### Quick Start Example: Basic CLI with Greet Command Source: https://github.com/larsartmann/cmdguard/blob/master/README.md A minimal example demonstrating how to set up a CLI application with cmdguard, defining configuration and a 'greet' command with typed flags. The command handles greeting a specified name, with an option to shout. ```go package main import ( "context" "fmt" "os" "strings" "github.com/larsartmann/cmdguard/pkg/cmdguard/v2" ) type AppConfig struct { Verbose bool `flag:"verbose" short:"v" default:"false" help:"Enable verbose output" Output string `flag:"output" short:"o" default:"text" help:"Output format" } type GreetFlags struct { Name string `flag:"name" short:"n" default:"World" help:"Name to greet" Shout bool `flag:"shout" short:"s" default:"false" help:"Uppercase output" } func main() { cli, err := v2.NewCLI[AppConfig]("myapp", "My CLI application", AppConfig{}) if err != nil { fmt.Fprintf(os.Stderr, "Failed to create CLI: %v\n", err) os.Exit(1) } greetCmd, err := v2.NewCommand[AppConfig, *GreetFlags]("greet", func(ctx context.Context, cfg *AppConfig, flags *GreetFlags) error { msg := fmt.Sprintf("Hello, %s!", flags.Name) if flags.Shout { msg = strings.ToUpper(msg) } fmt.Println(msg) return nil }, v2.WithShort[AppConfig, *GreetFlags]("Greet someone"), v2.WithFlags[AppConfig, *GreetFlags](&GreetFlags{}), ) if err != nil { fmt.Fprintf(os.Stderr, "Failed to create command: %v\n", err) os.Exit(1) } v2.AddCommand(cli, greetCmd) cli.ExecuteAndExit(context.Background()) } ``` -------------------------------- ### Project Setup with Go Module and cmdguard Source: https://github.com/larsartmann/cmdguard/blob/master/docs/TUTORIAL.md Initializes a new Go module and installs the cmdguard library. This is the first step in setting up the project. ```bash mkdir taskctl && cd taskctl go mod init taskctl go get github.com/larsartmann/cmdguard ``` -------------------------------- ### Add Example Option Source: https://github.com/larsartmann/cmdguard/blob/master/docs/status/2026-05-16_21-38_comprehensive-status-report.md Sets an example usage string for a command. ```go cmdguard.WithExample("cmdguard my-command --flag value") ``` -------------------------------- ### Example Usage of Config File Loading Source: https://github.com/larsartmann/cmdguard/blob/master/docs/status/2026-05-27_02-12_final-config-verification.md Demonstrates how to integrate config file loading into a CLI application using JSON files. This example shows the basic setup for loading configuration from specified paths. ```go package main import ( "fmt" "os" "github.com/larsartmann/cmdguard/v2" "github.com/larsartmann/cmdguard/v2/configload" ) func main() { // Example CLI structure with config file loading enabled cli := cmdguard.CLI[Config]{} // Specify paths for config files (JSON only for this basic example) // The loader will automatically expand environment variables and tilde paths. cli.WithConfigFile( "~/.config/myapp/config.json", "./config.json", ) // Initialize the CLI, parsing flags and loading config files. // This happens between registry creation and flag registration. err := cli.Initialize() if err != nil { fmt.Fprintf(os.Stderr, "Error initializing CLI: %v\n", err) os.Exit(1) } // Access configuration values after initialization fmt.Printf("App Name: %s\n", cli.Config.AppName) fmt.Printf("Database URL: %s\n", cli.Config.DatabaseURL) } // Config defines the structure of the application's configuration. // The field names must match the keys in the JSON config file and/or environment variables. // The `flag` tag is used for mapping to command-line flags. type Config struct { AppName string `flag:"app-name"` DatabaseURL string `flag:"db-url"` } ``` -------------------------------- ### CLI Constructor Example Source: https://github.com/larsartmann/cmdguard/blob/master/AGENTS.md Example of how to instantiate a new CLI with a specific configuration type, name, description, and default configuration. ```go cli, err := v2.NewCLI[AppConfig]("myapp", "My application", AppConfig{}) ``` -------------------------------- ### Install cmdguard Source: https://github.com/larsartmann/cmdguard/blob/master/docs/QUICKSTART.md Install the cmdguard Go library using the go get command. ```bash go get github.com/larsartmann/cmdguard ``` -------------------------------- ### Run DI Example Source: https://github.com/larsartmann/cmdguard/blob/master/examples/README.md Execute the dependency injection example for cmdguard. This demonstrates DI patterns. ```bash go run examples/di/main.go check ``` -------------------------------- ### Complete Library Integration Example Source: https://github.com/larsartmann/cmdguard/blob/master/docs/API_DESIGN_REVIEW.md Provides a comprehensive example of integrating library components, including configuration, client, and interface binding. ```go // mylib/package.go package mylib import "github.com/samber/do/v2" func Package() func(do.Injector) { return do.Package( // Configuration - eager for fail-fast validation do.ProvideValue(&Config{Timeout: 30 * time.Second}), // Client - lazy, depends on config do.Provide(NewClient), // Health check interface binding func(i do.Injector) { do.As[*Client, HealthChecker](i) }, ) } // mylib/client.go type Client struct { config *Config } func NewClient(i do.Injector) (*Client, error) { config := do.MustInvoke[*Config](i) client := &Client{config: config} if err := client.connect(); err != nil { return nil, fmt.Errorf("connect: %w", err) } return client, nil } func (c *Client) HealthCheck() error { return c.ping() } func (c *Client) Shutdown() error { return c.close() } ``` -------------------------------- ### Get full CLI framework Source: https://github.com/larsartmann/cmdguard/blob/master/docs/modularization/DEPENDENCY_GRAPH.md Example of how to get the full CLI framework, which includes all core packages and their external dependencies. ```bash go get github.com/larsartmann/cmdguard → pulls in: cobra, pflag, samber/do/v2, fang/v2, mango, etc. → transitively: types, output ``` -------------------------------- ### Verifying Help Examples Programmatically Source: https://github.com/larsartmann/cmdguard/blob/master/docs/CLI_DESIGN_PRINCIPLES.md Illustrates a Go approach to ensure that all examples provided in the CLI's help documentation are functional. It defines a struct to hold example commands and a boolean to track their validity, facilitating automated testing. ```go // ✅ GOOD: Programmatically verify examples type Example struct { Command string Valid bool // Set to true only if tested } var examples = []Example{ {Command: "cmdguard validate --strict", Valid: true}, {Command: "cmdguard --log-level debug", Valid: true}, } ``` -------------------------------- ### Run Basic Example Source: https://github.com/larsartmann/cmdguard/blob/master/examples/README.md Execute the basic cmdguard example from the project root. This demonstrates a simple CLI with subcommands. ```bash # From the project root: go run examples/basic/main.go hello ``` -------------------------------- ### Ginkgo Test Suite Setup Source: https://github.com/larsartmann/cmdguard/blob/master/BDD_TESTS_REVIEW.md Demonstrates the basic setup for a Ginkgo test suite, including necessary imports and the Describe/Context/It structure. ```go package v2_test import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("CLI User", func() { Context("when creating a new CLI", func() { It("should succeed with valid configuration", func() { cli, err := v2.New[AppConfig, v2.NoFlags]("myapp", "My App", AppConfig{}) Expect(err).ToNot(HaveOccurred()) Expect(cli).ToNot(BeNil()) }) It("should fail with empty name", func() { _, err := v2.New[AppConfig, v2.NoFlags]("", "My App", AppConfig{}) Expect(err).To(HaveOccurred()) Expect(errors.Is(err, v2.ErrInvalidCommand)).To(BeTrue()) }) }) }) ``` -------------------------------- ### Basic CLI Application Setup Source: https://github.com/larsartmann/cmdguard/blob/master/docs/planning/2026-03-22_v3.0-major-redesign-plan.md Demonstrates how to create a basic CLI application with a single command using Cmdguard. ```go package main import ( "context" "fmt" "github.com/larsartmann/cmdguard/v3" ) type Config struct { LogLevel v3.LogLevel `flag:"log-level" short:"l" default:"info" help:"Log level" } func main() { cli, err := v3.New[Config]("myapp", "My application", Config{}) if err != nil { panic(err) } cli.AddCommand(v3.Command[Config, v3.NoFlags]("greet", v3.WithShort("Say hello"), v3.WithRunE(func(ctx context.Context, cfg *Config, _ v3.NoFlags) error { fmt.Println("Hello!") return nil }), )) cli.ExecuteAndExit(context.Background()) } ``` -------------------------------- ### Run Typed Example Source: https://github.com/larsartmann/cmdguard/blob/master/examples/README.md Execute the typed cmdguard example. This example showcases dependency injection and lifecycle hooks. ```bash go run examples/typed/main.go ``` -------------------------------- ### Add examples/middleware/ Example Source: https://github.com/larsartmann/cmdguard/blob/master/docs/status/2026-05-27_02-41_consumer-perspective-audit-resolution-status.md Create a dedicated example to illustrate the concept and implementation of middleware patterns within the CLI framework. This will help users understand how to apply middleware for cross-cutting concerns. ```go Add examples/middleware/ — Dedicated middleware example (est. 30 min) ``` -------------------------------- ### Run Kitchen Sink Example Source: https://github.com/larsartmann/cmdguard/blob/master/examples/README.md Execute the kitchen sink example for cmdguard. This is a full task manager combining all features. ```bash go run examples/kitchen-sink/main.go list ``` -------------------------------- ### Bash: Build and test examples Source: https://github.com/larsartmann/cmdguard/blob/master/docs/modularization/EXECUTION_PLAN.md Ensure that all examples within the project build and execute correctly after potential import changes. This step is crucial for validating example code. ```bash go build ./examples/... go test ./examples/... -count=1 -timeout 120s -race ``` -------------------------------- ### Running the Basic CLI Source: https://github.com/larsartmann/cmdguard/blob/master/docs/TUTORIAL.md Demonstrates how to run the initialized CLI and access its help message. This verifies the basic setup. ```bash go run main.go --help ``` -------------------------------- ### Add examples/version/ Example Source: https://github.com/larsartmann/cmdguard/blob/master/docs/status/2026-05-27_02-41_consumer-perspective-audit-resolution-status.md Create a dedicated example for the MustVersionCommand functionality. This will provide a clear and focused demonstration of how to implement version commands in CLI applications. ```go Add examples/version/ — Dedicated example for MustVersionCommand (est. 30 min) ``` -------------------------------- ### Cmdguard CLI Usage Example Source: https://github.com/larsartmann/cmdguard/blob/master/docs/ARCHITECTURE_REVIEW.md A basic example demonstrating how to initialize the cmdguard root command, add a new command, and execute it. ```go package main import ( "context" "github.com/larsartmann/cmdguard/pkg/cmdguard" "github.com/spf13/cobra" ) func main() { // Create root - single step initialization root := cmdguard.New("myapp", "My application") // Add commands - panics if invalid root.AddCommand(&cobra.Command{ Use: "greet", Short: "Say hello", Run: func(cmd *cobra.Command, args []string) { println("Hello!") }, }) // Execute root.Execute(context.Background()) } ``` -------------------------------- ### Example: Output Table and Result Formats Source: https://github.com/larsartmann/cmdguard/blob/master/docs/status/2026-04-30_03-57_comprehensive-status-report.md Shows how to use OutputTable and OutputResult with various formats. ```go package main import ( "fmt" "github.com/larsartmann/cmdguard/v2" "github.com/larsartmann/cmdguard/v2/output" ) type MyData struct { Name string `json:"name"` Value int `json:"value"` } func main() { data := []MyData{ {Name: "Item A", Value: 10}, {Name: "Item B", Value: 20}, } cli := cmdguard.New( cmdguard.WithName("mycli"), ) // Example using OutputTable fmt.Println("--- OutputTable ---") _ = cli.OutputTable(data, output.FormatJSON) // Example using OutputResult fmt.Println("--- OutputResult ---") _ = cli.OutputResult(data, output.FormatYAML) } ``` -------------------------------- ### Run Signals Example Source: https://github.com/larsartmann/cmdguard/blob/master/examples/README.md Execute the signal handling example for cmdguard. This demonstrates graceful shutdown with signal handling. ```bash go run examples/signals/main.go serve ``` -------------------------------- ### Run Output Example Source: https://github.com/larsartmann/cmdguard/blob/master/examples/README.md Execute the rich output formats example for cmdguard. This supports table, JSON, CSV, and YAML formats. ```bash go run examples/output/main.go users --format json ``` -------------------------------- ### Add examples/strict-validation/ Example Source: https://github.com/larsartmann/cmdguard/blob/master/docs/status/2026-05-27_02-41_consumer-perspective-audit-resolution-status.md Introduce an example demonstrating the usage of WithStrictValidation and WithDraconianValidation options. This will illustrate how to enforce stricter argument parsing and validation rules. ```go Add examples/strict-validation/ — Example showing WithStrictValidation and WithDraconianValidation (est. 30 min) ``` -------------------------------- ### Example: Graceful Shutdown with Signal Handling Source: https://github.com/larsartmann/cmdguard/blob/master/docs/status/2026-04-30_03-57_comprehensive-status-report.md Shows how to implement graceful shutdown using WithSignalHandling. ```go package main import ( "context" "fmt" "os" "os/signal" "syscall" "time" "github.com/larsartmann/cmdguard/v2" ) func main() { cli := cmdguard.New( cmdguard.WithName("mycli"), // Enable signal handling for graceful shutdown cmdguard.WithSignalHandling(os.Interrupt, syscall.SIGTERM), ) // Simulate a long-running process ctx, cancel := context.WithCancel(context.Background()) defer cancel() go func() { fmt.Println("Service started. Press Ctrl+C to stop.") select { case <-ctx.Done(): fmt.Println("Context cancelled, shutting down...") return } }() // Wait for interrupt signal or context cancellation ssig := cli.WaitForSignal() sselect { case <-sig: fmt.Println("\nReceived shutdown signal. Initiating graceful shutdown...") cancel() // Signal the long-running process to stop case <-ctx.Done(): // This case is unlikely to be hit here unless cancel() is called elsewhere fmt.Println("Context done, shutting down...") } // Simulate graceful shutdown delay time.Sleep(2 * time.Second) fmt.Println("Shutdown complete.") } ``` -------------------------------- ### Add examples/positional-args/ Example Source: https://github.com/larsartmann/cmdguard/blob/master/docs/status/2026-05-27_02-41_consumer-perspective-audit-resolution-status.md Create an example showcasing the different options for handling positional arguments, such as WithExactArgs, WithRangeArgs, etc. This will help users understand how to define and manage positional parameters in their CLIs. ```go Add examples/positional-args/ — Example for WithExactArgs, WithRangeArgs, etc. (est. 30 min) ``` -------------------------------- ### Example: Environment Tag Priority Chain Source: https://github.com/larsartmann/cmdguard/blob/master/docs/status/2026-04-30_03-57_comprehensive-status-report.md Demonstrates the priority chain for environment variables when using WithEnvPrefix. ```go package main import ( "fmt" "os" "github.com/larsartmann/cmdguard/v2" ) func main() { // Example: Set environment variables to test priority os.Setenv("APP_NAME_VERSION", "myapp-v1.0.0") os.Setenv("APP_NAME", "myapp") cli := cmdguard.New( cmdguard.WithName("myapp"), cmdguard.WithEnvPrefix("APP_NAME"), // This prefix is used for env vars ) // The flag will be resolved from APP_NAME_VERSION first, then APP_NAME version, err := cli.OutputFormat("version") if err != nil { panic(err) } fmt.Printf("Resolved version: %s\n", version) } ``` -------------------------------- ### Get output package Source: https://github.com/larsartmann/cmdguard/blob/master/docs/modularization/DEPENDENCY_GRAPH.md Example of how to get only the 'output' package. This package depends on 'go-output'. ```bash go get github.com/larsartmann/cmdguard/output → pulls in: go-output + transitive deps ``` -------------------------------- ### Get types package Source: https://github.com/larsartmann/cmdguard/blob/master/docs/modularization/DEPENDENCY_GRAPH.md Example of how to get only the 'types' package. This package has no external dependencies. ```bash go get github.com/larsartmann/cmdguard/types → pulls in: nothing (stdlib only) ``` -------------------------------- ### Write "Building a Task CLI" Tutorial Source: https://github.com/larsartmann/cmdguard/blob/master/docs/status/2026-05-27_02-41_consumer-perspective-audit-resolution-status.md Create a narrative tutorial to improve the onboarding experience for new users. This tutorial will guide users through building a real-world CLI application end-to-end, complementing the existing reference documentation. ```go Write "Building a Task CLI" tutorial — Narrative walkthrough in docs/TUTORIAL.md (est. 3–4 hours) ``` -------------------------------- ### Dependency Injection Setup and Invocation Source: https://github.com/larsartmann/cmdguard/blob/master/docs/FEATURES.md Shows how to register services using `v2.Provide` and `v2.ProvideValue`, and how to invoke them within command handlers using `v2.Invoke`. ```go // Register services func setupDI(scope *v2.Scope, cfg Config) { // Provide with constructor v2.Provide(scope, func(i do.Injector) (*Database, error) { return &Database{URL: cfg.DBURL}, nil }) // Provide value directly v2.ProvideValue(scope, &Logger{Level: cfg.LogLevel}) } // Invoke in handlers (with proper error handling) RunE: func(ctx context.Context, cfg *Config, flags *Flags) error { db, err := v2.Invoke[*Database](cli.ScopeStruct()) if err != nil { return v2.NewServiceError("*Database", err) } logger, err := v2.Invoke[*Logger](cli.ScopeStruct()) if err != nil { return v2.NewServiceError("*Logger", err) } // ... } ``` -------------------------------- ### Install Direnv and Nix-Direnv Source: https://github.com/larsartmann/cmdguard/blob/master/MIGRATION_TO_NIX_FLAKES_PROPOSAL.md Provides instructions for installing direnv and nix-direnv on macOS and configuring them for shell integration. This setup is necessary for using the `use flake` command in `.envrc`. ```bash # Install direnv (macOS) brew install direnv # Add to shell rc (~/.zshrc or ~/.bashrc) eval "$(direnv hook zsh)" # or bash # Install nix-direnv for persistent GC roots nix profile install nixpkgs#nix-direnv # Then in project root direnv allow ``` -------------------------------- ### Run Example: Greet Command with Options Source: https://github.com/larsartmann/cmdguard/blob/master/README.md Demonstrates executing the 'greet' command with custom name and shout options. The output is uppercased as requested. ```bash $ go run main.go greet -n "cmdguard" --shout HELLO, CMDGUARD! ``` -------------------------------- ### Enable Nix Integrations with Direnv Source: https://github.com/larsartmann/cmdguard/blob/master/MIGRATION_TO_NIX_FLAKES_PROPOSAL.md Activates Nix integrations for automatic shell environment setup using direnv and nix-direnv. Ensure direnv and nix-direnv are installed and configured in your shell's rc file. ```bash # Enable nix integrations for automatic shell activation # Requires: direnv (https://direnv.net/) and nix-direnv use flake ``` -------------------------------- ### Run the Simple CLI Source: https://github.com/larsartmann/cmdguard/blob/master/docs/QUICKSTART.md Execute the 'hello' CLI with the 'greet' command and view its output. Also, check the help message. ```bash go run main.go greet # Output: Hello, World! go run main.go --help # Shows styled usage help ``` -------------------------------- ### Add More Godoc Examples Source: https://github.com/larsartmann/cmdguard/blob/master/docs/status/2026-05-27_02-41_consumer-perspective-audit-resolution-status.md Enhance the godoc documentation by adding more inline code examples for various functionalities. This includes examples for NewParentCommand, WithPreRunE/PostRunE, WithConfigFile, GenerateManPageCommand, and EditInEditor. ```go Add more godoc examples — NewParentCommand, WithPreRunE/PostRunE, WithConfigFile, GenerateManPageCommand, EditInEditor (est. 1–2 hours) ``` -------------------------------- ### Add godoc Example for ParseURL Source: https://github.com/larsartmann/cmdguard/blob/master/docs/EXECUTION_PLAN_2026-04-01_REFINED.md Include godoc examples to demonstrate API usage and help users understand how to use the ParseURL function. Examples are displayed in godoc. ```go func ExampleParseURL() { u, err := v2.ParseURL("https://example.com") if err != nil { log.Fatal(err) } fmt.Println(u.Hostname()) // Output: example.com } ``` -------------------------------- ### Initialize CLI with Options Source: https://github.com/larsartmann/cmdguard/blob/master/README.md Initialize a new CLI application with various configuration options like version, environment prefix, signal handling, and validation. ```go cli, _ := v2.NewCLI[AppConfig]("myapp", "My app", AppConfig{}, v2.WithCLIVersion[AppConfig]("1.0.0"), v2.WithEnvPrefix[AppConfig]("MYAPP_"), v2.WithSignalHandling[AppConfig](), v2.WithFang[AppConfig](true), // Styled help output v2.WithMiddleware[AppConfig](myMiddleware), // Wrap all handlers v2.WithStrictValidation[AppConfig](), // Require WithShort on commands v2.WithConfigValidation[AppConfig](validateFn), // Validate config after parsing ) ``` -------------------------------- ### Running with Defaults and Config File Source: https://github.com/larsartmann/cmdguard/blob/master/examples/config-file/README.md Shows how to run the application with default settings and then with a configuration file loaded from the default location. ```bash # With defaults go run . # With config file mkdir -p ~/.config/greet echo '{"name": "Config", "count": 3}' > ~/.config/greet/config.json go run . ``` -------------------------------- ### Lint Failure Example Source: https://github.com/larsartmann/cmdguard/blob/master/docs/status/2026-05-16_22-29_mid-session-honest-status.md An example of a linting error, specifically a function that is too long. ```go pkg/cmdguard/v2/cli_command.go:48:6: Function 'cliToCobraCommand' is too long (91 > 80) (funlen) ``` -------------------------------- ### Run Subcommands Example Source: https://github.com/larsartmann/cmdguard/blob/master/examples/README.md Execute the subcommands example for cmdguard. This shows how to use NewParentCommand and command groups. ```bash go run examples/subcommands/main.go migrate up --env=production ``` -------------------------------- ### Opt-in DI with v2.New Source: https://github.com/larsartmann/cmdguard/blob/master/docs/API_DESIGN_REVIEW.md Demonstrates how to create a CLI instance with and without dependency injection using functional options. ```go cli, _ := v2.New[Config]("app", "My app", Config{}) // No DI cli, _ := v2.New[Config]("app", "My app", Config{}, v2.WithDI(), // Opt-in to DI ) ``` -------------------------------- ### Run Validation Example Source: https://github.com/larsartmann/cmdguard/blob/master/examples/README.md Execute the validation example for cmdguard. This showcases PreRunE validation and required flags. ```bash go run examples/validation/main.go greet --name=Alice ``` -------------------------------- ### Table-Driven Test Example in Go Source: https://github.com/larsartmann/cmdguard/blob/master/CONTRIBUTING.md An example of a table-driven test for a Go function, using testify/require for assertions. ```go func TestNewGuardedCommand(t *testing.T) { tests := []struct { name string args []string wantErr bool }{ {"valid", []string{"test"}, false}, {"empty", []string{}, true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := New(tt.args...) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) }) } } ``` -------------------------------- ### Create and Execute Basic CLI Application Source: https://github.com/larsartmann/cmdguard/blob/master/AGENTS.md This snippet shows how to initialize a new CLI application with a specific configuration struct and add a simple command. It then executes the CLI with the background context. ```Go package main import ( "context" "fmt" "github.com/larsartmann/cmdguard/pkg/cmdguard/v2" ) type AppConfig struct { Verbose bool `flag:"verbose" short:"v" default:"false" help:"Enable verbose output"` Output string `flag:"output" short:"o" default:"text" help:"Output format"` } func main() { cli, err := v2.NewCLI[AppConfig]("myapp", "My application", AppConfig{}) if err != nil { panic(err) } cmd, err := v2.NewCommand[AppConfig, v2.NoFlags]("hello", func(ctx context.Context, cfg *AppConfig, flags v2.NoFlags) error { fmt.Printf("Hello! Verbose: %v\n", cfg.Verbose) return nil }, v2.WithShort[AppConfig, v2.NoFlags]("Say hello"), ) if err != nil { panic(err) } if err := v2.AddCommand(cli, cmd); err != nil { panic(err) } if err := cli.Execute(context.Background()); err != nil { fmt.Println("Error:", err) } } ``` -------------------------------- ### Run Env Tags Example Source: https://github.com/larsartmann/cmdguard/blob/master/examples/README.md Execute the environment variable binding example for cmdguard. This demonstrates binding with WithEnvPrefix. ```bash DB_HOST=db.example.com go run examples/env-tags/main.go show ``` -------------------------------- ### Conventional Commit Message Example Source: https://github.com/larsartmann/cmdguard/blob/master/CONTRIBUTING.md Example of a conventional commit message for a new feature, including a detailed body. ```bash git commit -m "feat: add JSON logging option - Add LoggerFormat option to Config - Support \"json\" and \"text\" formats - Default remains \"text\" for backward compatibility Assisted-by: Your Name " ``` -------------------------------- ### Initializing a Structured Logger Source: https://github.com/larsartmann/cmdguard/blob/master/PARTS.md Provides an example of setting up a basic structured logger using the standard library's slog package. It shows how to configure the logger's format and level. ```go logger := logging.NewLogger("text", "debug") // or "json", "info", etc. ``` -------------------------------- ### Command and CLI Initialization with Error Handling Source: https://github.com/larsartmann/cmdguard/blob/master/AGENTS.md Initialize CLIs and Commands, and demonstrate checking for sentinel errors and using rich error types. ```go // All v2 functions return errors cli, err := v2.NewCLI[Config]("app", "My app", Config{}) cmd, err := v2.NewCommand[Config, NoFlags]("test", handler) // Sentinel errors for errors.Is() errors.Is(err, v2.ErrInvalidCommand) errors.Is(err, v2.ErrMissingName) errors.Is(err, v2.ErrDuplicateCommand) errors.Is(err, v2.ErrMissingHandler) // Rich error types v2.NewCommandError(name, err) // wraps with command context v2.NewServiceError(type, err) // wraps with DI service context v2.NewFlagError(name, err) // wraps with flag context v2.NewFlagErrorWithSuggestion(name, err, suggestion) // includes typo fix // Exit codes v2.NewExitError(code, err) // error with custom exit code for ExecuteAndExit errors.As(err, &exitCoder) // check if error implements ExitCoder ``` -------------------------------- ### Run Error Handling Example Source: https://github.com/larsartmann/cmdguard/blob/master/examples/README.md Execute the error handling example for cmdguard. This covers sentinel errors, FlagError, and suggestions. ```bash go run examples/error-handling/main.go fetch --url=invalid ``` -------------------------------- ### Nix Quick Start for Reviewers Source: https://github.com/larsartmann/cmdguard/blob/master/MIGRATION_TO_NIX_FLAKES_PROPOSAL.md A sequence of bash commands to set up a Nix development environment, enable flakes, enter a development shell, run checks, and format Nix files. ```bash # 1. Install Nix (if not already installed) curl --proto '=https' --tlsv1.2 -sSf -L https://install.determinate.systems/nix | sh -s -- install # 2. Enable flakes (add to ~/.config/nix/nix.conf or /etc/nix/nix.conf) experimental-features = nix-command flakes # 3. Enter dev shell nix develop # 4. Run all checks nix flake check -L # 5. Format Nix files nix fmt ``` -------------------------------- ### Bootstrap Application with cmdguard and DI Source: https://github.com/larsartmann/cmdguard/blob/master/docs/design/2026-02-15_v2_type_safe_di_design.md Initialize the cmdguard application, define the root scope, register services using `samber/do/v2`, and add commands. This process returns errors instead of panicking. ```go package main import ( "context" "github.com/larsartmann/cmdguard/v2/pkg/cmdguard" "github.com/samber/do/v2" ) // Define your config - SINGLE SOURCE OF TRUTH type Config struct { LogLevel cmdguard.Enum `flag:"log-level" short:"l" default:"info" values:"debug,info,warn,error"` LogFormat cmdguard.Enum `flag:"log-format" default:"text" values:"text,json"` StrictMode bool `flag:"strict" short:"s" default:"false"` } func main() { ctx := context.Background() // Create root scope with config root := cmdguard.New("myapp", "My application", Config{}) // Register services in root scope do.Provide(root, NewLogger) do.Provide(root, NewDatabase) // Build command tree (returns errors, never panics) if err := root.AddCommand(greetCmd()); err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) os.Exit(1) } // Execute - injects typed config everywhere if err := root.Execute(ctx); err != nil { os.Exit(1) } } ``` -------------------------------- ### CLI Application with Dependency Injection Source: https://github.com/larsartmann/cmdguard/blob/master/docs/planning/2026-03-22_v3.0-major-redesign-plan.md Demonstrates setting up a CLI application with dependency injection using Cmdguard and samber/do. ```go type Database struct { /* ... */ } func NewDatabase(cfg *Config) (*Database, error) { return &Database{dsn: cfg.DSN}, nil } func main() { cli, _ := v3.New[Config]("myapp", "My app", Config{}, v3.WithDI(), ) // Register services v3.Provide(cli.Scope(), func(i do.Injector) (*Database, error) { cfg := v3.MustInvoke[*Config](cli.Scope()) return NewDatabase(cfg) }) cli.AddCommand(v3.Command[Config, v3.NoFlags]("migrate", v3.WithRunE(func(ctx context.Context, cfg *Config, _ v3.NoFlags) error { db := v3.MustInvoke[*Database](cli.Scope()) return db.Migrate(ctx) }), )) cli.ExecuteAndExit(context.Background()) } ``` -------------------------------- ### Run DI Patterns Example Source: https://github.com/larsartmann/cmdguard/blob/master/examples/README.md Execute the DI patterns example for cmdguard. This covers service registration, invocation, and health checks. ```bash go run examples/di-patterns/main.go list ``` -------------------------------- ### Initialize Go Workspace Source: https://github.com/larsartmann/cmdguard/blob/master/docs/modularization/EXECUTION_PLAN.md Sets up a Go workspace at the repository root and includes the root module. ```bash go work init go work use . go work sync ``` -------------------------------- ### Creating a New CLI with Error Handling Source: https://github.com/larsartmann/cmdguard/blob/master/docs/QUICKSTART.md Demonstrates the proper way to initialize a new CLI application, including essential error handling for the `NewCLI` function. ```go cli, err := v2.NewCLI[AppConfig]("myapp", "My app", AppConfig{}) if err != nil { return err } ``` -------------------------------- ### Run Counting Flags Example Source: https://github.com/larsartmann/cmdguard/blob/master/examples/README.md Execute the counting flags example for cmdguard. This demonstrates verbose flags like -v, -vv, and -vvv. ```bash go run examples/counting/main.go greet -vvv ```