@@ -34,7 +34,7 @@ func Execute(currentVersion string) error {
3434
3535func init () {
3636 cobra .OnInitialize (initConfig )
37- rootCmd .PersistentFlags ().StringVar (& cfgFile , "config" , "" , "config file (default $HOME/.bootdev.yaml)" )
37+ rootCmd .PersistentFlags ().StringVar (& cfgFile , "config" , "" , "config file (default $HOME/.bootdev.yaml, or in XDG_CONFIG_HOME if set )" )
3838}
3939
4040func readViperConfig (paths []string ) error {
@@ -61,18 +61,35 @@ func initConfig() {
6161 err := viper .ReadInConfig ()
6262 cobra .CheckErr (err )
6363 } else {
64- // Find home directory.
64+ // find home dir
6565 home , err := os .UserHomeDir ()
6666 cobra .CheckErr (err )
6767
68- // viper's built in config path thing sucks, let's do it ourselves
69- defaultPath := path .Join (home , ".bootdev.yaml" )
68+ // construct paths where existing config files may be located
69+ // use hard-coded XDG path for backwards compatibility
70+ xdgPath := path .Join (home , ".config" , "bootdev" , "config.yaml" )
71+ homeDotfilePath := path .Join (home , ".bootdev.yaml" )
72+
7073 configPaths := []string {}
71- configPaths = append (configPaths , path .Join (home , ".config" , "bootdev" , "config.yaml" ))
72- configPaths = append (configPaths , defaultPath )
74+ configPaths = append (configPaths , xdgPath ) // this one takes precedence
75+ configPaths = append (configPaths , homeDotfilePath )
76+
7377 if err := readViperConfig (configPaths ); err != nil {
74- viper .SafeWriteConfigAs (defaultPath )
75- viper .SetConfigFile (defaultPath )
78+ // no existing config found; create a new one
79+ // respect XDG_CONFIG_HOME if set, otherwise use dotfile in home dir
80+ var newConfigPath string
81+ if xdgConfigHome := os .Getenv ("XDG_CONFIG_HOME" ); xdgConfigHome != "" {
82+ newConfigPath = path .Join (xdgConfigHome , "bootdev" , "config.yaml" )
83+ configDir := path .Join (xdgConfigHome , "bootdev" )
84+ if err := os .MkdirAll (configDir , 0o755 ); err != nil {
85+ cobra .CheckErr (err )
86+ }
87+ } else {
88+ newConfigPath = homeDotfilePath
89+ }
90+
91+ viper .SafeWriteConfigAs (newConfigPath )
92+ viper .SetConfigFile (newConfigPath )
7693 err = viper .ReadInConfig ()
7794 cobra .CheckErr (err )
7895 }
0 commit comments