isothrum_runner/
console.rs1use std::path::PathBuf;
8
9use serde::{Deserialize, Serialize};
10
11use crate::error::{Error, Result};
12
13pub(crate) mod shells;
14
15#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
21#[non_exhaustive]
22pub struct ShellCommand {
23 pub program: String,
25 pub args: Vec<String>,
27 pub cwd: PathBuf,
29 pub env: Vec<(String, String)>,
33}
34
35impl ShellCommand {
36 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 #[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 #[must_use]
56 pub fn with_env(mut self, env: Vec<(String, String)>) -> ShellCommand {
57 self.env = env;
58 self
59 }
60
61 #[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
74pub(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
94pub(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
105pub(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 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 #[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 #[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}