Skip to main content

host/
shell.rs

1//! The shell commands run under (utils/shell.ts `getShellConfig` on Unix): the `shellPath` setting when it names an
2//! existing file (else the command fails with "Custom shell path not found: <path>"), else `/bin/bash`, else `bash`
3//! found on PATH, else `sh`. Every shell runs the command as `<shell> -c <command>`.
4
5use std::path::Path;
6
7/// The shell and the arguments before the command.
8#[derive(Clone, Debug, PartialEq, Eq)]
9pub struct ShellConfig {
10    pub shell: String,
11    pub args: Vec<String>,
12}
13
14impl ShellConfig {
15    fn bash(shell: &str) -> Self {
16        ShellConfig {
17            shell: shell.to_string(),
18            args: vec!["-c".into()],
19        }
20    }
21
22    pub fn argv(&self, command: &str) -> Vec<String> {
23        let mut argv = vec![self.shell.clone()];
24        argv.extend(self.args.iter().cloned());
25        argv.push(command.to_string());
26        argv
27    }
28}
29
30/// `getShellConfig(customShellPath)`; `exists` checks a path, `which` finds an executable on PATH.
31pub fn shell_config(
32    custom: Option<&str>,
33    exists: &dyn Fn(&Path) -> bool,
34    which: &dyn Fn(&str) -> Option<String>,
35) -> Result<ShellConfig, String> {
36    if let Some(custom) = custom.filter(|c| !c.is_empty()) {
37        if exists(Path::new(custom)) {
38            return Ok(ShellConfig::bash(custom));
39        }
40        return Err(format!("Custom shell path not found: {custom}"));
41    }
42    if exists(Path::new("/bin/bash")) {
43        return Ok(ShellConfig::bash("/bin/bash"));
44    }
45    if let Some(bash) = which("bash") {
46        return Ok(ShellConfig::bash(&bash));
47    }
48    Ok(ShellConfig {
49        shell: "sh".into(),
50        args: vec!["-c".into()],
51    })
52}
53
54/// [`shell_config`] on this machine: the file system and this process's PATH.
55pub fn system_shell_config(custom: Option<&str>) -> Result<ShellConfig, String> {
56    let path = std::env::var("PATH").ok();
57    shell_config_on_path(custom, path.as_deref())
58}
59
60/// [`shell_config`] on this machine's file system with `bash` looked up on `path` (a session's PATH).
61pub fn shell_config_on_path(custom: Option<&str>, path: Option<&str>) -> Result<ShellConfig, String> {
62    let which = |name: &str| {
63        std::env::split_paths(path?)
64            .map(|dir| dir.join(name))
65            .find(|candidate| candidate.is_file())
66            .map(|p| p.to_string_lossy().into_owned())
67    };
68    shell_config(custom, &|p: &Path| p.exists(), &which)
69}
70
71/// A user `!` command under the `shellCommandPrefix` setting (session-control-provider.ts `bash`): the prefix, a
72/// newline, then the command; an absent or empty prefix leaves the command alone.
73pub fn prefixed_command(prefix: Option<&str>, command: &str) -> String {
74    match prefix.filter(|p| !p.is_empty()) {
75        Some(prefix) => format!("{prefix}\n{command}"),
76        None => command.to_string(),
77    }
78}