fullpath.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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) IsLongerFileName(maxFilenameLength uint32) bool {
  27. if maxFilenameLength == 0 {
  28. return false
  29. }
  30. return uint32(len([]byte(fp.Name()))) > maxFilenameLength
  31. }
  32. func (fp FullPath) Child(name string) FullPath {
  33. dir := string(fp)
  34. noPrefix := name
  35. if strings.HasPrefix(name, "/") {
  36. noPrefix = name[1:]
  37. }
  38. if strings.HasSuffix(dir, "/") {
  39. return FullPath(dir + noPrefix)
  40. }
  41. return FullPath(dir + "/" + noPrefix)
  42. }
  43. // AsInode an in-memory only inode representation
  44. func (fp FullPath) AsInode(unixTime int64) uint64 {
  45. inode := uint64(HashStringToLong(string(fp)))
  46. inode = inode + uint64(unixTime)*37
  47. return inode
  48. }
  49. // split, but skipping the root
  50. func (fp FullPath) Split() []string {
  51. if fp == "" || fp == "/" {
  52. return []string{}
  53. }
  54. return strings.Split(string(fp)[1:], "/")
  55. }
  56. func Join(names ...string) string {
  57. return filepath.ToSlash(filepath.Join(names...))
  58. }
  59. func JoinPath(names ...string) FullPath {
  60. return FullPath(Join(names...))
  61. }
  62. func (fp FullPath) IsUnder(other FullPath) bool {
  63. if other == "/" {
  64. return true
  65. }
  66. return strings.HasPrefix(string(fp), string(other)+"/")
  67. }
  68. func StringSplit(separatedValues string, sep string) []string {
  69. if separatedValues == "" {
  70. return nil
  71. }
  72. return strings.Split(separatedValues, sep)
  73. }