Programming Search⌘K

Taskcore

Diff two texts

Also called compare two files line by line, line diff, edit script of two files, shortest edit script, diff with a longest common subsequence.

Read two UTF-8 files, split each into lines, and return a shortest edit script of kept, deleted and added lines, made from a longest common subsequence of the lines.

Task

Compare two text files line by line, and show how to change the lines of the first file into the lines of the second. The POSIX diff utility writes a list of such changes, and POSIX says: "This list should be minimal. No output shall be produced if the files are identical."1

The list of changes is an edit script. In this task, the script has one line for each line of the two files that it uses. The task needs rules for what a line is, when two lines are equal, and which script to give. This page uses these rules:

  • A line ends at LF. POSIX defines a line as "A sequence of zero or more non- characters plus a terminating character."2 The LF is not part of the line. A CR before the LF stays in the line, so a CRLF and a LF are two different lines.
  • A last line with no LF is a line too. POSIX calls it an incomplete line: "A sequence of one or more non- characters at the end of the file."2 This page compares it as a full line, so the texts a, LF, b and a, LF, b, LF have the same lines.
  • Two lines are equal if their bytes are equal. The solutions do not ignore case, do not remove spaces, and do not normalize Unicode text.
  • The script is a shortest script. The lines that stay are a longest common subsequence (LCS) of the two lists of lines. An LCS is a longest list of lines that are in the two files in the same order, but not always next to each other. So the script has the smallest number of lines that go and lines that come.
  • Each line of the script is a mark and a line. The mark is a space for a line that stays, - for a line of the old file that goes, and + for a line of the new file that comes. Each line of the script ends with an LF. Two empty files give an empty script.
  • Ties have a fixed order. Many scripts can be equally short. The script starts at the first line of each file. If the next lines of the two files are equal, the line stays. If a - and a + give equally short scripts, the - comes first.

For example, the old file has the lines a, b, c, and the new file has the lines a, c, d. The LCS is a, c, and the script is:

 a
-b
 c
+d

If a file does not exist, the solution reports an error.

Solutions

All the solutions use the same method, which is dynamic programming on a table of LCS lengths. The steps:

  1. Split each text into a list of lines: a has n lines and b has m lines. A final LF does not start a new line.
  2. Make a table of (n+1) × (m+1) numbers. The cell (i, j) holds the length of an LCS of the lines from a[i] to the end of a and the lines from b[j] to the end of b. Row n and column m hold 0.
  3. Fill the table from the last row and the last column back to the cell (0, 0). If a[i] and b[j] are equal, the cell is 1 more than the cell (i+1, j+1). If not, the cell is the larger of the cells (i+1, j) and (i, j+1).
  4. Start at the cell (0, 0). If a[i] and b[j] are equal, write a space and the line, and go to the cell (i+1, j+1). If not, and the cell (i+1, j) is not smaller than the cell (i, j+1), write - and a[i], and go to the cell (i+1, j). If not, write + and b[j], and go to the cell (i, j+1).
  5. When one list has no more lines, write - and each line that is left in a, and then + and each line that is left in b.

Each cell holds the length for the ends of the two lists, so step 4 can start at the first lines, and the script comes out in order. The table is one flat array, and the cell (i, j) is at the index i × (m+1) + j. The time and the memory grow with n × m.

  • Python. open(path, 'rb') reads the bytes of each file, and decode('utf-8') makes a str. The solution does not use text mode, because text mode changes CRLF to LF (see the pitfalls). text.split('\n') gives an empty last part when the text ends with an LF, and split_lines removes it. The table is a list of int. A missing file gives FileNotFoundError.
  • JavaScript and TypeScript (Node.js). readFileSync(path, 'utf8') reads each file as a string. split('\n') and the same removal of the empty last part give the lines. The table is an Int32Array. A missing file gives an error with the code ENOENT. The TypeScript file adds types only.
  • Java. Files.readString(path) reads each file as UTF-8 text. A loop with indexOf('\n', start) splits the text, and it does not add an empty line after a final LF. equals compares two lines, and the table is an int[]. A missing file gives NoSuchFileException.
  • C#. File.ReadAllText(path, Encoding.UTF8) reads each file. Split('\n') and the removal of the empty last part give the lines. string.Equals with StringComparison.Ordinal compares two lines, and the table is an int[]. A missing file gives FileNotFoundException.
  • Go. os.ReadFile reads the bytes of each file. strings.Split "slices s into all substrings separated by sep and returns a slice of the substrings between those separators."3 So a text that ends with an LF gives an empty last part, and SplitLines removes it. The table is a []int32, and a strings.Builder collects the script. A missing file gives an error that matches fs.ErrNotExist.
  • Rust. fs::read_to_string reads each file. split_terminator('\n') gives the lines with no extra step. It works as split does, except that "the trailing substring is skipped if empty."4 The table is a Vec<u32>. A missing file gives an io::Error of the kind NotFound.
  • C. diff_files reads each file in binary mode with fread. split_lines makes an array of struct line, which holds a pointer into the text and a length, so the lines are not copied. memcmp compares two lines of the same length. The table is an array of size_t from calloc, and the code makes sure that (n+1) × (m+1) cells fit in a size_t first. Each line of the two files is in the script once, so the result needs the bytes of the two texts, plus a mark and an LF for each line. diff_lines and diff_files return a new string that the caller frees, or NULL with errno set to the error of fopen, to EIO, or to ENOMEM.
  • C++. diff_files reads each file with a binary std::ifstream. split_lines gives a std::vector<std::string_view> that points into the text, and the table is a std::vector<std::size_t>. The result is a std::expected<std::string, DiffError> (C++23), and the errors are cannot_open and read_failed.
  • Bash. mapfile -t a reads the lines of its standard input, here the first file, into the array a. The -t option will "Remove a trailing delim (default newline) from each line read."5 A last line with no LF is also read, and a CR stays in its line. The table is an indexed array, and the code reads an element that is not set as 0. The function prints the script with one printf for all its lines. If a file cannot be read, the function prints an error message on the standard error and returns 1. The two loops run n × m steps in the shell, so this solution is slow for large files.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl, with the files in fixtures/.

  • simple: a, b, c and a, c, d give ' a\n-b\n c\n+d\n'.
  • change-a-line: a line that changes is a - and a +: ' one\n-two\n+2\n three\n'.
  • identical: each line stays: ' a\n b\n'. POSIX diff writes nothing for two equal files, but this script still has the lines.
  • lines-of-a-poem: a line changes, and a line comes at the end.
  • both-empty, old-empty, new-empty: two empty files give ''. An empty old file gives a + for each line, and an empty new file gives a - for each line.
  • all-different: a, b and c, d give '-a\n-b\n+c\n+d\n'. The - lines come first.
  • insert-at-start, delete-at-end: '+a\n b\n c\n' and ' a\n b\n-c\n'.
  • swap: a, b and b, a give '-a\n b\n+a\n'. The script '+b\n a\n-b\n' is equally short, but the tie rule puts the - first.
  • repeated-lines: a, a, b and a, b, b give ' a\n-a\n b\n+b\n'.
  • empty-line: a, an empty line, b and a, b give ' a\n-\n b\n'. An empty line that goes is a - alone.
  • no-final-newline: 'a\nb' and 'a\nb\n' give ' a\n b\n'.
  • crlf: 'a\r\nb\n' and 'a\nb\n' give '-a\r\n+a\n b\n'. The CR stays in the line.
  • trailing-space: 'a \nb\n' and 'a\nb\n' give '-a \n+a\n b\n'.
  • normalization: U+00E9, and e with U+0301, give a - and a +. The two lines look the same, but their bytes are not equal.

The tests also compare two texts of 1000 lines, the numbers 0 to 999. In the new text, the 10 lines 50, 150, and so on to 950 change from n to xn. The script must have 1010 lines, its lines 50 to 52 must be ' 49', '-50' and '+x50', and its last line must be ' 999'. The Bash test uses 100 lines and 10 changes, and the script must have 110 lines. The case in cases/errors.jsonl must give the error not-found. The toolchain does not load that file yet, so each test file holds the case by name.

Pitfalls

  • The table needs n × m memory. For two files of 10000 lines each, the table has 10001 × 10001 = 100020001 cells. With 4 bytes for each cell, that is about 400 MB. GNU diff uses another method. Its manual says that the basic algorithm is the one that Eugene W. Myers describes in the 1986 paper An O(ND) Difference Algorithm and its Variations, and also: "Unless the --minimal option is used, diff uses a heuristic by Paul Eggert that limits the cost to O(N^1.5 log N) at the price of producing suboptimal output for large inputs with many differences."6 So the default script of GNU diff is not always a shortest script.
  • A shortest script is not always the clearest. The Python difflib documentation says that "minimal diffs are often counter-intuitive for humans, because they synch up anywhere possible, sometimes at accidental matches 100 pages apart."7 Git has a choice of algorithms. Its default, myers, is "The basic greedy diff algorithm. Currently, this is the default."8 With --minimal, Git will "Spend extra time to make sure the smallest possible diff is produced."8 The patience and histogram algorithms are also available. Two tools can also give two different scripts of the same length. For the swap case, difflib keeps the line a, and this page keeps the line b:
import difflib

for line in difflib.ndiff(["a", "b"], ["b", "a"]):
    print(repr(line))
Output
'+ b'
'  a'
'- b'
  • An incomplete line is not a full line for diff. This page compares a last line with no LF as a full line, so the script does not show that the LF is missing. GNU diff does not do this: "Incomplete lines do not match full lines unless differences in white space are ignored".9 It writes a line that starts with a backslash after the incomplete line. The exit status 1 means that "Differences were found and all differences were successfully output."1 A script that must rebuild the new file byte for byte needs such a mark:
