|
1 | 1 | package config |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "errors" |
4 | 5 | "fmt" |
| 6 | + "io/fs" |
5 | 7 | "os" |
6 | 8 | "path/filepath" |
7 | 9 | "strconv" |
@@ -63,26 +65,29 @@ func SetupViper(configDir string) error { |
63 | 65 | viper.SetDefault("password_storage", DefaultPasswordStorage) |
64 | 66 | viper.SetDefault("debug", DefaultDebug) |
65 | 67 |
|
66 | | - // Try to read config file if it exists |
67 | | - if _, err := os.Stat(configFile); err == nil { |
68 | | - // File exists, try to read it |
69 | | - if err := viper.ReadInConfig(); err != nil { |
70 | | - return fmt.Errorf("error reading config file: %w", err) |
71 | | - } |
| 68 | + return readInConfig() |
| 69 | +} |
72 | 70 |
|
73 | | - // Configure viper to watch for file changes and update its in-memory |
74 | | - // representation of the config. Note that this won't automatically |
75 | | - // update [Config] structs already returned from [Load]. |
76 | | - viper.WatchConfig() |
77 | | - } |
| 71 | +func readInConfig() error { |
| 72 | + // Try to read config file if it exists |
78 | 73 | // If file doesn't exist, that's okay - we'll use defaults and env vars |
79 | | - |
| 74 | + if err := viper.ReadInConfig(); err != nil && |
| 75 | + !errors.As(err, &viper.ConfigFileNotFoundError{}) && |
| 76 | + !errors.Is(err, fs.ErrNotExist) { |
| 77 | + return err |
| 78 | + } |
80 | 79 | return nil |
81 | 80 | } |
82 | 81 |
|
83 | 82 | // Load creates a new Config instance from the current viper state |
84 | 83 | // This function should be called after SetupViper has been called to initialize viper |
85 | 84 | func Load() (*Config, error) { |
| 85 | + // Try to read config file into viper to ensure we're unmarshaling the most |
| 86 | + // up-to-date values into the config struct. |
| 87 | + if err := readInConfig(); err != nil { |
| 88 | + return nil, err |
| 89 | + } |
| 90 | + |
86 | 91 | cfg := &Config{ |
87 | 92 | ConfigDir: GetConfigDir(), |
88 | 93 | } |
|
0 commit comments