4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
15 #include "xdiff-interface.h"
18 #include "parse-options.h"
23 static void git_apply_config(void)
25 git_config_get_string_const("apply.whitespace", &apply_default_whitespace);
26 git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);
27 git_config(git_default_config, NULL);
30 static int parse_whitespace_option(struct apply_state *state, const char *option)
33 state->ws_error_action = warn_on_ws_error;
36 if (!strcmp(option, "warn")) {
37 state->ws_error_action = warn_on_ws_error;
40 if (!strcmp(option, "nowarn")) {
41 state->ws_error_action = nowarn_ws_error;
44 if (!strcmp(option, "error")) {
45 state->ws_error_action = die_on_ws_error;
48 if (!strcmp(option, "error-all")) {
49 state->ws_error_action = die_on_ws_error;
50 state->squelch_whitespace_errors = 0;
53 if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
54 state->ws_error_action = correct_ws_error;
57 return error(_("unrecognized whitespace option '%s'"), option);
60 static int parse_ignorewhitespace_option(struct apply_state *state,
63 if (!option || !strcmp(option, "no") ||
64 !strcmp(option, "false") || !strcmp(option, "never") ||
65 !strcmp(option, "none")) {
66 state->ws_ignore_action = ignore_ws_none;
69 if (!strcmp(option, "change")) {
70 state->ws_ignore_action = ignore_ws_change;
73 return error(_("unrecognized whitespace ignore option '%s'"), option);
76 int init_apply_state(struct apply_state *state,
78 struct lock_file *lock_file)
80 memset(state, 0, sizeof(*state));
81 state->prefix = prefix;
82 state->prefix_length = state->prefix ? strlen(state->prefix) : 0;
83 state->lock_file = lock_file;
86 state->line_termination = '\n';
88 state->p_context = UINT_MAX;
89 state->squelch_whitespace_errors = 5;
90 state->ws_error_action = warn_on_ws_error;
91 state->ws_ignore_action = ignore_ws_none;
93 string_list_init(&state->fn_table, 0);
94 string_list_init(&state->limit_by_name, 0);
95 string_list_init(&state->symlink_changes, 0);
96 strbuf_init(&state->root, 0);
99 if (apply_default_whitespace && parse_whitespace_option(state, apply_default_whitespace))
101 if (apply_default_ignorewhitespace && parse_ignorewhitespace_option(state, apply_default_ignorewhitespace))
106 void clear_apply_state(struct apply_state *state)
108 string_list_clear(&state->limit_by_name, 0);
109 string_list_clear(&state->symlink_changes, 0);
110 strbuf_release(&state->root);
112 /* &state->fn_table is cleared at the end of apply_patch() */
115 static void mute_routine(const char *msg, va_list params)
120 int check_apply_state(struct apply_state *state, int force_apply)
122 int is_not_gitdir = !startup_info->have_repository;
124 if (state->apply_with_reject && state->threeway)
125 return error(_("--reject and --3way cannot be used together."));
126 if (state->cached && state->threeway)
127 return error(_("--cached and --3way cannot be used together."));
128 if (state->threeway) {
130 return error(_("--3way outside a repository"));
131 state->check_index = 1;
133 if (state->apply_with_reject) {
135 if (state->apply_verbosity == verbosity_normal)
136 state->apply_verbosity = verbosity_verbose;
138 if (!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor))
140 if (state->check_index && is_not_gitdir)
141 return error(_("--index outside a repository"));
144 return error(_("--cached outside a repository"));
145 state->check_index = 1;
147 if (state->check_index)
148 state->unsafe_paths = 0;
149 if (!state->lock_file)
150 return error("BUG: state->lock_file should not be NULL");
152 if (state->apply_verbosity <= verbosity_silent) {
153 state->saved_error_routine = get_error_routine();
154 state->saved_warn_routine = get_warn_routine();
155 set_error_routine(mute_routine);
156 set_warn_routine(mute_routine);
162 static void set_default_whitespace_mode(struct apply_state *state)
164 if (!state->whitespace_option && !apply_default_whitespace)
165 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error);
169 * This represents one "hunk" from a patch, starting with
170 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
171 * patch text is pointed at by patch, and its byte length
172 * is stored in size. leading and trailing are the number
176 unsigned long leading, trailing;
177 unsigned long oldpos, oldlines;
178 unsigned long newpos, newlines;
180 * 'patch' is usually borrowed from buf in apply_patch(),
181 * but some codepaths store an allocated buffer.
184 unsigned free_patch:1,
188 struct fragment *next;
192 * When dealing with a binary patch, we reuse "leading" field
193 * to store the type of the binary hunk, either deflated "delta"
194 * or deflated "literal".
196 #define binary_patch_method leading
197 #define BINARY_DELTA_DEFLATED 1
198 #define BINARY_LITERAL_DEFLATED 2
201 * This represents a "patch" to a file, both metainfo changes
202 * such as creation/deletion, filemode and content changes represented
203 * as a series of fragments.
206 char *new_name, *old_name, *def_name;
207 unsigned int old_mode, new_mode;
208 int is_new, is_delete; /* -1 = unknown, 0 = false, 1 = true */
211 int lines_added, lines_deleted;
213 int extension_linenr; /* first line specifying delete/new/rename/copy */
214 unsigned int is_toplevel_relative:1;
215 unsigned int inaccurate_eof:1;
216 unsigned int is_binary:1;
217 unsigned int is_copy:1;
218 unsigned int is_rename:1;
219 unsigned int recount:1;
220 unsigned int conflicted_threeway:1;
221 unsigned int direct_to_threeway:1;
222 struct fragment *fragments;
225 char old_sha1_prefix[41];
226 char new_sha1_prefix[41];
229 /* three-way fallback result */
230 struct object_id threeway_stage[3];
233 static void free_fragment_list(struct fragment *list)
236 struct fragment *next = list->next;
237 if (list->free_patch)
238 free((char *)list->patch);
244 static void free_patch(struct patch *patch)
246 free_fragment_list(patch->fragments);
247 free(patch->def_name);
248 free(patch->old_name);
249 free(patch->new_name);
254 static void free_patch_list(struct patch *list)
257 struct patch *next = list->next;
264 * A line in a file, len-bytes long (includes the terminating LF,
265 * except for an incomplete line at the end if the file ends with
266 * one), and its contents hashes to 'hash'.
272 #define LINE_COMMON 1
273 #define LINE_PATCHED 2
277 * This represents a "file", which is an array of "lines".
284 struct line *line_allocated;
288 static uint32_t hash_line(const char *cp, size_t len)
292 for (i = 0, h = 0; i < len; i++) {
293 if (!isspace(cp[i])) {
294 h = h * 3 + (cp[i] & 0xff);
301 * Compare lines s1 of length n1 and s2 of length n2, ignoring
302 * whitespace difference. Returns 1 if they match, 0 otherwise
304 static int fuzzy_matchlines(const char *s1, size_t n1,
305 const char *s2, size_t n2)
307 const char *last1 = s1 + n1 - 1;
308 const char *last2 = s2 + n2 - 1;
311 /* ignore line endings */
312 while ((*last1 == '\r') || (*last1 == '\n'))
314 while ((*last2 == '\r') || (*last2 == '\n'))
317 /* skip leading whitespaces, if both begin with whitespace */
318 if (s1 <= last1 && s2 <= last2 && isspace(*s1) && isspace(*s2)) {
319 while (isspace(*s1) && (s1 <= last1))
321 while (isspace(*s2) && (s2 <= last2))
324 /* early return if both lines are empty */
325 if ((s1 > last1) && (s2 > last2))
328 result = *s1++ - *s2++;
330 * Skip whitespace inside. We check for whitespace on
331 * both buffers because we don't want "a b" to match
334 if (isspace(*s1) && isspace(*s2)) {
335 while (isspace(*s1) && s1 <= last1)
337 while (isspace(*s2) && s2 <= last2)
341 * If we reached the end on one side only,
345 ((s2 > last2) && (s1 <= last1)) ||
346 ((s1 > last1) && (s2 <= last2)))
348 if ((s1 > last1) && (s2 > last2))
355 static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
357 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
358 img->line_allocated[img->nr].len = len;
359 img->line_allocated[img->nr].hash = hash_line(bol, len);
360 img->line_allocated[img->nr].flag = flag;
365 * "buf" has the file contents to be patched (read from various sources).
366 * attach it to "image" and add line-based index to it.
367 * "image" now owns the "buf".
369 static void prepare_image(struct image *image, char *buf, size_t len,
370 int prepare_linetable)
374 memset(image, 0, sizeof(*image));
378 if (!prepare_linetable)
381 ep = image->buf + image->len;
385 for (next = cp; next < ep && *next != '\n'; next++)
389 add_line_info(image, cp, next - cp, 0);
392 image->line = image->line_allocated;
395 static void clear_image(struct image *image)
398 free(image->line_allocated);
399 memset(image, 0, sizeof(*image));
402 /* fmt must contain _one_ %s and no other substitution */
403 static void say_patch_name(FILE *output, const char *fmt, struct patch *patch)
405 struct strbuf sb = STRBUF_INIT;
407 if (patch->old_name && patch->new_name &&
408 strcmp(patch->old_name, patch->new_name)) {
409 quote_c_style(patch->old_name, &sb, NULL, 0);
410 strbuf_addstr(&sb, " => ");
411 quote_c_style(patch->new_name, &sb, NULL, 0);
413 const char *n = patch->new_name;
416 quote_c_style(n, &sb, NULL, 0);
418 fprintf(output, fmt, sb.buf);
425 static int read_patch_file(struct strbuf *sb, int fd)
427 if (strbuf_read(sb, fd, 0) < 0)
428 return error_errno("git apply: failed to read");
431 * Make sure that we have some slop in the buffer
432 * so that we can do speculative "memcmp" etc, and
433 * see to it that it is NUL-filled.
435 strbuf_grow(sb, SLOP);
436 memset(sb->buf + sb->len, 0, SLOP);
440 static unsigned long linelen(const char *buffer, unsigned long size)
442 unsigned long len = 0;
445 if (*buffer++ == '\n')
451 static int is_dev_null(const char *str)
453 return skip_prefix(str, "/dev/null", &str) && isspace(*str);
459 static int name_terminate(int c, int terminate)
461 if (c == ' ' && !(terminate & TERM_SPACE))
463 if (c == '\t' && !(terminate & TERM_TAB))
469 /* remove double slashes to make --index work with such filenames */
470 static char *squash_slash(char *name)
478 if ((name[j++] = name[i++]) == '/')
479 while (name[i] == '/')
486 static char *find_name_gnu(struct apply_state *state,
491 struct strbuf name = STRBUF_INIT;
495 * Proposed "new-style" GNU patch/diff format; see
496 * http://marc.info/?l=git&m=112927316408690&w=2
498 if (unquote_c_style(&name, line, NULL)) {
499 strbuf_release(&name);
503 for (cp = name.buf; p_value; p_value--) {
504 cp = strchr(cp, '/');
506 strbuf_release(&name);
512 strbuf_remove(&name, 0, cp - name.buf);
514 strbuf_insert(&name, 0, state->root.buf, state->root.len);
515 return squash_slash(strbuf_detach(&name, NULL));
518 static size_t sane_tz_len(const char *line, size_t len)
522 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
524 tz = line + len - strlen(" +0500");
526 if (tz[1] != '+' && tz[1] != '-')
529 for (p = tz + 2; p != line + len; p++)
533 return line + len - tz;
536 static size_t tz_with_colon_len(const char *line, size_t len)
540 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
542 tz = line + len - strlen(" +08:00");
544 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
547 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
548 !isdigit(*p++) || !isdigit(*p++))
551 return line + len - tz;
554 static size_t date_len(const char *line, size_t len)
556 const char *date, *p;
558 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
560 p = date = line + len - strlen("72-02-05");
562 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
563 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
564 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */
567 if (date - line >= strlen("19") &&
568 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */
569 date -= strlen("19");
571 return line + len - date;
574 static size_t short_time_len(const char *line, size_t len)
576 const char *time, *p;
578 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
580 p = time = line + len - strlen(" 07:01:32");
582 /* Permit 1-digit hours? */
584 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
585 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
586 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */
589 return line + len - time;
592 static size_t fractional_time_len(const char *line, size_t len)
597 /* Expected format: 19:41:17.620000023 */
598 if (!len || !isdigit(line[len - 1]))
602 /* Fractional seconds. */
603 while (p > line && isdigit(*p))
608 /* Hours, minutes, and whole seconds. */
609 n = short_time_len(line, p - line);
613 return line + len - p + n;
616 static size_t trailing_spaces_len(const char *line, size_t len)
620 /* Expected format: ' ' x (1 or more) */
621 if (!len || line[len - 1] != ' ')
628 return line + len - (p + 1);
635 static size_t diff_timestamp_len(const char *line, size_t len)
637 const char *end = line + len;
641 * Posix: 2010-07-05 19:41:17
642 * GNU: 2010-07-05 19:41:17.620000023 -0500
645 if (!isdigit(end[-1]))
648 n = sane_tz_len(line, end - line);
650 n = tz_with_colon_len(line, end - line);
653 n = short_time_len(line, end - line);
655 n = fractional_time_len(line, end - line);
658 n = date_len(line, end - line);
659 if (!n) /* No date. Too bad. */
663 if (end == line) /* No space before date. */
665 if (end[-1] == '\t') { /* Success! */
667 return line + len - end;
669 if (end[-1] != ' ') /* No space before date. */
672 /* Whitespace damage. */
673 end -= trailing_spaces_len(line, end - line);
674 return line + len - end;
677 static char *find_name_common(struct apply_state *state,
685 const char *start = NULL;
689 while (line != end) {
692 if (!end && isspace(c)) {
695 if (name_terminate(c, terminate))
699 if (c == '/' && !--p_value)
703 return squash_slash(xstrdup_or_null(def));
706 return squash_slash(xstrdup_or_null(def));
709 * Generally we prefer the shorter name, especially
710 * if the other one is just a variation of that with
711 * something else tacked on to the end (ie "file.orig"
715 int deflen = strlen(def);
716 if (deflen < len && !strncmp(start, def, deflen))
717 return squash_slash(xstrdup(def));
720 if (state->root.len) {
721 char *ret = xstrfmt("%s%.*s", state->root.buf, len, start);
722 return squash_slash(ret);
725 return squash_slash(xmemdupz(start, len));
728 static char *find_name(struct apply_state *state,
735 char *name = find_name_gnu(state, line, def, p_value);
740 return find_name_common(state, line, def, p_value, NULL, terminate);
743 static char *find_name_traditional(struct apply_state *state,
752 char *name = find_name_gnu(state, line, def, p_value);
757 len = strchrnul(line, '\n') - line;
758 date_len = diff_timestamp_len(line, len);
760 return find_name_common(state, line, def, p_value, NULL, TERM_TAB);
763 return find_name_common(state, line, def, p_value, line + len, 0);
766 static int count_slashes(const char *cp)
778 * Given the string after "--- " or "+++ ", guess the appropriate
779 * p_value for the given patch.
781 static int guess_p_value(struct apply_state *state, const char *nameline)
786 if (is_dev_null(nameline))
788 name = find_name_traditional(state, nameline, NULL, 0);
791 cp = strchr(name, '/');
794 else if (state->prefix) {
796 * Does it begin with "a/$our-prefix" and such? Then this is
797 * very likely to apply to our directory.
799 if (!strncmp(name, state->prefix, state->prefix_length))
800 val = count_slashes(state->prefix);
803 if (!strncmp(cp, state->prefix, state->prefix_length))
804 val = count_slashes(state->prefix) + 1;
812 * Does the ---/+++ line have the POSIX timestamp after the last HT?
813 * GNU diff puts epoch there to signal a creation/deletion event. Is
814 * this such a timestamp?
816 static int has_epoch_timestamp(const char *nameline)
819 * We are only interested in epoch timestamp; any non-zero
820 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
821 * For the same reason, the date must be either 1969-12-31 or
822 * 1970-01-01, and the seconds part must be "00".
824 const char stamp_regexp[] =
825 "^(1969-12-31|1970-01-01)"
827 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
829 "([-+][0-2][0-9]:?[0-5][0-9])\n";
830 const char *timestamp = NULL, *cp, *colon;
831 static regex_t *stamp;
837 for (cp = nameline; *cp != '\n'; cp++) {
844 stamp = xmalloc(sizeof(*stamp));
845 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
846 warning(_("Cannot prepare timestamp regexp %s"),
852 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
854 if (status != REG_NOMATCH)
855 warning(_("regexec returned %d for input: %s"),
860 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
862 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
864 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
865 if (timestamp[m[3].rm_so] == '-')
866 zoneoffset = -zoneoffset;
869 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
870 * (west of GMT) or 1970-01-01 (east of GMT)
872 if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) ||
873 (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10)))
876 hourminute = (strtol(timestamp + 11, NULL, 10) * 60 +
877 strtol(timestamp + 14, NULL, 10) -
880 return ((zoneoffset < 0 && hourminute == 1440) ||
881 (0 <= zoneoffset && !hourminute));
885 * Get the name etc info from the ---/+++ lines of a traditional patch header
887 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
888 * files, we can happily check the index for a match, but for creating a
889 * new file we should try to match whatever "patch" does. I have no idea.
891 static int parse_traditional_patch(struct apply_state *state,
898 first += 4; /* skip "--- " */
899 second += 4; /* skip "+++ " */
900 if (!state->p_value_known) {
902 p = guess_p_value(state, first);
903 q = guess_p_value(state, second);
905 if (0 <= p && p == q) {
907 state->p_value_known = 1;
910 if (is_dev_null(first)) {
912 patch->is_delete = 0;
913 name = find_name_traditional(state, second, NULL, state->p_value);
914 patch->new_name = name;
915 } else if (is_dev_null(second)) {
917 patch->is_delete = 1;
918 name = find_name_traditional(state, first, NULL, state->p_value);
919 patch->old_name = name;
922 first_name = find_name_traditional(state, first, NULL, state->p_value);
923 name = find_name_traditional(state, second, first_name, state->p_value);
925 if (has_epoch_timestamp(first)) {
927 patch->is_delete = 0;
928 patch->new_name = name;
929 } else if (has_epoch_timestamp(second)) {
931 patch->is_delete = 1;
932 patch->old_name = name;
934 patch->old_name = name;
935 patch->new_name = xstrdup_or_null(name);
939 return error(_("unable to find filename in patch at line %d"), state->linenr);
944 static int gitdiff_hdrend(struct apply_state *state,
952 * We're anal about diff header consistency, to make
953 * sure that we don't end up having strange ambiguous
954 * patches floating around.
956 * As a result, gitdiff_{old|new}name() will check
957 * their names against any previous information, just
960 #define DIFF_OLD_NAME 0
961 #define DIFF_NEW_NAME 1
963 static int gitdiff_verify_name(struct apply_state *state,
969 if (!*name && !isnull) {
970 *name = find_name(state, line, NULL, state->p_value, TERM_TAB);
977 return error(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
978 *name, state->linenr);
979 another = find_name(state, line, NULL, state->p_value, TERM_TAB);
980 if (!another || strcmp(another, *name)) {
982 return error((side == DIFF_NEW_NAME) ?
983 _("git apply: bad git-diff - inconsistent new filename on line %d") :
984 _("git apply: bad git-diff - inconsistent old filename on line %d"), state->linenr);
988 if (!starts_with(line, "/dev/null\n"))
989 return error(_("git apply: bad git-diff - expected /dev/null on line %d"), state->linenr);
995 static int gitdiff_oldname(struct apply_state *state,
999 return gitdiff_verify_name(state, line,
1000 patch->is_new, &patch->old_name,
1004 static int gitdiff_newname(struct apply_state *state,
1006 struct patch *patch)
1008 return gitdiff_verify_name(state, line,
1009 patch->is_delete, &patch->new_name,
1013 static int parse_mode_line(const char *line, int linenr, unsigned int *mode)
1016 *mode = strtoul(line, &end, 8);
1017 if (end == line || !isspace(*end))
1018 return error(_("invalid mode on line %d: %s"), linenr, line);
1022 static int gitdiff_oldmode(struct apply_state *state,
1024 struct patch *patch)
1026 return parse_mode_line(line, state->linenr, &patch->old_mode);
1029 static int gitdiff_newmode(struct apply_state *state,
1031 struct patch *patch)
1033 return parse_mode_line(line, state->linenr, &patch->new_mode);
1036 static int gitdiff_delete(struct apply_state *state,
1038 struct patch *patch)
1040 patch->is_delete = 1;
1041 free(patch->old_name);
1042 patch->old_name = xstrdup_or_null(patch->def_name);
1043 return gitdiff_oldmode(state, line, patch);
1046 static int gitdiff_newfile(struct apply_state *state,
1048 struct patch *patch)
1051 free(patch->new_name);
1052 patch->new_name = xstrdup_or_null(patch->def_name);
1053 return gitdiff_newmode(state, line, patch);
1056 static int gitdiff_copysrc(struct apply_state *state,
1058 struct patch *patch)
1061 free(patch->old_name);
1062 patch->old_name = find_name(state, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1066 static int gitdiff_copydst(struct apply_state *state,
1068 struct patch *patch)
1071 free(patch->new_name);
1072 patch->new_name = find_name(state, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1076 static int gitdiff_renamesrc(struct apply_state *state,
1078 struct patch *patch)
1080 patch->is_rename = 1;
1081 free(patch->old_name);
1082 patch->old_name = find_name(state, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1086 static int gitdiff_renamedst(struct apply_state *state,
1088 struct patch *patch)
1090 patch->is_rename = 1;
1091 free(patch->new_name);
1092 patch->new_name = find_name(state, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1096 static int gitdiff_similarity(struct apply_state *state,
1098 struct patch *patch)
1100 unsigned long val = strtoul(line, NULL, 10);
1106 static int gitdiff_dissimilarity(struct apply_state *state,
1108 struct patch *patch)
1110 unsigned long val = strtoul(line, NULL, 10);
1116 static int gitdiff_index(struct apply_state *state,
1118 struct patch *patch)
1121 * index line is N hexadecimal, "..", N hexadecimal,
1122 * and optional space with octal mode.
1124 const char *ptr, *eol;
1127 ptr = strchr(line, '.');
1128 if (!ptr || ptr[1] != '.' || 40 < ptr - line)
1131 memcpy(patch->old_sha1_prefix, line, len);
1132 patch->old_sha1_prefix[len] = 0;
1135 ptr = strchr(line, ' ');
1136 eol = strchrnul(line, '\n');
1138 if (!ptr || eol < ptr)
1144 memcpy(patch->new_sha1_prefix, line, len);
1145 patch->new_sha1_prefix[len] = 0;
1147 return gitdiff_oldmode(state, ptr + 1, patch);
1152 * This is normal for a diff that doesn't change anything: we'll fall through
1153 * into the next diff. Tell the parser to break out.
1155 static int gitdiff_unrecognized(struct apply_state *state,
1157 struct patch *patch)
1163 * Skip p_value leading components from "line"; as we do not accept
1164 * absolute paths, return NULL in that case.
1166 static const char *skip_tree_prefix(struct apply_state *state,
1173 if (!state->p_value)
1174 return (llen && line[0] == '/') ? NULL : line;
1176 nslash = state->p_value;
1177 for (i = 0; i < llen; i++) {
1179 if (ch == '/' && --nslash <= 0)
1180 return (i == 0) ? NULL : &line[i + 1];
1186 * This is to extract the same name that appears on "diff --git"
1187 * line. We do not find and return anything if it is a rename
1188 * patch, and it is OK because we will find the name elsewhere.
1189 * We need to reliably find name only when it is mode-change only,
1190 * creation or deletion of an empty file. In any of these cases,
1191 * both sides are the same name under a/ and b/ respectively.
1193 static char *git_header_name(struct apply_state *state,
1198 const char *second = NULL;
1199 size_t len, line_len;
1201 line += strlen("diff --git ");
1202 llen -= strlen("diff --git ");
1206 struct strbuf first = STRBUF_INIT;
1207 struct strbuf sp = STRBUF_INIT;
1209 if (unquote_c_style(&first, line, &second))
1210 goto free_and_fail1;
1212 /* strip the a/b prefix including trailing slash */
1213 cp = skip_tree_prefix(state, first.buf, first.len);
1215 goto free_and_fail1;
1216 strbuf_remove(&first, 0, cp - first.buf);
1219 * second points at one past closing dq of name.
1220 * find the second name.
1222 while ((second < line + llen) && isspace(*second))
1225 if (line + llen <= second)
1226 goto free_and_fail1;
1227 if (*second == '"') {
1228 if (unquote_c_style(&sp, second, NULL))
1229 goto free_and_fail1;
1230 cp = skip_tree_prefix(state, sp.buf, sp.len);
1232 goto free_and_fail1;
1233 /* They must match, otherwise ignore */
1234 if (strcmp(cp, first.buf))
1235 goto free_and_fail1;
1236 strbuf_release(&sp);
1237 return strbuf_detach(&first, NULL);
1240 /* unquoted second */
1241 cp = skip_tree_prefix(state, second, line + llen - second);
1243 goto free_and_fail1;
1244 if (line + llen - cp != first.len ||
1245 memcmp(first.buf, cp, first.len))
1246 goto free_and_fail1;
1247 return strbuf_detach(&first, NULL);
1250 strbuf_release(&first);
1251 strbuf_release(&sp);
1255 /* unquoted first name */
1256 name = skip_tree_prefix(state, line, llen);
1261 * since the first name is unquoted, a dq if exists must be
1262 * the beginning of the second name.
1264 for (second = name; second < line + llen; second++) {
1265 if (*second == '"') {
1266 struct strbuf sp = STRBUF_INIT;
1269 if (unquote_c_style(&sp, second, NULL))
1270 goto free_and_fail2;
1272 np = skip_tree_prefix(state, sp.buf, sp.len);
1274 goto free_and_fail2;
1276 len = sp.buf + sp.len - np;
1277 if (len < second - name &&
1278 !strncmp(np, name, len) &&
1279 isspace(name[len])) {
1281 strbuf_remove(&sp, 0, np - sp.buf);
1282 return strbuf_detach(&sp, NULL);
1286 strbuf_release(&sp);
1292 * Accept a name only if it shows up twice, exactly the same
1295 second = strchr(name, '\n');
1298 line_len = second - name;
1299 for (len = 0 ; ; len++) {
1300 switch (name[len]) {
1305 case '\t': case ' ':
1307 * Is this the separator between the preimage
1308 * and the postimage pathname? Again, we are
1309 * only interested in the case where there is
1310 * no rename, as this is only to set def_name
1311 * and a rename patch has the names elsewhere
1312 * in an unambiguous form.
1315 return NULL; /* no postimage name */
1316 second = skip_tree_prefix(state, name + len + 1,
1317 line_len - (len + 1));
1321 * Does len bytes starting at "name" and "second"
1322 * (that are separated by one HT or SP we just
1323 * found) exactly match?
1325 if (second[len] == '\n' && !strncmp(name, second, len))
1326 return xmemdupz(name, len);
1331 static int check_header_line(struct apply_state *state, struct patch *patch)
1333 int extensions = (patch->is_delete == 1) + (patch->is_new == 1) +
1334 (patch->is_rename == 1) + (patch->is_copy == 1);
1336 return error(_("inconsistent header lines %d and %d"),
1337 patch->extension_linenr, state->linenr);
1338 if (extensions && !patch->extension_linenr)
1339 patch->extension_linenr = state->linenr;
1343 /* Verify that we recognize the lines following a git header */
1344 static int parse_git_header(struct apply_state *state,
1348 struct patch *patch)
1350 unsigned long offset;
1352 /* A git diff has explicit new/delete information, so we don't guess */
1354 patch->is_delete = 0;
1357 * Some things may not have the old name in the
1358 * rest of the headers anywhere (pure mode changes,
1359 * or removing or adding empty files), so we get
1360 * the default name from the header.
1362 patch->def_name = git_header_name(state, line, len);
1363 if (patch->def_name && state->root.len) {
1364 char *s = xstrfmt("%s%s", state->root.buf, patch->def_name);
1365 free(patch->def_name);
1366 patch->def_name = s;
1372 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, state->linenr++) {
1373 static const struct opentry {
1375 int (*fn)(struct apply_state *, const char *, struct patch *);
1377 { "@@ -", gitdiff_hdrend },
1378 { "--- ", gitdiff_oldname },
1379 { "+++ ", gitdiff_newname },
1380 { "old mode ", gitdiff_oldmode },
1381 { "new mode ", gitdiff_newmode },
1382 { "deleted file mode ", gitdiff_delete },
1383 { "new file mode ", gitdiff_newfile },
1384 { "copy from ", gitdiff_copysrc },
1385 { "copy to ", gitdiff_copydst },
1386 { "rename old ", gitdiff_renamesrc },
1387 { "rename new ", gitdiff_renamedst },
1388 { "rename from ", gitdiff_renamesrc },
1389 { "rename to ", gitdiff_renamedst },
1390 { "similarity index ", gitdiff_similarity },
1391 { "dissimilarity index ", gitdiff_dissimilarity },
1392 { "index ", gitdiff_index },
1393 { "", gitdiff_unrecognized },
1397 len = linelen(line, size);
1398 if (!len || line[len-1] != '\n')
1400 for (i = 0; i < ARRAY_SIZE(optable); i++) {
1401 const struct opentry *p = optable + i;
1402 int oplen = strlen(p->str);
1404 if (len < oplen || memcmp(p->str, line, oplen))
1406 res = p->fn(state, line + oplen, patch);
1409 if (check_header_line(state, patch))
1420 static int parse_num(const char *line, unsigned long *p)
1424 if (!isdigit(*line))
1426 *p = strtoul(line, &ptr, 10);
1430 static int parse_range(const char *line, int len, int offset, const char *expect,
1431 unsigned long *p1, unsigned long *p2)
1435 if (offset < 0 || offset >= len)
1440 digits = parse_num(line, p1);
1450 digits = parse_num(line+1, p2);
1459 ex = strlen(expect);
1462 if (memcmp(line, expect, ex))
1468 static void recount_diff(const char *line, int size, struct fragment *fragment)
1470 int oldlines = 0, newlines = 0, ret = 0;
1473 warning("recount: ignore empty hunk");
1478 int len = linelen(line, size);
1486 case ' ': case '\n':
1498 ret = size < 3 || !starts_with(line, "@@ ");
1501 ret = size < 5 || !starts_with(line, "diff ");
1508 warning(_("recount: unexpected line: %.*s"),
1509 (int)linelen(line, size), line);
1514 fragment->oldlines = oldlines;
1515 fragment->newlines = newlines;
1519 * Parse a unified diff fragment header of the
1520 * form "@@ -a,b +c,d @@"
1522 static int parse_fragment_header(const char *line, int len, struct fragment *fragment)
1526 if (!len || line[len-1] != '\n')
1529 /* Figure out the number of lines in a fragment */
1530 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1531 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1537 * Find file diff header
1540 * -1 if no header was found
1541 * -128 in case of error
1542 * the size of the header in bytes (called "offset") otherwise
1544 static int find_header(struct apply_state *state,
1548 struct patch *patch)
1550 unsigned long offset, len;
1552 patch->is_toplevel_relative = 0;
1553 patch->is_rename = patch->is_copy = 0;
1554 patch->is_new = patch->is_delete = -1;
1555 patch->old_mode = patch->new_mode = 0;
1556 patch->old_name = patch->new_name = NULL;
1557 for (offset = 0; size > 0; offset += len, size -= len, line += len, state->linenr++) {
1558 unsigned long nextlen;
1560 len = linelen(line, size);
1564 /* Testing this early allows us to take a few shortcuts.. */
1569 * Make sure we don't find any unconnected patch fragments.
1570 * That's a sign that we didn't find a header, and that a
1571 * patch has become corrupted/broken up.
1573 if (!memcmp("@@ -", line, 4)) {
1574 struct fragment dummy;
1575 if (parse_fragment_header(line, len, &dummy) < 0)
1577 error(_("patch fragment without header at line %d: %.*s"),
1578 state->linenr, (int)len-1, line);
1586 * Git patch? It might not have a real patch, just a rename
1587 * or mode change, so we handle that specially
1589 if (!memcmp("diff --git ", line, 11)) {
1590 int git_hdr_len = parse_git_header(state, line, len, size, patch);
1591 if (git_hdr_len < 0)
1593 if (git_hdr_len <= len)
1595 if (!patch->old_name && !patch->new_name) {
1596 if (!patch->def_name) {
1597 error(Q_("git diff header lacks filename information when removing "
1598 "%d leading pathname component (line %d)",
1599 "git diff header lacks filename information when removing "
1600 "%d leading pathname components (line %d)",
1602 state->p_value, state->linenr);
1605 patch->old_name = xstrdup(patch->def_name);
1606 patch->new_name = xstrdup(patch->def_name);
1608 if ((!patch->new_name && !patch->is_delete) ||
1609 (!patch->old_name && !patch->is_new)) {
1610 error(_("git diff header lacks filename information "
1611 "(line %d)"), state->linenr);
1614 patch->is_toplevel_relative = 1;
1615 *hdrsize = git_hdr_len;
1619 /* --- followed by +++ ? */
1620 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1624 * We only accept unified patches, so we want it to
1625 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1626 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1628 nextlen = linelen(line + len, size - len);
1629 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1632 /* Ok, we'll consider it a patch */
1633 if (parse_traditional_patch(state, line, line+len, patch))
1635 *hdrsize = len + nextlen;
1642 static void record_ws_error(struct apply_state *state,
1653 state->whitespace_error++;
1654 if (state->squelch_whitespace_errors &&
1655 state->squelch_whitespace_errors < state->whitespace_error)
1658 err = whitespace_error_string(result);
1659 if (state->apply_verbosity > verbosity_silent)
1660 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1661 state->patch_input_file, linenr, err, len, line);
1665 static void check_whitespace(struct apply_state *state,
1670 unsigned result = ws_check(line + 1, len - 1, ws_rule);
1672 record_ws_error(state, result, line + 1, len - 2, state->linenr);
1676 * Parse a unified diff. Note that this really needs to parse each
1677 * fragment separately, since the only way to know the difference
1678 * between a "---" that is part of a patch, and a "---" that starts
1679 * the next patch is to look at the line counts..
1681 static int parse_fragment(struct apply_state *state,
1684 struct patch *patch,
1685 struct fragment *fragment)
1688 int len = linelen(line, size), offset;
1689 unsigned long oldlines, newlines;
1690 unsigned long leading, trailing;
1692 offset = parse_fragment_header(line, len, fragment);
1695 if (offset > 0 && patch->recount)
1696 recount_diff(line + offset, size - offset, fragment);
1697 oldlines = fragment->oldlines;
1698 newlines = fragment->newlines;
1702 /* Parse the thing.. */
1706 added = deleted = 0;
1709 offset += len, size -= len, line += len, state->linenr++) {
1710 if (!oldlines && !newlines)
1712 len = linelen(line, size);
1713 if (!len || line[len-1] != '\n')
1718 case '\n': /* newer GNU diff, an empty context line */
1722 if (!deleted && !added)
1725 if (!state->apply_in_reverse &&
1726 state->ws_error_action == correct_ws_error)
1727 check_whitespace(state, line, len, patch->ws_rule);
1730 if (state->apply_in_reverse &&
1731 state->ws_error_action != nowarn_ws_error)
1732 check_whitespace(state, line, len, patch->ws_rule);
1738 if (!state->apply_in_reverse &&
1739 state->ws_error_action != nowarn_ws_error)
1740 check_whitespace(state, line, len, patch->ws_rule);
1747 * We allow "\ No newline at end of file". Depending
1748 * on locale settings when the patch was produced we
1749 * don't know what this line looks like. The only
1750 * thing we do know is that it begins with "\ ".
1751 * Checking for 12 is just for sanity check -- any
1752 * l10n of "\ No newline..." is at least that long.
1755 if (len < 12 || memcmp(line, "\\ ", 2))
1760 if (oldlines || newlines)
1762 if (!deleted && !added)
1765 fragment->leading = leading;
1766 fragment->trailing = trailing;
1769 * If a fragment ends with an incomplete line, we failed to include
1770 * it in the above loop because we hit oldlines == newlines == 0
1773 if (12 < size && !memcmp(line, "\\ ", 2))
1774 offset += linelen(line, size);
1776 patch->lines_added += added;
1777 patch->lines_deleted += deleted;
1779 if (0 < patch->is_new && oldlines)
1780 return error(_("new file depends on old contents"));
1781 if (0 < patch->is_delete && newlines)
1782 return error(_("deleted file still has contents"));
1787 * We have seen "diff --git a/... b/..." header (or a traditional patch
1788 * header). Read hunks that belong to this patch into fragments and hang
1789 * them to the given patch structure.
1791 * The (fragment->patch, fragment->size) pair points into the memory given
1792 * by the caller, not a copy, when we return.
1795 * -1 in case of error,
1796 * the number of bytes in the patch otherwise.
1798 static int parse_single_patch(struct apply_state *state,
1801 struct patch *patch)
1803 unsigned long offset = 0;
1804 unsigned long oldlines = 0, newlines = 0, context = 0;
1805 struct fragment **fragp = &patch->fragments;
1807 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1808 struct fragment *fragment;
1811 fragment = xcalloc(1, sizeof(*fragment));
1812 fragment->linenr = state->linenr;
1813 len = parse_fragment(state, line, size, patch, fragment);
1816 return error(_("corrupt patch at line %d"), state->linenr);
1818 fragment->patch = line;
1819 fragment->size = len;
1820 oldlines += fragment->oldlines;
1821 newlines += fragment->newlines;
1822 context += fragment->leading + fragment->trailing;
1825 fragp = &fragment->next;
1833 * If something was removed (i.e. we have old-lines) it cannot
1834 * be creation, and if something was added it cannot be
1835 * deletion. However, the reverse is not true; --unified=0
1836 * patches that only add are not necessarily creation even
1837 * though they do not have any old lines, and ones that only
1838 * delete are not necessarily deletion.
1840 * Unfortunately, a real creation/deletion patch do _not_ have
1841 * any context line by definition, so we cannot safely tell it
1842 * apart with --unified=0 insanity. At least if the patch has
1843 * more than one hunk it is not creation or deletion.
1845 if (patch->is_new < 0 &&
1846 (oldlines || (patch->fragments && patch->fragments->next)))
1848 if (patch->is_delete < 0 &&
1849 (newlines || (patch->fragments && patch->fragments->next)))
1850 patch->is_delete = 0;
1852 if (0 < patch->is_new && oldlines)
1853 return error(_("new file %s depends on old contents"), patch->new_name);
1854 if (0 < patch->is_delete && newlines)
1855 return error(_("deleted file %s still has contents"), patch->old_name);
1856 if (!patch->is_delete && !newlines && context && state->apply_verbosity > verbosity_silent)
1859 "file %s becomes empty but is not deleted"),
1865 static inline int metadata_changes(struct patch *patch)
1867 return patch->is_rename > 0 ||
1868 patch->is_copy > 0 ||
1869 patch->is_new > 0 ||
1871 (patch->old_mode && patch->new_mode &&
1872 patch->old_mode != patch->new_mode);
1875 static char *inflate_it(const void *data, unsigned long size,
1876 unsigned long inflated_size)
1882 memset(&stream, 0, sizeof(stream));
1884 stream.next_in = (unsigned char *)data;
1885 stream.avail_in = size;
1886 stream.next_out = out = xmalloc(inflated_size);
1887 stream.avail_out = inflated_size;
1888 git_inflate_init(&stream);
1889 st = git_inflate(&stream, Z_FINISH);
1890 git_inflate_end(&stream);
1891 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1899 * Read a binary hunk and return a new fragment; fragment->patch
1900 * points at an allocated memory that the caller must free, so
1901 * it is marked as "->free_patch = 1".
1903 static struct fragment *parse_binary_hunk(struct apply_state *state,
1905 unsigned long *sz_p,
1910 * Expect a line that begins with binary patch method ("literal"
1911 * or "delta"), followed by the length of data before deflating.
1912 * a sequence of 'length-byte' followed by base-85 encoded data
1913 * should follow, terminated by a newline.
1915 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1916 * and we would limit the patch line to 66 characters,
1917 * so one line can fit up to 13 groups that would decode
1918 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1919 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1922 unsigned long size = *sz_p;
1923 char *buffer = *buf_p;
1925 unsigned long origlen;
1928 struct fragment *frag;
1930 llen = linelen(buffer, size);
1935 if (starts_with(buffer, "delta ")) {
1936 patch_method = BINARY_DELTA_DEFLATED;
1937 origlen = strtoul(buffer + 6, NULL, 10);
1939 else if (starts_with(buffer, "literal ")) {
1940 patch_method = BINARY_LITERAL_DEFLATED;
1941 origlen = strtoul(buffer + 8, NULL, 10);
1949 int byte_length, max_byte_length, newsize;
1950 llen = linelen(buffer, size);
1954 /* consume the blank line */
1960 * Minimum line is "A00000\n" which is 7-byte long,
1961 * and the line length must be multiple of 5 plus 2.
1963 if ((llen < 7) || (llen-2) % 5)
1965 max_byte_length = (llen - 2) / 5 * 4;
1966 byte_length = *buffer;
1967 if ('A' <= byte_length && byte_length <= 'Z')
1968 byte_length = byte_length - 'A' + 1;
1969 else if ('a' <= byte_length && byte_length <= 'z')
1970 byte_length = byte_length - 'a' + 27;
1973 /* if the input length was not multiple of 4, we would
1974 * have filler at the end but the filler should never
1977 if (max_byte_length < byte_length ||
1978 byte_length <= max_byte_length - 4)
1980 newsize = hunk_size + byte_length;
1981 data = xrealloc(data, newsize);
1982 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1984 hunk_size = newsize;
1989 frag = xcalloc(1, sizeof(*frag));
1990 frag->patch = inflate_it(data, hunk_size, origlen);
1991 frag->free_patch = 1;
1995 frag->size = origlen;
1999 frag->binary_patch_method = patch_method;
2005 error(_("corrupt binary patch at line %d: %.*s"),
2006 state->linenr-1, llen-1, buffer);
2012 * -1 in case of error,
2013 * the length of the parsed binary patch otherwise
2015 static int parse_binary(struct apply_state *state,
2018 struct patch *patch)
2021 * We have read "GIT binary patch\n"; what follows is a line
2022 * that says the patch method (currently, either "literal" or
2023 * "delta") and the length of data before deflating; a
2024 * sequence of 'length-byte' followed by base-85 encoded data
2027 * When a binary patch is reversible, there is another binary
2028 * hunk in the same format, starting with patch method (either
2029 * "literal" or "delta") with the length of data, and a sequence
2030 * of length-byte + base-85 encoded data, terminated with another
2031 * empty line. This data, when applied to the postimage, produces
2034 struct fragment *forward;
2035 struct fragment *reverse;
2039 forward = parse_binary_hunk(state, &buffer, &size, &status, &used);
2040 if (!forward && !status)
2041 /* there has to be one hunk (forward hunk) */
2042 return error(_("unrecognized binary patch at line %d"), state->linenr-1);
2044 /* otherwise we already gave an error message */
2047 reverse = parse_binary_hunk(state, &buffer, &size, &status, &used_1);
2052 * Not having reverse hunk is not an error, but having
2053 * a corrupt reverse hunk is.
2055 free((void*) forward->patch);
2059 forward->next = reverse;
2060 patch->fragments = forward;
2061 patch->is_binary = 1;
2065 static void prefix_one(struct apply_state *state, char **name)
2067 char *old_name = *name;
2070 *name = prefix_filename(state->prefix, *name);
2074 static void prefix_patch(struct apply_state *state, struct patch *p)
2076 if (!state->prefix || p->is_toplevel_relative)
2078 prefix_one(state, &p->new_name);
2079 prefix_one(state, &p->old_name);
2086 static void add_name_limit(struct apply_state *state,
2090 struct string_list_item *it;
2092 it = string_list_append(&state->limit_by_name, name);
2093 it->util = exclude ? NULL : (void *) 1;
2096 static int use_patch(struct apply_state *state, struct patch *p)
2098 const char *pathname = p->new_name ? p->new_name : p->old_name;
2101 /* Paths outside are not touched regardless of "--include" */
2102 if (0 < state->prefix_length) {
2103 int pathlen = strlen(pathname);
2104 if (pathlen <= state->prefix_length ||
2105 memcmp(state->prefix, pathname, state->prefix_length))
2109 /* See if it matches any of exclude/include rule */
2110 for (i = 0; i < state->limit_by_name.nr; i++) {
2111 struct string_list_item *it = &state->limit_by_name.items[i];
2112 if (!wildmatch(it->string, pathname, 0, NULL))
2113 return (it->util != NULL);
2117 * If we had any include, a path that does not match any rule is
2118 * not used. Otherwise, we saw bunch of exclude rules (or none)
2119 * and such a path is used.
2121 return !state->has_include;
2125 * Read the patch text in "buffer" that extends for "size" bytes; stop
2126 * reading after seeing a single patch (i.e. changes to a single file).
2127 * Create fragments (i.e. patch hunks) and hang them to the given patch.
2130 * -1 if no header was found or parse_binary() failed,
2131 * -128 on another error,
2132 * the number of bytes consumed otherwise,
2133 * so that the caller can call us again for the next patch.
2135 static int parse_chunk(struct apply_state *state, char *buffer, unsigned long size, struct patch *patch)
2137 int hdrsize, patchsize;
2138 int offset = find_header(state, buffer, size, &hdrsize, patch);
2143 prefix_patch(state, patch);
2145 if (!use_patch(state, patch))
2148 patch->ws_rule = whitespace_rule(patch->new_name
2152 patchsize = parse_single_patch(state,
2153 buffer + offset + hdrsize,
2154 size - offset - hdrsize,
2161 static const char git_binary[] = "GIT binary patch\n";
2162 int hd = hdrsize + offset;
2163 unsigned long llen = linelen(buffer + hd, size - hd);
2165 if (llen == sizeof(git_binary) - 1 &&
2166 !memcmp(git_binary, buffer + hd, llen)) {
2169 used = parse_binary(state, buffer + hd + llen,
2170 size - hd - llen, patch);
2174 patchsize = used + llen;
2178 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
2179 static const char *binhdr[] = {
2185 for (i = 0; binhdr[i]; i++) {
2186 int len = strlen(binhdr[i]);
2187 if (len < size - hd &&
2188 !memcmp(binhdr[i], buffer + hd, len)) {
2190 patch->is_binary = 1;
2197 /* Empty patch cannot be applied if it is a text patch
2198 * without metadata change. A binary patch appears
2201 if ((state->apply || state->check) &&
2202 (!patch->is_binary && !metadata_changes(patch))) {
2203 error(_("patch with only garbage at line %d"), state->linenr);
2208 return offset + hdrsize + patchsize;
2211 static void reverse_patches(struct patch *p)
2213 for (; p; p = p->next) {
2214 struct fragment *frag = p->fragments;
2216 SWAP(p->new_name, p->old_name);
2217 SWAP(p->new_mode, p->old_mode);
2218 SWAP(p->is_new, p->is_delete);
2219 SWAP(p->lines_added, p->lines_deleted);
2220 SWAP(p->old_sha1_prefix, p->new_sha1_prefix);
2222 for (; frag; frag = frag->next) {
2223 SWAP(frag->newpos, frag->oldpos);
2224 SWAP(frag->newlines, frag->oldlines);
2229 static const char pluses[] =
2230 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2231 static const char minuses[]=
2232 "----------------------------------------------------------------------";
2234 static void show_stats(struct apply_state *state, struct patch *patch)
2236 struct strbuf qname = STRBUF_INIT;
2237 char *cp = patch->new_name ? patch->new_name : patch->old_name;
2240 quote_c_style(cp, &qname, NULL, 0);
2243 * "scale" the filename
2245 max = state->max_len;
2249 if (qname.len > max) {
2250 cp = strchr(qname.buf + qname.len + 3 - max, '/');
2252 cp = qname.buf + qname.len + 3 - max;
2253 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
2256 if (patch->is_binary) {
2257 printf(" %-*s | Bin\n", max, qname.buf);
2258 strbuf_release(&qname);
2262 printf(" %-*s |", max, qname.buf);
2263 strbuf_release(&qname);
2266 * scale the add/delete
2268 max = max + state->max_change > 70 ? 70 - max : state->max_change;
2269 add = patch->lines_added;
2270 del = patch->lines_deleted;
2272 if (state->max_change > 0) {
2273 int total = ((add + del) * max + state->max_change / 2) / state->max_change;
2274 add = (add * max + state->max_change / 2) / state->max_change;
2277 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
2278 add, pluses, del, minuses);
2281 static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
2283 switch (st->st_mode & S_IFMT) {
2285 if (strbuf_readlink(buf, path, st->st_size) < 0)
2286 return error(_("unable to read symlink %s"), path);
2289 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
2290 return error(_("unable to open or read %s"), path);
2291 convert_to_git(path, buf->buf, buf->len, buf, 0);
2299 * Update the preimage, and the common lines in postimage,
2300 * from buffer buf of length len. If postlen is 0 the postimage
2301 * is updated in place, otherwise it's updated on a new buffer
2305 static void update_pre_post_images(struct image *preimage,
2306 struct image *postimage,
2308 size_t len, size_t postlen)
2310 int i, ctx, reduced;
2311 char *new, *old, *fixed;
2312 struct image fixed_preimage;
2315 * Update the preimage with whitespace fixes. Note that we
2316 * are not losing preimage->buf -- apply_one_fragment() will
2319 prepare_image(&fixed_preimage, buf, len, 1);
2321 ? fixed_preimage.nr == preimage->nr
2322 : fixed_preimage.nr <= preimage->nr);
2323 for (i = 0; i < fixed_preimage.nr; i++)
2324 fixed_preimage.line[i].flag = preimage->line[i].flag;
2325 free(preimage->line_allocated);
2326 *preimage = fixed_preimage;
2329 * Adjust the common context lines in postimage. This can be
2330 * done in-place when we are shrinking it with whitespace
2331 * fixing, but needs a new buffer when ignoring whitespace or
2332 * expanding leading tabs to spaces.
2334 * We trust the caller to tell us if the update can be done
2335 * in place (postlen==0) or not.
2337 old = postimage->buf;
2339 new = postimage->buf = xmalloc(postlen);
2342 fixed = preimage->buf;
2344 for (i = reduced = ctx = 0; i < postimage->nr; i++) {
2345 size_t l_len = postimage->line[i].len;
2346 if (!(postimage->line[i].flag & LINE_COMMON)) {
2347 /* an added line -- no counterparts in preimage */
2348 memmove(new, old, l_len);
2354 /* a common context -- skip it in the original postimage */
2357 /* and find the corresponding one in the fixed preimage */
2358 while (ctx < preimage->nr &&
2359 !(preimage->line[ctx].flag & LINE_COMMON)) {
2360 fixed += preimage->line[ctx].len;
2365 * preimage is expected to run out, if the caller
2366 * fixed addition of trailing blank lines.
2368 if (preimage->nr <= ctx) {
2373 /* and copy it in, while fixing the line length */
2374 l_len = preimage->line[ctx].len;
2375 memcpy(new, fixed, l_len);
2378 postimage->line[i].len = l_len;
2383 ? postlen < new - postimage->buf
2384 : postimage->len < new - postimage->buf)
2385 die("BUG: caller miscounted postlen: asked %d, orig = %d, used = %d",
2386 (int)postlen, (int) postimage->len, (int)(new - postimage->buf));
2388 /* Fix the length of the whole thing */
2389 postimage->len = new - postimage->buf;
2390 postimage->nr -= reduced;
2393 static int line_by_line_fuzzy_match(struct image *img,
2394 struct image *preimage,
2395 struct image *postimage,
2403 size_t postlen = postimage->len;
2408 struct strbuf fixed;
2412 for (i = 0; i < preimage_limit; i++) {
2413 size_t prelen = preimage->line[i].len;
2414 size_t imglen = img->line[try_lno+i].len;
2416 if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,
2417 preimage->buf + preoff, prelen))
2419 if (preimage->line[i].flag & LINE_COMMON)
2420 postlen += imglen - prelen;
2426 * Ok, the preimage matches with whitespace fuzz.
2428 * imgoff now holds the true length of the target that
2429 * matches the preimage before the end of the file.
2431 * Count the number of characters in the preimage that fall
2432 * beyond the end of the file and make sure that all of them
2433 * are whitespace characters. (This can only happen if
2434 * we are removing blank lines at the end of the file.)
2436 buf = preimage_eof = preimage->buf + preoff;
2437 for ( ; i < preimage->nr; i++)
2438 preoff += preimage->line[i].len;
2439 preimage_end = preimage->buf + preoff;
2440 for ( ; buf < preimage_end; buf++)
2445 * Update the preimage and the common postimage context
2446 * lines to use the same whitespace as the target.
2447 * If whitespace is missing in the target (i.e.
2448 * if the preimage extends beyond the end of the file),
2449 * use the whitespace from the preimage.
2451 extra_chars = preimage_end - preimage_eof;
2452 strbuf_init(&fixed, imgoff + extra_chars);
2453 strbuf_add(&fixed, img->buf + try, imgoff);
2454 strbuf_add(&fixed, preimage_eof, extra_chars);
2455 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2456 update_pre_post_images(preimage, postimage,
2457 fixed_buf, fixed_len, postlen);
2461 static int match_fragment(struct apply_state *state,
2463 struct image *preimage,
2464 struct image *postimage,
2468 int match_beginning, int match_end)
2471 char *fixed_buf, *buf, *orig, *target;
2472 struct strbuf fixed;
2473 size_t fixed_len, postlen;
2476 if (preimage->nr + try_lno <= img->nr) {
2478 * The hunk falls within the boundaries of img.
2480 preimage_limit = preimage->nr;
2481 if (match_end && (preimage->nr + try_lno != img->nr))
2483 } else if (state->ws_error_action == correct_ws_error &&
2484 (ws_rule & WS_BLANK_AT_EOF)) {
2486 * This hunk extends beyond the end of img, and we are
2487 * removing blank lines at the end of the file. This
2488 * many lines from the beginning of the preimage must
2489 * match with img, and the remainder of the preimage
2492 preimage_limit = img->nr - try_lno;
2495 * The hunk extends beyond the end of the img and
2496 * we are not removing blanks at the end, so we
2497 * should reject the hunk at this position.
2502 if (match_beginning && try_lno)
2505 /* Quick hash check */
2506 for (i = 0; i < preimage_limit; i++)
2507 if ((img->line[try_lno + i].flag & LINE_PATCHED) ||
2508 (preimage->line[i].hash != img->line[try_lno + i].hash))
2511 if (preimage_limit == preimage->nr) {
2513 * Do we have an exact match? If we were told to match
2514 * at the end, size must be exactly at try+fragsize,
2515 * otherwise try+fragsize must be still within the preimage,
2516 * and either case, the old piece should match the preimage
2520 ? (try + preimage->len == img->len)
2521 : (try + preimage->len <= img->len)) &&
2522 !memcmp(img->buf + try, preimage->buf, preimage->len))
2526 * The preimage extends beyond the end of img, so
2527 * there cannot be an exact match.
2529 * There must be one non-blank context line that match
2530 * a line before the end of img.
2534 buf = preimage->buf;
2536 for (i = 0; i < preimage_limit; i++)
2537 buf_end += preimage->line[i].len;
2539 for ( ; buf < buf_end; buf++)
2547 * No exact match. If we are ignoring whitespace, run a line-by-line
2548 * fuzzy matching. We collect all the line length information because
2549 * we need it to adjust whitespace if we match.
2551 if (state->ws_ignore_action == ignore_ws_change)
2552 return line_by_line_fuzzy_match(img, preimage, postimage,
2553 try, try_lno, preimage_limit);
2555 if (state->ws_error_action != correct_ws_error)
2559 * The hunk does not apply byte-by-byte, but the hash says
2560 * it might with whitespace fuzz. We weren't asked to
2561 * ignore whitespace, we were asked to correct whitespace
2562 * errors, so let's try matching after whitespace correction.
2564 * While checking the preimage against the target, whitespace
2565 * errors in both fixed, we count how large the corresponding
2566 * postimage needs to be. The postimage prepared by
2567 * apply_one_fragment() has whitespace errors fixed on added
2568 * lines already, but the common lines were propagated as-is,
2569 * which may become longer when their whitespace errors are
2573 /* First count added lines in postimage */
2575 for (i = 0; i < postimage->nr; i++) {
2576 if (!(postimage->line[i].flag & LINE_COMMON))
2577 postlen += postimage->line[i].len;
2581 * The preimage may extend beyond the end of the file,
2582 * but in this loop we will only handle the part of the
2583 * preimage that falls within the file.
2585 strbuf_init(&fixed, preimage->len + 1);
2586 orig = preimage->buf;
2587 target = img->buf + try;
2588 for (i = 0; i < preimage_limit; i++) {
2589 size_t oldlen = preimage->line[i].len;
2590 size_t tgtlen = img->line[try_lno + i].len;
2591 size_t fixstart = fixed.len;
2592 struct strbuf tgtfix;
2595 /* Try fixing the line in the preimage */
2596 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2598 /* Try fixing the line in the target */
2599 strbuf_init(&tgtfix, tgtlen);
2600 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2603 * If they match, either the preimage was based on
2604 * a version before our tree fixed whitespace breakage,
2605 * or we are lacking a whitespace-fix patch the tree
2606 * the preimage was based on already had (i.e. target
2607 * has whitespace breakage, the preimage doesn't).
2608 * In either case, we are fixing the whitespace breakages
2609 * so we might as well take the fix together with their
2612 match = (tgtfix.len == fixed.len - fixstart &&
2613 !memcmp(tgtfix.buf, fixed.buf + fixstart,
2614 fixed.len - fixstart));
2616 /* Add the length if this is common with the postimage */
2617 if (preimage->line[i].flag & LINE_COMMON)
2618 postlen += tgtfix.len;
2620 strbuf_release(&tgtfix);
2630 * Now handle the lines in the preimage that falls beyond the
2631 * end of the file (if any). They will only match if they are
2632 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2635 for ( ; i < preimage->nr; i++) {
2636 size_t fixstart = fixed.len; /* start of the fixed preimage */
2637 size_t oldlen = preimage->line[i].len;
2640 /* Try fixing the line in the preimage */
2641 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2643 for (j = fixstart; j < fixed.len; j++)
2644 if (!isspace(fixed.buf[j]))
2651 * Yes, the preimage is based on an older version that still
2652 * has whitespace breakages unfixed, and fixing them makes the
2653 * hunk match. Update the context lines in the postimage.
2655 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2656 if (postlen < postimage->len)
2658 update_pre_post_images(preimage, postimage,
2659 fixed_buf, fixed_len, postlen);
2663 strbuf_release(&fixed);
2667 static int find_pos(struct apply_state *state,
2669 struct image *preimage,
2670 struct image *postimage,
2673 int match_beginning, int match_end)
2676 unsigned long backwards, forwards, try;
2677 int backwards_lno, forwards_lno, try_lno;
2680 * If match_beginning or match_end is specified, there is no
2681 * point starting from a wrong line that will never match and
2682 * wander around and wait for a match at the specified end.
2684 if (match_beginning)
2687 line = img->nr - preimage->nr;
2690 * Because the comparison is unsigned, the following test
2691 * will also take care of a negative line number that can
2692 * result when match_end and preimage is larger than the target.
2694 if ((size_t) line > img->nr)
2698 for (i = 0; i < line; i++)
2699 try += img->line[i].len;
2702 * There's probably some smart way to do this, but I'll leave
2703 * that to the smart and beautiful people. I'm simple and stupid.
2706 backwards_lno = line;
2708 forwards_lno = line;
2711 for (i = 0; ; i++) {
2712 if (match_fragment(state, img, preimage, postimage,
2713 try, try_lno, ws_rule,
2714 match_beginning, match_end))
2718 if (backwards_lno == 0 && forwards_lno == img->nr)
2722 if (backwards_lno == 0) {
2727 backwards -= img->line[backwards_lno].len;
2729 try_lno = backwards_lno;
2731 if (forwards_lno == img->nr) {
2735 forwards += img->line[forwards_lno].len;
2738 try_lno = forwards_lno;
2745 static void remove_first_line(struct image *img)
2747 img->buf += img->line[0].len;
2748 img->len -= img->line[0].len;
2753 static void remove_last_line(struct image *img)
2755 img->len -= img->line[--img->nr].len;
2759 * The change from "preimage" and "postimage" has been found to
2760 * apply at applied_pos (counts in line numbers) in "img".
2761 * Update "img" to remove "preimage" and replace it with "postimage".
2763 static void update_image(struct apply_state *state,
2766 struct image *preimage,
2767 struct image *postimage)
2770 * remove the copy of preimage at offset in img
2771 * and replace it with postimage
2774 size_t remove_count, insert_count, applied_at = 0;
2779 * If we are removing blank lines at the end of img,
2780 * the preimage may extend beyond the end.
2781 * If that is the case, we must be careful only to
2782 * remove the part of the preimage that falls within
2783 * the boundaries of img. Initialize preimage_limit
2784 * to the number of lines in the preimage that falls
2785 * within the boundaries.
2787 preimage_limit = preimage->nr;
2788 if (preimage_limit > img->nr - applied_pos)
2789 preimage_limit = img->nr - applied_pos;
2791 for (i = 0; i < applied_pos; i++)
2792 applied_at += img->line[i].len;
2795 for (i = 0; i < preimage_limit; i++)
2796 remove_count += img->line[applied_pos + i].len;
2797 insert_count = postimage->len;
2799 /* Adjust the contents */
2800 result = xmalloc(st_add3(st_sub(img->len, remove_count), insert_count, 1));
2801 memcpy(result, img->buf, applied_at);
2802 memcpy(result + applied_at, postimage->buf, postimage->len);
2803 memcpy(result + applied_at + postimage->len,
2804 img->buf + (applied_at + remove_count),
2805 img->len - (applied_at + remove_count));
2808 img->len += insert_count - remove_count;
2809 result[img->len] = '\0';
2811 /* Adjust the line table */
2812 nr = img->nr + postimage->nr - preimage_limit;
2813 if (preimage_limit < postimage->nr) {
2815 * NOTE: this knows that we never call remove_first_line()
2816 * on anything other than pre/post image.
2818 REALLOC_ARRAY(img->line, nr);
2819 img->line_allocated = img->line;
2821 if (preimage_limit != postimage->nr)
2822 memmove(img->line + applied_pos + postimage->nr,
2823 img->line + applied_pos + preimage_limit,
2824 (img->nr - (applied_pos + preimage_limit)) *
2825 sizeof(*img->line));
2826 memcpy(img->line + applied_pos,
2828 postimage->nr * sizeof(*img->line));
2829 if (!state->allow_overlap)
2830 for (i = 0; i < postimage->nr; i++)
2831 img->line[applied_pos + i].flag |= LINE_PATCHED;
2836 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2837 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2838 * replace the part of "img" with "postimage" text.
2840 static int apply_one_fragment(struct apply_state *state,
2841 struct image *img, struct fragment *frag,
2842 int inaccurate_eof, unsigned ws_rule,
2845 int match_beginning, match_end;
2846 const char *patch = frag->patch;
2847 int size = frag->size;
2848 char *old, *oldlines;
2849 struct strbuf newlines;
2850 int new_blank_lines_at_end = 0;
2851 int found_new_blank_lines_at_end = 0;
2852 int hunk_linenr = frag->linenr;
2853 unsigned long leading, trailing;
2854 int pos, applied_pos;
2855 struct image preimage;
2856 struct image postimage;
2858 memset(&preimage, 0, sizeof(preimage));
2859 memset(&postimage, 0, sizeof(postimage));
2860 oldlines = xmalloc(size);
2861 strbuf_init(&newlines, size);
2866 int len = linelen(patch, size);
2868 int added_blank_line = 0;
2869 int is_blank_context = 0;
2876 * "plen" is how much of the line we should use for
2877 * the actual patch data. Normally we just remove the
2878 * first character on the line, but if the line is
2879 * followed by "\ No newline", then we also remove the
2880 * last one (which is the newline, of course).
2883 if (len < size && patch[len] == '\\')
2886 if (state->apply_in_reverse) {
2889 else if (first == '+')
2895 /* Newer GNU diff, empty context line */
2897 /* ... followed by '\No newline'; nothing */
2900 strbuf_addch(&newlines, '\n');
2901 add_line_info(&preimage, "\n", 1, LINE_COMMON);
2902 add_line_info(&postimage, "\n", 1, LINE_COMMON);
2903 is_blank_context = 1;
2906 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2907 ws_blank_line(patch + 1, plen, ws_rule))
2908 is_blank_context = 1;
2910 memcpy(old, patch + 1, plen);
2911 add_line_info(&preimage, old, plen,
2912 (first == ' ' ? LINE_COMMON : 0));
2916 /* Fall-through for ' ' */
2918 /* --no-add does not add new lines */
2919 if (first == '+' && state->no_add)
2922 start = newlines.len;
2924 !state->whitespace_error ||
2925 state->ws_error_action != correct_ws_error) {
2926 strbuf_add(&newlines, patch + 1, plen);
2929 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &state->applied_after_fixing_ws);
2931 add_line_info(&postimage, newlines.buf + start, newlines.len - start,
2932 (first == '+' ? 0 : LINE_COMMON));
2934 (ws_rule & WS_BLANK_AT_EOF) &&
2935 ws_blank_line(patch + 1, plen, ws_rule))
2936 added_blank_line = 1;
2938 case '@': case '\\':
2939 /* Ignore it, we already handled it */
2942 if (state->apply_verbosity > verbosity_normal)
2943 error(_("invalid start of line: '%c'"), first);
2947 if (added_blank_line) {
2948 if (!new_blank_lines_at_end)
2949 found_new_blank_lines_at_end = hunk_linenr;
2950 new_blank_lines_at_end++;
2952 else if (is_blank_context)
2955 new_blank_lines_at_end = 0;
2960 if (inaccurate_eof &&
2961 old > oldlines && old[-1] == '\n' &&
2962 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
2964 strbuf_setlen(&newlines, newlines.len - 1);
2967 leading = frag->leading;
2968 trailing = frag->trailing;
2971 * A hunk to change lines at the beginning would begin with
2973 * but we need to be careful. -U0 that inserts before the second
2974 * line also has this pattern.
2976 * And a hunk to add to an empty file would begin with
2979 * In other words, a hunk that is (frag->oldpos <= 1) with or
2980 * without leading context must match at the beginning.
2982 match_beginning = (!frag->oldpos ||
2983 (frag->oldpos == 1 && !state->unidiff_zero));
2986 * A hunk without trailing lines must match at the end.
2987 * However, we simply cannot tell if a hunk must match end
2988 * from the lack of trailing lines if the patch was generated
2989 * with unidiff without any context.
2991 match_end = !state->unidiff_zero && !trailing;
2993 pos = frag->newpos ? (frag->newpos - 1) : 0;
2994 preimage.buf = oldlines;
2995 preimage.len = old - oldlines;
2996 postimage.buf = newlines.buf;
2997 postimage.len = newlines.len;
2998 preimage.line = preimage.line_allocated;
2999 postimage.line = postimage.line_allocated;
3003 applied_pos = find_pos(state, img, &preimage, &postimage, pos,
3004 ws_rule, match_beginning, match_end);
3006 if (applied_pos >= 0)
3009 /* Am I at my context limits? */
3010 if ((leading <= state->p_context) && (trailing <= state->p_context))
3012 if (match_beginning || match_end) {
3013 match_beginning = match_end = 0;
3018 * Reduce the number of context lines; reduce both
3019 * leading and trailing if they are equal otherwise
3020 * just reduce the larger context.
3022 if (leading >= trailing) {
3023 remove_first_line(&preimage);
3024 remove_first_line(&postimage);
3028 if (trailing > leading) {
3029 remove_last_line(&preimage);
3030 remove_last_line(&postimage);
3035 if (applied_pos >= 0) {
3036 if (new_blank_lines_at_end &&
3037 preimage.nr + applied_pos >= img->nr &&
3038 (ws_rule & WS_BLANK_AT_EOF) &&
3039 state->ws_error_action != nowarn_ws_error) {
3040 record_ws_error(state, WS_BLANK_AT_EOF, "+", 1,
3041 found_new_blank_lines_at_end);
3042 if (state->ws_error_action == correct_ws_error) {
3043 while (new_blank_lines_at_end--)
3044 remove_last_line(&postimage);
3047 * We would want to prevent write_out_results()
3048 * from taking place in apply_patch() that follows
3049 * the callchain led us here, which is:
3050 * apply_patch->check_patch_list->check_patch->
3051 * apply_data->apply_fragments->apply_one_fragment
3053 if (state->ws_error_action == die_on_ws_error)
3057 if (state->apply_verbosity > verbosity_normal && applied_pos != pos) {
3058 int offset = applied_pos - pos;
3059 if (state->apply_in_reverse)
3060 offset = 0 - offset;
3062 Q_("Hunk #%d succeeded at %d (offset %d line).",
3063 "Hunk #%d succeeded at %d (offset %d lines).",
3065 nth_fragment, applied_pos + 1, offset);
3069 * Warn if it was necessary to reduce the number
3072 if ((leading != frag->leading ||
3073 trailing != frag->trailing) && state->apply_verbosity > verbosity_silent)
3074 fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"
3075 " to apply fragment at %d"),
3076 leading, trailing, applied_pos+1);
3077 update_image(state, img, applied_pos, &preimage, &postimage);
3079 if (state->apply_verbosity > verbosity_normal)
3080 error(_("while searching for:\n%.*s"),
3081 (int)(old - oldlines), oldlines);
3086 strbuf_release(&newlines);
3087 free(preimage.line_allocated);
3088 free(postimage.line_allocated);
3090 return (applied_pos < 0);
3093 static int apply_binary_fragment(struct apply_state *state,
3095 struct patch *patch)
3097 struct fragment *fragment = patch->fragments;
3102 return error(_("missing binary patch data for '%s'"),
3107 /* Binary patch is irreversible without the optional second hunk */
3108 if (state->apply_in_reverse) {
3109 if (!fragment->next)
3110 return error(_("cannot reverse-apply a binary patch "
3111 "without the reverse hunk to '%s'"),
3113 ? patch->new_name : patch->old_name);
3114 fragment = fragment->next;
3116 switch (fragment->binary_patch_method) {
3117 case BINARY_DELTA_DEFLATED:
3118 dst = patch_delta(img->buf, img->len, fragment->patch,
3119 fragment->size, &len);
3126 case BINARY_LITERAL_DEFLATED:
3128 img->len = fragment->size;
3129 img->buf = xmemdupz(fragment->patch, img->len);
3136 * Replace "img" with the result of applying the binary patch.
3137 * The binary patch data itself in patch->fragment is still kept
3138 * but the preimage prepared by the caller in "img" is freed here
3139 * or in the helper function apply_binary_fragment() this calls.
3141 static int apply_binary(struct apply_state *state,
3143 struct patch *patch)
3145 const char *name = patch->old_name ? patch->old_name : patch->new_name;
3146 struct object_id oid;
3149 * For safety, we require patch index line to contain
3150 * full 40-byte textual SHA1 for old and new, at least for now.
3152 if (strlen(patch->old_sha1_prefix) != 40 ||
3153 strlen(patch->new_sha1_prefix) != 40 ||
3154 get_oid_hex(patch->old_sha1_prefix, &oid) ||
3155 get_oid_hex(patch->new_sha1_prefix, &oid))
3156 return error(_("cannot apply binary patch to '%s' "
3157 "without full index line"), name);
3159 if (patch->old_name) {
3161 * See if the old one matches what the patch
3164 hash_sha1_file(img->buf, img->len, blob_type, oid.hash);
3165 if (strcmp(oid_to_hex(&oid), patch->old_sha1_prefix))
3166 return error(_("the patch applies to '%s' (%s), "
3167 "which does not match the "
3168 "current contents."),
3169 name, oid_to_hex(&oid));
3172 /* Otherwise, the old one must be empty. */
3174 return error(_("the patch applies to an empty "
3175 "'%s' but it is not empty"), name);
3178 get_oid_hex(patch->new_sha1_prefix, &oid);
3179 if (is_null_oid(&oid)) {
3181 return 0; /* deletion patch */
3184 if (has_sha1_file(oid.hash)) {
3185 /* We already have the postimage */
3186 enum object_type type;
3190 result = read_sha1_file(oid.hash, &type, &size);
3192 return error(_("the necessary postimage %s for "
3193 "'%s' cannot be read"),
3194 patch->new_sha1_prefix, name);
3200 * We have verified buf matches the preimage;
3201 * apply the patch data to it, which is stored
3202 * in the patch->fragments->{patch,size}.
3204 if (apply_binary_fragment(state, img, patch))
3205 return error(_("binary patch does not apply to '%s'"),
3208 /* verify that the result matches */
3209 hash_sha1_file(img->buf, img->len, blob_type, oid.hash);
3210 if (strcmp(oid_to_hex(&oid), patch->new_sha1_prefix))
3211 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3212 name, patch->new_sha1_prefix, oid_to_hex(&oid));
3218 static int apply_fragments(struct apply_state *state, struct image *img, struct patch *patch)
3220 struct fragment *frag = patch->fragments;
3221 const char *name = patch->old_name ? patch->old_name : patch->new_name;
3222 unsigned ws_rule = patch->ws_rule;
3223 unsigned inaccurate_eof = patch->inaccurate_eof;
3226 if (patch->is_binary)
3227 return apply_binary(state, img, patch);
3231 if (apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {
3232 error(_("patch failed: %s:%ld"), name, frag->oldpos);
3233 if (!state->apply_with_reject)
3242 static int read_blob_object(struct strbuf *buf, const struct object_id *oid, unsigned mode)
3244 if (S_ISGITLINK(mode)) {
3245 strbuf_grow(buf, 100);
3246 strbuf_addf(buf, "Subproject commit %s\n", oid_to_hex(oid));
3248 enum object_type type;
3252 result = read_sha1_file(oid->hash, &type, &sz);
3255 /* XXX read_sha1_file NUL-terminates */
3256 strbuf_attach(buf, result, sz, sz + 1);
3261 static int read_file_or_gitlink(const struct cache_entry *ce, struct strbuf *buf)
3265 return read_blob_object(buf, &ce->oid, ce->ce_mode);
3268 static struct patch *in_fn_table(struct apply_state *state, const char *name)
3270 struct string_list_item *item;
3275 item = string_list_lookup(&state->fn_table, name);
3277 return (struct patch *)item->util;
3283 * item->util in the filename table records the status of the path.
3284 * Usually it points at a patch (whose result records the contents
3285 * of it after applying it), but it could be PATH_WAS_DELETED for a
3286 * path that a previously applied patch has already removed, or
3287 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3289 * The latter is needed to deal with a case where two paths A and B
3290 * are swapped by first renaming A to B and then renaming B to A;
3291 * moving A to B should not be prevented due to presence of B as we
3292 * will remove it in a later patch.
3294 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3295 #define PATH_WAS_DELETED ((struct patch *) -1)
3297 static int to_be_deleted(struct patch *patch)
3299 return patch == PATH_TO_BE_DELETED;
3302 static int was_deleted(struct patch *patch)
3304 return patch == PATH_WAS_DELETED;
3307 static void add_to_fn_table(struct apply_state *state, struct patch *patch)
3309 struct string_list_item *item;
3312 * Always add new_name unless patch is a deletion
3313 * This should cover the cases for normal diffs,
3314 * file creations and copies
3316 if (patch->new_name != NULL) {
3317 item = string_list_insert(&state->fn_table, patch->new_name);
3322 * store a failure on rename/deletion cases because
3323 * later chunks shouldn't patch old names
3325 if ((patch->new_name == NULL) || (patch->is_rename)) {
3326 item = string_list_insert(&state->fn_table, patch->old_name);
3327 item->util = PATH_WAS_DELETED;
3331 static void prepare_fn_table(struct apply_state *state, struct patch *patch)
3334 * store information about incoming file deletion
3337 if ((patch->new_name == NULL) || (patch->is_rename)) {
3338 struct string_list_item *item;
3339 item = string_list_insert(&state->fn_table, patch->old_name);
3340 item->util = PATH_TO_BE_DELETED;
3342 patch = patch->next;
3346 static int checkout_target(struct index_state *istate,
3347 struct cache_entry *ce, struct stat *st)
3349 struct checkout costate = CHECKOUT_INIT;
3351 costate.refresh_cache = 1;
3352 costate.istate = istate;
3353 if (checkout_entry(ce, &costate, NULL) || lstat(ce->name, st))
3354 return error(_("cannot checkout %s"), ce->name);
3358 static struct patch *previous_patch(struct apply_state *state,
3359 struct patch *patch,
3362 struct patch *previous;
3365 if (patch->is_copy || patch->is_rename)
3366 return NULL; /* "git" patches do not depend on the order */
3368 previous = in_fn_table(state, patch->old_name);
3372 if (to_be_deleted(previous))
3373 return NULL; /* the deletion hasn't happened yet */
3375 if (was_deleted(previous))
3381 static int verify_index_match(const struct cache_entry *ce, struct stat *st)
3383 if (S_ISGITLINK(ce->ce_mode)) {
3384 if (!S_ISDIR(st->st_mode))
3388 return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
3391 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3393 static int load_patch_target(struct apply_state *state,
3395 const struct cache_entry *ce,
3398 unsigned expected_mode)
3400 if (state->cached || state->check_index) {
3401 if (read_file_or_gitlink(ce, buf))
3402 return error(_("failed to read %s"), name);
3404 if (S_ISGITLINK(expected_mode)) {
3406 return read_file_or_gitlink(ce, buf);
3408 return SUBMODULE_PATCH_WITHOUT_INDEX;
3409 } else if (has_symlink_leading_path(name, strlen(name))) {
3410 return error(_("reading from '%s' beyond a symbolic link"), name);
3412 if (read_old_data(st, name, buf))
3413 return error(_("failed to read %s"), name);
3420 * We are about to apply "patch"; populate the "image" with the
3421 * current version we have, from the working tree or from the index,
3422 * depending on the situation e.g. --cached/--index. If we are
3423 * applying a non-git patch that incrementally updates the tree,
3424 * we read from the result of a previous diff.
3426 static int load_preimage(struct apply_state *state,
3427 struct image *image,
3428 struct patch *patch, struct stat *st,
3429 const struct cache_entry *ce)
3431 struct strbuf buf = STRBUF_INIT;
3434 struct patch *previous;
3437 previous = previous_patch(state, patch, &status);
3439 return error(_("path %s has been renamed/deleted"),
3442 /* We have a patched copy in memory; use that. */
3443 strbuf_add(&buf, previous->result, previous->resultsize);
3445 status = load_patch_target(state, &buf, ce, st,
3446 patch->old_name, patch->old_mode);
3449 else if (status == SUBMODULE_PATCH_WITHOUT_INDEX) {
3451 * There is no way to apply subproject
3452 * patch without looking at the index.
3453 * NEEDSWORK: shouldn't this be flagged
3456 free_fragment_list(patch->fragments);
3457 patch->fragments = NULL;
3458 } else if (status) {
3459 return error(_("failed to read %s"), patch->old_name);
3463 img = strbuf_detach(&buf, &len);
3464 prepare_image(image, img, len, !patch->is_binary);
3468 static int three_way_merge(struct image *image,
3470 const struct object_id *base,
3471 const struct object_id *ours,
3472 const struct object_id *theirs)
3474 mmfile_t base_file, our_file, their_file;
3475 mmbuffer_t result = { NULL };
3478 read_mmblob(&base_file, base);
3479 read_mmblob(&our_file, ours);
3480 read_mmblob(&their_file, theirs);
3481 status = ll_merge(&result, path,
3484 &their_file, "theirs", NULL);
3485 free(base_file.ptr);
3487 free(their_file.ptr);
3488 if (status < 0 || !result.ptr) {
3493 image->buf = result.ptr;
3494 image->len = result.size;
3500 * When directly falling back to add/add three-way merge, we read from
3501 * the current contents of the new_name. In no cases other than that
3502 * this function will be called.
3504 static int load_current(struct apply_state *state,
3505 struct image *image,
3506 struct patch *patch)
3508 struct strbuf buf = STRBUF_INIT;
3513 struct cache_entry *ce;
3514 char *name = patch->new_name;
3515 unsigned mode = patch->new_mode;
3518 die("BUG: patch to %s is not a creation", patch->old_name);
3520 pos = cache_name_pos(name, strlen(name));
3522 return error(_("%s: does not exist in index"), name);
3523 ce = active_cache[pos];
3524 if (lstat(name, &st)) {
3525 if (errno != ENOENT)
3526 return error_errno("%s", name);
3527 if (checkout_target(&the_index, ce, &st))
3530 if (verify_index_match(ce, &st))
3531 return error(_("%s: does not match index"), name);
3533 status = load_patch_target(state, &buf, ce, &st, name, mode);
3538 img = strbuf_detach(&buf, &len);
3539 prepare_image(image, img, len, !patch->is_binary);
3543 static int try_threeway(struct apply_state *state,
3544 struct image *image,
3545 struct patch *patch,
3547 const struct cache_entry *ce)
3549 struct object_id pre_oid, post_oid, our_oid;
3550 struct strbuf buf = STRBUF_INIT;
3554 struct image tmp_image;
3556 /* No point falling back to 3-way merge in these cases */
3557 if (patch->is_delete ||
3558 S_ISGITLINK(patch->old_mode) || S_ISGITLINK(patch->new_mode))
3561 /* Preimage the patch was prepared for */
3563 write_sha1_file("", 0, blob_type, pre_oid.hash);
3564 else if (get_sha1(patch->old_sha1_prefix, pre_oid.hash) ||
3565 read_blob_object(&buf, &pre_oid, patch->old_mode))
3566 return error(_("repository lacks the necessary blob to fall back on 3-way merge."));
3568 if (state->apply_verbosity > verbosity_silent)
3569 fprintf(stderr, _("Falling back to three-way merge...\n"));
3571 img = strbuf_detach(&buf, &len);
3572 prepare_image(&tmp_image, img, len, 1);
3573 /* Apply the patch to get the post image */
3574 if (apply_fragments(state, &tmp_image, patch) < 0) {
3575 clear_image(&tmp_image);
3578 /* post_oid is theirs */
3579 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_oid.hash);
3580 clear_image(&tmp_image);
3582 /* our_oid is ours */
3583 if (patch->is_new) {
3584 if (load_current(state, &tmp_image, patch))
3585 return error(_("cannot read the current contents of '%s'"),
3588 if (load_preimage(state, &tmp_image, patch, st, ce))
3589 return error(_("cannot read the current contents of '%s'"),
3592 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_oid.hash);
3593 clear_image(&tmp_image);
3595 /* in-core three-way merge between post and our using pre as base */
3596 status = three_way_merge(image, patch->new_name,
3597 &pre_oid, &our_oid, &post_oid);
3599 if (state->apply_verbosity > verbosity_silent)
3601 _("Failed to fall back on three-way merge...\n"));
3606 patch->conflicted_threeway = 1;
3608 oidclr(&patch->threeway_stage[0]);
3610 oidcpy(&patch->threeway_stage[0], &pre_oid);
3611 oidcpy(&patch->threeway_stage[1], &our_oid);
3612 oidcpy(&patch->threeway_stage[2], &post_oid);
3613 if (state->apply_verbosity > verbosity_silent)
3615 _("Applied patch to '%s' with conflicts.\n"),
3618 if (state->apply_verbosity > verbosity_silent)
3620 _("Applied patch to '%s' cleanly.\n"),
3626 static int apply_data(struct apply_state *state, struct patch *patch,
3627 struct stat *st, const struct cache_entry *ce)
3631 if (load_preimage(state, &image, patch, st, ce) < 0)
3634 if (patch->direct_to_threeway ||
3635 apply_fragments(state, &image, patch) < 0) {
3636 /* Note: with --reject, apply_fragments() returns 0 */
3637 if (!state->threeway || try_threeway(state, &image, patch, st, ce) < 0)
3640 patch->result = image.buf;
3641 patch->resultsize = image.len;
3642 add_to_fn_table(state, patch);
3643 free(image.line_allocated);
3645 if (0 < patch->is_delete && patch->resultsize)
3646 return error(_("removal patch leaves file contents"));
3652 * If "patch" that we are looking at modifies or deletes what we have,
3653 * we would want it not to lose any local modification we have, either
3654 * in the working tree or in the index.
3656 * This also decides if a non-git patch is a creation patch or a
3657 * modification to an existing empty file. We do not check the state
3658 * of the current tree for a creation patch in this function; the caller
3659 * check_patch() separately makes sure (and errors out otherwise) that
3660 * the path the patch creates does not exist in the current tree.
3662 static int check_preimage(struct apply_state *state,
3663 struct patch *patch,
3664 struct cache_entry **ce,
3667 const char *old_name = patch->old_name;
3668 struct patch *previous = NULL;
3669 int stat_ret = 0, status;
3670 unsigned st_mode = 0;
3675 assert(patch->is_new <= 0);
3676 previous = previous_patch(state, patch, &status);
3679 return error(_("path %s has been renamed/deleted"), old_name);
3681 st_mode = previous->new_mode;
3682 } else if (!state->cached) {
3683 stat_ret = lstat(old_name, st);
3684 if (stat_ret && errno != ENOENT)
3685 return error_errno("%s", old_name);
3688 if (state->check_index && !previous) {
3689 int pos = cache_name_pos(old_name, strlen(old_name));
3691 if (patch->is_new < 0)
3693 return error(_("%s: does not exist in index"), old_name);
3695 *ce = active_cache[pos];
3697 if (checkout_target(&the_index, *ce, st))
3700 if (!state->cached && verify_index_match(*ce, st))
3701 return error(_("%s: does not match index"), old_name);
3703 st_mode = (*ce)->ce_mode;
3704 } else if (stat_ret < 0) {
3705 if (patch->is_new < 0)
3707 return error_errno("%s", old_name);
3710 if (!state->cached && !previous)
3711 st_mode = ce_mode_from_stat(*ce, st->st_mode);
3713 if (patch->is_new < 0)
3715 if (!patch->old_mode)
3716 patch->old_mode = st_mode;
3717 if ((st_mode ^ patch->old_mode) & S_IFMT)
3718 return error(_("%s: wrong type"), old_name);
3719 if (st_mode != patch->old_mode)
3720 warning(_("%s has type %o, expected %o"),
3721 old_name, st_mode, patch->old_mode);
3722 if (!patch->new_mode && !patch->is_delete)
3723 patch->new_mode = st_mode;
3728 patch->is_delete = 0;
3729 free(patch->old_name);
3730 patch->old_name = NULL;
3735 #define EXISTS_IN_INDEX 1
3736 #define EXISTS_IN_WORKTREE 2
3738 static int check_to_create(struct apply_state *state,
3739 const char *new_name,
3744 if (state->check_index &&
3745 cache_name_pos(new_name, strlen(new_name)) >= 0 &&
3747 return EXISTS_IN_INDEX;
3751 if (!lstat(new_name, &nst)) {
3752 if (S_ISDIR(nst.st_mode) || ok_if_exists)
3755 * A leading component of new_name might be a symlink
3756 * that is going to be removed with this patch, but
3757 * still pointing at somewhere that has the path.
3758 * In such a case, path "new_name" does not exist as
3759 * far as git is concerned.
3761 if (has_symlink_leading_path(new_name, strlen(new_name)))
3764 return EXISTS_IN_WORKTREE;
3765 } else if ((errno != ENOENT) && (errno != ENOTDIR)) {
3766 return error_errno("%s", new_name);
3771 static uintptr_t register_symlink_changes(struct apply_state *state,
3775 struct string_list_item *ent;
3777 ent = string_list_lookup(&state->symlink_changes, path);
3779 ent = string_list_insert(&state->symlink_changes, path);
3780 ent->util = (void *)0;
3782 ent->util = (void *)(what | ((uintptr_t)ent->util));
3783 return (uintptr_t)ent->util;
3786 static uintptr_t check_symlink_changes(struct apply_state *state, const char *path)
3788 struct string_list_item *ent;
3790 ent = string_list_lookup(&state->symlink_changes, path);
3793 return (uintptr_t)ent->util;
3796 static void prepare_symlink_changes(struct apply_state *state, struct patch *patch)
3798 for ( ; patch; patch = patch->next) {
3799 if ((patch->old_name && S_ISLNK(patch->old_mode)) &&
3800 (patch->is_rename || patch->is_delete))
3801 /* the symlink at patch->old_name is removed */
3802 register_symlink_changes(state, patch->old_name, APPLY_SYMLINK_GOES_AWAY);
3804 if (patch->new_name && S_ISLNK(patch->new_mode))
3805 /* the symlink at patch->new_name is created or remains */
3806 register_symlink_changes(state, patch->new_name, APPLY_SYMLINK_IN_RESULT);
3810 static int path_is_beyond_symlink_1(struct apply_state *state, struct strbuf *name)
3813 unsigned int change;
3815 while (--name->len && name->buf[name->len] != '/')
3816 ; /* scan backwards */
3819 name->buf[name->len] = '\0';
3820 change = check_symlink_changes(state, name->buf);
3821 if (change & APPLY_SYMLINK_IN_RESULT)
3823 if (change & APPLY_SYMLINK_GOES_AWAY)
3825 * This cannot be "return 0", because we may
3826 * see a new one created at a higher level.
3830 /* otherwise, check the preimage */
3831 if (state->check_index) {
3832 struct cache_entry *ce;
3834 ce = cache_file_exists(name->buf, name->len, ignore_case);
3835 if (ce && S_ISLNK(ce->ce_mode))
3839 if (!lstat(name->buf, &st) && S_ISLNK(st.st_mode))
3846 static int path_is_beyond_symlink(struct apply_state *state, const char *name_)
3849 struct strbuf name = STRBUF_INIT;
3851 assert(*name_ != '\0');
3852 strbuf_addstr(&name, name_);
3853 ret = path_is_beyond_symlink_1(state, &name);
3854 strbuf_release(&name);
3859 static int check_unsafe_path(struct patch *patch)
3861 const char *old_name = NULL;
3862 const char *new_name = NULL;
3863 if (patch->is_delete)
3864 old_name = patch->old_name;
3865 else if (!patch->is_new && !patch->is_copy)
3866 old_name = patch->old_name;
3867 if (!patch->is_delete)
3868 new_name = patch->new_name;
3870 if (old_name && !verify_path(old_name))
3871 return error(_("invalid path '%s'"), old_name);
3872 if (new_name && !verify_path(new_name))
3873 return error(_("invalid path '%s'"), new_name);
3878 * Check and apply the patch in-core; leave the result in patch->result
3879 * for the caller to write it out to the final destination.
3881 static int check_patch(struct apply_state *state, struct patch *patch)
3884 const char *old_name = patch->old_name;
3885 const char *new_name = patch->new_name;
3886 const char *name = old_name ? old_name : new_name;
3887 struct cache_entry *ce = NULL;
3888 struct patch *tpatch;
3892 patch->rejected = 1; /* we will drop this after we succeed */
3894 status = check_preimage(state, patch, &ce, &st);
3897 old_name = patch->old_name;
3900 * A type-change diff is always split into a patch to delete
3901 * old, immediately followed by a patch to create new (see
3902 * diff.c::run_diff()); in such a case it is Ok that the entry
3903 * to be deleted by the previous patch is still in the working
3904 * tree and in the index.
3906 * A patch to swap-rename between A and B would first rename A
3907 * to B and then rename B to A. While applying the first one,
3908 * the presence of B should not stop A from getting renamed to
3909 * B; ask to_be_deleted() about the later rename. Removal of
3910 * B and rename from A to B is handled the same way by asking
3913 if ((tpatch = in_fn_table(state, new_name)) &&
3914 (was_deleted(tpatch) || to_be_deleted(tpatch)))
3920 ((0 < patch->is_new) || patch->is_rename || patch->is_copy)) {
3921 int err = check_to_create(state, new_name, ok_if_exists);
3923 if (err && state->threeway) {
3924 patch->direct_to_threeway = 1;
3925 } else switch (err) {
3928 case EXISTS_IN_INDEX:
3929 return error(_("%s: already exists in index"), new_name);
3931 case EXISTS_IN_WORKTREE:
3932 return error(_("%s: already exists in working directory"),
3938 if (!patch->new_mode) {
3939 if (0 < patch->is_new)
3940 patch->new_mode = S_IFREG | 0644;
3942 patch->new_mode = patch->old_mode;
3946 if (new_name && old_name) {
3947 int same = !strcmp(old_name, new_name);
3948 if (!patch->new_mode)
3949 patch->new_mode = patch->old_mode;
3950 if ((patch->old_mode ^ patch->new_mode) & S_IFMT) {
3952 return error(_("new mode (%o) of %s does not "
3953 "match old mode (%o)"),
3954 patch->new_mode, new_name,
3957 return error(_("new mode (%o) of %s does not "
3958 "match old mode (%o) of %s"),
3959 patch->new_mode, new_name,
3960 patch->old_mode, old_name);
3964 if (!state->unsafe_paths && check_unsafe_path(patch))
3968 * An attempt to read from or delete a path that is beyond a
3969 * symbolic link will be prevented by load_patch_target() that
3970 * is called at the beginning of apply_data() so we do not
3971 * have to worry about a patch marked with "is_delete" bit
3972 * here. We however need to make sure that the patch result
3973 * is not deposited to a path that is beyond a symbolic link
3976 if (!patch->is_delete && path_is_beyond_symlink(state, patch->new_name))
3977 return error(_("affected file '%s' is beyond a symbolic link"),
3980 if (apply_data(state, patch, &st, ce) < 0)
3981 return error(_("%s: patch does not apply"), name);
3982 patch->rejected = 0;
3986 static int check_patch_list(struct apply_state *state, struct patch *patch)
3990 prepare_symlink_changes(state, patch);
3991 prepare_fn_table(state, patch);
3994 if (state->apply_verbosity > verbosity_normal)
3995 say_patch_name(stderr,
3996 _("Checking patch %s..."), patch);
3997 res = check_patch(state, patch);
4001 patch = patch->next;
4006 static int read_apply_cache(struct apply_state *state)
4008 if (state->index_file)
4009 return read_cache_from(state->index_file);
4011 return read_cache();
4014 /* This function tries to read the object name from the current index */
4015 static int get_current_oid(struct apply_state *state, const char *path,
4016 struct object_id *oid)
4020 if (read_apply_cache(state) < 0)
4022 pos = cache_name_pos(path, strlen(path));
4025 oidcpy(oid, &active_cache[pos]->oid);
4029 static int preimage_oid_in_gitlink_patch(struct patch *p, struct object_id *oid)
4032 * A usable gitlink patch has only one fragment (hunk) that looks like:
4034 * -Subproject commit <old sha1>
4035 * +Subproject commit <new sha1>
4038 * -Subproject commit <old sha1>
4039 * for a removal patch.
4041 struct fragment *hunk = p->fragments;
4042 static const char heading[] = "-Subproject commit ";
4045 if (/* does the patch have only one hunk? */
4046 hunk && !hunk->next &&
4047 /* is its preimage one line? */
4048 hunk->oldpos == 1 && hunk->oldlines == 1 &&
4049 /* does preimage begin with the heading? */
4050 (preimage = memchr(hunk->patch, '\n', hunk->size)) != NULL &&
4051 starts_with(++preimage, heading) &&
4052 /* does it record full SHA-1? */
4053 !get_oid_hex(preimage + sizeof(heading) - 1, oid) &&
4054 preimage[sizeof(heading) + GIT_SHA1_HEXSZ - 1] == '\n' &&
4055 /* does the abbreviated name on the index line agree with it? */
4056 starts_with(preimage + sizeof(heading) - 1, p->old_sha1_prefix))
4057 return 0; /* it all looks fine */
4059 /* we may have full object name on the index line */
4060 return get_oid_hex(p->old_sha1_prefix, oid);
4063 /* Build an index that contains the just the files needed for a 3way merge */
4064 static int build_fake_ancestor(struct apply_state *state, struct patch *list)
4066 struct patch *patch;
4067 struct index_state result = { NULL };
4068 static struct lock_file lock;
4071 /* Once we start supporting the reverse patch, it may be
4072 * worth showing the new sha1 prefix, but until then...
4074 for (patch = list; patch; patch = patch->next) {
4075 struct object_id oid;
4076 struct cache_entry *ce;
4079 name = patch->old_name ? patch->old_name : patch->new_name;
4080 if (0 < patch->is_new)
4083 if (S_ISGITLINK(patch->old_mode)) {
4084 if (!preimage_oid_in_gitlink_patch(patch, &oid))
4085 ; /* ok, the textual part looks sane */
4087 return error(_("sha1 information is lacking or "
4088 "useless for submodule %s"), name);
4089 } else if (!get_sha1_blob(patch->old_sha1_prefix, oid.hash)) {
4091 } else if (!patch->lines_added && !patch->lines_deleted) {
4092 /* mode-only change: update the current */
4093 if (get_current_oid(state, patch->old_name, &oid))
4094 return error(_("mode change for %s, which is not "
4095 "in current HEAD"), name);
4097 return error(_("sha1 information is lacking or useless "
4100 ce = make_cache_entry(patch->old_mode, oid.hash, name, 0, 0);
4102 return error(_("make_cache_entry failed for path '%s'"),
4104 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) {
4106 return error(_("could not add %s to temporary index"),
4111 hold_lock_file_for_update(&lock, state->fake_ancestor, LOCK_DIE_ON_ERROR);
4112 res = write_locked_index(&result, &lock, COMMIT_LOCK);
4113 discard_index(&result);
4116 return error(_("could not write temporary index to %s"),
4117 state->fake_ancestor);
4122 static void stat_patch_list(struct apply_state *state, struct patch *patch)
4124 int files, adds, dels;
4126 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
4128 adds += patch->lines_added;
4129 dels += patch->lines_deleted;
4130 show_stats(state, patch);
4133 print_stat_summary(stdout, files, adds, dels);
4136 static void numstat_patch_list(struct apply_state *state,
4137 struct patch *patch)
4139 for ( ; patch; patch = patch->next) {
4141 name = patch->new_name ? patch->new_name : patch->old_name;
4142 if (patch->is_binary)
4145 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
4146 write_name_quoted(name, stdout, state->line_termination);
4150 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
4153 printf(" %s mode %06o %s\n", newdelete, mode, name);
4155 printf(" %s %s\n", newdelete, name);
4158 static void show_mode_change(struct patch *p, int show_name)
4160 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
4162 printf(" mode change %06o => %06o %s\n",
4163 p->old_mode, p->new_mode, p->new_name);
4165 printf(" mode change %06o => %06o\n",
4166 p->old_mode, p->new_mode);
4170 static void show_rename_copy(struct patch *p)
4172 const char *renamecopy = p->is_rename ? "rename" : "copy";
4173 const char *old, *new;
4175 /* Find common prefix */
4179 const char *slash_old, *slash_new;
4180 slash_old = strchr(old, '/');
4181 slash_new = strchr(new, '/');
4184 slash_old - old != slash_new - new ||
4185 memcmp(old, new, slash_new - new))
4187 old = slash_old + 1;
4188 new = slash_new + 1;
4190 /* p->old_name thru old is the common prefix, and old and new
4191 * through the end of names are renames
4193 if (old != p->old_name)
4194 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
4195 (int)(old - p->old_name), p->old_name,
4196 old, new, p->score);
4198 printf(" %s %s => %s (%d%%)\n", renamecopy,
4199 p->old_name, p->new_name, p->score);
4200 show_mode_change(p, 0);
4203 static void summary_patch_list(struct patch *patch)
4207 for (p = patch; p; p = p->next) {
4209 show_file_mode_name("create", p->new_mode, p->new_name);
4210 else if (p->is_delete)
4211 show_file_mode_name("delete", p->old_mode, p->old_name);
4213 if (p->is_rename || p->is_copy)
4214 show_rename_copy(p);
4217 printf(" rewrite %s (%d%%)\n",
4218 p->new_name, p->score);
4219 show_mode_change(p, 0);
4222 show_mode_change(p, 1);
4228 static void patch_stats(struct apply_state *state, struct patch *patch)
4230 int lines = patch->lines_added + patch->lines_deleted;
4232 if (lines > state->max_change)
4233 state->max_change = lines;
4234 if (patch->old_name) {
4235 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
4237 len = strlen(patch->old_name);
4238 if (len > state->max_len)
4239 state->max_len = len;
4241 if (patch->new_name) {
4242 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
4244 len = strlen(patch->new_name);
4245 if (len > state->max_len)
4246 state->max_len = len;
4250 static int remove_file(struct apply_state *state, struct patch *patch, int rmdir_empty)
4252 if (state->update_index) {
4253 if (remove_file_from_cache(patch->old_name) < 0)
4254 return error(_("unable to remove %s from index"), patch->old_name);
4256 if (!state->cached) {
4257 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
4258 remove_path(patch->old_name);
4264 static int add_index_file(struct apply_state *state,
4271 struct cache_entry *ce;
4272 int namelen = strlen(path);
4273 unsigned ce_size = cache_entry_size(namelen);
4275 if (!state->update_index)
4278 ce = xcalloc(1, ce_size);
4279 memcpy(ce->name, path, namelen);
4280 ce->ce_mode = create_ce_mode(mode);
4281 ce->ce_flags = create_ce_flags(0);
4282 ce->ce_namelen = namelen;
4283 if (S_ISGITLINK(mode)) {
4286 if (!skip_prefix(buf, "Subproject commit ", &s) ||
4287 get_oid_hex(s, &ce->oid)) {
4289 return error(_("corrupt patch for submodule %s"), path);
4292 if (!state->cached) {
4293 if (lstat(path, &st) < 0) {
4295 return error_errno(_("unable to stat newly "
4296 "created file '%s'"),
4299 fill_stat_cache_info(ce, &st);
4301 if (write_sha1_file(buf, size, blob_type, ce->oid.hash) < 0) {
4303 return error(_("unable to create backing store "
4304 "for newly created file %s"), path);
4307 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0) {
4309 return error(_("unable to add cache entry for %s"), path);
4317 * -1 if an unrecoverable error happened
4318 * 0 if everything went well
4319 * 1 if a recoverable error happened
4321 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
4324 struct strbuf nbuf = STRBUF_INIT;
4326 if (S_ISGITLINK(mode)) {
4328 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
4330 return !!mkdir(path, 0777);
4333 if (has_symlinks && S_ISLNK(mode))
4334 /* Although buf:size is counted string, it also is NUL
4337 return !!symlink(buf, path);
4339 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
4343 if (convert_to_working_tree(path, buf, size, &nbuf)) {
4348 res = write_in_full(fd, buf, size) < 0;
4350 error_errno(_("failed to write to '%s'"), path);
4351 strbuf_release(&nbuf);
4353 if (close(fd) < 0 && !res)
4354 return error_errno(_("closing file '%s'"), path);
4356 return res ? -1 : 0;
4360 * We optimistically assume that the directories exist,
4361 * which is true 99% of the time anyway. If they don't,
4362 * we create them and try again.
4368 static int create_one_file(struct apply_state *state,
4379 res = try_create_file(path, mode, buf, size);
4385 if (errno == ENOENT) {
4386 if (safe_create_leading_directories(path))
4388 res = try_create_file(path, mode, buf, size);
4395 if (errno == EEXIST || errno == EACCES) {
4396 /* We may be trying to create a file where a directory
4400 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
4404 if (errno == EEXIST) {
4405 unsigned int nr = getpid();
4408 char newpath[PATH_MAX];
4409 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
4410 res = try_create_file(newpath, mode, buf, size);
4414 if (!rename(newpath, path))
4416 unlink_or_warn(newpath);
4419 if (errno != EEXIST)
4424 return error_errno(_("unable to write file '%s' mode %o"),
4428 static int add_conflicted_stages_file(struct apply_state *state,
4429 struct patch *patch)
4432 unsigned ce_size, mode;
4433 struct cache_entry *ce;
4435 if (!state->update_index)
4437 namelen = strlen(patch->new_name);
4438 ce_size = cache_entry_size(namelen);
4439 mode = patch->new_mode ? patch->new_mode : (S_IFREG | 0644);
4441 remove_file_from_cache(patch->new_name);
4442 for (stage = 1; stage < 4; stage++) {
4443 if (is_null_oid(&patch->threeway_stage[stage - 1]))
4445 ce = xcalloc(1, ce_size);
4446 memcpy(ce->name, patch->new_name, namelen);
4447 ce->ce_mode = create_ce_mode(mode);
4448 ce->ce_flags = create_ce_flags(stage);
4449 ce->ce_namelen = namelen;
4450 oidcpy(&ce->oid, &patch->threeway_stage[stage - 1]);
4451 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0) {
4453 return error(_("unable to add cache entry for %s"),
4461 static int create_file(struct apply_state *state, struct patch *patch)
4463 char *path = patch->new_name;
4464 unsigned mode = patch->new_mode;
4465 unsigned long size = patch->resultsize;
4466 char *buf = patch->result;
4469 mode = S_IFREG | 0644;
4470 if (create_one_file(state, path, mode, buf, size))
4473 if (patch->conflicted_threeway)
4474 return add_conflicted_stages_file(state, patch);
4476 return add_index_file(state, path, mode, buf, size);
4479 /* phase zero is to remove, phase one is to create */
4480 static int write_out_one_result(struct apply_state *state,
4481 struct patch *patch,
4484 if (patch->is_delete > 0) {
4486 return remove_file(state, patch, 1);
4489 if (patch->is_new > 0 || patch->is_copy) {
4491 return create_file(state, patch);
4495 * Rename or modification boils down to the same
4496 * thing: remove the old, write the new
4499 return remove_file(state, patch, patch->is_rename);
4501 return create_file(state, patch);
4505 static int write_out_one_reject(struct apply_state *state, struct patch *patch)
4508 char namebuf[PATH_MAX];
4509 struct fragment *frag;
4511 struct strbuf sb = STRBUF_INIT;
4513 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
4514 if (!frag->rejected)
4520 if (state->apply_verbosity > verbosity_normal)
4521 say_patch_name(stderr,
4522 _("Applied patch %s cleanly."), patch);
4526 /* This should not happen, because a removal patch that leaves
4527 * contents are marked "rejected" at the patch level.
4529 if (!patch->new_name)
4530 die(_("internal error"));
4532 /* Say this even without --verbose */
4533 strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",
4534 "Applying patch %%s with %d rejects...",
4537 if (state->apply_verbosity > verbosity_silent)
4538 say_patch_name(stderr, sb.buf, patch);
4539 strbuf_release(&sb);
4541 cnt = strlen(patch->new_name);
4542 if (ARRAY_SIZE(namebuf) <= cnt + 5) {
4543 cnt = ARRAY_SIZE(namebuf) - 5;
4544 warning(_("truncating .rej filename to %.*s.rej"),
4545 cnt - 1, patch->new_name);
4547 memcpy(namebuf, patch->new_name, cnt);
4548 memcpy(namebuf + cnt, ".rej", 5);
4550 rej = fopen(namebuf, "w");
4552 return error_errno(_("cannot open %s"), namebuf);
4554 /* Normal git tools never deal with .rej, so do not pretend
4555 * this is a git patch by saying --git or giving extended
4556 * headers. While at it, maybe please "kompare" that wants
4557 * the trailing TAB and some garbage at the end of line ;-).
4559 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
4560 patch->new_name, patch->new_name);
4561 for (cnt = 1, frag = patch->fragments;
4563 cnt++, frag = frag->next) {
4564 if (!frag->rejected) {
4565 if (state->apply_verbosity > verbosity_silent)
4566 fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);
4569 if (state->apply_verbosity > verbosity_silent)
4570 fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);
4571 fprintf(rej, "%.*s", frag->size, frag->patch);
4572 if (frag->patch[frag->size-1] != '\n')
4581 * -1 if an error happened
4582 * 0 if the patch applied cleanly
4583 * 1 if the patch did not apply cleanly
4585 static int write_out_results(struct apply_state *state, struct patch *list)
4590 struct string_list cpath = STRING_LIST_INIT_DUP;
4592 for (phase = 0; phase < 2; phase++) {
4598 if (write_out_one_result(state, l, phase)) {
4599 string_list_clear(&cpath, 0);
4603 if (write_out_one_reject(state, l))
4605 if (l->conflicted_threeway) {
4606 string_list_append(&cpath, l->new_name);
4616 struct string_list_item *item;
4618 string_list_sort(&cpath);
4619 if (state->apply_verbosity > verbosity_silent) {
4620 for_each_string_list_item(item, &cpath)
4621 fprintf(stderr, "U %s\n", item->string);
4623 string_list_clear(&cpath, 0);
4632 * Try to apply a patch.
4635 * -128 if a bad error happened (like patch unreadable)
4636 * -1 if patch did not apply and user cannot deal with it
4637 * 0 if the patch applied
4638 * 1 if the patch did not apply but user might fix it
4640 static int apply_patch(struct apply_state *state,
4642 const char *filename,
4646 struct strbuf buf = STRBUF_INIT; /* owns the patch text */
4647 struct patch *list = NULL, **listp = &list;
4648 int skipped_patch = 0;
4651 state->patch_input_file = filename;
4652 if (read_patch_file(&buf, fd) < 0)
4655 while (offset < buf.len) {
4656 struct patch *patch;
4659 patch = xcalloc(1, sizeof(*patch));
4660 patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF);
4661 patch->recount = !!(options & APPLY_OPT_RECOUNT);
4662 nr = parse_chunk(state, buf.buf + offset, buf.len - offset, patch);
4671 if (state->apply_in_reverse)
4672 reverse_patches(patch);
4673 if (use_patch(state, patch)) {
4674 patch_stats(state, patch);
4676 listp = &patch->next;
4679 if (state->apply_verbosity > verbosity_normal)
4680 say_patch_name(stderr, _("Skipped patch '%s'."), patch);
4687 if (!list && !skipped_patch) {
4688 error(_("unrecognized input"));
4693 if (state->whitespace_error && (state->ws_error_action == die_on_ws_error))
4696 state->update_index = state->check_index && state->apply;
4697 if (state->update_index && state->newfd < 0) {
4698 if (state->index_file)
4699 state->newfd = hold_lock_file_for_update(state->lock_file,
4703 state->newfd = hold_locked_index(state->lock_file, LOCK_DIE_ON_ERROR);
4706 if (state->check_index && read_apply_cache(state) < 0) {
4707 error(_("unable to read index file"));
4712 if (state->check || state->apply) {
4713 int r = check_patch_list(state, list);
4718 if (r < 0 && !state->apply_with_reject) {
4725 int write_res = write_out_results(state, list);
4726 if (write_res < 0) {
4730 if (write_res > 0) {
4731 /* with --3way, we still need to write the index out */
4732 res = state->apply_with_reject ? -1 : 1;
4737 if (state->fake_ancestor &&
4738 build_fake_ancestor(state, list)) {
4743 if (state->diffstat && state->apply_verbosity > verbosity_silent)
4744 stat_patch_list(state, list);
4746 if (state->numstat && state->apply_verbosity > verbosity_silent)
4747 numstat_patch_list(state, list);
4749 if (state->summary && state->apply_verbosity > verbosity_silent)
4750 summary_patch_list(list);
4753 free_patch_list(list);
4754 strbuf_release(&buf);
4755 string_list_clear(&state->fn_table, 0);
4759 static int apply_option_parse_exclude(const struct option *opt,
4760 const char *arg, int unset)
4762 struct apply_state *state = opt->value;
4763 add_name_limit(state, arg, 1);
4767 static int apply_option_parse_include(const struct option *opt,
4768 const char *arg, int unset)
4770 struct apply_state *state = opt->value;
4771 add_name_limit(state, arg, 0);
4772 state->has_include = 1;
4776 static int apply_option_parse_p(const struct option *opt,
4780 struct apply_state *state = opt->value;
4781 state->p_value = atoi(arg);
4782 state->p_value_known = 1;
4786 static int apply_option_parse_space_change(const struct option *opt,
4787 const char *arg, int unset)
4789 struct apply_state *state = opt->value;
4791 state->ws_ignore_action = ignore_ws_none;
4793 state->ws_ignore_action = ignore_ws_change;
4797 static int apply_option_parse_whitespace(const struct option *opt,
4798 const char *arg, int unset)
4800 struct apply_state *state = opt->value;
4801 state->whitespace_option = arg;
4802 if (parse_whitespace_option(state, arg))
4807 static int apply_option_parse_directory(const struct option *opt,
4808 const char *arg, int unset)
4810 struct apply_state *state = opt->value;
4811 strbuf_reset(&state->root);
4812 strbuf_addstr(&state->root, arg);
4813 strbuf_complete(&state->root, '/');
4817 int apply_all_patches(struct apply_state *state,
4827 for (i = 0; i < argc; i++) {
4828 const char *arg = argv[i];
4829 char *to_free = NULL;
4832 if (!strcmp(arg, "-")) {
4833 res = apply_patch(state, 0, "<stdin>", options);
4840 arg = to_free = prefix_filename(state->prefix, arg);
4842 fd = open(arg, O_RDONLY);
4844 error(_("can't open patch '%s': %s"), arg, strerror(errno));
4850 set_default_whitespace_mode(state);
4851 res = apply_patch(state, fd, arg, options);
4858 set_default_whitespace_mode(state);
4860 res = apply_patch(state, 0, "<stdin>", options);
4866 if (state->whitespace_error) {
4867 if (state->squelch_whitespace_errors &&
4868 state->squelch_whitespace_errors < state->whitespace_error) {
4870 state->whitespace_error - state->squelch_whitespace_errors;
4871 warning(Q_("squelched %d whitespace error",
4872 "squelched %d whitespace errors",
4876 if (state->ws_error_action == die_on_ws_error) {
4877 error(Q_("%d line adds whitespace errors.",
4878 "%d lines add whitespace errors.",
4879 state->whitespace_error),
4880 state->whitespace_error);
4884 if (state->applied_after_fixing_ws && state->apply)
4885 warning(Q_("%d line applied after"
4886 " fixing whitespace errors.",
4887 "%d lines applied after"
4888 " fixing whitespace errors.",
4889 state->applied_after_fixing_ws),
4890 state->applied_after_fixing_ws);
4891 else if (state->whitespace_error)
4892 warning(Q_("%d line adds whitespace errors.",
4893 "%d lines add whitespace errors.",
4894 state->whitespace_error),
4895 state->whitespace_error);
4898 if (state->update_index) {
4899 res = write_locked_index(&the_index, state->lock_file, COMMIT_LOCK);
4901 error(_("Unable to write new index file"));
4911 if (state->newfd >= 0) {
4912 rollback_lock_file(state->lock_file);
4916 if (state->apply_verbosity <= verbosity_silent) {
4917 set_error_routine(state->saved_error_routine);
4918 set_warn_routine(state->saved_warn_routine);
4923 return (res == -1 ? 1 : 128);
4926 int apply_parse_options(int argc, const char **argv,
4927 struct apply_state *state,
4928 int *force_apply, int *options,
4929 const char * const *apply_usage)
4931 struct option builtin_apply_options[] = {
4932 { OPTION_CALLBACK, 0, "exclude", state, N_("path"),
4933 N_("don't apply changes matching the given path"),
4934 0, apply_option_parse_exclude },
4935 { OPTION_CALLBACK, 0, "include", state, N_("path"),
4936 N_("apply changes matching the given path"),
4937 0, apply_option_parse_include },
4938 { OPTION_CALLBACK, 'p', NULL, state, N_("num"),
4939 N_("remove <num> leading slashes from traditional diff paths"),
4940 0, apply_option_parse_p },
4941 OPT_BOOL(0, "no-add", &state->no_add,
4942 N_("ignore additions made by the patch")),
4943 OPT_BOOL(0, "stat", &state->diffstat,
4944 N_("instead of applying the patch, output diffstat for the input")),
4945 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
4946 OPT_NOOP_NOARG(0, "binary"),
4947 OPT_BOOL(0, "numstat", &state->numstat,
4948 N_("show number of added and deleted lines in decimal notation")),
4949 OPT_BOOL(0, "summary", &state->summary,
4950 N_("instead of applying the patch, output a summary for the input")),
4951 OPT_BOOL(0, "check", &state->check,
4952 N_("instead of applying the patch, see if the patch is applicable")),
4953 OPT_BOOL(0, "index", &state->check_index,
4954 N_("make sure the patch is applicable to the current index")),
4955 OPT_BOOL(0, "cached", &state->cached,
4956 N_("apply a patch without touching the working tree")),
4957 OPT_BOOL(0, "unsafe-paths", &state->unsafe_paths,
4958 N_("accept a patch that touches outside the working area")),
4959 OPT_BOOL(0, "apply", force_apply,
4960 N_("also apply the patch (use with --stat/--summary/--check)")),
4961 OPT_BOOL('3', "3way", &state->threeway,
4962 N_( "attempt three-way merge if a patch does not apply")),
4963 OPT_FILENAME(0, "build-fake-ancestor", &state->fake_ancestor,
4964 N_("build a temporary index based on embedded index information")),
4965 /* Think twice before adding "--nul" synonym to this */
4966 OPT_SET_INT('z', NULL, &state->line_termination,
4967 N_("paths are separated with NUL character"), '\0'),
4968 OPT_INTEGER('C', NULL, &state->p_context,
4969 N_("ensure at least <n> lines of context match")),
4970 { OPTION_CALLBACK, 0, "whitespace", state, N_("action"),
4971 N_("detect new or modified lines that have whitespace errors"),
4972 0, apply_option_parse_whitespace },
4973 { OPTION_CALLBACK, 0, "ignore-space-change", state, NULL,
4974 N_("ignore changes in whitespace when finding context"),
4975 PARSE_OPT_NOARG, apply_option_parse_space_change },
4976 { OPTION_CALLBACK, 0, "ignore-whitespace", state, NULL,
4977 N_("ignore changes in whitespace when finding context"),
4978 PARSE_OPT_NOARG, apply_option_parse_space_change },
4979 OPT_BOOL('R', "reverse", &state->apply_in_reverse,
4980 N_("apply the patch in reverse")),
4981 OPT_BOOL(0, "unidiff-zero", &state->unidiff_zero,
4982 N_("don't expect at least one line of context")),
4983 OPT_BOOL(0, "reject", &state->apply_with_reject,
4984 N_("leave the rejected hunks in corresponding *.rej files")),
4985 OPT_BOOL(0, "allow-overlap", &state->allow_overlap,
4986 N_("allow overlapping hunks")),
4987 OPT__VERBOSE(&state->apply_verbosity, N_("be verbose")),
4988 OPT_BIT(0, "inaccurate-eof", options,
4989 N_("tolerate incorrectly detected missing new-line at the end of file"),
4990 APPLY_OPT_INACCURATE_EOF),
4991 OPT_BIT(0, "recount", options,
4992 N_("do not trust the line counts in the hunk headers"),
4994 { OPTION_CALLBACK, 0, "directory", state, N_("root"),
4995 N_("prepend <root> to all filenames"),
4996 0, apply_option_parse_directory },
5000 return parse_options(argc, argv, state->prefix, builtin_apply_options, apply_usage, 0);