dir=$(mktemp -d)
printf 'a\nb' >"$dir/old.txt"
printf 'a\nb\n' >"$dir/new.txt"
diff "$dir/old.txt" "$dir/new.txt"
echo "status $?"
rm -r "$dir"
Output
2c2
< b
\ No newline at end of file
---
> b
status 1
  • Text mode can remove the CR. In Python text mode with the default newline, a line in the input can end in '\n', '\r' or '\r\n', and the documentation says that "these are translated into" '\n' before the caller gets the line.10 So a CRLF file and an LF file seem to have the same lines, and the script does not show the change. With newline='', the line ends stay. The solutions read the bytes, or a mode that does not change them:
import io


def lines(data, newline):
    f = io.TextIOWrapper(io.BytesIO(data), encoding="utf-8", newline=newline)
    return f.read().split("\n")


old, new = b"a\r\nb\n", b"a\nb\n"
print(lines(old, None) == lines(new, None))
print(lines(old, "") == lines(new, ""))
Output
True
False
  • Lines that look the same can be different. A CR, a space at the end of a line, or another Unicode form of the same text makes two lines different, and the script shows a - and a + for them. To ignore such changes, compare a key for each line, for example the line with no spaces at the end, but write the line itself in the script.

Code

The build runs the native tests of each language in a pinned toolchain.

diff_two_texts.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/diff-two-texts/.

"""Compares two texts line by line, and gives a shortest edit script."""

from os import PathLike


def split_lines(text: str) -> list[str]:
    """Splits text at each LF. A final LF does not start a new line."""
    lines = text.split("\n")
    # "a\n".split("\n") is ["a", ""], and "".split("\n") is [""].
    if lines[-1] == "":
        lines.pop()
    return lines


def diff_lines(old: str, new: str) -> str:
    """Returns the edit script that changes the lines of old into the lines of new.

    Each line of the result is a space and a line that stays, a - and a line
    of old that goes, or a + and a line of new that comes, with an LF at the
    end. The script has the smallest number of - and + lines. When two
    scripts are equally short, a - comes before a +.
    """
    a, b = split_lines(old), split_lines(new)
    n, m = len(a), len(b)
    w = m + 1
    # lcs[i * w + j] is the length of a longest common subsequence of a[i:]
    # and b[j:]. Row n and column m stay 0.
    lcs = [0] * ((n + 1) * w)
    for i in range(n - 1, -1, -1):
        for j in range(m - 1, -1, -1):
            if a[i] == b[j]:
                lcs[i * w + j] = lcs[(i + 1) * w + j + 1] + 1
            else:
                lcs[i * w + j] = max(lcs[(i + 1) * w + j], lcs[i * w + j + 1])
    out = []
    i = j = 0
    while i < n and j < m:
        if a[i] == b[j]:
            out.append(" " + a[i])
            i += 1
            j += 1
        elif lcs[(i + 1) * w + j] >= lcs[i * w + j + 1]:
            out.append("-" + a[i])
            i += 1
        else:
            out.append("+" + b[j])
            j += 1
    out.extend("-" + line for line in a[i:])
    out.extend("+" + line for line in b[j:])
    return "".join(line + "\n" for line in out)


def diff_files(old_path: str | PathLike[str], new_path: str | PathLike[str]) -> str:
    """Returns diff_lines of the two UTF-8 files.

    Raises FileNotFoundError if a file does not exist, and UnicodeDecodeError
    if a file is not valid UTF-8.
    """
    # Binary mode, then decode: a text mode file would change CRLF to LF.
    with open(old_path, "rb") as f:
        old = f.read().decode("utf-8")
    with open(new_path, "rb") as f:
        new = f.read().decode("utf-8")
    return diff_lines(old, new)
test_diff_two_texts.py 57 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/diff-two-texts/.

import pytest

from diff_two_texts import diff_files, diff_lines

# name: (the old text, the new text, the edit script)
CASES = {
    "simple": ("a\nb\nc\n", "a\nc\nd\n", " a\n-b\n c\n+d\n"),
    "change-a-line": ("one\ntwo\nthree\n", "one\n2\nthree\n", " one\n-two\n+2\n three\n"),
    "identical": ("a\nb\n", "a\nb\n", " a\n b\n"),
    "lines-of-a-poem": ("The cat sat\non the mat.\nIt was flat.\n", "The cat sat\non the hat.\nIt was flat.\nThe end.\n", " The cat sat\n-on the mat.\n+on the hat.\n It was flat.\n+The end.\n"),
    "both-empty": ("", "", ""),
    "old-empty": ("", "a\nb\n", "+a\n+b\n"),
    "new-empty": ("a\nb\n", "", "-a\n-b\n"),
    "all-different": ("a\nb\n", "c\nd\n", "-a\n-b\n+c\n+d\n"),
    "insert-at-start": ("b\nc\n", "a\nb\nc\n", "+a\n b\n c\n"),
    "delete-at-end": ("a\nb\nc\n", "a\nb\n", " a\n b\n-c\n"),
    "swap": ("a\nb\n", "b\na\n", "-a\n b\n+a\n"),
    "repeated-lines": ("a\na\nb\n", "a\nb\nb\n", " a\n-a\n b\n+b\n"),
    "empty-line": ("a\n\nb\n", "a\nb\n", " a\n-\n b\n"),
    "no-final-newline": ("a\nb", "a\nb\n", " a\n b\n"),
    "crlf": ("a\r\nb\n", "a\nb\n", "-a\r\n+a\n b\n"),
    "trailing-space": ("a \nb\n", "a\nb\n", "-a \n+a\n b\n"),
    "normalization": ("caf\u00e9\n", "cafe\u0301\n", "-caf\u00e9\n+cafe\u0301\n"),
}


@pytest.mark.parametrize("name", CASES)
def test_diff_lines(name):
    old, new, want = CASES[name]
    assert diff_lines(old, new) == want


def test_many_lines():
    # 1000 lines, and 10 of them change.
    old = "".join(f"{i}\n" for i in range(1000))
    new = "".join((f"x{i}" if i % 100 == 50 else str(i)) + "\n" for i in range(1000))
    lines = diff_lines(old, new).splitlines()
    assert len(lines) == 1010
    assert lines[49:52] == [" 49", "-50", "+x50"]
    assert lines[-1] == " 999"


def test_diff_files(tmp_path):
    old, new, want = CASES["crlf"]
    # write_bytes keeps the CR, and write_text could change each LF.
    (tmp_path / "old.txt").write_bytes(old.encode())
    (tmp_path / "new.txt").write_bytes(new.encode())
    assert diff_files(tmp_path / "old.txt", tmp_path / "new.txt") == want


def test_not_found(tmp_path):
    (tmp_path / "new.txt").write_bytes(b"a\n")
    with pytest.raises(FileNotFoundError):
        diff_files(tmp_path / "missing.txt", tmp_path / "new.txt")
diff_two_texts.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/diff-two-texts/.

#include "diff_two_texts.hpp"

#include <algorithm>
#include <fstream>
#include <iterator>

std::vector<std::string_view> split_lines(std::string_view text) {
    std::vector<std::string_view> lines;
    while (!text.empty()) {
        std::size_t lf = text.find('\n');
        lines.push_back(text.substr(0, lf));
        text.remove_prefix(lf == std::string_view::npos ? text.size() : lf + 1);
    }
    return lines;
}

std::string diff_lines(std::string_view old_text, std::string_view new_text) {
    const auto a = split_lines(old_text);
    const auto b = split_lines(new_text);
    const std::size_t n = a.size(), m = b.size(), w = m + 1;
    // lcs[i * w + j] is the length of a longest common subsequence of the
    // lines from a[i] and from b[j]. Row n and column m stay 0.
    std::vector<std::size_t> lcs((n + 1) * w);
    for (std::size_t i = n; i-- > 0;) {
        for (std::size_t j = m; j-- > 0;) {
            lcs[i * w + j] =
                a[i] == b[j] ? lcs[(i + 1) * w + j + 1] + 1 : std::max(lcs[(i + 1) * w + j], lcs[i * w + j + 1]);
        }
    }
    std::string out;
    auto line = [&out](char mark, std::string_view s) {
        out += mark;
        out += s;
        out += '\n';
    };
    std::size_t i = 0, j = 0;
    while (i < n && j < m) {
        if (a[i] == b[j]) {
            line(' ', a[i]);
            i++;
            j++;
        } else if (lcs[(i + 1) * w + j] >= lcs[i * w + j + 1]) {
            line('-', a[i++]);
        } else {
            line('+', b[j++]);
        }
    }
    for (; i < n; i++) {
        line('-', a[i]);
    }
    for (; j < m; j++) {
        line('+', b[j]);
    }
    return out;
}

