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