gfile_home.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. "github.com/gogf/gf/errors/gcode"
  10. "github.com/gogf/gf/errors/gerror"
  11. "os"
  12. "os/exec"
  13. "os/user"
  14. "runtime"
  15. "strings"
  16. )
  17. // Home returns absolute path of current user's home directory.
  18. // The optional parameter <names> specifies the its sub-folders/sub-files,
  19. // which will be joined with current system separator and returned with the path.
  20. func Home(names ...string) (string, error) {
  21. path, err := getHomePath()
  22. if err != nil {
  23. return "", err
  24. }
  25. for _, name := range names {
  26. path += Separator + name
  27. }
  28. return path, nil
  29. }
  30. // getHomePath returns absolute path of current user's home directory.
  31. func getHomePath() (string, error) {
  32. u, err := user.Current()
  33. if nil == err {
  34. return u.HomeDir, nil
  35. }
  36. if "windows" == runtime.GOOS {
  37. return homeWindows()
  38. }
  39. return homeUnix()
  40. }
  41. // homeUnix retrieves and returns the home on unix system.
  42. func homeUnix() (string, error) {
  43. if home := os.Getenv("HOME"); home != "" {
  44. return home, nil
  45. }
  46. var stdout bytes.Buffer
  47. cmd := exec.Command("sh", "-c", "eval echo ~$USER")
  48. cmd.Stdout = &stdout
  49. if err := cmd.Run(); err != nil {
  50. return "", err
  51. }
  52. result := strings.TrimSpace(stdout.String())
  53. if result == "" {
  54. return "", gerror.NewCode(gcode.CodeInternalError, "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.NewCode(gcode.CodeOperationFailed, "HOMEDRIVE, HOMEPATH, and USERPROFILE are blank")
  70. }
  71. return home, nil
  72. }