fullpath.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package util
  2. import (
  3. "path/filepath"
  4. "strings"
  5. )
  6. type FullPath string
  7. func NewFullPath(dir, name string) FullPath {
  8. return FullPath(dir).Child(name)
  9. }
  10. func (fp FullPath) DirAndName() (string, string) {
  11. dir, name := filepath.Split(string(fp))
  12. name = strings.ToValidUTF8(name, "?")
  13. if dir == "/" {
  14. return dir, name
  15. }
  16. if len(dir) < 1 {
  17. return "/", ""
  18. }
  19. return dir[:len(dir)-1], name
  20. }
  21. func (fp FullPath) Name() string {
  22. _, name := filepath.Split(string(fp))
  23. name = strings.ToValidUTF8(name, "?")
  24. return name
  25. }
  26. func (fp FullPath) Child(name string) FullPath {
  27. dir := string(fp)
  28. noPrefix := name
  29. if strings.HasPrefix(name, "/") {
  30. noPrefix = name[1:]
  31. }
  32. if strings.HasSuffix(dir, "/") {
  33. return FullPath(dir + noPrefix)
  34. }
  35. return FullPath(dir + "/" + noPrefix)
  36. }
  37. // AsInode an in-memory only inode representation
  38. func (fp FullPath) AsInode(unixTime int64) uint64 {
  39. inode := uint64(HashStringToLong(string(fp)))
  40. inode = inode + uint64(unixTime)*37
  41. return inode
  42. }
  43. // split, but skipping the root
  44. func (fp FullPath) Split() []string {
  45. if fp == "" || fp == "/" {
  46. return []string{}
  47. }
  48. return strings.Split(string(fp)[1:], "/")
  49. }
  50. func Join(names ...string) string {
  51. return filepath.ToSlash(filepath.Join(names...))
  52. }
  53. func JoinPath(names ...string) FullPath {
  54. return FullPath(Join(names...))
  55. }
  56. func (fp FullPath) IsUnder(other FullPath) bool {
  57. if other == "/" {
  58. return true
  59. }
  60. return strings.HasPrefix(string(fp), string(other)+"/")
  61. }
  62. func StringSplit(separatedValues string, sep string) []string {
  63. if separatedValues == "" {
  64. return nil
  65. }
  66. return strings.Split(separatedValues, sep)
  67. }