// Reads the whole file in binary mode, so that each CR stays.
static std::expected<std::string, DiffError> read_file(const std::filesystem::path& path) {
    std::ifstream in(path, std::ios::binary);
    if (!in) {
        return std::unexpected(DiffError::cannot_open);
    }
    std::string data{std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
    if (in.bad()) {
        return std::unexpected(DiffError::read_failed);
    }
    return data;
}

std::expected<std::string, DiffError> diff_files(const std::filesystem::path& old_path,
                                                 const std::filesystem::path& new_path) {
    auto old_text = read_file(old_path);
    if (!old_text) {
        return std::unexpected(old_text.error());
    }
    auto new_text = read_file(new_path);
    if (!new_text) {
        return std::unexpected(new_text.error());
    }
    return diff_lines(*old_text, *new_text);
}
diff_two_texts.hpp 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/diff-two-texts/.
// since: C++23 (std::expected)

#pragma once

#include <expected>
#include <filesystem>
#include <string>
#include <string_view>
#include <vector>

enum class DiffError { cannot_open, read_failed };

// Splits text at each LF. A final LF does not start a new line.
std::vector<std::string_view> split_lines(std::string_view text);

// Returns the edit script that changes the lines of old_text into the lines of
// new_text. Each line of the result is a space and a line that stays, a - and
// a line of old_text that goes, or a + and a line of new_text that comes, with
// an LF at the end. The script has the smallest number of - and + lines. When
// two scripts are equally short, a - comes before a +.
std::string diff_lines(std::string_view old_text, std::string_view new_text);

// Returns diff_lines of the two files.
std::expected<std::string, DiffError> diff_files(const std::filesystem::path& old_path,
                                                 const std::filesystem::path& new_path);
test_diff_two_texts.cpp 80 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/diff-two-texts/.

#include "diff_two_texts.hpp"

#include <algorithm>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>

#include <unistd.h>  // getpid

struct TestCase {
    const char *name, *old_text, *new_text, *want;
};

static const TestCase cases[] = {
    {"simple", "a\nb\nc\n", "a\nc\nd\n", " a\n-b\n c\n+d\n"},
    {"change-a-line", "one\ntwo\nthree\n", "one\n2\nthree\n", " one\n-two\n+2\n three\n"},
    {"identical", "a\nb\n", "a\nb\n", " a\n b\n"},
    {"lines-of-a-poem", "The cat sat\non the mat.\nIt was flat.\n", "The cat sat\non the hat.\nIt was flat.\nThe end.\n", " The cat sat\n-on the mat.\n+on the hat.\n It was flat.\n+The end.\n"},
    {"both-empty", "", "", ""},
    {"old-empty", "", "a\nb\n", "+a\n+b\n"},
    {"new-empty", "a\nb\n", "", "-a\n-b\n"},
    {"all-different", "a\nb\n", "c\nd\n", "-a\n-b\n+c\n+d\n"},
    {"insert-at-start", "b\nc\n", "a\nb\nc\n", "+a\n b\n c\n"},
    {"delete-at-end", "a\nb\nc\n", "a\nb\n", " a\n b\n-c\n"},
    {"swap", "a\nb\n", "b\na\n", "-a\n b\n+a\n"},
    {"repeated-lines", "a\na\nb\n", "a\nb\nb\n", " a\n-a\n b\n+b\n"},
    {"empty-line", "a\n\nb\n", "a\nb\n", " a\n-\n b\n"},
    {"no-final-newline", "a\nb", "a\nb\n", " a\n b\n"},
    {"crlf", "a\r\nb\n", "a\nb\n", "-a\r\n+a\n b\n"},
    {"trailing-space", "a \nb\n", "a\nb\n", "-a \n+a\n b\n"},
    {"normalization", "caf\303\251\n", "cafe\314\201\n", "-caf\303\251\n+cafe\314\201\n"},
};

static void write_file(const std::filesystem::path& path, const std::string& text) {
    std::ofstream(path, std::ios::binary) << text;
}

int main() {
    int failures = 0;
    for (const auto& c : cases) {
        if (std::string got = diff_lines(c.old_text, c.new_text); got != c.want) {
            std::cerr << "FAIL " << c.name << ": got \"" << got << "\"\n";
            failures++;
        }
    }

    // 1000 lines, and 10 of them change.
    std::string old_text, new_text;
    for (int i = 0; i < 1000; i++) {
        old_text += std::to_string(i) + "\n";
        new_text += (i % 100 == 50 ? "x" : "") + std::to_string(i) + "\n";
    }
    std::string got = diff_lines(old_text, new_text);
    if (std::ranges::count(got, '\n') != 1010 || !got.contains(" 49\n-50\n+x50\n 51\n") || !got.ends_with("\n 999\n")) {
        std::cerr << "FAIL many-lines\n";
        failures++;
    }

    const auto dir = std::filesystem::temp_directory_path() / ("diff-two-texts-cpp-" + std::to_string(::getpid()));
    std::filesystem::create_directories(dir);
    write_file(dir / "old.txt", "a\r\nb\n");
    write_file(dir / "new.txt", "a\nb\n");
    if (auto r = diff_files(dir / "old.txt", dir / "new.txt"); !r || *r != "-a\r\n+a\n b\n") {
        std::cerr << "FAIL diff-files\n";
        failures++;
    }
    if (auto r = diff_files(dir / "missing.txt", dir / "new.txt"); r || r.error() != DiffError::cannot_open) {
        std::cerr << "FAIL not-found\n";
        failures++;
    }
    std::filesystem::remove_all(dir);
    if (failures == 0) {
        std::cout << "ok\n";
    }
    return failures == 0 ? 0 : 1;
}
DiffTexts.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/diff-two-texts/.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

/** Compares two texts line by line. */
public final class DiffTexts {
  private DiffTexts() {}

  /** Splits text at each LF. A final LF does not start a new line. */
  public static List<String> splitLines(String text) {
    List<String> lines = new ArrayList<>();
    int start = 0;
    while (start < text.length()) {
      int end = text.indexOf('\n', start);
      if (end < 0) {
        end = text.length();
      }
      lines.add(text.substring(start, end));
      start = end + 1;
    }
    return lines;
  }

  /**
   * Returns the edit script that changes the lines of oldText into the lines of newText. Each
   * line of the result is a space and a line that stays, a - and a line of oldText that goes, or
   * a + and a line of newText that comes, with an LF at the end. The script has the smallest
   * number of - and + lines. When two scripts are equally short, a - comes before a +.
   */
  public static String lines(String oldText, String newText) {
    List<String> a = splitLines(oldText);
    List<String> b = splitLines(newText);
    int n = a.size();
    int m = b.size();
    int w = m + 1;
    // lcs[i * w + j] is the length of a longest common subsequence of the lines from a[i] and
    // from b[j]. Row n and column m stay 0.
    int[] lcs = new int[Math.multiplyExact(n + 1, w)];
    for (int i = n - 1; i >= 0; i--) {
      for (int j = m - 1; j >= 0; j--) {
        lcs[i * w + j] =
            a.get(i).equals(b.get(j))
                ? lcs[(i + 1) * w + j + 1] + 1
                : Math.max(lcs[(i + 1) * w + j], lcs[i * w + j + 1]);
      }
    }
    StringBuilder out = new StringBuilder();
    int i = 0;
    int j = 0;
    while (i < n && j < m) {
      if (a.get(i).equals(b.get(j))) {
        out.append(' ').append(a.get(i++)).append('\n');
        j++;
      } else if (lcs[(i + 1) * w + j] >= lcs[i * w + j + 1]) {
        out.append('-').append(a.get(i++)).append('\n');
      } else {
        out.append('+').append(b.get(j++)).append('\n');
      }
    }
    while (i < n) {
      out.append('-').append(a.get(i++)).append('\n');
    }
    while (j < m) {
      out.append('+').append(b.get(j++)).append('\n');
    }
    return out.toString();
  }

  /**
   * Returns {@link #lines} of the two UTF-8 files.
   *
   * @throws java.nio.file.NoSuchFileException if a file does not exist
   * @throws java.nio.charset.MalformedInputException if a file is not valid UTF-8
   */
  public static String files(Path oldPath, Path newPath) throws IOException {
    return lines(Files.readString(oldPath), Files.readString(newPath));
  }
}
DiffTextsTest.java 80 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/diff-two-texts/.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class DiffTextsTest {
  @TempDir Path dir;

  // name, the old text, the new text, the edit script
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("simple", "a\nb\nc\n", "a\nc\nd\n", " a\n-b\n c\n+d\n"),
        Arguments.of("change-a-line", "one\ntwo\nthree\n", "one\n2\nthree\n", " one\n-two\n+2\n three\n"),
        Arguments.of("identical", "a\nb\n", "a\nb\n", " a\n b\n"),
        Arguments.of("lines-of-a-poem", "The cat sat\non the mat.\nIt was flat.\n", "The cat sat\non the hat.\nIt was flat.\nThe end.\n", " The cat sat\n-on the mat.\n+on the hat.\n It was flat.\n+The end.\n"),
        Arguments.of("both-empty", "", "", ""),
        Arguments.of("old-empty", "", "a\nb\n", "+a\n+b\n"),
        Arguments.of("new-empty", "a\nb\n", "", "-a\n-b\n"),
        Arguments.of("all-different", "a\nb\n", "c\nd\n", "-a\n-b\n+c\n+d\n"),
        Arguments.of("insert-at-start", "b\nc\n", "a\nb\nc\n", "+a\n b\n c\n"),
        Arguments.of("delete-at-end", "a\nb\nc\n", "a\nb\n", " a\n b\n-c\n"),
        Arguments.of("swap", "a\nb\n", "b\na\n", "-a\n b\n+a\n"),
        Arguments.of("repeated-lines", "a\na\nb\n", "a\nb\nb\n", " a\n-a\n b\n+b\n"),
        Arguments.of("empty-line", "a\n\nb\n", "a\nb\n", " a\n-\n b\n"),
        Arguments.of("no-final-newline", "a\nb", "a\nb\n", " a\n b\n"),
        Arguments.of("crlf", "a\r\nb\n", "a\nb\n", "-a\r\n+a\n b\n"),
        Arguments.of("trailing-space", "a \nb\n", "a\nb\n", "-a \n+a\n b\n"),
        Arguments.of("normalization", "caf\u00e9\n", "cafe\u0301\n", "-caf\u00e9\n+cafe\u0301\n"));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void lines(String name, String oldText, String newText, String want) {
    assertEquals(want, DiffTexts.lines(oldText, newText), name);
  }

  @Test
  void manyLines() {
    // 1000 lines, and 10 of them change.
    StringBuilder oldText = new StringBuilder();
    StringBuilder newText = new StringBuilder();
    for (int i = 0; i < 1000; i++) {
      oldText.append(i).append('\n');
      newText.append(i % 100 == 50 ? "x" + i : Integer.toString(i)).append('\n');
    }
    List<String> lines = DiffTexts.splitLines(DiffTexts.lines(oldText.toString(), newText.toString()));
    assertEquals(1010, lines.size());
    assertEquals(List.of(" 49", "-50", "+x50"), lines.subList(49, 52));
    assertEquals(" 999", lines.get(1009));
  }

  @Test
  void files() throws IOException {
    Files.writeString(dir.resolve("old.txt"), "a\r\nb\n", StandardCharsets.UTF_8);
    Files.writeString(dir.resolve("new.txt"), "a\nb\n", StandardCharsets.UTF_8);
    assertEquals("-a\r\n+a\n b\n", DiffTexts.files(dir.resolve("old.txt"), dir.resolve("new.txt")));
  }

  @Test
  void notFound() throws IOException {
    Files.writeString(dir.resolve("new.txt"), "a\n", StandardCharsets.UTF_8);
    assertThrows(
        NoSuchFileException.class,
        () -> DiffTexts.files(dir.resolve("missing.txt"), dir.resolve("new.txt")));
  }
}
diff_two_texts.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/diff-two-texts/.

