golang-spf13-cobra
Golang CLI command tree library using spf13/cobra — cobra.Command, RunE vs Run, PersistentPreRunE hook chain, Args validators (NoArgs, ExactArgs, MatchAll, custom), persistent vs local flags, command groups, ValidArgsFunction, RegisterFlagCompletionFunc, ShellCompDirective, usage/help template customization, man-page and markdown doc generation, and testing with SetArgs/SetOut/SetErr. Apply when using or adopting spf13/cobra, or when the codebase imports `github.com/spf13/cobra`. For configuration layering alongside cobra, see the `samber/cc-skills-golang@golang-spf13-viper` skill. For general CLI architecture (project layout, exit codes, signal handling, I/O patterns), see `samber/cc-skills-golang@golang-cli`.
Rank
62
Safety
84
Downloads
1.0k
Updated
Oct 11, 2026
Version
1.1.0
Source
CLAWHUB
About
What it does, and when to use it.
Capability contract not published. No trust telemetry is available yet. 1K downloads reported by the source. Last updated 10/11/2026.
Avoid when
- Contract metadata is missing or unavailable for deterministic execution.
Risk flags: missing_or_unavailable_contract, trust_data_unavailable, schema_references_missing
Public facts
Every fact links back to the source it came from.
- Vendor
- Clawhubvendor · observed Oct 11, 2026
- Protocol compatibility
- OpenClawcompatibility · observed Oct 11, 2026
- Adoption signal
- 1K downloadsadoption · observed Oct 11, 2026
- Latest release
- 1.1.0release · observed Aug 23, 2026
- Handshake status
- UNKNOWNsecurity
Install and run
Setup complexity: low.
clawhub skill install s173arkhs3131fq5jf769qq75583hdgt:golang-spf13-cobra- Install using `clawhub skill install s173arkhs3131fq5jf769qq75583hdgt:golang-spf13-cobra` in an isolated environment before connecting it to live workloads.
- No published capability contract is available yet, so validate auth and request/response behavior manually.
- Review the upstream CLAWHUB listing at https://clawhub.ai/samber/golang-spf13-cobra before using production credentials.
Contract: missing
curl -s "https://www.xpersona.co/api/v1/agents/clawhub-samber-golang-spf13-cobra/snapshot"
Run-check
$0.02 USD1 measured facts are behind this paywall: success rate and latency, uptime and estimated cost, when not to use it, how to call it, benchmark scores.
Agents pay $0.02 in USDC. A card payment is $0.50, the smallest a card allows.
Documentation
CLAWHUB
143,976 characters of source documentation, loaded on request.
Extracted files
5 files captured from the source.
SKILL.md
---
name: golang-spf13-cobra
description: "Golang CLI command tree library using spf13/cobra — cobra.Command, RunE vs Run, PersistentPreRunE hook chain, Args validators (NoArgs, ExactArgs, MatchAll, custom), persistent vs local flags, command groups, ValidArgsFunction, RegisterFlagCompletionFunc, ShellCompDirective, usage/help template customization, man-page and markdown doc generation, and testing with SetArgs/SetOut/SetErr. Apply when using or adopting spf13/cobra, or when the codebase imports `github.com/spf13/cobra`. For configuration layering alongside cobra, see the `samber/cc-skills-golang@golang-spf13-viper` skill. For general CLI architecture (project layout, exit codes, signal handling, I/O patterns), see `samber/cc-skills-golang@golang-cli`."
user-invocable: true
license: MIT
compatibility: Designed for Claude Code, Codex or similar harness, and for projects using Golang.
metadata:
author: samber
version: "1.1.0"
openclaw:
emoji: "🐍"
homepage: https://github.com/samber/cc-skills-golang
requires:
bins:
- go
install: []
skill-library-version: "1.10.2"
allowed-tools: Read Edit Write Glob Grep Bash(go:*) Bash(golangci-lint:*) Bash(git:*) Agent WebFetch mcp__context7__resolve-library-id mcp__context7__query-docs Bash(godig:*) Bash(gopls:*) LSP mcp__gopls__*
paths:
- "**/*.go"
---
**Persona:** You are a Go CLI engineer building command trees that feel native to the Unix shell. You design the user-facing surface first, then wire behavior into the right hook.
**Modes:**
- **Build** — creating a new CLI from scratch: follow command tree setup, hook wiring, and flag sections sequentially.
- **Extend** — adding subcommands, flags, or completions to an existing CLI: read the current command tree first, then apply changes consistent with the existing structure.
- **Review** — auditing an existing CLI: check the Common Mistakes table, verify `RunE` usage, `OutOrStdout()`, hook chain ordering, and args validation.
# Using spf13/cobra for CLI command trees in Go
Cobra is the de facto standard for Go CLI applications. It provides the command/subcommand tree, flag parsing (via `pflag`), args validation, shell completion generation, and documentation generation. It does **not** handle configuration layering — that's viper's job.
**Official Resources:**
- [pkg.go.dev/github.com/spf13/cobra](https://pkg.go.dev/github.com/spf13/cobra)
- [github.com/spf13/cobra](https://github.com/spf13/cobra)
- [cobra.dev](https://cobra.dev)
This skill is not exhaustive. Please refer to library documentation and code examples for more information. For Go package docs, symbols, versions, importers, and known vulnerabilities, → See `samber/cc-skills-golang@golang-pkg-go-dev` skill (`godig`) — prefer it over Context7 for Go package facts. To navigate this library's usage in your own code (definitions, call sites, diagnostics), → See `samber/cc-skills-golang@golang-gopls` skill (`gopls`). Context7 remains a fallback for docs n_meta.json
{
"ownerId": "kn72rhnkwjfeex9wr1n7y24qa983cjn3",
"slug": "golang-spf13-cobra",
"version": "1.1.0",
"publishedAt": 1787448813168
}references/commands-and-args.md
# Cobra Commands, Hooks, and Args Validators
## The Run\* lifecycle
Cobra commands have five run hooks. Cobra executes them in this fixed order:
```
PersistentPreRunE → PreRunE → RunE → PostRunE → PersistentPostRunE
```
Each `*E` hook returns `error`. The non-`*E` variants (`PersistentPreRun`, `PreRun`, `Run`, `PostRun`, `PersistentPostRun`) have signature `func(cmd *cobra.Command, args []string)` — they cannot signal failure without `os.Exit` or panic. **Always use the `*E` variants.**
### Which hook to use
| Hook | Scope | When to use |
| --- | --- | --- |
| `PersistentPreRunE` | Parent + all descendants | Config init, auth check, telemetry setup — must run before every subcommand |
| `PreRunE` | This command only | Validation that runs only for this command before `RunE` |
| `RunE` | This command only | Main handler — the primary business logic |
| `PostRunE` | This command only | Cleanup that runs only if `RunE` succeeded |
| `PersistentPostRunE` | Parent + all descendants | Global cleanup (close connections, flush buffers) |
### Inheritance rules
`PersistentPreRunE` defined on the root command runs before every subcommand. But if a child command defines **its own** `PersistentPreRunE`, it **replaces** (does not chain) the parent's hook. Call the parent explicitly if you need both:
```go
var childCmd = &cobra.Command{
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
// call parent's hook first
if err := rootCmd.PersistentPreRunE(cmd, args); err != nil {
return err
}
// child-specific logic
return nil
},
}
```
### Execution stops on first error
If `PersistentPreRunE` returns an error, cobra stops — `RunE` and later hooks never run. Use this for fail-fast auth checks.
## Args validators
Args validators run before `RunE`. Cobra prints a clear error message and exits without calling `RunE` when validation fails.
### Built-in validators
```go
cobra.NoArgs // fails if any positional args provided
cobra.ArbitraryArgs // accepts any number of args (default)
cobra.ExactArgs(n int) // requires exactly n args
cobra.MinimumNArgs(n int) // requires at least n args
cobra.MaximumNArgs(n int) // requires at most n args
cobra.RangeArgs(min, max int) // requires between min and max args
cobra.OnlyValidArgs // all args must be in ValidArgs list
cobra.ExactValidArgs(n int) // exactly n args, all in ValidArgs
```
### Composing validators with MatchAll
```go
var deleteCmd = &cobra.Command{
Use: "delete <resource>",
Args: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs),
ValidArgs: []string{"pod", "service", "deployment"},
RunE: func(cmd *cobra.Command, args []string) error {
return doDelete(args[0])
},
}
```
### Custom validators
Signature: `func(cmd *cobra.Command, args []string) error`
```go
func validatePositiveInt(cmd references/completions.md
# Cobra Shell Completions Reference
Cobra generates shell completion scripts for bash, zsh, fish, and PowerShell automatically. Subcommand names and flag names are completed for free. You add completions for flag values and positional arguments.
## Built-in completion command
Cobra registers a `completion` subcommand automatically:
```bash
myapp completion bash # generate bash script
myapp completion zsh # generate zsh script
myapp completion fish # generate fish script
myapp completion powershell
# Install (example for zsh):
myapp completion zsh > "${fpath[1]}/_myapp"
```
## ShellCompDirective
The `ShellCompDirective` controls shell behavior after your completion function returns:
| Directive | Meaning |
| --- | --- |
| `ShellCompDirectiveDefault` | Fall back to file completion after your results |
| `ShellCompDirectiveNoFileComp` | Disable file completion fallback |
| `ShellCompDirectiveNoSpace` | Don't add a space after the completion |
| `ShellCompDirectiveFilterFileExt(exts)` | Only show files with given extensions |
| `ShellCompDirectiveFilterDirs(dirs)` | Only show directories |
| `ShellCompDirectiveError` | Signal an error (show no completions) |
Combine with bitwise OR: `cobra.ShellCompDirectiveNoFileComp | cobra.ShellCompDirectiveNoSpace`.
Use `ShellCompDirectiveNoFileComp` whenever your list is exhaustive — it prevents the shell from appending irrelevant files.
## Static arg completions
```go
var getCmd = &cobra.Command{
Use: "get <resource>",
ValidArgs: []string{"pod", "service", "deployment", "configmap"},
Args: cobra.OnlyValidArgs,
RunE: func(cmd *cobra.Command, args []string) error { /* ... */ },
}
```
## Dynamic arg completions
```go
var getCmd = &cobra.Command{
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) > 0 {
// first arg already provided — no more completions
return nil, cobra.ShellCompDirectiveNoFileComp
}
resources, err := listResources(toComplete)
if err != nil {
return nil, cobra.ShellCompDirectiveError
}
return resources, cobra.ShellCompDirectiveNoFileComp
},
}
```
`toComplete` is the prefix the user has typed so far — filter your results by it for responsive completions.
## Flag value completions
```go
func init() {
rootCmd.RegisterFlagCompletionFunc("output", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return []string{"json\tJSON output", "yaml\tYAML output", "table\tTable output"}, cobra.ShellCompDirectiveNoFileComp
})
rootCmd.RegisterFlagCompletionFunc("namespace", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
ns, err := listNamespaces()
if err != nil {
return nil, cobra.ShellCompDirectiveError
}
return ns, cobra.ShellCompDirereferences/flags.md
# Cobra Flags Reference
Cobra delegates all flag parsing to `github.com/spf13/pflag`. `cobra.Command` exposes two `*pflag.FlagSet`s:
- `cmd.Flags()` — local flags, only available on this command.
- `cmd.PersistentFlags()` — inherited by all subcommands.
## Common flag types
```go
// String
cmd.Flags().String("name", "default", "description")
cmd.Flags().StringP("name", "n", "default", "description") // with shorthand
// With pointer binding (no Lookup needed later)
var name string
cmd.Flags().StringVar(&name, "name", "default", "description")
cmd.Flags().StringVarP(&name, "name", "n", "default", "description")
// Other types follow the same pattern:
cmd.Flags().Int / IntVar / IntVarP
cmd.Flags().Bool / BoolVar / BoolVarP
cmd.Flags().Float64 / Float64Var
cmd.Flags().Duration / DurationVar // parses "1h30m", "500ms"
cmd.Flags().StringSlice / StringSliceVar // comma-separated or repeated flags
cmd.Flags().StringArray / StringArrayVar // repeated flags only (no comma splitting)
cmd.Flags().IntSlice / IntSliceVar
cmd.Flags().StringToString // --label key=value --label k2=v2
```
## StringSlice vs StringArray
| Flag type | Input | Result |
| ------------- | --------------------- | --------------------------------- |
| `StringSlice` | `--tags a,b --tags c` | `["a", "b", "c"]` — commas split |
| `StringArray` | `--tags a,b --tags c` | `["a,b", "c"]` — commas NOT split |
Use `StringArray` when values may legitimately contain commas.
## Flag constraints
```go
// Fail if flag not provided
cmd.MarkFlagRequired("output")
// Fail if both provided
cmd.MarkFlagsMutuallyExclusive("json", "yaml", "table")
// Fail if none provided
cmd.MarkFlagsOneRequired("file", "stdin")
// Require flag only if another flag is set
cmd.MarkFlagsMutuallyExclusive("tls", "no-tls")
```
## Persistent flag patterns
```go
func init() {
// global flags on root
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default: $HOME/.myapp.yaml)")
rootCmd.PersistentFlags().StringVar(&logLevel, "log-level", "info", "log level (debug, info, warn, error)")
// bind to viper immediately after defining
viper.BindPFlag("config", rootCmd.PersistentFlags().Lookup("config"))
viper.BindPFlag("log-level", rootCmd.PersistentFlags().Lookup("log-level"))
}
```
## Custom flag value types
Implement `pflag.Value` to parse arbitrary types:
```go
type enumValue struct {
val string
allowed []string
}
func (e *enumValue) String() string { return e.val }
func (e *enumValue) Type() string { return "enum" }
func (e *enumValue) Set(s string) error {
for _, a := range e.allowed {
if s == a {
e.val = s
return nil
}
}
return fmt.Errorf("must be one of %v", e.allowed)
}
var outputFmt = &enumValue{val: "table", allowed: []string{"table", "json", "yaml"}}
cmd.Flags().Var(outputFmt, "output", "output format (table, json, yaml)")AionUi
Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!
activepieces
AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
cherry-studio
AI productivity studio with smart chat, autonomous agents, and 300+ assistants.
CopilotKit
The Frontend for Agents & Generative UI. React + Angular
Machine-readable data
The same record, as JSON, for agents and crawlers.
{
"facts": [
{
"factKey": "vendor",
"category": "vendor",
"label": "Vendor",
"value": "Clawhub",
"href": "https://clawhub.ai/samber/skills/golang-spf13-cobra",
"sourceUrl": "https://clawhub.ai/samber/skills/golang-spf13-cobra",
"sourceType": "profile",
"confidence": "medium",
"observedAt": "2026-10-11T14:31:24.676Z",
"isPublic": true
},
{
"factKey": "protocols",
"category": "compatibility",
"label": "Protocol compatibility",
"value": "OpenClaw",
"href": "https://www.xpersona.co/api/v1/agents/clawhub-samber-golang-spf13-cobra/contract",
"sourceUrl": "https://www.xpersona.co/api/v1/agents/clawhub-samber-golang-spf13-cobra/contract",
"sourceType": "contract",
"confidence": "medium",
"observedAt": "2026-10-11T14:31:24.676Z",
"isPublic": true
},
{
"factKey": "traction",
"category": "adoption",
"label": "Adoption signal",
"value": "1K downloads",
"href": "https://clawhub.ai/samber/golang-spf13-cobra",
"sourceUrl": "https://clawhub.ai/samber/golang-spf13-cobra",
"sourceType": "profile",
"confidence": "medium",
"observedAt": "2026-10-11T14:31:24.676Z",
"isPublic": true
},
{
"factKey": "latest_release",
"category": "release",
"label": "Latest release",
"value": "1.1.0",
"href": "https://clawhub.ai/samber/golang-spf13-cobra",
"sourceUrl": "https://clawhub.ai/samber/golang-spf13-cobra",
"sourceType": "release",
"confidence": "medium",
"observedAt": "2026-08-23T01:33:33.168Z",
"isPublic": true
},
{
"factKey": "handshake_status",
"category": "security",
"label": "Handshake status",
"value": "UNKNOWN",
"href": "https://www.xpersona.co/api/v1/agents/clawhub-samber-golang-spf13-cobra/trust",
"sourceUrl": "https://www.xpersona.co/api/v1/agents/clawhub-samber-golang-spf13-cobra/trust",
"sourceType": "trust",
"confidence": "medium",
"observedAt": null,
"isPublic": true
}
],
"events": [
{
"eventType": "release",
"title": "Release 1.1.0",
"description": "- Added explicit compatibility and navigation guidance for Go package and symbol documentation, referencing the `golang-pkg-go-dev` and `golang-gopls` skills. - Updated compatibility section to mention Codex and similar harnesses (not just Claude Code). - Expanded allowed tools, adding support for Bash(godig:*), Bash(gopls:*), LSP, and gopls MCP tools. - Introduced a `paths` section to scope skill application to `**/*.go`. - Bumped version to 1.1.0 and removed the obsolete `skill-card.md` file.",
"href": "https://clawhub.ai/samber/golang-spf13-cobra",
"sourceUrl": "https://clawhub.ai/samber/golang-spf13-cobra",
"sourceType": "release",
"confidence": "medium",
"observedAt": "2026-08-23T01:33:33.168Z",
"isPublic": true
}
]
}Record generated Oct 11, 2026.
