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) {
81 if runtime.GOOS == "plan9" {
82 // On plan9, env vars are lowercase.
86 // First prefer the HOME environmental variable
87 if home := os.Getenv(homeEnv); home != "" {
91 var stdout bytes.Buffer
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/^[^ ]*: //'`)
97 if err := cmd.Run(); err == nil {
98 result := strings.TrimSpace(stdout.String())
104 cmd := exec.Command("getent", "passwd", strconv.Itoa(os.Getuid()))
106 if err := cmd.Run(); err != nil {
107 // If the error is ErrNotFound, we ignore it. Otherwise, return it.
108 if err != exec.ErrNotFound {
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
122 // If all else fails, try the shell
124 cmd := exec.Command("sh", "-c", "cd && pwd")
126 if err := cmd.Run(); err != nil {
130 result := strings.TrimSpace(stdout.String())
132 return "", errors.New("blank output when reading home directory")
138 func dirWindows() (string, error) {
139 // First prefer the HOME environmental variable
140 if home := os.Getenv("HOME"); home != "" {
144 // Prefer standard environment variable USERPROFILE
145 if home := os.Getenv("USERPROFILE"); home != "" {
149 drive := os.Getenv("HOMEDRIVE")
150 path := os.Getenv("HOMEPATH")
152 if drive == "" || path == "" {
153 return "", errors.New("HOMEDRIVE, HOMEPATH, or USERPROFILE are blank")