diff --git a/cmd/archie-gateway/main.go b/cmd/archie-gateway/main.go index e9c8c9989..d0a94f303 100644 --- a/cmd/archie-gateway/main.go +++ b/cmd/archie-gateway/main.go @@ -7,22 +7,17 @@ import ( "fmt" "os" "os/signal" - "path/filepath" "syscall" "github.com/samcharles93/archie-core/internal/app/archied" + "github.com/samcharles93/archie-core/internal/infrastructure/configuration" ) func main() { os.Exit(run()) } func run() int { - base, err := os.UserConfigDir() - if err != nil { - fmt.Fprintln(os.Stderr, err) - return 1 - } var options archied.GatewayOptions - flag.StringVar(&options.Config, "config", filepath.Join(base, "archie", "config.toml"), "configuration file or directory") + flag.StringVar(&options.Config, "config", configuration.DefaultConfigPath(), "configuration file or directory") flag.StringVar(&options.Overlay, "config-overlay", "", "configuration overlay file or directory") flag.StringVar(&options.Listen, "listen", "", "gateway gRPC listen address (defaults to [services.gateway].listen, else 127.0.0.1:8585)") flag.StringVar(&options.Token, "token", "", "Bearer [REDACTED] required for a non-loopback listener (defaults to [services.gateway].target_token)") diff --git a/cmd/archie-messaging/main.go b/cmd/archie-messaging/main.go index 32ee215e4..57c36fa56 100644 --- a/cmd/archie-messaging/main.go +++ b/cmd/archie-messaging/main.go @@ -8,22 +8,17 @@ import ( "fmt" "os" "os/signal" - "path/filepath" "syscall" "github.com/samcharles93/archie-core/internal/app/archiemessaging" + "github.com/samcharles93/archie-core/internal/infrastructure/configuration" ) func main() { os.Exit(run()) } func run() int { - base, err := os.UserConfigDir() - if err != nil { - fmt.Fprintln(os.Stderr, err) - return 1 - } var options archiemessaging.Options - flag.StringVar(&options.Config, "config", filepath.Join(base, "archie", "config.toml"), "configuration file or directory") + flag.StringVar(&options.Config, "config", configuration.DefaultConfigPath(), "configuration file or directory") flag.StringVar(&options.Overlay, "config-overlay", "", "configuration overlay file or directory") flag.StringVar(&options.Gateway.Target, "gateway-target", "", "archie-gateway gRPC address (defaults to [services.gateway].target, else 127.0.0.1:8585)") flag.StringVar(&options.Gateway.Token, "gateway-token", "", "bearer token presented to archie-gateway") diff --git a/cmd/archie-state-store/main.go b/cmd/archie-state-store/main.go index 6ca5ba8a5..be0b23077 100644 --- a/cmd/archie-state-store/main.go +++ b/cmd/archie-state-store/main.go @@ -14,11 +14,11 @@ import ( "fmt" "os" "os/signal" - "path/filepath" "strings" "syscall" "github.com/samcharles93/archie-core/internal/app/archied" + "github.com/samcharles93/archie-core/internal/infrastructure/configuration" ) func main() { os.Exit(run()) } @@ -31,13 +31,8 @@ func run() int { if args := os.Args[1:]; len(args) > 0 && !strings.HasPrefix(args[0], "-") { return runRecovery(args, os.Stdout, os.Stderr) } - base, err := os.UserConfigDir() - if err != nil { - fmt.Fprintln(os.Stderr, err) - return 1 - } var options archied.StateStoreOptions - flag.StringVar(&options.Config, "config", filepath.Join(base, "archie", "config.toml"), "configuration file or directory") + flag.StringVar(&options.Config, "config", configuration.DefaultConfigPath(), "configuration file or directory") flag.StringVar(&options.Overlay, "config-overlay", "", "configuration overlay file or directory") flag.StringVar(&options.Listen, "listen", "", "state store gRPC listen address (defaults to [services.state].listen, else 127.0.0.1:9090)") flag.StringVar(&options.Token, "token", "", "bearer token required for a non-loopback listener (defaults to [services.state].target_token)") diff --git a/cmd/archie-state-store/recovery.go b/cmd/archie-state-store/recovery.go index 259410236..4d115a338 100644 --- a/cmd/archie-state-store/recovery.go +++ b/cmd/archie-state-store/recovery.go @@ -8,15 +8,9 @@ import ( "io" "github.com/samcharles93/archie-core/internal/app/archied" + "github.com/samcharles93/archie-core/internal/infrastructure/configuration" ) -// defaultConfigPath is the configuration the serve path reads by default, and -// the one the daemon boots with. It is the daemon's own rule rather than a -// second derivation of it: os.UserConfigDir (what the sibling processes use) -// disagrees with archied on darwin and rejects a relative XDG_CONFIG_HOME -// outright, which would leave validate answering about a file nobody boots. -func defaultConfigPath() string { return archied.DefaultConfigPath() } - // recoveryUsage is the whole flag surface of the offline recovery commands. // They are subcommands of this binary rather than a recovery binary of their // own: offline database maintenance belongs to the process that owns the file @@ -68,7 +62,7 @@ func runRecovery(args []string, stdout, stderr io.Writer) int { // Only validate asks a question about the process rather than the file, so // only validate takes the configuration the process would boot with. if command == archied.RecoveryValidate { - flags.StringVar(&options.Config, "config", defaultConfigPath(), "configuration file or directory the daemon boots with") + flags.StringVar(&options.Config, "config", configuration.DefaultConfigPath(), "configuration file or directory the daemon boots with") flags.StringVar(&options.Overlay, "config-overlay", "", "configuration overlay file or directory") } if err := flags.Parse(args[1:]); err != nil { diff --git a/cmd/archie-state-store/recovery_test.go b/cmd/archie-state-store/recovery_test.go index 0f0359b31..0ab53025c 100644 --- a/cmd/archie-state-store/recovery_test.go +++ b/cmd/archie-state-store/recovery_test.go @@ -388,24 +388,55 @@ func TestRecoveryValidateLeavesTheDaemonLogAlone(t *testing.T) { } // validate's verdict is the daemon's verdict only if it reads the configuration -// the daemon reads. archied resolves that default from its own configHome, which -// honours a relative XDG_CONFIG_HOME; os.UserConfigDir rejects a relative one -// outright, which left the command with no config and no verdict at all. -func TestRecoveryDefaultConfigFollowsTheDaemonsConfigHome(t *testing.T) { - relative := filepath.Join("relative", "config") - t.Setenv("XDG_CONFIG_HOME", relative) - if got, want := defaultConfigPath(), filepath.Join(relative, "archie", "config.toml"); got != want { - t.Errorf("defaultConfigPath() with a relative XDG_CONFIG_HOME = %q, want %q", got, want) +// the daemon reads, and with no -config it reads whatever the one shared +// helper resolves. The resolution rule itself is pinned where it lives +// (internal/infrastructure/configuration); what only this test can pin is that +// the command takes its default from that helper rather than deriving it. +// +// A relative XDG_CONFIG_HOME is the case that separates the two: the command +// has to resolve ${XDG_CONFIG_HOME}/archie/config.toml relative to its working +// directory, and a second derivation through os.UserConfigDir rejects a +// relative value outright, leaving the command with no config to answer about. +func TestRecoveryDefaultConfigResolvesWhereTheDaemonReads(t *testing.T) { + // The second layout is the teeth: the command has to read the config at the + // resolved path, not merely find some config somewhere under the config home. + // A resolution that drifts finds nothing and validate has no verdict. + tests := []struct { + name string + configDir string // relative to $XDG_CONFIG_HOME + wantOK bool + }{ + {name: "$XDG_CONFIG_HOME/archie/config.toml", configDir: "archie", wantOK: true}, + {name: "a config elsewhere in the config home is not the default", configDir: "wrong-place"}, } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + root := t.TempDir() + t.Chdir(root) + t.Setenv("XDG_CONFIG_HOME", "xdg") - absolute := t.TempDir() - t.Setenv("XDG_CONFIG_HOME", absolute) - if got, want := defaultConfigPath(), filepath.Join(absolute, "archie", "config.toml"); got != want { - t.Errorf("defaultConfigPath() = %q, want %q", got, want) - } - // The equality itself: one helper, so the two cannot drift apart again. - if got, want := defaultConfigPath(), archied.DefaultConfigPath(); got != want { - t.Errorf("defaultConfigPath() = %q, but the daemon resolves %q", got, want) + configDir := filepath.Join(root, "xdg", tc.configDir) + if err := os.MkdirAll(configDir, 0o700); err != nil { + t.Fatalf("create %s: %v", configDir, err) + } + configPath := writeMinimalConfig(t, configDir) + db := filepath.Join(root, "archie.db-tasks.sqlite") + seedStoreResources(t, openTaskStore(t, db), configPath) + + code, stdout, stderr := runRecoveryCmd(t, "validate", "-db", db) + if !tc.wantOK { + if code == 0 { + t.Fatalf("validate exited 0 with no config at the resolved path %s: %s", configPath, stdout) + } + return + } + if code != 0 { + t.Fatalf("validate with no -config exited %d, so it did not read %s: %s", code, configPath, stderr) + } + if !strings.Contains(stdout, "stored resources validate") { + t.Errorf("validate reported %q, want the verdict on the store seeded from the resolved config", stdout) + } + }) } } diff --git a/cmd/archie-ui/main.go b/cmd/archie-ui/main.go index 9b6435845..0941d277d 100644 --- a/cmd/archie-ui/main.go +++ b/cmd/archie-ui/main.go @@ -13,23 +13,18 @@ import ( "fmt" "os" "os/signal" - "path/filepath" "strconv" "syscall" "github.com/samcharles93/archie-core/internal/app/archieui" + "github.com/samcharles93/archie-core/internal/infrastructure/configuration" ) func main() { os.Exit(run()) } func run() int { - base, err := os.UserConfigDir() - if err != nil { - fmt.Fprintln(os.Stderr, err) - return 1 - } var options archieui.Options - flag.StringVar(&options.Config, "config", filepath.Join(base, "archie", "config.toml"), "configuration file or directory (only [services.*] targets and [web] are read)") + flag.StringVar(&options.Config, "config", configuration.DefaultConfigPath(), "configuration file or directory (only [services.*] targets and [web] are read)") flag.StringVar(&options.Overlay, "config-overlay", "", "configuration overlay file or directory") flag.StringVar(&options.Listen, "listen", "", "dashboard HTTP listen address (defaults to [web].listen, else 127.0.0.1:8484)") flag.StringVar(&options.Token, "token", "", "dashboard token; required for a non-loopback listener") diff --git a/internal/app/archied/drain.go b/internal/app/archied/drain.go index ec283bf54..e3d4c92a7 100644 --- a/internal/app/archied/drain.go +++ b/internal/app/archied/drain.go @@ -8,6 +8,7 @@ import ( "time" "github.com/samcharles93/archie-core/internal/domain/drain" + "github.com/samcharles93/archie-core/internal/infrastructure/configuration" drainio "github.com/samcharles93/archie-core/internal/infrastructure/drain" ) @@ -17,14 +18,14 @@ import ( const defaultDrainPollInterval = 5 * time.Second // DefaultDrainRequestPath returns the marker file path the daemon watches. It -// lives under the repo's config home (${XDG_CONFIG_HOME:-~/.config}/archie) -- -// the established convention for archied's per-user paths -- rather than the +// lives under the config home (${XDG_CONFIG_HOME:-~/.config}/archie) -- the +// established convention for archied's per-user paths -- rather than the // epic's literal ~/.archie, which is not a path this daemon ever uses. The // discrepancy is intentional: every other archied path reads from the XDG // config home, so the drain marker must too, or an operator pointing at the // documented location would miss it. func DefaultDrainRequestPath() string { - return filepath.Join(configHome(), "archie", drainio.DefaultMarkerFilename) + return filepath.Join(configuration.DefaultConfigDir(), drainio.DefaultMarkerFilename) } // monitorDrainRequests polls check for a live drain request and invokes diff --git a/internal/app/archied/main.go b/internal/app/archied/main.go index 3ea12fbe2..a139feb5e 100644 --- a/internal/app/archied/main.go +++ b/internal/app/archied/main.go @@ -315,9 +315,8 @@ type runArgs struct { } func parseArgs() (runArgs, bool) { - defaultCfg := DefaultConfigPath() var args runArgs - flag.StringVar(&args.cfgPath, "config", defaultCfg, "path to a TOML/YAML config file or configuration directory") + flag.StringVar(&args.cfgPath, "config", configuration.DefaultConfigPath(), "path to a TOML/YAML config file or configuration directory") flag.StringVar(&args.overlayPath, "config-overlay", "", "path to a TOML/YAML overlay file or configuration directory applied on top of -config") flag.BoolVar(&args.once, "once", false, "run a single poll+process cycle and exit (systemd timer / testing)") flag.Int64Var(&args.requeue, "requeue", 0, "requeue a parked/waiting task by id (keeps its workflow), then exit unless -once is also set") @@ -910,23 +909,6 @@ func configuredNATSToken(cfg config.NATSConfig, getenv func(string) string) (str return token, nil } -func configHome() string { - if x := os.Getenv("XDG_CONFIG_HOME"); x != "" { - return x - } - home, _ := os.UserHomeDir() - return filepath.Join(home, ".config") -} - -// DefaultConfigPath is the configuration the daemon reads when -config is not -// given, and the one every command that asks a question about the daemon has to -// read to be answering about the same deployment: it is the daemon's rule, not -// a second one. It is exported for exactly that reason -- an offline command -// resolving the default any other way answers about a different config file -// (os.UserConfigDir, notably, rejects a relative XDG_CONFIG_HOME outright and -// leaves the caller with no path at all). -func DefaultConfigPath() string { return filepath.Join(configHome(), "archie", "config.toml") } - // updateReportPath is where the update watchdog leaves the phase-2 outcome // of an update for this identity to relay on its next launch. The identity is // hashed so multiple identities sharing one daemon (see diff --git a/internal/app/archied/setup.go b/internal/app/archied/setup.go index cffa8c6dd..78d111803 100644 --- a/internal/app/archied/setup.go +++ b/internal/app/archied/setup.go @@ -67,7 +67,7 @@ type setupFlags struct { func bindSetupFlags(fs *flag.FlagSet) *setupFlags { f := &setupFlags{} - fs.StringVar(&f.cfgPath, "config", filepath.Join(configHome(), "archie", "config.toml"), "path to write config.toml") + fs.StringVar(&f.cfgPath, "config", configuration.DefaultConfigPath(), "path to write config.toml") fs.BoolVar(&f.defaults, "defaults", false, "write a known-valid unattended baseline config without prompting") fs.StringVar(&f.botUser, "bot-user", "", "forge username for archied's commits and API calls") fs.StringVar(&f.operator, "operator", "", "operator display name (optional)") diff --git a/internal/infrastructure/configuration/configpath_test.go b/internal/infrastructure/configuration/configpath_test.go new file mode 100644 index 000000000..dd707ff6b --- /dev/null +++ b/internal/infrastructure/configuration/configpath_test.go @@ -0,0 +1,269 @@ +// This file fences the claim that every archie binary reads the same +// configuration file when the operator names none. The value is only +// observable by starting a process and reading which file it opened, but the +// failure being guarded against is a second derivation of that value, which is +// a shape in the source before it is a wrong path at runtime -- so the fence +// reads the source. +// +// Four binaries derived their default with os.UserConfigDir while the daemon +// resolved it from its own config home (archie-core-8i6l). The two agree on +// Linux with an absolute XDG_CONFIG_HOME and diverge everywhere else: darwin +// resolves os.UserConfigDir to ~/Library/Application Support, and a relative +// XDG_CONFIG_HOME is rejected outright rather than honoured. One deployment +// then boots from a different config file depending on which binary started it. + +package configuration + +import ( + "bytes" + "go/ast" + "go/parser" + "go/printer" + "go/token" + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "testing" +) + +const moduleImportPrefix = "github.com/samcharles93/archie-core/" + +// configPackageImportPath is this package as its importers name it, spelled +// out so a moved or renamed package fails this fence instead of matching +// nothing and passing. +const configPackageImportPath = moduleImportPrefix + "internal/infrastructure/configuration" + +// helperName is the single helper that resolves the default configuration path. +const helperName = "DefaultConfigPath" + +// configFlagDefault is one -config registration found by the fence: where it +// is, what it defaults to, and whether that default comes from the helper. +type configFlagDefault struct { + at token.Position + expr string + resolved bool +} + +// TestDefaultConfigPathFollowsTheConfigHome pins the precedence every archie +// binary shares: $XDG_CONFIG_HOME when it is set, ~/.config when it is not. +// +// The relative and unknowable-home cases are the ones a second derivation gets +// wrong, so they are the reason this table exists rather than a single +// assertion: os.UserConfigDir rejects a relative $XDG_CONFIG_HOME with an error +// rather than resolving it, and answers with ~/Library/Application Support on +// darwin, where this rule says ~/.config. +func TestDefaultConfigPathFollowsTheConfigHome(t *testing.T) { + home := t.TempDir() + tests := []struct { + name string + xdg string + home string // an empty home is an unknowable one: os.UserHomeDir fails + wantDir string + }{ + { + name: "an absolute XDG_CONFIG_HOME is used as given", + xdg: filepath.Join(home, "xdg"), + home: filepath.Join(home, "ignored"), + wantDir: filepath.Join(home, "xdg", "archie"), + }, + { + name: "a relative XDG_CONFIG_HOME is honoured rather than rejected", + xdg: filepath.Join("relative", "config"), + home: home, + wantDir: filepath.Join("relative", "config", "archie"), + }, + { + // $XDG_CONFIG_HOME "either not set or empty" is one case to the code + // under test, which reads it with os.Getenv: nothing downstream can + // tell an absent variable from an empty one, so neither can this. + name: "an unset or empty XDG_CONFIG_HOME falls back to the home directory", + home: home, + wantDir: filepath.Join(home, ".config", "archie"), + }, + { + name: "an unknowable home leaves the path relative instead of empty", + wantDir: filepath.Join(".config", "archie"), + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Setenv("HOME", tc.home) + t.Setenv("XDG_CONFIG_HOME", tc.xdg) + if got := DefaultConfigDir(); got != tc.wantDir { + t.Errorf("DefaultConfigDir() = %q, want %q", got, tc.wantDir) + } + if got, want := DefaultConfigPath(), filepath.Join(tc.wantDir, "config.toml"); got != want { + t.Errorf("DefaultConfigPath() = %q, want %q", got, want) + } + }) + } +} + +func TestBinariesTakeTheDefaultConfigPathFromHere(t *testing.T) { + fset := token.NewFileSet() + var defaults []configFlagDefault + + root := moduleRoot(t) + + for _, pattern := range []string{ + filepath.Join(root, "cmd", "*", "*.go"), + filepath.Join(root, "internal", "app", "archied", "*.go"), + } { + paths, err := filepath.Glob(pattern) + if err != nil { + t.Fatalf("glob %s: %v", pattern, err) + } + if len(paths) == 0 { + t.Fatalf("glob %s matched no file, so this fence checked nothing", pattern) + } + for _, path := range paths { + if strings.HasSuffix(path, "_test.go") { + continue + } + file, err := parser.ParseFile(fset, path, nil, 0) + if err != nil { + t.Fatalf("parse %s: %v", path, err) + } + helper := importedName(file, configPackageImportPath) + ast.Inspect(file, func(node ast.Node) bool { + call, ok := node.(*ast.CallExpr) + if !ok { + return true + } + if isSelectorCall(call, "os", "UserConfigDir") { + t.Errorf("%s: resolves the config directory itself with os.UserConfigDir; it rejects a relative XDG_CONFIG_HOME and resolves to ~/Library/Application Support on darwin, so this process would boot from a different file than the daemon (%s.%s resolves it once)", + fset.Position(call.Pos()), lastElement(configPackageImportPath), helperName) + } + defaultExpr, ok := configFlagDefaultExpr(call) + if !ok { + return true + } + defaults = append(defaults, configFlagDefault{ + at: fset.Position(call.Pos()), + expr: renderExpr(fset, defaultExpr), + resolved: callsHelper(defaultExpr, helper), + }) + return true + }) + } + } + + if len(defaults) == 0 { + t.Fatalf("no -config registration found under %s; this fence matched nothing and would pass vacuously", root) + } + for _, d := range defaults { + if !d.resolved { + t.Errorf("%s: -config defaults to %s instead of %s.%s(); every binary reads the same file only while they all take the path from that one helper (archie-core-8i6l)", + d.at, d.expr, lastElement(configPackageImportPath), helperName) + } + } +} + +// configFlagDefaultExpr returns the default expression of a call registering a +// flag named "config", and whether the call registers one at all. Both +// flag.StringVar(target, name, value, usage) and flag.String(name, value, +// usage) are recognised, whatever name the FlagSet is bound to -- the callers +// use flag.CommandLine, fs and flags interchangeably. +func configFlagDefaultExpr(call *ast.CallExpr) (ast.Expr, bool) { + sel, ok := call.Fun.(*ast.SelectorExpr) + if !ok { + return nil, false + } + switch sel.Sel.Name { + case "StringVar": + if len(call.Args) >= 3 && isStringLiteral(call.Args[1], "config") { + return call.Args[2], true + } + case "String": + if len(call.Args) >= 2 && isStringLiteral(call.Args[0], "config") { + return call.Args[1], true + } + } + return nil, false +} + +// isSelectorCall reports whether call is qualifier.name(...). +func isSelectorCall(call *ast.CallExpr, qualifier, name string) bool { + sel, ok := call.Fun.(*ast.SelectorExpr) + if !ok { + return false + } + ident, ok := sel.X.(*ast.Ident) + return ok && ident.Name == qualifier && sel.Sel.Name == name +} + +// callsHelper reports whether expr is helper.name(), where helper is the local +// name this file's imports give the configuration package ("" when the file +// does not import it). +func callsHelper(expr ast.Expr, helper string) bool { + if helper == "" { + return false + } + call, ok := expr.(*ast.CallExpr) + return ok && isSelectorCall(call, helper, helperName) +} + +// isStringLiteral reports whether expr is the string literal want. +func isStringLiteral(expr ast.Expr, want string) bool { + literal, ok := expr.(*ast.BasicLit) + if !ok || literal.Kind != token.STRING { + return false + } + value, err := strconv.Unquote(literal.Value) + return err == nil && value == want +} + +// importedName returns the name file's imports bind path to, or "" when the +// file does not import it. +func importedName(file *ast.File, path string) string { + for _, imported := range file.Imports { + if imported.Path == nil { + continue + } + importedPath, err := strconv.Unquote(imported.Path.Value) + if err != nil || importedPath != path { + continue + } + if name := imported.Name; name != nil && name.Name != "" && name.Name != "_" && name.Name != "." { + return name.Name + } + return lastElement(path) + } + return "" +} + +// renderExpr renders expr as source text, for a failure message that names the +// derivation instead of only its position. +func renderExpr(fset *token.FileSet, expr ast.Expr) string { + var buf bytes.Buffer + if err := printer.Fprint(&buf, fset, expr); err != nil { + return "" + } + return buf.String() +} + +func lastElement(path string) string { + return path[strings.LastIndex(path, "/")+1:] +} + +// moduleRoot walks up from this test's source to the directory holding go.mod. +func moduleRoot(t *testing.T) string { + t.Helper() + _, file, _, ok := runtime.Caller(0) + if !ok { + t.Fatal("cannot locate this test's source file") + } + dir := filepath.Dir(file) + for { + if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil { + return dir + } + parent := filepath.Dir(dir) + if parent == dir { + t.Fatal("no go.mod above this test's source file") + } + dir = parent + } +} diff --git a/internal/infrastructure/configuration/defaults.go b/internal/infrastructure/configuration/defaults.go index 9135b46af..120471b5b 100644 --- a/internal/infrastructure/configuration/defaults.go +++ b/internal/infrastructure/configuration/defaults.go @@ -199,6 +199,25 @@ func DefaultWorkDir() string { return filepath.Join(xdgDataHome(), "archie", "work") } +// DefaultConfigDir returns the directory archie's configuration lives in: +// $XDG_CONFIG_HOME/archie, or ~/.config/archie. It is the base every +// config-home-derived path is built on. It is not the -config source +// directory, which is whichever file or directory the operator names. +func DefaultConfigDir() string { + return filepath.Join(xdgConfigHome(), "archie") +} + +// DefaultConfigPath returns the configuration file an archie binary reads when +// -config is not given. Every binary that asks a question about a deployment +// has to read this path to be answering about the same deployment, so the rule +// lives here once and the binaries take it from here. Deriving it a second way +// is what went wrong before: os.UserConfigDir is a plausible-looking source for +// the same value that disagrees with this one on darwin and for a relative +// $XDG_CONFIG_HOME. +func DefaultConfigPath() string { + return filepath.Join(DefaultConfigDir(), "config.toml") +} + // applyGeneralDefaults derives the paths and limits that have no owning // section. func (l *Loader) applyGeneralDefaults(cfg *config.Config) { diff --git a/internal/infrastructure/configuration/loader.go b/internal/infrastructure/configuration/loader.go index 5cff2a138..758298a5c 100644 --- a/internal/infrastructure/configuration/loader.go +++ b/internal/infrastructure/configuration/loader.go @@ -79,6 +79,24 @@ func xdgDataHome() string { return filepath.Join(home, ".local", "share") } +// xdgConfigHome returns $XDG_CONFIG_HOME, falling back to ~/.config, and +// finally to a relative path when the home directory is unknowable. +// +// os.UserConfigDir is the XDG-spec-shaped function and is deliberately not +// used: it resolves to ~/Library/Application Support on darwin and returns an +// error rather than a relative path for a relative $XDG_CONFIG_HOME, so two +// archie processes would read two different configuration files. +func xdgConfigHome() string { + if dir := os.Getenv("XDG_CONFIG_HOME"); dir != "" { + return dir + } + home, err := os.UserHomeDir() + if err != nil { + return ".config" + } + return filepath.Join(home, ".config") +} + // File loads a single configuration file. TOML remains supported for existing // deployments; YAML files use the same defaults and validation path. func (l *Loader) File(path string) (*Document, error) {