From 480f1c0cdd18d34ce0d94e15e01c70237d8d078f Mon Sep 17 00:00:00 2001 From: Sebastian Mark Date: Wed, 30 Oct 2024 09:32:01 +0100 Subject: [PATCH] feat: improve config file handling MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - add default config file - read passed config file or use default if none provided - ensure cli parameters always supersede config file settings - add function to check if a file exists 🤖 --- cmd/client/main.go | 22 ++++++++++++++++------ internal/helper/{config.go => files.go} | 18 ++++++++++++++---- 2 files changed, 30 insertions(+), 10 deletions(-) rename internal/helper/{config.go => files.go} (71%) diff --git a/cmd/client/main.go b/cmd/client/main.go index d2e920f..d1e7850 100644 --- a/cmd/client/main.go +++ b/cmd/client/main.go @@ -15,6 +15,8 @@ import ( var ( config ChronoTomato.Config + defaultConfigFile = "~/.config/ChronoTomato.yml" + parameter_url = flag.String("url", "", "GoTomato Server URL (eg ws://localhost:8080/ws)") parameter_password = flag.String("password", "", "Control password for pomodoro session") configfile = flag.String("config", "", "Path to config file") @@ -26,13 +28,21 @@ func Start() { cursor.Hide() defer cursor.Show() - // read cli parameters if no config file passed - if *configfile == "" { - config.URL = *parameter_url - config.Password = *parameter_password - } else { - // otherwise read config + // read passed config file or try to use default config + if *configfile != "" { config = helper.ParseConfig(*configfile) + } else { + if helper.FileExists(defaultConfigFile) { + config = helper.ParseConfig(defaultConfigFile) + } + } + + // cli parameters always supersede config file + if *parameter_url != "" { + config.URL = *parameter_url + } + if *parameter_password != "" { + config.Password = *parameter_password } client := websocket.Connect(config.URL) diff --git a/internal/helper/config.go b/internal/helper/files.go similarity index 71% rename from internal/helper/config.go rename to internal/helper/files.go index 4cd2f7a..0f6b7e8 100644 --- a/internal/helper/config.go +++ b/internal/helper/files.go @@ -10,15 +10,25 @@ import ( ChronoTomato "git.smsvc.net/pomodoro/ChronoTomato/pkg/models" ) -func ParseConfig(filename string) ChronoTomato.Config { - var config ChronoTomato.Config - +func expandUnixPath(filename string) string { if strings.HasPrefix(filename, "~/") { dirname, _ := os.UserHomeDir() filename = filepath.Join(dirname, filename[2:]) } - yamlFile, err := os.ReadFile(filename) + return filename +} + +func FileExists(filename string) bool { + _, err := os.Stat(expandUnixPath(filename)) + + return !os.IsNotExist(err) +} + +func ParseConfig(filename string) ChronoTomato.Config { + var config ChronoTomato.Config + + yamlFile, err := os.ReadFile(expandUnixPath(filename)) if err != nil { log.Fatal("Error opening config file!", "reason", err) }