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