Skip to content

Commit

Permalink
Add function to reverse a patch
Browse files Browse the repository at this point in the history
  • Loading branch information
ExplodingCabbage committed Dec 29, 2023
1 parent 8bd13d6 commit 8bf5f08
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/patch/reverse.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
export function reversePatch(structuredPatch) {
const result = {...structuredPatch, hunks: structuredPatch.hunks.slice()};
const { oldFileName, newFileName, oldHeader, newHeader, hunks } = result;

result.oldFileName = newFileName;
result.oldHeader = newHeader;
result.newFileName = oldFileName;
result.newHeader = oldHeader;

for (const hunk of hunks) {
const { oldLines, oldStart, newLines, newStart, lines } = hunk;
hunk.oldLines = newLines.slice();
hunk.oldStart = newStart;
hunk.newLines = oldLines.slice();
hunk.newStart = oldStart;

hunk.lines = lines.map(l => {
if (l.startsWith('-')) return `+${l.slice(1)}`;
if (l.startsWith('+')) return `-${l.slice(1)}`;
return l;
});
}

return structuredPatch;
}

0 comments on commit 8bf5f08

Please sign in to comment.