Taskcore
Apply a patch
Also called apply a unified diff, patch a file, apply a diff to a text, apply hunks, strict patch.
Read a UTF-8 file and a unified diff, and return the new text. Each hunk must match the old lines at the place that its header gives, with no fuzz and no offset.
- Evidence
- Code in 10 languages
Task
Read a text file and a unified diff for it, and make the new text. The page Unified diff format describes the format, and Diff two texts finds the changes. The GNU manual says: "If you think of diff as subtracting one file from another to produce their difference, you can think of patch as adding the difference to one file to reproduce the other."1
A patch tool must find the lines of each hunk in the old file, and it must decide what to do when they are not there. This page uses these rules:
- A line ends after LF. A CR before the LF stays in the line, so
aCRLF andaLF are two different lines. A last line with no LF is a line too. - The lines outside the hunks are skipped. These are the
---and+++lines, and thediff --gitandindexlines of Git. POSIX says that "The patch file shall contain zero or more lines of header information followed by one or more patches."2 A patch with no hunk is an error. - A hunk starts with a header. The header is
@@ -start,count +start,count @@. A missing count is 1, and the text after the second@@is skipped. For a range with no lines, POSIX says: "If a range is empty, its beginning line number shall be the number of the line just before the range, or 0 if the empty range starts the file."3 - Each line of a hunk has a mark. A space is a line that stays,
-is a line that goes, and+is a line that comes. An empty line is an empty line that stays, because some tools remove the space at the end of a line. A line that starts with a backslash, such as\ No newline at end of file, removes the LF of the line before it4. The two counts of the header give the end of the hunk. - No fuzz and no offset. The space lines and the
-lines of a hunk must be equal to the lines of the old file at the start of the old range. If the old range is empty, the hunk goes after the linestart. The solution does not look for the lines at another place. - The hunks are in order. POSIX says: "The line numbers for successive hunks within a patch shall occur in ascending order."2 The lines of the old file between two hunks stay.
- Errors. If a file does not exist, the solution reports
not-found. If the patch is not a correct unified diff, it reportsmalformed. If the lines of a hunk are not in the old file at their place, it reportsmismatch. The two patch errors give the number of the line of the patch where the error is.
For example, the old file has the lines a, b, c, and the patch is:
--- old.txt
+++ new.txt
@@ -1,3 +1,3 @@
a
-b
+B
c
The old range starts at line 1, and the lines a, b, c are there. The new text is a, B, c.
Solutions
All the solutions use the same method. They read the patch once, and they copy the old file once. The steps:
- Split the old text after each LF, so that each line keeps its LF. Split the patch in the same way, and remove the LF of each line of the patch.
- Skip the lines of the patch until a line starts with
@@. Read the four numbers of the header. If the header is not correct, the patch is malformed. - Find the place of the hunk. If the old count is more than 0, the hunk starts at the line
start, which has the index start − 1. If the old count is 0, the hunk starts after the linestart, at the indexstart. If this index is before the next old line that is not used yet, or after the end of the old text, the hunk does not match. Copy the old lines up to the index. - Read the lines of the hunk until the two counts are used up. A space line counts in the two ranges, a
-line in the old range, and a+line in the new range. A backslash line does not count, and it marks the line before it as a line with no LF. Another mark, a line that makes a count less than 0, or the end of the patch before the counts are used up, makes the patch malformed. After the counts, one more backslash line can come. - Apply the lines of the hunk. Each space line and each
-line, with its LF or with no LF, must be equal to the next old line. If it is not, the hunk does not match. A space line and a+line go to the new text. - After the last hunk, copy the old lines that are left.
The time grows with the sizes of the old text and the patch. The new text is never longer than the two of them together, because each byte comes from an old line or from a + line of the patch.
- Python.
open(path, 'rb')reads the bytes of each file, anddecode('utf-8')makes astr. The bytes keep each CR.split_linesusesstr.find('\n'), notstr.splitlines(see the pitfalls). A regular expression fromrereads the header. The errors arePatchError, aValueErrorwith the attributeskindandline, andFileNotFoundErrorfor a missing file. - JavaScript and TypeScript (Node.js).
readFileSync(path, 'utf8')reads each file as a string. ARegExpreads the header.PatchErrorextendsErrorwith the propertieskindandline. A missing file gives an error with the codeENOENT. The TypeScript file adds types only, and the kind has the type"malformed" | "mismatch". - Java.
Files.readString(path)reads each file as UTF-8 text. APatternandMatcher.lookingAtread the header.ApplyPatch.PatchExceptionis aRuntimeExceptionwith aKindofMALFORMEDorMISMATCH, and a line number. A missing file givesNoSuchFileException. - C#.
File.ReadAllText(path, Encoding.UTF8)reads each file. A[GeneratedRegex]pattern reads the header.string.EqualswithStringComparison.Ordinalcompares two lines.PatchExceptionhas aKindand aLine. A missing file givesFileNotFoundException. - Go.
os.ReadFilereads the bytes of each file.regexpreads the header. The error is a*PatchErrorwith aKindand aLine, anderrors.Ismatches it withErrMalformedorErrMismatch. A missing file gives an error that matchesfs.ErrNotExist. - Rust.
fs::read_to_stringreads each file, andsplit_inclusive('\n')gives the lines with their LF. A small parser withstrip_prefixandparsereads the header, with no crate.PatchErroris an enum with the variantsIo,MalformedandMismatch. A missing file givesPatchError::Iowith anio::Errorof the kindNotFound. - C.
apply_patch_filereads each file in binary mode withfread. The lines are arrays ofstruct span, a pointer into the text and a length, so the lines are not copied. Each hunk has two passes: the first pass checks the marks and the counts, and the second pass applies the lines. The result has space for the bytes of the two texts, from onemalloc. The functions return anenum patch_status:PATCH_OK,PATCH_IOwitherrnoset,PATCH_NOMEM,PATCH_MALFORMEDorPATCH_MISMATCH. For the two patch errors, the line number goes to*line. - C++.
apply_patch_filereads each file with a binarystd::ifstream.split_linesgives astd::vector<std::string_view>that points into the text, andstd::from_charsreads the numbers of the header. The result is astd::expected<std::string, PatchError>(C++23). The kinds of the error arecannot_open,read_failed,malformedandmismatch. - Bash.
mapfile lineswith no-treads the old file, so each line keeps its LF and a last line with no LF has none.mapfile -t preads the patch with no LF. The=~operator reads the header intoBASH_REMATCH, with at most 18 digits for each number. The function prints the new text withprintf '%s'. It returns 1 if a file cannot be read, 2 if a hunk does not match, and 3 if the patch is malformed, with a message on the standard error.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl, with the files in fixtures/.
change-a-line: the example of the task.two-hunks: two hunks changebananaandgrape, and the lines between them stay.git-header: thediff --gitandindexlines are skipped, and the textdef main():after the second@@is skipped.add-at-end:@@ -1 +1,2 @@adds a line after the last line.old-empty,delete-all:@@ -0,0 +1,2 @@makes two lines from an empty file, and@@ -1,2 +0,0 @@gives an empty text.no-count:@@ -2 +2 @@has no counts, and each range has one line.zero-context,insert-at-start: hunks with no context. In@@ -6 +5,0 @@the new range is empty, and in@@ -7,0 +7 @@the old range is empty, so the new line goes after line 7.@@ -0,0 +1 @@adds a line before the first line.old-no-final-newline,new-no-final-newline: a backslash line after the-line or after the+line. The first case adds the LF, and the second case removes it.empty-context-line,space-context-line: an empty line and a line with one space in a hunk are the same empty line that stays.crlf: the CR of each line stays, and the lines of the patch have the CR too.header-like-line: the old line-- ygoes, so the patch has the line--- y. The counts say that this line is in the hunk, so it is not a header.non-ascii:caféchanges tonaïve.
The case in cases/errors.jsonl with the name not-found must give the error not-found. The case mismatch has the - line x where the old file has b. The case malformed has a hunk that ends before its counts are used up. The tests also give malformed for a patch with no hunk and for a line with the mark *, and mismatch for a hunk after the end of the file. The tests also apply 10 hunks with no context to a text of 1000 lines, the numbers 0 to 999. The hunks change the lines 50, 150, and so on to 950 from n to xn. The Bash test uses 100 lines and 10 hunks. The toolchain does not load cases/errors.jsonl yet, so each test file holds these cases by name.
Pitfalls
- Other tools look for the hunk at another place. POSIX says: "For each hunk, the patch utility shall begin to search for the place to apply the patch at the line number at the beginning of the hunk, plus or minus any offset used in applying the previous hunk."2 GNU
patchalso uses a fuzz factor: it can ignore the first and the last lines of context. The GNU manual says: "The default fuzz factor is 2"5, and "Note that a larger fuzz factor increases the odds of making a faulty patch."5 In this example, a line came at the top of the file, and then a line of context changed. GNUpatchapplies the hunk in the two files:
dir=$(mktemp -d) && cd "$dir" || exit 1
trap 'rm -rf "$dir"' EXIT
printf '%s\n' a b c d e f g >old.txt
sed 's/^d$/D/' old.txt >new.txt
diff -u old.txt new.txt | tail -n +3 >change.patch
head -n 1 change.patch
# A line came at the top of the file after the diff was made.
{ echo top; cat old.txt; } >moved.txt
patch moved.txt <change.patch
# A line of context changed after the diff was made.
sed 's/^a$/A/' old.txt >fuzzy.txt
patch fuzzy.txt <change.patch
paste -s -d ' ' moved.txt
paste -s -d ' ' fuzzy.txt
@@ -1,7 +1,7 @@
patching file moved.txt
Hunk #1 succeeded at 2 (offset 1 line).
patching file fuzzy.txt
Hunk #1 succeeded at 1 with fuzz 1.
top a b c D e f g
A b c D e f g
This page gives mismatch for the two files. That is safer when the file changed in a way that the patch does not know, but it fails for a correct patch of a file that changed in another place. Git does not use fuzz: for git apply -C, the documentation says "By default no context is ever ignored."6 Also, the GNU manual says that "the results are guaranteed only when the patch is applied to an exact copy of the file that the patch was generated from."5
- A hunk with no context fits at any place. "For proper operation, patch typically needs at least three lines of context."7 Git says: "By default, git apply expects that the patch being applied is a unified diff with at least one line of context."6 A hunk that only adds lines, with an empty old range and no context, has no old lines to check. So this page applies such a hunk again if the patch is applied two times, and the lines come two times. A hunk with
-lines or with context givesmismatchthe second time. GNUpatchtakes a patch that was applied before as a reversed patch: "If you apply a patch that you have already applied, patch thinks it is a reversed patch and offers to un-apply the patch."8 - Line ends must be the same. A patch with LF lines does not match a file with CRLF lines, because the CR is part of each line. GNU
patchalso stops, and it gives the reason:
dir=$(mktemp -d) && cd "$dir" || exit 1
trap 'rm -rf "$dir"' EXIT
printf 'a\r\nb\r\n' >file.txt
printf '%s\n' '--- file.txt' '+++ file.txt' '@@ -1,2 +1,2 @@' ' a' '-b' '+c' >lf.patch
patch --dry-run file.txt <lf.patch
echo "status $?"
checking file file.txt
Hunk #1 FAILED at 1 (different line endings).
1 out of 1 hunk FAILED
status 1
GNU patch can remove a CR in some cases: "If a context diff contains trailing carriage return on each line, patch automatically ignores the carriage return."9 This page does not change the CR. Make the patch from files with the same line ends as the file that gets the patch.
- The backslash line changes the last line. GNU
diffwrites\ No newline at end of fileafter a line with no LF, and "Incomplete lines do not match full lines unless differences in white space are ignored"4. In this example, the old file and the new file have no LF at the end.patchkeeps the new file with no LF, asod -cshows:
dir=$(mktemp -d) && cd "$dir" || exit 1
trap 'rm -rf "$dir"' EXIT
printf 'a\nb' >old.txt
printf 'a\nc' >new.txt
diff -u old.txt new.txt | tail -n +3 >change.patch
cat change.patch
patch old.txt <change.patch
od -c old.txt
@@ -1,2 +1,2 @@
a
-b
\ No newline at end of file
+c
\ No newline at end of file
patching file old.txt
0000000 a \n c
0000003
A tool that skips the backslash line adds an LF to the last line. A tool that takes the backslash line as a line of the hunk counts one line too many.
- Split the text only at LF. In Python,
str.splitlinessplits at more characters than LF. The documentation says: "This method splits on the following line boundaries."10 Its list has LF, CR, CRLF, form feed, U+2028 and other characters. So a form feed, a lone CR or U+2028 in a line makes two lines, and the line numbers of the patch point at the wrong lines:
text = "a\x0cb\rc\u2028d\n"
print(text.splitlines(keepends=True))
print(text.split("\n"))
['a\x0c', 'b\r', 'c\u2028', 'd\n']
['a\x0cb\rc\u2028d', '']
- Read the hunk by its counts. A deleted line with the text
-- yis the line--- yin the patch. A reader that looks for a---header in each line takes it for the start of a new file. Look for a header only after the counts of the hunk are used up. - Do not change a part of the file. If one hunk does not match, the solution returns an error and no text. Git does the same for the whole patch: "For atomicity, git apply by default fails the whole patch and does not touch the working tree when some of the hunks do not apply."6 GNU
patchandgit apply --rejectapply the hunks that match, and write the other hunks to a.rejfile26.
Related tasks
- Diff two texts: find the lines that go and the lines that come.
- Unified diff format: the format of the patch.
- Line ending: LF, CRLF, and a last line with no line ending.
- Remove duplicate lines: compare the lines of a file by their bytes, with the same rules for a line.
- Unix text processing pipeline: join small text tools in a pipeline.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/apply-a-patch/.
"""Applies a unified diff to a text, with no fuzz and no offset."""
import re
from os import PathLike
HUNK = re.compile(r"@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
class PatchError(ValueError):
"""The patch is malformed, or a hunk does not match the text.
kind is "malformed" or "mismatch", and line is the number of the line of
the patch where the error is.
"""
def __init__(self, kind: str, line: int) -> None:
super().__init__(f"{kind} at line {line} of the patch")
self.kind = kind
self.line = line
def split_lines(text: str) -> list[str]:
"""Splits text after each LF. Each line keeps its LF, and a last line
with no LF is a line too."""
lines = []
start = 0
while start < len(text):
end = text.find("\n", start)
end = len(text) if end < 0 else end + 1
lines.append(text[start:end])
start = end
return lines
def apply_patch(old: str, patch: str) -> str:
"""Returns the text that the unified diff patch makes from the text old.
Each hunk must match the lines of old at the start of its old range.
Raises PatchError if the patch is malformed or a hunk does not match.
"""
lines = split_lines(old)
# The lines of the patch, with no LF. A CR stays in its line.
p = [line.removesuffix("\n") for line in split_lines(patch)]
out: list[str] = []
cur = 0 # the index of the next line of old to use
hunks = 0
i = 0
while i < len(p):
if not p[i].startswith("@@"):
i += 1 # a header line, or another line outside a hunk
continue
m = HUNK.match(p[i])
if not m:
raise PatchError("malformed", i + 1)
hunks += 1
old_start, old_count = int(m[1]), int(m[2] or 1)
new_count = int(m[4] or 1)
# An empty range starts after the line old_start.
pos = old_start - 1 if old_count > 0 else old_start
if pos < 0:
raise PatchError("malformed", i + 1)
if pos < cur or pos > len(lines):
raise PatchError("mismatch", i + 1)
out.extend(lines[cur:pos])
cur = pos
i += 1
# The mark, the text and the number in the patch of each line, and
# the end of each line: an LF, or "" before a backslash line.
body: list[tuple[str, str, int]] = []
ends: list[str] = []
old_left, new_left = old_count, new_count
while old_left > 0 or new_left > 0:
if i == len(p):
raise PatchError("malformed", i)
line = p[i]
mark, text = (line[0], line[1:]) if line else (" ", "")
if mark == "\\":
if not body:
raise PatchError("malformed", i + 1)
ends[-1] = "" # the line before has no LF
i += 1
continue
if mark not in " -+":
raise PatchError("malformed", i + 1)
if mark in " -":
old_left -= 1
if mark in " +":
new_left -= 1
if old_left < 0 or new_left < 0:
raise PatchError("malformed", i + 1)
body.append((mark, text, i + 1))
ends.append("\n")
i += 1
if i < len(p) and p[i].startswith("\\") and body:
ends[-1] = ""
i += 1
for (mark, text, number), end in zip(body, ends):
line = text + end
if mark in " -":
if cur == len(lines) or lines[cur] != line:
raise PatchError("mismatch", number)
cur += 1
if mark in " +":
out.append(line)
if hunks == 0:
raise PatchError("malformed", len(p))
out.extend(lines[cur:])
return "".join(out)
def apply_patch_file(path: str | PathLike[str], patch_path: str | PathLike[str]) -> str:
"""Returns apply_patch of the two UTF-8 files.
Raises FileNotFoundError if a file does not exist, and PatchError.
"""
# Binary mode, then decode: a text mode file would change CRLF to LF.
with open(path, "rb") as f:
old = f.read().decode("utf-8")
with open(patch_path, "rb") as f:
patch = f.read().decode("utf-8")
return apply_patch(old, patch)
test_apply_a_patch.py 77 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/apply-a-patch/.
import pytest
from apply_a_patch import PatchError, apply_patch, apply_patch_file
# name: (the old text, the patch, the new text)
CASES = {
"change-a-line": ("a\nb\nc\n", "--- old.txt\n+++ new.txt\n@@ -1,3 +1,3 @@\n a\n-b\n+B\n c\n", "a\nB\nc\n"),
"two-hunks": ("apple\nbanana\ncherry\ndate\nelder\nfig\ngrape\n", "--- old.txt\n+++ new.txt\n@@ -1,3 +1,3 @@\n apple\n-banana\n+blueberry\n cherry\n@@ -6,2 +6,2 @@\n fig\n-grape\n+guava\n", "apple\nblueberry\ncherry\ndate\nelder\nfig\nguava\n"),
"git-header": ("def main():\n print(1)\n", "diff --git a/main.py b/main.py\nindex 1234567..89abcde 100644\n--- a/main.py\n+++ b/main.py\n@@ -1,2 +1,2 @@ def main():\n def main():\n- print(1)\n+ print(2)\n", "def main():\n print(2)\n"),
"add-at-end": ("a\n", "@@ -1 +1,2 @@\n a\n+b\n", "a\nb\n"),
"old-empty": ("", "--- /dev/null\n+++ b.txt\n@@ -0,0 +1,2 @@\n+a\n+b\n", "a\nb\n"),
"delete-all": ("a\nb\n", "@@ -1,2 +0,0 @@\n-a\n-b\n", ""),
"no-count": ("a\nb\nc\n", "@@ -2 +2 @@\n-b\n+x\n", "a\nx\nc\n"),
"zero-context": ("apple\nbanana\ncherry\ndate\nelder\nfig\ngrape\n", "@@ -3 +3 @@\n-cherry\n+coconut\n@@ -6 +5,0 @@\n-fig\n@@ -7,0 +7 @@\n+honeydew\n", "apple\nbanana\ncoconut\ndate\nelder\ngrape\nhoneydew\n"),
"insert-at-start": ("b\n", "@@ -0,0 +1 @@\n+a\n", "a\nb\n"),
"old-no-final-newline": ("a\nb", "@@ -1,2 +1,2 @@\n a\n-b\n\\ No newline at end of file\n+b\n", "a\nb\n"),
"new-no-final-newline": ("a\nb\n", "@@ -1,2 +1,2 @@\n a\n-b\n+b\n\\ No newline at end of file\n", "a\nb"),
"empty-context-line": ("a\n\nb\n", "@@ -1,3 +1,3 @@\n a\n\n-b\n+c\n", "a\n\nc\n"),
"space-context-line": ("a\n\nb\n", "@@ -1,3 +1,3 @@\n a\n \n-b\n+c\n", "a\n\nc\n"),
"crlf": ("a\r\nb\r\n", "@@ -1,2 +1,2 @@\n a\r\n-b\r\n+c\r\n", "a\r\nc\r\n"),
"header-like-line": ("x\n-- y\n", "--- old.txt\n+++ new.txt\n@@ -1,2 +1 @@\n x\n--- y\n", "x\n"),
"non-ascii": ("caf\u00e9\n", "@@ -1 +1 @@\n-caf\u00e9\n+na\u00efve\n", "na\u00efve\n"),
}
# name: (the old text, the patch, the kind of the error)
ERRORS = {
"mismatch": ("a\nb\nc\n", "@@ -1,3 +1,3 @@\n a\n-x\n+y\n c\n", "mismatch"),
"malformed": ("a\nb\nc\n", "@@ -1,3 +1,3 @@\n a\n-b\n", "malformed"),
}
@pytest.mark.parametrize("name", CASES)
def test_apply_patch(name):
old, patch, want = CASES[name]
assert apply_patch(old, patch) == want
@pytest.mark.parametrize("name", ERRORS)
def test_errors(name):
old, patch, kind = ERRORS[name]
with pytest.raises(PatchError) as e:
apply_patch(old, patch)
assert e.value.kind == kind
def test_more_errors():
with pytest.raises(PatchError, match="malformed"):
apply_patch("a\n", "no hunk here\n")
with pytest.raises(PatchError, match="malformed"):
apply_patch("a\n", "@@ -1 +1 @@\n*a\n")
with pytest.raises(PatchError, match="mismatch"):
apply_patch("a\n", "@@ -2 +2 @@\n-a\n+b\n")
def test_many_hunks():
# 1000 lines, and 10 hunks with no context change 10 of them.
old = "".join(f"{i}\n" for i in range(1000))
patch = "".join(f"@@ -{i + 1} +{i + 1} @@\n-{i}\n+x{i}\n" for i in range(50, 1000, 100))
want = "".join((f"x{i}" if i % 100 == 50 else str(i)) + "\n" for i in range(1000))
assert apply_patch(old, patch) == want
def test_apply_patch_file(tmp_path):
old, patch, 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 / "fix.patch").write_bytes(patch.encode())
assert apply_patch_file(tmp_path / "old.txt", tmp_path / "fix.patch") == want
def test_not_found(tmp_path):
(tmp_path / "fix.patch").write_bytes(b"@@ -1 +1 @@\n-a\n+b\n")
with pytest.raises(FileNotFoundError):
apply_patch_file(tmp_path / "missing.txt", tmp_path / "fix.patch")
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-patch/.
#include "apply_a_patch.hpp"
#include <charconv>
#include <fstream>
#include <iterator>
#include <optional>
std::vector<std::string_view> split_lines(std::string_view text) {
std::vector<std::string_view> lines;
while (!text.empty()) {
std::size_t end = text.find('\n');
end = end == std::string_view::npos ? text.size() : end + 1;
lines.push_back(text.substr(0, end));
text.remove_prefix(end);
}
return lines;
}
namespace {
struct Hunk {
std::size_t old_start, old_count, new_count;
};
// Reads a number at the start of s. It fails if there is no digit or the
// number is too large.
bool number(std::string_view& s, std::size_t& v) {
auto [p, ec] = std::from_chars(s.data(), s.data() + s.size(), v);
if (ec != std::errc{}) {
return false;
}
s.remove_prefix(static_cast<std::size_t>(p - s.data()));
return true;
}
bool prefix(std::string_view& s, std::string_view t) {
if (!s.starts_with(t)) {
return false;
}
s.remove_prefix(t.size());
return true;
}
// Reads a start and an optional comma and count. A missing count is 1.
bool range(std::string_view& s, std::size_t& start, std::size_t& count) {
count = 1;
return number(s, start) && (!prefix(s, ",") || number(s, count));
}
// Reads a line such as @@ -1,3 +1,4 @@ and the text after it.
std::optional<Hunk> hunk_header(std::string_view s) {
Hunk h{};
std::size_t new_start = 0;
if (prefix(s, "@@ -") && range(s, h.old_start, h.old_count) && prefix(s, " +") &&
range(s, new_start, h.new_count) && prefix(s, " @@")) {
return h;
}
return std::nullopt;
}
struct BodyLine {
char mark;
std::string_view text;
std::size_t number;
bool lf;
};
std::unexpected<PatchError> error(PatchErrorKind kind, std::size_t line) {
return std::unexpected(PatchError{kind, line});
}
} // namespace
std::expected<std::string, PatchError> apply_patch(std::string_view old_text, std::string_view patch) {
using enum PatchErrorKind;
const auto lines = split_lines(old_text);
// The lines of the patch, with no LF. A CR stays in its line.
auto p = split_lines(patch);
for (auto& l : p) {
if (l.ends_with('\n')) {
l.remove_suffix(1);
}
}
std::string out;
std::size_t cur = 0; // the index of the next line of old_text to use
std::size_t hunks = 0;
std::size_t i = 0;
while (i < p.size()) {
if (!p[i].starts_with("@@")) {
i++; // a header line, or another line outside a hunk
continue;
}
auto h = hunk_header(p[i]);
if (!h || (h->old_count > 0 && h->old_start == 0)) {
return error(malformed, i + 1);
}
hunks++;
// An empty range starts after the line old_start.
std::size_t pos = h->old_count > 0 ? h->old_start - 1 : h->old_start;
if (pos < cur || pos > lines.size()) {
return error(mismatch, i + 1);
}
for (; cur < pos; cur++) {
out += lines[cur];
}
i++;
std::vector<BodyLine> body;
std::size_t old_left = h->old_count, new_left = h->new_count;
while (old_left > 0 || new_left > 0) {
if (i == p.size()) {
return error(malformed, i);
}
std::string_view line = p[i];
char mark = line.empty() ? ' ' : line[0];
if (mark == '\\') {
if (body.empty()) {
return error(malformed, i + 1);
}
body.back().lf = false; // the line before has no LF
i++;
continue;
}
if (mark != ' ' && mark != '-' && mark != '+') {
return error(malformed, i + 1);
}
if ((mark != '+' && old_left-- == 0) || (mark != '-' && new_left-- == 0)) {
return error(malformed, i + 1);
}
body.push_back({mark, line.empty() ? line : line.substr(1), i + 1, true});
i++;
}
if (i < p.size() && p[i].starts_with('\\') && !body.empty()) {
body.back().lf = false;
i++;
}
for (const auto& b : body) {
if (b.mark != '+') {
std::string_view want = cur < lines.size() ? lines[cur] : std::string_view{};
bool same = cur < lines.size() && want.size() == b.text.size() + (b.lf ? 1 : 0) &&
want.starts_with(b.text) && (!b.lf || want.ends_with('\n'));
if (!same) {
return error(mismatch, b.number);
}
cur++;
}
if (b.mark != '-') {
out += b.text;
if (b.lf) {
out += '\n';
}
}
}
}
if (hunks == 0) {
return error(malformed, p.size());
}
for (; cur < lines.size(); cur++) {
out += lines[cur];
}
return out;
}
namespace {
// Reads the whole file in binary mode, so that each CR stays.
std::expected<std::string, PatchError> read_file(const std::filesystem::path& path) {
std::ifstream in(path, std::ios::binary);
if (!in) {
return std::unexpected(PatchError{PatchErrorKind::cannot_open, 0});
}
std::string data{std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
if (in.bad()) {
return std::unexpected(PatchError{PatchErrorKind::read_failed, 0});
}
return data;
}
} // namespace
std::expected<std::string, PatchError> apply_patch_file(const std::filesystem::path& path,
const std::filesystem::path& patch_path) {
auto old_text = read_file(path);
if (!old_text) {
return std::unexpected(old_text.error());
}
auto patch = read_file(patch_path);
if (!patch) {
return std::unexpected(patch.error());
}
return apply_patch(*old_text, *patch);
}
apply_a_patch.hpp 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-patch/.
// since: C++23 (std::expected)
#pragma once
#include <cstddef>
#include <expected>
#include <filesystem>
#include <string>
#include <string_view>
#include <vector>
enum class PatchErrorKind { cannot_open, read_failed, malformed, mismatch };
// The kind of the error, and for malformed and mismatch the number of the line
// of the patch where the error is.
struct PatchError {
PatchErrorKind kind;
std::size_t line = 0;
};
// Splits text after each LF. Each line keeps its LF, and a last line with no
// LF is a line too.
std::vector<std::string_view> split_lines(std::string_view text);
// Returns the text that the unified diff patch makes from old_text, with no
// fuzz and no offset. Each hunk must match the lines of old_text at the start
// of its old range.
std::expected<std::string, PatchError> apply_patch(std::string_view old_text, std::string_view patch);
// Returns apply_patch of the two files.
std::expected<std::string, PatchError> apply_patch_file(const std::filesystem::path& path,
const std::filesystem::path& patch_path);
test_apply_a_patch.cpp 103 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-patch/.
#include "apply_a_patch.hpp"
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
#include <unistd.h> // getpid
struct TestCase {
const char *name, *old_text, *patch, *want;
};
static const TestCase cases[] = {
{"change-a-line", "a\nb\nc\n", "--- old.txt\n+++ new.txt\n@@ -1,3 +1,3 @@\n a\n-b\n+B\n c\n", "a\nB\nc\n"},
{"two-hunks", "apple\nbanana\ncherry\ndate\nelder\nfig\ngrape\n", "--- old.txt\n+++ new.txt\n@@ -1,3 +1,3 @@\n apple\n-banana\n+blueberry\n cherry\n@@ -6,2 +6,2 @@\n fig\n-grape\n+guava\n", "apple\nblueberry\ncherry\ndate\nelder\nfig\nguava\n"},
{"git-header", "def main():\n print(1)\n", "diff --git a/main.py b/main.py\nindex 1234567..89abcde 100644\n--- a/main.py\n+++ b/main.py\n@@ -1,2 +1,2 @@ def main():\n def main():\n- print(1)\n+ print(2)\n", "def main():\n print(2)\n"},
{"add-at-end", "a\n", "@@ -1 +1,2 @@\n a\n+b\n", "a\nb\n"},
{"old-empty", "", "--- /dev/null\n+++ b.txt\n@@ -0,0 +1,2 @@\n+a\n+b\n", "a\nb\n"},
{"delete-all", "a\nb\n", "@@ -1,2 +0,0 @@\n-a\n-b\n", ""},
{"no-count", "a\nb\nc\n", "@@ -2 +2 @@\n-b\n+x\n", "a\nx\nc\n"},
{"zero-context", "apple\nbanana\ncherry\ndate\nelder\nfig\ngrape\n", "@@ -3 +3 @@\n-cherry\n+coconut\n@@ -6 +5,0 @@\n-fig\n@@ -7,0 +7 @@\n+honeydew\n", "apple\nbanana\ncoconut\ndate\nelder\ngrape\nhoneydew\n"},
{"insert-at-start", "b\n", "@@ -0,0 +1 @@\n+a\n", "a\nb\n"},
{"old-no-final-newline", "a\nb", "@@ -1,2 +1,2 @@\n a\n-b\n\\ No newline at end of file\n+b\n", "a\nb\n"},
{"new-no-final-newline", "a\nb\n", "@@ -1,2 +1,2 @@\n a\n-b\n+b\n\\ No newline at end of file\n", "a\nb"},
{"empty-context-line", "a\n\nb\n", "@@ -1,3 +1,3 @@\n a\n\n-b\n+c\n", "a\n\nc\n"},
{"space-context-line", "a\n\nb\n", "@@ -1,3 +1,3 @@\n a\n \n-b\n+c\n", "a\n\nc\n"},
{"crlf", "a\r\nb\r\n", "@@ -1,2 +1,2 @@\n a\r\n-b\r\n+c\r\n", "a\r\nc\r\n"},
{"header-like-line", "x\n-- y\n", "--- old.txt\n+++ new.txt\n@@ -1,2 +1 @@\n x\n--- y\n", "x\n"},
{"non-ascii", "caf\303\251\n", "@@ -1 +1 @@\n-caf\303\251\n+na\303\257ve\n", "na\303\257ve\n"},
};
struct ErrorCase {
const char *name, *old_text, *patch;
PatchErrorKind want;
};
static const ErrorCase errors[] = {
{"mismatch", "a\nb\nc\n", "@@ -1,3 +1,3 @@\n a\n-x\n+y\n c\n", PatchErrorKind::mismatch},
{"malformed", "a\nb\nc\n", "@@ -1,3 +1,3 @@\n a\n-b\n", PatchErrorKind::malformed},
{"no-hunk", "a\n", "no hunk here\n", PatchErrorKind::malformed},
{"bad-mark", "a\n", "@@ -1 +1 @@\n*a\n", PatchErrorKind::malformed},
{"past-the-end", "a\n", "@@ -2 +2 @@\n-a\n+b\n", PatchErrorKind::mismatch},
};
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 (auto got = apply_patch(c.old_text, c.patch); !got || *got != c.want) {
std::cerr << "FAIL " << c.name << "\n";
failures++;
}
}
for (const auto& c : errors) {
if (auto got = apply_patch(c.old_text, c.patch); got || got.error().kind != c.want) {
std::cerr << "FAIL " << c.name << "\n";
failures++;
}
}
// 1000 lines, and 10 hunks with no context change 10 of them.
std::string old_text, patch, want;
for (int i = 0; i < 1000; i++) {
std::string n = std::to_string(i);
old_text += n + "\n";
if (i % 100 == 50) {
std::string at = std::to_string(i + 1);
patch += "@@ -" + at + " +" + at + " @@\n-" + n + "\n+x" + n + "\n";
want += "x";
}
want += n + "\n";
}
if (auto got = apply_patch(old_text, patch); !got || *got != want) {
std::cerr << "FAIL many-hunks\n";
failures++;
}
const auto dir = std::filesystem::temp_directory_path() / ("apply-a-patch-cpp-" + std::to_string(::getpid()));
std::filesystem::create_directories(dir);
write_file(dir / "old.txt", "a\r\nb\r\n");
write_file(dir / "a.patch", "@@ -1,2 +1,2 @@\n a\r\n-b\r\n+c\r\n");
if (auto r = apply_patch_file(dir / "old.txt", dir / "a.patch"); !r || *r != "a\r\nc\r\n") {
std::cerr << "FAIL apply-patch-file\n";
failures++;
}
if (auto r = apply_patch_file(dir / "missing.txt", dir / "a.patch");
r || r.error().kind != PatchErrorKind::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;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-patch/.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** Applies a unified diff to a text, with no fuzz and no offset. */
public final class ApplyPatch {
private ApplyPatch() {}
private static final Pattern HUNK =
Pattern.compile("@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@");
/** The patch is malformed, or a hunk does not match the text. */
public static final class PatchException extends RuntimeException {
private static final long serialVersionUID = 1L;
/** The kinds of the error. */
public enum Kind {
MALFORMED,
MISMATCH
}
private final Kind kind;
private final int line;
PatchException(Kind kind, int line) {
super(kind.name().toLowerCase(java.util.Locale.ROOT) + " at line " + line + " of the patch");
this.kind = kind;
this.line = line;
}
public Kind kind() {
return kind;
}
/** The number of the line of the patch where the error is. */
public int line() {
return line;
}
}
private record BodyLine(char mark, String text, int number) {}
/** Splits text after each LF. Each line keeps its LF, and a last line with no LF is a line too. */
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);
end = end < 0 ? text.length() : end + 1;
lines.add(text.substring(start, end));
start = end;
}
return lines;
}
private static PatchException malformed(int line) {
return new PatchException(PatchException.Kind.MALFORMED, line);
}
private static PatchException mismatch(int line) {
return new PatchException(PatchException.Kind.MISMATCH, line);
}
private static int count(String s) {
return s == null ? 1 : Integer.parseInt(s);
}
/**
* Returns the text that the unified diff patch makes from the text oldText. Each hunk must
* match the lines of oldText at the start of its old range. Throws PatchException if the patch
* is malformed or a hunk does not match.
*/
public static String apply(String oldText, String patch) {
List<String> lines = splitLines(oldText);
// The lines of the patch, with no LF. A CR stays in its line.
List<String> p = new ArrayList<>();
for (String l : splitLines(patch)) {
p.add(l.endsWith("\n") ? l.substring(0, l.length() - 1) : l);
}
StringBuilder out = new StringBuilder();
int cur = 0; // the index of the next line of oldText to use
int hunks = 0;
int i = 0;
while (i < p.size()) {
if (!p.get(i).startsWith("@@")) {
i++; // a header line, or another line outside a hunk
continue;
}
Matcher m = HUNK.matcher(p.get(i));
if (!m.lookingAt()) {
throw malformed(i + 1);
}
int oldStart;
int oldCount;
int newCount;
try {
oldStart = Integer.parseInt(m.group(1));
oldCount = count(m.group(2));
newCount = count(m.group(4));
} catch (NumberFormatException e) {
throw malformed(i + 1);
}
hunks++;
// An empty range starts after the line oldStart.
int pos = oldCount > 0 ? oldStart - 1 : oldStart;
if (pos < 0) {
throw malformed(i + 1);
}
if (pos < cur || pos > lines.size()) {
throw mismatch(i + 1);
}
for (; cur < pos; cur++) {
out.append(lines.get(cur));
}
i++;
List<BodyLine> body = new ArrayList<>();
// The end of each line: an LF, or "" before a backslash line.
List<String> ends = new ArrayList<>();
int oldLeft = oldCount;
int newLeft = newCount;
while (oldLeft > 0 || newLeft > 0) {
if (i == p.size()) {
throw malformed(i);
}
String line = p.get(i);
char mark = line.isEmpty() ? ' ' : line.charAt(0);
if (mark == '\\') {
if (body.isEmpty()) {
throw malformed(i + 1);
}
ends.set(ends.size() - 1, ""); // the line before has no LF
i++;
continue;
}
if (mark != ' ' && mark != '-' && mark != '+') {
throw malformed(i + 1);
}
if (mark != '+') {
oldLeft--;
}
if (mark != '-') {
newLeft--;
}
if (oldLeft < 0 || newLeft < 0) {
throw malformed(i + 1);
}
body.add(new BodyLine(mark, line.isEmpty() ? "" : line.substring(1), i + 1));
ends.add("\n");
i++;
}
if (i < p.size() && p.get(i).startsWith("\\") && !body.isEmpty()) {
ends.set(ends.size() - 1, "");
i++;
}
for (int k = 0; k < body.size(); k++) {
BodyLine b = body.get(k);
String line = b.text() + ends.get(k);
if (b.mark() != '+') {
if (cur == lines.size() || !lines.get(cur).equals(line)) {
throw mismatch(b.number());
}
cur++;
}
if (b.mark() != '-') {
out.append(line);
}
}
}
if (hunks == 0) {
throw malformed(p.size());
}
for (; cur < lines.size(); cur++) {
out.append(lines.get(cur));
}
return out.toString();
}
/**
* Returns apply of the two UTF-8 files. Throws NoSuchFileException if a file does not exist,
* and PatchException.
*/
public static String applyFile(Path path, Path patchPath) throws IOException {
return apply(Files.readString(path), Files.readString(patchPath));
}
}
ApplyPatchTest.java 98 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-patch/.
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.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 ApplyPatchTest {
@TempDir Path dir;
// name, the old text, the patch, the new text
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("change-a-line", "a\nb\nc\n", "--- old.txt\n+++ new.txt\n@@ -1,3 +1,3 @@\n a\n-b\n+B\n c\n", "a\nB\nc\n"),
Arguments.of("two-hunks", "apple\nbanana\ncherry\ndate\nelder\nfig\ngrape\n", "--- old.txt\n+++ new.txt\n@@ -1,3 +1,3 @@\n apple\n-banana\n+blueberry\n cherry\n@@ -6,2 +6,2 @@\n fig\n-grape\n+guava\n", "apple\nblueberry\ncherry\ndate\nelder\nfig\nguava\n"),
Arguments.of("git-header", "def main():\n print(1)\n", "diff --git a/main.py b/main.py\nindex 1234567..89abcde 100644\n--- a/main.py\n+++ b/main.py\n@@ -1,2 +1,2 @@ def main():\n def main():\n- print(1)\n+ print(2)\n", "def main():\n print(2)\n"),
Arguments.of("add-at-end", "a\n", "@@ -1 +1,2 @@\n a\n+b\n", "a\nb\n"),
Arguments.of("old-empty", "", "--- /dev/null\n+++ b.txt\n@@ -0,0 +1,2 @@\n+a\n+b\n", "a\nb\n"),
Arguments.of("delete-all", "a\nb\n", "@@ -1,2 +0,0 @@\n-a\n-b\n", ""),
Arguments.of("no-count", "a\nb\nc\n", "@@ -2 +2 @@\n-b\n+x\n", "a\nx\nc\n"),
Arguments.of("zero-context", "apple\nbanana\ncherry\ndate\nelder\nfig\ngrape\n", "@@ -3 +3 @@\n-cherry\n+coconut\n@@ -6 +5,0 @@\n-fig\n@@ -7,0 +7 @@\n+honeydew\n", "apple\nbanana\ncoconut\ndate\nelder\ngrape\nhoneydew\n"),
Arguments.of("insert-at-start", "b\n", "@@ -0,0 +1 @@\n+a\n", "a\nb\n"),
Arguments.of("old-no-final-newline", "a\nb", "@@ -1,2 +1,2 @@\n a\n-b\n\\ No newline at end of file\n+b\n", "a\nb\n"),
Arguments.of("new-no-final-newline", "a\nb\n", "@@ -1,2 +1,2 @@\n a\n-b\n+b\n\\ No newline at end of file\n", "a\nb"),
Arguments.of("empty-context-line", "a\n\nb\n", "@@ -1,3 +1,3 @@\n a\n\n-b\n+c\n", "a\n\nc\n"),
Arguments.of("space-context-line", "a\n\nb\n", "@@ -1,3 +1,3 @@\n a\n \n-b\n+c\n", "a\n\nc\n"),
Arguments.of("crlf", "a\r\nb\r\n", "@@ -1,2 +1,2 @@\n a\r\n-b\r\n+c\r\n", "a\r\nc\r\n"),
Arguments.of("header-like-line", "x\n-- y\n", "--- old.txt\n+++ new.txt\n@@ -1,2 +1 @@\n x\n--- y\n", "x\n"),
Arguments.of("non-ascii", "caf\u00e9\n", "@@ -1 +1 @@\n-caf\u00e9\n+na\u00efve\n", "na\u00efve\n"));
}
// name, the old text, the patch, the kind of the error
static Stream<Arguments> errors() {
return Stream.of(
Arguments.of("mismatch", "a\nb\nc\n", "@@ -1,3 +1,3 @@\n a\n-x\n+y\n c\n", "mismatch"),
Arguments.of("malformed", "a\nb\nc\n", "@@ -1,3 +1,3 @@\n a\n-b\n", "malformed"),
Arguments.of("no-hunk", "a\n", "no hunk here\n", "malformed"),
Arguments.of("bad-mark", "a\n", "@@ -1 +1 @@\n*a\n", "malformed"),
Arguments.of("past-the-end", "a\n", "@@ -2 +2 @@\n-a\n+b\n", "mismatch"));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void apply(String name, String oldText, String patch, String want) {
assertEquals(want, ApplyPatch.apply(oldText, patch), name);
}
@ParameterizedTest(name = "{0}")
@MethodSource("errors")
void error(String name, String oldText, String patch, String kind) {
ApplyPatch.PatchException e =
assertThrows(ApplyPatch.PatchException.class, () -> ApplyPatch.apply(oldText, patch), name);
assertEquals(kind, e.kind().name().toLowerCase(java.util.Locale.ROOT), name);
}
@Test
void manyHunks() {
// 1000 lines, and 10 hunks with no context change 10 of them.
StringBuilder oldText = new StringBuilder();
StringBuilder patch = new StringBuilder();
StringBuilder want = new StringBuilder();
for (int i = 0; i < 1000; i++) {
oldText.append(i).append('\n');
if (i % 100 == 50) {
patch.append("@@ -" + (i + 1) + " +" + (i + 1) + " @@\n-" + i + "\n+x" + i + "\n");
want.append('x');
}
want.append(i).append('\n');
}
assertEquals(want.toString(), ApplyPatch.apply(oldText.toString(), patch.toString()));
}
@Test
void applyFile() throws IOException {
Files.writeString(dir.resolve("old.txt"), "a\r\nb\r\n", StandardCharsets.UTF_8);
Files.writeString(dir.resolve("a.patch"), "@@ -1,2 +1,2 @@\n a\r\n-b\r\n+c\r\n", StandardCharsets.UTF_8);
assertEquals("a\r\nc\r\n", ApplyPatch.applyFile(dir.resolve("old.txt"), dir.resolve("a.patch")));
}
@Test
void notFound() throws IOException {
Files.writeString(dir.resolve("a.patch"), "@@ -1 +1 @@\n-a\n+b\n", StandardCharsets.UTF_8);
assertThrows(
NoSuchFileException.class,
() -> ApplyPatch.applyFile(dir.resolve("missing.txt"), dir.resolve("a.patch")));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-patch/.
#include "apply_a_patch.h"
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// A line of a text: a pointer into the text and a length.
struct span {
const char *s;
size_t len;
};
// split_lines splits text after each LF into a new array, and sets *n to the
// number of lines. With keep_lf, each line keeps its LF. A last line with no
// LF is a line too. It returns NULL if there is not enough memory.
static struct span *split_lines(const char *text, size_t *n, int keep_lf) {
size_t count = 0;
for (const char *p = text; *p != '\0'; count++) {
const char *lf = strchr(p, '\n');
p = lf != NULL ? lf + 1 : p + strlen(p);
}
struct span *lines = malloc((count + 1) * sizeof *lines);
if (lines == NULL) {
return NULL;
}
size_t k = 0;
for (const char *p = text; *p != '\0'; k++) {
const char *lf = strchr(p, '\n');
size_t len = lf != NULL ? (size_t)(lf - p) : strlen(p);
lines[k].s = p;
lines[k].len = len + (lf != NULL && keep_lf);
p += len + (lf != NULL);
}
*n = count;
return lines;
}
// number reads a decimal number at s[*k], before the index end. It returns 0
// if there is no digit or the number is too large.
static int number(const char *s, size_t end, size_t *k, size_t *v) {
if (*k >= end || s[*k] < '0' || s[*k] > '9') {
return 0;
}
*v = 0;
for (; *k < end && s[*k] >= '0' && s[*k] <= '9'; (*k)++) {
size_t d = (size_t)(s[*k] - '0');
if (*v > (SIZE_MAX - d) / 10) {
return 0;
}
*v = *v * 10 + d;
}
return 1;
}
// prefix reads the text t at s[*k], before the index end.
static int prefix(const char *s, size_t end, size_t *k, const char *t) {
size_t n = strlen(t);
if (end - *k < n || memcmp(s + *k, t, n) != 0) {
return 0;
}
*k += n;
return 1;
}
// range reads a start and an optional comma and count. A missing count is 1.
static int range(const char *s, size_t end, size_t *k, size_t *start, size_t *count) {
if (!number(s, end, k, start)) {
return 0;
}
*count = 1;
return !prefix(s, end, k, ",") || number(s, end, k, count);
}
// hunk_header reads a line such as @@ -1,3 +1,4 @@ and the text after it.
static int hunk_header(struct span h, size_t *old_start, size_t *old_count, size_t *new_count) {
size_t k = 0, new_start;
return prefix(h.s, h.len, &k, "@@ -") && range(h.s, h.len, &k, old_start, old_count) &&
prefix(h.s, h.len, &k, " +") && range(h.s, h.len, &k, &new_start, new_count) &&
prefix(h.s, h.len, &k, " @@");
}
static char mark_of(struct span l) { return l.len == 0 ? ' ' : l.s[0]; }
static enum patch_status apply(const struct span *lines, size_t nl, const struct span *p, size_t np, char *out,
size_t *line) {
size_t used = 0, cur = 0, hunks = 0, i = 0;
while (i < np) {
if (p[i].len < 2 || p[i].s[0] != '@' || p[i].s[1] != '@') {
i++; // a header line, or another line outside a hunk
continue;
}
size_t old_start, old_count, new_count;
*line = i + 1;
if (!hunk_header(p[i], &old_start, &old_count, &new_count)) {
return PATCH_MALFORMED;
}
hunks++;
// An empty range starts after the line old_start.
if (old_count > 0 && old_start == 0) {
return PATCH_MALFORMED;
}
size_t pos = old_count > 0 ? old_start - 1 : old_start;
if (pos < cur || pos > nl) {
return PATCH_MISMATCH;
}
for (; cur < pos; cur++) {
memcpy(out + used, lines[cur].s, lines[cur].len);
used += lines[cur].len;
}
// The first pass checks the marks and the counts, and finds the end.
size_t first = ++i, old_left = old_count, new_left = new_count, body = 0;
while (old_left > 0 || new_left > 0) {
*line = i + 1;
if (i == np) {
*line = i;
return PATCH_MALFORMED;
}
char mark = mark_of(p[i]);
if (mark == '\\') {
if (body == 0) {
return PATCH_MALFORMED;
}
i++;
continue;
}
if (mark != ' ' && mark != '-' && mark != '+') {
return PATCH_MALFORMED;
}
if (mark != '+' && old_left-- == 0) {
return PATCH_MALFORMED;
}
if (mark != '-' && new_left-- == 0) {
return PATCH_MALFORMED;
}
body++;
i++;
}
if (i < np && body > 0 && p[i].len > 0 && p[i].s[0] == '\\') {
i++;
}
// The second pass applies the lines. A line before a backslash line
// has no LF.
for (size_t k = first; k < i; k++) {
char mark = mark_of(p[k]);
if (mark == '\\') {
continue;
}
const char *text = p[k].len > 0 ? p[k].s + 1 : p[k].s;
size_t tlen = p[k].len > 0 ? p[k].len - 1 : 0;
int lf = !(k + 1 < i && p[k + 1].len > 0 && p[k + 1].s[0] == '\\');
if (mark != '+') {
if (cur == nl || lines[cur].len != tlen + (size_t)lf || memcmp(lines[cur].s, text, tlen) != 0 ||
(lf && lines[cur].s[tlen] != '\n')) {
*line = k + 1;
return PATCH_MISMATCH;
}
cur++;
}
if (mark != '-') {
memcpy(out + used, text, tlen);
used += tlen;
if (lf) {
out[used++] = '\n';
}
}
}
}
if (hunks == 0) {
*line = np;
return PATCH_MALFORMED;
}
for (; cur < nl; cur++) {
memcpy(out + used, lines[cur].s, lines[cur].len);
used += lines[cur].len;
}
out[used] = '\0';
return PATCH_OK;
}
enum patch_status apply_patch(const char *old_text, const char *patch, char **out, size_t *line) {
*out = NULL;
*line = 0;
size_t old_len = strlen(old_text), patch_len = strlen(patch);
// Each byte of the result is a byte of old_text, a byte of a + line of
// the patch, or the LF of such a line, so the result fits in old_len +
// patch_len bytes.
if (old_len > SIZE_MAX - patch_len - 1) {
return PATCH_NOMEM;
}
size_t nl, np;
struct span *lines = split_lines(old_text, &nl, 1);
struct span *p = split_lines(patch, &np, 0);
char *result = malloc(old_len + patch_len + 1);
enum patch_status st = PATCH_NOMEM;
if (lines != NULL && p != NULL && result != NULL) {
st = apply(lines, nl, p, np, result, line);
}
free(lines);
free(p);
if (st == PATCH_OK) {
*out = result;
} else {
free(result);
}
return st;
}
// 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;
}
enum patch_status apply_patch_file(const char *path, const char *patch_path, char **out, size_t *line) {
*out = NULL;
*line = 0;
char *old_text = read_file(path);
if (old_text == NULL) {
return errno == ENOMEM ? PATCH_NOMEM : PATCH_IO;
}
char *patch = read_file(patch_path);
if (patch == NULL) {
int saved = errno;
free(old_text);
errno = saved;
return saved == ENOMEM ? PATCH_NOMEM : PATCH_IO;
}
enum patch_status st = apply_patch(old_text, patch, out, line);
free(old_text);
free(patch);
return st;
}
apply_a_patch.h 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-patch/.
#ifndef APPLY_A_PATCH_H
#define APPLY_A_PATCH_H
#include <stddef.h>
enum patch_status {
PATCH_OK,
PATCH_IO, // a file cannot be read, and errno tells why
PATCH_NOMEM, // there is not enough memory
PATCH_MALFORMED, // the patch is not a correct unified diff
PATCH_MISMATCH, // a hunk does not match the text
};
// apply_patch applies the unified diff patch to old_text, with no fuzz and no
// offset. Each hunk must match the lines of old_text at the start of its old
// range. On PATCH_OK, *out is a new string that the caller frees with free.
// On PATCH_MALFORMED and PATCH_MISMATCH, *line is the number of the line of
// the patch where the error is.
enum patch_status apply_patch(const char *old_text, const char *patch, char **out, size_t *line);
// apply_patch_file is apply_patch of the two files at path and patch_path.
// On PATCH_IO, errno is the error of fopen, or EIO for a read error.
enum patch_status apply_patch_file(const char *path, const char *patch_path, char **out, size_t *line);
#endif
test_apply_a_patch.c 138 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-patch/.
// mkdtemp and rmdir are POSIX functions.
#define _POSIX_C_SOURCE 200809L
#include "apply_a_patch.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
struct test_case {
const char *name, *old_text, *patch, *want;
};
static const struct test_case cases[] = {
{"change-a-line", "a\nb\nc\n", "--- old.txt\n+++ new.txt\n@@ -1,3 +1,3 @@\n a\n-b\n+B\n c\n", "a\nB\nc\n"},
{"two-hunks", "apple\nbanana\ncherry\ndate\nelder\nfig\ngrape\n", "--- old.txt\n+++ new.txt\n@@ -1,3 +1,3 @@\n apple\n-banana\n+blueberry\n cherry\n@@ -6,2 +6,2 @@\n fig\n-grape\n+guava\n", "apple\nblueberry\ncherry\ndate\nelder\nfig\nguava\n"},
{"git-header", "def main():\n print(1)\n", "diff --git a/main.py b/main.py\nindex 1234567..89abcde 100644\n--- a/main.py\n+++ b/main.py\n@@ -1,2 +1,2 @@ def main():\n def main():\n- print(1)\n+ print(2)\n", "def main():\n print(2)\n"},
{"add-at-end", "a\n", "@@ -1 +1,2 @@\n a\n+b\n", "a\nb\n"},
{"old-empty", "", "--- /dev/null\n+++ b.txt\n@@ -0,0 +1,2 @@\n+a\n+b\n", "a\nb\n"},
{"delete-all", "a\nb\n", "@@ -1,2 +0,0 @@\n-a\n-b\n", ""},
{"no-count", "a\nb\nc\n", "@@ -2 +2 @@\n-b\n+x\n", "a\nx\nc\n"},
{"zero-context", "apple\nbanana\ncherry\ndate\nelder\nfig\ngrape\n", "@@ -3 +3 @@\n-cherry\n+coconut\n@@ -6 +5,0 @@\n-fig\n@@ -7,0 +7 @@\n+honeydew\n", "apple\nbanana\ncoconut\ndate\nelder\ngrape\nhoneydew\n"},
{"insert-at-start", "b\n", "@@ -0,0 +1 @@\n+a\n", "a\nb\n"},
{"old-no-final-newline", "a\nb", "@@ -1,2 +1,2 @@\n a\n-b\n\\ No newline at end of file\n+b\n", "a\nb\n"},
{"new-no-final-newline", "a\nb\n", "@@ -1,2 +1,2 @@\n a\n-b\n+b\n\\ No newline at end of file\n", "a\nb"},
{"empty-context-line", "a\n\nb\n", "@@ -1,3 +1,3 @@\n a\n\n-b\n+c\n", "a\n\nc\n"},
{"space-context-line", "a\n\nb\n", "@@ -1,3 +1,3 @@\n a\n \n-b\n+c\n", "a\n\nc\n"},
{"crlf", "a\r\nb\r\n", "@@ -1,2 +1,2 @@\n a\r\n-b\r\n+c\r\n", "a\r\nc\r\n"},
{"header-like-line", "x\n-- y\n", "--- old.txt\n+++ new.txt\n@@ -1,2 +1 @@\n x\n--- y\n", "x\n"},
{"non-ascii", "caf\303\251\n", "@@ -1 +1 @@\n-caf\303\251\n+na\303\257ve\n", "na\303\257ve\n"},
};
struct error_case {
const char *name, *old_text, *patch;
enum patch_status want;
};
static const struct error_case errors[] = {
{"mismatch", "a\nb\nc\n", "@@ -1,3 +1,3 @@\n a\n-x\n+y\n c\n", PATCH_MISMATCH},
{"malformed", "a\nb\nc\n", "@@ -1,3 +1,3 @@\n a\n-b\n", PATCH_MALFORMED},
{"no-hunk", "a\n", "no hunk here\n", PATCH_MALFORMED},
{"bad-mark", "a\n", "@@ -1 +1 @@\n*a\n", PATCH_MALFORMED},
{"past-the-end", "a\n", "@@ -2 +2 @@\n-a\n+b\n", PATCH_MISMATCH},
};
// 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;
char *got;
size_t line;
for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
const struct test_case *c = &cases[i];
enum patch_status st = apply_patch(c->old_text, c->patch, &got, &line);
if (st != PATCH_OK || strcmp(got, c->want) != 0) {
fprintf(stderr, "FAIL %s: status %d\n", c->name, (int)st);
failures++;
}
free(got);
}
for (size_t i = 0; i < sizeof errors / sizeof errors[0]; i++) {
const struct error_case *c = &errors[i];
enum patch_status st = apply_patch(c->old_text, c->patch, &got, &line);
if (st != c->want || got != NULL) {
fprintf(stderr, "FAIL %s: status %d\n", c->name, (int)st);
failures++;
}
}
// 1000 lines, and 10 hunks with no context change 10 of them.
enum { CAP = 32000 };
char *old_text = malloc(CAP), *patch = malloc(CAP), *want = malloc(CAP);
if (old_text == NULL || patch == NULL || want == NULL) {
return 1;
}
size_t old_len = 0, patch_len = 0, want_len = 0;
for (int i = 0; i < 1000; i++) {
old_len += (size_t)snprintf(old_text + old_len, CAP - old_len, "%d\n", i);
if (i % 100 == 50) {
patch_len += (size_t)snprintf(patch + patch_len, CAP - patch_len, "@@ -%d +%d @@\n-%d\n+x%d\n", i + 1,
i + 1, i, i);
want_len += (size_t)snprintf(want + want_len, CAP - want_len, "x%d\n", i);
} else {
want_len += (size_t)snprintf(want + want_len, CAP - want_len, "%d\n", i);
}
}
if (apply_patch(old_text, patch, &got, &line) != PATCH_OK || strcmp(got, want) != 0) {
fprintf(stderr, "FAIL many-hunks\n");
failures++;
}
free(got);
free(old_text);
free(patch);
free(want);
char dir[] = "/tmp/apply-a-patch-XXXXXX";
if (mkdtemp(dir) == NULL) {
perror("mkdtemp");
return 1;
}
char old_path[64], patch_path[64], missing[64];
snprintf(old_path, sizeof old_path, "%s/old.txt", dir);
snprintf(patch_path, sizeof patch_path, "%s/a.patch", dir);
snprintf(missing, sizeof missing, "%s/missing.txt", dir);
got = NULL;
if (write_file(old_path, "a\r\nb\r\n") != 0 || write_file(patch_path, "@@ -1,2 +1,2 @@\n a\r\n-b\r\n+c\r\n") != 0 ||
apply_patch_file(old_path, patch_path, &got, &line) != PATCH_OK || strcmp(got, "a\r\nc\r\n") != 0) {
fprintf(stderr, "FAIL apply-patch-file\n");
failures++;
}
free(got);
errno = 0;
if (apply_patch_file(missing, patch_path, &got, &line) != PATCH_IO || errno != ENOENT) {
fprintf(stderr, "FAIL not-found\n");
failures++;
}
remove(old_path);
remove(patch_path);
rmdir(dir);
if (failures == 0) {
printf("ok\n");
}
return failures == 0 ? 0 : 1;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-patch/.
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
/// <summary>The patch is malformed, or a hunk does not match the text.</summary>
public sealed class PatchException(PatchException.Kinds kind, int line)
: Exception($"{kind.ToString().ToLowerInvariant()} at line {line} of the patch")
{
/// <summary>The kinds of the error.</summary>
public enum Kinds { Malformed, Mismatch }
public Kinds Kind { get; } = kind;
/// <summary>The number of the line of the patch where the error is.</summary>
public int Line { get; } = line;
}
/// <summary>Applies a unified diff to a text, with no fuzz and no offset.</summary>
public static partial class ApplyPatch
{
[GeneratedRegex(@"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@", RegexOptions.CultureInvariant)]
private static partial Regex Hunk();
/// <summary>Splits text after each LF. Each line keeps its LF, and a last line with no LF is a line too.</summary>
public static List<string> SplitLines(string text)
{
var lines = new List<string>();
int start = 0;
while (start < text.Length)
{
int end = text.IndexOf('\n', start);
end = end < 0 ? text.Length : end + 1;
lines.Add(text[start..end]);
start = end;
}
return lines;
}
private static PatchException Malformed(int line) => new(PatchException.Kinds.Malformed, line);
private static PatchException Mismatch(int line) => new(PatchException.Kinds.Mismatch, line);
private static int Count(Group g) => g.Success ? int.Parse(g.Value, CultureInfo.InvariantCulture) : 1;
/// <summary>
/// Returns the text that the unified diff patch makes from the text oldText. Each hunk must
/// match the lines of oldText at the start of its old range. Throws PatchException if the
/// patch is malformed or a hunk does not match.
/// </summary>
public static string Apply(string oldText, string patch)
{
List<string> lines = SplitLines(oldText);
// The lines of the patch, with no LF. A CR stays in its line.
List<string> p = SplitLines(patch).ConvertAll(l => l.EndsWith('\n') ? l[..^1] : l);
var output = new StringBuilder();
int cur = 0; // the index of the next line of oldText to use
int hunks = 0;
int i = 0;
while (i < p.Count)
{
if (!p[i].StartsWith("@@", StringComparison.Ordinal))
{
i++; // a header line, or another line outside a hunk
continue;
}
Match m = Hunk().Match(p[i]);
if (!m.Success)
{
throw Malformed(i + 1);
}
int oldStart, oldCount, newCount;
try
{
oldStart = int.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture);
oldCount = Count(m.Groups[2]);
newCount = Count(m.Groups[4]);
}
catch (OverflowException)
{
throw Malformed(i + 1);
}
hunks++;
// An empty range starts after the line oldStart.
int pos = oldCount > 0 ? oldStart - 1 : oldStart;
if (pos < 0)
{
throw Malformed(i + 1);
}
if (pos < cur || pos > lines.Count)
{
throw Mismatch(i + 1);
}
for (; cur < pos; cur++)
{
output.Append(lines[cur]);
}
i++;
// The mark, the text, the number in the patch and the end of each line: an LF, or ""
// before a backslash line.
var body = new List<(char Mark, string Text, int Number)>();
var ends = new List<string>();
int oldLeft = oldCount, newLeft = newCount;
while (oldLeft > 0 || newLeft > 0)
{
if (i == p.Count)
{
throw Malformed(i);
}
string line = p[i];
char mark = line.Length == 0 ? ' ' : line[0];
if (mark == '\\')
{
if (body.Count == 0)
{
throw Malformed(i + 1);
}
ends[^1] = ""; // the line before has no LF
i++;
continue;
}
if (mark is not (' ' or '-' or '+'))
{
throw Malformed(i + 1);
}
if (mark != '+')
{
oldLeft--;
}
if (mark != '-')
{
newLeft--;
}
if (oldLeft < 0 || newLeft < 0)
{
throw Malformed(i + 1);
}
body.Add((mark, line.Length == 0 ? "" : line[1..], i + 1));
ends.Add("\n");
i++;
}
if (i < p.Count && p[i].StartsWith('\\') && body.Count > 0)
{
ends[^1] = "";
i++;
}
for (int k = 0; k < body.Count; k++)
{
var (mark, text, number) = body[k];
string line = text + ends[k];
if (mark != '+')
{
if (cur == lines.Count || !string.Equals(lines[cur], line, StringComparison.Ordinal))
{
throw Mismatch(number);
}
cur++;
}
if (mark != '-')
{
output.Append(line);
}
}
}
if (hunks == 0)
{
throw Malformed(p.Count);
}
for (; cur < lines.Count; cur++)
{
output.Append(lines[cur]);
}
return output.ToString();
}
/// <summary>
/// Returns Apply of the two UTF-8 files. Throws FileNotFoundException if a file does not exist,
/// and PatchException.
/// </summary>
public static string ApplyFile(string path, string patchPath) =>
Apply(File.ReadAllText(path, Encoding.UTF8), File.ReadAllText(patchPath, Encoding.UTF8));
}
ApplyPatchTests.cs 86 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-patch/.
using System.Text;
using Xunit;
public sealed class ApplyPatchTests : IDisposable
{
private readonly string dir = Directory.CreateTempSubdirectory("apply-a-patch-").FullName;
public void Dispose() => Directory.Delete(dir, recursive: true);
// name, the old text, the patch, the new text
public static TheoryData<string, string, string, string> Cases => new()
{
{ "change-a-line", "a\nb\nc\n", "--- old.txt\n+++ new.txt\n@@ -1,3 +1,3 @@\n a\n-b\n+B\n c\n", "a\nB\nc\n" },
{ "two-hunks", "apple\nbanana\ncherry\ndate\nelder\nfig\ngrape\n", "--- old.txt\n+++ new.txt\n@@ -1,3 +1,3 @@\n apple\n-banana\n+blueberry\n cherry\n@@ -6,2 +6,2 @@\n fig\n-grape\n+guava\n", "apple\nblueberry\ncherry\ndate\nelder\nfig\nguava\n" },
{ "git-header", "def main():\n print(1)\n", "diff --git a/main.py b/main.py\nindex 1234567..89abcde 100644\n--- a/main.py\n+++ b/main.py\n@@ -1,2 +1,2 @@ def main():\n def main():\n- print(1)\n+ print(2)\n", "def main():\n print(2)\n" },
{ "add-at-end", "a\n", "@@ -1 +1,2 @@\n a\n+b\n", "a\nb\n" },
{ "old-empty", "", "--- /dev/null\n+++ b.txt\n@@ -0,0 +1,2 @@\n+a\n+b\n", "a\nb\n" },
{ "delete-all", "a\nb\n", "@@ -1,2 +0,0 @@\n-a\n-b\n", "" },
{ "no-count", "a\nb\nc\n", "@@ -2 +2 @@\n-b\n+x\n", "a\nx\nc\n" },
{ "zero-context", "apple\nbanana\ncherry\ndate\nelder\nfig\ngrape\n", "@@ -3 +3 @@\n-cherry\n+coconut\n@@ -6 +5,0 @@\n-fig\n@@ -7,0 +7 @@\n+honeydew\n", "apple\nbanana\ncoconut\ndate\nelder\ngrape\nhoneydew\n" },
{ "insert-at-start", "b\n", "@@ -0,0 +1 @@\n+a\n", "a\nb\n" },
{ "old-no-final-newline", "a\nb", "@@ -1,2 +1,2 @@\n a\n-b\n\\ No newline at end of file\n+b\n", "a\nb\n" },
{ "new-no-final-newline", "a\nb\n", "@@ -1,2 +1,2 @@\n a\n-b\n+b\n\\ No newline at end of file\n", "a\nb" },
{ "empty-context-line", "a\n\nb\n", "@@ -1,3 +1,3 @@\n a\n\n-b\n+c\n", "a\n\nc\n" },
{ "space-context-line", "a\n\nb\n", "@@ -1,3 +1,3 @@\n a\n \n-b\n+c\n", "a\n\nc\n" },
{ "crlf", "a\r\nb\r\n", "@@ -1,2 +1,2 @@\n a\r\n-b\r\n+c\r\n", "a\r\nc\r\n" },
{ "header-like-line", "x\n-- y\n", "--- old.txt\n+++ new.txt\n@@ -1,2 +1 @@\n x\n--- y\n", "x\n" },
{ "non-ascii", "caf\u00e9\n", "@@ -1 +1 @@\n-caf\u00e9\n+na\u00efve\n", "na\u00efve\n" },
};
// name, the old text, the patch, the kind of the error
public static TheoryData<string, string, string, PatchException.Kinds> Errors => new()
{
{ "mismatch", "a\nb\nc\n", "@@ -1,3 +1,3 @@\n a\n-x\n+y\n c\n", PatchException.Kinds.Mismatch },
{ "malformed", "a\nb\nc\n", "@@ -1,3 +1,3 @@\n a\n-b\n", PatchException.Kinds.Malformed },
{ "no-hunk", "a\n", "no hunk here\n", PatchException.Kinds.Malformed },
{ "bad-mark", "a\n", "@@ -1 +1 @@\n*a\n", PatchException.Kinds.Malformed },
{ "past-the-end", "a\n", "@@ -2 +2 @@\n-a\n+b\n", PatchException.Kinds.Mismatch },
};
[Theory]
[MemberData(nameof(Cases))]
public void Apply(string name, string oldText, string patch, string want)
{
_ = name;
Assert.Equal(want, ApplyPatch.Apply(oldText, patch));
}
[Theory]
[MemberData(nameof(Errors))]
public void Error(string name, string oldText, string patch, PatchException.Kinds kind)
{
_ = name;
PatchException e = Assert.Throws<PatchException>(() => ApplyPatch.Apply(oldText, patch));
Assert.Equal(kind, e.Kind);
}
[Fact]
public void ManyHunks()
{
// 1000 lines, and 10 hunks with no context change 10 of them.
string oldText = string.Concat(Enumerable.Range(0, 1000).Select(i => $"{i}\n"));
string patch = string.Concat(Enumerable.Range(0, 10).Select(k => k * 100 + 50).Select(i => $"@@ -{i + 1} +{i + 1} @@\n-{i}\n+x{i}\n"));
string want = string.Concat(Enumerable.Range(0, 1000).Select(i => i % 100 == 50 ? $"x{i}\n" : $"{i}\n"));
Assert.Equal(want, ApplyPatch.Apply(oldText, patch));
}
[Fact]
public void ApplyFile()
{
// UTF8Encoding(false) writes no byte order mark.
File.WriteAllText(Path.Combine(dir, "old.txt"), "a\r\nb\r\n", new UTF8Encoding(false));
File.WriteAllText(Path.Combine(dir, "a.patch"), "@@ -1,2 +1,2 @@\n a\r\n-b\r\n+c\r\n", new UTF8Encoding(false));
Assert.Equal("a\r\nc\r\n", ApplyPatch.ApplyFile(Path.Combine(dir, "old.txt"), Path.Combine(dir, "a.patch")));
}
[Fact]
public void NotFound()
{
File.WriteAllText(Path.Combine(dir, "a.patch"), "@@ -1 +1 @@\n-a\n+b\n", new UTF8Encoding(false));
Assert.Throws<FileNotFoundException>(() => ApplyPatch.ApplyFile(Path.Combine(dir, "missing.txt"), Path.Combine(dir, "a.patch")));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-patch/.
import { readFileSync } from "node:fs";
const HUNK = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
/**
* The patch is malformed, or a hunk does not match the text. kind is
* "malformed" or "mismatch", and line is the number of the line of the patch
* where the error is.
*/
export class PatchError extends Error {
constructor(kind, line) {
super(`${kind} at line ${line} of the patch`);
this.name = "PatchError";
this.kind = kind;
this.line = line;
}
}
/** Splits text after each LF. Each line keeps its LF, and a last line with no LF is a line too. */
export function splitLines(text) {
const lines = [];
let start = 0;
while (start < text.length) {
let end = text.indexOf("\n", start);
end = end < 0 ? text.length : end + 1;
lines.push(text.slice(start, end));
start = end;
}
return lines;
}
/**
* Returns the text that the unified diff patch makes from the text oldText.
* Each hunk must match the lines of oldText at the start of its old range.
* Throws PatchError if the patch is malformed or a hunk does not match.
*/
export function applyPatch(oldText, patch) {
const lines = splitLines(oldText);
// The lines of the patch, with no LF. A CR stays in its line.
const p = splitLines(patch).map((l) => (l.endsWith("\n") ? l.slice(0, -1) : l));
const out = [];
let cur = 0; // the index of the next line of oldText to use
let hunks = 0;
let i = 0;
while (i < p.length) {
if (!p[i].startsWith("@@")) {
i++; // a header line, or another line outside a hunk
continue;
}
const m = HUNK.exec(p[i]);
if (m === null) throw new PatchError("malformed", i + 1);
hunks++;
const oldStart = Number(m[1]);
const oldCount = m[2] === undefined ? 1 : Number(m[2]);
const newCount = m[4] === undefined ? 1 : Number(m[4]);
// An empty range starts after the line oldStart.
const pos = oldCount > 0 ? oldStart - 1 : oldStart;
if (pos < 0) throw new PatchError("malformed", i + 1);
if (pos < cur || pos > lines.length) throw new PatchError("mismatch", i + 1);
for (; cur < pos; cur++) out.push(lines[cur]);
i++;
// The mark, the text, the number in the patch and the end of each line:
// an LF, or "" before a backslash line.
const body = [];
let oldLeft = oldCount;
let newLeft = newCount;
while (oldLeft > 0 || newLeft > 0) {
if (i === p.length) throw new PatchError("malformed", i);
const line = p[i];
const mark = line === "" ? " " : line[0];
if (mark === "\\") {
if (body.length === 0) throw new PatchError("malformed", i + 1);
body[body.length - 1].end = ""; // the line before has no LF
i++;
continue;
}
if (!" -+".includes(mark)) throw new PatchError("malformed", i + 1);
if (mark !== "+") oldLeft--;
if (mark !== "-") newLeft--;
if (oldLeft < 0 || newLeft < 0) throw new PatchError("malformed", i + 1);
body.push({ mark, text: line.slice(1), number: i + 1, end: "\n" });
i++;
}
if (i < p.length && p[i].startsWith("\\") && body.length > 0) {
body[body.length - 1].end = "";
i++;
}
for (const { mark, text, number, end } of body) {
const line = text + end;
if (mark !== "+") {
if (cur === lines.length || lines[cur] !== line) throw new PatchError("mismatch", number);
cur++;
}
if (mark !== "-") out.push(line);
}
}
if (hunks === 0) throw new PatchError("malformed", p.length);
for (; cur < lines.length; cur++) out.push(lines[cur]);
return out.join("");
}
/**
* Returns applyPatch of the two UTF-8 files. Throws an error with the code
* ENOENT if a file does not exist, and PatchError.
*/
export function applyPatchFile(path, patchPath) {
return applyPatch(readFileSync(path, "utf8"), readFileSync(patchPath, "utf8"));
}
applyAPatch.test.js 80 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-patch/.
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 { PatchError, applyPatch, applyPatchFile } from "./applyAPatch.js";
// name: [the old text, the patch, the new text]
const CASES = {
"change-a-line": ["a\nb\nc\n", "--- old.txt\n+++ new.txt\n@@ -1,3 +1,3 @@\n a\n-b\n+B\n c\n", "a\nB\nc\n"],
"two-hunks": ["apple\nbanana\ncherry\ndate\nelder\nfig\ngrape\n", "--- old.txt\n+++ new.txt\n@@ -1,3 +1,3 @@\n apple\n-banana\n+blueberry\n cherry\n@@ -6,2 +6,2 @@\n fig\n-grape\n+guava\n", "apple\nblueberry\ncherry\ndate\nelder\nfig\nguava\n"],
"git-header": ["def main():\n print(1)\n", "diff --git a/main.py b/main.py\nindex 1234567..89abcde 100644\n--- a/main.py\n+++ b/main.py\n@@ -1,2 +1,2 @@ def main():\n def main():\n- print(1)\n+ print(2)\n", "def main():\n print(2)\n"],
"add-at-end": ["a\n", "@@ -1 +1,2 @@\n a\n+b\n", "a\nb\n"],
"old-empty": ["", "--- /dev/null\n+++ b.txt\n@@ -0,0 +1,2 @@\n+a\n+b\n", "a\nb\n"],
"delete-all": ["a\nb\n", "@@ -1,2 +0,0 @@\n-a\n-b\n", ""],
"no-count": ["a\nb\nc\n", "@@ -2 +2 @@\n-b\n+x\n", "a\nx\nc\n"],
"zero-context": ["apple\nbanana\ncherry\ndate\nelder\nfig\ngrape\n", "@@ -3 +3 @@\n-cherry\n+coconut\n@@ -6 +5,0 @@\n-fig\n@@ -7,0 +7 @@\n+honeydew\n", "apple\nbanana\ncoconut\ndate\nelder\ngrape\nhoneydew\n"],
"insert-at-start": ["b\n", "@@ -0,0 +1 @@\n+a\n", "a\nb\n"],
"old-no-final-newline": ["a\nb", "@@ -1,2 +1,2 @@\n a\n-b\n\\ No newline at end of file\n+b\n", "a\nb\n"],
"new-no-final-newline": ["a\nb\n", "@@ -1,2 +1,2 @@\n a\n-b\n+b\n\\ No newline at end of file\n", "a\nb"],
"empty-context-line": ["a\n\nb\n", "@@ -1,3 +1,3 @@\n a\n\n-b\n+c\n", "a\n\nc\n"],
"space-context-line": ["a\n\nb\n", "@@ -1,3 +1,3 @@\n a\n \n-b\n+c\n", "a\n\nc\n"],
"crlf": ["a\r\nb\r\n", "@@ -1,2 +1,2 @@\n a\r\n-b\r\n+c\r\n", "a\r\nc\r\n"],
"header-like-line": ["x\n-- y\n", "--- old.txt\n+++ new.txt\n@@ -1,2 +1 @@\n x\n--- y\n", "x\n"],
"non-ascii": ["caf\u00e9\n", "@@ -1 +1 @@\n-caf\u00e9\n+na\u00efve\n", "na\u00efve\n"],
};
// name: [the old text, the patch, the kind of the error]
const ERRORS = {
"mismatch": ["a\nb\nc\n", "@@ -1,3 +1,3 @@\n a\n-x\n+y\n c\n", "mismatch"],
"malformed": ["a\nb\nc\n", "@@ -1,3 +1,3 @@\n a\n-b\n", "malformed"],
};
for (const [name, [oldText, patch, want]] of Object.entries(CASES)) {
test(name, () => {
assert.equal(applyPatch(oldText, patch), want);
});
}
for (const [name, [oldText, patch, kind]] of Object.entries(ERRORS)) {
test(name, () => {
assert.throws(() => applyPatch(oldText, patch), (e) => e instanceof PatchError && e.kind === kind);
});
}
test("more-errors", () => {
const kind = (k) => (e) => e instanceof PatchError && e.kind === k;
assert.throws(() => applyPatch("a\n", "no hunk here\n"), kind("malformed"));
assert.throws(() => applyPatch("a\n", "@@ -1 +1 @@\n*a\n"), kind("malformed"));
assert.throws(() => applyPatch("a\n", "@@ -2 +2 @@\n-a\n+b\n"), kind("mismatch"));
});
test("many-hunks", () => {
// 1000 lines, and 10 hunks with no context change 10 of them.
const range = Array.from({ length: 1000 }, (_, i) => i);
const oldText = range.map((i) => `${i}\n`).join("");
let patch = "";
for (let i = 50; i < 1000; i += 100) patch += `@@ -${i + 1} +${i + 1} @@\n-${i}\n+x${i}\n`;
const want = range.map((i) => (i % 100 === 50 ? `x${i}\n` : `${i}\n`)).join("");
assert.equal(applyPatch(oldText, patch), want);
});
const dir = mkdtempSync(join(tmpdir(), "apply-a-patch-"));
after(() => rmSync(dir, { recursive: true, force: true }));
test("apply-patch-file", () => {
const [oldText, patch, want] = CASES["crlf"];
writeFileSync(join(dir, "old.txt"), oldText, "utf8");
writeFileSync(join(dir, "a.patch"), patch, "utf8");
assert.equal(applyPatchFile(join(dir, "old.txt"), join(dir, "a.patch")), want);
});
test("not-found", () => {
writeFileSync(join(dir, "a.patch"), "@@ -1 +1 @@\n-a\n+b\n", "utf8");
assert.throws(() => applyPatchFile(join(dir, "missing.txt"), join(dir, "a.patch")), { code: "ENOENT" });
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-patch/.
import { readFileSync } from "node:fs";
const HUNK = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
/**
* The patch is malformed, or a hunk does not match the text. kind is
* "malformed" or "mismatch", and line is the number of the line of the patch
* where the error is.
*/
export type PatchErrorKind = "malformed" | "mismatch";
export class PatchError extends Error {
readonly kind: PatchErrorKind;
readonly line: number;
constructor(kind: PatchErrorKind, line: number) {
super(`${kind} at line ${line} of the patch`);
this.name = "PatchError";
this.kind = kind;
this.line = line;
}
}
/** Splits text after each LF. Each line keeps its LF, and a last line with no LF is a line too. */
export function splitLines(text: string): string[] {
const lines: string[] = [];
let start = 0;
while (start < text.length) {
let end = text.indexOf("\n", start);
end = end < 0 ? text.length : end + 1;
lines.push(text.slice(start, end));
start = end;
}
return lines;
}
/**
* Returns the text that the unified diff patch makes from the text oldText.
* Each hunk must match the lines of oldText at the start of its old range.
* Throws PatchError if the patch is malformed or a hunk does not match.
*/
export function applyPatch(oldText: string, patch: string): string {
const lines = splitLines(oldText);
// The lines of the patch, with no LF. A CR stays in its line.
const p = splitLines(patch).map((l) => (l.endsWith("\n") ? l.slice(0, -1) : l));
const out: string[] = [];
let cur = 0; // the index of the next line of oldText to use
let hunks = 0;
let i = 0;
while (i < p.length) {
if (!p[i].startsWith("@@")) {
i++; // a header line, or another line outside a hunk
continue;
}
const m = HUNK.exec(p[i]);
if (m === null) throw new PatchError("malformed", i + 1);
hunks++;
const oldStart = Number(m[1]);
const oldCount = m[2] === undefined ? 1 : Number(m[2]);
const newCount = m[4] === undefined ? 1 : Number(m[4]);
// An empty range starts after the line oldStart.
const pos = oldCount > 0 ? oldStart - 1 : oldStart;
if (pos < 0) throw new PatchError("malformed", i + 1);
if (pos < cur || pos > lines.length) throw new PatchError("mismatch", i + 1);
for (; cur < pos; cur++) out.push(lines[cur]);
i++;
// The mark, the text, the number in the patch and the end of each line:
// an LF, or "" before a backslash line.
const body: { mark: string; text: string; number: number; end: string }[] = [];
let oldLeft = oldCount;
let newLeft = newCount;
while (oldLeft > 0 || newLeft > 0) {
if (i === p.length) throw new PatchError("malformed", i);
const line = p[i];
const mark = line === "" ? " " : line[0];
if (mark === "\\") {
if (body.length === 0) throw new PatchError("malformed", i + 1);
body[body.length - 1].end = ""; // the line before has no LF
i++;
continue;
}
if (!" -+".includes(mark)) throw new PatchError("malformed", i + 1);
if (mark !== "+") oldLeft--;
if (mark !== "-") newLeft--;
if (oldLeft < 0 || newLeft < 0) throw new PatchError("malformed", i + 1);
body.push({ mark, text: line.slice(1), number: i + 1, end: "\n" });
i++;
}
if (i < p.length && p[i].startsWith("\\") && body.length > 0) {
body[body.length - 1].end = "";
i++;
}
for (const { mark, text, number, end } of body) {
const line = text + end;
if (mark !== "+") {
if (cur === lines.length || lines[cur] !== line) throw new PatchError("mismatch", number);
cur++;
}
if (mark !== "-") out.push(line);
}
}
if (hunks === 0) throw new PatchError("malformed", p.length);
for (; cur < lines.length; cur++) out.push(lines[cur]);
return out.join("");
}
/**
* Returns applyPatch of the two UTF-8 files. Throws an error with the code
* ENOENT if a file does not exist, and PatchError.
*/
export function applyPatchFile(path: string, patchPath: string): string {
return applyPatch(readFileSync(path, "utf8"), readFileSync(patchPath, "utf8"));
}
applyAPatch.test.ts 80 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-patch/.
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 { PatchError, applyPatch, applyPatchFile, type PatchErrorKind } from "./applyAPatch.ts";
// name: [the old text, the patch, the new text]
const CASES: Record<string, [string, string, string]> = {
"change-a-line": ["a\nb\nc\n", "--- old.txt\n+++ new.txt\n@@ -1,3 +1,3 @@\n a\n-b\n+B\n c\n", "a\nB\nc\n"],
"two-hunks": ["apple\nbanana\ncherry\ndate\nelder\nfig\ngrape\n", "--- old.txt\n+++ new.txt\n@@ -1,3 +1,3 @@\n apple\n-banana\n+blueberry\n cherry\n@@ -6,2 +6,2 @@\n fig\n-grape\n+guava\n", "apple\nblueberry\ncherry\ndate\nelder\nfig\nguava\n"],
"git-header": ["def main():\n print(1)\n", "diff --git a/main.py b/main.py\nindex 1234567..89abcde 100644\n--- a/main.py\n+++ b/main.py\n@@ -1,2 +1,2 @@ def main():\n def main():\n- print(1)\n+ print(2)\n", "def main():\n print(2)\n"],
"add-at-end": ["a\n", "@@ -1 +1,2 @@\n a\n+b\n", "a\nb\n"],
"old-empty": ["", "--- /dev/null\n+++ b.txt\n@@ -0,0 +1,2 @@\n+a\n+b\n", "a\nb\n"],
"delete-all": ["a\nb\n", "@@ -1,2 +0,0 @@\n-a\n-b\n", ""],
"no-count": ["a\nb\nc\n", "@@ -2 +2 @@\n-b\n+x\n", "a\nx\nc\n"],
"zero-context": ["apple\nbanana\ncherry\ndate\nelder\nfig\ngrape\n", "@@ -3 +3 @@\n-cherry\n+coconut\n@@ -6 +5,0 @@\n-fig\n@@ -7,0 +7 @@\n+honeydew\n", "apple\nbanana\ncoconut\ndate\nelder\ngrape\nhoneydew\n"],
"insert-at-start": ["b\n", "@@ -0,0 +1 @@\n+a\n", "a\nb\n"],
"old-no-final-newline": ["a\nb", "@@ -1,2 +1,2 @@\n a\n-b\n\\ No newline at end of file\n+b\n", "a\nb\n"],
"new-no-final-newline": ["a\nb\n", "@@ -1,2 +1,2 @@\n a\n-b\n+b\n\\ No newline at end of file\n", "a\nb"],
"empty-context-line": ["a\n\nb\n", "@@ -1,3 +1,3 @@\n a\n\n-b\n+c\n", "a\n\nc\n"],
"space-context-line": ["a\n\nb\n", "@@ -1,3 +1,3 @@\n a\n \n-b\n+c\n", "a\n\nc\n"],
"crlf": ["a\r\nb\r\n", "@@ -1,2 +1,2 @@\n a\r\n-b\r\n+c\r\n", "a\r\nc\r\n"],
"header-like-line": ["x\n-- y\n", "--- old.txt\n+++ new.txt\n@@ -1,2 +1 @@\n x\n--- y\n", "x\n"],
"non-ascii": ["caf\u00e9\n", "@@ -1 +1 @@\n-caf\u00e9\n+na\u00efve\n", "na\u00efve\n"],
};
// name: [the old text, the patch, the kind of the error]
const ERRORS: Record<string, [string, string, PatchErrorKind]> = {
"mismatch": ["a\nb\nc\n", "@@ -1,3 +1,3 @@\n a\n-x\n+y\n c\n", "mismatch"],
"malformed": ["a\nb\nc\n", "@@ -1,3 +1,3 @@\n a\n-b\n", "malformed"],
};
for (const [name, [oldText, patch, want]] of Object.entries(CASES)) {
test(name, () => {
assert.equal(applyPatch(oldText, patch), want);
});
}
for (const [name, [oldText, patch, kind]] of Object.entries(ERRORS)) {
test(name, () => {
assert.throws(() => applyPatch(oldText, patch), (e: unknown) => e instanceof PatchError && e.kind === kind);
});
}
test("more-errors", () => {
const kind = (k: PatchErrorKind) => (e: unknown) => e instanceof PatchError && e.kind === k;
assert.throws(() => applyPatch("a\n", "no hunk here\n"), kind("malformed"));
assert.throws(() => applyPatch("a\n", "@@ -1 +1 @@\n*a\n"), kind("malformed"));
assert.throws(() => applyPatch("a\n", "@@ -2 +2 @@\n-a\n+b\n"), kind("mismatch"));
});
test("many-hunks", () => {
// 1000 lines, and 10 hunks with no context change 10 of them.
const range = Array.from({ length: 1000 }, (_, i) => i);
const oldText = range.map((i) => `${i}\n`).join("");
let patch = "";
for (let i = 50; i < 1000; i += 100) patch += `@@ -${i + 1} +${i + 1} @@\n-${i}\n+x${i}\n`;
const want = range.map((i) => (i % 100 === 50 ? `x${i}\n` : `${i}\n`)).join("");
assert.equal(applyPatch(oldText, patch), want);
});
const dir = mkdtempSync(join(tmpdir(), "apply-a-patch-"));
after(() => rmSync(dir, { recursive: true, force: true }));
test("apply-patch-file", () => {
const [oldText, patch, want] = CASES["crlf"];
writeFileSync(join(dir, "old.txt"), oldText, "utf8");
writeFileSync(join(dir, "a.patch"), patch, "utf8");
assert.equal(applyPatchFile(join(dir, "old.txt"), join(dir, "a.patch")), want);
});
test("not-found", () => {
writeFileSync(join(dir, "a.patch"), "@@ -1 +1 @@\n-a\n+b\n", "utf8");
assert.throws(() => applyPatchFile(join(dir, "missing.txt"), join(dir, "a.patch")), { code: "ENOENT" });
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-patch/.
// Package applypatch applies a unified diff to a text, with no fuzz and no
// offset.
package applypatch
import (
"errors"
"fmt"
"os"
"regexp"
"strconv"
"strings"
)
// ErrMalformed and ErrMismatch are the kinds of a PatchError.
var (
ErrMalformed = errors.New("malformed")
ErrMismatch = errors.New("mismatch")
)
// PatchError is a malformed patch, or a hunk that does not match the text.
// Kind is ErrMalformed or ErrMismatch, and Line is the number of the line of
// the patch where the error is.
type PatchError struct {
Kind error
Line int
}
func (e *PatchError) Error() string {
return fmt.Sprintf("%v at line %d of the patch", e.Kind, e.Line)
}
// Unwrap lets errors.Is find the kind.
func (e *PatchError) Unwrap() error { return e.Kind }
var hunkRe = regexp.MustCompile(`^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@`)
// SplitLines splits text after each LF. Each line keeps its LF, and a last
// line with no LF is a line too.
func SplitLines(text string) []string {
var lines []string
for text != "" {
end := strings.IndexByte(text, '\n') + 1
if end == 0 {
end = len(text)
}
lines = append(lines, text[:end])
text = text[end:]
}
return lines
}
type bodyLine struct {
mark byte
text string
number int
end string
}
// count returns the number in s, or 1 if s is empty.
func count(s string) (int, error) {
if s == "" {
return 1, nil
}
return strconv.Atoi(s)
}
// ApplyPatch returns the text that the unified diff patch makes from the text
// oldText. Each hunk must match the lines of oldText at the start of its old
// range. The error is a *PatchError if the patch is malformed or a hunk does
// not match.
func ApplyPatch(oldText, patch string) (string, error) {
lines := SplitLines(oldText)
// The lines of the patch, with no LF. A CR stays in its line.
p := SplitLines(patch)
for i := range p {
p[i] = strings.TrimSuffix(p[i], "\n")
}
var out strings.Builder
cur := 0 // the index of the next line of oldText to use
hunks := 0
i := 0
for i < len(p) {
if !strings.HasPrefix(p[i], "@@") {
i++ // a header line, or another line outside a hunk
continue
}
m := hunkRe.FindStringSubmatch(p[i])
if m == nil {
return "", &PatchError{ErrMalformed, i + 1}
}
oldStart, err1 := strconv.Atoi(m[1])
oldCount, err2 := count(m[2])
newCount, err3 := count(m[4])
if err1 != nil || err2 != nil || err3 != nil {
return "", &PatchError{ErrMalformed, i + 1}
}
hunks++
// An empty range starts after the line oldStart.
pos := oldStart
if oldCount > 0 {
pos--
}
if pos < 0 {
return "", &PatchError{ErrMalformed, i + 1}
}
if pos < cur || pos > len(lines) {
return "", &PatchError{ErrMismatch, i + 1}
}
for ; cur < pos; cur++ {
out.WriteString(lines[cur])
}
i++
// The end of each line is an LF, or "" before a backslash line.
var body []bodyLine
oldLeft, newLeft := oldCount, newCount
for oldLeft > 0 || newLeft > 0 {
if i == len(p) {
return "", &PatchError{ErrMalformed, i}
}
line := p[i]
mark, text := byte(' '), ""
if line != "" {
mark, text = line[0], line[1:]
}
if mark == '\\' {
if len(body) == 0 {
return "", &PatchError{ErrMalformed, i + 1}
}
body[len(body)-1].end = "" // the line before has no LF
i++
continue
}
switch mark {
case ' ':
oldLeft--
newLeft--
case '-':
oldLeft--
case '+':
newLeft--
default:
return "", &PatchError{ErrMalformed, i + 1}
}
if oldLeft < 0 || newLeft < 0 {
return "", &PatchError{ErrMalformed, i + 1}
}
body = append(body, bodyLine{mark, text, i + 1, "\n"})
i++
}
if i < len(p) && strings.HasPrefix(p[i], "\\") && len(body) > 0 {
body[len(body)-1].end = ""
i++
}
for _, b := range body {
line := b.text + b.end
if b.mark != '+' {
if cur == len(lines) || lines[cur] != line {
return "", &PatchError{ErrMismatch, b.number}
}
cur++
}
if b.mark != '-' {
out.WriteString(line)
}
}
}
if hunks == 0 {
return "", &PatchError{ErrMalformed, len(p)}
}
for ; cur < len(lines); cur++ {
out.WriteString(lines[cur])
}
return out.String(), nil
}
// ApplyPatchFile returns ApplyPatch of the two UTF-8 files. If a file does
// not exist, the error matches fs.ErrNotExist.
func ApplyPatchFile(path, patchPath string) (string, error) {
oldText, err := os.ReadFile(path)
if err != nil {
return "", err
}
patch, err := os.ReadFile(patchPath)
if err != nil {
return "", err
}
return ApplyPatch(string(oldText), string(patch))
}
apply_a_patch_test.go 117 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-patch/.
package applypatch
import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"testing"
)
// name: the old text, the patch, the new text
var cases = []struct{ name, old, patch, want string }{
{"change-a-line", "a\nb\nc\n", "--- old.txt\n+++ new.txt\n@@ -1,3 +1,3 @@\n a\n-b\n+B\n c\n", "a\nB\nc\n"},
{"two-hunks", "apple\nbanana\ncherry\ndate\nelder\nfig\ngrape\n", "--- old.txt\n+++ new.txt\n@@ -1,3 +1,3 @@\n apple\n-banana\n+blueberry\n cherry\n@@ -6,2 +6,2 @@\n fig\n-grape\n+guava\n", "apple\nblueberry\ncherry\ndate\nelder\nfig\nguava\n"},
{"git-header", "def main():\n print(1)\n", "diff --git a/main.py b/main.py\nindex 1234567..89abcde 100644\n--- a/main.py\n+++ b/main.py\n@@ -1,2 +1,2 @@ def main():\n def main():\n- print(1)\n+ print(2)\n", "def main():\n print(2)\n"},
{"add-at-end", "a\n", "@@ -1 +1,2 @@\n a\n+b\n", "a\nb\n"},
{"old-empty", "", "--- /dev/null\n+++ b.txt\n@@ -0,0 +1,2 @@\n+a\n+b\n", "a\nb\n"},
{"delete-all", "a\nb\n", "@@ -1,2 +0,0 @@\n-a\n-b\n", ""},
{"no-count", "a\nb\nc\n", "@@ -2 +2 @@\n-b\n+x\n", "a\nx\nc\n"},
{"zero-context", "apple\nbanana\ncherry\ndate\nelder\nfig\ngrape\n", "@@ -3 +3 @@\n-cherry\n+coconut\n@@ -6 +5,0 @@\n-fig\n@@ -7,0 +7 @@\n+honeydew\n", "apple\nbanana\ncoconut\ndate\nelder\ngrape\nhoneydew\n"},
{"insert-at-start", "b\n", "@@ -0,0 +1 @@\n+a\n", "a\nb\n"},
{"old-no-final-newline", "a\nb", "@@ -1,2 +1,2 @@\n a\n-b\n\\ No newline at end of file\n+b\n", "a\nb\n"},
{"new-no-final-newline", "a\nb\n", "@@ -1,2 +1,2 @@\n a\n-b\n+b\n\\ No newline at end of file\n", "a\nb"},
{"empty-context-line", "a\n\nb\n", "@@ -1,3 +1,3 @@\n a\n\n-b\n+c\n", "a\n\nc\n"},
{"space-context-line", "a\n\nb\n", "@@ -1,3 +1,3 @@\n a\n \n-b\n+c\n", "a\n\nc\n"},
{"crlf", "a\r\nb\r\n", "@@ -1,2 +1,2 @@\n a\r\n-b\r\n+c\r\n", "a\r\nc\r\n"},
{"header-like-line", "x\n-- y\n", "--- old.txt\n+++ new.txt\n@@ -1,2 +1 @@\n x\n--- y\n", "x\n"},
{"non-ascii", "caf\u00e9\n", "@@ -1 +1 @@\n-caf\u00e9\n+na\u00efve\n", "na\u00efve\n"},
}
// name: the old text, the patch, the kind of the error
var errorCases = []struct {
name, old, patch string
kind error
}{
{"mismatch", "a\nb\nc\n", "@@ -1,3 +1,3 @@\n a\n-x\n+y\n c\n", ErrMismatch},
{"malformed", "a\nb\nc\n", "@@ -1,3 +1,3 @@\n a\n-b\n", ErrMalformed},
{"no-hunk", "a\n", "no hunk here\n", ErrMalformed},
{"bad-mark", "a\n", "@@ -1 +1 @@\n*a\n", ErrMalformed},
{"past-the-end", "a\n", "@@ -2 +2 @@\n-a\n+b\n", ErrMismatch},
}
func TestApplyPatch(t *testing.T) {
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got, err := ApplyPatch(c.old, c.patch)
if err != nil || got != c.want {
t.Errorf("ApplyPatch = %q, %v; want %q", got, err, c.want)
}
})
}
}
func TestErrors(t *testing.T) {
for _, c := range errorCases {
t.Run(c.name, func(t *testing.T) {
_, err := ApplyPatch(c.old, c.patch)
var pe *PatchError
if !errors.As(err, &pe) || !errors.Is(err, c.kind) {
t.Errorf("ApplyPatch error = %v; want %v", err, c.kind)
}
})
}
}
func TestManyHunks(t *testing.T) {
// 1000 lines, and 10 hunks with no context change 10 of them.
var oldText, patch, want strings.Builder
for i := range 1000 {
fmt.Fprintf(&oldText, "%d\n", i)
if i%100 == 50 {
fmt.Fprintf(&patch, "@@ -%d +%d @@\n-%d\n+x%d\n", i+1, i+1, i, i)
fmt.Fprintf(&want, "x%d\n", i)
} else {
fmt.Fprintf(&want, "%d\n", i)
}
}
got, err := ApplyPatch(oldText.String(), patch.String())
if err != nil || got != want.String() {
t.Errorf("ApplyPatch: %v, or the text is wrong", err)
}
}
func TestApplyPatchFile(t *testing.T) {
dir := t.TempDir()
c := cases[13] // crlf
if c.name != "crlf" {
t.Fatalf("cases[13] is %s", c.name)
}
oldPath, patchPath := filepath.Join(dir, "old.txt"), filepath.Join(dir, "a.patch")
if err := os.WriteFile(oldPath, []byte(c.old), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(patchPath, []byte(c.patch), 0o600); err != nil {
t.Fatal(err)
}
got, err := ApplyPatchFile(oldPath, patchPath)
if err != nil || got != c.want {
t.Errorf("ApplyPatchFile = %q, %v; want %q", got, err, c.want)
}
}
func TestNotFound(t *testing.T) {
dir := t.TempDir()
patchPath := filepath.Join(dir, "a.patch")
if err := os.WriteFile(patchPath, []byte("@@ -1 +1 @@\n-a\n+b\n"), 0o600); err != nil {
t.Fatal(err)
}
if _, err := ApplyPatchFile(filepath.Join(dir, "missing.txt"), patchPath); !errors.Is(err, fs.ErrNotExist) {
t.Errorf("ApplyPatchFile error = %v; want fs.ErrNotExist", err)
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-patch/.
//! Applies a unified diff to a text, with no fuzz and no offset.
use std::fmt;
use std::fs;
use std::io;
use std::path::Path;
/// The error of `apply_patch` and `apply_patch_file`. `line` is the number of
/// the line of the patch where the error is.
#[derive(Debug)]
pub enum PatchError {
/// A file cannot be read.
Io(io::Error),
/// The patch is not a correct unified diff.
Malformed { line: usize },
/// A hunk does not match the text.
Mismatch { line: usize },
}
impl fmt::Display for PatchError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PatchError::Io(e) => write!(f, "{e}"),
PatchError::Malformed { line } => write!(f, "malformed at line {line} of the patch"),
PatchError::Mismatch { line } => write!(f, "mismatch at line {line} of the patch"),
}
}
}
impl std::error::Error for PatchError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
PatchError::Io(e) => Some(e),
_ => None,
}
}
}
impl From<io::Error> for PatchError {
fn from(e: io::Error) -> Self {
PatchError::Io(e)
}
}
/// Splits text after each LF. Each line keeps its LF, and a last line with no
/// LF is a line too.
pub fn split_lines(text: &str) -> Vec<&str> {
text.split_inclusive('\n').collect()
}
/// Reads a number and an optional comma and count from the start of s. A
/// missing count is 1.
fn range(s: &str) -> Option<(usize, usize, &str)> {
let digits = |s: &str| s.bytes().take_while(u8::is_ascii_digit).count();
let n = digits(s);
let start = s.get(..n)?.parse().ok()?;
let mut rest = &s[n..];
let mut count = 1;
if let Some(r) = rest.strip_prefix(',') {
let n = digits(r);
count = r.get(..n)?.parse().ok()?;
rest = &r[n..];
}
Some((start, count, rest))
}
/// Reads a hunk header such as `@@ -1,3 +1,4 @@`, and returns the old start,
/// the old count and the new count.
fn hunk_header(line: &str) -> Option<(usize, usize, usize)> {
let (old_start, old_count, rest) = range(line.strip_prefix("@@ -")?)?;
let (_, new_count, rest) = range(rest.strip_prefix(" +")?)?;
rest.starts_with(" @@")
.then_some((old_start, old_count, new_count))
}
/// Returns the text that the unified diff `patch` makes from the text `old`.
/// Each hunk must match the lines of `old` at the start of its old range.
pub fn apply_patch(old: &str, patch: &str) -> Result<String, PatchError> {
let lines = split_lines(old);
// The lines of the patch, with no LF. A CR stays in its line.
let p: Vec<&str> = split_lines(patch)
.into_iter()
.map(|l| l.strip_suffix('\n').unwrap_or(l))
.collect();
let mut out = String::new();
let mut cur = 0; // the index of the next line of old to use
let mut hunks = 0;
let mut i = 0;
while i < p.len() {
if !p[i].starts_with("@@") {
i += 1; // a header line, or another line outside a hunk
continue;
}
let (old_start, old_count, new_count) =
hunk_header(p[i]).ok_or(PatchError::Malformed { line: i + 1 })?;
hunks += 1;
// An empty range starts after the line old_start.
let pos = if old_count > 0 {
old_start
.checked_sub(1)
.ok_or(PatchError::Malformed { line: i + 1 })?
} else {
old_start
};
if pos < cur || pos > lines.len() {
return Err(PatchError::Mismatch { line: i + 1 });
}
out.extend(lines[cur..pos].iter().copied());
cur = pos;
i += 1;
// The mark, the text, the number in the patch and the end of each
// line: an LF, or "" before a backslash line.
let mut body: Vec<(u8, &str, usize, &str)> = Vec::new();
let (mut old_left, mut new_left) = (old_count, new_count);
while old_left > 0 || new_left > 0 {
let Some(&line) = p.get(i) else {
return Err(PatchError::Malformed { line: i });
};
let (mark, text) = match line.as_bytes().first() {
None => (b' ', ""),
Some(&m) => (m, &line[1..]),
};
let malformed = PatchError::Malformed { line: i + 1 };
match mark {
b'\\' => {
let last = body.last_mut().ok_or(malformed)?;
last.3 = ""; // the line before has no LF
i += 1;
continue;
}
b' ' | b'-' | b'+' => {}
_ => return Err(malformed),
}
if mark != b'+' {
old_left = old_left.checked_sub(1).ok_or(malformed)?;
}
if mark != b'-' {
new_left = new_left
.checked_sub(1)
.ok_or(PatchError::Malformed { line: i + 1 })?;
}
body.push((mark, text, i + 1, "\n"));
i += 1;
}
if i < p.len() && p[i].starts_with('\\') {
if let Some(last) = body.last_mut() {
last.3 = "";
i += 1;
}
}
for (mark, text, number, end) in body {
if mark != b'+' {
let same = lines.get(cur).is_some_and(|l| {
l.len() == text.len() + end.len() && l.starts_with(text) && l.ends_with(end)
});
if !same {
return Err(PatchError::Mismatch { line: number });
}
cur += 1;
}
if mark != b'-' {
out.push_str(text);
out.push_str(end);
}
}
}
if hunks == 0 {
return Err(PatchError::Malformed { line: p.len() });
}
out.extend(lines[cur..].iter().copied());
Ok(out)
}
/// Returns `apply_patch` of the two UTF-8 files. A file that does not exist
/// gives `PatchError::Io` with an error of the kind `NotFound`.
pub fn apply_patch_file(
path: impl AsRef<Path>,
patch_path: impl AsRef<Path>,
) -> Result<String, PatchError> {
let old = fs::read_to_string(path)?;
let patch = fs::read_to_string(patch_path)?;
apply_patch(&old, &patch)
}
tests/apply_a_patch_test.rs 116 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-patch/.
use std::fs;
use std::io::ErrorKind;
use std::path::PathBuf;
use algo_apply_a_patch::{apply_patch, apply_patch_file, PatchError};
/// (name, the old text, the patch, the new text)
const CASES: &[(&str, &str, &str, &str)] = &[
("change-a-line", "a\nb\nc\n", "--- old.txt\n+++ new.txt\n@@ -1,3 +1,3 @@\n a\n-b\n+B\n c\n", "a\nB\nc\n"),
("two-hunks", "apple\nbanana\ncherry\ndate\nelder\nfig\ngrape\n", "--- old.txt\n+++ new.txt\n@@ -1,3 +1,3 @@\n apple\n-banana\n+blueberry\n cherry\n@@ -6,2 +6,2 @@\n fig\n-grape\n+guava\n", "apple\nblueberry\ncherry\ndate\nelder\nfig\nguava\n"),
("git-header", "def main():\n print(1)\n", "diff --git a/main.py b/main.py\nindex 1234567..89abcde 100644\n--- a/main.py\n+++ b/main.py\n@@ -1,2 +1,2 @@ def main():\n def main():\n- print(1)\n+ print(2)\n", "def main():\n print(2)\n"),
("add-at-end", "a\n", "@@ -1 +1,2 @@\n a\n+b\n", "a\nb\n"),
("old-empty", "", "--- /dev/null\n+++ b.txt\n@@ -0,0 +1,2 @@\n+a\n+b\n", "a\nb\n"),
("delete-all", "a\nb\n", "@@ -1,2 +0,0 @@\n-a\n-b\n", ""),
("no-count", "a\nb\nc\n", "@@ -2 +2 @@\n-b\n+x\n", "a\nx\nc\n"),
("zero-context", "apple\nbanana\ncherry\ndate\nelder\nfig\ngrape\n", "@@ -3 +3 @@\n-cherry\n+coconut\n@@ -6 +5,0 @@\n-fig\n@@ -7,0 +7 @@\n+honeydew\n", "apple\nbanana\ncoconut\ndate\nelder\ngrape\nhoneydew\n"),
("insert-at-start", "b\n", "@@ -0,0 +1 @@\n+a\n", "a\nb\n"),
("old-no-final-newline", "a\nb", "@@ -1,2 +1,2 @@\n a\n-b\n\\ No newline at end of file\n+b\n", "a\nb\n"),
("new-no-final-newline", "a\nb\n", "@@ -1,2 +1,2 @@\n a\n-b\n+b\n\\ No newline at end of file\n", "a\nb"),
("empty-context-line", "a\n\nb\n", "@@ -1,3 +1,3 @@\n a\n\n-b\n+c\n", "a\n\nc\n"),
("space-context-line", "a\n\nb\n", "@@ -1,3 +1,3 @@\n a\n \n-b\n+c\n", "a\n\nc\n"),
("crlf", "a\r\nb\r\n", "@@ -1,2 +1,2 @@\n a\r\n-b\r\n+c\r\n", "a\r\nc\r\n"),
("header-like-line", "x\n-- y\n", "--- old.txt\n+++ new.txt\n@@ -1,2 +1 @@\n x\n--- y\n", "x\n"),
("non-ascii", "caf\u{e9}\n", "@@ -1 +1 @@\n-caf\u{e9}\n+na\u{ef}ve\n", "na\u{ef}ve\n"),
];
/// (name, the old text, the patch, the kind of the error)
const ERRORS: &[(&str, &str, &str, &str)] = &[
(
"mismatch",
"a\nb\nc\n",
"@@ -1,3 +1,3 @@\n a\n-x\n+y\n c\n",
"mismatch",
),
(
"malformed",
"a\nb\nc\n",
"@@ -1,3 +1,3 @@\n a\n-b\n",
"malformed",
),
("no-hunk", "a\n", "no hunk here\n", "malformed"),
("bad-mark", "a\n", "@@ -1 +1 @@\n*a\n", "malformed"),
("past-the-end", "a\n", "@@ -2 +2 @@\n-a\n+b\n", "mismatch"),
];
#[test]
fn apply_patch_cases() {
for &(name, old, patch, want) in CASES {
assert_eq!(
apply_patch(old, patch).ok().as_deref(),
Some(want),
"{name}"
);
}
}
#[test]
fn error_cases() {
for &(name, old, patch, kind) in ERRORS {
let got = match apply_patch(old, patch) {
Err(PatchError::Malformed { .. }) => "malformed",
Err(PatchError::Mismatch { .. }) => "mismatch",
_ => "other",
};
assert_eq!(got, kind, "{name}");
}
}
#[test]
fn many_hunks() {
// 1000 lines, and 10 hunks with no context change 10 of them.
let old: String = (0..1000).map(|i| format!("{i}\n")).collect();
let patch: String = (50..1000)
.step_by(100)
.map(|i| format!("@@ -{} +{} @@\n-{i}\n+x{i}\n", i + 1, i + 1))
.collect();
let want: String = (0..1000)
.map(|i| {
if i % 100 == 50 {
format!("x{i}\n")
} else {
format!("{i}\n")
}
})
.collect();
assert_eq!(apply_patch(&old, &patch).unwrap(), want);
}
fn temp_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("apply-a-patch-{name}-{}", std::process::id()));
fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn apply_patch_file_crlf() {
let dir = temp_dir("file");
let &(_, old, patch, want) = CASES.iter().find(|c| c.0 == "crlf").unwrap();
fs::write(dir.join("old.txt"), old).unwrap();
fs::write(dir.join("a.patch"), patch).unwrap();
let got = apply_patch_file(dir.join("old.txt"), dir.join("a.patch"));
fs::remove_dir_all(&dir).unwrap();
assert_eq!(got.unwrap(), want);
}
#[test]
fn not_found() {
let dir = temp_dir("missing");
fs::write(dir.join("a.patch"), "@@ -1 +1 @@\n-a\n+b\n").unwrap();
let got = apply_patch_file(dir.join("missing.txt"), dir.join("a.patch"));
fs::remove_dir_all(&dir).unwrap();
assert!(matches!(got, Err(PatchError::Io(e)) if e.kind() == ErrorKind::NotFound));
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/apply-a-patch/.
# apply_patch FILE PATCH
# Prints the text that the unified diff in the file PATCH makes from the file
# FILE, with no fuzz and no offset. Each hunk must match the lines of FILE at
# the start of its old range. Prints nothing on stdout and returns 1 if a file
# cannot be read, 2 if a hunk does not match, and 3 if the patch is malformed.
apply_patch() {
local path
for path in "$1" "$2"; do
[[ -r $path && ! -d $path ]] || { printf 'apply_patch: cannot read %s\n' "$path" >&2; return 1; }
done
# LC_ALL=C compares the bytes of the lines.
local LC_ALL=C
local -a lines p marks texts numbers ends
# Without -t, each line keeps its LF, and a last line with no LF has none.
mapfile lines <"$1"
# With -t, the LF goes. A CR stays in its line.
mapfile -t p <"$2"
local hunk_re='^@@ -([0-9]{1,18})(,([0-9]{1,18}))? \+([0-9]{1,18})(,([0-9]{1,18}))? @@'
local out='' nl=${#lines[@]} np=${#p[@]}
local cur=0 hunks=0 i=0 k pos old_start old_count new_count old_left new_left mark text line
while ((i < np)); do
if [[ ${p[i]} != @@* ]]; then
((i += 1)) # a header line, or another line outside a hunk
continue
fi
[[ ${p[i]} =~ $hunk_re ]] || { _patch_error 3 $((i + 1)); return; }
((hunks += 1))
old_start=$((10#${BASH_REMATCH[1]}))
old_count=$((10#${BASH_REMATCH[3]:-1}))
new_count=$((10#${BASH_REMATCH[6]:-1}))
# An empty range starts after the line old_start.
pos=$((old_count > 0 ? old_start - 1 : old_start))
((pos >= 0)) || { _patch_error 3 $((i + 1)); return; }
((pos >= cur && pos <= nl)) || { _patch_error 2 $((i + 1)); return; }
for ((; cur < pos; cur++)); do out+=${lines[cur]}; done
((i += 1))
# The mark, the text, the number in the patch and the end of each line:
# an LF, or nothing before a backslash line.
marks=() texts=() numbers=() ends=()
old_left=$old_count new_left=$new_count
while ((old_left > 0 || new_left > 0)); do
((i < np)) || { _patch_error 3 "$i"; return; }
line=${p[i]}
mark=${line:0:1} text=${line:1}
[[ -n $line ]] || mark=' '
if [[ $mark == '\' ]]; then
((${#marks[@]} > 0)) || { _patch_error 3 $((i + 1)); return; }
ends[-1]='' # the line before has no LF
((i += 1))
continue
fi
case $mark in
' ') old_left=$((old_left - 1)) new_left=$((new_left - 1)) ;;
-) old_left=$((old_left - 1)) ;;
+) new_left=$((new_left - 1)) ;;
*) _patch_error 3 $((i + 1)); return ;;
esac
((old_left >= 0 && new_left >= 0)) || { _patch_error 3 $((i + 1)); return; }
marks+=("$mark") texts+=("$text") numbers+=($((i + 1))) ends+=($'\n')
((i += 1))
done
if ((i < np && ${#marks[@]} > 0)) && [[ ${p[i]} == '\'* ]]; then
ends[-1]=''
((i += 1))
fi
for ((k = 0; k < ${#marks[@]}; k++)); do
line=${texts[k]}${ends[k]}
if [[ ${marks[k]} != + ]]; then
((cur < nl)) && [[ ${lines[cur]} == "$line" ]] || { _patch_error 2 "${numbers[k]}"; return; }
((cur += 1))
fi
[[ ${marks[k]} == - ]] || out+=$line
done
done
((hunks > 0)) || { _patch_error 3 "$np"; return; }
for ((; cur < nl; cur++)); do out+=${lines[cur]}; done
printf '%s' "$out"
}
# _patch_error STATUS LINE prints the error and returns STATUS.
_patch_error() {
local kind=malformed
(($1 == 2)) && kind=mismatch
printf 'apply_patch: %s at line %s of the patch\n' "$kind" "$2" >&2
return "$1"
}
test_apply_a_patch.bats 65 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/apply-a-patch/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/apply_a_patch.sh"
old="$BATS_TEST_TMPDIR/old.txt"
patch="$BATS_TEST_TMPDIR/a.patch"
}
check() { # check OLD PATCH WANT, each as printf %b bytes
printf '%b' "$1" >"$old"
printf '%b' "$2" >"$patch"
# The x keeps the final LFs, which $(...) removes.
got=$(apply_patch "$old" "$patch" && printf x)
[ "$got" = "$(printf '%bx' "$3")" ]
}
check_error() { # check_error OLD PATCH STATUS
printf '%b' "$1" >"$old"
printf '%b' "$2" >"$patch"
run -"$3" apply_patch "$old" "$patch"
}
@test "change-a-line" { check 'a\nb\nc\n' '--- old.txt\n+++ new.txt\n@@ -1,3 +1,3 @@\n a\n-b\n+B\n c\n' 'a\nB\nc\n'; }
@test "two-hunks" { check 'apple\nbanana\ncherry\ndate\nelder\nfig\ngrape\n' '--- old.txt\n+++ new.txt\n@@ -1,3 +1,3 @@\n apple\n-banana\n+blueberry\n cherry\n@@ -6,2 +6,2 @@\n fig\n-grape\n+guava\n' 'apple\nblueberry\ncherry\ndate\nelder\nfig\nguava\n'; }
@test "git-header" { check 'def main():\n print(1)\n' 'diff --git a/main.py b/main.py\nindex 1234567..89abcde 100644\n--- a/main.py\n+++ b/main.py\n@@ -1,2 +1,2 @@ def main():\n def main():\n- print(1)\n+ print(2)\n' 'def main():\n print(2)\n'; }
@test "add-at-end" { check 'a\n' '@@ -1 +1,2 @@\n a\n+b\n' 'a\nb\n'; }
@test "old-empty" { check '' '--- /dev/null\n+++ b.txt\n@@ -0,0 +1,2 @@\n+a\n+b\n' 'a\nb\n'; }
@test "delete-all" { check 'a\nb\n' '@@ -1,2 +0,0 @@\n-a\n-b\n' ''; }
@test "no-count" { check 'a\nb\nc\n' '@@ -2 +2 @@\n-b\n+x\n' 'a\nx\nc\n'; }
@test "zero-context" { check 'apple\nbanana\ncherry\ndate\nelder\nfig\ngrape\n' '@@ -3 +3 @@\n-cherry\n+coconut\n@@ -6 +5,0 @@\n-fig\n@@ -7,0 +7 @@\n+honeydew\n' 'apple\nbanana\ncoconut\ndate\nelder\ngrape\nhoneydew\n'; }
@test "insert-at-start" { check 'b\n' '@@ -0,0 +1 @@\n+a\n' 'a\nb\n'; }
@test "old-no-final-newline" { check 'a\nb' '@@ -1,2 +1,2 @@\n a\n-b\n\\ No newline at end of file\n+b\n' 'a\nb\n'; }
@test "new-no-final-newline" { check 'a\nb\n' '@@ -1,2 +1,2 @@\n a\n-b\n+b\n\\ No newline at end of file\n' 'a\nb'; }
@test "empty-context-line" { check 'a\n\nb\n' '@@ -1,3 +1,3 @@\n a\n\n-b\n+c\n' 'a\n\nc\n'; }
@test "space-context-line" { check 'a\n\nb\n' '@@ -1,3 +1,3 @@\n a\n \n-b\n+c\n' 'a\n\nc\n'; }
@test "crlf" { check 'a\r\nb\r\n' '@@ -1,2 +1,2 @@\n a\r\n-b\r\n+c\r\n' 'a\r\nc\r\n'; }
@test "header-like-line" { check 'x\n-- y\n' '--- old.txt\n+++ new.txt\n@@ -1,2 +1 @@\n x\n--- y\n' 'x\n'; }
@test "non-ascii" { check 'caf\xc3\xa9\n' '@@ -1 +1 @@\n-caf\xc3\xa9\n+na\xc3\xafve\n' 'na\xc3\xafve\n'; }
@test "mismatch" { check_error 'a\nb\nc\n' '@@ -1,3 +1,3 @@\n a\n-x\n+y\n c\n' 2; }
@test "malformed" { check_error 'a\nb\nc\n' '@@ -1,3 +1,3 @@\n a\n-b\n' 3; }
@test "no-hunk" { check_error 'a\n' 'no hunk here\n' 3; }
@test "bad-mark" { check_error 'a\n' '@@ -1 +1 @@\n*a\n' 3; }
@test "past-the-end" { check_error 'a\n' '@@ -2 +2 @@\n-a\n+b\n' 2; }
@test "many-hunks" {
# 100 lines, and 10 hunks with no context change 10 of them. A new bash
# keeps the loops fast, with no DEBUG trap of bats.
seq 0 99 >"$old"
for ((i = 5; i < 100; i += 10)); do
printf '@@ -%d +%d @@\n-%d\n+x%d\n' $((i + 1)) $((i + 1)) "$i" "$i"
done >"$patch"
out=$(bash -c '. "$1" && apply_patch "$2" "$3"' bash "$BATS_TEST_DIRNAME/apply_a_patch.sh" "$old" "$patch")
[ "$out" = "$(seq 0 99 | awk '{ print ($1 % 10 == 5 ? "x" $1 : $1) }')" ]
}
@test "not-found" {
printf '@@ -1 +1 @@\n-a\n+b\n' >"$patch"
run -1 apply_patch "$BATS_TEST_TMPDIR/missing.txt" "$patch"
[ "$output" = "apply_patch: cannot read $BATS_TEST_TMPDIR/missing.txt" ]
}
References
- Comparing and Merging Files (GNU Diffutils manual), Overview
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), patch, DESCRIPTION; EXTENDED DESCRIPTION, Patch File Format, Patch Application
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), diff, STDOUT, Diff -u or -U Output Format
- Comparing and Merging Files (GNU Diffutils manual), Incomplete Lines
- Comparing and Merging Files (GNU Diffutils manual), Helping patch Find Inexact Matches
- Git documentation, git-apply, OPTIONS (-C, --unidiff-zero, --reject)
- Comparing and Merging Files (GNU Diffutils manual), Unified Format
- Comparing and Merging Files (GNU Diffutils manual), Applying Reversed Patches
- Comparing and Merging Files (GNU Diffutils manual), Applying Imperfect Patches
- The Python Standard Library, Built-in Types, str.splitlines
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag X4069W Edit this page History Report an error Markdown