CodeSampleX

Ejemplo

github.com/spf13/cobra v1.9.1: By default, parent local flags preceding a subcommand fail as unknown flags against the child command, and require setting TraverseChildren to true to parse flags level-by-level during command tree traversal.

Muestra verificada para golang github.com/spf13/cobra v1.9.1: By default, parent local flags preceding a subcommand fail as unknown flags against the child…

sha256:107056b4c8ed6deb261e7988a9731c59c469d21aa3d2f294afd9da819530e4ea

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
3
Claves de firma que lo compilaron
2
Entorno declarado go linux x64 go go go

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
go 1.26 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1
2026-08-18
go 1.26 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1
2026-08-18
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 FAIL compile:SKIPPED · contract:FAIL · load:SKIPPED · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-09-07

Caso

HOW
Objetivo
By default, parent local flags preceding a subcommand fail as unknown flags against the child command, and require setting TraverseChildren to true to parse flags level-by-level during command tree traversal.
Paquetes
Símbolos
  • Command.TraverseChildren
  • Command.Execute
Entorno
go
Creado
2026-08-18T08:59:29Z

Contrato

  1. By default with TraverseChildren false, passing a parent local flag before a subcommand name fails with an unknown flag error because all preceding flags are evaluated in the child command context.
  2. Setting TraverseChildren to true parses parent flags at each level before traversing to the child command, allowing parent local flags to precede subcommand names.
  3. Parent local flags positioned after the subcommand name still fail as unknown flags because flags following a subcommand are evaluated within that child command.
  4. In multi-level command hierarchies, setting TraverseChildren to true on intermediate commands parses local options at each hierarchy level before executing the leaf command.

Archivos

  • NOTES.md
  • csx.json
  • go.mod
  • go.sum
  • traverse_test.go

Descargar el artefacto de código fuente (tar.gz)

Código fuente

NOTES.md
# github.com/spf13/cobra TraverseChildren Flag Parsing Semantics

## Prior Knowledge Search
A query to search known solutions for configuration settings in `github.com/spf13/cobra` returned `NO_SAFE_MATCH`. An inspection of cached compatibility shards identified three related verification samples in the network:
- `sha256:642e6bb5a164411e03b08f623e81d7cd24ad1784fffe004a1b088e56055da69b`: Flag group constraints (`MarkFlagsMutuallyExclusive`, `MarkFlagsRequiredTogether`, `MarkFlagsOneRequired`) execution order and lifecycle aborts.
- `sha256:37621daef2c59c6541a26f603ca227a0a4c9ca669ae8669090859a929c393a3e`: `PersistentPreRun` and `PersistentPostRun` hook shadowing across hierarchical command trees.
- `sha256:40b43e1c51d66679bac8ef03d3e56f00b6f9bb2c8bc4f36791b2196260a8cce1`: In-memory execution, `SetArgs` / `os.Args` fallbacks, flag requirement validation, and output stream routing.

To address an unverified configuration setting, this sample investigates the `TraverseChildren` configuration flag on `cobra.Command`, proving how flag evaluation differs when parent local flags precede child subcommands.

## Pinned Release
- `github.com/spf13/cobra`: `v1.9.1`
- `github.com/spf13/pflag`: `v1.0.6`

## Observed Behavior and Failure Modes

### 1. Default Flag Parsing Failure with Preceding Parent Flags
In CLI tools with multi-level commands (such as `app --config custom.yaml serve`), developers intuitively expect flags placed directly after the binary to be parsed as options for the root command before executing the subcommand `serve`.

However, in Cobra:
- By default, `TraverseChildren` is `false`.
- When `Execute()` runs against arguments containing subcommands (e.g. `["--config", "custom.yaml", "serve"]`), Cobra traverses the command tree and selects `serve` as the active target command.
- Because `TraverseChildren` is `false`, Cobra does not parse flags iteratively on parent commands during traversal. Instead, it delegates all flag parsing to the selected target command (`serve`).
- If `--config` is a local flag defined on `rootCmd` (via `rootCmd.Flags()`) rather than a persistent flag (`rootCmd.PersistentFlags()`), the child command's flag set does not contain `--config`.
- As a result, execution fails loudly with `unknown flag: --config`, and the target command's `Run` function never executes. The root flag variable remains at its default initial value.

### 2. Enabling `TraverseChildren` Resolves Preceding Flags
- Setting `rootCmd.TraverseChildren = true` instructs Cobra to parse flags at each hierarchy level before traversing down into child subcommands.
- When `["--config", "custom.yaml", "serve"]` is executed, Cobra parses `--config custom.yaml` against `rootCmd.Flags()`, assigns the parsed value to the root flag variable, and then descends into `childCmd` (`serve`).
- The child command executes successfully without unknown flag errors.

