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 N_("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 int lines_added, lines_deleted;
189 unsigned int is_toplevel_relative:1;
190 unsigned int inaccurate_eof:1;
191 unsigned int is_binary:1;
192 unsigned int is_copy:1;
193 unsigned int is_rename:1;
194 unsigned int recount:1;
195 struct fragment *fragments;
198 char old_sha1_prefix[41];
199 char new_sha1_prefix[41];
203 static void free_fragment_list(struct fragment *list)
206 struct fragment *next = list->next;
207 if (list->free_patch)
208 free((char *)list->patch);
214 static void free_patch(struct patch *patch)
216 free_fragment_list(patch->fragments);
217 free(patch->def_name);
218 free(patch->old_name);
219 free(patch->new_name);
224 static void free_patch_list(struct patch *list)
227 struct patch *next = list->next;
234 * A line in a file, len-bytes long (includes the terminating LF,
235 * except for an incomplete line at the end if the file ends with
236 * one), and its contents hashes to 'hash'.
242 #define LINE_COMMON 1
243 #define LINE_PATCHED 2
247 * This represents a "file", which is an array of "lines".
254 struct line *line_allocated;
259 * Records filenames that have been touched, in order to handle
260 * the case where more than one patches touch the same file.
263 static struct string_list fn_table;
265 static uint32_t hash_line(const char *cp, size_t len)
269 for (i = 0, h = 0; i < len; i++) {
270 if (!isspace(cp[i])) {
271 h = h * 3 + (cp[i] & 0xff);
278 * Compare lines s1 of length n1 and s2 of length n2, ignoring
279 * whitespace difference. Returns 1 if they match, 0 otherwise
281 static int fuzzy_matchlines(const char *s1, size_t n1,
282 const char *s2, size_t n2)
284 const char *last1 = s1 + n1 - 1;
285 const char *last2 = s2 + n2 - 1;
288 /* ignore line endings */
289 while ((*last1 == '\r') || (*last1 == '\n'))
291 while ((*last2 == '\r') || (*last2 == '\n'))
294 /* skip leading whitespace */
295 while (isspace(*s1) && (s1 <= last1))
297 while (isspace(*s2) && (s2 <= last2))
299 /* early return if both lines are empty */
300 if ((s1 > last1) && (s2 > last2))
303 result = *s1++ - *s2++;
305 * Skip whitespace inside. We check for whitespace on
306 * both buffers because we don't want "a b" to match
309 if (isspace(*s1) && isspace(*s2)) {
310 while (isspace(*s1) && s1 <= last1)
312 while (isspace(*s2) && s2 <= last2)
316 * If we reached the end on one side only,
320 ((s2 > last2) && (s1 <= last1)) ||
321 ((s1 > last1) && (s2 <= last2)))
323 if ((s1 > last1) && (s2 > last2))
330 static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
332 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
333 img->line_allocated[img->nr].len = len;
334 img->line_allocated[img->nr].hash = hash_line(bol, len);
335 img->line_allocated[img->nr].flag = flag;
340 * "buf" has the file contents to be patched (read from various sources).
341 * attach it to "image" and add line-based index to it.
342 * "image" now owns the "buf".
344 static void prepare_image(struct image *image, char *buf, size_t len,
345 int prepare_linetable)
349 memset(image, 0, sizeof(*image));
353 if (!prepare_linetable)
356 ep = image->buf + image->len;
360 for (next = cp; next < ep && *next != '\n'; next++)
364 add_line_info(image, cp, next - cp, 0);
367 image->line = image->line_allocated;
370 static void clear_image(struct image *image)
377 /* fmt must contain _one_ %s and no other substitution */
378 static void say_patch_name(FILE *output, const char *fmt, struct patch *patch)
380 struct strbuf sb = STRBUF_INIT;
382 if (patch->old_name && patch->new_name &&
383 strcmp(patch->old_name, patch->new_name)) {
384 quote_c_style(patch->old_name, &sb, NULL, 0);
385 strbuf_addstr(&sb, " => ");
386 quote_c_style(patch->new_name, &sb, NULL, 0);
388 const char *n = patch->new_name;
391 quote_c_style(n, &sb, NULL, 0);
393 fprintf(output, fmt, sb.buf);
400 static void read_patch_file(struct strbuf *sb, int fd)
402 if (strbuf_read(sb, fd, 0) < 0)
403 die_errno("git apply: failed to read");
406 * Make sure that we have some slop in the buffer
407 * so that we can do speculative "memcmp" etc, and
408 * see to it that it is NUL-filled.
410 strbuf_grow(sb, SLOP);
411 memset(sb->buf + sb->len, 0, SLOP);
414 static unsigned long linelen(const char *buffer, unsigned long size)
416 unsigned long len = 0;
419 if (*buffer++ == '\n')
425 static int is_dev_null(const char *str)
427 return !memcmp("/dev/null", str, 9) && isspace(str[9]);
433 static int name_terminate(const char *name, int namelen, int c, int terminate)
435 if (c == ' ' && !(terminate & TERM_SPACE))
437 if (c == '\t' && !(terminate & TERM_TAB))
443 /* remove double slashes to make --index work with such filenames */
444 static char *squash_slash(char *name)
452 if ((name[j++] = name[i++]) == '/')
453 while (name[i] == '/')
460 static char *find_name_gnu(const char *line, const char *def, int p_value)
462 struct strbuf name = STRBUF_INIT;
466 * Proposed "new-style" GNU patch/diff format; see
467 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
469 if (unquote_c_style(&name, line, NULL)) {
470 strbuf_release(&name);
474 for (cp = name.buf; p_value; p_value--) {
475 cp = strchr(cp, '/');
477 strbuf_release(&name);
483 strbuf_remove(&name, 0, cp - name.buf);
485 strbuf_insert(&name, 0, root, root_len);
486 return squash_slash(strbuf_detach(&name, NULL));
489 static size_t sane_tz_len(const char *line, size_t len)
493 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
495 tz = line + len - strlen(" +0500");
497 if (tz[1] != '+' && tz[1] != '-')
500 for (p = tz + 2; p != line + len; p++)
504 return line + len - tz;
507 static size_t tz_with_colon_len(const char *line, size_t len)
511 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
513 tz = line + len - strlen(" +08:00");
515 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
518 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
519 !isdigit(*p++) || !isdigit(*p++))
522 return line + len - tz;
525 static size_t date_len(const char *line, size_t len)
527 const char *date, *p;
529 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
531 p = date = line + len - strlen("72-02-05");
533 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
534 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
535 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */
538 if (date - line >= strlen("19") &&
539 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */
540 date -= strlen("19");
542 return line + len - date;
545 static size_t short_time_len(const char *line, size_t len)
547 const char *time, *p;
549 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
551 p = time = line + len - strlen(" 07:01:32");
553 /* Permit 1-digit hours? */
555 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
556 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
557 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */
560 return line + len - time;
563 static size_t fractional_time_len(const char *line, size_t len)
568 /* Expected format: 19:41:17.620000023 */
569 if (!len || !isdigit(line[len - 1]))
573 /* Fractional seconds. */
574 while (p > line && isdigit(*p))
579 /* Hours, minutes, and whole seconds. */
580 n = short_time_len(line, p - line);
584 return line + len - p + n;
587 static size_t trailing_spaces_len(const char *line, size_t len)
591 /* Expected format: ' ' x (1 or more) */
592 if (!len || line[len - 1] != ' ')
599 return line + len - (p + 1);
606 static size_t diff_timestamp_len(const char *line, size_t len)
608 const char *end = line + len;
612 * Posix: 2010-07-05 19:41:17
613 * GNU: 2010-07-05 19:41:17.620000023 -0500
616 if (!isdigit(end[-1]))
619 n = sane_tz_len(line, end - line);
621 n = tz_with_colon_len(line, end - line);
624 n = short_time_len(line, end - line);
626 n = fractional_time_len(line, end - line);
629 n = date_len(line, end - line);
630 if (!n) /* No date. Too bad. */
634 if (end == line) /* No space before date. */
636 if (end[-1] == '\t') { /* Success! */
638 return line + len - end;
640 if (end[-1] != ' ') /* No space before date. */
643 /* Whitespace damage. */
644 end -= trailing_spaces_len(line, end - line);
645 return line + len - end;
648 static char *null_strdup(const char *s)
650 return s ? xstrdup(s) : NULL;
653 static char *find_name_common(const char *line, const char *def,
654 int p_value, const char *end, int terminate)
657 const char *start = NULL;
661 while (line != end) {
664 if (!end && isspace(c)) {
667 if (name_terminate(start, line-start, c, terminate))
671 if (c == '/' && !--p_value)
675 return squash_slash(null_strdup(def));
678 return squash_slash(null_strdup(def));
681 * Generally we prefer the shorter name, especially
682 * if the other one is just a variation of that with
683 * something else tacked on to the end (ie "file.orig"
687 int deflen = strlen(def);
688 if (deflen < len && !strncmp(start, def, deflen))
689 return squash_slash(xstrdup(def));
693 char *ret = xmalloc(root_len + len + 1);
695 memcpy(ret + root_len, start, len);
696 ret[root_len + len] = '\0';
697 return squash_slash(ret);
700 return squash_slash(xmemdupz(start, len));
703 static char *find_name(const char *line, char *def, int p_value, int terminate)
706 char *name = find_name_gnu(line, def, p_value);
711 return find_name_common(line, def, p_value, NULL, terminate);
714 static char *find_name_traditional(const char *line, char *def, int p_value)
716 size_t len = strlen(line);
720 char *name = find_name_gnu(line, def, p_value);
725 len = strchrnul(line, '\n') - line;
726 date_len = diff_timestamp_len(line, len);
728 return find_name_common(line, def, p_value, NULL, TERM_TAB);
731 return find_name_common(line, def, p_value, line + len, 0);
734 static int count_slashes(const char *cp)
746 * Given the string after "--- " or "+++ ", guess the appropriate
747 * p_value for the given patch.
749 static int guess_p_value(const char *nameline)
754 if (is_dev_null(nameline))
756 name = find_name_traditional(nameline, NULL, 0);
759 cp = strchr(name, '/');
764 * Does it begin with "a/$our-prefix" and such? Then this is
765 * very likely to apply to our directory.
767 if (!strncmp(name, prefix, prefix_length))
768 val = count_slashes(prefix);
771 if (!strncmp(cp, prefix, prefix_length))
772 val = count_slashes(prefix) + 1;
780 * Does the ---/+++ line has the POSIX timestamp after the last HT?
781 * GNU diff puts epoch there to signal a creation/deletion event. Is
782 * this such a timestamp?
784 static int has_epoch_timestamp(const char *nameline)
787 * We are only interested in epoch timestamp; any non-zero
788 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
789 * For the same reason, the date must be either 1969-12-31 or
790 * 1970-01-01, and the seconds part must be "00".
792 const char stamp_regexp[] =
793 "^(1969-12-31|1970-01-01)"
795 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
797 "([-+][0-2][0-9]:?[0-5][0-9])\n";
798 const char *timestamp = NULL, *cp, *colon;
799 static regex_t *stamp;
805 for (cp = nameline; *cp != '\n'; cp++) {
812 stamp = xmalloc(sizeof(*stamp));
813 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
814 warning(_("Cannot prepare timestamp regexp %s"),
820 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
822 if (status != REG_NOMATCH)
823 warning(_("regexec returned %d for input: %s"),
828 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
830 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
832 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
833 if (timestamp[m[3].rm_so] == '-')
834 zoneoffset = -zoneoffset;
837 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
838 * (west of GMT) or 1970-01-01 (east of GMT)
840 if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) ||
841 (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10)))
844 hourminute = (strtol(timestamp + 11, NULL, 10) * 60 +
845 strtol(timestamp + 14, NULL, 10) -
848 return ((zoneoffset < 0 && hourminute == 1440) ||
849 (0 <= zoneoffset && !hourminute));
853 * Get the name etc info from the ---/+++ lines of a traditional patch header
855 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
856 * files, we can happily check the index for a match, but for creating a
857 * new file we should try to match whatever "patch" does. I have no idea.
859 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
863 first += 4; /* skip "--- " */
864 second += 4; /* skip "+++ " */
865 if (!p_value_known) {
867 p = guess_p_value(first);
868 q = guess_p_value(second);
870 if (0 <= p && p == q) {
875 if (is_dev_null(first)) {
877 patch->is_delete = 0;
878 name = find_name_traditional(second, NULL, p_value);
879 patch->new_name = name;
880 } else if (is_dev_null(second)) {
882 patch->is_delete = 1;
883 name = find_name_traditional(first, NULL, p_value);
884 patch->old_name = name;
887 first_name = find_name_traditional(first, NULL, p_value);
888 name = find_name_traditional(second, first_name, p_value);
890 if (has_epoch_timestamp(first)) {
892 patch->is_delete = 0;
893 patch->new_name = name;
894 } else if (has_epoch_timestamp(second)) {
896 patch->is_delete = 1;
897 patch->old_name = name;
899 patch->old_name = name;
900 patch->new_name = xstrdup(name);
904 die(_("unable to find filename in patch at line %d"), linenr);
907 static int gitdiff_hdrend(const char *line, struct patch *patch)
913 * We're anal about diff header consistency, to make
914 * sure that we don't end up having strange ambiguous
915 * patches floating around.
917 * As a result, gitdiff_{old|new}name() will check
918 * their names against any previous information, just
921 #define DIFF_OLD_NAME 0
922 #define DIFF_NEW_NAME 1
924 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, int side)
926 if (!orig_name && !isnull)
927 return find_name(line, NULL, p_value, TERM_TAB);
936 die(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"), name, linenr);
937 another = find_name(line, NULL, p_value, TERM_TAB);
938 if (!another || memcmp(another, name, len + 1))
939 die((side == DIFF_NEW_NAME) ?
940 _("git apply: bad git-diff - inconsistent new filename on line %d") :
941 _("git apply: bad git-diff - inconsistent old filename on line %d"), linenr);
946 /* expect "/dev/null" */
947 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
948 die(_("git apply: bad git-diff - expected /dev/null on line %d"), linenr);
953 static int gitdiff_oldname(const char *line, struct patch *patch)
955 char *orig = patch->old_name;
956 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name,
958 if (orig != patch->old_name)
963 static int gitdiff_newname(const char *line, struct patch *patch)
965 char *orig = patch->new_name;
966 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name,
968 if (orig != patch->new_name)
973 static int gitdiff_oldmode(const char *line, struct patch *patch)
975 patch->old_mode = strtoul(line, NULL, 8);
979 static int gitdiff_newmode(const char *line, struct patch *patch)
981 patch->new_mode = strtoul(line, NULL, 8);
985 static int gitdiff_delete(const char *line, struct patch *patch)
987 patch->is_delete = 1;
988 free(patch->old_name);
989 patch->old_name = null_strdup(patch->def_name);
990 return gitdiff_oldmode(line, patch);
993 static int gitdiff_newfile(const char *line, struct patch *patch)
996 free(patch->new_name);
997 patch->new_name = null_strdup(patch->def_name);
998 return gitdiff_newmode(line, patch);
1001 static int gitdiff_copysrc(const char *line, struct patch *patch)
1004 free(patch->old_name);
1005 patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1009 static int gitdiff_copydst(const char *line, struct patch *patch)
1012 free(patch->new_name);
1013 patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1017 static int gitdiff_renamesrc(const char *line, struct patch *patch)
1019 patch->is_rename = 1;
1020 free(patch->old_name);
1021 patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1025 static int gitdiff_renamedst(const char *line, struct patch *patch)
1027 patch->is_rename = 1;
1028 free(patch->new_name);
1029 patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1033 static int gitdiff_similarity(const char *line, struct patch *patch)
1035 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
1040 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
1042 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
1047 static int gitdiff_index(const char *line, struct patch *patch)
1050 * index line is N hexadecimal, "..", N hexadecimal,
1051 * and optional space with octal mode.
1053 const char *ptr, *eol;
1056 ptr = strchr(line, '.');
1057 if (!ptr || ptr[1] != '.' || 40 < ptr - line)
1060 memcpy(patch->old_sha1_prefix, line, len);
1061 patch->old_sha1_prefix[len] = 0;
1064 ptr = strchr(line, ' ');
1065 eol = strchr(line, '\n');
1067 if (!ptr || eol < ptr)
1073 memcpy(patch->new_sha1_prefix, line, len);
1074 patch->new_sha1_prefix[len] = 0;
1076 patch->old_mode = strtoul(ptr+1, NULL, 8);
1081 * This is normal for a diff that doesn't change anything: we'll fall through
1082 * into the next diff. Tell the parser to break out.
1084 static int gitdiff_unrecognized(const char *line, struct patch *patch)
1089 static const char *stop_at_slash(const char *line, int llen)
1091 int nslash = p_value;
1094 for (i = 0; i < llen; i++) {
1096 if (ch == '/' && --nslash <= 0)
1103 * This is to extract the same name that appears on "diff --git"
1104 * line. We do not find and return anything if it is a rename
1105 * patch, and it is OK because we will find the name elsewhere.
1106 * We need to reliably find name only when it is mode-change only,
1107 * creation or deletion of an empty file. In any of these cases,
1108 * both sides are the same name under a/ and b/ respectively.
1110 static char *git_header_name(const char *line, int llen)
1113 const char *second = NULL;
1114 size_t len, line_len;
1116 line += strlen("diff --git ");
1117 llen -= strlen("diff --git ");
1121 struct strbuf first = STRBUF_INIT;
1122 struct strbuf sp = STRBUF_INIT;
1124 if (unquote_c_style(&first, line, &second))
1125 goto free_and_fail1;
1127 /* advance to the first slash */
1128 cp = stop_at_slash(first.buf, first.len);
1129 /* we do not accept absolute paths */
1130 if (!cp || cp == first.buf)
1131 goto free_and_fail1;
1132 strbuf_remove(&first, 0, cp + 1 - first.buf);
1135 * second points at one past closing dq of name.
1136 * find the second name.
1138 while ((second < line + llen) && isspace(*second))
1141 if (line + llen <= second)
1142 goto free_and_fail1;
1143 if (*second == '"') {
1144 if (unquote_c_style(&sp, second, NULL))
1145 goto free_and_fail1;
1146 cp = stop_at_slash(sp.buf, sp.len);
1147 if (!cp || cp == sp.buf)
1148 goto free_and_fail1;
1149 /* They must match, otherwise ignore */
1150 if (strcmp(cp + 1, first.buf))
1151 goto free_and_fail1;
1152 strbuf_release(&sp);
1153 return strbuf_detach(&first, NULL);
1156 /* unquoted second */
1157 cp = stop_at_slash(second, line + llen - second);
1158 if (!cp || cp == second)
1159 goto free_and_fail1;
1161 if (line + llen - cp != first.len + 1 ||
1162 memcmp(first.buf, cp, first.len))
1163 goto free_and_fail1;
1164 return strbuf_detach(&first, NULL);
1167 strbuf_release(&first);
1168 strbuf_release(&sp);
1172 /* unquoted first name */
1173 name = stop_at_slash(line, llen);
1174 if (!name || name == line)
1179 * since the first name is unquoted, a dq if exists must be
1180 * the beginning of the second name.
1182 for (second = name; second < line + llen; second++) {
1183 if (*second == '"') {
1184 struct strbuf sp = STRBUF_INIT;
1187 if (unquote_c_style(&sp, second, NULL))
1188 goto free_and_fail2;
1190 np = stop_at_slash(sp.buf, sp.len);
1191 if (!np || np == sp.buf)
1192 goto free_and_fail2;
1195 len = sp.buf + sp.len - np;
1196 if (len < second - name &&
1197 !strncmp(np, name, len) &&
1198 isspace(name[len])) {
1200 strbuf_remove(&sp, 0, np - sp.buf);
1201 return strbuf_detach(&sp, NULL);
1205 strbuf_release(&sp);
1211 * Accept a name only if it shows up twice, exactly the same
1214 second = strchr(name, '\n');
1217 line_len = second - name;
1218 for (len = 0 ; ; len++) {
1219 switch (name[len]) {
1224 case '\t': case ' ':
1225 second = stop_at_slash(name + len, line_len - len);
1229 if (second[len] == '\n' && !strncmp(name, second, len)) {
1230 return xmemdupz(name, len);
1236 /* Verify that we recognize the lines following a git header */
1237 static int parse_git_header(const char *line, int len, unsigned int size, struct patch *patch)
1239 unsigned long offset;
1241 /* A git diff has explicit new/delete information, so we don't guess */
1243 patch->is_delete = 0;
1246 * Some things may not have the old name in the
1247 * rest of the headers anywhere (pure mode changes,
1248 * or removing or adding empty files), so we get
1249 * the default name from the header.
1251 patch->def_name = git_header_name(line, len);
1252 if (patch->def_name && root) {
1253 char *s = xmalloc(root_len + strlen(patch->def_name) + 1);
1255 strcpy(s + root_len, patch->def_name);
1256 free(patch->def_name);
1257 patch->def_name = s;
1263 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
1264 static const struct opentry {
1266 int (*fn)(const char *, struct patch *);
1268 { "@@ -", gitdiff_hdrend },
1269 { "--- ", gitdiff_oldname },
1270 { "+++ ", gitdiff_newname },
1271 { "old mode ", gitdiff_oldmode },
1272 { "new mode ", gitdiff_newmode },
1273 { "deleted file mode ", gitdiff_delete },
1274 { "new file mode ", gitdiff_newfile },
1275 { "copy from ", gitdiff_copysrc },
1276 { "copy to ", gitdiff_copydst },
1277 { "rename old ", gitdiff_renamesrc },
1278 { "rename new ", gitdiff_renamedst },
1279 { "rename from ", gitdiff_renamesrc },
1280 { "rename to ", gitdiff_renamedst },
1281 { "similarity index ", gitdiff_similarity },
1282 { "dissimilarity index ", gitdiff_dissimilarity },
1283 { "index ", gitdiff_index },
1284 { "", gitdiff_unrecognized },
1288 len = linelen(line, size);
1289 if (!len || line[len-1] != '\n')
1291 for (i = 0; i < ARRAY_SIZE(optable); i++) {
1292 const struct opentry *p = optable + i;
1293 int oplen = strlen(p->str);
1294 if (len < oplen || memcmp(p->str, line, oplen))
1296 if (p->fn(line + oplen, patch) < 0)
1305 static int parse_num(const char *line, unsigned long *p)
1309 if (!isdigit(*line))
1311 *p = strtoul(line, &ptr, 10);
1315 static int parse_range(const char *line, int len, int offset, const char *expect,
1316 unsigned long *p1, unsigned long *p2)
1320 if (offset < 0 || offset >= len)
1325 digits = parse_num(line, p1);
1335 digits = parse_num(line+1, p2);
1344 ex = strlen(expect);
1347 if (memcmp(line, expect, ex))
1353 static void recount_diff(const char *line, int size, struct fragment *fragment)
1355 int oldlines = 0, newlines = 0, ret = 0;
1358 warning("recount: ignore empty hunk");
1363 int len = linelen(line, size);
1371 case ' ': case '\n':
1383 ret = size < 3 || prefixcmp(line, "@@ ");
1386 ret = size < 5 || prefixcmp(line, "diff ");
1393 warning(_("recount: unexpected line: %.*s"),
1394 (int)linelen(line, size), line);
1399 fragment->oldlines = oldlines;
1400 fragment->newlines = newlines;
1404 * Parse a unified diff fragment header of the
1405 * form "@@ -a,b +c,d @@"
1407 static int parse_fragment_header(const char *line, int len, struct fragment *fragment)
1411 if (!len || line[len-1] != '\n')
1414 /* Figure out the number of lines in a fragment */
1415 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1416 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1421 static int find_header(const char *line, unsigned long size, int *hdrsize, struct patch *patch)
1423 unsigned long offset, len;
1425 patch->is_toplevel_relative = 0;
1426 patch->is_rename = patch->is_copy = 0;
1427 patch->is_new = patch->is_delete = -1;
1428 patch->old_mode = patch->new_mode = 0;
1429 patch->old_name = patch->new_name = NULL;
1430 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
1431 unsigned long nextlen;
1433 len = linelen(line, size);
1437 /* Testing this early allows us to take a few shortcuts.. */
1442 * Make sure we don't find any unconnected patch fragments.
1443 * That's a sign that we didn't find a header, and that a
1444 * patch has become corrupted/broken up.
1446 if (!memcmp("@@ -", line, 4)) {
1447 struct fragment dummy;
1448 if (parse_fragment_header(line, len, &dummy) < 0)
1450 die(_("patch fragment without header at line %d: %.*s"),
1451 linenr, (int)len-1, line);
1458 * Git patch? It might not have a real patch, just a rename
1459 * or mode change, so we handle that specially
1461 if (!memcmp("diff --git ", line, 11)) {
1462 int git_hdr_len = parse_git_header(line, len, size, patch);
1463 if (git_hdr_len <= len)
1465 if (!patch->old_name && !patch->new_name) {
1466 if (!patch->def_name)
1467 die(Q_("git diff header lacks filename information when removing "
1468 "%d leading pathname component (line %d)",
1469 "git diff header lacks filename information when removing "
1470 "%d leading pathname components (line %d)",
1473 patch->old_name = xstrdup(patch->def_name);
1474 patch->new_name = xstrdup(patch->def_name);
1476 if (!patch->is_delete && !patch->new_name)
1477 die("git diff header lacks filename information "
1478 "(line %d)", linenr);
1479 patch->is_toplevel_relative = 1;
1480 *hdrsize = git_hdr_len;
1484 /* --- followed by +++ ? */
1485 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1489 * We only accept unified patches, so we want it to
1490 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1491 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1493 nextlen = linelen(line + len, size - len);
1494 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1497 /* Ok, we'll consider it a patch */
1498 parse_traditional_patch(line, line+len, patch);
1499 *hdrsize = len + nextlen;
1506 static void record_ws_error(unsigned result, const char *line, int len, int linenr)
1514 if (squelch_whitespace_errors &&
1515 squelch_whitespace_errors < whitespace_error)
1518 err = whitespace_error_string(result);
1519 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1520 patch_input_file, linenr, err, len, line);
1524 static void check_whitespace(const char *line, int len, unsigned ws_rule)
1526 unsigned result = ws_check(line + 1, len - 1, ws_rule);
1528 record_ws_error(result, line + 1, len - 2, linenr);
1532 * Parse a unified diff. Note that this really needs to parse each
1533 * fragment separately, since the only way to know the difference
1534 * between a "---" that is part of a patch, and a "---" that starts
1535 * the next patch is to look at the line counts..
1537 static int parse_fragment(const char *line, unsigned long size,
1538 struct patch *patch, struct fragment *fragment)
1541 int len = linelen(line, size), offset;
1542 unsigned long oldlines, newlines;
1543 unsigned long leading, trailing;
1545 offset = parse_fragment_header(line, len, fragment);
1548 if (offset > 0 && patch->recount)
1549 recount_diff(line + offset, size - offset, fragment);
1550 oldlines = fragment->oldlines;
1551 newlines = fragment->newlines;
1555 /* Parse the thing.. */
1559 added = deleted = 0;
1562 offset += len, size -= len, line += len, linenr++) {
1563 if (!oldlines && !newlines)
1565 len = linelen(line, size);
1566 if (!len || line[len-1] != '\n')
1571 case '\n': /* newer GNU diff, an empty context line */
1575 if (!deleted && !added)
1580 if (apply_in_reverse &&
1581 ws_error_action != nowarn_ws_error)
1582 check_whitespace(line, len, patch->ws_rule);
1588 if (!apply_in_reverse &&
1589 ws_error_action != nowarn_ws_error)
1590 check_whitespace(line, len, patch->ws_rule);
1597 * We allow "\ No newline at end of file". Depending
1598 * on locale settings when the patch was produced we
1599 * don't know what this line looks like. The only
1600 * thing we do know is that it begins with "\ ".
1601 * Checking for 12 is just for sanity check -- any
1602 * l10n of "\ No newline..." is at least that long.
1605 if (len < 12 || memcmp(line, "\\ ", 2))
1610 if (oldlines || newlines)
1612 fragment->leading = leading;
1613 fragment->trailing = trailing;
1616 * If a fragment ends with an incomplete line, we failed to include
1617 * it in the above loop because we hit oldlines == newlines == 0
1620 if (12 < size && !memcmp(line, "\\ ", 2))
1621 offset += linelen(line, size);
1623 patch->lines_added += added;
1624 patch->lines_deleted += deleted;
1626 if (0 < patch->is_new && oldlines)
1627 return error(_("new file depends on old contents"));
1628 if (0 < patch->is_delete && newlines)
1629 return error(_("deleted file still has contents"));
1634 * We have seen "diff --git a/... b/..." header (or a traditional patch
1635 * header). Read hunks that belong to this patch into fragments and hang
1636 * them to the given patch structure.
1638 * The (fragment->patch, fragment->size) pair points into the memory given
1639 * by the caller, not a copy, when we return.
1641 static int parse_single_patch(const char *line, unsigned long size, struct patch *patch)
1643 unsigned long offset = 0;
1644 unsigned long oldlines = 0, newlines = 0, context = 0;
1645 struct fragment **fragp = &patch->fragments;
1647 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1648 struct fragment *fragment;
1651 fragment = xcalloc(1, sizeof(*fragment));
1652 fragment->linenr = linenr;
1653 len = parse_fragment(line, size, patch, fragment);
1655 die(_("corrupt patch at line %d"), linenr);
1656 fragment->patch = line;
1657 fragment->size = len;
1658 oldlines += fragment->oldlines;
1659 newlines += fragment->newlines;
1660 context += fragment->leading + fragment->trailing;
1663 fragp = &fragment->next;
1671 * If something was removed (i.e. we have old-lines) it cannot
1672 * be creation, and if something was added it cannot be
1673 * deletion. However, the reverse is not true; --unified=0
1674 * patches that only add are not necessarily creation even
1675 * though they do not have any old lines, and ones that only
1676 * delete are not necessarily deletion.
1678 * Unfortunately, a real creation/deletion patch do _not_ have
1679 * any context line by definition, so we cannot safely tell it
1680 * apart with --unified=0 insanity. At least if the patch has
1681 * more than one hunk it is not creation or deletion.
1683 if (patch->is_new < 0 &&
1684 (oldlines || (patch->fragments && patch->fragments->next)))
1686 if (patch->is_delete < 0 &&
1687 (newlines || (patch->fragments && patch->fragments->next)))
1688 patch->is_delete = 0;
1690 if (0 < patch->is_new && oldlines)
1691 die(_("new file %s depends on old contents"), patch->new_name);
1692 if (0 < patch->is_delete && newlines)
1693 die(_("deleted file %s still has contents"), patch->old_name);
1694 if (!patch->is_delete && !newlines && context)
1697 "file %s becomes empty but is not deleted"),
1703 static inline int metadata_changes(struct patch *patch)
1705 return patch->is_rename > 0 ||
1706 patch->is_copy > 0 ||
1707 patch->is_new > 0 ||
1709 (patch->old_mode && patch->new_mode &&
1710 patch->old_mode != patch->new_mode);
1713 static char *inflate_it(const void *data, unsigned long size,
1714 unsigned long inflated_size)
1720 memset(&stream, 0, sizeof(stream));
1722 stream.next_in = (unsigned char *)data;
1723 stream.avail_in = size;
1724 stream.next_out = out = xmalloc(inflated_size);
1725 stream.avail_out = inflated_size;
1726 git_inflate_init(&stream);
1727 st = git_inflate(&stream, Z_FINISH);
1728 git_inflate_end(&stream);
1729 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1737 * Read a binary hunk and return a new fragment; fragment->patch
1738 * points at an allocated memory that the caller must free, so
1739 * it is marked as "->free_patch = 1".
1741 static struct fragment *parse_binary_hunk(char **buf_p,
1742 unsigned long *sz_p,
1747 * Expect a line that begins with binary patch method ("literal"
1748 * or "delta"), followed by the length of data before deflating.
1749 * a sequence of 'length-byte' followed by base-85 encoded data
1750 * should follow, terminated by a newline.
1752 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1753 * and we would limit the patch line to 66 characters,
1754 * so one line can fit up to 13 groups that would decode
1755 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1756 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1759 unsigned long size = *sz_p;
1760 char *buffer = *buf_p;
1762 unsigned long origlen;
1765 struct fragment *frag;
1767 llen = linelen(buffer, size);
1772 if (!prefixcmp(buffer, "delta ")) {
1773 patch_method = BINARY_DELTA_DEFLATED;
1774 origlen = strtoul(buffer + 6, NULL, 10);
1776 else if (!prefixcmp(buffer, "literal ")) {
1777 patch_method = BINARY_LITERAL_DEFLATED;
1778 origlen = strtoul(buffer + 8, NULL, 10);
1786 int byte_length, max_byte_length, newsize;
1787 llen = linelen(buffer, size);
1791 /* consume the blank line */
1797 * Minimum line is "A00000\n" which is 7-byte long,
1798 * and the line length must be multiple of 5 plus 2.
1800 if ((llen < 7) || (llen-2) % 5)
1802 max_byte_length = (llen - 2) / 5 * 4;
1803 byte_length = *buffer;
1804 if ('A' <= byte_length && byte_length <= 'Z')
1805 byte_length = byte_length - 'A' + 1;
1806 else if ('a' <= byte_length && byte_length <= 'z')
1807 byte_length = byte_length - 'a' + 27;
1810 /* if the input length was not multiple of 4, we would
1811 * have filler at the end but the filler should never
1814 if (max_byte_length < byte_length ||
1815 byte_length <= max_byte_length - 4)
1817 newsize = hunk_size + byte_length;
1818 data = xrealloc(data, newsize);
1819 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1821 hunk_size = newsize;
1826 frag = xcalloc(1, sizeof(*frag));
1827 frag->patch = inflate_it(data, hunk_size, origlen);
1828 frag->free_patch = 1;
1832 frag->size = origlen;
1836 frag->binary_patch_method = patch_method;
1842 error(_("corrupt binary patch at line %d: %.*s"),
1843 linenr-1, llen-1, buffer);
1847 static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1850 * We have read "GIT binary patch\n"; what follows is a line
1851 * that says the patch method (currently, either "literal" or
1852 * "delta") and the length of data before deflating; a
1853 * sequence of 'length-byte' followed by base-85 encoded data
1856 * When a binary patch is reversible, there is another binary
1857 * hunk in the same format, starting with patch method (either
1858 * "literal" or "delta") with the length of data, and a sequence
1859 * of length-byte + base-85 encoded data, terminated with another
1860 * empty line. This data, when applied to the postimage, produces
1863 struct fragment *forward;
1864 struct fragment *reverse;
1868 forward = parse_binary_hunk(&buffer, &size, &status, &used);
1869 if (!forward && !status)
1870 /* there has to be one hunk (forward hunk) */
1871 return error(_("unrecognized binary patch at line %d"), linenr-1);
1873 /* otherwise we already gave an error message */
1876 reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1881 * Not having reverse hunk is not an error, but having
1882 * a corrupt reverse hunk is.
1884 free((void*) forward->patch);
1888 forward->next = reverse;
1889 patch->fragments = forward;
1890 patch->is_binary = 1;
1895 * Read the patch text in "buffer" taht extends for "size" bytes; stop
1896 * reading after seeing a single patch (i.e. changes to a single file).
1897 * Create fragments (i.e. patch hunks) and hang them to the given patch.
1898 * Return the number of bytes consumed, so that the caller can call us
1899 * again for the next patch.
1901 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
1903 int hdrsize, patchsize;
1904 int offset = find_header(buffer, size, &hdrsize, patch);
1909 patch->ws_rule = whitespace_rule(patch->new_name
1913 patchsize = parse_single_patch(buffer + offset + hdrsize,
1914 size - offset - hdrsize, patch);
1917 static const char *binhdr[] = {
1922 static const char git_binary[] = "GIT binary patch\n";
1924 int hd = hdrsize + offset;
1925 unsigned long llen = linelen(buffer + hd, size - hd);
1927 if (llen == sizeof(git_binary) - 1 &&
1928 !memcmp(git_binary, buffer + hd, llen)) {
1931 used = parse_binary(buffer + hd + llen,
1932 size - hd - llen, patch);
1934 patchsize = used + llen;
1938 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
1939 for (i = 0; binhdr[i]; i++) {
1940 int len = strlen(binhdr[i]);
1941 if (len < size - hd &&
1942 !memcmp(binhdr[i], buffer + hd, len)) {
1944 patch->is_binary = 1;
1951 /* Empty patch cannot be applied if it is a text patch
1952 * without metadata change. A binary patch appears
1955 if ((apply || check) &&
1956 (!patch->is_binary && !metadata_changes(patch)))
1957 die(_("patch with only garbage at line %d"), linenr);
1960 return offset + hdrsize + patchsize;
1963 #define swap(a,b) myswap((a),(b),sizeof(a))
1965 #define myswap(a, b, size) do { \
1966 unsigned char mytmp[size]; \
1967 memcpy(mytmp, &a, size); \
1968 memcpy(&a, &b, size); \
1969 memcpy(&b, mytmp, size); \
1972 static void reverse_patches(struct patch *p)
1974 for (; p; p = p->next) {
1975 struct fragment *frag = p->fragments;
1977 swap(p->new_name, p->old_name);
1978 swap(p->new_mode, p->old_mode);
1979 swap(p->is_new, p->is_delete);
1980 swap(p->lines_added, p->lines_deleted);
1981 swap(p->old_sha1_prefix, p->new_sha1_prefix);
1983 for (; frag; frag = frag->next) {
1984 swap(frag->newpos, frag->oldpos);
1985 swap(frag->newlines, frag->oldlines);
1990 static const char pluses[] =
1991 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1992 static const char minuses[]=
1993 "----------------------------------------------------------------------";
1995 static void show_stats(struct patch *patch)
1997 struct strbuf qname = STRBUF_INIT;
1998 char *cp = patch->new_name ? patch->new_name : patch->old_name;
2001 quote_c_style(cp, &qname, NULL, 0);
2004 * "scale" the filename
2010 if (qname.len > max) {
2011 cp = strchr(qname.buf + qname.len + 3 - max, '/');
2013 cp = qname.buf + qname.len + 3 - max;
2014 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
2017 if (patch->is_binary) {
2018 printf(" %-*s | Bin\n", max, qname.buf);
2019 strbuf_release(&qname);
2023 printf(" %-*s |", max, qname.buf);
2024 strbuf_release(&qname);
2027 * scale the add/delete
2029 max = max + max_change > 70 ? 70 - max : max_change;
2030 add = patch->lines_added;
2031 del = patch->lines_deleted;
2033 if (max_change > 0) {
2034 int total = ((add + del) * max + max_change / 2) / max_change;
2035 add = (add * max + max_change / 2) / max_change;
2038 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
2039 add, pluses, del, minuses);
2042 static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
2044 switch (st->st_mode & S_IFMT) {
2046 if (strbuf_readlink(buf, path, st->st_size) < 0)
2047 return error(_("unable to read symlink %s"), path);
2050 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
2051 return error(_("unable to open or read %s"), path);
2052 convert_to_git(path, buf->buf, buf->len, buf, 0);
2060 * Update the preimage, and the common lines in postimage,
2061 * from buffer buf of length len. If postlen is 0 the postimage
2062 * is updated in place, otherwise it's updated on a new buffer
2066 static void update_pre_post_images(struct image *preimage,
2067 struct image *postimage,
2069 size_t len, size_t postlen)
2072 char *new, *old, *fixed;
2073 struct image fixed_preimage;
2076 * Update the preimage with whitespace fixes. Note that we
2077 * are not losing preimage->buf -- apply_one_fragment() will
2080 prepare_image(&fixed_preimage, buf, len, 1);
2081 assert(fixed_preimage.nr == preimage->nr);
2082 for (i = 0; i < preimage->nr; i++)
2083 fixed_preimage.line[i].flag = preimage->line[i].flag;
2084 free(preimage->line_allocated);
2085 *preimage = fixed_preimage;
2088 * Adjust the common context lines in postimage. This can be
2089 * done in-place when we are just doing whitespace fixing,
2090 * which does not make the string grow, but needs a new buffer
2091 * when ignoring whitespace causes the update, since in this case
2092 * we could have e.g. tabs converted to multiple spaces.
2093 * We trust the caller to tell us if the update can be done
2094 * in place (postlen==0) or not.
2096 old = postimage->buf;
2098 new = postimage->buf = xmalloc(postlen);
2101 fixed = preimage->buf;
2102 for (i = ctx = 0; i < postimage->nr; i++) {
2103 size_t len = postimage->line[i].len;
2104 if (!(postimage->line[i].flag & LINE_COMMON)) {
2105 /* an added line -- no counterparts in preimage */
2106 memmove(new, old, len);
2112 /* a common context -- skip it in the original postimage */
2115 /* and find the corresponding one in the fixed preimage */
2116 while (ctx < preimage->nr &&
2117 !(preimage->line[ctx].flag & LINE_COMMON)) {
2118 fixed += preimage->line[ctx].len;
2121 if (preimage->nr <= ctx)
2124 /* and copy it in, while fixing the line length */
2125 len = preimage->line[ctx].len;
2126 memcpy(new, fixed, len);
2129 postimage->line[i].len = len;
2133 /* Fix the length of the whole thing */
2134 postimage->len = new - postimage->buf;
2137 static int match_fragment(struct image *img,
2138 struct image *preimage,
2139 struct image *postimage,
2143 int match_beginning, int match_end)
2146 char *fixed_buf, *buf, *orig, *target;
2147 struct strbuf fixed;
2151 if (preimage->nr + try_lno <= img->nr) {
2153 * The hunk falls within the boundaries of img.
2155 preimage_limit = preimage->nr;
2156 if (match_end && (preimage->nr + try_lno != img->nr))
2158 } else if (ws_error_action == correct_ws_error &&
2159 (ws_rule & WS_BLANK_AT_EOF)) {
2161 * This hunk extends beyond the end of img, and we are
2162 * removing blank lines at the end of the file. This
2163 * many lines from the beginning of the preimage must
2164 * match with img, and the remainder of the preimage
2167 preimage_limit = img->nr - try_lno;
2170 * The hunk extends beyond the end of the img and
2171 * we are not removing blanks at the end, so we
2172 * should reject the hunk at this position.
2177 if (match_beginning && try_lno)
2180 /* Quick hash check */
2181 for (i = 0; i < preimage_limit; i++)
2182 if ((img->line[try_lno + i].flag & LINE_PATCHED) ||
2183 (preimage->line[i].hash != img->line[try_lno + i].hash))
2186 if (preimage_limit == preimage->nr) {
2188 * Do we have an exact match? If we were told to match
2189 * at the end, size must be exactly at try+fragsize,
2190 * otherwise try+fragsize must be still within the preimage,
2191 * and either case, the old piece should match the preimage
2195 ? (try + preimage->len == img->len)
2196 : (try + preimage->len <= img->len)) &&
2197 !memcmp(img->buf + try, preimage->buf, preimage->len))
2201 * The preimage extends beyond the end of img, so
2202 * there cannot be an exact match.
2204 * There must be one non-blank context line that match
2205 * a line before the end of img.
2209 buf = preimage->buf;
2211 for (i = 0; i < preimage_limit; i++)
2212 buf_end += preimage->line[i].len;
2214 for ( ; buf < buf_end; buf++)
2222 * No exact match. If we are ignoring whitespace, run a line-by-line
2223 * fuzzy matching. We collect all the line length information because
2224 * we need it to adjust whitespace if we match.
2226 if (ws_ignore_action == ignore_ws_change) {
2229 size_t postlen = postimage->len;
2233 for (i = 0; i < preimage_limit; i++) {
2234 size_t prelen = preimage->line[i].len;
2235 size_t imglen = img->line[try_lno+i].len;
2237 if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,
2238 preimage->buf + preoff, prelen))
2240 if (preimage->line[i].flag & LINE_COMMON)
2241 postlen += imglen - prelen;
2247 * Ok, the preimage matches with whitespace fuzz.
2249 * imgoff now holds the true length of the target that
2250 * matches the preimage before the end of the file.
2252 * Count the number of characters in the preimage that fall
2253 * beyond the end of the file and make sure that all of them
2254 * are whitespace characters. (This can only happen if
2255 * we are removing blank lines at the end of the file.)
2257 buf = preimage_eof = preimage->buf + preoff;
2258 for ( ; i < preimage->nr; i++)
2259 preoff += preimage->line[i].len;
2260 preimage_end = preimage->buf + preoff;
2261 for ( ; buf < preimage_end; buf++)
2266 * Update the preimage and the common postimage context
2267 * lines to use the same whitespace as the target.
2268 * If whitespace is missing in the target (i.e.
2269 * if the preimage extends beyond the end of the file),
2270 * use the whitespace from the preimage.
2272 extra_chars = preimage_end - preimage_eof;
2273 strbuf_init(&fixed, imgoff + extra_chars);
2274 strbuf_add(&fixed, img->buf + try, imgoff);
2275 strbuf_add(&fixed, preimage_eof, extra_chars);
2276 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2277 update_pre_post_images(preimage, postimage,
2278 fixed_buf, fixed_len, postlen);
2282 if (ws_error_action != correct_ws_error)
2286 * The hunk does not apply byte-by-byte, but the hash says
2287 * it might with whitespace fuzz. We haven't been asked to
2288 * ignore whitespace, we were asked to correct whitespace
2289 * errors, so let's try matching after whitespace correction.
2291 * The preimage may extend beyond the end of the file,
2292 * but in this loop we will only handle the part of the
2293 * preimage that falls within the file.
2295 strbuf_init(&fixed, preimage->len + 1);
2296 orig = preimage->buf;
2297 target = img->buf + try;
2298 for (i = 0; i < preimage_limit; i++) {
2299 size_t oldlen = preimage->line[i].len;
2300 size_t tgtlen = img->line[try_lno + i].len;
2301 size_t fixstart = fixed.len;
2302 struct strbuf tgtfix;
2305 /* Try fixing the line in the preimage */
2306 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2308 /* Try fixing the line in the target */
2309 strbuf_init(&tgtfix, tgtlen);
2310 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2313 * If they match, either the preimage was based on
2314 * a version before our tree fixed whitespace breakage,
2315 * or we are lacking a whitespace-fix patch the tree
2316 * the preimage was based on already had (i.e. target
2317 * has whitespace breakage, the preimage doesn't).
2318 * In either case, we are fixing the whitespace breakages
2319 * so we might as well take the fix together with their
2322 match = (tgtfix.len == fixed.len - fixstart &&
2323 !memcmp(tgtfix.buf, fixed.buf + fixstart,
2324 fixed.len - fixstart));
2326 strbuf_release(&tgtfix);
2336 * Now handle the lines in the preimage that falls beyond the
2337 * end of the file (if any). They will only match if they are
2338 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2341 for ( ; i < preimage->nr; i++) {
2342 size_t fixstart = fixed.len; /* start of the fixed preimage */
2343 size_t oldlen = preimage->line[i].len;
2346 /* Try fixing the line in the preimage */
2347 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2349 for (j = fixstart; j < fixed.len; j++)
2350 if (!isspace(fixed.buf[j]))
2357 * Yes, the preimage is based on an older version that still
2358 * has whitespace breakages unfixed, and fixing them makes the
2359 * hunk match. Update the context lines in the postimage.
2361 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2362 update_pre_post_images(preimage, postimage,
2363 fixed_buf, fixed_len, 0);
2367 strbuf_release(&fixed);
2371 static int find_pos(struct image *img,
2372 struct image *preimage,
2373 struct image *postimage,
2376 int match_beginning, int match_end)
2379 unsigned long backwards, forwards, try;
2380 int backwards_lno, forwards_lno, try_lno;
2383 * If match_beginning or match_end is specified, there is no
2384 * point starting from a wrong line that will never match and
2385 * wander around and wait for a match at the specified end.
2387 if (match_beginning)
2390 line = img->nr - preimage->nr;
2393 * Because the comparison is unsigned, the following test
2394 * will also take care of a negative line number that can
2395 * result when match_end and preimage is larger than the target.
2397 if ((size_t) line > img->nr)
2401 for (i = 0; i < line; i++)
2402 try += img->line[i].len;
2405 * There's probably some smart way to do this, but I'll leave
2406 * that to the smart and beautiful people. I'm simple and stupid.
2409 backwards_lno = line;
2411 forwards_lno = line;
2414 for (i = 0; ; i++) {
2415 if (match_fragment(img, preimage, postimage,
2416 try, try_lno, ws_rule,
2417 match_beginning, match_end))
2421 if (backwards_lno == 0 && forwards_lno == img->nr)
2425 if (backwards_lno == 0) {
2430 backwards -= img->line[backwards_lno].len;
2432 try_lno = backwards_lno;
2434 if (forwards_lno == img->nr) {
2438 forwards += img->line[forwards_lno].len;
2441 try_lno = forwards_lno;
2448 static void remove_first_line(struct image *img)
2450 img->buf += img->line[0].len;
2451 img->len -= img->line[0].len;
2456 static void remove_last_line(struct image *img)
2458 img->len -= img->line[--img->nr].len;
2462 * The change from "preimage" and "postimage" has been found to
2463 * apply at applied_pos (counts in line numbers) in "img".
2464 * Update "img" to remove "preimage" and replace it with "postimage".
2466 static void update_image(struct image *img,
2468 struct image *preimage,
2469 struct image *postimage)
2472 * remove the copy of preimage at offset in img
2473 * and replace it with postimage
2476 size_t remove_count, insert_count, applied_at = 0;
2481 * If we are removing blank lines at the end of img,
2482 * the preimage may extend beyond the end.
2483 * If that is the case, we must be careful only to
2484 * remove the part of the preimage that falls within
2485 * the boundaries of img. Initialize preimage_limit
2486 * to the number of lines in the preimage that falls
2487 * within the boundaries.
2489 preimage_limit = preimage->nr;
2490 if (preimage_limit > img->nr - applied_pos)
2491 preimage_limit = img->nr - applied_pos;
2493 for (i = 0; i < applied_pos; i++)
2494 applied_at += img->line[i].len;
2497 for (i = 0; i < preimage_limit; i++)
2498 remove_count += img->line[applied_pos + i].len;
2499 insert_count = postimage->len;
2501 /* Adjust the contents */
2502 result = xmalloc(img->len + insert_count - remove_count + 1);
2503 memcpy(result, img->buf, applied_at);
2504 memcpy(result + applied_at, postimage->buf, postimage->len);
2505 memcpy(result + applied_at + postimage->len,
2506 img->buf + (applied_at + remove_count),
2507 img->len - (applied_at + remove_count));
2510 img->len += insert_count - remove_count;
2511 result[img->len] = '\0';
2513 /* Adjust the line table */
2514 nr = img->nr + postimage->nr - preimage_limit;
2515 if (preimage_limit < postimage->nr) {
2517 * NOTE: this knows that we never call remove_first_line()
2518 * on anything other than pre/post image.
2520 img->line = xrealloc(img->line, nr * sizeof(*img->line));
2521 img->line_allocated = img->line;
2523 if (preimage_limit != postimage->nr)
2524 memmove(img->line + applied_pos + postimage->nr,
2525 img->line + applied_pos + preimage_limit,
2526 (img->nr - (applied_pos + preimage_limit)) *
2527 sizeof(*img->line));
2528 memcpy(img->line + applied_pos,
2530 postimage->nr * sizeof(*img->line));
2532 for (i = 0; i < postimage->nr; i++)
2533 img->line[applied_pos + i].flag |= LINE_PATCHED;
2538 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2539 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2540 * replace the part of "img" with "postimage" text.
2542 static int apply_one_fragment(struct image *img, struct fragment *frag,
2543 int inaccurate_eof, unsigned ws_rule,
2546 int match_beginning, match_end;
2547 const char *patch = frag->patch;
2548 int size = frag->size;
2549 char *old, *oldlines;
2550 struct strbuf newlines;
2551 int new_blank_lines_at_end = 0;
2552 int found_new_blank_lines_at_end = 0;
2553 int hunk_linenr = frag->linenr;
2554 unsigned long leading, trailing;
2555 int pos, applied_pos;
2556 struct image preimage;
2557 struct image postimage;
2559 memset(&preimage, 0, sizeof(preimage));
2560 memset(&postimage, 0, sizeof(postimage));
2561 oldlines = xmalloc(size);
2562 strbuf_init(&newlines, size);
2567 int len = linelen(patch, size);
2569 int added_blank_line = 0;
2570 int is_blank_context = 0;
2577 * "plen" is how much of the line we should use for
2578 * the actual patch data. Normally we just remove the
2579 * first character on the line, but if the line is
2580 * followed by "\ No newline", then we also remove the
2581 * last one (which is the newline, of course).
2584 if (len < size && patch[len] == '\\')
2587 if (apply_in_reverse) {
2590 else if (first == '+')
2596 /* Newer GNU diff, empty context line */
2598 /* ... followed by '\No newline'; nothing */
2601 strbuf_addch(&newlines, '\n');
2602 add_line_info(&preimage, "\n", 1, LINE_COMMON);
2603 add_line_info(&postimage, "\n", 1, LINE_COMMON);
2604 is_blank_context = 1;
2607 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2608 ws_blank_line(patch + 1, plen, ws_rule))
2609 is_blank_context = 1;
2611 memcpy(old, patch + 1, plen);
2612 add_line_info(&preimage, old, plen,
2613 (first == ' ' ? LINE_COMMON : 0));
2617 /* Fall-through for ' ' */
2619 /* --no-add does not add new lines */
2620 if (first == '+' && no_add)
2623 start = newlines.len;
2625 !whitespace_error ||
2626 ws_error_action != correct_ws_error) {
2627 strbuf_add(&newlines, patch + 1, plen);
2630 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &applied_after_fixing_ws);
2632 add_line_info(&postimage, newlines.buf + start, newlines.len - start,
2633 (first == '+' ? 0 : LINE_COMMON));
2635 (ws_rule & WS_BLANK_AT_EOF) &&
2636 ws_blank_line(patch + 1, plen, ws_rule))
2637 added_blank_line = 1;
2639 case '@': case '\\':
2640 /* Ignore it, we already handled it */
2643 if (apply_verbosely)
2644 error(_("invalid start of line: '%c'"), first);
2647 if (added_blank_line) {
2648 if (!new_blank_lines_at_end)
2649 found_new_blank_lines_at_end = hunk_linenr;
2650 new_blank_lines_at_end++;
2652 else if (is_blank_context)
2655 new_blank_lines_at_end = 0;
2660 if (inaccurate_eof &&
2661 old > oldlines && old[-1] == '\n' &&
2662 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
2664 strbuf_setlen(&newlines, newlines.len - 1);
2667 leading = frag->leading;
2668 trailing = frag->trailing;
2671 * A hunk to change lines at the beginning would begin with
2673 * but we need to be careful. -U0 that inserts before the second
2674 * line also has this pattern.
2676 * And a hunk to add to an empty file would begin with
2679 * In other words, a hunk that is (frag->oldpos <= 1) with or
2680 * without leading context must match at the beginning.
2682 match_beginning = (!frag->oldpos ||
2683 (frag->oldpos == 1 && !unidiff_zero));
2686 * A hunk without trailing lines must match at the end.
2687 * However, we simply cannot tell if a hunk must match end
2688 * from the lack of trailing lines if the patch was generated
2689 * with unidiff without any context.
2691 match_end = !unidiff_zero && !trailing;
2693 pos = frag->newpos ? (frag->newpos - 1) : 0;
2694 preimage.buf = oldlines;
2695 preimage.len = old - oldlines;
2696 postimage.buf = newlines.buf;
2697 postimage.len = newlines.len;
2698 preimage.line = preimage.line_allocated;
2699 postimage.line = postimage.line_allocated;
2703 applied_pos = find_pos(img, &preimage, &postimage, pos,
2704 ws_rule, match_beginning, match_end);
2706 if (applied_pos >= 0)
2709 /* Am I at my context limits? */
2710 if ((leading <= p_context) && (trailing <= p_context))
2712 if (match_beginning || match_end) {
2713 match_beginning = match_end = 0;
2718 * Reduce the number of context lines; reduce both
2719 * leading and trailing if they are equal otherwise
2720 * just reduce the larger context.
2722 if (leading >= trailing) {
2723 remove_first_line(&preimage);
2724 remove_first_line(&postimage);
2728 if (trailing > leading) {
2729 remove_last_line(&preimage);
2730 remove_last_line(&postimage);
2735 if (applied_pos >= 0) {
2736 if (new_blank_lines_at_end &&
2737 preimage.nr + applied_pos >= img->nr &&
2738 (ws_rule & WS_BLANK_AT_EOF) &&
2739 ws_error_action != nowarn_ws_error) {
2740 record_ws_error(WS_BLANK_AT_EOF, "+", 1,
2741 found_new_blank_lines_at_end);
2742 if (ws_error_action == correct_ws_error) {
2743 while (new_blank_lines_at_end--)
2744 remove_last_line(&postimage);
2747 * We would want to prevent write_out_results()
2748 * from taking place in apply_patch() that follows
2749 * the callchain led us here, which is:
2750 * apply_patch->check_patch_list->check_patch->
2751 * apply_data->apply_fragments->apply_one_fragment
2753 if (ws_error_action == die_on_ws_error)
2757 if (apply_verbosely && applied_pos != pos) {
2758 int offset = applied_pos - pos;
2759 if (apply_in_reverse)
2760 offset = 0 - offset;
2762 Q_("Hunk #%d succeeded at %d (offset %d line).",
2763 "Hunk #%d succeeded at %d (offset %d lines).",
2765 nth_fragment, applied_pos + 1, offset);
2769 * Warn if it was necessary to reduce the number
2772 if ((leading != frag->leading) ||
2773 (trailing != frag->trailing))
2774 fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"
2775 " to apply fragment at %d"),
2776 leading, trailing, applied_pos+1);
2777 update_image(img, applied_pos, &preimage, &postimage);
2779 if (apply_verbosely)
2780 error(_("while searching for:\n%.*s"),
2781 (int)(old - oldlines), oldlines);
2785 strbuf_release(&newlines);
2786 free(preimage.line_allocated);
2787 free(postimage.line_allocated);
2789 return (applied_pos < 0);
2792 static int apply_binary_fragment(struct image *img, struct patch *patch)
2794 struct fragment *fragment = patch->fragments;
2799 return error(_("missing binary patch data for '%s'"),
2804 /* Binary patch is irreversible without the optional second hunk */
2805 if (apply_in_reverse) {
2806 if (!fragment->next)
2807 return error("cannot reverse-apply a binary patch "
2808 "without the reverse hunk to '%s'",
2810 ? patch->new_name : patch->old_name);
2811 fragment = fragment->next;
2813 switch (fragment->binary_patch_method) {
2814 case BINARY_DELTA_DEFLATED:
2815 dst = patch_delta(img->buf, img->len, fragment->patch,
2816 fragment->size, &len);
2823 case BINARY_LITERAL_DEFLATED:
2825 img->len = fragment->size;
2826 img->buf = xmalloc(img->len+1);
2827 memcpy(img->buf, fragment->patch, img->len);
2828 img->buf[img->len] = '\0';
2835 * Replace "img" with the result of applying the binary patch.
2836 * The binary patch data itself in patch->fragment is still kept
2837 * but the preimage prepared by the caller in "img" is freed here
2838 * or in the helper function apply_binary_fragment() this calls.
2840 static int apply_binary(struct image *img, struct patch *patch)
2842 const char *name = patch->old_name ? patch->old_name : patch->new_name;
2843 unsigned char sha1[20];
2846 * For safety, we require patch index line to contain
2847 * full 40-byte textual SHA1 for old and new, at least for now.
2849 if (strlen(patch->old_sha1_prefix) != 40 ||
2850 strlen(patch->new_sha1_prefix) != 40 ||
2851 get_sha1_hex(patch->old_sha1_prefix, sha1) ||
2852 get_sha1_hex(patch->new_sha1_prefix, sha1))
2853 return error("cannot apply binary patch to '%s' "
2854 "without full index line", name);
2856 if (patch->old_name) {
2858 * See if the old one matches what the patch
2861 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2862 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
2863 return error("the patch applies to '%s' (%s), "
2864 "which does not match the "
2865 "current contents.",
2866 name, sha1_to_hex(sha1));
2869 /* Otherwise, the old one must be empty. */
2871 return error("the patch applies to an empty "
2872 "'%s' but it is not empty", name);
2875 get_sha1_hex(patch->new_sha1_prefix, sha1);
2876 if (is_null_sha1(sha1)) {
2878 return 0; /* deletion patch */
2881 if (has_sha1_file(sha1)) {
2882 /* We already have the postimage */
2883 enum object_type type;
2887 result = read_sha1_file(sha1, &type, &size);
2889 return error("the necessary postimage %s for "
2890 "'%s' cannot be read",
2891 patch->new_sha1_prefix, name);
2897 * We have verified buf matches the preimage;
2898 * apply the patch data to it, which is stored
2899 * in the patch->fragments->{patch,size}.
2901 if (apply_binary_fragment(img, patch))
2902 return error(_("binary patch does not apply to '%s'"),
2905 /* verify that the result matches */
2906 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2907 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
2908 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
2909 name, patch->new_sha1_prefix, sha1_to_hex(sha1));
2915 static int apply_fragments(struct image *img, struct patch *patch)
2917 struct fragment *frag = patch->fragments;
2918 const char *name = patch->old_name ? patch->old_name : patch->new_name;
2919 unsigned ws_rule = patch->ws_rule;
2920 unsigned inaccurate_eof = patch->inaccurate_eof;
2923 if (patch->is_binary)
2924 return apply_binary(img, patch);
2928 if (apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {
2929 error(_("patch failed: %s:%ld"), name, frag->oldpos);
2930 if (!apply_with_reject)
2939 static int read_file_or_gitlink(struct cache_entry *ce, struct strbuf *buf)
2944 if (S_ISGITLINK(ce->ce_mode)) {
2945 strbuf_grow(buf, 100);
2946 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(ce->sha1));
2948 enum object_type type;
2952 result = read_sha1_file(ce->sha1, &type, &sz);
2955 /* XXX read_sha1_file NUL-terminates */
2956 strbuf_attach(buf, result, sz, sz + 1);
2961 static struct patch *in_fn_table(const char *name)
2963 struct string_list_item *item;
2968 item = string_list_lookup(&fn_table, name);
2970 return (struct patch *)item->util;
2976 * item->util in the filename table records the status of the path.
2977 * Usually it points at a patch (whose result records the contents
2978 * of it after applying it), but it could be PATH_WAS_DELETED for a
2979 * path that a previously applied patch has already removed.
2981 #define PATH_TO_BE_DELETED ((struct patch *) -2)
2982 #define PATH_WAS_DELETED ((struct patch *) -1)
2984 static int to_be_deleted(struct patch *patch)
2986 return patch == PATH_TO_BE_DELETED;
2989 static int was_deleted(struct patch *patch)
2991 return patch == PATH_WAS_DELETED;
2994 static void add_to_fn_table(struct patch *patch)
2996 struct string_list_item *item;
2999 * Always add new_name unless patch is a deletion
3000 * This should cover the cases for normal diffs,
3001 * file creations and copies
3003 if (patch->new_name != NULL) {
3004 item = string_list_insert(&fn_table, patch->new_name);
3009 * store a failure on rename/deletion cases because
3010 * later chunks shouldn't patch old names
3012 if ((patch->new_name == NULL) || (patch->is_rename)) {
3013 item = string_list_insert(&fn_table, patch->old_name);
3014 item->util = PATH_WAS_DELETED;
3018 static void prepare_fn_table(struct patch *patch)
3021 * store information about incoming file deletion
3024 if ((patch->new_name == NULL) || (patch->is_rename)) {
3025 struct string_list_item *item;
3026 item = string_list_insert(&fn_table, patch->old_name);
3027 item->util = PATH_TO_BE_DELETED;
3029 patch = patch->next;
3033 static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce)
3035 struct strbuf buf = STRBUF_INIT;
3039 struct patch *tpatch;
3041 if (!(patch->is_copy || patch->is_rename) &&
3042 (tpatch = in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {
3043 if (was_deleted(tpatch)) {
3044 return error(_("patch %s has been renamed/deleted"),
3047 /* We have a patched copy in memory; use that. */
3048 strbuf_add(&buf, tpatch->result, tpatch->resultsize);
3049 } else if (cached) {
3050 if (read_file_or_gitlink(ce, &buf))
3051 return error(_("read of %s failed"), patch->old_name);
3052 } else if (patch->old_name) {
3053 if (S_ISGITLINK(patch->old_mode)) {
3055 read_file_or_gitlink(ce, &buf);
3058 * There is no way to apply subproject
3059 * patch without looking at the index.
3060 * NEEDSWORK: shouldn't this be flagged
3063 free_fragment_list(patch->fragments);
3064 patch->fragments = NULL;
3067 if (read_old_data(st, patch->old_name, &buf))
3068 return error(_("read of %s failed"), patch->old_name);
3072 img = strbuf_detach(&buf, &len);
3073 prepare_image(&image, img, len, !patch->is_binary);
3075 if (apply_fragments(&image, patch) < 0)
3076 return -1; /* note with --reject this succeeds. */
3077 patch->result = image.buf;
3078 patch->resultsize = image.len;
3079 add_to_fn_table(patch);
3080 free(image.line_allocated);
3082 if (0 < patch->is_delete && patch->resultsize)
3083 return error(_("removal patch leaves file contents"));
3088 static int check_to_create_blob(const char *new_name, int ok_if_exists)
3091 if (!lstat(new_name, &nst)) {
3092 if (S_ISDIR(nst.st_mode) || ok_if_exists)
3095 * A leading component of new_name might be a symlink
3096 * that is going to be removed with this patch, but
3097 * still pointing at somewhere that has the path.
3098 * In such a case, path "new_name" does not exist as
3099 * far as git is concerned.
3101 if (has_symlink_leading_path(new_name, strlen(new_name)))
3104 return error(_("%s: already exists in working directory"), new_name);
3106 else if ((errno != ENOENT) && (errno != ENOTDIR))
3107 return error("%s: %s", new_name, strerror(errno));
3111 static int verify_index_match(struct cache_entry *ce, struct stat *st)
3113 if (S_ISGITLINK(ce->ce_mode)) {
3114 if (!S_ISDIR(st->st_mode))
3118 return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
3121 static int check_preimage(struct patch *patch, struct cache_entry **ce, struct stat *st)
3123 const char *old_name = patch->old_name;
3124 struct patch *tpatch = NULL;
3126 unsigned st_mode = 0;
3129 * Make sure that we do not have local modifications from the
3130 * index when we are looking at the index. Also make sure
3131 * we have the preimage file to be patched in the work tree,
3132 * unless --cached, which tells git to apply only in the index.
3137 assert(patch->is_new <= 0);
3139 if (!(patch->is_copy || patch->is_rename) &&
3140 (tpatch = in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {
3141 if (was_deleted(tpatch))
3142 return error(_("%s: has been deleted/renamed"), old_name);
3143 st_mode = tpatch->new_mode;
3144 } else if (!cached) {
3145 stat_ret = lstat(old_name, st);
3146 if (stat_ret && errno != ENOENT)
3147 return error(_("%s: %s"), old_name, strerror(errno));
3150 if (to_be_deleted(tpatch))
3153 if (check_index && !tpatch) {
3154 int pos = cache_name_pos(old_name, strlen(old_name));
3156 if (patch->is_new < 0)
3158 return error(_("%s: does not exist in index"), old_name);
3160 *ce = active_cache[pos];
3162 struct checkout costate;
3164 memset(&costate, 0, sizeof(costate));
3165 costate.base_dir = "";
3166 costate.refresh_cache = 1;
3167 if (checkout_entry(*ce, &costate, NULL) ||
3168 lstat(old_name, st))
3171 if (!cached && verify_index_match(*ce, st))
3172 return error(_("%s: does not match index"), old_name);
3174 st_mode = (*ce)->ce_mode;
3175 } else if (stat_ret < 0) {
3176 if (patch->is_new < 0)
3178 return error(_("%s: %s"), old_name, strerror(errno));
3181 if (!cached && !tpatch)
3182 st_mode = ce_mode_from_stat(*ce, st->st_mode);
3184 if (patch->is_new < 0)
3186 if (!patch->old_mode)
3187 patch->old_mode = st_mode;
3188 if ((st_mode ^ patch->old_mode) & S_IFMT)
3189 return error(_("%s: wrong type"), old_name);
3190 if (st_mode != patch->old_mode)
3191 warning(_("%s has type %o, expected %o"),
3192 old_name, st_mode, patch->old_mode);
3193 if (!patch->new_mode && !patch->is_delete)
3194 patch->new_mode = st_mode;
3199 patch->is_delete = 0;
3200 free(patch->old_name);
3201 patch->old_name = NULL;
3206 * Check and apply the patch in-core; leave the result in patch->result
3207 * for the caller to write it out to the final destination.
3209 static int check_patch(struct patch *patch)
3212 const char *old_name = patch->old_name;
3213 const char *new_name = patch->new_name;
3214 const char *name = old_name ? old_name : new_name;
3215 struct cache_entry *ce = NULL;
3216 struct patch *tpatch;
3220 patch->rejected = 1; /* we will drop this after we succeed */
3222 status = check_preimage(patch, &ce, &st);
3225 old_name = patch->old_name;
3227 if ((tpatch = in_fn_table(new_name)) &&
3228 (was_deleted(tpatch) || to_be_deleted(tpatch)))
3230 * A type-change diff is always split into a patch to
3231 * delete old, immediately followed by a patch to
3232 * create new (see diff.c::run_diff()); in such a case
3233 * it is Ok that the entry to be deleted by the
3234 * previous patch is still in the working tree and in
3242 ((0 < patch->is_new) | (0 < patch->is_rename) | patch->is_copy)) {
3244 cache_name_pos(new_name, strlen(new_name)) >= 0 &&
3246 return error(_("%s: already exists in index"), new_name);
3248 int err = check_to_create_blob(new_name, ok_if_exists);
3252 if (!patch->new_mode) {
3253 if (0 < patch->is_new)
3254 patch->new_mode = S_IFREG | 0644;
3256 patch->new_mode = patch->old_mode;
3260 if (new_name && old_name) {
3261 int same = !strcmp(old_name, new_name);
3262 if (!patch->new_mode)
3263 patch->new_mode = patch->old_mode;
3264 if ((patch->old_mode ^ patch->new_mode) & S_IFMT) {
3266 return error(_("new mode (%o) of %s does not "
3267 "match old mode (%o)"),
3268 patch->new_mode, new_name,
3271 return error(_("new mode (%o) of %s does not "
3272 "match old mode (%o) of %s"),
3273 patch->new_mode, new_name,
3274 patch->old_mode, old_name);
3278 if (apply_data(patch, &st, ce) < 0)
3279 return error(_("%s: patch does not apply"), name);
3280 patch->rejected = 0;
3284 static int check_patch_list(struct patch *patch)
3288 prepare_fn_table(patch);
3290 if (apply_verbosely)
3291 say_patch_name(stderr,
3292 _("Checking patch %s..."), patch);
3293 err |= check_patch(patch);
3294 patch = patch->next;
3299 /* This function tries to read the sha1 from the current index */
3300 static int get_current_sha1(const char *path, unsigned char *sha1)
3304 if (read_cache() < 0)
3306 pos = cache_name_pos(path, strlen(path));
3309 hashcpy(sha1, active_cache[pos]->sha1);
3313 /* Build an index that contains the just the files needed for a 3way merge */
3314 static void build_fake_ancestor(struct patch *list, const char *filename)
3316 struct patch *patch;
3317 struct index_state result = { NULL };
3320 /* Once we start supporting the reverse patch, it may be
3321 * worth showing the new sha1 prefix, but until then...
3323 for (patch = list; patch; patch = patch->next) {
3324 const unsigned char *sha1_ptr;
3325 unsigned char sha1[20];
3326 struct cache_entry *ce;
3329 name = patch->old_name ? patch->old_name : patch->new_name;
3330 if (0 < patch->is_new)
3332 else if (get_sha1(patch->old_sha1_prefix, sha1))
3333 /* git diff has no index line for mode/type changes */
3334 if (!patch->lines_added && !patch->lines_deleted) {
3335 if (get_current_sha1(patch->old_name, sha1))
3336 die("mode change for %s, which is not "
3337 "in current HEAD", name);
3340 die("sha1 information is lacking or useless "
3345 ce = make_cache_entry(patch->old_mode, sha1_ptr, name, 0, 0);
3347 die(_("make_cache_entry failed for path '%s'"), name);
3348 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))
3349 die ("Could not add %s to temporary index", name);
3352 fd = open(filename, O_WRONLY | O_CREAT, 0666);
3353 if (fd < 0 || write_index(&result, fd) || close(fd))
3354 die ("Could not write temporary index to %s", filename);
3356 discard_index(&result);
3359 static void stat_patch_list(struct patch *patch)
3361 int files, adds, dels;
3363 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
3365 adds += patch->lines_added;
3366 dels += patch->lines_deleted;
3370 print_stat_summary(stdout, files, adds, dels);
3373 static void numstat_patch_list(struct patch *patch)
3375 for ( ; patch; patch = patch->next) {
3377 name = patch->new_name ? patch->new_name : patch->old_name;
3378 if (patch->is_binary)
3381 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
3382 write_name_quoted(name, stdout, line_termination);
3386 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
3389 printf(" %s mode %06o %s\n", newdelete, mode, name);
3391 printf(" %s %s\n", newdelete, name);
3394 static void show_mode_change(struct patch *p, int show_name)
3396 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
3398 printf(" mode change %06o => %06o %s\n",
3399 p->old_mode, p->new_mode, p->new_name);
3401 printf(" mode change %06o => %06o\n",
3402 p->old_mode, p->new_mode);
3406 static void show_rename_copy(struct patch *p)
3408 const char *renamecopy = p->is_rename ? "rename" : "copy";
3409 const char *old, *new;
3411 /* Find common prefix */
3415 const char *slash_old, *slash_new;
3416 slash_old = strchr(old, '/');
3417 slash_new = strchr(new, '/');
3420 slash_old - old != slash_new - new ||
3421 memcmp(old, new, slash_new - new))
3423 old = slash_old + 1;
3424 new = slash_new + 1;
3426 /* p->old_name thru old is the common prefix, and old and new
3427 * through the end of names are renames
3429 if (old != p->old_name)
3430 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
3431 (int)(old - p->old_name), p->old_name,
3432 old, new, p->score);
3434 printf(" %s %s => %s (%d%%)\n", renamecopy,
3435 p->old_name, p->new_name, p->score);
3436 show_mode_change(p, 0);
3439 static void summary_patch_list(struct patch *patch)
3443 for (p = patch; p; p = p->next) {
3445 show_file_mode_name("create", p->new_mode, p->new_name);
3446 else if (p->is_delete)
3447 show_file_mode_name("delete", p->old_mode, p->old_name);
3449 if (p->is_rename || p->is_copy)
3450 show_rename_copy(p);
3453 printf(" rewrite %s (%d%%)\n",
3454 p->new_name, p->score);
3455 show_mode_change(p, 0);
3458 show_mode_change(p, 1);
3464 static void patch_stats(struct patch *patch)
3466 int lines = patch->lines_added + patch->lines_deleted;
3468 if (lines > max_change)
3470 if (patch->old_name) {
3471 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
3473 len = strlen(patch->old_name);
3477 if (patch->new_name) {
3478 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
3480 len = strlen(patch->new_name);
3486 static void remove_file(struct patch *patch, int rmdir_empty)
3489 if (remove_file_from_cache(patch->old_name) < 0)
3490 die(_("unable to remove %s from index"), patch->old_name);
3493 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
3494 remove_path(patch->old_name);
3499 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
3502 struct cache_entry *ce;
3503 int namelen = strlen(path);
3504 unsigned ce_size = cache_entry_size(namelen);
3509 ce = xcalloc(1, ce_size);
3510 memcpy(ce->name, path, namelen);
3511 ce->ce_mode = create_ce_mode(mode);
3512 ce->ce_flags = namelen;
3513 if (S_ISGITLINK(mode)) {
3514 const char *s = buf;
3516 if (get_sha1_hex(s + strlen("Subproject commit "), ce->sha1))
3517 die(_("corrupt patch for subproject %s"), path);
3520 if (lstat(path, &st) < 0)
3521 die_errno(_("unable to stat newly created file '%s'"),
3523 fill_stat_cache_info(ce, &st);
3525 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
3526 die(_("unable to create backing store for newly created file %s"), path);
3528 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
3529 die(_("unable to add cache entry for %s"), path);
3532 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
3535 struct strbuf nbuf = STRBUF_INIT;
3537 if (S_ISGITLINK(mode)) {
3539 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
3541 return mkdir(path, 0777);
3544 if (has_symlinks && S_ISLNK(mode))
3545 /* Although buf:size is counted string, it also is NUL
3548 return symlink(buf, path);
3550 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
3554 if (convert_to_working_tree(path, buf, size, &nbuf)) {
3558 write_or_die(fd, buf, size);
3559 strbuf_release(&nbuf);
3562 die_errno(_("closing file '%s'"), path);
3567 * We optimistically assume that the directories exist,
3568 * which is true 99% of the time anyway. If they don't,
3569 * we create them and try again.
3571 static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
3575 if (!try_create_file(path, mode, buf, size))
3578 if (errno == ENOENT) {
3579 if (safe_create_leading_directories(path))
3581 if (!try_create_file(path, mode, buf, size))
3585 if (errno == EEXIST || errno == EACCES) {
3586 /* We may be trying to create a file where a directory
3590 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
3594 if (errno == EEXIST) {
3595 unsigned int nr = getpid();
3598 char newpath[PATH_MAX];
3599 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
3600 if (!try_create_file(newpath, mode, buf, size)) {
3601 if (!rename(newpath, path))
3603 unlink_or_warn(newpath);
3606 if (errno != EEXIST)
3611 die_errno(_("unable to write file '%s' mode %o"), path, mode);
3614 static void create_file(struct patch *patch)
3616 char *path = patch->new_name;
3617 unsigned mode = patch->new_mode;
3618 unsigned long size = patch->resultsize;
3619 char *buf = patch->result;
3622 mode = S_IFREG | 0644;
3623 create_one_file(path, mode, buf, size);
3624 add_index_file(path, mode, buf, size);
3627 /* phase zero is to remove, phase one is to create */
3628 static void write_out_one_result(struct patch *patch, int phase)
3630 if (patch->is_delete > 0) {
3632 remove_file(patch, 1);
3635 if (patch->is_new > 0 || patch->is_copy) {
3641 * Rename or modification boils down to the same
3642 * thing: remove the old, write the new
3645 remove_file(patch, patch->is_rename);
3650 static int write_out_one_reject(struct patch *patch)
3653 char namebuf[PATH_MAX];
3654 struct fragment *frag;
3656 struct strbuf sb = STRBUF_INIT;
3658 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
3659 if (!frag->rejected)
3665 if (apply_verbosely)
3666 say_patch_name(stderr,
3667 _("Applied patch %s cleanly."), patch);
3671 /* This should not happen, because a removal patch that leaves
3672 * contents are marked "rejected" at the patch level.
3674 if (!patch->new_name)
3675 die(_("internal error"));
3677 /* Say this even without --verbose */
3678 strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",
3679 "Applying patch %%s with %d rejects...",
3682 say_patch_name(stderr, sb.buf, patch);
3683 strbuf_release(&sb);
3685 cnt = strlen(patch->new_name);
3686 if (ARRAY_SIZE(namebuf) <= cnt + 5) {
3687 cnt = ARRAY_SIZE(namebuf) - 5;
3688 warning(_("truncating .rej filename to %.*s.rej"),
3689 cnt - 1, patch->new_name);
3691 memcpy(namebuf, patch->new_name, cnt);
3692 memcpy(namebuf + cnt, ".rej", 5);
3694 rej = fopen(namebuf, "w");
3696 return error(_("cannot open %s: %s"), namebuf, strerror(errno));
3698 /* Normal git tools never deal with .rej, so do not pretend
3699 * this is a git patch by saying --git nor give extended
3700 * headers. While at it, maybe please "kompare" that wants
3701 * the trailing TAB and some garbage at the end of line ;-).
3703 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
3704 patch->new_name, patch->new_name);
3705 for (cnt = 1, frag = patch->fragments;
3707 cnt++, frag = frag->next) {
3708 if (!frag->rejected) {
3709 fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);
3712 fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);
3713 fprintf(rej, "%.*s", frag->size, frag->patch);
3714 if (frag->patch[frag->size-1] != '\n')
3721 static int write_out_results(struct patch *list)
3727 for (phase = 0; phase < 2; phase++) {
3733 write_out_one_result(l, phase);
3734 if (phase == 1 && write_out_one_reject(l))
3743 static struct lock_file lock_file;
3745 static struct string_list limit_by_name;
3746 static int has_include;
3747 static void add_name_limit(const char *name, int exclude)
3749 struct string_list_item *it;
3751 it = string_list_append(&limit_by_name, name);
3752 it->util = exclude ? NULL : (void *) 1;
3755 static int use_patch(struct patch *p)
3757 const char *pathname = p->new_name ? p->new_name : p->old_name;
3760 /* Paths outside are not touched regardless of "--include" */
3761 if (0 < prefix_length) {
3762 int pathlen = strlen(pathname);
3763 if (pathlen <= prefix_length ||
3764 memcmp(prefix, pathname, prefix_length))
3768 /* See if it matches any of exclude/include rule */
3769 for (i = 0; i < limit_by_name.nr; i++) {
3770 struct string_list_item *it = &limit_by_name.items[i];
3771 if (!fnmatch(it->string, pathname, 0))
3772 return (it->util != NULL);
3776 * If we had any include, a path that does not match any rule is
3777 * not used. Otherwise, we saw bunch of exclude rules (or none)
3778 * and such a path is used.
3780 return !has_include;
3784 static void prefix_one(char **name)
3786 char *old_name = *name;
3789 *name = xstrdup(prefix_filename(prefix, prefix_length, *name));
3793 static void prefix_patches(struct patch *p)
3795 if (!prefix || p->is_toplevel_relative)
3797 for ( ; p; p = p->next) {
3798 prefix_one(&p->new_name);
3799 prefix_one(&p->old_name);
3803 #define INACCURATE_EOF (1<<0)
3804 #define RECOUNT (1<<1)
3806 static int apply_patch(int fd, const char *filename, int options)
3809 struct strbuf buf = STRBUF_INIT; /* owns the patch text */
3810 struct patch *list = NULL, **listp = &list;
3811 int skipped_patch = 0;
3813 patch_input_file = filename;
3814 read_patch_file(&buf, fd);
3816 while (offset < buf.len) {
3817 struct patch *patch;
3820 patch = xcalloc(1, sizeof(*patch));
3821 patch->inaccurate_eof = !!(options & INACCURATE_EOF);
3822 patch->recount = !!(options & RECOUNT);
3823 nr = parse_chunk(buf.buf + offset, buf.len - offset, patch);
3826 if (apply_in_reverse)
3827 reverse_patches(patch);
3829 prefix_patches(patch);
3830 if (use_patch(patch)) {
3833 listp = &patch->next;
3842 if (!list && !skipped_patch)
3843 die(_("unrecognized input"));
3845 if (whitespace_error && (ws_error_action == die_on_ws_error))
3848 update_index = check_index && apply;
3849 if (update_index && newfd < 0)
3850 newfd = hold_locked_index(&lock_file, 1);
3853 if (read_cache() < 0)
3854 die(_("unable to read index file"));
3857 if ((check || apply) &&
3858 check_patch_list(list) < 0 &&
3862 if (apply && write_out_results(list))
3866 build_fake_ancestor(list, fake_ancestor);
3869 stat_patch_list(list);
3872 numstat_patch_list(list);
3875 summary_patch_list(list);
3877 free_patch_list(list);
3878 strbuf_release(&buf);
3879 string_list_clear(&fn_table, 0);
3883 static int git_apply_config(const char *var, const char *value, void *cb)
3885 if (!strcmp(var, "apply.whitespace"))
3886 return git_config_string(&apply_default_whitespace, var, value);
3887 else if (!strcmp(var, "apply.ignorewhitespace"))
3888 return git_config_string(&apply_default_ignorewhitespace, var, value);
3889 return git_default_config(var, value, cb);
3892 static int option_parse_exclude(const struct option *opt,
3893 const char *arg, int unset)
3895 add_name_limit(arg, 1);
3899 static int option_parse_include(const struct option *opt,
3900 const char *arg, int unset)
3902 add_name_limit(arg, 0);
3907 static int option_parse_p(const struct option *opt,
3908 const char *arg, int unset)
3910 p_value = atoi(arg);
3915 static int option_parse_z(const struct option *opt,
3916 const char *arg, int unset)
3919 line_termination = '\n';
3921 line_termination = 0;
3925 static int option_parse_space_change(const struct option *opt,
3926 const char *arg, int unset)
3929 ws_ignore_action = ignore_ws_none;
3931 ws_ignore_action = ignore_ws_change;
3935 static int option_parse_whitespace(const struct option *opt,
3936 const char *arg, int unset)
3938 const char **whitespace_option = opt->value;
3940 *whitespace_option = arg;
3941 parse_whitespace_option(arg);
3945 static int option_parse_directory(const struct option *opt,
3946 const char *arg, int unset)
3948 root_len = strlen(arg);
3949 if (root_len && arg[root_len - 1] != '/') {
3951 root = new_root = xmalloc(root_len + 2);
3952 strcpy(new_root, arg);
3953 strcpy(new_root + root_len++, "/");
3959 int cmd_apply(int argc, const char **argv, const char *prefix_)
3963 int is_not_gitdir = !startup_info->have_repository;
3964 int force_apply = 0;
3966 const char *whitespace_option = NULL;
3968 struct option builtin_apply_options[] = {
3969 { OPTION_CALLBACK, 0, "exclude", NULL, N_("path"),
3970 N_("don't apply changes matching the given path"),
3971 0, option_parse_exclude },
3972 { OPTION_CALLBACK, 0, "include", NULL, N_("path"),
3973 N_("apply changes matching the given path"),
3974 0, option_parse_include },
3975 { OPTION_CALLBACK, 'p', NULL, NULL, N_("num"),
3976 N_("remove <num> leading slashes from traditional diff paths"),
3977 0, option_parse_p },
3978 OPT_BOOLEAN(0, "no-add", &no_add,
3979 N_("ignore additions made by the patch")),
3980 OPT_BOOLEAN(0, "stat", &diffstat,
3981 N_("instead of applying the patch, output diffstat for the input")),
3982 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
3983 OPT_NOOP_NOARG(0, "binary"),
3984 OPT_BOOLEAN(0, "numstat", &numstat,
3985 N_("shows number of added and deleted lines in decimal notation")),
3986 OPT_BOOLEAN(0, "summary", &summary,
3987 N_("instead of applying the patch, output a summary for the input")),
3988 OPT_BOOLEAN(0, "check", &check,
3989 N_("instead of applying the patch, see if the patch is applicable")),
3990 OPT_BOOLEAN(0, "index", &check_index,
3991 N_("make sure the patch is applicable to the current index")),
3992 OPT_BOOLEAN(0, "cached", &cached,
3993 N_("apply a patch without touching the working tree")),
3994 OPT_BOOLEAN(0, "apply", &force_apply,
3995 N_("also apply the patch (use with --stat/--summary/--check)")),
3996 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor,
3997 N_("build a temporary index based on embedded index information")),
3998 { OPTION_CALLBACK, 'z', NULL, NULL, NULL,
3999 N_("paths are separated with NUL character"),
4000 PARSE_OPT_NOARG, option_parse_z },
4001 OPT_INTEGER('C', NULL, &p_context,
4002 N_("ensure at least <n> lines of context match")),
4003 { OPTION_CALLBACK, 0, "whitespace", &whitespace_option, N_("action"),
4004 N_("detect new or modified lines that have whitespace errors"),
4005 0, option_parse_whitespace },
4006 { OPTION_CALLBACK, 0, "ignore-space-change", NULL, NULL,
4007 N_("ignore changes in whitespace when finding context"),
4008 PARSE_OPT_NOARG, option_parse_space_change },
4009 { OPTION_CALLBACK, 0, "ignore-whitespace", NULL, NULL,
4010 N_("ignore changes in whitespace when finding context"),
4011 PARSE_OPT_NOARG, option_parse_space_change },
4012 OPT_BOOLEAN('R', "reverse", &apply_in_reverse,
4013 N_("apply the patch in reverse")),
4014 OPT_BOOLEAN(0, "unidiff-zero", &unidiff_zero,
4015 N_("don't expect at least one line of context")),
4016 OPT_BOOLEAN(0, "reject", &apply_with_reject,
4017 N_("leave the rejected hunks in corresponding *.rej files")),
4018 OPT_BOOLEAN(0, "allow-overlap", &allow_overlap,
4019 N_("allow overlapping hunks")),
4020 OPT__VERBOSE(&apply_verbosely, N_("be verbose")),
4021 OPT_BIT(0, "inaccurate-eof", &options,
4022 N_("tolerate incorrectly detected missing new-line at the end of file"),
4024 OPT_BIT(0, "recount", &options,
4025 N_("do not trust the line counts in the hunk headers"),
4027 { OPTION_CALLBACK, 0, "directory", NULL, N_("root"),
4028 N_("prepend <root> to all filenames"),
4029 0, option_parse_directory },
4034 prefix_length = prefix ? strlen(prefix) : 0;
4035 git_config(git_apply_config, NULL);
4036 if (apply_default_whitespace)
4037 parse_whitespace_option(apply_default_whitespace);
4038 if (apply_default_ignorewhitespace)
4039 parse_ignorewhitespace_option(apply_default_ignorewhitespace);
4041 argc = parse_options(argc, argv, prefix, builtin_apply_options,
4044 if (apply_with_reject)
4045 apply = apply_verbosely = 1;
4046 if (!force_apply && (diffstat || numstat || summary || check || fake_ancestor))
4048 if (check_index && is_not_gitdir)
4049 die(_("--index outside a repository"));
4052 die(_("--cached outside a repository"));
4055 for (i = 0; i < argc; i++) {
4056 const char *arg = argv[i];
4059 if (!strcmp(arg, "-")) {
4060 errs |= apply_patch(0, "<stdin>", options);
4063 } else if (0 < prefix_length)
4064 arg = prefix_filename(prefix, prefix_length, arg);
4066 fd = open(arg, O_RDONLY);
4068 die_errno(_("can't open patch '%s'"), arg);
4070 set_default_whitespace_mode(whitespace_option);
4071 errs |= apply_patch(fd, arg, options);
4074 set_default_whitespace_mode(whitespace_option);
4076 errs |= apply_patch(0, "<stdin>", options);
4077 if (whitespace_error) {
4078 if (squelch_whitespace_errors &&
4079 squelch_whitespace_errors < whitespace_error) {
4081 whitespace_error - squelch_whitespace_errors;
4082 warning(Q_("squelched %d whitespace error",
4083 "squelched %d whitespace errors",
4087 if (ws_error_action == die_on_ws_error)
4088 die(Q_("%d line adds whitespace errors.",
4089 "%d lines add whitespace errors.",
4092 if (applied_after_fixing_ws && apply)
4093 warning("%d line%s applied after"
4094 " fixing whitespace errors.",
4095 applied_after_fixing_ws,
4096 applied_after_fixing_ws == 1 ? "" : "s");
4097 else if (whitespace_error)
4098 warning(Q_("%d line adds whitespace errors.",
4099 "%d lines add whitespace errors.",
4105 if (write_cache(newfd, active_cache, active_nr) ||
4106 commit_locked_index(&lock_file))
4107 die(_("Unable to write new index file"));