From ebdc24c3d334132542daa7c57246389e0b259227 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Mart=C3=AD?= Date: Sat, 2 Feb 2019 11:40:55 +0000 Subject: [PATCH] os: add UserConfigDir MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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í TryBot-Result: Gobot Gobot Reviewed-by: Brad Fitzpatrick --- src/os/file.go | 51 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/src/os/file.go b/src/os/file.go index 8c25cc0a3b5dac..d880a37569dd89 100644 --- a/src/os/file.go +++ b/src/os/file.go @@ -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.