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;
32 static int check_index;
33 static int write_index;
40 static int apply_in_reverse;
41 static int apply_with_reject;
43 static int show_index_info;
44 static int line_termination = '\n';
45 static unsigned long p_context = -1;
46 static const char apply_usage[] =
47 "git-apply [--stat] [--numstat] [--summary] [--check] [--index] [--cached] [--apply] [--no-add] [--index-info] [--allow-binary-replacement] [--reverse] [--reject] [-z] [-pNUM] [-CNUM] [--whitespace=<nowarn|warn|error|error-all|strip>] <patch>...";
49 static enum whitespace_eol {
54 } new_whitespace = warn_on_whitespace;
55 static int whitespace_error;
56 static int squelch_whitespace_errors = 5;
57 static int applied_after_stripping;
58 static const char *patch_input_file;
60 static void parse_whitespace_option(const char *option)
63 new_whitespace = warn_on_whitespace;
66 if (!strcmp(option, "warn")) {
67 new_whitespace = warn_on_whitespace;
70 if (!strcmp(option, "nowarn")) {
71 new_whitespace = nowarn_whitespace;
74 if (!strcmp(option, "error")) {
75 new_whitespace = error_on_whitespace;
78 if (!strcmp(option, "error-all")) {
79 new_whitespace = error_on_whitespace;
80 squelch_whitespace_errors = 0;
83 if (!strcmp(option, "strip")) {
84 new_whitespace = strip_whitespace;
87 die("unrecognized whitespace option '%s'", option);
90 static void set_default_whitespace_mode(const char *whitespace_option)
92 if (!whitespace_option && !apply_default_whitespace) {
93 new_whitespace = (apply
100 * For "diff-stat" like behaviour, we keep track of the biggest change
101 * we've seen, and the longest filename. That allows us to do simple
104 static int max_change, max_len;
107 * Various "current state", notably line numbers and what
108 * file (and how) we're patching right now.. The "is_xxxx"
109 * things are flags, where -1 means "don't know yet".
111 static int linenr = 1;
114 * This represents one "hunk" from a patch, starting with
115 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
116 * patch text is pointed at by patch, and its byte length
117 * is stored in size. leading and trailing are the number
121 unsigned long leading, trailing;
122 unsigned long oldpos, oldlines;
123 unsigned long newpos, newlines;
127 struct fragment *next;
131 * When dealing with a binary patch, we reuse "leading" field
132 * to store the type of the binary hunk, either deflated "delta"
133 * or deflated "literal".
135 #define binary_patch_method leading
136 #define BINARY_DELTA_DEFLATED 1
137 #define BINARY_LITERAL_DEFLATED 2
140 char *new_name, *old_name, *def_name;
141 unsigned int old_mode, new_mode;
142 int is_rename, is_copy, is_new, is_delete, is_binary;
144 unsigned long deflate_origlen;
145 int lines_added, lines_deleted;
147 int inaccurate_eof:1;
148 struct fragment *fragments;
150 unsigned long resultsize;
151 char old_sha1_prefix[41];
152 char new_sha1_prefix[41];
156 #define CHUNKSIZE (8192)
159 static void *read_patch_file(int fd, unsigned long *sizep)
161 unsigned long size = 0, alloc = CHUNKSIZE;
162 void *buffer = xmalloc(alloc);
165 int nr = alloc - size;
168 buffer = xrealloc(buffer, alloc);
171 nr = xread(fd, (char *) buffer + size, nr);
175 die("git-apply: read returned %s", strerror(errno));
181 * Make sure that we have some slop in the buffer
182 * so that we can do speculative "memcmp" etc, and
183 * see to it that it is NUL-filled.
185 if (alloc < size + SLOP)
186 buffer = xrealloc(buffer, size + SLOP);
187 memset((char *) buffer + size, 0, SLOP);
191 static unsigned long linelen(const char *buffer, unsigned long size)
193 unsigned long len = 0;
196 if (*buffer++ == '\n')
202 static int is_dev_null(const char *str)
204 return !memcmp("/dev/null", str, 9) && isspace(str[9]);
210 static int name_terminate(const char *name, int namelen, int c, int terminate)
212 if (c == ' ' && !(terminate & TERM_SPACE))
214 if (c == '\t' && !(terminate & TERM_TAB))
220 static char * find_name(const char *line, char *def, int p_value, int terminate)
223 const char *start = line;
227 /* Proposed "new-style" GNU patch/diff format; see
228 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
230 name = unquote_c_style(line, NULL);
234 cp = strchr(name, '/');
241 /* name can later be freed, so we need
242 * to memmove, not just return cp
244 memmove(name, cp, strlen(cp) + 1);
261 if (name_terminate(start, line-start, c, terminate))
265 if (c == '/' && !--p_value)
275 * Generally we prefer the shorter name, especially
276 * if the other one is just a variation of that with
277 * something else tacked on to the end (ie "file.orig"
281 int deflen = strlen(def);
282 if (deflen < len && !strncmp(start, def, deflen))
286 name = xmalloc(len + 1);
287 memcpy(name, start, len);
294 * Get the name etc info from the --/+++ lines of a traditional patch header
296 * NOTE! This hardcodes "-p1" behaviour in filename detection.
298 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
299 * files, we can happily check the index for a match, but for creating a
300 * new file we should try to match whatever "patch" does. I have no idea.
302 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
306 first += 4; /* skip "--- " */
307 second += 4; /* skip "+++ " */
308 if (is_dev_null(first)) {
310 patch->is_delete = 0;
311 name = find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB);
312 patch->new_name = name;
313 } else if (is_dev_null(second)) {
315 patch->is_delete = 1;
316 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
317 patch->old_name = name;
319 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
320 name = find_name(second, name, p_value, TERM_SPACE | TERM_TAB);
321 patch->old_name = patch->new_name = name;
324 die("unable to find filename in patch at line %d", linenr);
327 static int gitdiff_hdrend(const char *line, struct patch *patch)
333 * We're anal about diff header consistency, to make
334 * sure that we don't end up having strange ambiguous
335 * patches floating around.
337 * As a result, gitdiff_{old|new}name() will check
338 * their names against any previous information, just
341 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
343 if (!orig_name && !isnull)
344 return find_name(line, NULL, 1, 0);
353 die("git-apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
354 another = find_name(line, NULL, 1, 0);
355 if (!another || memcmp(another, name, len))
356 die("git-apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
361 /* expect "/dev/null" */
362 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
363 die("git-apply: bad git-diff - expected /dev/null on line %d", linenr);
368 static int gitdiff_oldname(const char *line, struct patch *patch)
370 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
374 static int gitdiff_newname(const char *line, struct patch *patch)
376 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
380 static int gitdiff_oldmode(const char *line, struct patch *patch)
382 patch->old_mode = strtoul(line, NULL, 8);
386 static int gitdiff_newmode(const char *line, struct patch *patch)
388 patch->new_mode = strtoul(line, NULL, 8);
392 static int gitdiff_delete(const char *line, struct patch *patch)
394 patch->is_delete = 1;
395 patch->old_name = patch->def_name;
396 return gitdiff_oldmode(line, patch);
399 static int gitdiff_newfile(const char *line, struct patch *patch)
402 patch->new_name = patch->def_name;
403 return gitdiff_newmode(line, patch);
406 static int gitdiff_copysrc(const char *line, struct patch *patch)
409 patch->old_name = find_name(line, NULL, 0, 0);
413 static int gitdiff_copydst(const char *line, struct patch *patch)
416 patch->new_name = find_name(line, NULL, 0, 0);
420 static int gitdiff_renamesrc(const char *line, struct patch *patch)
422 patch->is_rename = 1;
423 patch->old_name = find_name(line, NULL, 0, 0);
427 static int gitdiff_renamedst(const char *line, struct patch *patch)
429 patch->is_rename = 1;
430 patch->new_name = find_name(line, NULL, 0, 0);
434 static int gitdiff_similarity(const char *line, struct patch *patch)
436 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
441 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
443 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
448 static int gitdiff_index(const char *line, struct patch *patch)
450 /* index line is N hexadecimal, "..", N hexadecimal,
451 * and optional space with octal mode.
453 const char *ptr, *eol;
456 ptr = strchr(line, '.');
457 if (!ptr || ptr[1] != '.' || 40 < ptr - line)
460 memcpy(patch->old_sha1_prefix, line, len);
461 patch->old_sha1_prefix[len] = 0;
464 ptr = strchr(line, ' ');
465 eol = strchr(line, '\n');
467 if (!ptr || eol < ptr)
473 memcpy(patch->new_sha1_prefix, line, len);
474 patch->new_sha1_prefix[len] = 0;
476 patch->new_mode = patch->old_mode = strtoul(ptr+1, NULL, 8);
481 * This is normal for a diff that doesn't change anything: we'll fall through
482 * into the next diff. Tell the parser to break out.
484 static int gitdiff_unrecognized(const char *line, struct patch *patch)
489 static const char *stop_at_slash(const char *line, int llen)
493 for (i = 0; i < llen; i++) {
501 /* This is to extract the same name that appears on "diff --git"
502 * line. We do not find and return anything if it is a rename
503 * patch, and it is OK because we will find the name elsewhere.
504 * We need to reliably find name only when it is mode-change only,
505 * creation or deletion of an empty file. In any of these cases,
506 * both sides are the same name under a/ and b/ respectively.
508 static char *git_header_name(char *line, int llen)
512 const char *second = NULL;
514 line += strlen("diff --git ");
515 llen -= strlen("diff --git ");
519 char *first = unquote_c_style(line, &second);
523 /* advance to the first slash */
524 cp = stop_at_slash(first, strlen(first));
525 if (!cp || cp == first) {
526 /* we do not accept absolute paths */
532 memmove(first, cp+1, len+1); /* including NUL */
534 /* second points at one past closing dq of name.
535 * find the second name.
537 while ((second < line + llen) && isspace(*second))
540 if (line + llen <= second)
541 goto free_first_and_fail;
542 if (*second == '"') {
543 char *sp = unquote_c_style(second, NULL);
545 goto free_first_and_fail;
546 cp = stop_at_slash(sp, strlen(sp));
547 if (!cp || cp == sp) {
550 goto free_first_and_fail;
552 /* They must match, otherwise ignore */
553 if (strcmp(cp+1, first))
554 goto free_both_and_fail;
559 /* unquoted second */
560 cp = stop_at_slash(second, line + llen - second);
561 if (!cp || cp == second)
562 goto free_first_and_fail;
564 if (line + llen - cp != len + 1 ||
565 memcmp(first, cp, len))
566 goto free_first_and_fail;
570 /* unquoted first name */
571 name = stop_at_slash(line, llen);
572 if (!name || name == line)
577 /* since the first name is unquoted, a dq if exists must be
578 * the beginning of the second name.
580 for (second = name; second < line + llen; second++) {
581 if (*second == '"') {
582 const char *cp = second;
584 char *sp = unquote_c_style(second, NULL);
588 np = stop_at_slash(sp, strlen(sp));
589 if (!np || np == sp) {
590 free_second_and_fail:
596 if (len < cp - name &&
597 !strncmp(np, name, len) &&
598 isspace(name[len])) {
600 memmove(sp, np, len + 1);
603 goto free_second_and_fail;
608 * Accept a name only if it shows up twice, exactly the same
611 for (len = 0 ; ; len++) {
628 if (second[len] == '\n' && !memcmp(name, second, len)) {
629 char *ret = xmalloc(len + 1);
630 memcpy(ret, name, len);
639 /* Verify that we recognize the lines following a git header */
640 static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
642 unsigned long offset;
644 /* A git diff has explicit new/delete information, so we don't guess */
646 patch->is_delete = 0;
649 * Some things may not have the old name in the
650 * rest of the headers anywhere (pure mode changes,
651 * or removing or adding empty files), so we get
652 * the default name from the header.
654 patch->def_name = git_header_name(line, len);
659 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
660 static const struct opentry {
662 int (*fn)(const char *, struct patch *);
664 { "@@ -", gitdiff_hdrend },
665 { "--- ", gitdiff_oldname },
666 { "+++ ", gitdiff_newname },
667 { "old mode ", gitdiff_oldmode },
668 { "new mode ", gitdiff_newmode },
669 { "deleted file mode ", gitdiff_delete },
670 { "new file mode ", gitdiff_newfile },
671 { "copy from ", gitdiff_copysrc },
672 { "copy to ", gitdiff_copydst },
673 { "rename old ", gitdiff_renamesrc },
674 { "rename new ", gitdiff_renamedst },
675 { "rename from ", gitdiff_renamesrc },
676 { "rename to ", gitdiff_renamedst },
677 { "similarity index ", gitdiff_similarity },
678 { "dissimilarity index ", gitdiff_dissimilarity },
679 { "index ", gitdiff_index },
680 { "", gitdiff_unrecognized },
684 len = linelen(line, size);
685 if (!len || line[len-1] != '\n')
687 for (i = 0; i < ARRAY_SIZE(optable); i++) {
688 const struct opentry *p = optable + i;
689 int oplen = strlen(p->str);
690 if (len < oplen || memcmp(p->str, line, oplen))
692 if (p->fn(line + oplen, patch) < 0)
701 static int parse_num(const char *line, unsigned long *p)
707 *p = strtoul(line, &ptr, 10);
711 static int parse_range(const char *line, int len, int offset, const char *expect,
712 unsigned long *p1, unsigned long *p2)
716 if (offset < 0 || offset >= len)
721 digits = parse_num(line, p1);
731 digits = parse_num(line+1, p2);
743 if (memcmp(line, expect, ex))
750 * Parse a unified diff fragment header of the
751 * form "@@ -a,b +c,d @@"
753 static int parse_fragment_header(char *line, int len, struct fragment *fragment)
757 if (!len || line[len-1] != '\n')
760 /* Figure out the number of lines in a fragment */
761 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
762 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
767 static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
769 unsigned long offset, len;
771 patch->is_rename = patch->is_copy = 0;
772 patch->is_new = patch->is_delete = -1;
773 patch->old_mode = patch->new_mode = 0;
774 patch->old_name = patch->new_name = NULL;
775 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
776 unsigned long nextlen;
778 len = linelen(line, size);
782 /* Testing this early allows us to take a few shortcuts.. */
787 * Make sure we don't find any unconnected patch fragments.
788 * That's a sign that we didn't find a header, and that a
789 * patch has become corrupted/broken up.
791 if (!memcmp("@@ -", line, 4)) {
792 struct fragment dummy;
793 if (parse_fragment_header(line, len, &dummy) < 0)
795 error("patch fragment without header at line %d: %.*s", linenr, (int)len-1, line);
802 * Git patch? It might not have a real patch, just a rename
803 * or mode change, so we handle that specially
805 if (!memcmp("diff --git ", line, 11)) {
806 int git_hdr_len = parse_git_header(line, len, size, patch);
807 if (git_hdr_len <= len)
809 if (!patch->old_name && !patch->new_name) {
810 if (!patch->def_name)
811 die("git diff header lacks filename information (line %d)", linenr);
812 patch->old_name = patch->new_name = patch->def_name;
814 *hdrsize = git_hdr_len;
818 /** --- followed by +++ ? */
819 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
823 * We only accept unified patches, so we want it to
824 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
827 nextlen = linelen(line + len, size - len);
828 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
831 /* Ok, we'll consider it a patch */
832 parse_traditional_patch(line, line+len, patch);
833 *hdrsize = len + nextlen;
841 * Parse a unified diff. Note that this really needs
842 * to parse each fragment separately, since the only
843 * way to know the difference between a "---" that is
844 * part of a patch, and a "---" that starts the next
845 * patch is to look at the line counts..
847 static int parse_fragment(char *line, unsigned long size, struct patch *patch, struct fragment *fragment)
850 int len = linelen(line, size), offset;
851 unsigned long oldlines, newlines;
852 unsigned long leading, trailing;
854 offset = parse_fragment_header(line, len, fragment);
857 oldlines = fragment->oldlines;
858 newlines = fragment->newlines;
862 if (patch->is_new < 0) {
863 patch->is_new = !oldlines;
865 patch->old_name = NULL;
867 if (patch->is_delete < 0) {
868 patch->is_delete = !newlines;
870 patch->new_name = NULL;
873 if (patch->is_new && oldlines)
874 return error("new file depends on old contents");
875 if (patch->is_delete != !newlines) {
877 return error("deleted file still has contents");
878 fprintf(stderr, "** warning: file %s becomes empty but is not deleted\n", patch->new_name);
881 /* Parse the thing.. */
886 for (offset = len; size > 0; offset += len, size -= len, line += len, linenr++) {
887 if (!oldlines && !newlines)
889 len = linelen(line, size);
890 if (!len || line[len-1] != '\n')
898 if (!deleted && !added)
909 * We know len is at least two, since we have a '+' and
910 * we checked that the last character was a '\n' above.
911 * That is, an addition of an empty line would check
912 * the '+' here. Sneaky...
914 if ((new_whitespace != nowarn_whitespace) &&
915 isspace(line[len-2])) {
917 if (squelch_whitespace_errors &&
918 squelch_whitespace_errors <
922 fprintf(stderr, "Adds trailing whitespace.\n%s:%d:%.*s\n",
924 linenr, len-2, line+1);
932 /* We allow "\ No newline at end of file". Depending
933 * on locale settings when the patch was produced we
934 * don't know what this line looks like. The only
935 * thing we do know is that it begins with "\ ".
936 * Checking for 12 is just for sanity check -- any
937 * l10n of "\ No newline..." is at least that long.
940 if (len < 12 || memcmp(line, "\\ ", 2))
945 if (oldlines || newlines)
947 fragment->leading = leading;
948 fragment->trailing = trailing;
950 /* If a fragment ends with an incomplete line, we failed to include
951 * it in the above loop because we hit oldlines == newlines == 0
954 if (12 < size && !memcmp(line, "\\ ", 2))
955 offset += linelen(line, size);
957 patch->lines_added += added;
958 patch->lines_deleted += deleted;
962 static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
964 unsigned long offset = 0;
965 struct fragment **fragp = &patch->fragments;
967 while (size > 4 && !memcmp(line, "@@ -", 4)) {
968 struct fragment *fragment;
971 fragment = xcalloc(1, sizeof(*fragment));
972 len = parse_fragment(line, size, patch, fragment);
974 die("corrupt patch at line %d", linenr);
976 fragment->patch = line;
977 fragment->size = len;
980 fragp = &fragment->next;
989 static inline int metadata_changes(struct patch *patch)
991 return patch->is_rename > 0 ||
992 patch->is_copy > 0 ||
995 (patch->old_mode && patch->new_mode &&
996 patch->old_mode != patch->new_mode);
999 static char *inflate_it(const void *data, unsigned long size,
1000 unsigned long inflated_size)
1006 memset(&stream, 0, sizeof(stream));
1008 stream.next_in = (unsigned char *)data;
1009 stream.avail_in = size;
1010 stream.next_out = out = xmalloc(inflated_size);
1011 stream.avail_out = inflated_size;
1012 inflateInit(&stream);
1013 st = inflate(&stream, Z_FINISH);
1014 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1021 static struct fragment *parse_binary_hunk(char **buf_p,
1022 unsigned long *sz_p,
1026 /* Expect a line that begins with binary patch method ("literal"
1027 * or "delta"), followed by the length of data before deflating.
1028 * a sequence of 'length-byte' followed by base-85 encoded data
1029 * should follow, terminated by a newline.
1031 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1032 * and we would limit the patch line to 66 characters,
1033 * so one line can fit up to 13 groups that would decode
1034 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1035 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1038 unsigned long size = *sz_p;
1039 char *buffer = *buf_p;
1041 unsigned long origlen;
1044 struct fragment *frag;
1046 llen = linelen(buffer, size);
1051 if (!strncmp(buffer, "delta ", 6)) {
1052 patch_method = BINARY_DELTA_DEFLATED;
1053 origlen = strtoul(buffer + 6, NULL, 10);
1055 else if (!strncmp(buffer, "literal ", 8)) {
1056 patch_method = BINARY_LITERAL_DEFLATED;
1057 origlen = strtoul(buffer + 8, NULL, 10);
1065 int byte_length, max_byte_length, newsize;
1066 llen = linelen(buffer, size);
1070 /* consume the blank line */
1075 /* Minimum line is "A00000\n" which is 7-byte long,
1076 * and the line length must be multiple of 5 plus 2.
1078 if ((llen < 7) || (llen-2) % 5)
1080 max_byte_length = (llen - 2) / 5 * 4;
1081 byte_length = *buffer;
1082 if ('A' <= byte_length && byte_length <= 'Z')
1083 byte_length = byte_length - 'A' + 1;
1084 else if ('a' <= byte_length && byte_length <= 'z')
1085 byte_length = byte_length - 'a' + 27;
1088 /* if the input length was not multiple of 4, we would
1089 * have filler at the end but the filler should never
1092 if (max_byte_length < byte_length ||
1093 byte_length <= max_byte_length - 4)
1095 newsize = hunk_size + byte_length;
1096 data = xrealloc(data, newsize);
1097 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1099 hunk_size = newsize;
1104 frag = xcalloc(1, sizeof(*frag));
1105 frag->patch = inflate_it(data, hunk_size, origlen);
1109 frag->size = origlen;
1113 frag->binary_patch_method = patch_method;
1120 error("corrupt binary patch at line %d: %.*s",
1121 linenr-1, llen-1, buffer);
1125 static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1127 /* We have read "GIT binary patch\n"; what follows is a line
1128 * that says the patch method (currently, either "literal" or
1129 * "delta") and the length of data before deflating; a
1130 * sequence of 'length-byte' followed by base-85 encoded data
1133 * When a binary patch is reversible, there is another binary
1134 * hunk in the same format, starting with patch method (either
1135 * "literal" or "delta") with the length of data, and a sequence
1136 * of length-byte + base-85 encoded data, terminated with another
1137 * empty line. This data, when applied to the postimage, produces
1140 struct fragment *forward;
1141 struct fragment *reverse;
1145 forward = parse_binary_hunk(&buffer, &size, &status, &used);
1146 if (!forward && !status)
1147 /* there has to be one hunk (forward hunk) */
1148 return error("unrecognized binary patch at line %d", linenr-1);
1150 /* otherwise we already gave an error message */
1153 reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1157 /* not having reverse hunk is not an error, but having
1158 * a corrupt reverse hunk is.
1160 free((void*) forward->patch);
1164 forward->next = reverse;
1165 patch->fragments = forward;
1166 patch->is_binary = 1;
1170 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
1172 int hdrsize, patchsize;
1173 int offset = find_header(buffer, size, &hdrsize, patch);
1178 patchsize = parse_single_patch(buffer + offset + hdrsize, size - offset - hdrsize, patch);
1181 static const char *binhdr[] = {
1186 static const char git_binary[] = "GIT binary patch\n";
1188 int hd = hdrsize + offset;
1189 unsigned long llen = linelen(buffer + hd, size - hd);
1191 if (llen == sizeof(git_binary) - 1 &&
1192 !memcmp(git_binary, buffer + hd, llen)) {
1195 used = parse_binary(buffer + hd + llen,
1196 size - hd - llen, patch);
1198 patchsize = used + llen;
1202 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
1203 for (i = 0; binhdr[i]; i++) {
1204 int len = strlen(binhdr[i]);
1205 if (len < size - hd &&
1206 !memcmp(binhdr[i], buffer + hd, len)) {
1208 patch->is_binary = 1;
1215 /* Empty patch cannot be applied if:
1216 * - it is a binary patch and we do not do binary_replace, or
1217 * - text patch without metadata change
1219 if ((apply || check) &&
1221 ? !allow_binary_replacement
1222 : !metadata_changes(patch)))
1223 die("patch with only garbage at line %d", linenr);
1226 return offset + hdrsize + patchsize;
1229 #define swap(a,b) myswap((a),(b),sizeof(a))
1231 #define myswap(a, b, size) do { \
1232 unsigned char mytmp[size]; \
1233 memcpy(mytmp, &a, size); \
1234 memcpy(&a, &b, size); \
1235 memcpy(&b, mytmp, size); \
1238 static void reverse_patches(struct patch *p)
1240 for (; p; p = p->next) {
1241 struct fragment *frag = p->fragments;
1243 swap(p->new_name, p->old_name);
1244 swap(p->new_mode, p->old_mode);
1245 swap(p->is_new, p->is_delete);
1246 swap(p->lines_added, p->lines_deleted);
1247 swap(p->old_sha1_prefix, p->new_sha1_prefix);
1249 for (; frag; frag = frag->next) {
1250 swap(frag->newpos, frag->oldpos);
1251 swap(frag->newlines, frag->oldlines);
1256 static const char pluses[] = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1257 static const char minuses[]= "----------------------------------------------------------------------";
1259 static void show_stats(struct patch *patch)
1261 const char *prefix = "";
1262 char *name = patch->new_name;
1264 int len, max, add, del, total;
1267 name = patch->old_name;
1269 if (0 < (len = quote_c_style(name, NULL, NULL, 0))) {
1270 qname = xmalloc(len + 1);
1271 quote_c_style(name, qname, NULL, 0);
1276 * "scale" the filename
1287 slash = strchr(name, '/');
1294 * scale the add/delete
1300 add = patch->lines_added;
1301 del = patch->lines_deleted;
1304 if (max_change > 0) {
1305 total = (total * max + max_change / 2) / max_change;
1306 add = (add * max + max_change / 2) / max_change;
1309 if (patch->is_binary)
1310 printf(" %s%-*s | Bin\n", prefix, len, name);
1312 printf(" %s%-*s |%5d %.*s%.*s\n", prefix,
1313 len, name, patch->lines_added + patch->lines_deleted,
1314 add, pluses, del, minuses);
1319 static int read_old_data(struct stat *st, const char *path, void *buf, unsigned long size)
1324 switch (st->st_mode & S_IFMT) {
1326 return readlink(path, buf, size);
1328 fd = open(path, O_RDONLY);
1330 return error("unable to open %s", path);
1333 int ret = xread(fd, (char *) buf + got, size - got);
1346 static int find_offset(const char *buf, unsigned long size, const char *fragment, unsigned long fragsize, int line, int *lines)
1349 unsigned long start, backwards, forwards;
1351 if (fragsize > size)
1356 unsigned long offset = 0;
1358 while (offset + fragsize <= size) {
1359 if (buf[offset++] == '\n') {
1367 /* Exact line number? */
1368 if (!memcmp(buf + start, fragment, fragsize))
1372 * There's probably some smart way to do this, but I'll leave
1373 * that to the smart and beautiful people. I'm simple and stupid.
1377 for (i = 0; ; i++) {
1384 if (forwards + fragsize > size)
1390 } while (backwards && buf[backwards-1] != '\n');
1393 while (forwards + fragsize <= size) {
1394 if (buf[forwards++] == '\n')
1400 if (try + fragsize > size)
1402 if (memcmp(buf + try, fragment, fragsize))
1412 * We should start searching forward and backward.
1417 static void remove_first_line(const char **rbuf, int *rsize)
1419 const char *buf = *rbuf;
1421 unsigned long offset;
1423 while (offset <= size) {
1424 if (buf[offset++] == '\n')
1427 *rsize = size - offset;
1428 *rbuf = buf + offset;
1431 static void remove_last_line(const char **rbuf, int *rsize)
1433 const char *buf = *rbuf;
1435 unsigned long offset;
1437 while (offset > 0) {
1438 if (buf[--offset] == '\n')
1441 *rsize = offset + 1;
1444 struct buffer_desc {
1447 unsigned long alloc;
1450 static int apply_line(char *output, const char *patch, int plen)
1452 /* plen is number of bytes to be copied from patch,
1453 * starting at patch+1 (patch[0] is '+'). Typically
1454 * patch[plen] is '\n'.
1456 int add_nl_to_tail = 0;
1457 if ((new_whitespace == strip_whitespace) &&
1458 1 < plen && isspace(patch[plen-1])) {
1459 if (patch[plen] == '\n')
1462 while (0 < plen && isspace(patch[plen]))
1464 applied_after_stripping++;
1466 memcpy(output, patch + 1, plen);
1468 output[plen++] = '\n';
1472 static int apply_one_fragment(struct buffer_desc *desc, struct fragment *frag, int inaccurate_eof)
1474 int match_beginning, match_end;
1475 char *buf = desc->buffer;
1476 const char *patch = frag->patch;
1477 int offset, size = frag->size;
1478 char *old = xmalloc(size);
1479 char *new = xmalloc(size);
1480 const char *oldlines, *newlines;
1481 int oldsize = 0, newsize = 0;
1482 unsigned long leading, trailing;
1487 int len = linelen(patch, size);
1494 * "plen" is how much of the line we should use for
1495 * the actual patch data. Normally we just remove the
1496 * first character on the line, but if the line is
1497 * followed by "\ No newline", then we also remove the
1498 * last one (which is the newline, of course).
1501 if (len < size && patch[len] == '\\')
1504 if (apply_in_reverse) {
1507 else if (first == '+')
1513 memcpy(old + oldsize, patch + 1, plen);
1517 /* Fall-through for ' ' */
1519 if (first != '+' || !no_add)
1520 newsize += apply_line(new + newsize, patch,
1523 case '@': case '\\':
1524 /* Ignore it, we already handled it */
1533 if (inaccurate_eof && oldsize > 0 && old[oldsize - 1] == '\n' &&
1534 newsize > 0 && new[newsize - 1] == '\n') {
1541 leading = frag->leading;
1542 trailing = frag->trailing;
1545 * If we don't have any leading/trailing data in the patch,
1546 * we want it to match at the beginning/end of the file.
1548 match_beginning = !leading && (frag->oldpos == 1);
1549 match_end = !trailing;
1554 offset = find_offset(buf, desc->size,
1555 oldlines, oldsize, pos, &lines);
1556 if (match_end && offset + oldsize != desc->size)
1558 if (match_beginning && offset)
1561 int diff = newsize - oldsize;
1562 unsigned long size = desc->size + diff;
1563 unsigned long alloc = desc->alloc;
1565 /* Warn if it was necessary to reduce the number
1568 if ((leading != frag->leading) ||
1569 (trailing != frag->trailing))
1570 fprintf(stderr, "Context reduced to (%ld/%ld)"
1571 " to apply fragment at %d\n",
1572 leading, trailing, pos + lines);
1575 alloc = size + 8192;
1576 desc->alloc = alloc;
1577 buf = xrealloc(buf, alloc);
1581 memmove(buf + offset + newsize,
1582 buf + offset + oldsize,
1583 size - offset - newsize);
1584 memcpy(buf + offset, newlines, newsize);
1590 /* Am I at my context limits? */
1591 if ((leading <= p_context) && (trailing <= p_context))
1593 if (match_beginning || match_end) {
1594 match_beginning = match_end = 0;
1597 /* Reduce the number of context lines
1598 * Reduce both leading and trailing if they are equal
1599 * otherwise just reduce the larger context.
1601 if (leading >= trailing) {
1602 remove_first_line(&oldlines, &oldsize);
1603 remove_first_line(&newlines, &newsize);
1607 if (trailing > leading) {
1608 remove_last_line(&oldlines, &oldsize);
1609 remove_last_line(&newlines, &newsize);
1619 static int apply_binary_fragment(struct buffer_desc *desc, struct patch *patch)
1621 unsigned long dst_size;
1622 struct fragment *fragment = patch->fragments;
1626 /* Binary patch is irreversible without the optional second hunk */
1627 if (apply_in_reverse) {
1628 if (!fragment->next)
1629 return error("cannot reverse-apply a binary patch "
1630 "without the reverse hunk to '%s'",
1632 ? patch->new_name : patch->old_name);
1633 fragment = fragment->next;
1635 data = (void*) fragment->patch;
1636 switch (fragment->binary_patch_method) {
1637 case BINARY_DELTA_DEFLATED:
1638 result = patch_delta(desc->buffer, desc->size,
1643 desc->buffer = result;
1645 case BINARY_LITERAL_DEFLATED:
1647 desc->buffer = data;
1648 dst_size = fragment->size;
1653 desc->size = desc->alloc = dst_size;
1657 static int apply_binary(struct buffer_desc *desc, struct patch *patch)
1659 const char *name = patch->old_name ? patch->old_name : patch->new_name;
1660 unsigned char sha1[20];
1661 unsigned char hdr[50];
1664 if (!allow_binary_replacement)
1665 return error("cannot apply binary patch to '%s' "
1666 "without --allow-binary-replacement",
1669 /* For safety, we require patch index line to contain
1670 * full 40-byte textual SHA1 for old and new, at least for now.
1672 if (strlen(patch->old_sha1_prefix) != 40 ||
1673 strlen(patch->new_sha1_prefix) != 40 ||
1674 get_sha1_hex(patch->old_sha1_prefix, sha1) ||
1675 get_sha1_hex(patch->new_sha1_prefix, sha1))
1676 return error("cannot apply binary patch to '%s' "
1677 "without full index line", name);
1679 if (patch->old_name) {
1680 /* See if the old one matches what the patch
1683 write_sha1_file_prepare(desc->buffer, desc->size,
1684 blob_type, sha1, hdr, &hdrlen);
1685 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
1686 return error("the patch applies to '%s' (%s), "
1687 "which does not match the "
1688 "current contents.",
1689 name, sha1_to_hex(sha1));
1692 /* Otherwise, the old one must be empty. */
1694 return error("the patch applies to an empty "
1695 "'%s' but it is not empty", name);
1698 get_sha1_hex(patch->new_sha1_prefix, sha1);
1699 if (is_null_sha1(sha1)) {
1701 desc->alloc = desc->size = 0;
1702 desc->buffer = NULL;
1703 return 0; /* deletion patch */
1706 if (has_sha1_file(sha1)) {
1707 /* We already have the postimage */
1712 desc->buffer = read_sha1_file(sha1, type, &size);
1714 return error("the necessary postimage %s for "
1715 "'%s' cannot be read",
1716 patch->new_sha1_prefix, name);
1717 desc->alloc = desc->size = size;
1720 /* We have verified desc matches the preimage;
1721 * apply the patch data to it, which is stored
1722 * in the patch->fragments->{patch,size}.
1724 if (apply_binary_fragment(desc, patch))
1725 return error("binary patch does not apply to '%s'",
1728 /* verify that the result matches */
1729 write_sha1_file_prepare(desc->buffer, desc->size, blob_type,
1730 sha1, hdr, &hdrlen);
1731 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
1732 return error("binary patch to '%s' creates incorrect result (expecting %s, got %s)", name, patch->new_sha1_prefix, sha1_to_hex(sha1));
1738 static int apply_fragments(struct buffer_desc *desc, struct patch *patch)
1740 struct fragment *frag = patch->fragments;
1741 const char *name = patch->old_name ? patch->old_name : patch->new_name;
1743 if (patch->is_binary)
1744 return apply_binary(desc, patch);
1747 if (apply_one_fragment(desc, frag, patch->inaccurate_eof)) {
1748 error("patch failed: %s:%ld", name, frag->oldpos);
1749 if (!apply_with_reject)
1758 static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce)
1761 unsigned long size, alloc;
1762 struct buffer_desc desc;
1770 buf = read_sha1_file(ce->sha1, type, &size);
1772 return error("read of %s failed",
1777 else if (patch->old_name) {
1779 alloc = size + 8192;
1780 buf = xmalloc(alloc);
1781 if (read_old_data(st, patch->old_name, buf, alloc) != size)
1782 return error("read of %s failed", patch->old_name);
1789 if (apply_fragments(&desc, patch) < 0)
1790 return -1; /* note with --reject this succeeds. */
1792 /* NUL terminate the result */
1793 if (desc.alloc <= desc.size)
1794 desc.buffer = xrealloc(desc.buffer, desc.size + 1);
1795 desc.buffer[desc.size] = 0;
1797 patch->result = desc.buffer;
1798 patch->resultsize = desc.size;
1800 if (patch->is_delete && patch->resultsize)
1801 return error("removal patch leaves file contents");
1806 static int check_patch(struct patch *patch, struct patch *prev_patch)
1809 const char *old_name = patch->old_name;
1810 const char *new_name = patch->new_name;
1811 const char *name = old_name ? old_name : new_name;
1812 struct cache_entry *ce = NULL;
1815 patch->rejected = 1; /* we will drop this after we succeed */
1819 unsigned st_mode = 0;
1822 stat_ret = lstat(old_name, &st);
1824 int pos = cache_name_pos(old_name, strlen(old_name));
1826 return error("%s: does not exist in index",
1828 ce = active_cache[pos];
1830 struct checkout costate;
1831 if (errno != ENOENT)
1832 return error("%s: %s", old_name,
1835 costate.base_dir = "";
1836 costate.base_dir_len = 0;
1839 costate.not_new = 0;
1840 costate.refresh_cache = 1;
1841 if (checkout_entry(ce,
1844 lstat(old_name, &st))
1848 changed = ce_match_stat(ce, &st, 1);
1850 return error("%s: does not match index",
1853 st_mode = ntohl(ce->ce_mode);
1855 else if (stat_ret < 0)
1856 return error("%s: %s", old_name, strerror(errno));
1859 st_mode = ntohl(create_ce_mode(st.st_mode));
1861 if (patch->is_new < 0)
1863 if (!patch->old_mode)
1864 patch->old_mode = st_mode;
1865 if ((st_mode ^ patch->old_mode) & S_IFMT)
1866 return error("%s: wrong type", old_name);
1867 if (st_mode != patch->old_mode)
1868 fprintf(stderr, "warning: %s has type %o, expected %o\n",
1869 old_name, st_mode, patch->old_mode);
1872 if (new_name && prev_patch && prev_patch->is_delete &&
1873 !strcmp(prev_patch->old_name, new_name))
1874 /* A type-change diff is always split into a patch to
1875 * delete old, immediately followed by a patch to
1876 * create new (see diff.c::run_diff()); in such a case
1877 * it is Ok that the entry to be deleted by the
1878 * previous patch is still in the working tree and in
1885 if (new_name && (patch->is_new | patch->is_rename | patch->is_copy)) {
1887 cache_name_pos(new_name, strlen(new_name)) >= 0 &&
1889 return error("%s: already exists in index", new_name);
1892 if (!lstat(new_name, &nst)) {
1893 if (S_ISDIR(nst.st_mode) || ok_if_exists)
1896 return error("%s: already exists in working directory", new_name);
1898 else if ((errno != ENOENT) && (errno != ENOTDIR))
1899 return error("%s: %s", new_name, strerror(errno));
1901 if (!patch->new_mode) {
1903 patch->new_mode = S_IFREG | 0644;
1905 patch->new_mode = patch->old_mode;
1909 if (new_name && old_name) {
1910 int same = !strcmp(old_name, new_name);
1911 if (!patch->new_mode)
1912 patch->new_mode = patch->old_mode;
1913 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
1914 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
1915 patch->new_mode, new_name, patch->old_mode,
1916 same ? "" : " of ", same ? "" : old_name);
1919 if (apply_data(patch, &st, ce) < 0)
1920 return error("%s: patch does not apply", name);
1921 patch->rejected = 0;
1925 static int check_patch_list(struct patch *patch)
1927 struct patch *prev_patch = NULL;
1930 for (prev_patch = NULL; patch ; patch = patch->next) {
1931 error |= check_patch(patch, prev_patch);
1937 static void show_index_list(struct patch *list)
1939 struct patch *patch;
1941 /* Once we start supporting the reverse patch, it may be
1942 * worth showing the new sha1 prefix, but until then...
1944 for (patch = list; patch; patch = patch->next) {
1945 const unsigned char *sha1_ptr;
1946 unsigned char sha1[20];
1949 name = patch->old_name ? patch->old_name : patch->new_name;
1951 sha1_ptr = null_sha1;
1952 else if (get_sha1(patch->old_sha1_prefix, sha1))
1953 die("sha1 information is lacking or useless (%s).",
1958 printf("%06o %s ",patch->old_mode, sha1_to_hex(sha1_ptr));
1959 if (line_termination && quote_c_style(name, NULL, NULL, 0))
1960 quote_c_style(name, NULL, stdout, 0);
1962 fputs(name, stdout);
1963 putchar(line_termination);
1967 static void stat_patch_list(struct patch *patch)
1969 int files, adds, dels;
1971 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
1973 adds += patch->lines_added;
1974 dels += patch->lines_deleted;
1978 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
1981 static void numstat_patch_list(struct patch *patch)
1983 for ( ; patch; patch = patch->next) {
1985 name = patch->new_name ? patch->new_name : patch->old_name;
1986 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
1987 if (line_termination && quote_c_style(name, NULL, NULL, 0))
1988 quote_c_style(name, NULL, stdout, 0);
1990 fputs(name, stdout);
1995 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
1998 printf(" %s mode %06o %s\n", newdelete, mode, name);
2000 printf(" %s %s\n", newdelete, name);
2003 static void show_mode_change(struct patch *p, int show_name)
2005 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
2007 printf(" mode change %06o => %06o %s\n",
2008 p->old_mode, p->new_mode, p->new_name);
2010 printf(" mode change %06o => %06o\n",
2011 p->old_mode, p->new_mode);
2015 static void show_rename_copy(struct patch *p)
2017 const char *renamecopy = p->is_rename ? "rename" : "copy";
2018 const char *old, *new;
2020 /* Find common prefix */
2024 const char *slash_old, *slash_new;
2025 slash_old = strchr(old, '/');
2026 slash_new = strchr(new, '/');
2029 slash_old - old != slash_new - new ||
2030 memcmp(old, new, slash_new - new))
2032 old = slash_old + 1;
2033 new = slash_new + 1;
2035 /* p->old_name thru old is the common prefix, and old and new
2036 * through the end of names are renames
2038 if (old != p->old_name)
2039 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
2040 (int)(old - p->old_name), p->old_name,
2041 old, new, p->score);
2043 printf(" %s %s => %s (%d%%)\n", renamecopy,
2044 p->old_name, p->new_name, p->score);
2045 show_mode_change(p, 0);
2048 static void summary_patch_list(struct patch *patch)
2052 for (p = patch; p; p = p->next) {
2054 show_file_mode_name("create", p->new_mode, p->new_name);
2055 else if (p->is_delete)
2056 show_file_mode_name("delete", p->old_mode, p->old_name);
2058 if (p->is_rename || p->is_copy)
2059 show_rename_copy(p);
2062 printf(" rewrite %s (%d%%)\n",
2063 p->new_name, p->score);
2064 show_mode_change(p, 0);
2067 show_mode_change(p, 1);
2073 static void patch_stats(struct patch *patch)
2075 int lines = patch->lines_added + patch->lines_deleted;
2077 if (lines > max_change)
2079 if (patch->old_name) {
2080 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
2082 len = strlen(patch->old_name);
2086 if (patch->new_name) {
2087 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
2089 len = strlen(patch->new_name);
2095 static void remove_file(struct patch *patch)
2098 if (remove_file_from_cache(patch->old_name) < 0)
2099 die("unable to remove %s from index", patch->old_name);
2100 cache_tree_invalidate_path(active_cache_tree, patch->old_name);
2103 unlink(patch->old_name);
2106 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
2109 struct cache_entry *ce;
2110 int namelen = strlen(path);
2111 unsigned ce_size = cache_entry_size(namelen);
2116 ce = xcalloc(1, ce_size);
2117 memcpy(ce->name, path, namelen);
2118 ce->ce_mode = create_ce_mode(mode);
2119 ce->ce_flags = htons(namelen);
2121 if (lstat(path, &st) < 0)
2122 die("unable to stat newly created file %s", path);
2123 fill_stat_cache_info(ce, &st);
2125 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
2126 die("unable to create backing store for newly created file %s", path);
2127 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
2128 die("unable to add cache entry for %s", path);
2131 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
2136 /* Although buf:size is counted string, it also is NUL
2139 return symlink(buf, path);
2140 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
2144 int written = xwrite(fd, buf, size);
2146 die("writing file %s: %s", path, strerror(errno));
2148 die("out of space writing file %s", path);
2153 die("closing file %s: %s", path, strerror(errno));
2158 * We optimistically assume that the directories exist,
2159 * which is true 99% of the time anyway. If they don't,
2160 * we create them and try again.
2162 static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
2166 if (!try_create_file(path, mode, buf, size))
2169 if (errno == ENOENT) {
2170 if (safe_create_leading_directories(path))
2172 if (!try_create_file(path, mode, buf, size))
2176 if (errno == EEXIST || errno == EACCES) {
2177 /* We may be trying to create a file where a directory
2182 if (!lstat(path, &st) && S_ISDIR(st.st_mode) && !rmdir(path))
2186 if (errno == EEXIST) {
2187 unsigned int nr = getpid();
2190 const char *newpath;
2191 newpath = mkpath("%s~%u", path, nr);
2192 if (!try_create_file(newpath, mode, buf, size)) {
2193 if (!rename(newpath, path))
2198 if (errno != EEXIST)
2203 die("unable to write file %s mode %o", path, mode);
2206 static void create_file(struct patch *patch)
2208 char *path = patch->new_name;
2209 unsigned mode = patch->new_mode;
2210 unsigned long size = patch->resultsize;
2211 char *buf = patch->result;
2214 mode = S_IFREG | 0644;
2215 create_one_file(path, mode, buf, size);
2216 add_index_file(path, mode, buf, size);
2217 cache_tree_invalidate_path(active_cache_tree, path);
2220 /* phase zero is to remove, phase one is to create */
2221 static void write_out_one_result(struct patch *patch, int phase)
2223 if (patch->is_delete > 0) {
2228 if (patch->is_new > 0 || patch->is_copy) {
2234 * Rename or modification boils down to the same
2235 * thing: remove the old, write the new
2243 static int write_out_one_reject(struct patch *patch)
2245 struct fragment *frag;
2248 for (rejects = 0, frag = patch->fragments; frag; frag = frag->next) {
2249 if (!frag->rejected)
2253 printf("** Rejected hunk(s) for ");
2254 if (patch->old_name && patch->new_name &&
2255 strcmp(patch->old_name, patch->new_name)) {
2256 write_name_quoted(NULL, 0,
2257 patch->old_name, 1, stdout);
2258 fputs(" => ", stdout);
2259 write_name_quoted(NULL, 0,
2260 patch->new_name, 1, stdout);
2263 const char *n = patch->new_name;
2265 n = patch->old_name;
2266 write_name_quoted(NULL, 0, n, 1, stdout);
2270 printf("%.*s", frag->size, frag->patch);
2271 if (frag->patch[frag->size-1] != '\n')
2277 static int write_out_results(struct patch *list, int skipped_patch)
2283 if (!list && !skipped_patch)
2284 return error("No changes");
2286 for (phase = 0; phase < 2; phase++) {
2292 write_out_one_result(l, phase);
2296 if (apply_with_reject) {
2300 if (write_out_one_reject(l))
2309 static struct lock_file lock_file;
2311 static struct excludes {
2312 struct excludes *next;
2316 static int use_patch(struct patch *p)
2318 const char *pathname = p->new_name ? p->new_name : p->old_name;
2319 struct excludes *x = excludes;
2321 if (fnmatch(x->path, pathname, 0) == 0)
2325 if (0 < prefix_length) {
2326 int pathlen = strlen(pathname);
2327 if (pathlen <= prefix_length ||
2328 memcmp(prefix, pathname, prefix_length))
2334 static int apply_patch(int fd, const char *filename, int inaccurate_eof)
2336 unsigned long offset, size;
2337 char *buffer = read_patch_file(fd, &size);
2338 struct patch *list = NULL, **listp = &list;
2339 int skipped_patch = 0;
2341 patch_input_file = filename;
2346 struct patch *patch;
2349 patch = xcalloc(1, sizeof(*patch));
2350 patch->inaccurate_eof = inaccurate_eof;
2351 nr = parse_chunk(buffer + offset, size, patch);
2354 if (apply_in_reverse)
2355 reverse_patches(patch);
2356 if (use_patch(patch)) {
2359 listp = &patch->next;
2361 /* perhaps free it a bit better? */
2369 if (whitespace_error && (new_whitespace == error_on_whitespace))
2372 write_index = check_index && apply;
2373 if (write_index && newfd < 0)
2374 newfd = hold_lock_file_for_update(&lock_file,
2375 get_index_file(), 1);
2377 if (read_cache() < 0)
2378 die("unable to read index file");
2381 if ((check || apply) &&
2382 check_patch_list(list) < 0 &&
2386 if (apply && write_out_results(list, skipped_patch))
2389 if (show_index_info)
2390 show_index_list(list);
2393 stat_patch_list(list);
2396 numstat_patch_list(list);
2399 summary_patch_list(list);
2405 static int git_apply_config(const char *var, const char *value)
2407 if (!strcmp(var, "apply.whitespace")) {
2408 apply_default_whitespace = strdup(value);
2411 return git_default_config(var, value);
2415 int cmd_apply(int argc, const char **argv, const char *prefix)
2419 int inaccurate_eof = 0;
2422 const char *whitespace_option = NULL;
2424 for (i = 1; i < argc; i++) {
2425 const char *arg = argv[i];
2429 if (!strcmp(arg, "-")) {
2430 errs |= apply_patch(0, "<stdin>", inaccurate_eof);
2434 if (!strncmp(arg, "--exclude=", 10)) {
2435 struct excludes *x = xmalloc(sizeof(*x));
2441 if (!strncmp(arg, "-p", 2)) {
2442 p_value = atoi(arg + 2);
2445 if (!strcmp(arg, "--no-add")) {
2449 if (!strcmp(arg, "--stat")) {
2454 if (!strcmp(arg, "--allow-binary-replacement") ||
2455 !strcmp(arg, "--binary")) {
2456 allow_binary_replacement = 1;
2459 if (!strcmp(arg, "--numstat")) {
2464 if (!strcmp(arg, "--summary")) {
2469 if (!strcmp(arg, "--check")) {
2474 if (!strcmp(arg, "--index")) {
2478 if (!strcmp(arg, "--cached")) {
2483 if (!strcmp(arg, "--apply")) {
2487 if (!strcmp(arg, "--index-info")) {
2489 show_index_info = 1;
2492 if (!strcmp(arg, "-z")) {
2493 line_termination = 0;
2496 if (!strncmp(arg, "-C", 2)) {
2497 p_context = strtoul(arg + 2, &end, 0);
2499 die("unrecognized context count '%s'", arg + 2);
2502 if (!strncmp(arg, "--whitespace=", 13)) {
2503 whitespace_option = arg + 13;
2504 parse_whitespace_option(arg + 13);
2507 if (!strcmp(arg, "-R") || !strcmp(arg, "--reverse")) {
2508 apply_in_reverse = 1;
2511 if (!strcmp(arg, "--reject")) {
2512 apply = apply_with_reject = 1;
2515 if (!strcmp(arg, "--inaccurate-eof")) {
2520 if (check_index && prefix_length < 0) {
2521 prefix = setup_git_directory();
2522 prefix_length = prefix ? strlen(prefix) : 0;
2523 git_config(git_apply_config);
2524 if (!whitespace_option && apply_default_whitespace)
2525 parse_whitespace_option(apply_default_whitespace);
2527 if (0 < prefix_length)
2528 arg = prefix_filename(prefix, prefix_length, arg);
2530 fd = open(arg, O_RDONLY);
2534 set_default_whitespace_mode(whitespace_option);
2535 errs |= apply_patch(fd, arg, inaccurate_eof);
2538 set_default_whitespace_mode(whitespace_option);
2540 errs |= apply_patch(0, "<stdin>", inaccurate_eof);
2541 if (whitespace_error) {
2542 if (squelch_whitespace_errors &&
2543 squelch_whitespace_errors < whitespace_error) {
2545 whitespace_error - squelch_whitespace_errors;
2546 fprintf(stderr, "warning: squelched %d "
2547 "whitespace error%s\n",
2549 squelched == 1 ? "" : "s");
2551 if (new_whitespace == error_on_whitespace)
2552 die("%d line%s add%s trailing whitespaces.",
2554 whitespace_error == 1 ? "" : "s",
2555 whitespace_error == 1 ? "s" : "");
2556 if (applied_after_stripping)
2557 fprintf(stderr, "warning: %d line%s applied after"
2558 " stripping trailing whitespaces.\n",
2559 applied_after_stripping,
2560 applied_after_stripping == 1 ? "" : "s");
2561 else if (whitespace_error)
2562 fprintf(stderr, "warning: %d line%s add%s trailing"
2565 whitespace_error == 1 ? "" : "s",
2566 whitespace_error == 1 ? "s" : "");
2570 if (write_cache(newfd, active_cache, active_nr) ||
2571 close(newfd) || commit_lock_file(&lock_file))
2572 die("Unable to write new index file");