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;
46 static int allow_overlap;
48 static const char *fake_ancestor;
49 static int line_termination = '\n';
50 static unsigned int p_context = UINT_MAX;
51 static const char * const apply_usage[] = {
52 "git apply [options] [<patch>...]",
56 static enum ws_error_action {
61 } ws_error_action = warn_on_ws_error;
62 static int whitespace_error;
63 static int squelch_whitespace_errors = 5;
64 static int applied_after_fixing_ws;
66 static enum ws_ignore {
69 } ws_ignore_action = ignore_ws_none;
72 static const char *patch_input_file;
73 static const char *root;
75 static int read_stdin = 1;
78 static void parse_whitespace_option(const char *option)
81 ws_error_action = warn_on_ws_error;
84 if (!strcmp(option, "warn")) {
85 ws_error_action = warn_on_ws_error;
88 if (!strcmp(option, "nowarn")) {
89 ws_error_action = nowarn_ws_error;
92 if (!strcmp(option, "error")) {
93 ws_error_action = die_on_ws_error;
96 if (!strcmp(option, "error-all")) {
97 ws_error_action = die_on_ws_error;
98 squelch_whitespace_errors = 0;
101 if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
102 ws_error_action = correct_ws_error;
105 die("unrecognized whitespace option '%s'", option);
108 static void parse_ignorewhitespace_option(const char *option)
110 if (!option || !strcmp(option, "no") ||
111 !strcmp(option, "false") || !strcmp(option, "never") ||
112 !strcmp(option, "none")) {
113 ws_ignore_action = ignore_ws_none;
116 if (!strcmp(option, "change")) {
117 ws_ignore_action = ignore_ws_change;
120 die("unrecognized whitespace ignore option '%s'", option);
123 static void set_default_whitespace_mode(const char *whitespace_option)
125 if (!whitespace_option && !apply_default_whitespace)
126 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error);
130 * For "diff-stat" like behaviour, we keep track of the biggest change
131 * we've seen, and the longest filename. That allows us to do simple
134 static int max_change, max_len;
137 * Various "current state", notably line numbers and what
138 * file (and how) we're patching right now.. The "is_xxxx"
139 * things are flags, where -1 means "don't know yet".
141 static int linenr = 1;
144 * This represents one "hunk" from a patch, starting with
145 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
146 * patch text is pointed at by patch, and its byte length
147 * is stored in size. leading and trailing are the number
151 unsigned long leading, trailing;
152 unsigned long oldpos, oldlines;
153 unsigned long newpos, newlines;
158 struct fragment *next;
162 * When dealing with a binary patch, we reuse "leading" field
163 * to store the type of the binary hunk, either deflated "delta"
164 * or deflated "literal".
166 #define binary_patch_method leading
167 #define BINARY_DELTA_DEFLATED 1
168 #define BINARY_LITERAL_DEFLATED 2
171 * This represents a "patch" to a file, both metainfo changes
172 * such as creation/deletion, filemode and content changes represented
173 * as a series of fragments.
176 char *new_name, *old_name, *def_name;
177 unsigned int old_mode, new_mode;
178 int is_new, is_delete; /* -1 = unknown, 0 = false, 1 = true */
181 unsigned long deflate_origlen;
182 int lines_added, lines_deleted;
184 unsigned int is_toplevel_relative:1;
185 unsigned int inaccurate_eof:1;
186 unsigned int is_binary:1;
187 unsigned int is_copy:1;
188 unsigned int is_rename:1;
189 unsigned int recount:1;
190 struct fragment *fragments;
193 char old_sha1_prefix[41];
194 char new_sha1_prefix[41];
199 * A line in a file, len-bytes long (includes the terminating LF,
200 * except for an incomplete line at the end if the file ends with
201 * one), and its contents hashes to 'hash'.
207 #define LINE_COMMON 1
208 #define LINE_PATCHED 2
212 * This represents a "file", which is an array of "lines".
219 struct line *line_allocated;
224 * Records filenames that have been touched, in order to handle
225 * the case where more than one patches touch the same file.
228 static struct string_list fn_table;
230 static uint32_t hash_line(const char *cp, size_t len)
234 for (i = 0, h = 0; i < len; i++) {
235 if (!isspace(cp[i])) {
236 h = h * 3 + (cp[i] & 0xff);
243 * Compare lines s1 of length n1 and s2 of length n2, ignoring
244 * whitespace difference. Returns 1 if they match, 0 otherwise
246 static int fuzzy_matchlines(const char *s1, size_t n1,
247 const char *s2, size_t n2)
249 const char *last1 = s1 + n1 - 1;
250 const char *last2 = s2 + n2 - 1;
253 /* ignore line endings */
254 while ((*last1 == '\r') || (*last1 == '\n'))
256 while ((*last2 == '\r') || (*last2 == '\n'))
259 /* skip leading whitespace */
260 while (isspace(*s1) && (s1 <= last1))
262 while (isspace(*s2) && (s2 <= last2))
264 /* early return if both lines are empty */
265 if ((s1 > last1) && (s2 > last2))
268 result = *s1++ - *s2++;
270 * Skip whitespace inside. We check for whitespace on
271 * both buffers because we don't want "a b" to match
274 if (isspace(*s1) && isspace(*s2)) {
275 while (isspace(*s1) && s1 <= last1)
277 while (isspace(*s2) && s2 <= last2)
281 * If we reached the end on one side only,
285 ((s2 > last2) && (s1 <= last1)) ||
286 ((s1 > last1) && (s2 <= last2)))
288 if ((s1 > last1) && (s2 > last2))
295 static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
297 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
298 img->line_allocated[img->nr].len = len;
299 img->line_allocated[img->nr].hash = hash_line(bol, len);
300 img->line_allocated[img->nr].flag = flag;
304 static void prepare_image(struct image *image, char *buf, size_t len,
305 int prepare_linetable)
309 memset(image, 0, sizeof(*image));
313 if (!prepare_linetable)
316 ep = image->buf + image->len;
320 for (next = cp; next < ep && *next != '\n'; next++)
324 add_line_info(image, cp, next - cp, 0);
327 image->line = image->line_allocated;
330 static void clear_image(struct image *image)
337 static void say_patch_name(FILE *output, const char *pre,
338 struct patch *patch, const char *post)
341 if (patch->old_name && patch->new_name &&
342 strcmp(patch->old_name, patch->new_name)) {
343 quote_c_style(patch->old_name, NULL, output, 0);
344 fputs(" => ", output);
345 quote_c_style(patch->new_name, NULL, output, 0);
347 const char *n = patch->new_name;
350 quote_c_style(n, NULL, output, 0);
355 #define CHUNKSIZE (8192)
358 static void read_patch_file(struct strbuf *sb, int fd)
360 if (strbuf_read(sb, fd, 0) < 0)
361 die_errno("git apply: failed to read");
364 * Make sure that we have some slop in the buffer
365 * so that we can do speculative "memcmp" etc, and
366 * see to it that it is NUL-filled.
368 strbuf_grow(sb, SLOP);
369 memset(sb->buf + sb->len, 0, SLOP);
372 static unsigned long linelen(const char *buffer, unsigned long size)
374 unsigned long len = 0;
377 if (*buffer++ == '\n')
383 static int is_dev_null(const char *str)
385 return !memcmp("/dev/null", str, 9) && isspace(str[9]);
391 static int name_terminate(const char *name, int namelen, int c, int terminate)
393 if (c == ' ' && !(terminate & TERM_SPACE))
395 if (c == '\t' && !(terminate & TERM_TAB))
401 /* remove double slashes to make --index work with such filenames */
402 static char *squash_slash(char *name)
410 if ((name[j++] = name[i++]) == '/')
411 while (name[i] == '/')
418 static char *find_name_gnu(const char *line, char *def, int p_value)
420 struct strbuf name = STRBUF_INIT;
424 * Proposed "new-style" GNU patch/diff format; see
425 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
427 if (unquote_c_style(&name, line, NULL)) {
428 strbuf_release(&name);
432 for (cp = name.buf; p_value; p_value--) {
433 cp = strchr(cp, '/');
435 strbuf_release(&name);
441 /* name can later be freed, so we need
442 * to memmove, not just return cp
444 strbuf_remove(&name, 0, cp - name.buf);
447 strbuf_insert(&name, 0, root, root_len);
448 return squash_slash(strbuf_detach(&name, NULL));
451 static size_t sane_tz_len(const char *line, size_t len)
455 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
457 tz = line + len - strlen(" +0500");
459 if (tz[1] != '+' && tz[1] != '-')
462 for (p = tz + 2; p != line + len; p++)
466 return line + len - tz;
469 static size_t tz_with_colon_len(const char *line, size_t len)
473 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
475 tz = line + len - strlen(" +08:00");
477 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
480 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
481 !isdigit(*p++) || !isdigit(*p++))
484 return line + len - tz;
487 static size_t date_len(const char *line, size_t len)
489 const char *date, *p;
491 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
493 p = date = line + len - strlen("72-02-05");
495 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
496 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
497 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */
500 if (date - line >= strlen("19") &&
501 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */
502 date -= strlen("19");
504 return line + len - date;
507 static size_t short_time_len(const char *line, size_t len)
509 const char *time, *p;
511 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
513 p = time = line + len - strlen(" 07:01:32");
515 /* Permit 1-digit hours? */
517 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
518 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
519 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */
522 return line + len - time;
525 static size_t fractional_time_len(const char *line, size_t len)
530 /* Expected format: 19:41:17.620000023 */
531 if (!len || !isdigit(line[len - 1]))
535 /* Fractional seconds. */
536 while (p > line && isdigit(*p))
541 /* Hours, minutes, and whole seconds. */
542 n = short_time_len(line, p - line);
546 return line + len - p + n;
549 static size_t trailing_spaces_len(const char *line, size_t len)
553 /* Expected format: ' ' x (1 or more) */
554 if (!len || line[len - 1] != ' ')
561 return line + len - (p + 1);
568 static size_t diff_timestamp_len(const char *line, size_t len)
570 const char *end = line + len;
574 * Posix: 2010-07-05 19:41:17
575 * GNU: 2010-07-05 19:41:17.620000023 -0500
578 if (!isdigit(end[-1]))
581 n = sane_tz_len(line, end - line);
583 n = tz_with_colon_len(line, end - line);
586 n = short_time_len(line, end - line);
588 n = fractional_time_len(line, end - line);
591 n = date_len(line, end - line);
592 if (!n) /* No date. Too bad. */
596 if (end == line) /* No space before date. */
598 if (end[-1] == '\t') { /* Success! */
600 return line + len - end;
602 if (end[-1] != ' ') /* No space before date. */
605 /* Whitespace damage. */
606 end -= trailing_spaces_len(line, end - line);
607 return line + len - end;
610 static char *find_name_common(const char *line, char *def, int p_value,
611 const char *end, int terminate)
614 const char *start = NULL;
618 while (line != end) {
621 if (!end && isspace(c)) {
624 if (name_terminate(start, line-start, c, terminate))
628 if (c == '/' && !--p_value)
632 return squash_slash(def);
635 return squash_slash(def);
638 * Generally we prefer the shorter name, especially
639 * if the other one is just a variation of that with
640 * something else tacked on to the end (ie "file.orig"
644 int deflen = strlen(def);
645 if (deflen < len && !strncmp(start, def, deflen))
646 return squash_slash(def);
651 char *ret = xmalloc(root_len + len + 1);
653 memcpy(ret + root_len, start, len);
654 ret[root_len + len] = '\0';
655 return squash_slash(ret);
658 return squash_slash(xmemdupz(start, len));
661 static char *find_name(const char *line, char *def, int p_value, int terminate)
664 char *name = find_name_gnu(line, def, p_value);
669 return find_name_common(line, def, p_value, NULL, terminate);
672 static char *find_name_traditional(const char *line, char *def, int p_value)
674 size_t len = strlen(line);
678 char *name = find_name_gnu(line, def, p_value);
683 len = strchrnul(line, '\n') - line;
684 date_len = diff_timestamp_len(line, len);
686 return find_name_common(line, def, p_value, NULL, TERM_TAB);
689 return find_name_common(line, def, p_value, line + len, 0);
692 static int count_slashes(const char *cp)
704 * Given the string after "--- " or "+++ ", guess the appropriate
705 * p_value for the given patch.
707 static int guess_p_value(const char *nameline)
712 if (is_dev_null(nameline))
714 name = find_name_traditional(nameline, NULL, 0);
717 cp = strchr(name, '/');
722 * Does it begin with "a/$our-prefix" and such? Then this is
723 * very likely to apply to our directory.
725 if (!strncmp(name, prefix, prefix_length))
726 val = count_slashes(prefix);
729 if (!strncmp(cp, prefix, prefix_length))
730 val = count_slashes(prefix) + 1;
738 * Does the ---/+++ line has the POSIX timestamp after the last HT?
739 * GNU diff puts epoch there to signal a creation/deletion event. Is
740 * this such a timestamp?
742 static int has_epoch_timestamp(const char *nameline)
745 * We are only interested in epoch timestamp; any non-zero
746 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
747 * For the same reason, the date must be either 1969-12-31 or
748 * 1970-01-01, and the seconds part must be "00".
750 const char stamp_regexp[] =
751 "^(1969-12-31|1970-01-01)"
753 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
755 "([-+][0-2][0-9]:?[0-5][0-9])\n";
756 const char *timestamp = NULL, *cp, *colon;
757 static regex_t *stamp;
763 for (cp = nameline; *cp != '\n'; cp++) {
770 stamp = xmalloc(sizeof(*stamp));
771 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
772 warning("Cannot prepare timestamp regexp %s",
778 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
780 if (status != REG_NOMATCH)
781 warning("regexec returned %d for input: %s",
786 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
788 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
790 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
791 if (timestamp[m[3].rm_so] == '-')
792 zoneoffset = -zoneoffset;
795 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
796 * (west of GMT) or 1970-01-01 (east of GMT)
798 if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) ||
799 (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10)))
802 hourminute = (strtol(timestamp + 11, NULL, 10) * 60 +
803 strtol(timestamp + 14, NULL, 10) -
806 return ((zoneoffset < 0 && hourminute == 1440) ||
807 (0 <= zoneoffset && !hourminute));
811 * Get the name etc info from the ---/+++ lines of a traditional patch header
813 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
814 * files, we can happily check the index for a match, but for creating a
815 * new file we should try to match whatever "patch" does. I have no idea.
817 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
821 first += 4; /* skip "--- " */
822 second += 4; /* skip "+++ " */
823 if (!p_value_known) {
825 p = guess_p_value(first);
826 q = guess_p_value(second);
828 if (0 <= p && p == q) {
833 if (is_dev_null(first)) {
835 patch->is_delete = 0;
836 name = find_name_traditional(second, NULL, p_value);
837 patch->new_name = name;
838 } else if (is_dev_null(second)) {
840 patch->is_delete = 1;
841 name = find_name_traditional(first, NULL, p_value);
842 patch->old_name = name;
844 name = find_name_traditional(first, NULL, p_value);
845 name = find_name_traditional(second, name, p_value);
846 if (has_epoch_timestamp(first)) {
848 patch->is_delete = 0;
849 patch->new_name = name;
850 } else if (has_epoch_timestamp(second)) {
852 patch->is_delete = 1;
853 patch->old_name = name;
855 patch->old_name = patch->new_name = name;
859 die("unable to find filename in patch at line %d", linenr);
862 static int gitdiff_hdrend(const char *line, struct patch *patch)
868 * We're anal about diff header consistency, to make
869 * sure that we don't end up having strange ambiguous
870 * patches floating around.
872 * As a result, gitdiff_{old|new}name() will check
873 * their names against any previous information, just
876 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
878 if (!orig_name && !isnull)
879 return find_name(line, NULL, p_value, TERM_TAB);
888 die("git apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
889 another = find_name(line, NULL, p_value, TERM_TAB);
890 if (!another || memcmp(another, name, len + 1))
891 die("git apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
896 /* expect "/dev/null" */
897 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
898 die("git apply: bad git-diff - expected /dev/null on line %d", linenr);
903 static int gitdiff_oldname(const char *line, struct patch *patch)
905 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
909 static int gitdiff_newname(const char *line, struct patch *patch)
911 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
915 static int gitdiff_oldmode(const char *line, struct patch *patch)
917 patch->old_mode = strtoul(line, NULL, 8);
921 static int gitdiff_newmode(const char *line, struct patch *patch)
923 patch->new_mode = strtoul(line, NULL, 8);
927 static int gitdiff_delete(const char *line, struct patch *patch)
929 patch->is_delete = 1;
930 patch->old_name = patch->def_name;
931 return gitdiff_oldmode(line, patch);
934 static int gitdiff_newfile(const char *line, struct patch *patch)
937 patch->new_name = patch->def_name;
938 return gitdiff_newmode(line, patch);
941 static int gitdiff_copysrc(const char *line, struct patch *patch)
944 patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
948 static int gitdiff_copydst(const char *line, struct patch *patch)
951 patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
955 static int gitdiff_renamesrc(const char *line, struct patch *patch)
957 patch->is_rename = 1;
958 patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
962 static int gitdiff_renamedst(const char *line, struct patch *patch)
964 patch->is_rename = 1;
965 patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
969 static int gitdiff_similarity(const char *line, struct patch *patch)
971 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
976 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
978 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
983 static int gitdiff_index(const char *line, struct patch *patch)
986 * index line is N hexadecimal, "..", N hexadecimal,
987 * and optional space with octal mode.
989 const char *ptr, *eol;
992 ptr = strchr(line, '.');
993 if (!ptr || ptr[1] != '.' || 40 < ptr - line)
996 memcpy(patch->old_sha1_prefix, line, len);
997 patch->old_sha1_prefix[len] = 0;
1000 ptr = strchr(line, ' ');
1001 eol = strchr(line, '\n');
1003 if (!ptr || eol < ptr)
1009 memcpy(patch->new_sha1_prefix, line, len);
1010 patch->new_sha1_prefix[len] = 0;
1012 patch->old_mode = strtoul(ptr+1, NULL, 8);
1017 * This is normal for a diff that doesn't change anything: we'll fall through
1018 * into the next diff. Tell the parser to break out.
1020 static int gitdiff_unrecognized(const char *line, struct patch *patch)
1025 static const char *stop_at_slash(const char *line, int llen)
1027 int nslash = p_value;
1030 for (i = 0; i < llen; i++) {
1032 if (ch == '/' && --nslash <= 0)
1039 * This is to extract the same name that appears on "diff --git"
1040 * line. We do not find and return anything if it is a rename
1041 * patch, and it is OK because we will find the name elsewhere.
1042 * We need to reliably find name only when it is mode-change only,
1043 * creation or deletion of an empty file. In any of these cases,
1044 * both sides are the same name under a/ and b/ respectively.
1046 static char *git_header_name(char *line, int llen)
1049 const char *second = NULL;
1050 size_t len, line_len;
1052 line += strlen("diff --git ");
1053 llen -= strlen("diff --git ");
1057 struct strbuf first = STRBUF_INIT;
1058 struct strbuf sp = STRBUF_INIT;
1060 if (unquote_c_style(&first, line, &second))
1061 goto free_and_fail1;
1063 /* advance to the first slash */
1064 cp = stop_at_slash(first.buf, first.len);
1065 /* we do not accept absolute paths */
1066 if (!cp || cp == first.buf)
1067 goto free_and_fail1;
1068 strbuf_remove(&first, 0, cp + 1 - first.buf);
1071 * second points at one past closing dq of name.
1072 * find the second name.
1074 while ((second < line + llen) && isspace(*second))
1077 if (line + llen <= second)
1078 goto free_and_fail1;
1079 if (*second == '"') {
1080 if (unquote_c_style(&sp, second, NULL))
1081 goto free_and_fail1;
1082 cp = stop_at_slash(sp.buf, sp.len);
1083 if (!cp || cp == sp.buf)
1084 goto free_and_fail1;
1085 /* They must match, otherwise ignore */
1086 if (strcmp(cp + 1, first.buf))
1087 goto free_and_fail1;
1088 strbuf_release(&sp);
1089 return strbuf_detach(&first, NULL);
1092 /* unquoted second */
1093 cp = stop_at_slash(second, line + llen - second);
1094 if (!cp || cp == second)
1095 goto free_and_fail1;
1097 if (line + llen - cp != first.len + 1 ||
1098 memcmp(first.buf, cp, first.len))
1099 goto free_and_fail1;
1100 return strbuf_detach(&first, NULL);
1103 strbuf_release(&first);
1104 strbuf_release(&sp);
1108 /* unquoted first name */
1109 name = stop_at_slash(line, llen);
1110 if (!name || name == line)
1115 * since the first name is unquoted, a dq if exists must be
1116 * the beginning of the second name.
1118 for (second = name; second < line + llen; second++) {
1119 if (*second == '"') {
1120 struct strbuf sp = STRBUF_INIT;
1123 if (unquote_c_style(&sp, second, NULL))
1124 goto free_and_fail2;
1126 np = stop_at_slash(sp.buf, sp.len);
1127 if (!np || np == sp.buf)
1128 goto free_and_fail2;
1131 len = sp.buf + sp.len - np;
1132 if (len < second - name &&
1133 !strncmp(np, name, len) &&
1134 isspace(name[len])) {
1136 strbuf_remove(&sp, 0, np - sp.buf);
1137 return strbuf_detach(&sp, NULL);
1141 strbuf_release(&sp);
1147 * Accept a name only if it shows up twice, exactly the same
1150 second = strchr(name, '\n');
1153 line_len = second - name;
1154 for (len = 0 ; ; len++) {
1155 switch (name[len]) {
1160 case '\t': case ' ':
1161 second = stop_at_slash(name + len, line_len - len);
1165 if (second[len] == '\n' && !strncmp(name, second, len)) {
1166 return xmemdupz(name, len);
1172 /* Verify that we recognize the lines following a git header */
1173 static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
1175 unsigned long offset;
1177 /* A git diff has explicit new/delete information, so we don't guess */
1179 patch->is_delete = 0;
1182 * Some things may not have the old name in the
1183 * rest of the headers anywhere (pure mode changes,
1184 * or removing or adding empty files), so we get
1185 * the default name from the header.
1187 patch->def_name = git_header_name(line, len);
1188 if (patch->def_name && root) {
1189 char *s = xmalloc(root_len + strlen(patch->def_name) + 1);
1191 strcpy(s + root_len, patch->def_name);
1192 free(patch->def_name);
1193 patch->def_name = s;
1199 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
1200 static const struct opentry {
1202 int (*fn)(const char *, struct patch *);
1204 { "@@ -", gitdiff_hdrend },
1205 { "--- ", gitdiff_oldname },
1206 { "+++ ", gitdiff_newname },
1207 { "old mode ", gitdiff_oldmode },
1208 { "new mode ", gitdiff_newmode },
1209 { "deleted file mode ", gitdiff_delete },
1210 { "new file mode ", gitdiff_newfile },
1211 { "copy from ", gitdiff_copysrc },
1212 { "copy to ", gitdiff_copydst },
1213 { "rename old ", gitdiff_renamesrc },
1214 { "rename new ", gitdiff_renamedst },
1215 { "rename from ", gitdiff_renamesrc },
1216 { "rename to ", gitdiff_renamedst },
1217 { "similarity index ", gitdiff_similarity },
1218 { "dissimilarity index ", gitdiff_dissimilarity },
1219 { "index ", gitdiff_index },
1220 { "", gitdiff_unrecognized },
1224 len = linelen(line, size);
1225 if (!len || line[len-1] != '\n')
1227 for (i = 0; i < ARRAY_SIZE(optable); i++) {
1228 const struct opentry *p = optable + i;
1229 int oplen = strlen(p->str);
1230 if (len < oplen || memcmp(p->str, line, oplen))
1232 if (p->fn(line + oplen, patch) < 0)
1241 static int parse_num(const char *line, unsigned long *p)
1245 if (!isdigit(*line))
1247 *p = strtoul(line, &ptr, 10);
1251 static int parse_range(const char *line, int len, int offset, const char *expect,
1252 unsigned long *p1, unsigned long *p2)
1256 if (offset < 0 || offset >= len)
1261 digits = parse_num(line, p1);
1271 digits = parse_num(line+1, p2);
1280 ex = strlen(expect);
1283 if (memcmp(line, expect, ex))
1289 static void recount_diff(char *line, int size, struct fragment *fragment)
1291 int oldlines = 0, newlines = 0, ret = 0;
1294 warning("recount: ignore empty hunk");
1299 int len = linelen(line, size);
1307 case ' ': case '\n':
1319 ret = size < 3 || prefixcmp(line, "@@ ");
1322 ret = size < 5 || prefixcmp(line, "diff ");
1329 warning("recount: unexpected line: %.*s",
1330 (int)linelen(line, size), line);
1335 fragment->oldlines = oldlines;
1336 fragment->newlines = newlines;
1340 * Parse a unified diff fragment header of the
1341 * form "@@ -a,b +c,d @@"
1343 static int parse_fragment_header(char *line, int len, struct fragment *fragment)
1347 if (!len || line[len-1] != '\n')
1350 /* Figure out the number of lines in a fragment */
1351 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1352 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1357 static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
1359 unsigned long offset, len;
1361 patch->is_toplevel_relative = 0;
1362 patch->is_rename = patch->is_copy = 0;
1363 patch->is_new = patch->is_delete = -1;
1364 patch->old_mode = patch->new_mode = 0;
1365 patch->old_name = patch->new_name = NULL;
1366 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
1367 unsigned long nextlen;
1369 len = linelen(line, size);
1373 /* Testing this early allows us to take a few shortcuts.. */
1378 * Make sure we don't find any unconnected patch fragments.
1379 * That's a sign that we didn't find a header, and that a
1380 * patch has become corrupted/broken up.
1382 if (!memcmp("@@ -", line, 4)) {
1383 struct fragment dummy;
1384 if (parse_fragment_header(line, len, &dummy) < 0)
1386 die("patch fragment without header at line %d: %.*s",
1387 linenr, (int)len-1, line);
1394 * Git patch? It might not have a real patch, just a rename
1395 * or mode change, so we handle that specially
1397 if (!memcmp("diff --git ", line, 11)) {
1398 int git_hdr_len = parse_git_header(line, len, size, patch);
1399 if (git_hdr_len <= len)
1401 if (!patch->old_name && !patch->new_name) {
1402 if (!patch->def_name)
1403 die("git diff header lacks filename information when removing "
1404 "%d leading pathname components (line %d)" , p_value, linenr);
1405 patch->old_name = patch->new_name = patch->def_name;
1407 if (!patch->is_delete && !patch->new_name)
1408 die("git diff header lacks filename information "
1409 "(line %d)", linenr);
1410 patch->is_toplevel_relative = 1;
1411 *hdrsize = git_hdr_len;
1415 /* --- followed by +++ ? */
1416 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1420 * We only accept unified patches, so we want it to
1421 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1422 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1424 nextlen = linelen(line + len, size - len);
1425 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1428 /* Ok, we'll consider it a patch */
1429 parse_traditional_patch(line, line+len, patch);
1430 *hdrsize = len + nextlen;
1437 static void record_ws_error(unsigned result, const char *line, int len, int linenr)
1445 if (squelch_whitespace_errors &&
1446 squelch_whitespace_errors < whitespace_error)
1449 err = whitespace_error_string(result);
1450 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1451 patch_input_file, linenr, err, len, line);
1455 static void check_whitespace(const char *line, int len, unsigned ws_rule)
1457 unsigned result = ws_check(line + 1, len - 1, ws_rule);
1459 record_ws_error(result, line + 1, len - 2, linenr);
1463 * Parse a unified diff. Note that this really needs to parse each
1464 * fragment separately, since the only way to know the difference
1465 * between a "---" that is part of a patch, and a "---" that starts
1466 * the next patch is to look at the line counts..
1468 static int parse_fragment(char *line, unsigned long size,
1469 struct patch *patch, struct fragment *fragment)
1472 int len = linelen(line, size), offset;
1473 unsigned long oldlines, newlines;
1474 unsigned long leading, trailing;
1476 offset = parse_fragment_header(line, len, fragment);
1479 if (offset > 0 && patch->recount)
1480 recount_diff(line + offset, size - offset, fragment);
1481 oldlines = fragment->oldlines;
1482 newlines = fragment->newlines;
1486 /* Parse the thing.. */
1490 added = deleted = 0;
1493 offset += len, size -= len, line += len, linenr++) {
1494 if (!oldlines && !newlines)
1496 len = linelen(line, size);
1497 if (!len || line[len-1] != '\n')
1502 case '\n': /* newer GNU diff, an empty context line */
1506 if (!deleted && !added)
1511 if (apply_in_reverse &&
1512 ws_error_action != nowarn_ws_error)
1513 check_whitespace(line, len, patch->ws_rule);
1519 if (!apply_in_reverse &&
1520 ws_error_action != nowarn_ws_error)
1521 check_whitespace(line, len, patch->ws_rule);
1528 * We allow "\ No newline at end of file". Depending
1529 * on locale settings when the patch was produced we
1530 * don't know what this line looks like. The only
1531 * thing we do know is that it begins with "\ ".
1532 * Checking for 12 is just for sanity check -- any
1533 * l10n of "\ No newline..." is at least that long.
1536 if (len < 12 || memcmp(line, "\\ ", 2))
1541 if (oldlines || newlines)
1543 fragment->leading = leading;
1544 fragment->trailing = trailing;
1547 * If a fragment ends with an incomplete line, we failed to include
1548 * it in the above loop because we hit oldlines == newlines == 0
1551 if (12 < size && !memcmp(line, "\\ ", 2))
1552 offset += linelen(line, size);
1554 patch->lines_added += added;
1555 patch->lines_deleted += deleted;
1557 if (0 < patch->is_new && oldlines)
1558 return error("new file depends on old contents");
1559 if (0 < patch->is_delete && newlines)
1560 return error("deleted file still has contents");
1564 static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
1566 unsigned long offset = 0;
1567 unsigned long oldlines = 0, newlines = 0, context = 0;
1568 struct fragment **fragp = &patch->fragments;
1570 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1571 struct fragment *fragment;
1574 fragment = xcalloc(1, sizeof(*fragment));
1575 fragment->linenr = linenr;
1576 len = parse_fragment(line, size, patch, fragment);
1578 die("corrupt patch at line %d", linenr);
1579 fragment->patch = line;
1580 fragment->size = len;
1581 oldlines += fragment->oldlines;
1582 newlines += fragment->newlines;
1583 context += fragment->leading + fragment->trailing;
1586 fragp = &fragment->next;
1594 * If something was removed (i.e. we have old-lines) it cannot
1595 * be creation, and if something was added it cannot be
1596 * deletion. However, the reverse is not true; --unified=0
1597 * patches that only add are not necessarily creation even
1598 * though they do not have any old lines, and ones that only
1599 * delete are not necessarily deletion.
1601 * Unfortunately, a real creation/deletion patch do _not_ have
1602 * any context line by definition, so we cannot safely tell it
1603 * apart with --unified=0 insanity. At least if the patch has
1604 * more than one hunk it is not creation or deletion.
1606 if (patch->is_new < 0 &&
1607 (oldlines || (patch->fragments && patch->fragments->next)))
1609 if (patch->is_delete < 0 &&
1610 (newlines || (patch->fragments && patch->fragments->next)))
1611 patch->is_delete = 0;
1613 if (0 < patch->is_new && oldlines)
1614 die("new file %s depends on old contents", patch->new_name);
1615 if (0 < patch->is_delete && newlines)
1616 die("deleted file %s still has contents", patch->old_name);
1617 if (!patch->is_delete && !newlines && context)
1618 fprintf(stderr, "** warning: file %s becomes empty but "
1619 "is not deleted\n", patch->new_name);
1624 static inline int metadata_changes(struct patch *patch)
1626 return patch->is_rename > 0 ||
1627 patch->is_copy > 0 ||
1628 patch->is_new > 0 ||
1630 (patch->old_mode && patch->new_mode &&
1631 patch->old_mode != patch->new_mode);
1634 static char *inflate_it(const void *data, unsigned long size,
1635 unsigned long inflated_size)
1641 memset(&stream, 0, sizeof(stream));
1643 stream.next_in = (unsigned char *)data;
1644 stream.avail_in = size;
1645 stream.next_out = out = xmalloc(inflated_size);
1646 stream.avail_out = inflated_size;
1647 git_inflate_init(&stream);
1648 st = git_inflate(&stream, Z_FINISH);
1649 git_inflate_end(&stream);
1650 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1657 static struct fragment *parse_binary_hunk(char **buf_p,
1658 unsigned long *sz_p,
1663 * Expect a line that begins with binary patch method ("literal"
1664 * or "delta"), followed by the length of data before deflating.
1665 * a sequence of 'length-byte' followed by base-85 encoded data
1666 * should follow, terminated by a newline.
1668 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1669 * and we would limit the patch line to 66 characters,
1670 * so one line can fit up to 13 groups that would decode
1671 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1672 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1675 unsigned long size = *sz_p;
1676 char *buffer = *buf_p;
1678 unsigned long origlen;
1681 struct fragment *frag;
1683 llen = linelen(buffer, size);
1688 if (!prefixcmp(buffer, "delta ")) {
1689 patch_method = BINARY_DELTA_DEFLATED;
1690 origlen = strtoul(buffer + 6, NULL, 10);
1692 else if (!prefixcmp(buffer, "literal ")) {
1693 patch_method = BINARY_LITERAL_DEFLATED;
1694 origlen = strtoul(buffer + 8, NULL, 10);
1702 int byte_length, max_byte_length, newsize;
1703 llen = linelen(buffer, size);
1707 /* consume the blank line */
1713 * Minimum line is "A00000\n" which is 7-byte long,
1714 * and the line length must be multiple of 5 plus 2.
1716 if ((llen < 7) || (llen-2) % 5)
1718 max_byte_length = (llen - 2) / 5 * 4;
1719 byte_length = *buffer;
1720 if ('A' <= byte_length && byte_length <= 'Z')
1721 byte_length = byte_length - 'A' + 1;
1722 else if ('a' <= byte_length && byte_length <= 'z')
1723 byte_length = byte_length - 'a' + 27;
1726 /* if the input length was not multiple of 4, we would
1727 * have filler at the end but the filler should never
1730 if (max_byte_length < byte_length ||
1731 byte_length <= max_byte_length - 4)
1733 newsize = hunk_size + byte_length;
1734 data = xrealloc(data, newsize);
1735 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1737 hunk_size = newsize;
1742 frag = xcalloc(1, sizeof(*frag));
1743 frag->patch = inflate_it(data, hunk_size, origlen);
1747 frag->size = origlen;
1751 frag->binary_patch_method = patch_method;
1757 error("corrupt binary patch at line %d: %.*s",
1758 linenr-1, llen-1, buffer);
1762 static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1765 * We have read "GIT binary patch\n"; what follows is a line
1766 * that says the patch method (currently, either "literal" or
1767 * "delta") and the length of data before deflating; a
1768 * sequence of 'length-byte' followed by base-85 encoded data
1771 * When a binary patch is reversible, there is another binary
1772 * hunk in the same format, starting with patch method (either
1773 * "literal" or "delta") with the length of data, and a sequence
1774 * of length-byte + base-85 encoded data, terminated with another
1775 * empty line. This data, when applied to the postimage, produces
1778 struct fragment *forward;
1779 struct fragment *reverse;
1783 forward = parse_binary_hunk(&buffer, &size, &status, &used);
1784 if (!forward && !status)
1785 /* there has to be one hunk (forward hunk) */
1786 return error("unrecognized binary patch at line %d", linenr-1);
1788 /* otherwise we already gave an error message */
1791 reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1796 * Not having reverse hunk is not an error, but having
1797 * a corrupt reverse hunk is.
1799 free((void*) forward->patch);
1803 forward->next = reverse;
1804 patch->fragments = forward;
1805 patch->is_binary = 1;
1809 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
1811 int hdrsize, patchsize;
1812 int offset = find_header(buffer, size, &hdrsize, patch);
1817 patch->ws_rule = whitespace_rule(patch->new_name
1821 patchsize = parse_single_patch(buffer + offset + hdrsize,
1822 size - offset - hdrsize, patch);
1825 static const char *binhdr[] = {
1830 static const char git_binary[] = "GIT binary patch\n";
1832 int hd = hdrsize + offset;
1833 unsigned long llen = linelen(buffer + hd, size - hd);
1835 if (llen == sizeof(git_binary) - 1 &&
1836 !memcmp(git_binary, buffer + hd, llen)) {
1839 used = parse_binary(buffer + hd + llen,
1840 size - hd - llen, patch);
1842 patchsize = used + llen;
1846 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
1847 for (i = 0; binhdr[i]; i++) {
1848 int len = strlen(binhdr[i]);
1849 if (len < size - hd &&
1850 !memcmp(binhdr[i], buffer + hd, len)) {
1852 patch->is_binary = 1;
1859 /* Empty patch cannot be applied if it is a text patch
1860 * without metadata change. A binary patch appears
1863 if ((apply || check) &&
1864 (!patch->is_binary && !metadata_changes(patch)))
1865 die("patch with only garbage at line %d", linenr);
1868 return offset + hdrsize + patchsize;
1871 #define swap(a,b) myswap((a),(b),sizeof(a))
1873 #define myswap(a, b, size) do { \
1874 unsigned char mytmp[size]; \
1875 memcpy(mytmp, &a, size); \
1876 memcpy(&a, &b, size); \
1877 memcpy(&b, mytmp, size); \
1880 static void reverse_patches(struct patch *p)
1882 for (; p; p = p->next) {
1883 struct fragment *frag = p->fragments;
1885 swap(p->new_name, p->old_name);
1886 swap(p->new_mode, p->old_mode);
1887 swap(p->is_new, p->is_delete);
1888 swap(p->lines_added, p->lines_deleted);
1889 swap(p->old_sha1_prefix, p->new_sha1_prefix);
1891 for (; frag; frag = frag->next) {
1892 swap(frag->newpos, frag->oldpos);
1893 swap(frag->newlines, frag->oldlines);
1898 static const char pluses[] =
1899 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1900 static const char minuses[]=
1901 "----------------------------------------------------------------------";
1903 static void show_stats(struct patch *patch)
1905 struct strbuf qname = STRBUF_INIT;
1906 char *cp = patch->new_name ? patch->new_name : patch->old_name;
1909 quote_c_style(cp, &qname, NULL, 0);
1912 * "scale" the filename
1918 if (qname.len > max) {
1919 cp = strchr(qname.buf + qname.len + 3 - max, '/');
1921 cp = qname.buf + qname.len + 3 - max;
1922 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
1925 if (patch->is_binary) {
1926 printf(" %-*s | Bin\n", max, qname.buf);
1927 strbuf_release(&qname);
1931 printf(" %-*s |", max, qname.buf);
1932 strbuf_release(&qname);
1935 * scale the add/delete
1937 max = max + max_change > 70 ? 70 - max : max_change;
1938 add = patch->lines_added;
1939 del = patch->lines_deleted;
1941 if (max_change > 0) {
1942 int total = ((add + del) * max + max_change / 2) / max_change;
1943 add = (add * max + max_change / 2) / max_change;
1946 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
1947 add, pluses, del, minuses);
1950 static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
1952 switch (st->st_mode & S_IFMT) {
1954 if (strbuf_readlink(buf, path, st->st_size) < 0)
1955 return error("unable to read symlink %s", path);
1958 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
1959 return error("unable to open or read %s", path);
1960 convert_to_git(path, buf->buf, buf->len, buf, 0);
1968 * Update the preimage, and the common lines in postimage,
1969 * from buffer buf of length len. If postlen is 0 the postimage
1970 * is updated in place, otherwise it's updated on a new buffer
1974 static void update_pre_post_images(struct image *preimage,
1975 struct image *postimage,
1977 size_t len, size_t postlen)
1980 char *new, *old, *fixed;
1981 struct image fixed_preimage;
1984 * Update the preimage with whitespace fixes. Note that we
1985 * are not losing preimage->buf -- apply_one_fragment() will
1988 prepare_image(&fixed_preimage, buf, len, 1);
1989 assert(fixed_preimage.nr == preimage->nr);
1990 for (i = 0; i < preimage->nr; i++)
1991 fixed_preimage.line[i].flag = preimage->line[i].flag;
1992 free(preimage->line_allocated);
1993 *preimage = fixed_preimage;
1996 * Adjust the common context lines in postimage. This can be
1997 * done in-place when we are just doing whitespace fixing,
1998 * which does not make the string grow, but needs a new buffer
1999 * when ignoring whitespace causes the update, since in this case
2000 * we could have e.g. tabs converted to multiple spaces.
2001 * We trust the caller to tell us if the update can be done
2002 * in place (postlen==0) or not.
2004 old = postimage->buf;
2006 new = postimage->buf = xmalloc(postlen);
2009 fixed = preimage->buf;
2010 for (i = ctx = 0; i < postimage->nr; i++) {
2011 size_t len = postimage->line[i].len;
2012 if (!(postimage->line[i].flag & LINE_COMMON)) {
2013 /* an added line -- no counterparts in preimage */
2014 memmove(new, old, len);
2020 /* a common context -- skip it in the original postimage */
2023 /* and find the corresponding one in the fixed preimage */
2024 while (ctx < preimage->nr &&
2025 !(preimage->line[ctx].flag & LINE_COMMON)) {
2026 fixed += preimage->line[ctx].len;
2029 if (preimage->nr <= ctx)
2032 /* and copy it in, while fixing the line length */
2033 len = preimage->line[ctx].len;
2034 memcpy(new, fixed, len);
2037 postimage->line[i].len = len;
2041 /* Fix the length of the whole thing */
2042 postimage->len = new - postimage->buf;
2045 static int match_fragment(struct image *img,
2046 struct image *preimage,
2047 struct image *postimage,
2051 int match_beginning, int match_end)
2054 char *fixed_buf, *buf, *orig, *target;
2055 struct strbuf fixed;
2059 if (preimage->nr + try_lno <= img->nr) {
2061 * The hunk falls within the boundaries of img.
2063 preimage_limit = preimage->nr;
2064 if (match_end && (preimage->nr + try_lno != img->nr))
2066 } else if (ws_error_action == correct_ws_error &&
2067 (ws_rule & WS_BLANK_AT_EOF)) {
2069 * This hunk extends beyond the end of img, and we are
2070 * removing blank lines at the end of the file. This
2071 * many lines from the beginning of the preimage must
2072 * match with img, and the remainder of the preimage
2075 preimage_limit = img->nr - try_lno;
2078 * The hunk extends beyond the end of the img and
2079 * we are not removing blanks at the end, so we
2080 * should reject the hunk at this position.
2085 if (match_beginning && try_lno)
2088 /* Quick hash check */
2089 for (i = 0; i < preimage_limit; i++)
2090 if ((img->line[try_lno + i].flag & LINE_PATCHED) ||
2091 (preimage->line[i].hash != img->line[try_lno + i].hash))
2094 if (preimage_limit == preimage->nr) {
2096 * Do we have an exact match? If we were told to match
2097 * at the end, size must be exactly at try+fragsize,
2098 * otherwise try+fragsize must be still within the preimage,
2099 * and either case, the old piece should match the preimage
2103 ? (try + preimage->len == img->len)
2104 : (try + preimage->len <= img->len)) &&
2105 !memcmp(img->buf + try, preimage->buf, preimage->len))
2109 * The preimage extends beyond the end of img, so
2110 * there cannot be an exact match.
2112 * There must be one non-blank context line that match
2113 * a line before the end of img.
2117 buf = preimage->buf;
2119 for (i = 0; i < preimage_limit; i++)
2120 buf_end += preimage->line[i].len;
2122 for ( ; buf < buf_end; buf++)
2130 * No exact match. If we are ignoring whitespace, run a line-by-line
2131 * fuzzy matching. We collect all the line length information because
2132 * we need it to adjust whitespace if we match.
2134 if (ws_ignore_action == ignore_ws_change) {
2137 size_t postlen = postimage->len;
2141 for (i = 0; i < preimage_limit; i++) {
2142 size_t prelen = preimage->line[i].len;
2143 size_t imglen = img->line[try_lno+i].len;
2145 if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,
2146 preimage->buf + preoff, prelen))
2148 if (preimage->line[i].flag & LINE_COMMON)
2149 postlen += imglen - prelen;
2155 * Ok, the preimage matches with whitespace fuzz.
2157 * imgoff now holds the true length of the target that
2158 * matches the preimage before the end of the file.
2160 * Count the number of characters in the preimage that fall
2161 * beyond the end of the file and make sure that all of them
2162 * are whitespace characters. (This can only happen if
2163 * we are removing blank lines at the end of the file.)
2165 buf = preimage_eof = preimage->buf + preoff;
2166 for ( ; i < preimage->nr; i++)
2167 preoff += preimage->line[i].len;
2168 preimage_end = preimage->buf + preoff;
2169 for ( ; buf < preimage_end; buf++)
2174 * Update the preimage and the common postimage context
2175 * lines to use the same whitespace as the target.
2176 * If whitespace is missing in the target (i.e.
2177 * if the preimage extends beyond the end of the file),
2178 * use the whitespace from the preimage.
2180 extra_chars = preimage_end - preimage_eof;
2181 strbuf_init(&fixed, imgoff + extra_chars);
2182 strbuf_add(&fixed, img->buf + try, imgoff);
2183 strbuf_add(&fixed, preimage_eof, extra_chars);
2184 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2185 update_pre_post_images(preimage, postimage,
2186 fixed_buf, fixed_len, postlen);
2190 if (ws_error_action != correct_ws_error)
2194 * The hunk does not apply byte-by-byte, but the hash says
2195 * it might with whitespace fuzz. We haven't been asked to
2196 * ignore whitespace, we were asked to correct whitespace
2197 * errors, so let's try matching after whitespace correction.
2199 * The preimage may extend beyond the end of the file,
2200 * but in this loop we will only handle the part of the
2201 * preimage that falls within the file.
2203 strbuf_init(&fixed, preimage->len + 1);
2204 orig = preimage->buf;
2205 target = img->buf + try;
2206 for (i = 0; i < preimage_limit; i++) {
2207 size_t oldlen = preimage->line[i].len;
2208 size_t tgtlen = img->line[try_lno + i].len;
2209 size_t fixstart = fixed.len;
2210 struct strbuf tgtfix;
2213 /* Try fixing the line in the preimage */
2214 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2216 /* Try fixing the line in the target */
2217 strbuf_init(&tgtfix, tgtlen);
2218 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2221 * If they match, either the preimage was based on
2222 * a version before our tree fixed whitespace breakage,
2223 * or we are lacking a whitespace-fix patch the tree
2224 * the preimage was based on already had (i.e. target
2225 * has whitespace breakage, the preimage doesn't).
2226 * In either case, we are fixing the whitespace breakages
2227 * so we might as well take the fix together with their
2230 match = (tgtfix.len == fixed.len - fixstart &&
2231 !memcmp(tgtfix.buf, fixed.buf + fixstart,
2232 fixed.len - fixstart));
2234 strbuf_release(&tgtfix);
2244 * Now handle the lines in the preimage that falls beyond the
2245 * end of the file (if any). They will only match if they are
2246 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2249 for ( ; i < preimage->nr; i++) {
2250 size_t fixstart = fixed.len; /* start of the fixed preimage */
2251 size_t oldlen = preimage->line[i].len;
2254 /* Try fixing the line in the preimage */
2255 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2257 for (j = fixstart; j < fixed.len; j++)
2258 if (!isspace(fixed.buf[j]))
2265 * Yes, the preimage is based on an older version that still
2266 * has whitespace breakages unfixed, and fixing them makes the
2267 * hunk match. Update the context lines in the postimage.
2269 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2270 update_pre_post_images(preimage, postimage,
2271 fixed_buf, fixed_len, 0);
2275 strbuf_release(&fixed);
2279 static int find_pos(struct image *img,
2280 struct image *preimage,
2281 struct image *postimage,
2284 int match_beginning, int match_end)
2287 unsigned long backwards, forwards, try;
2288 int backwards_lno, forwards_lno, try_lno;
2291 * If match_beginning or match_end is specified, there is no
2292 * point starting from a wrong line that will never match and
2293 * wander around and wait for a match at the specified end.
2295 if (match_beginning)
2298 line = img->nr - preimage->nr;
2301 * Because the comparison is unsigned, the following test
2302 * will also take care of a negative line number that can
2303 * result when match_end and preimage is larger than the target.
2305 if ((size_t) line > img->nr)
2309 for (i = 0; i < line; i++)
2310 try += img->line[i].len;
2313 * There's probably some smart way to do this, but I'll leave
2314 * that to the smart and beautiful people. I'm simple and stupid.
2317 backwards_lno = line;
2319 forwards_lno = line;
2322 for (i = 0; ; i++) {
2323 if (match_fragment(img, preimage, postimage,
2324 try, try_lno, ws_rule,
2325 match_beginning, match_end))
2329 if (backwards_lno == 0 && forwards_lno == img->nr)
2333 if (backwards_lno == 0) {
2338 backwards -= img->line[backwards_lno].len;
2340 try_lno = backwards_lno;
2342 if (forwards_lno == img->nr) {
2346 forwards += img->line[forwards_lno].len;
2349 try_lno = forwards_lno;
2356 static void remove_first_line(struct image *img)
2358 img->buf += img->line[0].len;
2359 img->len -= img->line[0].len;
2364 static void remove_last_line(struct image *img)
2366 img->len -= img->line[--img->nr].len;
2369 static void update_image(struct image *img,
2371 struct image *preimage,
2372 struct image *postimage)
2375 * remove the copy of preimage at offset in img
2376 * and replace it with postimage
2379 size_t remove_count, insert_count, applied_at = 0;
2384 * If we are removing blank lines at the end of img,
2385 * the preimage may extend beyond the end.
2386 * If that is the case, we must be careful only to
2387 * remove the part of the preimage that falls within
2388 * the boundaries of img. Initialize preimage_limit
2389 * to the number of lines in the preimage that falls
2390 * within the boundaries.
2392 preimage_limit = preimage->nr;
2393 if (preimage_limit > img->nr - applied_pos)
2394 preimage_limit = img->nr - applied_pos;
2396 for (i = 0; i < applied_pos; i++)
2397 applied_at += img->line[i].len;
2400 for (i = 0; i < preimage_limit; i++)
2401 remove_count += img->line[applied_pos + i].len;
2402 insert_count = postimage->len;
2404 /* Adjust the contents */
2405 result = xmalloc(img->len + insert_count - remove_count + 1);
2406 memcpy(result, img->buf, applied_at);
2407 memcpy(result + applied_at, postimage->buf, postimage->len);
2408 memcpy(result + applied_at + postimage->len,
2409 img->buf + (applied_at + remove_count),
2410 img->len - (applied_at + remove_count));
2413 img->len += insert_count - remove_count;
2414 result[img->len] = '\0';
2416 /* Adjust the line table */
2417 nr = img->nr + postimage->nr - preimage_limit;
2418 if (preimage_limit < postimage->nr) {
2420 * NOTE: this knows that we never call remove_first_line()
2421 * on anything other than pre/post image.
2423 img->line = xrealloc(img->line, nr * sizeof(*img->line));
2424 img->line_allocated = img->line;
2426 if (preimage_limit != postimage->nr)
2427 memmove(img->line + applied_pos + postimage->nr,
2428 img->line + applied_pos + preimage_limit,
2429 (img->nr - (applied_pos + preimage_limit)) *
2430 sizeof(*img->line));
2431 memcpy(img->line + applied_pos,
2433 postimage->nr * sizeof(*img->line));
2435 for (i = 0; i < postimage->nr; i++)
2436 img->line[applied_pos + i].flag |= LINE_PATCHED;
2440 static int apply_one_fragment(struct image *img, struct fragment *frag,
2441 int inaccurate_eof, unsigned ws_rule,
2444 int match_beginning, match_end;
2445 const char *patch = frag->patch;
2446 int size = frag->size;
2447 char *old, *oldlines;
2448 struct strbuf newlines;
2449 int new_blank_lines_at_end = 0;
2450 int found_new_blank_lines_at_end = 0;
2451 int hunk_linenr = frag->linenr;
2452 unsigned long leading, trailing;
2453 int pos, applied_pos;
2454 struct image preimage;
2455 struct image postimage;
2457 memset(&preimage, 0, sizeof(preimage));
2458 memset(&postimage, 0, sizeof(postimage));
2459 oldlines = xmalloc(size);
2460 strbuf_init(&newlines, size);
2465 int len = linelen(patch, size);
2467 int added_blank_line = 0;
2468 int is_blank_context = 0;
2475 * "plen" is how much of the line we should use for
2476 * the actual patch data. Normally we just remove the
2477 * first character on the line, but if the line is
2478 * followed by "\ No newline", then we also remove the
2479 * last one (which is the newline, of course).
2482 if (len < size && patch[len] == '\\')
2485 if (apply_in_reverse) {
2488 else if (first == '+')
2494 /* Newer GNU diff, empty context line */
2496 /* ... followed by '\No newline'; nothing */
2499 strbuf_addch(&newlines, '\n');
2500 add_line_info(&preimage, "\n", 1, LINE_COMMON);
2501 add_line_info(&postimage, "\n", 1, LINE_COMMON);
2502 is_blank_context = 1;
2505 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2506 ws_blank_line(patch + 1, plen, ws_rule))
2507 is_blank_context = 1;
2509 memcpy(old, patch + 1, plen);
2510 add_line_info(&preimage, old, plen,
2511 (first == ' ' ? LINE_COMMON : 0));
2515 /* Fall-through for ' ' */
2517 /* --no-add does not add new lines */
2518 if (first == '+' && no_add)
2521 start = newlines.len;
2523 !whitespace_error ||
2524 ws_error_action != correct_ws_error) {
2525 strbuf_add(&newlines, patch + 1, plen);
2528 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &applied_after_fixing_ws);
2530 add_line_info(&postimage, newlines.buf + start, newlines.len - start,
2531 (first == '+' ? 0 : LINE_COMMON));
2533 (ws_rule & WS_BLANK_AT_EOF) &&
2534 ws_blank_line(patch + 1, plen, ws_rule))
2535 added_blank_line = 1;
2537 case '@': case '\\':
2538 /* Ignore it, we already handled it */
2541 if (apply_verbosely)
2542 error("invalid start of line: '%c'", first);
2545 if (added_blank_line) {
2546 if (!new_blank_lines_at_end)
2547 found_new_blank_lines_at_end = hunk_linenr;
2548 new_blank_lines_at_end++;
2550 else if (is_blank_context)
2553 new_blank_lines_at_end = 0;
2558 if (inaccurate_eof &&
2559 old > oldlines && old[-1] == '\n' &&
2560 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
2562 strbuf_setlen(&newlines, newlines.len - 1);
2565 leading = frag->leading;
2566 trailing = frag->trailing;
2569 * A hunk to change lines at the beginning would begin with
2571 * but we need to be careful. -U0 that inserts before the second
2572 * line also has this pattern.
2574 * And a hunk to add to an empty file would begin with
2577 * In other words, a hunk that is (frag->oldpos <= 1) with or
2578 * without leading context must match at the beginning.
2580 match_beginning = (!frag->oldpos ||
2581 (frag->oldpos == 1 && !unidiff_zero));
2584 * A hunk without trailing lines must match at the end.
2585 * However, we simply cannot tell if a hunk must match end
2586 * from the lack of trailing lines if the patch was generated
2587 * with unidiff without any context.
2589 match_end = !unidiff_zero && !trailing;
2591 pos = frag->newpos ? (frag->newpos - 1) : 0;
2592 preimage.buf = oldlines;
2593 preimage.len = old - oldlines;
2594 postimage.buf = newlines.buf;
2595 postimage.len = newlines.len;
2596 preimage.line = preimage.line_allocated;
2597 postimage.line = postimage.line_allocated;
2601 applied_pos = find_pos(img, &preimage, &postimage, pos,
2602 ws_rule, match_beginning, match_end);
2604 if (applied_pos >= 0)
2607 /* Am I at my context limits? */
2608 if ((leading <= p_context) && (trailing <= p_context))
2610 if (match_beginning || match_end) {
2611 match_beginning = match_end = 0;
2616 * Reduce the number of context lines; reduce both
2617 * leading and trailing if they are equal otherwise
2618 * just reduce the larger context.
2620 if (leading >= trailing) {
2621 remove_first_line(&preimage);
2622 remove_first_line(&postimage);
2626 if (trailing > leading) {
2627 remove_last_line(&preimage);
2628 remove_last_line(&postimage);
2633 if (applied_pos >= 0) {
2634 if (new_blank_lines_at_end &&
2635 preimage.nr + applied_pos >= img->nr &&
2636 (ws_rule & WS_BLANK_AT_EOF) &&
2637 ws_error_action != nowarn_ws_error) {
2638 record_ws_error(WS_BLANK_AT_EOF, "+", 1,
2639 found_new_blank_lines_at_end);
2640 if (ws_error_action == correct_ws_error) {
2641 while (new_blank_lines_at_end--)
2642 remove_last_line(&postimage);
2645 * We would want to prevent write_out_results()
2646 * from taking place in apply_patch() that follows
2647 * the callchain led us here, which is:
2648 * apply_patch->check_patch_list->check_patch->
2649 * apply_data->apply_fragments->apply_one_fragment
2651 if (ws_error_action == die_on_ws_error)
2655 if (apply_verbosely && applied_pos != pos) {
2656 int offset = applied_pos - pos;
2657 if (apply_in_reverse)
2658 offset = 0 - offset;
2660 "Hunk #%d succeeded at %d (offset %d lines).\n",
2661 nth_fragment, applied_pos + 1, offset);
2665 * Warn if it was necessary to reduce the number
2668 if ((leading != frag->leading) ||
2669 (trailing != frag->trailing))
2670 fprintf(stderr, "Context reduced to (%ld/%ld)"
2671 " to apply fragment at %d\n",
2672 leading, trailing, applied_pos+1);
2673 update_image(img, applied_pos, &preimage, &postimage);
2675 if (apply_verbosely)
2676 error("while searching for:\n%.*s",
2677 (int)(old - oldlines), oldlines);
2681 strbuf_release(&newlines);
2682 free(preimage.line_allocated);
2683 free(postimage.line_allocated);
2685 return (applied_pos < 0);
2688 static int apply_binary_fragment(struct image *img, struct patch *patch)
2690 struct fragment *fragment = patch->fragments;
2695 return error("missing binary patch data for '%s'",
2700 /* Binary patch is irreversible without the optional second hunk */
2701 if (apply_in_reverse) {
2702 if (!fragment->next)
2703 return error("cannot reverse-apply a binary patch "
2704 "without the reverse hunk to '%s'",
2706 ? patch->new_name : patch->old_name);
2707 fragment = fragment->next;
2709 switch (fragment->binary_patch_method) {
2710 case BINARY_DELTA_DEFLATED:
2711 dst = patch_delta(img->buf, img->len, fragment->patch,
2712 fragment->size, &len);
2719 case BINARY_LITERAL_DEFLATED:
2721 img->len = fragment->size;
2722 img->buf = xmalloc(img->len+1);
2723 memcpy(img->buf, fragment->patch, img->len);
2724 img->buf[img->len] = '\0';
2730 static int apply_binary(struct image *img, struct patch *patch)
2732 const char *name = patch->old_name ? patch->old_name : patch->new_name;
2733 unsigned char sha1[20];
2736 * For safety, we require patch index line to contain
2737 * full 40-byte textual SHA1 for old and new, at least for now.
2739 if (strlen(patch->old_sha1_prefix) != 40 ||
2740 strlen(patch->new_sha1_prefix) != 40 ||
2741 get_sha1_hex(patch->old_sha1_prefix, sha1) ||
2742 get_sha1_hex(patch->new_sha1_prefix, sha1))
2743 return error("cannot apply binary patch to '%s' "
2744 "without full index line", name);
2746 if (patch->old_name) {
2748 * See if the old one matches what the patch
2751 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2752 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
2753 return error("the patch applies to '%s' (%s), "
2754 "which does not match the "
2755 "current contents.",
2756 name, sha1_to_hex(sha1));
2759 /* Otherwise, the old one must be empty. */
2761 return error("the patch applies to an empty "
2762 "'%s' but it is not empty", name);
2765 get_sha1_hex(patch->new_sha1_prefix, sha1);
2766 if (is_null_sha1(sha1)) {
2768 return 0; /* deletion patch */
2771 if (has_sha1_file(sha1)) {
2772 /* We already have the postimage */
2773 enum object_type type;
2777 result = read_sha1_file(sha1, &type, &size);
2779 return error("the necessary postimage %s for "
2780 "'%s' cannot be read",
2781 patch->new_sha1_prefix, name);
2787 * We have verified buf matches the preimage;
2788 * apply the patch data to it, which is stored
2789 * in the patch->fragments->{patch,size}.
2791 if (apply_binary_fragment(img, patch))
2792 return error("binary patch does not apply to '%s'",
2795 /* verify that the result matches */
2796 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2797 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
2798 return error("binary patch to '%s' creates incorrect result (expecting %s, got %s)",
2799 name, patch->new_sha1_prefix, sha1_to_hex(sha1));
2805 static int apply_fragments(struct image *img, struct patch *patch)
2807 struct fragment *frag = patch->fragments;
2808 const char *name = patch->old_name ? patch->old_name : patch->new_name;
2809 unsigned ws_rule = patch->ws_rule;
2810 unsigned inaccurate_eof = patch->inaccurate_eof;
2813 if (patch->is_binary)
2814 return apply_binary(img, patch);
2818 if (apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {
2819 error("patch failed: %s:%ld", name, frag->oldpos);
2820 if (!apply_with_reject)
2829 static int read_file_or_gitlink(struct cache_entry *ce, struct strbuf *buf)
2834 if (S_ISGITLINK(ce->ce_mode)) {
2835 strbuf_grow(buf, 100);
2836 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(ce->sha1));
2838 enum object_type type;
2842 result = read_sha1_file(ce->sha1, &type, &sz);
2845 /* XXX read_sha1_file NUL-terminates */
2846 strbuf_attach(buf, result, sz, sz + 1);
2851 static struct patch *in_fn_table(const char *name)
2853 struct string_list_item *item;
2858 item = string_list_lookup(&fn_table, name);
2860 return (struct patch *)item->util;
2866 * item->util in the filename table records the status of the path.
2867 * Usually it points at a patch (whose result records the contents
2868 * of it after applying it), but it could be PATH_WAS_DELETED for a
2869 * path that a previously applied patch has already removed.
2871 #define PATH_TO_BE_DELETED ((struct patch *) -2)
2872 #define PATH_WAS_DELETED ((struct patch *) -1)
2874 static int to_be_deleted(struct patch *patch)
2876 return patch == PATH_TO_BE_DELETED;
2879 static int was_deleted(struct patch *patch)
2881 return patch == PATH_WAS_DELETED;
2884 static void add_to_fn_table(struct patch *patch)
2886 struct string_list_item *item;
2889 * Always add new_name unless patch is a deletion
2890 * This should cover the cases for normal diffs,
2891 * file creations and copies
2893 if (patch->new_name != NULL) {
2894 item = string_list_insert(&fn_table, patch->new_name);
2899 * store a failure on rename/deletion cases because
2900 * later chunks shouldn't patch old names
2902 if ((patch->new_name == NULL) || (patch->is_rename)) {
2903 item = string_list_insert(&fn_table, patch->old_name);
2904 item->util = PATH_WAS_DELETED;
2908 static void prepare_fn_table(struct patch *patch)
2911 * store information about incoming file deletion
2914 if ((patch->new_name == NULL) || (patch->is_rename)) {
2915 struct string_list_item *item;
2916 item = string_list_insert(&fn_table, patch->old_name);
2917 item->util = PATH_TO_BE_DELETED;
2919 patch = patch->next;
2923 static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce)
2925 struct strbuf buf = STRBUF_INIT;
2929 struct patch *tpatch;
2931 if (!(patch->is_copy || patch->is_rename) &&
2932 (tpatch = in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {
2933 if (was_deleted(tpatch)) {
2934 return error("patch %s has been renamed/deleted",
2937 /* We have a patched copy in memory use that */
2938 strbuf_add(&buf, tpatch->result, tpatch->resultsize);
2939 } else if (cached) {
2940 if (read_file_or_gitlink(ce, &buf))
2941 return error("read of %s failed", patch->old_name);
2942 } else if (patch->old_name) {
2943 if (S_ISGITLINK(patch->old_mode)) {
2945 read_file_or_gitlink(ce, &buf);
2948 * There is no way to apply subproject
2949 * patch without looking at the index.
2951 patch->fragments = NULL;
2954 if (read_old_data(st, patch->old_name, &buf))
2955 return error("read of %s failed", patch->old_name);
2959 img = strbuf_detach(&buf, &len);
2960 prepare_image(&image, img, len, !patch->is_binary);
2962 if (apply_fragments(&image, patch) < 0)
2963 return -1; /* note with --reject this succeeds. */
2964 patch->result = image.buf;
2965 patch->resultsize = image.len;
2966 add_to_fn_table(patch);
2967 free(image.line_allocated);
2969 if (0 < patch->is_delete && patch->resultsize)
2970 return error("removal patch leaves file contents");
2975 static int check_to_create_blob(const char *new_name, int ok_if_exists)
2978 if (!lstat(new_name, &nst)) {
2979 if (S_ISDIR(nst.st_mode) || ok_if_exists)
2982 * A leading component of new_name might be a symlink
2983 * that is going to be removed with this patch, but
2984 * still pointing at somewhere that has the path.
2985 * In such a case, path "new_name" does not exist as
2986 * far as git is concerned.
2988 if (has_symlink_leading_path(new_name, strlen(new_name)))
2991 return error("%s: already exists in working directory", new_name);
2993 else if ((errno != ENOENT) && (errno != ENOTDIR))
2994 return error("%s: %s", new_name, strerror(errno));
2998 static int verify_index_match(struct cache_entry *ce, struct stat *st)
3000 if (S_ISGITLINK(ce->ce_mode)) {
3001 if (!S_ISDIR(st->st_mode))
3005 return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
3008 static int check_preimage(struct patch *patch, struct cache_entry **ce, struct stat *st)
3010 const char *old_name = patch->old_name;
3011 struct patch *tpatch = NULL;
3013 unsigned st_mode = 0;
3016 * Make sure that we do not have local modifications from the
3017 * index when we are looking at the index. Also make sure
3018 * we have the preimage file to be patched in the work tree,
3019 * unless --cached, which tells git to apply only in the index.
3024 assert(patch->is_new <= 0);
3026 if (!(patch->is_copy || patch->is_rename) &&
3027 (tpatch = in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {
3028 if (was_deleted(tpatch))
3029 return error("%s: has been deleted/renamed", old_name);
3030 st_mode = tpatch->new_mode;
3031 } else if (!cached) {
3032 stat_ret = lstat(old_name, st);
3033 if (stat_ret && errno != ENOENT)
3034 return error("%s: %s", old_name, strerror(errno));
3037 if (to_be_deleted(tpatch))
3040 if (check_index && !tpatch) {
3041 int pos = cache_name_pos(old_name, strlen(old_name));
3043 if (patch->is_new < 0)
3045 return error("%s: does not exist in index", old_name);
3047 *ce = active_cache[pos];
3049 struct checkout costate;
3051 memset(&costate, 0, sizeof(costate));
3052 costate.base_dir = "";
3053 costate.refresh_cache = 1;
3054 if (checkout_entry(*ce, &costate, NULL) ||
3055 lstat(old_name, st))
3058 if (!cached && verify_index_match(*ce, st))
3059 return error("%s: does not match index", old_name);
3061 st_mode = (*ce)->ce_mode;
3062 } else if (stat_ret < 0) {
3063 if (patch->is_new < 0)
3065 return error("%s: %s", old_name, strerror(errno));
3068 if (!cached && !tpatch)
3069 st_mode = ce_mode_from_stat(*ce, st->st_mode);
3071 if (patch->is_new < 0)
3073 if (!patch->old_mode)
3074 patch->old_mode = st_mode;
3075 if ((st_mode ^ patch->old_mode) & S_IFMT)
3076 return error("%s: wrong type", old_name);
3077 if (st_mode != patch->old_mode)
3078 warning("%s has type %o, expected %o",
3079 old_name, st_mode, patch->old_mode);
3080 if (!patch->new_mode && !patch->is_delete)
3081 patch->new_mode = st_mode;
3086 patch->is_delete = 0;
3087 patch->old_name = NULL;
3091 static int check_patch(struct patch *patch)
3094 const char *old_name = patch->old_name;
3095 const char *new_name = patch->new_name;
3096 const char *name = old_name ? old_name : new_name;
3097 struct cache_entry *ce = NULL;
3098 struct patch *tpatch;
3102 patch->rejected = 1; /* we will drop this after we succeed */
3104 status = check_preimage(patch, &ce, &st);
3107 old_name = patch->old_name;
3109 if ((tpatch = in_fn_table(new_name)) &&
3110 (was_deleted(tpatch) || to_be_deleted(tpatch)))
3112 * A type-change diff is always split into a patch to
3113 * delete old, immediately followed by a patch to
3114 * create new (see diff.c::run_diff()); in such a case
3115 * it is Ok that the entry to be deleted by the
3116 * previous patch is still in the working tree and in
3124 ((0 < patch->is_new) | (0 < patch->is_rename) | patch->is_copy)) {
3126 cache_name_pos(new_name, strlen(new_name)) >= 0 &&
3128 return error("%s: already exists in index", new_name);
3130 int err = check_to_create_blob(new_name, ok_if_exists);
3134 if (!patch->new_mode) {
3135 if (0 < patch->is_new)
3136 patch->new_mode = S_IFREG | 0644;
3138 patch->new_mode = patch->old_mode;
3142 if (new_name && old_name) {
3143 int same = !strcmp(old_name, new_name);
3144 if (!patch->new_mode)
3145 patch->new_mode = patch->old_mode;
3146 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
3147 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
3148 patch->new_mode, new_name, patch->old_mode,
3149 same ? "" : " of ", same ? "" : old_name);
3152 if (apply_data(patch, &st, ce) < 0)
3153 return error("%s: patch does not apply", name);
3154 patch->rejected = 0;
3158 static int check_patch_list(struct patch *patch)
3162 prepare_fn_table(patch);
3164 if (apply_verbosely)
3165 say_patch_name(stderr,
3166 "Checking patch ", patch, "...\n");
3167 err |= check_patch(patch);
3168 patch = patch->next;
3173 /* This function tries to read the sha1 from the current index */
3174 static int get_current_sha1(const char *path, unsigned char *sha1)
3178 if (read_cache() < 0)
3180 pos = cache_name_pos(path, strlen(path));
3183 hashcpy(sha1, active_cache[pos]->sha1);
3187 /* Build an index that contains the just the files needed for a 3way merge */
3188 static void build_fake_ancestor(struct patch *list, const char *filename)
3190 struct patch *patch;
3191 struct index_state result = { NULL };
3194 /* Once we start supporting the reverse patch, it may be
3195 * worth showing the new sha1 prefix, but until then...
3197 for (patch = list; patch; patch = patch->next) {
3198 const unsigned char *sha1_ptr;
3199 unsigned char sha1[20];
3200 struct cache_entry *ce;
3203 name = patch->old_name ? patch->old_name : patch->new_name;
3204 if (0 < patch->is_new)
3206 else if (get_sha1(patch->old_sha1_prefix, sha1))
3207 /* git diff has no index line for mode/type changes */
3208 if (!patch->lines_added && !patch->lines_deleted) {
3209 if (get_current_sha1(patch->old_name, sha1))
3210 die("mode change for %s, which is not "
3211 "in current HEAD", name);
3214 die("sha1 information is lacking or useless "
3219 ce = make_cache_entry(patch->old_mode, sha1_ptr, name, 0, 0);
3221 die("make_cache_entry failed for path '%s'", name);
3222 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))
3223 die ("Could not add %s to temporary index", name);
3226 fd = open(filename, O_WRONLY | O_CREAT, 0666);
3227 if (fd < 0 || write_index(&result, fd) || close(fd))
3228 die ("Could not write temporary index to %s", filename);
3230 discard_index(&result);
3233 static void stat_patch_list(struct patch *patch)
3235 int files, adds, dels;
3237 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
3239 adds += patch->lines_added;
3240 dels += patch->lines_deleted;
3244 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
3247 static void numstat_patch_list(struct patch *patch)
3249 for ( ; patch; patch = patch->next) {
3251 name = patch->new_name ? patch->new_name : patch->old_name;
3252 if (patch->is_binary)
3255 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
3256 write_name_quoted(name, stdout, line_termination);
3260 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
3263 printf(" %s mode %06o %s\n", newdelete, mode, name);
3265 printf(" %s %s\n", newdelete, name);
3268 static void show_mode_change(struct patch *p, int show_name)
3270 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
3272 printf(" mode change %06o => %06o %s\n",
3273 p->old_mode, p->new_mode, p->new_name);
3275 printf(" mode change %06o => %06o\n",
3276 p->old_mode, p->new_mode);
3280 static void show_rename_copy(struct patch *p)
3282 const char *renamecopy = p->is_rename ? "rename" : "copy";
3283 const char *old, *new;
3285 /* Find common prefix */
3289 const char *slash_old, *slash_new;
3290 slash_old = strchr(old, '/');
3291 slash_new = strchr(new, '/');
3294 slash_old - old != slash_new - new ||
3295 memcmp(old, new, slash_new - new))
3297 old = slash_old + 1;
3298 new = slash_new + 1;
3300 /* p->old_name thru old is the common prefix, and old and new
3301 * through the end of names are renames
3303 if (old != p->old_name)
3304 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
3305 (int)(old - p->old_name), p->old_name,
3306 old, new, p->score);
3308 printf(" %s %s => %s (%d%%)\n", renamecopy,
3309 p->old_name, p->new_name, p->score);
3310 show_mode_change(p, 0);
3313 static void summary_patch_list(struct patch *patch)
3317 for (p = patch; p; p = p->next) {
3319 show_file_mode_name("create", p->new_mode, p->new_name);
3320 else if (p->is_delete)
3321 show_file_mode_name("delete", p->old_mode, p->old_name);
3323 if (p->is_rename || p->is_copy)
3324 show_rename_copy(p);
3327 printf(" rewrite %s (%d%%)\n",
3328 p->new_name, p->score);
3329 show_mode_change(p, 0);
3332 show_mode_change(p, 1);
3338 static void patch_stats(struct patch *patch)
3340 int lines = patch->lines_added + patch->lines_deleted;
3342 if (lines > max_change)
3344 if (patch->old_name) {
3345 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
3347 len = strlen(patch->old_name);
3351 if (patch->new_name) {
3352 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
3354 len = strlen(patch->new_name);
3360 static void remove_file(struct patch *patch, int rmdir_empty)
3363 if (remove_file_from_cache(patch->old_name) < 0)
3364 die("unable to remove %s from index", patch->old_name);
3367 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
3368 remove_path(patch->old_name);
3373 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
3376 struct cache_entry *ce;
3377 int namelen = strlen(path);
3378 unsigned ce_size = cache_entry_size(namelen);
3383 ce = xcalloc(1, ce_size);
3384 memcpy(ce->name, path, namelen);
3385 ce->ce_mode = create_ce_mode(mode);
3386 ce->ce_flags = namelen;
3387 if (S_ISGITLINK(mode)) {
3388 const char *s = buf;
3390 if (get_sha1_hex(s + strlen("Subproject commit "), ce->sha1))
3391 die("corrupt patch for subproject %s", path);
3394 if (lstat(path, &st) < 0)
3395 die_errno("unable to stat newly created file '%s'",
3397 fill_stat_cache_info(ce, &st);
3399 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
3400 die("unable to create backing store for newly created file %s", path);
3402 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
3403 die("unable to add cache entry for %s", path);
3406 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
3409 struct strbuf nbuf = STRBUF_INIT;
3411 if (S_ISGITLINK(mode)) {
3413 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
3415 return mkdir(path, 0777);
3418 if (has_symlinks && S_ISLNK(mode))
3419 /* Although buf:size is counted string, it also is NUL
3422 return symlink(buf, path);
3424 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
3428 if (convert_to_working_tree(path, buf, size, &nbuf)) {
3432 write_or_die(fd, buf, size);
3433 strbuf_release(&nbuf);
3436 die_errno("closing file '%s'", path);
3441 * We optimistically assume that the directories exist,
3442 * which is true 99% of the time anyway. If they don't,
3443 * we create them and try again.
3445 static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
3449 if (!try_create_file(path, mode, buf, size))
3452 if (errno == ENOENT) {
3453 if (safe_create_leading_directories(path))
3455 if (!try_create_file(path, mode, buf, size))
3459 if (errno == EEXIST || errno == EACCES) {
3460 /* We may be trying to create a file where a directory
3464 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
3468 if (errno == EEXIST) {
3469 unsigned int nr = getpid();
3472 char newpath[PATH_MAX];
3473 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
3474 if (!try_create_file(newpath, mode, buf, size)) {
3475 if (!rename(newpath, path))
3477 unlink_or_warn(newpath);
3480 if (errno != EEXIST)
3485 die_errno("unable to write file '%s' mode %o", path, mode);
3488 static void create_file(struct patch *patch)
3490 char *path = patch->new_name;
3491 unsigned mode = patch->new_mode;
3492 unsigned long size = patch->resultsize;
3493 char *buf = patch->result;
3496 mode = S_IFREG | 0644;
3497 create_one_file(path, mode, buf, size);
3498 add_index_file(path, mode, buf, size);
3501 /* phase zero is to remove, phase one is to create */
3502 static void write_out_one_result(struct patch *patch, int phase)
3504 if (patch->is_delete > 0) {
3506 remove_file(patch, 1);
3509 if (patch->is_new > 0 || patch->is_copy) {
3515 * Rename or modification boils down to the same
3516 * thing: remove the old, write the new
3519 remove_file(patch, patch->is_rename);
3524 static int write_out_one_reject(struct patch *patch)
3527 char namebuf[PATH_MAX];
3528 struct fragment *frag;
3531 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
3532 if (!frag->rejected)
3538 if (apply_verbosely)
3539 say_patch_name(stderr,
3540 "Applied patch ", patch, " cleanly.\n");
3544 /* This should not happen, because a removal patch that leaves
3545 * contents are marked "rejected" at the patch level.
3547 if (!patch->new_name)
3548 die("internal error");
3550 /* Say this even without --verbose */
3551 say_patch_name(stderr, "Applying patch ", patch, " with");
3552 fprintf(stderr, " %d rejects...\n", cnt);
3554 cnt = strlen(patch->new_name);
3555 if (ARRAY_SIZE(namebuf) <= cnt + 5) {
3556 cnt = ARRAY_SIZE(namebuf) - 5;
3557 warning("truncating .rej filename to %.*s.rej",
3558 cnt - 1, patch->new_name);
3560 memcpy(namebuf, patch->new_name, cnt);
3561 memcpy(namebuf + cnt, ".rej", 5);
3563 rej = fopen(namebuf, "w");
3565 return error("cannot open %s: %s", namebuf, strerror(errno));
3567 /* Normal git tools never deal with .rej, so do not pretend
3568 * this is a git patch by saying --git nor give extended
3569 * headers. While at it, maybe please "kompare" that wants
3570 * the trailing TAB and some garbage at the end of line ;-).
3572 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
3573 patch->new_name, patch->new_name);
3574 for (cnt = 1, frag = patch->fragments;
3576 cnt++, frag = frag->next) {
3577 if (!frag->rejected) {
3578 fprintf(stderr, "Hunk #%d applied cleanly.\n", cnt);
3581 fprintf(stderr, "Rejected hunk #%d.\n", cnt);
3582 fprintf(rej, "%.*s", frag->size, frag->patch);
3583 if (frag->patch[frag->size-1] != '\n')
3590 static int write_out_results(struct patch *list)
3596 for (phase = 0; phase < 2; phase++) {
3602 write_out_one_result(l, phase);
3603 if (phase == 1 && write_out_one_reject(l))
3612 static struct lock_file lock_file;
3614 static struct string_list limit_by_name;
3615 static int has_include;
3616 static void add_name_limit(const char *name, int exclude)
3618 struct string_list_item *it;
3620 it = string_list_append(&limit_by_name, name);
3621 it->util = exclude ? NULL : (void *) 1;
3624 static int use_patch(struct patch *p)
3626 const char *pathname = p->new_name ? p->new_name : p->old_name;
3629 /* Paths outside are not touched regardless of "--include" */
3630 if (0 < prefix_length) {
3631 int pathlen = strlen(pathname);
3632 if (pathlen <= prefix_length ||
3633 memcmp(prefix, pathname, prefix_length))
3637 /* See if it matches any of exclude/include rule */
3638 for (i = 0; i < limit_by_name.nr; i++) {
3639 struct string_list_item *it = &limit_by_name.items[i];
3640 if (!fnmatch(it->string, pathname, 0))
3641 return (it->util != NULL);
3645 * If we had any include, a path that does not match any rule is
3646 * not used. Otherwise, we saw bunch of exclude rules (or none)
3647 * and such a path is used.
3649 return !has_include;
3653 static void prefix_one(char **name)
3655 char *old_name = *name;
3658 *name = xstrdup(prefix_filename(prefix, prefix_length, *name));
3662 static void prefix_patches(struct patch *p)
3664 if (!prefix || p->is_toplevel_relative)
3666 for ( ; p; p = p->next) {
3667 if (p->new_name == p->old_name) {
3668 char *prefixed = p->new_name;
3669 prefix_one(&prefixed);
3670 p->new_name = p->old_name = prefixed;
3673 prefix_one(&p->new_name);
3674 prefix_one(&p->old_name);
3679 #define INACCURATE_EOF (1<<0)
3680 #define RECOUNT (1<<1)
3682 static int apply_patch(int fd, const char *filename, int options)
3685 struct strbuf buf = STRBUF_INIT;
3686 struct patch *list = NULL, **listp = &list;
3687 int skipped_patch = 0;
3689 /* FIXME - memory leak when using multiple patch files as inputs */
3690 memset(&fn_table, 0, sizeof(struct string_list));
3691 patch_input_file = filename;
3692 read_patch_file(&buf, fd);
3694 while (offset < buf.len) {
3695 struct patch *patch;
3698 patch = xcalloc(1, sizeof(*patch));
3699 patch->inaccurate_eof = !!(options & INACCURATE_EOF);
3700 patch->recount = !!(options & RECOUNT);
3701 nr = parse_chunk(buf.buf + offset, buf.len - offset, patch);
3704 if (apply_in_reverse)
3705 reverse_patches(patch);
3707 prefix_patches(patch);
3708 if (use_patch(patch)) {
3711 listp = &patch->next;
3714 /* perhaps free it a bit better? */
3721 if (!list && !skipped_patch)
3722 die("unrecognized input");
3724 if (whitespace_error && (ws_error_action == die_on_ws_error))
3727 update_index = check_index && apply;
3728 if (update_index && newfd < 0)
3729 newfd = hold_locked_index(&lock_file, 1);
3732 if (read_cache() < 0)
3733 die("unable to read index file");
3736 if ((check || apply) &&
3737 check_patch_list(list) < 0 &&
3741 if (apply && write_out_results(list))
3745 build_fake_ancestor(list, fake_ancestor);
3748 stat_patch_list(list);
3751 numstat_patch_list(list);
3754 summary_patch_list(list);
3756 strbuf_release(&buf);
3760 static int git_apply_config(const char *var, const char *value, void *cb)
3762 if (!strcmp(var, "apply.whitespace"))
3763 return git_config_string(&apply_default_whitespace, var, value);
3764 else if (!strcmp(var, "apply.ignorewhitespace"))
3765 return git_config_string(&apply_default_ignorewhitespace, var, value);
3766 return git_default_config(var, value, cb);
3769 static int option_parse_exclude(const struct option *opt,
3770 const char *arg, int unset)
3772 add_name_limit(arg, 1);
3776 static int option_parse_include(const struct option *opt,
3777 const char *arg, int unset)
3779 add_name_limit(arg, 0);
3784 static int option_parse_p(const struct option *opt,
3785 const char *arg, int unset)
3787 p_value = atoi(arg);
3792 static int option_parse_z(const struct option *opt,
3793 const char *arg, int unset)
3796 line_termination = '\n';
3798 line_termination = 0;
3802 static int option_parse_space_change(const struct option *opt,
3803 const char *arg, int unset)
3806 ws_ignore_action = ignore_ws_none;
3808 ws_ignore_action = ignore_ws_change;
3812 static int option_parse_whitespace(const struct option *opt,
3813 const char *arg, int unset)
3815 const char **whitespace_option = opt->value;
3817 *whitespace_option = arg;
3818 parse_whitespace_option(arg);
3822 static int option_parse_directory(const struct option *opt,
3823 const char *arg, int unset)
3825 root_len = strlen(arg);
3826 if (root_len && arg[root_len - 1] != '/') {
3828 root = new_root = xmalloc(root_len + 2);
3829 strcpy(new_root, arg);
3830 strcpy(new_root + root_len++, "/");
3836 int cmd_apply(int argc, const char **argv, const char *prefix_)
3840 int is_not_gitdir = !startup_info->have_repository;
3841 int force_apply = 0;
3843 const char *whitespace_option = NULL;
3845 struct option builtin_apply_options[] = {
3846 { OPTION_CALLBACK, 0, "exclude", NULL, "path",
3847 "don't apply changes matching the given path",
3848 0, option_parse_exclude },
3849 { OPTION_CALLBACK, 0, "include", NULL, "path",
3850 "apply changes matching the given path",
3851 0, option_parse_include },
3852 { OPTION_CALLBACK, 'p', NULL, NULL, "num",
3853 "remove <num> leading slashes from traditional diff paths",
3854 0, option_parse_p },
3855 OPT_BOOLEAN(0, "no-add", &no_add,
3856 "ignore additions made by the patch"),
3857 OPT_BOOLEAN(0, "stat", &diffstat,
3858 "instead of applying the patch, output diffstat for the input"),
3859 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
3860 OPT_NOOP_NOARG(0, "binary"),
3861 OPT_BOOLEAN(0, "numstat", &numstat,
3862 "shows number of added and deleted lines in decimal notation"),
3863 OPT_BOOLEAN(0, "summary", &summary,
3864 "instead of applying the patch, output a summary for the input"),
3865 OPT_BOOLEAN(0, "check", &check,
3866 "instead of applying the patch, see if the patch is applicable"),
3867 OPT_BOOLEAN(0, "index", &check_index,
3868 "make sure the patch is applicable to the current index"),
3869 OPT_BOOLEAN(0, "cached", &cached,
3870 "apply a patch without touching the working tree"),
3871 OPT_BOOLEAN(0, "apply", &force_apply,
3872 "also apply the patch (use with --stat/--summary/--check)"),
3873 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor,
3874 "build a temporary index based on embedded index information"),
3875 { OPTION_CALLBACK, 'z', NULL, NULL, NULL,
3876 "paths are separated with NUL character",
3877 PARSE_OPT_NOARG, option_parse_z },
3878 OPT_INTEGER('C', NULL, &p_context,
3879 "ensure at least <n> lines of context match"),
3880 { OPTION_CALLBACK, 0, "whitespace", &whitespace_option, "action",
3881 "detect new or modified lines that have whitespace errors",
3882 0, option_parse_whitespace },
3883 { OPTION_CALLBACK, 0, "ignore-space-change", NULL, NULL,
3884 "ignore changes in whitespace when finding context",
3885 PARSE_OPT_NOARG, option_parse_space_change },
3886 { OPTION_CALLBACK, 0, "ignore-whitespace", NULL, NULL,
3887 "ignore changes in whitespace when finding context",
3888 PARSE_OPT_NOARG, option_parse_space_change },
3889 OPT_BOOLEAN('R', "reverse", &apply_in_reverse,
3890 "apply the patch in reverse"),
3891 OPT_BOOLEAN(0, "unidiff-zero", &unidiff_zero,
3892 "don't expect at least one line of context"),
3893 OPT_BOOLEAN(0, "reject", &apply_with_reject,
3894 "leave the rejected hunks in corresponding *.rej files"),
3895 OPT_BOOLEAN(0, "allow-overlap", &allow_overlap,
3896 "allow overlapping hunks"),
3897 OPT__VERBOSE(&apply_verbosely, "be verbose"),
3898 OPT_BIT(0, "inaccurate-eof", &options,
3899 "tolerate incorrectly detected missing new-line at the end of file",
3901 OPT_BIT(0, "recount", &options,
3902 "do not trust the line counts in the hunk headers",
3904 { OPTION_CALLBACK, 0, "directory", NULL, "root",
3905 "prepend <root> to all filenames",
3906 0, option_parse_directory },
3911 prefix_length = prefix ? strlen(prefix) : 0;
3912 git_config(git_apply_config, NULL);
3913 if (apply_default_whitespace)
3914 parse_whitespace_option(apply_default_whitespace);
3915 if (apply_default_ignorewhitespace)
3916 parse_ignorewhitespace_option(apply_default_ignorewhitespace);
3918 argc = parse_options(argc, argv, prefix, builtin_apply_options,
3921 if (apply_with_reject)
3922 apply = apply_verbosely = 1;
3923 if (!force_apply && (diffstat || numstat || summary || check || fake_ancestor))
3925 if (check_index && is_not_gitdir)
3926 die("--index outside a repository");
3929 die("--cached outside a repository");
3932 for (i = 0; i < argc; i++) {
3933 const char *arg = argv[i];
3936 if (!strcmp(arg, "-")) {
3937 errs |= apply_patch(0, "<stdin>", options);
3940 } else if (0 < prefix_length)
3941 arg = prefix_filename(prefix, prefix_length, arg);
3943 fd = open(arg, O_RDONLY);
3945 die_errno("can't open patch '%s'", arg);
3947 set_default_whitespace_mode(whitespace_option);
3948 errs |= apply_patch(fd, arg, options);
3951 set_default_whitespace_mode(whitespace_option);
3953 errs |= apply_patch(0, "<stdin>", options);
3954 if (whitespace_error) {
3955 if (squelch_whitespace_errors &&
3956 squelch_whitespace_errors < whitespace_error) {
3958 whitespace_error - squelch_whitespace_errors;
3959 warning("squelched %d "
3960 "whitespace error%s",
3962 squelched == 1 ? "" : "s");
3964 if (ws_error_action == die_on_ws_error)
3965 die("%d line%s add%s whitespace errors.",
3967 whitespace_error == 1 ? "" : "s",
3968 whitespace_error == 1 ? "s" : "");
3969 if (applied_after_fixing_ws && apply)
3970 warning("%d line%s applied after"
3971 " fixing whitespace errors.",
3972 applied_after_fixing_ws,
3973 applied_after_fixing_ws == 1 ? "" : "s");
3974 else if (whitespace_error)
3975 warning("%d line%s add%s whitespace errors.",
3977 whitespace_error == 1 ? "" : "s",
3978 whitespace_error == 1 ? "s" : "");
3982 if (write_cache(newfd, active_cache, active_nr) ||
3983 commit_locked_index(&lock_file))
3984 die("Unable to write new index file");