Skip to content

Type-Safe Flags

cmdguard replaces Cobra’s Flags().GetString("name") pattern with typed structs. A field becomes a flag when it carries a flag tag; NewCommand takes the flags struct by value and passes it to the handler as the third parameter. Root flags live in T, per-command flags in F.

package main
import (
"context"
"fmt"
"log"
"strings"
"github.com/larsartmann/cmdguard/v5/pkg/cmdguard/v5"
)
type AppConfig struct {
Verbose bool `flag:"verbose" short:"v" default:"false" help:"Enable verbose output"`
Config string `flag:"config" help:"Path to the config file" local:"true"`
}
type GreetFlags struct {
Name string `flag:"name" short:"n" default:"World" help:"Name to greet"`
Loud bool `flag:"loud" default:"false" help:"Uppercase the greeting"`
Times int `flag:"times" default:"1" help:"Repetitions" validate:"min=1,max=100"`
}
func main() {
cli, err := v5.NewCLI[AppConfig]("demo", "A greeting CLI", AppConfig{})
if err != nil {
log.Fatal(err)
}
b := v5.NewBuilder(cli)
v5.Add(b, "greet", GreetFlags{},
func(_ context.Context, _ *AppConfig, f GreetFlags) error {
msg := fmt.Sprintf("Hello, %s!", f.Name)
if f.Loud {
msg = strings.ToUpper(msg)
}
for range f.Times {
fmt.Println(msg)
}
return nil
},
v5.WithShort("Greet someone"),
v5.WithExample("demo greet --name Alice --times 2"),
)
if err := b.Build(); err != nil {
log.Fatal(err)
}
cli.ExecuteAndExit(context.Background())
}
Tag Effect Example
flag Flag name. A field registers as a flag only when this tag is present flag:"name"
short Single-character shorthand short:"n"
default Default value (the zero value when absent) default:"World"
help Help text help:"Name to greet"
env Environment variable fallback (prefixable with WithEnvPrefix) env:"DB_HOST"
required Must be set by flag or env var. Bool tag; a tag default does not satisfy it required:"true"
count Counting flag (-vvv becomes 3). The field must be int count:"true"
local Owning command only, not inherited by subcommands. Bool tag local:"true"
hidden Excluded from --help, fully functional. Bool tag hidden:"true"
values Comma-separated allowed values, enforced as an enum values:"dev,prod"
validate Rule list, enforced after parsing and against the default at construction validate:"min=1,max=100"
prompt Prompt text shown when the flag is missing (needs the prompts sub-module) prompt:"Your name?"
secret Redacts the value in config explain, describe, docs, and schemas secret:"true"
Where the field lives Scope
Root T struct, plain Persistent: inherited by every subcommand
Root T struct with local:"true" Root only, not inherited by subcommands
A command’s own F struct That command only, rejected elsewhere

F-struct flags are registered on the command’s own flag set, so demo greet --build fails with “unknown flag” unless the greet struct declares build. That is the designed behavior. A subcommand that needs a root-local flag opts in with cli.RegisterLocalCommandFlags(cobraCmd).

An explicit flag beats an environment variable, which beats a config-file value, which beats the tag default. Config-file values are loaded before flags register and rewrite the tag defaults, which is what gives them their position in the chain.

The count:"true" tag turns a field into a verbosity ladder: -v sets it to 1, -vvv to 3. The field must be an int, and counting flags must not reuse a root config flag name.

Ten rules ship built in; this is the whole registry (source of truth: flags_validate.go). Combine any of them comma-separated in one validate tag. An unknown rule name fails with ErrUnknownValidator; a malformed parameter with ErrInvalidValidatorParam.

Rule Parameter Checks Failure sentinel
email — RFC 5322 address (empty value passes) ErrInvalidEmail
url — Absolute URL with scheme (empty passes) ErrInvalidURL
minlen=N integer (rune count) string length ≥ N ErrValueTooShort
maxlen=N integer (rune count) string length ≤ N ErrValueTooLong
min=N number numeric value ≥ N ErrValueTooSmall
max=N number numeric value ≤ N ErrValueTooLarge
dmin=D duration (e.g. 10s) duration value ≥ D ErrValueTooSmall
dmax=D duration duration value ≤ D ErrValueTooLarge
regex=R Go regexp (RE2) value matches R ErrValuePatternMismatch
nonempty — value not empty ErrValueEmpty

min/max are type-aware: on string kinds (and URL/Email/HostPort/FilePath) they rewrite to length bounds; on durations (Duration, time.Duration) to duration bounds; on everything else they stay numeric. Prefer the explicit minlen/maxlen/dmin/dmax forms when you want the domain spelled out.

values:"a,b,c" rejects anything outside the list with ErrInvalidEnum.

Rules run against whatever the flag resolves to (flag → env → default), and tag defaults are re-checked at construction — an impossible default fails NewCLI with ErrInvalidFlagDefault, so a bad default never reaches users.

required:"true" runs after parsing and is satisfied only by an explicit flag or a set environment variable, so a default cannot mask a missing credential.

WithEnvPrefix prepends a prefix to every env tag lookup. The prefix is applied to the tag value verbatim, so an already prefixed tag gets it twice.

type DBFlags struct {
Host string `flag:"host" env:"DB_HOST" default:"localhost"`
Port int `flag:"port" env:"DB_PORT" default:"5432"`
}
cli, err := v5.NewCLI[AppConfig]("myapp", "My app", AppConfig{},
v5.WithEnvPrefix("MYAPP_"), // reads MYAPP_DB_HOST, MYAPP_DB_PORT
)
Type Parses
Duration 30s, 5m, 1h30m
Enum One value of an allowed list
LogLevel debug, info, warn, error
LogFormat text, json
URL Absolute URL with scheme and host
Email RFC 5322 address
Port 1 to 65535, numeric or named
HostPort host:port
FilePath Cleaned path, optional existence check

ParseFlagTags recurses into nested structs, so flags can be grouped while keeping flat flag names. Registered value types stay atomic and are never descended into.

type AppConfig struct {
Verbose bool `flag:"verbose" short:"v" default:"false"`
DB DatabaseConfig
}
type DatabaseConfig struct {
Host string `flag:"db-host" env:"DB_HOST" default:"localhost"`
Port int `flag:"db-port" env:"DB_PORT" default:"5432"`
}