bots-garden/mini-mepublic Fork
⑂ 5a0f4b1
Commits
⬇ Clone ▾
git clone https://git.rickub.com/bots-garden/mini-me.git
git clone ssh://git@rickub.com/bots-garden/mini-me.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Download ZIP

♻️ Quality: internal/fileedit without smells (6 → 0)

- middle as replaced (too large), lcsTable and walk
- apply as resolve, checkOverlaps, rebuild; locate with match.at and
  pickOccurrence (the line rule of ticket 241)
- headline as unchangedOrCreated and changeSummary; write with fill
- diff_render.go: the unified diff and the hunks

Checked: Replace (13 cases: success, misses, empty old, overlaps,
several occurrences with and without line, identical pairs, loose match,
dry run, a 3000-line diff past the LCS limit) and Write (4) byte-identical
old vs new — results, headlines, diffs and the files written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
agent committed 2026-11-28T12:29:35+01:00 Browse files
5a0f4b1 parent: 8b276c0
modified internal/fileedit/diff.go +24 -155
@@ -1,7 +1,6 @@
11 package fileedit
22
33 import (
4- "fmt"
54 "strings"
65 )
76
@@ -138,18 +137,28 @@ func middle(old, new []string, off int) []line {
138137 return nil
139138 }
140139 if len(old)*len(new) > maxCells {
141- out := make([]line, 0, len(old)+len(new))
142- for i, l := range old {
143- out = append(out, line{del, l, off + i + 1, 0})
144- }
145- for j, l := range new {
146- out = append(out, line{add, l, 0, off + j + 1})
147- }
148- return out
140+ return replaced(old, new, off)
141+ }
142+ return walk(old, new, lcsTable(old, new), off)
143+}
144+
145+// replaced is old deleted then new added, line for line: the diff of two
146+// texts too large for the LCS table.
147+func replaced(old, new []string, off int) []line {
148+ out := make([]line, 0, len(old)+len(new))
149+ for i, l := range old {
150+ out = append(out, line{del, l, off + i + 1, 0})
151+ }
152+ for j, l := range new {
153+ out = append(out, line{add, l, 0, off + j + 1})
149154 }
155+ return out
156+}
150157
151- // Classic LCS: length table, then walk. Files edited by an agent fit in it
152- // comfortably.
158+// lcsTable is the classic LCS length table: lcs[i][j] is the length of the
159+// longest common subsequence of old[i:] and new[j:]. Files edited by an
160+// agent fit in it comfortably.
161+func lcsTable(old, new []string) [][]int {
153162 lcs := make([][]int, len(old)+1)
154163 for i := range lcs {
155164 lcs[i] = make([]int, len(new)+1)
@@ -163,7 +172,11 @@ func middle(old, new []string, off int) []line {
163172 }
164173 }
165174 }
175+ return lcs
176+}
166177
178+// walk reads the diff off the LCS table: kept lines, deletions, additions.
179+func walk(old, new []string, lcs [][]int, off int) []line {
167180 var out []line
168181 i, j := 0, 0
169182 for i < len(old) && j < len(new) {
@@ -221,147 +234,3 @@ const noNewline = `\ No newline at end of file`
221234 // contextLines is how many unchanged lines are kept around each change. Three
222235 // is the value of `diff -u` and of git.
223236 const contextLines = 3
224-
225-// unified renders a unified patch, applicable as-is by `patch -p1` or
226-// `git apply`. Paths are prefixed a/ and b/ like git does.
227-func (r comparison) unified(path string) string {
228- if !changed(r.lines) {
229- return ""
230- }
231- var b strings.Builder
232- fmt.Fprintf(&b, "--- a/%s\n+++ b/%s\n", path, path)
233-
234- lastOld, lastNew := 0, 0
235- for _, l := range r.lines {
236- lastOld, lastNew = max(lastOld, l.oldNo), max(lastNew, l.newNo)
237- }
238- for _, h := range hunks(r.lines) {
239- oldStart, oldCount, newStart, newCount := h.ranges()
240- fmt.Fprintf(&b, "@@ -%d,%d +%d,%d @@\n", oldStart, oldCount, newStart, newCount)
241- for _, l := range h {
242- b.WriteByte(byte(l.op))
243- b.WriteString(l.text)
244- b.WriteByte('\n')
245- // The marker follows the LAST line of each version, and a kept
246- // line belongs to both: it may carry it for both at once.
247- if (!r.oldNL && l.oldNo == lastOld && l.op != add) ||
248- (!r.newNL && l.newNo == lastNew && l.op != del) {
249- b.WriteString(noNewline + "\n")
250- }
251- }
252- }
253- return b.String()
254-}
255-
256-// hunk is a group of contiguous lines shown together.
257-type hunk []line
258-
259-// hunks cuts the diff into pieces: each change plus `contextLines` on both
260-// sides. Touching pieces are merged — otherwise two neighbouring changes would
261-// produce overlapping @@ headers, and the patch would be refused.
262-func hunks(lines []line) []hunk {
263- var out []hunk
264- i := 0
265- for i < len(lines) {
266- if lines[i].op == keep {
267- i++
268- continue
269- }
270- start := max(0, i-contextLines)
271- if n := len(out); n > 0 {
272- if prevEnd := indexAfter(lines, out[n-1]); prevEnd >= start {
273- out[n-1] = append(out[n-1], lines[prevEnd:hunkEnd(lines, i)]...)
274- i = hunkEnd(lines, i)
275- continue
276- }
277- }
278- out = append(out, append(hunk(nil), lines[start:hunkEnd(lines, i)]...))
279- i = hunkEnd(lines, i)
280- }
281- return out
282-}
283-
284-// hunkEnd finds the end of the piece opened at `i`: advance while a change
285-// occurs within `contextLines` lines, then keep the trailing context.
286-func hunkEnd(lines []line, i int) int {
287- last := i
288- for j := i; j < len(lines); j++ {
289- if lines[j].op != keep {
290- last = j
291- continue
292- }
293- if j-last > contextLines {
294- break
295- }
296- }
297- return min(len(lines), last+contextLines+1)
298-}
299-
300-// indexAfter returns the position, in `lines`, of the line following the last
301-// element of `h`.
302-func indexAfter(lines []line, h hunk) int {
303- if len(h) == 0 {
304- return 0
305- }
306- target := h[len(h)-1]
307- for i, l := range lines {
308- if l == target {
309- return i + 1
310- }
311- }
312- return 0
313-}
314-
315-// ranges computes the @@ header of the piece.
316-func (h hunk) ranges() (oldStart, oldCount, newStart, newCount int) {
317- for _, l := range h {
318- if l.op != add {
319- if oldStart == 0 {
320- oldStart = l.oldNo
321- }
322- oldCount++
323- }
324- if l.op != del {
325- if newStart == 0 {
326- newStart = l.newNo
327- }
328- newCount++
329- }
330- }
331- if oldCount == 0 {
332- oldStart = 0
333- }
334- if newCount == 0 {
335- newStart = 0
336- }
337- return oldStart, oldCount, newStart, newCount
338-}
339-
340-// render formats the diff for the screen and for the model: a line number, a
341-// sign, the text. No colours here at all — the same text goes back to the
342-// model, and ANSI codes in a tool result only get in its way; the screen gets
343-// its grey from the caller's preview mechanism.
344-//
345-// The number shown is ALWAYS the new version's: the one to look at after the
346-// edit. A deleted line no longer exists there, so it gets the number of the
347-// place where it vanished — a replacement shows "-" and "+" on the SAME number
348-// and the column never goes backwards.
349-func (r comparison) render() string {
350- if !changed(r.lines) {
351- return ""
352- }
353- var b strings.Builder
354- for _, h := range hunks(r.lines) {
355- current := 0
356- for _, l := range h {
357- no := l.newNo
358- if no > 0 {
359- current = no
360- } else {
361- no = current + 1
362- }
363- fmt.Fprintf(&b, "%4d %c %s\n", no, l.op, l.text)
364- }
365- }
366- return b.String()
367-}
@@ -1,7 +1,6 @@
1 package fileedit1 package fileedit
2 2
3 import (3 import (
4- "fmt"
5 "strings"4 "strings"
6 )5 )
7 6
@@ -138,18 +137,28 @@ func middle(old, new []string, off int) []line {
138 return nil137 return nil
139 }138 }
140 if len(old)*len(new) > maxCells {139 if len(old)*len(new) > maxCells {
141- out := make([]line, 0, len(old)+len(new))140+ return replaced(old, new, off)
142- for i, l := range old {141+ }
143- out = append(out, line{del, l, off + i + 1, 0})142+ return walk(old, new, lcsTable(old, new), off)
144- }143+}
145- for j, l := range new {144+
146- out = append(out, line{add, l, 0, off + j + 1})145+// replaced is old deleted then new added, line for line: the diff of two
147- }146+// texts too large for the LCS table.
148- return out147+func replaced(old, new []string, off int) []line {
148+ out := make([]line, 0, len(old)+len(new))
149+ for i, l := range old {
150+ out = append(out, line{del, l, off + i + 1, 0})
151+ }
152+ for j, l := range new {
153+ out = append(out, line{add, l, 0, off + j + 1})
149 }154 }
155+ return out
156+}
150 157
151- // Classic LCS: length table, then walk. Files edited by an agent fit in it158+// lcsTable is the classic LCS length table: lcs[i][j] is the length of the
152- // comfortably.159+// longest common subsequence of old[i:] and new[j:]. Files edited by an
160+// agent fit in it comfortably.
161+func lcsTable(old, new []string) [][]int {
153 lcs := make([][]int, len(old)+1)162 lcs := make([][]int, len(old)+1)
154 for i := range lcs {163 for i := range lcs {
155 lcs[i] = make([]int, len(new)+1)164 lcs[i] = make([]int, len(new)+1)
@@ -163,7 +172,11 @@ func middle(old, new []string, off int) []line {
163 }172 }
164 }173 }
165 }174 }
175+ return lcs
176+}
166 177
178+// walk reads the diff off the LCS table: kept lines, deletions, additions.
179+func walk(old, new []string, lcs [][]int, off int) []line {
167 var out []line180 var out []line
168 i, j := 0, 0181 i, j := 0, 0
169 for i < len(old) && j < len(new) {182 for i < len(old) && j < len(new) {
@@ -221,147 +234,3 @@ const noNewline = `\ No newline at end of file`
221 // contextLines is how many unchanged lines are kept around each change. Three234 // contextLines is how many unchanged lines are kept around each change. Three
222 // is the value of `diff -u` and of git.235 // is the value of `diff -u` and of git.
223 const contextLines = 3236 const contextLines = 3
224-
225-// unified renders a unified patch, applicable as-is by `patch -p1` or
226-// `git apply`. Paths are prefixed a/ and b/ like git does.
227-func (r comparison) unified(path string) string {
228- if !changed(r.lines) {
229- return ""
230- }
231- var b strings.Builder
232- fmt.Fprintf(&b, "--- a/%s\n+++ b/%s\n", path, path)
233-
234- lastOld, lastNew := 0, 0
235- for _, l := range r.lines {
236- lastOld, lastNew = max(lastOld, l.oldNo), max(lastNew, l.newNo)
237- }
238- for _, h := range hunks(r.lines) {
239- oldStart, oldCount, newStart, newCount := h.ranges()
240- fmt.Fprintf(&b, "@@ -%d,%d +%d,%d @@\n", oldStart, oldCount, newStart, newCount)
241- for _, l := range h {
242- b.WriteByte(byte(l.op))
243- b.WriteString(l.text)
244- b.WriteByte('\n')
245- // The marker follows the LAST line of each version, and a kept
246- // line belongs to both: it may carry it for both at once.
247- if (!r.oldNL && l.oldNo == lastOld && l.op != add) ||
248- (!r.newNL && l.newNo == lastNew && l.op != del) {
249- b.WriteString(noNewline + "\n")
250- }
251- }
252- }
253- return b.String()
254-}
255-
256-// hunk is a group of contiguous lines shown together.
257-type hunk []line
258-
259-// hunks cuts the diff into pieces: each change plus `contextLines` on both
260-// sides. Touching pieces are merged — otherwise two neighbouring changes would
261-// produce overlapping @@ headers, and the patch would be refused.
262-func hunks(lines []line) []hunk {
263- var out []hunk
264- i := 0
265- for i < len(lines) {
266- if lines[i].op == keep {
267- i++
268- continue
269- }
270- start := max(0, i-contextLines)
271- if n := len(out); n > 0 {
272- if prevEnd := indexAfter(lines, out[n-1]); prevEnd >= start {
273- out[n-1] = append(out[n-1], lines[prevEnd:hunkEnd(lines, i)]...)
274- i = hunkEnd(lines, i)
275- continue
276- }
277- }
278- out = append(out, append(hunk(nil), lines[start:hunkEnd(lines, i)]...))
279- i = hunkEnd(lines, i)
280- }
281- return out
282-}
283-
284-// hunkEnd finds the end of the piece opened at `i`: advance while a change
285-// occurs within `contextLines` lines, then keep the trailing context.
286-func hunkEnd(lines []line, i int) int {
287- last := i
288- for j := i; j < len(lines); j++ {
289- if lines[j].op != keep {
290- last = j
291- continue
292- }
293- if j-last > contextLines {
294- break
295- }
296- }
297- return min(len(lines), last+contextLines+1)
298-}
299-
300-// indexAfter returns the position, in `lines`, of the line following the last
301-// element of `h`.
302-func indexAfter(lines []line, h hunk) int {
303- if len(h) == 0 {
304- return 0
305- }
306- target := h[len(h)-1]
307- for i, l := range lines {
308- if l == target {
309- return i + 1
310- }
311- }
312- return 0
313-}
314-
315-// ranges computes the @@ header of the piece.
316-func (h hunk) ranges() (oldStart, oldCount, newStart, newCount int) {
317- for _, l := range h {
318- if l.op != add {
319- if oldStart == 0 {
320- oldStart = l.oldNo
321- }
322- oldCount++
323- }
324- if l.op != del {
325- if newStart == 0 {
326- newStart = l.newNo
327- }
328- newCount++
329- }
330- }
331- if oldCount == 0 {
332- oldStart = 0
333- }
334- if newCount == 0 {
335- newStart = 0
336- }
337- return oldStart, oldCount, newStart, newCount
338-}
339-
340-// render formats the diff for the screen and for the model: a line number, a
341-// sign, the text. No colours here at all — the same text goes back to the
342-// model, and ANSI codes in a tool result only get in its way; the screen gets
343-// its grey from the caller's preview mechanism.
344-//
345-// The number shown is ALWAYS the new version's: the one to look at after the
346-// edit. A deleted line no longer exists there, so it gets the number of the
347-// place where it vanished — a replacement shows "-" and "+" on the SAME number
348-// and the column never goes backwards.
349-func (r comparison) render() string {
350- if !changed(r.lines) {
351- return ""
352- }
353- var b strings.Builder
354- for _, h := range hunks(r.lines) {
355- current := 0
356- for _, l := range h {
357- no := l.newNo
358- if no > 0 {
359- current = no
360- } else {
361- no = current + 1
362- }
363- fmt.Fprintf(&b, "%4d %c %s\n", no, l.op, l.text)
364- }
365- }
366- return b.String()
367-}
added internal/fileedit/diff_render.go +150 -0
new file mode 100644
@@ -0,0 +1,150 @@
1+package fileedit
2+
3+import (
4+ "fmt"
5+ "strings"
6+)
7+
8+// unified renders a unified patch, applicable as-is by `patch -p1` or
9+// `git apply`. Paths are prefixed a/ and b/ like git does.
10+func (r comparison) unified(path string) string {
11+ if !changed(r.lines) {
12+ return ""
13+ }
14+ var b strings.Builder
15+ fmt.Fprintf(&b, "--- a/%s\n+++ b/%s\n", path, path)
16+
17+ lastOld, lastNew := 0, 0
18+ for _, l := range r.lines {
19+ lastOld, lastNew = max(lastOld, l.oldNo), max(lastNew, l.newNo)
20+ }
21+ for _, h := range hunks(r.lines) {
22+ oldStart, oldCount, newStart, newCount := h.ranges()
23+ fmt.Fprintf(&b, "@@ -%d,%d +%d,%d @@\n", oldStart, oldCount, newStart, newCount)
24+ for _, l := range h {
25+ b.WriteByte(byte(l.op))
26+ b.WriteString(l.text)
27+ b.WriteByte('\n')
28+ // The marker follows the LAST line of each version, and a kept
29+ // line belongs to both: it may carry it for both at once.
30+ if (!r.oldNL && l.oldNo == lastOld && l.op != add) ||
31+ (!r.newNL && l.newNo == lastNew && l.op != del) {
32+ b.WriteString(noNewline + "\n")
33+ }
34+ }
35+ }
36+ return b.String()
37+}
38+
39+// hunk is a group of contiguous lines shown together.
40+type hunk []line
41+
42+// hunks cuts the diff into pieces: each change plus `contextLines` on both
43+// sides. Touching pieces are merged — otherwise two neighbouring changes would
44+// produce overlapping @@ headers, and the patch would be refused.
45+func hunks(lines []line) []hunk {
46+ var out []hunk
47+ i := 0
48+ for i < len(lines) {
49+ if lines[i].op == keep {
50+ i++
51+ continue
52+ }
53+ start := max(0, i-contextLines)
54+ if n := len(out); n > 0 {
55+ if prevEnd := indexAfter(lines, out[n-1]); prevEnd >= start {
56+ out[n-1] = append(out[n-1], lines[prevEnd:hunkEnd(lines, i)]...)
57+ i = hunkEnd(lines, i)
58+ continue
59+ }
60+ }
61+ out = append(out, append(hunk(nil), lines[start:hunkEnd(lines, i)]...))
62+ i = hunkEnd(lines, i)
63+ }
64+ return out
65+}
66+
67+// hunkEnd finds the end of the piece opened at `i`: advance while a change
68+// occurs within `contextLines` lines, then keep the trailing context.
69+func hunkEnd(lines []line, i int) int {
70+ last := i
71+ for j := i; j < len(lines); j++ {
72+ if lines[j].op != keep {
73+ last = j
74+ continue
75+ }
76+ if j-last > contextLines {
77+ break
78+ }
79+ }
80+ return min(len(lines), last+contextLines+1)
81+}
82+
83+// indexAfter returns the position, in `lines`, of the line following the last
84+// element of `h`.
85+func indexAfter(lines []line, h hunk) int {
86+ if len(h) == 0 {
87+ return 0
88+ }
89+ target := h[len(h)-1]
90+ for i, l := range lines {
91+ if l == target {
92+ return i + 1
93+ }
94+ }
95+ return 0
96+}
97+
98+// ranges computes the @@ header of the piece.
99+func (h hunk) ranges() (oldStart, oldCount, newStart, newCount int) {
100+ for _, l := range h {
101+ if l.op != add {
102+ if oldStart == 0 {
103+ oldStart = l.oldNo
104+ }
105+ oldCount++
106+ }
107+ if l.op != del {
108+ if newStart == 0 {
109+ newStart = l.newNo
110+ }
111+ newCount++
112+ }
113+ }
114+ if oldCount == 0 {
115+ oldStart = 0
116+ }
117+ if newCount == 0 {
118+ newStart = 0
119+ }
120+ return oldStart, oldCount, newStart, newCount
121+}
122+
123+// render formats the diff for the screen and for the model: a line number, a
124+// sign, the text. No colours here at all — the same text goes back to the
125+// model, and ANSI codes in a tool result only get in its way; the screen gets
126+// its grey from the caller's preview mechanism.
127+//
128+// The number shown is ALWAYS the new version's: the one to look at after the
129+// edit. A deleted line no longer exists there, so it gets the number of the
130+// place where it vanished — a replacement shows "-" and "+" on the SAME number
131+// and the column never goes backwards.
132+func (r comparison) render() string {
133+ if !changed(r.lines) {
134+ return ""
135+ }
136+ var b strings.Builder
137+ for _, h := range hunks(r.lines) {
138+ current := 0
139+ for _, l := range h {
140+ no := l.newNo
141+ if no > 0 {
142+ current = no
143+ } else {
144+ no = current + 1
145+ }
146+ fmt.Fprintf(&b, "%4d %c %s\n", no, l.op, l.text)
147+ }
148+ }
149+ return b.String()
150+}
new file mode 100644
@@ -0,0 +1,150 @@
1+package fileedit
2+
3+import (
4+ "fmt"
5+ "strings"
6+)
7+
8+// unified renders a unified patch, applicable as-is by `patch -p1` or
9+// `git apply`. Paths are prefixed a/ and b/ like git does.
10+func (r comparison) unified(path string) string {
11+ if !changed(r.lines) {
12+ return ""
13+ }
14+ var b strings.Builder
15+ fmt.Fprintf(&b, "--- a/%s\n+++ b/%s\n", path, path)
16+
17+ lastOld, lastNew := 0, 0
18+ for _, l := range r.lines {
19+ lastOld, lastNew = max(lastOld, l.oldNo), max(lastNew, l.newNo)
20+ }
21+ for _, h := range hunks(r.lines) {
22+ oldStart, oldCount, newStart, newCount := h.ranges()
23+ fmt.Fprintf(&b, "@@ -%d,%d +%d,%d @@\n", oldStart, oldCount, newStart, newCount)
24+ for _, l := range h {
25+ b.WriteByte(byte(l.op))
26+ b.WriteString(l.text)
27+ b.WriteByte('\n')
28+ // The marker follows the LAST line of each version, and a kept
29+ // line belongs to both: it may carry it for both at once.
30+ if (!r.oldNL && l.oldNo == lastOld && l.op != add) ||
31+ (!r.newNL && l.newNo == lastNew && l.op != del) {
32+ b.WriteString(noNewline + "\n")
33+ }
34+ }
35+ }
36+ return b.String()
37+}
38+
39+// hunk is a group of contiguous lines shown together.
40+type hunk []line
41+
42+// hunks cuts the diff into pieces: each change plus `contextLines` on both
43+// sides. Touching pieces are merged — otherwise two neighbouring changes would
44+// produce overlapping @@ headers, and the patch would be refused.
45+func hunks(lines []line) []hunk {
46+ var out []hunk
47+ i := 0
48+ for i < len(lines) {
49+ if lines[i].op == keep {
50+ i++
51+ continue
52+ }
53+ start := max(0, i-contextLines)
54+ if n := len(out); n > 0 {
55+ if prevEnd := indexAfter(lines, out[n-1]); prevEnd >= start {
56+ out[n-1] = append(out[n-1], lines[prevEnd:hunkEnd(lines, i)]...)
57+ i = hunkEnd(lines, i)
58+ continue
59+ }
60+ }
61+ out = append(out, append(hunk(nil), lines[start:hunkEnd(lines, i)]...))
62+ i = hunkEnd(lines, i)
63+ }
64+ return out
65+}
66+
67+// hunkEnd finds the end of the piece opened at `i`: advance while a change
68+// occurs within `contextLines` lines, then keep the trailing context.
69+func hunkEnd(lines []line, i int) int {
70+ last := i
71+ for j := i; j < len(lines); j++ {
72+ if lines[j].op != keep {
73+ last = j
74+ continue
75+ }
76+ if j-last > contextLines {
77+ break
78+ }
79+ }
80+ return min(len(lines), last+contextLines+1)
81+}
82+
83+// indexAfter returns the position, in `lines`, of the line following the last
84+// element of `h`.
85+func indexAfter(lines []line, h hunk) int {
86+ if len(h) == 0 {
87+ return 0
88+ }
89+ target := h[len(h)-1]
90+ for i, l := range lines {
91+ if l == target {
92+ return i + 1
93+ }
94+ }
95+ return 0
96+}
97+
98+// ranges computes the @@ header of the piece.
99+func (h hunk) ranges() (oldStart, oldCount, newStart, newCount int) {
100+ for _, l := range h {
101+ if l.op != add {
102+ if oldStart == 0 {
103+ oldStart = l.oldNo
104+ }
105+ oldCount++
106+ }
107+ if l.op != del {
108+ if newStart == 0 {
109+ newStart = l.newNo
110+ }
111+ newCount++
112+ }
113+ }
114+ if oldCount == 0 {
115+ oldStart = 0
116+ }
117+ if newCount == 0 {
118+ newStart = 0
119+ }
120+ return oldStart, oldCount, newStart, newCount
121+}
122+
123+// render formats the diff for the screen and for the model: a line number, a
124+// sign, the text. No colours here at all — the same text goes back to the
125+// model, and ANSI codes in a tool result only get in its way; the screen gets
126+// its grey from the caller's preview mechanism.
127+//
128+// The number shown is ALWAYS the new version's: the one to look at after the
129+// edit. A deleted line no longer exists there, so it gets the number of the
130+// place where it vanished — a replacement shows "-" and "+" on the SAME number
131+// and the column never goes backwards.
132+func (r comparison) render() string {
133+ if !changed(r.lines) {
134+ return ""
135+ }
136+ var b strings.Builder
137+ for _, h := range hunks(r.lines) {
138+ current := 0
139+ for _, l := range h {
140+ no := l.newNo
141+ if no > 0 {
142+ current = no
143+ } else {
144+ no = current + 1
145+ }
146+ fmt.Fprintf(&b, "%4d %c %s\n", no, l.op, l.text)
147+ }
148+ }
149+ return b.String()
150+}
modified internal/fileedit/edits.go +54 -24
@@ -42,7 +42,22 @@ func apply(body string, list []Edit) (string, int, error) {
4242 if len(list) == 0 {
4343 return "", 0, fmt.Errorf("no edit given: each edit needs an old and a new text")
4444 }
45+ spans, loose, err := resolve(body, list)
46+ if err != nil {
47+ return "", 0, err
48+ }
49+ // Sorted by position: the overlap check and the rebuild both walk the file
50+ // in its order, not in the order of the request.
51+ sort.Slice(spans, func(i, j int) bool { return spans[i].start < spans[j].start })
52+ if err := checkOverlaps(body, spans); err != nil {
53+ return "", 0, err
54+ }
55+ return rebuild(body, spans), loose, nil
56+}
4557
58+// resolve finds the span of every edit in the original body, and counts
59+// those matched ignoring whitespace.
60+func resolve(body string, list []Edit) ([]span, int, error) {
4661 loose := 0
4762 spans := make([]span, 0, len(list))
4863 for i, e := range list {
@@ -52,34 +67,41 @@ func apply(body string, list []Edit) (string, int, error) {
5267 // hold means the model's picture of the file is wrong, and it is
5368 // told so the same way as any miss.
5469 if err := present(body, e, i); err != nil {
55- return "", 0, err
70+ return nil, 0, err
5671 }
5772 continue
5873 }
5974 s, err := locate(body, e, i)
6075 if err != nil {
61- return "", 0, err
76+ return nil, 0, err
6277 }
6378 if s.loose {
6479 loose++
6580 }
6681 spans = append(spans, s)
6782 }
83+ return spans, loose, nil
84+}
6885
69- // Sorted by position: the overlap check and the rebuild both walk the file
70- // in its order, not in the order of the request.
71- sort.Slice(spans, func(i, j int) bool { return spans[i].start < spans[j].start })
86+// checkOverlaps refuses two edits that touch, nest or repeat: spans sorted
87+// by position.
88+func checkOverlaps(body string, spans []span) error {
7289 for i := 1; i < len(spans); i++ {
7390 if spans[i].start < spans[i-1].end {
7491 a, b := spans[i-1], spans[i]
75- return "", 0, fmt.Errorf(
92+ return fmt.Errorf(
7693 "edits #%d and #%d overlap (lines %d-%d and %d-%d): merge them into a single old/new pair",
7794 a.index+1, b.index+1,
7895 lineOf(body, a.start), lineOf(body, a.end),
7996 lineOf(body, b.start), lineOf(body, b.end))
8097 }
8198 }
99+ return nil
100+}
82101
102+// rebuild is the body with every span replaced by its text: spans sorted by
103+// position, none overlapping.
104+func rebuild(body string, spans []span) string {
83105 var b strings.Builder
84106 at := 0
85107 for _, s := range spans {
@@ -88,7 +110,7 @@ func apply(body string, list []Edit) (string, int, error) {
88110 at = s.end
89111 }
90112 b.WriteString(body[at:])
91- return b.String(), loose, nil
113+ return b.String()
92114 }
93115
94116 // locate finds the single occurrence of an `old` text.
@@ -106,26 +128,34 @@ func locate(body string, e Edit, i int) (span, error) {
106128 case 0:
107129 return span{}, notFound(body, e, i)
108130 case 1:
109- m := spans[0]
110- return span{start: m.start, end: m.end, index: i, text: m.text, loose: loose}, nil
111- }
112- // Several occurrences: `line` picks one (ticket 241). A small model
113- // knows WHICH line it wants — Mellum2 and Olala both said "line 8" —
114- // but could not widen old until it was unique; given the line numbers in
115- // the message below, it only has to copy one back.
116- if e.Line > 0 {
117- for _, m := range spans {
118- if lineOf(body, m.start) == e.Line {
119- return span{start: m.start, end: m.end, index: i, text: m.text, loose: loose}, nil
120- }
121- }
131+ return spans[0].at(i, loose), nil
132+ }
133+ return pickOccurrence(body, e, i, spans, loose)
134+}
135+
136+// at is the match as the span of edit i.
137+func (m match) at(i int, loose bool) span {
138+ return span{start: m.start, end: m.end, index: i, text: m.text, loose: loose}
139+}
140+
141+// pickOccurrence chooses among several occurrences: `line` picks one
142+// (ticket 241). A small model knows WHICH line it wants — Mellum2 and Olala
143+// both said "line 8" — but could not widen old until it was unique; given
144+// the line numbers in the message below, it only has to copy one back.
145+func pickOccurrence(body string, e Edit, i int, spans []match, loose bool) (span, error) {
146+ if e.Line <= 0 {
122147 return span{}, fmt.Errorf(
123- "edit #%d: old text appears %d times, at lines %s — none starts at line %d: give one of these lines in \"line\"",
124- i+1, len(spans), occurrenceLines(body, spans), e.Line)
148+ "edit #%d: old text appears %d times (lines %s) — to change ONE of them, add \"line\": the number of the line where it starts (one of %s); or include its surrounding lines in old until the text is unique; to change several, send one edit per place:\n%s",
149+ i+1, len(spans), occurrenceLines(body, spans), occurrenceLines(body, spans), quote(e.Old))
150+ }
151+ for _, m := range spans {
152+ if lineOf(body, m.start) == e.Line {
153+ return m.at(i, loose), nil
154+ }
125155 }
126156 return span{}, fmt.Errorf(
127- "edit #%d: old text appears %d times (lines %s) — to change ONE of them, add \"line\": the number of the line where it starts (one of %s); or include its surrounding lines in old until the text is unique; to change several, send one edit per place:\n%s",
128- i+1, len(spans), occurrenceLines(body, spans), occurrenceLines(body, spans), quote(e.Old))
157+ "edit #%d: old text appears %d times, at lines %s — none starts at line %d: give one of these lines in \"line\"",
158+ i+1, len(spans), occurrenceLines(body, spans), e.Line)
129159 }
130160
131161 // present checks that the text of an edit whose old and new are identical is
@@ -42,7 +42,22 @@ func apply(body string, list []Edit) (string, int, error) {
42 if len(list) == 0 {42 if len(list) == 0 {
43 return "", 0, fmt.Errorf("no edit given: each edit needs an old and a new text")43 return "", 0, fmt.Errorf("no edit given: each edit needs an old and a new text")
44 }44 }
45+ spans, loose, err := resolve(body, list)
46+ if err != nil {
47+ return "", 0, err
48+ }
49+ // Sorted by position: the overlap check and the rebuild both walk the file
50+ // in its order, not in the order of the request.
51+ sort.Slice(spans, func(i, j int) bool { return spans[i].start < spans[j].start })
52+ if err := checkOverlaps(body, spans); err != nil {
53+ return "", 0, err
54+ }
55+ return rebuild(body, spans), loose, nil
56+}
45 57
58+// resolve finds the span of every edit in the original body, and counts
59+// those matched ignoring whitespace.
60+func resolve(body string, list []Edit) ([]span, int, error) {
46 loose := 061 loose := 0
47 spans := make([]span, 0, len(list))62 spans := make([]span, 0, len(list))
48 for i, e := range list {63 for i, e := range list {
@@ -52,34 +67,41 @@ func apply(body string, list []Edit) (string, int, error) {
52 // hold means the model's picture of the file is wrong, and it is67 // hold means the model's picture of the file is wrong, and it is
53 // told so the same way as any miss.68 // told so the same way as any miss.
54 if err := present(body, e, i); err != nil {69 if err := present(body, e, i); err != nil {
55- return "", 0, err70+ return nil, 0, err
56 }71 }
57 continue72 continue
58 }73 }
59 s, err := locate(body, e, i)74 s, err := locate(body, e, i)
60 if err != nil {75 if err != nil {
61- return "", 0, err76+ return nil, 0, err
62 }77 }
63 if s.loose {78 if s.loose {
64 loose++79 loose++
65 }80 }
66 spans = append(spans, s)81 spans = append(spans, s)
67 }82 }
83+ return spans, loose, nil
84+}
68 85
69- // Sorted by position: the overlap check and the rebuild both walk the file86+// checkOverlaps refuses two edits that touch, nest or repeat: spans sorted
70- // in its order, not in the order of the request.87+// by position.
71- sort.Slice(spans, func(i, j int) bool { return spans[i].start < spans[j].start })88+func checkOverlaps(body string, spans []span) error {
72 for i := 1; i < len(spans); i++ {89 for i := 1; i < len(spans); i++ {
73 if spans[i].start < spans[i-1].end {90 if spans[i].start < spans[i-1].end {
74 a, b := spans[i-1], spans[i]91 a, b := spans[i-1], spans[i]
75- return "", 0, fmt.Errorf(92+ return fmt.Errorf(
76 "edits #%d and #%d overlap (lines %d-%d and %d-%d): merge them into a single old/new pair",93 "edits #%d and #%d overlap (lines %d-%d and %d-%d): merge them into a single old/new pair",
77 a.index+1, b.index+1,94 a.index+1, b.index+1,
78 lineOf(body, a.start), lineOf(body, a.end),95 lineOf(body, a.start), lineOf(body, a.end),
79 lineOf(body, b.start), lineOf(body, b.end))96 lineOf(body, b.start), lineOf(body, b.end))
80 }97 }
81 }98 }
99+ return nil
100+}
82 101
102+// rebuild is the body with every span replaced by its text: spans sorted by
103+// position, none overlapping.
104+func rebuild(body string, spans []span) string {
83 var b strings.Builder105 var b strings.Builder
84 at := 0106 at := 0
85 for _, s := range spans {107 for _, s := range spans {
@@ -88,7 +110,7 @@ func apply(body string, list []Edit) (string, int, error) {
88 at = s.end110 at = s.end
89 }111 }
90 b.WriteString(body[at:])112 b.WriteString(body[at:])
91- return b.String(), loose, nil113+ return b.String()
92 }114 }
93 115
94 // locate finds the single occurrence of an `old` text.116 // locate finds the single occurrence of an `old` text.
@@ -106,26 +128,34 @@ func locate(body string, e Edit, i int) (span, error) {
106 case 0:128 case 0:
107 return span{}, notFound(body, e, i)129 return span{}, notFound(body, e, i)
108 case 1:130 case 1:
109- m := spans[0]131+ return spans[0].at(i, loose), nil
110- return span{start: m.start, end: m.end, index: i, text: m.text, loose: loose}, nil132+ }
111- }133+ return pickOccurrence(body, e, i, spans, loose)
112- // Several occurrences: `line` picks one (ticket 241). A small model134+}
113- // knows WHICH line it wants — Mellum2 and Olala both said "line 8" —135+
114- // but could not widen old until it was unique; given the line numbers in136+// at is the match as the span of edit i.
115- // the message below, it only has to copy one back.137+func (m match) at(i int, loose bool) span {
116- if e.Line > 0 {138+ return span{start: m.start, end: m.end, index: i, text: m.text, loose: loose}
117- for _, m := range spans {139+}
118- if lineOf(body, m.start) == e.Line {140+
119- return span{start: m.start, end: m.end, index: i, text: m.text, loose: loose}, nil141+// pickOccurrence chooses among several occurrences: `line` picks one
120- }142+// (ticket 241). A small model knows WHICH line it wants — Mellum2 and Olala
121- }143+// both said "line 8" — but could not widen old until it was unique; given
144+// the line numbers in the message below, it only has to copy one back.
145+func pickOccurrence(body string, e Edit, i int, spans []match, loose bool) (span, error) {
146+ if e.Line <= 0 {
122 return span{}, fmt.Errorf(147 return span{}, fmt.Errorf(
123- "edit #%d: old text appears %d times, at lines %s — none starts at line %d: give one of these lines in \"line\"",148+ "edit #%d: old text appears %d times (lines %s) — to change ONE of them, add \"line\": the number of the line where it starts (one of %s); or include its surrounding lines in old until the text is unique; to change several, send one edit per place:\n%s",
124- i+1, len(spans), occurrenceLines(body, spans), e.Line)149+ i+1, len(spans), occurrenceLines(body, spans), occurrenceLines(body, spans), quote(e.Old))
150+ }
151+ for _, m := range spans {
152+ if lineOf(body, m.start) == e.Line {
153+ return m.at(i, loose), nil
154+ }
125 }155 }
126 return span{}, fmt.Errorf(156 return span{}, fmt.Errorf(
127- "edit #%d: old text appears %d times (lines %s) — to change ONE of them, add \"line\": the number of the line where it starts (one of %s); or include its surrounding lines in old until the text is unique; to change several, send one edit per place:\n%s",157+ "edit #%d: old text appears %d times, at lines %s — none starts at line %d: give one of these lines in \"line\"",
128- i+1, len(spans), occurrenceLines(body, spans), occurrenceLines(body, spans), quote(e.Old))158+ i+1, len(spans), occurrenceLines(body, spans), e.Line)
129 }159 }
130 160
131 // present checks that the text of an edit whose old and new are identical is161 // present checks that the text of an edit whose old and new are identical is
modified internal/fileedit/fileedit.go +23 -8
@@ -154,16 +154,34 @@ func finish(r Result, f *file, body string) (Result, error) {
154154 // headline sums the operation up in one line — the one the model re-reads in
155155 // its tool result, and the one the screen shows under the display line.
156156 func headline(r Result) string {
157+ if line, ok := unchangedOrCreated(r); ok {
158+ return line
159+ }
160+ what := changeSummary(r)
161+ if r.DryRun {
162+ return fmt.Sprintf("%s: dry run — nothing written (%s)", r.Path, what)
163+ }
164+ return fmt.Sprintf("%s: %s", r.Path, what)
165+}
166+
167+// unchangedOrCreated is the headline of a file left as it was or created.
168+func unchangedOrCreated(r Result) (string, bool) {
157169 switch {
158170 case !r.Changed && r.Already > 0:
159- return fmt.Sprintf("%s: unchanged — already as asked: %d edit(s) with identical old and new, nothing to change", r.Path, r.Already)
171+ return fmt.Sprintf("%s: unchanged — already as asked: %d edit(s) with identical old and new, nothing to change", r.Path, r.Already), true
160172 case !r.Changed:
161- return fmt.Sprintf("%s: unchanged", r.Path)
173+ return fmt.Sprintf("%s: unchanged", r.Path), true
162174 case r.Created && r.DryRun:
163- return fmt.Sprintf("%s: would be created, %d line(s)", r.Path, r.Added)
175+ return fmt.Sprintf("%s: would be created, %d line(s)", r.Path, r.Added), true
164176 case r.Created:
165- return fmt.Sprintf("%s: created, %d line(s)", r.Path, r.Added)
177+ return fmt.Sprintf("%s: created, %d line(s)", r.Path, r.Added), true
166178 }
179+ return "", false
180+}
181+
182+// changeSummary says what changed in an existing file: lines added and
183+// deleted, the first change, and how the edits matched.
184+func changeSummary(r Result) string {
167185 what := fmt.Sprintf("+%d -%d, first change at line %d", r.Added, r.Deleted, r.FirstChangedLine)
168186 if r.Edits > 0 {
169187 what = fmt.Sprintf("%d edit(s) applied, %s", r.Edits, what)
@@ -174,8 +192,5 @@ func headline(r Result) string {
174192 if r.Already > 0 {
175193 what += fmt.Sprintf(" · %d already as asked (identical old and new)", r.Already)
176194 }
177- if r.DryRun {
178- return fmt.Sprintf("%s: dry run — nothing written (%s)", r.Path, what)
179- }
180- return fmt.Sprintf("%s: %s", r.Path, what)
195+ return what
181196 }
@@ -154,16 +154,34 @@ func finish(r Result, f *file, body string) (Result, error) {
154 // headline sums the operation up in one line — the one the model re-reads in154 // headline sums the operation up in one line — the one the model re-reads in
155 // its tool result, and the one the screen shows under the display line.155 // its tool result, and the one the screen shows under the display line.
156 func headline(r Result) string {156 func headline(r Result) string {
157+ if line, ok := unchangedOrCreated(r); ok {
158+ return line
159+ }
160+ what := changeSummary(r)
161+ if r.DryRun {
162+ return fmt.Sprintf("%s: dry run — nothing written (%s)", r.Path, what)
163+ }
164+ return fmt.Sprintf("%s: %s", r.Path, what)
165+}
166+
167+// unchangedOrCreated is the headline of a file left as it was or created.
168+func unchangedOrCreated(r Result) (string, bool) {
157 switch {169 switch {
158 case !r.Changed && r.Already > 0:170 case !r.Changed && r.Already > 0:
159- return fmt.Sprintf("%s: unchanged — already as asked: %d edit(s) with identical old and new, nothing to change", r.Path, r.Already)171+ return fmt.Sprintf("%s: unchanged — already as asked: %d edit(s) with identical old and new, nothing to change", r.Path, r.Already), true
160 case !r.Changed:172 case !r.Changed:
161- return fmt.Sprintf("%s: unchanged", r.Path)173+ return fmt.Sprintf("%s: unchanged", r.Path), true
162 case r.Created && r.DryRun:174 case r.Created && r.DryRun:
163- return fmt.Sprintf("%s: would be created, %d line(s)", r.Path, r.Added)175+ return fmt.Sprintf("%s: would be created, %d line(s)", r.Path, r.Added), true
164 case r.Created:176 case r.Created:
165- return fmt.Sprintf("%s: created, %d line(s)", r.Path, r.Added)177+ return fmt.Sprintf("%s: created, %d line(s)", r.Path, r.Added), true
166 }178 }
179+ return "", false
180+}
181+
182+// changeSummary says what changed in an existing file: lines added and
183+// deleted, the first change, and how the edits matched.
184+func changeSummary(r Result) string {
167 what := fmt.Sprintf("+%d -%d, first change at line %d", r.Added, r.Deleted, r.FirstChangedLine)185 what := fmt.Sprintf("+%d -%d, first change at line %d", r.Added, r.Deleted, r.FirstChangedLine)
168 if r.Edits > 0 {186 if r.Edits > 0 {
169 what = fmt.Sprintf("%d edit(s) applied, %s", r.Edits, what)187 what = fmt.Sprintf("%d edit(s) applied, %s", r.Edits, what)
@@ -174,8 +192,5 @@ func headline(r Result) string {
174 if r.Already > 0 {192 if r.Already > 0 {
175 what += fmt.Sprintf(" · %d already as asked (identical old and new)", r.Already)193 what += fmt.Sprintf(" · %d already as asked (identical old and new)", r.Already)
176 }194 }
177- if r.DryRun {195+ return what
178- return fmt.Sprintf("%s: dry run — nothing written (%s)", r.Path, what)
179- }
180- return fmt.Sprintf("%s: %s", r.Path, what)
181 }196 }
modified internal/fileedit/textfile.go +15 -8
@@ -102,14 +102,7 @@ func (f *file) write(body string) error {
102102 }
103103 defer func() { _ = os.Remove(tmp.Name()) }() // no effect once the rename succeeded
104104
105- if _, err := tmp.WriteString(f.render(body)); err != nil {
106- _ = tmp.Close() // the write error is the one worth reporting
107- return err
108- }
109- if err := tmp.Close(); err != nil {
110- return err
111- }
112- if err := os.Chmod(tmp.Name(), f.mode); err != nil {
105+ if err := fill(tmp, f.render(body), f.mode); err != nil {
113106 return err
114107 }
115108 if err := os.Rename(tmp.Name(), f.path); err != nil {
@@ -118,3 +111,17 @@ func (f *file) write(body string) error {
118111 f.body, f.isNew = body, false
119112 return nil
120113 }
114+
115+// fill writes content into the temporary file, closes it and gives it the
116+// file's mode. A failed write closes it anyway: the write error is the one
117+// worth reporting.
118+func fill(tmp *os.File, content string, mode os.FileMode) error {
119+ if _, err := tmp.WriteString(content); err != nil {
120+ _ = tmp.Close()
121+ return err
122+ }
123+ if err := tmp.Close(); err != nil {
124+ return err
125+ }
126+ return os.Chmod(tmp.Name(), mode)
127+}
@@ -102,14 +102,7 @@ func (f *file) write(body string) error {
102 }102 }
103 defer func() { _ = os.Remove(tmp.Name()) }() // no effect once the rename succeeded103 defer func() { _ = os.Remove(tmp.Name()) }() // no effect once the rename succeeded
104 104
105- if _, err := tmp.WriteString(f.render(body)); err != nil {105+ if err := fill(tmp, f.render(body), f.mode); err != nil {
106- _ = tmp.Close() // the write error is the one worth reporting
107- return err
108- }
109- if err := tmp.Close(); err != nil {
110- return err
111- }
112- if err := os.Chmod(tmp.Name(), f.mode); err != nil {
113 return err106 return err
114 }107 }
115 if err := os.Rename(tmp.Name(), f.path); err != nil {108 if err := os.Rename(tmp.Name(), f.path); err != nil {
@@ -118,3 +111,17 @@ func (f *file) write(body string) error {
118 f.body, f.isNew = body, false111 f.body, f.isNew = body, false
119 return nil112 return nil
120 }113 }
114+
115+// fill writes content into the temporary file, closes it and gives it the
116+// file's mode. A failed write closes it anyway: the write error is the one
117+// worth reporting.
118+func fill(tmp *os.File, content string, mode os.FileMode) error {
119+ if _, err := tmp.WriteString(content); err != nil {
120+ _ = tmp.Close()
121+ return err
122+ }
123+ if err := tmp.Close(); err != nil {
124+ return err
125+ }
126+ return os.Chmod(tmp.Name(), mode)
127+}