本站源代码
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.

91 lines
2.0KB

  1. package noder
  2. import (
  3. "bytes"
  4. "strings"
  5. )
  6. // Path values represent a noder and its ancestors. The root goes first
  7. // and the actual final noder the path is referring to will be the last.
  8. //
  9. // A path implements the Noder interface, redirecting all the interface
  10. // calls to its final noder.
  11. //
  12. // Paths build from an empty Noder slice are not valid paths and should
  13. // not be used.
  14. type Path []Noder
  15. // String returns the full path of the final noder as a string, using
  16. // "/" as the separator.
  17. func (p Path) String() string {
  18. var buf bytes.Buffer
  19. sep := ""
  20. for _, e := range p {
  21. _, _ = buf.WriteString(sep)
  22. sep = "/"
  23. _, _ = buf.WriteString(e.Name())
  24. }
  25. return buf.String()
  26. }
  27. // Last returns the final noder in the path.
  28. func (p Path) Last() Noder {
  29. return p[len(p)-1]
  30. }
  31. // Hash returns the hash of the final noder of the path.
  32. func (p Path) Hash() []byte {
  33. return p.Last().Hash()
  34. }
  35. // Name returns the name of the final noder of the path.
  36. func (p Path) Name() string {
  37. return p.Last().Name()
  38. }
  39. // IsDir returns if the final noder of the path is a directory-like
  40. // noder.
  41. func (p Path) IsDir() bool {
  42. return p.Last().IsDir()
  43. }
  44. // Children returns the children of the final noder in the path.
  45. func (p Path) Children() ([]Noder, error) {
  46. return p.Last().Children()
  47. }
  48. // NumChildren returns the number of children the final noder of the
  49. // path has.
  50. func (p Path) NumChildren() (int, error) {
  51. return p.Last().NumChildren()
  52. }
  53. // Compare returns -1, 0 or 1 if the path p is smaller, equal or bigger
  54. // than other, in "directory order"; for example:
  55. //
  56. // "a" < "b"
  57. // "a/b/c/d/z" < "b"
  58. // "a/b/a" > "a/b"
  59. func (p Path) Compare(other Path) int {
  60. i := 0
  61. for {
  62. switch {
  63. case len(other) == len(p) && i == len(p):
  64. return 0
  65. case i == len(other):
  66. return 1
  67. case i == len(p):
  68. return -1
  69. default:
  70. // We do *not* normalize Unicode here. CGit doesn't.
  71. // https://github.com/src-d/go-git/issues/1057
  72. cmp := strings.Compare(p[i].Name(), other[i].Name())
  73. if cmp != 0 {
  74. return cmp
  75. }
  76. }
  77. i++
  78. }
  79. }
上海开阖软件有限公司 沪ICP备12045867号-1