Skip to content

Repository files navigation

PatchSharp

CINuGetNuGet Downloadscodecov

A C# library for applying text diffs and replacements with built-in fuzzy matching. Supports OpenAI's V4A patch format and Anthropic-style str_replace operations.

Installation

dotnet add package PatchSharp

Targets netstandard2.1, net8.0, and net10.0.

Usage

All methods are on the static class PatchSharp.ApplyPatch.

Apply a V4A diff

usingPatchSharp;varoriginal="line one\nline two\nline three\n";vardiff=@"*** original.txt line one-line two+line 2 line three";varresult=ApplyPatch.Apply(original,diff);// "line one\nline 2\nline three\n"

Create a new file from a diff

vardiff=@"*** new-file.txt+hello+world";varresult=ApplyPatch.Create(diff);// "hello\nworld\n"

Find and replace with fuzzy matching

varinput="function hello() {\n return 'world';\n}\n";varresult=ApplyPatch.StrReplace(input,oldStr:" return 'world';",newStr:" return 'hello world';");

Replace all occurrences:

varresult=ApplyPatch.StrReplace(input,"old","new",allowMulti:true);

Use a regex pattern:

varresult=ApplyPatch.StrReplace(input,@"v\d+\.\d+","v2.0",useRegex:true);

Error handling

All methods throw PatchApplyException on failure:

try{ApplyPatch.Apply(input,diff);}catch(PatchApplyExceptionex){Console.WriteLine(ex.Message);Console.WriteLine(ex.LineNumber);// line in the diff where the error occurredConsole.WriteLine(ex.Fuzz);// fuzzy match level used (0 = exact)Console.WriteLine(ex.Context);// surrounding context for diagnostics}

Fuzzy matching

When an exact match isn't found, PatchSharp tries progressively looser matching:

Fuzz levelStrategy
0Exact match
1Ignore trailing whitespace
100Ignore leading and trailing whitespace
500Skip blank lines (handles AI models omitting blank lines from diff context)
1000Unicode normalization (smart quotes → ASCII quotes, em-dashes → hyphens, etc.)

The lowest fuzz level that produces a match wins.

V4A diff format

*** path/to/file.txt ← file header
@@ context line ← anchor (jump to this line)
unchanged line ← context (space prefix)
-removed line ← deletion
+added line ← insertion
*** End of File ← anchor to end of file

Wrapped in optional *** Begin Patch / *** End Patch markers.

Origin

PatchSharp was extracted from Instruct UI, an AI-powered platform that generates production-ready Blazor UI code from text descriptions and screenshots. These patching and replacement algorithms are battle-tested across thousands of AI-generated code edits in Instruct UI's multi-agent workflow, where reliable diff application is critical for compiling and rendering live previews.

License

MIT

About

No description, website, or topics provided.

Resources

Stars

9 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages