- Add new CLI structure in cmd/cli/ - Implement version, server, and greet commands - Update build script to compile new CLI binary - Add Cobra dependency to go.mod - Update ADR 0015 to reflect implementation status - Update README and AGENTS.md with CLI usage - Maintain backward compatibility with existing binaries Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
7.4 KiB
7.4 KiB
15. CLI Subcommands and Flag Management with Cobra
Date: 2026-04-05 Status: ✅ Implemented Authors: DanceLessonsCoach Team Decision Date: 2026-04-05 Implementation Status: Phase 1 Complete
Context
As DanceLessonsCoach grows, we need a more robust and maintainable CLI structure. Currently, we use simple flag parsing (--version), but this approach has limitations:
- Limited scalability: Adding more commands/flags becomes messy
- Poor user experience: No built-in help, completion, or validation
- Hard to maintain: Manual flag parsing is error-prone
- No subcommands: Can't easily add commands like
server start,server stop, etc.
Decision Drivers
- Scalability: Support growing CLI needs as project expands
- User Experience: Provide professional CLI with help, completion, validation
- Maintainability: Easy to add/remove commands and flags
- Standards: Follow industry best practices for CLI tools
- Extensibility: Support future commands (migrate, seed, etc.)
- Integration: Work well with existing config system
Decision
We will adopt Cobra as our CLI framework. Cobra is a mature, widely-used library for building modern CLI applications in Go.
Selected Solution: Cobra CLI Framework
Repository: https://github.com/spf13/cobra Version: v1.8.0 (or latest stable)
Key Features
- Subcommands:
server start,server stop,migrate, etc. - Flags:
--config,--env,--verbose, etc. - Help System: Automatic
--helpgeneration - Shell Completion: Built-in support
- Validation: Type-safe flag parsing
- Middleware: Pre/post command hooks
Implementation Plan
Phase 1: Basic Integration (✅ COMPLETED)
Implemented in: cmd/cli/main.go
var rootCmd = &cobra.Command{
Use: "dance-lessons-coach",
Short: "DanceLessonsCoach - API server and CLI tools",
Long: `DanceLessonsCoach provides greeting services and API management.
To begin working with DanceLessonsCoach, run:
dance-lessons-coach server --help`,
SilenceUsage: true,
}
var versionCmd = &cobra.Command{
Use: "version",
Short: "Print version information",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println(version.Full())
},
}
var serverCmd = &cobra.Command{
Use: "server",
Short: "Start the DanceLessonsCoach server",
Run: func(cmd *cobra.Command, args []string) {
// Load config and start server
cfg, err := config.LoadConfig()
if err != nil {
log.Fatal().Err(err).Msg("Failed to load configuration")
}
server := server.NewServer(cfg, context.Background())
if err := server.Run(); err != nil {
log.Fatal().Err(err).Msg("Server failed")
}
},
}
var greetCmd = &cobra.Command{
Use: "greet [name]",
Short: "Greet someone by name",
Args: cobra.MaximumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
name := ""
if len(args) > 0 {
name = args[0]
}
fmt.Printf("Hello %s!\n", name)
},
}
func init() {
rootCmd.AddCommand(versionCmd)
rootCmd.AddCommand(serverCmd)
rootCmd.AddCommand(greetCmd)
// Add flags to server command
serverCmd.Flags().String("config", "", "Config file path")
serverCmd.Flags().String("env", "", "Environment (dev, staging, prod)")
serverCmd.Flags().Bool("debug", false, "Enable debug logging")
}
func main() {
if err := rootCmd.Execute(); err != nil {
log.Fatal().Err(err).Msg("CLI execution failed")
}
}
Current Commands:
version: Print version informationserver: Start the DanceLessonsCoach servergreet [name]: Greet someone by namehelp: Built-in help systemcompletion: Shell completion scripts (automatic)
Current Flags:
--config: Config file path (server command)--env: Environment (dev, staging, prod) (server command)--debug: Enable debug logging (server command)--help: Help for any command (built-in)
Phase 2: Advanced Features (Future)
- Subcommand groups:
server,db,migrate,tools - Persistent flags: Global flags like
--config,--env - Command aliases: Shorter command names
- Custom help templates: Branded help output
- Shell completion scripts: Generate completion for bash/zsh/fish
Phase 3: Migration (Ongoing)
- Migrate existing flags to Cobra
- Deprecate old flag parsing
- Update documentation
- Add new commands as needed
Migration Strategy
- Incremental adoption: Start with version command, then server command
- Backward compatibility: Support old flags during transition
- Documentation: Update README with new CLI usage
- Testing: Ensure all existing functionality works
Command Structure Proposal
# Main commands
dance-lessons-coach server # Start the server
dance-lessons-coach version # Show version
dance-lessons-coach migrate # Database migrations
dance-lessons-coach config # Config management
# Server subcommands
dance-lessons-coach server start # Start server
dance-lessons-coach server stop # Stop server
dance-lessons-coach server restart # Restart server
dance-lessons-coach server status # Server status
# Global flags
dance-lessons-coach --help # Show help
dance-lessons-coach --version # Show version (shortcut)
dance-lessons-coach --config /path/to/config.yaml
# Example usage
dance-lessons-coach server start --env production --debug
dance-lessons-coach migrate up
dance-lessons-coach config validate
Pros and Cons of Cobra
✅ Advantages
- Industry Standard: Used by Kubernetes, Hugo, etcd, and many others
- Mature Ecosystem: Well-documented, widely adopted
- Feature Rich: Help, completion, validation built-in
- Extensible: Easy to add new commands
- Go Idiomatic: Fits well with Go patterns
- Good Documentation: Excellent docs and examples
❌ Disadvantages
- Learning Curve: New patterns to learn
- Migration Effort: Need to refactor existing code
- Slight Overhead: More complex than simple flag parsing
- Dependency: Adds cobra to project
Validation
Does this meet our requirements?
- ✅ Scalability: Easy to add new commands
- ✅ User Experience: Professional CLI with help/completion
- ✅ Maintainability: Clean, structured code
- ✅ Standards: Follows industry best practices
- ✅ Extensibility: Supports future growth
- ✅ Integration: Works with existing config system
What's still needed?
- ✅ Implementation: Actual cobra integration (Phase 1 complete)
- ❌ Migration: Move existing flags to cobra (Phase 2)
- ❌ Documentation: Update docs with new CLI (Phase 2)
- ❌ Testing: Ensure all functionality works (Phase 2)
Future Enhancements
- Add more commands:
migrate,config,db, etc. - Improve help: Custom templates, examples
- Add completion: Shell completion scripts
- Enhance validation: Better error messages
- Add aliases: Shorter command names
References
Status: Proposed
Next Review: 2026-04-12
Implementation Owner: DanceLessonsCoach Team
Approvers Needed: @gabrielradureau