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, is_windows: bool) -> 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, is_windows);
 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                    let interactivity = self.interactive.then_some("-i ").unwrap_or_default();
 61                    format!(
 62                        "{PROGRAM} {interactivity}-c '{command_to_use_in_label}'",
 63                        PROGRAM = self.program
 64                    )
 65                }
 66            }
 67        }
 68    }
 69
 70    pub fn redirect_stdin_to_dev_null(mut self) -> Self {
 71        self.redirect_stdin = true;
 72        self
 73    }
 74
 75    /// Returns the program and arguments to run this task in a shell.
 76    pub fn build(
 77        mut self,
 78        task_command: Option<String>,
 79        task_args: &[String],
 80    ) -> (String, Vec<String>) {
 81        if let Some(task_command) = task_command {
 82            let mut combined_command = task_args.iter().fold(task_command, |mut command, arg| {
 83                command.push(' ');
 84                command.push_str(&self.kind.to_shell_variable(arg));
 85                command
 86            });
 87            if self.redirect_stdin {
 88                match self.kind {
 89                    ShellKind::Posix
 90                    | ShellKind::Nushell
 91                    | ShellKind::Fish
 92                    | ShellKind::Csh
 93                    | ShellKind::Tcsh
 94                    | ShellKind::Rc => {
 95                        combined_command.insert(0, '(');
 96                        combined_command.push_str(") </dev/null");
 97                    }
 98                    ShellKind::PowerShell => {
 99                        combined_command.insert_str(0, "$null | & {");
100                        combined_command.push_str("}");
101                    }
102                    ShellKind::Cmd => {
103                        combined_command.push_str("< NUL");
104                    }
105                }
106            }
107
108            self.args
109                .extend(self.kind.args_for_shell(self.interactive, combined_command));
110        }
111
112        (self.program, self.args)
113    }
114}
115
116#[cfg(test)]
117mod test {
118    use super::*;
119
120    #[test]
121    fn test_nu_shell_variable_substitution() {
122        let shell = Shell::Program("nu".to_owned());
123        let shell_builder = ShellBuilder::new(&shell, false);
124
125        let (program, args) = shell_builder.build(
126            Some("echo".into()),
127            &[
128                "${hello}".to_string(),
129                "$world".to_string(),
130                "nothing".to_string(),
131                "--$something".to_string(),
132                "$".to_string(),
133                "${test".to_string(),
134            ],
135        );
136
137        assert_eq!(program, "nu");
138        assert_eq!(
139            args,
140            vec![
141                "-i",
142                "-c",
143                "echo $env.hello $env.world nothing --($env.something) $ ${test"
144            ]
145        );
146    }
147
148    #[test]
149    fn redirect_stdin_to_dev_null_precedence() {
150        let shell = Shell::Program("nu".to_owned());
151        let shell_builder = ShellBuilder::new(&shell, false);
152
153        let (program, args) = shell_builder
154            .redirect_stdin_to_dev_null()
155            .build(Some("echo".into()), &["nothing".to_string()]);
156
157        assert_eq!(program, "nu");
158        assert_eq!(args, vec!["-i", "-c", "(echo nothing) </dev/null"]);
159    }
160}