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
pub fn escape_quote_string(input: &str) -> String {
let mut output = String::with_capacity(input.len() + 2);
output.push('"');
for c in input.chars() {
if c == '"' || c == '\\' {
output.push('\\');
}
output.push(c);
}
output.push('"');
output
}
pub fn escape_for_script_arg(input: &str) -> String {
if input.starts_with("--") {
if let Some((arg_name, arg_val)) = input.split_once('=') {
let arg_val = if arg_val.contains(' ') {
format!("`{arg_val}`")
} else if arg_val.contains('"') || arg_val.contains('\\') {
escape_quote_string(arg_val)
} else {
arg_val.into()
};
return format!("{arg_name}={arg_val}");
}
}
if input.contains(' ') {
format!("`{input}`")
} else if input.contains('"') || input.contains('\\') {
escape_quote_string(input)
} else {
input.to_string()
}
}
#[cfg(test)]
mod test {
use super::escape_for_script_arg;
#[test]
fn test_not_extra_quote() {
assert_eq!(escape_for_script_arg("8"), "8".to_string());
}
#[test]
fn test_arg_with_flag() {
assert_eq!(escape_for_script_arg("linux"), "linux".to_string());
assert_eq!(
escape_for_script_arg("--version=v5.2"),
"--version=v5.2".to_string()
);
assert_eq!(escape_for_script_arg("--version"), "--version".to_string());
assert_eq!(escape_for_script_arg("v5.2"), "v5.2".to_string());
}
#[test]
fn test_flag_arg_with_values_contains_space() {
assert_eq!(
escape_for_script_arg("--version='xx yy'"),
"--version=`'xx yy'`".to_string()
);
assert_eq!(
escape_for_script_arg("--arch=ghi"),
"--arch=ghi".to_string()
);
}
#[test]
fn test_escape() {
assert_eq!(escape_for_script_arg(r#"""#), r#""\"""#.to_string());
}
}