gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2024 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package git
  4. import (
  5. "bytes"
  6. "fmt"
  7. "strconv"
  8. "strings"
  9. "code.gitea.io/gitea/modules/optional"
  10. )
  11. var sepSpace = []byte{' '}
  12. type LsTreeEntry struct {
  13. ID ObjectID
  14. EntryMode EntryMode
  15. Name string
  16. Size optional.Option[int64]
  17. }
  18. func parseLsTreeLine(line []byte) (*LsTreeEntry, error) {
  19. // expect line to be of the form:
  20. // <mode> <type> <sha> <space-padded-size>\t<filename>
  21. // <mode> <type> <sha>\t<filename>
  22. var err error
  23. posTab := bytes.IndexByte(line, '\t')
  24. if posTab == -1 {
  25. return nil, fmt.Errorf("invalid ls-tree output (no tab): %q", line)
  26. }
  27. entry := new(LsTreeEntry)
  28. entryAttrs := line[:posTab]
  29. entryName := line[posTab+1:]
  30. entryMode, entryAttrs, _ := bytes.Cut(entryAttrs, sepSpace)
  31. _ /* entryType */, entryAttrs, _ = bytes.Cut(entryAttrs, sepSpace) // the type is not used, the mode is enough to determine the type
  32. entryObjectID, entryAttrs, _ := bytes.Cut(entryAttrs, sepSpace)
  33. if len(entryAttrs) > 0 {
  34. entrySize := entryAttrs // the last field is the space-padded-size
  35. size, _ := strconv.ParseInt(strings.TrimSpace(string(entrySize)), 10, 64)
  36. entry.Size = optional.Some(size)
  37. }
  38. entry.EntryMode, err = ParseEntryMode(string(entryMode))
  39. if err != nil || entry.EntryMode == EntryModeNoEntry {
  40. return nil, fmt.Errorf("invalid ls-tree output (invalid mode): %q, err: %w", line, err)
  41. }
  42. entry.ID, err = NewIDFromString(string(entryObjectID))
  43. if err != nil {
  44. return nil, fmt.Errorf("invalid ls-tree output (invalid object id): %q, err: %w", line, err)
  45. }
  46. if len(entryName) > 0 && entryName[0] == '"' {
  47. entry.Name, err = strconv.Unquote(string(entryName))
  48. if err != nil {
  49. return nil, fmt.Errorf("invalid ls-tree output (invalid name): %q, err: %w", line, err)
  50. }
  51. } else {
  52. entry.Name = string(entryName)
  53. }
  54. return entry, nil
  55. }