#include "diff_two_texts.h"

#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct line {
    const char *text;  // the bytes of the line, in the text; not ended by a NUL
    size_t len;        // the number of bytes, with no LF
};

// split_lines splits text at each LF into a new array, and sets *count. A
// final LF does not start a new line. It returns NULL for an empty text too,
// with *count 0, so the caller checks errno only if *count is not 0.
static struct line *split_lines(const char *text, size_t *count) {
    size_t n = 0;
    for (const char *p = text; *p != '\0'; n++) {
        const char *lf = strchr(p, '\n');
        p = lf != NULL ? lf + 1 : p + strlen(p);
    }
    *count = n;
    if (n == 0) {
        return NULL;
    }
    struct line *lines = malloc(n * sizeof *lines);
    if (lines == NULL) {
        return NULL;
    }
    size_t i = 0;
    for (const char *p = text; *p != '\0'; i++) {
        const char *lf = strchr(p, '\n');
        size_t len = lf != NULL ? (size_t)(lf - p) : strlen(p);
        lines[i] = (struct line){p, len};
        p += lf != NULL ? len + 1 : len;
    }
    return lines;
}

static int equal(struct line x, struct line y) {
    return x.len == y.len && memcmp(x.text, y.text, x.len) == 0;
}

// put writes the mark, the line and an LF at *out, and moves *out after them.
static void put(char **out, char mark, struct line l) {
    *(*out)++ = mark;
    memcpy(*out, l.text, l.len);
    *out += l.len;
    *(*out)++ = '\n';
}

char *diff_lines(const char *old_text, const char *new_text) {
    size_t n, m;
    struct line *a = split_lines(old_text, &n);
    if (a == NULL && n > 0) {
        errno = ENOMEM;
        return NULL;
    }
    struct line *b = split_lines(new_text, &m);
    if (b == NULL && m > 0) {
        free(a);
        errno = ENOMEM;
        return NULL;
    }
    size_t w = m + 1;
    // lcs[i * w + j] is the length of a longest common subsequence of the
    // lines from a[i] and from b[j]. Row n and column m stay 0.
    size_t *lcs = NULL;
    if (n + 1 <= SIZE_MAX / sizeof *lcs / w) {
        lcs = calloc((n + 1) * w, sizeof *lcs);
    }
    // Each line of the script is one line of a or b, with a mark and an LF.
    char *result = malloc(strlen(old_text) + strlen(new_text) + 2 * (n + m) + 1);
    if (lcs == NULL || result == NULL) {
        free(a);
        free(b);
        free(lcs);
        free(result);
        errno = ENOMEM;
        return NULL;
    }
    for (size_t i = n; i-- > 0;) {
        for (size_t j = m; j-- > 0;) {
            if (equal(a[i], b[j])) {
                lcs[i * w + j] = lcs[(i + 1) * w + j + 1] + 1;
            } else {
                size_t down = lcs[(i + 1) * w + j], right = lcs[i * w + j + 1];
                lcs[i * w + j] = down >= right ? down : right;
            }
        }
    }
    char *out = result;
    size_t i = 0, j = 0;
    while (i < n && j < m) {
        if (equal(a[i], b[j])) {
            put(&out, ' ', a[i]);
            i++;
            j++;
        } else if (lcs[(i + 1) * w + j] >= lcs[i * w + j + 1]) {
            put(&out, '-', a[i++]);
        } else {
            put(&out, '+', b[j++]);
        }
    }
    while (i < n) {
        put(&out, '-', a[i++]);
    }
    while (j < m) {
        put(&out, '+', b[j++]);
    }
    *out = '\0';
    free(a);
    free(b);
    free(lcs);
    return result;
}

// read_file reads the whole file at path into a new string that ends with a
// NUL. On an error it returns NULL and sets errno.
static char *read_file(const char *path) {
    FILE *f = fopen(path, "rb");
    if (f == NULL) {
        return NULL;
    }
    size_t cap = 4096, used = 0;
    char *data = malloc(cap);
    for (;;) {
        if (data == NULL) {
            fclose(f);
            errno = ENOMEM;
            return NULL;
        }
        used += fread(data + used, 1, cap - used - 1, f);
        if (used < cap - 1) {
            break;
        }
        char *bigger = cap <= SIZE_MAX / 2 ? realloc(data, cap * 2) : NULL;
        if (bigger == NULL) {
            free(data);
        }
        data = bigger;
        cap *= 2;
    }
    int failed = ferror(f);
    fclose(f);
    if (failed) {
        free(data);
        errno = EIO;
        return NULL;
    }
    data[used] = '\0';
    return data;
}

char *diff_files(const char *old_path, const char *new_path) {
    char *old_text = read_file(old_path);
    if (old_text == NULL) {
        return NULL;
    }
    char *new_text = read_file(new_path);
    if (new_text == NULL) {
        int saved = errno;
        free(old_text);
        errno = saved;
        return NULL;
    }
    char *result = diff_lines(old_text, new_text);
    int saved = errno;
    free(old_text);
    free(new_text);
    errno = saved;
    return result;
}
diff_two_texts.h 22 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/diff-two-texts/.

#ifndef DIFF_TWO_TEXTS_H
#define DIFF_TWO_TEXTS_H

// diff_lines returns the edit script that changes the lines of old_text into
// the lines of new_text, as a new string. Each line of the result is a space
// and a line that stays, a - and a line of old_text that goes, or a + and a
// line of new_text that comes, with an LF at the end. The script has the
// smallest number of - and + lines. When two scripts are equally short, a -
// comes before a +. A line ends at LF, and a final LF does not start a new
// line. Free the result with free. On an error it returns NULL and sets errno
// to ENOMEM.
char *diff_lines(const char *old_text, const char *new_text);

// diff_files returns diff_lines of the two files at old_path and new_path. On
// an error it returns NULL and sets errno: the error of fopen, EIO for a read
// error, or ENOMEM.
char *diff_files(const char *old_path, const char *new_path);

#endif
test_diff_two_texts.c 112 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/diff-two-texts/.

// mkdtemp and rmdir are POSIX functions.
#define _POSIX_C_SOURCE 200809L

#include "diff_two_texts.h"

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

struct test_case {
    const char *name, *old_text, *new_text, *want;
};

static const struct test_case cases[] = {
    {"simple", "a\nb\nc\n", "a\nc\nd\n", " a\n-b\n c\n+d\n"},
    {"change-a-line", "one\ntwo\nthree\n", "one\n2\nthree\n", " one\n-two\n+2\n three\n"},
    {"identical", "a\nb\n", "a\nb\n", " a\n b\n"},
    {"lines-of-a-poem", "The cat sat\non the mat.\nIt was flat.\n", "The cat sat\non the hat.\nIt was flat.\nThe end.\n", " The cat sat\n-on the mat.\n+on the hat.\n It was flat.\n+The end.\n"},
    {"both-empty", "", "", ""},
    {"old-empty", "", "a\nb\n", "+a\n+b\n"},
    {"new-empty", "a\nb\n", "", "-a\n-b\n"},
    {"all-different", "a\nb\n", "c\nd\n", "-a\n-b\n+c\n+d\n"},
    {"insert-at-start", "b\nc\n", "a\nb\nc\n", "+a\n b\n c\n"},
    {"delete-at-end", "a\nb\nc\n", "a\nb\n", " a\n b\n-c\n"},
    {"swap", "a\nb\n", "b\na\n", "-a\n b\n+a\n"},
    {"repeated-lines", "a\na\nb\n", "a\nb\nb\n", " a\n-a\n b\n+b\n"},
    {"empty-line", "a\n\nb\n", "a\nb\n", " a\n-\n b\n"},
    {"no-final-newline", "a\nb", "a\nb\n", " a\n b\n"},
    {"crlf", "a\r\nb\n", "a\nb\n", "-a\r\n+a\n b\n"},
    {"trailing-space", "a \nb\n", "a\nb\n", "-a \n+a\n b\n"},
    {"normalization", "caf\303\251\n", "cafe\314\201\n", "-caf\303\251\n+cafe\314\201\n"},
};

// write_file writes text to the file at path, and returns 0 if it can.
static int write_file(const char *path, const char *text) {
    FILE *f = fopen(path, "wb");
    if (f == NULL) {
        return -1;
    }
    size_t len = strlen(text);
    int ok = fwrite(text, 1, len, f) == len;
    return fclose(f) == 0 && ok ? 0 : -1;
}

