pathutil_plan9.go 763 B

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