1use std::error::Error;
2use std::fmt;
3use std::path::Path;
4
5use anyhow::{Context, Result, bail};
6use xshell::Shell;
7
8#[derive(Debug)]
22pub struct ExitCode(i32);
23
24impl ExitCode {
25 pub fn new(code: i32) -> Self {
27 Self(code)
28 }
29
30 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
44pub fn shell() -> Result<Shell> {
46 Shell::new().context("create shell")
47}
48
49pub 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
59pub 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
68pub fn push_dir<'a>(sh: &'a Shell, path: impl AsRef<Path>) -> xshell::PushDir<'a> {
70 sh.push_dir(path)
71}