feat: improve config file handling

- 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

🤖
This commit is contained in:
Sebastian Mark 2024-10-30 09:32:01 +01:00
parent b06fac60d5
commit 480f1c0cdd
2 changed files with 30 additions and 10 deletions

View file

@ -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)

View file

@ -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)
}