forked from git-lfs/git-lfs
/
scanner.go
371 lines (310 loc) · 8.45 KB
/
scanner.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
package lfs
import (
"bufio"
"bytes"
"io"
"os/exec"
"regexp"
"strconv"
"strings"
"time"
"github.com/github/git-lfs/vendor/_nuts/github.com/rubyist/tracerx"
)
const (
// blobSizeCutoff is used to determine which files to scan for Git LFS
// pointers. Any file with a size below this cutoff will be scanned.
blobSizeCutoff = 140
// stdoutBufSize is the size of the buffers given to a sub-process stdout
stdoutBufSize = 16384
// chanBufSize is the size of the channels used to pass data from one
// sub-process to another.
chanBufSize = 100
)
// WrappedPointer wraps a pointer.Pointer and provides the git sha1
// and the file name associated with the object, taken from the
// rev-list output.
type WrappedPointer struct {
Sha1 string
Name string
SrcName string
Size int64
Status string
*Pointer
}
// indexFile is used when scanning the index. It stores the name of
// the file, the status of the file in the index, and, in the case of
// a moved or copied file, the original name of the file.
type indexFile struct {
Name string
SrcName string
Status string
}
var z40 = regexp.MustCompile(`\^?0{40}`)
// ScanRefs takes a ref and returns a slice of WrappedPointer objects
// for all Git LFS pointers it finds for that ref.
func ScanRefs(refLeft, refRight string) ([]*WrappedPointer, error) {
nameMap := make(map[string]string, 0)
start := time.Now()
defer func() {
tracerx.PerformanceSince("scan", start)
}()
revs, err := revListShas(refLeft, refRight, refLeft == "", nameMap)
if err != nil {
return nil, err
}
smallShas, err := catFileBatchCheck(revs)
if err != nil {
return nil, err
}
pointerc, err := catFileBatch(smallShas)
if err != nil {
return nil, err
}
pointers := make([]*WrappedPointer, 0)
for p := range pointerc {
if name, ok := nameMap[p.Sha1]; ok {
p.Name = name
}
pointers = append(pointers, p)
}
return pointers, nil
}
// ScanIndex returns a slice of WrappedPointer objects for all
// Git LFS pointers it finds in the index.
func ScanIndex() ([]*WrappedPointer, error) {
nameMap := make(map[string]*indexFile, 0)
start := time.Now()
defer func() {
tracerx.PerformanceSince("scan-staging", start)
}()
revs, err := revListIndex(false, nameMap)
if err != nil {
return nil, err
}
cachedRevs, err := revListIndex(true, nameMap)
if err != nil {
return nil, err
}
allRevs := make(chan string)
go func() {
seenRevs := make(map[string]bool, 0)
for rev := range revs {
seenRevs[rev] = true
allRevs <- rev
}
for rev := range cachedRevs {
if _, ok := seenRevs[rev]; !ok {
allRevs <- rev
}
}
close(allRevs)
}()
smallShas, err := catFileBatchCheck(allRevs)
if err != nil {
return nil, err
}
pointerc, err := catFileBatch(smallShas)
if err != nil {
return nil, err
}
pointers := make([]*WrappedPointer, 0)
for p := range pointerc {
if e, ok := nameMap[p.Sha1]; ok {
p.Name = e.Name
p.Status = e.Status
p.SrcName = e.SrcName
}
pointers = append(pointers, p)
}
return pointers, nil
}
// revListShas uses git rev-list to return the list of object sha1s
// for the given ref. If all is true, ref is ignored. It returns a
// channel from which sha1 strings can be read.
func revListShas(refLeft, refRight string, all bool, nameMap map[string]string) (chan string, error) {
refArgs := []string{"rev-list", "--objects"}
if all {
refArgs = append(refArgs, "--all")
} else {
refArgs = append(refArgs, "--no-walk")
refArgs = append(refArgs, refLeft)
if refRight != "" && !z40.MatchString(refRight) {
refArgs = append(refArgs, refRight)
}
}
cmd, err := startCommand("git", refArgs...)
if err != nil {
return nil, err
}
cmd.Stdin.Close()
revs := make(chan string, chanBufSize)
go func() {
scanner := bufio.NewScanner(cmd.Stdout)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if len(line) < 40 {
continue
}
sha1 := line[0:40]
if len(line) > 40 {
nameMap[sha1] = line[41:len(line)]
}
revs <- sha1
}
close(revs)
}()
return revs, nil
}
// revListIndex uses git diff-index to return the list of object sha1s
// for in the indexf. It returns a channel from which sha1 strings can be read.
// The namMap will be filled indexFile pointers mapping sha1s to indexFiles.
func revListIndex(cache bool, nameMap map[string]*indexFile) (chan string, error) {
cmdArgs := []string{"diff-index", "-M"}
if cache {
cmdArgs = append(cmdArgs, "--cached")
}
cmdArgs = append(cmdArgs, "HEAD")
cmd, err := startCommand("git", cmdArgs...)
if err != nil {
return nil, err
}
cmd.Stdin.Close()
revs := make(chan string, chanBufSize)
go func() {
scanner := bufio.NewScanner(cmd.Stdout)
for scanner.Scan() {
// Format is:
// :100644 100644 c5b3d83a7542255ec7856487baa5e83d65b1624c 9e82ac1b514be060945392291b5b3108c22f6fe3 M foo.gif
// :<old mode> <new mode> <old sha1> <new sha1> <status>\t<file name>[\t<file name>]
line := scanner.Text()
parts := strings.Split(line, "\t")
if len(parts) < 2 {
continue
}
description := strings.Split(parts[0], " ")
files := parts[1:len(parts)]
if len(description) >= 5 {
status := description[4][0:1]
sha1 := description[3]
if status == "M" {
sha1 = description[2] // This one is modified but not added
}
nameMap[sha1] = &indexFile{files[len(files)-1], files[0], status}
revs <- sha1
}
}
close(revs)
}()
return revs, nil
}
// catFileBatchCheck uses git cat-file --batch-check to get the type
// and size of a git object. Any object that isn't of type blob and
// under the blobSizeCutoff will be ignored. revs is a channel over
// which strings containing git sha1s will be sent. It returns a channel
// from which sha1 strings can be read.
func catFileBatchCheck(revs chan string) (chan string, error) {
cmd, err := startCommand("git", "cat-file", "--batch-check")
if err != nil {
return nil, err
}
smallRevs := make(chan string, chanBufSize)
go func() {
scanner := bufio.NewScanner(cmd.Stdout)
for scanner.Scan() {
line := scanner.Text()
// Format is:
// <sha1> <type> <size>
// type is at a fixed spot, if we see that it's "blob", we can avoid
// splitting the line just to get the size.
if line[41:45] == "blob" {
size, err := strconv.Atoi(line[46:len(line)])
if err != nil {
continue
}
if size < blobSizeCutoff {
smallRevs <- line[0:40]
}
}
}
close(smallRevs)
}()
go func() {
for r := range revs {
cmd.Stdin.Write([]byte(r + "\n"))
}
cmd.Stdin.Close()
}()
return smallRevs, nil
}
// catFileBatch uses git cat-file --batch to get the object contents
// of a git object, given its sha1. The contents will be decoded into
// a Git LFS pointer. revs is a channel over which strings containing Git SHA1s
// will be sent. It returns a channel from which point.Pointers can be read.
func catFileBatch(revs chan string) (chan *WrappedPointer, error) {
cmd, err := startCommand("git", "cat-file", "--batch")
if err != nil {
return nil, err
}
pointers := make(chan *WrappedPointer, chanBufSize)
go func() {
for {
l, err := cmd.Stdout.ReadBytes('\n')
if err != nil {
break
}
// Line is formatted:
// <sha1> <type> <size>
fields := bytes.Fields(l)
s, _ := strconv.Atoi(string(fields[2]))
nbuf := make([]byte, s)
_, err = io.ReadFull(cmd.Stdout, nbuf)
if err != nil {
break // Legit errors
}
p, err := DecodePointer(bytes.NewBuffer(nbuf))
if err == nil {
pointers <- &WrappedPointer{
Sha1: string(fields[0]),
Size: p.Size,
Pointer: p,
}
}
_, err = cmd.Stdout.ReadBytes('\n') // Extra \n inserted by cat-file
if err != nil {
break
}
}
close(pointers)
}()
go func() {
for r := range revs {
cmd.Stdin.Write([]byte(r + "\n"))
}
cmd.Stdin.Close()
}()
return pointers, nil
}
type wrappedCmd struct {
Stdin io.WriteCloser
Stdout *bufio.Reader
*exec.Cmd
}
// startCommand starts up a command and creates a stdin pipe and a buffered
// stdout pipe, wrapped in a wrappedCmd. The stdout buffer will be of stdoutBufSize
// bytes.
func startCommand(command string, args ...string) (*wrappedCmd, error) {
cmd := exec.Command(command, args...)
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
stdin, err := cmd.StdinPipe()
if err != nil {
return nil, err
}
tracerx.Printf("run_command: %s %s", command, strings.Join(args, " "))
if err := cmd.Start(); err != nil {
return nil, err
}
return &wrappedCmd{stdin, bufio.NewReaderSize(stdout, stdoutBufSize), cmd}, nil
}