diff --git a/cmd/root.go b/cmd/root.go index 105615f..c2f9da0 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -26,7 +26,6 @@ import ( "fmt" "os" "os/signal" - "path/filepath" "strings" "syscall" @@ -146,7 +145,7 @@ func init() { rootCmd.Flags().Bool("add", false, "bookmarkにカレントディレクトリを追加します") // make rootCmd.Flags().Bool("make", false, "ディレクトリが無い場合、作ってから移動します") - _ = viper.BindPFlag("make", rootCmd.Flags().Lookup("make")) + _ = viper.BindPFlag("Make", rootCmd.Flags().Lookup("make")) // stdin rootCmd.Flags().BoolP("stdin", "i", false, "stdinから候補を受け取ります") // init @@ -159,35 +158,9 @@ func init() { // initConfig reads in config file and ENV variables if set. func initConfig() { - if cfgFile != "" { - // Use config file from the flag. - viper.SetConfigFile(cfgFile) - } else { - // Find home directory. - home, err := homedir.Dir() - if err != nil { - fmt.Println(err) - os.Exit(1) - } - - // Search config in home directory with name ".go-cdx" (without extension). - viper.AddConfigPath(filepath.Join(home, ".config", "go-cdx")) - viper.SetConfigName("go-cdx") - } - - viper.AutomaticEnv() // read in environment variables that match - - // If a config file is found, read it in. - if err := viper.ReadInConfig(); err != nil { - logrus.WithError(err).Fatal("[cdx] failed read config file") - } - - if err := viper.Unmarshal(&cfg); err != nil { - logrus.WithError(err).Fatal("[cdx] failed unmarshal config file") - } - { - home, _ := homedir.Dir() - cfg.HistoryFile = strings.Replace(cfg.HistoryFile, "~", home, 1) - cfg.BookmarkFile = strings.Replace(cfg.BookmarkFile, "~", home, 1) + var err error + cfg, err = config.Load(cfgFile) + if err != nil { + logrus.Fatal(err) } } diff --git a/config/config.go b/config/config.go index ac1c610..429ea33 100644 --- a/config/config.go +++ b/config/config.go @@ -1,7 +1,12 @@ package config import ( + "path/filepath" "runtime" + "strings" + + "github.com/mitchellh/go-homedir" + "github.com/spf13/viper" ) type ( @@ -53,3 +58,36 @@ func ExitCommand() string { } return exitCommand } + +func Load(path string) (Config, error) { + home, err := homedir.Dir() + if err != nil { + return Config{}, err + } + if len(path) != 0 { + viper.SetConfigFile(path) + } else { + + // linux/macOSは$HOME/.config/go-cdx/以下を見る + viper.AddConfigPath(filepath.Join(home, ".config", "go-cdx")) + // Windowsなら追加で $HOME\AppData\Roaming\go-cdxも見る + if runtime.GOOS == "windows" { + viper.AddConfigPath(filepath.Join(home, "AppData", "Roaming", "go-cdx")) + } + // ファイル名は go-cdx.{json,toml,yaml}など。viperが解釈できればなんでも + viper.SetConfigName("go-cdx") + } + + err = viper.ReadInConfig() + if err != nil { + return Config{}, err + } + + var cfg Config + err = viper.Unmarshal(&cfg) + + cfg.HistoryFile = strings.Replace(cfg.HistoryFile, "~", home, 1) + cfg.BookmarkFile = strings.Replace(cfg.BookmarkFile, "~", home, 1) + + return cfg, err +}