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::Fish => {
 90                        combined_command.insert_str(0, "begin; ");
 91                        combined_command.push_str("; end </dev/null");
 92                    }
 93                    ShellKind::Posix
 94                    | ShellKind::Nushell
 95                    | ShellKind::Csh
 96                    | ShellKind::Tcsh
 97                    | ShellKind::Rc => {
 98                        combined_command.insert(0, '(');
 99                        combined_command.push_str(") </dev/null");
100                    }
101                    ShellKind::PowerShell => {
102                        combined_command.insert_str(0, "$null | & {");
103                        combined_command.push_str("}");
104                    }
105                    ShellKind::Cmd => {
106                        combined_command.push_str("< NUL");
107                    }
108                }
109            }
110
111            self.args
112                .extend(self.kind.args_for_shell(self.interactive, combined_command));
113        }
114
115        (self.program, self.args)
116    }
117}
118
119#[cfg(test)]
120mod test {
121    use super::*;
122
123    #[test]
124    fn test_nu_shell_variable_substitution() {
125        let shell = Shell::Program("nu".to_owned());
126        let shell_builder = ShellBuilder::new(&shell, false);
127
128        let (program, args) = shell_builder.build(
129            Some("echo".into()),
130            &[
131                "${hello}".to_string(),
132                "$world".to_string(),
133                "nothing".to_string(),
134                "--$something".to_string(),
135                "$".to_string(),
136                "${test".to_string(),
137            ],
138        );
139
140        assert_eq!(program, "nu");
141        assert_eq!(
142            args,
143            vec![
144                "-i",
145                "-c",
146                "echo $env.hello $env.world nothing --($env.something) $ ${test"
147            ]
148        );
149    }
150
151    #[test]
152    fn redirect_stdin_to_dev_null_precedence() {
153        let shell = Shell::Program("nu".to_owned());
154        let shell_builder = ShellBuilder::new(&shell, false);
155
156        let (program, args) = shell_builder
157            .redirect_stdin_to_dev_null()
158            .build(Some("echo".into()), &["nothing".to_string()]);
159
160        assert_eq!(program, "nu");
161        assert_eq!(args, vec!["-i", "-c", "(echo nothing) </dev/null"]);
162    }
163
164    #[test]
165    fn redirect_stdin_to_dev_null_fish() {
166        let shell = Shell::Program("fish".to_owned());
167        let shell_builder = ShellBuilder::new(&shell, false);
168
169        let (program, args) = shell_builder
170            .redirect_stdin_to_dev_null()
171            .build(Some("echo".into()), &["test".to_string()]);
172
173        assert_eq!(program, "fish");
174        assert_eq!(args, vec!["-i", "-c", "begin; echo test; end </dev/null"]);
175    }
176}