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

93 lines
1.7KB

  1. package packp
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "gopkg.in/src-d/go-git.v4/plumbing"
  7. "gopkg.in/src-d/go-git.v4/plumbing/format/pktline"
  8. )
  9. const (
  10. shallowLineLen = 48
  11. unshallowLineLen = 50
  12. )
  13. type ShallowUpdate struct {
  14. Shallows []plumbing.Hash
  15. Unshallows []plumbing.Hash
  16. }
  17. func (r *ShallowUpdate) Decode(reader io.Reader) error {
  18. s := pktline.NewScanner(reader)
  19. for s.Scan() {
  20. line := s.Bytes()
  21. line = bytes.TrimSpace(line)
  22. var err error
  23. switch {
  24. case bytes.HasPrefix(line, shallow):
  25. err = r.decodeShallowLine(line)
  26. case bytes.HasPrefix(line, unshallow):
  27. err = r.decodeUnshallowLine(line)
  28. case bytes.Equal(line, pktline.Flush):
  29. return nil
  30. }
  31. if err != nil {
  32. return err
  33. }
  34. }
  35. return s.Err()
  36. }
  37. func (r *ShallowUpdate) decodeShallowLine(line []byte) error {
  38. hash, err := r.decodeLine(line, shallow, shallowLineLen)
  39. if err != nil {
  40. return err
  41. }
  42. r.Shallows = append(r.Shallows, hash)
  43. return nil
  44. }
  45. func (r *ShallowUpdate) decodeUnshallowLine(line []byte) error {
  46. hash, err := r.decodeLine(line, unshallow, unshallowLineLen)
  47. if err != nil {
  48. return err
  49. }
  50. r.Unshallows = append(r.Unshallows, hash)
  51. return nil
  52. }
  53. func (r *ShallowUpdate) decodeLine(line, prefix []byte, expLen int) (plumbing.Hash, error) {
  54. if len(line) != expLen {
  55. return plumbing.ZeroHash, fmt.Errorf("malformed %s%q", prefix, line)
  56. }
  57. raw := string(line[expLen-40 : expLen])
  58. return plumbing.NewHash(raw), nil
  59. }
  60. func (r *ShallowUpdate) Encode(w io.Writer) error {
  61. e := pktline.NewEncoder(w)
  62. for _, h := range r.Shallows {
  63. if err := e.Encodef("%s%s\n", shallow, h.String()); err != nil {
  64. return err
  65. }
  66. }
  67. for _, h := range r.Unshallows {
  68. if err := e.Encodef("%s%s\n", unshallow, h.String()); err != nil {
  69. return err
  70. }
  71. }
  72. return e.Flush()
  73. }
上海开阖软件有限公司 沪ICP备12045867号-1