dsco

package module
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Jul 1, 2026 License: GPL-3.0 Imports: 18 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

dsco

dsco is a Go configuration library. Config fields are pointers, so a nil field means "not set" and stays distinct from a zero value. Fill reads layers in priority order and returns an error when a required field is left unset, so the app stops at startup instead of running with missing config.

var config *Config
dsco.Fill(&config,
    dsco.WithCmdlineLayer(),                     // Local overrides
    dsco.WithEnvLayer("MYAPP"),                  // Container/K8s config
    dsco.WithStructLayer(defaults, "defaults"),  // Defaults baked in
)
// A required field left unset fails Fill(), so the app does not start.

Go Go Reference Go Version Go Report Card

Français | English


Why dsco?

Plain Go configuration can't distinguish a missing value from a zero value:

type Config struct {
    Host string  // Is "" intentional or did someone forget to set it?
    Port int     // Is 0 a valid port or a missing value?
}

dsco makes intent explicit:

type Config struct {
    Host *string `yaml:"host"`  // nil = not configured (fail fast)
    Port *int    `yaml:"port"`  // nil = not configured (fail fast)
}
Problem dsco Solution
Service starts with missing DB password Fails immediately with clear error
Zero value 0 masks missing port config nil explicitly means "not set"
Config works locally, breaks in prod Same validation everywhere
"Which env var overrode what?" Full audit trail with source tracking

Quick Start

go get github.com/byte4ever/dsco
package main

import (
    "fmt"
    "log"

    "github.com/byte4ever/dsco"
)

type Config struct {
    Host *string `yaml:"host"`
    Port *int    `yaml:"port"`
}

func main() {
    var config *Config

    _, err := dsco.Fill(&config,
        // Layer 1: command line (highest priority)
        dsco.WithCmdlineLayer(),
        // Layer 2: environment variables
        dsco.WithEnvLayer("MYAPP"),
        // Layer 3: defaults (lowest priority)
        dsco.WithStructLayer(&Config{
            Host: dsco.R("localhost"),
            Port: dsco.R(8080),
        }, "defaults"),
    )
    if err != nil {
        log.Fatal(err)  // Missing config? Crash here, not in production.
    }

    fmt.Printf("Server: %s:%d\n", *config.Host, *config.Port)
}
# Just works with defaults
./myapp

# Override via environment (Kubernetes/Docker)
MYAPP-HOST=api.prod.internal MYAPP-PORT=9000 ./myapp

# Override via command line (local dev)
./myapp --host=staging.example.com --port=9000

New to dsco? The Quick Start Guide covers all concepts step-by-step.


Table of Contents


Key Features

Feature Benefit
Layered Priority Cmdline → env vars → struct defaults. First wins.
Pointer-Based Safety nil = not configured. No silent zero values.
Strict Mode Catch typos and unwanted overrides immediately.
Source Tracking Know exactly where every value came from.
Multi-Source Cmdline, env vars, files, structs, custom providers.
Type Safety Automatic conversion with clear parse errors.
Alias Support --db-host instead of --database-host.
Minimal Deps Only yaml.v3 and afero.

The Safety Design

Why Pointers?
// Ambiguous: is Port 0 intentional or unset?
type Config struct {
    Port int
}

// Explicit: nil means "not configured"
type Config struct {
    Port *int `yaml:"port"`
}

The dsco.R() helper builds the pointers:

config := &Config{
    Host:    dsco.R("localhost"),   // dsco.R[T](v T) *T
    Port:    dsco.R(8080),
    Timeout: dsco.R(30 * time.Second),
}
Fail-Fast Guarantee

Fill returns an error if a required field is still nil, so the app stops before running with incomplete config:

// This FAILS - Password is nil
dsco.Fill(&config,
    dsco.WithStructLayer(&DatabaseConfig{
        Host: dsco.R("localhost"),
        Port: dsco.R(5432),
        // Password not set - nil
    }, "defaults"),
)
// Error: "password" is not configured

// This SUCCEEDS - all fields explicitly set
dsco.Fill(&config,
    dsco.WithEnvLayer("DB"),  // DB-PASSWORD must be set
    dsco.WithStructLayer(&DatabaseConfig{
        Host: dsco.R("localhost"),
        Port: dsco.R(5432),
    }, "defaults"),
)
Production Example
type DatabaseConfig struct {
    Host     *string `yaml:"host"`
    Port     *int    `yaml:"port"`
    Username *string `yaml:"username"`
    Password *string `yaml:"password"`
    SSLMode  *string `yaml:"ssl_mode"`
}

_, err := dsco.Fill(&dbConfig,
    // Secrets from Vault/external system
    dsco.WithStringValueProvider(secretProvider),
    // Environment overrides
    dsco.WithStrictEnvLayer("DB"),
    // Base configuration
    dsco.WithStructLayer(&DatabaseConfig{
        Host:    dsco.R("postgres.prod.internal"),
        Port:    dsco.R(5432),
        SSLMode: dsco.R("require"),
        // Username/Password MUST come from higher layers
    }, "base"),
)

if err != nil {
    // Clear error: "username is not configured"
    log.Fatal("Configuration incomplete:", err)
}

You're In Control

You choose which fields are configurable, from which layers, and which are locked.

The Progressive Exposure Pattern

Start with everything hardcoded, then progressively expose parameters as needed:

Phase 1: All defaults in code

// Initial deployment - everything hardcoded, nothing external
dsco.Fill(&config,
    dsco.WithStructLayer(&Config{
        Host:       dsco.R("api.internal"),
        Port:       dsco.R(8080),
        MaxRetries: dsco.R(3),
        Timeout:    dsco.R(30 * time.Second),
        BatchSize:  dsco.R(100),
    }, "defaults"),
)

