Repository navigation
fix(grep): stabilize argument parsing — trailing_var_arg, -v invert-match, --version passthrough, safe rg invocation - #2333
Conversation
|
Hey @KuSh Starting the first review pass with the -vvv bug we talked about.
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 |
|
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
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:
So what can i propose for this issue:
Problem: we'd have to know each flag's exact behavior (some take multiple values, some are optional), and maintain this exhaustive list.
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 |
|
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 |
…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]>
|
@aeppling took care of most of your feedback except:
|
|
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:
The first two are blockers, silent wrong results: 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 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]>
|
@aeppling thanks for feedback, I've pushed a fix
The #2138 test contract and -E dialect conflict are left untouched, I'll document in that PR what should be done |
… 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]>
|
Hey @KuSh , LGTM ! Thanks for addressing all fix |
…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).
…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.
…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.
…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.
…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.
Summary
rtk grephad three distinct bugs that made it unreliable in real usage:Clap parse failure for any unknown flag before the pattern —
rtk grep --version,rtk grep --glob '*.ts' pattern,rtk grep --type-add 'web:*.html' patternall failed with"unexpected argument" Clap errors because
patternwas a required positional and Clap tried to interpret any flag before it as a named subcommand flag.-vverbose flag silently swallowing grep's invert-match —rtk grep -v pattern .ran a normal (non-inverted) search becauseverbosewas declaredglobal = true, causing Clapto consume every
-vanywhere in the arg list as RTK verbosity.rg misinterpreting flag-shaped patterns —
rtk grep -- --versioncalledrg ... "--version" .without a--separator before the pattern. rg interpreted--versionas its ownversion 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_filemap).Changes
src/main.rsglobal = truefrom theverboseflag.-vis now only recognized before the subcommand; any-vaftergrepflows intoargsand is forwarded to rg as invert-match.pattern,path, andline_numbersas Clap-managed fields from theGrepvariant. A singletrailing_var_argfieldargs: 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.rschange.src/cmds/system/grep_cmd.rsextract_pattern_path(args)— scans the flat arg slice, assigns the first and second non-flag tokens as pattern and path (default.), collects the rest asextra_argsfor rg.Handles
--boundary correctly.--version/--help/-h— routes directly to rg (or grep fallback) without filtering.--before<pattern> <path>in both rg and grep invocations — prevents rg/grep from misinterpreting flag-shaped patterns.total_matches— derived fromby_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
-g/--globflags--fixed-stringsbefore pattern causes fallback to native grep-vswallowed)Test plan
cargo fmt --all && cargo clippy --all-targets && cargo test-
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/✅️