internal/site/diff.go12.9 KB · Go
Raw
  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
package site

import (
	"context"
	"fmt"
	"html/template"
	"path"
	"regexp"
	"strconv"
	"strings"

	"github.com/alecthomas/chroma/v2"
	"github.com/alecthomas/chroma/v2/lexers"
)

const (
	maxCommitPatchBytes = 8 * 1024 * 1024
	maxCommitDiffRows   = 4000
	maxFileDiffRows     = 2000
)

var hunkHeaderPattern = regexp.MustCompile(`^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@`)

type CommitParent struct {
	OID      string
	ShortOID string
	URL      string
}

type CommitView struct {
	Commit    Commit
	Parents   []CommitParent
	Files     []DiffFile
	FileCount int
	Binaries  int
	Additions int
	Deletions int
	Truncated bool
}

type DiffFile struct {
	Anchor      string
	OldPath     string
	NewPath     string
	DisplayPath string
	TreePath    string
	Status      string
	Rows        []DiffRow
	Additions   int
	Deletions   int
	Binary      bool
	Truncated   bool
}

type DiffRow struct {
	Hunk       bool
	Header     string
	OldNumber  int
	NewNumber  int
	OldText    string
	NewText    string
	OldCode    template.HTML
	NewCode    template.HTML
	OldClass   string
	NewClass   string
	OldPresent bool
	NewPresent bool
}

type numberedLine struct {
	number int
	text   string
}

func (g *Generator) commitPages(ctx context.Context, branch, oldOID, newOID string, summary branchSummary) ([]Page, error) {
	wanted := make(map[string]struct{})
	// A site-version change is also our migration signal: the first push after
	// installing commit views backfills historical pages once. Ordinary pushes
	// with current assets remain proportional to newly reachable commits.
	if oldOID == "" || !g.AssetsCurrent {
		for _, group := range summary.Groups {
			for _, commit := range group.Commits {
				wanted[commit.OID] = struct{}{}
			}
		}
	} else {
		out, err := g.Git.Run(ctx, "rev-list", newOID, "^"+oldOID)
		if err != nil {
			g.progress("could not enumerate new commits from %s; generating reachable commit pages", short(oldOID))
			for _, group := range summary.Groups {
				for _, commit := range group.Commits {
					wanted[commit.OID] = struct{}{}
				}
			}
		} else {
			for _, oid := range strings.Fields(string(out)) {
				wanted[oid] = struct{}{}
			}
		}
	}

	var pages []Page
	for _, group := range summary.Groups {
		for _, commit := range group.Commits {
			if _, ok := wanted[commit.OID]; !ok || g.commitGenerated(commit.OID) {
				continue
			}
			page, err := g.commitPage(ctx, branch, commit, summary)
			if err != nil {
				return nil, err
			}
			pages = append(pages, page)
		}
	}
	if len(pages) > 0 {
		g.progress("generated %d commit diff page(s)", len(pages))
	}
	return pages, nil
}

func (g *Generator) commitGenerated(oid string) bool {
	g.commitMu.Lock()
	defer g.commitMu.Unlock()
	_, ok := g.generated[oid]
	return ok
}

func (g *Generator) markCommitGenerated(oid string) {
	g.commitMu.Lock()
	g.generated[oid] = struct{}{}
	g.commitMu.Unlock()
}

func (g *Generator) commitPage(ctx context.Context, branch string, commit Commit, summary branchSummary) (Page, error) {
	view := CommitView{Commit: commit}
	for _, oid := range commit.Parents {
		view.Parents = append(view.Parents, CommitParent{
			OID:      oid,
			ShortOID: short(oid),
			URL:      routeURL(g.BaseURL, path.Join("commit", oid)),
		})
	}

	args := []string{"diff", "--no-ext-diff", "--no-color", "--find-renames", "--unified=3"}
	if len(commit.Parents) > 0 {
		args = append(args, commit.Parents[0], commit.OID, "--")
	} else {
		args = []string{"diff-tree", "--root", "--no-commit-id", "-r", "-p", "--no-ext-diff", "--no-color", "--find-renames", "--unified=3", commit.OID, "--"}
	}
	patch, truncated, err := g.Git.RunLimited(ctx, maxCommitPatchBytes, args...)
	if err != nil {
		return Page{}, err
	}
	view.Truncated = truncated
	if !truncated {
		parsed := parsePatch(patch)
		view.FileCount = len(parsed)
		for _, file := range parsed {
			if file.Binary {
				view.Binaries++
				continue
			}
			highlightDiffFile(&file)
			view.Files = append(view.Files, file)
			view.Additions += file.Additions
			view.Deletions += file.Deletions
		}
	}

	data := g.pageData("commit", commit.Message+" · "+g.RepoName, branch, summary)
	data.ViewedCommit = view
	body, err := g.render(data)
	if err != nil {
		return Page{}, err
	}
	return Page{
		Route:       path.Join("commit", commit.OID),
		Body:        body,
		ContentType: "text/html; charset=utf-8",
		Cache:       siteCache,
	}, nil
}

