pkg/utils: Address the confusion around handling errors from Viper

It turns out that Viper's custom error implementations use non-pointer
receivers, whereas often people assume pointer receivers.  This can
cause confusion when trying to use errors.As(...) with those errors [1].

Secondly, Viper may or may not throw ConfigFileNotFoundError depending
on its build tags.

[1] https://github.com/spf13/viper/issues/1139

https://github.com/containers/toolbox/pull/1105
This commit is contained in:
Debarshi Ray 2022-09-02 18:42:55 +02:00
parent 53c5694040
commit 00def007f5

View file

@ -572,27 +572,19 @@ func SetUpConfiguration() error {
viper.SetConfigFile(configFile) viper.SetConfigFile(configFile)
if err := viper.MergeInConfig(); err != nil { if err := viper.MergeInConfig(); err != nil {
// Seems like Viper's errors can't be examined with var errConfigFileNotFound viper.ConfigFileNotFoundError
// errors.As. var errConfigParse viper.ConfigParseError
// Seems like Viper doesn't actually throw if errors.As(err, &errConfigFileNotFound) || os.IsNotExist(err) {
// viper.ConfigFileNotFoundError if a configuration
// file is not found. We still check for it for the
// sake of completion or in case Viper uses it in a
// different version.
_, ok := err.(viper.ConfigFileNotFoundError)
if ok || os.IsNotExist(err) {
logrus.Debugf("Setting up configuration: file %s not found", configFile) logrus.Debugf("Setting up configuration: file %s not found", configFile)
continue continue
} } else if errors.As(err, &errConfigParse) {
if _, ok := err.(viper.ConfigParseError); ok {
logrus.Debugf("Setting up configuration: failed to parse file %s: %s", configFile, err) logrus.Debugf("Setting up configuration: failed to parse file %s: %s", configFile, err)
return fmt.Errorf("failed to parse file %s", configFile) return fmt.Errorf("failed to parse file %s", configFile)
} else {
logrus.Debugf("Setting up configuration: failed to read file %s: %s", configFile, err)
return fmt.Errorf("failed to read file %s", configFile)
} }
logrus.Debugf("Setting up configuration: failed to read file %s: %s", configFile, err)
return fmt.Errorf("failed to read file %s", configFile)
} }
} }