From da8d82f75d9e587a43611dd4966511fc1b483ebc Mon Sep 17 00:00:00 2001 From: Liang-Shih Lin Date: Wed, 28 Aug 2024 11:43:14 +0800 Subject: [PATCH] fix: Use golang's native directory functions --- config.go | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/config.go b/config.go index 0cabc1a..20b863d 100644 --- a/config.go +++ b/config.go @@ -6,6 +6,7 @@ import ( "fmt" "log" "os" + "path/filepath" "strings" ) @@ -13,18 +14,28 @@ type Config struct { DbPath string } -var ( - configHome = os.Getenv("XDG_CONFIG_HOME") - configDir = configHome + "/kancli" - configFile = configDir + "/config.json" -) - func readConfig() Config { - mkdirErr := os.MkdirAll(configDir, 0755) + // look for $XDG_CONFIG_HOME/kancli/config.json or $HOME/.config/kancli/config.json + configDir, err := os.UserConfigDir() + if err != nil { + homeDir, err := os.UserHomeDir() + if err != nil { + // cant find home or config just give up + return Config{} + } + configDir = filepath.Join(homeDir, ".config") + } + + // Create ~/.config/kancli/ if it does not exist + configPath := filepath.Join(configDir, "kancli") + + mkdirErr := os.MkdirAll(configPath, 0755) if mkdirErr != nil { log.Fatal(mkdirErr) } + configFile := filepath.Join(configPath, "config.json") + var config Config if _, err := os.Stat(configFile); os.IsNotExist(err) { file, err := os.Create(configFile)