Skip to content

Commit

Permalink
Update config detection to allow absent files
Browse files Browse the repository at this point in the history
Previously, if a non-existent config file was passed via CLI, the app
would error out. This will allow the app to continue even with a
non-existent config file.

This will prove useful for adwatchd where the app can be fully
configured via CLI, for the interactive root command which can accept a
`--config` argument (not necessarily present on the disk) and for cases
where the default config file doesn't exist.
  • Loading branch information
GabrielNagy committed Jun 15, 2022
1 parent 7a18369 commit ad95fb4
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 4 deletions.
4 changes: 2 additions & 2 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ func Init(name string, rootCmd cobra.Command, vip *viper.Viper, configChanged fu

if err := vip.ReadInConfig(); err != nil {
var e viper.ConfigFileNotFoundError
if errors.As(err, &e) {
log.Infof(context.Background(), "No configuration file: %v.\nWe will only use the defaults, env variables or flags.", e)
if errors.As(err, &e) || !vip.IsSet("config") {
log.Infof(context.Background(), "No configuration file: %v.\nWe will only use the defaults, env variables or flags.", err)
} else {
return fmt.Errorf("invalid configuration file: %w", err)
}
Expand Down
6 changes: 4 additions & 2 deletions internal/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,9 +161,11 @@ func TestInit(t *testing.T) {

// Error cases
"Error on no verbose flag set before Init is call": {noVerboseFlag: true, wantErr: true},
"Error on invalid configuration file": {configFileContent: "invalidcontent", want: "filecontentvalue", wantErr: true},
"Error on callback returning error on first call": {errFromCallbackOn: 1, wantErr: true},
"Error on config flag points to unexisting path": {withConfigFlagSet: "DELETED.yaml", wantErr: true},

// Configuration file not found
"Config flag points to unexisting path": {withConfigFlagSet: "DELETED.yaml", wantCallbackCalled: 1},
"Invalid configuration file": {configFileContent: "invalidcontent", wantCallbackCalled: 1},
}

for name, tc := range tests {
Expand Down

0 comments on commit ad95fb4

Please sign in to comment.