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