pathutil_unix.go 878 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. //go:build aix || darwin || dragonfly || freebsd || (js && wasm) || nacl || linux || netbsd || openbsd || solaris
  2. package pathutil
  3. import (
  4. "errors"
  5. "io/fs"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. )
  10. // UserHomeDir returns the home directory of the current user.
  11. func UserHomeDir() string {
  12. if home := os.Getenv("HOME"); home != "" {
  13. return home
  14. }
  15. return "/"
  16. }
  17. // Exists returns true if the specified path exists.
  18. func Exists(path string) bool {
  19. _, err := os.Stat(path)
  20. return err == nil || errors.Is(err, fs.ErrExist)
  21. }
  22. // ExpandHome substitutes `~` and `$HOME` at the start of the specified `path`.
  23. func ExpandHome(path string) string {
  24. home := UserHomeDir()
  25. if path == "" || home == "" {
  26. return path
  27. }
  28. if path[0] == '~' {
  29. return filepath.Join(home, path[1:])
  30. }
  31. if strings.HasPrefix(path, "$HOME") {
  32. return filepath.Join(home, path[5:])
  33. }
  34. return path
  35. }