The service runs with no external configuration: no environment variables or config files to deploy.

Phase 2: Expose what matters

Later, you realize Timeout needs adjustment per environment:

// Now Timeout can be overridden via environment, everything else stays fixed
dsco.Fill(&config,
    dsco.WithEnvLayer("MYSERVICE"),  // Only MYSERVICE-TIMEOUT needs to exist
    dsco.WithStructLayer(&Config{
        Host:       dsco.R("api.internal"),
        Port:       dsco.R(8080),
        MaxRetries: dsco.R(3),
        Timeout:    dsco.R(30 * time.Second),  // Default, but overridable
        BatchSize:  dsco.R(100),
    }, "defaults"),
)

Adding the env layer needs no recompilation. Operations can set MYSERVICE-TIMEOUT=60s without touching the binary.

Phase 3: Protect critical values

Some defaults should never be overridden in production:

dsco.Fill(&config,
    // These values are LOCKED - highest priority, strict enforcement
    dsco.WithStrictStructLayer(&Config{
        APIEndpoint: dsco.R("https://api.production.com"),
        AuditMode:   dsco.R(true),
    }, "immutable"),

    // Operational overrides allowed
    dsco.WithEnvLayer("MYSERVICE"),
    dsco.WithCmdlineLayer(),
)

If someone sets MYSERVICE-API-ENDPOINT, the strict struct layer wins and raises an error about the attempted override.

Why This Matters
Traditional Approach dsco Approach
Expose everything upfront "just in case" Start minimal, expose on demand
Config sprawl - hundreds of env vars Only what's actually needed
No protection - any value can be overridden Lock critical values with strict layers
Must redeploy to change exposure Add layers without code changes
"What's the default?" - check docs/code Defaults visible in layer definition
Real-World Scenarios

Scenario 1: New service deployment

// Week 1: Ship with safe defaults, zero external config
dsco.Fill(&config, dsco.WithStructLayer(productionDefaults, "defaults"))

Scenario 2: Ops needs to tune performance

// Week 3: Add env layer - ops can now adjust without new release
dsco.Fill(&config,
    dsco.WithEnvLayer("SVC"),
    dsco.WithStructLayer(productionDefaults, "defaults"),
)
// Ops sets SVC-CONNECTION-POOL-SIZE=50

Scenario 3: Prevent accidental security misconfiguration

// Security audit: ensure TLS and audit logging can't be disabled
dsco.Fill(&config,
    dsco.WithStrictStructLayer(&Config{
        TLSEnabled:    dsco.R(true),
        AuditLogging:  dsco.R(true),
        MinTLSVersion: dsco.R("1.3"),
    }, "security"),
    dsco.WithEnvLayer("SVC"),
)

You decide what's flexible and what's fixed; dsco enforces it.


Layer Types

Struct Layers (Defaults)
dsco.WithStructLayer(&Config{
    Host: dsco.R("localhost"),
    Port: dsco.R(8080),
}, "defaults")

// Strict: errors if values are overridden
dsco.WithStrictStructLayer(&Config{
    APIEndpoint: dsco.R("https://api.prod.com"),
}, "immutable")

Local development pattern - zero config to start:

dsco.Fill(&config,
    dsco.WithCmdlineLayer(),
    dsco.WithStructLayer(devDefaults, "dev"),
)
./myapp                    # Just works
./myapp --port=9000        # Quick override
./myapp --database-host=staging-db
Command Line Layers
dsco.WithCmdlineLayer()
dsco.WithStrictCmdlineLayer()  // Error on unknown flags

// With aliases
dsco.WithCmdlineLayer(
    dsco.WithAliases(map[string]string{
        "v": "verbose",
        "p": "port",
    }),
)

Format: --key=value (lowercase, hyphens for nested fields)

./myapp --host=localhost --database-port=5432
Environment Variable Layers
dsco.WithEnvLayer("MYAPP")
dsco.WithStrictEnvLayer("MYAPP")  // Error on unmatched vars
Custom Providers
type SecretProvider struct{}

func (s SecretProvider) GetName() string { return "vault" }
func (s SecretProvider) GetStringValues() svalue.Values {
    return svalue.Values{
        "database-password": &svalue.Value{
            Value:    fetchFromVault("db-password"),
            Location: "vault:db-password",
        },
    }
}

dsco.WithStringValueProvider(&SecretProvider{})

Environment Variables

Why Prefixes Matter

Multi-container pods (Kubernetes):

All containers in a pod share environment variables. Prefixes target specific containers:

env:
  - name: FRONTEND-PORT
    value: "8080"
  - name: BACKEND-PORT
    value: "3000"

Avoid conflicts:

Prevents collision with PATH, HOME, HTTP_PROXY, DATABASE_URL, etc.

Multiple instances:

WORKER1-QUEUE=high-priority ./worker &
WORKER2-QUEUE=low-priority ./worker &
Choosing Good Prefixes

Avoid generic prefixes that cause confusion:

# BAD: Too generic
APP-HOST=...       # Which app?
SERVER-PORT=...    # Which server?
SERVICE-URL=...    # Meaningless

Use specific, role-based prefixes:

# GOOD: Clear and distinguishable
ORDERAPI-HOST=...           # Order API service
PAYMENTWORKER-TIMEOUT=...   # Payment background worker
EVENTCONSUMER-BATCH=...     # Event queue consumer

This makes debugging easier ("check INDEXER config"), Kubernetes manifests self-documenting, and prevents cross-contamination in shared environments.

