Search by

inilim / v4a-diff

inilim

Package info

github.com/inilim/v4a-diff

pkg:composer/inilim/v4a-diff

Statistics

Installs: 12

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

0.1.20261205 2026-12-03 22:02 UTC

This package is auto-updated.

Last update: 2026-12-03 22:03:20 UTC


README

V4A Diff

Context-anchored diff patch applicator for PHP

Apply readable patches to strings and files, get structured diffs, and safely perform create, update, delete, and move operations.

PHP >= 8.4 License: MIT

Table of Contents

Features

  • Context-aware application. Source lines are matched by context, not just by line number.
  • OpenAI V4A compatibility. Headerless hunks, create mode, stacked anchors, and *** End of File markers behave like OpenAI's applyDiff reference implementation. Line endings are normalized to LF (see Line endings).
  • Dry-run previews. Compute file changes without writing, deleting, moving, or creating directories.
  • Readable format. The +, -, and @@ anchors are human-readable.
  • Create, update, delete, move. String API and file API with atomic writes.
  • Multi-file transactions. Route patches with *** Add File, *** Delete File, *** Update File, and *** Move to headers and roll back on failure.
  • Diff generation. Builds a V4A patch from two strings or files.
  • Fuzzy matching. Tolerates differences in whitespace, Unicode quotes, dashes, and non-breaking spaces.
  • Structured result. Get the resulting text and a list of lines with oldLine and newLine numbers.
  • Refiner. Split replacements into intra-line segments for change highlighting.
  • Typed exceptions. All library-specific failures share V4AException and include contextual details.
  • PHP 8.4+. Modern strict code, readonly value objects, and the ApplyMode enum.

Requirements

  • PHP 8.4 or higher.
  • Composer.
  • For advanced Unicode normalization, the intl extension with the Normalizer class is recommended. The library continues to work without it.
  • For single-file operations, the source file must exist and the destination directory must already exist and be writable. Missing destination directories cause a FileOperationException.
  • For multi-file operations, missing destination directories are created automatically.

Installation

composer require inilim/v4a-diff

Quick Start

<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use Inilim\V4A\ApplyMode;
use Inilim\V4A\V4A;

$source = "Hello, world!\n";

$diff = <<<'DIFF'
@@ Hello, world!
-Hello, world!
+Hello, V4A!
DIFF;

$result = V4A::apply($source, $diff, ApplyMode::UPDATE);

echo $result->text;
// Hello, V4A!

$result->text contains the resulting text, and $result->diff contains a detailed list of change lines.

V4A Format

A patch consists of one or more sections:

@@ <anchor>
<prefix><content>

The following prefixes are supported:

Prefix Meaning Participates in context search
Context line Yes
- Deleted line Yes, as expected source content
+ Added line No
Empty line Empty context line Yes

Anchors and Sections

@@ class Greeter
-class Greeter
+final class Greeter
  • @@ <anchor> finds the reference line and applies context starting from the matched position.
  • @@ without text marks a section boundary or participates in a stack without adding a search string.
  • The first section may start directly with context, without an anchor.
  • For subsequent sections, use an anchor or @@.
  • *** End of File after a section indicates that the context should be searched closer to the end of the file.
  • Deleted lines are part of the checked context. Their content must match the source, subject to allowed fuzzy matching.

Multiple consecutive @@ lines can be stacked before a section. Each non-empty anchor narrows the search, and every non-empty anchor in a stack must match:

@@ class Greeter
@@ public function greet():
-    return 'hi';
+    return 'hello';

When a stack contains only one non-empty anchor, a missing anchor is ignored and the following context is matched normally. A missing anchor in a multi-anchor stack raises a DiffSyntaxException. For a stack with only one non-empty anchor, the anchor is required to be unique in the source; ambiguity raises DiffSyntaxException.

Line endings

Line endings are normalized to LF for parsed sources, diffs, and results. An input with CRLF source is accepted, and the result uses LF. This intentionally diverges from OpenAI's applyDiff, which preserves CRLF byte-for-byte. Full CRLF preservation is documented as a limitation because it conflicts with the library's stable line-ending invariant.

Envelope Lines

Compatibility wrappers and headers are recognized and discarded during parsing:

*** Begin Patch
*** Update File: src/Greeter.php
@@ class Greeter
-class Greeter
+final class Greeter
*** End Patch

