Skip to content

Commit

Permalink
fix(cli): error on missing config file (#7154)
Browse files Browse the repository at this point in the history
  • Loading branch information
sgaist authored Jul 25, 2024
1 parent 8c87194 commit 7fa5e7d
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
10 changes: 6 additions & 4 deletions pkg/commands/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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
}

Expand Down
9 changes: 9 additions & 0 deletions pkg/commands/app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit 7fa5e7d

Please sign in to comment.