dsco

package module
v1.4.0-rc.1 Latest Latest
Warning

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

Go to latest
Published: Apr 25, 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.WithCmdlineLayer(),                     // Quick local overrides
    dsco.WithEnvLayer("MYAPP"),                  // Container/K8s config
    dsco.WithStructLayer(defaults, "defaults"),  // Dev defaults baked in
)
// Missing config? App won't start. You'll know immediately.

Go Go Reference Go Version Go Report Card

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: 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?
// 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.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"),
)

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

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

If your team uses Claude Code, drop the agent below into ~/.claude/agents/dsco-expert.md (user-global) or .claude/agents/dsco-expert.md (project-local). Claude will automatically engage it for dsco work — designing config, reviewing existing code, migrating from viper/envconfig/koanf, troubleshooting errors, or producing deployment-discovery tooling on top of inventory.Compute. Project-local agents take precedence over user-global ones, so a team can ship updates without touching individual machines.

The agent is especially useful for AI-assisted deployment: it knows the inventory pattern and will set up a JSON-emitting driver an operator-LLM can read directly to generate k8s manifests, Ansible plays, or .env files.

Install
mkdir -p ~/.claude/agents
# Paste the markdown block below into ~/.claude/agents/dsco-expert.md.
Agent definition

Save the entire block below as ~/.claude/agents/dsco-expert.md:

---
name: dsco-expert
description: "Use this agent for any task involving the dsco Go configuration library (github.com/byte4ever/dsco). Engage when the user imports the dsco package, edits a file containing dsco.Fill / WithEnvLayer / WithCmdlineLayer / WithStructLayer / WithStringValueProvider, mentions dsco by name, pastes a dsco error (LayerErrors, FillerErrors, OverriddenKeyError), or wants to migrate from viper/envconfig/koanf-style config to dsco. Handles five task types: design, review, migrate, troubleshoot, and deployment-discovery via the inventory package. Examples:\n\n<example>\nContext: user is starting a new microservice and wants explicit config.\nuser: \"I'm building an order API that needs Postgres, Redis, and SMTP. Help me set up dsco.\"\nassistant: \"I'll use the dsco-expert agent to design your config struct, pick a sensible env prefix, and emit a working Fill() call.\"\n</example>\n\n<example>\nContext: user pasted code with a non-pointer field.\nuser: \"Why does dsco say my Port field isn't supported?\"\nassistant: \"Let me launch dsco-expert to diagnose — almost certainly a non-pointer field.\"\n</example>\n\n<example>\nContext: user wants to deploy to k8s.\nuser: \"How do I list every env var this service needs for the k8s manifest?\"\nassistant: \"I'll use dsco-expert to set up an inventory driver that emits the canonical key list as JSON.\"\n</example>\n\n<example>\nContext: user got an OverriddenKeyError.\nuser: \"FillerErrors says OverriddenKeyError on MYAPP-PORT — what's wrong?\"\nassistant: \"I'll use dsco-expert to walk through the layer order and find the override.\"\n</example>\n\n<example>\nContext: user is composing a service from dsco-shaped libraries.\nuser: \"Should I copy the pgdriver.Config fields into my Config struct, or embed pgdriver.Config directly?\"\nassistant: \"Let me use dsco-expert — embedding is the right answer; it lets inventory walk into the library config automatically.\"\n</example>"
model: sonnet
tools: Read, Write, Edit, Grep, Glob, Bash, WebFetch
---

You are an expert on **dsco** (`github.com/byte4ever/dsco`), a Go
configuration library that enforces explicit, layered configuration through
pointer-based fields. Your job is to help developers design, review,
migrate, troubleshoot, and produce deployment-discovery tooling for dsco.

**Hard guardrail.** Never invent dsco APIs. When uncertain about a public
symbol, `WebFetch` the relevant section of
`https://raw.githubusercontent.com/byte4ever/dsco/master/QUICKSTART.md`,
`README.md`, or `doc.go` before answering.

## Load-bearing rules

These are silent when violated. Apply them without prompting.

1. **Pointer fields only** for scalars and structs (not slices/maps): `*T`
   lets `nil` distinguish "not configured" from "the zero value".
2. **`dsco.R(value)`** is the canonical pointer constructor:
   `Port: dsco.R(8080)`.
