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 size_t sane_tz_len(const char *line, size_t len)
456 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
458 tz = line + len - strlen(" +0500");
460 if (tz[1] != '+' && tz[1] != '-')
463 for (p = tz + 2; p != line + len; p++)
467 return line + len - tz;
470 static size_t tz_with_colon_len(const char *line, size_t len)
474 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
476 tz = line + len - strlen(" +08:00");
478 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
481 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
482 !isdigit(*p++) || !isdigit(*p++))
485 return line + len - tz;
488 static size_t date_len(const char *line, size_t len)
490 const char *date, *p;
492 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
494 p = date = line + len - strlen("72-02-05");
496 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
497 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
498 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */
501 if (date - line >= strlen("19") &&
502 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */
503 date -= strlen("19");
505 return line + len - date;
508 static size_t short_time_len(const char *line, size_t len)
510 const char *time, *p;
512 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
514 p = time = line + len - strlen(" 07:01:32");
516 /* Permit 1-digit hours? */
518 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
519 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
520 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */
523 return line + len - time;
526 static size_t fractional_time_len(const char *line, size_t len)
531 /* Expected format: 19:41:17.620000023 */
532 if (!len || !isdigit(line[len - 1]))
536 /* Fractional seconds. */
537 while (p > line && isdigit(*p))
542 /* Hours, minutes, and whole seconds. */
543 n = short_time_len(line, p - line);
547 return line + len - p + n;
550 static size_t trailing_spaces_len(const char *line, size_t len)
554 /* Expected format: ' ' x (1 or more) */
555 if (!len || line[len - 1] != ' ')
562 return line + len - (p + 1);
569 static size_t diff_timestamp_len(const char *line, size_t len)
571 const char *end = line + len;
575 * Posix: 2010-07-05 19:41:17
576 * GNU: 2010-07-05 19:41:17.620000023 -0500
579 if (!isdigit(end[-1]))
582 n = sane_tz_len(line, end - line);
584 n = tz_with_colon_len(line, end - line);
587 n = short_time_len(line, end - line);
589 n = fractional_time_len(line, end - line);
592 n = date_len(line, end - line);
593 if (!n) /* No date. Too bad. */
597 if (end == line) /* No space before date. */
599 if (end[-1] == '\t') { /* Success! */
601 return line + len - end;
603 if (end[-1] != ' ') /* No space before date. */
606 /* Whitespace damage. */
607 end -= trailing_spaces_len(line, end - line);
608 return line + len - end;
611 static char *find_name_common(const char *line, char *def, int p_value,
612 const char *end, int terminate)
615 const char *start = NULL;
619 while (line != end) {
622 if (!end && isspace(c)) {
625 if (name_terminate(start, line-start, c, terminate))
629 if (c == '/' && !--p_value)
633 return squash_slash(def);
636 return squash_slash(def);
639 * Generally we prefer the shorter name, especially
640 * if the other one is just a variation of that with
641 * something else tacked on to the end (ie "file.orig"
645 int deflen = strlen(def);
646 if (deflen < len && !strncmp(start, def, deflen))
647 return squash_slash(def);
652 char *ret = xmalloc(root_len + len + 1);
654 memcpy(ret + root_len, start, len);
655 ret[root_len + len] = '\0';
656 return squash_slash(ret);
659 return squash_slash(xmemdupz(start, len));
662 static char *find_name(const char *line, char *def, int p_value, int terminate)
665 char *name = find_name_gnu(line, def, p_value);
670 return find_name_common(line, def, p_value, NULL, terminate);
673 static char *find_name_traditional(const char *line, char *def, int p_value)
675 size_t len = strlen(line);
679 char *name = find_name_gnu(line, def, p_value);
684 len = strchrnul(line, '\n') - line;
685 date_len = diff_timestamp_len(line, len);
687 return find_name_common(line, def, p_value, NULL, TERM_TAB);
690 return find_name_common(line, def, p_value, line + len, 0);
693 static int count_slashes(const char *cp)
705 * Given the string after "--- " or "+++ ", guess the appropriate
706 * p_value for the given patch.
708 static int guess_p_value(const char *nameline)
713 if (is_dev_null(nameline))
715 name = find_name_traditional(nameline, NULL, 0);
718 cp = strchr(name, '/');
723 * Does it begin with "a/$our-prefix" and such? Then this is
724 * very likely to apply to our directory.
726 if (!strncmp(name, prefix, prefix_length))
727 val = count_slashes(prefix);
730 if (!strncmp(cp, prefix, prefix_length))
731 val = count_slashes(prefix) + 1;
739 * Does the ---/+++ line has the POSIX timestamp after the last HT?
740 * GNU diff puts epoch there to signal a creation/deletion event. Is
741 * this such a timestamp?
743 static int has_epoch_timestamp(const char *nameline)
746 * We are only interested in epoch timestamp; any non-zero
747 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
748 * For the same reason, the date must be either 1969-12-31 or
749 * 1970-01-01, and the seconds part must be "00".
751 const char stamp_regexp[] =
752 "^(1969-12-31|1970-01-01)"
754 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
756 "([-+][0-2][0-9]:?[0-5][0-9])\n";
757 const char *timestamp = NULL, *cp, *colon;
758 static regex_t *stamp;
764 for (cp = nameline; *cp != '\n'; cp++) {
771 stamp = xmalloc(sizeof(*stamp));
772 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
773 warning("Cannot prepare timestamp regexp %s",
779 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
781 if (status != REG_NOMATCH)
782 warning("regexec returned %d for input: %s",
787 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
789 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
791 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
792 if (timestamp[m[3].rm_so] == '-')
793 zoneoffset = -zoneoffset;
796 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
797 * (west of GMT) or 1970-01-01 (east of GMT)
799 if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) ||
800 (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10)))
803 hourminute = (strtol(timestamp + 11, NULL, 10) * 60 +
804 strtol(timestamp + 14, NULL, 10) -
807 return ((zoneoffset < 0 && hourminute == 1440) ||
808 (0 <= zoneoffset && !hourminute));
812 * Get the name etc info from the ---/+++ lines of a traditional patch header
814 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
815 * files, we can happily check the index for a match, but for creating a
816 * new file we should try to match whatever "patch" does. I have no idea.
818 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
822 first += 4; /* skip "--- " */
823 second += 4; /* skip "+++ " */
824 if (!p_value_known) {
826 p = guess_p_value(first);
827 q = guess_p_value(second);
829 if (0 <= p && p == q) {
834 if (is_dev_null(first)) {
836 patch->is_delete = 0;
837 name = find_name_traditional(second, NULL, p_value);
838 patch->new_name = name;
839 } else if (is_dev_null(second)) {
841 patch->is_delete = 1;
842 name = find_name_traditional(first, NULL, p_value);
843 patch->old_name = name;
845 name = find_name_traditional(first, NULL, p_value);
846 name = find_name_traditional(second, name, p_value);
847 if (has_epoch_timestamp(first)) {
849 patch->is_delete = 0;
850 patch->new_name = name;
851 } else if (has_epoch_timestamp(second)) {
853 patch->is_delete = 1;
854 patch->old_name = name;
856 patch->old_name = patch->new_name = name;
860 die("unable to find filename in patch at line %d", linenr);
863 static int gitdiff_hdrend(const char *line, struct patch *patch)
869 * We're anal about diff header consistency, to make
870 * sure that we don't end up having strange ambiguous
871 * patches floating around.
873 * As a result, gitdiff_{old|new}name() will check
874 * their names against any previous information, just
877 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
879 if (!orig_name && !isnull)
880 return find_name(line, NULL, p_value, TERM_TAB);
889 die("git apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
890 another = find_name(line, NULL, p_value, TERM_TAB);
891 if (!another || memcmp(another, name, len + 1))
892 die("git apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
897 /* expect "/dev/null" */
898 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
899 die("git apply: bad git-diff - expected /dev/null on line %d", linenr);
904 static int gitdiff_oldname(const char *line, struct patch *patch)
906 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
910 static int gitdiff_newname(const char *line, struct patch *patch)
912 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
916 static int gitdiff_oldmode(const char *line, struct patch *patch)
918 patch->old_mode = strtoul(line, NULL, 8);
922 static int gitdiff_newmode(const char *line, struct patch *patch)
924 patch->new_mode = strtoul(line, NULL, 8);
928 static int gitdiff_delete(const char *line, struct patch *patch)
930 patch->is_delete = 1;
931 patch->old_name = patch->def_name;
932 return gitdiff_oldmode(line, patch);
935 static int gitdiff_newfile(const char *line, struct patch *patch)
938 patch->new_name = patch->def_name;
939 return gitdiff_newmode(line, patch);
942 static int gitdiff_copysrc(const char *line, struct patch *patch)
945 patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
949 static int gitdiff_copydst(const char *line, struct patch *patch)
952 patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
956 static int gitdiff_renamesrc(const char *line, struct patch *patch)
958 patch->is_rename = 1;
959 patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
963 static int gitdiff_renamedst(const char *line, struct patch *patch)
965 patch->is_rename = 1;
966 patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
970 static int gitdiff_similarity(const char *line, struct patch *patch)
972 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
977 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
979 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
984 static int gitdiff_index(const char *line, struct patch *patch)
987 * index line is N hexadecimal, "..", N hexadecimal,
988 * and optional space with octal mode.
990 const char *ptr, *eol;
993 ptr = strchr(line, '.');
994 if (!ptr || ptr[1] != '.' || 40 < ptr - line)
997 memcpy(patch->old_sha1_prefix, line, len);
998 patch->old_sha1_prefix[len] = 0;
1001 ptr = strchr(line, ' ');
1002 eol = strchr(line, '\n');
1004 if (!ptr || eol < ptr)
1010 memcpy(patch->new_sha1_prefix, line, len);
1011 patch->new_sha1_prefix[len] = 0;
1013 patch->old_mode = strtoul(ptr+1, NULL, 8);
1018 * This is normal for a diff that doesn't change anything: we'll fall through
1019 * into the next diff. Tell the parser to break out.
1021 static int gitdiff_unrecognized(const char *line, struct patch *patch)
1026 static const char *stop_at_slash(const char *line, int llen)
1028 int nslash = p_value;
1031 for (i = 0; i < llen; i++) {
1033 if (ch == '/' && --nslash <= 0)
1040 * This is to extract the same name that appears on "diff --git"
1041 * line. We do not find and return anything if it is a rename
1042 * patch, and it is OK because we will find the name elsewhere.
1043 * We need to reliably find name only when it is mode-change only,
1044 * creation or deletion of an empty file. In any of these cases,
1045 * both sides are the same name under a/ and b/ respectively.
1047 static char *git_header_name(char *line, int llen)
1050 const char *second = NULL;
1051 size_t len, line_len;
1053 line += strlen("diff --git ");
1054 llen -= strlen("diff --git ");
1058 struct strbuf first = STRBUF_INIT;
1059 struct strbuf sp = STRBUF_INIT;
1061 if (unquote_c_style(&first, line, &second))
1062 goto free_and_fail1;
1064 /* advance to the first slash */
1065 cp = stop_at_slash(first.buf, first.len);
1066 /* we do not accept absolute paths */
1067 if (!cp || cp == first.buf)
1068 goto free_and_fail1;
1069 strbuf_remove(&first, 0, cp + 1 - first.buf);
1072 * second points at one past closing dq of name.
1073 * find the second name.
1075 while ((second < line + llen) && isspace(*second))
1078 if (line + llen <= second)
1079 goto free_and_fail1;
1080 if (*second == '"') {
1081 if (unquote_c_style(&sp, second, NULL))
1082 goto free_and_fail1;
1083 cp = stop_at_slash(sp.buf, sp.len);
1084 if (!cp || cp == sp.buf)
1085 goto free_and_fail1;
1086 /* They must match, otherwise ignore */
1087 if (strcmp(cp + 1, first.buf))
1088 goto free_and_fail1;
1089 strbuf_release(&sp);
1090 return strbuf_detach(&first, NULL);
1093 /* unquoted second */
1094 cp = stop_at_slash(second, line + llen - second);
1095 if (!cp || cp == second)
1096 goto free_and_fail1;
1098 if (line + llen - cp != first.len + 1 ||
1099 memcmp(first.buf, cp, first.len))
1100 goto free_and_fail1;
1101 return strbuf_detach(&first, NULL);
1104 strbuf_release(&first);
1105 strbuf_release(&sp);
1109 /* unquoted first name */
1110 name = stop_at_slash(line, llen);
1111 if (!name || name == line)
1116 * since the first name is unquoted, a dq if exists must be
1117 * the beginning of the second name.
1119 for (second = name; second < line + llen; second++) {
1120 if (*second == '"') {
1121 struct strbuf sp = STRBUF_INIT;
1124 if (unquote_c_style(&sp, second, NULL))
1125 goto free_and_fail2;
1127 np = stop_at_slash(sp.buf, sp.len);
1128 if (!np || np == sp.buf)
1129 goto free_and_fail2;
1132 len = sp.buf + sp.len - np;
1133 if (len < second - name &&
1134 !strncmp(np, name, len) &&
1135 isspace(name[len])) {
1137 strbuf_remove(&sp, 0, np - sp.buf);
1138 return strbuf_detach(&sp, NULL);
1142 strbuf_release(&sp);
1148 * Accept a name only if it shows up twice, exactly the same
1151 second = strchr(name, '\n');
1154 line_len = second - name;
1155 for (len = 0 ; ; len++) {
1156 switch (name[len]) {
1161 case '\t': case ' ':
1162 second = stop_at_slash(name + len, line_len - len);
1166 if (second[len] == '\n' && !strncmp(name, second, len)) {
1167 return xmemdupz(name, len);
1173 /* Verify that we recognize the lines following a git header */
1174 static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
1176 unsigned long offset;
1178 /* A git diff has explicit new/delete information, so we don't guess */
1180 patch->is_delete = 0;
1183 * Some things may not have the old name in the
1184 * rest of the headers anywhere (pure mode changes,
1185 * or removing or adding empty files), so we get
1186 * the default name from the header.
1188 patch->def_name = git_header_name(line, len);
1189 if (patch->def_name && root) {
1190 char *s = xmalloc(root_len + strlen(patch->def_name) + 1);
1192 strcpy(s + root_len, patch->def_name);
1193 free(patch->def_name);
1194 patch->def_name = s;
1200 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
1201 static const struct opentry {
1203 int (*fn)(const char *, struct patch *);
1205 { "@@ -", gitdiff_hdrend },
1206 { "--- ", gitdiff_oldname },
1207 { "+++ ", gitdiff_newname },
1208 { "old mode ", gitdiff_oldmode },
1209 { "new mode ", gitdiff_newmode },
1210 { "deleted file mode ", gitdiff_delete },
1211 { "new file mode ", gitdiff_newfile },
1212 { "copy from ", gitdiff_copysrc },
1213 { "copy to ", gitdiff_copydst },
1214 { "rename old ", gitdiff_renamesrc },
1215 { "rename new ", gitdiff_renamedst },
1216 { "rename from ", gitdiff_renamesrc },
1217 { "rename to ", gitdiff_renamedst },
1218 { "similarity index ", gitdiff_similarity },
1219 { "dissimilarity index ", gitdiff_dissimilarity },
1220 { "index ", gitdiff_index },
1221 { "", gitdiff_unrecognized },
1225 len = linelen(line, size);
1226 if (!len || line[len-1] != '\n')
1228 for (i = 0; i < ARRAY_SIZE(optable); i++) {
1229 const struct opentry *p = optable + i;
1230 int oplen = strlen(p->str);
1231 if (len < oplen || memcmp(p->str, line, oplen))
1233 if (p->fn(line + oplen, patch) < 0)
1242 static int parse_num(const char *line, unsigned long *p)
1246 if (!isdigit(*line))
1248 *p = strtoul(line, &ptr, 10);
1252 static int parse_range(const char *line, int len, int offset, const char *expect,
1253 unsigned long *p1, unsigned long *p2)
1257 if (offset < 0 || offset >= len)
1262 digits = parse_num(line, p1);
1272 digits = parse_num(line+1, p2);
1281 ex = strlen(expect);
1284 if (memcmp(line, expect, ex))
1290 static void recount_diff(char *line, int size, struct fragment *fragment)
1292 int oldlines = 0, newlines = 0, ret = 0;
1295 warning("recount: ignore empty hunk");
1300 int len = linelen(line, size);
1308 case ' ': case '\n':
1320 ret = size < 3 || prefixcmp(line, "@@ ");
1323 ret = size < 5 || prefixcmp(line, "diff ");
1330 warning("recount: unexpected line: %.*s",
1331 (int)linelen(line, size), line);
1336 fragment->oldlines = oldlines;
1337 fragment->newlines = newlines;
1341 * Parse a unified diff fragment header of the
1342 * form "@@ -a,b +c,d @@"
1344 static int parse_fragment_header(char *line, int len, struct fragment *fragment)
1348 if (!len || line[len-1] != '\n')
1351 /* Figure out the number of lines in a fragment */
1352 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1353 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1358 static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
1360 unsigned long offset, len;
1362 patch->is_toplevel_relative = 0;
1363 patch->is_rename = patch->is_copy = 0;
1364 patch->is_new = patch->is_delete = -1;
1365 patch->old_mode = patch->new_mode = 0;
1366 patch->old_name = patch->new_name = NULL;
1367 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
1368 unsigned long nextlen;
1370 len = linelen(line, size);
1374 /* Testing this early allows us to take a few shortcuts.. */
1379 * Make sure we don't find any unconnected patch fragments.
1380 * That's a sign that we didn't find a header, and that a
1381 * patch has become corrupted/broken up.
1383 if (!memcmp("@@ -", line, 4)) {
1384 struct fragment dummy;
1385 if (parse_fragment_header(line, len, &dummy) < 0)
1387 die("patch fragment without header at line %d: %.*s",
1388 linenr, (int)len-1, line);
1395 * Git patch? It might not have a real patch, just a rename
1396 * or mode change, so we handle that specially
1398 if (!memcmp("diff --git ", line, 11)) {
1399 int git_hdr_len = parse_git_header(line, len, size, patch);
1400 if (git_hdr_len <= len)
1402 if (!patch->old_name && !patch->new_name) {
1403 if (!patch->def_name)
1404 die("git diff header lacks filename information when removing "
1405 "%d leading pathname components (line %d)" , p_value, linenr);
1406 patch->old_name = patch->new_name = patch->def_name;
1408 patch->is_toplevel_relative = 1;
1409 *hdrsize = git_hdr_len;
1413 /* --- followed by +++ ? */
1414 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1418 * We only accept unified patches, so we want it to
1419 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1420 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1422 nextlen = linelen(line + len, size - len);
1423 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1426 /* Ok, we'll consider it a patch */
1427 parse_traditional_patch(line, line+len, patch);
1428 *hdrsize = len + nextlen;
1435 static void record_ws_error(unsigned result, const char *line, int len, int linenr)
1443 if (squelch_whitespace_errors &&
1444 squelch_whitespace_errors < whitespace_error)
1447 err = whitespace_error_string(result);
1448 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1449 patch_input_file, linenr, err, len, line);
1453 static void check_whitespace(const char *line, int len, unsigned ws_rule)
1455 unsigned result = ws_check(line + 1, len - 1, ws_rule);
1457 record_ws_error(result, line + 1, len - 2, linenr);
1461 * Parse a unified diff. Note that this really needs to parse each
1462 * fragment separately, since the only way to know the difference
1463 * between a "---" that is part of a patch, and a "---" that starts
1464 * the next patch is to look at the line counts..
1466 static int parse_fragment(char *line, unsigned long size,
1467 struct patch *patch, struct fragment *fragment)
1470 int len = linelen(line, size), offset;
1471 unsigned long oldlines, newlines;
1472 unsigned long leading, trailing;
1474 offset = parse_fragment_header(line, len, fragment);
1477 if (offset > 0 && patch->recount)
1478 recount_diff(line + offset, size - offset, fragment);
1479 oldlines = fragment->oldlines;
1480 newlines = fragment->newlines;
1484 /* Parse the thing.. */
1488 added = deleted = 0;
1491 offset += len, size -= len, line += len, linenr++) {
1492 if (!oldlines && !newlines)
1494 len = linelen(line, size);
1495 if (!len || line[len-1] != '\n')
1500 case '\n': /* newer GNU diff, an empty context line */
1504 if (!deleted && !added)
1509 if (apply_in_reverse &&
1510 ws_error_action != nowarn_ws_error)
1511 check_whitespace(line, len, patch->ws_rule);
1517 if (!apply_in_reverse &&
1518 ws_error_action != nowarn_ws_error)
1519 check_whitespace(line, len, patch->ws_rule);
1526 * We allow "\ No newline at end of file". Depending
1527 * on locale settings when the patch was produced we
1528 * don't know what this line looks like. The only
1529 * thing we do know is that it begins with "\ ".
1530 * Checking for 12 is just for sanity check -- any
1531 * l10n of "\ No newline..." is at least that long.
1534 if (len < 12 || memcmp(line, "\\ ", 2))
1539 if (oldlines || newlines)
1541 fragment->leading = leading;
1542 fragment->trailing = trailing;
1545 * If a fragment ends with an incomplete line, we failed to include
1546 * it in the above loop because we hit oldlines == newlines == 0
1549 if (12 < size && !memcmp(line, "\\ ", 2))
1550 offset += linelen(line, size);
1552 patch->lines_added += added;
1553 patch->lines_deleted += deleted;
1555 if (0 < patch->is_new && oldlines)
1556 return error("new file depends on old contents");
1557 if (0 < patch->is_delete && newlines)
1558 return error("deleted file still has contents");
1562 static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
1564 unsigned long offset = 0;
1565 unsigned long oldlines = 0, newlines = 0, context = 0;
1566 struct fragment **fragp = &patch->fragments;
1568 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1569 struct fragment *fragment;
1572 fragment = xcalloc(1, sizeof(*fragment));
1573 fragment->linenr = linenr;
1574 len = parse_fragment(line, size, patch, fragment);
1576 die("corrupt patch at line %d", linenr);
1577 fragment->patch = line;
1578 fragment->size = len;
1579 oldlines += fragment->oldlines;
1580 newlines += fragment->newlines;
1581 context += fragment->leading + fragment->trailing;
1584 fragp = &fragment->next;
1592 * If something was removed (i.e. we have old-lines) it cannot
1593 * be creation, and if something was added it cannot be
1594 * deletion. However, the reverse is not true; --unified=0
1595 * patches that only add are not necessarily creation even
1596 * though they do not have any old lines, and ones that only
1597 * delete are not necessarily deletion.
1599 * Unfortunately, a real creation/deletion patch do _not_ have
1600 * any context line by definition, so we cannot safely tell it
1601 * apart with --unified=0 insanity. At least if the patch has
1602 * more than one hunk it is not creation or deletion.
1604 if (patch->is_new < 0 &&
1605 (oldlines || (patch->fragments && patch->fragments->next)))
1607 if (patch->is_delete < 0 &&
1608 (newlines || (patch->fragments && patch->fragments->next)))
1609 patch->is_delete = 0;
1611 if (0 < patch->is_new && oldlines)
1612 die("new file %s depends on old contents", patch->new_name);
1613 if (0 < patch->is_delete && newlines)
1614 die("deleted file %s still has contents", patch->old_name);
1615 if (!patch->is_delete && !newlines && context)
1616 fprintf(stderr, "** warning: file %s becomes empty but "
1617 "is not deleted\n", patch->new_name);
1622 static inline int metadata_changes(struct patch *patch)
1624 return patch->is_rename > 0 ||
1625 patch->is_copy > 0 ||
1626 patch->is_new > 0 ||
1628 (patch->old_mode && patch->new_mode &&
1629 patch->old_mode != patch->new_mode);
1632 static char *inflate_it(const void *data, unsigned long size,
1633 unsigned long inflated_size)
1639 memset(&stream, 0, sizeof(stream));
1641 stream.next_in = (unsigned char *)data;
1642 stream.avail_in = size;
1643 stream.next_out = out = xmalloc(inflated_size);
1644 stream.avail_out = inflated_size;
1645 git_inflate_init(&stream);
1646 st = git_inflate(&stream, Z_FINISH);
1647 git_inflate_end(&stream);
1648 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1655 static struct fragment *parse_binary_hunk(char **buf_p,
1656 unsigned long *sz_p,
1661 * Expect a line that begins with binary patch method ("literal"
1662 * or "delta"), followed by the length of data before deflating.
1663 * a sequence of 'length-byte' followed by base-85 encoded data
1664 * should follow, terminated by a newline.
1666 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1667 * and we would limit the patch line to 66 characters,
1668 * so one line can fit up to 13 groups that would decode
1669 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1670 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1673 unsigned long size = *sz_p;
1674 char *buffer = *buf_p;
1676 unsigned long origlen;
1679 struct fragment *frag;
1681 llen = linelen(buffer, size);
1686 if (!prefixcmp(buffer, "delta ")) {
1687 patch_method = BINARY_DELTA_DEFLATED;
1688 origlen = strtoul(buffer + 6, NULL, 10);
1690 else if (!prefixcmp(buffer, "literal ")) {
1691 patch_method = BINARY_LITERAL_DEFLATED;
1692 origlen = strtoul(buffer + 8, NULL, 10);
1700 int byte_length, max_byte_length, newsize;
1701 llen = linelen(buffer, size);
1705 /* consume the blank line */
1711 * Minimum line is "A00000\n" which is 7-byte long,
1712 * and the line length must be multiple of 5 plus 2.
1714 if ((llen < 7) || (llen-2) % 5)
1716 max_byte_length = (llen - 2) / 5 * 4;
1717 byte_length = *buffer;
1718 if ('A' <= byte_length && byte_length <= 'Z')
1719 byte_length = byte_length - 'A' + 1;
1720 else if ('a' <= byte_length && byte_length <= 'z')
1721 byte_length = byte_length - 'a' + 27;
1724 /* if the input length was not multiple of 4, we would
1725 * have filler at the end but the filler should never
1728 if (max_byte_length < byte_length ||
1729 byte_length <= max_byte_length - 4)
1731 newsize = hunk_size + byte_length;
1732 data = xrealloc(data, newsize);
1733 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1735 hunk_size = newsize;
1740 frag = xcalloc(1, sizeof(*frag));
1741 frag->patch = inflate_it(data, hunk_size, origlen);
1745 frag->size = origlen;
1749 frag->binary_patch_method = patch_method;
1755 error("corrupt binary patch at line %d: %.*s",
1756 linenr-1, llen-1, buffer);
1760 static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1763 * We have read "GIT binary patch\n"; what follows is a line
1764 * that says the patch method (currently, either "literal" or
1765 * "delta") and the length of data before deflating; a
1766 * sequence of 'length-byte' followed by base-85 encoded data
1769 * When a binary patch is reversible, there is another binary
1770 * hunk in the same format, starting with patch method (either
1771 * "literal" or "delta") with the length of data, and a sequence
1772 * of length-byte + base-85 encoded data, terminated with another
1773 * empty line. This data, when applied to the postimage, produces
1776 struct fragment *forward;
1777 struct fragment *reverse;
1781 forward = parse_binary_hunk(&buffer, &size, &status, &used);
1782 if (!forward && !status)
1783 /* there has to be one hunk (forward hunk) */
1784 return error("unrecognized binary patch at line %d", linenr-1);
1786 /* otherwise we already gave an error message */
1789 reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1794 * Not having reverse hunk is not an error, but having
1795 * a corrupt reverse hunk is.
1797 free((void*) forward->patch);
1801 forward->next = reverse;
1802 patch->fragments = forward;
1803 patch->is_binary = 1;
1807 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
1809 int hdrsize, patchsize;
1810 int offset = find_header(buffer, size, &hdrsize, patch);
1815 patch->ws_rule = whitespace_rule(patch->new_name
1819 patchsize = parse_single_patch(buffer + offset + hdrsize,
1820 size - offset - hdrsize, patch);
1823 static const char *binhdr[] = {
1828 static const char git_binary[] = "GIT binary patch\n";
1830 int hd = hdrsize + offset;
1831 unsigned long llen = linelen(buffer + hd, size - hd);
1833 if (llen == sizeof(git_binary) - 1 &&
1834 !memcmp(git_binary, buffer + hd, llen)) {
1837 used = parse_binary(buffer + hd + llen,
1838 size - hd - llen, patch);
1840 patchsize = used + llen;
1844 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
1845 for (i = 0; binhdr[i]; i++) {
1846 int len = strlen(binhdr[i]);
1847 if (len < size - hd &&
1848 !memcmp(binhdr[i], buffer + hd, len)) {
1850 patch->is_binary = 1;
1857 /* Empty patch cannot be applied if it is a text patch
1858 * without metadata change. A binary patch appears
1861 if ((apply || check) &&
1862 (!patch->is_binary && !metadata_changes(patch)))
1863 die("patch with only garbage at line %d", linenr);
1866 return offset + hdrsize + patchsize;
1869 #define swap(a,b) myswap((a),(b),sizeof(a))
1871 #define myswap(a, b, size) do { \
1872 unsigned char mytmp[size]; \
1873 memcpy(mytmp, &a, size); \
1874 memcpy(&a, &b, size); \
1875 memcpy(&b, mytmp, size); \
1878 static void reverse_patches(struct patch *p)
1880 for (; p; p = p->next) {
1881 struct fragment *frag = p->fragments;
1883 swap(p->new_name, p->old_name);
1884 swap(p->new_mode, p->old_mode);
1885 swap(p->is_new, p->is_delete);
1886 swap(p->lines_added, p->lines_deleted);
1887 swap(p->old_sha1_prefix, p->new_sha1_prefix);
1889 for (; frag; frag = frag->next) {
1890 swap(frag->newpos, frag->oldpos);
1891 swap(frag->newlines, frag->oldlines);
1896 static const char pluses[] =
1897 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1898 static const char minuses[]=
1899 "----------------------------------------------------------------------";
1901 static void show_stats(struct patch *patch)
1903 struct strbuf qname = STRBUF_INIT;
1904 char *cp = patch->new_name ? patch->new_name : patch->old_name;
1907 quote_c_style(cp, &qname, NULL, 0);
1910 * "scale" the filename
1916 if (qname.len > max) {
1917 cp = strchr(qname.buf + qname.len + 3 - max, '/');
1919 cp = qname.buf + qname.len + 3 - max;
1920 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
1923 if (patch->is_binary) {
1924 printf(" %-*s | Bin\n", max, qname.buf);
1925 strbuf_release(&qname);
1929 printf(" %-*s |", max, qname.buf);
1930 strbuf_release(&qname);
1933 * scale the add/delete
1935 max = max + max_change > 70 ? 70 - max : max_change;
1936 add = patch->lines_added;
1937 del = patch->lines_deleted;
1939 if (max_change > 0) {
1940 int total = ((add + del) * max + max_change / 2) / max_change;
1941 add = (add * max + max_change / 2) / max_change;
1944 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
1945 add, pluses, del, minuses);
1948 static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
1950 switch (st->st_mode & S_IFMT) {
1952 if (strbuf_readlink(buf, path, st->st_size) < 0)
1953 return error("unable to read symlink %s", path);
1956 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
1957 return error("unable to open or read %s", path);
1958 convert_to_git(path, buf->buf, buf->len, buf, 0);
1966 * Update the preimage, and the common lines in postimage,
1967 * from buffer buf of length len. If postlen is 0 the postimage
1968 * is updated in place, otherwise it's updated on a new buffer
1972 static void update_pre_post_images(struct image *preimage,
1973 struct image *postimage,
1975 size_t len, size_t postlen)
1978 char *new, *old, *fixed;
1979 struct image fixed_preimage;
1982 * Update the preimage with whitespace fixes. Note that we
1983 * are not losing preimage->buf -- apply_one_fragment() will
1986 prepare_image(&fixed_preimage, buf, len, 1);
1987 assert(fixed_preimage.nr == preimage->nr);
1988 for (i = 0; i < preimage->nr; i++)
1989 fixed_preimage.line[i].flag = preimage->line[i].flag;
1990 free(preimage->line_allocated);
1991 *preimage = fixed_preimage;
1994 * Adjust the common context lines in postimage. This can be
1995 * done in-place when we are just doing whitespace fixing,
1996 * which does not make the string grow, but needs a new buffer
1997 * when ignoring whitespace causes the update, since in this case
1998 * we could have e.g. tabs converted to multiple spaces.
1999 * We trust the caller to tell us if the update can be done
2000 * in place (postlen==0) or not.
2002 old = postimage->buf;
2004 new = postimage->buf = xmalloc(postlen);
2007 fixed = preimage->buf;
2008 for (i = ctx = 0; i < postimage->nr; i++) {
2009 size_t len = postimage->line[i].len;
2010 if (!(postimage->line[i].flag & LINE_COMMON)) {
2011 /* an added line -- no counterparts in preimage */
2012 memmove(new, old, len);
2018 /* a common context -- skip it in the original postimage */
2021 /* and find the corresponding one in the fixed preimage */
2022 while (ctx < preimage->nr &&
2023 !(preimage->line[ctx].flag & LINE_COMMON)) {
2024 fixed += preimage->line[ctx].len;
2027 if (preimage->nr <= ctx)
2030 /* and copy it in, while fixing the line length */
2031 len = preimage->line[ctx].len;
2032 memcpy(new, fixed, len);
2035 postimage->line[i].len = len;
2039 /* Fix the length of the whole thing */
2040 postimage->len = new - postimage->buf;
2043 static int match_fragment(struct image *img,
2044 struct image *preimage,
2045 struct image *postimage,
2049 int match_beginning, int match_end)
2052 char *fixed_buf, *buf, *orig, *target;
2053 struct strbuf fixed;
2057 if (preimage->nr + try_lno <= img->nr) {
2059 * The hunk falls within the boundaries of img.
2061 preimage_limit = preimage->nr;
2062 if (match_end && (preimage->nr + try_lno != img->nr))
2064 } else if (ws_error_action == correct_ws_error &&
2065 (ws_rule & WS_BLANK_AT_EOF)) {
2067 * This hunk extends beyond the end of img, and we are
2068 * removing blank lines at the end of the file. This
2069 * many lines from the beginning of the preimage must
2070 * match with img, and the remainder of the preimage
2073 preimage_limit = img->nr - try_lno;
2076 * The hunk extends beyond the end of the img and
2077 * we are not removing blanks at the end, so we
2078 * should reject the hunk at this position.
2083 if (match_beginning && try_lno)
2086 /* Quick hash check */
2087 for (i = 0; i < preimage_limit; i++)
2088 if (preimage->line[i].hash != img->line[try_lno + i].hash)
2091 if (preimage_limit == preimage->nr) {
2093 * Do we have an exact match? If we were told to match
2094 * at the end, size must be exactly at try+fragsize,
2095 * otherwise try+fragsize must be still within the preimage,
2096 * and either case, the old piece should match the preimage
2100 ? (try + preimage->len == img->len)
2101 : (try + preimage->len <= img->len)) &&
2102 !memcmp(img->buf + try, preimage->buf, preimage->len))
2106 * The preimage extends beyond the end of img, so
2107 * there cannot be an exact match.
2109 * There must be one non-blank context line that match
2110 * a line before the end of img.
2114 buf = preimage->buf;
2116 for (i = 0; i < preimage_limit; i++)
2117 buf_end += preimage->line[i].len;
2119 for ( ; buf < buf_end; buf++)
2127 * No exact match. If we are ignoring whitespace, run a line-by-line
2128 * fuzzy matching. We collect all the line length information because
2129 * we need it to adjust whitespace if we match.
2131 if (ws_ignore_action == ignore_ws_change) {
2134 size_t postlen = postimage->len;
2138 for (i = 0; i < preimage_limit; i++) {
2139 size_t prelen = preimage->line[i].len;
2140 size_t imglen = img->line[try_lno+i].len;
2142 if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,
2143 preimage->buf + preoff, prelen))
2145 if (preimage->line[i].flag & LINE_COMMON)
2146 postlen += imglen - prelen;
2152 * Ok, the preimage matches with whitespace fuzz.
2154 * imgoff now holds the true length of the target that
2155 * matches the preimage before the end of the file.
2157 * Count the number of characters in the preimage that fall
2158 * beyond the end of the file and make sure that all of them
2159 * are whitespace characters. (This can only happen if
2160 * we are removing blank lines at the end of the file.)
2162 buf = preimage_eof = preimage->buf + preoff;
2163 for ( ; i < preimage->nr; i++)
2164 preoff += preimage->line[i].len;
2165 preimage_end = preimage->buf + preoff;
2166 for ( ; buf < preimage_end; buf++)
2171 * Update the preimage and the common postimage context
2172 * lines to use the same whitespace as the target.
2173 * If whitespace is missing in the target (i.e.
2174 * if the preimage extends beyond the end of the file),
2175 * use the whitespace from the preimage.
2177 extra_chars = preimage_end - preimage_eof;
2178 strbuf_init(&fixed, imgoff + extra_chars);
2179 strbuf_add(&fixed, img->buf + try, imgoff);
2180 strbuf_add(&fixed, preimage_eof, extra_chars);
2181 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2182 update_pre_post_images(preimage, postimage,
2183 fixed_buf, fixed_len, postlen);
2187 if (ws_error_action != correct_ws_error)
2191 * The hunk does not apply byte-by-byte, but the hash says
2192 * it might with whitespace fuzz. We haven't been asked to
2193 * ignore whitespace, we were asked to correct whitespace
2194 * errors, so let's try matching after whitespace correction.
2196 * The preimage may extend beyond the end of the file,
2197 * but in this loop we will only handle the part of the
2198 * preimage that falls within the file.
2200 strbuf_init(&fixed, preimage->len + 1);
2201 orig = preimage->buf;
2202 target = img->buf + try;
2203 for (i = 0; i < preimage_limit; i++) {
2204 size_t oldlen = preimage->line[i].len;
2205 size_t tgtlen = img->line[try_lno + i].len;
2206 size_t fixstart = fixed.len;
2207 struct strbuf tgtfix;
2210 /* Try fixing the line in the preimage */
2211 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2213 /* Try fixing the line in the target */
2214 strbuf_init(&tgtfix, tgtlen);
2215 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2218 * If they match, either the preimage was based on
2219 * a version before our tree fixed whitespace breakage,
2220 * or we are lacking a whitespace-fix patch the tree
2221 * the preimage was based on already had (i.e. target
2222 * has whitespace breakage, the preimage doesn't).
2223 * In either case, we are fixing the whitespace breakages
2224 * so we might as well take the fix together with their
2227 match = (tgtfix.len == fixed.len - fixstart &&
2228 !memcmp(tgtfix.buf, fixed.buf + fixstart,
2229 fixed.len - fixstart));
2231 strbuf_release(&tgtfix);
2241 * Now handle the lines in the preimage that falls beyond the
2242 * end of the file (if any). They will only match if they are
2243 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2246 for ( ; i < preimage->nr; i++) {
2247 size_t fixstart = fixed.len; /* start of the fixed preimage */
2248 size_t oldlen = preimage->line[i].len;
2251 /* Try fixing the line in the preimage */
2252 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2254 for (j = fixstart; j < fixed.len; j++)
2255 if (!isspace(fixed.buf[j]))
2262 * Yes, the preimage is based on an older version that still
2263 * has whitespace breakages unfixed, and fixing them makes the
2264 * hunk match. Update the context lines in the postimage.
2266 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2267 update_pre_post_images(preimage, postimage,
2268 fixed_buf, fixed_len, 0);
2272 strbuf_release(&fixed);
2276 static int find_pos(struct image *img,
2277 struct image *preimage,
2278 struct image *postimage,
2281 int match_beginning, int match_end)
2284 unsigned long backwards, forwards, try;
2285 int backwards_lno, forwards_lno, try_lno;
2288 * If match_beginning or match_end is specified, there is no
2289 * point starting from a wrong line that will never match and
2290 * wander around and wait for a match at the specified end.
2292 if (match_beginning)
2295 line = img->nr - preimage->nr;
2298 * Because the comparison is unsigned, the following test
2299 * will also take care of a negative line number that can
2300 * result when match_end and preimage is larger than the target.
2302 if ((size_t) line > img->nr)
2306 for (i = 0; i < line; i++)
2307 try += img->line[i].len;
2310 * There's probably some smart way to do this, but I'll leave
2311 * that to the smart and beautiful people. I'm simple and stupid.
2314 backwards_lno = line;
2316 forwards_lno = line;
2319 for (i = 0; ; i++) {
2320 if (match_fragment(img, preimage, postimage,
2321 try, try_lno, ws_rule,
2322 match_beginning, match_end))
2326 if (backwards_lno == 0 && forwards_lno == img->nr)
2330 if (backwards_lno == 0) {
2335 backwards -= img->line[backwards_lno].len;
2337 try_lno = backwards_lno;
2339 if (forwards_lno == img->nr) {
2343 forwards += img->line[forwards_lno].len;
2346 try_lno = forwards_lno;
2353 static void remove_first_line(struct image *img)
2355 img->buf += img->line[0].len;
2356 img->len -= img->line[0].len;
2361 static void remove_last_line(struct image *img)
2363 img->len -= img->line[--img->nr].len;
2366 static void update_image(struct image *img,
2368 struct image *preimage,
2369 struct image *postimage)
2372 * remove the copy of preimage at offset in img
2373 * and replace it with postimage
2376 size_t remove_count, insert_count, applied_at = 0;
2381 * If we are removing blank lines at the end of img,
2382 * the preimage may extend beyond the end.
2383 * If that is the case, we must be careful only to
2384 * remove the part of the preimage that falls within
2385 * the boundaries of img. Initialize preimage_limit
2386 * to the number of lines in the preimage that falls
2387 * within the boundaries.
2389 preimage_limit = preimage->nr;
2390 if (preimage_limit > img->nr - applied_pos)
2391 preimage_limit = img->nr - applied_pos;
2393 for (i = 0; i < applied_pos; i++)
2394 applied_at += img->line[i].len;
2397 for (i = 0; i < preimage_limit; i++)
2398 remove_count += img->line[applied_pos + i].len;
2399 insert_count = postimage->len;
2401 /* Adjust the contents */
2402 result = xmalloc(img->len + insert_count - remove_count + 1);
2403 memcpy(result, img->buf, applied_at);
2404 memcpy(result + applied_at, postimage->buf, postimage->len);
2405 memcpy(result + applied_at + postimage->len,
2406 img->buf + (applied_at + remove_count),
2407 img->len - (applied_at + remove_count));
2410 img->len += insert_count - remove_count;
2411 result[img->len] = '\0';
2413 /* Adjust the line table */
2414 nr = img->nr + postimage->nr - preimage_limit;
2415 if (preimage_limit < postimage->nr) {
2417 * NOTE: this knows that we never call remove_first_line()
2418 * on anything other than pre/post image.
2420 img->line = xrealloc(img->line, nr * sizeof(*img->line));
2421 img->line_allocated = img->line;
2423 if (preimage_limit != postimage->nr)
2424 memmove(img->line + applied_pos + postimage->nr,
2425 img->line + applied_pos + preimage_limit,
2426 (img->nr - (applied_pos + preimage_limit)) *
2427 sizeof(*img->line));
2428 memcpy(img->line + applied_pos,
2430 postimage->nr * sizeof(*img->line));
2434 static int apply_one_fragment(struct image *img, struct fragment *frag,
2435 int inaccurate_eof, unsigned ws_rule)
2437 int match_beginning, match_end;
2438 const char *patch = frag->patch;
2439 int size = frag->size;
2440 char *old, *oldlines;
2441 struct strbuf newlines;
2442 int new_blank_lines_at_end = 0;
2443 unsigned long leading, trailing;
2444 int pos, applied_pos;
2445 struct image preimage;
2446 struct image postimage;
2448 memset(&preimage, 0, sizeof(preimage));
2449 memset(&postimage, 0, sizeof(postimage));
2450 oldlines = xmalloc(size);
2451 strbuf_init(&newlines, size);
2456 int len = linelen(patch, size);
2458 int added_blank_line = 0;
2459 int is_blank_context = 0;
2466 * "plen" is how much of the line we should use for
2467 * the actual patch data. Normally we just remove the
2468 * first character on the line, but if the line is
2469 * followed by "\ No newline", then we also remove the
2470 * last one (which is the newline, of course).
2473 if (len < size && patch[len] == '\\')
2476 if (apply_in_reverse) {
2479 else if (first == '+')
2485 /* Newer GNU diff, empty context line */
2487 /* ... followed by '\No newline'; nothing */
2490 strbuf_addch(&newlines, '\n');
2491 add_line_info(&preimage, "\n", 1, LINE_COMMON);
2492 add_line_info(&postimage, "\n", 1, LINE_COMMON);
2493 is_blank_context = 1;
2496 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2497 ws_blank_line(patch + 1, plen, ws_rule))
2498 is_blank_context = 1;
2500 memcpy(old, patch + 1, plen);
2501 add_line_info(&preimage, old, plen,
2502 (first == ' ' ? LINE_COMMON : 0));
2506 /* Fall-through for ' ' */
2508 /* --no-add does not add new lines */
2509 if (first == '+' && no_add)
2512 start = newlines.len;
2514 !whitespace_error ||
2515 ws_error_action != correct_ws_error) {
2516 strbuf_add(&newlines, patch + 1, plen);
2519 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &applied_after_fixing_ws);
2521 add_line_info(&postimage, newlines.buf + start, newlines.len - start,
2522 (first == '+' ? 0 : LINE_COMMON));
2524 (ws_rule & WS_BLANK_AT_EOF) &&
2525 ws_blank_line(patch + 1, plen, ws_rule))
2526 added_blank_line = 1;
2528 case '@': case '\\':
2529 /* Ignore it, we already handled it */
2532 if (apply_verbosely)
2533 error("invalid start of line: '%c'", first);
2536 if (added_blank_line)
2537 new_blank_lines_at_end++;
2538 else if (is_blank_context)
2541 new_blank_lines_at_end = 0;
2545 if (inaccurate_eof &&
2546 old > oldlines && old[-1] == '\n' &&
2547 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
2549 strbuf_setlen(&newlines, newlines.len - 1);
2552 leading = frag->leading;
2553 trailing = frag->trailing;
2556 * A hunk to change lines at the beginning would begin with
2558 * but we need to be careful. -U0 that inserts before the second
2559 * line also has this pattern.
2561 * And a hunk to add to an empty file would begin with
2564 * In other words, a hunk that is (frag->oldpos <= 1) with or
2565 * without leading context must match at the beginning.
2567 match_beginning = (!frag->oldpos ||
2568 (frag->oldpos == 1 && !unidiff_zero));
2571 * A hunk without trailing lines must match at the end.
2572 * However, we simply cannot tell if a hunk must match end
2573 * from the lack of trailing lines if the patch was generated
2574 * with unidiff without any context.
2576 match_end = !unidiff_zero && !trailing;
2578 pos = frag->newpos ? (frag->newpos - 1) : 0;
2579 preimage.buf = oldlines;
2580 preimage.len = old - oldlines;
2581 postimage.buf = newlines.buf;
2582 postimage.len = newlines.len;
2583 preimage.line = preimage.line_allocated;
2584 postimage.line = postimage.line_allocated;
2588 applied_pos = find_pos(img, &preimage, &postimage, pos,
2589 ws_rule, match_beginning, match_end);
2591 if (applied_pos >= 0)
2594 /* Am I at my context limits? */
2595 if ((leading <= p_context) && (trailing <= p_context))
2597 if (match_beginning || match_end) {
2598 match_beginning = match_end = 0;
2603 * Reduce the number of context lines; reduce both
2604 * leading and trailing if they are equal otherwise
2605 * just reduce the larger context.
2607 if (leading >= trailing) {
2608 remove_first_line(&preimage);
2609 remove_first_line(&postimage);
2613 if (trailing > leading) {
2614 remove_last_line(&preimage);
2615 remove_last_line(&postimage);
2620 if (applied_pos >= 0) {
2621 if (new_blank_lines_at_end &&
2622 preimage.nr + applied_pos >= img->nr &&
2623 (ws_rule & WS_BLANK_AT_EOF) &&
2624 ws_error_action != nowarn_ws_error) {
2625 record_ws_error(WS_BLANK_AT_EOF, "+", 1, frag->linenr);
2626 if (ws_error_action == correct_ws_error) {
2627 while (new_blank_lines_at_end--)
2628 remove_last_line(&postimage);
2631 * We would want to prevent write_out_results()
2632 * from taking place in apply_patch() that follows
2633 * the callchain led us here, which is:
2634 * apply_patch->check_patch_list->check_patch->
2635 * apply_data->apply_fragments->apply_one_fragment
2637 if (ws_error_action == die_on_ws_error)
2642 * Warn if it was necessary to reduce the number
2645 if ((leading != frag->leading) ||
2646 (trailing != frag->trailing))
2647 fprintf(stderr, "Context reduced to (%ld/%ld)"
2648 " to apply fragment at %d\n",
2649 leading, trailing, applied_pos+1);
2650 update_image(img, applied_pos, &preimage, &postimage);
2652 if (apply_verbosely)
2653 error("while searching for:\n%.*s",
2654 (int)(old - oldlines), oldlines);
2658 strbuf_release(&newlines);
2659 free(preimage.line_allocated);
2660 free(postimage.line_allocated);
2662 return (applied_pos < 0);
2665 static int apply_binary_fragment(struct image *img, struct patch *patch)
2667 struct fragment *fragment = patch->fragments;
2672 return error("missing binary patch data for '%s'",
2677 /* Binary patch is irreversible without the optional second hunk */
2678 if (apply_in_reverse) {
2679 if (!fragment->next)
2680 return error("cannot reverse-apply a binary patch "
2681 "without the reverse hunk to '%s'",
2683 ? patch->new_name : patch->old_name);
2684 fragment = fragment->next;
2686 switch (fragment->binary_patch_method) {
2687 case BINARY_DELTA_DEFLATED:
2688 dst = patch_delta(img->buf, img->len, fragment->patch,
2689 fragment->size, &len);
2696 case BINARY_LITERAL_DEFLATED:
2698 img->len = fragment->size;
2699 img->buf = xmalloc(img->len+1);
2700 memcpy(img->buf, fragment->patch, img->len);
2701 img->buf[img->len] = '\0';
2707 static int apply_binary(struct image *img, struct patch *patch)
2709 const char *name = patch->old_name ? patch->old_name : patch->new_name;
2710 unsigned char sha1[20];
2713 * For safety, we require patch index line to contain
2714 * full 40-byte textual SHA1 for old and new, at least for now.
2716 if (strlen(patch->old_sha1_prefix) != 40 ||
2717 strlen(patch->new_sha1_prefix) != 40 ||
2718 get_sha1_hex(patch->old_sha1_prefix, sha1) ||
2719 get_sha1_hex(patch->new_sha1_prefix, sha1))
2720 return error("cannot apply binary patch to '%s' "
2721 "without full index line", name);
2723 if (patch->old_name) {
2725 * See if the old one matches what the patch
2728 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2729 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
2730 return error("the patch applies to '%s' (%s), "
2731 "which does not match the "
2732 "current contents.",
2733 name, sha1_to_hex(sha1));
2736 /* Otherwise, the old one must be empty. */
2738 return error("the patch applies to an empty "
2739 "'%s' but it is not empty", name);
2742 get_sha1_hex(patch->new_sha1_prefix, sha1);
2743 if (is_null_sha1(sha1)) {
2745 return 0; /* deletion patch */
2748 if (has_sha1_file(sha1)) {
2749 /* We already have the postimage */
2750 enum object_type type;
2754 result = read_sha1_file(sha1, &type, &size);
2756 return error("the necessary postimage %s for "
2757 "'%s' cannot be read",
2758 patch->new_sha1_prefix, name);
2764 * We have verified buf matches the preimage;
2765 * apply the patch data to it, which is stored
2766 * in the patch->fragments->{patch,size}.
2768 if (apply_binary_fragment(img, patch))
2769 return error("binary patch does not apply to '%s'",
2772 /* verify that the result matches */
2773 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2774 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
2775 return error("binary patch to '%s' creates incorrect result (expecting %s, got %s)",
2776 name, patch->new_sha1_prefix, sha1_to_hex(sha1));
2782 static int apply_fragments(struct image *img, struct patch *patch)
2784 struct fragment *frag = patch->fragments;
2785 const char *name = patch->old_name ? patch->old_name : patch->new_name;
2786 unsigned ws_rule = patch->ws_rule;
2787 unsigned inaccurate_eof = patch->inaccurate_eof;
2789 if (patch->is_binary)
2790 return apply_binary(img, patch);
2793 if (apply_one_fragment(img, frag, inaccurate_eof, ws_rule)) {
2794 error("patch failed: %s:%ld", name, frag->oldpos);
2795 if (!apply_with_reject)
2804 static int read_file_or_gitlink(struct cache_entry *ce, struct strbuf *buf)
2809 if (S_ISGITLINK(ce->ce_mode)) {
2810 strbuf_grow(buf, 100);
2811 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(ce->sha1));
2813 enum object_type type;
2817 result = read_sha1_file(ce->sha1, &type, &sz);
2820 /* XXX read_sha1_file NUL-terminates */
2821 strbuf_attach(buf, result, sz, sz + 1);
2826 static struct patch *in_fn_table(const char *name)
2828 struct string_list_item *item;
2833 item = string_list_lookup(&fn_table, name);
2835 return (struct patch *)item->util;
2841 * item->util in the filename table records the status of the path.
2842 * Usually it points at a patch (whose result records the contents
2843 * of it after applying it), but it could be PATH_WAS_DELETED for a
2844 * path that a previously applied patch has already removed.
2846 #define PATH_TO_BE_DELETED ((struct patch *) -2)
2847 #define PATH_WAS_DELETED ((struct patch *) -1)
2849 static int to_be_deleted(struct patch *patch)
2851 return patch == PATH_TO_BE_DELETED;
2854 static int was_deleted(struct patch *patch)
2856 return patch == PATH_WAS_DELETED;
2859 static void add_to_fn_table(struct patch *patch)
2861 struct string_list_item *item;
2864 * Always add new_name unless patch is a deletion
2865 * This should cover the cases for normal diffs,
2866 * file creations and copies
2868 if (patch->new_name != NULL) {
2869 item = string_list_insert(&fn_table, patch->new_name);
2874 * store a failure on rename/deletion cases because
2875 * later chunks shouldn't patch old names
2877 if ((patch->new_name == NULL) || (patch->is_rename)) {
2878 item = string_list_insert(&fn_table, patch->old_name);
2879 item->util = PATH_WAS_DELETED;
2883 static void prepare_fn_table(struct patch *patch)
2886 * store information about incoming file deletion
2889 if ((patch->new_name == NULL) || (patch->is_rename)) {
2890 struct string_list_item *item;
2891 item = string_list_insert(&fn_table, patch->old_name);
2892 item->util = PATH_TO_BE_DELETED;
2894 patch = patch->next;
2898 static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce)
2900 struct strbuf buf = STRBUF_INIT;
2904 struct patch *tpatch;
2906 if (!(patch->is_copy || patch->is_rename) &&
2907 (tpatch = in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {
2908 if (was_deleted(tpatch)) {
2909 return error("patch %s has been renamed/deleted",
2912 /* We have a patched copy in memory use that */
2913 strbuf_add(&buf, tpatch->result, tpatch->resultsize);
2914 } else if (cached) {
2915 if (read_file_or_gitlink(ce, &buf))
2916 return error("read of %s failed", patch->old_name);
2917 } else if (patch->old_name) {
2918 if (S_ISGITLINK(patch->old_mode)) {
2920 read_file_or_gitlink(ce, &buf);
2923 * There is no way to apply subproject
2924 * patch without looking at the index.
2926 patch->fragments = NULL;
2929 if (read_old_data(st, patch->old_name, &buf))
2930 return error("read of %s failed", patch->old_name);
2934 img = strbuf_detach(&buf, &len);
2935 prepare_image(&image, img, len, !patch->is_binary);
2937 if (apply_fragments(&image, patch) < 0)
2938 return -1; /* note with --reject this succeeds. */
2939 patch->result = image.buf;
2940 patch->resultsize = image.len;
2941 add_to_fn_table(patch);
2942 free(image.line_allocated);
2944 if (0 < patch->is_delete && patch->resultsize)
2945 return error("removal patch leaves file contents");
2950 static int check_to_create_blob(const char *new_name, int ok_if_exists)
2953 if (!lstat(new_name, &nst)) {
2954 if (S_ISDIR(nst.st_mode) || ok_if_exists)
2957 * A leading component of new_name might be a symlink
2958 * that is going to be removed with this patch, but
2959 * still pointing at somewhere that has the path.
2960 * In such a case, path "new_name" does not exist as
2961 * far as git is concerned.
2963 if (has_symlink_leading_path(new_name, strlen(new_name)))
2966 return error("%s: already exists in working directory", new_name);
2968 else if ((errno != ENOENT) && (errno != ENOTDIR))
2969 return error("%s: %s", new_name, strerror(errno));
2973 static int verify_index_match(struct cache_entry *ce, struct stat *st)
2975 if (S_ISGITLINK(ce->ce_mode)) {
2976 if (!S_ISDIR(st->st_mode))
2980 return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
2983 static int check_preimage(struct patch *patch, struct cache_entry **ce, struct stat *st)
2985 const char *old_name = patch->old_name;
2986 struct patch *tpatch = NULL;
2988 unsigned st_mode = 0;
2991 * Make sure that we do not have local modifications from the
2992 * index when we are looking at the index. Also make sure
2993 * we have the preimage file to be patched in the work tree,
2994 * unless --cached, which tells git to apply only in the index.
2999 assert(patch->is_new <= 0);
3001 if (!(patch->is_copy || patch->is_rename) &&
3002 (tpatch = in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {
3003 if (was_deleted(tpatch))
3004 return error("%s: has been deleted/renamed", old_name);
3005 st_mode = tpatch->new_mode;
3006 } else if (!cached) {
3007 stat_ret = lstat(old_name, st);
3008 if (stat_ret && errno != ENOENT)
3009 return error("%s: %s", old_name, strerror(errno));
3012 if (to_be_deleted(tpatch))
3015 if (check_index && !tpatch) {
3016 int pos = cache_name_pos(old_name, strlen(old_name));
3018 if (patch->is_new < 0)
3020 return error("%s: does not exist in index", old_name);
3022 *ce = active_cache[pos];
3024 struct checkout costate;
3026 memset(&costate, 0, sizeof(costate));
3027 costate.base_dir = "";
3028 costate.refresh_cache = 1;
3029 if (checkout_entry(*ce, &costate, NULL) ||
3030 lstat(old_name, st))
3033 if (!cached && verify_index_match(*ce, st))
3034 return error("%s: does not match index", old_name);
3036 st_mode = (*ce)->ce_mode;
3037 } else if (stat_ret < 0) {
3038 if (patch->is_new < 0)
3040 return error("%s: %s", old_name, strerror(errno));
3043 if (!cached && !tpatch)
3044 st_mode = ce_mode_from_stat(*ce, st->st_mode);
3046 if (patch->is_new < 0)
3048 if (!patch->old_mode)
3049 patch->old_mode = st_mode;
3050 if ((st_mode ^ patch->old_mode) & S_IFMT)
3051 return error("%s: wrong type", old_name);
3052 if (st_mode != patch->old_mode)
3053 warning("%s has type %o, expected %o",
3054 old_name, st_mode, patch->old_mode);
3055 if (!patch->new_mode && !patch->is_delete)
3056 patch->new_mode = st_mode;
3061 patch->is_delete = 0;
3062 patch->old_name = NULL;
3066 static int check_patch(struct patch *patch)
3069 const char *old_name = patch->old_name;
3070 const char *new_name = patch->new_name;
3071 const char *name = old_name ? old_name : new_name;
3072 struct cache_entry *ce = NULL;
3073 struct patch *tpatch;
3077 patch->rejected = 1; /* we will drop this after we succeed */
3079 status = check_preimage(patch, &ce, &st);
3082 old_name = patch->old_name;
3084 if ((tpatch = in_fn_table(new_name)) &&
3085 (was_deleted(tpatch) || to_be_deleted(tpatch)))
3087 * A type-change diff is always split into a patch to
3088 * delete old, immediately followed by a patch to
3089 * create new (see diff.c::run_diff()); in such a case
3090 * it is Ok that the entry to be deleted by the
3091 * previous patch is still in the working tree and in
3099 ((0 < patch->is_new) | (0 < patch->is_rename) | patch->is_copy)) {
3101 cache_name_pos(new_name, strlen(new_name)) >= 0 &&
3103 return error("%s: already exists in index", new_name);
3105 int err = check_to_create_blob(new_name, ok_if_exists);
3109 if (!patch->new_mode) {
3110 if (0 < patch->is_new)
3111 patch->new_mode = S_IFREG | 0644;
3113 patch->new_mode = patch->old_mode;
3117 if (new_name && old_name) {
3118 int same = !strcmp(old_name, new_name);
3119 if (!patch->new_mode)
3120 patch->new_mode = patch->old_mode;
3121 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
3122 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
3123 patch->new_mode, new_name, patch->old_mode,
3124 same ? "" : " of ", same ? "" : old_name);
3127 if (apply_data(patch, &st, ce) < 0)
3128 return error("%s: patch does not apply", name);
3129 patch->rejected = 0;
3133 static int check_patch_list(struct patch *patch)
3137 prepare_fn_table(patch);
3139 if (apply_verbosely)
3140 say_patch_name(stderr,
3141 "Checking patch ", patch, "...\n");
3142 err |= check_patch(patch);
3143 patch = patch->next;
3148 /* This function tries to read the sha1 from the current index */
3149 static int get_current_sha1(const char *path, unsigned char *sha1)
3153 if (read_cache() < 0)
3155 pos = cache_name_pos(path, strlen(path));
3158 hashcpy(sha1, active_cache[pos]->sha1);
3162 /* Build an index that contains the just the files needed for a 3way merge */
3163 static void build_fake_ancestor(struct patch *list, const char *filename)
3165 struct patch *patch;
3166 struct index_state result = { NULL };
3169 /* Once we start supporting the reverse patch, it may be
3170 * worth showing the new sha1 prefix, but until then...
3172 for (patch = list; patch; patch = patch->next) {
3173 const unsigned char *sha1_ptr;
3174 unsigned char sha1[20];
3175 struct cache_entry *ce;
3178 name = patch->old_name ? patch->old_name : patch->new_name;
3179 if (0 < patch->is_new)
3181 else if (get_sha1(patch->old_sha1_prefix, sha1))
3182 /* git diff has no index line for mode/type changes */
3183 if (!patch->lines_added && !patch->lines_deleted) {
3184 if (get_current_sha1(patch->old_name, sha1))
3185 die("mode change for %s, which is not "
3186 "in current HEAD", name);
3189 die("sha1 information is lacking or useless "
3194 ce = make_cache_entry(patch->old_mode, sha1_ptr, name, 0, 0);
3196 die("make_cache_entry failed for path '%s'", name);
3197 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))
3198 die ("Could not add %s to temporary index", name);
3201 fd = open(filename, O_WRONLY | O_CREAT, 0666);
3202 if (fd < 0 || write_index(&result, fd) || close(fd))
3203 die ("Could not write temporary index to %s", filename);
3205 discard_index(&result);
3208 static void stat_patch_list(struct patch *patch)
3210 int files, adds, dels;
3212 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
3214 adds += patch->lines_added;
3215 dels += patch->lines_deleted;
3219 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
3222 static void numstat_patch_list(struct patch *patch)
3224 for ( ; patch; patch = patch->next) {
3226 name = patch->new_name ? patch->new_name : patch->old_name;
3227 if (patch->is_binary)
3230 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
3231 write_name_quoted(name, stdout, line_termination);
3235 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
3238 printf(" %s mode %06o %s\n", newdelete, mode, name);
3240 printf(" %s %s\n", newdelete, name);
3243 static void show_mode_change(struct patch *p, int show_name)
3245 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
3247 printf(" mode change %06o => %06o %s\n",
3248 p->old_mode, p->new_mode, p->new_name);
3250 printf(" mode change %06o => %06o\n",
3251 p->old_mode, p->new_mode);
3255 static void show_rename_copy(struct patch *p)
3257 const char *renamecopy = p->is_rename ? "rename" : "copy";
3258 const char *old, *new;
3260 /* Find common prefix */
3264 const char *slash_old, *slash_new;
3265 slash_old = strchr(old, '/');
3266 slash_new = strchr(new, '/');
3269 slash_old - old != slash_new - new ||
3270 memcmp(old, new, slash_new - new))
3272 old = slash_old + 1;
3273 new = slash_new + 1;
3275 /* p->old_name thru old is the common prefix, and old and new
3276 * through the end of names are renames
3278 if (old != p->old_name)
3279 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
3280 (int)(old - p->old_name), p->old_name,
3281 old, new, p->score);
3283 printf(" %s %s => %s (%d%%)\n", renamecopy,
3284 p->old_name, p->new_name, p->score);
3285 show_mode_change(p, 0);
3288 static void summary_patch_list(struct patch *patch)
3292 for (p = patch; p; p = p->next) {
3294 show_file_mode_name("create", p->new_mode, p->new_name);
3295 else if (p->is_delete)
3296 show_file_mode_name("delete", p->old_mode, p->old_name);
3298 if (p->is_rename || p->is_copy)
3299 show_rename_copy(p);
3302 printf(" rewrite %s (%d%%)\n",
3303 p->new_name, p->score);
3304 show_mode_change(p, 0);
3307 show_mode_change(p, 1);
3313 static void patch_stats(struct patch *patch)
3315 int lines = patch->lines_added + patch->lines_deleted;
3317 if (lines > max_change)
3319 if (patch->old_name) {
3320 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
3322 len = strlen(patch->old_name);
3326 if (patch->new_name) {
3327 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
3329 len = strlen(patch->new_name);
3335 static void remove_file(struct patch *patch, int rmdir_empty)
3338 if (remove_file_from_cache(patch->old_name) < 0)
3339 die("unable to remove %s from index", patch->old_name);
3342 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
3343 remove_path(patch->old_name);
3348 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
3351 struct cache_entry *ce;
3352 int namelen = strlen(path);
3353 unsigned ce_size = cache_entry_size(namelen);
3358 ce = xcalloc(1, ce_size);
3359 memcpy(ce->name, path, namelen);
3360 ce->ce_mode = create_ce_mode(mode);
3361 ce->ce_flags = namelen;
3362 if (S_ISGITLINK(mode)) {
3363 const char *s = buf;
3365 if (get_sha1_hex(s + strlen("Subproject commit "), ce->sha1))
3366 die("corrupt patch for subproject %s", path);
3369 if (lstat(path, &st) < 0)
3370 die_errno("unable to stat newly created file '%s'",
3372 fill_stat_cache_info(ce, &st);
3374 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
3375 die("unable to create backing store for newly created file %s", path);
3377 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
3378 die("unable to add cache entry for %s", path);
3381 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
3384 struct strbuf nbuf = STRBUF_INIT;
3386 if (S_ISGITLINK(mode)) {
3388 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
3390 return mkdir(path, 0777);
3393 if (has_symlinks && S_ISLNK(mode))
3394 /* Although buf:size is counted string, it also is NUL
3397 return symlink(buf, path);
3399 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
3403 if (convert_to_working_tree(path, buf, size, &nbuf)) {
3407 write_or_die(fd, buf, size);
3408 strbuf_release(&nbuf);
3411 die_errno("closing file '%s'", path);
3416 * We optimistically assume that the directories exist,
3417 * which is true 99% of the time anyway. If they don't,
3418 * we create them and try again.
3420 static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
3424 if (!try_create_file(path, mode, buf, size))
3427 if (errno == ENOENT) {
3428 if (safe_create_leading_directories(path))
3430 if (!try_create_file(path, mode, buf, size))
3434 if (errno == EEXIST || errno == EACCES) {
3435 /* We may be trying to create a file where a directory
3439 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
3443 if (errno == EEXIST) {
3444 unsigned int nr = getpid();
3447 char newpath[PATH_MAX];
3448 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
3449 if (!try_create_file(newpath, mode, buf, size)) {
3450 if (!rename(newpath, path))
3452 unlink_or_warn(newpath);
3455 if (errno != EEXIST)
3460 die_errno("unable to write file '%s' mode %o", path, mode);
3463 static void create_file(struct patch *patch)
3465 char *path = patch->new_name;
3466 unsigned mode = patch->new_mode;
3467 unsigned long size = patch->resultsize;
3468 char *buf = patch->result;
3471 mode = S_IFREG | 0644;
3472 create_one_file(path, mode, buf, size);
3473 add_index_file(path, mode, buf, size);
3476 /* phase zero is to remove, phase one is to create */
3477 static void write_out_one_result(struct patch *patch, int phase)
3479 if (patch->is_delete > 0) {
3481 remove_file(patch, 1);
3484 if (patch->is_new > 0 || patch->is_copy) {
3490 * Rename or modification boils down to the same
3491 * thing: remove the old, write the new
3494 remove_file(patch, patch->is_rename);
3499 static int write_out_one_reject(struct patch *patch)
3502 char namebuf[PATH_MAX];
3503 struct fragment *frag;
3506 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
3507 if (!frag->rejected)
3513 if (apply_verbosely)
3514 say_patch_name(stderr,
3515 "Applied patch ", patch, " cleanly.\n");
3519 /* This should not happen, because a removal patch that leaves
3520 * contents are marked "rejected" at the patch level.
3522 if (!patch->new_name)
3523 die("internal error");
3525 /* Say this even without --verbose */
3526 say_patch_name(stderr, "Applying patch ", patch, " with");
3527 fprintf(stderr, " %d rejects...\n", cnt);
3529 cnt = strlen(patch->new_name);
3530 if (ARRAY_SIZE(namebuf) <= cnt + 5) {
3531 cnt = ARRAY_SIZE(namebuf) - 5;
3532 warning("truncating .rej filename to %.*s.rej",
3533 cnt - 1, patch->new_name);
3535 memcpy(namebuf, patch->new_name, cnt);
3536 memcpy(namebuf + cnt, ".rej", 5);
3538 rej = fopen(namebuf, "w");
3540 return error("cannot open %s: %s", namebuf, strerror(errno));
3542 /* Normal git tools never deal with .rej, so do not pretend
3543 * this is a git patch by saying --git nor give extended
3544 * headers. While at it, maybe please "kompare" that wants
3545 * the trailing TAB and some garbage at the end of line ;-).
3547 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
3548 patch->new_name, patch->new_name);
3549 for (cnt = 1, frag = patch->fragments;
3551 cnt++, frag = frag->next) {
3552 if (!frag->rejected) {
3553 fprintf(stderr, "Hunk #%d applied cleanly.\n", cnt);
3556 fprintf(stderr, "Rejected hunk #%d.\n", cnt);
3557 fprintf(rej, "%.*s", frag->size, frag->patch);
3558 if (frag->patch[frag->size-1] != '\n')
3565 static int write_out_results(struct patch *list, int skipped_patch)
3571 if (!list && !skipped_patch)
3572 return error("No changes");
3574 for (phase = 0; phase < 2; phase++) {
3580 write_out_one_result(l, phase);
3581 if (phase == 1 && write_out_one_reject(l))
3590 static struct lock_file lock_file;
3592 static struct string_list limit_by_name;
3593 static int has_include;
3594 static void add_name_limit(const char *name, int exclude)
3596 struct string_list_item *it;
3598 it = string_list_append(&limit_by_name, name);
3599 it->util = exclude ? NULL : (void *) 1;
3602 static int use_patch(struct patch *p)
3604 const char *pathname = p->new_name ? p->new_name : p->old_name;
3607 /* Paths outside are not touched regardless of "--include" */
3608 if (0 < prefix_length) {
3609 int pathlen = strlen(pathname);
3610 if (pathlen <= prefix_length ||
3611 memcmp(prefix, pathname, prefix_length))
3615 /* See if it matches any of exclude/include rule */
3616 for (i = 0; i < limit_by_name.nr; i++) {
3617 struct string_list_item *it = &limit_by_name.items[i];
3618 if (!fnmatch(it->string, pathname, 0))
3619 return (it->util != NULL);
3623 * If we had any include, a path that does not match any rule is
3624 * not used. Otherwise, we saw bunch of exclude rules (or none)
3625 * and such a path is used.
3627 return !has_include;
3631 static void prefix_one(char **name)
3633 char *old_name = *name;
3636 *name = xstrdup(prefix_filename(prefix, prefix_length, *name));
3640 static void prefix_patches(struct patch *p)
3642 if (!prefix || p->is_toplevel_relative)
3644 for ( ; p; p = p->next) {
3645 if (p->new_name == p->old_name) {
3646 char *prefixed = p->new_name;
3647 prefix_one(&prefixed);
3648 p->new_name = p->old_name = prefixed;
3651 prefix_one(&p->new_name);
3652 prefix_one(&p->old_name);
3657 #define INACCURATE_EOF (1<<0)
3658 #define RECOUNT (1<<1)
3660 static int apply_patch(int fd, const char *filename, int options)
3663 struct strbuf buf = STRBUF_INIT;
3664 struct patch *list = NULL, **listp = &list;
3665 int skipped_patch = 0;
3667 /* FIXME - memory leak when using multiple patch files as inputs */
3668 memset(&fn_table, 0, sizeof(struct string_list));
3669 patch_input_file = filename;
3670 read_patch_file(&buf, fd);
3672 while (offset < buf.len) {
3673 struct patch *patch;
3676 patch = xcalloc(1, sizeof(*patch));
3677 patch->inaccurate_eof = !!(options & INACCURATE_EOF);
3678 patch->recount = !!(options & RECOUNT);
3679 nr = parse_chunk(buf.buf + offset, buf.len - offset, patch);
3682 if (apply_in_reverse)
3683 reverse_patches(patch);
3685 prefix_patches(patch);
3686 if (use_patch(patch)) {
3689 listp = &patch->next;
3692 /* perhaps free it a bit better? */
3699 if (whitespace_error && (ws_error_action == die_on_ws_error))
3702 update_index = check_index && apply;
3703 if (update_index && newfd < 0)
3704 newfd = hold_locked_index(&lock_file, 1);
3707 if (read_cache() < 0)
3708 die("unable to read index file");
3711 if ((check || apply) &&
3712 check_patch_list(list) < 0 &&
3716 if (apply && write_out_results(list, skipped_patch))
3720 build_fake_ancestor(list, fake_ancestor);
3723 stat_patch_list(list);
3726 numstat_patch_list(list);
3729 summary_patch_list(list);
3731 strbuf_release(&buf);
3735 static int git_apply_config(const char *var, const char *value, void *cb)
3737 if (!strcmp(var, "apply.whitespace"))
3738 return git_config_string(&apply_default_whitespace, var, value);
3739 else if (!strcmp(var, "apply.ignorewhitespace"))
3740 return git_config_string(&apply_default_ignorewhitespace, var, value);
3741 return git_default_config(var, value, cb);
3744 static int option_parse_exclude(const struct option *opt,
3745 const char *arg, int unset)
3747 add_name_limit(arg, 1);
3751 static int option_parse_include(const struct option *opt,
3752 const char *arg, int unset)
3754 add_name_limit(arg, 0);
3759 static int option_parse_p(const struct option *opt,
3760 const char *arg, int unset)
3762 p_value = atoi(arg);
3767 static int option_parse_z(const struct option *opt,
3768 const char *arg, int unset)
3771 line_termination = '\n';
3773 line_termination = 0;
3777 static int option_parse_space_change(const struct option *opt,
3778 const char *arg, int unset)
3781 ws_ignore_action = ignore_ws_none;
3783 ws_ignore_action = ignore_ws_change;
3787 static int option_parse_whitespace(const struct option *opt,
3788 const char *arg, int unset)
3790 const char **whitespace_option = opt->value;
3792 *whitespace_option = arg;
3793 parse_whitespace_option(arg);
3797 static int option_parse_directory(const struct option *opt,
3798 const char *arg, int unset)
3800 root_len = strlen(arg);
3801 if (root_len && arg[root_len - 1] != '/') {
3803 root = new_root = xmalloc(root_len + 2);
3804 strcpy(new_root, arg);
3805 strcpy(new_root + root_len++, "/");
3811 int cmd_apply(int argc, const char **argv, const char *prefix_)
3815 int is_not_gitdir = !startup_info->have_repository;
3817 int force_apply = 0;
3819 const char *whitespace_option = NULL;
3821 struct option builtin_apply_options[] = {
3822 { OPTION_CALLBACK, 0, "exclude", NULL, "path",
3823 "don't apply changes matching the given path",
3824 0, option_parse_exclude },
3825 { OPTION_CALLBACK, 0, "include", NULL, "path",
3826 "apply changes matching the given path",
3827 0, option_parse_include },
3828 { OPTION_CALLBACK, 'p', NULL, NULL, "num",
3829 "remove <num> leading slashes from traditional diff paths",
3830 0, option_parse_p },
3831 OPT_BOOLEAN(0, "no-add", &no_add,
3832 "ignore additions made by the patch"),
3833 OPT_BOOLEAN(0, "stat", &diffstat,
3834 "instead of applying the patch, output diffstat for the input"),
3835 { OPTION_BOOLEAN, 0, "allow-binary-replacement", &binary,
3836 NULL, "old option, now no-op",
3837 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },
3838 { OPTION_BOOLEAN, 0, "binary", &binary,
3839 NULL, "old option, now no-op",
3840 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },
3841 OPT_BOOLEAN(0, "numstat", &numstat,
3842 "shows number of added and deleted lines in decimal notation"),
3843 OPT_BOOLEAN(0, "summary", &summary,
3844 "instead of applying the patch, output a summary for the input"),
3845 OPT_BOOLEAN(0, "check", &check,
3846 "instead of applying the patch, see if the patch is applicable"),
3847 OPT_BOOLEAN(0, "index", &check_index,
3848 "make sure the patch is applicable to the current index"),
3849 OPT_BOOLEAN(0, "cached", &cached,
3850 "apply a patch without touching the working tree"),
3851 OPT_BOOLEAN(0, "apply", &force_apply,
3852 "also apply the patch (use with --stat/--summary/--check)"),
3853 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor,
3854 "build a temporary index based on embedded index information"),
3855 { OPTION_CALLBACK, 'z', NULL, NULL, NULL,
3856 "paths are separated with NUL character",
3857 PARSE_OPT_NOARG, option_parse_z },
3858 OPT_INTEGER('C', NULL, &p_context,
3859 "ensure at least <n> lines of context match"),
3860 { OPTION_CALLBACK, 0, "whitespace", &whitespace_option, "action",
3861 "detect new or modified lines that have whitespace errors",
3862 0, option_parse_whitespace },
3863 { OPTION_CALLBACK, 0, "ignore-space-change", NULL, NULL,
3864 "ignore changes in whitespace when finding context",
3865 PARSE_OPT_NOARG, option_parse_space_change },
3866 { OPTION_CALLBACK, 0, "ignore-whitespace", NULL, NULL,
3867 "ignore changes in whitespace when finding context",
3868 PARSE_OPT_NOARG, option_parse_space_change },
3869 OPT_BOOLEAN('R', "reverse", &apply_in_reverse,
3870 "apply the patch in reverse"),
3871 OPT_BOOLEAN(0, "unidiff-zero", &unidiff_zero,
3872 "don't expect at least one line of context"),
3873 OPT_BOOLEAN(0, "reject", &apply_with_reject,
3874 "leave the rejected hunks in corresponding *.rej files"),
3875 OPT__VERBOSE(&apply_verbosely, "be verbose"),
3876 OPT_BIT(0, "inaccurate-eof", &options,
3877 "tolerate incorrectly detected missing new-line at the end of file",
3879 OPT_BIT(0, "recount", &options,
3880 "do not trust the line counts in the hunk headers",
3882 { OPTION_CALLBACK, 0, "directory", NULL, "root",
3883 "prepend <root> to all filenames",
3884 0, option_parse_directory },
3889 prefix_length = prefix ? strlen(prefix) : 0;
3890 git_config(git_apply_config, NULL);
3891 if (apply_default_whitespace)
3892 parse_whitespace_option(apply_default_whitespace);
3893 if (apply_default_ignorewhitespace)
3894 parse_ignorewhitespace_option(apply_default_ignorewhitespace);
3896 argc = parse_options(argc, argv, prefix, builtin_apply_options,
3899 if (apply_with_reject)
3900 apply = apply_verbosely = 1;
3901 if (!force_apply && (diffstat || numstat || summary || check || fake_ancestor))
3903 if (check_index && is_not_gitdir)
3904 die("--index outside a repository");
3907 die("--cached outside a repository");
3910 for (i = 0; i < argc; i++) {
3911 const char *arg = argv[i];
3914 if (!strcmp(arg, "-")) {
3915 errs |= apply_patch(0, "<stdin>", options);
3918 } else if (0 < prefix_length)
3919 arg = prefix_filename(prefix, prefix_length, arg);
3921 fd = open(arg, O_RDONLY);
3923 die_errno("can't open patch '%s'", arg);
3925 set_default_whitespace_mode(whitespace_option);
3926 errs |= apply_patch(fd, arg, options);
3929 set_default_whitespace_mode(whitespace_option);
3931 errs |= apply_patch(0, "<stdin>", options);
3932 if (whitespace_error) {
3933 if (squelch_whitespace_errors &&
3934 squelch_whitespace_errors < whitespace_error) {
3936 whitespace_error - squelch_whitespace_errors;
3937 warning("squelched %d "
3938 "whitespace error%s",
3940 squelched == 1 ? "" : "s");
3942 if (ws_error_action == die_on_ws_error)
3943 die("%d line%s add%s whitespace errors.",
3945 whitespace_error == 1 ? "" : "s",
3946 whitespace_error == 1 ? "s" : "");
3947 if (applied_after_fixing_ws && apply)
3948 warning("%d line%s applied after"
3949 " fixing whitespace errors.",
3950 applied_after_fixing_ws,
3951 applied_after_fixing_ws == 1 ? "" : "s");
3952 else if (whitespace_error)
3953 warning("%d line%s add%s whitespace errors.",
3955 whitespace_error == 1 ? "" : "s",
3956 whitespace_error == 1 ? "s" : "");
3960 if (write_cache(newfd, active_cache, active_nr) ||
3961 commit_locked_index(&lock_file))
3962 die("Unable to write new index file");