int main(void) {
    int failures = 0;
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        const struct test_case *c = &cases[i];
        char *got = diff_lines(c->old_text, c->new_text);
        if (got == NULL || strcmp(got, c->want) != 0) {
            fprintf(stderr, "FAIL %s: got \"%s\"\n", c->name, got != NULL ? got : "(null)");
            failures++;
        }
        free(got);
    }

    // 1000 lines, and 10 of them change. Each line has at most 5 bytes.
    char *old_text = malloc(1000 * 5 + 1), *new_text = malloc(1000 * 5 + 1);
    size_t old_len = 0, new_len = 0;
    for (int i = 0; i < 1000; i++) {
        old_len += (size_t)snprintf(old_text + old_len, 1000 * 5 + 1 - old_len, "%d\n", i);
        new_len += (size_t)snprintf(new_text + new_len, 1000 * 5 + 1 - new_len, i % 100 == 50 ? "x%d\n" : "%d\n", i);
    }
    char *got = diff_lines(old_text, new_text);
    size_t lines = 0;
    for (const char *p = got; p != NULL && *p != '\0'; p++) {
        lines += *p == '\n';
    }
    const char *start = got != NULL ? strstr(got, " 49\n") : NULL;
    if (lines != 1010 || start == NULL || strncmp(start, " 49\n-50\n+x50\n", 13) != 0 ||
        strcmp(got + strlen(got) - 5, " 999\n") != 0) {
        fprintf(stderr, "FAIL many-lines\n");
        failures++;
    }
    free(got);
    free(old_text);
    free(new_text);

    char dir[] = "/tmp/diff-two-texts-XXXXXX";
    if (mkdtemp(dir) == NULL) {
        perror("mkdtemp");
        return 1;
    }
    char old_path[64], new_path[64], missing[64];
    snprintf(old_path, sizeof old_path, "%s/old.txt", dir);
    snprintf(new_path, sizeof new_path, "%s/new.txt", dir);
    snprintf(missing, sizeof missing, "%s/missing.txt", dir);
    got = NULL;
    if (write_file(old_path, "a\r\nb\n") != 0 || write_file(new_path, "a\nb\n") != 0 ||
        (got = diff_files(old_path, new_path)) == NULL || strcmp(got, "-a\r\n+a\n b\n") != 0) {
        fprintf(stderr, "FAIL diff-files\n");
        failures++;
    }
    free(got);
    errno = 0;
    if (diff_files(missing, new_path) != NULL || errno != ENOENT) {
        fprintf(stderr, "FAIL not-found\n");
        failures++;
    }
    remove(old_path);
    remove(new_path);
    rmdir(dir);
    if (failures == 0) {
        printf("ok\n");
    }
    return failures == 0 ? 0 : 1;
}
DiffTexts.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/diff-two-texts/.

using System.Text;

/// <summary>Compares two texts line by line.</summary>
public static class DiffTexts
{
    /// <summary>Splits text at each LF. A final LF does not start a new line.</summary>
    public static List<string> SplitLines(string text)
    {
        var lines = new List<string>(text.Split('\n'));
        // "a\n".Split('\n') is ["a", ""], and "".Split('\n') is [""].
        if (lines[^1].Length == 0)
        {
            lines.RemoveAt(lines.Count - 1);
        }
        return lines;
    }

    /// <summary>
    /// Returns the edit script that changes the lines of oldText into the lines of newText. Each
    /// line of the result is a space and a line that stays, a - and a line of oldText that goes,
    /// or a + and a line of newText that comes, with an LF at the end. The script has the smallest
    /// number of - and + lines. When two scripts are equally short, a - comes before a +.
    /// </summary>
    public static string Lines(string oldText, string newText)
    {
        List<string> a = SplitLines(oldText), b = SplitLines(newText);
        int n = a.Count, m = b.Count, w = m + 1;
        // lcs[i * w + j] is the length of a longest common subsequence of the lines from a[i]
        // and from b[j]. Row n and column m stay 0.
        var lcs = new int[checked((n + 1) * w)];
        for (int i = n - 1; i >= 0; i--)
        {
            for (int j = m - 1; j >= 0; j--)
            {
                lcs[i * w + j] = string.Equals(a[i], b[j], StringComparison.Ordinal)
                    ? lcs[(i + 1) * w + j + 1] + 1
                    : Math.Max(lcs[(i + 1) * w + j], lcs[i * w + j + 1]);
            }
        }
        var output = new StringBuilder();
        void Line(char mark, string s) => output.Append(mark).Append(s).Append('\n');
        int x = 0, y = 0;
        while (x < n && y < m)
        {
            if (string.Equals(a[x], b[y], StringComparison.Ordinal))
            {
                Line(' ', a[x++]);
                y++;
            }
            else if (lcs[(x + 1) * w + y] >= lcs[x * w + y + 1])
            {
                Line('-', a[x++]);
            }
            else
            {
                Line('+', b[y++]);
            }
        }
        while (x < n)
        {
            Line('-', a[x++]);
        }
        while (y < m)
        {
            Line('+', b[y++]);
        }
        return output.ToString();
    }

    /// <summary>Returns <see cref="Lines"/> of the two UTF-8 files.</summary>
    /// <exception cref="FileNotFoundException">A file does not exist.</exception>
    public static string Files(string oldPath, string newPath) =>
        Lines(File.ReadAllText(oldPath, Encoding.UTF8), File.ReadAllText(newPath, Encoding.UTF8));
}
DiffTextsTests.cs 70 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/diff-two-texts/.

using System.Text;
using Xunit;

public sealed class DiffTextsTests : IDisposable
{
    private readonly string dir = Directory.CreateTempSubdirectory("diff-two-texts-").FullName;

    public void Dispose() => Directory.Delete(dir, recursive: true);

    // name, the old text, the new text, the edit script
    public static TheoryData<string, string, string, string> Cases => new()
    {
        { "simple", "a\nb\nc\n", "a\nc\nd\n", " a\n-b\n c\n+d\n" },
        { "change-a-line", "one\ntwo\nthree\n", "one\n2\nthree\n", " one\n-two\n+2\n three\n" },
        { "identical", "a\nb\n", "a\nb\n", " a\n b\n" },
        { "lines-of-a-poem", "The cat sat\non the mat.\nIt was flat.\n", "The cat sat\non the hat.\nIt was flat.\nThe end.\n", " The cat sat\n-on the mat.\n+on the hat.\n It was flat.\n+The end.\n" },
        { "both-empty", "", "", "" },
        { "old-empty", "", "a\nb\n", "+a\n+b\n" },
        { "new-empty", "a\nb\n", "", "-a\n-b\n" },
        { "all-different", "a\nb\n", "c\nd\n", "-a\n-b\n+c\n+d\n" },
        { "insert-at-start", "b\nc\n", "a\nb\nc\n", "+a\n b\n c\n" },
        { "delete-at-end", "a\nb\nc\n", "a\nb\n", " a\n b\n-c\n" },
        { "swap", "a\nb\n", "b\na\n", "-a\n b\n+a\n" },
        { "repeated-lines", "a\na\nb\n", "a\nb\nb\n", " a\n-a\n b\n+b\n" },
        { "empty-line", "a\n\nb\n", "a\nb\n", " a\n-\n b\n" },
        { "no-final-newline", "a\nb", "a\nb\n", " a\n b\n" },
        { "crlf", "a\r\nb\n", "a\nb\n", "-a\r\n+a\n b\n" },
        { "trailing-space", "a \nb\n", "a\nb\n", "-a \n+a\n b\n" },
        { "normalization", "caf\u00e9\n", "cafe\u0301\n", "-caf\u00e9\n+cafe\u0301\n" },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Lines(string name, string oldText, string newText, string want)
    {
        Assert.Equal(want, DiffTexts.Lines(oldText, newText));
        _ = name;
    }

    [Fact]
    public void ManyLines()
    {
        // 1000 lines, and 10 of them change.
        string oldText = string.Concat(Enumerable.Range(0, 1000).Select(i => $"{i}\n"));
        string newText = string.Concat(Enumerable.Range(0, 1000).Select(i => i % 100 == 50 ? $"x{i}\n" : $"{i}\n"));
        List<string> lines = DiffTexts.SplitLines(DiffTexts.Lines(oldText, newText));
        Assert.Equal(1010, lines.Count);
        Assert.Equal(" 49,-50,+x50", string.Join(",", lines.GetRange(49, 3)));
        Assert.Equal(" 999", lines[1009]);
    }

    [Fact]
    public void Files()
    {
        // UTF8Encoding(false) writes no byte order mark.
        File.WriteAllText(Path.Combine(dir, "old.txt"), "a\r\nb\n", new UTF8Encoding(false));
        File.WriteAllText(Path.Combine(dir, "new.txt"), "a\nb\n", new UTF8Encoding(false));
        Assert.Equal("-a\r\n+a\n b\n", DiffTexts.Files(Path.Combine(dir, "old.txt"), Path.Combine(dir, "new.txt")));
    }

    [Fact]
    public void NotFound()
    {
        File.WriteAllText(Path.Combine(dir, "new.txt"), "a\n", new UTF8Encoding(false));
        Assert.Throws<FileNotFoundException>(() => DiffTexts.Files(Path.Combine(dir, "missing.txt"), Path.Combine(dir, "new.txt")));
    }
}
diffTwoTexts.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/diff-two-texts/.

import { readFileSync } from "node:fs";

/** Splits text at each LF. A final LF does not start a new line. */
export function splitLines(text) {
  const lines = text.split("\n");
  // "a\n".split("\n") is ["a", ""], and "".split("\n") is [""].
  if (lines[lines.length - 1] === "") lines.pop();
  return lines;
}

/**
 * Returns the edit script that changes the lines of oldText into the lines of
 * newText. Each line of the result is a space and a line that stays, a - and a
 * line of oldText that goes, or a + and a line of newText that comes, with an
 * LF at the end. The script has the smallest number of - and + lines. When two
 * scripts are equally short, a - comes before a +.
 */
export function diffLines(oldText, newText) {
  const a = splitLines(oldText);
  const b = splitLines(newText);
  const n = a.length;
  const m = b.length;
  const w = m + 1;
  // lcs[i * w + j] is the length of a longest common subsequence of the lines
  // from a[i] and from b[j]. Row n and column m stay 0.
  const lcs = new Int32Array((n + 1) * w);
  for (let i = n - 1; i >= 0; i--) {
    for (let j = m - 1; j >= 0; j--) {
      lcs[i * w + j] =
        a[i] === b[j] ? lcs[(i + 1) * w + j + 1] + 1 : Math.max(lcs[(i + 1) * w + j], lcs[i * w + j + 1]);
    }
  }
  const out = [];
  let i = 0;
  let j = 0;
  while (i < n && j < m) {
    if (a[i] === b[j]) {
      out.push(` ${a[i++]}\n`);
      j++;
    } else if (lcs[(i + 1) * w + j] >= lcs[i * w + j + 1]) {
      out.push(`-${a[i++]}\n`);
    } else {
      out.push(`+${b[j++]}\n`);
    }
  }
  while (i < n) out.push(`-${a[i++]}\n`);
  while (j < m) out.push(`+${b[j++]}\n`);
  return out.join("");
}

/**
 * Returns diffLines of the two UTF-8 files. Throws an error with the code
 * ENOENT if a file does not exist.
 */
export function diffFiles(oldPath, newPath) {
  return diffLines(readFileSync(oldPath, "utf8"), readFileSync(newPath, "utf8"));
}
diffTwoTexts.test.js 63 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/diff-two-texts/.

import assert from "node:assert/strict";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, test } from "node:test";

