Repository navigation
Expand file tree
/
Copy pathlexer.rs
More file actions
1630 lines (1474 loc) · 51.2 KB
/
Copy pathlexer.rs
File metadata and controls
1630 lines (1474 loc) · 51.2 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
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PipeKind {
/// Standard stdout pipeline (`|`).
Stdout,
/// Combined stdout-and-stderr pipeline (`|&`).
StdoutAndStderr,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TokenKind {
Arg,
Operator,
Pipe(PipeKind),
Redirect,
Shellism,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedToken {
pub kind: TokenKind,
pub value: String,
pub offset: usize,
}
/// How `tokenize_inner` treats `\n`/`\r`.
#[derive(Clone, Copy, PartialEq, Eq)]
enum NewlineMode {
/// Ordinary characters, no Operator tokens.
None,
/// `\n`, and the `\r` of a CRLF pair, are Operator boundaries; a lone
/// `\r` stays glued to its word — real bash's behavior.
Bash,
/// Like `Bash`, but a lone `\r` is a boundary too. Only
/// `split_for_permissions` uses this, to stay maximally conservative.
Conservative,
}
pub fn tokenize(input: &str) -> Vec<ParsedToken> {
tokenize_inner(input, NewlineMode::None)
}
/// Like [`tokenize`] but emits a `\n` operator token for each newline that
/// sits outside quotes. Newlines inside quoted strings stay part of their
/// argument, so callers can use the emitted offsets as safe line-split points.
pub fn tokenize_with_newlines(input: &str) -> Vec<ParsedToken> {
tokenize_inner(input, NewlineMode::Bash)
}
/// Applies one character's effect on quote state, mirroring bash: only the
/// quote char that opened a span closes it. Shared by `tokenize_inner`,
/// `shell_split`, and `registry.rs::QuoteScan` so they can't drift.
pub(crate) fn advance_quote_state(quote: Option<char>, c: char) -> Option<char> {
match (quote, c) {
(None, '\'' | '"') => Some(c),
(Some(q), c) if c == q => None,
(q, _) => q,
}
}
/// Bash's default `$IFS` is exactly space/tab/newline — not Rust's
/// `char::is_whitespace()`, which wrongly includes non-IFS Unicode
/// whitespace like NBSP. Shared with `permissions.rs::command_matches_pattern`.
pub(crate) fn is_word_boundary_whitespace(c: char) -> bool {
matches!(c, ' ' | '\t' | '\n')
}
/// True if `bytes[i..]` starts a CRLF pair. Shared by `tokenize_inner` and
/// `registry.rs::rewrite_multiline_block`'s raw-newline parity check.
pub(crate) fn is_crlf_at(bytes: &[u8], i: usize) -> bool {
bytes.get(i) == Some(&b'\r') && bytes.get(i + 1) == Some(&b'\n')
}
/// Merges `tokenize()` tokens that are directly adjacent in `cmd` (no gap)
/// into single words — e.g. `*.yml` tokenizes as `Shellism("*")` +
/// `Arg(".yml")` but is one bash word. For callers that only need "was there
/// a space here", not full shell-operator awareness.
pub(crate) fn coalesce_words<'a>(cmd: &'a str, tokens: &[ParsedToken]) -> Vec<(&'a str, usize)> {
let mut words = Vec::new();
let mut run_start: Option<usize> = None;
let mut run_end: usize = 0;
for tok in tokens {
if let Some(start) = run_start
&& tok.offset != run_end
{
words.push((&cmd[start..run_end], start));
run_start = None;
}
if run_start.is_none() {
run_start = Some(tok.offset);
}
run_end = tok.offset + tok.value.len();
}
if let Some(start) = run_start {
words.push((&cmd[start..run_end], start));
}
words
}
fn tokenize_inner(input: &str, newline_mode: NewlineMode) -> Vec<ParsedToken> {
let mut tokens = Vec::new();
let mut current = String::new();
let mut current_start: usize = 0;
let mut byte_pos: usize = 0;
let mut chars = input.chars().peekable();
let mut quote: Option<char> = None;
let mut escaped = false;
while let Some(c) = chars.next() {
let char_len = c.len_utf8();
if escaped {
current.push('\\');
current.push(c);
byte_pos += char_len;
escaped = false;
continue;
}
if c == '\\' && quote != Some('\'') {
escaped = true;
if current.is_empty() {
current_start = byte_pos;
}
byte_pos += char_len;
continue;
}
if quote.is_some() || c == '\'' || c == '"' {
if quote.is_none() && current.is_empty() {
current_start = byte_pos;
}
quote = advance_quote_state(quote, c);
current.push(c);
byte_pos += char_len;
continue;
}
match c {
'$' => {
flush_arg(&mut tokens, &mut current, current_start);
let start = byte_pos;
byte_pos += char_len;
if chars
.peek()
.is_some_and(|&nc| nc.is_ascii_alphabetic() || nc == '_')
{
let mut name = String::from("$");
while let Some(&nc) = chars.peek() {
if !nc.is_ascii_alphanumeric() && nc != '_' {
break;
}
chars.next();
byte_pos += nc.len_utf8();
name.push(nc);
}
tokens.push(ParsedToken {
kind: TokenKind::Arg,
value: name,
offset: start,
});
} else {
tokens.push(ParsedToken {
kind: TokenKind::Shellism,
value: "$".into(),
offset: start,
});
}
current_start = byte_pos;
}
'*' | '?' | '`' | '(' | ')' | '{' | '}' | '!' => {
flush_arg(&mut tokens, &mut current, current_start);
tokens.push(ParsedToken {
kind: TokenKind::Shellism,
value: c.to_string(),
offset: byte_pos,
});
byte_pos += char_len;
current_start = byte_pos;
}
'|' => {
flush_arg(&mut tokens, &mut current, current_start);
let start = byte_pos;
byte_pos += char_len;
if chars.peek() == Some(&'|') {
chars.next();
byte_pos += 1;
tokens.push(ParsedToken {
kind: TokenKind::Operator,
value: "||".into(),
offset: start,
});
} else if chars.peek() == Some(&'&') {
chars.next();
byte_pos += 1;
tokens.push(ParsedToken {
kind: TokenKind::Pipe(PipeKind::StdoutAndStderr),
value: "|&".into(),
offset: start,
});
} else {
tokens.push(ParsedToken {
kind: TokenKind::Pipe(PipeKind::Stdout),
value: "|".into(),
offset: start,
});
}
current_start = byte_pos;
}
';' => {
flush_arg(&mut tokens, &mut current, current_start);
tokens.push(ParsedToken {
kind: TokenKind::Operator,
value: ";".into(),
offset: byte_pos,
});
byte_pos += char_len;
current_start = byte_pos;
}
'&' => {
flush_arg(&mut tokens, &mut current, current_start);
let start = byte_pos;
byte_pos += char_len;
if chars.peek() == Some(&'&') {
chars.next();
byte_pos += 1;
tokens.push(ParsedToken {
kind: TokenKind::Operator,
value: "&&".into(),
offset: start,
});
} else if chars.peek() == Some(&'>') {
chars.next();
byte_pos += 1;
let mut val = String::from("&>");
if chars.peek() == Some(&'>') {
chars.next();
byte_pos += 1;
val.push('>');
}
tokens.push(ParsedToken {
kind: TokenKind::Redirect,
value: val,
offset: start,
});
} else {
tokens.push(ParsedToken {
kind: TokenKind::Shellism,
value: "&".into(),
offset: start,
});
}
current_start = byte_pos;
}
'>' => {
let fd_prefix =
if !current.is_empty() && current.chars().all(|ch| ch.is_ascii_digit()) {
Some(std::mem::take(&mut current))
} else {
flush_arg(&mut tokens, &mut current, current_start);
None
};
let redir_start = if fd_prefix.is_some() {
current_start
} else {
byte_pos
};
let mut val = fd_prefix.unwrap_or_default();
val.push('>');
byte_pos += char_len;
if chars.peek() == Some(&'>') {
chars.next();
byte_pos += 1;
val.push('>');
}
if chars.peek() == Some(&'&') {
chars.next();
byte_pos += 1;
val.push('&');
while let Some(&nc) = chars.peek() {
if !nc.is_ascii_digit() && nc != '-' {
break;
}
chars.next();
val.push(nc);
byte_pos += nc.len_utf8();
}
}
tokens.push(ParsedToken {
kind: TokenKind::Redirect,
value: val,
offset: redir_start,
});
current_start = byte_pos;
}
'<' => {
flush_arg(&mut tokens, &mut current, current_start);
let start = byte_pos;
let mut val = String::from("<");
byte_pos += char_len;
if chars.peek() == Some(&'<') {
chars.next();
byte_pos += 1;
val.push('<');
}
tokens.push(ParsedToken {
kind: TokenKind::Redirect,
value: val,
offset: start,
});
current_start = byte_pos;
}
c @ ('\n' | '\r')
if newline_mode != NewlineMode::None
&& (c == '\n'
|| newline_mode == NewlineMode::Conservative
|| is_crlf_at(input.as_bytes(), byte_pos)) =>
{
flush_arg(&mut tokens, &mut current, current_start);
tokens.push(ParsedToken {
kind: TokenKind::Operator,
value: "\n".into(),
offset: byte_pos,
});
byte_pos += char_len;
current_start = byte_pos;
}
c if is_word_boundary_whitespace(c) => {
flush_arg(&mut tokens, &mut current, current_start);
byte_pos += c.len_utf8();
current_start = byte_pos;
}
_ => {
if current.is_empty() {
current_start = byte_pos;
}
current.push(c);
byte_pos += char_len;
}
}
}
if escaped {
current.push('\\');
}
flush_arg(&mut tokens, &mut current, current_start);
tokens
}
fn flush_arg(tokens: &mut Vec<ParsedToken>, current: &mut String, offset: usize) {
if !current.is_empty() {
tokens.push(ParsedToken {
kind: TokenKind::Arg,
value: std::mem::take(current),
offset,
});
}
}
/// True for constructs the permission gate can't decompose, so they must never
/// be auto-allowed: command/process substitution, or a real file-target redirect
/// (fd-dup like `2>&1` and `/dev/null` are exempt). Separators and subshells are
/// handled by [`split_for_permissions`], not flagged here.
pub fn contains_unattestable_construct(cmd: &str) -> bool {
if contains_substitution(cmd) {
return true;
}
let tokens = tokenize(cmd);
tokens
.iter()
.enumerate()
.any(|(i, tok)| tok.kind == TokenKind::Redirect && redirect_has_file_target(&tokens, i))
}
/// Quote-aware: bash runs backtick/`$(...)` unquoted and inside double quotes,
/// but treats single-quoted text literally; `<(`/`>(` is unquoted-only.
fn contains_substitution(cmd: &str) -> bool {
let bytes = cmd.as_bytes();
let mut in_single = false;
let mut in_double = false;
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'\\' if !in_single => {
i += 2;
continue;
}
b'\'' if !in_double => in_single = !in_single,
b'"' if !in_single => in_double = !in_double,
b'`' if !in_single => return true,
b'$' if !in_single && bytes.get(i + 1) == Some(&b'(') => return true,
b'<' | b'>' if !in_single && !in_double && bytes.get(i + 1) == Some(&b'(') => {
return true;
}
_ => {}
}
i += 1;
}
false
}
// `>&N`/`>&-` (and `N>&M`) is fd-dup/close; bare `>&` before a word is
// `>word 2>&1` — a file target.
pub(crate) fn redirect_has_file_target(tokens: &[ParsedToken], i: usize) -> bool {
let value = &tokens[i].value;
if let Some(pos) = value.find(">&") {
let tail = &value[pos + 2..];
if !tail.is_empty() && tail.chars().all(|c| c.is_ascii_digit() || c == '-') {
return false;
}
}
match tokens.get(i + 1) {
Some(next) if next.kind == TokenKind::Arg => next.value != "/dev/null",
_ => true,
}
}
/// Segments `cmd` for the **permission gate** (`permissions.rs::check_command_with_rules`):
/// every segment this returns is independently checked against deny/ask/allow
/// rules, so this is deliberately the most paranoid of the three compound-command
/// segmenters in this codebase — see [`split_on_operators`] (analytics/discovery
/// classification) and `registry.rs::rewrite_compound`'s inline token walk (actual
/// rewrite) for the other two, which intentionally segment the same kind of input
/// differently:
///
/// | | here (permission gate) | [`split_on_operators`] (analytics) | `rewrite_compound` (rewrite) |
/// |---|---|---|---|
/// | `&&` / `\|\|` / `;` | splits | splits | splits |
/// | `\|` | always splits | stops at first `\|` | pipeline handled specially |
/// | background `&` | splits (Shellism boundary) | does not split | splits |
/// | `( ... )` grouping | splits (Shellism boundary) | does not split | does not split standalone |
/// | trailing redirect | truncates the segment | kept | kept (rewritten output preserves it) |
/// | lone `\r` (no following `\n`) | splits | does not split | does not split |
///
/// Like [`split_on_operators`] but also breaks on newline, background `&`,
/// subshell `( ... )`, and a lone `\r` (`NewlineMode::Conservative`), and
/// truncates each segment at its first redirect — deliberately conservative
/// so a hidden command can't evade the gate by hiding behind a construct
/// another segmenter would leave intact.
/// Callers must still gate on [`contains_unattestable_construct`] first.
pub fn split_for_permissions(cmd: &str) -> Vec<&str> {
let trimmed = cmd.trim();
if trimmed.is_empty() {
return vec![];
}
let tokens = tokenize_inner(trimmed, NewlineMode::Conservative);
let mut results = Vec::new();
let mut seg_start: usize = 0;
let mut seg_end: Option<usize> = None;
for tok in &tokens {
let is_boundary = match tok.kind {
TokenKind::Operator | TokenKind::Pipe(_) => true,
TokenKind::Shellism => matches!(tok.value.as_str(), "&" | "(" | ")"),
_ => false,
};
if is_boundary {
let end = seg_end.take().unwrap_or(tok.offset);
let segment = trimmed[seg_start..end].trim();
if !segment.is_empty() {
results.push(segment);
}
seg_start = tok.offset + tok.value.len();
} else if tok.kind == TokenKind::Redirect && seg_end.is_none() {
seg_end = Some(tok.offset);
}
}
let end = seg_end.unwrap_or(trimmed.len());
let tail = trimmed[seg_start..end].trim();
if !tail.is_empty() {
results.push(tail);
}
results
}
/// Split a shell command on operators (`&&`, `||`, `;`) and optionally pipes
/// (`|`), quote-aware. `stop_at_pipe: true` returns only segments before the
/// first `|` (rewrite's left-side-only case); `false` splits through pipes
/// too (permission checking, every segment validated).
///
/// For classification only — unlike [`split_for_permissions`] this never
/// splits on background `&`/`( ... )` or truncates at a redirect (see that
/// function's comparison table), so it must not be repurposed for
/// permission/security decisions.
pub fn split_on_operators(cmd: &str, stop_at_pipe: bool) -> Vec<&str> {
let trimmed = cmd.trim();
if trimmed.is_empty() {
return vec![];
}
let tokens = tokenize(trimmed);
let mut results = Vec::new();
let mut seg_start: usize = 0;
for tok in &tokens {
match tok.kind {
TokenKind::Operator => {
let segment = trimmed[seg_start..tok.offset].trim();
if !segment.is_empty() {
results.push(segment);
}
seg_start = tok.offset + tok.value.len();
}
TokenKind::Pipe(_) => {
let segment = trimmed[seg_start..tok.offset].trim();
if !segment.is_empty() {
results.push(segment);
}
if stop_at_pipe {
return results;
}
seg_start = tok.offset + tok.value.len();
}
_ => {}
}
}
let tail = trimmed[seg_start..].trim();
if !tail.is_empty() {
results.push(tail);
}
results
}
#[cfg(test)]
pub fn strip_quotes(s: &str) -> String {
let chars: Vec<char> = s.chars().collect();
if chars.len() >= 2
&& ((chars[0] == '"' && chars[chars.len() - 1] == '"')
|| (chars[0] == '\'' && chars[chars.len() - 1] == '\''))
{
return chars[1..chars.len() - 1].iter().collect();
}
s.to_string()
}
/// Turns a coalesced word's raw text (quotes/escapes still literal, as
/// `tokenize()` preserves them) into argv-ready text: quote chars that
/// open/close a span are stripped, backslash escapes resolved.
fn resolve_word_text(raw: &str) -> String {
let mut result = String::new();
let mut chars = raw.chars().peekable();
let mut quote: Option<char> = None;
while let Some(c) = chars.next() {
match c {
// Inside double quotes bash only lets `\` escape `$`, `` ` ``, `"`,
// `\` or a newline; before anything else it is a literal character.
// That is what keeps a quoted Windows path (`"C:\Program Files"`)
// intact instead of eating its separators.
'\\' if quote == Some('"') => match chars.peek() {
Some('$' | '`' | '"' | '\\' | '\n') => {
if let Some(next) = chars.next() {
result.push(next);
}
}
_ => result.push('\\'),
},
'\\' if quote.is_none() => {
if let Some(next) = chars.next() {
result.push(next);
}
}
'\'' | '"' => {
// advance_quote_state leaves `quote` unchanged when `c` is the
// "wrong" quote char for the current span (e.g. a `'` while
// inside `"..."`) — that's literal text, not a toggle.
let new_quote = advance_quote_state(quote, c);
if new_quote == quote {
result.push(c);
} else {
quote = new_quote;
}
}
_ => result.push(c),
}
}
result
}
/// Quote-aware split of a single shell command into argv-ready words: quotes
/// stripped, backslash escapes resolved — for callers that hand the result
/// straight to `Command::new`/exec or compare it against literal words
/// (`hooks/mod.rs::is_claude_hook_command`, `rtk proxy` arg-splitting).
pub fn shell_split(input: &str) -> Vec<String> {
coalesce_words(input, &tokenize(input))
.into_iter()
.map(|(raw, _)| resolve_word_text(raw))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_coalesce_words_merges_adjacent_tokens() {
let cmd = "golangci-lint --config *.yml run";
let words: Vec<&str> = coalesce_words(cmd, &tokenize(cmd))
.into_iter()
.map(|(w, _)| w)
.collect();
assert_eq!(words, vec!["golangci-lint", "--config", "*.yml", "run"]);
}
#[test]
fn test_coalesce_words_preserves_offsets() {
let cmd = "a *.yml b";
let words = coalesce_words(cmd, &tokenize(cmd));
assert_eq!(words, vec![("a", 0), ("*.yml", 2), ("b", 8)]);
}
#[test]
fn test_simple_command() {
let tokens = tokenize("git status");
assert_eq!(tokens.len(), 2);
assert_eq!(tokens[0].kind, TokenKind::Arg);
assert_eq!(tokens[0].value, "git");
assert_eq!(tokens[1].value, "status");
}
#[test]
fn test_command_with_args() {
let tokens = tokenize("git commit -m message");
assert_eq!(tokens.len(), 4);
assert_eq!(tokens[0].value, "git");
assert_eq!(tokens[1].value, "commit");
assert_eq!(tokens[2].value, "-m");
assert_eq!(tokens[3].value, "message");
}
#[test]
fn test_quoted_operator_not_split() {
let tokens = tokenize(r#"git commit -m "Fix && Bug""#);
assert!(
!tokens
.iter()
.any(|t| matches!(t.kind, TokenKind::Operator) && t.value == "&&")
);
assert!(tokens.iter().any(|t| t.value.contains("Fix && Bug")));
}
#[test]
fn test_single_quoted_string() {
let tokens = tokenize("echo 'hello world'");
assert!(tokens.iter().any(|t| t.value == "'hello world'"));
}
#[test]
fn test_double_quoted_string() {
let tokens = tokenize(r#"echo "hello world""#);
assert!(tokens.iter().any(|t| t.value == "\"hello world\""));
}
#[test]
fn test_empty_quoted_string() {
let tokens = tokenize("echo \"\"");
assert!(tokens.iter().any(|t| t.value == "\"\""));
}
#[test]
fn test_nested_quotes() {
let tokens = tokenize(r#"echo "outer 'inner' outer""#);
assert!(tokens.iter().any(|t| t.value.contains("'inner'")));
}
#[test]
fn test_escaped_space() {
let tokens = tokenize("echo hello\\ world");
assert!(tokens.iter().any(|t| t.value.contains("hello")));
}
#[test]
fn test_backslash_in_single_quotes() {
let tokens = tokenize(r#"echo 'hello\nworld'"#);
assert!(tokens.iter().any(|t| t.value.contains(r"\n")));
}
#[test]
fn test_escaped_quote_in_double() {
let tokens = tokenize(r#"echo "hello\"world""#);
assert!(tokens.iter().any(|t| t.value.contains("hello")));
}
#[test]
fn test_empty_input() {
assert!(tokenize("").is_empty());
}
#[test]
fn test_whitespace_only() {
assert!(tokenize(" ").is_empty());
}
#[test]
fn test_unclosed_single_quote() {
let tokens = tokenize("'unclosed");
assert!(!tokens.is_empty());
}
#[test]
fn test_unclosed_double_quote() {
let tokens = tokenize("\"unclosed");
assert!(!tokens.is_empty());
}
#[test]
fn test_unicode_preservation() {
let tokens = tokenize("echo \"héllo wörld\"");
assert!(tokens.iter().any(|t| t.value.contains("héllo")));
}
#[test]
fn test_multiple_spaces() {
let tokens = tokenize("git status");
assert_eq!(tokens.len(), 2);
}
#[test]
fn test_leading_trailing_spaces() {
let tokens = tokenize(" git status ");
assert_eq!(tokens.len(), 2);
}
#[test]
fn test_and_operator() {
let tokens = tokenize("cmd1 && cmd2");
assert!(
tokens
.iter()
.any(|t| t.kind == TokenKind::Operator && t.value == "&&")
);
}
#[test]
fn test_or_operator() {
let tokens = tokenize("cmd1 || cmd2");
assert!(
tokens
.iter()
.any(|t| t.kind == TokenKind::Operator && t.value == "||")
);
}
#[test]
fn test_semicolon() {
let tokens = tokenize("cmd1 ; cmd2");
assert!(
tokens
.iter()
.any(|t| t.kind == TokenKind::Operator && t.value == ";")
);
}
#[test]
fn test_multiple_and() {
let tokens = tokenize("a && b && c");
let ops: Vec<_> = tokens
.iter()
.filter(|t| t.kind == TokenKind::Operator)
.collect();
assert_eq!(ops.len(), 2);
}
#[test]
fn test_mixed_operators() {
let tokens = tokenize("a && b || c");
let ops: Vec<_> = tokens
.iter()
.filter(|t| t.kind == TokenKind::Operator)
.collect();
assert_eq!(ops.len(), 2);
}
#[test]
fn test_operator_at_start() {
let tokens = tokenize("&& cmd");
assert!(tokens.iter().any(|t| t.value == "&&"));
}
#[test]
fn test_operator_at_end() {
let tokens = tokenize("cmd &&");
assert!(tokens.iter().any(|t| t.value == "&&"));
}
#[test]
fn test_pipe_detection() {
let tokens = tokenize("cat file | grep pattern");
assert!(
tokens
.iter()
.any(|t| t.kind == TokenKind::Pipe(PipeKind::Stdout))
);
}
#[test]
fn test_stderr_pipe_is_atomic() {
let tokens = tokenize("cargo test |& grep FAILED");
let pipes: Vec<_> = tokens
.iter()
.filter(|token| matches!(token.kind, TokenKind::Pipe(_)))
.collect();
assert_eq!(pipes.len(), 1);
assert_eq!(pipes[0].kind, TokenKind::Pipe(PipeKind::StdoutAndStderr));
assert_eq!(pipes[0].value, "|&");
assert!(
!tokens
.iter()
.any(|token| token.kind == TokenKind::Shellism && token.value == "&")
);
assert_eq!(
split_for_permissions("cargo test |& grep FAILED"),
vec!["cargo test", "grep FAILED"]
);
}
#[test]
fn test_quoted_pipe_not_pipe() {
let tokens = tokenize("\"a|b\"");
assert!(!tokens.iter().any(|t| matches!(t.kind, TokenKind::Pipe(_))));
}
#[test]
fn test_multiple_pipes() {
let tokens = tokenize("a | b | c");
let pipes: Vec<_> = tokens
.iter()
.filter(|t| matches!(t.kind, TokenKind::Pipe(_)))
.collect();
assert_eq!(pipes.len(), 2);
}
#[test]
fn test_glob_detection() {
let tokens = tokenize("ls *.rs");
assert!(tokens.iter().any(|t| t.kind == TokenKind::Shellism));
}
#[test]
fn test_quoted_glob_not_shellism() {
let tokens = tokenize("echo \"*.txt\"");
assert!(!tokens.iter().any(|t| t.kind == TokenKind::Shellism));
}
#[test]
fn test_simple_var_is_arg() {
let tokens = tokenize("echo $HOME");
assert!(
tokens
.iter()
.any(|t| t.kind == TokenKind::Arg && t.value == "$HOME"),
"Simple $VAR must be Arg — shell expands at execution time"
);
assert!(
!tokens.iter().any(|t| t.kind == TokenKind::Shellism),
"No Shellism expected for simple $VAR"
);
}
#[test]
fn test_simple_var_enables_native_routing() {
let tokens = tokenize("git log $BRANCH");
assert!(
!tokens.iter().any(|t| t.kind == TokenKind::Shellism),
"git log $BRANCH must have no Shellism"
);
}
#[test]
fn test_dollar_subshell_stays_shellism() {
let tokens = tokenize("echo $(date)");
assert!(tokens.iter().any(|t| t.kind == TokenKind::Shellism));
}
#[test]
fn test_dollar_brace_stays_shellism() {
let tokens = tokenize("echo ${HOME}");
assert!(tokens.iter().any(|t| t.kind == TokenKind::Shellism));
}
#[test]
fn test_dollar_special_vars_stay_shellism() {
for s in &["echo $?", "echo $$", "echo $!"] {
let tokens = tokenize(s);
assert!(
tokens.iter().any(|t| t.kind == TokenKind::Shellism),
"{} should produce Shellism",
s
);
}
}
#[test]
fn test_dollar_digit_stays_shellism() {
let tokens = tokenize("echo $1");
assert!(tokens.iter().any(|t| t.kind == TokenKind::Shellism));
}
#[test]
fn test_quoted_variable_not_shellism() {
let tokens = tokenize("echo \"$HOME\"");
assert!(!tokens.iter().any(|t| t.kind == TokenKind::Shellism));
}
#[test]
fn test_backtick_substitution() {
let tokens = tokenize("echo `date`");
assert!(tokens.iter().any(|t| t.kind == TokenKind::Shellism));
}
#[test]
fn test_subshell_detection() {
let tokens = tokenize("echo $(date)");
let shellisms: Vec<_> = tokens
.iter()
.filter(|t| t.kind == TokenKind::Shellism)
.collect();
assert!(!shellisms.is_empty());
}
#[test]
fn test_brace_expansion() {
let tokens = tokenize("echo {a,b}.txt");
assert!(tokens.iter().any(|t| t.kind == TokenKind::Shellism));
}
#[test]
fn test_escaped_glob() {
let tokens = tokenize("echo \\*.txt");
assert!(
!tokens
.iter()
.any(|t| t.kind == TokenKind::Shellism && t.value == "*")
);
}
#[test]
fn test_redirect_out() {
let tokens = tokenize("cmd > file");
assert!(tokens.iter().any(|t| t.kind == TokenKind::Redirect));
}
#[test]
fn test_redirect_append() {
let tokens = tokenize("cmd >> file");
assert!(
tokens
.iter()
.any(|t| t.kind == TokenKind::Redirect && t.value == ">>")
);
}
#[test]
fn test_redirect_in() {
let tokens = tokenize("cmd < file");
assert!(tokens.iter().any(|t| t.kind == TokenKind::Redirect));
}
#[test]
fn test_redirect_stderr() {
let tokens = tokenize("cmd 2> file");
assert!(
tokens
.iter()
.any(|t| t.kind == TokenKind::Redirect && t.value.starts_with("2>"))
);
}
#[test]
fn test_redirect_stderr_no_space() {
let tokens = tokenize("cmd 2>/dev/null");
assert!(
tokens
.iter()
.any(|t| t.kind == TokenKind::Redirect && t.value == "2>")
);
assert!(
tokens
.iter()
.any(|t| t.kind == TokenKind::Arg && t.value == "/dev/null")
);
}
#[test]
fn test_redirect_dev_null() {
let tokens = tokenize("cmd > /dev/null");
assert!(
tokens
.iter()
.any(|t| t.kind == TokenKind::Redirect && t.value == ">")
);
}