1 /* patch.c - Apply a "universal" diff.
3 * Copyright 2007 Rob Landley <rob@landley.net>
5 * see http://opengroup.org/onlinepubs/9699919799/utilities/patch.html
6 * (But only does -u, because who still cares about "ed"?)
10 * -N ignore already applied
12 * -D define wrap #ifdef and #ifndef around changes
13 * -o outfile output here instead of in place
14 * -r rejectfile write rejected hunks to this file
16 * -E remove empty files --remove-empty-files
17 * -f force (no questions asked)
18 * -F fuzz (number, default 2)
19 * [file] which file to patch
21 USE_PATCH(NEWTOY(patch, "(dry-run)"USE_TOYBOX_DEBUG("x")"d:ulp#i:R", TOYFLAG_USR|TOYFLAG_BIN))
27 usage: patch [-d DIR] [-i file] [-p depth] [-Rlu] [--dry-run]
29 Apply a unified diff to one or more files.
31 -d modify files in DIR
32 -i Input file (defaults=stdin)
33 -l Loose match (ignore whitespace)
34 -p Number of '/' to strip from start of file paths (default=all)
36 -u Ignored (only handles "unified" diffs)
37 --dry-run Don't change files, just confirm patch applies
39 This version of patch only handles unified diffs, and only modifies
40 a file when all all hunks to that file apply. Patch prints failed
41 hunks to stderr, and exits with nonzero status if any hunks fail.
43 A file compared against /dev/null (or with a date <= the epoch) is
44 created/deleted as appropriate.
55 struct double_list *current_hunk;
56 long oldline, oldlen, newline, newlen;
58 int context, state, filein, fileout, filepatch, hunknum;
62 // Dispose of a line of input, either by writing it out or discarding it.
64 // state < 2: just free
65 // state = 2: write whole line to stderr
66 // state = 3: write whole line to fileout
67 // state > 3: write line+1 to fileout when *line != state
69 static void do_line(void *data)
71 struct double_list *dlist = (struct double_list *)data;
73 if (TT.state>1 && *dlist->data != TT.state) {
74 char *s = dlist->data+(TT.state>3 ? 1 : 0);
75 int i = TT.state == 2 ? 2 : TT.fileout;
77 xwrite(i, s, strlen(s));
81 if (toys.optflags & FLAG_x)
82 fprintf(stderr, "DO %d: %s\n", TT.state, dlist->data);
88 static void finish_oldfile(void)
90 if (TT.tempname) replace_tempfile(TT.filein, TT.fileout, &TT.tempname);
91 TT.fileout = TT.filein = -1;
94 static void fail_hunk(void)
96 if (!TT.current_hunk) return;
98 fprintf(stderr, "Hunk %d FAILED %ld/%ld.\n",
99 TT.hunknum, TT.oldline, TT.newline);
102 // If we got to this point, we've seeked to the end. Discard changes to
103 // this file and advance to next file.
106 llist_traverse(TT.current_hunk, do_line);
107 TT.current_hunk = NULL;
108 if (!(toys.optflags & FLAG_dry_run))
109 delete_tempfile(TT.filein, TT.fileout, &TT.tempname);
113 // Compare ignoring whitespace. Just returns 0/1, no > or <
114 static int loosecmp(char *aa, char *bb)
119 while (isspace(aa[a])) a++;
120 while (isspace(bb[b])) b++;
121 if (aa[a] != bb[b]) return 1;
122 if (!aa[a]) return 0;
127 // Given a hunk of a unified diff, make the appropriate change to the file.
128 // This does not use the location information, but instead treats a hunk
129 // as a sort of regex. Copies data from input to output until it finds
130 // the change to be made, then outputs the changed data and returns.
131 // (Finding EOF first is an error.) This is a single pass operation, so
132 // multiple hunks must occur in order in the file.
134 static int apply_one_hunk(void)
136 struct double_list *plist, *buf = NULL, *check;
137 int matcheof, trailing = 0, reverse = toys.optflags & FLAG_R, backwarn = 0;
138 int (*lcmp)(char *aa, char *bb);
140 lcmp = (toys.optflags & FLAG_l) ? (void *)loosecmp : (void *)strcmp;
141 dlist_terminate(TT.current_hunk);
143 // Match EOF if there aren't as many ending context lines as beginning
144 for (plist = TT.current_hunk; plist; plist = plist->next) {
145 if (plist->data[0]==' ') trailing++;
147 if (toys.optflags & FLAG_x) fprintf(stderr, "HUNK:%s\n", plist->data);
149 matcheof = !trailing || trailing < TT.context;
151 if (toys.optflags & FLAG_x)
152 fprintf(stderr,"MATCHEOF=%c\n", matcheof ? 'Y' : 'N');
154 // Loop through input data searching for this hunk. Match all context
155 // lines and all lines to be removed until we've found the end of a
157 plist = TT.current_hunk;
161 char *data = get_line(TT.filein);
164 // Figure out which line of hunk to compare with next. (Skip lines
165 // of the hunk we'd be adding.)
166 while (plist && *plist->data == "+-"[reverse]) {
167 if (data && !lcmp(data, plist->data+1)) {
168 if (!backwarn) backwarn = TT.linenum;
175 if (toys.optflags & FLAG_x) fprintf(stderr, "INEOF\n");
177 // Does this hunk need to match EOF?
178 if (!plist && matcheof) break;
181 fprintf(stderr, "Possibly reversed hunk %d at %ld\n",
182 TT.hunknum, TT.linenum);
184 // File ended before we found a place for this hunk.
187 } else if (toys.optflags & FLAG_x) fprintf(stderr, "IN: %s\n", data);
188 check = dlist_add(&buf, data);
190 // Compare this line with next expected line of hunk.
192 // A match can fail because the next line doesn't match, or because
193 // we hit the end of a hunk that needed EOF, and this isn't EOF.
195 // If match failed, flush first line of buffered data and
196 // recheck buffered data for a new match until we find one or run
200 if (!plist || lcmp(check->data, plist->data+1)) {
201 // Match failed. Write out first line of buffered data and
202 // recheck remaining buffered data for a new match.
204 if (toys.optflags & FLAG_x) {
207 if (!plist) fprintf(stderr, "NULL plist\n");
209 while (plist->data[bug] == check->data[bug]) bug++;
210 fprintf(stderr, "NOT(%d:%d!=%d): %s\n", bug, plist->data[bug],
211 check->data[bug], plist->data);
215 // If this hunk must match start of file, fail if it didn't.
216 if (!TT.context || trailing>TT.context) {
222 do_line(check = dlist_pop(&buf));
223 plist = TT.current_hunk;
225 // If we've reached the end of the buffer without confirming a
226 // match, read more lines.
230 if (toys.optflags & FLAG_x) fprintf(stderr, "MAYBE: %s\n", plist->data);
231 // This line matches. Advance plist, detect successful match.
233 if (!plist && !matcheof) goto out;
235 if (check == buf) break;
240 // We have a match. Emit changed data.
241 TT.state = "-+"[reverse];
242 llist_traverse(TT.current_hunk, do_line);
243 TT.current_hunk = NULL;
247 dlist_terminate(buf);
248 llist_traverse(buf, do_line);
254 // Read a patch file and find hunks, opening/creating/deleting files.
255 // Call apply_one_hunk() on each hunk.
257 // state 0: Not in a hunk, look for +++.
258 // state 1: Found +++ file indicator, look for @@
259 // state 2: In hunk: counting initial context lines
260 // state 3: In hunk: getting body
262 void patch_main(void)
264 int reverse = toys.optflags&FLAG_R, state = 0, patchlinenum = 0,
266 char *oldname = NULL, *newname = NULL;
268 if (TT.infile) TT.filepatch = xopen(TT.infile, O_RDONLY);
269 TT.filein = TT.fileout = -1;
271 if (TT.dir) xchdir(TT.dir);
273 // Loop through the lines in the patch
277 patchline = get_line(TT.filepatch);
278 if (!patchline) break;
280 // Other versions of patch accept damaged patches,
281 // so we need to also.
282 if (strip || !patchlinenum++) {
283 int len = strlen(patchline);
284 if (patchline[len-1] == '\r') {
285 if (!strip) fprintf(stderr, "Removing DOS newlines\n");
292 patchline = xstrdup(" ");
295 // Are we assembling a hunk?
297 if (*patchline==' ' || *patchline=='+' || *patchline=='-') {
298 dlist_add(&TT.current_hunk, patchline);
300 if (*patchline != '+') TT.oldlen--;
301 if (*patchline != '-') TT.newlen--;
304 if (*patchline==' ' && state==2) TT.context++;
307 // If we've consumed all expected hunk lines, apply the hunk.
309 if (!TT.oldlen && !TT.newlen) state = apply_one_hunk();
312 dlist_terminate(TT.current_hunk);
319 if (!strncmp("--- ", patchline, 4) || !strncmp("+++ ", patchline, 4)) {
320 char *s, **name = &oldname;
323 if (*patchline == '+') {
331 // Trim date from end of filename (if any). We don't care.
332 for (s = patchline+4; *s && *s!='\t'; s++)
333 if (*s=='\\' && s[1]) s++;
335 if (i>1900 && i<=1970) *name = xstrdup("/dev/null");
338 *name = xstrdup(patchline+4);
341 // We defer actually opening the file because svn produces broken
342 // patches that don't signal they want to create a new file the
343 // way the patch man page says, so you have to read the first hunk
346 // Start a new hunk? Usually @@ -oldline,oldlen +newline,newlen @@
347 // but a missing ,value means the value is 1.
348 } else if (state == 1 && !strncmp("@@ -", patchline, 4)) {
350 char *s = patchline+4;
352 // Read oldline[,oldlen] +newline[,newlen]
354 TT.oldlen = TT.newlen = 1;
355 TT.oldline = strtol(s, &s, 10);
356 if (*s == ',') TT.oldlen=strtol(s+1, &s, 10);
357 TT.newline = strtol(s+2, &s, 10);
358 if (*s == ',') TT.newlen = strtol(s+1, &s, 10);
363 // If this is the first hunk, open the file.
364 if (TT.filein == -1) {
365 int oldsum, newsum, del = 0;
368 oldsum = TT.oldline + TT.oldlen;
369 newsum = TT.newline + TT.newlen;
371 name = reverse ? oldname : newname;
373 // We're deleting oldname if new file is /dev/null (before -p)
374 // or if new hunk is empty (zero context) after patching
375 if (!strcmp(name, "/dev/null") || !(reverse ? oldsum : newsum))
377 name = reverse ? newname : oldname;
381 // handle -p path truncation.
382 for (i = 0, s = name; *s;) {
383 if ((toys.optflags & FLAG_p) && TT.prefix == i) break;
384 if (*s++ != '/') continue;
385 while (*s == '/') s++;
391 printf("removing %s\n", name);
394 // If we've got a file to open, do so.
395 } else if (!(toys.optflags & FLAG_p) || i <= TT.prefix) {
396 // If the old file was null, we're creating a new one.
397 if ((!strcmp(oldname, "/dev/null") || !oldsum) && access(name, F_OK))
399 printf("creating %s\n", name);
400 if (mkpathat(AT_FDCWD, name, 0, 2))
401 perror_exit("mkpath %s", name);
402 TT.filein = xcreate(name, O_CREAT|O_EXCL|O_RDWR, 0666);
404 printf("patching %s\n", name);
405 TT.filein = xopen(name, O_RDONLY);
407 if (toys.optflags & FLAG_dry_run)
408 TT.fileout = xopen("/dev/null", O_RDWR);
409 else TT.fileout = copy_tempfile(TT.filein, name, &TT.tempname);
420 // If we didn't continue above, discard this line.
426 if (CFG_TOYBOX_FREE) {