| 1 |
package xdg |
| 2 |
|
| 3 |
import ( |
| 4 |
"os" |
| 5 |
"os/user" |
| 6 |
"path" |
| 7 |
"strings" |
| 8 |
|
| 9 |
"git.sr.ht/~rjarry/aerc/lib/log" |
| 10 |
) |
| 11 |
|
| 12 |
// assign to a local var to allow mocking in unit tests |
| 13 |
var currentUser = user.Current |
| 14 |
|
| 15 |
// Get the current user home directory (first from the $HOME env var and |
| 16 |
// fallback on calling getpwuid_r() from libc if $HOME is unset). |
| 17 |
func HomeDir() string { |
| 18 |
home, err := os.UserHomeDir() |
| 19 |
if err != nil { |
| 20 |
u, e := currentUser() |
| 21 |
if e == nil { |
| 22 |
home = u.HomeDir |
| 23 |
} else { |
| 24 |
log.Errorf("HomeDir: %s (while handling %s)", e, err) |
| 25 |
} |
| 26 |
} |
| 27 |
return home |
| 28 |
} |
| 29 |
|
| 30 |
// Replace ~ with the current user's home dir |
| 31 |
func ExpandHome(fragments ...string) string { |
| 32 |
home := HomeDir() |
| 33 |
res := path.Join(fragments...) |
| 34 |
if strings.HasPrefix(res, "~/") || res == "~" { |
| 35 |
res = home + strings.TrimPrefix(res, "~") |
| 36 |
} |
| 37 |
return res |
| 38 |
} |
| 39 |
|
| 40 |
// Replace $HOME with ~ (inverse function of ExpandHome) |
| 41 |
func TildeHome(path string) string { |
| 42 |
home := HomeDir() |
| 43 |
if strings.HasPrefix(path, home+"/") || path == home { |
| 44 |
path = "~" + strings.TrimPrefix(path, home) |
| 45 |
} |
| 46 |
return path |
| 47 |
} |