code.pablomurad.com

patchwork

Publishes the revisions of your pages as a feed, with notes and readable diffs, written in Go

internal/diff/excerpt.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
package diff

// keepDeleted is how many blocks of a run of deletions an excerpt shows
// before summing up the rest. In a rewrite, a long run of removed
// paragraphs would otherwise use up the excerpt before the new text.
const keepDeleted = 2

// Excerpt keeps the changed ops of a full diff, with up to context unchanged
// blocks around each, and folds the other unchanged runs into gap ops. Runs
// of deleted blocks longer than keepDeleted are cut to a "removed" gap. It
// stops after maxChanged changed ops and reports whether it cut anything.
func Excerpt(ops []Op, context, maxChanged int) ([]Op, bool) {
	keep := make([]bool, len(ops))
	for i, op := range ops {
		if op.Op == OpEq {
			continue
		}
		keep[i] = true
		for k := 1; k <= context; k++ {
			if i-k >= 0 && ops[i-k].Op == OpEq {
				keep[i-k] = true
			}
			if i+k < len(ops) && ops[i+k].Op == OpEq {
				keep[i+k] = true
			}
		}
	}

	var out []Op
	gap, changed, deleted := 0, 0, 0
	for i, op := range ops {
		if !keep[i] {
			gap++
			continue
		}
		if op.Op == OpDelete {
			deleted++
			if deleted > keepDeleted {
				if n := len(out); n > 0 && out[n-1].Op == OpGap && out[n-1].Removed {
					out[n-1].Count++
				} else {
					out = append(out, Op{Op: OpGap, Count: 1, Removed: true})
				}
				continue
			}
		} else {
			deleted = 0
		}
		if op.Op != OpEq {
			if changed == maxChanged {
				return out, true
			}
			changed++
		}
		if gap > 0 {
			out = append(out, Op{Op: OpGap, Count: gap})
			gap = 0
		}
		out = append(out, op)
	}
	if gap > 0 && len(out) > 0 {
		out = append(out, Op{Op: OpGap, Count: gap})
	}
	return out, false
}