apply: free patch->{def,old,new}_name fields
[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 "cache.h"
10 #include "cache-tree.h"
11 #include "quote.h"
12 #include "blob.h"
13 #include "delta.h"
14 #include "builtin.h"
15 #include "string-list.h"
16 #include "dir.h"
17 #include "parse-options.h"
18
19 /*
20  *  --check turns on checking that the working tree matches the
21  *    files that are being modified, but doesn't apply the patch
22  *  --stat does just a diffstat, and doesn't actually apply
23  *  --numstat does numeric diffstat, and doesn't actually apply
24  *  --index-info shows the old and new index info for paths if available.
25  *  --index updates the cache as well.
26  *  --cached updates only the cache without ever touching the working tree.
27  */
28 static const char *prefix;
29 static int prefix_length = -1;
30 static int newfd = -1;
31
32 static int unidiff_zero;
33 static int p_value = 1;
34 static int p_value_known;
35 static int check_index;
36 static int update_index;
37 static int cached;
38 static int diffstat;
39 static int numstat;
40 static int summary;
41 static int check;
42 static int apply = 1;
43 static int apply_in_reverse;
44 static int apply_with_reject;
45 static int apply_verbosely;
46 static int allow_overlap;
47 static int no_add;
48 static const char *fake_ancestor;
49 static int line_termination = '\n';
50 static unsigned int p_context = UINT_MAX;
51 static const char * const apply_usage[] = {
52         "git apply [options] [<patch>...]",
53         NULL
54 };
55
56 static enum ws_error_action {
57         nowarn_ws_error,
58         warn_on_ws_error,
59         die_on_ws_error,
60         correct_ws_error
61 } ws_error_action = warn_on_ws_error;
62 static int whitespace_error;
63 static int squelch_whitespace_errors = 5;
64 static int applied_after_fixing_ws;
65
66 static enum ws_ignore {
67         ignore_ws_none,
68         ignore_ws_change
69 } ws_ignore_action = ignore_ws_none;
70
71
72 static const char *patch_input_file;
73 static const char *root;
74 static int root_len;
75 static int read_stdin = 1;
76 static int options;
77
78 static void parse_whitespace_option(const char *option)
79 {
80         if (!option) {
81                 ws_error_action = warn_on_ws_error;
82                 return;
83         }
84         if (!strcmp(option, "warn")) {
85                 ws_error_action = warn_on_ws_error;
86                 return;
87         }
88         if (!strcmp(option, "nowarn")) {
89                 ws_error_action = nowarn_ws_error;
90                 return;
91         }
92         if (!strcmp(option, "error")) {
93                 ws_error_action = die_on_ws_error;
94                 return;
95         }
96         if (!strcmp(option, "error-all")) {
97                 ws_error_action = die_on_ws_error;
98                 squelch_whitespace_errors = 0;
99                 return;
100         }
101         if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
102                 ws_error_action = correct_ws_error;
103                 return;
104         }
105         die("unrecognized whitespace option '%s'", option);
106 }
107
108 static void parse_ignorewhitespace_option(const char *option)
109 {
110         if (!option || !strcmp(option, "no") ||
111             !strcmp(option, "false") || !strcmp(option, "never") ||
112             !strcmp(option, "none")) {
113                 ws_ignore_action = ignore_ws_none;
114                 return;
115         }
116         if (!strcmp(option, "change")) {
117                 ws_ignore_action = ignore_ws_change;
118                 return;
119         }
120         die("unrecognized whitespace ignore option '%s'", option);
121 }
122
123 static void set_default_whitespace_mode(const char *whitespace_option)
124 {
125         if (!whitespace_option && !apply_default_whitespace)
126                 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error);
127 }
128
129 /*
130  * For "diff-stat" like behaviour, we keep track of the biggest change
131  * we've seen, and the longest filename. That allows us to do simple
132  * scaling.
133  */
134 static int max_change, max_len;
135
136 /*
137  * Various "current state", notably line numbers and what
138  * file (and how) we're patching right now.. The "is_xxxx"
139  * things are flags, where -1 means "don't know yet".
140  */
141 static int linenr = 1;
142
143 /*
144  * This represents one "hunk" from a patch, starting with
145  * "@@ -oldpos,oldlines +newpos,newlines @@" marker.  The
146  * patch text is pointed at by patch, and its byte length
147  * is stored in size.  leading and trailing are the number
148  * of context lines.
149  */
150 struct fragment {
151         unsigned long leading, trailing;
152         unsigned long oldpos, oldlines;
153         unsigned long newpos, newlines;
154         const char *patch;
155         unsigned free_patch:1,
156                 rejected:1;
157         int size;
158         int linenr;
159         struct fragment *next;
160 };
161
162 /*
163  * When dealing with a binary patch, we reuse "leading" field
164  * to store the type of the binary hunk, either deflated "delta"
165  * or deflated "literal".
166  */
167 #define binary_patch_method leading
168 #define BINARY_DELTA_DEFLATED   1
169 #define BINARY_LITERAL_DEFLATED 2
170
171 /*
172  * This represents a "patch" to a file, both metainfo changes
173  * such as creation/deletion, filemode and content changes represented
174  * as a series of fragments.
175  */
176 struct patch {
177         char *new_name, *old_name, *def_name;
178         unsigned int old_mode, new_mode;
179         int is_new, is_delete;  /* -1 = unknown, 0 = false, 1 = true */
180         int rejected;
181         unsigned ws_rule;
182         unsigned long deflate_origlen;
183         int lines_added, lines_deleted;
184         int score;
185         unsigned int is_toplevel_relative:1;
186         unsigned int inaccurate_eof:1;
187         unsigned int is_binary:1;
188         unsigned int is_copy:1;
189         unsigned int is_rename:1;
190         unsigned int recount:1;
191         struct fragment *fragments;
192         char *result;
193         size_t resultsize;
194         char old_sha1_prefix[41];
195         char new_sha1_prefix[41];
196         struct patch *next;
197 };
198
199 static void free_patch(struct patch *patch)
200 {
201         struct fragment *fragment = patch->fragments;
202
203         while (fragment) {
204                 struct fragment *fragment_next = fragment->next;
205                 if (fragment->patch != NULL && fragment->free_patch)
206                         free((char *)fragment->patch);
207                 free(fragment);
208                 fragment = fragment_next;
209         }
210         free(patch->def_name);
211         free(patch->old_name);
212         free(patch->new_name);
213         free(patch);
214 }
215
216 static void free_patch_list(struct patch *list)
217 {
218         while (list) {
219                 struct patch *next = list->next;
220                 free_patch(list);
221                 list = next;
222         }
223 }
224
225 /*
226  * A line in a file, len-bytes long (includes the terminating LF,
227  * except for an incomplete line at the end if the file ends with
228  * one), and its contents hashes to 'hash'.
229  */
230 struct line {
231         size_t len;
232         unsigned hash : 24;
233         unsigned flag : 8;
234 #define LINE_COMMON     1
235 #define LINE_PATCHED    2
236 };
237
238 /*
239  * This represents a "file", which is an array of "lines".
240  */
241 struct image {
242         char *buf;
243         size_t len;
244         size_t nr;
245         size_t alloc;
246         struct line *line_allocated;
247         struct line *line;
248 };
249
250 /*
251  * Records filenames that have been touched, in order to handle
252  * the case where more than one patches touch the same file.
253  */
254
255 static struct string_list fn_table;
256
257 static uint32_t hash_line(const char *cp, size_t len)
258 {
259         size_t i;
260         uint32_t h;
261         for (i = 0, h = 0; i < len; i++) {
262                 if (!isspace(cp[i])) {
263                         h = h * 3 + (cp[i] & 0xff);
264                 }
265         }
266         return h;
267 }
268
269 /*
270  * Compare lines s1 of length n1 and s2 of length n2, ignoring
271  * whitespace difference. Returns 1 if they match, 0 otherwise
272  */
273 static int fuzzy_matchlines(const char *s1, size_t n1,
274                             const char *s2, size_t n2)
275 {
276         const char *last1 = s1 + n1 - 1;
277         const char *last2 = s2 + n2 - 1;
278         int result = 0;
279
280         /* ignore line endings */
281         while ((*last1 == '\r') || (*last1 == '\n'))
282                 last1--;
283         while ((*last2 == '\r') || (*last2 == '\n'))
284                 last2--;
285
286         /* skip leading whitespace */
287         while (isspace(*s1) && (s1 <= last1))
288                 s1++;
289         while (isspace(*s2) && (s2 <= last2))
290                 s2++;
291         /* early return if both lines are empty */
292         if ((s1 > last1) && (s2 > last2))
293                 return 1;
294         while (!result) {
295                 result = *s1++ - *s2++;
296                 /*
297                  * Skip whitespace inside. We check for whitespace on
298                  * both buffers because we don't want "a b" to match
299                  * "ab"
300                  */
301                 if (isspace(*s1) && isspace(*s2)) {
302                         while (isspace(*s1) && s1 <= last1)
303                                 s1++;
304                         while (isspace(*s2) && s2 <= last2)
305                                 s2++;
306                 }
307                 /*
308                  * If we reached the end on one side only,
309                  * lines don't match
310                  */
311                 if (
312                     ((s2 > last2) && (s1 <= last1)) ||
313                     ((s1 > last1) && (s2 <= last2)))
314                         return 0;
315                 if ((s1 > last1) && (s2 > last2))
316                         break;
317         }
318
319         return !result;
320 }
321
322 static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
323 {
324         ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
325         img->line_allocated[img->nr].len = len;
326         img->line_allocated[img->nr].hash = hash_line(bol, len);
327         img->line_allocated[img->nr].flag = flag;
328         img->nr++;
329 }
330
331 static void prepare_image(struct image *image, char *buf, size_t len,
332                           int prepare_linetable)
333 {
334         const char *cp, *ep;
335
336         memset(image, 0, sizeof(*image));
337         image->buf = buf;
338         image->len = len;
339
340         if (!prepare_linetable)
341                 return;
342
343         ep = image->buf + image->len;
344         cp = image->buf;
345         while (cp < ep) {
346                 const char *next;
347                 for (next = cp; next < ep && *next != '\n'; next++)
348                         ;
349                 if (next < ep)
350                         next++;
351                 add_line_info(image, cp, next - cp, 0);
352                 cp = next;
353         }
354         image->line = image->line_allocated;
355 }
356
357 static void clear_image(struct image *image)
358 {
359         free(image->buf);
360         image->buf = NULL;
361         image->len = 0;
362 }
363
364 static void say_patch_name(FILE *output, const char *pre,
365                            struct patch *patch, const char *post)
366 {
367         fputs(pre, output);
368         if (patch->old_name && patch->new_name &&
369             strcmp(patch->old_name, patch->new_name)) {
370                 quote_c_style(patch->old_name, NULL, output, 0);
371                 fputs(" => ", output);
372                 quote_c_style(patch->new_name, NULL, output, 0);
373         } else {
374                 const char *n = patch->new_name;
375                 if (!n)
376                         n = patch->old_name;
377                 quote_c_style(n, NULL, output, 0);
378         }
379         fputs(post, output);
380 }
381
382 #define CHUNKSIZE (8192)
383 #define SLOP (16)
384
385 static void read_patch_file(struct strbuf *sb, int fd)
386 {
387         if (strbuf_read(sb, fd, 0) < 0)
388                 die_errno("git apply: failed to read");
389
390         /*
391          * Make sure that we have some slop in the buffer
392          * so that we can do speculative "memcmp" etc, and
393          * see to it that it is NUL-filled.
394          */
395         strbuf_grow(sb, SLOP);
396         memset(sb->buf + sb->len, 0, SLOP);
397 }
398
399 static unsigned long linelen(const char *buffer, unsigned long size)
400 {
401         unsigned long len = 0;
402         while (size--) {
403                 len++;
404                 if (*buffer++ == '\n')
405                         break;
406         }
407         return len;
408 }
409
410 static int is_dev_null(const char *str)
411 {
412         return !memcmp("/dev/null", str, 9) && isspace(str[9]);
413 }
414
415 #define TERM_SPACE      1
416 #define TERM_TAB        2
417
418 static int name_terminate(const char *name, int namelen, int c, int terminate)
419 {
420         if (c == ' ' && !(terminate & TERM_SPACE))
421                 return 0;
422         if (c == '\t' && !(terminate & TERM_TAB))
423                 return 0;
424
425         return 1;
426 }
427
428 /* remove double slashes to make --index work with such filenames */
429 static char *squash_slash(char *name)
430 {
431         int i = 0, j = 0;
432
433         if (!name)
434                 return NULL;
435
436         while (name[i]) {
437                 if ((name[j++] = name[i++]) == '/')
438                         while (name[i] == '/')
439                                 i++;
440         }
441         name[j] = '\0';
442         return name;
443 }
444
445 static char *find_name_gnu(const char *line, const char *def, int p_value)
446 {
447         struct strbuf name = STRBUF_INIT;
448         char *cp;
449
450         /*
451          * Proposed "new-style" GNU patch/diff format; see
452          * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
453          */
454         if (unquote_c_style(&name, line, NULL)) {
455                 strbuf_release(&name);
456                 return NULL;
457         }
458
459         for (cp = name.buf; p_value; p_value--) {
460                 cp = strchr(cp, '/');
461                 if (!cp) {
462                         strbuf_release(&name);
463                         return NULL;
464                 }
465                 cp++;
466         }
467
468         strbuf_remove(&name, 0, cp - name.buf);
469         if (root)
470                 strbuf_insert(&name, 0, root, root_len);
471         return squash_slash(strbuf_detach(&name, NULL));
472 }
473
474 static size_t sane_tz_len(const char *line, size_t len)
475 {
476         const char *tz, *p;
477
478         if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
479                 return 0;
480         tz = line + len - strlen(" +0500");
481
482         if (tz[1] != '+' && tz[1] != '-')
483                 return 0;
484
485         for (p = tz + 2; p != line + len; p++)
486                 if (!isdigit(*p))
487                         return 0;
488
489         return line + len - tz;
490 }
491
492 static size_t tz_with_colon_len(const char *line, size_t len)
493 {
494         const char *tz, *p;
495
496         if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
497                 return 0;
498         tz = line + len - strlen(" +08:00");
499
500         if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
501                 return 0;
502         p = tz + 2;
503         if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
504             !isdigit(*p++) || !isdigit(*p++))
505                 return 0;
506
507         return line + len - tz;
508 }
509
510 static size_t date_len(const char *line, size_t len)
511 {
512         const char *date, *p;
513
514         if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
515                 return 0;
516         p = date = line + len - strlen("72-02-05");
517
518         if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
519             !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
520             !isdigit(*p++) || !isdigit(*p++))   /* Not a date. */
521                 return 0;
522
523         if (date - line >= strlen("19") &&
524             isdigit(date[-1]) && isdigit(date[-2]))     /* 4-digit year */
525                 date -= strlen("19");
526
527         return line + len - date;
528 }
529
530 static size_t short_time_len(const char *line, size_t len)
531 {
532         const char *time, *p;
533
534         if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
535                 return 0;
536         p = time = line + len - strlen(" 07:01:32");
537
538         /* Permit 1-digit hours? */
539         if (*p++ != ' ' ||
540             !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
541             !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
542             !isdigit(*p++) || !isdigit(*p++))   /* Not a time. */
543                 return 0;
544
545         return line + len - time;
546 }
547
548 static size_t fractional_time_len(const char *line, size_t len)
549 {
550         const char *p;
551         size_t n;
552
553         /* Expected format: 19:41:17.620000023 */
554         if (!len || !isdigit(line[len - 1]))
555                 return 0;
556         p = line + len - 1;
557
558         /* Fractional seconds. */
559         while (p > line && isdigit(*p))
560                 p--;
561         if (*p != '.')
562                 return 0;
563
564         /* Hours, minutes, and whole seconds. */
565         n = short_time_len(line, p - line);
566         if (!n)
567                 return 0;
568
569         return line + len - p + n;
570 }
571
572 static size_t trailing_spaces_len(const char *line, size_t len)
573 {
574         const char *p;
575
576         /* Expected format: ' ' x (1 or more)  */
577         if (!len || line[len - 1] != ' ')
578                 return 0;
579
580         p = line + len;
581         while (p != line) {
582                 p--;
583                 if (*p != ' ')
584                         return line + len - (p + 1);
585         }
586
587         /* All spaces! */
588         return len;
589 }
590
591 static size_t diff_timestamp_len(const char *line, size_t len)
592 {
593         const char *end = line + len;
594         size_t n;
595
596         /*
597          * Posix: 2010-07-05 19:41:17
598          * GNU: 2010-07-05 19:41:17.620000023 -0500
599          */
600
601         if (!isdigit(end[-1]))
602                 return 0;
603
604         n = sane_tz_len(line, end - line);
605         if (!n)
606                 n = tz_with_colon_len(line, end - line);
607         end -= n;
608
609         n = short_time_len(line, end - line);
610         if (!n)
611                 n = fractional_time_len(line, end - line);
612         end -= n;
613
614         n = date_len(line, end - line);
615         if (!n) /* No date.  Too bad. */
616                 return 0;
617         end -= n;
618
619         if (end == line)        /* No space before date. */
620                 return 0;
621         if (end[-1] == '\t') {  /* Success! */
622                 end--;
623                 return line + len - end;
624         }
625         if (end[-1] != ' ')     /* No space before date. */
626                 return 0;
627
628         /* Whitespace damage. */
629         end -= trailing_spaces_len(line, end - line);
630         return line + len - end;
631 }
632
633 static char *null_strdup(const char *s)
634 {
635         return s ? xstrdup(s) : NULL;
636 }
637
638 static char *find_name_common(const char *line, const char *def,
639                               int p_value, const char *end, int terminate)
640 {
641         int len;
642         const char *start = NULL;
643
644         if (p_value == 0)
645                 start = line;
646         while (line != end) {
647                 char c = *line;
648
649                 if (!end && isspace(c)) {
650                         if (c == '\n')
651                                 break;
652                         if (name_terminate(start, line-start, c, terminate))
653                                 break;
654                 }
655                 line++;
656                 if (c == '/' && !--p_value)
657                         start = line;
658         }
659         if (!start)
660                 return squash_slash(null_strdup(def));
661         len = line - start;
662         if (!len)
663                 return squash_slash(null_strdup(def));
664
665         /*
666          * Generally we prefer the shorter name, especially
667          * if the other one is just a variation of that with
668          * something else tacked on to the end (ie "file.orig"
669          * or "file~").
670          */
671         if (def) {
672                 int deflen = strlen(def);
673                 if (deflen < len && !strncmp(start, def, deflen))
674                         return squash_slash(xstrdup(def));
675         }
676
677         if (root) {
678                 char *ret = xmalloc(root_len + len + 1);
679                 strcpy(ret, root);
680                 memcpy(ret + root_len, start, len);
681                 ret[root_len + len] = '\0';
682                 return squash_slash(ret);
683         }
684
685         return squash_slash(xmemdupz(start, len));
686 }
687
688 static char *find_name(const char *line, char *def, int p_value, int terminate)
689 {
690         if (*line == '"') {
691                 char *name = find_name_gnu(line, def, p_value);
692                 if (name)
693                         return name;
694         }
695
696         return find_name_common(line, def, p_value, NULL, terminate);
697 }
698
699 static char *find_name_traditional(const char *line, char *def, int p_value)
700 {
701         size_t len = strlen(line);
702         size_t date_len;
703
704         if (*line == '"') {
705                 char *name = find_name_gnu(line, def, p_value);
706                 if (name)
707                         return name;
708         }
709
710         len = strchrnul(line, '\n') - line;
711         date_len = diff_timestamp_len(line, len);
712         if (!date_len)
713                 return find_name_common(line, def, p_value, NULL, TERM_TAB);
714         len -= date_len;
715
716         return find_name_common(line, def, p_value, line + len, 0);
717 }
718
719 static int count_slashes(const char *cp)
720 {
721         int cnt = 0;
722         char ch;
723
724         while ((ch = *cp++))
725                 if (ch == '/')
726                         cnt++;
727         return cnt;
728 }
729
730 /*
731  * Given the string after "--- " or "+++ ", guess the appropriate
732  * p_value for the given patch.
733  */
734 static int guess_p_value(const char *nameline)
735 {
736         char *name, *cp;
737         int val = -1;
738
739         if (is_dev_null(nameline))
740                 return -1;
741         name = find_name_traditional(nameline, NULL, 0);
742         if (!name)
743                 return -1;
744         cp = strchr(name, '/');
745         if (!cp)
746                 val = 0;
747         else if (prefix) {
748                 /*
749                  * Does it begin with "a/$our-prefix" and such?  Then this is
750                  * very likely to apply to our directory.
751                  */
752                 if (!strncmp(name, prefix, prefix_length))
753                         val = count_slashes(prefix);
754                 else {
755                         cp++;
756                         if (!strncmp(cp, prefix, prefix_length))
757                                 val = count_slashes(prefix) + 1;
758                 }
759         }
760         free(name);
761         return val;
762 }
763
764 /*
765  * Does the ---/+++ line has the POSIX timestamp after the last HT?
766  * GNU diff puts epoch there to signal a creation/deletion event.  Is
767  * this such a timestamp?
768  */
769 static int has_epoch_timestamp(const char *nameline)
770 {
771         /*
772          * We are only interested in epoch timestamp; any non-zero
773          * fraction cannot be one, hence "(\.0+)?" in the regexp below.
774          * For the same reason, the date must be either 1969-12-31 or
775          * 1970-01-01, and the seconds part must be "00".
776          */
777         const char stamp_regexp[] =
778                 "^(1969-12-31|1970-01-01)"
779                 " "
780                 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
781                 " "
782                 "([-+][0-2][0-9]:?[0-5][0-9])\n";
783         const char *timestamp = NULL, *cp, *colon;
784         static regex_t *stamp;
785         regmatch_t m[10];
786         int zoneoffset;
787         int hourminute;
788         int status;
789
790         for (cp = nameline; *cp != '\n'; cp++) {
791                 if (*cp == '\t')
792                         timestamp = cp + 1;
793         }
794         if (!timestamp)
795                 return 0;
796         if (!stamp) {
797                 stamp = xmalloc(sizeof(*stamp));
798                 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
799                         warning("Cannot prepare timestamp regexp %s",
800                                 stamp_regexp);
801                         return 0;
802                 }
803         }
804
805         status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
806         if (status) {
807                 if (status != REG_NOMATCH)
808                         warning("regexec returned %d for input: %s",
809                                 status, timestamp);
810                 return 0;
811         }
812
813         zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
814         if (*colon == ':')
815                 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
816         else
817                 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
818         if (timestamp[m[3].rm_so] == '-')
819                 zoneoffset = -zoneoffset;
820
821         /*
822          * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
823          * (west of GMT) or 1970-01-01 (east of GMT)
824          */
825         if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) ||
826             (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10)))
827                 return 0;
828
829         hourminute = (strtol(timestamp + 11, NULL, 10) * 60 +
830                       strtol(timestamp + 14, NULL, 10) -
831                       zoneoffset);
832
833         return ((zoneoffset < 0 && hourminute == 1440) ||
834                 (0 <= zoneoffset && !hourminute));
835 }
836
837 /*
838  * Get the name etc info from the ---/+++ lines of a traditional patch header
839  *
840  * FIXME! The end-of-filename heuristics are kind of screwy. For existing
841  * files, we can happily check the index for a match, but for creating a
842  * new file we should try to match whatever "patch" does. I have no idea.
843  */
844 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
845 {
846         char *name;
847
848         first += 4;     /* skip "--- " */
849         second += 4;    /* skip "+++ " */
850         if (!p_value_known) {
851                 int p, q;
852                 p = guess_p_value(first);
853                 q = guess_p_value(second);
854                 if (p < 0) p = q;
855                 if (0 <= p && p == q) {
856                         p_value = p;
857                         p_value_known = 1;
858                 }
859         }
860         if (is_dev_null(first)) {
861                 patch->is_new = 1;
862                 patch->is_delete = 0;
863                 name = find_name_traditional(second, NULL, p_value);
864                 patch->new_name = name;
865         } else if (is_dev_null(second)) {
866                 patch->is_new = 0;
867                 patch->is_delete = 1;
868                 name = find_name_traditional(first, NULL, p_value);
869                 patch->old_name = name;
870         } else {
871                 char *first_name;
872                 first_name = find_name_traditional(first, NULL, p_value);
873                 name = find_name_traditional(second, first_name, p_value);
874                 free(first_name);
875                 if (has_epoch_timestamp(first)) {
876                         patch->is_new = 1;
877                         patch->is_delete = 0;
878                         patch->new_name = name;
879                 } else if (has_epoch_timestamp(second)) {
880                         patch->is_new = 0;
881                         patch->is_delete = 1;
882                         patch->old_name = name;
883                 } else {
884                         patch->old_name = name;
885                         patch->new_name = xstrdup(name);
886                 }
887         }
888         if (!name)
889                 die("unable to find filename in patch at line %d", linenr);
890 }
891
892 static int gitdiff_hdrend(const char *line, struct patch *patch)
893 {
894         return -1;
895 }
896
897 /*
898  * We're anal about diff header consistency, to make
899  * sure that we don't end up having strange ambiguous
900  * patches floating around.
901  *
902  * As a result, gitdiff_{old|new}name() will check
903  * their names against any previous information, just
904  * to make sure..
905  */
906 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
907 {
908         if (!orig_name && !isnull)
909                 return find_name(line, NULL, p_value, TERM_TAB);
910
911         if (orig_name) {
912                 int len;
913                 const char *name;
914                 char *another;
915                 name = orig_name;
916                 len = strlen(name);
917                 if (isnull)
918                         die("git apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
919                 another = find_name(line, NULL, p_value, TERM_TAB);
920                 if (!another || memcmp(another, name, len + 1))
921                         die("git apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
922                 free(another);
923                 return orig_name;
924         }
925         else {
926                 /* expect "/dev/null" */
927                 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
928                         die("git apply: bad git-diff - expected /dev/null on line %d", linenr);
929                 return NULL;
930         }
931 }
932
933 static int gitdiff_oldname(const char *line, struct patch *patch)
934 {
935         char *orig = patch->old_name;
936         patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
937         if (orig != patch->old_name)
938                 free(orig);
939         return 0;
940 }
941
942 static int gitdiff_newname(const char *line, struct patch *patch)
943 {
944         char *orig = patch->new_name;
945         patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
946         if (orig != patch->new_name)
947                 free(orig);
948         return 0;
949 }
950
951 static int gitdiff_oldmode(const char *line, struct patch *patch)
952 {
953         patch->old_mode = strtoul(line, NULL, 8);
954         return 0;
955 }
956
957 static int gitdiff_newmode(const char *line, struct patch *patch)
958 {
959         patch->new_mode = strtoul(line, NULL, 8);
960         return 0;
961 }
962
963 static int gitdiff_delete(const char *line, struct patch *patch)
964 {
965         patch->is_delete = 1;
966         free(patch->old_name);
967         patch->old_name = null_strdup(patch->def_name);
968         return gitdiff_oldmode(line, patch);
969 }
970
971 static int gitdiff_newfile(const char *line, struct patch *patch)
972 {
973         patch->is_new = 1;
974         free(patch->new_name);
975         patch->new_name = null_strdup(patch->def_name);
976         return gitdiff_newmode(line, patch);
977 }
978
979 static int gitdiff_copysrc(const char *line, struct patch *patch)
980 {
981         patch->is_copy = 1;
982         free(patch->old_name);
983         patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
984         return 0;
985 }
986
987 static int gitdiff_copydst(const char *line, struct patch *patch)
988 {
989         patch->is_copy = 1;
990         free(patch->new_name);
991         patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
992         return 0;
993 }
994
995 static int gitdiff_renamesrc(const char *line, struct patch *patch)
996 {
997         patch->is_rename = 1;
998         free(patch->old_name);
999         patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1000         return 0;
1001 }
1002
1003 static int gitdiff_renamedst(const char *line, struct patch *patch)
1004 {
1005         patch->is_rename = 1;
1006         free(patch->new_name);
1007         patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1008         return 0;
1009 }
1010
1011 static int gitdiff_similarity(const char *line, struct patch *patch)
1012 {
1013         if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
1014                 patch->score = 0;
1015         return 0;
1016 }
1017
1018 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
1019 {
1020         if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
1021                 patch->score = 0;
1022         return 0;
1023 }
1024
1025 static int gitdiff_index(const char *line, struct patch *patch)
1026 {
1027         /*
1028          * index line is N hexadecimal, "..", N hexadecimal,
1029          * and optional space with octal mode.
1030          */
1031         const char *ptr, *eol;
1032         int len;
1033
1034         ptr = strchr(line, '.');
1035         if (!ptr || ptr[1] != '.' || 40 < ptr - line)
1036                 return 0;
1037         len = ptr - line;
1038         memcpy(patch->old_sha1_prefix, line, len);
1039         patch->old_sha1_prefix[len] = 0;
1040
1041         line = ptr + 2;
1042         ptr = strchr(line, ' ');
1043         eol = strchr(line, '\n');
1044
1045         if (!ptr || eol < ptr)
1046                 ptr = eol;
1047         len = ptr - line;
1048
1049         if (40 < len)
1050                 return 0;
1051         memcpy(patch->new_sha1_prefix, line, len);
1052         patch->new_sha1_prefix[len] = 0;
1053         if (*ptr == ' ')
1054                 patch->old_mode = strtoul(ptr+1, NULL, 8);
1055         return 0;
1056 }
1057
1058 /*
1059  * This is normal for a diff that doesn't change anything: we'll fall through
1060  * into the next diff. Tell the parser to break out.
1061  */
1062 static int gitdiff_unrecognized(const char *line, struct patch *patch)
1063 {
1064         return -1;
1065 }
1066
1067 static const char *stop_at_slash(const char *line, int llen)
1068 {
1069         int nslash = p_value;
1070         int i;
1071
1072         for (i = 0; i < llen; i++) {
1073                 int ch = line[i];
1074                 if (ch == '/' && --nslash <= 0)
1075                         return &line[i];
1076         }
1077         return NULL;
1078 }
1079
1080 /*
1081  * This is to extract the same name that appears on "diff --git"
1082  * line.  We do not find and return anything if it is a rename
1083  * patch, and it is OK because we will find the name elsewhere.
1084  * We need to reliably find name only when it is mode-change only,
1085  * creation or deletion of an empty file.  In any of these cases,
1086  * both sides are the same name under a/ and b/ respectively.
1087  */
1088 static char *git_header_name(char *line, int llen)
1089 {
1090         const char *name;
1091         const char *second = NULL;
1092         size_t len, line_len;
1093
1094         line += strlen("diff --git ");
1095         llen -= strlen("diff --git ");
1096
1097         if (*line == '"') {
1098                 const char *cp;
1099                 struct strbuf first = STRBUF_INIT;
1100                 struct strbuf sp = STRBUF_INIT;
1101
1102                 if (unquote_c_style(&first, line, &second))
1103                         goto free_and_fail1;
1104
1105                 /* advance to the first slash */
1106                 cp = stop_at_slash(first.buf, first.len);
1107                 /* we do not accept absolute paths */
1108                 if (!cp || cp == first.buf)
1109                         goto free_and_fail1;
1110                 strbuf_remove(&first, 0, cp + 1 - first.buf);
1111
1112                 /*
1113                  * second points at one past closing dq of name.
1114                  * find the second name.
1115                  */
1116                 while ((second < line + llen) && isspace(*second))
1117                         second++;
1118
1119                 if (line + llen <= second)
1120                         goto free_and_fail1;
1121                 if (*second == '"') {
1122                         if (unquote_c_style(&sp, second, NULL))
1123                                 goto free_and_fail1;
1124                         cp = stop_at_slash(sp.buf, sp.len);
1125                         if (!cp || cp == sp.buf)
1126                                 goto free_and_fail1;
1127                         /* They must match, otherwise ignore */
1128                         if (strcmp(cp + 1, first.buf))
1129                                 goto free_and_fail1;
1130                         strbuf_release(&sp);
1131                         return strbuf_detach(&first, NULL);
1132                 }
1133
1134                 /* unquoted second */
1135                 cp = stop_at_slash(second, line + llen - second);
1136                 if (!cp || cp == second)
1137                         goto free_and_fail1;
1138                 cp++;
1139                 if (line + llen - cp != first.len + 1 ||
1140                     memcmp(first.buf, cp, first.len))
1141                         goto free_and_fail1;
1142                 return strbuf_detach(&first, NULL);
1143
1144         free_and_fail1:
1145                 strbuf_release(&first);
1146                 strbuf_release(&sp);
1147                 return NULL;
1148         }
1149
1150         /* unquoted first name */
1151         name = stop_at_slash(line, llen);
1152         if (!name || name == line)
1153                 return NULL;
1154         name++;
1155
1156         /*
1157          * since the first name is unquoted, a dq if exists must be
1158          * the beginning of the second name.
1159          */
1160         for (second = name; second < line + llen; second++) {
1161                 if (*second == '"') {
1162                         struct strbuf sp = STRBUF_INIT;
1163                         const char *np;
1164
1165                         if (unquote_c_style(&sp, second, NULL))
1166                                 goto free_and_fail2;
1167
1168                         np = stop_at_slash(sp.buf, sp.len);
1169                         if (!np || np == sp.buf)
1170                                 goto free_and_fail2;
1171                         np++;
1172
1173                         len = sp.buf + sp.len - np;
1174                         if (len < second - name &&
1175                             !strncmp(np, name, len) &&
1176                             isspace(name[len])) {
1177                                 /* Good */
1178                                 strbuf_remove(&sp, 0, np - sp.buf);
1179                                 return strbuf_detach(&sp, NULL);
1180                         }
1181
1182                 free_and_fail2:
1183                         strbuf_release(&sp);
1184                         return NULL;
1185                 }
1186         }
1187
1188         /*
1189          * Accept a name only if it shows up twice, exactly the same
1190          * form.
1191          */
1192         second = strchr(name, '\n');
1193         if (!second)
1194                 return NULL;
1195         line_len = second - name;
1196         for (len = 0 ; ; len++) {
1197                 switch (name[len]) {
1198                 default:
1199                         continue;
1200                 case '\n':
1201                         return NULL;
1202                 case '\t': case ' ':
1203                         second = stop_at_slash(name + len, line_len - len);
1204                         if (!second)
1205                                 return NULL;
1206                         second++;
1207                         if (second[len] == '\n' && !strncmp(name, second, len)) {
1208                                 return xmemdupz(name, len);
1209                         }
1210                 }
1211         }
1212 }
1213
1214 /* Verify that we recognize the lines following a git header */
1215 static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
1216 {
1217         unsigned long offset;
1218
1219         /* A git diff has explicit new/delete information, so we don't guess */
1220         patch->is_new = 0;
1221         patch->is_delete = 0;
1222
1223         /*
1224          * Some things may not have the old name in the
1225          * rest of the headers anywhere (pure mode changes,
1226          * or removing or adding empty files), so we get
1227          * the default name from the header.
1228          */
1229         patch->def_name = git_header_name(line, len);
1230         if (patch->def_name && root) {
1231                 char *s = xmalloc(root_len + strlen(patch->def_name) + 1);
1232                 strcpy(s, root);
1233                 strcpy(s + root_len, patch->def_name);
1234                 free(patch->def_name);
1235                 patch->def_name = s;
1236         }
1237
1238         line += len;
1239         size -= len;
1240         linenr++;
1241         for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
1242                 static const struct opentry {
1243                         const char *str;
1244                         int (*fn)(const char *, struct patch *);
1245                 } optable[] = {
1246                         { "@@ -", gitdiff_hdrend },
1247                         { "--- ", gitdiff_oldname },
1248                         { "+++ ", gitdiff_newname },
1249                         { "old mode ", gitdiff_oldmode },
1250                         { "new mode ", gitdiff_newmode },
1251                         { "deleted file mode ", gitdiff_delete },
1252                         { "new file mode ", gitdiff_newfile },
1253                         { "copy from ", gitdiff_copysrc },
1254                         { "copy to ", gitdiff_copydst },
1255                         { "rename old ", gitdiff_renamesrc },
1256                         { "rename new ", gitdiff_renamedst },
1257                         { "rename from ", gitdiff_renamesrc },
1258                         { "rename to ", gitdiff_renamedst },
1259                         { "similarity index ", gitdiff_similarity },
1260                         { "dissimilarity index ", gitdiff_dissimilarity },
1261                         { "index ", gitdiff_index },
1262                         { "", gitdiff_unrecognized },
1263                 };
1264                 int i;
1265
1266                 len = linelen(line, size);
1267                 if (!len || line[len-1] != '\n')
1268                         break;
1269                 for (i = 0; i < ARRAY_SIZE(optable); i++) {
1270                         const struct opentry *p = optable + i;
1271                         int oplen = strlen(p->str);
1272                         if (len < oplen || memcmp(p->str, line, oplen))
1273                                 continue;
1274                         if (p->fn(line + oplen, patch) < 0)
1275                                 return offset;
1276                         break;
1277                 }
1278         }
1279
1280         return offset;
1281 }
1282
1283 static int parse_num(const char *line, unsigned long *p)
1284 {
1285         char *ptr;
1286
1287         if (!isdigit(*line))
1288                 return 0;
1289         *p = strtoul(line, &ptr, 10);
1290         return ptr - line;
1291 }
1292
1293 static int parse_range(const char *line, int len, int offset, const char *expect,
1294                        unsigned long *p1, unsigned long *p2)
1295 {
1296         int digits, ex;
1297
1298         if (offset < 0 || offset >= len)
1299                 return -1;
1300         line += offset;
1301         len -= offset;
1302
1303         digits = parse_num(line, p1);
1304         if (!digits)
1305                 return -1;
1306
1307         offset += digits;
1308         line += digits;
1309         len -= digits;
1310
1311         *p2 = 1;
1312         if (*line == ',') {
1313                 digits = parse_num(line+1, p2);
1314                 if (!digits)
1315                         return -1;
1316
1317                 offset += digits+1;
1318                 line += digits+1;
1319                 len -= digits+1;
1320         }
1321
1322         ex = strlen(expect);
1323         if (ex > len)
1324                 return -1;
1325         if (memcmp(line, expect, ex))
1326                 return -1;
1327
1328         return offset + ex;
1329 }
1330
1331 static void recount_diff(char *line, int size, struct fragment *fragment)
1332 {
1333         int oldlines = 0, newlines = 0, ret = 0;
1334
1335         if (size < 1) {
1336                 warning("recount: ignore empty hunk");
1337                 return;
1338         }
1339
1340         for (;;) {
1341                 int len = linelen(line, size);
1342                 size -= len;
1343                 line += len;
1344
1345                 if (size < 1)
1346                         break;
1347
1348                 switch (*line) {
1349                 case ' ': case '\n':
1350                         newlines++;
1351                         /* fall through */
1352                 case '-':
1353                         oldlines++;
1354                         continue;
1355                 case '+':
1356                         newlines++;
1357                         continue;
1358                 case '\\':
1359                         continue;
1360                 case '@':
1361                         ret = size < 3 || prefixcmp(line, "@@ ");
1362                         break;
1363                 case 'd':
1364                         ret = size < 5 || prefixcmp(line, "diff ");
1365                         break;
1366                 default:
1367                         ret = -1;
1368                         break;
1369                 }
1370                 if (ret) {
1371                         warning("recount: unexpected line: %.*s",
1372                                 (int)linelen(line, size), line);
1373                         return;
1374                 }
1375                 break;
1376         }
1377         fragment->oldlines = oldlines;
1378         fragment->newlines = newlines;
1379 }
1380
1381 /*
1382  * Parse a unified diff fragment header of the
1383  * form "@@ -a,b +c,d @@"
1384  */
1385 static int parse_fragment_header(char *line, int len, struct fragment *fragment)
1386 {
1387         int offset;
1388
1389         if (!len || line[len-1] != '\n')
1390                 return -1;
1391
1392         /* Figure out the number of lines in a fragment */
1393         offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1394         offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1395
1396         return offset;
1397 }
1398
1399 static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
1400 {
1401         unsigned long offset, len;
1402
1403         patch->is_toplevel_relative = 0;
1404         patch->is_rename = patch->is_copy = 0;
1405         patch->is_new = patch->is_delete = -1;
1406         patch->old_mode = patch->new_mode = 0;
1407         patch->old_name = patch->new_name = NULL;
1408         for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
1409                 unsigned long nextlen;
1410
1411                 len = linelen(line, size);
1412                 if (!len)
1413                         break;
1414
1415                 /* Testing this early allows us to take a few shortcuts.. */
1416                 if (len < 6)
1417                         continue;
1418
1419                 /*
1420                  * Make sure we don't find any unconnected patch fragments.
1421                  * That's a sign that we didn't find a header, and that a
1422                  * patch has become corrupted/broken up.
1423                  */
1424                 if (!memcmp("@@ -", line, 4)) {
1425                         struct fragment dummy;
1426                         if (parse_fragment_header(line, len, &dummy) < 0)
1427                                 continue;
1428                         die("patch fragment without header at line %d: %.*s",
1429                             linenr, (int)len-1, line);
1430                 }
1431
1432                 if (size < len + 6)
1433                         break;
1434
1435                 /*
1436                  * Git patch? It might not have a real patch, just a rename
1437                  * or mode change, so we handle that specially
1438                  */
1439                 if (!memcmp("diff --git ", line, 11)) {
1440                         int git_hdr_len = parse_git_header(line, len, size, patch);
1441                         if (git_hdr_len <= len)
1442                                 continue;
1443                         if (!patch->old_name && !patch->new_name) {
1444                                 if (!patch->def_name)
1445                                         die("git diff header lacks filename information when removing "
1446                                             "%d leading pathname components (line %d)" , p_value, linenr);
1447                                 patch->old_name = xstrdup(patch->def_name);
1448                                 patch->new_name = xstrdup(patch->def_name);
1449                         }
1450                         if (!patch->is_delete && !patch->new_name)
1451                                 die("git diff header lacks filename information "
1452                                     "(line %d)", linenr);
1453                         patch->is_toplevel_relative = 1;
1454                         *hdrsize = git_hdr_len;
1455                         return offset;
1456                 }
1457
1458                 /* --- followed by +++ ? */
1459                 if (memcmp("--- ", line,  4) || memcmp("+++ ", line + len, 4))
1460                         continue;
1461
1462                 /*
1463                  * We only accept unified patches, so we want it to
1464                  * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1465                  * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1466                  */
1467                 nextlen = linelen(line + len, size - len);
1468                 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1469                         continue;
1470
1471                 /* Ok, we'll consider it a patch */
1472                 parse_traditional_patch(line, line+len, patch);
1473                 *hdrsize = len + nextlen;
1474                 linenr += 2;
1475                 return offset;
1476         }
1477         return -1;
1478 }
1479
1480 static void record_ws_error(unsigned result, const char *line, int len, int linenr)
1481 {
1482         char *err;
1483
1484         if (!result)
1485                 return;
1486
1487         whitespace_error++;
1488         if (squelch_whitespace_errors &&
1489             squelch_whitespace_errors < whitespace_error)
1490                 return;
1491
1492         err = whitespace_error_string(result);
1493         fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1494                 patch_input_file, linenr, err, len, line);
1495         free(err);
1496 }
1497
1498 static void check_whitespace(const char *line, int len, unsigned ws_rule)
1499 {
1500         unsigned result = ws_check(line + 1, len - 1, ws_rule);
1501
1502         record_ws_error(result, line + 1, len - 2, linenr);
1503 }
1504
1505 /*
1506  * Parse a unified diff. Note that this really needs to parse each
1507  * fragment separately, since the only way to know the difference
1508  * between a "---" that is part of a patch, and a "---" that starts
1509  * the next patch is to look at the line counts..
1510  */
1511 static int parse_fragment(char *line, unsigned long size,
1512                           struct patch *patch, struct fragment *fragment)
1513 {
1514         int added, deleted;
1515         int len = linelen(line, size), offset;
1516         unsigned long oldlines, newlines;
1517         unsigned long leading, trailing;
1518
1519         offset = parse_fragment_header(line, len, fragment);
1520         if (offset < 0)
1521                 return -1;
1522         if (offset > 0 && patch->recount)
1523                 recount_diff(line + offset, size - offset, fragment);
1524         oldlines = fragment->oldlines;
1525         newlines = fragment->newlines;
1526         leading = 0;
1527         trailing = 0;
1528
1529         /* Parse the thing.. */
1530         line += len;
1531         size -= len;
1532         linenr++;
1533         added = deleted = 0;
1534         for (offset = len;
1535              0 < size;
1536              offset += len, size -= len, line += len, linenr++) {
1537                 if (!oldlines && !newlines)
1538                         break;
1539                 len = linelen(line, size);
1540                 if (!len || line[len-1] != '\n')
1541                         return -1;
1542                 switch (*line) {
1543                 default:
1544                         return -1;
1545                 case '\n': /* newer GNU diff, an empty context line */
1546                 case ' ':
1547                         oldlines--;
1548                         newlines--;
1549                         if (!deleted && !added)
1550                                 leading++;
1551                         trailing++;
1552                         break;
1553                 case '-':
1554                         if (apply_in_reverse &&
1555                             ws_error_action != nowarn_ws_error)
1556                                 check_whitespace(line, len, patch->ws_rule);
1557                         deleted++;
1558                         oldlines--;
1559                         trailing = 0;
1560                         break;
1561                 case '+':
1562                         if (!apply_in_reverse &&
1563                             ws_error_action != nowarn_ws_error)
1564                                 check_whitespace(line, len, patch->ws_rule);
1565                         added++;
1566                         newlines--;
1567                         trailing = 0;
1568                         break;
1569
1570                 /*
1571                  * We allow "\ No newline at end of file". Depending
1572                  * on locale settings when the patch was produced we
1573                  * don't know what this line looks like. The only
1574                  * thing we do know is that it begins with "\ ".
1575                  * Checking for 12 is just for sanity check -- any
1576                  * l10n of "\ No newline..." is at least that long.
1577                  */
1578                 case '\\':
1579                         if (len < 12 || memcmp(line, "\\ ", 2))
1580                                 return -1;
1581                         break;
1582                 }
1583         }
1584         if (oldlines || newlines)
1585                 return -1;
1586         fragment->leading = leading;
1587         fragment->trailing = trailing;
1588
1589         /*
1590          * If a fragment ends with an incomplete line, we failed to include
1591          * it in the above loop because we hit oldlines == newlines == 0
1592          * before seeing it.
1593          */
1594         if (12 < size && !memcmp(line, "\\ ", 2))
1595                 offset += linelen(line, size);
1596
1597         patch->lines_added += added;
1598         patch->lines_deleted += deleted;
1599
1600         if (0 < patch->is_new && oldlines)
1601                 return error("new file depends on old contents");
1602         if (0 < patch->is_delete && newlines)
1603                 return error("deleted file still has contents");
1604         return offset;
1605 }
1606
1607 static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
1608 {
1609         unsigned long offset = 0;
1610         unsigned long oldlines = 0, newlines = 0, context = 0;
1611         struct fragment **fragp = &patch->fragments;
1612
1613         while (size > 4 && !memcmp(line, "@@ -", 4)) {
1614                 struct fragment *fragment;
1615                 int len;
1616
1617                 fragment = xcalloc(1, sizeof(*fragment));
1618                 fragment->linenr = linenr;
1619                 len = parse_fragment(line, size, patch, fragment);
1620                 if (len <= 0)
1621                         die("corrupt patch at line %d", linenr);
1622                 fragment->patch = line;
1623                 fragment->size = len;
1624                 oldlines += fragment->oldlines;
1625                 newlines += fragment->newlines;
1626                 context += fragment->leading + fragment->trailing;
1627
1628                 *fragp = fragment;
1629                 fragp = &fragment->next;
1630
1631                 offset += len;
1632                 line += len;
1633                 size -= len;
1634         }
1635
1636         /*
1637          * If something was removed (i.e. we have old-lines) it cannot
1638          * be creation, and if something was added it cannot be
1639          * deletion.  However, the reverse is not true; --unified=0
1640          * patches that only add are not necessarily creation even
1641          * though they do not have any old lines, and ones that only
1642          * delete are not necessarily deletion.
1643          *
1644          * Unfortunately, a real creation/deletion patch do _not_ have
1645          * any context line by definition, so we cannot safely tell it
1646          * apart with --unified=0 insanity.  At least if the patch has
1647          * more than one hunk it is not creation or deletion.
1648          */
1649         if (patch->is_new < 0 &&
1650             (oldlines || (patch->fragments && patch->fragments->next)))
1651                 patch->is_new = 0;
1652         if (patch->is_delete < 0 &&
1653             (newlines || (patch->fragments && patch->fragments->next)))
1654                 patch->is_delete = 0;
1655
1656         if (0 < patch->is_new && oldlines)
1657                 die("new file %s depends on old contents", patch->new_name);
1658         if (0 < patch->is_delete && newlines)
1659                 die("deleted file %s still has contents", patch->old_name);
1660         if (!patch->is_delete && !newlines && context)
1661                 fprintf(stderr, "** warning: file %s becomes empty but "
1662                         "is not deleted\n", patch->new_name);
1663
1664         return offset;
1665 }
1666
1667 static inline int metadata_changes(struct patch *patch)
1668 {
1669         return  patch->is_rename > 0 ||
1670                 patch->is_copy > 0 ||
1671                 patch->is_new > 0 ||
1672                 patch->is_delete ||
1673                 (patch->old_mode && patch->new_mode &&
1674                  patch->old_mode != patch->new_mode);
1675 }
1676
1677 static char *inflate_it(const void *data, unsigned long size,
1678                         unsigned long inflated_size)
1679 {
1680         git_zstream stream;
1681         void *out;
1682         int st;
1683
1684         memset(&stream, 0, sizeof(stream));
1685
1686         stream.next_in = (unsigned char *)data;
1687         stream.avail_in = size;
1688         stream.next_out = out = xmalloc(inflated_size);
1689         stream.avail_out = inflated_size;
1690         git_inflate_init(&stream);
1691         st = git_inflate(&stream, Z_FINISH);
1692         git_inflate_end(&stream);
1693         if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1694                 free(out);
1695                 return NULL;
1696         }
1697         return out;
1698 }
1699
1700 static struct fragment *parse_binary_hunk(char **buf_p,
1701                                           unsigned long *sz_p,
1702                                           int *status_p,
1703                                           int *used_p)
1704 {
1705         /*
1706          * Expect a line that begins with binary patch method ("literal"
1707          * or "delta"), followed by the length of data before deflating.
1708          * a sequence of 'length-byte' followed by base-85 encoded data
1709          * should follow, terminated by a newline.
1710          *
1711          * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1712          * and we would limit the patch line to 66 characters,
1713          * so one line can fit up to 13 groups that would decode
1714          * to 52 bytes max.  The length byte 'A'-'Z' corresponds
1715          * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1716          */
1717         int llen, used;
1718         unsigned long size = *sz_p;
1719         char *buffer = *buf_p;
1720         int patch_method;
1721         unsigned long origlen;
1722         char *data = NULL;
1723         int hunk_size = 0;
1724         struct fragment *frag;
1725
1726         llen = linelen(buffer, size);
1727         used = llen;
1728
1729         *status_p = 0;
1730
1731         if (!prefixcmp(buffer, "delta ")) {
1732                 patch_method = BINARY_DELTA_DEFLATED;
1733                 origlen = strtoul(buffer + 6, NULL, 10);
1734         }
1735         else if (!prefixcmp(buffer, "literal ")) {
1736                 patch_method = BINARY_LITERAL_DEFLATED;
1737                 origlen = strtoul(buffer + 8, NULL, 10);
1738         }
1739         else
1740                 return NULL;
1741
1742         linenr++;
1743         buffer += llen;
1744         while (1) {
1745                 int byte_length, max_byte_length, newsize;
1746                 llen = linelen(buffer, size);
1747                 used += llen;
1748                 linenr++;
1749                 if (llen == 1) {
1750                         /* consume the blank line */
1751                         buffer++;
1752                         size--;
1753                         break;
1754                 }
1755                 /*
1756                  * Minimum line is "A00000\n" which is 7-byte long,
1757                  * and the line length must be multiple of 5 plus 2.
1758                  */
1759                 if ((llen < 7) || (llen-2) % 5)
1760                         goto corrupt;
1761                 max_byte_length = (llen - 2) / 5 * 4;
1762                 byte_length = *buffer;
1763                 if ('A' <= byte_length && byte_length <= 'Z')
1764                         byte_length = byte_length - 'A' + 1;
1765                 else if ('a' <= byte_length && byte_length <= 'z')
1766                         byte_length = byte_length - 'a' + 27;
1767                 else
1768                         goto corrupt;
1769                 /* if the input length was not multiple of 4, we would
1770                  * have filler at the end but the filler should never
1771                  * exceed 3 bytes
1772                  */
1773                 if (max_byte_length < byte_length ||
1774                     byte_length <= max_byte_length - 4)
1775                         goto corrupt;
1776                 newsize = hunk_size + byte_length;
1777                 data = xrealloc(data, newsize);
1778                 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1779                         goto corrupt;
1780                 hunk_size = newsize;
1781                 buffer += llen;
1782                 size -= llen;
1783         }
1784
1785         frag = xcalloc(1, sizeof(*frag));
1786         frag->patch = inflate_it(data, hunk_size, origlen);
1787         frag->free_patch = 1;
1788         if (!frag->patch)
1789                 goto corrupt;
1790         free(data);
1791         frag->size = origlen;
1792         *buf_p = buffer;
1793         *sz_p = size;
1794         *used_p = used;
1795         frag->binary_patch_method = patch_method;
1796         return frag;
1797
1798  corrupt:
1799         free(data);
1800         *status_p = -1;
1801         error("corrupt binary patch at line %d: %.*s",
1802               linenr-1, llen-1, buffer);
1803         return NULL;
1804 }
1805
1806 static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1807 {
1808         /*
1809          * We have read "GIT binary patch\n"; what follows is a line
1810          * that says the patch method (currently, either "literal" or
1811          * "delta") and the length of data before deflating; a
1812          * sequence of 'length-byte' followed by base-85 encoded data
1813          * follows.
1814          *
1815          * When a binary patch is reversible, there is another binary
1816          * hunk in the same format, starting with patch method (either
1817          * "literal" or "delta") with the length of data, and a sequence
1818          * of length-byte + base-85 encoded data, terminated with another
1819          * empty line.  This data, when applied to the postimage, produces
1820          * the preimage.
1821          */
1822         struct fragment *forward;
1823         struct fragment *reverse;
1824         int status;
1825         int used, used_1;
1826
1827         forward = parse_binary_hunk(&buffer, &size, &status, &used);
1828         if (!forward && !status)
1829                 /* there has to be one hunk (forward hunk) */
1830                 return error("unrecognized binary patch at line %d", linenr-1);
1831         if (status)
1832                 /* otherwise we already gave an error message */
1833                 return status;
1834
1835         reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1836         if (reverse)
1837                 used += used_1;
1838         else if (status) {
1839                 /*
1840                  * Not having reverse hunk is not an error, but having
1841                  * a corrupt reverse hunk is.
1842                  */
1843                 free((void*) forward->patch);
1844                 free(forward);
1845                 return status;
1846         }
1847         forward->next = reverse;
1848         patch->fragments = forward;
1849         patch->is_binary = 1;
1850         return used;
1851 }
1852
1853 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
1854 {
1855         int hdrsize, patchsize;
1856         int offset = find_header(buffer, size, &hdrsize, patch);
1857
1858         if (offset < 0)
1859                 return offset;
1860
1861         patch->ws_rule = whitespace_rule(patch->new_name
1862                                          ? patch->new_name
1863                                          : patch->old_name);
1864
1865         patchsize = parse_single_patch(buffer + offset + hdrsize,
1866                                        size - offset - hdrsize, patch);
1867
1868         if (!patchsize) {
1869                 static const char *binhdr[] = {
1870                         "Binary files ",
1871                         "Files ",
1872                         NULL,
1873                 };
1874                 static const char git_binary[] = "GIT binary patch\n";
1875                 int i;
1876                 int hd = hdrsize + offset;
1877                 unsigned long llen = linelen(buffer + hd, size - hd);
1878
1879                 if (llen == sizeof(git_binary) - 1 &&
1880                     !memcmp(git_binary, buffer + hd, llen)) {
1881                         int used;
1882                         linenr++;
1883                         used = parse_binary(buffer + hd + llen,
1884                                             size - hd - llen, patch);
1885                         if (used)
1886                                 patchsize = used + llen;
1887                         else
1888                                 patchsize = 0;
1889                 }
1890                 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
1891                         for (i = 0; binhdr[i]; i++) {
1892                                 int len = strlen(binhdr[i]);
1893                                 if (len < size - hd &&
1894                                     !memcmp(binhdr[i], buffer + hd, len)) {
1895                                         linenr++;
1896                                         patch->is_binary = 1;
1897                                         patchsize = llen;
1898                                         break;
1899                                 }
1900                         }
1901                 }
1902
1903                 /* Empty patch cannot be applied if it is a text patch
1904                  * without metadata change.  A binary patch appears
1905                  * empty to us here.
1906                  */
1907                 if ((apply || check) &&
1908                     (!patch->is_binary && !metadata_changes(patch)))
1909                         die("patch with only garbage at line %d", linenr);
1910         }
1911
1912         return offset + hdrsize + patchsize;
1913 }
1914
1915 #define swap(a,b) myswap((a),(b),sizeof(a))
1916
1917 #define myswap(a, b, size) do {         \
1918         unsigned char mytmp[size];      \
1919         memcpy(mytmp, &a, size);                \
1920         memcpy(&a, &b, size);           \
1921         memcpy(&b, mytmp, size);                \
1922 } while (0)
1923
1924 static void reverse_patches(struct patch *p)
1925 {
1926         for (; p; p = p->next) {
1927                 struct fragment *frag = p->fragments;
1928
1929                 swap(p->new_name, p->old_name);
1930                 swap(p->new_mode, p->old_mode);
1931                 swap(p->is_new, p->is_delete);
1932                 swap(p->lines_added, p->lines_deleted);
1933                 swap(p->old_sha1_prefix, p->new_sha1_prefix);
1934
1935                 for (; frag; frag = frag->next) {
1936                         swap(frag->newpos, frag->oldpos);
1937                         swap(frag->newlines, frag->oldlines);
1938                 }
1939         }
1940 }
1941
1942 static const char pluses[] =
1943 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1944 static const char minuses[]=
1945 "----------------------------------------------------------------------";
1946
1947 static void show_stats(struct patch *patch)
1948 {
1949         struct strbuf qname = STRBUF_INIT;
1950         char *cp = patch->new_name ? patch->new_name : patch->old_name;
1951         int max, add, del;
1952
1953         quote_c_style(cp, &qname, NULL, 0);
1954
1955         /*
1956          * "scale" the filename
1957          */
1958         max = max_len;
1959         if (max > 50)
1960                 max = 50;
1961
1962         if (qname.len > max) {
1963                 cp = strchr(qname.buf + qname.len + 3 - max, '/');
1964                 if (!cp)
1965                         cp = qname.buf + qname.len + 3 - max;
1966                 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
1967         }
1968
1969         if (patch->is_binary) {
1970                 printf(" %-*s |  Bin\n", max, qname.buf);
1971                 strbuf_release(&qname);
1972                 return;
1973         }
1974
1975         printf(" %-*s |", max, qname.buf);
1976         strbuf_release(&qname);
1977
1978         /*
1979          * scale the add/delete
1980          */
1981         max = max + max_change > 70 ? 70 - max : max_change;
1982         add = patch->lines_added;
1983         del = patch->lines_deleted;
1984
1985         if (max_change > 0) {
1986                 int total = ((add + del) * max + max_change / 2) / max_change;
1987                 add = (add * max + max_change / 2) / max_change;
1988                 del = total - add;
1989         }
1990         printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
1991                 add, pluses, del, minuses);
1992 }
1993
1994 static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
1995 {
1996         switch (st->st_mode & S_IFMT) {
1997         case S_IFLNK:
1998                 if (strbuf_readlink(buf, path, st->st_size) < 0)
1999                         return error("unable to read symlink %s", path);
2000                 return 0;
2001         case S_IFREG:
2002                 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
2003                         return error("unable to open or read %s", path);
2004                 convert_to_git(path, buf->buf, buf->len, buf, 0);
2005                 return 0;
2006         default:
2007                 return -1;
2008         }
2009 }
2010
2011 /*
2012  * Update the preimage, and the common lines in postimage,
2013  * from buffer buf of length len. If postlen is 0 the postimage
2014  * is updated in place, otherwise it's updated on a new buffer
2015  * of length postlen
2016  */
2017
2018 static void update_pre_post_images(struct image *preimage,
2019                                    struct image *postimage,
2020                                    char *buf,
2021                                    size_t len, size_t postlen)
2022 {
2023         int i, ctx;
2024         char *new, *old, *fixed;
2025         struct image fixed_preimage;
2026
2027         /*
2028          * Update the preimage with whitespace fixes.  Note that we
2029          * are not losing preimage->buf -- apply_one_fragment() will
2030          * free "oldlines".
2031          */
2032         prepare_image(&fixed_preimage, buf, len, 1);
2033         assert(fixed_preimage.nr == preimage->nr);
2034         for (i = 0; i < preimage->nr; i++)
2035                 fixed_preimage.line[i].flag = preimage->line[i].flag;
2036         free(preimage->line_allocated);
2037         *preimage = fixed_preimage;
2038
2039         /*
2040          * Adjust the common context lines in postimage. This can be
2041          * done in-place when we are just doing whitespace fixing,
2042          * which does not make the string grow, but needs a new buffer
2043          * when ignoring whitespace causes the update, since in this case
2044          * we could have e.g. tabs converted to multiple spaces.
2045          * We trust the caller to tell us if the update can be done
2046          * in place (postlen==0) or not.
2047          */
2048         old = postimage->buf;
2049         if (postlen)
2050                 new = postimage->buf = xmalloc(postlen);
2051         else
2052                 new = old;
2053         fixed = preimage->buf;
2054         for (i = ctx = 0; i < postimage->nr; i++) {
2055                 size_t len = postimage->line[i].len;
2056                 if (!(postimage->line[i].flag & LINE_COMMON)) {
2057                         /* an added line -- no counterparts in preimage */
2058                         memmove(new, old, len);
2059                         old += len;
2060                         new += len;
2061                         continue;
2062                 }
2063
2064                 /* a common context -- skip it in the original postimage */
2065                 old += len;
2066
2067                 /* and find the corresponding one in the fixed preimage */
2068                 while (ctx < preimage->nr &&
2069                        !(preimage->line[ctx].flag & LINE_COMMON)) {
2070                         fixed += preimage->line[ctx].len;
2071                         ctx++;
2072                 }
2073                 if (preimage->nr <= ctx)
2074                         die("oops");
2075
2076                 /* and copy it in, while fixing the line length */
2077                 len = preimage->line[ctx].len;
2078                 memcpy(new, fixed, len);
2079                 new += len;
2080                 fixed += len;
2081                 postimage->line[i].len = len;
2082                 ctx++;
2083         }
2084
2085         /* Fix the length of the whole thing */
2086         postimage->len = new - postimage->buf;
2087 }
2088
2089 static int match_fragment(struct image *img,
2090                           struct image *preimage,
2091                           struct image *postimage,
2092                           unsigned long try,
2093                           int try_lno,
2094                           unsigned ws_rule,
2095                           int match_beginning, int match_end)
2096 {
2097         int i;
2098         char *fixed_buf, *buf, *orig, *target;
2099         struct strbuf fixed;
2100         size_t fixed_len;
2101         int preimage_limit;
2102
2103         if (preimage->nr + try_lno <= img->nr) {
2104                 /*
2105                  * The hunk falls within the boundaries of img.
2106                  */
2107                 preimage_limit = preimage->nr;
2108                 if (match_end && (preimage->nr + try_lno != img->nr))
2109                         return 0;
2110         } else if (ws_error_action == correct_ws_error &&
2111                    (ws_rule & WS_BLANK_AT_EOF)) {
2112                 /*
2113                  * This hunk extends beyond the end of img, and we are
2114                  * removing blank lines at the end of the file.  This
2115                  * many lines from the beginning of the preimage must
2116                  * match with img, and the remainder of the preimage
2117                  * must be blank.
2118                  */
2119                 preimage_limit = img->nr - try_lno;
2120         } else {
2121                 /*
2122                  * The hunk extends beyond the end of the img and
2123                  * we are not removing blanks at the end, so we
2124                  * should reject the hunk at this position.
2125                  */
2126                 return 0;
2127         }
2128
2129         if (match_beginning && try_lno)
2130                 return 0;
2131
2132         /* Quick hash check */
2133         for (i = 0; i < preimage_limit; i++)
2134                 if ((img->line[try_lno + i].flag & LINE_PATCHED) ||
2135                     (preimage->line[i].hash != img->line[try_lno + i].hash))
2136                         return 0;
2137
2138         if (preimage_limit == preimage->nr) {
2139                 /*
2140                  * Do we have an exact match?  If we were told to match
2141                  * at the end, size must be exactly at try+fragsize,
2142                  * otherwise try+fragsize must be still within the preimage,
2143                  * and either case, the old piece should match the preimage
2144                  * exactly.
2145                  */
2146                 if ((match_end
2147                      ? (try + preimage->len == img->len)
2148                      : (try + preimage->len <= img->len)) &&
2149                     !memcmp(img->buf + try, preimage->buf, preimage->len))
2150                         return 1;
2151         } else {
2152                 /*
2153                  * The preimage extends beyond the end of img, so
2154                  * there cannot be an exact match.
2155                  *
2156                  * There must be one non-blank context line that match
2157                  * a line before the end of img.
2158                  */
2159                 char *buf_end;
2160
2161                 buf = preimage->buf;
2162                 buf_end = buf;
2163                 for (i = 0; i < preimage_limit; i++)
2164                         buf_end += preimage->line[i].len;
2165
2166                 for ( ; buf < buf_end; buf++)
2167                         if (!isspace(*buf))
2168                                 break;
2169                 if (buf == buf_end)
2170                         return 0;
2171         }
2172
2173         /*
2174          * No exact match. If we are ignoring whitespace, run a line-by-line
2175          * fuzzy matching. We collect all the line length information because
2176          * we need it to adjust whitespace if we match.
2177          */
2178         if (ws_ignore_action == ignore_ws_change) {
2179                 size_t imgoff = 0;
2180                 size_t preoff = 0;
2181                 size_t postlen = postimage->len;
2182                 size_t extra_chars;
2183                 char *preimage_eof;
2184                 char *preimage_end;
2185                 for (i = 0; i < preimage_limit; i++) {
2186                         size_t prelen = preimage->line[i].len;
2187                         size_t imglen = img->line[try_lno+i].len;
2188
2189                         if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,
2190                                               preimage->buf + preoff, prelen))
2191                                 return 0;
2192                         if (preimage->line[i].flag & LINE_COMMON)
2193                                 postlen += imglen - prelen;
2194                         imgoff += imglen;
2195                         preoff += prelen;
2196                 }
2197
2198                 /*
2199                  * Ok, the preimage matches with whitespace fuzz.
2200                  *
2201                  * imgoff now holds the true length of the target that
2202                  * matches the preimage before the end of the file.
2203                  *
2204                  * Count the number of characters in the preimage that fall
2205                  * beyond the end of the file and make sure that all of them
2206                  * are whitespace characters. (This can only happen if
2207                  * we are removing blank lines at the end of the file.)
2208                  */
2209                 buf = preimage_eof = preimage->buf + preoff;
2210                 for ( ; i < preimage->nr; i++)
2211                         preoff += preimage->line[i].len;
2212                 preimage_end = preimage->buf + preoff;
2213                 for ( ; buf < preimage_end; buf++)
2214                         if (!isspace(*buf))
2215                                 return 0;
2216
2217                 /*
2218                  * Update the preimage and the common postimage context
2219                  * lines to use the same whitespace as the target.
2220                  * If whitespace is missing in the target (i.e.
2221                  * if the preimage extends beyond the end of the file),
2222                  * use the whitespace from the preimage.
2223                  */
2224                 extra_chars = preimage_end - preimage_eof;
2225                 strbuf_init(&fixed, imgoff + extra_chars);
2226                 strbuf_add(&fixed, img->buf + try, imgoff);
2227                 strbuf_add(&fixed, preimage_eof, extra_chars);
2228                 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2229                 update_pre_post_images(preimage, postimage,
2230                                 fixed_buf, fixed_len, postlen);
2231                 return 1;
2232         }
2233
2234         if (ws_error_action != correct_ws_error)
2235                 return 0;
2236
2237         /*
2238          * The hunk does not apply byte-by-byte, but the hash says
2239          * it might with whitespace fuzz. We haven't been asked to
2240          * ignore whitespace, we were asked to correct whitespace
2241          * errors, so let's try matching after whitespace correction.
2242          *
2243          * The preimage may extend beyond the end of the file,
2244          * but in this loop we will only handle the part of the
2245          * preimage that falls within the file.
2246          */
2247         strbuf_init(&fixed, preimage->len + 1);
2248         orig = preimage->buf;
2249         target = img->buf + try;
2250         for (i = 0; i < preimage_limit; i++) {
2251                 size_t oldlen = preimage->line[i].len;
2252                 size_t tgtlen = img->line[try_lno + i].len;
2253                 size_t fixstart = fixed.len;
2254                 struct strbuf tgtfix;
2255                 int match;
2256
2257                 /* Try fixing the line in the preimage */
2258                 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2259
2260                 /* Try fixing the line in the target */
2261                 strbuf_init(&tgtfix, tgtlen);
2262                 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2263
2264                 /*
2265                  * If they match, either the preimage was based on
2266                  * a version before our tree fixed whitespace breakage,
2267                  * or we are lacking a whitespace-fix patch the tree
2268                  * the preimage was based on already had (i.e. target
2269                  * has whitespace breakage, the preimage doesn't).
2270                  * In either case, we are fixing the whitespace breakages
2271                  * so we might as well take the fix together with their
2272                  * real change.
2273                  */
2274                 match = (tgtfix.len == fixed.len - fixstart &&
2275                          !memcmp(tgtfix.buf, fixed.buf + fixstart,
2276                                              fixed.len - fixstart));
2277
2278                 strbuf_release(&tgtfix);
2279                 if (!match)
2280                         goto unmatch_exit;
2281
2282                 orig += oldlen;
2283                 target += tgtlen;
2284         }
2285
2286
2287         /*
2288          * Now handle the lines in the preimage that falls beyond the
2289          * end of the file (if any). They will only match if they are
2290          * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2291          * false).
2292          */
2293         for ( ; i < preimage->nr; i++) {
2294                 size_t fixstart = fixed.len; /* start of the fixed preimage */
2295                 size_t oldlen = preimage->line[i].len;
2296                 int j;
2297
2298                 /* Try fixing the line in the preimage */
2299                 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2300
2301                 for (j = fixstart; j < fixed.len; j++)
2302                         if (!isspace(fixed.buf[j]))
2303                                 goto unmatch_exit;
2304
2305                 orig += oldlen;
2306         }
2307
2308         /*
2309          * Yes, the preimage is based on an older version that still
2310          * has whitespace breakages unfixed, and fixing them makes the
2311          * hunk match.  Update the context lines in the postimage.
2312          */
2313         fixed_buf = strbuf_detach(&fixed, &fixed_len);
2314         update_pre_post_images(preimage, postimage,
2315                                fixed_buf, fixed_len, 0);
2316         return 1;
2317
2318  unmatch_exit:
2319         strbuf_release(&fixed);
2320         return 0;
2321 }
2322
2323 static int find_pos(struct image *img,
2324                     struct image *preimage,
2325                     struct image *postimage,
2326                     int line,
2327                     unsigned ws_rule,
2328                     int match_beginning, int match_end)
2329 {
2330         int i;
2331         unsigned long backwards, forwards, try;
2332         int backwards_lno, forwards_lno, try_lno;
2333
2334         /*
2335          * If match_beginning or match_end is specified, there is no
2336          * point starting from a wrong line that will never match and
2337          * wander around and wait for a match at the specified end.
2338          */
2339         if (match_beginning)
2340                 line = 0;
2341         else if (match_end)
2342                 line = img->nr - preimage->nr;
2343
2344         /*
2345          * Because the comparison is unsigned, the following test
2346          * will also take care of a negative line number that can
2347          * result when match_end and preimage is larger than the target.
2348          */
2349         if ((size_t) line > img->nr)
2350                 line = img->nr;
2351
2352         try = 0;
2353         for (i = 0; i < line; i++)
2354                 try += img->line[i].len;
2355
2356         /*
2357          * There's probably some smart way to do this, but I'll leave
2358          * that to the smart and beautiful people. I'm simple and stupid.
2359          */
2360         backwards = try;
2361         backwards_lno = line;
2362         forwards = try;
2363         forwards_lno = line;
2364         try_lno = line;
2365
2366         for (i = 0; ; i++) {
2367                 if (match_fragment(img, preimage, postimage,
2368                                    try, try_lno, ws_rule,
2369                                    match_beginning, match_end))
2370                         return try_lno;
2371
2372         again:
2373                 if (backwards_lno == 0 && forwards_lno == img->nr)
2374                         break;
2375
2376                 if (i & 1) {
2377                         if (backwards_lno == 0) {
2378                                 i++;
2379                                 goto again;
2380                         }
2381                         backwards_lno--;
2382                         backwards -= img->line[backwards_lno].len;
2383                         try = backwards;
2384                         try_lno = backwards_lno;
2385                 } else {
2386                         if (forwards_lno == img->nr) {
2387                                 i++;
2388                                 goto again;
2389                         }
2390                         forwards += img->line[forwards_lno].len;
2391                         forwards_lno++;
2392                         try = forwards;
2393                         try_lno = forwards_lno;
2394                 }
2395
2396         }
2397         return -1;
2398 }
2399
2400 static void remove_first_line(struct image *img)
2401 {
2402         img->buf += img->line[0].len;
2403         img->len -= img->line[0].len;
2404         img->line++;
2405         img->nr--;
2406 }
2407
2408 static void remove_last_line(struct image *img)
2409 {
2410         img->len -= img->line[--img->nr].len;
2411 }
2412
2413 static void update_image(struct image *img,
2414                          int applied_pos,
2415                          struct image *preimage,
2416                          struct image *postimage)
2417 {
2418         /*
2419          * remove the copy of preimage at offset in img
2420          * and replace it with postimage
2421          */
2422         int i, nr;
2423         size_t remove_count, insert_count, applied_at = 0;
2424         char *result;
2425         int preimage_limit;
2426
2427         /*
2428          * If we are removing blank lines at the end of img,
2429          * the preimage may extend beyond the end.
2430          * If that is the case, we must be careful only to
2431          * remove the part of the preimage that falls within
2432          * the boundaries of img. Initialize preimage_limit
2433          * to the number of lines in the preimage that falls
2434          * within the boundaries.
2435          */
2436         preimage_limit = preimage->nr;
2437         if (preimage_limit > img->nr - applied_pos)
2438                 preimage_limit = img->nr - applied_pos;
2439
2440         for (i = 0; i < applied_pos; i++)
2441                 applied_at += img->line[i].len;
2442
2443         remove_count = 0;
2444         for (i = 0; i < preimage_limit; i++)
2445                 remove_count += img->line[applied_pos + i].len;
2446         insert_count = postimage->len;
2447
2448         /* Adjust the contents */
2449         result = xmalloc(img->len + insert_count - remove_count + 1);
2450         memcpy(result, img->buf, applied_at);
2451         memcpy(result + applied_at, postimage->buf, postimage->len);
2452         memcpy(result + applied_at + postimage->len,
2453                img->buf + (applied_at + remove_count),
2454                img->len - (applied_at + remove_count));
2455         free(img->buf);
2456         img->buf = result;
2457         img->len += insert_count - remove_count;
2458         result[img->len] = '\0';
2459
2460         /* Adjust the line table */
2461         nr = img->nr + postimage->nr - preimage_limit;
2462         if (preimage_limit < postimage->nr) {
2463                 /*
2464                  * NOTE: this knows that we never call remove_first_line()
2465                  * on anything other than pre/post image.
2466                  */
2467                 img->line = xrealloc(img->line, nr * sizeof(*img->line));
2468                 img->line_allocated = img->line;
2469         }
2470         if (preimage_limit != postimage->nr)
2471                 memmove(img->line + applied_pos + postimage->nr,
2472                         img->line + applied_pos + preimage_limit,
2473                         (img->nr - (applied_pos + preimage_limit)) *
2474                         sizeof(*img->line));
2475         memcpy(img->line + applied_pos,
2476                postimage->line,
2477                postimage->nr * sizeof(*img->line));
2478         if (!allow_overlap)
2479                 for (i = 0; i < postimage->nr; i++)
2480                         img->line[applied_pos + i].flag |= LINE_PATCHED;
2481         img->nr = nr;
2482 }
2483
2484 static int apply_one_fragment(struct image *img, struct fragment *frag,
2485                               int inaccurate_eof, unsigned ws_rule,
2486                               int nth_fragment)
2487 {
2488         int match_beginning, match_end;
2489         const char *patch = frag->patch;
2490         int size = frag->size;
2491         char *old, *oldlines;
2492         struct strbuf newlines;
2493         int new_blank_lines_at_end = 0;
2494         int found_new_blank_lines_at_end = 0;
2495         int hunk_linenr = frag->linenr;
2496         unsigned long leading, trailing;
2497         int pos, applied_pos;
2498         struct image preimage;
2499         struct image postimage;
2500
2501         memset(&preimage, 0, sizeof(preimage));
2502         memset(&postimage, 0, sizeof(postimage));
2503         oldlines = xmalloc(size);
2504         strbuf_init(&newlines, size);
2505
2506         old = oldlines;
2507         while (size > 0) {
2508                 char first;
2509                 int len = linelen(patch, size);
2510                 int plen;
2511                 int added_blank_line = 0;
2512                 int is_blank_context = 0;
2513                 size_t start;
2514
2515                 if (!len)
2516                         break;
2517
2518                 /*
2519                  * "plen" is how much of the line we should use for
2520                  * the actual patch data. Normally we just remove the
2521                  * first character on the line, but if the line is
2522                  * followed by "\ No newline", then we also remove the
2523                  * last one (which is the newline, of course).
2524                  */
2525                 plen = len - 1;
2526                 if (len < size && patch[len] == '\\')
2527                         plen--;
2528                 first = *patch;
2529                 if (apply_in_reverse) {
2530                         if (first == '-')
2531                                 first = '+';
2532                         else if (first == '+')
2533                                 first = '-';
2534                 }
2535
2536                 switch (first) {
2537                 case '\n':
2538                         /* Newer GNU diff, empty context line */
2539                         if (plen < 0)
2540                                 /* ... followed by '\No newline'; nothing */
2541                                 break;
2542                         *old++ = '\n';
2543                         strbuf_addch(&newlines, '\n');
2544                         add_line_info(&preimage, "\n", 1, LINE_COMMON);
2545                         add_line_info(&postimage, "\n", 1, LINE_COMMON);
2546                         is_blank_context = 1;
2547                         break;
2548                 case ' ':
2549                         if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2550                             ws_blank_line(patch + 1, plen, ws_rule))
2551                                 is_blank_context = 1;
2552                 case '-':
2553                         memcpy(old, patch + 1, plen);
2554                         add_line_info(&preimage, old, plen,
2555                                       (first == ' ' ? LINE_COMMON : 0));
2556                         old += plen;
2557                         if (first == '-')
2558                                 break;
2559                 /* Fall-through for ' ' */
2560                 case '+':
2561                         /* --no-add does not add new lines */
2562                         if (first == '+' && no_add)
2563                                 break;
2564
2565                         start = newlines.len;
2566                         if (first != '+' ||
2567                             !whitespace_error ||
2568                             ws_error_action != correct_ws_error) {
2569                                 strbuf_add(&newlines, patch + 1, plen);
2570                         }
2571                         else {
2572                                 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &applied_after_fixing_ws);
2573                         }
2574                         add_line_info(&postimage, newlines.buf + start, newlines.len - start,
2575                                       (first == '+' ? 0 : LINE_COMMON));
2576                         if (first == '+' &&
2577                             (ws_rule & WS_BLANK_AT_EOF) &&
2578                             ws_blank_line(patch + 1, plen, ws_rule))
2579                                 added_blank_line = 1;
2580                         break;
2581                 case '@': case '\\':
2582                         /* Ignore it, we already handled it */
2583                         break;
2584                 default:
2585                         if (apply_verbosely)
2586                                 error("invalid start of line: '%c'", first);
2587                         return -1;
2588                 }
2589                 if (added_blank_line) {
2590                         if (!new_blank_lines_at_end)
2591                                 found_new_blank_lines_at_end = hunk_linenr;
2592                         new_blank_lines_at_end++;
2593                 }
2594                 else if (is_blank_context)
2595                         ;
2596                 else
2597                         new_blank_lines_at_end = 0;
2598                 patch += len;
2599                 size -= len;
2600                 hunk_linenr++;
2601         }
2602         if (inaccurate_eof &&
2603             old > oldlines && old[-1] == '\n' &&
2604             newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
2605                 old--;
2606                 strbuf_setlen(&newlines, newlines.len - 1);
2607         }
2608
2609         leading = frag->leading;
2610         trailing = frag->trailing;
2611
2612         /*
2613          * A hunk to change lines at the beginning would begin with
2614          * @@ -1,L +N,M @@
2615          * but we need to be careful.  -U0 that inserts before the second
2616          * line also has this pattern.
2617          *
2618          * And a hunk to add to an empty file would begin with
2619          * @@ -0,0 +N,M @@
2620          *
2621          * In other words, a hunk that is (frag->oldpos <= 1) with or
2622          * without leading context must match at the beginning.
2623          */
2624         match_beginning = (!frag->oldpos ||
2625                            (frag->oldpos == 1 && !unidiff_zero));
2626
2627         /*
2628          * A hunk without trailing lines must match at the end.
2629          * However, we simply cannot tell if a hunk must match end
2630          * from the lack of trailing lines if the patch was generated
2631          * with unidiff without any context.
2632          */
2633         match_end = !unidiff_zero && !trailing;
2634
2635         pos = frag->newpos ? (frag->newpos - 1) : 0;
2636         preimage.buf = oldlines;
2637         preimage.len = old - oldlines;
2638         postimage.buf = newlines.buf;
2639         postimage.len = newlines.len;
2640         preimage.line = preimage.line_allocated;
2641         postimage.line = postimage.line_allocated;
2642
2643         for (;;) {
2644
2645                 applied_pos = find_pos(img, &preimage, &postimage, pos,
2646                                        ws_rule, match_beginning, match_end);
2647
2648                 if (applied_pos >= 0)
2649                         break;
2650
2651                 /* Am I at my context limits? */
2652                 if ((leading <= p_context) && (trailing <= p_context))
2653                         break;
2654                 if (match_beginning || match_end) {
2655                         match_beginning = match_end = 0;
2656                         continue;
2657                 }
2658
2659                 /*
2660                  * Reduce the number of context lines; reduce both
2661                  * leading and trailing if they are equal otherwise
2662                  * just reduce the larger context.
2663                  */
2664                 if (leading >= trailing) {
2665                         remove_first_line(&preimage);
2666                         remove_first_line(&postimage);
2667                         pos--;
2668                         leading--;
2669                 }
2670                 if (trailing > leading) {
2671                         remove_last_line(&preimage);
2672                         remove_last_line(&postimage);
2673                         trailing--;
2674                 }
2675         }
2676
2677         if (applied_pos >= 0) {
2678                 if (new_blank_lines_at_end &&
2679                     preimage.nr + applied_pos >= img->nr &&
2680                     (ws_rule & WS_BLANK_AT_EOF) &&
2681                     ws_error_action != nowarn_ws_error) {
2682                         record_ws_error(WS_BLANK_AT_EOF, "+", 1,
2683                                         found_new_blank_lines_at_end);
2684                         if (ws_error_action == correct_ws_error) {
2685                                 while (new_blank_lines_at_end--)
2686                                         remove_last_line(&postimage);
2687                         }
2688                         /*
2689                          * We would want to prevent write_out_results()
2690                          * from taking place in apply_patch() that follows
2691                          * the callchain led us here, which is:
2692                          * apply_patch->check_patch_list->check_patch->
2693                          * apply_data->apply_fragments->apply_one_fragment
2694                          */
2695                         if (ws_error_action == die_on_ws_error)
2696                                 apply = 0;
2697                 }
2698
2699                 if (apply_verbosely && applied_pos != pos) {
2700                         int offset = applied_pos - pos;
2701                         if (apply_in_reverse)
2702                                 offset = 0 - offset;
2703                         fprintf(stderr,
2704                                 "Hunk #%d succeeded at %d (offset %d lines).\n",
2705                                 nth_fragment, applied_pos + 1, offset);
2706                 }
2707
2708                 /*
2709                  * Warn if it was necessary to reduce the number
2710                  * of context lines.
2711                  */
2712                 if ((leading != frag->leading) ||
2713                     (trailing != frag->trailing))
2714                         fprintf(stderr, "Context reduced to (%ld/%ld)"
2715                                 " to apply fragment at %d\n",
2716                                 leading, trailing, applied_pos+1);
2717                 update_image(img, applied_pos, &preimage, &postimage);
2718         } else {
2719                 if (apply_verbosely)
2720                         error("while searching for:\n%.*s",
2721                               (int)(old - oldlines), oldlines);
2722         }
2723
2724         free(oldlines);
2725         strbuf_release(&newlines);
2726         free(preimage.line_allocated);
2727         free(postimage.line_allocated);
2728
2729         return (applied_pos < 0);
2730 }
2731
2732 static int apply_binary_fragment(struct image *img, struct patch *patch)
2733 {
2734         struct fragment *fragment = patch->fragments;
2735         unsigned long len;
2736         void *dst;
2737
2738         if (!fragment)
2739                 return error("missing binary patch data for '%s'",
2740                              patch->new_name ?
2741                              patch->new_name :
2742                              patch->old_name);
2743
2744         /* Binary patch is irreversible without the optional second hunk */
2745         if (apply_in_reverse) {
2746                 if (!fragment->next)
2747                         return error("cannot reverse-apply a binary patch "
2748                                      "without the reverse hunk to '%s'",
2749                                      patch->new_name
2750                                      ? patch->new_name : patch->old_name);
2751                 fragment = fragment->next;
2752         }
2753         switch (fragment->binary_patch_method) {
2754         case BINARY_DELTA_DEFLATED:
2755                 dst = patch_delta(img->buf, img->len, fragment->patch,
2756                                   fragment->size, &len);
2757                 if (!dst)
2758                         return -1;
2759                 clear_image(img);
2760                 img->buf = dst;
2761                 img->len = len;
2762                 return 0;
2763         case BINARY_LITERAL_DEFLATED:
2764                 clear_image(img);
2765                 img->len = fragment->size;
2766                 img->buf = xmalloc(img->len+1);
2767                 memcpy(img->buf, fragment->patch, img->len);
2768                 img->buf[img->len] = '\0';
2769                 return 0;
2770         }
2771         return -1;
2772 }
2773
2774 static int apply_binary(struct image *img, struct patch *patch)
2775 {
2776         const char *name = patch->old_name ? patch->old_name : patch->new_name;
2777         unsigned char sha1[20];
2778
2779         /*
2780          * For safety, we require patch index line to contain
2781          * full 40-byte textual SHA1 for old and new, at least for now.
2782          */
2783         if (strlen(patch->old_sha1_prefix) != 40 ||
2784             strlen(patch->new_sha1_prefix) != 40 ||
2785             get_sha1_hex(patch->old_sha1_prefix, sha1) ||
2786             get_sha1_hex(patch->new_sha1_prefix, sha1))
2787                 return error("cannot apply binary patch to '%s' "
2788                              "without full index line", name);
2789
2790         if (patch->old_name) {
2791                 /*
2792                  * See if the old one matches what the patch
2793                  * applies to.
2794                  */
2795                 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2796                 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
2797                         return error("the patch applies to '%s' (%s), "
2798                                      "which does not match the "
2799                                      "current contents.",
2800                                      name, sha1_to_hex(sha1));
2801         }
2802         else {
2803                 /* Otherwise, the old one must be empty. */
2804                 if (img->len)
2805                         return error("the patch applies to an empty "
2806                                      "'%s' but it is not empty", name);
2807         }
2808
2809         get_sha1_hex(patch->new_sha1_prefix, sha1);
2810         if (is_null_sha1(sha1)) {
2811                 clear_image(img);
2812                 return 0; /* deletion patch */
2813         }
2814
2815         if (has_sha1_file(sha1)) {
2816                 /* We already have the postimage */
2817                 enum object_type type;
2818                 unsigned long size;
2819                 char *result;
2820
2821                 result = read_sha1_file(sha1, &type, &size);
2822                 if (!result)
2823                         return error("the necessary postimage %s for "
2824                                      "'%s' cannot be read",
2825                                      patch->new_sha1_prefix, name);
2826                 clear_image(img);
2827                 img->buf = result;
2828                 img->len = size;
2829         } else {
2830                 /*
2831                  * We have verified buf matches the preimage;
2832                  * apply the patch data to it, which is stored
2833                  * in the patch->fragments->{patch,size}.
2834                  */
2835                 if (apply_binary_fragment(img, patch))
2836                         return error("binary patch does not apply to '%s'",
2837                                      name);
2838
2839                 /* verify that the result matches */
2840                 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2841                 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
2842                         return error("binary patch to '%s' creates incorrect result (expecting %s, got %s)",
2843                                 name, patch->new_sha1_prefix, sha1_to_hex(sha1));
2844         }
2845
2846         return 0;
2847 }
2848
2849 static int apply_fragments(struct image *img, struct patch *patch)
2850 {
2851         struct fragment *frag = patch->fragments;
2852         const char *name = patch->old_name ? patch->old_name : patch->new_name;
2853         unsigned ws_rule = patch->ws_rule;
2854         unsigned inaccurate_eof = patch->inaccurate_eof;
2855         int nth = 0;
2856
2857         if (patch->is_binary)
2858                 return apply_binary(img, patch);
2859
2860         while (frag) {
2861                 nth++;
2862                 if (apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {
2863                         error("patch failed: %s:%ld", name, frag->oldpos);
2864                         if (!apply_with_reject)
2865                                 return -1;
2866                         frag->rejected = 1;
2867                 }
2868                 frag = frag->next;
2869         }
2870         return 0;
2871 }
2872
2873 static int read_file_or_gitlink(struct cache_entry *ce, struct strbuf *buf)
2874 {
2875         if (!ce)
2876                 return 0;
2877
2878         if (S_ISGITLINK(ce->ce_mode)) {
2879                 strbuf_grow(buf, 100);
2880                 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(ce->sha1));
2881         } else {
2882                 enum object_type type;
2883                 unsigned long sz;
2884                 char *result;
2885
2886                 result = read_sha1_file(ce->sha1, &type, &sz);
2887                 if (!result)
2888                         return -1;
2889                 /* XXX read_sha1_file NUL-terminates */
2890                 strbuf_attach(buf, result, sz, sz + 1);
2891         }
2892         return 0;
2893 }
2894
2895 static struct patch *in_fn_table(const char *name)
2896 {
2897         struct string_list_item *item;
2898
2899         if (name == NULL)
2900                 return NULL;
2901
2902         item = string_list_lookup(&fn_table, name);
2903         if (item != NULL)
2904                 return (struct patch *)item->util;
2905
2906         return NULL;
2907 }
2908
2909 /*
2910  * item->util in the filename table records the status of the path.
2911  * Usually it points at a patch (whose result records the contents
2912  * of it after applying it), but it could be PATH_WAS_DELETED for a
2913  * path that a previously applied patch has already removed.
2914  */
2915  #define PATH_TO_BE_DELETED ((struct patch *) -2)
2916 #define PATH_WAS_DELETED ((struct patch *) -1)
2917
2918 static int to_be_deleted(struct patch *patch)
2919 {
2920         return patch == PATH_TO_BE_DELETED;
2921 }
2922
2923 static int was_deleted(struct patch *patch)
2924 {
2925         return patch == PATH_WAS_DELETED;
2926 }
2927
2928 static void add_to_fn_table(struct patch *patch)
2929 {
2930         struct string_list_item *item;
2931
2932         /*
2933          * Always add new_name unless patch is a deletion
2934          * This should cover the cases for normal diffs,
2935          * file creations and copies
2936          */
2937         if (patch->new_name != NULL) {
2938                 item = string_list_insert(&fn_table, patch->new_name);
2939                 item->util = patch;
2940         }
2941
2942         /*
2943          * store a failure on rename/deletion cases because
2944          * later chunks shouldn't patch old names
2945          */
2946         if ((patch->new_name == NULL) || (patch->is_rename)) {
2947                 item = string_list_insert(&fn_table, patch->old_name);
2948                 item->util = PATH_WAS_DELETED;
2949         }
2950 }
2951
2952 static void prepare_fn_table(struct patch *patch)
2953 {
2954         /*
2955          * store information about incoming file deletion
2956          */
2957         while (patch) {
2958                 if ((patch->new_name == NULL) || (patch->is_rename)) {
2959                         struct string_list_item *item;
2960                         item = string_list_insert(&fn_table, patch->old_name);
2961                         item->util = PATH_TO_BE_DELETED;
2962                 }
2963                 patch = patch->next;
2964         }
2965 }
2966
2967 static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce)
2968 {
2969         struct strbuf buf = STRBUF_INIT;
2970         struct image image;
2971         size_t len;
2972         char *img;
2973         struct patch *tpatch;
2974
2975         if (!(patch->is_copy || patch->is_rename) &&
2976             (tpatch = in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {
2977                 if (was_deleted(tpatch)) {
2978                         return error("patch %s has been renamed/deleted",
2979                                 patch->old_name);
2980                 }
2981                 /* We have a patched copy in memory use that */
2982                 strbuf_add(&buf, tpatch->result, tpatch->resultsize);
2983         } else if (cached) {
2984                 if (read_file_or_gitlink(ce, &buf))
2985                         return error("read of %s failed", patch->old_name);
2986         } else if (patch->old_name) {
2987                 if (S_ISGITLINK(patch->old_mode)) {
2988                         if (ce) {
2989                                 read_file_or_gitlink(ce, &buf);
2990                         } else {
2991                                 /*
2992                                  * There is no way to apply subproject
2993                                  * patch without looking at the index.
2994                                  */
2995                                 patch->fragments = NULL;
2996                         }
2997                 } else {
2998                         if (read_old_data(st, patch->old_name, &buf))
2999                                 return error("read of %s failed", patch->old_name);
3000                 }
3001         }
3002
3003         img = strbuf_detach(&buf, &len);
3004         prepare_image(&image, img, len, !patch->is_binary);
3005
3006         if (apply_fragments(&image, patch) < 0)
3007                 return -1; /* note with --reject this succeeds. */
3008         patch->result = image.buf;
3009         patch->resultsize = image.len;
3010         add_to_fn_table(patch);
3011         free(image.line_allocated);
3012
3013         if (0 < patch->is_delete && patch->resultsize)
3014                 return error("removal patch leaves file contents");
3015
3016         return 0;
3017 }
3018
3019 static int check_to_create_blob(const char *new_name, int ok_if_exists)
3020 {
3021         struct stat nst;
3022         if (!lstat(new_name, &nst)) {
3023                 if (S_ISDIR(nst.st_mode) || ok_if_exists)
3024                         return 0;
3025                 /*
3026                  * A leading component of new_name might be a symlink
3027                  * that is going to be removed with this patch, but
3028                  * still pointing at somewhere that has the path.
3029                  * In such a case, path "new_name" does not exist as
3030                  * far as git is concerned.
3031                  */
3032                 if (has_symlink_leading_path(new_name, strlen(new_name)))
3033                         return 0;
3034
3035                 return error("%s: already exists in working directory", new_name);
3036         }
3037         else if ((errno != ENOENT) && (errno != ENOTDIR))
3038                 return error("%s: %s", new_name, strerror(errno));
3039         return 0;
3040 }
3041
3042 static int verify_index_match(struct cache_entry *ce, struct stat *st)
3043 {
3044         if (S_ISGITLINK(ce->ce_mode)) {
3045                 if (!S_ISDIR(st->st_mode))
3046                         return -1;
3047                 return 0;
3048         }
3049         return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
3050 }
3051
3052 static int check_preimage(struct patch *patch, struct cache_entry **ce, struct stat *st)
3053 {
3054         const char *old_name = patch->old_name;
3055         struct patch *tpatch = NULL;
3056         int stat_ret = 0;
3057         unsigned st_mode = 0;
3058
3059         /*
3060          * Make sure that we do not have local modifications from the
3061          * index when we are looking at the index.  Also make sure
3062          * we have the preimage file to be patched in the work tree,
3063          * unless --cached, which tells git to apply only in the index.
3064          */
3065         if (!old_name)
3066                 return 0;
3067
3068         assert(patch->is_new <= 0);
3069
3070         if (!(patch->is_copy || patch->is_rename) &&
3071             (tpatch = in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {
3072                 if (was_deleted(tpatch))
3073                         return error("%s: has been deleted/renamed", old_name);
3074                 st_mode = tpatch->new_mode;
3075         } else if (!cached) {
3076                 stat_ret = lstat(old_name, st);
3077                 if (stat_ret && errno != ENOENT)
3078                         return error("%s: %s", old_name, strerror(errno));
3079         }
3080
3081         if (to_be_deleted(tpatch))
3082                 tpatch = NULL;
3083
3084         if (check_index && !tpatch) {
3085                 int pos = cache_name_pos(old_name, strlen(old_name));
3086                 if (pos < 0) {
3087                         if (patch->is_new < 0)
3088                                 goto is_new;
3089                         return error("%s: does not exist in index", old_name);
3090                 }
3091                 *ce = active_cache[pos];
3092                 if (stat_ret < 0) {
3093                         struct checkout costate;
3094                         /* checkout */
3095                         memset(&costate, 0, sizeof(costate));
3096                         costate.base_dir = "";
3097                         costate.refresh_cache = 1;
3098                         if (checkout_entry(*ce, &costate, NULL) ||
3099                             lstat(old_name, st))
3100                                 return -1;
3101                 }
3102                 if (!cached && verify_index_match(*ce, st))
3103                         return error("%s: does not match index", old_name);
3104                 if (cached)
3105                         st_mode = (*ce)->ce_mode;
3106         } else if (stat_ret < 0) {
3107                 if (patch->is_new < 0)
3108                         goto is_new;
3109                 return error("%s: %s", old_name, strerror(errno));
3110         }
3111
3112         if (!cached && !tpatch)
3113                 st_mode = ce_mode_from_stat(*ce, st->st_mode);
3114
3115         if (patch->is_new < 0)
3116                 patch->is_new = 0;
3117         if (!patch->old_mode)
3118                 patch->old_mode = st_mode;
3119         if ((st_mode ^ patch->old_mode) & S_IFMT)
3120                 return error("%s: wrong type", old_name);
3121         if (st_mode != patch->old_mode)
3122                 warning("%s has type %o, expected %o",
3123                         old_name, st_mode, patch->old_mode);
3124         if (!patch->new_mode && !patch->is_delete)
3125                 patch->new_mode = st_mode;
3126         return 0;
3127
3128  is_new:
3129         patch->is_new = 1;
3130         patch->is_delete = 0;
3131         free(patch->old_name);
3132         patch->old_name = NULL;
3133         return 0;
3134 }
3135
3136 static int check_patch(struct patch *patch)
3137 {
3138         struct stat st;
3139         const char *old_name = patch->old_name;
3140         const char *new_name = patch->new_name;
3141         const char *name = old_name ? old_name : new_name;
3142         struct cache_entry *ce = NULL;
3143         struct patch *tpatch;
3144         int ok_if_exists;
3145         int status;
3146
3147         patch->rejected = 1; /* we will drop this after we succeed */
3148
3149         status = check_preimage(patch, &ce, &st);
3150         if (status)
3151                 return status;
3152         old_name = patch->old_name;
3153
3154         if ((tpatch = in_fn_table(new_name)) &&
3155                         (was_deleted(tpatch) || to_be_deleted(tpatch)))
3156                 /*
3157                  * A type-change diff is always split into a patch to
3158                  * delete old, immediately followed by a patch to
3159                  * create new (see diff.c::run_diff()); in such a case
3160                  * it is Ok that the entry to be deleted by the
3161                  * previous patch is still in the working tree and in
3162                  * the index.
3163                  */
3164                 ok_if_exists = 1;
3165         else
3166                 ok_if_exists = 0;
3167
3168         if (new_name &&
3169             ((0 < patch->is_new) | (0 < patch->is_rename) | patch->is_copy)) {
3170                 if (check_index &&
3171                     cache_name_pos(new_name, strlen(new_name)) >= 0 &&
3172                     !ok_if_exists)
3173                         return error("%s: already exists in index", new_name);
3174                 if (!cached) {
3175                         int err = check_to_create_blob(new_name, ok_if_exists);
3176                         if (err)
3177                                 return err;
3178                 }
3179                 if (!patch->new_mode) {
3180                         if (0 < patch->is_new)
3181                                 patch->new_mode = S_IFREG | 0644;
3182                         else
3183                                 patch->new_mode = patch->old_mode;
3184                 }
3185         }
3186
3187         if (new_name && old_name) {
3188                 int same = !strcmp(old_name, new_name);
3189                 if (!patch->new_mode)
3190                         patch->new_mode = patch->old_mode;
3191                 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
3192                         return error("new mode (%o) of %s does not match old mode (%o)%s%s",
3193                                 patch->new_mode, new_name, patch->old_mode,
3194                                 same ? "" : " of ", same ? "" : old_name);
3195         }
3196
3197         if (apply_data(patch, &st, ce) < 0)
3198                 return error("%s: patch does not apply", name);
3199         patch->rejected = 0;
3200         return 0;
3201 }
3202
3203 static int check_patch_list(struct patch *patch)
3204 {
3205         int err = 0;
3206
3207         prepare_fn_table(patch);
3208         while (patch) {
3209                 if (apply_verbosely)
3210                         say_patch_name(stderr,
3211                                        "Checking patch ", patch, "...\n");
3212                 err |= check_patch(patch);
3213                 patch = patch->next;
3214         }
3215         return err;
3216 }
3217
3218 /* This function tries to read the sha1 from the current index */
3219 static int get_current_sha1(const char *path, unsigned char *sha1)
3220 {
3221         int pos;
3222
3223         if (read_cache() < 0)
3224                 return -1;
3225         pos = cache_name_pos(path, strlen(path));
3226         if (pos < 0)
3227                 return -1;
3228         hashcpy(sha1, active_cache[pos]->sha1);
3229         return 0;
3230 }
3231
3232 /* Build an index that contains the just the files needed for a 3way merge */
3233 static void build_fake_ancestor(struct patch *list, const char *filename)
3234 {
3235         struct patch *patch;
3236         struct index_state result = { NULL };
3237         int fd;
3238
3239         /* Once we start supporting the reverse patch, it may be
3240          * worth showing the new sha1 prefix, but until then...
3241          */
3242         for (patch = list; patch; patch = patch->next) {
3243                 const unsigned char *sha1_ptr;
3244                 unsigned char sha1[20];
3245                 struct cache_entry *ce;
3246                 const char *name;
3247
3248                 name = patch->old_name ? patch->old_name : patch->new_name;
3249                 if (0 < patch->is_new)
3250                         continue;
3251                 else if (get_sha1(patch->old_sha1_prefix, sha1))
3252                         /* git diff has no index line for mode/type changes */
3253                         if (!patch->lines_added && !patch->lines_deleted) {
3254                                 if (get_current_sha1(patch->old_name, sha1))
3255                                         die("mode change for %s, which is not "
3256                                                 "in current HEAD", name);
3257                                 sha1_ptr = sha1;
3258                         } else
3259                                 die("sha1 information is lacking or useless "
3260                                         "(%s).", name);
3261                 else
3262                         sha1_ptr = sha1;
3263
3264                 ce = make_cache_entry(patch->old_mode, sha1_ptr, name, 0, 0);
3265                 if (!ce)
3266                         die("make_cache_entry failed for path '%s'", name);
3267                 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))
3268                         die ("Could not add %s to temporary index", name);
3269         }
3270
3271         fd = open(filename, O_WRONLY | O_CREAT, 0666);
3272         if (fd < 0 || write_index(&result, fd) || close(fd))
3273                 die ("Could not write temporary index to %s", filename);
3274
3275         discard_index(&result);
3276 }
3277
3278 static void stat_patch_list(struct patch *patch)
3279 {
3280         int files, adds, dels;
3281
3282         for (files = adds = dels = 0 ; patch ; patch = patch->next) {
3283                 files++;
3284                 adds += patch->lines_added;
3285                 dels += patch->lines_deleted;
3286                 show_stats(patch);
3287         }
3288
3289         printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
3290 }
3291
3292 static void numstat_patch_list(struct patch *patch)
3293 {
3294         for ( ; patch; patch = patch->next) {
3295                 const char *name;
3296                 name = patch->new_name ? patch->new_name : patch->old_name;
3297                 if (patch->is_binary)
3298                         printf("-\t-\t");
3299                 else
3300                         printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
3301                 write_name_quoted(name, stdout, line_termination);
3302         }
3303 }
3304
3305 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
3306 {
3307         if (mode)
3308                 printf(" %s mode %06o %s\n", newdelete, mode, name);
3309         else
3310                 printf(" %s %s\n", newdelete, name);
3311 }
3312
3313 static void show_mode_change(struct patch *p, int show_name)
3314 {
3315         if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
3316                 if (show_name)
3317                         printf(" mode change %06o => %06o %s\n",
3318                                p->old_mode, p->new_mode, p->new_name);
3319                 else
3320                         printf(" mode change %06o => %06o\n",
3321                                p->old_mode, p->new_mode);
3322         }
3323 }
3324
3325 static void show_rename_copy(struct patch *p)
3326 {
3327         const char *renamecopy = p->is_rename ? "rename" : "copy";
3328         const char *old, *new;
3329
3330         /* Find common prefix */
3331         old = p->old_name;
3332         new = p->new_name;
3333         while (1) {
3334                 const char *slash_old, *slash_new;
3335                 slash_old = strchr(old, '/');
3336                 slash_new = strchr(new, '/');
3337                 if (!slash_old ||
3338                     !slash_new ||
3339                     slash_old - old != slash_new - new ||
3340                     memcmp(old, new, slash_new - new))
3341                         break;
3342                 old = slash_old + 1;
3343                 new = slash_new + 1;
3344         }
3345         /* p->old_name thru old is the common prefix, and old and new
3346          * through the end of names are renames
3347          */
3348         if (old != p->old_name)
3349                 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
3350                        (int)(old - p->old_name), p->old_name,
3351                        old, new, p->score);
3352         else
3353                 printf(" %s %s => %s (%d%%)\n", renamecopy,
3354                        p->old_name, p->new_name, p->score);
3355         show_mode_change(p, 0);
3356 }
3357
3358 static void summary_patch_list(struct patch *patch)
3359 {
3360         struct patch *p;
3361
3362         for (p = patch; p; p = p->next) {
3363                 if (p->is_new)
3364                         show_file_mode_name("create", p->new_mode, p->new_name);
3365                 else if (p->is_delete)
3366                         show_file_mode_name("delete", p->old_mode, p->old_name);
3367                 else {
3368                         if (p->is_rename || p->is_copy)
3369                                 show_rename_copy(p);
3370                         else {
3371                                 if (p->score) {
3372                                         printf(" rewrite %s (%d%%)\n",
3373                                                p->new_name, p->score);
3374                                         show_mode_change(p, 0);
3375                                 }
3376                                 else
3377                                         show_mode_change(p, 1);
3378                         }
3379                 }
3380         }
3381 }
3382
3383 static void patch_stats(struct patch *patch)
3384 {
3385         int lines = patch->lines_added + patch->lines_deleted;
3386
3387         if (lines > max_change)
3388                 max_change = lines;
3389         if (patch->old_name) {
3390                 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
3391                 if (!len)
3392                         len = strlen(patch->old_name);
3393                 if (len > max_len)
3394                         max_len = len;
3395         }
3396         if (patch->new_name) {
3397                 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
3398                 if (!len)
3399                         len = strlen(patch->new_name);
3400                 if (len > max_len)
3401                         max_len = len;
3402         }
3403 }
3404
3405 static void remove_file(struct patch *patch, int rmdir_empty)
3406 {
3407         if (update_index) {
3408                 if (remove_file_from_cache(patch->old_name) < 0)
3409                         die("unable to remove %s from index", patch->old_name);
3410         }
3411         if (!cached) {
3412                 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
3413                         remove_path(patch->old_name);
3414                 }
3415         }
3416 }
3417
3418 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
3419 {
3420         struct stat st;
3421         struct cache_entry *ce;
3422         int namelen = strlen(path);
3423         unsigned ce_size = cache_entry_size(namelen);
3424
3425         if (!update_index)
3426                 return;
3427
3428         ce = xcalloc(1, ce_size);
3429         memcpy(ce->name, path, namelen);
3430         ce->ce_mode = create_ce_mode(mode);
3431         ce->ce_flags = namelen;
3432         if (S_ISGITLINK(mode)) {
3433                 const char *s = buf;
3434
3435                 if (get_sha1_hex(s + strlen("Subproject commit "), ce->sha1))
3436                         die("corrupt patch for subproject %s", path);
3437         } else {
3438                 if (!cached) {
3439                         if (lstat(path, &st) < 0)
3440                                 die_errno("unable to stat newly created file '%s'",
3441                                           path);
3442                         fill_stat_cache_info(ce, &st);
3443                 }
3444                 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
3445                         die("unable to create backing store for newly created file %s", path);
3446         }
3447         if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
3448                 die("unable to add cache entry for %s", path);
3449 }
3450
3451 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
3452 {
3453         int fd;
3454         struct strbuf nbuf = STRBUF_INIT;
3455
3456         if (S_ISGITLINK(mode)) {
3457                 struct stat st;
3458                 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
3459                         return 0;
3460                 return mkdir(path, 0777);
3461         }
3462
3463         if (has_symlinks && S_ISLNK(mode))
3464                 /* Although buf:size is counted string, it also is NUL
3465                  * terminated.
3466                  */
3467                 return symlink(buf, path);
3468
3469         fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
3470         if (fd < 0)
3471                 return -1;
3472
3473         if (convert_to_working_tree(path, buf, size, &nbuf)) {
3474                 size = nbuf.len;
3475                 buf  = nbuf.buf;
3476         }
3477         write_or_die(fd, buf, size);
3478         strbuf_release(&nbuf);
3479
3480         if (close(fd) < 0)
3481                 die_errno("closing file '%s'", path);
3482         return 0;
3483 }
3484
3485 /*
3486  * We optimistically assume that the directories exist,
3487  * which is true 99% of the time anyway. If they don't,
3488  * we create them and try again.
3489  */
3490 static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
3491 {
3492         if (cached)
3493                 return;
3494         if (!try_create_file(path, mode, buf, size))
3495                 return;
3496
3497         if (errno == ENOENT) {
3498                 if (safe_create_leading_directories(path))
3499                         return;
3500                 if (!try_create_file(path, mode, buf, size))
3501                         return;
3502         }
3503
3504         if (errno == EEXIST || errno == EACCES) {
3505                 /* We may be trying to create a file where a directory
3506                  * used to be.
3507                  */
3508                 struct stat st;
3509                 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
3510                         errno = EEXIST;
3511         }
3512
3513         if (errno == EEXIST) {
3514                 unsigned int nr = getpid();
3515
3516                 for (;;) {
3517                         char newpath[PATH_MAX];
3518                         mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
3519                         if (!try_create_file(newpath, mode, buf, size)) {
3520                                 if (!rename(newpath, path))
3521                                         return;
3522                                 unlink_or_warn(newpath);
3523                                 break;
3524                         }
3525                         if (errno != EEXIST)
3526                                 break;
3527                         ++nr;
3528                 }
3529         }
3530         die_errno("unable to write file '%s' mode %o", path, mode);
3531 }
3532
3533 static void create_file(struct patch *patch)
3534 {
3535         char *path = patch->new_name;
3536         unsigned mode = patch->new_mode;
3537         unsigned long size = patch->resultsize;
3538         char *buf = patch->result;
3539
3540         if (!mode)
3541                 mode = S_IFREG | 0644;
3542         create_one_file(path, mode, buf, size);
3543         add_index_file(path, mode, buf, size);
3544 }
3545
3546 /* phase zero is to remove, phase one is to create */
3547 static void write_out_one_result(struct patch *patch, int phase)
3548 {
3549         if (patch->is_delete > 0) {
3550                 if (phase == 0)
3551                         remove_file(patch, 1);
3552                 return;
3553         }
3554         if (patch->is_new > 0 || patch->is_copy) {
3555                 if (phase == 1)
3556                         create_file(patch);
3557                 return;
3558         }
3559         /*
3560          * Rename or modification boils down to the same
3561          * thing: remove the old, write the new
3562          */
3563         if (phase == 0)
3564                 remove_file(patch, patch->is_rename);
3565         if (phase == 1)
3566                 create_file(patch);
3567 }
3568
3569 static int write_out_one_reject(struct patch *patch)
3570 {
3571         FILE *rej;
3572         char namebuf[PATH_MAX];
3573         struct fragment *frag;
3574         int cnt = 0;
3575
3576         for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
3577                 if (!frag->rejected)
3578                         continue;
3579                 cnt++;
3580         }
3581
3582         if (!cnt) {
3583                 if (apply_verbosely)
3584                         say_patch_name(stderr,
3585                                        "Applied patch ", patch, " cleanly.\n");
3586                 return 0;
3587         }
3588
3589         /* This should not happen, because a removal patch that leaves
3590          * contents are marked "rejected" at the patch level.
3591          */
3592         if (!patch->new_name)
3593                 die("internal error");
3594
3595         /* Say this even without --verbose */
3596         say_patch_name(stderr, "Applying patch ", patch, " with");
3597         fprintf(stderr, " %d rejects...\n", cnt);
3598
3599         cnt = strlen(patch->new_name);
3600         if (ARRAY_SIZE(namebuf) <= cnt + 5) {
3601                 cnt = ARRAY_SIZE(namebuf) - 5;
3602                 warning("truncating .rej filename to %.*s.rej",
3603                         cnt - 1, patch->new_name);
3604         }
3605         memcpy(namebuf, patch->new_name, cnt);
3606         memcpy(namebuf + cnt, ".rej", 5);
3607
3608         rej = fopen(namebuf, "w");
3609         if (!rej)
3610                 return error("cannot open %s: %s", namebuf, strerror(errno));
3611
3612         /* Normal git tools never deal with .rej, so do not pretend
3613          * this is a git patch by saying --git nor give extended
3614          * headers.  While at it, maybe please "kompare" that wants
3615          * the trailing TAB and some garbage at the end of line ;-).
3616          */
3617         fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
3618                 patch->new_name, patch->new_name);
3619         for (cnt = 1, frag = patch->fragments;
3620              frag;
3621              cnt++, frag = frag->next) {
3622                 if (!frag->rejected) {
3623                         fprintf(stderr, "Hunk #%d applied cleanly.\n", cnt);
3624                         continue;
3625                 }
3626                 fprintf(stderr, "Rejected hunk #%d.\n", cnt);
3627                 fprintf(rej, "%.*s", frag->size, frag->patch);
3628                 if (frag->patch[frag->size-1] != '\n')
3629                         fputc('\n', rej);
3630         }
3631         fclose(rej);
3632         return -1;
3633 }
3634
3635 static int write_out_results(struct patch *list)
3636 {
3637         int phase;
3638         int errs = 0;
3639         struct patch *l;
3640
3641         for (phase = 0; phase < 2; phase++) {
3642                 l = list;
3643                 while (l) {
3644                         if (l->rejected)
3645                                 errs = 1;
3646                         else {
3647                                 write_out_one_result(l, phase);
3648                                 if (phase == 1 && write_out_one_reject(l))
3649                                         errs = 1;
3650                         }
3651                         l = l->next;
3652                 }
3653         }
3654         return errs;
3655 }
3656
3657 static struct lock_file lock_file;
3658
3659 static struct string_list limit_by_name;
3660 static int has_include;
3661 static void add_name_limit(const char *name, int exclude)
3662 {
3663         struct string_list_item *it;
3664
3665         it = string_list_append(&limit_by_name, name);
3666         it->util = exclude ? NULL : (void *) 1;
3667 }
3668
3669 static int use_patch(struct patch *p)
3670 {
3671         const char *pathname = p->new_name ? p->new_name : p->old_name;
3672         int i;
3673
3674         /* Paths outside are not touched regardless of "--include" */
3675         if (0 < prefix_length) {
3676                 int pathlen = strlen(pathname);
3677                 if (pathlen <= prefix_length ||
3678                     memcmp(prefix, pathname, prefix_length))
3679                         return 0;
3680         }
3681
3682         /* See if it matches any of exclude/include rule */
3683         for (i = 0; i < limit_by_name.nr; i++) {
3684                 struct string_list_item *it = &limit_by_name.items[i];
3685                 if (!fnmatch(it->string, pathname, 0))
3686                         return (it->util != NULL);
3687         }
3688
3689         /*
3690          * If we had any include, a path that does not match any rule is
3691          * not used.  Otherwise, we saw bunch of exclude rules (or none)
3692          * and such a path is used.
3693          */
3694         return !has_include;
3695 }
3696
3697
3698 static void prefix_one(char **name)
3699 {
3700         char *old_name = *name;
3701         if (!old_name)
3702                 return;
3703         *name = xstrdup(prefix_filename(prefix, prefix_length, *name));
3704         free(old_name);
3705 }
3706
3707 static void prefix_patches(struct patch *p)
3708 {
3709         if (!prefix || p->is_toplevel_relative)
3710                 return;
3711         for ( ; p; p = p->next) {
3712                 prefix_one(&p->new_name);
3713                 prefix_one(&p->old_name);
3714         }
3715 }
3716
3717 #define INACCURATE_EOF  (1<<0)
3718 #define RECOUNT         (1<<1)
3719
3720 static int apply_patch(int fd, const char *filename, int options)
3721 {
3722         size_t offset;
3723         struct strbuf buf = STRBUF_INIT;
3724         struct patch *list = NULL, **listp = &list;
3725         int skipped_patch = 0;
3726
3727         memset(&fn_table, 0, sizeof(struct string_list));
3728         patch_input_file = filename;
3729         read_patch_file(&buf, fd);
3730         offset = 0;
3731         while (offset < buf.len) {
3732                 struct patch *patch;
3733                 int nr;
3734
3735                 patch = xcalloc(1, sizeof(*patch));
3736                 patch->inaccurate_eof = !!(options & INACCURATE_EOF);
3737                 patch->recount =  !!(options & RECOUNT);
3738                 nr = parse_chunk(buf.buf + offset, buf.len - offset, patch);
3739                 if (nr < 0)
3740                         break;
3741                 if (apply_in_reverse)
3742                         reverse_patches(patch);
3743                 if (prefix)
3744                         prefix_patches(patch);
3745                 if (use_patch(patch)) {
3746                         patch_stats(patch);
3747                         *listp = patch;
3748                         listp = &patch->next;
3749                 }
3750                 else {
3751                         free_patch(patch);
3752                         skipped_patch++;
3753                 }
3754                 offset += nr;
3755         }
3756
3757         if (!list && !skipped_patch)
3758                 die("unrecognized input");
3759
3760         if (whitespace_error && (ws_error_action == die_on_ws_error))
3761                 apply = 0;
3762
3763         update_index = check_index && apply;
3764         if (update_index && newfd < 0)
3765                 newfd = hold_locked_index(&lock_file, 1);
3766
3767         if (check_index) {
3768                 if (read_cache() < 0)
3769                         die("unable to read index file");
3770         }
3771
3772         if ((check || apply) &&
3773             check_patch_list(list) < 0 &&
3774             !apply_with_reject)
3775                 exit(1);
3776
3777         if (apply && write_out_results(list))
3778                 exit(1);
3779
3780         if (fake_ancestor)
3781                 build_fake_ancestor(list, fake_ancestor);
3782
3783         if (diffstat)
3784                 stat_patch_list(list);
3785
3786         if (numstat)
3787                 numstat_patch_list(list);
3788
3789         if (summary)
3790                 summary_patch_list(list);
3791
3792         free_patch_list(list);
3793         strbuf_release(&buf);
3794         return 0;
3795 }
3796
3797 static int git_apply_config(const char *var, const char *value, void *cb)
3798 {
3799         if (!strcmp(var, "apply.whitespace"))
3800                 return git_config_string(&apply_default_whitespace, var, value);
3801         else if (!strcmp(var, "apply.ignorewhitespace"))
3802                 return git_config_string(&apply_default_ignorewhitespace, var, value);
3803         return git_default_config(var, value, cb);
3804 }
3805
3806 static int option_parse_exclude(const struct option *opt,
3807                                 const char *arg, int unset)
3808 {
3809         add_name_limit(arg, 1);
3810         return 0;
3811 }
3812
3813 static int option_parse_include(const struct option *opt,
3814                                 const char *arg, int unset)
3815 {
3816         add_name_limit(arg, 0);
3817         has_include = 1;
3818         return 0;
3819 }
3820
3821 static int option_parse_p(const struct option *opt,
3822                           const char *arg, int unset)
3823 {
3824         p_value = atoi(arg);
3825         p_value_known = 1;
3826         return 0;
3827 }
3828
3829 static int option_parse_z(const struct option *opt,
3830                           const char *arg, int unset)
3831 {
3832         if (unset)
3833                 line_termination = '\n';
3834         else
3835                 line_termination = 0;
3836         return 0;
3837 }
3838
3839 static int option_parse_space_change(const struct option *opt,
3840                           const char *arg, int unset)
3841 {
3842         if (unset)
3843                 ws_ignore_action = ignore_ws_none;
3844         else
3845                 ws_ignore_action = ignore_ws_change;
3846         return 0;
3847 }
3848
3849 static int option_parse_whitespace(const struct option *opt,
3850                                    const char *arg, int unset)
3851 {
3852         const char **whitespace_option = opt->value;
3853
3854         *whitespace_option = arg;
3855         parse_whitespace_option(arg);
3856         return 0;
3857 }
3858
3859 static int option_parse_directory(const struct option *opt,
3860                                   const char *arg, int unset)
3861 {
3862         root_len = strlen(arg);
3863         if (root_len && arg[root_len - 1] != '/') {
3864                 char *new_root;
3865                 root = new_root = xmalloc(root_len + 2);
3866                 strcpy(new_root, arg);
3867                 strcpy(new_root + root_len++, "/");
3868         } else
3869                 root = arg;
3870         return 0;
3871 }
3872
3873 int cmd_apply(int argc, const char **argv, const char *prefix_)
3874 {
3875         int i;
3876         int errs = 0;
3877         int is_not_gitdir = !startup_info->have_repository;
3878         int force_apply = 0;
3879
3880         const char *whitespace_option = NULL;
3881
3882         struct option builtin_apply_options[] = {
3883                 { OPTION_CALLBACK, 0, "exclude", NULL, "path",
3884                         "don't apply changes matching the given path",
3885                         0, option_parse_exclude },
3886                 { OPTION_CALLBACK, 0, "include", NULL, "path",
3887                         "apply changes matching the given path",
3888                         0, option_parse_include },
3889                 { OPTION_CALLBACK, 'p', NULL, NULL, "num",
3890                         "remove <num> leading slashes from traditional diff paths",
3891                         0, option_parse_p },
3892                 OPT_BOOLEAN(0, "no-add", &no_add,
3893                         "ignore additions made by the patch"),
3894                 OPT_BOOLEAN(0, "stat", &diffstat,
3895                         "instead of applying the patch, output diffstat for the input"),
3896                 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
3897                 OPT_NOOP_NOARG(0, "binary"),
3898                 OPT_BOOLEAN(0, "numstat", &numstat,
3899                         "shows number of added and deleted lines in decimal notation"),
3900                 OPT_BOOLEAN(0, "summary", &summary,
3901                         "instead of applying the patch, output a summary for the input"),
3902                 OPT_BOOLEAN(0, "check", &check,
3903                         "instead of applying the patch, see if the patch is applicable"),
3904                 OPT_BOOLEAN(0, "index", &check_index,
3905                         "make sure the patch is applicable to the current index"),
3906                 OPT_BOOLEAN(0, "cached", &cached,
3907                         "apply a patch without touching the working tree"),
3908                 OPT_BOOLEAN(0, "apply", &force_apply,
3909                         "also apply the patch (use with --stat/--summary/--check)"),
3910                 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor,
3911                         "build a temporary index based on embedded index information"),
3912                 { OPTION_CALLBACK, 'z', NULL, NULL, NULL,
3913                         "paths are separated with NUL character",
3914                         PARSE_OPT_NOARG, option_parse_z },
3915                 OPT_INTEGER('C', NULL, &p_context,
3916                                 "ensure at least <n> lines of context match"),
3917                 { OPTION_CALLBACK, 0, "whitespace", &whitespace_option, "action",
3918                         "detect new or modified lines that have whitespace errors",
3919                         0, option_parse_whitespace },
3920                 { OPTION_CALLBACK, 0, "ignore-space-change", NULL, NULL,
3921                         "ignore changes in whitespace when finding context",
3922                         PARSE_OPT_NOARG, option_parse_space_change },
3923                 { OPTION_CALLBACK, 0, "ignore-whitespace", NULL, NULL,
3924                         "ignore changes in whitespace when finding context",
3925                         PARSE_OPT_NOARG, option_parse_space_change },
3926                 OPT_BOOLEAN('R', "reverse", &apply_in_reverse,
3927                         "apply the patch in reverse"),
3928                 OPT_BOOLEAN(0, "unidiff-zero", &unidiff_zero,
3929                         "don't expect at least one line of context"),
3930                 OPT_BOOLEAN(0, "reject", &apply_with_reject,
3931                         "leave the rejected hunks in corresponding *.rej files"),
3932                 OPT_BOOLEAN(0, "allow-overlap", &allow_overlap,
3933                         "allow overlapping hunks"),
3934                 OPT__VERBOSE(&apply_verbosely, "be verbose"),
3935                 OPT_BIT(0, "inaccurate-eof", &options,
3936                         "tolerate incorrectly detected missing new-line at the end of file",
3937                         INACCURATE_EOF),
3938                 OPT_BIT(0, "recount", &options,
3939                         "do not trust the line counts in the hunk headers",
3940                         RECOUNT),
3941                 { OPTION_CALLBACK, 0, "directory", NULL, "root",
3942                         "prepend <root> to all filenames",
3943                         0, option_parse_directory },
3944                 OPT_END()
3945         };
3946
3947         prefix = prefix_;
3948         prefix_length = prefix ? strlen(prefix) : 0;
3949         git_config(git_apply_config, NULL);
3950         if (apply_default_whitespace)
3951                 parse_whitespace_option(apply_default_whitespace);
3952         if (apply_default_ignorewhitespace)
3953                 parse_ignorewhitespace_option(apply_default_ignorewhitespace);
3954
3955         argc = parse_options(argc, argv, prefix, builtin_apply_options,
3956                         apply_usage, 0);
3957
3958         if (apply_with_reject)
3959                 apply = apply_verbosely = 1;
3960         if (!force_apply && (diffstat || numstat || summary || check || fake_ancestor))
3961                 apply = 0;
3962         if (check_index && is_not_gitdir)
3963                 die("--index outside a repository");
3964         if (cached) {
3965                 if (is_not_gitdir)
3966                         die("--cached outside a repository");
3967                 check_index = 1;
3968         }
3969         for (i = 0; i < argc; i++) {
3970                 const char *arg = argv[i];
3971                 int fd;
3972
3973                 if (!strcmp(arg, "-")) {
3974                         errs |= apply_patch(0, "<stdin>", options);
3975                         read_stdin = 0;
3976                         continue;
3977                 } else if (0 < prefix_length)
3978                         arg = prefix_filename(prefix, prefix_length, arg);
3979
3980                 fd = open(arg, O_RDONLY);
3981                 if (fd < 0)
3982                         die_errno("can't open patch '%s'", arg);
3983                 read_stdin = 0;
3984                 set_default_whitespace_mode(whitespace_option);
3985                 errs |= apply_patch(fd, arg, options);
3986                 close(fd);
3987         }
3988         set_default_whitespace_mode(whitespace_option);
3989         if (read_stdin)
3990                 errs |= apply_patch(0, "<stdin>", options);
3991         if (whitespace_error) {
3992                 if (squelch_whitespace_errors &&
3993                     squelch_whitespace_errors < whitespace_error) {
3994                         int squelched =
3995                                 whitespace_error - squelch_whitespace_errors;
3996                         warning("squelched %d "
3997                                 "whitespace error%s",
3998                                 squelched,
3999                                 squelched == 1 ? "" : "s");
4000                 }
4001                 if (ws_error_action == die_on_ws_error)
4002                         die("%d line%s add%s whitespace errors.",
4003                             whitespace_error,
4004                             whitespace_error == 1 ? "" : "s",
4005                             whitespace_error == 1 ? "s" : "");
4006                 if (applied_after_fixing_ws && apply)
4007                         warning("%d line%s applied after"
4008                                 " fixing whitespace errors.",
4009                                 applied_after_fixing_ws,
4010                                 applied_after_fixing_ws == 1 ? "" : "s");
4011                 else if (whitespace_error)
4012                         warning("%d line%s add%s whitespace errors.",
4013                                 whitespace_error,
4014                                 whitespace_error == 1 ? "" : "s",
4015                                 whitespace_error == 1 ? "s" : "");
4016         }
4017
4018         if (update_index) {
4019                 if (write_cache(newfd, active_cache, active_nr) ||
4020                     commit_locked_index(&lock_file))
4021                         die("Unable to write new index file");
4022         }
4023
4024         return !!errs;
4025 }