Format
PREFIX-KEY=value
│      │
│      └─ UPPERCASE key (hyphens/underscores allowed)
└─ UPPERCASE prefix
Mapping Examples
Struct Field YAML Tag Environment Variable
Host host MYAPP-HOST
MaxRetry max_retry MYAPP-MAX_RETRY
Database.Host database.host MYAPP-DATABASE-HOST
Database.PoolSize database.pool_size MYAPP-DATABASE-POOL_SIZE

Rules:

  • Prefix and keys: UPPERCASE
  • Prefix-to-key separator: hyphen (-)
  • Nested struct separator: hyphen (-)
  • Underscores in yaml tags: preserved

Architecture

graph TB
    A[Configuration Sources] --> B[Layer Registration]
    B --> C[Model Generation]
    C --> D[Value Collection]
    D --> E[Precedence Resolution]
    E --> F[Type Conversion]
    F --> G[Validation]
    G --> H[Struct Filling]

    A1[Command Line] --> B1[CmdlineLayer]
    A2[Environment] --> B2[EnvLayer]
    A3[Files] --> B3[FileLayer]
    A4[Structs] --> B4[StructLayer]
    A5[Custom] --> B5[StringProviderLayer]

    B1 --> B
    B2 --> B
    B3 --> B
    B4 --> B
    B5 --> B

Flow:

  1. Layer Registration - Sources register as layers
  2. Model Generation - Struct analyzed via reflection
  3. Value Collection - Each layer provides values
  4. Precedence Resolution - Earlier layers override later (first-layer wins)
  5. Type Conversion - Strings → target types via YAML
  6. Validation - Required fields checked
  7. Struct Filling - Target populated with resolved values

Configuration Patterns

Field Rules
type DatabaseConfig struct {
    // Pointers for scalar types
    Host    *string `yaml:"host"`
    Port    *int    `yaml:"port"`
    Timeout *int    `yaml:"timeout"`

    // Slices and maps: non-pointer OK
    Tables  []string          `yaml:"tables"`
    Options map[string]string `yaml:"options"`
}
Validation Pattern

dsco fills structs; you validate:

func (c *Config) Validate() error {
    if c.Port == nil {
        return errors.New("port is required")
    }
    if *c.Port < 1 || *c.Port > 65535 {
        return errors.New("port must be 1-65535")
    }
    return nil
}

// Usage
_, err := dsco.Fill(&config, layers...)
if err != nil {
    log.Fatal(err)
}
if err := config.Validate(); err != nil {
    log.Fatal("validation:", err)
}

Error Handling

Error Types
Error Cause
LayerErrors Layer registration issues
FillerErrors Struct filling issues
InvalidInputError Target not *Config pointer
CmdlineAlreadyUsedError Multiple cmdline layers
OverriddenKeyError Strict layer value overridden
Checking Errors
_, err := dsco.Fill(&config, layers...)
if err != nil {
    var layerErr LayerErrors
    if errors.As(err, &layerErr) {
        for _, e := range layerErr.Errors() {
            log.Printf("Layer: %v", e)
        }
    }
}

Advanced Usage

Strict Mode

Strict layers error when values are not consumed:

  1. Value doesn't match any field (typo detection)
  2. Value overridden by an earlier layer (override detection)
_, err := dsco.Fill(&config,
    dsco.WithCmdlineLayer(),            // Earlier layer: its values win
    dsco.WithStrictEnvLayer("MYAPP"),  // Strict: errors if cmdline already supplied the field
)
// --port=9000 + MYAPP-PORT=8080 → Error!
// Env value was overridden by cmdline.
Aliases
dsco.WithCmdlineLayer(
    dsco.WithAliases(map[string]string{
        "db-host": "database.host",
        "db-port": "database.port",
        "v":       "verbose",
    }),
)
./myapp --db-host=localhost --v=true
# Instead of: --database-host=localhost --verbose=true
File-Based Configuration
type FileProvider struct {
    name   string
    values svalue.Values
}

func NewFileProvider(path string) (*FileProvider, error) {
    data, _ := os.ReadFile(path)
    var raw map[string]string
    yaml.Unmarshal(data, &raw)

    values := make(svalue.Values)
    for k, v := range raw {
        values[k] = &svalue.Value{Value: v, Location: "file:" + path}
    }
    return &FileProvider{name: path, values: values}, nil
}

func (f *FileProvider) GetName() string              { return f.name }
func (f *FileProvider) GetStringValues() svalue.Values { return f.values }

API Reference

Core
Fill(target any, layers ...Layer) (plocation.Locations, error)
Layer Builders
Function Description
WithCmdlineLayer(opts...) Command line arguments
WithStrictCmdlineLayer(opts...) Strict command line
WithEnvLayer(prefix, opts...) Environment variables
WithStrictEnvLayer(prefix, opts...) Strict environment
WithStructLayer(input, id) Struct defaults
WithStrictStructLayer(input, id) Immutable struct values
WithStringValueProvider(provider, opts...) Custom provider
WithStrictStringValueProvider(provider, opts...) Strict custom provider
Helpers
R[T any](value T) *T              // Create pointer
WithAliases(map[string]string)    // Define aliases
Interfaces
type StringValuesProvider interface {
    GetStringValues() svalue.Values
}

type NamedStringValuesProvider interface {
    StringValuesProvider
    GetName() string
}

Full API docs: pkg.go.dev/github.com/byte4ever/dsco


Inventory

Want to know which keys an operator must set before the service will start? inventory.Compute walks your config struct and the layers you plan to register, then reports the canonical key each layer would accept for every leaf field. It reads nothing: no env vars, no flags, no files.

import (
    "os"

    "github.com/byte4ever/dsco"
    "github.com/byte4ever/dsco/inventory"
)

