Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Jan 21, 2026

Go Fan report identified 5 improvements to Cobra usage. All implemented with full test coverage.

Changes

Validation lifecycle - Moved config validation to PersistentPreRun:

rootCmd.PersistentPreRunE = preRun  // Validates before command execution

func preRun(cmd *cobra.Command, args []string) error {
    if !configStdin && configFile == "" {
        return fmt.Errorf("configuration source required")
    }
    // Apply verbosity levels to DEBUG env var
    return nil
}

Verbosity flags - Added CountVarP for -v/-vv/-vvv:

  • -v: info (no DEBUG)
  • -vv: DEBUG=cmd:*,server:*,launcher:*
  • -vvv: DEBUG=*

Complements existing DEBUG env var without overriding it.

Shell completions - Registered custom completions:

cmd.RegisterFlagCompletionFunc("config", func(...) ([]string, cobra.ShellCompDirective) {
    return []string{"toml"}, cobra.ShellCompDirectiveFilterFileExt
})

Enables context-aware completion for --config (.toml), --log-dir (dirs), --env (.env).

Error branding - Set prefix: rootCmd.SetErrPrefix("MCPG Error:")

Version metadata - Enhanced output with build info via runtime/debug:

awmg version dev, commit: a365c31, built: 2026-01-21T15:46:19Z

Falls back to VCS info from debug.ReadBuildInfo() when ldflags not set.

Files Modified

  • internal/cmd/root.go - Core changes, constants extracted
  • internal/cmd/completion.go - Override parent PreRun
  • internal/cmd/root_test.go - 7 new validation tests
  • main.go - Version string builder
  • main_test.go - 6 new version tests
  • version.go - Added GitCommit, BuildDate vars

Zero breaking changes. Backward compatible.

Warning

Firewall rules blocked me from connecting to one or more addresses (expand for details)

I tried to connect to the following addresses, but was blocked by firewall rules:

  • this-host-does-not-exist-12345.com
    • Triggering command: /tmp/go-build2448058465/b278/mcp.test /tmp/go-build2448058465/b278/mcp.test -test.testlogfile=/tmp/go-build2448058465/b278/testlog.txt -test.paniconexit0 -test.timeout=10m0s -test.v=true 64/src/runtime/cgo DHQXH4KkN ache/go/1.25.5/x64/pkg/tool/linu-o pull.rebase (dns block)

If you need me to access, download, or install something from one of these locations, you can either:

Original prompt

This section details on the original issue you should resolve

<issue_title>[go-fan] Go Module Review: spf13/cobra</issue_title>
<issue_description># 🐹 Go Fan Report: Cobra CLI Framework

Module Overview

Cobra is a powerful library for creating modern CLI applications in Go. It's the foundation of major projects like Kubernetes, Hugo, and GitHub CLI. The library provides a simple interface to create command-line interfaces with subcommands, flags, automatic help generation, and shell autocompletion.

Current Usage in gh-aw-mcpg

The project uses Cobra effectively as its CLI foundation, implementing a clean and straightforward interface for the MCP Gateway proxy server.

Implementation Details

  • Files: 2 files directly using Cobra
    • internal/cmd/root.go - Main command definition (416 lines)
    • internal/cmd/completion.go - Shell completion subcommand (70 lines)
  • Commands: 1 root command (awmg) + 1 subcommand (completion)
  • Flags: 8 flags with proper short/long variants
  • Tests: Comprehensive test coverage in root_test.go

Key APIs Used

  1. &cobra.Command{} - Command structure definition
  2. Flags().StringVarP() / BoolVar() - Flag management
  3. MarkFlagsMutuallyExclusive() - Flag validation
  4. MatchAll(), ExactArgs(), OnlyValidArgs - Argument validation
  5. ✅ Shell completion generators (bash, zsh, fish, PowerShell)
  6. RunE for proper error handling

Usage Pattern Assessment

Strengths:

  • ✅ Proper use of RunE for error propagation
  • ✅ Correct flag mutual exclusivity (--routed vs --unified)
  • ✅ Complete shell completion support
  • ✅ Clean version management via SetVersion()
  • ✅ Well-structured flag definitions with sensible defaults
  • ✅ Good test coverage for CLI functionality

