From 73d7493c5d5ff1c9c37375a50aeb6dd6a0b44794 Mon Sep 17 00:00:00 2001 From: Martyn R Date: Wed, 29 Dec 2021 01:49:56 +0000 Subject: [PATCH] initial port of https://lib.rs/crates/directories Based entirely on the documentation and not rust code. Pulled in handy Golang stuff where appropriate. --- base/base.go | 104 +++++++++++++++++++++++++++++++++++++++++++++++++++ go.mod | 3 ++ 2 files changed, 107 insertions(+) create mode 100644 base/base.go create mode 100644 go.mod diff --git a/base/base.go b/base/base.go new file mode 100644 index 0000000..5a10f8b --- /dev/null +++ b/base/base.go @@ -0,0 +1,104 @@ +package base + +import ( + "errors" + "os" + "runtime" +) + +func Home() (string, error) { + dir, err := os.UserHomeDir() + return dir, err +} + +func Cache() (string, error) { + dir, err := os.UserCacheDir() + return dir, err +} + +func Config() (string, error) { + dir, err := os.UserCacheDir() + return dir, err +} + +func Data() (string, error) { + switch runtime.GOOS { + case "linux": + e, ok := os.LookupEnv("XDG_DATA_HOME") + if ok { + return e, nil + } else { + h, err := Home() + return h + "/.local/share", err + } + case "windows": + return Config() + case "darwin": + return Config() + } + return "", errors.New("could not determine location for Data()") +} + +func DataLocal() (string, error) { + switch runtime.GOOS { + case "linux": + return Data() + case "windows": + return Cache() + case "darwin": + return Data() + } + return "", errors.New("could not determine location for DataLocal()") +} + +func Executable() (string, error) { + switch runtime.GOOS { + case "linux": + e, ok := os.LookupEnv("XDG_BIN_HOME") + if ok { + return e, nil + } else { + h, err := Home() + return h + "/.local/bin", err + } + } + return "", errors.New("could not determine location for Executable()") +} + +func Preferences() (string, error) { + switch runtime.GOOS { + case "linux": + return Config() + case "windows": + return Config() + case "darwin": + h, err := Home() + return h + "/Library/Preferences", err + } + return "", errors.New("could not determine location for Preferences()") +} + +func Runtime() (string, error) { + switch runtime.GOOS { + case "linux": + e, ok := os.LookupEnv("XDG_CONFIG_HOME") + if ok { + return e, nil + } + } + return "", errors.New("could not determine location for Runtime()") +} + +func State() (string, error) { + switch runtime.GOOS { + case "linux": + e, ok := os.LookupEnv("XDG_STATE_HOME") + if ok { + return e, nil + } else { + h, err := Home() + return h + "/.local/state", err + } + } + return "", errors.New("could not determine location for State()") +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..993c836 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module git.martyn.berlin/martyn/golang-directories + +go 1.17