Files
nilsandClaude Sonnet 5.5 eb11fc30b3 Name the element a change is in and let the diff show the lines around it
Each group of changes gets a bar with its place in the settings (like
router.firewall.rules[3], and the rule's zones) and buttons to show more
lines above and below, or all that are hidden.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-18 19:56:54 +01:00

316 lines
7.9 KiB
Go

package main
import (
"encoding/json"
"fmt"
"os"
"regexp"
"strings"
)
// DiffRow is a line of a diff: Op is ' ' (unchanged), '-' (removed), '+'
// (added) or '.' (a bar above a group of lines: see diffView). 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
Hidden bool // unchanged and far from a change: shown when the page is asked to
// Of a bar: where the group below it is in the settings (Path, and Label
// naming the element), how many hidden lines follow it (N) and which way
// there is more to show: Up (above the next change), Down (below the last).
Path, Label string
N int
Up, Down bool
}
// 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 {
all, keep := diffAll(a, b)
var out strings.Builder
skipped := false
for k, l := range all {
if !keep[k] {
skipped = true
continue
}
if skipped {
out.WriteString("…\n")
skipped = false
}
out.WriteString(string(l.Op) + " " + l.Text + "\n")
}
return out.String()
}
// diffContext is how many unchanged lines are shown around a change.
const diffContext = 2
// diffAll is every line of the two texts in diff order, and which of them are
// a change or near one; nil when the texts are equal.
func diffAll(a, b string) ([]DiffRow, []bool) {
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{Op: ' ', Old: i + 1, New: j + 1, Text: x[i]})
i++
j++
case i < len(x) && (j == len(y) || lcs[i+1][j] >= lcs[i][j+1]):
all = append(all, DiffRow{Op: '-', Old: i + 1, Text: x[i]})
i++
default:
all = append(all, DiffRow{Op: '+', New: j + 1, Text: y[j]})
j++
}
}
keep := make([]bool, len(all))
changed := false
for k, l := range all {
if l.Op != ' ' {
changed = true
for d := -diffContext; d <= diffContext; d++ {
if k+d >= 0 && k+d < len(all) {
keep[k+d] = true
}
}
}
}
if !changed {
return nil, nil
}
return all, keep
}
// diffView is the diff for the page: all lines, the ones far from a change
// marked Hidden, and a bar before each group of changed lines (and after the
// last) that names where in the settings the group is and offers the lines
// hidden next to it. nil when the texts are equal.
func diffView(a, b string) []DiffRow {
all, keep := diffAll(a, b)
if all == nil {
return nil
}
oldPaths, newPaths := jsonPaths(a), jsonPaths(b)
var oldDoc, newDoc any
json.Unmarshal([]byte(a), &oldDoc)
json.Unmarshal([]byte(b), &newDoc)
// where is the settings path of a changed line, and its element's name.
where := func(l DiffRow) (string, string) {
if l.Op == '+' && l.New-1 < len(newPaths) {
p := newPaths[l.New-1]
return pathName(p), pathLabel(newDoc, p)
}
if l.Op == '-' && l.Old-1 < len(oldPaths) {
p := oldPaths[l.Old-1]
return pathName(p), pathLabel(oldDoc, p)
}
return "", ""
}
var rows []DiffRow
for k := 0; k < len(all); {
start := k
hidden := !keep[k]
for k < len(all) && keep[k] == !hidden {
k++
}
if hidden {
bar := DiffRow{Op: '.', N: k - start, Down: start > 0, Up: k < len(all)}
if k < len(all) {
bar.Path, bar.Label = firstChange(all[k:], keep[k:], where)
}
rows = append(rows, bar)
for _, l := range all[start:k] {
l.Hidden = true
rows = append(rows, l)
}
continue
}
if start == 0 {
bar := DiffRow{Op: '.'}
bar.Path, bar.Label = firstChange(all[start:k], keep[start:k], where)
rows = append(rows, bar)
}
rows = append(rows, all[start:k]...)
}
return rows
}
// firstChange is where the first changed line of the lines that are kept is.
func firstChange(rows []DiffRow, keep []bool, where func(DiffRow) (string, string)) (string, string) {
for i, l := range rows {
if !keep[i] {
break
}
if l.Op != ' ' {
return where(l)
}
}
return "", ""
}
// pathSeg is a step into the settings: a key, or an index into an array.
type pathSeg struct {
key string
index int
array bool // index is meant
}
var jsonKey = regexp.MustCompile(`^"((?:[^"\\]|\\.)*)":`)
// jsonPaths is, for each line of indented JSON, the path of the object or
// array the line is in (a line that opens one is in its parent).
func jsonPaths(text string) [][]pathSeg {
type frame struct {
seg pathSeg
array bool // the frame is an array
next int // index of the next element
}
var stack []frame
lines := strings.Split(text, "\n")
paths := make([][]pathSeg, len(lines))
for i, line := range lines {
t := strings.TrimSpace(line)
for _, f := range stack {
if f.seg != (pathSeg{}) {
paths[i] = append(paths[i], f.seg)
}
}
switch {
case strings.HasPrefix(t, "}") || strings.HasPrefix(t, "]"):
if len(stack) > 0 {
stack = stack[:len(stack)-1]
}
case strings.HasSuffix(t, "{") || strings.HasSuffix(t, "["):
var seg pathSeg
if m := jsonKey.FindStringSubmatch(t); m != nil {
seg = pathSeg{key: m[1]}
} else if n := len(stack); n > 0 && stack[n-1].array {
seg = pathSeg{index: stack[n-1].next, array: true}
stack[n-1].next++
}
stack = append(stack, frame{seg: seg, array: strings.HasSuffix(t, "[")})
default:
if n := len(stack); n > 0 && stack[n-1].array {
stack[n-1].next++
}
}
}
return paths
}
// pathName writes a path like router.firewall.rules[3].
func pathName(p []pathSeg) string {
var b strings.Builder
for _, s := range p {
if s.array {
fmt.Fprintf(&b, "[%d]", s.index)
continue
}
if b.Len() > 0 {
b.WriteByte('.')
}
b.WriteString(s.key)
}
return b.String()
}
// pathLabel names the element at a path when it says what it is: a rule or a
// forward has a from and a to ("lan → family").
func pathLabel(doc any, p []pathSeg) string {
v := doc
for _, s := range p {
switch c := v.(type) {
case map[string]any:
v = c[s.key]
case []any:
if !s.array || s.index >= len(c) {
return ""
}
v = c[s.index]
default:
return ""
}
}
if m, ok := v.(map[string]any); ok {
from, _ := m["from"].(string)
to, _ := m["to"].(string)
if from != "" && to != "" {
return from + " → " + to
}
}
return ""
}
// 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 for the page (see diffView).
func (s System) pendingRows() []DiffRow {
return diffView(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)
}