Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes15kdownloads
apply.js268 linesDownload Raw Back to patch
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.applyPatch = applyPatch;
4exports.applyPatches = applyPatches;
5var string_js_1 = require("../util/string.js");
6var line_endings_js_1 = require("./line-endings.js");
7var parse_js_1 = require("./parse.js");
8var distance_iterator_js_1 = require("../util/distance-iterator.js");
9/**
10 * attempts to apply a unified diff patch.
11 *
12 * Hunks are applied first to last.
13 * `applyPatch` first tries to apply the first hunk at the line number specified in the hunk header, and with all context lines matching exactly.
14 * If that fails, it tries scanning backwards and forwards, one line at a time, to find a place to apply the hunk where the context lines match exactly.
15 * If that still fails, and `fuzzFactor` is greater than zero, it increments the maximum number of mismatches (missing, extra, or changed context lines) that there can be between the hunk context and a region where we are trying to apply the patch such that the hunk will still be considered to match.
16 * Regardless of `fuzzFactor`, lines to be deleted in the hunk *must* be present for a hunk to match, and the context lines *immediately* before and after an insertion must match exactly.
17 *
18 * Once a hunk is successfully fitted, the process begins again with the next hunk.
19 * Regardless of `fuzzFactor`, later hunks must be applied later in the file than earlier hunks.
20 *
21 * If a hunk cannot be successfully fitted *anywhere* with fewer than `fuzzFactor` mismatches, `applyPatch` fails and returns `false`.
22 *
23 * If a hunk is successfully fitted but not at the line number specified by the hunk header, all subsequent hunks have their target line number adjusted accordingly.
24 * (e.g. if the first hunk is applied 10 lines below where the hunk header said it should fit, `applyPatch` will *start* looking for somewhere to apply the second hunk 10 lines below where its hunk header says it goes.)
25 *
26 * If the patch was applied successfully, returns a string containing the patched text.
27 * If the patch could not be applied (because some hunks in the patch couldn't be fitted to the text in `source`), `applyPatch` returns false.
28 *
29 * @param patch a string diff or the output from the `parsePatch` or `structuredPatch` methods.
30 */
31function applyPatch(source, patch, options) {
32    if (options === void 0) { options = {}; }
33    var patches;
34    if (typeof patch === 'string') {
35        patches = (0, parse_js_1.parsePatch)(patch);
36    }
37    else if (Array.isArray(patch)) {
38        patches = patch;
39    }
40    else {
41        patches = [patch];
42    }
43    if (patches.length > 1) {
44        throw new Error('applyPatch only works with a single input.');
45    }
46    return applyStructuredPatch(source, patches[0], options);
47}
48function applyStructuredPatch(source, patch, options) {
49    if (options === void 0) { options = {}; }
50    if (options.autoConvertLineEndings || options.autoConvertLineEndings == null) {
51        if ((0, string_js_1.hasOnlyWinLineEndings)(source) && (0, line_endings_js_1.isUnix)(patch)) {
52            patch = (0, line_endings_js_1.unixToWin)(patch);
53        }
54        else if ((0, string_js_1.hasOnlyUnixLineEndings)(source) && (0, line_endings_js_1.isWin)(patch)) {
55            patch = (0, line_endings_js_1.winToUnix)(patch);
56        }
57    }
58    // Apply the diff to the input
59    var lines = source.split('\n'), hunks = patch.hunks, compareLine = options.compareLine || (function (lineNumber, line, operation, patchContent) { return line === patchContent; }), fuzzFactor = options.fuzzFactor || 0;
60    var minLine = 0;
61    if (fuzzFactor < 0 || !Number.isInteger(fuzzFactor)) {
62        throw new Error('fuzzFactor must be a non-negative integer');
63    }
64    // Special case for empty patch.
65    if (!hunks.length) {
66        return source;
67    }
68    // Before anything else, handle EOFNL insertion/removal. If the patch tells us to make a change
69    // to the EOFNL that is redundant/impossible - i.e. to remove a newline that's not there, or add a
70    // newline that already exists - then we either return false and fail to apply the patch (if
71    // fuzzFactor is 0) or simply ignore the problem and do nothing (if fuzzFactor is >0).
72    // If we do need to remove/add a newline at EOF, this will always be in the final hunk:
73    var prevLine = '', removeEOFNL = false, addEOFNL = false;
74    for (var i = 0; i < hunks[hunks.length - 1].lines.length; i++) {
75        var line = hunks[hunks.length - 1].lines[i];
76        if (line[0] == '\\') {
77            if (prevLine[0] == '+') {
78                removeEOFNL = true;
79            }
80            else if (prevLine[0] == '-') {
81                addEOFNL = true;
82            }
83        }
84        prevLine = line;
85    }
86    if (removeEOFNL) {
87        if (addEOFNL) {
88            // This means the final line gets changed but doesn't have a trailing newline in either the
89            // original or patched version. In that case, we do nothing if fuzzFactor > 0, and if
90            // fuzzFactor is 0, we simply validate that the source file has no trailing newline.
91            if (!fuzzFactor && lines[lines.length - 1] == '') {
92                return false;
93            }
94        }
95        else if (lines[lines.length - 1] == '') {
96            lines.pop();
97        }
98        else if (!fuzzFactor) {
99            return false;
100        }
101    }
102    else if (addEOFNL) {
103        if (lines[lines.length - 1] != '') {
104            lines.push('');
105        }
106        else if (!fuzzFactor) {
107            return false;
108        }
109    }
110    /**
111     * Checks if the hunk can be made to fit at the provided location with at most `maxErrors`
112     * insertions, substitutions, or deletions, while ensuring also that:
113     * - lines deleted in the hunk match exactly, and
114     * - wherever an insertion operation or block of insertion operations appears in the hunk, the
115     *   immediately preceding and following lines of context match exactly
116     *
117     * `toPos` should be set such that lines[toPos] is meant to match hunkLines[0].
118     *
119     * If the hunk can be applied, returns an object with properties `oldLineLastI` and
120     * `replacementLines`. Otherwise, returns null.
121     */
122    function applyHunk(hunkLines, toPos, maxErrors, hunkLinesI, lastContextLineMatched, patchedLines, patchedLinesLength) {
123        if (hunkLinesI === void 0) { hunkLinesI = 0; }
124        if (lastContextLineMatched === void 0) { lastContextLineMatched = true; }
125        if (patchedLines === void 0) { patchedLines = []; }
126        if (patchedLinesLength === void 0) { patchedLinesLength = 0; }
127        var nConsecutiveOldContextLines = 0;
128        var nextContextLineMustMatch = false;
129        for (; hunkLinesI < hunkLines.length; hunkLinesI++) {
130            var hunkLine = hunkLines[hunkLinesI], operation = (hunkLine.length > 0 ? hunkLine[0] : ' '), content = (hunkLine.length > 0 ? hunkLine.substr(1) : hunkLine);
131            if (operation === '-') {
132                if (compareLine(toPos + 1, lines[toPos], operation, content)) {
133                    toPos++;
134                    nConsecutiveOldContextLines = 0;
135                }
136                else {
137                    if (!maxErrors || lines[toPos] == null) {
138                        return null;
139                    }
140                    patchedLines[patchedLinesLength] = lines[toPos];
141                    return applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI, false, patchedLines, patchedLinesLength + 1);
142                }
143            }
144            if (operation === '+') {
145                if (!lastContextLineMatched) {
146                    return null;
147                }
148                patchedLines[patchedLinesLength] = content;
149                patchedLinesLength++;
150                nConsecutiveOldContextLines = 0;
151                nextContextLineMustMatch = true;
152            }
153            if (operation === ' ') {
154                nConsecutiveOldContextLines++;
155                patchedLines[patchedLinesLength] = lines[toPos];
156                if (compareLine(toPos + 1, lines[toPos], operation, content)) {
157                    patchedLinesLength++;
158                    lastContextLineMatched = true;
159                    nextContextLineMustMatch = false;
160                    toPos++;
161                }
162                else {
163                    if (nextContextLineMustMatch || !maxErrors) {
164                        return null;
165                    }
166                    // Consider 3 possibilities in sequence:
167                    // 1. lines contains a *substitution* not included in the patch context, or
168                    // 2. lines contains an *insertion* not included in the patch context, or
169                    // 3. lines contains a *deletion* not included in the patch context
170                    // The first two options are of course only possible if the line from lines is non-null -
171                    // i.e. only option 3 is possible if we've overrun the end of the old file.
172                    return (lines[toPos] && (applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI + 1, false, patchedLines, patchedLinesLength + 1) || applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI, false, patchedLines, patchedLinesLength + 1)) || applyHunk(hunkLines, toPos, maxErrors - 1, hunkLinesI + 1, false, patchedLines, patchedLinesLength));
173                }
174            }
175        }
176        // Before returning, trim any unmodified context lines off the end of patchedLines and reduce
177        // toPos (and thus oldLineLastI) accordingly. This allows later hunks to be applied to a region
178        // that starts in this hunk's trailing context.
179        patchedLinesLength -= nConsecutiveOldContextLines;
180        toPos -= nConsecutiveOldContextLines;
181        patchedLines.length = patchedLinesLength;
182        return {
183            patchedLines: patchedLines,
184            oldLineLastI: toPos - 1
185        };
186    }
187    var resultLines = [];
188    // Search best fit offsets for each hunk based on the previous ones
189    var prevHunkOffset = 0;
190    for (var i = 0; i < hunks.length; i++) {
191        var hunk = hunks[i];
192        var hunkResult = void 0;
193        var maxLine = lines.length - hunk.oldLines + fuzzFactor;
194        var toPos = void 0;
195        for (var maxErrors = 0; maxErrors <= fuzzFactor; maxErrors++) {
196            toPos = hunk.oldStart + prevHunkOffset - 1;
197            var iterator = (0, distance_iterator_js_1.default)(toPos, minLine, maxLine);
198            for (; toPos !== undefined; toPos = iterator()) {
199                hunkResult = applyHunk(hunk.lines, toPos, maxErrors);
200                if (hunkResult) {
201                    break;
202                }
203            }
204            if (hunkResult) {
205                break;
206            }
207        }
208        if (!hunkResult) {
209            return false;
210        }
211        // Copy everything from the end of where we applied the last hunk to the start of this hunk
212        for (var i_1 = minLine; i_1 < toPos; i_1++) {
213            resultLines.push(lines[i_1]);
214        }
215        // Add the lines produced by applying the hunk:
216        for (var i_2 = 0; i_2 < hunkResult.patchedLines.length; i_2++) {
217            var line = hunkResult.patchedLines[i_2];
218            resultLines.push(line);
219        }
220        // Set lower text limit to end of the current hunk, so next ones don't try
221        // to fit over already patched text
222        minLine = hunkResult.oldLineLastI + 1;
223        // Note the offset between where the patch said the hunk should've applied and where we
224        // applied it, so we can adjust future hunks accordingly:
225        prevHunkOffset = toPos + 1 - hunk.oldStart;
226    }
227    // Copy over the rest of the lines from the old text
228    for (var i = minLine; i < lines.length; i++) {
229        resultLines.push(lines[i]);
230    }
231    return resultLines.join('\n');
232}
233/**
234 * applies one or more patches.
235 *
236 * `patch` may be either an array of structured patch objects, or a string representing a patch in unified diff format (which may patch one or more files).
237 *
238 * This method will iterate over the contents of the patch and apply to data provided through callbacks. The general flow for each patch index is:
239 *
240 * - `options.loadFile(index, callback)` is called. The caller should then load the contents of the file and then pass that to the `callback(err, data)` callback. Passing an `err` will terminate further patch execution.
241 * - `options.patched(index, content, callback)` is called once the patch has been applied. `content` will be the return value from `applyPatch`. When it's ready, the caller should call `callback(err)` callback. Passing an `err` will terminate further patch execution.
242 *
243 * Once all patches have been applied or an error occurs, the `options.complete(err)` callback is made.
244 */
245function applyPatches(uniDiff, options) {
246    var spDiff = typeof uniDiff === 'string' ? (0, parse_js_1.parsePatch)(uniDiff) : uniDiff;
247    var currentIndex = 0;
248    function processIndex() {
249        var index = spDiff[currentIndex++];
250        if (!index) {
251            return options.complete();
252        }
253        options.loadFile(index, function (err, data) {
254            if (err) {
255                return options.complete(err);
256            }
257            var updatedContent = applyPatch(data, index, options);
258            options.patched(index, updatedContent, function (err) {
259                if (err) {
260                    return options.complete(err);
261                }
262                processIndex();
263            });
264        });
265    }
266    processIndex();
267}
268 
codekingpro/portable-devtools · Team Ai