You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

157 lines
3.4 KiB

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