shell_builder.rs

  1use util::shell::get_system_shell;
  2
  3use crate::Shell;
  4
  5pub use util::shell::ShellKind;
  6
  7/// ShellBuilder is used to turn a user-requested task into a
  8/// program that can be executed by the shell.
  9pub struct ShellBuilder {
 10    /// The shell to run
 11    program: String,
 12    args: Vec<String>,
 13    interactive: bool,
 14    /// Whether to redirect stdin to /dev/null for the spawned command as a subshell.
 15    redirect_stdin: bool,
 16    kind: ShellKind,
 17}
 18
 19impl ShellBuilder {
 20    /// Create a new ShellBuilder as configured.
 21    pub fn new(shell: &Shell) -> Self {
 22        let (program, args) = match shell {
 23            Shell::System => (get_system_shell(), Vec::new()),
 24            Shell::Program(shell) => (shell.clone(), Vec::new()),
 25            Shell::WithArguments { program, args, .. } => (program.clone(), args.clone()),
 26        };
 27
 28        let kind = ShellKind::new(&program);
 29        Self {
 30            program,
 31            args,
 32            interactive: true,
 33            kind,
 34            redirect_stdin: false,
 35        }
 36    }
 37    pub fn non_interactive(mut self) -> Self {
 38        self.interactive = false;
 39        self
 40    }
 41
 42    /// Returns the label to show in the terminal tab
 43    pub fn command_label(&self, command_to_use_in_label: &str) -> String {
 44        if command_to_use_in_label.trim().is_empty() {
 45            self.program.clone()
 46        } else {
 47            match self.kind {
 48                ShellKind::PowerShell => {
 49                    format!("{} -C '{}'", self.program, command_to_use_in_label)
 50                }
 51                ShellKind::Cmd => {
 52                    format!("{} /C \"{}\"", self.program, command_to_use_in_label)
 53                }
 54                ShellKind::Posix
 55                | ShellKind::Nushell
 56                | ShellKind::Fish
 57                | ShellKind::Csh
 58                | ShellKind::Tcsh
 59                | ShellKind::Rc
 60                | ShellKind::Xonsh => {
 61                    let interactivity = self.interactive.then_some("-i ").unwrap_or_default();
 62                    format!(
 63                        "{PROGRAM} {interactivity}-c '{command_to_use_in_label}'",
 64                        PROGRAM = self.program
 65                    )
 66                }
 67            }
 68        }
 69    }
 70
 71    pub fn redirect_stdin_to_dev_null(mut self) -> Self {
 72        self.redirect_stdin = true;
 73        self
 74    }
 75
 76    /// Returns the program and arguments to run this task in a shell.
 77    pub fn build(
 78        mut self,
 79        task_command: Option<String>,
 80        task_args: &[String],
 81    ) -> (String, Vec<String>) {
 82        if let Some(task_command) = task_command {
 83            let mut combined_command = task_args.iter().fold(task_command, |mut command, arg| {
 84                command.push(' ');
 85                command.push_str(&self.kind.to_shell_variable(arg));
 86                command
 87            });
 88            if self.redirect_stdin {
 89                match self.kind {
 90                    ShellKind::Posix
 91                    | ShellKind::Nushell
 92                    | ShellKind::Fish
 93                    | ShellKind::Csh
 94                    | ShellKind::Tcsh
 95                    | ShellKind::Rc
 96                    | ShellKind::Xonsh => {
 97                        combined_command.insert(0, '(');
 98                        combined_command.push_str(") </dev/null");
 99                    }
100                    ShellKind::PowerShell => {
101                        combined_command.insert_str(0, "$null | & {");
102                        combined_command.push_str("}");
103                    }
104                    ShellKind::Cmd => {
105                        combined_command.push_str("< NUL");
106                    }
107                }
108            }
109
110            self.args
111                .extend(self.kind.args_for_shell(self.interactive, combined_command));
112        }
113
114        (self.program, self.args)
115    }
116}
117
118#[cfg(test)]
119mod test {
120    use super::*;
121
122    #[test]
123    fn test_nu_shell_variable_substitution() {
124        let shell = Shell::Program("nu".to_owned());
125        let shell_builder = ShellBuilder::new(&shell);
126
127        let (program, args) = shell_builder.build(
128            Some("echo".into()),
129            &[
130                "${hello}".to_string(),
131                "$world".to_string(),
132                "nothing".to_string(),
133                "--$something".to_string(),
134                "$".to_string(),
135                "${test".to_string(),
136            ],
137        );
138
139        assert_eq!(program, "nu");
140        assert_eq!(
141            args,
142            vec![
143                "-i",
144                "-c",
145                "echo $env.hello $env.world nothing --($env.something) $ ${test"
146            ]
147        );
148    }
149
150    #[test]
151    fn redirect_stdin_to_dev_null_precedence() {
152        let shell = Shell::Program("nu".to_owned());
153        let shell_builder = ShellBuilder::new(&shell);
154
155        let (program, args) = shell_builder
156            .redirect_stdin_to_dev_null()
157            .build(Some("echo".into()), &["nothing".to_string()]);
158
159        assert_eq!(program, "nu");
160        assert_eq!(args, vec!["-i", "-c", "(echo nothing) </dev/null"]);
161    }
162}