Skip to main content

xtask_kit/
process.rs

1use std::error::Error;
2use std::fmt;
3use std::path::Path;
4
5use anyhow::{Context, Result, bail};
6use xshell::Shell;
7
8/// Error type for commands that intentionally terminate with a specific process exit code.
9///
10/// This lets an `xtask` command communicate meaningful statuses to shell scripts while
11/// still using `anyhow::Result` internally:
12///
13/// ```
14/// # fn run() -> anyhow::Result<()> {
15/// if true {
16///     return Err(xtask_kit::process::ExitCode::new(2).into());
17/// }
18/// # Ok(())
19/// # }
20/// ```
21#[derive(Debug)]
22pub struct ExitCode(i32);
23
24impl ExitCode {
25    /// Create an exit-code error.
26    pub fn new(code: i32) -> Self {
27        Self(code)
28    }
29
30    /// Return the process exit code.
31    pub fn code(&self) -> i32 {
32        self.0
33    }
34}
35
36impl fmt::Display for ExitCode {
37    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
38        write!(formatter, "exit with status {}", self.0)
39    }
40}
41
42impl Error for ExitCode {}
43
44/// Create an [`xshell::Shell`] with context suitable for CLI errors.
45pub fn shell() -> Result<Shell> {
46    Shell::new().context("create shell")
47}
48
49/// Return true when `program` exists somewhere on `PATH`.
50pub fn command_exists(program: &str) -> bool {
51    std::env::var_os("PATH").is_some_and(|path| {
52        std::env::split_paths(&path).any(|dir| {
53            let candidate = dir.join(program);
54            candidate.is_file()
55        })
56    })
57}
58
59/// Fail with a user-facing message when `program` is not on `PATH`.
60pub fn ensure_command(program: &str) -> Result<()> {
61    if command_exists(program) {
62        Ok(())
63    } else {
64        bail!("{program} not found on PATH")
65    }
66}
67
68/// Temporarily change the shell's current directory for a command block.
69pub fn push_dir<'a>(sh: &'a Shell, path: impl AsRef<Path>) -> xshell::PushDir<'a> {
70    sh.push_dir(path)
71}