internal/httpd/diff.go

160fc0ec2bbbb4367ce5db1814c1a7404b656048
gitbay/internal/httpd/diff.go history · blame · raw

300 lines · 9072 bytes

  1package httpd
  2
  3import (
  4	"bytes"
  5	"html/template"
  6	"regexp"
  7	"strconv"
  8	"strings"
  9
 10	"github.com/alecthomas/chroma/v2"
 11	"github.com/alecthomas/chroma/v2/formatters/html"
 12	"github.com/alecthomas/chroma/v2/lexers"
 13	"github.com/alecthomas/chroma/v2/styles"
 14)
 15
 16type diffLine struct {
 17	Class   string        // meta | hunk | add | del | ctx
 18	Text    string        // the raw diff line, marker included
 19	Content string        // the line without its +/- marker
 20	Code    template.HTML // Content highlighted; empty when the type is unknown
 21	Path    string        // file this line belongs to
 22	NewLine int64         // line number in the new file (0 when absent)
 23	OldLine int64         // line number in the old file (0 when absent)
 24	Threads []diffThread
 25}
 26
 27// diffFile is one file's worth of a unified diff: the header lines are
 28// consumed into the fields here, so the template renders a section rather
 29// than replaying "diff --git" at the reader.
 30type diffFile struct {
 31	Path    string // new path; the old one for a delete
 32	OldPath string // set only on a rename
 33	Status  string // added | deleted | renamed | modified
 34	Adds    int
 35	Dels    int
 36	Binary  bool
 37	Lines   []diffLine
 38	Threads int  // threads anchored in this file, so it can stay unfolded
 39	Open    bool // rendered unfolded: small files, and anything under review
 40}
 41
 42type diffStat struct{ Files, Adds, Dels int }
 43
 44var hunkPat = regexp.MustCompile(`^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@`)
 45
 46// parseDiff splits a unified diff into per-file sections, tracking old and
 47// new line numbers so review threads can anchor inline.
 48func parseDiff(patch string) []diffFile {
 49	var files []diffFile
 50	var cur *diffFile
 51	var oldN, newN int64
 52
 53	// Paths arrive both in "diff --git a/x b/y" and in the ---/+++ pair.
 54	// The latter is authoritative (it survives quoting oddities), so the
 55	// git line only opens the section.
 56	start := func() *diffFile {
 57		files = append(files, diffFile{Status: "modified"})
 58		return &files[len(files)-1]
 59	}
 60
 61	for _, l := range strings.Split(patch, "\n") {
 62		switch {
 63		case strings.HasPrefix(l, "diff --git "):
 64			cur = start()
 65			if a, b, ok := gitHeaderPaths(l); ok {
 66				cur.OldPath, cur.Path = a, b
 67			}
 68			continue
 69		case cur == nil:
 70			continue // preamble before the first file
 71		case strings.HasPrefix(l, "new file mode"):
 72			cur.Status = "added"
 73			continue
 74		case strings.HasPrefix(l, "deleted file mode"):
 75			cur.Status = "deleted"
 76			continue
 77		case strings.HasPrefix(l, "rename from "):
 78			cur.Status, cur.OldPath = "renamed", strings.TrimPrefix(l, "rename from ")
 79			continue
 80		case strings.HasPrefix(l, "rename to "):
 81			cur.Status, cur.Path = "renamed", strings.TrimPrefix(l, "rename to ")
 82			continue
 83		case strings.HasPrefix(l, "Binary files "), strings.HasPrefix(l, "GIT binary patch"):
 84			cur.Binary = true
 85			continue
 86		case strings.HasPrefix(l, "--- "):
 87			if p := strings.TrimPrefix(l, "--- "); p != "/dev/null" {
 88				cur.OldPath = strings.TrimPrefix(p, "a/")
 89			}
 90			continue
 91		case strings.HasPrefix(l, "+++ "):
 92			if p := strings.TrimPrefix(l, "+++ "); p != "/dev/null" {
 93				cur.Path = strings.TrimPrefix(p, "b/")
 94			}
 95			continue
 96		case strings.HasPrefix(l, "index "), strings.HasPrefix(l, "old mode "),
 97			strings.HasPrefix(l, "new mode "), strings.HasPrefix(l, "similarity index "),
 98			strings.HasPrefix(l, "dissimilarity index "):
 99			continue
100		}
101
102		d := diffLine{Text: l, Content: l, Path: cur.Path}
103		switch {
104		case strings.HasPrefix(l, "@@"):
105			d.Class, d.Path = "hunk", ""
106			if m := hunkPat.FindStringSubmatch(l); m != nil {
107				oldN, _ = strconv.ParseInt(m[1], 10, 64)
108				newN, _ = strconv.ParseInt(m[2], 10, 64)
109			}
110		case strings.HasPrefix(l, "+"):
111			d.Class, d.Content, d.NewLine = "add", l[1:], newN
112			newN++
113			cur.Adds++
114		case strings.HasPrefix(l, "-"):
115			d.Class, d.Content, d.OldLine = "del", l[1:], oldN
116			oldN++
117			cur.Dels++
118		case l == `\ No newline at end of file`:
119			d.Class, d.Path = "meta", ""
120		case l == "":
121			continue // trailing newline from the split
122		default:
123			d.Class, d.Content, d.OldLine, d.NewLine = "ctx", l[1:], oldN, newN
124			oldN++
125			newN++
126		}
127		cur.Lines = append(cur.Lines, d)
128	}
129
130	for i := range files {
131		if files[i].Path == "" {
132			files[i].Path = files[i].OldPath
133		}
134		if files[i].Status == "renamed" && files[i].OldPath == files[i].Path {
135			files[i].Status = "modified"
136		}
137		highlightFile(&files[i])
138		// Big files fold shut so a large diff is navigable; anything
139		// carrying review threads stays open regardless.
140		files[i].Open = len(files[i].Lines) <= 300
141	}
142	return files
143}
144
145// gitHeaderPaths pulls both paths out of a "diff --git a/x b/y" line. Paths
146// with spaces make this ambiguous in general; git quotes those, and the
147// ---/+++ lines correct us either way.
148func gitHeaderPaths(l string) (string, string, bool) {
149	rest := strings.TrimPrefix(l, "diff --git ")
150	i := strings.Index(rest, " b/")
151	if !strings.HasPrefix(rest, "a/") || i < 0 {
152		return "", "", false
153	}
154	return rest[2:i], rest[i+3:], true
155}
156
157// diffFormatter is the blob formatter without line numbers: the diff
158// supplies its own gutters. PreventSurroundingPre also drops chroma's
159// per-line <span class="line"> wrapper, which the generated CSS gives
160// display:flex — inside a diff row that breaks the +/- marker onto a line
161// of its own.
162var diffFormatter = html.New(html.WithClasses(true), html.PreventSurroundingPre(true))
163
164// highlightFile syntax-highlights a file's diff content one hunk at a time,
165// each side separately. A hunk's context+deletions are contiguous lines of
166// the old file and its context+additions are contiguous lines of the new
167// one, so each side lexes as real code — highlighting line by line instead
168// would break every multi-line string and block comment.
169func highlightFile(f *diffFile) {
170	if f.Binary || len(f.Lines) == 0 {
171		return
172	}
173	lexer := lexers.Match(f.Path)
174	if lexer == nil {
175		return // unknown type: plain text reads fine, and guessing is worse
176	}
177	for start := 0; start < len(f.Lines); {
178		if f.Lines[start].Class == "hunk" || f.Lines[start].Class == "meta" {
179			start++
180			continue
181		}
182		end := start
183		for end < len(f.Lines) && f.Lines[end].Class != "hunk" && f.Lines[end].Class != "meta" {
184			end++
185		}
186		hunk := f.Lines[start:end]
187		assign(hunk, "del", highlightLines(lexer, sideText(hunk, "del")))
188		assign(hunk, "add", highlightLines(lexer, sideText(hunk, "add")))
189		start = end
190	}
191}
192
193// sideText joins one side of a hunk: context plus the given change class.
194func sideText(hunk []diffLine, class string) string {
195	var b strings.Builder
196	for _, l := range hunk {
197		if l.Class == "ctx" || l.Class == class {
198			b.WriteString(strings.TrimPrefix(strings.TrimPrefix(l.Text, "+"), "-"))
199			b.WriteByte('\n')
200		}
201	}
202	return b.String()
203}
204
205// assign hands highlighted lines back to the diff lines they came from.
206// Context lines take whichever side ran last; both sides hold identical
207// text there, so the result is the same either way.
208func assign(hunk []diffLine, class string, out []template.HTML) {
209	i := 0
210	for j := range hunk {
211		if hunk[j].Class != "ctx" && hunk[j].Class != class {
212			continue
213		}
214		if i < len(out) {
215			hunk[j].Code = out[i]
216		}
217		i++
218	}
219}
220
221// highlightLines formats source and splits the result back into lines.
222// chroma emits tokens that may span newlines, so the split happens on the
223// rendered HTML with tags reopened per line.
224func highlightLines(lexer chroma.Lexer, src string) []template.HTML {
225	if src == "" {
226		return nil
227	}
228	it, err := lexer.Tokenise(nil, src)
229	if err != nil {
230		return nil
231	}
232	var buf bytes.Buffer
233	if err := diffFormatter.Format(&buf, styles.Get(lightStyle), it); err != nil {
234		return nil
235	}
236	body := strings.TrimSuffix(buf.String(), "\n")
237
238	var out []template.HTML
239	for _, line := range splitHighlighted(body) {
240		out = append(out, template.HTML(line))
241	}
242	return out
243}
244
245// splitHighlighted breaks formatted HTML on newlines that sit outside a
246// tag, closing and reopening the spans that straddle the break so every
247// line is balanced markup on its own.
248func splitHighlighted(body string) []string {
249	var lines []string
250	var open []string
251	var cur strings.Builder
252	for i := 0; i < len(body); {
253		switch body[i] {
254		case '<':
255			j := strings.IndexByte(body[i:], '>')
256			if j < 0 {
257				cur.WriteString(body[i:])
258				i = len(body)
259				continue
260			}
261			tag := body[i : i+j+1]
262			if strings.HasPrefix(tag, "</") {
263				if len(open) > 0 {
264					open = open[:len(open)-1]
265				}
266			} else if !strings.HasSuffix(tag, "/>") {
267				open = append(open, tag)
268			}
269			cur.WriteString(tag)
270			i += j + 1
271		case '\n':
272			for range open {
273				cur.WriteString("</span>")
274			}
275			lines = append(lines, cur.String())
276			cur.Reset()
277			for _, t := range open {
278				cur.WriteString(t)
279			}
280			i++
281		default:
282			cur.WriteByte(body[i])
283			i++
284		}
285	}
286	if cur.Len() > 0 {
287		lines = append(lines, cur.String())
288	}
289	return lines
290}
291
292// statOf totals a parsed diff for the summary line.
293func statOf(files []diffFile) diffStat {
294	st := diffStat{Files: len(files)}
295	for _, f := range files {
296		st.Adds += f.Adds
297		st.Dels += f.Dels
298	}
299	return st
300}