4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
10 #include "cache-tree.h"
15 #include "string-list.h"
17 #include "parse-options.h"
20 * --check turns on checking that the working tree matches the
21 * files that are being modified, but doesn't apply the patch
22 * --stat does just a diffstat, and doesn't actually apply
23 * --numstat does numeric diffstat, and doesn't actually apply
24 * --index-info shows the old and new index info for paths if available.
25 * --index updates the cache as well.
26 * --cached updates only the cache without ever touching the working tree.
28 static const char *prefix;
29 static int prefix_length = -1;
30 static int newfd = -1;
32 static int unidiff_zero;
33 static int p_value = 1;
34 static int p_value_known;
35 static int check_index;
36 static int update_index;
43 static int apply_in_reverse;
44 static int apply_with_reject;
45 static int apply_verbosely;
47 static const char *fake_ancestor;
48 static int line_termination = '\n';
49 static unsigned int p_context = UINT_MAX;
50 static const char * const apply_usage[] = {
51 "git apply [options] [<patch>...]",
55 static enum ws_error_action {
60 } ws_error_action = warn_on_ws_error;
61 static int whitespace_error;
62 static int squelch_whitespace_errors = 5;
63 static int applied_after_fixing_ws;
65 static enum ws_ignore {
68 } ws_ignore_action = ignore_ws_none;
71 static const char *patch_input_file;
72 static const char *root;
74 static int read_stdin = 1;
77 static void parse_whitespace_option(const char *option)
80 ws_error_action = warn_on_ws_error;
83 if (!strcmp(option, "warn")) {
84 ws_error_action = warn_on_ws_error;
87 if (!strcmp(option, "nowarn")) {
88 ws_error_action = nowarn_ws_error;
91 if (!strcmp(option, "error")) {
92 ws_error_action = die_on_ws_error;
95 if (!strcmp(option, "error-all")) {
96 ws_error_action = die_on_ws_error;
97 squelch_whitespace_errors = 0;
100 if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
101 ws_error_action = correct_ws_error;
104 die("unrecognized whitespace option '%s'", option);
107 static void parse_ignorewhitespace_option(const char *option)
109 if (!option || !strcmp(option, "no") ||
110 !strcmp(option, "false") || !strcmp(option, "never") ||
111 !strcmp(option, "none")) {
112 ws_ignore_action = ignore_ws_none;
115 if (!strcmp(option, "change")) {
116 ws_ignore_action = ignore_ws_change;
119 die("unrecognized whitespace ignore option '%s'", option);
122 static void set_default_whitespace_mode(const char *whitespace_option)
124 if (!whitespace_option && !apply_default_whitespace)
125 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error);
129 * For "diff-stat" like behaviour, we keep track of the biggest change
130 * we've seen, and the longest filename. That allows us to do simple
133 static int max_change, max_len;
136 * Various "current state", notably line numbers and what
137 * file (and how) we're patching right now.. The "is_xxxx"
138 * things are flags, where -1 means "don't know yet".
140 static int linenr = 1;
143 * This represents one "hunk" from a patch, starting with
144 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
145 * patch text is pointed at by patch, and its byte length
146 * is stored in size. leading and trailing are the number
150 unsigned long leading, trailing;
151 unsigned long oldpos, oldlines;
152 unsigned long newpos, newlines;
157 struct fragment *next;
161 * When dealing with a binary patch, we reuse "leading" field
162 * to store the type of the binary hunk, either deflated "delta"
163 * or deflated "literal".
165 #define binary_patch_method leading
166 #define BINARY_DELTA_DEFLATED 1
167 #define BINARY_LITERAL_DEFLATED 2
170 * This represents a "patch" to a file, both metainfo changes
171 * such as creation/deletion, filemode and content changes represented
172 * as a series of fragments.
175 char *new_name, *old_name, *def_name;
176 unsigned int old_mode, new_mode;
177 int is_new, is_delete; /* -1 = unknown, 0 = false, 1 = true */
180 unsigned long deflate_origlen;
181 int lines_added, lines_deleted;
183 unsigned int is_toplevel_relative:1;
184 unsigned int inaccurate_eof:1;
185 unsigned int is_binary:1;
186 unsigned int is_copy:1;
187 unsigned int is_rename:1;
188 unsigned int recount:1;
189 struct fragment *fragments;
192 char old_sha1_prefix[41];
193 char new_sha1_prefix[41];
198 * A line in a file, len-bytes long (includes the terminating LF,
199 * except for an incomplete line at the end if the file ends with
200 * one), and its contents hashes to 'hash'.
206 #define LINE_COMMON 1
210 * This represents a "file", which is an array of "lines".
217 struct line *line_allocated;
222 * Records filenames that have been touched, in order to handle
223 * the case where more than one patches touch the same file.
226 static struct string_list fn_table;
228 static uint32_t hash_line(const char *cp, size_t len)
232 for (i = 0, h = 0; i < len; i++) {
233 if (!isspace(cp[i])) {
234 h = h * 3 + (cp[i] & 0xff);
241 * Compare lines s1 of length n1 and s2 of length n2, ignoring
242 * whitespace difference. Returns 1 if they match, 0 otherwise
244 static int fuzzy_matchlines(const char *s1, size_t n1,
245 const char *s2, size_t n2)
247 const char *last1 = s1 + n1 - 1;
248 const char *last2 = s2 + n2 - 1;
251 if (n1 < 0 || n2 < 0)
254 /* ignore line endings */
255 while ((*last1 == '\r') || (*last1 == '\n'))
257 while ((*last2 == '\r') || (*last2 == '\n'))
260 /* skip leading whitespace */
261 while (isspace(*s1) && (s1 <= last1))
263 while (isspace(*s2) && (s2 <= last2))
265 /* early return if both lines are empty */
266 if ((s1 > last1) && (s2 > last2))
269 result = *s1++ - *s2++;
271 * Skip whitespace inside. We check for whitespace on
272 * both buffers because we don't want "a b" to match
275 if (isspace(*s1) && isspace(*s2)) {
276 while (isspace(*s1) && s1 <= last1)
278 while (isspace(*s2) && s2 <= last2)
282 * If we reached the end on one side only,
286 ((s2 > last2) && (s1 <= last1)) ||
287 ((s1 > last1) && (s2 <= last2)))
289 if ((s1 > last1) && (s2 > last2))
296 static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
298 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
299 img->line_allocated[img->nr].len = len;
300 img->line_allocated[img->nr].hash = hash_line(bol, len);
301 img->line_allocated[img->nr].flag = flag;
305 static void prepare_image(struct image *image, char *buf, size_t len,
306 int prepare_linetable)
310 memset(image, 0, sizeof(*image));
314 if (!prepare_linetable)
317 ep = image->buf + image->len;
321 for (next = cp; next < ep && *next != '\n'; next++)
325 add_line_info(image, cp, next - cp, 0);
328 image->line = image->line_allocated;
331 static void clear_image(struct image *image)
338 static void say_patch_name(FILE *output, const char *pre,
339 struct patch *patch, const char *post)
342 if (patch->old_name && patch->new_name &&
343 strcmp(patch->old_name, patch->new_name)) {
344 quote_c_style(patch->old_name, NULL, output, 0);
345 fputs(" => ", output);
346 quote_c_style(patch->new_name, NULL, output, 0);
348 const char *n = patch->new_name;
351 quote_c_style(n, NULL, output, 0);
356 #define CHUNKSIZE (8192)
359 static void read_patch_file(struct strbuf *sb, int fd)
361 if (strbuf_read(sb, fd, 0) < 0)
362 die_errno("git apply: failed to read");
365 * Make sure that we have some slop in the buffer
366 * so that we can do speculative "memcmp" etc, and
367 * see to it that it is NUL-filled.
369 strbuf_grow(sb, SLOP);
370 memset(sb->buf + sb->len, 0, SLOP);
373 static unsigned long linelen(const char *buffer, unsigned long size)
375 unsigned long len = 0;
378 if (*buffer++ == '\n')
384 static int is_dev_null(const char *str)
386 return !memcmp("/dev/null", str, 9) && isspace(str[9]);
392 static int name_terminate(const char *name, int namelen, int c, int terminate)
394 if (c == ' ' && !(terminate & TERM_SPACE))
396 if (c == '\t' && !(terminate & TERM_TAB))
402 /* remove double slashes to make --index work with such filenames */
403 static char *squash_slash(char *name)
411 if ((name[j++] = name[i++]) == '/')
412 while (name[i] == '/')
419 static char *find_name_gnu(const char *line, char *def, int p_value)
421 struct strbuf name = STRBUF_INIT;
425 * Proposed "new-style" GNU patch/diff format; see
426 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
428 if (unquote_c_style(&name, line, NULL)) {
429 strbuf_release(&name);
433 for (cp = name.buf; p_value; p_value--) {
434 cp = strchr(cp, '/');
436 strbuf_release(&name);
442 /* name can later be freed, so we need
443 * to memmove, not just return cp
445 strbuf_remove(&name, 0, cp - name.buf);
448 strbuf_insert(&name, 0, root, root_len);
449 return squash_slash(strbuf_detach(&name, NULL));
452 static char *find_name(const char *line, char *def, int p_value, int terminate)
455 const char *start = NULL;
458 char *name = find_name_gnu(line, def, p_value);
471 if (name_terminate(start, line-start, c, terminate))
475 if (c == '/' && !--p_value)
479 return squash_slash(def);
482 return squash_slash(def);
485 * Generally we prefer the shorter name, especially
486 * if the other one is just a variation of that with
487 * something else tacked on to the end (ie "file.orig"
491 int deflen = strlen(def);
492 if (deflen < len && !strncmp(start, def, deflen))
493 return squash_slash(def);
498 char *ret = xmalloc(root_len + len + 1);
500 memcpy(ret + root_len, start, len);
501 ret[root_len + len] = '\0';
502 return squash_slash(ret);
505 return squash_slash(xmemdupz(start, len));
508 static int count_slashes(const char *cp)
520 * Given the string after "--- " or "+++ ", guess the appropriate
521 * p_value for the given patch.
523 static int guess_p_value(const char *nameline)
528 if (is_dev_null(nameline))
530 name = find_name(nameline, NULL, 0, TERM_SPACE | TERM_TAB);
533 cp = strchr(name, '/');
538 * Does it begin with "a/$our-prefix" and such? Then this is
539 * very likely to apply to our directory.
541 if (!strncmp(name, prefix, prefix_length))
542 val = count_slashes(prefix);
545 if (!strncmp(cp, prefix, prefix_length))
546 val = count_slashes(prefix) + 1;
554 * Does the ---/+++ line has the POSIX timestamp after the last HT?
555 * GNU diff puts epoch there to signal a creation/deletion event. Is
556 * this such a timestamp?
558 static int has_epoch_timestamp(const char *nameline)
561 * We are only interested in epoch timestamp; any non-zero
562 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
563 * For the same reason, the date must be either 1969-12-31 or
564 * 1970-01-01, and the seconds part must be "00".
566 const char stamp_regexp[] =
567 "^(1969-12-31|1970-01-01)"
569 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
571 "([-+][0-2][0-9][0-5][0-9])\n";
572 const char *timestamp = NULL, *cp;
573 static regex_t *stamp;
579 for (cp = nameline; *cp != '\n'; cp++) {
586 stamp = xmalloc(sizeof(*stamp));
587 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
588 warning("Cannot prepare timestamp regexp %s",
594 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
596 if (status != REG_NOMATCH)
597 warning("regexec returned %d for input: %s",
602 zoneoffset = strtol(timestamp + m[3].rm_so + 1, NULL, 10);
603 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
604 if (timestamp[m[3].rm_so] == '-')
605 zoneoffset = -zoneoffset;
608 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
609 * (west of GMT) or 1970-01-01 (east of GMT)
611 if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) ||
612 (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10)))
615 hourminute = (strtol(timestamp + 11, NULL, 10) * 60 +
616 strtol(timestamp + 14, NULL, 10) -
619 return ((zoneoffset < 0 && hourminute == 1440) ||
620 (0 <= zoneoffset && !hourminute));
624 * Get the name etc info from the ---/+++ lines of a traditional patch header
626 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
627 * files, we can happily check the index for a match, but for creating a
628 * new file we should try to match whatever "patch" does. I have no idea.
630 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
634 first += 4; /* skip "--- " */
635 second += 4; /* skip "+++ " */
636 if (!p_value_known) {
638 p = guess_p_value(first);
639 q = guess_p_value(second);
641 if (0 <= p && p == q) {
646 if (is_dev_null(first)) {
648 patch->is_delete = 0;
649 name = find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB);
650 patch->new_name = name;
651 } else if (is_dev_null(second)) {
653 patch->is_delete = 1;
654 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
655 patch->old_name = name;
657 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
658 name = find_name(second, name, p_value, TERM_SPACE | TERM_TAB);
659 if (has_epoch_timestamp(first)) {
661 patch->is_delete = 0;
662 patch->new_name = name;
663 } else if (has_epoch_timestamp(second)) {
665 patch->is_delete = 1;
666 patch->old_name = name;
668 patch->old_name = patch->new_name = name;
672 die("unable to find filename in patch at line %d", linenr);
675 static int gitdiff_hdrend(const char *line, struct patch *patch)
681 * We're anal about diff header consistency, to make
682 * sure that we don't end up having strange ambiguous
683 * patches floating around.
685 * As a result, gitdiff_{old|new}name() will check
686 * their names against any previous information, just
689 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
691 if (!orig_name && !isnull)
692 return find_name(line, NULL, p_value, TERM_TAB);
701 die("git apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
702 another = find_name(line, NULL, p_value, TERM_TAB);
703 if (!another || memcmp(another, name, len + 1))
704 die("git apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
709 /* expect "/dev/null" */
710 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
711 die("git apply: bad git-diff - expected /dev/null on line %d", linenr);
716 static int gitdiff_oldname(const char *line, struct patch *patch)
718 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
722 static int gitdiff_newname(const char *line, struct patch *patch)
724 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
728 static int gitdiff_oldmode(const char *line, struct patch *patch)
730 patch->old_mode = strtoul(line, NULL, 8);
734 static int gitdiff_newmode(const char *line, struct patch *patch)
736 patch->new_mode = strtoul(line, NULL, 8);
740 static int gitdiff_delete(const char *line, struct patch *patch)
742 patch->is_delete = 1;
743 patch->old_name = patch->def_name;
744 return gitdiff_oldmode(line, patch);
747 static int gitdiff_newfile(const char *line, struct patch *patch)
750 patch->new_name = patch->def_name;
751 return gitdiff_newmode(line, patch);
754 static int gitdiff_copysrc(const char *line, struct patch *patch)
757 patch->old_name = find_name(line, NULL, 0, 0);
761 static int gitdiff_copydst(const char *line, struct patch *patch)
764 patch->new_name = find_name(line, NULL, 0, 0);
768 static int gitdiff_renamesrc(const char *line, struct patch *patch)
770 patch->is_rename = 1;
771 patch->old_name = find_name(line, NULL, 0, 0);
775 static int gitdiff_renamedst(const char *line, struct patch *patch)
777 patch->is_rename = 1;
778 patch->new_name = find_name(line, NULL, 0, 0);
782 static int gitdiff_similarity(const char *line, struct patch *patch)
784 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
789 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
791 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
796 static int gitdiff_index(const char *line, struct patch *patch)
799 * index line is N hexadecimal, "..", N hexadecimal,
800 * and optional space with octal mode.
802 const char *ptr, *eol;
805 ptr = strchr(line, '.');
806 if (!ptr || ptr[1] != '.' || 40 < ptr - line)
809 memcpy(patch->old_sha1_prefix, line, len);
810 patch->old_sha1_prefix[len] = 0;
813 ptr = strchr(line, ' ');
814 eol = strchr(line, '\n');
816 if (!ptr || eol < ptr)
822 memcpy(patch->new_sha1_prefix, line, len);
823 patch->new_sha1_prefix[len] = 0;
825 patch->old_mode = strtoul(ptr+1, NULL, 8);
830 * This is normal for a diff that doesn't change anything: we'll fall through
831 * into the next diff. Tell the parser to break out.
833 static int gitdiff_unrecognized(const char *line, struct patch *patch)
838 static const char *stop_at_slash(const char *line, int llen)
840 int nslash = p_value;
843 for (i = 0; i < llen; i++) {
845 if (ch == '/' && --nslash <= 0)
852 * This is to extract the same name that appears on "diff --git"
853 * line. We do not find and return anything if it is a rename
854 * patch, and it is OK because we will find the name elsewhere.
855 * We need to reliably find name only when it is mode-change only,
856 * creation or deletion of an empty file. In any of these cases,
857 * both sides are the same name under a/ and b/ respectively.
859 static char *git_header_name(char *line, int llen)
862 const char *second = NULL;
865 line += strlen("diff --git ");
866 llen -= strlen("diff --git ");
870 struct strbuf first = STRBUF_INIT;
871 struct strbuf sp = STRBUF_INIT;
873 if (unquote_c_style(&first, line, &second))
876 /* advance to the first slash */
877 cp = stop_at_slash(first.buf, first.len);
878 /* we do not accept absolute paths */
879 if (!cp || cp == first.buf)
881 strbuf_remove(&first, 0, cp + 1 - first.buf);
884 * second points at one past closing dq of name.
885 * find the second name.
887 while ((second < line + llen) && isspace(*second))
890 if (line + llen <= second)
892 if (*second == '"') {
893 if (unquote_c_style(&sp, second, NULL))
895 cp = stop_at_slash(sp.buf, sp.len);
896 if (!cp || cp == sp.buf)
898 /* They must match, otherwise ignore */
899 if (strcmp(cp + 1, first.buf))
902 return strbuf_detach(&first, NULL);
905 /* unquoted second */
906 cp = stop_at_slash(second, line + llen - second);
907 if (!cp || cp == second)
910 if (line + llen - cp != first.len + 1 ||
911 memcmp(first.buf, cp, first.len))
913 return strbuf_detach(&first, NULL);
916 strbuf_release(&first);
921 /* unquoted first name */
922 name = stop_at_slash(line, llen);
923 if (!name || name == line)
928 * since the first name is unquoted, a dq if exists must be
929 * the beginning of the second name.
931 for (second = name; second < line + llen; second++) {
932 if (*second == '"') {
933 struct strbuf sp = STRBUF_INIT;
936 if (unquote_c_style(&sp, second, NULL))
939 np = stop_at_slash(sp.buf, sp.len);
940 if (!np || np == sp.buf)
944 len = sp.buf + sp.len - np;
945 if (len < second - name &&
946 !strncmp(np, name, len) &&
947 isspace(name[len])) {
949 strbuf_remove(&sp, 0, np - sp.buf);
950 return strbuf_detach(&sp, NULL);
960 * Accept a name only if it shows up twice, exactly the same
963 for (len = 0 ; ; len++) {
978 if (second[len] == '\n' && !memcmp(name, second, len)) {
979 return xmemdupz(name, len);
985 /* Verify that we recognize the lines following a git header */
986 static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
988 unsigned long offset;
990 /* A git diff has explicit new/delete information, so we don't guess */
992 patch->is_delete = 0;
995 * Some things may not have the old name in the
996 * rest of the headers anywhere (pure mode changes,
997 * or removing or adding empty files), so we get
998 * the default name from the header.
1000 patch->def_name = git_header_name(line, len);
1001 if (patch->def_name && root) {
1002 char *s = xmalloc(root_len + strlen(patch->def_name) + 1);
1004 strcpy(s + root_len, patch->def_name);
1005 free(patch->def_name);
1006 patch->def_name = s;
1012 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
1013 static const struct opentry {
1015 int (*fn)(const char *, struct patch *);
1017 { "@@ -", gitdiff_hdrend },
1018 { "--- ", gitdiff_oldname },
1019 { "+++ ", gitdiff_newname },
1020 { "old mode ", gitdiff_oldmode },
1021 { "new mode ", gitdiff_newmode },
1022 { "deleted file mode ", gitdiff_delete },
1023 { "new file mode ", gitdiff_newfile },
1024 { "copy from ", gitdiff_copysrc },
1025 { "copy to ", gitdiff_copydst },
1026 { "rename old ", gitdiff_renamesrc },
1027 { "rename new ", gitdiff_renamedst },
1028 { "rename from ", gitdiff_renamesrc },
1029 { "rename to ", gitdiff_renamedst },
1030 { "similarity index ", gitdiff_similarity },
1031 { "dissimilarity index ", gitdiff_dissimilarity },
1032 { "index ", gitdiff_index },
1033 { "", gitdiff_unrecognized },
1037 len = linelen(line, size);
1038 if (!len || line[len-1] != '\n')
1040 for (i = 0; i < ARRAY_SIZE(optable); i++) {
1041 const struct opentry *p = optable + i;
1042 int oplen = strlen(p->str);
1043 if (len < oplen || memcmp(p->str, line, oplen))
1045 if (p->fn(line + oplen, patch) < 0)
1054 static int parse_num(const char *line, unsigned long *p)
1058 if (!isdigit(*line))
1060 *p = strtoul(line, &ptr, 10);
1064 static int parse_range(const char *line, int len, int offset, const char *expect,
1065 unsigned long *p1, unsigned long *p2)
1069 if (offset < 0 || offset >= len)
1074 digits = parse_num(line, p1);
1084 digits = parse_num(line+1, p2);
1093 ex = strlen(expect);
1096 if (memcmp(line, expect, ex))
1102 static void recount_diff(char *line, int size, struct fragment *fragment)
1104 int oldlines = 0, newlines = 0, ret = 0;
1107 warning("recount: ignore empty hunk");
1112 int len = linelen(line, size);
1120 case ' ': case '\n':
1132 ret = size < 3 || prefixcmp(line, "@@ ");
1135 ret = size < 5 || prefixcmp(line, "diff ");
1142 warning("recount: unexpected line: %.*s",
1143 (int)linelen(line, size), line);
1148 fragment->oldlines = oldlines;
1149 fragment->newlines = newlines;
1153 * Parse a unified diff fragment header of the
1154 * form "@@ -a,b +c,d @@"
1156 static int parse_fragment_header(char *line, int len, struct fragment *fragment)
1160 if (!len || line[len-1] != '\n')
1163 /* Figure out the number of lines in a fragment */
1164 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1165 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1170 static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
1172 unsigned long offset, len;
1174 patch->is_toplevel_relative = 0;
1175 patch->is_rename = patch->is_copy = 0;
1176 patch->is_new = patch->is_delete = -1;
1177 patch->old_mode = patch->new_mode = 0;
1178 patch->old_name = patch->new_name = NULL;
1179 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
1180 unsigned long nextlen;
1182 len = linelen(line, size);
1186 /* Testing this early allows us to take a few shortcuts.. */
1191 * Make sure we don't find any unconnected patch fragments.
1192 * That's a sign that we didn't find a header, and that a
1193 * patch has become corrupted/broken up.
1195 if (!memcmp("@@ -", line, 4)) {
1196 struct fragment dummy;
1197 if (parse_fragment_header(line, len, &dummy) < 0)
1199 die("patch fragment without header at line %d: %.*s",
1200 linenr, (int)len-1, line);
1207 * Git patch? It might not have a real patch, just a rename
1208 * or mode change, so we handle that specially
1210 if (!memcmp("diff --git ", line, 11)) {
1211 int git_hdr_len = parse_git_header(line, len, size, patch);
1212 if (git_hdr_len <= len)
1214 if (!patch->old_name && !patch->new_name) {
1215 if (!patch->def_name)
1216 die("git diff header lacks filename information when removing "
1217 "%d leading pathname components (line %d)" , p_value, linenr);
1218 patch->old_name = patch->new_name = patch->def_name;
1220 patch->is_toplevel_relative = 1;
1221 *hdrsize = git_hdr_len;
1225 /* --- followed by +++ ? */
1226 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1230 * We only accept unified patches, so we want it to
1231 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1232 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1234 nextlen = linelen(line + len, size - len);
1235 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1238 /* Ok, we'll consider it a patch */
1239 parse_traditional_patch(line, line+len, patch);
1240 *hdrsize = len + nextlen;
1247 static void record_ws_error(unsigned result, const char *line, int len, int linenr)
1255 if (squelch_whitespace_errors &&
1256 squelch_whitespace_errors < whitespace_error)
1259 err = whitespace_error_string(result);
1260 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1261 patch_input_file, linenr, err, len, line);
1265 static void check_whitespace(const char *line, int len, unsigned ws_rule)
1267 unsigned result = ws_check(line + 1, len - 1, ws_rule);
1269 record_ws_error(result, line + 1, len - 2, linenr);
1273 * Parse a unified diff. Note that this really needs to parse each
1274 * fragment separately, since the only way to know the difference
1275 * between a "---" that is part of a patch, and a "---" that starts
1276 * the next patch is to look at the line counts..
1278 static int parse_fragment(char *line, unsigned long size,
1279 struct patch *patch, struct fragment *fragment)
1282 int len = linelen(line, size), offset;
1283 unsigned long oldlines, newlines;
1284 unsigned long leading, trailing;
1286 offset = parse_fragment_header(line, len, fragment);
1289 if (offset > 0 && patch->recount)
1290 recount_diff(line + offset, size - offset, fragment);
1291 oldlines = fragment->oldlines;
1292 newlines = fragment->newlines;
1296 /* Parse the thing.. */
1300 added = deleted = 0;
1303 offset += len, size -= len, line += len, linenr++) {
1304 if (!oldlines && !newlines)
1306 len = linelen(line, size);
1307 if (!len || line[len-1] != '\n')
1312 case '\n': /* newer GNU diff, an empty context line */
1316 if (!deleted && !added)
1321 if (apply_in_reverse &&
1322 ws_error_action != nowarn_ws_error)
1323 check_whitespace(line, len, patch->ws_rule);
1329 if (!apply_in_reverse &&
1330 ws_error_action != nowarn_ws_error)
1331 check_whitespace(line, len, patch->ws_rule);
1338 * We allow "\ No newline at end of file". Depending
1339 * on locale settings when the patch was produced we
1340 * don't know what this line looks like. The only
1341 * thing we do know is that it begins with "\ ".
1342 * Checking for 12 is just for sanity check -- any
1343 * l10n of "\ No newline..." is at least that long.
1346 if (len < 12 || memcmp(line, "\\ ", 2))
1351 if (oldlines || newlines)
1353 fragment->leading = leading;
1354 fragment->trailing = trailing;
1357 * If a fragment ends with an incomplete line, we failed to include
1358 * it in the above loop because we hit oldlines == newlines == 0
1361 if (12 < size && !memcmp(line, "\\ ", 2))
1362 offset += linelen(line, size);
1364 patch->lines_added += added;
1365 patch->lines_deleted += deleted;
1367 if (0 < patch->is_new && oldlines)
1368 return error("new file depends on old contents");
1369 if (0 < patch->is_delete && newlines)
1370 return error("deleted file still has contents");
1374 static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
1376 unsigned long offset = 0;
1377 unsigned long oldlines = 0, newlines = 0, context = 0;
1378 struct fragment **fragp = &patch->fragments;
1380 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1381 struct fragment *fragment;
1384 fragment = xcalloc(1, sizeof(*fragment));
1385 fragment->linenr = linenr;
1386 len = parse_fragment(line, size, patch, fragment);
1388 die("corrupt patch at line %d", linenr);
1389 fragment->patch = line;
1390 fragment->size = len;
1391 oldlines += fragment->oldlines;
1392 newlines += fragment->newlines;
1393 context += fragment->leading + fragment->trailing;
1396 fragp = &fragment->next;
1404 * If something was removed (i.e. we have old-lines) it cannot
1405 * be creation, and if something was added it cannot be
1406 * deletion. However, the reverse is not true; --unified=0
1407 * patches that only add are not necessarily creation even
1408 * though they do not have any old lines, and ones that only
1409 * delete are not necessarily deletion.
1411 * Unfortunately, a real creation/deletion patch do _not_ have
1412 * any context line by definition, so we cannot safely tell it
1413 * apart with --unified=0 insanity. At least if the patch has
1414 * more than one hunk it is not creation or deletion.
1416 if (patch->is_new < 0 &&
1417 (oldlines || (patch->fragments && patch->fragments->next)))
1419 if (patch->is_delete < 0 &&
1420 (newlines || (patch->fragments && patch->fragments->next)))
1421 patch->is_delete = 0;
1423 if (0 < patch->is_new && oldlines)
1424 die("new file %s depends on old contents", patch->new_name);
1425 if (0 < patch->is_delete && newlines)
1426 die("deleted file %s still has contents", patch->old_name);
1427 if (!patch->is_delete && !newlines && context)
1428 fprintf(stderr, "** warning: file %s becomes empty but "
1429 "is not deleted\n", patch->new_name);
1434 static inline int metadata_changes(struct patch *patch)
1436 return patch->is_rename > 0 ||
1437 patch->is_copy > 0 ||
1438 patch->is_new > 0 ||
1440 (patch->old_mode && patch->new_mode &&
1441 patch->old_mode != patch->new_mode);
1444 static char *inflate_it(const void *data, unsigned long size,
1445 unsigned long inflated_size)
1451 memset(&stream, 0, sizeof(stream));
1453 stream.next_in = (unsigned char *)data;
1454 stream.avail_in = size;
1455 stream.next_out = out = xmalloc(inflated_size);
1456 stream.avail_out = inflated_size;
1457 git_inflate_init(&stream);
1458 st = git_inflate(&stream, Z_FINISH);
1459 git_inflate_end(&stream);
1460 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1467 static struct fragment *parse_binary_hunk(char **buf_p,
1468 unsigned long *sz_p,
1473 * Expect a line that begins with binary patch method ("literal"
1474 * or "delta"), followed by the length of data before deflating.
1475 * a sequence of 'length-byte' followed by base-85 encoded data
1476 * should follow, terminated by a newline.
1478 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1479 * and we would limit the patch line to 66 characters,
1480 * so one line can fit up to 13 groups that would decode
1481 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1482 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1485 unsigned long size = *sz_p;
1486 char *buffer = *buf_p;
1488 unsigned long origlen;
1491 struct fragment *frag;
1493 llen = linelen(buffer, size);
1498 if (!prefixcmp(buffer, "delta ")) {
1499 patch_method = BINARY_DELTA_DEFLATED;
1500 origlen = strtoul(buffer + 6, NULL, 10);
1502 else if (!prefixcmp(buffer, "literal ")) {
1503 patch_method = BINARY_LITERAL_DEFLATED;
1504 origlen = strtoul(buffer + 8, NULL, 10);
1512 int byte_length, max_byte_length, newsize;
1513 llen = linelen(buffer, size);
1517 /* consume the blank line */
1523 * Minimum line is "A00000\n" which is 7-byte long,
1524 * and the line length must be multiple of 5 plus 2.
1526 if ((llen < 7) || (llen-2) % 5)
1528 max_byte_length = (llen - 2) / 5 * 4;
1529 byte_length = *buffer;
1530 if ('A' <= byte_length && byte_length <= 'Z')
1531 byte_length = byte_length - 'A' + 1;
1532 else if ('a' <= byte_length && byte_length <= 'z')
1533 byte_length = byte_length - 'a' + 27;
1536 /* if the input length was not multiple of 4, we would
1537 * have filler at the end but the filler should never
1540 if (max_byte_length < byte_length ||
1541 byte_length <= max_byte_length - 4)
1543 newsize = hunk_size + byte_length;
1544 data = xrealloc(data, newsize);
1545 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1547 hunk_size = newsize;
1552 frag = xcalloc(1, sizeof(*frag));
1553 frag->patch = inflate_it(data, hunk_size, origlen);
1557 frag->size = origlen;
1561 frag->binary_patch_method = patch_method;
1567 error("corrupt binary patch at line %d: %.*s",
1568 linenr-1, llen-1, buffer);
1572 static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1575 * We have read "GIT binary patch\n"; what follows is a line
1576 * that says the patch method (currently, either "literal" or
1577 * "delta") and the length of data before deflating; a
1578 * sequence of 'length-byte' followed by base-85 encoded data
1581 * When a binary patch is reversible, there is another binary
1582 * hunk in the same format, starting with patch method (either
1583 * "literal" or "delta") with the length of data, and a sequence
1584 * of length-byte + base-85 encoded data, terminated with another
1585 * empty line. This data, when applied to the postimage, produces
1588 struct fragment *forward;
1589 struct fragment *reverse;
1593 forward = parse_binary_hunk(&buffer, &size, &status, &used);
1594 if (!forward && !status)
1595 /* there has to be one hunk (forward hunk) */
1596 return error("unrecognized binary patch at line %d", linenr-1);
1598 /* otherwise we already gave an error message */
1601 reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1606 * Not having reverse hunk is not an error, but having
1607 * a corrupt reverse hunk is.
1609 free((void*) forward->patch);
1613 forward->next = reverse;
1614 patch->fragments = forward;
1615 patch->is_binary = 1;
1619 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
1621 int hdrsize, patchsize;
1622 int offset = find_header(buffer, size, &hdrsize, patch);
1627 patch->ws_rule = whitespace_rule(patch->new_name
1631 patchsize = parse_single_patch(buffer + offset + hdrsize,
1632 size - offset - hdrsize, patch);
1635 static const char *binhdr[] = {
1640 static const char git_binary[] = "GIT binary patch\n";
1642 int hd = hdrsize + offset;
1643 unsigned long llen = linelen(buffer + hd, size - hd);
1645 if (llen == sizeof(git_binary) - 1 &&
1646 !memcmp(git_binary, buffer + hd, llen)) {
1649 used = parse_binary(buffer + hd + llen,
1650 size - hd - llen, patch);
1652 patchsize = used + llen;
1656 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
1657 for (i = 0; binhdr[i]; i++) {
1658 int len = strlen(binhdr[i]);
1659 if (len < size - hd &&
1660 !memcmp(binhdr[i], buffer + hd, len)) {
1662 patch->is_binary = 1;
1669 /* Empty patch cannot be applied if it is a text patch
1670 * without metadata change. A binary patch appears
1673 if ((apply || check) &&
1674 (!patch->is_binary && !metadata_changes(patch)))
1675 die("patch with only garbage at line %d", linenr);
1678 return offset + hdrsize + patchsize;
1681 #define swap(a,b) myswap((a),(b),sizeof(a))
1683 #define myswap(a, b, size) do { \
1684 unsigned char mytmp[size]; \
1685 memcpy(mytmp, &a, size); \
1686 memcpy(&a, &b, size); \
1687 memcpy(&b, mytmp, size); \
1690 static void reverse_patches(struct patch *p)
1692 for (; p; p = p->next) {
1693 struct fragment *frag = p->fragments;
1695 swap(p->new_name, p->old_name);
1696 swap(p->new_mode, p->old_mode);
1697 swap(p->is_new, p->is_delete);
1698 swap(p->lines_added, p->lines_deleted);
1699 swap(p->old_sha1_prefix, p->new_sha1_prefix);
1701 for (; frag; frag = frag->next) {
1702 swap(frag->newpos, frag->oldpos);
1703 swap(frag->newlines, frag->oldlines);
1708 static const char pluses[] =
1709 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1710 static const char minuses[]=
1711 "----------------------------------------------------------------------";
1713 static void show_stats(struct patch *patch)
1715 struct strbuf qname = STRBUF_INIT;
1716 char *cp = patch->new_name ? patch->new_name : patch->old_name;
1719 quote_c_style(cp, &qname, NULL, 0);
1722 * "scale" the filename
1728 if (qname.len > max) {
1729 cp = strchr(qname.buf + qname.len + 3 - max, '/');
1731 cp = qname.buf + qname.len + 3 - max;
1732 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
1735 if (patch->is_binary) {
1736 printf(" %-*s | Bin\n", max, qname.buf);
1737 strbuf_release(&qname);
1741 printf(" %-*s |", max, qname.buf);
1742 strbuf_release(&qname);
1745 * scale the add/delete
1747 max = max + max_change > 70 ? 70 - max : max_change;
1748 add = patch->lines_added;
1749 del = patch->lines_deleted;
1751 if (max_change > 0) {
1752 int total = ((add + del) * max + max_change / 2) / max_change;
1753 add = (add * max + max_change / 2) / max_change;
1756 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
1757 add, pluses, del, minuses);
1760 static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
1762 switch (st->st_mode & S_IFMT) {
1764 if (strbuf_readlink(buf, path, st->st_size) < 0)
1765 return error("unable to read symlink %s", path);
1768 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
1769 return error("unable to open or read %s", path);
1770 convert_to_git(path, buf->buf, buf->len, buf, 0);
1778 * Update the preimage, and the common lines in postimage,
1779 * from buffer buf of length len. If postlen is 0 the postimage
1780 * is updated in place, otherwise it's updated on a new buffer
1784 static void update_pre_post_images(struct image *preimage,
1785 struct image *postimage,
1787 size_t len, size_t postlen)
1790 char *new, *old, *fixed;
1791 struct image fixed_preimage;
1794 * Update the preimage with whitespace fixes. Note that we
1795 * are not losing preimage->buf -- apply_one_fragment() will
1798 prepare_image(&fixed_preimage, buf, len, 1);
1799 assert(fixed_preimage.nr == preimage->nr);
1800 for (i = 0; i < preimage->nr; i++)
1801 fixed_preimage.line[i].flag = preimage->line[i].flag;
1802 free(preimage->line_allocated);
1803 *preimage = fixed_preimage;
1806 * Adjust the common context lines in postimage. This can be
1807 * done in-place when we are just doing whitespace fixing,
1808 * which does not make the string grow, but needs a new buffer
1809 * when ignoring whitespace causes the update, since in this case
1810 * we could have e.g. tabs converted to multiple spaces.
1811 * We trust the caller to tell us if the update can be done
1812 * in place (postlen==0) or not.
1814 old = postimage->buf;
1816 new = postimage->buf = xmalloc(postlen);
1819 fixed = preimage->buf;
1820 for (i = ctx = 0; i < postimage->nr; i++) {
1821 size_t len = postimage->line[i].len;
1822 if (!(postimage->line[i].flag & LINE_COMMON)) {
1823 /* an added line -- no counterparts in preimage */
1824 memmove(new, old, len);
1830 /* a common context -- skip it in the original postimage */
1833 /* and find the corresponding one in the fixed preimage */
1834 while (ctx < preimage->nr &&
1835 !(preimage->line[ctx].flag & LINE_COMMON)) {
1836 fixed += preimage->line[ctx].len;
1839 if (preimage->nr <= ctx)
1842 /* and copy it in, while fixing the line length */
1843 len = preimage->line[ctx].len;
1844 memcpy(new, fixed, len);
1847 postimage->line[i].len = len;
1851 /* Fix the length of the whole thing */
1852 postimage->len = new - postimage->buf;
1855 static int match_fragment(struct image *img,
1856 struct image *preimage,
1857 struct image *postimage,
1861 int match_beginning, int match_end)
1864 char *fixed_buf, *buf, *orig, *target;
1865 struct strbuf fixed;
1869 if (preimage->nr + try_lno <= img->nr) {
1871 * The hunk falls within the boundaries of img.
1873 preimage_limit = preimage->nr;
1874 if (match_end && (preimage->nr + try_lno != img->nr))
1876 } else if (ws_error_action == correct_ws_error &&
1877 (ws_rule & WS_BLANK_AT_EOF)) {
1879 * This hunk extends beyond the end of img, and we are
1880 * removing blank lines at the end of the file. This
1881 * many lines from the beginning of the preimage must
1882 * match with img, and the remainder of the preimage
1885 preimage_limit = img->nr - try_lno;
1888 * The hunk extends beyond the end of the img and
1889 * we are not removing blanks at the end, so we
1890 * should reject the hunk at this position.
1895 if (match_beginning && try_lno)
1898 /* Quick hash check */
1899 for (i = 0; i < preimage_limit; i++)
1900 if (preimage->line[i].hash != img->line[try_lno + i].hash)
1903 if (preimage_limit == preimage->nr) {
1905 * Do we have an exact match? If we were told to match
1906 * at the end, size must be exactly at try+fragsize,
1907 * otherwise try+fragsize must be still within the preimage,
1908 * and either case, the old piece should match the preimage
1912 ? (try + preimage->len == img->len)
1913 : (try + preimage->len <= img->len)) &&
1914 !memcmp(img->buf + try, preimage->buf, preimage->len))
1918 * The preimage extends beyond the end of img, so
1919 * there cannot be an exact match.
1921 * There must be one non-blank context line that match
1922 * a line before the end of img.
1926 buf = preimage->buf;
1928 for (i = 0; i < preimage_limit; i++)
1929 buf_end += preimage->line[i].len;
1931 for ( ; buf < buf_end; buf++)
1939 * No exact match. If we are ignoring whitespace, run a line-by-line
1940 * fuzzy matching. We collect all the line length information because
1941 * we need it to adjust whitespace if we match.
1943 if (ws_ignore_action == ignore_ws_change) {
1946 size_t postlen = postimage->len;
1950 for (i = 0; i < preimage_limit; i++) {
1951 size_t prelen = preimage->line[i].len;
1952 size_t imglen = img->line[try_lno+i].len;
1954 if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,
1955 preimage->buf + preoff, prelen))
1957 if (preimage->line[i].flag & LINE_COMMON)
1958 postlen += imglen - prelen;
1964 * Ok, the preimage matches with whitespace fuzz.
1966 * imgoff now holds the true length of the target that
1967 * matches the preimage before the end of the file.
1969 * Count the number of characters in the preimage that fall
1970 * beyond the end of the file and make sure that all of them
1971 * are whitespace characters. (This can only happen if
1972 * we are removing blank lines at the end of the file.)
1974 buf = preimage_eof = preimage->buf + preoff;
1975 for ( ; i < preimage->nr; i++)
1976 preoff += preimage->line[i].len;
1977 preimage_end = preimage->buf + preoff;
1978 for ( ; buf < preimage_end; buf++)
1983 * Update the preimage and the common postimage context
1984 * lines to use the same whitespace as the target.
1985 * If whitespace is missing in the target (i.e.
1986 * if the preimage extends beyond the end of the file),
1987 * use the whitespace from the preimage.
1989 extra_chars = preimage_end - preimage_eof;
1990 strbuf_init(&fixed, imgoff + extra_chars);
1991 strbuf_add(&fixed, img->buf + try, imgoff);
1992 strbuf_add(&fixed, preimage_eof, extra_chars);
1993 fixed_buf = strbuf_detach(&fixed, &fixed_len);
1994 update_pre_post_images(preimage, postimage,
1995 fixed_buf, fixed_len, postlen);
1999 if (ws_error_action != correct_ws_error)
2003 * The hunk does not apply byte-by-byte, but the hash says
2004 * it might with whitespace fuzz. We haven't been asked to
2005 * ignore whitespace, we were asked to correct whitespace
2006 * errors, so let's try matching after whitespace correction.
2008 * The preimage may extend beyond the end of the file,
2009 * but in this loop we will only handle the part of the
2010 * preimage that falls within the file.
2012 strbuf_init(&fixed, preimage->len + 1);
2013 orig = preimage->buf;
2014 target = img->buf + try;
2015 for (i = 0; i < preimage_limit; i++) {
2016 size_t oldlen = preimage->line[i].len;
2017 size_t tgtlen = img->line[try_lno + i].len;
2018 size_t fixstart = fixed.len;
2019 struct strbuf tgtfix;
2022 /* Try fixing the line in the preimage */
2023 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2025 /* Try fixing the line in the target */
2026 strbuf_init(&tgtfix, tgtlen);
2027 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2030 * If they match, either the preimage was based on
2031 * a version before our tree fixed whitespace breakage,
2032 * or we are lacking a whitespace-fix patch the tree
2033 * the preimage was based on already had (i.e. target
2034 * has whitespace breakage, the preimage doesn't).
2035 * In either case, we are fixing the whitespace breakages
2036 * so we might as well take the fix together with their
2039 match = (tgtfix.len == fixed.len - fixstart &&
2040 !memcmp(tgtfix.buf, fixed.buf + fixstart,
2041 fixed.len - fixstart));
2043 strbuf_release(&tgtfix);
2053 * Now handle the lines in the preimage that falls beyond the
2054 * end of the file (if any). They will only match if they are
2055 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2058 for ( ; i < preimage->nr; i++) {
2059 size_t fixstart = fixed.len; /* start of the fixed preimage */
2060 size_t oldlen = preimage->line[i].len;
2063 /* Try fixing the line in the preimage */
2064 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2066 for (j = fixstart; j < fixed.len; j++)
2067 if (!isspace(fixed.buf[j]))
2074 * Yes, the preimage is based on an older version that still
2075 * has whitespace breakages unfixed, and fixing them makes the
2076 * hunk match. Update the context lines in the postimage.
2078 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2079 update_pre_post_images(preimage, postimage,
2080 fixed_buf, fixed_len, 0);
2084 strbuf_release(&fixed);
2088 static int find_pos(struct image *img,
2089 struct image *preimage,
2090 struct image *postimage,
2093 int match_beginning, int match_end)
2096 unsigned long backwards, forwards, try;
2097 int backwards_lno, forwards_lno, try_lno;
2100 * If match_beginning or match_end is specified, there is no
2101 * point starting from a wrong line that will never match and
2102 * wander around and wait for a match at the specified end.
2104 if (match_beginning)
2107 line = img->nr - preimage->nr;
2110 * Because the comparison is unsigned, the following test
2111 * will also take care of a negative line number that can
2112 * result when match_end and preimage is larger than the target.
2114 if ((size_t) line > img->nr)
2118 for (i = 0; i < line; i++)
2119 try += img->line[i].len;
2122 * There's probably some smart way to do this, but I'll leave
2123 * that to the smart and beautiful people. I'm simple and stupid.
2126 backwards_lno = line;
2128 forwards_lno = line;
2131 for (i = 0; ; i++) {
2132 if (match_fragment(img, preimage, postimage,
2133 try, try_lno, ws_rule,
2134 match_beginning, match_end))
2138 if (backwards_lno == 0 && forwards_lno == img->nr)
2142 if (backwards_lno == 0) {
2147 backwards -= img->line[backwards_lno].len;
2149 try_lno = backwards_lno;
2151 if (forwards_lno == img->nr) {
2155 forwards += img->line[forwards_lno].len;
2158 try_lno = forwards_lno;
2165 static void remove_first_line(struct image *img)
2167 img->buf += img->line[0].len;
2168 img->len -= img->line[0].len;
2173 static void remove_last_line(struct image *img)
2175 img->len -= img->line[--img->nr].len;
2178 static void update_image(struct image *img,
2180 struct image *preimage,
2181 struct image *postimage)
2184 * remove the copy of preimage at offset in img
2185 * and replace it with postimage
2188 size_t remove_count, insert_count, applied_at = 0;
2193 * If we are removing blank lines at the end of img,
2194 * the preimage may extend beyond the end.
2195 * If that is the case, we must be careful only to
2196 * remove the part of the preimage that falls within
2197 * the boundaries of img. Initialize preimage_limit
2198 * to the number of lines in the preimage that falls
2199 * within the boundaries.
2201 preimage_limit = preimage->nr;
2202 if (preimage_limit > img->nr - applied_pos)
2203 preimage_limit = img->nr - applied_pos;
2205 for (i = 0; i < applied_pos; i++)
2206 applied_at += img->line[i].len;
2209 for (i = 0; i < preimage_limit; i++)
2210 remove_count += img->line[applied_pos + i].len;
2211 insert_count = postimage->len;
2213 /* Adjust the contents */
2214 result = xmalloc(img->len + insert_count - remove_count + 1);
2215 memcpy(result, img->buf, applied_at);
2216 memcpy(result + applied_at, postimage->buf, postimage->len);
2217 memcpy(result + applied_at + postimage->len,
2218 img->buf + (applied_at + remove_count),
2219 img->len - (applied_at + remove_count));
2222 img->len += insert_count - remove_count;
2223 result[img->len] = '\0';
2225 /* Adjust the line table */
2226 nr = img->nr + postimage->nr - preimage_limit;
2227 if (preimage_limit < postimage->nr) {
2229 * NOTE: this knows that we never call remove_first_line()
2230 * on anything other than pre/post image.
2232 img->line = xrealloc(img->line, nr * sizeof(*img->line));
2233 img->line_allocated = img->line;
2235 if (preimage_limit != postimage->nr)
2236 memmove(img->line + applied_pos + postimage->nr,
2237 img->line + applied_pos + preimage_limit,
2238 (img->nr - (applied_pos + preimage_limit)) *
2239 sizeof(*img->line));
2240 memcpy(img->line + applied_pos,
2242 postimage->nr * sizeof(*img->line));
2246 static int apply_one_fragment(struct image *img, struct fragment *frag,
2247 int inaccurate_eof, unsigned ws_rule)
2249 int match_beginning, match_end;
2250 const char *patch = frag->patch;
2251 int size = frag->size;
2252 char *old, *oldlines;
2253 struct strbuf newlines;
2254 int new_blank_lines_at_end = 0;
2255 unsigned long leading, trailing;
2256 int pos, applied_pos;
2257 struct image preimage;
2258 struct image postimage;
2260 memset(&preimage, 0, sizeof(preimage));
2261 memset(&postimage, 0, sizeof(postimage));
2262 oldlines = xmalloc(size);
2263 strbuf_init(&newlines, size);
2268 int len = linelen(patch, size);
2270 int added_blank_line = 0;
2271 int is_blank_context = 0;
2278 * "plen" is how much of the line we should use for
2279 * the actual patch data. Normally we just remove the
2280 * first character on the line, but if the line is
2281 * followed by "\ No newline", then we also remove the
2282 * last one (which is the newline, of course).
2285 if (len < size && patch[len] == '\\')
2288 if (apply_in_reverse) {
2291 else if (first == '+')
2297 /* Newer GNU diff, empty context line */
2299 /* ... followed by '\No newline'; nothing */
2302 strbuf_addch(&newlines, '\n');
2303 add_line_info(&preimage, "\n", 1, LINE_COMMON);
2304 add_line_info(&postimage, "\n", 1, LINE_COMMON);
2305 is_blank_context = 1;
2308 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2309 ws_blank_line(patch + 1, plen, ws_rule))
2310 is_blank_context = 1;
2312 memcpy(old, patch + 1, plen);
2313 add_line_info(&preimage, old, plen,
2314 (first == ' ' ? LINE_COMMON : 0));
2318 /* Fall-through for ' ' */
2320 /* --no-add does not add new lines */
2321 if (first == '+' && no_add)
2324 start = newlines.len;
2326 !whitespace_error ||
2327 ws_error_action != correct_ws_error) {
2328 strbuf_add(&newlines, patch + 1, plen);
2331 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &applied_after_fixing_ws);
2333 add_line_info(&postimage, newlines.buf + start, newlines.len - start,
2334 (first == '+' ? 0 : LINE_COMMON));
2336 (ws_rule & WS_BLANK_AT_EOF) &&
2337 ws_blank_line(patch + 1, plen, ws_rule))
2338 added_blank_line = 1;
2340 case '@': case '\\':
2341 /* Ignore it, we already handled it */
2344 if (apply_verbosely)
2345 error("invalid start of line: '%c'", first);
2348 if (added_blank_line)
2349 new_blank_lines_at_end++;
2350 else if (is_blank_context)
2353 new_blank_lines_at_end = 0;
2357 if (inaccurate_eof &&
2358 old > oldlines && old[-1] == '\n' &&
2359 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
2361 strbuf_setlen(&newlines, newlines.len - 1);
2364 leading = frag->leading;
2365 trailing = frag->trailing;
2368 * A hunk to change lines at the beginning would begin with
2370 * but we need to be careful. -U0 that inserts before the second
2371 * line also has this pattern.
2373 * And a hunk to add to an empty file would begin with
2376 * In other words, a hunk that is (frag->oldpos <= 1) with or
2377 * without leading context must match at the beginning.
2379 match_beginning = (!frag->oldpos ||
2380 (frag->oldpos == 1 && !unidiff_zero));
2383 * A hunk without trailing lines must match at the end.
2384 * However, we simply cannot tell if a hunk must match end
2385 * from the lack of trailing lines if the patch was generated
2386 * with unidiff without any context.
2388 match_end = !unidiff_zero && !trailing;
2390 pos = frag->newpos ? (frag->newpos - 1) : 0;
2391 preimage.buf = oldlines;
2392 preimage.len = old - oldlines;
2393 postimage.buf = newlines.buf;
2394 postimage.len = newlines.len;
2395 preimage.line = preimage.line_allocated;
2396 postimage.line = postimage.line_allocated;
2400 applied_pos = find_pos(img, &preimage, &postimage, pos,
2401 ws_rule, match_beginning, match_end);
2403 if (applied_pos >= 0)
2406 /* Am I at my context limits? */
2407 if ((leading <= p_context) && (trailing <= p_context))
2409 if (match_beginning || match_end) {
2410 match_beginning = match_end = 0;
2415 * Reduce the number of context lines; reduce both
2416 * leading and trailing if they are equal otherwise
2417 * just reduce the larger context.
2419 if (leading >= trailing) {
2420 remove_first_line(&preimage);
2421 remove_first_line(&postimage);
2425 if (trailing > leading) {
2426 remove_last_line(&preimage);
2427 remove_last_line(&postimage);
2432 if (applied_pos >= 0) {
2433 if (new_blank_lines_at_end &&
2434 preimage.nr + applied_pos >= img->nr &&
2435 (ws_rule & WS_BLANK_AT_EOF) &&
2436 ws_error_action != nowarn_ws_error) {
2437 record_ws_error(WS_BLANK_AT_EOF, "+", 1, frag->linenr);
2438 if (ws_error_action == correct_ws_error) {
2439 while (new_blank_lines_at_end--)
2440 remove_last_line(&postimage);
2443 * We would want to prevent write_out_results()
2444 * from taking place in apply_patch() that follows
2445 * the callchain led us here, which is:
2446 * apply_patch->check_patch_list->check_patch->
2447 * apply_data->apply_fragments->apply_one_fragment
2449 if (ws_error_action == die_on_ws_error)
2454 * Warn if it was necessary to reduce the number
2457 if ((leading != frag->leading) ||
2458 (trailing != frag->trailing))
2459 fprintf(stderr, "Context reduced to (%ld/%ld)"
2460 " to apply fragment at %d\n",
2461 leading, trailing, applied_pos+1);
2462 update_image(img, applied_pos, &preimage, &postimage);
2464 if (apply_verbosely)
2465 error("while searching for:\n%.*s",
2466 (int)(old - oldlines), oldlines);
2470 strbuf_release(&newlines);
2471 free(preimage.line_allocated);
2472 free(postimage.line_allocated);
2474 return (applied_pos < 0);
2477 static int apply_binary_fragment(struct image *img, struct patch *patch)
2479 struct fragment *fragment = patch->fragments;
2483 /* Binary patch is irreversible without the optional second hunk */
2484 if (apply_in_reverse) {
2485 if (!fragment->next)
2486 return error("cannot reverse-apply a binary patch "
2487 "without the reverse hunk to '%s'",
2489 ? patch->new_name : patch->old_name);
2490 fragment = fragment->next;
2492 switch (fragment->binary_patch_method) {
2493 case BINARY_DELTA_DEFLATED:
2494 dst = patch_delta(img->buf, img->len, fragment->patch,
2495 fragment->size, &len);
2502 case BINARY_LITERAL_DEFLATED:
2504 img->len = fragment->size;
2505 img->buf = xmalloc(img->len+1);
2506 memcpy(img->buf, fragment->patch, img->len);
2507 img->buf[img->len] = '\0';
2513 static int apply_binary(struct image *img, struct patch *patch)
2515 const char *name = patch->old_name ? patch->old_name : patch->new_name;
2516 unsigned char sha1[20];
2519 * For safety, we require patch index line to contain
2520 * full 40-byte textual SHA1 for old and new, at least for now.
2522 if (strlen(patch->old_sha1_prefix) != 40 ||
2523 strlen(patch->new_sha1_prefix) != 40 ||
2524 get_sha1_hex(patch->old_sha1_prefix, sha1) ||
2525 get_sha1_hex(patch->new_sha1_prefix, sha1))
2526 return error("cannot apply binary patch to '%s' "
2527 "without full index line", name);
2529 if (patch->old_name) {
2531 * See if the old one matches what the patch
2534 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2535 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
2536 return error("the patch applies to '%s' (%s), "
2537 "which does not match the "
2538 "current contents.",
2539 name, sha1_to_hex(sha1));
2542 /* Otherwise, the old one must be empty. */
2544 return error("the patch applies to an empty "
2545 "'%s' but it is not empty", name);
2548 get_sha1_hex(patch->new_sha1_prefix, sha1);
2549 if (is_null_sha1(sha1)) {
2551 return 0; /* deletion patch */
2554 if (has_sha1_file(sha1)) {
2555 /* We already have the postimage */
2556 enum object_type type;
2560 result = read_sha1_file(sha1, &type, &size);
2562 return error("the necessary postimage %s for "
2563 "'%s' cannot be read",
2564 patch->new_sha1_prefix, name);
2570 * We have verified buf matches the preimage;
2571 * apply the patch data to it, which is stored
2572 * in the patch->fragments->{patch,size}.
2574 if (apply_binary_fragment(img, patch))
2575 return error("binary patch does not apply to '%s'",
2578 /* verify that the result matches */
2579 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2580 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
2581 return error("binary patch to '%s' creates incorrect result (expecting %s, got %s)",
2582 name, patch->new_sha1_prefix, sha1_to_hex(sha1));
2588 static int apply_fragments(struct image *img, struct patch *patch)
2590 struct fragment *frag = patch->fragments;
2591 const char *name = patch->old_name ? patch->old_name : patch->new_name;
2592 unsigned ws_rule = patch->ws_rule;
2593 unsigned inaccurate_eof = patch->inaccurate_eof;
2595 if (patch->is_binary)
2596 return apply_binary(img, patch);
2599 if (apply_one_fragment(img, frag, inaccurate_eof, ws_rule)) {
2600 error("patch failed: %s:%ld", name, frag->oldpos);
2601 if (!apply_with_reject)
2610 static int read_file_or_gitlink(struct cache_entry *ce, struct strbuf *buf)
2615 if (S_ISGITLINK(ce->ce_mode)) {
2616 strbuf_grow(buf, 100);
2617 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(ce->sha1));
2619 enum object_type type;
2623 result = read_sha1_file(ce->sha1, &type, &sz);
2626 /* XXX read_sha1_file NUL-terminates */
2627 strbuf_attach(buf, result, sz, sz + 1);
2632 static struct patch *in_fn_table(const char *name)
2634 struct string_list_item *item;
2639 item = string_list_lookup(&fn_table, name);
2641 return (struct patch *)item->util;
2647 * item->util in the filename table records the status of the path.
2648 * Usually it points at a patch (whose result records the contents
2649 * of it after applying it), but it could be PATH_WAS_DELETED for a
2650 * path that a previously applied patch has already removed.
2652 #define PATH_TO_BE_DELETED ((struct patch *) -2)
2653 #define PATH_WAS_DELETED ((struct patch *) -1)
2655 static int to_be_deleted(struct patch *patch)
2657 return patch == PATH_TO_BE_DELETED;
2660 static int was_deleted(struct patch *patch)
2662 return patch == PATH_WAS_DELETED;
2665 static void add_to_fn_table(struct patch *patch)
2667 struct string_list_item *item;
2670 * Always add new_name unless patch is a deletion
2671 * This should cover the cases for normal diffs,
2672 * file creations and copies
2674 if (patch->new_name != NULL) {
2675 item = string_list_insert(&fn_table, patch->new_name);
2680 * store a failure on rename/deletion cases because
2681 * later chunks shouldn't patch old names
2683 if ((patch->new_name == NULL) || (patch->is_rename)) {
2684 item = string_list_insert(&fn_table, patch->old_name);
2685 item->util = PATH_WAS_DELETED;
2689 static void prepare_fn_table(struct patch *patch)
2692 * store information about incoming file deletion
2695 if ((patch->new_name == NULL) || (patch->is_rename)) {
2696 struct string_list_item *item;
2697 item = string_list_insert(&fn_table, patch->old_name);
2698 item->util = PATH_TO_BE_DELETED;
2700 patch = patch->next;
2704 static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce)
2706 struct strbuf buf = STRBUF_INIT;
2710 struct patch *tpatch;
2712 if (!(patch->is_copy || patch->is_rename) &&
2713 (tpatch = in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {
2714 if (was_deleted(tpatch)) {
2715 return error("patch %s has been renamed/deleted",
2718 /* We have a patched copy in memory use that */
2719 strbuf_add(&buf, tpatch->result, tpatch->resultsize);
2720 } else if (cached) {
2721 if (read_file_or_gitlink(ce, &buf))
2722 return error("read of %s failed", patch->old_name);
2723 } else if (patch->old_name) {
2724 if (S_ISGITLINK(patch->old_mode)) {
2726 read_file_or_gitlink(ce, &buf);
2729 * There is no way to apply subproject
2730 * patch without looking at the index.
2732 patch->fragments = NULL;
2735 if (read_old_data(st, patch->old_name, &buf))
2736 return error("read of %s failed", patch->old_name);
2740 img = strbuf_detach(&buf, &len);
2741 prepare_image(&image, img, len, !patch->is_binary);
2743 if (apply_fragments(&image, patch) < 0)
2744 return -1; /* note with --reject this succeeds. */
2745 patch->result = image.buf;
2746 patch->resultsize = image.len;
2747 add_to_fn_table(patch);
2748 free(image.line_allocated);
2750 if (0 < patch->is_delete && patch->resultsize)
2751 return error("removal patch leaves file contents");
2756 static int check_to_create_blob(const char *new_name, int ok_if_exists)
2759 if (!lstat(new_name, &nst)) {
2760 if (S_ISDIR(nst.st_mode) || ok_if_exists)
2763 * A leading component of new_name might be a symlink
2764 * that is going to be removed with this patch, but
2765 * still pointing at somewhere that has the path.
2766 * In such a case, path "new_name" does not exist as
2767 * far as git is concerned.
2769 if (has_symlink_leading_path(new_name, strlen(new_name)))
2772 return error("%s: already exists in working directory", new_name);
2774 else if ((errno != ENOENT) && (errno != ENOTDIR))
2775 return error("%s: %s", new_name, strerror(errno));
2779 static int verify_index_match(struct cache_entry *ce, struct stat *st)
2781 if (S_ISGITLINK(ce->ce_mode)) {
2782 if (!S_ISDIR(st->st_mode))
2786 return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
2789 static int check_preimage(struct patch *patch, struct cache_entry **ce, struct stat *st)
2791 const char *old_name = patch->old_name;
2792 struct patch *tpatch = NULL;
2794 unsigned st_mode = 0;
2797 * Make sure that we do not have local modifications from the
2798 * index when we are looking at the index. Also make sure
2799 * we have the preimage file to be patched in the work tree,
2800 * unless --cached, which tells git to apply only in the index.
2805 assert(patch->is_new <= 0);
2807 if (!(patch->is_copy || patch->is_rename) &&
2808 (tpatch = in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {
2809 if (was_deleted(tpatch))
2810 return error("%s: has been deleted/renamed", old_name);
2811 st_mode = tpatch->new_mode;
2812 } else if (!cached) {
2813 stat_ret = lstat(old_name, st);
2814 if (stat_ret && errno != ENOENT)
2815 return error("%s: %s", old_name, strerror(errno));
2818 if (to_be_deleted(tpatch))
2821 if (check_index && !tpatch) {
2822 int pos = cache_name_pos(old_name, strlen(old_name));
2824 if (patch->is_new < 0)
2826 return error("%s: does not exist in index", old_name);
2828 *ce = active_cache[pos];
2830 struct checkout costate;
2832 memset(&costate, 0, sizeof(costate));
2833 costate.base_dir = "";
2834 costate.refresh_cache = 1;
2835 if (checkout_entry(*ce, &costate, NULL) ||
2836 lstat(old_name, st))
2839 if (!cached && verify_index_match(*ce, st))
2840 return error("%s: does not match index", old_name);
2842 st_mode = (*ce)->ce_mode;
2843 } else if (stat_ret < 0) {
2844 if (patch->is_new < 0)
2846 return error("%s: %s", old_name, strerror(errno));
2849 if (!cached && !tpatch)
2850 st_mode = ce_mode_from_stat(*ce, st->st_mode);
2852 if (patch->is_new < 0)
2854 if (!patch->old_mode)
2855 patch->old_mode = st_mode;
2856 if ((st_mode ^ patch->old_mode) & S_IFMT)
2857 return error("%s: wrong type", old_name);
2858 if (st_mode != patch->old_mode)
2859 warning("%s has type %o, expected %o",
2860 old_name, st_mode, patch->old_mode);
2861 if (!patch->new_mode && !patch->is_delete)
2862 patch->new_mode = st_mode;
2867 patch->is_delete = 0;
2868 patch->old_name = NULL;
2872 static int check_patch(struct patch *patch)
2875 const char *old_name = patch->old_name;
2876 const char *new_name = patch->new_name;
2877 const char *name = old_name ? old_name : new_name;
2878 struct cache_entry *ce = NULL;
2879 struct patch *tpatch;
2883 patch->rejected = 1; /* we will drop this after we succeed */
2885 status = check_preimage(patch, &ce, &st);
2888 old_name = patch->old_name;
2890 if ((tpatch = in_fn_table(new_name)) &&
2891 (was_deleted(tpatch) || to_be_deleted(tpatch)))
2893 * A type-change diff is always split into a patch to
2894 * delete old, immediately followed by a patch to
2895 * create new (see diff.c::run_diff()); in such a case
2896 * it is Ok that the entry to be deleted by the
2897 * previous patch is still in the working tree and in
2905 ((0 < patch->is_new) | (0 < patch->is_rename) | patch->is_copy)) {
2907 cache_name_pos(new_name, strlen(new_name)) >= 0 &&
2909 return error("%s: already exists in index", new_name);
2911 int err = check_to_create_blob(new_name, ok_if_exists);
2915 if (!patch->new_mode) {
2916 if (0 < patch->is_new)
2917 patch->new_mode = S_IFREG | 0644;
2919 patch->new_mode = patch->old_mode;
2923 if (new_name && old_name) {
2924 int same = !strcmp(old_name, new_name);
2925 if (!patch->new_mode)
2926 patch->new_mode = patch->old_mode;
2927 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
2928 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
2929 patch->new_mode, new_name, patch->old_mode,
2930 same ? "" : " of ", same ? "" : old_name);
2933 if (apply_data(patch, &st, ce) < 0)
2934 return error("%s: patch does not apply", name);
2935 patch->rejected = 0;
2939 static int check_patch_list(struct patch *patch)
2943 prepare_fn_table(patch);
2945 if (apply_verbosely)
2946 say_patch_name(stderr,
2947 "Checking patch ", patch, "...\n");
2948 err |= check_patch(patch);
2949 patch = patch->next;
2954 /* This function tries to read the sha1 from the current index */
2955 static int get_current_sha1(const char *path, unsigned char *sha1)
2959 if (read_cache() < 0)
2961 pos = cache_name_pos(path, strlen(path));
2964 hashcpy(sha1, active_cache[pos]->sha1);
2968 /* Build an index that contains the just the files needed for a 3way merge */
2969 static void build_fake_ancestor(struct patch *list, const char *filename)
2971 struct patch *patch;
2972 struct index_state result = { NULL };
2975 /* Once we start supporting the reverse patch, it may be
2976 * worth showing the new sha1 prefix, but until then...
2978 for (patch = list; patch; patch = patch->next) {
2979 const unsigned char *sha1_ptr;
2980 unsigned char sha1[20];
2981 struct cache_entry *ce;
2984 name = patch->old_name ? patch->old_name : patch->new_name;
2985 if (0 < patch->is_new)
2987 else if (get_sha1(patch->old_sha1_prefix, sha1))
2988 /* git diff has no index line for mode/type changes */
2989 if (!patch->lines_added && !patch->lines_deleted) {
2990 if (get_current_sha1(patch->new_name, sha1) ||
2991 get_current_sha1(patch->old_name, sha1))
2992 die("mode change for %s, which is not "
2993 "in current HEAD", name);
2996 die("sha1 information is lacking or useless "
3001 ce = make_cache_entry(patch->old_mode, sha1_ptr, name, 0, 0);
3003 die("make_cache_entry failed for path '%s'", name);
3004 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))
3005 die ("Could not add %s to temporary index", name);
3008 fd = open(filename, O_WRONLY | O_CREAT, 0666);
3009 if (fd < 0 || write_index(&result, fd) || close(fd))
3010 die ("Could not write temporary index to %s", filename);
3012 discard_index(&result);
3015 static void stat_patch_list(struct patch *patch)
3017 int files, adds, dels;
3019 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
3021 adds += patch->lines_added;
3022 dels += patch->lines_deleted;
3026 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
3029 static void numstat_patch_list(struct patch *patch)
3031 for ( ; patch; patch = patch->next) {
3033 name = patch->new_name ? patch->new_name : patch->old_name;
3034 if (patch->is_binary)
3037 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
3038 write_name_quoted(name, stdout, line_termination);
3042 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
3045 printf(" %s mode %06o %s\n", newdelete, mode, name);
3047 printf(" %s %s\n", newdelete, name);
3050 static void show_mode_change(struct patch *p, int show_name)
3052 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
3054 printf(" mode change %06o => %06o %s\n",
3055 p->old_mode, p->new_mode, p->new_name);
3057 printf(" mode change %06o => %06o\n",
3058 p->old_mode, p->new_mode);
3062 static void show_rename_copy(struct patch *p)
3064 const char *renamecopy = p->is_rename ? "rename" : "copy";
3065 const char *old, *new;
3067 /* Find common prefix */
3071 const char *slash_old, *slash_new;
3072 slash_old = strchr(old, '/');
3073 slash_new = strchr(new, '/');
3076 slash_old - old != slash_new - new ||
3077 memcmp(old, new, slash_new - new))
3079 old = slash_old + 1;
3080 new = slash_new + 1;
3082 /* p->old_name thru old is the common prefix, and old and new
3083 * through the end of names are renames
3085 if (old != p->old_name)
3086 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
3087 (int)(old - p->old_name), p->old_name,
3088 old, new, p->score);
3090 printf(" %s %s => %s (%d%%)\n", renamecopy,
3091 p->old_name, p->new_name, p->score);
3092 show_mode_change(p, 0);
3095 static void summary_patch_list(struct patch *patch)
3099 for (p = patch; p; p = p->next) {
3101 show_file_mode_name("create", p->new_mode, p->new_name);
3102 else if (p->is_delete)
3103 show_file_mode_name("delete", p->old_mode, p->old_name);
3105 if (p->is_rename || p->is_copy)
3106 show_rename_copy(p);
3109 printf(" rewrite %s (%d%%)\n",
3110 p->new_name, p->score);
3111 show_mode_change(p, 0);
3114 show_mode_change(p, 1);
3120 static void patch_stats(struct patch *patch)
3122 int lines = patch->lines_added + patch->lines_deleted;
3124 if (lines > max_change)
3126 if (patch->old_name) {
3127 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
3129 len = strlen(patch->old_name);
3133 if (patch->new_name) {
3134 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
3136 len = strlen(patch->new_name);
3142 static void remove_file(struct patch *patch, int rmdir_empty)
3145 if (remove_file_from_cache(patch->old_name) < 0)
3146 die("unable to remove %s from index", patch->old_name);
3149 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
3150 remove_path(patch->old_name);
3155 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
3158 struct cache_entry *ce;
3159 int namelen = strlen(path);
3160 unsigned ce_size = cache_entry_size(namelen);
3165 ce = xcalloc(1, ce_size);
3166 memcpy(ce->name, path, namelen);
3167 ce->ce_mode = create_ce_mode(mode);
3168 ce->ce_flags = namelen;
3169 if (S_ISGITLINK(mode)) {
3170 const char *s = buf;
3172 if (get_sha1_hex(s + strlen("Subproject commit "), ce->sha1))
3173 die("corrupt patch for subproject %s", path);
3176 if (lstat(path, &st) < 0)
3177 die_errno("unable to stat newly created file '%s'",
3179 fill_stat_cache_info(ce, &st);
3181 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
3182 die("unable to create backing store for newly created file %s", path);
3184 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
3185 die("unable to add cache entry for %s", path);
3188 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
3191 struct strbuf nbuf = STRBUF_INIT;
3193 if (S_ISGITLINK(mode)) {
3195 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
3197 return mkdir(path, 0777);
3200 if (has_symlinks && S_ISLNK(mode))
3201 /* Although buf:size is counted string, it also is NUL
3204 return symlink(buf, path);
3206 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
3210 if (convert_to_working_tree(path, buf, size, &nbuf)) {
3214 write_or_die(fd, buf, size);
3215 strbuf_release(&nbuf);
3218 die_errno("closing file '%s'", path);
3223 * We optimistically assume that the directories exist,
3224 * which is true 99% of the time anyway. If they don't,
3225 * we create them and try again.
3227 static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
3231 if (!try_create_file(path, mode, buf, size))
3234 if (errno == ENOENT) {
3235 if (safe_create_leading_directories(path))
3237 if (!try_create_file(path, mode, buf, size))
3241 if (errno == EEXIST || errno == EACCES) {
3242 /* We may be trying to create a file where a directory
3246 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
3250 if (errno == EEXIST) {
3251 unsigned int nr = getpid();
3254 char newpath[PATH_MAX];
3255 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
3256 if (!try_create_file(newpath, mode, buf, size)) {
3257 if (!rename(newpath, path))
3259 unlink_or_warn(newpath);
3262 if (errno != EEXIST)
3267 die_errno("unable to write file '%s' mode %o", path, mode);
3270 static void create_file(struct patch *patch)
3272 char *path = patch->new_name;
3273 unsigned mode = patch->new_mode;
3274 unsigned long size = patch->resultsize;
3275 char *buf = patch->result;
3278 mode = S_IFREG | 0644;
3279 create_one_file(path, mode, buf, size);
3280 add_index_file(path, mode, buf, size);
3283 /* phase zero is to remove, phase one is to create */
3284 static void write_out_one_result(struct patch *patch, int phase)
3286 if (patch->is_delete > 0) {
3288 remove_file(patch, 1);
3291 if (patch->is_new > 0 || patch->is_copy) {
3297 * Rename or modification boils down to the same
3298 * thing: remove the old, write the new
3301 remove_file(patch, patch->is_rename);
3306 static int write_out_one_reject(struct patch *patch)
3309 char namebuf[PATH_MAX];
3310 struct fragment *frag;
3313 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
3314 if (!frag->rejected)
3320 if (apply_verbosely)
3321 say_patch_name(stderr,
3322 "Applied patch ", patch, " cleanly.\n");
3326 /* This should not happen, because a removal patch that leaves
3327 * contents are marked "rejected" at the patch level.
3329 if (!patch->new_name)
3330 die("internal error");
3332 /* Say this even without --verbose */
3333 say_patch_name(stderr, "Applying patch ", patch, " with");
3334 fprintf(stderr, " %d rejects...\n", cnt);
3336 cnt = strlen(patch->new_name);
3337 if (ARRAY_SIZE(namebuf) <= cnt + 5) {
3338 cnt = ARRAY_SIZE(namebuf) - 5;
3339 warning("truncating .rej filename to %.*s.rej",
3340 cnt - 1, patch->new_name);
3342 memcpy(namebuf, patch->new_name, cnt);
3343 memcpy(namebuf + cnt, ".rej", 5);
3345 rej = fopen(namebuf, "w");
3347 return error("cannot open %s: %s", namebuf, strerror(errno));
3349 /* Normal git tools never deal with .rej, so do not pretend
3350 * this is a git patch by saying --git nor give extended
3351 * headers. While at it, maybe please "kompare" that wants
3352 * the trailing TAB and some garbage at the end of line ;-).
3354 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
3355 patch->new_name, patch->new_name);
3356 for (cnt = 1, frag = patch->fragments;
3358 cnt++, frag = frag->next) {
3359 if (!frag->rejected) {
3360 fprintf(stderr, "Hunk #%d applied cleanly.\n", cnt);
3363 fprintf(stderr, "Rejected hunk #%d.\n", cnt);
3364 fprintf(rej, "%.*s", frag->size, frag->patch);
3365 if (frag->patch[frag->size-1] != '\n')
3372 static int write_out_results(struct patch *list, int skipped_patch)
3378 if (!list && !skipped_patch)
3379 return error("No changes");
3381 for (phase = 0; phase < 2; phase++) {
3387 write_out_one_result(l, phase);
3388 if (phase == 1 && write_out_one_reject(l))
3397 static struct lock_file lock_file;
3399 static struct string_list limit_by_name;
3400 static int has_include;
3401 static void add_name_limit(const char *name, int exclude)
3403 struct string_list_item *it;
3405 it = string_list_append(&limit_by_name, name);
3406 it->util = exclude ? NULL : (void *) 1;
3409 static int use_patch(struct patch *p)
3411 const char *pathname = p->new_name ? p->new_name : p->old_name;
3414 /* Paths outside are not touched regardless of "--include" */
3415 if (0 < prefix_length) {
3416 int pathlen = strlen(pathname);
3417 if (pathlen <= prefix_length ||
3418 memcmp(prefix, pathname, prefix_length))
3422 /* See if it matches any of exclude/include rule */
3423 for (i = 0; i < limit_by_name.nr; i++) {
3424 struct string_list_item *it = &limit_by_name.items[i];
3425 if (!fnmatch(it->string, pathname, 0))
3426 return (it->util != NULL);
3430 * If we had any include, a path that does not match any rule is
3431 * not used. Otherwise, we saw bunch of exclude rules (or none)
3432 * and such a path is used.
3434 return !has_include;
3438 static void prefix_one(char **name)
3440 char *old_name = *name;
3443 *name = xstrdup(prefix_filename(prefix, prefix_length, *name));
3447 static void prefix_patches(struct patch *p)
3449 if (!prefix || p->is_toplevel_relative)
3451 for ( ; p; p = p->next) {
3452 if (p->new_name == p->old_name) {
3453 char *prefixed = p->new_name;
3454 prefix_one(&prefixed);
3455 p->new_name = p->old_name = prefixed;
3458 prefix_one(&p->new_name);
3459 prefix_one(&p->old_name);
3464 #define INACCURATE_EOF (1<<0)
3465 #define RECOUNT (1<<1)
3467 static int apply_patch(int fd, const char *filename, int options)
3470 struct strbuf buf = STRBUF_INIT;
3471 struct patch *list = NULL, **listp = &list;
3472 int skipped_patch = 0;
3474 /* FIXME - memory leak when using multiple patch files as inputs */
3475 memset(&fn_table, 0, sizeof(struct string_list));
3476 patch_input_file = filename;
3477 read_patch_file(&buf, fd);
3479 while (offset < buf.len) {
3480 struct patch *patch;
3483 patch = xcalloc(1, sizeof(*patch));
3484 patch->inaccurate_eof = !!(options & INACCURATE_EOF);
3485 patch->recount = !!(options & RECOUNT);
3486 nr = parse_chunk(buf.buf + offset, buf.len - offset, patch);
3489 if (apply_in_reverse)
3490 reverse_patches(patch);
3492 prefix_patches(patch);
3493 if (use_patch(patch)) {
3496 listp = &patch->next;
3499 /* perhaps free it a bit better? */
3506 if (whitespace_error && (ws_error_action == die_on_ws_error))
3509 update_index = check_index && apply;
3510 if (update_index && newfd < 0)
3511 newfd = hold_locked_index(&lock_file, 1);
3514 if (read_cache() < 0)
3515 die("unable to read index file");
3518 if ((check || apply) &&
3519 check_patch_list(list) < 0 &&
3523 if (apply && write_out_results(list, skipped_patch))
3527 build_fake_ancestor(list, fake_ancestor);
3530 stat_patch_list(list);
3533 numstat_patch_list(list);
3536 summary_patch_list(list);
3538 strbuf_release(&buf);
3542 static int git_apply_config(const char *var, const char *value, void *cb)
3544 if (!strcmp(var, "apply.whitespace"))
3545 return git_config_string(&apply_default_whitespace, var, value);
3546 else if (!strcmp(var, "apply.ignorewhitespace"))
3547 return git_config_string(&apply_default_ignorewhitespace, var, value);
3548 return git_default_config(var, value, cb);
3551 static int option_parse_exclude(const struct option *opt,
3552 const char *arg, int unset)
3554 add_name_limit(arg, 1);
3558 static int option_parse_include(const struct option *opt,
3559 const char *arg, int unset)
3561 add_name_limit(arg, 0);
3566 static int option_parse_p(const struct option *opt,
3567 const char *arg, int unset)
3569 p_value = atoi(arg);
3574 static int option_parse_z(const struct option *opt,
3575 const char *arg, int unset)
3578 line_termination = '\n';
3580 line_termination = 0;
3584 static int option_parse_space_change(const struct option *opt,
3585 const char *arg, int unset)
3588 ws_ignore_action = ignore_ws_none;
3590 ws_ignore_action = ignore_ws_change;
3594 static int option_parse_whitespace(const struct option *opt,
3595 const char *arg, int unset)
3597 const char **whitespace_option = opt->value;
3599 *whitespace_option = arg;
3600 parse_whitespace_option(arg);
3604 static int option_parse_directory(const struct option *opt,
3605 const char *arg, int unset)
3607 root_len = strlen(arg);
3608 if (root_len && arg[root_len - 1] != '/') {
3610 root = new_root = xmalloc(root_len + 2);
3611 strcpy(new_root, arg);
3612 strcpy(new_root + root_len++, "/");
3618 int cmd_apply(int argc, const char **argv, const char *unused_prefix)
3624 int force_apply = 0;
3626 const char *whitespace_option = NULL;
3628 struct option builtin_apply_options[] = {
3629 { OPTION_CALLBACK, 0, "exclude", NULL, "path",
3630 "don't apply changes matching the given path",
3631 0, option_parse_exclude },
3632 { OPTION_CALLBACK, 0, "include", NULL, "path",
3633 "apply changes matching the given path",
3634 0, option_parse_include },
3635 { OPTION_CALLBACK, 'p', NULL, NULL, "num",
3636 "remove <num> leading slashes from traditional diff paths",
3637 0, option_parse_p },
3638 OPT_BOOLEAN(0, "no-add", &no_add,
3639 "ignore additions made by the patch"),
3640 OPT_BOOLEAN(0, "stat", &diffstat,
3641 "instead of applying the patch, output diffstat for the input"),
3642 { OPTION_BOOLEAN, 0, "allow-binary-replacement", &binary,
3643 NULL, "old option, now no-op",
3644 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },
3645 { OPTION_BOOLEAN, 0, "binary", &binary,
3646 NULL, "old option, now no-op",
3647 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },
3648 OPT_BOOLEAN(0, "numstat", &numstat,
3649 "shows number of added and deleted lines in decimal notation"),
3650 OPT_BOOLEAN(0, "summary", &summary,
3651 "instead of applying the patch, output a summary for the input"),
3652 OPT_BOOLEAN(0, "check", &check,
3653 "instead of applying the patch, see if the patch is applicable"),
3654 OPT_BOOLEAN(0, "index", &check_index,
3655 "make sure the patch is applicable to the current index"),
3656 OPT_BOOLEAN(0, "cached", &cached,
3657 "apply a patch without touching the working tree"),
3658 OPT_BOOLEAN(0, "apply", &force_apply,
3659 "also apply the patch (use with --stat/--summary/--check)"),
3660 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor,
3661 "build a temporary index based on embedded index information"),
3662 { OPTION_CALLBACK, 'z', NULL, NULL, NULL,
3663 "paths are separated with NUL character",
3664 PARSE_OPT_NOARG, option_parse_z },
3665 OPT_INTEGER('C', NULL, &p_context,
3666 "ensure at least <n> lines of context match"),
3667 { OPTION_CALLBACK, 0, "whitespace", &whitespace_option, "action",
3668 "detect new or modified lines that have whitespace errors",
3669 0, option_parse_whitespace },
3670 { OPTION_CALLBACK, 0, "ignore-space-change", NULL, NULL,
3671 "ignore changes in whitespace when finding context",
3672 PARSE_OPT_NOARG, option_parse_space_change },
3673 { OPTION_CALLBACK, 0, "ignore-whitespace", NULL, NULL,
3674 "ignore changes in whitespace when finding context",
3675 PARSE_OPT_NOARG, option_parse_space_change },
3676 OPT_BOOLEAN('R', "reverse", &apply_in_reverse,
3677 "apply the patch in reverse"),
3678 OPT_BOOLEAN(0, "unidiff-zero", &unidiff_zero,
3679 "don't expect at least one line of context"),
3680 OPT_BOOLEAN(0, "reject", &apply_with_reject,
3681 "leave the rejected hunks in corresponding *.rej files"),
3682 OPT__VERBOSE(&apply_verbosely),
3683 OPT_BIT(0, "inaccurate-eof", &options,
3684 "tolerate incorrectly detected missing new-line at the end of file",
3686 OPT_BIT(0, "recount", &options,
3687 "do not trust the line counts in the hunk headers",
3689 { OPTION_CALLBACK, 0, "directory", NULL, "root",
3690 "prepend <root> to all filenames",
3691 0, option_parse_directory },
3695 prefix = setup_git_directory_gently(&is_not_gitdir);
3696 prefix_length = prefix ? strlen(prefix) : 0;
3697 git_config(git_apply_config, NULL);
3698 if (apply_default_whitespace)
3699 parse_whitespace_option(apply_default_whitespace);
3700 if (apply_default_ignorewhitespace)
3701 parse_ignorewhitespace_option(apply_default_ignorewhitespace);
3703 argc = parse_options(argc, argv, prefix, builtin_apply_options,
3706 if (apply_with_reject)
3707 apply = apply_verbosely = 1;
3708 if (!force_apply && (diffstat || numstat || summary || check || fake_ancestor))
3710 if (check_index && is_not_gitdir)
3711 die("--index outside a repository");
3714 die("--cached outside a repository");
3717 for (i = 0; i < argc; i++) {
3718 const char *arg = argv[i];
3721 if (!strcmp(arg, "-")) {
3722 errs |= apply_patch(0, "<stdin>", options);
3725 } else if (0 < prefix_length)
3726 arg = prefix_filename(prefix, prefix_length, arg);
3728 fd = open(arg, O_RDONLY);
3730 die_errno("can't open patch '%s'", arg);
3732 set_default_whitespace_mode(whitespace_option);
3733 errs |= apply_patch(fd, arg, options);
3736 set_default_whitespace_mode(whitespace_option);
3738 errs |= apply_patch(0, "<stdin>", options);
3739 if (whitespace_error) {
3740 if (squelch_whitespace_errors &&
3741 squelch_whitespace_errors < whitespace_error) {
3743 whitespace_error - squelch_whitespace_errors;
3744 warning("squelched %d "
3745 "whitespace error%s",
3747 squelched == 1 ? "" : "s");
3749 if (ws_error_action == die_on_ws_error)
3750 die("%d line%s add%s whitespace errors.",
3752 whitespace_error == 1 ? "" : "s",
3753 whitespace_error == 1 ? "s" : "");
3754 if (applied_after_fixing_ws && apply)
3755 warning("%d line%s applied after"
3756 " fixing whitespace errors.",
3757 applied_after_fixing_ws,
3758 applied_after_fixing_ws == 1 ? "" : "s");
3759 else if (whitespace_error)
3760 warning("%d line%s add%s whitespace errors.",
3762 whitespace_error == 1 ? "" : "s",
3763 whitespace_error == 1 ? "s" : "");
3767 if (write_cache(newfd, active_cache, active_nr) ||
3768 commit_locked_index(&lock_file))
3769 die("Unable to write new index file");