SugarDiff
Unified-diff engine — hunks, writer, patch scanner, and side-by-side row pairing for gutters/split viewers
A unified-diff engine the whole ecosystem can share: LCS line diffing, numbered context hunks, a GNU diff -u writer, and a scanner that numbers the rows of any patch. Extracted from candy-code's BuildsUnifiedDiff trait (now a delegating consumer) and the DiffGutter region model (D1a fold landed: the gutter's scan half delegates to UnifiedScan::lines(), fileHeaders() and isHunkHeader(); only the fixed-width gutter formatting stays app-side). First-party — there is no 1:1 Go counterpart.
Install
composer require sugarcraft/sugar-diff
Quickstart
use SugarCraft\Diff\Diff;
use SugarCraft\Diff\DiffOptions;
use SugarCraft\Diff\Reader\UnifiedScan;
$before = "Hello World\n";
$after = "Hello PHP\n";
$diff = Diff::compute($before, $after);
$patchText = $diff->unified('file.txt');
echo $patchText;
// --- a/file.txt
// +++ b/file.txt
// @@ -1 +1 @@
// -Hello World
// +Hello PHP
// Immutable, fluent options — context width, folding and GNU
// annotations are all opt-in; see the README Fidelity notes for
// exactly which shapes the defaults pin.
$wide = Diff::compute($before, $after, DiffOptions::new()
->withContextLines(10)
->withIgnoreWhitespace()
->withNoNewlineAnnotation()
->withDevNullOnEmptySide());
// None of those four options bite this one-line change: the sides differ
// beyond whitespace, neither is empty, both end in a newline, and the single
// hunk fits any context window — so the wide-options patch is byte-identical:
echo $wide->unified('file.txt') === $patchText ? "same patch\n" : "wider patch\n";
// same patch
// Number the rows of an existing patch (gutter/viewer support):
foreach (UnifiedScan::lines($patchText) as $row) {
// $row->old, $row->new, $row->fileHeader, $row->kind (ScanRowKind enum)
}
// Real files: (string) file_get_contents() both sides — a file() list side
// is terminated by construction and hides a missing final newline (README
// recipe).
The model
Diffcompute() entry point; lines, hunks, per-side counts and final-newline facts; isEmpty/addedLines/removedLines/unified/hunkText.
Hunk / Line / LineKindOne @@ block; one numbered row; eq/del/ins. All immutable value objects.
Writer\UnifiedFormatRenders the GNU diff -u shape: headers (path labels whose text carries control bytes, a double quote or a backslash are C-quoted git core.quotePath-style), @@ ranges with GNU count elision, opt-in "\ No newline" markers and /dev/null labels.
Writer\SideBySideFormat / SideBySideRowPairs a diff into [left?, right?] rows for split viewers — from a computed Diff or raw patch text, one shared pairing rule.
Reader\UnifiedScanWalks any rendered unified diff, honoring each hunk's declared counts and classifying every row with ScanRowKind — row classification and numbering, no drawing. The public isHunkHeader() predicate is the walk's own recognition pattern, published so consumers gate boundaries without a second regex to drift.
Use it for
- Patch display in TUIs — numbered hunks feed gutters, diff panes, and review overlays without re-deriving line numbers; every row ships redundant non-color channels (
LineKind::marker(),ScanRowKind), so a viewer can tint with color without ever making color carry the change alone (WCAG 1.4.1). - Editing tools — the same engine candy-code's Edit, Write and ApplyPatch tools use to report changes to the model and the user.
- Patch consumers — UnifiedScan answers "which file line is this row?" for arbitrary incoming diffs, including multi-file git output.
Source
API
| Class | Method | Description |
|---|---|---|
| Diff | compute(string|list<string> $before, string|list<string> $after, ?DiffOptions $options = null): self | Line-mode LCS diff; degraded reports the cell-budget fallback (the exact default shapes live in the README Fidelity notes) |
| Diff | unified(string $oldPath, ?string $newPath = null): string | Full diff -u text with --- / +++ headers; the second argument names the new side only |
| Diff | hunkText(): string | Hunks only, no file headers |
| Diff | isEmpty() / addedLines() / removedLines(): int|bool | Summary counts |
| Hunk | header() / lines() / removedCount() / addedCount() | The @@ block (GNU-elided single-line ranges), its rows, and -/+ row tallies |
| Line / LineKind | kind / text / oldNumber / newNumber; marker() / toUnifiedRow() | One numbered verbatim row; eq/del/ins vocabulary |
| DiffOptions | withContextLines(int) / withMaxLcsCells(int) | Context window (negative clamps to 0; DEFAULT_CONTEXT_LINES = 3) and LCS cell budget (0 = a middle with rows on both sides falls back degraded, while a one-sided middle is linear work and stays exact; DEFAULT_MAX_LCS_CELLS = 250 000, counted as the table's real (n+1)×(m+1) footprint) |
| DiffOptions | withIgnoreWhitespace(bool $ignore = true) / withIgnoreCase(bool $ignore = true) | Fold comparisons; emitted rows keep original bytes |
| DiffOptions | withNoNewlineAnnotation(bool $on = true) / withDevNullOnEmptySide(bool $on = true) | GNU annotations, opt-in (the annotation only attaches to STRING sides) |
| UnifiedFormat | write(Diff, string $oldPath, ?string $newPath) / hunksOnly(Diff): string | The writer behind Diff::unified()/hunkText(); NO_NEWLINE_ROW; path labels are control-byte-safe |
| SideBySideFormat | rows(Diff) / fromUnified(string|list<string>): list<SideBySideRow> | Split-view pairing; SideBySideRow->left/->right, isPaired(); list rows are taken as given (no newline refusal — unlike a compute() side), so a host printing an embedded newline into its channel owns sanitizing it |
| UnifiedScan | lines(string|list<string>): list<ScannedLine> | Per-row old/new line numbers, fileHeader flag, and ScanRowKind; declared-count budgets, fail-closed boundaries (MAX_LINE_NUMBER_DIGITS caps start fields); list input is not newline-refused the way compute() sides are — a "a\n+++ forged" element scans as one verbatim row and the lib never re-emits it. ScanRowKind::isContentRow() is true exactly for Context/Insert/Delete, so pairing renderers gate runs on the kind instead of re-sniffing the marker column |
| UnifiedScan | fileHeaders(string|list<string>): list<bool> / rowsOf(string): list<string> | Which rows start a new file; the writer-compatible row split |
| UnifiedScan | isHunkHeader(string): bool | Recognition of the @@ -a,b +c,d @@ boundary by the single pattern the walk itself matches — recognized even when the numbers are too large to number (they close the hunk above without counting), so a consumer gating rows on this predicate cannot drift from what lines() reports |