printable_shell_command/
command.rs

1use std::{ffi::OsStr, process::Command, str::Utf8Error};
2
3use crate::{
4    print_builder::PrintBuilder, shell_printable::ShellPrintableWithOptions, FormattingOptions,
5    ShellPrintable,
6};
7
8pub(crate) fn add_arg_from_command_lossy(print_builder: &mut PrintBuilder, arg: &OsStr) {
9    print_builder.add_single_arg(&arg.to_string_lossy());
10}
11
12pub(crate) fn add_arg_from_command(
13    print_builder: &mut PrintBuilder,
14    arg: &OsStr,
15) -> Result<(), Utf8Error> {
16    print_builder.add_single_arg(TryInto::<&str>::try_into(arg)?);
17    Ok(())
18}
19
20impl ShellPrintableWithOptions for Command {
21    fn printable_invocation_string_lossy_with_options(
22        &self,
23        formatting_options: FormattingOptions,
24    ) -> String {
25        let mut print_builder =
26            PrintBuilder::new(&self.get_program().to_string_lossy(), formatting_options);
27        for arg in self.get_args() {
28            add_arg_from_command_lossy(&mut print_builder, arg);
29        }
30        print_builder.get()
31    }
32
33    fn printable_invocation_string_with_options(
34        &self,
35        formatting_options: FormattingOptions,
36    ) -> Result<String, Utf8Error> {
37        let mut print_builder = PrintBuilder::new(
38            TryInto::<&str>::try_into(self.get_program())?,
39            formatting_options,
40        );
41        for arg in self.get_args() {
42            add_arg_from_command(&mut print_builder, arg)?;
43        }
44        Ok(print_builder.get())
45    }
46}
47
48impl ShellPrintable for Command {
49    fn printable_invocation_string(&self) -> Result<String, Utf8Error> {
50        self.printable_invocation_string_with_options(Default::default())
51    }
52
53    fn printable_invocation_string_lossy(&self) -> String {
54        self.printable_invocation_string_lossy_with_options(Default::default())
55    }
56}
57
58#[cfg(test)]
59mod tests {
60    use std::process::Command;
61
62    use crate::ShellPrintable;
63
64    #[test]
65    fn echo() -> Result<(), String> {
66        let mut command = Command::new("echo");
67        command.args(["#hi"]);
68        // Not printed by tests, but we can at least check this doesn't panic.
69        let _ = command.print_invocation();
70
71        assert_eq!(
72            command.printable_invocation_string().unwrap(),
73            "echo \\
74  '#hi'"
75        );
76        Ok(())
77    }
78}