Skip to content

fix(windows): expand glob operands a non-globbing caller left as written - #4544

Open
bharvey42 wants to merge 7 commits into
rtk-ai:developfrom
bharvey42:feat/windows-operand-glob
Open

bharvey42 wants to merge 7 commits into
rtk-ai:developfrom
bharvey42:feat/windows-operand-glob

Conversation

@bharvey42

@bharvey42 bharvey42 commented Oct 13, 2026 •

Copy link
Copy Markdown

Stacked on #4103 (draft until that merges), to be merged right after it, per #4103 (comment). This is the operand-globbing follow-up named in its description.

Review the last five commits (8db8d1b find + grep/rg, a6b57ab ls, 28b6ff0 wc, then round 1: eda28ca wc names, cf23e15 the command-line-limit fallback and the pins). The first commit is #4103's head (e36369a); it shows here because a PR can't target another fork's branch, and it drops out once #4103 merges and this is rebased onto develop.

Scope, per #4103 (comment): expansion lives in each command's operand parser, not in ChildCommand, which gains only what the fallback past the command-line limit needs (below). This PR covers find, the search engines, ls (its GNU/BSD grammar is on develop since #5099) and wc (which gets its grammar here). tree still needs a grammar (-P/-I) and follows separately.

Problem

#4103 quotes every argument that holds a glob character, so an MSYS child no longer globifys it. That is right for a pattern and wrong for a file operand. From a caller that doesn't expand globs (PowerShell, cmd), rtk grep x *.rs, rtk find ./s* -name '*.rs', rtk ls *.txt and rtk wc -l *.txt now reach the child as literal names and fail with No such file or directory. On develop the MSYS children expanded them. rg is a native binary and never globbed, so rtk rg x *.rs from PowerShell fails on develop too (os error 123). For rg this is new behaviour rather than a restore, included so the two engines agree.

Change

Each command expands its own file operands, at the point where its parser already knows which arguments are files, so a pattern, flag or flag value still reaches the child literally.

  • core/operand_glob.rs: expand_operands, plus for_child, which expands the arguments at the indices a command's parser picked and keeps the rest. Windows only; on Unix the caller's shell has already expanded, so operands pass through.
  • Past the command-line limit. An expanded list has to fit in the child's command line, which Windows caps at 32,767 characters; the MSYS child's own expansion never had to. When the expanded command would not fit, for_child returns the arguments as typed with the operands that would have expanded marked, and wc, ls (both runs) and grep (passthrough, capture, streaming) send those through ChildCommand::glob_arg, std's encoding, so the child globs them itself as it did on develop. Everything else stays literal. ChildCommand::command_line_len is the length std hands CreateProcessW (a Windows test spawns one unit under the limit and one at it), and every spawn checks it first, so a line that cannot fit — rg, which has no globbing of its own, or find's starting points — fails with an error naming the limit instead of os error 206.
  • grep/rg: the path positionals, read the same way as extract_pattern_path (all positionals when -e/-f/rg --files supply the pattern). The expansion runs once at the top of run, so the passthrough (-c, -l), streaming and capture modes all see the same operands. The tracked command stays what the user typed (grep x '*.rs'), as it does for find, ls and wc.
  • find: the starting points only. The expression (-name '*.rs') and the legacy rtk find <pattern> form's pattern stay literal. The verbatim (-exec/-delete) path, legacy form included, is rebuilt from the expanded starting points.
  • ls: the free positionals of the host flavour's grammar, so -I '*.o', --ignore '*.o' and --hide='*~' stay patterns (and BSD's boolean -I leaves the next word an operand). Expanded once at the top of run, so the filtered listing and native_listing name the same files.
  • wc: gets a declared grammar per flavour, transcribed from each wc's own help: GNU (coreutils 8.32 and 9.4) -c/-m/-l/-w/-L with their long names, --files0-from F, --total WHEN, --help, --version, with getopt_long's unique-prefix abbreviation (--t=never, --f list); BSD -Lclmw and --libxo. Three things read it:
    • the operands to expand: the free positionals, never --files0-from's or --total's value;
    • whether wc reads stdin, replacing the starts_with('-') check: with no file operand, with - as one, or with a last --files0-from naming -. Before, --total always counted always as a file, so … | rtk wc --total always didn't forward the pipe;
    • the output mode, replacing a per-character scan of every dash-led argument, which read --chars as -c (bytes) and --bytes as no flag (so the three-column formatter got one column and passed it through raw). The formatter now reads each line as the mode's count columns, one space, and the name, so a name with spaces stays whole (3 my file.txt, where it printed 3 file.txt). Now long names, abbreviations and -L count as columns, ---protected operands don't, and the BSD reading follows BSD: options stop at the first operand (wc f -l names a file -l there), and -c/-m cancel, the last one winning, both checked against macOS 27's wc.

The rules follow what globify did, measured against Git for Windows' ls with unquoted arguments from PowerShell: *, ? and [...] match within one component, case-sensitively (*.TOML doesn't match Cargo.toml); a leading . needs a literal .; {a,b} expands; a leading ~ is home; a trailing separator keeps only directories; an operand that matches nothing is kept, so the child reports it as before. There are two deliberate differences:

  • \ separates components, as it does in the paths a PowerShell or cmd user writes. globify reads it as an escape, so 'sub\*.rs' asked for sub*.rs there.
  • An operand that names an existing path is never expanded. Called from Git Bash, bash has already expanded, so a[1].txt would otherwise be globbed a second time into a1.txt (which globify did).

rtk can't tell which caller it has. So from Git Bash a glob the user quoted to keep it literal (rtk grep x '*.rs') is expanded here, exactly as develop's MSYS children did. A literal name that exists on disk is still passed unchanged.

