blob: fb87bef94f3f7d44d2505afbdfeaec168a25e860 [file] [log] [blame]
khenaidooac637102019-01-14 15:44:34 -05001package homedir
2
3import (
4 "bytes"
5 "errors"
6 "os"
7 "os/exec"
8 "path/filepath"
9 "runtime"
10 "strconv"
11 "strings"
12 "sync"
13)
14
15// DisableCache will disable caching of the home directory. Caching is enabled
16// by default.
17var DisableCache bool
18
19var homedirCache string
20var cacheLock sync.RWMutex
21
22// Dir returns the home directory for the executing user.
23//
24// This uses an OS-specific method for discovering the home directory.
25// An error is returned if a home directory cannot be detected.
26func Dir() (string, error) {
27 if !DisableCache {
28 cacheLock.RLock()
29 cached := homedirCache
30 cacheLock.RUnlock()
31 if cached != "" {
32 return cached, nil
33 }
34 }
35
36 cacheLock.Lock()
37 defer cacheLock.Unlock()
38
39 var result string
40 var err error
41 if runtime.GOOS == "windows" {
42 result, err = dirWindows()
43 } else {
44 // Unix-like system, so just assume Unix
45 result, err = dirUnix()
46 }
47
48 if err != nil {
49 return "", err
50 }
51 homedirCache = result
52 return result, nil
53}
54
55// Expand expands the path to include the home directory if the path
56// is prefixed with `~`. If it isn't prefixed with `~`, the path is
57// returned as-is.
58func Expand(path string) (string, error) {
59 if len(path) == 0 {
60 return path, nil
61 }
62
63 if path[0] != '~' {
64 return path, nil
65 }
66
67 if len(path) > 1 && path[1] != '/' && path[1] != '\\' {
68 return "", errors.New("cannot expand user-specific home dir")
69 }
70
71 dir, err := Dir()
72 if err != nil {
73 return "", err
74 }
75
76 return filepath.Join(dir, path[1:]), nil
77}
78
79func dirUnix() (string, error) {
80 homeEnv := "HOME"
81 if runtime.GOOS == "plan9" {
82 // On plan9, env vars are lowercase.
83 homeEnv = "home"
84 }
85
86 // First prefer the HOME environmental variable
87 if home := os.Getenv(homeEnv); home != "" {
88 return home, nil
89 }
90
91 var stdout bytes.Buffer
92
93 // If that fails, try OS specific commands
94 if runtime.GOOS == "darwin" {
95 cmd := exec.Command("sh", "-c", `dscl -q . -read /Users/"$(whoami)" NFSHomeDirectory | sed 's/^[^ ]*: //'`)
96 cmd.Stdout = &stdout
97 if err := cmd.Run(); err == nil {
98 result := strings.TrimSpace(stdout.String())
99 if result != "" {
100 return result, nil
101 }
102 }
103 } else {
104 cmd := exec.Command("getent", "passwd", strconv.Itoa(os.Getuid()))
105 cmd.Stdout = &stdout
106 if err := cmd.Run(); err != nil {
107 // If the error is ErrNotFound, we ignore it. Otherwise, return it.
108 if err != exec.ErrNotFound {
109 return "", err
110 }
111 } else {
112 if passwd := strings.TrimSpace(stdout.String()); passwd != "" {
113 // username:password:uid:gid:gecos:home:shell
114 passwdParts := strings.SplitN(passwd, ":", 7)
115 if len(passwdParts) > 5 {
116 return passwdParts[5], nil
117 }
118 }
119 }
120 }
121
122 // If all else fails, try the shell
123 stdout.Reset()
124 cmd := exec.Command("sh", "-c", "cd && pwd")
125 cmd.Stdout = &stdout
126 if err := cmd.Run(); err != nil {
127 return "", err
128 }
129
130 result := strings.TrimSpace(stdout.String())
131 if result == "" {
132 return "", errors.New("blank output when reading home directory")
133 }
134
135 return result, nil
136}
137
138func dirWindows() (string, error) {
139 // First prefer the HOME environmental variable
140 if home := os.Getenv("HOME"); home != "" {
141 return home, nil
142 }
143
144 // Prefer standard environment variable USERPROFILE
145 if home := os.Getenv("USERPROFILE"); home != "" {
146 return home, nil
147 }
148
149 drive := os.Getenv("HOMEDRIVE")
150 path := os.Getenv("HOMEPATH")
151 home := drive + path
152 if drive == "" || path == "" {
153 return "", errors.New("HOMEDRIVE, HOMEPATH, or USERPROFILE are blank")
154 }
155
156 return home, nil
157}