The following lines are supported:

  • *** Begin Patch
  • *** End Patch
  • *** Add File: <path>
  • *** Delete File: <path>
  • *** Update File: <path>
  • *** Move to: <path>
  • --- a/<path>
  • +++ b/<path>
  • \ No newline at end of file

Important

In V4A::apply() and V4A::applyFile(), these headers are compatibility wrappers and do not route across multiple files. Use V4A::applyFiles(), V4A::applyPatch(), or V4A::applyMultiFile() for automatic routing and transactional multi-file application.

Modes

Mode String value String API File API
ApplyMode::UPDATE update Applies the patch and returns the updated text. Requires an existing file; writes only if there are changes.
ApplyMode::CREATE create Parses the patch from lines prefixed with + and creates text from scratch. Error if the file already exists; creates a new file.
ApplyMode::DELETE delete Returns empty text and a diff of deleted lines. Deletes an existing file.
ApplyMode::MOVE move Handled as UPDATE at the string level. Moves the file, applying changes if necessary.

UPDATE

$result = V4A::apply($source, $diff, ApplyMode::UPDATE);

CREATE

$result = V4A::applyFile(
    __DIR__ . '/generated/Greeter.php',
    <<<'DIFF'
+<?php
+
+declare(strict_types=1);
+
+final class Greeter
+{
+}
DIFF,
    ApplyMode::CREATE
);

Note

All meaningful lines of a create patch must start with +. The destination directory must already exist for the single-file API.

DELETE

$result = V4A::applyFile(
    __DIR__ . '/generated/Greeter.php',
    '',
    ApplyMode::DELETE
);

$result->deleted; // true

In DELETE mode, the diff content is ignored: the entire source file is deleted.

MOVE

Pure move via the targetPath parameter:

$result = V4A::applyFile(
    __DIR__ . '/src/Legacy.php',
    '',
    ApplyMode::MOVE,
    __DIR__ . '/src/Modern.php'
);

Move with changes and target specified via *** Move to::

$result = V4A::applyFile(
    __DIR__ . '/src/Legacy.php',
    <<<'DIFF'
*** Move to: src/Modern.php
@@ final class Legacy
-final class Legacy
+final class Modern
DIFF,
    ApplyMode::MOVE
);

If targetPath is provided, it takes precedence over *** Move to:. If the target is not specified in either place, a FileOperationException is thrown. The destination directory must already exist.

Public API

V4A::apply()

public static function apply(
    ?string $sourceText,
    ?string $diffText,
    ApplyMode|string $mode = ApplyMode::UPDATE
): ApplyDiffResult

Applies a patch to a string. null values are treated as empty strings. The mode can be passed as an enum value or a string: update, create, delete, move.

V4A::applyString()

Alias of V4A::apply().

V4A::applyFile()

public static function applyFile(
    string $path,
    string $diffText,
    ApplyMode|string $mode = ApplyMode::UPDATE,
    ?string $targetPath = null,
    bool $dryRun = false
): FileApplyResult

Applies a patch to a file. For CREATE, the $path parameter is the file to create. For MOVE, $targetPath specifies the new location. When $dryRun is true, the result is computed without writing, deleting, moving, or creating directories. Use V4A::previewFile() as a shortcut.

V4A::applyToFile()

Alias of V4A::applyFile(). It accepts the same $dryRun parameter.

V4A::previewFile()

public static function previewFile(
    string $path,
    string $diffText,
    ApplyMode|string $mode = ApplyMode::UPDATE,
    ?string $targetPath = null
): FileApplyResult

Shortcut for V4A::applyFile($path, $diffText, $mode, $targetPath, true).

V4A::applyFiles()

public static function applyFiles(
    string $diffText,
    string $basePath = '.',
    bool $dryRun = false
): MultiFileApplyResult

Applies a routed multi-file patch. File operations are selected by *** Add File:, *** Delete File:, and *** Update File:. An *** Update File: section may contain or be preceded by *** Move to: to move the updated file. Relative paths are resolved against $basePath.

All operations are prepared in memory first. The resulting file set is committed as a single best-effort transaction with rollback on failure. When $dryRun is true, the commit phase is skipped entirely.

V4A::applyPatch()

Alias of V4A::applyFiles(). It accepts the same $dryRun parameter.

V4A::applyMultiFile()

