lean_ctx/core/shell_allowlist/tokenizer.rs
1/// Tokenize a shell command segment respecting single/double quotes and backslash escapes.
2/// Returns tokens with outer quotes stripped, matching how the shell would parse them.
3/// E.g. `git -C "Program Files" status` → `["git", "-C", "Program Files", "status"]`
4pub fn shell_tokenize(input: &str) -> Vec<String> {
5 let mut tokens = Vec::new();
6 let mut current = String::new();
7 let mut chars = input.chars().peekable();
8 let mut in_single = false;
9 let mut in_double = false;
10 let mut parameter_depth: u32 = 0;
11
12 while let Some(c) = chars.next() {
13 match c {
14 '\'' if !in_double => in_single = !in_single,
15 '"' if !in_single => in_double = !in_double,
16 '\\' if !in_single => {
17 // #1781: inside double quotes a backslash is literal unless it
18 // precedes `$`, `` ` ``, `"`, `\` or a newline (POSIX 2.2.3).
19 // The old arm consumed it unconditionally, so a quoted Windows
20 // path — `Start-Process "C:\Program Files\Docker\Docker Desktop.exe"`
21 // — tokenized as `C:Program FilesDockerDocker Desktop.exe`, and
22 // the allowlist then refused a fragment that was never a command
23 // and asked the user to report it. Outside quotes the escape
24 // still applies to any character, which `tokenize_backslash_escape`
25 // pins.
26 let escapes_next =
27 !in_double || matches!(chars.peek(), Some('$' | '`' | '"' | '\\' | '\n'));
28 if escapes_next {
29 if let Some(next) = chars.next() {
30 current.push(next);
31 }
32 } else {
33 current.push('\\');
34 }
35 }
36 '$' if !in_single && chars.peek() == Some(&'{') => {
37 parameter_depth += 1;
38 current.push(c);
39 }
40 '}' if !in_single && parameter_depth > 0 => {
41 parameter_depth -= 1;
42 current.push(c);
43 }
44 c if c.is_whitespace() && !in_single && !in_double && parameter_depth == 0 => {
45 if !current.is_empty() {
46 tokens.push(std::mem::take(&mut current));
47 }
48 }
49 _ => current.push(c),
50 }
51 }
52 if !current.is_empty() {
53 tokens.push(current);
54 }
55 tokens
56}
57
58/// Returns the byte length of the first shell token in `input`, respecting quotes
59/// and `(...)` nesting. Used by `skip_env_assignments` to advance past env
60/// assignments with quoted values like `FOO="bar baz"` — and, critically, past
61/// assignments whose value is a command substitution like `FOO=$(cmd a b)`
62/// (#855): without paren-depth tracking, whitespace *inside* the unclosed
63/// `$(...)` looked like the end of the token, splitting `s=$(gh pr view …)`
64/// into a bogus token `s=$(gh` plus a leftover `pr` that got misread as the
65/// base command.
66pub(super) fn quote_aware_token_end(input: &str) -> usize {
67 let bytes = input.as_bytes();
68 let len = bytes.len();
69 let mut i = 0;
70 let mut in_single = false;
71 let mut in_double = false;
72 let mut paren_depth: u32 = 0;
73 let mut parameter_depth: u32 = 0;
74
75 while i < len {
76 let ch = bytes[i];
77 match ch {
78 b'\'' if !in_double => {
79 in_single = !in_single;
80 i += 1;
81 }
82 b'"' if !in_single => {
83 in_double = !in_double;
84 i += 1;
85 }
86 b'\\' if !in_single => {
87 i = (i + 2).min(len);
88 }
89 b'(' if !in_single && !in_double => {
90 paren_depth += 1;
91 i += 1;
92 }
93 b')' if !in_single && !in_double && paren_depth > 0 => {
94 paren_depth -= 1;
95 i += 1;
96 }
97 b'$' if !in_single && !in_double && bytes.get(i + 1) == Some(&b'{') => {
98 parameter_depth += 1;
99 i += 1;
100 }
101 b'}' if !in_single && parameter_depth > 0 => {
102 parameter_depth -= 1;
103 i += 1;
104 }
105 b if b.is_ascii_whitespace()
106 && !in_single
107 && !in_double
108 && paren_depth == 0
109 && parameter_depth == 0 =>
110 {
111 return i;
112 }
113 _ => i += 1,
114 }
115 }
116 len
117}
118/// Extract ALL command segments from a compound shell command.
119/// Splits on: &&, ||, ;, | (pipe), and handles subshell grouping.
120pub(super) fn extract_all_commands(command: &str) -> Vec<String> {
121 split_on_operators(command)
122 .into_iter()
123 .map(|s| s.trim().to_string())
124 .filter(|s| !s.is_empty())
125 .collect()
126}
127
128/// One lexical context.
129///
130/// A command substitution starts a **fresh** one. POSIX says quoting restarts
131/// inside `$( … )`, so in `echo "$(python3 -c "a;b")"` the inner `"…"` is its
132/// own string and its `;` separates nothing (GH #1646). Tracking quotes as two
133/// flat booleans could not express that: the scanner never noticed `$(` while
134/// inside double quotes, so the inner opening quote *closed* the outer one,
135/// `a;b` looked unquoted, and the `;` split a bogus command out of a Python
136/// source line — which the allowlist then rejected with an unusable suggestion.
137///
138/// Treating the substitution as one word here loses no enforcement: its real
139/// contents are re-split and checked by `substitution::extract_substitution_commands`,
140/// which is where commands that a substitution genuinely *runs* are caught.
141#[derive(Clone, Copy)]
142struct Frame {
143 in_single_quote: bool,
144 in_double_quote: bool,
145 paren_depth: u32,
146 /// #939: brace groups (`{ cmd; }`) need the same operator-shielding as
147 /// `( cmd )` subshells — otherwise a `}` that closes a `{` opened on an
148 /// earlier physical line (e.g. after heredoc-body stripping collapses the
149 /// body between them) is misread as its own bare command segment.
150 brace_depth: u32,
151 /// #1793: `[[ … ]]` is a bash conditional *construct*, not a command, and
152 /// the `&&`/`||` inside it join predicates rather than commands. Without
153 /// shielding, `[[ -x a && -x b ]]` was split mid-condition into fragments
154 /// like `[[ -x a` and `-x b ]]`, none of which resolve to a real command.
155 bracket_depth: u32,
156 kind: FrameKind,
157}
158
159#[derive(Clone, Copy, PartialEq, Eq)]
160enum FrameKind {
161 /// The command line itself. Separators split only at this level.
162 Base,
163 /// Opened by `$(`, closed by the matching `)`.
164 DollarParen,
165 /// Opened and closed by a backtick — the older substitution form, same
166 /// quoting-restart rule.
167 Backtick,
168}
169
170impl Frame {
171 const fn new(kind: FrameKind) -> Self {
172 Self {
173 in_single_quote: false,
174 in_double_quote: false,
175 paren_depth: 0,
176 brace_depth: 0,
177 bracket_depth: 0,
178 kind,
179 }
180 }
181
182 /// Inside quotes, or inside a group whose closing delimiter is still open.
183 const fn shields_operators(&self) -> bool {
184 self.in_single_quote
185 || self.in_double_quote
186 || self.paren_depth > 0
187 || self.brace_depth > 0
188 || self.bracket_depth > 0
189 }
190}
191
192/// True when the two bytes at `i` form a standalone `[[` token — the opener of
193/// a bash conditional (#1793).
194///
195/// Bash requires `[[` to be its own word, and so does this: a word boundary
196/// before and whitespace after. That distinction is what keeps a glob character
197/// class (`ls a[[:alpha:]]`) or a nested array subscript (`${arr[[i]]}`) from
198/// opening a depth that would never close and swallow the rest of the line.
199fn opens_double_bracket(bytes: &[u8], i: usize) -> bool {
200 if bytes.get(i) != Some(&b'[') || bytes.get(i + 1) != Some(&b'[') {
201 return false;
202 }
203 let boundary_before = i == 0
204 || matches!(
205 bytes[i - 1],
206 b' ' | b'\t' | b'\n' | b'\r' | b';' | b'&' | b'|' | b'('
207 );
208 let space_after = matches!(bytes.get(i + 2), Some(b' ' | b'\t' | b'\n' | b'\r'));
209 boundary_before && space_after
210}
211
212/// True when the two bytes at `i` form a standalone `]]` token closing a
213/// conditional opened by [`opens_double_bracket`]. Mirrors its word-boundary
214/// rule: whitespace before, and a separator or end of input after.
215fn closes_double_bracket(bytes: &[u8], i: usize) -> bool {
216 if bytes.get(i) != Some(&b']') || bytes.get(i + 1) != Some(&b']') {
217 return false;
218 }
219 let space_before = i > 0 && matches!(bytes[i - 1], b' ' | b'\t' | b'\n' | b'\r');
220 let separator_after = matches!(
221 bytes.get(i + 2),
222 None | Some(b' ' | b'\t' | b'\n' | b'\r' | b';' | b'&' | b'|' | b')')
223 );
224 space_before && separator_after
225}
226
227/// Split command string on shell operators: ;, &&, ||, |
228/// Respects single/double quotes, parentheses nesting, and backslash escapes
229/// outside single quotes (GL #1160): `rg split\.label\|quantityLabel` is ONE
230/// command — the escaped pipe is regex data, not an operator. The old scanner
231/// split there and blocked the pattern fragment as an unknown command; same
232/// for `find … -exec rm {} \;`.
233pub(super) fn split_on_operators(command: &str) -> Vec<&str> {
234 split_with_separators(command)
235 .into_iter()
236 .map(|(segment, _)| segment)
237 .collect()
238}
239
240/// The operator that ends a command segment.
241///
242/// Where a segment runs can depend on it (#1850): a `cd` followed by `&&`
243/// moves the next command, one followed by `||` only runs the next command if
244/// it failed, and one in a pipeline or in the background moves nothing at all.
245#[derive(Debug, Clone, Copy, PartialEq, Eq)]
246pub enum Separator {
247 /// `;`, a newline or a carriage return.
248 Sequence,
249 /// `&&`
250 And,
251 /// `||`
252 Or,
253 /// `|`
254 Pipe,
255 /// A single `&`.
256 Background,
257}
258
259/// Every segment together with the separator that ends it; the last segment
260/// has none. Same scanner as `split_on_operators`, so the two never disagree
261/// about where a command ends.
262pub fn segments_with_separators(command: &str) -> Vec<(String, Option<Separator>)> {
263 split_with_separators(command)
264 .into_iter()
265 .map(|(segment, sep)| (segment.trim().to_string(), sep))
266 .filter(|(segment, _)| !segment.is_empty())
267 .collect()
268}
269
270fn split_with_separators(command: &str) -> Vec<(&str, Option<Separator>)> {
271 let mut segments = Vec::new();
272 let mut start = 0;
273 let bytes = command.as_bytes();
274 let len = bytes.len();
275 let mut i = 0;
276 // Stack, not booleans: see [`Frame`]. Index 0 is always the command line.
277 let mut stack: Vec<Frame> = vec![Frame::new(FrameKind::Base)];
278
279 while i < len {
280 let ch = bytes[i];
281 // `$(` and a backtick open a substitution wherever the shell would
282 // expand one: unquoted, or inside double quotes. Single quotes inhibit
283 // it entirely, which the single-quote arm below handles by consuming
284 // everything to the closing quote.
285 let opens_substitution = |i: usize| -> Option<(FrameKind, usize)> {
286 match bytes[i] {
287 b'$' if i + 1 < len && bytes[i + 1] == b'(' => Some((FrameKind::DollarParen, 2)),
288 b'`' => Some((FrameKind::Backtick, 1)),
289 _ => None,
290 }
291 };
292
293 let frame = *stack.last().expect("base frame is never popped");
294
295 if frame.in_single_quote {
296 if ch == b'\'' {
297 stack.last_mut().expect("frame").in_single_quote = false;
298 }
299 i += 1;
300 continue;
301 }
302
303 if frame.in_double_quote {
304 match ch {
305 // \" stays inside the string; \\ consumes both so `"x\\"` closes.
306 b'\\' => i = (i + 2).min(len),
307 b'"' => {
308 stack.last_mut().expect("frame").in_double_quote = false;
309 i += 1;
310 }
311 _ => {
312 if let Some((kind, width)) = opens_substitution(i) {
313 stack.push(Frame::new(kind));
314 i += width;
315 } else {
316 i += 1;
317 }
318 }
319 }
320 continue;
321 }
322
323 // Unquoted within the current frame.
324 if let Some((kind, width)) = opens_substitution(i) {
325 if kind == FrameKind::Backtick && frame.kind == FrameKind::Backtick {
326 // The same character closes a backtick substitution.
327 stack.pop();
328 } else {
329 stack.push(Frame::new(kind));
330 }
331 i += width;
332 continue;
333 }
334
335 let at_top = stack.len() == 1;
336 let unshielded = at_top && !frame.shields_operators();
337
338 // #1793: enter/leave a `[[ … ]]` conditional so its internal `&&`/`||`
339 // stay part of the condition. Both delimiters must be standalone words
340 // (see the helpers), so a glob class (`ls a[[:alpha:]]`) or an array
341 // subscript never opens a depth that would swallow the rest of the line.
342 if ch == b'[' && opens_double_bracket(bytes, i) {
343 stack.last_mut().expect("frame").bracket_depth += 1;
344 i += 2;
345 continue;
346 }
347 if ch == b']' && frame.bracket_depth > 0 && closes_double_bracket(bytes, i) {
348 let top = stack.last_mut().expect("frame");
349 top.bracket_depth = top.bracket_depth.saturating_sub(1);
350 i += 2;
351 continue;
352 }
353
354 match ch {
355 b'\\' => {
356 // Escaped char is data (bash semantics outside quotes) — never
357 // an operator or quote opener.
358 i = (i + 2).min(len);
359 }
360 b'\'' => {
361 stack.last_mut().expect("frame").in_single_quote = true;
362 i += 1;
363 }
364 b'"' => {
365 stack.last_mut().expect("frame").in_double_quote = true;
366 i += 1;
367 }
368 b'(' => {
369 stack.last_mut().expect("frame").paren_depth += 1;
370 i += 1;
371 }
372 b')' => {
373 let top = stack.last_mut().expect("frame");
374 if top.kind == FrameKind::DollarParen && top.paren_depth == 0 {
375 // Matching close of `$(` — back to the enclosing context,
376 // whose quoting resumes exactly where it left off.
377 stack.pop();
378 } else {
379 top.paren_depth = top.paren_depth.saturating_sub(1);
380 }
381 i += 1;
382 }
383 b'{' => {
384 stack.last_mut().expect("frame").brace_depth += 1;
385 i += 1;
386 }
387 b'}' => {
388 let top = stack.last_mut().expect("frame");
389 top.brace_depth = top.brace_depth.saturating_sub(1);
390 i += 1;
391 }
392 // GH #2131: bash allows line breaks between a function head and
393 // its body (`run()\n{\n…\n}`). The newline ends no command there,
394 // so the definition stays one segment, as on a single line.
395 b'\n' | b'\r' if unshielded && is_function_head(&command[start..i]) => {
396 i += 1;
397 }
398 b'\n' | b'\r' | b';' if unshielded => {
399 segments.push((&command[start..i], Some(Separator::Sequence)));
400 i += 1;
401 start = i;
402 }
403 b'&' if unshielded => {
404 if i + 1 < len && bytes[i + 1] == b'&' {
405 // &&
406 segments.push((&command[start..i], Some(Separator::And)));
407 i += 2;
408 start = i;
409 } else if (i > 0 && matches!(bytes[i - 1], b'>' | b'<'))
410 || (i + 1 < len && bytes[i + 1] == b'>')
411 {
412 // Redirect operator, NOT a separator: `2>&1`, `1>&2`, `>&file`, `<&3`,
413 // `0<&-` (prev is '>' or '<') or `&>file`, `&>>file` (next is '>'). The '&' belongs to the current
414 // command — splitting here would mistake the fd/target (e.g. `1`) for a
415 // standalone command and falsely block it (#334).
416 i += 1;
417 } else {
418 // single & (background operator) — still a command separator
419 segments.push((&command[start..i], Some(Separator::Background)));
420 i += 1;
421 start = i;
422 }
423 }
424 b'|' if unshielded => {
425 if i + 1 < len && bytes[i + 1] == b'|' {
426 // ||
427 segments.push((&command[start..i], Some(Separator::Or)));
428 i += 2;
429 start = i;
430 } else if i > 0 && bytes[i - 1] == b'>' {
431 // `>|` (noclobber redirect), NOT a pipe: the '|' belongs to
432 // the redirect operator and the following token is a file
433 // path, not a command. Splitting here treated the target
434 // (e.g. `out` in `date >| out`) as a command and falsely
435 // blocked it against the allowlist (#387).
436 i += 1;
437 } else {
438 // pipe
439 segments.push((&command[start..i], Some(Separator::Pipe)));
440 i += 1;
441 start = i;
442 }
443 }
444 _ => {
445 i += 1;
446 }
447 }
448 }
449
450 if start < len {
451 segments.push((&command[start..], None));
452 }
453
454 segments
455}
456
457/// Extract normalized command tokens from a single segment (no operators):
458/// skip env assignments, skip a PowerShell assignment, return empty for a
459/// PowerShell value expression, skip a leading `{` brace-group token (#939 —
460/// lean-ctx's own agent wrapper emits this form), and take the basename of
461/// the first token. Shared by `extract_base_from_segment` (which returns just
462/// the first token) and the subcommand-scoped allowlist matcher (which needs
463/// the rest of the tokens too), so the two normalizations cannot drift
464/// (GH #1419 follow-up).
465pub(super) fn extract_command_tokens_from_segment(segment: &str) -> Vec<String> {
466 let trimmed = segment.trim();
467 if trimmed.is_empty() {
468 return Vec::new();
469 }
470
471 let cmd_part = skip_powershell_assignment(skip_env_assignments(trimmed));
472 if cmd_part.is_empty() {
473 return Vec::new();
474 }
475 if is_powershell_value_expression(cmd_part) {
476 return Vec::new();
477 }
478
479 let tokens = shell_tokenize(cmd_part);
480 // #939: a leading `{` brace-group token (e.g. from
481 // `agent_wrapper::rebuild`'s `{ <real command>\n} && pwd ...` wrapping)
482 // is not itself a command — skip it so the base extracted is the real
483 // command inside the group, not the brace.
484 let mut token_iter = tokens.into_iter();
485 let first_token = match token_iter.next() {
486 Some(t) if t == "{" => token_iter.next(),
487 other => other,
488 };
489 let Some(first_token) = first_token else {
490 return Vec::new();
491 };
492 let basename = first_token
493 .rsplit('/')
494 .next()
495 .unwrap_or(&first_token)
496 .to_string();
497
498 std::iter::once(basename).chain(token_iter).collect()
499}
500
501/// Extract the base command name from a single segment (no operators).
502pub(super) fn extract_base_from_segment(segment: &str) -> String {
503 extract_command_tokens_from_segment(segment)
504 .into_iter()
505 .next()
506 .unwrap_or_default()
507}
508
509/// Skip a local PowerShell assignment (`$result = Get-Content …`) so the
510/// wrapped cmdlet is validated. Environment/scoped variables contain `:` and
511/// intentionally remain unrecognized, preventing `$env:PATH = …` bypasses.
512pub(super) fn skip_powershell_assignment(segment: &str) -> &str {
513 let trimmed = segment.trim_start();
514 let Some(variable_end) = powershell_local_variable_end(trimmed) else {
515 return trimmed;
516 };
517 let after_variable = trimmed[variable_end..].trim_start();
518 let Some(after_equals) = after_variable.strip_prefix('=') else {
519 return trimmed;
520 };
521 after_equals.trim_start()
522}
523
524fn powershell_local_variable_end(segment: &str) -> Option<usize> {
525 let bytes = segment.as_bytes();
526 if bytes.first() != Some(&b'$') {
527 return None;
528 }
529 let mut end = 1;
530 let first = *bytes.get(end)?;
531 if !(first.is_ascii_alphabetic() || first == b'_') {
532 return None;
533 }
534 end += 1;
535 while bytes
536 .get(end)
537 .is_some_and(|byte| byte.is_ascii_alphanumeric() || *byte == b'_')
538 {
539 end += 1;
540 }
541 (bytes.get(end) != Some(&b':')).then_some(end)
542}
543
544/// A bare local variable or simple index lookup is pipeline data, not a command.
545/// Method calls and scoped variables deliberately fall through to deny-by-default.
546fn is_powershell_value_expression(segment: &str) -> bool {
547 let trimmed = segment.trim();
548 let Some(variable_end) = powershell_local_variable_end(trimmed) else {
549 return false;
550 };
551 let suffix = trimmed[variable_end..].trim();
552 suffix.is_empty()
553 || (suffix.starts_with('[')
554 && suffix.ends_with(']')
555 && !suffix.contains(['(', ')', ';', '|', '&', '=']))
556}
557
558/// #1488: detect whether a segment is a shell function definition.
559/// Pattern: `NAME() {`, `function NAME {` or `function NAME() {`; GH #2131
560/// adds `NAME(){`, a body on the next line and a `( … )` subshell body.
561/// Returns the function name if it is a definition, `None` otherwise.
562pub(super) fn detect_function_def(segment: &str) -> Option<String> {
563 function_def_parts(segment).map(|(name, _)| name.to_string())
564}
565
566/// #1488: the commands of a function definition segment, between the outer
567/// `{` and `}` (or `(` and `)`) — `greet() { echo hi; echo bye; }` gives
568/// `echo hi; echo bye;`. The allowlist expands it like a top-level command
569/// line, so control flow in a body (`for … do … done`, `if … then … fi`) is not
570/// mistaken for commands (GH #2002).
571pub(super) fn function_body(segment: &str) -> Option<&str> {
572 function_def_parts(segment).map(|(_, body)| body)
573}
574
575/// Split a function definition into its name and body text.
576///
577/// The body must be one balanced `{ … }` group or `( … )` subshell that ends
578/// the segment (GH #2131). Anything after it, such as a redirect evaluated on
579/// every call, makes this `None`, so the segment falls through to base
580/// extraction and is blocked rather than half-checked.
581fn function_def_parts(segment: &str) -> Option<(&str, &str)> {
582 let (name, rest) = function_def_head(segment)?;
583 let body = rest.trim();
584 if body.starts_with('{') {
585 return Some((name, super::compound::balanced_brace_inner(body)?));
586 }
587 if body.starts_with('(') {
588 let (inner, end) = super::compound::balanced_paren_at(body, 0)?;
589 return (end == body.len()).then_some((name, inner.trim()));
590 }
591 None
592}
593
594/// GH #2131: is `text` exactly a function head with its body still to come?
595/// See [`split_with_separators`].
596fn is_function_head(text: &str) -> bool {
597 function_def_head(text).is_some_and(|(_, rest)| rest.trim().is_empty())
598}
599
600/// Parse a function head — `NAME()`, `NAME ()`, `function NAME` or
601/// `function NAME()` — and return the name and the text after the head. Bash
602/// accepts any whitespace, line breaks included, before the body, and
603/// `NAME(){` needs none. `function NAME` without `()` needs whitespace, as
604/// `function f{` names a function `f{`.
605fn function_def_head(segment: &str) -> Option<(&str, &str)> {
606 let cmd_part = skip_env_assignments(segment.trim());
607 let keyword_rest = cmd_part
608 .strip_prefix("function")
609 .filter(|rest| rest.starts_with(|c: char| c.is_whitespace()));
610 let (name, after_name) = match keyword_rest {
611 Some(rest) => split_function_name(rest.trim_start())?,
612 None => split_function_name(cmd_part)?,
613 };
614 match strip_empty_parens(after_name) {
615 Some(rest) => Some((name, rest)),
616 None if keyword_rest.is_some()
617 && (after_name.is_empty() || after_name.starts_with(|c: char| c.is_whitespace())) =>
618 {
619 Some((name, after_name))
620 }
621 None => None,
622 }
623}
624
625fn split_function_name(text: &str) -> Option<(&str, &str)> {
626 let end = text
627 .find(|c: char| !(c.is_alphanumeric() || c == '_'))
628 .unwrap_or(text.len());
629 (end > 0).then(|| text.split_at(end))
630}
631
632/// `()` with optional blanks before and inside it; returns what follows.
633fn strip_empty_parens(text: &str) -> Option<&str> {
634 let rest = text.trim_start_matches([' ', '\t']).strip_prefix('(')?;
635 rest.trim_start_matches([' ', '\t']).strip_prefix(')')
636}
637
638/// Shell builtins that legitimately export or mutate environment variables.
639/// A segment beginning with one of these (`export PATH=…`, `readonly FOO=bar`)
640/// is not a bare inline `PATH=… cmd` hijack — skip the builtin and any
641/// following `VAR=value` tokens so export-only segments contribute no leaf
642/// command and `export PATH=… ; python3 …` resolves to `python3`.
643const ENV_SETTING_BUILTINS: &[&str] =
644 &["export", "unset", "readonly", "local", "declare", "typeset"];
645
646/// Skip leading KEY=VALUE environment variable assignments.
647/// Uses quote-aware scanning so `FOO="bar baz" git status` correctly
648/// skips the entire `FOO="bar baz"` token.
649pub(super) fn skip_env_assignments(segment: &str) -> &str {
650 let mut rest = segment;
651 loop {
652 let rest_trimmed = rest.trim_start();
653 if rest_trimmed.is_empty() {
654 return rest_trimmed;
655 }
656 let end = quote_aware_token_end(rest_trimmed);
657 if end == 0 {
658 return rest_trimmed;
659 }
660 let raw_token = &rest_trimmed[..end];
661 let unquoted: String = raw_token
662 .chars()
663 .filter(|c| *c != '"' && *c != '\'')
664 .collect();
665 let base_token = unquoted.rsplit('/').next().unwrap_or(unquoted.as_str());
666 if ENV_SETTING_BUILTINS.contains(&base_token) {
667 rest = &rest_trimmed[end..];
668 continue;
669 }
670 let is_posix_assignment = unquoted.split_once('=').is_some_and(|(name, _)| {
671 let mut bytes = name.bytes();
672 bytes
673 .next()
674 .is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')
675 && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
676 });
677 if is_posix_assignment {
678 rest = &rest_trimmed[end..];
679 } else {
680 return rest_trimmed;
681 }
682 }
683}
684/// Public accessor for extracting all command segments.
685pub fn extract_all_commands_pub(command: &str) -> Vec<String> {
686 extract_all_commands(command)
687}
688// Legacy compat: single-segment extraction (used by other callers)
689pub fn extract_base_command(command: &str) -> String {
690 let first_seg = split_on_operators(command)
691 .into_iter()
692 .next()
693 .unwrap_or(command);
694 extract_base_from_segment(first_seg)
695}