MCPcopy Index your code
hub / github.com/ds300/patch-package / applyPatch

Function applyPatch

src/patch/apply.ts:144–230  ·  view source on GitHub ↗

* 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: * *

(
  { hunks, path }: FilePatch,
  {
    dryRun,
    cwd,
    bestEffort,
    errors,
  }: { dryRun: boolean; cwd?: string; bestEffort: boolean; errors?: string[] },
)

Source from the content-addressed store, hash-verified

142 */
143
144function applyPatch(
145 { hunks, path }: FilePatch,
146 {
147 dryRun,
148 cwd,
149 bestEffort,
150 errors,
151 }: { dryRun: boolean; cwd?: string; bestEffort: boolean; errors?: string[] },
152): void {
153 path = cwd ? resolve(cwd, path) : path
154 // modifying the file in place
155 const fileContents = fs.readFileSync(path).toString()
156 const mode = fs.statSync(path).mode
157
158 const fileLines: string[] = fileContents.split(/\n/)
159
160 const result: Modification[][] = []
161
162 for (const hunk of hunks) {
163 let fuzzingOffset = 0
164 while (true) {
165 const modifications = evaluateHunk(hunk, fileLines, fuzzingOffset)
166 if (modifications) {
167 result.push(modifications)
168 break
169 }
170
171 fuzzingOffset =
172 fuzzingOffset < 0 ? fuzzingOffset * -1 : fuzzingOffset * -1 - 1
173
174 if (Math.abs(fuzzingOffset) > 20) {
175 const message = `Cannot apply hunk ${hunks.indexOf(
176 hunk,
177 )} for file ${relative(process.cwd(), path)}\n\`\`\`diff\n${
178 hunk.source
179 }\n\`\`\`\n`
180
181 if (bestEffort) {
182 errors?.push(message)
183 break
184 } else {
185 throw new Error(message)
186 }
187 }
188 }
189 }
190
191 if (dryRun) {
192 return
193 }
194
195 let diffOffset = 0
196
197 for (const modifications of result) {
198 for (const modification of modifications) {
199 switch (modification.type) {
200 case "splice":
201 fileLines.splice(

Callers 1

executeEffectsFunction · 0.70

Calls 4

resolveFunction · 0.90
relativeFunction · 0.90
assertNeverFunction · 0.90
evaluateHunkFunction · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…