Skip to content

refactor(cli): migrate to Cobra framework for shell completion support - #625

Merged
lizhengfeng101 merged 5 commits into
mainfrom
refactor/cobra-cli-migration
Jul 31, 2026
Merged

lizhengfeng101 merged 5 commits into
mainfrom
refactor/cobra-cli-migration

Conversation

@lizhengfeng101

Copy link
Copy Markdown
Contributor

Summary

Migrate the CLI from a hand-rolled ocrFlagSet + switch dispatch to spf13/cobra, enabling native shell completion support requested in #576.

  • New files: root.go, completion.go, shared_flags.go, compat_test.go
  • Deleted: flags.go (custom ocrFlagSet, expandShortFlags, all parseXxxFlags functions)
  • Rewritten: all *_cmd.go files now use cobra.Command with RunE
  • Net result: -334 lines, zero new dependencies in go.sum (cobra was already an indirect dep of the MCP SDK)

Behavioral changes

Aspect Before After
Shell completion ❌ None ✅ ocr completion [bash|zsh|fish|powershell]
Misspelled command "unknown command: revew" "Did you mean this? review"
Unknown flag Dumps entire flag list Clean one-line error
ocr review somefile.go Silently ignores positional arg Rejects with clear error
Binary size 61MB 61MB (no change)

All existing flag names, short forms, defaults, and validation error messages are preserved. Verified via side-by-side comparison with the main branch binary.

Verification

  • make check passes (gofmt + go vet)
  • make test passes (all 23 packages, including -race)
  • Cross-compilation: linux/amd64, linux/arm64, windows/amd64, darwin/amd64
  • Side-by-side behavioral comparison with main branch binary for all commands and error paths
  • Shell completion generates valid zsh/bash/fish scripts

Related

Closes #576

Replace the hand-rolled ocrFlagSet + switch dispatch with spf13/cobra,
enabling native bash/zsh/fish/powershell completion via `ocr completion`.

Key changes:
- Add root.go (rootCmd definition, version flag with -V shorthand)
- Add completion.go (ocr completion [bash|zsh|fish|powershell])
- Add shared_flags.go (reusable flag registration helpers + validation)
- Rewrite all *_cmd.go to use cobra.Command with RunE
- Delete flags.go (ocrFlagSet, expandShortFlags, parseXxxFlags)
- Add compat_test.go (test compatibility wrappers for existing tests)
- Promote github.com/spf13/cobra from indirect to direct dependency

Behavioral improvements over the previous implementation:
- Shell completion for all commands, flags, and enum values
- "Did you mean?" suggestions for misspelled commands
- cobra.NoArgs on review/scan prevents silent positional arg ignoring
- Cleaner error messages on unknown flags (no full flag dump)
- Consistent help output format across all subcommands

Closes #576
@github-actions

github-actions Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

🔍 OpenCodeReview found 3 issue(s) in this PR.

  • ✅ Successfully posted inline: 3 comment(s)

Comment on lines +22 to +24
var sessionListRepoDir string
var sessionListJSON bool
var sessionListLimit int

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[maintainability · medium]
Inconsistent flag storage pattern: every other command refactored in this PR (reviewOptions, scanOptions, viewerOptions, delegateOptions) groups its flags into a struct, but session commands use five separate package-level variables. Consider defining sessionListOptions and sessionShowOptions structs (or a single sessionOptions struct) to match the convention established by the sibling commands. This improves cohesion, makes it easier to pass options as a unit, and avoids scattering related state across multiple globals.

