Skip to content

fix(grep): stabilize argument parsing — trailing_var_arg, -v invert-match, --version passthrough, safe rg invocation - #2333

Merged
aeppling merged 8 commits into
rtk-ai:developfrom
KuSh:grep_arg_parsing
Jun 14, 2026
Merged

aeppling merged 8 commits into
rtk-ai:developfrom
KuSh:grep_arg_parsing

Conversation

@KuSh

@KuSh KuSh commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator

Summary

rtk grep had three distinct bugs that made it unreliable in real usage:

  1. Clap parse failure for any unknown flag before the pattern — rtk grep --version, rtk grep --glob '*.ts' pattern, rtk grep --type-add 'web:*.html' pattern all failed with
    "unexpected argument" Clap errors because pattern was a required positional and Clap tried to interpret any flag before it as a named subcommand flag.

  2. -v verbose flag silently swallowing grep's invert-match — rtk grep -v pattern . ran a normal (non-inverted) search because verbose was declared global = true, causing Clap
    to consume every -v anywhere in the arg list as RTK verbosity.

  3. rg misinterpreting flag-shaped patterns — rtk grep -- --version called rg ... "--version" . without a -- separator before the pattern. rg interpreted --version as its own
    version flag, printed its version info (not in NUL match format), causing "7 matches in 0 files" output (total from pre-parse line count, zero from empty by_file map).

Changes

src/main.rs

  • Removed global = true from the verbose flag. -v is now only recognized before the subcommand; any -v after grep flows into args and is forwarded to rg as invert-match.
  • Removed pattern, path, and line_numbers as Clap-managed fields from the Grep variant. A single trailing_var_arg field args: Vec<String> captures everything — pattern, path,
    and any grep/rg flag — without Clap needing to know about them. New rg flags no longer require a main.rs change.

src/cmds/system/grep_cmd.rs

  • Added extract_pattern_path(args) — scans the flat arg slice, assigns the first and second non-flag tokens as pattern and path (default .), collects the rest as extra_args for rg.
    Handles -- boundary correctly.
  • Added early passthrough for --version / --help / -h — routes directly to rg (or grep fallback) without filtering.
  • Added -- before <pattern> <path> in both rg and grep invocations — prevents rg/grep from misinterpreting flag-shaped patterns.
  • Fixed total_matches — derived from by_file.values().map(|v| v.len()).sum() after parsing, so the "N matches in M files" header is always consistent with what's displayed.

Issues fixed

Issue Title
#2167 rtk grep calls system grep — breaks -g/--glob flags
#2120 --fixed-strings before pattern causes fallback to native grep
#880 65 grep failures, 0 savings (invert-match -v swallowed)

Test plan

  • cargo fmt --all && cargo clippy --all-targets && cargo test
  • Manual testing:
    -rtk grep --version ✅️
    -rtk -vvv grep --version ✅️
    -rtk grep -- --version ✅️
    -rtk grep -v TODO src/ ✅️
    -rtk grep 'fn run' src/ ✅️
    -rtk grep -i -A 2 'error' src/ ✅️

@aeppling

aeppling commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Hey @KuSh

Starting the first review pass with the -vvv bug we talked about.
What I found (tested on your branch, compiled binary):

Command ran BRanch KuSh:grep_arg_parsing
rtk -vvv grep --version OK (no more -vvv error)
rtk -vvv (alone) broken: Failed to resolve '-vvv' via PATH
rtk -vvv git --badflag broken: Failed to resolve '-vvv' via PATH
rtk -vvv frobnicate broken: Failed to resolve '-vvv' via PATH

So the symptom only disappears for grep, because you made grep's parsing infallible (trailing_var_arg). For every other command that fails to parse with a leading global flag, the bug is still fully there.

The real root cause isn't in grep. This may be in run_fallback when clap fails to parse, the fallback takes the first token of argv as the command to execute via $PATH. If you lead with a global flag (-vvv, --verbose, --ultra-compact, --skip-env), that first token is the flag, so rtk tries to run a binary called -vvv. I think it is a RTK fallback bug, not related to grep directly.

Fix direction (without touching grep): in run_fallback, skip leading global flags before choosing the command; if nothing is left (rtk -vvv alone), show clap's normal error

@aeppling

Copy link
Copy Markdown
Contributor

Re @KuSh !

On the grep arg parsing this time :p --fixed-strings before the pattern #2120 is fixed, but extract_pattern_path seems to fail on some args sadly