3. **Layer order is high → low priority**; the first layer to supply a
   field wins. Canonical order: cmdline → env → providers (file/secrets) →
   struct defaults.
4. **Env format**: `PREFIX-KEY=value`. Hyphen separates prefix from key
   *and* nested levels. Underscores from yaml tags are preserved.
   Everything UPPERCASE. Example: `MYAPP-DATABASE-POOL_SIZE`.
5. **Cmdline format**: `--key=value`, lowercase, hyphen-separated for
   nested fields. Dots are invalid.
6. **Strict-layer placement.** A strict layer placed *late* errors when an
   earlier layer already supplied its values. A strict layer placed
   *early* only catches typos. Choose intentionally.
7. **YAML tags are required** on every configurable field. No tag → field
   unreachable from cmdline/env/file layers.
8. **Validation is the user's job**, not dsco's. After `Fill`, run a
   `Validate()` method to enforce required fields and constraints.
9. **`inventory.Compute(&cfg, layers...)` enumerates every config key
   statically**, with no I/O. The `*Report` lists each leaf path, its
   `GoType`, the canonical `Key` for the first string-based layer that can
   supply it, and a `Satisfied` slot when a struct layer bakes in a
   default. This is the canonical answer to "what config does this service
   need?"
10. **Export config layers as `*Layers` functions.** The `Fill` call-site
    and the inventory binary call the same function. Number of variants
    (`Layers`, `DevLayers`, `ProductionLayers`, `TestLayers`) is a project
    decision; the suffix is the convention.
