Production-ready Cobra CLI patterns including command structure, flags (local and persistent), nested commands, PreRun/PostRun hooks, argument validation, and initialization patterns used by kubectl and hugo. Use when building Go CLIs, implementing Cobra commands, creating nested command structures, managing flags, validating arguments, or when user mentions Cobra, CLI development, command-line tools, kubectl patterns, or Go CLI frameworks.
View on GitHubvanman2024/cli-builder
cli-builder
plugins/cli-builder/skills/cobra-patterns/SKILL.md
January 22, 2026
Select agents to install to:
npx add-skill https://github.com/vanman2024/cli-builder/blob/main/plugins/cli-builder/skills/cobra-patterns/SKILL.md -a claude-code --skill cobra-patternsInstallation paths:
.claude/skills/cobra-patterns/# Cobra Patterns Skill
Production-ready patterns for building powerful CLI applications with Cobra, following best practices from kubectl, hugo, and other production CLIs.
## Instructions
### 1. Choose CLI Structure Pattern
Select the appropriate CLI structure based on your use case:
- **simple**: Single command with flags (quick utilities)
- **flat**: Root command with subcommands at one level
- **nested**: Hierarchical command structure (kubectl-style)
- **plugin**: Extensible CLI with plugin support
- **hybrid**: Mix of built-in and dynamic commands
### 2. Generate Cobra CLI Structure
Use the setup script to scaffold a new Cobra CLI:
```bash
cd /home/gotime2022/.claude/plugins/repos/cli-builder/skills/cobra-patterns
./scripts/setup-cobra-cli.sh <cli-name> <structure-type>
```
**Structure types:** `simple`, `flat`, `nested`, `plugin`, `hybrid`
**Example:**
```bash
./scripts/setup-cobra-cli.sh myctl nested
```
**What This Creates:**
- Complete directory structure with cmd/ package
- Root command with initialization
- Example subcommands
- Flag definitions (local and persistent)
- Cobra initialization (cobra init pattern)
- Go module configuration
- Main entry point
### 3. Command Structure Patterns
#### Basic Command Structure
```go
var exampleCmd = &cobra.Command{
Use: "example [flags]",
Short: "Brief description",
Long: `Detailed description with examples`,
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
// Command logic
},
}
```
#### Command with Lifecycle Hooks
```go
var advancedCmd = &cobra.Command{
Use: "advanced",
Short: "Advanced command with hooks",
PersistentPreRun: func(cmd *cobra.Command, args []string) {
// Runs before command execution (inherited by children)
},
PreRun: func(cmd *cobra.Command, args []string) {
// Runs before command execution (local only)
},
Run: func(cmd *cobra.Command, args []string) {
// Main command l