diff-apply-alvamind
v1.0.5
Published
A utility for applying file diffs programmatically
Maintainers
Readme
Diff Apply Alvamind
diff-apply-alvamind is a powerful and flexible JavaScript/TypeScript library designed to apply diffs to text content, particularly source code. It offers multiple diff strategies, robust error handling, and features specifically tailored for handling whitespace and indentation, making it ideal for code modification tools, automated refactoring, and collaborative editing scenarios. It leverages the power of the Alvamind framework for dependency injection and extensibility.
Key Features
- Multiple Diff Strategies: Offers a variety of diffing algorithms to handle different scenarios and diff formats:
searchReplaceDiffStrategy: Performs a precise search and replace operation. Excellent for surgical modifications where you know the exact content to be changed. Supports fuzzy matching, line number constraints, and middle-out searching.multiSearchReplaceDiffStrategy: Similar tosearchReplaceDiffStrategy, but supports applying multiple search/replace blocks within a single diff. This is highly efficient for making several related changes in one go.unifiedDiffStrategy: Applies standard unified diffs (as generated bydiff -u). A common format for patches and version control.newUnifiedDiffStrategy: A enhanced version of theunifiedDiffStrategywith more advanced features, better fuzzy, anchor and fallback to git strategy.
- Whitespace and Indentation Handling: Carefully preserves indentation (spaces and tabs) during replacements, ensuring code formatting remains consistent. Handles mixed indentation styles.
- Fuzzy Matching:
searchReplaceDiffStrategyandmultiSearchReplaceDiffStrategycan handle slight variations between the diff and the original content, making it more resilient to minor changes. - Line Number Constraints:
searchReplaceDiffStrategyandmultiSearchReplaceDiffStrategyallow you to specify a line number range to constrain the search, improving accuracy and preventing unintended modifications. - Detailed Error Reporting: Provides comprehensive error messages when a diff cannot be applied, including similarity scores, matched ranges, and debugging information, helping you pinpoint the cause of the issue.
- Line Number Stripping:
searchReplaceDiffStrategyandmultiSearchReplaceDiffStrategyautomatically handles diffs that include or omit line numbers, adding flexibility. - Insertion and Deletion: Supports inserting new code blocks at specific lines and deleting entire sections of code.
- TypeScript Support: Fully typed for a better development experience.
- Middle-Out Search:
searchReplaceDiffStrategyandmultiSearchReplaceDiffStrategysupport efficient searching for matches that prioritizes areas closer to the middle, this help the AI to select the right place, when there are multiple instances of the same code. - Extensible with Alvamind: Built with Alvamind, making it easy to extend and customize.
Installation
npm install diff-apply-alvamindUsage
import {
searchReplaceDiffStrategy,
multiSearchReplaceDiffStrategy,
unifiedDiffStrategy,
newUnifiedDiffStrategy,
DiffResult,
DiffStrategy,
InsertGroup,
insertGroups,
} from 'diff-apply-alvamind';
// --- Example with searchReplaceDiffStrategy ---
const originalContent = `
function hello() {
console.log("hello");
}
`;
const diffContent = `
<<<<<<< SEARCH
function hello() {
console.log("hello");
}
=======
function hello() {
console.log("hello world");
}
>>>>>>> REPLACE
`;
const result: DiffResult = searchReplaceDiffStrategy.applyDiff({ originalContent, diffContent });
if (result.success) {
console.log("Modified Content (searchReplace):\n", result.content);
} else {
console.error("Error applying diff (searchReplace):\n", result.error);
}
// --- Example with multiSearchReplaceDiffStrategy ---
const originalContentMulti = `
function one() {
return "target";
}
function two() {
return "target";
}
`;
const diffContentMulti = `
<<<<<<< SEARCH
return "target";
=======
return "updated";
>>>>>>> REPLACE
<<<<<<< SEARCH
function two() {
=======
function twoChanged() {
>>>>>>> REPLACE
`;
const resultMulti: DiffResult = multiSearchReplaceDiffStrategy.applyDiff(originalContentMulti, diffContentMulti);
if (resultMulti.success) {
console.log("Modified Content (multiSearchReplace):\n", resultMulti.content);
} else {
console.error("Error applying diff (multiSearchReplace):\n", resultMulti.error);
}
// --- Example with unifiedDiffStrategy ---
const originalContentUnified = `
function greet(name) {
return "Hello, " + name + "!";
}
`;
const diffContentUnified = `
--- a/file.js
+++ b/file.js
@@ -1,3 +1,3 @@
function greet(name) {
- return "Hello, " + name + "!";
+ return "Hello, " + name + "!!";
}
`;
const resultUnified: DiffResult = unifiedDiffStrategy.applyDiff(originalContentUnified, diffContentUnified);
if (resultUnified.success) {
console.log("Modified Content (unified):\n", resultUnified.content);
} else {
console.error("Error applying diff (unified):\n", resultUnified.error);
}
// --- Example with newUnifiedDiffStrategy ---
const originalContentNewUnified = `
function greet(name) {
return "Hello, " + name + "!";
}
`;
const diffContentNewUnified = `
--- a/file.js
+++ b/file.js
@@ ... @@
function greet(name) {
- return "Hello, " + name + "!";
+ return "Hello, " + name + "!!";
}
`;
const resultNewUnified: DiffResult = newUnifiedDiffStrategy.applyDiff({
originalContent: originalContentNewUnified,
diffContent: diffContentNewUnified
});
if (resultNewUnified.success) {
console.log("Modified Content (newUnified):\n", resultNewUnified.content);
} else {
console.error("Error applying diff (newUnified):\n", resultNewUnified.error);
}
// --- Example with insertGroups ---
const original = ['line1', 'line2', 'line3'];
const groups: InsertGroup[] = [
{ index: 1, elements: ['inserted1', 'inserted2'] },
{ index: 3, elements: ['inserted3'] },
];
const inserted = insertGroups(original, groups);
console.log("Inserted Content:\n", inserted.join('\n'));
// Output:
// line1
// inserted1
// inserted2
// line2
// inserted3
// line3
API Reference
DiffStrategy Interface
interface DiffStrategy {
getToolDescription(args: { cwd: string; toolOptions?: { [key: string]: string } }): string;
applyDiff(params: ApplyDiffParams): DiffResult;
}getToolDescription(args: { cwd: string }): Returns a string describing the strategy, intended for use in tools or documentation. Thecwdargument represents the current working directory.applyDiff(params: ApplyDiffParams): Applies the diff. Returns aDiffResult.originalContent: The original text content.diffContent: The diff content, in the format specific to the strategy.fuzzyThreshold?: (Optional,searchReplaceDiffStrategyandmultiSearchReplaceDiffStrategyonly) A number between 0 and 1 (inclusive) representing the minimum similarity score required for a fuzzy match. Defaults to 1.0 (exact match).bufferLines?: (Optional,searchReplaceDiffStrategyandmultiSearchReplaceDiffStrategyonly) The number of lines before and after the specified line range to consider when searching. Defaults to 20.startLine?: (Optional,searchReplaceDiffStrategyandmultiSearchReplaceDiffStrategyonly) The starting line number for the search (1-indexed).endLine?: (Optional,searchReplaceDiffStrategyandmultiSearchReplaceDiffStrategyonly) The ending line number for the search (1-indexed).
DiffResult Type
type DiffResult =
| { success: true; content: string; failParts?: DiffResult[] }
| ({
success: false
error?: string
details?: {
similarity?: number
threshold?: number
matchedRange?: { start: number; end: number }
searchContent?: string
bestMatch?: string
}
failParts?: DiffResult[]
} & ({ error: string } | { failParts: DiffResult[] }))success:trueif the diff was applied successfully,falseotherwise.content: (Ifsuccessistrue) The modified content.error: (Ifsuccessisfalse) A human-readable error message.details: (Ifsuccessisfalse, optional) An object containing more details about the failure:similarity: The similarity score between the search content and the best match found (0 to 1).threshold: The minimum similarity threshold required.matchedRange: The line range where the best match was found.searchContent: The content that was searched for.bestMatch: The best matching content found.
failParts: (Optional) diff results for each operation, when there are multiple operations
insertGroups Function
function insertGroups(original: string[], insertGroups: InsertGroup[]): string[];
interface InsertGroup {
index: number;
elements: string[];
}Inserts groups of strings into an array at specified indices.
original: The original array of strings.insertGroups: An array ofInsertGroupobjects, each specifying anindex(where to insert) andelements(the strings to insert). TheinsertGroupsarray will be sorted by index before insertion.
Exported Strategies
searchReplaceDiffStrategymultiSearchReplaceDiffStrategyunifiedDiffStrategynewUnifiedDiffStrategy
Each of these exports an object that implements the DiffStrategy interface.
Diff Formats
searchReplaceDiffStrategy and multiSearchReplaceDiffStrategy Format
<<<<<<< SEARCH
[exact content to find, including whitespace and indentation]
=======
[new content to replace with, preserving indentation relative to the SEARCH block]
>>>>>>> REPLACE- Example with multi:
<<<<<<< SEARCH
:start_line:1
:end_line:2
-------
def calculate_sum(items):
sum = 0
=======
def calculate_sum(items):
sum = 0
>>>>>>> REPLACE
<<<<<<< SEARCH
:start_line:4
:end_line:5
-------
total += item
return total
=======
sum += item
return sum
>>>>>>> REPLACE<<<<<<< SEARCH: Marks the beginning of the section to search for.=======: Separates the search section from the replacement section.>>>>>>> REPLACE: Marks the end of the replacement section.- Line numbers You can use or not line numbers.
- Indentation You must preserve the correct indentation.
unifiedDiffStrategy Format
Standard unified diff format (output of diff -u).
--- a/file.ext
+++ b/file.ext
@@ -1,3 +1,3 @@
line1
-line2
+new line2
line3--- a/file.ext: The original file path.+++ b/file.ext: The modified file path.@@ -1,3 +1,3 @@: The hunk header, indicating the line numbers and changes.-: Lines to be removed.+: Lines to be added.- (space): Context lines.
newUnifiedDiffStrategy Format
Standard unified diff format (output of diff -u).
--- a/file.ext
+++ b/file.ext
@@ ... @@
line1
-line2
+new line2
line3--- a/file.ext: The original file path.+++ b/file.ext: The modified file path.@@ ... @@: The hunk header.-: Lines to be removed.+: Lines to be added.- (space): Context lines.
Error Handling
The applyDiff method returns a DiffResult object. If success is false, the error property will contain a detailed error message. The details property may provide further information, such as the similarity score and the range where the best match was found. This allows you to implement robust error handling and provide helpful feedback to the user.
Contributing
Contributions are welcome! Please follow these guidelines:
- Fork the repository.
- Create a new branch for your feature or bug fix:
git checkout -b feature/my-new-featureorgit checkout -b fix/some-bug. - Write tests for your changes.
- Make your changes.
- Run the tests:
bun test. - Commit your changes:
git commit -m "Add a helpful commit message". - Push your branch:
git push origin feature/my-new-feature. - Create a pull request.
Please ensure your code adheres to the existing coding style and that all tests pass before submitting a pull request.
License
MIT License (see LICENSE file).
