-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patheditor.go
More file actions
367 lines (343 loc) · 9.2 KB
/
Copy patheditor.go
File metadata and controls
367 lines (343 loc) · 9.2 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
package hpatch
import (
"cmp"
"fmt"
"slices"
"strings"
)
type targetSpan struct {
start int
end int
linewise bool
}
type editOrigin struct {
command int
line int
operation string
target targetVariant
multilineValue bool
}
type baselineEdit struct {
editOrigin
start int
end int
targetStart int
targetEnd int
replacement string
sequence int
}
type editor struct {
baseline string
edits []baselineEdit
lastOrigin editOrigin
finalContent *string
finalOffsets *formattedOffsetMap
}
type logicalLine struct {
start int
contentEnd int
fullEnd int
}
func (e *editor) resolveTarget(target targetSpec) ([]targetSpan, error) {
switch target.kind {
case targetLine:
line, err := resolveRow(e.baseline, target.start)
if err != nil {
return nil, err
}
return []targetSpan{{start: line.start, end: line.fullEnd, linewise: true}}, nil
case targetRange:
start, err := resolveRow(e.baseline, target.start)
if err != nil {
return nil, err
}
end, err := resolveRow(e.baseline, target.end)
if err != nil {
return nil, err
}
if target.start.line > target.end.line {
return nil, withReason(reasonTargetOrder, fmt.Errorf(
"row range start %d exceeds end %d",
target.start.line,
target.end.line,
))
}
return []targetSpan{{start: start.start, end: end.fullEnd, linewise: true}}, nil
case targetText:
anchor, err := resolveRow(e.baseline, target.start)
if err != nil {
return nil, err
}
offsets := nonOverlappingLiteralOffsets(e.baseline[anchor.start:], target.literal, target.count)
if len(offsets) != target.count {
return nil, withReason(reasonOccurrenceMissing, fmt.Errorf(
"found %d of %d requested matches of %q at or after line %d",
len(offsets),
target.count,
target.literal,
target.start.line,
))
}
spans := make([]targetSpan, len(offsets))
for index, offset := range offsets {
start := anchor.start + offset
spans[index] = targetSpan{start: start, end: start + len(target.literal)}
}
return spans, nil
default:
return nil, withReason(reasonInitialization, fmt.Errorf("mutation requires an explicit target"))
}
}
func resolveRow(baseline string, reference rowReference) (logicalLine, error) {
lines := logicalLines(baseline)
if reference.line < 1 || reference.line > len(lines) {
return logicalLine{}, withReason(reasonRowMissing, fmt.Errorf(
"row %d is outside immutable baseline with %d lines",
reference.line,
len(lines),
))
}
line := lines[reference.line-1]
actual := hashLine(lineContent(baseline, line))
if actual != reference.hash {
return logicalLine{}, withReason(reasonRowStale, fmt.Errorf(
"row %d is stale: expected hash %s, actual %s",
reference.line,
reference.hash,
actual,
))
}
return line, nil
}
func (e *editor) applyMutation(operation string, target targetSpec, value string, origin editOrigin) error {
spans, err := e.resolveTarget(target)
if err != nil {
return err
}
edits := make([]baselineEdit, len(spans))
for index, span := range spans {
replacement := value
start, end := span.start, span.end
switch operation {
case "type":
if replacement != "" && span.linewise && lineTerminatorSuffix(replacement) == "" {
replacement += lineTerminatorSuffix(e.baseline[span.start:span.end])
}
if len(spans) == 1 {
if correction := detectIndentationCorrection(e.baseline, span, replacement); correction != nil {
return correction
}
}
case "type-":
end = start
case "type+":
start = end
default:
panic("parsed instruction has no mutation executor: " + operation)
}
edits[index] = baselineEdit{
start: start,
end: end,
targetStart: span.start,
targetEnd: span.end,
replacement: replacement,
editOrigin: origin,
}
}
if err := e.recordEdits(edits); err != nil {
return withReason(reasonEditConflict, err)
}
return nil
}
func (e *editor) initialize(value string, origin editOrigin) {
e.baseline = ""
e.edits = nil
e.finalContent = nil
e.finalOffsets = nil
if value == "" {
return
}
e.edits = []baselineEdit{{
start: 0,
end: 0,
targetStart: 0,
targetEnd: 0,
replacement: value,
sequence: 1,
editOrigin: origin,
}}
e.lastOrigin = origin
}
func (e *editor) recordEdits(candidates []baselineEdit) error {
pending := slices.Clone(e.edits)
additions := make([]baselineEdit, 0, len(candidates))
for _, candidate := range candidates {
if candidate.start == candidate.end && candidate.replacement == "" {
continue
}
if candidate.start != candidate.end && candidate.replacement == e.baseline[candidate.start:candidate.end] {
continue
}
for _, existing := range pending {
description, conflict := describeEditConflict(e.baseline, existing, candidate)
if !conflict {
continue
}
return fmt.Errorf(
"conflicts with edit from command %d (source line %d, operation %q): %s",
existing.command,
existing.line,
existing.operation,
description,
)
}
candidate.sequence = len(pending) + 1
pending = append(pending, candidate)
additions = append(additions, candidate)
}
e.edits = append(e.edits, additions...)
if len(additions) != 0 {
e.lastOrigin = additions[len(additions)-1].editOrigin
}
return nil
}
func describeEditConflict(baseline string, first, second baselineEdit) (string, bool) {
firstInsertion := first.start == first.end
secondInsertion := second.start == second.end
switch {
case firstInsertion && secondInsertion:
return "", false
case firstInsertion:
if first.start <= second.start || first.start >= second.end {
return "", false
}
return fmt.Sprintf("baseline line %d is both replaced and inserted into", baselineLine(baseline, first.start)), true
case secondInsertion:
if second.start <= first.start || second.start >= first.end {
return "", false
}
return fmt.Sprintf("baseline line %d is both replaced and inserted into", baselineLine(baseline, second.start)), true
default:
start := max(first.start, second.start)
end := min(first.end, second.end)
if start >= end {
return "", false
}
startLine := baselineLine(baseline, start)
endLine := baselineLine(baseline, end-1)
if startLine == endLine {
return fmt.Sprintf("baseline line %d is modified by both edits", startLine), true
}
return fmt.Sprintf("baseline lines %d:%d are modified by both edits", startLine, endLine), true
}
}
func baselineLine(text string, offset int) int {
lines := logicalLines(text)
for index, line := range lines {
if offset < line.fullEnd {
return index + 1
}
}
if len(lines) == 0 {
return 1
}
return len(lines)
}
func (e *editor) firstEdit() (baselineEdit, bool) {
if len(e.edits) == 0 {
return baselineEdit{}, false
}
return e.edits[0], true
}
func (e *editor) orderedEdits() []baselineEdit {
return orderedBaselineEdits(e.edits)
}
func orderedBaselineEdits(source []baselineEdit) []baselineEdit {
edits := slices.Clone(source)
slices.SortFunc(edits, func(first, second baselineEdit) int {
if order := cmp.Compare(first.start, second.start); order != 0 {
return order
}
firstInsertion := first.start == first.end
secondInsertion := second.start == second.end
if firstInsertion != secondInsertion {
if firstInsertion {
return -1
}
return 1
}
return cmp.Compare(first.sequence, second.sequence)
})
return edits
}
func (e *editor) content() string {
if e.finalContent != nil {
return *e.finalContent
}
return e.contentWithEdits(e.edits)
}
func (e *editor) contentWithEdits(source []baselineEdit) string {
edits := orderedBaselineEdits(source)
var result strings.Builder
cursor := 0
for _, edit := range edits {
result.WriteString(e.baseline[cursor:edit.start])
result.WriteString(edit.replacement)
cursor = max(cursor, edit.end)
}
result.WriteString(e.baseline[cursor:])
return result.String()
}
func nonOverlappingLiteralOffsets(text, literal string, limit int) []int {
return findLiteralOffsets(text, literal, len(literal), limit)
}
func findLiteralOffsets(text, literal string, advance, limit int) []int {
var offsets []int
for searchFrom := 0; searchFrom <= len(text)-len(literal); {
relative := strings.Index(text[searchFrom:], literal)
if relative < 0 {
break
}
match := searchFrom + relative
offsets = append(offsets, match)
searchFrom = match + advance
if limit > 0 && len(offsets) == limit {
break
}
}
return offsets
}
func logicalLines(text string) []logicalLine {
var lines []logicalLine
for start := 0; start < len(text); {
contentEnd := start
for contentEnd < len(text) && text[contentEnd] != '\r' && text[contentEnd] != '\n' {
contentEnd++
}
fullEnd := contentEnd
if fullEnd < len(text) {
fullEnd++
if text[contentEnd] == '\r' && fullEnd < len(text) && text[fullEnd] == '\n' {
fullEnd++
}
}
lines = append(lines, logicalLine{start: start, contentEnd: contentEnd, fullEnd: fullEnd})
start = fullEnd
}
return lines
}
func lineTerminatorSuffix(text string) string {
switch {
case strings.HasSuffix(text, "\r\n"):
return "\r\n"
case strings.HasSuffix(text, "\n"):
return "\n"
case strings.HasSuffix(text, "\r"):
return "\r"
default:
return ""
}
}
func endsWithLineTerminator(text string) bool {
return lineTerminatorSuffix(text) != ""
}