gfile_home.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gfile
  7. import (
  8. "bytes"
  9. "os"
  10. "os/exec"
  11. "os/user"
  12. "runtime"
  13. "strings"
  14. "github.com/gogf/gf/v2/errors/gerror"
  15. )
  16. // Home returns absolute path of current user's home directory.
  17. // The optional parameter `names` specifies the sub-folders/sub-files,
  18. // which will be joined with current system separator and returned with the path.
  19. func Home(names ...string) (string, error) {
  20. path, err := getHomePath()
  21. if err != nil {
  22. return "", err
  23. }
  24. for _, name := range names {
  25. path += Separator + name
  26. }
  27. return path, nil
  28. }
  29. // getHomePath returns absolute path of current user's home directory.
  30. func getHomePath() (string, error) {
  31. u, err := user.Current()
  32. if nil == err {
  33. return u.HomeDir, nil
  34. }
  35. if runtime.GOOS == "windows" {
  36. return homeWindows()
  37. }
  38. return homeUnix()
  39. }
  40. // homeUnix retrieves and returns the home on unix system.
  41. func homeUnix() (string, error) {
  42. if home := os.Getenv("HOME"); home != "" {
  43. return home, nil
  44. }
  45. var stdout bytes.Buffer
  46. cmd := exec.Command("sh", "-c", "eval echo ~$USER")
  47. cmd.Stdout = &stdout
  48. if err := cmd.Run(); err != nil {
  49. err = gerror.Wrapf(err, `retrieve home directory failed`)
  50. return "", err
  51. }
  52. result := strings.TrimSpace(stdout.String())
  53. if result == "" {
  54. return "", gerror.New("blank output when reading home directory")
  55. }
  56. return result, nil
  57. }
  58. // homeWindows retrieves and returns the home on windows system.
  59. func homeWindows() (string, error) {
  60. var (
  61. drive = os.Getenv("HOMEDRIVE")
  62. path = os.Getenv("HOMEPATH")
  63. home = drive + path
  64. )
  65. if drive == "" || path == "" {
  66. home = os.Getenv("USERPROFILE")
  67. }
  68. if home == "" {
  69. return "", gerror.New("environment keys HOMEDRIVE, HOMEPATH and USERPROFILE are empty")
  70. }
  71. return home, nil
  72. }