config

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Dec 26, 2025 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package config provides hierarchical configuration resolution for CLI applications.

This package supports layered configuration with clear precedence:

  1. Environment variables (highest priority)
  2. Local config (e.g., .myapp.yaml in git root)
  3. Global config (e.g., ~/.config/myapp/config.yaml)
  4. Built-in defaults (lowest priority)

Basic Usage

Create a resolver with your application's settings:

resolver := config.NewResolver(config.ResolverConfig{
    EnvPrefix:       "MYAPP_",
    GlobalConfigDir: "myapp",
    LocalConfigName: ".myapp.yaml",
    Defaults: map[string]string{
        "api_url": "http://localhost:8080",
        "format":  "table",
    },
})

cfg := resolver.Resolve()
fmt.Println(cfg.Get("api_url"))        // "http://localhost:8080"
fmt.Println(cfg.Source("api_url"))     // "default"

Environment Variables

Environment variables are automatically detected using the configured prefix:

# With EnvPrefix: "MYAPP_"
MYAPP_API_URL=https://api.example.com  # sets "api_url"
MYAPP_FORMAT=json                       # sets "format"

Config Sources

Each resolved value tracks where it came from:

  • "default": Built-in default value
  • "global": ~/.config/<app>/config.yaml
  • "local": .myapp.yaml in git root
  • "env": Environment variable
  • "flag": Command-line flag (set via SetFlagValue)

Git Root Detection

By default, the resolver looks for the local config in the git repository root. You can customize this by providing a GitRootFinder function:

resolver := config.NewResolver(config.ResolverConfig{
    GitRootFinder: func(dir string) (string, error) {
        // Custom logic to find git root
        return myGitRoot(), nil
    },
})

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Resolved

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

Resolved holds the final merged configuration.

func (*Resolved) All

func (c *Resolved) All() map[string]string

All returns a copy of all key-value pairs.

func (*Resolved) Get

func (c *Resolved) Get(key string) string

Get returns the value for a key, or empty string if not set.

func (*Resolved) GetWithSource

func (c *Resolved) GetWithSource(key string) (string, Source)

GetWithSource returns both the value and its source.

func (*Resolved) Keys

func (c *Resolved) Keys() []string

Keys returns all configuration keys.

func (*Resolved) Source

func (c *Resolved) Source(key string) Source

Source returns the source of a key's value.

type Resolver

type Resolver struct {

	// Warnings collects non-fatal issues during resolution.
	Warnings []string
	// contains filtered or unexported fields
}

Resolver handles hierarchical configuration resolution.

func NewResolver

func NewResolver(cfg ResolverConfig) *Resolver

NewResolver creates a new configuration resolver.

func NewResolverWithPaths

func NewResolverWithPaths(cfg ResolverConfig, globalPath, localPath string) *Resolver

NewResolverWithPaths creates a resolver with explicit global and local paths. This is useful for testing or when paths are known ahead of time.

func (*Resolver) GitRoot

func (r *Resolver) GitRoot() string

GitRoot returns the detected git root directory.

func (*Resolver) GlobalPath

func (r *Resolver) GlobalPath() string

GlobalPath returns the path to the global config file.

func (*Resolver) LocalPath

func (r *Resolver) LocalPath() string

LocalPath returns the path to the local config file.

func (*Resolver) Resolve

func (r *Resolver) Resolve() *Resolved

Resolve builds the final config by merging all sources. Priority (highest to lowest): flags > env > local > global > defaults.

func (*Resolver) ResolveWithFlags

func (r *Resolver) ResolveWithFlags(flags map[string]string) *Resolved

ResolveWithFlags resolves config and applies flag overrides.

type ResolverConfig

type ResolverConfig struct {
	// EnvPrefix is prepended to key names for environment variable lookup.
	// For example, with EnvPrefix "MYAPP_", key "api_url" maps to MYAPP_API_URL.
	EnvPrefix string

	// GlobalConfigDir is the name of the directory under ~/.config/
	// where the global config is stored.
	// For example, "myapp" results in ~/.config/myapp/config.yaml.
	GlobalConfigDir string

	// GlobalConfigFile is the filename for global config.
	// Defaults to "config.yaml" if empty.
	GlobalConfigFile string

	// LocalConfigName is the filename for local config in the git root.
	// For example, ".myapp.yaml".
	LocalConfigName string

	// Defaults provides the default values for configuration keys.
	Defaults map[string]string

	// ValidGlobalKeys lists keys that can be set in global config.
	// If nil, all keys are valid.
	ValidGlobalKeys []string

	// ValidLocalKeys lists keys that can be set in local config.
	// If nil, all keys are valid.
	ValidLocalKeys []string

	// GitRootFinder is a function that finds the git root directory.
	// If nil, uses a simple git root detection.
	GitRootFinder func(startDir string) (string, error)

	// ErrWriter is where warnings are written.
	// Defaults to os.Stderr if nil.
	ErrWriter io.Writer
}

ResolverConfig configures the hierarchical config resolver.

type SaveConfig

type SaveConfig struct {
	// GlobalConfigDir is the directory under ~/.config/ for global config.
	GlobalConfigDir string

	// GlobalConfigFile is the filename. Defaults to "config.yaml".
	GlobalConfigFile string

	// LocalConfigName is the filename for local config in git root.
	LocalConfigName string

	// ValidGlobalKeys lists keys that can be set in global config.
	ValidGlobalKeys []string

	// ValidLocalKeys lists keys that can be set in local config.
	ValidLocalKeys []string
}

SaveConfig provides methods to save configuration values.

func (SaveConfig) DeleteGlobalKey

func (c SaveConfig) DeleteGlobalKey(key string) error

DeleteGlobalKey removes a key from the global config.

func (SaveConfig) SaveGlobal

func (c SaveConfig) SaveGlobal(key, value string) error

SaveGlobal saves a key-value pair to the global config file.

func (SaveConfig) SaveLocal

func (c SaveConfig) SaveLocal(gitRoot, key, value string) error

SaveLocal saves a key-value pair to the local config file in the git root.

type Source

type Source string

Source indicates where a configuration value came from.

const (
	// SourceDefault indicates the value is a built-in default.
	SourceDefault Source = "default"

	// SourceGlobal indicates the value came from global config
	// (e.g., ~/.config/<app>/config.yaml).
	SourceGlobal Source = "global"

	// SourceLocal indicates the value came from local config
	// (e.g., .myapp.yaml in git root).
	SourceLocal Source = "local"

	// SourceEnv indicates the value came from an environment variable.
	SourceEnv Source = "env"

	// SourceFlag indicates the value was set via command-line flag.
	SourceFlag Source = "flag"
)

Configuration source constants.

Jump to

Keyboard shortcuts

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