dsco

package module
v1.3.0-beta Latest Latest
Warning

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

Go to latest
Published: Mar 30, 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

Stop deploying microservices with broken configuration.

dsco is a Go configuration library that makes misconfiguration impossible. No more silent defaults. No more "it works on my machine." No more 3 AM pages because someone forgot to set DATABASE_PASSWORD in production.

// 30 seconds to bulletproof configuration
var config *Config
dsco.Fill(&config,
    dsco.WithStructLayer(defaults, "defaults"),  // Dev defaults baked in
    dsco.WithEnvLayer("MYAPP"),                  // Container/K8s config
    dsco.WithCmdlineLayer(),                     // Quick local overrides
)
// Missing config? App won't start. You'll know immediately.

Go Go Reference Go Version Go Report Card Test Coverage

Français | English


Why dsco?

Traditional Go configuration is dangerous:

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: defaults (lowest priority)
        dsco.WithStructLayer(&Config{
            Host: dsco.R("localhost"),
            Port: dsco.R(8080),
        }, "defaults"),
        // Layer 2: environment variables
        dsco.WithEnvLayer("MYAPP"),
        // Layer 3: command line (highest priority)
        dsco.WithCmdlineLayer(),
    )
    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 Struct defaults → env vars → cmdline. Later 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?
// DANGEROUS: Is Port 0 intentional or missing?
type Config struct {
    Port int
}

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

The dsco.R() helper makes pointer creation painless:

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

dsco ensures all configuration is complete before your app starts:

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

dsco gives you complete control over what's configurable, when, and by whom.

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"),
)

Your service runs perfectly. No external configuration needed. No environment variables to forget. No 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.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"),
    dsco.WithEnvLayer("MYSERVICE"),  // Only MYSERVICE-TIMEOUT needs to exist
)

No recompilation required. The code didn't change - you just added an env layer. Operations can now tune MYSERVICE-TIMEOUT=60s without touching the binary.

Phase 3: Protect critical values

Some defaults should never be overridden in production:

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

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

Even 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.WithStructLayer(productionDefaults, "defaults"),
    dsco.WithEnvLayer("SVC"),
)
// 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.WithEnvLayer("SVC"),
    dsco.WithStrictStructLayer(&Config{
        TLSEnabled:    dsco.R(true),
        AuditLogging:  dsco.R(true),
        MinTLSVersion: dsco.R("1.3"),
    }, "security"),
)

You decide what's flexible and what's fixed. dsco enforces your decisions.


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.WithStructLayer(devDefaults, "dev"),
    dsco.WithCmdlineLayer(),
)
./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 - Later layers override earlier
  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 later layer (override detection)
_, err := dsco.Fill(&config,
    dsco.WithStrictEnvLayer("MYAPP"),  // Strict
    dsco.WithCmdlineLayer(),            // Can override
)
// MYAPP-PORT=8080 + --port=9000 → Error!
// Env value was overridden.
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


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. Later layers override earlier ones, with optional strict mode for conflict detection.

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: Later layers override earlier ones 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

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 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 ErrDuplicateStructID = errors.New("")

ErrDuplicateStructID is the sentinel error for duplicate struct ID.

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

ErrFiller is the sentinel error for configuration filling failures.

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 ErrNilInput = errors.New("nil input")

ErrNilInput is dummy...

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.

Functions

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

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 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 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 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.

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 (*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.

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

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