check a list of locations for the config file

* First, check the following locations in order (skip if the
  corresponding environment variable is undefined or empty):

  * `$ASCIINEMA_CONFIG_HOME/config`
  * `$XDG_CONFIG_HOME/asciinema/config`
  * `$HOME/.config/asciinema/config`
  * `$HOME/.asciinema/config`

  Use the first one that is found.

* If not found, create a new config file at the first location listed
  above whose corresponding environment variable is nonempty; i.e.,

  * Use `$ASCIINEMA_CONFIG_HOME/config` if `ASCIINEMA_CONFIG_HOME` is
    nonempty;
  * Next, use `$XDG_CONFIG_HOME/asciinema/config` if `XDG_CONFIG_HOME`
  is nonempty;
  * Finally, use `$HOME/.config/asciinema/config` if `HOME` is nonempty.

* If none of the above works, exit with error `"Need $HOME"`.
This commit is contained in:
Zhiming Wang
2015-05-23 01:36:36 -07:00
parent e753db2688
commit fd38b0f453

View File

@@ -81,15 +81,36 @@ func GetConfig(env map[string]string) (*Config, error) {
}
func loadConfigFile(env map[string]string) (*ConfigFile, error) {
homeDir := env["HOME"]
if homeDir == "" {
return nil, errors.New("Need $HOME")
pathsToCheck := make([]string, 0, 4)
if env["ASCIINEMA_CONFIG_HOME"] != "" {
pathsToCheck = append(pathsToCheck,
filepath.Join(env["ASCIINEMA_CONFIG_HOME"], "config"))
}
if env["XDG_CONFIG_HOME"] != "" {
pathsToCheck = append(pathsToCheck,
filepath.Join(env["XDG_CONFIG_HOME"], ".asciinema", "config"))
}
if env["HOME"] != "" {
pathsToCheck = append(pathsToCheck,
filepath.Join(env["HOME"], ".config", "asciinema", "config"))
pathsToCheck = append(pathsToCheck,
filepath.Join(env["HOME"], ".asciinema", "config"))
}
cfgPath := filepath.Join(homeDir, ".asciinema", "config")
cfgPath := ""
for _, pathToCheck := range pathsToCheck {
if _, err := os.Stat(pathToCheck); err == nil {
cfgPath = pathToCheck
break
}
}
if _, err := os.Stat(cfgPath); os.IsNotExist(err) {
if err = createConfigFile(cfgPath); err != nil {
if cfgPath == "" {
if len(pathsToCheck) == 0 {
return nil, errors.New("Need $HOME")
}
cfgPath = pathsToCheck[0]
if err := createConfigFile(cfgPath); err != nil {
return nil, err
}
}