Repository navigation
Add shell completion generation - #764
Conversation
Add zero completions for bash, zsh, fish, PowerShell, and Elvish using one shared command tree that covers aliases, nested commands, root flags, and common exec flags. Validate missing and unsupported shell arguments as usage errors and document safe installation examples in command help. Refs #499
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
WalkthroughAdds ChangesShell completions
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant CLI
participant runCompletions
participant completionContexts
participant ShellWriter
participant stdout
CLI->>runCompletions: dispatch completions <shell>
runCompletions->>completionContexts: derive command contexts
runCompletions->>ShellWriter: generate selected shell script
ShellWriter->>stdout: write completion script
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/cli/completions.go`:
- Around line 145-164: Update writeCompletionsHelp to include an Elvish
installation example alongside the existing shell completion examples, using the
supported elvish target and an appropriate output or sourcing form.
- Line 35: Update the completions command node in completionContexts to include
child names for every static shell supported by runCompletions, matching the
cases in its switch. Keep the existing completions names and help flags
unchanged, and exclude only the dynamic completion sources.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 539d73c4-d9eb-4545-8bbc-04ef03d6bc00
📒 Files selected for processing (3)
internal/cli/app.gointernal/cli/completions.gointernal/cli/completions_test.go
Zero automated PR reviewVerdict: No blockers found Blockers
Validation
ScopeHead: This deterministic review checks validation status and basic diff hygiene. A human reviewer still owns product judgment and design quality. |
Expose every supported shell as a completions subcommand candidate and document Elvish activation. Refs #499
gnanam1990
left a comment
There was a problem hiding this comment.
REQUEST CHANGES — the elvish script is syntactically invalid and cannot be sourced, and the test suite can't detect that. Everything else is in good shape; bash and zsh are genuinely solid.
Up front on method, because it matters for how much weight to give each part: I executed bash and zsh (both installed here) — syntax checks and real functional completion. fish, powershell and elvish are not installed, so those I reviewed by reading the generated output. The elvish finding below does not depend on running elvish: it's an objective brace count.
[Blocker] The elvish script is unparseable — every if/elif block is opened and never closed
writeElvishCompletions (internal/cli/completions.go:376-384, and again at :388-396) emits an opening { per branch but only writes one closing } after the whole loop:
fmt.Fprintf(w, " %s (== $context'|'$token %q) {\n set context = %q\n", keyword, key, transitions[key])Generated output:
if (== $context'|'$token "auth|chatgpt") {
set context = "auth chatgpt"
elif (== $context'|'$token "auth|login") {
set context = "auth login"
elif ...Counting the emitted file: 379 { against 4 }. The transition loop alone opens 1 if + 187 elif blocks and closes exactly one. The candidates section at the bottom has the identical defect:
elif (== $context "worktrees") {
put prepare
elif (== $context "worktrees prepare") {
put
}
}Elvish requires each block closed before the next keyword — if $cond { body } elif $cond2 { body2 }. As emitted, this cannot parse, so zero completions elvish produces a file that fails on source. For comparison, the other four are all balanced: bash 3/3, zsh 3/3, powershell 384/384, and fish correctly uses one switch … 188 case … one end.
There is a second, independent bug in the same function. Elvish's == is numeric equality (eq is the general value comparison; older releases used ==s for strings). (== $context'|'$token "auth|chatgpt") compares strings with a numeric operator, so even with balanced braces every comparison would fail at runtime.
Fix: close each branch and switch the operator — } elif (eq $context'|'$token "…") { — with a final } after the chain. Same in both loops.
For what it's worth, $args[1..-1] is correct and I'd leave it alone: Elvish ranges are upper-exclusive, so this deliberately drops the word currently being completed, which is what a completer wants.
[Major] The tests cannot detect a malformed script — which is why the above shipped green
TestCompletionsGeneratesEverySupportedShell (internal/cli/completions_test.go:63-91) asserts only three things per shell: exit success, one marker substring, and the four substrings daemon / mcp oauth / sandbox grants / --output-format. The broken elvish output contains all five — I checked each individually — so go test ./internal/cli/ -run TestCompletion passes clean against a file that no elvish can parse.
That's the gap worth closing regardless of the blocker: the suite validates content and never shape, so any future structural regression in any of the five emitters lands silently.
Fix, cheapest first:
- Assert structural balance per shell in the existing table — brace balance for elvish/powershell,
switch/endfor fish. That alone catches this class. - Better, for the two shells CI already has: shell out to
bash -nandzsh -non the generated script, skipping viaexec.LookPathwhen absent. I ran both here and they pass, so this is a cheap, non-flaky guard.
Minor
Agreed with CodeRabbit's two, and I confirmed the first empirically rather than by reading — sourcing the generated bash script and driving the completion function gives:
[zero completions | cword=2] -> -h --help
so the completion generator can't complete its own shell argument. The five shell names are a static list already present in the switch at :125-138; adding children: leafNodes("bash","zsh","fish","powershell","elvish") to the completions node at :35 fixes it.
Nit
Nothing fails when a new CLI command is added without updating completionRoot. The tree is accurate today (see below), but it's hand-maintained with no guard, so it will drift silently. A test comparing the root node's names against the command list in app.go would pin it.
What's genuinely good here
I want to be concrete about this rather than polite, because the parts that work are the parts that were hard:
- bash is correct, not just syntactically valid.
bash -npasses, and driving_zerodirectly withCOMP_WORDS/COMP_CWORDreturns the right candidates at every position I tried — top level, a partial prefix (zero ex→exec), a nested subcommand (zero sessions→list children lineage tree rewind-plan rewind compact-plan), and flags after a subcommand (zero exec --→ the full flag set). zsh passeszsh -n. - The command tree is accurate and complete. Every one of the 33 commands in
zero --helpis completed — no gaps. It also completes 13 undocumented aliases (backend,change,init,plugin,repoinfo,repomap,session,skill,specialists,tool,trust,upgrade,worktree), and I ran each one against the built binary to confirm they're all real, working aliases rather than phantom entries. That's better than most hand-maintained completion trees manage. - One shared tree feeding five emitters is the right structure, and
completionContextshandling alias expansion into multiple paths is a nice touch — it's whyzero session <TAB>andzero sessions <TAB>both work. - Everything interpolated into the scripts is a compile-time constant from
completionRoot— nothing from argv, env, or the filesystem — so there's no injection surface here at all. I looked specifically because sourced shell scripts are a natural place for it.
Verification
gofmt clean on all three files, go vet ./internal/cli/ clean, go test ./internal/cli/ -run TestCompletion passes (which is precisely the problem — see the Major). All five shells generate non-empty output with exit 0. No pre-existing failures were implicated; I didn't need a base comparison since nothing failed.
Merge is kevin's call per the program gate.
Close generated Elvish conditional branches, use value equality, and validate generated script structure plus native Bash and Zsh syntax. Refs #499
gnanam1990
left a comment
There was a problem hiding this comment.
APPROVE. Re-reviewed at c0a1cbe. The blocker is fixed on both counts, the test gap is closed better than I suggested, and both minors are done.
I went further than reading the diff this round: I installed elvish 0.21.0 and ran the real interpreter against both versions of the script, so the central claim is now verified rather than inferred.
Blocker — fixed, and confirmed with real elvish
Both halves are addressed:
- Brace structure. The generator now emits
} elif (…) {, and the file balances at 389{/ 389}(was 379/4). - Operator.
(== …)→(eq …): zero occurrences of(==remain, 387 of(eq. This was the half that would still have failed at runtime even with balanced braces, so I'm glad it was caught too.
Verified by execution, not inspection:
OLD (056373f): elvish -compileonly -> Multiple parse errors: should be '}'
NEW (c0a1cbe): elvish -compileonly -> parses and compiles cleanly
One note so the output isn't misread if you try this yourself: running elvish -compileonly on the script as-shipped reports cannot find variable $edit:completion:arg-completer. That is not a defect — edit: is the interactive editor module and isn't bound in non-interactive mode. Stubbing line 2 to a plain var isolates syntax from module availability, and with that done the new script compiles clean while the old one still fails on parse errors. So the fix is genuinely correct, not merely balanced.
If you ever want elvish in CI, elvish -compileonly is the equivalent of bash -n and would slot straight into assertNativeShellSyntax — though pulling in an elvish binary is a heavier lift than the two shells already covered, so I wouldn't push for it.
Major — fixed, and mutation-tested
Both suggestions landed, plus one I didn't think of:
assertBalancedBracesfor powershell/elvish (completions_test.go:93)assertNativeShellSyntaxshelling out tobash -n/zsh -n, gated onexec.LookPathwitht.Skipfwhen the shell is absent (:135) — including the skip detail, so this won't turn into a flaky Windows failureassertBalancedFishBlocks(:101), a proper depth counter overfunction/for/switch/ifvsend, which is more precise than the brace count I proposed and correctly models fish's grammar
The important question is whether the new guard would actually have caught the original bug, so I mutation-tested it — restored the old generator, kept the new tests:
--- FAIL: TestCompletionsGeneratesEverySupportedShell/elvish
completions_test.go:97: unbalanced braces: 379 opening, 4 closing
It fires, with the exact numbers from my review. That's a real regression test, not a decorative one.
Minors — both fixed
zero completions <TAB>now completes the shell list. Verified functionally by sourcing the generated bash script and driving_zero:[zero completions |cw=2] -> -h --help bash zsh fish powershell elvish.TestCompletionTreeCoversAliasesNestingAndCommonFlagsnow pins it too.- The elvish install example is in the help (
eval (zero completions elvish | slurp)) and asserted inTestCompletionsHelpAndRootHelp.
One nit, non-blocking
assertBalancedBraces counts braces anywhere in the text, including inside quoted strings. That's sound today because every command name, alias and flag in completionRoot is brace-free, so the count can't be skewed. But it would silently mis-handle a future command containing { or }. Not worth changing now — the fish checker's line-oriented approach is the model if it ever matters.
Verification
Re-ran everything on a clean tree at c0a1cbe:
- All five shells generate non-empty output, exit 0; all five balance.
bash -nandzsh -npass. bash is still functionally correct — spot-checked top level, nested (zero sessions→ the seven subcommands), and prefix filtering (zero exec --mod→--mode --model).gofmtandgo vet ./internal/cli/clean.go test ./internal/cli/ -run TestCompletion— all four tests pass, including the five new per-shell subtests.
Good turnaround, and the elvish fix addressed the operator bug rather than just silencing the brace count — which is the difference between it parsing and it working.
Merge is kevin's call per the program gate.
Summary
zero completions <shell>for Bash, Zsh, Fish, PowerShell, and Elvishexecflags from one shared command treeVerification
make fmt-checkgo vet ./...go test ./...go run ./cmd/zero-release buildgo run ./cmd/zero-release smokego run golang.org/x/vuln/cmd/govulncheck@v1.3.0 ./...git diff HEAD --checkCloses #499
Summary by CodeRabbit
New Features
completionscommand to generate shell completion scripts.completionsand improved completion coverage for nested commands/aliases and common options.Tests
completionshelp output, shell argument validation, and generation for every supported shell.