1.0.5 • Published 4 months ago

diff-apply-alvamind v1.0.5

Weekly downloads
-
License
MIT
Repository
github
Last release
4 months ago

Diff Apply Alvamind

npm version License

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 to searchReplaceDiffStrategy, 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 by diff -u). A common format for patches and version control.
    • newUnifiedDiffStrategy: A enhanced version of the unifiedDiffStrategy with 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: searchReplaceDiffStrategy and multiSearchReplaceDiffStrategy can handle slight variations between the diff and the original content, making it more resilient to minor changes.
  • Line Number Constraints: searchReplaceDiffStrategy and multiSearchReplaceDiffStrategy allow 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: searchReplaceDiffStrategy and multiSearchReplaceDiffStrategy automatically 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: searchReplaceDiffStrategy and multiSearchReplaceDiffStrategy support 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-alvamind

Usage

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. The cwd argument represents the current working directory.

  • applyDiff(params: ApplyDiffParams): Applies the diff. Returns a DiffResult.

    • originalContent: The original text content.
    • diffContent: The diff content, in the format specific to the strategy.
    • fuzzyThreshold?: (Optional, searchReplaceDiffStrategy and multiSearchReplaceDiffStrategy only) 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, searchReplaceDiffStrategy and multiSearchReplaceDiffStrategy only) The number of lines before and after the specified line range to consider when searching. Defaults to 20.
    • startLine?: (Optional, searchReplaceDiffStrategy and multiSearchReplaceDiffStrategy only) The starting line number for the search (1-indexed).
    • endLine?: (Optional, searchReplaceDiffStrategy and multiSearchReplaceDiffStrategy only) 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: true if the diff was applied successfully, false otherwise.
  • content: (If success is true) The modified content.
  • error: (If success is false) A human-readable error message.
  • details: (If success is false, 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 of InsertGroup objects, each specifying an index (where to insert) and elements (the strings to insert). The insertGroups array will be sorted by index before insertion.

Exported Strategies

  • searchReplaceDiffStrategy
  • multiSearchReplaceDiffStrategy
  • unifiedDiffStrategy
  • newUnifiedDiffStrategy

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:

  1. Fork the repository.
  2. Create a new branch for your feature or bug fix: git checkout -b feature/my-new-feature or git checkout -b fix/some-bug.
  3. Write tests for your changes.
  4. Make your changes.
  5. Run the tests: bun test.
  6. Commit your changes: git commit -m "Add a helpful commit message".
  7. Push your branch: git push origin feature/my-new-feature.
  8. 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).