func highlightDiffFile(file *DiffFile) {
	filename := file.NewPath
	if filename == "" {
		filename = file.OldPath
	}
	lexer := lexers.Match(filename)
	if lexer == nil {
		setPlainDiffCode(file)
		return
	}
	lexer = chroma.Coalesce(lexer)
	for start := 0; start < len(file.Rows); {
		if file.Rows[start].Hunk {
			start++
			continue
		}
		end := start
		for end < len(file.Rows) && !file.Rows[end].Hunk {
			end++
		}
		highlightDiffSide(file.Rows[start:end], lexer, true)
		highlightDiffSide(file.Rows[start:end], lexer, false)
		start = end
	}
}

func setPlainDiffCode(file *DiffFile) {
	for index := range file.Rows {
		if file.Rows[index].OldPresent {
			file.Rows[index].OldCode = template.HTML(template.HTMLEscapeString(file.Rows[index].OldText))
		}
		if file.Rows[index].NewPresent {
			file.Rows[index].NewCode = template.HTML(template.HTMLEscapeString(file.Rows[index].NewText))
		}
	}
}

func highlightDiffSide(rows []DiffRow, lexer chroma.Lexer, old bool) {
	var indexes []int
	var source strings.Builder
	for index, row := range rows {
		present, value := row.NewPresent, row.NewText
		if old {
			present, value = row.OldPresent, row.OldText
		}
		if !present {
			continue
		}
		indexes = append(indexes, index)
		source.WriteString(value)
		source.WriteByte('\n')
	}
	if len(indexes) == 0 {
		return
	}
	iterator, err := lexer.Tokenise(nil, source.String())
	if err != nil {
		setPlainDiffSide(rows, indexes, old)
		return
	}
	lines := chroma.SplitTokensIntoLines(iterator.Tokens())
	if len(lines) != len(indexes) {
		setPlainDiffSide(rows, indexes, old)
		return
	}
	for offset, tokens := range lines {
		formatted := formatDiffTokens(tokens)
		if old {
			rows[indexes[offset]].OldCode = formatted
		} else {
			rows[indexes[offset]].NewCode = formatted
		}
	}
}

func setPlainDiffSide(rows []DiffRow, indexes []int, old bool) {
	for _, index := range indexes {
		value := rows[index].NewText
		if old {
			value = rows[index].OldText
		}
		formatted := template.HTML(template.HTMLEscapeString(value))
		if old {
			rows[index].OldCode = formatted
		} else {
			rows[index].NewCode = formatted
		}
	}
}

func formatDiffTokens(tokens []chroma.Token) template.HTML {
	var result strings.Builder
	for _, token := range tokens {
		value := strings.TrimSuffix(token.Value, "\n")
		if value == "" {
			continue
		}
		escaped := template.HTMLEscapeString(value)
		class := diffTokenClass(token.Type)
		if class == "" {
			result.WriteString(escaped)
			continue
		}
		result.WriteString(`<span class="diff-`)
		result.WriteString(class)
		result.WriteString(`">`)
		result.WriteString(escaped)
		result.WriteString(`</span>`)
	}
	return template.HTML(result.String())
}

func diffTokenClass(tokenType chroma.TokenType) string {
	for tokenType != 0 {
		if class, ok := chroma.StandardTypes[tokenType]; ok {
			return class
		}
		tokenType = tokenType.Parent()
	}
	return chroma.StandardTypes[tokenType]
}

