1 /* Adapted from toybox's patch. */
5 * patch.c - Apply a "universal" diff.
7 * Copyright 2007 Rob Landley <rob@landley.net>
9 * see http://www.opengroup.org/onlinepubs/009695399/utilities/patch.html
10 * (But only does -u, because who still cares about "ed"?)
14 * -l treat all whitespace as a single space
15 * -N ignore already applied
17 * -D define wrap #ifdef and #ifndef around changes
18 * -o outfile output here instead of in place
19 * -r rejectfile write rejected hunks to this file
21 * -E remove empty files --remove-empty-files
22 * -f force (no questions asked)
23 * -F fuzz (number, default 2)
24 * [file] which file to patch
26 USE_PATCH(NEWTOY(patch, USE_TOYBOX_DEBUG("x")"up#i:R", TOYFLAG_USR|TOYFLAG_BIN))
32 usage: patch [-i file] [-p depth] [-Ru]
34 Apply a unified diff to one or more files.
36 -i Input file (defaults=stdin)
37 -p number of '/' to strip from start of file paths (default=all)
39 -u Ignored (only handles "unified" diffs)
41 This version of patch only handles unified diffs, and only modifies
42 a file when all all hunks to that file apply. Patch prints failed
43 hunks to stderr, and exits with nonzero status if any hunks fail.
45 A file compared against /dev/null (or with a date <= the epoch) is
46 created/deleted as appropriate.
51 struct double_list *next;
52 struct double_list *prev;
56 // Return the first item from the list, advancing the list (which must be called
59 void *TOY_llist_pop(void *list)
61 // I'd use a void ** for the argument, and even accept the typecast in all
62 // callers as documentation you need the &, except the stupid compiler
63 // would then scream about type-punned pointers. Screw it.
64 void **llist = (void **)list;
65 void **next = (void **)*llist;
71 // Free all the elements of a linked list
72 // if freeit!=NULL call freeit() on each element before freeing it.
74 void TOY_llist_free(void *list, void (*freeit)(void *data))
77 void *pop = TOY_llist_pop(&list);
78 if (freeit) freeit(pop);
81 // End doubly linked list too.
86 // Add an entry to the end off a doubly linked list
88 struct double_list *dlist_add(struct double_list **list, char *data)
90 struct double_list *line = xmalloc(sizeof(struct double_list));
95 line->prev = (*list)->prev;
96 (*list)->prev->next = line;
98 } else *list = line->next = line->prev = line;
103 // Ensure entire path exists.
104 // If mode != -1 set permissions on newly created dirs.
105 // Requires that path string be writable (for temporary null terminators).
107 void xmkpath(char *path, int mode)
114 for (p = path; ; p++) {
115 if (!*p || *p == '/') {
118 if (stat(path, &st) || !S_ISDIR(st.st_mode)) {
121 rc = mkdir(path, mode);
123 } else rc = mkdir(path, 0777);
126 if(rc) bb_perror_msg_and_die("mkpath '%s'", path);
134 char *get_rawline(int fd, long *plen, char end)
140 if (1>read(fd, &c, 1)) break;
141 if (!(len & 63)) buf=xrealloc(buf, len+65);
142 if ((buf[len++]=c) == end) break;
145 if (plen) *plen = len;
151 char *get_line(int fd)
154 char *buf = get_rawline(fd, &len, '\n');
156 if (buf && buf[--len]=='\n') buf[len]=0;
161 // Copy the rest of in to out and close both files.
163 void xsendfile(int in, int out)
170 len = safe_read(in, buf, 4096);
172 xwrite(out, buf, len);
176 // Copy the rest of the data and replace the original with the copy.
178 void replace_tempfile(int fdin, int fdout, char **tempname)
180 char *temp = xstrdup(*tempname);
182 temp[strlen(temp)-6]=0;
184 xsendfile(fdin, fdout);
188 rename(*tempname, temp);
194 // Open a temporary file to copy an existing file into.
196 int copy_tempfile(int fdin, char *name, char **tempname)
201 *tempname = xasprintf("%sXXXXXX", name);
202 fd = mkstemp(*tempname);
203 if(-1 == fd) bb_perror_msg_and_die("no temp file");
205 // Set permissions of output file
206 fstat(fdin, &statbuf);
207 fchmod(fd, statbuf.st_mode);
212 // Abort the copy and delete the temporary file.
214 void delete_tempfile(int fdin, int fdout, char **tempname)
229 struct double_list *current_hunk;
230 long oldline, oldlen, newline, newlen, linenum;
231 int context, state, filein, fileout, filepatch, hunknum;
237 #define TT (*ptr_to_globals)
238 #define INIT_TT() do { \
239 SET_PTR_TO_GLOBALS(xzalloc(sizeof(TT))); \
244 #define FLAG_STR "Rup:i:x"
245 /* FLAG_REVERSE must be == 1! Code uses this fact. */
246 #define FLAG_REVERSE (1 << 0)
247 #define FLAG_u (1 << 1)
248 #define FLAG_PATHLEN (1 << 2)
249 #define FLAG_INPUT (1 << 3)
251 #define FLAG_DEBUG (1 << 4)
253 // Dispose of a line of input, either by writing it out or discarding it.
255 // state < 2: just free
256 // state = 2: write whole line to stderr
257 // state = 3: write whole line to fileout
258 // state > 3: write line+1 to fileout when *line != state
260 #define PATCH_DEBUG (option_mask32 & FLAG_DEBUG)
262 static void do_line(void *data)
264 struct double_list *dlist = (struct double_list *)data;
266 if (TT.state>1 && *dlist->data != TT.state)
267 fdprintf(TT.state == 2 ? 2 : TT.fileout,
268 "%s\n", dlist->data+(TT.state>3 ? 1 : 0));
270 if (PATCH_DEBUG) fdprintf(2, "DO %d: %s\n", TT.state, dlist->data);
276 static void finish_oldfile(void)
278 if (TT.tempname) replace_tempfile(TT.filein, TT.fileout, &TT.tempname);
279 TT.fileout = TT.filein = -1;
282 static void fail_hunk(void)
284 if (!TT.current_hunk) return;
285 TT.current_hunk->prev->next = 0;
287 fdprintf(2, "Hunk %d FAILED %ld/%ld.\n", TT.hunknum, TT.oldline, TT.newline);
290 // If we got to this point, we've seeked to the end. Discard changes to
291 // this file and advance to next file.
294 TOY_llist_free(TT.current_hunk, do_line);
295 TT.current_hunk = NULL;
296 delete_tempfile(TT.filein, TT.fileout, &TT.tempname);
300 // Given a hunk of a unified diff, make the appropriate change to the file.
301 // This does not use the location information, but instead treats a hunk
302 // as a sort of regex. Copies data from input to output until it finds
303 // the change to be made, then outputs the changed data and returns.
304 // (Finding EOF first is an error.) This is a single pass operation, so
305 // multiple hunks must occur in order in the file.
307 static int apply_one_hunk(void)
309 struct double_list *plist, *buf = NULL, *check;
310 int matcheof = 0, reverse = option_mask32 & FLAG_REVERSE, backwarn = 0;
312 // Break doubly linked list so we can use singly linked traversal function.
313 TT.current_hunk->prev->next = NULL;
315 // Match EOF if there aren't as many ending context lines as beginning
316 for (plist = TT.current_hunk; plist; plist = plist->next) {
317 if (plist->data[0]==' ') matcheof++;
319 if (PATCH_DEBUG) fdprintf(2, "HUNK:%s\n", plist->data);
321 matcheof = matcheof < TT.context;
323 if (PATCH_DEBUG) fdprintf(2,"MATCHEOF=%c\n", matcheof ? 'Y' : 'N');
325 // Loop through input data searching for this hunk. Match all context
326 // lines and all lines to be removed until we've found the end of a
328 plist = TT.current_hunk;
330 if (TT.context) for (;;) {
331 char *data = get_line(TT.filein);
335 // Figure out which line of hunk to compare with next. (Skip lines
336 // of the hunk we'd be adding.)
337 while (plist && *plist->data == "+-"[reverse]) {
338 if (data && !strcmp(data, plist->data+1)) {
340 fdprintf(2,"Possibly reversed hunk %d at %ld\n",
341 TT.hunknum, TT.linenum);
350 if (PATCH_DEBUG) fdprintf(2, "INEOF\n");
352 // Does this hunk need to match EOF?
353 if (!plist && matcheof) break;
355 // File ended before we found a place for this hunk.
358 } else if (PATCH_DEBUG) fdprintf(2, "IN: %s\n", data);
359 check = dlist_add(&buf, data);
361 // Compare this line with next expected line of hunk.
362 // todo: teach the strcmp() to ignore whitespace.
364 // A match can fail because the next line doesn't match, or because
365 // we hit the end of a hunk that needed EOF, and this isn't EOF.
367 // If match failed, flush first line of buffered data and
368 // recheck buffered data for a new match until we find one or run
372 if (!plist || strcmp(check->data, plist->data+1)) {
373 // Match failed. Write out first line of buffered data and
374 // recheck remaining buffered data for a new match.
377 fdprintf(2, "NOT: %s\n", plist->data);
380 check = TOY_llist_pop(&buf);
381 check->prev->next = buf;
382 buf->prev = check->prev;
384 plist = TT.current_hunk;
386 // If we've reached the end of the buffer without confirming a
387 // match, read more lines.
395 fdprintf(2, "MAYBE: %s\n", plist->data);
396 // This line matches. Advance plist, detect successful match.
398 if (!plist && !matcheof) goto out;
400 if (check == buf) break;
405 // We have a match. Emit changed data.
406 TT.state = "-+"[reverse];
407 TOY_llist_free(TT.current_hunk, do_line);
408 TT.current_hunk = NULL;
412 buf->prev->next = NULL;
413 TOY_llist_free(buf, do_line);
419 // Read a patch file and find hunks, opening/creating/deleting files.
420 // Call apply_one_hunk() on each hunk.
422 // state 0: Not in a hunk, look for +++.
423 // state 1: Found +++ file indicator, look for @@
424 // state 2: In hunk: counting initial context lines
425 // state 3: In hunk: getting body
427 int patch_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
428 int patch_main(int argc UNUSED_PARAM, char **argv)
431 int reverse, state = 0;
432 char *oldname = NULL, *newname = NULL;
437 opts = getopt32(argv, FLAG_STR, &opt_p, &opt_i);
438 reverse = opts & FLAG_REVERSE;
439 TT.prefix = (opts & FLAG_PATHLEN) ? xatoi(opt_p) : 0; // can be negative!
440 if (opts & FLAG_INPUT) TT.filepatch = xopen(opt_i, O_RDONLY);
441 TT.filein = TT.fileout = -1;
443 // Loop through the lines in the patch
447 patchline = get_line(TT.filepatch);
448 if (!patchline) break;
450 // Other versions of patch accept damaged patches,
451 // so we need to also.
454 patchline = xstrdup(" ");
457 // Are we assembling a hunk?
459 if (*patchline==' ' || *patchline=='+' || *patchline=='-') {
460 dlist_add(&TT.current_hunk, patchline);
462 if (*patchline != '+') TT.oldlen--;
463 if (*patchline != '-') TT.newlen--;
466 if (*patchline==' ' && state==2) TT.context++;
469 // If we've consumed all expected hunk lines, apply the hunk.
471 if (!TT.oldlen && !TT.newlen) state = apply_one_hunk();
480 if (!strncmp("--- ", patchline, 4) || !strncmp("+++ ", patchline, 4)) {
481 char *s, **name = reverse ? &newname : &oldname;
484 if (*patchline == '+') {
485 name = reverse ? &oldname : &newname;
492 // Trim date from end of filename (if any). We don't care.
493 for (s = patchline+4; *s && *s!='\t'; s++)
494 if (*s=='\\' && s[1]) s++;
496 if (i>1900 && i<=1970)
497 *name = xstrdup("/dev/null");
500 *name = xstrdup(patchline+4);
503 // We defer actually opening the file because svn produces broken
504 // patches that don't signal they want to create a new file the
505 // way the patch man page says, so you have to read the first hunk
509 } else if (state == 1 && !strncmp("@@ -", patchline, 4)) {
512 i = sscanf(patchline+4, "%ld,%ld +%ld,%ld", &TT.oldline,
513 &TT.oldlen, &TT.newline, &TT.newlen);
515 bb_error_msg_and_die("corrupt hunk %d at %ld", TT.hunknum, TT.linenum);
520 // If this is the first hunk, open the file.
521 if (TT.filein == -1) {
522 int oldsum, newsum, del = 0;
525 oldsum = TT.oldline + TT.oldlen;
526 newsum = TT.newline + TT.newlen;
528 name = reverse ? oldname : newname;
530 // We're deleting oldname if new file is /dev/null (before -p)
531 // or if new hunk is empty (zero context) after patching
532 if (!strcmp(name, "/dev/null") || !(reverse ? oldsum : newsum))
534 name = reverse ? newname : oldname;
538 // handle -p path truncation.
539 for (i=0, s = name; *s;) {
540 if ((option_mask32 & FLAG_PATHLEN) && TT.prefix == i) break;
548 printf("removing %s\n", name);
551 // If we've got a file to open, do so.
552 } else if (!(option_mask32 & FLAG_PATHLEN) || i <= TT.prefix) {
553 // If the old file was null, we're creating a new one.
554 if (!strcmp(oldname, "/dev/null") || !oldsum) {
555 printf("creating %s\n", name);
556 s = strrchr(name, '/');
562 TT.filein = xopen(name, O_CREAT|O_EXCL|O_RDWR);
564 printf("patching file %s\n", name);
565 TT.filein = xopen(name, O_RDWR);
567 TT.fileout = copy_tempfile(TT.filein, name, &TT.tempname);
578 // If we didn't continue above, discard this line.
584 if (ENABLE_FEATURE_CLEAN_UP) {