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.

81 lines
2.2 KiB

  1. // Copyright 2018 The Gitea 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. "bytes"
  7. "fmt"
  8. "strconv"
  9. )
  10. // ParseTreeEntries parses the output of a `git ls-tree` command.
  11. func ParseTreeEntries(data []byte) ([]*TreeEntry, error) {
  12. return parseTreeEntries(data, nil)
  13. }
  14. func parseTreeEntries(data []byte, ptree *Tree) ([]*TreeEntry, error) {
  15. entries := make([]*TreeEntry, 0, 10)
  16. for pos := 0; pos < len(data); {
  17. // expect line to be of the form "<mode> <type> <sha>\t<filename>"
  18. entry := new(TreeEntry)
  19. entry.ptree = ptree
  20. if pos+6 > len(data) {
  21. return nil, fmt.Errorf("Invalid ls-tree output: %s", string(data))
  22. }
  23. switch string(data[pos : pos+6]) {
  24. case "100644":
  25. entry.mode = EntryModeBlob
  26. entry.Type = ObjectBlob
  27. pos += 12 // skip over "100644 blob "
  28. case "100755":
  29. entry.mode = EntryModeExec
  30. entry.Type = ObjectBlob
  31. pos += 12 // skip over "100755 blob "
  32. case "120000":
  33. entry.mode = EntryModeSymlink
  34. entry.Type = ObjectBlob
  35. pos += 12 // skip over "120000 blob "
  36. case "160000":
  37. entry.mode = EntryModeCommit
  38. entry.Type = ObjectCommit
  39. pos += 14 // skip over "160000 object "
  40. case "040000":
  41. entry.mode = EntryModeTree
  42. entry.Type = ObjectTree
  43. pos += 12 // skip over "040000 tree "
  44. default:
  45. return nil, fmt.Errorf("unknown type: %v", string(data[pos:pos+6]))
  46. }
  47. if pos+40 > len(data) {
  48. return nil, fmt.Errorf("Invalid ls-tree output: %s", string(data))
  49. }
  50. id, err := NewIDFromString(string(data[pos : pos+40]))
  51. if err != nil {
  52. return nil, fmt.Errorf("Invalid ls-tree output: %v", err)
  53. }
  54. entry.ID = id
  55. pos += 41 // skip over sha and trailing space
  56. end := pos + bytes.IndexByte(data[pos:], '\n')
  57. if end < pos {
  58. return nil, fmt.Errorf("Invalid ls-tree output: %s", string(data))
  59. }
  60. // In case entry name is surrounded by double quotes(it happens only in git-shell).
  61. if data[pos] == '"' {
  62. entry.name, err = strconv.Unquote(string(data[pos:end]))
  63. if err != nil {
  64. return nil, fmt.Errorf("Invalid ls-tree output: %v", err)
  65. }
  66. } else {
  67. entry.name = string(data[pos:end])
  68. }
  69. pos = end + 1
  70. entries = append(entries, entry)
  71. }
  72. return entries, nil
  73. }