Test plan

  • Unit tests for the expander (operand_glob: dotfiles, case, no-match, existing path, both separators, trailing separator, sort order, braces, tilde, matcher rules including [a-], and for_child's three outcomes: expanded, left to the child, nothing to measure). They run against a real scratch tree on every platform.
  • Classification tests with a marker expander for grep/rg (including -f pats and --file=pats), ls (GNU and BSD) and wc (GNU and BSD), so which arguments count as operands is asserted on Linux too. wc's grammar is pinned with assert_takes_value_table per flavour. find's verbatim argv is pinned with and without leading options. wc's formatter is tested on Git for Windows' own output for a name with a space.
  • ChildCommand: std_encoded_len against std's append_arg rules, command_line_len per way of sending, the refusal one unit past the limit, and on Windows a real spawn at the limit (hostname: one unit under spawns, one at it gives 206).
  • tests/operand_glob_test.rs spawns rtk with no shell, Git's usr\bin first on PATH, skipped without an MSYS wc: wc -l *.txt, grep -c x *.rs, find ./s* -name *.rs, ls -I *.txt sub; 3000 long names through wc, grep and ls; rg past the limit; and wc -- -l counting the file, which also runs on Linux.
  • Mutations: 13 over this round's decisions (the expansion itself, find's starting points, ls's flavour, the fallback, rg's exclusion from it, glob_arg's encoding, the spawn check, the length model's quote escaping, restore_double_dash, grep's -f, find's verbatim slice, the [a-] guard, the name as the last word). Every one fails a named test.
  • Windows (x86_64-pc-windows-gnu): cargo fmt --check, cargo clippy --all-targets clean; cargo test --all --no-fail-fast 5521 passed, 1 failed across 78 targets. The failure is the environment baseline core::stream::test_read_lines_lossy_preserves_lines_after_invalid_utf8, which fails at the same assertion (stream.rs:845) on unmodified e36369a.
  • Linux (aarch64-unknown-linux-gnu, GNU grep 3.11, ripgrep 16.0, git 2.43), at cf23e15: cargo fmt --check, cargo clippy --all-targets clean; cargo test --all --no-fail-fast 5925 passed, 1 failed across 78 targets, the search/grep integration targets included. The failure, guard_integration_test::git_log_malformed_digit_run_propagates_real_git_error, fails the same way on unmodified e36369a: it expects git 2.51's wording (not an integer) and git 2.43 says not a non-negative integer.
  • End to end on Windows 11, PowerShell 5.1, Git's usr\bin on PATH, every row run on both builds in one scratch tree (b.rs, a.txt, c.txt, my file.txt, pats, sub/x.rs, sub/d.txt), and the last four in a directory of 3000 files longer_file_name_number_NNNN.txt (about 99,000 characters expanded):
