Skip to content

Commit

Permalink
os: add UserConfigDir
Browse files Browse the repository at this point in the history
After UserCacheDir and UserHomeDir, the only remaining piece which is
commonly needed and portable is a per-user directory to store persistent
files.

For that purpose, UserCacheDir is wrong, as it's meant only for
temporary files. UserHomeDir is also far from ideal, as that clutters
the user's home directory.

Add UserConfigDir, which is implemented in a similar manner to
UserConfigDir.

Fixes #29960.

Change-Id: I7d7a56615103cf76e2b5e2bab2029a6b09d19f0b
Reviewed-on: https://go-review.googlesource.com/c/go/+/160877
Run-TryBot: Daniel Martí <[email protected]>
TryBot-Result: Gobot Gobot <[email protected]>
Reviewed-by: Brad Fitzpatrick <[email protected]>
  • Loading branch information
mvdan committed Mar 5, 2019
1 parent b3fac01 commit ebdc24c
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions src/os/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,57 @@ func UserCacheDir() (string, error) {
return dir, nil
}

// UserConfigDir returns the default root directory to use for user-specific
// configuration data. Users should create their own application-specific
// subdirectory within this one and use that.
//
// On Unix systems, it returns $XDG_CONFIG_HOME as specified by
// https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html if
// non-empty, else $HOME/.config.
// On Darwin, it returns $HOME/Library/Preferences.
// On Windows, it returns %AppData%.
// On Plan 9, it returns $home/lib.
//
// If the location cannot be determined (for example, $HOME is not defined),
// then it will return an error.
func UserConfigDir() (string, error) {
var dir string

switch runtime.GOOS {
case "windows":
dir = Getenv("AppData")
if dir == "" {
return "", errors.New("%AppData% is not defined")
}

case "darwin":
dir = Getenv("HOME")
if dir == "" {
return "", errors.New("$HOME is not defined")
}
dir += "/Library/Preferences"

case "plan9":
dir = Getenv("home")
if dir == "" {
return "", errors.New("$home is not defined")
}
dir += "/lib"

default: // Unix
dir = Getenv("XDG_CONFIG_HOME")
if dir == "" {
dir = Getenv("HOME")
if dir == "" {
return "", errors.New("neither $XDG_CONFIG_HOME nor $HOME are defined")
}
dir += "/.config"
}
}

return dir, nil
}

// UserHomeDir returns the current user's home directory.
//
// On Unix, including macOS, it returns the $HOME environment variable.
Expand Down

0 comments on commit ebdc24c

Please sign in to comment.