Skip to main content

isothrum_runner/
console.rs

1//! The way into a machine as the embedder runs it: [`ShellCommand`], the command that opens a
2//! console there, and the one line a POSIX shell runs it from, its words quoted as a POSIX shell
3//! reads them back ([`sh_quote`], which every script the runner writes for a shell uses); the
4//! account a console may be asked to open as ([`check_name`]); and the scripts a console runs once
5//! it is in ([`shells`]).
6
7use std::path::PathBuf;
8
9use serde::{Deserialize, Serialize};
10
11use crate::error::{Error, Result};
12
13pub(crate) mod shells;
14
15/// The command that opens an interactive console into a machine (a shell in a container, `vagrant
16/// ssh`, an SSH login): the runner builds it (it alone knows the runtime: the Compose project and
17/// files, the Vagrant define, the address and user a module gives), the embedder runs it in its
18/// own terminal. Addresses the machine by service or define name, or by the address the run gives
19/// it, never a guessed container.
20#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
21#[non_exhaustive]
22pub struct ShellCommand {
23    /// The program to run (`docker`, `vagrant`, `ssh`).
24    pub program: String,
25    /// Its arguments.
26    pub args: Vec<String>,
27    /// The folder to run it in (the run's folder).
28    pub cwd: PathBuf,
29    /// Variables to run it with, besides the embedder's own (a Vagrant run's state folder,
30    /// `VAGRANT_DOTFILE_PATH`, without which Vagrant doesn't find the VM; its forwarded ports).
31    /// Empty for a Compose service on this computer and for an SSH login.
32    pub env: Vec<(String, String)>,
33}
34
35impl ShellCommand {
36    /// The command `spec` starts, in its folder, else in `dir`, with its variables: a console an
37    /// adapter built.
38    pub(crate) fn of_spec(spec: crate::process::ProcessSpec, dir: &std::path::Path) -> ShellCommand {
39        let cwd = spec.cwd.unwrap_or_else(|| dir.to_path_buf());
40        ShellCommand::new(spec.program, spec.args, cwd).with_env(spec.env)
41    }
42
43    /// `program` with `args`, run in `cwd`, with no variable of its own.
44    #[must_use]
45    pub fn new(program: impl Into<String>, args: impl IntoIterator<Item = impl Into<String>>, cwd: impl Into<PathBuf>) -> ShellCommand {
46        ShellCommand {
47            program: program.into(),
48            args: args.into_iter().map(Into::into).collect(),
49            cwd: cwd.into(),
50            env: Vec::new(),
51        }
52    }
53
54    /// The same, run with `env` besides the embedder's own variables.
55    #[must_use]
56    pub fn with_env(mut self, env: Vec<(String, String)>) -> ShellCommand {
57        self.env = env;
58        self
59    }
60
61    /// The command as one line a POSIX shell runs as it is, to paste in a terminal:
62    /// `cd <cwd> && VAR=value… program args…`, each word that needs it single-quoted (a `sh -c`
63    /// script with `;` or `>`, a JSON value), so the shell splits it back into this argv.
64    #[must_use]
65    pub fn sh_line(&self) -> String {
66        let cwd = sh_word(&self.cwd.display().to_string());
67        let env = self.env.iter().map(|(k, v)| format!("{k}={}", sh_word(v)));
68        let argv = std::iter::once(&self.program).chain(&self.args).map(|w| sh_word(w));
69        let words: Vec<String> = env.chain(argv).collect();
70        format!("cd {cwd} && {}", words.join(" "))
71    }
72}
73
74/// Checks `user`, an account a console is asked to open as: a name a Unix account has (1 to 32
75/// lowercase letters, digits, `_` or `-`, starting with a letter or `_`), so it goes into a shell
76/// script, a `docker exec --user` or a `sudo -u` as it is.
77///
78/// # Errors
79///
80/// `unsupported` for a name no account has.
81pub(crate) fn check_name(user: &str) -> Result<&str> {
82    let first = |c: char| c.is_ascii_lowercase() || c == '_';
83    let rest = |c: char| first(c) || c.is_ascii_digit() || c == '-';
84    let named = user.len() <= 32 && user.chars().next().is_some_and(first) && user.chars().all(rest);
85    if named {
86        Ok(user)
87    } else {
88        Err(Error::Unsupported {
89            what: format!("a console as `{user}`, which names no account (1 to 32 lowercase letters, digits, `_` or `-`, starting with a letter or `_`),"),
90        })
91    }
92}
93
94/// `word` as a POSIX shell reads it back: as it is when nothing in it is special, else
95/// single-quoted.
96pub(crate) fn sh_word(word: &str) -> String {
97    let plain = |c: char| c.is_ascii_alphanumeric() || "_-.,/:@%+=".contains(c);
98    if !word.is_empty() && word.chars().all(plain) {
99        word.to_owned()
100    } else {
101        sh_quote(word)
102    }
103}
104
105/// `s` single-quoted for a POSIX shell (`'` written `'\''`): a local terminal's line, a remote
106/// shell's command, a script's argument.
107pub(crate) fn sh_quote(s: &str) -> String {
108    format!("'{}'", s.replace('\'', r"'\''"))
109}
110
111#[cfg(test)]
112mod tests {
113    use proptest::prelude::*;
114
115    use super::*;
116
117    proptest! {
118        #[test]
119        fn a_quoted_word_reads_back_as_itself(s in ".{0,40}") {
120            // `'…'` with each `'` as `'\''`: undo it the way sh reads it.
121            let q = sh_quote(&s);
122            let inner = q.strip_prefix('\'').and_then(|q| q.strip_suffix('\'')).unwrap();
123            prop_assert_eq!(inner.replace(r"'\''", "'"), s);
124        }
125    }
126
127    /// The line a shell is given splits back into the command: its folder, its variables, and
128    /// each argument whole, whatever it holds.
129    #[cfg(unix)]
130    #[test]
131    fn a_shell_line_splits_back_into_the_command() {
132        let dir = tempfile::tempdir().unwrap();
133        let cwd = dir.path().join("a run's folder");
134        std::fs::create_dir(&cwd).unwrap();
135        let args = [
136            "-c",
137            r#"printf '%s\n' "$(pwd -P)" "$J" "$@""#,
138            "argv0",
139            "a b",
140            "x; echo no > /dev/null",
141            "it's",
142            "",
143            "$HOME",
144        ];
145        let cmd = ShellCommand::new("sh", args, cwd.clone()).with_env(vec![("J".into(), r#"{"a": [1, "b c"]}"#.into())]);
146        let line = cmd.sh_line();
147        assert!(line.starts_with("cd '"), "{line}");
148        let out = std::process::Command::new("sh").args(["-c", &line]).output().unwrap();
149        let said = String::from_utf8(out.stdout).unwrap();
150        let pwd = cwd.canonicalize().unwrap().display().to_string();
151        let expected = [pwd.as_str(), r#"{"a": [1, "b c"]}"#, "a b", "x; echo no > /dev/null", "it's", "", "$HOME"];
152        assert_eq!(said.lines().collect::<Vec<_>>(), expected, "{line}");
153    }
154
155    /// A word that needs no quote (a path, a variable's plain value) is written as it is: the
156    /// line `isothrum console` prints to paste reads as the command.
157    #[test]
158    fn a_plain_word_is_written_unquoted_in_a_shell_line() {
159        let cmd = ShellCommand::new("vagrant", ["ssh", "web"], "/work/web-vm")
160            .with_env(vec![("VAGRANT_DOTFILE_PATH".into(), "/home/u/.isothrum/runs/web-vm/vagrant".into())]);
161        assert_eq!(
162            cmd.sh_line(),
163            "cd /work/web-vm && VAGRANT_DOTFILE_PATH=/home/u/.isothrum/runs/web-vm/vagrant vagrant ssh web"
164        );
165    }
166}