treewide: remove cache.h inclusion due to object-file.h changes
[alt-git.git] / apply.c
blob2868cef5ddd91efb65817b0a1604fb6ba4c7bc50
1 /*
2 * apply.c
4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
8 */
10 #include "cache.h"
11 #include "abspath.h"
12 #include "alloc.h"
13 #include "config.h"
14 #include "object-store.h"
15 #include "blob.h"
16 #include "delta.h"
17 #include "diff.h"
18 #include "dir.h"
19 #include "environment.h"
20 #include "gettext.h"
21 #include "hex.h"
22 #include "xdiff-interface.h"
23 #include "ll-merge.h"
24 #include "lockfile.h"
25 #include "object-name.h"
26 #include "object-file.h"
27 #include "parse-options.h"
28 #include "quote.h"
29 #include "rerere.h"
30 #include "apply.h"
31 #include "entry.h"
32 #include "setup.h"
33 #include "wrapper.h"
35 struct gitdiff_data {
36 struct strbuf *root;
37 int linenr;
38 int p_value;
41 static void git_apply_config(void)
43 git_config_get_string("apply.whitespace", &apply_default_whitespace);
44 git_config_get_string("apply.ignorewhitespace", &apply_default_ignorewhitespace);
45 git_config(git_xmerge_config, NULL);
48 static int parse_whitespace_option(struct apply_state *state, const char *option)
50 if (!option) {
51 state->ws_error_action = warn_on_ws_error;
52 return 0;
54 if (!strcmp(option, "warn")) {
55 state->ws_error_action = warn_on_ws_error;
56 return 0;
58 if (!strcmp(option, "nowarn")) {
59 state->ws_error_action = nowarn_ws_error;
60 return 0;
62 if (!strcmp(option, "error")) {
63 state->ws_error_action = die_on_ws_error;
64 return 0;
66 if (!strcmp(option, "error-all")) {
67 state->ws_error_action = die_on_ws_error;
68 state->squelch_whitespace_errors = 0;
69 return 0;
71 if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
72 state->ws_error_action = correct_ws_error;
73 return 0;
76 * Please update $__git_whitespacelist in git-completion.bash
77 * when you add new options.
79 return error(_("unrecognized whitespace option '%s'"), option);
82 static int parse_ignorewhitespace_option(struct apply_state *state,
83 const char *option)
85 if (!option || !strcmp(option, "no") ||
86 !strcmp(option, "false") || !strcmp(option, "never") ||
87 !strcmp(option, "none")) {
88 state->ws_ignore_action = ignore_ws_none;
89 return 0;
91 if (!strcmp(option, "change")) {
92 state->ws_ignore_action = ignore_ws_change;
93 return 0;
95 return error(_("unrecognized whitespace ignore option '%s'"), option);
98 int init_apply_state(struct apply_state *state,
99 struct repository *repo,
100 const char *prefix)
102 memset(state, 0, sizeof(*state));
103 state->prefix = prefix;
104 state->repo = repo;
105 state->apply = 1;
106 state->line_termination = '\n';
107 state->p_value = 1;
108 state->p_context = UINT_MAX;
109 state->squelch_whitespace_errors = 5;
110 state->ws_error_action = warn_on_ws_error;
111 state->ws_ignore_action = ignore_ws_none;
112 state->linenr = 1;
113 string_list_init_nodup(&state->fn_table);
114 string_list_init_nodup(&state->limit_by_name);
115 strset_init(&state->removed_symlinks);
116 strset_init(&state->kept_symlinks);
117 strbuf_init(&state->root, 0);
119 git_apply_config();
120 if (apply_default_whitespace && parse_whitespace_option(state, apply_default_whitespace))
121 return -1;
122 if (apply_default_ignorewhitespace && parse_ignorewhitespace_option(state, apply_default_ignorewhitespace))
123 return -1;
124 return 0;
127 void clear_apply_state(struct apply_state *state)
129 string_list_clear(&state->limit_by_name, 0);
130 strset_clear(&state->removed_symlinks);
131 strset_clear(&state->kept_symlinks);
132 strbuf_release(&state->root);
134 /* &state->fn_table is cleared at the end of apply_patch() */
137 static void mute_routine(const char *msg UNUSED, va_list params UNUSED)
139 /* do nothing */
142 int check_apply_state(struct apply_state *state, int force_apply)
144 int is_not_gitdir = !startup_info->have_repository;
146 if (state->apply_with_reject && state->threeway)
147 return error(_("options '%s' and '%s' cannot be used together"), "--reject", "--3way");
148 if (state->threeway) {
149 if (is_not_gitdir)
150 return error(_("'%s' outside a repository"), "--3way");
151 state->check_index = 1;
153 if (state->apply_with_reject) {
154 state->apply = 1;
155 if (state->apply_verbosity == verbosity_normal)
156 state->apply_verbosity = verbosity_verbose;
158 if (!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor))
159 state->apply = 0;
160 if (state->check_index && is_not_gitdir)
161 return error(_("'%s' outside a repository"), "--index");
162 if (state->cached) {
163 if (is_not_gitdir)
164 return error(_("'%s' outside a repository"), "--cached");
165 state->check_index = 1;
167 if (state->ita_only && (state->check_index || is_not_gitdir))
168 state->ita_only = 0;
169 if (state->check_index)
170 state->unsafe_paths = 0;
172 if (state->apply_verbosity <= verbosity_silent) {
173 state->saved_error_routine = get_error_routine();
174 state->saved_warn_routine = get_warn_routine();
175 set_error_routine(mute_routine);
176 set_warn_routine(mute_routine);
179 return 0;
182 static void set_default_whitespace_mode(struct apply_state *state)
184 if (!state->whitespace_option && !apply_default_whitespace)
185 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error);
189 * This represents one "hunk" from a patch, starting with
190 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
191 * patch text is pointed at by patch, and its byte length
192 * is stored in size. leading and trailing are the number
193 * of context lines.
195 struct fragment {
196 unsigned long leading, trailing;
197 unsigned long oldpos, oldlines;
198 unsigned long newpos, newlines;
200 * 'patch' is usually borrowed from buf in apply_patch(),
201 * but some codepaths store an allocated buffer.
203 const char *patch;
204 unsigned free_patch:1,
205 rejected:1;
206 int size;
207 int linenr;
208 struct fragment *next;
212 * When dealing with a binary patch, we reuse "leading" field
213 * to store the type of the binary hunk, either deflated "delta"
214 * or deflated "literal".
216 #define binary_patch_method leading
217 #define BINARY_DELTA_DEFLATED 1
218 #define BINARY_LITERAL_DEFLATED 2
220 static void free_fragment_list(struct fragment *list)
222 while (list) {
223 struct fragment *next = list->next;
224 if (list->free_patch)
225 free((char *)list->patch);
226 free(list);
227 list = next;
231 void release_patch(struct patch *patch)
233 free_fragment_list(patch->fragments);
234 free(patch->def_name);
235 free(patch->old_name);
236 free(patch->new_name);
237 free(patch->result);
240 static void free_patch(struct patch *patch)
242 release_patch(patch);
243 free(patch);
246 static void free_patch_list(struct patch *list)
248 while (list) {
249 struct patch *next = list->next;
250 free_patch(list);
251 list = next;
256 * A line in a file, len-bytes long (includes the terminating LF,
257 * except for an incomplete line at the end if the file ends with
258 * one), and its contents hashes to 'hash'.
260 struct line {
261 size_t len;
262 unsigned hash : 24;
263 unsigned flag : 8;
264 #define LINE_COMMON 1
265 #define LINE_PATCHED 2
269 * This represents a "file", which is an array of "lines".
271 struct image {
272 char *buf;
273 size_t len;
274 size_t nr;
275 size_t alloc;
276 struct line *line_allocated;
277 struct line *line;
280 static uint32_t hash_line(const char *cp, size_t len)
282 size_t i;
283 uint32_t h;
284 for (i = 0, h = 0; i < len; i++) {
285 if (!isspace(cp[i])) {
286 h = h * 3 + (cp[i] & 0xff);
289 return h;
293 * Compare lines s1 of length n1 and s2 of length n2, ignoring
294 * whitespace difference. Returns 1 if they match, 0 otherwise
296 static int fuzzy_matchlines(const char *s1, size_t n1,
297 const char *s2, size_t n2)
299 const char *end1 = s1 + n1;
300 const char *end2 = s2 + n2;
302 /* ignore line endings */
303 while (s1 < end1 && (end1[-1] == '\r' || end1[-1] == '\n'))
304 end1--;
305 while (s2 < end2 && (end2[-1] == '\r' || end2[-1] == '\n'))
306 end2--;
308 while (s1 < end1 && s2 < end2) {
309 if (isspace(*s1)) {
311 * Skip whitespace. We check on both buffers
312 * because we don't want "a b" to match "ab".
314 if (!isspace(*s2))
315 return 0;
316 while (s1 < end1 && isspace(*s1))
317 s1++;
318 while (s2 < end2 && isspace(*s2))
319 s2++;
320 } else if (*s1++ != *s2++)
321 return 0;
324 /* If we reached the end on one side only, lines don't match. */
325 return s1 == end1 && s2 == end2;
328 static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
330 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
331 img->line_allocated[img->nr].len = len;
332 img->line_allocated[img->nr].hash = hash_line(bol, len);
333 img->line_allocated[img->nr].flag = flag;
334 img->nr++;
338 * "buf" has the file contents to be patched (read from various sources).
339 * attach it to "image" and add line-based index to it.
340 * "image" now owns the "buf".
342 static void prepare_image(struct image *image, char *buf, size_t len,
343 int prepare_linetable)
345 const char *cp, *ep;
347 memset(image, 0, sizeof(*image));
348 image->buf = buf;
349 image->len = len;
351 if (!prepare_linetable)
352 return;
354 ep = image->buf + image->len;
355 cp = image->buf;
356 while (cp < ep) {
357 const char *next;
358 for (next = cp; next < ep && *next != '\n'; next++)
360 if (next < ep)
361 next++;
362 add_line_info(image, cp, next - cp, 0);
363 cp = next;
365 image->line = image->line_allocated;
368 static void clear_image(struct image *image)
370 free(image->buf);
371 free(image->line_allocated);
372 memset(image, 0, sizeof(*image));
375 /* fmt must contain _one_ %s and no other substitution */
376 static void say_patch_name(FILE *output, const char *fmt, struct patch *patch)
378 struct strbuf sb = STRBUF_INIT;
380 if (patch->old_name && patch->new_name &&
381 strcmp(patch->old_name, patch->new_name)) {
382 quote_c_style(patch->old_name, &sb, NULL, 0);
383 strbuf_addstr(&sb, " => ");
384 quote_c_style(patch->new_name, &sb, NULL, 0);
385 } else {
386 const char *n = patch->new_name;
387 if (!n)
388 n = patch->old_name;
389 quote_c_style(n, &sb, NULL, 0);
391 fprintf(output, fmt, sb.buf);
392 fputc('\n', output);
393 strbuf_release(&sb);
396 #define SLOP (16)
399 * apply.c isn't equipped to handle arbitrarily large patches, because
400 * it intermingles `unsigned long` with `int` for the type used to store
401 * buffer lengths.
403 * Only process patches that are just shy of 1 GiB large in order to
404 * avoid any truncation or overflow issues.
406 #define MAX_APPLY_SIZE (1024UL * 1024 * 1023)
408 static int read_patch_file(struct strbuf *sb, int fd)
410 if (strbuf_read(sb, fd, 0) < 0 || sb->len >= MAX_APPLY_SIZE)
411 return error_errno("git apply: failed to read");
414 * Make sure that we have some slop in the buffer
415 * so that we can do speculative "memcmp" etc, and
416 * see to it that it is NUL-filled.
418 strbuf_grow(sb, SLOP);
419 memset(sb->buf + sb->len, 0, SLOP);
420 return 0;
423 static unsigned long linelen(const char *buffer, unsigned long size)
425 unsigned long len = 0;
426 while (size--) {
427 len++;
428 if (*buffer++ == '\n')
429 break;
431 return len;
434 static int is_dev_null(const char *str)
436 return skip_prefix(str, "/dev/null", &str) && isspace(*str);
439 #define TERM_SPACE 1
440 #define TERM_TAB 2
442 static int name_terminate(int c, int terminate)
444 if (c == ' ' && !(terminate & TERM_SPACE))
445 return 0;
446 if (c == '\t' && !(terminate & TERM_TAB))
447 return 0;
449 return 1;
452 /* remove double slashes to make --index work with such filenames */
453 static char *squash_slash(char *name)
455 int i = 0, j = 0;
457 if (!name)
458 return NULL;
460 while (name[i]) {
461 if ((name[j++] = name[i++]) == '/')
462 while (name[i] == '/')
463 i++;
465 name[j] = '\0';
466 return name;
469 static char *find_name_gnu(struct strbuf *root,
470 const char *line,
471 int p_value)
473 struct strbuf name = STRBUF_INIT;
474 char *cp;
477 * Proposed "new-style" GNU patch/diff format; see
478 * https://lore.kernel.org/git/7vll0wvb2a.fsf@assigned-by-dhcp.cox.net/
480 if (unquote_c_style(&name, line, NULL)) {
481 strbuf_release(&name);
482 return NULL;
485 for (cp = name.buf; p_value; p_value--) {
486 cp = strchr(cp, '/');
487 if (!cp) {
488 strbuf_release(&name);
489 return NULL;
491 cp++;
494 strbuf_remove(&name, 0, cp - name.buf);
495 if (root->len)
496 strbuf_insert(&name, 0, root->buf, root->len);
497 return squash_slash(strbuf_detach(&name, NULL));
500 static size_t sane_tz_len(const char *line, size_t len)
502 const char *tz, *p;
504 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
505 return 0;
506 tz = line + len - strlen(" +0500");
508 if (tz[1] != '+' && tz[1] != '-')
509 return 0;
511 for (p = tz + 2; p != line + len; p++)
512 if (!isdigit(*p))
513 return 0;
515 return line + len - tz;
518 static size_t tz_with_colon_len(const char *line, size_t len)
520 const char *tz, *p;
522 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
523 return 0;
524 tz = line + len - strlen(" +08:00");
526 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
527 return 0;
528 p = tz + 2;
529 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
530 !isdigit(*p++) || !isdigit(*p++))
531 return 0;
533 return line + len - tz;
536 static size_t date_len(const char *line, size_t len)
538 const char *date, *p;
540 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
541 return 0;
542 p = date = line + len - strlen("72-02-05");
544 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
545 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
546 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */
547 return 0;
549 if (date - line >= strlen("19") &&
550 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */
551 date -= strlen("19");
553 return line + len - date;
556 static size_t short_time_len(const char *line, size_t len)
558 const char *time, *p;
560 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
561 return 0;
562 p = time = line + len - strlen(" 07:01:32");
564 /* Permit 1-digit hours? */
565 if (*p++ != ' ' ||
566 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
567 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
568 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */
569 return 0;
571 return line + len - time;
574 static size_t fractional_time_len(const char *line, size_t len)
576 const char *p;
577 size_t n;
579 /* Expected format: 19:41:17.620000023 */
580 if (!len || !isdigit(line[len - 1]))
581 return 0;
582 p = line + len - 1;
584 /* Fractional seconds. */
585 while (p > line && isdigit(*p))
586 p--;
587 if (*p != '.')
588 return 0;
590 /* Hours, minutes, and whole seconds. */
591 n = short_time_len(line, p - line);
592 if (!n)
593 return 0;
595 return line + len - p + n;
598 static size_t trailing_spaces_len(const char *line, size_t len)
600 const char *p;
602 /* Expected format: ' ' x (1 or more) */
603 if (!len || line[len - 1] != ' ')
604 return 0;
606 p = line + len;
607 while (p != line) {
608 p--;
609 if (*p != ' ')
610 return line + len - (p + 1);
613 /* All spaces! */
614 return len;
617 static size_t diff_timestamp_len(const char *line, size_t len)
619 const char *end = line + len;
620 size_t n;
623 * Posix: 2010-07-05 19:41:17
624 * GNU: 2010-07-05 19:41:17.620000023 -0500
627 if (!isdigit(end[-1]))
628 return 0;
630 n = sane_tz_len(line, end - line);
631 if (!n)
632 n = tz_with_colon_len(line, end - line);
633 end -= n;
635 n = short_time_len(line, end - line);
636 if (!n)
637 n = fractional_time_len(line, end - line);
638 end -= n;
640 n = date_len(line, end - line);
641 if (!n) /* No date. Too bad. */
642 return 0;
643 end -= n;
645 if (end == line) /* No space before date. */
646 return 0;
647 if (end[-1] == '\t') { /* Success! */
648 end--;
649 return line + len - end;
651 if (end[-1] != ' ') /* No space before date. */
652 return 0;
654 /* Whitespace damage. */
655 end -= trailing_spaces_len(line, end - line);
656 return line + len - end;
659 static char *find_name_common(struct strbuf *root,
660 const char *line,
661 const char *def,
662 int p_value,
663 const char *end,
664 int terminate)
666 int len;
667 const char *start = NULL;
669 if (p_value == 0)
670 start = line;
671 while (line != end) {
672 char c = *line;
674 if (!end && isspace(c)) {
675 if (c == '\n')
676 break;
677 if (name_terminate(c, terminate))
678 break;
680 line++;
681 if (c == '/' && !--p_value)
682 start = line;
684 if (!start)
685 return squash_slash(xstrdup_or_null(def));
686 len = line - start;
687 if (!len)
688 return squash_slash(xstrdup_or_null(def));
691 * Generally we prefer the shorter name, especially
692 * if the other one is just a variation of that with
693 * something else tacked on to the end (ie "file.orig"
694 * or "file~").
696 if (def) {
697 int deflen = strlen(def);
698 if (deflen < len && !strncmp(start, def, deflen))
699 return squash_slash(xstrdup(def));
702 if (root->len) {
703 char *ret = xstrfmt("%s%.*s", root->buf, len, start);
704 return squash_slash(ret);
707 return squash_slash(xmemdupz(start, len));
710 static char *find_name(struct strbuf *root,
711 const char *line,
712 char *def,
713 int p_value,
714 int terminate)
716 if (*line == '"') {
717 char *name = find_name_gnu(root, line, p_value);
718 if (name)
719 return name;
722 return find_name_common(root, line, def, p_value, NULL, terminate);
725 static char *find_name_traditional(struct strbuf *root,
726 const char *line,
727 char *def,
728 int p_value)
730 size_t len;
731 size_t date_len;
733 if (*line == '"') {
734 char *name = find_name_gnu(root, line, p_value);
735 if (name)
736 return name;
739 len = strchrnul(line, '\n') - line;
740 date_len = diff_timestamp_len(line, len);
741 if (!date_len)
742 return find_name_common(root, line, def, p_value, NULL, TERM_TAB);
743 len -= date_len;
745 return find_name_common(root, line, def, p_value, line + len, 0);
749 * Given the string after "--- " or "+++ ", guess the appropriate
750 * p_value for the given patch.
752 static int guess_p_value(struct apply_state *state, const char *nameline)
754 char *name, *cp;
755 int val = -1;
757 if (is_dev_null(nameline))
758 return -1;
759 name = find_name_traditional(&state->root, nameline, NULL, 0);
760 if (!name)
761 return -1;
762 cp = strchr(name, '/');
763 if (!cp)
764 val = 0;
765 else if (state->prefix) {
767 * Does it begin with "a/$our-prefix" and such? Then this is
768 * very likely to apply to our directory.
770 if (starts_with(name, state->prefix))
771 val = count_slashes(state->prefix);
772 else {
773 cp++;
774 if (starts_with(cp, state->prefix))
775 val = count_slashes(state->prefix) + 1;
778 free(name);
779 return val;
783 * Does the ---/+++ line have the POSIX timestamp after the last HT?
784 * GNU diff puts epoch there to signal a creation/deletion event. Is
785 * this such a timestamp?
787 static int has_epoch_timestamp(const char *nameline)
790 * We are only interested in epoch timestamp; any non-zero
791 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
792 * For the same reason, the date must be either 1969-12-31 or
793 * 1970-01-01, and the seconds part must be "00".
795 const char stamp_regexp[] =
796 "^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?"
798 "([-+][0-2][0-9]:?[0-5][0-9])\n";
799 const char *timestamp = NULL, *cp, *colon;
800 static regex_t *stamp;
801 regmatch_t m[10];
802 int zoneoffset, epoch_hour, hour, minute;
803 int status;
805 for (cp = nameline; *cp != '\n'; cp++) {
806 if (*cp == '\t')
807 timestamp = cp + 1;
809 if (!timestamp)
810 return 0;
813 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
814 * (west of GMT) or 1970-01-01 (east of GMT)
816 if (skip_prefix(timestamp, "1969-12-31 ", &timestamp))
817 epoch_hour = 24;
818 else if (skip_prefix(timestamp, "1970-01-01 ", &timestamp))
819 epoch_hour = 0;
820 else
821 return 0;
823 if (!stamp) {
824 stamp = xmalloc(sizeof(*stamp));
825 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
826 warning(_("Cannot prepare timestamp regexp %s"),
827 stamp_regexp);
828 return 0;
832 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
833 if (status) {
834 if (status != REG_NOMATCH)
835 warning(_("regexec returned %d for input: %s"),
836 status, timestamp);
837 return 0;
840 hour = strtol(timestamp, NULL, 10);
841 minute = strtol(timestamp + m[1].rm_so, NULL, 10);
843 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
844 if (*colon == ':')
845 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
846 else
847 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
848 if (timestamp[m[3].rm_so] == '-')
849 zoneoffset = -zoneoffset;
851 return hour * 60 + minute - zoneoffset == epoch_hour * 60;
855 * Get the name etc info from the ---/+++ lines of a traditional patch header
857 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
858 * files, we can happily check the index for a match, but for creating a
859 * new file we should try to match whatever "patch" does. I have no idea.
861 static int parse_traditional_patch(struct apply_state *state,
862 const char *first,
863 const char *second,
864 struct patch *patch)
866 char *name;
868 first += 4; /* skip "--- " */
869 second += 4; /* skip "+++ " */
870 if (!state->p_value_known) {
871 int p, q;
872 p = guess_p_value(state, first);
873 q = guess_p_value(state, second);
874 if (p < 0) p = q;
875 if (0 <= p && p == q) {
876 state->p_value = p;
877 state->p_value_known = 1;
880 if (is_dev_null(first)) {
881 patch->is_new = 1;
882 patch->is_delete = 0;
883 name = find_name_traditional(&state->root, second, NULL, state->p_value);
884 patch->new_name = name;
885 } else if (is_dev_null(second)) {
886 patch->is_new = 0;
887 patch->is_delete = 1;
888 name = find_name_traditional(&state->root, first, NULL, state->p_value);
889 patch->old_name = name;
890 } else {
891 char *first_name;
892 first_name = find_name_traditional(&state->root, first, NULL, state->p_value);
893 name = find_name_traditional(&state->root, second, first_name, state->p_value);
894 free(first_name);
895 if (has_epoch_timestamp(first)) {
896 patch->is_new = 1;
897 patch->is_delete = 0;
898 patch->new_name = name;
899 } else if (has_epoch_timestamp(second)) {
900 patch->is_new = 0;
901 patch->is_delete = 1;
902 patch->old_name = name;
903 } else {
904 patch->old_name = name;
905 patch->new_name = xstrdup_or_null(name);
908 if (!name)
909 return error(_("unable to find filename in patch at line %d"), state->linenr);
911 return 0;
914 static int gitdiff_hdrend(struct gitdiff_data *state UNUSED,
915 const char *line UNUSED,
916 struct patch *patch UNUSED)
918 return 1;
922 * We're anal about diff header consistency, to make
923 * sure that we don't end up having strange ambiguous
924 * patches floating around.
926 * As a result, gitdiff_{old|new}name() will check
927 * their names against any previous information, just
928 * to make sure..
930 #define DIFF_OLD_NAME 0
931 #define DIFF_NEW_NAME 1
933 static int gitdiff_verify_name(struct gitdiff_data *state,
934 const char *line,
935 int isnull,
936 char **name,
937 int side)
939 if (!*name && !isnull) {
940 *name = find_name(state->root, line, NULL, state->p_value, TERM_TAB);
941 return 0;
944 if (*name) {
945 char *another;
946 if (isnull)
947 return error(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
948 *name, state->linenr);
949 another = find_name(state->root, line, NULL, state->p_value, TERM_TAB);
950 if (!another || strcmp(another, *name)) {
951 free(another);
952 return error((side == DIFF_NEW_NAME) ?
953 _("git apply: bad git-diff - inconsistent new filename on line %d") :
954 _("git apply: bad git-diff - inconsistent old filename on line %d"), state->linenr);
956 free(another);
957 } else {
958 if (!is_dev_null(line))
959 return error(_("git apply: bad git-diff - expected /dev/null on line %d"), state->linenr);
962 return 0;
965 static int gitdiff_oldname(struct gitdiff_data *state,
966 const char *line,
967 struct patch *patch)
969 return gitdiff_verify_name(state, line,
970 patch->is_new, &patch->old_name,
971 DIFF_OLD_NAME);
974 static int gitdiff_newname(struct gitdiff_data *state,
975 const char *line,
976 struct patch *patch)
978 return gitdiff_verify_name(state, line,
979 patch->is_delete, &patch->new_name,
980 DIFF_NEW_NAME);
983 static int parse_mode_line(const char *line, int linenr, unsigned int *mode)
985 char *end;
986 *mode = strtoul(line, &end, 8);
987 if (end == line || !isspace(*end))
988 return error(_("invalid mode on line %d: %s"), linenr, line);
989 return 0;
992 static int gitdiff_oldmode(struct gitdiff_data *state,
993 const char *line,
994 struct patch *patch)
996 return parse_mode_line(line, state->linenr, &patch->old_mode);
999 static int gitdiff_newmode(struct gitdiff_data *state,
1000 const char *line,
1001 struct patch *patch)
1003 return parse_mode_line(line, state->linenr, &patch->new_mode);
1006 static int gitdiff_delete(struct gitdiff_data *state,
1007 const char *line,
1008 struct patch *patch)
1010 patch->is_delete = 1;
1011 free(patch->old_name);
1012 patch->old_name = xstrdup_or_null(patch->def_name);
1013 return gitdiff_oldmode(state, line, patch);
1016 static int gitdiff_newfile(struct gitdiff_data *state,
1017 const char *line,
1018 struct patch *patch)
1020 patch->is_new = 1;
1021 free(patch->new_name);
1022 patch->new_name = xstrdup_or_null(patch->def_name);
1023 return gitdiff_newmode(state, line, patch);
1026 static int gitdiff_copysrc(struct gitdiff_data *state,
1027 const char *line,
1028 struct patch *patch)
1030 patch->is_copy = 1;
1031 free(patch->old_name);
1032 patch->old_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1033 return 0;
1036 static int gitdiff_copydst(struct gitdiff_data *state,
1037 const char *line,
1038 struct patch *patch)
1040 patch->is_copy = 1;
1041 free(patch->new_name);
1042 patch->new_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1043 return 0;
1046 static int gitdiff_renamesrc(struct gitdiff_data *state,
1047 const char *line,
1048 struct patch *patch)
1050 patch->is_rename = 1;
1051 free(patch->old_name);
1052 patch->old_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1053 return 0;
1056 static int gitdiff_renamedst(struct gitdiff_data *state,
1057 const char *line,
1058 struct patch *patch)
1060 patch->is_rename = 1;
1061 free(patch->new_name);
1062 patch->new_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1063 return 0;
1066 static int gitdiff_similarity(struct gitdiff_data *state UNUSED,
1067 const char *line,
1068 struct patch *patch)
1070 unsigned long val = strtoul(line, NULL, 10);
1071 if (val <= 100)
1072 patch->score = val;
1073 return 0;
1076 static int gitdiff_dissimilarity(struct gitdiff_data *state UNUSED,
1077 const char *line,
1078 struct patch *patch)
1080 unsigned long val = strtoul(line, NULL, 10);
1081 if (val <= 100)
1082 patch->score = val;
1083 return 0;
1086 static int gitdiff_index(struct gitdiff_data *state,
1087 const char *line,
1088 struct patch *patch)
1091 * index line is N hexadecimal, "..", N hexadecimal,
1092 * and optional space with octal mode.
1094 const char *ptr, *eol;
1095 int len;
1096 const unsigned hexsz = the_hash_algo->hexsz;
1098 ptr = strchr(line, '.');
1099 if (!ptr || ptr[1] != '.' || hexsz < ptr - line)
1100 return 0;
1101 len = ptr - line;
1102 memcpy(patch->old_oid_prefix, line, len);
1103 patch->old_oid_prefix[len] = 0;
1105 line = ptr + 2;
1106 ptr = strchr(line, ' ');
1107 eol = strchrnul(line, '\n');
1109 if (!ptr || eol < ptr)
1110 ptr = eol;
1111 len = ptr - line;
1113 if (hexsz < len)
1114 return 0;
1115 memcpy(patch->new_oid_prefix, line, len);
1116 patch->new_oid_prefix[len] = 0;
1117 if (*ptr == ' ')
1118 return gitdiff_oldmode(state, ptr + 1, patch);
1119 return 0;
1123 * This is normal for a diff that doesn't change anything: we'll fall through
1124 * into the next diff. Tell the parser to break out.
1126 static int gitdiff_unrecognized(struct gitdiff_data *state UNUSED,
1127 const char *line UNUSED,
1128 struct patch *patch UNUSED)
1130 return 1;
1134 * Skip p_value leading components from "line"; as we do not accept
1135 * absolute paths, return NULL in that case.
1137 static const char *skip_tree_prefix(int p_value,
1138 const char *line,
1139 int llen)
1141 int nslash;
1142 int i;
1144 if (!p_value)
1145 return (llen && line[0] == '/') ? NULL : line;
1147 nslash = p_value;
1148 for (i = 0; i < llen; i++) {
1149 int ch = line[i];
1150 if (ch == '/' && --nslash <= 0)
1151 return (i == 0) ? NULL : &line[i + 1];
1153 return NULL;
1157 * This is to extract the same name that appears on "diff --git"
1158 * line. We do not find and return anything if it is a rename
1159 * patch, and it is OK because we will find the name elsewhere.
1160 * We need to reliably find name only when it is mode-change only,
1161 * creation or deletion of an empty file. In any of these cases,
1162 * both sides are the same name under a/ and b/ respectively.
1164 static char *git_header_name(int p_value,
1165 const char *line,
1166 int llen)
1168 const char *name;
1169 const char *second = NULL;
1170 size_t len, line_len;
1172 line += strlen("diff --git ");
1173 llen -= strlen("diff --git ");
1175 if (*line == '"') {
1176 const char *cp;
1177 struct strbuf first = STRBUF_INIT;
1178 struct strbuf sp = STRBUF_INIT;
1180 if (unquote_c_style(&first, line, &second))
1181 goto free_and_fail1;
1183 /* strip the a/b prefix including trailing slash */
1184 cp = skip_tree_prefix(p_value, first.buf, first.len);
1185 if (!cp)
1186 goto free_and_fail1;
1187 strbuf_remove(&first, 0, cp - first.buf);
1190 * second points at one past closing dq of name.
1191 * find the second name.
1193 while ((second < line + llen) && isspace(*second))
1194 second++;
1196 if (line + llen <= second)
1197 goto free_and_fail1;
1198 if (*second == '"') {
1199 if (unquote_c_style(&sp, second, NULL))
1200 goto free_and_fail1;
1201 cp = skip_tree_prefix(p_value, sp.buf, sp.len);
1202 if (!cp)
1203 goto free_and_fail1;
1204 /* They must match, otherwise ignore */
1205 if (strcmp(cp, first.buf))
1206 goto free_and_fail1;
1207 strbuf_release(&sp);
1208 return strbuf_detach(&first, NULL);
1211 /* unquoted second */
1212 cp = skip_tree_prefix(p_value, second, line + llen - second);
1213 if (!cp)
1214 goto free_and_fail1;
1215 if (line + llen - cp != first.len ||
1216 memcmp(first.buf, cp, first.len))
1217 goto free_and_fail1;
1218 return strbuf_detach(&first, NULL);
1220 free_and_fail1:
1221 strbuf_release(&first);
1222 strbuf_release(&sp);
1223 return NULL;
1226 /* unquoted first name */
1227 name = skip_tree_prefix(p_value, line, llen);
1228 if (!name)
1229 return NULL;
1232 * since the first name is unquoted, a dq if exists must be
1233 * the beginning of the second name.
1235 for (second = name; second < line + llen; second++) {
1236 if (*second == '"') {
1237 struct strbuf sp = STRBUF_INIT;
1238 const char *np;
1240 if (unquote_c_style(&sp, second, NULL))
1241 goto free_and_fail2;
1243 np = skip_tree_prefix(p_value, sp.buf, sp.len);
1244 if (!np)
1245 goto free_and_fail2;
1247 len = sp.buf + sp.len - np;
1248 if (len < second - name &&
1249 !strncmp(np, name, len) &&
1250 isspace(name[len])) {
1251 /* Good */
1252 strbuf_remove(&sp, 0, np - sp.buf);
1253 return strbuf_detach(&sp, NULL);
1256 free_and_fail2:
1257 strbuf_release(&sp);
1258 return NULL;
1263 * Accept a name only if it shows up twice, exactly the same
1264 * form.
1266 second = strchr(name, '\n');
1267 if (!second)
1268 return NULL;
1269 line_len = second - name;
1270 for (len = 0 ; ; len++) {
1271 switch (name[len]) {
1272 default:
1273 continue;
1274 case '\n':
1275 return NULL;
1276 case '\t': case ' ':
1278 * Is this the separator between the preimage
1279 * and the postimage pathname? Again, we are
1280 * only interested in the case where there is
1281 * no rename, as this is only to set def_name
1282 * and a rename patch has the names elsewhere
1283 * in an unambiguous form.
1285 if (!name[len + 1])
1286 return NULL; /* no postimage name */
1287 second = skip_tree_prefix(p_value, name + len + 1,
1288 line_len - (len + 1));
1289 if (!second)
1290 return NULL;
1292 * Does len bytes starting at "name" and "second"
1293 * (that are separated by one HT or SP we just
1294 * found) exactly match?
1296 if (second[len] == '\n' && !strncmp(name, second, len))
1297 return xmemdupz(name, len);
1302 static int check_header_line(int linenr, struct patch *patch)
1304 int extensions = (patch->is_delete == 1) + (patch->is_new == 1) +
1305 (patch->is_rename == 1) + (patch->is_copy == 1);
1306 if (extensions > 1)
1307 return error(_("inconsistent header lines %d and %d"),
1308 patch->extension_linenr, linenr);
1309 if (extensions && !patch->extension_linenr)
1310 patch->extension_linenr = linenr;
1311 return 0;
1314 int parse_git_diff_header(struct strbuf *root,
1315 int *linenr,
1316 int p_value,
1317 const char *line,
1318 int len,
1319 unsigned int size,
1320 struct patch *patch)
1322 unsigned long offset;
1323 struct gitdiff_data parse_hdr_state;
1325 /* A git diff has explicit new/delete information, so we don't guess */
1326 patch->is_new = 0;
1327 patch->is_delete = 0;
1330 * Some things may not have the old name in the
1331 * rest of the headers anywhere (pure mode changes,
1332 * or removing or adding empty files), so we get
1333 * the default name from the header.
1335 patch->def_name = git_header_name(p_value, line, len);
1336 if (patch->def_name && root->len) {
1337 char *s = xstrfmt("%s%s", root->buf, patch->def_name);
1338 free(patch->def_name);
1339 patch->def_name = s;
1342 line += len;
1343 size -= len;
1344 (*linenr)++;
1345 parse_hdr_state.root = root;
1346 parse_hdr_state.linenr = *linenr;
1347 parse_hdr_state.p_value = p_value;
1349 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, (*linenr)++) {
1350 static const struct opentry {
1351 const char *str;
1352 int (*fn)(struct gitdiff_data *, const char *, struct patch *);
1353 } optable[] = {
1354 { "@@ -", gitdiff_hdrend },
1355 { "--- ", gitdiff_oldname },
1356 { "+++ ", gitdiff_newname },
1357 { "old mode ", gitdiff_oldmode },
1358 { "new mode ", gitdiff_newmode },
1359 { "deleted file mode ", gitdiff_delete },
1360 { "new file mode ", gitdiff_newfile },
1361 { "copy from ", gitdiff_copysrc },
1362 { "copy to ", gitdiff_copydst },
1363 { "rename old ", gitdiff_renamesrc },
1364 { "rename new ", gitdiff_renamedst },
1365 { "rename from ", gitdiff_renamesrc },
1366 { "rename to ", gitdiff_renamedst },
1367 { "similarity index ", gitdiff_similarity },
1368 { "dissimilarity index ", gitdiff_dissimilarity },
1369 { "index ", gitdiff_index },
1370 { "", gitdiff_unrecognized },
1372 int i;
1374 len = linelen(line, size);
1375 if (!len || line[len-1] != '\n')
1376 break;
1377 for (i = 0; i < ARRAY_SIZE(optable); i++) {
1378 const struct opentry *p = optable + i;
1379 int oplen = strlen(p->str);
1380 int res;
1381 if (len < oplen || memcmp(p->str, line, oplen))
1382 continue;
1383 res = p->fn(&parse_hdr_state, line + oplen, patch);
1384 if (res < 0)
1385 return -1;
1386 if (check_header_line(*linenr, patch))
1387 return -1;
1388 if (res > 0)
1389 goto done;
1390 break;
1394 done:
1395 if (!patch->old_name && !patch->new_name) {
1396 if (!patch->def_name) {
1397 error(Q_("git diff header lacks filename information when removing "
1398 "%d leading pathname component (line %d)",
1399 "git diff header lacks filename information when removing "
1400 "%d leading pathname components (line %d)",
1401 parse_hdr_state.p_value),
1402 parse_hdr_state.p_value, *linenr);
1403 return -128;
1405 patch->old_name = xstrdup(patch->def_name);
1406 patch->new_name = xstrdup(patch->def_name);
1408 if ((!patch->new_name && !patch->is_delete) ||
1409 (!patch->old_name && !patch->is_new)) {
1410 error(_("git diff header lacks filename information "
1411 "(line %d)"), *linenr);
1412 return -128;
1414 patch->is_toplevel_relative = 1;
1415 return offset;
1418 static int parse_num(const char *line, unsigned long *p)
1420 char *ptr;
1422 if (!isdigit(*line))
1423 return 0;
1424 *p = strtoul(line, &ptr, 10);
1425 return ptr - line;
1428 static int parse_range(const char *line, int len, int offset, const char *expect,
1429 unsigned long *p1, unsigned long *p2)
1431 int digits, ex;
1433 if (offset < 0 || offset >= len)
1434 return -1;
1435 line += offset;
1436 len -= offset;
1438 digits = parse_num(line, p1);
1439 if (!digits)
1440 return -1;
1442 offset += digits;
1443 line += digits;
1444 len -= digits;
1446 *p2 = 1;
1447 if (*line == ',') {
1448 digits = parse_num(line+1, p2);
1449 if (!digits)
1450 return -1;
1452 offset += digits+1;
1453 line += digits+1;
1454 len -= digits+1;
1457 ex = strlen(expect);
1458 if (ex > len)
1459 return -1;
1460 if (memcmp(line, expect, ex))
1461 return -1;
1463 return offset + ex;
1466 static void recount_diff(const char *line, int size, struct fragment *fragment)
1468 int oldlines = 0, newlines = 0, ret = 0;
1470 if (size < 1) {
1471 warning("recount: ignore empty hunk");
1472 return;
1475 for (;;) {
1476 int len = linelen(line, size);
1477 size -= len;
1478 line += len;
1480 if (size < 1)
1481 break;
1483 switch (*line) {
1484 case ' ': case '\n':
1485 newlines++;
1486 /* fall through */
1487 case '-':
1488 oldlines++;
1489 continue;
1490 case '+':
1491 newlines++;
1492 continue;
1493 case '\\':
1494 continue;
1495 case '@':
1496 ret = size < 3 || !starts_with(line, "@@ ");
1497 break;
1498 case 'd':
1499 ret = size < 5 || !starts_with(line, "diff ");
1500 break;
1501 default:
1502 ret = -1;
1503 break;
1505 if (ret) {
1506 warning(_("recount: unexpected line: %.*s"),
1507 (int)linelen(line, size), line);
1508 return;
1510 break;
1512 fragment->oldlines = oldlines;
1513 fragment->newlines = newlines;
1517 * Parse a unified diff fragment header of the
1518 * form "@@ -a,b +c,d @@"
1520 static int parse_fragment_header(const char *line, int len, struct fragment *fragment)
1522 int offset;
1524 if (!len || line[len-1] != '\n')
1525 return -1;
1527 /* Figure out the number of lines in a fragment */
1528 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1529 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1531 return offset;
1535 * Find file diff header
1537 * Returns:
1538 * -1 if no header was found
1539 * -128 in case of error
1540 * the size of the header in bytes (called "offset") otherwise
1542 static int find_header(struct apply_state *state,
1543 const char *line,
1544 unsigned long size,
1545 int *hdrsize,
1546 struct patch *patch)
1548 unsigned long offset, len;
1550 patch->is_toplevel_relative = 0;
1551 patch->is_rename = patch->is_copy = 0;
1552 patch->is_new = patch->is_delete = -1;
1553 patch->old_mode = patch->new_mode = 0;
1554 patch->old_name = patch->new_name = NULL;
1555 for (offset = 0; size > 0; offset += len, size -= len, line += len, state->linenr++) {
1556 unsigned long nextlen;
1558 len = linelen(line, size);
1559 if (!len)
1560 break;
1562 /* Testing this early allows us to take a few shortcuts.. */
1563 if (len < 6)
1564 continue;
1567 * Make sure we don't find any unconnected patch fragments.
1568 * That's a sign that we didn't find a header, and that a
1569 * patch has become corrupted/broken up.
1571 if (!memcmp("@@ -", line, 4)) {
1572 struct fragment dummy;
1573 if (parse_fragment_header(line, len, &dummy) < 0)
1574 continue;
1575 error(_("patch fragment without header at line %d: %.*s"),
1576 state->linenr, (int)len-1, line);
1577 return -128;
1580 if (size < len + 6)
1581 break;
1584 * Git patch? It might not have a real patch, just a rename
1585 * or mode change, so we handle that specially
1587 if (!memcmp("diff --git ", line, 11)) {
1588 int git_hdr_len = parse_git_diff_header(&state->root, &state->linenr,
1589 state->p_value, line, len,
1590 size, patch);
1591 if (git_hdr_len < 0)
1592 return -128;
1593 if (git_hdr_len <= len)
1594 continue;
1595 *hdrsize = git_hdr_len;
1596 return offset;
1599 /* --- followed by +++ ? */
1600 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1601 continue;
1604 * We only accept unified patches, so we want it to
1605 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1606 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1608 nextlen = linelen(line + len, size - len);
1609 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1610 continue;
1612 /* Ok, we'll consider it a patch */
1613 if (parse_traditional_patch(state, line, line+len, patch))
1614 return -128;
1615 *hdrsize = len + nextlen;
1616 state->linenr += 2;
1617 return offset;
1619 return -1;
1622 static void record_ws_error(struct apply_state *state,
1623 unsigned result,
1624 const char *line,
1625 int len,
1626 int linenr)
1628 char *err;
1630 if (!result)
1631 return;
1633 state->whitespace_error++;
1634 if (state->squelch_whitespace_errors &&
1635 state->squelch_whitespace_errors < state->whitespace_error)
1636 return;
1638 err = whitespace_error_string(result);
1639 if (state->apply_verbosity > verbosity_silent)
1640 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1641 state->patch_input_file, linenr, err, len, line);
1642 free(err);
1645 static void check_whitespace(struct apply_state *state,
1646 const char *line,
1647 int len,
1648 unsigned ws_rule)
1650 unsigned result = ws_check(line + 1, len - 1, ws_rule);
1652 record_ws_error(state, result, line + 1, len - 2, state->linenr);
1656 * Check if the patch has context lines with CRLF or
1657 * the patch wants to remove lines with CRLF.
1659 static void check_old_for_crlf(struct patch *patch, const char *line, int len)
1661 if (len >= 2 && line[len-1] == '\n' && line[len-2] == '\r') {
1662 patch->ws_rule |= WS_CR_AT_EOL;
1663 patch->crlf_in_old = 1;
1669 * Parse a unified diff. Note that this really needs to parse each
1670 * fragment separately, since the only way to know the difference
1671 * between a "---" that is part of a patch, and a "---" that starts
1672 * the next patch is to look at the line counts..
1674 static int parse_fragment(struct apply_state *state,
1675 const char *line,
1676 unsigned long size,
1677 struct patch *patch,
1678 struct fragment *fragment)
1680 int added, deleted;
1681 int len = linelen(line, size), offset;
1682 unsigned long oldlines, newlines;
1683 unsigned long leading, trailing;
1685 offset = parse_fragment_header(line, len, fragment);
1686 if (offset < 0)
1687 return -1;
1688 if (offset > 0 && patch->recount)
1689 recount_diff(line + offset, size - offset, fragment);
1690 oldlines = fragment->oldlines;
1691 newlines = fragment->newlines;
1692 leading = 0;
1693 trailing = 0;
1695 /* Parse the thing.. */
1696 line += len;
1697 size -= len;
1698 state->linenr++;
1699 added = deleted = 0;
1700 for (offset = len;
1701 0 < size;
1702 offset += len, size -= len, line += len, state->linenr++) {
1703 if (!oldlines && !newlines)
1704 break;
1705 len = linelen(line, size);
1706 if (!len || line[len-1] != '\n')
1707 return -1;
1708 switch (*line) {
1709 default:
1710 return -1;
1711 case '\n': /* newer GNU diff, an empty context line */
1712 case ' ':
1713 oldlines--;
1714 newlines--;
1715 if (!deleted && !added)
1716 leading++;
1717 trailing++;
1718 check_old_for_crlf(patch, line, len);
1719 if (!state->apply_in_reverse &&
1720 state->ws_error_action == correct_ws_error)
1721 check_whitespace(state, line, len, patch->ws_rule);
1722 break;
1723 case '-':
1724 if (!state->apply_in_reverse)
1725 check_old_for_crlf(patch, line, len);
1726 if (state->apply_in_reverse &&
1727 state->ws_error_action != nowarn_ws_error)
1728 check_whitespace(state, line, len, patch->ws_rule);
1729 deleted++;
1730 oldlines--;
1731 trailing = 0;
1732 break;
1733 case '+':
1734 if (state->apply_in_reverse)
1735 check_old_for_crlf(patch, line, len);
1736 if (!state->apply_in_reverse &&
1737 state->ws_error_action != nowarn_ws_error)
1738 check_whitespace(state, line, len, patch->ws_rule);
1739 added++;
1740 newlines--;
1741 trailing = 0;
1742 break;
1745 * We allow "\ No newline at end of file". Depending
1746 * on locale settings when the patch was produced we
1747 * don't know what this line looks like. The only
1748 * thing we do know is that it begins with "\ ".
1749 * Checking for 12 is just for sanity check -- any
1750 * l10n of "\ No newline..." is at least that long.
1752 case '\\':
1753 if (len < 12 || memcmp(line, "\\ ", 2))
1754 return -1;
1755 break;
1758 if (oldlines || newlines)
1759 return -1;
1760 if (!patch->recount && !deleted && !added)
1761 return -1;
1763 fragment->leading = leading;
1764 fragment->trailing = trailing;
1767 * If a fragment ends with an incomplete line, we failed to include
1768 * it in the above loop because we hit oldlines == newlines == 0
1769 * before seeing it.
1771 if (12 < size && !memcmp(line, "\\ ", 2))
1772 offset += linelen(line, size);
1774 patch->lines_added += added;
1775 patch->lines_deleted += deleted;
1777 if (0 < patch->is_new && oldlines)
1778 return error(_("new file depends on old contents"));
1779 if (0 < patch->is_delete && newlines)
1780 return error(_("deleted file still has contents"));
1781 return offset;
1785 * We have seen "diff --git a/... b/..." header (or a traditional patch
1786 * header). Read hunks that belong to this patch into fragments and hang
1787 * them to the given patch structure.
1789 * The (fragment->patch, fragment->size) pair points into the memory given
1790 * by the caller, not a copy, when we return.
1792 * Returns:
1793 * -1 in case of error,
1794 * the number of bytes in the patch otherwise.
1796 static int parse_single_patch(struct apply_state *state,
1797 const char *line,
1798 unsigned long size,
1799 struct patch *patch)
1801 unsigned long offset = 0;
1802 unsigned long oldlines = 0, newlines = 0, context = 0;
1803 struct fragment **fragp = &patch->fragments;
1805 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1806 struct fragment *fragment;
1807 int len;
1809 CALLOC_ARRAY(fragment, 1);
1810 fragment->linenr = state->linenr;
1811 len = parse_fragment(state, line, size, patch, fragment);
1812 if (len <= 0) {
1813 free(fragment);
1814 return error(_("corrupt patch at line %d"), state->linenr);
1816 fragment->patch = line;
1817 fragment->size = len;
1818 oldlines += fragment->oldlines;
1819 newlines += fragment->newlines;
1820 context += fragment->leading + fragment->trailing;
1822 *fragp = fragment;
1823 fragp = &fragment->next;
1825 offset += len;
1826 line += len;
1827 size -= len;
1831 * If something was removed (i.e. we have old-lines) it cannot
1832 * be creation, and if something was added it cannot be
1833 * deletion. However, the reverse is not true; --unified=0
1834 * patches that only add are not necessarily creation even
1835 * though they do not have any old lines, and ones that only
1836 * delete are not necessarily deletion.
1838 * Unfortunately, a real creation/deletion patch do _not_ have
1839 * any context line by definition, so we cannot safely tell it
1840 * apart with --unified=0 insanity. At least if the patch has
1841 * more than one hunk it is not creation or deletion.
1843 if (patch->is_new < 0 &&
1844 (oldlines || (patch->fragments && patch->fragments->next)))
1845 patch->is_new = 0;
1846 if (patch->is_delete < 0 &&
1847 (newlines || (patch->fragments && patch->fragments->next)))
1848 patch->is_delete = 0;
1850 if (0 < patch->is_new && oldlines)
1851 return error(_("new file %s depends on old contents"), patch->new_name);
1852 if (0 < patch->is_delete && newlines)
1853 return error(_("deleted file %s still has contents"), patch->old_name);
1854 if (!patch->is_delete && !newlines && context && state->apply_verbosity > verbosity_silent)
1855 fprintf_ln(stderr,
1856 _("** warning: "
1857 "file %s becomes empty but is not deleted"),
1858 patch->new_name);
1860 return offset;
1863 static inline int metadata_changes(struct patch *patch)
1865 return patch->is_rename > 0 ||
1866 patch->is_copy > 0 ||
1867 patch->is_new > 0 ||
1868 patch->is_delete ||
1869 (patch->old_mode && patch->new_mode &&
1870 patch->old_mode != patch->new_mode);
1873 static char *inflate_it(const void *data, unsigned long size,
1874 unsigned long inflated_size)
1876 git_zstream stream;
1877 void *out;
1878 int st;
1880 memset(&stream, 0, sizeof(stream));
1882 stream.next_in = (unsigned char *)data;
1883 stream.avail_in = size;
1884 stream.next_out = out = xmalloc(inflated_size);
1885 stream.avail_out = inflated_size;
1886 git_inflate_init(&stream);
1887 st = git_inflate(&stream, Z_FINISH);
1888 git_inflate_end(&stream);
1889 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1890 free(out);
1891 return NULL;
1893 return out;
1897 * Read a binary hunk and return a new fragment; fragment->patch
1898 * points at an allocated memory that the caller must free, so
1899 * it is marked as "->free_patch = 1".
1901 static struct fragment *parse_binary_hunk(struct apply_state *state,
1902 char **buf_p,
1903 unsigned long *sz_p,
1904 int *status_p,
1905 int *used_p)
1908 * Expect a line that begins with binary patch method ("literal"
1909 * or "delta"), followed by the length of data before deflating.
1910 * a sequence of 'length-byte' followed by base-85 encoded data
1911 * should follow, terminated by a newline.
1913 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1914 * and we would limit the patch line to 66 characters,
1915 * so one line can fit up to 13 groups that would decode
1916 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1917 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1919 int llen, used;
1920 unsigned long size = *sz_p;
1921 char *buffer = *buf_p;
1922 int patch_method;
1923 unsigned long origlen;
1924 char *data = NULL;
1925 int hunk_size = 0;
1926 struct fragment *frag;
1928 llen = linelen(buffer, size);
1929 used = llen;
1931 *status_p = 0;
1933 if (starts_with(buffer, "delta ")) {
1934 patch_method = BINARY_DELTA_DEFLATED;
1935 origlen = strtoul(buffer + 6, NULL, 10);
1937 else if (starts_with(buffer, "literal ")) {
1938 patch_method = BINARY_LITERAL_DEFLATED;
1939 origlen = strtoul(buffer + 8, NULL, 10);
1941 else
1942 return NULL;
1944 state->linenr++;
1945 buffer += llen;
1946 size -= llen;
1947 while (1) {
1948 int byte_length, max_byte_length, newsize;
1949 llen = linelen(buffer, size);
1950 used += llen;
1951 state->linenr++;
1952 if (llen == 1) {
1953 /* consume the blank line */
1954 buffer++;
1955 size--;
1956 break;
1959 * Minimum line is "A00000\n" which is 7-byte long,
1960 * and the line length must be multiple of 5 plus 2.
1962 if ((llen < 7) || (llen-2) % 5)
1963 goto corrupt;
1964 max_byte_length = (llen - 2) / 5 * 4;
1965 byte_length = *buffer;
1966 if ('A' <= byte_length && byte_length <= 'Z')
1967 byte_length = byte_length - 'A' + 1;
1968 else if ('a' <= byte_length && byte_length <= 'z')
1969 byte_length = byte_length - 'a' + 27;
1970 else
1971 goto corrupt;
1972 /* if the input length was not multiple of 4, we would
1973 * have filler at the end but the filler should never
1974 * exceed 3 bytes
1976 if (max_byte_length < byte_length ||
1977 byte_length <= max_byte_length - 4)
1978 goto corrupt;
1979 newsize = hunk_size + byte_length;
1980 data = xrealloc(data, newsize);
1981 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1982 goto corrupt;
1983 hunk_size = newsize;
1984 buffer += llen;
1985 size -= llen;
1988 CALLOC_ARRAY(frag, 1);
1989 frag->patch = inflate_it(data, hunk_size, origlen);
1990 frag->free_patch = 1;
1991 if (!frag->patch)
1992 goto corrupt;
1993 free(data);
1994 frag->size = origlen;
1995 *buf_p = buffer;
1996 *sz_p = size;
1997 *used_p = used;
1998 frag->binary_patch_method = patch_method;
1999 return frag;
2001 corrupt:
2002 free(data);
2003 *status_p = -1;
2004 error(_("corrupt binary patch at line %d: %.*s"),
2005 state->linenr-1, llen-1, buffer);
2006 return NULL;
2010 * Returns:
2011 * -1 in case of error,
2012 * the length of the parsed binary patch otherwise
2014 static int parse_binary(struct apply_state *state,
2015 char *buffer,
2016 unsigned long size,
2017 struct patch *patch)
2020 * We have read "GIT binary patch\n"; what follows is a line
2021 * that says the patch method (currently, either "literal" or
2022 * "delta") and the length of data before deflating; a
2023 * sequence of 'length-byte' followed by base-85 encoded data
2024 * follows.
2026 * When a binary patch is reversible, there is another binary
2027 * hunk in the same format, starting with patch method (either
2028 * "literal" or "delta") with the length of data, and a sequence
2029 * of length-byte + base-85 encoded data, terminated with another
2030 * empty line. This data, when applied to the postimage, produces
2031 * the preimage.
2033 struct fragment *forward;
2034 struct fragment *reverse;
2035 int status;
2036 int used, used_1;
2038 forward = parse_binary_hunk(state, &buffer, &size, &status, &used);
2039 if (!forward && !status)
2040 /* there has to be one hunk (forward hunk) */
2041 return error(_("unrecognized binary patch at line %d"), state->linenr-1);
2042 if (status)
2043 /* otherwise we already gave an error message */
2044 return status;
2046 reverse = parse_binary_hunk(state, &buffer, &size, &status, &used_1);
2047 if (reverse)
2048 used += used_1;
2049 else if (status) {
2051 * Not having reverse hunk is not an error, but having
2052 * a corrupt reverse hunk is.
2054 free((void*) forward->patch);
2055 free(forward);
2056 return status;
2058 forward->next = reverse;
2059 patch->fragments = forward;
2060 patch->is_binary = 1;
2061 return used;
2064 static void prefix_one(struct apply_state *state, char **name)
2066 char *old_name = *name;
2067 if (!old_name)
2068 return;
2069 *name = prefix_filename(state->prefix, *name);
2070 free(old_name);
2073 static void prefix_patch(struct apply_state *state, struct patch *p)
2075 if (!state->prefix || p->is_toplevel_relative)
2076 return;
2077 prefix_one(state, &p->new_name);
2078 prefix_one(state, &p->old_name);
2082 * include/exclude
2085 static void add_name_limit(struct apply_state *state,
2086 const char *name,
2087 int exclude)
2089 struct string_list_item *it;
2091 it = string_list_append(&state->limit_by_name, name);
2092 it->util = exclude ? NULL : (void *) 1;
2095 static int use_patch(struct apply_state *state, struct patch *p)
2097 const char *pathname = p->new_name ? p->new_name : p->old_name;
2098 int i;
2100 /* Paths outside are not touched regardless of "--include" */
2101 if (state->prefix && *state->prefix) {
2102 const char *rest;
2103 if (!skip_prefix(pathname, state->prefix, &rest) || !*rest)
2104 return 0;
2107 /* See if it matches any of exclude/include rule */
2108 for (i = 0; i < state->limit_by_name.nr; i++) {
2109 struct string_list_item *it = &state->limit_by_name.items[i];
2110 if (!wildmatch(it->string, pathname, 0))
2111 return (it->util != NULL);
2115 * If we had any include, a path that does not match any rule is
2116 * not used. Otherwise, we saw bunch of exclude rules (or none)
2117 * and such a path is used.
2119 return !state->has_include;
2123 * Read the patch text in "buffer" that extends for "size" bytes; stop
2124 * reading after seeing a single patch (i.e. changes to a single file).
2125 * Create fragments (i.e. patch hunks) and hang them to the given patch.
2127 * Returns:
2128 * -1 if no header was found or parse_binary() failed,
2129 * -128 on another error,
2130 * the number of bytes consumed otherwise,
2131 * so that the caller can call us again for the next patch.
2133 static int parse_chunk(struct apply_state *state, char *buffer, unsigned long size, struct patch *patch)
2135 int hdrsize, patchsize;
2136 int offset = find_header(state, buffer, size, &hdrsize, patch);
2138 if (offset < 0)
2139 return offset;
2141 prefix_patch(state, patch);
2143 if (!use_patch(state, patch))
2144 patch->ws_rule = 0;
2145 else if (patch->new_name)
2146 patch->ws_rule = whitespace_rule(state->repo->index,
2147 patch->new_name);
2148 else
2149 patch->ws_rule = whitespace_rule(state->repo->index,
2150 patch->old_name);
2152 patchsize = parse_single_patch(state,
2153 buffer + offset + hdrsize,
2154 size - offset - hdrsize,
2155 patch);
2157 if (patchsize < 0)
2158 return -128;
2160 if (!patchsize) {
2161 static const char git_binary[] = "GIT binary patch\n";
2162 int hd = hdrsize + offset;
2163 unsigned long llen = linelen(buffer + hd, size - hd);
2165 if (llen == sizeof(git_binary) - 1 &&
2166 !memcmp(git_binary, buffer + hd, llen)) {
2167 int used;
2168 state->linenr++;
2169 used = parse_binary(state, buffer + hd + llen,
2170 size - hd - llen, patch);
2171 if (used < 0)
2172 return -1;
2173 if (used)
2174 patchsize = used + llen;
2175 else
2176 patchsize = 0;
2178 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
2179 static const char *binhdr[] = {
2180 "Binary files ",
2181 "Files ",
2182 NULL,
2184 int i;
2185 for (i = 0; binhdr[i]; i++) {
2186 int len = strlen(binhdr[i]);
2187 if (len < size - hd &&
2188 !memcmp(binhdr[i], buffer + hd, len)) {
2189 state->linenr++;
2190 patch->is_binary = 1;
2191 patchsize = llen;
2192 break;
2197 /* Empty patch cannot be applied if it is a text patch
2198 * without metadata change. A binary patch appears
2199 * empty to us here.
2201 if ((state->apply || state->check) &&
2202 (!patch->is_binary && !metadata_changes(patch))) {
2203 error(_("patch with only garbage at line %d"), state->linenr);
2204 return -128;
2208 return offset + hdrsize + patchsize;
2211 static void reverse_patches(struct patch *p)
2213 for (; p; p = p->next) {
2214 struct fragment *frag = p->fragments;
2216 SWAP(p->new_name, p->old_name);
2217 SWAP(p->new_mode, p->old_mode);
2218 SWAP(p->is_new, p->is_delete);
2219 SWAP(p->lines_added, p->lines_deleted);
2220 SWAP(p->old_oid_prefix, p->new_oid_prefix);
2222 for (; frag; frag = frag->next) {
2223 SWAP(frag->newpos, frag->oldpos);
2224 SWAP(frag->newlines, frag->oldlines);
2229 static const char pluses[] =
2230 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2231 static const char minuses[]=
2232 "----------------------------------------------------------------------";
2234 static void show_stats(struct apply_state *state, struct patch *patch)
2236 struct strbuf qname = STRBUF_INIT;
2237 char *cp = patch->new_name ? patch->new_name : patch->old_name;
2238 int max, add, del;
2240 quote_c_style(cp, &qname, NULL, 0);
2243 * "scale" the filename
2245 max = state->max_len;
2246 if (max > 50)
2247 max = 50;
2249 if (qname.len > max) {
2250 cp = strchr(qname.buf + qname.len + 3 - max, '/');
2251 if (!cp)
2252 cp = qname.buf + qname.len + 3 - max;
2253 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
2256 if (patch->is_binary) {
2257 printf(" %-*s | Bin\n", max, qname.buf);
2258 strbuf_release(&qname);
2259 return;
2262 printf(" %-*s |", max, qname.buf);
2263 strbuf_release(&qname);
2266 * scale the add/delete
2268 max = max + state->max_change > 70 ? 70 - max : state->max_change;
2269 add = patch->lines_added;
2270 del = patch->lines_deleted;
2272 if (state->max_change > 0) {
2273 int total = ((add + del) * max + state->max_change / 2) / state->max_change;
2274 add = (add * max + state->max_change / 2) / state->max_change;
2275 del = total - add;
2277 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
2278 add, pluses, del, minuses);
2281 static int read_old_data(struct stat *st, struct patch *patch,
2282 const char *path, struct strbuf *buf)
2284 int conv_flags = patch->crlf_in_old ?
2285 CONV_EOL_KEEP_CRLF : CONV_EOL_RENORMALIZE;
2286 switch (st->st_mode & S_IFMT) {
2287 case S_IFLNK:
2288 if (strbuf_readlink(buf, path, st->st_size) < 0)
2289 return error(_("unable to read symlink %s"), path);
2290 return 0;
2291 case S_IFREG:
2292 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
2293 return error(_("unable to open or read %s"), path);
2295 * "git apply" without "--index/--cached" should never look
2296 * at the index; the target file may not have been added to
2297 * the index yet, and we may not even be in any Git repository.
2298 * Pass NULL to convert_to_git() to stress this; the function
2299 * should never look at the index when explicit crlf option
2300 * is given.
2302 convert_to_git(NULL, path, buf->buf, buf->len, buf, conv_flags);
2303 return 0;
2304 default:
2305 return -1;
2310 * Update the preimage, and the common lines in postimage,
2311 * from buffer buf of length len. If postlen is 0 the postimage
2312 * is updated in place, otherwise it's updated on a new buffer
2313 * of length postlen
2316 static void update_pre_post_images(struct image *preimage,
2317 struct image *postimage,
2318 char *buf,
2319 size_t len, size_t postlen)
2321 int i, ctx, reduced;
2322 char *new_buf, *old_buf, *fixed;
2323 struct image fixed_preimage;
2326 * Update the preimage with whitespace fixes. Note that we
2327 * are not losing preimage->buf -- apply_one_fragment() will
2328 * free "oldlines".
2330 prepare_image(&fixed_preimage, buf, len, 1);
2331 assert(postlen
2332 ? fixed_preimage.nr == preimage->nr
2333 : fixed_preimage.nr <= preimage->nr);
2334 for (i = 0; i < fixed_preimage.nr; i++)
2335 fixed_preimage.line[i].flag = preimage->line[i].flag;
2336 free(preimage->line_allocated);
2337 *preimage = fixed_preimage;
2340 * Adjust the common context lines in postimage. This can be
2341 * done in-place when we are shrinking it with whitespace
2342 * fixing, but needs a new buffer when ignoring whitespace or
2343 * expanding leading tabs to spaces.
2345 * We trust the caller to tell us if the update can be done
2346 * in place (postlen==0) or not.
2348 old_buf = postimage->buf;
2349 if (postlen)
2350 new_buf = postimage->buf = xmalloc(postlen);
2351 else
2352 new_buf = old_buf;
2353 fixed = preimage->buf;
2355 for (i = reduced = ctx = 0; i < postimage->nr; i++) {
2356 size_t l_len = postimage->line[i].len;
2357 if (!(postimage->line[i].flag & LINE_COMMON)) {
2358 /* an added line -- no counterparts in preimage */
2359 memmove(new_buf, old_buf, l_len);
2360 old_buf += l_len;
2361 new_buf += l_len;
2362 continue;
2365 /* a common context -- skip it in the original postimage */
2366 old_buf += l_len;
2368 /* and find the corresponding one in the fixed preimage */
2369 while (ctx < preimage->nr &&
2370 !(preimage->line[ctx].flag & LINE_COMMON)) {
2371 fixed += preimage->line[ctx].len;
2372 ctx++;
2376 * preimage is expected to run out, if the caller
2377 * fixed addition of trailing blank lines.
2379 if (preimage->nr <= ctx) {
2380 reduced++;
2381 continue;
2384 /* and copy it in, while fixing the line length */
2385 l_len = preimage->line[ctx].len;
2386 memcpy(new_buf, fixed, l_len);
2387 new_buf += l_len;
2388 fixed += l_len;
2389 postimage->line[i].len = l_len;
2390 ctx++;
2393 if (postlen
2394 ? postlen < new_buf - postimage->buf
2395 : postimage->len < new_buf - postimage->buf)
2396 BUG("caller miscounted postlen: asked %d, orig = %d, used = %d",
2397 (int)postlen, (int) postimage->len, (int)(new_buf - postimage->buf));
2399 /* Fix the length of the whole thing */
2400 postimage->len = new_buf - postimage->buf;
2401 postimage->nr -= reduced;
2404 static int line_by_line_fuzzy_match(struct image *img,
2405 struct image *preimage,
2406 struct image *postimage,
2407 unsigned long current,
2408 int current_lno,
2409 int preimage_limit)
2411 int i;
2412 size_t imgoff = 0;
2413 size_t preoff = 0;
2414 size_t postlen = postimage->len;
2415 size_t extra_chars;
2416 char *buf;
2417 char *preimage_eof;
2418 char *preimage_end;
2419 struct strbuf fixed;
2420 char *fixed_buf;
2421 size_t fixed_len;
2423 for (i = 0; i < preimage_limit; i++) {
2424 size_t prelen = preimage->line[i].len;
2425 size_t imglen = img->line[current_lno+i].len;
2427 if (!fuzzy_matchlines(img->buf + current + imgoff, imglen,
2428 preimage->buf + preoff, prelen))
2429 return 0;
2430 if (preimage->line[i].flag & LINE_COMMON)
2431 postlen += imglen - prelen;
2432 imgoff += imglen;
2433 preoff += prelen;
2437 * Ok, the preimage matches with whitespace fuzz.
2439 * imgoff now holds the true length of the target that
2440 * matches the preimage before the end of the file.
2442 * Count the number of characters in the preimage that fall
2443 * beyond the end of the file and make sure that all of them
2444 * are whitespace characters. (This can only happen if
2445 * we are removing blank lines at the end of the file.)
2447 buf = preimage_eof = preimage->buf + preoff;
2448 for ( ; i < preimage->nr; i++)
2449 preoff += preimage->line[i].len;
2450 preimage_end = preimage->buf + preoff;
2451 for ( ; buf < preimage_end; buf++)
2452 if (!isspace(*buf))
2453 return 0;
2456 * Update the preimage and the common postimage context
2457 * lines to use the same whitespace as the target.
2458 * If whitespace is missing in the target (i.e.
2459 * if the preimage extends beyond the end of the file),
2460 * use the whitespace from the preimage.
2462 extra_chars = preimage_end - preimage_eof;
2463 strbuf_init(&fixed, imgoff + extra_chars);
2464 strbuf_add(&fixed, img->buf + current, imgoff);
2465 strbuf_add(&fixed, preimage_eof, extra_chars);
2466 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2467 update_pre_post_images(preimage, postimage,
2468 fixed_buf, fixed_len, postlen);
2469 return 1;
2472 static int match_fragment(struct apply_state *state,
2473 struct image *img,
2474 struct image *preimage,
2475 struct image *postimage,
2476 unsigned long current,
2477 int current_lno,
2478 unsigned ws_rule,
2479 int match_beginning, int match_end)
2481 int i;
2482 char *fixed_buf, *buf, *orig, *target;
2483 struct strbuf fixed;
2484 size_t fixed_len, postlen;
2485 int preimage_limit;
2487 if (preimage->nr + current_lno <= img->nr) {
2489 * The hunk falls within the boundaries of img.
2491 preimage_limit = preimage->nr;
2492 if (match_end && (preimage->nr + current_lno != img->nr))
2493 return 0;
2494 } else if (state->ws_error_action == correct_ws_error &&
2495 (ws_rule & WS_BLANK_AT_EOF)) {
2497 * This hunk extends beyond the end of img, and we are
2498 * removing blank lines at the end of the file. This
2499 * many lines from the beginning of the preimage must
2500 * match with img, and the remainder of the preimage
2501 * must be blank.
2503 preimage_limit = img->nr - current_lno;
2504 } else {
2506 * The hunk extends beyond the end of the img and
2507 * we are not removing blanks at the end, so we
2508 * should reject the hunk at this position.
2510 return 0;
2513 if (match_beginning && current_lno)
2514 return 0;
2516 /* Quick hash check */
2517 for (i = 0; i < preimage_limit; i++)
2518 if ((img->line[current_lno + i].flag & LINE_PATCHED) ||
2519 (preimage->line[i].hash != img->line[current_lno + i].hash))
2520 return 0;
2522 if (preimage_limit == preimage->nr) {
2524 * Do we have an exact match? If we were told to match
2525 * at the end, size must be exactly at current+fragsize,
2526 * otherwise current+fragsize must be still within the preimage,
2527 * and either case, the old piece should match the preimage
2528 * exactly.
2530 if ((match_end
2531 ? (current + preimage->len == img->len)
2532 : (current + preimage->len <= img->len)) &&
2533 !memcmp(img->buf + current, preimage->buf, preimage->len))
2534 return 1;
2535 } else {
2537 * The preimage extends beyond the end of img, so
2538 * there cannot be an exact match.
2540 * There must be one non-blank context line that match
2541 * a line before the end of img.
2543 char *buf_end;
2545 buf = preimage->buf;
2546 buf_end = buf;
2547 for (i = 0; i < preimage_limit; i++)
2548 buf_end += preimage->line[i].len;
2550 for ( ; buf < buf_end; buf++)
2551 if (!isspace(*buf))
2552 break;
2553 if (buf == buf_end)
2554 return 0;
2558 * No exact match. If we are ignoring whitespace, run a line-by-line
2559 * fuzzy matching. We collect all the line length information because
2560 * we need it to adjust whitespace if we match.
2562 if (state->ws_ignore_action == ignore_ws_change)
2563 return line_by_line_fuzzy_match(img, preimage, postimage,
2564 current, current_lno, preimage_limit);
2566 if (state->ws_error_action != correct_ws_error)
2567 return 0;
2570 * The hunk does not apply byte-by-byte, but the hash says
2571 * it might with whitespace fuzz. We weren't asked to
2572 * ignore whitespace, we were asked to correct whitespace
2573 * errors, so let's try matching after whitespace correction.
2575 * While checking the preimage against the target, whitespace
2576 * errors in both fixed, we count how large the corresponding
2577 * postimage needs to be. The postimage prepared by
2578 * apply_one_fragment() has whitespace errors fixed on added
2579 * lines already, but the common lines were propagated as-is,
2580 * which may become longer when their whitespace errors are
2581 * fixed.
2584 /* First count added lines in postimage */
2585 postlen = 0;
2586 for (i = 0; i < postimage->nr; i++) {
2587 if (!(postimage->line[i].flag & LINE_COMMON))
2588 postlen += postimage->line[i].len;
2592 * The preimage may extend beyond the end of the file,
2593 * but in this loop we will only handle the part of the
2594 * preimage that falls within the file.
2596 strbuf_init(&fixed, preimage->len + 1);
2597 orig = preimage->buf;
2598 target = img->buf + current;
2599 for (i = 0; i < preimage_limit; i++) {
2600 size_t oldlen = preimage->line[i].len;
2601 size_t tgtlen = img->line[current_lno + i].len;
2602 size_t fixstart = fixed.len;
2603 struct strbuf tgtfix;
2604 int match;
2606 /* Try fixing the line in the preimage */
2607 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2609 /* Try fixing the line in the target */
2610 strbuf_init(&tgtfix, tgtlen);
2611 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2614 * If they match, either the preimage was based on
2615 * a version before our tree fixed whitespace breakage,
2616 * or we are lacking a whitespace-fix patch the tree
2617 * the preimage was based on already had (i.e. target
2618 * has whitespace breakage, the preimage doesn't).
2619 * In either case, we are fixing the whitespace breakages
2620 * so we might as well take the fix together with their
2621 * real change.
2623 match = (tgtfix.len == fixed.len - fixstart &&
2624 !memcmp(tgtfix.buf, fixed.buf + fixstart,
2625 fixed.len - fixstart));
2627 /* Add the length if this is common with the postimage */
2628 if (preimage->line[i].flag & LINE_COMMON)
2629 postlen += tgtfix.len;
2631 strbuf_release(&tgtfix);
2632 if (!match)
2633 goto unmatch_exit;
2635 orig += oldlen;
2636 target += tgtlen;
2641 * Now handle the lines in the preimage that falls beyond the
2642 * end of the file (if any). They will only match if they are
2643 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2644 * false).
2646 for ( ; i < preimage->nr; i++) {
2647 size_t fixstart = fixed.len; /* start of the fixed preimage */
2648 size_t oldlen = preimage->line[i].len;
2649 int j;
2651 /* Try fixing the line in the preimage */
2652 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2654 for (j = fixstart; j < fixed.len; j++)
2655 if (!isspace(fixed.buf[j]))
2656 goto unmatch_exit;
2658 orig += oldlen;
2662 * Yes, the preimage is based on an older version that still
2663 * has whitespace breakages unfixed, and fixing them makes the
2664 * hunk match. Update the context lines in the postimage.
2666 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2667 if (postlen < postimage->len)
2668 postlen = 0;
2669 update_pre_post_images(preimage, postimage,
2670 fixed_buf, fixed_len, postlen);
2671 return 1;
2673 unmatch_exit:
2674 strbuf_release(&fixed);
2675 return 0;
2678 static int find_pos(struct apply_state *state,
2679 struct image *img,
2680 struct image *preimage,
2681 struct image *postimage,
2682 int line,
2683 unsigned ws_rule,
2684 int match_beginning, int match_end)
2686 int i;
2687 unsigned long backwards, forwards, current;
2688 int backwards_lno, forwards_lno, current_lno;
2691 * When running with --allow-overlap, it is possible that a hunk is
2692 * seen that pretends to start at the beginning (but no longer does),
2693 * and that *still* needs to match the end. So trust `match_end` more
2694 * than `match_beginning`.
2696 if (state->allow_overlap && match_beginning && match_end &&
2697 img->nr - preimage->nr != 0)
2698 match_beginning = 0;
2701 * If match_beginning or match_end is specified, there is no
2702 * point starting from a wrong line that will never match and
2703 * wander around and wait for a match at the specified end.
2705 if (match_beginning)
2706 line = 0;
2707 else if (match_end)
2708 line = img->nr - preimage->nr;
2711 * Because the comparison is unsigned, the following test
2712 * will also take care of a negative line number that can
2713 * result when match_end and preimage is larger than the target.
2715 if ((size_t) line > img->nr)
2716 line = img->nr;
2718 current = 0;
2719 for (i = 0; i < line; i++)
2720 current += img->line[i].len;
2723 * There's probably some smart way to do this, but I'll leave
2724 * that to the smart and beautiful people. I'm simple and stupid.
2726 backwards = current;
2727 backwards_lno = line;
2728 forwards = current;
2729 forwards_lno = line;
2730 current_lno = line;
2732 for (i = 0; ; i++) {
2733 if (match_fragment(state, img, preimage, postimage,
2734 current, current_lno, ws_rule,
2735 match_beginning, match_end))
2736 return current_lno;
2738 again:
2739 if (backwards_lno == 0 && forwards_lno == img->nr)
2740 break;
2742 if (i & 1) {
2743 if (backwards_lno == 0) {
2744 i++;
2745 goto again;
2747 backwards_lno--;
2748 backwards -= img->line[backwards_lno].len;
2749 current = backwards;
2750 current_lno = backwards_lno;
2751 } else {
2752 if (forwards_lno == img->nr) {
2753 i++;
2754 goto again;
2756 forwards += img->line[forwards_lno].len;
2757 forwards_lno++;
2758 current = forwards;
2759 current_lno = forwards_lno;
2763 return -1;
2766 static void remove_first_line(struct image *img)
2768 img->buf += img->line[0].len;
2769 img->len -= img->line[0].len;
2770 img->line++;
2771 img->nr--;
2774 static void remove_last_line(struct image *img)
2776 img->len -= img->line[--img->nr].len;
2780 * The change from "preimage" and "postimage" has been found to
2781 * apply at applied_pos (counts in line numbers) in "img".
2782 * Update "img" to remove "preimage" and replace it with "postimage".
2784 static void update_image(struct apply_state *state,
2785 struct image *img,
2786 int applied_pos,
2787 struct image *preimage,
2788 struct image *postimage)
2791 * remove the copy of preimage at offset in img
2792 * and replace it with postimage
2794 int i, nr;
2795 size_t remove_count, insert_count, applied_at = 0;
2796 char *result;
2797 int preimage_limit;
2800 * If we are removing blank lines at the end of img,
2801 * the preimage may extend beyond the end.
2802 * If that is the case, we must be careful only to
2803 * remove the part of the preimage that falls within
2804 * the boundaries of img. Initialize preimage_limit
2805 * to the number of lines in the preimage that falls
2806 * within the boundaries.
2808 preimage_limit = preimage->nr;
2809 if (preimage_limit > img->nr - applied_pos)
2810 preimage_limit = img->nr - applied_pos;
2812 for (i = 0; i < applied_pos; i++)
2813 applied_at += img->line[i].len;
2815 remove_count = 0;
2816 for (i = 0; i < preimage_limit; i++)
2817 remove_count += img->line[applied_pos + i].len;
2818 insert_count = postimage->len;
2820 /* Adjust the contents */
2821 result = xmalloc(st_add3(st_sub(img->len, remove_count), insert_count, 1));
2822 memcpy(result, img->buf, applied_at);
2823 memcpy(result + applied_at, postimage->buf, postimage->len);
2824 memcpy(result + applied_at + postimage->len,
2825 img->buf + (applied_at + remove_count),
2826 img->len - (applied_at + remove_count));
2827 free(img->buf);
2828 img->buf = result;
2829 img->len += insert_count - remove_count;
2830 result[img->len] = '\0';
2832 /* Adjust the line table */
2833 nr = img->nr + postimage->nr - preimage_limit;
2834 if (preimage_limit < postimage->nr) {
2836 * NOTE: this knows that we never call remove_first_line()
2837 * on anything other than pre/post image.
2839 REALLOC_ARRAY(img->line, nr);
2840 img->line_allocated = img->line;
2842 if (preimage_limit != postimage->nr)
2843 MOVE_ARRAY(img->line + applied_pos + postimage->nr,
2844 img->line + applied_pos + preimage_limit,
2845 img->nr - (applied_pos + preimage_limit));
2846 COPY_ARRAY(img->line + applied_pos, postimage->line, postimage->nr);
2847 if (!state->allow_overlap)
2848 for (i = 0; i < postimage->nr; i++)
2849 img->line[applied_pos + i].flag |= LINE_PATCHED;
2850 img->nr = nr;
2854 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2855 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2856 * replace the part of "img" with "postimage" text.
2858 static int apply_one_fragment(struct apply_state *state,
2859 struct image *img, struct fragment *frag,
2860 int inaccurate_eof, unsigned ws_rule,
2861 int nth_fragment)
2863 int match_beginning, match_end;
2864 const char *patch = frag->patch;
2865 int size = frag->size;
2866 char *old, *oldlines;
2867 struct strbuf newlines;
2868 int new_blank_lines_at_end = 0;
2869 int found_new_blank_lines_at_end = 0;
2870 int hunk_linenr = frag->linenr;
2871 unsigned long leading, trailing;
2872 int pos, applied_pos;
2873 struct image preimage;
2874 struct image postimage;
2876 memset(&preimage, 0, sizeof(preimage));
2877 memset(&postimage, 0, sizeof(postimage));
2878 oldlines = xmalloc(size);
2879 strbuf_init(&newlines, size);
2881 old = oldlines;
2882 while (size > 0) {
2883 char first;
2884 int len = linelen(patch, size);
2885 int plen;
2886 int added_blank_line = 0;
2887 int is_blank_context = 0;
2888 size_t start;
2890 if (!len)
2891 break;
2894 * "plen" is how much of the line we should use for
2895 * the actual patch data. Normally we just remove the
2896 * first character on the line, but if the line is
2897 * followed by "\ No newline", then we also remove the
2898 * last one (which is the newline, of course).
2900 plen = len - 1;
2901 if (len < size && patch[len] == '\\')
2902 plen--;
2903 first = *patch;
2904 if (state->apply_in_reverse) {
2905 if (first == '-')
2906 first = '+';
2907 else if (first == '+')
2908 first = '-';
2911 switch (first) {
2912 case '\n':
2913 /* Newer GNU diff, empty context line */
2914 if (plen < 0)
2915 /* ... followed by '\No newline'; nothing */
2916 break;
2917 *old++ = '\n';
2918 strbuf_addch(&newlines, '\n');
2919 add_line_info(&preimage, "\n", 1, LINE_COMMON);
2920 add_line_info(&postimage, "\n", 1, LINE_COMMON);
2921 is_blank_context = 1;
2922 break;
2923 case ' ':
2924 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2925 ws_blank_line(patch + 1, plen))
2926 is_blank_context = 1;
2927 /* fallthrough */
2928 case '-':
2929 memcpy(old, patch + 1, plen);
2930 add_line_info(&preimage, old, plen,
2931 (first == ' ' ? LINE_COMMON : 0));
2932 old += plen;
2933 if (first == '-')
2934 break;
2935 /* fallthrough */
2936 case '+':
2937 /* --no-add does not add new lines */
2938 if (first == '+' && state->no_add)
2939 break;
2941 start = newlines.len;
2942 if (first != '+' ||
2943 !state->whitespace_error ||
2944 state->ws_error_action != correct_ws_error) {
2945 strbuf_add(&newlines, patch + 1, plen);
2947 else {
2948 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &state->applied_after_fixing_ws);
2950 add_line_info(&postimage, newlines.buf + start, newlines.len - start,
2951 (first == '+' ? 0 : LINE_COMMON));
2952 if (first == '+' &&
2953 (ws_rule & WS_BLANK_AT_EOF) &&
2954 ws_blank_line(patch + 1, plen))
2955 added_blank_line = 1;
2956 break;
2957 case '@': case '\\':
2958 /* Ignore it, we already handled it */
2959 break;
2960 default:
2961 if (state->apply_verbosity > verbosity_normal)
2962 error(_("invalid start of line: '%c'"), first);
2963 applied_pos = -1;
2964 goto out;
2966 if (added_blank_line) {
2967 if (!new_blank_lines_at_end)
2968 found_new_blank_lines_at_end = hunk_linenr;
2969 new_blank_lines_at_end++;
2971 else if (is_blank_context)
2973 else
2974 new_blank_lines_at_end = 0;
2975 patch += len;
2976 size -= len;
2977 hunk_linenr++;
2979 if (inaccurate_eof &&
2980 old > oldlines && old[-1] == '\n' &&
2981 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
2982 old--;
2983 strbuf_setlen(&newlines, newlines.len - 1);
2984 preimage.line_allocated[preimage.nr - 1].len--;
2985 postimage.line_allocated[postimage.nr - 1].len--;
2988 leading = frag->leading;
2989 trailing = frag->trailing;
2992 * A hunk to change lines at the beginning would begin with
2993 * @@ -1,L +N,M @@
2994 * but we need to be careful. -U0 that inserts before the second
2995 * line also has this pattern.
2997 * And a hunk to add to an empty file would begin with
2998 * @@ -0,0 +N,M @@
3000 * In other words, a hunk that is (frag->oldpos <= 1) with or
3001 * without leading context must match at the beginning.
3003 match_beginning = (!frag->oldpos ||
3004 (frag->oldpos == 1 && !state->unidiff_zero));
3007 * A hunk without trailing lines must match at the end.
3008 * However, we simply cannot tell if a hunk must match end
3009 * from the lack of trailing lines if the patch was generated
3010 * with unidiff without any context.
3012 match_end = !state->unidiff_zero && !trailing;
3014 pos = frag->newpos ? (frag->newpos - 1) : 0;
3015 preimage.buf = oldlines;
3016 preimage.len = old - oldlines;
3017 postimage.buf = newlines.buf;
3018 postimage.len = newlines.len;
3019 preimage.line = preimage.line_allocated;
3020 postimage.line = postimage.line_allocated;
3022 for (;;) {
3024 applied_pos = find_pos(state, img, &preimage, &postimage, pos,
3025 ws_rule, match_beginning, match_end);
3027 if (applied_pos >= 0)
3028 break;
3030 /* Am I at my context limits? */
3031 if ((leading <= state->p_context) && (trailing <= state->p_context))
3032 break;
3033 if (match_beginning || match_end) {
3034 match_beginning = match_end = 0;
3035 continue;
3039 * Reduce the number of context lines; reduce both
3040 * leading and trailing if they are equal otherwise
3041 * just reduce the larger context.
3043 if (leading >= trailing) {
3044 remove_first_line(&preimage);
3045 remove_first_line(&postimage);
3046 pos--;
3047 leading--;
3049 if (trailing > leading) {
3050 remove_last_line(&preimage);
3051 remove_last_line(&postimage);
3052 trailing--;
3056 if (applied_pos >= 0) {
3057 if (new_blank_lines_at_end &&
3058 preimage.nr + applied_pos >= img->nr &&
3059 (ws_rule & WS_BLANK_AT_EOF) &&
3060 state->ws_error_action != nowarn_ws_error) {
3061 record_ws_error(state, WS_BLANK_AT_EOF, "+", 1,
3062 found_new_blank_lines_at_end);
3063 if (state->ws_error_action == correct_ws_error) {
3064 while (new_blank_lines_at_end--)
3065 remove_last_line(&postimage);
3068 * We would want to prevent write_out_results()
3069 * from taking place in apply_patch() that follows
3070 * the callchain led us here, which is:
3071 * apply_patch->check_patch_list->check_patch->
3072 * apply_data->apply_fragments->apply_one_fragment
3074 if (state->ws_error_action == die_on_ws_error)
3075 state->apply = 0;
3078 if (state->apply_verbosity > verbosity_normal && applied_pos != pos) {
3079 int offset = applied_pos - pos;
3080 if (state->apply_in_reverse)
3081 offset = 0 - offset;
3082 fprintf_ln(stderr,
3083 Q_("Hunk #%d succeeded at %d (offset %d line).",
3084 "Hunk #%d succeeded at %d (offset %d lines).",
3085 offset),
3086 nth_fragment, applied_pos + 1, offset);
3090 * Warn if it was necessary to reduce the number
3091 * of context lines.
3093 if ((leading != frag->leading ||
3094 trailing != frag->trailing) && state->apply_verbosity > verbosity_silent)
3095 fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"
3096 " to apply fragment at %d"),
3097 leading, trailing, applied_pos+1);
3098 update_image(state, img, applied_pos, &preimage, &postimage);
3099 } else {
3100 if (state->apply_verbosity > verbosity_normal)
3101 error(_("while searching for:\n%.*s"),
3102 (int)(old - oldlines), oldlines);
3105 out:
3106 free(oldlines);
3107 strbuf_release(&newlines);
3108 free(preimage.line_allocated);
3109 free(postimage.line_allocated);
3111 return (applied_pos < 0);
3114 static int apply_binary_fragment(struct apply_state *state,
3115 struct image *img,
3116 struct patch *patch)
3118 struct fragment *fragment = patch->fragments;
3119 unsigned long len;
3120 void *dst;
3122 if (!fragment)
3123 return error(_("missing binary patch data for '%s'"),
3124 patch->new_name ?
3125 patch->new_name :
3126 patch->old_name);
3128 /* Binary patch is irreversible without the optional second hunk */
3129 if (state->apply_in_reverse) {
3130 if (!fragment->next)
3131 return error(_("cannot reverse-apply a binary patch "
3132 "without the reverse hunk to '%s'"),
3133 patch->new_name
3134 ? patch->new_name : patch->old_name);
3135 fragment = fragment->next;
3137 switch (fragment->binary_patch_method) {
3138 case BINARY_DELTA_DEFLATED:
3139 dst = patch_delta(img->buf, img->len, fragment->patch,
3140 fragment->size, &len);
3141 if (!dst)
3142 return -1;
3143 clear_image(img);
3144 img->buf = dst;
3145 img->len = len;
3146 return 0;
3147 case BINARY_LITERAL_DEFLATED:
3148 clear_image(img);
3149 img->len = fragment->size;
3150 img->buf = xmemdupz(fragment->patch, img->len);
3151 return 0;
3153 return -1;
3157 * Replace "img" with the result of applying the binary patch.
3158 * The binary patch data itself in patch->fragment is still kept
3159 * but the preimage prepared by the caller in "img" is freed here
3160 * or in the helper function apply_binary_fragment() this calls.
3162 static int apply_binary(struct apply_state *state,
3163 struct image *img,
3164 struct patch *patch)
3166 const char *name = patch->old_name ? patch->old_name : patch->new_name;
3167 struct object_id oid;
3168 const unsigned hexsz = the_hash_algo->hexsz;
3171 * For safety, we require patch index line to contain
3172 * full hex textual object ID for old and new, at least for now.
3174 if (strlen(patch->old_oid_prefix) != hexsz ||
3175 strlen(patch->new_oid_prefix) != hexsz ||
3176 get_oid_hex(patch->old_oid_prefix, &oid) ||
3177 get_oid_hex(patch->new_oid_prefix, &oid))
3178 return error(_("cannot apply binary patch to '%s' "
3179 "without full index line"), name);
3181 if (patch->old_name) {
3183 * See if the old one matches what the patch
3184 * applies to.
3186 hash_object_file(the_hash_algo, img->buf, img->len, OBJ_BLOB,
3187 &oid);
3188 if (strcmp(oid_to_hex(&oid), patch->old_oid_prefix))
3189 return error(_("the patch applies to '%s' (%s), "
3190 "which does not match the "
3191 "current contents."),
3192 name, oid_to_hex(&oid));
3194 else {
3195 /* Otherwise, the old one must be empty. */
3196 if (img->len)
3197 return error(_("the patch applies to an empty "
3198 "'%s' but it is not empty"), name);
3201 get_oid_hex(patch->new_oid_prefix, &oid);
3202 if (is_null_oid(&oid)) {
3203 clear_image(img);
3204 return 0; /* deletion patch */
3207 if (has_object(the_repository, &oid, 0)) {
3208 /* We already have the postimage */
3209 enum object_type type;
3210 unsigned long size;
3211 char *result;
3213 result = repo_read_object_file(the_repository, &oid, &type,
3214 &size);
3215 if (!result)
3216 return error(_("the necessary postimage %s for "
3217 "'%s' cannot be read"),
3218 patch->new_oid_prefix, name);
3219 clear_image(img);
3220 img->buf = result;
3221 img->len = size;
3222 } else {
3224 * We have verified buf matches the preimage;
3225 * apply the patch data to it, which is stored
3226 * in the patch->fragments->{patch,size}.
3228 if (apply_binary_fragment(state, img, patch))
3229 return error(_("binary patch does not apply to '%s'"),
3230 name);
3232 /* verify that the result matches */
3233 hash_object_file(the_hash_algo, img->buf, img->len, OBJ_BLOB,
3234 &oid);
3235 if (strcmp(oid_to_hex(&oid), patch->new_oid_prefix))
3236 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3237 name, patch->new_oid_prefix, oid_to_hex(&oid));
3240 return 0;
3243 static int apply_fragments(struct apply_state *state, struct image *img, struct patch *patch)
3245 struct fragment *frag = patch->fragments;
3246 const char *name = patch->old_name ? patch->old_name : patch->new_name;
3247 unsigned ws_rule = patch->ws_rule;
3248 unsigned inaccurate_eof = patch->inaccurate_eof;
3249 int nth = 0;
3251 if (patch->is_binary)
3252 return apply_binary(state, img, patch);
3254 while (frag) {
3255 nth++;
3256 if (apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {
3257 error(_("patch failed: %s:%ld"), name, frag->oldpos);
3258 if (!state->apply_with_reject)
3259 return -1;
3260 frag->rejected = 1;
3262 frag = frag->next;
3264 return 0;
3267 static int read_blob_object(struct strbuf *buf, const struct object_id *oid, unsigned mode)
3269 if (S_ISGITLINK(mode)) {
3270 strbuf_grow(buf, 100);
3271 strbuf_addf(buf, "Subproject commit %s\n", oid_to_hex(oid));
3272 } else {
3273 enum object_type type;
3274 unsigned long sz;
3275 char *result;
3277 result = repo_read_object_file(the_repository, oid, &type,
3278 &sz);
3279 if (!result)
3280 return -1;
3281 /* XXX read_sha1_file NUL-terminates */
3282 strbuf_attach(buf, result, sz, sz + 1);
3284 return 0;
3287 static int read_file_or_gitlink(const struct cache_entry *ce, struct strbuf *buf)
3289 if (!ce)
3290 return 0;
3291 return read_blob_object(buf, &ce->oid, ce->ce_mode);
3294 static struct patch *in_fn_table(struct apply_state *state, const char *name)
3296 struct string_list_item *item;
3298 if (!name)
3299 return NULL;
3301 item = string_list_lookup(&state->fn_table, name);
3302 if (item)
3303 return (struct patch *)item->util;
3305 return NULL;
3309 * item->util in the filename table records the status of the path.
3310 * Usually it points at a patch (whose result records the contents
3311 * of it after applying it), but it could be PATH_WAS_DELETED for a
3312 * path that a previously applied patch has already removed, or
3313 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3315 * The latter is needed to deal with a case where two paths A and B
3316 * are swapped by first renaming A to B and then renaming B to A;
3317 * moving A to B should not be prevented due to presence of B as we
3318 * will remove it in a later patch.
3320 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3321 #define PATH_WAS_DELETED ((struct patch *) -1)
3323 static int to_be_deleted(struct patch *patch)
3325 return patch == PATH_TO_BE_DELETED;
3328 static int was_deleted(struct patch *patch)
3330 return patch == PATH_WAS_DELETED;
3333 static void add_to_fn_table(struct apply_state *state, struct patch *patch)
3335 struct string_list_item *item;
3338 * Always add new_name unless patch is a deletion
3339 * This should cover the cases for normal diffs,
3340 * file creations and copies
3342 if (patch->new_name) {
3343 item = string_list_insert(&state->fn_table, patch->new_name);
3344 item->util = patch;
3348 * store a failure on rename/deletion cases because
3349 * later chunks shouldn't patch old names
3351 if ((patch->new_name == NULL) || (patch->is_rename)) {
3352 item = string_list_insert(&state->fn_table, patch->old_name);
3353 item->util = PATH_WAS_DELETED;
3357 static void prepare_fn_table(struct apply_state *state, struct patch *patch)
3360 * store information about incoming file deletion
3362 while (patch) {
3363 if ((patch->new_name == NULL) || (patch->is_rename)) {
3364 struct string_list_item *item;
3365 item = string_list_insert(&state->fn_table, patch->old_name);
3366 item->util = PATH_TO_BE_DELETED;
3368 patch = patch->next;
3372 static int checkout_target(struct index_state *istate,
3373 struct cache_entry *ce, struct stat *st)
3375 struct checkout costate = CHECKOUT_INIT;
3377 costate.refresh_cache = 1;
3378 costate.istate = istate;
3379 if (checkout_entry(ce, &costate, NULL, NULL) ||
3380 lstat(ce->name, st))
3381 return error(_("cannot checkout %s"), ce->name);
3382 return 0;
3385 static struct patch *previous_patch(struct apply_state *state,
3386 struct patch *patch,
3387 int *gone)
3389 struct patch *previous;
3391 *gone = 0;
3392 if (patch->is_copy || patch->is_rename)
3393 return NULL; /* "git" patches do not depend on the order */
3395 previous = in_fn_table(state, patch->old_name);
3396 if (!previous)
3397 return NULL;
3399 if (to_be_deleted(previous))
3400 return NULL; /* the deletion hasn't happened yet */
3402 if (was_deleted(previous))
3403 *gone = 1;
3405 return previous;
3408 static int verify_index_match(struct apply_state *state,
3409 const struct cache_entry *ce,
3410 struct stat *st)
3412 if (S_ISGITLINK(ce->ce_mode)) {
3413 if (!S_ISDIR(st->st_mode))
3414 return -1;
3415 return 0;
3417 return ie_match_stat(state->repo->index, ce, st,
3418 CE_MATCH_IGNORE_VALID | CE_MATCH_IGNORE_SKIP_WORKTREE);
3421 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3423 static int load_patch_target(struct apply_state *state,
3424 struct strbuf *buf,
3425 const struct cache_entry *ce,
3426 struct stat *st,
3427 struct patch *patch,
3428 const char *name,
3429 unsigned expected_mode)
3431 if (state->cached || state->check_index) {
3432 if (read_file_or_gitlink(ce, buf))
3433 return error(_("failed to read %s"), name);
3434 } else if (name) {
3435 if (S_ISGITLINK(expected_mode)) {
3436 if (ce)
3437 return read_file_or_gitlink(ce, buf);
3438 else
3439 return SUBMODULE_PATCH_WITHOUT_INDEX;
3440 } else if (has_symlink_leading_path(name, strlen(name))) {
3441 return error(_("reading from '%s' beyond a symbolic link"), name);
3442 } else {
3443 if (read_old_data(st, patch, name, buf))
3444 return error(_("failed to read %s"), name);
3447 return 0;
3451 * We are about to apply "patch"; populate the "image" with the
3452 * current version we have, from the working tree or from the index,
3453 * depending on the situation e.g. --cached/--index. If we are
3454 * applying a non-git patch that incrementally updates the tree,
3455 * we read from the result of a previous diff.
3457 static int load_preimage(struct apply_state *state,
3458 struct image *image,
3459 struct patch *patch, struct stat *st,
3460 const struct cache_entry *ce)
3462 struct strbuf buf = STRBUF_INIT;
3463 size_t len;
3464 char *img;
3465 struct patch *previous;
3466 int status;
3468 previous = previous_patch(state, patch, &status);
3469 if (status)
3470 return error(_("path %s has been renamed/deleted"),
3471 patch->old_name);
3472 if (previous) {
3473 /* We have a patched copy in memory; use that. */
3474 strbuf_add(&buf, previous->result, previous->resultsize);
3475 } else {
3476 status = load_patch_target(state, &buf, ce, st, patch,
3477 patch->old_name, patch->old_mode);
3478 if (status < 0)
3479 return status;
3480 else if (status == SUBMODULE_PATCH_WITHOUT_INDEX) {
3482 * There is no way to apply subproject
3483 * patch without looking at the index.
3484 * NEEDSWORK: shouldn't this be flagged
3485 * as an error???
3487 free_fragment_list(patch->fragments);
3488 patch->fragments = NULL;
3489 } else if (status) {
3490 return error(_("failed to read %s"), patch->old_name);
3494 img = strbuf_detach(&buf, &len);
3495 prepare_image(image, img, len, !patch->is_binary);
3496 return 0;
3499 static int resolve_to(struct image *image, const struct object_id *result_id)
3501 unsigned long size;
3502 enum object_type type;
3504 clear_image(image);
3506 image->buf = repo_read_object_file(the_repository, result_id, &type,
3507 &size);
3508 if (!image->buf || type != OBJ_BLOB)
3509 die("unable to read blob object %s", oid_to_hex(result_id));
3510 image->len = size;
3512 return 0;
3515 static int three_way_merge(struct apply_state *state,
3516 struct image *image,
3517 char *path,
3518 const struct object_id *base,
3519 const struct object_id *ours,
3520 const struct object_id *theirs)
3522 mmfile_t base_file, our_file, their_file;
3523 mmbuffer_t result = { NULL };
3524 enum ll_merge_result status;
3526 /* resolve trivial cases first */
3527 if (oideq(base, ours))
3528 return resolve_to(image, theirs);
3529 else if (oideq(base, theirs) || oideq(ours, theirs))
3530 return resolve_to(image, ours);
3532 read_mmblob(&base_file, base);
3533 read_mmblob(&our_file, ours);
3534 read_mmblob(&their_file, theirs);
3535 status = ll_merge(&result, path,
3536 &base_file, "base",
3537 &our_file, "ours",
3538 &their_file, "theirs",
3539 state->repo->index,
3540 NULL);
3541 if (status == LL_MERGE_BINARY_CONFLICT)
3542 warning("Cannot merge binary files: %s (%s vs. %s)",
3543 path, "ours", "theirs");
3544 free(base_file.ptr);
3545 free(our_file.ptr);
3546 free(their_file.ptr);
3547 if (status < 0 || !result.ptr) {
3548 free(result.ptr);
3549 return -1;
3551 clear_image(image);
3552 image->buf = result.ptr;
3553 image->len = result.size;
3555 return status;
3559 * When directly falling back to add/add three-way merge, we read from
3560 * the current contents of the new_name. In no cases other than that
3561 * this function will be called.
3563 static int load_current(struct apply_state *state,
3564 struct image *image,
3565 struct patch *patch)
3567 struct strbuf buf = STRBUF_INIT;
3568 int status, pos;
3569 size_t len;
3570 char *img;
3571 struct stat st;
3572 struct cache_entry *ce;
3573 char *name = patch->new_name;
3574 unsigned mode = patch->new_mode;
3576 if (!patch->is_new)
3577 BUG("patch to %s is not a creation", patch->old_name);
3579 pos = index_name_pos(state->repo->index, name, strlen(name));
3580 if (pos < 0)
3581 return error(_("%s: does not exist in index"), name);
3582 ce = state->repo->index->cache[pos];
3583 if (lstat(name, &st)) {
3584 if (errno != ENOENT)
3585 return error_errno("%s", name);
3586 if (checkout_target(state->repo->index, ce, &st))
3587 return -1;
3589 if (verify_index_match(state, ce, &st))
3590 return error(_("%s: does not match index"), name);
3592 status = load_patch_target(state, &buf, ce, &st, patch, name, mode);
3593 if (status < 0)
3594 return status;
3595 else if (status)
3596 return -1;
3597 img = strbuf_detach(&buf, &len);
3598 prepare_image(image, img, len, !patch->is_binary);
3599 return 0;
3602 static int try_threeway(struct apply_state *state,
3603 struct image *image,
3604 struct patch *patch,
3605 struct stat *st,
3606 const struct cache_entry *ce)
3608 struct object_id pre_oid, post_oid, our_oid;
3609 struct strbuf buf = STRBUF_INIT;
3610 size_t len;
3611 int status;
3612 char *img;
3613 struct image tmp_image;
3615 /* No point falling back to 3-way merge in these cases */
3616 if (patch->is_delete ||
3617 S_ISGITLINK(patch->old_mode) || S_ISGITLINK(patch->new_mode) ||
3618 (patch->is_new && !patch->direct_to_threeway) ||
3619 (patch->is_rename && !patch->lines_added && !patch->lines_deleted))
3620 return -1;
3622 /* Preimage the patch was prepared for */
3623 if (patch->is_new)
3624 write_object_file("", 0, OBJ_BLOB, &pre_oid);
3625 else if (repo_get_oid(the_repository, patch->old_oid_prefix, &pre_oid) ||
3626 read_blob_object(&buf, &pre_oid, patch->old_mode))
3627 return error(_("repository lacks the necessary blob to perform 3-way merge."));
3629 if (state->apply_verbosity > verbosity_silent && patch->direct_to_threeway)
3630 fprintf(stderr, _("Performing three-way merge...\n"));
3632 img = strbuf_detach(&buf, &len);
3633 prepare_image(&tmp_image, img, len, 1);
3634 /* Apply the patch to get the post image */
3635 if (apply_fragments(state, &tmp_image, patch) < 0) {
3636 clear_image(&tmp_image);
3637 return -1;
3639 /* post_oid is theirs */
3640 write_object_file(tmp_image.buf, tmp_image.len, OBJ_BLOB, &post_oid);
3641 clear_image(&tmp_image);
3643 /* our_oid is ours */
3644 if (patch->is_new) {
3645 if (load_current(state, &tmp_image, patch))
3646 return error(_("cannot read the current contents of '%s'"),
3647 patch->new_name);
3648 } else {
3649 if (load_preimage(state, &tmp_image, patch, st, ce))
3650 return error(_("cannot read the current contents of '%s'"),
3651 patch->old_name);
3653 write_object_file(tmp_image.buf, tmp_image.len, OBJ_BLOB, &our_oid);
3654 clear_image(&tmp_image);
3656 /* in-core three-way merge between post and our using pre as base */
3657 status = three_way_merge(state, image, patch->new_name,
3658 &pre_oid, &our_oid, &post_oid);
3659 if (status < 0) {
3660 if (state->apply_verbosity > verbosity_silent)
3661 fprintf(stderr,
3662 _("Failed to perform three-way merge...\n"));
3663 return status;
3666 if (status) {
3667 patch->conflicted_threeway = 1;
3668 if (patch->is_new)
3669 oidclr(&patch->threeway_stage[0]);
3670 else
3671 oidcpy(&patch->threeway_stage[0], &pre_oid);
3672 oidcpy(&patch->threeway_stage[1], &our_oid);
3673 oidcpy(&patch->threeway_stage[2], &post_oid);
3674 if (state->apply_verbosity > verbosity_silent)
3675 fprintf(stderr,
3676 _("Applied patch to '%s' with conflicts.\n"),
3677 patch->new_name);
3678 } else {
3679 if (state->apply_verbosity > verbosity_silent)
3680 fprintf(stderr,
3681 _("Applied patch to '%s' cleanly.\n"),
3682 patch->new_name);
3684 return 0;
3687 static int apply_data(struct apply_state *state, struct patch *patch,
3688 struct stat *st, const struct cache_entry *ce)
3690 struct image image;
3692 if (load_preimage(state, &image, patch, st, ce) < 0)
3693 return -1;
3695 if (!state->threeway || try_threeway(state, &image, patch, st, ce) < 0) {
3696 if (state->apply_verbosity > verbosity_silent &&
3697 state->threeway && !patch->direct_to_threeway)
3698 fprintf(stderr, _("Falling back to direct application...\n"));
3700 /* Note: with --reject, apply_fragments() returns 0 */
3701 if (patch->direct_to_threeway || apply_fragments(state, &image, patch) < 0)
3702 return -1;
3704 patch->result = image.buf;
3705 patch->resultsize = image.len;
3706 add_to_fn_table(state, patch);
3707 free(image.line_allocated);
3709 if (0 < patch->is_delete && patch->resultsize)
3710 return error(_("removal patch leaves file contents"));
3712 return 0;
3716 * If "patch" that we are looking at modifies or deletes what we have,
3717 * we would want it not to lose any local modification we have, either
3718 * in the working tree or in the index.
3720 * This also decides if a non-git patch is a creation patch or a
3721 * modification to an existing empty file. We do not check the state
3722 * of the current tree for a creation patch in this function; the caller
3723 * check_patch() separately makes sure (and errors out otherwise) that
3724 * the path the patch creates does not exist in the current tree.
3726 static int check_preimage(struct apply_state *state,
3727 struct patch *patch,
3728 struct cache_entry **ce,
3729 struct stat *st)
3731 const char *old_name = patch->old_name;
3732 struct patch *previous = NULL;
3733 int stat_ret = 0, status;
3734 unsigned st_mode = 0;
3736 if (!old_name)
3737 return 0;
3739 assert(patch->is_new <= 0);
3740 previous = previous_patch(state, patch, &status);
3742 if (status)
3743 return error(_("path %s has been renamed/deleted"), old_name);
3744 if (previous) {
3745 st_mode = previous->new_mode;
3746 } else if (!state->cached) {
3747 stat_ret = lstat(old_name, st);
3748 if (stat_ret && errno != ENOENT)
3749 return error_errno("%s", old_name);
3752 if (state->check_index && !previous) {
3753 int pos = index_name_pos(state->repo->index, old_name,
3754 strlen(old_name));
3755 if (pos < 0) {
3756 if (patch->is_new < 0)
3757 goto is_new;
3758 return error(_("%s: does not exist in index"), old_name);
3760 *ce = state->repo->index->cache[pos];
3761 if (stat_ret < 0) {
3762 if (checkout_target(state->repo->index, *ce, st))
3763 return -1;
3765 if (!state->cached && verify_index_match(state, *ce, st))
3766 return error(_("%s: does not match index"), old_name);
3767 if (state->cached)
3768 st_mode = (*ce)->ce_mode;
3769 } else if (stat_ret < 0) {
3770 if (patch->is_new < 0)
3771 goto is_new;
3772 return error_errno("%s", old_name);
3775 if (!state->cached && !previous)
3776 st_mode = ce_mode_from_stat(*ce, st->st_mode);
3778 if (patch->is_new < 0)
3779 patch->is_new = 0;
3780 if (!patch->old_mode)
3781 patch->old_mode = st_mode;
3782 if ((st_mode ^ patch->old_mode) & S_IFMT)
3783 return error(_("%s: wrong type"), old_name);
3784 if (st_mode != patch->old_mode)
3785 warning(_("%s has type %o, expected %o"),
3786 old_name, st_mode, patch->old_mode);
3787 if (!patch->new_mode && !patch->is_delete)
3788 patch->new_mode = st_mode;
3789 return 0;
3791 is_new:
3792 patch->is_new = 1;
3793 patch->is_delete = 0;
3794 FREE_AND_NULL(patch->old_name);
3795 return 0;
3799 #define EXISTS_IN_INDEX 1
3800 #define EXISTS_IN_WORKTREE 2
3801 #define EXISTS_IN_INDEX_AS_ITA 3
3803 static int check_to_create(struct apply_state *state,
3804 const char *new_name,
3805 int ok_if_exists)
3807 struct stat nst;
3809 if (state->check_index && (!ok_if_exists || !state->cached)) {
3810 int pos;
3812 pos = index_name_pos(state->repo->index, new_name, strlen(new_name));
3813 if (pos >= 0) {
3814 struct cache_entry *ce = state->repo->index->cache[pos];
3816 /* allow ITA, as they do not yet exist in the index */
3817 if (!ok_if_exists && !(ce->ce_flags & CE_INTENT_TO_ADD))
3818 return EXISTS_IN_INDEX;
3820 /* ITA entries can never match working tree files */
3821 if (!state->cached && (ce->ce_flags & CE_INTENT_TO_ADD))
3822 return EXISTS_IN_INDEX_AS_ITA;
3826 if (state->cached)
3827 return 0;
3829 if (!lstat(new_name, &nst)) {
3830 if (S_ISDIR(nst.st_mode) || ok_if_exists)
3831 return 0;
3833 * A leading component of new_name might be a symlink
3834 * that is going to be removed with this patch, but
3835 * still pointing at somewhere that has the path.
3836 * In such a case, path "new_name" does not exist as
3837 * far as git is concerned.
3839 if (has_symlink_leading_path(new_name, strlen(new_name)))
3840 return 0;
3842 return EXISTS_IN_WORKTREE;
3843 } else if (!is_missing_file_error(errno)) {
3844 return error_errno("%s", new_name);
3846 return 0;
3849 static void prepare_symlink_changes(struct apply_state *state, struct patch *patch)
3851 for ( ; patch; patch = patch->next) {
3852 if ((patch->old_name && S_ISLNK(patch->old_mode)) &&
3853 (patch->is_rename || patch->is_delete))
3854 /* the symlink at patch->old_name is removed */
3855 strset_add(&state->removed_symlinks, patch->old_name);
3857 if (patch->new_name && S_ISLNK(patch->new_mode))
3858 /* the symlink at patch->new_name is created or remains */
3859 strset_add(&state->kept_symlinks, patch->new_name);
3863 static int path_is_beyond_symlink_1(struct apply_state *state, struct strbuf *name)
3865 do {
3866 while (--name->len && name->buf[name->len] != '/')
3867 ; /* scan backwards */
3868 if (!name->len)
3869 break;
3870 name->buf[name->len] = '\0';
3871 if (strset_contains(&state->kept_symlinks, name->buf))
3872 return 1;
3873 if (strset_contains(&state->removed_symlinks, name->buf))
3875 * This cannot be "return 0", because we may
3876 * see a new one created at a higher level.
3878 continue;
3880 /* otherwise, check the preimage */
3881 if (state->check_index) {
3882 struct cache_entry *ce;
3884 ce = index_file_exists(state->repo->index, name->buf,
3885 name->len, ignore_case);
3886 if (ce && S_ISLNK(ce->ce_mode))
3887 return 1;
3888 } else {
3889 struct stat st;
3890 if (!lstat(name->buf, &st) && S_ISLNK(st.st_mode))
3891 return 1;
3893 } while (1);
3894 return 0;
3897 static int path_is_beyond_symlink(struct apply_state *state, const char *name_)
3899 int ret;
3900 struct strbuf name = STRBUF_INIT;
3902 assert(*name_ != '\0');
3903 strbuf_addstr(&name, name_);
3904 ret = path_is_beyond_symlink_1(state, &name);
3905 strbuf_release(&name);
3907 return ret;
3910 static int check_unsafe_path(struct patch *patch)
3912 const char *old_name = NULL;
3913 const char *new_name = NULL;
3914 if (patch->is_delete)
3915 old_name = patch->old_name;
3916 else if (!patch->is_new && !patch->is_copy)
3917 old_name = patch->old_name;
3918 if (!patch->is_delete)
3919 new_name = patch->new_name;
3921 if (old_name && !verify_path(old_name, patch->old_mode))
3922 return error(_("invalid path '%s'"), old_name);
3923 if (new_name && !verify_path(new_name, patch->new_mode))
3924 return error(_("invalid path '%s'"), new_name);
3925 return 0;
3929 * Check and apply the patch in-core; leave the result in patch->result
3930 * for the caller to write it out to the final destination.
3932 static int check_patch(struct apply_state *state, struct patch *patch)
3934 struct stat st;
3935 const char *old_name = patch->old_name;
3936 const char *new_name = patch->new_name;
3937 const char *name = old_name ? old_name : new_name;
3938 struct cache_entry *ce = NULL;
3939 struct patch *tpatch;
3940 int ok_if_exists;
3941 int status;
3943 patch->rejected = 1; /* we will drop this after we succeed */
3945 status = check_preimage(state, patch, &ce, &st);
3946 if (status)
3947 return status;
3948 old_name = patch->old_name;
3951 * A type-change diff is always split into a patch to delete
3952 * old, immediately followed by a patch to create new (see
3953 * diff.c::run_diff()); in such a case it is Ok that the entry
3954 * to be deleted by the previous patch is still in the working
3955 * tree and in the index.
3957 * A patch to swap-rename between A and B would first rename A
3958 * to B and then rename B to A. While applying the first one,
3959 * the presence of B should not stop A from getting renamed to
3960 * B; ask to_be_deleted() about the later rename. Removal of
3961 * B and rename from A to B is handled the same way by asking
3962 * was_deleted().
3964 if ((tpatch = in_fn_table(state, new_name)) &&
3965 (was_deleted(tpatch) || to_be_deleted(tpatch)))
3966 ok_if_exists = 1;
3967 else
3968 ok_if_exists = 0;
3970 if (new_name &&
3971 ((0 < patch->is_new) || patch->is_rename || patch->is_copy)) {
3972 int err = check_to_create(state, new_name, ok_if_exists);
3974 if (err && state->threeway) {
3975 patch->direct_to_threeway = 1;
3976 } else switch (err) {
3977 case 0:
3978 break; /* happy */
3979 case EXISTS_IN_INDEX:
3980 return error(_("%s: already exists in index"), new_name);
3981 case EXISTS_IN_INDEX_AS_ITA:
3982 return error(_("%s: does not match index"), new_name);
3983 case EXISTS_IN_WORKTREE:
3984 return error(_("%s: already exists in working directory"),
3985 new_name);
3986 default:
3987 return err;
3990 if (!patch->new_mode) {
3991 if (0 < patch->is_new)
3992 patch->new_mode = S_IFREG | 0644;
3993 else
3994 patch->new_mode = patch->old_mode;
3998 if (new_name && old_name) {
3999 int same = !strcmp(old_name, new_name);
4000 if (!patch->new_mode)
4001 patch->new_mode = patch->old_mode;
4002 if ((patch->old_mode ^ patch->new_mode) & S_IFMT) {
4003 if (same)
4004 return error(_("new mode (%o) of %s does not "
4005 "match old mode (%o)"),
4006 patch->new_mode, new_name,
4007 patch->old_mode);
4008 else
4009 return error(_("new mode (%o) of %s does not "
4010 "match old mode (%o) of %s"),
4011 patch->new_mode, new_name,
4012 patch->old_mode, old_name);
4016 if (!state->unsafe_paths && check_unsafe_path(patch))
4017 return -128;
4020 * An attempt to read from or delete a path that is beyond a
4021 * symbolic link will be prevented by load_patch_target() that
4022 * is called at the beginning of apply_data() so we do not
4023 * have to worry about a patch marked with "is_delete" bit
4024 * here. We however need to make sure that the patch result
4025 * is not deposited to a path that is beyond a symbolic link
4026 * here.
4028 if (!patch->is_delete && path_is_beyond_symlink(state, patch->new_name))
4029 return error(_("affected file '%s' is beyond a symbolic link"),
4030 patch->new_name);
4032 if (apply_data(state, patch, &st, ce) < 0)
4033 return error(_("%s: patch does not apply"), name);
4034 patch->rejected = 0;
4035 return 0;
4038 static int check_patch_list(struct apply_state *state, struct patch *patch)
4040 int err = 0;
4042 prepare_symlink_changes(state, patch);
4043 prepare_fn_table(state, patch);
4044 while (patch) {
4045 int res;
4046 if (state->apply_verbosity > verbosity_normal)
4047 say_patch_name(stderr,
4048 _("Checking patch %s..."), patch);
4049 res = check_patch(state, patch);
4050 if (res == -128)
4051 return -128;
4052 err |= res;
4053 patch = patch->next;
4055 return err;
4058 static int read_apply_cache(struct apply_state *state)
4060 if (state->index_file)
4061 return read_index_from(state->repo->index, state->index_file,
4062 get_git_dir());
4063 else
4064 return repo_read_index(state->repo);
4067 /* This function tries to read the object name from the current index */
4068 static int get_current_oid(struct apply_state *state, const char *path,
4069 struct object_id *oid)
4071 int pos;
4073 if (read_apply_cache(state) < 0)
4074 return -1;
4075 pos = index_name_pos(state->repo->index, path, strlen(path));
4076 if (pos < 0)
4077 return -1;
4078 oidcpy(oid, &state->repo->index->cache[pos]->oid);
4079 return 0;
4082 static int preimage_oid_in_gitlink_patch(struct patch *p, struct object_id *oid)
4085 * A usable gitlink patch has only one fragment (hunk) that looks like:
4086 * @@ -1 +1 @@
4087 * -Subproject commit <old sha1>
4088 * +Subproject commit <new sha1>
4089 * or
4090 * @@ -1 +0,0 @@
4091 * -Subproject commit <old sha1>
4092 * for a removal patch.
4094 struct fragment *hunk = p->fragments;
4095 static const char heading[] = "-Subproject commit ";
4096 char *preimage;
4098 if (/* does the patch have only one hunk? */
4099 hunk && !hunk->next &&
4100 /* is its preimage one line? */
4101 hunk->oldpos == 1 && hunk->oldlines == 1 &&
4102 /* does preimage begin with the heading? */
4103 (preimage = memchr(hunk->patch, '\n', hunk->size)) != NULL &&
4104 starts_with(++preimage, heading) &&
4105 /* does it record full SHA-1? */
4106 !get_oid_hex(preimage + sizeof(heading) - 1, oid) &&
4107 preimage[sizeof(heading) + the_hash_algo->hexsz - 1] == '\n' &&
4108 /* does the abbreviated name on the index line agree with it? */
4109 starts_with(preimage + sizeof(heading) - 1, p->old_oid_prefix))
4110 return 0; /* it all looks fine */
4112 /* we may have full object name on the index line */
4113 return get_oid_hex(p->old_oid_prefix, oid);
4116 /* Build an index that contains just the files needed for a 3way merge */
4117 static int build_fake_ancestor(struct apply_state *state, struct patch *list)
4119 struct patch *patch;
4120 struct index_state result = INDEX_STATE_INIT(state->repo);
4121 struct lock_file lock = LOCK_INIT;
4122 int res;
4124 /* Once we start supporting the reverse patch, it may be
4125 * worth showing the new sha1 prefix, but until then...
4127 for (patch = list; patch; patch = patch->next) {
4128 struct object_id oid;
4129 struct cache_entry *ce;
4130 const char *name;
4132 name = patch->old_name ? patch->old_name : patch->new_name;
4133 if (0 < patch->is_new)
4134 continue;
4136 if (S_ISGITLINK(patch->old_mode)) {
4137 if (!preimage_oid_in_gitlink_patch(patch, &oid))
4138 ; /* ok, the textual part looks sane */
4139 else
4140 return error(_("sha1 information is lacking or "
4141 "useless for submodule %s"), name);
4142 } else if (!repo_get_oid_blob(the_repository, patch->old_oid_prefix, &oid)) {
4143 ; /* ok */
4144 } else if (!patch->lines_added && !patch->lines_deleted) {
4145 /* mode-only change: update the current */
4146 if (get_current_oid(state, patch->old_name, &oid))
4147 return error(_("mode change for %s, which is not "
4148 "in current HEAD"), name);
4149 } else
4150 return error(_("sha1 information is lacking or useless "
4151 "(%s)."), name);
4153 ce = make_cache_entry(&result, patch->old_mode, &oid, name, 0, 0);
4154 if (!ce)
4155 return error(_("make_cache_entry failed for path '%s'"),
4156 name);
4157 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) {
4158 discard_cache_entry(ce);
4159 return error(_("could not add %s to temporary index"),
4160 name);
4164 hold_lock_file_for_update(&lock, state->fake_ancestor, LOCK_DIE_ON_ERROR);
4165 res = write_locked_index(&result, &lock, COMMIT_LOCK);
4166 discard_index(&result);
4168 if (res)
4169 return error(_("could not write temporary index to %s"),
4170 state->fake_ancestor);
4172 return 0;
4175 static void stat_patch_list(struct apply_state *state, struct patch *patch)
4177 int files, adds, dels;
4179 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
4180 files++;
4181 adds += patch->lines_added;
4182 dels += patch->lines_deleted;
4183 show_stats(state, patch);
4186 print_stat_summary(stdout, files, adds, dels);
4189 static void numstat_patch_list(struct apply_state *state,
4190 struct patch *patch)
4192 for ( ; patch; patch = patch->next) {
4193 const char *name;
4194 name = patch->new_name ? patch->new_name : patch->old_name;
4195 if (patch->is_binary)
4196 printf("-\t-\t");
4197 else
4198 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
4199 write_name_quoted(name, stdout, state->line_termination);
4203 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
4205 if (mode)
4206 printf(" %s mode %06o %s\n", newdelete, mode, name);
4207 else
4208 printf(" %s %s\n", newdelete, name);
4211 static void show_mode_change(struct patch *p, int show_name)
4213 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
4214 if (show_name)
4215 printf(" mode change %06o => %06o %s\n",
4216 p->old_mode, p->new_mode, p->new_name);
4217 else
4218 printf(" mode change %06o => %06o\n",
4219 p->old_mode, p->new_mode);
4223 static void show_rename_copy(struct patch *p)
4225 const char *renamecopy = p->is_rename ? "rename" : "copy";
4226 const char *old_name, *new_name;
4228 /* Find common prefix */
4229 old_name = p->old_name;
4230 new_name = p->new_name;
4231 while (1) {
4232 const char *slash_old, *slash_new;
4233 slash_old = strchr(old_name, '/');
4234 slash_new = strchr(new_name, '/');
4235 if (!slash_old ||
4236 !slash_new ||
4237 slash_old - old_name != slash_new - new_name ||
4238 memcmp(old_name, new_name, slash_new - new_name))
4239 break;
4240 old_name = slash_old + 1;
4241 new_name = slash_new + 1;
4243 /* p->old_name through old_name is the common prefix, and old_name and
4244 * new_name through the end of names are renames
4246 if (old_name != p->old_name)
4247 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
4248 (int)(old_name - p->old_name), p->old_name,
4249 old_name, new_name, p->score);
4250 else
4251 printf(" %s %s => %s (%d%%)\n", renamecopy,
4252 p->old_name, p->new_name, p->score);
4253 show_mode_change(p, 0);
4256 static void summary_patch_list(struct patch *patch)
4258 struct patch *p;
4260 for (p = patch; p; p = p->next) {
4261 if (p->is_new)
4262 show_file_mode_name("create", p->new_mode, p->new_name);
4263 else if (p->is_delete)
4264 show_file_mode_name("delete", p->old_mode, p->old_name);
4265 else {
4266 if (p->is_rename || p->is_copy)
4267 show_rename_copy(p);
4268 else {
4269 if (p->score) {
4270 printf(" rewrite %s (%d%%)\n",
4271 p->new_name, p->score);
4272 show_mode_change(p, 0);
4274 else
4275 show_mode_change(p, 1);
4281 static void patch_stats(struct apply_state *state, struct patch *patch)
4283 int lines = patch->lines_added + patch->lines_deleted;
4285 if (lines > state->max_change)
4286 state->max_change = lines;
4287 if (patch->old_name) {
4288 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
4289 if (!len)
4290 len = strlen(patch->old_name);
4291 if (len > state->max_len)
4292 state->max_len = len;
4294 if (patch->new_name) {
4295 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
4296 if (!len)
4297 len = strlen(patch->new_name);
4298 if (len > state->max_len)
4299 state->max_len = len;
4303 static int remove_file(struct apply_state *state, struct patch *patch, int rmdir_empty)
4305 if (state->update_index && !state->ita_only) {
4306 if (remove_file_from_index(state->repo->index, patch->old_name) < 0)
4307 return error(_("unable to remove %s from index"), patch->old_name);
4309 if (!state->cached) {
4310 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
4311 remove_path(patch->old_name);
4314 return 0;
4317 static int add_index_file(struct apply_state *state,
4318 const char *path,
4319 unsigned mode,
4320 void *buf,
4321 unsigned long size)
4323 struct stat st;
4324 struct cache_entry *ce;
4325 int namelen = strlen(path);
4327 ce = make_empty_cache_entry(state->repo->index, namelen);
4328 memcpy(ce->name, path, namelen);
4329 ce->ce_mode = create_ce_mode(mode);
4330 ce->ce_flags = create_ce_flags(0);
4331 ce->ce_namelen = namelen;
4332 if (state->ita_only) {
4333 ce->ce_flags |= CE_INTENT_TO_ADD;
4334 set_object_name_for_intent_to_add_entry(ce);
4335 } else if (S_ISGITLINK(mode)) {
4336 const char *s;
4338 if (!skip_prefix(buf, "Subproject commit ", &s) ||
4339 get_oid_hex(s, &ce->oid)) {
4340 discard_cache_entry(ce);
4341 return error(_("corrupt patch for submodule %s"), path);
4343 } else {
4344 if (!state->cached) {
4345 if (lstat(path, &st) < 0) {
4346 discard_cache_entry(ce);
4347 return error_errno(_("unable to stat newly "
4348 "created file '%s'"),
4349 path);
4351 fill_stat_cache_info(state->repo->index, ce, &st);
4353 if (write_object_file(buf, size, OBJ_BLOB, &ce->oid) < 0) {
4354 discard_cache_entry(ce);
4355 return error(_("unable to create backing store "
4356 "for newly created file %s"), path);
4359 if (add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) < 0) {
4360 discard_cache_entry(ce);
4361 return error(_("unable to add cache entry for %s"), path);
4364 return 0;
4368 * Returns:
4369 * -1 if an unrecoverable error happened
4370 * 0 if everything went well
4371 * 1 if a recoverable error happened
4373 static int try_create_file(struct apply_state *state, const char *path,
4374 unsigned int mode, const char *buf,
4375 unsigned long size)
4377 int fd, res;
4378 struct strbuf nbuf = STRBUF_INIT;
4380 if (S_ISGITLINK(mode)) {
4381 struct stat st;
4382 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
4383 return 0;
4384 return !!mkdir(path, 0777);
4387 if (has_symlinks && S_ISLNK(mode))
4388 /* Although buf:size is counted string, it also is NUL
4389 * terminated.
4391 return !!symlink(buf, path);
4393 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
4394 if (fd < 0)
4395 return 1;
4397 if (convert_to_working_tree(state->repo->index, path, buf, size, &nbuf, NULL)) {
4398 size = nbuf.len;
4399 buf = nbuf.buf;
4402 res = write_in_full(fd, buf, size) < 0;
4403 if (res)
4404 error_errno(_("failed to write to '%s'"), path);
4405 strbuf_release(&nbuf);
4407 if (close(fd) < 0 && !res)
4408 return error_errno(_("closing file '%s'"), path);
4410 return res ? -1 : 0;
4414 * We optimistically assume that the directories exist,
4415 * which is true 99% of the time anyway. If they don't,
4416 * we create them and try again.
4418 * Returns:
4419 * -1 on error
4420 * 0 otherwise
4422 static int create_one_file(struct apply_state *state,
4423 char *path,
4424 unsigned mode,
4425 const char *buf,
4426 unsigned long size)
4428 int res;
4430 if (state->cached)
4431 return 0;
4434 * We already try to detect whether files are beyond a symlink in our
4435 * up-front checks. But in the case where symlinks are created by any
4436 * of the intermediate hunks it can happen that our up-front checks
4437 * didn't yet see the symlink, but at the point of arriving here there
4438 * in fact is one. We thus repeat the check for symlinks here.
4440 * Note that this does not make the up-front check obsolete as the
4441 * failure mode is different:
4443 * - The up-front checks cause us to abort before we have written
4444 * anything into the working directory. So when we exit this way the
4445 * working directory remains clean.
4447 * - The checks here happen in the middle of the action where we have
4448 * already started to apply the patch. The end result will be a dirty
4449 * working directory.
4451 * Ideally, we should update the up-front checks to catch what would
4452 * happen when we apply the patch before we damage the working tree.
4453 * We have all the information necessary to do so. But for now, as a
4454 * part of embargoed security work, having this check would serve as a
4455 * reasonable first step.
4457 if (path_is_beyond_symlink(state, path))
4458 return error(_("affected file '%s' is beyond a symbolic link"), path);
4460 res = try_create_file(state, path, mode, buf, size);
4461 if (res < 0)
4462 return -1;
4463 if (!res)
4464 return 0;
4466 if (errno == ENOENT) {
4467 if (safe_create_leading_directories_no_share(path))
4468 return 0;
4469 res = try_create_file(state, path, mode, buf, size);
4470 if (res < 0)
4471 return -1;
4472 if (!res)
4473 return 0;
4476 if (errno == EEXIST || errno == EACCES) {
4477 /* We may be trying to create a file where a directory
4478 * used to be.
4480 struct stat st;
4481 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
4482 errno = EEXIST;
4485 if (errno == EEXIST) {
4486 unsigned int nr = getpid();
4488 for (;;) {
4489 char newpath[PATH_MAX];
4490 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
4491 res = try_create_file(state, newpath, mode, buf, size);
4492 if (res < 0)
4493 return -1;
4494 if (!res) {
4495 if (!rename(newpath, path))
4496 return 0;
4497 unlink_or_warn(newpath);
4498 break;
4500 if (errno != EEXIST)
4501 break;
4502 ++nr;
4505 return error_errno(_("unable to write file '%s' mode %o"),
4506 path, mode);
4509 static int add_conflicted_stages_file(struct apply_state *state,
4510 struct patch *patch)
4512 int stage, namelen;
4513 unsigned mode;
4514 struct cache_entry *ce;
4516 if (!state->update_index)
4517 return 0;
4518 namelen = strlen(patch->new_name);
4519 mode = patch->new_mode ? patch->new_mode : (S_IFREG | 0644);
4521 remove_file_from_index(state->repo->index, patch->new_name);
4522 for (stage = 1; stage < 4; stage++) {
4523 if (is_null_oid(&patch->threeway_stage[stage - 1]))
4524 continue;
4525 ce = make_empty_cache_entry(state->repo->index, namelen);
4526 memcpy(ce->name, patch->new_name, namelen);
4527 ce->ce_mode = create_ce_mode(mode);
4528 ce->ce_flags = create_ce_flags(stage);
4529 ce->ce_namelen = namelen;
4530 oidcpy(&ce->oid, &patch->threeway_stage[stage - 1]);
4531 if (add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) < 0) {
4532 discard_cache_entry(ce);
4533 return error(_("unable to add cache entry for %s"),
4534 patch->new_name);
4538 return 0;
4541 static int create_file(struct apply_state *state, struct patch *patch)
4543 char *path = patch->new_name;
4544 unsigned mode = patch->new_mode;
4545 unsigned long size = patch->resultsize;
4546 char *buf = patch->result;
4548 if (!mode)
4549 mode = S_IFREG | 0644;
4550 if (create_one_file(state, path, mode, buf, size))
4551 return -1;
4553 if (patch->conflicted_threeway)
4554 return add_conflicted_stages_file(state, patch);
4555 else if (state->update_index)
4556 return add_index_file(state, path, mode, buf, size);
4557 return 0;
4560 /* phase zero is to remove, phase one is to create */
4561 static int write_out_one_result(struct apply_state *state,
4562 struct patch *patch,
4563 int phase)
4565 if (patch->is_delete > 0) {
4566 if (phase == 0)
4567 return remove_file(state, patch, 1);
4568 return 0;
4570 if (patch->is_new > 0 || patch->is_copy) {
4571 if (phase == 1)
4572 return create_file(state, patch);
4573 return 0;
4576 * Rename or modification boils down to the same
4577 * thing: remove the old, write the new
4579 if (phase == 0)
4580 return remove_file(state, patch, patch->is_rename);
4581 if (phase == 1)
4582 return create_file(state, patch);
4583 return 0;
4586 static int write_out_one_reject(struct apply_state *state, struct patch *patch)
4588 FILE *rej;
4589 char namebuf[PATH_MAX];
4590 struct fragment *frag;
4591 int cnt = 0;
4592 struct strbuf sb = STRBUF_INIT;
4594 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
4595 if (!frag->rejected)
4596 continue;
4597 cnt++;
4600 if (!cnt) {
4601 if (state->apply_verbosity > verbosity_normal)
4602 say_patch_name(stderr,
4603 _("Applied patch %s cleanly."), patch);
4604 return 0;
4607 /* This should not happen, because a removal patch that leaves
4608 * contents are marked "rejected" at the patch level.
4610 if (!patch->new_name)
4611 die(_("internal error"));
4613 /* Say this even without --verbose */
4614 strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",
4615 "Applying patch %%s with %d rejects...",
4616 cnt),
4617 cnt);
4618 if (state->apply_verbosity > verbosity_silent)
4619 say_patch_name(stderr, sb.buf, patch);
4620 strbuf_release(&sb);
4622 cnt = strlen(patch->new_name);
4623 if (ARRAY_SIZE(namebuf) <= cnt + 5) {
4624 cnt = ARRAY_SIZE(namebuf) - 5;
4625 warning(_("truncating .rej filename to %.*s.rej"),
4626 cnt - 1, patch->new_name);
4628 memcpy(namebuf, patch->new_name, cnt);
4629 memcpy(namebuf + cnt, ".rej", 5);
4631 rej = fopen(namebuf, "w");
4632 if (!rej)
4633 return error_errno(_("cannot open %s"), namebuf);
4635 /* Normal git tools never deal with .rej, so do not pretend
4636 * this is a git patch by saying --git or giving extended
4637 * headers. While at it, maybe please "kompare" that wants
4638 * the trailing TAB and some garbage at the end of line ;-).
4640 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
4641 patch->new_name, patch->new_name);
4642 for (cnt = 1, frag = patch->fragments;
4643 frag;
4644 cnt++, frag = frag->next) {
4645 if (!frag->rejected) {
4646 if (state->apply_verbosity > verbosity_silent)
4647 fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);
4648 continue;
4650 if (state->apply_verbosity > verbosity_silent)
4651 fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);
4652 fprintf(rej, "%.*s", frag->size, frag->patch);
4653 if (frag->patch[frag->size-1] != '\n')
4654 fputc('\n', rej);
4656 fclose(rej);
4657 return -1;
4661 * Returns:
4662 * -1 if an error happened
4663 * 0 if the patch applied cleanly
4664 * 1 if the patch did not apply cleanly
4666 static int write_out_results(struct apply_state *state, struct patch *list)
4668 int phase;
4669 int errs = 0;
4670 struct patch *l;
4671 struct string_list cpath = STRING_LIST_INIT_DUP;
4673 for (phase = 0; phase < 2; phase++) {
4674 l = list;
4675 while (l) {
4676 if (l->rejected)
4677 errs = 1;
4678 else {
4679 if (write_out_one_result(state, l, phase)) {
4680 string_list_clear(&cpath, 0);
4681 return -1;
4683 if (phase == 1) {
4684 if (write_out_one_reject(state, l))
4685 errs = 1;
4686 if (l->conflicted_threeway) {
4687 string_list_append(&cpath, l->new_name);
4688 errs = 1;
4692 l = l->next;
4696 if (cpath.nr) {
4697 struct string_list_item *item;
4699 string_list_sort(&cpath);
4700 if (state->apply_verbosity > verbosity_silent) {
4701 for_each_string_list_item(item, &cpath)
4702 fprintf(stderr, "U %s\n", item->string);
4704 string_list_clear(&cpath, 0);
4707 * rerere relies on the partially merged result being in the working
4708 * tree with conflict markers, but that isn't written with --cached.
4710 if (!state->cached)
4711 repo_rerere(state->repo, 0);
4714 return errs;
4718 * Try to apply a patch.
4720 * Returns:
4721 * -128 if a bad error happened (like patch unreadable)
4722 * -1 if patch did not apply and user cannot deal with it
4723 * 0 if the patch applied
4724 * 1 if the patch did not apply but user might fix it
4726 static int apply_patch(struct apply_state *state,
4727 int fd,
4728 const char *filename,
4729 int options)
4731 size_t offset;
4732 struct strbuf buf = STRBUF_INIT; /* owns the patch text */
4733 struct patch *list = NULL, **listp = &list;
4734 int skipped_patch = 0;
4735 int res = 0;
4736 int flush_attributes = 0;
4738 state->patch_input_file = filename;
4739 if (read_patch_file(&buf, fd) < 0)
4740 return -128;
4741 offset = 0;
4742 while (offset < buf.len) {
4743 struct patch *patch;
4744 int nr;
4746 CALLOC_ARRAY(patch, 1);
4747 patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF);
4748 patch->recount = !!(options & APPLY_OPT_RECOUNT);
4749 nr = parse_chunk(state, buf.buf + offset, buf.len - offset, patch);
4750 if (nr < 0) {
4751 free_patch(patch);
4752 if (nr == -128) {
4753 res = -128;
4754 goto end;
4756 break;
4758 if (state->apply_in_reverse)
4759 reverse_patches(patch);
4760 if (use_patch(state, patch)) {
4761 patch_stats(state, patch);
4762 if (!list || !state->apply_in_reverse) {
4763 *listp = patch;
4764 listp = &patch->next;
4765 } else {
4766 patch->next = list;
4767 list = patch;
4770 if ((patch->new_name &&
4771 ends_with_path_components(patch->new_name,
4772 GITATTRIBUTES_FILE)) ||
4773 (patch->old_name &&
4774 ends_with_path_components(patch->old_name,
4775 GITATTRIBUTES_FILE)))
4776 flush_attributes = 1;
4778 else {
4779 if (state->apply_verbosity > verbosity_normal)
4780 say_patch_name(stderr, _("Skipped patch '%s'."), patch);
4781 free_patch(patch);
4782 skipped_patch++;
4784 offset += nr;
4787 if (!list && !skipped_patch) {
4788 if (!state->allow_empty) {
4789 error(_("No valid patches in input (allow with \"--allow-empty\")"));
4790 res = -128;
4792 goto end;
4795 if (state->whitespace_error && (state->ws_error_action == die_on_ws_error))
4796 state->apply = 0;
4798 state->update_index = (state->check_index || state->ita_only) && state->apply;
4799 if (state->update_index && !is_lock_file_locked(&state->lock_file)) {
4800 if (state->index_file)
4801 hold_lock_file_for_update(&state->lock_file,
4802 state->index_file,
4803 LOCK_DIE_ON_ERROR);
4804 else
4805 repo_hold_locked_index(state->repo, &state->lock_file,
4806 LOCK_DIE_ON_ERROR);
4809 if (state->check_index && read_apply_cache(state) < 0) {
4810 error(_("unable to read index file"));
4811 res = -128;
4812 goto end;
4815 if (state->check || state->apply) {
4816 int r = check_patch_list(state, list);
4817 if (r == -128) {
4818 res = -128;
4819 goto end;
4821 if (r < 0 && !state->apply_with_reject) {
4822 res = -1;
4823 goto end;
4827 if (state->apply) {
4828 int write_res = write_out_results(state, list);
4829 if (write_res < 0) {
4830 res = -128;
4831 goto end;
4833 if (write_res > 0) {
4834 /* with --3way, we still need to write the index out */
4835 res = state->apply_with_reject ? -1 : 1;
4836 goto end;
4840 if (state->fake_ancestor &&
4841 build_fake_ancestor(state, list)) {
4842 res = -128;
4843 goto end;
4846 if (state->diffstat && state->apply_verbosity > verbosity_silent)
4847 stat_patch_list(state, list);
4849 if (state->numstat && state->apply_verbosity > verbosity_silent)
4850 numstat_patch_list(state, list);
4852 if (state->summary && state->apply_verbosity > verbosity_silent)
4853 summary_patch_list(list);
4855 if (flush_attributes)
4856 reset_parsed_attributes();
4857 end:
4858 free_patch_list(list);
4859 strbuf_release(&buf);
4860 string_list_clear(&state->fn_table, 0);
4861 return res;
4864 static int apply_option_parse_exclude(const struct option *opt,
4865 const char *arg, int unset)
4867 struct apply_state *state = opt->value;
4869 BUG_ON_OPT_NEG(unset);
4871 add_name_limit(state, arg, 1);
4872 return 0;
4875 static int apply_option_parse_include(const struct option *opt,
4876 const char *arg, int unset)
4878 struct apply_state *state = opt->value;
4880 BUG_ON_OPT_NEG(unset);
4882 add_name_limit(state, arg, 0);
4883 state->has_include = 1;
4884 return 0;
4887 static int apply_option_parse_p(const struct option *opt,
4888 const char *arg,
4889 int unset)
4891 struct apply_state *state = opt->value;
4893 BUG_ON_OPT_NEG(unset);
4895 state->p_value = atoi(arg);
4896 state->p_value_known = 1;
4897 return 0;
4900 static int apply_option_parse_space_change(const struct option *opt,
4901 const char *arg, int unset)
4903 struct apply_state *state = opt->value;
4905 BUG_ON_OPT_ARG(arg);
4907 if (unset)
4908 state->ws_ignore_action = ignore_ws_none;
4909 else
4910 state->ws_ignore_action = ignore_ws_change;
4911 return 0;
4914 static int apply_option_parse_whitespace(const struct option *opt,
4915 const char *arg, int unset)
4917 struct apply_state *state = opt->value;
4919 BUG_ON_OPT_NEG(unset);
4921 state->whitespace_option = arg;
4922 if (parse_whitespace_option(state, arg))
4923 return -1;
4924 return 0;
4927 static int apply_option_parse_directory(const struct option *opt,
4928 const char *arg, int unset)
4930 struct apply_state *state = opt->value;
4932 BUG_ON_OPT_NEG(unset);
4934 strbuf_reset(&state->root);
4935 strbuf_addstr(&state->root, arg);
4936 strbuf_complete(&state->root, '/');
4937 return 0;
4940 int apply_all_patches(struct apply_state *state,
4941 int argc,
4942 const char **argv,
4943 int options)
4945 int i;
4946 int res;
4947 int errs = 0;
4948 int read_stdin = 1;
4950 for (i = 0; i < argc; i++) {
4951 const char *arg = argv[i];
4952 char *to_free = NULL;
4953 int fd;
4955 if (!strcmp(arg, "-")) {
4956 res = apply_patch(state, 0, "<stdin>", options);
4957 if (res < 0)
4958 goto end;
4959 errs |= res;
4960 read_stdin = 0;
4961 continue;
4962 } else
4963 arg = to_free = prefix_filename(state->prefix, arg);
4965 fd = open(arg, O_RDONLY);
4966 if (fd < 0) {
4967 error(_("can't open patch '%s': %s"), arg, strerror(errno));
4968 res = -128;
4969 free(to_free);
4970 goto end;
4972 read_stdin = 0;
4973 set_default_whitespace_mode(state);
4974 res = apply_patch(state, fd, arg, options);
4975 close(fd);
4976 free(to_free);
4977 if (res < 0)
4978 goto end;
4979 errs |= res;
4981 set_default_whitespace_mode(state);
4982 if (read_stdin) {
4983 res = apply_patch(state, 0, "<stdin>", options);
4984 if (res < 0)
4985 goto end;
4986 errs |= res;
4989 if (state->whitespace_error) {
4990 if (state->squelch_whitespace_errors &&
4991 state->squelch_whitespace_errors < state->whitespace_error) {
4992 int squelched =
4993 state->whitespace_error - state->squelch_whitespace_errors;
4994 warning(Q_("squelched %d whitespace error",
4995 "squelched %d whitespace errors",
4996 squelched),
4997 squelched);
4999 if (state->ws_error_action == die_on_ws_error) {
5000 error(Q_("%d line adds whitespace errors.",
5001 "%d lines add whitespace errors.",
5002 state->whitespace_error),
5003 state->whitespace_error);
5004 res = -128;
5005 goto end;
5007 if (state->applied_after_fixing_ws && state->apply)
5008 warning(Q_("%d line applied after"
5009 " fixing whitespace errors.",
5010 "%d lines applied after"
5011 " fixing whitespace errors.",
5012 state->applied_after_fixing_ws),
5013 state->applied_after_fixing_ws);
5014 else if (state->whitespace_error)
5015 warning(Q_("%d line adds whitespace errors.",
5016 "%d lines add whitespace errors.",
5017 state->whitespace_error),
5018 state->whitespace_error);
5021 if (state->update_index) {
5022 res = write_locked_index(state->repo->index, &state->lock_file, COMMIT_LOCK);
5023 if (res) {
5024 error(_("Unable to write new index file"));
5025 res = -128;
5026 goto end;
5030 res = !!errs;
5032 end:
5033 rollback_lock_file(&state->lock_file);
5035 if (state->apply_verbosity <= verbosity_silent) {
5036 set_error_routine(state->saved_error_routine);
5037 set_warn_routine(state->saved_warn_routine);
5040 if (res > -1)
5041 return res;
5042 return (res == -1 ? 1 : 128);
5045 int apply_parse_options(int argc, const char **argv,
5046 struct apply_state *state,
5047 int *force_apply, int *options,
5048 const char * const *apply_usage)
5050 struct option builtin_apply_options[] = {
5051 OPT_CALLBACK_F(0, "exclude", state, N_("path"),
5052 N_("don't apply changes matching the given path"),
5053 PARSE_OPT_NONEG, apply_option_parse_exclude),
5054 OPT_CALLBACK_F(0, "include", state, N_("path"),
5055 N_("apply changes matching the given path"),
5056 PARSE_OPT_NONEG, apply_option_parse_include),
5057 OPT_CALLBACK('p', NULL, state, N_("num"),
5058 N_("remove <num> leading slashes from traditional diff paths"),
5059 apply_option_parse_p),
5060 OPT_BOOL(0, "no-add", &state->no_add,
5061 N_("ignore additions made by the patch")),
5062 OPT_BOOL(0, "stat", &state->diffstat,
5063 N_("instead of applying the patch, output diffstat for the input")),
5064 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
5065 OPT_NOOP_NOARG(0, "binary"),
5066 OPT_BOOL(0, "numstat", &state->numstat,
5067 N_("show number of added and deleted lines in decimal notation")),
5068 OPT_BOOL(0, "summary", &state->summary,
5069 N_("instead of applying the patch, output a summary for the input")),
5070 OPT_BOOL(0, "check", &state->check,
5071 N_("instead of applying the patch, see if the patch is applicable")),
5072 OPT_BOOL(0, "index", &state->check_index,
5073 N_("make sure the patch is applicable to the current index")),
5074 OPT_BOOL('N', "intent-to-add", &state->ita_only,
5075 N_("mark new files with `git add --intent-to-add`")),
5076 OPT_BOOL(0, "cached", &state->cached,
5077 N_("apply a patch without touching the working tree")),
5078 OPT_BOOL_F(0, "unsafe-paths", &state->unsafe_paths,
5079 N_("accept a patch that touches outside the working area"),
5080 PARSE_OPT_NOCOMPLETE),
5081 OPT_BOOL(0, "apply", force_apply,
5082 N_("also apply the patch (use with --stat/--summary/--check)")),
5083 OPT_BOOL('3', "3way", &state->threeway,
5084 N_( "attempt three-way merge, fall back on normal patch if that fails")),
5085 OPT_FILENAME(0, "build-fake-ancestor", &state->fake_ancestor,
5086 N_("build a temporary index based on embedded index information")),
5087 /* Think twice before adding "--nul" synonym to this */
5088 OPT_SET_INT('z', NULL, &state->line_termination,
5089 N_("paths are separated with NUL character"), '\0'),
5090 OPT_INTEGER('C', NULL, &state->p_context,
5091 N_("ensure at least <n> lines of context match")),
5092 OPT_CALLBACK(0, "whitespace", state, N_("action"),
5093 N_("detect new or modified lines that have whitespace errors"),
5094 apply_option_parse_whitespace),
5095 OPT_CALLBACK_F(0, "ignore-space-change", state, NULL,
5096 N_("ignore changes in whitespace when finding context"),
5097 PARSE_OPT_NOARG, apply_option_parse_space_change),
5098 OPT_CALLBACK_F(0, "ignore-whitespace", state, NULL,
5099 N_("ignore changes in whitespace when finding context"),
5100 PARSE_OPT_NOARG, apply_option_parse_space_change),
5101 OPT_BOOL('R', "reverse", &state->apply_in_reverse,
5102 N_("apply the patch in reverse")),
5103 OPT_BOOL(0, "unidiff-zero", &state->unidiff_zero,
5104 N_("don't expect at least one line of context")),
5105 OPT_BOOL(0, "reject", &state->apply_with_reject,
5106 N_("leave the rejected hunks in corresponding *.rej files")),
5107 OPT_BOOL(0, "allow-overlap", &state->allow_overlap,
5108 N_("allow overlapping hunks")),
5109 OPT__VERBOSITY(&state->apply_verbosity),
5110 OPT_BIT(0, "inaccurate-eof", options,
5111 N_("tolerate incorrectly detected missing new-line at the end of file"),
5112 APPLY_OPT_INACCURATE_EOF),
5113 OPT_BIT(0, "recount", options,
5114 N_("do not trust the line counts in the hunk headers"),
5115 APPLY_OPT_RECOUNT),
5116 OPT_CALLBACK(0, "directory", state, N_("root"),
5117 N_("prepend <root> to all filenames"),
5118 apply_option_parse_directory),
5119 OPT_BOOL(0, "allow-empty", &state->allow_empty,
5120 N_("don't return error for empty patches")),
5121 OPT_END()
5124 return parse_options(argc, argv, state->prefix, builtin_apply_options, apply_usage, 0);