Skip to content

Commit

Permalink
Merge branch 'rverst-feature/support_xdg_base_direcory'
Browse files Browse the repository at this point in the history
  • Loading branch information
marcosnils committed Mar 24, 2021
2 parents dd4755f + 32c5327 commit 7cec71d
Showing 1 changed file with 38 additions and 5 deletions.
43 changes: 38 additions & 5 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"io"
"os"
"path"
"path/filepath"
"runtime"

Expand All @@ -28,17 +29,16 @@ type Binary struct {
}

func CheckAndLoad() error {
home, err := os.UserHomeDir()
configDir, err := getConfigPath()
if err != nil {
return err
}

configDir := filepath.Join(home, ".bin")

if err := os.Mkdir(configDir, 0755); err != nil && !os.IsExist(err) {
return fmt.Errorf("Error creating config directory [%v]", err)
}

log.Debugf("Config directory is: %s", configDir)
f, err := os.OpenFile(filepath.Join(configDir, "config.json"), os.O_RDWR|os.O_CREATE, 0664)
if err != nil && !os.IsNotExist(err) {
return err
Expand Down Expand Up @@ -99,12 +99,12 @@ func RemoveBinaries(paths []string) error {
}

func write() error {
home, err := os.UserHomeDir()
configDir, err := getConfigPath()
if err != nil {
return err
}

f, err := os.OpenFile(filepath.Join(home, ".bin", "config.json"), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0664)
f, err := os.OpenFile(filepath.Join(configDir, "config.json"), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0664)
if err != nil {
return err
}
Expand Down Expand Up @@ -147,6 +147,39 @@ func GetOS() []string {
return res
}

// getConfigPath returns the path to the configuration directory respecting
// the `XDG Base Directory specification` using the following strategy:
// - to prevent breaking of existing configurations, check if "$HOME/.bin/config.json"
// exists and return "$HOME/.bin"
// - if "XDG_CONFIG_HOME" is set, return "$XDG_CONFIG_HOME/bin"
// - if "$HOME/.config" exists, return "$home/.config/bin"
// - default to "$HOME/.bin/"
// ToDo: move the function to config_unix.go and add a similar function for windows,
// %APPDATA% might be the right place on windows
func getConfigPath() (string, error) {
home, homeErr := os.UserHomeDir()
if homeErr == nil {
if _, err := os.Stat(filepath.Join(home, ".bin", "config.json")); !os.IsNotExist(err) {
return filepath.Join(path.Join(home, ".bin")), nil
}
}

c := os.Getenv("XDG_CONFIG_HOME")
if _, err := os.Stat(c); !os.IsNotExist(err) {
return filepath.Join(c, "bin"), nil
}

if homeErr != nil {
return "", homeErr
}
c = filepath.Join(home, ".config")
if _, err := os.Stat(c); !os.IsNotExist(err) {
return filepath.Join(c, "bin"), nil
}

return filepath.Join(home, ".bin"), nil
}

func GetOSSpecificExtensions() []string {
switch runtime.GOOS {
case "linux":
Expand Down

0 comments on commit 7cec71d

Please sign in to comment.