xonecas.io
8356
Wx

www-xonecas-io / files

www-xonecas-io / internal / site / diff.go

1.9 KB
1package site
2
3import (
4	"fmt"
5	"regexp"
6	"strconv"
7	"strings"
8)
9
10// MaxDiffLines is how many diff lines one commit page shows. The rest of its files are listed with their counts.
11const MaxDiffLines = 1000
12
13// maxLine cuts minified one-line files down to something a page can hold.
14const maxLine = 500
15
16var hunk = regexp.MustCompile(`^@@ -(\d+)(?:,\d+)? \+(\d+)`)
17
18// parseDiff splits git's patch output into files, keeping at most MaxDiffLines lines in all.
19func parseDiff(patch string) []Diff {
20	var diffs []Diff
21	var d *Diff
22	budget, old, nw, in := MaxDiffLines, 0, 0, false
23	for _, l := range strings.Split(patch, "\n") {
24		switch {
25		case strings.HasPrefix(l, "diff --git a/"):
26			rest := l[len("diff --git a/"):] // "P b/P"
27			diffs = append(diffs, Diff{Path: rest[:max(0, len(rest)-3)/2]})
28			d, in = &diffs[len(diffs)-1], false
29		case d == nil:
30		case !in && strings.HasPrefix(l, "rename to "):
31			d.Path = l[len("rename to "):]
32		case !in && strings.HasPrefix(l, "Binary files "):
33			d.Note = "Binary file, not shown."
34		case strings.HasPrefix(l, "@@"):
35			m := hunk.FindStringSubmatch(l)
36			if m == nil {
37				continue
38			}
39			old, _ = strconv.Atoi(m[1])
40			nw, _ = strconv.Atoi(m[2])
41			in = true
42			d.add(&budget, DiffLine{Op: "@", Text: l})
43		case !in || l == "" || l[0] == '\\':
44		case l[0] == '+':
45			d.Adds++
46			d.add(&budget, DiffLine{"+", 0, nw, l[1:]})
47			nw++
48		case l[0] == '-':
49			d.Dels++
50			d.add(&budget, DiffLine{"-", old, 0, l[1:]})
51			old++
52		default:
53			d.add(&budget, DiffLine{" ", old, nw, l[1:]})
54			old, nw = old+1, nw+1
55		}
56	}
57	return diffs
58}
59
60// add keeps line while the commit's budget lasts, and says so on the file once it runs out.
61func (d *Diff) add(budget *int, line DiffLine) {
62	if *budget == 0 {
63		if d.Note == "" {
64			d.Note = fmt.Sprintf("Cut short: this commit's diff is over %d lines.", MaxDiffLines)
65		}
66		return
67	}
68	*budget--
69	if len(line.Text) > maxLine {
70		line.Text = line.Text[:maxLine] + " …"
71	}
72	d.Lines = append(d.Lines, line)
73}