Move config to directory returned by os.UserConfigDir()
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/tag Build is passing Details

This version will migrate configuration from the old path, but migration
will be removed at some point in the future.
This commit is contained in:
IamTheFij 2021-02-05 11:43:23 -08:00
parent 1a1689cd88
commit 03399ac35d
1 changed files with 35 additions and 12 deletions

View File

@ -5,8 +5,8 @@ import (
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"log"
"os" "os"
"os/user"
"path/filepath" "path/filepath"
) )
@ -19,22 +19,45 @@ type configData struct {
DomainTokens map[string]string DomainTokens map[string]string
} }
// getConfigFilePath returns the path of a given file within the config folder. // getConfigFilePath returns the path of a given file within the UserConfigDir.
// The config folder will be created in ~/.config/slack-status-cli if it does not exist.
func getConfigFilePath(filename string) (string, error) { func getConfigFilePath(filename string) (string, error) {
configHome := os.Getenv("XDG_CONFIG_HOME") configApplicationName := "slack-status-cli"
if configHome == "" {
usr, err := user.Current() configDir, err := os.UserConfigDir()
if err != nil { if err != nil {
return "", fmt.Errorf("error getting current user information: %w", err) return "", fmt.Errorf("error getting current config: %w", err)
}
configHome = filepath.Join(usr.HomeDir, ".config")
} }
configDir := filepath.Join(configHome, "slack-status-cli") configDir = filepath.Join(configDir, configApplicationName)
_ = os.MkdirAll(configDir, 0755) _ = os.MkdirAll(configDir, 0755)
configFile := filepath.Join(configDir, filename)
return filepath.Join(configDir, filename), nil // Handle migration of old config file path
// NOTE: Will be removed in future versions
if !fileExists(configFile) {
// Get old config path to see if we should migrate
userHomeDir, _ := os.UserHomeDir()
legacyConfigFile := filepath.Join(
userHomeDir,
".config",
configApplicationName,
filename,
)
if fileExists(legacyConfigFile) {
log.Printf("Migrating config from %s to %s\n", legacyConfigFile, configFile)
err = os.Rename(legacyConfigFile, configFile)
if err != nil {
err = fmt.Errorf(
"error migrating old config from %s: %w",
legacyConfigFile,
err,
)
}
}
}
return configFile, err
} }
// readConfig returns the current configuration // readConfig returns the current configuration