Merge branch 'jk/output-prefix-cleanup'
[git/gitster.git] / apply.c
bloba3fc2d5330f91c02af853039281d48fc17cf8e57
1 /*
2 * apply.c
4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
8 */
10 #define USE_THE_REPOSITORY_VARIABLE
12 #include "git-compat-util.h"
13 #include "abspath.h"
14 #include "base85.h"
15 #include "config.h"
16 #include "object-store-ll.h"
17 #include "delta.h"
18 #include "diff.h"
19 #include "dir.h"
20 #include "environment.h"
21 #include "gettext.h"
22 #include "hex.h"
23 #include "xdiff-interface.h"
24 #include "merge-ll.h"
25 #include "lockfile.h"
26 #include "name-hash.h"
27 #include "object-name.h"
28 #include "object-file.h"
29 #include "parse-options.h"
30 #include "path.h"
31 #include "quote.h"
32 #include "read-cache.h"
33 #include "repository.h"
34 #include "rerere.h"
35 #include "apply.h"
36 #include "entry.h"
37 #include "setup.h"
38 #include "symlinks.h"
39 #include "wildmatch.h"
40 #include "ws.h"
42 struct gitdiff_data {
43 struct strbuf *root;
44 int linenr;
45 int p_value;
48 static void git_apply_config(void)
50 git_config_get_string("apply.whitespace", &apply_default_whitespace);
51 git_config_get_string("apply.ignorewhitespace", &apply_default_ignorewhitespace);
52 git_config(git_xmerge_config, NULL);
55 static int parse_whitespace_option(struct apply_state *state, const char *option)
57 if (!option) {
58 state->ws_error_action = warn_on_ws_error;
59 return 0;
61 if (!strcmp(option, "warn")) {
62 state->ws_error_action = warn_on_ws_error;
63 return 0;
65 if (!strcmp(option, "nowarn")) {
66 state->ws_error_action = nowarn_ws_error;
67 return 0;
69 if (!strcmp(option, "error")) {
70 state->ws_error_action = die_on_ws_error;
71 return 0;
73 if (!strcmp(option, "error-all")) {
74 state->ws_error_action = die_on_ws_error;
75 state->squelch_whitespace_errors = 0;
76 return 0;
78 if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
79 state->ws_error_action = correct_ws_error;
80 return 0;
83 * Please update $__git_whitespacelist in git-completion.bash,
84 * Documentation/git-apply.txt, and Documentation/git-am.txt
85 * when you add new options.
87 return error(_("unrecognized whitespace option '%s'"), option);
90 static int parse_ignorewhitespace_option(struct apply_state *state,
91 const char *option)
93 if (!option || !strcmp(option, "no") ||
94 !strcmp(option, "false") || !strcmp(option, "never") ||
95 !strcmp(option, "none")) {
96 state->ws_ignore_action = ignore_ws_none;
97 return 0;
99 if (!strcmp(option, "change")) {
100 state->ws_ignore_action = ignore_ws_change;
101 return 0;
103 return error(_("unrecognized whitespace ignore option '%s'"), option);
106 int init_apply_state(struct apply_state *state,
107 struct repository *repo,
108 const char *prefix)
110 memset(state, 0, sizeof(*state));
111 state->prefix = prefix;
112 state->repo = repo;
113 state->apply = 1;
114 state->line_termination = '\n';
115 state->p_value = 1;
116 state->p_context = UINT_MAX;
117 state->squelch_whitespace_errors = 5;
118 state->ws_error_action = warn_on_ws_error;
119 state->ws_ignore_action = ignore_ws_none;
120 state->linenr = 1;
121 string_list_init_nodup(&state->fn_table);
122 string_list_init_nodup(&state->limit_by_name);
123 strset_init(&state->removed_symlinks);
124 strset_init(&state->kept_symlinks);
125 strbuf_init(&state->root, 0);
127 git_apply_config();
128 if (apply_default_whitespace && parse_whitespace_option(state, apply_default_whitespace))
129 return -1;
130 if (apply_default_ignorewhitespace && parse_ignorewhitespace_option(state, apply_default_ignorewhitespace))
131 return -1;
132 return 0;
135 void clear_apply_state(struct apply_state *state)
137 string_list_clear(&state->limit_by_name, 0);
138 strset_clear(&state->removed_symlinks);
139 strset_clear(&state->kept_symlinks);
140 strbuf_release(&state->root);
141 FREE_AND_NULL(state->fake_ancestor);
143 /* &state->fn_table is cleared at the end of apply_patch() */
146 static void mute_routine(const char *msg UNUSED, va_list params UNUSED)
148 /* do nothing */
151 int check_apply_state(struct apply_state *state, int force_apply)
153 int is_not_gitdir = !startup_info->have_repository;
155 if (state->apply_with_reject && state->threeway)
156 return error(_("options '%s' and '%s' cannot be used together"), "--reject", "--3way");
157 if (state->threeway) {
158 if (is_not_gitdir)
159 return error(_("'%s' outside a repository"), "--3way");
160 state->check_index = 1;
162 if (state->apply_with_reject) {
163 state->apply = 1;
164 if (state->apply_verbosity == verbosity_normal)
165 state->apply_verbosity = verbosity_verbose;
167 if (!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor))
168 state->apply = 0;
169 if (state->check_index && is_not_gitdir)
170 return error(_("'%s' outside a repository"), "--index");
171 if (state->cached) {
172 if (is_not_gitdir)
173 return error(_("'%s' outside a repository"), "--cached");
174 state->check_index = 1;
176 if (state->ita_only && (state->check_index || is_not_gitdir))
177 state->ita_only = 0;
178 if (state->check_index)
179 state->unsafe_paths = 0;
181 if (state->apply_verbosity <= verbosity_silent) {
182 state->saved_error_routine = get_error_routine();
183 state->saved_warn_routine = get_warn_routine();
184 set_error_routine(mute_routine);
185 set_warn_routine(mute_routine);
188 return 0;
191 static void set_default_whitespace_mode(struct apply_state *state)
193 if (!state->whitespace_option && !apply_default_whitespace)
194 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error);
198 * This represents one "hunk" from a patch, starting with
199 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
200 * patch text is pointed at by patch, and its byte length
201 * is stored in size. leading and trailing are the number
202 * of context lines.
204 struct fragment {
205 unsigned long leading, trailing;
206 unsigned long oldpos, oldlines;
207 unsigned long newpos, newlines;
209 * 'patch' is usually borrowed from buf in apply_patch(),
210 * but some codepaths store an allocated buffer.
212 const char *patch;
213 unsigned free_patch:1,
214 rejected:1;
215 int size;
216 int linenr;
217 struct fragment *next;
221 * When dealing with a binary patch, we reuse "leading" field
222 * to store the type of the binary hunk, either deflated "delta"
223 * or deflated "literal".
225 #define binary_patch_method leading
226 #define BINARY_DELTA_DEFLATED 1
227 #define BINARY_LITERAL_DEFLATED 2
229 static void free_fragment_list(struct fragment *list)
231 while (list) {
232 struct fragment *next = list->next;
233 if (list->free_patch)
234 free((char *)list->patch);
235 free(list);
236 list = next;
240 void release_patch(struct patch *patch)
242 free_fragment_list(patch->fragments);
243 free(patch->def_name);
244 free(patch->old_name);
245 free(patch->new_name);
246 free(patch->result);
249 static void free_patch(struct patch *patch)
251 release_patch(patch);
252 free(patch);
255 static void free_patch_list(struct patch *list)
257 while (list) {
258 struct patch *next = list->next;
259 free_patch(list);
260 list = next;
265 * A line in a file, len-bytes long (includes the terminating LF,
266 * except for an incomplete line at the end if the file ends with
267 * one), and its contents hashes to 'hash'.
269 struct line {
270 size_t len;
271 unsigned hash : 24;
272 unsigned flag : 8;
273 #define LINE_COMMON 1
274 #define LINE_PATCHED 2
278 * This represents a "file", which is an array of "lines".
280 struct image {
281 struct strbuf buf;
282 struct line *line;
283 size_t line_nr, line_alloc;
285 #define IMAGE_INIT { \
286 .buf = STRBUF_INIT, \
289 static void image_init(struct image *image)
291 struct image empty = IMAGE_INIT;
292 memcpy(image, &empty, sizeof(*image));
295 static void image_clear(struct image *image)
297 strbuf_release(&image->buf);
298 free(image->line);
299 image_init(image);
302 static uint32_t hash_line(const char *cp, size_t len)
304 size_t i;
305 uint32_t h;
306 for (i = 0, h = 0; i < len; i++) {
307 if (!isspace(cp[i])) {
308 h = h * 3 + (cp[i] & 0xff);
311 return h;
314 static void image_add_line(struct image *img, const char *bol, size_t len, unsigned flag)
316 ALLOC_GROW(img->line, img->line_nr + 1, img->line_alloc);
317 img->line[img->line_nr].len = len;
318 img->line[img->line_nr].hash = hash_line(bol, len);
319 img->line[img->line_nr].flag = flag;
320 img->line_nr++;
324 * "buf" has the file contents to be patched (read from various sources).
325 * attach it to "image" and add line-based index to it.
326 * "image" now owns the "buf".
328 static void image_prepare(struct image *image, char *buf, size_t len,
329 int prepare_linetable)
331 const char *cp, *ep;
333 image_clear(image);
334 strbuf_attach(&image->buf, buf, len, len + 1);
336 if (!prepare_linetable)
337 return;
339 ep = image->buf.buf + image->buf.len;
340 cp = image->buf.buf;
341 while (cp < ep) {
342 const char *next;
343 for (next = cp; next < ep && *next != '\n'; next++)
345 if (next < ep)
346 next++;
347 image_add_line(image, cp, next - cp, 0);
348 cp = next;
352 static void image_remove_first_line(struct image *img)
354 strbuf_remove(&img->buf, 0, img->line[0].len);
355 img->line_nr--;
356 if (img->line_nr)
357 MOVE_ARRAY(img->line, img->line + 1, img->line_nr);
360 static void image_remove_last_line(struct image *img)
362 size_t last_line_len = img->line[img->line_nr - 1].len;
363 strbuf_setlen(&img->buf, img->buf.len - last_line_len);
364 img->line_nr--;
367 /* fmt must contain _one_ %s and no other substitution */
368 static void say_patch_name(FILE *output, const char *fmt, struct patch *patch)
370 struct strbuf sb = STRBUF_INIT;
372 if (patch->old_name && patch->new_name &&
373 strcmp(patch->old_name, patch->new_name)) {
374 quote_c_style(patch->old_name, &sb, NULL, 0);
375 strbuf_addstr(&sb, " => ");
376 quote_c_style(patch->new_name, &sb, NULL, 0);
377 } else {
378 const char *n = patch->new_name;
379 if (!n)
380 n = patch->old_name;
381 quote_c_style(n, &sb, NULL, 0);
383 fprintf(output, fmt, sb.buf);
384 fputc('\n', output);
385 strbuf_release(&sb);
388 #define SLOP (16)
391 * apply.c isn't equipped to handle arbitrarily large patches, because
392 * it intermingles `unsigned long` with `int` for the type used to store
393 * buffer lengths.
395 * Only process patches that are just shy of 1 GiB large in order to
396 * avoid any truncation or overflow issues.
398 #define MAX_APPLY_SIZE (1024UL * 1024 * 1023)
400 static int read_patch_file(struct strbuf *sb, int fd)
402 if (strbuf_read(sb, fd, 0) < 0)
403 return error_errno(_("failed to read patch"));
404 else if (sb->len >= MAX_APPLY_SIZE)
405 return error(_("patch too large"));
407 * Make sure that we have some slop in the buffer
408 * so that we can do speculative "memcmp" etc, and
409 * see to it that it is NUL-filled.
411 strbuf_grow(sb, SLOP);
412 memset(sb->buf + sb->len, 0, SLOP);
413 return 0;
416 static unsigned long linelen(const char *buffer, unsigned long size)
418 unsigned long len = 0;
419 while (size--) {
420 len++;
421 if (*buffer++ == '\n')
422 break;
424 return len;
427 static int is_dev_null(const char *str)
429 return skip_prefix(str, "/dev/null", &str) && isspace(*str);
432 #define TERM_SPACE 1
433 #define TERM_TAB 2
435 static int name_terminate(int c, int terminate)
437 if (c == ' ' && !(terminate & TERM_SPACE))
438 return 0;
439 if (c == '\t' && !(terminate & TERM_TAB))
440 return 0;
442 return 1;
445 /* remove double slashes to make --index work with such filenames */
446 static char *squash_slash(char *name)
448 int i = 0, j = 0;
450 if (!name)
451 return NULL;
453 while (name[i]) {
454 if ((name[j++] = name[i++]) == '/')
455 while (name[i] == '/')
456 i++;
458 name[j] = '\0';
459 return name;
462 static char *find_name_gnu(struct strbuf *root,
463 const char *line,
464 int p_value)
466 struct strbuf name = STRBUF_INIT;
467 char *cp;
470 * Proposed "new-style" GNU patch/diff format; see
471 * https://lore.kernel.org/git/7vll0wvb2a.fsf@assigned-by-dhcp.cox.net/
473 if (unquote_c_style(&name, line, NULL)) {
474 strbuf_release(&name);
475 return NULL;
478 for (cp = name.buf; p_value; p_value--) {
479 cp = strchr(cp, '/');
480 if (!cp) {
481 strbuf_release(&name);
482 return NULL;
484 cp++;
487 strbuf_remove(&name, 0, cp - name.buf);
488 if (root->len)
489 strbuf_insert(&name, 0, root->buf, root->len);
490 return squash_slash(strbuf_detach(&name, NULL));
493 static size_t sane_tz_len(const char *line, size_t len)
495 const char *tz, *p;
497 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
498 return 0;
499 tz = line + len - strlen(" +0500");
501 if (tz[1] != '+' && tz[1] != '-')
502 return 0;
504 for (p = tz + 2; p != line + len; p++)
505 if (!isdigit(*p))
506 return 0;
508 return line + len - tz;
511 static size_t tz_with_colon_len(const char *line, size_t len)
513 const char *tz, *p;
515 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
516 return 0;
517 tz = line + len - strlen(" +08:00");
519 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
520 return 0;
521 p = tz + 2;
522 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
523 !isdigit(*p++) || !isdigit(*p++))
524 return 0;
526 return line + len - tz;
529 static size_t date_len(const char *line, size_t len)
531 const char *date, *p;
533 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
534 return 0;
535 p = date = line + len - strlen("72-02-05");
537 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
538 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
539 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */
540 return 0;
542 if (date - line >= strlen("19") &&
543 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */
544 date -= strlen("19");
546 return line + len - date;
549 static size_t short_time_len(const char *line, size_t len)
551 const char *time, *p;
553 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
554 return 0;
555 p = time = line + len - strlen(" 07:01:32");
557 /* Permit 1-digit hours? */
558 if (*p++ != ' ' ||
559 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
560 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
561 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */
562 return 0;
564 return line + len - time;
567 static size_t fractional_time_len(const char *line, size_t len)
569 const char *p;
570 size_t n;
572 /* Expected format: 19:41:17.620000023 */
573 if (!len || !isdigit(line[len - 1]))
574 return 0;
575 p = line + len - 1;
577 /* Fractional seconds. */
578 while (p > line && isdigit(*p))
579 p--;
580 if (*p != '.')
581 return 0;
583 /* Hours, minutes, and whole seconds. */
584 n = short_time_len(line, p - line);
585 if (!n)
586 return 0;
588 return line + len - p + n;
591 static size_t trailing_spaces_len(const char *line, size_t len)
593 const char *p;
595 /* Expected format: ' ' x (1 or more) */
596 if (!len || line[len - 1] != ' ')
597 return 0;
599 p = line + len;
600 while (p != line) {
601 p--;
602 if (*p != ' ')
603 return line + len - (p + 1);
606 /* All spaces! */
607 return len;
610 static size_t diff_timestamp_len(const char *line, size_t len)
612 const char *end = line + len;
613 size_t n;
616 * Posix: 2010-07-05 19:41:17
617 * GNU: 2010-07-05 19:41:17.620000023 -0500
620 if (!isdigit(end[-1]))
621 return 0;
623 n = sane_tz_len(line, end - line);
624 if (!n)
625 n = tz_with_colon_len(line, end - line);
626 end -= n;
628 n = short_time_len(line, end - line);
629 if (!n)
630 n = fractional_time_len(line, end - line);
631 end -= n;
633 n = date_len(line, end - line);
634 if (!n) /* No date. Too bad. */
635 return 0;
636 end -= n;
638 if (end == line) /* No space before date. */
639 return 0;
640 if (end[-1] == '\t') { /* Success! */
641 end--;
642 return line + len - end;
644 if (end[-1] != ' ') /* No space before date. */
645 return 0;
647 /* Whitespace damage. */
648 end -= trailing_spaces_len(line, end - line);
649 return line + len - end;
652 static char *find_name_common(struct strbuf *root,
653 const char *line,
654 const char *def,
655 int p_value,
656 const char *end,
657 int terminate)
659 int len;
660 const char *start = NULL;
662 if (p_value == 0)
663 start = line;
664 while (line != end) {
665 char c = *line;
667 if (!end && isspace(c)) {
668 if (c == '\n')
669 break;
670 if (name_terminate(c, terminate))
671 break;
673 line++;
674 if (c == '/' && !--p_value)
675 start = line;
677 if (!start)
678 return squash_slash(xstrdup_or_null(def));
679 len = line - start;
680 if (!len)
681 return squash_slash(xstrdup_or_null(def));
684 * Generally we prefer the shorter name, especially
685 * if the other one is just a variation of that with
686 * something else tacked on to the end (ie "file.orig"
687 * or "file~").
689 if (def) {
690 int deflen = strlen(def);
691 if (deflen < len && !strncmp(start, def, deflen))
692 return squash_slash(xstrdup(def));
695 if (root->len) {
696 char *ret = xstrfmt("%s%.*s", root->buf, len, start);
697 return squash_slash(ret);
700 return squash_slash(xmemdupz(start, len));
703 static char *find_name(struct strbuf *root,
704 const char *line,
705 char *def,
706 int p_value,
707 int terminate)
709 if (*line == '"') {
710 char *name = find_name_gnu(root, line, p_value);
711 if (name)
712 return name;
715 return find_name_common(root, line, def, p_value, NULL, terminate);
718 static char *find_name_traditional(struct strbuf *root,
719 const char *line,
720 char *def,
721 int p_value)
723 size_t len;
724 size_t date_len;
726 if (*line == '"') {
727 char *name = find_name_gnu(root, line, p_value);
728 if (name)
729 return name;
732 len = strchrnul(line, '\n') - line;
733 date_len = diff_timestamp_len(line, len);
734 if (!date_len)
735 return find_name_common(root, line, def, p_value, NULL, TERM_TAB);
736 len -= date_len;
738 return find_name_common(root, line, def, p_value, line + len, 0);
742 * Given the string after "--- " or "+++ ", guess the appropriate
743 * p_value for the given patch.
745 static int guess_p_value(struct apply_state *state, const char *nameline)
747 char *name, *cp;
748 int val = -1;
750 if (is_dev_null(nameline))
751 return -1;
752 name = find_name_traditional(&state->root, nameline, NULL, 0);
753 if (!name)
754 return -1;
755 cp = strchr(name, '/');
756 if (!cp)
757 val = 0;
758 else if (state->prefix) {
760 * Does it begin with "a/$our-prefix" and such? Then this is
761 * very likely to apply to our directory.
763 if (starts_with(name, state->prefix))
764 val = count_slashes(state->prefix);
765 else {
766 cp++;
767 if (starts_with(cp, state->prefix))
768 val = count_slashes(state->prefix) + 1;
771 free(name);
772 return val;
776 * Does the ---/+++ line have the POSIX timestamp after the last HT?
777 * GNU diff puts epoch there to signal a creation/deletion event. Is
778 * this such a timestamp?
780 static int has_epoch_timestamp(const char *nameline)
783 * We are only interested in epoch timestamp; any non-zero
784 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
785 * For the same reason, the date must be either 1969-12-31 or
786 * 1970-01-01, and the seconds part must be "00".
788 const char stamp_regexp[] =
789 "^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?"
791 "([-+][0-2][0-9]:?[0-5][0-9])\n";
792 const char *timestamp = NULL, *cp, *colon;
793 static regex_t *stamp;
794 regmatch_t m[10];
795 int zoneoffset, epoch_hour, hour, minute;
796 int status;
798 for (cp = nameline; *cp != '\n'; cp++) {
799 if (*cp == '\t')
800 timestamp = cp + 1;
802 if (!timestamp)
803 return 0;
806 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
807 * (west of GMT) or 1970-01-01 (east of GMT)
809 if (skip_prefix(timestamp, "1969-12-31 ", &timestamp))
810 epoch_hour = 24;
811 else if (skip_prefix(timestamp, "1970-01-01 ", &timestamp))
812 epoch_hour = 0;
813 else
814 return 0;
816 if (!stamp) {
817 stamp = xmalloc(sizeof(*stamp));
818 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
819 warning(_("Cannot prepare timestamp regexp %s"),
820 stamp_regexp);
821 return 0;
825 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
826 if (status) {
827 if (status != REG_NOMATCH)
828 warning(_("regexec returned %d for input: %s"),
829 status, timestamp);
830 return 0;
833 hour = strtol(timestamp, NULL, 10);
834 minute = strtol(timestamp + m[1].rm_so, NULL, 10);
836 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
837 if (*colon == ':')
838 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
839 else
840 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
841 if (timestamp[m[3].rm_so] == '-')
842 zoneoffset = -zoneoffset;
844 return hour * 60 + minute - zoneoffset == epoch_hour * 60;
848 * Get the name etc info from the ---/+++ lines of a traditional patch header
850 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
851 * files, we can happily check the index for a match, but for creating a
852 * new file we should try to match whatever "patch" does. I have no idea.
854 static int parse_traditional_patch(struct apply_state *state,
855 const char *first,
856 const char *second,
857 struct patch *patch)
859 char *name;
861 first += 4; /* skip "--- " */
862 second += 4; /* skip "+++ " */
863 if (!state->p_value_known) {
864 int p, q;
865 p = guess_p_value(state, first);
866 q = guess_p_value(state, second);
867 if (p < 0) p = q;
868 if (0 <= p && p == q) {
869 state->p_value = p;
870 state->p_value_known = 1;
873 if (is_dev_null(first)) {
874 patch->is_new = 1;
875 patch->is_delete = 0;
876 name = find_name_traditional(&state->root, second, NULL, state->p_value);
877 patch->new_name = name;
878 } else if (is_dev_null(second)) {
879 patch->is_new = 0;
880 patch->is_delete = 1;
881 name = find_name_traditional(&state->root, first, NULL, state->p_value);
882 patch->old_name = name;
883 } else {
884 char *first_name;
885 first_name = find_name_traditional(&state->root, first, NULL, state->p_value);
886 name = find_name_traditional(&state->root, second, first_name, state->p_value);
887 free(first_name);
888 if (has_epoch_timestamp(first)) {
889 patch->is_new = 1;
890 patch->is_delete = 0;
891 patch->new_name = name;
892 } else if (has_epoch_timestamp(second)) {
893 patch->is_new = 0;
894 patch->is_delete = 1;
895 patch->old_name = name;
896 } else {
897 patch->old_name = name;
898 patch->new_name = xstrdup_or_null(name);
901 if (!name)
902 return error(_("unable to find filename in patch at line %d"), state->linenr);
904 return 0;
907 static int gitdiff_hdrend(struct gitdiff_data *state UNUSED,
908 const char *line UNUSED,
909 struct patch *patch UNUSED)
911 return 1;
915 * We're anal about diff header consistency, to make
916 * sure that we don't end up having strange ambiguous
917 * patches floating around.
919 * As a result, gitdiff_{old|new}name() will check
920 * their names against any previous information, just
921 * to make sure..
923 #define DIFF_OLD_NAME 0
924 #define DIFF_NEW_NAME 1
926 static int gitdiff_verify_name(struct gitdiff_data *state,
927 const char *line,
928 int isnull,
929 char **name,
930 int side)
932 if (!*name && !isnull) {
933 *name = find_name(state->root, line, NULL, state->p_value, TERM_TAB);
934 return 0;
937 if (*name) {
938 char *another;
939 if (isnull)
940 return error(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
941 *name, state->linenr);
942 another = find_name(state->root, line, NULL, state->p_value, TERM_TAB);
943 if (!another || strcmp(another, *name)) {
944 free(another);
945 return error((side == DIFF_NEW_NAME) ?
946 _("git apply: bad git-diff - inconsistent new filename on line %d") :
947 _("git apply: bad git-diff - inconsistent old filename on line %d"), state->linenr);
949 free(another);
950 } else {
951 if (!is_dev_null(line))
952 return error(_("git apply: bad git-diff - expected /dev/null on line %d"), state->linenr);
955 return 0;
958 static int gitdiff_oldname(struct gitdiff_data *state,
959 const char *line,
960 struct patch *patch)
962 return gitdiff_verify_name(state, line,
963 patch->is_new, &patch->old_name,
964 DIFF_OLD_NAME);
967 static int gitdiff_newname(struct gitdiff_data *state,
968 const char *line,
969 struct patch *patch)
971 return gitdiff_verify_name(state, line,
972 patch->is_delete, &patch->new_name,
973 DIFF_NEW_NAME);
976 static int parse_mode_line(const char *line, int linenr, unsigned int *mode)
978 char *end;
979 *mode = strtoul(line, &end, 8);
980 if (end == line || !isspace(*end))
981 return error(_("invalid mode on line %d: %s"), linenr, line);
982 *mode = canon_mode(*mode);
983 return 0;
986 static int gitdiff_oldmode(struct gitdiff_data *state,
987 const char *line,
988 struct patch *patch)
990 return parse_mode_line(line, state->linenr, &patch->old_mode);
993 static int gitdiff_newmode(struct gitdiff_data *state,
994 const char *line,
995 struct patch *patch)
997 return parse_mode_line(line, state->linenr, &patch->new_mode);
1000 static int gitdiff_delete(struct gitdiff_data *state,
1001 const char *line,
1002 struct patch *patch)
1004 patch->is_delete = 1;
1005 free(patch->old_name);
1006 patch->old_name = xstrdup_or_null(patch->def_name);
1007 return gitdiff_oldmode(state, line, patch);
1010 static int gitdiff_newfile(struct gitdiff_data *state,
1011 const char *line,
1012 struct patch *patch)
1014 patch->is_new = 1;
1015 free(patch->new_name);
1016 patch->new_name = xstrdup_or_null(patch->def_name);
1017 return gitdiff_newmode(state, line, patch);
1020 static int gitdiff_copysrc(struct gitdiff_data *state,
1021 const char *line,
1022 struct patch *patch)
1024 patch->is_copy = 1;
1025 free(patch->old_name);
1026 patch->old_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1027 return 0;
1030 static int gitdiff_copydst(struct gitdiff_data *state,
1031 const char *line,
1032 struct patch *patch)
1034 patch->is_copy = 1;
1035 free(patch->new_name);
1036 patch->new_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1037 return 0;
1040 static int gitdiff_renamesrc(struct gitdiff_data *state,
1041 const char *line,
1042 struct patch *patch)
1044 patch->is_rename = 1;
1045 free(patch->old_name);
1046 patch->old_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1047 return 0;
1050 static int gitdiff_renamedst(struct gitdiff_data *state,
1051 const char *line,
1052 struct patch *patch)
1054 patch->is_rename = 1;
1055 free(patch->new_name);
1056 patch->new_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1057 return 0;
1060 static int gitdiff_similarity(struct gitdiff_data *state UNUSED,
1061 const char *line,
1062 struct patch *patch)
1064 unsigned long val = strtoul(line, NULL, 10);
1065 if (val <= 100)
1066 patch->score = val;
1067 return 0;
1070 static int gitdiff_dissimilarity(struct gitdiff_data *state UNUSED,
1071 const char *line,
1072 struct patch *patch)
1074 unsigned long val = strtoul(line, NULL, 10);
1075 if (val <= 100)
1076 patch->score = val;
1077 return 0;
1080 static int gitdiff_index(struct gitdiff_data *state,
1081 const char *line,
1082 struct patch *patch)
1085 * index line is N hexadecimal, "..", N hexadecimal,
1086 * and optional space with octal mode.
1088 const char *ptr, *eol;
1089 int len;
1090 const unsigned hexsz = the_hash_algo->hexsz;
1092 ptr = strchr(line, '.');
1093 if (!ptr || ptr[1] != '.' || hexsz < ptr - line)
1094 return 0;
1095 len = ptr - line;
1096 memcpy(patch->old_oid_prefix, line, len);
1097 patch->old_oid_prefix[len] = 0;
1099 line = ptr + 2;
1100 ptr = strchr(line, ' ');
1101 eol = strchrnul(line, '\n');
1103 if (!ptr || eol < ptr)
1104 ptr = eol;
1105 len = ptr - line;
1107 if (hexsz < len)
1108 return 0;
1109 memcpy(patch->new_oid_prefix, line, len);
1110 patch->new_oid_prefix[len] = 0;
1111 if (*ptr == ' ')
1112 return gitdiff_oldmode(state, ptr + 1, patch);
1113 return 0;
1117 * This is normal for a diff that doesn't change anything: we'll fall through
1118 * into the next diff. Tell the parser to break out.
1120 static int gitdiff_unrecognized(struct gitdiff_data *state UNUSED,
1121 const char *line UNUSED,
1122 struct patch *patch UNUSED)
1124 return 1;
1128 * Skip p_value leading components from "line"; as we do not accept
1129 * absolute paths, return NULL in that case.
1131 static const char *skip_tree_prefix(int p_value,
1132 const char *line,
1133 int llen)
1135 int nslash;
1136 int i;
1138 if (!p_value)
1139 return (llen && line[0] == '/') ? NULL : line;
1141 nslash = p_value;
1142 for (i = 0; i < llen; i++) {
1143 int ch = line[i];
1144 if (ch == '/' && --nslash <= 0)
1145 return (i == 0) ? NULL : &line[i + 1];
1147 return NULL;
1151 * This is to extract the same name that appears on "diff --git"
1152 * line. We do not find and return anything if it is a rename
1153 * patch, and it is OK because we will find the name elsewhere.
1154 * We need to reliably find name only when it is mode-change only,
1155 * creation or deletion of an empty file. In any of these cases,
1156 * both sides are the same name under a/ and b/ respectively.
1158 static char *git_header_name(int p_value,
1159 const char *line,
1160 int llen)
1162 const char *name;
1163 const char *second = NULL;
1164 size_t len, line_len;
1166 line += strlen("diff --git ");
1167 llen -= strlen("diff --git ");
1169 if (*line == '"') {
1170 const char *cp;
1171 struct strbuf first = STRBUF_INIT;
1172 struct strbuf sp = STRBUF_INIT;
1174 if (unquote_c_style(&first, line, &second))
1175 goto free_and_fail1;
1177 /* strip the a/b prefix including trailing slash */
1178 cp = skip_tree_prefix(p_value, first.buf, first.len);
1179 if (!cp)
1180 goto free_and_fail1;
1181 strbuf_remove(&first, 0, cp - first.buf);
1184 * second points at one past closing dq of name.
1185 * find the second name.
1187 while ((second < line + llen) && isspace(*second))
1188 second++;
1190 if (line + llen <= second)
1191 goto free_and_fail1;
1192 if (*second == '"') {
1193 if (unquote_c_style(&sp, second, NULL))
1194 goto free_and_fail1;
1195 cp = skip_tree_prefix(p_value, sp.buf, sp.len);
1196 if (!cp)
1197 goto free_and_fail1;
1198 /* They must match, otherwise ignore */
1199 if (strcmp(cp, first.buf))
1200 goto free_and_fail1;
1201 strbuf_release(&sp);
1202 return strbuf_detach(&first, NULL);
1205 /* unquoted second */
1206 cp = skip_tree_prefix(p_value, second, line + llen - second);
1207 if (!cp)
1208 goto free_and_fail1;
1209 if (line + llen - cp != first.len ||
1210 memcmp(first.buf, cp, first.len))
1211 goto free_and_fail1;
1212 return strbuf_detach(&first, NULL);
1214 free_and_fail1:
1215 strbuf_release(&first);
1216 strbuf_release(&sp);
1217 return NULL;
1220 /* unquoted first name */
1221 name = skip_tree_prefix(p_value, line, llen);
1222 if (!name)
1223 return NULL;
1226 * since the first name is unquoted, a dq if exists must be
1227 * the beginning of the second name.
1229 for (second = name; second < line + llen; second++) {
1230 if (*second == '"') {
1231 struct strbuf sp = STRBUF_INIT;
1232 const char *np;
1234 if (unquote_c_style(&sp, second, NULL))
1235 goto free_and_fail2;
1237 np = skip_tree_prefix(p_value, sp.buf, sp.len);
1238 if (!np)
1239 goto free_and_fail2;
1241 len = sp.buf + sp.len - np;
1242 if (len < second - name &&
1243 !strncmp(np, name, len) &&
1244 isspace(name[len])) {
1245 /* Good */
1246 strbuf_remove(&sp, 0, np - sp.buf);
1247 return strbuf_detach(&sp, NULL);
1250 free_and_fail2:
1251 strbuf_release(&sp);
1252 return NULL;
1257 * Accept a name only if it shows up twice, exactly the same
1258 * form.
1260 second = strchr(name, '\n');
1261 if (!second)
1262 return NULL;
1263 line_len = second - name;
1264 for (len = 0 ; ; len++) {
1265 switch (name[len]) {
1266 default:
1267 continue;
1268 case '\n':
1269 return NULL;
1270 case '\t': case ' ':
1272 * Is this the separator between the preimage
1273 * and the postimage pathname? Again, we are
1274 * only interested in the case where there is
1275 * no rename, as this is only to set def_name
1276 * and a rename patch has the names elsewhere
1277 * in an unambiguous form.
1279 if (!name[len + 1])
1280 return NULL; /* no postimage name */
1281 second = skip_tree_prefix(p_value, name + len + 1,
1282 line_len - (len + 1));
1284 * If we are at the SP at the end of a directory,
1285 * skip_tree_prefix() may return NULL as that makes
1286 * it appears as if we have an absolute path.
1287 * Keep going to find another SP.
1289 if (!second)
1290 continue;
1293 * Does len bytes starting at "name" and "second"
1294 * (that are separated by one HT or SP we just
1295 * found) exactly match?
1297 if (second[len] == '\n' && !strncmp(name, second, len))
1298 return xmemdupz(name, len);
1303 static int check_header_line(int linenr, struct patch *patch)
1305 int extensions = (patch->is_delete == 1) + (patch->is_new == 1) +
1306 (patch->is_rename == 1) + (patch->is_copy == 1);
1307 if (extensions > 1)
1308 return error(_("inconsistent header lines %d and %d"),
1309 patch->extension_linenr, linenr);
1310 if (extensions && !patch->extension_linenr)
1311 patch->extension_linenr = linenr;
1312 return 0;
1315 int parse_git_diff_header(struct strbuf *root,
1316 int *linenr,
1317 int p_value,
1318 const char *line,
1319 int len,
1320 unsigned int size,
1321 struct patch *patch)
1323 unsigned long offset;
1324 struct gitdiff_data parse_hdr_state;
1326 /* A git diff has explicit new/delete information, so we don't guess */
1327 patch->is_new = 0;
1328 patch->is_delete = 0;
1331 * Some things may not have the old name in the
1332 * rest of the headers anywhere (pure mode changes,
1333 * or removing or adding empty files), so we get
1334 * the default name from the header.
1336 patch->def_name = git_header_name(p_value, line, len);
1337 if (patch->def_name && root->len) {
1338 char *s = xstrfmt("%s%s", root->buf, patch->def_name);
1339 free(patch->def_name);
1340 patch->def_name = s;
1343 line += len;
1344 size -= len;
1345 (*linenr)++;
1346 parse_hdr_state.root = root;
1347 parse_hdr_state.linenr = *linenr;
1348 parse_hdr_state.p_value = p_value;
1350 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, (*linenr)++) {
1351 static const struct opentry {
1352 const char *str;
1353 int (*fn)(struct gitdiff_data *, const char *, struct patch *);
1354 } optable[] = {
1355 { "@@ -", gitdiff_hdrend },
1356 { "--- ", gitdiff_oldname },
1357 { "+++ ", gitdiff_newname },
1358 { "old mode ", gitdiff_oldmode },
1359 { "new mode ", gitdiff_newmode },
1360 { "deleted file mode ", gitdiff_delete },
1361 { "new file mode ", gitdiff_newfile },
1362 { "copy from ", gitdiff_copysrc },
1363 { "copy to ", gitdiff_copydst },
1364 { "rename old ", gitdiff_renamesrc },
1365 { "rename new ", gitdiff_renamedst },
1366 { "rename from ", gitdiff_renamesrc },
1367 { "rename to ", gitdiff_renamedst },
1368 { "similarity index ", gitdiff_similarity },
1369 { "dissimilarity index ", gitdiff_dissimilarity },
1370 { "index ", gitdiff_index },
1371 { "", gitdiff_unrecognized },
1373 int i;
1375 len = linelen(line, size);
1376 if (!len || line[len-1] != '\n')
1377 break;
1378 for (i = 0; i < ARRAY_SIZE(optable); i++) {
1379 const struct opentry *p = optable + i;
1380 int oplen = strlen(p->str);
1381 int res;
1382 if (len < oplen || memcmp(p->str, line, oplen))
1383 continue;
1384 res = p->fn(&parse_hdr_state, line + oplen, patch);
1385 if (res < 0)
1386 return -1;
1387 if (check_header_line(*linenr, patch))
1388 return -1;
1389 if (res > 0)
1390 goto done;
1391 break;
1395 done:
1396 if (!patch->old_name && !patch->new_name) {
1397 if (!patch->def_name) {
1398 error(Q_("git diff header lacks filename information when removing "
1399 "%d leading pathname component (line %d)",
1400 "git diff header lacks filename information when removing "
1401 "%d leading pathname components (line %d)",
1402 parse_hdr_state.p_value),
1403 parse_hdr_state.p_value, *linenr);
1404 return -128;
1406 patch->old_name = xstrdup(patch->def_name);
1407 patch->new_name = xstrdup(patch->def_name);
1409 if ((!patch->new_name && !patch->is_delete) ||
1410 (!patch->old_name && !patch->is_new)) {
1411 error(_("git diff header lacks filename information "
1412 "(line %d)"), *linenr);
1413 return -128;
1415 patch->is_toplevel_relative = 1;
1416 return offset;
1419 static int parse_num(const char *line, unsigned long *p)
1421 char *ptr;
1423 if (!isdigit(*line))
1424 return 0;
1425 *p = strtoul(line, &ptr, 10);
1426 return ptr - line;
1429 static int parse_range(const char *line, int len, int offset, const char *expect,
1430 unsigned long *p1, unsigned long *p2)
1432 int digits, ex;
1434 if (offset < 0 || offset >= len)
1435 return -1;
1436 line += offset;
1437 len -= offset;
1439 digits = parse_num(line, p1);
1440 if (!digits)
1441 return -1;
1443 offset += digits;
1444 line += digits;
1445 len -= digits;
1447 *p2 = 1;
1448 if (*line == ',') {
1449 digits = parse_num(line+1, p2);
1450 if (!digits)
1451 return -1;
1453 offset += digits+1;
1454 line += digits+1;
1455 len -= digits+1;
1458 ex = strlen(expect);
1459 if (ex > len)
1460 return -1;
1461 if (memcmp(line, expect, ex))
1462 return -1;
1464 return offset + ex;
1467 static void recount_diff(const char *line, int size, struct fragment *fragment)
1469 int oldlines = 0, newlines = 0, ret = 0;
1471 if (size < 1) {
1472 warning("recount: ignore empty hunk");
1473 return;
1476 for (;;) {
1477 int len = linelen(line, size);
1478 size -= len;
1479 line += len;
1481 if (size < 1)
1482 break;
1484 switch (*line) {
1485 case ' ': case '\n':
1486 newlines++;
1487 /* fall through */
1488 case '-':
1489 oldlines++;
1490 continue;
1491 case '+':
1492 newlines++;
1493 continue;
1494 case '\\':
1495 continue;
1496 case '@':
1497 ret = size < 3 || !starts_with(line, "@@ ");
1498 break;
1499 case 'd':
1500 ret = size < 5 || !starts_with(line, "diff ");
1501 break;
1502 default:
1503 ret = -1;
1504 break;
1506 if (ret) {
1507 warning(_("recount: unexpected line: %.*s"),
1508 (int)linelen(line, size), line);
1509 return;
1511 break;
1513 fragment->oldlines = oldlines;
1514 fragment->newlines = newlines;
1518 * Parse a unified diff fragment header of the
1519 * form "@@ -a,b +c,d @@"
1521 static int parse_fragment_header(const char *line, int len, struct fragment *fragment)
1523 int offset;
1525 if (!len || line[len-1] != '\n')
1526 return -1;
1528 /* Figure out the number of lines in a fragment */
1529 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1530 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1532 return offset;
1536 * Find file diff header
1538 * Returns:
1539 * -1 if no header was found
1540 * -128 in case of error
1541 * the size of the header in bytes (called "offset") otherwise
1543 static int find_header(struct apply_state *state,
1544 const char *line,
1545 unsigned long size,
1546 int *hdrsize,
1547 struct patch *patch)
1549 unsigned long offset, len;
1551 patch->is_toplevel_relative = 0;
1552 patch->is_rename = patch->is_copy = 0;
1553 patch->is_new = patch->is_delete = -1;
1554 patch->old_mode = patch->new_mode = 0;
1555 patch->old_name = patch->new_name = NULL;
1556 for (offset = 0; size > 0; offset += len, size -= len, line += len, state->linenr++) {
1557 unsigned long nextlen;
1559 len = linelen(line, size);
1560 if (!len)
1561 break;
1563 /* Testing this early allows us to take a few shortcuts.. */
1564 if (len < 6)
1565 continue;
1568 * Make sure we don't find any unconnected patch fragments.
1569 * That's a sign that we didn't find a header, and that a
1570 * patch has become corrupted/broken up.
1572 if (!memcmp("@@ -", line, 4)) {
1573 struct fragment dummy;
1574 if (parse_fragment_header(line, len, &dummy) < 0)
1575 continue;
1576 error(_("patch fragment without header at line %d: %.*s"),
1577 state->linenr, (int)len-1, line);
1578 return -128;
1581 if (size < len + 6)
1582 break;
1585 * Git patch? It might not have a real patch, just a rename
1586 * or mode change, so we handle that specially
1588 if (!memcmp("diff --git ", line, 11)) {
1589 int git_hdr_len = parse_git_diff_header(&state->root, &state->linenr,
1590 state->p_value, line, len,
1591 size, patch);
1592 if (git_hdr_len < 0)
1593 return -128;
1594 if (git_hdr_len <= len)
1595 continue;
1596 *hdrsize = git_hdr_len;
1597 return offset;
1600 /* --- followed by +++ ? */
1601 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1602 continue;
1605 * We only accept unified patches, so we want it to
1606 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1607 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1609 nextlen = linelen(line + len, size - len);
1610 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1611 continue;
1613 /* Ok, we'll consider it a patch */
1614 if (parse_traditional_patch(state, line, line+len, patch))
1615 return -128;
1616 *hdrsize = len + nextlen;
1617 state->linenr += 2;
1618 return offset;
1620 return -1;
1623 static void record_ws_error(struct apply_state *state,
1624 unsigned result,
1625 const char *line,
1626 int len,
1627 int linenr)
1629 char *err;
1631 if (!result)
1632 return;
1634 state->whitespace_error++;
1635 if (state->squelch_whitespace_errors &&
1636 state->squelch_whitespace_errors < state->whitespace_error)
1637 return;
1639 err = whitespace_error_string(result);
1640 if (state->apply_verbosity > verbosity_silent)
1641 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1642 state->patch_input_file, linenr, err, len, line);
1643 free(err);
1646 static void check_whitespace(struct apply_state *state,
1647 const char *line,
1648 int len,
1649 unsigned ws_rule)
1651 unsigned result = ws_check(line + 1, len - 1, ws_rule);
1653 record_ws_error(state, result, line + 1, len - 2, state->linenr);
1657 * Check if the patch has context lines with CRLF or
1658 * the patch wants to remove lines with CRLF.
1660 static void check_old_for_crlf(struct patch *patch, const char *line, int len)
1662 if (len >= 2 && line[len-1] == '\n' && line[len-2] == '\r') {
1663 patch->ws_rule |= WS_CR_AT_EOL;
1664 patch->crlf_in_old = 1;
1670 * Parse a unified diff. Note that this really needs to parse each
1671 * fragment separately, since the only way to know the difference
1672 * between a "---" that is part of a patch, and a "---" that starts
1673 * the next patch is to look at the line counts..
1675 static int parse_fragment(struct apply_state *state,
1676 const char *line,
1677 unsigned long size,
1678 struct patch *patch,
1679 struct fragment *fragment)
1681 int added, deleted;
1682 int len = linelen(line, size), offset;
1683 unsigned long oldlines, newlines;
1684 unsigned long leading, trailing;
1686 offset = parse_fragment_header(line, len, fragment);
1687 if (offset < 0)
1688 return -1;
1689 if (offset > 0 && patch->recount)
1690 recount_diff(line + offset, size - offset, fragment);
1691 oldlines = fragment->oldlines;
1692 newlines = fragment->newlines;
1693 leading = 0;
1694 trailing = 0;
1696 /* Parse the thing.. */
1697 line += len;
1698 size -= len;
1699 state->linenr++;
1700 added = deleted = 0;
1701 for (offset = len;
1702 0 < size;
1703 offset += len, size -= len, line += len, state->linenr++) {
1704 if (!oldlines && !newlines)
1705 break;
1706 len = linelen(line, size);
1707 if (!len || line[len-1] != '\n')
1708 return -1;
1709 switch (*line) {
1710 default:
1711 return -1;
1712 case '\n': /* newer GNU diff, an empty context line */
1713 case ' ':
1714 oldlines--;
1715 newlines--;
1716 if (!deleted && !added)
1717 leading++;
1718 trailing++;
1719 check_old_for_crlf(patch, line, len);
1720 if (!state->apply_in_reverse &&
1721 state->ws_error_action == correct_ws_error)
1722 check_whitespace(state, line, len, patch->ws_rule);
1723 break;
1724 case '-':
1725 if (!state->apply_in_reverse)
1726 check_old_for_crlf(patch, line, len);
1727 if (state->apply_in_reverse &&
1728 state->ws_error_action != nowarn_ws_error)
1729 check_whitespace(state, line, len, patch->ws_rule);
1730 deleted++;
1731 oldlines--;
1732 trailing = 0;
1733 break;
1734 case '+':
1735 if (state->apply_in_reverse)
1736 check_old_for_crlf(patch, line, len);
1737 if (!state->apply_in_reverse &&
1738 state->ws_error_action != nowarn_ws_error)
1739 check_whitespace(state, line, len, patch->ws_rule);
1740 added++;
1741 newlines--;
1742 trailing = 0;
1743 break;
1746 * We allow "\ No newline at end of file". Depending
1747 * on locale settings when the patch was produced we
1748 * don't know what this line looks like. The only
1749 * thing we do know is that it begins with "\ ".
1750 * Checking for 12 is just for sanity check -- any
1751 * l10n of "\ No newline..." is at least that long.
1753 case '\\':
1754 if (len < 12 || memcmp(line, "\\ ", 2))
1755 return -1;
1756 break;
1759 if (oldlines || newlines)
1760 return -1;
1761 if (!patch->recount && !deleted && !added)
1762 return -1;
1764 fragment->leading = leading;
1765 fragment->trailing = trailing;
1768 * If a fragment ends with an incomplete line, we failed to include
1769 * it in the above loop because we hit oldlines == newlines == 0
1770 * before seeing it.
1772 if (12 < size && !memcmp(line, "\\ ", 2))
1773 offset += linelen(line, size);
1775 patch->lines_added += added;
1776 patch->lines_deleted += deleted;
1778 if (0 < patch->is_new && oldlines)
1779 return error(_("new file depends on old contents"));
1780 if (0 < patch->is_delete && newlines)
1781 return error(_("deleted file still has contents"));
1782 return offset;
1786 * We have seen "diff --git a/... b/..." header (or a traditional patch
1787 * header). Read hunks that belong to this patch into fragments and hang
1788 * them to the given patch structure.
1790 * The (fragment->patch, fragment->size) pair points into the memory given
1791 * by the caller, not a copy, when we return.
1793 * Returns:
1794 * -1 in case of error,
1795 * the number of bytes in the patch otherwise.
1797 static int parse_single_patch(struct apply_state *state,
1798 const char *line,
1799 unsigned long size,
1800 struct patch *patch)
1802 unsigned long offset = 0;
1803 unsigned long oldlines = 0, newlines = 0, context = 0;
1804 struct fragment **fragp = &patch->fragments;
1806 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1807 struct fragment *fragment;
1808 int len;
1810 CALLOC_ARRAY(fragment, 1);
1811 fragment->linenr = state->linenr;
1812 len = parse_fragment(state, line, size, patch, fragment);
1813 if (len <= 0) {
1814 free(fragment);
1815 return error(_("corrupt patch at line %d"), state->linenr);
1817 fragment->patch = line;
1818 fragment->size = len;
1819 oldlines += fragment->oldlines;
1820 newlines += fragment->newlines;
1821 context += fragment->leading + fragment->trailing;
1823 *fragp = fragment;
1824 fragp = &fragment->next;
1826 offset += len;
1827 line += len;
1828 size -= len;
1832 * If something was removed (i.e. we have old-lines) it cannot
1833 * be creation, and if something was added it cannot be
1834 * deletion. However, the reverse is not true; --unified=0
1835 * patches that only add are not necessarily creation even
1836 * though they do not have any old lines, and ones that only
1837 * delete are not necessarily deletion.
1839 * Unfortunately, a real creation/deletion patch do _not_ have
1840 * any context line by definition, so we cannot safely tell it
1841 * apart with --unified=0 insanity. At least if the patch has
1842 * more than one hunk it is not creation or deletion.
1844 if (patch->is_new < 0 &&
1845 (oldlines || (patch->fragments && patch->fragments->next)))
1846 patch->is_new = 0;
1847 if (patch->is_delete < 0 &&
1848 (newlines || (patch->fragments && patch->fragments->next)))
1849 patch->is_delete = 0;
1851 if (0 < patch->is_new && oldlines)
1852 return error(_("new file %s depends on old contents"), patch->new_name);
1853 if (0 < patch->is_delete && newlines)
1854 return error(_("deleted file %s still has contents"), patch->old_name);
1855 if (!patch->is_delete && !newlines && context && state->apply_verbosity > verbosity_silent)
1856 fprintf_ln(stderr,
1857 _("** warning: "
1858 "file %s becomes empty but is not deleted"),
1859 patch->new_name);
1861 return offset;
1864 static inline int metadata_changes(struct patch *patch)
1866 return patch->is_rename > 0 ||
1867 patch->is_copy > 0 ||
1868 patch->is_new > 0 ||
1869 patch->is_delete ||
1870 (patch->old_mode && patch->new_mode &&
1871 patch->old_mode != patch->new_mode);
1874 static char *inflate_it(const void *data, unsigned long size,
1875 unsigned long inflated_size)
1877 git_zstream stream;
1878 void *out;
1879 int st;
1881 memset(&stream, 0, sizeof(stream));
1883 stream.next_in = (unsigned char *)data;
1884 stream.avail_in = size;
1885 stream.next_out = out = xmalloc(inflated_size);
1886 stream.avail_out = inflated_size;
1887 git_inflate_init(&stream);
1888 st = git_inflate(&stream, Z_FINISH);
1889 git_inflate_end(&stream);
1890 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1891 free(out);
1892 return NULL;
1894 return out;
1898 * Read a binary hunk and return a new fragment; fragment->patch
1899 * points at an allocated memory that the caller must free, so
1900 * it is marked as "->free_patch = 1".
1902 static struct fragment *parse_binary_hunk(struct apply_state *state,
1903 char **buf_p,
1904 unsigned long *sz_p,
1905 int *status_p,
1906 int *used_p)
1909 * Expect a line that begins with binary patch method ("literal"
1910 * or "delta"), followed by the length of data before deflating.
1911 * a sequence of 'length-byte' followed by base-85 encoded data
1912 * should follow, terminated by a newline.
1914 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1915 * and we would limit the patch line to 66 characters,
1916 * so one line can fit up to 13 groups that would decode
1917 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1918 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1920 int llen, used;
1921 unsigned long size = *sz_p;
1922 char *buffer = *buf_p;
1923 int patch_method;
1924 unsigned long origlen;
1925 char *data = NULL;
1926 int hunk_size = 0;
1927 struct fragment *frag;
1929 llen = linelen(buffer, size);
1930 used = llen;
1932 *status_p = 0;
1934 if (starts_with(buffer, "delta ")) {
1935 patch_method = BINARY_DELTA_DEFLATED;
1936 origlen = strtoul(buffer + 6, NULL, 10);
1938 else if (starts_with(buffer, "literal ")) {
1939 patch_method = BINARY_LITERAL_DEFLATED;
1940 origlen = strtoul(buffer + 8, NULL, 10);
1942 else
1943 return NULL;
1945 state->linenr++;
1946 buffer += llen;
1947 size -= llen;
1948 while (1) {
1949 int byte_length, max_byte_length, newsize;
1950 llen = linelen(buffer, size);
1951 used += llen;
1952 state->linenr++;
1953 if (llen == 1) {
1954 /* consume the blank line */
1955 buffer++;
1956 size--;
1957 break;
1960 * Minimum line is "A00000\n" which is 7-byte long,
1961 * and the line length must be multiple of 5 plus 2.
1963 if ((llen < 7) || (llen-2) % 5)
1964 goto corrupt;
1965 max_byte_length = (llen - 2) / 5 * 4;
1966 byte_length = *buffer;
1967 if ('A' <= byte_length && byte_length <= 'Z')
1968 byte_length = byte_length - 'A' + 1;
1969 else if ('a' <= byte_length && byte_length <= 'z')
1970 byte_length = byte_length - 'a' + 27;
1971 else
1972 goto corrupt;
1973 /* if the input length was not multiple of 4, we would
1974 * have filler at the end but the filler should never
1975 * exceed 3 bytes
1977 if (max_byte_length < byte_length ||
1978 byte_length <= max_byte_length - 4)
1979 goto corrupt;
1980 newsize = hunk_size + byte_length;
1981 data = xrealloc(data, newsize);
1982 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1983 goto corrupt;
1984 hunk_size = newsize;
1985 buffer += llen;
1986 size -= llen;
1989 CALLOC_ARRAY(frag, 1);
1990 frag->patch = inflate_it(data, hunk_size, origlen);
1991 frag->free_patch = 1;
1992 if (!frag->patch)
1993 goto corrupt;
1994 free(data);
1995 frag->size = origlen;
1996 *buf_p = buffer;
1997 *sz_p = size;
1998 *used_p = used;
1999 frag->binary_patch_method = patch_method;
2000 return frag;
2002 corrupt:
2003 free(data);
2004 *status_p = -1;
2005 error(_("corrupt binary patch at line %d: %.*s"),
2006 state->linenr-1, llen-1, buffer);
2007 return NULL;
2011 * Returns:
2012 * -1 in case of error,
2013 * the length of the parsed binary patch otherwise
2015 static int parse_binary(struct apply_state *state,
2016 char *buffer,
2017 unsigned long size,
2018 struct patch *patch)
2021 * We have read "GIT binary patch\n"; what follows is a line
2022 * that says the patch method (currently, either "literal" or
2023 * "delta") and the length of data before deflating; a
2024 * sequence of 'length-byte' followed by base-85 encoded data
2025 * follows.
2027 * When a binary patch is reversible, there is another binary
2028 * hunk in the same format, starting with patch method (either
2029 * "literal" or "delta") with the length of data, and a sequence
2030 * of length-byte + base-85 encoded data, terminated with another
2031 * empty line. This data, when applied to the postimage, produces
2032 * the preimage.
2034 struct fragment *forward;
2035 struct fragment *reverse;
2036 int status;
2037 int used, used_1;
2039 forward = parse_binary_hunk(state, &buffer, &size, &status, &used);
2040 if (!forward && !status)
2041 /* there has to be one hunk (forward hunk) */
2042 return error(_("unrecognized binary patch at line %d"), state->linenr-1);
2043 if (status)
2044 /* otherwise we already gave an error message */
2045 return status;
2047 reverse = parse_binary_hunk(state, &buffer, &size, &status, &used_1);
2048 if (reverse)
2049 used += used_1;
2050 else if (status) {
2052 * Not having reverse hunk is not an error, but having
2053 * a corrupt reverse hunk is.
2055 free((void*) forward->patch);
2056 free(forward);
2057 return status;
2059 forward->next = reverse;
2060 patch->fragments = forward;
2061 patch->is_binary = 1;
2062 return used;
2065 static void prefix_one(struct apply_state *state, char **name)
2067 char *old_name = *name;
2068 if (!old_name)
2069 return;
2070 *name = prefix_filename(state->prefix, *name);
2071 free(old_name);
2074 static void prefix_patch(struct apply_state *state, struct patch *p)
2076 if (!state->prefix || p->is_toplevel_relative)
2077 return;
2078 prefix_one(state, &p->new_name);
2079 prefix_one(state, &p->old_name);
2083 * include/exclude
2086 static void add_name_limit(struct apply_state *state,
2087 const char *name,
2088 int exclude)
2090 struct string_list_item *it;
2092 it = string_list_append(&state->limit_by_name, name);
2093 it->util = exclude ? NULL : (void *) 1;
2096 static int use_patch(struct apply_state *state, struct patch *p)
2098 const char *pathname = p->new_name ? p->new_name : p->old_name;
2099 int i;
2101 /* Paths outside are not touched regardless of "--include" */
2102 if (state->prefix && *state->prefix) {
2103 const char *rest;
2104 if (!skip_prefix(pathname, state->prefix, &rest) || !*rest)
2105 return 0;
2108 /* See if it matches any of exclude/include rule */
2109 for (i = 0; i < state->limit_by_name.nr; i++) {
2110 struct string_list_item *it = &state->limit_by_name.items[i];
2111 if (!wildmatch(it->string, pathname, 0))
2112 return (it->util != NULL);
2116 * If we had any include, a path that does not match any rule is
2117 * not used. Otherwise, we saw bunch of exclude rules (or none)
2118 * and such a path is used.
2120 return !state->has_include;
2124 * Read the patch text in "buffer" that extends for "size" bytes; stop
2125 * reading after seeing a single patch (i.e. changes to a single file).
2126 * Create fragments (i.e. patch hunks) and hang them to the given patch.
2128 * Returns:
2129 * -1 if no header was found or parse_binary() failed,
2130 * -128 on another error,
2131 * the number of bytes consumed otherwise,
2132 * so that the caller can call us again for the next patch.
2134 static int parse_chunk(struct apply_state *state, char *buffer, unsigned long size, struct patch *patch)
2136 int hdrsize, patchsize;
2137 int offset = find_header(state, buffer, size, &hdrsize, patch);
2139 if (offset < 0)
2140 return offset;
2142 prefix_patch(state, patch);
2144 if (!use_patch(state, patch))
2145 patch->ws_rule = 0;
2146 else if (patch->new_name)
2147 patch->ws_rule = whitespace_rule(state->repo->index,
2148 patch->new_name);
2149 else
2150 patch->ws_rule = whitespace_rule(state->repo->index,
2151 patch->old_name);
2153 patchsize = parse_single_patch(state,
2154 buffer + offset + hdrsize,
2155 size - offset - hdrsize,
2156 patch);
2158 if (patchsize < 0)
2159 return -128;
2161 if (!patchsize) {
2162 static const char git_binary[] = "GIT binary patch\n";
2163 int hd = hdrsize + offset;
2164 unsigned long llen = linelen(buffer + hd, size - hd);
2166 if (llen == sizeof(git_binary) - 1 &&
2167 !memcmp(git_binary, buffer + hd, llen)) {
2168 int used;
2169 state->linenr++;
2170 used = parse_binary(state, buffer + hd + llen,
2171 size - hd - llen, patch);
2172 if (used < 0)
2173 return -1;
2174 if (used)
2175 patchsize = used + llen;
2176 else
2177 patchsize = 0;
2179 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
2180 static const char *binhdr[] = {
2181 "Binary files ",
2182 "Files ",
2183 NULL,
2185 int i;
2186 for (i = 0; binhdr[i]; i++) {
2187 int len = strlen(binhdr[i]);
2188 if (len < size - hd &&
2189 !memcmp(binhdr[i], buffer + hd, len)) {
2190 state->linenr++;
2191 patch->is_binary = 1;
2192 patchsize = llen;
2193 break;
2198 /* Empty patch cannot be applied if it is a text patch
2199 * without metadata change. A binary patch appears
2200 * empty to us here.
2202 if ((state->apply || state->check) &&
2203 (!patch->is_binary && !metadata_changes(patch))) {
2204 error(_("patch with only garbage at line %d"), state->linenr);
2205 return -128;
2209 return offset + hdrsize + patchsize;
2212 static void reverse_patches(struct patch *p)
2214 for (; p; p = p->next) {
2215 struct fragment *frag = p->fragments;
2217 SWAP(p->new_name, p->old_name);
2218 if (p->new_mode)
2219 SWAP(p->new_mode, p->old_mode);
2220 SWAP(p->is_new, p->is_delete);
2221 SWAP(p->lines_added, p->lines_deleted);
2222 SWAP(p->old_oid_prefix, p->new_oid_prefix);
2224 for (; frag; frag = frag->next) {
2225 SWAP(frag->newpos, frag->oldpos);
2226 SWAP(frag->newlines, frag->oldlines);
2231 static const char pluses[] =
2232 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2233 static const char minuses[]=
2234 "----------------------------------------------------------------------";
2236 static void show_stats(struct apply_state *state, struct patch *patch)
2238 struct strbuf qname = STRBUF_INIT;
2239 char *cp = patch->new_name ? patch->new_name : patch->old_name;
2240 int max, add, del;
2242 quote_c_style(cp, &qname, NULL, 0);
2245 * "scale" the filename
2247 max = state->max_len;
2248 if (max > 50)
2249 max = 50;
2251 if (qname.len > max) {
2252 cp = strchr(qname.buf + qname.len + 3 - max, '/');
2253 if (!cp)
2254 cp = qname.buf + qname.len + 3 - max;
2255 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
2258 if (patch->is_binary) {
2259 printf(" %-*s | Bin\n", max, qname.buf);
2260 strbuf_release(&qname);
2261 return;
2264 printf(" %-*s |", max, qname.buf);
2265 strbuf_release(&qname);
2268 * scale the add/delete
2270 max = max + state->max_change > 70 ? 70 - max : state->max_change;
2271 add = patch->lines_added;
2272 del = patch->lines_deleted;
2274 if (state->max_change > 0) {
2275 int total = ((add + del) * max + state->max_change / 2) / state->max_change;
2276 add = (add * max + state->max_change / 2) / state->max_change;
2277 del = total - add;
2279 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
2280 add, pluses, del, minuses);
2283 static int read_old_data(struct stat *st, struct patch *patch,
2284 const char *path, struct strbuf *buf)
2286 int conv_flags = patch->crlf_in_old ?
2287 CONV_EOL_KEEP_CRLF : CONV_EOL_RENORMALIZE;
2288 switch (st->st_mode & S_IFMT) {
2289 case S_IFLNK:
2290 if (strbuf_readlink(buf, path, st->st_size) < 0)
2291 return error(_("unable to read symlink %s"), path);
2292 return 0;
2293 case S_IFREG:
2294 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
2295 return error(_("unable to open or read %s"), path);
2297 * "git apply" without "--index/--cached" should never look
2298 * at the index; the target file may not have been added to
2299 * the index yet, and we may not even be in any Git repository.
2300 * Pass NULL to convert_to_git() to stress this; the function
2301 * should never look at the index when explicit crlf option
2302 * is given.
2304 convert_to_git(NULL, path, buf->buf, buf->len, buf, conv_flags);
2305 return 0;
2306 default:
2307 return -1;
2312 * Update the preimage, and the common lines in postimage,
2313 * from buffer buf of length len.
2315 static void update_pre_post_images(struct image *preimage,
2316 struct image *postimage,
2317 char *buf, size_t len)
2319 struct image fixed_preimage = IMAGE_INIT;
2320 size_t insert_pos = 0;
2321 int i, ctx, reduced;
2322 const char *fixed;
2325 * Update the preimage with whitespace fixes. Note that we
2326 * are not losing preimage->buf -- apply_one_fragment() will
2327 * free "oldlines".
2329 image_prepare(&fixed_preimage, buf, len, 1);
2330 for (i = 0; i < fixed_preimage.line_nr; i++)
2331 fixed_preimage.line[i].flag = preimage->line[i].flag;
2332 image_clear(preimage);
2333 *preimage = fixed_preimage;
2334 fixed = preimage->buf.buf;
2337 * Adjust the common context lines in postimage.
2339 for (i = reduced = ctx = 0; i < postimage->line_nr; i++) {
2340 size_t l_len = postimage->line[i].len;
2342 if (!(postimage->line[i].flag & LINE_COMMON)) {
2343 /* an added line -- no counterparts in preimage */
2344 insert_pos += l_len;
2345 continue;
2348 /* and find the corresponding one in the fixed preimage */
2349 while (ctx < preimage->line_nr &&
2350 !(preimage->line[ctx].flag & LINE_COMMON)) {
2351 fixed += preimage->line[ctx].len;
2352 ctx++;
2356 * preimage is expected to run out, if the caller
2357 * fixed addition of trailing blank lines.
2359 if (preimage->line_nr <= ctx) {
2360 reduced++;
2361 continue;
2364 /* and copy it in, while fixing the line length */
2365 l_len = preimage->line[ctx].len;
2366 strbuf_splice(&postimage->buf, insert_pos, postimage->line[i].len,
2367 fixed, l_len);
2368 insert_pos += l_len;
2369 fixed += l_len;
2370 postimage->line[i].len = l_len;
2371 ctx++;
2374 /* Fix the length of the whole thing */
2375 postimage->line_nr -= reduced;
2379 * Compare lines s1 of length n1 and s2 of length n2, ignoring
2380 * whitespace difference. Returns 1 if they match, 0 otherwise
2382 static int fuzzy_matchlines(const char *s1, size_t n1,
2383 const char *s2, size_t n2)
2385 const char *end1 = s1 + n1;
2386 const char *end2 = s2 + n2;
2388 /* ignore line endings */
2389 while (s1 < end1 && (end1[-1] == '\r' || end1[-1] == '\n'))
2390 end1--;
2391 while (s2 < end2 && (end2[-1] == '\r' || end2[-1] == '\n'))
2392 end2--;
2394 while (s1 < end1 && s2 < end2) {
2395 if (isspace(*s1)) {
2397 * Skip whitespace. We check on both buffers
2398 * because we don't want "a b" to match "ab".
2400 if (!isspace(*s2))
2401 return 0;
2402 while (s1 < end1 && isspace(*s1))
2403 s1++;
2404 while (s2 < end2 && isspace(*s2))
2405 s2++;
2406 } else if (*s1++ != *s2++)
2407 return 0;
2410 /* If we reached the end on one side only, lines don't match. */
2411 return s1 == end1 && s2 == end2;
2414 static int line_by_line_fuzzy_match(struct image *img,
2415 struct image *preimage,
2416 struct image *postimage,
2417 unsigned long current,
2418 int current_lno,
2419 int preimage_limit)
2421 int i;
2422 size_t imgoff = 0;
2423 size_t preoff = 0;
2424 size_t extra_chars;
2425 char *buf;
2426 char *preimage_eof;
2427 char *preimage_end;
2428 struct strbuf fixed;
2429 char *fixed_buf;
2430 size_t fixed_len;
2432 for (i = 0; i < preimage_limit; i++) {
2433 size_t prelen = preimage->line[i].len;
2434 size_t imglen = img->line[current_lno+i].len;
2436 if (!fuzzy_matchlines(img->buf.buf + current + imgoff, imglen,
2437 preimage->buf.buf + preoff, prelen))
2438 return 0;
2439 imgoff += imglen;
2440 preoff += prelen;
2444 * Ok, the preimage matches with whitespace fuzz.
2446 * imgoff now holds the true length of the target that
2447 * matches the preimage before the end of the file.
2449 * Count the number of characters in the preimage that fall
2450 * beyond the end of the file and make sure that all of them
2451 * are whitespace characters. (This can only happen if
2452 * we are removing blank lines at the end of the file.)
2454 buf = preimage_eof = preimage->buf.buf + preoff;
2455 for ( ; i < preimage->line_nr; i++)
2456 preoff += preimage->line[i].len;
2457 preimage_end = preimage->buf.buf + preoff;
2458 for ( ; buf < preimage_end; buf++)
2459 if (!isspace(*buf))
2460 return 0;
2463 * Update the preimage and the common postimage context
2464 * lines to use the same whitespace as the target.
2465 * If whitespace is missing in the target (i.e.
2466 * if the preimage extends beyond the end of the file),
2467 * use the whitespace from the preimage.
2469 extra_chars = preimage_end - preimage_eof;
2470 strbuf_init(&fixed, imgoff + extra_chars);
2471 strbuf_add(&fixed, img->buf.buf + current, imgoff);
2472 strbuf_add(&fixed, preimage_eof, extra_chars);
2473 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2474 update_pre_post_images(preimage, postimage,
2475 fixed_buf, fixed_len);
2476 return 1;
2479 static int match_fragment(struct apply_state *state,
2480 struct image *img,
2481 struct image *preimage,
2482 struct image *postimage,
2483 unsigned long current,
2484 int current_lno,
2485 unsigned ws_rule,
2486 int match_beginning, int match_end)
2488 int i;
2489 const char *orig, *target;
2490 struct strbuf fixed = STRBUF_INIT;
2491 char *fixed_buf;
2492 size_t fixed_len;
2493 int preimage_limit;
2494 int ret;
2496 if (preimage->line_nr + current_lno <= img->line_nr) {
2498 * The hunk falls within the boundaries of img.
2500 preimage_limit = preimage->line_nr;
2501 if (match_end && (preimage->line_nr + current_lno != img->line_nr)) {
2502 ret = 0;
2503 goto out;
2505 } else if (state->ws_error_action == correct_ws_error &&
2506 (ws_rule & WS_BLANK_AT_EOF)) {
2508 * This hunk extends beyond the end of img, and we are
2509 * removing blank lines at the end of the file. This
2510 * many lines from the beginning of the preimage must
2511 * match with img, and the remainder of the preimage
2512 * must be blank.
2514 preimage_limit = img->line_nr - current_lno;
2515 } else {
2517 * The hunk extends beyond the end of the img and
2518 * we are not removing blanks at the end, so we
2519 * should reject the hunk at this position.
2521 ret = 0;
2522 goto out;
2525 if (match_beginning && current_lno) {
2526 ret = 0;
2527 goto out;
2530 /* Quick hash check */
2531 for (i = 0; i < preimage_limit; i++) {
2532 if ((img->line[current_lno + i].flag & LINE_PATCHED) ||
2533 (preimage->line[i].hash != img->line[current_lno + i].hash)) {
2534 ret = 0;
2535 goto out;
2539 if (preimage_limit == preimage->line_nr) {
2541 * Do we have an exact match? If we were told to match
2542 * at the end, size must be exactly at current+fragsize,
2543 * otherwise current+fragsize must be still within the preimage,
2544 * and either case, the old piece should match the preimage
2545 * exactly.
2547 if ((match_end
2548 ? (current + preimage->buf.len == img->buf.len)
2549 : (current + preimage->buf.len <= img->buf.len)) &&
2550 !memcmp(img->buf.buf + current, preimage->buf.buf, preimage->buf.len)) {
2551 ret = 1;
2552 goto out;
2554 } else {
2556 * The preimage extends beyond the end of img, so
2557 * there cannot be an exact match.
2559 * There must be one non-blank context line that match
2560 * a line before the end of img.
2562 const char *buf, *buf_end;
2564 buf = preimage->buf.buf;
2565 buf_end = buf;
2566 for (i = 0; i < preimage_limit; i++)
2567 buf_end += preimage->line[i].len;
2569 for ( ; buf < buf_end; buf++)
2570 if (!isspace(*buf))
2571 break;
2572 if (buf == buf_end) {
2573 ret = 0;
2574 goto out;
2579 * No exact match. If we are ignoring whitespace, run a line-by-line
2580 * fuzzy matching. We collect all the line length information because
2581 * we need it to adjust whitespace if we match.
2583 if (state->ws_ignore_action == ignore_ws_change) {
2584 ret = line_by_line_fuzzy_match(img, preimage, postimage,
2585 current, current_lno, preimage_limit);
2586 goto out;
2589 if (state->ws_error_action != correct_ws_error) {
2590 ret = 0;
2591 goto out;
2595 * The hunk does not apply byte-by-byte, but the hash says
2596 * it might with whitespace fuzz. We weren't asked to
2597 * ignore whitespace, we were asked to correct whitespace
2598 * errors, so let's try matching after whitespace correction.
2600 * While checking the preimage against the target, whitespace
2601 * errors in both fixed, we count how large the corresponding
2602 * postimage needs to be. The postimage prepared by
2603 * apply_one_fragment() has whitespace errors fixed on added
2604 * lines already, but the common lines were propagated as-is,
2605 * which may become longer when their whitespace errors are
2606 * fixed.
2610 * The preimage may extend beyond the end of the file,
2611 * but in this loop we will only handle the part of the
2612 * preimage that falls within the file.
2614 strbuf_grow(&fixed, preimage->buf.len + 1);
2615 orig = preimage->buf.buf;
2616 target = img->buf.buf + current;
2617 for (i = 0; i < preimage_limit; i++) {
2618 size_t oldlen = preimage->line[i].len;
2619 size_t tgtlen = img->line[current_lno + i].len;
2620 size_t fixstart = fixed.len;
2621 struct strbuf tgtfix;
2622 int match;
2624 /* Try fixing the line in the preimage */
2625 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2627 /* Try fixing the line in the target */
2628 strbuf_init(&tgtfix, tgtlen);
2629 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2632 * If they match, either the preimage was based on
2633 * a version before our tree fixed whitespace breakage,
2634 * or we are lacking a whitespace-fix patch the tree
2635 * the preimage was based on already had (i.e. target
2636 * has whitespace breakage, the preimage doesn't).
2637 * In either case, we are fixing the whitespace breakages
2638 * so we might as well take the fix together with their
2639 * real change.
2641 match = (tgtfix.len == fixed.len - fixstart &&
2642 !memcmp(tgtfix.buf, fixed.buf + fixstart,
2643 fixed.len - fixstart));
2645 strbuf_release(&tgtfix);
2646 if (!match) {
2647 ret = 0;
2648 goto out;
2651 orig += oldlen;
2652 target += tgtlen;
2657 * Now handle the lines in the preimage that falls beyond the
2658 * end of the file (if any). They will only match if they are
2659 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2660 * false).
2662 for ( ; i < preimage->line_nr; i++) {
2663 size_t fixstart = fixed.len; /* start of the fixed preimage */
2664 size_t oldlen = preimage->line[i].len;
2665 int j;
2667 /* Try fixing the line in the preimage */
2668 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2670 for (j = fixstart; j < fixed.len; j++) {
2671 if (!isspace(fixed.buf[j])) {
2672 ret = 0;
2673 goto out;
2678 orig += oldlen;
2682 * Yes, the preimage is based on an older version that still
2683 * has whitespace breakages unfixed, and fixing them makes the
2684 * hunk match. Update the context lines in the postimage.
2686 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2687 update_pre_post_images(preimage, postimage,
2688 fixed_buf, fixed_len);
2690 ret = 1;
2692 out:
2693 strbuf_release(&fixed);
2694 return ret;
2697 static int find_pos(struct apply_state *state,
2698 struct image *img,
2699 struct image *preimage,
2700 struct image *postimage,
2701 int line,
2702 unsigned ws_rule,
2703 int match_beginning, int match_end)
2705 int i;
2706 unsigned long backwards, forwards, current;
2707 int backwards_lno, forwards_lno, current_lno;
2710 * When running with --allow-overlap, it is possible that a hunk is
2711 * seen that pretends to start at the beginning (but no longer does),
2712 * and that *still* needs to match the end. So trust `match_end` more
2713 * than `match_beginning`.
2715 if (state->allow_overlap && match_beginning && match_end &&
2716 img->line_nr - preimage->line_nr != 0)
2717 match_beginning = 0;
2720 * If match_beginning or match_end is specified, there is no
2721 * point starting from a wrong line that will never match and
2722 * wander around and wait for a match at the specified end.
2724 if (match_beginning)
2725 line = 0;
2726 else if (match_end)
2727 line = img->line_nr - preimage->line_nr;
2730 * Because the comparison is unsigned, the following test
2731 * will also take care of a negative line number that can
2732 * result when match_end and preimage is larger than the target.
2734 if ((size_t) line > img->line_nr)
2735 line = img->line_nr;
2737 current = 0;
2738 for (i = 0; i < line; i++)
2739 current += img->line[i].len;
2742 * There's probably some smart way to do this, but I'll leave
2743 * that to the smart and beautiful people. I'm simple and stupid.
2745 backwards = current;
2746 backwards_lno = line;
2747 forwards = current;
2748 forwards_lno = line;
2749 current_lno = line;
2751 for (i = 0; ; i++) {
2752 if (match_fragment(state, img, preimage, postimage,
2753 current, current_lno, ws_rule,
2754 match_beginning, match_end))
2755 return current_lno;
2757 again:
2758 if (backwards_lno == 0 && forwards_lno == img->line_nr)
2759 break;
2761 if (i & 1) {
2762 if (backwards_lno == 0) {
2763 i++;
2764 goto again;
2766 backwards_lno--;
2767 backwards -= img->line[backwards_lno].len;
2768 current = backwards;
2769 current_lno = backwards_lno;
2770 } else {
2771 if (forwards_lno == img->line_nr) {
2772 i++;
2773 goto again;
2775 forwards += img->line[forwards_lno].len;
2776 forwards_lno++;
2777 current = forwards;
2778 current_lno = forwards_lno;
2782 return -1;
2786 * The change from "preimage" and "postimage" has been found to
2787 * apply at applied_pos (counts in line numbers) in "img".
2788 * Update "img" to remove "preimage" and replace it with "postimage".
2790 static void update_image(struct apply_state *state,
2791 struct image *img,
2792 int applied_pos,
2793 struct image *preimage,
2794 struct image *postimage)
2797 * remove the copy of preimage at offset in img
2798 * and replace it with postimage
2800 int i, nr;
2801 size_t remove_count, insert_count, applied_at = 0;
2802 size_t result_alloc;
2803 char *result;
2804 int preimage_limit;
2807 * If we are removing blank lines at the end of img,
2808 * the preimage may extend beyond the end.
2809 * If that is the case, we must be careful only to
2810 * remove the part of the preimage that falls within
2811 * the boundaries of img. Initialize preimage_limit
2812 * to the number of lines in the preimage that falls
2813 * within the boundaries.
2815 preimage_limit = preimage->line_nr;
2816 if (preimage_limit > img->line_nr - applied_pos)
2817 preimage_limit = img->line_nr - applied_pos;
2819 for (i = 0; i < applied_pos; i++)
2820 applied_at += img->line[i].len;
2822 remove_count = 0;
2823 for (i = 0; i < preimage_limit; i++)
2824 remove_count += img->line[applied_pos + i].len;
2825 insert_count = postimage->buf.len;
2827 /* Adjust the contents */
2828 result_alloc = st_add3(st_sub(img->buf.len, remove_count), insert_count, 1);
2829 result = xmalloc(result_alloc);
2830 memcpy(result, img->buf.buf, applied_at);
2831 memcpy(result + applied_at, postimage->buf.buf, postimage->buf.len);
2832 memcpy(result + applied_at + postimage->buf.len,
2833 img->buf.buf + (applied_at + remove_count),
2834 img->buf.len - (applied_at + remove_count));
2835 strbuf_attach(&img->buf, result, postimage->buf.len + img->buf.len - remove_count,
2836 result_alloc);
2838 /* Adjust the line table */
2839 nr = img->line_nr + postimage->line_nr - preimage_limit;
2840 if (preimage_limit < postimage->line_nr)
2842 * NOTE: this knows that we never call image_remove_first_line()
2843 * on anything other than pre/post image.
2845 REALLOC_ARRAY(img->line, nr);
2846 if (preimage_limit != postimage->line_nr)
2847 MOVE_ARRAY(img->line + applied_pos + postimage->line_nr,
2848 img->line + applied_pos + preimage_limit,
2849 img->line_nr - (applied_pos + preimage_limit));
2850 COPY_ARRAY(img->line + applied_pos, postimage->line, postimage->line_nr);
2851 if (!state->allow_overlap)
2852 for (i = 0; i < postimage->line_nr; i++)
2853 img->line[applied_pos + i].flag |= LINE_PATCHED;
2854 img->line_nr = nr;
2858 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2859 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2860 * replace the part of "img" with "postimage" text.
2862 static int apply_one_fragment(struct apply_state *state,
2863 struct image *img, struct fragment *frag,
2864 int inaccurate_eof, unsigned ws_rule,
2865 int nth_fragment)
2867 int match_beginning, match_end;
2868 const char *patch = frag->patch;
2869 int size = frag->size;
2870 char *old, *oldlines;
2871 struct strbuf newlines;
2872 int new_blank_lines_at_end = 0;
2873 int found_new_blank_lines_at_end = 0;
2874 int hunk_linenr = frag->linenr;
2875 unsigned long leading, trailing;
2876 int pos, applied_pos;
2877 struct image preimage = IMAGE_INIT;
2878 struct image postimage = IMAGE_INIT;
2880 oldlines = xmalloc(size);
2881 strbuf_init(&newlines, size);
2883 old = oldlines;
2884 while (size > 0) {
2885 char first;
2886 int len = linelen(patch, size);
2887 int plen;
2888 int added_blank_line = 0;
2889 int is_blank_context = 0;
2890 size_t start;
2892 if (!len)
2893 break;
2896 * "plen" is how much of the line we should use for
2897 * the actual patch data. Normally we just remove the
2898 * first character on the line, but if the line is
2899 * followed by "\ No newline", then we also remove the
2900 * last one (which is the newline, of course).
2902 plen = len - 1;
2903 if (len < size && patch[len] == '\\')
2904 plen--;
2905 first = *patch;
2906 if (state->apply_in_reverse) {
2907 if (first == '-')
2908 first = '+';
2909 else if (first == '+')
2910 first = '-';
2913 switch (first) {
2914 case '\n':
2915 /* Newer GNU diff, empty context line */
2916 if (plen < 0)
2917 /* ... followed by '\No newline'; nothing */
2918 break;
2919 *old++ = '\n';
2920 strbuf_addch(&newlines, '\n');
2921 image_add_line(&preimage, "\n", 1, LINE_COMMON);
2922 image_add_line(&postimage, "\n", 1, LINE_COMMON);
2923 is_blank_context = 1;
2924 break;
2925 case ' ':
2926 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2927 ws_blank_line(patch + 1, plen))
2928 is_blank_context = 1;
2929 /* fallthrough */
2930 case '-':
2931 memcpy(old, patch + 1, plen);
2932 image_add_line(&preimage, old, plen,
2933 (first == ' ' ? LINE_COMMON : 0));
2934 old += plen;
2935 if (first == '-')
2936 break;
2937 /* fallthrough */
2938 case '+':
2939 /* --no-add does not add new lines */
2940 if (first == '+' && state->no_add)
2941 break;
2943 start = newlines.len;
2944 if (first != '+' ||
2945 !state->whitespace_error ||
2946 state->ws_error_action != correct_ws_error) {
2947 strbuf_add(&newlines, patch + 1, plen);
2949 else {
2950 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &state->applied_after_fixing_ws);
2952 image_add_line(&postimage, newlines.buf + start, newlines.len - start,
2953 (first == '+' ? 0 : LINE_COMMON));
2954 if (first == '+' &&
2955 (ws_rule & WS_BLANK_AT_EOF) &&
2956 ws_blank_line(patch + 1, plen))
2957 added_blank_line = 1;
2958 break;
2959 case '@': case '\\':
2960 /* Ignore it, we already handled it */
2961 break;
2962 default:
2963 if (state->apply_verbosity > verbosity_normal)
2964 error(_("invalid start of line: '%c'"), first);
2965 applied_pos = -1;
2966 goto out;
2968 if (added_blank_line) {
2969 if (!new_blank_lines_at_end)
2970 found_new_blank_lines_at_end = hunk_linenr;
2971 new_blank_lines_at_end++;
2973 else if (is_blank_context)
2975 else
2976 new_blank_lines_at_end = 0;
2977 patch += len;
2978 size -= len;
2979 hunk_linenr++;
2981 if (inaccurate_eof &&
2982 old > oldlines && old[-1] == '\n' &&
2983 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
2984 old--;
2985 strbuf_setlen(&newlines, newlines.len - 1);
2986 preimage.line[preimage.line_nr - 1].len--;
2987 postimage.line[postimage.line_nr - 1].len--;
2990 leading = frag->leading;
2991 trailing = frag->trailing;
2994 * A hunk to change lines at the beginning would begin with
2995 * @@ -1,L +N,M @@
2996 * but we need to be careful. -U0 that inserts before the second
2997 * line also has this pattern.
2999 * And a hunk to add to an empty file would begin with
3000 * @@ -0,0 +N,M @@
3002 * In other words, a hunk that is (frag->oldpos <= 1) with or
3003 * without leading context must match at the beginning.
3005 match_beginning = (!frag->oldpos ||
3006 (frag->oldpos == 1 && !state->unidiff_zero));
3009 * A hunk without trailing lines must match at the end.
3010 * However, we simply cannot tell if a hunk must match end
3011 * from the lack of trailing lines if the patch was generated
3012 * with unidiff without any context.
3014 match_end = !state->unidiff_zero && !trailing;
3016 pos = frag->newpos ? (frag->newpos - 1) : 0;
3017 strbuf_add(&preimage.buf, oldlines, old - oldlines);
3018 strbuf_swap(&postimage.buf, &newlines);
3020 for (;;) {
3022 applied_pos = find_pos(state, img, &preimage, &postimage, pos,
3023 ws_rule, match_beginning, match_end);
3025 if (applied_pos >= 0)
3026 break;
3028 /* Am I at my context limits? */
3029 if ((leading <= state->p_context) && (trailing <= state->p_context))
3030 break;
3031 if (match_beginning || match_end) {
3032 match_beginning = match_end = 0;
3033 continue;
3037 * Reduce the number of context lines; reduce both
3038 * leading and trailing if they are equal otherwise
3039 * just reduce the larger context.
3041 if (leading >= trailing) {
3042 image_remove_first_line(&preimage);
3043 image_remove_first_line(&postimage);
3044 pos--;
3045 leading--;
3047 if (trailing > leading) {
3048 image_remove_last_line(&preimage);
3049 image_remove_last_line(&postimage);
3050 trailing--;
3054 if (applied_pos >= 0) {
3055 if (new_blank_lines_at_end &&
3056 preimage.line_nr + applied_pos >= img->line_nr &&
3057 (ws_rule & WS_BLANK_AT_EOF) &&
3058 state->ws_error_action != nowarn_ws_error) {
3059 record_ws_error(state, WS_BLANK_AT_EOF, "+", 1,
3060 found_new_blank_lines_at_end);
3061 if (state->ws_error_action == correct_ws_error) {
3062 while (new_blank_lines_at_end--)
3063 image_remove_last_line(&postimage);
3066 * We would want to prevent write_out_results()
3067 * from taking place in apply_patch() that follows
3068 * the callchain led us here, which is:
3069 * apply_patch->check_patch_list->check_patch->
3070 * apply_data->apply_fragments->apply_one_fragment
3072 if (state->ws_error_action == die_on_ws_error)
3073 state->apply = 0;
3076 if (state->apply_verbosity > verbosity_normal && applied_pos != pos) {
3077 int offset = applied_pos - pos;
3078 if (state->apply_in_reverse)
3079 offset = 0 - offset;
3080 fprintf_ln(stderr,
3081 Q_("Hunk #%d succeeded at %d (offset %d line).",
3082 "Hunk #%d succeeded at %d (offset %d lines).",
3083 offset),
3084 nth_fragment, applied_pos + 1, offset);
3088 * Warn if it was necessary to reduce the number
3089 * of context lines.
3091 if ((leading != frag->leading ||
3092 trailing != frag->trailing) && state->apply_verbosity > verbosity_silent)
3093 fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"
3094 " to apply fragment at %d"),
3095 leading, trailing, applied_pos+1);
3096 update_image(state, img, applied_pos, &preimage, &postimage);
3097 } else {
3098 if (state->apply_verbosity > verbosity_normal)
3099 error(_("while searching for:\n%.*s"),
3100 (int)(old - oldlines), oldlines);
3103 out:
3104 free(oldlines);
3105 strbuf_release(&newlines);
3106 image_clear(&preimage);
3107 image_clear(&postimage);
3109 return (applied_pos < 0);
3112 static int apply_binary_fragment(struct apply_state *state,
3113 struct image *img,
3114 struct patch *patch)
3116 struct fragment *fragment = patch->fragments;
3117 unsigned long len;
3118 void *dst;
3120 if (!fragment)
3121 return error(_("missing binary patch data for '%s'"),
3122 patch->new_name ?
3123 patch->new_name :
3124 patch->old_name);
3126 /* Binary patch is irreversible without the optional second hunk */
3127 if (state->apply_in_reverse) {
3128 if (!fragment->next)
3129 return error(_("cannot reverse-apply a binary patch "
3130 "without the reverse hunk to '%s'"),
3131 patch->new_name
3132 ? patch->new_name : patch->old_name);
3133 fragment = fragment->next;
3135 switch (fragment->binary_patch_method) {
3136 case BINARY_DELTA_DEFLATED:
3137 dst = patch_delta(img->buf.buf, img->buf.len, fragment->patch,
3138 fragment->size, &len);
3139 if (!dst)
3140 return -1;
3141 image_clear(img);
3142 strbuf_attach(&img->buf, dst, len, len + 1);
3143 return 0;
3144 case BINARY_LITERAL_DEFLATED:
3145 image_clear(img);
3146 strbuf_add(&img->buf, fragment->patch, fragment->size);
3147 return 0;
3149 return -1;
3153 * Replace "img" with the result of applying the binary patch.
3154 * The binary patch data itself in patch->fragment is still kept
3155 * but the preimage prepared by the caller in "img" is freed here
3156 * or in the helper function apply_binary_fragment() this calls.
3158 static int apply_binary(struct apply_state *state,
3159 struct image *img,
3160 struct patch *patch)
3162 const char *name = patch->old_name ? patch->old_name : patch->new_name;
3163 struct object_id oid;
3164 const unsigned hexsz = the_hash_algo->hexsz;
3167 * For safety, we require patch index line to contain
3168 * full hex textual object ID for old and new, at least for now.
3170 if (strlen(patch->old_oid_prefix) != hexsz ||
3171 strlen(patch->new_oid_prefix) != hexsz ||
3172 get_oid_hex(patch->old_oid_prefix, &oid) ||
3173 get_oid_hex(patch->new_oid_prefix, &oid))
3174 return error(_("cannot apply binary patch to '%s' "
3175 "without full index line"), name);
3177 if (patch->old_name) {
3179 * See if the old one matches what the patch
3180 * applies to.
3182 hash_object_file(the_hash_algo, img->buf.buf, img->buf.len,
3183 OBJ_BLOB, &oid);
3184 if (strcmp(oid_to_hex(&oid), patch->old_oid_prefix))
3185 return error(_("the patch applies to '%s' (%s), "
3186 "which does not match the "
3187 "current contents."),
3188 name, oid_to_hex(&oid));
3190 else {
3191 /* Otherwise, the old one must be empty. */
3192 if (img->buf.len)
3193 return error(_("the patch applies to an empty "
3194 "'%s' but it is not empty"), name);
3197 get_oid_hex(patch->new_oid_prefix, &oid);
3198 if (is_null_oid(&oid)) {
3199 image_clear(img);
3200 return 0; /* deletion patch */
3203 if (has_object(the_repository, &oid, 0)) {
3204 /* We already have the postimage */
3205 enum object_type type;
3206 unsigned long size;
3207 char *result;
3209 result = repo_read_object_file(the_repository, &oid, &type,
3210 &size);
3211 if (!result)
3212 return error(_("the necessary postimage %s for "
3213 "'%s' cannot be read"),
3214 patch->new_oid_prefix, name);
3215 image_clear(img);
3216 strbuf_attach(&img->buf, result, size, size + 1);
3217 } else {
3219 * We have verified buf matches the preimage;
3220 * apply the patch data to it, which is stored
3221 * in the patch->fragments->{patch,size}.
3223 if (apply_binary_fragment(state, img, patch))
3224 return error(_("binary patch does not apply to '%s'"),
3225 name);
3227 /* verify that the result matches */
3228 hash_object_file(the_hash_algo, img->buf.buf, img->buf.len, OBJ_BLOB,
3229 &oid);
3230 if (strcmp(oid_to_hex(&oid), patch->new_oid_prefix))
3231 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3232 name, patch->new_oid_prefix, oid_to_hex(&oid));
3235 return 0;
3238 static int apply_fragments(struct apply_state *state, struct image *img, struct patch *patch)
3240 struct fragment *frag = patch->fragments;
3241 const char *name = patch->old_name ? patch->old_name : patch->new_name;
3242 unsigned ws_rule = patch->ws_rule;
3243 unsigned inaccurate_eof = patch->inaccurate_eof;
3244 int nth = 0;
3246 if (patch->is_binary)
3247 return apply_binary(state, img, patch);
3249 while (frag) {
3250 nth++;
3251 if (apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {
3252 error(_("patch failed: %s:%ld"), name, frag->oldpos);
3253 if (!state->apply_with_reject)
3254 return -1;
3255 frag->rejected = 1;
3257 frag = frag->next;
3259 return 0;
3262 static int read_blob_object(struct strbuf *buf, const struct object_id *oid, unsigned mode)
3264 if (S_ISGITLINK(mode)) {
3265 strbuf_grow(buf, 100);
3266 strbuf_addf(buf, "Subproject commit %s\n", oid_to_hex(oid));
3267 } else {
3268 enum object_type type;
3269 unsigned long sz;
3270 char *result;
3272 result = repo_read_object_file(the_repository, oid, &type,
3273 &sz);
3274 if (!result)
3275 return -1;
3276 /* XXX read_sha1_file NUL-terminates */
3277 strbuf_attach(buf, result, sz, sz + 1);
3279 return 0;
3282 static int read_file_or_gitlink(const struct cache_entry *ce, struct strbuf *buf)
3284 if (!ce)
3285 return 0;
3286 return read_blob_object(buf, &ce->oid, ce->ce_mode);
3289 static struct patch *in_fn_table(struct apply_state *state, const char *name)
3291 struct string_list_item *item;
3293 if (!name)
3294 return NULL;
3296 item = string_list_lookup(&state->fn_table, name);
3297 if (item)
3298 return (struct patch *)item->util;
3300 return NULL;
3304 * item->util in the filename table records the status of the path.
3305 * Usually it points at a patch (whose result records the contents
3306 * of it after applying it), but it could be PATH_WAS_DELETED for a
3307 * path that a previously applied patch has already removed, or
3308 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3310 * The latter is needed to deal with a case where two paths A and B
3311 * are swapped by first renaming A to B and then renaming B to A;
3312 * moving A to B should not be prevented due to presence of B as we
3313 * will remove it in a later patch.
3315 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3316 #define PATH_WAS_DELETED ((struct patch *) -1)
3318 static int to_be_deleted(struct patch *patch)
3320 return patch == PATH_TO_BE_DELETED;
3323 static int was_deleted(struct patch *patch)
3325 return patch == PATH_WAS_DELETED;
3328 static void add_to_fn_table(struct apply_state *state, struct patch *patch)
3330 struct string_list_item *item;
3333 * Always add new_name unless patch is a deletion
3334 * This should cover the cases for normal diffs,
3335 * file creations and copies
3337 if (patch->new_name) {
3338 item = string_list_insert(&state->fn_table, patch->new_name);
3339 item->util = patch;
3343 * store a failure on rename/deletion cases because
3344 * later chunks shouldn't patch old names
3346 if ((patch->new_name == NULL) || (patch->is_rename)) {
3347 item = string_list_insert(&state->fn_table, patch->old_name);
3348 item->util = PATH_WAS_DELETED;
3352 static void prepare_fn_table(struct apply_state *state, struct patch *patch)
3355 * store information about incoming file deletion
3357 while (patch) {
3358 if ((patch->new_name == NULL) || (patch->is_rename)) {
3359 struct string_list_item *item;
3360 item = string_list_insert(&state->fn_table, patch->old_name);
3361 item->util = PATH_TO_BE_DELETED;
3363 patch = patch->next;
3367 static int checkout_target(struct index_state *istate,
3368 struct cache_entry *ce, struct stat *st)
3370 struct checkout costate = CHECKOUT_INIT;
3372 costate.refresh_cache = 1;
3373 costate.istate = istate;
3374 if (checkout_entry(ce, &costate, NULL, NULL) ||
3375 lstat(ce->name, st))
3376 return error(_("cannot checkout %s"), ce->name);
3377 return 0;
3380 static struct patch *previous_patch(struct apply_state *state,
3381 struct patch *patch,
3382 int *gone)
3384 struct patch *previous;
3386 *gone = 0;
3387 if (patch->is_copy || patch->is_rename)
3388 return NULL; /* "git" patches do not depend on the order */
3390 previous = in_fn_table(state, patch->old_name);
3391 if (!previous)
3392 return NULL;
3394 if (to_be_deleted(previous))
3395 return NULL; /* the deletion hasn't happened yet */
3397 if (was_deleted(previous))
3398 *gone = 1;
3400 return previous;
3403 static int verify_index_match(struct apply_state *state,
3404 const struct cache_entry *ce,
3405 struct stat *st)
3407 if (S_ISGITLINK(ce->ce_mode)) {
3408 if (!S_ISDIR(st->st_mode))
3409 return -1;
3410 return 0;
3412 return ie_match_stat(state->repo->index, ce, st,
3413 CE_MATCH_IGNORE_VALID | CE_MATCH_IGNORE_SKIP_WORKTREE);
3416 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3418 static int load_patch_target(struct apply_state *state,
3419 struct strbuf *buf,
3420 const struct cache_entry *ce,
3421 struct stat *st,
3422 struct patch *patch,
3423 const char *name,
3424 unsigned expected_mode)
3426 if (state->cached || state->check_index) {
3427 if (read_file_or_gitlink(ce, buf))
3428 return error(_("failed to read %s"), name);
3429 } else if (name) {
3430 if (S_ISGITLINK(expected_mode)) {
3431 if (ce)
3432 return read_file_or_gitlink(ce, buf);
3433 else
3434 return SUBMODULE_PATCH_WITHOUT_INDEX;
3435 } else if (has_symlink_leading_path(name, strlen(name))) {
3436 return error(_("reading from '%s' beyond a symbolic link"), name);
3437 } else {
3438 if (read_old_data(st, patch, name, buf))
3439 return error(_("failed to read %s"), name);
3442 return 0;
3446 * We are about to apply "patch"; populate the "image" with the
3447 * current version we have, from the working tree or from the index,
3448 * depending on the situation e.g. --cached/--index. If we are
3449 * applying a non-git patch that incrementally updates the tree,
3450 * we read from the result of a previous diff.
3452 static int load_preimage(struct apply_state *state,
3453 struct image *image,
3454 struct patch *patch, struct stat *st,
3455 const struct cache_entry *ce)
3457 struct strbuf buf = STRBUF_INIT;
3458 size_t len;
3459 char *img;
3460 struct patch *previous;
3461 int status;
3463 previous = previous_patch(state, patch, &status);
3464 if (status)
3465 return error(_("path %s has been renamed/deleted"),
3466 patch->old_name);
3467 if (previous) {
3468 /* We have a patched copy in memory; use that. */
3469 strbuf_add(&buf, previous->result, previous->resultsize);
3470 } else {
3471 status = load_patch_target(state, &buf, ce, st, patch,
3472 patch->old_name, patch->old_mode);
3473 if (status < 0)
3474 return status;
3475 else if (status == SUBMODULE_PATCH_WITHOUT_INDEX) {
3477 * There is no way to apply subproject
3478 * patch without looking at the index.
3479 * NEEDSWORK: shouldn't this be flagged
3480 * as an error???
3482 free_fragment_list(patch->fragments);
3483 patch->fragments = NULL;
3484 } else if (status) {
3485 return error(_("failed to read %s"), patch->old_name);
3489 img = strbuf_detach(&buf, &len);
3490 image_prepare(image, img, len, !patch->is_binary);
3491 return 0;
3494 static int resolve_to(struct image *image, const struct object_id *result_id)
3496 unsigned long size;
3497 enum object_type type;
3498 char *data;
3500 image_clear(image);
3502 data = repo_read_object_file(the_repository, result_id, &type, &size);
3503 if (!data || type != OBJ_BLOB)
3504 die("unable to read blob object %s", oid_to_hex(result_id));
3505 strbuf_attach(&image->buf, data, size, size + 1);
3507 return 0;
3510 static int three_way_merge(struct apply_state *state,
3511 struct image *image,
3512 char *path,
3513 const struct object_id *base,
3514 const struct object_id *ours,
3515 const struct object_id *theirs)
3517 mmfile_t base_file, our_file, their_file;
3518 struct ll_merge_options merge_opts = LL_MERGE_OPTIONS_INIT;
3519 mmbuffer_t result = { NULL };
3520 enum ll_merge_result status;
3522 /* resolve trivial cases first */
3523 if (oideq(base, ours))
3524 return resolve_to(image, theirs);
3525 else if (oideq(base, theirs) || oideq(ours, theirs))
3526 return resolve_to(image, ours);
3528 read_mmblob(&base_file, base);
3529 read_mmblob(&our_file, ours);
3530 read_mmblob(&their_file, theirs);
3531 merge_opts.variant = state->merge_variant;
3532 status = ll_merge(&result, path,
3533 &base_file, "base",
3534 &our_file, "ours",
3535 &their_file, "theirs",
3536 state->repo->index,
3537 &merge_opts);
3538 if (status == LL_MERGE_BINARY_CONFLICT)
3539 warning("Cannot merge binary files: %s (%s vs. %s)",
3540 path, "ours", "theirs");
3541 free(base_file.ptr);
3542 free(our_file.ptr);
3543 free(their_file.ptr);
3544 if (status < 0 || !result.ptr) {
3545 free(result.ptr);
3546 return -1;
3548 image_clear(image);
3549 strbuf_attach(&image->buf, result.ptr, result.size, result.size);
3551 return status;
3555 * When directly falling back to add/add three-way merge, we read from
3556 * the current contents of the new_name. In no cases other than that
3557 * this function will be called.
3559 static int load_current(struct apply_state *state,
3560 struct image *image,
3561 struct patch *patch)
3563 struct strbuf buf = STRBUF_INIT;
3564 int status, pos;
3565 size_t len;
3566 char *img;
3567 struct stat st;
3568 struct cache_entry *ce;
3569 char *name = patch->new_name;
3570 unsigned mode = patch->new_mode;
3572 if (!patch->is_new)
3573 BUG("patch to %s is not a creation", patch->old_name);
3575 pos = index_name_pos(state->repo->index, name, strlen(name));
3576 if (pos < 0)
3577 return error(_("%s: does not exist in index"), name);
3578 ce = state->repo->index->cache[pos];
3579 if (lstat(name, &st)) {
3580 if (errno != ENOENT)
3581 return error_errno("%s", name);
3582 if (checkout_target(state->repo->index, ce, &st))
3583 return -1;
3585 if (verify_index_match(state, ce, &st))
3586 return error(_("%s: does not match index"), name);
3588 status = load_patch_target(state, &buf, ce, &st, patch, name, mode);
3589 if (status < 0)
3590 return status;
3591 else if (status)
3592 return -1;
3593 img = strbuf_detach(&buf, &len);
3594 image_prepare(image, img, len, !patch->is_binary);
3595 return 0;
3598 static int try_threeway(struct apply_state *state,
3599 struct image *image,
3600 struct patch *patch,
3601 struct stat *st,
3602 const struct cache_entry *ce)
3604 struct object_id pre_oid, post_oid, our_oid;
3605 struct strbuf buf = STRBUF_INIT;
3606 size_t len;
3607 int status;
3608 char *img;
3609 struct image tmp_image = IMAGE_INIT;
3611 /* No point falling back to 3-way merge in these cases */
3612 if (patch->is_delete ||
3613 S_ISGITLINK(patch->old_mode) || S_ISGITLINK(patch->new_mode) ||
3614 (patch->is_new && !patch->direct_to_threeway) ||
3615 (patch->is_rename && !patch->lines_added && !patch->lines_deleted))
3616 return -1;
3618 /* Preimage the patch was prepared for */
3619 if (patch->is_new)
3620 write_object_file("", 0, OBJ_BLOB, &pre_oid);
3621 else if (repo_get_oid(the_repository, patch->old_oid_prefix, &pre_oid) ||
3622 read_blob_object(&buf, &pre_oid, patch->old_mode))
3623 return error(_("repository lacks the necessary blob to perform 3-way merge."));
3625 if (state->apply_verbosity > verbosity_silent && patch->direct_to_threeway)
3626 fprintf(stderr, _("Performing three-way merge...\n"));
3628 img = strbuf_detach(&buf, &len);
3629 image_prepare(&tmp_image, img, len, 1);
3630 /* Apply the patch to get the post image */
3631 if (apply_fragments(state, &tmp_image, patch) < 0) {
3632 image_clear(&tmp_image);
3633 return -1;
3635 /* post_oid is theirs */
3636 write_object_file(tmp_image.buf.buf, tmp_image.buf.len, OBJ_BLOB, &post_oid);
3637 image_clear(&tmp_image);
3639 /* our_oid is ours */
3640 if (patch->is_new) {
3641 if (load_current(state, &tmp_image, patch))
3642 return error(_("cannot read the current contents of '%s'"),
3643 patch->new_name);
3644 } else {
3645 if (load_preimage(state, &tmp_image, patch, st, ce))
3646 return error(_("cannot read the current contents of '%s'"),
3647 patch->old_name);
3649 write_object_file(tmp_image.buf.buf, tmp_image.buf.len, OBJ_BLOB, &our_oid);
3650 image_clear(&tmp_image);
3652 /* in-core three-way merge between post and our using pre as base */
3653 status = three_way_merge(state, image, patch->new_name,
3654 &pre_oid, &our_oid, &post_oid);
3655 if (status < 0) {
3656 if (state->apply_verbosity > verbosity_silent)
3657 fprintf(stderr,
3658 _("Failed to perform three-way merge...\n"));
3659 return status;
3662 if (status) {
3663 patch->conflicted_threeway = 1;
3664 if (patch->is_new)
3665 oidclr(&patch->threeway_stage[0], the_repository->hash_algo);
3666 else
3667 oidcpy(&patch->threeway_stage[0], &pre_oid);
3668 oidcpy(&patch->threeway_stage[1], &our_oid);
3669 oidcpy(&patch->threeway_stage[2], &post_oid);
3670 if (state->apply_verbosity > verbosity_silent)
3671 fprintf(stderr,
3672 _("Applied patch to '%s' with conflicts.\n"),
3673 patch->new_name);
3674 } else {
3675 if (state->apply_verbosity > verbosity_silent)
3676 fprintf(stderr,
3677 _("Applied patch to '%s' cleanly.\n"),
3678 patch->new_name);
3680 return 0;
3683 static int apply_data(struct apply_state *state, struct patch *patch,
3684 struct stat *st, const struct cache_entry *ce)
3686 struct image image = IMAGE_INIT;
3688 if (load_preimage(state, &image, patch, st, ce) < 0)
3689 return -1;
3691 if (!state->threeway || try_threeway(state, &image, patch, st, ce) < 0) {
3692 if (state->apply_verbosity > verbosity_silent &&
3693 state->threeway && !patch->direct_to_threeway)
3694 fprintf(stderr, _("Falling back to direct application...\n"));
3696 /* Note: with --reject, apply_fragments() returns 0 */
3697 if (patch->direct_to_threeway || apply_fragments(state, &image, patch) < 0) {
3698 image_clear(&image);
3699 return -1;
3702 patch->result = strbuf_detach(&image.buf, &patch->resultsize);
3703 add_to_fn_table(state, patch);
3704 free(image.line);
3706 if (0 < patch->is_delete && patch->resultsize)
3707 return error(_("removal patch leaves file contents"));
3709 return 0;
3713 * If "patch" that we are looking at modifies or deletes what we have,
3714 * we would want it not to lose any local modification we have, either
3715 * in the working tree or in the index.
3717 * This also decides if a non-git patch is a creation patch or a
3718 * modification to an existing empty file. We do not check the state
3719 * of the current tree for a creation patch in this function; the caller
3720 * check_patch() separately makes sure (and errors out otherwise) that
3721 * the path the patch creates does not exist in the current tree.
3723 static int check_preimage(struct apply_state *state,
3724 struct patch *patch,
3725 struct cache_entry **ce,
3726 struct stat *st)
3728 const char *old_name = patch->old_name;
3729 struct patch *previous = NULL;
3730 int stat_ret = 0, status;
3731 unsigned st_mode = 0;
3733 if (!old_name)
3734 return 0;
3736 assert(patch->is_new <= 0);
3737 previous = previous_patch(state, patch, &status);
3739 if (status)
3740 return error(_("path %s has been renamed/deleted"), old_name);
3741 if (previous) {
3742 st_mode = previous->new_mode;
3743 } else if (!state->cached) {
3744 stat_ret = lstat(old_name, st);
3745 if (stat_ret && errno != ENOENT)
3746 return error_errno("%s", old_name);
3749 if (state->check_index && !previous) {
3750 int pos = index_name_pos(state->repo->index, old_name,
3751 strlen(old_name));
3752 if (pos < 0) {
3753 if (patch->is_new < 0)
3754 goto is_new;
3755 return error(_("%s: does not exist in index"), old_name);
3757 *ce = state->repo->index->cache[pos];
3758 if (stat_ret < 0) {
3759 if (checkout_target(state->repo->index, *ce, st))
3760 return -1;
3762 if (!state->cached && verify_index_match(state, *ce, st))
3763 return error(_("%s: does not match index"), old_name);
3764 if (state->cached)
3765 st_mode = (*ce)->ce_mode;
3766 } else if (stat_ret < 0) {
3767 if (patch->is_new < 0)
3768 goto is_new;
3769 return error_errno("%s", old_name);
3772 if (!state->cached && !previous) {
3773 if (*ce && !(*ce)->ce_mode)
3774 BUG("ce_mode == 0 for path '%s'", old_name);
3776 if (trust_executable_bit)
3777 st_mode = ce_mode_from_stat(*ce, st->st_mode);
3778 else if (*ce)
3779 st_mode = (*ce)->ce_mode;
3780 else
3781 st_mode = patch->old_mode;
3784 if (patch->is_new < 0)
3785 patch->is_new = 0;
3786 if (!patch->old_mode)
3787 patch->old_mode = st_mode;
3788 if ((st_mode ^ patch->old_mode) & S_IFMT)
3789 return error(_("%s: wrong type"), old_name);
3790 if (st_mode != patch->old_mode)
3791 warning(_("%s has type %o, expected %o"),
3792 old_name, st_mode, patch->old_mode);
3793 if (!patch->new_mode && !patch->is_delete)
3794 patch->new_mode = st_mode;
3795 return 0;
3797 is_new:
3798 patch->is_new = 1;
3799 patch->is_delete = 0;
3800 FREE_AND_NULL(patch->old_name);
3801 return 0;
3805 #define EXISTS_IN_INDEX 1
3806 #define EXISTS_IN_WORKTREE 2
3807 #define EXISTS_IN_INDEX_AS_ITA 3
3809 static int check_to_create(struct apply_state *state,
3810 const char *new_name,
3811 int ok_if_exists)
3813 struct stat nst;
3815 if (state->check_index && (!ok_if_exists || !state->cached)) {
3816 int pos;
3818 pos = index_name_pos(state->repo->index, new_name, strlen(new_name));
3819 if (pos >= 0) {
3820 struct cache_entry *ce = state->repo->index->cache[pos];
3822 /* allow ITA, as they do not yet exist in the index */
3823 if (!ok_if_exists && !(ce->ce_flags & CE_INTENT_TO_ADD))
3824 return EXISTS_IN_INDEX;
3826 /* ITA entries can never match working tree files */
3827 if (!state->cached && (ce->ce_flags & CE_INTENT_TO_ADD))
3828 return EXISTS_IN_INDEX_AS_ITA;
3832 if (state->cached)
3833 return 0;
3835 if (!lstat(new_name, &nst)) {
3836 if (S_ISDIR(nst.st_mode) || ok_if_exists)
3837 return 0;
3839 * A leading component of new_name might be a symlink
3840 * that is going to be removed with this patch, but
3841 * still pointing at somewhere that has the path.
3842 * In such a case, path "new_name" does not exist as
3843 * far as git is concerned.
3845 if (has_symlink_leading_path(new_name, strlen(new_name)))
3846 return 0;
3848 return EXISTS_IN_WORKTREE;
3849 } else if (!is_missing_file_error(errno)) {
3850 return error_errno("%s", new_name);
3852 return 0;
3855 static void prepare_symlink_changes(struct apply_state *state, struct patch *patch)
3857 for ( ; patch; patch = patch->next) {
3858 if ((patch->old_name && S_ISLNK(patch->old_mode)) &&
3859 (patch->is_rename || patch->is_delete))
3860 /* the symlink at patch->old_name is removed */
3861 strset_add(&state->removed_symlinks, patch->old_name);
3863 if (patch->new_name && S_ISLNK(patch->new_mode))
3864 /* the symlink at patch->new_name is created or remains */
3865 strset_add(&state->kept_symlinks, patch->new_name);
3869 static int path_is_beyond_symlink_1(struct apply_state *state, struct strbuf *name)
3871 do {
3872 while (--name->len && name->buf[name->len] != '/')
3873 ; /* scan backwards */
3874 if (!name->len)
3875 break;
3876 name->buf[name->len] = '\0';
3877 if (strset_contains(&state->kept_symlinks, name->buf))
3878 return 1;
3879 if (strset_contains(&state->removed_symlinks, name->buf))
3881 * This cannot be "return 0", because we may
3882 * see a new one created at a higher level.
3884 continue;
3886 /* otherwise, check the preimage */
3887 if (state->check_index) {
3888 struct cache_entry *ce;
3890 ce = index_file_exists(state->repo->index, name->buf,
3891 name->len, ignore_case);
3892 if (ce && S_ISLNK(ce->ce_mode))
3893 return 1;
3894 } else {
3895 struct stat st;
3896 if (!lstat(name->buf, &st) && S_ISLNK(st.st_mode))
3897 return 1;
3899 } while (1);
3900 return 0;
3903 static int path_is_beyond_symlink(struct apply_state *state, const char *name_)
3905 int ret;
3906 struct strbuf name = STRBUF_INIT;
3908 assert(*name_ != '\0');
3909 strbuf_addstr(&name, name_);
3910 ret = path_is_beyond_symlink_1(state, &name);
3911 strbuf_release(&name);
3913 return ret;
3916 static int check_unsafe_path(struct patch *patch)
3918 const char *old_name = NULL;
3919 const char *new_name = NULL;
3920 if (patch->is_delete)
3921 old_name = patch->old_name;
3922 else if (!patch->is_new && !patch->is_copy)
3923 old_name = patch->old_name;
3924 if (!patch->is_delete)
3925 new_name = patch->new_name;
3927 if (old_name && !verify_path(old_name, patch->old_mode))
3928 return error(_("invalid path '%s'"), old_name);
3929 if (new_name && !verify_path(new_name, patch->new_mode))
3930 return error(_("invalid path '%s'"), new_name);
3931 return 0;
3935 * Check and apply the patch in-core; leave the result in patch->result
3936 * for the caller to write it out to the final destination.
3938 static int check_patch(struct apply_state *state, struct patch *patch)
3940 struct stat st;
3941 const char *old_name = patch->old_name;
3942 const char *new_name = patch->new_name;
3943 const char *name = old_name ? old_name : new_name;
3944 struct cache_entry *ce = NULL;
3945 struct patch *tpatch;
3946 int ok_if_exists;
3947 int status;
3949 patch->rejected = 1; /* we will drop this after we succeed */
3951 status = check_preimage(state, patch, &ce, &st);
3952 if (status)
3953 return status;
3954 old_name = patch->old_name;
3957 * A type-change diff is always split into a patch to delete
3958 * old, immediately followed by a patch to create new (see
3959 * diff.c::run_diff()); in such a case it is Ok that the entry
3960 * to be deleted by the previous patch is still in the working
3961 * tree and in the index.
3963 * A patch to swap-rename between A and B would first rename A
3964 * to B and then rename B to A. While applying the first one,
3965 * the presence of B should not stop A from getting renamed to
3966 * B; ask to_be_deleted() about the later rename. Removal of
3967 * B and rename from A to B is handled the same way by asking
3968 * was_deleted().
3970 if ((tpatch = in_fn_table(state, new_name)) &&
3971 (was_deleted(tpatch) || to_be_deleted(tpatch)))
3972 ok_if_exists = 1;
3973 else
3974 ok_if_exists = 0;
3976 if (new_name &&
3977 ((0 < patch->is_new) || patch->is_rename || patch->is_copy)) {
3978 int err = check_to_create(state, new_name, ok_if_exists);
3980 if (err && state->threeway) {
3981 patch->direct_to_threeway = 1;
3982 } else switch (err) {
3983 case 0:
3984 break; /* happy */
3985 case EXISTS_IN_INDEX:
3986 return error(_("%s: already exists in index"), new_name);
3987 case EXISTS_IN_INDEX_AS_ITA:
3988 return error(_("%s: does not match index"), new_name);
3989 case EXISTS_IN_WORKTREE:
3990 return error(_("%s: already exists in working directory"),
3991 new_name);
3992 default:
3993 return err;
3996 if (!patch->new_mode) {
3997 if (0 < patch->is_new)
3998 patch->new_mode = S_IFREG | 0644;
3999 else
4000 patch->new_mode = patch->old_mode;
4004 if (new_name && old_name) {
4005 int same = !strcmp(old_name, new_name);
4006 if (!patch->new_mode)
4007 patch->new_mode = patch->old_mode;
4008 if ((patch->old_mode ^ patch->new_mode) & S_IFMT) {
4009 if (same)
4010 return error(_("new mode (%o) of %s does not "
4011 "match old mode (%o)"),
4012 patch->new_mode, new_name,
4013 patch->old_mode);
4014 else
4015 return error(_("new mode (%o) of %s does not "
4016 "match old mode (%o) of %s"),
4017 patch->new_mode, new_name,
4018 patch->old_mode, old_name);
4022 if (!state->unsafe_paths && check_unsafe_path(patch))
4023 return -128;
4026 * An attempt to read from or delete a path that is beyond a
4027 * symbolic link will be prevented by load_patch_target() that
4028 * is called at the beginning of apply_data() so we do not
4029 * have to worry about a patch marked with "is_delete" bit
4030 * here. We however need to make sure that the patch result
4031 * is not deposited to a path that is beyond a symbolic link
4032 * here.
4034 if (!patch->is_delete && path_is_beyond_symlink(state, patch->new_name))
4035 return error(_("affected file '%s' is beyond a symbolic link"),
4036 patch->new_name);
4038 if (apply_data(state, patch, &st, ce) < 0)
4039 return error(_("%s: patch does not apply"), name);
4040 patch->rejected = 0;
4041 return 0;
4044 static int check_patch_list(struct apply_state *state, struct patch *patch)
4046 int err = 0;
4048 prepare_symlink_changes(state, patch);
4049 prepare_fn_table(state, patch);
4050 while (patch) {
4051 int res;
4052 if (state->apply_verbosity > verbosity_normal)
4053 say_patch_name(stderr,
4054 _("Checking patch %s..."), patch);
4055 res = check_patch(state, patch);
4056 if (res == -128)
4057 return -128;
4058 err |= res;
4059 patch = patch->next;
4061 return err;
4064 static int read_apply_cache(struct apply_state *state)
4066 if (state->index_file)
4067 return read_index_from(state->repo->index, state->index_file,
4068 repo_get_git_dir(the_repository));
4069 else
4070 return repo_read_index(state->repo);
4073 /* This function tries to read the object name from the current index */
4074 static int get_current_oid(struct apply_state *state, const char *path,
4075 struct object_id *oid)
4077 int pos;
4079 if (read_apply_cache(state) < 0)
4080 return -1;
4081 pos = index_name_pos(state->repo->index, path, strlen(path));
4082 if (pos < 0)
4083 return -1;
4084 oidcpy(oid, &state->repo->index->cache[pos]->oid);
4085 return 0;
4088 static int preimage_oid_in_gitlink_patch(struct patch *p, struct object_id *oid)
4091 * A usable gitlink patch has only one fragment (hunk) that looks like:
4092 * @@ -1 +1 @@
4093 * -Subproject commit <old sha1>
4094 * +Subproject commit <new sha1>
4095 * or
4096 * @@ -1 +0,0 @@
4097 * -Subproject commit <old sha1>
4098 * for a removal patch.
4100 struct fragment *hunk = p->fragments;
4101 static const char heading[] = "-Subproject commit ";
4102 char *preimage;
4104 if (/* does the patch have only one hunk? */
4105 hunk && !hunk->next &&
4106 /* is its preimage one line? */
4107 hunk->oldpos == 1 && hunk->oldlines == 1 &&
4108 /* does preimage begin with the heading? */
4109 (preimage = memchr(hunk->patch, '\n', hunk->size)) != NULL &&
4110 starts_with(++preimage, heading) &&
4111 /* does it record full SHA-1? */
4112 !get_oid_hex(preimage + sizeof(heading) - 1, oid) &&
4113 preimage[sizeof(heading) + the_hash_algo->hexsz - 1] == '\n' &&
4114 /* does the abbreviated name on the index line agree with it? */
4115 starts_with(preimage + sizeof(heading) - 1, p->old_oid_prefix))
4116 return 0; /* it all looks fine */
4118 /* we may have full object name on the index line */
4119 return get_oid_hex(p->old_oid_prefix, oid);
4122 /* Build an index that contains just the files needed for a 3way merge */
4123 static int build_fake_ancestor(struct apply_state *state, struct patch *list)
4125 struct patch *patch;
4126 struct index_state result = INDEX_STATE_INIT(state->repo);
4127 struct lock_file lock = LOCK_INIT;
4128 int res;
4130 /* Once we start supporting the reverse patch, it may be
4131 * worth showing the new sha1 prefix, but until then...
4133 for (patch = list; patch; patch = patch->next) {
4134 struct object_id oid;
4135 struct cache_entry *ce;
4136 const char *name;
4138 name = patch->old_name ? patch->old_name : patch->new_name;
4139 if (0 < patch->is_new)
4140 continue;
4142 if (S_ISGITLINK(patch->old_mode)) {
4143 if (!preimage_oid_in_gitlink_patch(patch, &oid))
4144 ; /* ok, the textual part looks sane */
4145 else
4146 return error(_("sha1 information is lacking or "
4147 "useless for submodule %s"), name);
4148 } else if (!repo_get_oid_blob(the_repository, patch->old_oid_prefix, &oid)) {
4149 ; /* ok */
4150 } else if (!patch->lines_added && !patch->lines_deleted) {
4151 /* mode-only change: update the current */
4152 if (get_current_oid(state, patch->old_name, &oid))
4153 return error(_("mode change for %s, which is not "
4154 "in current HEAD"), name);
4155 } else
4156 return error(_("sha1 information is lacking or useless "
4157 "(%s)."), name);
4159 ce = make_cache_entry(&result, patch->old_mode, &oid, name, 0, 0);
4160 if (!ce)
4161 return error(_("make_cache_entry failed for path '%s'"),
4162 name);
4163 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) {
4164 discard_cache_entry(ce);
4165 return error(_("could not add %s to temporary index"),
4166 name);
4170 hold_lock_file_for_update(&lock, state->fake_ancestor, LOCK_DIE_ON_ERROR);
4171 res = write_locked_index(&result, &lock, COMMIT_LOCK);
4172 discard_index(&result);
4174 if (res)
4175 return error(_("could not write temporary index to %s"),
4176 state->fake_ancestor);
4178 return 0;
4181 static void stat_patch_list(struct apply_state *state, struct patch *patch)
4183 int files, adds, dels;
4185 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
4186 files++;
4187 adds += patch->lines_added;
4188 dels += patch->lines_deleted;
4189 show_stats(state, patch);
4192 print_stat_summary(stdout, files, adds, dels);
4195 static void numstat_patch_list(struct apply_state *state,
4196 struct patch *patch)
4198 for ( ; patch; patch = patch->next) {
4199 const char *name;
4200 name = patch->new_name ? patch->new_name : patch->old_name;
4201 if (patch->is_binary)
4202 printf("-\t-\t");
4203 else
4204 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
4205 write_name_quoted(name, stdout, state->line_termination);
4209 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
4211 if (mode)
4212 printf(" %s mode %06o %s\n", newdelete, mode, name);
4213 else
4214 printf(" %s %s\n", newdelete, name);
4217 static void show_mode_change(struct patch *p, int show_name)
4219 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
4220 if (show_name)
4221 printf(" mode change %06o => %06o %s\n",
4222 p->old_mode, p->new_mode, p->new_name);
4223 else
4224 printf(" mode change %06o => %06o\n",
4225 p->old_mode, p->new_mode);
4229 static void show_rename_copy(struct patch *p)
4231 const char *renamecopy = p->is_rename ? "rename" : "copy";
4232 const char *old_name, *new_name;
4234 /* Find common prefix */
4235 old_name = p->old_name;
4236 new_name = p->new_name;
4237 while (1) {
4238 const char *slash_old, *slash_new;
4239 slash_old = strchr(old_name, '/');
4240 slash_new = strchr(new_name, '/');
4241 if (!slash_old ||
4242 !slash_new ||
4243 slash_old - old_name != slash_new - new_name ||
4244 memcmp(old_name, new_name, slash_new - new_name))
4245 break;
4246 old_name = slash_old + 1;
4247 new_name = slash_new + 1;
4249 /* p->old_name through old_name is the common prefix, and old_name and
4250 * new_name through the end of names are renames
4252 if (old_name != p->old_name)
4253 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
4254 (int)(old_name - p->old_name), p->old_name,
4255 old_name, new_name, p->score);
4256 else
4257 printf(" %s %s => %s (%d%%)\n", renamecopy,
4258 p->old_name, p->new_name, p->score);
4259 show_mode_change(p, 0);
4262 static void summary_patch_list(struct patch *patch)
4264 struct patch *p;
4266 for (p = patch; p; p = p->next) {
4267 if (p->is_new)
4268 show_file_mode_name("create", p->new_mode, p->new_name);
4269 else if (p->is_delete)
4270 show_file_mode_name("delete", p->old_mode, p->old_name);
4271 else {
4272 if (p->is_rename || p->is_copy)
4273 show_rename_copy(p);
4274 else {
4275 if (p->score) {
4276 printf(" rewrite %s (%d%%)\n",
4277 p->new_name, p->score);
4278 show_mode_change(p, 0);
4280 else
4281 show_mode_change(p, 1);
4287 static void patch_stats(struct apply_state *state, struct patch *patch)
4289 int lines = patch->lines_added + patch->lines_deleted;
4291 if (lines > state->max_change)
4292 state->max_change = lines;
4293 if (patch->old_name) {
4294 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
4295 if (!len)
4296 len = strlen(patch->old_name);
4297 if (len > state->max_len)
4298 state->max_len = len;
4300 if (patch->new_name) {
4301 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
4302 if (!len)
4303 len = strlen(patch->new_name);
4304 if (len > state->max_len)
4305 state->max_len = len;
4309 static int remove_file(struct apply_state *state, struct patch *patch, int rmdir_empty)
4311 if (state->update_index && !state->ita_only) {
4312 if (remove_file_from_index(state->repo->index, patch->old_name) < 0)
4313 return error(_("unable to remove %s from index"), patch->old_name);
4315 if (!state->cached) {
4316 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
4317 remove_path(patch->old_name);
4320 return 0;
4323 static int add_index_file(struct apply_state *state,
4324 const char *path,
4325 unsigned mode,
4326 void *buf,
4327 unsigned long size)
4329 struct stat st;
4330 struct cache_entry *ce;
4331 int namelen = strlen(path);
4333 ce = make_empty_cache_entry(state->repo->index, namelen);
4334 memcpy(ce->name, path, namelen);
4335 ce->ce_mode = create_ce_mode(mode);
4336 ce->ce_flags = create_ce_flags(0);
4337 ce->ce_namelen = namelen;
4338 if (state->ita_only) {
4339 ce->ce_flags |= CE_INTENT_TO_ADD;
4340 set_object_name_for_intent_to_add_entry(ce);
4341 } else if (S_ISGITLINK(mode)) {
4342 const char *s;
4344 if (!skip_prefix(buf, "Subproject commit ", &s) ||
4345 get_oid_hex(s, &ce->oid)) {
4346 discard_cache_entry(ce);
4347 return error(_("corrupt patch for submodule %s"), path);
4349 } else {
4350 if (!state->cached) {
4351 if (lstat(path, &st) < 0) {
4352 discard_cache_entry(ce);
4353 return error_errno(_("unable to stat newly "
4354 "created file '%s'"),
4355 path);
4357 fill_stat_cache_info(state->repo->index, ce, &st);
4359 if (write_object_file(buf, size, OBJ_BLOB, &ce->oid) < 0) {
4360 discard_cache_entry(ce);
4361 return error(_("unable to create backing store "
4362 "for newly created file %s"), path);
4365 if (add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) < 0) {
4366 discard_cache_entry(ce);
4367 return error(_("unable to add cache entry for %s"), path);
4370 return 0;
4374 * Returns:
4375 * -1 if an unrecoverable error happened
4376 * 0 if everything went well
4377 * 1 if a recoverable error happened
4379 static int try_create_file(struct apply_state *state, const char *path,
4380 unsigned int mode, const char *buf,
4381 unsigned long size)
4383 int fd, res;
4384 struct strbuf nbuf = STRBUF_INIT;
4386 if (S_ISGITLINK(mode)) {
4387 struct stat st;
4388 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
4389 return 0;
4390 return !!mkdir(path, 0777);
4393 if (has_symlinks && S_ISLNK(mode))
4394 /* Although buf:size is counted string, it also is NUL
4395 * terminated.
4397 return !!symlink(buf, path);
4399 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
4400 if (fd < 0)
4401 return 1;
4403 if (convert_to_working_tree(state->repo->index, path, buf, size, &nbuf, NULL)) {
4404 size = nbuf.len;
4405 buf = nbuf.buf;
4408 res = write_in_full(fd, buf, size) < 0;
4409 if (res)
4410 error_errno(_("failed to write to '%s'"), path);
4411 strbuf_release(&nbuf);
4413 if (close(fd) < 0 && !res)
4414 return error_errno(_("closing file '%s'"), path);
4416 return res ? -1 : 0;
4420 * We optimistically assume that the directories exist,
4421 * which is true 99% of the time anyway. If they don't,
4422 * we create them and try again.
4424 * Returns:
4425 * -1 on error
4426 * 0 otherwise
4428 static int create_one_file(struct apply_state *state,
4429 char *path,
4430 unsigned mode,
4431 const char *buf,
4432 unsigned long size)
4434 char *newpath = NULL;
4435 int res;
4437 if (state->cached)
4438 return 0;
4441 * We already try to detect whether files are beyond a symlink in our
4442 * up-front checks. But in the case where symlinks are created by any
4443 * of the intermediate hunks it can happen that our up-front checks
4444 * didn't yet see the symlink, but at the point of arriving here there
4445 * in fact is one. We thus repeat the check for symlinks here.
4447 * Note that this does not make the up-front check obsolete as the
4448 * failure mode is different:
4450 * - The up-front checks cause us to abort before we have written
4451 * anything into the working directory. So when we exit this way the
4452 * working directory remains clean.
4454 * - The checks here happen in the middle of the action where we have
4455 * already started to apply the patch. The end result will be a dirty
4456 * working directory.
4458 * Ideally, we should update the up-front checks to catch what would
4459 * happen when we apply the patch before we damage the working tree.
4460 * We have all the information necessary to do so. But for now, as a
4461 * part of embargoed security work, having this check would serve as a
4462 * reasonable first step.
4464 if (path_is_beyond_symlink(state, path))
4465 return error(_("affected file '%s' is beyond a symbolic link"), path);
4467 res = try_create_file(state, path, mode, buf, size);
4468 if (res < 0)
4469 return -1;
4470 if (!res)
4471 return 0;
4473 if (errno == ENOENT) {
4474 if (safe_create_leading_directories_no_share(path))
4475 return 0;
4476 res = try_create_file(state, path, mode, buf, size);
4477 if (res < 0)
4478 return -1;
4479 if (!res)
4480 return 0;
4483 if (errno == EEXIST || errno == EACCES) {
4484 /* We may be trying to create a file where a directory
4485 * used to be.
4487 struct stat st;
4488 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
4489 errno = EEXIST;
4492 if (errno == EEXIST) {
4493 unsigned int nr = getpid();
4495 for (;;) {
4496 newpath = mkpathdup("%s~%u", path, nr);
4497 res = try_create_file(state, newpath, mode, buf, size);
4498 if (res < 0)
4499 goto out;
4500 if (!res) {
4501 if (!rename(newpath, path))
4502 goto out;
4503 unlink_or_warn(newpath);
4504 break;
4506 if (errno != EEXIST)
4507 break;
4508 ++nr;
4509 FREE_AND_NULL(newpath);
4512 res = error_errno(_("unable to write file '%s' mode %o"), path, mode);
4513 out:
4514 free(newpath);
4515 return res;
4518 static int add_conflicted_stages_file(struct apply_state *state,
4519 struct patch *patch)
4521 int stage, namelen;
4522 unsigned mode;
4523 struct cache_entry *ce;
4525 if (!state->update_index)
4526 return 0;
4527 namelen = strlen(patch->new_name);
4528 mode = patch->new_mode ? patch->new_mode : (S_IFREG | 0644);
4530 remove_file_from_index(state->repo->index, patch->new_name);
4531 for (stage = 1; stage < 4; stage++) {
4532 if (is_null_oid(&patch->threeway_stage[stage - 1]))
4533 continue;
4534 ce = make_empty_cache_entry(state->repo->index, namelen);
4535 memcpy(ce->name, patch->new_name, namelen);
4536 ce->ce_mode = create_ce_mode(mode);
4537 ce->ce_flags = create_ce_flags(stage);
4538 ce->ce_namelen = namelen;
4539 oidcpy(&ce->oid, &patch->threeway_stage[stage - 1]);
4540 if (add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) < 0) {
4541 discard_cache_entry(ce);
4542 return error(_("unable to add cache entry for %s"),
4543 patch->new_name);
4547 return 0;
4550 static int create_file(struct apply_state *state, struct patch *patch)
4552 char *path = patch->new_name;
4553 unsigned mode = patch->new_mode;
4554 unsigned long size = patch->resultsize;
4555 char *buf = patch->result;
4557 if (!mode)
4558 mode = S_IFREG | 0644;
4559 if (create_one_file(state, path, mode, buf, size))
4560 return -1;
4562 if (patch->conflicted_threeway)
4563 return add_conflicted_stages_file(state, patch);
4564 else if (state->update_index)
4565 return add_index_file(state, path, mode, buf, size);
4566 return 0;
4569 /* phase zero is to remove, phase one is to create */
4570 static int write_out_one_result(struct apply_state *state,
4571 struct patch *patch,
4572 int phase)
4574 if (patch->is_delete > 0) {
4575 if (phase == 0)
4576 return remove_file(state, patch, 1);
4577 return 0;
4579 if (patch->is_new > 0 || patch->is_copy) {
4580 if (phase == 1)
4581 return create_file(state, patch);
4582 return 0;
4585 * Rename or modification boils down to the same
4586 * thing: remove the old, write the new
4588 if (phase == 0)
4589 return remove_file(state, patch, patch->is_rename);
4590 if (phase == 1)
4591 return create_file(state, patch);
4592 return 0;
4595 static int write_out_one_reject(struct apply_state *state, struct patch *patch)
4597 FILE *rej;
4598 char *namebuf;
4599 struct fragment *frag;
4600 int fd, cnt = 0;
4601 struct strbuf sb = STRBUF_INIT;
4603 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
4604 if (!frag->rejected)
4605 continue;
4606 cnt++;
4609 if (!cnt) {
4610 if (state->apply_verbosity > verbosity_normal)
4611 say_patch_name(stderr,
4612 _("Applied patch %s cleanly."), patch);
4613 return 0;
4616 /* This should not happen, because a removal patch that leaves
4617 * contents are marked "rejected" at the patch level.
4619 if (!patch->new_name)
4620 die(_("internal error"));
4622 /* Say this even without --verbose */
4623 strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",
4624 "Applying patch %%s with %d rejects...",
4625 cnt),
4626 cnt);
4627 if (state->apply_verbosity > verbosity_silent)
4628 say_patch_name(stderr, sb.buf, patch);
4629 strbuf_release(&sb);
4631 namebuf = xstrfmt("%s.rej", patch->new_name);
4633 fd = open(namebuf, O_CREAT | O_EXCL | O_WRONLY, 0666);
4634 if (fd < 0) {
4635 if (errno != EEXIST) {
4636 error_errno(_("cannot open %s"), namebuf);
4637 goto error;
4639 if (unlink(namebuf)) {
4640 error_errno(_("cannot unlink '%s'"), namebuf);
4641 goto error;
4643 fd = open(namebuf, O_CREAT | O_EXCL | O_WRONLY, 0666);
4644 if (fd < 0) {
4645 error_errno(_("cannot open %s"), namebuf);
4646 goto error;
4649 rej = fdopen(fd, "w");
4650 if (!rej) {
4651 error_errno(_("cannot open %s"), namebuf);
4652 close(fd);
4653 goto error;
4656 /* Normal git tools never deal with .rej, so do not pretend
4657 * this is a git patch by saying --git or giving extended
4658 * headers. While at it, maybe please "kompare" that wants
4659 * the trailing TAB and some garbage at the end of line ;-).
4661 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
4662 patch->new_name, patch->new_name);
4663 for (cnt = 1, frag = patch->fragments;
4664 frag;
4665 cnt++, frag = frag->next) {
4666 if (!frag->rejected) {
4667 if (state->apply_verbosity > verbosity_silent)
4668 fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);
4669 continue;
4671 if (state->apply_verbosity > verbosity_silent)
4672 fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);
4673 fprintf(rej, "%.*s", frag->size, frag->patch);
4674 if (frag->patch[frag->size-1] != '\n')
4675 fputc('\n', rej);
4677 fclose(rej);
4678 error:
4679 free(namebuf);
4680 return -1;
4684 * Returns:
4685 * -1 if an error happened
4686 * 0 if the patch applied cleanly
4687 * 1 if the patch did not apply cleanly
4689 static int write_out_results(struct apply_state *state, struct patch *list)
4691 int phase;
4692 int errs = 0;
4693 struct patch *l;
4694 struct string_list cpath = STRING_LIST_INIT_DUP;
4696 for (phase = 0; phase < 2; phase++) {
4697 l = list;
4698 while (l) {
4699 if (l->rejected)
4700 errs = 1;
4701 else {
4702 if (write_out_one_result(state, l, phase)) {
4703 string_list_clear(&cpath, 0);
4704 return -1;
4706 if (phase == 1) {
4707 if (write_out_one_reject(state, l))
4708 errs = 1;
4709 if (l->conflicted_threeway) {
4710 string_list_append(&cpath, l->new_name);
4711 errs = 1;
4715 l = l->next;
4719 if (cpath.nr) {
4720 struct string_list_item *item;
4722 string_list_sort(&cpath);
4723 if (state->apply_verbosity > verbosity_silent) {
4724 for_each_string_list_item(item, &cpath)
4725 fprintf(stderr, "U %s\n", item->string);
4727 string_list_clear(&cpath, 0);
4730 * rerere relies on the partially merged result being in the working
4731 * tree with conflict markers, but that isn't written with --cached.
4733 if (!state->cached)
4734 repo_rerere(state->repo, 0);
4737 return errs;
4741 * Try to apply a patch.
4743 * Returns:
4744 * -128 if a bad error happened (like patch unreadable)
4745 * -1 if patch did not apply and user cannot deal with it
4746 * 0 if the patch applied
4747 * 1 if the patch did not apply but user might fix it
4749 static int apply_patch(struct apply_state *state,
4750 int fd,
4751 const char *filename,
4752 int options)
4754 size_t offset;
4755 struct strbuf buf = STRBUF_INIT; /* owns the patch text */
4756 struct patch *list = NULL, **listp = &list;
4757 int skipped_patch = 0;
4758 int res = 0;
4759 int flush_attributes = 0;
4761 state->patch_input_file = filename;
4762 if (read_patch_file(&buf, fd) < 0)
4763 return -128;
4764 offset = 0;
4765 while (offset < buf.len) {
4766 struct patch *patch;
4767 int nr;
4769 CALLOC_ARRAY(patch, 1);
4770 patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF);
4771 patch->recount = !!(options & APPLY_OPT_RECOUNT);
4772 nr = parse_chunk(state, buf.buf + offset, buf.len - offset, patch);
4773 if (nr < 0) {
4774 free_patch(patch);
4775 if (nr == -128) {
4776 res = -128;
4777 goto end;
4779 break;
4781 if (state->apply_in_reverse)
4782 reverse_patches(patch);
4783 if (use_patch(state, patch)) {
4784 patch_stats(state, patch);
4785 if (!list || !state->apply_in_reverse) {
4786 *listp = patch;
4787 listp = &patch->next;
4788 } else {
4789 patch->next = list;
4790 list = patch;
4793 if ((patch->new_name &&
4794 ends_with_path_components(patch->new_name,
4795 GITATTRIBUTES_FILE)) ||
4796 (patch->old_name &&
4797 ends_with_path_components(patch->old_name,
4798 GITATTRIBUTES_FILE)))
4799 flush_attributes = 1;
4801 else {
4802 if (state->apply_verbosity > verbosity_normal)
4803 say_patch_name(stderr, _("Skipped patch '%s'."), patch);
4804 free_patch(patch);
4805 skipped_patch++;
4807 offset += nr;
4810 if (!list && !skipped_patch) {
4811 if (!state->allow_empty) {
4812 error(_("No valid patches in input (allow with \"--allow-empty\")"));
4813 res = -128;
4815 goto end;
4818 if (state->whitespace_error && (state->ws_error_action == die_on_ws_error))
4819 state->apply = 0;
4821 state->update_index = (state->check_index || state->ita_only) && state->apply;
4822 if (state->update_index && !is_lock_file_locked(&state->lock_file)) {
4823 if (state->index_file)
4824 hold_lock_file_for_update(&state->lock_file,
4825 state->index_file,
4826 LOCK_DIE_ON_ERROR);
4827 else
4828 repo_hold_locked_index(state->repo, &state->lock_file,
4829 LOCK_DIE_ON_ERROR);
4832 if (state->check_index && read_apply_cache(state) < 0) {
4833 error(_("unable to read index file"));
4834 res = -128;
4835 goto end;
4838 if (state->check || state->apply) {
4839 int r = check_patch_list(state, list);
4840 if (r == -128) {
4841 res = -128;
4842 goto end;
4844 if (r < 0 && !state->apply_with_reject) {
4845 res = -1;
4846 goto end;
4850 if (state->apply) {
4851 int write_res = write_out_results(state, list);
4852 if (write_res < 0) {
4853 res = -128;
4854 goto end;
4856 if (write_res > 0) {
4857 /* with --3way, we still need to write the index out */
4858 res = state->apply_with_reject ? -1 : 1;
4859 goto end;
4863 if (state->fake_ancestor &&
4864 build_fake_ancestor(state, list)) {
4865 res = -128;
4866 goto end;
4869 if (state->diffstat && state->apply_verbosity > verbosity_silent)
4870 stat_patch_list(state, list);
4872 if (state->numstat && state->apply_verbosity > verbosity_silent)
4873 numstat_patch_list(state, list);
4875 if (state->summary && state->apply_verbosity > verbosity_silent)
4876 summary_patch_list(list);
4878 if (flush_attributes)
4879 reset_parsed_attributes();
4880 end:
4881 free_patch_list(list);
4882 strbuf_release(&buf);
4883 string_list_clear(&state->fn_table, 0);
4884 return res;
4887 static int apply_option_parse_exclude(const struct option *opt,
4888 const char *arg, int unset)
4890 struct apply_state *state = opt->value;
4892 BUG_ON_OPT_NEG(unset);
4894 add_name_limit(state, arg, 1);
4895 return 0;
4898 static int apply_option_parse_include(const struct option *opt,
4899 const char *arg, int unset)
4901 struct apply_state *state = opt->value;
4903 BUG_ON_OPT_NEG(unset);
4905 add_name_limit(state, arg, 0);
4906 state->has_include = 1;
4907 return 0;
4910 static int apply_option_parse_p(const struct option *opt,
4911 const char *arg,
4912 int unset)
4914 struct apply_state *state = opt->value;
4916 BUG_ON_OPT_NEG(unset);
4918 state->p_value = atoi(arg);
4919 state->p_value_known = 1;
4920 return 0;
4923 static int apply_option_parse_space_change(const struct option *opt,
4924 const char *arg, int unset)
4926 struct apply_state *state = opt->value;
4928 BUG_ON_OPT_ARG(arg);
4930 if (unset)
4931 state->ws_ignore_action = ignore_ws_none;
4932 else
4933 state->ws_ignore_action = ignore_ws_change;
4934 return 0;
4937 static int apply_option_parse_whitespace(const struct option *opt,
4938 const char *arg, int unset)
4940 struct apply_state *state = opt->value;
4942 BUG_ON_OPT_NEG(unset);
4944 state->whitespace_option = arg;
4945 if (parse_whitespace_option(state, arg))
4946 return -1;
4947 return 0;
4950 static int apply_option_parse_directory(const struct option *opt,
4951 const char *arg, int unset)
4953 struct apply_state *state = opt->value;
4955 BUG_ON_OPT_NEG(unset);
4957 strbuf_reset(&state->root);
4958 strbuf_addstr(&state->root, arg);
4959 strbuf_complete(&state->root, '/');
4960 return 0;
4963 int apply_all_patches(struct apply_state *state,
4964 int argc,
4965 const char **argv,
4966 int options)
4968 int i;
4969 int res;
4970 int errs = 0;
4971 int read_stdin = 1;
4973 for (i = 0; i < argc; i++) {
4974 const char *arg = argv[i];
4975 char *to_free = NULL;
4976 int fd;
4978 if (!strcmp(arg, "-")) {
4979 res = apply_patch(state, 0, "<stdin>", options);
4980 if (res < 0)
4981 goto end;
4982 errs |= res;
4983 read_stdin = 0;
4984 continue;
4985 } else
4986 arg = to_free = prefix_filename(state->prefix, arg);
4988 fd = open(arg, O_RDONLY);
4989 if (fd < 0) {
4990 error(_("can't open patch '%s': %s"), arg, strerror(errno));
4991 res = -128;
4992 free(to_free);
4993 goto end;
4995 read_stdin = 0;
4996 set_default_whitespace_mode(state);
4997 res = apply_patch(state, fd, arg, options);
4998 close(fd);
4999 free(to_free);
5000 if (res < 0)
5001 goto end;
5002 errs |= res;
5004 set_default_whitespace_mode(state);
5005 if (read_stdin) {
5006 res = apply_patch(state, 0, "<stdin>", options);
5007 if (res < 0)
5008 goto end;
5009 errs |= res;
5012 if (state->whitespace_error) {
5013 if (state->squelch_whitespace_errors &&
5014 state->squelch_whitespace_errors < state->whitespace_error) {
5015 int squelched =
5016 state->whitespace_error - state->squelch_whitespace_errors;
5017 warning(Q_("squelched %d whitespace error",
5018 "squelched %d whitespace errors",
5019 squelched),
5020 squelched);
5022 if (state->ws_error_action == die_on_ws_error) {
5023 error(Q_("%d line adds whitespace errors.",
5024 "%d lines add whitespace errors.",
5025 state->whitespace_error),
5026 state->whitespace_error);
5027 res = -128;
5028 goto end;
5030 if (state->applied_after_fixing_ws && state->apply)
5031 warning(Q_("%d line applied after"
5032 " fixing whitespace errors.",
5033 "%d lines applied after"
5034 " fixing whitespace errors.",
5035 state->applied_after_fixing_ws),
5036 state->applied_after_fixing_ws);
5037 else if (state->whitespace_error)
5038 warning(Q_("%d line adds whitespace errors.",
5039 "%d lines add whitespace errors.",
5040 state->whitespace_error),
5041 state->whitespace_error);
5044 if (state->update_index) {
5045 res = write_locked_index(state->repo->index, &state->lock_file, COMMIT_LOCK);
5046 if (res) {
5047 error(_("Unable to write new index file"));
5048 res = -128;
5049 goto end;
5053 res = !!errs;
5055 end:
5056 rollback_lock_file(&state->lock_file);
5058 if (state->apply_verbosity <= verbosity_silent) {
5059 set_error_routine(state->saved_error_routine);
5060 set_warn_routine(state->saved_warn_routine);
5063 if (res > -1)
5064 return res;
5065 return (res == -1 ? 1 : 128);
5068 int apply_parse_options(int argc, const char **argv,
5069 struct apply_state *state,
5070 int *force_apply, int *options,
5071 const char * const *apply_usage)
5073 struct option builtin_apply_options[] = {
5074 OPT_CALLBACK_F(0, "exclude", state, N_("path"),
5075 N_("don't apply changes matching the given path"),
5076 PARSE_OPT_NONEG, apply_option_parse_exclude),
5077 OPT_CALLBACK_F(0, "include", state, N_("path"),
5078 N_("apply changes matching the given path"),
5079 PARSE_OPT_NONEG, apply_option_parse_include),
5080 OPT_CALLBACK('p', NULL, state, N_("num"),
5081 N_("remove <num> leading slashes from traditional diff paths"),
5082 apply_option_parse_p),
5083 OPT_BOOL(0, "no-add", &state->no_add,
5084 N_("ignore additions made by the patch")),
5085 OPT_BOOL(0, "stat", &state->diffstat,
5086 N_("instead of applying the patch, output diffstat for the input")),
5087 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
5088 OPT_NOOP_NOARG(0, "binary"),
5089 OPT_BOOL(0, "numstat", &state->numstat,
5090 N_("show number of added and deleted lines in decimal notation")),
5091 OPT_BOOL(0, "summary", &state->summary,
5092 N_("instead of applying the patch, output a summary for the input")),
5093 OPT_BOOL(0, "check", &state->check,
5094 N_("instead of applying the patch, see if the patch is applicable")),
5095 OPT_BOOL(0, "index", &state->check_index,
5096 N_("make sure the patch is applicable to the current index")),
5097 OPT_BOOL('N', "intent-to-add", &state->ita_only,
5098 N_("mark new files with `git add --intent-to-add`")),
5099 OPT_BOOL(0, "cached", &state->cached,
5100 N_("apply a patch without touching the working tree")),
5101 OPT_BOOL_F(0, "unsafe-paths", &state->unsafe_paths,
5102 N_("accept a patch that touches outside the working area"),
5103 PARSE_OPT_NOCOMPLETE),
5104 OPT_BOOL(0, "apply", force_apply,
5105 N_("also apply the patch (use with --stat/--summary/--check)")),
5106 OPT_BOOL('3', "3way", &state->threeway,
5107 N_( "attempt three-way merge, fall back on normal patch if that fails")),
5108 OPT_SET_INT_F(0, "ours", &state->merge_variant,
5109 N_("for conflicts, use our version"),
5110 XDL_MERGE_FAVOR_OURS, PARSE_OPT_NONEG),
5111 OPT_SET_INT_F(0, "theirs", &state->merge_variant,
5112 N_("for conflicts, use their version"),
5113 XDL_MERGE_FAVOR_THEIRS, PARSE_OPT_NONEG),
5114 OPT_SET_INT_F(0, "union", &state->merge_variant,
5115 N_("for conflicts, use a union version"),
5116 XDL_MERGE_FAVOR_UNION, PARSE_OPT_NONEG),
5117 OPT_FILENAME(0, "build-fake-ancestor", &state->fake_ancestor,
5118 N_("build a temporary index based on embedded index information")),
5119 /* Think twice before adding "--nul" synonym to this */
5120 OPT_SET_INT('z', NULL, &state->line_termination,
5121 N_("paths are separated with NUL character"), '\0'),
5122 OPT_INTEGER('C', NULL, &state->p_context,
5123 N_("ensure at least <n> lines of context match")),
5124 OPT_CALLBACK(0, "whitespace", state, N_("action"),
5125 N_("detect new or modified lines that have whitespace errors"),
5126 apply_option_parse_whitespace),
5127 OPT_CALLBACK_F(0, "ignore-space-change", state, NULL,
5128 N_("ignore changes in whitespace when finding context"),
5129 PARSE_OPT_NOARG, apply_option_parse_space_change),
5130 OPT_CALLBACK_F(0, "ignore-whitespace", state, NULL,
5131 N_("ignore changes in whitespace when finding context"),
5132 PARSE_OPT_NOARG, apply_option_parse_space_change),
5133 OPT_BOOL('R', "reverse", &state->apply_in_reverse,
5134 N_("apply the patch in reverse")),
5135 OPT_BOOL(0, "unidiff-zero", &state->unidiff_zero,
5136 N_("don't expect at least one line of context")),
5137 OPT_BOOL(0, "reject", &state->apply_with_reject,
5138 N_("leave the rejected hunks in corresponding *.rej files")),
5139 OPT_BOOL(0, "allow-overlap", &state->allow_overlap,
5140 N_("allow overlapping hunks")),
5141 OPT__VERBOSITY(&state->apply_verbosity),
5142 OPT_BIT(0, "inaccurate-eof", options,
5143 N_("tolerate incorrectly detected missing new-line at the end of file"),
5144 APPLY_OPT_INACCURATE_EOF),
5145 OPT_BIT(0, "recount", options,
5146 N_("do not trust the line counts in the hunk headers"),
5147 APPLY_OPT_RECOUNT),
5148 OPT_CALLBACK(0, "directory", state, N_("root"),
5149 N_("prepend <root> to all filenames"),
5150 apply_option_parse_directory),
5151 OPT_BOOL(0, "allow-empty", &state->allow_empty,
5152 N_("don't return error for empty patches")),
5153 OPT_END()
5156 argc = parse_options(argc, argv, state->prefix, builtin_apply_options, apply_usage, 0);
5158 if (state->merge_variant && !state->threeway)
5159 die(_("--ours, --theirs, and --union require --3way"));
5161 return argc;