-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapply.go
More file actions
246 lines (214 loc) · 6.35 KB
/
apply.go
File metadata and controls
246 lines (214 loc) · 6.35 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
package git_diff_parser
import (
"bytes"
"errors"
"strings"
)
type patchHunk struct {
header string
oldStart int
oldCount int
newStart int
newCount int
lines []patchLine
}
type patchLine struct {
kind byte
text string
hasNewline bool
oldEOF bool
newEOF bool
}
type fileLine struct {
text string
hasNewline bool
eofMarker bool
}
func ApplyFile(pristine, patchData []byte) ([]byte, error) {
result, err := applyFileWithOptions(pristine, patchData, defaultApplyOptions())
return result.Content, err
}
func ApplyFileWithConflicts(pristine, patchData []byte) ([]byte, error) {
result, err := applyFileWithOptions(pristine, patchData, defaultMergeApplyOptions())
return result.Content, err
}
func applyFileWithOptions(pristine, patchData []byte, options applyOptions) (applyResult, error) {
return newPatchApply(options).applyFileWithResult(pristine, patchData)
}
func (p *patchApply) applyFile(pristine, patchData []byte) ([]byte, error) {
result, err := p.applyFileWithResult(pristine, patchData)
return result.Content, err
}
func (p *patchApply) applyFileWithResult(pristine, patchData []byte) (applyResult, error) {
patch, err := p.validateAndParsePatch(patchData)
if err != nil {
return applyResult{}, err
}
return p.applyValidatedPatch(pristine, patch)
}
func (p *patchApply) applyValidatedPatch(pristine []byte, patch validatedPatch) (applyResult, error) {
outcome, err := p.newApplySession(pristine).apply(patch)
if err != nil {
return applyResult{}, err
}
result := renderApplyResult(pristine, outcome, p.options)
if len(outcome.conflicts) == 0 {
return result, nil
}
if p.options.Mode == applyModeMerge {
return result, &applyError{
MergeConflicts: len(outcome.conflicts),
ConflictingHunks: len(outcome.conflicts),
}
}
return result, &applyError{DirectMisses: len(outcome.conflicts)}
}
func validateApplyFileDiff(fileDiff *fileDiff) error {
switch {
case fileDiff.IsBinary:
return errors.New("binary patches are not supported")
case fileDiff.NewMode != "":
return errors.New("file mode changes are not supported")
case fileDiff.Type == fileDiffTypeAdded || fileDiff.Type == fileDiffTypeDeleted:
return errors.New("patches may only modify existing files")
case len(fileDiff.Hunks) == 0:
return errors.New("patch contains no hunks")
case fileDiff.RenameFrom != "" || fileDiff.RenameTo != "" || fileDiff.CopyFrom != "" || fileDiff.CopyTo != "":
return errors.New("unsupported patch syntax: copy and rename headers are not supported")
case !fileDiffHasChanges(fileDiff):
return errors.New("patch contains no effective changes")
default:
return nil
}
}
func fileDiffHasChanges(fileDiff *fileDiff) bool {
for _, hunk := range fileDiff.Hunks {
for _, change := range hunk.ChangeList {
if change.Type != contentChangeTypeNOOP {
return true
}
}
}
return false
}
func desiredLines(hunk patchHunk) []fileLine {
return desiredLinesWindow(hunk, 0, len(hunk.lines))
}
func desiredLinesWindow(hunk patchHunk, start, end int) []fileLine {
lines := make([]fileLine, 0, len(hunk.lines))
for _, line := range hunk.lines[start:end] {
if line.kind == ' ' || line.kind == '+' {
lines = append(lines, fileLine{text: line.text, hasNewline: line.hasNewline, eofMarker: line.newEOF})
}
}
return lines
}
func preimageLinesWindow(hunk patchHunk, start, end int) []fileLine {
lines := make([]fileLine, 0, len(hunk.lines))
for _, line := range hunk.lines[start:end] {
if line.kind == ' ' || line.kind == '-' {
lines = append(lines, fileLine{text: line.text, hasNewline: line.hasNewline, eofMarker: line.oldEOF})
}
}
return lines
}
func matchFragment(source []fileLine, start int, fragment []fileLine, ignoreWhitespace bool) bool {
if len(fragment) == 0 {
return true
}
if start < 0 || start+len(fragment) > len(source) {
return false
}
for i := range fragment {
if !lineMatches(source[start+i], fragment[i], ignoreWhitespace) {
return false
}
}
return true
}
func lineMatches(left, right fileLine, ignoreWhitespace bool) bool {
if left.hasNewline != right.hasNewline {
return false
}
if left.eofMarker != right.eofMarker {
// eofMarker is unreliable on blank lines: a mid-file blank and the
// synthetic source-EOF sentinel both serialize as " \n" in unified
// diff, so the parser can't tell them apart. We accept the position
// match here; applyHunk then writes the correct eofMarker by copying
// it from the matched source line instead of the patch line.
isBlankWithNewLine := func(line fileLine) bool {
return line.text == "" && line.hasNewline
}
if !isBlankWithNewLine(left) || !isBlankWithNewLine(right) {
return false
}
}
if left.text == right.text {
return true
}
if !ignoreWhitespace {
return false
}
return normalizeWhitespace(left.text) == normalizeWhitespace(right.text)
}
func normalizeWhitespace(text string) string {
return strings.Join(strings.Fields(text), " ")
}
func appendSourceLines(dst []fileLine, src ...fileLine) []fileLine {
return append(dst, src...)
}
func ensureTrailingNewline(lines []fileLine) []fileLine {
if len(lines) == 0 {
return lines
}
lines[len(lines)-1].hasNewline = true
return lines
}
func splitFileLines(content []byte) []fileLine {
rawLines := splitLinesPreserveNewline(string(content))
lines := make([]fileLine, 0, len(rawLines))
for _, raw := range rawLines {
lines = append(lines, fileLine{
text: trimSingleLineEnding(raw),
hasNewline: strings.HasSuffix(raw, "\n"),
})
}
if len(content) > 0 && content[len(content)-1] == '\n' {
lines = append(lines, fileLine{text: "", hasNewline: true, eofMarker: true})
}
return lines
}
func joinFileLines(lines []fileLine) []byte {
var buf bytes.Buffer
for _, line := range lines {
if line.eofMarker {
continue
}
buf.WriteString(line.text)
if line.hasNewline {
buf.WriteByte('\n')
}
}
return buf.Bytes()
}
func trimSingleLineEnding(s string) string {
s = strings.TrimSuffix(s, "\n")
return s
}
func splitLinesPreserveNewline(s string) []string {
if s == "" {
return nil
}
lines := strings.SplitAfter(s, "\n")
if lines[len(lines)-1] == "" {
lines = lines[:len(lines)-1]
}
return lines
}
func normalizePatchForValidation(patchData []byte) []byte {
trimmed := bytes.TrimSpace(patchData)
if bytes.HasPrefix(trimmed, []byte("diff --git ")) {
return patchData
}
return []byte("diff --git a/__patch__ b/__patch__\n" + string(patchData))
}