gfile_home.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright 2020 gf Author(https://github.com/gogf/gf). 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. "errors"
  10. "os"
  11. "os/exec"
  12. "os/user"
  13. "runtime"
  14. "strings"
  15. )
  16. // Home returns absolute path of current user's home directory.
  17. // The optional parameter <names> specifies the its 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 "windows" == runtime.GOOS {
  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. return "", err
  50. }
  51. result := strings.TrimSpace(stdout.String())
  52. if result == "" {
  53. return "", errors.New("blank output when reading home directory")
  54. }
  55. return result, nil
  56. }
  57. // homeWindows retrieves and returns the home on windows system.
  58. func homeWindows() (string, error) {
  59. var (
  60. drive = os.Getenv("HOMEDRIVE")
  61. path = os.Getenv("HOMEPATH")
  62. home = drive + path
  63. )
  64. if drive == "" || path == "" {
  65. home = os.Getenv("USERPROFILE")
  66. }
  67. if home == "" {
  68. return "", errors.New("HOMEDRIVE, HOMEPATH, and USERPROFILE are blank")
  69. }
  70. return home, nil
  71. }