Skip to main content

git_policy_cli/worktree/
shell_quote.rs

1//! What:
2//!  Quoting of bytes that are printed inside a shell command for a person to copy and run.
3//! Why:
4//!  A path or a kernel argument can hold spaces, quotes, `;`, `$(...)` or bytes that are not UTF-8. Printed bare, a
5//!  pasted command runs whatever follows the separator or substitution, or passes the wrong arguments. A value of safe
6//!  characters is printed as it is; any other value is wrapped in single quotes (each single quote inside closed,
7//!  escaped and opened again); a value with a control character or a byte that is not UTF-8 is spelled in the ANSI-C
8//!  form `$'...'` of bash, zsh and ksh with those bytes written as `\xHH` escapes, so the printed text holds no control
9//!  character and no line break. The same rules as `package/wg/cli-quicker/src/shell-quote.ts`.
10//!
11//! In TS you'd write (pseudocode):
12//! ```ts
13//! shellQuote({ value: "it's" }); // "'it'\\''s'"
14//! ```
15
16/// Whether a byte is one a POSIX shell leaves alone in a word.
17fn is_bare(byte: u8) -> bool {
18    return byte.is_ascii_alphanumeric() || matches!(byte, b'@' | b'%' | b'+' | b'=' | b':' | b',' | b'.' | b'/' | b'_' | b'-');
19}
20
21/// Whether a character is a C0 control, DEL or a C1 control.
22fn is_control(character: char) -> bool {
23    return character.is_control();
24}
25
26/// The ANSI-C spelling of one byte.
27fn escaped_byte(byte: u8) -> String {
28    return format!("\\x{byte:02x}");
29}
30
31/// The ANSI-C spelling of one character.
32fn ansi_character(character: char) -> String {
33    return match character {
34        '\\' => String::from("\\\\"),
35        '\'' => String::from("\\'"),
36        '\n' => String::from("\\n"),
37        '\t' => String::from("\\t"),
38        other if is_control(other) => {
39            let mut buffer: [u8; 4] = [0; 4];
40            other.encode_utf8(&mut buffer).bytes().map(escaped_byte).collect()
41        }
42        other => other.to_string(),
43    };
44}
45
46/// What:
47///  Quote bytes so a POSIX shell (bash, zsh or ksh for the `$'...'` form) reads them back as one word.
48///  `&[u8]` is a borrowed byte view; a path's bytes come from `OsStrExt::as_bytes`.
49/// Why:
50///   See the module description.
51///
52/// In TS you'd write (pseudocode):
53/// ```ts
54/// shellQuote({ value: bytes });
55/// ```
56pub fn shell_quote(value: &[u8]) -> String {
57    if value.is_empty() {
58        return String::from("''");
59    }
60    if value.iter().all(|byte: &u8| { return is_bare(*byte); }) {
61        return value.iter().map(|byte: &u8| { return char::from(*byte); }).collect();
62    }
63    let mut spelled: String = String::new();
64    let mut needs_ansi: bool = false;
65    for chunk in value.utf8_chunks() {
66        for character in chunk.valid().chars() {
67            needs_ansi = needs_ansi || is_control(character);
68            spelled.push_str(ansi_character(character).as_str());
69        }
70        for byte in chunk.invalid() {
71            needs_ansi = true;
72            spelled.push_str(escaped_byte(*byte).as_str());
73        }
74    }
75    if needs_ansi {
76        return format!("$'{spelled}'");
77    }
78    let plain: String = String::from_utf8_lossy(value).replace('\'', "'\\''");
79    return format!("'{plain}'");
80}
81
82/// Shell quoting controls stay out of the release executable.
83#[cfg(test)]
84#[path = "shell_quote_tests.rs"]
85mod tests;