Rewrite convert_to_{git,working_tree} to use strbuf's.
[alt-git.git] / builtin-apply.c
blobe5c29ebf35f2dc44b816e9756505c428c2e7a28a
1 /*
2 * apply.c
4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
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"
15 #include "strbuf.h"
18 * --check turns on checking that the working tree matches the
19 * files that are being modified, but doesn't apply the patch
20 * --stat does just a diffstat, and doesn't actually apply
21 * --numstat does numeric diffstat, and doesn't actually apply
22 * --index-info shows the old and new index info for paths if available.
23 * --index updates the cache as well.
24 * --cached updates only the cache without ever touching the working tree.
26 static const char *prefix;
27 static int prefix_length = -1;
28 static int newfd = -1;
30 static int unidiff_zero;
31 static int p_value = 1;
32 static int p_value_known;
33 static int check_index;
34 static int update_index;
35 static int cached;
36 static int diffstat;
37 static int numstat;
38 static int summary;
39 static int check;
40 static int apply = 1;
41 static int apply_in_reverse;
42 static int apply_with_reject;
43 static int apply_verbosely;
44 static int no_add;
45 static int show_index_info;
46 static int line_termination = '\n';
47 static unsigned long p_context = ULONG_MAX;
48 static const char apply_usage[] =
49 "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|error|error-all|strip>] <patch>...";
51 static enum whitespace_eol {
52 nowarn_whitespace,
53 warn_on_whitespace,
54 error_on_whitespace,
55 strip_whitespace,
56 } new_whitespace = warn_on_whitespace;
57 static int whitespace_error;
58 static int squelch_whitespace_errors = 5;
59 static int applied_after_fixing_ws;
60 static const char *patch_input_file;
62 static void parse_whitespace_option(const char *option)
64 if (!option) {
65 new_whitespace = warn_on_whitespace;
66 return;
68 if (!strcmp(option, "warn")) {
69 new_whitespace = warn_on_whitespace;
70 return;
72 if (!strcmp(option, "nowarn")) {
73 new_whitespace = nowarn_whitespace;
74 return;
76 if (!strcmp(option, "error")) {
77 new_whitespace = error_on_whitespace;
78 return;
80 if (!strcmp(option, "error-all")) {
81 new_whitespace = error_on_whitespace;
82 squelch_whitespace_errors = 0;
83 return;
85 if (!strcmp(option, "strip")) {
86 new_whitespace = strip_whitespace;
87 return;
89 die("unrecognized whitespace option '%s'", option);
92 static void set_default_whitespace_mode(const char *whitespace_option)
94 if (!whitespace_option && !apply_default_whitespace) {
95 new_whitespace = (apply
96 ? warn_on_whitespace
97 : nowarn_whitespace);
102 * For "diff-stat" like behaviour, we keep track of the biggest change
103 * we've seen, and the longest filename. That allows us to do simple
104 * scaling.
106 static int max_change, max_len;
109 * Various "current state", notably line numbers and what
110 * file (and how) we're patching right now.. The "is_xxxx"
111 * things are flags, where -1 means "don't know yet".
113 static int linenr = 1;
116 * This represents one "hunk" from a patch, starting with
117 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
118 * patch text is pointed at by patch, and its byte length
119 * is stored in size. leading and trailing are the number
120 * of context lines.
122 struct fragment {
123 unsigned long leading, trailing;
124 unsigned long oldpos, oldlines;
125 unsigned long newpos, newlines;
126 const char *patch;
127 int size;
128 int rejected;
129 struct fragment *next;
133 * When dealing with a binary patch, we reuse "leading" field
134 * to store the type of the binary hunk, either deflated "delta"
135 * or deflated "literal".
137 #define binary_patch_method leading
138 #define BINARY_DELTA_DEFLATED 1
139 #define BINARY_LITERAL_DEFLATED 2
141 struct patch {
142 char *new_name, *old_name, *def_name;
143 unsigned int old_mode, new_mode;
144 int is_new, is_delete; /* -1 = unknown, 0 = false, 1 = true */
145 int rejected;
146 unsigned long deflate_origlen;
147 int lines_added, lines_deleted;
148 int score;
149 unsigned int is_toplevel_relative:1;
150 unsigned int inaccurate_eof:1;
151 unsigned int is_binary:1;
152 unsigned int is_copy:1;
153 unsigned int is_rename:1;
154 struct fragment *fragments;
155 char *result;
156 unsigned long resultsize;
157 char old_sha1_prefix[41];
158 char new_sha1_prefix[41];
159 struct patch *next;
162 static void say_patch_name(FILE *output, const char *pre, struct patch *patch, const char *post)
164 fputs(pre, output);
165 if (patch->old_name && patch->new_name &&
166 strcmp(patch->old_name, patch->new_name)) {
167 write_name_quoted(NULL, 0, patch->old_name, 1, output);
168 fputs(" => ", output);
169 write_name_quoted(NULL, 0, patch->new_name, 1, output);
171 else {
172 const char *n = patch->new_name;
173 if (!n)
174 n = patch->old_name;
175 write_name_quoted(NULL, 0, n, 1, output);
177 fputs(post, output);
180 #define CHUNKSIZE (8192)
181 #define SLOP (16)
183 static void *read_patch_file(int fd, unsigned long *sizep)
185 struct strbuf buf;
187 strbuf_init(&buf, 0);
188 if (strbuf_read(&buf, fd, 0) < 0)
189 die("git-apply: read returned %s", strerror(errno));
190 *sizep = buf.len;
193 * Make sure that we have some slop in the buffer
194 * so that we can do speculative "memcmp" etc, and
195 * see to it that it is NUL-filled.
197 strbuf_grow(&buf, SLOP);
198 memset(buf.buf + buf.len, 0, SLOP);
199 return strbuf_detach(&buf);
202 static unsigned long linelen(const char *buffer, unsigned long size)
204 unsigned long len = 0;
205 while (size--) {
206 len++;
207 if (*buffer++ == '\n')
208 break;
210 return len;
213 static int is_dev_null(const char *str)
215 return !memcmp("/dev/null", str, 9) && isspace(str[9]);
218 #define TERM_SPACE 1
219 #define TERM_TAB 2
221 static int name_terminate(const char *name, int namelen, int c, int terminate)
223 if (c == ' ' && !(terminate & TERM_SPACE))
224 return 0;
225 if (c == '\t' && !(terminate & TERM_TAB))
226 return 0;
228 return 1;
231 static char *find_name(const char *line, char *def, int p_value, int terminate)
233 int len;
234 const char *start = line;
235 char *name;
237 if (*line == '"') {
238 /* Proposed "new-style" GNU patch/diff format; see
239 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
241 name = unquote_c_style(line, NULL);
242 if (name) {
243 char *cp = name;
244 while (p_value) {
245 cp = strchr(name, '/');
246 if (!cp)
247 break;
248 cp++;
249 p_value--;
251 if (cp) {
252 /* name can later be freed, so we need
253 * to memmove, not just return cp
255 memmove(name, cp, strlen(cp) + 1);
256 free(def);
257 return name;
259 else {
260 free(name);
261 name = NULL;
266 for (;;) {
267 char c = *line;
269 if (isspace(c)) {
270 if (c == '\n')
271 break;
272 if (name_terminate(start, line-start, c, terminate))
273 break;
275 line++;
276 if (c == '/' && !--p_value)
277 start = line;
279 if (!start)
280 return def;
281 len = line - start;
282 if (!len)
283 return def;
286 * Generally we prefer the shorter name, especially
287 * if the other one is just a variation of that with
288 * something else tacked on to the end (ie "file.orig"
289 * or "file~").
291 if (def) {
292 int deflen = strlen(def);
293 if (deflen < len && !strncmp(start, def, deflen))
294 return def;
297 name = xmalloc(len + 1);
298 memcpy(name, start, len);
299 name[len] = 0;
300 free(def);
301 return name;
304 static int count_slashes(const char *cp)
306 int cnt = 0;
307 char ch;
309 while ((ch = *cp++))
310 if (ch == '/')
311 cnt++;
312 return cnt;
316 * Given the string after "--- " or "+++ ", guess the appropriate
317 * p_value for the given patch.
319 static int guess_p_value(const char *nameline)
321 char *name, *cp;
322 int val = -1;
324 if (is_dev_null(nameline))
325 return -1;
326 name = find_name(nameline, NULL, 0, TERM_SPACE | TERM_TAB);
327 if (!name)
328 return -1;
329 cp = strchr(name, '/');
330 if (!cp)
331 val = 0;
332 else if (prefix) {
334 * Does it begin with "a/$our-prefix" and such? Then this is
335 * very likely to apply to our directory.
337 if (!strncmp(name, prefix, prefix_length))
338 val = count_slashes(prefix);
339 else {
340 cp++;
341 if (!strncmp(cp, prefix, prefix_length))
342 val = count_slashes(prefix) + 1;
345 free(name);
346 return val;
350 * Get the name etc info from the --/+++ lines of a traditional patch header
352 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
353 * files, we can happily check the index for a match, but for creating a
354 * new file we should try to match whatever "patch" does. I have no idea.
356 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
358 char *name;
360 first += 4; /* skip "--- " */
361 second += 4; /* skip "+++ " */
362 if (!p_value_known) {
363 int p, q;
364 p = guess_p_value(first);
365 q = guess_p_value(second);
366 if (p < 0) p = q;
367 if (0 <= p && p == q) {
368 p_value = p;
369 p_value_known = 1;
372 if (is_dev_null(first)) {
373 patch->is_new = 1;
374 patch->is_delete = 0;
375 name = find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB);
376 patch->new_name = name;
377 } else if (is_dev_null(second)) {
378 patch->is_new = 0;
379 patch->is_delete = 1;
380 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
381 patch->old_name = name;
382 } else {
383 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
384 name = find_name(second, name, p_value, TERM_SPACE | TERM_TAB);
385 patch->old_name = patch->new_name = name;
387 if (!name)
388 die("unable to find filename in patch at line %d", linenr);
391 static int gitdiff_hdrend(const char *line, struct patch *patch)
393 return -1;
397 * We're anal about diff header consistency, to make
398 * sure that we don't end up having strange ambiguous
399 * patches floating around.
401 * As a result, gitdiff_{old|new}name() will check
402 * their names against any previous information, just
403 * to make sure..
405 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
407 if (!orig_name && !isnull)
408 return find_name(line, NULL, p_value, TERM_TAB);
410 if (orig_name) {
411 int len;
412 const char *name;
413 char *another;
414 name = orig_name;
415 len = strlen(name);
416 if (isnull)
417 die("git-apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
418 another = find_name(line, NULL, p_value, TERM_TAB);
419 if (!another || memcmp(another, name, len))
420 die("git-apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
421 free(another);
422 return orig_name;
424 else {
425 /* expect "/dev/null" */
426 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
427 die("git-apply: bad git-diff - expected /dev/null on line %d", linenr);
428 return NULL;
432 static int gitdiff_oldname(const char *line, struct patch *patch)
434 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
435 return 0;
438 static int gitdiff_newname(const char *line, struct patch *patch)
440 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
441 return 0;
444 static int gitdiff_oldmode(const char *line, struct patch *patch)
446 patch->old_mode = strtoul(line, NULL, 8);
447 return 0;
450 static int gitdiff_newmode(const char *line, struct patch *patch)
452 patch->new_mode = strtoul(line, NULL, 8);
453 return 0;
456 static int gitdiff_delete(const char *line, struct patch *patch)
458 patch->is_delete = 1;
459 patch->old_name = patch->def_name;
460 return gitdiff_oldmode(line, patch);
463 static int gitdiff_newfile(const char *line, struct patch *patch)
465 patch->is_new = 1;
466 patch->new_name = patch->def_name;
467 return gitdiff_newmode(line, patch);
470 static int gitdiff_copysrc(const char *line, struct patch *patch)
472 patch->is_copy = 1;
473 patch->old_name = find_name(line, NULL, 0, 0);
474 return 0;
477 static int gitdiff_copydst(const char *line, struct patch *patch)
479 patch->is_copy = 1;
480 patch->new_name = find_name(line, NULL, 0, 0);
481 return 0;
484 static int gitdiff_renamesrc(const char *line, struct patch *patch)
486 patch->is_rename = 1;
487 patch->old_name = find_name(line, NULL, 0, 0);
488 return 0;
491 static int gitdiff_renamedst(const char *line, struct patch *patch)
493 patch->is_rename = 1;
494 patch->new_name = find_name(line, NULL, 0, 0);
495 return 0;
498 static int gitdiff_similarity(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_dissimilarity(const char *line, struct patch *patch)
507 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
508 patch->score = 0;
509 return 0;
512 static int gitdiff_index(const char *line, struct patch *patch)
514 /* index line is N hexadecimal, "..", N hexadecimal,
515 * and optional space with octal mode.
517 const char *ptr, *eol;
518 int len;
520 ptr = strchr(line, '.');
521 if (!ptr || ptr[1] != '.' || 40 < ptr - line)
522 return 0;
523 len = ptr - line;
524 memcpy(patch->old_sha1_prefix, line, len);
525 patch->old_sha1_prefix[len] = 0;
527 line = ptr + 2;
528 ptr = strchr(line, ' ');
529 eol = strchr(line, '\n');
531 if (!ptr || eol < ptr)
532 ptr = eol;
533 len = ptr - line;
535 if (40 < len)
536 return 0;
537 memcpy(patch->new_sha1_prefix, line, len);
538 patch->new_sha1_prefix[len] = 0;
539 if (*ptr == ' ')
540 patch->new_mode = patch->old_mode = strtoul(ptr+1, NULL, 8);
541 return 0;
545 * This is normal for a diff that doesn't change anything: we'll fall through
546 * into the next diff. Tell the parser to break out.
548 static int gitdiff_unrecognized(const char *line, struct patch *patch)
550 return -1;
553 static const char *stop_at_slash(const char *line, int llen)
555 int i;
557 for (i = 0; i < llen; i++) {
558 int ch = line[i];
559 if (ch == '/')
560 return line + i;
562 return NULL;
565 /* This is to extract the same name that appears on "diff --git"
566 * line. We do not find and return anything if it is a rename
567 * patch, and it is OK because we will find the name elsewhere.
568 * We need to reliably find name only when it is mode-change only,
569 * creation or deletion of an empty file. In any of these cases,
570 * both sides are the same name under a/ and b/ respectively.
572 static char *git_header_name(char *line, int llen)
574 int len;
575 const char *name;
576 const char *second = NULL;
578 line += strlen("diff --git ");
579 llen -= strlen("diff --git ");
581 if (*line == '"') {
582 const char *cp;
583 char *first = unquote_c_style(line, &second);
584 if (!first)
585 return NULL;
587 /* advance to the first slash */
588 cp = stop_at_slash(first, strlen(first));
589 if (!cp || cp == first) {
590 /* we do not accept absolute paths */
591 free_first_and_fail:
592 free(first);
593 return NULL;
595 len = strlen(cp+1);
596 memmove(first, cp+1, len+1); /* including NUL */
598 /* second points at one past closing dq of name.
599 * find the second name.
601 while ((second < line + llen) && isspace(*second))
602 second++;
604 if (line + llen <= second)
605 goto free_first_and_fail;
606 if (*second == '"') {
607 char *sp = unquote_c_style(second, NULL);
608 if (!sp)
609 goto free_first_and_fail;
610 cp = stop_at_slash(sp, strlen(sp));
611 if (!cp || cp == sp) {
612 free_both_and_fail:
613 free(sp);
614 goto free_first_and_fail;
616 /* They must match, otherwise ignore */
617 if (strcmp(cp+1, first))
618 goto free_both_and_fail;
619 free(sp);
620 return first;
623 /* unquoted second */
624 cp = stop_at_slash(second, line + llen - second);
625 if (!cp || cp == second)
626 goto free_first_and_fail;
627 cp++;
628 if (line + llen - cp != len + 1 ||
629 memcmp(first, cp, len))
630 goto free_first_and_fail;
631 return first;
634 /* unquoted first name */
635 name = stop_at_slash(line, llen);
636 if (!name || name == line)
637 return NULL;
639 name++;
641 /* since the first name is unquoted, a dq if exists must be
642 * the beginning of the second name.
644 for (second = name; second < line + llen; second++) {
645 if (*second == '"') {
646 const char *cp = second;
647 const char *np;
648 char *sp = unquote_c_style(second, NULL);
650 if (!sp)
651 return NULL;
652 np = stop_at_slash(sp, strlen(sp));
653 if (!np || np == sp) {
654 free_second_and_fail:
655 free(sp);
656 return NULL;
658 np++;
659 len = strlen(np);
660 if (len < cp - name &&
661 !strncmp(np, name, len) &&
662 isspace(name[len])) {
663 /* Good */
664 memmove(sp, np, len + 1);
665 return sp;
667 goto free_second_and_fail;
672 * Accept a name only if it shows up twice, exactly the same
673 * form.
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;
690 if (second[len] == '\n' && !memcmp(name, second, len)) {
691 char *ret = xmalloc(len + 1);
692 memcpy(ret, name, len);
693 ret[len] = 0;
694 return ret;
698 return NULL;
701 /* Verify that we recognize the lines following a git header */
702 static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
704 unsigned long offset;
706 /* A git diff has explicit new/delete information, so we don't guess */
707 patch->is_new = 0;
708 patch->is_delete = 0;
711 * Some things may not have the old name in the
712 * rest of the headers anywhere (pure mode changes,
713 * or removing or adding empty files), so we get
714 * the default name from the header.
716 patch->def_name = git_header_name(line, len);
718 line += len;
719 size -= len;
720 linenr++;
721 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
722 static const struct opentry {
723 const char *str;
724 int (*fn)(const char *, struct patch *);
725 } optable[] = {
726 { "@@ -", gitdiff_hdrend },
727 { "--- ", gitdiff_oldname },
728 { "+++ ", gitdiff_newname },
729 { "old mode ", gitdiff_oldmode },
730 { "new mode ", gitdiff_newmode },
731 { "deleted file mode ", gitdiff_delete },
732 { "new file mode ", gitdiff_newfile },
733 { "copy from ", gitdiff_copysrc },
734 { "copy to ", gitdiff_copydst },
735 { "rename old ", gitdiff_renamesrc },
736 { "rename new ", gitdiff_renamedst },
737 { "rename from ", gitdiff_renamesrc },
738 { "rename to ", gitdiff_renamedst },
739 { "similarity index ", gitdiff_similarity },
740 { "dissimilarity index ", gitdiff_dissimilarity },
741 { "index ", gitdiff_index },
742 { "", gitdiff_unrecognized },
744 int i;
746 len = linelen(line, size);
747 if (!len || line[len-1] != '\n')
748 break;
749 for (i = 0; i < ARRAY_SIZE(optable); i++) {
750 const struct opentry *p = optable + i;
751 int oplen = strlen(p->str);
752 if (len < oplen || memcmp(p->str, line, oplen))
753 continue;
754 if (p->fn(line + oplen, patch) < 0)
755 return offset;
756 break;
760 return offset;
763 static int parse_num(const char *line, unsigned long *p)
765 char *ptr;
767 if (!isdigit(*line))
768 return 0;
769 *p = strtoul(line, &ptr, 10);
770 return ptr - line;
773 static int parse_range(const char *line, int len, int offset, const char *expect,
774 unsigned long *p1, unsigned long *p2)
776 int digits, ex;
778 if (offset < 0 || offset >= len)
779 return -1;
780 line += offset;
781 len -= offset;
783 digits = parse_num(line, p1);
784 if (!digits)
785 return -1;
787 offset += digits;
788 line += digits;
789 len -= digits;
791 *p2 = 1;
792 if (*line == ',') {
793 digits = parse_num(line+1, p2);
794 if (!digits)
795 return -1;
797 offset += digits+1;
798 line += digits+1;
799 len -= digits+1;
802 ex = strlen(expect);
803 if (ex > len)
804 return -1;
805 if (memcmp(line, expect, ex))
806 return -1;
808 return offset + ex;
812 * Parse a unified diff fragment header of the
813 * form "@@ -a,b +c,d @@"
815 static int parse_fragment_header(char *line, int len, struct fragment *fragment)
817 int offset;
819 if (!len || line[len-1] != '\n')
820 return -1;
822 /* Figure out the number of lines in a fragment */
823 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
824 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
826 return offset;
829 static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
831 unsigned long offset, len;
833 patch->is_toplevel_relative = 0;
834 patch->is_rename = patch->is_copy = 0;
835 patch->is_new = patch->is_delete = -1;
836 patch->old_mode = patch->new_mode = 0;
837 patch->old_name = patch->new_name = NULL;
838 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
839 unsigned long nextlen;
841 len = linelen(line, size);
842 if (!len)
843 break;
845 /* Testing this early allows us to take a few shortcuts.. */
846 if (len < 6)
847 continue;
850 * Make sure we don't find any unconnected patch fragments.
851 * That's a sign that we didn't find a header, and that a
852 * patch has become corrupted/broken up.
854 if (!memcmp("@@ -", line, 4)) {
855 struct fragment dummy;
856 if (parse_fragment_header(line, len, &dummy) < 0)
857 continue;
858 die("patch fragment without header at line %d: %.*s",
859 linenr, (int)len-1, line);
862 if (size < len + 6)
863 break;
866 * Git patch? It might not have a real patch, just a rename
867 * or mode change, so we handle that specially
869 if (!memcmp("diff --git ", line, 11)) {
870 int git_hdr_len = parse_git_header(line, len, size, patch);
871 if (git_hdr_len <= len)
872 continue;
873 if (!patch->old_name && !patch->new_name) {
874 if (!patch->def_name)
875 die("git diff header lacks filename information (line %d)", linenr);
876 patch->old_name = patch->new_name = patch->def_name;
878 patch->is_toplevel_relative = 1;
879 *hdrsize = git_hdr_len;
880 return offset;
883 /** --- followed by +++ ? */
884 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
885 continue;
888 * We only accept unified patches, so we want it to
889 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
890 * minimum
892 nextlen = linelen(line + len, size - len);
893 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
894 continue;
896 /* Ok, we'll consider it a patch */
897 parse_traditional_patch(line, line+len, patch);
898 *hdrsize = len + nextlen;
899 linenr += 2;
900 return offset;
902 return -1;
905 static void check_whitespace(const char *line, int len)
907 const char *err = "Adds trailing whitespace";
908 int seen_space = 0;
909 int i;
912 * We know len is at least two, since we have a '+' and we
913 * checked that the last character was a '\n' before calling
914 * this function. That is, an addition of an empty line would
915 * check the '+' here. Sneaky...
917 if (isspace(line[len-2]))
918 goto error;
921 * Make sure that there is no space followed by a tab in
922 * indentation.
924 err = "Space in indent is followed by a tab";
925 for (i = 1; i < len; i++) {
926 if (line[i] == '\t') {
927 if (seen_space)
928 goto error;
930 else if (line[i] == ' ')
931 seen_space = 1;
932 else
933 break;
935 return;
937 error:
938 whitespace_error++;
939 if (squelch_whitespace_errors &&
940 squelch_whitespace_errors < whitespace_error)
942 else
943 fprintf(stderr, "%s.\n%s:%d:%.*s\n",
944 err, patch_input_file, linenr, len-2, line+1);
949 * Parse a unified diff. Note that this really needs to parse each
950 * fragment separately, since the only way to know the difference
951 * between a "---" that is part of a patch, and a "---" that starts
952 * the next patch is to look at the line counts..
954 static int parse_fragment(char *line, unsigned long size, struct patch *patch, struct fragment *fragment)
956 int added, deleted;
957 int len = linelen(line, size), offset;
958 unsigned long oldlines, newlines;
959 unsigned long leading, trailing;
961 offset = parse_fragment_header(line, len, fragment);
962 if (offset < 0)
963 return -1;
964 oldlines = fragment->oldlines;
965 newlines = fragment->newlines;
966 leading = 0;
967 trailing = 0;
969 /* Parse the thing.. */
970 line += len;
971 size -= len;
972 linenr++;
973 added = deleted = 0;
974 for (offset = len;
975 0 < size;
976 offset += len, size -= len, line += len, linenr++) {
977 if (!oldlines && !newlines)
978 break;
979 len = linelen(line, size);
980 if (!len || line[len-1] != '\n')
981 return -1;
982 switch (*line) {
983 default:
984 return -1;
985 case '\n': /* newer GNU diff, an empty context line */
986 case ' ':
987 oldlines--;
988 newlines--;
989 if (!deleted && !added)
990 leading++;
991 trailing++;
992 break;
993 case '-':
994 if (apply_in_reverse &&
995 new_whitespace != nowarn_whitespace)
996 check_whitespace(line, len);
997 deleted++;
998 oldlines--;
999 trailing = 0;
1000 break;
1001 case '+':
1002 if (!apply_in_reverse &&
1003 new_whitespace != nowarn_whitespace)
1004 check_whitespace(line, len);
1005 added++;
1006 newlines--;
1007 trailing = 0;
1008 break;
1010 /* We allow "\ No newline at end of file". Depending
1011 * on locale settings when the patch was produced we
1012 * don't know what this line looks like. The only
1013 * thing we do know is that it begins with "\ ".
1014 * Checking for 12 is just for sanity check -- any
1015 * l10n of "\ No newline..." is at least that long.
1017 case '\\':
1018 if (len < 12 || memcmp(line, "\\ ", 2))
1019 return -1;
1020 break;
1023 if (oldlines || newlines)
1024 return -1;
1025 fragment->leading = leading;
1026 fragment->trailing = trailing;
1028 /* If a fragment ends with an incomplete line, we failed to include
1029 * it in the above loop because we hit oldlines == newlines == 0
1030 * before seeing it.
1032 if (12 < size && !memcmp(line, "\\ ", 2))
1033 offset += linelen(line, size);
1035 patch->lines_added += added;
1036 patch->lines_deleted += deleted;
1038 if (0 < patch->is_new && oldlines)
1039 return error("new file depends on old contents");
1040 if (0 < patch->is_delete && newlines)
1041 return error("deleted file still has contents");
1042 return offset;
1045 static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
1047 unsigned long offset = 0;
1048 unsigned long oldlines = 0, newlines = 0, context = 0;
1049 struct fragment **fragp = &patch->fragments;
1051 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1052 struct fragment *fragment;
1053 int len;
1055 fragment = xcalloc(1, sizeof(*fragment));
1056 len = parse_fragment(line, size, patch, fragment);
1057 if (len <= 0)
1058 die("corrupt patch at line %d", linenr);
1059 fragment->patch = line;
1060 fragment->size = len;
1061 oldlines += fragment->oldlines;
1062 newlines += fragment->newlines;
1063 context += fragment->leading + fragment->trailing;
1065 *fragp = fragment;
1066 fragp = &fragment->next;
1068 offset += len;
1069 line += len;
1070 size -= len;
1074 * If something was removed (i.e. we have old-lines) it cannot
1075 * be creation, and if something was added it cannot be
1076 * deletion. However, the reverse is not true; --unified=0
1077 * patches that only add are not necessarily creation even
1078 * though they do not have any old lines, and ones that only
1079 * delete are not necessarily deletion.
1081 * Unfortunately, a real creation/deletion patch do _not_ have
1082 * any context line by definition, so we cannot safely tell it
1083 * apart with --unified=0 insanity. At least if the patch has
1084 * more than one hunk it is not creation or deletion.
1086 if (patch->is_new < 0 &&
1087 (oldlines || (patch->fragments && patch->fragments->next)))
1088 patch->is_new = 0;
1089 if (patch->is_delete < 0 &&
1090 (newlines || (patch->fragments && patch->fragments->next)))
1091 patch->is_delete = 0;
1092 if (!unidiff_zero || context) {
1093 /* If the user says the patch is not generated with
1094 * --unified=0, or if we have seen context lines,
1095 * then not having oldlines means the patch is creation,
1096 * and not having newlines means the patch is deletion.
1098 if (patch->is_new < 0 && !oldlines) {
1099 patch->is_new = 1;
1100 patch->old_name = NULL;
1102 if (patch->is_delete < 0 && !newlines) {
1103 patch->is_delete = 1;
1104 patch->new_name = NULL;
1108 if (0 < patch->is_new && oldlines)
1109 die("new file %s depends on old contents", patch->new_name);
1110 if (0 < patch->is_delete && newlines)
1111 die("deleted file %s still has contents", patch->old_name);
1112 if (!patch->is_delete && !newlines && context)
1113 fprintf(stderr, "** warning: file %s becomes empty but "
1114 "is not deleted\n", patch->new_name);
1116 return offset;
1119 static inline int metadata_changes(struct patch *patch)
1121 return patch->is_rename > 0 ||
1122 patch->is_copy > 0 ||
1123 patch->is_new > 0 ||
1124 patch->is_delete ||
1125 (patch->old_mode && patch->new_mode &&
1126 patch->old_mode != patch->new_mode);
1129 static char *inflate_it(const void *data, unsigned long size,
1130 unsigned long inflated_size)
1132 z_stream stream;
1133 void *out;
1134 int st;
1136 memset(&stream, 0, sizeof(stream));
1138 stream.next_in = (unsigned char *)data;
1139 stream.avail_in = size;
1140 stream.next_out = out = xmalloc(inflated_size);
1141 stream.avail_out = inflated_size;
1142 inflateInit(&stream);
1143 st = inflate(&stream, Z_FINISH);
1144 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1145 free(out);
1146 return NULL;
1148 return out;
1151 static struct fragment *parse_binary_hunk(char **buf_p,
1152 unsigned long *sz_p,
1153 int *status_p,
1154 int *used_p)
1156 /* Expect a line that begins with binary patch method ("literal"
1157 * or "delta"), followed by the length of data before deflating.
1158 * a sequence of 'length-byte' followed by base-85 encoded data
1159 * should follow, terminated by a newline.
1161 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1162 * and we would limit the patch line to 66 characters,
1163 * so one line can fit up to 13 groups that would decode
1164 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1165 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1167 int llen, used;
1168 unsigned long size = *sz_p;
1169 char *buffer = *buf_p;
1170 int patch_method;
1171 unsigned long origlen;
1172 char *data = NULL;
1173 int hunk_size = 0;
1174 struct fragment *frag;
1176 llen = linelen(buffer, size);
1177 used = llen;
1179 *status_p = 0;
1181 if (!prefixcmp(buffer, "delta ")) {
1182 patch_method = BINARY_DELTA_DEFLATED;
1183 origlen = strtoul(buffer + 6, NULL, 10);
1185 else if (!prefixcmp(buffer, "literal ")) {
1186 patch_method = BINARY_LITERAL_DEFLATED;
1187 origlen = strtoul(buffer + 8, NULL, 10);
1189 else
1190 return NULL;
1192 linenr++;
1193 buffer += llen;
1194 while (1) {
1195 int byte_length, max_byte_length, newsize;
1196 llen = linelen(buffer, size);
1197 used += llen;
1198 linenr++;
1199 if (llen == 1) {
1200 /* consume the blank line */
1201 buffer++;
1202 size--;
1203 break;
1205 /* Minimum line is "A00000\n" which is 7-byte long,
1206 * and the line length must be multiple of 5 plus 2.
1208 if ((llen < 7) || (llen-2) % 5)
1209 goto corrupt;
1210 max_byte_length = (llen - 2) / 5 * 4;
1211 byte_length = *buffer;
1212 if ('A' <= byte_length && byte_length <= 'Z')
1213 byte_length = byte_length - 'A' + 1;
1214 else if ('a' <= byte_length && byte_length <= 'z')
1215 byte_length = byte_length - 'a' + 27;
1216 else
1217 goto corrupt;
1218 /* if the input length was not multiple of 4, we would
1219 * have filler at the end but the filler should never
1220 * exceed 3 bytes
1222 if (max_byte_length < byte_length ||
1223 byte_length <= max_byte_length - 4)
1224 goto corrupt;
1225 newsize = hunk_size + byte_length;
1226 data = xrealloc(data, newsize);
1227 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1228 goto corrupt;
1229 hunk_size = newsize;
1230 buffer += llen;
1231 size -= llen;
1234 frag = xcalloc(1, sizeof(*frag));
1235 frag->patch = inflate_it(data, hunk_size, origlen);
1236 if (!frag->patch)
1237 goto corrupt;
1238 free(data);
1239 frag->size = origlen;
1240 *buf_p = buffer;
1241 *sz_p = size;
1242 *used_p = used;
1243 frag->binary_patch_method = patch_method;
1244 return frag;
1246 corrupt:
1247 free(data);
1248 *status_p = -1;
1249 error("corrupt binary patch at line %d: %.*s",
1250 linenr-1, llen-1, buffer);
1251 return NULL;
1254 static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1256 /* We have read "GIT binary patch\n"; what follows is a line
1257 * that says the patch method (currently, either "literal" or
1258 * "delta") and the length of data before deflating; a
1259 * sequence of 'length-byte' followed by base-85 encoded data
1260 * follows.
1262 * When a binary patch is reversible, there is another binary
1263 * hunk in the same format, starting with patch method (either
1264 * "literal" or "delta") with the length of data, and a sequence
1265 * of length-byte + base-85 encoded data, terminated with another
1266 * empty line. This data, when applied to the postimage, produces
1267 * the preimage.
1269 struct fragment *forward;
1270 struct fragment *reverse;
1271 int status;
1272 int used, used_1;
1274 forward = parse_binary_hunk(&buffer, &size, &status, &used);
1275 if (!forward && !status)
1276 /* there has to be one hunk (forward hunk) */
1277 return error("unrecognized binary patch at line %d", linenr-1);
1278 if (status)
1279 /* otherwise we already gave an error message */
1280 return status;
1282 reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1283 if (reverse)
1284 used += used_1;
1285 else if (status) {
1286 /* not having reverse hunk is not an error, but having
1287 * a corrupt reverse hunk is.
1289 free((void*) forward->patch);
1290 free(forward);
1291 return status;
1293 forward->next = reverse;
1294 patch->fragments = forward;
1295 patch->is_binary = 1;
1296 return used;
1299 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
1301 int hdrsize, patchsize;
1302 int offset = find_header(buffer, size, &hdrsize, patch);
1304 if (offset < 0)
1305 return offset;
1307 patchsize = parse_single_patch(buffer + offset + hdrsize, size - offset - hdrsize, patch);
1309 if (!patchsize) {
1310 static const char *binhdr[] = {
1311 "Binary files ",
1312 "Files ",
1313 NULL,
1315 static const char git_binary[] = "GIT binary patch\n";
1316 int i;
1317 int hd = hdrsize + offset;
1318 unsigned long llen = linelen(buffer + hd, size - hd);
1320 if (llen == sizeof(git_binary) - 1 &&
1321 !memcmp(git_binary, buffer + hd, llen)) {
1322 int used;
1323 linenr++;
1324 used = parse_binary(buffer + hd + llen,
1325 size - hd - llen, patch);
1326 if (used)
1327 patchsize = used + llen;
1328 else
1329 patchsize = 0;
1331 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
1332 for (i = 0; binhdr[i]; i++) {
1333 int len = strlen(binhdr[i]);
1334 if (len < size - hd &&
1335 !memcmp(binhdr[i], buffer + hd, len)) {
1336 linenr++;
1337 patch->is_binary = 1;
1338 patchsize = llen;
1339 break;
1344 /* Empty patch cannot be applied if it is a text patch
1345 * without metadata change. A binary patch appears
1346 * empty to us here.
1348 if ((apply || check) &&
1349 (!patch->is_binary && !metadata_changes(patch)))
1350 die("patch with only garbage at line %d", linenr);
1353 return offset + hdrsize + patchsize;
1356 #define swap(a,b) myswap((a),(b),sizeof(a))
1358 #define myswap(a, b, size) do { \
1359 unsigned char mytmp[size]; \
1360 memcpy(mytmp, &a, size); \
1361 memcpy(&a, &b, size); \
1362 memcpy(&b, mytmp, size); \
1363 } while (0)
1365 static void reverse_patches(struct patch *p)
1367 for (; p; p = p->next) {
1368 struct fragment *frag = p->fragments;
1370 swap(p->new_name, p->old_name);
1371 swap(p->new_mode, p->old_mode);
1372 swap(p->is_new, p->is_delete);
1373 swap(p->lines_added, p->lines_deleted);
1374 swap(p->old_sha1_prefix, p->new_sha1_prefix);
1376 for (; frag; frag = frag->next) {
1377 swap(frag->newpos, frag->oldpos);
1378 swap(frag->newlines, frag->oldlines);
1383 static const char pluses[] = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1384 static const char minuses[]= "----------------------------------------------------------------------";
1386 static void show_stats(struct patch *patch)
1388 const char *prefix = "";
1389 char *name = patch->new_name;
1390 char *qname = NULL;
1391 int len, max, add, del, total;
1393 if (!name)
1394 name = patch->old_name;
1396 if (0 < (len = quote_c_style(name, NULL, NULL, 0))) {
1397 qname = xmalloc(len + 1);
1398 quote_c_style(name, qname, NULL, 0);
1399 name = qname;
1403 * "scale" the filename
1405 len = strlen(name);
1406 max = max_len;
1407 if (max > 50)
1408 max = 50;
1409 if (len > max) {
1410 char *slash;
1411 prefix = "...";
1412 max -= 3;
1413 name += len - max;
1414 slash = strchr(name, '/');
1415 if (slash)
1416 name = slash;
1418 len = max;
1421 * scale the add/delete
1423 max = max_change;
1424 if (max + len > 70)
1425 max = 70 - len;
1427 add = patch->lines_added;
1428 del = patch->lines_deleted;
1429 total = add + del;
1431 if (max_change > 0) {
1432 total = (total * max + max_change / 2) / max_change;
1433 add = (add * max + max_change / 2) / max_change;
1434 del = total - add;
1436 if (patch->is_binary)
1437 printf(" %s%-*s | Bin\n", prefix, len, name);
1438 else
1439 printf(" %s%-*s |%5d %.*s%.*s\n", prefix,
1440 len, name, patch->lines_added + patch->lines_deleted,
1441 add, pluses, del, minuses);
1442 free(qname);
1445 static int read_old_data(struct stat *st, const char *path, char **buf_p, unsigned long *alloc_p, unsigned long *size_p)
1447 int fd;
1448 unsigned long got;
1449 struct strbuf nbuf;
1450 unsigned long size = *size_p;
1451 char *buf = *buf_p;
1453 switch (st->st_mode & S_IFMT) {
1454 case S_IFLNK:
1455 return readlink(path, buf, size) != size;
1456 case S_IFREG:
1457 fd = open(path, O_RDONLY);
1458 if (fd < 0)
1459 return error("unable to open %s", path);
1460 got = 0;
1461 for (;;) {
1462 ssize_t ret = xread(fd, buf + got, size - got);
1463 if (ret <= 0)
1464 break;
1465 got += ret;
1467 close(fd);
1468 strbuf_init(&nbuf, 0);
1469 if (convert_to_git(path, buf, size, &nbuf)) {
1470 free(buf);
1471 *buf_p = nbuf.buf;
1472 *alloc_p = nbuf.alloc;
1473 *size_p = nbuf.len;
1475 return got != size;
1476 default:
1477 return -1;
1481 static int find_offset(const char *buf, unsigned long size, const char *fragment, unsigned long fragsize, int line, int *lines)
1483 int i;
1484 unsigned long start, backwards, forwards;
1486 if (fragsize > size)
1487 return -1;
1489 start = 0;
1490 if (line > 1) {
1491 unsigned long offset = 0;
1492 i = line-1;
1493 while (offset + fragsize <= size) {
1494 if (buf[offset++] == '\n') {
1495 start = offset;
1496 if (!--i)
1497 break;
1502 /* Exact line number? */
1503 if ((start + fragsize <= size) &&
1504 !memcmp(buf + start, fragment, fragsize))
1505 return start;
1508 * There's probably some smart way to do this, but I'll leave
1509 * that to the smart and beautiful people. I'm simple and stupid.
1511 backwards = start;
1512 forwards = start;
1513 for (i = 0; ; i++) {
1514 unsigned long try;
1515 int n;
1517 /* "backward" */
1518 if (i & 1) {
1519 if (!backwards) {
1520 if (forwards + fragsize > size)
1521 break;
1522 continue;
1524 do {
1525 --backwards;
1526 } while (backwards && buf[backwards-1] != '\n');
1527 try = backwards;
1528 } else {
1529 while (forwards + fragsize <= size) {
1530 if (buf[forwards++] == '\n')
1531 break;
1533 try = forwards;
1536 if (try + fragsize > size)
1537 continue;
1538 if (memcmp(buf + try, fragment, fragsize))
1539 continue;
1540 n = (i >> 1)+1;
1541 if (i & 1)
1542 n = -n;
1543 *lines = n;
1544 return try;
1548 * We should start searching forward and backward.
1550 return -1;
1553 static void remove_first_line(const char **rbuf, int *rsize)
1555 const char *buf = *rbuf;
1556 int size = *rsize;
1557 unsigned long offset;
1558 offset = 0;
1559 while (offset <= size) {
1560 if (buf[offset++] == '\n')
1561 break;
1563 *rsize = size - offset;
1564 *rbuf = buf + offset;
1567 static void remove_last_line(const char **rbuf, int *rsize)
1569 const char *buf = *rbuf;
1570 int size = *rsize;
1571 unsigned long offset;
1572 offset = size - 1;
1573 while (offset > 0) {
1574 if (buf[--offset] == '\n')
1575 break;
1577 *rsize = offset + 1;
1580 struct buffer_desc {
1581 char *buffer;
1582 unsigned long size;
1583 unsigned long alloc;
1586 static int apply_line(char *output, const char *patch, int plen)
1588 /* plen is number of bytes to be copied from patch,
1589 * starting at patch+1 (patch[0] is '+'). Typically
1590 * patch[plen] is '\n', unless this is the incomplete
1591 * last line.
1593 int i;
1594 int add_nl_to_tail = 0;
1595 int fixed = 0;
1596 int last_tab_in_indent = -1;
1597 int last_space_in_indent = -1;
1598 int need_fix_leading_space = 0;
1599 char *buf;
1601 if ((new_whitespace != strip_whitespace) || !whitespace_error ||
1602 *patch != '+') {
1603 memcpy(output, patch + 1, plen);
1604 return plen;
1607 if (1 < plen && isspace(patch[plen-1])) {
1608 if (patch[plen] == '\n')
1609 add_nl_to_tail = 1;
1610 plen--;
1611 while (0 < plen && isspace(patch[plen]))
1612 plen--;
1613 fixed = 1;
1616 for (i = 1; i < plen; i++) {
1617 char ch = patch[i];
1618 if (ch == '\t') {
1619 last_tab_in_indent = i;
1620 if (0 <= last_space_in_indent)
1621 need_fix_leading_space = 1;
1623 else if (ch == ' ')
1624 last_space_in_indent = i;
1625 else
1626 break;
1629 buf = output;
1630 if (need_fix_leading_space) {
1631 /* between patch[1..last_tab_in_indent] strip the
1632 * funny spaces, updating them to tab as needed.
1634 for (i = 1; i < last_tab_in_indent; i++, plen--) {
1635 char ch = patch[i];
1636 if (ch != ' ')
1637 *output++ = ch;
1638 else if ((i % 8) == 0)
1639 *output++ = '\t';
1641 fixed = 1;
1642 i = last_tab_in_indent;
1644 else
1645 i = 1;
1647 memcpy(output, patch + i, plen);
1648 if (add_nl_to_tail)
1649 output[plen++] = '\n';
1650 if (fixed)
1651 applied_after_fixing_ws++;
1652 return output + plen - buf;
1655 static int apply_one_fragment(struct buffer_desc *desc, struct fragment *frag, int inaccurate_eof)
1657 int match_beginning, match_end;
1658 char *buf = desc->buffer;
1659 const char *patch = frag->patch;
1660 int offset, size = frag->size;
1661 char *old = xmalloc(size);
1662 char *new = xmalloc(size);
1663 const char *oldlines, *newlines;
1664 int oldsize = 0, newsize = 0;
1665 int new_blank_lines_at_end = 0;
1666 unsigned long leading, trailing;
1667 int pos, lines;
1669 while (size > 0) {
1670 char first;
1671 int len = linelen(patch, size);
1672 int plen;
1673 int added_blank_line = 0;
1675 if (!len)
1676 break;
1679 * "plen" is how much of the line we should use for
1680 * the actual patch data. Normally we just remove the
1681 * first character on the line, but if the line is
1682 * followed by "\ No newline", then we also remove the
1683 * last one (which is the newline, of course).
1685 plen = len-1;
1686 if (len < size && patch[len] == '\\')
1687 plen--;
1688 first = *patch;
1689 if (apply_in_reverse) {
1690 if (first == '-')
1691 first = '+';
1692 else if (first == '+')
1693 first = '-';
1696 switch (first) {
1697 case '\n':
1698 /* Newer GNU diff, empty context line */
1699 if (plen < 0)
1700 /* ... followed by '\No newline'; nothing */
1701 break;
1702 old[oldsize++] = '\n';
1703 new[newsize++] = '\n';
1704 break;
1705 case ' ':
1706 case '-':
1707 memcpy(old + oldsize, patch + 1, plen);
1708 oldsize += plen;
1709 if (first == '-')
1710 break;
1711 /* Fall-through for ' ' */
1712 case '+':
1713 if (first != '+' || !no_add) {
1714 int added = apply_line(new + newsize, patch,
1715 plen);
1716 newsize += added;
1717 if (first == '+' &&
1718 added == 1 && new[newsize-1] == '\n')
1719 added_blank_line = 1;
1721 break;
1722 case '@': case '\\':
1723 /* Ignore it, we already handled it */
1724 break;
1725 default:
1726 if (apply_verbosely)
1727 error("invalid start of line: '%c'", first);
1728 return -1;
1730 if (added_blank_line)
1731 new_blank_lines_at_end++;
1732 else
1733 new_blank_lines_at_end = 0;
1734 patch += len;
1735 size -= len;
1738 if (inaccurate_eof && oldsize > 0 && old[oldsize - 1] == '\n' &&
1739 newsize > 0 && new[newsize - 1] == '\n') {
1740 oldsize--;
1741 newsize--;
1744 oldlines = old;
1745 newlines = new;
1746 leading = frag->leading;
1747 trailing = frag->trailing;
1750 * If we don't have any leading/trailing data in the patch,
1751 * we want it to match at the beginning/end of the file.
1753 * But that would break if the patch is generated with
1754 * --unified=0; sane people wouldn't do that to cause us
1755 * trouble, but we try to please not so sane ones as well.
1757 if (unidiff_zero) {
1758 match_beginning = (!leading && !frag->oldpos);
1759 match_end = 0;
1761 else {
1762 match_beginning = !leading && (frag->oldpos == 1);
1763 match_end = !trailing;
1766 lines = 0;
1767 pos = frag->newpos;
1768 for (;;) {
1769 offset = find_offset(buf, desc->size,
1770 oldlines, oldsize, pos, &lines);
1771 if (match_end && offset + oldsize != desc->size)
1772 offset = -1;
1773 if (match_beginning && offset)
1774 offset = -1;
1775 if (offset >= 0) {
1776 int diff;
1777 unsigned long size, alloc;
1779 if (new_whitespace == strip_whitespace &&
1780 (desc->size - oldsize - offset == 0)) /* end of file? */
1781 newsize -= new_blank_lines_at_end;
1783 diff = newsize - oldsize;
1784 size = desc->size + diff;
1785 alloc = desc->alloc;
1787 /* Warn if it was necessary to reduce the number
1788 * of context lines.
1790 if ((leading != frag->leading) ||
1791 (trailing != frag->trailing))
1792 fprintf(stderr, "Context reduced to (%ld/%ld)"
1793 " to apply fragment at %d\n",
1794 leading, trailing, pos + lines);
1796 if (size > alloc) {
1797 alloc = size + 8192;
1798 desc->alloc = alloc;
1799 buf = xrealloc(buf, alloc);
1800 desc->buffer = buf;
1802 desc->size = size;
1803 memmove(buf + offset + newsize,
1804 buf + offset + oldsize,
1805 size - offset - newsize);
1806 memcpy(buf + offset, newlines, newsize);
1807 offset = 0;
1809 break;
1812 /* Am I at my context limits? */
1813 if ((leading <= p_context) && (trailing <= p_context))
1814 break;
1815 if (match_beginning || match_end) {
1816 match_beginning = match_end = 0;
1817 continue;
1819 /* Reduce the number of context lines
1820 * Reduce both leading and trailing if they are equal
1821 * otherwise just reduce the larger context.
1823 if (leading >= trailing) {
1824 remove_first_line(&oldlines, &oldsize);
1825 remove_first_line(&newlines, &newsize);
1826 pos--;
1827 leading--;
1829 if (trailing > leading) {
1830 remove_last_line(&oldlines, &oldsize);
1831 remove_last_line(&newlines, &newsize);
1832 trailing--;
1836 if (offset && apply_verbosely)
1837 error("while searching for:\n%.*s", oldsize, oldlines);
1839 free(old);
1840 free(new);
1841 return offset;
1844 static int apply_binary_fragment(struct buffer_desc *desc, struct patch *patch)
1846 unsigned long dst_size;
1847 struct fragment *fragment = patch->fragments;
1848 void *data;
1849 void *result;
1851 /* Binary patch is irreversible without the optional second hunk */
1852 if (apply_in_reverse) {
1853 if (!fragment->next)
1854 return error("cannot reverse-apply a binary patch "
1855 "without the reverse hunk to '%s'",
1856 patch->new_name
1857 ? patch->new_name : patch->old_name);
1858 fragment = fragment->next;
1860 data = (void*) fragment->patch;
1861 switch (fragment->binary_patch_method) {
1862 case BINARY_DELTA_DEFLATED:
1863 result = patch_delta(desc->buffer, desc->size,
1864 data,
1865 fragment->size,
1866 &dst_size);
1867 free(desc->buffer);
1868 desc->buffer = result;
1869 break;
1870 case BINARY_LITERAL_DEFLATED:
1871 free(desc->buffer);
1872 desc->buffer = data;
1873 dst_size = fragment->size;
1874 break;
1876 if (!desc->buffer)
1877 return -1;
1878 desc->size = desc->alloc = dst_size;
1879 return 0;
1882 static int apply_binary(struct buffer_desc *desc, struct patch *patch)
1884 const char *name = patch->old_name ? patch->old_name : patch->new_name;
1885 unsigned char sha1[20];
1887 /* For safety, we require patch index line to contain
1888 * full 40-byte textual SHA1 for old and new, at least for now.
1890 if (strlen(patch->old_sha1_prefix) != 40 ||
1891 strlen(patch->new_sha1_prefix) != 40 ||
1892 get_sha1_hex(patch->old_sha1_prefix, sha1) ||
1893 get_sha1_hex(patch->new_sha1_prefix, sha1))
1894 return error("cannot apply binary patch to '%s' "
1895 "without full index line", name);
1897 if (patch->old_name) {
1898 /* See if the old one matches what the patch
1899 * applies to.
1901 hash_sha1_file(desc->buffer, desc->size, blob_type, sha1);
1902 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
1903 return error("the patch applies to '%s' (%s), "
1904 "which does not match the "
1905 "current contents.",
1906 name, sha1_to_hex(sha1));
1908 else {
1909 /* Otherwise, the old one must be empty. */
1910 if (desc->size)
1911 return error("the patch applies to an empty "
1912 "'%s' but it is not empty", name);
1915 get_sha1_hex(patch->new_sha1_prefix, sha1);
1916 if (is_null_sha1(sha1)) {
1917 free(desc->buffer);
1918 desc->alloc = desc->size = 0;
1919 desc->buffer = NULL;
1920 return 0; /* deletion patch */
1923 if (has_sha1_file(sha1)) {
1924 /* We already have the postimage */
1925 enum object_type type;
1926 unsigned long size;
1928 free(desc->buffer);
1929 desc->buffer = read_sha1_file(sha1, &type, &size);
1930 if (!desc->buffer)
1931 return error("the necessary postimage %s for "
1932 "'%s' cannot be read",
1933 patch->new_sha1_prefix, name);
1934 desc->alloc = desc->size = size;
1936 else {
1937 /* We have verified desc matches the preimage;
1938 * apply the patch data to it, which is stored
1939 * in the patch->fragments->{patch,size}.
1941 if (apply_binary_fragment(desc, patch))
1942 return error("binary patch does not apply to '%s'",
1943 name);
1945 /* verify that the result matches */
1946 hash_sha1_file(desc->buffer, desc->size, blob_type, sha1);
1947 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
1948 return error("binary patch to '%s' creates incorrect result (expecting %s, got %s)", name, patch->new_sha1_prefix, sha1_to_hex(sha1));
1951 return 0;
1954 static int apply_fragments(struct buffer_desc *desc, struct patch *patch)
1956 struct fragment *frag = patch->fragments;
1957 const char *name = patch->old_name ? patch->old_name : patch->new_name;
1959 if (patch->is_binary)
1960 return apply_binary(desc, patch);
1962 while (frag) {
1963 if (apply_one_fragment(desc, frag, patch->inaccurate_eof)) {
1964 error("patch failed: %s:%ld", name, frag->oldpos);
1965 if (!apply_with_reject)
1966 return -1;
1967 frag->rejected = 1;
1969 frag = frag->next;
1971 return 0;
1974 static int read_file_or_gitlink(struct cache_entry *ce, char **buf_p,
1975 unsigned long *size_p)
1977 if (!ce)
1978 return 0;
1980 if (S_ISGITLINK(ntohl(ce->ce_mode))) {
1981 *buf_p = xmalloc(100);
1982 *size_p = snprintf(*buf_p, 100,
1983 "Subproject commit %s\n", sha1_to_hex(ce->sha1));
1984 } else {
1985 enum object_type type;
1986 *buf_p = read_sha1_file(ce->sha1, &type, size_p);
1987 if (!*buf_p)
1988 return -1;
1990 return 0;
1993 static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce)
1995 char *buf;
1996 unsigned long size, alloc;
1997 struct buffer_desc desc;
1999 size = 0;
2000 alloc = 0;
2001 buf = NULL;
2002 if (cached) {
2003 if (read_file_or_gitlink(ce, &buf, &size))
2004 return error("read of %s failed", patch->old_name);
2005 alloc = size;
2006 } else if (patch->old_name) {
2007 if (S_ISGITLINK(patch->old_mode)) {
2008 if (ce)
2009 read_file_or_gitlink(ce, &buf, &size);
2010 else {
2012 * There is no way to apply subproject
2013 * patch without looking at the index.
2015 patch->fragments = NULL;
2016 size = 0;
2019 else {
2020 size = xsize_t(st->st_size);
2021 alloc = size + 8192;
2022 buf = xmalloc(alloc);
2023 if (read_old_data(st, patch->old_name,
2024 &buf, &alloc, &size))
2025 return error("read of %s failed",
2026 patch->old_name);
2030 desc.size = size;
2031 desc.alloc = alloc;
2032 desc.buffer = buf;
2034 if (apply_fragments(&desc, patch) < 0)
2035 return -1; /* note with --reject this succeeds. */
2037 /* NUL terminate the result */
2038 if (desc.alloc <= desc.size)
2039 desc.buffer = xrealloc(desc.buffer, desc.size + 1);
2040 desc.buffer[desc.size] = 0;
2042 patch->result = desc.buffer;
2043 patch->resultsize = desc.size;
2045 if (0 < patch->is_delete && patch->resultsize)
2046 return error("removal patch leaves file contents");
2048 return 0;
2051 static int check_to_create_blob(const char *new_name, int ok_if_exists)
2053 struct stat nst;
2054 if (!lstat(new_name, &nst)) {
2055 if (S_ISDIR(nst.st_mode) || ok_if_exists)
2056 return 0;
2058 * A leading component of new_name might be a symlink
2059 * that is going to be removed with this patch, but
2060 * still pointing at somewhere that has the path.
2061 * In such a case, path "new_name" does not exist as
2062 * far as git is concerned.
2064 if (has_symlink_leading_path(new_name, NULL))
2065 return 0;
2067 return error("%s: already exists in working directory", new_name);
2069 else if ((errno != ENOENT) && (errno != ENOTDIR))
2070 return error("%s: %s", new_name, strerror(errno));
2071 return 0;
2074 static int verify_index_match(struct cache_entry *ce, struct stat *st)
2076 if (S_ISGITLINK(ntohl(ce->ce_mode))) {
2077 if (!S_ISDIR(st->st_mode))
2078 return -1;
2079 return 0;
2081 return ce_match_stat(ce, st, 1);
2084 static int check_patch(struct patch *patch, struct patch *prev_patch)
2086 struct stat st;
2087 const char *old_name = patch->old_name;
2088 const char *new_name = patch->new_name;
2089 const char *name = old_name ? old_name : new_name;
2090 struct cache_entry *ce = NULL;
2091 int ok_if_exists;
2093 patch->rejected = 1; /* we will drop this after we succeed */
2096 * Make sure that we do not have local modifications from the
2097 * index when we are looking at the index. Also make sure
2098 * we have the preimage file to be patched in the work tree,
2099 * unless --cached, which tells git to apply only in the index.
2101 if (old_name) {
2102 int stat_ret = 0;
2103 unsigned st_mode = 0;
2105 if (!cached)
2106 stat_ret = lstat(old_name, &st);
2107 if (check_index) {
2108 int pos = cache_name_pos(old_name, strlen(old_name));
2109 if (pos < 0)
2110 return error("%s: does not exist in index",
2111 old_name);
2112 ce = active_cache[pos];
2113 if (stat_ret < 0) {
2114 struct checkout costate;
2115 if (errno != ENOENT)
2116 return error("%s: %s", old_name,
2117 strerror(errno));
2118 /* checkout */
2119 costate.base_dir = "";
2120 costate.base_dir_len = 0;
2121 costate.force = 0;
2122 costate.quiet = 0;
2123 costate.not_new = 0;
2124 costate.refresh_cache = 1;
2125 if (checkout_entry(ce,
2126 &costate,
2127 NULL) ||
2128 lstat(old_name, &st))
2129 return -1;
2131 if (!cached && verify_index_match(ce, &st))
2132 return error("%s: does not match index",
2133 old_name);
2134 if (cached)
2135 st_mode = ntohl(ce->ce_mode);
2136 } else if (stat_ret < 0)
2137 return error("%s: %s", old_name, strerror(errno));
2139 if (!cached)
2140 st_mode = ntohl(ce_mode_from_stat(ce, st.st_mode));
2142 if (patch->is_new < 0)
2143 patch->is_new = 0;
2144 if (!patch->old_mode)
2145 patch->old_mode = st_mode;
2146 if ((st_mode ^ patch->old_mode) & S_IFMT)
2147 return error("%s: wrong type", old_name);
2148 if (st_mode != patch->old_mode)
2149 fprintf(stderr, "warning: %s has type %o, expected %o\n",
2150 old_name, st_mode, patch->old_mode);
2153 if (new_name && prev_patch && 0 < prev_patch->is_delete &&
2154 !strcmp(prev_patch->old_name, new_name))
2155 /* A type-change diff is always split into a patch to
2156 * delete old, immediately followed by a patch to
2157 * create new (see diff.c::run_diff()); in such a case
2158 * it is Ok that the entry to be deleted by the
2159 * previous patch is still in the working tree and in
2160 * the index.
2162 ok_if_exists = 1;
2163 else
2164 ok_if_exists = 0;
2166 if (new_name &&
2167 ((0 < patch->is_new) | (0 < patch->is_rename) | patch->is_copy)) {
2168 if (check_index &&
2169 cache_name_pos(new_name, strlen(new_name)) >= 0 &&
2170 !ok_if_exists)
2171 return error("%s: already exists in index", new_name);
2172 if (!cached) {
2173 int err = check_to_create_blob(new_name, ok_if_exists);
2174 if (err)
2175 return err;
2177 if (!patch->new_mode) {
2178 if (0 < patch->is_new)
2179 patch->new_mode = S_IFREG | 0644;
2180 else
2181 patch->new_mode = patch->old_mode;
2185 if (new_name && old_name) {
2186 int same = !strcmp(old_name, new_name);
2187 if (!patch->new_mode)
2188 patch->new_mode = patch->old_mode;
2189 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
2190 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
2191 patch->new_mode, new_name, patch->old_mode,
2192 same ? "" : " of ", same ? "" : old_name);
2195 if (apply_data(patch, &st, ce) < 0)
2196 return error("%s: patch does not apply", name);
2197 patch->rejected = 0;
2198 return 0;
2201 static int check_patch_list(struct patch *patch)
2203 struct patch *prev_patch = NULL;
2204 int err = 0;
2206 for (prev_patch = NULL; patch ; patch = patch->next) {
2207 if (apply_verbosely)
2208 say_patch_name(stderr,
2209 "Checking patch ", patch, "...\n");
2210 err |= check_patch(patch, prev_patch);
2211 prev_patch = patch;
2213 return err;
2216 static void show_index_list(struct patch *list)
2218 struct patch *patch;
2220 /* Once we start supporting the reverse patch, it may be
2221 * worth showing the new sha1 prefix, but until then...
2223 for (patch = list; patch; patch = patch->next) {
2224 const unsigned char *sha1_ptr;
2225 unsigned char sha1[20];
2226 const char *name;
2228 name = patch->old_name ? patch->old_name : patch->new_name;
2229 if (0 < patch->is_new)
2230 sha1_ptr = null_sha1;
2231 else if (get_sha1(patch->old_sha1_prefix, sha1))
2232 die("sha1 information is lacking or useless (%s).",
2233 name);
2234 else
2235 sha1_ptr = sha1;
2237 printf("%06o %s ",patch->old_mode, sha1_to_hex(sha1_ptr));
2238 if (line_termination && quote_c_style(name, NULL, NULL, 0))
2239 quote_c_style(name, NULL, stdout, 0);
2240 else
2241 fputs(name, stdout);
2242 putchar(line_termination);
2246 static void stat_patch_list(struct patch *patch)
2248 int files, adds, dels;
2250 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
2251 files++;
2252 adds += patch->lines_added;
2253 dels += patch->lines_deleted;
2254 show_stats(patch);
2257 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
2260 static void numstat_patch_list(struct patch *patch)
2262 for ( ; patch; patch = patch->next) {
2263 const char *name;
2264 name = patch->new_name ? patch->new_name : patch->old_name;
2265 if (patch->is_binary)
2266 printf("-\t-\t");
2267 else
2268 printf("%d\t%d\t",
2269 patch->lines_added, patch->lines_deleted);
2270 if (line_termination && quote_c_style(name, NULL, NULL, 0))
2271 quote_c_style(name, NULL, stdout, 0);
2272 else
2273 fputs(name, stdout);
2274 putchar(line_termination);
2278 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
2280 if (mode)
2281 printf(" %s mode %06o %s\n", newdelete, mode, name);
2282 else
2283 printf(" %s %s\n", newdelete, name);
2286 static void show_mode_change(struct patch *p, int show_name)
2288 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
2289 if (show_name)
2290 printf(" mode change %06o => %06o %s\n",
2291 p->old_mode, p->new_mode, p->new_name);
2292 else
2293 printf(" mode change %06o => %06o\n",
2294 p->old_mode, p->new_mode);
2298 static void show_rename_copy(struct patch *p)
2300 const char *renamecopy = p->is_rename ? "rename" : "copy";
2301 const char *old, *new;
2303 /* Find common prefix */
2304 old = p->old_name;
2305 new = p->new_name;
2306 while (1) {
2307 const char *slash_old, *slash_new;
2308 slash_old = strchr(old, '/');
2309 slash_new = strchr(new, '/');
2310 if (!slash_old ||
2311 !slash_new ||
2312 slash_old - old != slash_new - new ||
2313 memcmp(old, new, slash_new - new))
2314 break;
2315 old = slash_old + 1;
2316 new = slash_new + 1;
2318 /* p->old_name thru old is the common prefix, and old and new
2319 * through the end of names are renames
2321 if (old != p->old_name)
2322 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
2323 (int)(old - p->old_name), p->old_name,
2324 old, new, p->score);
2325 else
2326 printf(" %s %s => %s (%d%%)\n", renamecopy,
2327 p->old_name, p->new_name, p->score);
2328 show_mode_change(p, 0);
2331 static void summary_patch_list(struct patch *patch)
2333 struct patch *p;
2335 for (p = patch; p; p = p->next) {
2336 if (p->is_new)
2337 show_file_mode_name("create", p->new_mode, p->new_name);
2338 else if (p->is_delete)
2339 show_file_mode_name("delete", p->old_mode, p->old_name);
2340 else {
2341 if (p->is_rename || p->is_copy)
2342 show_rename_copy(p);
2343 else {
2344 if (p->score) {
2345 printf(" rewrite %s (%d%%)\n",
2346 p->new_name, p->score);
2347 show_mode_change(p, 0);
2349 else
2350 show_mode_change(p, 1);
2356 static void patch_stats(struct patch *patch)
2358 int lines = patch->lines_added + patch->lines_deleted;
2360 if (lines > max_change)
2361 max_change = lines;
2362 if (patch->old_name) {
2363 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
2364 if (!len)
2365 len = strlen(patch->old_name);
2366 if (len > max_len)
2367 max_len = len;
2369 if (patch->new_name) {
2370 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
2371 if (!len)
2372 len = strlen(patch->new_name);
2373 if (len > max_len)
2374 max_len = len;
2378 static void remove_file(struct patch *patch, int rmdir_empty)
2380 if (update_index) {
2381 if (remove_file_from_cache(patch->old_name) < 0)
2382 die("unable to remove %s from index", patch->old_name);
2383 cache_tree_invalidate_path(active_cache_tree, patch->old_name);
2385 if (!cached) {
2386 if (S_ISGITLINK(patch->old_mode)) {
2387 if (rmdir(patch->old_name))
2388 warning("unable to remove submodule %s",
2389 patch->old_name);
2390 } else if (!unlink(patch->old_name) && rmdir_empty) {
2391 char *name = xstrdup(patch->old_name);
2392 char *end = strrchr(name, '/');
2393 while (end) {
2394 *end = 0;
2395 if (rmdir(name))
2396 break;
2397 end = strrchr(name, '/');
2399 free(name);
2404 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
2406 struct stat st;
2407 struct cache_entry *ce;
2408 int namelen = strlen(path);
2409 unsigned ce_size = cache_entry_size(namelen);
2411 if (!update_index)
2412 return;
2414 ce = xcalloc(1, ce_size);
2415 memcpy(ce->name, path, namelen);
2416 ce->ce_mode = create_ce_mode(mode);
2417 ce->ce_flags = htons(namelen);
2418 if (S_ISGITLINK(mode)) {
2419 const char *s = buf;
2421 if (get_sha1_hex(s + strlen("Subproject commit "), ce->sha1))
2422 die("corrupt patch for subproject %s", path);
2423 } else {
2424 if (!cached) {
2425 if (lstat(path, &st) < 0)
2426 die("unable to stat newly created file %s",
2427 path);
2428 fill_stat_cache_info(ce, &st);
2430 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
2431 die("unable to create backing store for newly created file %s", path);
2433 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
2434 die("unable to add cache entry for %s", path);
2437 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
2439 int fd;
2440 struct strbuf nbuf;
2442 if (S_ISGITLINK(mode)) {
2443 struct stat st;
2444 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
2445 return 0;
2446 return mkdir(path, 0777);
2449 if (has_symlinks && S_ISLNK(mode))
2450 /* Although buf:size is counted string, it also is NUL
2451 * terminated.
2453 return symlink(buf, path);
2455 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
2456 if (fd < 0)
2457 return -1;
2459 strbuf_init(&nbuf, 0);
2460 if (convert_to_working_tree(path, buf, size, &nbuf)) {
2461 size = nbuf.len;
2462 buf = nbuf.buf;
2465 while (size) {
2466 int written = xwrite(fd, buf, size);
2467 if (written < 0)
2468 die("writing file %s: %s", path, strerror(errno));
2469 if (!written)
2470 die("out of space writing file %s", path);
2471 buf += written;
2472 size -= written;
2474 if (close(fd) < 0)
2475 die("closing file %s: %s", path, strerror(errno));
2476 strbuf_release(&nbuf);
2477 return 0;
2481 * We optimistically assume that the directories exist,
2482 * which is true 99% of the time anyway. If they don't,
2483 * we create them and try again.
2485 static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
2487 if (cached)
2488 return;
2489 if (!try_create_file(path, mode, buf, size))
2490 return;
2492 if (errno == ENOENT) {
2493 if (safe_create_leading_directories(path))
2494 return;
2495 if (!try_create_file(path, mode, buf, size))
2496 return;
2499 if (errno == EEXIST || errno == EACCES) {
2500 /* We may be trying to create a file where a directory
2501 * used to be.
2503 struct stat st;
2504 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
2505 errno = EEXIST;
2508 if (errno == EEXIST) {
2509 unsigned int nr = getpid();
2511 for (;;) {
2512 const char *newpath;
2513 newpath = mkpath("%s~%u", path, nr);
2514 if (!try_create_file(newpath, mode, buf, size)) {
2515 if (!rename(newpath, path))
2516 return;
2517 unlink(newpath);
2518 break;
2520 if (errno != EEXIST)
2521 break;
2522 ++nr;
2525 die("unable to write file %s mode %o", path, mode);
2528 static void create_file(struct patch *patch)
2530 char *path = patch->new_name;
2531 unsigned mode = patch->new_mode;
2532 unsigned long size = patch->resultsize;
2533 char *buf = patch->result;
2535 if (!mode)
2536 mode = S_IFREG | 0644;
2537 create_one_file(path, mode, buf, size);
2538 add_index_file(path, mode, buf, size);
2539 cache_tree_invalidate_path(active_cache_tree, path);
2542 /* phase zero is to remove, phase one is to create */
2543 static void write_out_one_result(struct patch *patch, int phase)
2545 if (patch->is_delete > 0) {
2546 if (phase == 0)
2547 remove_file(patch, 1);
2548 return;
2550 if (patch->is_new > 0 || patch->is_copy) {
2551 if (phase == 1)
2552 create_file(patch);
2553 return;
2556 * Rename or modification boils down to the same
2557 * thing: remove the old, write the new
2559 if (phase == 0)
2560 remove_file(patch, patch->is_rename);
2561 if (phase == 1)
2562 create_file(patch);
2565 static int write_out_one_reject(struct patch *patch)
2567 FILE *rej;
2568 char namebuf[PATH_MAX];
2569 struct fragment *frag;
2570 int cnt = 0;
2572 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
2573 if (!frag->rejected)
2574 continue;
2575 cnt++;
2578 if (!cnt) {
2579 if (apply_verbosely)
2580 say_patch_name(stderr,
2581 "Applied patch ", patch, " cleanly.\n");
2582 return 0;
2585 /* This should not happen, because a removal patch that leaves
2586 * contents are marked "rejected" at the patch level.
2588 if (!patch->new_name)
2589 die("internal error");
2591 /* Say this even without --verbose */
2592 say_patch_name(stderr, "Applying patch ", patch, " with");
2593 fprintf(stderr, " %d rejects...\n", cnt);
2595 cnt = strlen(patch->new_name);
2596 if (ARRAY_SIZE(namebuf) <= cnt + 5) {
2597 cnt = ARRAY_SIZE(namebuf) - 5;
2598 fprintf(stderr,
2599 "warning: truncating .rej filename to %.*s.rej",
2600 cnt - 1, patch->new_name);
2602 memcpy(namebuf, patch->new_name, cnt);
2603 memcpy(namebuf + cnt, ".rej", 5);
2605 rej = fopen(namebuf, "w");
2606 if (!rej)
2607 return error("cannot open %s: %s", namebuf, strerror(errno));
2609 /* Normal git tools never deal with .rej, so do not pretend
2610 * this is a git patch by saying --git nor give extended
2611 * headers. While at it, maybe please "kompare" that wants
2612 * the trailing TAB and some garbage at the end of line ;-).
2614 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
2615 patch->new_name, patch->new_name);
2616 for (cnt = 1, frag = patch->fragments;
2617 frag;
2618 cnt++, frag = frag->next) {
2619 if (!frag->rejected) {
2620 fprintf(stderr, "Hunk #%d applied cleanly.\n", cnt);
2621 continue;
2623 fprintf(stderr, "Rejected hunk #%d.\n", cnt);
2624 fprintf(rej, "%.*s", frag->size, frag->patch);
2625 if (frag->patch[frag->size-1] != '\n')
2626 fputc('\n', rej);
2628 fclose(rej);
2629 return -1;
2632 static int write_out_results(struct patch *list, int skipped_patch)
2634 int phase;
2635 int errs = 0;
2636 struct patch *l;
2638 if (!list && !skipped_patch)
2639 return error("No changes");
2641 for (phase = 0; phase < 2; phase++) {
2642 l = list;
2643 while (l) {
2644 if (l->rejected)
2645 errs = 1;
2646 else {
2647 write_out_one_result(l, phase);
2648 if (phase == 1 && write_out_one_reject(l))
2649 errs = 1;
2651 l = l->next;
2654 return errs;
2657 static struct lock_file lock_file;
2659 static struct excludes {
2660 struct excludes *next;
2661 const char *path;
2662 } *excludes;
2664 static int use_patch(struct patch *p)
2666 const char *pathname = p->new_name ? p->new_name : p->old_name;
2667 struct excludes *x = excludes;
2668 while (x) {
2669 if (fnmatch(x->path, pathname, 0) == 0)
2670 return 0;
2671 x = x->next;
2673 if (0 < prefix_length) {
2674 int pathlen = strlen(pathname);
2675 if (pathlen <= prefix_length ||
2676 memcmp(prefix, pathname, prefix_length))
2677 return 0;
2679 return 1;
2682 static void prefix_one(char **name)
2684 char *old_name = *name;
2685 if (!old_name)
2686 return;
2687 *name = xstrdup(prefix_filename(prefix, prefix_length, *name));
2688 free(old_name);
2691 static void prefix_patches(struct patch *p)
2693 if (!prefix || p->is_toplevel_relative)
2694 return;
2695 for ( ; p; p = p->next) {
2696 if (p->new_name == p->old_name) {
2697 char *prefixed = p->new_name;
2698 prefix_one(&prefixed);
2699 p->new_name = p->old_name = prefixed;
2701 else {
2702 prefix_one(&p->new_name);
2703 prefix_one(&p->old_name);
2708 static int apply_patch(int fd, const char *filename, int inaccurate_eof)
2710 unsigned long offset, size;
2711 char *buffer = read_patch_file(fd, &size);
2712 struct patch *list = NULL, **listp = &list;
2713 int skipped_patch = 0;
2715 patch_input_file = filename;
2716 if (!buffer)
2717 return -1;
2718 offset = 0;
2719 while (size > 0) {
2720 struct patch *patch;
2721 int nr;
2723 patch = xcalloc(1, sizeof(*patch));
2724 patch->inaccurate_eof = inaccurate_eof;
2725 nr = parse_chunk(buffer + offset, size, patch);
2726 if (nr < 0)
2727 break;
2728 if (apply_in_reverse)
2729 reverse_patches(patch);
2730 if (prefix)
2731 prefix_patches(patch);
2732 if (use_patch(patch)) {
2733 patch_stats(patch);
2734 *listp = patch;
2735 listp = &patch->next;
2737 else {
2738 /* perhaps free it a bit better? */
2739 free(patch);
2740 skipped_patch++;
2742 offset += nr;
2743 size -= nr;
2746 if (whitespace_error && (new_whitespace == error_on_whitespace))
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");
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 (show_index_info)
2767 show_index_list(list);
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 free(buffer);
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;
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;
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;
2825 if (!prefixcmp(arg, "-p")) {
2826 p_value = atoi(arg + 2);
2827 p_value_known = 1;
2828 continue;
2830 if (!strcmp(arg, "--no-add")) {
2831 no_add = 1;
2832 continue;
2834 if (!strcmp(arg, "--stat")) {
2835 apply = 0;
2836 diffstat = 1;
2837 continue;
2839 if (!strcmp(arg, "--allow-binary-replacement") ||
2840 !strcmp(arg, "--binary")) {
2841 continue; /* now no-op */
2843 if (!strcmp(arg, "--numstat")) {
2844 apply = 0;
2845 numstat = 1;
2846 continue;
2848 if (!strcmp(arg, "--summary")) {
2849 apply = 0;
2850 summary = 1;
2851 continue;
2853 if (!strcmp(arg, "--check")) {
2854 apply = 0;
2855 check = 1;
2856 continue;
2858 if (!strcmp(arg, "--index")) {
2859 if (is_not_gitdir)
2860 die("--index outside a repository");
2861 check_index = 1;
2862 continue;
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;
2871 if (!strcmp(arg, "--apply")) {
2872 apply = 1;
2873 continue;
2875 if (!strcmp(arg, "--index-info")) {
2876 apply = 0;
2877 show_index_info = 1;
2878 continue;
2880 if (!strcmp(arg, "-z")) {
2881 line_termination = 0;
2882 continue;
2884 if (!prefixcmp(arg, "-C")) {
2885 p_context = strtoul(arg + 2, &end, 0);
2886 if (*end != '\0')
2887 die("unrecognized context count '%s'", arg + 2);
2888 continue;
2890 if (!prefixcmp(arg, "--whitespace=")) {
2891 whitespace_option = arg + 13;
2892 parse_whitespace_option(arg + 13);
2893 continue;
2895 if (!strcmp(arg, "-R") || !strcmp(arg, "--reverse")) {
2896 apply_in_reverse = 1;
2897 continue;
2899 if (!strcmp(arg, "--unidiff-zero")) {
2900 unidiff_zero = 1;
2901 continue;
2903 if (!strcmp(arg, "--reject")) {
2904 apply = apply_with_reject = apply_verbosely = 1;
2905 continue;
2907 if (!strcmp(arg, "-v") || !strcmp(arg, "--verbose")) {
2908 apply_verbosely = 1;
2909 continue;
2911 if (!strcmp(arg, "--inaccurate-eof")) {
2912 inaccurate_eof = 1;
2913 continue;
2915 if (0 < prefix_length)
2916 arg = prefix_filename(prefix, prefix_length, arg);
2918 fd = open(arg, O_RDONLY);
2919 if (fd < 0)
2920 usage(apply_usage);
2921 read_stdin = 0;
2922 set_default_whitespace_mode(whitespace_option);
2923 errs |= apply_patch(fd, arg, inaccurate_eof);
2924 close(fd);
2926 set_default_whitespace_mode(whitespace_option);
2927 if (read_stdin)
2928 errs |= apply_patch(0, "<stdin>", inaccurate_eof);
2929 if (whitespace_error) {
2930 if (squelch_whitespace_errors &&
2931 squelch_whitespace_errors < whitespace_error) {
2932 int squelched =
2933 whitespace_error - squelch_whitespace_errors;
2934 fprintf(stderr, "warning: squelched %d "
2935 "whitespace error%s\n",
2936 squelched,
2937 squelched == 1 ? "" : "s");
2939 if (new_whitespace == error_on_whitespace)
2940 die("%d line%s add%s whitespace errors.",
2941 whitespace_error,
2942 whitespace_error == 1 ? "" : "s",
2943 whitespace_error == 1 ? "s" : "");
2944 if (applied_after_fixing_ws)
2945 fprintf(stderr, "warning: %d line%s applied after"
2946 " fixing whitespace errors.\n",
2947 applied_after_fixing_ws,
2948 applied_after_fixing_ws == 1 ? "" : "s");
2949 else if (whitespace_error)
2950 fprintf(stderr, "warning: %d line%s add%s whitespace errors.\n",
2951 whitespace_error,
2952 whitespace_error == 1 ? "" : "s",
2953 whitespace_error == 1 ? "s" : "");
2956 if (update_index) {
2957 if (write_cache(newfd, active_cache, active_nr) ||
2958 close(newfd) || commit_locked_index(&lock_file))
2959 die("Unable to write new index file");
2962 return !!errs;