Debian Codegraph @

lfs/gitscanner_log.go

raw symbols SCIP
1 package lfs
2
3 import (
4 "bufio"
5 "bytes"
6 "fmt"
7 "io"
8 "regexp"
9 "strconv"
10 "strings"
11 "time"
12
13 "github.com/git-lfs/git-lfs/v3/errors"
14 "github.com/git-lfs/git-lfs/v3/filepathfilter"
15 "github.com/git-lfs/git-lfs/v3/git"
16 "github.com/git-lfs/git-lfs/v3/subprocess"
17 "github.com/git-lfs/git-lfs/v3/tr"
18 "github.com/rubyist/tracerx"
19 )
20
21 // When scanning diffs with parseScannerLogOutput(), the direction of diff
22 // to include data from, i.e., '+' or '-'. Depending on what you're scanning
23 // for either might be useful.
24 type LogDiffDirection byte
25
26 const (
27 LogDiffAdditions = LogDiffDirection('+') // include '+' diffs
28 LogDiffDeletions = LogDiffDirection('-') // include '-' diffs
29 )
30
31 var (
32 // Arguments to append to a git log call which will limit the output to
33 // lfs changes and format the output suitable for parseLogOutput.. method(s)
34 logLfsSearchArgs = []string{
35 "--no-ext-diff",
36 "--no-textconv",
37 "--color=never",
38 "-G", "oid sha256:", // only diffs which include an lfs file SHA change
39 "-p", // include diff so we can read the SHA
40 "-U12", // Make sure diff context is always big enough to support 10 extension lines to get whole pointer
41 `--format=lfs-commit-sha: %H %P`, // just a predictable commit header we can detect
42 }
43 )
44
45 type gitscannerResult struct {
46 Pointer *WrappedPointer
47 Err error
48 }
49
50 func scanUnpushed(cb GitScannerFoundPointer, remote string) error {
51 logArgs := []string{
52 "--branches", "--tags", // include all locally referenced commits
53 "--not"} // but exclude everything that comes after
54
55 if len(remote) == 0 {
56 logArgs = append(logArgs, "--remotes")
57 } else {
58 logArgs = append(logArgs, fmt.Sprintf("--remotes=%v", remote))
59 }
60
61 // Add standard search args to find lfs references
62 logArgs = append(logArgs, logLfsSearchArgs...)
63
64 cmd, err := git.Log(logArgs...)
65 if err != nil {
66 return err
67 }
68
69 parseScannerLogOutput(cb, LogDiffAdditions, cmd, nil)
70 return nil
71 }
72
73 func scanStashed(cb GitScannerFoundPointer) error {
74 // Stashes are actually 2-3 commits, each containing one of:
75 // 1. Working copy (WIP) modified files
76 // 2. Index changes
77 // 3. Untracked files (but only if "git stash -u" was used)
78 // The first of these, the WIP commit, is a merge whose first parent
79 // is HEAD and whose other parent(s) are commits 2 and 3 above.
80
81 // We need to get the individual diff of each of these commits to
82 // ensure we have all of the LFS objects referenced by the stash,
83 // so a future "git stash pop" can restore them all.
84
85 // First we get the list of SHAs of the WIP merge commits from the
86 // reflog using "git log -g --format=%h refs/stash --". Because
87 // older Git versions (at least <=2.7) don't report merge parents in
88 // the reflog, we can't extract the parent SHAs from "Merge:" lines
89 // in the log; we can, however, use the "git log -m" option to force
90 // an individual diff with the first merge parent in a second step.
91 logArgs := []string{"-g", "--format=%h", "refs/stash", "--"}
92
93 cmd, err := git.Log(logArgs...)
94 if err != nil {
95 return err
96 }
97
98 scanner := bufio.NewScanner(cmd.Stdout)
99
100 var stashMergeShas []string
101 for scanner.Scan() {
102 stashMergeSha := strings.TrimSpace(scanner.Text())
103 stashMergeShas = append(stashMergeShas, fmt.Sprintf("%v^..%v", stashMergeSha, stashMergeSha))
104 }
105 if err := scanner.Err(); err != nil {
106 errors.New(tr.Tr.Get("error while scanning `git log` for stashed refs: %v", err))
107 }
108 err = cmd.Wait()
109 if err != nil {
110 // Ignore this error, it really only happens when there's no refs/stash
111 return nil
112 }
113
114 // We can use the log parser if we provide the -m and --first-parent
115 // options to get the first WIP merge diff shown individually, then
116 // no additional options to get the second index merge diff and
117 // possible third untracked files merge diff in a subsequent step.
118 stashMergeLogArgs := [][]string{{"-m", "--first-parent"}, {}}
119
120 for _, logArgs := range stashMergeLogArgs {
121 // Add standard search args to find lfs references
122 logArgs = append(logArgs, logLfsSearchArgs...)
123
124 logArgs = append(logArgs, stashMergeShas...)
125
126 cmd, err = git.Log(logArgs...)
127 if err != nil {
128 return err
129 }
130
131 parseScannerLogOutput(cb, LogDiffAdditions, cmd, nil)
132 }
133
134 return nil
135 }
136
137 func parseScannerLogOutput(cb GitScannerFoundPointer, direction LogDiffDirection, cmd *subprocess.BufferedCmd, filter *filepathfilter.Filter) {
138 ch := make(chan gitscannerResult, chanBufSize)
139
140 cherr := make(chan []byte)
141
142 go func() {
143 stderr, _ := io.ReadAll(cmd.Stderr)
144 cherr <- stderr
145 close(cherr)
146 }()
147
148 go func() {
149 scanner := newLogScanner(direction, cmd.Stdout)
150 scanner.Filter = filter
151 for scanner.Scan() {
152 if p := scanner.Pointer(); p != nil {
153 ch <- gitscannerResult{Pointer: p}
154 }
155 }
156 if err := scanner.Err(); err != nil {
157 io.ReadAll(cmd.Stdout)
158 ch <- gitscannerResult{Err: errors.New(tr.Tr.Get("error while scanning `git log`: %v", err))}
159 }
160 stderr := <-cherr
161 err := cmd.Wait()
162 if err != nil {
163 ch <- gitscannerResult{Err: errors.New(tr.Tr.Get("error in `git log`: %v %v", err, string(stderr)))}
164 }
165 close(ch)
166 }()
167
168 cmd.Stdin.Close()
169 for result := range ch {
170 cb(result.Pointer, result.Err)
171 }
172 }
173
174 // logPreviousVersions scans history for all previous versions of LFS pointers
175 // from 'since' up to (but not including) the final state at ref
176 func logPreviousSHAs(cb GitScannerFoundPointer, ref string, filter *filepathfilter.Filter, since time.Time) error {
177 logArgs := []string{
178 fmt.Sprintf("--since=%v", git.FormatGitDate(since)),
179 }
180 // Add standard search args to find lfs references
181 logArgs = append(logArgs, logLfsSearchArgs...)
182 // ending at ref
183 logArgs = append(logArgs, ref)
184
185 cmd, err := git.Log(logArgs...)
186 if err != nil {
187 return err
188 }
189
190 parseScannerLogOutput(cb, LogDiffDeletions, cmd, filter)
191 return nil
192 }
193
194 // logScanner parses log output formatted as per logLfsSearchArgs & returns
195 // pointers.
196 type logScanner struct {
197 // Filter will ensure file paths matching the include patterns, or not matching
198 // the exclude patterns are skipped.
199 Filter *filepathfilter.Filter
200
201 r *bufio.Reader
202 err error
203 dir LogDiffDirection
204 pointer *WrappedPointer
205
206 pointerData *bytes.Buffer
207 currentFilename string
208 currentFileIncluded bool
209
210 commitHeaderRegex *regexp.Regexp
211 fileHeaderRegex *regexp.Regexp
212 fileMergeHeaderRegex *regexp.Regexp
213 pointerDataRegex *regexp.Regexp
214 }
215
216 // dir: whether to include results from + or - diffs
217 // r: a stream of output from git log with at least logLfsSearchArgs specified
218 func newLogScanner(dir LogDiffDirection, r io.Reader) *logScanner {
219 return &logScanner{
220 r: bufio.NewReader(r),
221 dir: dir,
222 pointerData: &bytes.Buffer{},
223 currentFileIncluded: true,
224
225 // no need to compile these regexes on every `git-lfs` call, just ones that
226 // use the scanner.
227 commitHeaderRegex: regexp.MustCompile(fmt.Sprintf(`^lfs-commit-sha: (%s)(?: (%s))*`, git.ObjectIDRegex, git.ObjectIDRegex)),
228 fileHeaderRegex: regexp.MustCompile(`^diff --git "?a\/(.+?)\s+"?b\/(.+)`),
229 fileMergeHeaderRegex: regexp.MustCompile(`^diff --cc (.+)`),
230 pointerDataRegex: regexp.MustCompile(`^([\+\- ])(version https://git-lfs|oid sha256|size|ext-).*$`),
231 }
232 }
233
234 func (s *logScanner) Pointer() *WrappedPointer {
235 return s.pointer
236 }
237
238 func (s *logScanner) Err() error {
239 return s.err
240 }
241
242 func (s *logScanner) Scan() bool {
243 s.pointer = nil
244 p, canScan := s.scan()
245 s.pointer = p
246 return canScan
247 }
248
249 // Utility func used at several points below (keep in narrow scope)
250 func (s *logScanner) finishLastPointer() *WrappedPointer {
251 if s.pointerData.Len() == 0 || !s.currentFileIncluded {
252 return nil
253 }
254
255 p, err := DecodePointer(s.pointerData)
256 s.pointerData.Reset()
257
258 if err == nil {
259 return &WrappedPointer{Name: s.currentFilename, Pointer: p}
260 } else {
261 tracerx.Printf("Unable to parse pointer from log: %v", err)
262 return nil
263 }
264 }
265
266 // For each commit we'll get something like this:
267 /*
268 lfs-commit-sha: 60fde3d23553e10a55e2a32ed18c20f65edd91e7 e2eaf1c10b57da7b98eb5d722ec5912ddeb53ea1
269
270 diff --git a/1D_Noise.png b/1D_Noise.png
271 new file mode 100644
272 index 0000000..2622b4a
273 --- /dev/null
274 +++ b/1D_Noise.png
275 @@ -0,0 +1,3 @@
276 +version https://git-lfs.github.com/spec/v1
277 +oid sha256:f5d84da40ab1f6aa28df2b2bf1ade2cdcd4397133f903c12b4106641b10e1ed6
278 +size 1289
279 */
280 // There can be multiple diffs per commit (multiple binaries)
281 // Also when a binary is changed the diff will include a '-' line for the old SHA
282 func (s *logScanner) scan() (*WrappedPointer, bool) {
283 for {
284 line, err := s.r.ReadString('\n')
285
286 if err != nil && err != io.EOF {
287 s.err = err
288 return nil, false
289 }
290
291 // remove trailing newline delimiter and optional single carriage return
292 line = strings.TrimSuffix(strings.TrimRight(line, "\n"), "\r")
293
294 if match := s.commitHeaderRegex.FindStringSubmatch(line); match != nil {
295 // Currently we're not pulling out commit groupings, but could if we wanted
296 // This just acts as a delimiter for finishing a multiline pointer
297 if p := s.finishLastPointer(); p != nil {
298 return p, true
299 }
300 } else if match := s.fileHeaderRegex.FindStringSubmatch(line); match != nil {
301 // Finding a regular file header
302 p := s.finishLastPointer()
303
304 // Pertinent file name depends on whether we're listening to additions or removals
305 if s.dir == LogDiffAdditions {
306 s.setFilename(match[2])
307 } else {
308 s.setFilename(match[1])
309 }
310
311 if p != nil {
312 return p, true
313 }
314 } else if match := s.fileMergeHeaderRegex.FindStringSubmatch(line); match != nil {
315 // Git merge file header is a little different, only one file
316 p := s.finishLastPointer()
317
318 s.setFilename(match[1])
319
320 if p != nil {
321 return p, true
322 }
323 } else if s.currentFileIncluded {
324 if match := s.pointerDataRegex.FindStringSubmatch(line); match != nil {
325 // An LFS pointer data line
326 // Include only the entirety of one side of the diff
327 // -U3 will ensure we always get all of it, even if only
328 // the SHA changed (version & size the same)
329 changeType := match[1][0]
330
331 // Always include unchanged context lines (normally just the version line)
332 if LogDiffDirection(changeType) == s.dir || changeType == ' ' {
333 // Must skip diff +/- marker
334 s.pointerData.WriteString(line[1:])
335 s.pointerData.WriteString("\n") // newline was stripped off by scanner
336 }
337 }
338 }
339
340 if err == io.EOF {
341 break
342 }
343 }
344
345 if p := s.finishLastPointer(); p != nil {
346 return p, true
347 }
348
349 return nil, false
350 }
351
352 func (s *logScanner) setFilename(name string) {
353 // Trim last character if it's a quote
354 if len(name) > 0 && name[len(name)-1] == '"' {
355 name = name[:len(name)-1]
356 }
357
358 // Convert octals to proper UTF-8 code
359 unquotedName, err := strconv.Unquote(`"` + name + `"`)
360 if err == nil {
361 name = unquotedName
362 }
363
364 s.currentFilename = name
365 s.currentFileIncluded = s.Filter.Allows(name)
366 }