-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand_parser.rs
More file actions
825 lines (744 loc) · 31 KB
/
command_parser.rs
File metadata and controls
825 lines (744 loc) · 31 KB
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
use std::collections::{HashMap, HashSet};
use crate::rules::CommandParseError;
/// Schema describing which flags take values vs. are boolean-only.
///
/// Derived from rule patterns (Policy-Derived Schema): if a rule writes
/// `deny: "curl -X POST"`, then `-X` is inferred to take a value.
/// Flags not listed in `value_flags` are treated as boolean (no value).
#[derive(Debug, Default)]
pub struct FlagSchema {
/// Flags known to take a following value (e.g., `-X`, `--request`).
pub value_flags: HashSet<String>,
}
/// A parsed command with structured flag and argument information.
#[derive(Debug, PartialEq)]
pub struct ParsedCommand {
/// The command name (first token).
pub command: String,
/// Flags and their optional values. Boolean flags have `None`.
/// For `=`-joined tokens like `-Dkey=value`, the key is the flag name
/// and the value is the part after `=`.
///
/// Duplicate flags are last-wins (HashMap semantics). This is acceptable
/// because the matching engine uses `raw_tokens` for pattern matching,
/// not this map. This map is for structured access in `when` expressions.
pub flags: HashMap<String, Option<String>>,
/// Positional arguments (non-flag tokens after the command name).
pub args: Vec<String>,
/// The original raw tokens from tokenization.
pub raw_tokens: Vec<String>,
}
/// Parse a command string into a structured `ParsedCommand`.
///
/// Uses `FlagSchema` to determine whether a flag consumes the next token
/// as its value. Unknown flags are treated as boolean (no value).
/// Tokens containing `=` (e.g., `-Denv=prod`, `--word-diff=color`) are
/// split into flag name and value at the first `=`.
///
/// Combined short flags (`-am`) are not split into individual flags.
/// Rules match tokens literally ("What You See Is How It Parses"),
/// so `-m` in a rule won't match `-am` in the input.
pub fn parse_command(input: &str, schema: &FlagSchema) -> Result<ParsedCommand, CommandParseError> {
let raw_tokens = tokenize(input)?;
let command = raw_tokens[0].clone();
let mut flags = HashMap::new();
let mut args = Vec::new();
let mut i = 1;
while i < raw_tokens.len() {
let token = &raw_tokens[i];
if let Some(eq_pos) = token.find('=') {
// Handle `=`-joined flags like `-Denv=prod` or `--word-diff=color`
let flag_part = &token[..eq_pos];
if flag_part.starts_with('-') {
let value_part = &token[eq_pos + 1..];
flags.insert(flag_part.to_string(), Some(value_part.to_string()));
i += 1;
continue;
}
}
if token.starts_with('-') {
if schema.value_flags.contains(token.as_str()) {
// Flag takes a value: consume the next token
let value = raw_tokens.get(i + 1).cloned();
flags.insert(token.clone(), value);
i += 2;
} else {
// Boolean flag (no value)
flags.insert(token.clone(), None);
i += 1;
}
} else {
args.push(token.clone());
i += 1;
}
}
Ok(ParsedCommand {
command,
flags,
args,
raw_tokens,
})
}
/// Tokenize a command string into a list of raw tokens.
///
/// Handles:
/// - Whitespace-delimited splitting
/// - Single-quoted strings (no escape processing inside)
/// - Double-quoted strings (backslash escapes for `\`, `"`, `$`, `` ` ``, newline;
/// unknown escapes preserve the backslash to match shell behavior)
/// - Backslash escapes outside of quotes
/// - Empty quoted strings (`""`, `''`) are preserved as empty tokens
pub fn tokenize(input: &str) -> Result<Vec<String>, CommandParseError> {
let trimmed = input.trim();
if trimmed.is_empty() {
return Err(CommandParseError::EmptyCommand);
}
let mut tokens = Vec::new();
let mut current = String::new();
let mut has_token = false;
let mut chars = trimmed.chars().peekable();
while let Some(&ch) = chars.peek() {
match ch {
// Whitespace outside quotes: emit current token
c if c.is_ascii_whitespace() => {
if has_token {
tokens.push(std::mem::take(&mut current));
has_token = false;
}
chars.next();
}
// Single quote: consume until closing quote, no escape processing
'\'' => {
has_token = true;
chars.next(); // consume opening quote
loop {
match chars.next() {
Some('\'') => break,
Some(c) => current.push(c),
None => return Err(CommandParseError::UnclosedQuote),
}
}
}
// Double quote: consume with escape processing
'"' => {
has_token = true;
chars.next(); // consume opening quote
loop {
match chars.next() {
Some('"') => break,
Some('\\') => match chars.next() {
Some(c @ ('"' | '\\' | '$' | '`')) => current.push(c),
Some('\n') => {} // line continuation
// Unknown escape: preserve backslash (match shell behavior)
Some(c) => {
current.push('\\');
current.push(c);
}
None => return Err(CommandParseError::UnclosedQuote),
},
Some(c) => current.push(c),
None => return Err(CommandParseError::UnclosedQuote),
}
}
}
// Backslash escape outside quotes
'\\' => {
chars.next(); // consume backslash
match chars.next() {
Some('\n') => {} // line continuation
Some(c) => {
has_token = true;
current.push(c);
}
None => {} // trailing backslash is ignored
}
}
// Regular character
_ => {
has_token = true;
current.push(ch);
chars.next();
}
}
}
if has_token {
tokens.push(current);
}
if tokens.is_empty() {
return Err(CommandParseError::EmptyCommand);
}
Ok(tokens)
}
/// Extract individual command strings from a potentially compound shell input.
///
/// Splits on pipelines (`|`), logical operators (`&&`, `||`), and semicolons (`;`).
/// Uses tree-sitter-bash to correctly handle quoting and nesting.
/// Returns `SyntaxError` if the input contains parse errors.
pub fn extract_commands(input: &str) -> Result<Vec<String>, CommandParseError> {
let trimmed = input.trim();
if trimmed.is_empty() {
return Err(CommandParseError::EmptyCommand);
}
let mut parser = tree_sitter::Parser::new();
parser
.set_language(&tree_sitter_bash::LANGUAGE.into())
.map_err(|_| CommandParseError::SyntaxError)?;
let tree = parser
.parse(trimmed, None)
.ok_or(CommandParseError::SyntaxError)?;
let root = tree.root_node();
if root.has_error() {
return Err(CommandParseError::SyntaxError);
}
let mut commands = Vec::new();
collect_commands(root, trimmed.as_bytes(), &mut commands);
if commands.is_empty() {
return Err(CommandParseError::SyntaxError);
}
Ok(commands)
}
/// Recursively walk the tree-sitter AST and collect individual command strings.
///
/// Compound constructs (pipeline, list, subshell, control structures) are split
/// into their constituent commands. Conditions and value lists are also recursed
/// into so that commands within them (including command substitutions) are extracted.
fn collect_commands(node: tree_sitter::Node, source: &[u8], commands: &mut Vec<String>) {
match node.kind() {
// Transparent containers: recurse into all named children.
// Skips anonymous tokens like `;`, `&&`, `||`, `|`, `(`, `)`,
// `do`, `done`, `then`, `fi`, `esac`, keywords, etc.
"program"
| "pipeline"
| "list"
| "subshell"
| "do_group"
| "compound_statement"
| "else_clause"
| "command_substitution"
| "while_statement"
| "if_statement"
| "elif_clause" => {
let mut cursor = node.walk();
for child in node.named_children(&mut cursor) {
collect_commands(child, source, commands);
}
}
// for_statement: recurse into body (do_group) and any command_substitution
// nodes in the value list. Literal values (number, word, etc.) are skipped.
"for_statement" => {
let mut cursor = node.walk();
for child in node.named_children(&mut cursor) {
match child.kind() {
"do_group" | "command_substitution" => {
collect_commands(child, source, commands);
}
_ => {}
}
}
}
// case_statement: recurse into each case_item (skip the match value)
"case_statement" => {
let mut cursor = node.walk();
for child in node.named_children(&mut cursor) {
if child.kind() == "case_item" {
collect_commands(child, source, commands);
}
}
}
// case_item: skip pattern values (field name "value"), recurse into the rest
"case_item" => {
for i in 0..node.child_count() {
if node.field_name_for_child(i as u32) == Some("value") {
continue;
}
if let Some(child) = node.child(i)
&& child.is_named()
{
collect_commands(child, source, commands);
}
}
}
// function_definition: recurse into body
"function_definition" => {
if let Some(body) = node.child_by_field_name("body") {
collect_commands(body, source, commands);
}
}
// Leaf command nodes — extract the source text, and also recurse
// into any command_substitution children to extract nested commands.
_ => {
let mut cursor = node.walk();
for child in node.named_children(&mut cursor) {
if child.kind() == "command_substitution" {
collect_commands(child, source, commands);
}
}
let text = &source[node.start_byte()..node.end_byte()];
let text = std::str::from_utf8(text).unwrap_or("").trim();
if !text.is_empty() {
commands.push(text.to_string());
}
}
}
}
/// Join tokens into a shell-safe string by quoting tokens that contain
/// spaces or shell metacharacters. Tokens without special characters are
/// emitted verbatim.
pub fn shell_quote_join(tokens: &[String]) -> String {
tokens
.iter()
.map(|t| shell_quote(t))
.collect::<Vec<_>>()
.join(" ")
}
/// Quote a single token for safe shell usage. If the token contains no
/// shell-significant characters it is returned as-is. Otherwise it is
/// wrapped in single quotes, with internal single quotes escaped as `'\''`.
fn shell_quote(token: &str) -> String {
if token.is_empty() {
return "''".to_string();
}
// Characters that require quoting in POSIX shells
if token.chars().all(|c| {
c.is_ascii_alphanumeric()
|| matches!(c, '-' | '_' | '.' | '/' | ':' | '=' | '@' | '%' | '+' | ',')
}) {
return token.to_string();
}
// Wrap in single quotes, escaping internal single quotes
let mut quoted = String::with_capacity(token.len() + 2);
quoted.push('\'');
for ch in token.chars() {
if ch == '\'' {
// End current quote, insert escaped quote, restart quote
quoted.push_str("'\\''");
} else {
quoted.push(ch);
}
}
quoted.push('\'');
quoted
}
#[cfg(test)]
mod tests {
use super::*;
use indoc::indoc;
use rstest::rstest;
// ========================================
// tokenize: simple commands
// ========================================
#[rstest]
#[case("echo hello", vec!["echo", "hello"])]
#[case("git status", vec!["git", "status"])]
#[case("ls -la /tmp", vec!["ls", "-la", "/tmp"])]
fn tokenize_simple_commands(#[case] input: &str, #[case] expected: Vec<&str>) {
let result = tokenize(input).unwrap();
assert_eq!(result, expected);
}
#[rstest]
#[case(" echo hello ", vec!["echo", "hello"])]
#[case("git\t\tstatus", vec!["git", "status"])]
fn tokenize_extra_whitespace(#[case] input: &str, #[case] expected: Vec<&str>) {
let result = tokenize(input).unwrap();
assert_eq!(result, expected);
}
#[test]
fn tokenize_single_command() {
let result = tokenize("ls").unwrap();
assert_eq!(result, vec!["ls"]);
}
// ========================================
// tokenize: single-quoted strings
// ========================================
#[rstest]
#[case("echo 'hello world'", vec!["echo", "hello world"])]
#[case("echo 'it'\\''s'", vec!["echo", "it's"])]
#[case("echo 'no \\escapes'", vec!["echo", "no \\escapes"])]
fn tokenize_single_quotes(#[case] input: &str, #[case] expected: Vec<&str>) {
let result = tokenize(input).unwrap();
assert_eq!(result, expected);
}
// ========================================
// tokenize: double-quoted strings
// ========================================
#[rstest]
#[case(r#"echo "hello world""#, vec!["echo", "hello world"])]
#[case(r#"echo "with \"quotes\"""#, vec!["echo", r#"with "quotes""#])]
#[case(r#"echo "back\\slash""#, vec!["echo", "back\\slash"])]
fn tokenize_double_quotes(#[case] input: &str, #[case] expected: Vec<&str>) {
let result = tokenize(input).unwrap();
assert_eq!(result, expected);
}
// ========================================
// tokenize: unknown escape sequences in double quotes
// ========================================
#[test]
fn tokenize_double_quote_unknown_escape_preserves_backslash() {
// Shell behavior: "\j" -> "\j" (backslash preserved for unknown escapes)
let result = tokenize(r#"echo "\j""#).unwrap();
assert_eq!(result, vec!["echo", "\\j"]);
}
#[test]
fn tokenize_double_quote_known_escapes_preserved() {
// Known escapes: \\, \", \$, \` are processed
let result = tokenize(r#"echo "a\$b""#).unwrap();
assert_eq!(result, vec!["echo", "a$b"]);
}
// ========================================
// tokenize: escape sequences (outside quotes)
// ========================================
#[rstest]
#[case("echo hello\\ world", vec!["echo", "hello world"])]
#[case("echo test\\\"quote", vec!["echo", "test\"quote"])]
fn tokenize_escapes(#[case] input: &str, #[case] expected: Vec<&str>) {
let result = tokenize(input).unwrap();
assert_eq!(result, expected);
}
#[test]
fn tokenize_trailing_backslash_ignored() {
// Trailing backslash at end of input should not produce a spurious empty token
let result = tokenize("echo \\").unwrap();
assert_eq!(result, vec!["echo"]);
}
// ========================================
// tokenize: mixed quoting
// ========================================
#[rstest]
#[case(
r#"curl -X POST -H "Content-Type: application/json" https://example.com"#,
vec!["curl", "-X", "POST", "-H", "Content-Type: application/json", "https://example.com"]
)]
#[case(
"git commit -m 'initial commit'",
vec!["git", "commit", "-m", "initial commit"]
)]
fn tokenize_mixed_quoting(#[case] input: &str, #[case] expected: Vec<&str>) {
let result = tokenize(input).unwrap();
assert_eq!(result, expected);
}
// ========================================
// tokenize: concatenated quoting
// ========================================
#[test]
fn tokenize_concatenated_quotes() {
// e.g., echo "hello"' world' -> "hello world"
let result = tokenize(r#"echo "hello"' world'"#).unwrap();
assert_eq!(result, vec!["echo", "hello world"]);
}
// ========================================
// tokenize: empty quoted strings
// ========================================
#[test]
fn tokenize_empty_double_quotes() {
let result = tokenize(r#"echo "" arg"#).unwrap();
assert_eq!(result, vec!["echo", "", "arg"]);
}
#[test]
fn tokenize_empty_single_quotes() {
let result = tokenize("echo '' arg").unwrap();
assert_eq!(result, vec!["echo", "", "arg"]);
}
// ========================================
// tokenize: error cases
// ========================================
#[rstest]
#[case("", CommandParseError::EmptyCommand)]
#[case(" ", CommandParseError::EmptyCommand)]
#[case("\\", CommandParseError::EmptyCommand)]
#[case("\\\n", CommandParseError::EmptyCommand)]
#[case("echo 'hello", CommandParseError::UnclosedQuote)]
#[case::unclosed_double_quote(r#"echo "hello"#, CommandParseError::UnclosedQuote)]
fn tokenize_errors(#[case] input: &str, #[case] expected: CommandParseError) {
let result = tokenize(input);
assert_eq!(
std::mem::discriminant(&result.unwrap_err()),
std::mem::discriminant(&expected),
);
}
// ========================================
// tokenize: flags with = syntax
// ========================================
#[rstest]
#[case("java -Denv=prod", vec!["java", "-Denv=prod"])]
#[case("git diff --word-diff=color", vec!["git", "diff", "--word-diff=color"])]
fn tokenize_equals_flags(#[case] input: &str, #[case] expected: Vec<&str>) {
let result = tokenize(input).unwrap();
assert_eq!(result, expected);
}
// ========================================
// extract_commands: compound commands
// ========================================
#[rstest]
#[case::single("echo hello", vec!["echo hello"])]
#[case::pipeline("echo hello | grep world", vec!["echo hello", "grep world"])]
#[case::and("cmd1 && cmd2", vec!["cmd1", "cmd2"])]
#[case::or("cmd1 || cmd2", vec!["cmd1", "cmd2"])]
#[case::semicolon("cmd1 ; cmd2", vec!["cmd1", "cmd2"])]
#[case::mixed_operators("curl url | jq '.data' && rm tmp.json", vec!["curl url", "jq '.data'", "rm tmp.json"])]
#[case::logical_chain("cmd1 && cmd2 || cmd3", vec!["cmd1", "cmd2", "cmd3"])]
#[case::quotes_preserved(r#"echo "hello | world" && grep test"#, vec![r#"echo "hello | world""#, "grep test"])]
fn extract_compound_commands(#[case] input: &str, #[case] expected: Vec<&str>) {
let result = extract_commands(input).unwrap();
assert_eq!(result, expected);
}
// ========================================
// extract_commands: subshell
// ========================================
#[rstest]
#[case::in_pipeline("(cmd1 && cmd2) | cmd3", vec!["cmd1", "cmd2", "cmd3"])]
#[case::in_logical_chain("(cmd1 ; cmd2) && cmd3", vec!["cmd1", "cmd2", "cmd3"])]
// `((...))` is arithmetic expansion in bash, so we use
// `(... | (...))` to test genuine subshell nesting.
#[case::deeply_nested("(cmd1 | (cmd2 ; cmd3)) && cmd4", vec!["cmd1", "cmd2", "cmd3", "cmd4"])]
fn extract_subshell(#[case] input: &str, #[case] expected: Vec<&str>) {
let result = extract_commands(input).unwrap();
assert_eq!(result, expected);
}
// ========================================
// extract_commands: special constructs
// ========================================
#[rstest]
#[case::process_substitution("diff <(cmd1) <(cmd2)", vec!["diff <(cmd1) <(cmd2)"])]
fn extract_special_constructs(#[case] input: &str, #[case] expected: Vec<&str>) {
let result = extract_commands(input).unwrap();
assert_eq!(result, expected);
}
#[test]
fn extract_heredoc() {
let input = indoc! {"
cat <<EOF
hello
EOF
"}
.trim_end();
let result = extract_commands(input).unwrap();
assert_eq!(result, vec![input]);
}
// ========================================
// extract_commands: whitespace handling
// ========================================
#[rstest]
#[case::extra_whitespace(" cmd1 && cmd2 ", vec!["cmd1", "cmd2"])]
#[case::with_subshell(" cmd1 && cmd2 | ( cmd3 ) ", vec!["cmd1", "cmd2", "cmd3"])]
fn extract_commands_whitespace(#[case] input: &str, #[case] expected: Vec<&str>) {
let result = extract_commands(input).unwrap();
assert_eq!(result, expected);
}
// ========================================
// extract_commands: control structures
// ========================================
#[rstest]
#[case::for_simple("for i in 1 2 3; do echo $i; done", vec!["echo $i"])]
#[case::for_multiple_cmds("for f in *.txt; do cat $f && rm $f; done", vec!["cat $f", "rm $f"])]
#[case::for_cmd_substitution("for f in $(find . -name '*.txt'); do echo $f; done", vec!["find . -name '*.txt'", "echo $f"])]
#[case::for_backtick_substitution("for f in `ls`; do cat $f; done", vec!["ls", "cat $f"])]
#[case::while_simple("while true; do echo hello; done", vec!["true", "echo hello"])]
#[case::while_pipeline("while read line; do echo $line | grep foo; done", vec!["read line", "echo $line", "grep foo"])]
#[case::if_then("if true; then echo yes; fi", vec!["true", "echo yes"])]
#[case::if_then_else("if true; then echo yes; else echo no; fi", vec!["true", "echo yes", "echo no"])]
#[case::if_elif_else("if true; then echo a; elif false; then echo b; else echo c; fi", vec!["true", "echo a", "false", "echo b", "echo c"])]
#[case::case_statement("case $x in a) echo a;; b) echo b;; esac", vec!["echo a", "echo b"])]
#[case::compound_statement("{ echo a; echo b; }", vec!["echo a", "echo b"])]
#[case::function_def("f() { echo hello; }", vec!["echo hello"])]
fn extract_control_structures(#[case] input: &str, #[case] expected: Vec<&str>) {
let result = extract_commands(input).unwrap();
assert_eq!(result, expected);
}
// ========================================
// extract_commands: nested control structures
// ========================================
#[rstest]
#[case::for_in_if("for i in 1 2; do if true; then echo $i; fi; done", vec!["true", "echo $i"])]
#[case::if_in_for("if true; then for i in a b; do echo $i; done; fi", vec!["true", "echo $i"])]
fn extract_nested_control_structures(#[case] input: &str, #[case] expected: Vec<&str>) {
let result = extract_commands(input).unwrap();
assert_eq!(result, expected);
}
// ========================================
// extract_commands: control structures with pipeline/list
// ========================================
#[rstest]
#[case::list_with_for("echo start && for i in 1 2; do echo $i; done", vec!["echo start", "echo $i"])]
#[case::for_piped("for i in 1 2; do echo $i; done | grep 1", vec!["echo $i", "grep 1"])]
#[case::cmd_sub_in_command("echo $(dangerous_cmd)", vec!["dangerous_cmd", "echo $(dangerous_cmd)"])]
#[case::backtick_in_command("echo `dangerous_cmd`", vec!["dangerous_cmd", "echo `dangerous_cmd`"])]
fn extract_control_with_operators(#[case] input: &str, #[case] expected: Vec<&str>) {
let result = extract_commands(input).unwrap();
assert_eq!(result, expected);
}
// ========================================
// extract_commands: error cases
// ========================================
#[rstest]
#[case::empty("", CommandParseError::EmptyCommand)]
#[case::syntax_error("&&", CommandParseError::SyntaxError)]
fn extract_commands_errors(#[case] input: &str, #[case] expected: CommandParseError) {
let result = extract_commands(input);
assert_eq!(
std::mem::discriminant(&result.unwrap_err()),
std::mem::discriminant(&expected),
);
}
// ========================================
// parse_command: no schema (default) — unknown flags are boolean
// ========================================
#[rstest]
// simple commands without flags
#[case::no_flags("git status", "git", &[], &["status"])]
#[case::multiple_args("cp src.txt dst.txt", "cp", &[], &["src.txt", "dst.txt"])]
// boolean flags (unknown → boolean)
#[case::short_combined("rm -rf /tmp/test", "rm", &[("-rf", None)], &["/tmp/test"])]
#[case::long_flag("git push --force origin main", "git", &[("--force", None)], &["push", "origin", "main"])]
// equals-joined flags
#[case::eq_short("java -Denv=prod Main", "java", &[("-Denv", Some("prod"))], &["Main"])]
#[case::eq_long("git diff --word-diff=color file.txt", "git", &[("--word-diff", Some("color"))], &["diff", "file.txt"])]
// equals in non-flag token → positional arg
#[case::eq_non_flag("echo key=value", "echo", &[], &["key=value"])]
fn parse_command_default_schema(
#[case] input: &str,
#[case] expected_cmd: &str,
#[case] expected_flags: &[(&str, Option<&str>)],
#[case] expected_args: &[&str],
) {
let schema = FlagSchema::default();
let result = parse_command(input, &schema).unwrap();
assert_eq!(result.command, expected_cmd);
assert_eq!(result.args, expected_args);
assert_eq!(result.flags.len(), expected_flags.len());
for &(flag, value) in expected_flags {
assert_eq!(
result.flags.get(flag),
Some(&value.map(String::from)),
"flag {flag}"
);
}
}
// ========================================
// parse_command: with schema — value flags consume next token
// ========================================
#[rstest]
// short value flag
#[case::short(
"curl -X POST https://example.com",
&["-X"],
"curl", &[("-X", Some("POST"))], &["https://example.com"],
)]
// long value flag
#[case::long(
"curl --request GET https://example.com",
&["--request"],
"curl", &[("--request", Some("GET"))], &["https://example.com"],
)]
// value flag at end with no following token
#[case::at_end(
"git commit -m",
&["-m"],
"git", &[("-m", None)], &["commit"],
)]
// separate boolean flag + value flag: `-a -m "msg"` keeps them distinct
#[case::separate_bool_and_value(
r#"git commit -a -m "initial commit""#,
&["-m"],
"git", &[("-a", None), ("-m", Some("initial commit"))], &["commit"],
)]
// combined short flags `-am` is treated as a single unknown flag token;
// runok does not split combined short flags (by design: "What You See
// Is How It Parses" — the rule `-m` won't match `-am`)
#[case::combined_short_flags(
r#"git commit -am "initial commit""#,
&["-m"],
"git", &[("-am", None)], &["commit", "initial commit"],
)]
// argument order independence: flag before arg
#[case::order_flag_first(
"curl -X POST https://example.com",
&["-X"],
"curl", &[("-X", Some("POST"))], &["https://example.com"],
)]
// argument order independence: flag after arg
#[case::order_flag_last(
"curl https://example.com -X POST",
&["-X"],
"curl", &[("-X", Some("POST"))], &["https://example.com"],
)]
fn parse_command_with_schema(
#[case] input: &str,
#[case] value_flags: &[&str],
#[case] expected_cmd: &str,
#[case] expected_flags: &[(&str, Option<&str>)],
#[case] expected_args: &[&str],
) {
let schema = FlagSchema {
value_flags: value_flags.iter().map(|s| s.to_string()).collect(),
};
let result = parse_command(input, &schema).unwrap();
assert_eq!(result.command, expected_cmd);
assert_eq!(result.args, expected_args);
assert_eq!(result.flags.len(), expected_flags.len());
for &(flag, value) in expected_flags {
assert_eq!(
result.flags.get(flag),
Some(&value.map(String::from)),
"flag {flag}"
);
}
}
// ========================================
// parse_command: multiple value flags
// ========================================
#[test]
fn parse_command_mixed_flags_and_args() {
let schema = FlagSchema {
value_flags: ["-H", "-X"].iter().map(|s| s.to_string()).collect(),
};
let result = parse_command(
r#"curl -X POST -H "Content-Type: application/json" https://example.com"#,
&schema,
)
.unwrap();
assert_eq!(result.command, "curl");
assert_eq!(result.flags.get("-X"), Some(&Some("POST".to_string())));
assert_eq!(
result.flags.get("-H"),
Some(&Some("Content-Type: application/json".to_string()))
);
assert_eq!(result.args, vec!["https://example.com"]);
}
// ========================================
// parse_command: error cases
// ========================================
#[test]
fn parse_command_empty_input() {
let schema = FlagSchema::default();
let result = parse_command("", &schema);
assert!(matches!(result, Err(CommandParseError::EmptyCommand)));
}
// ========================================
// parse_command: raw_tokens preserved
// ========================================
#[test]
fn parse_command_raw_tokens_preserved() {
let schema = FlagSchema {
value_flags: HashSet::from(["-X".to_string()]),
};
let result = parse_command("curl -X POST https://example.com", &schema).unwrap();
assert_eq!(
result.raw_tokens,
vec!["curl", "-X", "POST", "https://example.com"]
);
}
// ========================================
// shell_quote_join
// ========================================
#[rstest]
#[case::simple(&["echo", "hello"], "echo hello")]
#[case::space_in_token(&["echo", "hello world"], "echo 'hello world'")]
#[case::empty_token(&["echo", ""], "echo ''")]
#[case::single_quote_in_token(&["echo", "it's"], "echo 'it'\\''s'")]
#[case::flags_and_paths(&["rm", "-rf", "/tmp/dir"], "rm -rf /tmp/dir")]
#[case::single_token(&["ls"], "ls")]
fn shell_quote_join_cases(#[case] tokens: &[&str], #[case] expected: &str) {
let owned: Vec<String> = tokens.iter().map(|s| s.to_string()).collect();
assert_eq!(shell_quote_join(&owned), expected);
}
}