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;
156 * 'patch' is usually borrowed from buf in apply_patch(),
157 * but some codepaths store an allocated buffer.
160 unsigned free_patch:1,
164 struct fragment *next;
168 * When dealing with a binary patch, we reuse "leading" field
169 * to store the type of the binary hunk, either deflated "delta"
170 * or deflated "literal".
172 #define binary_patch_method leading
173 #define BINARY_DELTA_DEFLATED 1
174 #define BINARY_LITERAL_DEFLATED 2
177 * This represents a "patch" to a file, both metainfo changes
178 * such as creation/deletion, filemode and content changes represented
179 * as a series of fragments.
182 char *new_name, *old_name, *def_name;
183 unsigned int old_mode, new_mode;
184 int is_new, is_delete; /* -1 = unknown, 0 = false, 1 = true */
187 unsigned long deflate_origlen;
188 int lines_added, lines_deleted;
190 unsigned int is_toplevel_relative:1;
191 unsigned int inaccurate_eof:1;
192 unsigned int is_binary:1;
193 unsigned int is_copy:1;
194 unsigned int is_rename:1;
195 unsigned int recount:1;
196 struct fragment *fragments;
199 char old_sha1_prefix[41];
200 char new_sha1_prefix[41];
204 static void free_fragment_list(struct fragment *list)
207 struct fragment *next = list->next;
208 if (list->free_patch)
209 free((char *)list->patch);
215 static void free_patch(struct patch *patch)
217 free_fragment_list(patch->fragments);
218 free(patch->def_name);
219 free(patch->old_name);
220 free(patch->new_name);
225 static void free_patch_list(struct patch *list)
228 struct patch *next = list->next;
235 * A line in a file, len-bytes long (includes the terminating LF,
236 * except for an incomplete line at the end if the file ends with
237 * one), and its contents hashes to 'hash'.
243 #define LINE_COMMON 1
244 #define LINE_PATCHED 2
248 * This represents a "file", which is an array of "lines".
255 struct line *line_allocated;
260 * Records filenames that have been touched, in order to handle
261 * the case where more than one patches touch the same file.
264 static struct string_list fn_table;
266 static uint32_t hash_line(const char *cp, size_t len)
270 for (i = 0, h = 0; i < len; i++) {
271 if (!isspace(cp[i])) {
272 h = h * 3 + (cp[i] & 0xff);
279 * Compare lines s1 of length n1 and s2 of length n2, ignoring
280 * whitespace difference. Returns 1 if they match, 0 otherwise
282 static int fuzzy_matchlines(const char *s1, size_t n1,
283 const char *s2, size_t n2)
285 const char *last1 = s1 + n1 - 1;
286 const char *last2 = s2 + n2 - 1;
289 /* ignore line endings */
290 while ((*last1 == '\r') || (*last1 == '\n'))
292 while ((*last2 == '\r') || (*last2 == '\n'))
295 /* skip leading whitespace */
296 while (isspace(*s1) && (s1 <= last1))
298 while (isspace(*s2) && (s2 <= last2))
300 /* early return if both lines are empty */
301 if ((s1 > last1) && (s2 > last2))
304 result = *s1++ - *s2++;
306 * Skip whitespace inside. We check for whitespace on
307 * both buffers because we don't want "a b" to match
310 if (isspace(*s1) && isspace(*s2)) {
311 while (isspace(*s1) && s1 <= last1)
313 while (isspace(*s2) && s2 <= last2)
317 * If we reached the end on one side only,
321 ((s2 > last2) && (s1 <= last1)) ||
322 ((s1 > last1) && (s2 <= last2)))
324 if ((s1 > last1) && (s2 > last2))
331 static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
333 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
334 img->line_allocated[img->nr].len = len;
335 img->line_allocated[img->nr].hash = hash_line(bol, len);
336 img->line_allocated[img->nr].flag = flag;
341 * "buf" has the file contents to be patched (read from various sources).
342 * attach it to "image" and add line-based index to it.
343 * "image" now owns the "buf".
345 static void prepare_image(struct image *image, char *buf, size_t len,
346 int prepare_linetable)
350 memset(image, 0, sizeof(*image));
354 if (!prepare_linetable)
357 ep = image->buf + image->len;
361 for (next = cp; next < ep && *next != '\n'; next++)
365 add_line_info(image, cp, next - cp, 0);
368 image->line = image->line_allocated;
371 static void clear_image(struct image *image)
378 static void say_patch_name(FILE *output, const char *pre,
379 struct patch *patch, const char *post)
382 if (patch->old_name && patch->new_name &&
383 strcmp(patch->old_name, patch->new_name)) {
384 quote_c_style(patch->old_name, NULL, output, 0);
385 fputs(" => ", output);
386 quote_c_style(patch->new_name, NULL, output, 0);
388 const char *n = patch->new_name;
391 quote_c_style(n, NULL, output, 0);
398 static void read_patch_file(struct strbuf *sb, int fd)
400 if (strbuf_read(sb, fd, 0) < 0)
401 die_errno("git apply: failed to read");
404 * Make sure that we have some slop in the buffer
405 * so that we can do speculative "memcmp" etc, and
406 * see to it that it is NUL-filled.
408 strbuf_grow(sb, SLOP);
409 memset(sb->buf + sb->len, 0, SLOP);
412 static unsigned long linelen(const char *buffer, unsigned long size)
414 unsigned long len = 0;
417 if (*buffer++ == '\n')
423 static int is_dev_null(const char *str)
425 return !memcmp("/dev/null", str, 9) && isspace(str[9]);
431 static int name_terminate(const char *name, int namelen, int c, int terminate)
433 if (c == ' ' && !(terminate & TERM_SPACE))
435 if (c == '\t' && !(terminate & TERM_TAB))
441 /* remove double slashes to make --index work with such filenames */
442 static char *squash_slash(char *name)
450 if ((name[j++] = name[i++]) == '/')
451 while (name[i] == '/')
458 static char *find_name_gnu(const char *line, const char *def, int p_value)
460 struct strbuf name = STRBUF_INIT;
464 * Proposed "new-style" GNU patch/diff format; see
465 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
467 if (unquote_c_style(&name, line, NULL)) {
468 strbuf_release(&name);
472 for (cp = name.buf; p_value; p_value--) {
473 cp = strchr(cp, '/');
475 strbuf_release(&name);
481 strbuf_remove(&name, 0, cp - name.buf);
483 strbuf_insert(&name, 0, root, root_len);
484 return squash_slash(strbuf_detach(&name, NULL));
487 static size_t sane_tz_len(const char *line, size_t len)
491 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
493 tz = line + len - strlen(" +0500");
495 if (tz[1] != '+' && tz[1] != '-')
498 for (p = tz + 2; p != line + len; p++)
502 return line + len - tz;
505 static size_t tz_with_colon_len(const char *line, size_t len)
509 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
511 tz = line + len - strlen(" +08:00");
513 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
516 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
517 !isdigit(*p++) || !isdigit(*p++))
520 return line + len - tz;
523 static size_t date_len(const char *line, size_t len)
525 const char *date, *p;
527 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
529 p = date = line + len - strlen("72-02-05");
531 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
532 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
533 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */
536 if (date - line >= strlen("19") &&
537 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */
538 date -= strlen("19");
540 return line + len - date;
543 static size_t short_time_len(const char *line, size_t len)
545 const char *time, *p;
547 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
549 p = time = line + len - strlen(" 07:01:32");
551 /* Permit 1-digit hours? */
553 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
554 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
555 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */
558 return line + len - time;
561 static size_t fractional_time_len(const char *line, size_t len)
566 /* Expected format: 19:41:17.620000023 */
567 if (!len || !isdigit(line[len - 1]))
571 /* Fractional seconds. */
572 while (p > line && isdigit(*p))
577 /* Hours, minutes, and whole seconds. */
578 n = short_time_len(line, p - line);
582 return line + len - p + n;
585 static size_t trailing_spaces_len(const char *line, size_t len)
589 /* Expected format: ' ' x (1 or more) */
590 if (!len || line[len - 1] != ' ')
597 return line + len - (p + 1);
604 static size_t diff_timestamp_len(const char *line, size_t len)
606 const char *end = line + len;
610 * Posix: 2010-07-05 19:41:17
611 * GNU: 2010-07-05 19:41:17.620000023 -0500
614 if (!isdigit(end[-1]))
617 n = sane_tz_len(line, end - line);
619 n = tz_with_colon_len(line, end - line);
622 n = short_time_len(line, end - line);
624 n = fractional_time_len(line, end - line);
627 n = date_len(line, end - line);
628 if (!n) /* No date. Too bad. */
632 if (end == line) /* No space before date. */
634 if (end[-1] == '\t') { /* Success! */
636 return line + len - end;
638 if (end[-1] != ' ') /* No space before date. */
641 /* Whitespace damage. */
642 end -= trailing_spaces_len(line, end - line);
643 return line + len - end;
646 static char *null_strdup(const char *s)
648 return s ? xstrdup(s) : NULL;
651 static char *find_name_common(const char *line, const char *def,
652 int p_value, const char *end, int terminate)
655 const char *start = NULL;
659 while (line != end) {
662 if (!end && isspace(c)) {
665 if (name_terminate(start, line-start, c, terminate))
669 if (c == '/' && !--p_value)
673 return squash_slash(null_strdup(def));
676 return squash_slash(null_strdup(def));
679 * Generally we prefer the shorter name, especially
680 * if the other one is just a variation of that with
681 * something else tacked on to the end (ie "file.orig"
685 int deflen = strlen(def);
686 if (deflen < len && !strncmp(start, def, deflen))
687 return squash_slash(xstrdup(def));
691 char *ret = xmalloc(root_len + len + 1);
693 memcpy(ret + root_len, start, len);
694 ret[root_len + len] = '\0';
695 return squash_slash(ret);
698 return squash_slash(xmemdupz(start, len));
701 static char *find_name(const char *line, char *def, int p_value, int terminate)
704 char *name = find_name_gnu(line, def, p_value);
709 return find_name_common(line, def, p_value, NULL, terminate);
712 static char *find_name_traditional(const char *line, char *def, int p_value)
714 size_t len = strlen(line);
718 char *name = find_name_gnu(line, def, p_value);
723 len = strchrnul(line, '\n') - line;
724 date_len = diff_timestamp_len(line, len);
726 return find_name_common(line, def, p_value, NULL, TERM_TAB);
729 return find_name_common(line, def, p_value, line + len, 0);
732 static int count_slashes(const char *cp)
744 * Given the string after "--- " or "+++ ", guess the appropriate
745 * p_value for the given patch.
747 static int guess_p_value(const char *nameline)
752 if (is_dev_null(nameline))
754 name = find_name_traditional(nameline, NULL, 0);
757 cp = strchr(name, '/');
762 * Does it begin with "a/$our-prefix" and such? Then this is
763 * very likely to apply to our directory.
765 if (!strncmp(name, prefix, prefix_length))
766 val = count_slashes(prefix);
769 if (!strncmp(cp, prefix, prefix_length))
770 val = count_slashes(prefix) + 1;
778 * Does the ---/+++ line has the POSIX timestamp after the last HT?
779 * GNU diff puts epoch there to signal a creation/deletion event. Is
780 * this such a timestamp?
782 static int has_epoch_timestamp(const char *nameline)
785 * We are only interested in epoch timestamp; any non-zero
786 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
787 * For the same reason, the date must be either 1969-12-31 or
788 * 1970-01-01, and the seconds part must be "00".
790 const char stamp_regexp[] =
791 "^(1969-12-31|1970-01-01)"
793 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
795 "([-+][0-2][0-9]:?[0-5][0-9])\n";
796 const char *timestamp = NULL, *cp, *colon;
797 static regex_t *stamp;
803 for (cp = nameline; *cp != '\n'; cp++) {
810 stamp = xmalloc(sizeof(*stamp));
811 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
812 warning("Cannot prepare timestamp regexp %s",
818 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
820 if (status != REG_NOMATCH)
821 warning("regexec returned %d for input: %s",
826 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
828 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
830 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
831 if (timestamp[m[3].rm_so] == '-')
832 zoneoffset = -zoneoffset;
835 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
836 * (west of GMT) or 1970-01-01 (east of GMT)
838 if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) ||
839 (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10)))
842 hourminute = (strtol(timestamp + 11, NULL, 10) * 60 +
843 strtol(timestamp + 14, NULL, 10) -
846 return ((zoneoffset < 0 && hourminute == 1440) ||
847 (0 <= zoneoffset && !hourminute));
851 * Get the name etc info from the ---/+++ lines of a traditional patch header
853 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
854 * files, we can happily check the index for a match, but for creating a
855 * new file we should try to match whatever "patch" does. I have no idea.
857 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
861 first += 4; /* skip "--- " */
862 second += 4; /* skip "+++ " */
863 if (!p_value_known) {
865 p = guess_p_value(first);
866 q = guess_p_value(second);
868 if (0 <= p && p == q) {
873 if (is_dev_null(first)) {
875 patch->is_delete = 0;
876 name = find_name_traditional(second, NULL, p_value);
877 patch->new_name = name;
878 } else if (is_dev_null(second)) {
880 patch->is_delete = 1;
881 name = find_name_traditional(first, NULL, p_value);
882 patch->old_name = name;
885 first_name = find_name_traditional(first, NULL, p_value);
886 name = find_name_traditional(second, first_name, p_value);
888 if (has_epoch_timestamp(first)) {
890 patch->is_delete = 0;
891 patch->new_name = name;
892 } else if (has_epoch_timestamp(second)) {
894 patch->is_delete = 1;
895 patch->old_name = name;
897 patch->old_name = name;
898 patch->new_name = xstrdup(name);
902 die("unable to find filename in patch at line %d", linenr);
905 static int gitdiff_hdrend(const char *line, struct patch *patch)
911 * We're anal about diff header consistency, to make
912 * sure that we don't end up having strange ambiguous
913 * patches floating around.
915 * As a result, gitdiff_{old|new}name() will check
916 * their names against any previous information, just
919 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
921 if (!orig_name && !isnull)
922 return find_name(line, NULL, p_value, TERM_TAB);
931 die("git apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
932 another = find_name(line, NULL, p_value, TERM_TAB);
933 if (!another || memcmp(another, name, len + 1))
934 die("git apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
939 /* expect "/dev/null" */
940 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
941 die("git apply: bad git-diff - expected /dev/null on line %d", linenr);
946 static int gitdiff_oldname(const char *line, struct patch *patch)
948 char *orig = patch->old_name;
949 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
950 if (orig != patch->old_name)
955 static int gitdiff_newname(const char *line, struct patch *patch)
957 char *orig = patch->new_name;
958 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
959 if (orig != patch->new_name)
964 static int gitdiff_oldmode(const char *line, struct patch *patch)
966 patch->old_mode = strtoul(line, NULL, 8);
970 static int gitdiff_newmode(const char *line, struct patch *patch)
972 patch->new_mode = strtoul(line, NULL, 8);
976 static int gitdiff_delete(const char *line, struct patch *patch)
978 patch->is_delete = 1;
979 free(patch->old_name);
980 patch->old_name = null_strdup(patch->def_name);
981 return gitdiff_oldmode(line, patch);
984 static int gitdiff_newfile(const char *line, struct patch *patch)
987 free(patch->new_name);
988 patch->new_name = null_strdup(patch->def_name);
989 return gitdiff_newmode(line, patch);
992 static int gitdiff_copysrc(const char *line, struct patch *patch)
995 free(patch->old_name);
996 patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1000 static int gitdiff_copydst(const char *line, struct patch *patch)
1003 free(patch->new_name);
1004 patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1008 static int gitdiff_renamesrc(const char *line, struct patch *patch)
1010 patch->is_rename = 1;
1011 free(patch->old_name);
1012 patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1016 static int gitdiff_renamedst(const char *line, struct patch *patch)
1018 patch->is_rename = 1;
1019 free(patch->new_name);
1020 patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1024 static int gitdiff_similarity(const char *line, struct patch *patch)
1026 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
1031 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
1033 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
1038 static int gitdiff_index(const char *line, struct patch *patch)
1041 * index line is N hexadecimal, "..", N hexadecimal,
1042 * and optional space with octal mode.
1044 const char *ptr, *eol;
1047 ptr = strchr(line, '.');
1048 if (!ptr || ptr[1] != '.' || 40 < ptr - line)
1051 memcpy(patch->old_sha1_prefix, line, len);
1052 patch->old_sha1_prefix[len] = 0;
1055 ptr = strchr(line, ' ');
1056 eol = strchr(line, '\n');
1058 if (!ptr || eol < ptr)
1064 memcpy(patch->new_sha1_prefix, line, len);
1065 patch->new_sha1_prefix[len] = 0;
1067 patch->old_mode = strtoul(ptr+1, NULL, 8);
1072 * This is normal for a diff that doesn't change anything: we'll fall through
1073 * into the next diff. Tell the parser to break out.
1075 static int gitdiff_unrecognized(const char *line, struct patch *patch)
1080 static const char *stop_at_slash(const char *line, int llen)
1082 int nslash = p_value;
1085 for (i = 0; i < llen; i++) {
1087 if (ch == '/' && --nslash <= 0)
1094 * This is to extract the same name that appears on "diff --git"
1095 * line. We do not find and return anything if it is a rename
1096 * patch, and it is OK because we will find the name elsewhere.
1097 * We need to reliably find name only when it is mode-change only,
1098 * creation or deletion of an empty file. In any of these cases,
1099 * both sides are the same name under a/ and b/ respectively.
1101 static char *git_header_name(const char *line, int llen)
1104 const char *second = NULL;
1105 size_t len, line_len;
1107 line += strlen("diff --git ");
1108 llen -= strlen("diff --git ");
1112 struct strbuf first = STRBUF_INIT;
1113 struct strbuf sp = STRBUF_INIT;
1115 if (unquote_c_style(&first, line, &second))
1116 goto free_and_fail1;
1118 /* advance to the first slash */
1119 cp = stop_at_slash(first.buf, first.len);
1120 /* we do not accept absolute paths */
1121 if (!cp || cp == first.buf)
1122 goto free_and_fail1;
1123 strbuf_remove(&first, 0, cp + 1 - first.buf);
1126 * second points at one past closing dq of name.
1127 * find the second name.
1129 while ((second < line + llen) && isspace(*second))
1132 if (line + llen <= second)
1133 goto free_and_fail1;
1134 if (*second == '"') {
1135 if (unquote_c_style(&sp, second, NULL))
1136 goto free_and_fail1;
1137 cp = stop_at_slash(sp.buf, sp.len);
1138 if (!cp || cp == sp.buf)
1139 goto free_and_fail1;
1140 /* They must match, otherwise ignore */
1141 if (strcmp(cp + 1, first.buf))
1142 goto free_and_fail1;
1143 strbuf_release(&sp);
1144 return strbuf_detach(&first, NULL);
1147 /* unquoted second */
1148 cp = stop_at_slash(second, line + llen - second);
1149 if (!cp || cp == second)
1150 goto free_and_fail1;
1152 if (line + llen - cp != first.len + 1 ||
1153 memcmp(first.buf, cp, first.len))
1154 goto free_and_fail1;
1155 return strbuf_detach(&first, NULL);
1158 strbuf_release(&first);
1159 strbuf_release(&sp);
1163 /* unquoted first name */
1164 name = stop_at_slash(line, llen);
1165 if (!name || name == line)
1170 * since the first name is unquoted, a dq if exists must be
1171 * the beginning of the second name.
1173 for (second = name; second < line + llen; second++) {
1174 if (*second == '"') {
1175 struct strbuf sp = STRBUF_INIT;
1178 if (unquote_c_style(&sp, second, NULL))
1179 goto free_and_fail2;
1181 np = stop_at_slash(sp.buf, sp.len);
1182 if (!np || np == sp.buf)
1183 goto free_and_fail2;
1186 len = sp.buf + sp.len - np;
1187 if (len < second - name &&
1188 !strncmp(np, name, len) &&
1189 isspace(name[len])) {
1191 strbuf_remove(&sp, 0, np - sp.buf);
1192 return strbuf_detach(&sp, NULL);
1196 strbuf_release(&sp);
1202 * Accept a name only if it shows up twice, exactly the same
1205 second = strchr(name, '\n');
1208 line_len = second - name;
1209 for (len = 0 ; ; len++) {
1210 switch (name[len]) {
1215 case '\t': case ' ':
1216 second = stop_at_slash(name + len, line_len - len);
1220 if (second[len] == '\n' && !strncmp(name, second, len)) {
1221 return xmemdupz(name, len);
1227 /* Verify that we recognize the lines following a git header */
1228 static int parse_git_header(const char *line, int len, unsigned int size, struct patch *patch)
1230 unsigned long offset;
1232 /* A git diff has explicit new/delete information, so we don't guess */
1234 patch->is_delete = 0;
1237 * Some things may not have the old name in the
1238 * rest of the headers anywhere (pure mode changes,
1239 * or removing or adding empty files), so we get
1240 * the default name from the header.
1242 patch->def_name = git_header_name(line, len);
1243 if (patch->def_name && root) {
1244 char *s = xmalloc(root_len + strlen(patch->def_name) + 1);
1246 strcpy(s + root_len, patch->def_name);
1247 free(patch->def_name);
1248 patch->def_name = s;
1254 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
1255 static const struct opentry {
1257 int (*fn)(const char *, struct patch *);
1259 { "@@ -", gitdiff_hdrend },
1260 { "--- ", gitdiff_oldname },
1261 { "+++ ", gitdiff_newname },
1262 { "old mode ", gitdiff_oldmode },
1263 { "new mode ", gitdiff_newmode },
1264 { "deleted file mode ", gitdiff_delete },
1265 { "new file mode ", gitdiff_newfile },
1266 { "copy from ", gitdiff_copysrc },
1267 { "copy to ", gitdiff_copydst },
1268 { "rename old ", gitdiff_renamesrc },
1269 { "rename new ", gitdiff_renamedst },
1270 { "rename from ", gitdiff_renamesrc },
1271 { "rename to ", gitdiff_renamedst },
1272 { "similarity index ", gitdiff_similarity },
1273 { "dissimilarity index ", gitdiff_dissimilarity },
1274 { "index ", gitdiff_index },
1275 { "", gitdiff_unrecognized },
1279 len = linelen(line, size);
1280 if (!len || line[len-1] != '\n')
1282 for (i = 0; i < ARRAY_SIZE(optable); i++) {
1283 const struct opentry *p = optable + i;
1284 int oplen = strlen(p->str);
1285 if (len < oplen || memcmp(p->str, line, oplen))
1287 if (p->fn(line + oplen, patch) < 0)
1296 static int parse_num(const char *line, unsigned long *p)
1300 if (!isdigit(*line))
1302 *p = strtoul(line, &ptr, 10);
1306 static int parse_range(const char *line, int len, int offset, const char *expect,
1307 unsigned long *p1, unsigned long *p2)
1311 if (offset < 0 || offset >= len)
1316 digits = parse_num(line, p1);
1326 digits = parse_num(line+1, p2);
1335 ex = strlen(expect);
1338 if (memcmp(line, expect, ex))
1344 static void recount_diff(const char *line, int size, struct fragment *fragment)
1346 int oldlines = 0, newlines = 0, ret = 0;
1349 warning("recount: ignore empty hunk");
1354 int len = linelen(line, size);
1362 case ' ': case '\n':
1374 ret = size < 3 || prefixcmp(line, "@@ ");
1377 ret = size < 5 || prefixcmp(line, "diff ");
1384 warning("recount: unexpected line: %.*s",
1385 (int)linelen(line, size), line);
1390 fragment->oldlines = oldlines;
1391 fragment->newlines = newlines;
1395 * Parse a unified diff fragment header of the
1396 * form "@@ -a,b +c,d @@"
1398 static int parse_fragment_header(const char *line, int len, struct fragment *fragment)
1402 if (!len || line[len-1] != '\n')
1405 /* Figure out the number of lines in a fragment */
1406 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1407 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1412 static int find_header(const char *line, unsigned long size, int *hdrsize, struct patch *patch)
1414 unsigned long offset, len;
1416 patch->is_toplevel_relative = 0;
1417 patch->is_rename = patch->is_copy = 0;
1418 patch->is_new = patch->is_delete = -1;
1419 patch->old_mode = patch->new_mode = 0;
1420 patch->old_name = patch->new_name = NULL;
1421 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
1422 unsigned long nextlen;
1424 len = linelen(line, size);
1428 /* Testing this early allows us to take a few shortcuts.. */
1433 * Make sure we don't find any unconnected patch fragments.
1434 * That's a sign that we didn't find a header, and that a
1435 * patch has become corrupted/broken up.
1437 if (!memcmp("@@ -", line, 4)) {
1438 struct fragment dummy;
1439 if (parse_fragment_header(line, len, &dummy) < 0)
1441 die("patch fragment without header at line %d: %.*s",
1442 linenr, (int)len-1, line);
1449 * Git patch? It might not have a real patch, just a rename
1450 * or mode change, so we handle that specially
1452 if (!memcmp("diff --git ", line, 11)) {
1453 int git_hdr_len = parse_git_header(line, len, size, patch);
1454 if (git_hdr_len <= len)
1456 if (!patch->old_name && !patch->new_name) {
1457 if (!patch->def_name)
1458 die("git diff header lacks filename information when removing "
1459 "%d leading pathname components (line %d)" , p_value, linenr);
1460 patch->old_name = xstrdup(patch->def_name);
1461 patch->new_name = xstrdup(patch->def_name);
1463 if (!patch->is_delete && !patch->new_name)
1464 die("git diff header lacks filename information "
1465 "(line %d)", linenr);
1466 patch->is_toplevel_relative = 1;
1467 *hdrsize = git_hdr_len;
1471 /* --- followed by +++ ? */
1472 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1476 * We only accept unified patches, so we want it to
1477 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1478 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1480 nextlen = linelen(line + len, size - len);
1481 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1484 /* Ok, we'll consider it a patch */
1485 parse_traditional_patch(line, line+len, patch);
1486 *hdrsize = len + nextlen;
1493 static void record_ws_error(unsigned result, const char *line, int len, int linenr)
1501 if (squelch_whitespace_errors &&
1502 squelch_whitespace_errors < whitespace_error)
1505 err = whitespace_error_string(result);
1506 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1507 patch_input_file, linenr, err, len, line);
1511 static void check_whitespace(const char *line, int len, unsigned ws_rule)
1513 unsigned result = ws_check(line + 1, len - 1, ws_rule);
1515 record_ws_error(result, line + 1, len - 2, linenr);
1519 * Parse a unified diff. Note that this really needs to parse each
1520 * fragment separately, since the only way to know the difference
1521 * between a "---" that is part of a patch, and a "---" that starts
1522 * the next patch is to look at the line counts..
1524 static int parse_fragment(const char *line, unsigned long size,
1525 struct patch *patch, struct fragment *fragment)
1528 int len = linelen(line, size), offset;
1529 unsigned long oldlines, newlines;
1530 unsigned long leading, trailing;
1532 offset = parse_fragment_header(line, len, fragment);
1535 if (offset > 0 && patch->recount)
1536 recount_diff(line + offset, size - offset, fragment);
1537 oldlines = fragment->oldlines;
1538 newlines = fragment->newlines;
1542 /* Parse the thing.. */
1546 added = deleted = 0;
1549 offset += len, size -= len, line += len, linenr++) {
1550 if (!oldlines && !newlines)
1552 len = linelen(line, size);
1553 if (!len || line[len-1] != '\n')
1558 case '\n': /* newer GNU diff, an empty context line */
1562 if (!deleted && !added)
1567 if (apply_in_reverse &&
1568 ws_error_action != nowarn_ws_error)
1569 check_whitespace(line, len, patch->ws_rule);
1575 if (!apply_in_reverse &&
1576 ws_error_action != nowarn_ws_error)
1577 check_whitespace(line, len, patch->ws_rule);
1584 * We allow "\ No newline at end of file". Depending
1585 * on locale settings when the patch was produced we
1586 * don't know what this line looks like. The only
1587 * thing we do know is that it begins with "\ ".
1588 * Checking for 12 is just for sanity check -- any
1589 * l10n of "\ No newline..." is at least that long.
1592 if (len < 12 || memcmp(line, "\\ ", 2))
1597 if (oldlines || newlines)
1599 fragment->leading = leading;
1600 fragment->trailing = trailing;
1603 * If a fragment ends with an incomplete line, we failed to include
1604 * it in the above loop because we hit oldlines == newlines == 0
1607 if (12 < size && !memcmp(line, "\\ ", 2))
1608 offset += linelen(line, size);
1610 patch->lines_added += added;
1611 patch->lines_deleted += deleted;
1613 if (0 < patch->is_new && oldlines)
1614 return error("new file depends on old contents");
1615 if (0 < patch->is_delete && newlines)
1616 return error("deleted file still has contents");
1621 * We have seen "diff --git a/... b/..." header (or a traditional patch
1622 * header). Read hunks that belong to this patch into fragments and hang
1623 * them to the given patch structure.
1625 * The (fragment->patch, fragment->size) pair points into the memory given
1626 * by the caller, not a copy, when we return.
1628 static int parse_single_patch(const char *line, unsigned long size, struct patch *patch)
1630 unsigned long offset = 0;
1631 unsigned long oldlines = 0, newlines = 0, context = 0;
1632 struct fragment **fragp = &patch->fragments;
1634 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1635 struct fragment *fragment;
1638 fragment = xcalloc(1, sizeof(*fragment));
1639 fragment->linenr = linenr;
1640 len = parse_fragment(line, size, patch, fragment);
1642 die("corrupt patch at line %d", linenr);
1643 fragment->patch = line;
1644 fragment->size = len;
1645 oldlines += fragment->oldlines;
1646 newlines += fragment->newlines;
1647 context += fragment->leading + fragment->trailing;
1650 fragp = &fragment->next;
1658 * If something was removed (i.e. we have old-lines) it cannot
1659 * be creation, and if something was added it cannot be
1660 * deletion. However, the reverse is not true; --unified=0
1661 * patches that only add are not necessarily creation even
1662 * though they do not have any old lines, and ones that only
1663 * delete are not necessarily deletion.
1665 * Unfortunately, a real creation/deletion patch do _not_ have
1666 * any context line by definition, so we cannot safely tell it
1667 * apart with --unified=0 insanity. At least if the patch has
1668 * more than one hunk it is not creation or deletion.
1670 if (patch->is_new < 0 &&
1671 (oldlines || (patch->fragments && patch->fragments->next)))
1673 if (patch->is_delete < 0 &&
1674 (newlines || (patch->fragments && patch->fragments->next)))
1675 patch->is_delete = 0;
1677 if (0 < patch->is_new && oldlines)
1678 die("new file %s depends on old contents", patch->new_name);
1679 if (0 < patch->is_delete && newlines)
1680 die("deleted file %s still has contents", patch->old_name);
1681 if (!patch->is_delete && !newlines && context)
1682 fprintf(stderr, "** warning: file %s becomes empty but "
1683 "is not deleted\n", patch->new_name);
1688 static inline int metadata_changes(struct patch *patch)
1690 return patch->is_rename > 0 ||
1691 patch->is_copy > 0 ||
1692 patch->is_new > 0 ||
1694 (patch->old_mode && patch->new_mode &&
1695 patch->old_mode != patch->new_mode);
1698 static char *inflate_it(const void *data, unsigned long size,
1699 unsigned long inflated_size)
1705 memset(&stream, 0, sizeof(stream));
1707 stream.next_in = (unsigned char *)data;
1708 stream.avail_in = size;
1709 stream.next_out = out = xmalloc(inflated_size);
1710 stream.avail_out = inflated_size;
1711 git_inflate_init(&stream);
1712 st = git_inflate(&stream, Z_FINISH);
1713 git_inflate_end(&stream);
1714 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1722 * Read a binary hunk and return a new fragment; fragment->patch
1723 * points at an allocated memory that the caller must free, so
1724 * it is marked as "->free_patch = 1".
1726 static struct fragment *parse_binary_hunk(char **buf_p,
1727 unsigned long *sz_p,
1732 * Expect a line that begins with binary patch method ("literal"
1733 * or "delta"), followed by the length of data before deflating.
1734 * a sequence of 'length-byte' followed by base-85 encoded data
1735 * should follow, terminated by a newline.
1737 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1738 * and we would limit the patch line to 66 characters,
1739 * so one line can fit up to 13 groups that would decode
1740 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1741 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1744 unsigned long size = *sz_p;
1745 char *buffer = *buf_p;
1747 unsigned long origlen;
1750 struct fragment *frag;
1752 llen = linelen(buffer, size);
1757 if (!prefixcmp(buffer, "delta ")) {
1758 patch_method = BINARY_DELTA_DEFLATED;
1759 origlen = strtoul(buffer + 6, NULL, 10);
1761 else if (!prefixcmp(buffer, "literal ")) {
1762 patch_method = BINARY_LITERAL_DEFLATED;
1763 origlen = strtoul(buffer + 8, NULL, 10);
1771 int byte_length, max_byte_length, newsize;
1772 llen = linelen(buffer, size);
1776 /* consume the blank line */
1782 * Minimum line is "A00000\n" which is 7-byte long,
1783 * and the line length must be multiple of 5 plus 2.
1785 if ((llen < 7) || (llen-2) % 5)
1787 max_byte_length = (llen - 2) / 5 * 4;
1788 byte_length = *buffer;
1789 if ('A' <= byte_length && byte_length <= 'Z')
1790 byte_length = byte_length - 'A' + 1;
1791 else if ('a' <= byte_length && byte_length <= 'z')
1792 byte_length = byte_length - 'a' + 27;
1795 /* if the input length was not multiple of 4, we would
1796 * have filler at the end but the filler should never
1799 if (max_byte_length < byte_length ||
1800 byte_length <= max_byte_length - 4)
1802 newsize = hunk_size + byte_length;
1803 data = xrealloc(data, newsize);
1804 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1806 hunk_size = newsize;
1811 frag = xcalloc(1, sizeof(*frag));
1812 frag->patch = inflate_it(data, hunk_size, origlen);
1813 frag->free_patch = 1;
1817 frag->size = origlen;
1821 frag->binary_patch_method = patch_method;
1827 error("corrupt binary patch at line %d: %.*s",
1828 linenr-1, llen-1, buffer);
1832 static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1835 * We have read "GIT binary patch\n"; what follows is a line
1836 * that says the patch method (currently, either "literal" or
1837 * "delta") and the length of data before deflating; a
1838 * sequence of 'length-byte' followed by base-85 encoded data
1841 * When a binary patch is reversible, there is another binary
1842 * hunk in the same format, starting with patch method (either
1843 * "literal" or "delta") with the length of data, and a sequence
1844 * of length-byte + base-85 encoded data, terminated with another
1845 * empty line. This data, when applied to the postimage, produces
1848 struct fragment *forward;
1849 struct fragment *reverse;
1853 forward = parse_binary_hunk(&buffer, &size, &status, &used);
1854 if (!forward && !status)
1855 /* there has to be one hunk (forward hunk) */
1856 return error("unrecognized binary patch at line %d", linenr-1);
1858 /* otherwise we already gave an error message */
1861 reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1866 * Not having reverse hunk is not an error, but having
1867 * a corrupt reverse hunk is.
1869 free((void*) forward->patch);
1873 forward->next = reverse;
1874 patch->fragments = forward;
1875 patch->is_binary = 1;
1880 * Read the patch text in "buffer" taht extends for "size" bytes; stop
1881 * reading after seeing a single patch (i.e. changes to a single file).
1882 * Create fragments (i.e. patch hunks) and hang them to the given patch.
1883 * Return the number of bytes consumed, so that the caller can call us
1884 * again for the next patch.
1886 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
1888 int hdrsize, patchsize;
1889 int offset = find_header(buffer, size, &hdrsize, patch);
1894 patch->ws_rule = whitespace_rule(patch->new_name
1898 patchsize = parse_single_patch(buffer + offset + hdrsize,
1899 size - offset - hdrsize, patch);
1902 static const char *binhdr[] = {
1907 static const char git_binary[] = "GIT binary patch\n";
1909 int hd = hdrsize + offset;
1910 unsigned long llen = linelen(buffer + hd, size - hd);
1912 if (llen == sizeof(git_binary) - 1 &&
1913 !memcmp(git_binary, buffer + hd, llen)) {
1916 used = parse_binary(buffer + hd + llen,
1917 size - hd - llen, patch);
1919 patchsize = used + llen;
1923 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
1924 for (i = 0; binhdr[i]; i++) {
1925 int len = strlen(binhdr[i]);
1926 if (len < size - hd &&
1927 !memcmp(binhdr[i], buffer + hd, len)) {
1929 patch->is_binary = 1;
1936 /* Empty patch cannot be applied if it is a text patch
1937 * without metadata change. A binary patch appears
1940 if ((apply || check) &&
1941 (!patch->is_binary && !metadata_changes(patch)))
1942 die("patch with only garbage at line %d", linenr);
1945 return offset + hdrsize + patchsize;
1948 #define swap(a,b) myswap((a),(b),sizeof(a))
1950 #define myswap(a, b, size) do { \
1951 unsigned char mytmp[size]; \
1952 memcpy(mytmp, &a, size); \
1953 memcpy(&a, &b, size); \
1954 memcpy(&b, mytmp, size); \
1957 static void reverse_patches(struct patch *p)
1959 for (; p; p = p->next) {
1960 struct fragment *frag = p->fragments;
1962 swap(p->new_name, p->old_name);
1963 swap(p->new_mode, p->old_mode);
1964 swap(p->is_new, p->is_delete);
1965 swap(p->lines_added, p->lines_deleted);
1966 swap(p->old_sha1_prefix, p->new_sha1_prefix);
1968 for (; frag; frag = frag->next) {
1969 swap(frag->newpos, frag->oldpos);
1970 swap(frag->newlines, frag->oldlines);
1975 static const char pluses[] =
1976 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1977 static const char minuses[]=
1978 "----------------------------------------------------------------------";
1980 static void show_stats(struct patch *patch)
1982 struct strbuf qname = STRBUF_INIT;
1983 char *cp = patch->new_name ? patch->new_name : patch->old_name;
1986 quote_c_style(cp, &qname, NULL, 0);
1989 * "scale" the filename
1995 if (qname.len > max) {
1996 cp = strchr(qname.buf + qname.len + 3 - max, '/');
1998 cp = qname.buf + qname.len + 3 - max;
1999 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
2002 if (patch->is_binary) {
2003 printf(" %-*s | Bin\n", max, qname.buf);
2004 strbuf_release(&qname);
2008 printf(" %-*s |", max, qname.buf);
2009 strbuf_release(&qname);
2012 * scale the add/delete
2014 max = max + max_change > 70 ? 70 - max : max_change;
2015 add = patch->lines_added;
2016 del = patch->lines_deleted;
2018 if (max_change > 0) {
2019 int total = ((add + del) * max + max_change / 2) / max_change;
2020 add = (add * max + max_change / 2) / max_change;
2023 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
2024 add, pluses, del, minuses);
2027 static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
2029 switch (st->st_mode & S_IFMT) {
2031 if (strbuf_readlink(buf, path, st->st_size) < 0)
2032 return error("unable to read symlink %s", path);
2035 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
2036 return error("unable to open or read %s", path);
2037 convert_to_git(path, buf->buf, buf->len, buf, 0);
2045 * Update the preimage, and the common lines in postimage,
2046 * from buffer buf of length len. If postlen is 0 the postimage
2047 * is updated in place, otherwise it's updated on a new buffer
2051 static void update_pre_post_images(struct image *preimage,
2052 struct image *postimage,
2054 size_t len, size_t postlen)
2057 char *new, *old, *fixed;
2058 struct image fixed_preimage;
2061 * Update the preimage with whitespace fixes. Note that we
2062 * are not losing preimage->buf -- apply_one_fragment() will
2065 prepare_image(&fixed_preimage, buf, len, 1);
2066 assert(fixed_preimage.nr == preimage->nr);
2067 for (i = 0; i < preimage->nr; i++)
2068 fixed_preimage.line[i].flag = preimage->line[i].flag;
2069 free(preimage->line_allocated);
2070 *preimage = fixed_preimage;
2073 * Adjust the common context lines in postimage. This can be
2074 * done in-place when we are just doing whitespace fixing,
2075 * which does not make the string grow, but needs a new buffer
2076 * when ignoring whitespace causes the update, since in this case
2077 * we could have e.g. tabs converted to multiple spaces.
2078 * We trust the caller to tell us if the update can be done
2079 * in place (postlen==0) or not.
2081 old = postimage->buf;
2083 new = postimage->buf = xmalloc(postlen);
2086 fixed = preimage->buf;
2087 for (i = ctx = 0; i < postimage->nr; i++) {
2088 size_t len = postimage->line[i].len;
2089 if (!(postimage->line[i].flag & LINE_COMMON)) {
2090 /* an added line -- no counterparts in preimage */
2091 memmove(new, old, len);
2097 /* a common context -- skip it in the original postimage */
2100 /* and find the corresponding one in the fixed preimage */
2101 while (ctx < preimage->nr &&
2102 !(preimage->line[ctx].flag & LINE_COMMON)) {
2103 fixed += preimage->line[ctx].len;
2106 if (preimage->nr <= ctx)
2109 /* and copy it in, while fixing the line length */
2110 len = preimage->line[ctx].len;
2111 memcpy(new, fixed, len);
2114 postimage->line[i].len = len;
2118 /* Fix the length of the whole thing */
2119 postimage->len = new - postimage->buf;
2122 static int match_fragment(struct image *img,
2123 struct image *preimage,
2124 struct image *postimage,
2128 int match_beginning, int match_end)
2131 char *fixed_buf, *buf, *orig, *target;
2132 struct strbuf fixed;
2136 if (preimage->nr + try_lno <= img->nr) {
2138 * The hunk falls within the boundaries of img.
2140 preimage_limit = preimage->nr;
2141 if (match_end && (preimage->nr + try_lno != img->nr))
2143 } else if (ws_error_action == correct_ws_error &&
2144 (ws_rule & WS_BLANK_AT_EOF)) {
2146 * This hunk extends beyond the end of img, and we are
2147 * removing blank lines at the end of the file. This
2148 * many lines from the beginning of the preimage must
2149 * match with img, and the remainder of the preimage
2152 preimage_limit = img->nr - try_lno;
2155 * The hunk extends beyond the end of the img and
2156 * we are not removing blanks at the end, so we
2157 * should reject the hunk at this position.
2162 if (match_beginning && try_lno)
2165 /* Quick hash check */
2166 for (i = 0; i < preimage_limit; i++)
2167 if ((img->line[try_lno + i].flag & LINE_PATCHED) ||
2168 (preimage->line[i].hash != img->line[try_lno + i].hash))
2171 if (preimage_limit == preimage->nr) {
2173 * Do we have an exact match? If we were told to match
2174 * at the end, size must be exactly at try+fragsize,
2175 * otherwise try+fragsize must be still within the preimage,
2176 * and either case, the old piece should match the preimage
2180 ? (try + preimage->len == img->len)
2181 : (try + preimage->len <= img->len)) &&
2182 !memcmp(img->buf + try, preimage->buf, preimage->len))
2186 * The preimage extends beyond the end of img, so
2187 * there cannot be an exact match.
2189 * There must be one non-blank context line that match
2190 * a line before the end of img.
2194 buf = preimage->buf;
2196 for (i = 0; i < preimage_limit; i++)
2197 buf_end += preimage->line[i].len;
2199 for ( ; buf < buf_end; buf++)
2207 * No exact match. If we are ignoring whitespace, run a line-by-line
2208 * fuzzy matching. We collect all the line length information because
2209 * we need it to adjust whitespace if we match.
2211 if (ws_ignore_action == ignore_ws_change) {
2214 size_t postlen = postimage->len;
2218 for (i = 0; i < preimage_limit; i++) {
2219 size_t prelen = preimage->line[i].len;
2220 size_t imglen = img->line[try_lno+i].len;
2222 if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,
2223 preimage->buf + preoff, prelen))
2225 if (preimage->line[i].flag & LINE_COMMON)
2226 postlen += imglen - prelen;
2232 * Ok, the preimage matches with whitespace fuzz.
2234 * imgoff now holds the true length of the target that
2235 * matches the preimage before the end of the file.
2237 * Count the number of characters in the preimage that fall
2238 * beyond the end of the file and make sure that all of them
2239 * are whitespace characters. (This can only happen if
2240 * we are removing blank lines at the end of the file.)
2242 buf = preimage_eof = preimage->buf + preoff;
2243 for ( ; i < preimage->nr; i++)
2244 preoff += preimage->line[i].len;
2245 preimage_end = preimage->buf + preoff;
2246 for ( ; buf < preimage_end; buf++)
2251 * Update the preimage and the common postimage context
2252 * lines to use the same whitespace as the target.
2253 * If whitespace is missing in the target (i.e.
2254 * if the preimage extends beyond the end of the file),
2255 * use the whitespace from the preimage.
2257 extra_chars = preimage_end - preimage_eof;
2258 strbuf_init(&fixed, imgoff + extra_chars);
2259 strbuf_add(&fixed, img->buf + try, imgoff);
2260 strbuf_add(&fixed, preimage_eof, extra_chars);
2261 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2262 update_pre_post_images(preimage, postimage,
2263 fixed_buf, fixed_len, postlen);
2267 if (ws_error_action != correct_ws_error)
2271 * The hunk does not apply byte-by-byte, but the hash says
2272 * it might with whitespace fuzz. We haven't been asked to
2273 * ignore whitespace, we were asked to correct whitespace
2274 * errors, so let's try matching after whitespace correction.
2276 * The preimage may extend beyond the end of the file,
2277 * but in this loop we will only handle the part of the
2278 * preimage that falls within the file.
2280 strbuf_init(&fixed, preimage->len + 1);
2281 orig = preimage->buf;
2282 target = img->buf + try;
2283 for (i = 0; i < preimage_limit; i++) {
2284 size_t oldlen = preimage->line[i].len;
2285 size_t tgtlen = img->line[try_lno + i].len;
2286 size_t fixstart = fixed.len;
2287 struct strbuf tgtfix;
2290 /* Try fixing the line in the preimage */
2291 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2293 /* Try fixing the line in the target */
2294 strbuf_init(&tgtfix, tgtlen);
2295 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2298 * If they match, either the preimage was based on
2299 * a version before our tree fixed whitespace breakage,
2300 * or we are lacking a whitespace-fix patch the tree
2301 * the preimage was based on already had (i.e. target
2302 * has whitespace breakage, the preimage doesn't).
2303 * In either case, we are fixing the whitespace breakages
2304 * so we might as well take the fix together with their
2307 match = (tgtfix.len == fixed.len - fixstart &&
2308 !memcmp(tgtfix.buf, fixed.buf + fixstart,
2309 fixed.len - fixstart));
2311 strbuf_release(&tgtfix);
2321 * Now handle the lines in the preimage that falls beyond the
2322 * end of the file (if any). They will only match if they are
2323 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2326 for ( ; i < preimage->nr; i++) {
2327 size_t fixstart = fixed.len; /* start of the fixed preimage */
2328 size_t oldlen = preimage->line[i].len;
2331 /* Try fixing the line in the preimage */
2332 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2334 for (j = fixstart; j < fixed.len; j++)
2335 if (!isspace(fixed.buf[j]))
2342 * Yes, the preimage is based on an older version that still
2343 * has whitespace breakages unfixed, and fixing them makes the
2344 * hunk match. Update the context lines in the postimage.
2346 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2347 update_pre_post_images(preimage, postimage,
2348 fixed_buf, fixed_len, 0);
2352 strbuf_release(&fixed);
2356 static int find_pos(struct image *img,
2357 struct image *preimage,
2358 struct image *postimage,
2361 int match_beginning, int match_end)
2364 unsigned long backwards, forwards, try;
2365 int backwards_lno, forwards_lno, try_lno;
2368 * If match_beginning or match_end is specified, there is no
2369 * point starting from a wrong line that will never match and
2370 * wander around and wait for a match at the specified end.
2372 if (match_beginning)
2375 line = img->nr - preimage->nr;
2378 * Because the comparison is unsigned, the following test
2379 * will also take care of a negative line number that can
2380 * result when match_end and preimage is larger than the target.
2382 if ((size_t) line > img->nr)
2386 for (i = 0; i < line; i++)
2387 try += img->line[i].len;
2390 * There's probably some smart way to do this, but I'll leave
2391 * that to the smart and beautiful people. I'm simple and stupid.
2394 backwards_lno = line;
2396 forwards_lno = line;
2399 for (i = 0; ; i++) {
2400 if (match_fragment(img, preimage, postimage,
2401 try, try_lno, ws_rule,
2402 match_beginning, match_end))
2406 if (backwards_lno == 0 && forwards_lno == img->nr)
2410 if (backwards_lno == 0) {
2415 backwards -= img->line[backwards_lno].len;
2417 try_lno = backwards_lno;
2419 if (forwards_lno == img->nr) {
2423 forwards += img->line[forwards_lno].len;
2426 try_lno = forwards_lno;
2433 static void remove_first_line(struct image *img)
2435 img->buf += img->line[0].len;
2436 img->len -= img->line[0].len;
2441 static void remove_last_line(struct image *img)
2443 img->len -= img->line[--img->nr].len;
2447 * The change from "preimage" and "postimage" has been found to
2448 * apply at applied_pos (counts in line numbers) in "img".
2449 * Update "img" to remove "preimage" and replace it with "postimage".
2451 static void update_image(struct image *img,
2453 struct image *preimage,
2454 struct image *postimage)
2457 * remove the copy of preimage at offset in img
2458 * and replace it with postimage
2461 size_t remove_count, insert_count, applied_at = 0;
2466 * If we are removing blank lines at the end of img,
2467 * the preimage may extend beyond the end.
2468 * If that is the case, we must be careful only to
2469 * remove the part of the preimage that falls within
2470 * the boundaries of img. Initialize preimage_limit
2471 * to the number of lines in the preimage that falls
2472 * within the boundaries.
2474 preimage_limit = preimage->nr;
2475 if (preimage_limit > img->nr - applied_pos)
2476 preimage_limit = img->nr - applied_pos;
2478 for (i = 0; i < applied_pos; i++)
2479 applied_at += img->line[i].len;
2482 for (i = 0; i < preimage_limit; i++)
2483 remove_count += img->line[applied_pos + i].len;
2484 insert_count = postimage->len;
2486 /* Adjust the contents */
2487 result = xmalloc(img->len + insert_count - remove_count + 1);
2488 memcpy(result, img->buf, applied_at);
2489 memcpy(result + applied_at, postimage->buf, postimage->len);
2490 memcpy(result + applied_at + postimage->len,
2491 img->buf + (applied_at + remove_count),
2492 img->len - (applied_at + remove_count));
2495 img->len += insert_count - remove_count;
2496 result[img->len] = '\0';
2498 /* Adjust the line table */
2499 nr = img->nr + postimage->nr - preimage_limit;
2500 if (preimage_limit < postimage->nr) {
2502 * NOTE: this knows that we never call remove_first_line()
2503 * on anything other than pre/post image.
2505 img->line = xrealloc(img->line, nr * sizeof(*img->line));
2506 img->line_allocated = img->line;
2508 if (preimage_limit != postimage->nr)
2509 memmove(img->line + applied_pos + postimage->nr,
2510 img->line + applied_pos + preimage_limit,
2511 (img->nr - (applied_pos + preimage_limit)) *
2512 sizeof(*img->line));
2513 memcpy(img->line + applied_pos,
2515 postimage->nr * sizeof(*img->line));
2517 for (i = 0; i < postimage->nr; i++)
2518 img->line[applied_pos + i].flag |= LINE_PATCHED;
2523 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2524 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2525 * replace the part of "img" with "postimage" text.
2527 static int apply_one_fragment(struct image *img, struct fragment *frag,
2528 int inaccurate_eof, unsigned ws_rule,
2531 int match_beginning, match_end;
2532 const char *patch = frag->patch;
2533 int size = frag->size;
2534 char *old, *oldlines;
2535 struct strbuf newlines;
2536 int new_blank_lines_at_end = 0;
2537 int found_new_blank_lines_at_end = 0;
2538 int hunk_linenr = frag->linenr;
2539 unsigned long leading, trailing;
2540 int pos, applied_pos;
2541 struct image preimage;
2542 struct image postimage;
2544 memset(&preimage, 0, sizeof(preimage));
2545 memset(&postimage, 0, sizeof(postimage));
2546 oldlines = xmalloc(size);
2547 strbuf_init(&newlines, size);
2552 int len = linelen(patch, size);
2554 int added_blank_line = 0;
2555 int is_blank_context = 0;
2562 * "plen" is how much of the line we should use for
2563 * the actual patch data. Normally we just remove the
2564 * first character on the line, but if the line is
2565 * followed by "\ No newline", then we also remove the
2566 * last one (which is the newline, of course).
2569 if (len < size && patch[len] == '\\')
2572 if (apply_in_reverse) {
2575 else if (first == '+')
2581 /* Newer GNU diff, empty context line */
2583 /* ... followed by '\No newline'; nothing */
2586 strbuf_addch(&newlines, '\n');
2587 add_line_info(&preimage, "\n", 1, LINE_COMMON);
2588 add_line_info(&postimage, "\n", 1, LINE_COMMON);
2589 is_blank_context = 1;
2592 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2593 ws_blank_line(patch + 1, plen, ws_rule))
2594 is_blank_context = 1;
2596 memcpy(old, patch + 1, plen);
2597 add_line_info(&preimage, old, plen,
2598 (first == ' ' ? LINE_COMMON : 0));
2602 /* Fall-through for ' ' */
2604 /* --no-add does not add new lines */
2605 if (first == '+' && no_add)
2608 start = newlines.len;
2610 !whitespace_error ||
2611 ws_error_action != correct_ws_error) {
2612 strbuf_add(&newlines, patch + 1, plen);
2615 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &applied_after_fixing_ws);
2617 add_line_info(&postimage, newlines.buf + start, newlines.len - start,
2618 (first == '+' ? 0 : LINE_COMMON));
2620 (ws_rule & WS_BLANK_AT_EOF) &&
2621 ws_blank_line(patch + 1, plen, ws_rule))
2622 added_blank_line = 1;
2624 case '@': case '\\':
2625 /* Ignore it, we already handled it */
2628 if (apply_verbosely)
2629 error("invalid start of line: '%c'", first);
2632 if (added_blank_line) {
2633 if (!new_blank_lines_at_end)
2634 found_new_blank_lines_at_end = hunk_linenr;
2635 new_blank_lines_at_end++;
2637 else if (is_blank_context)
2640 new_blank_lines_at_end = 0;
2645 if (inaccurate_eof &&
2646 old > oldlines && old[-1] == '\n' &&
2647 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
2649 strbuf_setlen(&newlines, newlines.len - 1);
2652 leading = frag->leading;
2653 trailing = frag->trailing;
2656 * A hunk to change lines at the beginning would begin with
2658 * but we need to be careful. -U0 that inserts before the second
2659 * line also has this pattern.
2661 * And a hunk to add to an empty file would begin with
2664 * In other words, a hunk that is (frag->oldpos <= 1) with or
2665 * without leading context must match at the beginning.
2667 match_beginning = (!frag->oldpos ||
2668 (frag->oldpos == 1 && !unidiff_zero));
2671 * A hunk without trailing lines must match at the end.
2672 * However, we simply cannot tell if a hunk must match end
2673 * from the lack of trailing lines if the patch was generated
2674 * with unidiff without any context.
2676 match_end = !unidiff_zero && !trailing;
2678 pos = frag->newpos ? (frag->newpos - 1) : 0;
2679 preimage.buf = oldlines;
2680 preimage.len = old - oldlines;
2681 postimage.buf = newlines.buf;
2682 postimage.len = newlines.len;
2683 preimage.line = preimage.line_allocated;
2684 postimage.line = postimage.line_allocated;
2688 applied_pos = find_pos(img, &preimage, &postimage, pos,
2689 ws_rule, match_beginning, match_end);
2691 if (applied_pos >= 0)
2694 /* Am I at my context limits? */
2695 if ((leading <= p_context) && (trailing <= p_context))
2697 if (match_beginning || match_end) {
2698 match_beginning = match_end = 0;
2703 * Reduce the number of context lines; reduce both
2704 * leading and trailing if they are equal otherwise
2705 * just reduce the larger context.
2707 if (leading >= trailing) {
2708 remove_first_line(&preimage);
2709 remove_first_line(&postimage);
2713 if (trailing > leading) {
2714 remove_last_line(&preimage);
2715 remove_last_line(&postimage);
2720 if (applied_pos >= 0) {
2721 if (new_blank_lines_at_end &&
2722 preimage.nr + applied_pos >= img->nr &&
2723 (ws_rule & WS_BLANK_AT_EOF) &&
2724 ws_error_action != nowarn_ws_error) {
2725 record_ws_error(WS_BLANK_AT_EOF, "+", 1,
2726 found_new_blank_lines_at_end);
2727 if (ws_error_action == correct_ws_error) {
2728 while (new_blank_lines_at_end--)
2729 remove_last_line(&postimage);
2732 * We would want to prevent write_out_results()
2733 * from taking place in apply_patch() that follows
2734 * the callchain led us here, which is:
2735 * apply_patch->check_patch_list->check_patch->
2736 * apply_data->apply_fragments->apply_one_fragment
2738 if (ws_error_action == die_on_ws_error)
2742 if (apply_verbosely && applied_pos != pos) {
2743 int offset = applied_pos - pos;
2744 if (apply_in_reverse)
2745 offset = 0 - offset;
2747 "Hunk #%d succeeded at %d (offset %d lines).\n",
2748 nth_fragment, applied_pos + 1, offset);
2752 * Warn if it was necessary to reduce the number
2755 if ((leading != frag->leading) ||
2756 (trailing != frag->trailing))
2757 fprintf(stderr, "Context reduced to (%ld/%ld)"
2758 " to apply fragment at %d\n",
2759 leading, trailing, applied_pos+1);
2760 update_image(img, applied_pos, &preimage, &postimage);
2762 if (apply_verbosely)
2763 error("while searching for:\n%.*s",
2764 (int)(old - oldlines), oldlines);
2768 strbuf_release(&newlines);
2769 free(preimage.line_allocated);
2770 free(postimage.line_allocated);
2772 return (applied_pos < 0);
2775 static int apply_binary_fragment(struct image *img, struct patch *patch)
2777 struct fragment *fragment = patch->fragments;
2782 return error("missing binary patch data for '%s'",
2787 /* Binary patch is irreversible without the optional second hunk */
2788 if (apply_in_reverse) {
2789 if (!fragment->next)
2790 return error("cannot reverse-apply a binary patch "
2791 "without the reverse hunk to '%s'",
2793 ? patch->new_name : patch->old_name);
2794 fragment = fragment->next;
2796 switch (fragment->binary_patch_method) {
2797 case BINARY_DELTA_DEFLATED:
2798 dst = patch_delta(img->buf, img->len, fragment->patch,
2799 fragment->size, &len);
2806 case BINARY_LITERAL_DEFLATED:
2808 img->len = fragment->size;
2809 img->buf = xmalloc(img->len+1);
2810 memcpy(img->buf, fragment->patch, img->len);
2811 img->buf[img->len] = '\0';
2818 * Replace "img" with the result of applying the binary patch.
2819 * The binary patch data itself in patch->fragment is still kept
2820 * but the preimage prepared by the caller in "img" is freed here
2821 * or in the helper function apply_binary_fragment() this calls.
2823 static int apply_binary(struct image *img, struct patch *patch)
2825 const char *name = patch->old_name ? patch->old_name : patch->new_name;
2826 unsigned char sha1[20];
2829 * For safety, we require patch index line to contain
2830 * full 40-byte textual SHA1 for old and new, at least for now.
2832 if (strlen(patch->old_sha1_prefix) != 40 ||
2833 strlen(patch->new_sha1_prefix) != 40 ||
2834 get_sha1_hex(patch->old_sha1_prefix, sha1) ||
2835 get_sha1_hex(patch->new_sha1_prefix, sha1))
2836 return error("cannot apply binary patch to '%s' "
2837 "without full index line", name);
2839 if (patch->old_name) {
2841 * See if the old one matches what the patch
2844 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2845 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
2846 return error("the patch applies to '%s' (%s), "
2847 "which does not match the "
2848 "current contents.",
2849 name, sha1_to_hex(sha1));
2852 /* Otherwise, the old one must be empty. */
2854 return error("the patch applies to an empty "
2855 "'%s' but it is not empty", name);
2858 get_sha1_hex(patch->new_sha1_prefix, sha1);
2859 if (is_null_sha1(sha1)) {
2861 return 0; /* deletion patch */
2864 if (has_sha1_file(sha1)) {
2865 /* We already have the postimage */
2866 enum object_type type;
2870 result = read_sha1_file(sha1, &type, &size);
2872 return error("the necessary postimage %s for "
2873 "'%s' cannot be read",
2874 patch->new_sha1_prefix, name);
2880 * We have verified buf matches the preimage;
2881 * apply the patch data to it, which is stored
2882 * in the patch->fragments->{patch,size}.
2884 if (apply_binary_fragment(img, patch))
2885 return error("binary patch does not apply to '%s'",
2888 /* verify that the result matches */
2889 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2890 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
2891 return error("binary patch to '%s' creates incorrect result (expecting %s, got %s)",
2892 name, patch->new_sha1_prefix, sha1_to_hex(sha1));
2898 static int apply_fragments(struct image *img, struct patch *patch)
2900 struct fragment *frag = patch->fragments;
2901 const char *name = patch->old_name ? patch->old_name : patch->new_name;
2902 unsigned ws_rule = patch->ws_rule;
2903 unsigned inaccurate_eof = patch->inaccurate_eof;
2906 if (patch->is_binary)
2907 return apply_binary(img, patch);
2911 if (apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {
2912 error("patch failed: %s:%ld", name, frag->oldpos);
2913 if (!apply_with_reject)
2922 static int read_file_or_gitlink(struct cache_entry *ce, struct strbuf *buf)
2927 if (S_ISGITLINK(ce->ce_mode)) {
2928 strbuf_grow(buf, 100);
2929 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(ce->sha1));
2931 enum object_type type;
2935 result = read_sha1_file(ce->sha1, &type, &sz);
2938 /* XXX read_sha1_file NUL-terminates */
2939 strbuf_attach(buf, result, sz, sz + 1);
2944 static struct patch *in_fn_table(const char *name)
2946 struct string_list_item *item;
2951 item = string_list_lookup(&fn_table, name);
2953 return (struct patch *)item->util;
2959 * item->util in the filename table records the status of the path.
2960 * Usually it points at a patch (whose result records the contents
2961 * of it after applying it), but it could be PATH_WAS_DELETED for a
2962 * path that a previously applied patch has already removed.
2964 #define PATH_TO_BE_DELETED ((struct patch *) -2)
2965 #define PATH_WAS_DELETED ((struct patch *) -1)
2967 static int to_be_deleted(struct patch *patch)
2969 return patch == PATH_TO_BE_DELETED;
2972 static int was_deleted(struct patch *patch)
2974 return patch == PATH_WAS_DELETED;
2977 static void add_to_fn_table(struct patch *patch)
2979 struct string_list_item *item;
2982 * Always add new_name unless patch is a deletion
2983 * This should cover the cases for normal diffs,
2984 * file creations and copies
2986 if (patch->new_name != NULL) {
2987 item = string_list_insert(&fn_table, patch->new_name);
2992 * store a failure on rename/deletion cases because
2993 * later chunks shouldn't patch old names
2995 if ((patch->new_name == NULL) || (patch->is_rename)) {
2996 item = string_list_insert(&fn_table, patch->old_name);
2997 item->util = PATH_WAS_DELETED;
3001 static void prepare_fn_table(struct patch *patch)
3004 * store information about incoming file deletion
3007 if ((patch->new_name == NULL) || (patch->is_rename)) {
3008 struct string_list_item *item;
3009 item = string_list_insert(&fn_table, patch->old_name);
3010 item->util = PATH_TO_BE_DELETED;
3012 patch = patch->next;
3016 static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce)
3018 struct strbuf buf = STRBUF_INIT;
3022 struct patch *tpatch;
3024 if (!(patch->is_copy || patch->is_rename) &&
3025 (tpatch = in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {
3026 if (was_deleted(tpatch)) {
3027 return error("patch %s has been renamed/deleted",
3030 /* We have a patched copy in memory; use that. */
3031 strbuf_add(&buf, tpatch->result, tpatch->resultsize);
3032 } else if (cached) {
3033 if (read_file_or_gitlink(ce, &buf))
3034 return error("read of %s failed", patch->old_name);
3035 } else if (patch->old_name) {
3036 if (S_ISGITLINK(patch->old_mode)) {
3038 read_file_or_gitlink(ce, &buf);
3041 * There is no way to apply subproject
3042 * patch without looking at the index.
3043 * NEEDSWORK: shouldn't this be flagged
3046 free_fragment_list(patch->fragments);
3047 patch->fragments = NULL;
3050 if (read_old_data(st, patch->old_name, &buf))
3051 return error("read of %s failed", patch->old_name);
3055 img = strbuf_detach(&buf, &len);
3056 prepare_image(&image, img, len, !patch->is_binary);
3058 if (apply_fragments(&image, patch) < 0)
3059 return -1; /* note with --reject this succeeds. */
3060 patch->result = image.buf;
3061 patch->resultsize = image.len;
3062 add_to_fn_table(patch);
3063 free(image.line_allocated);
3065 if (0 < patch->is_delete && patch->resultsize)
3066 return error("removal patch leaves file contents");
3071 static int check_to_create_blob(const char *new_name, int ok_if_exists)
3074 if (!lstat(new_name, &nst)) {
3075 if (S_ISDIR(nst.st_mode) || ok_if_exists)
3078 * A leading component of new_name might be a symlink
3079 * that is going to be removed with this patch, but
3080 * still pointing at somewhere that has the path.
3081 * In such a case, path "new_name" does not exist as
3082 * far as git is concerned.
3084 if (has_symlink_leading_path(new_name, strlen(new_name)))
3087 return error("%s: already exists in working directory", new_name);
3089 else if ((errno != ENOENT) && (errno != ENOTDIR))
3090 return error("%s: %s", new_name, strerror(errno));
3094 static int verify_index_match(struct cache_entry *ce, struct stat *st)
3096 if (S_ISGITLINK(ce->ce_mode)) {
3097 if (!S_ISDIR(st->st_mode))
3101 return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
3104 static int check_preimage(struct patch *patch, struct cache_entry **ce, struct stat *st)
3106 const char *old_name = patch->old_name;
3107 struct patch *tpatch = NULL;
3109 unsigned st_mode = 0;
3112 * Make sure that we do not have local modifications from the
3113 * index when we are looking at the index. Also make sure
3114 * we have the preimage file to be patched in the work tree,
3115 * unless --cached, which tells git to apply only in the index.
3120 assert(patch->is_new <= 0);
3122 if (!(patch->is_copy || patch->is_rename) &&
3123 (tpatch = in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {
3124 if (was_deleted(tpatch))
3125 return error("%s: has been deleted/renamed", old_name);
3126 st_mode = tpatch->new_mode;
3127 } else if (!cached) {
3128 stat_ret = lstat(old_name, st);
3129 if (stat_ret && errno != ENOENT)
3130 return error("%s: %s", old_name, strerror(errno));
3133 if (to_be_deleted(tpatch))
3136 if (check_index && !tpatch) {
3137 int pos = cache_name_pos(old_name, strlen(old_name));
3139 if (patch->is_new < 0)
3141 return error("%s: does not exist in index", old_name);
3143 *ce = active_cache[pos];
3145 struct checkout costate;
3147 memset(&costate, 0, sizeof(costate));
3148 costate.base_dir = "";
3149 costate.refresh_cache = 1;
3150 if (checkout_entry(*ce, &costate, NULL) ||
3151 lstat(old_name, st))
3154 if (!cached && verify_index_match(*ce, st))
3155 return error("%s: does not match index", old_name);
3157 st_mode = (*ce)->ce_mode;
3158 } else if (stat_ret < 0) {
3159 if (patch->is_new < 0)
3161 return error("%s: %s", old_name, strerror(errno));
3164 if (!cached && !tpatch)
3165 st_mode = ce_mode_from_stat(*ce, st->st_mode);
3167 if (patch->is_new < 0)
3169 if (!patch->old_mode)
3170 patch->old_mode = st_mode;
3171 if ((st_mode ^ patch->old_mode) & S_IFMT)
3172 return error("%s: wrong type", old_name);
3173 if (st_mode != patch->old_mode)
3174 warning("%s has type %o, expected %o",
3175 old_name, st_mode, patch->old_mode);
3176 if (!patch->new_mode && !patch->is_delete)
3177 patch->new_mode = st_mode;
3182 patch->is_delete = 0;
3183 free(patch->old_name);
3184 patch->old_name = NULL;
3189 * Check and apply the patch in-core; leave the result in patch->result
3190 * for the caller to write it out to the final destination.
3192 static int check_patch(struct patch *patch)
3195 const char *old_name = patch->old_name;
3196 const char *new_name = patch->new_name;
3197 const char *name = old_name ? old_name : new_name;
3198 struct cache_entry *ce = NULL;
3199 struct patch *tpatch;
3203 patch->rejected = 1; /* we will drop this after we succeed */
3205 status = check_preimage(patch, &ce, &st);
3208 old_name = patch->old_name;
3210 if ((tpatch = in_fn_table(new_name)) &&
3211 (was_deleted(tpatch) || to_be_deleted(tpatch)))
3213 * A type-change diff is always split into a patch to
3214 * delete old, immediately followed by a patch to
3215 * create new (see diff.c::run_diff()); in such a case
3216 * it is Ok that the entry to be deleted by the
3217 * previous patch is still in the working tree and in
3225 ((0 < patch->is_new) | (0 < patch->is_rename) | patch->is_copy)) {
3227 cache_name_pos(new_name, strlen(new_name)) >= 0 &&
3229 return error("%s: already exists in index", new_name);
3231 int err = check_to_create_blob(new_name, ok_if_exists);
3235 if (!patch->new_mode) {
3236 if (0 < patch->is_new)
3237 patch->new_mode = S_IFREG | 0644;
3239 patch->new_mode = patch->old_mode;
3243 if (new_name && old_name) {
3244 int same = !strcmp(old_name, new_name);
3245 if (!patch->new_mode)
3246 patch->new_mode = patch->old_mode;
3247 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
3248 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
3249 patch->new_mode, new_name, patch->old_mode,
3250 same ? "" : " of ", same ? "" : old_name);
3253 if (apply_data(patch, &st, ce) < 0)
3254 return error("%s: patch does not apply", name);
3255 patch->rejected = 0;
3259 static int check_patch_list(struct patch *patch)
3263 prepare_fn_table(patch);
3265 if (apply_verbosely)
3266 say_patch_name(stderr,
3267 "Checking patch ", patch, "...\n");
3268 err |= check_patch(patch);
3269 patch = patch->next;
3274 /* This function tries to read the sha1 from the current index */
3275 static int get_current_sha1(const char *path, unsigned char *sha1)
3279 if (read_cache() < 0)
3281 pos = cache_name_pos(path, strlen(path));
3284 hashcpy(sha1, active_cache[pos]->sha1);
3288 /* Build an index that contains the just the files needed for a 3way merge */
3289 static void build_fake_ancestor(struct patch *list, const char *filename)
3291 struct patch *patch;
3292 struct index_state result = { NULL };
3295 /* Once we start supporting the reverse patch, it may be
3296 * worth showing the new sha1 prefix, but until then...
3298 for (patch = list; patch; patch = patch->next) {
3299 const unsigned char *sha1_ptr;
3300 unsigned char sha1[20];
3301 struct cache_entry *ce;
3304 name = patch->old_name ? patch->old_name : patch->new_name;
3305 if (0 < patch->is_new)
3307 else if (get_sha1(patch->old_sha1_prefix, sha1))
3308 /* git diff has no index line for mode/type changes */
3309 if (!patch->lines_added && !patch->lines_deleted) {
3310 if (get_current_sha1(patch->old_name, sha1))
3311 die("mode change for %s, which is not "
3312 "in current HEAD", name);
3315 die("sha1 information is lacking or useless "
3320 ce = make_cache_entry(patch->old_mode, sha1_ptr, name, 0, 0);
3322 die("make_cache_entry failed for path '%s'", name);
3323 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))
3324 die ("Could not add %s to temporary index", name);
3327 fd = open(filename, O_WRONLY | O_CREAT, 0666);
3328 if (fd < 0 || write_index(&result, fd) || close(fd))
3329 die ("Could not write temporary index to %s", filename);
3331 discard_index(&result);
3334 static void stat_patch_list(struct patch *patch)
3336 int files, adds, dels;
3338 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
3340 adds += patch->lines_added;
3341 dels += patch->lines_deleted;
3345 print_stat_summary(stdout, files, adds, dels);
3348 static void numstat_patch_list(struct patch *patch)
3350 for ( ; patch; patch = patch->next) {
3352 name = patch->new_name ? patch->new_name : patch->old_name;
3353 if (patch->is_binary)
3356 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
3357 write_name_quoted(name, stdout, line_termination);
3361 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
3364 printf(" %s mode %06o %s\n", newdelete, mode, name);
3366 printf(" %s %s\n", newdelete, name);
3369 static void show_mode_change(struct patch *p, int show_name)
3371 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
3373 printf(" mode change %06o => %06o %s\n",
3374 p->old_mode, p->new_mode, p->new_name);
3376 printf(" mode change %06o => %06o\n",
3377 p->old_mode, p->new_mode);
3381 static void show_rename_copy(struct patch *p)
3383 const char *renamecopy = p->is_rename ? "rename" : "copy";
3384 const char *old, *new;
3386 /* Find common prefix */
3390 const char *slash_old, *slash_new;
3391 slash_old = strchr(old, '/');
3392 slash_new = strchr(new, '/');
3395 slash_old - old != slash_new - new ||
3396 memcmp(old, new, slash_new - new))
3398 old = slash_old + 1;
3399 new = slash_new + 1;
3401 /* p->old_name thru old is the common prefix, and old and new
3402 * through the end of names are renames
3404 if (old != p->old_name)
3405 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
3406 (int)(old - p->old_name), p->old_name,
3407 old, new, p->score);
3409 printf(" %s %s => %s (%d%%)\n", renamecopy,
3410 p->old_name, p->new_name, p->score);
3411 show_mode_change(p, 0);
3414 static void summary_patch_list(struct patch *patch)
3418 for (p = patch; p; p = p->next) {
3420 show_file_mode_name("create", p->new_mode, p->new_name);
3421 else if (p->is_delete)
3422 show_file_mode_name("delete", p->old_mode, p->old_name);
3424 if (p->is_rename || p->is_copy)
3425 show_rename_copy(p);
3428 printf(" rewrite %s (%d%%)\n",
3429 p->new_name, p->score);
3430 show_mode_change(p, 0);
3433 show_mode_change(p, 1);
3439 static void patch_stats(struct patch *patch)
3441 int lines = patch->lines_added + patch->lines_deleted;
3443 if (lines > max_change)
3445 if (patch->old_name) {
3446 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
3448 len = strlen(patch->old_name);
3452 if (patch->new_name) {
3453 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
3455 len = strlen(patch->new_name);
3461 static void remove_file(struct patch *patch, int rmdir_empty)
3464 if (remove_file_from_cache(patch->old_name) < 0)
3465 die("unable to remove %s from index", patch->old_name);
3468 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
3469 remove_path(patch->old_name);
3474 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
3477 struct cache_entry *ce;
3478 int namelen = strlen(path);
3479 unsigned ce_size = cache_entry_size(namelen);
3484 ce = xcalloc(1, ce_size);
3485 memcpy(ce->name, path, namelen);
3486 ce->ce_mode = create_ce_mode(mode);
3487 ce->ce_flags = namelen;
3488 if (S_ISGITLINK(mode)) {
3489 const char *s = buf;
3491 if (get_sha1_hex(s + strlen("Subproject commit "), ce->sha1))
3492 die("corrupt patch for subproject %s", path);
3495 if (lstat(path, &st) < 0)
3496 die_errno("unable to stat newly created file '%s'",
3498 fill_stat_cache_info(ce, &st);
3500 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
3501 die("unable to create backing store for newly created file %s", path);
3503 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
3504 die("unable to add cache entry for %s", path);
3507 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
3510 struct strbuf nbuf = STRBUF_INIT;
3512 if (S_ISGITLINK(mode)) {
3514 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
3516 return mkdir(path, 0777);
3519 if (has_symlinks && S_ISLNK(mode))
3520 /* Although buf:size is counted string, it also is NUL
3523 return symlink(buf, path);
3525 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
3529 if (convert_to_working_tree(path, buf, size, &nbuf)) {
3533 write_or_die(fd, buf, size);
3534 strbuf_release(&nbuf);
3537 die_errno("closing file '%s'", path);
3542 * We optimistically assume that the directories exist,
3543 * which is true 99% of the time anyway. If they don't,
3544 * we create them and try again.
3546 static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
3550 if (!try_create_file(path, mode, buf, size))
3553 if (errno == ENOENT) {
3554 if (safe_create_leading_directories(path))
3556 if (!try_create_file(path, mode, buf, size))
3560 if (errno == EEXIST || errno == EACCES) {
3561 /* We may be trying to create a file where a directory
3565 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
3569 if (errno == EEXIST) {
3570 unsigned int nr = getpid();
3573 char newpath[PATH_MAX];
3574 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
3575 if (!try_create_file(newpath, mode, buf, size)) {
3576 if (!rename(newpath, path))
3578 unlink_or_warn(newpath);
3581 if (errno != EEXIST)
3586 die_errno("unable to write file '%s' mode %o", path, mode);
3589 static void create_file(struct patch *patch)
3591 char *path = patch->new_name;
3592 unsigned mode = patch->new_mode;
3593 unsigned long size = patch->resultsize;
3594 char *buf = patch->result;
3597 mode = S_IFREG | 0644;
3598 create_one_file(path, mode, buf, size);
3599 add_index_file(path, mode, buf, size);
3602 /* phase zero is to remove, phase one is to create */
3603 static void write_out_one_result(struct patch *patch, int phase)
3605 if (patch->is_delete > 0) {
3607 remove_file(patch, 1);
3610 if (patch->is_new > 0 || patch->is_copy) {
3616 * Rename or modification boils down to the same
3617 * thing: remove the old, write the new
3620 remove_file(patch, patch->is_rename);
3625 static int write_out_one_reject(struct patch *patch)
3628 char namebuf[PATH_MAX];
3629 struct fragment *frag;
3632 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
3633 if (!frag->rejected)
3639 if (apply_verbosely)
3640 say_patch_name(stderr,
3641 "Applied patch ", patch, " cleanly.\n");
3645 /* This should not happen, because a removal patch that leaves
3646 * contents are marked "rejected" at the patch level.
3648 if (!patch->new_name)
3649 die("internal error");
3651 /* Say this even without --verbose */
3652 say_patch_name(stderr, "Applying patch ", patch, " with");
3653 fprintf(stderr, " %d rejects...\n", cnt);
3655 cnt = strlen(patch->new_name);
3656 if (ARRAY_SIZE(namebuf) <= cnt + 5) {
3657 cnt = ARRAY_SIZE(namebuf) - 5;
3658 warning("truncating .rej filename to %.*s.rej",
3659 cnt - 1, patch->new_name);
3661 memcpy(namebuf, patch->new_name, cnt);
3662 memcpy(namebuf + cnt, ".rej", 5);
3664 rej = fopen(namebuf, "w");
3666 return error("cannot open %s: %s", namebuf, strerror(errno));
3668 /* Normal git tools never deal with .rej, so do not pretend
3669 * this is a git patch by saying --git nor give extended
3670 * headers. While at it, maybe please "kompare" that wants
3671 * the trailing TAB and some garbage at the end of line ;-).
3673 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
3674 patch->new_name, patch->new_name);
3675 for (cnt = 1, frag = patch->fragments;
3677 cnt++, frag = frag->next) {
3678 if (!frag->rejected) {
3679 fprintf(stderr, "Hunk #%d applied cleanly.\n", cnt);
3682 fprintf(stderr, "Rejected hunk #%d.\n", cnt);
3683 fprintf(rej, "%.*s", frag->size, frag->patch);
3684 if (frag->patch[frag->size-1] != '\n')
3691 static int write_out_results(struct patch *list)
3697 for (phase = 0; phase < 2; phase++) {
3703 write_out_one_result(l, phase);
3704 if (phase == 1 && write_out_one_reject(l))
3713 static struct lock_file lock_file;
3715 static struct string_list limit_by_name;
3716 static int has_include;
3717 static void add_name_limit(const char *name, int exclude)
3719 struct string_list_item *it;
3721 it = string_list_append(&limit_by_name, name);
3722 it->util = exclude ? NULL : (void *) 1;
3725 static int use_patch(struct patch *p)
3727 const char *pathname = p->new_name ? p->new_name : p->old_name;
3730 /* Paths outside are not touched regardless of "--include" */
3731 if (0 < prefix_length) {
3732 int pathlen = strlen(pathname);
3733 if (pathlen <= prefix_length ||
3734 memcmp(prefix, pathname, prefix_length))
3738 /* See if it matches any of exclude/include rule */
3739 for (i = 0; i < limit_by_name.nr; i++) {
3740 struct string_list_item *it = &limit_by_name.items[i];
3741 if (!fnmatch(it->string, pathname, 0))
3742 return (it->util != NULL);
3746 * If we had any include, a path that does not match any rule is
3747 * not used. Otherwise, we saw bunch of exclude rules (or none)
3748 * and such a path is used.
3750 return !has_include;
3754 static void prefix_one(char **name)
3756 char *old_name = *name;
3759 *name = xstrdup(prefix_filename(prefix, prefix_length, *name));
3763 static void prefix_patches(struct patch *p)
3765 if (!prefix || p->is_toplevel_relative)
3767 for ( ; p; p = p->next) {
3768 prefix_one(&p->new_name);
3769 prefix_one(&p->old_name);
3773 #define INACCURATE_EOF (1<<0)
3774 #define RECOUNT (1<<1)
3776 static int apply_patch(int fd, const char *filename, int options)
3779 struct strbuf buf = STRBUF_INIT; /* owns the patch text */
3780 struct patch *list = NULL, **listp = &list;
3781 int skipped_patch = 0;
3783 patch_input_file = filename;
3784 read_patch_file(&buf, fd);
3786 while (offset < buf.len) {
3787 struct patch *patch;
3790 patch = xcalloc(1, sizeof(*patch));
3791 patch->inaccurate_eof = !!(options & INACCURATE_EOF);
3792 patch->recount = !!(options & RECOUNT);
3793 nr = parse_chunk(buf.buf + offset, buf.len - offset, patch);
3796 if (apply_in_reverse)
3797 reverse_patches(patch);
3799 prefix_patches(patch);
3800 if (use_patch(patch)) {
3803 listp = &patch->next;
3812 if (!list && !skipped_patch)
3813 die("unrecognized input");
3815 if (whitespace_error && (ws_error_action == die_on_ws_error))
3818 update_index = check_index && apply;
3819 if (update_index && newfd < 0)
3820 newfd = hold_locked_index(&lock_file, 1);
3823 if (read_cache() < 0)
3824 die("unable to read index file");
3827 if ((check || apply) &&
3828 check_patch_list(list) < 0 &&
3832 if (apply && write_out_results(list))
3836 build_fake_ancestor(list, fake_ancestor);
3839 stat_patch_list(list);
3842 numstat_patch_list(list);
3845 summary_patch_list(list);
3847 free_patch_list(list);
3848 strbuf_release(&buf);
3849 string_list_clear(&fn_table, 0);
3853 static int git_apply_config(const char *var, const char *value, void *cb)
3855 if (!strcmp(var, "apply.whitespace"))
3856 return git_config_string(&apply_default_whitespace, var, value);
3857 else if (!strcmp(var, "apply.ignorewhitespace"))
3858 return git_config_string(&apply_default_ignorewhitespace, var, value);
3859 return git_default_config(var, value, cb);
3862 static int option_parse_exclude(const struct option *opt,
3863 const char *arg, int unset)
3865 add_name_limit(arg, 1);
3869 static int option_parse_include(const struct option *opt,
3870 const char *arg, int unset)
3872 add_name_limit(arg, 0);
3877 static int option_parse_p(const struct option *opt,
3878 const char *arg, int unset)
3880 p_value = atoi(arg);
3885 static int option_parse_z(const struct option *opt,
3886 const char *arg, int unset)
3889 line_termination = '\n';
3891 line_termination = 0;
3895 static int option_parse_space_change(const struct option *opt,
3896 const char *arg, int unset)
3899 ws_ignore_action = ignore_ws_none;
3901 ws_ignore_action = ignore_ws_change;
3905 static int option_parse_whitespace(const struct option *opt,
3906 const char *arg, int unset)
3908 const char **whitespace_option = opt->value;
3910 *whitespace_option = arg;
3911 parse_whitespace_option(arg);
3915 static int option_parse_directory(const struct option *opt,
3916 const char *arg, int unset)
3918 root_len = strlen(arg);
3919 if (root_len && arg[root_len - 1] != '/') {
3921 root = new_root = xmalloc(root_len + 2);
3922 strcpy(new_root, arg);
3923 strcpy(new_root + root_len++, "/");
3929 int cmd_apply(int argc, const char **argv, const char *prefix_)
3933 int is_not_gitdir = !startup_info->have_repository;
3934 int force_apply = 0;
3936 const char *whitespace_option = NULL;
3938 struct option builtin_apply_options[] = {
3939 { OPTION_CALLBACK, 0, "exclude", NULL, "path",
3940 "don't apply changes matching the given path",
3941 0, option_parse_exclude },
3942 { OPTION_CALLBACK, 0, "include", NULL, "path",
3943 "apply changes matching the given path",
3944 0, option_parse_include },
3945 { OPTION_CALLBACK, 'p', NULL, NULL, "num",
3946 "remove <num> leading slashes from traditional diff paths",
3947 0, option_parse_p },
3948 OPT_BOOLEAN(0, "no-add", &no_add,
3949 "ignore additions made by the patch"),
3950 OPT_BOOLEAN(0, "stat", &diffstat,
3951 "instead of applying the patch, output diffstat for the input"),
3952 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
3953 OPT_NOOP_NOARG(0, "binary"),
3954 OPT_BOOLEAN(0, "numstat", &numstat,
3955 "shows number of added and deleted lines in decimal notation"),
3956 OPT_BOOLEAN(0, "summary", &summary,
3957 "instead of applying the patch, output a summary for the input"),
3958 OPT_BOOLEAN(0, "check", &check,
3959 "instead of applying the patch, see if the patch is applicable"),
3960 OPT_BOOLEAN(0, "index", &check_index,
3961 "make sure the patch is applicable to the current index"),
3962 OPT_BOOLEAN(0, "cached", &cached,
3963 "apply a patch without touching the working tree"),
3964 OPT_BOOLEAN(0, "apply", &force_apply,
3965 "also apply the patch (use with --stat/--summary/--check)"),
3966 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor,
3967 "build a temporary index based on embedded index information"),
3968 { OPTION_CALLBACK, 'z', NULL, NULL, NULL,
3969 "paths are separated with NUL character",
3970 PARSE_OPT_NOARG, option_parse_z },
3971 OPT_INTEGER('C', NULL, &p_context,
3972 "ensure at least <n> lines of context match"),
3973 { OPTION_CALLBACK, 0, "whitespace", &whitespace_option, "action",
3974 "detect new or modified lines that have whitespace errors",
3975 0, option_parse_whitespace },
3976 { OPTION_CALLBACK, 0, "ignore-space-change", NULL, NULL,
3977 "ignore changes in whitespace when finding context",
3978 PARSE_OPT_NOARG, option_parse_space_change },
3979 { OPTION_CALLBACK, 0, "ignore-whitespace", NULL, NULL,
3980 "ignore changes in whitespace when finding context",
3981 PARSE_OPT_NOARG, option_parse_space_change },
3982 OPT_BOOLEAN('R', "reverse", &apply_in_reverse,
3983 "apply the patch in reverse"),
3984 OPT_BOOLEAN(0, "unidiff-zero", &unidiff_zero,
3985 "don't expect at least one line of context"),
3986 OPT_BOOLEAN(0, "reject", &apply_with_reject,
3987 "leave the rejected hunks in corresponding *.rej files"),
3988 OPT_BOOLEAN(0, "allow-overlap", &allow_overlap,
3989 "allow overlapping hunks"),
3990 OPT__VERBOSE(&apply_verbosely, "be verbose"),
3991 OPT_BIT(0, "inaccurate-eof", &options,
3992 "tolerate incorrectly detected missing new-line at the end of file",
3994 OPT_BIT(0, "recount", &options,
3995 "do not trust the line counts in the hunk headers",
3997 { OPTION_CALLBACK, 0, "directory", NULL, "root",
3998 "prepend <root> to all filenames",
3999 0, option_parse_directory },
4004 prefix_length = prefix ? strlen(prefix) : 0;
4005 git_config(git_apply_config, NULL);
4006 if (apply_default_whitespace)
4007 parse_whitespace_option(apply_default_whitespace);
4008 if (apply_default_ignorewhitespace)
4009 parse_ignorewhitespace_option(apply_default_ignorewhitespace);
4011 argc = parse_options(argc, argv, prefix, builtin_apply_options,
4014 if (apply_with_reject)
4015 apply = apply_verbosely = 1;
4016 if (!force_apply && (diffstat || numstat || summary || check || fake_ancestor))
4018 if (check_index && is_not_gitdir)
4019 die("--index outside a repository");
4022 die("--cached outside a repository");
4025 for (i = 0; i < argc; i++) {
4026 const char *arg = argv[i];
4029 if (!strcmp(arg, "-")) {
4030 errs |= apply_patch(0, "<stdin>", options);
4033 } else if (0 < prefix_length)
4034 arg = prefix_filename(prefix, prefix_length, arg);
4036 fd = open(arg, O_RDONLY);
4038 die_errno("can't open patch '%s'", arg);
4040 set_default_whitespace_mode(whitespace_option);
4041 errs |= apply_patch(fd, arg, options);
4044 set_default_whitespace_mode(whitespace_option);
4046 errs |= apply_patch(0, "<stdin>", options);
4047 if (whitespace_error) {
4048 if (squelch_whitespace_errors &&
4049 squelch_whitespace_errors < whitespace_error) {
4051 whitespace_error - squelch_whitespace_errors;
4052 warning("squelched %d "
4053 "whitespace error%s",
4055 squelched == 1 ? "" : "s");
4057 if (ws_error_action == die_on_ws_error)
4058 die("%d line%s add%s whitespace errors.",
4060 whitespace_error == 1 ? "" : "s",
4061 whitespace_error == 1 ? "s" : "");
4062 if (applied_after_fixing_ws && apply)
4063 warning("%d line%s applied after"
4064 " fixing whitespace errors.",
4065 applied_after_fixing_ws,
4066 applied_after_fixing_ws == 1 ? "" : "s");
4067 else if (whitespace_error)
4068 warning("%d line%s add%s whitespace errors.",
4070 whitespace_error == 1 ? "" : "s",
4071 whitespace_error == 1 ? "s" : "");
4075 if (write_cache(newfd, active_cache, active_nr) ||
4076 commit_locked_index(&lock_file))
4077 die("Unable to write new index file");