Skip to content

Commit 844d3fe

Browse files
committed
add config merging logic
1 parent c8b999d commit 844d3fe

File tree

1 file changed

+48
-5
lines changed

1 file changed

+48
-5
lines changed

config/config.go

+48-5
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package config
33
import (
44
"encoding/json"
55
"errors"
6+
"fmt"
67
"os"
78
"path/filepath"
89
"sync"
@@ -32,9 +33,46 @@ type Config struct {
3233
ServerPort string `json:"server_port"` // port to run the server on
3334
}
3435

36+
// Merges file config with default config
37+
func mergeConfigs(config, defaultConfig *Config) *Config {
38+
if config.RetroPath == "" {
39+
config.RetroPath = defaultConfig.RetroPath
40+
}
41+
if config.PathYTDL == "" {
42+
config.PathYTDL = defaultConfig.PathYTDL
43+
}
44+
if config.PathFFmpeg == "" {
45+
config.PathFFmpeg = defaultConfig.PathFFmpeg
46+
}
47+
if config.PathFFprobe == "" {
48+
config.PathFFprobe = defaultConfig.PathFFprobe
49+
}
50+
if config.SearchTimeout == 0 {
51+
config.SearchTimeout = defaultConfig.SearchTimeout
52+
}
53+
if config.Theme == "" {
54+
config.Theme = defaultConfig.Theme
55+
}
56+
if config.LogFile == "" {
57+
config.LogFile = defaultConfig.LogFile
58+
}
59+
if config.DBPath == "" {
60+
config.DBPath = defaultConfig.DBPath
61+
}
62+
if config.ServerPort == "" {
63+
config.ServerPort = defaultConfig.ServerPort
64+
}
65+
// No need to check boolean field (DiscordRPC) since false is a meaningful value
66+
return config
67+
}
68+
3569
func initConfig() *Config {
3670
retro_path := os.Getenv("HOME") + "/.retro/"
37-
config := &Config{
71+
configPath := filepath.Join(retro_path, "config.json")
72+
var config *Config
73+
74+
// Load default config
75+
defaultConfig := &Config{
3876
RetroPath: retro_path,
3977
PathYTDL: "yt-dlp",
4078
PathFFmpeg: "ffmpeg",
@@ -49,12 +87,18 @@ func initConfig() *Config {
4987

5088
// Attempt to load from file
5189
if jsonFile, err := os.ReadFile(configPath); err == nil {
52-
if err = json.Unmarshal(jsonFile, config); err != nil {
53-
return config // Return default config if unmarshaling fails
90+
config = &Config{}
91+
if err = json.Unmarshal(jsonFile, config); err == nil {
92+
// Merge file config with default config
93+
config = mergeConfigs(config, defaultConfig)
94+
return config
95+
} else {
96+
fmt.Println("Error loading config file:", err)
5497
}
5598
}
5699

57-
return config
100+
// If we can't load from file, return the default config
101+
return defaultConfig
58102
}
59103

60104
func GetConfig() *Config {
@@ -63,7 +107,6 @@ func GetConfig() *Config {
63107
})
64108
return cfg
65109
}
66-
67110
func EditConfigField(field, value string) error {
68111
config := GetConfig()
69112
switch field {

0 commit comments

Comments
 (0)