main.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package pathx
  2. // The package implements crossplatform structured
  3. // paths.
  4. import (
  5. //"fmt"
  6. "path"
  7. fp "path/filepath"
  8. "strings"
  9. )
  10. type Value string
  11. type Path struct {
  12. Values []Value
  13. IsAbs bool
  14. }
  15. func (p Path) Append(values ...string) Path {
  16. for _, v := range values {
  17. p.Values = append(p.Values, Value(v))
  18. }
  19. return p
  20. }
  21. func From(p string) Path {
  22. ret := Path{}
  23. if len(p) == 0 {
  24. return ret
  25. }
  26. p = path.Clean(p)
  27. if p[0] == '/' {
  28. ret.IsAbs = true
  29. }
  30. p, _ = strings.CutSuffix(p, "/")
  31. svalues := strings.Split(p, "/")
  32. values := make([]Value, len(svalues))
  33. for i, s := range svalues {
  34. values[i] = Value(s)
  35. }
  36. ret.Values = values
  37. return ret
  38. }
  39. func FromReal(p string) Path {
  40. ret := From(fp.ToSlash(p))
  41. //fmt.Println("from real:", ret)
  42. return ret
  43. }
  44. func (v Value) IsValid() bool {
  45. return v.Err() == nil
  46. }
  47. func (v Value) Err() error {
  48. return nil
  49. }
  50. func (p Path) StringValues() []string {
  51. ret := []string{}
  52. if p.IsAbs {
  53. ret = append(ret, "/")
  54. }
  55. for _, v := range p.Values {
  56. ret = append(ret, string(v))
  57. }
  58. return ret
  59. }
  60. func (p Path) Real() string {
  61. return strings.Join(p.StringValues(), string(fp.Separator))
  62. }
  63. func (p Path) String() string {
  64. ret := ""
  65. if p.IsAbs {
  66. ret = "/"
  67. }
  68. ret += path.Join(p.StringValues()...)
  69. return ret
  70. }
  71. func (p Path) IsValid() bool {
  72. for _, v := range p.Values {
  73. if !v.IsValid() {
  74. return false
  75. }
  76. }
  77. return true
  78. }
  79. func (p Path) Err() error {
  80. for _, v := range p.Values {
  81. if !v.IsValid() {
  82. return v.Err()
  83. }
  84. }
  85. return nil
  86. }