Merge pull request #156 from jjromannet/verbose-config-loading

Add error handling to reading of config file.
This commit is contained in:
Nicco 2022-02-13 16:23:05 +01:00 committed by GitHub
commit 7d87160706
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 31 additions and 7 deletions

View File

@ -1,8 +1,10 @@
package cmd package cmd
import ( import (
"fmt"
"os" "os"
"path/filepath" "path/filepath"
"strings"
"github.com/cupcakearmy/autorestic/internal" "github.com/cupcakearmy/autorestic/internal"
"github.com/cupcakearmy/autorestic/internal/colors" "github.com/cupcakearmy/autorestic/internal/colors"
@ -49,13 +51,21 @@ func initConfig() {
} }
if cfgFile != "" { if cfgFile != "" {
if internal.VERBOSE {
colors.Faint.Printf("> Using config file: %s\n", cfgFile)
}
viper.SetConfigFile(cfgFile) viper.SetConfigFile(cfgFile)
viper.AutomaticEnv()
if viper.ConfigFileUsed() == "" {
colors.Error.Println("cannot read config file %s\n", cfgFile)
os.Exit(1)
}
} else { } else {
viper.AddConfigPath(".") configPaths := []string{"."}
// Home // Home
if home, err := homedir.Dir(); err != nil { if home, err := homedir.Dir(); err != nil {
viper.AddConfigPath(home) configPaths = append(configPaths, home)
} }
// XDG_CONFIG_HOME // XDG_CONFIG_HOME
@ -66,10 +76,24 @@ func initConfig() {
prefix = filepath.Join(home, ".config") prefix = filepath.Join(home, ".config")
} }
} }
viper.AddConfigPath(filepath.Join(prefix, "autorestic")) xdgConfig := filepath.Join(prefix, "autorestic")
configPaths = append(configPaths, xdgConfig)
}
for _, cfgPath := range configPaths {
if internal.VERBOSE {
colors.Faint.Printf("> Adding config path: '%s'\n", cfgPath)
}
viper.AddConfigPath(cfgPath)
}
cfgFileName := ".autorestic"
viper.SetConfigName(cfgFileName)
viper.AutomaticEnv()
if viper.ConfigFileUsed() == "" {
colors.Error.Println(
fmt.Sprintf(
"cannot find configuration file '%s.yml' or '%s.yaml' in config paths: ['%s']",
cfgFileName, cfgFileName, strings.Join(configPaths, "', '")))
os.Exit(1)
} }
viper.SetConfigName(".autorestic")
} }
viper.AutomaticEnv()
} }

View File

@ -10,7 +10,7 @@ For remote backups (S3, B2, GCS, etc.) it's quite easy, as you only need to moun
docker run --rm \\ docker run --rm \\
-v $(pwd):/data \\ -v $(pwd):/data \\
cupcakearmy/autorestic \\ cupcakearmy/autorestic \\
autorestic backup -va autorestic backup -va -c /data/.autorestic.yaml
``` ```
## Rclone ## Rclone