Comment on lines +111 to +114
if opts.maxTools > 0 && opts.maxTools < minMaxTools {
fmt.Fprintf(os.Stderr, "[ocr] --max-tools %d is below minimum %d, using %d\n", opts.maxTools, minMaxTools, minMaxTools)
opts.maxTools = minMaxTools
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[maintainability · low]
This validation function mutates the input opts as a side effect (adjusting maxTools from a sub-minimum value to 10). While this works in the current call site (the RunE closure passes the same pointer that executeReview later reads), it violates the principle-of-least-surprise for a function named validate*. If a future caller invokes validation more than once, or inspects opts.maxTools after validation expecting the user-supplied value, the mutation will be surprising.

Consider either:

  1. Renaming to normalizeReviewOptions / validateAndNormalizeReviewOptions to make the mutation explicit, or
  2. Returning the corrected value separately so the caller decides whether to apply it.

Comment thread cmd/opencodereview/viewer_cmd.go Resolved
Prevents `ocr viewer localhost:3000` from silently ignoring the
positional argument and starting on the default address.
Consistent with reviewCmd and scanCmd.
Cobra only suggests corrections for unknown subcommands, not flags.
Add a levenshtein-distance based suggestion that fires when cobra
returns an "unknown flag" error, matching the same UX pattern.

Examples:
  --hel     → Did you mean this? --help
  --audienc → Did you mean this? --audience
  --comit   → Did you mean this? --commit
After the Cobra migration, pflag is directly imported but was still
marked as indirect in go.mod, causing CI's go-mod-tidy check to fail.

@css521 css521 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.

LGTM

@MuoDoo MuoDoo 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.

LGTM

…lag errors

Replace hand-rolled argument validation in configSetCmd/configUnsetCmd
with cobra.ExactArgs, and move flag typo suggestions from post-hoc error
string parsing into SetFlagErrorFunc where cobra provides the command
context directly.

@MuoDoo MuoDoo 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.

LGTM

@lizhengfeng101
lizhengfeng101 merged commit 80a5794 into main Jul 31, 2026
10 checks passed
@lizhengfeng101
lizhengfeng101 deleted the refactor/cobra-cli-migration branch July 31, 2026 08:56
Gongyl01 added a commit to Gongyl01/open-code-review that referenced this pull request Jul 31, 2026
冲突解决:
- cmd/opencodereview/flags.go: 接受 upstream 删除(alibaba#625 迁移到 Cobra),
  将 --max-tokens-budget 的说明文案迁移到 shared_flags.go 的 addConcurrencyFlags
- internal/viewer/store.go: SessionSummary 取双方字段并集(manifest 终态 + CommentCount);
  LoadSession 同时保留 CommentCount 统计与 readErr 返回
- internal/viewer/templates/sessions.html: 同时保留 Status 与 Comments 两列

另修复两处自动合并后编译失败:
- store.go ListSessions: 本分支已将 scanner 循环重构为 readJSONLLines 回调,
  alibaba#627 新增的 continue 落入闭包,改为 return
- compat_test.go: 补 runReview 兼容包装(alibaba#625 已拆为 reviewCmd + executeReview)

go build / go vet / go test ./... 全部通过。
kall pushed a commit to kall/open-code-review that referenced this pull request Aug 14, 2026
Three breakage classes from the merge, in one unit because the build does
not compile until all three are fixed:

- Rewrite the old module path to github.com/alibaba/open-code-review in
  core_cmd.go, core_diff.go and core_diff_test.go (alibaba#526).
- Replace the last stale helper call with the model.Diff method the branch
  extracted it into (internal/agent/agent.go).
- Re-register the core command group as cobra.Command trees after main
  deleted cmd/opencodereview/flags.go in the Cobra migration (alibaba#625). The
  newOcrFlagSet-based parsing in five run helpers is gone; flags now bind
  through Flags() and the helpers take explicit parameters.

Conventions carried over from the surrounding commands: the parent rejects
unknown subcommands and prints help when bare (alibaba#660, alibaba#694); rule and prompt
validate positional count through exactArgs so the error carries the
command's own usage (alibaba#749, alibaba#892); repo and diff flags reuse the shared
helpers; prompt phases are declared in ValidArgs for completion (alibaba#625).

The manual dispatcher and its hand-written usage block are dropped -- Cobra
owns both now -- and core_cmd_test.go trades its argv-slice calls for tests
that exercise the wiring through rootCmd.
Githab-capibara added a commit to Githab-capibara/open-code-review that referenced this pull request Sep 17, 2026
alibaba#625)

* refactor(cli): migrate to Cobra framework for shell completion support

Replace the hand-rolled ocrFlagSet + switch dispatch with spf13/cobra,
enabling native bash/zsh/fish/powershell completion via `ocr completion`.

Key changes:
- Add root.go (rootCmd definition, version flag with -V shorthand)
- Add completion.go (ocr completion [bash|zsh|fish|powershell])
- Add shared_flags.go (reusable flag registration helpers + validation)
- Rewrite all *_cmd.go to use cobra.Command with RunE
- Delete flags.go (ocrFlagSet, expandShortFlags, parseXxxFlags)
- Add compat_test.go (test compatibility wrappers for existing tests)
- Promote github.com/spf13/cobra from indirect to direct dependency

Behavioral improvements over the previous implementation:
- Shell completion for all commands, flags, and enum values
- "Did you mean?" suggestions for misspelled commands
- cobra.NoArgs on review/scan prevents silent positional arg ignoring
- Cleaner error messages on unknown flags (no full flag dump)
- Consistent help output format across all subcommands

Closes alibaba#576

* fix(cli): add Args: cobra.NoArgs to viewerCmd

Prevents `ocr viewer localhost:3000` from silently ignoring the
positional argument and starting on the default address.
Consistent with reviewCmd and scanCmd.

* feat(cli): add "Did you mean?" suggestions for misspelled flags

Cobra only suggests corrections for unknown subcommands, not flags.
Add a levenshtein-distance based suggestion that fires when cobra
returns an "unknown flag" error, matching the same UX pattern.

Examples:
  --hel     → Did you mean this? --help
  --audienc → Did you mean this? --audience
  --comit   → Did you mean this? --commit

* fix(deps): promote spf13/pflag to direct dependency

After the Cobra migration, pflag is directly imported but was still
marked as indirect in go.mod, causing CI's go-mod-tidy check to fail.

* refactor(cli): use idiomatic cobra patterns for args validation and flag errors

Replace hand-rolled argument validation in configSetCmd/configUnsetCmd
with cobra.ExactArgs, and move flag typo suggestions from post-hoc error
string parsing into SetFlagErrorFunc where cobra provides the command
context directly.
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.

Migrate to cli framework for proper completion support

3 participants