1 /* Adapted from toybox's patch. Currently unused */
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, "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)
226 struct double_list *plines;
236 #define TT (*ptr_to_globals)
237 #define INIT_TT() do { \
238 SET_PTR_TO_GLOBALS(xzalloc(sizeof(TT))); \
243 #define FLAG_STR "Rup:i:"
244 /* FLAG_REVERSE must be == 1! Code uses this fact. */
245 #define FLAG_REVERSE (1 << 0)
246 #define FLAG_u (1 << 1)
247 #define FLAG_PATHLEN (1 << 2)
248 #define FLAG_INPUT (1 << 3)
250 // Dispose of a line of input, either by writing it out or discarding it.
252 // state < 2: just free
253 // state = 2: write whole line to stderr
254 // state = 3: write whole line to fileout
255 // state > 3: write line+1 to fileout when *line != state
257 static void do_line(void *data)
259 struct double_list *dlist = (struct double_list *)data;
261 if (TT.state>1 && *dlist->data != TT.state)
262 fdprintf(TT.state == 2 ? 2 : TT.fileout,
263 "%s\n", dlist->data+(TT.state>3 ? 1 : 0));
269 static void finish_oldfile(void)
271 if (TT.tempname) replace_tempfile(TT.filein, TT.fileout, &TT.tempname);
272 TT.fileout = TT.filein = -1;
275 static void fail_hunk(void)
277 if (!TT.plines) return;
278 TT.plines->prev->next = 0;
280 fdprintf(2, "Hunk %d FAILED.\n", TT.hunknum);
283 // If we got to this point, we've seeked to the end. Discard changes to
284 // this file and advance to next file.
287 TOY_llist_free(TT.plines, do_line);
289 delete_tempfile(TT.filein, TT.fileout, &TT.tempname);
293 static int apply_hunk(void)
295 struct double_list *plist, *buf = NULL, *check;
296 int i = 0, backwards = 0, matcheof = 0,
297 reverse = option_mask32 & FLAG_REVERSE;
299 // Break doubly linked list so we can use singly linked traversal function.
300 TT.plines->prev->next = NULL;
302 // Match EOF if there aren't as many ending context lines as beginning
303 for (plist = TT.plines; plist; plist = plist->next) {
304 if (plist->data[0]==' ') i++;
307 if (i < TT.context) matcheof++;
309 // Search for a place to apply this hunk. Match all context lines and
310 // lines to be removed.
316 if (TT.context) for (;;) {
317 char *data = get_line(TT.filein);
321 // Skip lines of the hunk we'd be adding.
322 while (plist && *plist->data == "+-"[reverse]) {
323 if (data && !strcmp(data, plist->data+1)) {
324 if (++backwards == TT.context)
325 fdprintf(2,"Possibly reversed hunk %d at %ld\n",
326 TT.hunknum, TT.linenum);
333 // Does this hunk need to match EOF?
334 if (!plist && matcheof) break;
336 // File ended before we found a place for this hunk.
340 check = dlist_add(&buf, data);
342 // todo: teach the strcmp() to ignore whitespace.
345 // If we hit the end of a hunk that needed EOF and this isn't EOF,
346 // or next line doesn't match, flush first line of buffered data and
347 // recheck match until we find a new match or run out of buffer.
349 if (!plist || strcmp(check->data, plist->data+1)) {
350 // First line isn't a match, write it out.
352 check = TOY_llist_pop(&buf);
353 check->prev->next = buf;
354 buf->prev = check->prev;
358 // Out of buffered lines?
365 // This line matches. Advance plist, detect successful match.
367 if (!plist && !matcheof) goto out;
369 if (check == buf) break;
374 // Got it. Emit changed data.
375 TT.state = "-+"[reverse];
376 TOY_llist_free(TT.plines, do_line);
381 buf->prev->next = NULL;
382 TOY_llist_free(buf, do_line);
388 // state 0: Not in a hunk, look for +++.
389 // state 1: Found +++ file indicator, look for @@
390 // state 2: In hunk: counting initial context lines
391 // state 3: In hunk: getting body
393 int patch_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
394 int patch_main(int argc UNUSED_PARAM, char **argv)
397 int reverse, state = 0;
398 char *oldname = NULL, *newname = NULL;
402 long oldline = 0, oldlen = 0, newline = 0, newlen = 0;
406 opts = getopt32(argv, FLAG_STR, &opt_p, &opt_i);
407 reverse = opts & FLAG_REVERSE;
409 if (opts & FLAG_INPUT) xmove_fd(xopen(opt_i, O_RDONLY), STDIN_FILENO);
410 prefix = (opts & FLAG_PATHLEN) ? xatoi(opt_p) : 0; // can be negative!
411 TT.filein = TT.fileout = -1;
413 // Loop through the lines in the patch
417 patchline = get_line(STDIN_FILENO);
418 if (!patchline) break;
420 // Other versions of patch accept damaged patches,
421 // so we need to also.
424 patchline = xstrdup(" ");
427 // Are we assembling a hunk?
429 if (*patchline==' ' || *patchline=='+' || *patchline=='-') {
430 dlist_add(&TT.plines, patchline);
432 if (*patchline != '+') oldlen--;
433 if (*patchline != '-') newlen--;
436 if (*patchline==' ' && state==2) TT.context++;
439 // If we've consumed all expected hunk lines, apply the hunk.
440 if (!oldlen && !newlen) state = apply_hunk();
449 if (!strncmp("--- ", patchline, 4) || !strncmp("+++ ", patchline, 4)) {
450 char *s, **name = &oldname;
453 if (*patchline == '+') {
461 // Trim date from end of filename (if any). We don't care.
462 for (s = patchline+4; *s && *s!='\t'; s++)
463 if (*s=='\\' && s[1]) s++;
466 *name = xstrdup("/dev/null");
469 *name = xstrdup(patchline+4);
472 // We defer actually opening the file because svn produces broken
473 // patches that don't signal they want to create a new file the
474 // way the patch man page says, so you have to read the first hunk
478 } else if (state == 1 && !strncmp("@@ -", patchline, 4)) {
481 i = sscanf(patchline+4, "%ld,%ld +%ld,%ld",
482 &oldline, &oldlen, &newline, &newlen);
484 bb_error_msg_and_die("corrupt hunk %d at %ld", TT.hunknum, TT.linenum);
489 // If this is the first hunk, open the file.
490 if (TT.filein == -1) {
491 int oldsum, newsum, del = 0;
494 oldsum = oldline + oldlen;
495 newsum = newline + newlen;
497 name = reverse ? oldname : newname;
499 // We're deleting oldname if new file is /dev/null (before -p)
500 // or if new hunk is empty (zero context) after patching
501 if (!strcmp(name, "/dev/null") || !(reverse ? oldsum : newsum)) {
502 name = reverse ? newname : oldname;
506 // handle -p path truncation.
507 for (i=0, s = name; *s;) {
508 if ((option_mask32 & FLAG_PATHLEN) && prefix == i)
517 printf("removing %s\n", name);
520 // If we've got a file to open, do so.
521 } else if (!(option_mask32 & FLAG_PATHLEN) || i <= prefix) {
522 // If the old file was null, we're creating a new one.
523 if (!strcmp(oldname, "/dev/null") || !oldsum) {
524 printf("creating %s\n", name);
525 s = strrchr(name, '/');
531 TT.filein = xopen3(name, O_CREAT|O_EXCL|O_RDWR, 0666);
533 printf("patching file %s\n", name);
534 TT.filein = xopen(name, O_RDWR);
536 TT.fileout = copy_tempfile(TT.filein, name, &TT.tempname);
547 // If we didn't continue above, discard this line.
553 if (ENABLE_FEATURE_CLEAN_UP) {