Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(cli): error on missing config file #7154

Merged
merged 5 commits into from
Jul 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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