### Build and Test jsdiff with Yarn Source: https://github.com/kpdecker/jsdiff/blob/master/CONTRIBUTING.md Standard commands to install dependencies and run tests for the jsdiff project using Yarn. Assumes Yarn is installed and configured. ```shell yarn yarn test ``` -------------------------------- ### Run jsdiff Tests in a Browser with Karma Source: https://github.com/kpdecker/jsdiff/blob/master/CONTRIBUTING.md Instructions to start Karma test runner for browser-based testing of jsdiff. Requires Karma to be installed. Tests are initiated by opening localhost:9876 in the desired browser. ```shell yarn karma start ``` -------------------------------- ### Install jsdiff using npm Source: https://github.com/kpdecker/jsdiff/blob/master/README.md This command installs the jsdiff library as a project dependency using npm. ```bash npm install diff --save ``` -------------------------------- ### Release jsdiff with Yarn Source: https://github.com/kpdecker/jsdiff/blob/master/CONTRIBUTING.md Commands to perform a full release of the jsdiff library. This includes cleaning previous builds, creating a new production build, and publishing the package. Assumes Yarn is installed. ```shell yarn clean yarn build yarn publish ``` -------------------------------- ### Apply Multi-File Patch in Node.js using jsdiff Source: https://github.com/kpdecker/jsdiff/blob/master/README.md This Node.js example shows how to apply a multi-file patch, similar to the Unix `patch < mydiff.patch` command. It uses the `applyPatches` function, which requires callback functions for loading files (`loadFile`) and handling patched content (`patched`). It also includes a `complete` callback for error handling. ```javascript const {applyPatches} = require('diff'); const patch = fs.readFileSync("mydiff.patch").toString(); applyPatches(patch, { loadFile: (patch, callback) => { let fileContents; try { fileContents = fs.readFileSync(patch.oldFileName).toString(); } catch (e) { callback(`No such file: ${patch.oldFileName}`); return; } callback(undefined, fileContents); }, patched: (patch, patchedContent, callback) => { if (patchedContent === false) { callback(`Failed to apply patch to ${patch.oldFileName}`) return; } fs.writeFileSync(patch.oldFileName, patchedContent); callback(); }, complete: (err) => { if (err) { console.log("Failed with error:", err); } } }); ``` -------------------------------- ### Timeout and MaxEditLength for Large Diffs in Node.js Source: https://context7.com/kpdecker/jsdiff/llms.txt Illustrates how to prevent excessive computation on large or significantly different texts by setting timeout and maxEditLength limits. It shows examples of handling diffs that time out or exceed the maximum edit length, including combining these with async callbacks. ```javascript const {diffLines} = require('diff'); const hugeFile1 = 'Line 1\n'.repeat(100000); const hugeFile2 = 'Different\n'.repeat(100000); // Set timeout to 5 seconds const result1 = diffLines(hugeFile1, hugeFile2, { timeout: 5000 // milliseconds }); if (result1 === undefined) { console.log('Diff timed out'); } // Set maximum edit distance const result2 = diffLines(hugeFile1, hugeFile2, { maxEditLength: 10000 // maximum number of edits to consider }); if (result2 === undefined) { console.log('Diff exceeded maximum edit length'); } // Combine with async for non-blocking operation diffLines(hugeFile1, hugeFile2, { timeout: 5000, maxEditLength: 10000, callback: (changes) => { if (changes === undefined) { console.log('Diff aborted due to timeout or max length'); } else { console.log('Diff completed:', changes.length, 'blocks'); } } }); ``` -------------------------------- ### Basic Character Diffing in Web Page using jsdiff Source: https://github.com/kpdecker/jsdiff/blob/master/README.md This example demonstrates how to use jsdiff to compare two strings and display the differences in a web page. It iterates through the diff array, coloring added characters green, removed characters red, and common characters grey. It requires the 'diff.js' script to be included. ```html
``` -------------------------------- ### Generate Patch from Node.js using jsdiff Source: https://github.com/kpdecker/jsdiff/blob/master/README.md This Node.js example shows how to generate a diff patch between two files, similar to the Unix `diff -u` command. It utilizes the `createTwoFilesPatch` function from the 'diff' module and requires Node.js built-in 'fs' module for file operations. The output is saved to a '.patch' file. ```javascript const {createTwoFilesPatch} = require('diff'); const file1Contents = fs.readFileSync("file1.txt").toString(); const file2Contents = fs.readFileSync("file2.txt").toString(); const patch = createTwoFilesPatch("file1.txt", "file2.txt", file1Contents, file2Contents); fs.writeFileSync("mydiff.patch", patch); ``` -------------------------------- ### Async Diff and Patch Operations with Callbacks in Node.js Source: https://context7.com/kpdecker/jsdiff/llms.txt Demonstrates asynchronous diff and patch operations using callbacks to prevent blocking the event loop. It shows how to handle large files and process the results of diff and patch operations. ```javascript const {diffLines, createPatch, applyPatch} = require('diff'); const largeFile1 = 'A'.repeat(1000000) + '\nB\nC'; const largeFile2 = 'A'.repeat(1000000) + '\nD\nE'; // Async diff diffLines(largeFile1, largeFile2, { callback: (changes) => { console.log(`Diff complete: ${changes.length} change blocks`); changes.forEach((change) => { if (change.added || change.removed) { console.log(`${change.added ? '+' : '-'} ${change.count} lines`); } }); } }); // Async patch creation createPatch('large.txt', largeFile1, largeFile2, undefined, undefined, { callback: (patch) => { console.log('Patch created:', patch.length, 'characters'); // Process patch... } }); console.log('Diff operations started, continuing with other work...'); ``` -------------------------------- ### applyPatches - Apply multiple patches with callbacks Source: https://context7.com/kpdecker/jsdiff/llms.txt Applies multiple patches asynchronously with callbacks for loading files and handling results. Useful for batch patch operations in build tools or version control systems. ```APIDOC ## applyPatches ### Description Applies multiple patches asynchronously with callbacks for loading files and handling results. Useful for batch patch operations in build tools or version control systems. ### Method *Not specified, assumed to be a function call* ### Endpoint *Not applicable (JavaScript function)* ### Parameters #### Arguments - **multiFilePatch** (string) - Required - A string containing multiple patch definitions in unified diff format. - **options** (object) - Required - An object containing callback functions for patch processing: - **loadFile** (function) - Callback to load the content of a file for patching. Receives `(patch, callback)`. - **patched** (function) - Callback invoked after a patch is applied. Receives `(patch, patchedContent, callback)`. - **complete** (function) - Callback invoked when all patches have been processed. Receives `(err)`. ### Request Example ```javascript const {applyPatches} = require('diff'); const fs = require('fs'); const multiFilePatch = `--- file1.txt\n+++ file1.txt\n@@ -1,1 +1,1 @@\n-old content 1\n+new content 1\n--- file2.txt\n+++ file2.txt\n@@ -1,1 +1,1 @@\n-old content 2\n+new content 2`; applyPatches(multiFilePatch, { loadFile: (patch, callback) => { const filename = patch.oldFileName; try { const content = fs.readFileSync(filename, 'utf8'); callback(undefined, content); } catch (err) { callback(`Failed to read ${filename}: ${err.message}`); } }, patched: (patch, patchedContent, callback) => { if (patchedContent === false) { callback(`Failed to apply patch to ${patch.oldFileName}`); return; } try { fs.writeFileSync(patch.oldFileName, patchedContent); console.log(`Successfully patched ${patch.oldFileName}`); callback(); } catch (err) { callback(`Failed to write ${patch.oldFileName}: ${err.message}`); } }, complete: (err) => { if (err) { console.error('Patch operation failed:', err); } else { console.log('All patches applied successfully'); } } }); ``` ### Response *This function operates via callbacks and does not return a direct response. Errors and results are handled by the provided callback functions.* ``` -------------------------------- ### Basic Character Difference in Node.js Source: https://github.com/kpdecker/jsdiff/blob/master/README.md Demonstrates a basic usage of `diffChars` in Node.js to find differences between two strings. It highlights how to iterate through the diff results and display added or removed characters with color coding. Requires the 'colors' package for output formatting. ```javascript require('colors'); const {diffChars} = require('diff'); const one = 'beep boop'; const other = 'beep boob blah'; const diff = diffChars(one, other); diff.forEach((part) => { // green for additions, red for deletions let text = part.added ? part.value.bgGreen : part.removed ? part.value.bgRed : part.value; process.stderr.write(text); }); console.log(); ``` -------------------------------- ### Import jsdiff utilities (CommonJS) Source: https://github.com/kpdecker/jsdiff/blob/master/README.md Shows how to import specific functions like diffChars and createPatch from the jsdiff library in a CommonJS environment. ```javascript const {diffChars, createPatch} = require('diff'); ``` -------------------------------- ### convertChangesToDMP - Export to diff-match-patch format Source: https://context7.com/kpdecker/jsdiff/llms.txt Converts change objects to the format used by Google's diff-match-patch library, enabling interoperability between different diff implementations. ```APIDOC ## convertChangesToDMP ### Description Converts change objects to the format used by Google's diff-match-patch library, enabling interoperability between different diff implementations. ### Method *Not specified, assumed to be a function call* ### Endpoint *Not applicable (JavaScript function)* ### Parameters #### Arguments - **changes** (array) - Required - An array of change objects, typically generated by a diff function (e.g., `diffChars`). Each change object should have `added` (boolean or null), `removed` (boolean or null), and `value` (string) properties. ### Request Example ```javascript const {diffChars, convertChangesToDMP} = require('diff'); const changes = diffChars('Hello', 'Hallo'); const dmpFormat = convertChangesToDMP(changes); console.log(dmpFormat); ``` ### Response #### Success Response (200) - **dmpFormat** (array) - An array representing the diff in a format compatible with the diff-match-patch library. Each element is a tuple `[operation, text]`: - **operation** (number) - -1 for deletion, 0 for equality, 1 for insertion. - **text** (string) - The text content for the operation. #### Response Example ```json [[0, "H"], [-1, "e"], [1, "a"], [0, "llo"]] ``` ``` -------------------------------- ### Import jsdiff utilities (ESM) Source: https://github.com/kpdecker/jsdiff/blob/master/README.md Demonstrates how to import specific functions like diffChars and createPatch from the jsdiff library in an ECMAScript Module (ESM) environment. ```javascript import {diffChars, createPatch} from 'diff'; ``` -------------------------------- ### Apply Multiple Patches Asynchronously with Callbacks (JavaScript) Source: https://context7.com/kpdecker/jsdiff/llms.txt Applies multiple patches defined in a unified diff string asynchronously. It uses callbacks to load original file content and to handle the results of patching each file. This is useful for batch patch operations in build tools or version control systems. It requires the 'diff' and 'fs' modules. ```javascript const {applyPatches} = require('diff'); const fs = require('fs'); const multiFilePatch = `--- file1.txt +++ file1.txt @@ -1,1 +1,1 @@ -old content 1 +new content 1 --- file2.txt +++ file2.txt @@ -1,1 +1,1 @@ -old content 2 +new content 2`; applyPatches(multiFilePatch, { loadFile: (patch, callback) => { const filename = patch.oldFileName; try { const content = fs.readFileSync(filename, 'utf8'); callback(undefined, content); } catch (err) { callback(`Failed to read ${filename}: ${err.message}`); } }, patched: (patch, patchedContent, callback) => { if (patchedContent === false) { callback(`Failed to apply patch to ${patch.oldFileName}`); return; } try { fs.writeFileSync(patch.oldFileName, patchedContent); console.log(`Successfully patched ${patch.oldFileName}`); callback(); } catch (err) { callback(`Failed to write ${patch.oldFileName}: ${err.message}`); } }, complete: (err) => { if (err) { console.error('Patch operation failed:', err); } else { console.log('All patches applied successfully'); } } }); ``` -------------------------------- ### Apply Patch to a Specified File in Node.js using jsdiff Source: https://github.com/kpdecker/jsdiff/blob/master/README.md This Node.js code snippet demonstrates how to apply a diff patch to a specific file, mimicking the Unix `patch` command. It uses the `applyPatch` function from the 'diff' module and requires the 'fs' module for reading and writing files. The patched content is then written back to the original file. ```javascript const {applyPatch} = require('diff'); const file1Contents = fs.readFileSync("file1.txt").toString(); const patch = fs.readFileSync("mydiff.patch").toString(); const patchedFile = applyPatch(file1Contents, patch); fs.writeFileSync("file1.txt", patchedFile); ``` -------------------------------- ### structuredPatch - Generate structured patch object Source: https://context7.com/kpdecker/jsdiff/llms.txt Returns a structured patch object with detailed hunk information instead of a formatted string. Useful for programmatic patch manipulation and custom patch formatting. ```APIDOC ## structuredPatch ### Description Returns a structured patch object with detailed hunk information instead of a formatted string. Useful for programmatic patch manipulation and custom patch formatting. ### Method *Not specified, assumed to be a function call* ### Endpoint *Not applicable (JavaScript function)* ### Parameters #### Arguments - **oldFileName** (string) - Required - The original file name. - **newFileName** (string) - Required - The new file name. - **oldCode** (string) - Required - The content of the old file. - **newCode** (string) - Required - The content of the new file. - **oldHeader** (string) - Required - The header string for the old file. - **newHeader** (string) - Required - The header string for the new file. - **options** (object) - Optional - Configuration options for generating the patch: - **context** (number) - Optional - The number of context lines to include in each hunk. Defaults to 2. - **hash** (string) - Optional - A hash value for the patch. ### Request Example ```javascript const {structuredPatch} = require('diff'); const oldCode = `class User {\n constructor(name) {\n this.name = name;\n }\n}`; const newCode = `class User {\n constructor(name, email) {\n this.name = name;\n this.email = email;\n }\n}`; const patch = structuredPatch( 'User.js', 'User.js', oldCode, newCode, 'Before', 'After', {context: 2} ); console.log(patch); ``` ### Response #### Success Response (200) - **patch** (object) - A structured object representing the patch. - **oldFileName** (string) - The original file name. - **newFileName** (string) - The new file name. - **oldHeader** (string) - The header string for the old file. - **newHeader** (string) - The header string for the new file. - **hunks** (array) - An array of hunk objects: - **oldStart** (number) - The starting line number in the old file. - **oldLines** (number) - The number of lines in the old file for this hunk. - **newStart** (number) - The starting line number in the new file. - **newLines** (number) - The number of lines in the new file for this hunk. - **lines** (array) - An array of strings representing the lines in the hunk, prefixed with '-', '+', or ' '. #### Response Example ```json { "oldFileName": "User.js", "newFileName": "User.js", "oldHeader": "Before", "newHeader": "After", "hunks": [{ "oldStart": 1, "oldLines": 5, "newStart": 1, "newLines": 6, "lines": [ " class User {", "- constructor(name) {", "+ constructor(name, email) {", " this.name = name;", "+ this.email = email;", " }", " }" ] }] } ``` ``` -------------------------------- ### Character Diffing and Display with jsdiff (JavaScript) Source: https://github.com/kpdecker/jsdiff/blob/master/examples/web_example.html This snippet demonstrates how to use Diff.diffChars to find character differences between two strings. It then iterates over the differences, applying specific colors (green for additions, red for deletions, grey for common parts) to spans created for each part's value, and appends these spans to a document fragment for efficient DOM manipulation. Requires a DOM environment with an element having the ID 'display'. ```javascript var one = 'beep boop', other = 'beep boob blah', color = '', span = null; var diff = Diff.diffChars(one, other), display = document.getElementById('display'), fragment = document.createDocumentFragment(); diff.forEach(function(part){ // green for additions, red for deletions // grey for common parts color = part.added ? 'green' : part.removed ? 'red' : 'grey'; span = document.createElement('span'); span.style.color = color; span.appendChild(document.createTextNode(part.value)); fragment.appendChild(span); }); display.appendChild(fragment); ``` -------------------------------- ### Generate Structured Patch Data Source: https://github.com/kpdecker/jsdiff/blob/master/README.md Similar to `createTwoFilesPatch`, this function computes a diff and returns a structured object representing the patch, suitable for further programmatic processing. It includes detailed information about hunks and lines. Parameters are the same as `createTwoFilesPatch`. ```javascript structuredPatch(oldFileName, newFileName, oldStr, newStr[, oldHeader[, newHeader[, options]]]) ``` -------------------------------- ### Word-level Diffing with jsdiff Source: https://context7.com/kpdecker/jsdiff/llms.txt Compares two strings word by word, ideal for natural language text. Whitespace is ignored during diff computation but preserved in the output. Can leverage Intl.Segmenter for advanced word detection. ```javascript const {diffWords} = require('diff'); const original = 'The quick brown fox jumps over the lazy dog'; const modified = 'The fast brown fox leaps over the sleepy dog'; const wordDiff = diffWords(original, modified); wordDiff.forEach((part) => { const prefix = part.added ? '+' : part.removed ? '-' : ' '; console.log(`${prefix} ${part.value}`); }); // Output: // The // - quick // + fast // brown fox // - jumps // + leaps // over the // - lazy // + sleepy // dog // Using Intl.Segmenter for better word detection const segmenter = new Intl.Segmenter('en', {granularity: 'word'}); const advancedDiff = diffWords('Hello world', 'Hello earth', { intlSegmenter: segmenter }); console.log(advancedDiff); ``` -------------------------------- ### parsePatch - Parse unified diff string Source: https://context7.com/kpdecker/jsdiff/llms.txt Parses a unified diff patch string into structured patch objects. Converts patch text into a programmatic format for analysis or manipulation. ```APIDOC ## parsePatch ### Description Parses a unified diff patch string into structured patch objects. Converts patch text into a programmatic format for analysis or manipulation. ### Method *Not specified, assumed to be a function call* ### Endpoint *Not applicable (JavaScript function)* ### Parameters #### Arguments - **patchString** (string) - Required - The unified diff patch string to parse. ### Request Example ```javascript const {parsePatch} = require('diff'); const patchString = `Index: example.js\n=================================================================== --- example.js\t2024-01-01 10:00:00\n+++ example.js\t2024-01-01 11:00:00\n@@ -1,4 +1,5 @@\n const x = 1;\n-const y = 2;\n+const y = 3;\n+const z = 4;\n const sum = x + y;\n console.log(sum);`; const patches = parsePatch(patchString); patches.forEach((patch) => { console.log(`File: ${patch.oldFileName} -> ${patch.newFileName}`); console.log(`Hunks: ${patch.hunks.length}`); patch.hunks.forEach((hunk, index) => { console.log(`\nHunk ${index + 1}:`); console.log(` Old: lines ${hunk.oldStart}-${hunk.oldStart + hunk.oldLines - 1}`); console.log(` New: lines ${hunk.newStart}-${hunk.newStart + hunk.newLines - 1}`); console.log(' Changes:'); hunk.lines.forEach((line) => { console.log(` ${line}`); }); }); }); ``` ### Response #### Success Response (200) - **patches** (array) - An array of structured patch objects. Each object has the following properties: - **oldFileName** (string) - The original file name. - **newFileName** (string) - The new file name. - **oldHeader** (string) - The header string for the old file. - **newHeader** (string) - The header string for the new file. - **hunks** (array) - An array of hunk objects (same structure as returned by `structuredPatch`). #### Response Example ```json [ { "oldFileName": "example.js", "newFileName": "example.js", "oldHeader": "2024-01-01 10:00:00", "newHeader": "2024-01-01 11:00:00", "hunks": [ { "oldStart": 1, "oldLines": 4, "newStart": 1, "newLines": 5, "lines": [ " const x = 1;", "-const y = 2;", "+const y = 3;", "+const z = 4;", " const sum = x + y;", " console.log(sum);" ] } ] } ] ``` ``` -------------------------------- ### Create Unified Diff Patch Source: https://github.com/kpdecker/jsdiff/blob/master/README.md Generates a unified diff patch from two strings. It first computes a line-based diff using `diffLines` and then formats it into the unified diff standard. Supports specifying filenames, headers, and context options, including ignoring whitespace and stripping trailing carriage returns. ```javascript createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr[, oldHeader[, newHeader[, options]]]) ``` ```javascript createPatch(fileName, oldStr, newStr[, oldHeader[, newHeader[, options]]]) ``` -------------------------------- ### Create Patch for Different Files with jsdiff Source: https://context7.com/kpdecker/jsdiff/llms.txt Generates a unified diff patch comparing two distinct files by providing their names and content. This is useful for scenarios involving file renames or comparisons between files with different identifiers. ```javascript const {createTwoFilesPatch} = require('diff'); const file1Content = 'Original content\nLine 2\nLine 3'; const file2Content = 'Modified content\nLine 2\nLine 3'; const patch = createTwoFilesPatch( 'old-file.txt', // old filename 'new-file.txt', // new filename file1Content, // old content file2Content, // new content 'Version 1.0', // old header 'Version 2.0', { context: 2, // number of context lines ignoreWhitespace: false, stripTrailingCr: true } ); console.log(patch); // =================================================================== // --- old-file.txt Version 1.0 // +++ new-file.txt Version 2.0 // @@ -1,3 +1,3 @@ // -Original content // +Modified content // Line 2 // Line 3 ``` -------------------------------- ### convertChangesToXML - Export diff as XML Source: https://context7.com/kpdecker/jsdiff/llms.txt Converts an array of change objects to XML format for integration with XML-based tools or for structured data storage. ```APIDOC ## convertChangesToXML ### Description Converts an array of change objects to XML format for integration with XML-based tools or for structured data storage. ### Method *Not specified, assumed to be a function call* ### Endpoint *Not applicable (JavaScript function)* ### Parameters #### Arguments - **changes** (array) - Required - An array of change objects, typically generated by a diff function (e.g., `diffWords`). Each change object should have `added` (boolean) and `value` (string) properties. ### Request Example ```javascript const {diffWords, convertChangesToXML} = require('diff'); const oldText = 'The quick brown fox'; const newText = 'The fast brown wolf'; const changes = diffWords(oldText, newText); const xml = convertChangesToXML(changes); console.log(xml); ``` ### Response #### Success Response (200) - **xml** (string) - An XML string representing the changes. Added text is wrapped in `` tags, and deleted text is wrapped in `