diff options
author | Robin Jarry <robin@jarry.cc> | 2023-08-23 19:51:54 +0200 |
---|---|---|
committer | Robin Jarry <robin@jarry.cc> | 2023-08-27 18:44:06 +0200 |
commit | fff16640ad7cd8c4b73187fbce10f2aa558701be (patch) | |
tree | 8112c2d2414231d78d05dc255a430512c26fc4e1 /lib/xdg/home.go | |
parent | bc8fdbbe8479f9f604f429931e7c90e396ea6f00 (diff) | |
download | aerc-fff16640ad7cd8c4b73187fbce10f2aa558701be.tar.gz |
xdg: add functions to deal with user home paths
These are intended to replace the following deprecated libraries:
github.com/kyoh86/xdg
github.com/mitchellh/go-homedir
The feature set should be roughly equivalent with some tweaks to make
our life easier in aerc.
Signed-off-by: Robin Jarry <robin@jarry.cc>
Reviewed-by: Moritz Poldrack <moritz@poldrack.dev>
Diffstat (limited to 'lib/xdg/home.go')
-rw-r--r-- | lib/xdg/home.go | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/lib/xdg/home.go b/lib/xdg/home.go new file mode 100644 index 00000000..3471e5e2 --- /dev/null +++ b/lib/xdg/home.go @@ -0,0 +1,47 @@ +package xdg + +import ( + "os" + "os/user" + "path" + "strings" + + "git.sr.ht/~rjarry/aerc/log" +) + +// assign to a local var to allow mocking in unit tests +var currentUser = user.Current + +// Get the current user home directory (first from the $HOME env var and +// fallback on calling getpwuid_r() from libc if $HOME is unset). +func HomeDir() string { + home, err := os.UserHomeDir() + if err != nil { + u, e := currentUser() + if e == nil { + home = u.HomeDir + } else { + log.Errorf("HomeDir: %s (while handling %s)", e, err) + } + } + return home +} + +// Replace ~ with the current user's home dir +func ExpandHome(fragments ...string) string { + home := HomeDir() + res := path.Join(fragments...) + if strings.HasPrefix(res, "~/") || res == "~" { + res = home + strings.TrimPrefix(res, "~") + } + return res +} + +// Replace $HOME with ~ (inverse function of ExpandHome) +func TildeHome(path string) string { + home := HomeDir() + if strings.HasPrefix(path, home+"/") || path == home { + path = "~" + strings.TrimPrefix(path, home) + } + return path +} |