File utilities and wrappers that may be useful for some projects.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

40 lines
897B

  1. // Path helper and convenience utilities.
  2. package fileutils
  3. import (
  4. "os"
  5. "path/filepath"
  6. )
  7. // AbsPath expands and calculates some UNIX-specific path expansions while also
  8. // returning either the absolute path as determined via `filepath.Abs` or the
  9. // original string if Abs() returns an error. At the time of this writing, path
  10. // expansions are limited to ~ for the user's current HOME directory, which is
  11. // deduced from the value of the $HOME environment variable.
  12. //
  13. // Behavior under other operating systems may differ.
  14. func AbsPath(s string) string {
  15. var err error
  16. var path string
  17. home, exists := os.LookupEnv("HOME")
  18. if exists {
  19. if s[0] == '~' {
  20. s = s[1:]
  21. if home[len(home)-1] != '/' {
  22. home = home + "/"
  23. }
  24. if s[0] == '/' {
  25. s = home + s[1:]
  26. } else {
  27. s = home + s
  28. }
  29. }
  30. }
  31. if path, err = filepath.Abs(s); err != nil {
  32. return s
  33. }
  34. return path
  35. }