var config *Config
report, err := inventory.Compute(&config,
    dsco.WithCmdlineLayer(),
    dsco.WithEnvLayer("MYAPP"),
    dsco.WithStructLayer(defaults, "defaults"),
)
if err != nil {
    log.Fatal(err)
}
report.WriteText(os.Stdout) // or WriteJSON / WriteYAML

Sample text output:

TYPE: github.com/example/myapp.Config

PATH                  TYPE             KEY                              DEFAULT
Database.Host         *string          cmdline: --database-host=        —
Database.Port         *int             cmdline: --database-port=        defaults=5432
Server.Timeout        *time.Duration   —                                defaults=30s

A — in the DEFAULT column means no layer bakes in a value, so the operator must supply that key. Anything with defaults=... is already covered. The KEY column shows the canonical key from the first layer that can supply the field: here cmdline, since it is listed first (highest priority).

Three runnable examples ship in the repo:


Use Claude Code with dsco

The dsco-claude/ directory of this repository ships two Claude Code skills, kept separate from the library code and installed on their own. They ship with the repo, so their version always matches the dsco tag they were released with.

  • dsco writes and designs idiomatic dsco config: pointer fields, layered Fill, env prefixes, Validate(), and inventory-based deployment discovery.
  • review-dsco reviews that output adversarially (pointer discipline, layer order, strict placement, secret routing, and more), returning a REJECT / CONDITIONAL / APPROVE verdict.

Both read the dsco version in your go.mod before giving version-gated advice and offer an upgrade when a feature (e.g. inventory) needs a newer release than you have pinned.

Install in one line, no checkout needed (it downloads the bundle and symlinks the skills into Claude Code):

curl -fsSL https://raw.githubusercontent.com/byte4ever/dsco/master/dsco-claude/bootstrap.sh | sh

On Windows PowerShell: irm https://raw.githubusercontent.com/byte4ever/dsco/master/dsco-claude/bootstrap.ps1 | iex.

From a dsco checkout instead, run dsco-claude/install.sh (or install.ps1 on Windows), and dsco-claude/install.sh update after pulling a new version.

Then ask Claude things like:

  • "Set up dsco for a service that needs Postgres and Redis."
  • "Review the config in internal/config/config.go for dsco anti-patterns."
  • "Migrate this viper setup to dsco."
  • "I'm getting OverriddenKeyError on MYAPP-PORT. What's wrong?"
  • "Generate an inventory driver so I can produce the k8s env list from CI."

For a hands-on tour of dsco itself, see QUICKSTART.md.


Examples


Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Follow project coding standards
  4. Add tests
  5. Run go test -race -cover ./...
  6. Run golangci-lint run
  7. Submit PR
go build ./...
go test -race -cover ./...
golangci-lint run
gofumpt -w .
golines --max-len=80 --base-formatter=gofumpt -w .

License

MIT License - see LICENSE

Documentation

Overview

Package dsco (pronounce /ˈdɪskoʊ/) provides a layered configuration system supporting command line arguments, environment variables, YAML files, and struct-based configurations with strict validation.

Overview

dsco implements a layered configuration system where different configuration sources are organized into layers with configurable precedence. Earlier layers override later ones (first-layer wins); a layer that leaves a field nil falls through to the next layer. Strict mode detects conflicts and unused values.

The library is designed for microservices environments where configuration safety is critical. It enforces explicit configuration through pointer-based fields, ensuring no silent defaults or ambiguous states.

Quick Start

type Config struct {
	Host     *string        `yaml:"host"`
	Port     *int           `yaml:"port"`
	Timeout  *time.Duration `yaml:"timeout"`
	Verbose  *bool          `yaml:"verbose"`
}

var config *Config
_, err := dsco.Fill(
	&config,
	dsco.WithCmdlineLayer(),
	dsco.WithEnvLayer("MYAPP"),
	dsco.WithStructLayer(&Config{
		Host:    dsco.R("localhost"),
		Port:    dsco.R(8080),
		Timeout: dsco.R(30 * time.Second),
		Verbose: dsco.R(false),
	}, "defaults"),
)

Layer Types

The library supports multiple configuration sources:

- Command line arguments (WithCmdlineLayer, WithStrictCmdlineLayer) - Environment variables (WithEnvLayer, WithStrictEnvLayer) - Go structs (WithStructLayer, WithStrictStructLayer) - Custom string providers (WithStringValueProvider, WithStrictStringValueProvider) - File-based providers (via external packages like kfile)

Safety Design

dsco enforces explicit configuration through pointer-based fields:

- nil clearly means "not configured" - Non-nil values mean "explicitly configured" - Zero values (0, "", false) don't mask missing configuration - Services fail fast with clear error messages - No hidden defaults or silent failures

Strict Mode

Strict mode layers detect unused configuration values and conflicts:

_, err := dsco.Fill(
	&config,
	dsco.WithStrictCmdlineLayer(),
	dsco.WithStrictEnvLayer("MYAPP"),
)

This ensures all provided configuration values are actually used, preventing configuration drift and accidental misconfigurations.

Error Handling

The library provides comprehensive error types with location tracking:

if err != nil {
	var layerErr LayerErrors
	if errors.As(err, &layerErr) {
		// Handle layer registration errors
	}

	var fillerErr FillerErrors
	if errors.As(err, &fillerErr) {
		// Handle field filling errors
	}
}

Testing

The dsco library maintains 100% test coverage across all core packages, ensuring reliability and stability for production use. The test suite includes:

- Unit tests for all public APIs - Integration tests for multi-layer scenarios - Error path testing with comprehensive validation - Concurrent access testing for thread safety - Edge case handling with boundary conditions

The testing infrastructure follows project standards: - Parallel test execution with t.Parallel() - Mock-based testing using testify framework - Table-driven test patterns for comprehensive coverage - Error assertion using testify.ErrorIs, ErrorAs, and Contains