import { diffFiles, diffLines } from "./diffTwoTexts.js";

// name: [the old text, the new text, the edit script]
const CASES = {
  "simple": ["a\nb\nc\n", "a\nc\nd\n", " a\n-b\n c\n+d\n"],
  "change-a-line": ["one\ntwo\nthree\n", "one\n2\nthree\n", " one\n-two\n+2\n three\n"],
  "identical": ["a\nb\n", "a\nb\n", " a\n b\n"],
  "lines-of-a-poem": ["The cat sat\non the mat.\nIt was flat.\n", "The cat sat\non the hat.\nIt was flat.\nThe end.\n", " The cat sat\n-on the mat.\n+on the hat.\n It was flat.\n+The end.\n"],
  "both-empty": ["", "", ""],
  "old-empty": ["", "a\nb\n", "+a\n+b\n"],
  "new-empty": ["a\nb\n", "", "-a\n-b\n"],
  "all-different": ["a\nb\n", "c\nd\n", "-a\n-b\n+c\n+d\n"],
  "insert-at-start": ["b\nc\n", "a\nb\nc\n", "+a\n b\n c\n"],
  "delete-at-end": ["a\nb\nc\n", "a\nb\n", " a\n b\n-c\n"],
  "swap": ["a\nb\n", "b\na\n", "-a\n b\n+a\n"],
  "repeated-lines": ["a\na\nb\n", "a\nb\nb\n", " a\n-a\n b\n+b\n"],
  "empty-line": ["a\n\nb\n", "a\nb\n", " a\n-\n b\n"],
  "no-final-newline": ["a\nb", "a\nb\n", " a\n b\n"],
  "crlf": ["a\r\nb\n", "a\nb\n", "-a\r\n+a\n b\n"],
  "trailing-space": ["a \nb\n", "a\nb\n", "-a \n+a\n b\n"],
  "normalization": ["caf\u00e9\n", "cafe\u0301\n", "-caf\u00e9\n+cafe\u0301\n"],
};

for (const [name, [oldText, newText, want]] of Object.entries(CASES)) {
  test(name, () => {
    assert.equal(diffLines(oldText, newText), want);
  });
}

test("many-lines", () => {
  // 1000 lines, and 10 of them change.
  const range = Array.from({ length: 1000 }, (_, i) => i);
  const oldText = range.map((i) => `${i}\n`).join("");
  const newText = range.map((i) => (i % 100 === 50 ? `x${i}\n` : `${i}\n`)).join("");
  const lines = diffLines(oldText, newText).split("\n");
  assert.equal(lines.length, 1011);
  assert.deepEqual(lines.slice(49, 52), [" 49", "-50", "+x50"]);
  assert.equal(lines[1009], " 999");
});

const dir = mkdtempSync(join(tmpdir(), "diff-two-texts-"));
after(() => rmSync(dir, { recursive: true, force: true }));

test("diff-files", () => {
  const [oldText, newText, want] = CASES["crlf"];
  writeFileSync(join(dir, "old.txt"), oldText, "utf8");
  writeFileSync(join(dir, "new.txt"), newText, "utf8");
  assert.equal(diffFiles(join(dir, "old.txt"), join(dir, "new.txt")), want);
});

test("not-found", () => {
  writeFileSync(join(dir, "new.txt"), "a\n", "utf8");
  assert.throws(() => diffFiles(join(dir, "missing.txt"), join(dir, "new.txt")), { code: "ENOENT" });
});
diffTwoTexts.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/diff-two-texts/.

import { readFileSync } from "node:fs";

/** Splits text at each LF. A final LF does not start a new line. */
export function splitLines(text: string): string[] {
  const lines = text.split("\n");
  // "a\n".split("\n") is ["a", ""], and "".split("\n") is [""].
  if (lines[lines.length - 1] === "") lines.pop();
  return lines;
}

/**
 * Returns the edit script that changes the lines of oldText into the lines of
 * newText. Each line of the result is a space and a line that stays, a - and a
 * line of oldText that goes, or a + and a line of newText that comes, with an
 * LF at the end. The script has the smallest number of - and + lines. When two
 * scripts are equally short, a - comes before a +.
 */
export function diffLines(oldText: string, newText: string): string {
  const a = splitLines(oldText);
  const b = splitLines(newText);
  const n = a.length;
  const m = b.length;
  const w = m + 1;
  // lcs[i * w + j] is the length of a longest common subsequence of the lines
  // from a[i] and from b[j]. Row n and column m stay 0.
  const lcs = new Int32Array((n + 1) * w);
  for (let i = n - 1; i >= 0; i--) {
    for (let j = m - 1; j >= 0; j--) {
      lcs[i * w + j] =
        a[i] === b[j] ? lcs[(i + 1) * w + j + 1] + 1 : Math.max(lcs[(i + 1) * w + j], lcs[i * w + j + 1]);
    }
  }
  const out: string[] = [];
  let i = 0;
  let j = 0;
  while (i < n && j < m) {
    if (a[i] === b[j]) {
      out.push(` ${a[i++]}\n`);
      j++;
    } else if (lcs[(i + 1) * w + j] >= lcs[i * w + j + 1]) {
      out.push(`-${a[i++]}\n`);
    } else {
      out.push(`+${b[j++]}\n`);
    }
  }
  while (i < n) out.push(`-${a[i++]}\n`);
  while (j < m) out.push(`+${b[j++]}\n`);
  return out.join("");
}

/**
 * Returns diffLines of the two UTF-8 files. Throws an error with the code
 * ENOENT if a file does not exist.
 */
export function diffFiles(oldPath: string, newPath: string): string {
  return diffLines(readFileSync(oldPath, "utf8"), readFileSync(newPath, "utf8"));
}
diffTwoTexts.test.ts 63 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/diff-two-texts/.

import assert from "node:assert/strict";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, test } from "node:test";

import { diffFiles, diffLines } from "./diffTwoTexts.ts";

// name: [the old text, the new text, the edit script]
const CASES: Record<string, [string, string, string]> = {
  "simple": ["a\nb\nc\n", "a\nc\nd\n", " a\n-b\n c\n+d\n"],
  "change-a-line": ["one\ntwo\nthree\n", "one\n2\nthree\n", " one\n-two\n+2\n three\n"],
  "identical": ["a\nb\n", "a\nb\n", " a\n b\n"],
  "lines-of-a-poem": ["The cat sat\non the mat.\nIt was flat.\n", "The cat sat\non the hat.\nIt was flat.\nThe end.\n", " The cat sat\n-on the mat.\n+on the hat.\n It was flat.\n+The end.\n"],
  "both-empty": ["", "", ""],
  "old-empty": ["", "a\nb\n", "+a\n+b\n"],
  "new-empty": ["a\nb\n", "", "-a\n-b\n"],
  "all-different": ["a\nb\n", "c\nd\n", "-a\n-b\n+c\n+d\n"],
  "insert-at-start": ["b\nc\n", "a\nb\nc\n", "+a\n b\n c\n"],
  "delete-at-end": ["a\nb\nc\n", "a\nb\n", " a\n b\n-c\n"],
  "swap": ["a\nb\n", "b\na\n", "-a\n b\n+a\n"],
  "repeated-lines": ["a\na\nb\n", "a\nb\nb\n", " a\n-a\n b\n+b\n"],
  "empty-line": ["a\n\nb\n", "a\nb\n", " a\n-\n b\n"],
  "no-final-newline": ["a\nb", "a\nb\n", " a\n b\n"],
  "crlf": ["a\r\nb\n", "a\nb\n", "-a\r\n+a\n b\n"],
  "trailing-space": ["a \nb\n", "a\nb\n", "-a \n+a\n b\n"],
  "normalization": ["caf\u00e9\n", "cafe\u0301\n", "-caf\u00e9\n+cafe\u0301\n"],
};

for (const [name, [oldText, newText, want]] of Object.entries(CASES)) {
  test(name, () => {
    assert.equal(diffLines(oldText, newText), want);
  });
}

test("many-lines", () => {
  // 1000 lines, and 10 of them change.
  const range = Array.from({ length: 1000 }, (_, i) => i);
  const oldText = range.map((i) => `${i}\n`).join("");
  const newText = range.map((i) => (i % 100 === 50 ? `x${i}\n` : `${i}\n`)).join("");
  const lines = diffLines(oldText, newText).split("\n");
  assert.equal(lines.length, 1011);
  assert.deepEqual(lines.slice(49, 52), [" 49", "-50", "+x50"]);
  assert.equal(lines[1009], " 999");
});

const dir = mkdtempSync(join(tmpdir(), "diff-two-texts-"));
after(() => rmSync(dir, { recursive: true, force: true }));

test("diff-files", () => {
  const [oldText, newText, want] = CASES["crlf"];
  writeFileSync(join(dir, "old.txt"), oldText, "utf8");
  writeFileSync(join(dir, "new.txt"), newText, "utf8");
  assert.equal(diffFiles(join(dir, "old.txt"), join(dir, "new.txt")), want);
});

test("not-found", () => {
  writeFileSync(join(dir, "new.txt"), "a\n", "utf8");
  assert.throws(() => diffFiles(join(dir, "missing.txt"), join(dir, "new.txt")), { code: "ENOENT" });
});
diff_two_texts.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/diff-two-texts/.

