isothrum_runner/
console.rs1use std::path::PathBuf;
7
8use isoloom_manifest::Machine;
9use serde::Serialize;
10
11use crate::error::{Error, Result};
12
13#[derive(Debug, Clone, Serialize)]
19#[non_exhaustive]
20pub struct ShellCommand {
21 pub program: String,
23 pub args: Vec<String>,
25 pub cwd: PathBuf,
27 pub env: Vec<(String, String)>,
31}
32
33impl ShellCommand {
34 #[must_use]
36 pub fn new(program: impl Into<String>, args: impl IntoIterator<Item = impl Into<String>>, cwd: impl Into<PathBuf>) -> ShellCommand {
37 ShellCommand {
38 program: program.into(),
39 args: args.into_iter().map(Into::into).collect(),
40 cwd: cwd.into(),
41 env: Vec::new(),
42 }
43 }
44
45 #[must_use]
47 pub fn with_env(mut self, env: Vec<(String, String)>) -> ShellCommand {
48 self.env = env;
49 self
50 }
51
52 #[must_use]
56 pub fn sh_line(&self) -> String {
57 let cwd = sh_word(&self.cwd.display().to_string());
58 let env = self.env.iter().map(|(k, v)| format!("{k}={}", sh_word(v)));
59 let argv = std::iter::once(&self.program).chain(&self.args).map(|w| sh_word(w));
60 let words: Vec<String> = env.chain(argv).collect();
61 format!("cd {cwd} && {}", words.join(" "))
62 }
63}
64
65pub(crate) fn check_user<'u>(user: &'u str, machine: &Machine) -> Result<&'u str> {
74 let first = |c: char| c.is_ascii_lowercase() || c == '_';
75 let rest = |c: char| first(c) || c.is_ascii_digit() || c == '-';
76 let named = user.len() <= 32 && user.chars().next().is_some_and(first) && user.chars().all(rest);
77 if !named {
78 return Err(Error::Unsupported {
79 what: format!("a console as `{user}`, which names no account (1 to 32 lowercase letters, digits, `_` or `-`, starting with a letter or `_`),"),
80 });
81 }
82 if machine.windows {
83 return Err(Error::Unsupported {
84 what: format!("a console as `{user}` into `{}`, which runs Windows,", machine.name),
85 });
86 }
87 Ok(user)
88}
89
90fn sh_word(word: &str) -> String {
93 let plain = |c: char| c.is_ascii_alphanumeric() || "_-.,/:@%+=".contains(c);
94 if !word.is_empty() && word.chars().all(plain) {
95 word.to_owned()
96 } else {
97 sh_quote(word)
98 }
99}
100
101pub(crate) fn sh_quote(s: &str) -> String {
104 format!("'{}'", s.replace('\'', r"'\''"))
105}
106
107#[cfg(test)]
108mod tests {
109 use proptest::prelude::*;
110
111 use super::*;
112
113 proptest! {
114 #[test]
115 fn a_quoted_word_reads_back_as_itself(s in ".{0,40}") {
116 let q = sh_quote(&s);
118 let inner = q.strip_prefix('\'').and_then(|q| q.strip_suffix('\'')).unwrap();
119 prop_assert_eq!(inner.replace(r"'\''", "'"), s);
120 }
121 }
122
123 #[cfg(unix)]
126 #[test]
127 fn a_shell_line_splits_back_into_the_command() {
128 let dir = tempfile::tempdir().unwrap();
129 let cwd = dir.path().join("a run's folder");
130 std::fs::create_dir(&cwd).unwrap();
131 let args = [
132 "-c",
133 r#"printf '%s\n' "$(pwd -P)" "$J" "$@""#,
134 "argv0",
135 "a b",
136 "x; echo no > /dev/null",
137 "it's",
138 "",
139 "$HOME",
140 ];
141 let cmd = ShellCommand::new("sh", args, cwd.clone()).with_env(vec![("J".into(), r#"{"a": [1, "b c"]}"#.into())]);
142 let line = cmd.sh_line();
143 assert!(line.starts_with("cd '"), "{line}");
144 let out = std::process::Command::new("sh").args(["-c", &line]).output().unwrap();
145 let said = String::from_utf8(out.stdout).unwrap();
146 let pwd = cwd.canonicalize().unwrap().display().to_string();
147 let expected = [pwd.as_str(), r#"{"a": [1, "b c"]}"#, "a b", "x; echo no > /dev/null", "it's", "", "$HOME"];
148 assert_eq!(said.lines().collect::<Vec<_>>(), expected, "{line}");
149 }
150
151 #[test]
152 fn a_plain_word_stays_as_it_is() {
153 let cmd = ShellCommand::new("vagrant", ["ssh", "web"], "/work/web-vm")
154 .with_env(vec![("VAGRANT_DOTFILE_PATH".into(), "/home/u/.isothrum/runs/web-vm/vagrant".into())]);
155 assert_eq!(
156 (cmd.program.as_str(), cmd.args.as_slice(), cmd.cwd.as_path()),
157 ("vagrant", &["ssh".to_owned(), "web".to_owned()][..], std::path::Path::new("/work/web-vm"))
158 );
159 assert_eq!(ShellCommand::new("docker", ["ps"], "/w").env, [], "no variable of its own until given");
160 assert_eq!(
161 cmd.sh_line(),
162 "cd /work/web-vm && VAGRANT_DOTFILE_PATH=/home/u/.isothrum/runs/web-vm/vagrant vagrant ssh web"
163 );
164 }
165}