From 7fa5e7d0ab67f20d434b2922725988695e32e6af Mon Sep 17 00:00:00 2001 From: Samuel Gaist Date: Thu, 25 Jul 2024 11:35:13 +0200 Subject: [PATCH] fix(cli): error on missing config file (#7154) --- pkg/commands/app.go | 10 ++++++---- pkg/commands/app_test.go | 9 +++++++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/pkg/commands/app.go b/pkg/commands/app.go index 5ca651193c35..5a9baab6ca0b 100644 --- a/pkg/commands/app.go +++ b/pkg/commands/app.go @@ -151,14 +151,16 @@ func loadPluginCommands() []*cobra.Command { return commands } -func initConfig(configFile string) error { +func initConfig(configFile string, pathChanged bool) error { // Read from config viper.SetConfigFile(configFile) viper.SetConfigType("yaml") if err := viper.ReadInConfig(); err != nil { if errors.Is(err, os.ErrNotExist) { - log.Debug("Config file not found", log.FilePath(configFile)) - return nil + if !pathChanged { + log.Debugf("Default config file %q not found, using built in values", log.FilePath(configFile)) + return nil + } } return xerrors.Errorf("config file %q loading error: %s", configFile, err) } @@ -201,7 +203,7 @@ func NewRootCommand(globalFlags *flag.GlobalFlagGroup) *cobra.Command { // Configure environment variables and config file // It cannot be called in init() because it must be called after viper.BindPFlags. - if err := initConfig(configPath); err != nil { + if err := initConfig(configPath, cmd.Flags().Changed(flag.ConfigFileFlag.ConfigName)); err != nil { return err } diff --git a/pkg/commands/app_test.go b/pkg/commands/app_test.go index 7235a3e94c7d..308732ce918b 100644 --- a/pkg/commands/app_test.go +++ b/pkg/commands/app_test.go @@ -296,6 +296,15 @@ func TestFlags(t *testing.T) { }, wantErr: `invalid argument "foo" for "--format" flag`, }, + { + name: "missing config file", + arguments: []string{ + "test", + "--config", + "none", + }, + wantErr: `config file "none" loading error: open none:`, + }, } for _, tt := range tests {