Files
nixos-router/pkgs/router-webui/diff.go
T
2026-11-18 13:46:25 +01:00

152 lines
3.5 KiB
Go

package main
import (
"encoding/json"
"os"
"strings"
)
// DiffRow is a line of a diff: Op is ' ' (unchanged, near a change), '-'
// (removed), '+' (added) or '.' (lines left out). Old and New are the line
// numbers in the two texts (0 where the line is not in that text).
type DiffRow struct {
Op byte
Old, New int
Text string
}
// Class names the row for the page: add, del, ctx or gap.
func (r DiffRow) Class() string {
switch r.Op {
case '+':
return "add"
case '-':
return "del"
case '.':
return "gap"
}
return "ctx"
}
// Mark is the sign before the text.
func (r DiffRow) Mark() string {
if r.Op == '+' || r.Op == '-' {
return string(r.Op)
}
return ""
}
// diffLines is a line diff of two texts in the style of diff -u without the
// hunk headers: " " unchanged lines near a change, "-" removed, "+" added.
// It returns "" when the texts are equal.
func diffLines(a, b string) string {
var out strings.Builder
for _, r := range diffRows(a, b) {
if r.Op == '.' {
out.WriteString("…\n")
continue
}
out.WriteString(string(r.Op) + " " + r.Text + "\n")
}
return out.String()
}
// diffRows is the diff of two texts with two lines of context around each
// change; nil when they are equal.
func diffRows(a, b string) []DiffRow {
x, y := strings.Split(a, "\n"), strings.Split(b, "\n")
// Longest common subsequence table.
lcs := make([][]int, len(x)+1)
for i := range lcs {
lcs[i] = make([]int, len(y)+1)
}
for i := len(x) - 1; i >= 0; i-- {
for j := len(y) - 1; j >= 0; j-- {
if x[i] == y[j] {
lcs[i][j] = lcs[i+1][j+1] + 1
} else {
lcs[i][j] = max(lcs[i+1][j], lcs[i][j+1])
}
}
}
var all []DiffRow
i, j := 0, 0
for i < len(x) || j < len(y) {
switch {
case i < len(x) && j < len(y) && x[i] == y[j]:
all = append(all, DiffRow{' ', i + 1, j + 1, x[i]})
i++
j++
case i < len(x) && (j == len(y) || lcs[i+1][j] >= lcs[i][j+1]):
all = append(all, DiffRow{'-', i + 1, 0, x[i]})
i++
default:
all = append(all, DiffRow{'+', 0, j + 1, y[j]})
j++
}
}
// Keep two lines of context around changes.
const ctx = 2
keep := make([]bool, len(all))
changed := false
for k, l := range all {
if l.Op != ' ' {
changed = true
for d := -ctx; d <= ctx; d++ {
if k+d >= 0 && k+d < len(all) {
keep[k+d] = true
}
}
}
}
if !changed {
return nil
}
var rows []DiffRow
skipped := false
for k, l := range all {
if !keep[k] {
skipped = true
continue
}
if skipped {
rows = append(rows, DiffRow{Op: '.'})
skipped = false
}
rows = append(rows, l)
}
return rows
}
// pretty re-indents JSON with sorted keys, so two spellings of the same
// settings compare equal.
func pretty(data []byte) string {
var v any
if json.Unmarshal(data, &v) != nil {
return strings.TrimSpace(string(data))
}
out, _ := json.MarshalIndent(v, "", " ")
return string(out)
}
// pendingChanges is the diff from the confirmed settings to the saved ones.
func (s System) pendingChanges() string {
return diffLines(s.pendingTexts())
}
// pendingRows is the same as rows, for the page.
func (s System) pendingRows() []DiffRow {
return diffRows(s.pendingTexts())
}
// pendingTexts are the confirmed settings and the saved ones, normalized; two
// empty texts (nothing to compare) if either cannot be read.
func (s System) pendingTexts() (string, string) {
cur, err1 := os.ReadFile(s.settingsPath())
conf, err2 := os.ReadFile(s.confirmedPath())
if err1 != nil || err2 != nil {
return "", ""
}
return pretty(conf), pretty(cur)
}