Skip to content

Commit

Permalink
feat(cli): improve error reporting when cannot run cargo (#434)
Browse files Browse the repository at this point in the history
* improve error reporting

* fix

* update error message
  • Loading branch information
ValeryAntopol authored Jun 5, 2024
1 parent 30aaa28 commit 0bb178a
Showing 1 changed file with 39 additions and 2 deletions.
41 changes: 39 additions & 2 deletions tools/cli/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
* limitations under the License.
*/

use std::fmt::Formatter;
use std::io::ErrorKind;
use std::process::Command;
use std::process::Stdio;

Expand All @@ -32,13 +34,48 @@ fn run_command<T: Into<Stdio>>(
mut command: Command,
stdout_config: T,
) -> Result<String, anyhow::Error> {
let process = command.stdout(stdout_config).spawn()?;
let process = command
.stdout(stdout_config)
.spawn()
.map_err(|e| process_command_run_error(e, &command))?;

let output = process.wait_with_output()?;
if !output.status.success() {
anyhow::bail!("failed to execute, exited with {}", output.status)
anyhow::bail!(
r#"command `{}` exited with {}"#,
PrintCommand(&command),
output.status
)
}

let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
Ok(stdout)
}

struct PrintCommand<'c>(&'c Command);

impl<'c> std::fmt::Display for PrintCommand<'c> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0.get_program().to_string_lossy())?;
for arg in self.0.get_args() {
write!(f, " {}", arg.to_string_lossy())?;
}

Ok(())
}
}

fn process_command_run_error(e: std::io::Error, command: &Command) -> anyhow::Error {
if e.kind() == ErrorKind::NotFound {
anyhow::anyhow!(
r#"cannot run `{}`: executable not found in $PATH"#,
command.get_program().to_string_lossy(),
)
} else {
anyhow::anyhow!(
r#"cannot run `{}`: {}"#,
command.get_program().to_string_lossy(),
e
)
}
}

0 comments on commit 0bb178a

Please sign in to comment.