OSDN Git Service

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