OSDN Git Service

Adjust patch to use dlist_pop()
[android-x86/external-toybox.git] / toys / posix / patch.c
1 /* patch.c - Apply a "universal" diff.
2  *
3  * Copyright 2007 Rob Landley <rob@landley.net>
4  *
5  * see http://opengroup.org/onlinepubs/9699919799/utilities/patch.html
6  * (But only does -u, because who still cares about "ed"?)
7  *
8  * TODO:
9  * -b backup
10  * -l treat all whitespace as a single space
11  * -N ignore already applied
12  * -d chdir first
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
16  *
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
21
22 USE_PATCH(NEWTOY(patch, USE_TOYBOX_DEBUG("x")"ulp#i:R", TOYFLAG_USR|TOYFLAG_BIN))
23
24 config PATCH
25   bool "patch"
26   default y
27   help
28     usage: patch [-i file] [-p depth] [-Ru]
29
30     Apply a unified diff to one or more files.
31
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)
35     -R  Reverse patch.
36     -u  Ignored (only handles "unified" diffs)
37
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.
41
42     A file compared against /dev/null (or with a date <= the epoch) is
43     created/deleted as appropriate.
44 */
45
46 #define FOR_patch
47 #include "toys.h"
48
49 GLOBALS(
50   char *infile;
51   long prefix;
52
53   struct double_list *current_hunk;
54   long oldline, oldlen, newline, newlen;
55   long linenum;
56   int context, state, filein, fileout, filepatch, hunknum;
57   char *tempname;
58 )
59
60 // Dispose of a line of input, either by writing it out or discarding it.
61
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
66
67 #define PATCH_DEBUG (CFG_TOYBOX_DEBUG && (toys.optflags & 32))
68
69 static void do_line(void *data)
70 {
71   struct double_list *dlist = (struct double_list *)data;
72
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;
76
77     xwrite(i, s, strlen(s));
78     xwrite(i, "\n", 1);
79   }
80
81   if (PATCH_DEBUG) fprintf(stderr, "DO %d: %s\n", TT.state, dlist->data);
82
83   free(dlist->data);
84   free(data);
85 }
86
87 static void finish_oldfile(void)
88 {
89   if (TT.tempname) replace_tempfile(TT.filein, TT.fileout, &TT.tempname);
90   TT.fileout = TT.filein = -1;
91 }
92
93 static void fail_hunk(void)
94 {
95   if (!TT.current_hunk) return;
96   TT.current_hunk->prev->next = 0;
97
98   fprintf(stderr, "Hunk %d FAILED %ld/%ld.\n",
99       TT.hunknum, TT.oldline, TT.newline);
100   toys.exitval = 1;
101
102   // If we got to this point, we've seeked to the end.  Discard changes to
103   // this file and advance to next file.
104
105   TT.state = 2;
106   llist_traverse(TT.current_hunk, do_line);
107   TT.current_hunk = NULL;
108   delete_tempfile(TT.filein, TT.fileout, &TT.tempname);
109   TT.state = 0;
110 }
111
112 // Compare ignoring whitespace. Just returns
113 static int loosecmp(char *aa, char *bb)
114 {
115   int a = 0, b = 0;
116
117   for (;;) {
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;
122     a++, b++;
123   }
124 }
125
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.
132
133 static int apply_one_hunk(void)
134 {
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);
138
139   lcmp = (toys.optflags & FLAG_l) ? (void *)loosecmp : (void *)strcmp;
140
141   // Break doubly linked list so we can use singly linked traversal function.
142   TT.current_hunk->prev->next = NULL;
143
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++;
147     else matcheof = 0;
148     if (PATCH_DEBUG) fprintf(stderr, "HUNK:%s\n", plist->data);
149   }
150   matcheof = matcheof < TT.context;
151
152   if (PATCH_DEBUG) fprintf(stderr,"MATCHEOF=%c\n", matcheof ? 'Y' : 'N');
153
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
156   // complete hunk.
157   plist = TT.current_hunk;
158   buf = NULL;
159   if (TT.context) for (;;) {
160     char *data = get_line(TT.filein);
161
162     TT.linenum++;
163
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;
169       }
170       plist = plist->next;
171     }
172
173     // Is this EOF?
174     if (!data) {
175       if (PATCH_DEBUG) fprintf(stderr, "INEOF\n");
176
177       // Does this hunk need to match EOF?
178       if (!plist && matcheof) break;
179
180       if (backwarn)
181         fprintf(stderr, "Possibly reversed hunk %d at %ld\n",
182             TT.hunknum, TT.linenum);
183
184       // File ended before we found a place for this hunk.
185       fail_hunk();
186       goto done;
187     } else if (PATCH_DEBUG) fprintf(stderr, "IN: %s\n", data);
188     check = dlist_add(&buf, data);
189
190     // Compare this line with next expected line of hunk.
191
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.
194
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
197     // out of buffer.
198
199     for (;;) {
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.
203
204         if (PATCH_DEBUG) fprintf(stderr, "NOT: %s\n", plist->data);
205
206         TT.state = 3;
207         do_line(check = dlist_pop(&buf));
208         plist = TT.current_hunk;
209
210         // If we've reached the end of the buffer without confirming a
211         // match, read more lines.
212         if (!buf) break;
213         check = buf;
214       } else {
215         if (PATCH_DEBUG) fprintf(stderr, "MAYBE: %s\n", plist->data);
216         // This line matches.  Advance plist, detect successful match.
217         plist = plist->next;
218         if (!plist && !matcheof) goto out;
219         check = check->next;
220         if (check == buf) break;
221       }
222     }
223   }
224 out:
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;
229   TT.state = 1;
230 done:
231   if (buf) {
232     buf->prev->next = NULL;
233     llist_traverse(buf, do_line);
234   }
235
236   return TT.state;
237 }
238
239 // Read a patch file and find hunks, opening/creating/deleting files.
240 // Call apply_one_hunk() on each hunk.
241
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
246
247 void patch_main(void)
248 {
249   int reverse = toys.optflags&FLAG_R, state = 0, patchlinenum = 0,
250     strip = 0;
251   char *oldname = NULL, *newname = NULL;
252
253   if (TT.infile) TT.filepatch = xopen(TT.infile, O_RDONLY);
254   TT.filein = TT.fileout = -1;
255
256   // Loop through the lines in the patch
257   for (;;) {
258     char *patchline;
259
260     patchline = get_line(TT.filepatch);
261     if (!patchline) break;
262
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");
269         strip = 1;
270         patchline[len-1]=0;
271       }
272     }
273     if (!*patchline) {
274       free(patchline);
275       patchline = xstrdup(" ");
276     }
277
278     // Are we assembling a hunk?
279     if (state >= 2) {
280       if (*patchline==' ' || *patchline=='+' || *patchline=='-') {
281         dlist_add(&TT.current_hunk, patchline);
282
283         if (*patchline != '+') TT.oldlen--;
284         if (*patchline != '-') TT.newlen--;
285
286         // Context line?
287         if (*patchline==' ' && state==2) TT.context++;
288         else state=3;
289
290         // If we've consumed all expected hunk lines, apply the hunk.
291
292         if (!TT.oldlen && !TT.newlen) state = apply_one_hunk();
293         continue;
294       }
295       fail_hunk();
296       state = 0;
297       continue;
298     }
299
300     // Open a new file?
301     if (!strncmp("--- ", patchline, 4) || !strncmp("+++ ", patchline, 4)) {
302       char *s, **name = &oldname;
303       int i;
304
305       if (*patchline == '+') {
306         name = &newname;
307         state = 1;
308       }
309
310       free(*name);
311       finish_oldfile();
312
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++;
316       i = atoi(s);
317       if (i>1900 && i<=1970) *name = xstrdup("/dev/null");
318       else {
319         *s = 0;
320         *name = xstrdup(patchline+4);
321       }
322
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
326       // and _guess_.
327
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)) {
331       int i;
332       char *s = patchline+4;
333
334       // Read oldline[,oldlen] +newline[,newlen]
335
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);
341
342       TT.context = 0;
343       state = 2;
344
345       // If this is the first hunk, open the file.
346       if (TT.filein == -1) {
347         int oldsum, newsum, del = 0;
348         char *name;
349
350         oldsum = TT.oldline + TT.oldlen;
351         newsum = TT.newline + TT.newlen;
352
353         name = reverse ? oldname : newname;
354
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))
358         {
359           name = reverse ? newname : oldname;
360           del++;
361         }
362
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++;
368           name = s;
369           i++;
370         }
371
372         if (del) {
373           printf("removing %s\n", name);
374           xunlink(name);
375           state = 0;
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))
380           {
381             printf("creating %s\n", name);
382             s = strrchr(name, '/');
383             if (s) {
384               *s = 0;
385               xmkpath(name, -1);
386               *s = '/';
387             }
388             TT.filein = xcreate(name, O_CREAT|O_EXCL|O_RDWR, 0666);
389           } else {
390             printf("patching %s\n", name);
391             TT.filein = xopen(name, O_RDONLY);
392           }
393           TT.fileout = copy_tempfile(TT.filein, name, &TT.tempname);
394           TT.linenum = 0;
395           TT.hunknum = 0;
396         }
397       }
398
399       TT.hunknum++;
400
401       continue;
402     }
403
404     // If we didn't continue above, discard this line.
405     free(patchline);
406   }
407
408   finish_oldfile();
409
410   if (CFG_TOYBOX_FREE) {
411     close(TT.filepatch);
412     free(oldname);
413     free(newname);
414   }
415 }