configbind

package
v0.1.13 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 25, 2026 License: Apache-2.0 Imports: 11 Imported by: 9

Documentation

Overview

Package configbind loads Bind-style config from defaults, TOML, env, and CLI into structs.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bind

func Bind[T any](prefix string) *T

Bind allocates *T, registers it for the next Load, and returns the pointer. Code generation must Register[T] before Bind is used.

func EnvName

func EnvName(longOpt string) string

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

func ReadEnv(defs []cliparser.Def, environ []string) map[string]string

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 ResetTargets

func ResetTargets()

ResetTargets clears Bind registrations (tests only).

func ScaffoldEnv added in v0.1.11

func ScaffoldEnv() (string, error)

ScaffoldEnv renders all registered Bind fragments as one deterministic .env scaffold.

func ScaffoldTOML added in v0.1.11

func ScaffoldTOML() (string, error)

ScaffoldTOML renders all registered definitions as one deterministic TOML scaffold.

func SubCommand added in v0.1.12

func SubCommand[T any](name, help string) *T

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

func WriteScaffoldEnv(w io.Writer) error

WriteScaffoldEnv writes the combined .env scaffold to w.

func WriteScaffoldTOML added in v0.1.11

func WriteScaffoldTOML(w io.Writer) error

WriteScaffoldTOML writes the combined TOML scaffold to w.

Types

type ApplyFunc

type ApplyFunc func(dst any, o *Overlay) error

ApplyFunc applies an overlay onto a destination pointer without reflection.

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
	// 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
	// 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
	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
}

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.

type Overlay

type Overlay struct {
	// contains filtered or unexported fields
}

Overlay is a key-wise multi-source merge buffer (later Set wins).

func NewOverlay

func NewOverlay() *Overlay

NewOverlay returns an empty overlay.

func (*Overlay) Delete

func (o *Overlay) Delete(key string)

Delete removes a key from the overlay if present.

func (*Overlay) Get

func (o *Overlay) Get(key string) (Entry, bool)

Get returns the entry for key.

func (*Overlay) GetMulti

func (o *Overlay) GetMulti(key string) ([]string, bool)

GetMulti returns multi values when present; otherwise splits Raw by comma if needed.

func (*Overlay) GetString

func (o *Overlay) GetString(key string) (string, bool)

GetString returns a scalar raw string for key.

func (*Overlay) Keys

func (o *Overlay) Keys() []string

Keys returns sorted config keys.

func (*Overlay) MergeMap

func (o *Overlay) MergeMap(m map[string]string, place Place)

MergeMap merges scalar string values from m with the given place.

func (*Overlay) MergeMultiMap

func (o *Overlay) MergeMultiMap(m map[string][]string, place Place)

MergeMultiMap merges multi-value maps with the given place.

func (*Overlay) Set

func (o *Overlay) Set(key, raw string, place Place)

Set stores a scalar raw value for key from place (overwrites prior).

func (*Overlay) SetMulti

func (o *Overlay) SetMulti(key string, values []string, place Place)

SetMulti stores a multi-value for key from place.

type Place

type Place string

Place is the winning source layer for an overlay entry.

const (
	PlaceDefault Place = "default"
	PlaceFile    Place = "file_toml"
	PlaceEnv     Place = "env"
	PlaceCLI     Place = "cli"
)

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 ScaffoldField added in v0.1.11

type ScaffoldField struct {
	Key     string
	Kind    ScaffoldKind
	Default string
	Opt     string
	Env     string
	Help    string
}

ScaffoldField is generated metadata for one leaf configuration field.

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
	ScaffoldStringSlice
)

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

type UsageError struct {
	Message string
	Usage   string
}

UsageError reports a CLI parse failure together with generated usage text.

func (*UsageError) Error added in v0.1.12

func (e *UsageError) Error() string

Directories

Path Synopsis
Package codegen emits reflection-free configbind apply, flag, and env key tables.
Package codegen emits reflection-free configbind apply, flag, and env key tables.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL