Handling Malformed Patch Files
Identify and fix common errors in malformed patch files. Covers missing headers, incorrect counts, and encoding issues that prevent patch application.
Detailed Explanation
Diagnosing Malformed Patches
A malformed patch file has structural issues that prevent the parser from understanding it. Here are the most common problems and how to fix them.
Missing or Corrupt Hunk Headers
Problem: The @@ header is missing or has invalid numbers.
# Bad: missing counts
@@ -5 +5 @@
# Good: with counts
@@ -5,3 +5,4 @@
Note: A count of 1 can technically be omitted (@@ -5 +5,2 @@ means old count is 1), but some tools may not generate this shorthand.
Incorrect Line Counts
Problem: The number of lines in the hunk body does not match the counts in the header.
# Header says 3 old lines, but body has 4
@@ -1,3 +1,3 @@
line 1
-line 2
-line 3
line 4
+new line 2
+new line 3
Old lines = context ( ) + removed (-) = 1 + 2 + 1 = 4, but header says 3.
Fix: Recount and update the header to @@ -1,4 +1,4 @@.
Missing Line Prefixes
Problem: Lines in the hunk body are missing the , +, or - prefix.
@@ -1,3 +1,3 @@
line 1 <- missing space prefix!
-old line
+new line
line 3
Every line in a hunk body must start with (space), +, or -. A line without a prefix is ambiguous and may cause the parser to stop reading the hunk.
Encoding and Line Ending Issues
- CRLF vs LF: If the patch has \r\n line endings but the file has \n (or vice versa), context matching may fail
- BOM: A UTF-8 BOM at the start of the patch file can corrupt the first header
- Copy-paste artifacts: Rich text editors may convert dashes or add invisible characters
Use Case
You received a patch via email or a chat message and it fails to apply. The tool's error messages help you identify whether the issue is in the hunk headers, line prefixes, or encoding.