Merge branch 'jc/binary'
[git] / builtin-apply.c
1 /*
2  * apply.c
3  *
4  * Copyright (C) Linus Torvalds, 2005
5  *
6  * This applies patches on top of some (arbitrary) version of the SCM.
7  *
8  */
9 #include <fnmatch.h>
10 #include "cache.h"
11 #include "cache-tree.h"
12 #include "quote.h"
13 #include "blob.h"
14 #include "delta.h"
15 #include "builtin.h"
16
17 /*
18  *  --check turns on checking that the working tree matches the
19  *    files that are being modified, but doesn't apply the patch
20  *  --stat does just a diffstat, and doesn't actually apply
21  *  --numstat does numeric diffstat, and doesn't actually apply
22  *  --index-info shows the old and new index info for paths if available.
23  *  --index updates the cache as well.
24  *  --cached updates only the cache without ever touching the working tree.
25  */
26 static const char *prefix;
27 static int prefix_length = -1;
28 static int newfd = -1;
29
30 static int p_value = 1;
31 static int check_index;
32 static int write_index;
33 static int cached;
34 static int diffstat;
35 static int numstat;
36 static int summary;
37 static int check;
38 static int apply = 1;
39 static int apply_in_reverse;
40 static int apply_with_reject;
41 static int apply_verbosely;
42 static int no_add;
43 static int show_index_info;
44 static int line_termination = '\n';
45 static unsigned long p_context = -1;
46 static const char apply_usage[] =
47 "git-apply [--stat] [--numstat] [--summary] [--check] [--index] [--cached] [--apply] [--no-add] [--index-info] [--allow-binary-replacement] [--reverse] [--reject] [--verbose] [-z] [-pNUM] [-CNUM] [--whitespace=<nowarn|warn|error|error-all|strip>] <patch>...";
48
49 static enum whitespace_eol {
50         nowarn_whitespace,
51         warn_on_whitespace,
52         error_on_whitespace,
53         strip_whitespace,
54 } new_whitespace = warn_on_whitespace;
55 static int whitespace_error;
56 static int squelch_whitespace_errors = 5;
57 static int applied_after_stripping;
58 static const char *patch_input_file;
59
60 static void parse_whitespace_option(const char *option)
61 {
62         if (!option) {
63                 new_whitespace = warn_on_whitespace;
64                 return;
65         }
66         if (!strcmp(option, "warn")) {
67                 new_whitespace = warn_on_whitespace;
68                 return;
69         }
70         if (!strcmp(option, "nowarn")) {
71                 new_whitespace = nowarn_whitespace;
72                 return;
73         }
74         if (!strcmp(option, "error")) {
75                 new_whitespace = error_on_whitespace;
76                 return;
77         }
78         if (!strcmp(option, "error-all")) {
79                 new_whitespace = error_on_whitespace;
80                 squelch_whitespace_errors = 0;
81                 return;
82         }
83         if (!strcmp(option, "strip")) {
84                 new_whitespace = strip_whitespace;
85                 return;
86         }
87         die("unrecognized whitespace option '%s'", option);
88 }
89
90 static void set_default_whitespace_mode(const char *whitespace_option)
91 {
92         if (!whitespace_option && !apply_default_whitespace) {
93                 new_whitespace = (apply
94                                   ? warn_on_whitespace
95                                   : nowarn_whitespace);
96         }
97 }
98
99 /*
100  * For "diff-stat" like behaviour, we keep track of the biggest change
101  * we've seen, and the longest filename. That allows us to do simple
102  * scaling.
103  */
104 static int max_change, max_len;
105
106 /*
107  * Various "current state", notably line numbers and what
108  * file (and how) we're patching right now.. The "is_xxxx"
109  * things are flags, where -1 means "don't know yet".
110  */
111 static int linenr = 1;
112
113 /*
114  * This represents one "hunk" from a patch, starting with
115  * "@@ -oldpos,oldlines +newpos,newlines @@" marker.  The
116  * patch text is pointed at by patch, and its byte length
117  * is stored in size.  leading and trailing are the number
118  * of context lines.
119  */
120 struct fragment {
121         unsigned long leading, trailing;
122         unsigned long oldpos, oldlines;
123         unsigned long newpos, newlines;
124         const char *patch;
125         int size;
126         int rejected;
127         struct fragment *next;
128 };
129
130 /*
131  * When dealing with a binary patch, we reuse "leading" field
132  * to store the type of the binary hunk, either deflated "delta"
133  * or deflated "literal".
134  */
135 #define binary_patch_method leading
136 #define BINARY_DELTA_DEFLATED   1
137 #define BINARY_LITERAL_DEFLATED 2
138
139 struct patch {
140         char *new_name, *old_name, *def_name;
141         unsigned int old_mode, new_mode;
142         int is_rename, is_copy, is_new, is_delete, is_binary;
143         int rejected;
144         unsigned long deflate_origlen;
145         int lines_added, lines_deleted;
146         int score;
147         int inaccurate_eof:1;
148         struct fragment *fragments;
149         char *result;
150         unsigned long resultsize;
151         char old_sha1_prefix[41];
152         char new_sha1_prefix[41];
153         struct patch *next;
154 };
155
156 static void say_patch_name(FILE *output, const char *pre, struct patch *patch, const char *post)
157 {
158         fputs(pre, output);
159         if (patch->old_name && patch->new_name &&
160             strcmp(patch->old_name, patch->new_name)) {
161                 write_name_quoted(NULL, 0, patch->old_name, 1, output);
162                 fputs(" => ", output);
163                 write_name_quoted(NULL, 0, patch->new_name, 1, output);
164         }
165         else {
166                 const char *n = patch->new_name;
167                 if (!n)
168                         n = patch->old_name;
169                 write_name_quoted(NULL, 0, n, 1, output);
170         }
171         fputs(post, output);
172 }
173
174 #define CHUNKSIZE (8192)
175 #define SLOP (16)
176
177 static void *read_patch_file(int fd, unsigned long *sizep)
178 {
179         unsigned long size = 0, alloc = CHUNKSIZE;
180         void *buffer = xmalloc(alloc);
181
182         for (;;) {
183                 int nr = alloc - size;
184                 if (nr < 1024) {
185                         alloc += CHUNKSIZE;
186                         buffer = xrealloc(buffer, alloc);
187                         nr = alloc - size;
188                 }
189                 nr = xread(fd, (char *) buffer + size, nr);
190                 if (!nr)
191                         break;
192                 if (nr < 0)
193                         die("git-apply: read returned %s", strerror(errno));
194                 size += nr;
195         }
196         *sizep = size;
197
198         /*
199          * Make sure that we have some slop in the buffer
200          * so that we can do speculative "memcmp" etc, and
201          * see to it that it is NUL-filled.
202          */
203         if (alloc < size + SLOP)
204                 buffer = xrealloc(buffer, size + SLOP);
205         memset((char *) buffer + size, 0, SLOP);
206         return buffer;
207 }
208
209 static unsigned long linelen(const char *buffer, unsigned long size)
210 {
211         unsigned long len = 0;
212         while (size--) {
213                 len++;
214                 if (*buffer++ == '\n')
215                         break;
216         }
217         return len;
218 }
219
220 static int is_dev_null(const char *str)
221 {
222         return !memcmp("/dev/null", str, 9) && isspace(str[9]);
223 }
224
225 #define TERM_SPACE      1
226 #define TERM_TAB        2
227
228 static int name_terminate(const char *name, int namelen, int c, int terminate)
229 {
230         if (c == ' ' && !(terminate & TERM_SPACE))
231                 return 0;
232         if (c == '\t' && !(terminate & TERM_TAB))
233                 return 0;
234
235         return 1;
236 }
237
238 static char * find_name(const char *line, char *def, int p_value, int terminate)
239 {
240         int len;
241         const char *start = line;
242         char *name;
243
244         if (*line == '"') {
245                 /* Proposed "new-style" GNU patch/diff format; see
246                  * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
247                  */
248                 name = unquote_c_style(line, NULL);
249                 if (name) {
250                         char *cp = name;
251                         while (p_value) {
252                                 cp = strchr(name, '/');
253                                 if (!cp)
254                                         break;
255                                 cp++;
256                                 p_value--;
257                         }
258                         if (cp) {
259                                 /* name can later be freed, so we need
260                                  * to memmove, not just return cp
261                                  */
262                                 memmove(name, cp, strlen(cp) + 1);
263                                 free(def);
264                                 return name;
265                         }
266                         else {
267                                 free(name);
268                                 name = NULL;
269                         }
270                 }
271         }
272
273         for (;;) {
274                 char c = *line;
275
276                 if (isspace(c)) {
277                         if (c == '\n')
278                                 break;
279                         if (name_terminate(start, line-start, c, terminate))
280                                 break;
281                 }
282                 line++;
283                 if (c == '/' && !--p_value)
284                         start = line;
285         }
286         if (!start)
287                 return def;
288         len = line - start;
289         if (!len)
290                 return def;
291
292         /*
293          * Generally we prefer the shorter name, especially
294          * if the other one is just a variation of that with
295          * something else tacked on to the end (ie "file.orig"
296          * or "file~").
297          */
298         if (def) {
299                 int deflen = strlen(def);
300                 if (deflen < len && !strncmp(start, def, deflen))
301                         return def;
302         }
303
304         name = xmalloc(len + 1);
305         memcpy(name, start, len);
306         name[len] = 0;
307         free(def);
308         return name;
309 }
310
311 /*
312  * Get the name etc info from the --/+++ lines of a traditional patch header
313  *
314  * NOTE! This hardcodes "-p1" behaviour in filename detection.
315  *
316  * FIXME! The end-of-filename heuristics are kind of screwy. For existing
317  * files, we can happily check the index for a match, but for creating a
318  * new file we should try to match whatever "patch" does. I have no idea.
319  */
320 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
321 {
322         char *name;
323
324         first += 4;     /* skip "--- " */
325         second += 4;    /* skip "+++ " */
326         if (is_dev_null(first)) {
327                 patch->is_new = 1;
328                 patch->is_delete = 0;
329                 name = find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB);
330                 patch->new_name = name;
331         } else if (is_dev_null(second)) {
332                 patch->is_new = 0;
333                 patch->is_delete = 1;
334                 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
335                 patch->old_name = name;
336         } else {
337                 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
338                 name = find_name(second, name, p_value, TERM_SPACE | TERM_TAB);
339                 patch->old_name = patch->new_name = name;
340         }
341         if (!name)
342                 die("unable to find filename in patch at line %d", linenr);
343 }
344
345 static int gitdiff_hdrend(const char *line, struct patch *patch)
346 {
347         return -1;
348 }
349
350 /*
351  * We're anal about diff header consistency, to make
352  * sure that we don't end up having strange ambiguous
353  * patches floating around.
354  *
355  * As a result, gitdiff_{old|new}name() will check
356  * their names against any previous information, just
357  * to make sure..
358  */
359 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
360 {
361         if (!orig_name && !isnull)
362                 return find_name(line, NULL, 1, 0);
363
364         if (orig_name) {
365                 int len;
366                 const char *name;
367                 char *another;
368                 name = orig_name;
369                 len = strlen(name);
370                 if (isnull)
371                         die("git-apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
372                 another = find_name(line, NULL, 1, 0);
373                 if (!another || memcmp(another, name, len))
374                         die("git-apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
375                 free(another);
376                 return orig_name;
377         }
378         else {
379                 /* expect "/dev/null" */
380                 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
381                         die("git-apply: bad git-diff - expected /dev/null on line %d", linenr);
382                 return NULL;
383         }
384 }
385
386 static int gitdiff_oldname(const char *line, struct patch *patch)
387 {
388         patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
389         return 0;
390 }
391
392 static int gitdiff_newname(const char *line, struct patch *patch)
393 {
394         patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
395         return 0;
396 }
397
398 static int gitdiff_oldmode(const char *line, struct patch *patch)
399 {
400         patch->old_mode = strtoul(line, NULL, 8);
401         return 0;
402 }
403
404 static int gitdiff_newmode(const char *line, struct patch *patch)
405 {
406         patch->new_mode = strtoul(line, NULL, 8);
407         return 0;
408 }
409
410 static int gitdiff_delete(const char *line, struct patch *patch)
411 {
412         patch->is_delete = 1;
413         patch->old_name = patch->def_name;
414         return gitdiff_oldmode(line, patch);
415 }
416
417 static int gitdiff_newfile(const char *line, struct patch *patch)
418 {
419         patch->is_new = 1;
420         patch->new_name = patch->def_name;
421         return gitdiff_newmode(line, patch);
422 }
423
424 static int gitdiff_copysrc(const char *line, struct patch *patch)
425 {
426         patch->is_copy = 1;
427         patch->old_name = find_name(line, NULL, 0, 0);
428         return 0;
429 }
430
431 static int gitdiff_copydst(const char *line, struct patch *patch)
432 {
433         patch->is_copy = 1;
434         patch->new_name = find_name(line, NULL, 0, 0);
435         return 0;
436 }
437
438 static int gitdiff_renamesrc(const char *line, struct patch *patch)
439 {
440         patch->is_rename = 1;
441         patch->old_name = find_name(line, NULL, 0, 0);
442         return 0;
443 }
444
445 static int gitdiff_renamedst(const char *line, struct patch *patch)
446 {
447         patch->is_rename = 1;
448         patch->new_name = find_name(line, NULL, 0, 0);
449         return 0;
450 }
451
452 static int gitdiff_similarity(const char *line, struct patch *patch)
453 {
454         if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
455                 patch->score = 0;
456         return 0;
457 }
458
459 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
460 {
461         if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
462                 patch->score = 0;
463         return 0;
464 }
465
466 static int gitdiff_index(const char *line, struct patch *patch)
467 {
468         /* index line is N hexadecimal, "..", N hexadecimal,
469          * and optional space with octal mode.
470          */
471         const char *ptr, *eol;
472         int len;
473
474         ptr = strchr(line, '.');
475         if (!ptr || ptr[1] != '.' || 40 < ptr - line)
476                 return 0;
477         len = ptr - line;
478         memcpy(patch->old_sha1_prefix, line, len);
479         patch->old_sha1_prefix[len] = 0;
480
481         line = ptr + 2;
482         ptr = strchr(line, ' ');
483         eol = strchr(line, '\n');
484
485         if (!ptr || eol < ptr)
486                 ptr = eol;
487         len = ptr - line;
488
489         if (40 < len)
490                 return 0;
491         memcpy(patch->new_sha1_prefix, line, len);
492         patch->new_sha1_prefix[len] = 0;
493         if (*ptr == ' ')
494                 patch->new_mode = patch->old_mode = strtoul(ptr+1, NULL, 8);
495         return 0;
496 }
497
498 /*
499  * This is normal for a diff that doesn't change anything: we'll fall through
500  * into the next diff. Tell the parser to break out.
501  */
502 static int gitdiff_unrecognized(const char *line, struct patch *patch)
503 {
504         return -1;
505 }
506
507 static const char *stop_at_slash(const char *line, int llen)
508 {
509         int i;
510
511         for (i = 0; i < llen; i++) {
512                 int ch = line[i];
513                 if (ch == '/')
514                         return line + i;
515         }
516         return NULL;
517 }
518
519 /* This is to extract the same name that appears on "diff --git"
520  * line.  We do not find and return anything if it is a rename
521  * patch, and it is OK because we will find the name elsewhere.
522  * We need to reliably find name only when it is mode-change only,
523  * creation or deletion of an empty file.  In any of these cases,
524  * both sides are the same name under a/ and b/ respectively.
525  */
526 static char *git_header_name(char *line, int llen)
527 {
528         int len;
529         const char *name;
530         const char *second = NULL;
531
532         line += strlen("diff --git ");
533         llen -= strlen("diff --git ");
534
535         if (*line == '"') {
536                 const char *cp;
537                 char *first = unquote_c_style(line, &second);
538                 if (!first)
539                         return NULL;
540
541                 /* advance to the first slash */
542                 cp = stop_at_slash(first, strlen(first));
543                 if (!cp || cp == first) {
544                         /* we do not accept absolute paths */
545                 free_first_and_fail:
546                         free(first);
547                         return NULL;
548                 }
549                 len = strlen(cp+1);
550                 memmove(first, cp+1, len+1); /* including NUL */
551
552                 /* second points at one past closing dq of name.
553                  * find the second name.
554                  */
555                 while ((second < line + llen) && isspace(*second))
556                         second++;
557
558                 if (line + llen <= second)
559                         goto free_first_and_fail;
560                 if (*second == '"') {
561                         char *sp = unquote_c_style(second, NULL);
562                         if (!sp)
563                                 goto free_first_and_fail;
564                         cp = stop_at_slash(sp, strlen(sp));
565                         if (!cp || cp == sp) {
566                         free_both_and_fail:
567                                 free(sp);
568                                 goto free_first_and_fail;
569                         }
570                         /* They must match, otherwise ignore */
571                         if (strcmp(cp+1, first))
572                                 goto free_both_and_fail;
573                         free(sp);
574                         return first;
575                 }
576
577                 /* unquoted second */
578                 cp = stop_at_slash(second, line + llen - second);
579                 if (!cp || cp == second)
580                         goto free_first_and_fail;
581                 cp++;
582                 if (line + llen - cp != len + 1 ||
583                     memcmp(first, cp, len))
584                         goto free_first_and_fail;
585                 return first;
586         }
587
588         /* unquoted first name */
589         name = stop_at_slash(line, llen);
590         if (!name || name == line)
591                 return NULL;
592
593         name++;
594
595         /* since the first name is unquoted, a dq if exists must be
596          * the beginning of the second name.
597          */
598         for (second = name; second < line + llen; second++) {
599                 if (*second == '"') {
600                         const char *cp = second;
601                         const char *np;
602                         char *sp = unquote_c_style(second, NULL);
603
604                         if (!sp)
605                                 return NULL;
606                         np = stop_at_slash(sp, strlen(sp));
607                         if (!np || np == sp) {
608                         free_second_and_fail:
609                                 free(sp);
610                                 return NULL;
611                         }
612                         np++;
613                         len = strlen(np);
614                         if (len < cp - name &&
615                             !strncmp(np, name, len) &&
616                             isspace(name[len])) {
617                                 /* Good */
618                                 memmove(sp, np, len + 1);
619                                 return sp;
620                         }
621                         goto free_second_and_fail;
622                 }
623         }
624
625         /*
626          * Accept a name only if it shows up twice, exactly the same
627          * form.
628          */
629         for (len = 0 ; ; len++) {
630                 switch (name[len]) {
631                 default:
632                         continue;
633                 case '\n':
634                         return NULL;
635                 case '\t': case ' ':
636                         second = name+len;
637                         for (;;) {
638                                 char c = *second++;
639                                 if (c == '\n')
640                                         return NULL;
641                                 if (c == '/')
642                                         break;
643                         }
644                         if (second[len] == '\n' && !memcmp(name, second, len)) {
645                                 char *ret = xmalloc(len + 1);
646                                 memcpy(ret, name, len);
647                                 ret[len] = 0;
648                                 return ret;
649                         }
650                 }
651         }
652         return NULL;
653 }
654
655 /* Verify that we recognize the lines following a git header */
656 static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
657 {
658         unsigned long offset;
659
660         /* A git diff has explicit new/delete information, so we don't guess */
661         patch->is_new = 0;
662         patch->is_delete = 0;
663
664         /*
665          * Some things may not have the old name in the
666          * rest of the headers anywhere (pure mode changes,
667          * or removing or adding empty files), so we get
668          * the default name from the header.
669          */
670         patch->def_name = git_header_name(line, len);
671
672         line += len;
673         size -= len;
674         linenr++;
675         for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
676                 static const struct opentry {
677                         const char *str;
678                         int (*fn)(const char *, struct patch *);
679                 } optable[] = {
680                         { "@@ -", gitdiff_hdrend },
681                         { "--- ", gitdiff_oldname },
682                         { "+++ ", gitdiff_newname },
683                         { "old mode ", gitdiff_oldmode },
684                         { "new mode ", gitdiff_newmode },
685                         { "deleted file mode ", gitdiff_delete },
686                         { "new file mode ", gitdiff_newfile },
687                         { "copy from ", gitdiff_copysrc },
688                         { "copy to ", gitdiff_copydst },
689                         { "rename old ", gitdiff_renamesrc },
690                         { "rename new ", gitdiff_renamedst },
691                         { "rename from ", gitdiff_renamesrc },
692                         { "rename to ", gitdiff_renamedst },
693                         { "similarity index ", gitdiff_similarity },
694                         { "dissimilarity index ", gitdiff_dissimilarity },
695                         { "index ", gitdiff_index },
696                         { "", gitdiff_unrecognized },
697                 };
698                 int i;
699
700                 len = linelen(line, size);
701                 if (!len || line[len-1] != '\n')
702                         break;
703                 for (i = 0; i < ARRAY_SIZE(optable); i++) {
704                         const struct opentry *p = optable + i;
705                         int oplen = strlen(p->str);
706                         if (len < oplen || memcmp(p->str, line, oplen))
707                                 continue;
708                         if (p->fn(line + oplen, patch) < 0)
709                                 return offset;
710                         break;
711                 }
712         }
713
714         return offset;
715 }
716
717 static int parse_num(const char *line, unsigned long *p)
718 {
719         char *ptr;
720
721         if (!isdigit(*line))
722                 return 0;
723         *p = strtoul(line, &ptr, 10);
724         return ptr - line;
725 }
726
727 static int parse_range(const char *line, int len, int offset, const char *expect,
728                         unsigned long *p1, unsigned long *p2)
729 {
730         int digits, ex;
731
732         if (offset < 0 || offset >= len)
733                 return -1;
734         line += offset;
735         len -= offset;
736
737         digits = parse_num(line, p1);
738         if (!digits)
739                 return -1;
740
741         offset += digits;
742         line += digits;
743         len -= digits;
744
745         *p2 = 1;
746         if (*line == ',') {
747                 digits = parse_num(line+1, p2);
748                 if (!digits)
749                         return -1;
750
751                 offset += digits+1;
752                 line += digits+1;
753                 len -= digits+1;
754         }
755
756         ex = strlen(expect);
757         if (ex > len)
758                 return -1;
759         if (memcmp(line, expect, ex))
760                 return -1;
761
762         return offset + ex;
763 }
764
765 /*
766  * Parse a unified diff fragment header of the
767  * form "@@ -a,b +c,d @@"
768  */
769 static int parse_fragment_header(char *line, int len, struct fragment *fragment)
770 {
771         int offset;
772
773         if (!len || line[len-1] != '\n')
774                 return -1;
775
776         /* Figure out the number of lines in a fragment */
777         offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
778         offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
779
780         return offset;
781 }
782
783 static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
784 {
785         unsigned long offset, len;
786
787         patch->is_rename = patch->is_copy = 0;
788         patch->is_new = patch->is_delete = -1;
789         patch->old_mode = patch->new_mode = 0;
790         patch->old_name = patch->new_name = NULL;
791         for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
792                 unsigned long nextlen;
793
794                 len = linelen(line, size);
795                 if (!len)
796                         break;
797
798                 /* Testing this early allows us to take a few shortcuts.. */
799                 if (len < 6)
800                         continue;
801
802                 /*
803                  * Make sure we don't find any unconnected patch fragments.
804                  * That's a sign that we didn't find a header, and that a
805                  * patch has become corrupted/broken up.
806                  */
807                 if (!memcmp("@@ -", line, 4)) {
808                         struct fragment dummy;
809                         if (parse_fragment_header(line, len, &dummy) < 0)
810                                 continue;
811                         error("patch fragment without header at line %d: %.*s", linenr, (int)len-1, line);
812                 }
813
814                 if (size < len + 6)
815                         break;
816
817                 /*
818                  * Git patch? It might not have a real patch, just a rename
819                  * or mode change, so we handle that specially
820                  */
821                 if (!memcmp("diff --git ", line, 11)) {
822                         int git_hdr_len = parse_git_header(line, len, size, patch);
823                         if (git_hdr_len <= len)
824                                 continue;
825                         if (!patch->old_name && !patch->new_name) {
826                                 if (!patch->def_name)
827                                         die("git diff header lacks filename information (line %d)", linenr);
828                                 patch->old_name = patch->new_name = patch->def_name;
829                         }
830                         *hdrsize = git_hdr_len;
831                         return offset;
832                 }
833
834                 /** --- followed by +++ ? */
835                 if (memcmp("--- ", line,  4) || memcmp("+++ ", line + len, 4))
836                         continue;
837
838                 /*
839                  * We only accept unified patches, so we want it to
840                  * at least have "@@ -a,b +c,d @@\n", which is 14 chars
841                  * minimum
842                  */
843                 nextlen = linelen(line + len, size - len);
844                 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
845                         continue;
846
847                 /* Ok, we'll consider it a patch */
848                 parse_traditional_patch(line, line+len, patch);
849                 *hdrsize = len + nextlen;
850                 linenr += 2;
851                 return offset;
852         }
853         return -1;
854 }
855
856 /*
857  * Parse a unified diff. Note that this really needs
858  * to parse each fragment separately, since the only
859  * way to know the difference between a "---" that is
860  * part of a patch, and a "---" that starts the next
861  * patch is to look at the line counts..
862  */
863 static int parse_fragment(char *line, unsigned long size, struct patch *patch, struct fragment *fragment)
864 {
865         int added, deleted;
866         int len = linelen(line, size), offset;
867         unsigned long oldlines, newlines;
868         unsigned long leading, trailing;
869
870         offset = parse_fragment_header(line, len, fragment);
871         if (offset < 0)
872                 return -1;
873         oldlines = fragment->oldlines;
874         newlines = fragment->newlines;
875         leading = 0;
876         trailing = 0;
877
878         if (patch->is_new < 0) {
879                 patch->is_new =  !oldlines;
880                 if (!oldlines)
881                         patch->old_name = NULL;
882         }
883         if (patch->is_delete < 0) {
884                 patch->is_delete = !newlines;
885                 if (!newlines)
886                         patch->new_name = NULL;
887         }
888
889         if (patch->is_new && oldlines)
890                 return error("new file depends on old contents");
891         if (patch->is_delete != !newlines) {
892                 if (newlines)
893                         return error("deleted file still has contents");
894                 fprintf(stderr, "** warning: file %s becomes empty but is not deleted\n", patch->new_name);
895         }
896
897         /* Parse the thing.. */
898         line += len;
899         size -= len;
900         linenr++;
901         added = deleted = 0;
902         for (offset = len; size > 0; offset += len, size -= len, line += len, linenr++) {
903                 if (!oldlines && !newlines)
904                         break;
905                 len = linelen(line, size);
906                 if (!len || line[len-1] != '\n')
907                         return -1;
908                 switch (*line) {
909                 default:
910                         return -1;
911                 case ' ':
912                         oldlines--;
913                         newlines--;
914                         if (!deleted && !added)
915                                 leading++;
916                         trailing++;
917                         break;
918                 case '-':
919                         deleted++;
920                         oldlines--;
921                         trailing = 0;
922                         break;
923                 case '+':
924                         /*
925                          * We know len is at least two, since we have a '+' and
926                          * we checked that the last character was a '\n' above.
927                          * That is, an addition of an empty line would check
928                          * the '+' here.  Sneaky...
929                          */
930                         if ((new_whitespace != nowarn_whitespace) &&
931                             isspace(line[len-2])) {
932                                 whitespace_error++;
933                                 if (squelch_whitespace_errors &&
934                                     squelch_whitespace_errors <
935                                     whitespace_error)
936                                         ;
937                                 else {
938                                         fprintf(stderr, "Adds trailing whitespace.\n%s:%d:%.*s\n",
939                                                 patch_input_file,
940                                                 linenr, len-2, line+1);
941                                 }
942                         }
943                         added++;
944                         newlines--;
945                         trailing = 0;
946                         break;
947
948                 /* We allow "\ No newline at end of file". Depending
949                  * on locale settings when the patch was produced we
950                  * don't know what this line looks like. The only
951                  * thing we do know is that it begins with "\ ".
952                  * Checking for 12 is just for sanity check -- any
953                  * l10n of "\ No newline..." is at least that long.
954                  */
955                 case '\\':
956                         if (len < 12 || memcmp(line, "\\ ", 2))
957                                 return -1;
958                         break;
959                 }
960         }
961         if (oldlines || newlines)
962                 return -1;
963         fragment->leading = leading;
964         fragment->trailing = trailing;
965
966         /* If a fragment ends with an incomplete line, we failed to include
967          * it in the above loop because we hit oldlines == newlines == 0
968          * before seeing it.
969          */
970         if (12 < size && !memcmp(line, "\\ ", 2))
971                 offset += linelen(line, size);
972
973         patch->lines_added += added;
974         patch->lines_deleted += deleted;
975         return offset;
976 }
977
978 static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
979 {
980         unsigned long offset = 0;
981         struct fragment **fragp = &patch->fragments;
982
983         while (size > 4 && !memcmp(line, "@@ -", 4)) {
984                 struct fragment *fragment;
985                 int len;
986
987                 fragment = xcalloc(1, sizeof(*fragment));
988                 len = parse_fragment(line, size, patch, fragment);
989                 if (len <= 0)
990                         die("corrupt patch at line %d", linenr);
991
992                 fragment->patch = line;
993                 fragment->size = len;
994
995                 *fragp = fragment;
996                 fragp = &fragment->next;
997
998                 offset += len;
999                 line += len;
1000                 size -= len;
1001         }
1002         return offset;
1003 }
1004
1005 static inline int metadata_changes(struct patch *patch)
1006 {
1007         return  patch->is_rename > 0 ||
1008                 patch->is_copy > 0 ||
1009                 patch->is_new > 0 ||
1010                 patch->is_delete ||
1011                 (patch->old_mode && patch->new_mode &&
1012                  patch->old_mode != patch->new_mode);
1013 }
1014
1015 static char *inflate_it(const void *data, unsigned long size,
1016                         unsigned long inflated_size)
1017 {
1018         z_stream stream;
1019         void *out;
1020         int st;
1021
1022         memset(&stream, 0, sizeof(stream));
1023
1024         stream.next_in = (unsigned char *)data;
1025         stream.avail_in = size;
1026         stream.next_out = out = xmalloc(inflated_size);
1027         stream.avail_out = inflated_size;
1028         inflateInit(&stream);
1029         st = inflate(&stream, Z_FINISH);
1030         if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1031                 free(out);
1032                 return NULL;
1033         }
1034         return out;
1035 }
1036
1037 static struct fragment *parse_binary_hunk(char **buf_p,
1038                                           unsigned long *sz_p,
1039                                           int *status_p,
1040                                           int *used_p)
1041 {
1042         /* Expect a line that begins with binary patch method ("literal"
1043          * or "delta"), followed by the length of data before deflating.
1044          * a sequence of 'length-byte' followed by base-85 encoded data
1045          * should follow, terminated by a newline.
1046          *
1047          * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1048          * and we would limit the patch line to 66 characters,
1049          * so one line can fit up to 13 groups that would decode
1050          * to 52 bytes max.  The length byte 'A'-'Z' corresponds
1051          * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1052          */
1053         int llen, used;
1054         unsigned long size = *sz_p;
1055         char *buffer = *buf_p;
1056         int patch_method;
1057         unsigned long origlen;
1058         char *data = NULL;
1059         int hunk_size = 0;
1060         struct fragment *frag;
1061
1062         llen = linelen(buffer, size);
1063         used = llen;
1064
1065         *status_p = 0;
1066
1067         if (!strncmp(buffer, "delta ", 6)) {
1068                 patch_method = BINARY_DELTA_DEFLATED;
1069                 origlen = strtoul(buffer + 6, NULL, 10);
1070         }
1071         else if (!strncmp(buffer, "literal ", 8)) {
1072                 patch_method = BINARY_LITERAL_DEFLATED;
1073                 origlen = strtoul(buffer + 8, NULL, 10);
1074         }
1075         else
1076                 return NULL;
1077
1078         linenr++;
1079         buffer += llen;
1080         while (1) {
1081                 int byte_length, max_byte_length, newsize;
1082                 llen = linelen(buffer, size);
1083                 used += llen;
1084                 linenr++;
1085                 if (llen == 1) {
1086                         /* consume the blank line */
1087                         buffer++;
1088                         size--;
1089                         break;
1090                 }
1091                 /* Minimum line is "A00000\n" which is 7-byte long,
1092                  * and the line length must be multiple of 5 plus 2.
1093                  */
1094                 if ((llen < 7) || (llen-2) % 5)
1095                         goto corrupt;
1096                 max_byte_length = (llen - 2) / 5 * 4;
1097                 byte_length = *buffer;
1098                 if ('A' <= byte_length && byte_length <= 'Z')
1099                         byte_length = byte_length - 'A' + 1;
1100                 else if ('a' <= byte_length && byte_length <= 'z')
1101                         byte_length = byte_length - 'a' + 27;
1102                 else
1103                         goto corrupt;
1104                 /* if the input length was not multiple of 4, we would
1105                  * have filler at the end but the filler should never
1106                  * exceed 3 bytes
1107                  */
1108                 if (max_byte_length < byte_length ||
1109                     byte_length <= max_byte_length - 4)
1110                         goto corrupt;
1111                 newsize = hunk_size + byte_length;
1112                 data = xrealloc(data, newsize);
1113                 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1114                         goto corrupt;
1115                 hunk_size = newsize;
1116                 buffer += llen;
1117                 size -= llen;
1118         }
1119
1120         frag = xcalloc(1, sizeof(*frag));
1121         frag->patch = inflate_it(data, hunk_size, origlen);
1122         if (!frag->patch)
1123                 goto corrupt;
1124         free(data);
1125         frag->size = origlen;
1126         *buf_p = buffer;
1127         *sz_p = size;
1128         *used_p = used;
1129         frag->binary_patch_method = patch_method;
1130         return frag;
1131
1132  corrupt:
1133         free(data);
1134         *status_p = -1;
1135         error("corrupt binary patch at line %d: %.*s",
1136               linenr-1, llen-1, buffer);
1137         return NULL;
1138 }
1139
1140 static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1141 {
1142         /* We have read "GIT binary patch\n"; what follows is a line
1143          * that says the patch method (currently, either "literal" or
1144          * "delta") and the length of data before deflating; a
1145          * sequence of 'length-byte' followed by base-85 encoded data
1146          * follows.
1147          *
1148          * When a binary patch is reversible, there is another binary
1149          * hunk in the same format, starting with patch method (either
1150          * "literal" or "delta") with the length of data, and a sequence
1151          * of length-byte + base-85 encoded data, terminated with another
1152          * empty line.  This data, when applied to the postimage, produces
1153          * the preimage.
1154          */
1155         struct fragment *forward;
1156         struct fragment *reverse;
1157         int status;
1158         int used, used_1;
1159
1160         forward = parse_binary_hunk(&buffer, &size, &status, &used);
1161         if (!forward && !status)
1162                 /* there has to be one hunk (forward hunk) */
1163                 return error("unrecognized binary patch at line %d", linenr-1);
1164         if (status)
1165                 /* otherwise we already gave an error message */
1166                 return status;
1167
1168         reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1169         if (reverse)
1170                 used += used_1;
1171         else if (status) {
1172                 /* not having reverse hunk is not an error, but having
1173                  * a corrupt reverse hunk is.
1174                  */
1175                 free((void*) forward->patch);
1176                 free(forward);
1177                 return status;
1178         }
1179         forward->next = reverse;
1180         patch->fragments = forward;
1181         patch->is_binary = 1;
1182         return used;
1183 }
1184
1185 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
1186 {
1187         int hdrsize, patchsize;
1188         int offset = find_header(buffer, size, &hdrsize, patch);
1189
1190         if (offset < 0)
1191                 return offset;
1192
1193         patchsize = parse_single_patch(buffer + offset + hdrsize, size - offset - hdrsize, patch);
1194
1195         if (!patchsize) {
1196                 static const char *binhdr[] = {
1197                         "Binary files ",
1198                         "Files ",
1199                         NULL,
1200                 };
1201                 static const char git_binary[] = "GIT binary patch\n";
1202                 int i;
1203                 int hd = hdrsize + offset;
1204                 unsigned long llen = linelen(buffer + hd, size - hd);
1205
1206                 if (llen == sizeof(git_binary) - 1 &&
1207                     !memcmp(git_binary, buffer + hd, llen)) {
1208                         int used;
1209                         linenr++;
1210                         used = parse_binary(buffer + hd + llen,
1211                                             size - hd - llen, patch);
1212                         if (used)
1213                                 patchsize = used + llen;
1214                         else
1215                                 patchsize = 0;
1216                 }
1217                 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
1218                         for (i = 0; binhdr[i]; i++) {
1219                                 int len = strlen(binhdr[i]);
1220                                 if (len < size - hd &&
1221                                     !memcmp(binhdr[i], buffer + hd, len)) {
1222                                         linenr++;
1223                                         patch->is_binary = 1;
1224                                         patchsize = llen;
1225                                         break;
1226                                 }
1227                         }
1228                 }
1229
1230                 /* Empty patch cannot be applied if it is a text patch
1231                  * without metadata change.  A binary patch appears
1232                  * empty to us here.
1233                  */
1234                 if ((apply || check) &&
1235                     (!patch->is_binary && !metadata_changes(patch)))
1236                         die("patch with only garbage at line %d", linenr);
1237         }
1238
1239         return offset + hdrsize + patchsize;
1240 }
1241
1242 #define swap(a,b) myswap((a),(b),sizeof(a))
1243
1244 #define myswap(a, b, size) do {         \
1245         unsigned char mytmp[size];      \
1246         memcpy(mytmp, &a, size);                \
1247         memcpy(&a, &b, size);           \
1248         memcpy(&b, mytmp, size);                \
1249 } while (0)
1250
1251 static void reverse_patches(struct patch *p)
1252 {
1253         for (; p; p = p->next) {
1254                 struct fragment *frag = p->fragments;
1255
1256                 swap(p->new_name, p->old_name);
1257                 swap(p->new_mode, p->old_mode);
1258                 swap(p->is_new, p->is_delete);
1259                 swap(p->lines_added, p->lines_deleted);
1260                 swap(p->old_sha1_prefix, p->new_sha1_prefix);
1261
1262                 for (; frag; frag = frag->next) {
1263                         swap(frag->newpos, frag->oldpos);
1264                         swap(frag->newlines, frag->oldlines);
1265                 }
1266         }
1267 }
1268
1269 static const char pluses[] = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1270 static const char minuses[]= "----------------------------------------------------------------------";
1271
1272 static void show_stats(struct patch *patch)
1273 {
1274         const char *prefix = "";
1275         char *name = patch->new_name;
1276         char *qname = NULL;
1277         int len, max, add, del, total;
1278
1279         if (!name)
1280                 name = patch->old_name;
1281
1282         if (0 < (len = quote_c_style(name, NULL, NULL, 0))) {
1283                 qname = xmalloc(len + 1);
1284                 quote_c_style(name, qname, NULL, 0);
1285                 name = qname;
1286         }
1287
1288         /*
1289          * "scale" the filename
1290          */
1291         len = strlen(name);
1292         max = max_len;
1293         if (max > 50)
1294                 max = 50;
1295         if (len > max) {
1296                 char *slash;
1297                 prefix = "...";
1298                 max -= 3;
1299                 name += len - max;
1300                 slash = strchr(name, '/');
1301                 if (slash)
1302                         name = slash;
1303         }
1304         len = max;
1305
1306         /*
1307          * scale the add/delete
1308          */
1309         max = max_change;
1310         if (max + len > 70)
1311                 max = 70 - len;
1312
1313         add = patch->lines_added;
1314         del = patch->lines_deleted;
1315         total = add + del;
1316
1317         if (max_change > 0) {
1318                 total = (total * max + max_change / 2) / max_change;
1319                 add = (add * max + max_change / 2) / max_change;
1320                 del = total - add;
1321         }
1322         if (patch->is_binary)
1323                 printf(" %s%-*s |  Bin\n", prefix, len, name);
1324         else
1325                 printf(" %s%-*s |%5d %.*s%.*s\n", prefix,
1326                        len, name, patch->lines_added + patch->lines_deleted,
1327                        add, pluses, del, minuses);
1328         free(qname);
1329 }
1330
1331 static int read_old_data(struct stat *st, const char *path, void *buf, unsigned long size)
1332 {
1333         int fd;
1334         unsigned long got;
1335
1336         switch (st->st_mode & S_IFMT) {
1337         case S_IFLNK:
1338                 return readlink(path, buf, size);
1339         case S_IFREG:
1340                 fd = open(path, O_RDONLY);
1341                 if (fd < 0)
1342                         return error("unable to open %s", path);
1343                 got = 0;
1344                 for (;;) {
1345                         int ret = xread(fd, (char *) buf + got, size - got);
1346                         if (ret <= 0)
1347                                 break;
1348                         got += ret;
1349                 }
1350                 close(fd);
1351                 return got;
1352
1353         default:
1354                 return -1;
1355         }
1356 }
1357
1358 static int find_offset(const char *buf, unsigned long size, const char *fragment, unsigned long fragsize, int line, int *lines)
1359 {
1360         int i;
1361         unsigned long start, backwards, forwards;
1362
1363         if (fragsize > size)
1364                 return -1;
1365
1366         start = 0;
1367         if (line > 1) {
1368                 unsigned long offset = 0;
1369                 i = line-1;
1370                 while (offset + fragsize <= size) {
1371                         if (buf[offset++] == '\n') {
1372                                 start = offset;
1373                                 if (!--i)
1374                                         break;
1375                         }
1376                 }
1377         }
1378
1379         /* Exact line number? */
1380         if (!memcmp(buf + start, fragment, fragsize))
1381                 return start;
1382
1383         /*
1384          * There's probably some smart way to do this, but I'll leave
1385          * that to the smart and beautiful people. I'm simple and stupid.
1386          */
1387         backwards = start;
1388         forwards = start;
1389         for (i = 0; ; i++) {
1390                 unsigned long try;
1391                 int n;
1392
1393                 /* "backward" */
1394                 if (i & 1) {
1395                         if (!backwards) {
1396                                 if (forwards + fragsize > size)
1397                                         break;
1398                                 continue;
1399                         }
1400                         do {
1401                                 --backwards;
1402                         } while (backwards && buf[backwards-1] != '\n');
1403                         try = backwards;
1404                 } else {
1405                         while (forwards + fragsize <= size) {
1406                                 if (buf[forwards++] == '\n')
1407                                         break;
1408                         }
1409                         try = forwards;
1410                 }
1411
1412                 if (try + fragsize > size)
1413                         continue;
1414                 if (memcmp(buf + try, fragment, fragsize))
1415                         continue;
1416                 n = (i >> 1)+1;
1417                 if (i & 1)
1418                         n = -n;
1419                 *lines = n;
1420                 return try;
1421         }
1422
1423         /*
1424          * We should start searching forward and backward.
1425          */
1426         return -1;
1427 }
1428
1429 static void remove_first_line(const char **rbuf, int *rsize)
1430 {
1431         const char *buf = *rbuf;
1432         int size = *rsize;
1433         unsigned long offset;
1434         offset = 0;
1435         while (offset <= size) {
1436                 if (buf[offset++] == '\n')
1437                         break;
1438         }
1439         *rsize = size - offset;
1440         *rbuf = buf + offset;
1441 }
1442
1443 static void remove_last_line(const char **rbuf, int *rsize)
1444 {
1445         const char *buf = *rbuf;
1446         int size = *rsize;
1447         unsigned long offset;
1448         offset = size - 1;
1449         while (offset > 0) {
1450                 if (buf[--offset] == '\n')
1451                         break;
1452         }
1453         *rsize = offset + 1;
1454 }
1455
1456 struct buffer_desc {
1457         char *buffer;
1458         unsigned long size;
1459         unsigned long alloc;
1460 };
1461
1462 static int apply_line(char *output, const char *patch, int plen)
1463 {
1464         /* plen is number of bytes to be copied from patch,
1465          * starting at patch+1 (patch[0] is '+').  Typically
1466          * patch[plen] is '\n'.
1467          */
1468         int add_nl_to_tail = 0;
1469         if ((new_whitespace == strip_whitespace) &&
1470             1 < plen && isspace(patch[plen-1])) {
1471                 if (patch[plen] == '\n')
1472                         add_nl_to_tail = 1;
1473                 plen--;
1474                 while (0 < plen && isspace(patch[plen]))
1475                         plen--;
1476                 applied_after_stripping++;
1477         }
1478         memcpy(output, patch + 1, plen);
1479         if (add_nl_to_tail)
1480                 output[plen++] = '\n';
1481         return plen;
1482 }
1483
1484 static int apply_one_fragment(struct buffer_desc *desc, struct fragment *frag, int inaccurate_eof)
1485 {
1486         int match_beginning, match_end;
1487         char *buf = desc->buffer;
1488         const char *patch = frag->patch;
1489         int offset, size = frag->size;
1490         char *old = xmalloc(size);
1491         char *new = xmalloc(size);
1492         const char *oldlines, *newlines;
1493         int oldsize = 0, newsize = 0;
1494         unsigned long leading, trailing;
1495         int pos, lines;
1496
1497         while (size > 0) {
1498                 char first;
1499                 int len = linelen(patch, size);
1500                 int plen;
1501
1502                 if (!len)
1503                         break;
1504
1505                 /*
1506                  * "plen" is how much of the line we should use for
1507                  * the actual patch data. Normally we just remove the
1508                  * first character on the line, but if the line is
1509                  * followed by "\ No newline", then we also remove the
1510                  * last one (which is the newline, of course).
1511                  */
1512                 plen = len-1;
1513                 if (len < size && patch[len] == '\\')
1514                         plen--;
1515                 first = *patch;
1516                 if (apply_in_reverse) {
1517                         if (first == '-')
1518                                 first = '+';
1519                         else if (first == '+')
1520                                 first = '-';
1521                 }
1522                 switch (first) {
1523                 case ' ':
1524                 case '-':
1525                         memcpy(old + oldsize, patch + 1, plen);
1526                         oldsize += plen;
1527                         if (first == '-')
1528                                 break;
1529                 /* Fall-through for ' ' */
1530                 case '+':
1531                         if (first != '+' || !no_add)
1532                                 newsize += apply_line(new + newsize, patch,
1533                                                       plen);
1534                         break;
1535                 case '@': case '\\':
1536                         /* Ignore it, we already handled it */
1537                         break;
1538                 default:
1539                         return -1;
1540                 }
1541                 patch += len;
1542                 size -= len;
1543         }
1544
1545         if (inaccurate_eof && oldsize > 0 && old[oldsize - 1] == '\n' &&
1546                         newsize > 0 && new[newsize - 1] == '\n') {
1547                 oldsize--;
1548                 newsize--;
1549         }
1550
1551         oldlines = old;
1552         newlines = new;
1553         leading = frag->leading;
1554         trailing = frag->trailing;
1555
1556         /*
1557          * If we don't have any leading/trailing data in the patch,
1558          * we want it to match at the beginning/end of the file.
1559          */
1560         match_beginning = !leading && (frag->oldpos == 1);
1561         match_end = !trailing;
1562
1563         lines = 0;
1564         pos = frag->newpos;
1565         for (;;) {
1566                 offset = find_offset(buf, desc->size,
1567                                      oldlines, oldsize, pos, &lines);
1568                 if (match_end && offset + oldsize != desc->size)
1569                         offset = -1;
1570                 if (match_beginning && offset)
1571                         offset = -1;
1572                 if (offset >= 0) {
1573                         int diff = newsize - oldsize;
1574                         unsigned long size = desc->size + diff;
1575                         unsigned long alloc = desc->alloc;
1576
1577                         /* Warn if it was necessary to reduce the number
1578                          * of context lines.
1579                          */
1580                         if ((leading != frag->leading) ||
1581                             (trailing != frag->trailing))
1582                                 fprintf(stderr, "Context reduced to (%ld/%ld)"
1583                                         " to apply fragment at %d\n",
1584                                         leading, trailing, pos + lines);
1585
1586                         if (size > alloc) {
1587                                 alloc = size + 8192;
1588                                 desc->alloc = alloc;
1589                                 buf = xrealloc(buf, alloc);
1590                                 desc->buffer = buf;
1591                         }
1592                         desc->size = size;
1593                         memmove(buf + offset + newsize,
1594                                 buf + offset + oldsize,
1595                                 size - offset - newsize);
1596                         memcpy(buf + offset, newlines, newsize);
1597                         offset = 0;
1598
1599                         break;
1600                 }
1601
1602                 /* Am I at my context limits? */
1603                 if ((leading <= p_context) && (trailing <= p_context))
1604                         break;
1605                 if (match_beginning || match_end) {
1606                         match_beginning = match_end = 0;
1607                         continue;
1608                 }
1609                 /* Reduce the number of context lines
1610                  * Reduce both leading and trailing if they are equal
1611                  * otherwise just reduce the larger context.
1612                  */
1613                 if (leading >= trailing) {
1614                         remove_first_line(&oldlines, &oldsize);
1615                         remove_first_line(&newlines, &newsize);
1616                         pos--;
1617                         leading--;
1618                 }
1619                 if (trailing > leading) {
1620                         remove_last_line(&oldlines, &oldsize);
1621                         remove_last_line(&newlines, &newsize);
1622                         trailing--;
1623                 }
1624         }
1625
1626         free(old);
1627         free(new);
1628         return offset;
1629 }
1630
1631 static int apply_binary_fragment(struct buffer_desc *desc, struct patch *patch)
1632 {
1633         unsigned long dst_size;
1634         struct fragment *fragment = patch->fragments;
1635         void *data;
1636         void *result;
1637
1638         /* Binary patch is irreversible without the optional second hunk */
1639         if (apply_in_reverse) {
1640                 if (!fragment->next)
1641                         return error("cannot reverse-apply a binary patch "
1642                                      "without the reverse hunk to '%s'",
1643                                      patch->new_name
1644                                      ? patch->new_name : patch->old_name);
1645                 fragment = fragment->next;
1646         }
1647         data = (void*) fragment->patch;
1648         switch (fragment->binary_patch_method) {
1649         case BINARY_DELTA_DEFLATED:
1650                 result = patch_delta(desc->buffer, desc->size,
1651                                      data,
1652                                      fragment->size,
1653                                      &dst_size);
1654                 free(desc->buffer);
1655                 desc->buffer = result;
1656                 break;
1657         case BINARY_LITERAL_DEFLATED:
1658                 free(desc->buffer);
1659                 desc->buffer = data;
1660                 dst_size = fragment->size;
1661                 break;
1662         }
1663         if (!desc->buffer)
1664                 return -1;
1665         desc->size = desc->alloc = dst_size;
1666         return 0;
1667 }
1668
1669 static int apply_binary(struct buffer_desc *desc, struct patch *patch)
1670 {
1671         const char *name = patch->old_name ? patch->old_name : patch->new_name;
1672         unsigned char sha1[20];
1673         unsigned char hdr[50];
1674         int hdrlen;
1675
1676         /* For safety, we require patch index line to contain
1677          * full 40-byte textual SHA1 for old and new, at least for now.
1678          */
1679         if (strlen(patch->old_sha1_prefix) != 40 ||
1680             strlen(patch->new_sha1_prefix) != 40 ||
1681             get_sha1_hex(patch->old_sha1_prefix, sha1) ||
1682             get_sha1_hex(patch->new_sha1_prefix, sha1))
1683                 return error("cannot apply binary patch to '%s' "
1684                              "without full index line", name);
1685
1686         if (patch->old_name) {
1687                 /* See if the old one matches what the patch
1688                  * applies to.
1689                  */
1690                 write_sha1_file_prepare(desc->buffer, desc->size,
1691                                         blob_type, sha1, hdr, &hdrlen);
1692                 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
1693                         return error("the patch applies to '%s' (%s), "
1694                                      "which does not match the "
1695                                      "current contents.",
1696                                      name, sha1_to_hex(sha1));
1697         }
1698         else {
1699                 /* Otherwise, the old one must be empty. */
1700                 if (desc->size)
1701                         return error("the patch applies to an empty "
1702                                      "'%s' but it is not empty", name);
1703         }
1704
1705         get_sha1_hex(patch->new_sha1_prefix, sha1);
1706         if (is_null_sha1(sha1)) {
1707                 free(desc->buffer);
1708                 desc->alloc = desc->size = 0;
1709                 desc->buffer = NULL;
1710                 return 0; /* deletion patch */
1711         }
1712
1713         if (has_sha1_file(sha1)) {
1714                 /* We already have the postimage */
1715                 char type[10];
1716                 unsigned long size;
1717
1718                 free(desc->buffer);
1719                 desc->buffer = read_sha1_file(sha1, type, &size);
1720                 if (!desc->buffer)
1721                         return error("the necessary postimage %s for "
1722                                      "'%s' cannot be read",
1723                                      patch->new_sha1_prefix, name);
1724                 desc->alloc = desc->size = size;
1725         }
1726         else {
1727                 /* We have verified desc matches the preimage;
1728                  * apply the patch data to it, which is stored
1729                  * in the patch->fragments->{patch,size}.
1730                  */
1731                 if (apply_binary_fragment(desc, patch))
1732                         return error("binary patch does not apply to '%s'",
1733                                      name);
1734
1735                 /* verify that the result matches */
1736                 write_sha1_file_prepare(desc->buffer, desc->size, blob_type,
1737                                         sha1, hdr, &hdrlen);
1738                 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
1739                         return error("binary patch to '%s' creates incorrect result (expecting %s, got %s)", name, patch->new_sha1_prefix, sha1_to_hex(sha1));
1740         }
1741
1742         return 0;
1743 }
1744
1745 static int apply_fragments(struct buffer_desc *desc, struct patch *patch)
1746 {
1747         struct fragment *frag = patch->fragments;
1748         const char *name = patch->old_name ? patch->old_name : patch->new_name;
1749
1750         if (patch->is_binary)
1751                 return apply_binary(desc, patch);
1752
1753         while (frag) {
1754                 if (apply_one_fragment(desc, frag, patch->inaccurate_eof)) {
1755                         error("patch failed: %s:%ld", name, frag->oldpos);
1756                         if (!apply_with_reject)
1757                                 return -1;
1758                         frag->rejected = 1;
1759                 }
1760                 frag = frag->next;
1761         }
1762         return 0;
1763 }
1764
1765 static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce)
1766 {
1767         char *buf;
1768         unsigned long size, alloc;
1769         struct buffer_desc desc;
1770
1771         size = 0;
1772         alloc = 0;
1773         buf = NULL;
1774         if (cached) {
1775                 if (ce) {
1776                         char type[20];
1777                         buf = read_sha1_file(ce->sha1, type, &size);
1778                         if (!buf)
1779                                 return error("read of %s failed",
1780                                              patch->old_name);
1781                         alloc = size;
1782                 }
1783         }
1784         else if (patch->old_name) {
1785                 size = st->st_size;
1786                 alloc = size + 8192;
1787                 buf = xmalloc(alloc);
1788                 if (read_old_data(st, patch->old_name, buf, alloc) != size)
1789                         return error("read of %s failed", patch->old_name);
1790         }
1791
1792         desc.size = size;
1793         desc.alloc = alloc;
1794         desc.buffer = buf;
1795
1796         if (apply_fragments(&desc, patch) < 0)
1797                 return -1; /* note with --reject this succeeds. */
1798
1799         /* NUL terminate the result */
1800         if (desc.alloc <= desc.size)
1801                 desc.buffer = xrealloc(desc.buffer, desc.size + 1);
1802         desc.buffer[desc.size] = 0;
1803
1804         patch->result = desc.buffer;
1805         patch->resultsize = desc.size;
1806
1807         if (patch->is_delete && patch->resultsize)
1808                 return error("removal patch leaves file contents");
1809
1810         return 0;
1811 }
1812
1813 static int check_patch(struct patch *patch, struct patch *prev_patch)
1814 {
1815         struct stat st;
1816         const char *old_name = patch->old_name;
1817         const char *new_name = patch->new_name;
1818         const char *name = old_name ? old_name : new_name;
1819         struct cache_entry *ce = NULL;
1820         int ok_if_exists;
1821
1822         patch->rejected = 1; /* we will drop this after we succeed */
1823         if (old_name) {
1824                 int changed = 0;
1825                 int stat_ret = 0;
1826                 unsigned st_mode = 0;
1827
1828                 if (!cached)
1829                         stat_ret = lstat(old_name, &st);
1830                 if (check_index) {
1831                         int pos = cache_name_pos(old_name, strlen(old_name));
1832                         if (pos < 0)
1833                                 return error("%s: does not exist in index",
1834                                              old_name);
1835                         ce = active_cache[pos];
1836                         if (stat_ret < 0) {
1837                                 struct checkout costate;
1838                                 if (errno != ENOENT)
1839                                         return error("%s: %s", old_name,
1840                                                      strerror(errno));
1841                                 /* checkout */
1842                                 costate.base_dir = "";
1843                                 costate.base_dir_len = 0;
1844                                 costate.force = 0;
1845                                 costate.quiet = 0;
1846                                 costate.not_new = 0;
1847                                 costate.refresh_cache = 1;
1848                                 if (checkout_entry(ce,
1849                                                    &costate,
1850                                                    NULL) ||
1851                                     lstat(old_name, &st))
1852                                         return -1;
1853                         }
1854                         if (!cached)
1855                                 changed = ce_match_stat(ce, &st, 1);
1856                         if (changed)
1857                                 return error("%s: does not match index",
1858                                              old_name);
1859                         if (cached)
1860                                 st_mode = ntohl(ce->ce_mode);
1861                 }
1862                 else if (stat_ret < 0)
1863                         return error("%s: %s", old_name, strerror(errno));
1864
1865                 if (!cached)
1866                         st_mode = ntohl(create_ce_mode(st.st_mode));
1867
1868                 if (patch->is_new < 0)
1869                         patch->is_new = 0;
1870                 if (!patch->old_mode)
1871                         patch->old_mode = st_mode;
1872                 if ((st_mode ^ patch->old_mode) & S_IFMT)
1873                         return error("%s: wrong type", old_name);
1874                 if (st_mode != patch->old_mode)
1875                         fprintf(stderr, "warning: %s has type %o, expected %o\n",
1876                                 old_name, st_mode, patch->old_mode);
1877         }
1878
1879         if (new_name && prev_patch && prev_patch->is_delete &&
1880             !strcmp(prev_patch->old_name, new_name))
1881                 /* A type-change diff is always split into a patch to
1882                  * delete old, immediately followed by a patch to
1883                  * create new (see diff.c::run_diff()); in such a case
1884                  * it is Ok that the entry to be deleted by the
1885                  * previous patch is still in the working tree and in
1886                  * the index.
1887                  */
1888                 ok_if_exists = 1;
1889         else
1890                 ok_if_exists = 0;
1891
1892         if (new_name && (patch->is_new | patch->is_rename | patch->is_copy)) {
1893                 if (check_index &&
1894                     cache_name_pos(new_name, strlen(new_name)) >= 0 &&
1895                     !ok_if_exists)
1896                         return error("%s: already exists in index", new_name);
1897                 if (!cached) {
1898                         struct stat nst;
1899                         if (!lstat(new_name, &nst)) {
1900                                 if (S_ISDIR(nst.st_mode) || ok_if_exists)
1901                                         ; /* ok */
1902                                 else
1903                                         return error("%s: already exists in working directory", new_name);
1904                         }
1905                         else if ((errno != ENOENT) && (errno != ENOTDIR))
1906                                 return error("%s: %s", new_name, strerror(errno));
1907                 }
1908                 if (!patch->new_mode) {
1909                         if (patch->is_new)
1910                                 patch->new_mode = S_IFREG | 0644;
1911                         else
1912                                 patch->new_mode = patch->old_mode;
1913                 }
1914         }
1915
1916         if (new_name && old_name) {
1917                 int same = !strcmp(old_name, new_name);
1918                 if (!patch->new_mode)
1919                         patch->new_mode = patch->old_mode;
1920                 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
1921                         return error("new mode (%o) of %s does not match old mode (%o)%s%s",
1922                                 patch->new_mode, new_name, patch->old_mode,
1923                                 same ? "" : " of ", same ? "" : old_name);
1924         }
1925
1926         if (apply_data(patch, &st, ce) < 0)
1927                 return error("%s: patch does not apply", name);
1928         patch->rejected = 0;
1929         return 0;
1930 }
1931
1932 static int check_patch_list(struct patch *patch)
1933 {
1934         struct patch *prev_patch = NULL;
1935         int err = 0;
1936
1937         for (prev_patch = NULL; patch ; patch = patch->next) {
1938                 if (apply_verbosely)
1939                         say_patch_name(stderr,
1940                                        "Checking patch ", patch, "...\n");
1941                 err |= check_patch(patch, prev_patch);
1942                 prev_patch = patch;
1943         }
1944         return err;
1945 }
1946
1947 static void show_index_list(struct patch *list)
1948 {
1949         struct patch *patch;
1950
1951         /* Once we start supporting the reverse patch, it may be
1952          * worth showing the new sha1 prefix, but until then...
1953          */
1954         for (patch = list; patch; patch = patch->next) {
1955                 const unsigned char *sha1_ptr;
1956                 unsigned char sha1[20];
1957                 const char *name;
1958
1959                 name = patch->old_name ? patch->old_name : patch->new_name;
1960                 if (patch->is_new)
1961                         sha1_ptr = null_sha1;
1962                 else if (get_sha1(patch->old_sha1_prefix, sha1))
1963                         die("sha1 information is lacking or useless (%s).",
1964                             name);
1965                 else
1966                         sha1_ptr = sha1;
1967
1968                 printf("%06o %s ",patch->old_mode, sha1_to_hex(sha1_ptr));
1969                 if (line_termination && quote_c_style(name, NULL, NULL, 0))
1970                         quote_c_style(name, NULL, stdout, 0);
1971                 else
1972                         fputs(name, stdout);
1973                 putchar(line_termination);
1974         }
1975 }
1976
1977 static void stat_patch_list(struct patch *patch)
1978 {
1979         int files, adds, dels;
1980
1981         for (files = adds = dels = 0 ; patch ; patch = patch->next) {
1982                 files++;
1983                 adds += patch->lines_added;
1984                 dels += patch->lines_deleted;
1985                 show_stats(patch);
1986         }
1987
1988         printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
1989 }
1990
1991 static void numstat_patch_list(struct patch *patch)
1992 {
1993         for ( ; patch; patch = patch->next) {
1994                 const char *name;
1995                 name = patch->new_name ? patch->new_name : patch->old_name;
1996                 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
1997                 if (line_termination && quote_c_style(name, NULL, NULL, 0))
1998                         quote_c_style(name, NULL, stdout, 0);
1999                 else
2000                         fputs(name, stdout);
2001                 putchar('\n');
2002         }
2003 }
2004
2005 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
2006 {
2007         if (mode)
2008                 printf(" %s mode %06o %s\n", newdelete, mode, name);
2009         else
2010                 printf(" %s %s\n", newdelete, name);
2011 }
2012
2013 static void show_mode_change(struct patch *p, int show_name)
2014 {
2015         if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
2016                 if (show_name)
2017                         printf(" mode change %06o => %06o %s\n",
2018                                p->old_mode, p->new_mode, p->new_name);
2019                 else
2020                         printf(" mode change %06o => %06o\n",
2021                                p->old_mode, p->new_mode);
2022         }
2023 }
2024
2025 static void show_rename_copy(struct patch *p)
2026 {
2027         const char *renamecopy = p->is_rename ? "rename" : "copy";
2028         const char *old, *new;
2029
2030         /* Find common prefix */
2031         old = p->old_name;
2032         new = p->new_name;
2033         while (1) {
2034                 const char *slash_old, *slash_new;
2035                 slash_old = strchr(old, '/');
2036                 slash_new = strchr(new, '/');
2037                 if (!slash_old ||
2038                     !slash_new ||
2039                     slash_old - old != slash_new - new ||
2040                     memcmp(old, new, slash_new - new))
2041                         break;
2042                 old = slash_old + 1;
2043                 new = slash_new + 1;
2044         }
2045         /* p->old_name thru old is the common prefix, and old and new
2046          * through the end of names are renames
2047          */
2048         if (old != p->old_name)
2049                 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
2050                        (int)(old - p->old_name), p->old_name,
2051                        old, new, p->score);
2052         else
2053                 printf(" %s %s => %s (%d%%)\n", renamecopy,
2054                        p->old_name, p->new_name, p->score);
2055         show_mode_change(p, 0);
2056 }
2057
2058 static void summary_patch_list(struct patch *patch)
2059 {
2060         struct patch *p;
2061
2062         for (p = patch; p; p = p->next) {
2063                 if (p->is_new)
2064                         show_file_mode_name("create", p->new_mode, p->new_name);
2065                 else if (p->is_delete)
2066                         show_file_mode_name("delete", p->old_mode, p->old_name);
2067                 else {
2068                         if (p->is_rename || p->is_copy)
2069                                 show_rename_copy(p);
2070                         else {
2071                                 if (p->score) {
2072                                         printf(" rewrite %s (%d%%)\n",
2073                                                p->new_name, p->score);
2074                                         show_mode_change(p, 0);
2075                                 }
2076                                 else
2077                                         show_mode_change(p, 1);
2078                         }
2079                 }
2080         }
2081 }
2082
2083 static void patch_stats(struct patch *patch)
2084 {
2085         int lines = patch->lines_added + patch->lines_deleted;
2086
2087         if (lines > max_change)
2088                 max_change = lines;
2089         if (patch->old_name) {
2090                 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
2091                 if (!len)
2092                         len = strlen(patch->old_name);
2093                 if (len > max_len)
2094                         max_len = len;
2095         }
2096         if (patch->new_name) {
2097                 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
2098                 if (!len)
2099                         len = strlen(patch->new_name);
2100                 if (len > max_len)
2101                         max_len = len;
2102         }
2103 }
2104
2105 static void remove_file(struct patch *patch)
2106 {
2107         if (write_index) {
2108                 if (remove_file_from_cache(patch->old_name) < 0)
2109                         die("unable to remove %s from index", patch->old_name);
2110                 cache_tree_invalidate_path(active_cache_tree, patch->old_name);
2111         }
2112         if (!cached)
2113                 unlink(patch->old_name);
2114 }
2115
2116 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
2117 {
2118         struct stat st;
2119         struct cache_entry *ce;
2120         int namelen = strlen(path);
2121         unsigned ce_size = cache_entry_size(namelen);
2122
2123         if (!write_index)
2124                 return;
2125
2126         ce = xcalloc(1, ce_size);
2127         memcpy(ce->name, path, namelen);
2128         ce->ce_mode = create_ce_mode(mode);
2129         ce->ce_flags = htons(namelen);
2130         if (!cached) {
2131                 if (lstat(path, &st) < 0)
2132                         die("unable to stat newly created file %s", path);
2133                 fill_stat_cache_info(ce, &st);
2134         }
2135         if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
2136                 die("unable to create backing store for newly created file %s", path);
2137         if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
2138                 die("unable to add cache entry for %s", path);
2139 }
2140
2141 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
2142 {
2143         int fd;
2144
2145         if (S_ISLNK(mode))
2146                 /* Although buf:size is counted string, it also is NUL
2147                  * terminated.
2148                  */
2149                 return symlink(buf, path);
2150         fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
2151         if (fd < 0)
2152                 return -1;
2153         while (size) {
2154                 int written = xwrite(fd, buf, size);
2155                 if (written < 0)
2156                         die("writing file %s: %s", path, strerror(errno));
2157                 if (!written)
2158                         die("out of space writing file %s", path);
2159                 buf += written;
2160                 size -= written;
2161         }
2162         if (close(fd) < 0)
2163                 die("closing file %s: %s", path, strerror(errno));
2164         return 0;
2165 }
2166
2167 /*
2168  * We optimistically assume that the directories exist,
2169  * which is true 99% of the time anyway. If they don't,
2170  * we create them and try again.
2171  */
2172 static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
2173 {
2174         if (cached)
2175                 return;
2176         if (!try_create_file(path, mode, buf, size))
2177                 return;
2178
2179         if (errno == ENOENT) {
2180                 if (safe_create_leading_directories(path))
2181                         return;
2182                 if (!try_create_file(path, mode, buf, size))
2183                         return;
2184         }
2185
2186         if (errno == EEXIST || errno == EACCES) {
2187                 /* We may be trying to create a file where a directory
2188                  * used to be.
2189                  */
2190                 struct stat st;
2191                 errno = 0;
2192                 if (!lstat(path, &st) && S_ISDIR(st.st_mode) && !rmdir(path))
2193                         errno = EEXIST;
2194         }
2195
2196         if (errno == EEXIST) {
2197                 unsigned int nr = getpid();
2198
2199                 for (;;) {
2200                         const char *newpath;
2201                         newpath = mkpath("%s~%u", path, nr);
2202                         if (!try_create_file(newpath, mode, buf, size)) {
2203                                 if (!rename(newpath, path))
2204                                         return;
2205                                 unlink(newpath);
2206                                 break;
2207                         }
2208                         if (errno != EEXIST)
2209                                 break;
2210                         ++nr;
2211                 }
2212         }
2213         die("unable to write file %s mode %o", path, mode);
2214 }
2215
2216 static void create_file(struct patch *patch)
2217 {
2218         char *path = patch->new_name;
2219         unsigned mode = patch->new_mode;
2220         unsigned long size = patch->resultsize;
2221         char *buf = patch->result;
2222
2223         if (!mode)
2224                 mode = S_IFREG | 0644;
2225         create_one_file(path, mode, buf, size);
2226         add_index_file(path, mode, buf, size);
2227         cache_tree_invalidate_path(active_cache_tree, path);
2228 }
2229
2230 /* phase zero is to remove, phase one is to create */
2231 static void write_out_one_result(struct patch *patch, int phase)
2232 {
2233         if (patch->is_delete > 0) {
2234                 if (phase == 0)
2235                         remove_file(patch);
2236                 return;
2237         }
2238         if (patch->is_new > 0 || patch->is_copy) {
2239                 if (phase == 1)
2240                         create_file(patch);
2241                 return;
2242         }
2243         /*
2244          * Rename or modification boils down to the same
2245          * thing: remove the old, write the new
2246          */
2247         if (phase == 0)
2248                 remove_file(patch);
2249         if (phase == 1)
2250                 create_file(patch);
2251 }
2252
2253 static int write_out_one_reject(struct patch *patch)
2254 {
2255         FILE *rej;
2256         char namebuf[PATH_MAX];
2257         struct fragment *frag;
2258         int cnt = 0;
2259
2260         for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
2261                 if (!frag->rejected)
2262                         continue;
2263                 cnt++;
2264         }
2265
2266         if (!cnt) {
2267                 if (apply_verbosely)
2268                         say_patch_name(stderr,
2269                                        "Applied patch ", patch, " cleanly.\n");
2270                 return 0;
2271         }
2272
2273         /* This should not happen, because a removal patch that leaves
2274          * contents are marked "rejected" at the patch level.
2275          */
2276         if (!patch->new_name)
2277                 die("internal error");
2278
2279         /* Say this even without --verbose */
2280         say_patch_name(stderr, "Applying patch ", patch, " with");
2281         fprintf(stderr, " %d rejects...\n", cnt);
2282
2283         cnt = strlen(patch->new_name);
2284         if (ARRAY_SIZE(namebuf) <= cnt + 5) {
2285                 cnt = ARRAY_SIZE(namebuf) - 5;
2286                 fprintf(stderr,
2287                         "warning: truncating .rej filename to %.*s.rej",
2288                         cnt - 1, patch->new_name);
2289         }
2290         memcpy(namebuf, patch->new_name, cnt);
2291         memcpy(namebuf + cnt, ".rej", 5);
2292
2293         rej = fopen(namebuf, "w");
2294         if (!rej)
2295                 return error("cannot open %s: %s", namebuf, strerror(errno));
2296
2297         /* Normal git tools never deal with .rej, so do not pretend
2298          * this is a git patch by saying --git nor give extended
2299          * headers.  While at it, maybe please "kompare" that wants
2300          * the trailing TAB and some garbage at the end of line ;-).
2301          */
2302         fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
2303                 patch->new_name, patch->new_name);
2304         for (cnt = 1, frag = patch->fragments;
2305              frag;
2306              cnt++, frag = frag->next) {
2307                 if (!frag->rejected) {
2308                         fprintf(stderr, "Hunk #%d applied cleanly.\n", cnt);
2309                         continue;
2310                 }
2311                 fprintf(stderr, "Rejected hunk #%d.\n", cnt);
2312                 fprintf(rej, "%.*s", frag->size, frag->patch);
2313                 if (frag->patch[frag->size-1] != '\n')
2314                         fputc('\n', rej);
2315         }
2316         fclose(rej);
2317         return -1;
2318 }
2319
2320 static int write_out_results(struct patch *list, int skipped_patch)
2321 {
2322         int phase;
2323         int errs = 0;
2324         struct patch *l;
2325
2326         if (!list && !skipped_patch)
2327                 return error("No changes");
2328
2329         for (phase = 0; phase < 2; phase++) {
2330                 l = list;
2331                 while (l) {
2332                         if (l->rejected)
2333                                 errs = 1;
2334                         else {
2335                                 write_out_one_result(l, phase);
2336                                 if (phase == 1 && write_out_one_reject(l))
2337                                         errs = 1;
2338                         }
2339                         l = l->next;
2340                 }
2341         }
2342         return errs;
2343 }
2344
2345 static struct lock_file lock_file;
2346
2347 static struct excludes {
2348         struct excludes *next;
2349         const char *path;
2350 } *excludes;
2351
2352 static int use_patch(struct patch *p)
2353 {
2354         const char *pathname = p->new_name ? p->new_name : p->old_name;
2355         struct excludes *x = excludes;
2356         while (x) {
2357                 if (fnmatch(x->path, pathname, 0) == 0)
2358                         return 0;
2359                 x = x->next;
2360         }
2361         if (0 < prefix_length) {
2362                 int pathlen = strlen(pathname);
2363                 if (pathlen <= prefix_length ||
2364                     memcmp(prefix, pathname, prefix_length))
2365                         return 0;
2366         }
2367         return 1;
2368 }
2369
2370 static int apply_patch(int fd, const char *filename, int inaccurate_eof)
2371 {
2372         unsigned long offset, size;
2373         char *buffer = read_patch_file(fd, &size);
2374         struct patch *list = NULL, **listp = &list;
2375         int skipped_patch = 0;
2376
2377         patch_input_file = filename;
2378         if (!buffer)
2379                 return -1;
2380         offset = 0;
2381         while (size > 0) {
2382                 struct patch *patch;
2383                 int nr;
2384
2385                 patch = xcalloc(1, sizeof(*patch));
2386                 patch->inaccurate_eof = inaccurate_eof;
2387                 nr = parse_chunk(buffer + offset, size, patch);
2388                 if (nr < 0)
2389                         break;
2390                 if (apply_in_reverse)
2391                         reverse_patches(patch);
2392                 if (use_patch(patch)) {
2393                         patch_stats(patch);
2394                         *listp = patch;
2395                         listp = &patch->next;
2396                 } else {
2397                         /* perhaps free it a bit better? */
2398                         free(patch);
2399                         skipped_patch++;
2400                 }
2401                 offset += nr;
2402                 size -= nr;
2403         }
2404
2405         if (whitespace_error && (new_whitespace == error_on_whitespace))
2406                 apply = 0;
2407
2408         write_index = check_index && apply;
2409         if (write_index && newfd < 0)
2410                 newfd = hold_lock_file_for_update(&lock_file,
2411                                                   get_index_file(), 1);
2412         if (check_index) {
2413                 if (read_cache() < 0)
2414                         die("unable to read index file");
2415         }
2416
2417         if ((check || apply) &&
2418             check_patch_list(list) < 0 &&
2419             !apply_with_reject)
2420                 exit(1);
2421
2422         if (apply && write_out_results(list, skipped_patch))
2423                 exit(1);
2424
2425         if (show_index_info)
2426                 show_index_list(list);
2427
2428         if (diffstat)
2429                 stat_patch_list(list);
2430
2431         if (numstat)
2432                 numstat_patch_list(list);
2433
2434         if (summary)
2435                 summary_patch_list(list);
2436
2437         free(buffer);
2438         return 0;
2439 }
2440
2441 static int git_apply_config(const char *var, const char *value)
2442 {
2443         if (!strcmp(var, "apply.whitespace")) {
2444                 apply_default_whitespace = xstrdup(value);
2445                 return 0;
2446         }
2447         return git_default_config(var, value);
2448 }
2449
2450
2451 int cmd_apply(int argc, const char **argv, const char *prefix)
2452 {
2453         int i;
2454         int read_stdin = 1;
2455         int inaccurate_eof = 0;
2456         int errs = 0;
2457
2458         const char *whitespace_option = NULL;
2459
2460         for (i = 1; i < argc; i++) {
2461                 const char *arg = argv[i];
2462                 char *end;
2463                 int fd;
2464
2465                 if (!strcmp(arg, "-")) {
2466                         errs |= apply_patch(0, "<stdin>", inaccurate_eof);
2467                         read_stdin = 0;
2468                         continue;
2469                 }
2470                 if (!strncmp(arg, "--exclude=", 10)) {
2471                         struct excludes *x = xmalloc(sizeof(*x));
2472                         x->path = arg + 10;
2473                         x->next = excludes;
2474                         excludes = x;
2475                         continue;
2476                 }
2477                 if (!strncmp(arg, "-p", 2)) {
2478                         p_value = atoi(arg + 2);
2479                         continue;
2480                 }
2481                 if (!strcmp(arg, "--no-add")) {
2482                         no_add = 1;
2483                         continue;
2484                 }
2485                 if (!strcmp(arg, "--stat")) {
2486                         apply = 0;
2487                         diffstat = 1;
2488                         continue;
2489                 }
2490                 if (!strcmp(arg, "--allow-binary-replacement") ||
2491                     !strcmp(arg, "--binary")) {
2492                         continue; /* now no-op */
2493                 }
2494                 if (!strcmp(arg, "--numstat")) {
2495                         apply = 0;
2496                         numstat = 1;
2497                         continue;
2498                 }
2499                 if (!strcmp(arg, "--summary")) {
2500                         apply = 0;
2501                         summary = 1;
2502                         continue;
2503                 }
2504                 if (!strcmp(arg, "--check")) {
2505                         apply = 0;
2506                         check = 1;
2507                         continue;
2508                 }
2509                 if (!strcmp(arg, "--index")) {
2510                         check_index = 1;
2511                         continue;
2512                 }
2513                 if (!strcmp(arg, "--cached")) {
2514                         check_index = 1;
2515                         cached = 1;
2516                         continue;
2517                 }
2518                 if (!strcmp(arg, "--apply")) {
2519                         apply = 1;
2520                         continue;
2521                 }
2522                 if (!strcmp(arg, "--index-info")) {
2523                         apply = 0;
2524                         show_index_info = 1;
2525                         continue;
2526                 }
2527                 if (!strcmp(arg, "-z")) {
2528                         line_termination = 0;
2529                         continue;
2530                 }
2531                 if (!strncmp(arg, "-C", 2)) {
2532                         p_context = strtoul(arg + 2, &end, 0);
2533                         if (*end != '\0')
2534                                 die("unrecognized context count '%s'", arg + 2);
2535                         continue;
2536                 }
2537                 if (!strncmp(arg, "--whitespace=", 13)) {
2538                         whitespace_option = arg + 13;
2539                         parse_whitespace_option(arg + 13);
2540                         continue;
2541                 }
2542                 if (!strcmp(arg, "-R") || !strcmp(arg, "--reverse")) {
2543                         apply_in_reverse = 1;
2544                         continue;
2545                 }
2546                 if (!strcmp(arg, "--reject")) {
2547                         apply = apply_with_reject = apply_verbosely = 1;
2548                         continue;
2549                 }
2550                 if (!strcmp(arg, "--verbose")) {
2551                         apply_verbosely = 1;
2552                         continue;
2553                 }
2554                 if (!strcmp(arg, "--inaccurate-eof")) {
2555                         inaccurate_eof = 1;
2556                         continue;
2557                 }
2558
2559                 if (check_index && prefix_length < 0) {
2560                         prefix = setup_git_directory();
2561                         prefix_length = prefix ? strlen(prefix) : 0;
2562                         git_config(git_apply_config);
2563                         if (!whitespace_option && apply_default_whitespace)
2564                                 parse_whitespace_option(apply_default_whitespace);
2565                 }
2566                 if (0 < prefix_length)
2567                         arg = prefix_filename(prefix, prefix_length, arg);
2568
2569                 fd = open(arg, O_RDONLY);
2570                 if (fd < 0)
2571                         usage(apply_usage);
2572                 read_stdin = 0;
2573                 set_default_whitespace_mode(whitespace_option);
2574                 errs |= apply_patch(fd, arg, inaccurate_eof);
2575                 close(fd);
2576         }
2577         set_default_whitespace_mode(whitespace_option);
2578         if (read_stdin)
2579                 errs |= apply_patch(0, "<stdin>", inaccurate_eof);
2580         if (whitespace_error) {
2581                 if (squelch_whitespace_errors &&
2582                     squelch_whitespace_errors < whitespace_error) {
2583                         int squelched =
2584                                 whitespace_error - squelch_whitespace_errors;
2585                         fprintf(stderr, "warning: squelched %d "
2586                                 "whitespace error%s\n",
2587                                 squelched,
2588                                 squelched == 1 ? "" : "s");
2589                 }
2590                 if (new_whitespace == error_on_whitespace)
2591                         die("%d line%s add%s trailing whitespaces.",
2592                             whitespace_error,
2593                             whitespace_error == 1 ? "" : "s",
2594                             whitespace_error == 1 ? "s" : "");
2595                 if (applied_after_stripping)
2596                         fprintf(stderr, "warning: %d line%s applied after"
2597                                 " stripping trailing whitespaces.\n",
2598                                 applied_after_stripping,
2599                                 applied_after_stripping == 1 ? "" : "s");
2600                 else if (whitespace_error)
2601                         fprintf(stderr, "warning: %d line%s add%s trailing"
2602                                 " whitespaces.\n",
2603                                 whitespace_error,
2604                                 whitespace_error == 1 ? "" : "s",
2605                                 whitespace_error == 1 ? "s" : "");
2606         }
2607
2608         if (write_index) {
2609                 if (write_cache(newfd, active_cache, active_nr) ||
2610                     close(newfd) || commit_lock_file(&lock_file))
2611                         die("Unable to write new index file");
2612         }
2613
2614         return !!errs;
2615 }