15 // DisableCache will disable caching of the home directory. Caching is enabled
19 var homedirCache string
20 var cacheLock sync.RWMutex
22 // Dir returns the home directory for the executing user.
24 // This uses an OS-specific method for discovering the home directory.
25 // An error is returned if a home directory cannot be detected.
26 func Dir() (string, error) {
29 cached := homedirCache
37 defer cacheLock.Unlock()
41 if runtime.GOOS == "windows" {
42 result, err = dirWindows()
44 // Unix-like system, so just assume Unix
45 result, err = dirUnix()
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
58 func Expand(path string) (string, error) {
67 if len(path) > 1 && path[1] != '/' && path[1] != '\\' {
68 return "", errors.New("cannot expand user-specific home dir")
76 return filepath.Join(dir, path[1:]), nil
79 func dirUnix() (string, error) {
80 // First prefer the HOME environmental variable
81 if home := os.Getenv("HOME"); home != "" {
85 // If that fails, try getent
86 var stdout bytes.Buffer
87 cmd := exec.Command("getent", "passwd", strconv.Itoa(os.Getuid()))
89 if err := cmd.Run(); err != nil {
90 // If the error is ErrNotFound, we ignore it. Otherwise, return it.
91 if err != exec.ErrNotFound {
95 if passwd := strings.TrimSpace(stdout.String()); passwd != "" {
96 // username:password:uid:gid:gecos:home:shell
97 passwdParts := strings.SplitN(passwd, ":", 7)
98 if len(passwdParts) > 5 {
99 return passwdParts[5], nil
104 // If all else fails, try the shell
106 cmd = exec.Command("sh", "-c", "cd && pwd")
108 if err := cmd.Run(); err != nil {
112 result := strings.TrimSpace(stdout.String())
114 return "", errors.New("blank output when reading home directory")
120 func dirWindows() (string, error) {
121 // First prefer the HOME environmental variable
122 if home := os.Getenv("HOME"); home != "" {
126 drive := os.Getenv("HOMEDRIVE")
127 path := os.Getenv("HOMEPATH")
129 if drive == "" || path == "" {
130 home = os.Getenv("USERPROFILE")
133 return "", errors.New("HOMEDRIVE, HOMEPATH, and USERPROFILE are blank")