You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
github.com/spf13/cobra is the de facto standard CLI framework for Go. It provides command/subcommand structure, flag parsing (wrapping pflag), shell completions (Bash/Zsh/Fish/PowerShell), argument validation, PersistentPreRun hooks, Active Help, and more. Used by Docker, Kubernetes, GitHub CLI, and many other prominent Go projects.
Current Usage in gh-aw
Cobra is the backbone of the awmg CLI — every user-facing entry point goes through it.
Files: 12 files in internal/cmd/ (9 non-test, 3 test helpers)
Import Count: ~11 production imports + ~7 in test files
Key APIs Used:
cobra.Command{} — root command + proxy subcommand
cobra.EnableTraverseRunHooks — ensures parent PersistentPreRunE propagates to children
The codebase shows excellent understanding of cobra's extension points. The modular RegisterFlag() / flagRegistrars pattern (in flags.go) is particularly elegant — feature flags each live in their own flags_*.go file, avoiding merge conflicts.
Research Findings
Best Practices Observed ✅
SilenceErrors: true + manual fmt.Fprintln(os.Stderr, err) in Execute() — prevents double-printing errors; this is the canonical cobra pattern.
SilenceUsage: true — hides usage on runtime errors, reducing noise in production.
cobra.EnableTraverseRunHooks = true — correctly set in init() so parent PersistentPreRunE runs when a child also defines one; documented and tested.
cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs) — idiomatic combination of arg validators.
GroupID on subcommands with matching AddGroup() — organises help output cleanly.
Active Help via cobra.AppendActiveHelp on the root ValidArgsFunction — great UX.
Per-feature flag files using RegisterFlag() — scales well and reduces conflicts.
Recent cobra Updates (v1.10.x)
GenBashCompletionV2(w, includeDesc) — newer Bash v4 completion generator with description support; parallel to the PowerShell ...WithDesc variant already used.
cmd.MarkFlagFilename(name, extensions...) — convenience shortcut replacing RegisterFlagCompletionFunc for filename flags.
cmd.SetContext(ctx) — set context on a command before execution (useful in tests).
cobra.FixedCompletions — already used ✅.
Improvement Opportunities
🏃 Quick Wins
1. Proxy shutdown uses Close() instead of graceful Shutdown()
In proxy.go, runProxy ends with:
returnhttpServer.Close()
The root command (root.go) correctly drains in-flight requests:
Close() immediately closes all active connections, aborting in-flight GitHub API requests mid-stream. Replace with the same Shutdown() + timeout pattern used in the root command.
2. Proxy guards-mode default is hardcoded instead of using difc.DefaultEnforcementMode()
Hardcoding "filter" creates a silent inconsistency if the environment-variable default ever changes. Replace with difc.DefaultEnforcementMode().
3. Verbosity level 1 produces unexpected noise
In preRun:
case 1:
log.Printf("Logging level: info (-v)")
Level 1 (-v) is supposed to be "info level" but it just emits one log.Printf to stderr and changes nothing. Either remove this log line or make it do something meaningful.
✨ Feature Opportunities
4. Switch Bash completions to GenBashCompletionV2 for description support
Cobra v1.6+ offers GenBashCompletionV2(w, includeDesc) which generates Bash v4-compatible scripts with completion descriptions (matching the PowerShell ...WithDesc already used). Bash v3 users are rare on modern Linux and macOS:
This is more concise and idiomatic for simple extension-filter completions.
📐 Best Practice Alignment
6. SetErrPrefix has no visible effect with SilenceErrors: true
rootCmd.SetErrPrefix("MCPG Error:") is set but SilenceErrors: true means cobra never calls its internal error printer, so the prefix is never shown. Either:
Remove SetErrPrefix (the prefix is produced by the Execute() caller anyway), or
Use the prefix explicitly in Execute():
fmt.Fprintln(os.Stderr, "MCPG Error:", err)
7. cmd.SetErr() in tests for hermetic error capture
Several tests create &cobra.Command{} instances but let stderr bleed to the real process. Using cmd.SetErr(&bytes.Buffer{}) in test setup makes tests hermetic and prevents CI log noise.
🔧 General Improvements
8. Proxy --tls-dir relationship with --tls not validated early
--tls-dir is only meaningful when --tls is enabled, but there is no early validation or MarkFlagsMutuallyExclusive-style enforcement. A PersistentPreRunE check or flag group would catch the misconfiguration before the server starts up.
stretchr/testify@12f8b56list_commits: has lower integrity than agent requires. The agent cannot read data with integrity below "unapproved".
spf13/cobra@ad460ealist_commits: has lower integrity than agent requires. The agent cannot read data with integrity below "unapproved".
itchyny/gojq@b7ebffblist_commits: has lower integrity than agent requires. The agent cannot read data with integrity below "unapproved".
santhosh-tekuri/jsonschema@180cde3list_commits: has lower integrity than agent requires. The agent cannot read data with integrity below "unapproved".
wazero/wazero@5500f5clist_commits: has lower integrity than agent requires. The agent cannot read data with integrity below "unapproved".
list_tags list_tags: has lower integrity than agent requires. The agent cannot read data with integrity below "unapproved".
https://github.com/spf13/cobrasearch_repositories: has lower integrity than agent requires. The agent cannot read data with integrity below "unapproved".
... and 30 more items
To allow these resources, lower min-integrity in your GitHub frontmatter:
🐹 Go Fan Report: spf13/cobra
Module Overview
github.com/spf13/cobrais the de facto standard CLI framework for Go. It provides command/subcommand structure, flag parsing (wrappingpflag), shell completions (Bash/Zsh/Fish/PowerShell), argument validation, PersistentPreRun hooks, Active Help, and more. Used by Docker, Kubernetes, GitHub CLI, and many other prominent Go projects.Current Usage in gh-aw
Cobra is the backbone of the
awmgCLI — every user-facing entry point goes through it.internal/cmd/(9 non-test, 3 test helpers)cobra.Command{}— root command +proxysubcommandcobra.EnableTraverseRunHooks— ensures parent PersistentPreRunE propagates to childrencmd.SetErrPrefix(),cmd.SetVersionTemplate()— custom brandingcmd.Flags().{BoolVar,StringVar,StringVarP,IntVar,Float64Var,CountVarP,StringSliceVar}— rich flag typescmd.MarkFlagsMutuallyExclusive(),cmd.MarkFlagsOneRequired(),cmd.MarkFlagRequired()— flag constraint groupscmd.RegisterFlagCompletionFunc(),cobra.FixedCompletions()— enum/file completionscobra.ShellCompDirective{FilterFileExt,FilterDirs,NoFileComp}— completion directivescobra.AppendActiveHelp()— contextual tips in completionscobra.Group{}/cmd.AddGroup()— grouped subcommand helpcobra.MatchAll()/cobra.ExactArgs()/cobra.OnlyValidArgs()/cobra.NoArgs— argument validatorscmd.Context(),cmd.Flags().Changed(),cmd.GetFlagCompletionFunc()— runtime introspectionGenBashCompletion,GenZshCompletion,GenFishCompletion,GenPowerShellCompletionWithDesc— script generationThe codebase shows excellent understanding of cobra's extension points. The modular
RegisterFlag()/flagRegistrarspattern (inflags.go) is particularly elegant — feature flags each live in their ownflags_*.gofile, avoiding merge conflicts.Research Findings
Best Practices Observed ✅
SilenceErrors: true+ manualfmt.Fprintln(os.Stderr, err)inExecute()— prevents double-printing errors; this is the canonical cobra pattern.SilenceUsage: true— hides usage on runtime errors, reducing noise in production.cobra.EnableTraverseRunHooks = true— correctly set ininit()so parentPersistentPreRunEruns when a child also defines one; documented and tested.cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs)— idiomatic combination of arg validators.GroupIDon subcommands with matchingAddGroup()— organises help output cleanly.cobra.AppendActiveHelpon the rootValidArgsFunction— great UX.RegisterFlag()— scales well and reduces conflicts.Recent cobra Updates (v1.10.x)
GenBashCompletionV2(w, includeDesc)— newer Bash v4 completion generator with description support; parallel to the PowerShell...WithDescvariant already used.cmd.MarkFlagFilename(name, extensions...)— convenience shortcut replacingRegisterFlagCompletionFuncfor filename flags.cmd.SetContext(ctx)— set context on a command before execution (useful in tests).cobra.FixedCompletions— already used ✅.Improvement Opportunities
🏃 Quick Wins
1. Proxy shutdown uses
Close()instead of gracefulShutdown()In
proxy.go,runProxyends with:The root command (
root.go) correctly drains in-flight requests:Close()immediately closes all active connections, aborting in-flight GitHub API requests mid-stream. Replace with the sameShutdown()+ timeout pattern used in the root command.2. Proxy
guards-modedefault is hardcoded instead of usingdifc.DefaultEnforcementMode()In
proxy.go:The root command correctly calls:
Hardcoding
"filter"creates a silent inconsistency if the environment-variable default ever changes. Replace withdifc.DefaultEnforcementMode().3. Verbosity level 1 produces unexpected noise
In
preRun:Level 1 (
-v) is supposed to be "info level" but it just emits onelog.Printfto stderr and changes nothing. Either remove this log line or make it do something meaningful.✨ Feature Opportunities
4. Switch Bash completions to
GenBashCompletionV2for description supportCurrently:
Cobra v1.6+ offers
GenBashCompletionV2(w, includeDesc)which generates Bash v4-compatible scripts with completion descriptions (matching the PowerShell...WithDescalready used). Bash v3 users are rare on modern Linux and macOS:5. Replace
RegisterFlagCompletionFuncwithcmd.MarkFlagFilename()for file-extension flagsIn
flags.go:Cobra has a built-in shortcut:
This is more concise and idiomatic for simple extension-filter completions.
📐 Best Practice Alignment
6.
SetErrPrefixhas no visible effect withSilenceErrors: truerootCmd.SetErrPrefix("MCPG Error:")is set butSilenceErrors: truemeans cobra never calls its internal error printer, so the prefix is never shown. Either:SetErrPrefix(the prefix is produced by theExecute()caller anyway), orExecute():7.
cmd.SetErr()in tests for hermetic error captureSeveral tests create
&cobra.Command{}instances but let stderr bleed to the real process. Usingcmd.SetErr(&bytes.Buffer{})in test setup makes tests hermetic and prevents CI log noise.🔧 General Improvements
8. Proxy
--tls-dirrelationship with--tlsnot validated early--tls-diris only meaningful when--tlsis enabled, but there is no early validation orMarkFlagsMutuallyExclusive-style enforcement. APersistentPreRunEcheck or flag group would catch the misconfiguration before the server starts up.Module Summary
github.com/spf13/cobrav1.10.2internal/cmd/(12 files)Key Features
pflag-backed flag parsing withChanged()introspection--helpoutputEnableTraverseRunHooksfor multi-level hook chainingReferences
Recommendations
proxygraceful shutdown — replacehttpServer.Close()withhttpServer.Shutdown()+ 5s timeout; prevents aborting in-flight requests onSIGINT.proxyguards-mode default — usedifc.DefaultEnforcementMode()instead of hardcoded"filter".GenBashCompletionV2— upgrade Bash completions to v4 with descriptions.SetErrPrefix— reconcile withSilenceErrors: true; currently a no-op.log.PrintfinpreRun case 1:.MarkFlagFilename— simplifyconfigandenvcompletion registrations.cmd.SetErr()— use in tests for hermetic stderr capture.--tls-dirconstraint — validate that--tls-diris only used when--tlsis also set.Next Steps
Generated by Go Fan 🐹
Note
🔒 Integrity filter blocked 46 items
The following items were blocked because they don't meet the GitHub integrity level.
get_latest_release: has lower integrity than agent requires. The agent cannot read data with integrity below "unapproved".get_latest_release: has lower integrity than agent requires. The agent cannot read data with integrity below "unapproved".get_latest_release: has lower integrity than agent requires. The agent cannot read data with integrity below "unapproved".get_latest_release: has lower integrity than agent requires. The agent cannot read data with integrity below "unapproved".get_latest_release: has lower integrity than agent requires. The agent cannot read data with integrity below "unapproved".get_latest_release: has lower integrity than agent requires. The agent cannot read data with integrity below "unapproved".get_latest_release: has lower integrity than agent requires. The agent cannot read data with integrity below "unapproved".list_commits: has lower integrity than agent requires. The agent cannot read data with integrity below "unapproved".list_commits: has lower integrity than agent requires. The agent cannot read data with integrity below "unapproved".list_commits: has lower integrity than agent requires. The agent cannot read data with integrity below "unapproved".list_commits: has lower integrity than agent requires. The agent cannot read data with integrity below "unapproved".list_commits: has lower integrity than agent requires. The agent cannot read data with integrity below "unapproved".list_commits: has lower integrity than agent requires. The agent cannot read data with integrity below "unapproved".list_commits: has lower integrity than agent requires. The agent cannot read data with integrity below "unapproved".list_tags: has lower integrity than agent requires. The agent cannot read data with integrity below "unapproved".search_repositories: has lower integrity than agent requires. The agent cannot read data with integrity below "unapproved".To allow these resources, lower
min-integrityin your GitHub frontmatter: