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, USE_TOYBOX_DEBUG("x")"ulp#i:R", TOYFLAG_USR|TOYFLAG_BIN))
27 usage: patch [-i file] [-p depth] [-Ru]
29 Apply a unified diff to one or more files.
31 -i Input file (defaults=stdin)
32 -l Loose match (ignore whitespace)
33 -p Number of '/' to strip from start of file paths (default=all)
35 -u Ignored (only handles "unified" diffs)
37 This version of patch only handles unified diffs, and only modifies
38 a file when all all hunks to that file apply. Patch prints failed
39 hunks to stderr, and exits with nonzero status if any hunks fail.
41 A file compared against /dev/null (or with a date <= the epoch) is
42 created/deleted as appropriate.
52 struct double_list *current_hunk;
53 long oldline, oldlen, newline, newlen;
55 int context, state, filein, fileout, filepatch, hunknum;
59 // Dispose of a line of input, either by writing it out or discarding it.
61 // state < 2: just free
62 // state = 2: write whole line to stderr
63 // state = 3: write whole line to fileout
64 // state > 3: write line+1 to fileout when *line != state
66 static void do_line(void *data)
68 struct double_list *dlist = (struct double_list *)data;
70 if (TT.state>1 && *dlist->data != TT.state) {
71 char *s = dlist->data+(TT.state>3 ? 1 : 0);
72 int i = TT.state == 2 ? 2 : TT.fileout;
74 xwrite(i, s, strlen(s));
78 if (toys.optflags & FLAG_x)
79 fprintf(stderr, "DO %d: %s\n", TT.state, dlist->data);
85 static void finish_oldfile(void)
87 if (TT.tempname) replace_tempfile(TT.filein, TT.fileout, &TT.tempname);
88 TT.fileout = TT.filein = -1;
91 static void fail_hunk(void)
93 if (!TT.current_hunk) return;
95 fprintf(stderr, "Hunk %d FAILED %ld/%ld.\n",
96 TT.hunknum, TT.oldline, TT.newline);
99 // If we got to this point, we've seeked to the end. Discard changes to
100 // this file and advance to next file.
103 llist_traverse(TT.current_hunk, do_line);
104 TT.current_hunk = NULL;
105 delete_tempfile(TT.filein, TT.fileout, &TT.tempname);
109 // Compare ignoring whitespace. Just returns 0/1, no > or <
110 static int loosecmp(char *aa, char *bb)
115 while (isspace(aa[a])) a++;
116 while (isspace(bb[b])) b++;
117 if (aa[a] != bb[b]) return 1;
118 if (!aa[a]) return 0;
123 // Given a hunk of a unified diff, make the appropriate change to the file.
124 // This does not use the location information, but instead treats a hunk
125 // as a sort of regex. Copies data from input to output until it finds
126 // the change to be made, then outputs the changed data and returns.
127 // (Finding EOF first is an error.) This is a single pass operation, so
128 // multiple hunks must occur in order in the file.
130 static int apply_one_hunk(void)
132 struct double_list *plist, *buf = NULL, *check;
133 int matcheof, trailing = 0, reverse = toys.optflags & FLAG_R, backwarn = 0;
134 int (*lcmp)(char *aa, char *bb);
136 lcmp = (toys.optflags & FLAG_l) ? (void *)loosecmp : (void *)strcmp;
137 dlist_terminate(TT.current_hunk);
139 // Match EOF if there aren't as many ending context lines as beginning
140 for (plist = TT.current_hunk; plist; plist = plist->next) {
141 if (plist->data[0]==' ') trailing++;
143 if (toys.optflags & FLAG_x) fprintf(stderr, "HUNK:%s\n", plist->data);
145 matcheof = !trailing || trailing < TT.context;
147 if (toys.optflags & FLAG_x)
148 fprintf(stderr,"MATCHEOF=%c\n", matcheof ? 'Y' : 'N');
150 // Loop through input data searching for this hunk. Match all context
151 // lines and all lines to be removed until we've found the end of a
153 plist = TT.current_hunk;
157 char *data = get_line(TT.filein);
160 // Figure out which line of hunk to compare with next. (Skip lines
161 // of the hunk we'd be adding.)
162 while (plist && *plist->data == "+-"[reverse]) {
163 if (data && !lcmp(data, plist->data+1)) {
164 if (!backwarn) backwarn = TT.linenum;
171 if (toys.optflags & FLAG_x) fprintf(stderr, "INEOF\n");
173 // Does this hunk need to match EOF?
174 if (!plist && matcheof) break;
177 fprintf(stderr, "Possibly reversed hunk %d at %ld\n",
178 TT.hunknum, TT.linenum);
180 // File ended before we found a place for this hunk.
183 } else if (toys.optflags & FLAG_x) fprintf(stderr, "IN: %s\n", data);
184 check = dlist_add(&buf, data);
186 // Compare this line with next expected line of hunk.
188 // A match can fail because the next line doesn't match, or because
189 // we hit the end of a hunk that needed EOF, and this isn't EOF.
191 // If match failed, flush first line of buffered data and
192 // recheck buffered data for a new match until we find one or run
196 if (!plist || lcmp(check->data, plist->data+1)) {
197 // Match failed. Write out first line of buffered data and
198 // recheck remaining buffered data for a new match.
200 if (toys.optflags & FLAG_x) {
203 if (!plist) fprintf(stderr, "NULL plist\n");
205 while (plist->data[bug] == check->data[bug]) bug++;
206 fprintf(stderr, "NOT(%d:%d!=%d): %s\n", bug, plist->data[bug],
207 check->data[bug], plist->data);
211 // If this hunk must match start of file, fail if it didn't.
212 if (!TT.context || trailing>TT.context) {
218 do_line(check = dlist_pop(&buf));
219 plist = TT.current_hunk;
221 // If we've reached the end of the buffer without confirming a
222 // match, read more lines.
226 if (toys.optflags & FLAG_x) fprintf(stderr, "MAYBE: %s\n", plist->data);
227 // This line matches. Advance plist, detect successful match.
229 if (!plist && !matcheof) goto out;
231 if (check == buf) break;
236 // We have a match. Emit changed data.
237 TT.state = "-+"[reverse];
238 llist_traverse(TT.current_hunk, do_line);
239 TT.current_hunk = NULL;
243 dlist_terminate(buf);
244 llist_traverse(buf, do_line);
250 // Read a patch file and find hunks, opening/creating/deleting files.
251 // Call apply_one_hunk() on each hunk.
253 // state 0: Not in a hunk, look for +++.
254 // state 1: Found +++ file indicator, look for @@
255 // state 2: In hunk: counting initial context lines
256 // state 3: In hunk: getting body
258 void patch_main(void)
260 int reverse = toys.optflags&FLAG_R, state = 0, patchlinenum = 0,
262 char *oldname = NULL, *newname = NULL;
264 if (TT.infile) TT.filepatch = xopen(TT.infile, O_RDONLY);
265 TT.filein = TT.fileout = -1;
267 // Loop through the lines in the patch
271 patchline = get_line(TT.filepatch);
272 if (!patchline) break;
274 // Other versions of patch accept damaged patches,
275 // so we need to also.
276 if (strip || !patchlinenum++) {
277 int len = strlen(patchline);
278 if (patchline[len-1] == '\r') {
279 if (!strip) fprintf(stderr, "Removing DOS newlines\n");
286 patchline = xstrdup(" ");
289 // Are we assembling a hunk?
291 if (*patchline==' ' || *patchline=='+' || *patchline=='-') {
292 dlist_add(&TT.current_hunk, patchline);
294 if (*patchline != '+') TT.oldlen--;
295 if (*patchline != '-') TT.newlen--;
298 if (*patchline==' ' && state==2) TT.context++;
301 // If we've consumed all expected hunk lines, apply the hunk.
303 if (!TT.oldlen && !TT.newlen) state = apply_one_hunk();
306 dlist_terminate(TT.current_hunk);
313 if (!strncmp("--- ", patchline, 4) || !strncmp("+++ ", patchline, 4)) {
314 char *s, **name = &oldname;
317 if (*patchline == '+') {
325 // Trim date from end of filename (if any). We don't care.
326 for (s = patchline+4; *s && *s!='\t'; s++)
327 if (*s=='\\' && s[1]) s++;
329 if (i>1900 && i<=1970) *name = xstrdup("/dev/null");
332 *name = xstrdup(patchline+4);
335 // We defer actually opening the file because svn produces broken
336 // patches that don't signal they want to create a new file the
337 // way the patch man page says, so you have to read the first hunk
340 // Start a new hunk? Usually @@ -oldline,oldlen +newline,newlen @@
341 // but a missing ,value means the value is 1.
342 } else if (state == 1 && !strncmp("@@ -", patchline, 4)) {
344 char *s = patchline+4;
346 // Read oldline[,oldlen] +newline[,newlen]
348 TT.oldlen = TT.newlen = 1;
349 TT.oldline = strtol(s, &s, 10);
350 if (*s == ',') TT.oldlen=strtol(s+1, &s, 10);
351 TT.newline = strtol(s+2, &s, 10);
352 if (*s == ',') TT.newlen = strtol(s+1, &s, 10);
357 // If this is the first hunk, open the file.
358 if (TT.filein == -1) {
359 int oldsum, newsum, del = 0;
362 oldsum = TT.oldline + TT.oldlen;
363 newsum = TT.newline + TT.newlen;
365 name = reverse ? oldname : newname;
367 // We're deleting oldname if new file is /dev/null (before -p)
368 // or if new hunk is empty (zero context) after patching
369 if (!strcmp(name, "/dev/null") || !(reverse ? oldsum : newsum))
371 name = reverse ? newname : oldname;
375 // handle -p path truncation.
376 for (i = 0, s = name; *s;) {
377 if ((toys.optflags & FLAG_p) && TT.prefix == i) break;
378 if (*s++ != '/') continue;
379 while (*s == '/') s++;
385 printf("removing %s\n", name);
388 // If we've got a file to open, do so.
389 } else if (!(toys.optflags & FLAG_p) || i <= TT.prefix) {
390 // If the old file was null, we're creating a new one.
391 if ((!strcmp(oldname, "/dev/null") || !oldsum) && access(name, F_OK))
393 printf("creating %s\n", name);
394 if (mkpathat(AT_FDCWD, name, 0, 2))
395 perror_exit("mkpath %s", name);
396 TT.filein = xcreate(name, O_CREAT|O_EXCL|O_RDWR, 0666);
398 printf("patching %s\n", name);
399 TT.filein = xopen(name, O_RDONLY);
401 TT.fileout = copy_tempfile(TT.filein, name, &TT.tempname);
412 // If we didn't continue above, discard this line.
418 if (CFG_TOYBOX_FREE) {