3 * Apply a "universal" diff.
4 * Adapted from toybox's patch implementation.
6 * Copyright 2007 Rob Landley <rob@landley.net>
8 * see http://www.opengroup.org/onlinepubs/009695399/utilities/patch.html
9 * (But only does -u, because who still cares about "ed"?)
13 * -l treat all whitespace as a single space
15 * -D define wrap #ifdef and #ifndef around changes
16 * -o outfile output here instead of in place
17 * -r rejectfile write rejected hunks to this file
19 * -f force (no questions asked)
20 * -F fuzz (number, default 2)
21 * [file] which file to patch
24 //applet:IF_PATCH(APPLET(patch, BB_DIR_USR_BIN, BB_SUID_DROP))
26 //kbuild:lib-$(CONFIG_PATCH) += patch.o
29 //config: bool "patch"
32 //config: Apply a unified diff formatted patch.
34 //usage:#define patch_trivial_usage
35 //usage: "[OPTIONS] [ORIGFILE [PATCHFILE]]"
36 //usage:#define patch_full_usage "\n\n"
37 //usage: IF_LONG_OPTS(
38 //usage: " -p,--strip N Strip N leading components from file names"
39 //usage: "\n -i,--input DIFF Read DIFF instead of stdin"
40 //usage: "\n -R,--reverse Reverse patch"
41 //usage: "\n -N,--forward Ignore already applied patches"
42 //usage: "\n --dry-run Don't actually change files"
43 //usage: "\n -E,--remove-empty-files Remove output files if they become empty"
45 //usage: IF_NOT_LONG_OPTS(
46 //usage: " -p N Strip N leading components from file names"
47 //usage: "\n -i DIFF Read DIFF instead of stdin"
48 //usage: "\n -R Reverse patch"
49 //usage: "\n -N Ignore already applied patches"
50 //usage: "\n -E Remove output files if they become empty"
53 //usage:#define patch_example_usage
54 //usage: "$ patch -p1 < example.diff\n"
55 //usage: "$ patch -p0 -i example.diff"
63 struct double_list *next;
64 struct double_list *prev;
68 // Free all the elements of a linked list
69 // Call freeit() on each element before freeing it.
71 void dlist_free(struct double_list *list, void (*freeit)(void *data))
77 // Bail out also if list is circular.
78 if (list == pop) break;
82 // Add an entry before "list" element in (circular) doubly linked list
84 struct double_list *dlist_add(struct double_list **list, char *data)
86 struct double_list *llist;
87 struct double_list *line = xmalloc(sizeof(*line));
92 struct double_list *p;
94 p = line->prev = llist->prev;
95 // (list is circular, we assume p is never NULL)
99 *list = line->next = line->prev = line;
109 struct double_list *current_hunk;
111 long oldline, oldlen, newline, newlen;
113 int context, state, hunknum;
119 #define TT (*ptr_to_globals)
120 #define INIT_TT() do { \
121 SET_PTR_TO_GLOBALS(xzalloc(sizeof(TT))); \
125 #define FLAG_STR "Rup:i:NEx"
126 /* FLAG_REVERSE must be == 1! Code uses this fact. */
127 #define FLAG_REVERSE (1 << 0)
128 #define FLAG_u (1 << 1)
129 #define FLAG_PATHLEN (1 << 2)
130 #define FLAG_INPUT (1 << 3)
131 #define FLAG_IGNORE (1 << 4)
132 #define FLAG_RMEMPTY (1 << 5)
134 #define FLAG_DEBUG (1 << 6)
136 // Dispose of a line of input, either by writing it out or discarding it.
138 // state < 2: just free
139 // state = 2: write whole line to stderr
140 // state = 3: write whole line to fileout
141 // state > 3: write line+1 to fileout when *line != state
143 #define PATCH_DEBUG (option_mask32 & FLAG_DEBUG)
145 static void do_line(void *data)
147 struct double_list *dlist = data;
149 if (TT.state>1 && *dlist->data != TT.state)
150 fdprintf(TT.state == 2 ? 2 : TT.fileout,
151 "%s\n", dlist->data+(TT.state>3 ? 1 : 0));
153 if (PATCH_DEBUG) fdprintf(2, "DO %d: %s\n", TT.state, dlist->data);
159 static void finish_oldfile(void)
162 // Copy the rest of the data and replace the original with the copy.
165 if (TT.filein != -1) {
166 bb_copyfd_eof(TT.filein, TT.fileout);
171 temp = xstrdup(TT.tempname);
172 temp[strlen(temp) - 6] = '\0';
173 rename(TT.tempname, temp);
179 TT.fileout = TT.filein = -1;
182 static void fail_hunk(void)
184 if (!TT.current_hunk) return;
186 fdprintf(2, "Hunk %d FAILED %ld/%ld.\n", TT.hunknum, TT.oldline, TT.newline);
189 // If we got to this point, we've seeked to the end. Discard changes to
190 // this file and advance to next file.
193 TT.current_hunk->prev->next = NULL;
194 dlist_free(TT.current_hunk, do_line);
195 TT.current_hunk = NULL;
197 // Abort the copy and delete the temporary file.
207 // Given a hunk of a unified diff, make the appropriate change to the file.
208 // This does not use the location information, but instead treats a hunk
209 // as a sort of regex. Copies data from input to output until it finds
210 // the change to be made, then outputs the changed data and returns.
211 // (Finding EOF first is an error.) This is a single pass operation, so
212 // multiple hunks must occur in order in the file.
214 static int apply_one_hunk(void)
216 struct double_list *plist, *buf = NULL, *check;
217 int matcheof = 0, reverse = option_mask32 & FLAG_REVERSE, backwarn = 0;
218 /* Do we try "dummy" revert to check whether
219 * to silently skip this hunk? Used to implement -N.
221 int dummy_revert = 0;
223 // Break doubly linked list so we can use singly linked traversal function.
224 TT.current_hunk->prev->next = NULL;
226 // Match EOF if there aren't as many ending context lines as beginning
227 for (plist = TT.current_hunk; plist; plist = plist->next) {
228 if (plist->data[0]==' ') matcheof++;
230 if (PATCH_DEBUG) fdprintf(2, "HUNK:%s\n", plist->data);
232 matcheof = matcheof < TT.context;
234 if (PATCH_DEBUG) fdprintf(2,"MATCHEOF=%c\n", matcheof ? 'Y' : 'N');
236 // Loop through input data searching for this hunk. Match all context
237 // lines and all lines to be removed until we've found the end of a
239 plist = TT.current_hunk;
241 if (reverse ? TT.oldlen : TT.newlen) for (;;) {
242 char *data = xmalloc_reads(TT.filein, NULL, NULL);
246 // Figure out which line of hunk to compare with next. (Skip lines
247 // of the hunk we'd be adding.)
248 while (plist && *plist->data == "+-"[reverse]) {
249 if (data && !strcmp(data, plist->data+1)) {
251 backwarn = TT.linenum;
252 if (option_mask32 & FLAG_IGNORE) {
264 if (PATCH_DEBUG) fdprintf(2, "INEOF\n");
266 // Does this hunk need to match EOF?
267 if (!plist && matcheof) break;
270 fdprintf(2,"Possibly reversed hunk %d at %ld\n",
271 TT.hunknum, TT.linenum);
273 // File ended before we found a place for this hunk.
278 if (PATCH_DEBUG) fdprintf(2, "IN: %s\n", data);
279 check = dlist_add(&buf, data);
281 // Compare this line with next expected line of hunk.
282 // todo: teach the strcmp() to ignore whitespace.
284 // A match can fail because the next line doesn't match, or because
285 // we hit the end of a hunk that needed EOF, and this isn't EOF.
287 // If match failed, flush first line of buffered data and
288 // recheck buffered data for a new match until we find one or run
292 if (!plist || strcmp(check->data, plist->data+1)) {
293 // Match failed. Write out first line of buffered data and
294 // recheck remaining buffered data for a new match.
297 fdprintf(2, "NOT: %s\n", plist->data);
302 check->prev->next = buf;
303 buf->prev = check->prev;
305 plist = TT.current_hunk;
307 // If we've reached the end of the buffer without confirming a
308 // match, read more lines.
316 fdprintf(2, "MAYBE: %s\n", plist->data);
317 // This line matches. Advance plist, detect successful match.
319 if (!plist && !matcheof) goto out;
321 if (check == buf) break;
326 // We have a match. Emit changed data.
327 TT.state = "-+"[reverse ^ dummy_revert];
328 dlist_free(TT.current_hunk, do_line);
329 TT.current_hunk = NULL;
333 buf->prev->next = NULL;
334 dlist_free(buf, do_line);
340 // Read a patch file and find hunks, opening/creating/deleting files.
341 // Call apply_one_hunk() on each hunk.
343 // state 0: Not in a hunk, look for +++.
344 // state 1: Found +++ file indicator, look for @@
345 // state 2: In hunk: counting initial context lines
346 // state 3: In hunk: getting body
348 int patch_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
349 int patch_main(int argc UNUSED_PARAM, char **argv)
352 int reverse, state = 0;
353 char *oldname = NULL, *newname = NULL;
355 long oldlen = oldlen; /* for compiler */
356 long newlen = newlen; /* for compiler */
360 opts = getopt32(argv, FLAG_STR, &opt_p, &opt_i);
362 reverse = opts & FLAG_REVERSE;
363 TT.prefix = (opts & FLAG_PATHLEN) ? xatoi(opt_p) : 0; // can be negative!
364 TT.filein = TT.fileout = -1;
365 if (opts & FLAG_INPUT) {
366 xmove_fd(xopen_stdin(opt_i), STDIN_FILENO);
368 if (argv[0] && argv[1]) {
369 xmove_fd(xopen_stdin(argv[1]), STDIN_FILENO);
373 oldname = xstrdup(argv[0]);
374 newname = xstrdup(argv[0]);
377 // Loop through the lines in the patch
381 patchline = xmalloc_fgetline(stdin);
382 if (!patchline) break;
384 // Other versions of patch accept damaged patches,
385 // so we need to also.
388 patchline = xstrdup(" ");
391 // Are we assembling a hunk?
393 if (*patchline==' ' || *patchline=='+' || *patchline=='-') {
394 dlist_add(&TT.current_hunk, patchline);
396 if (*patchline != '+') oldlen--;
397 if (*patchline != '-') newlen--;
400 if (*patchline==' ' && state==2) TT.context++;
403 // If we've consumed all expected hunk lines, apply the hunk.
405 if (!oldlen && !newlen) state = apply_one_hunk();
414 if (!strncmp("--- ", patchline, 4) || !strncmp("+++ ", patchline, 4)) {
415 char *s, **name = reverse ? &newname : &oldname;
418 if (*patchline == '+') {
419 name = reverse ? &oldname : &newname;
427 // Trim date from end of filename (if any). We don't care.
428 for (s = patchline+4; *s && *s!='\t'; s++)
429 if (*s=='\\' && s[1]) s++;
431 if (i>1900 && i<=1970)
432 *name = xstrdup("/dev/null");
435 *name = xstrdup(patchline+4);
439 // We defer actually opening the file because svn produces broken
440 // patches that don't signal they want to create a new file the
441 // way the patch man page says, so you have to read the first hunk
444 // Start a new hunk? Usually @@ -oldline,oldlen +newline,newlen @@
445 // but a missing ,value means the value is 1.
446 } else if (state == 1 && !strncmp("@@ -", patchline, 4)) {
448 char *s = patchline+4;
450 // Read oldline[,oldlen] +newline[,newlen]
452 TT.oldlen = oldlen = TT.newlen = newlen = 1;
453 TT.oldline = strtol(s, &s, 10);
454 if (*s == ',') TT.oldlen = oldlen = strtol(s+1, &s, 10);
455 TT.newline = strtol(s+2, &s, 10);
456 if (*s == ',') TT.newlen = newlen = strtol(s+1, &s, 10);
458 if (oldlen < 1 && newlen < 1)
459 bb_error_msg_and_die("Really? %s", patchline);
464 // If this is the first hunk, open the file.
465 if (TT.filein == -1) {
466 int oldsum, newsum, empty = 0;
469 oldsum = TT.oldline + oldlen;
470 newsum = TT.newline + newlen;
472 name = reverse ? oldname : newname;
474 // We're deleting oldname if new file is /dev/null (before -p)
475 // or if new hunk is empty (zero context) after patching
476 if (!strcmp(name, "/dev/null") || !(reverse ? oldsum : newsum))
478 name = reverse ? newname : oldname;
482 // handle -p path truncation.
483 for (i=0, s = name; *s;) {
484 if ((option_mask32 & FLAG_PATHLEN) && TT.prefix == i) break;
492 // File is empty after the patches have been applied
494 if (option_mask32 & FLAG_RMEMPTY) {
495 // If flag -E or --remove-empty-files is set
496 printf("removing %s\n", name);
499 printf("patching file %s\n", name);
500 xclose(xopen(name, O_WRONLY | O_TRUNC));
502 // If we've got a file to open, do so.
503 } else if (!(option_mask32 & FLAG_PATHLEN) || i <= TT.prefix) {
506 // If the old file was null, we're creating a new one.
507 if (!strcmp(oldname, "/dev/null") || !oldsum) {
508 printf("creating %s\n", name);
509 s = strrchr(name, '/');
512 bb_make_directory(name, -1, FILEUTILS_RECUR);
515 TT.filein = xopen(name, O_CREAT|O_EXCL|O_RDWR);
517 printf("patching file %s\n", name);
518 TT.filein = xopen(name, O_RDONLY);
521 TT.tempname = xasprintf("%sXXXXXX", name);
522 TT.fileout = xmkstemp(TT.tempname);
523 // Set permissions of output file
524 fstat(TT.filein, &statbuf);
525 fchmod(TT.fileout, statbuf.st_mode);
537 // If we didn't continue above, discard this line.
543 if (ENABLE_FEATURE_CLEAN_UP) {