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