Alias of V4A::applyFiles(). It accepts the same $dryRun parameter.

V4A::previewFiles()

public static function previewFiles(
    string $diffText,
    string $basePath = '.'
): MultiFileApplyResult

Shortcut for V4A::applyFiles($diffText, $basePath, true).

V4A::previewPatch() and V4A::previewMultiFile()

Aliases of V4A::previewFiles().

V4A::refine()

public static function refine(mixed $diffLines): array

Accepts an array of DiffLine and returns a new array of DiffLine with populated segments for paired replacements. If a non-array is passed, an empty array is returned.

V4A::generate()

public static function generate(
    ?string $sourceText,
    ?string $targetText,
    int $contextLines = 3
): string

Builds a V4A patch that transforms $sourceText into $targetText. null values are treated as empty strings. If the texts are equal, an empty string is returned.

V4A::generateString()

Alias of V4A::generate().

V4A::generateFile()

public static function generateFile(
    string $sourcePath,
    string $targetPath,
    ?string $filePath = null,
    int $contextLines = 3
): string

Reads two files and returns a V4A patch with a *** Update File: header. If $filePath is not specified, the $sourcePath is used in the header. If the file contents are equal, an empty string is returned.

Line Type Constants

use Inilim\V4A\DiffLineType;

DiffLineType::ADD;
DiffLineType::DELETE;
DiffLineType::EQUAL;

Diff Generation

V4A::generate() builds a V4A patch from two texts. The patch can be passed to V4A::apply().

$source = "Hello, world!\n";
$target = "Hello, V4A!\n";

$patch = V4A::generate($source, $target);

echo $patch;

For files, use V4A::generateFile():

$patch = V4A::generateFile(
    __DIR__ . '/old/Example.php',
    __DIR__ . '/new/Example.php',
    'src/Example.php'
);

The third parameter sets the path in the *** Update File: header. If omitted, the source path is used. If the texts are equal, an empty string is returned. The $contextLines parameter controls the number of context lines around changes and defaults to 3.

Working with Files

V4A::applyFile() is a safe filesystem adapter.

  • For UPDATE, DELETE, and MOVE, the source file must exist.
  • For CREATE, the file must not exist.
  • For MOVE, the target file must not exist if the target differs from the source.
  • If MOVE is performed to the same path, the change is handled as a regular UPDATE.
  • Writing is atomic: a temporary file is created in the same directory, then rename is performed.
  • fsync is used when available.
  • The permission mode of an existing file is preserved for UPDATE and MOVE.
  • When creating a new file, permissions are computed as 0666 & ~umask().
  • If deleting the source after a move fails, the library attempts to delete the already-created target copy.
  • For single-file operations, the destination directory must already exist. Missing directories cause a FileOperationException.
  • Multi-file operations create missing destination directories automatically during the commit phase.

Result flags:

  • written - true if the file was written or overwritten, or would be written in dry-run mode.
  • written - false for UPDATE with no changes, for a no-op MOVE to the same path, and when a preview has no content changes.
  • deleted - true for ApplyMode::DELETE, or would be deleted in dry-run mode.
  • dryRun - true when no filesystem changes were made.
  • With MOVE, the source file is deleted, but deleted remains false: targetPath indicates the move.

For multi-file patches, use V4A::applyFiles() or its aliases. See the next sections.

Dry-run and Preview

Dry-run mode validates a patch and returns the resulting text, structured diff, and planned file operations without changing the filesystem.

use Inilim\V4A\ApplyMode;
use Inilim\V4A\V4A;

$preview = V4A::previewFile(
    __DIR__ . '/src/Example.php',
    $diff,
    ApplyMode::UPDATE
);

echo $preview->result->text; // resulting text
$preview->written;           // true when the patch would change the file
$preview->dryRun;            // true

The same behavior is available through the $dryRun parameter:

$preview = V4A::applyFile(
    __DIR__ . '/src/Example.php',
    $diff,
    ApplyMode::UPDATE,
    dryRun: true
);

For routed multi-file patches, use V4A::previewFiles():

$preview = V4A::previewFiles($patch, __DIR__);

$preview->files;  // list<FileApplyResult> with planned operations
$preview->dryRun; // true

Dry-run does not write files, delete files, move files, or create missing directories. Source files are still read, patches are still parsed, and in-memory operations are still validated. written and deleted describe the operations that would have been performed.

