shallow: fix leak when unregistering last shallow root
[alt-git.git] / apply.c
blob7b92387f4393dec4d5fd54c774030bdfac375bb3
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
12 #include "git-compat-util.h"
13 #include "abspath.h"
14 #include "base85.h"
15 #include "config.h"
16 #include "object-store-ll.h"
17 #include "delta.h"
18 #include "diff.h"
19 #include "dir.h"
20 #include "environment.h"
21 #include "gettext.h"
22 #include "hex.h"
23 #include "xdiff-interface.h"
24 #include "merge-ll.h"
25 #include "lockfile.h"
26 #include "name-hash.h"
27 #include "object-name.h"
28 #include "object-file.h"
29 #include "parse-options.h"
30 #include "path.h"
31 #include "quote.h"
32 #include "read-cache.h"
33 #include "repository.h"
34 #include "rerere.h"
35 #include "apply.h"
36 #include "entry.h"
37 #include "setup.h"
38 #include "symlinks.h"
39 #include "wildmatch.h"
40 #include "ws.h"
42 struct gitdiff_data {
43 struct strbuf *root;
44 int linenr;
45 int p_value;
48 static void git_apply_config(void)
50 git_config_get_string("apply.whitespace", &apply_default_whitespace);
51 git_config_get_string("apply.ignorewhitespace", &apply_default_ignorewhitespace);
52 git_config(git_xmerge_config, NULL);
55 static int parse_whitespace_option(struct apply_state *state, const char *option)
57 if (!option) {
58 state->ws_error_action = warn_on_ws_error;
59 return 0;
61 if (!strcmp(option, "warn")) {
62 state->ws_error_action = warn_on_ws_error;
63 return 0;
65 if (!strcmp(option, "nowarn")) {
66 state->ws_error_action = nowarn_ws_error;
67 return 0;
69 if (!strcmp(option, "error")) {
70 state->ws_error_action = die_on_ws_error;
71 return 0;
73 if (!strcmp(option, "error-all")) {
74 state->ws_error_action = die_on_ws_error;
75 state->squelch_whitespace_errors = 0;
76 return 0;
78 if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
79 state->ws_error_action = correct_ws_error;
80 return 0;
83 * Please update $__git_whitespacelist in git-completion.bash,
84 * Documentation/git-apply.txt, and Documentation/git-am.txt
85 * when you add new options.
87 return error(_("unrecognized whitespace option '%s'"), option);
90 static int parse_ignorewhitespace_option(struct apply_state *state,
91 const char *option)
93 if (!option || !strcmp(option, "no") ||
94 !strcmp(option, "false") || !strcmp(option, "never") ||
95 !strcmp(option, "none")) {
96 state->ws_ignore_action = ignore_ws_none;
97 return 0;
99 if (!strcmp(option, "change")) {
100 state->ws_ignore_action = ignore_ws_change;
101 return 0;
103 return error(_("unrecognized whitespace ignore option '%s'"), option);
106 int init_apply_state(struct apply_state *state,
107 struct repository *repo,
108 const char *prefix)
110 memset(state, 0, sizeof(*state));
111 state->prefix = prefix;
112 state->repo = repo;
113 state->apply = 1;
114 state->line_termination = '\n';
115 state->p_value = 1;
116 state->p_context = UINT_MAX;
117 state->squelch_whitespace_errors = 5;
118 state->ws_error_action = warn_on_ws_error;
119 state->ws_ignore_action = ignore_ws_none;
120 state->linenr = 1;
121 string_list_init_nodup(&state->fn_table);
122 string_list_init_nodup(&state->limit_by_name);
123 strset_init(&state->removed_symlinks);
124 strset_init(&state->kept_symlinks);
125 strbuf_init(&state->root, 0);
127 git_apply_config();
128 if (apply_default_whitespace && parse_whitespace_option(state, apply_default_whitespace))
129 return -1;
130 if (apply_default_ignorewhitespace && parse_ignorewhitespace_option(state, apply_default_ignorewhitespace))
131 return -1;
132 return 0;
135 void clear_apply_state(struct apply_state *state)
137 string_list_clear(&state->limit_by_name, 0);
138 strset_clear(&state->removed_symlinks);
139 strset_clear(&state->kept_symlinks);
140 strbuf_release(&state->root);
141 FREE_AND_NULL(state->fake_ancestor);
143 /* &state->fn_table is cleared at the end of apply_patch() */
146 static void mute_routine(const char *msg UNUSED, va_list params UNUSED)
148 /* do nothing */
151 int check_apply_state(struct apply_state *state, int force_apply)
153 int is_not_gitdir = !startup_info->have_repository;
155 if (state->apply_with_reject && state->threeway)
156 return error(_("options '%s' and '%s' cannot be used together"), "--reject", "--3way");
157 if (state->threeway) {
158 if (is_not_gitdir)
159 return error(_("'%s' outside a repository"), "--3way");
160 state->check_index = 1;
162 if (state->apply_with_reject) {
163 state->apply = 1;
164 if (state->apply_verbosity == verbosity_normal)
165 state->apply_verbosity = verbosity_verbose;
167 if (!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor))
168 state->apply = 0;
169 if (state->check_index && is_not_gitdir)
170 return error(_("'%s' outside a repository"), "--index");
171 if (state->cached) {
172 if (is_not_gitdir)
173 return error(_("'%s' outside a repository"), "--cached");
174 state->check_index = 1;
176 if (state->ita_only && (state->check_index || is_not_gitdir))
177 state->ita_only = 0;
178 if (state->check_index)
179 state->unsafe_paths = 0;
181 if (state->apply_verbosity <= verbosity_silent) {
182 state->saved_error_routine = get_error_routine();
183 state->saved_warn_routine = get_warn_routine();
184 set_error_routine(mute_routine);
185 set_warn_routine(mute_routine);
188 return 0;
191 static void set_default_whitespace_mode(struct apply_state *state)
193 if (!state->whitespace_option && !apply_default_whitespace)
194 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error);
198 * This represents one "hunk" from a patch, starting with
199 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
200 * patch text is pointed at by patch, and its byte length
201 * is stored in size. leading and trailing are the number
202 * of context lines.
204 struct fragment {
205 unsigned long leading, trailing;
206 unsigned long oldpos, oldlines;
207 unsigned long newpos, newlines;
209 * 'patch' is usually borrowed from buf in apply_patch(),
210 * but some codepaths store an allocated buffer.
212 const char *patch;
213 unsigned free_patch:1,
214 rejected:1;
215 int size;
216 int linenr;
217 struct fragment *next;
221 * When dealing with a binary patch, we reuse "leading" field
222 * to store the type of the binary hunk, either deflated "delta"
223 * or deflated "literal".
225 #define binary_patch_method leading
226 #define BINARY_DELTA_DEFLATED 1
227 #define BINARY_LITERAL_DEFLATED 2
229 static void free_fragment_list(struct fragment *list)
231 while (list) {
232 struct fragment *next = list->next;
233 if (list->free_patch)
234 free((char *)list->patch);
235 free(list);
236 list = next;
240 void release_patch(struct patch *patch)
242 free_fragment_list(patch->fragments);
243 free(patch->def_name);
244 free(patch->old_name);
245 free(patch->new_name);
246 free(patch->result);
249 static void free_patch(struct patch *patch)
251 release_patch(patch);
252 free(patch);
255 static void free_patch_list(struct patch *list)
257 while (list) {
258 struct patch *next = list->next;
259 free_patch(list);
260 list = next;
265 * A line in a file, len-bytes long (includes the terminating LF,
266 * except for an incomplete line at the end if the file ends with
267 * one), and its contents hashes to 'hash'.
269 struct line {
270 size_t len;
271 unsigned hash : 24;
272 unsigned flag : 8;
273 #define LINE_COMMON 1
274 #define LINE_PATCHED 2
278 * This represents a "file", which is an array of "lines".
280 struct image {
281 char *buf;
282 size_t len;
283 size_t nr;
284 size_t alloc;
285 struct line *line_allocated;
286 struct line *line;
289 static uint32_t hash_line(const char *cp, size_t len)
291 size_t i;
292 uint32_t h;
293 for (i = 0, h = 0; i < len; i++) {
294 if (!isspace(cp[i])) {
295 h = h * 3 + (cp[i] & 0xff);
298 return h;
302 * Compare lines s1 of length n1 and s2 of length n2, ignoring
303 * whitespace difference. Returns 1 if they match, 0 otherwise
305 static int fuzzy_matchlines(const char *s1, size_t n1,
306 const char *s2, size_t n2)
308 const char *end1 = s1 + n1;
309 const char *end2 = s2 + n2;
311 /* ignore line endings */
312 while (s1 < end1 && (end1[-1] == '\r' || end1[-1] == '\n'))
313 end1--;
314 while (s2 < end2 && (end2[-1] == '\r' || end2[-1] == '\n'))
315 end2--;
317 while (s1 < end1 && s2 < end2) {
318 if (isspace(*s1)) {
320 * Skip whitespace. We check on both buffers
321 * because we don't want "a b" to match "ab".
323 if (!isspace(*s2))
324 return 0;
325 while (s1 < end1 && isspace(*s1))
326 s1++;
327 while (s2 < end2 && isspace(*s2))
328 s2++;
329 } else if (*s1++ != *s2++)
330 return 0;
333 /* If we reached the end on one side only, lines don't match. */
334 return s1 == end1 && s2 == end2;
337 static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
339 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
340 img->line_allocated[img->nr].len = len;
341 img->line_allocated[img->nr].hash = hash_line(bol, len);
342 img->line_allocated[img->nr].flag = flag;
343 img->nr++;
347 * "buf" has the file contents to be patched (read from various sources).
348 * attach it to "image" and add line-based index to it.
349 * "image" now owns the "buf".
351 static void prepare_image(struct image *image, char *buf, size_t len,
352 int prepare_linetable)
354 const char *cp, *ep;
356 memset(image, 0, sizeof(*image));
357 image->buf = buf;
358 image->len = len;
360 if (!prepare_linetable)
361 return;
363 ep = image->buf + image->len;
364 cp = image->buf;
365 while (cp < ep) {
366 const char *next;
367 for (next = cp; next < ep && *next != '\n'; next++)
369 if (next < ep)
370 next++;
371 add_line_info(image, cp, next - cp, 0);
372 cp = next;
374 image->line = image->line_allocated;
377 static void clear_image(struct image *image)
379 free(image->buf);
380 free(image->line_allocated);
381 memset(image, 0, sizeof(*image));
384 /* fmt must contain _one_ %s and no other substitution */
385 static void say_patch_name(FILE *output, const char *fmt, struct patch *patch)
387 struct strbuf sb = STRBUF_INIT;
389 if (patch->old_name && patch->new_name &&
390 strcmp(patch->old_name, patch->new_name)) {
391 quote_c_style(patch->old_name, &sb, NULL, 0);
392 strbuf_addstr(&sb, " => ");
393 quote_c_style(patch->new_name, &sb, NULL, 0);
394 } else {
395 const char *n = patch->new_name;
396 if (!n)
397 n = patch->old_name;
398 quote_c_style(n, &sb, NULL, 0);
400 fprintf(output, fmt, sb.buf);
401 fputc('\n', output);
402 strbuf_release(&sb);
405 #define SLOP (16)
408 * apply.c isn't equipped to handle arbitrarily large patches, because
409 * it intermingles `unsigned long` with `int` for the type used to store
410 * buffer lengths.
412 * Only process patches that are just shy of 1 GiB large in order to
413 * avoid any truncation or overflow issues.
415 #define MAX_APPLY_SIZE (1024UL * 1024 * 1023)
417 static int read_patch_file(struct strbuf *sb, int fd)
419 if (strbuf_read(sb, fd, 0) < 0)
420 return error_errno(_("failed to read patch"));
421 else if (sb->len >= MAX_APPLY_SIZE)
422 return error(_("patch too large"));
424 * Make sure that we have some slop in the buffer
425 * so that we can do speculative "memcmp" etc, and
426 * see to it that it is NUL-filled.
428 strbuf_grow(sb, SLOP);
429 memset(sb->buf + sb->len, 0, SLOP);
430 return 0;
433 static unsigned long linelen(const char *buffer, unsigned long size)
435 unsigned long len = 0;
436 while (size--) {
437 len++;
438 if (*buffer++ == '\n')
439 break;
441 return len;
444 static int is_dev_null(const char *str)
446 return skip_prefix(str, "/dev/null", &str) && isspace(*str);
449 #define TERM_SPACE 1
450 #define TERM_TAB 2
452 static int name_terminate(int c, int terminate)
454 if (c == ' ' && !(terminate & TERM_SPACE))
455 return 0;
456 if (c == '\t' && !(terminate & TERM_TAB))
457 return 0;
459 return 1;
462 /* remove double slashes to make --index work with such filenames */
463 static char *squash_slash(char *name)
465 int i = 0, j = 0;
467 if (!name)
468 return NULL;
470 while (name[i]) {
471 if ((name[j++] = name[i++]) == '/')
472 while (name[i] == '/')
473 i++;
475 name[j] = '\0';
476 return name;
479 static char *find_name_gnu(struct strbuf *root,
480 const char *line,
481 int p_value)
483 struct strbuf name = STRBUF_INIT;
484 char *cp;
487 * Proposed "new-style" GNU patch/diff format; see
488 * https://lore.kernel.org/git/7vll0wvb2a.fsf@assigned-by-dhcp.cox.net/
490 if (unquote_c_style(&name, line, NULL)) {
491 strbuf_release(&name);
492 return NULL;
495 for (cp = name.buf; p_value; p_value--) {
496 cp = strchr(cp, '/');
497 if (!cp) {
498 strbuf_release(&name);
499 return NULL;
501 cp++;
504 strbuf_remove(&name, 0, cp - name.buf);
505 if (root->len)
506 strbuf_insert(&name, 0, root->buf, root->len);
507 return squash_slash(strbuf_detach(&name, NULL));
510 static size_t sane_tz_len(const char *line, size_t len)
512 const char *tz, *p;
514 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
515 return 0;
516 tz = line + len - strlen(" +0500");
518 if (tz[1] != '+' && tz[1] != '-')
519 return 0;
521 for (p = tz + 2; p != line + len; p++)
522 if (!isdigit(*p))
523 return 0;
525 return line + len - tz;
528 static size_t tz_with_colon_len(const char *line, size_t len)
530 const char *tz, *p;
532 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
533 return 0;
534 tz = line + len - strlen(" +08:00");
536 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
537 return 0;
538 p = tz + 2;
539 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
540 !isdigit(*p++) || !isdigit(*p++))
541 return 0;
543 return line + len - tz;
546 static size_t date_len(const char *line, size_t len)
548 const char *date, *p;
550 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
551 return 0;
552 p = date = line + len - strlen("72-02-05");
554 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
555 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
556 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */
557 return 0;
559 if (date - line >= strlen("19") &&
560 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */
561 date -= strlen("19");
563 return line + len - date;
566 static size_t short_time_len(const char *line, size_t len)
568 const char *time, *p;
570 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
571 return 0;
572 p = time = line + len - strlen(" 07:01:32");
574 /* Permit 1-digit hours? */
575 if (*p++ != ' ' ||
576 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
577 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
578 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */
579 return 0;
581 return line + len - time;
584 static size_t fractional_time_len(const char *line, size_t len)
586 const char *p;
587 size_t n;
589 /* Expected format: 19:41:17.620000023 */
590 if (!len || !isdigit(line[len - 1]))
591 return 0;
592 p = line + len - 1;
594 /* Fractional seconds. */
595 while (p > line && isdigit(*p))
596 p--;
597 if (*p != '.')
598 return 0;
600 /* Hours, minutes, and whole seconds. */
601 n = short_time_len(line, p - line);
602 if (!n)
603 return 0;
605 return line + len - p + n;
608 static size_t trailing_spaces_len(const char *line, size_t len)
610 const char *p;
612 /* Expected format: ' ' x (1 or more) */
613 if (!len || line[len - 1] != ' ')
614 return 0;
616 p = line + len;
617 while (p != line) {
618 p--;
619 if (*p != ' ')
620 return line + len - (p + 1);
623 /* All spaces! */
624 return len;
627 static size_t diff_timestamp_len(const char *line, size_t len)
629 const char *end = line + len;
630 size_t n;
633 * Posix: 2010-07-05 19:41:17
634 * GNU: 2010-07-05 19:41:17.620000023 -0500
637 if (!isdigit(end[-1]))
638 return 0;
640 n = sane_tz_len(line, end - line);
641 if (!n)
642 n = tz_with_colon_len(line, end - line);
643 end -= n;
645 n = short_time_len(line, end - line);
646 if (!n)
647 n = fractional_time_len(line, end - line);
648 end -= n;
650 n = date_len(line, end - line);
651 if (!n) /* No date. Too bad. */
652 return 0;
653 end -= n;
655 if (end == line) /* No space before date. */
656 return 0;
657 if (end[-1] == '\t') { /* Success! */
658 end--;
659 return line + len - end;
661 if (end[-1] != ' ') /* No space before date. */
662 return 0;
664 /* Whitespace damage. */
665 end -= trailing_spaces_len(line, end - line);
666 return line + len - end;
669 static char *find_name_common(struct strbuf *root,
670 const char *line,
671 const char *def,
672 int p_value,
673 const char *end,
674 int terminate)
676 int len;
677 const char *start = NULL;
679 if (p_value == 0)
680 start = line;
681 while (line != end) {
682 char c = *line;
684 if (!end && isspace(c)) {
685 if (c == '\n')
686 break;
687 if (name_terminate(c, terminate))
688 break;
690 line++;
691 if (c == '/' && !--p_value)
692 start = line;
694 if (!start)
695 return squash_slash(xstrdup_or_null(def));
696 len = line - start;
697 if (!len)
698 return squash_slash(xstrdup_or_null(def));
701 * Generally we prefer the shorter name, especially
702 * if the other one is just a variation of that with
703 * something else tacked on to the end (ie "file.orig"
704 * or "file~").
706 if (def) {
707 int deflen = strlen(def);
708 if (deflen < len && !strncmp(start, def, deflen))
709 return squash_slash(xstrdup(def));
712 if (root->len) {
713 char *ret = xstrfmt("%s%.*s", root->buf, len, start);
714 return squash_slash(ret);
717 return squash_slash(xmemdupz(start, len));
720 static char *find_name(struct strbuf *root,
721 const char *line,
722 char *def,
723 int p_value,
724 int terminate)
726 if (*line == '"') {
727 char *name = find_name_gnu(root, line, p_value);
728 if (name)
729 return name;
732 return find_name_common(root, line, def, p_value, NULL, terminate);
735 static char *find_name_traditional(struct strbuf *root,
736 const char *line,
737 char *def,
738 int p_value)
740 size_t len;
741 size_t date_len;
743 if (*line == '"') {
744 char *name = find_name_gnu(root, line, p_value);
745 if (name)
746 return name;
749 len = strchrnul(line, '\n') - line;
750 date_len = diff_timestamp_len(line, len);
751 if (!date_len)
752 return find_name_common(root, line, def, p_value, NULL, TERM_TAB);
753 len -= date_len;
755 return find_name_common(root, line, def, p_value, line + len, 0);
759 * Given the string after "--- " or "+++ ", guess the appropriate
760 * p_value for the given patch.
762 static int guess_p_value(struct apply_state *state, const char *nameline)
764 char *name, *cp;
765 int val = -1;
767 if (is_dev_null(nameline))
768 return -1;
769 name = find_name_traditional(&state->root, nameline, NULL, 0);
770 if (!name)
771 return -1;
772 cp = strchr(name, '/');
773 if (!cp)
774 val = 0;
775 else if (state->prefix) {
777 * Does it begin with "a/$our-prefix" and such? Then this is
778 * very likely to apply to our directory.
780 if (starts_with(name, state->prefix))
781 val = count_slashes(state->prefix);
782 else {
783 cp++;
784 if (starts_with(cp, state->prefix))
785 val = count_slashes(state->prefix) + 1;
788 free(name);
789 return val;
793 * Does the ---/+++ line have the POSIX timestamp after the last HT?
794 * GNU diff puts epoch there to signal a creation/deletion event. Is
795 * this such a timestamp?
797 static int has_epoch_timestamp(const char *nameline)
800 * We are only interested in epoch timestamp; any non-zero
801 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
802 * For the same reason, the date must be either 1969-12-31 or
803 * 1970-01-01, and the seconds part must be "00".
805 const char stamp_regexp[] =
806 "^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?"
808 "([-+][0-2][0-9]:?[0-5][0-9])\n";
809 const char *timestamp = NULL, *cp, *colon;
810 static regex_t *stamp;
811 regmatch_t m[10];
812 int zoneoffset, epoch_hour, hour, minute;
813 int status;
815 for (cp = nameline; *cp != '\n'; cp++) {
816 if (*cp == '\t')
817 timestamp = cp + 1;
819 if (!timestamp)
820 return 0;
823 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
824 * (west of GMT) or 1970-01-01 (east of GMT)
826 if (skip_prefix(timestamp, "1969-12-31 ", &timestamp))
827 epoch_hour = 24;
828 else if (skip_prefix(timestamp, "1970-01-01 ", &timestamp))
829 epoch_hour = 0;
830 else
831 return 0;
833 if (!stamp) {
834 stamp = xmalloc(sizeof(*stamp));
835 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
836 warning(_("Cannot prepare timestamp regexp %s"),
837 stamp_regexp);
838 return 0;
842 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
843 if (status) {
844 if (status != REG_NOMATCH)
845 warning(_("regexec returned %d for input: %s"),
846 status, timestamp);
847 return 0;
850 hour = strtol(timestamp, NULL, 10);
851 minute = strtol(timestamp + m[1].rm_so, NULL, 10);
853 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
854 if (*colon == ':')
855 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
856 else
857 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
858 if (timestamp[m[3].rm_so] == '-')
859 zoneoffset = -zoneoffset;
861 return hour * 60 + minute - zoneoffset == epoch_hour * 60;
865 * Get the name etc info from the ---/+++ lines of a traditional patch header
867 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
868 * files, we can happily check the index for a match, but for creating a
869 * new file we should try to match whatever "patch" does. I have no idea.
871 static int parse_traditional_patch(struct apply_state *state,
872 const char *first,
873 const char *second,
874 struct patch *patch)
876 char *name;
878 first += 4; /* skip "--- " */
879 second += 4; /* skip "+++ " */
880 if (!state->p_value_known) {
881 int p, q;
882 p = guess_p_value(state, first);
883 q = guess_p_value(state, second);
884 if (p < 0) p = q;
885 if (0 <= p && p == q) {
886 state->p_value = p;
887 state->p_value_known = 1;
890 if (is_dev_null(first)) {
891 patch->is_new = 1;
892 patch->is_delete = 0;
893 name = find_name_traditional(&state->root, second, NULL, state->p_value);
894 patch->new_name = name;
895 } else if (is_dev_null(second)) {
896 patch->is_new = 0;
897 patch->is_delete = 1;
898 name = find_name_traditional(&state->root, first, NULL, state->p_value);
899 patch->old_name = name;
900 } else {
901 char *first_name;
902 first_name = find_name_traditional(&state->root, first, NULL, state->p_value);
903 name = find_name_traditional(&state->root, second, first_name, state->p_value);
904 free(first_name);
905 if (has_epoch_timestamp(first)) {
906 patch->is_new = 1;
907 patch->is_delete = 0;
908 patch->new_name = name;
909 } else if (has_epoch_timestamp(second)) {
910 patch->is_new = 0;
911 patch->is_delete = 1;
912 patch->old_name = name;
913 } else {
914 patch->old_name = name;
915 patch->new_name = xstrdup_or_null(name);
918 if (!name)
919 return error(_("unable to find filename in patch at line %d"), state->linenr);
921 return 0;
924 static int gitdiff_hdrend(struct gitdiff_data *state UNUSED,
925 const char *line UNUSED,
926 struct patch *patch UNUSED)
928 return 1;
932 * We're anal about diff header consistency, to make
933 * sure that we don't end up having strange ambiguous
934 * patches floating around.
936 * As a result, gitdiff_{old|new}name() will check
937 * their names against any previous information, just
938 * to make sure..
940 #define DIFF_OLD_NAME 0
941 #define DIFF_NEW_NAME 1
943 static int gitdiff_verify_name(struct gitdiff_data *state,
944 const char *line,
945 int isnull,
946 char **name,
947 int side)
949 if (!*name && !isnull) {
950 *name = find_name(state->root, line, NULL, state->p_value, TERM_TAB);
951 return 0;
954 if (*name) {
955 char *another;
956 if (isnull)
957 return error(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
958 *name, state->linenr);
959 another = find_name(state->root, line, NULL, state->p_value, TERM_TAB);
960 if (!another || strcmp(another, *name)) {
961 free(another);
962 return error((side == DIFF_NEW_NAME) ?
963 _("git apply: bad git-diff - inconsistent new filename on line %d") :
964 _("git apply: bad git-diff - inconsistent old filename on line %d"), state->linenr);
966 free(another);
967 } else {
968 if (!is_dev_null(line))
969 return error(_("git apply: bad git-diff - expected /dev/null on line %d"), state->linenr);
972 return 0;
975 static int gitdiff_oldname(struct gitdiff_data *state,
976 const char *line,
977 struct patch *patch)
979 return gitdiff_verify_name(state, line,
980 patch->is_new, &patch->old_name,
981 DIFF_OLD_NAME);
984 static int gitdiff_newname(struct gitdiff_data *state,
985 const char *line,
986 struct patch *patch)
988 return gitdiff_verify_name(state, line,
989 patch->is_delete, &patch->new_name,
990 DIFF_NEW_NAME);
993 static int parse_mode_line(const char *line, int linenr, unsigned int *mode)
995 char *end;
996 *mode = strtoul(line, &end, 8);
997 if (end == line || !isspace(*end))
998 return error(_("invalid mode on line %d: %s"), linenr, line);
999 *mode = canon_mode(*mode);
1000 return 0;
1003 static int gitdiff_oldmode(struct gitdiff_data *state,
1004 const char *line,
1005 struct patch *patch)
1007 return parse_mode_line(line, state->linenr, &patch->old_mode);
1010 static int gitdiff_newmode(struct gitdiff_data *state,
1011 const char *line,
1012 struct patch *patch)
1014 return parse_mode_line(line, state->linenr, &patch->new_mode);
1017 static int gitdiff_delete(struct gitdiff_data *state,
1018 const char *line,
1019 struct patch *patch)
1021 patch->is_delete = 1;
1022 free(patch->old_name);
1023 patch->old_name = xstrdup_or_null(patch->def_name);
1024 return gitdiff_oldmode(state, line, patch);
1027 static int gitdiff_newfile(struct gitdiff_data *state,
1028 const char *line,
1029 struct patch *patch)
1031 patch->is_new = 1;
1032 free(patch->new_name);
1033 patch->new_name = xstrdup_or_null(patch->def_name);
1034 return gitdiff_newmode(state, line, patch);
1037 static int gitdiff_copysrc(struct gitdiff_data *state,
1038 const char *line,
1039 struct patch *patch)
1041 patch->is_copy = 1;
1042 free(patch->old_name);
1043 patch->old_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1044 return 0;
1047 static int gitdiff_copydst(struct gitdiff_data *state,
1048 const char *line,
1049 struct patch *patch)
1051 patch->is_copy = 1;
1052 free(patch->new_name);
1053 patch->new_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1054 return 0;
1057 static int gitdiff_renamesrc(struct gitdiff_data *state,
1058 const char *line,
1059 struct patch *patch)
1061 patch->is_rename = 1;
1062 free(patch->old_name);
1063 patch->old_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1064 return 0;
1067 static int gitdiff_renamedst(struct gitdiff_data *state,
1068 const char *line,
1069 struct patch *patch)
1071 patch->is_rename = 1;
1072 free(patch->new_name);
1073 patch->new_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1074 return 0;
1077 static int gitdiff_similarity(struct gitdiff_data *state UNUSED,
1078 const char *line,
1079 struct patch *patch)
1081 unsigned long val = strtoul(line, NULL, 10);
1082 if (val <= 100)
1083 patch->score = val;
1084 return 0;
1087 static int gitdiff_dissimilarity(struct gitdiff_data *state UNUSED,
1088 const char *line,
1089 struct patch *patch)
1091 unsigned long val = strtoul(line, NULL, 10);
1092 if (val <= 100)
1093 patch->score = val;
1094 return 0;
1097 static int gitdiff_index(struct gitdiff_data *state,
1098 const char *line,
1099 struct patch *patch)
1102 * index line is N hexadecimal, "..", N hexadecimal,
1103 * and optional space with octal mode.
1105 const char *ptr, *eol;
1106 int len;
1107 const unsigned hexsz = the_hash_algo->hexsz;
1109 ptr = strchr(line, '.');
1110 if (!ptr || ptr[1] != '.' || hexsz < ptr - line)
1111 return 0;
1112 len = ptr - line;
1113 memcpy(patch->old_oid_prefix, line, len);
1114 patch->old_oid_prefix[len] = 0;
1116 line = ptr + 2;
1117 ptr = strchr(line, ' ');
1118 eol = strchrnul(line, '\n');
1120 if (!ptr || eol < ptr)
1121 ptr = eol;
1122 len = ptr - line;
1124 if (hexsz < len)
1125 return 0;
1126 memcpy(patch->new_oid_prefix, line, len);
1127 patch->new_oid_prefix[len] = 0;
1128 if (*ptr == ' ')
1129 return gitdiff_oldmode(state, ptr + 1, patch);
1130 return 0;
1134 * This is normal for a diff that doesn't change anything: we'll fall through
1135 * into the next diff. Tell the parser to break out.
1137 static int gitdiff_unrecognized(struct gitdiff_data *state UNUSED,
1138 const char *line UNUSED,
1139 struct patch *patch UNUSED)
1141 return 1;
1145 * Skip p_value leading components from "line"; as we do not accept
1146 * absolute paths, return NULL in that case.
1148 static const char *skip_tree_prefix(int p_value,
1149 const char *line,
1150 int llen)
1152 int nslash;
1153 int i;
1155 if (!p_value)
1156 return (llen && line[0] == '/') ? NULL : line;
1158 nslash = p_value;
1159 for (i = 0; i < llen; i++) {
1160 int ch = line[i];
1161 if (ch == '/' && --nslash <= 0)
1162 return (i == 0) ? NULL : &line[i + 1];
1164 return NULL;
1168 * This is to extract the same name that appears on "diff --git"
1169 * line. We do not find and return anything if it is a rename
1170 * patch, and it is OK because we will find the name elsewhere.
1171 * We need to reliably find name only when it is mode-change only,
1172 * creation or deletion of an empty file. In any of these cases,
1173 * both sides are the same name under a/ and b/ respectively.
1175 static char *git_header_name(int p_value,
1176 const char *line,
1177 int llen)
1179 const char *name;
1180 const char *second = NULL;
1181 size_t len, line_len;
1183 line += strlen("diff --git ");
1184 llen -= strlen("diff --git ");
1186 if (*line == '"') {
1187 const char *cp;
1188 struct strbuf first = STRBUF_INIT;
1189 struct strbuf sp = STRBUF_INIT;
1191 if (unquote_c_style(&first, line, &second))
1192 goto free_and_fail1;
1194 /* strip the a/b prefix including trailing slash */
1195 cp = skip_tree_prefix(p_value, first.buf, first.len);
1196 if (!cp)
1197 goto free_and_fail1;
1198 strbuf_remove(&first, 0, cp - first.buf);
1201 * second points at one past closing dq of name.
1202 * find the second name.
1204 while ((second < line + llen) && isspace(*second))
1205 second++;
1207 if (line + llen <= second)
1208 goto free_and_fail1;
1209 if (*second == '"') {
1210 if (unquote_c_style(&sp, second, NULL))
1211 goto free_and_fail1;
1212 cp = skip_tree_prefix(p_value, sp.buf, sp.len);
1213 if (!cp)
1214 goto free_and_fail1;
1215 /* They must match, otherwise ignore */
1216 if (strcmp(cp, first.buf))
1217 goto free_and_fail1;
1218 strbuf_release(&sp);
1219 return strbuf_detach(&first, NULL);
1222 /* unquoted second */
1223 cp = skip_tree_prefix(p_value, second, line + llen - second);
1224 if (!cp)
1225 goto free_and_fail1;
1226 if (line + llen - cp != first.len ||
1227 memcmp(first.buf, cp, first.len))
1228 goto free_and_fail1;
1229 return strbuf_detach(&first, NULL);
1231 free_and_fail1:
1232 strbuf_release(&first);
1233 strbuf_release(&sp);
1234 return NULL;
1237 /* unquoted first name */
1238 name = skip_tree_prefix(p_value, line, llen);
1239 if (!name)
1240 return NULL;
1243 * since the first name is unquoted, a dq if exists must be
1244 * the beginning of the second name.
1246 for (second = name; second < line + llen; second++) {
1247 if (*second == '"') {
1248 struct strbuf sp = STRBUF_INIT;
1249 const char *np;
1251 if (unquote_c_style(&sp, second, NULL))
1252 goto free_and_fail2;
1254 np = skip_tree_prefix(p_value, sp.buf, sp.len);
1255 if (!np)
1256 goto free_and_fail2;
1258 len = sp.buf + sp.len - np;
1259 if (len < second - name &&
1260 !strncmp(np, name, len) &&
1261 isspace(name[len])) {
1262 /* Good */
1263 strbuf_remove(&sp, 0, np - sp.buf);
1264 return strbuf_detach(&sp, NULL);
1267 free_and_fail2:
1268 strbuf_release(&sp);
1269 return NULL;
1274 * Accept a name only if it shows up twice, exactly the same
1275 * form.
1277 second = strchr(name, '\n');
1278 if (!second)
1279 return NULL;
1280 line_len = second - name;
1281 for (len = 0 ; ; len++) {
1282 switch (name[len]) {
1283 default:
1284 continue;
1285 case '\n':
1286 return NULL;
1287 case '\t': case ' ':
1289 * Is this the separator between the preimage
1290 * and the postimage pathname? Again, we are
1291 * only interested in the case where there is
1292 * no rename, as this is only to set def_name
1293 * and a rename patch has the names elsewhere
1294 * in an unambiguous form.
1296 if (!name[len + 1])
1297 return NULL; /* no postimage name */
1298 second = skip_tree_prefix(p_value, name + len + 1,
1299 line_len - (len + 1));
1301 * If we are at the SP at the end of a directory,
1302 * skip_tree_prefix() may return NULL as that makes
1303 * it appears as if we have an absolute path.
1304 * Keep going to find another SP.
1306 if (!second)
1307 continue;
1310 * Does len bytes starting at "name" and "second"
1311 * (that are separated by one HT or SP we just
1312 * found) exactly match?
1314 if (second[len] == '\n' && !strncmp(name, second, len))
1315 return xmemdupz(name, len);
1320 static int check_header_line(int linenr, struct patch *patch)
1322 int extensions = (patch->is_delete == 1) + (patch->is_new == 1) +
1323 (patch->is_rename == 1) + (patch->is_copy == 1);
1324 if (extensions > 1)
1325 return error(_("inconsistent header lines %d and %d"),
1326 patch->extension_linenr, linenr);
1327 if (extensions && !patch->extension_linenr)
1328 patch->extension_linenr = linenr;
1329 return 0;
1332 int parse_git_diff_header(struct strbuf *root,
1333 int *linenr,
1334 int p_value,
1335 const char *line,
1336 int len,
1337 unsigned int size,
1338 struct patch *patch)
1340 unsigned long offset;
1341 struct gitdiff_data parse_hdr_state;
1343 /* A git diff has explicit new/delete information, so we don't guess */
1344 patch->is_new = 0;
1345 patch->is_delete = 0;
1348 * Some things may not have the old name in the
1349 * rest of the headers anywhere (pure mode changes,
1350 * or removing or adding empty files), so we get
1351 * the default name from the header.
1353 patch->def_name = git_header_name(p_value, line, len);
1354 if (patch->def_name && root->len) {
1355 char *s = xstrfmt("%s%s", root->buf, patch->def_name);
1356 free(patch->def_name);
1357 patch->def_name = s;
1360 line += len;
1361 size -= len;
1362 (*linenr)++;
1363 parse_hdr_state.root = root;
1364 parse_hdr_state.linenr = *linenr;
1365 parse_hdr_state.p_value = p_value;
1367 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, (*linenr)++) {
1368 static const struct opentry {
1369 const char *str;
1370 int (*fn)(struct gitdiff_data *, const char *, struct patch *);
1371 } optable[] = {
1372 { "@@ -", gitdiff_hdrend },
1373 { "--- ", gitdiff_oldname },
1374 { "+++ ", gitdiff_newname },
1375 { "old mode ", gitdiff_oldmode },
1376 { "new mode ", gitdiff_newmode },
1377 { "deleted file mode ", gitdiff_delete },
1378 { "new file mode ", gitdiff_newfile },
1379 { "copy from ", gitdiff_copysrc },
1380 { "copy to ", gitdiff_copydst },
1381 { "rename old ", gitdiff_renamesrc },
1382 { "rename new ", gitdiff_renamedst },
1383 { "rename from ", gitdiff_renamesrc },
1384 { "rename to ", gitdiff_renamedst },
1385 { "similarity index ", gitdiff_similarity },
1386 { "dissimilarity index ", gitdiff_dissimilarity },
1387 { "index ", gitdiff_index },
1388 { "", gitdiff_unrecognized },
1390 int i;
1392 len = linelen(line, size);
1393 if (!len || line[len-1] != '\n')
1394 break;
1395 for (i = 0; i < ARRAY_SIZE(optable); i++) {
1396 const struct opentry *p = optable + i;
1397 int oplen = strlen(p->str);
1398 int res;
1399 if (len < oplen || memcmp(p->str, line, oplen))
1400 continue;
1401 res = p->fn(&parse_hdr_state, line + oplen, patch);
1402 if (res < 0)
1403 return -1;
1404 if (check_header_line(*linenr, patch))
1405 return -1;
1406 if (res > 0)
1407 goto done;
1408 break;
1412 done:
1413 if (!patch->old_name && !patch->new_name) {
1414 if (!patch->def_name) {
1415 error(Q_("git diff header lacks filename information when removing "
1416 "%d leading pathname component (line %d)",
1417 "git diff header lacks filename information when removing "
1418 "%d leading pathname components (line %d)",
1419 parse_hdr_state.p_value),
1420 parse_hdr_state.p_value, *linenr);
1421 return -128;
1423 patch->old_name = xstrdup(patch->def_name);
1424 patch->new_name = xstrdup(patch->def_name);
1426 if ((!patch->new_name && !patch->is_delete) ||
1427 (!patch->old_name && !patch->is_new)) {
1428 error(_("git diff header lacks filename information "
1429 "(line %d)"), *linenr);
1430 return -128;
1432 patch->is_toplevel_relative = 1;
1433 return offset;
1436 static int parse_num(const char *line, unsigned long *p)
1438 char *ptr;
1440 if (!isdigit(*line))
1441 return 0;
1442 *p = strtoul(line, &ptr, 10);
1443 return ptr - line;
1446 static int parse_range(const char *line, int len, int offset, const char *expect,
1447 unsigned long *p1, unsigned long *p2)
1449 int digits, ex;
1451 if (offset < 0 || offset >= len)
1452 return -1;
1453 line += offset;
1454 len -= offset;
1456 digits = parse_num(line, p1);
1457 if (!digits)
1458 return -1;
1460 offset += digits;
1461 line += digits;
1462 len -= digits;
1464 *p2 = 1;
1465 if (*line == ',') {
1466 digits = parse_num(line+1, p2);
1467 if (!digits)
1468 return -1;
1470 offset += digits+1;
1471 line += digits+1;
1472 len -= digits+1;
1475 ex = strlen(expect);
1476 if (ex > len)
1477 return -1;
1478 if (memcmp(line, expect, ex))
1479 return -1;
1481 return offset + ex;
1484 static void recount_diff(const char *line, int size, struct fragment *fragment)
1486 int oldlines = 0, newlines = 0, ret = 0;
1488 if (size < 1) {
1489 warning("recount: ignore empty hunk");
1490 return;
1493 for (;;) {
1494 int len = linelen(line, size);
1495 size -= len;
1496 line += len;
1498 if (size < 1)
1499 break;
1501 switch (*line) {
1502 case ' ': case '\n':
1503 newlines++;
1504 /* fall through */
1505 case '-':
1506 oldlines++;
1507 continue;
1508 case '+':
1509 newlines++;
1510 continue;
1511 case '\\':
1512 continue;
1513 case '@':
1514 ret = size < 3 || !starts_with(line, "@@ ");
1515 break;
1516 case 'd':
1517 ret = size < 5 || !starts_with(line, "diff ");
1518 break;
1519 default:
1520 ret = -1;
1521 break;
1523 if (ret) {
1524 warning(_("recount: unexpected line: %.*s"),
1525 (int)linelen(line, size), line);
1526 return;
1528 break;
1530 fragment->oldlines = oldlines;
1531 fragment->newlines = newlines;
1535 * Parse a unified diff fragment header of the
1536 * form "@@ -a,b +c,d @@"
1538 static int parse_fragment_header(const char *line, int len, struct fragment *fragment)
1540 int offset;
1542 if (!len || line[len-1] != '\n')
1543 return -1;
1545 /* Figure out the number of lines in a fragment */
1546 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1547 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1549 return offset;
1553 * Find file diff header
1555 * Returns:
1556 * -1 if no header was found
1557 * -128 in case of error
1558 * the size of the header in bytes (called "offset") otherwise
1560 static int find_header(struct apply_state *state,
1561 const char *line,
1562 unsigned long size,
1563 int *hdrsize,
1564 struct patch *patch)
1566 unsigned long offset, len;
1568 patch->is_toplevel_relative = 0;
1569 patch->is_rename = patch->is_copy = 0;
1570 patch->is_new = patch->is_delete = -1;
1571 patch->old_mode = patch->new_mode = 0;
1572 patch->old_name = patch->new_name = NULL;
1573 for (offset = 0; size > 0; offset += len, size -= len, line += len, state->linenr++) {
1574 unsigned long nextlen;
1576 len = linelen(line, size);
1577 if (!len)
1578 break;
1580 /* Testing this early allows us to take a few shortcuts.. */
1581 if (len < 6)
1582 continue;
1585 * Make sure we don't find any unconnected patch fragments.
1586 * That's a sign that we didn't find a header, and that a
1587 * patch has become corrupted/broken up.
1589 if (!memcmp("@@ -", line, 4)) {
1590 struct fragment dummy;
1591 if (parse_fragment_header(line, len, &dummy) < 0)
1592 continue;
1593 error(_("patch fragment without header at line %d: %.*s"),
1594 state->linenr, (int)len-1, line);
1595 return -128;
1598 if (size < len + 6)
1599 break;
1602 * Git patch? It might not have a real patch, just a rename
1603 * or mode change, so we handle that specially
1605 if (!memcmp("diff --git ", line, 11)) {
1606 int git_hdr_len = parse_git_diff_header(&state->root, &state->linenr,
1607 state->p_value, line, len,
1608 size, patch);
1609 if (git_hdr_len < 0)
1610 return -128;
1611 if (git_hdr_len <= len)
1612 continue;
1613 *hdrsize = git_hdr_len;
1614 return offset;
1617 /* --- followed by +++ ? */
1618 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1619 continue;
1622 * We only accept unified patches, so we want it to
1623 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1624 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1626 nextlen = linelen(line + len, size - len);
1627 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1628 continue;
1630 /* Ok, we'll consider it a patch */
1631 if (parse_traditional_patch(state, line, line+len, patch))
1632 return -128;
1633 *hdrsize = len + nextlen;
1634 state->linenr += 2;
1635 return offset;
1637 return -1;
1640 static void record_ws_error(struct apply_state *state,
1641 unsigned result,
1642 const char *line,
1643 int len,
1644 int linenr)
1646 char *err;
1648 if (!result)
1649 return;
1651 state->whitespace_error++;
1652 if (state->squelch_whitespace_errors &&
1653 state->squelch_whitespace_errors < state->whitespace_error)
1654 return;
1656 err = whitespace_error_string(result);
1657 if (state->apply_verbosity > verbosity_silent)
1658 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1659 state->patch_input_file, linenr, err, len, line);
1660 free(err);
1663 static void check_whitespace(struct apply_state *state,
1664 const char *line,
1665 int len,
1666 unsigned ws_rule)
1668 unsigned result = ws_check(line + 1, len - 1, ws_rule);
1670 record_ws_error(state, result, line + 1, len - 2, state->linenr);
1674 * Check if the patch has context lines with CRLF or
1675 * the patch wants to remove lines with CRLF.
1677 static void check_old_for_crlf(struct patch *patch, const char *line, int len)
1679 if (len >= 2 && line[len-1] == '\n' && line[len-2] == '\r') {
1680 patch->ws_rule |= WS_CR_AT_EOL;
1681 patch->crlf_in_old = 1;
1687 * Parse a unified diff. Note that this really needs to parse each
1688 * fragment separately, since the only way to know the difference
1689 * between a "---" that is part of a patch, and a "---" that starts
1690 * the next patch is to look at the line counts..
1692 static int parse_fragment(struct apply_state *state,
1693 const char *line,
1694 unsigned long size,
1695 struct patch *patch,
1696 struct fragment *fragment)
1698 int added, deleted;
1699 int len = linelen(line, size), offset;
1700 unsigned long oldlines, newlines;
1701 unsigned long leading, trailing;
1703 offset = parse_fragment_header(line, len, fragment);
1704 if (offset < 0)
1705 return -1;
1706 if (offset > 0 && patch->recount)
1707 recount_diff(line + offset, size - offset, fragment);
1708 oldlines = fragment->oldlines;
1709 newlines = fragment->newlines;
1710 leading = 0;
1711 trailing = 0;
1713 /* Parse the thing.. */
1714 line += len;
1715 size -= len;
1716 state->linenr++;
1717 added = deleted = 0;
1718 for (offset = len;
1719 0 < size;
1720 offset += len, size -= len, line += len, state->linenr++) {
1721 if (!oldlines && !newlines)
1722 break;
1723 len = linelen(line, size);
1724 if (!len || line[len-1] != '\n')
1725 return -1;
1726 switch (*line) {
1727 default:
1728 return -1;
1729 case '\n': /* newer GNU diff, an empty context line */
1730 case ' ':
1731 oldlines--;
1732 newlines--;
1733 if (!deleted && !added)
1734 leading++;
1735 trailing++;
1736 check_old_for_crlf(patch, line, len);
1737 if (!state->apply_in_reverse &&
1738 state->ws_error_action == correct_ws_error)
1739 check_whitespace(state, line, len, patch->ws_rule);
1740 break;
1741 case '-':
1742 if (!state->apply_in_reverse)
1743 check_old_for_crlf(patch, line, len);
1744 if (state->apply_in_reverse &&
1745 state->ws_error_action != nowarn_ws_error)
1746 check_whitespace(state, line, len, patch->ws_rule);
1747 deleted++;
1748 oldlines--;
1749 trailing = 0;
1750 break;
1751 case '+':
1752 if (state->apply_in_reverse)
1753 check_old_for_crlf(patch, line, len);
1754 if (!state->apply_in_reverse &&
1755 state->ws_error_action != nowarn_ws_error)
1756 check_whitespace(state, line, len, patch->ws_rule);
1757 added++;
1758 newlines--;
1759 trailing = 0;
1760 break;
1763 * We allow "\ No newline at end of file". Depending
1764 * on locale settings when the patch was produced we
1765 * don't know what this line looks like. The only
1766 * thing we do know is that it begins with "\ ".
1767 * Checking for 12 is just for sanity check -- any
1768 * l10n of "\ No newline..." is at least that long.
1770 case '\\':
1771 if (len < 12 || memcmp(line, "\\ ", 2))
1772 return -1;
1773 break;
1776 if (oldlines || newlines)
1777 return -1;
1778 if (!patch->recount && !deleted && !added)
1779 return -1;
1781 fragment->leading = leading;
1782 fragment->trailing = trailing;
1785 * If a fragment ends with an incomplete line, we failed to include
1786 * it in the above loop because we hit oldlines == newlines == 0
1787 * before seeing it.
1789 if (12 < size && !memcmp(line, "\\ ", 2))
1790 offset += linelen(line, size);
1792 patch->lines_added += added;
1793 patch->lines_deleted += deleted;
1795 if (0 < patch->is_new && oldlines)
1796 return error(_("new file depends on old contents"));
1797 if (0 < patch->is_delete && newlines)
1798 return error(_("deleted file still has contents"));
1799 return offset;
1803 * We have seen "diff --git a/... b/..." header (or a traditional patch
1804 * header). Read hunks that belong to this patch into fragments and hang
1805 * them to the given patch structure.
1807 * The (fragment->patch, fragment->size) pair points into the memory given
1808 * by the caller, not a copy, when we return.
1810 * Returns:
1811 * -1 in case of error,
1812 * the number of bytes in the patch otherwise.
1814 static int parse_single_patch(struct apply_state *state,
1815 const char *line,
1816 unsigned long size,
1817 struct patch *patch)
1819 unsigned long offset = 0;
1820 unsigned long oldlines = 0, newlines = 0, context = 0;
1821 struct fragment **fragp = &patch->fragments;
1823 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1824 struct fragment *fragment;
1825 int len;
1827 CALLOC_ARRAY(fragment, 1);
1828 fragment->linenr = state->linenr;
1829 len = parse_fragment(state, line, size, patch, fragment);
1830 if (len <= 0) {
1831 free(fragment);
1832 return error(_("corrupt patch at line %d"), state->linenr);
1834 fragment->patch = line;
1835 fragment->size = len;
1836 oldlines += fragment->oldlines;
1837 newlines += fragment->newlines;
1838 context += fragment->leading + fragment->trailing;
1840 *fragp = fragment;
1841 fragp = &fragment->next;
1843 offset += len;
1844 line += len;
1845 size -= len;
1849 * If something was removed (i.e. we have old-lines) it cannot
1850 * be creation, and if something was added it cannot be
1851 * deletion. However, the reverse is not true; --unified=0
1852 * patches that only add are not necessarily creation even
1853 * though they do not have any old lines, and ones that only
1854 * delete are not necessarily deletion.
1856 * Unfortunately, a real creation/deletion patch do _not_ have
1857 * any context line by definition, so we cannot safely tell it
1858 * apart with --unified=0 insanity. At least if the patch has
1859 * more than one hunk it is not creation or deletion.
1861 if (patch->is_new < 0 &&
1862 (oldlines || (patch->fragments && patch->fragments->next)))
1863 patch->is_new = 0;
1864 if (patch->is_delete < 0 &&
1865 (newlines || (patch->fragments && patch->fragments->next)))
1866 patch->is_delete = 0;
1868 if (0 < patch->is_new && oldlines)
1869 return error(_("new file %s depends on old contents"), patch->new_name);
1870 if (0 < patch->is_delete && newlines)
1871 return error(_("deleted file %s still has contents"), patch->old_name);
1872 if (!patch->is_delete && !newlines && context && state->apply_verbosity > verbosity_silent)
1873 fprintf_ln(stderr,
1874 _("** warning: "
1875 "file %s becomes empty but is not deleted"),
1876 patch->new_name);
1878 return offset;
1881 static inline int metadata_changes(struct patch *patch)
1883 return patch->is_rename > 0 ||
1884 patch->is_copy > 0 ||
1885 patch->is_new > 0 ||
1886 patch->is_delete ||
1887 (patch->old_mode && patch->new_mode &&
1888 patch->old_mode != patch->new_mode);
1891 static char *inflate_it(const void *data, unsigned long size,
1892 unsigned long inflated_size)
1894 git_zstream stream;
1895 void *out;
1896 int st;
1898 memset(&stream, 0, sizeof(stream));
1900 stream.next_in = (unsigned char *)data;
1901 stream.avail_in = size;
1902 stream.next_out = out = xmalloc(inflated_size);
1903 stream.avail_out = inflated_size;
1904 git_inflate_init(&stream);
1905 st = git_inflate(&stream, Z_FINISH);
1906 git_inflate_end(&stream);
1907 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1908 free(out);
1909 return NULL;
1911 return out;
1915 * Read a binary hunk and return a new fragment; fragment->patch
1916 * points at an allocated memory that the caller must free, so
1917 * it is marked as "->free_patch = 1".
1919 static struct fragment *parse_binary_hunk(struct apply_state *state,
1920 char **buf_p,
1921 unsigned long *sz_p,
1922 int *status_p,
1923 int *used_p)
1926 * Expect a line that begins with binary patch method ("literal"
1927 * or "delta"), followed by the length of data before deflating.
1928 * a sequence of 'length-byte' followed by base-85 encoded data
1929 * should follow, terminated by a newline.
1931 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1932 * and we would limit the patch line to 66 characters,
1933 * so one line can fit up to 13 groups that would decode
1934 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1935 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1937 int llen, used;
1938 unsigned long size = *sz_p;
1939 char *buffer = *buf_p;
1940 int patch_method;
1941 unsigned long origlen;
1942 char *data = NULL;
1943 int hunk_size = 0;
1944 struct fragment *frag;
1946 llen = linelen(buffer, size);
1947 used = llen;
1949 *status_p = 0;
1951 if (starts_with(buffer, "delta ")) {
1952 patch_method = BINARY_DELTA_DEFLATED;
1953 origlen = strtoul(buffer + 6, NULL, 10);
1955 else if (starts_with(buffer, "literal ")) {
1956 patch_method = BINARY_LITERAL_DEFLATED;
1957 origlen = strtoul(buffer + 8, NULL, 10);
1959 else
1960 return NULL;
1962 state->linenr++;
1963 buffer += llen;
1964 size -= llen;
1965 while (1) {
1966 int byte_length, max_byte_length, newsize;
1967 llen = linelen(buffer, size);
1968 used += llen;
1969 state->linenr++;
1970 if (llen == 1) {
1971 /* consume the blank line */
1972 buffer++;
1973 size--;
1974 break;
1977 * Minimum line is "A00000\n" which is 7-byte long,
1978 * and the line length must be multiple of 5 plus 2.
1980 if ((llen < 7) || (llen-2) % 5)
1981 goto corrupt;
1982 max_byte_length = (llen - 2) / 5 * 4;
1983 byte_length = *buffer;
1984 if ('A' <= byte_length && byte_length <= 'Z')
1985 byte_length = byte_length - 'A' + 1;
1986 else if ('a' <= byte_length && byte_length <= 'z')
1987 byte_length = byte_length - 'a' + 27;
1988 else
1989 goto corrupt;
1990 /* if the input length was not multiple of 4, we would
1991 * have filler at the end but the filler should never
1992 * exceed 3 bytes
1994 if (max_byte_length < byte_length ||
1995 byte_length <= max_byte_length - 4)
1996 goto corrupt;
1997 newsize = hunk_size + byte_length;
1998 data = xrealloc(data, newsize);
1999 if (decode_85(data + hunk_size, buffer + 1, byte_length))
2000 goto corrupt;
2001 hunk_size = newsize;
2002 buffer += llen;
2003 size -= llen;
2006 CALLOC_ARRAY(frag, 1);
2007 frag->patch = inflate_it(data, hunk_size, origlen);
2008 frag->free_patch = 1;
2009 if (!frag->patch)
2010 goto corrupt;
2011 free(data);
2012 frag->size = origlen;
2013 *buf_p = buffer;
2014 *sz_p = size;
2015 *used_p = used;
2016 frag->binary_patch_method = patch_method;
2017 return frag;
2019 corrupt:
2020 free(data);
2021 *status_p = -1;
2022 error(_("corrupt binary patch at line %d: %.*s"),
2023 state->linenr-1, llen-1, buffer);
2024 return NULL;
2028 * Returns:
2029 * -1 in case of error,
2030 * the length of the parsed binary patch otherwise
2032 static int parse_binary(struct apply_state *state,
2033 char *buffer,
2034 unsigned long size,
2035 struct patch *patch)
2038 * We have read "GIT binary patch\n"; what follows is a line
2039 * that says the patch method (currently, either "literal" or
2040 * "delta") and the length of data before deflating; a
2041 * sequence of 'length-byte' followed by base-85 encoded data
2042 * follows.
2044 * When a binary patch is reversible, there is another binary
2045 * hunk in the same format, starting with patch method (either
2046 * "literal" or "delta") with the length of data, and a sequence
2047 * of length-byte + base-85 encoded data, terminated with another
2048 * empty line. This data, when applied to the postimage, produces
2049 * the preimage.
2051 struct fragment *forward;
2052 struct fragment *reverse;
2053 int status;
2054 int used, used_1;
2056 forward = parse_binary_hunk(state, &buffer, &size, &status, &used);
2057 if (!forward && !status)
2058 /* there has to be one hunk (forward hunk) */
2059 return error(_("unrecognized binary patch at line %d"), state->linenr-1);
2060 if (status)
2061 /* otherwise we already gave an error message */
2062 return status;
2064 reverse = parse_binary_hunk(state, &buffer, &size, &status, &used_1);
2065 if (reverse)
2066 used += used_1;
2067 else if (status) {
2069 * Not having reverse hunk is not an error, but having
2070 * a corrupt reverse hunk is.
2072 free((void*) forward->patch);
2073 free(forward);
2074 return status;
2076 forward->next = reverse;
2077 patch->fragments = forward;
2078 patch->is_binary = 1;
2079 return used;
2082 static void prefix_one(struct apply_state *state, char **name)
2084 char *old_name = *name;
2085 if (!old_name)
2086 return;
2087 *name = prefix_filename(state->prefix, *name);
2088 free(old_name);
2091 static void prefix_patch(struct apply_state *state, struct patch *p)
2093 if (!state->prefix || p->is_toplevel_relative)
2094 return;
2095 prefix_one(state, &p->new_name);
2096 prefix_one(state, &p->old_name);
2100 * include/exclude
2103 static void add_name_limit(struct apply_state *state,
2104 const char *name,
2105 int exclude)
2107 struct string_list_item *it;
2109 it = string_list_append(&state->limit_by_name, name);
2110 it->util = exclude ? NULL : (void *) 1;
2113 static int use_patch(struct apply_state *state, struct patch *p)
2115 const char *pathname = p->new_name ? p->new_name : p->old_name;
2116 int i;
2118 /* Paths outside are not touched regardless of "--include" */
2119 if (state->prefix && *state->prefix) {
2120 const char *rest;
2121 if (!skip_prefix(pathname, state->prefix, &rest) || !*rest)
2122 return 0;
2125 /* See if it matches any of exclude/include rule */
2126 for (i = 0; i < state->limit_by_name.nr; i++) {
2127 struct string_list_item *it = &state->limit_by_name.items[i];
2128 if (!wildmatch(it->string, pathname, 0))
2129 return (it->util != NULL);
2133 * If we had any include, a path that does not match any rule is
2134 * not used. Otherwise, we saw bunch of exclude rules (or none)
2135 * and such a path is used.
2137 return !state->has_include;
2141 * Read the patch text in "buffer" that extends for "size" bytes; stop
2142 * reading after seeing a single patch (i.e. changes to a single file).
2143 * Create fragments (i.e. patch hunks) and hang them to the given patch.
2145 * Returns:
2146 * -1 if no header was found or parse_binary() failed,
2147 * -128 on another error,
2148 * the number of bytes consumed otherwise,
2149 * so that the caller can call us again for the next patch.
2151 static int parse_chunk(struct apply_state *state, char *buffer, unsigned long size, struct patch *patch)
2153 int hdrsize, patchsize;
2154 int offset = find_header(state, buffer, size, &hdrsize, patch);
2156 if (offset < 0)
2157 return offset;
2159 prefix_patch(state, patch);
2161 if (!use_patch(state, patch))
2162 patch->ws_rule = 0;
2163 else if (patch->new_name)
2164 patch->ws_rule = whitespace_rule(state->repo->index,
2165 patch->new_name);
2166 else
2167 patch->ws_rule = whitespace_rule(state->repo->index,
2168 patch->old_name);
2170 patchsize = parse_single_patch(state,
2171 buffer + offset + hdrsize,
2172 size - offset - hdrsize,
2173 patch);
2175 if (patchsize < 0)
2176 return -128;
2178 if (!patchsize) {
2179 static const char git_binary[] = "GIT binary patch\n";
2180 int hd = hdrsize + offset;
2181 unsigned long llen = linelen(buffer + hd, size - hd);
2183 if (llen == sizeof(git_binary) - 1 &&
2184 !memcmp(git_binary, buffer + hd, llen)) {
2185 int used;
2186 state->linenr++;
2187 used = parse_binary(state, buffer + hd + llen,
2188 size - hd - llen, patch);
2189 if (used < 0)
2190 return -1;
2191 if (used)
2192 patchsize = used + llen;
2193 else
2194 patchsize = 0;
2196 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
2197 static const char *binhdr[] = {
2198 "Binary files ",
2199 "Files ",
2200 NULL,
2202 int i;
2203 for (i = 0; binhdr[i]; i++) {
2204 int len = strlen(binhdr[i]);
2205 if (len < size - hd &&
2206 !memcmp(binhdr[i], buffer + hd, len)) {
2207 state->linenr++;
2208 patch->is_binary = 1;
2209 patchsize = llen;
2210 break;
2215 /* Empty patch cannot be applied if it is a text patch
2216 * without metadata change. A binary patch appears
2217 * empty to us here.
2219 if ((state->apply || state->check) &&
2220 (!patch->is_binary && !metadata_changes(patch))) {
2221 error(_("patch with only garbage at line %d"), state->linenr);
2222 return -128;
2226 return offset + hdrsize + patchsize;
2229 static void reverse_patches(struct patch *p)
2231 for (; p; p = p->next) {
2232 struct fragment *frag = p->fragments;
2234 SWAP(p->new_name, p->old_name);
2235 if (p->new_mode)
2236 SWAP(p->new_mode, p->old_mode);
2237 SWAP(p->is_new, p->is_delete);
2238 SWAP(p->lines_added, p->lines_deleted);
2239 SWAP(p->old_oid_prefix, p->new_oid_prefix);
2241 for (; frag; frag = frag->next) {
2242 SWAP(frag->newpos, frag->oldpos);
2243 SWAP(frag->newlines, frag->oldlines);
2248 static const char pluses[] =
2249 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2250 static const char minuses[]=
2251 "----------------------------------------------------------------------";
2253 static void show_stats(struct apply_state *state, struct patch *patch)
2255 struct strbuf qname = STRBUF_INIT;
2256 char *cp = patch->new_name ? patch->new_name : patch->old_name;
2257 int max, add, del;
2259 quote_c_style(cp, &qname, NULL, 0);
2262 * "scale" the filename
2264 max = state->max_len;
2265 if (max > 50)
2266 max = 50;
2268 if (qname.len > max) {
2269 cp = strchr(qname.buf + qname.len + 3 - max, '/');
2270 if (!cp)
2271 cp = qname.buf + qname.len + 3 - max;
2272 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
2275 if (patch->is_binary) {
2276 printf(" %-*s | Bin\n", max, qname.buf);
2277 strbuf_release(&qname);
2278 return;
2281 printf(" %-*s |", max, qname.buf);
2282 strbuf_release(&qname);
2285 * scale the add/delete
2287 max = max + state->max_change > 70 ? 70 - max : state->max_change;
2288 add = patch->lines_added;
2289 del = patch->lines_deleted;
2291 if (state->max_change > 0) {
2292 int total = ((add + del) * max + state->max_change / 2) / state->max_change;
2293 add = (add * max + state->max_change / 2) / state->max_change;
2294 del = total - add;
2296 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
2297 add, pluses, del, minuses);
2300 static int read_old_data(struct stat *st, struct patch *patch,
2301 const char *path, struct strbuf *buf)
2303 int conv_flags = patch->crlf_in_old ?
2304 CONV_EOL_KEEP_CRLF : CONV_EOL_RENORMALIZE;
2305 switch (st->st_mode & S_IFMT) {
2306 case S_IFLNK:
2307 if (strbuf_readlink(buf, path, st->st_size) < 0)
2308 return error(_("unable to read symlink %s"), path);
2309 return 0;
2310 case S_IFREG:
2311 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
2312 return error(_("unable to open or read %s"), path);
2314 * "git apply" without "--index/--cached" should never look
2315 * at the index; the target file may not have been added to
2316 * the index yet, and we may not even be in any Git repository.
2317 * Pass NULL to convert_to_git() to stress this; the function
2318 * should never look at the index when explicit crlf option
2319 * is given.
2321 convert_to_git(NULL, path, buf->buf, buf->len, buf, conv_flags);
2322 return 0;
2323 default:
2324 return -1;
2329 * Update the preimage, and the common lines in postimage,
2330 * from buffer buf of length len. If postlen is 0 the postimage
2331 * is updated in place, otherwise it's updated on a new buffer
2332 * of length postlen
2335 static void update_pre_post_images(struct image *preimage,
2336 struct image *postimage,
2337 char *buf,
2338 size_t len, size_t postlen)
2340 int i, ctx, reduced;
2341 char *new_buf, *old_buf, *fixed;
2342 struct image fixed_preimage;
2345 * Update the preimage with whitespace fixes. Note that we
2346 * are not losing preimage->buf -- apply_one_fragment() will
2347 * free "oldlines".
2349 prepare_image(&fixed_preimage, buf, len, 1);
2350 assert(postlen
2351 ? fixed_preimage.nr == preimage->nr
2352 : fixed_preimage.nr <= preimage->nr);
2353 for (i = 0; i < fixed_preimage.nr; i++)
2354 fixed_preimage.line[i].flag = preimage->line[i].flag;
2355 free(preimage->line_allocated);
2356 *preimage = fixed_preimage;
2359 * Adjust the common context lines in postimage. This can be
2360 * done in-place when we are shrinking it with whitespace
2361 * fixing, but needs a new buffer when ignoring whitespace or
2362 * expanding leading tabs to spaces.
2364 * We trust the caller to tell us if the update can be done
2365 * in place (postlen==0) or not.
2367 old_buf = postimage->buf;
2368 if (postlen)
2369 new_buf = postimage->buf = xmalloc(postlen);
2370 else
2371 new_buf = old_buf;
2372 fixed = preimage->buf;
2374 for (i = reduced = ctx = 0; i < postimage->nr; i++) {
2375 size_t l_len = postimage->line[i].len;
2376 if (!(postimage->line[i].flag & LINE_COMMON)) {
2377 /* an added line -- no counterparts in preimage */
2378 memmove(new_buf, old_buf, l_len);
2379 old_buf += l_len;
2380 new_buf += l_len;
2381 continue;
2384 /* a common context -- skip it in the original postimage */
2385 old_buf += l_len;
2387 /* and find the corresponding one in the fixed preimage */
2388 while (ctx < preimage->nr &&
2389 !(preimage->line[ctx].flag & LINE_COMMON)) {
2390 fixed += preimage->line[ctx].len;
2391 ctx++;
2395 * preimage is expected to run out, if the caller
2396 * fixed addition of trailing blank lines.
2398 if (preimage->nr <= ctx) {
2399 reduced++;
2400 continue;
2403 /* and copy it in, while fixing the line length */
2404 l_len = preimage->line[ctx].len;
2405 memcpy(new_buf, fixed, l_len);
2406 new_buf += l_len;
2407 fixed += l_len;
2408 postimage->line[i].len = l_len;
2409 ctx++;
2412 if (postlen
2413 ? postlen < new_buf - postimage->buf
2414 : postimage->len < new_buf - postimage->buf)
2415 BUG("caller miscounted postlen: asked %d, orig = %d, used = %d",
2416 (int)postlen, (int) postimage->len, (int)(new_buf - postimage->buf));
2418 /* Fix the length of the whole thing */
2419 postimage->len = new_buf - postimage->buf;
2420 postimage->nr -= reduced;
2423 static int line_by_line_fuzzy_match(struct image *img,
2424 struct image *preimage,
2425 struct image *postimage,
2426 unsigned long current,
2427 int current_lno,
2428 int preimage_limit)
2430 int i;
2431 size_t imgoff = 0;
2432 size_t preoff = 0;
2433 size_t postlen = postimage->len;
2434 size_t extra_chars;
2435 char *buf;
2436 char *preimage_eof;
2437 char *preimage_end;
2438 struct strbuf fixed;
2439 char *fixed_buf;
2440 size_t fixed_len;
2442 for (i = 0; i < preimage_limit; i++) {
2443 size_t prelen = preimage->line[i].len;
2444 size_t imglen = img->line[current_lno+i].len;
2446 if (!fuzzy_matchlines(img->buf + current + imgoff, imglen,
2447 preimage->buf + preoff, prelen))
2448 return 0;
2449 if (preimage->line[i].flag & LINE_COMMON)
2450 postlen += imglen - prelen;
2451 imgoff += imglen;
2452 preoff += prelen;
2456 * Ok, the preimage matches with whitespace fuzz.
2458 * imgoff now holds the true length of the target that
2459 * matches the preimage before the end of the file.
2461 * Count the number of characters in the preimage that fall
2462 * beyond the end of the file and make sure that all of them
2463 * are whitespace characters. (This can only happen if
2464 * we are removing blank lines at the end of the file.)
2466 buf = preimage_eof = preimage->buf + preoff;
2467 for ( ; i < preimage->nr; i++)
2468 preoff += preimage->line[i].len;
2469 preimage_end = preimage->buf + preoff;
2470 for ( ; buf < preimage_end; buf++)
2471 if (!isspace(*buf))
2472 return 0;
2475 * Update the preimage and the common postimage context
2476 * lines to use the same whitespace as the target.
2477 * If whitespace is missing in the target (i.e.
2478 * if the preimage extends beyond the end of the file),
2479 * use the whitespace from the preimage.
2481 extra_chars = preimage_end - preimage_eof;
2482 strbuf_init(&fixed, imgoff + extra_chars);
2483 strbuf_add(&fixed, img->buf + current, imgoff);
2484 strbuf_add(&fixed, preimage_eof, extra_chars);
2485 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2486 update_pre_post_images(preimage, postimage,
2487 fixed_buf, fixed_len, postlen);
2488 return 1;
2491 static int match_fragment(struct apply_state *state,
2492 struct image *img,
2493 struct image *preimage,
2494 struct image *postimage,
2495 unsigned long current,
2496 int current_lno,
2497 unsigned ws_rule,
2498 int match_beginning, int match_end)
2500 int i;
2501 const char *orig, *target;
2502 struct strbuf fixed = STRBUF_INIT;
2503 size_t postlen;
2504 int preimage_limit;
2505 int ret;
2507 if (preimage->nr + current_lno <= img->nr) {
2509 * The hunk falls within the boundaries of img.
2511 preimage_limit = preimage->nr;
2512 if (match_end && (preimage->nr + current_lno != img->nr)) {
2513 ret = 0;
2514 goto out;
2516 } else if (state->ws_error_action == correct_ws_error &&
2517 (ws_rule & WS_BLANK_AT_EOF)) {
2519 * This hunk extends beyond the end of img, and we are
2520 * removing blank lines at the end of the file. This
2521 * many lines from the beginning of the preimage must
2522 * match with img, and the remainder of the preimage
2523 * must be blank.
2525 preimage_limit = img->nr - current_lno;
2526 } else {
2528 * The hunk extends beyond the end of the img and
2529 * we are not removing blanks at the end, so we
2530 * should reject the hunk at this position.
2532 ret = 0;
2533 goto out;
2536 if (match_beginning && current_lno) {
2537 ret = 0;
2538 goto out;
2541 /* Quick hash check */
2542 for (i = 0; i < preimage_limit; i++) {
2543 if ((img->line[current_lno + i].flag & LINE_PATCHED) ||
2544 (preimage->line[i].hash != img->line[current_lno + i].hash)) {
2545 ret = 0;
2546 goto out;
2550 if (preimage_limit == preimage->nr) {
2552 * Do we have an exact match? If we were told to match
2553 * at the end, size must be exactly at current+fragsize,
2554 * otherwise current+fragsize must be still within the preimage,
2555 * and either case, the old piece should match the preimage
2556 * exactly.
2558 if ((match_end
2559 ? (current + preimage->len == img->len)
2560 : (current + preimage->len <= img->len)) &&
2561 !memcmp(img->buf + current, preimage->buf, preimage->len)) {
2562 ret = 1;
2563 goto out;
2565 } else {
2567 * The preimage extends beyond the end of img, so
2568 * there cannot be an exact match.
2570 * There must be one non-blank context line that match
2571 * a line before the end of img.
2573 const char *buf, *buf_end;
2575 buf = preimage->buf;
2576 buf_end = buf;
2577 for (i = 0; i < preimage_limit; i++)
2578 buf_end += preimage->line[i].len;
2580 for ( ; buf < buf_end; buf++)
2581 if (!isspace(*buf))
2582 break;
2583 if (buf == buf_end) {
2584 ret = 0;
2585 goto out;
2590 * No exact match. If we are ignoring whitespace, run a line-by-line
2591 * fuzzy matching. We collect all the line length information because
2592 * we need it to adjust whitespace if we match.
2594 if (state->ws_ignore_action == ignore_ws_change) {
2595 ret = line_by_line_fuzzy_match(img, preimage, postimage,
2596 current, current_lno, preimage_limit);
2597 goto out;
2600 if (state->ws_error_action != correct_ws_error) {
2601 ret = 0;
2602 goto out;
2606 * The hunk does not apply byte-by-byte, but the hash says
2607 * it might with whitespace fuzz. We weren't asked to
2608 * ignore whitespace, we were asked to correct whitespace
2609 * errors, so let's try matching after whitespace correction.
2611 * While checking the preimage against the target, whitespace
2612 * errors in both fixed, we count how large the corresponding
2613 * postimage needs to be. The postimage prepared by
2614 * apply_one_fragment() has whitespace errors fixed on added
2615 * lines already, but the common lines were propagated as-is,
2616 * which may become longer when their whitespace errors are
2617 * fixed.
2620 /* First count added lines in postimage */
2621 postlen = 0;
2622 for (i = 0; i < postimage->nr; i++) {
2623 if (!(postimage->line[i].flag & LINE_COMMON))
2624 postlen += postimage->line[i].len;
2628 * The preimage may extend beyond the end of the file,
2629 * but in this loop we will only handle the part of the
2630 * preimage that falls within the file.
2632 strbuf_grow(&fixed, preimage->len + 1);
2633 orig = preimage->buf;
2634 target = img->buf + current;
2635 for (i = 0; i < preimage_limit; i++) {
2636 size_t oldlen = preimage->line[i].len;
2637 size_t tgtlen = img->line[current_lno + i].len;
2638 size_t fixstart = fixed.len;
2639 struct strbuf tgtfix;
2640 int match;
2642 /* Try fixing the line in the preimage */
2643 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2645 /* Try fixing the line in the target */
2646 strbuf_init(&tgtfix, tgtlen);
2647 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2650 * If they match, either the preimage was based on
2651 * a version before our tree fixed whitespace breakage,
2652 * or we are lacking a whitespace-fix patch the tree
2653 * the preimage was based on already had (i.e. target
2654 * has whitespace breakage, the preimage doesn't).
2655 * In either case, we are fixing the whitespace breakages
2656 * so we might as well take the fix together with their
2657 * real change.
2659 match = (tgtfix.len == fixed.len - fixstart &&
2660 !memcmp(tgtfix.buf, fixed.buf + fixstart,
2661 fixed.len - fixstart));
2663 /* Add the length if this is common with the postimage */
2664 if (preimage->line[i].flag & LINE_COMMON)
2665 postlen += tgtfix.len;
2667 strbuf_release(&tgtfix);
2668 if (!match) {
2669 ret = 0;
2670 goto out;
2673 orig += oldlen;
2674 target += tgtlen;
2679 * Now handle the lines in the preimage that falls beyond the
2680 * end of the file (if any). They will only match if they are
2681 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2682 * false).
2684 for ( ; i < preimage->nr; i++) {
2685 size_t fixstart = fixed.len; /* start of the fixed preimage */
2686 size_t oldlen = preimage->line[i].len;
2687 int j;
2689 /* Try fixing the line in the preimage */
2690 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2692 for (j = fixstart; j < fixed.len; j++) {
2693 if (!isspace(fixed.buf[j])) {
2694 ret = 0;
2695 goto out;
2700 orig += oldlen;
2704 * Yes, the preimage is based on an older version that still
2705 * has whitespace breakages unfixed, and fixing them makes the
2706 * hunk match. Update the context lines in the postimage.
2708 if (postlen < postimage->len)
2709 postlen = 0;
2710 update_pre_post_images(preimage, postimage,
2711 fixed.buf, fixed.len, postlen);
2713 ret = 1;
2715 out:
2716 strbuf_release(&fixed);
2717 return ret;
2720 static int find_pos(struct apply_state *state,
2721 struct image *img,
2722 struct image *preimage,
2723 struct image *postimage,
2724 int line,
2725 unsigned ws_rule,
2726 int match_beginning, int match_end)
2728 int i;
2729 unsigned long backwards, forwards, current;
2730 int backwards_lno, forwards_lno, current_lno;
2733 * When running with --allow-overlap, it is possible that a hunk is
2734 * seen that pretends to start at the beginning (but no longer does),
2735 * and that *still* needs to match the end. So trust `match_end` more
2736 * than `match_beginning`.
2738 if (state->allow_overlap && match_beginning && match_end &&
2739 img->nr - preimage->nr != 0)
2740 match_beginning = 0;
2743 * If match_beginning or match_end is specified, there is no
2744 * point starting from a wrong line that will never match and
2745 * wander around and wait for a match at the specified end.
2747 if (match_beginning)
2748 line = 0;
2749 else if (match_end)
2750 line = img->nr - preimage->nr;
2753 * Because the comparison is unsigned, the following test
2754 * will also take care of a negative line number that can
2755 * result when match_end and preimage is larger than the target.
2757 if ((size_t) line > img->nr)
2758 line = img->nr;
2760 current = 0;
2761 for (i = 0; i < line; i++)
2762 current += img->line[i].len;
2765 * There's probably some smart way to do this, but I'll leave
2766 * that to the smart and beautiful people. I'm simple and stupid.
2768 backwards = current;
2769 backwards_lno = line;
2770 forwards = current;
2771 forwards_lno = line;
2772 current_lno = line;
2774 for (i = 0; ; i++) {
2775 if (match_fragment(state, img, preimage, postimage,
2776 current, current_lno, ws_rule,
2777 match_beginning, match_end))
2778 return current_lno;
2780 again:
2781 if (backwards_lno == 0 && forwards_lno == img->nr)
2782 break;
2784 if (i & 1) {
2785 if (backwards_lno == 0) {
2786 i++;
2787 goto again;
2789 backwards_lno--;
2790 backwards -= img->line[backwards_lno].len;
2791 current = backwards;
2792 current_lno = backwards_lno;
2793 } else {
2794 if (forwards_lno == img->nr) {
2795 i++;
2796 goto again;
2798 forwards += img->line[forwards_lno].len;
2799 forwards_lno++;
2800 current = forwards;
2801 current_lno = forwards_lno;
2805 return -1;
2808 static void remove_first_line(struct image *img)
2810 img->buf += img->line[0].len;
2811 img->len -= img->line[0].len;
2812 img->line++;
2813 img->nr--;
2816 static void remove_last_line(struct image *img)
2818 img->len -= img->line[--img->nr].len;
2822 * The change from "preimage" and "postimage" has been found to
2823 * apply at applied_pos (counts in line numbers) in "img".
2824 * Update "img" to remove "preimage" and replace it with "postimage".
2826 static void update_image(struct apply_state *state,
2827 struct image *img,
2828 int applied_pos,
2829 struct image *preimage,
2830 struct image *postimage)
2833 * remove the copy of preimage at offset in img
2834 * and replace it with postimage
2836 int i, nr;
2837 size_t remove_count, insert_count, applied_at = 0;
2838 char *result;
2839 int preimage_limit;
2842 * If we are removing blank lines at the end of img,
2843 * the preimage may extend beyond the end.
2844 * If that is the case, we must be careful only to
2845 * remove the part of the preimage that falls within
2846 * the boundaries of img. Initialize preimage_limit
2847 * to the number of lines in the preimage that falls
2848 * within the boundaries.
2850 preimage_limit = preimage->nr;
2851 if (preimage_limit > img->nr - applied_pos)
2852 preimage_limit = img->nr - applied_pos;
2854 for (i = 0; i < applied_pos; i++)
2855 applied_at += img->line[i].len;
2857 remove_count = 0;
2858 for (i = 0; i < preimage_limit; i++)
2859 remove_count += img->line[applied_pos + i].len;
2860 insert_count = postimage->len;
2862 /* Adjust the contents */
2863 result = xmalloc(st_add3(st_sub(img->len, remove_count), insert_count, 1));
2864 memcpy(result, img->buf, applied_at);
2865 memcpy(result + applied_at, postimage->buf, postimage->len);
2866 memcpy(result + applied_at + postimage->len,
2867 img->buf + (applied_at + remove_count),
2868 img->len - (applied_at + remove_count));
2869 free(img->buf);
2870 img->buf = result;
2871 img->len += insert_count - remove_count;
2872 result[img->len] = '\0';
2874 /* Adjust the line table */
2875 nr = img->nr + postimage->nr - preimage_limit;
2876 if (preimage_limit < postimage->nr) {
2878 * NOTE: this knows that we never call remove_first_line()
2879 * on anything other than pre/post image.
2881 REALLOC_ARRAY(img->line, nr);
2882 img->line_allocated = img->line;
2884 if (preimage_limit != postimage->nr)
2885 MOVE_ARRAY(img->line + applied_pos + postimage->nr,
2886 img->line + applied_pos + preimage_limit,
2887 img->nr - (applied_pos + preimage_limit));
2888 COPY_ARRAY(img->line + applied_pos, postimage->line, postimage->nr);
2889 if (!state->allow_overlap)
2890 for (i = 0; i < postimage->nr; i++)
2891 img->line[applied_pos + i].flag |= LINE_PATCHED;
2892 img->nr = nr;
2896 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2897 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2898 * replace the part of "img" with "postimage" text.
2900 static int apply_one_fragment(struct apply_state *state,
2901 struct image *img, struct fragment *frag,
2902 int inaccurate_eof, unsigned ws_rule,
2903 int nth_fragment)
2905 int match_beginning, match_end;
2906 const char *patch = frag->patch;
2907 int size = frag->size;
2908 char *old, *oldlines;
2909 struct strbuf newlines;
2910 int new_blank_lines_at_end = 0;
2911 int found_new_blank_lines_at_end = 0;
2912 int hunk_linenr = frag->linenr;
2913 unsigned long leading, trailing;
2914 int pos, applied_pos;
2915 struct image preimage;
2916 struct image postimage;
2918 memset(&preimage, 0, sizeof(preimage));
2919 memset(&postimage, 0, sizeof(postimage));
2920 oldlines = xmalloc(size);
2921 strbuf_init(&newlines, size);
2923 old = oldlines;
2924 while (size > 0) {
2925 char first;
2926 int len = linelen(patch, size);
2927 int plen;
2928 int added_blank_line = 0;
2929 int is_blank_context = 0;
2930 size_t start;
2932 if (!len)
2933 break;
2936 * "plen" is how much of the line we should use for
2937 * the actual patch data. Normally we just remove the
2938 * first character on the line, but if the line is
2939 * followed by "\ No newline", then we also remove the
2940 * last one (which is the newline, of course).
2942 plen = len - 1;
2943 if (len < size && patch[len] == '\\')
2944 plen--;
2945 first = *patch;
2946 if (state->apply_in_reverse) {
2947 if (first == '-')
2948 first = '+';
2949 else if (first == '+')
2950 first = '-';
2953 switch (first) {
2954 case '\n':
2955 /* Newer GNU diff, empty context line */
2956 if (plen < 0)
2957 /* ... followed by '\No newline'; nothing */
2958 break;
2959 *old++ = '\n';
2960 strbuf_addch(&newlines, '\n');
2961 add_line_info(&preimage, "\n", 1, LINE_COMMON);
2962 add_line_info(&postimage, "\n", 1, LINE_COMMON);
2963 is_blank_context = 1;
2964 break;
2965 case ' ':
2966 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2967 ws_blank_line(patch + 1, plen))
2968 is_blank_context = 1;
2969 /* fallthrough */
2970 case '-':
2971 memcpy(old, patch + 1, plen);
2972 add_line_info(&preimage, old, plen,
2973 (first == ' ' ? LINE_COMMON : 0));
2974 old += plen;
2975 if (first == '-')
2976 break;
2977 /* fallthrough */
2978 case '+':
2979 /* --no-add does not add new lines */
2980 if (first == '+' && state->no_add)
2981 break;
2983 start = newlines.len;
2984 if (first != '+' ||
2985 !state->whitespace_error ||
2986 state->ws_error_action != correct_ws_error) {
2987 strbuf_add(&newlines, patch + 1, plen);
2989 else {
2990 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &state->applied_after_fixing_ws);
2992 add_line_info(&postimage, newlines.buf + start, newlines.len - start,
2993 (first == '+' ? 0 : LINE_COMMON));
2994 if (first == '+' &&
2995 (ws_rule & WS_BLANK_AT_EOF) &&
2996 ws_blank_line(patch + 1, plen))
2997 added_blank_line = 1;
2998 break;
2999 case '@': case '\\':
3000 /* Ignore it, we already handled it */
3001 break;
3002 default:
3003 if (state->apply_verbosity > verbosity_normal)
3004 error(_("invalid start of line: '%c'"), first);
3005 applied_pos = -1;
3006 goto out;
3008 if (added_blank_line) {
3009 if (!new_blank_lines_at_end)
3010 found_new_blank_lines_at_end = hunk_linenr;
3011 new_blank_lines_at_end++;
3013 else if (is_blank_context)
3015 else
3016 new_blank_lines_at_end = 0;
3017 patch += len;
3018 size -= len;
3019 hunk_linenr++;
3021 if (inaccurate_eof &&
3022 old > oldlines && old[-1] == '\n' &&
3023 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
3024 old--;
3025 strbuf_setlen(&newlines, newlines.len - 1);
3026 preimage.line_allocated[preimage.nr - 1].len--;
3027 postimage.line_allocated[postimage.nr - 1].len--;
3030 leading = frag->leading;
3031 trailing = frag->trailing;
3034 * A hunk to change lines at the beginning would begin with
3035 * @@ -1,L +N,M @@
3036 * but we need to be careful. -U0 that inserts before the second
3037 * line also has this pattern.
3039 * And a hunk to add to an empty file would begin with
3040 * @@ -0,0 +N,M @@
3042 * In other words, a hunk that is (frag->oldpos <= 1) with or
3043 * without leading context must match at the beginning.
3045 match_beginning = (!frag->oldpos ||
3046 (frag->oldpos == 1 && !state->unidiff_zero));
3049 * A hunk without trailing lines must match at the end.
3050 * However, we simply cannot tell if a hunk must match end
3051 * from the lack of trailing lines if the patch was generated
3052 * with unidiff without any context.
3054 match_end = !state->unidiff_zero && !trailing;
3056 pos = frag->newpos ? (frag->newpos - 1) : 0;
3057 preimage.buf = oldlines;
3058 preimage.len = old - oldlines;
3059 postimage.buf = newlines.buf;
3060 postimage.len = newlines.len;
3061 preimage.line = preimage.line_allocated;
3062 postimage.line = postimage.line_allocated;
3064 for (;;) {
3066 applied_pos = find_pos(state, img, &preimage, &postimage, pos,
3067 ws_rule, match_beginning, match_end);
3069 if (applied_pos >= 0)
3070 break;
3072 /* Am I at my context limits? */
3073 if ((leading <= state->p_context) && (trailing <= state->p_context))
3074 break;
3075 if (match_beginning || match_end) {
3076 match_beginning = match_end = 0;
3077 continue;
3081 * Reduce the number of context lines; reduce both
3082 * leading and trailing if they are equal otherwise
3083 * just reduce the larger context.
3085 if (leading >= trailing) {
3086 remove_first_line(&preimage);
3087 remove_first_line(&postimage);
3088 pos--;
3089 leading--;
3091 if (trailing > leading) {
3092 remove_last_line(&preimage);
3093 remove_last_line(&postimage);
3094 trailing--;
3098 if (applied_pos >= 0) {
3099 if (new_blank_lines_at_end &&
3100 preimage.nr + applied_pos >= img->nr &&
3101 (ws_rule & WS_BLANK_AT_EOF) &&
3102 state->ws_error_action != nowarn_ws_error) {
3103 record_ws_error(state, WS_BLANK_AT_EOF, "+", 1,
3104 found_new_blank_lines_at_end);
3105 if (state->ws_error_action == correct_ws_error) {
3106 while (new_blank_lines_at_end--)
3107 remove_last_line(&postimage);
3110 * We would want to prevent write_out_results()
3111 * from taking place in apply_patch() that follows
3112 * the callchain led us here, which is:
3113 * apply_patch->check_patch_list->check_patch->
3114 * apply_data->apply_fragments->apply_one_fragment
3116 if (state->ws_error_action == die_on_ws_error)
3117 state->apply = 0;
3120 if (state->apply_verbosity > verbosity_normal && applied_pos != pos) {
3121 int offset = applied_pos - pos;
3122 if (state->apply_in_reverse)
3123 offset = 0 - offset;
3124 fprintf_ln(stderr,
3125 Q_("Hunk #%d succeeded at %d (offset %d line).",
3126 "Hunk #%d succeeded at %d (offset %d lines).",
3127 offset),
3128 nth_fragment, applied_pos + 1, offset);
3132 * Warn if it was necessary to reduce the number
3133 * of context lines.
3135 if ((leading != frag->leading ||
3136 trailing != frag->trailing) && state->apply_verbosity > verbosity_silent)
3137 fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"
3138 " to apply fragment at %d"),
3139 leading, trailing, applied_pos+1);
3140 update_image(state, img, applied_pos, &preimage, &postimage);
3141 } else {
3142 if (state->apply_verbosity > verbosity_normal)
3143 error(_("while searching for:\n%.*s"),
3144 (int)(old - oldlines), oldlines);
3147 out:
3148 free(oldlines);
3149 strbuf_release(&newlines);
3150 free(preimage.line_allocated);
3151 free(postimage.line_allocated);
3153 return (applied_pos < 0);
3156 static int apply_binary_fragment(struct apply_state *state,
3157 struct image *img,
3158 struct patch *patch)
3160 struct fragment *fragment = patch->fragments;
3161 unsigned long len;
3162 void *dst;
3164 if (!fragment)
3165 return error(_("missing binary patch data for '%s'"),
3166 patch->new_name ?
3167 patch->new_name :
3168 patch->old_name);
3170 /* Binary patch is irreversible without the optional second hunk */
3171 if (state->apply_in_reverse) {
3172 if (!fragment->next)
3173 return error(_("cannot reverse-apply a binary patch "
3174 "without the reverse hunk to '%s'"),
3175 patch->new_name
3176 ? patch->new_name : patch->old_name);
3177 fragment = fragment->next;
3179 switch (fragment->binary_patch_method) {
3180 case BINARY_DELTA_DEFLATED:
3181 dst = patch_delta(img->buf, img->len, fragment->patch,
3182 fragment->size, &len);
3183 if (!dst)
3184 return -1;
3185 clear_image(img);
3186 img->buf = dst;
3187 img->len = len;
3188 return 0;
3189 case BINARY_LITERAL_DEFLATED:
3190 clear_image(img);
3191 img->len = fragment->size;
3192 img->buf = xmemdupz(fragment->patch, img->len);
3193 return 0;
3195 return -1;
3199 * Replace "img" with the result of applying the binary patch.
3200 * The binary patch data itself in patch->fragment is still kept
3201 * but the preimage prepared by the caller in "img" is freed here
3202 * or in the helper function apply_binary_fragment() this calls.
3204 static int apply_binary(struct apply_state *state,
3205 struct image *img,
3206 struct patch *patch)
3208 const char *name = patch->old_name ? patch->old_name : patch->new_name;
3209 struct object_id oid;
3210 const unsigned hexsz = the_hash_algo->hexsz;
3213 * For safety, we require patch index line to contain
3214 * full hex textual object ID for old and new, at least for now.
3216 if (strlen(patch->old_oid_prefix) != hexsz ||
3217 strlen(patch->new_oid_prefix) != hexsz ||
3218 get_oid_hex(patch->old_oid_prefix, &oid) ||
3219 get_oid_hex(patch->new_oid_prefix, &oid))
3220 return error(_("cannot apply binary patch to '%s' "
3221 "without full index line"), name);
3223 if (patch->old_name) {
3225 * See if the old one matches what the patch
3226 * applies to.
3228 hash_object_file(the_hash_algo, img->buf, img->len, OBJ_BLOB,
3229 &oid);
3230 if (strcmp(oid_to_hex(&oid), patch->old_oid_prefix))
3231 return error(_("the patch applies to '%s' (%s), "
3232 "which does not match the "
3233 "current contents."),
3234 name, oid_to_hex(&oid));
3236 else {
3237 /* Otherwise, the old one must be empty. */
3238 if (img->len)
3239 return error(_("the patch applies to an empty "
3240 "'%s' but it is not empty"), name);
3243 get_oid_hex(patch->new_oid_prefix, &oid);
3244 if (is_null_oid(&oid)) {
3245 clear_image(img);
3246 return 0; /* deletion patch */
3249 if (has_object(the_repository, &oid, 0)) {
3250 /* We already have the postimage */
3251 enum object_type type;
3252 unsigned long size;
3253 char *result;
3255 result = repo_read_object_file(the_repository, &oid, &type,
3256 &size);
3257 if (!result)
3258 return error(_("the necessary postimage %s for "
3259 "'%s' cannot be read"),
3260 patch->new_oid_prefix, name);
3261 clear_image(img);
3262 img->buf = result;
3263 img->len = size;
3264 } else {
3266 * We have verified buf matches the preimage;
3267 * apply the patch data to it, which is stored
3268 * in the patch->fragments->{patch,size}.
3270 if (apply_binary_fragment(state, img, patch))
3271 return error(_("binary patch does not apply to '%s'"),
3272 name);
3274 /* verify that the result matches */
3275 hash_object_file(the_hash_algo, img->buf, img->len, OBJ_BLOB,
3276 &oid);
3277 if (strcmp(oid_to_hex(&oid), patch->new_oid_prefix))
3278 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3279 name, patch->new_oid_prefix, oid_to_hex(&oid));
3282 return 0;
3285 static int apply_fragments(struct apply_state *state, struct image *img, struct patch *patch)
3287 struct fragment *frag = patch->fragments;
3288 const char *name = patch->old_name ? patch->old_name : patch->new_name;
3289 unsigned ws_rule = patch->ws_rule;
3290 unsigned inaccurate_eof = patch->inaccurate_eof;
3291 int nth = 0;
3293 if (patch->is_binary)
3294 return apply_binary(state, img, patch);
3296 while (frag) {
3297 nth++;
3298 if (apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {
3299 error(_("patch failed: %s:%ld"), name, frag->oldpos);
3300 if (!state->apply_with_reject)
3301 return -1;
3302 frag->rejected = 1;
3304 frag = frag->next;
3306 return 0;
3309 static int read_blob_object(struct strbuf *buf, const struct object_id *oid, unsigned mode)
3311 if (S_ISGITLINK(mode)) {
3312 strbuf_grow(buf, 100);
3313 strbuf_addf(buf, "Subproject commit %s\n", oid_to_hex(oid));
3314 } else {
3315 enum object_type type;
3316 unsigned long sz;
3317 char *result;
3319 result = repo_read_object_file(the_repository, oid, &type,
3320 &sz);
3321 if (!result)
3322 return -1;
3323 /* XXX read_sha1_file NUL-terminates */
3324 strbuf_attach(buf, result, sz, sz + 1);
3326 return 0;
3329 static int read_file_or_gitlink(const struct cache_entry *ce, struct strbuf *buf)
3331 if (!ce)
3332 return 0;
3333 return read_blob_object(buf, &ce->oid, ce->ce_mode);
3336 static struct patch *in_fn_table(struct apply_state *state, const char *name)
3338 struct string_list_item *item;
3340 if (!name)
3341 return NULL;
3343 item = string_list_lookup(&state->fn_table, name);
3344 if (item)
3345 return (struct patch *)item->util;
3347 return NULL;
3351 * item->util in the filename table records the status of the path.
3352 * Usually it points at a patch (whose result records the contents
3353 * of it after applying it), but it could be PATH_WAS_DELETED for a
3354 * path that a previously applied patch has already removed, or
3355 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3357 * The latter is needed to deal with a case where two paths A and B
3358 * are swapped by first renaming A to B and then renaming B to A;
3359 * moving A to B should not be prevented due to presence of B as we
3360 * will remove it in a later patch.
3362 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3363 #define PATH_WAS_DELETED ((struct patch *) -1)
3365 static int to_be_deleted(struct patch *patch)
3367 return patch == PATH_TO_BE_DELETED;
3370 static int was_deleted(struct patch *patch)
3372 return patch == PATH_WAS_DELETED;
3375 static void add_to_fn_table(struct apply_state *state, struct patch *patch)
3377 struct string_list_item *item;
3380 * Always add new_name unless patch is a deletion
3381 * This should cover the cases for normal diffs,
3382 * file creations and copies
3384 if (patch->new_name) {
3385 item = string_list_insert(&state->fn_table, patch->new_name);
3386 item->util = patch;
3390 * store a failure on rename/deletion cases because
3391 * later chunks shouldn't patch old names
3393 if ((patch->new_name == NULL) || (patch->is_rename)) {
3394 item = string_list_insert(&state->fn_table, patch->old_name);
3395 item->util = PATH_WAS_DELETED;
3399 static void prepare_fn_table(struct apply_state *state, struct patch *patch)
3402 * store information about incoming file deletion
3404 while (patch) {
3405 if ((patch->new_name == NULL) || (patch->is_rename)) {
3406 struct string_list_item *item;
3407 item = string_list_insert(&state->fn_table, patch->old_name);
3408 item->util = PATH_TO_BE_DELETED;
3410 patch = patch->next;
3414 static int checkout_target(struct index_state *istate,
3415 struct cache_entry *ce, struct stat *st)
3417 struct checkout costate = CHECKOUT_INIT;
3419 costate.refresh_cache = 1;
3420 costate.istate = istate;
3421 if (checkout_entry(ce, &costate, NULL, NULL) ||
3422 lstat(ce->name, st))
3423 return error(_("cannot checkout %s"), ce->name);
3424 return 0;
3427 static struct patch *previous_patch(struct apply_state *state,
3428 struct patch *patch,
3429 int *gone)
3431 struct patch *previous;
3433 *gone = 0;
3434 if (patch->is_copy || patch->is_rename)
3435 return NULL; /* "git" patches do not depend on the order */
3437 previous = in_fn_table(state, patch->old_name);
3438 if (!previous)
3439 return NULL;
3441 if (to_be_deleted(previous))
3442 return NULL; /* the deletion hasn't happened yet */
3444 if (was_deleted(previous))
3445 *gone = 1;
3447 return previous;
3450 static int verify_index_match(struct apply_state *state,
3451 const struct cache_entry *ce,
3452 struct stat *st)
3454 if (S_ISGITLINK(ce->ce_mode)) {
3455 if (!S_ISDIR(st->st_mode))
3456 return -1;
3457 return 0;
3459 return ie_match_stat(state->repo->index, ce, st,
3460 CE_MATCH_IGNORE_VALID | CE_MATCH_IGNORE_SKIP_WORKTREE);
3463 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3465 static int load_patch_target(struct apply_state *state,
3466 struct strbuf *buf,
3467 const struct cache_entry *ce,
3468 struct stat *st,
3469 struct patch *patch,
3470 const char *name,
3471 unsigned expected_mode)
3473 if (state->cached || state->check_index) {
3474 if (read_file_or_gitlink(ce, buf))
3475 return error(_("failed to read %s"), name);
3476 } else if (name) {
3477 if (S_ISGITLINK(expected_mode)) {
3478 if (ce)
3479 return read_file_or_gitlink(ce, buf);
3480 else
3481 return SUBMODULE_PATCH_WITHOUT_INDEX;
3482 } else if (has_symlink_leading_path(name, strlen(name))) {
3483 return error(_("reading from '%s' beyond a symbolic link"), name);
3484 } else {
3485 if (read_old_data(st, patch, name, buf))
3486 return error(_("failed to read %s"), name);
3489 return 0;
3493 * We are about to apply "patch"; populate the "image" with the
3494 * current version we have, from the working tree or from the index,
3495 * depending on the situation e.g. --cached/--index. If we are
3496 * applying a non-git patch that incrementally updates the tree,
3497 * we read from the result of a previous diff.
3499 static int load_preimage(struct apply_state *state,
3500 struct image *image,
3501 struct patch *patch, struct stat *st,
3502 const struct cache_entry *ce)
3504 struct strbuf buf = STRBUF_INIT;
3505 size_t len;
3506 char *img;
3507 struct patch *previous;
3508 int status;
3510 previous = previous_patch(state, patch, &status);
3511 if (status)
3512 return error(_("path %s has been renamed/deleted"),
3513 patch->old_name);
3514 if (previous) {
3515 /* We have a patched copy in memory; use that. */
3516 strbuf_add(&buf, previous->result, previous->resultsize);
3517 } else {
3518 status = load_patch_target(state, &buf, ce, st, patch,
3519 patch->old_name, patch->old_mode);
3520 if (status < 0)
3521 return status;
3522 else if (status == SUBMODULE_PATCH_WITHOUT_INDEX) {
3524 * There is no way to apply subproject
3525 * patch without looking at the index.
3526 * NEEDSWORK: shouldn't this be flagged
3527 * as an error???
3529 free_fragment_list(patch->fragments);
3530 patch->fragments = NULL;
3531 } else if (status) {
3532 return error(_("failed to read %s"), patch->old_name);
3536 img = strbuf_detach(&buf, &len);
3537 prepare_image(image, img, len, !patch->is_binary);
3538 return 0;
3541 static int resolve_to(struct image *image, const struct object_id *result_id)
3543 unsigned long size;
3544 enum object_type type;
3546 clear_image(image);
3548 image->buf = repo_read_object_file(the_repository, result_id, &type,
3549 &size);
3550 if (!image->buf || type != OBJ_BLOB)
3551 die("unable to read blob object %s", oid_to_hex(result_id));
3552 image->len = size;
3554 return 0;
3557 static int three_way_merge(struct apply_state *state,
3558 struct image *image,
3559 char *path,
3560 const struct object_id *base,
3561 const struct object_id *ours,
3562 const struct object_id *theirs)
3564 mmfile_t base_file, our_file, their_file;
3565 struct ll_merge_options merge_opts = LL_MERGE_OPTIONS_INIT;
3566 mmbuffer_t result = { NULL };
3567 enum ll_merge_result status;
3569 /* resolve trivial cases first */
3570 if (oideq(base, ours))
3571 return resolve_to(image, theirs);
3572 else if (oideq(base, theirs) || oideq(ours, theirs))
3573 return resolve_to(image, ours);
3575 read_mmblob(&base_file, base);
3576 read_mmblob(&our_file, ours);
3577 read_mmblob(&their_file, theirs);
3578 merge_opts.variant = state->merge_variant;
3579 status = ll_merge(&result, path,
3580 &base_file, "base",
3581 &our_file, "ours",
3582 &their_file, "theirs",
3583 state->repo->index,
3584 &merge_opts);
3585 if (status == LL_MERGE_BINARY_CONFLICT)
3586 warning("Cannot merge binary files: %s (%s vs. %s)",
3587 path, "ours", "theirs");
3588 free(base_file.ptr);
3589 free(our_file.ptr);
3590 free(their_file.ptr);
3591 if (status < 0 || !result.ptr) {
3592 free(result.ptr);
3593 return -1;
3595 clear_image(image);
3596 image->buf = result.ptr;
3597 image->len = result.size;
3599 return status;
3603 * When directly falling back to add/add three-way merge, we read from
3604 * the current contents of the new_name. In no cases other than that
3605 * this function will be called.
3607 static int load_current(struct apply_state *state,
3608 struct image *image,
3609 struct patch *patch)
3611 struct strbuf buf = STRBUF_INIT;
3612 int status, pos;
3613 size_t len;
3614 char *img;
3615 struct stat st;
3616 struct cache_entry *ce;
3617 char *name = patch->new_name;
3618 unsigned mode = patch->new_mode;
3620 if (!patch->is_new)
3621 BUG("patch to %s is not a creation", patch->old_name);
3623 pos = index_name_pos(state->repo->index, name, strlen(name));
3624 if (pos < 0)
3625 return error(_("%s: does not exist in index"), name);
3626 ce = state->repo->index->cache[pos];
3627 if (lstat(name, &st)) {
3628 if (errno != ENOENT)
3629 return error_errno("%s", name);
3630 if (checkout_target(state->repo->index, ce, &st))
3631 return -1;
3633 if (verify_index_match(state, ce, &st))
3634 return error(_("%s: does not match index"), name);
3636 status = load_patch_target(state, &buf, ce, &st, patch, name, mode);
3637 if (status < 0)
3638 return status;
3639 else if (status)
3640 return -1;
3641 img = strbuf_detach(&buf, &len);
3642 prepare_image(image, img, len, !patch->is_binary);
3643 return 0;
3646 static int try_threeway(struct apply_state *state,
3647 struct image *image,
3648 struct patch *patch,
3649 struct stat *st,
3650 const struct cache_entry *ce)
3652 struct object_id pre_oid, post_oid, our_oid;
3653 struct strbuf buf = STRBUF_INIT;
3654 size_t len;
3655 int status;
3656 char *img;
3657 struct image tmp_image;
3659 /* No point falling back to 3-way merge in these cases */
3660 if (patch->is_delete ||
3661 S_ISGITLINK(patch->old_mode) || S_ISGITLINK(patch->new_mode) ||
3662 (patch->is_new && !patch->direct_to_threeway) ||
3663 (patch->is_rename && !patch->lines_added && !patch->lines_deleted))
3664 return -1;
3666 /* Preimage the patch was prepared for */
3667 if (patch->is_new)
3668 write_object_file("", 0, OBJ_BLOB, &pre_oid);
3669 else if (repo_get_oid(the_repository, patch->old_oid_prefix, &pre_oid) ||
3670 read_blob_object(&buf, &pre_oid, patch->old_mode))
3671 return error(_("repository lacks the necessary blob to perform 3-way merge."));
3673 if (state->apply_verbosity > verbosity_silent && patch->direct_to_threeway)
3674 fprintf(stderr, _("Performing three-way merge...\n"));
3676 img = strbuf_detach(&buf, &len);
3677 prepare_image(&tmp_image, img, len, 1);
3678 /* Apply the patch to get the post image */
3679 if (apply_fragments(state, &tmp_image, patch) < 0) {
3680 clear_image(&tmp_image);
3681 return -1;
3683 /* post_oid is theirs */
3684 write_object_file(tmp_image.buf, tmp_image.len, OBJ_BLOB, &post_oid);
3685 clear_image(&tmp_image);
3687 /* our_oid is ours */
3688 if (patch->is_new) {
3689 if (load_current(state, &tmp_image, patch))
3690 return error(_("cannot read the current contents of '%s'"),
3691 patch->new_name);
3692 } else {
3693 if (load_preimage(state, &tmp_image, patch, st, ce))
3694 return error(_("cannot read the current contents of '%s'"),
3695 patch->old_name);
3697 write_object_file(tmp_image.buf, tmp_image.len, OBJ_BLOB, &our_oid);
3698 clear_image(&tmp_image);
3700 /* in-core three-way merge between post and our using pre as base */
3701 status = three_way_merge(state, image, patch->new_name,
3702 &pre_oid, &our_oid, &post_oid);
3703 if (status < 0) {
3704 if (state->apply_verbosity > verbosity_silent)
3705 fprintf(stderr,
3706 _("Failed to perform three-way merge...\n"));
3707 return status;
3710 if (status) {
3711 patch->conflicted_threeway = 1;
3712 if (patch->is_new)
3713 oidclr(&patch->threeway_stage[0], the_repository->hash_algo);
3714 else
3715 oidcpy(&patch->threeway_stage[0], &pre_oid);
3716 oidcpy(&patch->threeway_stage[1], &our_oid);
3717 oidcpy(&patch->threeway_stage[2], &post_oid);
3718 if (state->apply_verbosity > verbosity_silent)
3719 fprintf(stderr,
3720 _("Applied patch to '%s' with conflicts.\n"),
3721 patch->new_name);
3722 } else {
3723 if (state->apply_verbosity > verbosity_silent)
3724 fprintf(stderr,
3725 _("Applied patch to '%s' cleanly.\n"),
3726 patch->new_name);
3728 return 0;
3731 static int apply_data(struct apply_state *state, struct patch *patch,
3732 struct stat *st, const struct cache_entry *ce)
3734 struct image image;
3736 if (load_preimage(state, &image, patch, st, ce) < 0)
3737 return -1;
3739 if (!state->threeway || try_threeway(state, &image, patch, st, ce) < 0) {
3740 if (state->apply_verbosity > verbosity_silent &&
3741 state->threeway && !patch->direct_to_threeway)
3742 fprintf(stderr, _("Falling back to direct application...\n"));
3744 /* Note: with --reject, apply_fragments() returns 0 */
3745 if (patch->direct_to_threeway || apply_fragments(state, &image, patch) < 0) {
3746 clear_image(&image);
3747 return -1;
3750 patch->result = image.buf;
3751 patch->resultsize = image.len;
3752 add_to_fn_table(state, patch);
3753 free(image.line_allocated);
3755 if (0 < patch->is_delete && patch->resultsize)
3756 return error(_("removal patch leaves file contents"));
3758 return 0;
3762 * If "patch" that we are looking at modifies or deletes what we have,
3763 * we would want it not to lose any local modification we have, either
3764 * in the working tree or in the index.
3766 * This also decides if a non-git patch is a creation patch or a
3767 * modification to an existing empty file. We do not check the state
3768 * of the current tree for a creation patch in this function; the caller
3769 * check_patch() separately makes sure (and errors out otherwise) that
3770 * the path the patch creates does not exist in the current tree.
3772 static int check_preimage(struct apply_state *state,
3773 struct patch *patch,
3774 struct cache_entry **ce,
3775 struct stat *st)
3777 const char *old_name = patch->old_name;
3778 struct patch *previous = NULL;
3779 int stat_ret = 0, status;
3780 unsigned st_mode = 0;
3782 if (!old_name)
3783 return 0;
3785 assert(patch->is_new <= 0);
3786 previous = previous_patch(state, patch, &status);
3788 if (status)
3789 return error(_("path %s has been renamed/deleted"), old_name);
3790 if (previous) {
3791 st_mode = previous->new_mode;
3792 } else if (!state->cached) {
3793 stat_ret = lstat(old_name, st);
3794 if (stat_ret && errno != ENOENT)
3795 return error_errno("%s", old_name);
3798 if (state->check_index && !previous) {
3799 int pos = index_name_pos(state->repo->index, old_name,
3800 strlen(old_name));
3801 if (pos < 0) {
3802 if (patch->is_new < 0)
3803 goto is_new;
3804 return error(_("%s: does not exist in index"), old_name);
3806 *ce = state->repo->index->cache[pos];
3807 if (stat_ret < 0) {
3808 if (checkout_target(state->repo->index, *ce, st))
3809 return -1;
3811 if (!state->cached && verify_index_match(state, *ce, st))
3812 return error(_("%s: does not match index"), old_name);
3813 if (state->cached)
3814 st_mode = (*ce)->ce_mode;
3815 } else if (stat_ret < 0) {
3816 if (patch->is_new < 0)
3817 goto is_new;
3818 return error_errno("%s", old_name);
3821 if (!state->cached && !previous) {
3822 if (*ce && !(*ce)->ce_mode)
3823 BUG("ce_mode == 0 for path '%s'", old_name);
3825 if (trust_executable_bit)
3826 st_mode = ce_mode_from_stat(*ce, st->st_mode);
3827 else if (*ce)
3828 st_mode = (*ce)->ce_mode;
3829 else
3830 st_mode = patch->old_mode;
3833 if (patch->is_new < 0)
3834 patch->is_new = 0;
3835 if (!patch->old_mode)
3836 patch->old_mode = st_mode;
3837 if ((st_mode ^ patch->old_mode) & S_IFMT)
3838 return error(_("%s: wrong type"), old_name);
3839 if (st_mode != patch->old_mode)
3840 warning(_("%s has type %o, expected %o"),
3841 old_name, st_mode, patch->old_mode);
3842 if (!patch->new_mode && !patch->is_delete)
3843 patch->new_mode = st_mode;
3844 return 0;
3846 is_new:
3847 patch->is_new = 1;
3848 patch->is_delete = 0;
3849 FREE_AND_NULL(patch->old_name);
3850 return 0;
3854 #define EXISTS_IN_INDEX 1
3855 #define EXISTS_IN_WORKTREE 2
3856 #define EXISTS_IN_INDEX_AS_ITA 3
3858 static int check_to_create(struct apply_state *state,
3859 const char *new_name,
3860 int ok_if_exists)
3862 struct stat nst;
3864 if (state->check_index && (!ok_if_exists || !state->cached)) {
3865 int pos;
3867 pos = index_name_pos(state->repo->index, new_name, strlen(new_name));
3868 if (pos >= 0) {
3869 struct cache_entry *ce = state->repo->index->cache[pos];
3871 /* allow ITA, as they do not yet exist in the index */
3872 if (!ok_if_exists && !(ce->ce_flags & CE_INTENT_TO_ADD))
3873 return EXISTS_IN_INDEX;
3875 /* ITA entries can never match working tree files */
3876 if (!state->cached && (ce->ce_flags & CE_INTENT_TO_ADD))
3877 return EXISTS_IN_INDEX_AS_ITA;
3881 if (state->cached)
3882 return 0;
3884 if (!lstat(new_name, &nst)) {
3885 if (S_ISDIR(nst.st_mode) || ok_if_exists)
3886 return 0;
3888 * A leading component of new_name might be a symlink
3889 * that is going to be removed with this patch, but
3890 * still pointing at somewhere that has the path.
3891 * In such a case, path "new_name" does not exist as
3892 * far as git is concerned.
3894 if (has_symlink_leading_path(new_name, strlen(new_name)))
3895 return 0;
3897 return EXISTS_IN_WORKTREE;
3898 } else if (!is_missing_file_error(errno)) {
3899 return error_errno("%s", new_name);
3901 return 0;
3904 static void prepare_symlink_changes(struct apply_state *state, struct patch *patch)
3906 for ( ; patch; patch = patch->next) {
3907 if ((patch->old_name && S_ISLNK(patch->old_mode)) &&
3908 (patch->is_rename || patch->is_delete))
3909 /* the symlink at patch->old_name is removed */
3910 strset_add(&state->removed_symlinks, patch->old_name);
3912 if (patch->new_name && S_ISLNK(patch->new_mode))
3913 /* the symlink at patch->new_name is created or remains */
3914 strset_add(&state->kept_symlinks, patch->new_name);
3918 static int path_is_beyond_symlink_1(struct apply_state *state, struct strbuf *name)
3920 do {
3921 while (--name->len && name->buf[name->len] != '/')
3922 ; /* scan backwards */
3923 if (!name->len)
3924 break;
3925 name->buf[name->len] = '\0';
3926 if (strset_contains(&state->kept_symlinks, name->buf))
3927 return 1;
3928 if (strset_contains(&state->removed_symlinks, name->buf))
3930 * This cannot be "return 0", because we may
3931 * see a new one created at a higher level.
3933 continue;
3935 /* otherwise, check the preimage */
3936 if (state->check_index) {
3937 struct cache_entry *ce;
3939 ce = index_file_exists(state->repo->index, name->buf,
3940 name->len, ignore_case);
3941 if (ce && S_ISLNK(ce->ce_mode))
3942 return 1;
3943 } else {
3944 struct stat st;
3945 if (!lstat(name->buf, &st) && S_ISLNK(st.st_mode))
3946 return 1;
3948 } while (1);
3949 return 0;
3952 static int path_is_beyond_symlink(struct apply_state *state, const char *name_)
3954 int ret;
3955 struct strbuf name = STRBUF_INIT;
3957 assert(*name_ != '\0');
3958 strbuf_addstr(&name, name_);
3959 ret = path_is_beyond_symlink_1(state, &name);
3960 strbuf_release(&name);
3962 return ret;
3965 static int check_unsafe_path(struct patch *patch)
3967 const char *old_name = NULL;
3968 const char *new_name = NULL;
3969 if (patch->is_delete)
3970 old_name = patch->old_name;
3971 else if (!patch->is_new && !patch->is_copy)
3972 old_name = patch->old_name;
3973 if (!patch->is_delete)
3974 new_name = patch->new_name;
3976 if (old_name && !verify_path(old_name, patch->old_mode))
3977 return error(_("invalid path '%s'"), old_name);
3978 if (new_name && !verify_path(new_name, patch->new_mode))
3979 return error(_("invalid path '%s'"), new_name);
3980 return 0;
3984 * Check and apply the patch in-core; leave the result in patch->result
3985 * for the caller to write it out to the final destination.
3987 static int check_patch(struct apply_state *state, struct patch *patch)
3989 struct stat st;
3990 const char *old_name = patch->old_name;
3991 const char *new_name = patch->new_name;
3992 const char *name = old_name ? old_name : new_name;
3993 struct cache_entry *ce = NULL;
3994 struct patch *tpatch;
3995 int ok_if_exists;
3996 int status;
3998 patch->rejected = 1; /* we will drop this after we succeed */
4000 status = check_preimage(state, patch, &ce, &st);
4001 if (status)
4002 return status;
4003 old_name = patch->old_name;
4006 * A type-change diff is always split into a patch to delete
4007 * old, immediately followed by a patch to create new (see
4008 * diff.c::run_diff()); in such a case it is Ok that the entry
4009 * to be deleted by the previous patch is still in the working
4010 * tree and in the index.
4012 * A patch to swap-rename between A and B would first rename A
4013 * to B and then rename B to A. While applying the first one,
4014 * the presence of B should not stop A from getting renamed to
4015 * B; ask to_be_deleted() about the later rename. Removal of
4016 * B and rename from A to B is handled the same way by asking
4017 * was_deleted().
4019 if ((tpatch = in_fn_table(state, new_name)) &&
4020 (was_deleted(tpatch) || to_be_deleted(tpatch)))
4021 ok_if_exists = 1;
4022 else
4023 ok_if_exists = 0;
4025 if (new_name &&
4026 ((0 < patch->is_new) || patch->is_rename || patch->is_copy)) {
4027 int err = check_to_create(state, new_name, ok_if_exists);
4029 if (err && state->threeway) {
4030 patch->direct_to_threeway = 1;
4031 } else switch (err) {
4032 case 0:
4033 break; /* happy */
4034 case EXISTS_IN_INDEX:
4035 return error(_("%s: already exists in index"), new_name);
4036 case EXISTS_IN_INDEX_AS_ITA:
4037 return error(_("%s: does not match index"), new_name);
4038 case EXISTS_IN_WORKTREE:
4039 return error(_("%s: already exists in working directory"),
4040 new_name);
4041 default:
4042 return err;
4045 if (!patch->new_mode) {
4046 if (0 < patch->is_new)
4047 patch->new_mode = S_IFREG | 0644;
4048 else
4049 patch->new_mode = patch->old_mode;
4053 if (new_name && old_name) {
4054 int same = !strcmp(old_name, new_name);
4055 if (!patch->new_mode)
4056 patch->new_mode = patch->old_mode;
4057 if ((patch->old_mode ^ patch->new_mode) & S_IFMT) {
4058 if (same)
4059 return error(_("new mode (%o) of %s does not "
4060 "match old mode (%o)"),
4061 patch->new_mode, new_name,
4062 patch->old_mode);
4063 else
4064 return error(_("new mode (%o) of %s does not "
4065 "match old mode (%o) of %s"),
4066 patch->new_mode, new_name,
4067 patch->old_mode, old_name);
4071 if (!state->unsafe_paths && check_unsafe_path(patch))
4072 return -128;
4075 * An attempt to read from or delete a path that is beyond a
4076 * symbolic link will be prevented by load_patch_target() that
4077 * is called at the beginning of apply_data() so we do not
4078 * have to worry about a patch marked with "is_delete" bit
4079 * here. We however need to make sure that the patch result
4080 * is not deposited to a path that is beyond a symbolic link
4081 * here.
4083 if (!patch->is_delete && path_is_beyond_symlink(state, patch->new_name))
4084 return error(_("affected file '%s' is beyond a symbolic link"),
4085 patch->new_name);
4087 if (apply_data(state, patch, &st, ce) < 0)
4088 return error(_("%s: patch does not apply"), name);
4089 patch->rejected = 0;
4090 return 0;
4093 static int check_patch_list(struct apply_state *state, struct patch *patch)
4095 int err = 0;
4097 prepare_symlink_changes(state, patch);
4098 prepare_fn_table(state, patch);
4099 while (patch) {
4100 int res;
4101 if (state->apply_verbosity > verbosity_normal)
4102 say_patch_name(stderr,
4103 _("Checking patch %s..."), patch);
4104 res = check_patch(state, patch);
4105 if (res == -128)
4106 return -128;
4107 err |= res;
4108 patch = patch->next;
4110 return err;
4113 static int read_apply_cache(struct apply_state *state)
4115 if (state->index_file)
4116 return read_index_from(state->repo->index, state->index_file,
4117 repo_get_git_dir(the_repository));
4118 else
4119 return repo_read_index(state->repo);
4122 /* This function tries to read the object name from the current index */
4123 static int get_current_oid(struct apply_state *state, const char *path,
4124 struct object_id *oid)
4126 int pos;
4128 if (read_apply_cache(state) < 0)
4129 return -1;
4130 pos = index_name_pos(state->repo->index, path, strlen(path));
4131 if (pos < 0)
4132 return -1;
4133 oidcpy(oid, &state->repo->index->cache[pos]->oid);
4134 return 0;
4137 static int preimage_oid_in_gitlink_patch(struct patch *p, struct object_id *oid)
4140 * A usable gitlink patch has only one fragment (hunk) that looks like:
4141 * @@ -1 +1 @@
4142 * -Subproject commit <old sha1>
4143 * +Subproject commit <new sha1>
4144 * or
4145 * @@ -1 +0,0 @@
4146 * -Subproject commit <old sha1>
4147 * for a removal patch.
4149 struct fragment *hunk = p->fragments;
4150 static const char heading[] = "-Subproject commit ";
4151 char *preimage;
4153 if (/* does the patch have only one hunk? */
4154 hunk && !hunk->next &&
4155 /* is its preimage one line? */
4156 hunk->oldpos == 1 && hunk->oldlines == 1 &&
4157 /* does preimage begin with the heading? */
4158 (preimage = memchr(hunk->patch, '\n', hunk->size)) != NULL &&
4159 starts_with(++preimage, heading) &&
4160 /* does it record full SHA-1? */
4161 !get_oid_hex(preimage + sizeof(heading) - 1, oid) &&
4162 preimage[sizeof(heading) + the_hash_algo->hexsz - 1] == '\n' &&
4163 /* does the abbreviated name on the index line agree with it? */
4164 starts_with(preimage + sizeof(heading) - 1, p->old_oid_prefix))
4165 return 0; /* it all looks fine */
4167 /* we may have full object name on the index line */
4168 return get_oid_hex(p->old_oid_prefix, oid);
4171 /* Build an index that contains just the files needed for a 3way merge */
4172 static int build_fake_ancestor(struct apply_state *state, struct patch *list)
4174 struct patch *patch;
4175 struct index_state result = INDEX_STATE_INIT(state->repo);
4176 struct lock_file lock = LOCK_INIT;
4177 int res;
4179 /* Once we start supporting the reverse patch, it may be
4180 * worth showing the new sha1 prefix, but until then...
4182 for (patch = list; patch; patch = patch->next) {
4183 struct object_id oid;
4184 struct cache_entry *ce;
4185 const char *name;
4187 name = patch->old_name ? patch->old_name : patch->new_name;
4188 if (0 < patch->is_new)
4189 continue;
4191 if (S_ISGITLINK(patch->old_mode)) {
4192 if (!preimage_oid_in_gitlink_patch(patch, &oid))
4193 ; /* ok, the textual part looks sane */
4194 else
4195 return error(_("sha1 information is lacking or "
4196 "useless for submodule %s"), name);
4197 } else if (!repo_get_oid_blob(the_repository, patch->old_oid_prefix, &oid)) {
4198 ; /* ok */
4199 } else if (!patch->lines_added && !patch->lines_deleted) {
4200 /* mode-only change: update the current */
4201 if (get_current_oid(state, patch->old_name, &oid))
4202 return error(_("mode change for %s, which is not "
4203 "in current HEAD"), name);
4204 } else
4205 return error(_("sha1 information is lacking or useless "
4206 "(%s)."), name);
4208 ce = make_cache_entry(&result, patch->old_mode, &oid, name, 0, 0);
4209 if (!ce)
4210 return error(_("make_cache_entry failed for path '%s'"),
4211 name);
4212 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) {
4213 discard_cache_entry(ce);
4214 return error(_("could not add %s to temporary index"),
4215 name);
4219 hold_lock_file_for_update(&lock, state->fake_ancestor, LOCK_DIE_ON_ERROR);
4220 res = write_locked_index(&result, &lock, COMMIT_LOCK);
4221 discard_index(&result);
4223 if (res)
4224 return error(_("could not write temporary index to %s"),
4225 state->fake_ancestor);
4227 return 0;
4230 static void stat_patch_list(struct apply_state *state, struct patch *patch)
4232 int files, adds, dels;
4234 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
4235 files++;
4236 adds += patch->lines_added;
4237 dels += patch->lines_deleted;
4238 show_stats(state, patch);
4241 print_stat_summary(stdout, files, adds, dels);
4244 static void numstat_patch_list(struct apply_state *state,
4245 struct patch *patch)
4247 for ( ; patch; patch = patch->next) {
4248 const char *name;
4249 name = patch->new_name ? patch->new_name : patch->old_name;
4250 if (patch->is_binary)
4251 printf("-\t-\t");
4252 else
4253 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
4254 write_name_quoted(name, stdout, state->line_termination);
4258 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
4260 if (mode)
4261 printf(" %s mode %06o %s\n", newdelete, mode, name);
4262 else
4263 printf(" %s %s\n", newdelete, name);
4266 static void show_mode_change(struct patch *p, int show_name)
4268 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
4269 if (show_name)
4270 printf(" mode change %06o => %06o %s\n",
4271 p->old_mode, p->new_mode, p->new_name);
4272 else
4273 printf(" mode change %06o => %06o\n",
4274 p->old_mode, p->new_mode);
4278 static void show_rename_copy(struct patch *p)
4280 const char *renamecopy = p->is_rename ? "rename" : "copy";
4281 const char *old_name, *new_name;
4283 /* Find common prefix */
4284 old_name = p->old_name;
4285 new_name = p->new_name;
4286 while (1) {
4287 const char *slash_old, *slash_new;
4288 slash_old = strchr(old_name, '/');
4289 slash_new = strchr(new_name, '/');
4290 if (!slash_old ||
4291 !slash_new ||
4292 slash_old - old_name != slash_new - new_name ||
4293 memcmp(old_name, new_name, slash_new - new_name))
4294 break;
4295 old_name = slash_old + 1;
4296 new_name = slash_new + 1;
4298 /* p->old_name through old_name is the common prefix, and old_name and
4299 * new_name through the end of names are renames
4301 if (old_name != p->old_name)
4302 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
4303 (int)(old_name - p->old_name), p->old_name,
4304 old_name, new_name, p->score);
4305 else
4306 printf(" %s %s => %s (%d%%)\n", renamecopy,
4307 p->old_name, p->new_name, p->score);
4308 show_mode_change(p, 0);
4311 static void summary_patch_list(struct patch *patch)
4313 struct patch *p;
4315 for (p = patch; p; p = p->next) {
4316 if (p->is_new)
4317 show_file_mode_name("create", p->new_mode, p->new_name);
4318 else if (p->is_delete)
4319 show_file_mode_name("delete", p->old_mode, p->old_name);
4320 else {
4321 if (p->is_rename || p->is_copy)
4322 show_rename_copy(p);
4323 else {
4324 if (p->score) {
4325 printf(" rewrite %s (%d%%)\n",
4326 p->new_name, p->score);
4327 show_mode_change(p, 0);
4329 else
4330 show_mode_change(p, 1);
4336 static void patch_stats(struct apply_state *state, struct patch *patch)
4338 int lines = patch->lines_added + patch->lines_deleted;
4340 if (lines > state->max_change)
4341 state->max_change = lines;
4342 if (patch->old_name) {
4343 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
4344 if (!len)
4345 len = strlen(patch->old_name);
4346 if (len > state->max_len)
4347 state->max_len = len;
4349 if (patch->new_name) {
4350 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
4351 if (!len)
4352 len = strlen(patch->new_name);
4353 if (len > state->max_len)
4354 state->max_len = len;
4358 static int remove_file(struct apply_state *state, struct patch *patch, int rmdir_empty)
4360 if (state->update_index && !state->ita_only) {
4361 if (remove_file_from_index(state->repo->index, patch->old_name) < 0)
4362 return error(_("unable to remove %s from index"), patch->old_name);
4364 if (!state->cached) {
4365 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
4366 remove_path(patch->old_name);
4369 return 0;
4372 static int add_index_file(struct apply_state *state,
4373 const char *path,
4374 unsigned mode,
4375 void *buf,
4376 unsigned long size)
4378 struct stat st;
4379 struct cache_entry *ce;
4380 int namelen = strlen(path);
4382 ce = make_empty_cache_entry(state->repo->index, namelen);
4383 memcpy(ce->name, path, namelen);
4384 ce->ce_mode = create_ce_mode(mode);
4385 ce->ce_flags = create_ce_flags(0);
4386 ce->ce_namelen = namelen;
4387 if (state->ita_only) {
4388 ce->ce_flags |= CE_INTENT_TO_ADD;
4389 set_object_name_for_intent_to_add_entry(ce);
4390 } else if (S_ISGITLINK(mode)) {
4391 const char *s;
4393 if (!skip_prefix(buf, "Subproject commit ", &s) ||
4394 get_oid_hex(s, &ce->oid)) {
4395 discard_cache_entry(ce);
4396 return error(_("corrupt patch for submodule %s"), path);
4398 } else {
4399 if (!state->cached) {
4400 if (lstat(path, &st) < 0) {
4401 discard_cache_entry(ce);
4402 return error_errno(_("unable to stat newly "
4403 "created file '%s'"),
4404 path);
4406 fill_stat_cache_info(state->repo->index, ce, &st);
4408 if (write_object_file(buf, size, OBJ_BLOB, &ce->oid) < 0) {
4409 discard_cache_entry(ce);
4410 return error(_("unable to create backing store "
4411 "for newly created file %s"), path);
4414 if (add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) < 0) {
4415 discard_cache_entry(ce);
4416 return error(_("unable to add cache entry for %s"), path);
4419 return 0;
4423 * Returns:
4424 * -1 if an unrecoverable error happened
4425 * 0 if everything went well
4426 * 1 if a recoverable error happened
4428 static int try_create_file(struct apply_state *state, const char *path,
4429 unsigned int mode, const char *buf,
4430 unsigned long size)
4432 int fd, res;
4433 struct strbuf nbuf = STRBUF_INIT;
4435 if (S_ISGITLINK(mode)) {
4436 struct stat st;
4437 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
4438 return 0;
4439 return !!mkdir(path, 0777);
4442 if (has_symlinks && S_ISLNK(mode))
4443 /* Although buf:size is counted string, it also is NUL
4444 * terminated.
4446 return !!symlink(buf, path);
4448 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
4449 if (fd < 0)
4450 return 1;
4452 if (convert_to_working_tree(state->repo->index, path, buf, size, &nbuf, NULL)) {
4453 size = nbuf.len;
4454 buf = nbuf.buf;
4457 res = write_in_full(fd, buf, size) < 0;
4458 if (res)
4459 error_errno(_("failed to write to '%s'"), path);
4460 strbuf_release(&nbuf);
4462 if (close(fd) < 0 && !res)
4463 return error_errno(_("closing file '%s'"), path);
4465 return res ? -1 : 0;
4469 * We optimistically assume that the directories exist,
4470 * which is true 99% of the time anyway. If they don't,
4471 * we create them and try again.
4473 * Returns:
4474 * -1 on error
4475 * 0 otherwise
4477 static int create_one_file(struct apply_state *state,
4478 char *path,
4479 unsigned mode,
4480 const char *buf,
4481 unsigned long size)
4483 char *newpath = NULL;
4484 int res;
4486 if (state->cached)
4487 return 0;
4490 * We already try to detect whether files are beyond a symlink in our
4491 * up-front checks. But in the case where symlinks are created by any
4492 * of the intermediate hunks it can happen that our up-front checks
4493 * didn't yet see the symlink, but at the point of arriving here there
4494 * in fact is one. We thus repeat the check for symlinks here.
4496 * Note that this does not make the up-front check obsolete as the
4497 * failure mode is different:
4499 * - The up-front checks cause us to abort before we have written
4500 * anything into the working directory. So when we exit this way the
4501 * working directory remains clean.
4503 * - The checks here happen in the middle of the action where we have
4504 * already started to apply the patch. The end result will be a dirty
4505 * working directory.
4507 * Ideally, we should update the up-front checks to catch what would
4508 * happen when we apply the patch before we damage the working tree.
4509 * We have all the information necessary to do so. But for now, as a
4510 * part of embargoed security work, having this check would serve as a
4511 * reasonable first step.
4513 if (path_is_beyond_symlink(state, path))
4514 return error(_("affected file '%s' is beyond a symbolic link"), path);
4516 res = try_create_file(state, path, mode, buf, size);
4517 if (res < 0)
4518 return -1;
4519 if (!res)
4520 return 0;
4522 if (errno == ENOENT) {
4523 if (safe_create_leading_directories_no_share(path))
4524 return 0;
4525 res = try_create_file(state, path, mode, buf, size);
4526 if (res < 0)
4527 return -1;
4528 if (!res)
4529 return 0;
4532 if (errno == EEXIST || errno == EACCES) {
4533 /* We may be trying to create a file where a directory
4534 * used to be.
4536 struct stat st;
4537 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
4538 errno = EEXIST;
4541 if (errno == EEXIST) {
4542 unsigned int nr = getpid();
4544 for (;;) {
4545 newpath = mkpathdup("%s~%u", path, nr);
4546 res = try_create_file(state, newpath, mode, buf, size);
4547 if (res < 0)
4548 goto out;
4549 if (!res) {
4550 if (!rename(newpath, path))
4551 goto out;
4552 unlink_or_warn(newpath);
4553 break;
4555 if (errno != EEXIST)
4556 break;
4557 ++nr;
4558 FREE_AND_NULL(newpath);
4561 res = error_errno(_("unable to write file '%s' mode %o"), path, mode);
4562 out:
4563 free(newpath);
4564 return res;
4567 static int add_conflicted_stages_file(struct apply_state *state,
4568 struct patch *patch)
4570 int stage, namelen;
4571 unsigned mode;
4572 struct cache_entry *ce;
4574 if (!state->update_index)
4575 return 0;
4576 namelen = strlen(patch->new_name);
4577 mode = patch->new_mode ? patch->new_mode : (S_IFREG | 0644);
4579 remove_file_from_index(state->repo->index, patch->new_name);
4580 for (stage = 1; stage < 4; stage++) {
4581 if (is_null_oid(&patch->threeway_stage[stage - 1]))
4582 continue;
4583 ce = make_empty_cache_entry(state->repo->index, namelen);
4584 memcpy(ce->name, patch->new_name, namelen);
4585 ce->ce_mode = create_ce_mode(mode);
4586 ce->ce_flags = create_ce_flags(stage);
4587 ce->ce_namelen = namelen;
4588 oidcpy(&ce->oid, &patch->threeway_stage[stage - 1]);
4589 if (add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) < 0) {
4590 discard_cache_entry(ce);
4591 return error(_("unable to add cache entry for %s"),
4592 patch->new_name);
4596 return 0;
4599 static int create_file(struct apply_state *state, struct patch *patch)
4601 char *path = patch->new_name;
4602 unsigned mode = patch->new_mode;
4603 unsigned long size = patch->resultsize;
4604 char *buf = patch->result;
4606 if (!mode)
4607 mode = S_IFREG | 0644;
4608 if (create_one_file(state, path, mode, buf, size))
4609 return -1;
4611 if (patch->conflicted_threeway)
4612 return add_conflicted_stages_file(state, patch);
4613 else if (state->update_index)
4614 return add_index_file(state, path, mode, buf, size);
4615 return 0;
4618 /* phase zero is to remove, phase one is to create */
4619 static int write_out_one_result(struct apply_state *state,
4620 struct patch *patch,
4621 int phase)
4623 if (patch->is_delete > 0) {
4624 if (phase == 0)
4625 return remove_file(state, patch, 1);
4626 return 0;
4628 if (patch->is_new > 0 || patch->is_copy) {
4629 if (phase == 1)
4630 return create_file(state, patch);
4631 return 0;
4634 * Rename or modification boils down to the same
4635 * thing: remove the old, write the new
4637 if (phase == 0)
4638 return remove_file(state, patch, patch->is_rename);
4639 if (phase == 1)
4640 return create_file(state, patch);
4641 return 0;
4644 static int write_out_one_reject(struct apply_state *state, struct patch *patch)
4646 FILE *rej;
4647 char *namebuf;
4648 struct fragment *frag;
4649 int fd, cnt = 0;
4650 struct strbuf sb = STRBUF_INIT;
4652 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
4653 if (!frag->rejected)
4654 continue;
4655 cnt++;
4658 if (!cnt) {
4659 if (state->apply_verbosity > verbosity_normal)
4660 say_patch_name(stderr,
4661 _("Applied patch %s cleanly."), patch);
4662 return 0;
4665 /* This should not happen, because a removal patch that leaves
4666 * contents are marked "rejected" at the patch level.
4668 if (!patch->new_name)
4669 die(_("internal error"));
4671 /* Say this even without --verbose */
4672 strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",
4673 "Applying patch %%s with %d rejects...",
4674 cnt),
4675 cnt);
4676 if (state->apply_verbosity > verbosity_silent)
4677 say_patch_name(stderr, sb.buf, patch);
4678 strbuf_release(&sb);
4680 namebuf = xstrfmt("%s.rej", patch->new_name);
4682 fd = open(namebuf, O_CREAT | O_EXCL | O_WRONLY, 0666);
4683 if (fd < 0) {
4684 if (errno != EEXIST) {
4685 error_errno(_("cannot open %s"), namebuf);
4686 goto error;
4688 if (unlink(namebuf)) {
4689 error_errno(_("cannot unlink '%s'"), namebuf);
4690 goto error;
4692 fd = open(namebuf, O_CREAT | O_EXCL | O_WRONLY, 0666);
4693 if (fd < 0) {
4694 error_errno(_("cannot open %s"), namebuf);
4695 goto error;
4698 rej = fdopen(fd, "w");
4699 if (!rej) {
4700 error_errno(_("cannot open %s"), namebuf);
4701 close(fd);
4702 goto error;
4705 /* Normal git tools never deal with .rej, so do not pretend
4706 * this is a git patch by saying --git or giving extended
4707 * headers. While at it, maybe please "kompare" that wants
4708 * the trailing TAB and some garbage at the end of line ;-).
4710 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
4711 patch->new_name, patch->new_name);
4712 for (cnt = 1, frag = patch->fragments;
4713 frag;
4714 cnt++, frag = frag->next) {
4715 if (!frag->rejected) {
4716 if (state->apply_verbosity > verbosity_silent)
4717 fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);
4718 continue;
4720 if (state->apply_verbosity > verbosity_silent)
4721 fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);
4722 fprintf(rej, "%.*s", frag->size, frag->patch);
4723 if (frag->patch[frag->size-1] != '\n')
4724 fputc('\n', rej);
4726 fclose(rej);
4727 error:
4728 free(namebuf);
4729 return -1;
4733 * Returns:
4734 * -1 if an error happened
4735 * 0 if the patch applied cleanly
4736 * 1 if the patch did not apply cleanly
4738 static int write_out_results(struct apply_state *state, struct patch *list)
4740 int phase;
4741 int errs = 0;
4742 struct patch *l;
4743 struct string_list cpath = STRING_LIST_INIT_DUP;
4745 for (phase = 0; phase < 2; phase++) {
4746 l = list;
4747 while (l) {
4748 if (l->rejected)
4749 errs = 1;
4750 else {
4751 if (write_out_one_result(state, l, phase)) {
4752 string_list_clear(&cpath, 0);
4753 return -1;
4755 if (phase == 1) {
4756 if (write_out_one_reject(state, l))
4757 errs = 1;
4758 if (l->conflicted_threeway) {
4759 string_list_append(&cpath, l->new_name);
4760 errs = 1;
4764 l = l->next;
4768 if (cpath.nr) {
4769 struct string_list_item *item;
4771 string_list_sort(&cpath);
4772 if (state->apply_verbosity > verbosity_silent) {
4773 for_each_string_list_item(item, &cpath)
4774 fprintf(stderr, "U %s\n", item->string);
4776 string_list_clear(&cpath, 0);
4779 * rerere relies on the partially merged result being in the working
4780 * tree with conflict markers, but that isn't written with --cached.
4782 if (!state->cached)
4783 repo_rerere(state->repo, 0);
4786 return errs;
4790 * Try to apply a patch.
4792 * Returns:
4793 * -128 if a bad error happened (like patch unreadable)
4794 * -1 if patch did not apply and user cannot deal with it
4795 * 0 if the patch applied
4796 * 1 if the patch did not apply but user might fix it
4798 static int apply_patch(struct apply_state *state,
4799 int fd,
4800 const char *filename,
4801 int options)
4803 size_t offset;
4804 struct strbuf buf = STRBUF_INIT; /* owns the patch text */
4805 struct patch *list = NULL, **listp = &list;
4806 int skipped_patch = 0;
4807 int res = 0;
4808 int flush_attributes = 0;
4810 state->patch_input_file = filename;
4811 if (read_patch_file(&buf, fd) < 0)
4812 return -128;
4813 offset = 0;
4814 while (offset < buf.len) {
4815 struct patch *patch;
4816 int nr;
4818 CALLOC_ARRAY(patch, 1);
4819 patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF);
4820 patch->recount = !!(options & APPLY_OPT_RECOUNT);
4821 nr = parse_chunk(state, buf.buf + offset, buf.len - offset, patch);
4822 if (nr < 0) {
4823 free_patch(patch);
4824 if (nr == -128) {
4825 res = -128;
4826 goto end;
4828 break;
4830 if (state->apply_in_reverse)
4831 reverse_patches(patch);
4832 if (use_patch(state, patch)) {
4833 patch_stats(state, patch);
4834 if (!list || !state->apply_in_reverse) {
4835 *listp = patch;
4836 listp = &patch->next;
4837 } else {
4838 patch->next = list;
4839 list = patch;
4842 if ((patch->new_name &&
4843 ends_with_path_components(patch->new_name,
4844 GITATTRIBUTES_FILE)) ||
4845 (patch->old_name &&
4846 ends_with_path_components(patch->old_name,
4847 GITATTRIBUTES_FILE)))
4848 flush_attributes = 1;
4850 else {
4851 if (state->apply_verbosity > verbosity_normal)
4852 say_patch_name(stderr, _("Skipped patch '%s'."), patch);
4853 free_patch(patch);
4854 skipped_patch++;
4856 offset += nr;
4859 if (!list && !skipped_patch) {
4860 if (!state->allow_empty) {
4861 error(_("No valid patches in input (allow with \"--allow-empty\")"));
4862 res = -128;
4864 goto end;
4867 if (state->whitespace_error && (state->ws_error_action == die_on_ws_error))
4868 state->apply = 0;
4870 state->update_index = (state->check_index || state->ita_only) && state->apply;
4871 if (state->update_index && !is_lock_file_locked(&state->lock_file)) {
4872 if (state->index_file)
4873 hold_lock_file_for_update(&state->lock_file,
4874 state->index_file,
4875 LOCK_DIE_ON_ERROR);
4876 else
4877 repo_hold_locked_index(state->repo, &state->lock_file,
4878 LOCK_DIE_ON_ERROR);
4881 if (state->check_index && read_apply_cache(state) < 0) {
4882 error(_("unable to read index file"));
4883 res = -128;
4884 goto end;
4887 if (state->check || state->apply) {
4888 int r = check_patch_list(state, list);
4889 if (r == -128) {
4890 res = -128;
4891 goto end;
4893 if (r < 0 && !state->apply_with_reject) {
4894 res = -1;
4895 goto end;
4899 if (state->apply) {
4900 int write_res = write_out_results(state, list);
4901 if (write_res < 0) {
4902 res = -128;
4903 goto end;
4905 if (write_res > 0) {
4906 /* with --3way, we still need to write the index out */
4907 res = state->apply_with_reject ? -1 : 1;
4908 goto end;
4912 if (state->fake_ancestor &&
4913 build_fake_ancestor(state, list)) {
4914 res = -128;
4915 goto end;
4918 if (state->diffstat && state->apply_verbosity > verbosity_silent)
4919 stat_patch_list(state, list);
4921 if (state->numstat && state->apply_verbosity > verbosity_silent)
4922 numstat_patch_list(state, list);
4924 if (state->summary && state->apply_verbosity > verbosity_silent)
4925 summary_patch_list(list);
4927 if (flush_attributes)
4928 reset_parsed_attributes();
4929 end:
4930 free_patch_list(list);
4931 strbuf_release(&buf);
4932 string_list_clear(&state->fn_table, 0);
4933 return res;
4936 static int apply_option_parse_exclude(const struct option *opt,
4937 const char *arg, int unset)
4939 struct apply_state *state = opt->value;
4941 BUG_ON_OPT_NEG(unset);
4943 add_name_limit(state, arg, 1);
4944 return 0;
4947 static int apply_option_parse_include(const struct option *opt,
4948 const char *arg, int unset)
4950 struct apply_state *state = opt->value;
4952 BUG_ON_OPT_NEG(unset);
4954 add_name_limit(state, arg, 0);
4955 state->has_include = 1;
4956 return 0;
4959 static int apply_option_parse_p(const struct option *opt,
4960 const char *arg,
4961 int unset)
4963 struct apply_state *state = opt->value;
4965 BUG_ON_OPT_NEG(unset);
4967 state->p_value = atoi(arg);
4968 state->p_value_known = 1;
4969 return 0;
4972 static int apply_option_parse_space_change(const struct option *opt,
4973 const char *arg, int unset)
4975 struct apply_state *state = opt->value;
4977 BUG_ON_OPT_ARG(arg);
4979 if (unset)
4980 state->ws_ignore_action = ignore_ws_none;
4981 else
4982 state->ws_ignore_action = ignore_ws_change;
4983 return 0;
4986 static int apply_option_parse_whitespace(const struct option *opt,
4987 const char *arg, int unset)
4989 struct apply_state *state = opt->value;
4991 BUG_ON_OPT_NEG(unset);
4993 state->whitespace_option = arg;
4994 if (parse_whitespace_option(state, arg))
4995 return -1;
4996 return 0;
4999 static int apply_option_parse_directory(const struct option *opt,
5000 const char *arg, int unset)
5002 struct apply_state *state = opt->value;
5004 BUG_ON_OPT_NEG(unset);
5006 strbuf_reset(&state->root);
5007 strbuf_addstr(&state->root, arg);
5008 strbuf_complete(&state->root, '/');
5009 return 0;
5012 int apply_all_patches(struct apply_state *state,
5013 int argc,
5014 const char **argv,
5015 int options)
5017 int i;
5018 int res;
5019 int errs = 0;
5020 int read_stdin = 1;
5022 for (i = 0; i < argc; i++) {
5023 const char *arg = argv[i];
5024 char *to_free = NULL;
5025 int fd;
5027 if (!strcmp(arg, "-")) {
5028 res = apply_patch(state, 0, "<stdin>", options);
5029 if (res < 0)
5030 goto end;
5031 errs |= res;
5032 read_stdin = 0;
5033 continue;
5034 } else
5035 arg = to_free = prefix_filename(state->prefix, arg);
5037 fd = open(arg, O_RDONLY);
5038 if (fd < 0) {
5039 error(_("can't open patch '%s': %s"), arg, strerror(errno));
5040 res = -128;
5041 free(to_free);
5042 goto end;
5044 read_stdin = 0;
5045 set_default_whitespace_mode(state);
5046 res = apply_patch(state, fd, arg, options);
5047 close(fd);
5048 free(to_free);
5049 if (res < 0)
5050 goto end;
5051 errs |= res;
5053 set_default_whitespace_mode(state);
5054 if (read_stdin) {
5055 res = apply_patch(state, 0, "<stdin>", options);
5056 if (res < 0)
5057 goto end;
5058 errs |= res;
5061 if (state->whitespace_error) {
5062 if (state->squelch_whitespace_errors &&
5063 state->squelch_whitespace_errors < state->whitespace_error) {
5064 int squelched =
5065 state->whitespace_error - state->squelch_whitespace_errors;
5066 warning(Q_("squelched %d whitespace error",
5067 "squelched %d whitespace errors",
5068 squelched),
5069 squelched);
5071 if (state->ws_error_action == die_on_ws_error) {
5072 error(Q_("%d line adds whitespace errors.",
5073 "%d lines add whitespace errors.",
5074 state->whitespace_error),
5075 state->whitespace_error);
5076 res = -128;
5077 goto end;
5079 if (state->applied_after_fixing_ws && state->apply)
5080 warning(Q_("%d line applied after"
5081 " fixing whitespace errors.",
5082 "%d lines applied after"
5083 " fixing whitespace errors.",
5084 state->applied_after_fixing_ws),
5085 state->applied_after_fixing_ws);
5086 else if (state->whitespace_error)
5087 warning(Q_("%d line adds whitespace errors.",
5088 "%d lines add whitespace errors.",
5089 state->whitespace_error),
5090 state->whitespace_error);
5093 if (state->update_index) {
5094 res = write_locked_index(state->repo->index, &state->lock_file, COMMIT_LOCK);
5095 if (res) {
5096 error(_("Unable to write new index file"));
5097 res = -128;
5098 goto end;
5102 res = !!errs;
5104 end:
5105 rollback_lock_file(&state->lock_file);
5107 if (state->apply_verbosity <= verbosity_silent) {
5108 set_error_routine(state->saved_error_routine);
5109 set_warn_routine(state->saved_warn_routine);
5112 if (res > -1)
5113 return res;
5114 return (res == -1 ? 1 : 128);
5117 int apply_parse_options(int argc, const char **argv,
5118 struct apply_state *state,
5119 int *force_apply, int *options,
5120 const char * const *apply_usage)
5122 struct option builtin_apply_options[] = {
5123 OPT_CALLBACK_F(0, "exclude", state, N_("path"),
5124 N_("don't apply changes matching the given path"),
5125 PARSE_OPT_NONEG, apply_option_parse_exclude),
5126 OPT_CALLBACK_F(0, "include", state, N_("path"),
5127 N_("apply changes matching the given path"),
5128 PARSE_OPT_NONEG, apply_option_parse_include),
5129 OPT_CALLBACK('p', NULL, state, N_("num"),
5130 N_("remove <num> leading slashes from traditional diff paths"),
5131 apply_option_parse_p),
5132 OPT_BOOL(0, "no-add", &state->no_add,
5133 N_("ignore additions made by the patch")),
5134 OPT_BOOL(0, "stat", &state->diffstat,
5135 N_("instead of applying the patch, output diffstat for the input")),
5136 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
5137 OPT_NOOP_NOARG(0, "binary"),
5138 OPT_BOOL(0, "numstat", &state->numstat,
5139 N_("show number of added and deleted lines in decimal notation")),
5140 OPT_BOOL(0, "summary", &state->summary,
5141 N_("instead of applying the patch, output a summary for the input")),
5142 OPT_BOOL(0, "check", &state->check,
5143 N_("instead of applying the patch, see if the patch is applicable")),
5144 OPT_BOOL(0, "index", &state->check_index,
5145 N_("make sure the patch is applicable to the current index")),
5146 OPT_BOOL('N', "intent-to-add", &state->ita_only,
5147 N_("mark new files with `git add --intent-to-add`")),
5148 OPT_BOOL(0, "cached", &state->cached,
5149 N_("apply a patch without touching the working tree")),
5150 OPT_BOOL_F(0, "unsafe-paths", &state->unsafe_paths,
5151 N_("accept a patch that touches outside the working area"),
5152 PARSE_OPT_NOCOMPLETE),
5153 OPT_BOOL(0, "apply", force_apply,
5154 N_("also apply the patch (use with --stat/--summary/--check)")),
5155 OPT_BOOL('3', "3way", &state->threeway,
5156 N_( "attempt three-way merge, fall back on normal patch if that fails")),
5157 OPT_SET_INT_F(0, "ours", &state->merge_variant,
5158 N_("for conflicts, use our version"),
5159 XDL_MERGE_FAVOR_OURS, PARSE_OPT_NONEG),
5160 OPT_SET_INT_F(0, "theirs", &state->merge_variant,
5161 N_("for conflicts, use their version"),
5162 XDL_MERGE_FAVOR_THEIRS, PARSE_OPT_NONEG),
5163 OPT_SET_INT_F(0, "union", &state->merge_variant,
5164 N_("for conflicts, use a union version"),
5165 XDL_MERGE_FAVOR_UNION, PARSE_OPT_NONEG),
5166 OPT_FILENAME(0, "build-fake-ancestor", &state->fake_ancestor,
5167 N_("build a temporary index based on embedded index information")),
5168 /* Think twice before adding "--nul" synonym to this */
5169 OPT_SET_INT('z', NULL, &state->line_termination,
5170 N_("paths are separated with NUL character"), '\0'),
5171 OPT_INTEGER('C', NULL, &state->p_context,
5172 N_("ensure at least <n> lines of context match")),
5173 OPT_CALLBACK(0, "whitespace", state, N_("action"),
5174 N_("detect new or modified lines that have whitespace errors"),
5175 apply_option_parse_whitespace),
5176 OPT_CALLBACK_F(0, "ignore-space-change", state, NULL,
5177 N_("ignore changes in whitespace when finding context"),
5178 PARSE_OPT_NOARG, apply_option_parse_space_change),
5179 OPT_CALLBACK_F(0, "ignore-whitespace", state, NULL,
5180 N_("ignore changes in whitespace when finding context"),
5181 PARSE_OPT_NOARG, apply_option_parse_space_change),
5182 OPT_BOOL('R', "reverse", &state->apply_in_reverse,
5183 N_("apply the patch in reverse")),
5184 OPT_BOOL(0, "unidiff-zero", &state->unidiff_zero,
5185 N_("don't expect at least one line of context")),
5186 OPT_BOOL(0, "reject", &state->apply_with_reject,
5187 N_("leave the rejected hunks in corresponding *.rej files")),
5188 OPT_BOOL(0, "allow-overlap", &state->allow_overlap,
5189 N_("allow overlapping hunks")),
5190 OPT__VERBOSITY(&state->apply_verbosity),
5191 OPT_BIT(0, "inaccurate-eof", options,
5192 N_("tolerate incorrectly detected missing new-line at the end of file"),
5193 APPLY_OPT_INACCURATE_EOF),
5194 OPT_BIT(0, "recount", options,
5195 N_("do not trust the line counts in the hunk headers"),
5196 APPLY_OPT_RECOUNT),
5197 OPT_CALLBACK(0, "directory", state, N_("root"),
5198 N_("prepend <root> to all filenames"),
5199 apply_option_parse_directory),
5200 OPT_BOOL(0, "allow-empty", &state->allow_empty,
5201 N_("don't return error for empty patches")),
5202 OPT_END()
5205 argc = parse_options(argc, argv, state->prefix, builtin_apply_options, apply_usage, 0);
5207 if (state->merge_variant && !state->threeway)
5208 die(_("--ours, --theirs, and --union require --3way"));
5210 return argc;