func parsePatch(patch []byte) []DiffFile {
	var files []DiffFile
	var current *DiffFile
	var oldLine, newLine int
	var oldBlock, newBlock []numberedLine
	var blockTruncated bool
	renderedRows := 0
	fileRows := 0
	inHunk := false
	rowAllowance := func() int {
		return min(maxCommitDiffRows-renderedRows, maxFileDiffRows-fileRows)
	}
	appendRow := func(row DiffRow) {
		if current == nil {
			return
		}
		if rowAllowance() <= 0 {
			current.Truncated = true
			return
		}
		current.Rows = append(current.Rows, row)
		renderedRows++
		fileRows++
	}

	flushBlock := func() {
		if current == nil || len(oldBlock)+len(newBlock) == 0 {
			if current != nil {
				current.Truncated = current.Truncated || blockTruncated
			}
			blockTruncated = false
			return
		}
		count := max(len(oldBlock), len(newBlock))
		for index := range count {
			row := DiffRow{}
			if index < len(oldBlock) {
				row.OldNumber = oldBlock[index].number
				row.OldText = oldBlock[index].text
				row.OldClass = "deletion"
				row.OldPresent = true
			}
			if index < len(newBlock) {
				row.NewNumber = newBlock[index].number
				row.NewText = newBlock[index].text
				row.NewClass = "addition"
				row.NewPresent = true
			}
			appendRow(row)
		}
		current.Truncated = current.Truncated || blockTruncated
		oldBlock = oldBlock[:0]
		newBlock = newBlock[:0]
		blockTruncated = false
	}
	finishFile := func() {
		flushBlock()
		if current == nil {
			return
		}
		if current.NewPath == "" {
			current.NewPath = current.OldPath
		}
		if current.OldPath == "" {
			current.OldPath = current.NewPath
		}
		switch {
		case current.Status == "Renamed":
			current.DisplayPath = current.OldPath + " → " + current.NewPath
			current.TreePath = current.NewPath
		case current.Status == "Deleted":
			current.DisplayPath = current.OldPath
			current.TreePath = current.OldPath
		default:
			current.DisplayPath = current.NewPath
			current.TreePath = current.NewPath
		}
		if current.Status == "" {
			current.Status = "Modified"
		}
		current.Anchor = fmt.Sprintf("diff-%d", len(files)+1)
		files = append(files, *current)
		current = nil
		inHunk = false
		fileRows = 0
	}

	for _, line := range strings.Split(string(patch), "\n") {
		if strings.HasPrefix(line, "diff --git ") {
			finishFile()
			oldPath, newPath := diffHeaderPaths(strings.TrimPrefix(line, "diff --git "))
			current = &DiffFile{OldPath: oldPath, NewPath: newPath}
			continue
		}
		if current == nil {
			continue
		}
		if matches := hunkHeaderPattern.FindStringSubmatch(line); matches != nil {
			flushBlock()
			oldLine, _ = strconv.Atoi(matches[1])
			newLine, _ = strconv.Atoi(matches[2])
			appendRow(DiffRow{Hunk: true, Header: line})
			inHunk = true
			continue
		}
		if inHunk {
			if line == `\ No newline at end of file` {
				continue
			}
			if line == "" {
				continue
			}
			switch line[0] {
			case ' ':
				flushBlock()
				appendRow(DiffRow{
					OldNumber: oldLine, NewNumber: newLine,
					OldText: line[1:], NewText: line[1:],
					OldPresent: true, NewPresent: true,
				})
				oldLine++
				newLine++
			case '-':
				if len(oldBlock) < rowAllowance() {
					oldBlock = append(oldBlock, numberedLine{number: oldLine, text: line[1:]})
				} else {
					blockTruncated = true
				}
				current.Deletions++
				oldLine++
			case '+':
				if len(newBlock) < rowAllowance() {
					newBlock = append(newBlock, numberedLine{number: newLine, text: line[1:]})
				} else {
					blockTruncated = true
				}
				current.Additions++
				newLine++
			}
			continue
		}

		switch {
		case strings.HasPrefix(line, "new file mode "):
			current.Status = "Added"
		case strings.HasPrefix(line, "deleted file mode "):
			current.Status = "Deleted"
		case strings.HasPrefix(line, "rename from "):
			current.Status = "Renamed"
			current.OldPath = decodeGitPath(strings.TrimPrefix(line, "rename from "))
		case strings.HasPrefix(line, "rename to "):
			current.Status = "Renamed"
			current.NewPath = decodeGitPath(strings.TrimPrefix(line, "rename to "))
		case strings.HasPrefix(line, "Binary files ") || line == "GIT binary patch":
			current.Binary = true
		case strings.HasPrefix(line, "--- "):
			value := patchPath(strings.TrimPrefix(line, "--- "))
			if value != "" {
				current.OldPath = value
			}
		case strings.HasPrefix(line, "+++ "):
			value := patchPath(strings.TrimPrefix(line, "+++ "))
			if value != "" {
				current.NewPath = value
			}
		}
	}
	finishFile()
	return files
}

func diffHeaderPaths(value string) (string, string) {
	if strings.HasPrefix(value, `"`) {
		oldPath, rest := quotedGitField(value)
		newPath, _ := quotedGitField(strings.TrimSpace(rest))
		return stripDiffPrefix(oldPath), stripDiffPrefix(newPath)
	}
	marker := strings.Index(value, " b/")
	if marker < 0 {
		return stripDiffPrefix(value), stripDiffPrefix(value)
	}
	return stripDiffPrefix(value[:marker]), stripDiffPrefix(value[marker+1:])
}

func quotedGitField(value string) (string, string) {
	if !strings.HasPrefix(value, `"`) {
		field, rest, _ := strings.Cut(value, " ")
		return decodeGitPath(field), rest
	}
	escaped := false
	for index := 1; index < len(value); index++ {
		switch {
		case escaped:
			escaped = false
		case value[index] == '\\':
			escaped = true
		case value[index] == '"':
			return decodeGitPath(value[:index+1]), value[index+1:]
		}
	}
	return decodeGitPath(value), ""
}

func patchPath(value string) string {
	value = strings.TrimSuffix(value, "\t")
	value = decodeGitPath(value)
	if value == "/dev/null" {
		return ""
	}
	return stripDiffPrefix(value)
}

func stripDiffPrefix(value string) string {
	value = decodeGitPath(value)
	value = strings.TrimPrefix(value, "a/")
	value = strings.TrimPrefix(value, "b/")
	return value
}

func decodeGitPath(value string) string {
	if strings.HasPrefix(value, `"`) && strings.HasSuffix(value, `"`) {
		if decoded, err := strconv.Unquote(value); err == nil {
			return decoded
		}
	}
	return value
}