Repository: Rust-GPU/cargo-gpu
Pull request #56: Ran `cargo fmt` + added some `.context()` calls for non-obvious errors
Author: login: Niedzwiedzw
Created: 2025-03-15T16:24:57Z | Merged: 2025-03-30T02:04:02Z



Diff:
diff --git a/crates/cargo-gpu/src/install.rs b/crates/cargo-gpu/src/install.rs
index d6c286ba..9977227b 100644
--- a/crates/cargo-gpu/src/install.rs
+++ b/crates/cargo-gpu/src/install.rs
@@ -1,4 +1,5 @@
 //! Install a dedicated per-shader crate that has the `rust-gpu` compiler in it.
+
 use std::io::Write as _;
 
 use anyhow::Context as _;
@@ -117,18 +118,24 @@ impl Install {
 
     /// Create the `spirv-builder-cli` crate.
     fn write_source_files(&self) -> anyhow::Result<()> {
-        let spirv_cli = self.spirv_cli(&self.spirv_install.shader_crate)?;
-        let checkout = spirv_cli.cached_checkout_path()?;
-        std::fs::create_dir_all(checkout.join("src"))?;
+        let spirv_cli = self
+            .spirv_cli(&self.spirv_install.shader_crate)
+            .context("running spirv cli")?;
+        let checkout = spirv_cli
+            .cached_checkout_path()
+            .context("getting cached checkout path")?;
+        std::fs::create_dir_all(checkout.join("src")).context("creating directory for 'src'")?;
         for (filename, contents) in SPIRV_BUILDER_FILES {
             log::debug!("writing {filename}");
             let path = checkout.join(filename);
-            let mut file = std::fs::File::create(&path)?;
+            let mut file = std::fs::File::create(&path)
+                .with_context(|| format!("creating a file at [{}]", path.display()))?;
             let mut replaced_contents = contents.replace("${CHANNEL}", &spirv_cli.channel);
             if filename == &"Cargo.toml" {
                 replaced_contents = Self::update_cargo_toml(&replaced_contents, &spirv_cli.source);
             }
-            file.write_all(replaced_contents.as_bytes())?;
+            file.write_all(replaced_contents.as_bytes())
+                .context("writing to file")?;
         }
         Ok(())
     }
@@ -165,10 +172,14 @@ impl Install {
     /// Add the target spec files to the crate.
     fn write_target_spec_files(&self) -> anyhow::Result<()> {
         for (filename, contents) in TARGET_SPECS {
-            let path = target_spec_dir()?.join(filename);
+            let path = target_spec_dir()
+                .context("creating target spec dir")?
+                .join(filename);
             if !path.is_file() || self.spirv_install.force_spirv_cli_rebuild {
-                let mut file = std::fs::File::create(&path)?;
-                file.write_all(contents.as_bytes())?;
+                let mut file = std::fs::File::create(&path)
+                    .with_context(|| format!("creating file at [{}]", path.display()))?;
+                file.write_all(contents.as_bytes())
+                    .context("writing to file")?;
             }
         }
         Ok(())
@@ -183,10 +194,16 @@ impl Install {
             format!("could not create cache directory '{}'", cache_dir.display())
         })?;
 
-        let spirv_version = self.spirv_cli(&self.spirv_install.shader_crate)?;
-        spirv_version.ensure_toolchain_and_components_exist()?;
+        let spirv_version = self
+            .spirv_cli(&self.spirv_install.shader_crate)
+            .context("running spirv cli")?;
+        spirv_version
+            .ensure_toolchain_and_components_exist()
+            .context("ensuring toolchain and components exist")?;
 
-        let checkout = spirv_version.cached_checkout_path()?;
+        let checkout = spirv_version
+            .cached_checkout_path()
+            .context("getting cached checkout path")?;
         let release = checkout.join("target").join("release");
 
         let dylib_filename = format!(
@@ -214,8 +231,9 @@ impl Install {
                 "writing spirv-builder-cli source files into '{}'",
                 checkout.display()
             );
-            self.write_source_files()?;
-            self.write_target_spec_files()?;
+            self.write_source_files().context("writing source files")?;
+            self.write_target_spec_files()
+                .context("writing target spec files")?;
 
             crate::user_output!(
                 "Compiling shader-specific `spirv-builder-cli` for {}\n",
@@ -231,20 +249,29 @@ impl Install {
 
             build_command.args([
                 "--features",
-                &Self::get_required_spirv_builder_version(spirv_version.date)?,
+                &Self::get_required_spirv_builder_version(spirv_version.date)
+                    .context("getting required spirv builder version")?,
             ]);
 
             log::debug!("building artifacts with `{:?}`", build_command);
 
-            let build_output = build_command
+            build_command
                 .stdout(std::process::Stdio::inherit())
                 .stderr(std::process::Stdio::inherit())
-                .output()?;
-            anyhow::ensure!(build_output.status.success(), "...build error!");
+                .output()
+                .context("getting command output")
+                .and_then(|output| {
+                    if output.status.success() {
+                        Ok(output)
+                    } else {
+                        Err(anyhow::anyhow!("bad status {:?}", output.status))
+                    }
+                })
+                .context("running build command")?;
 
             if dylib_path.is_file() {
                 log::info!("successfully built {}", dylib_path.display());
-                std::fs::rename(&dylib_path, &dest_dylib_path)?;
+                std::fs::rename(&dylib_path, &dest_dylib_path).context("renaming dylib path")?;
             } else {
                 log::error!("could not find {}", dylib_path.display());
                 anyhow::bail!("spirv-builder-cli build failed");
@@ -257,11 +284,11 @@ impl Install {
             };
             if cli_path.is_file() {
                 log::info!("successfully built {}", cli_path.display());
-                std::fs::rename(&cli_path, &dest_cli_path)?;
+                std::fs::rename(&cli_path, &dest_cli_path).context("renaming cli path")?;
             } else {
                 log::error!("could not find {}", cli_path.display());
                 log::debug!("contents of '{}':", release.display());
-                for maybe_entry in std::fs::read_dir(&release)? {
+                for maybe_entry in std::fs::read_dir(&release).context("reading release dir")? {
                     let entry = maybe_entry?;
                     log::debug!("{}", entry.file_name().to_string_lossy());
                 }
diff --git a/crates/cargo-gpu/src/main.rs b/crates/cargo-gpu/src/main.rs
index b46cf5bd..69973861 100644
--- a/crates/cargo-gpu/src/main.rs
+++ b/crates/cargo-gpu/src/main.rs
@@ -110,7 +110,7 @@ fn main() {
             #[expect(clippy::restriction, reason = "Our central place for safely exiting")]
             std::process::exit(1);
         };
-    };
+    }
 }
 
 /// Wrappable "main" to catch errors.
@@ -150,11 +150,11 @@ fn run() -> anyhow::Result<()> {
                 command.run()?;
             } else {
                 command.run()?;
-            };
+            }
         }
         Command::Show(show) => show.run()?,
         Command::DumpUsage => dump_full_usage_for_readme()?,
-    };
+    }
 
     Ok(())
 }