Architecture

The library implements a sophisticated processing pipeline:

1. Layer Registration: Different configuration sources register as layers 2. Model Generation: Target struct is analyzed via reflection 3. Value Collection: Each layer provides field values from its source 4. Precedence Resolution: Earlier layers override later ones (first-layer wins) 5. Type Conversion: String values converted to target types via YAML 6. Validation: Required fields and custom validation applied 7. Struct Filling: Target struct populated with resolved values

For complete documentation and examples, see: https://pkg.go.dev/github.com/byte4ever/dsco

Inventory

The inventory sub-package (github.com/byte4ever/dsco/inventory) computes a static list of configuration keys a Fill call would expect, with no I/O, suitable for "what do I need to set" diagnostics in operator tooling. See the Inventory section in README.md for examples.

Package dsco provides configuration processing using layered sources. This file contains the core filling logic that orchestrates the configuration process from source layers to final struct population.

Package dsco layer policy definitions. This file defines constraint policies for configuration layers, distinguishing between strict and normal processing modes.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrFiller is the sentinel error for configuration filling failures.
	ErrFiller = errors.New("")

	// ErrCfgMustBePointer indicates that the value passed to Fill or
	// BuildModel is not a pointer to a struct.
	ErrCfgMustBePointer = errors.New("cfg must be a pointer to a struct")
)
View Source
var ErrAliasCollision = errors.New("alias collision")

ErrAliasCollision represents an error indicating that an alias is colliding with an actual key in the structure.

View Source
var ErrCmdlineAlreadyUsed = errors.New("")

ErrCmdlineAlreadyUsed is the sentinel error for cmdline already used.

View Source
var ErrDuplicateEnvPrefix = errors.New("")

ErrDuplicateEnvPrefix is the sentinel error for duplicate env prefix.

View Source
var ErrDuplicateInputStruct = errors.New("")

ErrDuplicateInputStruct is the sentinel error for duplicate input struct.

View Source
var ErrDuplicateStringProvider = errors.New("duplicate string provider")

ErrDuplicateStringProvider is the sentinel error for duplicate string provider.

View Source
var ErrDuplicateStructID = errors.New("")

ErrDuplicateStructID is the sentinel error for duplicate struct ID.

View Source
var ErrGet = errors.New("")
View Source
var ErrInvalidInput = errors.New("")

ErrInvalidInput is the sentinel error for invalid input types.

View Source
var ErrInvalidType = errors.New("invalid type")

ErrInvalidType represent an error where ....

View Source
var ErrLayer = errors.New("")

ErrLayer is the sentinel error for layer errors.

View Source
var ErrLayerNotInventoryReporter = errors.New(
	"layer does not implement InventoryReporter",
)

ErrLayerNotInventoryReporter indicates that a layer's underlying FieldValuesGetter does not implement InventoryReporter, which is required for PrepareInventoryWalk.

View Source
var ErrNilInput = errors.New("nil input")

ErrNilInput is dummy...

View Source
var ErrNilKeyFormatter = errors.New("nil key formatter")

ErrNilKeyFormatter indicates that ReportInventory was called on a StringBasedBuilder with no KeyFormatter set.

View Source
var ErrNilProvider = errors.New("nil provider")

ErrNilProvider is shitty...

View Source
var ErrNoAliasesProvided = errors.New("no aliases provided")

ErrNoAliasesProvided represent an error where no aliases map was provided with option.

View Source
var ErrOverriddenKey = errors.New("overridden key")

ErrOverriddenKey represents an error indicating that a potential key binding wha overridden in another layer.

View Source
var ErrParse = errors.New("parse error")

ErrParse represents an error indicating that a value cannot be parsed.

View Source
var ErrStructTypeDiffer = errors.New("struct type differ")

ErrStructTypeDiffer represent an error where cannot produce a valid value bases because struct source type and struct type to fillHelper differs.

View Source
var ErrUnboundedLocation = errors.New("unbound key")

ErrUnboundedLocation represents an error indicating that a key is never bound to the structure.

View Source
var ErrUnknownKeyFormatterKind = errors.New("unknown key-formatter kind")

ErrUnknownKeyFormatterKind is returned by NewStringBasedBuilderForTest when the kind argument is not a recognised formatter kind.

Functions

func CollectAliasesForTest added in v1.4.0

func CollectAliasesForTest(mdl ModelInterface) (map[string]string, error)

CollectAliasesForTest exposes collectAliases for testing only. It is intentionally not part of the public API.

func Fill

func Fill(
	inputModelRef any,
	layers ...Layer,
) (
	plocation.Locations,
	error,
)

Fill fills the structure using the layers.

func R

func R[T any](v T) *T

R returns a reference to any value thanks to generics in go1.18.

Types

type AliasCollisionError

type AliasCollisionError struct {
	Path string
}

func (AliasCollisionError) Error

func (a AliasCollisionError) Error() string

func (AliasCollisionError) Is

func (AliasCollisionError) Is(err error) bool

type AliasesOption

type AliasesOption map[string]string

AliasesOption defines keys aliasing.

func WithAliases

func WithAliases(mapping map[string]string) AliasesOption

WithAliases returns a keys aliasing option.

type CmdlineAlreadyUsedError

type CmdlineAlreadyUsedError struct {
	Index int
}

CmdlineAlreadyUsedError represents an error where cmdline is already used.

func (CmdlineAlreadyUsedError) Error

func (c CmdlineAlreadyUsedError) Error() string

CmdlineAlreadyUsedError methods.

func (CmdlineAlreadyUsedError) Is

type CmdlineLayer

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

CmdlineLayer is a command line layer.