Note

Dry-run does not execute the final multi-file commit. Commit-time failures such as permission changes, concurrent modifications, or unavailable filesystems are outside the preview.

Multi-file Patches

V4A::applyFiles() routes a patch by file header instead of applying it to a single source.

$result = V4A::applyFiles(
    <<<'DIFF'
*** Begin Patch
*** Update File: src/Greeter.php
@@ final class Greeter
-final class Greeter
+final class Greeter implements GreeterInterface
*** Add File: src/GreeterInterface.php
+<?php
+
+namespace App;
+
+interface GreeterInterface
+{
+}
*** Delete File: src/LegacyGreeter.php
*** Update File: src/OldGreeter.php
*** Move to: src/NewGreeter.php
@@ final class OldGreeter
-final class OldGreeter
+final class NewGreeter
*** End Patch
DIFF,
    __DIR__
);

$result->files;    // list<FileApplyResult>
$result->diff;     // original patch
$result->basePath; // resolved base path
  • *** Add File: creates the file from + lines.
  • *** Delete File: removes the file. Its body is ignored.
  • *** Update File: applies the following hunks to an existing file.
  • *** Move to: moves the file updated by the current *** Update File: section. The canonical position is directly after the *** Update File: header. For compatibility with patch producers that place the move marker first, a *** Move to: line immediately before an *** Update File: header is also accepted and applies to that following update section.
  • Empty separator lines between file sections are ignored. Use a + line to create an empty line inside an added file.
  • Relative paths are resolved against $basePath; absolute paths are preserved.
  • *** Begin Patch and *** End Patch are optional wrappers.
  • Missing destination directories are created automatically during the commit phase.
  • Pass $dryRun = true or use V4A::previewFiles() to prepare the same operations without committing them.

All operations are prepared in memory first. The final file set is committed as a single best-effort transaction. If validation, content application, or commit fails, files already changed during the commit are restored and newly created files are removed.

Important

Multi-file rollback is not an OS-level filesystem snapshot. The library does not provide file locking, so use external synchronization for concurrent changes.

Results

ApplyDiffResult

use Inilim\V4A\Types\ApplyDiffResult;

$result = V4A::apply($source, $diff);

$result->text;   // resulting text
$result->diff;   // list<DiffLine>
$result->source; // source text

The toArray() method returns an array:

$array = $result->toArray();

Example structure:

[
    'text' => "Hello, V4A!\n",
    'diff' => [
        [
            'type' => 'delete',
            'value' => 'Hello, world!',
            'oldLine' => 1,
            'newLine' => null,
        ],
        [
            'type' => 'add',
            'value' => 'Hello, V4A!',
            'oldLine' => null,
            'newLine' => 1,
        ],
        [
            'type' => 'equal',
            'value' => '',
            'oldLine' => 2,
            'newLine' => 2,
        ],
    ],
    'source' => "Hello, world!\n",
]

DiffLine

use Inilim\V4A\Types\DiffLine;

$line->type;     // add, delete, or equal
$line->value;    // line content
$line->oldLine;  // source line number or null
$line->newLine;  // result line number or null
$line->segments; // null or list<CharSegment>

CharSegment

use Inilim\V4A\Types\CharSegment;

$segment->type;  // add, delete, or equal
$segment->value; // line fragment

FileApplyResult

use Inilim\V4A\Types\FileApplyResult;

$result->result;     // ApplyDiffResult
$result->sourcePath; // source path
$result->targetPath; // target path or null
$result->written;    // bool
$result->deleted;    // bool
$result->dryRun;     // bool

MultiFileApplyResult

use Inilim\V4A\Types\MultiFileApplyResult;

$result->files;    // list<FileApplyResult>
$result->diff;     // original patch text
$result->basePath; // resolved base path
$result->dryRun;   // bool

The toArray() method returns the structured result of every routed file operation, including the per-file and top-level dryRun flags.

Diff Refinement

The refiner splits consecutive blocks of deletions and additions into intra-line segments. This is useful for highlighting changes in a UI.

use Inilim\V4A\V4A;

$result = V4A::apply($source, $diff);
$refined = V4A::refine($result->diff);

foreach ($refined as $line) {
    if (null === $line->segments) {
        continue;
    }

    foreach ($line->segments as $segment) {
        echo $segment->type . ': ' . $segment->value . PHP_EOL;
    }
}

