Code

apply --root: thinkofix.
[git.git] / builtin-apply.c
1 /*
2  * apply.c
3  *
4  * Copyright (C) Linus Torvalds, 2005
5  *
6  * This applies patches on top of some (arbitrary) version of the SCM.
7  *
8  */
9 #include "cache.h"
10 #include "cache-tree.h"
11 #include "quote.h"
12 #include "blob.h"
13 #include "delta.h"
14 #include "builtin.h"
16 /*
17  *  --check turns on checking that the working tree matches the
18  *    files that are being modified, but doesn't apply the patch
19  *  --stat does just a diffstat, and doesn't actually apply
20  *  --numstat does numeric diffstat, and doesn't actually apply
21  *  --index-info shows the old and new index info for paths if available.
22  *  --index updates the cache as well.
23  *  --cached updates only the cache without ever touching the working tree.
24  */
25 static const char *prefix;
26 static int prefix_length = -1;
27 static int newfd = -1;
29 static int unidiff_zero;
30 static int p_value = 1;
31 static int p_value_known;
32 static int check_index;
33 static int update_index;
34 static int cached;
35 static int diffstat;
36 static int numstat;
37 static int summary;
38 static int check;
39 static int apply = 1;
40 static int apply_in_reverse;
41 static int apply_with_reject;
42 static int apply_verbosely;
43 static int no_add;
44 static const char *fake_ancestor;
45 static int line_termination = '\n';
46 static unsigned long p_context = ULONG_MAX;
47 static const char apply_usage[] =
48 "git-apply [--stat] [--numstat] [--summary] [--check] [--index] [--cached] [--apply] [--no-add] [--index-info] [--allow-binary-replacement] [--reverse] [--reject] [--verbose] [-z] [-pNUM] [-CNUM] [--whitespace=<nowarn|warn|fix|error|error-all>] <patch>...";
50 static enum ws_error_action {
51         nowarn_ws_error,
52         warn_on_ws_error,
53         die_on_ws_error,
54         correct_ws_error,
55 } ws_error_action = warn_on_ws_error;
56 static int whitespace_error;
57 static int squelch_whitespace_errors = 5;
58 static int applied_after_fixing_ws;
59 static const char *patch_input_file;
60 static const char *root;
61 static int root_len;
63 static void parse_whitespace_option(const char *option)
64 {
65         if (!option) {
66                 ws_error_action = warn_on_ws_error;
67                 return;
68         }
69         if (!strcmp(option, "warn")) {
70                 ws_error_action = warn_on_ws_error;
71                 return;
72         }
73         if (!strcmp(option, "nowarn")) {
74                 ws_error_action = nowarn_ws_error;
75                 return;
76         }
77         if (!strcmp(option, "error")) {
78                 ws_error_action = die_on_ws_error;
79                 return;
80         }
81         if (!strcmp(option, "error-all")) {
82                 ws_error_action = die_on_ws_error;
83                 squelch_whitespace_errors = 0;
84                 return;
85         }
86         if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
87                 ws_error_action = correct_ws_error;
88                 return;
89         }
90         die("unrecognized whitespace option '%s'", option);
91 }
93 static void set_default_whitespace_mode(const char *whitespace_option)
94 {
95         if (!whitespace_option && !apply_default_whitespace)
96                 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error);
97 }
99 /*
100  * For "diff-stat" like behaviour, we keep track of the biggest change
101  * we've seen, and the longest filename. That allows us to do simple
102  * scaling.
103  */
104 static int max_change, max_len;
106 /*
107  * Various "current state", notably line numbers and what
108  * file (and how) we're patching right now.. The "is_xxxx"
109  * things are flags, where -1 means "don't know yet".
110  */
111 static int linenr = 1;
113 /*
114  * This represents one "hunk" from a patch, starting with
115  * "@@ -oldpos,oldlines +newpos,newlines @@" marker.  The
116  * patch text is pointed at by patch, and its byte length
117  * is stored in size.  leading and trailing are the number
118  * of context lines.
119  */
120 struct fragment {
121         unsigned long leading, trailing;
122         unsigned long oldpos, oldlines;
123         unsigned long newpos, newlines;
124         const char *patch;
125         int size;
126         int rejected;
127         struct fragment *next;
128 };
130 /*
131  * When dealing with a binary patch, we reuse "leading" field
132  * to store the type of the binary hunk, either deflated "delta"
133  * or deflated "literal".
134  */
135 #define binary_patch_method leading
136 #define BINARY_DELTA_DEFLATED   1
137 #define BINARY_LITERAL_DEFLATED 2
139 /*
140  * This represents a "patch" to a file, both metainfo changes
141  * such as creation/deletion, filemode and content changes represented
142  * as a series of fragments.
143  */
144 struct patch {
145         char *new_name, *old_name, *def_name;
146         unsigned int old_mode, new_mode;
147         int is_new, is_delete;  /* -1 = unknown, 0 = false, 1 = true */
148         int rejected;
149         unsigned ws_rule;
150         unsigned long deflate_origlen;
151         int lines_added, lines_deleted;
152         int score;
153         unsigned int is_toplevel_relative:1;
154         unsigned int inaccurate_eof:1;
155         unsigned int is_binary:1;
156         unsigned int is_copy:1;
157         unsigned int is_rename:1;
158         struct fragment *fragments;
159         char *result;
160         size_t resultsize;
161         char old_sha1_prefix[41];
162         char new_sha1_prefix[41];
163         struct patch *next;
164 };
166 /*
167  * A line in a file, len-bytes long (includes the terminating LF,
168  * except for an incomplete line at the end if the file ends with
169  * one), and its contents hashes to 'hash'.
170  */
171 struct line {
172         size_t len;
173         unsigned hash : 24;
174         unsigned flag : 8;
175 #define LINE_COMMON     1
176 };
178 /*
179  * This represents a "file", which is an array of "lines".
180  */
181 struct image {
182         char *buf;
183         size_t len;
184         size_t nr;
185         size_t alloc;
186         struct line *line_allocated;
187         struct line *line;
188 };
190 static uint32_t hash_line(const char *cp, size_t len)
192         size_t i;
193         uint32_t h;
194         for (i = 0, h = 0; i < len; i++) {
195                 if (!isspace(cp[i])) {
196                         h = h * 3 + (cp[i] & 0xff);
197                 }
198         }
199         return h;
202 static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
204         ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
205         img->line_allocated[img->nr].len = len;
206         img->line_allocated[img->nr].hash = hash_line(bol, len);
207         img->line_allocated[img->nr].flag = flag;
208         img->nr++;
211 static void prepare_image(struct image *image, char *buf, size_t len,
212                           int prepare_linetable)
214         const char *cp, *ep;
216         memset(image, 0, sizeof(*image));
217         image->buf = buf;
218         image->len = len;
220         if (!prepare_linetable)
221                 return;
223         ep = image->buf + image->len;
224         cp = image->buf;
225         while (cp < ep) {
226                 const char *next;
227                 for (next = cp; next < ep && *next != '\n'; next++)
228                         ;
229                 if (next < ep)
230                         next++;
231                 add_line_info(image, cp, next - cp, 0);
232                 cp = next;
233         }
234         image->line = image->line_allocated;
237 static void clear_image(struct image *image)
239         free(image->buf);
240         image->buf = NULL;
241         image->len = 0;
244 static void say_patch_name(FILE *output, const char *pre,
245                            struct patch *patch, const char *post)
247         fputs(pre, output);
248         if (patch->old_name && patch->new_name &&
249             strcmp(patch->old_name, patch->new_name)) {
250                 quote_c_style(patch->old_name, NULL, output, 0);
251                 fputs(" => ", output);
252                 quote_c_style(patch->new_name, NULL, output, 0);
253         } else {
254                 const char *n = patch->new_name;
255                 if (!n)
256                         n = patch->old_name;
257                 quote_c_style(n, NULL, output, 0);
258         }
259         fputs(post, output);
262 #define CHUNKSIZE (8192)
263 #define SLOP (16)
265 static void read_patch_file(struct strbuf *sb, int fd)
267         if (strbuf_read(sb, fd, 0) < 0)
268                 die("git-apply: read returned %s", strerror(errno));
270         /*
271          * Make sure that we have some slop in the buffer
272          * so that we can do speculative "memcmp" etc, and
273          * see to it that it is NUL-filled.
274          */
275         strbuf_grow(sb, SLOP);
276         memset(sb->buf + sb->len, 0, SLOP);
279 static unsigned long linelen(const char *buffer, unsigned long size)
281         unsigned long len = 0;
282         while (size--) {
283                 len++;
284                 if (*buffer++ == '\n')
285                         break;
286         }
287         return len;
290 static int is_dev_null(const char *str)
292         return !memcmp("/dev/null", str, 9) && isspace(str[9]);
295 #define TERM_SPACE      1
296 #define TERM_TAB        2
298 static int name_terminate(const char *name, int namelen, int c, int terminate)
300         if (c == ' ' && !(terminate & TERM_SPACE))
301                 return 0;
302         if (c == '\t' && !(terminate & TERM_TAB))
303                 return 0;
305         return 1;
308 static char *find_name(const char *line, char *def, int p_value, int terminate)
310         int len;
311         const char *start = line;
313         if (*line == '"') {
314                 struct strbuf name;
316                 /*
317                  * Proposed "new-style" GNU patch/diff format; see
318                  * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
319                  */
320                 strbuf_init(&name, 0);
321                 if (!unquote_c_style(&name, line, NULL)) {
322                         char *cp;
324                         for (cp = name.buf; p_value; p_value--) {
325                                 cp = strchr(cp, '/');
326                                 if (!cp)
327                                         break;
328                                 cp++;
329                         }
330                         if (cp) {
331                                 /* name can later be freed, so we need
332                                  * to memmove, not just return cp
333                                  */
334                                 strbuf_remove(&name, 0, cp - name.buf);
335                                 free(def);
336                                 if (root)
337                                         strbuf_insert(&name, 0, root, root_len);
338                                 return strbuf_detach(&name, NULL);
339                         }
340                 }
341                 strbuf_release(&name);
342         }
344         for (;;) {
345                 char c = *line;
347                 if (isspace(c)) {
348                         if (c == '\n')
349                                 break;
350                         if (name_terminate(start, line-start, c, terminate))
351                                 break;
352                 }
353                 line++;
354                 if (c == '/' && !--p_value)
355                         start = line;
356         }
357         if (!start)
358                 return def;
359         len = line - start;
360         if (!len)
361                 return def;
363         /*
364          * Generally we prefer the shorter name, especially
365          * if the other one is just a variation of that with
366          * something else tacked on to the end (ie "file.orig"
367          * or "file~").
368          */
369         if (def) {
370                 int deflen = strlen(def);
371                 if (deflen < len && !strncmp(start, def, deflen))
372                         return def;
373                 free(def);
374         }
376         if (root) {
377                 char *ret = xmalloc(root_len + len + 1);
378                 strcpy(ret, root);
379                 memcpy(ret + root_len, start, len);
380                 ret[root_len + len] = '\0';
381                 return ret;
382         }
384         return xmemdupz(start, len);
387 static int count_slashes(const char *cp)
389         int cnt = 0;
390         char ch;
392         while ((ch = *cp++))
393                 if (ch == '/')
394                         cnt++;
395         return cnt;
398 /*
399  * Given the string after "--- " or "+++ ", guess the appropriate
400  * p_value for the given patch.
401  */
402 static int guess_p_value(const char *nameline)
404         char *name, *cp;
405         int val = -1;
407         if (is_dev_null(nameline))
408                 return -1;
409         name = find_name(nameline, NULL, 0, TERM_SPACE | TERM_TAB);
410         if (!name)
411                 return -1;
412         cp = strchr(name, '/');
413         if (!cp)
414                 val = 0;
415         else if (prefix) {
416                 /*
417                  * Does it begin with "a/$our-prefix" and such?  Then this is
418                  * very likely to apply to our directory.
419                  */
420                 if (!strncmp(name, prefix, prefix_length))
421                         val = count_slashes(prefix);
422                 else {
423                         cp++;
424                         if (!strncmp(cp, prefix, prefix_length))
425                                 val = count_slashes(prefix) + 1;
426                 }
427         }
428         free(name);
429         return val;
432 /*
433  * Get the name etc info from the ---/+++ lines of a traditional patch header
434  *
435  * FIXME! The end-of-filename heuristics are kind of screwy. For existing
436  * files, we can happily check the index for a match, but for creating a
437  * new file we should try to match whatever "patch" does. I have no idea.
438  */
439 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
441         char *name;
443         first += 4;     /* skip "--- " */
444         second += 4;    /* skip "+++ " */
445         if (!p_value_known) {
446                 int p, q;
447                 p = guess_p_value(first);
448                 q = guess_p_value(second);
449                 if (p < 0) p = q;
450                 if (0 <= p && p == q) {
451                         p_value = p;
452                         p_value_known = 1;
453                 }
454         }
455         if (is_dev_null(first)) {
456                 patch->is_new = 1;
457                 patch->is_delete = 0;
458                 name = find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB);
459                 patch->new_name = name;
460         } else if (is_dev_null(second)) {
461                 patch->is_new = 0;
462                 patch->is_delete = 1;
463                 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
464                 patch->old_name = name;
465         } else {
466                 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
467                 name = find_name(second, name, p_value, TERM_SPACE | TERM_TAB);
468                 patch->old_name = patch->new_name = name;
469         }
470         if (!name)
471                 die("unable to find filename in patch at line %d", linenr);
474 static int gitdiff_hdrend(const char *line, struct patch *patch)
476         return -1;
479 /*
480  * We're anal about diff header consistency, to make
481  * sure that we don't end up having strange ambiguous
482  * patches floating around.
483  *
484  * As a result, gitdiff_{old|new}name() will check
485  * their names against any previous information, just
486  * to make sure..
487  */
488 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
490         if (!orig_name && !isnull)
491                 return find_name(line, NULL, p_value, TERM_TAB);
493         if (orig_name) {
494                 int len;
495                 const char *name;
496                 char *another;
497                 name = orig_name;
498                 len = strlen(name);
499                 if (isnull)
500                         die("git-apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
501                 another = find_name(line, NULL, p_value, TERM_TAB);
502                 if (!another || memcmp(another, name, len))
503                         die("git-apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
504                 free(another);
505                 return orig_name;
506         }
507         else {
508                 /* expect "/dev/null" */
509                 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
510                         die("git-apply: bad git-diff - expected /dev/null on line %d", linenr);
511                 return NULL;
512         }
515 static int gitdiff_oldname(const char *line, struct patch *patch)
517         patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
518         return 0;
521 static int gitdiff_newname(const char *line, struct patch *patch)
523         patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
524         return 0;
527 static int gitdiff_oldmode(const char *line, struct patch *patch)
529         patch->old_mode = strtoul(line, NULL, 8);
530         return 0;
533 static int gitdiff_newmode(const char *line, struct patch *patch)
535         patch->new_mode = strtoul(line, NULL, 8);
536         return 0;
539 static int gitdiff_delete(const char *line, struct patch *patch)
541         patch->is_delete = 1;
542         patch->old_name = patch->def_name;
543         return gitdiff_oldmode(line, patch);
546 static int gitdiff_newfile(const char *line, struct patch *patch)
548         patch->is_new = 1;
549         patch->new_name = patch->def_name;
550         return gitdiff_newmode(line, patch);
553 static int gitdiff_copysrc(const char *line, struct patch *patch)
555         patch->is_copy = 1;
556         patch->old_name = find_name(line, NULL, 0, 0);
557         return 0;
560 static int gitdiff_copydst(const char *line, struct patch *patch)
562         patch->is_copy = 1;
563         patch->new_name = find_name(line, NULL, 0, 0);
564         return 0;
567 static int gitdiff_renamesrc(const char *line, struct patch *patch)
569         patch->is_rename = 1;
570         patch->old_name = find_name(line, NULL, 0, 0);
571         return 0;
574 static int gitdiff_renamedst(const char *line, struct patch *patch)
576         patch->is_rename = 1;
577         patch->new_name = find_name(line, NULL, 0, 0);
578         return 0;
581 static int gitdiff_similarity(const char *line, struct patch *patch)
583         if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
584                 patch->score = 0;
585         return 0;
588 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
590         if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
591                 patch->score = 0;
592         return 0;
595 static int gitdiff_index(const char *line, struct patch *patch)
597         /*
598          * index line is N hexadecimal, "..", N hexadecimal,
599          * and optional space with octal mode.
600          */
601         const char *ptr, *eol;
602         int len;
604         ptr = strchr(line, '.');
605         if (!ptr || ptr[1] != '.' || 40 < ptr - line)
606                 return 0;
607         len = ptr - line;
608         memcpy(patch->old_sha1_prefix, line, len);
609         patch->old_sha1_prefix[len] = 0;
611         line = ptr + 2;
612         ptr = strchr(line, ' ');
613         eol = strchr(line, '\n');
615         if (!ptr || eol < ptr)
616                 ptr = eol;
617         len = ptr - line;
619         if (40 < len)
620                 return 0;
621         memcpy(patch->new_sha1_prefix, line, len);
622         patch->new_sha1_prefix[len] = 0;
623         if (*ptr == ' ')
624                 patch->new_mode = patch->old_mode = strtoul(ptr+1, NULL, 8);
625         return 0;
628 /*
629  * This is normal for a diff that doesn't change anything: we'll fall through
630  * into the next diff. Tell the parser to break out.
631  */
632 static int gitdiff_unrecognized(const char *line, struct patch *patch)
634         return -1;
637 static const char *stop_at_slash(const char *line, int llen)
639         int i;
641         for (i = 0; i < llen; i++) {
642                 int ch = line[i];
643                 if (ch == '/')
644                         return line + i;
645         }
646         return NULL;
649 /*
650  * This is to extract the same name that appears on "diff --git"
651  * line.  We do not find and return anything if it is a rename
652  * patch, and it is OK because we will find the name elsewhere.
653  * We need to reliably find name only when it is mode-change only,
654  * creation or deletion of an empty file.  In any of these cases,
655  * both sides are the same name under a/ and b/ respectively.
656  */
657 static char *git_header_name(char *line, int llen)
659         const char *name;
660         const char *second = NULL;
661         size_t len;
663         line += strlen("diff --git ");
664         llen -= strlen("diff --git ");
666         if (*line == '"') {
667                 const char *cp;
668                 struct strbuf first;
669                 struct strbuf sp;
671                 strbuf_init(&first, 0);
672                 strbuf_init(&sp, 0);
674                 if (unquote_c_style(&first, line, &second))
675                         goto free_and_fail1;
677                 /* advance to the first slash */
678                 cp = stop_at_slash(first.buf, first.len);
679                 /* we do not accept absolute paths */
680                 if (!cp || cp == first.buf)
681                         goto free_and_fail1;
682                 strbuf_remove(&first, 0, cp + 1 - first.buf);
684                 /*
685                  * second points at one past closing dq of name.
686                  * find the second name.
687                  */
688                 while ((second < line + llen) && isspace(*second))
689                         second++;
691                 if (line + llen <= second)
692                         goto free_and_fail1;
693                 if (*second == '"') {
694                         if (unquote_c_style(&sp, second, NULL))
695                                 goto free_and_fail1;
696                         cp = stop_at_slash(sp.buf, sp.len);
697                         if (!cp || cp == sp.buf)
698                                 goto free_and_fail1;
699                         /* They must match, otherwise ignore */
700                         if (strcmp(cp + 1, first.buf))
701                                 goto free_and_fail1;
702                         strbuf_release(&sp);
703                         return strbuf_detach(&first, NULL);
704                 }
706                 /* unquoted second */
707                 cp = stop_at_slash(second, line + llen - second);
708                 if (!cp || cp == second)
709                         goto free_and_fail1;
710                 cp++;
711                 if (line + llen - cp != first.len + 1 ||
712                     memcmp(first.buf, cp, first.len))
713                         goto free_and_fail1;
714                 return strbuf_detach(&first, NULL);
716         free_and_fail1:
717                 strbuf_release(&first);
718                 strbuf_release(&sp);
719                 return NULL;
720         }
722         /* unquoted first name */
723         name = stop_at_slash(line, llen);
724         if (!name || name == line)
725                 return NULL;
726         name++;
728         /*
729          * since the first name is unquoted, a dq if exists must be
730          * the beginning of the second name.
731          */
732         for (second = name; second < line + llen; second++) {
733                 if (*second == '"') {
734                         struct strbuf sp;
735                         const char *np;
737                         strbuf_init(&sp, 0);
738                         if (unquote_c_style(&sp, second, NULL))
739                                 goto free_and_fail2;
741                         np = stop_at_slash(sp.buf, sp.len);
742                         if (!np || np == sp.buf)
743                                 goto free_and_fail2;
744                         np++;
746                         len = sp.buf + sp.len - np;
747                         if (len < second - name &&
748                             !strncmp(np, name, len) &&
749                             isspace(name[len])) {
750                                 /* Good */
751                                 strbuf_remove(&sp, 0, np - sp.buf);
752                                 return strbuf_detach(&sp, NULL);
753                         }
755                 free_and_fail2:
756                         strbuf_release(&sp);
757                         return NULL;
758                 }
759         }
761         /*
762          * Accept a name only if it shows up twice, exactly the same
763          * form.
764          */
765         for (len = 0 ; ; len++) {
766                 switch (name[len]) {
767                 default:
768                         continue;
769                 case '\n':
770                         return NULL;
771                 case '\t': case ' ':
772                         second = name+len;
773                         for (;;) {
774                                 char c = *second++;
775                                 if (c == '\n')
776                                         return NULL;
777                                 if (c == '/')
778                                         break;
779                         }
780                         if (second[len] == '\n' && !memcmp(name, second, len)) {
781                                 return xmemdupz(name, len);
782                         }
783                 }
784         }
787 /* Verify that we recognize the lines following a git header */
788 static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
790         unsigned long offset;
792         /* A git diff has explicit new/delete information, so we don't guess */
793         patch->is_new = 0;
794         patch->is_delete = 0;
796         /*
797          * Some things may not have the old name in the
798          * rest of the headers anywhere (pure mode changes,
799          * or removing or adding empty files), so we get
800          * the default name from the header.
801          */
802         patch->def_name = git_header_name(line, len);
804         line += len;
805         size -= len;
806         linenr++;
807         for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
808                 static const struct opentry {
809                         const char *str;
810                         int (*fn)(const char *, struct patch *);
811                 } optable[] = {
812                         { "@@ -", gitdiff_hdrend },
813                         { "--- ", gitdiff_oldname },
814                         { "+++ ", gitdiff_newname },
815                         { "old mode ", gitdiff_oldmode },
816                         { "new mode ", gitdiff_newmode },
817                         { "deleted file mode ", gitdiff_delete },
818                         { "new file mode ", gitdiff_newfile },
819                         { "copy from ", gitdiff_copysrc },
820                         { "copy to ", gitdiff_copydst },
821                         { "rename old ", gitdiff_renamesrc },
822                         { "rename new ", gitdiff_renamedst },
823                         { "rename from ", gitdiff_renamesrc },
824                         { "rename to ", gitdiff_renamedst },
825                         { "similarity index ", gitdiff_similarity },
826                         { "dissimilarity index ", gitdiff_dissimilarity },
827                         { "index ", gitdiff_index },
828                         { "", gitdiff_unrecognized },
829                 };
830                 int i;
832                 len = linelen(line, size);
833                 if (!len || line[len-1] != '\n')
834                         break;
835                 for (i = 0; i < ARRAY_SIZE(optable); i++) {
836                         const struct opentry *p = optable + i;
837                         int oplen = strlen(p->str);
838                         if (len < oplen || memcmp(p->str, line, oplen))
839                                 continue;
840                         if (p->fn(line + oplen, patch) < 0)
841                                 return offset;
842                         break;
843                 }
844         }
846         return offset;
849 static int parse_num(const char *line, unsigned long *p)
851         char *ptr;
853         if (!isdigit(*line))
854                 return 0;
855         *p = strtoul(line, &ptr, 10);
856         return ptr - line;
859 static int parse_range(const char *line, int len, int offset, const char *expect,
860                        unsigned long *p1, unsigned long *p2)
862         int digits, ex;
864         if (offset < 0 || offset >= len)
865                 return -1;
866         line += offset;
867         len -= offset;
869         digits = parse_num(line, p1);
870         if (!digits)
871                 return -1;
873         offset += digits;
874         line += digits;
875         len -= digits;
877         *p2 = 1;
878         if (*line == ',') {
879                 digits = parse_num(line+1, p2);
880                 if (!digits)
881                         return -1;
883                 offset += digits+1;
884                 line += digits+1;
885                 len -= digits+1;
886         }
888         ex = strlen(expect);
889         if (ex > len)
890                 return -1;
891         if (memcmp(line, expect, ex))
892                 return -1;
894         return offset + ex;
897 /*
898  * Parse a unified diff fragment header of the
899  * form "@@ -a,b +c,d @@"
900  */
901 static int parse_fragment_header(char *line, int len, struct fragment *fragment)
903         int offset;
905         if (!len || line[len-1] != '\n')
906                 return -1;
908         /* Figure out the number of lines in a fragment */
909         offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
910         offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
912         return offset;
915 static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
917         unsigned long offset, len;
919         patch->is_toplevel_relative = 0;
920         patch->is_rename = patch->is_copy = 0;
921         patch->is_new = patch->is_delete = -1;
922         patch->old_mode = patch->new_mode = 0;
923         patch->old_name = patch->new_name = NULL;
924         for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
925                 unsigned long nextlen;
927                 len = linelen(line, size);
928                 if (!len)
929                         break;
931                 /* Testing this early allows us to take a few shortcuts.. */
932                 if (len < 6)
933                         continue;
935                 /*
936                  * Make sure we don't find any unconnected patch fragments.
937                  * That's a sign that we didn't find a header, and that a
938                  * patch has become corrupted/broken up.
939                  */
940                 if (!memcmp("@@ -", line, 4)) {
941                         struct fragment dummy;
942                         if (parse_fragment_header(line, len, &dummy) < 0)
943                                 continue;
944                         die("patch fragment without header at line %d: %.*s",
945                             linenr, (int)len-1, line);
946                 }
948                 if (size < len + 6)
949                         break;
951                 /*
952                  * Git patch? It might not have a real patch, just a rename
953                  * or mode change, so we handle that specially
954                  */
955                 if (!memcmp("diff --git ", line, 11)) {
956                         int git_hdr_len = parse_git_header(line, len, size, patch);
957                         if (git_hdr_len <= len)
958                                 continue;
959                         if (!patch->old_name && !patch->new_name) {
960                                 if (!patch->def_name)
961                                         die("git diff header lacks filename information (line %d)", linenr);
962                                 patch->old_name = patch->new_name = patch->def_name;
963                         }
964                         patch->is_toplevel_relative = 1;
965                         *hdrsize = git_hdr_len;
966                         return offset;
967                 }
969                 /* --- followed by +++ ? */
970                 if (memcmp("--- ", line,  4) || memcmp("+++ ", line + len, 4))
971                         continue;
973                 /*
974                  * We only accept unified patches, so we want it to
975                  * at least have "@@ -a,b +c,d @@\n", which is 14 chars
976                  * minimum ("@@ -0,0 +1 @@\n" is the shortest).
977                  */
978                 nextlen = linelen(line + len, size - len);
979                 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
980                         continue;
982                 /* Ok, we'll consider it a patch */
983                 parse_traditional_patch(line, line+len, patch);
984                 *hdrsize = len + nextlen;
985                 linenr += 2;
986                 return offset;
987         }
988         return -1;
991 static void check_whitespace(const char *line, int len, unsigned ws_rule)
993         char *err;
994         unsigned result = check_and_emit_line(line + 1, len - 1, ws_rule,
995             NULL, NULL, NULL, NULL);
996         if (!result)
997                 return;
999         whitespace_error++;
1000         if (squelch_whitespace_errors &&
1001             squelch_whitespace_errors < whitespace_error)
1002                 ;
1003         else {
1004                 err = whitespace_error_string(result);
1005                 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1006                      patch_input_file, linenr, err, len - 2, line + 1);
1007                 free(err);
1008         }
1011 /*
1012  * Parse a unified diff. Note that this really needs to parse each
1013  * fragment separately, since the only way to know the difference
1014  * between a "---" that is part of a patch, and a "---" that starts
1015  * the next patch is to look at the line counts..
1016  */
1017 static int parse_fragment(char *line, unsigned long size,
1018                           struct patch *patch, struct fragment *fragment)
1020         int added, deleted;
1021         int len = linelen(line, size), offset;
1022         unsigned long oldlines, newlines;
1023         unsigned long leading, trailing;
1025         offset = parse_fragment_header(line, len, fragment);
1026         if (offset < 0)
1027                 return -1;
1028         oldlines = fragment->oldlines;
1029         newlines = fragment->newlines;
1030         leading = 0;
1031         trailing = 0;
1033         /* Parse the thing.. */
1034         line += len;
1035         size -= len;
1036         linenr++;
1037         added = deleted = 0;
1038         for (offset = len;
1039              0 < size;
1040              offset += len, size -= len, line += len, linenr++) {
1041                 if (!oldlines && !newlines)
1042                         break;
1043                 len = linelen(line, size);
1044                 if (!len || line[len-1] != '\n')
1045                         return -1;
1046                 switch (*line) {
1047                 default:
1048                         return -1;
1049                 case '\n': /* newer GNU diff, an empty context line */
1050                 case ' ':
1051                         oldlines--;
1052                         newlines--;
1053                         if (!deleted && !added)
1054                                 leading++;
1055                         trailing++;
1056                         break;
1057                 case '-':
1058                         if (apply_in_reverse &&
1059                             ws_error_action != nowarn_ws_error)
1060                                 check_whitespace(line, len, patch->ws_rule);
1061                         deleted++;
1062                         oldlines--;
1063                         trailing = 0;
1064                         break;
1065                 case '+':
1066                         if (!apply_in_reverse &&
1067                             ws_error_action != nowarn_ws_error)
1068                                 check_whitespace(line, len, patch->ws_rule);
1069                         added++;
1070                         newlines--;
1071                         trailing = 0;
1072                         break;
1074                 /*
1075                  * We allow "\ No newline at end of file". Depending
1076                  * on locale settings when the patch was produced we
1077                  * don't know what this line looks like. The only
1078                  * thing we do know is that it begins with "\ ".
1079                  * Checking for 12 is just for sanity check -- any
1080                  * l10n of "\ No newline..." is at least that long.
1081                  */
1082                 case '\\':
1083                         if (len < 12 || memcmp(line, "\\ ", 2))
1084                                 return -1;
1085                         break;
1086                 }
1087         }
1088         if (oldlines || newlines)
1089                 return -1;
1090         fragment->leading = leading;
1091         fragment->trailing = trailing;
1093         /*
1094          * If a fragment ends with an incomplete line, we failed to include
1095          * it in the above loop because we hit oldlines == newlines == 0
1096          * before seeing it.
1097          */
1098         if (12 < size && !memcmp(line, "\\ ", 2))
1099                 offset += linelen(line, size);
1101         patch->lines_added += added;
1102         patch->lines_deleted += deleted;
1104         if (0 < patch->is_new && oldlines)
1105                 return error("new file depends on old contents");
1106         if (0 < patch->is_delete && newlines)
1107                 return error("deleted file still has contents");
1108         return offset;
1111 static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
1113         unsigned long offset = 0;
1114         unsigned long oldlines = 0, newlines = 0, context = 0;
1115         struct fragment **fragp = &patch->fragments;
1117         while (size > 4 && !memcmp(line, "@@ -", 4)) {
1118                 struct fragment *fragment;
1119                 int len;
1121                 fragment = xcalloc(1, sizeof(*fragment));
1122                 len = parse_fragment(line, size, patch, fragment);
1123                 if (len <= 0)
1124                         die("corrupt patch at line %d", linenr);
1125                 fragment->patch = line;
1126                 fragment->size = len;
1127                 oldlines += fragment->oldlines;
1128                 newlines += fragment->newlines;
1129                 context += fragment->leading + fragment->trailing;
1131                 *fragp = fragment;
1132                 fragp = &fragment->next;
1134                 offset += len;
1135                 line += len;
1136                 size -= len;
1137         }
1139         /*
1140          * If something was removed (i.e. we have old-lines) it cannot
1141          * be creation, and if something was added it cannot be
1142          * deletion.  However, the reverse is not true; --unified=0
1143          * patches that only add are not necessarily creation even
1144          * though they do not have any old lines, and ones that only
1145          * delete are not necessarily deletion.
1146          *
1147          * Unfortunately, a real creation/deletion patch do _not_ have
1148          * any context line by definition, so we cannot safely tell it
1149          * apart with --unified=0 insanity.  At least if the patch has
1150          * more than one hunk it is not creation or deletion.
1151          */
1152         if (patch->is_new < 0 &&
1153             (oldlines || (patch->fragments && patch->fragments->next)))
1154                 patch->is_new = 0;
1155         if (patch->is_delete < 0 &&
1156             (newlines || (patch->fragments && patch->fragments->next)))
1157                 patch->is_delete = 0;
1159         if (0 < patch->is_new && oldlines)
1160                 die("new file %s depends on old contents", patch->new_name);
1161         if (0 < patch->is_delete && newlines)
1162                 die("deleted file %s still has contents", patch->old_name);
1163         if (!patch->is_delete && !newlines && context)
1164                 fprintf(stderr, "** warning: file %s becomes empty but "
1165                         "is not deleted\n", patch->new_name);
1167         return offset;
1170 static inline int metadata_changes(struct patch *patch)
1172         return  patch->is_rename > 0 ||
1173                 patch->is_copy > 0 ||
1174                 patch->is_new > 0 ||
1175                 patch->is_delete ||
1176                 (patch->old_mode && patch->new_mode &&
1177                  patch->old_mode != patch->new_mode);
1180 static char *inflate_it(const void *data, unsigned long size,
1181                         unsigned long inflated_size)
1183         z_stream stream;
1184         void *out;
1185         int st;
1187         memset(&stream, 0, sizeof(stream));
1189         stream.next_in = (unsigned char *)data;
1190         stream.avail_in = size;
1191         stream.next_out = out = xmalloc(inflated_size);
1192         stream.avail_out = inflated_size;
1193         inflateInit(&stream);
1194         st = inflate(&stream, Z_FINISH);
1195         if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1196                 free(out);
1197                 return NULL;
1198         }
1199         return out;
1202 static struct fragment *parse_binary_hunk(char **buf_p,
1203                                           unsigned long *sz_p,
1204                                           int *status_p,
1205                                           int *used_p)
1207         /*
1208          * Expect a line that begins with binary patch method ("literal"
1209          * or "delta"), followed by the length of data before deflating.
1210          * a sequence of 'length-byte' followed by base-85 encoded data
1211          * should follow, terminated by a newline.
1212          *
1213          * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1214          * and we would limit the patch line to 66 characters,
1215          * so one line can fit up to 13 groups that would decode
1216          * to 52 bytes max.  The length byte 'A'-'Z' corresponds
1217          * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1218          */
1219         int llen, used;
1220         unsigned long size = *sz_p;
1221         char *buffer = *buf_p;
1222         int patch_method;
1223         unsigned long origlen;
1224         char *data = NULL;
1225         int hunk_size = 0;
1226         struct fragment *frag;
1228         llen = linelen(buffer, size);
1229         used = llen;
1231         *status_p = 0;
1233         if (!prefixcmp(buffer, "delta ")) {
1234                 patch_method = BINARY_DELTA_DEFLATED;
1235                 origlen = strtoul(buffer + 6, NULL, 10);
1236         }
1237         else if (!prefixcmp(buffer, "literal ")) {
1238                 patch_method = BINARY_LITERAL_DEFLATED;
1239                 origlen = strtoul(buffer + 8, NULL, 10);
1240         }
1241         else
1242                 return NULL;
1244         linenr++;
1245         buffer += llen;
1246         while (1) {
1247                 int byte_length, max_byte_length, newsize;
1248                 llen = linelen(buffer, size);
1249                 used += llen;
1250                 linenr++;
1251                 if (llen == 1) {
1252                         /* consume the blank line */
1253                         buffer++;
1254                         size--;
1255                         break;
1256                 }
1257                 /*
1258                  * Minimum line is "A00000\n" which is 7-byte long,
1259                  * and the line length must be multiple of 5 plus 2.
1260                  */
1261                 if ((llen < 7) || (llen-2) % 5)
1262                         goto corrupt;
1263                 max_byte_length = (llen - 2) / 5 * 4;
1264                 byte_length = *buffer;
1265                 if ('A' <= byte_length && byte_length <= 'Z')
1266                         byte_length = byte_length - 'A' + 1;
1267                 else if ('a' <= byte_length && byte_length <= 'z')
1268                         byte_length = byte_length - 'a' + 27;
1269                 else
1270                         goto corrupt;
1271                 /* if the input length was not multiple of 4, we would
1272                  * have filler at the end but the filler should never
1273                  * exceed 3 bytes
1274                  */
1275                 if (max_byte_length < byte_length ||
1276                     byte_length <= max_byte_length - 4)
1277                         goto corrupt;
1278                 newsize = hunk_size + byte_length;
1279                 data = xrealloc(data, newsize);
1280                 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1281                         goto corrupt;
1282                 hunk_size = newsize;
1283                 buffer += llen;
1284                 size -= llen;
1285         }
1287         frag = xcalloc(1, sizeof(*frag));
1288         frag->patch = inflate_it(data, hunk_size, origlen);
1289         if (!frag->patch)
1290                 goto corrupt;
1291         free(data);
1292         frag->size = origlen;
1293         *buf_p = buffer;
1294         *sz_p = size;
1295         *used_p = used;
1296         frag->binary_patch_method = patch_method;
1297         return frag;
1299  corrupt:
1300         free(data);
1301         *status_p = -1;
1302         error("corrupt binary patch at line %d: %.*s",
1303               linenr-1, llen-1, buffer);
1304         return NULL;
1307 static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1309         /*
1310          * We have read "GIT binary patch\n"; what follows is a line
1311          * that says the patch method (currently, either "literal" or
1312          * "delta") and the length of data before deflating; a
1313          * sequence of 'length-byte' followed by base-85 encoded data
1314          * follows.
1315          *
1316          * When a binary patch is reversible, there is another binary
1317          * hunk in the same format, starting with patch method (either
1318          * "literal" or "delta") with the length of data, and a sequence
1319          * of length-byte + base-85 encoded data, terminated with another
1320          * empty line.  This data, when applied to the postimage, produces
1321          * the preimage.
1322          */
1323         struct fragment *forward;
1324         struct fragment *reverse;
1325         int status;
1326         int used, used_1;
1328         forward = parse_binary_hunk(&buffer, &size, &status, &used);
1329         if (!forward && !status)
1330                 /* there has to be one hunk (forward hunk) */
1331                 return error("unrecognized binary patch at line %d", linenr-1);
1332         if (status)
1333                 /* otherwise we already gave an error message */
1334                 return status;
1336         reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1337         if (reverse)
1338                 used += used_1;
1339         else if (status) {
1340                 /*
1341                  * Not having reverse hunk is not an error, but having
1342                  * a corrupt reverse hunk is.
1343                  */
1344                 free((void*) forward->patch);
1345                 free(forward);
1346                 return status;
1347         }
1348         forward->next = reverse;
1349         patch->fragments = forward;
1350         patch->is_binary = 1;
1351         return used;
1354 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
1356         int hdrsize, patchsize;
1357         int offset = find_header(buffer, size, &hdrsize, patch);
1359         if (offset < 0)
1360                 return offset;
1362         patch->ws_rule = whitespace_rule(patch->new_name
1363                                          ? patch->new_name
1364                                          : patch->old_name);
1366         patchsize = parse_single_patch(buffer + offset + hdrsize,
1367                                        size - offset - hdrsize, patch);
1369         if (!patchsize) {
1370                 static const char *binhdr[] = {
1371                         "Binary files ",
1372                         "Files ",
1373                         NULL,
1374                 };
1375                 static const char git_binary[] = "GIT binary patch\n";
1376                 int i;
1377                 int hd = hdrsize + offset;
1378                 unsigned long llen = linelen(buffer + hd, size - hd);
1380                 if (llen == sizeof(git_binary) - 1 &&
1381                     !memcmp(git_binary, buffer + hd, llen)) {
1382                         int used;
1383                         linenr++;
1384                         used = parse_binary(buffer + hd + llen,
1385                                             size - hd - llen, patch);
1386                         if (used)
1387                                 patchsize = used + llen;
1388                         else
1389                                 patchsize = 0;
1390                 }
1391                 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
1392                         for (i = 0; binhdr[i]; i++) {
1393                                 int len = strlen(binhdr[i]);
1394                                 if (len < size - hd &&
1395                                     !memcmp(binhdr[i], buffer + hd, len)) {
1396                                         linenr++;
1397                                         patch->is_binary = 1;
1398                                         patchsize = llen;
1399                                         break;
1400                                 }
1401                         }
1402                 }
1404                 /* Empty patch cannot be applied if it is a text patch
1405                  * without metadata change.  A binary patch appears
1406                  * empty to us here.
1407                  */
1408                 if ((apply || check) &&
1409                     (!patch->is_binary && !metadata_changes(patch)))
1410                         die("patch with only garbage at line %d", linenr);
1411         }
1413         return offset + hdrsize + patchsize;
1416 #define swap(a,b) myswap((a),(b),sizeof(a))
1418 #define myswap(a, b, size) do {         \
1419         unsigned char mytmp[size];      \
1420         memcpy(mytmp, &a, size);                \
1421         memcpy(&a, &b, size);           \
1422         memcpy(&b, mytmp, size);                \
1423 } while (0)
1425 static void reverse_patches(struct patch *p)
1427         for (; p; p = p->next) {
1428                 struct fragment *frag = p->fragments;
1430                 swap(p->new_name, p->old_name);
1431                 swap(p->new_mode, p->old_mode);
1432                 swap(p->is_new, p->is_delete);
1433                 swap(p->lines_added, p->lines_deleted);
1434                 swap(p->old_sha1_prefix, p->new_sha1_prefix);
1436                 for (; frag; frag = frag->next) {
1437                         swap(frag->newpos, frag->oldpos);
1438                         swap(frag->newlines, frag->oldlines);
1439                 }
1440         }
1443 static const char pluses[] =
1444 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1445 static const char minuses[]=
1446 "----------------------------------------------------------------------";
1448 static void show_stats(struct patch *patch)
1450         struct strbuf qname;
1451         char *cp = patch->new_name ? patch->new_name : patch->old_name;
1452         int max, add, del;
1454         strbuf_init(&qname, 0);
1455         quote_c_style(cp, &qname, NULL, 0);
1457         /*
1458          * "scale" the filename
1459          */
1460         max = max_len;
1461         if (max > 50)
1462                 max = 50;
1464         if (qname.len > max) {
1465                 cp = strchr(qname.buf + qname.len + 3 - max, '/');
1466                 if (!cp)
1467                         cp = qname.buf + qname.len + 3 - max;
1468                 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
1469         }
1471         if (patch->is_binary) {
1472                 printf(" %-*s |  Bin\n", max, qname.buf);
1473                 strbuf_release(&qname);
1474                 return;
1475         }
1477         printf(" %-*s |", max, qname.buf);
1478         strbuf_release(&qname);
1480         /*
1481          * scale the add/delete
1482          */
1483         max = max + max_change > 70 ? 70 - max : max_change;
1484         add = patch->lines_added;
1485         del = patch->lines_deleted;
1487         if (max_change > 0) {
1488                 int total = ((add + del) * max + max_change / 2) / max_change;
1489                 add = (add * max + max_change / 2) / max_change;
1490                 del = total - add;
1491         }
1492         printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
1493                 add, pluses, del, minuses);
1496 static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
1498         switch (st->st_mode & S_IFMT) {
1499         case S_IFLNK:
1500                 strbuf_grow(buf, st->st_size);
1501                 if (readlink(path, buf->buf, st->st_size) != st->st_size)
1502                         return -1;
1503                 strbuf_setlen(buf, st->st_size);
1504                 return 0;
1505         case S_IFREG:
1506                 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
1507                         return error("unable to open or read %s", path);
1508                 convert_to_git(path, buf->buf, buf->len, buf, 0);
1509                 return 0;
1510         default:
1511                 return -1;
1512         }
1515 static void update_pre_post_images(struct image *preimage,
1516                                    struct image *postimage,
1517                                    char *buf,
1518                                    size_t len)
1520         int i, ctx;
1521         char *new, *old, *fixed;
1522         struct image fixed_preimage;
1524         /*
1525          * Update the preimage with whitespace fixes.  Note that we
1526          * are not losing preimage->buf -- apply_one_fragment() will
1527          * free "oldlines".
1528          */
1529         prepare_image(&fixed_preimage, buf, len, 1);
1530         assert(fixed_preimage.nr == preimage->nr);
1531         for (i = 0; i < preimage->nr; i++)
1532                 fixed_preimage.line[i].flag = preimage->line[i].flag;
1533         free(preimage->line_allocated);
1534         *preimage = fixed_preimage;
1536         /*
1537          * Adjust the common context lines in postimage, in place.
1538          * This is possible because whitespace fixing does not make
1539          * the string grow.
1540          */
1541         new = old = postimage->buf;
1542         fixed = preimage->buf;
1543         for (i = ctx = 0; i < postimage->nr; i++) {
1544                 size_t len = postimage->line[i].len;
1545                 if (!(postimage->line[i].flag & LINE_COMMON)) {
1546                         /* an added line -- no counterparts in preimage */
1547                         memmove(new, old, len);
1548                         old += len;
1549                         new += len;
1550                         continue;
1551                 }
1553                 /* a common context -- skip it in the original postimage */
1554                 old += len;
1556                 /* and find the corresponding one in the fixed preimage */
1557                 while (ctx < preimage->nr &&
1558                        !(preimage->line[ctx].flag & LINE_COMMON)) {
1559                         fixed += preimage->line[ctx].len;
1560                         ctx++;
1561                 }
1562                 if (preimage->nr <= ctx)
1563                         die("oops");
1565                 /* and copy it in, while fixing the line length */
1566                 len = preimage->line[ctx].len;
1567                 memcpy(new, fixed, len);
1568                 new += len;
1569                 fixed += len;
1570                 postimage->line[i].len = len;
1571                 ctx++;
1572         }
1574         /* Fix the length of the whole thing */
1575         postimage->len = new - postimage->buf;
1578 static int match_fragment(struct image *img,
1579                           struct image *preimage,
1580                           struct image *postimage,
1581                           unsigned long try,
1582                           int try_lno,
1583                           unsigned ws_rule,
1584                           int match_beginning, int match_end)
1586         int i;
1587         char *fixed_buf, *buf, *orig, *target;
1589         if (preimage->nr + try_lno > img->nr)
1590                 return 0;
1592         if (match_beginning && try_lno)
1593                 return 0;
1595         if (match_end && preimage->nr + try_lno != img->nr)
1596                 return 0;
1598         /* Quick hash check */
1599         for (i = 0; i < preimage->nr; i++)
1600                 if (preimage->line[i].hash != img->line[try_lno + i].hash)
1601                         return 0;
1603         /*
1604          * Do we have an exact match?  If we were told to match
1605          * at the end, size must be exactly at try+fragsize,
1606          * otherwise try+fragsize must be still within the preimage,
1607          * and either case, the old piece should match the preimage
1608          * exactly.
1609          */
1610         if ((match_end
1611              ? (try + preimage->len == img->len)
1612              : (try + preimage->len <= img->len)) &&
1613             !memcmp(img->buf + try, preimage->buf, preimage->len))
1614                 return 1;
1616         if (ws_error_action != correct_ws_error)
1617                 return 0;
1619         /*
1620          * The hunk does not apply byte-by-byte, but the hash says
1621          * it might with whitespace fuzz.
1622          */
1623         fixed_buf = xmalloc(preimage->len + 1);
1624         buf = fixed_buf;
1625         orig = preimage->buf;
1626         target = img->buf + try;
1627         for (i = 0; i < preimage->nr; i++) {
1628                 size_t fixlen; /* length after fixing the preimage */
1629                 size_t oldlen = preimage->line[i].len;
1630                 size_t tgtlen = img->line[try_lno + i].len;
1631                 size_t tgtfixlen; /* length after fixing the target line */
1632                 char tgtfixbuf[1024], *tgtfix;
1633                 int match;
1635                 /* Try fixing the line in the preimage */
1636                 fixlen = ws_fix_copy(buf, orig, oldlen, ws_rule, NULL);
1638                 /* Try fixing the line in the target */
1639                 if (sizeof(tgtfixbuf) < tgtlen)
1640                         tgtfix = tgtfixbuf;
1641                 else
1642                         tgtfix = xmalloc(tgtlen);
1643                 tgtfixlen = ws_fix_copy(tgtfix, target, tgtlen, ws_rule, NULL);
1645                 /*
1646                  * If they match, either the preimage was based on
1647                  * a version before our tree fixed whitespace breakage,
1648                  * or we are lacking a whitespace-fix patch the tree
1649                  * the preimage was based on already had (i.e. target
1650                  * has whitespace breakage, the preimage doesn't).
1651                  * In either case, we are fixing the whitespace breakages
1652                  * so we might as well take the fix together with their
1653                  * real change.
1654                  */
1655                 match = (tgtfixlen == fixlen && !memcmp(tgtfix, buf, fixlen));
1657                 if (tgtfix != tgtfixbuf)
1658                         free(tgtfix);
1659                 if (!match)
1660                         goto unmatch_exit;
1662                 orig += oldlen;
1663                 buf += fixlen;
1664                 target += tgtlen;
1665         }
1667         /*
1668          * Yes, the preimage is based on an older version that still
1669          * has whitespace breakages unfixed, and fixing them makes the
1670          * hunk match.  Update the context lines in the postimage.
1671          */
1672         update_pre_post_images(preimage, postimage,
1673                                fixed_buf, buf - fixed_buf);
1674         return 1;
1676  unmatch_exit:
1677         free(fixed_buf);
1678         return 0;
1681 static int find_pos(struct image *img,
1682                     struct image *preimage,
1683                     struct image *postimage,
1684                     int line,
1685                     unsigned ws_rule,
1686                     int match_beginning, int match_end)
1688         int i;
1689         unsigned long backwards, forwards, try;
1690         int backwards_lno, forwards_lno, try_lno;
1692         if (preimage->nr > img->nr)
1693                 return -1;
1695         /*
1696          * If match_begining or match_end is specified, there is no
1697          * point starting from a wrong line that will never match and
1698          * wander around and wait for a match at the specified end.
1699          */
1700         if (match_beginning)
1701                 line = 0;
1702         else if (match_end)
1703                 line = img->nr - preimage->nr;
1705         if (line > img->nr)
1706                 line = img->nr;
1708         try = 0;
1709         for (i = 0; i < line; i++)
1710                 try += img->line[i].len;
1712         /*
1713          * There's probably some smart way to do this, but I'll leave
1714          * that to the smart and beautiful people. I'm simple and stupid.
1715          */
1716         backwards = try;
1717         backwards_lno = line;
1718         forwards = try;
1719         forwards_lno = line;
1720         try_lno = line;
1722         for (i = 0; ; i++) {
1723                 if (match_fragment(img, preimage, postimage,
1724                                    try, try_lno, ws_rule,
1725                                    match_beginning, match_end))
1726                         return try_lno;
1728         again:
1729                 if (backwards_lno == 0 && forwards_lno == img->nr)
1730                         break;
1732                 if (i & 1) {
1733                         if (backwards_lno == 0) {
1734                                 i++;
1735                                 goto again;
1736                         }
1737                         backwards_lno--;
1738                         backwards -= img->line[backwards_lno].len;
1739                         try = backwards;
1740                         try_lno = backwards_lno;
1741                 } else {
1742                         if (forwards_lno == img->nr) {
1743                                 i++;
1744                                 goto again;
1745                         }
1746                         forwards += img->line[forwards_lno].len;
1747                         forwards_lno++;
1748                         try = forwards;
1749                         try_lno = forwards_lno;
1750                 }
1752         }
1753         return -1;
1756 static void remove_first_line(struct image *img)
1758         img->buf += img->line[0].len;
1759         img->len -= img->line[0].len;
1760         img->line++;
1761         img->nr--;
1764 static void remove_last_line(struct image *img)
1766         img->len -= img->line[--img->nr].len;
1769 static void update_image(struct image *img,
1770                          int applied_pos,
1771                          struct image *preimage,
1772                          struct image *postimage)
1774         /*
1775          * remove the copy of preimage at offset in img
1776          * and replace it with postimage
1777          */
1778         int i, nr;
1779         size_t remove_count, insert_count, applied_at = 0;
1780         char *result;
1782         for (i = 0; i < applied_pos; i++)
1783                 applied_at += img->line[i].len;
1785         remove_count = 0;
1786         for (i = 0; i < preimage->nr; i++)
1787                 remove_count += img->line[applied_pos + i].len;
1788         insert_count = postimage->len;
1790         /* Adjust the contents */
1791         result = xmalloc(img->len + insert_count - remove_count + 1);
1792         memcpy(result, img->buf, applied_at);
1793         memcpy(result + applied_at, postimage->buf, postimage->len);
1794         memcpy(result + applied_at + postimage->len,
1795                img->buf + (applied_at + remove_count),
1796                img->len - (applied_at + remove_count));
1797         free(img->buf);
1798         img->buf = result;
1799         img->len += insert_count - remove_count;
1800         result[img->len] = '\0';
1802         /* Adjust the line table */
1803         nr = img->nr + postimage->nr - preimage->nr;
1804         if (preimage->nr < postimage->nr) {
1805                 /*
1806                  * NOTE: this knows that we never call remove_first_line()
1807                  * on anything other than pre/post image.
1808                  */
1809                 img->line = xrealloc(img->line, nr * sizeof(*img->line));
1810                 img->line_allocated = img->line;
1811         }
1812         if (preimage->nr != postimage->nr)
1813                 memmove(img->line + applied_pos + postimage->nr,
1814                         img->line + applied_pos + preimage->nr,
1815                         (img->nr - (applied_pos + preimage->nr)) *
1816                         sizeof(*img->line));
1817         memcpy(img->line + applied_pos,
1818                postimage->line,
1819                postimage->nr * sizeof(*img->line));
1820         img->nr = nr;
1823 static int apply_one_fragment(struct image *img, struct fragment *frag,
1824                               int inaccurate_eof, unsigned ws_rule)
1826         int match_beginning, match_end;
1827         const char *patch = frag->patch;
1828         int size = frag->size;
1829         char *old, *new, *oldlines, *newlines;
1830         int new_blank_lines_at_end = 0;
1831         unsigned long leading, trailing;
1832         int pos, applied_pos;
1833         struct image preimage;
1834         struct image postimage;
1836         memset(&preimage, 0, sizeof(preimage));
1837         memset(&postimage, 0, sizeof(postimage));
1838         oldlines = xmalloc(size);
1839         newlines = xmalloc(size);
1841         old = oldlines;
1842         new = newlines;
1843         while (size > 0) {
1844                 char first;
1845                 int len = linelen(patch, size);
1846                 int plen, added;
1847                 int added_blank_line = 0;
1849                 if (!len)
1850                         break;
1852                 /*
1853                  * "plen" is how much of the line we should use for
1854                  * the actual patch data. Normally we just remove the
1855                  * first character on the line, but if the line is
1856                  * followed by "\ No newline", then we also remove the
1857                  * last one (which is the newline, of course).
1858                  */
1859                 plen = len - 1;
1860                 if (len < size && patch[len] == '\\')
1861                         plen--;
1862                 first = *patch;
1863                 if (apply_in_reverse) {
1864                         if (first == '-')
1865                                 first = '+';
1866                         else if (first == '+')
1867                                 first = '-';
1868                 }
1870                 switch (first) {
1871                 case '\n':
1872                         /* Newer GNU diff, empty context line */
1873                         if (plen < 0)
1874                                 /* ... followed by '\No newline'; nothing */
1875                                 break;
1876                         *old++ = '\n';
1877                         *new++ = '\n';
1878                         add_line_info(&preimage, "\n", 1, LINE_COMMON);
1879                         add_line_info(&postimage, "\n", 1, LINE_COMMON);
1880                         break;
1881                 case ' ':
1882                 case '-':
1883                         memcpy(old, patch + 1, plen);
1884                         add_line_info(&preimage, old, plen,
1885                                       (first == ' ' ? LINE_COMMON : 0));
1886                         old += plen;
1887                         if (first == '-')
1888                                 break;
1889                 /* Fall-through for ' ' */
1890                 case '+':
1891                         /* --no-add does not add new lines */
1892                         if (first == '+' && no_add)
1893                                 break;
1895                         if (first != '+' ||
1896                             !whitespace_error ||
1897                             ws_error_action != correct_ws_error) {
1898                                 memcpy(new, patch + 1, plen);
1899                                 added = plen;
1900                         }
1901                         else {
1902                                 added = ws_fix_copy(new, patch + 1, plen, ws_rule, &applied_after_fixing_ws);
1903                         }
1904                         add_line_info(&postimage, new, added,
1905                                       (first == '+' ? 0 : LINE_COMMON));
1906                         new += added;
1907                         if (first == '+' &&
1908                             added == 1 && new[-1] == '\n')
1909                                 added_blank_line = 1;
1910                         break;
1911                 case '@': case '\\':
1912                         /* Ignore it, we already handled it */
1913                         break;
1914                 default:
1915                         if (apply_verbosely)
1916                                 error("invalid start of line: '%c'", first);
1917                         return -1;
1918                 }
1919                 if (added_blank_line)
1920                         new_blank_lines_at_end++;
1921                 else
1922                         new_blank_lines_at_end = 0;
1923                 patch += len;
1924                 size -= len;
1925         }
1926         if (inaccurate_eof &&
1927             old > oldlines && old[-1] == '\n' &&
1928             new > newlines && new[-1] == '\n') {
1929                 old--;
1930                 new--;
1931         }
1933         leading = frag->leading;
1934         trailing = frag->trailing;
1936         /*
1937          * A hunk to change lines at the beginning would begin with
1938          * @@ -1,L +N,M @@
1939          *
1940          * And a hunk to add to an empty file would begin with
1941          * @@ -0,0 +N,M @@
1942          *
1943          * In other words, a hunk that is (frag->oldpos <= 1) with or
1944          * without leading context must match at the beginning.
1945          */
1946         match_beginning = frag->oldpos <= 1;
1948         /*
1949          * A hunk without trailing lines must match at the end.
1950          * However, we simply cannot tell if a hunk must match end
1951          * from the lack of trailing lines if the patch was generated
1952          * with unidiff without any context.
1953          */
1954         match_end = !unidiff_zero && !trailing;
1956         pos = frag->newpos ? (frag->newpos - 1) : 0;
1957         preimage.buf = oldlines;
1958         preimage.len = old - oldlines;
1959         postimage.buf = newlines;
1960         postimage.len = new - newlines;
1961         preimage.line = preimage.line_allocated;
1962         postimage.line = postimage.line_allocated;
1964         for (;;) {
1966                 applied_pos = find_pos(img, &preimage, &postimage, pos,
1967                                        ws_rule, match_beginning, match_end);
1969                 if (applied_pos >= 0)
1970                         break;
1972                 /* Am I at my context limits? */
1973                 if ((leading <= p_context) && (trailing <= p_context))
1974                         break;
1975                 if (match_beginning || match_end) {
1976                         match_beginning = match_end = 0;
1977                         continue;
1978                 }
1980                 /*
1981                  * Reduce the number of context lines; reduce both
1982                  * leading and trailing if they are equal otherwise
1983                  * just reduce the larger context.
1984                  */
1985                 if (leading >= trailing) {
1986                         remove_first_line(&preimage);
1987                         remove_first_line(&postimage);
1988                         pos--;
1989                         leading--;
1990                 }
1991                 if (trailing > leading) {
1992                         remove_last_line(&preimage);
1993                         remove_last_line(&postimage);
1994                         trailing--;
1995                 }
1996         }
1998         if (applied_pos >= 0) {
1999                 if (ws_error_action == correct_ws_error &&
2000                     new_blank_lines_at_end &&
2001                     postimage.nr + applied_pos == img->nr) {
2002                         /*
2003                          * If the patch application adds blank lines
2004                          * at the end, and if the patch applies at the
2005                          * end of the image, remove those added blank
2006                          * lines.
2007                          */
2008                         while (new_blank_lines_at_end--)
2009                                 remove_last_line(&postimage);
2010                 }
2012                 /*
2013                  * Warn if it was necessary to reduce the number
2014                  * of context lines.
2015                  */
2016                 if ((leading != frag->leading) ||
2017                     (trailing != frag->trailing))
2018                         fprintf(stderr, "Context reduced to (%ld/%ld)"
2019                                 " to apply fragment at %d\n",
2020                                 leading, trailing, applied_pos+1);
2021                 update_image(img, applied_pos, &preimage, &postimage);
2022         } else {
2023                 if (apply_verbosely)
2024                         error("while searching for:\n%.*s",
2025                               (int)(old - oldlines), oldlines);
2026         }
2028         free(oldlines);
2029         free(newlines);
2030         free(preimage.line_allocated);
2031         free(postimage.line_allocated);
2033         return (applied_pos < 0);
2036 static int apply_binary_fragment(struct image *img, struct patch *patch)
2038         struct fragment *fragment = patch->fragments;
2039         unsigned long len;
2040         void *dst;
2042         /* Binary patch is irreversible without the optional second hunk */
2043         if (apply_in_reverse) {
2044                 if (!fragment->next)
2045                         return error("cannot reverse-apply a binary patch "
2046                                      "without the reverse hunk to '%s'",
2047                                      patch->new_name
2048                                      ? patch->new_name : patch->old_name);
2049                 fragment = fragment->next;
2050         }
2051         switch (fragment->binary_patch_method) {
2052         case BINARY_DELTA_DEFLATED:
2053                 dst = patch_delta(img->buf, img->len, fragment->patch,
2054                                   fragment->size, &len);
2055                 if (!dst)
2056                         return -1;
2057                 clear_image(img);
2058                 img->buf = dst;
2059                 img->len = len;
2060                 return 0;
2061         case BINARY_LITERAL_DEFLATED:
2062                 clear_image(img);
2063                 img->len = fragment->size;
2064                 img->buf = xmalloc(img->len+1);
2065                 memcpy(img->buf, fragment->patch, img->len);
2066                 img->buf[img->len] = '\0';
2067                 return 0;
2068         }
2069         return -1;
2072 static int apply_binary(struct image *img, struct patch *patch)
2074         const char *name = patch->old_name ? patch->old_name : patch->new_name;
2075         unsigned char sha1[20];
2077         /*
2078          * For safety, we require patch index line to contain
2079          * full 40-byte textual SHA1 for old and new, at least for now.
2080          */
2081         if (strlen(patch->old_sha1_prefix) != 40 ||
2082             strlen(patch->new_sha1_prefix) != 40 ||
2083             get_sha1_hex(patch->old_sha1_prefix, sha1) ||
2084             get_sha1_hex(patch->new_sha1_prefix, sha1))
2085                 return error("cannot apply binary patch to '%s' "
2086                              "without full index line", name);
2088         if (patch->old_name) {
2089                 /*
2090                  * See if the old one matches what the patch
2091                  * applies to.
2092                  */
2093                 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2094                 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
2095                         return error("the patch applies to '%s' (%s), "
2096                                      "which does not match the "
2097                                      "current contents.",
2098                                      name, sha1_to_hex(sha1));
2099         }
2100         else {
2101                 /* Otherwise, the old one must be empty. */
2102                 if (img->len)
2103                         return error("the patch applies to an empty "
2104                                      "'%s' but it is not empty", name);
2105         }
2107         get_sha1_hex(patch->new_sha1_prefix, sha1);
2108         if (is_null_sha1(sha1)) {
2109                 clear_image(img);
2110                 return 0; /* deletion patch */
2111         }
2113         if (has_sha1_file(sha1)) {
2114                 /* We already have the postimage */
2115                 enum object_type type;
2116                 unsigned long size;
2117                 char *result;
2119                 result = read_sha1_file(sha1, &type, &size);
2120                 if (!result)
2121                         return error("the necessary postimage %s for "
2122                                      "'%s' cannot be read",
2123                                      patch->new_sha1_prefix, name);
2124                 clear_image(img);
2125                 img->buf = result;
2126                 img->len = size;
2127         } else {
2128                 /*
2129                  * We have verified buf matches the preimage;
2130                  * apply the patch data to it, which is stored
2131                  * in the patch->fragments->{patch,size}.
2132                  */
2133                 if (apply_binary_fragment(img, patch))
2134                         return error("binary patch does not apply to '%s'",
2135                                      name);
2137                 /* verify that the result matches */
2138                 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2139                 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
2140                         return error("binary patch to '%s' creates incorrect result (expecting %s, got %s)",
2141                                 name, patch->new_sha1_prefix, sha1_to_hex(sha1));
2142         }
2144         return 0;
2147 static int apply_fragments(struct image *img, struct patch *patch)
2149         struct fragment *frag = patch->fragments;
2150         const char *name = patch->old_name ? patch->old_name : patch->new_name;
2151         unsigned ws_rule = patch->ws_rule;
2152         unsigned inaccurate_eof = patch->inaccurate_eof;
2154         if (patch->is_binary)
2155                 return apply_binary(img, patch);
2157         while (frag) {
2158                 if (apply_one_fragment(img, frag, inaccurate_eof, ws_rule)) {
2159                         error("patch failed: %s:%ld", name, frag->oldpos);
2160                         if (!apply_with_reject)
2161                                 return -1;
2162                         frag->rejected = 1;
2163                 }
2164                 frag = frag->next;
2165         }
2166         return 0;
2169 static int read_file_or_gitlink(struct cache_entry *ce, struct strbuf *buf)
2171         if (!ce)
2172                 return 0;
2174         if (S_ISGITLINK(ce->ce_mode)) {
2175                 strbuf_grow(buf, 100);
2176                 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(ce->sha1));
2177         } else {
2178                 enum object_type type;
2179                 unsigned long sz;
2180                 char *result;
2182                 result = read_sha1_file(ce->sha1, &type, &sz);
2183                 if (!result)
2184                         return -1;
2185                 /* XXX read_sha1_file NUL-terminates */
2186                 strbuf_attach(buf, result, sz, sz + 1);
2187         }
2188         return 0;
2191 static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce)
2193         struct strbuf buf;
2194         struct image image;
2195         size_t len;
2196         char *img;
2198         strbuf_init(&buf, 0);
2199         if (cached) {
2200                 if (read_file_or_gitlink(ce, &buf))
2201                         return error("read of %s failed", patch->old_name);
2202         } else if (patch->old_name) {
2203                 if (S_ISGITLINK(patch->old_mode)) {
2204                         if (ce) {
2205                                 read_file_or_gitlink(ce, &buf);
2206                         } else {
2207                                 /*
2208                                  * There is no way to apply subproject
2209                                  * patch without looking at the index.
2210                                  */
2211                                 patch->fragments = NULL;
2212                         }
2213                 } else {
2214                         if (read_old_data(st, patch->old_name, &buf))
2215                                 return error("read of %s failed", patch->old_name);
2216                 }
2217         }
2219         img = strbuf_detach(&buf, &len);
2220         prepare_image(&image, img, len, !patch->is_binary);
2222         if (apply_fragments(&image, patch) < 0)
2223                 return -1; /* note with --reject this succeeds. */
2224         patch->result = image.buf;
2225         patch->resultsize = image.len;
2226         free(image.line_allocated);
2228         if (0 < patch->is_delete && patch->resultsize)
2229                 return error("removal patch leaves file contents");
2231         return 0;
2234 static int check_to_create_blob(const char *new_name, int ok_if_exists)
2236         struct stat nst;
2237         if (!lstat(new_name, &nst)) {
2238                 if (S_ISDIR(nst.st_mode) || ok_if_exists)
2239                         return 0;
2240                 /*
2241                  * A leading component of new_name might be a symlink
2242                  * that is going to be removed with this patch, but
2243                  * still pointing at somewhere that has the path.
2244                  * In such a case, path "new_name" does not exist as
2245                  * far as git is concerned.
2246                  */
2247                 if (has_symlink_leading_path(strlen(new_name), new_name))
2248                         return 0;
2250                 return error("%s: already exists in working directory", new_name);
2251         }
2252         else if ((errno != ENOENT) && (errno != ENOTDIR))
2253                 return error("%s: %s", new_name, strerror(errno));
2254         return 0;
2257 static int verify_index_match(struct cache_entry *ce, struct stat *st)
2259         if (S_ISGITLINK(ce->ce_mode)) {
2260                 if (!S_ISDIR(st->st_mode))
2261                         return -1;
2262                 return 0;
2263         }
2264         return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID);
2267 static int check_preimage(struct patch *patch, struct cache_entry **ce, struct stat *st)
2269         const char *old_name = patch->old_name;
2270         int stat_ret = 0;
2271         unsigned st_mode = 0;
2273         /*
2274          * Make sure that we do not have local modifications from the
2275          * index when we are looking at the index.  Also make sure
2276          * we have the preimage file to be patched in the work tree,
2277          * unless --cached, which tells git to apply only in the index.
2278          */
2279         if (!old_name)
2280                 return 0;
2282         assert(patch->is_new <= 0);
2283         if (!cached) {
2284                 stat_ret = lstat(old_name, st);
2285                 if (stat_ret && errno != ENOENT)
2286                         return error("%s: %s", old_name, strerror(errno));
2287         }
2288         if (check_index) {
2289                 int pos = cache_name_pos(old_name, strlen(old_name));
2290                 if (pos < 0) {
2291                         if (patch->is_new < 0)
2292                                 goto is_new;
2293                         return error("%s: does not exist in index", old_name);
2294                 }
2295                 *ce = active_cache[pos];
2296                 if (stat_ret < 0) {
2297                         struct checkout costate;
2298                         /* checkout */
2299                         costate.base_dir = "";
2300                         costate.base_dir_len = 0;
2301                         costate.force = 0;
2302                         costate.quiet = 0;
2303                         costate.not_new = 0;
2304                         costate.refresh_cache = 1;
2305                         if (checkout_entry(*ce, &costate, NULL) ||
2306                             lstat(old_name, st))
2307                                 return -1;
2308                 }
2309                 if (!cached && verify_index_match(*ce, st))
2310                         return error("%s: does not match index", old_name);
2311                 if (cached)
2312                         st_mode = (*ce)->ce_mode;
2313         } else if (stat_ret < 0) {
2314                 if (patch->is_new < 0)
2315                         goto is_new;
2316                 return error("%s: %s", old_name, strerror(errno));
2317         }
2319         if (!cached)
2320                 st_mode = ce_mode_from_stat(*ce, st->st_mode);
2322         if (patch->is_new < 0)
2323                 patch->is_new = 0;
2324         if (!patch->old_mode)
2325                 patch->old_mode = st_mode;
2326         if ((st_mode ^ patch->old_mode) & S_IFMT)
2327                 return error("%s: wrong type", old_name);
2328         if (st_mode != patch->old_mode)
2329                 fprintf(stderr, "warning: %s has type %o, expected %o\n",
2330                         old_name, st_mode, patch->old_mode);
2331         return 0;
2333  is_new:
2334         patch->is_new = 1;
2335         patch->is_delete = 0;
2336         patch->old_name = NULL;
2337         return 0;
2340 static int check_patch(struct patch *patch, struct patch *prev_patch)
2342         struct stat st;
2343         const char *old_name = patch->old_name;
2344         const char *new_name = patch->new_name;
2345         const char *name = old_name ? old_name : new_name;
2346         struct cache_entry *ce = NULL;
2347         int ok_if_exists;
2348         int status;
2350         patch->rejected = 1; /* we will drop this after we succeed */
2352         status = check_preimage(patch, &ce, &st);
2353         if (status)
2354                 return status;
2355         old_name = patch->old_name;
2357         if (new_name && prev_patch && 0 < prev_patch->is_delete &&
2358             !strcmp(prev_patch->old_name, new_name))
2359                 /*
2360                  * A type-change diff is always split into a patch to
2361                  * delete old, immediately followed by a patch to
2362                  * create new (see diff.c::run_diff()); in such a case
2363                  * it is Ok that the entry to be deleted by the
2364                  * previous patch is still in the working tree and in
2365                  * the index.
2366                  */
2367                 ok_if_exists = 1;
2368         else
2369                 ok_if_exists = 0;
2371         if (new_name &&
2372             ((0 < patch->is_new) | (0 < patch->is_rename) | patch->is_copy)) {
2373                 if (check_index &&
2374                     cache_name_pos(new_name, strlen(new_name)) >= 0 &&
2375                     !ok_if_exists)
2376                         return error("%s: already exists in index", new_name);
2377                 if (!cached) {
2378                         int err = check_to_create_blob(new_name, ok_if_exists);
2379                         if (err)
2380                                 return err;
2381                 }
2382                 if (!patch->new_mode) {
2383                         if (0 < patch->is_new)
2384                                 patch->new_mode = S_IFREG | 0644;
2385                         else
2386                                 patch->new_mode = patch->old_mode;
2387                 }
2388         }
2390         if (new_name && old_name) {
2391                 int same = !strcmp(old_name, new_name);
2392                 if (!patch->new_mode)
2393                         patch->new_mode = patch->old_mode;
2394                 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
2395                         return error("new mode (%o) of %s does not match old mode (%o)%s%s",
2396                                 patch->new_mode, new_name, patch->old_mode,
2397                                 same ? "" : " of ", same ? "" : old_name);
2398         }
2400         if (apply_data(patch, &st, ce) < 0)
2401                 return error("%s: patch does not apply", name);
2402         patch->rejected = 0;
2403         return 0;
2406 static int check_patch_list(struct patch *patch)
2408         struct patch *prev_patch = NULL;
2409         int err = 0;
2411         for (prev_patch = NULL; patch ; patch = patch->next) {
2412                 if (apply_verbosely)
2413                         say_patch_name(stderr,
2414                                        "Checking patch ", patch, "...\n");
2415                 err |= check_patch(patch, prev_patch);
2416                 prev_patch = patch;
2417         }
2418         return err;
2421 /* This function tries to read the sha1 from the current index */
2422 static int get_current_sha1(const char *path, unsigned char *sha1)
2424         int pos;
2426         if (read_cache() < 0)
2427                 return -1;
2428         pos = cache_name_pos(path, strlen(path));
2429         if (pos < 0)
2430                 return -1;
2431         hashcpy(sha1, active_cache[pos]->sha1);
2432         return 0;
2435 /* Build an index that contains the just the files needed for a 3way merge */
2436 static void build_fake_ancestor(struct patch *list, const char *filename)
2438         struct patch *patch;
2439         struct index_state result = { 0 };
2440         int fd;
2442         /* Once we start supporting the reverse patch, it may be
2443          * worth showing the new sha1 prefix, but until then...
2444          */
2445         for (patch = list; patch; patch = patch->next) {
2446                 const unsigned char *sha1_ptr;
2447                 unsigned char sha1[20];
2448                 struct cache_entry *ce;
2449                 const char *name;
2451                 name = patch->old_name ? patch->old_name : patch->new_name;
2452                 if (0 < patch->is_new)
2453                         continue;
2454                 else if (get_sha1(patch->old_sha1_prefix, sha1))
2455                         /* git diff has no index line for mode/type changes */
2456                         if (!patch->lines_added && !patch->lines_deleted) {
2457                                 if (get_current_sha1(patch->new_name, sha1) ||
2458                                     get_current_sha1(patch->old_name, sha1))
2459                                         die("mode change for %s, which is not "
2460                                                 "in current HEAD", name);
2461                                 sha1_ptr = sha1;
2462                         } else
2463                                 die("sha1 information is lacking or useless "
2464                                         "(%s).", name);
2465                 else
2466                         sha1_ptr = sha1;
2468                 ce = make_cache_entry(patch->old_mode, sha1_ptr, name, 0, 0);
2469                 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))
2470                         die ("Could not add %s to temporary index", name);
2471         }
2473         fd = open(filename, O_WRONLY | O_CREAT, 0666);
2474         if (fd < 0 || write_index(&result, fd) || close(fd))
2475                 die ("Could not write temporary index to %s", filename);
2477         discard_index(&result);
2480 static void stat_patch_list(struct patch *patch)
2482         int files, adds, dels;
2484         for (files = adds = dels = 0 ; patch ; patch = patch->next) {
2485                 files++;
2486                 adds += patch->lines_added;
2487                 dels += patch->lines_deleted;
2488                 show_stats(patch);
2489         }
2491         printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
2494 static void numstat_patch_list(struct patch *patch)
2496         for ( ; patch; patch = patch->next) {
2497                 const char *name;
2498                 name = patch->new_name ? patch->new_name : patch->old_name;
2499                 if (patch->is_binary)
2500                         printf("-\t-\t");
2501                 else
2502                         printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
2503                 write_name_quoted(name, stdout, line_termination);
2504         }
2507 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
2509         if (mode)
2510                 printf(" %s mode %06o %s\n", newdelete, mode, name);
2511         else
2512                 printf(" %s %s\n", newdelete, name);
2515 static void show_mode_change(struct patch *p, int show_name)
2517         if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
2518                 if (show_name)
2519                         printf(" mode change %06o => %06o %s\n",
2520                                p->old_mode, p->new_mode, p->new_name);
2521                 else
2522                         printf(" mode change %06o => %06o\n",
2523                                p->old_mode, p->new_mode);
2524         }
2527 static void show_rename_copy(struct patch *p)
2529         const char *renamecopy = p->is_rename ? "rename" : "copy";
2530         const char *old, *new;
2532         /* Find common prefix */
2533         old = p->old_name;
2534         new = p->new_name;
2535         while (1) {
2536                 const char *slash_old, *slash_new;
2537                 slash_old = strchr(old, '/');
2538                 slash_new = strchr(new, '/');
2539                 if (!slash_old ||
2540                     !slash_new ||
2541                     slash_old - old != slash_new - new ||
2542                     memcmp(old, new, slash_new - new))
2543                         break;
2544                 old = slash_old + 1;
2545                 new = slash_new + 1;
2546         }
2547         /* p->old_name thru old is the common prefix, and old and new
2548          * through the end of names are renames
2549          */
2550         if (old != p->old_name)
2551                 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
2552                        (int)(old - p->old_name), p->old_name,
2553                        old, new, p->score);
2554         else
2555                 printf(" %s %s => %s (%d%%)\n", renamecopy,
2556                        p->old_name, p->new_name, p->score);
2557         show_mode_change(p, 0);
2560 static void summary_patch_list(struct patch *patch)
2562         struct patch *p;
2564         for (p = patch; p; p = p->next) {
2565                 if (p->is_new)
2566                         show_file_mode_name("create", p->new_mode, p->new_name);
2567                 else if (p->is_delete)
2568                         show_file_mode_name("delete", p->old_mode, p->old_name);
2569                 else {
2570                         if (p->is_rename || p->is_copy)
2571                                 show_rename_copy(p);
2572                         else {
2573                                 if (p->score) {
2574                                         printf(" rewrite %s (%d%%)\n",
2575                                                p->new_name, p->score);
2576                                         show_mode_change(p, 0);
2577                                 }
2578                                 else
2579                                         show_mode_change(p, 1);
2580                         }
2581                 }
2582         }
2585 static void patch_stats(struct patch *patch)
2587         int lines = patch->lines_added + patch->lines_deleted;
2589         if (lines > max_change)
2590                 max_change = lines;
2591         if (patch->old_name) {
2592                 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
2593                 if (!len)
2594                         len = strlen(patch->old_name);
2595                 if (len > max_len)
2596                         max_len = len;
2597         }
2598         if (patch->new_name) {
2599                 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
2600                 if (!len)
2601                         len = strlen(patch->new_name);
2602                 if (len > max_len)
2603                         max_len = len;
2604         }
2607 static void remove_file(struct patch *patch, int rmdir_empty)
2609         if (update_index) {
2610                 if (remove_file_from_cache(patch->old_name) < 0)
2611                         die("unable to remove %s from index", patch->old_name);
2612         }
2613         if (!cached) {
2614                 if (S_ISGITLINK(patch->old_mode)) {
2615                         if (rmdir(patch->old_name))
2616                                 warning("unable to remove submodule %s",
2617                                         patch->old_name);
2618                 } else if (!unlink(patch->old_name) && rmdir_empty) {
2619                         char *name = xstrdup(patch->old_name);
2620                         char *end = strrchr(name, '/');
2621                         while (end) {
2622                                 *end = 0;
2623                                 if (rmdir(name))
2624                                         break;
2625                                 end = strrchr(name, '/');
2626                         }
2627                         free(name);
2628                 }
2629         }
2632 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
2634         struct stat st;
2635         struct cache_entry *ce;
2636         int namelen = strlen(path);
2637         unsigned ce_size = cache_entry_size(namelen);
2639         if (!update_index)
2640                 return;
2642         ce = xcalloc(1, ce_size);
2643         memcpy(ce->name, path, namelen);
2644         ce->ce_mode = create_ce_mode(mode);
2645         ce->ce_flags = namelen;
2646         if (S_ISGITLINK(mode)) {
2647                 const char *s = buf;
2649                 if (get_sha1_hex(s + strlen("Subproject commit "), ce->sha1))
2650                         die("corrupt patch for subproject %s", path);
2651         } else {
2652                 if (!cached) {
2653                         if (lstat(path, &st) < 0)
2654                                 die("unable to stat newly created file %s",
2655                                     path);
2656                         fill_stat_cache_info(ce, &st);
2657                 }
2658                 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
2659                         die("unable to create backing store for newly created file %s", path);
2660         }
2661         if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
2662                 die("unable to add cache entry for %s", path);
2665 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
2667         int fd;
2668         struct strbuf nbuf;
2670         if (S_ISGITLINK(mode)) {
2671                 struct stat st;
2672                 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
2673                         return 0;
2674                 return mkdir(path, 0777);
2675         }
2677         if (has_symlinks && S_ISLNK(mode))
2678                 /* Although buf:size is counted string, it also is NUL
2679                  * terminated.
2680                  */
2681                 return symlink(buf, path);
2683         fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
2684         if (fd < 0)
2685                 return -1;
2687         strbuf_init(&nbuf, 0);
2688         if (convert_to_working_tree(path, buf, size, &nbuf)) {
2689                 size = nbuf.len;
2690                 buf  = nbuf.buf;
2691         }
2692         write_or_die(fd, buf, size);
2693         strbuf_release(&nbuf);
2695         if (close(fd) < 0)
2696                 die("closing file %s: %s", path, strerror(errno));
2697         return 0;
2700 /*
2701  * We optimistically assume that the directories exist,
2702  * which is true 99% of the time anyway. If they don't,
2703  * we create them and try again.
2704  */
2705 static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
2707         if (cached)
2708                 return;
2709         if (!try_create_file(path, mode, buf, size))
2710                 return;
2712         if (errno == ENOENT) {
2713                 if (safe_create_leading_directories(path))
2714                         return;
2715                 if (!try_create_file(path, mode, buf, size))
2716                         return;
2717         }
2719         if (errno == EEXIST || errno == EACCES) {
2720                 /* We may be trying to create a file where a directory
2721                  * used to be.
2722                  */
2723                 struct stat st;
2724                 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
2725                         errno = EEXIST;
2726         }
2728         if (errno == EEXIST) {
2729                 unsigned int nr = getpid();
2731                 for (;;) {
2732                         const char *newpath;
2733                         newpath = mkpath("%s~%u", path, nr);
2734                         if (!try_create_file(newpath, mode, buf, size)) {
2735                                 if (!rename(newpath, path))
2736                                         return;
2737                                 unlink(newpath);
2738                                 break;
2739                         }
2740                         if (errno != EEXIST)
2741                                 break;
2742                         ++nr;
2743                 }
2744         }
2745         die("unable to write file %s mode %o", path, mode);
2748 static void create_file(struct patch *patch)
2750         char *path = patch->new_name;
2751         unsigned mode = patch->new_mode;
2752         unsigned long size = patch->resultsize;
2753         char *buf = patch->result;
2755         if (!mode)
2756                 mode = S_IFREG | 0644;
2757         create_one_file(path, mode, buf, size);
2758         add_index_file(path, mode, buf, size);
2761 /* phase zero is to remove, phase one is to create */
2762 static void write_out_one_result(struct patch *patch, int phase)
2764         if (patch->is_delete > 0) {
2765                 if (phase == 0)
2766                         remove_file(patch, 1);
2767                 return;
2768         }
2769         if (patch->is_new > 0 || patch->is_copy) {
2770                 if (phase == 1)
2771                         create_file(patch);
2772                 return;
2773         }
2774         /*
2775          * Rename or modification boils down to the same
2776          * thing: remove the old, write the new
2777          */
2778         if (phase == 0)
2779                 remove_file(patch, patch->is_rename);
2780         if (phase == 1)
2781                 create_file(patch);
2784 static int write_out_one_reject(struct patch *patch)
2786         FILE *rej;
2787         char namebuf[PATH_MAX];
2788         struct fragment *frag;
2789         int cnt = 0;
2791         for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
2792                 if (!frag->rejected)
2793                         continue;
2794                 cnt++;
2795         }
2797         if (!cnt) {
2798                 if (apply_verbosely)
2799                         say_patch_name(stderr,
2800                                        "Applied patch ", patch, " cleanly.\n");
2801                 return 0;
2802         }
2804         /* This should not happen, because a removal patch that leaves
2805          * contents are marked "rejected" at the patch level.
2806          */
2807         if (!patch->new_name)
2808                 die("internal error");
2810         /* Say this even without --verbose */
2811         say_patch_name(stderr, "Applying patch ", patch, " with");
2812         fprintf(stderr, " %d rejects...\n", cnt);
2814         cnt = strlen(patch->new_name);
2815         if (ARRAY_SIZE(namebuf) <= cnt + 5) {
2816                 cnt = ARRAY_SIZE(namebuf) - 5;
2817                 fprintf(stderr,
2818                         "warning: truncating .rej filename to %.*s.rej",
2819                         cnt - 1, patch->new_name);
2820         }
2821         memcpy(namebuf, patch->new_name, cnt);
2822         memcpy(namebuf + cnt, ".rej", 5);
2824         rej = fopen(namebuf, "w");
2825         if (!rej)
2826                 return error("cannot open %s: %s", namebuf, strerror(errno));
2828         /* Normal git tools never deal with .rej, so do not pretend
2829          * this is a git patch by saying --git nor give extended
2830          * headers.  While at it, maybe please "kompare" that wants
2831          * the trailing TAB and some garbage at the end of line ;-).
2832          */
2833         fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
2834                 patch->new_name, patch->new_name);
2835         for (cnt = 1, frag = patch->fragments;
2836              frag;
2837              cnt++, frag = frag->next) {
2838                 if (!frag->rejected) {
2839                         fprintf(stderr, "Hunk #%d applied cleanly.\n", cnt);
2840                         continue;
2841                 }
2842                 fprintf(stderr, "Rejected hunk #%d.\n", cnt);
2843                 fprintf(rej, "%.*s", frag->size, frag->patch);
2844                 if (frag->patch[frag->size-1] != '\n')
2845                         fputc('\n', rej);
2846         }
2847         fclose(rej);
2848         return -1;
2851 static int write_out_results(struct patch *list, int skipped_patch)
2853         int phase;
2854         int errs = 0;
2855         struct patch *l;
2857         if (!list && !skipped_patch)
2858                 return error("No changes");
2860         for (phase = 0; phase < 2; phase++) {
2861                 l = list;
2862                 while (l) {
2863                         if (l->rejected)
2864                                 errs = 1;
2865                         else {
2866                                 write_out_one_result(l, phase);
2867                                 if (phase == 1 && write_out_one_reject(l))
2868                                         errs = 1;
2869                         }
2870                         l = l->next;
2871                 }
2872         }
2873         return errs;
2876 static struct lock_file lock_file;
2878 static struct excludes {
2879         struct excludes *next;
2880         const char *path;
2881 } *excludes;
2883 static int use_patch(struct patch *p)
2885         const char *pathname = p->new_name ? p->new_name : p->old_name;
2886         struct excludes *x = excludes;
2887         while (x) {
2888                 if (fnmatch(x->path, pathname, 0) == 0)
2889                         return 0;
2890                 x = x->next;
2891         }
2892         if (0 < prefix_length) {
2893                 int pathlen = strlen(pathname);
2894                 if (pathlen <= prefix_length ||
2895                     memcmp(prefix, pathname, prefix_length))
2896                         return 0;
2897         }
2898         return 1;
2901 static void prefix_one(char **name)
2903         char *old_name = *name;
2904         if (!old_name)
2905                 return;
2906         *name = xstrdup(prefix_filename(prefix, prefix_length, *name));
2907         free(old_name);
2910 static void prefix_patches(struct patch *p)
2912         if (!prefix || p->is_toplevel_relative)
2913                 return;
2914         for ( ; p; p = p->next) {
2915                 if (p->new_name == p->old_name) {
2916                         char *prefixed = p->new_name;
2917                         prefix_one(&prefixed);
2918                         p->new_name = p->old_name = prefixed;
2919                 }
2920                 else {
2921                         prefix_one(&p->new_name);
2922                         prefix_one(&p->old_name);
2923                 }
2924         }
2927 static int apply_patch(int fd, const char *filename, int inaccurate_eof)
2929         size_t offset;
2930         struct strbuf buf;
2931         struct patch *list = NULL, **listp = &list;
2932         int skipped_patch = 0;
2934         strbuf_init(&buf, 0);
2935         patch_input_file = filename;
2936         read_patch_file(&buf, fd);
2937         offset = 0;
2938         while (offset < buf.len) {
2939                 struct patch *patch;
2940                 int nr;
2942                 patch = xcalloc(1, sizeof(*patch));
2943                 patch->inaccurate_eof = inaccurate_eof;
2944                 nr = parse_chunk(buf.buf + offset, buf.len - offset, patch);
2945                 if (nr < 0)
2946                         break;
2947                 if (apply_in_reverse)
2948                         reverse_patches(patch);
2949                 if (prefix)
2950                         prefix_patches(patch);
2951                 if (use_patch(patch)) {
2952                         patch_stats(patch);
2953                         *listp = patch;
2954                         listp = &patch->next;
2955                 }
2956                 else {
2957                         /* perhaps free it a bit better? */
2958                         free(patch);
2959                         skipped_patch++;
2960                 }
2961                 offset += nr;
2962         }
2964         if (whitespace_error && (ws_error_action == die_on_ws_error))
2965                 apply = 0;
2967         update_index = check_index && apply;
2968         if (update_index && newfd < 0)
2969                 newfd = hold_locked_index(&lock_file, 1);
2971         if (check_index) {
2972                 if (read_cache() < 0)
2973                         die("unable to read index file");
2974         }
2976         if ((check || apply) &&
2977             check_patch_list(list) < 0 &&
2978             !apply_with_reject)
2979                 exit(1);
2981         if (apply && write_out_results(list, skipped_patch))
2982                 exit(1);
2984         if (fake_ancestor)
2985                 build_fake_ancestor(list, fake_ancestor);
2987         if (diffstat)
2988                 stat_patch_list(list);
2990         if (numstat)
2991                 numstat_patch_list(list);
2993         if (summary)
2994                 summary_patch_list(list);
2996         strbuf_release(&buf);
2997         return 0;
3000 static int git_apply_config(const char *var, const char *value, void *cb)
3002         if (!strcmp(var, "apply.whitespace"))
3003                 return git_config_string(&apply_default_whitespace, var, value);
3004         return git_default_config(var, value, cb);
3008 int cmd_apply(int argc, const char **argv, const char *unused_prefix)
3010         int i;
3011         int read_stdin = 1;
3012         int inaccurate_eof = 0;
3013         int errs = 0;
3014         int is_not_gitdir;
3016         const char *whitespace_option = NULL;
3018         prefix = setup_git_directory_gently(&is_not_gitdir);
3019         prefix_length = prefix ? strlen(prefix) : 0;
3020         git_config(git_apply_config, NULL);
3021         if (apply_default_whitespace)
3022                 parse_whitespace_option(apply_default_whitespace);
3024         for (i = 1; i < argc; i++) {
3025                 const char *arg = argv[i];
3026                 char *end;
3027                 int fd;
3029                 if (!strcmp(arg, "-")) {
3030                         errs |= apply_patch(0, "<stdin>", inaccurate_eof);
3031                         read_stdin = 0;
3032                         continue;
3033                 }
3034                 if (!prefixcmp(arg, "--exclude=")) {
3035                         struct excludes *x = xmalloc(sizeof(*x));
3036                         x->path = arg + 10;
3037                         x->next = excludes;
3038                         excludes = x;
3039                         continue;
3040                 }
3041                 if (!prefixcmp(arg, "-p")) {
3042                         p_value = atoi(arg + 2);
3043                         p_value_known = 1;
3044                         continue;
3045                 }
3046                 if (!strcmp(arg, "--no-add")) {
3047                         no_add = 1;
3048                         continue;
3049                 }
3050                 if (!strcmp(arg, "--stat")) {
3051                         apply = 0;
3052                         diffstat = 1;
3053                         continue;
3054                 }
3055                 if (!strcmp(arg, "--allow-binary-replacement") ||
3056                     !strcmp(arg, "--binary")) {
3057                         continue; /* now no-op */
3058                 }
3059                 if (!strcmp(arg, "--numstat")) {
3060                         apply = 0;
3061                         numstat = 1;
3062                         continue;
3063                 }
3064                 if (!strcmp(arg, "--summary")) {
3065                         apply = 0;
3066                         summary = 1;
3067                         continue;
3068                 }
3069                 if (!strcmp(arg, "--check")) {
3070                         apply = 0;
3071                         check = 1;
3072                         continue;
3073                 }
3074                 if (!strcmp(arg, "--index")) {
3075                         if (is_not_gitdir)
3076                                 die("--index outside a repository");
3077                         check_index = 1;
3078                         continue;
3079                 }
3080                 if (!strcmp(arg, "--cached")) {
3081                         if (is_not_gitdir)
3082                                 die("--cached outside a repository");
3083                         check_index = 1;
3084                         cached = 1;
3085                         continue;
3086                 }
3087                 if (!strcmp(arg, "--apply")) {
3088                         apply = 1;
3089                         continue;
3090                 }
3091                 if (!strcmp(arg, "--build-fake-ancestor")) {
3092                         apply = 0;
3093                         if (++i >= argc)
3094                                 die ("need a filename");
3095                         fake_ancestor = argv[i];
3096                         continue;
3097                 }
3098                 if (!strcmp(arg, "-z")) {
3099                         line_termination = 0;
3100                         continue;
3101                 }
3102                 if (!prefixcmp(arg, "-C")) {
3103                         p_context = strtoul(arg + 2, &end, 0);
3104                         if (*end != '\0')
3105                                 die("unrecognized context count '%s'", arg + 2);
3106                         continue;
3107                 }
3108                 if (!prefixcmp(arg, "--whitespace=")) {
3109                         whitespace_option = arg + 13;
3110                         parse_whitespace_option(arg + 13);
3111                         continue;
3112                 }
3113                 if (!strcmp(arg, "-R") || !strcmp(arg, "--reverse")) {
3114                         apply_in_reverse = 1;
3115                         continue;
3116                 }
3117                 if (!strcmp(arg, "--unidiff-zero")) {
3118                         unidiff_zero = 1;
3119                         continue;
3120                 }
3121                 if (!strcmp(arg, "--reject")) {
3122                         apply = apply_with_reject = apply_verbosely = 1;
3123                         continue;
3124                 }
3125                 if (!strcmp(arg, "-v") || !strcmp(arg, "--verbose")) {
3126                         apply_verbosely = 1;
3127                         continue;
3128                 }
3129                 if (!strcmp(arg, "--inaccurate-eof")) {
3130                         inaccurate_eof = 1;
3131                         continue;
3132                 }
3133                 if (!prefixcmp(arg, "--root=")) {
3134                         arg += strlen("--root=");
3135                         root_len = strlen(arg);
3136                         if (root_len && arg[root_len - 1] != '/') {
3137                                 char *new_root;
3138                                 root = new_root = xmalloc(root_len + 2);
3139                                 strcpy(new_root, arg);
3140                                 strcpy(new_root + root_len++, "/");
3141                         } else
3142                                 root = arg;
3143                         continue;
3144                 }
3145                 if (0 < prefix_length)
3146                         arg = prefix_filename(prefix, prefix_length, arg);
3148                 fd = open(arg, O_RDONLY);
3149                 if (fd < 0)
3150                         die("can't open patch '%s': %s", arg, strerror(errno));
3151                 read_stdin = 0;
3152                 set_default_whitespace_mode(whitespace_option);
3153                 errs |= apply_patch(fd, arg, inaccurate_eof);
3154                 close(fd);
3155         }
3156         set_default_whitespace_mode(whitespace_option);
3157         if (read_stdin)
3158                 errs |= apply_patch(0, "<stdin>", inaccurate_eof);
3159         if (whitespace_error) {
3160                 if (squelch_whitespace_errors &&
3161                     squelch_whitespace_errors < whitespace_error) {
3162                         int squelched =
3163                                 whitespace_error - squelch_whitespace_errors;
3164                         fprintf(stderr, "warning: squelched %d "
3165                                 "whitespace error%s\n",
3166                                 squelched,
3167                                 squelched == 1 ? "" : "s");
3168                 }
3169                 if (ws_error_action == die_on_ws_error)
3170                         die("%d line%s add%s whitespace errors.",
3171                             whitespace_error,
3172                             whitespace_error == 1 ? "" : "s",
3173                             whitespace_error == 1 ? "s" : "");
3174                 if (applied_after_fixing_ws && apply)
3175                         fprintf(stderr, "warning: %d line%s applied after"
3176                                 " fixing whitespace errors.\n",
3177                                 applied_after_fixing_ws,
3178                                 applied_after_fixing_ws == 1 ? "" : "s");
3179                 else if (whitespace_error)
3180                         fprintf(stderr, "warning: %d line%s add%s whitespace errors.\n",
3181                                 whitespace_error,
3182                                 whitespace_error == 1 ? "" : "s",
3183                                 whitespace_error == 1 ? "s" : "");
3184         }
3186         if (update_index) {
3187                 if (write_cache(newfd, active_cache, active_nr) ||
3188                     commit_locked_index(&lock_file))
3189                         die("Unable to write new index file");
3190         }
3192         return !!errs;