func WithCmdlineLayer

func WithCmdlineLayer(options ...Option) *CmdlineLayer

WithCmdlineLayer creates a command line layer.

type DuplicateEnvPrefixError

type DuplicateEnvPrefixError struct {
	Prefix string
	Index  int
}

DuplicateEnvPrefixError represents an error where env prefix is duplicated.

func (DuplicateEnvPrefixError) Error

func (c DuplicateEnvPrefixError) Error() string

DuplicateEnvPrefixError methods.

func (DuplicateEnvPrefixError) Is

type DuplicateInputStructError

type DuplicateInputStructError struct {
	Index int
}

DuplicateInputStructError represents an error where input struct is duplicated.

func (DuplicateInputStructError) Error

DuplicateInputStructError methods.

func (DuplicateInputStructError) Is

type DuplicateStringProviderError

type DuplicateStringProviderError struct {
	ID    string
	Index int
}

func (DuplicateStringProviderError) Error

func (DuplicateStringProviderError) Is added in v1.4.0

type DuplicateStructIDError

type DuplicateStructIDError struct {
	ID    string
	Index int
}

DuplicateStructIDError represents an error where struct ID is duplicated.

func (DuplicateStructIDError) Error

func (c DuplicateStructIDError) Error() string

DuplicateStructIDError methods.

func (DuplicateStructIDError) Is

type EnvLayer

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

EnvLayer is an environnement variable layer.

func WithEnvLayer

func WithEnvLayer(prefix string, options ...Option) *EnvLayer

WithEnvLayer creates an environment variable layer.

type FieldProvision added in v1.4.0

type FieldProvision struct {
	// Value is the baked-in value for struct layers; nil for
	// string-based layers.
	Value any

	// FieldUID matches the model's field UID.
	FieldUID string

	// Key is the canonical key for string-based layers; empty for
	// struct layers.
	Key string
}

FieldProvision is one (field, layer) pair from a layer's perspective.

type FieldValuesGetter

type FieldValuesGetter interface {
	// GetFieldValuesFrom extracts configuration values from the given model.
	// Returns a map of field UIDs to their values, or an error if extraction
	// fails.
	GetFieldValuesFrom(model ModelInterface) (fvalue.Values, error)
}

FieldValuesGetter defines the ability to get field values from a configuration model. This interface is implemented by configuration sources (layers) to provide their configuration values in a standard format that can be merged and processed.

type FillerErrors

type FillerErrors struct {
	merror.MError
}

FillerErrors aggregates multiple errors that can occur during the configuration filling process across different layers and validation steps.

func (FillerErrors) Is

func (FillerErrors) Is(err error) bool

Is implements error matching for FillerErrors, allowing error.Is checks against ErrFiller to detect filling-related errors.

type GetError

type GetError struct {
	merror.MError
}

func (GetError) Is

func (GetError) Is(err error) bool

type InvalidInputError

type InvalidInputError struct {
	Type reflect.Type
}

InvalidInputError represents an error where the input type is invalid.

func (InvalidInputError) Error

func (c InvalidInputError) Error() string

InvalidInputError methods.

func (InvalidInputError) Is

func (InvalidInputError) Is(err error) bool

type InventoryReporter added in v1.4.0

type InventoryReporter interface {
	// ReportInventory returns the layer's contribution to an inventory
	// walk for the given model. Implementations must not perform any I/O.
	ReportInventory(model ModelInterface) (LayerInventory, error)
}

InventoryReporter is implemented by layer builders that can describe what they would contribute to an inventory without performing I/O.

Pattern: Strategy — each layer reports its own contribution shape (key form for string-based layers, baked-in values for struct layers).

type InventoryWalk added in v1.4.0

type InventoryWalk struct {
	Model     ModelInterface
	Reporters []InventoryReporter
}

InventoryWalk holds the prepared model and per-layer reporters used by the inventory sub-package to compute a Report. It contains no live configuration values — only structural metadata.

func PrepareInventoryWalk added in v1.4.0

func PrepareInventoryWalk(
	cfg any,
	layers ...Layer,
) (*InventoryWalk, error)

PrepareInventoryWalk constructs the model and the per-layer InventoryReporter list without performing any I/O. Used by the inventory sub-package to compute a Report.

Pattern: Factory — assembles the structural inputs needed for an inventory walk.

type KeyFormatter added in v1.4.0

type KeyFormatter interface {
	// LayerKind returns the layer category (e.g. "env", "cmdline", "file").
	// Empty for layers that cannot enumerate keys.
	LayerKind() string

	// LayerName returns the layer instance identifier
	// (e.g. "env:MYAPP", "cmdline", "file:config.yaml").
	LayerName() string

	// FormatKey converts an internal alias path (dash-separated, lowercase)
	// to the canonical user-facing key for this layer kind. Returns the
	// empty string when the layer cannot enumerate keys.
	FormatKey(aliasPath string) string
}

KeyFormatter renders a layer-internal alias path into the canonical user-facing key form for a specific layer kind (env, cmdline, file).

Pattern: Strategy — each layer kind formats keys differently; the formatter is injected into StringBasedBuilder at construction time.

type Layer

type Layer interface {
	// contains filtered or unexported methods
}

Layer defines a configuration layer.

type LayerErrors

type LayerErrors struct {
	merror.MError
}

LayerErrors represents multiple layer errors.

func (LayerErrors) Is

func (LayerErrors) Is(err error) bool

type LayerInventory added in v1.4.0

type LayerInventory struct {
	// Name uniquely identifies the layer instance, e.g. "env:MYAPP",
	// "cmdline", "file:<id>", "struct:<id>", or a custom provider name.
	Name string

	// Optional information for callers that cannot enumerate keys
	// (typically custom string providers).
	Note string

	// Provides lists every (field, key|value) pair this layer can
	// supply to the model.
	Provides []FieldProvision
}

