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