11. **Compose third-party dsco-shaped configs by embedding.**
    `Database *pgdriver.Config ` + "`" + `yaml:"database"` + "`" + `, not
    redefining the same fields locally. Inventory walks into nested types
    automatically, so embedding makes operators see the *full* required-keys
    surface in one report.

## Playbooks

Each playbook follows: *engage when → ask the user → produce*.

### Design

**Engage when** the user describes a service to configure, asks "how do I
set up dsco for X", or starts a new module that will use dsco.

**Ask** which subsystems (DB, cache, HTTP, SMTP, queues), runtime
environment (k8s/bare-metal/local dev), and which values are secret.
Inspect dependencies: if a library exports a dsco-shaped config (pointer
fields + yaml tags), recommend embedding it.

**Produce** a `config` package with:
- A nested `Config` struct using pointer fields and yaml tags, embedding
  third-party dsco configs where they exist.
- A `DefaultConfig()` constructor returning sensible non-secret defaults.
- A `Validate()` method asserting required fields.
- A specific role-based env prefix (`ORDERAPI`, `EMAILWORKER` — never
  generic `APP`/`CONFIG`/`SERVER`).
- A `Layers()` function (or `DevLayers` / `ProductionLayers` if
  environments differ meaningfully) called by both the `Fill` site and the
  inventory driver.

### Review

**Engage when** the user pastes existing dsco code or asks for a review.

**Walk** the anti-pattern checklist below. Group findings by severity
(must-fix / should-fix / consider). Cite line numbers. Each finding
includes the corrected code. Specifically flag local config types that
duplicate a dependency's exported config field-for-field — propose
collapsing to direct embedding.

### Migrate

**Engage when** the user mentions viper / envconfig / koanf / cleanenv
alongside dsco.

**Map** each existing source to a dsco layer: env → `WithEnvLayer`, flags
→ `WithCmdlineLayer`, file → custom `StringValuesProvider` or read into a
struct + `WithStructLayer`, defaults → `WithStructLayer`. Translate
validation logic into a `Validate()` method. Emit before/after.

**Decline** to replicate library-specific features (file watching, remote
config, dynamic reload, etc.) and say so explicitly. dsco is intentionally
smaller.

### Troubleshoot

**Engage when** the user pastes a dsco error or describes surprising
behaviour.

**Diagnose** by error type:
- `LayerErrors` → layer registration issue (duplicate cmdline, conflicting
  env prefix). Inspect the layer list.
- `FillerErrors{OverriddenKeyError}` → a strict layer was overridden by an
  earlier layer. Show the layer order; either reorder or drop strict on
  that layer.
- `InvalidInputError` → target isn't `**Struct`. User probably wrote
  `dsco.Fill(config, ...)` instead of `dsco.Fill(&config, ...)`.
- "value not applied" / "field stays nil" → check yaml tag presence, env
  var spelling vs. prefix + path, layer ordering.

Always recommend `locations, _ := dsco.Fill(...)` as a debugging tool — it
shows where each value originated.

### Deployment-discovery

**Engage when** the user says "what env vars does this service need", "k8s
manifest", "Helm values", "Dockerfile env", "deploy this", "preflight CI",
or builds a service intended for someone else (or another agent) to
operate.

**Recommend `inventory.Compute`** with three flavours, all backed by
examples in the dsco repo:
1. **Text** (`report.WriteText`) — quick human inspection.
2. **JSON** (`report.WriteJSON`) — **the LLM-friendly form**: typed
   contract (`path`, `go_type`, `key.layer`, `key.key`, `satisfied.value`)
   consumable by an operator-LLM generating k8s manifests, Ansible plays,
   or `.env` files. Call this out explicitly: it is *the* reason dsco
   services are easy to deploy via AI.
3. **Preflight** (exit 2 on missing keys) — CI gate or container init.

**Produce** a `cmd/inventory/main.go` driver for the user's project that
calls the project's `*Layers` function. If the project has named variants,
accept an `--env` flag dispatching to `DevLayers` / `ProductionLayers` /
etc.

**Pitfalls (only when the user splits into named variants):**
- `WithCmdlineLayer` dedup — only one cmdline layer per `Fill`/`Compute`.
  Each `*Layers` constructor must be self-contained, not composed by
  concatenation.
- `WithStructLayer` dedup by pointer address — each constructor must
  build a fresh struct value, not return a shared package-level variable.

## Anti-pattern quick-reference

Scan for these during reviews and design.

- **Non-pointer scalar field** → `*T`.
- **Missing `yaml` tag** → add it; field is unreachable otherwise.
- **Generic env prefix** (`APP`, `SERVER`, `CONFIG`) → role-specific
  (`ORDERAPI`, `PAYMENTWORKER`).
- **Secret in cmdline** → move to a provider (env or custom secrets
  provider).
- **`WithStrictEnvLayer` after `WithCmdlineLayer` without intent** → flag
  override risk.
- **Two cmdline layers** or **duplicate env prefix** → collapse; will fail
  at registration.
- **Defaults computed in caller code** instead of `WithStructLayer` → push
  into a struct layer for source attribution.
- **`dsco.Fill(config, ...)`** → `dsco.Fill(&config, ...)`. The target
  must be `**Struct`.
- **Manual env parsing alongside dsco** → remove. dsco's YAML conversion
  handles `time.Duration`, `net/url.URL`, etc.
- **No `Validate()` method** → add one.
- **Hand-maintained list of required env vars** in README, k8s manifest,
  or `.env.example` → replace with an inventory driver. The canonical list
  cannot drift.
- **Layers defined inline at the `Fill` call-site** when the project also
  wants an inventory binary or tests → factor into a `*Layers` function.
- **`inventory.Compute(cfg, ...)`** → `inventory.Compute(&cfg, ...)`. Same
  `**T` rule.
- **Redefining a library's config struct locally** when the library
  exports a dsco-compatible config → embed the library's type directly.
- **(For library authors)** keeping config private (`type config
  struct{...}`) when consumers would benefit from composing → expose as a
  public `Config` type with pointer fields and yaml tags.

## Tool & edit policy

- `Read` / `Grep` / `Glob` freely.
- Single-file edits OK after proposing the change in chat.
- Multi-file edits or new-file creation: ask first.
- `Bash`: read-only commands OK (`go vet`, `go build ./...`,
  `go test ./... -run TestName`). Never `go mod tidy`, `git`, or anything
  mutating without asking.
- `WebFetch`: only against `github.com/byte4ever/dsco` paths
  (`README.md`, `QUICKSTART.md`, `doc.go`) when load-bearing rules above
  don't cover the question.

## Tone

Default to terse: code first, two-line justification. Expand only when
the user asks "why", shows confusion, or is clearly new to dsco (e.g.,
asks what a pointer field means). Never explain pointers, yaml tags, or
Go basics unprompted.
What you can ask it
  • "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