feat: use OS-preferred config directory (#26)

This commit is contained in:
JY Tan
2026-02-01 16:17:33 -08:00
committed by GitHub
parent 7679fecf06
commit c8621e8f6c
8 changed files with 105 additions and 42 deletions

View File

@@ -133,12 +133,38 @@ func Default() *Config {
}
// DefaultConfigPath returns the default config file path.
// Uses the OS-preferred config directory (XDG on Linux, ~/Library/Application Support on macOS).
// Falls back to ~/.fence.json if the new location doesn't exist but the legacy one does.
func DefaultConfigPath() string {
// Try OS-preferred config directory first
configDir, err := os.UserConfigDir()
if err == nil {
newPath := filepath.Join(configDir, "fence", "fence.json")
if _, err := os.Stat(newPath); err == nil {
return newPath
}
// Check if parent directory exists (user has set up the new location)
// If so, prefer this even if config doesn't exist yet
if _, err := os.Stat(filepath.Dir(newPath)); err == nil {
return newPath
}
}
// Fall back to legacy path if it exists
home, err := os.UserHomeDir()
if err != nil {
return ".fence.json"
return "fence.json"
}
return filepath.Join(home, ".fence.json")
legacyPath := filepath.Join(home, ".fence.json")
if _, err := os.Stat(legacyPath); err == nil {
return legacyPath
}
// Neither exists, prefer new XDG-compliant path
if configDir != "" {
return filepath.Join(configDir, "fence", "fence.json")
}
return filepath.Join(home, ".config", "fence", "fence.json")
}
// Load loads configuration from a file path.

View File

@@ -295,9 +295,10 @@ func TestDefaultConfigPath(t *testing.T) {
if path == "" {
t.Error("DefaultConfigPath() returned empty string")
}
// Should end with .fence.json
if filepath.Base(path) != ".fence.json" {
t.Errorf("DefaultConfigPath() = %q, expected to end with .fence.json", path)
// Should end with fence.json (either new XDG path or legacy .fence.json)
base := filepath.Base(path)
if base != "fence.json" && base != ".fence.json" {
t.Errorf("DefaultConfigPath() = %q, expected to end with fence.json or .fence.json", path)
}
}