-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand_parser.rs
More file actions
1013 lines (924 loc) · 39.4 KB
/
command_parser.rs
File metadata and controls
1013 lines (924 loc) · 39.4 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
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
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);
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"
| "process_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 as u32)
&& child.is_named()
{
collect_commands(child, source, commands);
}
}
}
// redirected_statement: recurse into the body (the actual command),
// stripping redirect operators (>, >>, <, 2>&1, etc.).
// Redirect target paths are left to the OS-level sandbox to enforce.
// Also recurse into redirect children to extract nested commands
// (e.g. process substitutions: `cmd > >(nested_cmd)`).
"redirected_statement" => {
if let Some(body) = node.child_by_field_name("body") {
collect_commands(body, source, commands);
}
for i in 0..node.child_count() {
if node.field_name_for_child(i as u32) == Some("redirect")
&& let Some(child) = node.child(i as u32)
{
collect_substitutions_recursive(child, source, commands);
}
}
}
// comment: skip shell comments (e.g. `# description`)
"comment" => {}
// variable_assignment: transparent container — skip the assignment itself
// and recursively find command_substitution / process_substitution nodes
// anywhere in the subtree (they may be nested inside string nodes when
// the value is quoted, e.g. X="$(cmd)").
"variable_assignment" => {
collect_substitutions_recursive(node, source, commands);
}
// function_definition: recurse into body
"function_definition" => {
if let Some(body) = node.child_by_field_name("body") {
collect_commands(body, source, commands);
}
}
// command node: strip leading variable_assignment children
// (environment variable prefixes like `FOO=bar echo hello`), strip
// redirect children (herestring_redirect, etc. that tree-sitter
// attaches directly to a command node), extract nested
// command_substitution nodes, and emit the remaining text.
"command" => {
for i in 0..node.child_count() {
let Some(child) = node.child(i as u32) else {
continue;
};
if !child.is_named() {
continue;
}
if node.field_name_for_child(i as u32) == Some("redirect") {
// Recurse into redirect children for nested substitutions
// (e.g. `cat <<< $(secret_cmd)`)
collect_substitutions_recursive(child, source, commands);
} else {
match child.kind() {
"command_substitution" => {
collect_commands(child, source, commands);
}
"variable_assignment" => {
collect_substitutions_recursive(child, source, commands);
}
_ => {}
}
}
}
// Build command text excluding variable_assignment and redirect children.
// Redirects (e.g. herestring_redirect) attached directly to a command
// node use the field name "redirect".
let parts: Vec<&str> = (0..node.child_count())
.filter_map(|i| {
let child = node.child(i as u32)?;
if !child.is_named() {
return None;
}
if child.kind() == "variable_assignment" {
return None;
}
if node.field_name_for_child(i as u32) == Some("redirect") {
return None;
}
let text = &source[child.start_byte()..child.end_byte()];
std::str::from_utf8(text).ok()
})
.collect();
let text = parts.join(" ");
let text = text.trim();
if !text.is_empty() {
commands.push(text.to_string());
}
}
// 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());
}
}
}
}
/// Recursively walk a subtree to find `command_substitution` and
/// `process_substitution` nodes, then hand them off to `collect_commands`.
/// Used by `variable_assignment` to reach substitutions nested inside
/// `string` nodes (e.g. `X="$(cmd)"`).
fn collect_substitutions_recursive(
node: tree_sitter::Node,
source: &[u8],
commands: &mut Vec<String>,
) {
let mut cursor = node.walk();
for child in node.named_children(&mut cursor) {
match child.kind() {
"command_substitution" | "process_substitution" => {
collect_commands(child, source, commands);
}
_ => {
collect_substitutions_recursive(child, source, commands);
}
}
}
}
/// Join tokens into a shell-safe string by quoting tokens that contain
/// spaces or shell metacharacters. Tokens without special characters are
/// emitted verbatim.
///
/// Returns an error if any token contains a NUL byte (which cannot be
/// represented in shell syntax).
pub fn shell_quote_join(tokens: &[String]) -> Result<String, shlex::QuoteError> {
shlex::try_join(tokens.iter().map(|s| s.as_str()))
}
#[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();
// heredoc is a redirected_statement; only the body command is extracted
assert_eq!(result, vec!["cat"]);
}
// ========================================
// extract_commands: redirected statements
// ========================================
#[rstest]
#[case::stdout_to_file("echo hello > file.txt", vec!["echo hello"])]
#[case::append_to_file("echo hello >> file.txt", vec!["echo hello"])]
#[case::stdin_from_file("cat < input.txt", vec!["cat"])]
#[case::stderr_to_devnull("cmd 2> /dev/null", vec!["cmd"])]
#[case::stdout_and_stderr("cmd > out.txt 2>&1", vec!["cmd"])]
#[case::fd_redirect_only("echo hello 2>&1", vec!["echo hello"])]
#[case::devnull_redirect("curl url > /dev/null", vec!["curl url"])]
#[case::herestring("cat <<< hello", vec!["cat"])]
#[case::redirect_with_pipeline(
"echo hello 2>&1 | grep world",
vec!["echo hello", "grep world"],
)]
#[case::redirect_with_list(
"echo hello > file.txt && cat file.txt",
vec!["echo hello", "cat file.txt"],
)]
#[case::redirect_in_compound(
r#"X="test" && echo "$X" 2>&1"#,
vec![r#"echo "$X""#],
)]
#[case::process_substitution_in_redirect(
"cmd > >(nested_cmd)",
vec!["cmd", "nested_cmd"],
)]
#[case::command_substitution_in_redirect(
"cmd > $(echo /tmp/file)",
vec!["cmd", "echo /tmp/file"],
)]
#[case::command_substitution_in_herestring(
"cat <<< $(secret_cmd)",
vec!["secret_cmd", "cat"],
)]
fn extract_redirected_statements(#[case] input: &str, #[case] expected: Vec<&str>) {
let result = extract_commands(input).unwrap();
assert_eq!(result, expected);
}
// ========================================
// extract_commands: comments
// ========================================
#[rstest]
#[case::comment_before_command(
"# description\ngh api -X GET /repos",
vec!["gh api -X GET /repos"],
)]
#[case::comment_before_pipeline(
"# list agents\ngh api -X GET /repos | jq '.name'",
vec!["gh api -X GET /repos", "jq '.name'"],
)]
#[case::comment_only("# just a comment", vec![])]
#[case::inline_comment_after_semicolon(
"echo hello; # trailing comment",
vec!["echo hello"],
)]
fn extract_comments(#[case] input: &str, #[case] expected: Vec<&str>) {
let result = extract_commands(input).unwrap();
assert_eq!(result, expected);
}
// ========================================
// 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: variable assignments
// ========================================
#[rstest]
#[case::assignment_then_command("X=1 && echo hello", vec!["echo hello"])]
#[case::assignment_with_cmd_substitution("X=$(echo test)", vec!["echo test"])]
#[case::assignment_with_cmd_substitution_and_command(
"X=$(rm -rf /) && echo hello",
vec!["rm -rf /", "echo hello"]
)]
#[case::multiple_assignments("A=1 && B=2 && echo done", vec!["echo done"])]
#[case::assignment_with_backtick_substitution("X=`ls`", vec!["ls"])]
#[case::quoted_cmd_substitution(r#"X="$(echo test)""#, vec!["echo test"])]
#[case::quoted_backtick_substitution(r#"X="`ls`""#, vec!["ls"])]
#[case::process_substitution_in_assignment("X=<(cat file)", vec!["cat file"])]
fn extract_variable_assignments(#[case] input: &str, #[case] expected: Vec<&str>) {
let result = extract_commands(input).unwrap();
assert_eq!(result, expected);
}
#[test]
fn extract_bare_variable_assignment_returns_empty() {
// A bare variable assignment (no command substitution) produces no commands.
let result = extract_commands("X=1").unwrap();
assert!(result.is_empty());
}
// ========================================
// extract_commands: env-prefix commands (VAR=value cmd args)
// ========================================
#[rstest]
#[case::single_env_prefix("FOO=bar echo hello", vec!["echo hello"])]
#[case::multiple_env_prefixes("FOO=bar BAZ=qux echo hello", vec!["echo hello"])]
#[case::env_prefix_with_flags("FOO=bar curl -X POST https://example.com", vec!["curl -X POST https://example.com"])]
#[case::env_prefix_with_pipeline("FOO=bar echo hello | grep hello", vec!["echo hello", "grep hello"])]
#[case::env_prefix_with_cmd_substitution(
"FOO=$(echo bar) echo hello",
vec!["echo bar", "echo hello"]
)]
// `env FOO=bar echo hello`: tree-sitter treats `env` as the command name
// and `FOO=bar` as a regular argument (word node), not a variable_assignment.
// The entire text is preserved as a single command for wrapper evaluation.
#[case::env_cmd_with_var_arg(
"env FOO=bar echo hello",
vec!["env FOO=bar echo hello"]
)]
fn extract_env_prefix_commands(#[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
// ========================================