// Package difftexts compares two texts line by line.
package difftexts

import (
	"os"
	"strings"
)

// SplitLines splits text at each LF. A final LF does not start a new line.
func SplitLines(text string) []string {
	// strings.Split("a\n", "\n") is ["a" ""], and strings.Split("", "\n") is [""].
	lines := strings.Split(text, "\n")
	if lines[len(lines)-1] == "" {
		lines = lines[:len(lines)-1]
	}
	return lines
}

// DiffLines returns the edit script that changes the lines of oldText into
// the lines of newText. Each line of the result is a space and a line that
// stays, a - and a line of oldText that goes, or a + and a line of newText
// that comes, with an LF at the end. The script has the smallest number of -
// and + lines. When two scripts are equally short, a - comes before a +.
func DiffLines(oldText, newText string) string {
	a, b := SplitLines(oldText), SplitLines(newText)
	n, m := len(a), len(b)
	w := m + 1
	// lcs[i*w+j] is the length of a longest common subsequence of a[i:] and
	// b[j:]. Row n and column m stay 0.
	lcs := make([]int32, (n+1)*w)
	for i := n - 1; i >= 0; i-- {
		for j := m - 1; j >= 0; j-- {
			if a[i] == b[j] {
				lcs[i*w+j] = lcs[(i+1)*w+j+1] + 1
			} else {
				lcs[i*w+j] = max(lcs[(i+1)*w+j], lcs[i*w+j+1])
			}
		}
	}
	var out strings.Builder
	line := func(mark byte, s string) {
		out.WriteByte(mark)
		out.WriteString(s)
		out.WriteByte('\n')
	}
	i, j := 0, 0
	for i < n && j < m {
		switch {
		case a[i] == b[j]:
			line(' ', a[i])
			i++
			j++
		case lcs[(i+1)*w+j] >= lcs[i*w+j+1]:
			line('-', a[i])
			i++
		default:
			line('+', b[j])
			j++
		}
	}
	for ; i < n; i++ {
		line('-', a[i])
	}
	for ; j < m; j++ {
		line('+', b[j])
	}
	return out.String()
}

// DiffFiles returns DiffLines of the two files. A missing file gives an error
// that matches fs.ErrNotExist.
func DiffFiles(oldPath, newPath string) (string, error) {
	oldData, err := os.ReadFile(oldPath)
	if err != nil {
		return "", err
	}
	newData, err := os.ReadFile(newPath)
	if err != nil {
		return "", err
	}
	return DiffLines(string(oldData), string(newData)), nil
}
diff_two_texts_test.go 89 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/diff-two-texts/.

package difftexts

import (
	"errors"
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
	"slices"
	"strings"
	"testing"
)

type testCase struct{ name, oldText, newText, want string }

var cases = []testCase{
	{"simple", "a\nb\nc\n", "a\nc\nd\n", " a\n-b\n c\n+d\n"},
	{"change-a-line", "one\ntwo\nthree\n", "one\n2\nthree\n", " one\n-two\n+2\n three\n"},
	{"identical", "a\nb\n", "a\nb\n", " a\n b\n"},
	{"lines-of-a-poem", "The cat sat\non the mat.\nIt was flat.\n", "The cat sat\non the hat.\nIt was flat.\nThe end.\n", " The cat sat\n-on the mat.\n+on the hat.\n It was flat.\n+The end.\n"},
	{"both-empty", "", "", ""},
	{"old-empty", "", "a\nb\n", "+a\n+b\n"},
	{"new-empty", "a\nb\n", "", "-a\n-b\n"},
	{"all-different", "a\nb\n", "c\nd\n", "-a\n-b\n+c\n+d\n"},
	{"insert-at-start", "b\nc\n", "a\nb\nc\n", "+a\n b\n c\n"},
	{"delete-at-end", "a\nb\nc\n", "a\nb\n", " a\n b\n-c\n"},
	{"swap", "a\nb\n", "b\na\n", "-a\n b\n+a\n"},
	{"repeated-lines", "a\na\nb\n", "a\nb\nb\n", " a\n-a\n b\n+b\n"},
	{"empty-line", "a\n\nb\n", "a\nb\n", " a\n-\n b\n"},
	{"no-final-newline", "a\nb", "a\nb\n", " a\n b\n"},
	{"crlf", "a\r\nb\n", "a\nb\n", "-a\r\n+a\n b\n"},
	{"trailing-space", "a \nb\n", "a\nb\n", "-a \n+a\n b\n"},
	{"normalization", "caf\u00e9\n", "cafe\u0301\n", "-caf\u00e9\n+cafe\u0301\n"},
}

func TestDiffLines(t *testing.T) {
	for _, c := range cases {
		if got := DiffLines(c.oldText, c.newText); got != c.want {
			t.Errorf("%s: got %q, want %q", c.name, got, c.want)
		}
	}
}

func TestManyLines(t *testing.T) {
	// 1000 lines, and 10 of them change.
	var oldText, newText strings.Builder
	for i := range 1000 {
		fmt.Fprintf(&oldText, "%d\n", i)
		if i%100 == 50 {
			fmt.Fprintf(&newText, "x%d\n", i)
		} else {
			fmt.Fprintf(&newText, "%d\n", i)
		}
	}
	lines := strings.Split(DiffLines(oldText.String(), newText.String()), "\n")
	if len(lines) != 1011 || !slices.Equal(lines[49:52], []string{" 49", "-50", "+x50"}) || lines[1009] != " 999" {
		t.Errorf("got %d lines, %q, %q", len(lines), lines[49:52], lines[1009])
	}
}

func TestDiffFiles(t *testing.T) {
	dir := t.TempDir()
	c := cases[slices.IndexFunc(cases, func(c testCase) bool { return c.name == "crlf" })]
	oldPath, newPath := filepath.Join(dir, "old.txt"), filepath.Join(dir, "new.txt")
	if err := os.WriteFile(oldPath, []byte(c.oldText), 0o644); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(newPath, []byte(c.newText), 0o644); err != nil {
		t.Fatal(err)
	}
	got, err := DiffFiles(oldPath, newPath)
	if err != nil || got != c.want {
		t.Errorf("got %q, %v; want %q", got, err, c.want)
	}
}

func TestNotFound(t *testing.T) {
	dir := t.TempDir()
	newPath := filepath.Join(dir, "new.txt")
	if err := os.WriteFile(newPath, []byte("a\n"), 0o644); err != nil {
		t.Fatal(err)
	}
	if _, err := DiffFiles(filepath.Join(dir, "missing.txt"), newPath); !errors.Is(err, fs.ErrNotExist) {
		t.Errorf("got %v, want fs.ErrNotExist", err)
	}
}
diff_two_texts.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/diff-two-texts/.

//! Compares two texts line by line.

use std::fs;
use std::io;
use std::path::Path;

/// Splits `text` at each LF. A final LF does not start a new line.
pub fn split_lines(text: &str) -> Vec<&str> {
    // split_terminator skips the empty part after a final LF.
    text.split_terminator('\n').collect()
}

/// Returns the edit script that changes the lines of `old` into the lines of
/// `new`. Each line of the result is a space and a line that stays, a `-` and
/// a line of `old` that goes, or a `+` and a line of `new` that comes, with an
/// LF at the end. The script has the smallest number of `-` and `+` lines.
/// When two scripts are equally short, a `-` comes before a `+`.
pub fn diff_lines(old: &str, new: &str) -> String {
    let (a, b) = (split_lines(old), split_lines(new));
    let (n, m) = (a.len(), b.len());
    let w = m + 1;
    // lcs[i * w + j] is the length of a longest common subsequence of a[i..]
    // and b[j..]. Row n and column m stay 0.
    let mut lcs = vec![0u32; (n + 1) * w];
    for i in (0..n).rev() {
        for j in (0..m).rev() {
            lcs[i * w + j] = if a[i] == b[j] {
                lcs[(i + 1) * w + j + 1] + 1
            } else {
                lcs[(i + 1) * w + j].max(lcs[i * w + j + 1])
            };
        }
    }
    let mut out = String::new();
    let mut line = |mark: char, s: &str| {
        out.push(mark);
        out.push_str(s);
        out.push('\n');
    };
    let (mut i, mut j) = (0, 0);
    while i < n && j < m {
        if a[i] == b[j] {
            line(' ', a[i]);
            i += 1;
            j += 1;
        } else if lcs[(i + 1) * w + j] >= lcs[i * w + j + 1] {
            line('-', a[i]);
            i += 1;
        } else {
            line('+', b[j]);
            j += 1;
        }
    }
    for s in &a[i..] {
        line('-', s);
    }
    for s in &b[j..] {
        line('+', s);
    }
    out
}

/// Returns `diff_lines` of the two UTF-8 files. A missing file gives an error
/// of the kind `ErrorKind::NotFound`, and a file that is not valid UTF-8 gives
/// `ErrorKind::InvalidData`.
pub fn diff_files(old_path: impl AsRef<Path>, new_path: impl AsRef<Path>) -> io::Result<String> {
    let old = fs::read_to_string(old_path)?;
    let new = fs::read_to_string(new_path)?;
    Ok(diff_lines(&old, &new))
}
tests/diff_two_texts_test.rs 105 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/diff-two-texts/.

use std::fs;
use std::io::ErrorKind;
use std::path::PathBuf;

use algo_diff_two_texts::{diff_files, diff_lines};

