The fifth batch
[git.git] / apply.c
blob4a7b6120ac866e5bdae532da1d6946e94c7ec207
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 #define USE_THE_REPOSITORY_VARIABLE
11 #define DISABLE_SIGN_COMPARE_WARNINGS
13 #include "git-compat-util.h"
14 #include "abspath.h"
15 #include "base85.h"
16 #include "config.h"
17 #include "object-store-ll.h"
18 #include "delta.h"
19 #include "diff.h"
20 #include "dir.h"
21 #include "environment.h"
22 #include "gettext.h"
23 #include "hex.h"
24 #include "xdiff-interface.h"
25 #include "merge-ll.h"
26 #include "lockfile.h"
27 #include "name-hash.h"
28 #include "object-name.h"
29 #include "object-file.h"
30 #include "parse-options.h"
31 #include "path.h"
32 #include "quote.h"
33 #include "read-cache.h"
34 #include "repository.h"
35 #include "rerere.h"
36 #include "apply.h"
37 #include "entry.h"
38 #include "setup.h"
39 #include "symlinks.h"
40 #include "wildmatch.h"
41 #include "ws.h"
43 struct gitdiff_data {
44 struct strbuf *root;
45 int linenr;
46 int p_value;
49 static void git_apply_config(void)
51 git_config_get_string("apply.whitespace", &apply_default_whitespace);
52 git_config_get_string("apply.ignorewhitespace", &apply_default_ignorewhitespace);
53 git_config(git_xmerge_config, NULL);
56 static int parse_whitespace_option(struct apply_state *state, const char *option)
58 if (!option) {
59 state->ws_error_action = warn_on_ws_error;
60 return 0;
62 if (!strcmp(option, "warn")) {
63 state->ws_error_action = warn_on_ws_error;
64 return 0;
66 if (!strcmp(option, "nowarn")) {
67 state->ws_error_action = nowarn_ws_error;
68 return 0;
70 if (!strcmp(option, "error")) {
71 state->ws_error_action = die_on_ws_error;
72 return 0;
74 if (!strcmp(option, "error-all")) {
75 state->ws_error_action = die_on_ws_error;
76 state->squelch_whitespace_errors = 0;
77 return 0;
79 if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
80 state->ws_error_action = correct_ws_error;
81 return 0;
84 * Please update $__git_whitespacelist in git-completion.bash,
85 * Documentation/git-apply.txt, and Documentation/git-am.txt
86 * when you add new options.
88 return error(_("unrecognized whitespace option '%s'"), option);
91 static int parse_ignorewhitespace_option(struct apply_state *state,
92 const char *option)
94 if (!option || !strcmp(option, "no") ||
95 !strcmp(option, "false") || !strcmp(option, "never") ||
96 !strcmp(option, "none")) {
97 state->ws_ignore_action = ignore_ws_none;
98 return 0;
100 if (!strcmp(option, "change")) {
101 state->ws_ignore_action = ignore_ws_change;
102 return 0;
104 return error(_("unrecognized whitespace ignore option '%s'"), option);
107 int init_apply_state(struct apply_state *state,
108 struct repository *repo,
109 const char *prefix)
111 memset(state, 0, sizeof(*state));
112 state->prefix = prefix;
113 state->repo = repo;
114 state->apply = 1;
115 state->line_termination = '\n';
116 state->p_value = 1;
117 state->p_context = UINT_MAX;
118 state->squelch_whitespace_errors = 5;
119 state->ws_error_action = warn_on_ws_error;
120 state->ws_ignore_action = ignore_ws_none;
121 state->linenr = 1;
122 string_list_init_nodup(&state->fn_table);
123 string_list_init_nodup(&state->limit_by_name);
124 strset_init(&state->removed_symlinks);
125 strset_init(&state->kept_symlinks);
126 strbuf_init(&state->root, 0);
128 git_apply_config();
129 if (apply_default_whitespace && parse_whitespace_option(state, apply_default_whitespace))
130 return -1;
131 if (apply_default_ignorewhitespace && parse_ignorewhitespace_option(state, apply_default_ignorewhitespace))
132 return -1;
133 return 0;
136 void clear_apply_state(struct apply_state *state)
138 string_list_clear(&state->limit_by_name, 0);
139 strset_clear(&state->removed_symlinks);
140 strset_clear(&state->kept_symlinks);
141 strbuf_release(&state->root);
142 FREE_AND_NULL(state->fake_ancestor);
144 /* &state->fn_table is cleared at the end of apply_patch() */
147 static void mute_routine(const char *msg UNUSED, va_list params UNUSED)
149 /* do nothing */
152 int check_apply_state(struct apply_state *state, int force_apply)
154 int is_not_gitdir = !startup_info->have_repository;
156 if (state->apply_with_reject && state->threeway)
157 return error(_("options '%s' and '%s' cannot be used together"), "--reject", "--3way");
158 if (state->threeway) {
159 if (is_not_gitdir)
160 return error(_("'%s' outside a repository"), "--3way");
161 state->check_index = 1;
163 if (state->apply_with_reject) {
164 state->apply = 1;
165 if (state->apply_verbosity == verbosity_normal)
166 state->apply_verbosity = verbosity_verbose;
168 if (!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor))
169 state->apply = 0;
170 if (state->check_index && is_not_gitdir)
171 return error(_("'%s' outside a repository"), "--index");
172 if (state->cached) {
173 if (is_not_gitdir)
174 return error(_("'%s' outside a repository"), "--cached");
175 state->check_index = 1;
177 if (state->ita_only && (state->check_index || is_not_gitdir))
178 state->ita_only = 0;
179 if (state->check_index)
180 state->unsafe_paths = 0;
182 if (state->apply_verbosity <= verbosity_silent) {
183 state->saved_error_routine = get_error_routine();
184 state->saved_warn_routine = get_warn_routine();
185 set_error_routine(mute_routine);
186 set_warn_routine(mute_routine);
189 return 0;
192 static void set_default_whitespace_mode(struct apply_state *state)
194 if (!state->whitespace_option && !apply_default_whitespace)
195 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error);
199 * This represents one "hunk" from a patch, starting with
200 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
201 * patch text is pointed at by patch, and its byte length
202 * is stored in size. leading and trailing are the number
203 * of context lines.
205 struct fragment {
206 unsigned long leading, trailing;
207 unsigned long oldpos, oldlines;
208 unsigned long newpos, newlines;
210 * 'patch' is usually borrowed from buf in apply_patch(),
211 * but some codepaths store an allocated buffer.
213 const char *patch;
214 unsigned free_patch:1,
215 rejected:1;
216 int size;
217 int linenr;
218 struct fragment *next;
222 * When dealing with a binary patch, we reuse "leading" field
223 * to store the type of the binary hunk, either deflated "delta"
224 * or deflated "literal".
226 #define binary_patch_method leading
227 #define BINARY_DELTA_DEFLATED 1
228 #define BINARY_LITERAL_DEFLATED 2
230 static void free_fragment_list(struct fragment *list)
232 while (list) {
233 struct fragment *next = list->next;
234 if (list->free_patch)
235 free((char *)list->patch);
236 free(list);
237 list = next;
241 void release_patch(struct patch *patch)
243 free_fragment_list(patch->fragments);
244 free(patch->def_name);
245 free(patch->old_name);
246 free(patch->new_name);
247 free(patch->result);
250 static void free_patch(struct patch *patch)
252 release_patch(patch);
253 free(patch);
256 static void free_patch_list(struct patch *list)
258 while (list) {
259 struct patch *next = list->next;
260 free_patch(list);
261 list = next;
266 * A line in a file, len-bytes long (includes the terminating LF,
267 * except for an incomplete line at the end if the file ends with
268 * one), and its contents hashes to 'hash'.
270 struct line {
271 size_t len;
272 unsigned hash : 24;
273 unsigned flag : 8;
274 #define LINE_COMMON 1
275 #define LINE_PATCHED 2
279 * This represents a "file", which is an array of "lines".
281 struct image {
282 struct strbuf buf;
283 struct line *line;
284 size_t line_nr, line_alloc;
286 #define IMAGE_INIT { \
287 .buf = STRBUF_INIT, \
290 static void image_init(struct image *image)
292 struct image empty = IMAGE_INIT;
293 memcpy(image, &empty, sizeof(*image));
296 static void image_clear(struct image *image)
298 strbuf_release(&image->buf);
299 free(image->line);
300 image_init(image);
303 static uint32_t hash_line(const char *cp, size_t len)
305 size_t i;
306 uint32_t h;
307 for (i = 0, h = 0; i < len; i++) {
308 if (!isspace(cp[i])) {
309 h = h * 3 + (cp[i] & 0xff);
312 return h;
315 static void image_add_line(struct image *img, const char *bol, size_t len, unsigned flag)
317 ALLOC_GROW(img->line, img->line_nr + 1, img->line_alloc);
318 img->line[img->line_nr].len = len;
319 img->line[img->line_nr].hash = hash_line(bol, len);
320 img->line[img->line_nr].flag = flag;
321 img->line_nr++;
325 * "buf" has the file contents to be patched (read from various sources).
326 * attach it to "image" and add line-based index to it.
327 * "image" now owns the "buf".
329 static void image_prepare(struct image *image, char *buf, size_t len,
330 int prepare_linetable)
332 const char *cp, *ep;
334 image_clear(image);
335 strbuf_attach(&image->buf, buf, len, len + 1);
337 if (!prepare_linetable)
338 return;
340 ep = image->buf.buf + image->buf.len;
341 cp = image->buf.buf;
342 while (cp < ep) {
343 const char *next;
344 for (next = cp; next < ep && *next != '\n'; next++)
346 if (next < ep)
347 next++;
348 image_add_line(image, cp, next - cp, 0);
349 cp = next;
353 static void image_remove_first_line(struct image *img)
355 strbuf_remove(&img->buf, 0, img->line[0].len);
356 img->line_nr--;
357 if (img->line_nr)
358 MOVE_ARRAY(img->line, img->line + 1, img->line_nr);
361 static void image_remove_last_line(struct image *img)
363 size_t last_line_len = img->line[img->line_nr - 1].len;
364 strbuf_setlen(&img->buf, img->buf.len - last_line_len);
365 img->line_nr--;
368 /* fmt must contain _one_ %s and no other substitution */
369 static void say_patch_name(FILE *output, const char *fmt, struct patch *patch)
371 struct strbuf sb = STRBUF_INIT;
373 if (patch->old_name && patch->new_name &&
374 strcmp(patch->old_name, patch->new_name)) {
375 quote_c_style(patch->old_name, &sb, NULL, 0);
376 strbuf_addstr(&sb, " => ");
377 quote_c_style(patch->new_name, &sb, NULL, 0);
378 } else {
379 const char *n = patch->new_name;
380 if (!n)
381 n = patch->old_name;
382 quote_c_style(n, &sb, NULL, 0);
384 fprintf(output, fmt, sb.buf);
385 fputc('\n', output);
386 strbuf_release(&sb);
389 #define SLOP (16)
392 * apply.c isn't equipped to handle arbitrarily large patches, because
393 * it intermingles `unsigned long` with `int` for the type used to store
394 * buffer lengths.
396 * Only process patches that are just shy of 1 GiB large in order to
397 * avoid any truncation or overflow issues.
399 #define MAX_APPLY_SIZE (1024UL * 1024 * 1023)
401 static int read_patch_file(struct strbuf *sb, int fd)
403 if (strbuf_read(sb, fd, 0) < 0)
404 return error_errno(_("failed to read patch"));
405 else if (sb->len >= MAX_APPLY_SIZE)
406 return error(_("patch too large"));
408 * Make sure that we have some slop in the buffer
409 * so that we can do speculative "memcmp" etc, and
410 * see to it that it is NUL-filled.
412 strbuf_grow(sb, SLOP);
413 memset(sb->buf + sb->len, 0, SLOP);
414 return 0;
417 static unsigned long linelen(const char *buffer, unsigned long size)
419 unsigned long len = 0;
420 while (size--) {
421 len++;
422 if (*buffer++ == '\n')
423 break;
425 return len;
428 static int is_dev_null(const char *str)
430 return skip_prefix(str, "/dev/null", &str) && isspace(*str);
433 #define TERM_SPACE 1
434 #define TERM_TAB 2
436 static int name_terminate(int c, int terminate)
438 if (c == ' ' && !(terminate & TERM_SPACE))
439 return 0;
440 if (c == '\t' && !(terminate & TERM_TAB))
441 return 0;
443 return 1;
446 /* remove double slashes to make --index work with such filenames */
447 static char *squash_slash(char *name)
449 int i = 0, j = 0;
451 if (!name)
452 return NULL;
454 while (name[i]) {
455 if ((name[j++] = name[i++]) == '/')
456 while (name[i] == '/')
457 i++;
459 name[j] = '\0';
460 return name;
463 static char *find_name_gnu(struct strbuf *root,
464 const char *line,
465 int p_value)
467 struct strbuf name = STRBUF_INIT;
468 char *cp;
471 * Proposed "new-style" GNU patch/diff format; see
472 * https://lore.kernel.org/git/7vll0wvb2a.fsf@assigned-by-dhcp.cox.net/
474 if (unquote_c_style(&name, line, NULL)) {
475 strbuf_release(&name);
476 return NULL;
479 for (cp = name.buf; p_value; p_value--) {
480 cp = strchr(cp, '/');
481 if (!cp) {
482 strbuf_release(&name);
483 return NULL;
485 cp++;
488 strbuf_remove(&name, 0, cp - name.buf);
489 if (root->len)
490 strbuf_insert(&name, 0, root->buf, root->len);
491 return squash_slash(strbuf_detach(&name, NULL));
494 static size_t sane_tz_len(const char *line, size_t len)
496 const char *tz, *p;
498 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
499 return 0;
500 tz = line + len - strlen(" +0500");
502 if (tz[1] != '+' && tz[1] != '-')
503 return 0;
505 for (p = tz + 2; p != line + len; p++)
506 if (!isdigit(*p))
507 return 0;
509 return line + len - tz;
512 static size_t tz_with_colon_len(const char *line, size_t len)
514 const char *tz, *p;
516 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
517 return 0;
518 tz = line + len - strlen(" +08:00");
520 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
521 return 0;
522 p = tz + 2;
523 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
524 !isdigit(*p++) || !isdigit(*p++))
525 return 0;
527 return line + len - tz;
530 static size_t date_len(const char *line, size_t len)
532 const char *date, *p;
534 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
535 return 0;
536 p = date = line + len - strlen("72-02-05");
538 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
539 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
540 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */
541 return 0;
543 if (date - line >= strlen("19") &&
544 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */
545 date -= strlen("19");
547 return line + len - date;
550 static size_t short_time_len(const char *line, size_t len)
552 const char *time, *p;
554 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
555 return 0;
556 p = time = line + len - strlen(" 07:01:32");
558 /* Permit 1-digit hours? */
559 if (*p++ != ' ' ||
560 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
561 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
562 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */
563 return 0;
565 return line + len - time;
568 static size_t fractional_time_len(const char *line, size_t len)
570 const char *p;
571 size_t n;
573 /* Expected format: 19:41:17.620000023 */
574 if (!len || !isdigit(line[len - 1]))
575 return 0;
576 p = line + len - 1;
578 /* Fractional seconds. */
579 while (p > line && isdigit(*p))
580 p--;
581 if (*p != '.')
582 return 0;
584 /* Hours, minutes, and whole seconds. */
585 n = short_time_len(line, p - line);
586 if (!n)
587 return 0;
589 return line + len - p + n;
592 static size_t trailing_spaces_len(const char *line, size_t len)
594 const char *p;
596 /* Expected format: ' ' x (1 or more) */
597 if (!len || line[len - 1] != ' ')
598 return 0;
600 p = line + len;
601 while (p != line) {
602 p--;
603 if (*p != ' ')
604 return line + len - (p + 1);
607 /* All spaces! */
608 return len;
611 static size_t diff_timestamp_len(const char *line, size_t len)
613 const char *end = line + len;
614 size_t n;
617 * Posix: 2010-07-05 19:41:17
618 * GNU: 2010-07-05 19:41:17.620000023 -0500
621 if (!isdigit(end[-1]))
622 return 0;
624 n = sane_tz_len(line, end - line);
625 if (!n)
626 n = tz_with_colon_len(line, end - line);
627 end -= n;
629 n = short_time_len(line, end - line);
630 if (!n)
631 n = fractional_time_len(line, end - line);
632 end -= n;
634 n = date_len(line, end - line);
635 if (!n) /* No date. Too bad. */
636 return 0;
637 end -= n;
639 if (end == line) /* No space before date. */
640 return 0;
641 if (end[-1] == '\t') { /* Success! */
642 end--;
643 return line + len - end;
645 if (end[-1] != ' ') /* No space before date. */
646 return 0;
648 /* Whitespace damage. */
649 end -= trailing_spaces_len(line, end - line);
650 return line + len - end;
653 static char *find_name_common(struct strbuf *root,
654 const char *line,
655 const char *def,
656 int p_value,
657 const char *end,
658 int terminate)
660 int len;
661 const char *start = NULL;
663 if (p_value == 0)
664 start = line;
665 while (line != end) {
666 char c = *line;
668 if (!end && isspace(c)) {
669 if (c == '\n')
670 break;
671 if (name_terminate(c, terminate))
672 break;
674 line++;
675 if (c == '/' && !--p_value)
676 start = line;
678 if (!start)
679 return squash_slash(xstrdup_or_null(def));
680 len = line - start;
681 if (!len)
682 return squash_slash(xstrdup_or_null(def));
685 * Generally we prefer the shorter name, especially
686 * if the other one is just a variation of that with
687 * something else tacked on to the end (ie "file.orig"
688 * or "file~").
690 if (def) {
691 int deflen = strlen(def);
692 if (deflen < len && !strncmp(start, def, deflen))
693 return squash_slash(xstrdup(def));
696 if (root->len) {
697 char *ret = xstrfmt("%s%.*s", root->buf, len, start);
698 return squash_slash(ret);
701 return squash_slash(xmemdupz(start, len));
704 static char *find_name(struct strbuf *root,
705 const char *line,
706 char *def,
707 int p_value,
708 int terminate)
710 if (*line == '"') {
711 char *name = find_name_gnu(root, line, p_value);
712 if (name)
713 return name;
716 return find_name_common(root, line, def, p_value, NULL, terminate);
719 static char *find_name_traditional(struct strbuf *root,
720 const char *line,
721 char *def,
722 int p_value)
724 size_t len;
725 size_t date_len;
727 if (*line == '"') {
728 char *name = find_name_gnu(root, line, p_value);
729 if (name)
730 return name;
733 len = strchrnul(line, '\n') - line;
734 date_len = diff_timestamp_len(line, len);
735 if (!date_len)
736 return find_name_common(root, line, def, p_value, NULL, TERM_TAB);
737 len -= date_len;
739 return find_name_common(root, line, def, p_value, line + len, 0);
743 * Given the string after "--- " or "+++ ", guess the appropriate
744 * p_value for the given patch.
746 static int guess_p_value(struct apply_state *state, const char *nameline)
748 char *name, *cp;
749 int val = -1;
751 if (is_dev_null(nameline))
752 return -1;
753 name = find_name_traditional(&state->root, nameline, NULL, 0);
754 if (!name)
755 return -1;
756 cp = strchr(name, '/');
757 if (!cp)
758 val = 0;
759 else if (state->prefix) {
761 * Does it begin with "a/$our-prefix" and such? Then this is
762 * very likely to apply to our directory.
764 if (starts_with(name, state->prefix))
765 val = count_slashes(state->prefix);
766 else {
767 cp++;
768 if (starts_with(cp, state->prefix))
769 val = count_slashes(state->prefix) + 1;
772 free(name);
773 return val;
777 * Does the ---/+++ line have the POSIX timestamp after the last HT?
778 * GNU diff puts epoch there to signal a creation/deletion event. Is
779 * this such a timestamp?
781 static int has_epoch_timestamp(const char *nameline)
784 * We are only interested in epoch timestamp; any non-zero
785 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
786 * For the same reason, the date must be either 1969-12-31 or
787 * 1970-01-01, and the seconds part must be "00".
789 const char stamp_regexp[] =
790 "^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?"
792 "([-+][0-2][0-9]:?[0-5][0-9])\n";
793 const char *timestamp = NULL, *cp, *colon;
794 static regex_t *stamp;
795 regmatch_t m[10];
796 int zoneoffset, epoch_hour, hour, minute;
797 int status;
799 for (cp = nameline; *cp != '\n'; cp++) {
800 if (*cp == '\t')
801 timestamp = cp + 1;
803 if (!timestamp)
804 return 0;
807 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
808 * (west of GMT) or 1970-01-01 (east of GMT)
810 if (skip_prefix(timestamp, "1969-12-31 ", &timestamp))
811 epoch_hour = 24;
812 else if (skip_prefix(timestamp, "1970-01-01 ", &timestamp))
813 epoch_hour = 0;
814 else
815 return 0;
817 if (!stamp) {
818 stamp = xmalloc(sizeof(*stamp));
819 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
820 warning(_("Cannot prepare timestamp regexp %s"),
821 stamp_regexp);
822 return 0;
826 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
827 if (status) {
828 if (status != REG_NOMATCH)
829 warning(_("regexec returned %d for input: %s"),
830 status, timestamp);
831 return 0;
834 hour = strtol(timestamp, NULL, 10);
835 minute = strtol(timestamp + m[1].rm_so, NULL, 10);
837 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
838 if (*colon == ':')
839 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
840 else
841 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
842 if (timestamp[m[3].rm_so] == '-')
843 zoneoffset = -zoneoffset;
845 return hour * 60 + minute - zoneoffset == epoch_hour * 60;
849 * Get the name etc info from the ---/+++ lines of a traditional patch header
851 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
852 * files, we can happily check the index for a match, but for creating a
853 * new file we should try to match whatever "patch" does. I have no idea.
855 static int parse_traditional_patch(struct apply_state *state,
856 const char *first,
857 const char *second,
858 struct patch *patch)
860 char *name;
862 first += 4; /* skip "--- " */
863 second += 4; /* skip "+++ " */
864 if (!state->p_value_known) {
865 int p, q;
866 p = guess_p_value(state, first);
867 q = guess_p_value(state, second);
868 if (p < 0) p = q;
869 if (0 <= p && p == q) {
870 state->p_value = p;
871 state->p_value_known = 1;
874 if (is_dev_null(first)) {
875 patch->is_new = 1;
876 patch->is_delete = 0;
877 name = find_name_traditional(&state->root, second, NULL, state->p_value);
878 patch->new_name = name;
879 } else if (is_dev_null(second)) {
880 patch->is_new = 0;
881 patch->is_delete = 1;
882 name = find_name_traditional(&state->root, first, NULL, state->p_value);
883 patch->old_name = name;
884 } else {
885 char *first_name;
886 first_name = find_name_traditional(&state->root, first, NULL, state->p_value);
887 name = find_name_traditional(&state->root, second, first_name, state->p_value);
888 free(first_name);
889 if (has_epoch_timestamp(first)) {
890 patch->is_new = 1;
891 patch->is_delete = 0;
892 patch->new_name = name;
893 } else if (has_epoch_timestamp(second)) {
894 patch->is_new = 0;
895 patch->is_delete = 1;
896 patch->old_name = name;
897 } else {
898 patch->old_name = name;
899 patch->new_name = xstrdup_or_null(name);
902 if (!name)
903 return error(_("unable to find filename in patch at line %d"), state->linenr);
905 return 0;
908 static int gitdiff_hdrend(struct gitdiff_data *state UNUSED,
909 const char *line UNUSED,
910 struct patch *patch UNUSED)
912 return 1;
916 * We're anal about diff header consistency, to make
917 * sure that we don't end up having strange ambiguous
918 * patches floating around.
920 * As a result, gitdiff_{old|new}name() will check
921 * their names against any previous information, just
922 * to make sure..
924 #define DIFF_OLD_NAME 0
925 #define DIFF_NEW_NAME 1
927 static int gitdiff_verify_name(struct gitdiff_data *state,
928 const char *line,
929 int isnull,
930 char **name,
931 int side)
933 if (!*name && !isnull) {
934 *name = find_name(state->root, line, NULL, state->p_value, TERM_TAB);
935 return 0;
938 if (*name) {
939 char *another;
940 if (isnull)
941 return error(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
942 *name, state->linenr);
943 another = find_name(state->root, line, NULL, state->p_value, TERM_TAB);
944 if (!another || strcmp(another, *name)) {
945 free(another);
946 return error((side == DIFF_NEW_NAME) ?
947 _("git apply: bad git-diff - inconsistent new filename on line %d") :
948 _("git apply: bad git-diff - inconsistent old filename on line %d"), state->linenr);
950 free(another);
951 } else {
952 if (!is_dev_null(line))
953 return error(_("git apply: bad git-diff - expected /dev/null on line %d"), state->linenr);
956 return 0;
959 static int gitdiff_oldname(struct gitdiff_data *state,
960 const char *line,
961 struct patch *patch)
963 return gitdiff_verify_name(state, line,
964 patch->is_new, &patch->old_name,
965 DIFF_OLD_NAME);
968 static int gitdiff_newname(struct gitdiff_data *state,
969 const char *line,
970 struct patch *patch)
972 return gitdiff_verify_name(state, line,
973 patch->is_delete, &patch->new_name,
974 DIFF_NEW_NAME);
977 static int parse_mode_line(const char *line, int linenr, unsigned int *mode)
979 char *end;
980 *mode = strtoul(line, &end, 8);
981 if (end == line || !isspace(*end))
982 return error(_("invalid mode on line %d: %s"), linenr, line);
983 *mode = canon_mode(*mode);
984 return 0;
987 static int gitdiff_oldmode(struct gitdiff_data *state,
988 const char *line,
989 struct patch *patch)
991 return parse_mode_line(line, state->linenr, &patch->old_mode);
994 static int gitdiff_newmode(struct gitdiff_data *state,
995 const char *line,
996 struct patch *patch)
998 return parse_mode_line(line, state->linenr, &patch->new_mode);
1001 static int gitdiff_delete(struct gitdiff_data *state,
1002 const char *line,
1003 struct patch *patch)
1005 patch->is_delete = 1;
1006 free(patch->old_name);
1007 patch->old_name = xstrdup_or_null(patch->def_name);
1008 return gitdiff_oldmode(state, line, patch);
1011 static int gitdiff_newfile(struct gitdiff_data *state,
1012 const char *line,
1013 struct patch *patch)
1015 patch->is_new = 1;
1016 free(patch->new_name);
1017 patch->new_name = xstrdup_or_null(patch->def_name);
1018 return gitdiff_newmode(state, line, patch);
1021 static int gitdiff_copysrc(struct gitdiff_data *state,
1022 const char *line,
1023 struct patch *patch)
1025 patch->is_copy = 1;
1026 free(patch->old_name);
1027 patch->old_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1028 return 0;
1031 static int gitdiff_copydst(struct gitdiff_data *state,
1032 const char *line,
1033 struct patch *patch)
1035 patch->is_copy = 1;
1036 free(patch->new_name);
1037 patch->new_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1038 return 0;
1041 static int gitdiff_renamesrc(struct gitdiff_data *state,
1042 const char *line,
1043 struct patch *patch)
1045 patch->is_rename = 1;
1046 free(patch->old_name);
1047 patch->old_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1048 return 0;
1051 static int gitdiff_renamedst(struct gitdiff_data *state,
1052 const char *line,
1053 struct patch *patch)
1055 patch->is_rename = 1;
1056 free(patch->new_name);
1057 patch->new_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1058 return 0;
1061 static int gitdiff_similarity(struct gitdiff_data *state UNUSED,
1062 const char *line,
1063 struct patch *patch)
1065 unsigned long val = strtoul(line, NULL, 10);
1066 if (val <= 100)
1067 patch->score = val;
1068 return 0;
1071 static int gitdiff_dissimilarity(struct gitdiff_data *state UNUSED,
1072 const char *line,
1073 struct patch *patch)
1075 unsigned long val = strtoul(line, NULL, 10);
1076 if (val <= 100)
1077 patch->score = val;
1078 return 0;
1081 static int gitdiff_index(struct gitdiff_data *state,
1082 const char *line,
1083 struct patch *patch)
1086 * index line is N hexadecimal, "..", N hexadecimal,
1087 * and optional space with octal mode.
1089 const char *ptr, *eol;
1090 int len;
1091 const unsigned hexsz = the_hash_algo->hexsz;
1093 ptr = strchr(line, '.');
1094 if (!ptr || ptr[1] != '.' || hexsz < ptr - line)
1095 return 0;
1096 len = ptr - line;
1097 memcpy(patch->old_oid_prefix, line, len);
1098 patch->old_oid_prefix[len] = 0;
1100 line = ptr + 2;
1101 ptr = strchr(line, ' ');
1102 eol = strchrnul(line, '\n');
1104 if (!ptr || eol < ptr)
1105 ptr = eol;
1106 len = ptr - line;
1108 if (hexsz < len)
1109 return 0;
1110 memcpy(patch->new_oid_prefix, line, len);
1111 patch->new_oid_prefix[len] = 0;
1112 if (*ptr == ' ')
1113 return gitdiff_oldmode(state, ptr + 1, patch);
1114 return 0;
1118 * This is normal for a diff that doesn't change anything: we'll fall through
1119 * into the next diff. Tell the parser to break out.
1121 static int gitdiff_unrecognized(struct gitdiff_data *state UNUSED,
1122 const char *line UNUSED,
1123 struct patch *patch UNUSED)
1125 return 1;
1129 * Skip p_value leading components from "line"; as we do not accept
1130 * absolute paths, return NULL in that case.
1132 static const char *skip_tree_prefix(int p_value,
1133 const char *line,
1134 int llen)
1136 int nslash;
1137 int i;
1139 if (!p_value)
1140 return (llen && line[0] == '/') ? NULL : line;
1142 nslash = p_value;
1143 for (i = 0; i < llen; i++) {
1144 int ch = line[i];
1145 if (ch == '/' && --nslash <= 0)
1146 return (i == 0) ? NULL : &line[i + 1];
1148 return NULL;
1152 * This is to extract the same name that appears on "diff --git"
1153 * line. We do not find and return anything if it is a rename
1154 * patch, and it is OK because we will find the name elsewhere.
1155 * We need to reliably find name only when it is mode-change only,
1156 * creation or deletion of an empty file. In any of these cases,
1157 * both sides are the same name under a/ and b/ respectively.
1159 static char *git_header_name(int p_value,
1160 const char *line,
1161 int llen)
1163 const char *name;
1164 const char *second = NULL;
1165 size_t len, line_len;
1167 line += strlen("diff --git ");
1168 llen -= strlen("diff --git ");
1170 if (*line == '"') {
1171 const char *cp;
1172 struct strbuf first = STRBUF_INIT;
1173 struct strbuf sp = STRBUF_INIT;
1175 if (unquote_c_style(&first, line, &second))
1176 goto free_and_fail1;
1178 /* strip the a/b prefix including trailing slash */
1179 cp = skip_tree_prefix(p_value, first.buf, first.len);
1180 if (!cp)
1181 goto free_and_fail1;
1182 strbuf_remove(&first, 0, cp - first.buf);
1185 * second points at one past closing dq of name.
1186 * find the second name.
1188 while ((second < line + llen) && isspace(*second))
1189 second++;
1191 if (line + llen <= second)
1192 goto free_and_fail1;
1193 if (*second == '"') {
1194 if (unquote_c_style(&sp, second, NULL))
1195 goto free_and_fail1;
1196 cp = skip_tree_prefix(p_value, sp.buf, sp.len);
1197 if (!cp)
1198 goto free_and_fail1;
1199 /* They must match, otherwise ignore */
1200 if (strcmp(cp, first.buf))
1201 goto free_and_fail1;
1202 strbuf_release(&sp);
1203 return strbuf_detach(&first, NULL);
1206 /* unquoted second */
1207 cp = skip_tree_prefix(p_value, second, line + llen - second);
1208 if (!cp)
1209 goto free_and_fail1;
1210 if (line + llen - cp != first.len ||
1211 memcmp(first.buf, cp, first.len))
1212 goto free_and_fail1;
1213 return strbuf_detach(&first, NULL);
1215 free_and_fail1:
1216 strbuf_release(&first);
1217 strbuf_release(&sp);
1218 return NULL;
1221 /* unquoted first name */
1222 name = skip_tree_prefix(p_value, line, llen);
1223 if (!name)
1224 return NULL;
1227 * since the first name is unquoted, a dq if exists must be
1228 * the beginning of the second name.
1230 for (second = name; second < line + llen; second++) {
1231 if (*second == '"') {
1232 struct strbuf sp = STRBUF_INIT;
1233 const char *np;
1235 if (unquote_c_style(&sp, second, NULL))
1236 goto free_and_fail2;
1238 np = skip_tree_prefix(p_value, sp.buf, sp.len);
1239 if (!np)
1240 goto free_and_fail2;
1242 len = sp.buf + sp.len - np;
1243 if (len < second - name &&
1244 !strncmp(np, name, len) &&
1245 isspace(name[len])) {
1246 /* Good */
1247 strbuf_remove(&sp, 0, np - sp.buf);
1248 return strbuf_detach(&sp, NULL);
1251 free_and_fail2:
1252 strbuf_release(&sp);
1253 return NULL;
1258 * Accept a name only if it shows up twice, exactly the same
1259 * form.
1261 second = strchr(name, '\n');
1262 if (!second)
1263 return NULL;
1264 line_len = second - name;
1265 for (len = 0 ; ; len++) {
1266 switch (name[len]) {
1267 default:
1268 continue;
1269 case '\n':
1270 return NULL;
1271 case '\t': case ' ':
1273 * Is this the separator between the preimage
1274 * and the postimage pathname? Again, we are
1275 * only interested in the case where there is
1276 * no rename, as this is only to set def_name
1277 * and a rename patch has the names elsewhere
1278 * in an unambiguous form.
1280 if (!name[len + 1])
1281 return NULL; /* no postimage name */
1282 second = skip_tree_prefix(p_value, name + len + 1,
1283 line_len - (len + 1));
1285 * If we are at the SP at the end of a directory,
1286 * skip_tree_prefix() may return NULL as that makes
1287 * it appears as if we have an absolute path.
1288 * Keep going to find another SP.
1290 if (!second)
1291 continue;
1294 * Does len bytes starting at "name" and "second"
1295 * (that are separated by one HT or SP we just
1296 * found) exactly match?
1298 if (second[len] == '\n' && !strncmp(name, second, len))
1299 return xmemdupz(name, len);
1304 static int check_header_line(int linenr, struct patch *patch)
1306 int extensions = (patch->is_delete == 1) + (patch->is_new == 1) +
1307 (patch->is_rename == 1) + (patch->is_copy == 1);
1308 if (extensions > 1)
1309 return error(_("inconsistent header lines %d and %d"),
1310 patch->extension_linenr, linenr);
1311 if (extensions && !patch->extension_linenr)
1312 patch->extension_linenr = linenr;
1313 return 0;
1316 int parse_git_diff_header(struct strbuf *root,
1317 int *linenr,
1318 int p_value,
1319 const char *line,
1320 int len,
1321 unsigned int size,
1322 struct patch *patch)
1324 unsigned long offset;
1325 struct gitdiff_data parse_hdr_state;
1327 /* A git diff has explicit new/delete information, so we don't guess */
1328 patch->is_new = 0;
1329 patch->is_delete = 0;
1332 * Some things may not have the old name in the
1333 * rest of the headers anywhere (pure mode changes,
1334 * or removing or adding empty files), so we get
1335 * the default name from the header.
1337 patch->def_name = git_header_name(p_value, line, len);
1338 if (patch->def_name && root->len) {
1339 char *s = xstrfmt("%s%s", root->buf, patch->def_name);
1340 free(patch->def_name);
1341 patch->def_name = s;
1344 line += len;
1345 size -= len;
1346 (*linenr)++;
1347 parse_hdr_state.root = root;
1348 parse_hdr_state.linenr = *linenr;
1349 parse_hdr_state.p_value = p_value;
1351 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, (*linenr)++) {
1352 static const struct opentry {
1353 const char *str;
1354 int (*fn)(struct gitdiff_data *, const char *, struct patch *);
1355 } optable[] = {
1356 { "@@ -", gitdiff_hdrend },
1357 { "--- ", gitdiff_oldname },
1358 { "+++ ", gitdiff_newname },
1359 { "old mode ", gitdiff_oldmode },
1360 { "new mode ", gitdiff_newmode },
1361 { "deleted file mode ", gitdiff_delete },
1362 { "new file mode ", gitdiff_newfile },
1363 { "copy from ", gitdiff_copysrc },
1364 { "copy to ", gitdiff_copydst },
1365 { "rename old ", gitdiff_renamesrc },
1366 { "rename new ", gitdiff_renamedst },
1367 { "rename from ", gitdiff_renamesrc },
1368 { "rename to ", gitdiff_renamedst },
1369 { "similarity index ", gitdiff_similarity },
1370 { "dissimilarity index ", gitdiff_dissimilarity },
1371 { "index ", gitdiff_index },
1372 { "", gitdiff_unrecognized },
1374 int i;
1376 len = linelen(line, size);
1377 if (!len || line[len-1] != '\n')
1378 break;
1379 for (i = 0; i < ARRAY_SIZE(optable); i++) {
1380 const struct opentry *p = optable + i;
1381 int oplen = strlen(p->str);
1382 int res;
1383 if (len < oplen || memcmp(p->str, line, oplen))
1384 continue;
1385 res = p->fn(&parse_hdr_state, line + oplen, patch);
1386 if (res < 0)
1387 return -1;
1388 if (check_header_line(*linenr, patch))
1389 return -1;
1390 if (res > 0)
1391 goto done;
1392 break;
1396 done:
1397 if (!patch->old_name && !patch->new_name) {
1398 if (!patch->def_name) {
1399 error(Q_("git diff header lacks filename information when removing "
1400 "%d leading pathname component (line %d)",
1401 "git diff header lacks filename information when removing "
1402 "%d leading pathname components (line %d)",
1403 parse_hdr_state.p_value),
1404 parse_hdr_state.p_value, *linenr);
1405 return -128;
1407 patch->old_name = xstrdup(patch->def_name);
1408 patch->new_name = xstrdup(patch->def_name);
1410 if ((!patch->new_name && !patch->is_delete) ||
1411 (!patch->old_name && !patch->is_new)) {
1412 error(_("git diff header lacks filename information "
1413 "(line %d)"), *linenr);
1414 return -128;
1416 patch->is_toplevel_relative = 1;
1417 return offset;
1420 static int parse_num(const char *line, unsigned long *p)
1422 char *ptr;
1424 if (!isdigit(*line))
1425 return 0;
1426 *p = strtoul(line, &ptr, 10);
1427 return ptr - line;
1430 static int parse_range(const char *line, int len, int offset, const char *expect,
1431 unsigned long *p1, unsigned long *p2)
1433 int digits, ex;
1435 if (offset < 0 || offset >= len)
1436 return -1;
1437 line += offset;
1438 len -= offset;
1440 digits = parse_num(line, p1);
1441 if (!digits)
1442 return -1;
1444 offset += digits;
1445 line += digits;
1446 len -= digits;
1448 *p2 = 1;
1449 if (*line == ',') {
1450 digits = parse_num(line+1, p2);
1451 if (!digits)
1452 return -1;
1454 offset += digits+1;
1455 line += digits+1;
1456 len -= digits+1;
1459 ex = strlen(expect);
1460 if (ex > len)
1461 return -1;
1462 if (memcmp(line, expect, ex))
1463 return -1;
1465 return offset + ex;
1468 static void recount_diff(const char *line, int size, struct fragment *fragment)
1470 int oldlines = 0, newlines = 0, ret = 0;
1472 if (size < 1) {
1473 warning("recount: ignore empty hunk");
1474 return;
1477 for (;;) {
1478 int len = linelen(line, size);
1479 size -= len;
1480 line += len;
1482 if (size < 1)
1483 break;
1485 switch (*line) {
1486 case ' ': case '\n':
1487 newlines++;
1488 /* fall through */
1489 case '-':
1490 oldlines++;
1491 continue;
1492 case '+':
1493 newlines++;
1494 continue;
1495 case '\\':
1496 continue;
1497 case '@':
1498 ret = size < 3 || !starts_with(line, "@@ ");
1499 break;
1500 case 'd':
1501 ret = size < 5 || !starts_with(line, "diff ");
1502 break;
1503 default:
1504 ret = -1;
1505 break;
1507 if (ret) {
1508 warning(_("recount: unexpected line: %.*s"),
1509 (int)linelen(line, size), line);
1510 return;
1512 break;
1514 fragment->oldlines = oldlines;
1515 fragment->newlines = newlines;
1519 * Parse a unified diff fragment header of the
1520 * form "@@ -a,b +c,d @@"
1522 static int parse_fragment_header(const char *line, int len, struct fragment *fragment)
1524 int offset;
1526 if (!len || line[len-1] != '\n')
1527 return -1;
1529 /* Figure out the number of lines in a fragment */
1530 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1531 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1533 return offset;
1537 * Find file diff header
1539 * Returns:
1540 * -1 if no header was found
1541 * -128 in case of error
1542 * the size of the header in bytes (called "offset") otherwise
1544 static int find_header(struct apply_state *state,
1545 const char *line,
1546 unsigned long size,
1547 int *hdrsize,
1548 struct patch *patch)
1550 unsigned long offset, len;
1552 patch->is_toplevel_relative = 0;
1553 patch->is_rename = patch->is_copy = 0;
1554 patch->is_new = patch->is_delete = -1;
1555 patch->old_mode = patch->new_mode = 0;
1556 patch->old_name = patch->new_name = NULL;
1557 for (offset = 0; size > 0; offset += len, size -= len, line += len, state->linenr++) {
1558 unsigned long nextlen;
1560 len = linelen(line, size);
1561 if (!len)
1562 break;
1564 /* Testing this early allows us to take a few shortcuts.. */
1565 if (len < 6)
1566 continue;
1569 * Make sure we don't find any unconnected patch fragments.
1570 * That's a sign that we didn't find a header, and that a
1571 * patch has become corrupted/broken up.
1573 if (!memcmp("@@ -", line, 4)) {
1574 struct fragment dummy;
1575 if (parse_fragment_header(line, len, &dummy) < 0)
1576 continue;
1577 error(_("patch fragment without header at line %d: %.*s"),
1578 state->linenr, (int)len-1, line);
1579 return -128;
1582 if (size < len + 6)
1583 break;
1586 * Git patch? It might not have a real patch, just a rename
1587 * or mode change, so we handle that specially
1589 if (!memcmp("diff --git ", line, 11)) {
1590 int git_hdr_len = parse_git_diff_header(&state->root, &state->linenr,
1591 state->p_value, line, len,
1592 size, patch);
1593 if (git_hdr_len < 0)
1594 return -128;
1595 if (git_hdr_len <= len)
1596 continue;
1597 *hdrsize = git_hdr_len;
1598 return offset;
1601 /* --- followed by +++ ? */
1602 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1603 continue;
1606 * We only accept unified patches, so we want it to
1607 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1608 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1610 nextlen = linelen(line + len, size - len);
1611 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1612 continue;
1614 /* Ok, we'll consider it a patch */
1615 if (parse_traditional_patch(state, line, line+len, patch))
1616 return -128;
1617 *hdrsize = len + nextlen;
1618 state->linenr += 2;
1619 return offset;
1621 return -1;
1624 static void record_ws_error(struct apply_state *state,
1625 unsigned result,
1626 const char *line,
1627 int len,
1628 int linenr)
1630 char *err;
1632 if (!result)
1633 return;
1635 state->whitespace_error++;
1636 if (state->squelch_whitespace_errors &&
1637 state->squelch_whitespace_errors < state->whitespace_error)
1638 return;
1640 err = whitespace_error_string(result);
1641 if (state->apply_verbosity > verbosity_silent)
1642 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1643 state->patch_input_file, linenr, err, len, line);
1644 free(err);
1647 static void check_whitespace(struct apply_state *state,
1648 const char *line,
1649 int len,
1650 unsigned ws_rule)
1652 unsigned result = ws_check(line + 1, len - 1, ws_rule);
1654 record_ws_error(state, result, line + 1, len - 2, state->linenr);
1658 * Check if the patch has context lines with CRLF or
1659 * the patch wants to remove lines with CRLF.
1661 static void check_old_for_crlf(struct patch *patch, const char *line, int len)
1663 if (len >= 2 && line[len-1] == '\n' && line[len-2] == '\r') {
1664 patch->ws_rule |= WS_CR_AT_EOL;
1665 patch->crlf_in_old = 1;
1671 * Parse a unified diff. Note that this really needs to parse each
1672 * fragment separately, since the only way to know the difference
1673 * between a "---" that is part of a patch, and a "---" that starts
1674 * the next patch is to look at the line counts..
1676 static int parse_fragment(struct apply_state *state,
1677 const char *line,
1678 unsigned long size,
1679 struct patch *patch,
1680 struct fragment *fragment)
1682 int added, deleted;
1683 int len = linelen(line, size), offset;
1684 unsigned long oldlines, newlines;
1685 unsigned long leading, trailing;
1687 offset = parse_fragment_header(line, len, fragment);
1688 if (offset < 0)
1689 return -1;
1690 if (offset > 0 && patch->recount)
1691 recount_diff(line + offset, size - offset, fragment);
1692 oldlines = fragment->oldlines;
1693 newlines = fragment->newlines;
1694 leading = 0;
1695 trailing = 0;
1697 /* Parse the thing.. */
1698 line += len;
1699 size -= len;
1700 state->linenr++;
1701 added = deleted = 0;
1702 for (offset = len;
1703 0 < size;
1704 offset += len, size -= len, line += len, state->linenr++) {
1705 if (!oldlines && !newlines)
1706 break;
1707 len = linelen(line, size);
1708 if (!len || line[len-1] != '\n')
1709 return -1;
1710 switch (*line) {
1711 default:
1712 return -1;
1713 case '\n': /* newer GNU diff, an empty context line */
1714 case ' ':
1715 oldlines--;
1716 newlines--;
1717 if (!deleted && !added)
1718 leading++;
1719 trailing++;
1720 check_old_for_crlf(patch, line, len);
1721 if (!state->apply_in_reverse &&
1722 state->ws_error_action == correct_ws_error)
1723 check_whitespace(state, line, len, patch->ws_rule);
1724 break;
1725 case '-':
1726 if (!state->apply_in_reverse)
1727 check_old_for_crlf(patch, line, len);
1728 if (state->apply_in_reverse &&
1729 state->ws_error_action != nowarn_ws_error)
1730 check_whitespace(state, line, len, patch->ws_rule);
1731 deleted++;
1732 oldlines--;
1733 trailing = 0;
1734 break;
1735 case '+':
1736 if (state->apply_in_reverse)
1737 check_old_for_crlf(patch, line, len);
1738 if (!state->apply_in_reverse &&
1739 state->ws_error_action != nowarn_ws_error)
1740 check_whitespace(state, line, len, patch->ws_rule);
1741 added++;
1742 newlines--;
1743 trailing = 0;
1744 break;
1747 * We allow "\ No newline at end of file". Depending
1748 * on locale settings when the patch was produced we
1749 * don't know what this line looks like. The only
1750 * thing we do know is that it begins with "\ ".
1751 * Checking for 12 is just for sanity check -- any
1752 * l10n of "\ No newline..." is at least that long.
1754 case '\\':
1755 if (len < 12 || memcmp(line, "\\ ", 2))
1756 return -1;
1757 break;
1760 if (oldlines || newlines)
1761 return -1;
1762 if (!patch->recount && !deleted && !added)
1763 return -1;
1765 fragment->leading = leading;
1766 fragment->trailing = trailing;
1769 * If a fragment ends with an incomplete line, we failed to include
1770 * it in the above loop because we hit oldlines == newlines == 0
1771 * before seeing it.
1773 if (12 < size && !memcmp(line, "\\ ", 2))
1774 offset += linelen(line, size);
1776 patch->lines_added += added;
1777 patch->lines_deleted += deleted;
1779 if (0 < patch->is_new && oldlines)
1780 return error(_("new file depends on old contents"));
1781 if (0 < patch->is_delete && newlines)
1782 return error(_("deleted file still has contents"));
1783 return offset;
1787 * We have seen "diff --git a/... b/..." header (or a traditional patch
1788 * header). Read hunks that belong to this patch into fragments and hang
1789 * them to the given patch structure.
1791 * The (fragment->patch, fragment->size) pair points into the memory given
1792 * by the caller, not a copy, when we return.
1794 * Returns:
1795 * -1 in case of error,
1796 * the number of bytes in the patch otherwise.
1798 static int parse_single_patch(struct apply_state *state,
1799 const char *line,
1800 unsigned long size,
1801 struct patch *patch)
1803 unsigned long offset = 0;
1804 unsigned long oldlines = 0, newlines = 0, context = 0;
1805 struct fragment **fragp = &patch->fragments;
1807 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1808 struct fragment *fragment;
1809 int len;
1811 CALLOC_ARRAY(fragment, 1);
1812 fragment->linenr = state->linenr;
1813 len = parse_fragment(state, line, size, patch, fragment);
1814 if (len <= 0) {
1815 free(fragment);
1816 return error(_("corrupt patch at line %d"), state->linenr);
1818 fragment->patch = line;
1819 fragment->size = len;
1820 oldlines += fragment->oldlines;
1821 newlines += fragment->newlines;
1822 context += fragment->leading + fragment->trailing;
1824 *fragp = fragment;
1825 fragp = &fragment->next;
1827 offset += len;
1828 line += len;
1829 size -= len;
1833 * If something was removed (i.e. we have old-lines) it cannot
1834 * be creation, and if something was added it cannot be
1835 * deletion. However, the reverse is not true; --unified=0
1836 * patches that only add are not necessarily creation even
1837 * though they do not have any old lines, and ones that only
1838 * delete are not necessarily deletion.
1840 * Unfortunately, a real creation/deletion patch do _not_ have
1841 * any context line by definition, so we cannot safely tell it
1842 * apart with --unified=0 insanity. At least if the patch has
1843 * more than one hunk it is not creation or deletion.
1845 if (patch->is_new < 0 &&
1846 (oldlines || (patch->fragments && patch->fragments->next)))
1847 patch->is_new = 0;
1848 if (patch->is_delete < 0 &&
1849 (newlines || (patch->fragments && patch->fragments->next)))
1850 patch->is_delete = 0;
1852 if (0 < patch->is_new && oldlines)
1853 return error(_("new file %s depends on old contents"), patch->new_name);
1854 if (0 < patch->is_delete && newlines)
1855 return error(_("deleted file %s still has contents"), patch->old_name);
1856 if (!patch->is_delete && !newlines && context && state->apply_verbosity > verbosity_silent)
1857 fprintf_ln(stderr,
1858 _("** warning: "
1859 "file %s becomes empty but is not deleted"),
1860 patch->new_name);
1862 return offset;
1865 static inline int metadata_changes(struct patch *patch)
1867 return patch->is_rename > 0 ||
1868 patch->is_copy > 0 ||
1869 patch->is_new > 0 ||
1870 patch->is_delete ||
1871 (patch->old_mode && patch->new_mode &&
1872 patch->old_mode != patch->new_mode);
1875 static char *inflate_it(const void *data, unsigned long size,
1876 unsigned long inflated_size)
1878 git_zstream stream;
1879 void *out;
1880 int st;
1882 memset(&stream, 0, sizeof(stream));
1884 stream.next_in = (unsigned char *)data;
1885 stream.avail_in = size;
1886 stream.next_out = out = xmalloc(inflated_size);
1887 stream.avail_out = inflated_size;
1888 git_inflate_init(&stream);
1889 st = git_inflate(&stream, Z_FINISH);
1890 git_inflate_end(&stream);
1891 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1892 free(out);
1893 return NULL;
1895 return out;
1899 * Read a binary hunk and return a new fragment; fragment->patch
1900 * points at an allocated memory that the caller must free, so
1901 * it is marked as "->free_patch = 1".
1903 static struct fragment *parse_binary_hunk(struct apply_state *state,
1904 char **buf_p,
1905 unsigned long *sz_p,
1906 int *status_p,
1907 int *used_p)
1910 * Expect a line that begins with binary patch method ("literal"
1911 * or "delta"), followed by the length of data before deflating.
1912 * a sequence of 'length-byte' followed by base-85 encoded data
1913 * should follow, terminated by a newline.
1915 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1916 * and we would limit the patch line to 66 characters,
1917 * so one line can fit up to 13 groups that would decode
1918 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1919 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1921 int llen, used;
1922 unsigned long size = *sz_p;
1923 char *buffer = *buf_p;
1924 int patch_method;
1925 unsigned long origlen;
1926 char *data = NULL;
1927 int hunk_size = 0;
1928 struct fragment *frag;
1930 llen = linelen(buffer, size);
1931 used = llen;
1933 *status_p = 0;
1935 if (starts_with(buffer, "delta ")) {
1936 patch_method = BINARY_DELTA_DEFLATED;
1937 origlen = strtoul(buffer + 6, NULL, 10);
1939 else if (starts_with(buffer, "literal ")) {
1940 patch_method = BINARY_LITERAL_DEFLATED;
1941 origlen = strtoul(buffer + 8, NULL, 10);
1943 else
1944 return NULL;
1946 state->linenr++;
1947 buffer += llen;
1948 size -= llen;
1949 while (1) {
1950 int byte_length, max_byte_length, newsize;
1951 llen = linelen(buffer, size);
1952 used += llen;
1953 state->linenr++;
1954 if (llen == 1) {
1955 /* consume the blank line */
1956 buffer++;
1957 size--;
1958 break;
1961 * Minimum line is "A00000\n" which is 7-byte long,
1962 * and the line length must be multiple of 5 plus 2.
1964 if ((llen < 7) || (llen-2) % 5)
1965 goto corrupt;
1966 max_byte_length = (llen - 2) / 5 * 4;
1967 byte_length = *buffer;
1968 if ('A' <= byte_length && byte_length <= 'Z')
1969 byte_length = byte_length - 'A' + 1;
1970 else if ('a' <= byte_length && byte_length <= 'z')
1971 byte_length = byte_length - 'a' + 27;
1972 else
1973 goto corrupt;
1974 /* if the input length was not multiple of 4, we would
1975 * have filler at the end but the filler should never
1976 * exceed 3 bytes
1978 if (max_byte_length < byte_length ||
1979 byte_length <= max_byte_length - 4)
1980 goto corrupt;
1981 newsize = hunk_size + byte_length;
1982 data = xrealloc(data, newsize);
1983 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1984 goto corrupt;
1985 hunk_size = newsize;
1986 buffer += llen;
1987 size -= llen;
1990 CALLOC_ARRAY(frag, 1);
1991 frag->patch = inflate_it(data, hunk_size, origlen);
1992 frag->free_patch = 1;
1993 if (!frag->patch)
1994 goto corrupt;
1995 free(data);
1996 frag->size = origlen;
1997 *buf_p = buffer;
1998 *sz_p = size;
1999 *used_p = used;
2000 frag->binary_patch_method = patch_method;
2001 return frag;
2003 corrupt:
2004 free(data);
2005 *status_p = -1;
2006 error(_("corrupt binary patch at line %d: %.*s"),
2007 state->linenr-1, llen-1, buffer);
2008 return NULL;
2012 * Returns:
2013 * -1 in case of error,
2014 * the length of the parsed binary patch otherwise
2016 static int parse_binary(struct apply_state *state,
2017 char *buffer,
2018 unsigned long size,
2019 struct patch *patch)
2022 * We have read "GIT binary patch\n"; what follows is a line
2023 * that says the patch method (currently, either "literal" or
2024 * "delta") and the length of data before deflating; a
2025 * sequence of 'length-byte' followed by base-85 encoded data
2026 * follows.
2028 * When a binary patch is reversible, there is another binary
2029 * hunk in the same format, starting with patch method (either
2030 * "literal" or "delta") with the length of data, and a sequence
2031 * of length-byte + base-85 encoded data, terminated with another
2032 * empty line. This data, when applied to the postimage, produces
2033 * the preimage.
2035 struct fragment *forward;
2036 struct fragment *reverse;
2037 int status;
2038 int used, used_1;
2040 forward = parse_binary_hunk(state, &buffer, &size, &status, &used);
2041 if (!forward && !status)
2042 /* there has to be one hunk (forward hunk) */
2043 return error(_("unrecognized binary patch at line %d"), state->linenr-1);
2044 if (status)
2045 /* otherwise we already gave an error message */
2046 return status;
2048 reverse = parse_binary_hunk(state, &buffer, &size, &status, &used_1);
2049 if (reverse)
2050 used += used_1;
2051 else if (status) {
2053 * Not having reverse hunk is not an error, but having
2054 * a corrupt reverse hunk is.
2056 free((void*) forward->patch);
2057 free(forward);
2058 return status;
2060 forward->next = reverse;
2061 patch->fragments = forward;
2062 patch->is_binary = 1;
2063 return used;
2066 static void prefix_one(struct apply_state *state, char **name)
2068 char *old_name = *name;
2069 if (!old_name)
2070 return;
2071 *name = prefix_filename(state->prefix, *name);
2072 free(old_name);
2075 static void prefix_patch(struct apply_state *state, struct patch *p)
2077 if (!state->prefix || p->is_toplevel_relative)
2078 return;
2079 prefix_one(state, &p->new_name);
2080 prefix_one(state, &p->old_name);
2084 * include/exclude
2087 static void add_name_limit(struct apply_state *state,
2088 const char *name,
2089 int exclude)
2091 struct string_list_item *it;
2093 it = string_list_append(&state->limit_by_name, name);
2094 it->util = exclude ? NULL : (void *) 1;
2097 static int use_patch(struct apply_state *state, struct patch *p)
2099 const char *pathname = p->new_name ? p->new_name : p->old_name;
2100 int i;
2102 /* Paths outside are not touched regardless of "--include" */
2103 if (state->prefix && *state->prefix) {
2104 const char *rest;
2105 if (!skip_prefix(pathname, state->prefix, &rest) || !*rest)
2106 return 0;
2109 /* See if it matches any of exclude/include rule */
2110 for (i = 0; i < state->limit_by_name.nr; i++) {
2111 struct string_list_item *it = &state->limit_by_name.items[i];
2112 if (!wildmatch(it->string, pathname, 0))
2113 return (it->util != NULL);
2117 * If we had any include, a path that does not match any rule is
2118 * not used. Otherwise, we saw bunch of exclude rules (or none)
2119 * and such a path is used.
2121 return !state->has_include;
2125 * Read the patch text in "buffer" that extends for "size" bytes; stop
2126 * reading after seeing a single patch (i.e. changes to a single file).
2127 * Create fragments (i.e. patch hunks) and hang them to the given patch.
2129 * Returns:
2130 * -1 if no header was found or parse_binary() failed,
2131 * -128 on another error,
2132 * the number of bytes consumed otherwise,
2133 * so that the caller can call us again for the next patch.
2135 static int parse_chunk(struct apply_state *state, char *buffer, unsigned long size, struct patch *patch)
2137 int hdrsize, patchsize;
2138 int offset = find_header(state, buffer, size, &hdrsize, patch);
2140 if (offset < 0)
2141 return offset;
2143 prefix_patch(state, patch);
2145 if (!use_patch(state, patch))
2146 patch->ws_rule = 0;
2147 else if (patch->new_name)
2148 patch->ws_rule = whitespace_rule(state->repo->index,
2149 patch->new_name);
2150 else
2151 patch->ws_rule = whitespace_rule(state->repo->index,
2152 patch->old_name);
2154 patchsize = parse_single_patch(state,
2155 buffer + offset + hdrsize,
2156 size - offset - hdrsize,
2157 patch);
2159 if (patchsize < 0)
2160 return -128;
2162 if (!patchsize) {
2163 static const char git_binary[] = "GIT binary patch\n";
2164 int hd = hdrsize + offset;
2165 unsigned long llen = linelen(buffer + hd, size - hd);
2167 if (llen == sizeof(git_binary) - 1 &&
2168 !memcmp(git_binary, buffer + hd, llen)) {
2169 int used;
2170 state->linenr++;
2171 used = parse_binary(state, buffer + hd + llen,
2172 size - hd - llen, patch);
2173 if (used < 0)
2174 return -1;
2175 if (used)
2176 patchsize = used + llen;
2177 else
2178 patchsize = 0;
2180 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
2181 static const char *binhdr[] = {
2182 "Binary files ",
2183 "Files ",
2184 NULL,
2186 int i;
2187 for (i = 0; binhdr[i]; i++) {
2188 int len = strlen(binhdr[i]);
2189 if (len < size - hd &&
2190 !memcmp(binhdr[i], buffer + hd, len)) {
2191 state->linenr++;
2192 patch->is_binary = 1;
2193 patchsize = llen;
2194 break;
2199 /* Empty patch cannot be applied if it is a text patch
2200 * without metadata change. A binary patch appears
2201 * empty to us here.
2203 if ((state->apply || state->check) &&
2204 (!patch->is_binary && !metadata_changes(patch))) {
2205 error(_("patch with only garbage at line %d"), state->linenr);
2206 return -128;
2210 return offset + hdrsize + patchsize;
2213 static void reverse_patches(struct patch *p)
2215 for (; p; p = p->next) {
2216 struct fragment *frag = p->fragments;
2218 SWAP(p->new_name, p->old_name);
2219 if (p->new_mode)
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.
2316 static void update_pre_post_images(struct image *preimage,
2317 struct image *postimage,
2318 char *buf, size_t len)
2320 struct image fixed_preimage = IMAGE_INIT;
2321 size_t insert_pos = 0;
2322 int i, ctx, reduced;
2323 const char *fixed;
2326 * Update the preimage with whitespace fixes. Note that we
2327 * are not losing preimage->buf -- apply_one_fragment() will
2328 * free "oldlines".
2330 image_prepare(&fixed_preimage, buf, len, 1);
2331 for (i = 0; i < fixed_preimage.line_nr; i++)
2332 fixed_preimage.line[i].flag = preimage->line[i].flag;
2333 image_clear(preimage);
2334 *preimage = fixed_preimage;
2335 fixed = preimage->buf.buf;
2338 * Adjust the common context lines in postimage.
2340 for (i = reduced = ctx = 0; i < postimage->line_nr; i++) {
2341 size_t l_len = postimage->line[i].len;
2343 if (!(postimage->line[i].flag & LINE_COMMON)) {
2344 /* an added line -- no counterparts in preimage */
2345 insert_pos += l_len;
2346 continue;
2349 /* and find the corresponding one in the fixed preimage */
2350 while (ctx < preimage->line_nr &&
2351 !(preimage->line[ctx].flag & LINE_COMMON)) {
2352 fixed += preimage->line[ctx].len;
2353 ctx++;
2357 * preimage is expected to run out, if the caller
2358 * fixed addition of trailing blank lines.
2360 if (preimage->line_nr <= ctx) {
2361 reduced++;
2362 continue;
2365 /* and copy it in, while fixing the line length */
2366 l_len = preimage->line[ctx].len;
2367 strbuf_splice(&postimage->buf, insert_pos, postimage->line[i].len,
2368 fixed, l_len);
2369 insert_pos += l_len;
2370 fixed += l_len;
2371 postimage->line[i].len = l_len;
2372 ctx++;
2375 /* Fix the length of the whole thing */
2376 postimage->line_nr -= reduced;
2380 * Compare lines s1 of length n1 and s2 of length n2, ignoring
2381 * whitespace difference. Returns 1 if they match, 0 otherwise
2383 static int fuzzy_matchlines(const char *s1, size_t n1,
2384 const char *s2, size_t n2)
2386 const char *end1 = s1 + n1;
2387 const char *end2 = s2 + n2;
2389 /* ignore line endings */
2390 while (s1 < end1 && (end1[-1] == '\r' || end1[-1] == '\n'))
2391 end1--;
2392 while (s2 < end2 && (end2[-1] == '\r' || end2[-1] == '\n'))
2393 end2--;
2395 while (s1 < end1 && s2 < end2) {
2396 if (isspace(*s1)) {
2398 * Skip whitespace. We check on both buffers
2399 * because we don't want "a b" to match "ab".
2401 if (!isspace(*s2))
2402 return 0;
2403 while (s1 < end1 && isspace(*s1))
2404 s1++;
2405 while (s2 < end2 && isspace(*s2))
2406 s2++;
2407 } else if (*s1++ != *s2++)
2408 return 0;
2411 /* If we reached the end on one side only, lines don't match. */
2412 return s1 == end1 && s2 == end2;
2415 static int line_by_line_fuzzy_match(struct image *img,
2416 struct image *preimage,
2417 struct image *postimage,
2418 unsigned long current,
2419 int current_lno,
2420 int preimage_limit)
2422 int i;
2423 size_t imgoff = 0;
2424 size_t preoff = 0;
2425 size_t extra_chars;
2426 char *buf;
2427 char *preimage_eof;
2428 char *preimage_end;
2429 struct strbuf fixed;
2430 char *fixed_buf;
2431 size_t fixed_len;
2433 for (i = 0; i < preimage_limit; i++) {
2434 size_t prelen = preimage->line[i].len;
2435 size_t imglen = img->line[current_lno+i].len;
2437 if (!fuzzy_matchlines(img->buf.buf + current + imgoff, imglen,
2438 preimage->buf.buf + preoff, prelen))
2439 return 0;
2440 imgoff += imglen;
2441 preoff += prelen;
2445 * Ok, the preimage matches with whitespace fuzz.
2447 * imgoff now holds the true length of the target that
2448 * matches the preimage before the end of the file.
2450 * Count the number of characters in the preimage that fall
2451 * beyond the end of the file and make sure that all of them
2452 * are whitespace characters. (This can only happen if
2453 * we are removing blank lines at the end of the file.)
2455 buf = preimage_eof = preimage->buf.buf + preoff;
2456 for ( ; i < preimage->line_nr; i++)
2457 preoff += preimage->line[i].len;
2458 preimage_end = preimage->buf.buf + preoff;
2459 for ( ; buf < preimage_end; buf++)
2460 if (!isspace(*buf))
2461 return 0;
2464 * Update the preimage and the common postimage context
2465 * lines to use the same whitespace as the target.
2466 * If whitespace is missing in the target (i.e.
2467 * if the preimage extends beyond the end of the file),
2468 * use the whitespace from the preimage.
2470 extra_chars = preimage_end - preimage_eof;
2471 strbuf_init(&fixed, imgoff + extra_chars);
2472 strbuf_add(&fixed, img->buf.buf + current, imgoff);
2473 strbuf_add(&fixed, preimage_eof, extra_chars);
2474 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2475 update_pre_post_images(preimage, postimage,
2476 fixed_buf, fixed_len);
2477 return 1;
2480 static int match_fragment(struct apply_state *state,
2481 struct image *img,
2482 struct image *preimage,
2483 struct image *postimage,
2484 unsigned long current,
2485 int current_lno,
2486 unsigned ws_rule,
2487 int match_beginning, int match_end)
2489 int i;
2490 const char *orig, *target;
2491 struct strbuf fixed = STRBUF_INIT;
2492 char *fixed_buf;
2493 size_t fixed_len;
2494 int preimage_limit;
2495 int ret;
2497 if (preimage->line_nr + current_lno <= img->line_nr) {
2499 * The hunk falls within the boundaries of img.
2501 preimage_limit = preimage->line_nr;
2502 if (match_end && (preimage->line_nr + current_lno != img->line_nr)) {
2503 ret = 0;
2504 goto out;
2506 } else if (state->ws_error_action == correct_ws_error &&
2507 (ws_rule & WS_BLANK_AT_EOF)) {
2509 * This hunk extends beyond the end of img, and we are
2510 * removing blank lines at the end of the file. This
2511 * many lines from the beginning of the preimage must
2512 * match with img, and the remainder of the preimage
2513 * must be blank.
2515 preimage_limit = img->line_nr - current_lno;
2516 } else {
2518 * The hunk extends beyond the end of the img and
2519 * we are not removing blanks at the end, so we
2520 * should reject the hunk at this position.
2522 ret = 0;
2523 goto out;
2526 if (match_beginning && current_lno) {
2527 ret = 0;
2528 goto out;
2531 /* Quick hash check */
2532 for (i = 0; i < preimage_limit; i++) {
2533 if ((img->line[current_lno + i].flag & LINE_PATCHED) ||
2534 (preimage->line[i].hash != img->line[current_lno + i].hash)) {
2535 ret = 0;
2536 goto out;
2540 if (preimage_limit == preimage->line_nr) {
2542 * Do we have an exact match? If we were told to match
2543 * at the end, size must be exactly at current+fragsize,
2544 * otherwise current+fragsize must be still within the preimage,
2545 * and either case, the old piece should match the preimage
2546 * exactly.
2548 if ((match_end
2549 ? (current + preimage->buf.len == img->buf.len)
2550 : (current + preimage->buf.len <= img->buf.len)) &&
2551 !memcmp(img->buf.buf + current, preimage->buf.buf, preimage->buf.len)) {
2552 ret = 1;
2553 goto out;
2555 } else {
2557 * The preimage extends beyond the end of img, so
2558 * there cannot be an exact match.
2560 * There must be one non-blank context line that match
2561 * a line before the end of img.
2563 const char *buf, *buf_end;
2565 buf = preimage->buf.buf;
2566 buf_end = buf;
2567 for (i = 0; i < preimage_limit; i++)
2568 buf_end += preimage->line[i].len;
2570 for ( ; buf < buf_end; buf++)
2571 if (!isspace(*buf))
2572 break;
2573 if (buf == buf_end) {
2574 ret = 0;
2575 goto out;
2580 * No exact match. If we are ignoring whitespace, run a line-by-line
2581 * fuzzy matching. We collect all the line length information because
2582 * we need it to adjust whitespace if we match.
2584 if (state->ws_ignore_action == ignore_ws_change) {
2585 ret = line_by_line_fuzzy_match(img, preimage, postimage,
2586 current, current_lno, preimage_limit);
2587 goto out;
2590 if (state->ws_error_action != correct_ws_error) {
2591 ret = 0;
2592 goto out;
2596 * The hunk does not apply byte-by-byte, but the hash says
2597 * it might with whitespace fuzz. We weren't asked to
2598 * ignore whitespace, we were asked to correct whitespace
2599 * errors, so let's try matching after whitespace correction.
2601 * While checking the preimage against the target, whitespace
2602 * errors in both fixed, we count how large the corresponding
2603 * postimage needs to be. The postimage prepared by
2604 * apply_one_fragment() has whitespace errors fixed on added
2605 * lines already, but the common lines were propagated as-is,
2606 * which may become longer when their whitespace errors are
2607 * fixed.
2611 * The preimage may extend beyond the end of the file,
2612 * but in this loop we will only handle the part of the
2613 * preimage that falls within the file.
2615 strbuf_grow(&fixed, preimage->buf.len + 1);
2616 orig = preimage->buf.buf;
2617 target = img->buf.buf + current;
2618 for (i = 0; i < preimage_limit; i++) {
2619 size_t oldlen = preimage->line[i].len;
2620 size_t tgtlen = img->line[current_lno + i].len;
2621 size_t fixstart = fixed.len;
2622 struct strbuf tgtfix;
2623 int match;
2625 /* Try fixing the line in the preimage */
2626 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2628 /* Try fixing the line in the target */
2629 strbuf_init(&tgtfix, tgtlen);
2630 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2633 * If they match, either the preimage was based on
2634 * a version before our tree fixed whitespace breakage,
2635 * or we are lacking a whitespace-fix patch the tree
2636 * the preimage was based on already had (i.e. target
2637 * has whitespace breakage, the preimage doesn't).
2638 * In either case, we are fixing the whitespace breakages
2639 * so we might as well take the fix together with their
2640 * real change.
2642 match = (tgtfix.len == fixed.len - fixstart &&
2643 !memcmp(tgtfix.buf, fixed.buf + fixstart,
2644 fixed.len - fixstart));
2646 strbuf_release(&tgtfix);
2647 if (!match) {
2648 ret = 0;
2649 goto out;
2652 orig += oldlen;
2653 target += tgtlen;
2658 * Now handle the lines in the preimage that falls beyond the
2659 * end of the file (if any). They will only match if they are
2660 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2661 * false).
2663 for ( ; i < preimage->line_nr; i++) {
2664 size_t fixstart = fixed.len; /* start of the fixed preimage */
2665 size_t oldlen = preimage->line[i].len;
2666 int j;
2668 /* Try fixing the line in the preimage */
2669 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2671 for (j = fixstart; j < fixed.len; j++) {
2672 if (!isspace(fixed.buf[j])) {
2673 ret = 0;
2674 goto out;
2679 orig += oldlen;
2683 * Yes, the preimage is based on an older version that still
2684 * has whitespace breakages unfixed, and fixing them makes the
2685 * hunk match. Update the context lines in the postimage.
2687 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2688 update_pre_post_images(preimage, postimage,
2689 fixed_buf, fixed_len);
2691 ret = 1;
2693 out:
2694 strbuf_release(&fixed);
2695 return ret;
2698 static int find_pos(struct apply_state *state,
2699 struct image *img,
2700 struct image *preimage,
2701 struct image *postimage,
2702 int line,
2703 unsigned ws_rule,
2704 int match_beginning, int match_end)
2706 int i;
2707 unsigned long backwards, forwards, current;
2708 int backwards_lno, forwards_lno, current_lno;
2711 * When running with --allow-overlap, it is possible that a hunk is
2712 * seen that pretends to start at the beginning (but no longer does),
2713 * and that *still* needs to match the end. So trust `match_end` more
2714 * than `match_beginning`.
2716 if (state->allow_overlap && match_beginning && match_end &&
2717 img->line_nr - preimage->line_nr != 0)
2718 match_beginning = 0;
2721 * If match_beginning or match_end is specified, there is no
2722 * point starting from a wrong line that will never match and
2723 * wander around and wait for a match at the specified end.
2725 if (match_beginning)
2726 line = 0;
2727 else if (match_end)
2728 line = img->line_nr - preimage->line_nr;
2731 * Because the comparison is unsigned, the following test
2732 * will also take care of a negative line number that can
2733 * result when match_end and preimage is larger than the target.
2735 if ((size_t) line > img->line_nr)
2736 line = img->line_nr;
2738 current = 0;
2739 for (i = 0; i < line; i++)
2740 current += img->line[i].len;
2743 * There's probably some smart way to do this, but I'll leave
2744 * that to the smart and beautiful people. I'm simple and stupid.
2746 backwards = current;
2747 backwards_lno = line;
2748 forwards = current;
2749 forwards_lno = line;
2750 current_lno = line;
2752 for (i = 0; ; i++) {
2753 if (match_fragment(state, img, preimage, postimage,
2754 current, current_lno, ws_rule,
2755 match_beginning, match_end))
2756 return current_lno;
2758 again:
2759 if (backwards_lno == 0 && forwards_lno == img->line_nr)
2760 break;
2762 if (i & 1) {
2763 if (backwards_lno == 0) {
2764 i++;
2765 goto again;
2767 backwards_lno--;
2768 backwards -= img->line[backwards_lno].len;
2769 current = backwards;
2770 current_lno = backwards_lno;
2771 } else {
2772 if (forwards_lno == img->line_nr) {
2773 i++;
2774 goto again;
2776 forwards += img->line[forwards_lno].len;
2777 forwards_lno++;
2778 current = forwards;
2779 current_lno = forwards_lno;
2783 return -1;
2787 * The change from "preimage" and "postimage" has been found to
2788 * apply at applied_pos (counts in line numbers) in "img".
2789 * Update "img" to remove "preimage" and replace it with "postimage".
2791 static void update_image(struct apply_state *state,
2792 struct image *img,
2793 int applied_pos,
2794 struct image *preimage,
2795 struct image *postimage)
2798 * remove the copy of preimage at offset in img
2799 * and replace it with postimage
2801 int i, nr;
2802 size_t remove_count, insert_count, applied_at = 0;
2803 size_t result_alloc;
2804 char *result;
2805 int preimage_limit;
2808 * If we are removing blank lines at the end of img,
2809 * the preimage may extend beyond the end.
2810 * If that is the case, we must be careful only to
2811 * remove the part of the preimage that falls within
2812 * the boundaries of img. Initialize preimage_limit
2813 * to the number of lines in the preimage that falls
2814 * within the boundaries.
2816 preimage_limit = preimage->line_nr;
2817 if (preimage_limit > img->line_nr - applied_pos)
2818 preimage_limit = img->line_nr - applied_pos;
2820 for (i = 0; i < applied_pos; i++)
2821 applied_at += img->line[i].len;
2823 remove_count = 0;
2824 for (i = 0; i < preimage_limit; i++)
2825 remove_count += img->line[applied_pos + i].len;
2826 insert_count = postimage->buf.len;
2828 /* Adjust the contents */
2829 result_alloc = st_add3(st_sub(img->buf.len, remove_count), insert_count, 1);
2830 result = xmalloc(result_alloc);
2831 memcpy(result, img->buf.buf, applied_at);
2832 memcpy(result + applied_at, postimage->buf.buf, postimage->buf.len);
2833 memcpy(result + applied_at + postimage->buf.len,
2834 img->buf.buf + (applied_at + remove_count),
2835 img->buf.len - (applied_at + remove_count));
2836 strbuf_attach(&img->buf, result, postimage->buf.len + img->buf.len - remove_count,
2837 result_alloc);
2839 /* Adjust the line table */
2840 nr = img->line_nr + postimage->line_nr - preimage_limit;
2841 if (preimage_limit < postimage->line_nr)
2843 * NOTE: this knows that we never call image_remove_first_line()
2844 * on anything other than pre/post image.
2846 REALLOC_ARRAY(img->line, nr);
2847 if (preimage_limit != postimage->line_nr)
2848 MOVE_ARRAY(img->line + applied_pos + postimage->line_nr,
2849 img->line + applied_pos + preimage_limit,
2850 img->line_nr - (applied_pos + preimage_limit));
2851 COPY_ARRAY(img->line + applied_pos, postimage->line, postimage->line_nr);
2852 if (!state->allow_overlap)
2853 for (i = 0; i < postimage->line_nr; i++)
2854 img->line[applied_pos + i].flag |= LINE_PATCHED;
2855 img->line_nr = nr;
2859 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2860 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2861 * replace the part of "img" with "postimage" text.
2863 static int apply_one_fragment(struct apply_state *state,
2864 struct image *img, struct fragment *frag,
2865 int inaccurate_eof, unsigned ws_rule,
2866 int nth_fragment)
2868 int match_beginning, match_end;
2869 const char *patch = frag->patch;
2870 int size = frag->size;
2871 char *old, *oldlines;
2872 struct strbuf newlines;
2873 int new_blank_lines_at_end = 0;
2874 int found_new_blank_lines_at_end = 0;
2875 int hunk_linenr = frag->linenr;
2876 unsigned long leading, trailing;
2877 int pos, applied_pos;
2878 struct image preimage = IMAGE_INIT;
2879 struct image postimage = IMAGE_INIT;
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 image_add_line(&preimage, "\n", 1, LINE_COMMON);
2923 image_add_line(&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 image_add_line(&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 image_add_line(&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[preimage.line_nr - 1].len--;
2988 postimage.line[postimage.line_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 strbuf_add(&preimage.buf, oldlines, old - oldlines);
3019 strbuf_swap(&postimage.buf, &newlines);
3021 for (;;) {
3023 applied_pos = find_pos(state, img, &preimage, &postimage, pos,
3024 ws_rule, match_beginning, match_end);
3026 if (applied_pos >= 0)
3027 break;
3029 /* Am I at my context limits? */
3030 if ((leading <= state->p_context) && (trailing <= state->p_context))
3031 break;
3032 if (match_beginning || match_end) {
3033 match_beginning = match_end = 0;
3034 continue;
3038 * Reduce the number of context lines; reduce both
3039 * leading and trailing if they are equal otherwise
3040 * just reduce the larger context.
3042 if (leading >= trailing) {
3043 image_remove_first_line(&preimage);
3044 image_remove_first_line(&postimage);
3045 pos--;
3046 leading--;
3048 if (trailing > leading) {
3049 image_remove_last_line(&preimage);
3050 image_remove_last_line(&postimage);
3051 trailing--;
3055 if (applied_pos >= 0) {
3056 if (new_blank_lines_at_end &&
3057 preimage.line_nr + applied_pos >= img->line_nr &&
3058 (ws_rule & WS_BLANK_AT_EOF) &&
3059 state->ws_error_action != nowarn_ws_error) {
3060 record_ws_error(state, WS_BLANK_AT_EOF, "+", 1,
3061 found_new_blank_lines_at_end);
3062 if (state->ws_error_action == correct_ws_error) {
3063 while (new_blank_lines_at_end--)
3064 image_remove_last_line(&postimage);
3067 * We would want to prevent write_out_results()
3068 * from taking place in apply_patch() that follows
3069 * the callchain led us here, which is:
3070 * apply_patch->check_patch_list->check_patch->
3071 * apply_data->apply_fragments->apply_one_fragment
3073 if (state->ws_error_action == die_on_ws_error)
3074 state->apply = 0;
3077 if (state->apply_verbosity > verbosity_normal && applied_pos != pos) {
3078 int offset = applied_pos - pos;
3079 if (state->apply_in_reverse)
3080 offset = 0 - offset;
3081 fprintf_ln(stderr,
3082 Q_("Hunk #%d succeeded at %d (offset %d line).",
3083 "Hunk #%d succeeded at %d (offset %d lines).",
3084 offset),
3085 nth_fragment, applied_pos + 1, offset);
3089 * Warn if it was necessary to reduce the number
3090 * of context lines.
3092 if ((leading != frag->leading ||
3093 trailing != frag->trailing) && state->apply_verbosity > verbosity_silent)
3094 fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"
3095 " to apply fragment at %d"),
3096 leading, trailing, applied_pos+1);
3097 update_image(state, img, applied_pos, &preimage, &postimage);
3098 } else {
3099 if (state->apply_verbosity > verbosity_normal)
3100 error(_("while searching for:\n%.*s"),
3101 (int)(old - oldlines), oldlines);
3104 out:
3105 free(oldlines);
3106 strbuf_release(&newlines);
3107 image_clear(&preimage);
3108 image_clear(&postimage);
3110 return (applied_pos < 0);
3113 static int apply_binary_fragment(struct apply_state *state,
3114 struct image *img,
3115 struct patch *patch)
3117 struct fragment *fragment = patch->fragments;
3118 unsigned long len;
3119 void *dst;
3121 if (!fragment)
3122 return error(_("missing binary patch data for '%s'"),
3123 patch->new_name ?
3124 patch->new_name :
3125 patch->old_name);
3127 /* Binary patch is irreversible without the optional second hunk */
3128 if (state->apply_in_reverse) {
3129 if (!fragment->next)
3130 return error(_("cannot reverse-apply a binary patch "
3131 "without the reverse hunk to '%s'"),
3132 patch->new_name
3133 ? patch->new_name : patch->old_name);
3134 fragment = fragment->next;
3136 switch (fragment->binary_patch_method) {
3137 case BINARY_DELTA_DEFLATED:
3138 dst = patch_delta(img->buf.buf, img->buf.len, fragment->patch,
3139 fragment->size, &len);
3140 if (!dst)
3141 return -1;
3142 image_clear(img);
3143 strbuf_attach(&img->buf, dst, len, len + 1);
3144 return 0;
3145 case BINARY_LITERAL_DEFLATED:
3146 image_clear(img);
3147 strbuf_add(&img->buf, fragment->patch, fragment->size);
3148 return 0;
3150 return -1;
3154 * Replace "img" with the result of applying the binary patch.
3155 * The binary patch data itself in patch->fragment is still kept
3156 * but the preimage prepared by the caller in "img" is freed here
3157 * or in the helper function apply_binary_fragment() this calls.
3159 static int apply_binary(struct apply_state *state,
3160 struct image *img,
3161 struct patch *patch)
3163 const char *name = patch->old_name ? patch->old_name : patch->new_name;
3164 struct object_id oid;
3165 const unsigned hexsz = the_hash_algo->hexsz;
3168 * For safety, we require patch index line to contain
3169 * full hex textual object ID for old and new, at least for now.
3171 if (strlen(patch->old_oid_prefix) != hexsz ||
3172 strlen(patch->new_oid_prefix) != hexsz ||
3173 get_oid_hex(patch->old_oid_prefix, &oid) ||
3174 get_oid_hex(patch->new_oid_prefix, &oid))
3175 return error(_("cannot apply binary patch to '%s' "
3176 "without full index line"), name);
3178 if (patch->old_name) {
3180 * See if the old one matches what the patch
3181 * applies to.
3183 hash_object_file(the_hash_algo, img->buf.buf, img->buf.len,
3184 OBJ_BLOB, &oid);
3185 if (strcmp(oid_to_hex(&oid), patch->old_oid_prefix))
3186 return error(_("the patch applies to '%s' (%s), "
3187 "which does not match the "
3188 "current contents."),
3189 name, oid_to_hex(&oid));
3191 else {
3192 /* Otherwise, the old one must be empty. */
3193 if (img->buf.len)
3194 return error(_("the patch applies to an empty "
3195 "'%s' but it is not empty"), name);
3198 get_oid_hex(patch->new_oid_prefix, &oid);
3199 if (is_null_oid(&oid)) {
3200 image_clear(img);
3201 return 0; /* deletion patch */
3204 if (has_object(the_repository, &oid, 0)) {
3205 /* We already have the postimage */
3206 enum object_type type;
3207 unsigned long size;
3208 char *result;
3210 result = repo_read_object_file(the_repository, &oid, &type,
3211 &size);
3212 if (!result)
3213 return error(_("the necessary postimage %s for "
3214 "'%s' cannot be read"),
3215 patch->new_oid_prefix, name);
3216 image_clear(img);
3217 strbuf_attach(&img->buf, result, size, size + 1);
3218 } else {
3220 * We have verified buf matches the preimage;
3221 * apply the patch data to it, which is stored
3222 * in the patch->fragments->{patch,size}.
3224 if (apply_binary_fragment(state, img, patch))
3225 return error(_("binary patch does not apply to '%s'"),
3226 name);
3228 /* verify that the result matches */
3229 hash_object_file(the_hash_algo, img->buf.buf, img->buf.len, OBJ_BLOB,
3230 &oid);
3231 if (strcmp(oid_to_hex(&oid), patch->new_oid_prefix))
3232 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3233 name, patch->new_oid_prefix, oid_to_hex(&oid));
3236 return 0;
3239 static int apply_fragments(struct apply_state *state, struct image *img, struct patch *patch)
3241 struct fragment *frag = patch->fragments;
3242 const char *name = patch->old_name ? patch->old_name : patch->new_name;
3243 unsigned ws_rule = patch->ws_rule;
3244 unsigned inaccurate_eof = patch->inaccurate_eof;
3245 int nth = 0;
3247 if (patch->is_binary)
3248 return apply_binary(state, img, patch);
3250 while (frag) {
3251 nth++;
3252 if (apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {
3253 error(_("patch failed: %s:%ld"), name, frag->oldpos);
3254 if (!state->apply_with_reject)
3255 return -1;
3256 frag->rejected = 1;
3258 frag = frag->next;
3260 return 0;
3263 static int read_blob_object(struct strbuf *buf, const struct object_id *oid, unsigned mode)
3265 if (S_ISGITLINK(mode)) {
3266 strbuf_grow(buf, 100);
3267 strbuf_addf(buf, "Subproject commit %s\n", oid_to_hex(oid));
3268 } else {
3269 enum object_type type;
3270 unsigned long sz;
3271 char *result;
3273 result = repo_read_object_file(the_repository, oid, &type,
3274 &sz);
3275 if (!result)
3276 return -1;
3277 /* XXX read_sha1_file NUL-terminates */
3278 strbuf_attach(buf, result, sz, sz + 1);
3280 return 0;
3283 static int read_file_or_gitlink(const struct cache_entry *ce, struct strbuf *buf)
3285 if (!ce)
3286 return 0;
3287 return read_blob_object(buf, &ce->oid, ce->ce_mode);
3290 static struct patch *in_fn_table(struct apply_state *state, const char *name)
3292 struct string_list_item *item;
3294 if (!name)
3295 return NULL;
3297 item = string_list_lookup(&state->fn_table, name);
3298 if (item)
3299 return (struct patch *)item->util;
3301 return NULL;
3305 * item->util in the filename table records the status of the path.
3306 * Usually it points at a patch (whose result records the contents
3307 * of it after applying it), but it could be PATH_WAS_DELETED for a
3308 * path that a previously applied patch has already removed, or
3309 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3311 * The latter is needed to deal with a case where two paths A and B
3312 * are swapped by first renaming A to B and then renaming B to A;
3313 * moving A to B should not be prevented due to presence of B as we
3314 * will remove it in a later patch.
3316 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3317 #define PATH_WAS_DELETED ((struct patch *) -1)
3319 static int to_be_deleted(struct patch *patch)
3321 return patch == PATH_TO_BE_DELETED;
3324 static int was_deleted(struct patch *patch)
3326 return patch == PATH_WAS_DELETED;
3329 static void add_to_fn_table(struct apply_state *state, struct patch *patch)
3331 struct string_list_item *item;
3334 * Always add new_name unless patch is a deletion
3335 * This should cover the cases for normal diffs,
3336 * file creations and copies
3338 if (patch->new_name) {
3339 item = string_list_insert(&state->fn_table, patch->new_name);
3340 item->util = patch;
3344 * store a failure on rename/deletion cases because
3345 * later chunks shouldn't patch old names
3347 if ((patch->new_name == NULL) || (patch->is_rename)) {
3348 item = string_list_insert(&state->fn_table, patch->old_name);
3349 item->util = PATH_WAS_DELETED;
3353 static void prepare_fn_table(struct apply_state *state, struct patch *patch)
3356 * store information about incoming file deletion
3358 while (patch) {
3359 if ((patch->new_name == NULL) || (patch->is_rename)) {
3360 struct string_list_item *item;
3361 item = string_list_insert(&state->fn_table, patch->old_name);
3362 item->util = PATH_TO_BE_DELETED;
3364 patch = patch->next;
3368 static int checkout_target(struct index_state *istate,
3369 struct cache_entry *ce, struct stat *st)
3371 struct checkout costate = CHECKOUT_INIT;
3373 costate.refresh_cache = 1;
3374 costate.istate = istate;
3375 if (checkout_entry(ce, &costate, NULL, NULL) ||
3376 lstat(ce->name, st))
3377 return error(_("cannot checkout %s"), ce->name);
3378 return 0;
3381 static struct patch *previous_patch(struct apply_state *state,
3382 struct patch *patch,
3383 int *gone)
3385 struct patch *previous;
3387 *gone = 0;
3388 if (patch->is_copy || patch->is_rename)
3389 return NULL; /* "git" patches do not depend on the order */
3391 previous = in_fn_table(state, patch->old_name);
3392 if (!previous)
3393 return NULL;
3395 if (to_be_deleted(previous))
3396 return NULL; /* the deletion hasn't happened yet */
3398 if (was_deleted(previous))
3399 *gone = 1;
3401 return previous;
3404 static int verify_index_match(struct apply_state *state,
3405 const struct cache_entry *ce,
3406 struct stat *st)
3408 if (S_ISGITLINK(ce->ce_mode)) {
3409 if (!S_ISDIR(st->st_mode))
3410 return -1;
3411 return 0;
3413 return ie_match_stat(state->repo->index, ce, st,
3414 CE_MATCH_IGNORE_VALID | CE_MATCH_IGNORE_SKIP_WORKTREE);
3417 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3419 static int load_patch_target(struct apply_state *state,
3420 struct strbuf *buf,
3421 const struct cache_entry *ce,
3422 struct stat *st,
3423 struct patch *patch,
3424 const char *name,
3425 unsigned expected_mode)
3427 if (state->cached || state->check_index) {
3428 if (read_file_or_gitlink(ce, buf))
3429 return error(_("failed to read %s"), name);
3430 } else if (name) {
3431 if (S_ISGITLINK(expected_mode)) {
3432 if (ce)
3433 return read_file_or_gitlink(ce, buf);
3434 else
3435 return SUBMODULE_PATCH_WITHOUT_INDEX;
3436 } else if (has_symlink_leading_path(name, strlen(name))) {
3437 return error(_("reading from '%s' beyond a symbolic link"), name);
3438 } else {
3439 if (read_old_data(st, patch, name, buf))
3440 return error(_("failed to read %s"), name);
3443 return 0;
3447 * We are about to apply "patch"; populate the "image" with the
3448 * current version we have, from the working tree or from the index,
3449 * depending on the situation e.g. --cached/--index. If we are
3450 * applying a non-git patch that incrementally updates the tree,
3451 * we read from the result of a previous diff.
3453 static int load_preimage(struct apply_state *state,
3454 struct image *image,
3455 struct patch *patch, struct stat *st,
3456 const struct cache_entry *ce)
3458 struct strbuf buf = STRBUF_INIT;
3459 size_t len;
3460 char *img;
3461 struct patch *previous;
3462 int status;
3464 previous = previous_patch(state, patch, &status);
3465 if (status)
3466 return error(_("path %s has been renamed/deleted"),
3467 patch->old_name);
3468 if (previous) {
3469 /* We have a patched copy in memory; use that. */
3470 strbuf_add(&buf, previous->result, previous->resultsize);
3471 } else {
3472 status = load_patch_target(state, &buf, ce, st, patch,
3473 patch->old_name, patch->old_mode);
3474 if (status < 0)
3475 return status;
3476 else if (status == SUBMODULE_PATCH_WITHOUT_INDEX) {
3478 * There is no way to apply subproject
3479 * patch without looking at the index.
3480 * NEEDSWORK: shouldn't this be flagged
3481 * as an error???
3483 free_fragment_list(patch->fragments);
3484 patch->fragments = NULL;
3485 } else if (status) {
3486 return error(_("failed to read %s"), patch->old_name);
3490 img = strbuf_detach(&buf, &len);
3491 image_prepare(image, img, len, !patch->is_binary);
3492 return 0;
3495 static int resolve_to(struct image *image, const struct object_id *result_id)
3497 unsigned long size;
3498 enum object_type type;
3499 char *data;
3501 image_clear(image);
3503 data = repo_read_object_file(the_repository, result_id, &type, &size);
3504 if (!data || type != OBJ_BLOB)
3505 die("unable to read blob object %s", oid_to_hex(result_id));
3506 strbuf_attach(&image->buf, data, size, size + 1);
3508 return 0;
3511 static int three_way_merge(struct apply_state *state,
3512 struct image *image,
3513 char *path,
3514 const struct object_id *base,
3515 const struct object_id *ours,
3516 const struct object_id *theirs)
3518 mmfile_t base_file, our_file, their_file;
3519 struct ll_merge_options merge_opts = LL_MERGE_OPTIONS_INIT;
3520 mmbuffer_t result = { NULL };
3521 enum ll_merge_result status;
3523 /* resolve trivial cases first */
3524 if (oideq(base, ours))
3525 return resolve_to(image, theirs);
3526 else if (oideq(base, theirs) || oideq(ours, theirs))
3527 return resolve_to(image, ours);
3529 read_mmblob(&base_file, base);
3530 read_mmblob(&our_file, ours);
3531 read_mmblob(&their_file, theirs);
3532 merge_opts.variant = state->merge_variant;
3533 status = ll_merge(&result, path,
3534 &base_file, "base",
3535 &our_file, "ours",
3536 &their_file, "theirs",
3537 state->repo->index,
3538 &merge_opts);
3539 if (status == LL_MERGE_BINARY_CONFLICT)
3540 warning("Cannot merge binary files: %s (%s vs. %s)",
3541 path, "ours", "theirs");
3542 free(base_file.ptr);
3543 free(our_file.ptr);
3544 free(their_file.ptr);
3545 if (status < 0 || !result.ptr) {
3546 free(result.ptr);
3547 return -1;
3549 image_clear(image);
3550 strbuf_attach(&image->buf, result.ptr, result.size, result.size);
3552 return status;
3556 * When directly falling back to add/add three-way merge, we read from
3557 * the current contents of the new_name. In no cases other than that
3558 * this function will be called.
3560 static int load_current(struct apply_state *state,
3561 struct image *image,
3562 struct patch *patch)
3564 struct strbuf buf = STRBUF_INIT;
3565 int status, pos;
3566 size_t len;
3567 char *img;
3568 struct stat st;
3569 struct cache_entry *ce;
3570 char *name = patch->new_name;
3571 unsigned mode = patch->new_mode;
3573 if (!patch->is_new)
3574 BUG("patch to %s is not a creation", patch->old_name);
3576 pos = index_name_pos(state->repo->index, name, strlen(name));
3577 if (pos < 0)
3578 return error(_("%s: does not exist in index"), name);
3579 ce = state->repo->index->cache[pos];
3580 if (lstat(name, &st)) {
3581 if (errno != ENOENT)
3582 return error_errno("%s", name);
3583 if (checkout_target(state->repo->index, ce, &st))
3584 return -1;
3586 if (verify_index_match(state, ce, &st))
3587 return error(_("%s: does not match index"), name);
3589 status = load_patch_target(state, &buf, ce, &st, patch, name, mode);
3590 if (status < 0)
3591 return status;
3592 else if (status)
3593 return -1;
3594 img = strbuf_detach(&buf, &len);
3595 image_prepare(image, img, len, !patch->is_binary);
3596 return 0;
3599 static int try_threeway(struct apply_state *state,
3600 struct image *image,
3601 struct patch *patch,
3602 struct stat *st,
3603 const struct cache_entry *ce)
3605 struct object_id pre_oid, post_oid, our_oid;
3606 struct strbuf buf = STRBUF_INIT;
3607 size_t len;
3608 int status;
3609 char *img;
3610 struct image tmp_image = IMAGE_INIT;
3612 /* No point falling back to 3-way merge in these cases */
3613 if (patch->is_delete ||
3614 S_ISGITLINK(patch->old_mode) || S_ISGITLINK(patch->new_mode) ||
3615 (patch->is_new && !patch->direct_to_threeway) ||
3616 (patch->is_rename && !patch->lines_added && !patch->lines_deleted))
3617 return -1;
3619 /* Preimage the patch was prepared for */
3620 if (patch->is_new)
3621 write_object_file("", 0, OBJ_BLOB, &pre_oid);
3622 else if (repo_get_oid(the_repository, patch->old_oid_prefix, &pre_oid) ||
3623 read_blob_object(&buf, &pre_oid, patch->old_mode))
3624 return error(_("repository lacks the necessary blob to perform 3-way merge."));
3626 if (state->apply_verbosity > verbosity_silent && patch->direct_to_threeway)
3627 fprintf(stderr, _("Performing three-way merge...\n"));
3629 img = strbuf_detach(&buf, &len);
3630 image_prepare(&tmp_image, img, len, 1);
3631 /* Apply the patch to get the post image */
3632 if (apply_fragments(state, &tmp_image, patch) < 0) {
3633 image_clear(&tmp_image);
3634 return -1;
3636 /* post_oid is theirs */
3637 write_object_file(tmp_image.buf.buf, tmp_image.buf.len, OBJ_BLOB, &post_oid);
3638 image_clear(&tmp_image);
3640 /* our_oid is ours */
3641 if (patch->is_new) {
3642 if (load_current(state, &tmp_image, patch))
3643 return error(_("cannot read the current contents of '%s'"),
3644 patch->new_name);
3645 } else {
3646 if (load_preimage(state, &tmp_image, patch, st, ce))
3647 return error(_("cannot read the current contents of '%s'"),
3648 patch->old_name);
3650 write_object_file(tmp_image.buf.buf, tmp_image.buf.len, OBJ_BLOB, &our_oid);
3651 image_clear(&tmp_image);
3653 /* in-core three-way merge between post and our using pre as base */
3654 status = three_way_merge(state, image, patch->new_name,
3655 &pre_oid, &our_oid, &post_oid);
3656 if (status < 0) {
3657 if (state->apply_verbosity > verbosity_silent)
3658 fprintf(stderr,
3659 _("Failed to perform three-way merge...\n"));
3660 return status;
3663 if (status) {
3664 patch->conflicted_threeway = 1;
3665 if (patch->is_new)
3666 oidclr(&patch->threeway_stage[0], the_repository->hash_algo);
3667 else
3668 oidcpy(&patch->threeway_stage[0], &pre_oid);
3669 oidcpy(&patch->threeway_stage[1], &our_oid);
3670 oidcpy(&patch->threeway_stage[2], &post_oid);
3671 if (state->apply_verbosity > verbosity_silent)
3672 fprintf(stderr,
3673 _("Applied patch to '%s' with conflicts.\n"),
3674 patch->new_name);
3675 } else {
3676 if (state->apply_verbosity > verbosity_silent)
3677 fprintf(stderr,
3678 _("Applied patch to '%s' cleanly.\n"),
3679 patch->new_name);
3681 return 0;
3684 static int apply_data(struct apply_state *state, struct patch *patch,
3685 struct stat *st, const struct cache_entry *ce)
3687 struct image image = IMAGE_INIT;
3689 if (load_preimage(state, &image, patch, st, ce) < 0)
3690 return -1;
3692 if (!state->threeway || try_threeway(state, &image, patch, st, ce) < 0) {
3693 if (state->apply_verbosity > verbosity_silent &&
3694 state->threeway && !patch->direct_to_threeway)
3695 fprintf(stderr, _("Falling back to direct application...\n"));
3697 /* Note: with --reject, apply_fragments() returns 0 */
3698 if (patch->direct_to_threeway || apply_fragments(state, &image, patch) < 0) {
3699 image_clear(&image);
3700 return -1;
3703 patch->result = strbuf_detach(&image.buf, &patch->resultsize);
3704 add_to_fn_table(state, patch);
3705 free(image.line);
3707 if (0 < patch->is_delete && patch->resultsize)
3708 return error(_("removal patch leaves file contents"));
3710 return 0;
3714 * If "patch" that we are looking at modifies or deletes what we have,
3715 * we would want it not to lose any local modification we have, either
3716 * in the working tree or in the index.
3718 * This also decides if a non-git patch is a creation patch or a
3719 * modification to an existing empty file. We do not check the state
3720 * of the current tree for a creation patch in this function; the caller
3721 * check_patch() separately makes sure (and errors out otherwise) that
3722 * the path the patch creates does not exist in the current tree.
3724 static int check_preimage(struct apply_state *state,
3725 struct patch *patch,
3726 struct cache_entry **ce,
3727 struct stat *st)
3729 const char *old_name = patch->old_name;
3730 struct patch *previous = NULL;
3731 int stat_ret = 0, status;
3732 unsigned st_mode = 0;
3734 if (!old_name)
3735 return 0;
3737 assert(patch->is_new <= 0);
3738 previous = previous_patch(state, patch, &status);
3740 if (status)
3741 return error(_("path %s has been renamed/deleted"), old_name);
3742 if (previous) {
3743 st_mode = previous->new_mode;
3744 } else if (!state->cached) {
3745 stat_ret = lstat(old_name, st);
3746 if (stat_ret && errno != ENOENT)
3747 return error_errno("%s", old_name);
3750 if (state->check_index && !previous) {
3751 int pos = index_name_pos(state->repo->index, old_name,
3752 strlen(old_name));
3753 if (pos < 0) {
3754 if (patch->is_new < 0)
3755 goto is_new;
3756 return error(_("%s: does not exist in index"), old_name);
3758 *ce = state->repo->index->cache[pos];
3759 if (stat_ret < 0) {
3760 if (checkout_target(state->repo->index, *ce, st))
3761 return -1;
3763 if (!state->cached && verify_index_match(state, *ce, st))
3764 return error(_("%s: does not match index"), old_name);
3765 if (state->cached)
3766 st_mode = (*ce)->ce_mode;
3767 } else if (stat_ret < 0) {
3768 if (patch->is_new < 0)
3769 goto is_new;
3770 return error_errno("%s", old_name);
3773 if (!state->cached && !previous) {
3774 if (*ce && !(*ce)->ce_mode)
3775 BUG("ce_mode == 0 for path '%s'", old_name);
3777 if (trust_executable_bit)
3778 st_mode = ce_mode_from_stat(*ce, st->st_mode);
3779 else if (*ce)
3780 st_mode = (*ce)->ce_mode;
3781 else
3782 st_mode = patch->old_mode;
3785 if (patch->is_new < 0)
3786 patch->is_new = 0;
3787 if (!patch->old_mode)
3788 patch->old_mode = st_mode;
3789 if ((st_mode ^ patch->old_mode) & S_IFMT)
3790 return error(_("%s: wrong type"), old_name);
3791 if (st_mode != patch->old_mode)
3792 warning(_("%s has type %o, expected %o"),
3793 old_name, st_mode, patch->old_mode);
3794 if (!patch->new_mode && !patch->is_delete)
3795 patch->new_mode = st_mode;
3796 return 0;
3798 is_new:
3799 patch->is_new = 1;
3800 patch->is_delete = 0;
3801 FREE_AND_NULL(patch->old_name);
3802 return 0;
3806 #define EXISTS_IN_INDEX 1
3807 #define EXISTS_IN_WORKTREE 2
3808 #define EXISTS_IN_INDEX_AS_ITA 3
3810 static int check_to_create(struct apply_state *state,
3811 const char *new_name,
3812 int ok_if_exists)
3814 struct stat nst;
3816 if (state->check_index && (!ok_if_exists || !state->cached)) {
3817 int pos;
3819 pos = index_name_pos(state->repo->index, new_name, strlen(new_name));
3820 if (pos >= 0) {
3821 struct cache_entry *ce = state->repo->index->cache[pos];
3823 /* allow ITA, as they do not yet exist in the index */
3824 if (!ok_if_exists && !(ce->ce_flags & CE_INTENT_TO_ADD))
3825 return EXISTS_IN_INDEX;
3827 /* ITA entries can never match working tree files */
3828 if (!state->cached && (ce->ce_flags & CE_INTENT_TO_ADD))
3829 return EXISTS_IN_INDEX_AS_ITA;
3833 if (state->cached)
3834 return 0;
3836 if (!lstat(new_name, &nst)) {
3837 if (S_ISDIR(nst.st_mode) || ok_if_exists)
3838 return 0;
3840 * A leading component of new_name might be a symlink
3841 * that is going to be removed with this patch, but
3842 * still pointing at somewhere that has the path.
3843 * In such a case, path "new_name" does not exist as
3844 * far as git is concerned.
3846 if (has_symlink_leading_path(new_name, strlen(new_name)))
3847 return 0;
3849 return EXISTS_IN_WORKTREE;
3850 } else if (!is_missing_file_error(errno)) {
3851 return error_errno("%s", new_name);
3853 return 0;
3856 static void prepare_symlink_changes(struct apply_state *state, struct patch *patch)
3858 for ( ; patch; patch = patch->next) {
3859 if ((patch->old_name && S_ISLNK(patch->old_mode)) &&
3860 (patch->is_rename || patch->is_delete))
3861 /* the symlink at patch->old_name is removed */
3862 strset_add(&state->removed_symlinks, patch->old_name);
3864 if (patch->new_name && S_ISLNK(patch->new_mode))
3865 /* the symlink at patch->new_name is created or remains */
3866 strset_add(&state->kept_symlinks, patch->new_name);
3870 static int path_is_beyond_symlink_1(struct apply_state *state, struct strbuf *name)
3872 do {
3873 while (--name->len && name->buf[name->len] != '/')
3874 ; /* scan backwards */
3875 if (!name->len)
3876 break;
3877 name->buf[name->len] = '\0';
3878 if (strset_contains(&state->kept_symlinks, name->buf))
3879 return 1;
3880 if (strset_contains(&state->removed_symlinks, name->buf))
3882 * This cannot be "return 0", because we may
3883 * see a new one created at a higher level.
3885 continue;
3887 /* otherwise, check the preimage */
3888 if (state->check_index) {
3889 struct cache_entry *ce;
3891 ce = index_file_exists(state->repo->index, name->buf,
3892 name->len, ignore_case);
3893 if (ce && S_ISLNK(ce->ce_mode))
3894 return 1;
3895 } else {
3896 struct stat st;
3897 if (!lstat(name->buf, &st) && S_ISLNK(st.st_mode))
3898 return 1;
3900 } while (1);
3901 return 0;
3904 static int path_is_beyond_symlink(struct apply_state *state, const char *name_)
3906 int ret;
3907 struct strbuf name = STRBUF_INIT;
3909 assert(*name_ != '\0');
3910 strbuf_addstr(&name, name_);
3911 ret = path_is_beyond_symlink_1(state, &name);
3912 strbuf_release(&name);
3914 return ret;
3917 static int check_unsafe_path(struct patch *patch)
3919 const char *old_name = NULL;
3920 const char *new_name = NULL;
3921 if (patch->is_delete)
3922 old_name = patch->old_name;
3923 else if (!patch->is_new && !patch->is_copy)
3924 old_name = patch->old_name;
3925 if (!patch->is_delete)
3926 new_name = patch->new_name;
3928 if (old_name && !verify_path(old_name, patch->old_mode))
3929 return error(_("invalid path '%s'"), old_name);
3930 if (new_name && !verify_path(new_name, patch->new_mode))
3931 return error(_("invalid path '%s'"), new_name);
3932 return 0;
3936 * Check and apply the patch in-core; leave the result in patch->result
3937 * for the caller to write it out to the final destination.
3939 static int check_patch(struct apply_state *state, struct patch *patch)
3941 struct stat st;
3942 const char *old_name = patch->old_name;
3943 const char *new_name = patch->new_name;
3944 const char *name = old_name ? old_name : new_name;
3945 struct cache_entry *ce = NULL;
3946 struct patch *tpatch;
3947 int ok_if_exists;
3948 int status;
3950 patch->rejected = 1; /* we will drop this after we succeed */
3952 status = check_preimage(state, patch, &ce, &st);
3953 if (status)
3954 return status;
3955 old_name = patch->old_name;
3958 * A type-change diff is always split into a patch to delete
3959 * old, immediately followed by a patch to create new (see
3960 * diff.c::run_diff()); in such a case it is Ok that the entry
3961 * to be deleted by the previous patch is still in the working
3962 * tree and in the index.
3964 * A patch to swap-rename between A and B would first rename A
3965 * to B and then rename B to A. While applying the first one,
3966 * the presence of B should not stop A from getting renamed to
3967 * B; ask to_be_deleted() about the later rename. Removal of
3968 * B and rename from A to B is handled the same way by asking
3969 * was_deleted().
3971 if ((tpatch = in_fn_table(state, new_name)) &&
3972 (was_deleted(tpatch) || to_be_deleted(tpatch)))
3973 ok_if_exists = 1;
3974 else
3975 ok_if_exists = 0;
3977 if (new_name &&
3978 ((0 < patch->is_new) || patch->is_rename || patch->is_copy)) {
3979 int err = check_to_create(state, new_name, ok_if_exists);
3981 if (err && state->threeway) {
3982 patch->direct_to_threeway = 1;
3983 } else switch (err) {
3984 case 0:
3985 break; /* happy */
3986 case EXISTS_IN_INDEX:
3987 return error(_("%s: already exists in index"), new_name);
3988 case EXISTS_IN_INDEX_AS_ITA:
3989 return error(_("%s: does not match index"), new_name);
3990 case EXISTS_IN_WORKTREE:
3991 return error(_("%s: already exists in working directory"),
3992 new_name);
3993 default:
3994 return err;
3997 if (!patch->new_mode) {
3998 if (0 < patch->is_new)
3999 patch->new_mode = S_IFREG | 0644;
4000 else
4001 patch->new_mode = patch->old_mode;
4005 if (new_name && old_name) {
4006 int same = !strcmp(old_name, new_name);
4007 if (!patch->new_mode)
4008 patch->new_mode = patch->old_mode;
4009 if ((patch->old_mode ^ patch->new_mode) & S_IFMT) {
4010 if (same)
4011 return error(_("new mode (%o) of %s does not "
4012 "match old mode (%o)"),
4013 patch->new_mode, new_name,
4014 patch->old_mode);
4015 else
4016 return error(_("new mode (%o) of %s does not "
4017 "match old mode (%o) of %s"),
4018 patch->new_mode, new_name,
4019 patch->old_mode, old_name);
4023 if (!state->unsafe_paths && check_unsafe_path(patch))
4024 return -128;
4027 * An attempt to read from or delete a path that is beyond a
4028 * symbolic link will be prevented by load_patch_target() that
4029 * is called at the beginning of apply_data() so we do not
4030 * have to worry about a patch marked with "is_delete" bit
4031 * here. We however need to make sure that the patch result
4032 * is not deposited to a path that is beyond a symbolic link
4033 * here.
4035 if (!patch->is_delete && path_is_beyond_symlink(state, patch->new_name))
4036 return error(_("affected file '%s' is beyond a symbolic link"),
4037 patch->new_name);
4039 if (apply_data(state, patch, &st, ce) < 0)
4040 return error(_("%s: patch does not apply"), name);
4041 patch->rejected = 0;
4042 return 0;
4045 static int check_patch_list(struct apply_state *state, struct patch *patch)
4047 int err = 0;
4049 prepare_symlink_changes(state, patch);
4050 prepare_fn_table(state, patch);
4051 while (patch) {
4052 int res;
4053 if (state->apply_verbosity > verbosity_normal)
4054 say_patch_name(stderr,
4055 _("Checking patch %s..."), patch);
4056 res = check_patch(state, patch);
4057 if (res == -128)
4058 return -128;
4059 err |= res;
4060 patch = patch->next;
4062 return err;
4065 static int read_apply_cache(struct apply_state *state)
4067 if (state->index_file)
4068 return read_index_from(state->repo->index, state->index_file,
4069 repo_get_git_dir(the_repository));
4070 else
4071 return repo_read_index(state->repo);
4074 /* This function tries to read the object name from the current index */
4075 static int get_current_oid(struct apply_state *state, const char *path,
4076 struct object_id *oid)
4078 int pos;
4080 if (read_apply_cache(state) < 0)
4081 return -1;
4082 pos = index_name_pos(state->repo->index, path, strlen(path));
4083 if (pos < 0)
4084 return -1;
4085 oidcpy(oid, &state->repo->index->cache[pos]->oid);
4086 return 0;
4089 static int preimage_oid_in_gitlink_patch(struct patch *p, struct object_id *oid)
4092 * A usable gitlink patch has only one fragment (hunk) that looks like:
4093 * @@ -1 +1 @@
4094 * -Subproject commit <old sha1>
4095 * +Subproject commit <new sha1>
4096 * or
4097 * @@ -1 +0,0 @@
4098 * -Subproject commit <old sha1>
4099 * for a removal patch.
4101 struct fragment *hunk = p->fragments;
4102 static const char heading[] = "-Subproject commit ";
4103 char *preimage;
4105 if (/* does the patch have only one hunk? */
4106 hunk && !hunk->next &&
4107 /* is its preimage one line? */
4108 hunk->oldpos == 1 && hunk->oldlines == 1 &&
4109 /* does preimage begin with the heading? */
4110 (preimage = memchr(hunk->patch, '\n', hunk->size)) != NULL &&
4111 starts_with(++preimage, heading) &&
4112 /* does it record full SHA-1? */
4113 !get_oid_hex(preimage + sizeof(heading) - 1, oid) &&
4114 preimage[sizeof(heading) + the_hash_algo->hexsz - 1] == '\n' &&
4115 /* does the abbreviated name on the index line agree with it? */
4116 starts_with(preimage + sizeof(heading) - 1, p->old_oid_prefix))
4117 return 0; /* it all looks fine */
4119 /* we may have full object name on the index line */
4120 return get_oid_hex(p->old_oid_prefix, oid);
4123 /* Build an index that contains just the files needed for a 3way merge */
4124 static int build_fake_ancestor(struct apply_state *state, struct patch *list)
4126 struct patch *patch;
4127 struct index_state result = INDEX_STATE_INIT(state->repo);
4128 struct lock_file lock = LOCK_INIT;
4129 int res;
4131 /* Once we start supporting the reverse patch, it may be
4132 * worth showing the new sha1 prefix, but until then...
4134 for (patch = list; patch; patch = patch->next) {
4135 struct object_id oid;
4136 struct cache_entry *ce;
4137 const char *name;
4139 name = patch->old_name ? patch->old_name : patch->new_name;
4140 if (0 < patch->is_new)
4141 continue;
4143 if (S_ISGITLINK(patch->old_mode)) {
4144 if (!preimage_oid_in_gitlink_patch(patch, &oid))
4145 ; /* ok, the textual part looks sane */
4146 else
4147 return error(_("sha1 information is lacking or "
4148 "useless for submodule %s"), name);
4149 } else if (!repo_get_oid_blob(the_repository, patch->old_oid_prefix, &oid)) {
4150 ; /* ok */
4151 } else if (!patch->lines_added && !patch->lines_deleted) {
4152 /* mode-only change: update the current */
4153 if (get_current_oid(state, patch->old_name, &oid))
4154 return error(_("mode change for %s, which is not "
4155 "in current HEAD"), name);
4156 } else
4157 return error(_("sha1 information is lacking or useless "
4158 "(%s)."), name);
4160 ce = make_cache_entry(&result, patch->old_mode, &oid, name, 0, 0);
4161 if (!ce)
4162 return error(_("make_cache_entry failed for path '%s'"),
4163 name);
4164 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) {
4165 discard_cache_entry(ce);
4166 return error(_("could not add %s to temporary index"),
4167 name);
4171 hold_lock_file_for_update(&lock, state->fake_ancestor, LOCK_DIE_ON_ERROR);
4172 res = write_locked_index(&result, &lock, COMMIT_LOCK);
4173 discard_index(&result);
4175 if (res)
4176 return error(_("could not write temporary index to %s"),
4177 state->fake_ancestor);
4179 return 0;
4182 static void stat_patch_list(struct apply_state *state, struct patch *patch)
4184 int files, adds, dels;
4186 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
4187 files++;
4188 adds += patch->lines_added;
4189 dels += patch->lines_deleted;
4190 show_stats(state, patch);
4193 print_stat_summary(stdout, files, adds, dels);
4196 static void numstat_patch_list(struct apply_state *state,
4197 struct patch *patch)
4199 for ( ; patch; patch = patch->next) {
4200 const char *name;
4201 name = patch->new_name ? patch->new_name : patch->old_name;
4202 if (patch->is_binary)
4203 printf("-\t-\t");
4204 else
4205 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
4206 write_name_quoted(name, stdout, state->line_termination);
4210 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
4212 if (mode)
4213 printf(" %s mode %06o %s\n", newdelete, mode, name);
4214 else
4215 printf(" %s %s\n", newdelete, name);
4218 static void show_mode_change(struct patch *p, int show_name)
4220 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
4221 if (show_name)
4222 printf(" mode change %06o => %06o %s\n",
4223 p->old_mode, p->new_mode, p->new_name);
4224 else
4225 printf(" mode change %06o => %06o\n",
4226 p->old_mode, p->new_mode);
4230 static void show_rename_copy(struct patch *p)
4232 const char *renamecopy = p->is_rename ? "rename" : "copy";
4233 const char *old_name, *new_name;
4235 /* Find common prefix */
4236 old_name = p->old_name;
4237 new_name = p->new_name;
4238 while (1) {
4239 const char *slash_old, *slash_new;
4240 slash_old = strchr(old_name, '/');
4241 slash_new = strchr(new_name, '/');
4242 if (!slash_old ||
4243 !slash_new ||
4244 slash_old - old_name != slash_new - new_name ||
4245 memcmp(old_name, new_name, slash_new - new_name))
4246 break;
4247 old_name = slash_old + 1;
4248 new_name = slash_new + 1;
4250 /* p->old_name through old_name is the common prefix, and old_name and
4251 * new_name through the end of names are renames
4253 if (old_name != p->old_name)
4254 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
4255 (int)(old_name - p->old_name), p->old_name,
4256 old_name, new_name, p->score);
4257 else
4258 printf(" %s %s => %s (%d%%)\n", renamecopy,
4259 p->old_name, p->new_name, p->score);
4260 show_mode_change(p, 0);
4263 static void summary_patch_list(struct patch *patch)
4265 struct patch *p;
4267 for (p = patch; p; p = p->next) {
4268 if (p->is_new)
4269 show_file_mode_name("create", p->new_mode, p->new_name);
4270 else if (p->is_delete)
4271 show_file_mode_name("delete", p->old_mode, p->old_name);
4272 else {
4273 if (p->is_rename || p->is_copy)
4274 show_rename_copy(p);
4275 else {
4276 if (p->score) {
4277 printf(" rewrite %s (%d%%)\n",
4278 p->new_name, p->score);
4279 show_mode_change(p, 0);
4281 else
4282 show_mode_change(p, 1);
4288 static void patch_stats(struct apply_state *state, struct patch *patch)
4290 int lines = patch->lines_added + patch->lines_deleted;
4292 if (lines > state->max_change)
4293 state->max_change = lines;
4294 if (patch->old_name) {
4295 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
4296 if (!len)
4297 len = strlen(patch->old_name);
4298 if (len > state->max_len)
4299 state->max_len = len;
4301 if (patch->new_name) {
4302 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
4303 if (!len)
4304 len = strlen(patch->new_name);
4305 if (len > state->max_len)
4306 state->max_len = len;
4310 static int remove_file(struct apply_state *state, struct patch *patch, int rmdir_empty)
4312 if (state->update_index && !state->ita_only) {
4313 if (remove_file_from_index(state->repo->index, patch->old_name) < 0)
4314 return error(_("unable to remove %s from index"), patch->old_name);
4316 if (!state->cached) {
4317 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
4318 remove_path(patch->old_name);
4321 return 0;
4324 static int add_index_file(struct apply_state *state,
4325 const char *path,
4326 unsigned mode,
4327 void *buf,
4328 unsigned long size)
4330 struct stat st;
4331 struct cache_entry *ce;
4332 int namelen = strlen(path);
4334 ce = make_empty_cache_entry(state->repo->index, namelen);
4335 memcpy(ce->name, path, namelen);
4336 ce->ce_mode = create_ce_mode(mode);
4337 ce->ce_flags = create_ce_flags(0);
4338 ce->ce_namelen = namelen;
4339 if (state->ita_only) {
4340 ce->ce_flags |= CE_INTENT_TO_ADD;
4341 set_object_name_for_intent_to_add_entry(ce);
4342 } else if (S_ISGITLINK(mode)) {
4343 const char *s;
4345 if (!skip_prefix(buf, "Subproject commit ", &s) ||
4346 get_oid_hex(s, &ce->oid)) {
4347 discard_cache_entry(ce);
4348 return error(_("corrupt patch for submodule %s"), path);
4350 } else {
4351 if (!state->cached) {
4352 if (lstat(path, &st) < 0) {
4353 discard_cache_entry(ce);
4354 return error_errno(_("unable to stat newly "
4355 "created file '%s'"),
4356 path);
4358 fill_stat_cache_info(state->repo->index, ce, &st);
4360 if (write_object_file(buf, size, OBJ_BLOB, &ce->oid) < 0) {
4361 discard_cache_entry(ce);
4362 return error(_("unable to create backing store "
4363 "for newly created file %s"), path);
4366 if (add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) < 0) {
4367 discard_cache_entry(ce);
4368 return error(_("unable to add cache entry for %s"), path);
4371 return 0;
4375 * Returns:
4376 * -1 if an unrecoverable error happened
4377 * 0 if everything went well
4378 * 1 if a recoverable error happened
4380 static int try_create_file(struct apply_state *state, const char *path,
4381 unsigned int mode, const char *buf,
4382 unsigned long size)
4384 int fd, res;
4385 struct strbuf nbuf = STRBUF_INIT;
4387 if (S_ISGITLINK(mode)) {
4388 struct stat st;
4389 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
4390 return 0;
4391 return !!mkdir(path, 0777);
4394 if (has_symlinks && S_ISLNK(mode))
4395 /* Although buf:size is counted string, it also is NUL
4396 * terminated.
4398 return !!symlink(buf, path);
4400 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
4401 if (fd < 0)
4402 return 1;
4404 if (convert_to_working_tree(state->repo->index, path, buf, size, &nbuf, NULL)) {
4405 size = nbuf.len;
4406 buf = nbuf.buf;
4409 res = write_in_full(fd, buf, size) < 0;
4410 if (res)
4411 error_errno(_("failed to write to '%s'"), path);
4412 strbuf_release(&nbuf);
4414 if (close(fd) < 0 && !res)
4415 return error_errno(_("closing file '%s'"), path);
4417 return res ? -1 : 0;
4421 * We optimistically assume that the directories exist,
4422 * which is true 99% of the time anyway. If they don't,
4423 * we create them and try again.
4425 * Returns:
4426 * -1 on error
4427 * 0 otherwise
4429 static int create_one_file(struct apply_state *state,
4430 char *path,
4431 unsigned mode,
4432 const char *buf,
4433 unsigned long size)
4435 char *newpath = NULL;
4436 int res;
4438 if (state->cached)
4439 return 0;
4442 * We already try to detect whether files are beyond a symlink in our
4443 * up-front checks. But in the case where symlinks are created by any
4444 * of the intermediate hunks it can happen that our up-front checks
4445 * didn't yet see the symlink, but at the point of arriving here there
4446 * in fact is one. We thus repeat the check for symlinks here.
4448 * Note that this does not make the up-front check obsolete as the
4449 * failure mode is different:
4451 * - The up-front checks cause us to abort before we have written
4452 * anything into the working directory. So when we exit this way the
4453 * working directory remains clean.
4455 * - The checks here happen in the middle of the action where we have
4456 * already started to apply the patch. The end result will be a dirty
4457 * working directory.
4459 * Ideally, we should update the up-front checks to catch what would
4460 * happen when we apply the patch before we damage the working tree.
4461 * We have all the information necessary to do so. But for now, as a
4462 * part of embargoed security work, having this check would serve as a
4463 * reasonable first step.
4465 if (path_is_beyond_symlink(state, path))
4466 return error(_("affected file '%s' is beyond a symbolic link"), path);
4468 res = try_create_file(state, path, mode, buf, size);
4469 if (res < 0)
4470 return -1;
4471 if (!res)
4472 return 0;
4474 if (errno == ENOENT) {
4475 if (safe_create_leading_directories_no_share(path))
4476 return 0;
4477 res = try_create_file(state, path, mode, buf, size);
4478 if (res < 0)
4479 return -1;
4480 if (!res)
4481 return 0;
4484 if (errno == EEXIST || errno == EACCES) {
4485 /* We may be trying to create a file where a directory
4486 * used to be.
4488 struct stat st;
4489 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
4490 errno = EEXIST;
4493 if (errno == EEXIST) {
4494 unsigned int nr = getpid();
4496 for (;;) {
4497 newpath = mkpathdup("%s~%u", path, nr);
4498 res = try_create_file(state, newpath, mode, buf, size);
4499 if (res < 0)
4500 goto out;
4501 if (!res) {
4502 if (!rename(newpath, path))
4503 goto out;
4504 unlink_or_warn(newpath);
4505 break;
4507 if (errno != EEXIST)
4508 break;
4509 ++nr;
4510 FREE_AND_NULL(newpath);
4513 res = error_errno(_("unable to write file '%s' mode %o"), path, mode);
4514 out:
4515 free(newpath);
4516 return res;
4519 static int add_conflicted_stages_file(struct apply_state *state,
4520 struct patch *patch)
4522 int stage, namelen;
4523 unsigned mode;
4524 struct cache_entry *ce;
4526 if (!state->update_index)
4527 return 0;
4528 namelen = strlen(patch->new_name);
4529 mode = patch->new_mode ? patch->new_mode : (S_IFREG | 0644);
4531 remove_file_from_index(state->repo->index, patch->new_name);
4532 for (stage = 1; stage < 4; stage++) {
4533 if (is_null_oid(&patch->threeway_stage[stage - 1]))
4534 continue;
4535 ce = make_empty_cache_entry(state->repo->index, namelen);
4536 memcpy(ce->name, patch->new_name, namelen);
4537 ce->ce_mode = create_ce_mode(mode);
4538 ce->ce_flags = create_ce_flags(stage);
4539 ce->ce_namelen = namelen;
4540 oidcpy(&ce->oid, &patch->threeway_stage[stage - 1]);
4541 if (add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) < 0) {
4542 discard_cache_entry(ce);
4543 return error(_("unable to add cache entry for %s"),
4544 patch->new_name);
4548 return 0;
4551 static int create_file(struct apply_state *state, struct patch *patch)
4553 char *path = patch->new_name;
4554 unsigned mode = patch->new_mode;
4555 unsigned long size = patch->resultsize;
4556 char *buf = patch->result;
4558 if (!mode)
4559 mode = S_IFREG | 0644;
4560 if (create_one_file(state, path, mode, buf, size))
4561 return -1;
4563 if (patch->conflicted_threeway)
4564 return add_conflicted_stages_file(state, patch);
4565 else if (state->update_index)
4566 return add_index_file(state, path, mode, buf, size);
4567 return 0;
4570 /* phase zero is to remove, phase one is to create */
4571 static int write_out_one_result(struct apply_state *state,
4572 struct patch *patch,
4573 int phase)
4575 if (patch->is_delete > 0) {
4576 if (phase == 0)
4577 return remove_file(state, patch, 1);
4578 return 0;
4580 if (patch->is_new > 0 || patch->is_copy) {
4581 if (phase == 1)
4582 return create_file(state, patch);
4583 return 0;
4586 * Rename or modification boils down to the same
4587 * thing: remove the old, write the new
4589 if (phase == 0)
4590 return remove_file(state, patch, patch->is_rename);
4591 if (phase == 1)
4592 return create_file(state, patch);
4593 return 0;
4596 static int write_out_one_reject(struct apply_state *state, struct patch *patch)
4598 FILE *rej;
4599 char *namebuf;
4600 struct fragment *frag;
4601 int fd, cnt = 0;
4602 struct strbuf sb = STRBUF_INIT;
4604 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
4605 if (!frag->rejected)
4606 continue;
4607 cnt++;
4610 if (!cnt) {
4611 if (state->apply_verbosity > verbosity_normal)
4612 say_patch_name(stderr,
4613 _("Applied patch %s cleanly."), patch);
4614 return 0;
4617 /* This should not happen, because a removal patch that leaves
4618 * contents are marked "rejected" at the patch level.
4620 if (!patch->new_name)
4621 die(_("internal error"));
4623 /* Say this even without --verbose */
4624 strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",
4625 "Applying patch %%s with %d rejects...",
4626 cnt),
4627 cnt);
4628 if (state->apply_verbosity > verbosity_silent)
4629 say_patch_name(stderr, sb.buf, patch);
4630 strbuf_release(&sb);
4632 namebuf = xstrfmt("%s.rej", patch->new_name);
4634 fd = open(namebuf, O_CREAT | O_EXCL | O_WRONLY, 0666);
4635 if (fd < 0) {
4636 if (errno != EEXIST) {
4637 error_errno(_("cannot open %s"), namebuf);
4638 goto error;
4640 if (unlink(namebuf)) {
4641 error_errno(_("cannot unlink '%s'"), namebuf);
4642 goto error;
4644 fd = open(namebuf, O_CREAT | O_EXCL | O_WRONLY, 0666);
4645 if (fd < 0) {
4646 error_errno(_("cannot open %s"), namebuf);
4647 goto error;
4650 rej = fdopen(fd, "w");
4651 if (!rej) {
4652 error_errno(_("cannot open %s"), namebuf);
4653 close(fd);
4654 goto error;
4657 /* Normal git tools never deal with .rej, so do not pretend
4658 * this is a git patch by saying --git or giving extended
4659 * headers. While at it, maybe please "kompare" that wants
4660 * the trailing TAB and some garbage at the end of line ;-).
4662 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
4663 patch->new_name, patch->new_name);
4664 for (cnt = 1, frag = patch->fragments;
4665 frag;
4666 cnt++, frag = frag->next) {
4667 if (!frag->rejected) {
4668 if (state->apply_verbosity > verbosity_silent)
4669 fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);
4670 continue;
4672 if (state->apply_verbosity > verbosity_silent)
4673 fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);
4674 fprintf(rej, "%.*s", frag->size, frag->patch);
4675 if (frag->patch[frag->size-1] != '\n')
4676 fputc('\n', rej);
4678 fclose(rej);
4679 error:
4680 free(namebuf);
4681 return -1;
4685 * Returns:
4686 * -1 if an error happened
4687 * 0 if the patch applied cleanly
4688 * 1 if the patch did not apply cleanly
4690 static int write_out_results(struct apply_state *state, struct patch *list)
4692 int phase;
4693 int errs = 0;
4694 struct patch *l;
4695 struct string_list cpath = STRING_LIST_INIT_DUP;
4697 for (phase = 0; phase < 2; phase++) {
4698 l = list;
4699 while (l) {
4700 if (l->rejected)
4701 errs = 1;
4702 else {
4703 if (write_out_one_result(state, l, phase)) {
4704 string_list_clear(&cpath, 0);
4705 return -1;
4707 if (phase == 1) {
4708 if (write_out_one_reject(state, l))
4709 errs = 1;
4710 if (l->conflicted_threeway) {
4711 string_list_append(&cpath, l->new_name);
4712 errs = 1;
4716 l = l->next;
4720 if (cpath.nr) {
4721 struct string_list_item *item;
4723 string_list_sort(&cpath);
4724 if (state->apply_verbosity > verbosity_silent) {
4725 for_each_string_list_item(item, &cpath)
4726 fprintf(stderr, "U %s\n", item->string);
4728 string_list_clear(&cpath, 0);
4731 * rerere relies on the partially merged result being in the working
4732 * tree with conflict markers, but that isn't written with --cached.
4734 if (!state->cached)
4735 repo_rerere(state->repo, 0);
4738 return errs;
4742 * Try to apply a patch.
4744 * Returns:
4745 * -128 if a bad error happened (like patch unreadable)
4746 * -1 if patch did not apply and user cannot deal with it
4747 * 0 if the patch applied
4748 * 1 if the patch did not apply but user might fix it
4750 static int apply_patch(struct apply_state *state,
4751 int fd,
4752 const char *filename,
4753 int options)
4755 size_t offset;
4756 struct strbuf buf = STRBUF_INIT; /* owns the patch text */
4757 struct patch *list = NULL, **listp = &list;
4758 int skipped_patch = 0;
4759 int res = 0;
4760 int flush_attributes = 0;
4762 state->patch_input_file = filename;
4763 if (read_patch_file(&buf, fd) < 0)
4764 return -128;
4765 offset = 0;
4766 while (offset < buf.len) {
4767 struct patch *patch;
4768 int nr;
4770 CALLOC_ARRAY(patch, 1);
4771 patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF);
4772 patch->recount = !!(options & APPLY_OPT_RECOUNT);
4773 nr = parse_chunk(state, buf.buf + offset, buf.len - offset, patch);
4774 if (nr < 0) {
4775 free_patch(patch);
4776 if (nr == -128) {
4777 res = -128;
4778 goto end;
4780 break;
4782 if (state->apply_in_reverse)
4783 reverse_patches(patch);
4784 if (use_patch(state, patch)) {
4785 patch_stats(state, patch);
4786 if (!list || !state->apply_in_reverse) {
4787 *listp = patch;
4788 listp = &patch->next;
4789 } else {
4790 patch->next = list;
4791 list = patch;
4794 if ((patch->new_name &&
4795 ends_with_path_components(patch->new_name,
4796 GITATTRIBUTES_FILE)) ||
4797 (patch->old_name &&
4798 ends_with_path_components(patch->old_name,
4799 GITATTRIBUTES_FILE)))
4800 flush_attributes = 1;
4802 else {
4803 if (state->apply_verbosity > verbosity_normal)
4804 say_patch_name(stderr, _("Skipped patch '%s'."), patch);
4805 free_patch(patch);
4806 skipped_patch++;
4808 offset += nr;
4811 if (!list && !skipped_patch) {
4812 if (!state->allow_empty) {
4813 error(_("No valid patches in input (allow with \"--allow-empty\")"));
4814 res = -128;
4816 goto end;
4819 if (state->whitespace_error && (state->ws_error_action == die_on_ws_error))
4820 state->apply = 0;
4822 state->update_index = (state->check_index || state->ita_only) && state->apply;
4823 if (state->update_index && !is_lock_file_locked(&state->lock_file)) {
4824 if (state->index_file)
4825 hold_lock_file_for_update(&state->lock_file,
4826 state->index_file,
4827 LOCK_DIE_ON_ERROR);
4828 else
4829 repo_hold_locked_index(state->repo, &state->lock_file,
4830 LOCK_DIE_ON_ERROR);
4833 if (state->check_index && read_apply_cache(state) < 0) {
4834 error(_("unable to read index file"));
4835 res = -128;
4836 goto end;
4839 if (state->check || state->apply) {
4840 int r = check_patch_list(state, list);
4841 if (r == -128) {
4842 res = -128;
4843 goto end;
4845 if (r < 0 && !state->apply_with_reject) {
4846 res = -1;
4847 goto end;
4851 if (state->apply) {
4852 int write_res = write_out_results(state, list);
4853 if (write_res < 0) {
4854 res = -128;
4855 goto end;
4857 if (write_res > 0) {
4858 /* with --3way, we still need to write the index out */
4859 res = state->apply_with_reject ? -1 : 1;
4860 goto end;
4864 if (state->fake_ancestor &&
4865 build_fake_ancestor(state, list)) {
4866 res = -128;
4867 goto end;
4870 if (state->diffstat && state->apply_verbosity > verbosity_silent)
4871 stat_patch_list(state, list);
4873 if (state->numstat && state->apply_verbosity > verbosity_silent)
4874 numstat_patch_list(state, list);
4876 if (state->summary && state->apply_verbosity > verbosity_silent)
4877 summary_patch_list(list);
4879 if (flush_attributes)
4880 reset_parsed_attributes();
4881 end:
4882 free_patch_list(list);
4883 strbuf_release(&buf);
4884 string_list_clear(&state->fn_table, 0);
4885 return res;
4888 static int apply_option_parse_exclude(const struct option *opt,
4889 const char *arg, int unset)
4891 struct apply_state *state = opt->value;
4893 BUG_ON_OPT_NEG(unset);
4895 add_name_limit(state, arg, 1);
4896 return 0;
4899 static int apply_option_parse_include(const struct option *opt,
4900 const char *arg, int unset)
4902 struct apply_state *state = opt->value;
4904 BUG_ON_OPT_NEG(unset);
4906 add_name_limit(state, arg, 0);
4907 state->has_include = 1;
4908 return 0;
4911 static int apply_option_parse_p(const struct option *opt,
4912 const char *arg,
4913 int unset)
4915 struct apply_state *state = opt->value;
4917 BUG_ON_OPT_NEG(unset);
4919 state->p_value = atoi(arg);
4920 state->p_value_known = 1;
4921 return 0;
4924 static int apply_option_parse_space_change(const struct option *opt,
4925 const char *arg, int unset)
4927 struct apply_state *state = opt->value;
4929 BUG_ON_OPT_ARG(arg);
4931 if (unset)
4932 state->ws_ignore_action = ignore_ws_none;
4933 else
4934 state->ws_ignore_action = ignore_ws_change;
4935 return 0;
4938 static int apply_option_parse_whitespace(const struct option *opt,
4939 const char *arg, int unset)
4941 struct apply_state *state = opt->value;
4943 BUG_ON_OPT_NEG(unset);
4945 state->whitespace_option = arg;
4946 if (parse_whitespace_option(state, arg))
4947 return -1;
4948 return 0;
4951 static int apply_option_parse_directory(const struct option *opt,
4952 const char *arg, int unset)
4954 struct apply_state *state = opt->value;
4956 BUG_ON_OPT_NEG(unset);
4958 strbuf_reset(&state->root);
4959 strbuf_addstr(&state->root, arg);
4960 strbuf_complete(&state->root, '/');
4961 return 0;
4964 int apply_all_patches(struct apply_state *state,
4965 int argc,
4966 const char **argv,
4967 int options)
4969 int i;
4970 int res;
4971 int errs = 0;
4972 int read_stdin = 1;
4974 for (i = 0; i < argc; i++) {
4975 const char *arg = argv[i];
4976 char *to_free = NULL;
4977 int fd;
4979 if (!strcmp(arg, "-")) {
4980 res = apply_patch(state, 0, "<stdin>", options);
4981 if (res < 0)
4982 goto end;
4983 errs |= res;
4984 read_stdin = 0;
4985 continue;
4986 } else
4987 arg = to_free = prefix_filename(state->prefix, arg);
4989 fd = open(arg, O_RDONLY);
4990 if (fd < 0) {
4991 error(_("can't open patch '%s': %s"), arg, strerror(errno));
4992 res = -128;
4993 free(to_free);
4994 goto end;
4996 read_stdin = 0;
4997 set_default_whitespace_mode(state);
4998 res = apply_patch(state, fd, arg, options);
4999 close(fd);
5000 free(to_free);
5001 if (res < 0)
5002 goto end;
5003 errs |= res;
5005 set_default_whitespace_mode(state);
5006 if (read_stdin) {
5007 res = apply_patch(state, 0, "<stdin>", options);
5008 if (res < 0)
5009 goto end;
5010 errs |= res;
5013 if (state->whitespace_error) {
5014 if (state->squelch_whitespace_errors &&
5015 state->squelch_whitespace_errors < state->whitespace_error) {
5016 int squelched =
5017 state->whitespace_error - state->squelch_whitespace_errors;
5018 warning(Q_("squelched %d whitespace error",
5019 "squelched %d whitespace errors",
5020 squelched),
5021 squelched);
5023 if (state->ws_error_action == die_on_ws_error) {
5024 error(Q_("%d line adds whitespace errors.",
5025 "%d lines add whitespace errors.",
5026 state->whitespace_error),
5027 state->whitespace_error);
5028 res = -128;
5029 goto end;
5031 if (state->applied_after_fixing_ws && state->apply)
5032 warning(Q_("%d line applied after"
5033 " fixing whitespace errors.",
5034 "%d lines applied after"
5035 " fixing whitespace errors.",
5036 state->applied_after_fixing_ws),
5037 state->applied_after_fixing_ws);
5038 else if (state->whitespace_error)
5039 warning(Q_("%d line adds whitespace errors.",
5040 "%d lines add whitespace errors.",
5041 state->whitespace_error),
5042 state->whitespace_error);
5045 if (state->update_index) {
5046 res = write_locked_index(state->repo->index, &state->lock_file, COMMIT_LOCK);
5047 if (res) {
5048 error(_("Unable to write new index file"));
5049 res = -128;
5050 goto end;
5054 res = !!errs;
5056 end:
5057 rollback_lock_file(&state->lock_file);
5059 if (state->apply_verbosity <= verbosity_silent) {
5060 set_error_routine(state->saved_error_routine);
5061 set_warn_routine(state->saved_warn_routine);
5064 if (res > -1)
5065 return res;
5066 return (res == -1 ? 1 : 128);
5069 int apply_parse_options(int argc, const char **argv,
5070 struct apply_state *state,
5071 int *force_apply, int *options,
5072 const char * const *apply_usage)
5074 struct option builtin_apply_options[] = {
5075 OPT_CALLBACK_F(0, "exclude", state, N_("path"),
5076 N_("don't apply changes matching the given path"),
5077 PARSE_OPT_NONEG, apply_option_parse_exclude),
5078 OPT_CALLBACK_F(0, "include", state, N_("path"),
5079 N_("apply changes matching the given path"),
5080 PARSE_OPT_NONEG, apply_option_parse_include),
5081 OPT_CALLBACK('p', NULL, state, N_("num"),
5082 N_("remove <num> leading slashes from traditional diff paths"),
5083 apply_option_parse_p),
5084 OPT_BOOL(0, "no-add", &state->no_add,
5085 N_("ignore additions made by the patch")),
5086 OPT_BOOL(0, "stat", &state->diffstat,
5087 N_("instead of applying the patch, output diffstat for the input")),
5088 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
5089 OPT_NOOP_NOARG(0, "binary"),
5090 OPT_BOOL(0, "numstat", &state->numstat,
5091 N_("show number of added and deleted lines in decimal notation")),
5092 OPT_BOOL(0, "summary", &state->summary,
5093 N_("instead of applying the patch, output a summary for the input")),
5094 OPT_BOOL(0, "check", &state->check,
5095 N_("instead of applying the patch, see if the patch is applicable")),
5096 OPT_BOOL(0, "index", &state->check_index,
5097 N_("make sure the patch is applicable to the current index")),
5098 OPT_BOOL('N', "intent-to-add", &state->ita_only,
5099 N_("mark new files with `git add --intent-to-add`")),
5100 OPT_BOOL(0, "cached", &state->cached,
5101 N_("apply a patch without touching the working tree")),
5102 OPT_BOOL_F(0, "unsafe-paths", &state->unsafe_paths,
5103 N_("accept a patch that touches outside the working area"),
5104 PARSE_OPT_NOCOMPLETE),
5105 OPT_BOOL(0, "apply", force_apply,
5106 N_("also apply the patch (use with --stat/--summary/--check)")),
5107 OPT_BOOL('3', "3way", &state->threeway,
5108 N_( "attempt three-way merge, fall back on normal patch if that fails")),
5109 OPT_SET_INT_F(0, "ours", &state->merge_variant,
5110 N_("for conflicts, use our version"),
5111 XDL_MERGE_FAVOR_OURS, PARSE_OPT_NONEG),
5112 OPT_SET_INT_F(0, "theirs", &state->merge_variant,
5113 N_("for conflicts, use their version"),
5114 XDL_MERGE_FAVOR_THEIRS, PARSE_OPT_NONEG),
5115 OPT_SET_INT_F(0, "union", &state->merge_variant,
5116 N_("for conflicts, use a union version"),
5117 XDL_MERGE_FAVOR_UNION, PARSE_OPT_NONEG),
5118 OPT_FILENAME(0, "build-fake-ancestor", &state->fake_ancestor,
5119 N_("build a temporary index based on embedded index information")),
5120 /* Think twice before adding "--nul" synonym to this */
5121 OPT_SET_INT('z', NULL, &state->line_termination,
5122 N_("paths are separated with NUL character"), '\0'),
5123 OPT_INTEGER('C', NULL, &state->p_context,
5124 N_("ensure at least <n> lines of context match")),
5125 OPT_CALLBACK(0, "whitespace", state, N_("action"),
5126 N_("detect new or modified lines that have whitespace errors"),
5127 apply_option_parse_whitespace),
5128 OPT_CALLBACK_F(0, "ignore-space-change", state, NULL,
5129 N_("ignore changes in whitespace when finding context"),
5130 PARSE_OPT_NOARG, apply_option_parse_space_change),
5131 OPT_CALLBACK_F(0, "ignore-whitespace", state, NULL,
5132 N_("ignore changes in whitespace when finding context"),
5133 PARSE_OPT_NOARG, apply_option_parse_space_change),
5134 OPT_BOOL('R', "reverse", &state->apply_in_reverse,
5135 N_("apply the patch in reverse")),
5136 OPT_BOOL(0, "unidiff-zero", &state->unidiff_zero,
5137 N_("don't expect at least one line of context")),
5138 OPT_BOOL(0, "reject", &state->apply_with_reject,
5139 N_("leave the rejected hunks in corresponding *.rej files")),
5140 OPT_BOOL(0, "allow-overlap", &state->allow_overlap,
5141 N_("allow overlapping hunks")),
5142 OPT__VERBOSITY(&state->apply_verbosity),
5143 OPT_BIT(0, "inaccurate-eof", options,
5144 N_("tolerate incorrectly detected missing new-line at the end of file"),
5145 APPLY_OPT_INACCURATE_EOF),
5146 OPT_BIT(0, "recount", options,
5147 N_("do not trust the line counts in the hunk headers"),
5148 APPLY_OPT_RECOUNT),
5149 OPT_CALLBACK(0, "directory", state, N_("root"),
5150 N_("prepend <root> to all filenames"),
5151 apply_option_parse_directory),
5152 OPT_BOOL(0, "allow-empty", &state->allow_empty,
5153 N_("don't return error for empty patches")),
5154 OPT_END()
5157 argc = parse_options(argc, argv, state->prefix, builtin_apply_options, apply_usage, 0);
5159 if (state->merge_variant && !state->threeway)
5160 die(_("--ours, --theirs, and --union require --3way"));
5162 return argc;