UnifiedDiff Class
Writes, reads and applies diffs in the unified format of diff -u and git diff.
public static class UnifiedDiffMethods
| Name | Description |
|---|---|
| Apply(string, string) | Applies a unified diff that holds one file to text. |
| Create(string, string, UnifiedDiffOptions?, CancellationToken) | Compares oldText and newText line by line and returns the result as a unified diff. |
| Parse(string) | Reads the files of a unified diff, such as the output of diff -u or git diff. |
Apply(string, string)
UnifiedDiff.csApplies a unified diff that holds one file to text.
Parameters
Returns
string The patched text.
Exceptions
ArgumentNullExceptiontextorpatchisnull.ArgumentExceptionpatchdoes not hold exactly one file.FormatExceptionpatchis malformed.UnifiedDiffApplyException- A hunk does not match the text.
Remarks
See UnifiedDiffFile.Apply for how the hunks are matched.
Create(string, string, UnifiedDiffOptions?, CancellationToken)
UnifiedDiff.csCompares oldText and newText line by line and returns the result as a unified diff.
public static UnifiedDiffFile Create(string oldText, string newText, UnifiedDiffOptions? options = null, CancellationToken cancellationToken = default)Parameters
oldTextstring- The original text.
newTextstring- The modified text.
optionsUnifiedDiffOptions?- The file names, the number of lines of context and the algorithm.
cancellationTokenCancellationToken- The token to monitor for cancellation requests.
Returns
UnifiedDiffFile The diff. Call UnifiedDiffFile.ToString to write it.
Exceptions
ArgumentNullExceptionoldTextornewTextisnull.ArgumentOutOfRangeException- An option of
optionsis out of range. OperationCanceledExceptioncancellationTokenis canceled.
Remarks
Lines are separated by "\n" only, as diff does: a "\r" before it is part of the line, so the diff applies to the old text exactly. The comparison is ordinal.
Parse(string)
UnifiedDiff.csReads the files of a unified diff, such as the output of diff -u or git diff.
public static IReadOnlyList<UnifiedDiffFile> Parse(string patch)Parameters
patchstring- The text of the diff.
Returns
IReadOnlyList<UnifiedDiffFile> The files of the diff, in order. A --- line followed by a +++ line starts a file.
Exceptions
ArgumentNullExceptionpatchisnull.FormatException- A hunk is malformed: an invalid
@@line, a line with an unknown prefix, or fewer lines than its header gives.
Remarks
The lines outside the files, such as the diff --git and index lines of git, are ignored. The text after a tab in a --- or +++ line, a timestamp, is not part of the name. Binary patches and the renames and modes of git are not read.