/// (name, the old text, the new text, the edit script)
const CASES: &[(&str, &str, &str, &str)] = &[
    ("simple", "a\nb\nc\n", "a\nc\nd\n", " a\n-b\n c\n+d\n"),
    (
        "change-a-line",
        "one\ntwo\nthree\n",
        "one\n2\nthree\n",
        " one\n-two\n+2\n three\n",
    ),
    ("identical", "a\nb\n", "a\nb\n", " a\n b\n"),
    (
        "lines-of-a-poem",
        "The cat sat\non the mat.\nIt was flat.\n",
        "The cat sat\non the hat.\nIt was flat.\nThe end.\n",
        " The cat sat\n-on the mat.\n+on the hat.\n It was flat.\n+The end.\n",
    ),
    ("both-empty", "", "", ""),
    ("old-empty", "", "a\nb\n", "+a\n+b\n"),
    ("new-empty", "a\nb\n", "", "-a\n-b\n"),
    ("all-different", "a\nb\n", "c\nd\n", "-a\n-b\n+c\n+d\n"),
    ("insert-at-start", "b\nc\n", "a\nb\nc\n", "+a\n b\n c\n"),
    ("delete-at-end", "a\nb\nc\n", "a\nb\n", " a\n b\n-c\n"),
    ("swap", "a\nb\n", "b\na\n", "-a\n b\n+a\n"),
    (
        "repeated-lines",
        "a\na\nb\n",
        "a\nb\nb\n",
        " a\n-a\n b\n+b\n",
    ),
    ("empty-line", "a\n\nb\n", "a\nb\n", " a\n-\n b\n"),
    ("no-final-newline", "a\nb", "a\nb\n", " a\n b\n"),
    ("crlf", "a\r\nb\n", "a\nb\n", "-a\r\n+a\n b\n"),
    ("trailing-space", "a \nb\n", "a\nb\n", "-a \n+a\n b\n"),
    (
        "normalization",
        "caf\u{e9}\n",
        "cafe\u{301}\n",
        "-caf\u{e9}\n+cafe\u{301}\n",
    ),
];

/// Returns a new directory in the temporary directory, for one test.
fn temp_dir(name: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("diff-two-texts-{}-{name}", std::process::id()));
    fs::create_dir_all(&dir).unwrap();
    dir
}

#[test]
fn cases() {
    for (name, old, new, want) in CASES {
        assert_eq!(diff_lines(old, new), *want, "{name}");
    }
}

#[test]
fn many_lines() {
    // 1000 lines, and 10 of them change.
    let old: String = (0..1000).map(|i| format!("{i}\n")).collect();
    let new: String = (0..1000)
        .map(|i| {
            if i % 100 == 50 {
                format!("x{i}\n")
            } else {
                format!("{i}\n")
            }
        })
        .collect();
    let script = diff_lines(&old, &new);
    let lines: Vec<&str> = script.lines().collect();
    assert_eq!(lines.len(), 1010);
    assert_eq!(lines[49..52], [" 49", "-50", "+x50"]);
    assert_eq!(lines[1009], " 999");
}

#[test]
fn files() {
    let (_, old, new, want) = CASES.iter().find(|c| c.0 == "crlf").unwrap();
    let dir = temp_dir("files");
    fs::write(dir.join("old.txt"), old).unwrap();
    fs::write(dir.join("new.txt"), new).unwrap();
    assert_eq!(
        diff_files(dir.join("old.txt"), dir.join("new.txt")).unwrap(),
        *want
    );
    fs::remove_dir_all(dir).unwrap();
}

#[test]
fn not_found() {
    let dir = temp_dir("not-found");
    fs::write(dir.join("new.txt"), "a\n").unwrap();
    let err = diff_files(dir.join("missing.txt"), dir.join("new.txt")).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::NotFound);
    fs::remove_dir_all(dir).unwrap();
}
diff_two_texts.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/diff-two-texts/.

# diff_files OLD_PATH NEW_PATH
# Prints the edit script that changes the lines of the file OLD_PATH into the
# lines of the file NEW_PATH. Each line of the script is a space and a line
# that stays, a - and a line of OLD_PATH that goes, or a + and a line of
# NEW_PATH that comes. The script has the smallest number of - and + lines.
# When two scripts are equally short, a - comes before a +. Returns a nonzero
# status, and prints nothing on stdout, if a file cannot be read.
diff_files() {
  local path
  for path in "$1" "$2"; do
    [[ -r $path && ! -d $path ]] || { printf 'diff_files: cannot read %s\n' "$path" >&2; return 1; }
  done
  # LC_ALL=C compares the bytes of the lines.
  local LC_ALL=C
  local -a a b lcs out
  # mapfile -t removes the LF of each line and keeps a CR before it.
  mapfile -t a <"$1"
  mapfile -t b <"$2"
  local n=${#a[@]} m=${#b[@]}
  local w=$((m + 1)) i j down right
  # lcs[i*w+j] is the length of a longest common subsequence of the lines
  # from a[i] and from b[j]. An unset element of row n or column m is 0.
  for ((i = n - 1; i >= 0; i--)); do
    for ((j = m - 1; j >= 0; j--)); do
      if [[ ${a[i]} == "${b[j]}" ]]; then
        lcs[i * w + j]=$((${lcs[(i + 1) * w + j + 1]:-0} + 1))
      else
        down=${lcs[(i + 1) * w + j]:-0} right=${lcs[i * w + j + 1]:-0}
        lcs[i * w + j]=$((down >= right ? down : right))
      fi
    done
  done
  i=0 j=0
  while ((i < n && j < m)); do
    if [[ ${a[i]} == "${b[j]}" ]]; then
      out+=(" ${a[i]}")
      ((i += 1, j += 1))
    elif ((${lcs[(i + 1) * w + j]:-0} >= ${lcs[i * w + j + 1]:-0})); then
      out+=("-${a[i]}")
      ((i += 1))
    else
      out+=("+${b[j]}")
      ((j += 1))
    fi
  done
  for ((; i < n; i++)); do out+=("-${a[i]}"); done
  for ((; j < m; j++)); do out+=("+${b[j]}"); done
  ((${#out[@]} == 0)) || printf '%s\n' "${out[@]}"
}
test_diff_two_texts.bats 55 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/diff-two-texts/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/diff_two_texts.sh"
  old="$BATS_TEST_TMPDIR/old.txt"
  new="$BATS_TEST_TMPDIR/new.txt"
}

check() { # check OLD NEW WANT, each as printf %b bytes
  printf '%b' "$1" >"$old"
  printf '%b' "$2" >"$new"
  # The x keeps the final LFs, which $(...) removes.
  got=$(diff_files "$old" "$new" && printf x)
  [ "$got" = "$(printf '%bx' "$3")" ]
}

@test "simple" { check 'a\nb\nc\n' 'a\nc\nd\n' ' a\n-b\n c\n+d\n'; }
@test "change-a-line" { check 'one\ntwo\nthree\n' 'one\n2\nthree\n' ' one\n-two\n+2\n three\n'; }
@test "identical" { check 'a\nb\n' 'a\nb\n' ' a\n b\n'; }
@test "lines-of-a-poem" { check 'The cat sat\non the mat.\nIt was flat.\n' 'The cat sat\non the hat.\nIt was flat.\nThe end.\n' ' The cat sat\n-on the mat.\n+on the hat.\n It was flat.\n+The end.\n'; }
@test "both-empty" { check '' '' ''; }
@test "old-empty" { check '' 'a\nb\n' '+a\n+b\n'; }
@test "new-empty" { check 'a\nb\n' '' '-a\n-b\n'; }
@test "all-different" { check 'a\nb\n' 'c\nd\n' '-a\n-b\n+c\n+d\n'; }
@test "insert-at-start" { check 'b\nc\n' 'a\nb\nc\n' '+a\n b\n c\n'; }
@test "delete-at-end" { check 'a\nb\nc\n' 'a\nb\n' ' a\n b\n-c\n'; }
@test "swap" { check 'a\nb\n' 'b\na\n' '-a\n b\n+a\n'; }
@test "repeated-lines" { check 'a\na\nb\n' 'a\nb\nb\n' ' a\n-a\n b\n+b\n'; }
@test "empty-line" { check 'a\n\nb\n' 'a\nb\n' ' a\n-\n b\n'; }
@test "no-final-newline" { check 'a\nb' 'a\nb\n' ' a\n b\n'; }
@test "crlf" { check 'a\r\nb\n' 'a\nb\n' '-a\r\n+a\n b\n'; }
@test "trailing-space" { check 'a \nb\n' 'a\nb\n' '-a \n+a\n b\n'; }
@test "normalization" { check 'caf\xc3\xa9\n' 'cafe\xcc\x81\n' '-caf\xc3\xa9\n+cafe\xcc\x81\n'; }

@test "many-lines" {
  # 100 lines, and 10 of them change. A new bash keeps the loops fast, with no
  # DEBUG trap of bats.
  seq 0 99 >"$old"
  seq 0 99 | awk '{ print ($1 % 10 == 5 ? "x" $1 : $1) }' >"$new"
  out=$(bash -c '. "$1" && diff_files "$2" "$3"' bash "$BATS_TEST_DIRNAME/diff_two_texts.sh" "$old" "$new")
  [ "$(printf '%s\n' "$out" | wc -l)" -eq 110 ]
  [ "$(printf '%s\n' "$out" | sed -n '5,7p')" = "$(printf ' 4\n-5\n+x5')" ]
  [ "$(printf '%s\n' "$out" | tail -n 1)" = " 99" ]
}

@test "not-found" {
  printf 'a\n' >"$new"
  run diff_files "$BATS_TEST_TMPDIR/missing.txt" "$new"
  [ "$status" -ne 0 ]
  [ "$output" = "diff_files: cannot read $BATS_TEST_TMPDIR/missing.txt" ]
}

References

  1. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), diff, DESCRIPTION; EXIT STATUS
  2. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), Base Definitions, Chapter 3, Definitions, 3.172 Incomplete Line; 3.185 Line
  3. Go standard library, package strings, Split
  4. The Rust Standard Library, str, split_terminator
  5. Bash Reference Manual, Bash Builtin Commands, mapfile
  6. Comparing and Merging Files (GNU Diffutils manual), Overview
  7. The Python Standard Library, difflib, class Differ
  8. Git documentation, git-diff, OPTIONS (--minimal; --diff-algorithm)
  9. Comparing and Merging Files (GNU Diffutils manual), Incomplete Lines
  10. The Python Standard Library, io, TextIOWrapper (newline)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source