Skip to main content

safe_chains/
parse.rs

1use std::ops::Deref;
2
3#[derive(Debug, Clone, PartialEq, Eq)]
4pub struct Token(String);
5
6impl Deref for Token {
7    type Target = str;
8    fn deref(&self) -> &str {
9        &self.0
10    }
11}
12
13#[derive(Copy, Clone)]
14pub struct WordSet(&'static [&'static str]);
15
16impl WordSet {
17    pub const fn new(words: &'static [&'static str]) -> Self {
18        let mut i = 1;
19        while i < words.len() {
20            assert!(
21                const_less(words[i - 1].as_bytes(), words[i].as_bytes()),
22                "WordSet: entries must be sorted, no duplicates"
23            );
24            i += 1;
25        }
26        Self(words)
27    }
28
29    pub const fn flags(words: &'static [&'static str]) -> Self {
30        let mut i = 0;
31        while i < words.len() {
32            let b = words[i].as_bytes();
33            assert!(b.len() >= 2, "WordSet::flags: flag too short (need at least 2 chars)");
34            assert!(b[0] == b'-', "WordSet::flags: flag must start with '-'");
35            if b[1] == b'-' {
36                assert!(b.len() >= 3, "WordSet::flags: long flag needs at least 3 chars (e.g. --x)");
37            }
38            i += 1;
39        }
40        Self::new(words)
41    }
42
43    pub fn contains(&self, s: &str) -> bool {
44        self.0.binary_search(&s).is_ok()
45    }
46
47    pub fn contains_short(&self, b: u8) -> bool {
48        let target = [b'-', b];
49        std::str::from_utf8(&target).is_ok_and(|s| self.0.binary_search(&s).is_ok())
50    }
51
52    pub fn iter(&self) -> impl Iterator<Item = &'static str> + '_ {
53        self.0.iter().copied()
54    }
55}
56
57const fn const_less(a: &[u8], b: &[u8]) -> bool {
58    let min = if a.len() < b.len() { a.len() } else { b.len() };
59    let mut i = 0;
60    while i < min {
61        if a[i] < b[i] {
62            return true;
63        }
64        if a[i] > b[i] {
65            return false;
66        }
67        i += 1;
68    }
69    a.len() < b.len()
70}
71
72impl Token {
73    pub(crate) fn from_raw(s: String) -> Self {
74        Self(s)
75    }
76
77    #[cfg(test)]
78    pub(crate) fn from_test(s: &str) -> Self {
79        Self(s.to_string())
80    }
81
82    pub fn as_str(&self) -> &str {
83        &self.0
84    }
85
86    pub fn command_name(&self) -> &str {
87        self.as_str().rsplit('/').next().unwrap_or(self.as_str())
88    }
89
90    pub fn is_one_of(&self, options: &[&str]) -> bool {
91        options.contains(&self.as_str())
92    }
93
94    pub fn split_value(&self, sep: &str) -> Option<&str> {
95        self.as_str().split_once(sep).map(|(_, v)| v)
96    }
97
98    pub fn content_outside_double_quotes(&self) -> String {
99        let bytes = self.as_str().as_bytes();
100        let mut result = Vec::with_capacity(bytes.len());
101        let mut i = 0;
102        while i < bytes.len() {
103            if bytes[i] == b'"' {
104                result.push(b' ');
105                i += 1;
106                while i < bytes.len() {
107                    if bytes[i] == b'\\' && i + 1 < bytes.len() {
108                        i += 2;
109                        continue;
110                    }
111                    if bytes[i] == b'"' {
112                        i += 1;
113                        break;
114                    }
115                    i += 1;
116                }
117            } else {
118                result.push(bytes[i]);
119                i += 1;
120            }
121        }
122        String::from_utf8(result).unwrap_or_default()
123    }
124}
125
126impl PartialEq<str> for Token {
127    fn eq(&self, other: &str) -> bool {
128        self.0 == other
129    }
130}
131
132impl PartialEq<&str> for Token {
133    fn eq(&self, other: &&str) -> bool {
134        self.0 == *other
135    }
136}
137
138impl PartialEq<Token> for str {
139    fn eq(&self, other: &Token) -> bool {
140        self == other.as_str()
141    }
142}
143
144impl PartialEq<Token> for &str {
145    fn eq(&self, other: &Token) -> bool {
146        *self == other.as_str()
147    }
148}
149
150impl std::fmt::Display for Token {
151    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
152        f.write_str(&self.0)
153    }
154}
155
156pub fn has_flag(tokens: &[Token], short: Option<&str>, long: Option<&str>) -> bool {
157    for token in &tokens[1..] {
158        if token == "--" {
159            return false;
160        }
161        if let Some(long_flag) = long
162            && (token == long_flag || token.starts_with(&format!("{long_flag}=")))
163        {
164            return true;
165        }
166        if let Some(short_flag) = short {
167            let short_char = short_flag.trim_start_matches('-');
168            if token.starts_with('-')
169                && !token.starts_with("--")
170                && token[1..].contains(short_char)
171            {
172                return true;
173            }
174        }
175    }
176    false
177}
178
179#[cfg(test)]
180mod tests {
181    use super::*;
182
183    fn tok(s: &str) -> Token {
184        Token(s.to_string())
185    }
186
187    fn toks(words: &[&str]) -> Vec<Token> {
188        words.iter().map(|s| tok(s)).collect()
189    }
190
191    #[test]
192    fn has_flag_short() {
193        let tokens = toks(&["sed", "-i", "s/foo/bar/"]);
194        assert!(has_flag(&tokens, Some("-i"), Some("--in-place")));
195    }
196
197    #[test]
198    fn has_flag_long_with_eq() {
199        let tokens = toks(&["sed", "--in-place=.bak", "s/foo/bar/"]);
200        assert!(has_flag(&tokens, Some("-i"), Some("--in-place")));
201    }
202
203    #[test]
204    fn has_flag_combined_short() {
205        let tokens = toks(&["sed", "-ni", "s/foo/bar/p"]);
206        assert!(has_flag(&tokens, Some("-i"), Some("--in-place")));
207    }
208
209    #[test]
210    fn has_flag_stops_at_double_dash() {
211        let tokens = toks(&["cmd", "--", "-i"]);
212        assert!(!has_flag(&tokens, Some("-i"), Some("--in-place")));
213    }
214
215    #[test]
216    fn has_flag_long_only() {
217        let tokens = toks(&["sort", "--compress-program", "gzip", "file.txt"]);
218        assert!(has_flag(&tokens, None, Some("--compress-program")));
219    }
220
221    #[test]
222    fn has_flag_long_only_eq() {
223        let tokens = toks(&["sort", "--compress-program=gzip", "file.txt"]);
224        assert!(has_flag(&tokens, None, Some("--compress-program")));
225    }
226
227    #[test]
228    fn has_flag_long_only_absent() {
229        let tokens = toks(&["sort", "-r", "file.txt"]);
230        assert!(!has_flag(&tokens, None, Some("--compress-program")));
231    }
232
233    #[test]
234    fn command_name_simple() {
235        assert_eq!(tok("ls").command_name(), "ls");
236    }
237
238    #[test]
239    fn command_name_with_path() {
240        assert_eq!(tok("/usr/bin/ls").command_name(), "ls");
241    }
242
243    #[test]
244    fn command_name_relative_path() {
245        assert_eq!(tok("./scripts/test.sh").command_name(), "test.sh");
246    }
247
248    #[test]
249    fn reverse_partial_eq() {
250        let t = tok("hello");
251        assert!("hello" == t);
252        assert!("world" != t);
253    }
254
255    #[test]
256    fn token_deref() {
257        let t = tok("--flag");
258        assert!(t.starts_with("--"));
259        assert!(t.contains("fl"));
260        assert_eq!(t.len(), 6);
261    }
262
263    #[test]
264    fn token_is_one_of() {
265        assert!(tok("-v").is_one_of(&["-v", "--verbose"]));
266        assert!(!tok("-q").is_one_of(&["-v", "--verbose"]));
267    }
268
269    #[test]
270    fn token_split_value() {
271        assert_eq!(tok("--method=GET").split_value("="), Some("GET"));
272        assert_eq!(tok("--flag").split_value("="), None);
273    }
274
275    #[test]
276    fn word_set_contains() {
277        let set = WordSet::new(&["list", "show", "view"]);
278        assert!(set.contains(&tok("list")));
279        assert!(set.contains(&tok("view")));
280        assert!(!set.contains(&tok("delete")));
281    }
282
283    #[test]
284    fn word_set_iter() {
285        let set = WordSet::new(&["a", "b", "c"]);
286        let items: Vec<&str> = set.iter().collect();
287        assert_eq!(items, vec!["a", "b", "c"]);
288    }
289
290    #[test]
291    fn content_outside_double_quotes_strips_string() {
292        assert_eq!(tok(r#""system""#).content_outside_double_quotes(), " ");
293    }
294
295    #[test]
296    fn content_outside_double_quotes_preserves_code() {
297        let result = tok(r#"{print "hello"} END{print NR}"#).content_outside_double_quotes();
298        assert_eq!(result, r#"{print  } END{print NR}"#);
299    }
300
301    #[test]
302    fn content_outside_double_quotes_escaped() {
303        let result = tok(r#"{print "he said \"hi\""}"#).content_outside_double_quotes();
304        assert_eq!(result, "{print  }");
305    }
306
307    #[test]
308    fn content_outside_double_quotes_no_quotes() {
309        assert_eq!(tok("{print $1}").content_outside_double_quotes(), "{print $1}");
310    }
311
312    #[test]
313    fn content_outside_double_quotes_empty() {
314        assert_eq!(tok("").content_outside_double_quotes(), "");
315    }
316}