Documentation
¶
Overview ¶
Package cli is a zero-dependency command framework: a command tree dispatched from os.Args, flags with environment binding, layered configuration, and generated help.
Commands compose into a tree and dispatch context-first; handlers are plain funcs. Flags declared on a command are visible to it and all of its descendants, and every flag resolves with one fixed precedence:
explicit flag > environment variable > *_FILE indirection > config file > default
Environment names derive mechanically from flag names — with prefix MY_SERVICE, --http-addr binds to MY_SERVICE_HTTP_ADDR and MY_SERVICE_HTTP_ADDR_FILE — so the mapping is never documented by hand. The prefix is per-binary, derived from the root command's name, overridable via EnvPrefix, and disabled with NoPrefix.
Config files are JSON (the stdlib format); other formats plug in through the Decoder seam without cli growing parsers.
Exit codes follow convention: 0 success, 1 a command's Run returned an error, 2 usage, environment, or configuration error. Help and version output go to stdout; errors go to stderr.
Index ¶
- Constants
- func LoadDotEnv(path string) error
- type Command
- type ConfigFile
- type Decoder
- type FlagSet
- func (fs *FlagSet) Bind(v any)
- func (fs *FlagSet) Bool(name string, value bool, usage string) *bool
- func (fs *FlagSet) BoolVar(p *bool, name string, value bool, usage string)
- func (fs *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration
- func (fs *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string)
- func (fs *FlagSet) Float64(name string, value float64, usage string) *float64
- func (fs *FlagSet) Float64Var(p *float64, name string, value float64, usage string)
- func (fs *FlagSet) Int(name string, value int, usage string) *int
- func (fs *FlagSet) Int64(name string, value int64, usage string) *int64
- func (fs *FlagSet) Int64Var(p *int64, name string, value int64, usage string)
- func (fs *FlagSet) IntVar(p *int, name string, value int, usage string)
- func (fs *FlagSet) Required(name string)
- func (fs *FlagSet) Secret(name string)
- func (fs *FlagSet) String(name, value, usage string) *string
- func (fs *FlagSet) StringVar(p *string, name, value, usage string)
- func (fs *FlagSet) Var(value flag.Value, name, usage string)
Constants ¶
const NoPrefix = "-"
NoPrefix disables environment variable prefixing when set as a root Command's EnvPrefix: --http-addr binds to HTTP_ADDR. An empty EnvPrefix derives the prefix from the root command's name instead.
Variables ¶
This section is empty.
Functions ¶
func LoadDotEnv ¶
LoadDotEnv loads KEY=VALUE lines from path into the process environment, then returns — the environment layer picks the values up through the normal precedence, so keys carry the same prefixed names real environment variables do. Call it before Execute.
Variables already present in the environment win: the file supplies defaults for a bare machine, the real environment — a container orchestrator, CI — always overrides it.
The format is the minimal dotenv subset: one KEY=VALUE per line, blank lines and #-comments skipped, whitespace trimmed around the key, matching single or double quotes stripped from the value, a leading UTF-8 BOM ignored. A key containing whitespace — including shell-style "export KEY=..." lines — is a line-numbered error, never a silently wrong variable. No interpolation, no escapes, no multiline values — a file needing those belongs to an orchestrator's env_file, not to this loader.
Types ¶
type Command ¶
type Command struct {
// Name is the binary name on the root command and the verb on a
// subcommand ("serve", "migrate").
Name string
// Short is the one-line description shown in the parent's command list.
Short string
// Long is the description shown in this command's own help; Short is
// used when Long is empty.
Long string
// Flags declares this command's flags on the given set. Declared
// flags are visible to this command and all of its descendants;
// redeclaring an inherited name panics at dispatch.
Flags func(fs *FlagSet)
// Run executes the command; args are the operands left after flag
// parsing. A command with subcommands may leave Run nil — invoking it
// bare then prints help.
Run func(ctx context.Context, args []string) error
// Commands are the subcommands, matched by Name.
Commands []*Command
// Version enables the version subcommand and the --version flag,
// printing "<name> <version>". Root-only.
Version string
// EnvPrefix overrides the environment prefix derived from Name; the
// NoPrefix sentinel disables prefixing. Root-only.
EnvPrefix string
// Config enables config file support; the zero value disables it.
// Root-only.
Config ConfigFile
// contains filtered or unexported fields
}
Command is one node of a command tree. The zero value is unusable; set at least Name. Fields marked root-only are ignored on subcommands.
func (*Command) Execute ¶
Execute parses os.Args[1:], dispatches through the tree, resolves every visible flag with the documented precedence, and runs the resolved command. It returns the process exit code: 0 success, 1 the command's Run returned an error, 2 usage, environment, or configuration error.
type ConfigFile ¶
type ConfigFile struct {
// Flag is the flag name carrying the path, e.g. "config"; empty
// disables config file support.
Flag string
// Decoder decodes the file into flag values. Nil means JSON: a flat
// object keyed by flag name, with string, number, or bool values.
Decoder Decoder
}
ConfigFile enables config file support on a root Command. The named flag carries the file path; if the root does not declare it, cli declares it as a string flag with an empty default. A path set explicitly (flag or environment) must exist; a non-empty default path that does not exist is skipped.
type Decoder ¶
Decoder decodes config file bytes into a flat map keyed by flag name. Values are strings and flow through flag.Value.Set exactly like command-line input. Format packages plug in here.
type FlagSet ¶
type FlagSet struct {
// contains filtered or unexported fields
}
FlagSet declares a command's flags. It mirrors the flag.FlagSet constructors exactly — String, Bool, Int, Int64, Float64, Duration, their *Var forms, and Var — and adds only Secret. Values set from the environment or a config file flow through the same flag.Value.Set path as command-line input.
func (*FlagSet) Bind ¶
Bind declares one flag per exported field of the struct v points to — the struct is the schema, and every configuration layer resolves into it through the declared flags.
The `cli` tag names the flag and carries options; without it the name derives from the field name (HTTPAddr → http-addr, DBPassword → db-password). `cli:"-"` skips the field.
type Config struct {
HTTPAddr string `cli:"http-addr" default:":8080" usage:"listen address"`
DBPassword string `cli:"db-password,secret,required" usage:"database password"`
Timeout time.Duration `usage:"request timeout"`
}
Options: `secret` marks the flag as Secret; `required` makes startup fail with exit 2 unless some layer supplies a value. The `default` tag sets the default; without it the field's current value is the default. A field that is `required` cannot also carry a `default` — the pair is contradictory and panics at declaration.
Supported field types: string, bool, int, int64, float64, time.Duration, and any field whose pointer implements flag.Value. Anything else panics at declaration — a programmer error, caught at boot. Unexported fields are skipped. A required field must start at its zero value.
Bind assumes one Execute per process: without a default tag the field's current value is the default, so re-executing the same tree treats the previous run's result as the new default.
func (*FlagSet) Bool ¶
Bool defines a bool flag with specified name, default value, and usage string. The return value is the address of a bool variable that stores the value of the flag.
func (*FlagSet) BoolVar ¶
BoolVar defines a bool flag with specified name, default value, and usage string. The argument p points to a bool variable in which to store the value of the flag.
func (*FlagSet) Duration ¶
Duration defines a time.Duration flag with specified name, default value, and usage string. The return value is the address of a time.Duration variable that stores the value of the flag.
func (*FlagSet) DurationVar ¶
DurationVar defines a time.Duration flag with specified name, default value, and usage string. The argument p points to a time.Duration variable in which to store the value of the flag.
func (*FlagSet) Float64 ¶
Float64 defines a float64 flag with specified name, default value, and usage string. The return value is the address of a float64 variable that stores the value of the flag.
func (*FlagSet) Float64Var ¶
Float64Var defines a float64 flag with specified name, default value, and usage string. The argument p points to a float64 variable in which to store the value of the flag.
func (*FlagSet) Int ¶
Int defines an int flag with specified name, default value, and usage string. The return value is the address of an int variable that stores the value of the flag.
func (*FlagSet) Int64 ¶
Int64 defines an int64 flag with specified name, default value, and usage string. The return value is the address of an int64 variable that stores the value of the flag.
func (*FlagSet) Int64Var ¶
Int64Var defines an int64 flag with specified name, default value, and usage string. The argument p points to an int64 variable in which to store the value of the flag.
func (*FlagSet) IntVar ¶
IntVar defines an int flag with specified name, default value, and usage string. The argument p points to an int variable in which to store the value of the flag.
func (*FlagSet) Required ¶
Required marks a declared flag as mandatory: unless some layer — command line, environment, *_FILE, or config file — supplies a value, Execute fails with exit 2 before Run. Marking an undeclared flag panics.
func (*FlagSet) Secret ¶
Secret marks a declared flag as secret: generated help masks its default value and error messages never echo its value. Marking an undeclared flag panics — a programmer error, caught at boot.
func (*FlagSet) String ¶
String defines a string flag with specified name, default value, and usage string. The return value is the address of a string variable that stores the value of the flag.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package migrationx is a SQL migration engine on the standard library: ordered SQL files, a history table with checksums, transactions where the database supports them, and a migration lock — with database drivers staying entirely on the consumer's side.
|
Package migrationx is a SQL migration engine on the standard library: ordered SQL files, a history table with checksums, transactions where the database supports them, and a migration lock — with database drivers staying entirely on the consumer's side. |