本站源代码
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

82 lines
2.4KB

  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. "gopkg.in/src-d/go-git.v4/plumbing/filemode"
  10. "gopkg.in/src-d/go-git.v4/plumbing/object"
  11. )
  12. // ParseTreeEntries parses the output of a `git ls-tree` command.
  13. func ParseTreeEntries(data []byte) ([]*TreeEntry, error) {
  14. return parseTreeEntries(data, nil)
  15. }
  16. func parseTreeEntries(data []byte, ptree *Tree) ([]*TreeEntry, error) {
  17. entries := make([]*TreeEntry, 0, 10)
  18. for pos := 0; pos < len(data); {
  19. // expect line to be of the form "<mode> <type> <sha>\t<filename>"
  20. entry := new(TreeEntry)
  21. entry.gogitTreeEntry = &object.TreeEntry{}
  22. entry.ptree = ptree
  23. if pos+6 > len(data) {
  24. return nil, fmt.Errorf("Invalid ls-tree output: %s", string(data))
  25. }
  26. switch string(data[pos : pos+6]) {
  27. case "100644":
  28. entry.gogitTreeEntry.Mode = filemode.Regular
  29. pos += 12 // skip over "100644 blob "
  30. case "100755":
  31. entry.gogitTreeEntry.Mode = filemode.Executable
  32. pos += 12 // skip over "100755 blob "
  33. case "120000":
  34. entry.gogitTreeEntry.Mode = filemode.Symlink
  35. pos += 12 // skip over "120000 blob "
  36. case "160000":
  37. entry.gogitTreeEntry.Mode = filemode.Submodule
  38. pos += 14 // skip over "160000 object "
  39. case "040000":
  40. entry.gogitTreeEntry.Mode = filemode.Dir
  41. pos += 12 // skip over "040000 tree "
  42. default:
  43. return nil, fmt.Errorf("unknown type: %v", string(data[pos:pos+6]))
  44. }
  45. if pos+40 > len(data) {
  46. return nil, fmt.Errorf("Invalid ls-tree output: %s", string(data))
  47. }
  48. id, err := NewIDFromString(string(data[pos : pos+40]))
  49. if err != nil {
  50. return nil, fmt.Errorf("Invalid ls-tree output: %v", err)
  51. }
  52. entry.ID = id
  53. entry.gogitTreeEntry.Hash = id
  54. pos += 41 // skip over sha and trailing space
  55. end := pos + bytes.IndexByte(data[pos:], '\n')
  56. if end < pos {
  57. return nil, fmt.Errorf("Invalid ls-tree output: %s", string(data))
  58. }
  59. // In case entry name is surrounded by double quotes(it happens only in git-shell).
  60. if data[pos] == '"' {
  61. entry.gogitTreeEntry.Name, err = strconv.Unquote(string(data[pos:end]))
  62. if err != nil {
  63. return nil, fmt.Errorf("Invalid ls-tree output: %v", err)
  64. }
  65. } else {
  66. entry.gogitTreeEntry.Name = string(data[pos:end])
  67. }
  68. pos = end + 1
  69. entries = append(entries, entry)
  70. }
  71. return entries, nil
  72. }
上海开阖软件有限公司 沪ICP备12045867号-1