From 6bf49530031d3694d0c5e8c59e96a5f70257975f Mon Sep 17 00:00:00 2001 From: Jan Date: Wed, 9 Feb 2022 09:07:01 +0100 Subject: [PATCH] Add error handling to reading config file. --- cmd/root.go | 36 ++++++++++++++++++++++++++++++------ docs/markdown/docker.md | 2 +- 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/cmd/root.go b/cmd/root.go index 8b766ea..dd21124 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -1,8 +1,10 @@ package cmd import ( + "fmt" "os" "path/filepath" + "strings" "github.com/cupcakearmy/autorestic/internal" "github.com/cupcakearmy/autorestic/internal/colors" @@ -49,13 +51,21 @@ func initConfig() { } if cfgFile != "" { + if internal.VERBOSE { + colors.Faint.Printf("> Using config file: %s\n", cfgFile) + } viper.SetConfigFile(cfgFile) + viper.AutomaticEnv() + if viper.ConfigFileUsed() == "" { + colors.Error.Println("cannot read config file %s\n", cfgFile) + os.Exit(1) + } } else { - viper.AddConfigPath(".") + configPaths := []string{"."} // Home if home, err := homedir.Dir(); err != nil { - viper.AddConfigPath(home) + configPaths = append(configPaths, home) } // XDG_CONFIG_HOME @@ -66,10 +76,24 @@ func initConfig() { 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() } diff --git a/docs/markdown/docker.md b/docs/markdown/docker.md index 32636d2..86f17b6 100644 --- a/docs/markdown/docker.md +++ b/docs/markdown/docker.md @@ -10,7 +10,7 @@ For remote backups (S3, B2, GCS, etc.) it's quite easy, as you only need to moun docker run --rm \\ -v $(pwd):/data \\ cupcakearmy/autorestic \\ - autorestic backup -va + autorestic backup -va -c /data/.autorestic.yaml ``` ## Rclone