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
package diff

// 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. 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 := 0, 0
	for i, op := range ops {
		if !keep[i] {
			gap++
			continue
		}
		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
}