internal/httpd/diff.go
606 lines · 16602 bytes
23 symbols in this file
1package httpd
2
3import (
4 "bytes"
5 "html/template"
6 "net/http"
7 "net/url"
8 "regexp"
9 "strconv"
10 "strings"
11
12 "github.com/alecthomas/chroma/v2"
13 "github.com/alecthomas/chroma/v2/formatters/html"
14 "github.com/alecthomas/chroma/v2/lexers"
15 "github.com/alecthomas/chroma/v2/styles"
16)
17
18type diffLine struct {
19 Class string // meta | hunk | add | del | ctx
20 Text string // the raw diff line, marker included
21 Content string // the line without its +/- marker
22 Code template.HTML // Content highlighted; empty when the type is unknown
23 Path string // file this line belongs to
24 NewLine int64 // line number in the new file (0 when absent)
25 OldLine int64 // line number in the old file (0 when absent)
26 Threads []diffThread
27 Compose bool // render the new-thread form under this line
28}
29
30// diffFile is one file's worth of a unified diff: the header lines are
31// consumed into the fields here, so the template renders a section rather
32// than replaying "diff --git" at the reader.
33type diffFile struct {
34 Path string // new path; the old one for a delete
35 OldPath string // set only on a rename
36 Status string // added | deleted | renamed | modified
37 Adds int
38 Dels int
39 Binary bool
40 Lines []diffLine
41 Rows []splitRow // the split layout's rows; empty in the unified layout
42 Threads int // threads anchored in this file, so it can stay unfolded
43 Open bool // rendered unfolded: small files, and anything under review
44}
45
46type diffStat struct{ Files, Adds, Dels int }
47
48var hunkPat = regexp.MustCompile(`^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@`)
49
50// parseDiff splits a unified diff into per-file sections, tracking old and
51// new line numbers so review threads can anchor inline.
52func parseDiff(patch string) []diffFile {
53 var files []diffFile
54 var cur *diffFile
55 var oldN, newN int64
56
57 // Paths arrive both in "diff --git a/x b/y" and in the ---/+++ pair.
58 // The latter is authoritative (it survives quoting oddities), so the
59 // git line only opens the section.
60 start := func() *diffFile {
61 files = append(files, diffFile{Status: "modified"})
62 return &files[len(files)-1]
63 }
64
65 for _, l := range strings.Split(patch, "\n") {
66 switch {
67 case strings.HasPrefix(l, "diff --git "):
68 cur = start()
69 if a, b, ok := gitHeaderPaths(l); ok {
70 cur.OldPath, cur.Path = a, b
71 }
72 continue
73 case cur == nil:
74 continue // preamble before the first file
75 case strings.HasPrefix(l, "new file mode"):
76 cur.Status = "added"
77 continue
78 case strings.HasPrefix(l, "deleted file mode"):
79 cur.Status = "deleted"
80 continue
81 case strings.HasPrefix(l, "rename from "):
82 cur.Status, cur.OldPath = "renamed", strings.TrimPrefix(l, "rename from ")
83 continue
84 case strings.HasPrefix(l, "rename to "):
85 cur.Status, cur.Path = "renamed", strings.TrimPrefix(l, "rename to ")
86 continue
87 case strings.HasPrefix(l, "Binary files "), strings.HasPrefix(l, "GIT binary patch"):
88 cur.Binary = true
89 continue
90 case strings.HasPrefix(l, "--- "):
91 if p := strings.TrimPrefix(l, "--- "); p != "/dev/null" {
92 cur.OldPath = strings.TrimPrefix(p, "a/")
93 }
94 continue
95 case strings.HasPrefix(l, "+++ "):
96 if p := strings.TrimPrefix(l, "+++ "); p != "/dev/null" {
97 cur.Path = strings.TrimPrefix(p, "b/")
98 }
99 continue
100 case strings.HasPrefix(l, "index "), strings.HasPrefix(l, "old mode "),
101 strings.HasPrefix(l, "new mode "), strings.HasPrefix(l, "similarity index "),
102 strings.HasPrefix(l, "dissimilarity index "):
103 continue
104 }
105
106 d := diffLine{Text: l, Content: l, Path: cur.Path}
107 switch {
108 case strings.HasPrefix(l, "@@"):
109 d.Class, d.Path = "hunk", ""
110 if m := hunkPat.FindStringSubmatch(l); m != nil {
111 oldN, _ = strconv.ParseInt(m[1], 10, 64)
112 newN, _ = strconv.ParseInt(m[2], 10, 64)
113 }
114 case strings.HasPrefix(l, "+"):
115 d.Class, d.Content, d.NewLine = "add", l[1:], newN
116 newN++
117 cur.Adds++
118 case strings.HasPrefix(l, "-"):
119 d.Class, d.Content, d.OldLine = "del", l[1:], oldN
120 oldN++
121 cur.Dels++
122 case l == `\ No newline at end of file`:
123 d.Class, d.Path = "meta", ""
124 case l == "":
125 continue // trailing newline from the split
126 default:
127 d.Class, d.Content, d.OldLine, d.NewLine = "ctx", l[1:], oldN, newN
128 oldN++
129 newN++
130 }
131 cur.Lines = append(cur.Lines, d)
132 }
133
134 for i := range files {
135 if files[i].Path == "" {
136 files[i].Path = files[i].OldPath
137 }
138 if files[i].Status == "renamed" && files[i].OldPath == files[i].Path {
139 files[i].Status = "modified"
140 }
141 highlightFile(&files[i])
142 // Big files fold shut so a large diff is navigable; anything
143 // carrying review threads stays open regardless.
144 files[i].Open = len(files[i].Lines) <= 300
145 }
146 return files
147}
148
149// gitHeaderPaths pulls both paths out of a "diff --git a/x b/y" line. Paths
150// with spaces make this ambiguous in general; git quotes those, and the
151// ---/+++ lines correct us either way.
152func gitHeaderPaths(l string) (string, string, bool) {
153 rest := strings.TrimPrefix(l, "diff --git ")
154 i := strings.Index(rest, " b/")
155 if !strings.HasPrefix(rest, "a/") || i < 0 {
156 return "", "", false
157 }
158 return rest[2:i], rest[i+3:], true
159}
160
161// diffFormatter is the blob formatter without line numbers: the diff
162// supplies its own gutters. PreventSurroundingPre also drops chroma's
163// per-line <span class="line"> wrapper, which the generated CSS gives
164// display:flex — inside a diff row that breaks the +/- marker onto a line
165// of its own.
166var diffFormatter = html.New(html.WithClasses(true), html.PreventSurroundingPre(true))
167
168// highlightFile syntax-highlights a file's diff content one hunk at a time,
169// each side separately. A hunk's context+deletions are contiguous lines of
170// the old file and its context+additions are contiguous lines of the new
171// one, so each side lexes as real code — highlighting line by line instead
172// would break every multi-line string and block comment.
173func highlightFile(f *diffFile) {
174 if f.Binary || len(f.Lines) == 0 {
175 return
176 }
177 lexer := lexers.Match(f.Path)
178 if lexer == nil {
179 return // unknown type: plain text reads fine, and guessing is worse
180 }
181 for start := 0; start < len(f.Lines); {
182 if f.Lines[start].Class == "hunk" || f.Lines[start].Class == "meta" {
183 start++
184 continue
185 }
186 end := start
187 for end < len(f.Lines) && f.Lines[end].Class != "hunk" && f.Lines[end].Class != "meta" {
188 end++
189 }
190 hunk := f.Lines[start:end]
191 assign(hunk, "del", highlightLines(lexer, sideText(hunk, "del")))
192 assign(hunk, "add", highlightLines(lexer, sideText(hunk, "add")))
193 highlightIntraLine(hunk)
194 start = end
195 }
196}
197
198// highlightIntraLine marks the changed interior span on paired -/+ runs so
199// single-token edits pop out without scanning whole lines character by character.
200func highlightIntraLine(hunk []diffLine) {
201 for i := 0; i < len(hunk); {
202 if hunk[i].Class != "del" {
203 i++
204 continue
205 }
206 delStart := i
207 for i < len(hunk) && hunk[i].Class == "del" {
208 i++
209 }
210 delEnd := i
211 addStart := i
212 for i < len(hunk) && hunk[i].Class == "add" {
213 i++
214 }
215 addEnd := i
216 nDel, nAdd := delEnd-delStart, addEnd-addStart
217 if nDel == 0 || nAdd == 0 || nDel > 8 || nAdd > 8 {
218 continue
219 }
220 pairs := min(nDel, nAdd)
221 for k := 0; k < pairs; k++ {
222 dl := &hunk[delStart+k]
223 al := &hunk[addStart+k]
224 if dl.Code == "" || al.Code == "" || dl.Content == al.Content {
225 continue
226 }
227 dr, ar := []rune(dl.Content), []rune(al.Content)
228 pre := 0
229 for pre < len(dr) && pre < len(ar) && dr[pre] == ar[pre] {
230 pre++
231 }
232 suf := 0
233 for suf < len(dr)-pre && suf < len(ar)-pre && dr[len(dr)-1-suf] == ar[len(ar)-1-suf] {
234 suf++
235 }
236 minShared := 1
237 if nDel != nAdd {
238 minShared = 2
239 }
240 if pre < minShared && suf < minShared {
241 continue
242 }
243 dl.Code = template.HTML(markHTMLSpan(string(dl.Code), pre, len(dr)-suf, "idiff-del"))
244 al.Code = template.HTML(markHTMLSpan(string(al.Code), pre, len(ar)-suf, "idiff-add"))
245 }
246 }
247}
248
249// markHTMLSpan wraps visible runes [from, to) of balanced Chroma HTML in
250// <span class="cls">, closing and reopening any active tags at the boundaries.
251func markHTMLSpan(s string, from, to int, cls string) string {
252 if from >= to {
253 return s
254 }
255 var out strings.Builder
256 var open []string
257 pos := 0
258 inMark := false
259 openMark := func() {
260 if !inMark {
261 out.WriteString(`<span class="` + cls + `">`)
262 for _, t := range open {
263 out.WriteString(t)
264 }
265 inMark = true
266 }
267 }
268 closeMark := func() {
269 if inMark {
270 for range open {
271 out.WriteString("</span>")
272 }
273 out.WriteString("</span>")
274 for _, t := range open {
275 out.WriteString(t)
276 }
277 inMark = false
278 }
279 }
280 for i := 0; i < len(s); {
281 if s[i] == '<' {
282 j := strings.IndexByte(s[i:], '>')
283 if j < 0 {
284 out.WriteString(s[i:])
285 break
286 }
287 tag := s[i : i+j+1]
288 if strings.HasPrefix(tag, "</") {
289 if len(open) > 0 {
290 open = open[:len(open)-1]
291 }
292 } else if !strings.HasSuffix(tag, "/>") {
293 open = append(open, tag)
294 }
295 out.WriteString(tag)
296 i += j + 1
297 continue
298 }
299 if pos >= from && pos < to && !inMark {
300 for range open {
301 out.WriteString("</span>")
302 }
303 openMark()
304 } else if pos >= to && inMark {
305 closeMark()
306 }
307 if s[i] == '&' {
308 if semi := strings.IndexByte(s[i:], ';'); semi > 0 && semi <= 10 {
309 out.WriteString(s[i : i+semi+1])
310 i += semi + 1
311 pos++
312 continue
313 }
314 }
315 _, w := utf8DecodeRune(s[i:])
316 out.WriteString(s[i : i+w])
317 i += w
318 pos++
319 }
320 if inMark {
321 for range open {
322 out.WriteString("</span>")
323 }
324 out.WriteString("</span>")
325 }
326 return out.String()
327}
328
329func utf8DecodeRune(s string) (rune, int) {
330 for i, r := range s {
331 if i == 0 {
332 return r, len(string(r))
333 }
334 }
335 return 0, 1
336}
337
338// sideText joins one side of a hunk: context plus the given change class.
339// Content, not Text: the marker is already off it. Taking it off Text here
340// meant stripping "+" and then "-", which ate the dash of an added line that
341// begins with one.
342func sideText(hunk []diffLine, class string) string {
343 var b strings.Builder
344 for _, l := range hunk {
345 if l.Class == "ctx" || l.Class == class {
346 b.WriteString(l.Content)
347 b.WriteByte('\n')
348 }
349 }
350 return b.String()
351}
352
353// assign hands highlighted lines back to the diff lines they came from.
354// Context lines take whichever side ran last; both sides hold identical
355// text there, so the result is the same either way.
356func assign(hunk []diffLine, class string, out []template.HTML) {
357 i := 0
358 for j := range hunk {
359 if hunk[j].Class != "ctx" && hunk[j].Class != class {
360 continue
361 }
362 if i < len(out) {
363 hunk[j].Code = out[i]
364 }
365 i++
366 }
367}
368
369// highlightLines formats source and splits the result back into lines.
370// chroma emits tokens that may span newlines, so the split happens on the
371// rendered HTML with tags reopened per line.
372func highlightLines(lexer chroma.Lexer, src string) []template.HTML {
373 if src == "" {
374 return nil
375 }
376 it, err := lexer.Tokenise(nil, src)
377 if err != nil {
378 return nil
379 }
380 var buf bytes.Buffer
381 if err := diffFormatter.Format(&buf, styles.Get(lightStyle), it); err != nil {
382 return nil
383 }
384 body := strings.TrimSuffix(buf.String(), "\n")
385
386 var out []template.HTML
387 for _, line := range splitHighlighted(body) {
388 out = append(out, template.HTML(line))
389 }
390 return out
391}
392
393// splitHighlighted breaks formatted HTML on newlines that sit outside a
394// tag, closing and reopening the spans that straddle the break so every
395// line is balanced markup on its own.
396func splitHighlighted(body string) []string {
397 var lines []string
398 var open []string
399 var cur strings.Builder
400 for i := 0; i < len(body); {
401 switch body[i] {
402 case '<':
403 j := strings.IndexByte(body[i:], '>')
404 if j < 0 {
405 cur.WriteString(body[i:])
406 i = len(body)
407 continue
408 }
409 tag := body[i : i+j+1]
410 if strings.HasPrefix(tag, "</") {
411 if len(open) > 0 {
412 open = open[:len(open)-1]
413 }
414 } else if !strings.HasSuffix(tag, "/>") {
415 open = append(open, tag)
416 }
417 cur.WriteString(tag)
418 i += j + 1
419 case '\n':
420 for range open {
421 cur.WriteString("</span>")
422 }
423 lines = append(lines, cur.String())
424 cur.Reset()
425 for _, t := range open {
426 cur.WriteString(t)
427 }
428 i++
429 default:
430 cur.WriteByte(body[i])
431 i++
432 }
433 }
434 if cur.Len() > 0 {
435 lines = append(lines, cur.String())
436 }
437 return lines
438}
439
440// statOf totals a parsed diff for the summary line.
441func statOf(files []diffFile) diffStat {
442 st := diffStat{Files: len(files)}
443 for _, f := range files {
444 st.Adds += f.Adds
445 st.Dels += f.Dels
446 }
447 return st
448}
449
450// splitRow is one row of the side-by-side layout: a hunk or meta line
451// spanning both columns, or a pair of lines. In a run of deletions
452// followed by additions the two are zipped, and the shorter side is left
453// empty. Old and New point into the file's Lines.
454type splitRow struct {
455 Kind string // hunk | meta | pair
456 Text string
457 Old *diffLine
458 New *diffLine
459 Threads []diffThread
460 OldNote string // "\ No newline" marker belonging to the old side
461 NewNote string // and to the new side
462 Compose *diffLine // the line whose new-thread form opens under this row
463}
464
465// diffLayout is the layout a diff page renders in and the links that
466// switch it.
467type diffLayout struct {
468 Split bool
469 UnifiedURL string
470 SplitURL string
471 Carry string // "split" or "unified" when the request chose it, so links keep it
472}
473
474// splitFiles fills each file's Rows. It runs after threads and compose
475// forms are attached to the lines.
476func splitFiles(files []diffFile) {
477 for f := range files {
478 files[f].Rows = splitRows(files[f].Lines)
479 }
480}
481
482// splitRows pairs one file's deletions with its additions, side by side.
483func splitRows(lines []diffLine) []splitRow {
484 var rows []splitRow
485 for i := 0; i < len(lines); {
486 ln := &lines[i]
487 switch ln.Class {
488 case "hunk", "meta":
489 if ln.Class == "meta" && ln.Path == "" && len(rows) > 0 && strings.HasPrefix(ln.Text, `\`) {
490 // a marker after a context line: neither side ends in a newline
491 if last := &rows[len(rows)-1]; last.Old != nil && last.Old == last.New {
492 last.OldNote, last.NewNote = ln.Text, ln.Text
493 i++
494 continue
495 }
496 }
497 rows = append(rows, splitRow{Kind: ln.Class, Text: ln.Text})
498 i++
499 case "ctx":
500 r := splitRow{Kind: "pair", Old: ln, New: ln, Threads: ln.Threads}
501 if ln.Compose {
502 r.Compose = ln
503 }
504 rows = append(rows, r)
505 i++
506 default:
507 var dels, adds []*diffLine
508 marker := func() string {
509 if i < len(lines) && lines[i].Class == "meta" && strings.HasPrefix(lines[i].Text, `\`) {
510 i++
511 return lines[i-1].Text
512 }
513 return ""
514 }
515 var oldNote, newNote string
516 for i < len(lines) && lines[i].Class == "del" {
517 dels = append(dels, &lines[i])
518 i++
519 }
520 if len(dels) > 0 {
521 oldNote = marker()
522 }
523 for i < len(lines) && lines[i].Class == "add" {
524 adds = append(adds, &lines[i])
525 i++
526 }
527 if len(adds) > 0 {
528 newNote = marker()
529 }
530 if len(dels)+len(adds) == 0 {
531 i++ // an unknown class: skip rather than loop
532 continue
533 }
534 first := len(rows)
535 for k := 0; k < len(dels) || k < len(adds); k++ {
536 rows = append(rows, pairRow(pick(dels, k), pick(adds, k)))
537 }
538 if len(dels) > 0 {
539 rows[first+len(dels)-1].OldNote = oldNote
540 }
541 if len(adds) > 0 {
542 rows[first+len(adds)-1].NewNote = newNote
543 }
544 }
545 }
546 return rows
547}
548
549// pairRow is the row showing del beside add; either may be nil.
550func pairRow(del, add *diffLine) splitRow {
551 r := splitRow{Kind: "pair"}
552 for _, l := range []*diffLine{del, add} {
553 if l == nil {
554 continue
555 }
556 if l.Class == "del" {
557 r.Old = l
558 } else {
559 r.New = l
560 }
561 r.Threads = append(r.Threads, l.Threads...)
562 if l.Compose {
563 r.Compose = l
564 }
565 }
566 return r
567}
568
569func pick(s []*diffLine, i int) *diffLine {
570 if i < len(s) {
571 return s[i]
572 }
573 return nil
574}
575
576// diffLayoutFor resolves the layout for a request: ?layout= wins, then the
577// signed-in account's setting, then unified. The two switch links keep
578// every other query parameter.
579func (s *Server) diffLayoutFor(r *http.Request) diffLayout {
580 q := r.URL.Query()
581 l := diffLayout{}
582 switch q.Get("layout") {
583 case "split":
584 l.Split, l.Carry = true, "split"
585 case "unified":
586 l.Carry = "unified"
587 default:
588 if s.cfg.Web.Mode == "accounts" {
589 if u := s.viewer(r); u.ID != 0 {
590 if v, err := s.st.DiffLayout(u.ID); err == nil {
591 l.Split = v == "split"
592 }
593 }
594 }
595 }
596 link := func(v string) string {
597 c := url.Values{}
598 for k, vs := range q {
599 c[k] = vs
600 }
601 c.Set("layout", v)
602 return r.URL.Path + "?" + c.Encode()
603 }
604 l.UnifiedURL, l.SplitURL = link("unified"), link("split")
605 return l
606}