Custom Value Types
Built-in Value Types
Section titled “Built-in Value Types”cmdguard ships with validated types that parse a flag the moment it is read. A bad value fails the command with a typed error; nothing panics and nothing waits until the handler touches the field.
| Type | Constructor | Validation |
|---|---|---|
Duration |
v5.ParseDuration, v5.FromDuration |
time.ParseDuration syntax (30s, 1h30m) |
Enum |
v5.ParseEnum(value, allowed) |
Membership in the allowed list |
URL |
v5.ParseURL |
Absolute URL with scheme and host |
Email |
v5.ParseEmail |
RFC 5322 address |
Port |
v5.ParsePort, v5.PortFromInt |
1 to 65535, numeric or named |
HostPort |
v5.ParseHostPort, v5.NewHostPort |
host:port |
FilePath |
v5.ParseFilePath(s, checkExists) |
Cleaned path, optional existence check |
LogLevel |
v5.ParseLogLevel |
debug, info, warn, error |
LogFormat |
v5.ParseLogFormat |
text, json |
Use them as plain flag fields:
type ServerFlags struct { Addr v5.HostPort `flag:"addr" default:"localhost:8080" help:"Listen address"` Mode v5.Enum `flag:"mode" default:"dev" values:"dev,staging,prod" help:"Run mode"` Timeout v5.Duration `flag:"timeout" default:"30s" help:"Shutdown timeout"`}Enum needs a values tag, because parsing checks the value against that list. LogLevel and LogFormat carry their own allowed sets. time.Duration works directly as a field type, and time.Time is treated as an atomic value in config structs.
Registering a Custom Type
Section titled “Registering a Custom Type”A custom type is wired in with a TypeCodec: a Register method, a Parse method, and a Default method. Most codecs use the TypeCodecFunc adapter, which takes one function per method. RegisterFunc is mandatory: a codec that registers nothing makes the flag vanish and surface later as “unknown flag”, so cmdguard rejects it at registration time.
package main
import ( "context" "fmt" "log" "reflect"
"github.com/larsartmann/cmdguard/v5/pkg/cmdguard/v5" "github.com/spf13/pflag")
type Env string
func ParseEnv(s string) (Env, error) { switch s { case "dev", "staging", "prod": return Env(s), nil } return "", fmt.Errorf("unknown environment %q", s)}
type DeployFlags struct { Target Env `flag:"target" default:"dev" help:"Deployment target"`}
type AppConfig struct{}
func main() { err := v5.RegisterTypeCodec(reflect.TypeFor[Env](), v5.TypeCodecFunc{ RegisterFunc: func(flags *pflag.FlagSet, tag v5.FlagTag) error { flags.StringP(tag.Name, tag.Short, tag.Default, tag.Help) return nil }, ParseFunc: func(value string, _ v5.FlagTag) (any, error) { return ParseEnv(value) }, DefaultFunc: func(tag v5.FlagTag) any { env, _ := ParseEnv(tag.Default) return env }, }) if err != nil { log.Fatal(err) }
cli, err := v5.NewCLI[AppConfig]("deploy", "Custom type example", AppConfig{}) if err != nil { log.Fatal(err) }
b := v5.NewBuilder(cli) v5.Add(b, "plan", DeployFlags{}, func(_ context.Context, _ *AppConfig, f DeployFlags) error { fmt.Println("target:", f.Target) return nil }, v5.WithShort("Plan a deployment"), ) if err := b.Build(); err != nil { log.Fatal(err) }
cli.ExecuteAndExit(context.Background())}RegisterFuncadds the pflag that stores the raw value. Usetag.Name,tag.Short,tag.Default, andtag.Helpso the flag looks native.ParseFuncconverts the raw string to your type, andDefaultFuncsupplies the typed default (or the zero value). Parse errors are wrapped with the flag name and value.
Register the codec before constructing the command that uses the type. Flags are registered once at construction, so a codec added later cannot retroactively register a flag.
Defaults Are Validated at Construction
Section titled “Defaults Are Validated at Construction”A tag default is checked against the same rules as user input, so an impossible default fails NewCLI instead of shipping a broken flag. The check covers values lists and every resolvable validate rule:
type AppConfig struct { Mode string `flag:"mode" default:"staging" values:"dev,prod"`}
cli, err := v5.NewCLI[AppConfig]("app", "My app", AppConfig{})if errors.Is(err, v5.ErrInvalidFlagDefault) { // "staging" is not in values:"dev,prod"}Global and Instance Registries
Section titled “Global and Instance Registries”RegisterTypeCodec writes to the package-level defaults, which every registry created afterwards sees through a shared, copy-on-write view. FlagRegistry.RegisterTypeCodec and FlagRegistry.RegisterFlagValidator write only to one registry and trigger a lazy clone on first write, so two registries never share mutations.
err := v5.RegisterTypeCodec(reflect.TypeFor[Env](), codec)
registry, err := v5.NewFlagRegistry(DeployFlags{})if err != nil { return err}registry.RegisterTypeCodec(reflect.TypeFor[Env](), codec)Custom Validators
Section titled “Custom Validators”validate tags resolve validator names. Built-ins cover email, url, nonempty, regex, min, max, minlen, maxlen, dmin, and dmax; add your own with RegisterValidator, whose signature is v5.FlagValidator:
err := v5.RegisterValidator("alphanumeric", func(value string) error { matched, _ := regexp.MatchString(`^[a-zA-Z0-9]+$`, value) if !matched { return fmt.Errorf("must be alphanumeric") } return nil})Once registered, the name works in any tag: validate:"alphanumeric,minlen=3". Rules run against the value the flag resolves to, so a value from an environment variable or a tag default is validated too, not only one typed on the command line.
Where to go next
Section titled “Where to go next”- Type-Safe Flags for the full tag and scope reference.
- Plugin System for bundling codecs and validators into one registration.
- Config Files for the same types as config-file values.