Code

Use gitattributes to define per-path whitespace rule
[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;
61 static void parse_whitespace_option(const char *option)
62 {
63         if (!option) {
64                 ws_error_action = warn_on_ws_error;
65                 return;
66         }
67         if (!strcmp(option, "warn")) {
68                 ws_error_action = warn_on_ws_error;
69                 return;
70         }
71         if (!strcmp(option, "nowarn")) {
72                 ws_error_action = nowarn_ws_error;
73                 return;
74         }
75         if (!strcmp(option, "error")) {
76                 ws_error_action = die_on_ws_error;
77                 return;
78         }
79         if (!strcmp(option, "error-all")) {
80                 ws_error_action = die_on_ws_error;
81                 squelch_whitespace_errors = 0;
82                 return;
83         }
84         if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
85                 ws_error_action = correct_ws_error;
86                 return;
87         }
88         die("unrecognized whitespace option '%s'", option);
89 }
91 static void set_default_whitespace_mode(const char *whitespace_option)
92 {
93         if (!whitespace_option && !apply_default_whitespace)
94                 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error);
95 }
97 /*
98  * For "diff-stat" like behaviour, we keep track of the biggest change
99  * we've seen, and the longest filename. That allows us to do simple
100  * scaling.
101  */
102 static int max_change, max_len;
104 /*
105  * Various "current state", notably line numbers and what
106  * file (and how) we're patching right now.. The "is_xxxx"
107  * things are flags, where -1 means "don't know yet".
108  */
109 static int linenr = 1;
111 /*
112  * This represents one "hunk" from a patch, starting with
113  * "@@ -oldpos,oldlines +newpos,newlines @@" marker.  The
114  * patch text is pointed at by patch, and its byte length
115  * is stored in size.  leading and trailing are the number
116  * of context lines.
117  */
118 struct fragment {
119         unsigned long leading, trailing;
120         unsigned long oldpos, oldlines;
121         unsigned long newpos, newlines;
122         const char *patch;
123         int size;
124         int rejected;
125         struct fragment *next;
126 };
128 /*
129  * When dealing with a binary patch, we reuse "leading" field
130  * to store the type of the binary hunk, either deflated "delta"
131  * or deflated "literal".
132  */
133 #define binary_patch_method leading
134 #define BINARY_DELTA_DEFLATED   1
135 #define BINARY_LITERAL_DEFLATED 2
137 /*
138  * This represents a "patch" to a file, both metainfo changes
139  * such as creation/deletion, filemode and content changes represented
140  * as a series of fragments.
141  */
142 struct patch {
143         char *new_name, *old_name, *def_name;
144         unsigned int old_mode, new_mode;
145         int is_new, is_delete;  /* -1 = unknown, 0 = false, 1 = true */
146         int rejected;
147         unsigned ws_rule;
148         unsigned long deflate_origlen;
149         int lines_added, lines_deleted;
150         int score;
151         unsigned int is_toplevel_relative:1;
152         unsigned int inaccurate_eof:1;
153         unsigned int is_binary:1;
154         unsigned int is_copy:1;
155         unsigned int is_rename:1;
156         struct fragment *fragments;
157         char *result;
158         size_t resultsize;
159         char old_sha1_prefix[41];
160         char new_sha1_prefix[41];
161         struct patch *next;
162 };
164 static void say_patch_name(FILE *output, const char *pre,
165                            struct patch *patch, const char *post)
167         fputs(pre, output);
168         if (patch->old_name && patch->new_name &&
169             strcmp(patch->old_name, patch->new_name)) {
170                 quote_c_style(patch->old_name, NULL, output, 0);
171                 fputs(" => ", output);
172                 quote_c_style(patch->new_name, NULL, output, 0);
173         } else {
174                 const char *n = patch->new_name;
175                 if (!n)
176                         n = patch->old_name;
177                 quote_c_style(n, NULL, output, 0);
178         }
179         fputs(post, output);
182 #define CHUNKSIZE (8192)
183 #define SLOP (16)
185 static void read_patch_file(struct strbuf *sb, int fd)
187         if (strbuf_read(sb, fd, 0) < 0)
188                 die("git-apply: read returned %s", strerror(errno));
190         /*
191          * Make sure that we have some slop in the buffer
192          * so that we can do speculative "memcmp" etc, and
193          * see to it that it is NUL-filled.
194          */
195         strbuf_grow(sb, SLOP);
196         memset(sb->buf + sb->len, 0, SLOP);
199 static unsigned long linelen(const char *buffer, unsigned long size)
201         unsigned long len = 0;
202         while (size--) {
203                 len++;
204                 if (*buffer++ == '\n')
205                         break;
206         }
207         return len;
210 static int is_dev_null(const char *str)
212         return !memcmp("/dev/null", str, 9) && isspace(str[9]);
215 #define TERM_SPACE      1
216 #define TERM_TAB        2
218 static int name_terminate(const char *name, int namelen, int c, int terminate)
220         if (c == ' ' && !(terminate & TERM_SPACE))
221                 return 0;
222         if (c == '\t' && !(terminate & TERM_TAB))
223                 return 0;
225         return 1;
228 static char *find_name(const char *line, char *def, int p_value, int terminate)
230         int len;
231         const char *start = line;
233         if (*line == '"') {
234                 struct strbuf name;
236                 /*
237                  * Proposed "new-style" GNU patch/diff format; see
238                  * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
239                  */
240                 strbuf_init(&name, 0);
241                 if (!unquote_c_style(&name, line, NULL)) {
242                         char *cp;
244                         for (cp = name.buf; p_value; p_value--) {
245                                 cp = strchr(cp, '/');
246                                 if (!cp)
247                                         break;
248                                 cp++;
249                         }
250                         if (cp) {
251                                 /* name can later be freed, so we need
252                                  * to memmove, not just return cp
253                                  */
254                                 strbuf_remove(&name, 0, cp - name.buf);
255                                 free(def);
256                                 return strbuf_detach(&name, NULL);
257                         }
258                 }
259                 strbuf_release(&name);
260         }
262         for (;;) {
263                 char c = *line;
265                 if (isspace(c)) {
266                         if (c == '\n')
267                                 break;
268                         if (name_terminate(start, line-start, c, terminate))
269                                 break;
270                 }
271                 line++;
272                 if (c == '/' && !--p_value)
273                         start = line;
274         }
275         if (!start)
276                 return def;
277         len = line - start;
278         if (!len)
279                 return def;
281         /*
282          * Generally we prefer the shorter name, especially
283          * if the other one is just a variation of that with
284          * something else tacked on to the end (ie "file.orig"
285          * or "file~").
286          */
287         if (def) {
288                 int deflen = strlen(def);
289                 if (deflen < len && !strncmp(start, def, deflen))
290                         return def;
291                 free(def);
292         }
294         return xmemdupz(start, len);
297 static int count_slashes(const char *cp)
299         int cnt = 0;
300         char ch;
302         while ((ch = *cp++))
303                 if (ch == '/')
304                         cnt++;
305         return cnt;
308 /*
309  * Given the string after "--- " or "+++ ", guess the appropriate
310  * p_value for the given patch.
311  */
312 static int guess_p_value(const char *nameline)
314         char *name, *cp;
315         int val = -1;
317         if (is_dev_null(nameline))
318                 return -1;
319         name = find_name(nameline, NULL, 0, TERM_SPACE | TERM_TAB);
320         if (!name)
321                 return -1;
322         cp = strchr(name, '/');
323         if (!cp)
324                 val = 0;
325         else if (prefix) {
326                 /*
327                  * Does it begin with "a/$our-prefix" and such?  Then this is
328                  * very likely to apply to our directory.
329                  */
330                 if (!strncmp(name, prefix, prefix_length))
331                         val = count_slashes(prefix);
332                 else {
333                         cp++;
334                         if (!strncmp(cp, prefix, prefix_length))
335                                 val = count_slashes(prefix) + 1;
336                 }
337         }
338         free(name);
339         return val;
342 /*
343  * Get the name etc info from the --/+++ lines of a traditional patch header
344  *
345  * FIXME! The end-of-filename heuristics are kind of screwy. For existing
346  * files, we can happily check the index for a match, but for creating a
347  * new file we should try to match whatever "patch" does. I have no idea.
348  */
349 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
351         char *name;
353         first += 4;     /* skip "--- " */
354         second += 4;    /* skip "+++ " */
355         if (!p_value_known) {
356                 int p, q;
357                 p = guess_p_value(first);
358                 q = guess_p_value(second);
359                 if (p < 0) p = q;
360                 if (0 <= p && p == q) {
361                         p_value = p;
362                         p_value_known = 1;
363                 }
364         }
365         if (is_dev_null(first)) {
366                 patch->is_new = 1;
367                 patch->is_delete = 0;
368                 name = find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB);
369                 patch->new_name = name;
370         } else if (is_dev_null(second)) {
371                 patch->is_new = 0;
372                 patch->is_delete = 1;
373                 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
374                 patch->old_name = name;
375         } else {
376                 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
377                 name = find_name(second, name, p_value, TERM_SPACE | TERM_TAB);
378                 patch->old_name = patch->new_name = name;
379         }
380         if (!name)
381                 die("unable to find filename in patch at line %d", linenr);
384 static int gitdiff_hdrend(const char *line, struct patch *patch)
386         return -1;
389 /*
390  * We're anal about diff header consistency, to make
391  * sure that we don't end up having strange ambiguous
392  * patches floating around.
393  *
394  * As a result, gitdiff_{old|new}name() will check
395  * their names against any previous information, just
396  * to make sure..
397  */
398 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
400         if (!orig_name && !isnull)
401                 return find_name(line, NULL, p_value, TERM_TAB);
403         if (orig_name) {
404                 int len;
405                 const char *name;
406                 char *another;
407                 name = orig_name;
408                 len = strlen(name);
409                 if (isnull)
410                         die("git-apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
411                 another = find_name(line, NULL, p_value, TERM_TAB);
412                 if (!another || memcmp(another, name, len))
413                         die("git-apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
414                 free(another);
415                 return orig_name;
416         }
417         else {
418                 /* expect "/dev/null" */
419                 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
420                         die("git-apply: bad git-diff - expected /dev/null on line %d", linenr);
421                 return NULL;
422         }
425 static int gitdiff_oldname(const char *line, struct patch *patch)
427         patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
428         return 0;
431 static int gitdiff_newname(const char *line, struct patch *patch)
433         patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
434         return 0;
437 static int gitdiff_oldmode(const char *line, struct patch *patch)
439         patch->old_mode = strtoul(line, NULL, 8);
440         return 0;
443 static int gitdiff_newmode(const char *line, struct patch *patch)
445         patch->new_mode = strtoul(line, NULL, 8);
446         return 0;
449 static int gitdiff_delete(const char *line, struct patch *patch)
451         patch->is_delete = 1;
452         patch->old_name = patch->def_name;
453         return gitdiff_oldmode(line, patch);
456 static int gitdiff_newfile(const char *line, struct patch *patch)
458         patch->is_new = 1;
459         patch->new_name = patch->def_name;
460         return gitdiff_newmode(line, patch);
463 static int gitdiff_copysrc(const char *line, struct patch *patch)
465         patch->is_copy = 1;
466         patch->old_name = find_name(line, NULL, 0, 0);
467         return 0;
470 static int gitdiff_copydst(const char *line, struct patch *patch)
472         patch->is_copy = 1;
473         patch->new_name = find_name(line, NULL, 0, 0);
474         return 0;
477 static int gitdiff_renamesrc(const char *line, struct patch *patch)
479         patch->is_rename = 1;
480         patch->old_name = find_name(line, NULL, 0, 0);
481         return 0;
484 static int gitdiff_renamedst(const char *line, struct patch *patch)
486         patch->is_rename = 1;
487         patch->new_name = find_name(line, NULL, 0, 0);
488         return 0;
491 static int gitdiff_similarity(const char *line, struct patch *patch)
493         if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
494                 patch->score = 0;
495         return 0;
498 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
500         if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
501                 patch->score = 0;
502         return 0;
505 static int gitdiff_index(const char *line, struct patch *patch)
507         /*
508          * index line is N hexadecimal, "..", N hexadecimal,
509          * and optional space with octal mode.
510          */
511         const char *ptr, *eol;
512         int len;
514         ptr = strchr(line, '.');
515         if (!ptr || ptr[1] != '.' || 40 < ptr - line)
516                 return 0;
517         len = ptr - line;
518         memcpy(patch->old_sha1_prefix, line, len);
519         patch->old_sha1_prefix[len] = 0;
521         line = ptr + 2;
522         ptr = strchr(line, ' ');
523         eol = strchr(line, '\n');
525         if (!ptr || eol < ptr)
526                 ptr = eol;
527         len = ptr - line;
529         if (40 < len)
530                 return 0;
531         memcpy(patch->new_sha1_prefix, line, len);
532         patch->new_sha1_prefix[len] = 0;
533         if (*ptr == ' ')
534                 patch->new_mode = patch->old_mode = strtoul(ptr+1, NULL, 8);
535         return 0;
538 /*
539  * This is normal for a diff that doesn't change anything: we'll fall through
540  * into the next diff. Tell the parser to break out.
541  */
542 static int gitdiff_unrecognized(const char *line, struct patch *patch)
544         return -1;
547 static const char *stop_at_slash(const char *line, int llen)
549         int i;
551         for (i = 0; i < llen; i++) {
552                 int ch = line[i];
553                 if (ch == '/')
554                         return line + i;
555         }
556         return NULL;
559 /*
560  * This is to extract the same name that appears on "diff --git"
561  * line.  We do not find and return anything if it is a rename
562  * patch, and it is OK because we will find the name elsewhere.
563  * We need to reliably find name only when it is mode-change only,
564  * creation or deletion of an empty file.  In any of these cases,
565  * both sides are the same name under a/ and b/ respectively.
566  */
567 static char *git_header_name(char *line, int llen)
569         const char *name;
570         const char *second = NULL;
571         size_t len;
573         line += strlen("diff --git ");
574         llen -= strlen("diff --git ");
576         if (*line == '"') {
577                 const char *cp;
578                 struct strbuf first;
579                 struct strbuf sp;
581                 strbuf_init(&first, 0);
582                 strbuf_init(&sp, 0);
584                 if (unquote_c_style(&first, line, &second))
585                         goto free_and_fail1;
587                 /* advance to the first slash */
588                 cp = stop_at_slash(first.buf, first.len);
589                 /* we do not accept absolute paths */
590                 if (!cp || cp == first.buf)
591                         goto free_and_fail1;
592                 strbuf_remove(&first, 0, cp + 1 - first.buf);
594                 /*
595                  * second points at one past closing dq of name.
596                  * find the second name.
597                  */
598                 while ((second < line + llen) && isspace(*second))
599                         second++;
601                 if (line + llen <= second)
602                         goto free_and_fail1;
603                 if (*second == '"') {
604                         if (unquote_c_style(&sp, second, NULL))
605                                 goto free_and_fail1;
606                         cp = stop_at_slash(sp.buf, sp.len);
607                         if (!cp || cp == sp.buf)
608                                 goto free_and_fail1;
609                         /* They must match, otherwise ignore */
610                         if (strcmp(cp + 1, first.buf))
611                                 goto free_and_fail1;
612                         strbuf_release(&sp);
613                         return strbuf_detach(&first, NULL);
614                 }
616                 /* unquoted second */
617                 cp = stop_at_slash(second, line + llen - second);
618                 if (!cp || cp == second)
619                         goto free_and_fail1;
620                 cp++;
621                 if (line + llen - cp != first.len + 1 ||
622                     memcmp(first.buf, cp, first.len))
623                         goto free_and_fail1;
624                 return strbuf_detach(&first, NULL);
626         free_and_fail1:
627                 strbuf_release(&first);
628                 strbuf_release(&sp);
629                 return NULL;
630         }
632         /* unquoted first name */
633         name = stop_at_slash(line, llen);
634         if (!name || name == line)
635                 return NULL;
636         name++;
638         /*
639          * since the first name is unquoted, a dq if exists must be
640          * the beginning of the second name.
641          */
642         for (second = name; second < line + llen; second++) {
643                 if (*second == '"') {
644                         struct strbuf sp;
645                         const char *np;
647                         strbuf_init(&sp, 0);
648                         if (unquote_c_style(&sp, second, NULL))
649                                 goto free_and_fail2;
651                         np = stop_at_slash(sp.buf, sp.len);
652                         if (!np || np == sp.buf)
653                                 goto free_and_fail2;
654                         np++;
656                         len = sp.buf + sp.len - np;
657                         if (len < second - name &&
658                             !strncmp(np, name, len) &&
659                             isspace(name[len])) {
660                                 /* Good */
661                                 strbuf_remove(&sp, 0, np - sp.buf);
662                                 return strbuf_detach(&sp, NULL);
663                         }
665                 free_and_fail2:
666                         strbuf_release(&sp);
667                         return NULL;
668                 }
669         }
671         /*
672          * Accept a name only if it shows up twice, exactly the same
673          * form.
674          */
675         for (len = 0 ; ; len++) {
676                 switch (name[len]) {
677                 default:
678                         continue;
679                 case '\n':
680                         return NULL;
681                 case '\t': case ' ':
682                         second = name+len;
683                         for (;;) {
684                                 char c = *second++;
685                                 if (c == '\n')
686                                         return NULL;
687                                 if (c == '/')
688                                         break;
689                         }
690                         if (second[len] == '\n' && !memcmp(name, second, len)) {
691                                 return xmemdupz(name, len);
692                         }
693                 }
694         }
695         return NULL;
698 /* Verify that we recognize the lines following a git header */
699 static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
701         unsigned long offset;
703         /* A git diff has explicit new/delete information, so we don't guess */
704         patch->is_new = 0;
705         patch->is_delete = 0;
707         /*
708          * Some things may not have the old name in the
709          * rest of the headers anywhere (pure mode changes,
710          * or removing or adding empty files), so we get
711          * the default name from the header.
712          */
713         patch->def_name = git_header_name(line, len);
715         line += len;
716         size -= len;
717         linenr++;
718         for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
719                 static const struct opentry {
720                         const char *str;
721                         int (*fn)(const char *, struct patch *);
722                 } optable[] = {
723                         { "@@ -", gitdiff_hdrend },
724                         { "--- ", gitdiff_oldname },
725                         { "+++ ", gitdiff_newname },
726                         { "old mode ", gitdiff_oldmode },
727                         { "new mode ", gitdiff_newmode },
728                         { "deleted file mode ", gitdiff_delete },
729                         { "new file mode ", gitdiff_newfile },
730                         { "copy from ", gitdiff_copysrc },
731                         { "copy to ", gitdiff_copydst },
732                         { "rename old ", gitdiff_renamesrc },
733                         { "rename new ", gitdiff_renamedst },
734                         { "rename from ", gitdiff_renamesrc },
735                         { "rename to ", gitdiff_renamedst },
736                         { "similarity index ", gitdiff_similarity },
737                         { "dissimilarity index ", gitdiff_dissimilarity },
738                         { "index ", gitdiff_index },
739                         { "", gitdiff_unrecognized },
740                 };
741                 int i;
743                 len = linelen(line, size);
744                 if (!len || line[len-1] != '\n')
745                         break;
746                 for (i = 0; i < ARRAY_SIZE(optable); i++) {
747                         const struct opentry *p = optable + i;
748                         int oplen = strlen(p->str);
749                         if (len < oplen || memcmp(p->str, line, oplen))
750                                 continue;
751                         if (p->fn(line + oplen, patch) < 0)
752                                 return offset;
753                         break;
754                 }
755         }
757         return offset;
760 static int parse_num(const char *line, unsigned long *p)
762         char *ptr;
764         if (!isdigit(*line))
765                 return 0;
766         *p = strtoul(line, &ptr, 10);
767         return ptr - line;
770 static int parse_range(const char *line, int len, int offset, const char *expect,
771                        unsigned long *p1, unsigned long *p2)
773         int digits, ex;
775         if (offset < 0 || offset >= len)
776                 return -1;
777         line += offset;
778         len -= offset;
780         digits = parse_num(line, p1);
781         if (!digits)
782                 return -1;
784         offset += digits;
785         line += digits;
786         len -= digits;
788         *p2 = 1;
789         if (*line == ',') {
790                 digits = parse_num(line+1, p2);
791                 if (!digits)
792                         return -1;
794                 offset += digits+1;
795                 line += digits+1;
796                 len -= digits+1;
797         }
799         ex = strlen(expect);
800         if (ex > len)
801                 return -1;
802         if (memcmp(line, expect, ex))
803                 return -1;
805         return offset + ex;
808 /*
809  * Parse a unified diff fragment header of the
810  * form "@@ -a,b +c,d @@"
811  */
812 static int parse_fragment_header(char *line, int len, struct fragment *fragment)
814         int offset;
816         if (!len || line[len-1] != '\n')
817                 return -1;
819         /* Figure out the number of lines in a fragment */
820         offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
821         offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
823         return offset;
826 static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
828         unsigned long offset, len;
830         patch->is_toplevel_relative = 0;
831         patch->is_rename = patch->is_copy = 0;
832         patch->is_new = patch->is_delete = -1;
833         patch->old_mode = patch->new_mode = 0;
834         patch->old_name = patch->new_name = NULL;
835         for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
836                 unsigned long nextlen;
838                 len = linelen(line, size);
839                 if (!len)
840                         break;
842                 /* Testing this early allows us to take a few shortcuts.. */
843                 if (len < 6)
844                         continue;
846                 /*
847                  * Make sure we don't find any unconnected patch fragments.
848                  * That's a sign that we didn't find a header, and that a
849                  * patch has become corrupted/broken up.
850                  */
851                 if (!memcmp("@@ -", line, 4)) {
852                         struct fragment dummy;
853                         if (parse_fragment_header(line, len, &dummy) < 0)
854                                 continue;
855                         die("patch fragment without header at line %d: %.*s",
856                             linenr, (int)len-1, line);
857                 }
859                 if (size < len + 6)
860                         break;
862                 /*
863                  * Git patch? It might not have a real patch, just a rename
864                  * or mode change, so we handle that specially
865                  */
866                 if (!memcmp("diff --git ", line, 11)) {
867                         int git_hdr_len = parse_git_header(line, len, size, patch);
868                         if (git_hdr_len <= len)
869                                 continue;
870                         if (!patch->old_name && !patch->new_name) {
871                                 if (!patch->def_name)
872                                         die("git diff header lacks filename information (line %d)", linenr);
873                                 patch->old_name = patch->new_name = patch->def_name;
874                         }
875                         patch->is_toplevel_relative = 1;
876                         *hdrsize = git_hdr_len;
877                         return offset;
878                 }
880                 /* --- followed by +++ ? */
881                 if (memcmp("--- ", line,  4) || memcmp("+++ ", line + len, 4))
882                         continue;
884                 /*
885                  * We only accept unified patches, so we want it to
886                  * at least have "@@ -a,b +c,d @@\n", which is 14 chars
887                  * minimum ("@@ -0,0 +1 @@\n" is the shortest).
888                  */
889                 nextlen = linelen(line + len, size - len);
890                 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
891                         continue;
893                 /* Ok, we'll consider it a patch */
894                 parse_traditional_patch(line, line+len, patch);
895                 *hdrsize = len + nextlen;
896                 linenr += 2;
897                 return offset;
898         }
899         return -1;
902 static void check_whitespace(const char *line, int len, unsigned ws_rule)
904         const char *err = "Adds trailing whitespace";
905         int seen_space = 0;
906         int i;
908         /*
909          * We know len is at least two, since we have a '+' and we
910          * checked that the last character was a '\n' before calling
911          * this function.  That is, an addition of an empty line would
912          * check the '+' here.  Sneaky...
913          */
914         if ((ws_rule & WS_TRAILING_SPACE) && isspace(line[len-2]))
915                 goto error;
917         /*
918          * Make sure that there is no space followed by a tab in
919          * indentation.
920          */
921         if (ws_rule & WS_SPACE_BEFORE_TAB) {
922                 err = "Space in indent is followed by a tab";
923                 for (i = 1; i < len; i++) {
924                         if (line[i] == '\t') {
925                                 if (seen_space)
926                                         goto error;
927                         }
928                         else if (line[i] == ' ')
929                                 seen_space = 1;
930                         else
931                                 break;
932                 }
933         }
935         /*
936          * Make sure that the indentation does not contain more than
937          * 8 spaces.
938          */
939         if ((ws_rule & WS_INDENT_WITH_NON_TAB) &&
940             (8 < len) && !strncmp("+        ", line, 9)) {
941                 err = "Indent more than 8 places with spaces";
942                 goto error;
943         }
944         return;
946  error:
947         whitespace_error++;
948         if (squelch_whitespace_errors &&
949             squelch_whitespace_errors < whitespace_error)
950                 ;
951         else
952                 fprintf(stderr, "%s.\n%s:%d:%.*s\n",
953                         err, patch_input_file, linenr, len-2, line+1);
956 /*
957  * Parse a unified diff. Note that this really needs to parse each
958  * fragment separately, since the only way to know the difference
959  * between a "---" that is part of a patch, and a "---" that starts
960  * the next patch is to look at the line counts..
961  */
962 static int parse_fragment(char *line, unsigned long size,
963                           struct patch *patch, struct fragment *fragment)
965         int added, deleted;
966         int len = linelen(line, size), offset;
967         unsigned long oldlines, newlines;
968         unsigned long leading, trailing;
970         offset = parse_fragment_header(line, len, fragment);
971         if (offset < 0)
972                 return -1;
973         oldlines = fragment->oldlines;
974         newlines = fragment->newlines;
975         leading = 0;
976         trailing = 0;
978         /* Parse the thing.. */
979         line += len;
980         size -= len;
981         linenr++;
982         added = deleted = 0;
983         for (offset = len;
984              0 < size;
985              offset += len, size -= len, line += len, linenr++) {
986                 if (!oldlines && !newlines)
987                         break;
988                 len = linelen(line, size);
989                 if (!len || line[len-1] != '\n')
990                         return -1;
991                 switch (*line) {
992                 default:
993                         return -1;
994                 case '\n': /* newer GNU diff, an empty context line */
995                 case ' ':
996                         oldlines--;
997                         newlines--;
998                         if (!deleted && !added)
999                                 leading++;
1000                         trailing++;
1001                         break;
1002                 case '-':
1003                         if (apply_in_reverse &&
1004                             ws_error_action != nowarn_ws_error)
1005                                 check_whitespace(line, len, patch->ws_rule);
1006                         deleted++;
1007                         oldlines--;
1008                         trailing = 0;
1009                         break;
1010                 case '+':
1011                         if (!apply_in_reverse &&
1012                             ws_error_action != nowarn_ws_error)
1013                                 check_whitespace(line, len, patch->ws_rule);
1014                         added++;
1015                         newlines--;
1016                         trailing = 0;
1017                         break;
1019                 /*
1020                  * We allow "\ No newline at end of file". Depending
1021                  * on locale settings when the patch was produced we
1022                  * don't know what this line looks like. The only
1023                  * thing we do know is that it begins with "\ ".
1024                  * Checking for 12 is just for sanity check -- any
1025                  * l10n of "\ No newline..." is at least that long.
1026                  */
1027                 case '\\':
1028                         if (len < 12 || memcmp(line, "\\ ", 2))
1029                                 return -1;
1030                         break;
1031                 }
1032         }
1033         if (oldlines || newlines)
1034                 return -1;
1035         fragment->leading = leading;
1036         fragment->trailing = trailing;
1038         /*
1039          * If a fragment ends with an incomplete line, we failed to include
1040          * it in the above loop because we hit oldlines == newlines == 0
1041          * before seeing it.
1042          */
1043         if (12 < size && !memcmp(line, "\\ ", 2))
1044                 offset += linelen(line, size);
1046         patch->lines_added += added;
1047         patch->lines_deleted += deleted;
1049         if (0 < patch->is_new && oldlines)
1050                 return error("new file depends on old contents");
1051         if (0 < patch->is_delete && newlines)
1052                 return error("deleted file still has contents");
1053         return offset;
1056 static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
1058         unsigned long offset = 0;
1059         unsigned long oldlines = 0, newlines = 0, context = 0;
1060         struct fragment **fragp = &patch->fragments;
1062         while (size > 4 && !memcmp(line, "@@ -", 4)) {
1063                 struct fragment *fragment;
1064                 int len;
1066                 fragment = xcalloc(1, sizeof(*fragment));
1067                 len = parse_fragment(line, size, patch, fragment);
1068                 if (len <= 0)
1069                         die("corrupt patch at line %d", linenr);
1070                 fragment->patch = line;
1071                 fragment->size = len;
1072                 oldlines += fragment->oldlines;
1073                 newlines += fragment->newlines;
1074                 context += fragment->leading + fragment->trailing;
1076                 *fragp = fragment;
1077                 fragp = &fragment->next;
1079                 offset += len;
1080                 line += len;
1081                 size -= len;
1082         }
1084         /*
1085          * If something was removed (i.e. we have old-lines) it cannot
1086          * be creation, and if something was added it cannot be
1087          * deletion.  However, the reverse is not true; --unified=0
1088          * patches that only add are not necessarily creation even
1089          * though they do not have any old lines, and ones that only
1090          * delete are not necessarily deletion.
1091          *
1092          * Unfortunately, a real creation/deletion patch do _not_ have
1093          * any context line by definition, so we cannot safely tell it
1094          * apart with --unified=0 insanity.  At least if the patch has
1095          * more than one hunk it is not creation or deletion.
1096          */
1097         if (patch->is_new < 0 &&
1098             (oldlines || (patch->fragments && patch->fragments->next)))
1099                 patch->is_new = 0;
1100         if (patch->is_delete < 0 &&
1101             (newlines || (patch->fragments && patch->fragments->next)))
1102                 patch->is_delete = 0;
1103         if (!unidiff_zero || context) {
1104                 /* If the user says the patch is not generated with
1105                  * --unified=0, or if we have seen context lines,
1106                  * then not having oldlines means the patch is creation,
1107                  * and not having newlines means the patch is deletion.
1108                  */
1109                 if (patch->is_new < 0 && !oldlines) {
1110                         patch->is_new = 1;
1111                         patch->old_name = NULL;
1112                 }
1113                 if (patch->is_delete < 0 && !newlines) {
1114                         patch->is_delete = 1;
1115                         patch->new_name = NULL;
1116                 }
1117         }
1119         if (0 < patch->is_new && oldlines)
1120                 die("new file %s depends on old contents", patch->new_name);
1121         if (0 < patch->is_delete && newlines)
1122                 die("deleted file %s still has contents", patch->old_name);
1123         if (!patch->is_delete && !newlines && context)
1124                 fprintf(stderr, "** warning: file %s becomes empty but "
1125                         "is not deleted\n", patch->new_name);
1127         return offset;
1130 static inline int metadata_changes(struct patch *patch)
1132         return  patch->is_rename > 0 ||
1133                 patch->is_copy > 0 ||
1134                 patch->is_new > 0 ||
1135                 patch->is_delete ||
1136                 (patch->old_mode && patch->new_mode &&
1137                  patch->old_mode != patch->new_mode);
1140 static char *inflate_it(const void *data, unsigned long size,
1141                         unsigned long inflated_size)
1143         z_stream stream;
1144         void *out;
1145         int st;
1147         memset(&stream, 0, sizeof(stream));
1149         stream.next_in = (unsigned char *)data;
1150         stream.avail_in = size;
1151         stream.next_out = out = xmalloc(inflated_size);
1152         stream.avail_out = inflated_size;
1153         inflateInit(&stream);
1154         st = inflate(&stream, Z_FINISH);
1155         if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1156                 free(out);
1157                 return NULL;
1158         }
1159         return out;
1162 static struct fragment *parse_binary_hunk(char **buf_p,
1163                                           unsigned long *sz_p,
1164                                           int *status_p,
1165                                           int *used_p)
1167         /*
1168          * Expect a line that begins with binary patch method ("literal"
1169          * or "delta"), followed by the length of data before deflating.
1170          * a sequence of 'length-byte' followed by base-85 encoded data
1171          * should follow, terminated by a newline.
1172          *
1173          * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1174          * and we would limit the patch line to 66 characters,
1175          * so one line can fit up to 13 groups that would decode
1176          * to 52 bytes max.  The length byte 'A'-'Z' corresponds
1177          * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1178          */
1179         int llen, used;
1180         unsigned long size = *sz_p;
1181         char *buffer = *buf_p;
1182         int patch_method;
1183         unsigned long origlen;
1184         char *data = NULL;
1185         int hunk_size = 0;
1186         struct fragment *frag;
1188         llen = linelen(buffer, size);
1189         used = llen;
1191         *status_p = 0;
1193         if (!prefixcmp(buffer, "delta ")) {
1194                 patch_method = BINARY_DELTA_DEFLATED;
1195                 origlen = strtoul(buffer + 6, NULL, 10);
1196         }
1197         else if (!prefixcmp(buffer, "literal ")) {
1198                 patch_method = BINARY_LITERAL_DEFLATED;
1199                 origlen = strtoul(buffer + 8, NULL, 10);
1200         }
1201         else
1202                 return NULL;
1204         linenr++;
1205         buffer += llen;
1206         while (1) {
1207                 int byte_length, max_byte_length, newsize;
1208                 llen = linelen(buffer, size);
1209                 used += llen;
1210                 linenr++;
1211                 if (llen == 1) {
1212                         /* consume the blank line */
1213                         buffer++;
1214                         size--;
1215                         break;
1216                 }
1217                 /*
1218                  * Minimum line is "A00000\n" which is 7-byte long,
1219                  * and the line length must be multiple of 5 plus 2.
1220                  */
1221                 if ((llen < 7) || (llen-2) % 5)
1222                         goto corrupt;
1223                 max_byte_length = (llen - 2) / 5 * 4;
1224                 byte_length = *buffer;
1225                 if ('A' <= byte_length && byte_length <= 'Z')
1226                         byte_length = byte_length - 'A' + 1;
1227                 else if ('a' <= byte_length && byte_length <= 'z')
1228                         byte_length = byte_length - 'a' + 27;
1229                 else
1230                         goto corrupt;
1231                 /* if the input length was not multiple of 4, we would
1232                  * have filler at the end but the filler should never
1233                  * exceed 3 bytes
1234                  */
1235                 if (max_byte_length < byte_length ||
1236                     byte_length <= max_byte_length - 4)
1237                         goto corrupt;
1238                 newsize = hunk_size + byte_length;
1239                 data = xrealloc(data, newsize);
1240                 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1241                         goto corrupt;
1242                 hunk_size = newsize;
1243                 buffer += llen;
1244                 size -= llen;
1245         }
1247         frag = xcalloc(1, sizeof(*frag));
1248         frag->patch = inflate_it(data, hunk_size, origlen);
1249         if (!frag->patch)
1250                 goto corrupt;
1251         free(data);
1252         frag->size = origlen;
1253         *buf_p = buffer;
1254         *sz_p = size;
1255         *used_p = used;
1256         frag->binary_patch_method = patch_method;
1257         return frag;
1259  corrupt:
1260         free(data);
1261         *status_p = -1;
1262         error("corrupt binary patch at line %d: %.*s",
1263               linenr-1, llen-1, buffer);
1264         return NULL;
1267 static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1269         /*
1270          * We have read "GIT binary patch\n"; what follows is a line
1271          * that says the patch method (currently, either "literal" or
1272          * "delta") and the length of data before deflating; a
1273          * sequence of 'length-byte' followed by base-85 encoded data
1274          * follows.
1275          *
1276          * When a binary patch is reversible, there is another binary
1277          * hunk in the same format, starting with patch method (either
1278          * "literal" or "delta") with the length of data, and a sequence
1279          * of length-byte + base-85 encoded data, terminated with another
1280          * empty line.  This data, when applied to the postimage, produces
1281          * the preimage.
1282          */
1283         struct fragment *forward;
1284         struct fragment *reverse;
1285         int status;
1286         int used, used_1;
1288         forward = parse_binary_hunk(&buffer, &size, &status, &used);
1289         if (!forward && !status)
1290                 /* there has to be one hunk (forward hunk) */
1291                 return error("unrecognized binary patch at line %d", linenr-1);
1292         if (status)
1293                 /* otherwise we already gave an error message */
1294                 return status;
1296         reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1297         if (reverse)
1298                 used += used_1;
1299         else if (status) {
1300                 /*
1301                  * Not having reverse hunk is not an error, but having
1302                  * a corrupt reverse hunk is.
1303                  */
1304                 free((void*) forward->patch);
1305                 free(forward);
1306                 return status;
1307         }
1308         forward->next = reverse;
1309         patch->fragments = forward;
1310         patch->is_binary = 1;
1311         return used;
1314 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
1316         int hdrsize, patchsize;
1317         int offset = find_header(buffer, size, &hdrsize, patch);
1319         if (offset < 0)
1320                 return offset;
1322         patch->ws_rule = whitespace_rule(patch->new_name
1323                                          ? patch->new_name
1324                                          : patch->old_name);
1326         patchsize = parse_single_patch(buffer + offset + hdrsize,
1327                                        size - offset - hdrsize, patch);
1329         if (!patchsize) {
1330                 static const char *binhdr[] = {
1331                         "Binary files ",
1332                         "Files ",
1333                         NULL,
1334                 };
1335                 static const char git_binary[] = "GIT binary patch\n";
1336                 int i;
1337                 int hd = hdrsize + offset;
1338                 unsigned long llen = linelen(buffer + hd, size - hd);
1340                 if (llen == sizeof(git_binary) - 1 &&
1341                     !memcmp(git_binary, buffer + hd, llen)) {
1342                         int used;
1343                         linenr++;
1344                         used = parse_binary(buffer + hd + llen,
1345                                             size - hd - llen, patch);
1346                         if (used)
1347                                 patchsize = used + llen;
1348                         else
1349                                 patchsize = 0;
1350                 }
1351                 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
1352                         for (i = 0; binhdr[i]; i++) {
1353                                 int len = strlen(binhdr[i]);
1354                                 if (len < size - hd &&
1355                                     !memcmp(binhdr[i], buffer + hd, len)) {
1356                                         linenr++;
1357                                         patch->is_binary = 1;
1358                                         patchsize = llen;
1359                                         break;
1360                                 }
1361                         }
1362                 }
1364                 /* Empty patch cannot be applied if it is a text patch
1365                  * without metadata change.  A binary patch appears
1366                  * empty to us here.
1367                  */
1368                 if ((apply || check) &&
1369                     (!patch->is_binary && !metadata_changes(patch)))
1370                         die("patch with only garbage at line %d", linenr);
1371         }
1373         return offset + hdrsize + patchsize;
1376 #define swap(a,b) myswap((a),(b),sizeof(a))
1378 #define myswap(a, b, size) do {         \
1379         unsigned char mytmp[size];      \
1380         memcpy(mytmp, &a, size);                \
1381         memcpy(&a, &b, size);           \
1382         memcpy(&b, mytmp, size);                \
1383 } while (0)
1385 static void reverse_patches(struct patch *p)
1387         for (; p; p = p->next) {
1388                 struct fragment *frag = p->fragments;
1390                 swap(p->new_name, p->old_name);
1391                 swap(p->new_mode, p->old_mode);
1392                 swap(p->is_new, p->is_delete);
1393                 swap(p->lines_added, p->lines_deleted);
1394                 swap(p->old_sha1_prefix, p->new_sha1_prefix);
1396                 for (; frag; frag = frag->next) {
1397                         swap(frag->newpos, frag->oldpos);
1398                         swap(frag->newlines, frag->oldlines);
1399                 }
1400         }
1403 static const char pluses[] =
1404 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1405 static const char minuses[]=
1406 "----------------------------------------------------------------------";
1408 static void show_stats(struct patch *patch)
1410         struct strbuf qname;
1411         char *cp = patch->new_name ? patch->new_name : patch->old_name;
1412         int max, add, del;
1414         strbuf_init(&qname, 0);
1415         quote_c_style(cp, &qname, NULL, 0);
1417         /*
1418          * "scale" the filename
1419          */
1420         max = max_len;
1421         if (max > 50)
1422                 max = 50;
1424         if (qname.len > max) {
1425                 cp = strchr(qname.buf + qname.len + 3 - max, '/');
1426                 if (!cp)
1427                         cp = qname.buf + qname.len + 3 - max;
1428                 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
1429         }
1431         if (patch->is_binary) {
1432                 printf(" %-*s |  Bin\n", max, qname.buf);
1433                 strbuf_release(&qname);
1434                 return;
1435         }
1437         printf(" %-*s |", max, qname.buf);
1438         strbuf_release(&qname);
1440         /*
1441          * scale the add/delete
1442          */
1443         max = max + max_change > 70 ? 70 - max : max_change;
1444         add = patch->lines_added;
1445         del = patch->lines_deleted;
1447         if (max_change > 0) {
1448                 int total = ((add + del) * max + max_change / 2) / max_change;
1449                 add = (add * max + max_change / 2) / max_change;
1450                 del = total - add;
1451         }
1452         printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
1453                 add, pluses, del, minuses);
1456 static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
1458         switch (st->st_mode & S_IFMT) {
1459         case S_IFLNK:
1460                 strbuf_grow(buf, st->st_size);
1461                 if (readlink(path, buf->buf, st->st_size) != st->st_size)
1462                         return -1;
1463                 strbuf_setlen(buf, st->st_size);
1464                 return 0;
1465         case S_IFREG:
1466                 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
1467                         return error("unable to open or read %s", path);
1468                 convert_to_git(path, buf->buf, buf->len, buf);
1469                 return 0;
1470         default:
1471                 return -1;
1472         }
1475 static int find_offset(const char *buf, unsigned long size,
1476                        const char *fragment, unsigned long fragsize,
1477                        int line, int *lines)
1479         int i;
1480         unsigned long start, backwards, forwards;
1482         if (fragsize > size)
1483                 return -1;
1485         start = 0;
1486         if (line > 1) {
1487                 unsigned long offset = 0;
1488                 i = line-1;
1489                 while (offset + fragsize <= size) {
1490                         if (buf[offset++] == '\n') {
1491                                 start = offset;
1492                                 if (!--i)
1493                                         break;
1494                         }
1495                 }
1496         }
1498         /* Exact line number? */
1499         if ((start + fragsize <= size) &&
1500             !memcmp(buf + start, fragment, fragsize))
1501                 return start;
1503         /*
1504          * There's probably some smart way to do this, but I'll leave
1505          * that to the smart and beautiful people. I'm simple and stupid.
1506          */
1507         backwards = start;
1508         forwards = start;
1509         for (i = 0; ; i++) {
1510                 unsigned long try;
1511                 int n;
1513                 /* "backward" */
1514                 if (i & 1) {
1515                         if (!backwards) {
1516                                 if (forwards + fragsize > size)
1517                                         break;
1518                                 continue;
1519                         }
1520                         do {
1521                                 --backwards;
1522                         } while (backwards && buf[backwards-1] != '\n');
1523                         try = backwards;
1524                 } else {
1525                         while (forwards + fragsize <= size) {
1526                                 if (buf[forwards++] == '\n')
1527                                         break;
1528                         }
1529                         try = forwards;
1530                 }
1532                 if (try + fragsize > size)
1533                         continue;
1534                 if (memcmp(buf + try, fragment, fragsize))
1535                         continue;
1536                 n = (i >> 1)+1;
1537                 if (i & 1)
1538                         n = -n;
1539                 *lines = n;
1540                 return try;
1541         }
1543         /*
1544          * We should start searching forward and backward.
1545          */
1546         return -1;
1549 static void remove_first_line(const char **rbuf, int *rsize)
1551         const char *buf = *rbuf;
1552         int size = *rsize;
1553         unsigned long offset;
1554         offset = 0;
1555         while (offset <= size) {
1556                 if (buf[offset++] == '\n')
1557                         break;
1558         }
1559         *rsize = size - offset;
1560         *rbuf = buf + offset;
1563 static void remove_last_line(const char **rbuf, int *rsize)
1565         const char *buf = *rbuf;
1566         int size = *rsize;
1567         unsigned long offset;
1568         offset = size - 1;
1569         while (offset > 0) {
1570                 if (buf[--offset] == '\n')
1571                         break;
1572         }
1573         *rsize = offset + 1;
1576 static int apply_line(char *output, const char *patch, int plen,
1577                       unsigned ws_rule)
1579         /*
1580          * plen is number of bytes to be copied from patch,
1581          * starting at patch+1 (patch[0] is '+').  Typically
1582          * patch[plen] is '\n', unless this is the incomplete
1583          * last line.
1584          */
1585         int i;
1586         int add_nl_to_tail = 0;
1587         int fixed = 0;
1588         int last_tab_in_indent = -1;
1589         int last_space_in_indent = -1;
1590         int need_fix_leading_space = 0;
1591         char *buf;
1593         if ((ws_error_action != correct_ws_error) || !whitespace_error ||
1594             *patch != '+') {
1595                 memcpy(output, patch + 1, plen);
1596                 return plen;
1597         }
1599         /*
1600          * Strip trailing whitespace
1601          */
1602         if ((ws_rule & WS_TRAILING_SPACE) &&
1603             (1 < plen && isspace(patch[plen-1]))) {
1604                 if (patch[plen] == '\n')
1605                         add_nl_to_tail = 1;
1606                 plen--;
1607                 while (0 < plen && isspace(patch[plen]))
1608                         plen--;
1609                 fixed = 1;
1610         }
1612         /*
1613          * Check leading whitespaces (indent)
1614          */
1615         for (i = 1; i < plen; i++) {
1616                 char ch = patch[i];
1617                 if (ch == '\t') {
1618                         last_tab_in_indent = i;
1619                         if ((ws_rule & WS_SPACE_BEFORE_TAB) &&
1620                             0 <= last_space_in_indent)
1621                             need_fix_leading_space = 1;
1622                 } else if (ch == ' ') {
1623                         last_space_in_indent = i;
1624                         if ((ws_rule & WS_INDENT_WITH_NON_TAB) &&
1625                             last_tab_in_indent < 0 &&
1626                             8 <= i)
1627                                 need_fix_leading_space = 1;
1628                 }
1629                 else
1630                         break;
1631         }
1633         buf = output;
1634         if (need_fix_leading_space) {
1635                 int consecutive_spaces = 0;
1636                 int last = last_tab_in_indent + 1;
1638                 if (ws_rule & WS_INDENT_WITH_NON_TAB) {
1639                         /* have "last" point at one past the indent */
1640                         if (last_tab_in_indent < last_space_in_indent)
1641                                 last = last_space_in_indent + 1;
1642                         else
1643                                 last = last_tab_in_indent + 1;
1644                 }
1646                 /*
1647                  * between patch[1..last], strip the funny spaces,
1648                  * updating them to tab as needed.
1649                  */
1650                 for (i = 1; i < last; i++, plen--) {
1651                         char ch = patch[i];
1652                         if (ch != ' ') {
1653                                 consecutive_spaces = 0;
1654                                 *output++ = ch;
1655                         } else {
1656                                 consecutive_spaces++;
1657                                 if (consecutive_spaces == 8) {
1658                                         *output++ = '\t';
1659                                         consecutive_spaces = 0;
1660                                 }
1661                         }
1662                 }
1663                 while (0 < consecutive_spaces--)
1664                         *output++ = ' ';
1665                 fixed = 1;
1666                 i = last;
1667         }
1668         else
1669                 i = 1;
1671         memcpy(output, patch + i, plen);
1672         if (add_nl_to_tail)
1673                 output[plen++] = '\n';
1674         if (fixed)
1675                 applied_after_fixing_ws++;
1676         return output + plen - buf;
1679 static int apply_one_fragment(struct strbuf *buf, struct fragment *frag,
1680                               int inaccurate_eof, unsigned ws_rule)
1682         int match_beginning, match_end;
1683         const char *patch = frag->patch;
1684         int offset, size = frag->size;
1685         char *old = xmalloc(size);
1686         char *new = xmalloc(size);
1687         const char *oldlines, *newlines;
1688         int oldsize = 0, newsize = 0;
1689         int new_blank_lines_at_end = 0;
1690         unsigned long leading, trailing;
1691         int pos, lines;
1693         while (size > 0) {
1694                 char first;
1695                 int len = linelen(patch, size);
1696                 int plen;
1697                 int added_blank_line = 0;
1699                 if (!len)
1700                         break;
1702                 /*
1703                  * "plen" is how much of the line we should use for
1704                  * the actual patch data. Normally we just remove the
1705                  * first character on the line, but if the line is
1706                  * followed by "\ No newline", then we also remove the
1707                  * last one (which is the newline, of course).
1708                  */
1709                 plen = len-1;
1710                 if (len < size && patch[len] == '\\')
1711                         plen--;
1712                 first = *patch;
1713                 if (apply_in_reverse) {
1714                         if (first == '-')
1715                                 first = '+';
1716                         else if (first == '+')
1717                                 first = '-';
1718                 }
1720                 switch (first) {
1721                 case '\n':
1722                         /* Newer GNU diff, empty context line */
1723                         if (plen < 0)
1724                                 /* ... followed by '\No newline'; nothing */
1725                                 break;
1726                         old[oldsize++] = '\n';
1727                         new[newsize++] = '\n';
1728                         break;
1729                 case ' ':
1730                 case '-':
1731                         memcpy(old + oldsize, patch + 1, plen);
1732                         oldsize += plen;
1733                         if (first == '-')
1734                                 break;
1735                 /* Fall-through for ' ' */
1736                 case '+':
1737                         if (first != '+' || !no_add) {
1738                                 int added = apply_line(new + newsize, patch,
1739                                                        plen, ws_rule);
1740                                 newsize += added;
1741                                 if (first == '+' &&
1742                                     added == 1 && new[newsize-1] == '\n')
1743                                         added_blank_line = 1;
1744                         }
1745                         break;
1746                 case '@': case '\\':
1747                         /* Ignore it, we already handled it */
1748                         break;
1749                 default:
1750                         if (apply_verbosely)
1751                                 error("invalid start of line: '%c'", first);
1752                         return -1;
1753                 }
1754                 if (added_blank_line)
1755                         new_blank_lines_at_end++;
1756                 else
1757                         new_blank_lines_at_end = 0;
1758                 patch += len;
1759                 size -= len;
1760         }
1762         if (inaccurate_eof &&
1763             oldsize > 0 && old[oldsize - 1] == '\n' &&
1764             newsize > 0 && new[newsize - 1] == '\n') {
1765                 oldsize--;
1766                 newsize--;
1767         }
1769         oldlines = old;
1770         newlines = new;
1771         leading = frag->leading;
1772         trailing = frag->trailing;
1774         /*
1775          * If we don't have any leading/trailing data in the patch,
1776          * we want it to match at the beginning/end of the file.
1777          *
1778          * But that would break if the patch is generated with
1779          * --unified=0; sane people wouldn't do that to cause us
1780          * trouble, but we try to please not so sane ones as well.
1781          */
1782         if (unidiff_zero) {
1783                 match_beginning = (!leading && !frag->oldpos);
1784                 match_end = 0;
1785         }
1786         else {
1787                 match_beginning = !leading && (frag->oldpos == 1);
1788                 match_end = !trailing;
1789         }
1791         lines = 0;
1792         pos = frag->newpos;
1793         for (;;) {
1794                 offset = find_offset(buf->buf, buf->len,
1795                                      oldlines, oldsize, pos, &lines);
1796                 if (match_end && offset + oldsize != buf->len)
1797                         offset = -1;
1798                 if (match_beginning && offset)
1799                         offset = -1;
1800                 if (offset >= 0) {
1801                         if (ws_error_action == correct_ws_error &&
1802                             (buf->len - oldsize - offset == 0)) /* end of file? */
1803                                 newsize -= new_blank_lines_at_end;
1805                         /* Warn if it was necessary to reduce the number
1806                          * of context lines.
1807                          */
1808                         if ((leading != frag->leading) ||
1809                             (trailing != frag->trailing))
1810                                 fprintf(stderr, "Context reduced to (%ld/%ld)"
1811                                         " to apply fragment at %d\n",
1812                                         leading, trailing, pos + lines);
1814                         strbuf_splice(buf, offset, oldsize, newlines, newsize);
1815                         offset = 0;
1816                         break;
1817                 }
1819                 /* Am I at my context limits? */
1820                 if ((leading <= p_context) && (trailing <= p_context))
1821                         break;
1822                 if (match_beginning || match_end) {
1823                         match_beginning = match_end = 0;
1824                         continue;
1825                 }
1826                 /*
1827                  * Reduce the number of context lines; reduce both
1828                  * leading and trailing if they are equal otherwise
1829                  * just reduce the larger context.
1830                  */
1831                 if (leading >= trailing) {
1832                         remove_first_line(&oldlines, &oldsize);
1833                         remove_first_line(&newlines, &newsize);
1834                         pos--;
1835                         leading--;
1836                 }
1837                 if (trailing > leading) {
1838                         remove_last_line(&oldlines, &oldsize);
1839                         remove_last_line(&newlines, &newsize);
1840                         trailing--;
1841                 }
1842         }
1844         if (offset && apply_verbosely)
1845                 error("while searching for:\n%.*s", oldsize, oldlines);
1847         free(old);
1848         free(new);
1849         return offset;
1852 static int apply_binary_fragment(struct strbuf *buf, struct patch *patch)
1854         struct fragment *fragment = patch->fragments;
1855         unsigned long len;
1856         void *dst;
1858         /* Binary patch is irreversible without the optional second hunk */
1859         if (apply_in_reverse) {
1860                 if (!fragment->next)
1861                         return error("cannot reverse-apply a binary patch "
1862                                      "without the reverse hunk to '%s'",
1863                                      patch->new_name
1864                                      ? patch->new_name : patch->old_name);
1865                 fragment = fragment->next;
1866         }
1867         switch (fragment->binary_patch_method) {
1868         case BINARY_DELTA_DEFLATED:
1869                 dst = patch_delta(buf->buf, buf->len, fragment->patch,
1870                                   fragment->size, &len);
1871                 if (!dst)
1872                         return -1;
1873                 /* XXX patch_delta NUL-terminates */
1874                 strbuf_attach(buf, dst, len, len + 1);
1875                 return 0;
1876         case BINARY_LITERAL_DEFLATED:
1877                 strbuf_reset(buf);
1878                 strbuf_add(buf, fragment->patch, fragment->size);
1879                 return 0;
1880         }
1881         return -1;
1884 static int apply_binary(struct strbuf *buf, struct patch *patch)
1886         const char *name = patch->old_name ? patch->old_name : patch->new_name;
1887         unsigned char sha1[20];
1889         /*
1890          * For safety, we require patch index line to contain
1891          * full 40-byte textual SHA1 for old and new, at least for now.
1892          */
1893         if (strlen(patch->old_sha1_prefix) != 40 ||
1894             strlen(patch->new_sha1_prefix) != 40 ||
1895             get_sha1_hex(patch->old_sha1_prefix, sha1) ||
1896             get_sha1_hex(patch->new_sha1_prefix, sha1))
1897                 return error("cannot apply binary patch to '%s' "
1898                              "without full index line", name);
1900         if (patch->old_name) {
1901                 /*
1902                  * See if the old one matches what the patch
1903                  * applies to.
1904                  */
1905                 hash_sha1_file(buf->buf, buf->len, blob_type, sha1);
1906                 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
1907                         return error("the patch applies to '%s' (%s), "
1908                                      "which does not match the "
1909                                      "current contents.",
1910                                      name, sha1_to_hex(sha1));
1911         }
1912         else {
1913                 /* Otherwise, the old one must be empty. */
1914                 if (buf->len)
1915                         return error("the patch applies to an empty "
1916                                      "'%s' but it is not empty", name);
1917         }
1919         get_sha1_hex(patch->new_sha1_prefix, sha1);
1920         if (is_null_sha1(sha1)) {
1921                 strbuf_release(buf);
1922                 return 0; /* deletion patch */
1923         }
1925         if (has_sha1_file(sha1)) {
1926                 /* We already have the postimage */
1927                 enum object_type type;
1928                 unsigned long size;
1929                 char *result;
1931                 result = read_sha1_file(sha1, &type, &size);
1932                 if (!result)
1933                         return error("the necessary postimage %s for "
1934                                      "'%s' cannot be read",
1935                                      patch->new_sha1_prefix, name);
1936                 /* XXX read_sha1_file NUL-terminates */
1937                 strbuf_attach(buf, result, size, size + 1);
1938         } else {
1939                 /*
1940                  * We have verified buf matches the preimage;
1941                  * apply the patch data to it, which is stored
1942                  * in the patch->fragments->{patch,size}.
1943                  */
1944                 if (apply_binary_fragment(buf, patch))
1945                         return error("binary patch does not apply to '%s'",
1946                                      name);
1948                 /* verify that the result matches */
1949                 hash_sha1_file(buf->buf, buf->len, blob_type, sha1);
1950                 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
1951                         return error("binary patch to '%s' creates incorrect result (expecting %s, got %s)",
1952                                 name, patch->new_sha1_prefix, sha1_to_hex(sha1));
1953         }
1955         return 0;
1958 static int apply_fragments(struct strbuf *buf, struct patch *patch)
1960         struct fragment *frag = patch->fragments;
1961         const char *name = patch->old_name ? patch->old_name : patch->new_name;
1962         unsigned ws_rule = patch->ws_rule;
1963         unsigned inaccurate_eof = patch->inaccurate_eof;
1965         if (patch->is_binary)
1966                 return apply_binary(buf, patch);
1968         while (frag) {
1969                 if (apply_one_fragment(buf, frag, inaccurate_eof, ws_rule)) {
1970                         error("patch failed: %s:%ld", name, frag->oldpos);
1971                         if (!apply_with_reject)
1972                                 return -1;
1973                         frag->rejected = 1;
1974                 }
1975                 frag = frag->next;
1976         }
1977         return 0;
1980 static int read_file_or_gitlink(struct cache_entry *ce, struct strbuf *buf)
1982         if (!ce)
1983                 return 0;
1985         if (S_ISGITLINK(ntohl(ce->ce_mode))) {
1986                 strbuf_grow(buf, 100);
1987                 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(ce->sha1));
1988         } else {
1989                 enum object_type type;
1990                 unsigned long sz;
1991                 char *result;
1993                 result = read_sha1_file(ce->sha1, &type, &sz);
1994                 if (!result)
1995                         return -1;
1996                 /* XXX read_sha1_file NUL-terminates */
1997                 strbuf_attach(buf, result, sz, sz + 1);
1998         }
1999         return 0;
2002 static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce)
2004         struct strbuf buf;
2006         strbuf_init(&buf, 0);
2007         if (cached) {
2008                 if (read_file_or_gitlink(ce, &buf))
2009                         return error("read of %s failed", patch->old_name);
2010         } else if (patch->old_name) {
2011                 if (S_ISGITLINK(patch->old_mode)) {
2012                         if (ce) {
2013                                 read_file_or_gitlink(ce, &buf);
2014                         } else {
2015                                 /*
2016                                  * There is no way to apply subproject
2017                                  * patch without looking at the index.
2018                                  */
2019                                 patch->fragments = NULL;
2020                         }
2021                 } else {
2022                         if (read_old_data(st, patch->old_name, &buf))
2023                                 return error("read of %s failed", patch->old_name);
2024                 }
2025         }
2027         if (apply_fragments(&buf, patch) < 0)
2028                 return -1; /* note with --reject this succeeds. */
2029         patch->result = strbuf_detach(&buf, &patch->resultsize);
2031         if (0 < patch->is_delete && patch->resultsize)
2032                 return error("removal patch leaves file contents");
2034         return 0;
2037 static int check_to_create_blob(const char *new_name, int ok_if_exists)
2039         struct stat nst;
2040         if (!lstat(new_name, &nst)) {
2041                 if (S_ISDIR(nst.st_mode) || ok_if_exists)
2042                         return 0;
2043                 /*
2044                  * A leading component of new_name might be a symlink
2045                  * that is going to be removed with this patch, but
2046                  * still pointing at somewhere that has the path.
2047                  * In such a case, path "new_name" does not exist as
2048                  * far as git is concerned.
2049                  */
2050                 if (has_symlink_leading_path(new_name, NULL))
2051                         return 0;
2053                 return error("%s: already exists in working directory", new_name);
2054         }
2055         else if ((errno != ENOENT) && (errno != ENOTDIR))
2056                 return error("%s: %s", new_name, strerror(errno));
2057         return 0;
2060 static int verify_index_match(struct cache_entry *ce, struct stat *st)
2062         if (S_ISGITLINK(ntohl(ce->ce_mode))) {
2063                 if (!S_ISDIR(st->st_mode))
2064                         return -1;
2065                 return 0;
2066         }
2067         return ce_match_stat(ce, st, 1);
2070 static int check_patch(struct patch *patch, struct patch *prev_patch)
2072         struct stat st;
2073         const char *old_name = patch->old_name;
2074         const char *new_name = patch->new_name;
2075         const char *name = old_name ? old_name : new_name;
2076         struct cache_entry *ce = NULL;
2077         int ok_if_exists;
2079         patch->rejected = 1; /* we will drop this after we succeed */
2081         /*
2082          * Make sure that we do not have local modifications from the
2083          * index when we are looking at the index.  Also make sure
2084          * we have the preimage file to be patched in the work tree,
2085          * unless --cached, which tells git to apply only in the index.
2086          */
2087         if (old_name) {
2088                 int stat_ret = 0;
2089                 unsigned st_mode = 0;
2091                 if (!cached)
2092                         stat_ret = lstat(old_name, &st);
2093                 if (check_index) {
2094                         int pos = cache_name_pos(old_name, strlen(old_name));
2095                         if (pos < 0)
2096                                 return error("%s: does not exist in index",
2097                                              old_name);
2098                         ce = active_cache[pos];
2099                         if (stat_ret < 0) {
2100                                 struct checkout costate;
2101                                 if (errno != ENOENT)
2102                                         return error("%s: %s", old_name,
2103                                                      strerror(errno));
2104                                 /* checkout */
2105                                 costate.base_dir = "";
2106                                 costate.base_dir_len = 0;
2107                                 costate.force = 0;
2108                                 costate.quiet = 0;
2109                                 costate.not_new = 0;
2110                                 costate.refresh_cache = 1;
2111                                 if (checkout_entry(ce,
2112                                                    &costate,
2113                                                    NULL) ||
2114                                     lstat(old_name, &st))
2115                                         return -1;
2116                         }
2117                         if (!cached && verify_index_match(ce, &st))
2118                                 return error("%s: does not match index",
2119                                              old_name);
2120                         if (cached)
2121                                 st_mode = ntohl(ce->ce_mode);
2122                 } else if (stat_ret < 0)
2123                         return error("%s: %s", old_name, strerror(errno));
2125                 if (!cached)
2126                         st_mode = ntohl(ce_mode_from_stat(ce, st.st_mode));
2128                 if (patch->is_new < 0)
2129                         patch->is_new = 0;
2130                 if (!patch->old_mode)
2131                         patch->old_mode = st_mode;
2132                 if ((st_mode ^ patch->old_mode) & S_IFMT)
2133                         return error("%s: wrong type", old_name);
2134                 if (st_mode != patch->old_mode)
2135                         fprintf(stderr, "warning: %s has type %o, expected %o\n",
2136                                 old_name, st_mode, patch->old_mode);
2137         }
2139         if (new_name && prev_patch && 0 < prev_patch->is_delete &&
2140             !strcmp(prev_patch->old_name, new_name))
2141                 /*
2142                  * A type-change diff is always split into a patch to
2143                  * delete old, immediately followed by a patch to
2144                  * create new (see diff.c::run_diff()); in such a case
2145                  * it is Ok that the entry to be deleted by the
2146                  * previous patch is still in the working tree and in
2147                  * the index.
2148                  */
2149                 ok_if_exists = 1;
2150         else
2151                 ok_if_exists = 0;
2153         if (new_name &&
2154             ((0 < patch->is_new) | (0 < patch->is_rename) | patch->is_copy)) {
2155                 if (check_index &&
2156                     cache_name_pos(new_name, strlen(new_name)) >= 0 &&
2157                     !ok_if_exists)
2158                         return error("%s: already exists in index", new_name);
2159                 if (!cached) {
2160                         int err = check_to_create_blob(new_name, ok_if_exists);
2161                         if (err)
2162                                 return err;
2163                 }
2164                 if (!patch->new_mode) {
2165                         if (0 < patch->is_new)
2166                                 patch->new_mode = S_IFREG | 0644;
2167                         else
2168                                 patch->new_mode = patch->old_mode;
2169                 }
2170         }
2172         if (new_name && old_name) {
2173                 int same = !strcmp(old_name, new_name);
2174                 if (!patch->new_mode)
2175                         patch->new_mode = patch->old_mode;
2176                 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
2177                         return error("new mode (%o) of %s does not match old mode (%o)%s%s",
2178                                 patch->new_mode, new_name, patch->old_mode,
2179                                 same ? "" : " of ", same ? "" : old_name);
2180         }
2182         if (apply_data(patch, &st, ce) < 0)
2183                 return error("%s: patch does not apply", name);
2184         patch->rejected = 0;
2185         return 0;
2188 static int check_patch_list(struct patch *patch)
2190         struct patch *prev_patch = NULL;
2191         int err = 0;
2193         for (prev_patch = NULL; patch ; patch = patch->next) {
2194                 if (apply_verbosely)
2195                         say_patch_name(stderr,
2196                                        "Checking patch ", patch, "...\n");
2197                 err |= check_patch(patch, prev_patch);
2198                 prev_patch = patch;
2199         }
2200         return err;
2203 /* This function tries to read the sha1 from the current index */
2204 static int get_current_sha1(const char *path, unsigned char *sha1)
2206         int pos;
2208         if (read_cache() < 0)
2209                 return -1;
2210         pos = cache_name_pos(path, strlen(path));
2211         if (pos < 0)
2212                 return -1;
2213         hashcpy(sha1, active_cache[pos]->sha1);
2214         return 0;
2217 /* Build an index that contains the just the files needed for a 3way merge */
2218 static void build_fake_ancestor(struct patch *list, const char *filename)
2220         struct patch *patch;
2221         struct index_state result = { 0 };
2222         int fd;
2224         /* Once we start supporting the reverse patch, it may be
2225          * worth showing the new sha1 prefix, but until then...
2226          */
2227         for (patch = list; patch; patch = patch->next) {
2228                 const unsigned char *sha1_ptr;
2229                 unsigned char sha1[20];
2230                 struct cache_entry *ce;
2231                 const char *name;
2233                 name = patch->old_name ? patch->old_name : patch->new_name;
2234                 if (0 < patch->is_new)
2235                         continue;
2236                 else if (get_sha1(patch->old_sha1_prefix, sha1))
2237                         /* git diff has no index line for mode/type changes */
2238                         if (!patch->lines_added && !patch->lines_deleted) {
2239                                 if (get_current_sha1(patch->new_name, sha1) ||
2240                                     get_current_sha1(patch->old_name, sha1))
2241                                         die("mode change for %s, which is not "
2242                                                 "in current HEAD", name);
2243                                 sha1_ptr = sha1;
2244                         } else
2245                                 die("sha1 information is lacking or useless "
2246                                         "(%s).", name);
2247                 else
2248                         sha1_ptr = sha1;
2250                 ce = make_cache_entry(patch->old_mode, sha1_ptr, name, 0, 0);
2251                 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))
2252                         die ("Could not add %s to temporary index", name);
2253         }
2255         fd = open(filename, O_WRONLY | O_CREAT, 0666);
2256         if (fd < 0 || write_index(&result, fd) || close(fd))
2257                 die ("Could not write temporary index to %s", filename);
2259         discard_index(&result);
2262 static void stat_patch_list(struct patch *patch)
2264         int files, adds, dels;
2266         for (files = adds = dels = 0 ; patch ; patch = patch->next) {
2267                 files++;
2268                 adds += patch->lines_added;
2269                 dels += patch->lines_deleted;
2270                 show_stats(patch);
2271         }
2273         printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
2276 static void numstat_patch_list(struct patch *patch)
2278         for ( ; patch; patch = patch->next) {
2279                 const char *name;
2280                 name = patch->new_name ? patch->new_name : patch->old_name;
2281                 if (patch->is_binary)
2282                         printf("-\t-\t");
2283                 else
2284                         printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
2285                 write_name_quoted(name, stdout, line_termination);
2286         }
2289 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
2291         if (mode)
2292                 printf(" %s mode %06o %s\n", newdelete, mode, name);
2293         else
2294                 printf(" %s %s\n", newdelete, name);
2297 static void show_mode_change(struct patch *p, int show_name)
2299         if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
2300                 if (show_name)
2301                         printf(" mode change %06o => %06o %s\n",
2302                                p->old_mode, p->new_mode, p->new_name);
2303                 else
2304                         printf(" mode change %06o => %06o\n",
2305                                p->old_mode, p->new_mode);
2306         }
2309 static void show_rename_copy(struct patch *p)
2311         const char *renamecopy = p->is_rename ? "rename" : "copy";
2312         const char *old, *new;
2314         /* Find common prefix */
2315         old = p->old_name;
2316         new = p->new_name;
2317         while (1) {
2318                 const char *slash_old, *slash_new;
2319                 slash_old = strchr(old, '/');
2320                 slash_new = strchr(new, '/');
2321                 if (!slash_old ||
2322                     !slash_new ||
2323                     slash_old - old != slash_new - new ||
2324                     memcmp(old, new, slash_new - new))
2325                         break;
2326                 old = slash_old + 1;
2327                 new = slash_new + 1;
2328         }
2329         /* p->old_name thru old is the common prefix, and old and new
2330          * through the end of names are renames
2331          */
2332         if (old != p->old_name)
2333                 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
2334                        (int)(old - p->old_name), p->old_name,
2335                        old, new, p->score);
2336         else
2337                 printf(" %s %s => %s (%d%%)\n", renamecopy,
2338                        p->old_name, p->new_name, p->score);
2339         show_mode_change(p, 0);
2342 static void summary_patch_list(struct patch *patch)
2344         struct patch *p;
2346         for (p = patch; p; p = p->next) {
2347                 if (p->is_new)
2348                         show_file_mode_name("create", p->new_mode, p->new_name);
2349                 else if (p->is_delete)
2350                         show_file_mode_name("delete", p->old_mode, p->old_name);
2351                 else {
2352                         if (p->is_rename || p->is_copy)
2353                                 show_rename_copy(p);
2354                         else {
2355                                 if (p->score) {
2356                                         printf(" rewrite %s (%d%%)\n",
2357                                                p->new_name, p->score);
2358                                         show_mode_change(p, 0);
2359                                 }
2360                                 else
2361                                         show_mode_change(p, 1);
2362                         }
2363                 }
2364         }
2367 static void patch_stats(struct patch *patch)
2369         int lines = patch->lines_added + patch->lines_deleted;
2371         if (lines > max_change)
2372                 max_change = lines;
2373         if (patch->old_name) {
2374                 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
2375                 if (!len)
2376                         len = strlen(patch->old_name);
2377                 if (len > max_len)
2378                         max_len = len;
2379         }
2380         if (patch->new_name) {
2381                 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
2382                 if (!len)
2383                         len = strlen(patch->new_name);
2384                 if (len > max_len)
2385                         max_len = len;
2386         }
2389 static void remove_file(struct patch *patch, int rmdir_empty)
2391         if (update_index) {
2392                 if (remove_file_from_cache(patch->old_name) < 0)
2393                         die("unable to remove %s from index", patch->old_name);
2394         }
2395         if (!cached) {
2396                 if (S_ISGITLINK(patch->old_mode)) {
2397                         if (rmdir(patch->old_name))
2398                                 warning("unable to remove submodule %s",
2399                                         patch->old_name);
2400                 } else if (!unlink(patch->old_name) && rmdir_empty) {
2401                         char *name = xstrdup(patch->old_name);
2402                         char *end = strrchr(name, '/');
2403                         while (end) {
2404                                 *end = 0;
2405                                 if (rmdir(name))
2406                                         break;
2407                                 end = strrchr(name, '/');
2408                         }
2409                         free(name);
2410                 }
2411         }
2414 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
2416         struct stat st;
2417         struct cache_entry *ce;
2418         int namelen = strlen(path);
2419         unsigned ce_size = cache_entry_size(namelen);
2421         if (!update_index)
2422                 return;
2424         ce = xcalloc(1, ce_size);
2425         memcpy(ce->name, path, namelen);
2426         ce->ce_mode = create_ce_mode(mode);
2427         ce->ce_flags = htons(namelen);
2428         if (S_ISGITLINK(mode)) {
2429                 const char *s = buf;
2431                 if (get_sha1_hex(s + strlen("Subproject commit "), ce->sha1))
2432                         die("corrupt patch for subproject %s", path);
2433         } else {
2434                 if (!cached) {
2435                         if (lstat(path, &st) < 0)
2436                                 die("unable to stat newly created file %s",
2437                                     path);
2438                         fill_stat_cache_info(ce, &st);
2439                 }
2440                 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
2441                         die("unable to create backing store for newly created file %s", path);
2442         }
2443         if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
2444                 die("unable to add cache entry for %s", path);
2447 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
2449         int fd;
2450         struct strbuf nbuf;
2452         if (S_ISGITLINK(mode)) {
2453                 struct stat st;
2454                 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
2455                         return 0;
2456                 return mkdir(path, 0777);
2457         }
2459         if (has_symlinks && S_ISLNK(mode))
2460                 /* Although buf:size is counted string, it also is NUL
2461                  * terminated.
2462                  */
2463                 return symlink(buf, path);
2465         fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
2466         if (fd < 0)
2467                 return -1;
2469         strbuf_init(&nbuf, 0);
2470         if (convert_to_working_tree(path, buf, size, &nbuf)) {
2471                 size = nbuf.len;
2472                 buf  = nbuf.buf;
2473         }
2474         write_or_die(fd, buf, size);
2475         strbuf_release(&nbuf);
2477         if (close(fd) < 0)
2478                 die("closing file %s: %s", path, strerror(errno));
2479         return 0;
2482 /*
2483  * We optimistically assume that the directories exist,
2484  * which is true 99% of the time anyway. If they don't,
2485  * we create them and try again.
2486  */
2487 static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
2489         if (cached)
2490                 return;
2491         if (!try_create_file(path, mode, buf, size))
2492                 return;
2494         if (errno == ENOENT) {
2495                 if (safe_create_leading_directories(path))
2496                         return;
2497                 if (!try_create_file(path, mode, buf, size))
2498                         return;
2499         }
2501         if (errno == EEXIST || errno == EACCES) {
2502                 /* We may be trying to create a file where a directory
2503                  * used to be.
2504                  */
2505                 struct stat st;
2506                 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
2507                         errno = EEXIST;
2508         }
2510         if (errno == EEXIST) {
2511                 unsigned int nr = getpid();
2513                 for (;;) {
2514                         const char *newpath;
2515                         newpath = mkpath("%s~%u", path, nr);
2516                         if (!try_create_file(newpath, mode, buf, size)) {
2517                                 if (!rename(newpath, path))
2518                                         return;
2519                                 unlink(newpath);
2520                                 break;
2521                         }
2522                         if (errno != EEXIST)
2523                                 break;
2524                         ++nr;
2525                 }
2526         }
2527         die("unable to write file %s mode %o", path, mode);
2530 static void create_file(struct patch *patch)
2532         char *path = patch->new_name;
2533         unsigned mode = patch->new_mode;
2534         unsigned long size = patch->resultsize;
2535         char *buf = patch->result;
2537         if (!mode)
2538                 mode = S_IFREG | 0644;
2539         create_one_file(path, mode, buf, size);
2540         add_index_file(path, mode, buf, size);
2543 /* phase zero is to remove, phase one is to create */
2544 static void write_out_one_result(struct patch *patch, int phase)
2546         if (patch->is_delete > 0) {
2547                 if (phase == 0)
2548                         remove_file(patch, 1);
2549                 return;
2550         }
2551         if (patch->is_new > 0 || patch->is_copy) {
2552                 if (phase == 1)
2553                         create_file(patch);
2554                 return;
2555         }
2556         /*
2557          * Rename or modification boils down to the same
2558          * thing: remove the old, write the new
2559          */
2560         if (phase == 0)
2561                 remove_file(patch, patch->is_rename);
2562         if (phase == 1)
2563                 create_file(patch);
2566 static int write_out_one_reject(struct patch *patch)
2568         FILE *rej;
2569         char namebuf[PATH_MAX];
2570         struct fragment *frag;
2571         int cnt = 0;
2573         for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
2574                 if (!frag->rejected)
2575                         continue;
2576                 cnt++;
2577         }
2579         if (!cnt) {
2580                 if (apply_verbosely)
2581                         say_patch_name(stderr,
2582                                        "Applied patch ", patch, " cleanly.\n");
2583                 return 0;
2584         }
2586         /* This should not happen, because a removal patch that leaves
2587          * contents are marked "rejected" at the patch level.
2588          */
2589         if (!patch->new_name)
2590                 die("internal error");
2592         /* Say this even without --verbose */
2593         say_patch_name(stderr, "Applying patch ", patch, " with");
2594         fprintf(stderr, " %d rejects...\n", cnt);
2596         cnt = strlen(patch->new_name);
2597         if (ARRAY_SIZE(namebuf) <= cnt + 5) {
2598                 cnt = ARRAY_SIZE(namebuf) - 5;
2599                 fprintf(stderr,
2600                         "warning: truncating .rej filename to %.*s.rej",
2601                         cnt - 1, patch->new_name);
2602         }
2603         memcpy(namebuf, patch->new_name, cnt);
2604         memcpy(namebuf + cnt, ".rej", 5);
2606         rej = fopen(namebuf, "w");
2607         if (!rej)
2608                 return error("cannot open %s: %s", namebuf, strerror(errno));
2610         /* Normal git tools never deal with .rej, so do not pretend
2611          * this is a git patch by saying --git nor give extended
2612          * headers.  While at it, maybe please "kompare" that wants
2613          * the trailing TAB and some garbage at the end of line ;-).
2614          */
2615         fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
2616                 patch->new_name, patch->new_name);
2617         for (cnt = 1, frag = patch->fragments;
2618              frag;
2619              cnt++, frag = frag->next) {
2620                 if (!frag->rejected) {
2621                         fprintf(stderr, "Hunk #%d applied cleanly.\n", cnt);
2622                         continue;
2623                 }
2624                 fprintf(stderr, "Rejected hunk #%d.\n", cnt);
2625                 fprintf(rej, "%.*s", frag->size, frag->patch);
2626                 if (frag->patch[frag->size-1] != '\n')
2627                         fputc('\n', rej);
2628         }
2629         fclose(rej);
2630         return -1;
2633 static int write_out_results(struct patch *list, int skipped_patch)
2635         int phase;
2636         int errs = 0;
2637         struct patch *l;
2639         if (!list && !skipped_patch)
2640                 return error("No changes");
2642         for (phase = 0; phase < 2; phase++) {
2643                 l = list;
2644                 while (l) {
2645                         if (l->rejected)
2646                                 errs = 1;
2647                         else {
2648                                 write_out_one_result(l, phase);
2649                                 if (phase == 1 && write_out_one_reject(l))
2650                                         errs = 1;
2651                         }
2652                         l = l->next;
2653                 }
2654         }
2655         return errs;
2658 static struct lock_file lock_file;
2660 static struct excludes {
2661         struct excludes *next;
2662         const char *path;
2663 } *excludes;
2665 static int use_patch(struct patch *p)
2667         const char *pathname = p->new_name ? p->new_name : p->old_name;
2668         struct excludes *x = excludes;
2669         while (x) {
2670                 if (fnmatch(x->path, pathname, 0) == 0)
2671                         return 0;
2672                 x = x->next;
2673         }
2674         if (0 < prefix_length) {
2675                 int pathlen = strlen(pathname);
2676                 if (pathlen <= prefix_length ||
2677                     memcmp(prefix, pathname, prefix_length))
2678                         return 0;
2679         }
2680         return 1;
2683 static void prefix_one(char **name)
2685         char *old_name = *name;
2686         if (!old_name)
2687                 return;
2688         *name = xstrdup(prefix_filename(prefix, prefix_length, *name));
2689         free(old_name);
2692 static void prefix_patches(struct patch *p)
2694         if (!prefix || p->is_toplevel_relative)
2695                 return;
2696         for ( ; p; p = p->next) {
2697                 if (p->new_name == p->old_name) {
2698                         char *prefixed = p->new_name;
2699                         prefix_one(&prefixed);
2700                         p->new_name = p->old_name = prefixed;
2701                 }
2702                 else {
2703                         prefix_one(&p->new_name);
2704                         prefix_one(&p->old_name);
2705                 }
2706         }
2709 static int apply_patch(int fd, const char *filename, int inaccurate_eof)
2711         size_t offset;
2712         struct strbuf buf;
2713         struct patch *list = NULL, **listp = &list;
2714         int skipped_patch = 0;
2716         strbuf_init(&buf, 0);
2717         patch_input_file = filename;
2718         read_patch_file(&buf, fd);
2719         offset = 0;
2720         while (offset < buf.len) {
2721                 struct patch *patch;
2722                 int nr;
2724                 patch = xcalloc(1, sizeof(*patch));
2725                 patch->inaccurate_eof = inaccurate_eof;
2726                 nr = parse_chunk(buf.buf + offset, buf.len - offset, patch);
2727                 if (nr < 0)
2728                         break;
2729                 if (apply_in_reverse)
2730                         reverse_patches(patch);
2731                 if (prefix)
2732                         prefix_patches(patch);
2733                 if (use_patch(patch)) {
2734                         patch_stats(patch);
2735                         *listp = patch;
2736                         listp = &patch->next;
2737                 }
2738                 else {
2739                         /* perhaps free it a bit better? */
2740                         free(patch);
2741                         skipped_patch++;
2742                 }
2743                 offset += nr;
2744         }
2746         if (whitespace_error && (ws_error_action == die_on_ws_error))
2747                 apply = 0;
2749         update_index = check_index && apply;
2750         if (update_index && newfd < 0)
2751                 newfd = hold_locked_index(&lock_file, 1);
2753         if (check_index) {
2754                 if (read_cache() < 0)
2755                         die("unable to read index file");
2756         }
2758         if ((check || apply) &&
2759             check_patch_list(list) < 0 &&
2760             !apply_with_reject)
2761                 exit(1);
2763         if (apply && write_out_results(list, skipped_patch))
2764                 exit(1);
2766         if (fake_ancestor)
2767                 build_fake_ancestor(list, fake_ancestor);
2769         if (diffstat)
2770                 stat_patch_list(list);
2772         if (numstat)
2773                 numstat_patch_list(list);
2775         if (summary)
2776                 summary_patch_list(list);
2778         strbuf_release(&buf);
2779         return 0;
2782 static int git_apply_config(const char *var, const char *value)
2784         if (!strcmp(var, "apply.whitespace")) {
2785                 apply_default_whitespace = xstrdup(value);
2786                 return 0;
2787         }
2788         return git_default_config(var, value);
2792 int cmd_apply(int argc, const char **argv, const char *unused_prefix)
2794         int i;
2795         int read_stdin = 1;
2796         int inaccurate_eof = 0;
2797         int errs = 0;
2798         int is_not_gitdir = 0;
2800         const char *whitespace_option = NULL;
2802         prefix = setup_git_directory_gently(&is_not_gitdir);
2803         prefix_length = prefix ? strlen(prefix) : 0;
2804         git_config(git_apply_config);
2805         if (apply_default_whitespace)
2806                 parse_whitespace_option(apply_default_whitespace);
2808         for (i = 1; i < argc; i++) {
2809                 const char *arg = argv[i];
2810                 char *end;
2811                 int fd;
2813                 if (!strcmp(arg, "-")) {
2814                         errs |= apply_patch(0, "<stdin>", inaccurate_eof);
2815                         read_stdin = 0;
2816                         continue;
2817                 }
2818                 if (!prefixcmp(arg, "--exclude=")) {
2819                         struct excludes *x = xmalloc(sizeof(*x));
2820                         x->path = arg + 10;
2821                         x->next = excludes;
2822                         excludes = x;
2823                         continue;
2824                 }
2825                 if (!prefixcmp(arg, "-p")) {
2826                         p_value = atoi(arg + 2);
2827                         p_value_known = 1;
2828                         continue;
2829                 }
2830                 if (!strcmp(arg, "--no-add")) {
2831                         no_add = 1;
2832                         continue;
2833                 }
2834                 if (!strcmp(arg, "--stat")) {
2835                         apply = 0;
2836                         diffstat = 1;
2837                         continue;
2838                 }
2839                 if (!strcmp(arg, "--allow-binary-replacement") ||
2840                     !strcmp(arg, "--binary")) {
2841                         continue; /* now no-op */
2842                 }
2843                 if (!strcmp(arg, "--numstat")) {
2844                         apply = 0;
2845                         numstat = 1;
2846                         continue;
2847                 }
2848                 if (!strcmp(arg, "--summary")) {
2849                         apply = 0;
2850                         summary = 1;
2851                         continue;
2852                 }
2853                 if (!strcmp(arg, "--check")) {
2854                         apply = 0;
2855                         check = 1;
2856                         continue;
2857                 }
2858                 if (!strcmp(arg, "--index")) {
2859                         if (is_not_gitdir)
2860                                 die("--index outside a repository");
2861                         check_index = 1;
2862                         continue;
2863                 }
2864                 if (!strcmp(arg, "--cached")) {
2865                         if (is_not_gitdir)
2866                                 die("--cached outside a repository");
2867                         check_index = 1;
2868                         cached = 1;
2869                         continue;
2870                 }
2871                 if (!strcmp(arg, "--apply")) {
2872                         apply = 1;
2873                         continue;
2874                 }
2875                 if (!strcmp(arg, "--build-fake-ancestor")) {
2876                         apply = 0;
2877                         if (++i >= argc)
2878                                 die ("need a filename");
2879                         fake_ancestor = argv[i];
2880                         continue;
2881                 }
2882                 if (!strcmp(arg, "-z")) {
2883                         line_termination = 0;
2884                         continue;
2885                 }
2886                 if (!prefixcmp(arg, "-C")) {
2887                         p_context = strtoul(arg + 2, &end, 0);
2888                         if (*end != '\0')
2889                                 die("unrecognized context count '%s'", arg + 2);
2890                         continue;
2891                 }
2892                 if (!prefixcmp(arg, "--whitespace=")) {
2893                         whitespace_option = arg + 13;
2894                         parse_whitespace_option(arg + 13);
2895                         continue;
2896                 }
2897                 if (!strcmp(arg, "-R") || !strcmp(arg, "--reverse")) {
2898                         apply_in_reverse = 1;
2899                         continue;
2900                 }
2901                 if (!strcmp(arg, "--unidiff-zero")) {
2902                         unidiff_zero = 1;
2903                         continue;
2904                 }
2905                 if (!strcmp(arg, "--reject")) {
2906                         apply = apply_with_reject = apply_verbosely = 1;
2907                         continue;
2908                 }
2909                 if (!strcmp(arg, "-v") || !strcmp(arg, "--verbose")) {
2910                         apply_verbosely = 1;
2911                         continue;
2912                 }
2913                 if (!strcmp(arg, "--inaccurate-eof")) {
2914                         inaccurate_eof = 1;
2915                         continue;
2916                 }
2917                 if (0 < prefix_length)
2918                         arg = prefix_filename(prefix, prefix_length, arg);
2920                 fd = open(arg, O_RDONLY);
2921                 if (fd < 0)
2922                         usage(apply_usage);
2923                 read_stdin = 0;
2924                 set_default_whitespace_mode(whitespace_option);
2925                 errs |= apply_patch(fd, arg, inaccurate_eof);
2926                 close(fd);
2927         }
2928         set_default_whitespace_mode(whitespace_option);
2929         if (read_stdin)
2930                 errs |= apply_patch(0, "<stdin>", inaccurate_eof);
2931         if (whitespace_error) {
2932                 if (squelch_whitespace_errors &&
2933                     squelch_whitespace_errors < whitespace_error) {
2934                         int squelched =
2935                                 whitespace_error - squelch_whitespace_errors;
2936                         fprintf(stderr, "warning: squelched %d "
2937                                 "whitespace error%s\n",
2938                                 squelched,
2939                                 squelched == 1 ? "" : "s");
2940                 }
2941                 if (ws_error_action == die_on_ws_error)
2942                         die("%d line%s add%s whitespace errors.",
2943                             whitespace_error,
2944                             whitespace_error == 1 ? "" : "s",
2945                             whitespace_error == 1 ? "s" : "");
2946                 if (applied_after_fixing_ws)
2947                         fprintf(stderr, "warning: %d line%s applied after"
2948                                 " fixing whitespace errors.\n",
2949                                 applied_after_fixing_ws,
2950                                 applied_after_fixing_ws == 1 ? "" : "s");
2951                 else if (whitespace_error)
2952                         fprintf(stderr, "warning: %d line%s add%s whitespace errors.\n",
2953                                 whitespace_error,
2954                                 whitespace_error == 1 ? "" : "s",
2955                                 whitespace_error == 1 ? "s" : "");
2956         }
2958         if (update_index) {
2959                 if (write_cache(newfd, active_cache, active_nr) ||
2960                     close(newfd) || commit_locked_index(&lock_file))
2961                         die("Unable to write new index file");
2962         }
2964         return !!errs;