Command #4103 e36369a this branch cf23e15
rtk grep -c x *.rs sub/* No such file ×2, rc 2 b.rs:1 sub/d.txt:0 sub/x.rs:0, rc 0
rtk grep -c 'x*' b.rs 1 1 (pattern untouched)
rtk grep -c -f pats *.rs *.rs: No such file, rc 2 1, rc 0
rtk rg -c x *.rs os error 123, rc 2 1, rc 0
rtk find './s*' -name '*.rs' No such file, rc 1 x.rs, rc 0
rtk find './s*' -name '*.rs' -exec echo hit '{}' ';' No such file, rc 1 hit ./sub/x.rs, rc 0
rtk find '*.rs' 's*' -exec echo hit '{}' ';' 's*': No such file, rc 1 hit sub/x.rs, rc 0
rtk ls *.txt cannot access '*.txt', rc 2 the .txt files, rc 0
rtk ls -I '*.txt' * cannot access '*', rc 2 the named entries, then sub: listing x.rs but not d.txt (pattern untouched), rc 0
rtk ls sub\*.txt cannot access 'sub\*.txt', rc 2 sub\d.txt, rc 0
rtk wc -l *.txt '*.txt': No such file, rc 1 1 a.txt 2 c.txt 1 my file.txt Σ 4, rc 0
rtk wc --bytes 'my file.txt' a.txt 3 my file.txt 6 a.txt 9 total (passed through raw) 3 my file.txt 6 a.txt Σ 9
rtk wc -l 'my file.txt' a.txt 1 file.txt 1 a.txt Σ 2 1 my file.txt 1 a.txt Σ 2
rtk wc -l --files0-from list 1 a.txt 2 c.txt Σ 3 same
rtk wc -l *.zz '*.zz': No such file, rc 1 same (kept as written)
3000 files: rtk wc -l *.txt No such file, rc 1 3000 counts and Σ 3000, rc 0
3000 files: rtk ls *.txt cannot access '*.txt', rc 2 the listing (capped, rest in the tee file), rc 0
3000 files: rtk grep -c x *.txt No such file, rc 2 3000 name:1 lines, rc 0
3000 files: rtk rg -c x *.txt os error 123, rc 2 the command line for …\rg.exe would be 99068 characters with its terminating NUL, past Windows' limit of 32767 (…), rc 1

Round 1's previous head (8a9e0b7) failed the three 3000-file wc/ls/grep rows with os error 206. rtk wc 'my file.txt' a.txt now prints wc's own lines (1 1 3 my file.txt …): with one-digit counts the compact 1L 1W 3B form is longer, so the never-worse guard keeps the raw output.

From Git Bash, printf 'a.txt\0b.txt\0' | rtk wc -l --files0-from=- counts both files, so the names reach wc on stdin.

Not covered: tree (see Scope) and the native Rust readers (read), which never went through globify. rtk find s* -name '*.rs' (a glob first starting point with no separator) is still read as the legacy pattern form, as on develop (#2995).

@rtk-wshm-sync-bot

Copy link
Copy Markdown

wshm · Automated triage by AI

📊 Automated PR Analysis

🐛 Type bug-fix
🟡 Risk medium

Summary

Adds Windows-only glob expansion (core/operand_glob.rs) for file operands in ls, wc, grep/rg, and find, restoring behavior that broke when PR #4103 began quoting glob-containing arguments so MSYS children no longer expand them. Each command expands only its own file-operand positions (not patterns, flags, or flag values), with rules modeled on Git for Windows' legacy globify plus two deliberate differences for \ separators and already-existing paths.

Review Checklist

  • Tests present
  • Breaking change
  • Docs updated

Analyzed automatically by wshm · This is an automated analysis, not a human review.

@KuSh

KuSh commented Nov 21, 2026

Copy link
Copy Markdown
Collaborator

@bharvey42, #4103 is rebased on develop (head de78669e), and pszymkowiak's Windows runs on #4103 leave one gap: from PowerShell or cmd, rtk ls *.txt and rtk wc -l *.txt still fail with this PR on top. The plan on #4103 is to merge it and this PR back to back once this one covers those two, so could you rebase onto the new head and add them?

  • ls: its GNU/BSD grammar is on develop now, so the operand slice is already bounded and expansion is globbing the free positionals. run spawns ls twice (the filtered run and native_listing), and both need the expanded operands.
  • wc: needs a grammar first (--files0-from F, --total WHEN, the count flags of each flavour). It also replaces the starts_with('-') check that decides whether wc reads stdin.

@bharvey42
bharvey42 force-pushed the feat/windows-operand-glob branch from b929d66 to 6c9662a Compare November 24, 2026 00:49
@bharvey42

Copy link
Copy Markdown
Author

@KuSh, ls and wc are in, on top of de78669e:

  • ea0dda64 ls: expands the free positionals of the host flavour's grammar once, at the top of run, so the filtered run and native_listing get the same operands. -I/--ignore/--hide values stay patterns.
  • 8a9e0b74 wc: GNU and BSD grammars (--files0-from F, --total WHEN, each flavour's count flags, BSD's --libxo), checked against coreutils 8.32/9.4 and macOS's wc. They now decide the operands to expand, whether wc reads stdin (replacing the starts_with('-') check) and the output mode. The old per-character scan read --chars as bytes and didn't recognise --bytes.

From PowerShell, rtk ls *.txt and rtk wc -l *.txt now work. The description has the table, with every row run on both de78669e and this head. The Windows and Linux suites pass apart from the known environment baselines, and the Linux run covers the cfg(unix) search/grep integration tests. tree still needs a grammar, so it stays a follow-up.

It's still a draft while it sits on #4103. Say if you'd rather it be marked ready now.

@KuSh KuSh left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 1 — CHANGES REQUESTED

Claim: from a caller that doesn't expand globs (PowerShell, cmd), grep/rg, find, ls and wc expand their own file operands again, and wc reads its arguments with a declared grammar that decides operands, stdin forwarding and output mode.
Scope: accept. Checked against #4103 (KuSh): the three commits apply cleanly on its current head 577c220, and fmt, clippy and cargo test --all pass there (5915 passed, 0 failed); wincheck is clean.
Ran: Windows 11, PowerShell 5.1 and cmd with Git for Windows' usr\bin first on PATH: 40 rows × develop e87da19 / #4103 de78669 / 8a9e0b7, plus Git Bash rows run through rtk rewrite. Linux, GNU coreutils 9.12: 36 rows × de78669 / 8a9e0b7. Invariants: non-default targets (absolute paths, ~, braces, sub\*.txt, an existing a[1].txt, names with spaces), over-cap (3000 files, ~99K characters of names), under the hook, every decision. Savings on wc over src/cmds/system/*.rs: -l 49%, default 35%, --bytes 44% (3% before, when it was passed through raw), against the 20% floor (CONTRIBUTING.md).
Pins: 41 mutations over the decisions the three commits add: 27 killed, 14 survive. 8 of those are listed under 2 and 3. The other 6 change nothing observable: the trailing-separator is_dir check (Windows and Linux both refuse a.txt\), either of the two sorts alone (each covers the other), and the three tracked-label sites.
Matrix: executed this round; pin check: executed this round.
CI @8a9e0b74: not run yet (the fork workflow waits for a maintainer approval).

Blocks merge (4)

  1. src/cmds/system/wc_cmd.rs:210 — file names with whitespace, newly reached through --bytes. The formatter takes the last whitespace-separated word as the file name. Before this PR --bytes didn't select a mode, so its output went through raw and kept the name whole; it now goes through that formatter:

    • rtk wc --bytes 'my file.txt' a.txt → 3 file.txt / 6 a.txt / Σ 9. #4103 and v1.2.1 print 3 my file.txt. Reproduced on Linux and from Git Bash.

    The same parsing already truncates the name for -l, -w, -c, -m and the default output; that's the wc part of #3433, in the function this PR changes, and the fix is the same: the name is everything after the count columns. A correct fix passes:

    • rtk wc --bytes 'my file.txt' a.txt → 3 my file.txt
    • rtk wc -l 'my file.txt' a.txt → 1 my file.txt (now 1 file.txt)
    • rtk wc 'my file.txt' a.txt → 1L 1W 3B my file.txt (now 1L 1W 3B my)

    with a test holding a name with a space that fails when only the last word is kept.

  2. src/core/operand_glob.rs:36 — unpinned behaviour: the expansion itself never runs under test on Windows. Every caller test uses a marker expander, the operand_glob tests call expand() directly, and unix_leaves_operands_to_the_shell is a no-op on Windows. A Windows test binary where expand_operands returns its operands unchanged passes the same 4851 lib tests on Windows as the head does, and no integration test spawns rtk with an unexpanded glob. Two more mutations are invisible on Linux for the same reason: let paths = rest[..split].to_vec() in find_cmd.rs, and expand_file_operands(typed, Flavor::Bsd, …) in ls.rs. The test must spawn rtk without a shell on Windows, with Git for Windows' tools first on PATH (skipping when they are absent, like tests/windows_child_quoting_test.rs), in a temp tree holding a.txt, c.txt, b.rs, sub/x.rs and sub/d.txt:

    • rtk wc -l *.txt → a line for each of a.txt and c.txt, then the total
    • rtk grep -c x *.rs → 1
    • rtk find ./s* -name *.rs → x.rs
    • rtk ls -I *.txt sub → x.rs without d.txt (the -I value stays a pattern)

    All three mutations above must turn it red.

  3. Unpinned behaviour: four decisions whose correct behaviour no test checks. Each mutation below passes the full suite (5852 tests):

    • src/cmds/system/search.rs:286: drop "f" from the TokenKind::Short arm, or "file" from the long one. marked_paths(Engine::Grep, &["-f", "pats", "*.rs"]) must give ["-f", "pats", "<*.rs>"], and &["--file=pats", "*.rs"] must give ["--file=pats", "<*.rs>"]. Both rows are correct on Windows today.
    • src/cmds/system/find_cmd.rs:183: &original[options.len() + split..] → &original[options.len()..]. That mutant makes rtk find sub -name '*.rs' -exec echo hit {} ';' print hit sub/x.rs twice on Linux. A test that dispatches that argv must get Dispatch::Verbatim with the argv unchanged.
    • src/cmds/system/wc_cmd.rs:120: restore_double_dash(args) → args.to_vec(). With a file named -l, rtk wc -- -l must count the file (1L 1W 3B); on #4103 it read stdin and printed 0. restore_double_dash reads the process arguments, so this one needs an integration test through common::rtk_command() in a temp dir.
    • src/core/operand_glob.rs:291: drop the if hi != ']' guard. matches("[a-]x", "-x") must be true.
  4. src/core/operand_glob.rs:31 — large globs fail where develop expanded them. rtk now expands the operands itself, so the whole list has to fit in the child's command line, which Windows caps at 32,767 characters. On develop the MSYS child expanded *.txt after it started, with no such limit. From PowerShell, in a directory of 3000 files named longer_file_name_number_NNNN.txt:

    • rtk wc -l *.txt, rtk ls *.txt, rtk grep -c x *.txt → develop: all 3000 files, exit 0; this branch: Failed to spawn process: … (os error 206), exit 1.

    The fallback should keep this PR's expansion for everything that fits, and when the expanded command line would not fit, run the child as develop did: the glob operands go to an MSYS child unquoted so it expands them itself, while patterns, flags and their values stay quoted. That needs one narrow addition to ChildCommand (src/core/child_command.rs): a way to pass an argument that skips the glob quoting, plus the encoded command line's length, so the caller can decide before spawning. A native child such as rg has no expansion of its own; past the limit it should fail with an rtk message naming the limit (rg didn't expand globs from PowerShell on develop either). A correct fix passes:

    • the three rows above from PowerShell → the same output as develop (3000 counts and the total; 3000 names; 3000 name:1 lines)
    • rtk wc -l *.txt with a few files → still expanded by rtk (sub\*.txt, an existing a[1].txt and the other rows under "Checked and correct" unchanged)
    • rtk rg -c x *.txt past the limit → an rtk error that names the command-line limit, not os error 206

    with a test that fails when the fallback is removed (a Windows test like the one in 2, over a generated tree past the limit).

Optional — will not hold merge

  • find_cmd.rs:177: the legacy form with a verbatim action still passes its starting point unexpanded, while the same command without the action is expanded: rtk find '*.rs' 's*' -exec echo hit '{}' ';' → find: 's*': No such file or directory from PowerShell, while rtk find '*.rs' 's*' prints x.rs. Rebuilding that argv from paths as the non-legacy branch now does would cover it.
  • search.rs:286: expand_path_operands compares t.text against "regexp"/"file"/"files", while extract_pattern_path uses the grammar's t.is(…), so the doc comment's "the same reading" holds only while neither has another spelling. Matching through the grammar's flags would keep the two in step.
  • With -L the total line shows Σ 7, but for that column wc's total is the longest line, not a sum.
  • matches!(t.text, "regexp" | "file"), GNU_FLAGS, BSD_FLAGS and the ["c", "m", "l", "w", "L"] test rows are order-free lists left unsorted.

Follow-ups

  • rtk find s* -name '*.rs' (a glob first starting point with no separator) is read as the legacy pattern form and prints nothing with exit 0, on develop as well. It's the same misreading as #2995, where I added this case.

Checked and correct — no need to re-verify

  • Every row of the PR's Windows table, from PowerShell and cmd. Also: absolute paths, ~\…, {a,c}.txt, an existing a[1].txt kept, dotfiles skipped, *.TXT kept as written, an unmatched *.zz kept, -e/-f/--file with glob paths.
  • Git Bash: rtk rewrite output and every row match develop, apart from blocker 1; a quoted '*.txt' expands as develop's globify did.
  • Linux: ls, grep, rg and find output is unchanged. wc now compacts --bytes, --chars and -L, keeps both columns for -lL, forwards stdin for --total always and for - next to a file, and passes --files0-from - and --files0-from=- correctly.
  • The pin check's other 27 mutations are killed by the named tests, including both reads_stdin branches, BSD stop-at-first-operand, the -c/-m cancel and the abbreviation dialect.

Your questions

  • "Say if you'd rather it be marked ready now." → Mark it ready with the push that addresses this round. The fork CI run needs a maintainer approval, and it gets one on a ready PR.

Next

Blockers 1–4: the name parsing in filter_wc_output, a Windows integration test for the expansion, the four tests under 3, and the fallback for globs past the command-line limit.
Threads: 4 open (waiting on the author), 0 resolved this round.

Comment thread src/cmds/system/wc_cmd.rs Resolved
Comment thread src/core/operand_glob.rs Resolved
Comment thread src/cmds/system/search.rs Resolved
Comment thread src/core/operand_glob.rs
///
/// Call it only on arguments the command reads as file operands: a pattern, a
/// flag or a flag's value must reach the child as written.
pub fn expand_operands<I, S>(operands: I) -> Vec<String>

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Past 32,767 characters the expanded command line can't be spawned (os error 206 at 3000 files from PowerShell, where develop worked). Blocker 4 describes the fallback and its rows.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wc, ls and grep now match develop past the limit. Still open: find's starting points (two rows in the review that develop ran past the limit and this branch refuses), and tests for grep's plain capture path, the spawn check (the rg test can drop its which("rg") skip) and the legacy find rebuild.

KuSh and others added 6 commits November 25, 2026 03:15
`ChildArgExt::child_arg` requires every call site to remember a second
name for `arg`, and a call site can forget it, as `tree.rs` did (rtk-ai#4101).
`resolved_command` now returns `ChildCommand`, whose own `arg`/`args` do
the encoding, and which keeps its `Command` private: an extension trait
cannot replace std's inherent `arg`.

Every argument to a program cmd.exe does not parse is encoded literally
(`cmd` and `.bat`/`.cmd` shims are below). It is quoted whenever it
holds what Cygwin's `build_argv` and `globify` reinterpret: `"` or `'`,
one of `()*?[{}`, a leading `~`, a leading `@` (read as a response
file) and a line break (an argument separator). That closes rtk-ai#4102:
without it `rtk grep "it's"` reaches MSYS grep as `its`, and
`rtk grep '^\[TAG\]'` as the class `^[TAG]`. Glob metacharacters and a
leading `~` are in that set, so an MSYS child never glob- or
tilde-expands an argument rtk hands it: what the calling shell left
unexpanded reaches the tool as written. From cmd or PowerShell, which
leave globs to the program, `rtk cat *.rs` therefore fails on a missing
`*.rs`: without the tool's grammar a file operand cannot be told from a
pattern, and a pattern the child expands (`find -name '*.tmp' -delete`)
silently runs a different command. Arguments are encoded as UTF-16
code units, so an unpaired surrogate is protected like any other text.
The quoting is libuv's, exact for native children; for an MSYS child a
run of two or more backslashes that is not in front of a quote loses
one backslash of each pair (see rtk-ai#4326). A UNC path whose host starts
with a letter and is followed by a `\`, when it must be wrapped (for one
of those characters, a space or a tab), goes out with its `\\` and the
host's first letter before the opening quote, `\\s"rv\share\x(1)"`:
`globify` still reads it as a DOS path and keeps the `\\` that quoting
it whole would halve, so both parsers read it as written.

On Windows `cmd` parses its own command line and gets its script
verbatim, as `cmd /S /C "<script>"`: `/S` makes cmd strip exactly the
wrapping pair of quotes instead of applying its
two-quotes-around-an-executable heuristic. Other arguments to a program
cmd.exe parses stay on std's encoders, the batch-aware one for a
`.bat`/`.cmd` shim and the general one for `cmd`. A batch file is told
apart as std tells it: on the path Windows resolves, so `x.bat.`,
`x.bat\.` and `x.bat` with a trailing space are batch files, and a
verbatim `\\?\` or `\??\` path as written. Windows integration tests run
`rtk run -c` through cmd, with `echo "a b" & echo c` and with a quoted
program path holding a space, and a script with a quoted `&` and an exit
code through `run -c` and `run`/`err`/`test`/`summary --shell cmd`.

Only the `raw_arg` calls and that path resolution are Windows-only:
every other encoding decision is asserted on every platform. In a test
build the git `resolved_command` returns is isolated through a test-only
`ChildCommand` method, which applies `isolate_git_config` to the private
`Command`. Code that reads the argv, such as the usage guard, reads the
arguments as written, since on Windows the command line carries their
encoding.

`clippy.toml` disallows `std::process::Command::new`, and `src/lib.rs`
denies that lint outside test builds, so production code builds every
child through `ChildCommand::new`, the one allowed site. The workspace
lints allow it, so tests, integration tests and the other workspace
crates are not bound by it. `.semgrep.yml`'s `dynamic-command-execution`
and `interpreter-execution` also match `ChildCommand::new`.
`.claude/rules/rust-patterns.md` states the rule for agents, and the
contributor docs, `SECURITY.md` and the agent and skill guides build
production children through `ChildCommand` (`resolved_command`,
`tool_exec`).

Fixes rtk-ai#4102
Fixes rtk-ai#4116
Fixes rtk-ai#4288
Refs rtk-ai#4256

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
ChildCommand quotes every argument holding a glob character, so an MSYS
child no longer globifies it. That is right for a pattern and wrong for a
file operand: from PowerShell or cmd, `rtk grep x *.rs` and
`rtk find ./s* -name '*.rs'` reached the child as literal names and failed.

grep/rg and find now expand their own file operands, where their parsers
already know which arguments name files: grep/rg's path positionals and
find's starting points. Patterns, flags and flag values still reach the
child as written. core/operand_glob follows globify's rules as measured
against Git for Windows' ls, except that `\` separates components and an
operand naming an existing path is never expanded. On Unix operands pass
through, since the shell already expanded.

ls, wc and tree need a declared flag grammar before their operands can be
bounded, so they follow separately: ls on top of rtk-ai#4401, wc and tree with
grammars of their own.
From PowerShell or cmd, `rtk ls *.txt` reached the child as the literal
name `*.txt` (rtk-ai#4103 quotes it), so ls failed with `cannot access`.

ls now expands its free positionals, as read with the host flavour's
grammar from rtk-ai#5099, so a flag's value such as `-I '*.o'`, `--ignore
'*.o'` or `--hide='*~'` still reaches ls as a pattern, and BSD's boolean
`-I` leaves the next word an operand. The expansion runs once at the top
of `run`, so the filtered listing and `native_listing` name the same
files; the tracked command stays what the user typed.

operand_glob gains `expand_at`, which expands the arguments at the
indices a command's parser picked and keeps the rest; grep/rg now use it
too.
From PowerShell or cmd, `rtk wc -l *.txt` reached the child as the
literal name `*.txt` (rtk-ai#4103 quotes it). Bounding wc's operands needs a
grammar, so wc gets one per flavour, transcribed from each wc's help:
GNU (coreutils 8.32 and 9.4) `-c/-m/-l/-w/-L` with their long names,
`--files0-from F`, `--total WHEN`, `--help` and `--version`, with
getopt_long's unique-prefix abbreviation; BSD `-Lclmw` and `--libxo`.

Three decisions now read it instead of `starts_with('-')`:

- Operand expansion: the free positionals only, never `--files0-from`'s
  or `--total`'s value.
- Whether wc reads stdin: with no file operand, with `-` as one, or when
  the last `--files0-from` names `-`. Before, `--total always` counted
  `always` as a file.
- The output mode. A per-character scan of every dash-led argument read
  `--chars` as `-c` (bytes) and `--bytes` as no flag, so its output was
  passed through raw. Long names, abbreviations and `-L` now count as
  columns and `--`-protected operands don't. For BSD, options stop at
  the first operand (`wc f -l` names a file `-l` there) and `-c`/`-m`
  cancel, the last one winning, both checked against macOS's wc.

ls's `Flavor` and `HOST_FLAVOR` become `pub(super)` so wc reads the same
host flavour.
The compact formatter took the last whitespace-separated word of each line
as the file name, so `rtk wc -l 'my file.txt' a.txt` printed `1 file.txt`.
`--bytes` reached the same formatter once the wc grammar read it as a mode,
which is how it surfaced (rtk-ai#4544 review, blocker 1; the `wc` part of rtk-ai#3433).

Each line is now read as the count columns the mode prints (one, three, or
one per column asked for, so `Mixed` carries its count) followed by one
space and the name. The name keeps its spaces, a leading space included,
and a name made of digits is not read as another column. A line that does
not start with that many counts passes through trimmed, as before.

The tests use Git for Windows' wc output for `my file.txt` and `a.txt`.
rtk expands file operands itself now, so the whole list has to fit on the
child's command line, which Windows caps at 32,767 characters. Before, the
MSYS child expanded `*.txt` after it started, with no such limit: from
PowerShell in a directory of 3000 long names, `rtk wc -l *.txt`, `rtk ls
*.txt` and `rtk grep -c x *.txt` failed with `os error 206` where develop
listed every file (rtk-ai#4544 review, blocker 4).

`ChildCommand` gets the one narrow addition this needs:
- `glob_arg`: an argument sent with std's encoding, which an MSYS child's
  `globify` expands, for an operand the child should glob itself;
- `command_line_len`: the length std hands `CreateProcessW`, modelled on
  std's `make_command_line` and `append_arg`. A Windows test spawns a line
  one unit under the limit and one at it, so the model is checked against
  Windows rather than against itself;
- every spawn checks that length first, so a line that cannot fit fails
  with an error naming the limit instead of `os error 206`.

`operand_glob::for_child` expands as before and, when the expanded command
would not fit, returns the arguments as typed with the operands that would
have expanded marked. `wc`, `ls` (the filtered run and `native_listing`) and
`grep` (passthrough, capture and streaming) send those through `glob_arg`
and everything else literally, so a pattern, flag or flag value is still
never globbed. `rg` has no globbing of its own: past the limit it gets the
named error. Everything that fits is still expanded by rtk.

Also from the review:
- `tests/operand_glob_test.rs` spawns rtk with no shell, Git's `usr\bin`
  first on PATH (skipped without an MSYS `wc`): the expansion for wc, grep,
  find and `ls -I`, the fallback over 3000 files, rg's error, and
  `wc -- -l` counting the file (which runs on Unix too) (blockers 2, 3).
- `grep -f pats *.rs` / `--file=pats *.rs`, find's verbatim argv, and the
  matcher's `[a-]` are pinned (blocker 3).
- The legacy `find <pattern> <path>` form with a verbatim action rebuilds
  its starting points from the expanded list too.
- `expand_path_operands` matches `-e`/`-f`/`--files` through the grammar,
  as `extract_pattern_path` does.
- wc's flag lists and test rows are sorted.
@bharvey42
bharvey42 force-pushed the feat/windows-operand-glob branch from 8a9e0b7 to cf23e15 Compare November 25, 2026 06:05
@bharvey42

Copy link
Copy Markdown
Author

@KuSh, round 1 is addressed. The branch is rebased onto #4103's current head e36369a5 (the three earlier commits carried over unchanged, git range-diff =), with two new commits, and the PR is marked ready.

Blockers

  1. wc names with spaces (eda28ca6). The formatter reads each line as the count columns the mode prints (one, three, or one per column asked for, so Mixed carries its count), then one space, then the name. The name keeps its spaces, and a name made of digits isn't taken for another column. From PowerShell: wc --bytes 'my file.txt' a.txt → 3 my file.txt / 6 a.txt / Σ 9, and -l → 1 my file.txt (refactor(core): make MSYS-safe child argument encoding unforgettable #4103: 1 file.txt). The tests use Git for Windows' own wc output and fail when only the last word is kept. One note: end to end, the default rtk wc 'my file.txt' a.txt now prints wc's own 1 1 3 my file.txt lines. With one-digit counts the compact 1L 1W 3B my file.txt is longer, so the never-worse guard keeps the raw output.

  2. A Windows test that runs the expansion (tests/operand_glob_test.rs). It spawns rtk with no shell and Git's usr\bin first on PATH, and skips when there is no MSYS wc. It covers your four rows over a.txt, c.txt, b.rs, sub/x.rs, sub/d.txt. Each of the three mutations you named turns it red (identity expand_operands, rest[..split].to_vec(), Flavor::Bsd in ls).

  3. The four unpinned decisions. The -f pats *.rs and --file=pats *.rs rows are in only_path_operands_are_expanded. a_verbatim_action_reaches_find_with_its_argv_unchanged covers the find slice, with and without a leading -L. wc -- -l counts the file through common::rtk_command(), and that test also runs on Linux. [a-]x matches -x and ax but not bx.

  4. Past the command-line limit (cf23e158). ChildCommand gets the narrow addition you described:

    • glob_arg: std's encoding, for an operand the MSYS child should glob itself.
    • command_line_len: the length std hands CreateProcessW. A Windows test spawns hostname one unit under the limit (spawns) and at it (os error 206), so the model is checked against Windows rather than against itself.
    • Every spawn checks that length first.

    operand_glob::for_child expands as before. When the expanded command would not fit, it returns the arguments as typed, with the operands that would have expanded marked. wc, ls (both runs) and grep (passthrough, capture and streaming) send those through glob_arg and everything else literally. From PowerShell over 3000 longer_file_name_number_NNNN.txt files, everything exits 0: rtk wc -l *.txt → 3000 counts and Σ 3000, rtk ls *.txt → the listing, rtk grep -c x *.txt → 3000 name:1 lines. With a few files, rtk still does the expansion (the test in 2). rg has nothing to fall back to, so rtk rg -c x *.txt there prints the command line for …\rg.exe would be 99068 characters with its terminating NUL, past Windows' limit of 32767 (…) rather than os error 206. The same check covers find past the limit. Its starting points are not handed to the child to glob; say if you want that too.

Optional

  • Done:
    • The legacy find form with a verbatim action now rebuilds its starting points from the expanded list: rtk find '*.rs' 's*' -exec echo hit '{}' ';' → hit sub/x.rs.
    • expand_path_operands matches -e/-f/--files through the grammar's t.is(…), as extract_pattern_path does.
    • GNU_FLAGS, BSD_FLAGS and the short-flag test rows are sorted. The matches! list is gone.
  • Not done: the -L total. wc prints the longest line there, and rtk still labels it Σ. Fixing the label changes Mixed's output for every combination that includes -L, so I'd keep it for a separate change unless you'd rather have it here.

Pins: 13 mutations over this round's decisions. These are the expansion itself, find's starting points, ls's flavour, the fallback, rg's exclusion from it, glob_arg's encoding, the spawn check, the length model's quote escaping, restore_double_dash, grep's -f, find's verbatim slice, the [a-] guard, and the name read as the last word. All 13 are killed by named tests.

Ran:

  • Windows: cargo test --all --no-fail-fast gives 5521 passed and 1 failed across 78 targets. The failure is the core::stream invalid-UTF-8 baseline, which fails at stream.rs:845 on unmodified e36369a5.
  • Linux (aarch64, GNU grep 3.11, ripgrep 16.0, git 2.43) at cf23e158: 5925 passed and 1 failed across 78 targets. The failure is git_log_malformed_digit_run_propagates_real_git_error, git 2.43's wording, which fails the same way on e36369a5.
  • fmt and clippy are clean on both.
  • The description's table is re-run on e36369a5 vs cf23e158, with the new rows added.

@bharvey42
bharvey42 marked this pull request as ready for review November 25, 2026 06:05
Resolves the one conflict in src/core/mod.rs: develop's `pub mod invocation;`
and this branch's `pub mod operand_glob;` landed on the same line. Both are kept.

@KuSh KuSh left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 2 — CHANGES REQUESTED

Claim: from a caller that doesn't expand globs (PowerShell, cmd), grep/rg, find, ls and wc expand their own file operands again, falling back to the MSYS child's own expansion past Windows' command-line limit, and wc reads its arguments with a declared grammar.
Scope: accept (round 1). Checked against #4103 (KuSh): this head carries its current e36369a5 and develop bf1d1366, and the gate passes there.
Ran: Windows 11, PowerShell 5.1 and cmd with Git for Windows' usr\bin first on PATH: the round-1 rows plus this round's × develop bf1d136 / #4103 e36369a / 928627f, including the over-limit rows on 3000 files (wc, ls, ls -la, grep -c, grep, grep -l, three find forms, rg, a space in the operand) and the Git Bash rows run through rtk rewrite. Linux, GNU coreutils 9.12: the round-1 rows plus names with a space, a leading space or digits only, --total=only, -lw. Invariants: non-default targets, over-cap, under the hook, every decision. Savings unchanged from round 1, above the 20% floor (CONTRIBUTING.md).
Pins: 36 mutations over this push's decisions and round 1's survivors: 23 on Linux (lib tests and operand_glob_test), 13 on Windows (operand_glob_test on a Windows 11 VM, then the lib suite for the survivors). 27 killed. 9 survive: the 6 listed under 1 (one of them, rg's exclusion from the fallback, mutated on both platforms), plus two that change nothing observable (the digits == 0 guard, which the one-space check after it already covers, and native_listing's glob args, which only feed the never-worse comparison).
Matrix: executed this round; pin check: executed this round.
CI @928627fe: all green.

Thank you for this push. All four blockers were worked through carefully, every row was measured on real Windows against both builds, and the fallback came with a test that checks the length model against Windows itself. That makes this round short.

Blocks merge (1 of 4 left, frozen at round 1)

Blockers 1–3 are closed: the rows pass, and every mutation named under them now fails a test (test_multi_file_name_with_a_space_is_kept_whole, test_padded_columns_and_a_leading_space_in_a_name, unexpanded_globs_are_expanded_by_rtk, only_path_operands_are_expanded, a_verbatim_action_reaches_find_with_its_argv_unchanged, wc_counts_a_file_named_like_a_flag_after_double_dash, the_matcher_follows_glob_rules).

  1. src/core/operand_glob.rs:31 — globs past the command-line limit: wc, ls and grep now match develop (3000 counts, the listing, 3000 name:1 lines). Two parts are left.
    • find. Develop expanded its starting points in the MSYS child, so these worked there and this branch refuses them:

      • rtk find big/* -name '*_0001.txt' -exec echo hit '{}' ';' → develop: hit big/longer_file_name_number_0001.txt, exit 0; here: the command line for …\find.exe would be 111081 characters …, exit 1
      • rtk find big/* -name '*_0001.txt' -type f -newer b.rs → develop: the file, exit 0; here: the same refusal

      The rtk-native form (rtk find big/* -name '*_3000.txt' with nothing else) fails on develop too, so it's not part of this. A correct fix routes find's starting points through for_child for the verbatim and compress commands, and passes the two rows above, with a test that fails when that fallback is removed.

    • Tests for the fallback's other paths. Each of these mutations passes operand_glob_test and the Windows lib suite (4940 passed and the same 23 failures as the head, on the VM):

      • globs.push_operand(&mut cmd, path) → cmd.arg(path) in engine_command. That breaks plain rtk grep x *.txt past the limit (it gets "*.txt" quoted, which is #4103's No such file). The past-limit test runs grep only with -c, which takes the passthrough path. Add a plain grep x *.txt case.
      • Removing self.check_command_line()? from spawn(), output() or status(), and giving rg the fallback (if engine == Engine::Rg && false). rg_past_the_command_line_limit_names_the_limit is the only test through them, and it skips without rg, which neither the Windows CI runner nor my VM has. It doesn't need rg: without it, rtk rg -c x *.txt past the limit already prints the command line for rg would be 99010 characters … past Windows' limit of 32767. Dropping the which("rg") skip makes it run everywhere.
      • The legacy verbatim rebuild in find_cmd.rs: making the verbatim argv full.clone() for the legacy form brings back find: 's*': No such file or directory for rtk find '*.rs' 's*' -exec echo hit '{}' ';' from PowerShell. a_verbatim_action_reaches_find_with_its_argv_unchanged has no legacy case. A legacy row with a glob starting point, in the Windows test, must print hit sub/x.rs.

Optional — will not hold merge

  • Past the limit, rtk grep needle *.txt with one matching file prints needle without its file name, since paths holds one typed *.txt (develop does the same; below the limit this branch prints c.txt:three needle where develop printed three needle). Treating a child-globbed operand as several paths in wants_show_file would keep the name.
  • The refusal message suggests running from bash, but for a native program such as rg bash hits the same limit when it starts the .exe (#4210). The hint fits only when an MSYS child was left the globs.
  • wc --help in coreutils 9.12 lists --debug, which GNU_FLAGS doesn't declare.
  • BSD_FLAGS and its test rows are in byte order (L, c, l, m, w); sorted case-insensitively with byte order as tie-break they read c, L, l, m, w.

Follow-ups

  • #5321 wc -L: the total line is labelled Σ but holds the longest line — kept out of this PR at your suggestion; filed.

Checked and correct — no need to re-verify

  • Every round-1 row again on develop / #4103 / this head, from PowerShell, cmd and Git Bash; rtk wc -l *.txt from Git Bash now keeps my file.txt whole too.
  • Past the limit, an operand with a space (my big/*.txt) fails as it does on develop, where globify doesn't expand a quoted glob either; below the limit rtk's own expansion handles it.
  • std_encoded_len and command_line_len against std's encoder: 8 of the mutations above (quote rules, backslash runs, program quotes, the limit comparison, cmd.exe programs) fail the unit tests, and command_line_len_is_exact_at_windows_limit ran on the Windows CI job.
  • wc parsing on Linux: names with a space, a leading space, digits only (2024), --total=only, -lw, and the raw fallback for the default columns when the compact form is longer.
  • Full gate on this head: fmt and clippy clean, cargo test --all 5966 passed, 0 failed.

Your questions

  • "the -L total … I'd keep it for a separate change unless you'd rather have it here" → Separate change: #5321.
  • "The same check covers find past the limit. Its starting points are not handed to the child to glob; say if you want that too." → Yes: develop handled the two find rows above past the limit, so it's the remaining part of blocker 1.

Next

find's starting points through for_child, and the three test additions under 1.
Threads: 1 open (the limit, waiting on the author), 3 resolved this round (fixed).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants