From 7fd6545eab88e41d50deac5154eb2a9ae9417b0a Mon Sep 17 00:00:00 2001 From: Patrick D'appollonio <930925+patrickdappollonio@users.noreply.github.com> Date: Tue, 10 Jun 2025 15:55:01 -0400 Subject: [PATCH] Fix config file error handling --- app.go | 3 ++- app_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 app_test.go diff --git a/app.go b/app.go index a374ec5..9541e5f 100644 --- a/app.go +++ b/app.go @@ -191,7 +191,8 @@ func bindCobraAndViper(rootCommand *cobra.Command) error { if err := v.ReadInConfig(); err != nil { // If the configuration file was not found, it's all good, we ignore // the failure and proceed with the default settings - if f := (&viper.ConfigFileNotFoundError{}); errors.As(err, &f) { + var cfErr viper.ConfigFileNotFoundError + if !errors.As(err, &cfErr) { return fmt.Errorf("unable to read configuration file: %w", err) } } diff --git a/app_test.go b/app_test.go new file mode 100644 index 0000000..8d901a0 --- /dev/null +++ b/app_test.go @@ -0,0 +1,28 @@ +package main + +import ( + "os" + "testing" + + "github.com/spf13/cobra" +) + +func TestBindCobraAndViper_NoConfigFile(t *testing.T) { + tempDir := t.TempDir() + + prev, err := os.Getwd() + if err != nil { + t.Fatalf("getwd: %v", err) + } + if err := os.Chdir(tempDir); err != nil { + t.Fatalf("chdir to temp dir: %v", err) + } + defer os.Chdir(prev) + + cmd := &cobra.Command{Use: "test"} + cmd.Flags().Bool("foo", false, "") + + if err := bindCobraAndViper(cmd); err != nil { + t.Fatalf("bindCobraAndViper returned error: %v", err) + } +}