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"
18 #include "parse-options.h"
21 * --check turns on checking that the working tree matches the
22 * files that are being modified, but doesn't apply the patch
23 * --stat does just a diffstat, and doesn't actually apply
24 * --numstat does numeric diffstat, and doesn't actually apply
25 * --index-info shows the old and new index info for paths if available.
26 * --index updates the cache as well.
27 * --cached updates only the cache without ever touching the working tree.
29 static const char *prefix;
30 static int prefix_length = -1;
31 static int newfd = -1;
33 static int unidiff_zero;
34 static int p_value = 1;
35 static int p_value_known;
36 static int check_index;
37 static int update_index;
44 static int apply_in_reverse;
45 static int apply_with_reject;
46 static int apply_verbosely;
47 static int allow_overlap;
49 static const char *fake_ancestor;
50 static int line_termination = '\n';
51 static unsigned int p_context = UINT_MAX;
52 static const char * const apply_usage[] = {
53 "git apply [options] [<patch>...]",
57 static enum ws_error_action {
62 } ws_error_action = warn_on_ws_error;
63 static int whitespace_error;
64 static int squelch_whitespace_errors = 5;
65 static int applied_after_fixing_ws;
67 static enum ws_ignore {
70 } ws_ignore_action = ignore_ws_none;
73 static const char *patch_input_file;
74 static const char *root;
76 static int read_stdin = 1;
79 static void parse_whitespace_option(const char *option)
82 ws_error_action = warn_on_ws_error;
85 if (!strcmp(option, "warn")) {
86 ws_error_action = warn_on_ws_error;
89 if (!strcmp(option, "nowarn")) {
90 ws_error_action = nowarn_ws_error;
93 if (!strcmp(option, "error")) {
94 ws_error_action = die_on_ws_error;
97 if (!strcmp(option, "error-all")) {
98 ws_error_action = die_on_ws_error;
99 squelch_whitespace_errors = 0;
102 if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
103 ws_error_action = correct_ws_error;
106 die(_("unrecognized whitespace option '%s'"), option);
109 static void parse_ignorewhitespace_option(const char *option)
111 if (!option || !strcmp(option, "no") ||
112 !strcmp(option, "false") || !strcmp(option, "never") ||
113 !strcmp(option, "none")) {
114 ws_ignore_action = ignore_ws_none;
117 if (!strcmp(option, "change")) {
118 ws_ignore_action = ignore_ws_change;
121 die(_("unrecognized whitespace ignore option '%s'"), option);
124 static void set_default_whitespace_mode(const char *whitespace_option)
126 if (!whitespace_option && !apply_default_whitespace)
127 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error);
131 * For "diff-stat" like behaviour, we keep track of the biggest change
132 * we've seen, and the longest filename. That allows us to do simple
135 static int max_change, max_len;
138 * Various "current state", notably line numbers and what
139 * file (and how) we're patching right now.. The "is_xxxx"
140 * things are flags, where -1 means "don't know yet".
142 static int linenr = 1;
145 * This represents one "hunk" from a patch, starting with
146 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
147 * patch text is pointed at by patch, and its byte length
148 * is stored in size. leading and trailing are the number
152 unsigned long leading, trailing;
153 unsigned long oldpos, oldlines;
154 unsigned long newpos, newlines;
159 struct fragment *next;
163 * When dealing with a binary patch, we reuse "leading" field
164 * to store the type of the binary hunk, either deflated "delta"
165 * or deflated "literal".
167 #define binary_patch_method leading
168 #define BINARY_DELTA_DEFLATED 1
169 #define BINARY_LITERAL_DEFLATED 2
172 * This represents a "patch" to a file, both metainfo changes
173 * such as creation/deletion, filemode and content changes represented
174 * as a series of fragments.
177 char *new_name, *old_name, *def_name;
178 unsigned int old_mode, new_mode;
179 int is_new, is_delete; /* -1 = unknown, 0 = false, 1 = true */
182 unsigned long deflate_origlen;
183 int lines_added, lines_deleted;
185 unsigned int is_toplevel_relative:1;
186 unsigned int inaccurate_eof:1;
187 unsigned int is_binary:1;
188 unsigned int is_copy:1;
189 unsigned int is_rename:1;
190 unsigned int recount:1;
191 struct fragment *fragments;
194 char old_sha1_prefix[41];
195 char new_sha1_prefix[41];
200 * A line in a file, len-bytes long (includes the terminating LF,
201 * except for an incomplete line at the end if the file ends with
202 * one), and its contents hashes to 'hash'.
208 #define LINE_COMMON 1
209 #define LINE_PATCHED 2
213 * This represents a "file", which is an array of "lines".
220 struct line *line_allocated;
225 * Records filenames that have been touched, in order to handle
226 * the case where more than one patches touch the same file.
229 static struct string_list fn_table;
231 static uint32_t hash_line(const char *cp, size_t len)
235 for (i = 0, h = 0; i < len; i++) {
236 if (!isspace(cp[i])) {
237 h = h * 3 + (cp[i] & 0xff);
244 * Compare lines s1 of length n1 and s2 of length n2, ignoring
245 * whitespace difference. Returns 1 if they match, 0 otherwise
247 static int fuzzy_matchlines(const char *s1, size_t n1,
248 const char *s2, size_t n2)
250 const char *last1 = s1 + n1 - 1;
251 const char *last2 = s2 + n2 - 1;
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 /* fmt must contain _one_ %s and no other substitution */
339 static void say_patch_name(FILE *output, const char *fmt, struct patch *patch)
341 struct strbuf sb = STRBUF_INIT;
343 if (patch->old_name && patch->new_name &&
344 strcmp(patch->old_name, patch->new_name)) {
345 quote_c_style(patch->old_name, &sb, NULL, 0);
346 strbuf_addstr(&sb, " => ");
347 quote_c_style(patch->new_name, &sb, NULL, 0);
349 const char *n = patch->new_name;
352 quote_c_style(n, &sb, NULL, 0);
354 fprintf(output, fmt, sb.buf);
359 #define CHUNKSIZE (8192)
362 static void read_patch_file(struct strbuf *sb, int fd)
364 if (strbuf_read(sb, fd, 0) < 0)
365 die_errno("git apply: failed to read");
368 * Make sure that we have some slop in the buffer
369 * so that we can do speculative "memcmp" etc, and
370 * see to it that it is NUL-filled.
372 strbuf_grow(sb, SLOP);
373 memset(sb->buf + sb->len, 0, SLOP);
376 static unsigned long linelen(const char *buffer, unsigned long size)
378 unsigned long len = 0;
381 if (*buffer++ == '\n')
387 static int is_dev_null(const char *str)
389 return !memcmp("/dev/null", str, 9) && isspace(str[9]);
395 static int name_terminate(const char *name, int namelen, int c, int terminate)
397 if (c == ' ' && !(terminate & TERM_SPACE))
399 if (c == '\t' && !(terminate & TERM_TAB))
405 /* remove double slashes to make --index work with such filenames */
406 static char *squash_slash(char *name)
414 if ((name[j++] = name[i++]) == '/')
415 while (name[i] == '/')
422 static char *find_name_gnu(const char *line, char *def, int p_value)
424 struct strbuf name = STRBUF_INIT;
428 * Proposed "new-style" GNU patch/diff format; see
429 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
431 if (unquote_c_style(&name, line, NULL)) {
432 strbuf_release(&name);
436 for (cp = name.buf; p_value; p_value--) {
437 cp = strchr(cp, '/');
439 strbuf_release(&name);
445 /* name can later be freed, so we need
446 * to memmove, not just return cp
448 strbuf_remove(&name, 0, cp - name.buf);
451 strbuf_insert(&name, 0, root, root_len);
452 return squash_slash(strbuf_detach(&name, NULL));
455 static size_t sane_tz_len(const char *line, size_t len)
459 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
461 tz = line + len - strlen(" +0500");
463 if (tz[1] != '+' && tz[1] != '-')
466 for (p = tz + 2; p != line + len; p++)
470 return line + len - tz;
473 static size_t tz_with_colon_len(const char *line, size_t len)
477 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
479 tz = line + len - strlen(" +08:00");
481 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
484 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
485 !isdigit(*p++) || !isdigit(*p++))
488 return line + len - tz;
491 static size_t date_len(const char *line, size_t len)
493 const char *date, *p;
495 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
497 p = date = line + len - strlen("72-02-05");
499 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
500 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
501 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */
504 if (date - line >= strlen("19") &&
505 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */
506 date -= strlen("19");
508 return line + len - date;
511 static size_t short_time_len(const char *line, size_t len)
513 const char *time, *p;
515 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
517 p = time = line + len - strlen(" 07:01:32");
519 /* Permit 1-digit hours? */
521 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
522 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
523 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */
526 return line + len - time;
529 static size_t fractional_time_len(const char *line, size_t len)
534 /* Expected format: 19:41:17.620000023 */
535 if (!len || !isdigit(line[len - 1]))
539 /* Fractional seconds. */
540 while (p > line && isdigit(*p))
545 /* Hours, minutes, and whole seconds. */
546 n = short_time_len(line, p - line);
550 return line + len - p + n;
553 static size_t trailing_spaces_len(const char *line, size_t len)
557 /* Expected format: ' ' x (1 or more) */
558 if (!len || line[len - 1] != ' ')
565 return line + len - (p + 1);
572 static size_t diff_timestamp_len(const char *line, size_t len)
574 const char *end = line + len;
578 * Posix: 2010-07-05 19:41:17
579 * GNU: 2010-07-05 19:41:17.620000023 -0500
582 if (!isdigit(end[-1]))
585 n = sane_tz_len(line, end - line);
587 n = tz_with_colon_len(line, end - line);
590 n = short_time_len(line, end - line);
592 n = fractional_time_len(line, end - line);
595 n = date_len(line, end - line);
596 if (!n) /* No date. Too bad. */
600 if (end == line) /* No space before date. */
602 if (end[-1] == '\t') { /* Success! */
604 return line + len - end;
606 if (end[-1] != ' ') /* No space before date. */
609 /* Whitespace damage. */
610 end -= trailing_spaces_len(line, end - line);
611 return line + len - end;
614 static char *find_name_common(const char *line, char *def, int p_value,
615 const char *end, int terminate)
618 const char *start = NULL;
622 while (line != end) {
625 if (!end && isspace(c)) {
628 if (name_terminate(start, line-start, c, terminate))
632 if (c == '/' && !--p_value)
636 return squash_slash(def);
639 return squash_slash(def);
642 * Generally we prefer the shorter name, especially
643 * if the other one is just a variation of that with
644 * something else tacked on to the end (ie "file.orig"
648 int deflen = strlen(def);
649 if (deflen < len && !strncmp(start, def, deflen))
650 return squash_slash(def);
655 char *ret = xmalloc(root_len + len + 1);
657 memcpy(ret + root_len, start, len);
658 ret[root_len + len] = '\0';
659 return squash_slash(ret);
662 return squash_slash(xmemdupz(start, len));
665 static char *find_name(const char *line, char *def, int p_value, int terminate)
668 char *name = find_name_gnu(line, def, p_value);
673 return find_name_common(line, def, p_value, NULL, terminate);
676 static char *find_name_traditional(const char *line, char *def, int p_value)
678 size_t len = strlen(line);
682 char *name = find_name_gnu(line, def, p_value);
687 len = strchrnul(line, '\n') - line;
688 date_len = diff_timestamp_len(line, len);
690 return find_name_common(line, def, p_value, NULL, TERM_TAB);
693 return find_name_common(line, def, p_value, line + len, 0);
696 static int count_slashes(const char *cp)
708 * Given the string after "--- " or "+++ ", guess the appropriate
709 * p_value for the given patch.
711 static int guess_p_value(const char *nameline)
716 if (is_dev_null(nameline))
718 name = find_name_traditional(nameline, NULL, 0);
721 cp = strchr(name, '/');
726 * Does it begin with "a/$our-prefix" and such? Then this is
727 * very likely to apply to our directory.
729 if (!strncmp(name, prefix, prefix_length))
730 val = count_slashes(prefix);
733 if (!strncmp(cp, prefix, prefix_length))
734 val = count_slashes(prefix) + 1;
742 * Does the ---/+++ line has the POSIX timestamp after the last HT?
743 * GNU diff puts epoch there to signal a creation/deletion event. Is
744 * this such a timestamp?
746 static int has_epoch_timestamp(const char *nameline)
749 * We are only interested in epoch timestamp; any non-zero
750 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
751 * For the same reason, the date must be either 1969-12-31 or
752 * 1970-01-01, and the seconds part must be "00".
754 const char stamp_regexp[] =
755 "^(1969-12-31|1970-01-01)"
757 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
759 "([-+][0-2][0-9]:?[0-5][0-9])\n";
760 const char *timestamp = NULL, *cp, *colon;
761 static regex_t *stamp;
767 for (cp = nameline; *cp != '\n'; cp++) {
774 stamp = xmalloc(sizeof(*stamp));
775 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
776 warning(_("Cannot prepare timestamp regexp %s"),
782 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
784 if (status != REG_NOMATCH)
785 warning(_("regexec returned %d for input: %s"),
790 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
792 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
794 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
795 if (timestamp[m[3].rm_so] == '-')
796 zoneoffset = -zoneoffset;
799 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
800 * (west of GMT) or 1970-01-01 (east of GMT)
802 if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) ||
803 (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10)))
806 hourminute = (strtol(timestamp + 11, NULL, 10) * 60 +
807 strtol(timestamp + 14, NULL, 10) -
810 return ((zoneoffset < 0 && hourminute == 1440) ||
811 (0 <= zoneoffset && !hourminute));
815 * Get the name etc info from the ---/+++ lines of a traditional patch header
817 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
818 * files, we can happily check the index for a match, but for creating a
819 * new file we should try to match whatever "patch" does. I have no idea.
821 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
825 first += 4; /* skip "--- " */
826 second += 4; /* skip "+++ " */
827 if (!p_value_known) {
829 p = guess_p_value(first);
830 q = guess_p_value(second);
832 if (0 <= p && p == q) {
837 if (is_dev_null(first)) {
839 patch->is_delete = 0;
840 name = find_name_traditional(second, NULL, p_value);
841 patch->new_name = name;
842 } else if (is_dev_null(second)) {
844 patch->is_delete = 1;
845 name = find_name_traditional(first, NULL, p_value);
846 patch->old_name = name;
848 name = find_name_traditional(first, NULL, p_value);
849 name = find_name_traditional(second, name, p_value);
850 if (has_epoch_timestamp(first)) {
852 patch->is_delete = 0;
853 patch->new_name = name;
854 } else if (has_epoch_timestamp(second)) {
856 patch->is_delete = 1;
857 patch->old_name = name;
859 patch->old_name = patch->new_name = name;
863 die(_("unable to find filename in patch at line %d"), linenr);
866 static int gitdiff_hdrend(const char *line, struct patch *patch)
872 * We're anal about diff header consistency, to make
873 * sure that we don't end up having strange ambiguous
874 * patches floating around.
876 * As a result, gitdiff_{old|new}name() will check
877 * their names against any previous information, just
880 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
882 if (!orig_name && !isnull)
883 return find_name(line, NULL, p_value, TERM_TAB);
892 die(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"), name, linenr);
893 another = find_name(line, NULL, p_value, TERM_TAB);
894 if (!another || memcmp(another, name, len + 1))
895 die(_("git apply: bad git-diff - inconsistent %s filename on line %d"), oldnew, linenr);
900 /* expect "/dev/null" */
901 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
902 die(_("git apply: bad git-diff - expected /dev/null on line %d"), linenr);
907 static int gitdiff_oldname(const char *line, struct patch *patch)
909 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
913 static int gitdiff_newname(const char *line, struct patch *patch)
915 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
919 static int gitdiff_oldmode(const char *line, struct patch *patch)
921 patch->old_mode = strtoul(line, NULL, 8);
925 static int gitdiff_newmode(const char *line, struct patch *patch)
927 patch->new_mode = strtoul(line, NULL, 8);
931 static int gitdiff_delete(const char *line, struct patch *patch)
933 patch->is_delete = 1;
934 patch->old_name = patch->def_name;
935 return gitdiff_oldmode(line, patch);
938 static int gitdiff_newfile(const char *line, struct patch *patch)
941 patch->new_name = patch->def_name;
942 return gitdiff_newmode(line, patch);
945 static int gitdiff_copysrc(const char *line, struct patch *patch)
948 patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
952 static int gitdiff_copydst(const char *line, struct patch *patch)
955 patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
959 static int gitdiff_renamesrc(const char *line, struct patch *patch)
961 patch->is_rename = 1;
962 patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
966 static int gitdiff_renamedst(const char *line, struct patch *patch)
968 patch->is_rename = 1;
969 patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
973 static int gitdiff_similarity(const char *line, struct patch *patch)
975 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
980 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
982 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
987 static int gitdiff_index(const char *line, struct patch *patch)
990 * index line is N hexadecimal, "..", N hexadecimal,
991 * and optional space with octal mode.
993 const char *ptr, *eol;
996 ptr = strchr(line, '.');
997 if (!ptr || ptr[1] != '.' || 40 < ptr - line)
1000 memcpy(patch->old_sha1_prefix, line, len);
1001 patch->old_sha1_prefix[len] = 0;
1004 ptr = strchr(line, ' ');
1005 eol = strchr(line, '\n');
1007 if (!ptr || eol < ptr)
1013 memcpy(patch->new_sha1_prefix, line, len);
1014 patch->new_sha1_prefix[len] = 0;
1016 patch->old_mode = strtoul(ptr+1, NULL, 8);
1021 * This is normal for a diff that doesn't change anything: we'll fall through
1022 * into the next diff. Tell the parser to break out.
1024 static int gitdiff_unrecognized(const char *line, struct patch *patch)
1029 static const char *stop_at_slash(const char *line, int llen)
1031 int nslash = p_value;
1034 for (i = 0; i < llen; i++) {
1036 if (ch == '/' && --nslash <= 0)
1043 * This is to extract the same name that appears on "diff --git"
1044 * line. We do not find and return anything if it is a rename
1045 * patch, and it is OK because we will find the name elsewhere.
1046 * We need to reliably find name only when it is mode-change only,
1047 * creation or deletion of an empty file. In any of these cases,
1048 * both sides are the same name under a/ and b/ respectively.
1050 static char *git_header_name(char *line, int llen)
1053 const char *second = NULL;
1054 size_t len, line_len;
1056 line += strlen("diff --git ");
1057 llen -= strlen("diff --git ");
1061 struct strbuf first = STRBUF_INIT;
1062 struct strbuf sp = STRBUF_INIT;
1064 if (unquote_c_style(&first, line, &second))
1065 goto free_and_fail1;
1067 /* advance to the first slash */
1068 cp = stop_at_slash(first.buf, first.len);
1069 /* we do not accept absolute paths */
1070 if (!cp || cp == first.buf)
1071 goto free_and_fail1;
1072 strbuf_remove(&first, 0, cp + 1 - first.buf);
1075 * second points at one past closing dq of name.
1076 * find the second name.
1078 while ((second < line + llen) && isspace(*second))
1081 if (line + llen <= second)
1082 goto free_and_fail1;
1083 if (*second == '"') {
1084 if (unquote_c_style(&sp, second, NULL))
1085 goto free_and_fail1;
1086 cp = stop_at_slash(sp.buf, sp.len);
1087 if (!cp || cp == sp.buf)
1088 goto free_and_fail1;
1089 /* They must match, otherwise ignore */
1090 if (strcmp(cp + 1, first.buf))
1091 goto free_and_fail1;
1092 strbuf_release(&sp);
1093 return strbuf_detach(&first, NULL);
1096 /* unquoted second */
1097 cp = stop_at_slash(second, line + llen - second);
1098 if (!cp || cp == second)
1099 goto free_and_fail1;
1101 if (line + llen - cp != first.len + 1 ||
1102 memcmp(first.buf, cp, first.len))
1103 goto free_and_fail1;
1104 return strbuf_detach(&first, NULL);
1107 strbuf_release(&first);
1108 strbuf_release(&sp);
1112 /* unquoted first name */
1113 name = stop_at_slash(line, llen);
1114 if (!name || name == line)
1119 * since the first name is unquoted, a dq if exists must be
1120 * the beginning of the second name.
1122 for (second = name; second < line + llen; second++) {
1123 if (*second == '"') {
1124 struct strbuf sp = STRBUF_INIT;
1127 if (unquote_c_style(&sp, second, NULL))
1128 goto free_and_fail2;
1130 np = stop_at_slash(sp.buf, sp.len);
1131 if (!np || np == sp.buf)
1132 goto free_and_fail2;
1135 len = sp.buf + sp.len - np;
1136 if (len < second - name &&
1137 !strncmp(np, name, len) &&
1138 isspace(name[len])) {
1140 strbuf_remove(&sp, 0, np - sp.buf);
1141 return strbuf_detach(&sp, NULL);
1145 strbuf_release(&sp);
1151 * Accept a name only if it shows up twice, exactly the same
1154 second = strchr(name, '\n');
1157 line_len = second - name;
1158 for (len = 0 ; ; len++) {
1159 switch (name[len]) {
1164 case '\t': case ' ':
1165 second = stop_at_slash(name + len, line_len - len);
1169 if (second[len] == '\n' && !strncmp(name, second, len)) {
1170 return xmemdupz(name, len);
1176 /* Verify that we recognize the lines following a git header */
1177 static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
1179 unsigned long offset;
1181 /* A git diff has explicit new/delete information, so we don't guess */
1183 patch->is_delete = 0;
1186 * Some things may not have the old name in the
1187 * rest of the headers anywhere (pure mode changes,
1188 * or removing or adding empty files), so we get
1189 * the default name from the header.
1191 patch->def_name = git_header_name(line, len);
1192 if (patch->def_name && root) {
1193 char *s = xmalloc(root_len + strlen(patch->def_name) + 1);
1195 strcpy(s + root_len, patch->def_name);
1196 free(patch->def_name);
1197 patch->def_name = s;
1203 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
1204 static const struct opentry {
1206 int (*fn)(const char *, struct patch *);
1208 { "@@ -", gitdiff_hdrend },
1209 { "--- ", gitdiff_oldname },
1210 { "+++ ", gitdiff_newname },
1211 { "old mode ", gitdiff_oldmode },
1212 { "new mode ", gitdiff_newmode },
1213 { "deleted file mode ", gitdiff_delete },
1214 { "new file mode ", gitdiff_newfile },
1215 { "copy from ", gitdiff_copysrc },
1216 { "copy to ", gitdiff_copydst },
1217 { "rename old ", gitdiff_renamesrc },
1218 { "rename new ", gitdiff_renamedst },
1219 { "rename from ", gitdiff_renamesrc },
1220 { "rename to ", gitdiff_renamedst },
1221 { "similarity index ", gitdiff_similarity },
1222 { "dissimilarity index ", gitdiff_dissimilarity },
1223 { "index ", gitdiff_index },
1224 { "", gitdiff_unrecognized },
1228 len = linelen(line, size);
1229 if (!len || line[len-1] != '\n')
1231 for (i = 0; i < ARRAY_SIZE(optable); i++) {
1232 const struct opentry *p = optable + i;
1233 int oplen = strlen(p->str);
1234 if (len < oplen || memcmp(p->str, line, oplen))
1236 if (p->fn(line + oplen, patch) < 0)
1245 static int parse_num(const char *line, unsigned long *p)
1249 if (!isdigit(*line))
1251 *p = strtoul(line, &ptr, 10);
1255 static int parse_range(const char *line, int len, int offset, const char *expect,
1256 unsigned long *p1, unsigned long *p2)
1260 if (offset < 0 || offset >= len)
1265 digits = parse_num(line, p1);
1275 digits = parse_num(line+1, p2);
1284 ex = strlen(expect);
1287 if (memcmp(line, expect, ex))
1293 static void recount_diff(char *line, int size, struct fragment *fragment)
1295 int oldlines = 0, newlines = 0, ret = 0;
1298 warning("recount: ignore empty hunk");
1303 int len = linelen(line, size);
1311 case ' ': case '\n':
1323 ret = size < 3 || prefixcmp(line, "@@ ");
1326 ret = size < 5 || prefixcmp(line, "diff ");
1333 warning(_("recount: unexpected line: %.*s"),
1334 (int)linelen(line, size), line);
1339 fragment->oldlines = oldlines;
1340 fragment->newlines = newlines;
1344 * Parse a unified diff fragment header of the
1345 * form "@@ -a,b +c,d @@"
1347 static int parse_fragment_header(char *line, int len, struct fragment *fragment)
1351 if (!len || line[len-1] != '\n')
1354 /* Figure out the number of lines in a fragment */
1355 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1356 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1361 static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
1363 unsigned long offset, len;
1365 patch->is_toplevel_relative = 0;
1366 patch->is_rename = patch->is_copy = 0;
1367 patch->is_new = patch->is_delete = -1;
1368 patch->old_mode = patch->new_mode = 0;
1369 patch->old_name = patch->new_name = NULL;
1370 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
1371 unsigned long nextlen;
1373 len = linelen(line, size);
1377 /* Testing this early allows us to take a few shortcuts.. */
1382 * Make sure we don't find any unconnected patch fragments.
1383 * That's a sign that we didn't find a header, and that a
1384 * patch has become corrupted/broken up.
1386 if (!memcmp("@@ -", line, 4)) {
1387 struct fragment dummy;
1388 if (parse_fragment_header(line, len, &dummy) < 0)
1390 die(_("patch fragment without header at line %d: %.*s"),
1391 linenr, (int)len-1, line);
1398 * Git patch? It might not have a real patch, just a rename
1399 * or mode change, so we handle that specially
1401 if (!memcmp("diff --git ", line, 11)) {
1402 int git_hdr_len = parse_git_header(line, len, size, patch);
1403 if (git_hdr_len <= len)
1405 if (!patch->old_name && !patch->new_name) {
1406 if (!patch->def_name)
1407 die(Q_("git diff header lacks filename information when removing "
1408 "%d leading pathname component (line %d)",
1409 "git diff header lacks filename information when removing "
1410 "%d leading pathname components (line %d)",
1413 patch->old_name = patch->new_name = patch->def_name;
1415 if (!patch->is_delete && !patch->new_name)
1416 die("git diff header lacks filename information "
1417 "(line %d)", linenr);
1418 patch->is_toplevel_relative = 1;
1419 *hdrsize = git_hdr_len;
1423 /* --- followed by +++ ? */
1424 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1428 * We only accept unified patches, so we want it to
1429 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1430 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1432 nextlen = linelen(line + len, size - len);
1433 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1436 /* Ok, we'll consider it a patch */
1437 parse_traditional_patch(line, line+len, patch);
1438 *hdrsize = len + nextlen;
1445 static void record_ws_error(unsigned result, const char *line, int len, int linenr)
1453 if (squelch_whitespace_errors &&
1454 squelch_whitespace_errors < whitespace_error)
1457 err = whitespace_error_string(result);
1458 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1459 patch_input_file, linenr, err, len, line);
1463 static void check_whitespace(const char *line, int len, unsigned ws_rule)
1465 unsigned result = ws_check(line + 1, len - 1, ws_rule);
1467 record_ws_error(result, line + 1, len - 2, linenr);
1471 * Parse a unified diff. Note that this really needs to parse each
1472 * fragment separately, since the only way to know the difference
1473 * between a "---" that is part of a patch, and a "---" that starts
1474 * the next patch is to look at the line counts..
1476 static int parse_fragment(char *line, unsigned long size,
1477 struct patch *patch, struct fragment *fragment)
1480 int len = linelen(line, size), offset;
1481 unsigned long oldlines, newlines;
1482 unsigned long leading, trailing;
1484 offset = parse_fragment_header(line, len, fragment);
1487 if (offset > 0 && patch->recount)
1488 recount_diff(line + offset, size - offset, fragment);
1489 oldlines = fragment->oldlines;
1490 newlines = fragment->newlines;
1494 /* Parse the thing.. */
1498 added = deleted = 0;
1501 offset += len, size -= len, line += len, linenr++) {
1502 if (!oldlines && !newlines)
1504 len = linelen(line, size);
1505 if (!len || line[len-1] != '\n')
1510 case '\n': /* newer GNU diff, an empty context line */
1514 if (!deleted && !added)
1519 if (apply_in_reverse &&
1520 ws_error_action != nowarn_ws_error)
1521 check_whitespace(line, len, patch->ws_rule);
1527 if (!apply_in_reverse &&
1528 ws_error_action != nowarn_ws_error)
1529 check_whitespace(line, len, patch->ws_rule);
1536 * We allow "\ No newline at end of file". Depending
1537 * on locale settings when the patch was produced we
1538 * don't know what this line looks like. The only
1539 * thing we do know is that it begins with "\ ".
1540 * Checking for 12 is just for sanity check -- any
1541 * l10n of "\ No newline..." is at least that long.
1544 if (len < 12 || memcmp(line, "\\ ", 2))
1549 if (oldlines || newlines)
1551 fragment->leading = leading;
1552 fragment->trailing = trailing;
1555 * If a fragment ends with an incomplete line, we failed to include
1556 * it in the above loop because we hit oldlines == newlines == 0
1559 if (12 < size && !memcmp(line, "\\ ", 2))
1560 offset += linelen(line, size);
1562 patch->lines_added += added;
1563 patch->lines_deleted += deleted;
1565 if (0 < patch->is_new && oldlines)
1566 return error(_("new file depends on old contents"));
1567 if (0 < patch->is_delete && newlines)
1568 return error(_("deleted file still has contents"));
1572 static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
1574 unsigned long offset = 0;
1575 unsigned long oldlines = 0, newlines = 0, context = 0;
1576 struct fragment **fragp = &patch->fragments;
1578 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1579 struct fragment *fragment;
1582 fragment = xcalloc(1, sizeof(*fragment));
1583 fragment->linenr = linenr;
1584 len = parse_fragment(line, size, patch, fragment);
1586 die(_("corrupt patch at line %d"), linenr);
1587 fragment->patch = line;
1588 fragment->size = len;
1589 oldlines += fragment->oldlines;
1590 newlines += fragment->newlines;
1591 context += fragment->leading + fragment->trailing;
1594 fragp = &fragment->next;
1602 * If something was removed (i.e. we have old-lines) it cannot
1603 * be creation, and if something was added it cannot be
1604 * deletion. However, the reverse is not true; --unified=0
1605 * patches that only add are not necessarily creation even
1606 * though they do not have any old lines, and ones that only
1607 * delete are not necessarily deletion.
1609 * Unfortunately, a real creation/deletion patch do _not_ have
1610 * any context line by definition, so we cannot safely tell it
1611 * apart with --unified=0 insanity. At least if the patch has
1612 * more than one hunk it is not creation or deletion.
1614 if (patch->is_new < 0 &&
1615 (oldlines || (patch->fragments && patch->fragments->next)))
1617 if (patch->is_delete < 0 &&
1618 (newlines || (patch->fragments && patch->fragments->next)))
1619 patch->is_delete = 0;
1621 if (0 < patch->is_new && oldlines)
1622 die(_("new file %s depends on old contents"), patch->new_name);
1623 if (0 < patch->is_delete && newlines)
1624 die(_("deleted file %s still has contents"), patch->old_name);
1625 if (!patch->is_delete && !newlines && context)
1628 "file %s becomes empty but is not deleted"),
1634 static inline int metadata_changes(struct patch *patch)
1636 return patch->is_rename > 0 ||
1637 patch->is_copy > 0 ||
1638 patch->is_new > 0 ||
1640 (patch->old_mode && patch->new_mode &&
1641 patch->old_mode != patch->new_mode);
1644 static char *inflate_it(const void *data, unsigned long size,
1645 unsigned long inflated_size)
1651 memset(&stream, 0, sizeof(stream));
1653 stream.next_in = (unsigned char *)data;
1654 stream.avail_in = size;
1655 stream.next_out = out = xmalloc(inflated_size);
1656 stream.avail_out = inflated_size;
1657 git_inflate_init(&stream);
1658 st = git_inflate(&stream, Z_FINISH);
1659 git_inflate_end(&stream);
1660 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1667 static struct fragment *parse_binary_hunk(char **buf_p,
1668 unsigned long *sz_p,
1673 * Expect a line that begins with binary patch method ("literal"
1674 * or "delta"), followed by the length of data before deflating.
1675 * a sequence of 'length-byte' followed by base-85 encoded data
1676 * should follow, terminated by a newline.
1678 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1679 * and we would limit the patch line to 66 characters,
1680 * so one line can fit up to 13 groups that would decode
1681 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1682 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1685 unsigned long size = *sz_p;
1686 char *buffer = *buf_p;
1688 unsigned long origlen;
1691 struct fragment *frag;
1693 llen = linelen(buffer, size);
1698 if (!prefixcmp(buffer, "delta ")) {
1699 patch_method = BINARY_DELTA_DEFLATED;
1700 origlen = strtoul(buffer + 6, NULL, 10);
1702 else if (!prefixcmp(buffer, "literal ")) {
1703 patch_method = BINARY_LITERAL_DEFLATED;
1704 origlen = strtoul(buffer + 8, NULL, 10);
1712 int byte_length, max_byte_length, newsize;
1713 llen = linelen(buffer, size);
1717 /* consume the blank line */
1723 * Minimum line is "A00000\n" which is 7-byte long,
1724 * and the line length must be multiple of 5 plus 2.
1726 if ((llen < 7) || (llen-2) % 5)
1728 max_byte_length = (llen - 2) / 5 * 4;
1729 byte_length = *buffer;
1730 if ('A' <= byte_length && byte_length <= 'Z')
1731 byte_length = byte_length - 'A' + 1;
1732 else if ('a' <= byte_length && byte_length <= 'z')
1733 byte_length = byte_length - 'a' + 27;
1736 /* if the input length was not multiple of 4, we would
1737 * have filler at the end but the filler should never
1740 if (max_byte_length < byte_length ||
1741 byte_length <= max_byte_length - 4)
1743 newsize = hunk_size + byte_length;
1744 data = xrealloc(data, newsize);
1745 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1747 hunk_size = newsize;
1752 frag = xcalloc(1, sizeof(*frag));
1753 frag->patch = inflate_it(data, hunk_size, origlen);
1757 frag->size = origlen;
1761 frag->binary_patch_method = patch_method;
1767 error(_("corrupt binary patch at line %d: %.*s"),
1768 linenr-1, llen-1, buffer);
1772 static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1775 * We have read "GIT binary patch\n"; what follows is a line
1776 * that says the patch method (currently, either "literal" or
1777 * "delta") and the length of data before deflating; a
1778 * sequence of 'length-byte' followed by base-85 encoded data
1781 * When a binary patch is reversible, there is another binary
1782 * hunk in the same format, starting with patch method (either
1783 * "literal" or "delta") with the length of data, and a sequence
1784 * of length-byte + base-85 encoded data, terminated with another
1785 * empty line. This data, when applied to the postimage, produces
1788 struct fragment *forward;
1789 struct fragment *reverse;
1793 forward = parse_binary_hunk(&buffer, &size, &status, &used);
1794 if (!forward && !status)
1795 /* there has to be one hunk (forward hunk) */
1796 return error(_("unrecognized binary patch at line %d"), linenr-1);
1798 /* otherwise we already gave an error message */
1801 reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1806 * Not having reverse hunk is not an error, but having
1807 * a corrupt reverse hunk is.
1809 free((void*) forward->patch);
1813 forward->next = reverse;
1814 patch->fragments = forward;
1815 patch->is_binary = 1;
1819 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
1821 int hdrsize, patchsize;
1822 int offset = find_header(buffer, size, &hdrsize, patch);
1827 patch->ws_rule = whitespace_rule(patch->new_name
1831 patchsize = parse_single_patch(buffer + offset + hdrsize,
1832 size - offset - hdrsize, patch);
1835 static const char *binhdr[] = {
1840 static const char git_binary[] = "GIT binary patch\n";
1842 int hd = hdrsize + offset;
1843 unsigned long llen = linelen(buffer + hd, size - hd);
1845 if (llen == sizeof(git_binary) - 1 &&
1846 !memcmp(git_binary, buffer + hd, llen)) {
1849 used = parse_binary(buffer + hd + llen,
1850 size - hd - llen, patch);
1852 patchsize = used + llen;
1856 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
1857 for (i = 0; binhdr[i]; i++) {
1858 int len = strlen(binhdr[i]);
1859 if (len < size - hd &&
1860 !memcmp(binhdr[i], buffer + hd, len)) {
1862 patch->is_binary = 1;
1869 /* Empty patch cannot be applied if it is a text patch
1870 * without metadata change. A binary patch appears
1873 if ((apply || check) &&
1874 (!patch->is_binary && !metadata_changes(patch)))
1875 die(_("patch with only garbage at line %d"), linenr);
1878 return offset + hdrsize + patchsize;
1881 #define swap(a,b) myswap((a),(b),sizeof(a))
1883 #define myswap(a, b, size) do { \
1884 unsigned char mytmp[size]; \
1885 memcpy(mytmp, &a, size); \
1886 memcpy(&a, &b, size); \
1887 memcpy(&b, mytmp, size); \
1890 static void reverse_patches(struct patch *p)
1892 for (; p; p = p->next) {
1893 struct fragment *frag = p->fragments;
1895 swap(p->new_name, p->old_name);
1896 swap(p->new_mode, p->old_mode);
1897 swap(p->is_new, p->is_delete);
1898 swap(p->lines_added, p->lines_deleted);
1899 swap(p->old_sha1_prefix, p->new_sha1_prefix);
1901 for (; frag; frag = frag->next) {
1902 swap(frag->newpos, frag->oldpos);
1903 swap(frag->newlines, frag->oldlines);
1908 static const char pluses[] =
1909 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1910 static const char minuses[]=
1911 "----------------------------------------------------------------------";
1913 static void show_stats(struct patch *patch)
1915 struct strbuf qname = STRBUF_INIT;
1916 char *cp = patch->new_name ? patch->new_name : patch->old_name;
1919 quote_c_style(cp, &qname, NULL, 0);
1922 * "scale" the filename
1928 if (qname.len > max) {
1929 cp = strchr(qname.buf + qname.len + 3 - max, '/');
1931 cp = qname.buf + qname.len + 3 - max;
1932 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
1935 if (patch->is_binary) {
1936 printf(" %-*s | Bin\n", max, qname.buf);
1937 strbuf_release(&qname);
1941 printf(" %-*s |", max, qname.buf);
1942 strbuf_release(&qname);
1945 * scale the add/delete
1947 max = max + max_change > 70 ? 70 - max : max_change;
1948 add = patch->lines_added;
1949 del = patch->lines_deleted;
1951 if (max_change > 0) {
1952 int total = ((add + del) * max + max_change / 2) / max_change;
1953 add = (add * max + max_change / 2) / max_change;
1956 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
1957 add, pluses, del, minuses);
1960 static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
1962 switch (st->st_mode & S_IFMT) {
1964 if (strbuf_readlink(buf, path, st->st_size) < 0)
1965 return error(_("unable to read symlink %s"), path);
1968 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
1969 return error(_("unable to open or read %s"), path);
1970 convert_to_git(path, buf->buf, buf->len, buf, 0);
1978 * Update the preimage, and the common lines in postimage,
1979 * from buffer buf of length len. If postlen is 0 the postimage
1980 * is updated in place, otherwise it's updated on a new buffer
1984 static void update_pre_post_images(struct image *preimage,
1985 struct image *postimage,
1987 size_t len, size_t postlen)
1990 char *new, *old, *fixed;
1991 struct image fixed_preimage;
1994 * Update the preimage with whitespace fixes. Note that we
1995 * are not losing preimage->buf -- apply_one_fragment() will
1998 prepare_image(&fixed_preimage, buf, len, 1);
1999 assert(fixed_preimage.nr == preimage->nr);
2000 for (i = 0; i < preimage->nr; i++)
2001 fixed_preimage.line[i].flag = preimage->line[i].flag;
2002 free(preimage->line_allocated);
2003 *preimage = fixed_preimage;
2006 * Adjust the common context lines in postimage. This can be
2007 * done in-place when we are just doing whitespace fixing,
2008 * which does not make the string grow, but needs a new buffer
2009 * when ignoring whitespace causes the update, since in this case
2010 * we could have e.g. tabs converted to multiple spaces.
2011 * We trust the caller to tell us if the update can be done
2012 * in place (postlen==0) or not.
2014 old = postimage->buf;
2016 new = postimage->buf = xmalloc(postlen);
2019 fixed = preimage->buf;
2020 for (i = ctx = 0; i < postimage->nr; i++) {
2021 size_t len = postimage->line[i].len;
2022 if (!(postimage->line[i].flag & LINE_COMMON)) {
2023 /* an added line -- no counterparts in preimage */
2024 memmove(new, old, len);
2030 /* a common context -- skip it in the original postimage */
2033 /* and find the corresponding one in the fixed preimage */
2034 while (ctx < preimage->nr &&
2035 !(preimage->line[ctx].flag & LINE_COMMON)) {
2036 fixed += preimage->line[ctx].len;
2039 if (preimage->nr <= ctx)
2042 /* and copy it in, while fixing the line length */
2043 len = preimage->line[ctx].len;
2044 memcpy(new, fixed, len);
2047 postimage->line[i].len = len;
2051 /* Fix the length of the whole thing */
2052 postimage->len = new - postimage->buf;
2055 static int match_fragment(struct image *img,
2056 struct image *preimage,
2057 struct image *postimage,
2061 int match_beginning, int match_end)
2064 char *fixed_buf, *buf, *orig, *target;
2065 struct strbuf fixed;
2069 if (preimage->nr + try_lno <= img->nr) {
2071 * The hunk falls within the boundaries of img.
2073 preimage_limit = preimage->nr;
2074 if (match_end && (preimage->nr + try_lno != img->nr))
2076 } else if (ws_error_action == correct_ws_error &&
2077 (ws_rule & WS_BLANK_AT_EOF)) {
2079 * This hunk extends beyond the end of img, and we are
2080 * removing blank lines at the end of the file. This
2081 * many lines from the beginning of the preimage must
2082 * match with img, and the remainder of the preimage
2085 preimage_limit = img->nr - try_lno;
2088 * The hunk extends beyond the end of the img and
2089 * we are not removing blanks at the end, so we
2090 * should reject the hunk at this position.
2095 if (match_beginning && try_lno)
2098 /* Quick hash check */
2099 for (i = 0; i < preimage_limit; i++)
2100 if ((img->line[try_lno + i].flag & LINE_PATCHED) ||
2101 (preimage->line[i].hash != img->line[try_lno + i].hash))
2104 if (preimage_limit == preimage->nr) {
2106 * Do we have an exact match? If we were told to match
2107 * at the end, size must be exactly at try+fragsize,
2108 * otherwise try+fragsize must be still within the preimage,
2109 * and either case, the old piece should match the preimage
2113 ? (try + preimage->len == img->len)
2114 : (try + preimage->len <= img->len)) &&
2115 !memcmp(img->buf + try, preimage->buf, preimage->len))
2119 * The preimage extends beyond the end of img, so
2120 * there cannot be an exact match.
2122 * There must be one non-blank context line that match
2123 * a line before the end of img.
2127 buf = preimage->buf;
2129 for (i = 0; i < preimage_limit; i++)
2130 buf_end += preimage->line[i].len;
2132 for ( ; buf < buf_end; buf++)
2140 * No exact match. If we are ignoring whitespace, run a line-by-line
2141 * fuzzy matching. We collect all the line length information because
2142 * we need it to adjust whitespace if we match.
2144 if (ws_ignore_action == ignore_ws_change) {
2147 size_t postlen = postimage->len;
2151 for (i = 0; i < preimage_limit; i++) {
2152 size_t prelen = preimage->line[i].len;
2153 size_t imglen = img->line[try_lno+i].len;
2155 if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,
2156 preimage->buf + preoff, prelen))
2158 if (preimage->line[i].flag & LINE_COMMON)
2159 postlen += imglen - prelen;
2165 * Ok, the preimage matches with whitespace fuzz.
2167 * imgoff now holds the true length of the target that
2168 * matches the preimage before the end of the file.
2170 * Count the number of characters in the preimage that fall
2171 * beyond the end of the file and make sure that all of them
2172 * are whitespace characters. (This can only happen if
2173 * we are removing blank lines at the end of the file.)
2175 buf = preimage_eof = preimage->buf + preoff;
2176 for ( ; i < preimage->nr; i++)
2177 preoff += preimage->line[i].len;
2178 preimage_end = preimage->buf + preoff;
2179 for ( ; buf < preimage_end; buf++)
2184 * Update the preimage and the common postimage context
2185 * lines to use the same whitespace as the target.
2186 * If whitespace is missing in the target (i.e.
2187 * if the preimage extends beyond the end of the file),
2188 * use the whitespace from the preimage.
2190 extra_chars = preimage_end - preimage_eof;
2191 strbuf_init(&fixed, imgoff + extra_chars);
2192 strbuf_add(&fixed, img->buf + try, imgoff);
2193 strbuf_add(&fixed, preimage_eof, extra_chars);
2194 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2195 update_pre_post_images(preimage, postimage,
2196 fixed_buf, fixed_len, postlen);
2200 if (ws_error_action != correct_ws_error)
2204 * The hunk does not apply byte-by-byte, but the hash says
2205 * it might with whitespace fuzz. We haven't been asked to
2206 * ignore whitespace, we were asked to correct whitespace
2207 * errors, so let's try matching after whitespace correction.
2209 * The preimage may extend beyond the end of the file,
2210 * but in this loop we will only handle the part of the
2211 * preimage that falls within the file.
2213 strbuf_init(&fixed, preimage->len + 1);
2214 orig = preimage->buf;
2215 target = img->buf + try;
2216 for (i = 0; i < preimage_limit; i++) {
2217 size_t oldlen = preimage->line[i].len;
2218 size_t tgtlen = img->line[try_lno + i].len;
2219 size_t fixstart = fixed.len;
2220 struct strbuf tgtfix;
2223 /* Try fixing the line in the preimage */
2224 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2226 /* Try fixing the line in the target */
2227 strbuf_init(&tgtfix, tgtlen);
2228 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2231 * If they match, either the preimage was based on
2232 * a version before our tree fixed whitespace breakage,
2233 * or we are lacking a whitespace-fix patch the tree
2234 * the preimage was based on already had (i.e. target
2235 * has whitespace breakage, the preimage doesn't).
2236 * In either case, we are fixing the whitespace breakages
2237 * so we might as well take the fix together with their
2240 match = (tgtfix.len == fixed.len - fixstart &&
2241 !memcmp(tgtfix.buf, fixed.buf + fixstart,
2242 fixed.len - fixstart));
2244 strbuf_release(&tgtfix);
2254 * Now handle the lines in the preimage that falls beyond the
2255 * end of the file (if any). They will only match if they are
2256 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2259 for ( ; i < preimage->nr; i++) {
2260 size_t fixstart = fixed.len; /* start of the fixed preimage */
2261 size_t oldlen = preimage->line[i].len;
2264 /* Try fixing the line in the preimage */
2265 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2267 for (j = fixstart; j < fixed.len; j++)
2268 if (!isspace(fixed.buf[j]))
2275 * Yes, the preimage is based on an older version that still
2276 * has whitespace breakages unfixed, and fixing them makes the
2277 * hunk match. Update the context lines in the postimage.
2279 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2280 update_pre_post_images(preimage, postimage,
2281 fixed_buf, fixed_len, 0);
2285 strbuf_release(&fixed);
2289 static int find_pos(struct image *img,
2290 struct image *preimage,
2291 struct image *postimage,
2294 int match_beginning, int match_end)
2297 unsigned long backwards, forwards, try;
2298 int backwards_lno, forwards_lno, try_lno;
2301 * If match_beginning or match_end is specified, there is no
2302 * point starting from a wrong line that will never match and
2303 * wander around and wait for a match at the specified end.
2305 if (match_beginning)
2308 line = img->nr - preimage->nr;
2311 * Because the comparison is unsigned, the following test
2312 * will also take care of a negative line number that can
2313 * result when match_end and preimage is larger than the target.
2315 if ((size_t) line > img->nr)
2319 for (i = 0; i < line; i++)
2320 try += img->line[i].len;
2323 * There's probably some smart way to do this, but I'll leave
2324 * that to the smart and beautiful people. I'm simple and stupid.
2327 backwards_lno = line;
2329 forwards_lno = line;
2332 for (i = 0; ; i++) {
2333 if (match_fragment(img, preimage, postimage,
2334 try, try_lno, ws_rule,
2335 match_beginning, match_end))
2339 if (backwards_lno == 0 && forwards_lno == img->nr)
2343 if (backwards_lno == 0) {
2348 backwards -= img->line[backwards_lno].len;
2350 try_lno = backwards_lno;
2352 if (forwards_lno == img->nr) {
2356 forwards += img->line[forwards_lno].len;
2359 try_lno = forwards_lno;
2366 static void remove_first_line(struct image *img)
2368 img->buf += img->line[0].len;
2369 img->len -= img->line[0].len;
2374 static void remove_last_line(struct image *img)
2376 img->len -= img->line[--img->nr].len;
2379 static void update_image(struct image *img,
2381 struct image *preimage,
2382 struct image *postimage)
2385 * remove the copy of preimage at offset in img
2386 * and replace it with postimage
2389 size_t remove_count, insert_count, applied_at = 0;
2394 * If we are removing blank lines at the end of img,
2395 * the preimage may extend beyond the end.
2396 * If that is the case, we must be careful only to
2397 * remove the part of the preimage that falls within
2398 * the boundaries of img. Initialize preimage_limit
2399 * to the number of lines in the preimage that falls
2400 * within the boundaries.
2402 preimage_limit = preimage->nr;
2403 if (preimage_limit > img->nr - applied_pos)
2404 preimage_limit = img->nr - applied_pos;
2406 for (i = 0; i < applied_pos; i++)
2407 applied_at += img->line[i].len;
2410 for (i = 0; i < preimage_limit; i++)
2411 remove_count += img->line[applied_pos + i].len;
2412 insert_count = postimage->len;
2414 /* Adjust the contents */
2415 result = xmalloc(img->len + insert_count - remove_count + 1);
2416 memcpy(result, img->buf, applied_at);
2417 memcpy(result + applied_at, postimage->buf, postimage->len);
2418 memcpy(result + applied_at + postimage->len,
2419 img->buf + (applied_at + remove_count),
2420 img->len - (applied_at + remove_count));
2423 img->len += insert_count - remove_count;
2424 result[img->len] = '\0';
2426 /* Adjust the line table */
2427 nr = img->nr + postimage->nr - preimage_limit;
2428 if (preimage_limit < postimage->nr) {
2430 * NOTE: this knows that we never call remove_first_line()
2431 * on anything other than pre/post image.
2433 img->line = xrealloc(img->line, nr * sizeof(*img->line));
2434 img->line_allocated = img->line;
2436 if (preimage_limit != postimage->nr)
2437 memmove(img->line + applied_pos + postimage->nr,
2438 img->line + applied_pos + preimage_limit,
2439 (img->nr - (applied_pos + preimage_limit)) *
2440 sizeof(*img->line));
2441 memcpy(img->line + applied_pos,
2443 postimage->nr * sizeof(*img->line));
2445 for (i = 0; i < postimage->nr; i++)
2446 img->line[applied_pos + i].flag |= LINE_PATCHED;
2450 static int apply_one_fragment(struct image *img, struct fragment *frag,
2451 int inaccurate_eof, unsigned ws_rule,
2454 int match_beginning, match_end;
2455 const char *patch = frag->patch;
2456 int size = frag->size;
2457 char *old, *oldlines;
2458 struct strbuf newlines;
2459 int new_blank_lines_at_end = 0;
2460 int found_new_blank_lines_at_end = 0;
2461 int hunk_linenr = frag->linenr;
2462 unsigned long leading, trailing;
2463 int pos, applied_pos;
2464 struct image preimage;
2465 struct image postimage;
2467 memset(&preimage, 0, sizeof(preimage));
2468 memset(&postimage, 0, sizeof(postimage));
2469 oldlines = xmalloc(size);
2470 strbuf_init(&newlines, size);
2475 int len = linelen(patch, size);
2477 int added_blank_line = 0;
2478 int is_blank_context = 0;
2485 * "plen" is how much of the line we should use for
2486 * the actual patch data. Normally we just remove the
2487 * first character on the line, but if the line is
2488 * followed by "\ No newline", then we also remove the
2489 * last one (which is the newline, of course).
2492 if (len < size && patch[len] == '\\')
2495 if (apply_in_reverse) {
2498 else if (first == '+')
2504 /* Newer GNU diff, empty context line */
2506 /* ... followed by '\No newline'; nothing */
2509 strbuf_addch(&newlines, '\n');
2510 add_line_info(&preimage, "\n", 1, LINE_COMMON);
2511 add_line_info(&postimage, "\n", 1, LINE_COMMON);
2512 is_blank_context = 1;
2515 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2516 ws_blank_line(patch + 1, plen, ws_rule))
2517 is_blank_context = 1;
2519 memcpy(old, patch + 1, plen);
2520 add_line_info(&preimage, old, plen,
2521 (first == ' ' ? LINE_COMMON : 0));
2525 /* Fall-through for ' ' */
2527 /* --no-add does not add new lines */
2528 if (first == '+' && no_add)
2531 start = newlines.len;
2533 !whitespace_error ||
2534 ws_error_action != correct_ws_error) {
2535 strbuf_add(&newlines, patch + 1, plen);
2538 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &applied_after_fixing_ws);
2540 add_line_info(&postimage, newlines.buf + start, newlines.len - start,
2541 (first == '+' ? 0 : LINE_COMMON));
2543 (ws_rule & WS_BLANK_AT_EOF) &&
2544 ws_blank_line(patch + 1, plen, ws_rule))
2545 added_blank_line = 1;
2547 case '@': case '\\':
2548 /* Ignore it, we already handled it */
2551 if (apply_verbosely)
2552 error(_("invalid start of line: '%c'"), first);
2555 if (added_blank_line) {
2556 if (!new_blank_lines_at_end)
2557 found_new_blank_lines_at_end = hunk_linenr;
2558 new_blank_lines_at_end++;
2560 else if (is_blank_context)
2563 new_blank_lines_at_end = 0;
2568 if (inaccurate_eof &&
2569 old > oldlines && old[-1] == '\n' &&
2570 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
2572 strbuf_setlen(&newlines, newlines.len - 1);
2575 leading = frag->leading;
2576 trailing = frag->trailing;
2579 * A hunk to change lines at the beginning would begin with
2581 * but we need to be careful. -U0 that inserts before the second
2582 * line also has this pattern.
2584 * And a hunk to add to an empty file would begin with
2587 * In other words, a hunk that is (frag->oldpos <= 1) with or
2588 * without leading context must match at the beginning.
2590 match_beginning = (!frag->oldpos ||
2591 (frag->oldpos == 1 && !unidiff_zero));
2594 * A hunk without trailing lines must match at the end.
2595 * However, we simply cannot tell if a hunk must match end
2596 * from the lack of trailing lines if the patch was generated
2597 * with unidiff without any context.
2599 match_end = !unidiff_zero && !trailing;
2601 pos = frag->newpos ? (frag->newpos - 1) : 0;
2602 preimage.buf = oldlines;
2603 preimage.len = old - oldlines;
2604 postimage.buf = newlines.buf;
2605 postimage.len = newlines.len;
2606 preimage.line = preimage.line_allocated;
2607 postimage.line = postimage.line_allocated;
2611 applied_pos = find_pos(img, &preimage, &postimage, pos,
2612 ws_rule, match_beginning, match_end);
2614 if (applied_pos >= 0)
2617 /* Am I at my context limits? */
2618 if ((leading <= p_context) && (trailing <= p_context))
2620 if (match_beginning || match_end) {
2621 match_beginning = match_end = 0;
2626 * Reduce the number of context lines; reduce both
2627 * leading and trailing if they are equal otherwise
2628 * just reduce the larger context.
2630 if (leading >= trailing) {
2631 remove_first_line(&preimage);
2632 remove_first_line(&postimage);
2636 if (trailing > leading) {
2637 remove_last_line(&preimage);
2638 remove_last_line(&postimage);
2643 if (applied_pos >= 0) {
2644 if (new_blank_lines_at_end &&
2645 preimage.nr + applied_pos >= img->nr &&
2646 (ws_rule & WS_BLANK_AT_EOF) &&
2647 ws_error_action != nowarn_ws_error) {
2648 record_ws_error(WS_BLANK_AT_EOF, "+", 1,
2649 found_new_blank_lines_at_end);
2650 if (ws_error_action == correct_ws_error) {
2651 while (new_blank_lines_at_end--)
2652 remove_last_line(&postimage);
2655 * We would want to prevent write_out_results()
2656 * from taking place in apply_patch() that follows
2657 * the callchain led us here, which is:
2658 * apply_patch->check_patch_list->check_patch->
2659 * apply_data->apply_fragments->apply_one_fragment
2661 if (ws_error_action == die_on_ws_error)
2665 if (apply_verbosely && applied_pos != pos) {
2666 int offset = applied_pos - pos;
2667 if (apply_in_reverse)
2668 offset = 0 - offset;
2670 Q_("Hunk #%d succeeded at %d (offset %d line).",
2671 "Hunk #%d succeeded at %d (offset %d lines).",
2673 nth_fragment, applied_pos + 1, offset);
2677 * Warn if it was necessary to reduce the number
2680 if ((leading != frag->leading) ||
2681 (trailing != frag->trailing))
2682 fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"
2683 " to apply fragment at %d"),
2684 leading, trailing, applied_pos+1);
2685 update_image(img, applied_pos, &preimage, &postimage);
2687 if (apply_verbosely)
2688 error(_("while searching for:\n%.*s"),
2689 (int)(old - oldlines), oldlines);
2693 strbuf_release(&newlines);
2694 free(preimage.line_allocated);
2695 free(postimage.line_allocated);
2697 return (applied_pos < 0);
2700 static int apply_binary_fragment(struct image *img, struct patch *patch)
2702 struct fragment *fragment = patch->fragments;
2707 return error(_("missing binary patch data for '%s'"),
2712 /* Binary patch is irreversible without the optional second hunk */
2713 if (apply_in_reverse) {
2714 if (!fragment->next)
2715 return error("cannot reverse-apply a binary patch "
2716 "without the reverse hunk to '%s'",
2718 ? patch->new_name : patch->old_name);
2719 fragment = fragment->next;
2721 switch (fragment->binary_patch_method) {
2722 case BINARY_DELTA_DEFLATED:
2723 dst = patch_delta(img->buf, img->len, fragment->patch,
2724 fragment->size, &len);
2731 case BINARY_LITERAL_DEFLATED:
2733 img->len = fragment->size;
2734 img->buf = xmalloc(img->len+1);
2735 memcpy(img->buf, fragment->patch, img->len);
2736 img->buf[img->len] = '\0';
2742 static int apply_binary(struct image *img, struct patch *patch)
2744 const char *name = patch->old_name ? patch->old_name : patch->new_name;
2745 unsigned char sha1[20];
2748 * For safety, we require patch index line to contain
2749 * full 40-byte textual SHA1 for old and new, at least for now.
2751 if (strlen(patch->old_sha1_prefix) != 40 ||
2752 strlen(patch->new_sha1_prefix) != 40 ||
2753 get_sha1_hex(patch->old_sha1_prefix, sha1) ||
2754 get_sha1_hex(patch->new_sha1_prefix, sha1))
2755 return error("cannot apply binary patch to '%s' "
2756 "without full index line", name);
2758 if (patch->old_name) {
2760 * See if the old one matches what the patch
2763 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2764 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
2765 return error("the patch applies to '%s' (%s), "
2766 "which does not match the "
2767 "current contents.",
2768 name, sha1_to_hex(sha1));
2771 /* Otherwise, the old one must be empty. */
2773 return error("the patch applies to an empty "
2774 "'%s' but it is not empty", name);
2777 get_sha1_hex(patch->new_sha1_prefix, sha1);
2778 if (is_null_sha1(sha1)) {
2780 return 0; /* deletion patch */
2783 if (has_sha1_file(sha1)) {
2784 /* We already have the postimage */
2785 enum object_type type;
2789 result = read_sha1_file(sha1, &type, &size);
2791 return error("the necessary postimage %s for "
2792 "'%s' cannot be read",
2793 patch->new_sha1_prefix, name);
2799 * We have verified buf matches the preimage;
2800 * apply the patch data to it, which is stored
2801 * in the patch->fragments->{patch,size}.
2803 if (apply_binary_fragment(img, patch))
2804 return error(_("binary patch does not apply to '%s'"),
2807 /* verify that the result matches */
2808 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2809 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
2810 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
2811 name, patch->new_sha1_prefix, sha1_to_hex(sha1));
2817 static int apply_fragments(struct image *img, struct patch *patch)
2819 struct fragment *frag = patch->fragments;
2820 const char *name = patch->old_name ? patch->old_name : patch->new_name;
2821 unsigned ws_rule = patch->ws_rule;
2822 unsigned inaccurate_eof = patch->inaccurate_eof;
2825 if (patch->is_binary)
2826 return apply_binary(img, patch);
2830 if (apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {
2831 error(_("patch failed: %s:%ld"), name, frag->oldpos);
2832 if (!apply_with_reject)
2841 static int read_file_or_gitlink(struct cache_entry *ce, struct strbuf *buf)
2846 if (S_ISGITLINK(ce->ce_mode)) {
2847 strbuf_grow(buf, 100);
2848 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(ce->sha1));
2850 enum object_type type;
2854 result = read_sha1_file(ce->sha1, &type, &sz);
2857 /* XXX read_sha1_file NUL-terminates */
2858 strbuf_attach(buf, result, sz, sz + 1);
2863 static struct patch *in_fn_table(const char *name)
2865 struct string_list_item *item;
2870 item = string_list_lookup(&fn_table, name);
2872 return (struct patch *)item->util;
2878 * item->util in the filename table records the status of the path.
2879 * Usually it points at a patch (whose result records the contents
2880 * of it after applying it), but it could be PATH_WAS_DELETED for a
2881 * path that a previously applied patch has already removed.
2883 #define PATH_TO_BE_DELETED ((struct patch *) -2)
2884 #define PATH_WAS_DELETED ((struct patch *) -1)
2886 static int to_be_deleted(struct patch *patch)
2888 return patch == PATH_TO_BE_DELETED;
2891 static int was_deleted(struct patch *patch)
2893 return patch == PATH_WAS_DELETED;
2896 static void add_to_fn_table(struct patch *patch)
2898 struct string_list_item *item;
2901 * Always add new_name unless patch is a deletion
2902 * This should cover the cases for normal diffs,
2903 * file creations and copies
2905 if (patch->new_name != NULL) {
2906 item = string_list_insert(&fn_table, patch->new_name);
2911 * store a failure on rename/deletion cases because
2912 * later chunks shouldn't patch old names
2914 if ((patch->new_name == NULL) || (patch->is_rename)) {
2915 item = string_list_insert(&fn_table, patch->old_name);
2916 item->util = PATH_WAS_DELETED;
2920 static void prepare_fn_table(struct patch *patch)
2923 * store information about incoming file deletion
2926 if ((patch->new_name == NULL) || (patch->is_rename)) {
2927 struct string_list_item *item;
2928 item = string_list_insert(&fn_table, patch->old_name);
2929 item->util = PATH_TO_BE_DELETED;
2931 patch = patch->next;
2935 static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce)
2937 struct strbuf buf = STRBUF_INIT;
2941 struct patch *tpatch;
2943 if (!(patch->is_copy || patch->is_rename) &&
2944 (tpatch = in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {
2945 if (was_deleted(tpatch)) {
2946 return error(_("patch %s has been renamed/deleted"),
2949 /* We have a patched copy in memory use that */
2950 strbuf_add(&buf, tpatch->result, tpatch->resultsize);
2951 } else if (cached) {
2952 if (read_file_or_gitlink(ce, &buf))
2953 return error(_("read of %s failed"), patch->old_name);
2954 } else if (patch->old_name) {
2955 if (S_ISGITLINK(patch->old_mode)) {
2957 read_file_or_gitlink(ce, &buf);
2960 * There is no way to apply subproject
2961 * patch without looking at the index.
2963 patch->fragments = NULL;
2966 if (read_old_data(st, patch->old_name, &buf))
2967 return error(_("read of %s failed"), patch->old_name);
2971 img = strbuf_detach(&buf, &len);
2972 prepare_image(&image, img, len, !patch->is_binary);
2974 if (apply_fragments(&image, patch) < 0)
2975 return -1; /* note with --reject this succeeds. */
2976 patch->result = image.buf;
2977 patch->resultsize = image.len;
2978 add_to_fn_table(patch);
2979 free(image.line_allocated);
2981 if (0 < patch->is_delete && patch->resultsize)
2982 return error(_("removal patch leaves file contents"));
2987 static int check_to_create_blob(const char *new_name, int ok_if_exists)
2990 if (!lstat(new_name, &nst)) {
2991 if (S_ISDIR(nst.st_mode) || ok_if_exists)
2994 * A leading component of new_name might be a symlink
2995 * that is going to be removed with this patch, but
2996 * still pointing at somewhere that has the path.
2997 * In such a case, path "new_name" does not exist as
2998 * far as git is concerned.
3000 if (has_symlink_leading_path(new_name, strlen(new_name)))
3003 return error(_("%s: already exists in working directory"), new_name);
3005 else if ((errno != ENOENT) && (errno != ENOTDIR))
3006 return error("%s: %s", new_name, strerror(errno));
3010 static int verify_index_match(struct cache_entry *ce, struct stat *st)
3012 if (S_ISGITLINK(ce->ce_mode)) {
3013 if (!S_ISDIR(st->st_mode))
3017 return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
3020 static int check_preimage(struct patch *patch, struct cache_entry **ce, struct stat *st)
3022 const char *old_name = patch->old_name;
3023 struct patch *tpatch = NULL;
3025 unsigned st_mode = 0;
3028 * Make sure that we do not have local modifications from the
3029 * index when we are looking at the index. Also make sure
3030 * we have the preimage file to be patched in the work tree,
3031 * unless --cached, which tells git to apply only in the index.
3036 assert(patch->is_new <= 0);
3038 if (!(patch->is_copy || patch->is_rename) &&
3039 (tpatch = in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {
3040 if (was_deleted(tpatch))
3041 return error(_("%s: has been deleted/renamed"), old_name);
3042 st_mode = tpatch->new_mode;
3043 } else if (!cached) {
3044 stat_ret = lstat(old_name, st);
3045 if (stat_ret && errno != ENOENT)
3046 return error(_("%s: %s"), old_name, strerror(errno));
3049 if (to_be_deleted(tpatch))
3052 if (check_index && !tpatch) {
3053 int pos = cache_name_pos(old_name, strlen(old_name));
3055 if (patch->is_new < 0)
3057 return error(_("%s: does not exist in index"), old_name);
3059 *ce = active_cache[pos];
3061 struct checkout costate;
3063 memset(&costate, 0, sizeof(costate));
3064 costate.base_dir = "";
3065 costate.refresh_cache = 1;
3066 if (checkout_entry(*ce, &costate, NULL) ||
3067 lstat(old_name, st))
3070 if (!cached && verify_index_match(*ce, st))
3071 return error(_("%s: does not match index"), old_name);
3073 st_mode = (*ce)->ce_mode;
3074 } else if (stat_ret < 0) {
3075 if (patch->is_new < 0)
3077 return error(_("%s: %s"), old_name, strerror(errno));
3080 if (!cached && !tpatch)
3081 st_mode = ce_mode_from_stat(*ce, st->st_mode);
3083 if (patch->is_new < 0)
3085 if (!patch->old_mode)
3086 patch->old_mode = st_mode;
3087 if ((st_mode ^ patch->old_mode) & S_IFMT)
3088 return error(_("%s: wrong type"), old_name);
3089 if (st_mode != patch->old_mode)
3090 warning(_("%s has type %o, expected %o"),
3091 old_name, st_mode, patch->old_mode);
3092 if (!patch->new_mode && !patch->is_delete)
3093 patch->new_mode = st_mode;
3098 patch->is_delete = 0;
3099 patch->old_name = NULL;
3103 static int check_patch(struct patch *patch)
3106 const char *old_name = patch->old_name;
3107 const char *new_name = patch->new_name;
3108 const char *name = old_name ? old_name : new_name;
3109 struct cache_entry *ce = NULL;
3110 struct patch *tpatch;
3114 patch->rejected = 1; /* we will drop this after we succeed */
3116 status = check_preimage(patch, &ce, &st);
3119 old_name = patch->old_name;
3121 if ((tpatch = in_fn_table(new_name)) &&
3122 (was_deleted(tpatch) || to_be_deleted(tpatch)))
3124 * A type-change diff is always split into a patch to
3125 * delete old, immediately followed by a patch to
3126 * create new (see diff.c::run_diff()); in such a case
3127 * it is Ok that the entry to be deleted by the
3128 * previous patch is still in the working tree and in
3136 ((0 < patch->is_new) | (0 < patch->is_rename) | patch->is_copy)) {
3138 cache_name_pos(new_name, strlen(new_name)) >= 0 &&
3140 return error(_("%s: already exists in index"), new_name);
3142 int err = check_to_create_blob(new_name, ok_if_exists);
3146 if (!patch->new_mode) {
3147 if (0 < patch->is_new)
3148 patch->new_mode = S_IFREG | 0644;
3150 patch->new_mode = patch->old_mode;
3154 if (new_name && old_name) {
3155 int same = !strcmp(old_name, new_name);
3156 if (!patch->new_mode)
3157 patch->new_mode = patch->old_mode;
3158 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
3159 return error(_("new mode (%o) of %s does not match old mode (%o)%s%s"),
3160 patch->new_mode, new_name, patch->old_mode,
3161 same ? "" : " of ", same ? "" : old_name);
3164 if (apply_data(patch, &st, ce) < 0)
3165 return error(_("%s: patch does not apply"), name);
3166 patch->rejected = 0;
3170 static int check_patch_list(struct patch *patch)
3174 prepare_fn_table(patch);
3176 if (apply_verbosely)
3177 say_patch_name(stderr,
3178 _("Checking patch %s..."), patch);
3179 err |= check_patch(patch);
3180 patch = patch->next;
3185 /* This function tries to read the sha1 from the current index */
3186 static int get_current_sha1(const char *path, unsigned char *sha1)
3190 if (read_cache() < 0)
3192 pos = cache_name_pos(path, strlen(path));
3195 hashcpy(sha1, active_cache[pos]->sha1);
3199 /* Build an index that contains the just the files needed for a 3way merge */
3200 static void build_fake_ancestor(struct patch *list, const char *filename)
3202 struct patch *patch;
3203 struct index_state result = { NULL };
3206 /* Once we start supporting the reverse patch, it may be
3207 * worth showing the new sha1 prefix, but until then...
3209 for (patch = list; patch; patch = patch->next) {
3210 const unsigned char *sha1_ptr;
3211 unsigned char sha1[20];
3212 struct cache_entry *ce;
3215 name = patch->old_name ? patch->old_name : patch->new_name;
3216 if (0 < patch->is_new)
3218 else if (get_sha1(patch->old_sha1_prefix, sha1))
3219 /* git diff has no index line for mode/type changes */
3220 if (!patch->lines_added && !patch->lines_deleted) {
3221 if (get_current_sha1(patch->old_name, sha1))
3222 die("mode change for %s, which is not "
3223 "in current HEAD", name);
3226 die("sha1 information is lacking or useless "
3231 ce = make_cache_entry(patch->old_mode, sha1_ptr, name, 0, 0);
3233 die(_("make_cache_entry failed for path '%s'"), name);
3234 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))
3235 die ("Could not add %s to temporary index", name);
3238 fd = open(filename, O_WRONLY | O_CREAT, 0666);
3239 if (fd < 0 || write_index(&result, fd) || close(fd))
3240 die ("Could not write temporary index to %s", filename);
3242 discard_index(&result);
3245 static void stat_patch_list(struct patch *patch)
3247 int files, adds, dels;
3249 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
3251 adds += patch->lines_added;
3252 dels += patch->lines_deleted;
3256 print_stat_summary(stdout, files, adds, dels);
3259 static void numstat_patch_list(struct patch *patch)
3261 for ( ; patch; patch = patch->next) {
3263 name = patch->new_name ? patch->new_name : patch->old_name;
3264 if (patch->is_binary)
3267 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
3268 write_name_quoted(name, stdout, line_termination);
3272 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
3275 printf(" %s mode %06o %s\n", newdelete, mode, name);
3277 printf(" %s %s\n", newdelete, name);
3280 static void show_mode_change(struct patch *p, int show_name)
3282 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
3284 printf(" mode change %06o => %06o %s\n",
3285 p->old_mode, p->new_mode, p->new_name);
3287 printf(" mode change %06o => %06o\n",
3288 p->old_mode, p->new_mode);
3292 static void show_rename_copy(struct patch *p)
3294 const char *renamecopy = p->is_rename ? "rename" : "copy";
3295 const char *old, *new;
3297 /* Find common prefix */
3301 const char *slash_old, *slash_new;
3302 slash_old = strchr(old, '/');
3303 slash_new = strchr(new, '/');
3306 slash_old - old != slash_new - new ||
3307 memcmp(old, new, slash_new - new))
3309 old = slash_old + 1;
3310 new = slash_new + 1;
3312 /* p->old_name thru old is the common prefix, and old and new
3313 * through the end of names are renames
3315 if (old != p->old_name)
3316 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
3317 (int)(old - p->old_name), p->old_name,
3318 old, new, p->score);
3320 printf(" %s %s => %s (%d%%)\n", renamecopy,
3321 p->old_name, p->new_name, p->score);
3322 show_mode_change(p, 0);
3325 static void summary_patch_list(struct patch *patch)
3329 for (p = patch; p; p = p->next) {
3331 show_file_mode_name("create", p->new_mode, p->new_name);
3332 else if (p->is_delete)
3333 show_file_mode_name("delete", p->old_mode, p->old_name);
3335 if (p->is_rename || p->is_copy)
3336 show_rename_copy(p);
3339 printf(" rewrite %s (%d%%)\n",
3340 p->new_name, p->score);
3341 show_mode_change(p, 0);
3344 show_mode_change(p, 1);
3350 static void patch_stats(struct patch *patch)
3352 int lines = patch->lines_added + patch->lines_deleted;
3354 if (lines > max_change)
3356 if (patch->old_name) {
3357 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
3359 len = strlen(patch->old_name);
3363 if (patch->new_name) {
3364 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
3366 len = strlen(patch->new_name);
3372 static void remove_file(struct patch *patch, int rmdir_empty)
3375 if (remove_file_from_cache(patch->old_name) < 0)
3376 die(_("unable to remove %s from index"), patch->old_name);
3379 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
3380 remove_path(patch->old_name);
3385 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
3388 struct cache_entry *ce;
3389 int namelen = strlen(path);
3390 unsigned ce_size = cache_entry_size(namelen);
3395 ce = xcalloc(1, ce_size);
3396 memcpy(ce->name, path, namelen);
3397 ce->ce_mode = create_ce_mode(mode);
3398 ce->ce_flags = namelen;
3399 if (S_ISGITLINK(mode)) {
3400 const char *s = buf;
3402 if (get_sha1_hex(s + strlen("Subproject commit "), ce->sha1))
3403 die(_("corrupt patch for subproject %s"), path);
3406 if (lstat(path, &st) < 0)
3407 die_errno(_("unable to stat newly created file '%s'"),
3409 fill_stat_cache_info(ce, &st);
3411 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
3412 die(_("unable to create backing store for newly created file %s"), path);
3414 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
3415 die(_("unable to add cache entry for %s"), path);
3418 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
3421 struct strbuf nbuf = STRBUF_INIT;
3423 if (S_ISGITLINK(mode)) {
3425 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
3427 return mkdir(path, 0777);
3430 if (has_symlinks && S_ISLNK(mode))
3431 /* Although buf:size is counted string, it also is NUL
3434 return symlink(buf, path);
3436 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
3440 if (convert_to_working_tree(path, buf, size, &nbuf)) {
3444 write_or_die(fd, buf, size);
3445 strbuf_release(&nbuf);
3448 die_errno(_("closing file '%s'"), path);
3453 * We optimistically assume that the directories exist,
3454 * which is true 99% of the time anyway. If they don't,
3455 * we create them and try again.
3457 static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
3461 if (!try_create_file(path, mode, buf, size))
3464 if (errno == ENOENT) {
3465 if (safe_create_leading_directories(path))
3467 if (!try_create_file(path, mode, buf, size))
3471 if (errno == EEXIST || errno == EACCES) {
3472 /* We may be trying to create a file where a directory
3476 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
3480 if (errno == EEXIST) {
3481 unsigned int nr = getpid();
3484 char newpath[PATH_MAX];
3485 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
3486 if (!try_create_file(newpath, mode, buf, size)) {
3487 if (!rename(newpath, path))
3489 unlink_or_warn(newpath);
3492 if (errno != EEXIST)
3497 die_errno(_("unable to write file '%s' mode %o"), path, mode);
3500 static void create_file(struct patch *patch)
3502 char *path = patch->new_name;
3503 unsigned mode = patch->new_mode;
3504 unsigned long size = patch->resultsize;
3505 char *buf = patch->result;
3508 mode = S_IFREG | 0644;
3509 create_one_file(path, mode, buf, size);
3510 add_index_file(path, mode, buf, size);
3513 /* phase zero is to remove, phase one is to create */
3514 static void write_out_one_result(struct patch *patch, int phase)
3516 if (patch->is_delete > 0) {
3518 remove_file(patch, 1);
3521 if (patch->is_new > 0 || patch->is_copy) {
3527 * Rename or modification boils down to the same
3528 * thing: remove the old, write the new
3531 remove_file(patch, patch->is_rename);
3536 static int write_out_one_reject(struct patch *patch)
3539 char namebuf[PATH_MAX];
3540 struct fragment *frag;
3542 struct strbuf sb = STRBUF_INIT;
3544 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
3545 if (!frag->rejected)
3551 if (apply_verbosely)
3552 say_patch_name(stderr,
3553 _("Applied patch %s cleanly."), patch);
3557 /* This should not happen, because a removal patch that leaves
3558 * contents are marked "rejected" at the patch level.
3560 if (!patch->new_name)
3561 die(_("internal error"));
3563 /* Say this even without --verbose */
3564 strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",
3565 "Applying patch %%s with %d rejects...",
3568 say_patch_name(stderr, sb.buf, patch);
3569 strbuf_release(&sb);
3571 cnt = strlen(patch->new_name);
3572 if (ARRAY_SIZE(namebuf) <= cnt + 5) {
3573 cnt = ARRAY_SIZE(namebuf) - 5;
3574 warning(_("truncating .rej filename to %.*s.rej"),
3575 cnt - 1, patch->new_name);
3577 memcpy(namebuf, patch->new_name, cnt);
3578 memcpy(namebuf + cnt, ".rej", 5);
3580 rej = fopen(namebuf, "w");
3582 return error(_("cannot open %s: %s"), namebuf, strerror(errno));
3584 /* Normal git tools never deal with .rej, so do not pretend
3585 * this is a git patch by saying --git nor give extended
3586 * headers. While at it, maybe please "kompare" that wants
3587 * the trailing TAB and some garbage at the end of line ;-).
3589 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
3590 patch->new_name, patch->new_name);
3591 for (cnt = 1, frag = patch->fragments;
3593 cnt++, frag = frag->next) {
3594 if (!frag->rejected) {
3595 fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);
3598 fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);
3599 fprintf(rej, "%.*s", frag->size, frag->patch);
3600 if (frag->patch[frag->size-1] != '\n')
3607 static int write_out_results(struct patch *list)
3613 for (phase = 0; phase < 2; phase++) {
3619 write_out_one_result(l, phase);
3620 if (phase == 1 && write_out_one_reject(l))
3629 static struct lock_file lock_file;
3631 static struct string_list limit_by_name;
3632 static int has_include;
3633 static void add_name_limit(const char *name, int exclude)
3635 struct string_list_item *it;
3637 it = string_list_append(&limit_by_name, name);
3638 it->util = exclude ? NULL : (void *) 1;
3641 static int use_patch(struct patch *p)
3643 const char *pathname = p->new_name ? p->new_name : p->old_name;
3646 /* Paths outside are not touched regardless of "--include" */
3647 if (0 < prefix_length) {
3648 int pathlen = strlen(pathname);
3649 if (pathlen <= prefix_length ||
3650 memcmp(prefix, pathname, prefix_length))
3654 /* See if it matches any of exclude/include rule */
3655 for (i = 0; i < limit_by_name.nr; i++) {
3656 struct string_list_item *it = &limit_by_name.items[i];
3657 if (!fnmatch(it->string, pathname, 0))
3658 return (it->util != NULL);
3662 * If we had any include, a path that does not match any rule is
3663 * not used. Otherwise, we saw bunch of exclude rules (or none)
3664 * and such a path is used.
3666 return !has_include;
3670 static void prefix_one(char **name)
3672 char *old_name = *name;
3675 *name = xstrdup(prefix_filename(prefix, prefix_length, *name));
3679 static void prefix_patches(struct patch *p)
3681 if (!prefix || p->is_toplevel_relative)
3683 for ( ; p; p = p->next) {
3684 if (p->new_name == p->old_name) {
3685 char *prefixed = p->new_name;
3686 prefix_one(&prefixed);
3687 p->new_name = p->old_name = prefixed;
3690 prefix_one(&p->new_name);
3691 prefix_one(&p->old_name);
3696 #define INACCURATE_EOF (1<<0)
3697 #define RECOUNT (1<<1)
3699 static int apply_patch(int fd, const char *filename, int options)
3702 struct strbuf buf = STRBUF_INIT;
3703 struct patch *list = NULL, **listp = &list;
3704 int skipped_patch = 0;
3706 /* FIXME - memory leak when using multiple patch files as inputs */
3707 memset(&fn_table, 0, sizeof(struct string_list));
3708 patch_input_file = filename;
3709 read_patch_file(&buf, fd);
3711 while (offset < buf.len) {
3712 struct patch *patch;
3715 patch = xcalloc(1, sizeof(*patch));
3716 patch->inaccurate_eof = !!(options & INACCURATE_EOF);
3717 patch->recount = !!(options & RECOUNT);
3718 nr = parse_chunk(buf.buf + offset, buf.len - offset, patch);
3721 if (apply_in_reverse)
3722 reverse_patches(patch);
3724 prefix_patches(patch);
3725 if (use_patch(patch)) {
3728 listp = &patch->next;
3731 /* perhaps free it a bit better? */
3738 if (!list && !skipped_patch)
3739 die(_("unrecognized input"));
3741 if (whitespace_error && (ws_error_action == die_on_ws_error))
3744 update_index = check_index && apply;
3745 if (update_index && newfd < 0)
3746 newfd = hold_locked_index(&lock_file, 1);
3749 if (read_cache() < 0)
3750 die(_("unable to read index file"));
3753 if ((check || apply) &&
3754 check_patch_list(list) < 0 &&
3758 if (apply && write_out_results(list))
3762 build_fake_ancestor(list, fake_ancestor);
3765 stat_patch_list(list);
3768 numstat_patch_list(list);
3771 summary_patch_list(list);
3773 strbuf_release(&buf);
3777 static int git_apply_config(const char *var, const char *value, void *cb)
3779 if (!strcmp(var, "apply.whitespace"))
3780 return git_config_string(&apply_default_whitespace, var, value);
3781 else if (!strcmp(var, "apply.ignorewhitespace"))
3782 return git_config_string(&apply_default_ignorewhitespace, var, value);
3783 return git_default_config(var, value, cb);
3786 static int option_parse_exclude(const struct option *opt,
3787 const char *arg, int unset)
3789 add_name_limit(arg, 1);
3793 static int option_parse_include(const struct option *opt,
3794 const char *arg, int unset)
3796 add_name_limit(arg, 0);
3801 static int option_parse_p(const struct option *opt,
3802 const char *arg, int unset)
3804 p_value = atoi(arg);
3809 static int option_parse_z(const struct option *opt,
3810 const char *arg, int unset)
3813 line_termination = '\n';
3815 line_termination = 0;
3819 static int option_parse_space_change(const struct option *opt,
3820 const char *arg, int unset)
3823 ws_ignore_action = ignore_ws_none;
3825 ws_ignore_action = ignore_ws_change;
3829 static int option_parse_whitespace(const struct option *opt,
3830 const char *arg, int unset)
3832 const char **whitespace_option = opt->value;
3834 *whitespace_option = arg;
3835 parse_whitespace_option(arg);
3839 static int option_parse_directory(const struct option *opt,
3840 const char *arg, int unset)
3842 root_len = strlen(arg);
3843 if (root_len && arg[root_len - 1] != '/') {
3845 root = new_root = xmalloc(root_len + 2);
3846 strcpy(new_root, arg);
3847 strcpy(new_root + root_len++, "/");
3853 int cmd_apply(int argc, const char **argv, const char *prefix_)
3857 int is_not_gitdir = !startup_info->have_repository;
3858 int force_apply = 0;
3860 const char *whitespace_option = NULL;
3862 struct option builtin_apply_options[] = {
3863 { OPTION_CALLBACK, 0, "exclude", NULL, "path",
3864 "don't apply changes matching the given path",
3865 0, option_parse_exclude },
3866 { OPTION_CALLBACK, 0, "include", NULL, "path",
3867 "apply changes matching the given path",
3868 0, option_parse_include },
3869 { OPTION_CALLBACK, 'p', NULL, NULL, "num",
3870 "remove <num> leading slashes from traditional diff paths",
3871 0, option_parse_p },
3872 OPT_BOOLEAN(0, "no-add", &no_add,
3873 "ignore additions made by the patch"),
3874 OPT_BOOLEAN(0, "stat", &diffstat,
3875 "instead of applying the patch, output diffstat for the input"),
3876 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
3877 OPT_NOOP_NOARG(0, "binary"),
3878 OPT_BOOLEAN(0, "numstat", &numstat,
3879 "shows number of added and deleted lines in decimal notation"),
3880 OPT_BOOLEAN(0, "summary", &summary,
3881 "instead of applying the patch, output a summary for the input"),
3882 OPT_BOOLEAN(0, "check", &check,
3883 "instead of applying the patch, see if the patch is applicable"),
3884 OPT_BOOLEAN(0, "index", &check_index,
3885 "make sure the patch is applicable to the current index"),
3886 OPT_BOOLEAN(0, "cached", &cached,
3887 "apply a patch without touching the working tree"),
3888 OPT_BOOLEAN(0, "apply", &force_apply,
3889 "also apply the patch (use with --stat/--summary/--check)"),
3890 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor,
3891 "build a temporary index based on embedded index information"),
3892 { OPTION_CALLBACK, 'z', NULL, NULL, NULL,
3893 "paths are separated with NUL character",
3894 PARSE_OPT_NOARG, option_parse_z },
3895 OPT_INTEGER('C', NULL, &p_context,
3896 "ensure at least <n> lines of context match"),
3897 { OPTION_CALLBACK, 0, "whitespace", &whitespace_option, "action",
3898 "detect new or modified lines that have whitespace errors",
3899 0, option_parse_whitespace },
3900 { OPTION_CALLBACK, 0, "ignore-space-change", NULL, NULL,
3901 "ignore changes in whitespace when finding context",
3902 PARSE_OPT_NOARG, option_parse_space_change },
3903 { OPTION_CALLBACK, 0, "ignore-whitespace", NULL, NULL,
3904 "ignore changes in whitespace when finding context",
3905 PARSE_OPT_NOARG, option_parse_space_change },
3906 OPT_BOOLEAN('R', "reverse", &apply_in_reverse,
3907 "apply the patch in reverse"),
3908 OPT_BOOLEAN(0, "unidiff-zero", &unidiff_zero,
3909 "don't expect at least one line of context"),
3910 OPT_BOOLEAN(0, "reject", &apply_with_reject,
3911 "leave the rejected hunks in corresponding *.rej files"),
3912 OPT_BOOLEAN(0, "allow-overlap", &allow_overlap,
3913 "allow overlapping hunks"),
3914 OPT__VERBOSE(&apply_verbosely, "be verbose"),
3915 OPT_BIT(0, "inaccurate-eof", &options,
3916 "tolerate incorrectly detected missing new-line at the end of file",
3918 OPT_BIT(0, "recount", &options,
3919 "do not trust the line counts in the hunk headers",
3921 { OPTION_CALLBACK, 0, "directory", NULL, "root",
3922 "prepend <root> to all filenames",
3923 0, option_parse_directory },
3928 prefix_length = prefix ? strlen(prefix) : 0;
3929 git_config(git_apply_config, NULL);
3930 if (apply_default_whitespace)
3931 parse_whitespace_option(apply_default_whitespace);
3932 if (apply_default_ignorewhitespace)
3933 parse_ignorewhitespace_option(apply_default_ignorewhitespace);
3935 argc = parse_options(argc, argv, prefix, builtin_apply_options,
3938 if (apply_with_reject)
3939 apply = apply_verbosely = 1;
3940 if (!force_apply && (diffstat || numstat || summary || check || fake_ancestor))
3942 if (check_index && is_not_gitdir)
3943 die(_("--index outside a repository"));
3946 die(_("--cached outside a repository"));
3949 for (i = 0; i < argc; i++) {
3950 const char *arg = argv[i];
3953 if (!strcmp(arg, "-")) {
3954 errs |= apply_patch(0, "<stdin>", options);
3957 } else if (0 < prefix_length)
3958 arg = prefix_filename(prefix, prefix_length, arg);
3960 fd = open(arg, O_RDONLY);
3962 die_errno(_("can't open patch '%s'"), arg);
3964 set_default_whitespace_mode(whitespace_option);
3965 errs |= apply_patch(fd, arg, options);
3968 set_default_whitespace_mode(whitespace_option);
3970 errs |= apply_patch(0, "<stdin>", options);
3971 if (whitespace_error) {
3972 if (squelch_whitespace_errors &&
3973 squelch_whitespace_errors < whitespace_error) {
3975 whitespace_error - squelch_whitespace_errors;
3976 warning(Q_("squelched %d whitespace error",
3977 "squelched %d whitespace errors",
3981 if (ws_error_action == die_on_ws_error)
3982 die(Q_("%d line adds whitespace errors.",
3983 "%d lines add whitespace errors.",
3986 if (applied_after_fixing_ws && apply)
3987 warning("%d line%s applied after"
3988 " fixing whitespace errors.",
3989 applied_after_fixing_ws,
3990 applied_after_fixing_ws == 1 ? "" : "s");
3991 else if (whitespace_error)
3992 warning(Q_("%d line adds whitespace errors.",
3993 "%d lines add whitespace errors.",
3999 if (write_cache(newfd, active_cache, active_nr) ||
4000 commit_locked_index(&lock_file))
4001 die(_("Unable to write new index file"));