forked from ds300/patch-package
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapply.ts
308 lines (286 loc) Β· 7.83 KB
/
apply.ts
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
import fs from "fs-extra"
import { dirname, join, relative, resolve } from "path"
import { ParsedPatchFile, FilePatch, Hunk } from "./parse"
import { assertNever } from "../assertNever"
export const executeEffects = (
effects: ParsedPatchFile,
{
dryRun,
bestEffort,
errors,
cwd,
}: { dryRun: boolean; cwd?: string; errors?: string[]; bestEffort: boolean },
) => {
const inCwd = (path: string) => (cwd ? join(cwd, path) : path)
const humanReadable = (path: string) => relative(process.cwd(), inCwd(path))
effects.forEach((eff) => {
switch (eff.type) {
case "file deletion":
if (dryRun) {
if (!fs.existsSync(inCwd(eff.path))) {
throw new Error(
"Trying to delete file that doesn't exist: " +
humanReadable(eff.path),
)
}
} else {
// TODO: integrity checks
try {
fs.unlinkSync(inCwd(eff.path))
} catch (e) {
if (bestEffort) {
errors?.push(`Failed to delete file ${eff.path}`)
} else {
throw e
}
}
}
break
case "rename":
if (dryRun) {
// TODO: see what patch files look like if moving to exising path
if (!fs.existsSync(inCwd(eff.fromPath))) {
throw new Error(
"Trying to move file that doesn't exist: " +
humanReadable(eff.fromPath),
)
}
} else {
try {
fs.moveSync(inCwd(eff.fromPath), inCwd(eff.toPath))
} catch (e) {
if (bestEffort) {
errors?.push(
`Failed to rename file ${eff.fromPath} to ${eff.toPath}`,
)
} else {
throw e
}
}
}
break
case "file creation":
if (dryRun) {
if (fs.existsSync(inCwd(eff.path))) {
throw new Error(
"Trying to create file that already exists: " +
humanReadable(eff.path),
)
}
// todo: check file contents matches
} else {
const fileContents = eff.hunk
? eff.hunk.parts[0].lines.join("\n") +
(eff.hunk.parts[0].noNewlineAtEndOfFile ? "" : "\n")
: ""
const path = inCwd(eff.path)
try {
fs.ensureDirSync(dirname(path))
fs.writeFileSync(path, fileContents, { mode: eff.mode })
} catch (e) {
if (bestEffort) {
errors?.push(`Failed to create new file ${eff.path}`)
} else {
throw e
}
}
}
break
case "patch":
applyPatch(eff, { dryRun, cwd, bestEffort, errors })
break
case "mode change":
const currentMode = fs.statSync(inCwd(eff.path)).mode
if (
((isExecutable(eff.newMode) && isExecutable(currentMode)) ||
(!isExecutable(eff.newMode) && !isExecutable(currentMode))) &&
dryRun
) {
console.log(
`Mode change is not required for file ${humanReadable(eff.path)}`,
)
}
fs.chmodSync(inCwd(eff.path), eff.newMode)
break
default:
assertNever(eff)
}
})
}
function isExecutable(fileMode: number) {
// tslint:disable-next-line:no-bitwise
return (fileMode & 0b001_000_000) > 0
}
const trimRight = (s: string) => s.replace(/\s+$/, "")
function linesAreEqual(a: string, b: string) {
return trimRight(a) === trimRight(b)
}
/**
* How does noNewLineAtEndOfFile work?
*
* if you remove the newline from a file that had one without editing other bits:
*
* it creates an insertion/removal pair where the insertion has \ No new line at end of file
*
* if you edit a file that didn't have a new line and don't add one:
*
* both insertion and deletion have \ No new line at end of file
*
* if you edit a file that didn't have a new line and add one:
*
* deletion has \ No new line at end of file
* but not insertion
*
* if you edit a file that had a new line and leave it in:
*
* neither insetion nor deletion have the annoation
*
*/
function applyPatch(
{ hunks, path }: FilePatch,
{
dryRun,
cwd,
bestEffort,
errors,
}: { dryRun: boolean; cwd?: string; bestEffort: boolean; errors?: string[] },
): void {
path = cwd ? resolve(cwd, path) : path
// modifying the file in place
const fileContents = fs.readFileSync(path).toString()
const mode = fs.statSync(path).mode
const fileLines: string[] = fileContents.split(/\n/)
const result: Modification[][] = []
for (const hunk of hunks) {
let fuzzingOffset = 0
while (true) {
const modifications = evaluateHunk(hunk, fileLines, fuzzingOffset)
if (modifications) {
result.push(modifications)
break
}
fuzzingOffset =
fuzzingOffset < 0 ? fuzzingOffset * -1 : fuzzingOffset * -1 - 1
if (Math.abs(fuzzingOffset) > 20) {
const message = `Cannot apply hunk ${hunks.indexOf(
hunk,
)} for file ${relative(process.cwd(), path)}\n\`\`\`diff\n${
hunk.source
}\n\`\`\`\n`
if (bestEffort) {
errors?.push(message)
break
} else {
throw new Error(message)
}
}
}
}
if (dryRun) {
return
}
let diffOffset = 0
for (const modifications of result) {
for (const modification of modifications) {
switch (modification.type) {
case "splice":
fileLines.splice(
modification.index + diffOffset,
modification.numToDelete,
...modification.linesToInsert,
)
diffOffset +=
modification.linesToInsert.length - modification.numToDelete
break
case "pop":
fileLines.pop()
break
case "push":
fileLines.push(modification.line)
break
default:
assertNever(modification)
}
}
}
try {
fs.writeFileSync(path, fileLines.join("\n"), { mode })
} catch (e) {
if (bestEffort) {
errors?.push(`Failed to write file ${path}`)
} else {
throw e
}
}
}
interface Push {
type: "push"
line: string
}
interface Pop {
type: "pop"
}
interface Splice {
type: "splice"
index: number
numToDelete: number
linesToInsert: string[]
}
type Modification = Push | Pop | Splice
function evaluateHunk(
hunk: Hunk,
fileLines: string[],
fuzzingOffset: number,
): Modification[] | null {
const result: Modification[] = []
let contextIndex = hunk.header.original.start - 1 + fuzzingOffset
// do bounds checks for index
if (contextIndex < 0) {
return null
}
if (fileLines.length - contextIndex < hunk.header.original.length) {
return null
}
for (const part of hunk.parts) {
switch (part.type) {
case "deletion":
case "context":
for (const line of part.lines) {
const originalLine = fileLines[contextIndex]
if (!linesAreEqual(originalLine, line)) {
return null
}
contextIndex++
}
if (part.type === "deletion") {
result.push({
type: "splice",
index: contextIndex - part.lines.length,
numToDelete: part.lines.length,
linesToInsert: [],
})
if (part.noNewlineAtEndOfFile) {
result.push({
type: "push",
line: "",
})
}
}
break
case "insertion":
result.push({
type: "splice",
index: contextIndex,
numToDelete: 0,
linesToInsert: part.lines,
})
if (part.noNewlineAtEndOfFile) {
result.push({ type: "pop" })
}
break
default:
assertNever(part.type)
}
}
return result
}