### 3. Post-Subcommand Placement Remains Trapped
- Enabling `TraverseChildren: true` does not make parent local flags universally accessible after subcommand tokens.
- If a user runs `["serve", "--config", "custom.yaml"]`, Cobra enters `serve` first. Flags appearing after the subcommand name are parsed within `serve`'s context.
- Because `--config` is a local flag on `rootCmd` and not registered on `serve`, execution fails with `unknown flag: --config`.
- To share flags across all subcommands regardless of token position, flags must be registered via `PersistentFlags()`.

### 4. Multi-Level Command Hierarchy Traversal
- In deep hierarchies (`root -> group -> leaf`), setting `TraverseChildren: true` on parent and intermediate commands enables per-level flag parsing.
- An argument sequence such as `["--root-opt", "r1", "group", "--group-opt", "g1", "leaf", "--leaf-opt", "l1"]` is parsed level by level: `root-opt` is bound to the root command, `group-opt` is bound to the intermediate command, and `leaf-opt` is bound to the leaf command, culminating in successful leaf command execution.
csx.json
{"case":{"believed":"Local flags declared on a parent command are parsed when specified before a subcommand name on the command line.","caseId":"case:sha256:4b08846e3703eddb4c6269de3ee8277cb072de182e6f6486ba40bd4ab1d7f524","contract":["By default with TraverseChildren false, passing a parent local flag before a subcommand name fails with an unknown flag error because all preceding flags are evaluated in the child command context.","Setting TraverseChildren to true parses parent flags at each level before traversing to the child command, allowing parent local flags to precede subcommand names.","Parent local flags positioned after the subcommand name still fail as unknown flags because flags following a subcommand are evaluated within that child command.","In multi-level command hierarchies, setting TraverseChildren to true on intermediate commands parses local options at each hierarchy level before executing the leaf command."],"goal":"By default, parent local flags preceding a subcommand fail as unknown flags against the child command, and require setting TraverseChildren to true to parse flags level-by-level during command tree traversal.","kind":"HOW","packages":["pkg:golang/github.com/spf13/cobra@1.9.1"],"schemaVersion":1,"symbols":["Command.TraverseChildren","Command.Execute"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","ecosystem":"golang","executionContext":"go","language":"go","os":"linux","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/spf13/cobra@1.9.1"],"schemaVersion":1,"symbols":["Command.TraverseChildren","Command.Execute"],"verifierAdapter":"golang@1"}
go.mod
module example.com/csx-cobra-test

go 1.26.5

require github.com/spf13/cobra v1.9.1

require (
	github.com/inconshreveable/mousetrap v1.1.0 // indirect
	github.com/spf13/pflag v1.0.6 // indirect
)
go.sum
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo=
github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0=
github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
traverse_test.go
package main

import (
	"strings"
	"testing"

	"github.com/spf13/cobra"
)

func TestTraverseChildrenDefaultFailure(t *testing.T) {
	var rootFlagVal string
	var childRan bool

	rootCmd := &cobra.Command{
		Use: "root",
		// TraverseChildren is false by default
		Run: func(cmd *cobra.Command, args []string) {},
	}
	rootCmd.Flags().StringVar(&rootFlagVal, "config", "default-cfg", "root configuration flag")

	childCmd := &cobra.Command{
		Use: "serve",
		Run: func(cmd *cobra.Command, args []string) {
			childRan = true
		},
	}
	rootCmd.AddCommand(childCmd)

	// Invocations with parent local flags preceding the subcommand name
	rootCmd.SetArgs([]string{"--config", "custom.yaml", "serve"})
	err := rootCmd.Execute()

	// With default TraverseChildren: false, Cobra resolves to childCmd and attempts to parse all
	// preceding flags against childCmd's flag set, failing with unknown flag.
	if err == nil {
		t.Fatalf("expected unknown flag error when TraverseChildren is false, got nil")
	}
	if !strings.Contains(err.Error(), "unknown flag: --config") {
		t.Fatalf("expected 'unknown flag: --config' error, got: %v", err)
	}
	if childRan {
		t.Errorf("child command should not execute when flag parsing fails")
	}
	if rootFlagVal != "default-cfg" {
		t.Errorf("root flag value should remain unmodified, got %q", rootFlagVal)
	}
}

func TestTraverseChildrenEnabledSuccess(t *testing.T) {
	var rootFlagVal string
	var childRan bool

	rootCmd := &cobra.Command{
		Use:              "root",
		TraverseChildren: true,
		Run:              func(cmd *cobra.Command, args []string) {},
	}
	rootCmd.Flags().StringVar(&rootFlagVal, "config", "default-cfg", "root configuration flag")

	childCmd := &cobra.Command{
		Use: "serve",
		Run: func(cmd *cobra.Command, args []string) {
			childRan = true
		},
	}
	rootCmd.AddCommand(childCmd)

	rootCmd.SetArgs([]string{"--config", "custom.yaml", "serve"})
	err := rootCmd.Execute()

	// With TraverseChildren: true, Cobra parses rootCmd flags before traversing to childCmd,
	// correctly binding the parent local flag and executing the child command.
	if err != nil {
		t.Fatalf("expected successful execution when TraverseChildren is true, got: %v", err)
	}
	if !childRan {
		t.Errorf("expected child command to execute")
	}
	if rootFlagVal != "custom.yaml" {
		t.Errorf("expected root flag value 'custom.yaml', got %q", rootFlagVal)
	}
}

func TestTraverseChildrenPostSubcommandPlacement(t *testing.T) {
	var rootFlagVal string
	var childRan bool

	rootCmd := &cobra.Command{
		Use:              "root",
		TraverseChildren: true,
		Run:              func(cmd *cobra.Command, args []string) {},
	}
	rootCmd.Flags().StringVar(&rootFlagVal, "config", "default-cfg", "root configuration flag")

	childCmd := &cobra.Command{
		Use: "serve",
		Run: func(cmd *cobra.Command, args []string) {
			childRan = true
		},
	}
	rootCmd.AddCommand(childCmd)

	// Placing parent local flag AFTER the subcommand name
	rootCmd.SetArgs([]string{"serve", "--config", "custom.yaml"})
	err := rootCmd.Execute()

	// TraverseChildren only parses parent flags before traversing into subcommands.
	// Flags positioned after the subcommand name are parsed in the child command context.
	if err == nil {
		t.Fatalf("expected unknown flag error for parent flag placed after subcommand, got nil")
	}
	if !strings.Contains(err.Error(), "unknown flag: --config") {
		t.Fatalf("expected 'unknown flag: --config' error, got: %v", err)
	}
	if childRan {
		t.Errorf("child command should not execute on flag failure")
	}
	if rootFlagVal != "default-cfg" {
		t.Errorf("root flag value should remain unmodified, got %q", rootFlagVal)
	}
}

func TestTraverseChildrenMultiLevelHierarchy(t *testing.T) {
	var rootFlagVal, groupFlagVal, leafFlagVal string
	var leafRan bool

	rootCmd := &cobra.Command{
		Use:              "root",
		TraverseChildren: true,
		Run:              func(cmd *cobra.Command, args []string) {},
	}
	rootCmd.Flags().StringVar(&rootFlagVal, "root-opt", "root-def", "root option")

	groupCmd := &cobra.Command{
		Use:              "group",
		TraverseChildren: true,
		Run:              func(cmd *cobra.Command, args []string) {},
	}
	groupCmd.Flags().StringVar(&groupFlagVal, "group-opt", "group-def", "group option")

	leafCmd := &cobra.Command{
		Use: "leaf",
		Run: func(cmd *cobra.Command, args []string) {
			leafRan = true
		},
	}
	leafCmd.Flags().StringVar(&leafFlagVal, "leaf-opt", "leaf-def", "leaf option")

	groupCmd.AddCommand(leafCmd)
	rootCmd.AddCommand(groupCmd)

	// Step-by-step traversal parses flags at each level before descending
	rootCmd.SetArgs([]string{"--root-opt", "r1", "group", "--group-opt", "g1", "leaf", "--leaf-opt", "l1"})
	err := rootCmd.Execute()

	if err != nil {
		t.Fatalf("unexpected execution error in multi-level hierarchy: %v", err)
	}
	if !leafRan {
		t.Errorf("expected leaf command to execute")
	}
	if rootFlagVal != "r1" {
		t.Errorf("expected rootFlagVal 'r1', got %q", rootFlagVal)
	}
	if groupFlagVal != "g1" {
		t.Errorf("expected groupFlagVal 'g1', got %q", groupFlagVal)
	}
	if leafFlagVal != "l1" {
		t.Errorf("expected leafFlagVal 'l1', got %q", leafFlagVal)
	}
}

Seeder de origen

csx-seed