From ad95fb4ed36bc2f7b8d5dc377f11897667a49c22 Mon Sep 17 00:00:00 2001 From: Gabriel Nagy Date: Wed, 15 Jun 2022 16:05:46 +0300 Subject: [PATCH] Update config detection to allow absent files 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. --- internal/config/config.go | 4 ++-- internal/config/config_test.go | 6 ++++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/internal/config/config.go b/internal/config/config.go index 27cf44672..981b8b68a 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -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) } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 155548030..1227bc941 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -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 {