Applying a Multi-Hunk Refactoring Patch
Apply a patch with multiple hunks that refactors code across different sections of a file. Learn how hunks are applied sequentially and how line offsets adjust.
Detailed Explanation
Multi-Hunk Patches
Real-world patches often contain multiple hunks — each targeting a different section of the file. The patch engine applies hunks from top to bottom, adjusting line offsets as previous hunks add or remove lines.
Example: Refactoring a Module
--- a/api.js
+++ b/api.js
@@ -2,7 +2,7 @@
-const API_URL = "http://localhost:3000";
+const API_URL = process.env.API_URL || "http://localhost:3000";
async function fetchUsers() {
const response = await fetch(API_URL + "/users");
@@ -15,6 +15,10 @@
return data;
}
+async function fetchUserById(id) {
+ const response = await fetch(API_URL + "/users/" + id);
+ return response.json();
+}
+
module.exports = { fetchUsers };
@@ -22,3 +26,3 @@
-module.exports = { fetchUsers };
+module.exports = { fetchUsers, fetchUserById };
Hunk Application Order
- Hunk 1 (line 2): Replaces hardcoded URL with environment variable — no line count change
- Hunk 2 (line 15): Adds a new function — adds 4 lines, creating an offset of +4
- Hunk 3 (line 22 + offset = 26): Updates exports — the offset from Hunk 2 shifts this hunk's target
Offset Tracking
After each hunk, the engine tracks a cumulative line offset:
- Hunk adds N lines: offset increases by N
- Hunk removes N lines: offset decreases by N
- Subsequent hunks have their target line number adjusted by the current offset
Selective Application
The Diff Patch Applier lets you accept or reject each hunk independently. For example, you might accept the URL change (Hunk 1) and the new function (Hunk 2) but reject the export change (Hunk 3) if you want to handle it differently.
Use Case
A code review suggests three changes in different parts of the same file: a config improvement, a new function, and an export update. You want to apply the first two but handle the export differently.