LayerInventory is one layer's contribution to a Report.

type Layers

type Layers []Layer

func (Layers) GetPolicies

func (layers Layers) GetPolicies() (

	constraintLayerPolicies,
	error,
)

type ModelInterface

type ModelInterface interface {
	// TypeName returns a human-readable name for the configuration type.
	// Used for error reporting and debugging.
	TypeName() string

	// ApplyOn extracts configuration values using the provided value getter.
	// Returns field values mapped by their unique identifiers.
	ApplyOn(g internal.ValueGetter) (fvalue.Values, error)

	// Expand processes struct expansion using the provided struct expander.
	// This handles complex configuration structures and nested types.
	Expand(g internal.StructExpander) error

	// GetFieldValuesFor extracts field values from the given struct value.
	// Used to convert Go structs into the internal field value representation.
	GetFieldValuesFor(id string, v reflect.Value) fvalue.Values

	// Fill populates the target struct with values from configuration layers.
	// Returns location information for debugging and error reporting.
	Fill(
		inputModelValue reflect.Value,
		layers []fvalue.Values,
	) (plocation.Locations, error)
}

ModelInterface represents a configuration structure model that defines how configuration data should be processed, validated, and filled into Go structs. It provides the metadata and operations needed for dsco's configuration processing.

func BuildModel added in v1.4.0

func BuildModel(cfg any) (ModelInterface, error)

BuildModel constructs the configuration model from a pointer-to-struct value, mirroring the model-build phase of Fill. Exposed for the inventory sub-package; callers should generally use Fill or PrepareInventoryWalk instead.

type NamedStringValuesProvider

type NamedStringValuesProvider interface {
	StringValuesProvider
	// GetName returns a human-readable identifier for this provider,
	// used in error messages and debugging output.
	GetName() string
}

NamedStringValuesProvider extends StringValuesProvider with identification capabilities, allowing the provider to be uniquely named for debugging and error reporting purposes.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option is processing option for string based binder.

type OverriddenKeyError

type OverriddenKeyError struct {
	Path             string
	Location         string
	OverrideLocation string
}

func (OverriddenKeyError) Error

func (a OverriddenKeyError) Error() string

func (OverriddenKeyError) Is

func (OverriddenKeyError) Is(err error) bool

type ParseError

type ParseError struct {
	Path     string
	Type     reflect.Type
	Location string
}

func (ParseError) Error

func (a ParseError) Error() string

func (ParseError) Is

func (ParseError) Is(err error) bool

type PoliciesGetter

type PoliciesGetter interface {
	// GetPolicies transforms configuration layers into policy objects
	// that determine how values are processed and validated.
	GetPolicies() (constraintLayerPolicies, error)
}

PoliciesGetter defines the ability to retrieve layer policies for configuration processing, converting layers into constraint policies.

type StrictCmdlineLayer

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

StrictCmdlineLayer is a strict command line layer.

func WithStrictCmdlineLayer

func WithStrictCmdlineLayer(options ...Option) *StrictCmdlineLayer

WithStrictCmdlineLayer creates a strict command line layer. It can be used only once.

type StrictEnvLayer

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

StrictEnvLayer is a strict environnement variables layer.

func WithStrictEnvLayer

func WithStrictEnvLayer(prefix string, options ...Option) *StrictEnvLayer

WithStrictEnvLayer creates a new strict environment layer.

type StrictStringProviderLayer

type StrictStringProviderLayer struct {
	StringProviderLayer
}

func WithStrictStringValueProvider

func WithStrictStringValueProvider(
	provider NamedStringValuesProvider,
	options ...Option,
) *StrictStringProviderLayer

type StrictStructLayer

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

StrictStructLayer is a strict structure layer.

func WithStrictStructLayer

func WithStrictStructLayer(input any, id string) *StrictStructLayer

WithStrictStructLayer creates a new strict structure layer.

type StringBasedBuilder

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

StringBasedBuilder is a value bases builder depending on text values.

func CmdLine

func CmdLine(options ...Option) (
	*StringBasedBuilder,
	error,
)

CmdLine builds a command line manager.

func Env

func Env(prefix string, options ...Option) (
	*StringBasedBuilder,
	error,
)

Env builds a env manager.

func NewStringBasedBuilder

func NewStringBasedBuilder(
	provider StringValuesProvider,
	options ...Option,
) (
	*StringBasedBuilder,
	error,
)

NewStringBasedBuilder creates a bases builder for the provided path/text value set.

func NewStringBasedBuilderForTest added in v1.4.0

func NewStringBasedBuilderForTest(
	provider StringValuesProvider,
	kind, metaOrPrefix string,
) (*StringBasedBuilder, error)

NewStringBasedBuilderForTest constructs a StringBasedBuilder with a synthetic KeyFormatter. Intended solely for tests that need to exercise ReportInventory without going through the layer wrappers in builders.go.

kind must be one of "env", "cmdline", "file", or "" (nil formatter for custom-provider behaviour). For "env" / "file", metaOrPrefix is the prefix or file id.

func (*StringBasedBuilder) ExpandStruct

func (s *StringBasedBuilder) ExpandStruct(
	path string,
	_type reflect.Type) (
	err error,
)

func (*StringBasedBuilder) Get

func (s *StringBasedBuilder) Get(
	path string,
	_type reflect.Type,
) (
	fieldValue *fvalue.Value,
	err error,
)

func (*StringBasedBuilder) GetFieldValuesFrom

func (s *StringBasedBuilder) GetFieldValuesFrom(
	_model ModelInterface,
) (
	fvalue.Values,
	error,
)

