2018-08-27 22:53:10 +03:00
|
|
|
package config
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"os"
|
2020-02-11 21:09:17 +03:00
|
|
|
"path/filepath"
|
2018-08-27 22:53:10 +03:00
|
|
|
|
|
|
|
homedir "github.com/mitchellh/go-homedir"
|
|
|
|
)
|
|
|
|
|
|
|
|
var ConfigDir string
|
|
|
|
|
|
|
|
// InitConfigDir finds the configuration directory for micro according to the XDG spec.
|
|
|
|
// If no directory is found, it creates one.
|
|
|
|
func InitConfigDir(flagConfigDir string) error {
|
|
|
|
var e error
|
|
|
|
|
2019-12-29 07:10:51 +03:00
|
|
|
microHome := os.Getenv("MICRO_CONFIG_HOME")
|
|
|
|
if microHome == "" {
|
|
|
|
// The user has not set $MICRO_CONFIG_HOME so we'll try $XDG_CONFIG_HOME
|
|
|
|
xdgHome := os.Getenv("XDG_CONFIG_HOME")
|
|
|
|
if xdgHome == "" {
|
|
|
|
// The user has not set $XDG_CONFIG_HOME so we should act like it was set to ~/.config
|
|
|
|
home, err := homedir.Dir()
|
|
|
|
if err != nil {
|
2020-01-01 00:48:45 +03:00
|
|
|
return errors.New("Error finding your home directory\nCan't load config files: " + err.Error())
|
2019-12-29 07:10:51 +03:00
|
|
|
}
|
2020-02-11 21:09:17 +03:00
|
|
|
xdgHome = filepath.Join(home, ".config")
|
2018-08-27 22:53:10 +03:00
|
|
|
}
|
2020-01-01 00:48:45 +03:00
|
|
|
|
2020-02-11 21:09:17 +03:00
|
|
|
microHome = filepath.Join(xdgHome, "micro")
|
2018-08-27 22:53:10 +03:00
|
|
|
}
|
2019-12-29 07:10:51 +03:00
|
|
|
ConfigDir = microHome
|
2018-08-27 22:53:10 +03:00
|
|
|
|
|
|
|
if len(flagConfigDir) > 0 {
|
|
|
|
if _, err := os.Stat(flagConfigDir); os.IsNotExist(err) {
|
|
|
|
e = errors.New("Error: " + flagConfigDir + " does not exist. Defaulting to " + ConfigDir + ".")
|
|
|
|
} else {
|
|
|
|
ConfigDir = flagConfigDir
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-01 00:48:45 +03:00
|
|
|
// Create micro config home directory if it does not exist
|
|
|
|
// This creates parent directories and does nothing if it already exists
|
|
|
|
err := os.MkdirAll(ConfigDir, os.ModePerm)
|
|
|
|
if err != nil {
|
|
|
|
return errors.New("Error creating configuration directory: " + err.Error())
|
2018-08-27 22:53:10 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return e
|
|
|
|
}
|