-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapply_session.go
More file actions
376 lines (328 loc) · 9.07 KB
/
apply_session.go
File metadata and controls
376 lines (328 loc) · 9.07 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
368
369
370
371
372
373
374
375
376
package git_diff_parser
import "fmt"
type validatedPatch struct {
rejectHead string
hunks []patchHunk
}
type applySession struct {
applier *patchApply
sourceLines []fileLine
patched []bool
image []fileLine
cursor int
conflicts []applyConflict
rejectHead string
}
type matchedHunk struct {
sourceStart int
sourceEnd int
hunkStart int
hunkEnd int
}
func (p *patchApply) validateAndParsePatch(patchData []byte) (validatedPatch, error) {
normalizedPatch := normalizePatchForValidation(patchData)
parsed, errs := parse(string(normalizedPatch))
if len(errs) > 0 {
return validatedPatch{}, fmt.Errorf("unsupported patch syntax: %w", errs[0])
}
if len(parsed.FileDiff) != 1 {
return validatedPatch{}, fmt.Errorf("expected exactly 1 file diff, found %d", len(parsed.FileDiff))
}
fileDiff := parsed.FileDiff[0]
if err := validateApplyFileDiff(&fileDiff); err != nil {
return validatedPatch{}, err
}
hunks := make([]patchHunk, 0, len(fileDiff.Hunks))
for i := range fileDiff.Hunks {
hunks = append(hunks, patchHunkFromHunk(&fileDiff.Hunks[i]))
}
return validatedPatch{
rejectHead: formatRejectHeader(&fileDiff),
hunks: hunks,
}, nil
}
func (p *patchApply) newApplySession(pristine []byte) *applySession {
sourceLines := splitFileLines(pristine)
return &applySession{
applier: p,
sourceLines: sourceLines,
patched: make([]bool, len(sourceLines)),
image: make([]fileLine, 0, len(sourceLines)),
}
}
func (s *applySession) apply(patch validatedPatch) (applyOutcome, error) {
s.rejectHead = patch.rejectHead
for _, hunk := range patch.hunks {
match, matched := s.findPos(hunk)
if !matched {
s.appendConflictingHunk(hunk)
continue
}
s.applyHunk(hunk, match)
}
s.appendSourceUntil(len(s.sourceLines))
return applyOutcome{
content: append([]fileLine(nil), s.image...),
conflicts: append([]applyConflict(nil), s.conflicts...),
rejectHead: s.rejectHead,
}, nil
}
func (s *applySession) applyHunk(hunk patchHunk, match matchedHunk) {
s.appendSourceUntil(match.sourceStart)
for _, hunkLine := range hunk.lines[match.hunkStart:match.hunkEnd] {
switch hunkLine.kind {
case ' ':
// Source eofMarker from the matched source line. The parser's
// hunkLine.newEOF flag is unreliable for blank trailing context
// because markEOFMarkers cannot distinguish a real mid-file
// blank context line from the synthetic source EOF marker
// (see related comment in lineMatches).
eof := hunkLine.newEOF
if s.cursor < len(s.sourceLines) {
eof = s.sourceLines[s.cursor].eofMarker
}
s.image = append(s.image, fileLine{text: hunkLine.text, hasNewline: hunkLine.hasNewline, eofMarker: eof})
s.cursor++
case '-':
s.cursor++
case '+':
s.image = append(s.image, fileLine{text: hunkLine.text, hasNewline: hunkLine.hasNewline, eofMarker: hunkLine.newEOF})
}
}
if !s.allowOverlap() {
for i := match.sourceStart; i < match.sourceEnd && i < len(s.patched); i++ {
s.patched[i] = true
}
}
}
func (s *applySession) appendConflictingHunk(hunk patchHunk) {
conflictStart := hunk.oldStart - 1
if conflictStart < s.cursor {
conflictStart = s.cursor
}
if conflictStart > len(s.sourceLines) {
conflictStart = len(s.sourceLines)
}
conflictEnd := conflictStart + hunk.oldCount
if conflictEnd > len(s.sourceLines) {
conflictEnd = len(s.sourceLines)
}
s.appendSourceUntil(conflictStart)
offset := len(s.image)
ours := append([]fileLine(nil), s.sourceLines[conflictStart:conflictEnd]...)
theirs := desiredLines(hunk)
s.image = appendSourceLines(s.image, ours...)
s.conflicts = append(s.conflicts, applyConflict{
offset: offset,
hunk: hunk,
ours: ours,
theirs: theirs,
})
s.cursor = conflictEnd
}
func (s *applySession) appendSourceUntil(limit int) {
if limit <= s.cursor {
return
}
s.image = appendSourceLines(s.image, s.sourceLines[s.cursor:limit]...)
s.cursor = limit
}
func (s *applySession) findPos(hunk patchHunk) (matchedHunk, bool) {
preferred := hunk.oldStart - 1
if hunk.oldCount == 0 {
preferred = hunk.oldStart
}
if preferred < s.cursor {
preferred = s.cursor
}
postimage := desiredLines(hunk)
if hunk.newCount >= hunk.oldCount && preferred <= len(s.sourceLines) && matchFragment(s.sourceLines, preferred, postimage, s.ignoreWhitespace()) {
return matchedHunk{}, false
}
matchBeginning := hunk.oldStart == 0 || hunk.oldStart == 1
leading, trailing := hunkContext(hunk.lines)
matchEnd := trailing == 0
hunkStart := 0
hunkEnd := len(hunk.lines)
for {
preimage := preimageLinesWindow(hunk, hunkStart, hunkEnd)
if pos, ok := s.findPosForFragment(preferred, preimage, matchBeginning, matchEnd); ok {
return matchedHunk{
sourceStart: pos,
sourceEnd: pos + len(preimage),
hunkStart: hunkStart,
hunkEnd: hunkEnd,
}, true
}
if leading <= s.minContext() && trailing <= s.minContext() {
break
}
if matchBeginning || matchEnd {
matchBeginning = false
matchEnd = false
continue
}
if leading >= trailing && hunkStart < hunkEnd {
hunkStart++
preferred--
if preferred < s.cursor {
preferred = s.cursor
}
leading--
}
if trailing > leading && hunkStart < hunkEnd {
hunkEnd--
trailing--
}
}
return matchedHunk{}, false
}
func (s *applySession) findPosForFragment(preferred int, fragment []fileLine, matchBeginning, matchEnd bool) (int, bool) {
maxStart := s.fragmentEndLimit(fragment) - len(fragment)
if maxStart < 0 {
maxStart = s.fragmentEndLimit(fragment)
}
if matchBeginning {
preferred = 0
} else if matchEnd {
preferred = maxStart
}
if preferred > maxStart {
preferred = maxStart
}
if preferred < s.cursor {
preferred = s.cursor
}
for offset := 0; ; offset++ {
left := preferred - offset
if left >= s.cursor && s.matchFragmentAt(left, fragment, matchBeginning, matchEnd) {
return left, true
}
right := preferred + offset
if offset > 0 && right >= s.cursor && s.matchFragmentAt(right, fragment, matchBeginning, matchEnd) {
return right, true
}
if left < s.cursor && right > maxStart {
break
}
}
return 0, false
}
func (s *applySession) matchFragmentAt(start int, fragment []fileLine, matchBeginning, matchEnd bool) bool {
if matchBeginning && start != 0 {
return false
}
if start < 0 {
return false
}
if len(fragment) == 0 {
if matchEnd {
return start == s.sourceContentLines()
}
return start <= s.sourceContentLines()
}
if start+len(fragment) > len(s.sourceLines) {
return false
}
if matchEnd && start+len(fragment) != s.fragmentEndLimit(fragment) {
return false
}
if !s.allowOverlap() {
for i := start; i < start+len(fragment); i++ {
if i < len(s.patched) && s.patched[i] {
return false
}
}
}
return matchFragment(s.sourceLines, start, fragment, s.ignoreWhitespace())
}
func patchHunkFromHunk(hunk *hunk) patchHunk {
lines := make([]patchLine, 0, len(hunk.Lines))
for _, line := range hunk.Lines {
lines = append(lines, patchLine{
kind: line.Kind,
text: line.Text,
hasNewline: line.HasNewline,
oldEOF: line.OldEOF,
newEOF: line.NewEOF,
})
}
return patchHunk{
header: formatPatchHunkHeader(hunk),
oldStart: hunk.StartLineNumberOld,
oldCount: hunk.CountOld,
newStart: hunk.StartLineNumberNew,
newCount: hunk.CountNew,
lines: lines,
}
}
func formatRejectHeader(fileDiff *fileDiff) string {
path := firstNonEmpty(fileDiff.ToFile, fileDiff.FromFile)
if path == "" {
return ""
}
return "diff a/" + path + " b/" + path + "\t(rejected hunks)"
}
func formatPatchHunkHeader(hunk *hunk) string {
oldRange := formatPatchHunkRange(hunk.StartLineNumberOld, hunk.CountOld)
newRange := formatPatchHunkRange(hunk.StartLineNumberNew, hunk.CountNew)
return fmt.Sprintf("@@ -%s +%s @@", oldRange, newRange)
}
func formatPatchHunkRange(start, count int) string {
if count == 1 {
return fmt.Sprintf("%d", start)
}
return fmt.Sprintf("%d,%d", start, count)
}
func (s *applySession) ignoreWhitespace() bool {
return s.applier != nil && s.applier.options.IgnoreWhitespace
}
func (s *applySession) allowOverlap() bool {
return s.applier != nil && s.applier.options.AllowOverlap
}
func (s *applySession) minContext() int {
if s.applier == nil {
return 0
}
return s.applier.options.MinContext
}
func (s *applySession) sourceContentLines() int {
if n := len(s.sourceLines); n > 0 && s.sourceLines[n-1].eofMarker {
return n - 1
}
return len(s.sourceLines)
}
func (s *applySession) fragmentEndLimit(fragment []fileLine) int {
if len(fragment) > 0 && fragment[len(fragment)-1].eofMarker {
return len(s.sourceLines)
}
return s.sourceContentLines()
}
func hunkContext(lines []patchLine) (leading, trailing int) {
firstChange := len(lines)
lastChange := -1
for i, line := range lines {
if line.kind == '+' || line.kind == '-' {
if firstChange == len(lines) {
firstChange = i
}
lastChange = i
}
}
if lastChange < 0 {
return len(lines), len(lines)
}
leading = 0
for i := 0; i < firstChange; i++ {
if lines[i].kind == ' ' {
leading++
}
}
trailing = 0
for i := len(lines) - 1; i > lastChange; i-- {
if lines[i].kind == ' ' {
trailing++
}
}
return leading, trailing
}