Add Command
Add a new cobra subcommand following the project's patterns.
Steps
- •Read existing commands in
cmd/to understand patterns - •Create
cmd/<name>.gowith aNew<Name>Cmdfactory function - •The factory accepts a parent options struct or
*iostreams.IOStreams - •Register the command with its parent via
AddCommandin the parent's factory - •Add
--formatoutput support (json, table, yaml) - •Implement both interactive (TTY prompts) and non-interactive (flags-only) paths
- •Create
cmd/<name>_test.gowith tests usingiostreams.Test()
Command Pattern
go
func NewExampleCmd(ios *iostreams.IOStreams) *cobra.Command {
opts := &ExampleOptions{IOStreams: ios}
cmd := &cobra.Command{
Use: "example",
Short: "One-line description",
RunE: func(_ *cobra.Command, _ []string) error {
return runExample(opts)
},
}
cmd.Flags().StringVar(&opts.Format, "format", "", "Output format: json, table, yaml")
return cmd
}
func runExample(opts *ExampleOptions) error {
// Implementation
return nil
}
Checklist
- •
New*Cmdfactory, noinit() - •
SilenceUsage: trueon subcommands that haveRunE - • Registered with parent command
- •
--formatflag if command produces output - • Interactive path with prompts (when
ios.CanPrompt()) - • Non-interactive path requiring all flags
- • Test file with
iostreams.Test()