4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
11 #include "cache-tree.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 p_value = 1;
31 static int allow_binary_replacement = 0;
32 static int check_index = 0;
33 static int write_index = 0;
34 static int cached = 0;
35 static int diffstat = 0;
36 static int numstat = 0;
37 static int summary = 0;
40 static int no_add = 0;
41 static int show_index_info = 0;
42 static int line_termination = '\n';
43 static unsigned long p_context = -1;
44 static const char apply_usage[] =
45 "git-apply [--stat] [--numstat] [--summary] [--check] [--index] [--cached] [--apply] [--no-add] [--index-info] [--allow-binary-replacement] [-z] [-pNUM] [-CNUM] [--whitespace=<nowarn|warn|error|error-all|strip>] <patch>...";
47 static enum whitespace_eol {
52 } new_whitespace = warn_on_whitespace;
53 static int whitespace_error = 0;
54 static int squelch_whitespace_errors = 5;
55 static int applied_after_stripping = 0;
56 static const char *patch_input_file = NULL;
58 static void parse_whitespace_option(const char *option)
61 new_whitespace = warn_on_whitespace;
64 if (!strcmp(option, "warn")) {
65 new_whitespace = warn_on_whitespace;
68 if (!strcmp(option, "nowarn")) {
69 new_whitespace = nowarn_whitespace;
72 if (!strcmp(option, "error")) {
73 new_whitespace = error_on_whitespace;
76 if (!strcmp(option, "error-all")) {
77 new_whitespace = error_on_whitespace;
78 squelch_whitespace_errors = 0;
81 if (!strcmp(option, "strip")) {
82 new_whitespace = strip_whitespace;
85 die("unrecognized whitespace option '%s'", option);
88 static void set_default_whitespace_mode(const char *whitespace_option)
90 if (!whitespace_option && !apply_default_whitespace) {
91 new_whitespace = (apply
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
102 static int max_change, max_len;
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".
109 static int linenr = 1;
112 unsigned long leading, trailing;
113 unsigned long oldpos, oldlines;
114 unsigned long newpos, newlines;
117 struct fragment *next;
121 char *new_name, *old_name, *def_name;
122 unsigned int old_mode, new_mode;
123 int is_rename, is_copy, is_new, is_delete, is_binary, is_reverse;
124 #define BINARY_DELTA_DEFLATED 1
125 #define BINARY_LITERAL_DEFLATED 2
126 unsigned long deflate_origlen;
127 int lines_added, lines_deleted;
129 int inaccurate_eof:1;
130 struct fragment *fragments;
132 unsigned long resultsize;
133 char old_sha1_prefix[41];
134 char new_sha1_prefix[41];
138 #define CHUNKSIZE (8192)
141 static void *read_patch_file(int fd, unsigned long *sizep)
143 unsigned long size = 0, alloc = CHUNKSIZE;
144 void *buffer = xmalloc(alloc);
147 int nr = alloc - size;
150 buffer = xrealloc(buffer, alloc);
153 nr = xread(fd, (char *) buffer + size, nr);
157 die("git-apply: read returned %s", strerror(errno));
163 * Make sure that we have some slop in the buffer
164 * so that we can do speculative "memcmp" etc, and
165 * see to it that it is NUL-filled.
167 if (alloc < size + SLOP)
168 buffer = xrealloc(buffer, size + SLOP);
169 memset((char *) buffer + size, 0, SLOP);
173 static unsigned long linelen(const char *buffer, unsigned long size)
175 unsigned long len = 0;
178 if (*buffer++ == '\n')
184 static int is_dev_null(const char *str)
186 return !memcmp("/dev/null", str, 9) && isspace(str[9]);
192 static int name_terminate(const char *name, int namelen, int c, int terminate)
194 if (c == ' ' && !(terminate & TERM_SPACE))
196 if (c == '\t' && !(terminate & TERM_TAB))
202 static char * find_name(const char *line, char *def, int p_value, int terminate)
205 const char *start = line;
209 /* Proposed "new-style" GNU patch/diff format; see
210 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
212 name = unquote_c_style(line, NULL);
216 cp = strchr(name, '/');
223 /* name can later be freed, so we need
224 * to memmove, not just return cp
226 memmove(name, cp, strlen(cp) + 1);
243 if (name_terminate(start, line-start, c, terminate))
247 if (c == '/' && !--p_value)
257 * Generally we prefer the shorter name, especially
258 * if the other one is just a variation of that with
259 * something else tacked on to the end (ie "file.orig"
263 int deflen = strlen(def);
264 if (deflen < len && !strncmp(start, def, deflen))
268 name = xmalloc(len + 1);
269 memcpy(name, start, len);
276 * Get the name etc info from the --/+++ lines of a traditional patch header
278 * NOTE! This hardcodes "-p1" behaviour in filename detection.
280 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
281 * files, we can happily check the index for a match, but for creating a
282 * new file we should try to match whatever "patch" does. I have no idea.
284 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
288 first += 4; /* skip "--- " */
289 second += 4; /* skip "+++ " */
290 if (is_dev_null(first)) {
292 patch->is_delete = 0;
293 name = find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB);
294 patch->new_name = name;
295 } else if (is_dev_null(second)) {
297 patch->is_delete = 1;
298 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
299 patch->old_name = name;
301 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
302 name = find_name(second, name, p_value, TERM_SPACE | TERM_TAB);
303 patch->old_name = patch->new_name = name;
306 die("unable to find filename in patch at line %d", linenr);
309 static int gitdiff_hdrend(const char *line, struct patch *patch)
315 * We're anal about diff header consistency, to make
316 * sure that we don't end up having strange ambiguous
317 * patches floating around.
319 * As a result, gitdiff_{old|new}name() will check
320 * their names against any previous information, just
323 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
325 if (!orig_name && !isnull)
326 return find_name(line, NULL, 1, 0);
335 die("git-apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
336 another = find_name(line, NULL, 1, 0);
337 if (!another || memcmp(another, name, len))
338 die("git-apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
343 /* expect "/dev/null" */
344 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
345 die("git-apply: bad git-diff - expected /dev/null on line %d", linenr);
350 static int gitdiff_oldname(const char *line, struct patch *patch)
352 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
356 static int gitdiff_newname(const char *line, struct patch *patch)
358 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
362 static int gitdiff_oldmode(const char *line, struct patch *patch)
364 patch->old_mode = strtoul(line, NULL, 8);
368 static int gitdiff_newmode(const char *line, struct patch *patch)
370 patch->new_mode = strtoul(line, NULL, 8);
374 static int gitdiff_delete(const char *line, struct patch *patch)
376 patch->is_delete = 1;
377 patch->old_name = patch->def_name;
378 return gitdiff_oldmode(line, patch);
381 static int gitdiff_newfile(const char *line, struct patch *patch)
384 patch->new_name = patch->def_name;
385 return gitdiff_newmode(line, patch);
388 static int gitdiff_copysrc(const char *line, struct patch *patch)
391 patch->old_name = find_name(line, NULL, 0, 0);
395 static int gitdiff_copydst(const char *line, struct patch *patch)
398 patch->new_name = find_name(line, NULL, 0, 0);
402 static int gitdiff_renamesrc(const char *line, struct patch *patch)
404 patch->is_rename = 1;
405 patch->old_name = find_name(line, NULL, 0, 0);
409 static int gitdiff_renamedst(const char *line, struct patch *patch)
411 patch->is_rename = 1;
412 patch->new_name = find_name(line, NULL, 0, 0);
416 static int gitdiff_similarity(const char *line, struct patch *patch)
418 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
423 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
425 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
430 static int gitdiff_index(const char *line, struct patch *patch)
432 /* index line is N hexadecimal, "..", N hexadecimal,
433 * and optional space with octal mode.
435 const char *ptr, *eol;
438 ptr = strchr(line, '.');
439 if (!ptr || ptr[1] != '.' || 40 < ptr - line)
442 memcpy(patch->old_sha1_prefix, line, len);
443 patch->old_sha1_prefix[len] = 0;
446 ptr = strchr(line, ' ');
447 eol = strchr(line, '\n');
449 if (!ptr || eol < ptr)
455 memcpy(patch->new_sha1_prefix, line, len);
456 patch->new_sha1_prefix[len] = 0;
458 patch->new_mode = patch->old_mode = strtoul(ptr+1, NULL, 8);
463 * This is normal for a diff that doesn't change anything: we'll fall through
464 * into the next diff. Tell the parser to break out.
466 static int gitdiff_unrecognized(const char *line, struct patch *patch)
471 static const char *stop_at_slash(const char *line, int llen)
475 for (i = 0; i < llen; i++) {
483 /* This is to extract the same name that appears on "diff --git"
484 * line. We do not find and return anything if it is a rename
485 * patch, and it is OK because we will find the name elsewhere.
486 * We need to reliably find name only when it is mode-change only,
487 * creation or deletion of an empty file. In any of these cases,
488 * both sides are the same name under a/ and b/ respectively.
490 static char *git_header_name(char *line, int llen)
494 const char *second = NULL;
496 line += strlen("diff --git ");
497 llen -= strlen("diff --git ");
501 char *first = unquote_c_style(line, &second);
505 /* advance to the first slash */
506 cp = stop_at_slash(first, strlen(first));
507 if (!cp || cp == first) {
508 /* we do not accept absolute paths */
514 memmove(first, cp+1, len+1); /* including NUL */
516 /* second points at one past closing dq of name.
517 * find the second name.
519 while ((second < line + llen) && isspace(*second))
522 if (line + llen <= second)
523 goto free_first_and_fail;
524 if (*second == '"') {
525 char *sp = unquote_c_style(second, NULL);
527 goto free_first_and_fail;
528 cp = stop_at_slash(sp, strlen(sp));
529 if (!cp || cp == sp) {
532 goto free_first_and_fail;
534 /* They must match, otherwise ignore */
535 if (strcmp(cp+1, first))
536 goto free_both_and_fail;
541 /* unquoted second */
542 cp = stop_at_slash(second, line + llen - second);
543 if (!cp || cp == second)
544 goto free_first_and_fail;
546 if (line + llen - cp != len + 1 ||
547 memcmp(first, cp, len))
548 goto free_first_and_fail;
552 /* unquoted first name */
553 name = stop_at_slash(line, llen);
554 if (!name || name == line)
559 /* since the first name is unquoted, a dq if exists must be
560 * the beginning of the second name.
562 for (second = name; second < line + llen; second++) {
563 if (*second == '"') {
564 const char *cp = second;
566 char *sp = unquote_c_style(second, NULL);
570 np = stop_at_slash(sp, strlen(sp));
571 if (!np || np == sp) {
572 free_second_and_fail:
578 if (len < cp - name &&
579 !strncmp(np, name, len) &&
580 isspace(name[len])) {
582 memmove(sp, np, len + 1);
585 goto free_second_and_fail;
590 * Accept a name only if it shows up twice, exactly the same
593 for (len = 0 ; ; len++) {
610 if (second[len] == '\n' && !memcmp(name, second, len)) {
611 char *ret = xmalloc(len + 1);
612 memcpy(ret, name, len);
621 /* Verify that we recognize the lines following a git header */
622 static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
624 unsigned long offset;
626 /* A git diff has explicit new/delete information, so we don't guess */
628 patch->is_delete = 0;
631 * Some things may not have the old name in the
632 * rest of the headers anywhere (pure mode changes,
633 * or removing or adding empty files), so we get
634 * the default name from the header.
636 patch->def_name = git_header_name(line, len);
641 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
642 static const struct opentry {
644 int (*fn)(const char *, struct patch *);
646 { "@@ -", gitdiff_hdrend },
647 { "--- ", gitdiff_oldname },
648 { "+++ ", gitdiff_newname },
649 { "old mode ", gitdiff_oldmode },
650 { "new mode ", gitdiff_newmode },
651 { "deleted file mode ", gitdiff_delete },
652 { "new file mode ", gitdiff_newfile },
653 { "copy from ", gitdiff_copysrc },
654 { "copy to ", gitdiff_copydst },
655 { "rename old ", gitdiff_renamesrc },
656 { "rename new ", gitdiff_renamedst },
657 { "rename from ", gitdiff_renamesrc },
658 { "rename to ", gitdiff_renamedst },
659 { "similarity index ", gitdiff_similarity },
660 { "dissimilarity index ", gitdiff_dissimilarity },
661 { "index ", gitdiff_index },
662 { "", gitdiff_unrecognized },
666 len = linelen(line, size);
667 if (!len || line[len-1] != '\n')
669 for (i = 0; i < ARRAY_SIZE(optable); i++) {
670 const struct opentry *p = optable + i;
671 int oplen = strlen(p->str);
672 if (len < oplen || memcmp(p->str, line, oplen))
674 if (p->fn(line + oplen, patch) < 0)
683 static int parse_num(const char *line, unsigned long *p)
689 *p = strtoul(line, &ptr, 10);
693 static int parse_range(const char *line, int len, int offset, const char *expect,
694 unsigned long *p1, unsigned long *p2)
698 if (offset < 0 || offset >= len)
703 digits = parse_num(line, p1);
713 digits = parse_num(line+1, p2);
725 if (memcmp(line, expect, ex))
732 * Parse a unified diff fragment header of the
733 * form "@@ -a,b +c,d @@"
735 static int parse_fragment_header(char *line, int len, struct fragment *fragment)
739 if (!len || line[len-1] != '\n')
742 /* Figure out the number of lines in a fragment */
743 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
744 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
749 static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
751 unsigned long offset, len;
753 patch->is_rename = patch->is_copy = 0;
754 patch->is_new = patch->is_delete = -1;
755 patch->old_mode = patch->new_mode = 0;
756 patch->old_name = patch->new_name = NULL;
757 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
758 unsigned long nextlen;
760 len = linelen(line, size);
764 /* Testing this early allows us to take a few shortcuts.. */
769 * Make sure we don't find any unconnected patch fragments.
770 * That's a sign that we didn't find a header, and that a
771 * patch has become corrupted/broken up.
773 if (!memcmp("@@ -", line, 4)) {
774 struct fragment dummy;
775 if (parse_fragment_header(line, len, &dummy) < 0)
777 error("patch fragment without header at line %d: %.*s", linenr, (int)len-1, line);
784 * Git patch? It might not have a real patch, just a rename
785 * or mode change, so we handle that specially
787 if (!memcmp("diff --git ", line, 11)) {
788 int git_hdr_len = parse_git_header(line, len, size, patch);
789 if (git_hdr_len <= len)
791 if (!patch->old_name && !patch->new_name) {
792 if (!patch->def_name)
793 die("git diff header lacks filename information (line %d)", linenr);
794 patch->old_name = patch->new_name = patch->def_name;
796 *hdrsize = git_hdr_len;
800 /** --- followed by +++ ? */
801 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
805 * We only accept unified patches, so we want it to
806 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
809 nextlen = linelen(line + len, size - len);
810 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
813 /* Ok, we'll consider it a patch */
814 parse_traditional_patch(line, line+len, patch);
815 *hdrsize = len + nextlen;
823 * Parse a unified diff. Note that this really needs
824 * to parse each fragment separately, since the only
825 * way to know the difference between a "---" that is
826 * part of a patch, and a "---" that starts the next
827 * patch is to look at the line counts..
829 static int parse_fragment(char *line, unsigned long size, struct patch *patch, struct fragment *fragment)
832 int len = linelen(line, size), offset;
833 unsigned long oldlines, newlines;
834 unsigned long leading, trailing;
836 offset = parse_fragment_header(line, len, fragment);
839 oldlines = fragment->oldlines;
840 newlines = fragment->newlines;
844 if (patch->is_new < 0) {
845 patch->is_new = !oldlines;
847 patch->old_name = NULL;
849 if (patch->is_delete < 0) {
850 patch->is_delete = !newlines;
852 patch->new_name = NULL;
855 if (patch->is_new && oldlines)
856 return error("new file depends on old contents");
857 if (patch->is_delete != !newlines) {
859 return error("deleted file still has contents");
860 fprintf(stderr, "** warning: file %s becomes empty but is not deleted\n", patch->new_name);
863 /* Parse the thing.. */
868 for (offset = len; size > 0; offset += len, size -= len, line += len, linenr++) {
869 if (!oldlines && !newlines)
871 len = linelen(line, size);
872 if (!len || line[len-1] != '\n')
880 if (!deleted && !added)
891 * We know len is at least two, since we have a '+' and
892 * we checked that the last character was a '\n' above.
893 * That is, an addition of an empty line would check
894 * the '+' here. Sneaky...
896 if ((new_whitespace != nowarn_whitespace) &&
897 isspace(line[len-2])) {
899 if (squelch_whitespace_errors &&
900 squelch_whitespace_errors <
904 fprintf(stderr, "Adds trailing whitespace.\n%s:%d:%.*s\n",
906 linenr, len-2, line+1);
914 /* We allow "\ No newline at end of file". Depending
915 * on locale settings when the patch was produced we
916 * don't know what this line looks like. The only
917 * thing we do know is that it begins with "\ ".
918 * Checking for 12 is just for sanity check -- any
919 * l10n of "\ No newline..." is at least that long.
922 if (len < 12 || memcmp(line, "\\ ", 2))
927 if (oldlines || newlines)
929 fragment->leading = leading;
930 fragment->trailing = trailing;
932 /* If a fragment ends with an incomplete line, we failed to include
933 * it in the above loop because we hit oldlines == newlines == 0
936 if (12 < size && !memcmp(line, "\\ ", 2))
937 offset += linelen(line, size);
939 patch->lines_added += added;
940 patch->lines_deleted += deleted;
944 static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
946 unsigned long offset = 0;
947 struct fragment **fragp = &patch->fragments;
949 while (size > 4 && !memcmp(line, "@@ -", 4)) {
950 struct fragment *fragment;
953 fragment = xcalloc(1, sizeof(*fragment));
954 len = parse_fragment(line, size, patch, fragment);
956 die("corrupt patch at line %d", linenr);
958 fragment->patch = line;
959 fragment->size = len;
962 fragp = &fragment->next;
971 static inline int metadata_changes(struct patch *patch)
973 return patch->is_rename > 0 ||
974 patch->is_copy > 0 ||
977 (patch->old_mode && patch->new_mode &&
978 patch->old_mode != patch->new_mode);
981 static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
983 /* We have read "GIT binary patch\n"; what follows is a line
984 * that says the patch method (currently, either "deflated
985 * literal" or "deflated delta") and the length of data before
986 * deflating; a sequence of 'length-byte' followed by base-85
987 * encoded data follows.
989 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
990 * and we would limit the patch line to 66 characters,
991 * so one line can fit up to 13 groups that would decode
992 * to 52 bytes max. The length byte 'A'-'Z' corresponds
993 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
994 * The end of binary is signaled with an empty line.
997 struct fragment *fragment;
1000 patch->fragments = fragment = xcalloc(1, sizeof(*fragment));
1002 /* Grab the type of patch */
1003 llen = linelen(buffer, size);
1007 if (!strncmp(buffer, "delta ", 6)) {
1008 patch->is_binary = BINARY_DELTA_DEFLATED;
1009 patch->deflate_origlen = strtoul(buffer + 6, NULL, 10);
1011 else if (!strncmp(buffer, "literal ", 8)) {
1012 patch->is_binary = BINARY_LITERAL_DEFLATED;
1013 patch->deflate_origlen = strtoul(buffer + 8, NULL, 10);
1016 return error("unrecognized binary patch at line %d: %.*s",
1017 linenr-1, llen-1, buffer);
1020 int byte_length, max_byte_length, newsize;
1021 llen = linelen(buffer, size);
1026 /* Minimum line is "A00000\n" which is 7-byte long,
1027 * and the line length must be multiple of 5 plus 2.
1029 if ((llen < 7) || (llen-2) % 5)
1031 max_byte_length = (llen - 2) / 5 * 4;
1032 byte_length = *buffer;
1033 if ('A' <= byte_length && byte_length <= 'Z')
1034 byte_length = byte_length - 'A' + 1;
1035 else if ('a' <= byte_length && byte_length <= 'z')
1036 byte_length = byte_length - 'a' + 27;
1039 /* if the input length was not multiple of 4, we would
1040 * have filler at the end but the filler should never
1043 if (max_byte_length < byte_length ||
1044 byte_length <= max_byte_length - 4)
1046 newsize = fragment->size + byte_length;
1047 data = xrealloc(data, newsize);
1048 if (decode_85(data + fragment->size,
1052 fragment->size = newsize;
1056 fragment->patch = data;
1059 return error("corrupt binary patch at line %d: %.*s",
1060 linenr-1, llen-1, buffer);
1063 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
1065 int hdrsize, patchsize;
1066 int offset = find_header(buffer, size, &hdrsize, patch);
1071 patchsize = parse_single_patch(buffer + offset + hdrsize, size - offset - hdrsize, patch);
1074 static const char *binhdr[] = {
1079 static const char git_binary[] = "GIT binary patch\n";
1081 int hd = hdrsize + offset;
1082 unsigned long llen = linelen(buffer + hd, size - hd);
1084 if (llen == sizeof(git_binary) - 1 &&
1085 !memcmp(git_binary, buffer + hd, llen)) {
1088 used = parse_binary(buffer + hd + llen,
1089 size - hd - llen, patch);
1091 patchsize = used + llen;
1095 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
1096 for (i = 0; binhdr[i]; i++) {
1097 int len = strlen(binhdr[i]);
1098 if (len < size - hd &&
1099 !memcmp(binhdr[i], buffer + hd, len)) {
1101 patch->is_binary = 1;
1108 /* Empty patch cannot be applied if:
1109 * - it is a binary patch and we do not do binary_replace, or
1110 * - text patch without metadata change
1112 if ((apply || check) &&
1114 ? !allow_binary_replacement
1115 : !metadata_changes(patch)))
1116 die("patch with only garbage at line %d", linenr);
1119 return offset + hdrsize + patchsize;
1122 #define swap(a,b) myswap((a),(b),sizeof(a))
1124 #define myswap(a, b, size) do { \
1125 unsigned char mytmp[size]; \
1126 memcpy(mytmp, &a, size); \
1127 memcpy(&a, &b, size); \
1128 memcpy(&b, mytmp, size); \
1131 static void reverse_patches(struct patch *p)
1133 for (; p; p = p->next) {
1134 struct fragment *frag = p->fragments;
1136 swap(p->new_name, p->old_name);
1137 swap(p->new_mode, p->old_mode);
1138 swap(p->is_new, p->is_delete);
1139 swap(p->lines_added, p->lines_deleted);
1140 swap(p->old_sha1_prefix, p->new_sha1_prefix);
1142 for (; frag; frag = frag->next) {
1143 swap(frag->newpos, frag->oldpos);
1144 swap(frag->newlines, frag->oldlines);
1146 p->is_reverse = !p->is_reverse;
1150 static const char pluses[] = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1151 static const char minuses[]= "----------------------------------------------------------------------";
1153 static void show_stats(struct patch *patch)
1155 const char *prefix = "";
1156 char *name = patch->new_name;
1158 int len, max, add, del, total;
1161 name = patch->old_name;
1163 if (0 < (len = quote_c_style(name, NULL, NULL, 0))) {
1164 qname = xmalloc(len + 1);
1165 quote_c_style(name, qname, NULL, 0);
1170 * "scale" the filename
1181 slash = strchr(name, '/');
1188 * scale the add/delete
1194 add = patch->lines_added;
1195 del = patch->lines_deleted;
1198 if (max_change > 0) {
1199 total = (total * max + max_change / 2) / max_change;
1200 add = (add * max + max_change / 2) / max_change;
1203 if (patch->is_binary)
1204 printf(" %s%-*s | Bin\n", prefix, len, name);
1206 printf(" %s%-*s |%5d %.*s%.*s\n", prefix,
1207 len, name, patch->lines_added + patch->lines_deleted,
1208 add, pluses, del, minuses);
1213 static int read_old_data(struct stat *st, const char *path, void *buf, unsigned long size)
1218 switch (st->st_mode & S_IFMT) {
1220 return readlink(path, buf, size);
1222 fd = open(path, O_RDONLY);
1224 return error("unable to open %s", path);
1227 int ret = xread(fd, (char *) buf + got, size - got);
1240 static int find_offset(const char *buf, unsigned long size, const char *fragment, unsigned long fragsize, int line, int *lines)
1243 unsigned long start, backwards, forwards;
1245 if (fragsize > size)
1250 unsigned long offset = 0;
1252 while (offset + fragsize <= size) {
1253 if (buf[offset++] == '\n') {
1261 /* Exact line number? */
1262 if (!memcmp(buf + start, fragment, fragsize))
1266 * There's probably some smart way to do this, but I'll leave
1267 * that to the smart and beautiful people. I'm simple and stupid.
1271 for (i = 0; ; i++) {
1278 if (forwards + fragsize > size)
1284 } while (backwards && buf[backwards-1] != '\n');
1287 while (forwards + fragsize <= size) {
1288 if (buf[forwards++] == '\n')
1294 if (try + fragsize > size)
1296 if (memcmp(buf + try, fragment, fragsize))
1306 * We should start searching forward and backward.
1311 static void remove_first_line(const char **rbuf, int *rsize)
1313 const char *buf = *rbuf;
1315 unsigned long offset;
1317 while (offset <= size) {
1318 if (buf[offset++] == '\n')
1321 *rsize = size - offset;
1322 *rbuf = buf + offset;
1325 static void remove_last_line(const char **rbuf, int *rsize)
1327 const char *buf = *rbuf;
1329 unsigned long offset;
1331 while (offset > 0) {
1332 if (buf[--offset] == '\n')
1335 *rsize = offset + 1;
1338 struct buffer_desc {
1341 unsigned long alloc;
1344 static int apply_line(char *output, const char *patch, int plen)
1346 /* plen is number of bytes to be copied from patch,
1347 * starting at patch+1 (patch[0] is '+'). Typically
1348 * patch[plen] is '\n'.
1350 int add_nl_to_tail = 0;
1351 if ((new_whitespace == strip_whitespace) &&
1352 1 < plen && isspace(patch[plen-1])) {
1353 if (patch[plen] == '\n')
1356 while (0 < plen && isspace(patch[plen]))
1358 applied_after_stripping++;
1360 memcpy(output, patch + 1, plen);
1362 output[plen++] = '\n';
1366 static int apply_one_fragment(struct buffer_desc *desc, struct fragment *frag,
1367 int reverse, int inaccurate_eof)
1369 int match_beginning, match_end;
1370 char *buf = desc->buffer;
1371 const char *patch = frag->patch;
1372 int offset, size = frag->size;
1373 char *old = xmalloc(size);
1374 char *new = xmalloc(size);
1375 const char *oldlines, *newlines;
1376 int oldsize = 0, newsize = 0;
1377 unsigned long leading, trailing;
1382 int len = linelen(patch, size);
1389 * "plen" is how much of the line we should use for
1390 * the actual patch data. Normally we just remove the
1391 * first character on the line, but if the line is
1392 * followed by "\ No newline", then we also remove the
1393 * last one (which is the newline, of course).
1396 if (len < size && patch[len] == '\\')
1402 else if (first == '+')
1408 memcpy(old + oldsize, patch + 1, plen);
1412 /* Fall-through for ' ' */
1414 if (first != '+' || !no_add)
1415 newsize += apply_line(new + newsize, patch,
1418 case '@': case '\\':
1419 /* Ignore it, we already handled it */
1428 if (inaccurate_eof && oldsize > 0 && old[oldsize - 1] == '\n' &&
1429 newsize > 0 && new[newsize - 1] == '\n') {
1436 leading = frag->leading;
1437 trailing = frag->trailing;
1440 * If we don't have any leading/trailing data in the patch,
1441 * we want it to match at the beginning/end of the file.
1443 match_beginning = !leading && (frag->oldpos == 1);
1444 match_end = !trailing;
1449 offset = find_offset(buf, desc->size, oldlines, oldsize, pos, &lines);
1450 if (match_end && offset + oldsize != desc->size)
1452 if (match_beginning && offset)
1455 int diff = newsize - oldsize;
1456 unsigned long size = desc->size + diff;
1457 unsigned long alloc = desc->alloc;
1459 /* Warn if it was necessary to reduce the number
1462 if ((leading != frag->leading) || (trailing != frag->trailing))
1463 fprintf(stderr, "Context reduced to (%ld/%ld) to apply fragment at %d\n",
1464 leading, trailing, pos + lines);
1467 alloc = size + 8192;
1468 desc->alloc = alloc;
1469 buf = xrealloc(buf, alloc);
1473 memmove(buf + offset + newsize, buf + offset + oldsize, size - offset - newsize);
1474 memcpy(buf + offset, newlines, newsize);
1480 /* Am I at my context limits? */
1481 if ((leading <= p_context) && (trailing <= p_context))
1483 if (match_beginning || match_end) {
1484 match_beginning = match_end = 0;
1487 /* Reduce the number of context lines
1488 * Reduce both leading and trailing if they are equal
1489 * otherwise just reduce the larger context.
1491 if (leading >= trailing) {
1492 remove_first_line(&oldlines, &oldsize);
1493 remove_first_line(&newlines, &newsize);
1497 if (trailing > leading) {
1498 remove_last_line(&oldlines, &oldsize);
1499 remove_last_line(&newlines, &newsize);
1509 static char *inflate_it(const void *data, unsigned long size,
1510 unsigned long inflated_size)
1516 memset(&stream, 0, sizeof(stream));
1518 stream.next_in = (unsigned char *)data;
1519 stream.avail_in = size;
1520 stream.next_out = out = xmalloc(inflated_size);
1521 stream.avail_out = inflated_size;
1522 inflateInit(&stream);
1523 st = inflate(&stream, Z_FINISH);
1524 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1531 static int apply_binary_fragment(struct buffer_desc *desc, struct patch *patch)
1533 unsigned long dst_size;
1534 struct fragment *fragment = patch->fragments;
1538 /* Binary patch is irreversible */
1539 if (patch->is_reverse)
1540 return error("cannot reverse-apply a binary patch to '%s'",
1542 ? patch->new_name : patch->old_name);
1544 data = inflate_it(fragment->patch, fragment->size,
1545 patch->deflate_origlen);
1547 return error("corrupt patch data");
1548 switch (patch->is_binary) {
1549 case BINARY_DELTA_DEFLATED:
1550 result = patch_delta(desc->buffer, desc->size,
1552 patch->deflate_origlen,
1555 desc->buffer = result;
1558 case BINARY_LITERAL_DEFLATED:
1560 desc->buffer = data;
1561 dst_size = patch->deflate_origlen;
1566 desc->size = desc->alloc = dst_size;
1570 static int apply_binary(struct buffer_desc *desc, struct patch *patch)
1572 const char *name = patch->old_name ? patch->old_name : patch->new_name;
1573 unsigned char sha1[20];
1574 unsigned char hdr[50];
1577 if (!allow_binary_replacement)
1578 return error("cannot apply binary patch to '%s' "
1579 "without --allow-binary-replacement",
1582 /* For safety, we require patch index line to contain
1583 * full 40-byte textual SHA1 for old and new, at least for now.
1585 if (strlen(patch->old_sha1_prefix) != 40 ||
1586 strlen(patch->new_sha1_prefix) != 40 ||
1587 get_sha1_hex(patch->old_sha1_prefix, sha1) ||
1588 get_sha1_hex(patch->new_sha1_prefix, sha1))
1589 return error("cannot apply binary patch to '%s' "
1590 "without full index line", name);
1592 if (patch->old_name) {
1593 /* See if the old one matches what the patch
1596 write_sha1_file_prepare(desc->buffer, desc->size,
1597 blob_type, sha1, hdr, &hdrlen);
1598 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
1599 return error("the patch applies to '%s' (%s), "
1600 "which does not match the "
1601 "current contents.",
1602 name, sha1_to_hex(sha1));
1605 /* Otherwise, the old one must be empty. */
1607 return error("the patch applies to an empty "
1608 "'%s' but it is not empty", name);
1611 get_sha1_hex(patch->new_sha1_prefix, sha1);
1612 if (!memcmp(sha1, null_sha1, 20)) {
1614 desc->alloc = desc->size = 0;
1615 desc->buffer = NULL;
1616 return 0; /* deletion patch */
1619 if (has_sha1_file(sha1)) {
1620 /* We already have the postimage */
1625 desc->buffer = read_sha1_file(sha1, type, &size);
1627 return error("the necessary postimage %s for "
1628 "'%s' cannot be read",
1629 patch->new_sha1_prefix, name);
1630 desc->alloc = desc->size = size;
1633 /* We have verified desc matches the preimage;
1634 * apply the patch data to it, which is stored
1635 * in the patch->fragments->{patch,size}.
1637 if (apply_binary_fragment(desc, patch))
1638 return error("binary patch does not apply to '%s'",
1641 /* verify that the result matches */
1642 write_sha1_file_prepare(desc->buffer, desc->size, blob_type,
1643 sha1, hdr, &hdrlen);
1644 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
1645 return error("binary patch to '%s' creates incorrect result", name);
1651 static int apply_fragments(struct buffer_desc *desc, struct patch *patch)
1653 struct fragment *frag = patch->fragments;
1654 const char *name = patch->old_name ? patch->old_name : patch->new_name;
1656 if (patch->is_binary)
1657 return apply_binary(desc, patch);
1660 if (apply_one_fragment(desc, frag, patch->is_reverse,
1661 patch->inaccurate_eof) < 0)
1662 return error("patch failed: %s:%ld",
1663 name, frag->oldpos);
1669 static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce)
1672 unsigned long size, alloc;
1673 struct buffer_desc desc;
1681 buf = read_sha1_file(ce->sha1, type, &size);
1683 return error("read of %s failed",
1688 else if (patch->old_name) {
1690 alloc = size + 8192;
1691 buf = xmalloc(alloc);
1692 if (read_old_data(st, patch->old_name, buf, alloc) != size)
1693 return error("read of %s failed", patch->old_name);
1699 if (apply_fragments(&desc, patch) < 0)
1702 /* NUL terminate the result */
1703 if (desc.alloc <= desc.size)
1704 desc.buffer = xrealloc(desc.buffer, desc.size + 1);
1705 desc.buffer[desc.size] = 0;
1707 patch->result = desc.buffer;
1708 patch->resultsize = desc.size;
1710 if (patch->is_delete && patch->resultsize)
1711 return error("removal patch leaves file contents");
1716 static int check_patch(struct patch *patch, struct patch *prev_patch)
1719 const char *old_name = patch->old_name;
1720 const char *new_name = patch->new_name;
1721 const char *name = old_name ? old_name : new_name;
1722 struct cache_entry *ce = NULL;
1728 unsigned st_mode = 0;
1731 stat_ret = lstat(old_name, &st);
1733 int pos = cache_name_pos(old_name, strlen(old_name));
1735 return error("%s: does not exist in index",
1737 ce = active_cache[pos];
1739 struct checkout costate;
1740 if (errno != ENOENT)
1741 return error("%s: %s", old_name,
1744 costate.base_dir = "";
1745 costate.base_dir_len = 0;
1748 costate.not_new = 0;
1749 costate.refresh_cache = 1;
1750 if (checkout_entry(ce,
1753 lstat(old_name, &st))
1757 changed = ce_match_stat(ce, &st, 1);
1759 return error("%s: does not match index",
1762 st_mode = ntohl(ce->ce_mode);
1764 else if (stat_ret < 0)
1765 return error("%s: %s", old_name, strerror(errno));
1768 st_mode = ntohl(create_ce_mode(st.st_mode));
1770 if (patch->is_new < 0)
1772 if (!patch->old_mode)
1773 patch->old_mode = st_mode;
1774 if ((st_mode ^ patch->old_mode) & S_IFMT)
1775 return error("%s: wrong type", old_name);
1776 if (st_mode != patch->old_mode)
1777 fprintf(stderr, "warning: %s has type %o, expected %o\n",
1778 old_name, st_mode, patch->old_mode);
1781 if (new_name && prev_patch && prev_patch->is_delete &&
1782 !strcmp(prev_patch->old_name, new_name))
1783 /* A type-change diff is always split into a patch to
1784 * delete old, immediately followed by a patch to
1785 * create new (see diff.c::run_diff()); in such a case
1786 * it is Ok that the entry to be deleted by the
1787 * previous patch is still in the working tree and in
1794 if (new_name && (patch->is_new | patch->is_rename | patch->is_copy)) {
1796 cache_name_pos(new_name, strlen(new_name)) >= 0 &&
1798 return error("%s: already exists in index", new_name);
1801 if (!lstat(new_name, &nst)) {
1802 if (S_ISDIR(nst.st_mode) || ok_if_exists)
1805 return error("%s: already exists in working directory", new_name);
1807 else if ((errno != ENOENT) && (errno != ENOTDIR))
1808 return error("%s: %s", new_name, strerror(errno));
1810 if (!patch->new_mode) {
1812 patch->new_mode = S_IFREG | 0644;
1814 patch->new_mode = patch->old_mode;
1818 if (new_name && old_name) {
1819 int same = !strcmp(old_name, new_name);
1820 if (!patch->new_mode)
1821 patch->new_mode = patch->old_mode;
1822 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
1823 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
1824 patch->new_mode, new_name, patch->old_mode,
1825 same ? "" : " of ", same ? "" : old_name);
1828 if (apply_data(patch, &st, ce) < 0)
1829 return error("%s: patch does not apply", name);
1833 static int check_patch_list(struct patch *patch)
1835 struct patch *prev_patch = NULL;
1838 for (prev_patch = NULL; patch ; patch = patch->next) {
1839 error |= check_patch(patch, prev_patch);
1845 static inline int is_null_sha1(const unsigned char *sha1)
1847 return !memcmp(sha1, null_sha1, 20);
1850 static void show_index_list(struct patch *list)
1852 struct patch *patch;
1854 /* Once we start supporting the reverse patch, it may be
1855 * worth showing the new sha1 prefix, but until then...
1857 for (patch = list; patch; patch = patch->next) {
1858 const unsigned char *sha1_ptr;
1859 unsigned char sha1[20];
1862 name = patch->old_name ? patch->old_name : patch->new_name;
1864 sha1_ptr = null_sha1;
1865 else if (get_sha1(patch->old_sha1_prefix, sha1))
1866 die("sha1 information is lacking or useless (%s).",
1871 printf("%06o %s ",patch->old_mode, sha1_to_hex(sha1_ptr));
1872 if (line_termination && quote_c_style(name, NULL, NULL, 0))
1873 quote_c_style(name, NULL, stdout, 0);
1875 fputs(name, stdout);
1876 putchar(line_termination);
1880 static void stat_patch_list(struct patch *patch)
1882 int files, adds, dels;
1884 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
1886 adds += patch->lines_added;
1887 dels += patch->lines_deleted;
1891 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
1894 static void numstat_patch_list(struct patch *patch)
1896 for ( ; patch; patch = patch->next) {
1898 name = patch->new_name ? patch->new_name : patch->old_name;
1899 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
1900 if (line_termination && quote_c_style(name, NULL, NULL, 0))
1901 quote_c_style(name, NULL, stdout, 0);
1903 fputs(name, stdout);
1908 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
1911 printf(" %s mode %06o %s\n", newdelete, mode, name);
1913 printf(" %s %s\n", newdelete, name);
1916 static void show_mode_change(struct patch *p, int show_name)
1918 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
1920 printf(" mode change %06o => %06o %s\n",
1921 p->old_mode, p->new_mode, p->new_name);
1923 printf(" mode change %06o => %06o\n",
1924 p->old_mode, p->new_mode);
1928 static void show_rename_copy(struct patch *p)
1930 const char *renamecopy = p->is_rename ? "rename" : "copy";
1931 const char *old, *new;
1933 /* Find common prefix */
1937 const char *slash_old, *slash_new;
1938 slash_old = strchr(old, '/');
1939 slash_new = strchr(new, '/');
1942 slash_old - old != slash_new - new ||
1943 memcmp(old, new, slash_new - new))
1945 old = slash_old + 1;
1946 new = slash_new + 1;
1948 /* p->old_name thru old is the common prefix, and old and new
1949 * through the end of names are renames
1951 if (old != p->old_name)
1952 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
1953 (int)(old - p->old_name), p->old_name,
1954 old, new, p->score);
1956 printf(" %s %s => %s (%d%%)\n", renamecopy,
1957 p->old_name, p->new_name, p->score);
1958 show_mode_change(p, 0);
1961 static void summary_patch_list(struct patch *patch)
1965 for (p = patch; p; p = p->next) {
1967 show_file_mode_name("create", p->new_mode, p->new_name);
1968 else if (p->is_delete)
1969 show_file_mode_name("delete", p->old_mode, p->old_name);
1971 if (p->is_rename || p->is_copy)
1972 show_rename_copy(p);
1975 printf(" rewrite %s (%d%%)\n",
1976 p->new_name, p->score);
1977 show_mode_change(p, 0);
1980 show_mode_change(p, 1);
1986 static void patch_stats(struct patch *patch)
1988 int lines = patch->lines_added + patch->lines_deleted;
1990 if (lines > max_change)
1992 if (patch->old_name) {
1993 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
1995 len = strlen(patch->old_name);
1999 if (patch->new_name) {
2000 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
2002 len = strlen(patch->new_name);
2008 static void remove_file(struct patch *patch)
2011 if (remove_file_from_cache(patch->old_name) < 0)
2012 die("unable to remove %s from index", patch->old_name);
2013 cache_tree_invalidate_path(active_cache_tree, patch->old_name);
2016 unlink(patch->old_name);
2019 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
2022 struct cache_entry *ce;
2023 int namelen = strlen(path);
2024 unsigned ce_size = cache_entry_size(namelen);
2029 ce = xcalloc(1, ce_size);
2030 memcpy(ce->name, path, namelen);
2031 ce->ce_mode = create_ce_mode(mode);
2032 ce->ce_flags = htons(namelen);
2034 if (lstat(path, &st) < 0)
2035 die("unable to stat newly created file %s", path);
2036 fill_stat_cache_info(ce, &st);
2038 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
2039 die("unable to create backing store for newly created file %s", path);
2040 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
2041 die("unable to add cache entry for %s", path);
2044 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
2049 /* Although buf:size is counted string, it also is NUL
2052 return symlink(buf, path);
2053 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
2057 int written = xwrite(fd, buf, size);
2059 die("writing file %s: %s", path, strerror(errno));
2061 die("out of space writing file %s", path);
2066 die("closing file %s: %s", path, strerror(errno));
2071 * We optimistically assume that the directories exist,
2072 * which is true 99% of the time anyway. If they don't,
2073 * we create them and try again.
2075 static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
2079 if (!try_create_file(path, mode, buf, size))
2082 if (errno == ENOENT) {
2083 if (safe_create_leading_directories(path))
2085 if (!try_create_file(path, mode, buf, size))
2089 if (errno == EEXIST || errno == EACCES) {
2090 /* We may be trying to create a file where a directory
2095 if (!lstat(path, &st) && S_ISDIR(st.st_mode) && !rmdir(path))
2099 if (errno == EEXIST) {
2100 unsigned int nr = getpid();
2103 const char *newpath;
2104 newpath = mkpath("%s~%u", path, nr);
2105 if (!try_create_file(newpath, mode, buf, size)) {
2106 if (!rename(newpath, path))
2111 if (errno != EEXIST)
2116 die("unable to write file %s mode %o", path, mode);
2119 static void create_file(struct patch *patch)
2121 char *path = patch->new_name;
2122 unsigned mode = patch->new_mode;
2123 unsigned long size = patch->resultsize;
2124 char *buf = patch->result;
2127 mode = S_IFREG | 0644;
2128 create_one_file(path, mode, buf, size);
2129 add_index_file(path, mode, buf, size);
2130 cache_tree_invalidate_path(active_cache_tree, path);
2133 /* phase zero is to remove, phase one is to create */
2134 static void write_out_one_result(struct patch *patch, int phase)
2136 if (patch->is_delete > 0) {
2141 if (patch->is_new > 0 || patch->is_copy) {
2147 * Rename or modification boils down to the same
2148 * thing: remove the old, write the new
2156 static void write_out_results(struct patch *list, int skipped_patch)
2160 if (!list && !skipped_patch)
2163 for (phase = 0; phase < 2; phase++) {
2164 struct patch *l = list;
2166 write_out_one_result(l, phase);
2172 static struct lock_file lock_file;
2174 static struct excludes {
2175 struct excludes *next;
2179 static int use_patch(struct patch *p)
2181 const char *pathname = p->new_name ? p->new_name : p->old_name;
2182 struct excludes *x = excludes;
2184 if (fnmatch(x->path, pathname, 0) == 0)
2188 if (0 < prefix_length) {
2189 int pathlen = strlen(pathname);
2190 if (pathlen <= prefix_length ||
2191 memcmp(prefix, pathname, prefix_length))
2197 static int apply_patch(int fd, const char *filename,
2198 int reverse, int inaccurate_eof)
2200 unsigned long offset, size;
2201 char *buffer = read_patch_file(fd, &size);
2202 struct patch *list = NULL, **listp = &list;
2203 int skipped_patch = 0;
2205 patch_input_file = filename;
2210 struct patch *patch;
2213 patch = xcalloc(1, sizeof(*patch));
2214 patch->inaccurate_eof = inaccurate_eof;
2215 nr = parse_chunk(buffer + offset, size, patch);
2219 reverse_patches(patch);
2220 if (use_patch(patch)) {
2223 listp = &patch->next;
2225 /* perhaps free it a bit better? */
2233 if (whitespace_error && (new_whitespace == error_on_whitespace))
2236 write_index = check_index && apply;
2237 if (write_index && newfd < 0)
2238 newfd = hold_lock_file_for_update(&lock_file,
2239 get_index_file(), 1);
2241 if (read_cache() < 0)
2242 die("unable to read index file");
2245 if ((check || apply) && check_patch_list(list) < 0)
2249 write_out_results(list, skipped_patch);
2251 if (show_index_info)
2252 show_index_list(list);
2255 stat_patch_list(list);
2258 numstat_patch_list(list);
2261 summary_patch_list(list);
2267 static int git_apply_config(const char *var, const char *value)
2269 if (!strcmp(var, "apply.whitespace")) {
2270 apply_default_whitespace = strdup(value);
2273 return git_default_config(var, value);
2277 int cmd_apply(int argc, const char **argv, const char *prefix)
2282 int inaccurate_eof = 0;
2284 const char *whitespace_option = NULL;
2286 for (i = 1; i < argc; i++) {
2287 const char *arg = argv[i];
2291 if (!strcmp(arg, "-")) {
2292 apply_patch(0, "<stdin>", reverse, inaccurate_eof);
2296 if (!strncmp(arg, "--exclude=", 10)) {
2297 struct excludes *x = xmalloc(sizeof(*x));
2303 if (!strncmp(arg, "-p", 2)) {
2304 p_value = atoi(arg + 2);
2307 if (!strcmp(arg, "--no-add")) {
2311 if (!strcmp(arg, "--stat")) {
2316 if (!strcmp(arg, "--allow-binary-replacement") ||
2317 !strcmp(arg, "--binary")) {
2318 allow_binary_replacement = 1;
2321 if (!strcmp(arg, "--numstat")) {
2326 if (!strcmp(arg, "--summary")) {
2331 if (!strcmp(arg, "--check")) {
2336 if (!strcmp(arg, "--index")) {
2340 if (!strcmp(arg, "--cached")) {
2345 if (!strcmp(arg, "--apply")) {
2349 if (!strcmp(arg, "--index-info")) {
2351 show_index_info = 1;
2354 if (!strcmp(arg, "-z")) {
2355 line_termination = 0;
2358 if (!strncmp(arg, "-C", 2)) {
2359 p_context = strtoul(arg + 2, &end, 0);
2361 die("unrecognized context count '%s'", arg + 2);
2364 if (!strncmp(arg, "--whitespace=", 13)) {
2365 whitespace_option = arg + 13;
2366 parse_whitespace_option(arg + 13);
2369 if (!strcmp(arg, "-R") || !strcmp(arg, "--reverse")) {
2373 if (!strcmp(arg, "--inaccurate-eof")) {
2378 if (check_index && prefix_length < 0) {
2379 prefix = setup_git_directory();
2380 prefix_length = prefix ? strlen(prefix) : 0;
2381 git_config(git_apply_config);
2382 if (!whitespace_option && apply_default_whitespace)
2383 parse_whitespace_option(apply_default_whitespace);
2385 if (0 < prefix_length)
2386 arg = prefix_filename(prefix, prefix_length, arg);
2388 fd = open(arg, O_RDONLY);
2392 set_default_whitespace_mode(whitespace_option);
2393 apply_patch(fd, arg, reverse, inaccurate_eof);
2396 set_default_whitespace_mode(whitespace_option);
2398 apply_patch(0, "<stdin>", reverse, inaccurate_eof);
2399 if (whitespace_error) {
2400 if (squelch_whitespace_errors &&
2401 squelch_whitespace_errors < whitespace_error) {
2403 whitespace_error - squelch_whitespace_errors;
2404 fprintf(stderr, "warning: squelched %d whitespace error%s\n",
2406 squelched == 1 ? "" : "s");
2408 if (new_whitespace == error_on_whitespace)
2409 die("%d line%s add%s trailing whitespaces.",
2411 whitespace_error == 1 ? "" : "s",
2412 whitespace_error == 1 ? "s" : "");
2413 if (applied_after_stripping)
2414 fprintf(stderr, "warning: %d line%s applied after"
2415 " stripping trailing whitespaces.\n",
2416 applied_after_stripping,
2417 applied_after_stripping == 1 ? "" : "s");
2418 else if (whitespace_error)
2419 fprintf(stderr, "warning: %d line%s add%s trailing"
2422 whitespace_error == 1 ? "" : "s",
2423 whitespace_error == 1 ? "s" : "");
2427 if (write_cache(newfd, active_cache, active_nr) ||
2428 close(newfd) || commit_lock_file(&lock_file))
2429 die("Unable to write new index file");