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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
//! Minimal POSIX shell word splitting and quoting used by specs and parser output.
//!
//! Adapted from `shell-words` 1.1.1. Keeping this narrow implementation in-tree avoids
//! making every `usage-lib` consumer compile a crate for four internal call sites.
use std::borrow::Cow;
use std::fmt;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ParseError;
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("missing closing quote")
}
}
impl std::error::Error for ParseError {}
enum State {
Delimiter,
Backslash,
Unquoted,
UnquotedBackslash,
SingleQuoted,
DoubleQuoted,
DoubleQuotedBackslash,
Comment,
}
pub fn split(input: &str) -> Result<Vec<String>, ParseError> {
use State::*;
let mut words = Vec::new();
let mut word = String::new();
let mut chars = input.chars();
let mut state = Delimiter;
loop {
let current = chars.next();
state = match state {
Delimiter => match current {
None => break,
Some('\'') => SingleQuoted,
Some('"') => DoubleQuoted,
Some('\\') => Backslash,
Some('\t' | ' ' | '\n') => Delimiter,
Some('#') => Comment,
Some(c) => {
word.push(c);
Unquoted
}
},
Backslash => match current {
None => {
word.push('\\');
words.push(std::mem::take(&mut word));
break;
}
Some('\n') => Delimiter,
Some(c) => {
word.push(c);
Unquoted
}
},
Unquoted => match current {
None => {
words.push(std::mem::take(&mut word));
break;
}
Some('\'') => SingleQuoted,
Some('"') => DoubleQuoted,
Some('\\') => UnquotedBackslash,
Some('\t' | ' ' | '\n') => {
words.push(std::mem::take(&mut word));
Delimiter
}
Some(c) => {
word.push(c);
Unquoted
}
},
UnquotedBackslash => match current {
None => {
word.push('\\');
words.push(std::mem::take(&mut word));
break;
}
Some('\n') => Unquoted,
Some(c) => {
word.push(c);
Unquoted
}
},
SingleQuoted => match current {
None => return Err(ParseError),
Some('\'') => Unquoted,
Some(c) => {
word.push(c);
SingleQuoted
}
},
DoubleQuoted => match current {
None => return Err(ParseError),
Some('"') => Unquoted,
Some('\\') => DoubleQuotedBackslash,
Some(c) => {
word.push(c);
DoubleQuoted
}
},
DoubleQuotedBackslash => match current {
None => return Err(ParseError),
Some('\n') => DoubleQuoted,
Some(c @ ('$' | '`' | '"' | '\\')) => {
word.push(c);
DoubleQuoted
}
Some(c) => {
word.push('\\');
word.push(c);
DoubleQuoted
}
},
Comment => match current {
None => break,
Some('\n') => Delimiter,
Some(_) => Comment,
},
};
}
Ok(words)
}
fn quote(word: &str) -> Cow<'_, str> {
if !word.is_empty()
&& !word.chars().any(|c| {
matches!(
c,
'\n' | '\''
| '|'
| '&'
| ';'
| '<'
| '>'
| '('
| ')'
| '$'
| '`'
| '\\'
| '"'
| ' '
| '\t'
| '*'
| '?'
| '['
| '#'
| '~'
| '='
| '%'
)
})
{
return Cow::Borrowed(word);
}
let mut quoted = String::with_capacity(word.len() + 2);
quoted.push('\'');
for c in word.chars() {
if c == '\'' {
quoted.push_str("'\\''");
} else {
quoted.push(c);
}
}
quoted.push('\'');
Cow::Owned(quoted)
}
pub fn join<I, S>(words: I) -> String
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
words
.into_iter()
.map(|word| quote(word.as_ref()).into_owned())
.collect::<Vec<_>>()
.join(" ")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn split_and_join_shell_words() {
let words = split("one 'two three' four\\ five # ignored").unwrap();
assert_eq!(words, ["one", "two three", "four five"]);
assert_eq!(split(&join(&words)).unwrap(), words);
assert!(split("'unterminated").is_err());
}
}