Repository navigation
Expand file tree
/
Copy pathdiff.go
More file actions
786 lines (747 loc) · 28.5 KB
/
Copy pathdiff.go
File metadata and controls
786 lines (747 loc) · 28.5 KB
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
package main
import (
"fmt"
"net/http"
"os"
"os/exec"
"path/filepath"
"slices"
"strconv"
"strings"
)
// The diff tab shows everything a worktree holds that the base branch does not
// — the commits on its branch AND the uncommitted work, in one tree. They are
// not separate modes: a file is listed once and marked with where its change
// lives (branch / uncommitted / both), because "what is in this worktree" is
// the question, and whether a line is committed yet is a detail of it.
//
// That makes one diff command cover every case: the fork point (`git
// merge-base <base> HEAD`) against the working tree. For a checkout on the
// base branch, or a detached one, the fork point IS HEAD, so the same command
// degrades to the plain uncommitted diff with nothing special-cased.
//
// A checkout with submodules is several repositories — itself, and every
// submodule checked out under it, nested ones included (diffRepos below).
// Work on a ticket usually spans more than one, so every checked-out repo is
// scanned, each file tagged with the `repo` it came from.
//
// GET /api/diff?name=myrepo1 -> the repos and their changed files
// GET /api/diff?name=myrepo1&repo=<submodule>&file=… -> the unified diff of one
// commentIgnores are the patterns behind "ignore comments". git does the work:
// -I drops a hunk whose changed lines ALL match, so a file whose only change is
// a reworded comment disappears from the diff entirely. Its own regex engine,
// hence POSIX classes rather than \s.
//
// Block-comment continuation lines (" * more text") are deliberately absent:
// they are indistinguishable from a Markdown bullet, and hiding a real content
// change would be worse than showing a comment. Go and TypeScript here use //
// almost throughout.
var commentIgnores = []string{
`^[[:space:]]*//`, // Go, TypeScript, JavaScript, C-like
`^[[:space:]]*#`, // YAML, shell, Python, CoffeeScript, Makefile
`^[[:space:]]*--`, // SQL
`^[[:space:]]*/\*`, // block comment opener
`^[[:space:]]*\*/`, // block comment closer
`^[[:space:]]*<!--`, // HTML, XML
}
// ignoring is what the reader has asked a diff to leave out. Each is a flag
// git already has; what they share is the consequence for the file list: git's
// --numstat honours them while --name-status does not, so a file that is
// missing from the stats is one with nothing left to show, and leaves.
type ignoring struct {
comments bool // a -I per comment syntax, commentIgnores
whitespace bool // -w: any change in whitespace, line endings included
}
func (ig ignoring) any() bool { return ig.comments || ig.whitespace }
// args are the flags for a git invocation, or nothing.
func (ig ignoring) args() []string {
var args []string
if ig.whitespace {
args = append(args, "-w")
}
if ig.comments {
for _, re := range commentIgnores {
args = append(args, "-I", re)
}
}
return args
}
// diffMax caps one file's diff. A generated file or a vendored blob would
// otherwise push megabytes into the browser for nothing.
const diffMax = 400 << 10
type DiffFile struct {
Repo string `json:"repo"` // the checkout itself, or one of its submodules
Path string `json:"path"`
Status string `json:"status"` // modified | added | deleted | renamed | new | …
// Origin says where this file's change lives: "branch" (committed on this
// branch since the fork point), "working" (uncommitted only) or "both".
Origin string `json:"origin"`
// Preview is set when a browser can render this file itself (image, pdf,
// video, audio) — the viewer then shows it instead of "Binary files differ".
Preview string `json:"preview,omitempty"`
Added int `json:"added"`
Deleted int `json:"deleted"`
Untracked bool `json:"untracked,omitempty"`
// Merged marks a committed file whose change the branch this range is
// measured against already holds, found by content (markLanded).
Merged bool `json:"merged,omitempty"`
// Submodule marks a gitlink: not a file but a whole repository, whose
// "change" is that it sits on a different commit than this one records.
// Discarding one is a checkout inside it, not a line restored, and the UI
// has to say so before it happens.
Submodule bool `json:"submodule,omitempty"`
// SubmoduleDirty is set when there is uncommitted work to TRACKED files
// inside it. Git refuses to move a submodule over such work rather than
// overwriting it, so this is not a warning about loss — it is a warning
// that the discard will not happen.
SubmoduleDirty bool `json:"submodule_dirty,omitempty"`
// OldPath is where a renamed or copied file came from. Without it a rename
// is indistinguishable from a new file — in the list, in its counts, and in
// its diff, which git can only pair with the old file when it is asked
// about both.
OldPath string `json:"old_path,omitempty"`
// SubmoduleBranch is the branch checked out INSIDE it, when there is one.
// Putting a submodule back to a recorded commit detaches it, and a
// submodule that is somebody's working branch — a linked worktree, which
// is how they are set up here — is a place somebody is standing.
SubmoduleBranch string `json:"submodule_branch,omitempty"`
}
// submoduleWork says which of these submodules hold uncommitted changes to
// tracked files — what a discard would take with it. Untracked files survive
// the checkout and are not counted; that is measured, not assumed.
//
// Asked of the PARENT in one path-limited status rather than by running git
// inside each submodule: porcelain=v2 spells the state out as S<c><m><u>, and
// m is M exactly when there is modified content in there. Nothing runs at all
// unless a gitlink is among the files on screen, which is the rare case.
func submoduleWork(root string, paths []string) map[string]bool {
if len(paths) == 0 {
return nil
}
out, err := git(root, append([]string{"status", "--porcelain=v2", "--"}, paths...)...)
if err != nil {
return nil
}
dirty := map[string]bool{}
for _, line := range strings.Split(out, "\n") {
// "1 <XY> <sub> <mH> <mI> <mW> <hH> <hI> <path>" — split to exactly
// nine so a path with spaces in it arrives whole
f := strings.SplitN(line, " ", 9)
if len(f) != 9 || f[0] != "1" {
continue
}
if st := f[2]; len(st) == 4 && st[0] == 'S' && st[2] == 'M' {
dirty[f[8]] = true
}
}
return dirty
}
type DiffList struct {
Name string `json:"name"`
Repo string `json:"repo"`
Files []DiffFile `json:"files"`
}
// subRepo is one of the repositories a checkout spans, named for the scope
// and diff lists.
// subRepo is one of the repositories a checkout spans. Parent is the
// repository that declares it — its IMMEDIATE parent, which for a nested
// submodule is another submodule and not the checkout. The list is flat and
// the nesting is not: easydb-library is declared by easydb-webfrontend, which
// is declared by fylr, and only easydb-webfrontend records a commit for it.
type subRepo struct{ Name, Path, Parent string }
// primaryRepo names a checkout's own repository in the scope and diff lists.
func primaryRepo(c Checkout) string {
if c.Repo != "" {
return c.Repo
}
return "repo"
}
// diffRepos lists the repositories a checkout spans: itself, then every
// submodule checked out under it, nested ones included, in .gitmodules order.
// Each is a git checkout of its own and needs its own `git diff`. A submodule
// that was never initialised is an empty directory without a .git and is
// left out. Names are the submodule directory's base name; a name that
// repeats at another depth keeps its full relative path instead.
func diffRepos(c Checkout) []subRepo {
out := []subRepo{{primaryRepo(c), c.Path, ""}}
seen := map[string]bool{out[0].Name: true}
var walk func(root, prefix string, depth int)
walk = func(root, prefix string, depth int) {
if depth > 4 {
return
}
for _, rel := range submodulePaths(root) {
path := filepath.Join(root, rel)
if _, err := os.Stat(filepath.Join(path, ".git")); err != nil {
continue
}
name := filepath.Base(rel)
if seen[name] {
name = filepath.ToSlash(filepath.Join(prefix, rel))
}
seen[name] = true
out = append(out, subRepo{name, path, root})
walk(path, filepath.Join(prefix, rel), depth+1)
}
}
walk(c.Path, "", 1)
return out
}
// submodulePaths reads the submodule paths a checkout declares. No
// .gitmodules is the common case and makes git exit non-zero: no submodules.
func submodulePaths(root string) []string {
out, err := git(root, "config", "--file", ".gitmodules", "--get-regexp", `^submodule\..*\.path$`)
if err != nil {
return nil
}
var paths []string
for _, line := range strings.Split(out, "\n") {
if _, p, ok := strings.Cut(line, " "); ok && p != "" {
paths = append(paths, p)
}
}
return paths
}
type DiffText struct {
Path string `json:"path"`
Diff string `json:"diff"`
// Total is how many lines the file has on the scope's AFTER side, so the
// viewer knows from the first render whether anything is hidden below the
// last hunk — without it the "more" expander has to appear on every file
// and only discovers it was pointing at nothing once clicked. 0 means the
// after side has no file at all (a deletion).
Total int `json:"total"`
Truncated bool `json:"truncated,omitempty"`
}
func (d *grove) handleDiff(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
c, ok := d.checkout(q.Get("name"))
if !ok {
writeErr(w, http.StatusNotFound, fmt.Errorf("no checkout at %q", q.Get("name")))
return
}
want := q.Get("repo")
if want == "" {
want = primaryRepo(c)
}
root := ""
for _, repo := range diffRepos(c) {
if repo.Name == want {
root = repo.Path
}
}
if root == "" {
writeErr(w, http.StatusNotFound, fmt.Errorf("%s has no %s checkout", c.Name, want))
return
}
spec, err := resolveScope(root, want, d.baseFor(c.Path), primaryRepo(c), q.Get("scope"))
if err != nil {
writeErr(w, http.StatusBadRequest, err)
return
}
ignore := ignoring{
comments: q.Get("ignore_comments") == "1",
whitespace: q.Get("ignore_whitespace") == "1",
}
if file := q.Get("file"); file != "" {
if !safeRepoPath(file) {
writeErr(w, http.StatusBadRequest, fmt.Errorf("path must stay inside the checkout"))
return
}
old := q.Get("old")
if old != "" && !safeRepoPath(old) {
writeErr(w, http.StatusBadRequest, fmt.Errorf("path must stay inside the checkout"))
return
}
text, truncated, err := fileDiff(root, file, q.Get("untracked") == "1", spec, ignore, old)
if err != nil {
writeErr(w, http.StatusInternalServerError, err)
return
}
total := 0
if body, err := fileAt(root, file, spec, false); err == nil && body != "" {
total = strings.Count(strings.TrimSuffix(body, "\n"), "\n") + 1
}
writeJSON(w, http.StatusOK, DiffText{Path: file, Diff: text, Total: total, Truncated: truncated})
return
}
files, err := scopeFiles(root, spec, ignore)
if err != nil {
writeErr(w, http.StatusInternalServerError, err)
return
}
for i := range files {
files[i].Repo = want
}
writeJSON(w, http.StatusOK, DiffList{Name: c.Name, Repo: want, Files: files})
}
// scopeFiles lists the files a scope covers. Only the range scopes merge
// committed and uncommitted work — the others are one side of git by
// definition, and their origin marker says which.
func scopeFiles(root string, spec scopeSpec, ignore ignoring) ([]DiffFile, error) {
files, err := scopeFileList(root, spec, ignore)
if err != nil {
return nil, err
}
// A gitlink among them is a whole repository, not a file, and what can be
// done to it is not what can be done to a file — discarding one is a
// checkout inside it. Marked here rather than in any one lister because
// all four kinds can turn one up, and marking it in the range scope alone
// is how the uncommitted view went on offering a file's actions for it.
if subs := submodulePaths(root); len(subs) > 0 {
at := map[string]bool{}
for _, p := range subs {
at[p] = true
}
var here []string
for i := range files {
if at[files[i].Path] {
files[i].Submodule = true
here = append(here, files[i].Path)
}
}
work := submoduleWork(root, here)
for i := range files {
if !files[i].Submodule {
continue
}
files[i].SubmoduleDirty = work[files[i].Path]
// asked of the submodule itself; there is no field of the parent's
// status that carries it
files[i].SubmoduleBranch, _ = git(filepath.Join(root, files[i].Path),
"symbolic-ref", "--quiet", "--short", "HEAD")
}
}
return files, nil
}
func scopeFileList(root string, spec scopeSpec, ignore ignoring) ([]DiffFile, error) {
switch spec.kind {
case "range":
files, err := changedFiles(root, spec.from, ignore)
if err == nil && spec.ref != "" {
markLanded(root, spec.ref, files)
}
return files, err
case "staged":
return nameStatus(root, "staged", ignore, "diff", "--cached", "--name-status")
case "unstaged":
files, err := nameStatus(root, "working", ignore, "diff", "--name-status")
if err != nil {
return nil, err
}
// untracked files are unstaged too — git just leaves them out of a diff
out, err := git(root, "ls-files", "--others", "--exclude-standard")
if err == nil && out != "" {
for _, path := range strings.Split(out, "\n") {
if path == "" {
continue
}
files = append(files, DiffFile{
Path: path, Status: "new", Origin: "working",
Untracked: true, Preview: previewKind(path),
})
}
}
slices.SortFunc(files, func(a, b DiffFile) int { return strings.Compare(a.Path, b.Path) })
return files, nil
case "commit":
// Against the FIRST parent, not `git show`. For a merge, show prints a
// combined diff: only the files that differ from every parent, the few
// the merge had to reconcile. A merge that brought a thousand commits
// into main listed 15 files and counted none of the 11,000 it added.
// What a merge did to its branch is its first-parent diff, and for any
// other commit the two are the same thing.
return nameStatus(root, "branch", ignore, "diff", "--name-status", spec.from, spec.sha)
}
return nil, fmt.Errorf("unknown scope kind %q", spec.kind)
}
// nameStatus lists files from any git command that prints --name-status, with
// the stats of the matching --numstat run.
func nameStatus(root, origin string, ignore ignoring, args ...string) ([]DiffFile, error) {
out, err := git(root, append(args, ignore.args()...)...)
if err != nil {
return nil, fmt.Errorf("git %s: %w", strings.Join(args, " "), err)
}
numArgs := make([]string, len(args))
copy(numArgs, args)
for i, a := range numArgs {
if a == "--name-status" {
numArgs[i] = "--numstat"
}
}
stats := numstatArgs(root, append(numArgs, ignore.args()...)...)
plain := stats
if ignore.any() {
plain = numstatArgs(root, numArgs...)
}
var files []DiffFile
for _, line := range strings.Split(out, "\n") {
f := strings.Split(line, "\t")
if len(f) < 2 {
continue
}
path := f[len(f)-1] // "R100\told\tnew" -> the new name
file := DiffFile{
Path: path, Status: statusWord(f[0][:1]),
Origin: origin, Preview: previewKind(path),
}
if len(f) == 3 && (f[0][0] == 'R' || f[0][0] == 'C') {
file.OldPath = f[1]
}
if s, ok := stats[path]; ok {
file.Added, file.Deleted = s[0], s[1]
} else if _, had := plain[path]; had && ignore.any() {
// --name-status ignores -I and -w, --numstat honours both: a file
// that HAD stats and has none now has nothing left once they are
// applied. One missing from both was never about what is ignored.
continue
}
files = append(files, file)
}
return files, nil
}
// repoBase is the branch a repo's commits are measured against. The checkout's
// own repo uses the dashboard's base (the main checkout's branch — never a
// hardcoded name); a submodule is a repository with a history of its own, so
// it uses its remote's default branch.
func repoBase(root, name, dashboardBase string, primary string) string {
if name == primary {
return dashboardBase
}
if b, err := git(root, "symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"); err == nil && b != "" {
return b
}
return ""
}
// mergeBaseOf is the commit this checkout forked from — the point everything is
// measured against. It is HEAD itself when there is nothing to fork from: a
// detached checkout, one sitting ON the base branch, or a base that does not
// resolve here. The uncommitted work is then the whole diff, with nothing
// special-cased anywhere else.
func mergeBaseOf(root, base string) string {
if base == "" {
return "HEAD"
}
mb, err := git(root, "merge-base", base, "HEAD")
if err != nil || mb == "" {
return "HEAD"
}
if head, err := git(root, "rev-parse", "HEAD"); err == nil && head == mb {
return "HEAD"
}
return mb
}
// changedFiles lists everything the checkout holds that forkPoint does not:
// the files its commits touched plus the uncommitted ones, merged into one
// list, each marked with where its change lives. -uall expands untracked
// directories to their files, so a fresh directory is a list of files in the
// tree instead of one unopenable entry.
func changedFiles(root, forkPoint string, ignore ignoring) ([]DiffFile, error) {
committed := map[string]string{} // path -> status letter
if forkPoint != "HEAD" {
out, err := git(root, append([]string{"diff", "--name-status", forkPoint + "..HEAD"}, ignore.args()...)...)
if err != nil {
return nil, fmt.Errorf("git diff --name-status: %w", err)
}
for _, line := range strings.Split(out, "\n") {
f := strings.Split(line, "\t")
if len(f) < 2 {
continue
}
committed[f[len(f)-1]] = f[0][:1] // "R100\told\tnew" -> the new name
}
}
out, err := git(root, "status", "--porcelain", "-uall")
if err != nil {
return nil, fmt.Errorf("git status: %w", err)
}
working := map[string]string{}
var order []string
for _, line := range strings.Split(out, "\n") {
if len(line) < 4 {
continue
}
code, path := line[:2], line[3:]
// a rename reads "R old -> new"; the new name is the one to diff
if i := strings.Index(path, " -> "); i >= 0 {
path = path[i+4:]
}
path = strings.Trim(path, `"`)
working[path] = code
order = append(order, path)
}
for path := range committed {
if _, dup := working[path]; !dup {
order = append(order, path)
}
}
slices.Sort(order)
// One numstat over the whole span covers every case: a committed-only file
// gets its branch counts, an uncommitted-only file its working counts, and
// a file that is both gets the sum a reviewer actually cares about.
//
// Read without the flags first: it is the list of files that differ from
// the fork point AT ALL. The two sources above say a file was touched, and
// touched is not changed — a commit adds five lines, the working tree
// takes them out again, and the file is main's own, byte for byte. It
// used to be listed anyway, with no counts and an empty diff, a row that
// asks "what changed?" and has no answer. Git numstats every difference
// there is, a mode, a binary, a submodule's dirt, so a file missing from
// this one has none; only an untracked file is in no diff at all. A
// rename is a fact about the files rather than about what is ignored, so
// it is read from here too.
plain, from, err := numstatRead(root, "diff", forkPoint, "--numstat")
if err != nil {
return nil, fmt.Errorf("git diff --numstat: %w", err)
}
stats := plain
if ignore.any() {
stats, _ = numstatFull(root, append([]string{"diff", forkPoint, "--numstat"}, ignore.args()...)...)
}
files := make([]DiffFile, 0, len(order))
for _, path := range order {
code, dirty := working[path]
status, onBranch := committed[path]
f := DiffFile{Path: path, Untracked: code == "??", Preview: previewKind(path), OldPath: from[path]}
switch {
case onBranch && dirty:
f.Origin, f.Status = "both", statusWord(code)
case onBranch:
f.Origin, f.Status = "branch", statusWord(status)
default:
f.Origin, f.Status = "working", statusWord(code)
}
if _, differs := plain[path]; !differs && !f.Untracked {
continue // changed, and changed back
}
if s, ok := stats[path]; ok {
f.Added, f.Deleted = s[0], s[1]
} else if ignore.any() && !f.Untracked {
continue // nothing of this file survives what is being ignored
}
files = append(files, f)
}
return files, nil
}
// markLanded flags the committed files whose change ref already holds. The
// range is measured from the fork point, so a file the base branch picked up
// through another commit — a change lifted into a review commit, say — stays
// in it, and `git cherry` keeps the commit "not in base" because it compares
// whole commits. So the content is asked instead: git merge-tree merges HEAD
// onto ref in memory (no worktree, no index) and the files that merge would
// still change on ref are the ones ref lacks. A committed file it would not
// change is already there. Uncommitted work is never on ref and stays
// unmarked, as does everything when the merge cannot be formed at all.
func markLanded(root, ref string, files []DiffFile) {
tree := mergedTree(root, ref)
if tree == "" {
return
}
still, err := git(root, "diff", "--name-only", ref, tree)
if err != nil {
return
}
differs := map[string]bool{}
for _, p := range strings.Split(still, "\n") {
differs[p] = true
}
for i := range files {
if files[i].Origin == "branch" && !differs[files[i].Path] {
files[i].Merged = true
}
}
}
// mergedTree merges HEAD onto ref in memory — no worktree, no index — and
// returns the resulting tree. Empty when the merge cannot be formed at all.
func mergedTree(root, ref string) string {
cmd := exec.Command(gitExe, "merge-tree", "--write-tree", ref, "HEAD")
cmd.Dir = root
out, err := cmd.Output()
if err != nil {
// exit 1 is a merge with conflicts: the tree is still written, and a
// conflicted file still differs from ref, which reads as not there
if ee, ok := err.(*exec.ExitError); !ok || ee.ExitCode() != 1 {
return ""
}
}
tree, _, _ := strings.Cut(string(out), "\n")
if !plainSha(tree) {
return ""
}
return tree
}
// landedInto reports whether merging this checkout into ref would leave ref
// exactly as it is — every change here is already in it. That is the state a
// SQUASH merge leaves behind, and the one no count can see: the branch's
// commits are not ancestors of the base, so it still reads as N ahead, while
// the base holds every line of them under one commit of its own.
//
// refTree is passed in rather than read here because it is the same for every
// checkout of a repository, and this runs once per checkout.
func landedInto(root, ref, refTree string) bool {
if ref == "" || refTree == "" {
return false
}
return mergedTree(root, ref) == refTree
}
// treeOf is a ref's tree, for landedInto to compare against.
func treeOf(root, ref string) string {
t, err := git(root, "rev-parse", "--verify", "--quiet", ref+"^{tree}")
if err != nil {
return ""
}
return t
}
// numstat maps path -> {added, deleted} from a ref to the working tree.
func numstat(root, from string, ignore ignoring) map[string][2]int {
return numstatArgs(root, append([]string{"diff", from, "--numstat"}, ignore.args()...)...)
}
// numstatArgs is numstat over any git invocation that prints --numstat lines,
// so staged/unstaged/commit scopes share the parsing.
func numstatArgs(root string, args ...string) map[string][2]int {
stats, _ := numstatFull(root, args...)
return stats
}
// numstatFull is numstat keyed by the path each change ENDS at, with where the
// renamed and copied ones came from beside it.
func numstatFull(root string, args ...string) (map[string][2]int, map[string]string) {
stats, from, _ := numstatRead(root, args...)
return stats, from
}
// numstatRead is numstatFull for a caller that must tell "no files" from "git
// failed": one that drops whatever is not in the answer.
func numstatRead(root string, args ...string) (map[string][2]int, map[string]string, error) {
stats := map[string][2]int{}
from := map[string]string{}
out, err := git(root, args...)
if err != nil {
return stats, from, err
}
for _, line := range strings.Split(out, "\n") {
f := strings.Split(line, "\t")
if len(f) != 3 {
continue
}
a, _ := strconv.Atoi(f[0]) // "-" for binary files -> 0
d, _ := strconv.Atoi(f[1])
old, path := renamePaths(f[2])
stats[path] = [2]int{a, d}
if old != path {
from[path] = old
}
}
return stats, from, nil
}
// renamePaths reads the path column of a --numstat line. A rename is written
// with what its two names share pulled outside braces —
// internal/openapi/{gitbook.go => render.go}, src/{old => new}/main.go — or, if
// they share nothing, as old => new. Either side of the braces may be empty:
// {=> sub}/x.go is x.go moved into sub/, which leaves a slash to close up.
//
// The parse this replaces kept what followed " => " and cut a trailing brace,
// so internal/openapi/{gitbook.go => render.go} was counted under "render.go"
// and the renamed file showed no counts at all — 280 lines missing from the
// commit it was in.
func renamePaths(p string) (old, path string) {
arrow := strings.Index(p, " => ")
if arrow < 0 {
return p, p
}
open := strings.LastIndex(p[:arrow], "{")
if open < 0 {
return p[:arrow], p[arrow+4:]
}
shut := strings.Index(p[arrow:], "}")
if shut < 0 {
return p, p
}
shut += arrow
join := func(a, mid, b string) string {
out := strings.ReplaceAll(a+mid+b, "//", "/")
return strings.TrimPrefix(out, "/")
}
pre, suf := p[:open], p[shut+1:]
return join(pre, p[open+1:arrow], suf), join(pre, p[arrow+4:shut], suf)
}
func statusWord(code string) string {
switch {
case code == "??":
return "new"
case strings.ContainsAny(code, "R"):
return "renamed"
case strings.ContainsAny(code, "A"):
return "added"
case strings.ContainsAny(code, "D"):
return "deleted"
case strings.ContainsAny(code, "M"):
return "modified"
default:
return strings.TrimSpace(code)
}
}
// fileDiff renders one file from the fork point to the working tree, so a file
// that is partly committed and partly not shows as one diff. An untracked file
// is in no commit and no index, so it is compared to /dev/null — which makes
// git print it as all additions, exactly how a new file should read.
func fileDiff(root, path string, untracked bool, spec scopeSpec, ignore ignoring, oldPath string) (string, bool, error) {
var args []string
switch {
case untracked:
// A new symlink is spelled out rather than handed to --no-index, which
// follows one that points at a DIRECTORY, takes the directory for the
// place to diff /dev/null into, and fails looking for <link>/null — a
// new link to a directory could not be opened at all. What is shown is
// what git records once it is added: the path it points to.
if target, ok := symlinkTarget(filepath.Join(root, filepath.Clean(path))); ok {
return newLinkDiff(path, target), false, nil
}
// in no commit and no index, so there is nothing to diff against
args = []string{"diff", "--no-index", "--", "/dev/null", path}
default:
switch {
case spec.kind == "staged":
args = []string{"diff", "--cached"}
case spec.kind == "unstaged":
args = []string{"diff"}
case spec.kind == "commit":
args = []string{"diff", spec.from, spec.sha} // see scopeFileList
default:
args = []string{"diff", spec.from}
}
args = append(args, ignore.args()...)
// Both names, for a rename: git pairs a file with its old self only
// when the old self is in the pathspec too. Asked about the new name
// alone it shows a NEW file — every line of it added — which is how
// gitbook.go becoming render.go read as 308 lines written from scratch
// rather than 280 taken out.
args = append(args, "--", path)
if oldPath != "" && oldPath != path {
args = append(args, oldPath)
}
}
cmd := exec.Command(gitExe, args...)
cmd.Dir = root
out, err := cmd.Output()
// --no-index exits 1 whenever there IS a difference, which is the normal
// case here; only a missing stdout is a real failure
if err != nil && len(out) == 0 {
return "", false, fmt.Errorf("git diff: %w", err)
}
if len(out) > diffMax {
return string(out[:diffMax]), true, nil
}
return string(out), false, nil
}
// safeRepoPath keeps the file parameter inside the checkout: a relative path,
// no parent-directory hops, and not an option git could interpret.
//
// filepath.IsLocal is the whole guard on the first two, and it has to be.
// Checking IsAbs and walking the segments by hand is right on Unix and wrong
// on Windows, where `\etc\passwd` is ROOTED but not absolute — it names no
// drive, so IsAbs says false and the path went through. IsLocal knows the
// difference, and it also refuses the reserved device names: os.ReadFile("NUL")
// on Windows opens the null device, and /api/lines reads what it is handed.
func safeRepoPath(p string) bool {
// a leading dash is an option to git whatever the filesystem makes of it
return p != "" && !strings.HasPrefix(p, "-") && filepath.IsLocal(p)
}