GetBaseFor creates the bases.

func (*StringBasedBuilder) ReportInventory added in v1.4.0

func (s *StringBasedBuilder) ReportInventory(
	mdl ModelInterface,
) (LayerInventory, error)

ReportInventory implements InventoryReporter by walking the model's alias map and rendering each entry through the layer's KeyFormatter. No I/O is performed.

type StringProviderLayer

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

func WithStringValueProvider

func WithStringValueProvider(
	provider NamedStringValuesProvider,
	options ...Option,
) *StringProviderLayer

type StringValuesProvider

type StringValuesProvider interface {
	// GetStringValues retrieves all string values provided by this source,
	// returning a map of keys to their corresponding string values and
	// locations.
	GetStringValues() svalue.Values
}

StringValuesProvider defines the interface for providers that supply string-based configuration values from various sources like environment variables, command line arguments, or configuration files.

type StructBuilder

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

StructBuilder is a structure layer builder.

func NewStructBuilder

func NewStructBuilder(inputStruct any, id string) (*StructBuilder, error)

NewStructBuilder creates a new structure layer builder.

func (*StructBuilder) GetFieldValuesFrom

func (s *StructBuilder) GetFieldValuesFrom(model ModelInterface) (
	fvalue.Values, error,
)

func (*StructBuilder) ReportInventory added in v1.4.0

func (s *StructBuilder) ReportInventory(
	mdl ModelInterface,
) (LayerInventory, error)

ReportInventory implements InventoryReporter by enumerating every non-nil field of the source struct and recording its value as a FieldProvision. No I/O is performed.

type StructLayer

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

StructLayer is a structure layer.

func WithStructLayer

func WithStructLayer(input any, id string) *StructLayer

WithStructLayer creates a structure layer.

type UnboundedLocationError

type UnboundedLocationError struct {
	Location string
}

func (UnboundedLocationError) Error

func (a UnboundedLocationError) Error() string

func (UnboundedLocationError) Is

type UnboundedLocationErrors

type UnboundedLocationErrors []UnboundedLocationError

func (UnboundedLocationErrors) Len

func (u UnboundedLocationErrors) Len() int

func (UnboundedLocationErrors) Less

func (u UnboundedLocationErrors) Less(i, j int) bool

func (UnboundedLocationErrors) Swap

func (u UnboundedLocationErrors) Swap(i, j int)

Directories

Path Synopsis
dummy
d1
examples
deadsimple command
deadsimple2 command
inventory command
Package main demonstrates the dsco inventory sub-package.
Package main demonstrates the dsco inventory sub-package.
inventory/json command
Package main shows how to dump a dsco inventory as JSON, the format you'd feed to jq, ansible, or whatever else fills env files for you.
Package main shows how to dump a dsco inventory as JSON, the format you'd feed to jq, ansible, or whatever else fills env files for you.
inventory/preflight command
Package main is a preflight check you can run in CI or on container startup to list every config key that has no default.
Package main is a preflight check you can run in CI or on container startup to list every config key that has no default.
simplemain command
Package fvalue provides field value types with location tracking for dsco's internal configuration processing pipeline.
Package fvalue provides field value types with location tracking for dsco's internal configuration processing pipeline.
hit
Package hit provides hash-based utilities for dsco's deduplication and caching systems.
Package hit provides hash-based utilities for dsco's deduplication and caching systems.
hprovider
Package hprovider provides hash instance pooling for efficient hash computation in dsco's hit package.
Package hprovider provides hash instance pooling for efficient hash computation in dsco's hit package.
cmdline
Package cmdline provides command-line argument parsing functionality for dsco's configuration system.
Package cmdline provides command-line argument parsing functionality for dsco's configuration system.
env
Package env provides environment variable parsing functionality for dsco's configuration system.
Package env provides environment variable parsing functionality for dsco's configuration system.
fvalue
Package fvalue provides field value representation for dsco's configuration processing system.
Package fvalue provides field value representation for dsco's configuration processing system.
ierror
Package ierror provides indexed error handling for dsco's configuration processing system.
Package ierror provides indexed error handling for dsco's configuration processing system.
kfile
Package kfile provides file-based configuration value extraction for dsco's configuration system.
Package kfile provides file-based configuration value extraction for dsco's configuration system.
merror
Package merror provides multiple error aggregation functionality for dsco's configuration processing system.
Package merror provides multiple error aggregation functionality for dsco's configuration processing system.
model
Package model provides reflection-based struct analysis and field mapping for dsco's configuration processing system.
Package model provides reflection-based struct analysis and field mapping for dsco's configuration processing system.
plocation
Package plocation provides path location tracking for dsco's configuration debugging and reporting system.
Package plocation provides path location tracking for dsco's configuration debugging and reporting system.
utils
Package utils provides utility functions for dsco's configuration processing system.
Package utils provides utility functions for dsco's configuration processing system.
Package inventory computes the static list of configuration keys a dsco-managed struct expects, given a set of layers, without performing any I/O.
Package inventory computes the static list of configuration keys a dsco-managed struct expects, given a set of layers, without performing any I/O.
Package ref provides utility functions for creating references to values.
Package ref provides utility functions for creating references to values.
Package registry provides type name registration and formatting utilities for dsco's reflection-based configuration system.
Package registry provides type name registration and formatting utilities for dsco's reflection-based configuration system.
Package svalue provides string value types with location tracking for dsco configuration sources.
Package svalue provides string value types with location tracking for dsco configuration sources.
Package url provides an unmarshallable URL type for dsco configuration fields.
Package url provides an unmarshallable URL type for dsco configuration fields.

Jump to

Keyboard shortcuts

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