Command ran Branch KuSh:grep_arg_parsing
rtk grep -i todo src OK (now filtered, was fallback)
rtk grep -A 2 error src broken: rg error, "2" taken as the pattern
rtk grep -rn foo src wrong: match replaced, prints "n" instead of the line
rtk grep TODO src tests broken: rg "No such file" (multi-path)
rtk grep -i x agent -g '*.md' broken: regex parse error (the #2167 repro)

The approach looks good to me, removing pattern from the main definition to catch all as args and then parse,

But the rule "dash means flag, no dash means pattern/path" does not match how grep/rg flags actually work, so it misreads three common shapes:

  • Value-taking flags: grep -A 2 error : the 2 (value of -A) has no dash, so it's taken as the pattern. Same with -g "*.md" (glob value becomes the pattern, rg errors). So rtk grep calls system grep instead of ripgrep — breaks -g/--glob flags #2167 not fully closed

  • Combined clusters: the -r strip only matches the standalone -r, so -rn leaks to rg, where -r means --replace and rewrites every match to "n". grep -rn foo prints n instead of the line.

  • Multiple paths: grep TODO src tests keeps only one path and breaks the rg call.


So what can i propose for this issue:

  • We could hold a list of value-taking flags so the splitter consumes their value instead of reading it as the pattern. Plus strip -r out of combined clusters and keep every non-flag positional as a path.

Problem: we'd have to know each flag's exact behavior (some take multiple values, some are optional), and maintain this exhaustive list.

  • We give the parser a small spec of the flags rtk cares about and their arity (-A/-B/-C/-g/-e take one value, -i/-w/-n take none, grep's -r means recursive so we drop it), with one rule for everything else: unknown flag = pass straight through to rg untouched.

Problem: this still involves a list, like the first option, but the difference is where the risk lands. In the first option the list is load-bearing: miss a value-flag and it silently corrupts again. Here the list sits on top of a passthrough, so a missing entry just means that flag is not specially optimized, the command itself is not broken.


Honestly this seems like an important issue, so I'm in favor of fixing it on your splitter directly: a small value-taking flag list (kept deliberately small at first, the common ones, then grown), plus stripping -r out of combined clusters, plus keeping every non-flag positional as a path.

We can move to another approach later if this gets painful, but we stop the bleed now on the known cases

Of course open to others ideas

@aeppling

Copy link
Copy Markdown
Contributor

I've did not go through all #2138 but we'll get conflicts, maybe merge this one first since it define pattern parsing then 2138 will rebase on it

KuSh and others added 4 commits June 10, 2026 23:38
…atterns

Four bugs in `extract_pattern_path` caused `rtk grep` to misparse
common invocations:

- `-A 2 error src` → `2` was taken as the pattern (value-taking
  flags not recognised)
- `-rn foo src` → `n` leaked to rg as `--replace` value (only
  standalone `-r` was stripped, not combined clusters like `-rn`)
- `TODO src tests` → second path silently dropped (only one path
  kept)
- `-i x agent -g '*.md'` → rg regex error (`*.md` became positional
  before `-g` could consume it)

New implementation:
- `VALUE_FLAGS_SHORT`: explicit byte-set of 2-char flags that consume
  one following token (`A`, `B`, `C`, `g`, `f`, `j`, `m`)
- `process_flag()`: strips `r`/`R` from any single-dash cluster,
  drops `--recursive`; replaces the old inline `if arg == "-r"` loop
- `extract_pattern_path` returns `(Vec<String>, Vec<String>, Vec<String>)`
  (patterns, paths, flags) — no more `Option<String>` for pattern
- `-e` values collected separately; if any `-e` is present, all
  positionals are paths; otherwise first positional is the pattern
- All patterns forwarded to rg as `-e` flags (BRE `\|`→`|` inline)

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
A combined cluster like -rne PATTERN or -rA 2 had the last flag's
value consumed only if the cluster was exactly 2 chars. Longer
clusters (e.g. -rne) fell through to process_flag, which stripped
-r and emitted -ne — then -e ended up in flags without a value,
causing rg to error.

New unified short-flag handler: for any single-dash cluster, inspect
the last byte. If it is -e or a VALUE_FLAGS_SHORT member, strip the
r/R chars from the prefix, emit the prefix as a flag (if non-empty),
and consume the next token as the value (pattern for -e, flag value
otherwise). Long flags (--foo) are still routed through process_flag.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@KuSh
KuSh force-pushed the grep_arg_parsing branch from 070252f to 7d6255f Compare June 10, 2026 23:55
@KuSh

KuSh commented Jun 10, 2026 •

Copy link
Copy Markdown
Collaborator Author

@aeppling took care of most of your feedback except:

@KuSh
KuSh requested a review from aeppling June 10, 2026 23:59
@aeppling

aeppling commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Re @KuSh

Rechecked with latest commit, all last tests I shown are now green, but here is some additionals, and all five worked on develop, so they are working-to-broken regressions:

Command ran Branch KuSh:grep_arg_parsing
rtk grep -ecarrot file wrong: matches "caot" instead of "carrot" (silent)
rtk grep aaa sub -g'*.rs' wrong: glob becomes *.s, 0 matches (silent)
rtk grep compact sub --glob '*.md' broken: glob taken as path, rg error
rtk grep --max-count 1 fn file broken: rg error, "1" taken as the pattern
rtk grep -E 'a b' file

The first two are blockers, silent wrong results: strip_r eats the r's of attached values, not just the cluster letters. To be fair the trap was in my suggestion too, it should have said flag letters only.

Rows 3 and 4 are blockers too: the value list only covers short flags, the separated long forms put the value in the pattern or paths.

Row 5 is dialect territory, grep's -E is boolean ERE but rg's -E takes an encoding value. Probably #2138's job to handle properly, just flagging it so it does not get lost.

The current suite stays green because none of these shapes are covered, so a test per row would lock it in.

…hrough

Five regressions on grep_arg_parsing vs develop:

- `-ecarrot` matched "caot" — strip_r was applied to the inline value bytes.
  Fix: scan cluster left-to-right; stop at first value-taking letter and
  treat the remainder as the inline value without r/R stripping.

- `-g*.rs` glob became `*.s` — same root cause, inline glob value r-stripped.

- `--glob '*.md'` took `*.md` as a path — no VALUE_FLAGS_LONG existed; the
  value token fell through to the positional collector.
  Fix: add VALUE_FLAGS_LONG covering all rg long flags that take a value.

- `--max-count 1 fn file` took `1` as the pattern — same missing long flag.

- VALUE_FLAGS_SHORT expanded: add t/T (--type/--type-not), d (--max-depth),
  M (--max-columns) so inline short forms and space-separated forms parse
  correctly without mis-routing values to patterns or paths.

- --regexp (long form of -e) now routes to patterns like -e does.

- has_format_flag: add --count-matches, --json, --passthru, --files so
  these output-format modes get passthrough treatment instead of silent
  "0 matches in 0 files".

2183 tests pass.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@KuSh

KuSh commented Jun 14, 2026

Copy link
Copy Markdown
Collaborator Author

@aeppling thanks for feedback, I've pushed a fix

  • Left-to-right cluster scan: The old "check last byte" algorithm applied strip_r to the prefix, corrupting inline values like -ecarrot → -ecaot or -g*.rs → -g*.s. The new scan walks the cluster byte-by-byte; when it hits a value-taking flag letter (e, A, g, t, M, etc.), it stops and treats everything after that letter as the inline value — no r/R stripping touches it.

  • VALUE_FLAGS_LONG: New constant covering all rg long flags that take a space-separated value (--glob, --max-count, --type, --engine, --ignore-file, --path-separator, --field-context-separator, etc.). --regexp is handled separately as the long form of -e.

  • VALUE_FLAGS_SHORT: Expanded from ABCgfjm to ABCgfjmtTdM (added --type, --type-not, --max-depth, --max-columns).

  • has_format_flag: Added --count-matches, --json, --passthru, --files so those output modes get passthrough treatment instead of silently showing "0 matches".

The #2138 test contract and -E dialect conflict are left untouched, I'll document in that PR what should be done

KuSh and others added 2 commits June 14, 2026 15:29
… clippy fix

The left-to-right cluster scan now calls strip_r() at emit time on the
accumulated flag-letter prefix (raw_prefix), never on inline value bytes.
This makes the safety contract explicit and testable: strip_r("carrot")
produces "caot", documenting exactly why it must not touch value bytes.

Also fix pre-existing unused-mut in aws_cmd.rs (has_output_flag).

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…y testable

The left-to-right scanning logic now lives entirely in parse_cluster(), which
returns a ClusterResult enum (Boolean or ValueTaking). extract_pattern_path
just dispatches on the result — no loop logic inline.

parse_cluster() is the only place that touches cluster bytes, so the full
contract is testable in isolation:

  parse_cluster("ecarrot") → ValueTaking { prefix: None, flag: 'e', inline: "carrot" }
  parse_cluster("rne")     → ValueTaking { prefix: Some("n"), flag: 'e', inline: "" }
  parse_cluster("g*.rs")   → ValueTaking { prefix: None, flag: 'g', inline: "*.rs" }
  parse_cluster("rn")      → Boolean(Some("n"))

strip_r() remains as the focused r/R-stripping helper used internally by
parse_cluster (and tested directly to document the "carrot"→"caot" danger).

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@KuSh
KuSh force-pushed the grep_arg_parsing branch from 40258fc to 34aac6e Compare June 14, 2026 13:29
@aeppling

Copy link
Copy Markdown
Contributor

Hey @KuSh , LGTM !

Thanks for addressing all fix

@aeppling
aeppling merged commit d8c550e into rtk-ai:develop Jun 14, 2026
11 checks passed
@KuSh
KuSh deleted the grep_arg_parsing branch June 14, 2026 17:24
F0rty-Tw0 added a commit to F0rty-Tw0/rtk that referenced this pull request Jun 14, 2026
…tk-ai#1436)

Rebased onto rtk-ai#2333's extract_pattern_path / trailing_var_arg rework.

rtk grep shells out to ripgrep, whose default engine treats ( ) + ? | { }
as metacharacters. Plain grep defaults to POSIX BRE where those are
literal, so `rtk grep 'delete()'` matched every `delete` instead of the
literal call (rtk-ai#1436).

Detect the requested dialect from the forwarded flags and route:
- BRE default       -> translate pattern to rg's dialect (bre_to_pcre)
- -E/--extended     -> rg default engine, no translation
- -P/--perl-regexp  -> rg --pcre2, no translation
- -F/--fixed        -> rg -F, no translation
- -G/--basic-regexp -> native grep directly (caller named grep's engine)

Dialect flags are stripped before rg (it misreads -E as --encoding, has
no -G); the grep fallback keeps them since grep understands each. The
discover rule split tags rg-origin rewrites with -E so an rg pattern
reaches rg's engine unchanged instead of being BRE-translated.

bre_to_pcre leaves [...] bracket contents untranslated (metacharacters
are already literal there).
pidefrem added a commit to pidefrem/rtk that referenced this pull request Jun 23, 2026
…th rg --encoding)

GNU grep -E is a boolean (extended-regexp); ripgrep -E is --encoding
(value-taking). Any short-flag cluster ending in E (-hoE, -nE, -rE) was
forwarded verbatim to rg, which consumed the next token (the pattern, or
rtk's injected -e) as an encoding name -> 'unknown encoding' crash.

Strip E as a GNU-ERE no-op (rg's default engine is already an ERE superset):
- strip_r -> strip_collisions, filter set {r,R} -> {r,R,E}
- strip_recursive -> strip_long_collisions, also drop --extended-regexp
  and --dereference-recursive
Only ever applied to accumulated flag letters, never inline value bytes.

The -r/-R half of this collision was already fixed by rtk-ai#2333; -E was the
remaining gap. +11 tests.
pidefrem added a commit to pidefrem/rtk that referenced this pull request Jun 23, 2026
…th rg --encoding)

GNU grep -E is a boolean (extended-regexp); ripgrep -E is --encoding
(value-taking). Any short-flag cluster ending in E (-hoE, -nE, -rE) was
forwarded verbatim to rg, which consumed the next token (the pattern, or
rtk's injected -e) as an encoding name -> 'unknown encoding' crash.

Strip E as a GNU-ERE no-op (rg's default engine is already an ERE superset):
- strip_r -> strip_collisions, filter set {r,R} -> {r,R,E}
- strip_recursive -> strip_long_collisions, also drop --extended-regexp
  and --dereference-recursive
Only ever applied to accumulated flag letters, never inline value bytes.

The -r/-R half of this collision was already fixed by rtk-ai#2333; -E was the
remaining gap. +11 tests.
pidefrem added a commit to pidefrem/rtk that referenced this pull request Jun 25, 2026
…th rg --encoding)

GNU grep -E is a boolean (extended-regexp); ripgrep -E is --encoding
(value-taking). Any short-flag cluster ending in E (-hoE, -nE, -rE) was
forwarded verbatim to rg, which consumed the next token (the pattern, or
rtk's injected -e) as an encoding name -> 'unknown encoding' crash.

Strip E as a GNU-ERE no-op (rg's default engine is already an ERE superset):
- strip_r -> strip_collisions, filter set {r,R} -> {r,R,E}
- strip_recursive -> strip_long_collisions, also drop --extended-regexp
  and --dereference-recursive
Only ever applied to accumulated flag letters, never inline value bytes.

The -r/-R half of this collision was already fixed by rtk-ai#2333; -E was the
remaining gap. +11 tests.
pidefrem added a commit to pidefrem/rtk that referenced this pull request Jun 25, 2026
…th rg --encoding)

GNU grep -E is a boolean (extended-regexp); ripgrep -E is --encoding
(value-taking). Any short-flag cluster ending in E (-hoE, -nE, -rE) was
forwarded verbatim to rg, which consumed the next token (the pattern, or
rtk's injected -e) as an encoding name -> 'unknown encoding' crash.

Strip E as a GNU-ERE no-op (rg's default engine is already an ERE superset):
- strip_r -> strip_collisions, filter set {r,R} -> {r,R,E}
- strip_recursive -> strip_long_collisions, also drop --extended-regexp
  and --dereference-recursive
Only ever applied to accumulated flag letters, never inline value bytes.

The -r/-R half of this collision was already fixed by rtk-ai#2333; -E was the
remaining gap. +11 tests.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants