dir.h: move DTYPE defines from cache.h
[git.git] / apply.c
blob2de8bb203d72ef9caf6ccedd6e0dc98ce8409393
1 /*
2 * apply.c
4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
8 */
10 #include "cache.h"
11 #include "abspath.h"
12 #include "alloc.h"
13 #include "base85.h"
14 #include "config.h"
15 #include "object-store.h"
16 #include "blob.h"
17 #include "delta.h"
18 #include "diff.h"
19 #include "dir.h"
20 #include "environment.h"
21 #include "gettext.h"
22 #include "hex.h"
23 #include "xdiff-interface.h"
24 #include "ll-merge.h"
25 #include "lockfile.h"
26 #include "object-name.h"
27 #include "object-file.h"
28 #include "parse-options.h"
29 #include "quote.h"
30 #include "rerere.h"
31 #include "apply.h"
32 #include "entry.h"
33 #include "setup.h"
34 #include "symlinks.h"
35 #include "ws.h"
36 #include "wrapper.h"
38 struct gitdiff_data {
39 struct strbuf *root;
40 int linenr;
41 int p_value;
44 static void git_apply_config(void)
46 git_config_get_string("apply.whitespace", &apply_default_whitespace);
47 git_config_get_string("apply.ignorewhitespace", &apply_default_ignorewhitespace);
48 git_config(git_xmerge_config, NULL);
51 static int parse_whitespace_option(struct apply_state *state, const char *option)
53 if (!option) {
54 state->ws_error_action = warn_on_ws_error;
55 return 0;
57 if (!strcmp(option, "warn")) {
58 state->ws_error_action = warn_on_ws_error;
59 return 0;
61 if (!strcmp(option, "nowarn")) {
62 state->ws_error_action = nowarn_ws_error;
63 return 0;
65 if (!strcmp(option, "error")) {
66 state->ws_error_action = die_on_ws_error;
67 return 0;
69 if (!strcmp(option, "error-all")) {
70 state->ws_error_action = die_on_ws_error;
71 state->squelch_whitespace_errors = 0;
72 return 0;
74 if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
75 state->ws_error_action = correct_ws_error;
76 return 0;
79 * Please update $__git_whitespacelist in git-completion.bash
80 * when you add new options.
82 return error(_("unrecognized whitespace option '%s'"), option);
85 static int parse_ignorewhitespace_option(struct apply_state *state,
86 const char *option)
88 if (!option || !strcmp(option, "no") ||
89 !strcmp(option, "false") || !strcmp(option, "never") ||
90 !strcmp(option, "none")) {
91 state->ws_ignore_action = ignore_ws_none;
92 return 0;
94 if (!strcmp(option, "change")) {
95 state->ws_ignore_action = ignore_ws_change;
96 return 0;
98 return error(_("unrecognized whitespace ignore option '%s'"), option);
101 int init_apply_state(struct apply_state *state,
102 struct repository *repo,
103 const char *prefix)
105 memset(state, 0, sizeof(*state));
106 state->prefix = prefix;
107 state->repo = repo;
108 state->apply = 1;
109 state->line_termination = '\n';
110 state->p_value = 1;
111 state->p_context = UINT_MAX;
112 state->squelch_whitespace_errors = 5;
113 state->ws_error_action = warn_on_ws_error;
114 state->ws_ignore_action = ignore_ws_none;
115 state->linenr = 1;
116 string_list_init_nodup(&state->fn_table);
117 string_list_init_nodup(&state->limit_by_name);
118 strset_init(&state->removed_symlinks);
119 strset_init(&state->kept_symlinks);
120 strbuf_init(&state->root, 0);
122 git_apply_config();
123 if (apply_default_whitespace && parse_whitespace_option(state, apply_default_whitespace))
124 return -1;
125 if (apply_default_ignorewhitespace && parse_ignorewhitespace_option(state, apply_default_ignorewhitespace))
126 return -1;
127 return 0;
130 void clear_apply_state(struct apply_state *state)
132 string_list_clear(&state->limit_by_name, 0);
133 strset_clear(&state->removed_symlinks);
134 strset_clear(&state->kept_symlinks);
135 strbuf_release(&state->root);
137 /* &state->fn_table is cleared at the end of apply_patch() */
140 static void mute_routine(const char *msg UNUSED, va_list params UNUSED)
142 /* do nothing */
145 int check_apply_state(struct apply_state *state, int force_apply)
147 int is_not_gitdir = !startup_info->have_repository;
149 if (state->apply_with_reject && state->threeway)
150 return error(_("options '%s' and '%s' cannot be used together"), "--reject", "--3way");
151 if (state->threeway) {
152 if (is_not_gitdir)
153 return error(_("'%s' outside a repository"), "--3way");
154 state->check_index = 1;
156 if (state->apply_with_reject) {
157 state->apply = 1;
158 if (state->apply_verbosity == verbosity_normal)
159 state->apply_verbosity = verbosity_verbose;
161 if (!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor))
162 state->apply = 0;
163 if (state->check_index && is_not_gitdir)
164 return error(_("'%s' outside a repository"), "--index");
165 if (state->cached) {
166 if (is_not_gitdir)
167 return error(_("'%s' outside a repository"), "--cached");
168 state->check_index = 1;
170 if (state->ita_only && (state->check_index || is_not_gitdir))
171 state->ita_only = 0;
172 if (state->check_index)
173 state->unsafe_paths = 0;
175 if (state->apply_verbosity <= verbosity_silent) {
176 state->saved_error_routine = get_error_routine();
177 state->saved_warn_routine = get_warn_routine();
178 set_error_routine(mute_routine);
179 set_warn_routine(mute_routine);
182 return 0;
185 static void set_default_whitespace_mode(struct apply_state *state)
187 if (!state->whitespace_option && !apply_default_whitespace)
188 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error);
192 * This represents one "hunk" from a patch, starting with
193 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
194 * patch text is pointed at by patch, and its byte length
195 * is stored in size. leading and trailing are the number
196 * of context lines.
198 struct fragment {
199 unsigned long leading, trailing;
200 unsigned long oldpos, oldlines;
201 unsigned long newpos, newlines;
203 * 'patch' is usually borrowed from buf in apply_patch(),
204 * but some codepaths store an allocated buffer.
206 const char *patch;
207 unsigned free_patch:1,
208 rejected:1;
209 int size;
210 int linenr;
211 struct fragment *next;
215 * When dealing with a binary patch, we reuse "leading" field
216 * to store the type of the binary hunk, either deflated "delta"
217 * or deflated "literal".
219 #define binary_patch_method leading
220 #define BINARY_DELTA_DEFLATED 1
221 #define BINARY_LITERAL_DEFLATED 2
223 static void free_fragment_list(struct fragment *list)
225 while (list) {
226 struct fragment *next = list->next;
227 if (list->free_patch)
228 free((char *)list->patch);
229 free(list);
230 list = next;
234 void release_patch(struct patch *patch)
236 free_fragment_list(patch->fragments);
237 free(patch->def_name);
238 free(patch->old_name);
239 free(patch->new_name);
240 free(patch->result);
243 static void free_patch(struct patch *patch)
245 release_patch(patch);
246 free(patch);
249 static void free_patch_list(struct patch *list)
251 while (list) {
252 struct patch *next = list->next;
253 free_patch(list);
254 list = next;
259 * A line in a file, len-bytes long (includes the terminating LF,
260 * except for an incomplete line at the end if the file ends with
261 * one), and its contents hashes to 'hash'.
263 struct line {
264 size_t len;
265 unsigned hash : 24;
266 unsigned flag : 8;
267 #define LINE_COMMON 1
268 #define LINE_PATCHED 2
272 * This represents a "file", which is an array of "lines".
274 struct image {
275 char *buf;
276 size_t len;
277 size_t nr;
278 size_t alloc;
279 struct line *line_allocated;
280 struct line *line;
283 static uint32_t hash_line(const char *cp, size_t len)
285 size_t i;
286 uint32_t h;
287 for (i = 0, h = 0; i < len; i++) {
288 if (!isspace(cp[i])) {
289 h = h * 3 + (cp[i] & 0xff);
292 return h;
296 * Compare lines s1 of length n1 and s2 of length n2, ignoring
297 * whitespace difference. Returns 1 if they match, 0 otherwise
299 static int fuzzy_matchlines(const char *s1, size_t n1,
300 const char *s2, size_t n2)
302 const char *end1 = s1 + n1;
303 const char *end2 = s2 + n2;
305 /* ignore line endings */
306 while (s1 < end1 && (end1[-1] == '\r' || end1[-1] == '\n'))
307 end1--;
308 while (s2 < end2 && (end2[-1] == '\r' || end2[-1] == '\n'))
309 end2--;
311 while (s1 < end1 && s2 < end2) {
312 if (isspace(*s1)) {
314 * Skip whitespace. We check on both buffers
315 * because we don't want "a b" to match "ab".
317 if (!isspace(*s2))
318 return 0;
319 while (s1 < end1 && isspace(*s1))
320 s1++;
321 while (s2 < end2 && isspace(*s2))
322 s2++;
323 } else if (*s1++ != *s2++)
324 return 0;
327 /* If we reached the end on one side only, lines don't match. */
328 return s1 == end1 && s2 == end2;
331 static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
333 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
334 img->line_allocated[img->nr].len = len;
335 img->line_allocated[img->nr].hash = hash_line(bol, len);
336 img->line_allocated[img->nr].flag = flag;
337 img->nr++;
341 * "buf" has the file contents to be patched (read from various sources).
342 * attach it to "image" and add line-based index to it.
343 * "image" now owns the "buf".
345 static void prepare_image(struct image *image, char *buf, size_t len,
346 int prepare_linetable)
348 const char *cp, *ep;
350 memset(image, 0, sizeof(*image));
351 image->buf = buf;
352 image->len = len;
354 if (!prepare_linetable)
355 return;
357 ep = image->buf + image->len;
358 cp = image->buf;
359 while (cp < ep) {
360 const char *next;
361 for (next = cp; next < ep && *next != '\n'; next++)
363 if (next < ep)
364 next++;
365 add_line_info(image, cp, next - cp, 0);
366 cp = next;
368 image->line = image->line_allocated;
371 static void clear_image(struct image *image)
373 free(image->buf);
374 free(image->line_allocated);
375 memset(image, 0, sizeof(*image));
378 /* fmt must contain _one_ %s and no other substitution */
379 static void say_patch_name(FILE *output, const char *fmt, struct patch *patch)
381 struct strbuf sb = STRBUF_INIT;
383 if (patch->old_name && patch->new_name &&
384 strcmp(patch->old_name, patch->new_name)) {
385 quote_c_style(patch->old_name, &sb, NULL, 0);
386 strbuf_addstr(&sb, " => ");
387 quote_c_style(patch->new_name, &sb, NULL, 0);
388 } else {
389 const char *n = patch->new_name;
390 if (!n)
391 n = patch->old_name;
392 quote_c_style(n, &sb, NULL, 0);
394 fprintf(output, fmt, sb.buf);
395 fputc('\n', output);
396 strbuf_release(&sb);
399 #define SLOP (16)
402 * apply.c isn't equipped to handle arbitrarily large patches, because
403 * it intermingles `unsigned long` with `int` for the type used to store
404 * buffer lengths.
406 * Only process patches that are just shy of 1 GiB large in order to
407 * avoid any truncation or overflow issues.
409 #define MAX_APPLY_SIZE (1024UL * 1024 * 1023)
411 static int read_patch_file(struct strbuf *sb, int fd)
413 if (strbuf_read(sb, fd, 0) < 0 || sb->len >= MAX_APPLY_SIZE)
414 return error_errno("git apply: failed to read");
417 * Make sure that we have some slop in the buffer
418 * so that we can do speculative "memcmp" etc, and
419 * see to it that it is NUL-filled.
421 strbuf_grow(sb, SLOP);
422 memset(sb->buf + sb->len, 0, SLOP);
423 return 0;
426 static unsigned long linelen(const char *buffer, unsigned long size)
428 unsigned long len = 0;
429 while (size--) {
430 len++;
431 if (*buffer++ == '\n')
432 break;
434 return len;
437 static int is_dev_null(const char *str)
439 return skip_prefix(str, "/dev/null", &str) && isspace(*str);
442 #define TERM_SPACE 1
443 #define TERM_TAB 2
445 static int name_terminate(int c, int terminate)
447 if (c == ' ' && !(terminate & TERM_SPACE))
448 return 0;
449 if (c == '\t' && !(terminate & TERM_TAB))
450 return 0;
452 return 1;
455 /* remove double slashes to make --index work with such filenames */
456 static char *squash_slash(char *name)
458 int i = 0, j = 0;
460 if (!name)
461 return NULL;
463 while (name[i]) {
464 if ((name[j++] = name[i++]) == '/')
465 while (name[i] == '/')
466 i++;
468 name[j] = '\0';
469 return name;
472 static char *find_name_gnu(struct strbuf *root,
473 const char *line,
474 int p_value)
476 struct strbuf name = STRBUF_INIT;
477 char *cp;
480 * Proposed "new-style" GNU patch/diff format; see
481 * https://lore.kernel.org/git/7vll0wvb2a.fsf@assigned-by-dhcp.cox.net/
483 if (unquote_c_style(&name, line, NULL)) {
484 strbuf_release(&name);
485 return NULL;
488 for (cp = name.buf; p_value; p_value--) {
489 cp = strchr(cp, '/');
490 if (!cp) {
491 strbuf_release(&name);
492 return NULL;
494 cp++;
497 strbuf_remove(&name, 0, cp - name.buf);
498 if (root->len)
499 strbuf_insert(&name, 0, root->buf, root->len);
500 return squash_slash(strbuf_detach(&name, NULL));
503 static size_t sane_tz_len(const char *line, size_t len)
505 const char *tz, *p;
507 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
508 return 0;
509 tz = line + len - strlen(" +0500");
511 if (tz[1] != '+' && tz[1] != '-')
512 return 0;
514 for (p = tz + 2; p != line + len; p++)
515 if (!isdigit(*p))
516 return 0;
518 return line + len - tz;
521 static size_t tz_with_colon_len(const char *line, size_t len)
523 const char *tz, *p;
525 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
526 return 0;
527 tz = line + len - strlen(" +08:00");
529 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
530 return 0;
531 p = tz + 2;
532 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
533 !isdigit(*p++) || !isdigit(*p++))
534 return 0;
536 return line + len - tz;
539 static size_t date_len(const char *line, size_t len)
541 const char *date, *p;
543 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
544 return 0;
545 p = date = line + len - strlen("72-02-05");
547 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
548 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
549 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */
550 return 0;
552 if (date - line >= strlen("19") &&
553 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */
554 date -= strlen("19");
556 return line + len - date;
559 static size_t short_time_len(const char *line, size_t len)
561 const char *time, *p;
563 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
564 return 0;
565 p = time = line + len - strlen(" 07:01:32");
567 /* Permit 1-digit hours? */
568 if (*p++ != ' ' ||
569 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
570 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
571 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */
572 return 0;
574 return line + len - time;
577 static size_t fractional_time_len(const char *line, size_t len)
579 const char *p;
580 size_t n;
582 /* Expected format: 19:41:17.620000023 */
583 if (!len || !isdigit(line[len - 1]))
584 return 0;
585 p = line + len - 1;
587 /* Fractional seconds. */
588 while (p > line && isdigit(*p))
589 p--;
590 if (*p != '.')
591 return 0;
593 /* Hours, minutes, and whole seconds. */
594 n = short_time_len(line, p - line);
595 if (!n)
596 return 0;
598 return line + len - p + n;
601 static size_t trailing_spaces_len(const char *line, size_t len)
603 const char *p;
605 /* Expected format: ' ' x (1 or more) */
606 if (!len || line[len - 1] != ' ')
607 return 0;
609 p = line + len;
610 while (p != line) {
611 p--;
612 if (*p != ' ')
613 return line + len - (p + 1);
616 /* All spaces! */
617 return len;
620 static size_t diff_timestamp_len(const char *line, size_t len)
622 const char *end = line + len;
623 size_t n;
626 * Posix: 2010-07-05 19:41:17
627 * GNU: 2010-07-05 19:41:17.620000023 -0500
630 if (!isdigit(end[-1]))
631 return 0;
633 n = sane_tz_len(line, end - line);
634 if (!n)
635 n = tz_with_colon_len(line, end - line);
636 end -= n;
638 n = short_time_len(line, end - line);
639 if (!n)
640 n = fractional_time_len(line, end - line);
641 end -= n;
643 n = date_len(line, end - line);
644 if (!n) /* No date. Too bad. */
645 return 0;
646 end -= n;
648 if (end == line) /* No space before date. */
649 return 0;
650 if (end[-1] == '\t') { /* Success! */
651 end--;
652 return line + len - end;
654 if (end[-1] != ' ') /* No space before date. */
655 return 0;
657 /* Whitespace damage. */
658 end -= trailing_spaces_len(line, end - line);
659 return line + len - end;
662 static char *find_name_common(struct strbuf *root,
663 const char *line,
664 const char *def,
665 int p_value,
666 const char *end,
667 int terminate)
669 int len;
670 const char *start = NULL;
672 if (p_value == 0)
673 start = line;
674 while (line != end) {
675 char c = *line;
677 if (!end && isspace(c)) {
678 if (c == '\n')
679 break;
680 if (name_terminate(c, terminate))
681 break;
683 line++;
684 if (c == '/' && !--p_value)
685 start = line;
687 if (!start)
688 return squash_slash(xstrdup_or_null(def));
689 len = line - start;
690 if (!len)
691 return squash_slash(xstrdup_or_null(def));
694 * Generally we prefer the shorter name, especially
695 * if the other one is just a variation of that with
696 * something else tacked on to the end (ie "file.orig"
697 * or "file~").
699 if (def) {
700 int deflen = strlen(def);
701 if (deflen < len && !strncmp(start, def, deflen))
702 return squash_slash(xstrdup(def));
705 if (root->len) {
706 char *ret = xstrfmt("%s%.*s", root->buf, len, start);
707 return squash_slash(ret);
710 return squash_slash(xmemdupz(start, len));
713 static char *find_name(struct strbuf *root,
714 const char *line,
715 char *def,
716 int p_value,
717 int terminate)
719 if (*line == '"') {
720 char *name = find_name_gnu(root, line, p_value);
721 if (name)
722 return name;
725 return find_name_common(root, line, def, p_value, NULL, terminate);
728 static char *find_name_traditional(struct strbuf *root,
729 const char *line,
730 char *def,
731 int p_value)
733 size_t len;
734 size_t date_len;
736 if (*line == '"') {
737 char *name = find_name_gnu(root, line, p_value);
738 if (name)
739 return name;
742 len = strchrnul(line, '\n') - line;
743 date_len = diff_timestamp_len(line, len);
744 if (!date_len)
745 return find_name_common(root, line, def, p_value, NULL, TERM_TAB);
746 len -= date_len;
748 return find_name_common(root, line, def, p_value, line + len, 0);
752 * Given the string after "--- " or "+++ ", guess the appropriate
753 * p_value for the given patch.
755 static int guess_p_value(struct apply_state *state, const char *nameline)
757 char *name, *cp;
758 int val = -1;
760 if (is_dev_null(nameline))
761 return -1;
762 name = find_name_traditional(&state->root, nameline, NULL, 0);
763 if (!name)
764 return -1;
765 cp = strchr(name, '/');
766 if (!cp)
767 val = 0;
768 else if (state->prefix) {
770 * Does it begin with "a/$our-prefix" and such? Then this is
771 * very likely to apply to our directory.
773 if (starts_with(name, state->prefix))
774 val = count_slashes(state->prefix);
775 else {
776 cp++;
777 if (starts_with(cp, state->prefix))
778 val = count_slashes(state->prefix) + 1;
781 free(name);
782 return val;
786 * Does the ---/+++ line have the POSIX timestamp after the last HT?
787 * GNU diff puts epoch there to signal a creation/deletion event. Is
788 * this such a timestamp?
790 static int has_epoch_timestamp(const char *nameline)
793 * We are only interested in epoch timestamp; any non-zero
794 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
795 * For the same reason, the date must be either 1969-12-31 or
796 * 1970-01-01, and the seconds part must be "00".
798 const char stamp_regexp[] =
799 "^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?"
801 "([-+][0-2][0-9]:?[0-5][0-9])\n";
802 const char *timestamp = NULL, *cp, *colon;
803 static regex_t *stamp;
804 regmatch_t m[10];
805 int zoneoffset, epoch_hour, hour, minute;
806 int status;
808 for (cp = nameline; *cp != '\n'; cp++) {
809 if (*cp == '\t')
810 timestamp = cp + 1;
812 if (!timestamp)
813 return 0;
816 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
817 * (west of GMT) or 1970-01-01 (east of GMT)
819 if (skip_prefix(timestamp, "1969-12-31 ", &timestamp))
820 epoch_hour = 24;
821 else if (skip_prefix(timestamp, "1970-01-01 ", &timestamp))
822 epoch_hour = 0;
823 else
824 return 0;
826 if (!stamp) {
827 stamp = xmalloc(sizeof(*stamp));
828 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
829 warning(_("Cannot prepare timestamp regexp %s"),
830 stamp_regexp);
831 return 0;
835 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
836 if (status) {
837 if (status != REG_NOMATCH)
838 warning(_("regexec returned %d for input: %s"),
839 status, timestamp);
840 return 0;
843 hour = strtol(timestamp, NULL, 10);
844 minute = strtol(timestamp + m[1].rm_so, NULL, 10);
846 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
847 if (*colon == ':')
848 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
849 else
850 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
851 if (timestamp[m[3].rm_so] == '-')
852 zoneoffset = -zoneoffset;
854 return hour * 60 + minute - zoneoffset == epoch_hour * 60;
858 * Get the name etc info from the ---/+++ lines of a traditional patch header
860 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
861 * files, we can happily check the index for a match, but for creating a
862 * new file we should try to match whatever "patch" does. I have no idea.
864 static int parse_traditional_patch(struct apply_state *state,
865 const char *first,
866 const char *second,
867 struct patch *patch)
869 char *name;
871 first += 4; /* skip "--- " */
872 second += 4; /* skip "+++ " */
873 if (!state->p_value_known) {
874 int p, q;
875 p = guess_p_value(state, first);
876 q = guess_p_value(state, second);
877 if (p < 0) p = q;
878 if (0 <= p && p == q) {
879 state->p_value = p;
880 state->p_value_known = 1;
883 if (is_dev_null(first)) {
884 patch->is_new = 1;
885 patch->is_delete = 0;
886 name = find_name_traditional(&state->root, second, NULL, state->p_value);
887 patch->new_name = name;
888 } else if (is_dev_null(second)) {
889 patch->is_new = 0;
890 patch->is_delete = 1;
891 name = find_name_traditional(&state->root, first, NULL, state->p_value);
892 patch->old_name = name;
893 } else {
894 char *first_name;
895 first_name = find_name_traditional(&state->root, first, NULL, state->p_value);
896 name = find_name_traditional(&state->root, second, first_name, state->p_value);
897 free(first_name);
898 if (has_epoch_timestamp(first)) {
899 patch->is_new = 1;
900 patch->is_delete = 0;
901 patch->new_name = name;
902 } else if (has_epoch_timestamp(second)) {
903 patch->is_new = 0;
904 patch->is_delete = 1;
905 patch->old_name = name;
906 } else {
907 patch->old_name = name;
908 patch->new_name = xstrdup_or_null(name);
911 if (!name)
912 return error(_("unable to find filename in patch at line %d"), state->linenr);
914 return 0;
917 static int gitdiff_hdrend(struct gitdiff_data *state UNUSED,
918 const char *line UNUSED,
919 struct patch *patch UNUSED)
921 return 1;
925 * We're anal about diff header consistency, to make
926 * sure that we don't end up having strange ambiguous
927 * patches floating around.
929 * As a result, gitdiff_{old|new}name() will check
930 * their names against any previous information, just
931 * to make sure..
933 #define DIFF_OLD_NAME 0
934 #define DIFF_NEW_NAME 1
936 static int gitdiff_verify_name(struct gitdiff_data *state,
937 const char *line,
938 int isnull,
939 char **name,
940 int side)
942 if (!*name && !isnull) {
943 *name = find_name(state->root, line, NULL, state->p_value, TERM_TAB);
944 return 0;
947 if (*name) {
948 char *another;
949 if (isnull)
950 return error(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
951 *name, state->linenr);
952 another = find_name(state->root, line, NULL, state->p_value, TERM_TAB);
953 if (!another || strcmp(another, *name)) {
954 free(another);
955 return error((side == DIFF_NEW_NAME) ?
956 _("git apply: bad git-diff - inconsistent new filename on line %d") :
957 _("git apply: bad git-diff - inconsistent old filename on line %d"), state->linenr);
959 free(another);
960 } else {
961 if (!is_dev_null(line))
962 return error(_("git apply: bad git-diff - expected /dev/null on line %d"), state->linenr);
965 return 0;
968 static int gitdiff_oldname(struct gitdiff_data *state,
969 const char *line,
970 struct patch *patch)
972 return gitdiff_verify_name(state, line,
973 patch->is_new, &patch->old_name,
974 DIFF_OLD_NAME);
977 static int gitdiff_newname(struct gitdiff_data *state,
978 const char *line,
979 struct patch *patch)
981 return gitdiff_verify_name(state, line,
982 patch->is_delete, &patch->new_name,
983 DIFF_NEW_NAME);
986 static int parse_mode_line(const char *line, int linenr, unsigned int *mode)
988 char *end;
989 *mode = strtoul(line, &end, 8);
990 if (end == line || !isspace(*end))
991 return error(_("invalid mode on line %d: %s"), linenr, line);
992 return 0;
995 static int gitdiff_oldmode(struct gitdiff_data *state,
996 const char *line,
997 struct patch *patch)
999 return parse_mode_line(line, state->linenr, &patch->old_mode);
1002 static int gitdiff_newmode(struct gitdiff_data *state,
1003 const char *line,
1004 struct patch *patch)
1006 return parse_mode_line(line, state->linenr, &patch->new_mode);
1009 static int gitdiff_delete(struct gitdiff_data *state,
1010 const char *line,
1011 struct patch *patch)
1013 patch->is_delete = 1;
1014 free(patch->old_name);
1015 patch->old_name = xstrdup_or_null(patch->def_name);
1016 return gitdiff_oldmode(state, line, patch);
1019 static int gitdiff_newfile(struct gitdiff_data *state,
1020 const char *line,
1021 struct patch *patch)
1023 patch->is_new = 1;
1024 free(patch->new_name);
1025 patch->new_name = xstrdup_or_null(patch->def_name);
1026 return gitdiff_newmode(state, line, patch);
1029 static int gitdiff_copysrc(struct gitdiff_data *state,
1030 const char *line,
1031 struct patch *patch)
1033 patch->is_copy = 1;
1034 free(patch->old_name);
1035 patch->old_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1036 return 0;
1039 static int gitdiff_copydst(struct gitdiff_data *state,
1040 const char *line,
1041 struct patch *patch)
1043 patch->is_copy = 1;
1044 free(patch->new_name);
1045 patch->new_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1046 return 0;
1049 static int gitdiff_renamesrc(struct gitdiff_data *state,
1050 const char *line,
1051 struct patch *patch)
1053 patch->is_rename = 1;
1054 free(patch->old_name);
1055 patch->old_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1056 return 0;
1059 static int gitdiff_renamedst(struct gitdiff_data *state,
1060 const char *line,
1061 struct patch *patch)
1063 patch->is_rename = 1;
1064 free(patch->new_name);
1065 patch->new_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1066 return 0;
1069 static int gitdiff_similarity(struct gitdiff_data *state UNUSED,
1070 const char *line,
1071 struct patch *patch)
1073 unsigned long val = strtoul(line, NULL, 10);
1074 if (val <= 100)
1075 patch->score = val;
1076 return 0;
1079 static int gitdiff_dissimilarity(struct gitdiff_data *state UNUSED,
1080 const char *line,
1081 struct patch *patch)
1083 unsigned long val = strtoul(line, NULL, 10);
1084 if (val <= 100)
1085 patch->score = val;
1086 return 0;
1089 static int gitdiff_index(struct gitdiff_data *state,
1090 const char *line,
1091 struct patch *patch)
1094 * index line is N hexadecimal, "..", N hexadecimal,
1095 * and optional space with octal mode.
1097 const char *ptr, *eol;
1098 int len;
1099 const unsigned hexsz = the_hash_algo->hexsz;
1101 ptr = strchr(line, '.');
1102 if (!ptr || ptr[1] != '.' || hexsz < ptr - line)
1103 return 0;
1104 len = ptr - line;
1105 memcpy(patch->old_oid_prefix, line, len);
1106 patch->old_oid_prefix[len] = 0;
1108 line = ptr + 2;
1109 ptr = strchr(line, ' ');
1110 eol = strchrnul(line, '\n');
1112 if (!ptr || eol < ptr)
1113 ptr = eol;
1114 len = ptr - line;
1116 if (hexsz < len)
1117 return 0;
1118 memcpy(patch->new_oid_prefix, line, len);
1119 patch->new_oid_prefix[len] = 0;
1120 if (*ptr == ' ')
1121 return gitdiff_oldmode(state, ptr + 1, patch);
1122 return 0;
1126 * This is normal for a diff that doesn't change anything: we'll fall through
1127 * into the next diff. Tell the parser to break out.
1129 static int gitdiff_unrecognized(struct gitdiff_data *state UNUSED,
1130 const char *line UNUSED,
1131 struct patch *patch UNUSED)
1133 return 1;
1137 * Skip p_value leading components from "line"; as we do not accept
1138 * absolute paths, return NULL in that case.
1140 static const char *skip_tree_prefix(int p_value,
1141 const char *line,
1142 int llen)
1144 int nslash;
1145 int i;
1147 if (!p_value)
1148 return (llen && line[0] == '/') ? NULL : line;
1150 nslash = p_value;
1151 for (i = 0; i < llen; i++) {
1152 int ch = line[i];
1153 if (ch == '/' && --nslash <= 0)
1154 return (i == 0) ? NULL : &line[i + 1];
1156 return NULL;
1160 * This is to extract the same name that appears on "diff --git"
1161 * line. We do not find and return anything if it is a rename
1162 * patch, and it is OK because we will find the name elsewhere.
1163 * We need to reliably find name only when it is mode-change only,
1164 * creation or deletion of an empty file. In any of these cases,
1165 * both sides are the same name under a/ and b/ respectively.
1167 static char *git_header_name(int p_value,
1168 const char *line,
1169 int llen)
1171 const char *name;
1172 const char *second = NULL;
1173 size_t len, line_len;
1175 line += strlen("diff --git ");
1176 llen -= strlen("diff --git ");
1178 if (*line == '"') {
1179 const char *cp;
1180 struct strbuf first = STRBUF_INIT;
1181 struct strbuf sp = STRBUF_INIT;
1183 if (unquote_c_style(&first, line, &second))
1184 goto free_and_fail1;
1186 /* strip the a/b prefix including trailing slash */
1187 cp = skip_tree_prefix(p_value, first.buf, first.len);
1188 if (!cp)
1189 goto free_and_fail1;
1190 strbuf_remove(&first, 0, cp - first.buf);
1193 * second points at one past closing dq of name.
1194 * find the second name.
1196 while ((second < line + llen) && isspace(*second))
1197 second++;
1199 if (line + llen <= second)
1200 goto free_and_fail1;
1201 if (*second == '"') {
1202 if (unquote_c_style(&sp, second, NULL))
1203 goto free_and_fail1;
1204 cp = skip_tree_prefix(p_value, sp.buf, sp.len);
1205 if (!cp)
1206 goto free_and_fail1;
1207 /* They must match, otherwise ignore */
1208 if (strcmp(cp, first.buf))
1209 goto free_and_fail1;
1210 strbuf_release(&sp);
1211 return strbuf_detach(&first, NULL);
1214 /* unquoted second */
1215 cp = skip_tree_prefix(p_value, second, line + llen - second);
1216 if (!cp)
1217 goto free_and_fail1;
1218 if (line + llen - cp != first.len ||
1219 memcmp(first.buf, cp, first.len))
1220 goto free_and_fail1;
1221 return strbuf_detach(&first, NULL);
1223 free_and_fail1:
1224 strbuf_release(&first);
1225 strbuf_release(&sp);
1226 return NULL;
1229 /* unquoted first name */
1230 name = skip_tree_prefix(p_value, line, llen);
1231 if (!name)
1232 return NULL;
1235 * since the first name is unquoted, a dq if exists must be
1236 * the beginning of the second name.
1238 for (second = name; second < line + llen; second++) {
1239 if (*second == '"') {
1240 struct strbuf sp = STRBUF_INIT;
1241 const char *np;
1243 if (unquote_c_style(&sp, second, NULL))
1244 goto free_and_fail2;
1246 np = skip_tree_prefix(p_value, sp.buf, sp.len);
1247 if (!np)
1248 goto free_and_fail2;
1250 len = sp.buf + sp.len - np;
1251 if (len < second - name &&
1252 !strncmp(np, name, len) &&
1253 isspace(name[len])) {
1254 /* Good */
1255 strbuf_remove(&sp, 0, np - sp.buf);
1256 return strbuf_detach(&sp, NULL);
1259 free_and_fail2:
1260 strbuf_release(&sp);
1261 return NULL;
1266 * Accept a name only if it shows up twice, exactly the same
1267 * form.
1269 second = strchr(name, '\n');
1270 if (!second)
1271 return NULL;
1272 line_len = second - name;
1273 for (len = 0 ; ; len++) {
1274 switch (name[len]) {
1275 default:
1276 continue;
1277 case '\n':
1278 return NULL;
1279 case '\t': case ' ':
1281 * Is this the separator between the preimage
1282 * and the postimage pathname? Again, we are
1283 * only interested in the case where there is
1284 * no rename, as this is only to set def_name
1285 * and a rename patch has the names elsewhere
1286 * in an unambiguous form.
1288 if (!name[len + 1])
1289 return NULL; /* no postimage name */
1290 second = skip_tree_prefix(p_value, name + len + 1,
1291 line_len - (len + 1));
1292 if (!second)
1293 return NULL;
1295 * Does len bytes starting at "name" and "second"
1296 * (that are separated by one HT or SP we just
1297 * found) exactly match?
1299 if (second[len] == '\n' && !strncmp(name, second, len))
1300 return xmemdupz(name, len);
1305 static int check_header_line(int linenr, struct patch *patch)
1307 int extensions = (patch->is_delete == 1) + (patch->is_new == 1) +
1308 (patch->is_rename == 1) + (patch->is_copy == 1);
1309 if (extensions > 1)
1310 return error(_("inconsistent header lines %d and %d"),
1311 patch->extension_linenr, linenr);
1312 if (extensions && !patch->extension_linenr)
1313 patch->extension_linenr = linenr;
1314 return 0;
1317 int parse_git_diff_header(struct strbuf *root,
1318 int *linenr,
1319 int p_value,
1320 const char *line,
1321 int len,
1322 unsigned int size,
1323 struct patch *patch)
1325 unsigned long offset;
1326 struct gitdiff_data parse_hdr_state;
1328 /* A git diff has explicit new/delete information, so we don't guess */
1329 patch->is_new = 0;
1330 patch->is_delete = 0;
1333 * Some things may not have the old name in the
1334 * rest of the headers anywhere (pure mode changes,
1335 * or removing or adding empty files), so we get
1336 * the default name from the header.
1338 patch->def_name = git_header_name(p_value, line, len);
1339 if (patch->def_name && root->len) {
1340 char *s = xstrfmt("%s%s", root->buf, patch->def_name);
1341 free(patch->def_name);
1342 patch->def_name = s;
1345 line += len;
1346 size -= len;
1347 (*linenr)++;
1348 parse_hdr_state.root = root;
1349 parse_hdr_state.linenr = *linenr;
1350 parse_hdr_state.p_value = p_value;
1352 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, (*linenr)++) {
1353 static const struct opentry {
1354 const char *str;
1355 int (*fn)(struct gitdiff_data *, const char *, struct patch *);
1356 } optable[] = {
1357 { "@@ -", gitdiff_hdrend },
1358 { "--- ", gitdiff_oldname },
1359 { "+++ ", gitdiff_newname },
1360 { "old mode ", gitdiff_oldmode },
1361 { "new mode ", gitdiff_newmode },
1362 { "deleted file mode ", gitdiff_delete },
1363 { "new file mode ", gitdiff_newfile },
1364 { "copy from ", gitdiff_copysrc },
1365 { "copy to ", gitdiff_copydst },
1366 { "rename old ", gitdiff_renamesrc },
1367 { "rename new ", gitdiff_renamedst },
1368 { "rename from ", gitdiff_renamesrc },
1369 { "rename to ", gitdiff_renamedst },
1370 { "similarity index ", gitdiff_similarity },
1371 { "dissimilarity index ", gitdiff_dissimilarity },
1372 { "index ", gitdiff_index },
1373 { "", gitdiff_unrecognized },
1375 int i;
1377 len = linelen(line, size);
1378 if (!len || line[len-1] != '\n')
1379 break;
1380 for (i = 0; i < ARRAY_SIZE(optable); i++) {
1381 const struct opentry *p = optable + i;
1382 int oplen = strlen(p->str);
1383 int res;
1384 if (len < oplen || memcmp(p->str, line, oplen))
1385 continue;
1386 res = p->fn(&parse_hdr_state, line + oplen, patch);
1387 if (res < 0)
1388 return -1;
1389 if (check_header_line(*linenr, patch))
1390 return -1;
1391 if (res > 0)
1392 goto done;
1393 break;
1397 done:
1398 if (!patch->old_name && !patch->new_name) {
1399 if (!patch->def_name) {
1400 error(Q_("git diff header lacks filename information when removing "
1401 "%d leading pathname component (line %d)",
1402 "git diff header lacks filename information when removing "
1403 "%d leading pathname components (line %d)",
1404 parse_hdr_state.p_value),
1405 parse_hdr_state.p_value, *linenr);
1406 return -128;
1408 patch->old_name = xstrdup(patch->def_name);
1409 patch->new_name = xstrdup(patch->def_name);
1411 if ((!patch->new_name && !patch->is_delete) ||
1412 (!patch->old_name && !patch->is_new)) {
1413 error(_("git diff header lacks filename information "
1414 "(line %d)"), *linenr);
1415 return -128;
1417 patch->is_toplevel_relative = 1;
1418 return offset;
1421 static int parse_num(const char *line, unsigned long *p)
1423 char *ptr;
1425 if (!isdigit(*line))
1426 return 0;
1427 *p = strtoul(line, &ptr, 10);
1428 return ptr - line;
1431 static int parse_range(const char *line, int len, int offset, const char *expect,
1432 unsigned long *p1, unsigned long *p2)
1434 int digits, ex;
1436 if (offset < 0 || offset >= len)
1437 return -1;
1438 line += offset;
1439 len -= offset;
1441 digits = parse_num(line, p1);
1442 if (!digits)
1443 return -1;
1445 offset += digits;
1446 line += digits;
1447 len -= digits;
1449 *p2 = 1;
1450 if (*line == ',') {
1451 digits = parse_num(line+1, p2);
1452 if (!digits)
1453 return -1;
1455 offset += digits+1;
1456 line += digits+1;
1457 len -= digits+1;
1460 ex = strlen(expect);
1461 if (ex > len)
1462 return -1;
1463 if (memcmp(line, expect, ex))
1464 return -1;
1466 return offset + ex;
1469 static void recount_diff(const char *line, int size, struct fragment *fragment)
1471 int oldlines = 0, newlines = 0, ret = 0;
1473 if (size < 1) {
1474 warning("recount: ignore empty hunk");
1475 return;
1478 for (;;) {
1479 int len = linelen(line, size);
1480 size -= len;
1481 line += len;
1483 if (size < 1)
1484 break;
1486 switch (*line) {
1487 case ' ': case '\n':
1488 newlines++;
1489 /* fall through */
1490 case '-':
1491 oldlines++;
1492 continue;
1493 case '+':
1494 newlines++;
1495 continue;
1496 case '\\':
1497 continue;
1498 case '@':
1499 ret = size < 3 || !starts_with(line, "@@ ");
1500 break;
1501 case 'd':
1502 ret = size < 5 || !starts_with(line, "diff ");
1503 break;
1504 default:
1505 ret = -1;
1506 break;
1508 if (ret) {
1509 warning(_("recount: unexpected line: %.*s"),
1510 (int)linelen(line, size), line);
1511 return;
1513 break;
1515 fragment->oldlines = oldlines;
1516 fragment->newlines = newlines;
1520 * Parse a unified diff fragment header of the
1521 * form "@@ -a,b +c,d @@"
1523 static int parse_fragment_header(const char *line, int len, struct fragment *fragment)
1525 int offset;
1527 if (!len || line[len-1] != '\n')
1528 return -1;
1530 /* Figure out the number of lines in a fragment */
1531 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1532 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1534 return offset;
1538 * Find file diff header
1540 * Returns:
1541 * -1 if no header was found
1542 * -128 in case of error
1543 * the size of the header in bytes (called "offset") otherwise
1545 static int find_header(struct apply_state *state,
1546 const char *line,
1547 unsigned long size,
1548 int *hdrsize,
1549 struct patch *patch)
1551 unsigned long offset, len;
1553 patch->is_toplevel_relative = 0;
1554 patch->is_rename = patch->is_copy = 0;
1555 patch->is_new = patch->is_delete = -1;
1556 patch->old_mode = patch->new_mode = 0;
1557 patch->old_name = patch->new_name = NULL;
1558 for (offset = 0; size > 0; offset += len, size -= len, line += len, state->linenr++) {
1559 unsigned long nextlen;
1561 len = linelen(line, size);
1562 if (!len)
1563 break;
1565 /* Testing this early allows us to take a few shortcuts.. */
1566 if (len < 6)
1567 continue;
1570 * Make sure we don't find any unconnected patch fragments.
1571 * That's a sign that we didn't find a header, and that a
1572 * patch has become corrupted/broken up.
1574 if (!memcmp("@@ -", line, 4)) {
1575 struct fragment dummy;
1576 if (parse_fragment_header(line, len, &dummy) < 0)
1577 continue;
1578 error(_("patch fragment without header at line %d: %.*s"),
1579 state->linenr, (int)len-1, line);
1580 return -128;
1583 if (size < len + 6)
1584 break;
1587 * Git patch? It might not have a real patch, just a rename
1588 * or mode change, so we handle that specially
1590 if (!memcmp("diff --git ", line, 11)) {
1591 int git_hdr_len = parse_git_diff_header(&state->root, &state->linenr,
1592 state->p_value, line, len,
1593 size, patch);
1594 if (git_hdr_len < 0)
1595 return -128;
1596 if (git_hdr_len <= len)
1597 continue;
1598 *hdrsize = git_hdr_len;
1599 return offset;
1602 /* --- followed by +++ ? */
1603 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1604 continue;
1607 * We only accept unified patches, so we want it to
1608 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1609 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1611 nextlen = linelen(line + len, size - len);
1612 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1613 continue;
1615 /* Ok, we'll consider it a patch */
1616 if (parse_traditional_patch(state, line, line+len, patch))
1617 return -128;
1618 *hdrsize = len + nextlen;
1619 state->linenr += 2;
1620 return offset;
1622 return -1;
1625 static void record_ws_error(struct apply_state *state,
1626 unsigned result,
1627 const char *line,
1628 int len,
1629 int linenr)
1631 char *err;
1633 if (!result)
1634 return;
1636 state->whitespace_error++;
1637 if (state->squelch_whitespace_errors &&
1638 state->squelch_whitespace_errors < state->whitespace_error)
1639 return;
1641 err = whitespace_error_string(result);
1642 if (state->apply_verbosity > verbosity_silent)
1643 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1644 state->patch_input_file, linenr, err, len, line);
1645 free(err);
1648 static void check_whitespace(struct apply_state *state,
1649 const char *line,
1650 int len,
1651 unsigned ws_rule)
1653 unsigned result = ws_check(line + 1, len - 1, ws_rule);
1655 record_ws_error(state, result, line + 1, len - 2, state->linenr);
1659 * Check if the patch has context lines with CRLF or
1660 * the patch wants to remove lines with CRLF.
1662 static void check_old_for_crlf(struct patch *patch, const char *line, int len)
1664 if (len >= 2 && line[len-1] == '\n' && line[len-2] == '\r') {
1665 patch->ws_rule |= WS_CR_AT_EOL;
1666 patch->crlf_in_old = 1;
1672 * Parse a unified diff. Note that this really needs to parse each
1673 * fragment separately, since the only way to know the difference
1674 * between a "---" that is part of a patch, and a "---" that starts
1675 * the next patch is to look at the line counts..
1677 static int parse_fragment(struct apply_state *state,
1678 const char *line,
1679 unsigned long size,
1680 struct patch *patch,
1681 struct fragment *fragment)
1683 int added, deleted;
1684 int len = linelen(line, size), offset;
1685 unsigned long oldlines, newlines;
1686 unsigned long leading, trailing;
1688 offset = parse_fragment_header(line, len, fragment);
1689 if (offset < 0)
1690 return -1;
1691 if (offset > 0 && patch->recount)
1692 recount_diff(line + offset, size - offset, fragment);
1693 oldlines = fragment->oldlines;
1694 newlines = fragment->newlines;
1695 leading = 0;
1696 trailing = 0;
1698 /* Parse the thing.. */
1699 line += len;
1700 size -= len;
1701 state->linenr++;
1702 added = deleted = 0;
1703 for (offset = len;
1704 0 < size;
1705 offset += len, size -= len, line += len, state->linenr++) {
1706 if (!oldlines && !newlines)
1707 break;
1708 len = linelen(line, size);
1709 if (!len || line[len-1] != '\n')
1710 return -1;
1711 switch (*line) {
1712 default:
1713 return -1;
1714 case '\n': /* newer GNU diff, an empty context line */
1715 case ' ':
1716 oldlines--;
1717 newlines--;
1718 if (!deleted && !added)
1719 leading++;
1720 trailing++;
1721 check_old_for_crlf(patch, line, len);
1722 if (!state->apply_in_reverse &&
1723 state->ws_error_action == correct_ws_error)
1724 check_whitespace(state, line, len, patch->ws_rule);
1725 break;
1726 case '-':
1727 if (!state->apply_in_reverse)
1728 check_old_for_crlf(patch, line, len);
1729 if (state->apply_in_reverse &&
1730 state->ws_error_action != nowarn_ws_error)
1731 check_whitespace(state, line, len, patch->ws_rule);
1732 deleted++;
1733 oldlines--;
1734 trailing = 0;
1735 break;
1736 case '+':
1737 if (state->apply_in_reverse)
1738 check_old_for_crlf(patch, line, len);
1739 if (!state->apply_in_reverse &&
1740 state->ws_error_action != nowarn_ws_error)
1741 check_whitespace(state, line, len, patch->ws_rule);
1742 added++;
1743 newlines--;
1744 trailing = 0;
1745 break;
1748 * We allow "\ No newline at end of file". Depending
1749 * on locale settings when the patch was produced we
1750 * don't know what this line looks like. The only
1751 * thing we do know is that it begins with "\ ".
1752 * Checking for 12 is just for sanity check -- any
1753 * l10n of "\ No newline..." is at least that long.
1755 case '\\':
1756 if (len < 12 || memcmp(line, "\\ ", 2))
1757 return -1;
1758 break;
1761 if (oldlines || newlines)
1762 return -1;
1763 if (!patch->recount && !deleted && !added)
1764 return -1;
1766 fragment->leading = leading;
1767 fragment->trailing = trailing;
1770 * If a fragment ends with an incomplete line, we failed to include
1771 * it in the above loop because we hit oldlines == newlines == 0
1772 * before seeing it.
1774 if (12 < size && !memcmp(line, "\\ ", 2))
1775 offset += linelen(line, size);
1777 patch->lines_added += added;
1778 patch->lines_deleted += deleted;
1780 if (0 < patch->is_new && oldlines)
1781 return error(_("new file depends on old contents"));
1782 if (0 < patch->is_delete && newlines)
1783 return error(_("deleted file still has contents"));
1784 return offset;
1788 * We have seen "diff --git a/... b/..." header (or a traditional patch
1789 * header). Read hunks that belong to this patch into fragments and hang
1790 * them to the given patch structure.
1792 * The (fragment->patch, fragment->size) pair points into the memory given
1793 * by the caller, not a copy, when we return.
1795 * Returns:
1796 * -1 in case of error,
1797 * the number of bytes in the patch otherwise.
1799 static int parse_single_patch(struct apply_state *state,
1800 const char *line,
1801 unsigned long size,
1802 struct patch *patch)
1804 unsigned long offset = 0;
1805 unsigned long oldlines = 0, newlines = 0, context = 0;
1806 struct fragment **fragp = &patch->fragments;
1808 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1809 struct fragment *fragment;
1810 int len;
1812 CALLOC_ARRAY(fragment, 1);
1813 fragment->linenr = state->linenr;
1814 len = parse_fragment(state, line, size, patch, fragment);
1815 if (len <= 0) {
1816 free(fragment);
1817 return error(_("corrupt patch at line %d"), state->linenr);
1819 fragment->patch = line;
1820 fragment->size = len;
1821 oldlines += fragment->oldlines;
1822 newlines += fragment->newlines;
1823 context += fragment->leading + fragment->trailing;
1825 *fragp = fragment;
1826 fragp = &fragment->next;
1828 offset += len;
1829 line += len;
1830 size -= len;
1834 * If something was removed (i.e. we have old-lines) it cannot
1835 * be creation, and if something was added it cannot be
1836 * deletion. However, the reverse is not true; --unified=0
1837 * patches that only add are not necessarily creation even
1838 * though they do not have any old lines, and ones that only
1839 * delete are not necessarily deletion.
1841 * Unfortunately, a real creation/deletion patch do _not_ have
1842 * any context line by definition, so we cannot safely tell it
1843 * apart with --unified=0 insanity. At least if the patch has
1844 * more than one hunk it is not creation or deletion.
1846 if (patch->is_new < 0 &&
1847 (oldlines || (patch->fragments && patch->fragments->next)))
1848 patch->is_new = 0;
1849 if (patch->is_delete < 0 &&
1850 (newlines || (patch->fragments && patch->fragments->next)))
1851 patch->is_delete = 0;
1853 if (0 < patch->is_new && oldlines)
1854 return error(_("new file %s depends on old contents"), patch->new_name);
1855 if (0 < patch->is_delete && newlines)
1856 return error(_("deleted file %s still has contents"), patch->old_name);
1857 if (!patch->is_delete && !newlines && context && state->apply_verbosity > verbosity_silent)
1858 fprintf_ln(stderr,
1859 _("** warning: "
1860 "file %s becomes empty but is not deleted"),
1861 patch->new_name);
1863 return offset;
1866 static inline int metadata_changes(struct patch *patch)
1868 return patch->is_rename > 0 ||
1869 patch->is_copy > 0 ||
1870 patch->is_new > 0 ||
1871 patch->is_delete ||
1872 (patch->old_mode && patch->new_mode &&
1873 patch->old_mode != patch->new_mode);
1876 static char *inflate_it(const void *data, unsigned long size,
1877 unsigned long inflated_size)
1879 git_zstream stream;
1880 void *out;
1881 int st;
1883 memset(&stream, 0, sizeof(stream));
1885 stream.next_in = (unsigned char *)data;
1886 stream.avail_in = size;
1887 stream.next_out = out = xmalloc(inflated_size);
1888 stream.avail_out = inflated_size;
1889 git_inflate_init(&stream);
1890 st = git_inflate(&stream, Z_FINISH);
1891 git_inflate_end(&stream);
1892 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1893 free(out);
1894 return NULL;
1896 return out;
1900 * Read a binary hunk and return a new fragment; fragment->patch
1901 * points at an allocated memory that the caller must free, so
1902 * it is marked as "->free_patch = 1".
1904 static struct fragment *parse_binary_hunk(struct apply_state *state,
1905 char **buf_p,
1906 unsigned long *sz_p,
1907 int *status_p,
1908 int *used_p)
1911 * Expect a line that begins with binary patch method ("literal"
1912 * or "delta"), followed by the length of data before deflating.
1913 * a sequence of 'length-byte' followed by base-85 encoded data
1914 * should follow, terminated by a newline.
1916 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1917 * and we would limit the patch line to 66 characters,
1918 * so one line can fit up to 13 groups that would decode
1919 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1920 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1922 int llen, used;
1923 unsigned long size = *sz_p;
1924 char *buffer = *buf_p;
1925 int patch_method;
1926 unsigned long origlen;
1927 char *data = NULL;
1928 int hunk_size = 0;
1929 struct fragment *frag;
1931 llen = linelen(buffer, size);
1932 used = llen;
1934 *status_p = 0;
1936 if (starts_with(buffer, "delta ")) {
1937 patch_method = BINARY_DELTA_DEFLATED;
1938 origlen = strtoul(buffer + 6, NULL, 10);
1940 else if (starts_with(buffer, "literal ")) {
1941 patch_method = BINARY_LITERAL_DEFLATED;
1942 origlen = strtoul(buffer + 8, NULL, 10);
1944 else
1945 return NULL;
1947 state->linenr++;
1948 buffer += llen;
1949 size -= llen;
1950 while (1) {
1951 int byte_length, max_byte_length, newsize;
1952 llen = linelen(buffer, size);
1953 used += llen;
1954 state->linenr++;
1955 if (llen == 1) {
1956 /* consume the blank line */
1957 buffer++;
1958 size--;
1959 break;
1962 * Minimum line is "A00000\n" which is 7-byte long,
1963 * and the line length must be multiple of 5 plus 2.
1965 if ((llen < 7) || (llen-2) % 5)
1966 goto corrupt;
1967 max_byte_length = (llen - 2) / 5 * 4;
1968 byte_length = *buffer;
1969 if ('A' <= byte_length && byte_length <= 'Z')
1970 byte_length = byte_length - 'A' + 1;
1971 else if ('a' <= byte_length && byte_length <= 'z')
1972 byte_length = byte_length - 'a' + 27;
1973 else
1974 goto corrupt;
1975 /* if the input length was not multiple of 4, we would
1976 * have filler at the end but the filler should never
1977 * exceed 3 bytes
1979 if (max_byte_length < byte_length ||
1980 byte_length <= max_byte_length - 4)
1981 goto corrupt;
1982 newsize = hunk_size + byte_length;
1983 data = xrealloc(data, newsize);
1984 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1985 goto corrupt;
1986 hunk_size = newsize;
1987 buffer += llen;
1988 size -= llen;
1991 CALLOC_ARRAY(frag, 1);
1992 frag->patch = inflate_it(data, hunk_size, origlen);
1993 frag->free_patch = 1;
1994 if (!frag->patch)
1995 goto corrupt;
1996 free(data);
1997 frag->size = origlen;
1998 *buf_p = buffer;
1999 *sz_p = size;
2000 *used_p = used;
2001 frag->binary_patch_method = patch_method;
2002 return frag;
2004 corrupt:
2005 free(data);
2006 *status_p = -1;
2007 error(_("corrupt binary patch at line %d: %.*s"),
2008 state->linenr-1, llen-1, buffer);
2009 return NULL;
2013 * Returns:
2014 * -1 in case of error,
2015 * the length of the parsed binary patch otherwise
2017 static int parse_binary(struct apply_state *state,
2018 char *buffer,
2019 unsigned long size,
2020 struct patch *patch)
2023 * We have read "GIT binary patch\n"; what follows is a line
2024 * that says the patch method (currently, either "literal" or
2025 * "delta") and the length of data before deflating; a
2026 * sequence of 'length-byte' followed by base-85 encoded data
2027 * follows.
2029 * When a binary patch is reversible, there is another binary
2030 * hunk in the same format, starting with patch method (either
2031 * "literal" or "delta") with the length of data, and a sequence
2032 * of length-byte + base-85 encoded data, terminated with another
2033 * empty line. This data, when applied to the postimage, produces
2034 * the preimage.
2036 struct fragment *forward;
2037 struct fragment *reverse;
2038 int status;
2039 int used, used_1;
2041 forward = parse_binary_hunk(state, &buffer, &size, &status, &used);
2042 if (!forward && !status)
2043 /* there has to be one hunk (forward hunk) */
2044 return error(_("unrecognized binary patch at line %d"), state->linenr-1);
2045 if (status)
2046 /* otherwise we already gave an error message */
2047 return status;
2049 reverse = parse_binary_hunk(state, &buffer, &size, &status, &used_1);
2050 if (reverse)
2051 used += used_1;
2052 else if (status) {
2054 * Not having reverse hunk is not an error, but having
2055 * a corrupt reverse hunk is.
2057 free((void*) forward->patch);
2058 free(forward);
2059 return status;
2061 forward->next = reverse;
2062 patch->fragments = forward;
2063 patch->is_binary = 1;
2064 return used;
2067 static void prefix_one(struct apply_state *state, char **name)
2069 char *old_name = *name;
2070 if (!old_name)
2071 return;
2072 *name = prefix_filename(state->prefix, *name);
2073 free(old_name);
2076 static void prefix_patch(struct apply_state *state, struct patch *p)
2078 if (!state->prefix || p->is_toplevel_relative)
2079 return;
2080 prefix_one(state, &p->new_name);
2081 prefix_one(state, &p->old_name);
2085 * include/exclude
2088 static void add_name_limit(struct apply_state *state,
2089 const char *name,
2090 int exclude)
2092 struct string_list_item *it;
2094 it = string_list_append(&state->limit_by_name, name);
2095 it->util = exclude ? NULL : (void *) 1;
2098 static int use_patch(struct apply_state *state, struct patch *p)
2100 const char *pathname = p->new_name ? p->new_name : p->old_name;
2101 int i;
2103 /* Paths outside are not touched regardless of "--include" */
2104 if (state->prefix && *state->prefix) {
2105 const char *rest;
2106 if (!skip_prefix(pathname, state->prefix, &rest) || !*rest)
2107 return 0;
2110 /* See if it matches any of exclude/include rule */
2111 for (i = 0; i < state->limit_by_name.nr; i++) {
2112 struct string_list_item *it = &state->limit_by_name.items[i];
2113 if (!wildmatch(it->string, pathname, 0))
2114 return (it->util != NULL);
2118 * If we had any include, a path that does not match any rule is
2119 * not used. Otherwise, we saw bunch of exclude rules (or none)
2120 * and such a path is used.
2122 return !state->has_include;
2126 * Read the patch text in "buffer" that extends for "size" bytes; stop
2127 * reading after seeing a single patch (i.e. changes to a single file).
2128 * Create fragments (i.e. patch hunks) and hang them to the given patch.
2130 * Returns:
2131 * -1 if no header was found or parse_binary() failed,
2132 * -128 on another error,
2133 * the number of bytes consumed otherwise,
2134 * so that the caller can call us again for the next patch.
2136 static int parse_chunk(struct apply_state *state, char *buffer, unsigned long size, struct patch *patch)
2138 int hdrsize, patchsize;
2139 int offset = find_header(state, buffer, size, &hdrsize, patch);
2141 if (offset < 0)
2142 return offset;
2144 prefix_patch(state, patch);
2146 if (!use_patch(state, patch))
2147 patch->ws_rule = 0;
2148 else if (patch->new_name)
2149 patch->ws_rule = whitespace_rule(state->repo->index,
2150 patch->new_name);
2151 else
2152 patch->ws_rule = whitespace_rule(state->repo->index,
2153 patch->old_name);
2155 patchsize = parse_single_patch(state,
2156 buffer + offset + hdrsize,
2157 size - offset - hdrsize,
2158 patch);
2160 if (patchsize < 0)
2161 return -128;
2163 if (!patchsize) {
2164 static const char git_binary[] = "GIT binary patch\n";
2165 int hd = hdrsize + offset;
2166 unsigned long llen = linelen(buffer + hd, size - hd);
2168 if (llen == sizeof(git_binary) - 1 &&
2169 !memcmp(git_binary, buffer + hd, llen)) {
2170 int used;
2171 state->linenr++;
2172 used = parse_binary(state, buffer + hd + llen,
2173 size - hd - llen, patch);
2174 if (used < 0)
2175 return -1;
2176 if (used)
2177 patchsize = used + llen;
2178 else
2179 patchsize = 0;
2181 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
2182 static const char *binhdr[] = {
2183 "Binary files ",
2184 "Files ",
2185 NULL,
2187 int i;
2188 for (i = 0; binhdr[i]; i++) {
2189 int len = strlen(binhdr[i]);
2190 if (len < size - hd &&
2191 !memcmp(binhdr[i], buffer + hd, len)) {
2192 state->linenr++;
2193 patch->is_binary = 1;
2194 patchsize = llen;
2195 break;
2200 /* Empty patch cannot be applied if it is a text patch
2201 * without metadata change. A binary patch appears
2202 * empty to us here.
2204 if ((state->apply || state->check) &&
2205 (!patch->is_binary && !metadata_changes(patch))) {
2206 error(_("patch with only garbage at line %d"), state->linenr);
2207 return -128;
2211 return offset + hdrsize + patchsize;
2214 static void reverse_patches(struct patch *p)
2216 for (; p; p = p->next) {
2217 struct fragment *frag = p->fragments;
2219 SWAP(p->new_name, p->old_name);
2220 SWAP(p->new_mode, p->old_mode);
2221 SWAP(p->is_new, p->is_delete);
2222 SWAP(p->lines_added, p->lines_deleted);
2223 SWAP(p->old_oid_prefix, p->new_oid_prefix);
2225 for (; frag; frag = frag->next) {
2226 SWAP(frag->newpos, frag->oldpos);
2227 SWAP(frag->newlines, frag->oldlines);
2232 static const char pluses[] =
2233 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2234 static const char minuses[]=
2235 "----------------------------------------------------------------------";
2237 static void show_stats(struct apply_state *state, struct patch *patch)
2239 struct strbuf qname = STRBUF_INIT;
2240 char *cp = patch->new_name ? patch->new_name : patch->old_name;
2241 int max, add, del;
2243 quote_c_style(cp, &qname, NULL, 0);
2246 * "scale" the filename
2248 max = state->max_len;
2249 if (max > 50)
2250 max = 50;
2252 if (qname.len > max) {
2253 cp = strchr(qname.buf + qname.len + 3 - max, '/');
2254 if (!cp)
2255 cp = qname.buf + qname.len + 3 - max;
2256 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
2259 if (patch->is_binary) {
2260 printf(" %-*s | Bin\n", max, qname.buf);
2261 strbuf_release(&qname);
2262 return;
2265 printf(" %-*s |", max, qname.buf);
2266 strbuf_release(&qname);
2269 * scale the add/delete
2271 max = max + state->max_change > 70 ? 70 - max : state->max_change;
2272 add = patch->lines_added;
2273 del = patch->lines_deleted;
2275 if (state->max_change > 0) {
2276 int total = ((add + del) * max + state->max_change / 2) / state->max_change;
2277 add = (add * max + state->max_change / 2) / state->max_change;
2278 del = total - add;
2280 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
2281 add, pluses, del, minuses);
2284 static int read_old_data(struct stat *st, struct patch *patch,
2285 const char *path, struct strbuf *buf)
2287 int conv_flags = patch->crlf_in_old ?
2288 CONV_EOL_KEEP_CRLF : CONV_EOL_RENORMALIZE;
2289 switch (st->st_mode & S_IFMT) {
2290 case S_IFLNK:
2291 if (strbuf_readlink(buf, path, st->st_size) < 0)
2292 return error(_("unable to read symlink %s"), path);
2293 return 0;
2294 case S_IFREG:
2295 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
2296 return error(_("unable to open or read %s"), path);
2298 * "git apply" without "--index/--cached" should never look
2299 * at the index; the target file may not have been added to
2300 * the index yet, and we may not even be in any Git repository.
2301 * Pass NULL to convert_to_git() to stress this; the function
2302 * should never look at the index when explicit crlf option
2303 * is given.
2305 convert_to_git(NULL, path, buf->buf, buf->len, buf, conv_flags);
2306 return 0;
2307 default:
2308 return -1;
2313 * Update the preimage, and the common lines in postimage,
2314 * from buffer buf of length len. If postlen is 0 the postimage
2315 * is updated in place, otherwise it's updated on a new buffer
2316 * of length postlen
2319 static void update_pre_post_images(struct image *preimage,
2320 struct image *postimage,
2321 char *buf,
2322 size_t len, size_t postlen)
2324 int i, ctx, reduced;
2325 char *new_buf, *old_buf, *fixed;
2326 struct image fixed_preimage;
2329 * Update the preimage with whitespace fixes. Note that we
2330 * are not losing preimage->buf -- apply_one_fragment() will
2331 * free "oldlines".
2333 prepare_image(&fixed_preimage, buf, len, 1);
2334 assert(postlen
2335 ? fixed_preimage.nr == preimage->nr
2336 : fixed_preimage.nr <= preimage->nr);
2337 for (i = 0; i < fixed_preimage.nr; i++)
2338 fixed_preimage.line[i].flag = preimage->line[i].flag;
2339 free(preimage->line_allocated);
2340 *preimage = fixed_preimage;
2343 * Adjust the common context lines in postimage. This can be
2344 * done in-place when we are shrinking it with whitespace
2345 * fixing, but needs a new buffer when ignoring whitespace or
2346 * expanding leading tabs to spaces.
2348 * We trust the caller to tell us if the update can be done
2349 * in place (postlen==0) or not.
2351 old_buf = postimage->buf;
2352 if (postlen)
2353 new_buf = postimage->buf = xmalloc(postlen);
2354 else
2355 new_buf = old_buf;
2356 fixed = preimage->buf;
2358 for (i = reduced = ctx = 0; i < postimage->nr; i++) {
2359 size_t l_len = postimage->line[i].len;
2360 if (!(postimage->line[i].flag & LINE_COMMON)) {
2361 /* an added line -- no counterparts in preimage */
2362 memmove(new_buf, old_buf, l_len);
2363 old_buf += l_len;
2364 new_buf += l_len;
2365 continue;
2368 /* a common context -- skip it in the original postimage */
2369 old_buf += l_len;
2371 /* and find the corresponding one in the fixed preimage */
2372 while (ctx < preimage->nr &&
2373 !(preimage->line[ctx].flag & LINE_COMMON)) {
2374 fixed += preimage->line[ctx].len;
2375 ctx++;
2379 * preimage is expected to run out, if the caller
2380 * fixed addition of trailing blank lines.
2382 if (preimage->nr <= ctx) {
2383 reduced++;
2384 continue;
2387 /* and copy it in, while fixing the line length */
2388 l_len = preimage->line[ctx].len;
2389 memcpy(new_buf, fixed, l_len);
2390 new_buf += l_len;
2391 fixed += l_len;
2392 postimage->line[i].len = l_len;
2393 ctx++;
2396 if (postlen
2397 ? postlen < new_buf - postimage->buf
2398 : postimage->len < new_buf - postimage->buf)
2399 BUG("caller miscounted postlen: asked %d, orig = %d, used = %d",
2400 (int)postlen, (int) postimage->len, (int)(new_buf - postimage->buf));
2402 /* Fix the length of the whole thing */
2403 postimage->len = new_buf - postimage->buf;
2404 postimage->nr -= reduced;
2407 static int line_by_line_fuzzy_match(struct image *img,
2408 struct image *preimage,
2409 struct image *postimage,
2410 unsigned long current,
2411 int current_lno,
2412 int preimage_limit)
2414 int i;
2415 size_t imgoff = 0;
2416 size_t preoff = 0;
2417 size_t postlen = postimage->len;
2418 size_t extra_chars;
2419 char *buf;
2420 char *preimage_eof;
2421 char *preimage_end;
2422 struct strbuf fixed;
2423 char *fixed_buf;
2424 size_t fixed_len;
2426 for (i = 0; i < preimage_limit; i++) {
2427 size_t prelen = preimage->line[i].len;
2428 size_t imglen = img->line[current_lno+i].len;
2430 if (!fuzzy_matchlines(img->buf + current + imgoff, imglen,
2431 preimage->buf + preoff, prelen))
2432 return 0;
2433 if (preimage->line[i].flag & LINE_COMMON)
2434 postlen += imglen - prelen;
2435 imgoff += imglen;
2436 preoff += prelen;
2440 * Ok, the preimage matches with whitespace fuzz.
2442 * imgoff now holds the true length of the target that
2443 * matches the preimage before the end of the file.
2445 * Count the number of characters in the preimage that fall
2446 * beyond the end of the file and make sure that all of them
2447 * are whitespace characters. (This can only happen if
2448 * we are removing blank lines at the end of the file.)
2450 buf = preimage_eof = preimage->buf + preoff;
2451 for ( ; i < preimage->nr; i++)
2452 preoff += preimage->line[i].len;
2453 preimage_end = preimage->buf + preoff;
2454 for ( ; buf < preimage_end; buf++)
2455 if (!isspace(*buf))
2456 return 0;
2459 * Update the preimage and the common postimage context
2460 * lines to use the same whitespace as the target.
2461 * If whitespace is missing in the target (i.e.
2462 * if the preimage extends beyond the end of the file),
2463 * use the whitespace from the preimage.
2465 extra_chars = preimage_end - preimage_eof;
2466 strbuf_init(&fixed, imgoff + extra_chars);
2467 strbuf_add(&fixed, img->buf + current, imgoff);
2468 strbuf_add(&fixed, preimage_eof, extra_chars);
2469 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2470 update_pre_post_images(preimage, postimage,
2471 fixed_buf, fixed_len, postlen);
2472 return 1;
2475 static int match_fragment(struct apply_state *state,
2476 struct image *img,
2477 struct image *preimage,
2478 struct image *postimage,
2479 unsigned long current,
2480 int current_lno,
2481 unsigned ws_rule,
2482 int match_beginning, int match_end)
2484 int i;
2485 char *fixed_buf, *buf, *orig, *target;
2486 struct strbuf fixed;
2487 size_t fixed_len, postlen;
2488 int preimage_limit;
2490 if (preimage->nr + current_lno <= img->nr) {
2492 * The hunk falls within the boundaries of img.
2494 preimage_limit = preimage->nr;
2495 if (match_end && (preimage->nr + current_lno != img->nr))
2496 return 0;
2497 } else if (state->ws_error_action == correct_ws_error &&
2498 (ws_rule & WS_BLANK_AT_EOF)) {
2500 * This hunk extends beyond the end of img, and we are
2501 * removing blank lines at the end of the file. This
2502 * many lines from the beginning of the preimage must
2503 * match with img, and the remainder of the preimage
2504 * must be blank.
2506 preimage_limit = img->nr - current_lno;
2507 } else {
2509 * The hunk extends beyond the end of the img and
2510 * we are not removing blanks at the end, so we
2511 * should reject the hunk at this position.
2513 return 0;
2516 if (match_beginning && current_lno)
2517 return 0;
2519 /* Quick hash check */
2520 for (i = 0; i < preimage_limit; i++)
2521 if ((img->line[current_lno + i].flag & LINE_PATCHED) ||
2522 (preimage->line[i].hash != img->line[current_lno + i].hash))
2523 return 0;
2525 if (preimage_limit == preimage->nr) {
2527 * Do we have an exact match? If we were told to match
2528 * at the end, size must be exactly at current+fragsize,
2529 * otherwise current+fragsize must be still within the preimage,
2530 * and either case, the old piece should match the preimage
2531 * exactly.
2533 if ((match_end
2534 ? (current + preimage->len == img->len)
2535 : (current + preimage->len <= img->len)) &&
2536 !memcmp(img->buf + current, preimage->buf, preimage->len))
2537 return 1;
2538 } else {
2540 * The preimage extends beyond the end of img, so
2541 * there cannot be an exact match.
2543 * There must be one non-blank context line that match
2544 * a line before the end of img.
2546 char *buf_end;
2548 buf = preimage->buf;
2549 buf_end = buf;
2550 for (i = 0; i < preimage_limit; i++)
2551 buf_end += preimage->line[i].len;
2553 for ( ; buf < buf_end; buf++)
2554 if (!isspace(*buf))
2555 break;
2556 if (buf == buf_end)
2557 return 0;
2561 * No exact match. If we are ignoring whitespace, run a line-by-line
2562 * fuzzy matching. We collect all the line length information because
2563 * we need it to adjust whitespace if we match.
2565 if (state->ws_ignore_action == ignore_ws_change)
2566 return line_by_line_fuzzy_match(img, preimage, postimage,
2567 current, current_lno, preimage_limit);
2569 if (state->ws_error_action != correct_ws_error)
2570 return 0;
2573 * The hunk does not apply byte-by-byte, but the hash says
2574 * it might with whitespace fuzz. We weren't asked to
2575 * ignore whitespace, we were asked to correct whitespace
2576 * errors, so let's try matching after whitespace correction.
2578 * While checking the preimage against the target, whitespace
2579 * errors in both fixed, we count how large the corresponding
2580 * postimage needs to be. The postimage prepared by
2581 * apply_one_fragment() has whitespace errors fixed on added
2582 * lines already, but the common lines were propagated as-is,
2583 * which may become longer when their whitespace errors are
2584 * fixed.
2587 /* First count added lines in postimage */
2588 postlen = 0;
2589 for (i = 0; i < postimage->nr; i++) {
2590 if (!(postimage->line[i].flag & LINE_COMMON))
2591 postlen += postimage->line[i].len;
2595 * The preimage may extend beyond the end of the file,
2596 * but in this loop we will only handle the part of the
2597 * preimage that falls within the file.
2599 strbuf_init(&fixed, preimage->len + 1);
2600 orig = preimage->buf;
2601 target = img->buf + current;
2602 for (i = 0; i < preimage_limit; i++) {
2603 size_t oldlen = preimage->line[i].len;
2604 size_t tgtlen = img->line[current_lno + i].len;
2605 size_t fixstart = fixed.len;
2606 struct strbuf tgtfix;
2607 int match;
2609 /* Try fixing the line in the preimage */
2610 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2612 /* Try fixing the line in the target */
2613 strbuf_init(&tgtfix, tgtlen);
2614 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2617 * If they match, either the preimage was based on
2618 * a version before our tree fixed whitespace breakage,
2619 * or we are lacking a whitespace-fix patch the tree
2620 * the preimage was based on already had (i.e. target
2621 * has whitespace breakage, the preimage doesn't).
2622 * In either case, we are fixing the whitespace breakages
2623 * so we might as well take the fix together with their
2624 * real change.
2626 match = (tgtfix.len == fixed.len - fixstart &&
2627 !memcmp(tgtfix.buf, fixed.buf + fixstart,
2628 fixed.len - fixstart));
2630 /* Add the length if this is common with the postimage */
2631 if (preimage->line[i].flag & LINE_COMMON)
2632 postlen += tgtfix.len;
2634 strbuf_release(&tgtfix);
2635 if (!match)
2636 goto unmatch_exit;
2638 orig += oldlen;
2639 target += tgtlen;
2644 * Now handle the lines in the preimage that falls beyond the
2645 * end of the file (if any). They will only match if they are
2646 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2647 * false).
2649 for ( ; i < preimage->nr; i++) {
2650 size_t fixstart = fixed.len; /* start of the fixed preimage */
2651 size_t oldlen = preimage->line[i].len;
2652 int j;
2654 /* Try fixing the line in the preimage */
2655 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2657 for (j = fixstart; j < fixed.len; j++)
2658 if (!isspace(fixed.buf[j]))
2659 goto unmatch_exit;
2661 orig += oldlen;
2665 * Yes, the preimage is based on an older version that still
2666 * has whitespace breakages unfixed, and fixing them makes the
2667 * hunk match. Update the context lines in the postimage.
2669 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2670 if (postlen < postimage->len)
2671 postlen = 0;
2672 update_pre_post_images(preimage, postimage,
2673 fixed_buf, fixed_len, postlen);
2674 return 1;
2676 unmatch_exit:
2677 strbuf_release(&fixed);
2678 return 0;
2681 static int find_pos(struct apply_state *state,
2682 struct image *img,
2683 struct image *preimage,
2684 struct image *postimage,
2685 int line,
2686 unsigned ws_rule,
2687 int match_beginning, int match_end)
2689 int i;
2690 unsigned long backwards, forwards, current;
2691 int backwards_lno, forwards_lno, current_lno;
2694 * When running with --allow-overlap, it is possible that a hunk is
2695 * seen that pretends to start at the beginning (but no longer does),
2696 * and that *still* needs to match the end. So trust `match_end` more
2697 * than `match_beginning`.
2699 if (state->allow_overlap && match_beginning && match_end &&
2700 img->nr - preimage->nr != 0)
2701 match_beginning = 0;
2704 * If match_beginning or match_end is specified, there is no
2705 * point starting from a wrong line that will never match and
2706 * wander around and wait for a match at the specified end.
2708 if (match_beginning)
2709 line = 0;
2710 else if (match_end)
2711 line = img->nr - preimage->nr;
2714 * Because the comparison is unsigned, the following test
2715 * will also take care of a negative line number that can
2716 * result when match_end and preimage is larger than the target.
2718 if ((size_t) line > img->nr)
2719 line = img->nr;
2721 current = 0;
2722 for (i = 0; i < line; i++)
2723 current += img->line[i].len;
2726 * There's probably some smart way to do this, but I'll leave
2727 * that to the smart and beautiful people. I'm simple and stupid.
2729 backwards = current;
2730 backwards_lno = line;
2731 forwards = current;
2732 forwards_lno = line;
2733 current_lno = line;
2735 for (i = 0; ; i++) {
2736 if (match_fragment(state, img, preimage, postimage,
2737 current, current_lno, ws_rule,
2738 match_beginning, match_end))
2739 return current_lno;
2741 again:
2742 if (backwards_lno == 0 && forwards_lno == img->nr)
2743 break;
2745 if (i & 1) {
2746 if (backwards_lno == 0) {
2747 i++;
2748 goto again;
2750 backwards_lno--;
2751 backwards -= img->line[backwards_lno].len;
2752 current = backwards;
2753 current_lno = backwards_lno;
2754 } else {
2755 if (forwards_lno == img->nr) {
2756 i++;
2757 goto again;
2759 forwards += img->line[forwards_lno].len;
2760 forwards_lno++;
2761 current = forwards;
2762 current_lno = forwards_lno;
2766 return -1;
2769 static void remove_first_line(struct image *img)
2771 img->buf += img->line[0].len;
2772 img->len -= img->line[0].len;
2773 img->line++;
2774 img->nr--;
2777 static void remove_last_line(struct image *img)
2779 img->len -= img->line[--img->nr].len;
2783 * The change from "preimage" and "postimage" has been found to
2784 * apply at applied_pos (counts in line numbers) in "img".
2785 * Update "img" to remove "preimage" and replace it with "postimage".
2787 static void update_image(struct apply_state *state,
2788 struct image *img,
2789 int applied_pos,
2790 struct image *preimage,
2791 struct image *postimage)
2794 * remove the copy of preimage at offset in img
2795 * and replace it with postimage
2797 int i, nr;
2798 size_t remove_count, insert_count, applied_at = 0;
2799 char *result;
2800 int preimage_limit;
2803 * If we are removing blank lines at the end of img,
2804 * the preimage may extend beyond the end.
2805 * If that is the case, we must be careful only to
2806 * remove the part of the preimage that falls within
2807 * the boundaries of img. Initialize preimage_limit
2808 * to the number of lines in the preimage that falls
2809 * within the boundaries.
2811 preimage_limit = preimage->nr;
2812 if (preimage_limit > img->nr - applied_pos)
2813 preimage_limit = img->nr - applied_pos;
2815 for (i = 0; i < applied_pos; i++)
2816 applied_at += img->line[i].len;
2818 remove_count = 0;
2819 for (i = 0; i < preimage_limit; i++)
2820 remove_count += img->line[applied_pos + i].len;
2821 insert_count = postimage->len;
2823 /* Adjust the contents */
2824 result = xmalloc(st_add3(st_sub(img->len, remove_count), insert_count, 1));
2825 memcpy(result, img->buf, applied_at);
2826 memcpy(result + applied_at, postimage->buf, postimage->len);
2827 memcpy(result + applied_at + postimage->len,
2828 img->buf + (applied_at + remove_count),
2829 img->len - (applied_at + remove_count));
2830 free(img->buf);
2831 img->buf = result;
2832 img->len += insert_count - remove_count;
2833 result[img->len] = '\0';
2835 /* Adjust the line table */
2836 nr = img->nr + postimage->nr - preimage_limit;
2837 if (preimage_limit < postimage->nr) {
2839 * NOTE: this knows that we never call remove_first_line()
2840 * on anything other than pre/post image.
2842 REALLOC_ARRAY(img->line, nr);
2843 img->line_allocated = img->line;
2845 if (preimage_limit != postimage->nr)
2846 MOVE_ARRAY(img->line + applied_pos + postimage->nr,
2847 img->line + applied_pos + preimage_limit,
2848 img->nr - (applied_pos + preimage_limit));
2849 COPY_ARRAY(img->line + applied_pos, postimage->line, postimage->nr);
2850 if (!state->allow_overlap)
2851 for (i = 0; i < postimage->nr; i++)
2852 img->line[applied_pos + i].flag |= LINE_PATCHED;
2853 img->nr = nr;
2857 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2858 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2859 * replace the part of "img" with "postimage" text.
2861 static int apply_one_fragment(struct apply_state *state,
2862 struct image *img, struct fragment *frag,
2863 int inaccurate_eof, unsigned ws_rule,
2864 int nth_fragment)
2866 int match_beginning, match_end;
2867 const char *patch = frag->patch;
2868 int size = frag->size;
2869 char *old, *oldlines;
2870 struct strbuf newlines;
2871 int new_blank_lines_at_end = 0;
2872 int found_new_blank_lines_at_end = 0;
2873 int hunk_linenr = frag->linenr;
2874 unsigned long leading, trailing;
2875 int pos, applied_pos;
2876 struct image preimage;
2877 struct image postimage;
2879 memset(&preimage, 0, sizeof(preimage));
2880 memset(&postimage, 0, sizeof(postimage));
2881 oldlines = xmalloc(size);
2882 strbuf_init(&newlines, size);
2884 old = oldlines;
2885 while (size > 0) {
2886 char first;
2887 int len = linelen(patch, size);
2888 int plen;
2889 int added_blank_line = 0;
2890 int is_blank_context = 0;
2891 size_t start;
2893 if (!len)
2894 break;
2897 * "plen" is how much of the line we should use for
2898 * the actual patch data. Normally we just remove the
2899 * first character on the line, but if the line is
2900 * followed by "\ No newline", then we also remove the
2901 * last one (which is the newline, of course).
2903 plen = len - 1;
2904 if (len < size && patch[len] == '\\')
2905 plen--;
2906 first = *patch;
2907 if (state->apply_in_reverse) {
2908 if (first == '-')
2909 first = '+';
2910 else if (first == '+')
2911 first = '-';
2914 switch (first) {
2915 case '\n':
2916 /* Newer GNU diff, empty context line */
2917 if (plen < 0)
2918 /* ... followed by '\No newline'; nothing */
2919 break;
2920 *old++ = '\n';
2921 strbuf_addch(&newlines, '\n');
2922 add_line_info(&preimage, "\n", 1, LINE_COMMON);
2923 add_line_info(&postimage, "\n", 1, LINE_COMMON);
2924 is_blank_context = 1;
2925 break;
2926 case ' ':
2927 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2928 ws_blank_line(patch + 1, plen))
2929 is_blank_context = 1;
2930 /* fallthrough */
2931 case '-':
2932 memcpy(old, patch + 1, plen);
2933 add_line_info(&preimage, old, plen,
2934 (first == ' ' ? LINE_COMMON : 0));
2935 old += plen;
2936 if (first == '-')
2937 break;
2938 /* fallthrough */
2939 case '+':
2940 /* --no-add does not add new lines */
2941 if (first == '+' && state->no_add)
2942 break;
2944 start = newlines.len;
2945 if (first != '+' ||
2946 !state->whitespace_error ||
2947 state->ws_error_action != correct_ws_error) {
2948 strbuf_add(&newlines, patch + 1, plen);
2950 else {
2951 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &state->applied_after_fixing_ws);
2953 add_line_info(&postimage, newlines.buf + start, newlines.len - start,
2954 (first == '+' ? 0 : LINE_COMMON));
2955 if (first == '+' &&
2956 (ws_rule & WS_BLANK_AT_EOF) &&
2957 ws_blank_line(patch + 1, plen))
2958 added_blank_line = 1;
2959 break;
2960 case '@': case '\\':
2961 /* Ignore it, we already handled it */
2962 break;
2963 default:
2964 if (state->apply_verbosity > verbosity_normal)
2965 error(_("invalid start of line: '%c'"), first);
2966 applied_pos = -1;
2967 goto out;
2969 if (added_blank_line) {
2970 if (!new_blank_lines_at_end)
2971 found_new_blank_lines_at_end = hunk_linenr;
2972 new_blank_lines_at_end++;
2974 else if (is_blank_context)
2976 else
2977 new_blank_lines_at_end = 0;
2978 patch += len;
2979 size -= len;
2980 hunk_linenr++;
2982 if (inaccurate_eof &&
2983 old > oldlines && old[-1] == '\n' &&
2984 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
2985 old--;
2986 strbuf_setlen(&newlines, newlines.len - 1);
2987 preimage.line_allocated[preimage.nr - 1].len--;
2988 postimage.line_allocated[postimage.nr - 1].len--;
2991 leading = frag->leading;
2992 trailing = frag->trailing;
2995 * A hunk to change lines at the beginning would begin with
2996 * @@ -1,L +N,M @@
2997 * but we need to be careful. -U0 that inserts before the second
2998 * line also has this pattern.
3000 * And a hunk to add to an empty file would begin with
3001 * @@ -0,0 +N,M @@
3003 * In other words, a hunk that is (frag->oldpos <= 1) with or
3004 * without leading context must match at the beginning.
3006 match_beginning = (!frag->oldpos ||
3007 (frag->oldpos == 1 && !state->unidiff_zero));
3010 * A hunk without trailing lines must match at the end.
3011 * However, we simply cannot tell if a hunk must match end
3012 * from the lack of trailing lines if the patch was generated
3013 * with unidiff without any context.
3015 match_end = !state->unidiff_zero && !trailing;
3017 pos = frag->newpos ? (frag->newpos - 1) : 0;
3018 preimage.buf = oldlines;
3019 preimage.len = old - oldlines;
3020 postimage.buf = newlines.buf;
3021 postimage.len = newlines.len;
3022 preimage.line = preimage.line_allocated;
3023 postimage.line = postimage.line_allocated;
3025 for (;;) {
3027 applied_pos = find_pos(state, img, &preimage, &postimage, pos,
3028 ws_rule, match_beginning, match_end);
3030 if (applied_pos >= 0)
3031 break;
3033 /* Am I at my context limits? */
3034 if ((leading <= state->p_context) && (trailing <= state->p_context))
3035 break;
3036 if (match_beginning || match_end) {
3037 match_beginning = match_end = 0;
3038 continue;
3042 * Reduce the number of context lines; reduce both
3043 * leading and trailing if they are equal otherwise
3044 * just reduce the larger context.
3046 if (leading >= trailing) {
3047 remove_first_line(&preimage);
3048 remove_first_line(&postimage);
3049 pos--;
3050 leading--;
3052 if (trailing > leading) {
3053 remove_last_line(&preimage);
3054 remove_last_line(&postimage);
3055 trailing--;
3059 if (applied_pos >= 0) {
3060 if (new_blank_lines_at_end &&
3061 preimage.nr + applied_pos >= img->nr &&
3062 (ws_rule & WS_BLANK_AT_EOF) &&
3063 state->ws_error_action != nowarn_ws_error) {
3064 record_ws_error(state, WS_BLANK_AT_EOF, "+", 1,
3065 found_new_blank_lines_at_end);
3066 if (state->ws_error_action == correct_ws_error) {
3067 while (new_blank_lines_at_end--)
3068 remove_last_line(&postimage);
3071 * We would want to prevent write_out_results()
3072 * from taking place in apply_patch() that follows
3073 * the callchain led us here, which is:
3074 * apply_patch->check_patch_list->check_patch->
3075 * apply_data->apply_fragments->apply_one_fragment
3077 if (state->ws_error_action == die_on_ws_error)
3078 state->apply = 0;
3081 if (state->apply_verbosity > verbosity_normal && applied_pos != pos) {
3082 int offset = applied_pos - pos;
3083 if (state->apply_in_reverse)
3084 offset = 0 - offset;
3085 fprintf_ln(stderr,
3086 Q_("Hunk #%d succeeded at %d (offset %d line).",
3087 "Hunk #%d succeeded at %d (offset %d lines).",
3088 offset),
3089 nth_fragment, applied_pos + 1, offset);
3093 * Warn if it was necessary to reduce the number
3094 * of context lines.
3096 if ((leading != frag->leading ||
3097 trailing != frag->trailing) && state->apply_verbosity > verbosity_silent)
3098 fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"
3099 " to apply fragment at %d"),
3100 leading, trailing, applied_pos+1);
3101 update_image(state, img, applied_pos, &preimage, &postimage);
3102 } else {
3103 if (state->apply_verbosity > verbosity_normal)
3104 error(_("while searching for:\n%.*s"),
3105 (int)(old - oldlines), oldlines);
3108 out:
3109 free(oldlines);
3110 strbuf_release(&newlines);
3111 free(preimage.line_allocated);
3112 free(postimage.line_allocated);
3114 return (applied_pos < 0);
3117 static int apply_binary_fragment(struct apply_state *state,
3118 struct image *img,
3119 struct patch *patch)
3121 struct fragment *fragment = patch->fragments;
3122 unsigned long len;
3123 void *dst;
3125 if (!fragment)
3126 return error(_("missing binary patch data for '%s'"),
3127 patch->new_name ?
3128 patch->new_name :
3129 patch->old_name);
3131 /* Binary patch is irreversible without the optional second hunk */
3132 if (state->apply_in_reverse) {
3133 if (!fragment->next)
3134 return error(_("cannot reverse-apply a binary patch "
3135 "without the reverse hunk to '%s'"),
3136 patch->new_name
3137 ? patch->new_name : patch->old_name);
3138 fragment = fragment->next;
3140 switch (fragment->binary_patch_method) {
3141 case BINARY_DELTA_DEFLATED:
3142 dst = patch_delta(img->buf, img->len, fragment->patch,
3143 fragment->size, &len);
3144 if (!dst)
3145 return -1;
3146 clear_image(img);
3147 img->buf = dst;
3148 img->len = len;
3149 return 0;
3150 case BINARY_LITERAL_DEFLATED:
3151 clear_image(img);
3152 img->len = fragment->size;
3153 img->buf = xmemdupz(fragment->patch, img->len);
3154 return 0;
3156 return -1;
3160 * Replace "img" with the result of applying the binary patch.
3161 * The binary patch data itself in patch->fragment is still kept
3162 * but the preimage prepared by the caller in "img" is freed here
3163 * or in the helper function apply_binary_fragment() this calls.
3165 static int apply_binary(struct apply_state *state,
3166 struct image *img,
3167 struct patch *patch)
3169 const char *name = patch->old_name ? patch->old_name : patch->new_name;
3170 struct object_id oid;
3171 const unsigned hexsz = the_hash_algo->hexsz;
3174 * For safety, we require patch index line to contain
3175 * full hex textual object ID for old and new, at least for now.
3177 if (strlen(patch->old_oid_prefix) != hexsz ||
3178 strlen(patch->new_oid_prefix) != hexsz ||
3179 get_oid_hex(patch->old_oid_prefix, &oid) ||
3180 get_oid_hex(patch->new_oid_prefix, &oid))
3181 return error(_("cannot apply binary patch to '%s' "
3182 "without full index line"), name);
3184 if (patch->old_name) {
3186 * See if the old one matches what the patch
3187 * applies to.
3189 hash_object_file(the_hash_algo, img->buf, img->len, OBJ_BLOB,
3190 &oid);
3191 if (strcmp(oid_to_hex(&oid), patch->old_oid_prefix))
3192 return error(_("the patch applies to '%s' (%s), "
3193 "which does not match the "
3194 "current contents."),
3195 name, oid_to_hex(&oid));
3197 else {
3198 /* Otherwise, the old one must be empty. */
3199 if (img->len)
3200 return error(_("the patch applies to an empty "
3201 "'%s' but it is not empty"), name);
3204 get_oid_hex(patch->new_oid_prefix, &oid);
3205 if (is_null_oid(&oid)) {
3206 clear_image(img);
3207 return 0; /* deletion patch */
3210 if (has_object(the_repository, &oid, 0)) {
3211 /* We already have the postimage */
3212 enum object_type type;
3213 unsigned long size;
3214 char *result;
3216 result = repo_read_object_file(the_repository, &oid, &type,
3217 &size);
3218 if (!result)
3219 return error(_("the necessary postimage %s for "
3220 "'%s' cannot be read"),
3221 patch->new_oid_prefix, name);
3222 clear_image(img);
3223 img->buf = result;
3224 img->len = size;
3225 } else {
3227 * We have verified buf matches the preimage;
3228 * apply the patch data to it, which is stored
3229 * in the patch->fragments->{patch,size}.
3231 if (apply_binary_fragment(state, img, patch))
3232 return error(_("binary patch does not apply to '%s'"),
3233 name);
3235 /* verify that the result matches */
3236 hash_object_file(the_hash_algo, img->buf, img->len, OBJ_BLOB,
3237 &oid);
3238 if (strcmp(oid_to_hex(&oid), patch->new_oid_prefix))
3239 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3240 name, patch->new_oid_prefix, oid_to_hex(&oid));
3243 return 0;
3246 static int apply_fragments(struct apply_state *state, struct image *img, struct patch *patch)
3248 struct fragment *frag = patch->fragments;
3249 const char *name = patch->old_name ? patch->old_name : patch->new_name;
3250 unsigned ws_rule = patch->ws_rule;
3251 unsigned inaccurate_eof = patch->inaccurate_eof;
3252 int nth = 0;
3254 if (patch->is_binary)
3255 return apply_binary(state, img, patch);
3257 while (frag) {
3258 nth++;
3259 if (apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {
3260 error(_("patch failed: %s:%ld"), name, frag->oldpos);
3261 if (!state->apply_with_reject)
3262 return -1;
3263 frag->rejected = 1;
3265 frag = frag->next;
3267 return 0;
3270 static int read_blob_object(struct strbuf *buf, const struct object_id *oid, unsigned mode)
3272 if (S_ISGITLINK(mode)) {
3273 strbuf_grow(buf, 100);
3274 strbuf_addf(buf, "Subproject commit %s\n", oid_to_hex(oid));
3275 } else {
3276 enum object_type type;
3277 unsigned long sz;
3278 char *result;
3280 result = repo_read_object_file(the_repository, oid, &type,
3281 &sz);
3282 if (!result)
3283 return -1;
3284 /* XXX read_sha1_file NUL-terminates */
3285 strbuf_attach(buf, result, sz, sz + 1);
3287 return 0;
3290 static int read_file_or_gitlink(const struct cache_entry *ce, struct strbuf *buf)
3292 if (!ce)
3293 return 0;
3294 return read_blob_object(buf, &ce->oid, ce->ce_mode);
3297 static struct patch *in_fn_table(struct apply_state *state, const char *name)
3299 struct string_list_item *item;
3301 if (!name)
3302 return NULL;
3304 item = string_list_lookup(&state->fn_table, name);
3305 if (item)
3306 return (struct patch *)item->util;
3308 return NULL;
3312 * item->util in the filename table records the status of the path.
3313 * Usually it points at a patch (whose result records the contents
3314 * of it after applying it), but it could be PATH_WAS_DELETED for a
3315 * path that a previously applied patch has already removed, or
3316 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3318 * The latter is needed to deal with a case where two paths A and B
3319 * are swapped by first renaming A to B and then renaming B to A;
3320 * moving A to B should not be prevented due to presence of B as we
3321 * will remove it in a later patch.
3323 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3324 #define PATH_WAS_DELETED ((struct patch *) -1)
3326 static int to_be_deleted(struct patch *patch)
3328 return patch == PATH_TO_BE_DELETED;
3331 static int was_deleted(struct patch *patch)
3333 return patch == PATH_WAS_DELETED;
3336 static void add_to_fn_table(struct apply_state *state, struct patch *patch)
3338 struct string_list_item *item;
3341 * Always add new_name unless patch is a deletion
3342 * This should cover the cases for normal diffs,
3343 * file creations and copies
3345 if (patch->new_name) {
3346 item = string_list_insert(&state->fn_table, patch->new_name);
3347 item->util = patch;
3351 * store a failure on rename/deletion cases because
3352 * later chunks shouldn't patch old names
3354 if ((patch->new_name == NULL) || (patch->is_rename)) {
3355 item = string_list_insert(&state->fn_table, patch->old_name);
3356 item->util = PATH_WAS_DELETED;
3360 static void prepare_fn_table(struct apply_state *state, struct patch *patch)
3363 * store information about incoming file deletion
3365 while (patch) {
3366 if ((patch->new_name == NULL) || (patch->is_rename)) {
3367 struct string_list_item *item;
3368 item = string_list_insert(&state->fn_table, patch->old_name);
3369 item->util = PATH_TO_BE_DELETED;
3371 patch = patch->next;
3375 static int checkout_target(struct index_state *istate,
3376 struct cache_entry *ce, struct stat *st)
3378 struct checkout costate = CHECKOUT_INIT;
3380 costate.refresh_cache = 1;
3381 costate.istate = istate;
3382 if (checkout_entry(ce, &costate, NULL, NULL) ||
3383 lstat(ce->name, st))
3384 return error(_("cannot checkout %s"), ce->name);
3385 return 0;
3388 static struct patch *previous_patch(struct apply_state *state,
3389 struct patch *patch,
3390 int *gone)
3392 struct patch *previous;
3394 *gone = 0;
3395 if (patch->is_copy || patch->is_rename)
3396 return NULL; /* "git" patches do not depend on the order */
3398 previous = in_fn_table(state, patch->old_name);
3399 if (!previous)
3400 return NULL;
3402 if (to_be_deleted(previous))
3403 return NULL; /* the deletion hasn't happened yet */
3405 if (was_deleted(previous))
3406 *gone = 1;
3408 return previous;
3411 static int verify_index_match(struct apply_state *state,
3412 const struct cache_entry *ce,
3413 struct stat *st)
3415 if (S_ISGITLINK(ce->ce_mode)) {
3416 if (!S_ISDIR(st->st_mode))
3417 return -1;
3418 return 0;
3420 return ie_match_stat(state->repo->index, ce, st,
3421 CE_MATCH_IGNORE_VALID | CE_MATCH_IGNORE_SKIP_WORKTREE);
3424 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3426 static int load_patch_target(struct apply_state *state,
3427 struct strbuf *buf,
3428 const struct cache_entry *ce,
3429 struct stat *st,
3430 struct patch *patch,
3431 const char *name,
3432 unsigned expected_mode)
3434 if (state->cached || state->check_index) {
3435 if (read_file_or_gitlink(ce, buf))
3436 return error(_("failed to read %s"), name);
3437 } else if (name) {
3438 if (S_ISGITLINK(expected_mode)) {
3439 if (ce)
3440 return read_file_or_gitlink(ce, buf);
3441 else
3442 return SUBMODULE_PATCH_WITHOUT_INDEX;
3443 } else if (has_symlink_leading_path(name, strlen(name))) {
3444 return error(_("reading from '%s' beyond a symbolic link"), name);
3445 } else {
3446 if (read_old_data(st, patch, name, buf))
3447 return error(_("failed to read %s"), name);
3450 return 0;
3454 * We are about to apply "patch"; populate the "image" with the
3455 * current version we have, from the working tree or from the index,
3456 * depending on the situation e.g. --cached/--index. If we are
3457 * applying a non-git patch that incrementally updates the tree,
3458 * we read from the result of a previous diff.
3460 static int load_preimage(struct apply_state *state,
3461 struct image *image,
3462 struct patch *patch, struct stat *st,
3463 const struct cache_entry *ce)
3465 struct strbuf buf = STRBUF_INIT;
3466 size_t len;
3467 char *img;
3468 struct patch *previous;
3469 int status;
3471 previous = previous_patch(state, patch, &status);
3472 if (status)
3473 return error(_("path %s has been renamed/deleted"),
3474 patch->old_name);
3475 if (previous) {
3476 /* We have a patched copy in memory; use that. */
3477 strbuf_add(&buf, previous->result, previous->resultsize);
3478 } else {
3479 status = load_patch_target(state, &buf, ce, st, patch,
3480 patch->old_name, patch->old_mode);
3481 if (status < 0)
3482 return status;
3483 else if (status == SUBMODULE_PATCH_WITHOUT_INDEX) {
3485 * There is no way to apply subproject
3486 * patch without looking at the index.
3487 * NEEDSWORK: shouldn't this be flagged
3488 * as an error???
3490 free_fragment_list(patch->fragments);
3491 patch->fragments = NULL;
3492 } else if (status) {
3493 return error(_("failed to read %s"), patch->old_name);
3497 img = strbuf_detach(&buf, &len);
3498 prepare_image(image, img, len, !patch->is_binary);
3499 return 0;
3502 static int resolve_to(struct image *image, const struct object_id *result_id)
3504 unsigned long size;
3505 enum object_type type;
3507 clear_image(image);
3509 image->buf = repo_read_object_file(the_repository, result_id, &type,
3510 &size);
3511 if (!image->buf || type != OBJ_BLOB)
3512 die("unable to read blob object %s", oid_to_hex(result_id));
3513 image->len = size;
3515 return 0;
3518 static int three_way_merge(struct apply_state *state,
3519 struct image *image,
3520 char *path,
3521 const struct object_id *base,
3522 const struct object_id *ours,
3523 const struct object_id *theirs)
3525 mmfile_t base_file, our_file, their_file;
3526 mmbuffer_t result = { NULL };
3527 enum ll_merge_result status;
3529 /* resolve trivial cases first */
3530 if (oideq(base, ours))
3531 return resolve_to(image, theirs);
3532 else if (oideq(base, theirs) || oideq(ours, theirs))
3533 return resolve_to(image, ours);
3535 read_mmblob(&base_file, base);
3536 read_mmblob(&our_file, ours);
3537 read_mmblob(&their_file, theirs);
3538 status = ll_merge(&result, path,
3539 &base_file, "base",
3540 &our_file, "ours",
3541 &their_file, "theirs",
3542 state->repo->index,
3543 NULL);
3544 if (status == LL_MERGE_BINARY_CONFLICT)
3545 warning("Cannot merge binary files: %s (%s vs. %s)",
3546 path, "ours", "theirs");
3547 free(base_file.ptr);
3548 free(our_file.ptr);
3549 free(their_file.ptr);
3550 if (status < 0 || !result.ptr) {
3551 free(result.ptr);
3552 return -1;
3554 clear_image(image);
3555 image->buf = result.ptr;
3556 image->len = result.size;
3558 return status;
3562 * When directly falling back to add/add three-way merge, we read from
3563 * the current contents of the new_name. In no cases other than that
3564 * this function will be called.
3566 static int load_current(struct apply_state *state,
3567 struct image *image,
3568 struct patch *patch)
3570 struct strbuf buf = STRBUF_INIT;
3571 int status, pos;
3572 size_t len;
3573 char *img;
3574 struct stat st;
3575 struct cache_entry *ce;
3576 char *name = patch->new_name;
3577 unsigned mode = patch->new_mode;
3579 if (!patch->is_new)
3580 BUG("patch to %s is not a creation", patch->old_name);
3582 pos = index_name_pos(state->repo->index, name, strlen(name));
3583 if (pos < 0)
3584 return error(_("%s: does not exist in index"), name);
3585 ce = state->repo->index->cache[pos];
3586 if (lstat(name, &st)) {
3587 if (errno != ENOENT)
3588 return error_errno("%s", name);
3589 if (checkout_target(state->repo->index, ce, &st))
3590 return -1;
3592 if (verify_index_match(state, ce, &st))
3593 return error(_("%s: does not match index"), name);
3595 status = load_patch_target(state, &buf, ce, &st, patch, name, mode);
3596 if (status < 0)
3597 return status;
3598 else if (status)
3599 return -1;
3600 img = strbuf_detach(&buf, &len);
3601 prepare_image(image, img, len, !patch->is_binary);
3602 return 0;
3605 static int try_threeway(struct apply_state *state,
3606 struct image *image,
3607 struct patch *patch,
3608 struct stat *st,
3609 const struct cache_entry *ce)
3611 struct object_id pre_oid, post_oid, our_oid;
3612 struct strbuf buf = STRBUF_INIT;
3613 size_t len;
3614 int status;
3615 char *img;
3616 struct image tmp_image;
3618 /* No point falling back to 3-way merge in these cases */
3619 if (patch->is_delete ||
3620 S_ISGITLINK(patch->old_mode) || S_ISGITLINK(patch->new_mode) ||
3621 (patch->is_new && !patch->direct_to_threeway) ||
3622 (patch->is_rename && !patch->lines_added && !patch->lines_deleted))
3623 return -1;
3625 /* Preimage the patch was prepared for */
3626 if (patch->is_new)
3627 write_object_file("", 0, OBJ_BLOB, &pre_oid);
3628 else if (repo_get_oid(the_repository, patch->old_oid_prefix, &pre_oid) ||
3629 read_blob_object(&buf, &pre_oid, patch->old_mode))
3630 return error(_("repository lacks the necessary blob to perform 3-way merge."));
3632 if (state->apply_verbosity > verbosity_silent && patch->direct_to_threeway)
3633 fprintf(stderr, _("Performing three-way merge...\n"));
3635 img = strbuf_detach(&buf, &len);
3636 prepare_image(&tmp_image, img, len, 1);
3637 /* Apply the patch to get the post image */
3638 if (apply_fragments(state, &tmp_image, patch) < 0) {
3639 clear_image(&tmp_image);
3640 return -1;
3642 /* post_oid is theirs */
3643 write_object_file(tmp_image.buf, tmp_image.len, OBJ_BLOB, &post_oid);
3644 clear_image(&tmp_image);
3646 /* our_oid is ours */
3647 if (patch->is_new) {
3648 if (load_current(state, &tmp_image, patch))
3649 return error(_("cannot read the current contents of '%s'"),
3650 patch->new_name);
3651 } else {
3652 if (load_preimage(state, &tmp_image, patch, st, ce))
3653 return error(_("cannot read the current contents of '%s'"),
3654 patch->old_name);
3656 write_object_file(tmp_image.buf, tmp_image.len, OBJ_BLOB, &our_oid);
3657 clear_image(&tmp_image);
3659 /* in-core three-way merge between post and our using pre as base */
3660 status = three_way_merge(state, image, patch->new_name,
3661 &pre_oid, &our_oid, &post_oid);
3662 if (status < 0) {
3663 if (state->apply_verbosity > verbosity_silent)
3664 fprintf(stderr,
3665 _("Failed to perform three-way merge...\n"));
3666 return status;
3669 if (status) {
3670 patch->conflicted_threeway = 1;
3671 if (patch->is_new)
3672 oidclr(&patch->threeway_stage[0]);
3673 else
3674 oidcpy(&patch->threeway_stage[0], &pre_oid);
3675 oidcpy(&patch->threeway_stage[1], &our_oid);
3676 oidcpy(&patch->threeway_stage[2], &post_oid);
3677 if (state->apply_verbosity > verbosity_silent)
3678 fprintf(stderr,
3679 _("Applied patch to '%s' with conflicts.\n"),
3680 patch->new_name);
3681 } else {
3682 if (state->apply_verbosity > verbosity_silent)
3683 fprintf(stderr,
3684 _("Applied patch to '%s' cleanly.\n"),
3685 patch->new_name);
3687 return 0;
3690 static int apply_data(struct apply_state *state, struct patch *patch,
3691 struct stat *st, const struct cache_entry *ce)
3693 struct image image;
3695 if (load_preimage(state, &image, patch, st, ce) < 0)
3696 return -1;
3698 if (!state->threeway || try_threeway(state, &image, patch, st, ce) < 0) {
3699 if (state->apply_verbosity > verbosity_silent &&
3700 state->threeway && !patch->direct_to_threeway)
3701 fprintf(stderr, _("Falling back to direct application...\n"));
3703 /* Note: with --reject, apply_fragments() returns 0 */
3704 if (patch->direct_to_threeway || apply_fragments(state, &image, patch) < 0)
3705 return -1;
3707 patch->result = image.buf;
3708 patch->resultsize = image.len;
3709 add_to_fn_table(state, patch);
3710 free(image.line_allocated);
3712 if (0 < patch->is_delete && patch->resultsize)
3713 return error(_("removal patch leaves file contents"));
3715 return 0;
3719 * If "patch" that we are looking at modifies or deletes what we have,
3720 * we would want it not to lose any local modification we have, either
3721 * in the working tree or in the index.
3723 * This also decides if a non-git patch is a creation patch or a
3724 * modification to an existing empty file. We do not check the state
3725 * of the current tree for a creation patch in this function; the caller
3726 * check_patch() separately makes sure (and errors out otherwise) that
3727 * the path the patch creates does not exist in the current tree.
3729 static int check_preimage(struct apply_state *state,
3730 struct patch *patch,
3731 struct cache_entry **ce,
3732 struct stat *st)
3734 const char *old_name = patch->old_name;
3735 struct patch *previous = NULL;
3736 int stat_ret = 0, status;
3737 unsigned st_mode = 0;
3739 if (!old_name)
3740 return 0;
3742 assert(patch->is_new <= 0);
3743 previous = previous_patch(state, patch, &status);
3745 if (status)
3746 return error(_("path %s has been renamed/deleted"), old_name);
3747 if (previous) {
3748 st_mode = previous->new_mode;
3749 } else if (!state->cached) {
3750 stat_ret = lstat(old_name, st);
3751 if (stat_ret && errno != ENOENT)
3752 return error_errno("%s", old_name);
3755 if (state->check_index && !previous) {
3756 int pos = index_name_pos(state->repo->index, old_name,
3757 strlen(old_name));
3758 if (pos < 0) {
3759 if (patch->is_new < 0)
3760 goto is_new;
3761 return error(_("%s: does not exist in index"), old_name);
3763 *ce = state->repo->index->cache[pos];
3764 if (stat_ret < 0) {
3765 if (checkout_target(state->repo->index, *ce, st))
3766 return -1;
3768 if (!state->cached && verify_index_match(state, *ce, st))
3769 return error(_("%s: does not match index"), old_name);
3770 if (state->cached)
3771 st_mode = (*ce)->ce_mode;
3772 } else if (stat_ret < 0) {
3773 if (patch->is_new < 0)
3774 goto is_new;
3775 return error_errno("%s", old_name);
3778 if (!state->cached && !previous)
3779 st_mode = ce_mode_from_stat(*ce, st->st_mode);
3781 if (patch->is_new < 0)
3782 patch->is_new = 0;
3783 if (!patch->old_mode)
3784 patch->old_mode = st_mode;
3785 if ((st_mode ^ patch->old_mode) & S_IFMT)
3786 return error(_("%s: wrong type"), old_name);
3787 if (st_mode != patch->old_mode)
3788 warning(_("%s has type %o, expected %o"),
3789 old_name, st_mode, patch->old_mode);
3790 if (!patch->new_mode && !patch->is_delete)
3791 patch->new_mode = st_mode;
3792 return 0;
3794 is_new:
3795 patch->is_new = 1;
3796 patch->is_delete = 0;
3797 FREE_AND_NULL(patch->old_name);
3798 return 0;
3802 #define EXISTS_IN_INDEX 1
3803 #define EXISTS_IN_WORKTREE 2
3804 #define EXISTS_IN_INDEX_AS_ITA 3
3806 static int check_to_create(struct apply_state *state,
3807 const char *new_name,
3808 int ok_if_exists)
3810 struct stat nst;
3812 if (state->check_index && (!ok_if_exists || !state->cached)) {
3813 int pos;
3815 pos = index_name_pos(state->repo->index, new_name, strlen(new_name));
3816 if (pos >= 0) {
3817 struct cache_entry *ce = state->repo->index->cache[pos];
3819 /* allow ITA, as they do not yet exist in the index */
3820 if (!ok_if_exists && !(ce->ce_flags & CE_INTENT_TO_ADD))
3821 return EXISTS_IN_INDEX;
3823 /* ITA entries can never match working tree files */
3824 if (!state->cached && (ce->ce_flags & CE_INTENT_TO_ADD))
3825 return EXISTS_IN_INDEX_AS_ITA;
3829 if (state->cached)
3830 return 0;
3832 if (!lstat(new_name, &nst)) {
3833 if (S_ISDIR(nst.st_mode) || ok_if_exists)
3834 return 0;
3836 * A leading component of new_name might be a symlink
3837 * that is going to be removed with this patch, but
3838 * still pointing at somewhere that has the path.
3839 * In such a case, path "new_name" does not exist as
3840 * far as git is concerned.
3842 if (has_symlink_leading_path(new_name, strlen(new_name)))
3843 return 0;
3845 return EXISTS_IN_WORKTREE;
3846 } else if (!is_missing_file_error(errno)) {
3847 return error_errno("%s", new_name);
3849 return 0;
3852 static void prepare_symlink_changes(struct apply_state *state, struct patch *patch)
3854 for ( ; patch; patch = patch->next) {
3855 if ((patch->old_name && S_ISLNK(patch->old_mode)) &&
3856 (patch->is_rename || patch->is_delete))
3857 /* the symlink at patch->old_name is removed */
3858 strset_add(&state->removed_symlinks, patch->old_name);
3860 if (patch->new_name && S_ISLNK(patch->new_mode))
3861 /* the symlink at patch->new_name is created or remains */
3862 strset_add(&state->kept_symlinks, patch->new_name);
3866 static int path_is_beyond_symlink_1(struct apply_state *state, struct strbuf *name)
3868 do {
3869 while (--name->len && name->buf[name->len] != '/')
3870 ; /* scan backwards */
3871 if (!name->len)
3872 break;
3873 name->buf[name->len] = '\0';
3874 if (strset_contains(&state->kept_symlinks, name->buf))
3875 return 1;
3876 if (strset_contains(&state->removed_symlinks, name->buf))
3878 * This cannot be "return 0", because we may
3879 * see a new one created at a higher level.
3881 continue;
3883 /* otherwise, check the preimage */
3884 if (state->check_index) {
3885 struct cache_entry *ce;
3887 ce = index_file_exists(state->repo->index, name->buf,
3888 name->len, ignore_case);
3889 if (ce && S_ISLNK(ce->ce_mode))
3890 return 1;
3891 } else {
3892 struct stat st;
3893 if (!lstat(name->buf, &st) && S_ISLNK(st.st_mode))
3894 return 1;
3896 } while (1);
3897 return 0;
3900 static int path_is_beyond_symlink(struct apply_state *state, const char *name_)
3902 int ret;
3903 struct strbuf name = STRBUF_INIT;
3905 assert(*name_ != '\0');
3906 strbuf_addstr(&name, name_);
3907 ret = path_is_beyond_symlink_1(state, &name);
3908 strbuf_release(&name);
3910 return ret;
3913 static int check_unsafe_path(struct patch *patch)
3915 const char *old_name = NULL;
3916 const char *new_name = NULL;
3917 if (patch->is_delete)
3918 old_name = patch->old_name;
3919 else if (!patch->is_new && !patch->is_copy)
3920 old_name = patch->old_name;
3921 if (!patch->is_delete)
3922 new_name = patch->new_name;
3924 if (old_name && !verify_path(old_name, patch->old_mode))
3925 return error(_("invalid path '%s'"), old_name);
3926 if (new_name && !verify_path(new_name, patch->new_mode))
3927 return error(_("invalid path '%s'"), new_name);
3928 return 0;
3932 * Check and apply the patch in-core; leave the result in patch->result
3933 * for the caller to write it out to the final destination.
3935 static int check_patch(struct apply_state *state, struct patch *patch)
3937 struct stat st;
3938 const char *old_name = patch->old_name;
3939 const char *new_name = patch->new_name;
3940 const char *name = old_name ? old_name : new_name;
3941 struct cache_entry *ce = NULL;
3942 struct patch *tpatch;
3943 int ok_if_exists;
3944 int status;
3946 patch->rejected = 1; /* we will drop this after we succeed */
3948 status = check_preimage(state, patch, &ce, &st);
3949 if (status)
3950 return status;
3951 old_name = patch->old_name;
3954 * A type-change diff is always split into a patch to delete
3955 * old, immediately followed by a patch to create new (see
3956 * diff.c::run_diff()); in such a case it is Ok that the entry
3957 * to be deleted by the previous patch is still in the working
3958 * tree and in the index.
3960 * A patch to swap-rename between A and B would first rename A
3961 * to B and then rename B to A. While applying the first one,
3962 * the presence of B should not stop A from getting renamed to
3963 * B; ask to_be_deleted() about the later rename. Removal of
3964 * B and rename from A to B is handled the same way by asking
3965 * was_deleted().
3967 if ((tpatch = in_fn_table(state, new_name)) &&
3968 (was_deleted(tpatch) || to_be_deleted(tpatch)))
3969 ok_if_exists = 1;
3970 else
3971 ok_if_exists = 0;
3973 if (new_name &&
3974 ((0 < patch->is_new) || patch->is_rename || patch->is_copy)) {
3975 int err = check_to_create(state, new_name, ok_if_exists);
3977 if (err && state->threeway) {
3978 patch->direct_to_threeway = 1;
3979 } else switch (err) {
3980 case 0:
3981 break; /* happy */
3982 case EXISTS_IN_INDEX:
3983 return error(_("%s: already exists in index"), new_name);
3984 case EXISTS_IN_INDEX_AS_ITA:
3985 return error(_("%s: does not match index"), new_name);
3986 case EXISTS_IN_WORKTREE:
3987 return error(_("%s: already exists in working directory"),
3988 new_name);
3989 default:
3990 return err;
3993 if (!patch->new_mode) {
3994 if (0 < patch->is_new)
3995 patch->new_mode = S_IFREG | 0644;
3996 else
3997 patch->new_mode = patch->old_mode;
4001 if (new_name && old_name) {
4002 int same = !strcmp(old_name, new_name);
4003 if (!patch->new_mode)
4004 patch->new_mode = patch->old_mode;
4005 if ((patch->old_mode ^ patch->new_mode) & S_IFMT) {
4006 if (same)
4007 return error(_("new mode (%o) of %s does not "
4008 "match old mode (%o)"),
4009 patch->new_mode, new_name,
4010 patch->old_mode);
4011 else
4012 return error(_("new mode (%o) of %s does not "
4013 "match old mode (%o) of %s"),
4014 patch->new_mode, new_name,
4015 patch->old_mode, old_name);
4019 if (!state->unsafe_paths && check_unsafe_path(patch))
4020 return -128;
4023 * An attempt to read from or delete a path that is beyond a
4024 * symbolic link will be prevented by load_patch_target() that
4025 * is called at the beginning of apply_data() so we do not
4026 * have to worry about a patch marked with "is_delete" bit
4027 * here. We however need to make sure that the patch result
4028 * is not deposited to a path that is beyond a symbolic link
4029 * here.
4031 if (!patch->is_delete && path_is_beyond_symlink(state, patch->new_name))
4032 return error(_("affected file '%s' is beyond a symbolic link"),
4033 patch->new_name);
4035 if (apply_data(state, patch, &st, ce) < 0)
4036 return error(_("%s: patch does not apply"), name);
4037 patch->rejected = 0;
4038 return 0;
4041 static int check_patch_list(struct apply_state *state, struct patch *patch)
4043 int err = 0;
4045 prepare_symlink_changes(state, patch);
4046 prepare_fn_table(state, patch);
4047 while (patch) {
4048 int res;
4049 if (state->apply_verbosity > verbosity_normal)
4050 say_patch_name(stderr,
4051 _("Checking patch %s..."), patch);
4052 res = check_patch(state, patch);
4053 if (res == -128)
4054 return -128;
4055 err |= res;
4056 patch = patch->next;
4058 return err;
4061 static int read_apply_cache(struct apply_state *state)
4063 if (state->index_file)
4064 return read_index_from(state->repo->index, state->index_file,
4065 get_git_dir());
4066 else
4067 return repo_read_index(state->repo);
4070 /* This function tries to read the object name from the current index */
4071 static int get_current_oid(struct apply_state *state, const char *path,
4072 struct object_id *oid)
4074 int pos;
4076 if (read_apply_cache(state) < 0)
4077 return -1;
4078 pos = index_name_pos(state->repo->index, path, strlen(path));
4079 if (pos < 0)
4080 return -1;
4081 oidcpy(oid, &state->repo->index->cache[pos]->oid);
4082 return 0;
4085 static int preimage_oid_in_gitlink_patch(struct patch *p, struct object_id *oid)
4088 * A usable gitlink patch has only one fragment (hunk) that looks like:
4089 * @@ -1 +1 @@
4090 * -Subproject commit <old sha1>
4091 * +Subproject commit <new sha1>
4092 * or
4093 * @@ -1 +0,0 @@
4094 * -Subproject commit <old sha1>
4095 * for a removal patch.
4097 struct fragment *hunk = p->fragments;
4098 static const char heading[] = "-Subproject commit ";
4099 char *preimage;
4101 if (/* does the patch have only one hunk? */
4102 hunk && !hunk->next &&
4103 /* is its preimage one line? */
4104 hunk->oldpos == 1 && hunk->oldlines == 1 &&
4105 /* does preimage begin with the heading? */
4106 (preimage = memchr(hunk->patch, '\n', hunk->size)) != NULL &&
4107 starts_with(++preimage, heading) &&
4108 /* does it record full SHA-1? */
4109 !get_oid_hex(preimage + sizeof(heading) - 1, oid) &&
4110 preimage[sizeof(heading) + the_hash_algo->hexsz - 1] == '\n' &&
4111 /* does the abbreviated name on the index line agree with it? */
4112 starts_with(preimage + sizeof(heading) - 1, p->old_oid_prefix))
4113 return 0; /* it all looks fine */
4115 /* we may have full object name on the index line */
4116 return get_oid_hex(p->old_oid_prefix, oid);
4119 /* Build an index that contains just the files needed for a 3way merge */
4120 static int build_fake_ancestor(struct apply_state *state, struct patch *list)
4122 struct patch *patch;
4123 struct index_state result = INDEX_STATE_INIT(state->repo);
4124 struct lock_file lock = LOCK_INIT;
4125 int res;
4127 /* Once we start supporting the reverse patch, it may be
4128 * worth showing the new sha1 prefix, but until then...
4130 for (patch = list; patch; patch = patch->next) {
4131 struct object_id oid;
4132 struct cache_entry *ce;
4133 const char *name;
4135 name = patch->old_name ? patch->old_name : patch->new_name;
4136 if (0 < patch->is_new)
4137 continue;
4139 if (S_ISGITLINK(patch->old_mode)) {
4140 if (!preimage_oid_in_gitlink_patch(patch, &oid))
4141 ; /* ok, the textual part looks sane */
4142 else
4143 return error(_("sha1 information is lacking or "
4144 "useless for submodule %s"), name);
4145 } else if (!repo_get_oid_blob(the_repository, patch->old_oid_prefix, &oid)) {
4146 ; /* ok */
4147 } else if (!patch->lines_added && !patch->lines_deleted) {
4148 /* mode-only change: update the current */
4149 if (get_current_oid(state, patch->old_name, &oid))
4150 return error(_("mode change for %s, which is not "
4151 "in current HEAD"), name);
4152 } else
4153 return error(_("sha1 information is lacking or useless "
4154 "(%s)."), name);
4156 ce = make_cache_entry(&result, patch->old_mode, &oid, name, 0, 0);
4157 if (!ce)
4158 return error(_("make_cache_entry failed for path '%s'"),
4159 name);
4160 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) {
4161 discard_cache_entry(ce);
4162 return error(_("could not add %s to temporary index"),
4163 name);
4167 hold_lock_file_for_update(&lock, state->fake_ancestor, LOCK_DIE_ON_ERROR);
4168 res = write_locked_index(&result, &lock, COMMIT_LOCK);
4169 discard_index(&result);
4171 if (res)
4172 return error(_("could not write temporary index to %s"),
4173 state->fake_ancestor);
4175 return 0;
4178 static void stat_patch_list(struct apply_state *state, struct patch *patch)
4180 int files, adds, dels;
4182 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
4183 files++;
4184 adds += patch->lines_added;
4185 dels += patch->lines_deleted;
4186 show_stats(state, patch);
4189 print_stat_summary(stdout, files, adds, dels);
4192 static void numstat_patch_list(struct apply_state *state,
4193 struct patch *patch)
4195 for ( ; patch; patch = patch->next) {
4196 const char *name;
4197 name = patch->new_name ? patch->new_name : patch->old_name;
4198 if (patch->is_binary)
4199 printf("-\t-\t");
4200 else
4201 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
4202 write_name_quoted(name, stdout, state->line_termination);
4206 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
4208 if (mode)
4209 printf(" %s mode %06o %s\n", newdelete, mode, name);
4210 else
4211 printf(" %s %s\n", newdelete, name);
4214 static void show_mode_change(struct patch *p, int show_name)
4216 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
4217 if (show_name)
4218 printf(" mode change %06o => %06o %s\n",
4219 p->old_mode, p->new_mode, p->new_name);
4220 else
4221 printf(" mode change %06o => %06o\n",
4222 p->old_mode, p->new_mode);
4226 static void show_rename_copy(struct patch *p)
4228 const char *renamecopy = p->is_rename ? "rename" : "copy";
4229 const char *old_name, *new_name;
4231 /* Find common prefix */
4232 old_name = p->old_name;
4233 new_name = p->new_name;
4234 while (1) {
4235 const char *slash_old, *slash_new;
4236 slash_old = strchr(old_name, '/');
4237 slash_new = strchr(new_name, '/');
4238 if (!slash_old ||
4239 !slash_new ||
4240 slash_old - old_name != slash_new - new_name ||
4241 memcmp(old_name, new_name, slash_new - new_name))
4242 break;
4243 old_name = slash_old + 1;
4244 new_name = slash_new + 1;
4246 /* p->old_name through old_name is the common prefix, and old_name and
4247 * new_name through the end of names are renames
4249 if (old_name != p->old_name)
4250 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
4251 (int)(old_name - p->old_name), p->old_name,
4252 old_name, new_name, p->score);
4253 else
4254 printf(" %s %s => %s (%d%%)\n", renamecopy,
4255 p->old_name, p->new_name, p->score);
4256 show_mode_change(p, 0);
4259 static void summary_patch_list(struct patch *patch)
4261 struct patch *p;
4263 for (p = patch; p; p = p->next) {
4264 if (p->is_new)
4265 show_file_mode_name("create", p->new_mode, p->new_name);
4266 else if (p->is_delete)
4267 show_file_mode_name("delete", p->old_mode, p->old_name);
4268 else {
4269 if (p->is_rename || p->is_copy)
4270 show_rename_copy(p);
4271 else {
4272 if (p->score) {
4273 printf(" rewrite %s (%d%%)\n",
4274 p->new_name, p->score);
4275 show_mode_change(p, 0);
4277 else
4278 show_mode_change(p, 1);
4284 static void patch_stats(struct apply_state *state, struct patch *patch)
4286 int lines = patch->lines_added + patch->lines_deleted;
4288 if (lines > state->max_change)
4289 state->max_change = lines;
4290 if (patch->old_name) {
4291 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
4292 if (!len)
4293 len = strlen(patch->old_name);
4294 if (len > state->max_len)
4295 state->max_len = len;
4297 if (patch->new_name) {
4298 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
4299 if (!len)
4300 len = strlen(patch->new_name);
4301 if (len > state->max_len)
4302 state->max_len = len;
4306 static int remove_file(struct apply_state *state, struct patch *patch, int rmdir_empty)
4308 if (state->update_index && !state->ita_only) {
4309 if (remove_file_from_index(state->repo->index, patch->old_name) < 0)
4310 return error(_("unable to remove %s from index"), patch->old_name);
4312 if (!state->cached) {
4313 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
4314 remove_path(patch->old_name);
4317 return 0;
4320 static int add_index_file(struct apply_state *state,
4321 const char *path,
4322 unsigned mode,
4323 void *buf,
4324 unsigned long size)
4326 struct stat st;
4327 struct cache_entry *ce;
4328 int namelen = strlen(path);
4330 ce = make_empty_cache_entry(state->repo->index, namelen);
4331 memcpy(ce->name, path, namelen);
4332 ce->ce_mode = create_ce_mode(mode);
4333 ce->ce_flags = create_ce_flags(0);
4334 ce->ce_namelen = namelen;
4335 if (state->ita_only) {
4336 ce->ce_flags |= CE_INTENT_TO_ADD;
4337 set_object_name_for_intent_to_add_entry(ce);
4338 } else if (S_ISGITLINK(mode)) {
4339 const char *s;
4341 if (!skip_prefix(buf, "Subproject commit ", &s) ||
4342 get_oid_hex(s, &ce->oid)) {
4343 discard_cache_entry(ce);
4344 return error(_("corrupt patch for submodule %s"), path);
4346 } else {
4347 if (!state->cached) {
4348 if (lstat(path, &st) < 0) {
4349 discard_cache_entry(ce);
4350 return error_errno(_("unable to stat newly "
4351 "created file '%s'"),
4352 path);
4354 fill_stat_cache_info(state->repo->index, ce, &st);
4356 if (write_object_file(buf, size, OBJ_BLOB, &ce->oid) < 0) {
4357 discard_cache_entry(ce);
4358 return error(_("unable to create backing store "
4359 "for newly created file %s"), path);
4362 if (add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) < 0) {
4363 discard_cache_entry(ce);
4364 return error(_("unable to add cache entry for %s"), path);
4367 return 0;
4371 * Returns:
4372 * -1 if an unrecoverable error happened
4373 * 0 if everything went well
4374 * 1 if a recoverable error happened
4376 static int try_create_file(struct apply_state *state, const char *path,
4377 unsigned int mode, const char *buf,
4378 unsigned long size)
4380 int fd, res;
4381 struct strbuf nbuf = STRBUF_INIT;
4383 if (S_ISGITLINK(mode)) {
4384 struct stat st;
4385 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
4386 return 0;
4387 return !!mkdir(path, 0777);
4390 if (has_symlinks && S_ISLNK(mode))
4391 /* Although buf:size is counted string, it also is NUL
4392 * terminated.
4394 return !!symlink(buf, path);
4396 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
4397 if (fd < 0)
4398 return 1;
4400 if (convert_to_working_tree(state->repo->index, path, buf, size, &nbuf, NULL)) {
4401 size = nbuf.len;
4402 buf = nbuf.buf;
4405 res = write_in_full(fd, buf, size) < 0;
4406 if (res)
4407 error_errno(_("failed to write to '%s'"), path);
4408 strbuf_release(&nbuf);
4410 if (close(fd) < 0 && !res)
4411 return error_errno(_("closing file '%s'"), path);
4413 return res ? -1 : 0;
4417 * We optimistically assume that the directories exist,
4418 * which is true 99% of the time anyway. If they don't,
4419 * we create them and try again.
4421 * Returns:
4422 * -1 on error
4423 * 0 otherwise
4425 static int create_one_file(struct apply_state *state,
4426 char *path,
4427 unsigned mode,
4428 const char *buf,
4429 unsigned long size)
4431 int res;
4433 if (state->cached)
4434 return 0;
4437 * We already try to detect whether files are beyond a symlink in our
4438 * up-front checks. But in the case where symlinks are created by any
4439 * of the intermediate hunks it can happen that our up-front checks
4440 * didn't yet see the symlink, but at the point of arriving here there
4441 * in fact is one. We thus repeat the check for symlinks here.
4443 * Note that this does not make the up-front check obsolete as the
4444 * failure mode is different:
4446 * - The up-front checks cause us to abort before we have written
4447 * anything into the working directory. So when we exit this way the
4448 * working directory remains clean.
4450 * - The checks here happen in the middle of the action where we have
4451 * already started to apply the patch. The end result will be a dirty
4452 * working directory.
4454 * Ideally, we should update the up-front checks to catch what would
4455 * happen when we apply the patch before we damage the working tree.
4456 * We have all the information necessary to do so. But for now, as a
4457 * part of embargoed security work, having this check would serve as a
4458 * reasonable first step.
4460 if (path_is_beyond_symlink(state, path))
4461 return error(_("affected file '%s' is beyond a symbolic link"), path);
4463 res = try_create_file(state, path, mode, buf, size);
4464 if (res < 0)
4465 return -1;
4466 if (!res)
4467 return 0;
4469 if (errno == ENOENT) {
4470 if (safe_create_leading_directories_no_share(path))
4471 return 0;
4472 res = try_create_file(state, path, mode, buf, size);
4473 if (res < 0)
4474 return -1;
4475 if (!res)
4476 return 0;
4479 if (errno == EEXIST || errno == EACCES) {
4480 /* We may be trying to create a file where a directory
4481 * used to be.
4483 struct stat st;
4484 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
4485 errno = EEXIST;
4488 if (errno == EEXIST) {
4489 unsigned int nr = getpid();
4491 for (;;) {
4492 char newpath[PATH_MAX];
4493 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
4494 res = try_create_file(state, newpath, mode, buf, size);
4495 if (res < 0)
4496 return -1;
4497 if (!res) {
4498 if (!rename(newpath, path))
4499 return 0;
4500 unlink_or_warn(newpath);
4501 break;
4503 if (errno != EEXIST)
4504 break;
4505 ++nr;
4508 return error_errno(_("unable to write file '%s' mode %o"),
4509 path, mode);
4512 static int add_conflicted_stages_file(struct apply_state *state,
4513 struct patch *patch)
4515 int stage, namelen;
4516 unsigned mode;
4517 struct cache_entry *ce;
4519 if (!state->update_index)
4520 return 0;
4521 namelen = strlen(patch->new_name);
4522 mode = patch->new_mode ? patch->new_mode : (S_IFREG | 0644);
4524 remove_file_from_index(state->repo->index, patch->new_name);
4525 for (stage = 1; stage < 4; stage++) {
4526 if (is_null_oid(&patch->threeway_stage[stage - 1]))
4527 continue;
4528 ce = make_empty_cache_entry(state->repo->index, namelen);
4529 memcpy(ce->name, patch->new_name, namelen);
4530 ce->ce_mode = create_ce_mode(mode);
4531 ce->ce_flags = create_ce_flags(stage);
4532 ce->ce_namelen = namelen;
4533 oidcpy(&ce->oid, &patch->threeway_stage[stage - 1]);
4534 if (add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) < 0) {
4535 discard_cache_entry(ce);
4536 return error(_("unable to add cache entry for %s"),
4537 patch->new_name);
4541 return 0;
4544 static int create_file(struct apply_state *state, struct patch *patch)
4546 char *path = patch->new_name;
4547 unsigned mode = patch->new_mode;
4548 unsigned long size = patch->resultsize;
4549 char *buf = patch->result;
4551 if (!mode)
4552 mode = S_IFREG | 0644;
4553 if (create_one_file(state, path, mode, buf, size))
4554 return -1;
4556 if (patch->conflicted_threeway)
4557 return add_conflicted_stages_file(state, patch);
4558 else if (state->update_index)
4559 return add_index_file(state, path, mode, buf, size);
4560 return 0;
4563 /* phase zero is to remove, phase one is to create */
4564 static int write_out_one_result(struct apply_state *state,
4565 struct patch *patch,
4566 int phase)
4568 if (patch->is_delete > 0) {
4569 if (phase == 0)
4570 return remove_file(state, patch, 1);
4571 return 0;
4573 if (patch->is_new > 0 || patch->is_copy) {
4574 if (phase == 1)
4575 return create_file(state, patch);
4576 return 0;
4579 * Rename or modification boils down to the same
4580 * thing: remove the old, write the new
4582 if (phase == 0)
4583 return remove_file(state, patch, patch->is_rename);
4584 if (phase == 1)
4585 return create_file(state, patch);
4586 return 0;
4589 static int write_out_one_reject(struct apply_state *state, struct patch *patch)
4591 FILE *rej;
4592 char namebuf[PATH_MAX];
4593 struct fragment *frag;
4594 int cnt = 0;
4595 struct strbuf sb = STRBUF_INIT;
4597 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
4598 if (!frag->rejected)
4599 continue;
4600 cnt++;
4603 if (!cnt) {
4604 if (state->apply_verbosity > verbosity_normal)
4605 say_patch_name(stderr,
4606 _("Applied patch %s cleanly."), patch);
4607 return 0;
4610 /* This should not happen, because a removal patch that leaves
4611 * contents are marked "rejected" at the patch level.
4613 if (!patch->new_name)
4614 die(_("internal error"));
4616 /* Say this even without --verbose */
4617 strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",
4618 "Applying patch %%s with %d rejects...",
4619 cnt),
4620 cnt);
4621 if (state->apply_verbosity > verbosity_silent)
4622 say_patch_name(stderr, sb.buf, patch);
4623 strbuf_release(&sb);
4625 cnt = strlen(patch->new_name);
4626 if (ARRAY_SIZE(namebuf) <= cnt + 5) {
4627 cnt = ARRAY_SIZE(namebuf) - 5;
4628 warning(_("truncating .rej filename to %.*s.rej"),
4629 cnt - 1, patch->new_name);
4631 memcpy(namebuf, patch->new_name, cnt);
4632 memcpy(namebuf + cnt, ".rej", 5);
4634 rej = fopen(namebuf, "w");
4635 if (!rej)
4636 return error_errno(_("cannot open %s"), namebuf);
4638 /* Normal git tools never deal with .rej, so do not pretend
4639 * this is a git patch by saying --git or giving extended
4640 * headers. While at it, maybe please "kompare" that wants
4641 * the trailing TAB and some garbage at the end of line ;-).
4643 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
4644 patch->new_name, patch->new_name);
4645 for (cnt = 1, frag = patch->fragments;
4646 frag;
4647 cnt++, frag = frag->next) {
4648 if (!frag->rejected) {
4649 if (state->apply_verbosity > verbosity_silent)
4650 fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);
4651 continue;
4653 if (state->apply_verbosity > verbosity_silent)
4654 fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);
4655 fprintf(rej, "%.*s", frag->size, frag->patch);
4656 if (frag->patch[frag->size-1] != '\n')
4657 fputc('\n', rej);
4659 fclose(rej);
4660 return -1;
4664 * Returns:
4665 * -1 if an error happened
4666 * 0 if the patch applied cleanly
4667 * 1 if the patch did not apply cleanly
4669 static int write_out_results(struct apply_state *state, struct patch *list)
4671 int phase;
4672 int errs = 0;
4673 struct patch *l;
4674 struct string_list cpath = STRING_LIST_INIT_DUP;
4676 for (phase = 0; phase < 2; phase++) {
4677 l = list;
4678 while (l) {
4679 if (l->rejected)
4680 errs = 1;
4681 else {
4682 if (write_out_one_result(state, l, phase)) {
4683 string_list_clear(&cpath, 0);
4684 return -1;
4686 if (phase == 1) {
4687 if (write_out_one_reject(state, l))
4688 errs = 1;
4689 if (l->conflicted_threeway) {
4690 string_list_append(&cpath, l->new_name);
4691 errs = 1;
4695 l = l->next;
4699 if (cpath.nr) {
4700 struct string_list_item *item;
4702 string_list_sort(&cpath);
4703 if (state->apply_verbosity > verbosity_silent) {
4704 for_each_string_list_item(item, &cpath)
4705 fprintf(stderr, "U %s\n", item->string);
4707 string_list_clear(&cpath, 0);
4710 * rerere relies on the partially merged result being in the working
4711 * tree with conflict markers, but that isn't written with --cached.
4713 if (!state->cached)
4714 repo_rerere(state->repo, 0);
4717 return errs;
4721 * Try to apply a patch.
4723 * Returns:
4724 * -128 if a bad error happened (like patch unreadable)
4725 * -1 if patch did not apply and user cannot deal with it
4726 * 0 if the patch applied
4727 * 1 if the patch did not apply but user might fix it
4729 static int apply_patch(struct apply_state *state,
4730 int fd,
4731 const char *filename,
4732 int options)
4734 size_t offset;
4735 struct strbuf buf = STRBUF_INIT; /* owns the patch text */
4736 struct patch *list = NULL, **listp = &list;
4737 int skipped_patch = 0;
4738 int res = 0;
4739 int flush_attributes = 0;
4741 state->patch_input_file = filename;
4742 if (read_patch_file(&buf, fd) < 0)
4743 return -128;
4744 offset = 0;
4745 while (offset < buf.len) {
4746 struct patch *patch;
4747 int nr;
4749 CALLOC_ARRAY(patch, 1);
4750 patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF);
4751 patch->recount = !!(options & APPLY_OPT_RECOUNT);
4752 nr = parse_chunk(state, buf.buf + offset, buf.len - offset, patch);
4753 if (nr < 0) {
4754 free_patch(patch);
4755 if (nr == -128) {
4756 res = -128;
4757 goto end;
4759 break;
4761 if (state->apply_in_reverse)
4762 reverse_patches(patch);
4763 if (use_patch(state, patch)) {
4764 patch_stats(state, patch);
4765 if (!list || !state->apply_in_reverse) {
4766 *listp = patch;
4767 listp = &patch->next;
4768 } else {
4769 patch->next = list;
4770 list = patch;
4773 if ((patch->new_name &&
4774 ends_with_path_components(patch->new_name,
4775 GITATTRIBUTES_FILE)) ||
4776 (patch->old_name &&
4777 ends_with_path_components(patch->old_name,
4778 GITATTRIBUTES_FILE)))
4779 flush_attributes = 1;
4781 else {
4782 if (state->apply_verbosity > verbosity_normal)
4783 say_patch_name(stderr, _("Skipped patch '%s'."), patch);
4784 free_patch(patch);
4785 skipped_patch++;
4787 offset += nr;
4790 if (!list && !skipped_patch) {
4791 if (!state->allow_empty) {
4792 error(_("No valid patches in input (allow with \"--allow-empty\")"));
4793 res = -128;
4795 goto end;
4798 if (state->whitespace_error && (state->ws_error_action == die_on_ws_error))
4799 state->apply = 0;
4801 state->update_index = (state->check_index || state->ita_only) && state->apply;
4802 if (state->update_index && !is_lock_file_locked(&state->lock_file)) {
4803 if (state->index_file)
4804 hold_lock_file_for_update(&state->lock_file,
4805 state->index_file,
4806 LOCK_DIE_ON_ERROR);
4807 else
4808 repo_hold_locked_index(state->repo, &state->lock_file,
4809 LOCK_DIE_ON_ERROR);
4812 if (state->check_index && read_apply_cache(state) < 0) {
4813 error(_("unable to read index file"));
4814 res = -128;
4815 goto end;
4818 if (state->check || state->apply) {
4819 int r = check_patch_list(state, list);
4820 if (r == -128) {
4821 res = -128;
4822 goto end;
4824 if (r < 0 && !state->apply_with_reject) {
4825 res = -1;
4826 goto end;
4830 if (state->apply) {
4831 int write_res = write_out_results(state, list);
4832 if (write_res < 0) {
4833 res = -128;
4834 goto end;
4836 if (write_res > 0) {
4837 /* with --3way, we still need to write the index out */
4838 res = state->apply_with_reject ? -1 : 1;
4839 goto end;
4843 if (state->fake_ancestor &&
4844 build_fake_ancestor(state, list)) {
4845 res = -128;
4846 goto end;
4849 if (state->diffstat && state->apply_verbosity > verbosity_silent)
4850 stat_patch_list(state, list);
4852 if (state->numstat && state->apply_verbosity > verbosity_silent)
4853 numstat_patch_list(state, list);
4855 if (state->summary && state->apply_verbosity > verbosity_silent)
4856 summary_patch_list(list);
4858 if (flush_attributes)
4859 reset_parsed_attributes();
4860 end:
4861 free_patch_list(list);
4862 strbuf_release(&buf);
4863 string_list_clear(&state->fn_table, 0);
4864 return res;
4867 static int apply_option_parse_exclude(const struct option *opt,
4868 const char *arg, int unset)
4870 struct apply_state *state = opt->value;
4872 BUG_ON_OPT_NEG(unset);
4874 add_name_limit(state, arg, 1);
4875 return 0;
4878 static int apply_option_parse_include(const struct option *opt,
4879 const char *arg, int unset)
4881 struct apply_state *state = opt->value;
4883 BUG_ON_OPT_NEG(unset);
4885 add_name_limit(state, arg, 0);
4886 state->has_include = 1;
4887 return 0;
4890 static int apply_option_parse_p(const struct option *opt,
4891 const char *arg,
4892 int unset)
4894 struct apply_state *state = opt->value;
4896 BUG_ON_OPT_NEG(unset);
4898 state->p_value = atoi(arg);
4899 state->p_value_known = 1;
4900 return 0;
4903 static int apply_option_parse_space_change(const struct option *opt,
4904 const char *arg, int unset)
4906 struct apply_state *state = opt->value;
4908 BUG_ON_OPT_ARG(arg);
4910 if (unset)
4911 state->ws_ignore_action = ignore_ws_none;
4912 else
4913 state->ws_ignore_action = ignore_ws_change;
4914 return 0;
4917 static int apply_option_parse_whitespace(const struct option *opt,
4918 const char *arg, int unset)
4920 struct apply_state *state = opt->value;
4922 BUG_ON_OPT_NEG(unset);
4924 state->whitespace_option = arg;
4925 if (parse_whitespace_option(state, arg))
4926 return -1;
4927 return 0;
4930 static int apply_option_parse_directory(const struct option *opt,
4931 const char *arg, int unset)
4933 struct apply_state *state = opt->value;
4935 BUG_ON_OPT_NEG(unset);
4937 strbuf_reset(&state->root);
4938 strbuf_addstr(&state->root, arg);
4939 strbuf_complete(&state->root, '/');
4940 return 0;
4943 int apply_all_patches(struct apply_state *state,
4944 int argc,
4945 const char **argv,
4946 int options)
4948 int i;
4949 int res;
4950 int errs = 0;
4951 int read_stdin = 1;
4953 for (i = 0; i < argc; i++) {
4954 const char *arg = argv[i];
4955 char *to_free = NULL;
4956 int fd;
4958 if (!strcmp(arg, "-")) {
4959 res = apply_patch(state, 0, "<stdin>", options);
4960 if (res < 0)
4961 goto end;
4962 errs |= res;
4963 read_stdin = 0;
4964 continue;
4965 } else
4966 arg = to_free = prefix_filename(state->prefix, arg);
4968 fd = open(arg, O_RDONLY);
4969 if (fd < 0) {
4970 error(_("can't open patch '%s': %s"), arg, strerror(errno));
4971 res = -128;
4972 free(to_free);
4973 goto end;
4975 read_stdin = 0;
4976 set_default_whitespace_mode(state);
4977 res = apply_patch(state, fd, arg, options);
4978 close(fd);
4979 free(to_free);
4980 if (res < 0)
4981 goto end;
4982 errs |= res;
4984 set_default_whitespace_mode(state);
4985 if (read_stdin) {
4986 res = apply_patch(state, 0, "<stdin>", options);
4987 if (res < 0)
4988 goto end;
4989 errs |= res;
4992 if (state->whitespace_error) {
4993 if (state->squelch_whitespace_errors &&
4994 state->squelch_whitespace_errors < state->whitespace_error) {
4995 int squelched =
4996 state->whitespace_error - state->squelch_whitespace_errors;
4997 warning(Q_("squelched %d whitespace error",
4998 "squelched %d whitespace errors",
4999 squelched),
5000 squelched);
5002 if (state->ws_error_action == die_on_ws_error) {
5003 error(Q_("%d line adds whitespace errors.",
5004 "%d lines add whitespace errors.",
5005 state->whitespace_error),
5006 state->whitespace_error);
5007 res = -128;
5008 goto end;
5010 if (state->applied_after_fixing_ws && state->apply)
5011 warning(Q_("%d line applied after"
5012 " fixing whitespace errors.",
5013 "%d lines applied after"
5014 " fixing whitespace errors.",
5015 state->applied_after_fixing_ws),
5016 state->applied_after_fixing_ws);
5017 else if (state->whitespace_error)
5018 warning(Q_("%d line adds whitespace errors.",
5019 "%d lines add whitespace errors.",
5020 state->whitespace_error),
5021 state->whitespace_error);
5024 if (state->update_index) {
5025 res = write_locked_index(state->repo->index, &state->lock_file, COMMIT_LOCK);
5026 if (res) {
5027 error(_("Unable to write new index file"));
5028 res = -128;
5029 goto end;
5033 res = !!errs;
5035 end:
5036 rollback_lock_file(&state->lock_file);
5038 if (state->apply_verbosity <= verbosity_silent) {
5039 set_error_routine(state->saved_error_routine);
5040 set_warn_routine(state->saved_warn_routine);
5043 if (res > -1)
5044 return res;
5045 return (res == -1 ? 1 : 128);
5048 int apply_parse_options(int argc, const char **argv,
5049 struct apply_state *state,
5050 int *force_apply, int *options,
5051 const char * const *apply_usage)
5053 struct option builtin_apply_options[] = {
5054 OPT_CALLBACK_F(0, "exclude", state, N_("path"),
5055 N_("don't apply changes matching the given path"),
5056 PARSE_OPT_NONEG, apply_option_parse_exclude),
5057 OPT_CALLBACK_F(0, "include", state, N_("path"),
5058 N_("apply changes matching the given path"),
5059 PARSE_OPT_NONEG, apply_option_parse_include),
5060 OPT_CALLBACK('p', NULL, state, N_("num"),
5061 N_("remove <num> leading slashes from traditional diff paths"),
5062 apply_option_parse_p),
5063 OPT_BOOL(0, "no-add", &state->no_add,
5064 N_("ignore additions made by the patch")),
5065 OPT_BOOL(0, "stat", &state->diffstat,
5066 N_("instead of applying the patch, output diffstat for the input")),
5067 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
5068 OPT_NOOP_NOARG(0, "binary"),
5069 OPT_BOOL(0, "numstat", &state->numstat,
5070 N_("show number of added and deleted lines in decimal notation")),
5071 OPT_BOOL(0, "summary", &state->summary,
5072 N_("instead of applying the patch, output a summary for the input")),
5073 OPT_BOOL(0, "check", &state->check,
5074 N_("instead of applying the patch, see if the patch is applicable")),
5075 OPT_BOOL(0, "index", &state->check_index,
5076 N_("make sure the patch is applicable to the current index")),
5077 OPT_BOOL('N', "intent-to-add", &state->ita_only,
5078 N_("mark new files with `git add --intent-to-add`")),
5079 OPT_BOOL(0, "cached", &state->cached,
5080 N_("apply a patch without touching the working tree")),
5081 OPT_BOOL_F(0, "unsafe-paths", &state->unsafe_paths,
5082 N_("accept a patch that touches outside the working area"),
5083 PARSE_OPT_NOCOMPLETE),
5084 OPT_BOOL(0, "apply", force_apply,
5085 N_("also apply the patch (use with --stat/--summary/--check)")),
5086 OPT_BOOL('3', "3way", &state->threeway,
5087 N_( "attempt three-way merge, fall back on normal patch if that fails")),
5088 OPT_FILENAME(0, "build-fake-ancestor", &state->fake_ancestor,
5089 N_("build a temporary index based on embedded index information")),
5090 /* Think twice before adding "--nul" synonym to this */
5091 OPT_SET_INT('z', NULL, &state->line_termination,
5092 N_("paths are separated with NUL character"), '\0'),
5093 OPT_INTEGER('C', NULL, &state->p_context,
5094 N_("ensure at least <n> lines of context match")),
5095 OPT_CALLBACK(0, "whitespace", state, N_("action"),
5096 N_("detect new or modified lines that have whitespace errors"),
5097 apply_option_parse_whitespace),
5098 OPT_CALLBACK_F(0, "ignore-space-change", state, NULL,
5099 N_("ignore changes in whitespace when finding context"),
5100 PARSE_OPT_NOARG, apply_option_parse_space_change),
5101 OPT_CALLBACK_F(0, "ignore-whitespace", state, NULL,
5102 N_("ignore changes in whitespace when finding context"),
5103 PARSE_OPT_NOARG, apply_option_parse_space_change),
5104 OPT_BOOL('R', "reverse", &state->apply_in_reverse,
5105 N_("apply the patch in reverse")),
5106 OPT_BOOL(0, "unidiff-zero", &state->unidiff_zero,
5107 N_("don't expect at least one line of context")),
5108 OPT_BOOL(0, "reject", &state->apply_with_reject,
5109 N_("leave the rejected hunks in corresponding *.rej files")),
5110 OPT_BOOL(0, "allow-overlap", &state->allow_overlap,
5111 N_("allow overlapping hunks")),
5112 OPT__VERBOSITY(&state->apply_verbosity),
5113 OPT_BIT(0, "inaccurate-eof", options,
5114 N_("tolerate incorrectly detected missing new-line at the end of file"),
5115 APPLY_OPT_INACCURATE_EOF),
5116 OPT_BIT(0, "recount", options,
5117 N_("do not trust the line counts in the hunk headers"),
5118 APPLY_OPT_RECOUNT),
5119 OPT_CALLBACK(0, "directory", state, N_("root"),
5120 N_("prepend <root> to all filenames"),
5121 apply_option_parse_directory),
5122 OPT_BOOL(0, "allow-empty", &state->allow_empty,
5123 N_("don't return error for empty patches")),
5124 OPT_END()
5127 return parse_options(argc, argv, state->prefix, builtin_apply_options, apply_usage, 0);