Recursive AI

Reverse a unified diff patch in C#

OneDiff is a free, open-source diff library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

A reverse patch restores deleted lines and removes added ones.

Terminal
dotnet add package RecursiveAI.OneDiff

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using OneDiff.Patching;
var patch = "--- old\n+++ new\n"
    + "@@ -1 +1 @@\n-off\n+on\n";
var undo = UnifiedPatch.Parse(patch)
    .Reverse().ToString();
Console.Write(undo);

Unzip the example, then dotnet run.

Prints the undo patch:

DIFF
--- new
+++ old
@@ -1 +1 @@
+off
-on

+off comes first because OneDiff flips the signs without reordering the lines.

The full program

The zip’s forward.diff contains the forward patch from the snippet at the top. The other input, changed.txt, contains on followed by a line break. The program prints the reversed patch, then applies it to the changed text in memory.

C#
using OneDiff;
using OneDiff.Patching;
 
string forward = File.ReadAllText("forward.diff");
string changed = File.ReadAllText("changed.txt");
string reverse = UnifiedPatch.Parse(forward)
    .Reverse().ToString();
Console.Write(reverse);
 
var result = Diff.ApplyUnified(changed, reverse);
if (!result.Success)
    throw new InvalidOperationException("Undo patch rejected.");
 
Console.Write($"Restored: {result.Text}");
Text
--- new
+++ old
@@ -1 +1 @@
+off
-on
Restored: off

Malformed patch text throws PatchFormatException; if a valid hunk can’t be applied, check Success before saving the result because it can contain only some of the changes.

Variations

Undo the change without exporting another patch. Pass Reverse = true when applying the original patch:

C#
using OneDiff;
using OneDiff.Patching;
 
var patch = "--- old\n+++ new\n"
    + "@@ -1 +1 @@\n-off\n+on\n";
var options = new UnifiedApplyOptions { Reverse = true };
var result = Diff.ApplyUnified("on\n", patch, options);
if (!result.Success)
    throw new InvalidOperationException("Undo patch rejected.");
Console.Write(result.Text);
Text
off

The short answer

Use UnifiedPatch.Parse(patchText).Reverse().ToString() to turn an existing unified diff into patch text you can save or pass to another process. You don’t need both versions of the file to do this: the forward patch already contains the lines it adds and deletes. To apply the result, start with the changed text, not the original.

How do I reverse a patch?

A unified diff has an old-side --- header and a new-side +++ header. Each hunk (a block of changes) starts with an @@ line that gives its position and length on each side. Reversing a patch swaps those sides. OneDiff swaps the header names and timestamps, swaps the hunk ranges, and turns insertions into deletions and vice versa. Context lines, which help locate a change, stay as they were. Changing only the + and - markers by hand would leave the hunk ranges wrong whenever the two sides have different positions or lengths.

Use the reversed patch with the default apply direction. If you set Reverse = true on an already reversed patch, you swap the sides twice and end up applying the original change. Use that option only when holding on to the forward patch and undoing directly in memory.

A patch made against the exact current text is the clearest case. If the file has been edited since the forward patch ran, OneDiff looks for matching lines around the hunk’s original position. Its default settings also let it ignore up to two lines of context when looking for a match. A hunk that still doesn’t fit is listed in Rejected; use Hunks to see each result. Successful hunks are still reflected in Text, so don’t save it as a complete rollback unless Success is true.

How do I open a .diff file?

If the input is a text file containing unified diff, read its contents as a string and pass that string to UnifiedPatch.Parse. The .diff or .patch extension does not determine the format. Look for --- and +++ file headers, followed by @@ hunk headers. A malformed or truncated hunk fails at parse time; a valid hunk that can’t match the changed text fails at apply time instead.

The recipe handles text hunks. OneDiff skips binary and rename-only sections and retains Git’s extended header lines as written; reversing the text hunks is not a way to undo renames or file mode changes. UnifiedPatch.Reverse() can reverse the text hunks for multiple files, but Diff.ApplyUnified accepts at most one file’s patch. For multiple files, choose each target yourself and apply the matching UnifiedFilePatch to its contents. OneDiff works on strings and does not open or overwrite the files named in the headers.

All onediff recipes