1use crate::shell::get_system_shell;
  2use crate::shell::{Shell, ShellKind};
  3
  4/// ShellBuilder is used to turn a user-requested task into a
  5/// program that can be executed by the shell.
  6pub struct ShellBuilder {
  7    /// The shell to run
  8    program: String,
  9    args: Vec<String>,
 10    interactive: bool,
 11    /// Whether to redirect stdin to /dev/null for the spawned command as a subshell.
 12    redirect_stdin: bool,
 13    kind: ShellKind,
 14}
 15
 16impl ShellBuilder {
 17    /// Create a new ShellBuilder as configured.
 18    pub fn new(shell: &Shell, is_windows: bool) -> Self {
 19        let (program, args) = match shell {
 20            Shell::System => (get_system_shell(), Vec::new()),
 21            Shell::Program(shell) => (shell.clone(), Vec::new()),
 22            Shell::WithArguments { program, args, .. } => (program.clone(), args.clone()),
 23        };
 24
 25        let kind = ShellKind::new(&program, is_windows);
 26        Self {
 27            program,
 28            args,
 29            interactive: true,
 30            kind,
 31            redirect_stdin: false,
 32        }
 33    }
 34    pub fn non_interactive(mut self) -> Self {
 35        self.interactive = false;
 36        self
 37    }
 38
 39    /// Returns the label to show in the terminal tab
 40    pub fn command_label(&self, command_to_use_in_label: &str) -> String {
 41        if command_to_use_in_label.trim().is_empty() {
 42            self.program.clone()
 43        } else {
 44            match self.kind {
 45                ShellKind::PowerShell => {
 46                    format!("{} -C '{}'", self.program, command_to_use_in_label)
 47                }
 48                ShellKind::Cmd => {
 49                    format!("{} /C \"{}\"", self.program, command_to_use_in_label)
 50                }
 51                ShellKind::Posix
 52                | ShellKind::Nushell
 53                | ShellKind::Fish
 54                | ShellKind::Csh
 55                | ShellKind::Tcsh
 56                | ShellKind::Rc
 57                | ShellKind::Xonsh => {
 58                    let interactivity = self.interactive.then_some("-i ").unwrap_or_default();
 59                    format!(
 60                        "{PROGRAM} {interactivity}-c '{command_to_use_in_label}'",
 61                        PROGRAM = self.program
 62                    )
 63                }
 64            }
 65        }
 66    }
 67
 68    pub fn redirect_stdin_to_dev_null(mut self) -> Self {
 69        self.redirect_stdin = true;
 70        self
 71    }
 72
 73    /// Returns the program and arguments to run this task in a shell.
 74    pub fn build(
 75        mut self,
 76        task_command: Option<String>,
 77        task_args: &[String],
 78    ) -> (String, Vec<String>) {
 79        if let Some(task_command) = task_command {
 80            let mut combined_command = task_args.iter().fold(task_command, |mut command, arg| {
 81                command.push(' ');
 82                command.push_str(&self.kind.to_shell_variable(arg));
 83                command
 84            });
 85            if self.redirect_stdin {
 86                match self.kind {
 87                    ShellKind::Fish => {
 88                        combined_command.insert_str(0, "begin; ");
 89                        combined_command.push_str("; end </dev/null");
 90                    }
 91                    ShellKind::Posix
 92                    | ShellKind::Nushell
 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, false);
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, false);
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
163    #[test]
164    fn redirect_stdin_to_dev_null_fish() {
165        let shell = Shell::Program("fish".to_owned());
166        let shell_builder = ShellBuilder::new(&shell, false);
167
168        let (program, args) = shell_builder
169            .redirect_stdin_to_dev_null()
170            .build(Some("echo".into()), &["test".to_string()]);
171
172        assert_eq!(program, "fish");
173        assert_eq!(args, vec!["-i", "-c", "begin; echo test; end </dev/null"]);
174    }
175}