tree_entry.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package git
  5. import (
  6. "sort"
  7. "strings"
  8. "github.com/Unknwon/com"
  9. )
  10. type EntryMode int
  11. // There are only a few file modes in Git. They look like unix file modes, but they can only be
  12. // one of these.
  13. const (
  14. ModeBlob EntryMode = 0100644
  15. ModeExec EntryMode = 0100755
  16. ModeSymlink EntryMode = 0120000
  17. ModeCommit EntryMode = 0160000
  18. ModeTree EntryMode = 0040000
  19. )
  20. type TreeEntry struct {
  21. ID sha1
  22. Type ObjectType
  23. mode EntryMode
  24. name string
  25. ptree *Tree
  26. commited bool
  27. size int64
  28. sized bool
  29. }
  30. func (te *TreeEntry) Name() string {
  31. return te.name
  32. }
  33. func (te *TreeEntry) Size() int64 {
  34. if te.IsDir() {
  35. return 0
  36. }
  37. if te.sized {
  38. return te.size
  39. }
  40. stdout, _, err := com.ExecCmdDir(te.ptree.repo.Path, "git", "cat-file", "-s", te.ID.String())
  41. if err != nil {
  42. return 0
  43. }
  44. te.sized = true
  45. te.size = com.StrTo(strings.TrimSpace(stdout)).MustInt64()
  46. return te.size
  47. }
  48. func (te *TreeEntry) IsSubModule() bool {
  49. return te.mode == ModeCommit
  50. }
  51. func (te *TreeEntry) IsDir() bool {
  52. return te.mode == ModeTree
  53. }
  54. func (te *TreeEntry) EntryMode() EntryMode {
  55. return te.mode
  56. }
  57. func (te *TreeEntry) Blob() *Blob {
  58. return &Blob{
  59. repo: te.ptree.repo,
  60. TreeEntry: te,
  61. }
  62. }
  63. type Entries []*TreeEntry
  64. var sorter = []func(t1, t2 *TreeEntry) bool{
  65. func(t1, t2 *TreeEntry) bool {
  66. return (t1.IsDir() || t1.IsSubModule()) && !t2.IsDir() && !t2.IsSubModule()
  67. },
  68. func(t1, t2 *TreeEntry) bool {
  69. return t1.name < t2.name
  70. },
  71. }
  72. func (bs Entries) Len() int { return len(bs) }
  73. func (bs Entries) Swap(i, j int) { bs[i], bs[j] = bs[j], bs[i] }
  74. func (bs Entries) Less(i, j int) bool {
  75. t1, t2 := bs[i], bs[j]
  76. var k int
  77. for k = 0; k < len(sorter)-1; k++ {
  78. sort := sorter[k]
  79. switch {
  80. case sort(t1, t2):
  81. return true
  82. case sort(t2, t1):
  83. return false
  84. }
  85. }
  86. return sorter[k](t1, t2)
  87. }
  88. func (bs Entries) Sort() {
  89. sort.Sort(bs)
  90. }