diff --git a/crates/cargo-gpu/src/show.rs b/crates/cargo-gpu/src/show.rs
index 985a33f6..61202cbf 100644
--- a/crates/cargo-gpu/src/show.rs
+++ b/crates/cargo-gpu/src/show.rs
@@ -5,7 +5,7 @@ use crate::cache_dir;
 /// Show the computed source of the spirv-std dependency.
 #[derive(Clone, Debug, clap::Parser)]
 pub struct SpirvSourceDep {
-    /// The location of the shader-crate to inspect to determine its spirv-std dependency.    
+    /// The location of the shader-crate to inspect to determine its spirv-std dependency.
     #[clap(long, default_value = "./")]
     pub shader_crate: std::path::PathBuf,
 }
diff --git a/crates/cargo-gpu/src/spirv_cli.rs b/crates/cargo-gpu/src/spirv_cli.rs
index abe2e1f4..9dfb7e58 100644
--- a/crates/cargo-gpu/src/spirv_cli.rs
+++ b/crates/cargo-gpu/src/spirv_cli.rs
@@ -61,21 +61,24 @@ impl SpirvCli {
             Self::ensure_workspace_rust_version_doesnt_conflict_with_shader(
                 shader_crate_path,
                 is_force_overwrite_lockfiles_v4_to_v3,
-            )?;
+            )
+            .context("ensure_workspace_rust_version_doesnt_conflict_with_shader")?;
 
         if let Some(shader_crate_lock) = maybe_shader_crate_lock {
             cargo_lock_files_with_changed_manifest_versions.push(shader_crate_lock);
         }
 
         let (default_rust_gpu_source, rust_gpu_date, default_rust_gpu_channel) =
