Add platform-independent path/config resolution library

Implements core/paths (Config/Data/State/Cache/Runtime/Log/Bin
directory resolution with canonical-vs-search-dir separation, XDG on
Unix, native APPDATA/LOCALAPPDATA/PROGRAMDATA layering on Windows,
~/Library on macOS Desktop, injectable environment/platform for
deterministic cross-platform tests) and core/config (file search,
first-match resolution, layered YAML merging, safe ${VAR} expansion,
Explain/doctor introspection) on top of the shared Application/
Kind/Scope model in the core package.
This commit is contained in:
terminar committed 2026-09-19 16:26:01 +02:00
1 parent 027b327c3d
commit 13801bec11
41 files changed
+4834 -2

No files matched your search

+169
View File
@@ -0,0 +1,169 @@
// Package config resolves, searches, and layers a Yetano application's
// configuration *files* -- built on top of core/paths, which only
// resolves *directories* and knows nothing about file contents (see
// AGENTS.md: "paths must not implicitly parse configuration").
//
// A Resolver is obtained via For (or New):
//
// app := core.Application{Name: "yet", Kind: core.CLI}
// cfg := config.For(app)
//
// selected, found, err := cfg.Resolve() // highest-priority existing file
// all, err := cfg.ResolveAll() // every layer, with metadata
//
// var target MyConfig
// err = cfg.LoadMerged(&target) // lowest-to-highest priority merge
//
// # Search order and merge order are the same hierarchy
//
// Resolve/ResolveAll walk the priority hierarchy highest-to-lowest
// (first match wins); LoadMerged walks the exact same hierarchy
// lowest-to-highest (each layer overlays the previous one). Both derive
// from one ordered []Layer -- see layers() in layers.go -- so there is
// never a second, independently-maintained ordering to keep in sync.
//
// # Priority hierarchy
//
// Highest to lowest, on Unix:
//
// working directory (./) -- toggle: WithWorkingDirectory
// <app>'s user config dir (paths.ConfigDir/ConfigSearchDirs)
// <app>'s system config dir -- toggle: WithSystemConfig
// the shared Yetano config dir -- toggle: WithYetanoDefaults (opt-in, off by default)
//
// On Windows, the user/system tier expands to the same three-layer
// LOCALAPPDATA > APPDATA > PROGRAMDATA search core/paths already
// resolves (see core/paths's package doc); config only adds the working
// directory layer on top and the Yetano-defaults layer below.
//
// # Environment expansion
//
// A loaded file's string values may reference ${VAR}/$VAR (see
// expand.go); this is plain variable substitution, never a shell -- no
// $(...), no backticks, no command execution of any kind.
package config
import (
"yetano.dev/yetano/core"
"yetano.dev/yetano/core/paths"
)
// Filename derives the default configuration file name for an
// application: "<name>.yaml".
func Filename(app core.Application) string {
return app.Name + ".yaml"
}
// Resolver resolves, searches, and layers one application's
// configuration files.
type Resolver struct {
app core.Application
paths *paths.Resolver
filename string
workdir bool
workdirPath string
systemConfig bool
yetanoDefaults bool
envExpansion bool
env paths.Environment
pathsOpts []paths.Option
}
// Option configures a Resolver constructed by New/For.
type Option func(*Resolver)
// New constructs a Resolver for app.
func New(app core.Application, opts ...Option) (*Resolver, error) {
if err := app.Validate(); err != nil {
return nil, err
}
r := &Resolver{
app: app,
filename: Filename(app),
workdir: true,
workdirPath: ".",
systemConfig: true,
envExpansion: true,
env: paths.OSEnvironment,
}
for _, opt := range opts {
opt(r)
}
pr, err := paths.New(app, append([]paths.Option{paths.WithEnvironmentProvider(r.env)}, r.pathsOpts...)...)
if err != nil {
return nil, err
}
r.paths = pr
return r, nil
}
// For is an alias for New, matching the spec's `config.For(app)` spelling.
func For(app core.Application, opts ...Option) (*Resolver, error) {
return New(app, opts...)
}
// WithFilename overrides the configuration file name (default
// "<app-name>.yaml").
func WithFilename(name string) Option {
return func(r *Resolver) { r.filename = name }
}
// WithWorkingDirectory enables or disables the working-directory layer
// (spec section 23) -- important to disable for services, which have no
// meaningful "current directory" a human invoked them from.
func WithWorkingDirectory(enabled bool) Option {
return func(r *Resolver) { r.workdir = enabled }
}
// WithWorkdirPath overrides the directory used for the working-directory
// layer (default "."). Mainly useful for deterministic tests.
func WithWorkdirPath(path string) Option {
return func(r *Resolver) { r.workdirPath = path }
}
// WithSystemConfig enables or disables the system-wide configuration
// layer (/etc/<app>, %PROGRAMDATA%\<app>, ...). Enabled by default.
func WithSystemConfig(enabled bool) Option {
return func(r *Resolver) { r.systemConfig = enabled }
}
// WithYetanoDefaults enables the shared, ecosystem-wide Yetano
// configuration directory (spec section 4) as the lowest-priority
// fallback layer. Disabled by default: an application must opt in.
func WithYetanoDefaults(enabled bool) Option {
return func(r *Resolver) { r.yetanoDefaults = enabled }
}
// WithEnvExpansion enables or disables ${VAR}/$VAR expansion of string
// values when loading a file (LoadMerged). Enabled by default.
func WithEnvExpansion(enabled bool) Option {
return func(r *Resolver) { r.envExpansion = enabled }
}
// WithEnvironment injects a fixed environment variable map, used both
// for ${VAR} expansion and (via WithEnvironmentProvider on the
// underlying paths.Resolver) for locating the configuration directories
// themselves -- so a test can set HOME once and have it apply
// consistently everywhere.
func WithEnvironment(env map[string]string) Option {
return func(r *Resolver) { r.env = paths.MapEnvironment(env) }
}
// WithEnvironmentProvider injects a custom paths.Environment
// implementation, for the same purposes as WithEnvironment.
func WithEnvironmentProvider(env paths.Environment) Option {
return func(r *Resolver) { r.env = env }
}
// WithPathsOptions passes additional options through to the underlying
// core/paths.Resolver (e.g. paths.WithPlatform, paths.WithRoot).
func WithPathsOptions(opts ...paths.Option) Option {
return func(r *Resolver) { r.pathsOpts = append(r.pathsOpts, opts...) }
}
// Application returns the Application this Resolver was built for.
func (r *Resolver) Application() core.Application { return r.app }
// Filename returns the configuration file name this Resolver searches
// for in every layer.
func (r *Resolver) Filename() string { return r.filename }
+82
View File
@@ -0,0 +1,82 @@
package config
import (
"path/filepath"
"testing"
"yetano.dev/yetano/core/paths"
)
func TestConfigResolverAccessors(t *testing.T) {
r := mustResolver(t, yetApp(), WithFilename("custom.yaml"))
if r.Application().Name != "yet" {
t.Errorf("Application().Name = %q, want yet", r.Application().Name)
}
if r.Filename() != "custom.yaml" {
t.Errorf("Filename() = %q, want custom.yaml", r.Filename())
}
r2, err := For(yetApp())
if err != nil {
t.Fatalf("For: %v", err)
}
if r2.Filename() != "yet.yaml" {
t.Errorf("For(...).Filename() = %q, want yet.yaml", r2.Filename())
}
}
func TestWithEnvironmentProviderAndExpansionToggle(t *testing.T) {
root := t.TempDir()
writeFile(t, filepath.Join(root, "etc", "yet", "yet.yaml"), "path: ${HOME}/data\n")
env := paths.MapEnvironment{"HOME": "/home/test"}
r := mustResolver(t, yetApp(),
WithEnvironmentProvider(env),
WithPathsOptions(paths.WithPlatform("linux"), paths.WithRoot(root)),
WithWorkingDirectory(false),
)
var target struct {
Path string `yaml:"path"`
}
if err := r.LoadMerged(&target); err != nil {
t.Fatalf("LoadMerged: %v", err)
}
if want := "/home/test/data"; target.Path != want {
t.Errorf("Path = %q, want %q", target.Path, want)
}
r2 := mustResolver(t, yetApp(),
WithEnvironmentProvider(env),
WithPathsOptions(paths.WithPlatform("linux"), paths.WithRoot(root)),
WithWorkingDirectory(false),
WithEnvExpansion(false),
)
var target2 struct {
Path string `yaml:"path"`
}
if err := r2.LoadMerged(&target2); err != nil {
t.Fatalf("LoadMerged: %v", err)
}
if want := "${HOME}/data"; target2.Path != want {
t.Errorf("Path = %q, want %q (expansion disabled)", target2.Path, want)
}
}
func TestReadLayerMissingFileIsNotAnError(t *testing.T) {
m, err := readLayer("/does/not/exist/yet.yaml")
if err != nil {
t.Fatalf("readLayer() error = %v, want nil", err)
}
if len(m) != 0 {
t.Errorf("readLayer() = %v, want empty map", m)
}
}
func TestReadLayerInvalidYAML(t *testing.T) {
root := t.TempDir()
path := filepath.Join(root, "bad.yaml")
writeFile(t, path, "not: valid: yaml: [")
if _, err := readLayer(path); err == nil {
t.Fatal("readLayer() error = nil, want a parse error")
}
}
+99
View File
@@ -0,0 +1,99 @@
package config
import (
"strings"
"yetano.dev/yetano/core/paths"
)
// expandTree walks a value produced by yaml.Unmarshal into interface{}
// (maps, slices, scalars) and expands ${VAR}/$VAR references in every
// string value it finds. Map keys and non-string scalars are left
// untouched (spec section 30: "no expansion of YAML keys", "expansion
// only in string values").
func expandTree(v any, env paths.Environment) any {
switch t := v.(type) {
case string:
return expandString(t, env)
case map[string]any:
out := make(map[string]any, len(t))
for k, val := range t {
out[k] = expandTree(val, env)
}
return out
case []any:
out := make([]any, len(t))
for i, val := range t {
out[i] = expandTree(val, env)
}
return out
default:
return v
}
}
func isNameStart(c byte) bool {
return c == '_' || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
}
func isNameChar(c byte) bool {
return isNameStart(c) || (c >= '0' && c <= '9')
}
// expandString performs plain ${VAR} and $VAR substitution -- never a
// shell: there is no $(...), no backticks, no command execution of any
// kind, because this scanner simply has no grammar for them (spec
// section 30). A variable that is not set in env is left literally
// unexpanded (e.g. "${MISSING}" stays in the result) rather than
// silently becoming an empty string, so a typo is visible in the
// resolved configuration instead of turning into a wrong-but-valid
// path. A variable that *is* set, even to "", expands to its value --
// this is how "unset" and "set but empty" are told apart (spec section
// 30).
func expandString(s string, env paths.Environment) string {
if !strings.Contains(s, "$") {
return s
}
var b strings.Builder
for i := 0; i < len(s); {
c := s[i]
if c != '$' || i+1 >= len(s) {
b.WriteByte(c)
i++
continue
}
if s[i+1] == '{' {
end := strings.IndexByte(s[i+2:], '}')
if end < 0 {
b.WriteByte(c)
i++
continue
}
name := s[i+2 : i+2+end]
if val, ok := env.Lookup(name); ok {
b.WriteString(val)
} else {
b.WriteString(s[i : i+2+end+1])
}
i += 2 + end + 1
continue
}
if isNameStart(s[i+1]) {
j := i + 1
for j < len(s) && isNameChar(s[j]) {
j++
}
name := s[i+1 : j]
if val, ok := env.Lookup(name); ok {
b.WriteString(val)
} else {
b.WriteString(s[i:j])
}
i = j
continue
}
b.WriteByte(c)
i++
}
return b.String()
}
+78
View File
@@ -0,0 +1,78 @@
package config
import (
"testing"
"yetano.dev/yetano/core/paths"
)
func TestExpandStringBraceForm(t *testing.T) {
env := paths.MapEnvironment{"HOME": "/home/test"}
if got, want := expandString("${HOME}/data", env), "/home/test/data"; got != want {
t.Errorf("expandString() = %q, want %q", got, want)
}
}
func TestExpandStringBareForm(t *testing.T) {
env := paths.MapEnvironment{"HOME": "/home/test"}
if got, want := expandString("$HOME/data", env), "/home/test/data"; got != want {
t.Errorf("expandString() = %q, want %q", got, want)
}
}
func TestExpandStringUnknownVariableLeftUnexpanded(t *testing.T) {
env := paths.MapEnvironment{"HOME": "/home/test"}
if got, want := expandString("${MISSING}/data", env), "${MISSING}/data"; got != want {
t.Errorf("expandString() = %q, want %q (unset var left literal)", got, want)
}
}
func TestExpandStringSetButEmptyExpandsToEmpty(t *testing.T) {
env := paths.MapEnvironment{"EMPTY": ""}
if got, want := expandString("[${EMPTY}]", env), "[]"; got != want {
t.Errorf("expandString() = %q, want %q (set-but-empty expands to empty string)", got, want)
}
}
func TestExpandStringNoCommandSubstitution(t *testing.T) {
env := paths.MapEnvironment{}
input := "$(rm -rf /) `echo hi` plain text"
if got := expandString(input, env); got != input {
t.Errorf("expandString() = %q, want unchanged %q (no shell eval)", got, input)
}
}
func TestExpandStringWindowsPathValue(t *testing.T) {
env := paths.MapEnvironment{"LOCALAPPDATA": `C:\Users\test\AppData\Local`}
got := expandString(`${LOCALAPPDATA}\yet\objects`, env)
if want := `C:\Users\test\AppData\Local\yet\objects`; got != want {
t.Errorf("expandString() = %q, want %q", got, want)
}
}
func TestExpandTreeOnlyExpandsStringValues(t *testing.T) {
env := paths.MapEnvironment{"HOME": "/home/test"}
tree := map[string]any{
"path": "${HOME}/data",
"count": 5,
"list": []any{"${HOME}/a", 1, true},
"nested": map[string]any{
"path": "${HOME}/b",
},
}
got := expandTree(tree, env).(map[string]any)
if got["path"] != "/home/test/data" {
t.Errorf("path = %v, want /home/test/data", got["path"])
}
if got["count"] != 5 {
t.Errorf("count = %v, want 5 (non-string scalar untouched)", got["count"])
}
list := got["list"].([]any)
if list[0] != "/home/test/a" || list[1] != 1 || list[2] != true {
t.Errorf("list = %v, want [/home/test/a 1 true]", list)
}
nested := got["nested"].(map[string]any)
if nested["path"] != "/home/test/b" {
t.Errorf("nested.path = %v, want /home/test/b", nested["path"])
}
}
+74
View File
@@ -0,0 +1,74 @@
package config
import (
"fmt"
"strings"
"yetano.dev/yetano/core"
"yetano.dev/yetano/core/paths"
)
// Explanation is the full, structured report for a doctor-style command
// (spec sections 42/44/45): every configuration layer this Resolver
// considered, plus the paths.Explanation for everything else (Data,
// State, Cache, Runtime, Log, Bin). Building it never mutates the
// filesystem.
type Explanation struct {
Application core.Application
Filename string
Layers []Layer
Selected string // "", if no layer's file exists
Paths paths.Explanation
}
// Explain resolves every configuration layer and every core/paths
// category and returns a combined, structured report.
func (r *Resolver) Explain() (Explanation, error) {
layers, err := r.layers()
if err != nil {
return Explanation{}, err
}
pathsExplanation, err := r.paths.Explain()
if err != nil {
return Explanation{}, err
}
ex := Explanation{
Application: r.app,
Filename: r.filename,
Layers: layers,
Paths: pathsExplanation,
}
for _, l := range layers {
if l.Selected {
ex.Selected = l.Path
}
}
return ex, nil
}
// String renders a human-readable report similar to spec section 44.
func (e Explanation) String() string {
var b strings.Builder
fmt.Fprintf(&b, "Application: %s\n", e.Application.Name)
fmt.Fprintf(&b, "Kind: %s\n", e.Application.Kind)
fmt.Fprintf(&b, "Scope: %s\n\n", e.Application.Scope)
b.WriteString("Configuration layers:\n")
for _, l := range e.Layers {
found := "no"
if l.Exists {
found = "yes"
}
fmt.Fprintf(&b, " %s\n priority: %d\n source: %s\n found: %s\n", l.Path, l.Priority, l.Source, found)
}
b.WriteString("\n")
if e.Selected != "" {
fmt.Fprintf(&b, "Selected:\n %s\n\n", e.Selected)
} else {
b.WriteString("Selected:\n (none found)\n\n")
}
b.WriteString(e.Paths.String())
return b.String()
}
+39
View File
@@ -0,0 +1,39 @@
package config
import (
"path/filepath"
"strings"
"testing"
"yetano.dev/yetano/core/paths"
)
func TestConfigExplain(t *testing.T) {
root := t.TempDir()
writeFile(t, filepath.Join(root, "home", "test", ".config", "yet", "yet.yaml"), "port: 8080\n")
env := map[string]string{"HOME": "/home/test"}
r := mustResolver(t, yetApp(),
WithEnvironment(env),
WithPathsOptions(paths.WithPlatform("linux"), paths.WithRoot(root)),
WithWorkdirPath(filepath.Join(root, "workdir")),
)
ex, err := r.Explain()
if err != nil {
t.Fatalf("Explain: %v", err)
}
if ex.Selected == "" {
t.Fatal("Explain().Selected is empty, want the existing user layer")
}
if want := filepath.Join(root, "home", "test", ".config", "yet", "yet.yaml"); ex.Selected != want {
t.Errorf("Explain().Selected = %q, want %q", ex.Selected, want)
}
if len(ex.Paths.Paths) == 0 {
t.Error("Explain().Paths.Paths is empty, want core/paths categories included")
}
text := ex.String()
if !strings.Contains(text, "Configuration layers:") || !strings.Contains(text, "Selected:") {
t.Errorf("Explain().String() missing expected sections:\n%s", text)
}
}
+111
View File
@@ -0,0 +1,111 @@
package config
import (
"os"
"yetano.dev/yetano/core"
"yetano.dev/yetano/core/paths"
)
// Layer is one location in the configuration search/merge hierarchy
// (spec section 48). Search order is descending Priority (first match
// wins); LoadMerged walks the exact same list in reverse (lowest
// priority first, so a higher-priority layer overlays it).
type Layer struct {
Path string
Source paths.Source
Priority int
Exists bool
Selected bool
}
// PriorityYetanoDefaults is lower than any layer core/paths itself
// resolves (see paths.PrioritySystem), so the shared Yetano config
// directory (spec section 4, opt-in via WithYetanoDefaults) is always
// the last fallback.
const PriorityYetanoDefaults = 0
func statExists(path string) bool {
_, err := os.Stat(path)
return err == nil
}
// layers builds the full, ordered layer list (spec sections 21/22): the
// working directory (if enabled), then core/paths's own ConfigSearchDirs
// for this application (optionally dropping the system-tier layer), then
// -- opt-in only -- the shared Yetano defaults directory.
func (r *Resolver) layers() ([]Layer, error) {
var out []Layer
if r.workdir {
out = append(out, Layer{
Path: paths.JoinFamily(r.paths.Platform(), r.workdirPath, r.filename),
Source: paths.WorkingDirectory,
Priority: paths.PriorityWorkingDirectory,
})
}
dirs, err := r.paths.ConfigSearchDirs()
if err != nil {
return nil, err
}
for _, d := range dirs {
if !r.systemConfig && d.Priority <= paths.PrioritySystem {
continue
}
out = append(out, Layer{
Path: paths.JoinDirFile(d.Path, r.filename),
Source: d.Source,
Priority: d.Priority,
})
}
if r.yetanoDefaults {
layer, err := r.yetanoDefaultsLayer()
if err != nil {
return nil, err
}
out = append(out, layer)
}
for i := range out {
out[i].Exists = statExists(out[i].Path)
}
selected := false
for i := range out {
if out[i].Exists && !selected {
out[i].Selected = true
selected = true
}
}
return out, nil
}
// yetanoDefaultsLayer resolves the ecosystem-wide shared configuration
// directory (spec section 4: "~/.config/yetano/", or the platform
// equivalent) as its own pseudo-Application named "yetano" -- always
// CLI-shaped (XDG-flavored on every OS), since it is a shared,
// admin/CLI-facing location, not tied to any one application's Kind.
func (r *Resolver) yetanoDefaultsLayer() (Layer, error) {
yetanoApp := core.Application{Name: "yetano", Kind: core.CLI, Scope: r.app.Scope}
yp, err := paths.New(yetanoApp, append([]paths.Option{paths.WithEnvironmentProvider(r.env)}, r.pathsOpts...)...)
if err != nil {
return Layer{}, err
}
ex, err := yp.Explain()
if err != nil {
return Layer{}, err
}
var dir string
var source paths.Source
for _, p := range ex.Paths {
if p.Kind == paths.ConfigPath {
dir, source = p.Path, p.Source
}
}
return Layer{
Path: paths.JoinDirFile(dir, r.filename),
Source: source,
Priority: PriorityYetanoDefaults,
}, nil
}
+101
View File
@@ -0,0 +1,101 @@
package config
import (
"fmt"
"os"
"gopkg.in/yaml.v3"
)
// mergeMaps overlays over onto base in place and returns base (spec
// section 28's V1 merge semantics):
//
// - scalars: the higher-priority layer's value replaces the lower one.
// - maps: merged recursively, key by key.
// - lists: replaced wholesale by the higher-priority layer's list --
// never concatenated element-by-element.
// - explicit YAML null: removes the key from the merged result (a
// layer can use "key: null" to intentionally unset a lower layer's
// value), rather than being stored as a literal nil.
//
// over is expected to be the *higher-priority* layer; base accumulates
// lower-priority layers applied first, per LoadMerged's lowest-to-
// highest iteration order.
func mergeMaps(base, over map[string]any) map[string]any {
if base == nil {
base = map[string]any{}
}
for k, v := range over {
if v == nil {
delete(base, k)
continue
}
if overMap, ok := v.(map[string]any); ok {
if baseMap, ok := base[k].(map[string]any); ok {
base[k] = mergeMaps(baseMap, overMap)
continue
}
}
base[k] = v
}
return base
}
// readLayer reads and parses path as a YAML mapping, returning an empty
// map (not an error) if the file does not exist -- callers already know
// which layers exist via Layer.Exists; this is a convenience for callers
// that don't check first.
func readLayer(path string) (map[string]any, error) {
data, err := os.ReadFile(path)
if os.IsNotExist(err) {
return map[string]any{}, nil
}
if err != nil {
return nil, fmt.Errorf("config: read %s: %w", path, err)
}
var m map[string]any
if err := yaml.Unmarshal(data, &m); err != nil {
return nil, fmt.Errorf("config: parse %s: %w", path, err)
}
if m == nil {
m = map[string]any{}
}
return m, nil
}
// LoadMerged loads every existing layer, lowest priority first, merging
// each one on top of the last (spec sections 27/28), optionally
// expanding ${VAR}/$VAR in string values (WithEnvExpansion, default
// on), and unmarshals the merged result into target (a pointer, as for
// yaml.Unmarshal).
func (r *Resolver) LoadMerged(target any) error {
all, err := r.layers()
if err != nil {
return err
}
merged := map[string]any{}
for i := len(all) - 1; i >= 0; i-- {
l := all[i]
if !l.Exists {
continue
}
m, err := readLayer(l.Path)
if err != nil {
return err
}
if r.envExpansion {
m = expandTree(m, r.env).(map[string]any)
}
merged = mergeMaps(merged, m)
}
data, err := yaml.Marshal(merged)
if err != nil {
return fmt.Errorf("config: re-marshal merged result: %w", err)
}
if err := yaml.Unmarshal(data, target); err != nil {
return fmt.Errorf("config: unmarshal merged result: %w", err)
}
return nil
}
+97
View File
@@ -0,0 +1,97 @@
package config
import (
"path/filepath"
"testing"
"yetano.dev/yetano/core/paths"
)
func TestMergeScalarOverride(t *testing.T) {
base := map[string]any{"port": 8080}
over := map[string]any{"port": 9090}
got := mergeMaps(base, over)
if got["port"] != 9090 {
t.Errorf("port = %v, want 9090", got["port"])
}
}
func TestMergeNestedMap(t *testing.T) {
base := map[string]any{
"http": map[string]any{"host": "0.0.0.0", "port": 8080, "tls": false},
}
over := map[string]any{
"http": map[string]any{"port": 9090},
}
got := mergeMaps(base, over)
httpMap := got["http"].(map[string]any)
if httpMap["host"] != "0.0.0.0" {
t.Errorf("host = %v, want 0.0.0.0 (should survive from base)", httpMap["host"])
}
if httpMap["port"] != 9090 {
t.Errorf("port = %v, want 9090", httpMap["port"])
}
if httpMap["tls"] != false {
t.Errorf("tls = %v, want false (should survive from base)", httpMap["tls"])
}
}
func TestMergeListReplacesWhollyNoConcatenation(t *testing.T) {
base := map[string]any{"registries": []any{"a", "b"}}
over := map[string]any{"registries": []any{"c"}}
got := mergeMaps(base, over)
list := got["registries"].([]any)
if len(list) != 1 || list[0] != "c" {
t.Errorf("registries = %v, want [c] (full replace, no concatenation)", list)
}
}
func TestMergeNullRemovesKey(t *testing.T) {
base := map[string]any{"ca_cert": "/etc/ssl/ca.pem", "port": 8080}
over := map[string]any{"ca_cert": nil}
got := mergeMaps(base, over)
if _, exists := got["ca_cert"]; exists {
t.Errorf("ca_cert = %v, want key removed entirely", got["ca_cert"])
}
if got["port"] != 8080 {
t.Errorf("port = %v, want 8080 (untouched)", got["port"])
}
}
func TestLoadMergedEndToEnd(t *testing.T) {
root := t.TempDir()
writeFile(t, filepath.Join(root, "etc", "yet", "yet.yaml"), "http:\n host: 0.0.0.0\n port: 8080\n tls: false\nregistries:\n - a\n - b\n")
writeFile(t, filepath.Join(root, "home", "test", ".config", "yet", "yet.yaml"), "http:\n port: 9090\nregistries:\n - c\n")
env := map[string]string{"HOME": "/home/test"}
r := mustResolver(t, yetApp(),
WithEnvironment(env),
WithPathsOptions(paths.WithPlatform("linux"), paths.WithRoot(root)),
WithWorkingDirectory(false),
)
type httpConfig struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
TLS bool `yaml:"tls"`
}
var target struct {
HTTP httpConfig `yaml:"http"`
Registries []string `yaml:"registries"`
}
if err := r.LoadMerged(&target); err != nil {
t.Fatalf("LoadMerged: %v", err)
}
if target.HTTP.Host != "0.0.0.0" {
t.Errorf("HTTP.Host = %q, want 0.0.0.0", target.HTTP.Host)
}
if target.HTTP.Port != 9090 {
t.Errorf("HTTP.Port = %d, want 9090", target.HTTP.Port)
}
if target.HTTP.TLS != false {
t.Errorf("HTTP.TLS = %v, want false", target.HTTP.TLS)
}
if len(target.Registries) != 1 || target.Registries[0] != "c" {
t.Errorf("Registries = %v, want [c]", target.Registries)
}
}
+25
View File
@@ -0,0 +1,25 @@
package config
// Resolve returns the highest-priority existing configuration file
// (spec section 25). found is false if no layer's file exists -- this is
// not an error; callers decide whether "no configuration file" is fine.
func (r *Resolver) Resolve() (layer Layer, found bool, err error) {
all, err := r.layers()
if err != nil {
return Layer{}, false, err
}
for _, l := range all {
if l.Exists {
return l, true, nil
}
}
return Layer{}, false, nil
}
// ResolveAll returns every layer in the priority hierarchy, highest
// priority first, whether or not the file exists there (spec section
// 26) -- e.g. for a `doctor`-style report of every location that was
// considered.
func (r *Resolver) ResolveAll() ([]Layer, error) {
return r.layers()
}
+193
View File
@@ -0,0 +1,193 @@
package config
import (
"os"
"path/filepath"
"testing"
"yetano.dev/yetano/core"
"yetano.dev/yetano/core/paths"
)
func yetApp() core.Application {
return core.Application{Name: "yet", Kind: core.CLI}
}
func mustResolver(t *testing.T, app core.Application, opts ...Option) *Resolver {
t.Helper()
r, err := New(app, opts...)
if err != nil {
t.Fatalf("New: %v", err)
}
return r
}
func writeFile(t *testing.T, path, content string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
func TestLinuxLayerOrder(t *testing.T) {
root := t.TempDir()
env := map[string]string{"HOME": "/home/test"}
r := mustResolver(t, yetApp(),
WithEnvironment(env),
WithPathsOptions(paths.WithPlatform("linux"), paths.WithRoot(root)),
WithWorkdirPath(filepath.Join(root, "workdir")),
)
layers, err := r.ResolveAll()
if err != nil {
t.Fatalf("ResolveAll: %v", err)
}
want := []string{
filepath.Join(root, "workdir", "yet.yaml"),
filepath.Join(root, "home", "test", ".config", "yet", "yet.yaml"),
filepath.Join(root, "etc", "yet", "yet.yaml"),
}
if len(layers) != len(want) {
t.Fatalf("ResolveAll() = %v, want %v", layers, want)
}
for i, w := range want {
if layers[i].Path != w {
t.Errorf("layers[%d].Path = %q, want %q", i, layers[i].Path, w)
}
}
}
func TestWorkdirDisabled(t *testing.T) {
root := t.TempDir()
writeFile(t, filepath.Join(root, "workdir", "yet.yaml"), "ignored: true\n")
env := map[string]string{"HOME": "/home/test"}
r := mustResolver(t, yetApp(),
WithEnvironment(env),
WithPathsOptions(paths.WithPlatform("linux"), paths.WithRoot(root)),
WithWorkdirPath(filepath.Join(root, "workdir")),
WithWorkingDirectory(false),
)
layers, err := r.ResolveAll()
if err != nil {
t.Fatalf("ResolveAll: %v", err)
}
for _, l := range layers {
if l.Source == paths.WorkingDirectory {
t.Fatalf("ResolveAll() included a working-directory layer despite WithWorkingDirectory(false): %v", layers)
}
}
}
func TestSystemConfigDisabled(t *testing.T) {
root := t.TempDir()
env := map[string]string{"HOME": "/home/test"}
r := mustResolver(t, yetApp(),
WithEnvironment(env),
WithPathsOptions(paths.WithPlatform("linux"), paths.WithRoot(root)),
WithSystemConfig(false),
)
layers, err := r.ResolveAll()
if err != nil {
t.Fatalf("ResolveAll: %v", err)
}
for _, l := range layers {
if l.Priority <= paths.PrioritySystem {
t.Errorf("ResolveAll() included a system layer despite WithSystemConfig(false): %v", layers)
}
}
}
func TestResolveFirstMatch(t *testing.T) {
root := t.TempDir()
writeFile(t, filepath.Join(root, "etc", "yet", "yet.yaml"), "layer: system\n")
env := map[string]string{"HOME": "/home/test"}
r := mustResolver(t, yetApp(),
WithEnvironment(env),
WithPathsOptions(paths.WithPlatform("linux"), paths.WithRoot(root)),
WithWorkdirPath(filepath.Join(root, "workdir")),
)
layer, found, err := r.Resolve()
if err != nil {
t.Fatalf("Resolve: %v", err)
}
if !found {
t.Fatal("Resolve() found = false, want true")
}
if want := filepath.Join(root, "etc", "yet", "yet.yaml"); layer.Path != want {
t.Errorf("Resolve().Path = %q, want %q", layer.Path, want)
}
writeFile(t, filepath.Join(root, "home", "test", ".config", "yet", "yet.yaml"), "layer: user\n")
layer, found, err = r.Resolve()
if err != nil {
t.Fatalf("Resolve: %v", err)
}
if !found {
t.Fatal("Resolve() found = false, want true")
}
if want := filepath.Join(root, "home", "test", ".config", "yet", "yet.yaml"); layer.Path != want {
t.Errorf("Resolve().Path = %q, want %q (user should now win over system)", layer.Path, want)
}
}
func TestResolveNotFoundIsNotAnError(t *testing.T) {
root := t.TempDir()
env := map[string]string{"HOME": "/home/test"}
r := mustResolver(t, yetApp(),
WithEnvironment(env),
WithPathsOptions(paths.WithPlatform("linux"), paths.WithRoot(root)),
WithWorkdirPath(filepath.Join(root, "workdir")),
)
_, found, err := r.Resolve()
if err != nil {
t.Fatalf("Resolve() error = %v, want nil", err)
}
if found {
t.Fatalf("Resolve() found = true, want false")
}
}
func TestYetanoDefaultsFallbackLayer(t *testing.T) {
root := t.TempDir()
env := map[string]string{"HOME": "/home/test"}
r := mustResolver(t, yetApp(),
WithEnvironment(env),
WithPathsOptions(paths.WithPlatform("linux"), paths.WithRoot(root)),
WithWorkdirPath(filepath.Join(root, "workdir")),
WithYetanoDefaults(true),
)
layers, err := r.ResolveAll()
if err != nil {
t.Fatalf("ResolveAll: %v", err)
}
last := layers[len(layers)-1]
if want := filepath.Join(root, "home", "test", ".config", "yetano", "yet.yaml"); last.Path != want {
t.Errorf("last layer = %q, want %q", last.Path, want)
}
if last.Priority != PriorityYetanoDefaults {
t.Errorf("last layer priority = %d, want %d", last.Priority, PriorityYetanoDefaults)
}
}
func TestWithFilename(t *testing.T) {
root := t.TempDir()
env := map[string]string{"HOME": "/home/test"}
r := mustResolver(t, yetApp(),
WithEnvironment(env),
WithPathsOptions(paths.WithPlatform("linux"), paths.WithRoot(root)),
WithFilename("repositories.yaml"),
WithWorkingDirectory(false),
)
layers, err := r.ResolveAll()
if err != nil {
t.Fatalf("ResolveAll: %v", err)
}
if want := filepath.Join(root, "home", "test", ".config", "yet", "repositories.yaml"); layers[0].Path != want {
t.Errorf("layers[0].Path = %q, want %q", layers[0].Path, want)
}
}
+78
View File
@@ -0,0 +1,78 @@
package config
import (
"testing"
"yetano.dev/yetano/core/paths"
)
func windowsEnv() map[string]string {
return map[string]string{
"PROGRAMDATA": `C:\ProgramData`,
"APPDATA": `C:\Users\test\AppData\Roaming`,
"LOCALAPPDATA": `C:\Users\test\AppData\Local`,
"USERPROFILE": `C:\Users\test`,
}
}
func TestWindowsSearchOrder(t *testing.T) {
r := mustResolver(t, yetApp(),
WithEnvironment(windowsEnv()),
WithPathsOptions(paths.WithPlatform("windows")),
WithWorkdirPath(`C:\work\project`),
)
layers, err := r.ResolveAll()
if err != nil {
t.Fatalf("ResolveAll: %v", err)
}
want := []string{
`C:\work\project\yet.yaml`,
`C:\Users\test\AppData\Local\yet\yet.yaml`,
`C:\Users\test\AppData\Roaming\yet\yet.yaml`,
`C:\ProgramData\yet\yet.yaml`,
}
if len(layers) != len(want) {
t.Fatalf("ResolveAll() = %v, want %v", layers, want)
}
for i, w := range want {
if layers[i].Path != w {
t.Errorf("layers[%d].Path = %q, want %q", i, layers[i].Path, w)
}
}
}
func TestWindowsMergeOrderIsSearchOrderReversed(t *testing.T) {
r := mustResolver(t, yetApp(),
WithEnvironment(windowsEnv()),
WithPathsOptions(paths.WithPlatform("windows")),
WithWorkdirPath(`C:\work\project`),
)
layers, err := r.ResolveAll()
if err != nil {
t.Fatalf("ResolveAll: %v", err)
}
for i := 0; i < len(layers)-1; i++ {
if layers[i].Priority < layers[i+1].Priority {
t.Fatalf("ResolveAll() not in descending priority order: %v", layers)
}
}
}
func TestWindowsPathSeparatorsNeverForwardSlash(t *testing.T) {
r := mustResolver(t, yetApp(),
WithEnvironment(windowsEnv()),
WithPathsOptions(paths.WithPlatform("windows")),
WithWorkdirPath(`C:\work\project`),
)
layers, err := r.ResolveAll()
if err != nil {
t.Fatalf("ResolveAll: %v", err)
}
for _, l := range layers {
for _, c := range l.Path {
if c == '/' {
t.Errorf("layer path %q contains a forward slash", l.Path)
}
}
}
}