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