Current State: Well-implemented - The project follows Cobra best practices appropriately for its current scope.

Research Findings

Recent Updates (v1.9.0 - v1.10.2)

v1.10.2 (Dec 2025) - Current

  • Dependency Cleanup: Migrated from deprecated gopkg.in/yaml.v3 to go.yaml.in/yaml/v3
  • Documentation: Added comprehensive documentation for repeated flags
  • Performance: Replaced several vars with consts for optimization

v1.10.0

  • New: Context flow in help functions via SetHelpFunc
  • New: Customizable default ShellCompDirective
  • Enhanced: Bash, PowerShell, and fish completion improvements
  • Note: pflag upgrade (later fixed in v1.0.9 for compatibility)

v1.9.0

  • Optimization: Linker deadcode elimination support
  • New: CompletionWithDesc helper for richer completions
  • Enhanced: Improved flag detection for multi-value flags

Best Practices from Maintainers

  1. Validation Separation: Use PersistentPreRun for validation logic
  2. Flag Groups: Leverage MarkFlagsRequiredTogether and MarkFlagsMutuallyExclusive
  3. Completions: Implement custom completions for better UX
  4. Command Organization: Separate files per subcommand in larger CLIs
  5. Repeated Flags: Use CountVarP for verbosity (-v, -vv, -vvv)

Improvement Opportunities

🏃 Quick Wins

  1. Enhanced Validation with PreRun Hooks

    • Current: Validation logic embedded in main run() function
    • Improvement: Move config validation to PersistentPreRun
    • Code Example:
      rootCmd.PersistentPreRun = func(cmd *cobra.Command, args []string) error {
          if !configStdin && configFile == "" {
              return fmt.Errorf("configuration source required")
          }
          return nil
      }
    • Benefit: Cleaner separation of concerns, validation runs before command logic
    • Effort: Low (simple refactor in root.go)
    • Impact: Medium - improves code organization
  2. Error Message Branding

    • Current: Using default "Error:" prefix
    • Improvement: Customize with rootCmd.SetErrPrefix("MCPG Error:")
    • Benefit: Consistent branding and clearer error attribution
    • Effort: Very Low (one-liner)
    • Impact: Low - cosmetic but professional

✨ Feature Opportunities

  1. Verbosity Flags with Repeated Flags
    • Feature: Cobra v1.10.2 documented repeated flags (-v, -vv, -vvv)
    • Current: Using DEBUG environment variable for log control
    • Improvement: Add verbosity flag using CountVarP:
      var verbose int
      rootCmd.PersistentFlags().CountVarP(&verbose, "verbose", "v", "verbose output")
      // Then: -v (info), -vv (debug), -vvv (trace)
    • Benefit: More intuitive CLI pattern, complements existing DEBUG env var
    • Effort: Medium (needs integration with logger package)
    • Impact: Medium - enhances user experience
    • Note: Could replace or work alongsi...

Custom agent used: agentic-workflows
GitHub Agentic Workflows (gh-aw) - Create, debug, and upgrade AI-powered workflows with intelligent prompt routing


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

Copilot AI and others added 3 commits January 21, 2026 15:52
Co-authored-by: lpcox <15877973+lpcox@users.noreply.github.com>
Co-authored-by: lpcox <15877973+lpcox@users.noreply.github.com>
Co-authored-by: lpcox <15877973+lpcox@users.noreply.github.com>
Copilot AI changed the title [WIP] Review Go module spf13/cobra for CLI usage Implement Cobra CLI enhancements: validation hooks, verbosity flags, completions Jan 21, 2026
Copilot AI requested a review from lpcox January 21, 2026 15:59
@lpcox lpcox marked this pull request as ready for review January 21, 2026 16:17
@lpcox lpcox merged commit 89fe59f into main Jan 21, 2026
3 checks passed
@lpcox lpcox deleted the copilot/review-cobra-go-module branch January 21, 2026 16:17
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.

[go-fan] Go Module Review: spf13/cobra

2 participants