Diff

Compare text and arrays, and create, parse and apply unified diffs with Bun.diff

Bun.diff compares text and arrays. It also creates, parses and applies patches in the unified diff format.

import { diff } from "bun";

const patch = diff.createPatch("a\nb\n", "a\nc\n", { oldFileName: "file.txt" });
// --- file.txt
// +++ file.txt
// @@ -1,2 +1,2 @@
//  a
// -b
// +c

diff.applyPatch("a\nb\n", patch); // "a\nc\n"

Compare#

FunctionA token is
diff.lines(oldText, newText)a line, with its \n or \r\n
diff.words(oldText, newText)a word of Latin letters, digits and _, a run of spaces, a line ending, or any other code point
diff.chars(oldText, newText)a code point
diff.arrays(oldArr, newArr)an element, compared with ===

Each function returns a list of changes. A change is a run of tokens, and count is the number of tokens in it.

Bun.diff.words("the quick fox", "the slow fox");
// [
//   { value: "the ", added: false, removed: false, count: 2 },
//   { value: "quick", added: false, removed: true, count: 1 },
//   { value: "slow", added: true, removed: false, count: 1 },
//   { value: " fox", added: false, removed: false, count: 2 },
// ]

Bun.diff.arrays([1, 2, 3], [1, 3, 4]);
// [
//   { value: [1], added: false, removed: false, count: 1 },
//   { value: [2], added: false, removed: true, count: 1 },
//   { value: [3], added: false, removed: false, count: 1 },
//   { value: [4], added: true, removed: false, count: 1 },
// ]

maxEditLength#

Pass maxEditLength to skip inputs that have little in common. The function returns undefined when the diff adds and removes more tokens than that. hunks and createPatch take the same option.

Bun.diff.chars("abc", "xyz", { maxEditLength: 5 }); // undefined

Large inputs#

Bun looks for the shortest diff and limits the work it spends on the search. The limit is a number of steps, so the same inputs give the same result on every machine.

Tokens that appear in only one input don't count toward the limit. Inputs stay within it when one of these is true:

  • Each input has up to about 70,000 tokens.
  • The diff has up to about 8,000 additions plus 8,000 removals.
  • Few tokens repeat, as with a long list of unique lines in a different order.

Past the limit, Bun returns a diff that is correct but can be longer than the shortest one, and maxEditLength applies to that diff.

Create a patch#

diff.createPatch returns a unified diff. It returns "" when the texts are equal.

Bun.diff.createPatch(oldText, newText, {
  oldFileName: "a/file.txt", // defaults to newFileName
  newFileName: "b/file.txt", // defaults to oldFileName
  oldHeader: "2024-01-01", // text after the old name
  newHeader: "2024-01-02", // text after the new name
  context: 3, // unchanged lines around each change. Default: 4. Infinity for the whole file
});

Without a file name, the patch starts at the first @@ line. Bun quotes names that contain special characters the way Git does.

diff.hunks returns the same information as objects.

Bun.diff.hunks("a\nb\nc\n", "a\nx\nc\n", { context: 1 });
// [{ oldStart: 1, oldLines: 3, newStart: 1, newLines: 3, lines: [" a", "-b", "+x", " c"] }]

Parse a patch#

diff.parsePatch reads the output of diff -u, git diff, git format-patch, svn diff and hg diff. It returns one entry for each file and throws a SyntaxError for a malformed hunk or file header.

for (const file of Bun.diff.parsePatch(await Bun.$`git diff`.text())) {
  console.log(file.newFileName, file.hunks.length);
}

File names come from the patch as they are. Check them before you use them as paths.

Entries from git diff have isGit: true. They also have isRename, isCopy, isCreate, isDelete, isBinary, oldMode and newMode when the patch says so.

Apply a patch#

diff.applyPatch takes a unified diff for one file, or an array of hunks. It returns the patched text, or undefined when a hunk does not match.

const [file] = Bun.diff.parsePatch(patch);
Bun.diff.applyPatch(source, file.hunks);
  • The lines that a hunk keeps and removes have to match exactly.
  • If they don't match at oldStart, Bun uses the nearest line where they do, after the previous hunk. This search has a limit on its number of steps, and applyPatch returns undefined when it reaches the limit.
  • A hunk that adds or removes a line marked \ No newline at end of file has to reach the end of the source. diff does not check this.
  • If the source only has \r\n line endings and the patch only has \n, or the reverse, Bun converts the patch first. A patch made with context: 0 that adds the other line ending is converted too.

Migrate from the diff package#

Changes, hunks and parsed patches have the same shape as in diff 9. When several shortest diffs exist, Bun picks the same one, up to the limit for large inputs.

diffBun.diff
diffLines(a, b)lines(a, b)
diffWordsWithSpace(a, b)words(a, b)
diffChars(a, b)chars(a, b)
diffArrays(a, b)arrays(a, b)
structuredPatch(oldName, newName, a, b).hunkshunks(a, b)
createPatch(name, a, b)createPatch(a, b, { oldFileName: name })
createTwoFilesPatch(oldName, newName, a, b)createPatch(a, b, { oldFileName: oldName, newFileName: newName })
parsePatch(patch)parsePatch(patch)
applyPatch(source, patch), applyPatch(source, parsed)applyPatch(source, patch), applyPatch(source, parsed.hunks)

Differences:

  • createPatch does not write the Index: and === lines, and returns "" for equal texts. It writes a tab after a file name with a space, as Git does.
  • applyPatch returns undefined instead of false. It rejects a hunk that only fits outside the source or before the previous hunk. It throws for a binary patch from git diff.
  • parsePatch throws for a malformed @@ line, accepts the -- signature of git format-patch, sets isBinary for GIT binary patch, and returns one entry for each file of svn diff --git.
  • parsePatch skips a single --- text or +++ text line in the message before diff --git.
  • parsePatch and applyPatch accept a patch whose line endings were converted to \r\n. The lines of a hunk keep the \r. File names do not.
  • The only options are the ones on this page. timeout, callback, comparator, fuzzFactor and the ignore* options are not supported.