aboutsummaryrefslogtreecommitdiffstats
path: root/lib/xdg/home.go
blob: 39894cf67c2470c3cf1287b3040ab1687a46d950 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package xdg

import (
	"os"
	"os/user"
	"path"
	"strings"

	"git.sr.ht/~rjarry/aerc/lib/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
}