| 1 | package git |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "bytes" |
| 6 | "io" |
| 7 | "strconv" |
| 8 | "strings" |
| 9 | ) |
| 10 | |
| 11 | // An entry from ls-tree or rev-list including a blob sha and tree path |
| 12 | type TreeBlob struct { |
| 13 | Oid string |
| 14 | Size int64 |
| 15 | Mode int32 |
| 16 | Filename string |
| 17 | } |
| 18 | |
| 19 | type LsTreeScanner struct { |
| 20 | s *bufio.Scanner |
| 21 | tree *TreeBlob |
| 22 | } |
| 23 | |
| 24 | func NewLsTreeScanner(r io.Reader) *LsTreeScanner { |
| 25 | s := bufio.NewScanner(r) |
| 26 | s.Split(scanNullLines) |
| 27 | return &LsTreeScanner{s: s} |
| 28 | } |
| 29 | |
| 30 | func (s *LsTreeScanner) TreeBlob() *TreeBlob { |
| 31 | return s.tree |
| 32 | } |
| 33 | |
| 34 | func (s *LsTreeScanner) Err() error { |
| 35 | return nil |
| 36 | } |
| 37 | |
| 38 | func (s *LsTreeScanner) Scan() bool { |
| 39 | t, hasNext := s.next() |
| 40 | s.tree = t |
| 41 | return hasNext |
| 42 | } |
| 43 | |
| 44 | func (s *LsTreeScanner) next() (*TreeBlob, bool) { |
| 45 | hasNext := s.s.Scan() |
| 46 | line := s.s.Text() |
| 47 | parts := strings.SplitN(line, "\t", 2) |
| 48 | if len(parts) < 2 { |
| 49 | return nil, hasNext |
| 50 | } |
| 51 | |
| 52 | attrs := strings.SplitN(parts[0], " ", 4) |
| 53 | if len(attrs) < 4 { |
| 54 | return nil, hasNext |
| 55 | } |
| 56 | |
| 57 | mode, err := strconv.ParseInt(strings.TrimSpace(attrs[0]), 8, 32) |
| 58 | if err != nil { |
| 59 | return nil, hasNext |
| 60 | } |
| 61 | |
| 62 | if attrs[1] != "blob" { |
| 63 | return nil, hasNext |
| 64 | } |
| 65 | |
| 66 | sz, err := strconv.ParseInt(strings.TrimSpace(attrs[3]), 10, 64) |
| 67 | if err != nil { |
| 68 | return nil, hasNext |
| 69 | } |
| 70 | |
| 71 | oid := attrs[2] |
| 72 | filename := parts[1] |
| 73 | return &TreeBlob{Oid: oid, Size: sz, Mode: int32(mode), Filename: filename}, hasNext |
| 74 | } |
| 75 | |
| 76 | func scanNullLines(data []byte, atEOF bool) (advance int, token []byte, err error) { |
| 77 | if atEOF && len(data) == 0 { |
| 78 | return 0, nil, nil |
| 79 | } |
| 80 | |
| 81 | if i := bytes.IndexByte(data, '\000'); i >= 0 { |
| 82 | // We have a full null-terminated line. |
| 83 | return i + 1, data[0:i], nil |
| 84 | } |
| 85 | |
| 86 | // If we're at EOF, we have a final, non-terminated line. Return it. |
| 87 | if atEOF { |
| 88 | return len(data), data, nil |
| 89 | } |
| 90 | |
| 91 | // Request more data. |
| 92 | return 0, nil, nil |
| 93 | } |