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 * -l treat all whitespace as a single space
11 * -N ignore already applied
13 * -D define wrap #ifdef and #ifndef around changes
14 * -o outfile output here instead of in place
15 * -r rejectfile write rejected hunks to this file
17 * -E remove empty files --remove-empty-files
18 * -f force (no questions asked)
19 * -F fuzz (number, default 2)
20 * [file] which file to patch
22 USE_PATCH(NEWTOY(patch, USE_TOYBOX_DEBUG("x")"ulp#i:R", TOYFLAG_USR|TOYFLAG_BIN))
28 usage: patch [-i file] [-p depth] [-Ru]
30 Apply a unified diff to one or more files.
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)
38 This version of patch only handles unified diffs, and only modifies
39 a file when all all hunks to that file apply. Patch prints failed
40 hunks to stderr, and exits with nonzero status if any hunks fail.
42 A file compared against /dev/null (or with a date <= the epoch) is
43 created/deleted as appropriate.
53 struct double_list *current_hunk;
54 long oldline, oldlen, newline, newlen;
56 int context, state, filein, fileout, filepatch, hunknum;
60 // Dispose of a line of input, either by writing it out or discarding it.
62 // state < 2: just free
63 // state = 2: write whole line to stderr
64 // state = 3: write whole line to fileout
65 // state > 3: write line+1 to fileout when *line != state
67 #define PATCH_DEBUG (CFG_TOYBOX_DEBUG && (toys.optflags & 32))
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 (PATCH_DEBUG) fprintf(stderr, "DO %d: %s\n", TT.state, dlist->data);
87 static void finish_oldfile(void)
89 if (TT.tempname) replace_tempfile(TT.filein, TT.fileout, &TT.tempname);
90 TT.fileout = TT.filein = -1;
93 static void fail_hunk(void)
95 if (!TT.current_hunk) return;
96 TT.current_hunk->prev->next = 0;
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 delete_tempfile(TT.filein, TT.fileout, &TT.tempname);
112 // Compare ignoring whitespace. Just returns
113 static int loosecmp(char *aa, char *bb)
118 while (isspace(aa[a])) a++;
119 while (isspace(bb[b])) b++;
120 if (aa[a] != bb[b]) return 1;
121 if (!aa[a]) return 0;
126 // Given a hunk of a unified diff, make the appropriate change to the file.
127 // This does not use the location information, but instead treats a hunk
128 // as a sort of regex. Copies data from input to output until it finds
129 // the change to be made, then outputs the changed data and returns.
130 // (Finding EOF first is an error.) This is a single pass operation, so
131 // multiple hunks must occur in order in the file.
133 static int apply_one_hunk(void)
135 struct double_list *plist, *buf = NULL, *check;
136 int matcheof = 0, reverse = toys.optflags & FLAG_R, backwarn = 0;
137 int (*lcmp)(char *aa, char *bb);
139 lcmp = (toys.optflags & FLAG_l) ? (void *)loosecmp : (void *)strcmp;
141 // Break doubly linked list so we can use singly linked traversal function.
142 TT.current_hunk->prev->next = NULL;
144 // Match EOF if there aren't as many ending context lines as beginning
145 for (plist = TT.current_hunk; plist; plist = plist->next) {
146 if (plist->data[0]==' ') matcheof++;
148 if (PATCH_DEBUG) fprintf(stderr, "HUNK:%s\n", plist->data);
150 matcheof = matcheof < TT.context;
152 if (PATCH_DEBUG) 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;
159 if (TT.context) for (;;) {
160 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 (PATCH_DEBUG) 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 (PATCH_DEBUG) 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 (PATCH_DEBUG) fprintf(stderr, "NOT: %s\n", plist->data);
207 do_line(check = dlist_pop(&buf));
208 plist = TT.current_hunk;
210 // If we've reached the end of the buffer without confirming a
211 // match, read more lines.
215 if (PATCH_DEBUG) fprintf(stderr, "MAYBE: %s\n", plist->data);
216 // This line matches. Advance plist, detect successful match.
218 if (!plist && !matcheof) goto out;
220 if (check == buf) break;
225 // We have a match. Emit changed data.
226 TT.state = "-+"[reverse];
227 llist_traverse(TT.current_hunk, do_line);
228 TT.current_hunk = NULL;
232 buf->prev->next = NULL;
233 llist_traverse(buf, do_line);
239 // Read a patch file and find hunks, opening/creating/deleting files.
240 // Call apply_one_hunk() on each hunk.
242 // state 0: Not in a hunk, look for +++.
243 // state 1: Found +++ file indicator, look for @@
244 // state 2: In hunk: counting initial context lines
245 // state 3: In hunk: getting body
247 void patch_main(void)
249 int reverse = toys.optflags&FLAG_R, state = 0, patchlinenum = 0,
251 char *oldname = NULL, *newname = NULL;
253 if (TT.infile) TT.filepatch = xopen(TT.infile, O_RDONLY);
254 TT.filein = TT.fileout = -1;
256 // Loop through the lines in the patch
260 patchline = get_line(TT.filepatch);
261 if (!patchline) break;
263 // Other versions of patch accept damaged patches,
264 // so we need to also.
265 if (strip || !patchlinenum++) {
266 int len = strlen(patchline);
267 if (patchline[len-1] == '\r') {
268 if (!strip) fprintf(stderr, "Removing DOS newlines\n");
275 patchline = xstrdup(" ");
278 // Are we assembling a hunk?
280 if (*patchline==' ' || *patchline=='+' || *patchline=='-') {
281 dlist_add(&TT.current_hunk, patchline);
283 if (*patchline != '+') TT.oldlen--;
284 if (*patchline != '-') TT.newlen--;
287 if (*patchline==' ' && state==2) TT.context++;
290 // If we've consumed all expected hunk lines, apply the hunk.
292 if (!TT.oldlen && !TT.newlen) state = apply_one_hunk();
301 if (!strncmp("--- ", patchline, 4) || !strncmp("+++ ", patchline, 4)) {
302 char *s, **name = &oldname;
305 if (*patchline == '+') {
313 // Trim date from end of filename (if any). We don't care.
314 for (s = patchline+4; *s && *s!='\t'; s++)
315 if (*s=='\\' && s[1]) s++;
317 if (i>1900 && i<=1970) *name = xstrdup("/dev/null");
320 *name = xstrdup(patchline+4);
323 // We defer actually opening the file because svn produces broken
324 // patches that don't signal they want to create a new file the
325 // way the patch man page says, so you have to read the first hunk
328 // Start a new hunk? Usually @@ -oldline,oldlen +newline,newlen @@
329 // but a missing ,value means the value is 1.
330 } else if (state == 1 && !strncmp("@@ -", patchline, 4)) {
332 char *s = patchline+4;
334 // Read oldline[,oldlen] +newline[,newlen]
336 TT.oldlen = TT.newlen = 1;
337 TT.oldline = strtol(s, &s, 10);
338 if (*s == ',') TT.oldlen=strtol(s+1, &s, 10);
339 TT.newline = strtol(s+2, &s, 10);
340 if (*s == ',') TT.newlen = strtol(s+1, &s, 10);
345 // If this is the first hunk, open the file.
346 if (TT.filein == -1) {
347 int oldsum, newsum, del = 0;
350 oldsum = TT.oldline + TT.oldlen;
351 newsum = TT.newline + TT.newlen;
353 name = reverse ? oldname : newname;
355 // We're deleting oldname if new file is /dev/null (before -p)
356 // or if new hunk is empty (zero context) after patching
357 if (!strcmp(name, "/dev/null") || !(reverse ? oldsum : newsum))
359 name = reverse ? newname : oldname;
363 // handle -p path truncation.
364 for (i = 0, s = name; *s;) {
365 if ((toys.optflags & FLAG_p) && TT.prefix == i) break;
366 if (*s++ != '/') continue;
367 while (*s == '/') s++;
373 printf("removing %s\n", name);
376 // If we've got a file to open, do so.
377 } else if (!(toys.optflags & FLAG_p) || i <= TT.prefix) {
378 // If the old file was null, we're creating a new one.
379 if ((!strcmp(oldname, "/dev/null") || !oldsum) && access(name, F_OK))
381 printf("creating %s\n", name);
382 s = strrchr(name, '/');
388 TT.filein = xcreate(name, O_CREAT|O_EXCL|O_RDWR, 0666);
390 printf("patching %s\n", name);
391 TT.filein = xopen(name, O_RDONLY);
393 TT.fileout = copy_tempfile(TT.filein, name, &TT.tempname);
404 // If we didn't continue above, discard this line.
410 if (CFG_TOYBOX_FREE) {