Documentation
¶
Overview ¶
Package configbind loads Bind-style config from defaults, TOML, env, and CLI into structs.
Index ¶
- func Bind[T any](prefix string) *T
- func EnvName(longOpt string) string
- func ReadEnv(defs []cliparser.Def, environ []string) map[string]string
- func Register[T any](definition Definition)
- func RegisterSubCommand[T any](definition SubCommandDefinition)
- func ResetDefinitions()
- func ResetTargets()
- func ScaffoldEnv() (string, error)
- func ScaffoldTOML() (string, error)
- func SubCommand[T any](name, help string) *T
- func WriteScaffoldEnv(w io.Writer) error
- func WriteScaffoldTOML(w io.Writer) error
- type ApplyFunc
- type Definition
- type Entry
- type LoadOptions
- type LoadResult
- type Overlay
- func (o *Overlay) All() iter.Seq2[string, Entry]
- func (o *Overlay) Delete(key string)
- func (o *Overlay) Get(key string) (Entry, bool)
- func (o *Overlay) GetMulti(key string) ([]string, bool)
- func (o *Overlay) GetString(key string) (string, bool)
- func (o *Overlay) GetTables(key string) ([]*Overlay, bool)
- func (o *Overlay) Keys() []string
- func (o *Overlay) MergeMap(m map[string]string, place Place)
- func (o *Overlay) MergeMultiMap(m map[string][]string, place Place)
- func (o *Overlay) Set(key, raw string, place Place)
- func (o *Overlay) SetMulti(key string, values []string, place Place)
- func (o *Overlay) SetTables(key string, tables []*Overlay, place Place)
- type Place
- type Positional
- type PositionalRole
- type ProvenanceEntry
- type ScaffoldField
- type ScaffoldKind
- type SubCommandDefinition
- type UsageError
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Bind ¶
Bind allocates *T, registers it for the next Load, and returns the pointer. Code generation must Register[T] before Bind is used.
func EnvName ¶
EnvName converts a CLI long option name (without leading dashes) to an env var name. Hyphens become underscores; the result is uppercased.
"port" -> "PORT" "webserver-host" -> "WEBSERVER_HOST" "webserver-tls-cert_path" -> "WEBSERVER_TLS_CERT_PATH"
func ReadEnv ¶
ReadEnv maps present environment variables onto stable config keys using CLI long names. For each def, the first Longs entry determines the env var via EnvName; the value is stored under def.ConfigKey. Unset vars are absent from the result. environ is "KEY=value" lines as from os.Environ(); if nil, os.Environ() is used.
func Register ¶ added in v0.1.12
func Register[T any](definition Definition)
Register installs one generated definition.
func RegisterSubCommand ¶ added in v0.1.12
func RegisterSubCommand[T any](definition SubCommandDefinition)
RegisterSubCommand installs one generated subcommand definition.
func ResetDefinitions ¶ added in v0.1.12
func ResetDefinitions()
ResetDefinitions clears generated definitions. It is intended for tests.
func ScaffoldEnv ¶ added in v0.1.11
ScaffoldEnv renders all registered Bind fragments as one deterministic .env scaffold. Struct docs are omitted: env output is sorted globally by variable name, so a per-definition comment has no stable position.
func ScaffoldTOML ¶ added in v0.1.11
ScaffoldTOML renders all registered definitions as one deterministic TOML scaffold.
func SubCommand ¶ added in v0.1.12
SubCommand returns a generated *T only when name is the process-selected subcommand. Load fills the selected value from CLI flags and positionals.
Selection uses os.Args because the nil/non-nil result must be known when this function returns. LoadOptions.Args should therefore mirror os.Args[1:] when an application uses SubCommand.
func WriteScaffoldEnv ¶ added in v0.1.11
WriteScaffoldEnv writes the combined .env scaffold to w.
func WriteScaffoldTOML ¶ added in v0.1.11
WriteScaffoldTOML writes the combined TOML scaffold to w.
Types ¶
type Definition ¶ added in v0.1.12
type Definition struct {
// TypeName is the package-qualified Go type identity used for diagnostics.
TypeName string
// Prefix is the configuration key prefix passed to Bind.
Prefix string
// Doc is the config struct's godoc text, rendered above the scaffold table.
Doc string
// KnownKeys lists stable config keys for env and provenance.
KnownKeys []string
// FlagMetas builds cliparser defs for this type's fields.
FlagMetas []cliparser.FieldMeta
// Defaults maps stable keys to default raw strings applied when absent.
Defaults map[string]string
// DependsOn maps a stable key to every parent it answers to: its own
// dependon tag plus the tags of the structs it sits under. One empty parent
// is enough to hide the key from provenance output; nothing else.
DependsOn map[string][]string
// Falsy maps a stable key to the choice from its falsy tag. The key resolves
// to that value when nothing sets it and it has no default, and the value
// counts as empty when other keys depend on this one.
Falsy map[string]string
// Secrets maps a stable key to its secret tag: hide, mask, or show. A key
// with no entry follows the key-name policy in displayValue.
Secrets map[string]string
// Apply writes overlay values into *T (dst must be *T).
Apply ApplyFunc
// Scaffold contains the leaf fields used to render example configuration.
Scaffold []ScaffoldField
}
Definition describes one generated Bind target and its scaffold fields.
type Entry ¶
type Entry struct {
Raw string
Multi []string
IsMulti bool
// Tables holds one overlay per [[key]] element when IsTables is true. Their
// keys are relative to the table-array key. Only the TOML layer produces
// them: env and CLI have no repeated-table form.
Tables []*Overlay
IsTables bool
Place Place
}
Entry is one winning raw value in the overlay.
type LoadOptions ¶
type LoadOptions struct {
// Vendor is the configdir vendor name (required when resolving via configdir).
Vendor string
// Tool is the application/tool name (required when resolving via configdir).
Tool string
// FileName is the config basename (default "config.toml").
FileName string
// Args are CLI args without the program name (default os.Args[1:]).
Args []string
// Environ is KEY=value lines (default os.Environ()).
Environ []string
// ExplicitConfigPath forces a config file path (overrides --config-path when set).
// Prefer leaving empty and passing --config-path via Args in production.
ExplicitConfigPath string
// ExtraConfigReadPaths are optional config files searched in slice order
// after ExplicitConfigPath/--config-path and before user/system config dirs.
// Missing or unreadable entries are skipped; only the first found file is read.
ExtraConfigReadPaths []string
}
LoadOptions configures multi-source Bind load.
type LoadResult ¶
type LoadResult struct {
Overlay *Overlay
ConfigPath string
FoundFile bool
// contains filtered or unexported fields
}
LoadResult holds the overlay after load (for tests/provenance).
func Load ¶
func Load(opts LoadOptions) (*LoadResult, error)
Load merges default → TOML → env → CLI into Bind targets and applies without reflection.
func (*LoadResult) Provenance ¶ added in v0.2.0
func (r *LoadResult) Provenance() []ProvenanceEntry
Provenance returns the effective configuration as an ordered, redacted slice.
Entries follow Bind registration order, and within one binding the field declaration order of its struct; keys that belong to no registered binding sort lexicographically after all known keys. An array of tables expands in place into one entry per element field, keyed key[index].field and ordered by index then declaration. A secret tag decides whether a value is shown, masked, or dropped, and a key with no tag is masked when its name looks sensitive. Fields whose dependon parent is empty are omitted, while the parent itself is kept: an empty parent is the reason its dependents vanished.
type Overlay ¶
type Overlay struct {
// contains filtered or unexported fields
}
Overlay is a key-wise multi-source merge buffer (later Set wins).
func (*Overlay) All ¶ added in v0.2.0
All iterates entries in sorted key order. Callers get a stable sequence instead of the map iteration order behind the overlay.
func (*Overlay) GetMulti ¶
GetMulti returns multi values when present; otherwise splits Raw by comma if needed.
func (*Overlay) GetString ¶
GetString returns a scalar raw string for key. An array of tables has no scalar form, so it reads as absent.
func (*Overlay) GetTables ¶ added in v0.2.0
GetTables returns the per-element overlays of an array of tables.
func (*Overlay) MergeMultiMap ¶
MergeMultiMap merges multi-value maps with the given place.
type Positional ¶ added in v0.1.12
type Positional struct {
ConfigKey string
Name string
Help string
Role PositionalRole
}
Positional defines one generated positional argument.
type PositionalRole ¶ added in v0.1.12
type PositionalRole uint8
PositionalRole describes how a generated subcommand field consumes positional command-line arguments.
const ( PositionalRequired PositionalRole = iota + 1 PositionalOptional PositionalRest )
type ProvenanceEntry ¶ added in v0.2.0
type ProvenanceEntry struct {
// Key is the stable config key (e.g. "webserver.port"), or the indexed form
// for a field of an array-of-tables element (e.g. "rdb.connections[0].dsn").
Key string
// Value is the display form after redaction, never the raw secret.
Value string
// Place is the source layer that won for this key.
Place Place
// Masked reports that Value is the redaction placeholder rather than the
// configured value, so a caller re-rendering these entries can tell the two
// apart without comparing against the mask text.
Masked bool
// ArrayKey is the array of tables this entry is an element field of, with
// the indices of any enclosing arrays already in place. It is empty for an
// ordinary key, so a caller groups a tree by it and orders by Index without
// parsing Key apart at its brackets.
ArrayKey string
// Index is the element's position within ArrayKey, and 0 when ArrayKey is
// empty.
Index int
}
ProvenanceEntry is one effective config key prepared for logging.
type ScaffoldField ¶ added in v0.1.11
type ScaffoldField struct {
Key string
Kind ScaffoldKind
Default string
Opt string
Env string
Help string
// Nested holds the element fields when Kind is ScaffoldTableArray. Their
// keys are relative to Key.
Nested []ScaffoldField
}
ScaffoldField is generated metadata for one leaf configuration field, or for one array of tables and its element fields.
type ScaffoldKind ¶ added in v0.1.11
type ScaffoldKind uint8
ScaffoldKind is the value kind needed to render a configuration example.
const ( ScaffoldString ScaffoldKind = iota ScaffoldBool ScaffoldInt ScaffoldDuration ScaffoldStringSlice // ScaffoldTableArray is an array of tables rendered as a [[key]] block. ScaffoldTableArray )
type SubCommandDefinition ¶ added in v0.1.12
type SubCommandDefinition struct {
TypeName string
Name string
Help string
FlagMetas []cliparser.FieldMeta
Defaults map[string]string
Positionals []Positional
Apply ApplyFunc
}
SubCommandDefinition describes one generated CLI-only subcommand.
type UsageError ¶ added in v0.1.12
UsageError reports a CLI parse failure together with generated usage text.
func (*UsageError) Error ¶ added in v0.1.12
func (e *UsageError) Error() string