refine() does not change the resulting text. It only augments DiffLine with segments metadata.

Fuzzy Matching

Exact matching is always checked before fuzzy matching.

The following strategies are used for anchors:

  1. Exact match.
  2. Trimming leading and trailing whitespace.
  3. Unicode normalization and typographic character replacement.

The following strategies are used for context:

  1. Exact match.
  2. Ignoring trailing whitespace.
  3. Collapsing repeated whitespace.
  4. Trimming leading and trailing whitespace.
  5. Unicode normalization and typographic character replacement.

Unicode normalization helps match:

  • various hyphen and dash characters;
  • typographic quotes;
  • ellipses;
  • non-breaking and narrow spaces.

Tip

If the file contains repeated lines, add more surrounding context and make the anchor unique. An ambiguous single exact anchor may cause a DiffSyntaxException. Stacked anchors narrow the search before ambiguity becomes an issue.

The *** End of File marker makes the library search for context closer to the end of the file first, then fall back to normal search.

Errors and Safety

All custom library exceptions extend Inilim\V4A\Exception\V4AException.

Exception When it occurs
V4AException Base class for all custom library exceptions.
DiffSyntaxException Invalid patch syntax, empty section, unknown marker, unmatched context, ambiguous exact single anchor, missing required stacked anchor.
FileOperationException File does not exist, file already exists, missing destination directory, no access to directory, failed to create temporary file, failed to move or delete file, failed multi-file transaction.
DiffRangeException Chunk is out of source bounds or overlaps with an already applied chunk.
InvalidApplyModeException An unknown mode string was passed through the public API.

DiffSyntaxException extends V4AException:

use Inilim\V4A\Exception\DiffSyntaxException;
use Inilim\V4A\V4A;

try {
    V4A::apply($source, $diff);
} catch (DiffSyntaxException $exception) {
    echo $exception->getMessage();
}

File errors are represented by FileOperationException:

use Inilim\V4A\ApplyMode;
use Inilim\V4A\Exception\FileOperationException;
use Inilim\V4A\V4A;

try {
    V4A::applyFile(__DIR__ . '/src/Example.php', $diff, ApplyMode::UPDATE);
} catch (FileOperationException $exception) {
    echo $exception->getMessage();
}

File Operation Safety

  • Changes are written via a temporary file in the same directory.
  • Writing and buffer flushing are performed first, then replacement via rename.
  • For MOVE, an attempt is made to roll back the target copy if deleting the source fails.
  • For multi-file patches, all operations are simulated in memory before any file is changed.
  • If a commit step fails, changed files are restored and newly created files are removed.
  • For single-file operations, the destination directory must already exist.
  • For multi-file operations, missing destination directories are created automatically during the commit phase.
  • Dry-run skips the write, delete, move, and directory creation phases entirely.
  • The library does not try to guess the project structure.
  • There is no built-in file locking. Use external synchronization for concurrent changes.

Limitations

  • V4A::apply(), V4A::applyString(), V4A::applyFile(), and V4A::applyToFile() apply one patch to one source. Use V4A::applyFiles() for automatic multi-file routing.
  • *** Update File, *** Add File, and *** Delete File route only in the multi-file API; in the single-source API they remain compatibility headers.
  • *** Move to: must be associated with an *** Update File: section. The canonical position is directly after the header; a preceding marker is accepted for compatibility.
  • Single-file operations do not create missing destination directories. Multi-file operations do.
  • Multi-file rollback is best effort and is not a substitute for an OS-level transaction or external locking.
  • In DELETE mode, the diff content is ignored.
  • The service line \ No newline at end of file is accepted for compatibility and ignored.
  • There is no built-in file locking.
  • Dry-run validates parsing and in-memory operations, but it does not perform the final filesystem commit. Commit-time failures such as permission changes or concurrent modifications are not detected by a preview.
  • Fuzzy matching does not replace business validation of the result. Use sufficient context for repeated sections.
  • Consecutive @@ lines are treated as a stacked anchor group; an empty section is an anchor group with no following hunk lines.
  • Line endings are normalized to LF. OpenAI's applyDiff preserves CRLF byte-for-byte, but this library intentionally normalizes input and output to LF for consistency with the rest of the project.

License

The project is distributed under the MIT license.