| 1 |
package packp |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"fmt" |
| 6 |
"io" |
| 7 |
|
| 8 |
"github.com/go-git/go-git/v5/plumbing" |
| 9 |
"github.com/go-git/go-git/v5/plumbing/format/pktline" |
| 10 |
) |
| 11 |
|
| 12 |
const ( |
| 13 |
shallowLineLen = 48 |
| 14 |
unshallowLineLen = 50 |
| 15 |
) |
| 16 |
|
| 17 |
type ShallowUpdate struct { |
| 18 |
Shallows []plumbing.Hash |
| 19 |
Unshallows []plumbing.Hash |
| 20 |
} |
| 21 |
|
| 22 |
func (r *ShallowUpdate) Decode(reader io.Reader) error { |
| 23 |
s := pktline.NewScanner(reader) |
| 24 |
|
| 25 |
for s.Scan() { |
| 26 |
line := s.Bytes() |
| 27 |
line = bytes.TrimSpace(line) |
| 28 |
|
| 29 |
var err error |
| 30 |
switch { |
| 31 |
case bytes.HasPrefix(line, shallow): |
| 32 |
err = r.decodeShallowLine(line) |
| 33 |
case bytes.HasPrefix(line, unshallow): |
| 34 |
err = r.decodeUnshallowLine(line) |
| 35 |
case bytes.Equal(line, pktline.Flush): |
| 36 |
return nil |
| 37 |
} |
| 38 |
|
| 39 |
if err != nil { |
| 40 |
return err |
| 41 |
} |
| 42 |
} |
| 43 |
|
| 44 |
return s.Err() |
| 45 |
} |
| 46 |
|
| 47 |
func (r *ShallowUpdate) decodeShallowLine(line []byte) error { |
| 48 |
hash, err := r.decodeLine(line, shallow, shallowLineLen) |
| 49 |
if err != nil { |
| 50 |
return err |
| 51 |
} |
| 52 |
|
| 53 |
r.Shallows = append(r.Shallows, hash) |
| 54 |
return nil |
| 55 |
} |
| 56 |
|
| 57 |
func (r *ShallowUpdate) decodeUnshallowLine(line []byte) error { |
| 58 |
hash, err := r.decodeLine(line, unshallow, unshallowLineLen) |
| 59 |
if err != nil { |
| 60 |
return err |
| 61 |
} |
| 62 |
|
| 63 |
r.Unshallows = append(r.Unshallows, hash) |
| 64 |
return nil |
| 65 |
} |
| 66 |
|
| 67 |
func (r *ShallowUpdate) decodeLine(line, prefix []byte, expLen int) (plumbing.Hash, error) { |
| 68 |
if len(line) != expLen { |
| 69 |
return plumbing.ZeroHash, fmt.Errorf("malformed %s%q", prefix, line) |
| 70 |
} |
| 71 |
|
| 72 |
raw := string(line[expLen-40 : expLen]) |
| 73 |
return plumbing.NewHash(raw), nil |
| 74 |
} |
| 75 |
|
| 76 |
func (r *ShallowUpdate) Encode(w io.Writer) error { |
| 77 |
e := pktline.NewEncoder(w) |
| 78 |
|
| 79 |
for _, h := range r.Shallows { |
| 80 |
if err := e.Encodef("%s%s\n", shallow, h.String()); err != nil { |
| 81 |
return err |
| 82 |
} |
| 83 |
} |
| 84 |
|
| 85 |
for _, h := range r.Unshallows { |
| 86 |
if err := e.Encodef("%s%s\n", unshallow, h.String()); err != nil { |
| 87 |
return err |
| 88 |
} |
| 89 |
} |
| 90 |
|
| 91 |
return e.Flush() |
| 92 |
} |