-            SpirvSource::get_rust_gpu_deps_from_shader(shader_crate_path)?;
+            SpirvSource::get_rust_gpu_deps_from_shader(shader_crate_path)
+                .context("get_rust_gpu_deps_from_shader")?;
 
         let maybe_workspace_crate_lock =
             Self::ensure_shader_rust_version_doesnt_conflict_with_any_cargo_locks(
                 shader_crate_path,
                 default_rust_gpu_channel.clone(),
                 is_force_overwrite_lockfiles_v4_to_v3,
-            )?;
+            )
+            .context("ensure_shader_rust_version_doesnt_conflict_with_any_cargo_locks")?;
 
         if let Some(workspace_crate_lock) = maybe_workspace_crate_lock {
             cargo_lock_files_with_changed_manifest_versions.push(workspace_crate_lock);
@@ -104,12 +107,13 @@ impl SpirvCli {
 
     /// Create and/or return the cache directory
     pub fn cached_checkout_path(&self) -> anyhow::Result<std::path::PathBuf> {
-        let checkout_dir = crate::cache_dir()?
+        let checkout_dir = crate::cache_dir()
+            .context("reading cache dir")?
             .join("spirv-builder-cli")
             .join(crate::to_dirname(self.to_string().as_ref()));
-        std::fs::create_dir_all(&checkout_dir).with_context(|| {
-            format!("could not create checkout dir '{}'", checkout_dir.display())
-        })?;
+        std::fs::create_dir_all(&checkout_dir)
+            .with_context(|| format!("could not create checkout dir '{}'", checkout_dir.display()))
+            .context("crating directory in cahce dir")?;
 
         Ok(checkout_dir)
     }
@@ -124,7 +128,8 @@ impl SpirvCli {
         // Check for the required toolchain
         let output_toolchain_list = std::process::Command::new("rustup")
             .args(["toolchain", "list"])
-            .output()?;
+            .output()
+            .context("running rustup command")?;
         anyhow::ensure!(
             output_toolchain_list.status.success(),
             "could not list installed toolchains"
@@ -145,7 +150,8 @@ impl SpirvCli {
                 .arg(&self.channel)
                 .stdout(std::process::Stdio::inherit())
                 .stderr(std::process::Stdio::inherit())
-                .output()?;
+                .output()
+                .context("adding toolchain")?;
             anyhow::ensure!(
                 output_toolchain_add.status.success(),
                 "could not install required toolchain"
@@ -156,7 +162,8 @@ impl SpirvCli {
         let output_component_list = std::process::Command::new("rustup")
             .args(["component", "list", "--toolchain"])
             .arg(&self.channel)
-            .output()?;
+            .output()
+            .context("getting toolchain list")?;
         anyhow::ensure!(
             output_component_list.status.success(),
             "could not list installed components"
@@ -184,7 +191,8 @@ impl SpirvCli {
                 .args(["rust-src", "rustc-dev", "llvm-tools"])
                 .stdout(std::process::Stdio::inherit())
                 .stderr(std::process::Stdio::inherit())
-                .output()?;
+                .output()
+                .context("adding rustup component")?;
             anyhow::ensure!(
                 output_component_add.status.success(),
                 "could not install required components"
@@ -200,10 +208,10 @@ impl SpirvCli {
             return Ok(());
         }
         log::debug!("asking for consent to install the required toolchain");
-        crossterm::terminal::enable_raw_mode()?;
+        crossterm::terminal::enable_raw_mode().context("enabling raw mode")?;
         crate::user_output!("{prompt} [y/n]: ");
-        let input = crossterm::event::read()?;
-        crossterm::terminal::disable_raw_mode()?;
+        let input = crossterm::event::read().context("reading crossterm event")?;
+        crossterm::terminal::disable_raw_mode().context("disabling raw mode")?;
 
         if let crossterm::event::Event::Key(crossterm::event::KeyEvent {
             code: crossterm::event::KeyCode::Char('y'),
@@ -223,7 +231,8 @@ impl SpirvCli {
         is_force_overwrite_lockfiles_v4_to_v3: bool,
     ) -> anyhow::Result<Option<std::path::PathBuf>> {
         log::debug!("Ensuring no v3/v4 `Cargo.lock` conflicts from workspace Rust...");
-        let workspace_rust_version = Self::get_rustc_version(None)?;
+        let workspace_rust_version =
+            Self::get_rustc_version(None).context("reading rustc version")?;
         if version_check::Version::at_least(
             &workspace_rust_version,
             RUST_VERSION_THAT_USES_V4_CARGO_LOCKS,
@@ -238,7 +247,8 @@ impl SpirvCli {
         Self::handle_conflicting_cargo_lock_v4(
             shader_crate_path,
             is_force_overwrite_lockfiles_v4_to_v3,
-        )?;
+        )
+        .context("handling v4/v3 conflict")?;
 
         if is_force_overwrite_lockfiles_v4_to_v3 {
             Ok(Some(shader_crate_path.join("Cargo.lock")))
@@ -254,7 +264,8 @@ impl SpirvCli {
         is_force_overwrite_lockfiles_v4_to_v3: bool,
     ) -> anyhow::Result<Option<std::path::PathBuf>> {
         log::debug!("Ensuring no v3/v4 `Cargo.lock` conflicts from shader's Rust...");
-        let shader_rust_version = Self::get_rustc_version(Some(channel))?;
+        let shader_rust_version =
+            Self::get_rustc_version(Some(channel)).context("getting rustc version")?;
         if version_check::Version::at_least(
             &shader_rust_version,
             RUST_VERSION_THAT_USES_V4_CARGO_LOCKS,
@@ -279,14 +290,18 @@ impl SpirvCli {
             Self::handle_conflicting_cargo_lock_v4(
                 shader_crate_path,
                 is_force_overwrite_lockfiles_v4_to_v3,
-            )?;
+            )
+            .context("handling v4/v3 conflict")?;
         }
 
-        if let Some(workspace_root) = Self::get_workspace_root(shader_crate_path)? {
+        if let Some(workspace_root) =
+            Self::get_workspace_root(shader_crate_path).context("reading workspace root")?
+        {
             Self::handle_conflicting_cargo_lock_v4(
                 workspace_root,
                 is_force_overwrite_lockfiles_v4_to_v3,
-            )?;
+            )
+            .context("handling conflicting cargo v4")?;
             return Ok(Some(workspace_root.join("Cargo.lock")));
         }
 
@@ -299,7 +314,8 @@ impl SpirvCli {
     fn get_workspace_root(
         shader_crate_path: &std::path::Path,
     ) -> anyhow::Result<Option<&std::path::Path>> {
-        let shader_cargo_toml = std::fs::read_to_string(shader_crate_path.join("Cargo.toml"))?;
+        let shader_cargo_toml = std::fs::read_to_string(shader_crate_path.join("Cargo.toml"))
+            .with_context(|| format!("reading Cargo.toml at {}", shader_crate_path.display()))?;
         if !shader_cargo_toml.contains("workspace = true") {
             return Ok(None);
         }
@@ -327,13 +343,15 @@ impl SpirvCli {
         is_force_overwrite_lockfiles_v4_to_v3: bool,
     ) -> anyhow::Result<()> {
         let shader_cargo_lock_path = folder.join("Cargo.lock");
-        let shader_cargo_lock = std::fs::read_to_string(shader_cargo_lock_path.clone())?;
-        let third_line = shader_cargo_lock.lines().nth(2).context("")?;
+        let shader_cargo_lock = std::fs::read_to_string(shader_cargo_lock_path.clone())
+            .context("reading shader cargo lock")?;
+        let third_line = shader_cargo_lock.lines().nth(2).context("no third line")?;
         if third_line.contains("version = 4") {
             Self::handle_v3v4_conflict(
                 &shader_cargo_lock_path,
                 is_force_overwrite_lockfiles_v4_to_v3,
-            )?;
+            )
+            .context("handling v4/v3 conflict")?;
             return Ok(());
         }
         if third_line.contains("version = 3") {
@@ -355,7 +373,8 @@ impl SpirvCli {
             Self::exit_with_v3v4_hack_suggestion();
         }
 
-        Self::replace_cargo_lock_manifest_version(offending_cargo_lock, "4", "3")?;
+        Self::replace_cargo_lock_manifest_version(offending_cargo_lock, "4", "3")
+            .context("replacing version 4 -> 3")?;
 
         Ok(())
     }
@@ -365,7 +384,8 @@ impl SpirvCli {
     pub fn revert_cargo_lock_manifest_versions(&self) -> anyhow::Result<()> {
         for offending_cargo_lock in &self.cargo_lock_files_with_changed_manifest_versions {
             log::debug!("Reverting: {}", offending_cargo_lock.display());
-            Self::replace_cargo_lock_manifest_version(offending_cargo_lock, "3", "4")?;
+            Self::replace_cargo_lock_manifest_version(offending_cargo_lock, "3", "4")
+                .context("replacing version 3 -> 4")?;
         }
 
         Ok(())
@@ -383,7 +403,8 @@ impl SpirvCli {
             to_version,
             offending_cargo_lock.display()
         );
-        let old_contents = std::fs::read_to_string(offending_cargo_lock)?;
+        let old_contents = std::fs::read_to_string(offending_cargo_lock)
+            .context("reading offending Cargo.lock")?;
         let new_contents = old_contents.replace(
             &format!("\nversion = {from_version}\n"),
             &format!("\nversion = {to_version}\n"),
@@ -392,7 +413,8 @@ impl SpirvCli {
         let mut file = std::fs::OpenOptions::new()
             .write(true)
             .truncate(true)
-            .open(offending_cargo_lock)?;
+            .open(offending_cargo_lock)
+            .context("opening offending Cargo.lock")?;
         file.write_all(new_contents.as_bytes())?;
 
         Ok(())
diff --git a/crates/cargo-gpu/src/spirv_source.rs b/crates/cargo-gpu/src/spirv_source.rs
index ec4526e6..c1815d62 100644
--- a/crates/cargo-gpu/src/spirv_source.rs
+++ b/crates/cargo-gpu/src/spirv_source.rs
@@ -110,7 +110,7 @@ impl SpirvSource {
         if !canonical_path.is_dir() {
             log::error!("{shader_crate_path:?} is not a directory, aborting");
             anyhow::bail!("{shader_crate_path:?} is not a directory");
-        };
+        }
 
         *shader_crate_path = canonical_path;
 


Reviews:
user: login: schell
body: Thank you! Just a few little nits and then I think we're ready to merge.
state: CHANGES_REQUESTED
author_association: COLLABORATOR
submitted_at: 2025-03-15T19:40:21Z
user: login: schell
state: APPROVED
author_association: COLLABORATOR
submitted_at: 2025-03-16T22:31:38Z

Review comments:
diff_hunk: @@ -7,7 +7,6 @@ use std::io::Write as _;
 
 use crate::{install::Install, target_spec_dir};
 use spirv_builder_cli::{args::BuildArgs, Linkage, ShaderModule};
-
path: crates/cargo-gpu/src/build.rs
user: login: schell
body: Was this removed by auto formatting?
created_at: 2025-03-15T19:31:24Z
author_association: COLLABORATOR
diff_hunk: @@ -1,4 +1,5 @@
 //! Install a dedicated per-shader crate that has the `rust-gpu` compiler in it.
+//!
path: crates/cargo-gpu/src/install.rs
user: login: schell
body: This should be a blank line, instead of a blank comment.
created_at: 2025-03-15T19:31:56Z
author_association: COLLABORATOR
diff_hunk: @@ -165,10 +172,14 @@ impl Install {
     /// Add the target spec files to the crate.
     fn write_target_spec_files(&self) -> anyhow::Result<()> {
         for (filename, contents) in TARGET_SPECS {
-            let path = target_spec_dir()?.join(filename);
+            let path = target_spec_dir()
+                .context("creating target spec dir")?
+                .join(filename);
             if !path.is_file() || self.spirv_install.force_spirv_cli_rebuild {
-                let mut file = std::fs::File::create(&path)?;
-                file.write_all(contents.as_bytes())?;
+                let mut file = std::fs::File::create(&path)
+                    .with_context(|| format!("creating file at [{}]", path.display()))?;
+                file.write_all(contents.as_bytes())
+                    .context("writring to file")?;
path: crates/cargo-gpu/src/install.rs
user: login: schell
body: Little typo here.
created_at: 2025-03-15T19:32:25Z
author_association: COLLABORATOR
diff_hunk: @@ -231,20 +249,31 @@ impl Install {
 
             build_command.args([
                 "--features",
-                &Self::get_required_spirv_builder_version(spirv_version.date)?,
+                &Self::get_required_spirv_builder_version(spirv_version.date)
+                    .context("getting required spirv builder version")?,
             ]);
 
             log::debug!("building artifacts with `{:?}`", build_command);
 
-            let build_output = build_command
+            build_command
                 .stdout(std::process::Stdio::inherit())
                 .stderr(std::process::Stdio::inherit())
-                .output()?;
-            anyhow::ensure!(build_output.status.success(), "...build error!");
+                .output()
+                .context("getting command output")
+                .and_then(|output| {
+                    log::trace!("STDOUT:\n{}", String::from_utf8_lossy(&output.stdout));
+                    log::trace!("STDERR:\n{}", String::from_utf8_lossy(&output.stderr));
path: crates/cargo-gpu/src/install.rs
user: login: schell
body: These lines shouldn't be necessary, since the command inherits stdin and stdout, right? Maybe I'm missing something though.
created_at: 2025-03-15T19:35:27Z
author_association: COLLABORATOR

PR comments:
user: login: tombh
created_at: 2025-03-15T16:37:53Z
body: Oh nice! I see we already have a `cargo fmt` in CI, but it seems it produces different output to yours. Do you have a particular config?
author_association: COLLABORATOR
user: login: Niedzwiedzw
created_at: 2025-03-15T16:39:25Z
body: hmmm noo I don't think so... it'd have to be in ~/rustfmt.toml right?
author_association: CONTRIBUTOR
user: login: Niedzwiedzw
created_at: 2025-03-15T16:44:46Z
body: ahh but now the imports didn't change back

author_association: CONTRIBUTOR
user: login: Niedzwiedzw
created_at: 2025-03-15T17:10:08Z
body: @tombh  all right I think it's ready for review
author_association: CONTRIBUTOR
user: login: schell
created_at: 2025-03-16T22:31:18Z
body: Thanks @Niedzwiedzw - just waiting for the CI checks and then I'll merge 👍 .
author_association: COLLABORATOR