Skip to main content

treeboot_spec/
command.rs

1use std::ffi::{OsStr, OsString};
2use std::io::{Error, ErrorKind};
3use std::path::{Path, PathBuf};
4
5use serde::Serialize;
6
7/// A candidate program and the arguments placed before every case invocation.
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct CommandTemplate {
10    program: OsString,
11    prefix_args: Vec<OsString>,
12}
13
14impl CommandTemplate {
15    /// Creates a template that invokes `program` directly, without a shell.
16    pub fn new(program: impl Into<OsString>) -> Self {
17        Self {
18            program: program.into(),
19            prefix_args: Vec::new(),
20        }
21    }
22
23    /// Creates a template with native prefix arguments.
24    pub fn with_args<I, S>(program: impl Into<OsString>, args: I) -> Self
25    where
26        I: IntoIterator<Item = S>,
27        S: Into<OsString>,
28    {
29        Self {
30            program: program.into(),
31            prefix_args: args.into_iter().map(Into::into).collect(),
32        }
33    }
34
35    /// Appends one prefix argument and returns the updated template.
36    #[must_use]
37    pub fn with_prefix_arg(mut self, arg: impl Into<OsString>) -> Self {
38        self.prefix_args.push(arg.into());
39        self
40    }
41
42    /// Returns the candidate program.
43    pub fn program(&self) -> &OsStr {
44        &self.program
45    }
46
47    /// Returns the arguments placed before each case's arguments.
48    pub fn prefix_args(&self) -> &[OsString] {
49        &self.prefix_args
50    }
51
52    /// Returns a report-safe, lossy projection of the native command.
53    pub fn report(&self) -> CommandReport {
54        CommandReport {
55            program: self.program.to_string_lossy().into_owned(),
56            prefix_args: self
57                .prefix_args
58                .iter()
59                .map(|argument| argument.to_string_lossy().into_owned())
60                .collect(),
61        }
62    }
63
64    /// Resolves a path-like program before case working directories are entered.
65    ///
66    /// # Errors
67    ///
68    /// Returns an I/O error when the program cannot be found or made absolute.
69    pub fn resolve(&self) -> std::io::Result<Self> {
70        let path = Path::new(&self.program);
71        let program = if path.components().count() == 1 {
72            resolve_from_path(path)?
73        } else {
74            let path = if path.is_absolute() {
75                path.to_path_buf()
76            } else {
77                std::env::current_dir()?.join(path)
78            };
79            dunce::canonicalize(path)?
80        };
81        Ok(Self {
82            program: program.into_os_string(),
83            prefix_args: self.prefix_args.clone(),
84        })
85    }
86}
87
88fn resolve_from_path(program: &Path) -> std::io::Result<PathBuf> {
89    let search_path = std::env::var_os("PATH").ok_or_else(|| {
90        Error::new(
91            ErrorKind::NotFound,
92            format!("cannot find {:?}: PATH is not set", program.as_os_str()),
93        )
94    })?;
95    for directory in std::env::split_paths(&search_path) {
96        for candidate in executable_candidates(directory.join(program)) {
97            if candidate.is_file() {
98                return dunce::canonicalize(candidate);
99            }
100        }
101    }
102    Err(Error::new(
103        ErrorKind::NotFound,
104        format!("cannot find {:?} in PATH", program.as_os_str()),
105    ))
106}
107
108#[cfg(not(windows))]
109fn executable_candidates(candidate: PathBuf) -> Vec<PathBuf> {
110    vec![candidate]
111}
112
113#[cfg(windows)]
114fn executable_candidates(candidate: PathBuf) -> Vec<PathBuf> {
115    let path_ext = std::env::var_os("PATHEXT").unwrap_or_else(|| ".COM;.EXE;.BAT;.CMD".into());
116    executable_candidates_with_path_ext(candidate, &path_ext)
117}
118
119#[cfg(windows)]
120fn executable_candidates_with_path_ext(candidate: PathBuf, path_ext: &OsStr) -> Vec<PathBuf> {
121    let extensions = path_ext
122        .to_string_lossy()
123        .split(';')
124        .filter(|extension| !extension.is_empty())
125        .map(str::to_owned)
126        .collect::<Vec<_>>();
127    if extensions.is_empty() {
128        return vec![candidate];
129    }
130
131    if candidate.extension().is_some_and(|candidate_extension| {
132        extensions.iter().any(|extension| {
133            candidate_extension
134                .to_string_lossy()
135                .eq_ignore_ascii_case(extension.trim_start_matches('.'))
136        })
137    }) {
138        return vec![candidate];
139    }
140
141    let Some(file_name) = candidate.file_name() else {
142        return vec![candidate];
143    };
144    extensions
145        .into_iter()
146        .map(|extension| {
147            let mut suffixed_name = file_name.to_os_string();
148            if !extension.starts_with('.') {
149                suffixed_name.push(".");
150            }
151            suffixed_name.push(extension);
152            candidate.with_file_name(suffixed_name)
153        })
154        .collect()
155}
156
157/// Serializable projection of a native candidate command.
158#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
159pub struct CommandReport {
160    /// Candidate program rendered lossily for reports.
161    pub program: String,
162    /// Prefix arguments rendered lossily for reports.
163    pub prefix_args: Vec<String>,
164}
165
166#[cfg(all(test, windows))]
167mod tests {
168    use super::*;
169
170    #[test]
171    fn executable_candidates_preserve_recognized_extensions() {
172        assert_eq!(
173            executable_candidates_with_path_ext(
174                PathBuf::from("treeboot.exe"),
175                ".COM;.EXE".as_ref()
176            ),
177            vec![PathBuf::from("treeboot.exe")]
178        );
179    }
180
181    #[test]
182    fn executable_candidates_append_path_ext_to_unrecognized_extensions() {
183        assert_eq!(
184            executable_candidates_with_path_ext(PathBuf::from("treeboot.v2"), ".EXE;CMD".as_ref()),
185            vec![
186                PathBuf::from("treeboot.v2.EXE"),
187                PathBuf::from("treeboot.v2.CMD"),
188            ]
189        );
190        assert_eq!(
191            executable_candidates_with_path_ext(PathBuf::from("treeboot"), ".EXE;CMD".as_ref()),
192            vec![PathBuf::from("treeboot.EXE"), PathBuf::from("treeboot.CMD"),]
193        );
194    }
195
196    #[test]
197    fn executable_candidates_preserve_candidate_when_path_ext_is_empty() {
198        assert_eq!(
199            executable_candidates_with_path_ext(PathBuf::from("treeboot"), "".as_ref()),
200            vec![PathBuf::from("treeboot")]
201        );
202    }
203}