hash.h: move some oid-related declarations from cache.h
[git/debian.git] / apply.c
blob7f12ebf04c5d6dd74cba80c02a9ff7bd1ddcb9f5
1 /*
2 * apply.c
4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
8 */
10 #include "cache.h"
11 #include "alloc.h"
12 #include "config.h"
13 #include "object-store.h"
14 #include "blob.h"
15 #include "delta.h"
16 #include "diff.h"
17 #include "dir.h"
18 #include "xdiff-interface.h"
19 #include "ll-merge.h"
20 #include "lockfile.h"
21 #include "parse-options.h"
22 #include "quote.h"
23 #include "rerere.h"
24 #include "apply.h"
25 #include "entry.h"
27 struct gitdiff_data {
28 struct strbuf *root;
29 int linenr;
30 int p_value;
33 static void git_apply_config(void)
35 git_config_get_string("apply.whitespace", &apply_default_whitespace);
36 git_config_get_string("apply.ignorewhitespace", &apply_default_ignorewhitespace);
37 git_config(git_xmerge_config, NULL);
40 static int parse_whitespace_option(struct apply_state *state, const char *option)
42 if (!option) {
43 state->ws_error_action = warn_on_ws_error;
44 return 0;
46 if (!strcmp(option, "warn")) {
47 state->ws_error_action = warn_on_ws_error;
48 return 0;
50 if (!strcmp(option, "nowarn")) {
51 state->ws_error_action = nowarn_ws_error;
52 return 0;
54 if (!strcmp(option, "error")) {
55 state->ws_error_action = die_on_ws_error;
56 return 0;
58 if (!strcmp(option, "error-all")) {
59 state->ws_error_action = die_on_ws_error;
60 state->squelch_whitespace_errors = 0;
61 return 0;
63 if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
64 state->ws_error_action = correct_ws_error;
65 return 0;
68 * Please update $__git_whitespacelist in git-completion.bash
69 * when you add new options.
71 return error(_("unrecognized whitespace option '%s'"), option);
74 static int parse_ignorewhitespace_option(struct apply_state *state,
75 const char *option)
77 if (!option || !strcmp(option, "no") ||
78 !strcmp(option, "false") || !strcmp(option, "never") ||
79 !strcmp(option, "none")) {
80 state->ws_ignore_action = ignore_ws_none;
81 return 0;
83 if (!strcmp(option, "change")) {
84 state->ws_ignore_action = ignore_ws_change;
85 return 0;
87 return error(_("unrecognized whitespace ignore option '%s'"), option);
90 int init_apply_state(struct apply_state *state,
91 struct repository *repo,
92 const char *prefix)
94 memset(state, 0, sizeof(*state));
95 state->prefix = prefix;
96 state->repo = repo;
97 state->apply = 1;
98 state->line_termination = '\n';
99 state->p_value = 1;
100 state->p_context = UINT_MAX;
101 state->squelch_whitespace_errors = 5;
102 state->ws_error_action = warn_on_ws_error;
103 state->ws_ignore_action = ignore_ws_none;
104 state->linenr = 1;
105 string_list_init_nodup(&state->fn_table);
106 string_list_init_nodup(&state->limit_by_name);
107 strset_init(&state->removed_symlinks);
108 strset_init(&state->kept_symlinks);
109 strbuf_init(&state->root, 0);
111 git_apply_config();
112 if (apply_default_whitespace && parse_whitespace_option(state, apply_default_whitespace))
113 return -1;
114 if (apply_default_ignorewhitespace && parse_ignorewhitespace_option(state, apply_default_ignorewhitespace))
115 return -1;
116 return 0;
119 void clear_apply_state(struct apply_state *state)
121 string_list_clear(&state->limit_by_name, 0);
122 strset_clear(&state->removed_symlinks);
123 strset_clear(&state->kept_symlinks);
124 strbuf_release(&state->root);
126 /* &state->fn_table is cleared at the end of apply_patch() */
129 static void mute_routine(const char *msg UNUSED, va_list params UNUSED)
131 /* do nothing */
134 int check_apply_state(struct apply_state *state, int force_apply)
136 int is_not_gitdir = !startup_info->have_repository;
138 if (state->apply_with_reject && state->threeway)
139 return error(_("options '%s' and '%s' cannot be used together"), "--reject", "--3way");
140 if (state->threeway) {
141 if (is_not_gitdir)
142 return error(_("'%s' outside a repository"), "--3way");
143 state->check_index = 1;
145 if (state->apply_with_reject) {
146 state->apply = 1;
147 if (state->apply_verbosity == verbosity_normal)
148 state->apply_verbosity = verbosity_verbose;
150 if (!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor))
151 state->apply = 0;
152 if (state->check_index && is_not_gitdir)
153 return error(_("'%s' outside a repository"), "--index");
154 if (state->cached) {
155 if (is_not_gitdir)
156 return error(_("'%s' outside a repository"), "--cached");
157 state->check_index = 1;
159 if (state->ita_only && (state->check_index || is_not_gitdir))
160 state->ita_only = 0;
161 if (state->check_index)
162 state->unsafe_paths = 0;
164 if (state->apply_verbosity <= verbosity_silent) {
165 state->saved_error_routine = get_error_routine();
166 state->saved_warn_routine = get_warn_routine();
167 set_error_routine(mute_routine);
168 set_warn_routine(mute_routine);
171 return 0;
174 static void set_default_whitespace_mode(struct apply_state *state)
176 if (!state->whitespace_option && !apply_default_whitespace)
177 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error);
181 * This represents one "hunk" from a patch, starting with
182 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
183 * patch text is pointed at by patch, and its byte length
184 * is stored in size. leading and trailing are the number
185 * of context lines.
187 struct fragment {
188 unsigned long leading, trailing;
189 unsigned long oldpos, oldlines;
190 unsigned long newpos, newlines;
192 * 'patch' is usually borrowed from buf in apply_patch(),
193 * but some codepaths store an allocated buffer.
195 const char *patch;
196 unsigned free_patch:1,
197 rejected:1;
198 int size;
199 int linenr;
200 struct fragment *next;
204 * When dealing with a binary patch, we reuse "leading" field
205 * to store the type of the binary hunk, either deflated "delta"
206 * or deflated "literal".
208 #define binary_patch_method leading
209 #define BINARY_DELTA_DEFLATED 1
210 #define BINARY_LITERAL_DEFLATED 2
212 static void free_fragment_list(struct fragment *list)
214 while (list) {
215 struct fragment *next = list->next;
216 if (list->free_patch)
217 free((char *)list->patch);
218 free(list);
219 list = next;
223 void release_patch(struct patch *patch)
225 free_fragment_list(patch->fragments);
226 free(patch->def_name);
227 free(patch->old_name);
228 free(patch->new_name);
229 free(patch->result);
232 static void free_patch(struct patch *patch)
234 release_patch(patch);
235 free(patch);
238 static void free_patch_list(struct patch *list)
240 while (list) {
241 struct patch *next = list->next;
242 free_patch(list);
243 list = next;
248 * A line in a file, len-bytes long (includes the terminating LF,
249 * except for an incomplete line at the end if the file ends with
250 * one), and its contents hashes to 'hash'.
252 struct line {
253 size_t len;
254 unsigned hash : 24;
255 unsigned flag : 8;
256 #define LINE_COMMON 1
257 #define LINE_PATCHED 2
261 * This represents a "file", which is an array of "lines".
263 struct image {
264 char *buf;
265 size_t len;
266 size_t nr;
267 size_t alloc;
268 struct line *line_allocated;
269 struct line *line;
272 static uint32_t hash_line(const char *cp, size_t len)
274 size_t i;
275 uint32_t h;
276 for (i = 0, h = 0; i < len; i++) {
277 if (!isspace(cp[i])) {
278 h = h * 3 + (cp[i] & 0xff);
281 return h;
285 * Compare lines s1 of length n1 and s2 of length n2, ignoring
286 * whitespace difference. Returns 1 if they match, 0 otherwise
288 static int fuzzy_matchlines(const char *s1, size_t n1,
289 const char *s2, size_t n2)
291 const char *end1 = s1 + n1;
292 const char *end2 = s2 + n2;
294 /* ignore line endings */
295 while (s1 < end1 && (end1[-1] == '\r' || end1[-1] == '\n'))
296 end1--;
297 while (s2 < end2 && (end2[-1] == '\r' || end2[-1] == '\n'))
298 end2--;
300 while (s1 < end1 && s2 < end2) {
301 if (isspace(*s1)) {
303 * Skip whitespace. We check on both buffers
304 * because we don't want "a b" to match "ab".
306 if (!isspace(*s2))
307 return 0;
308 while (s1 < end1 && isspace(*s1))
309 s1++;
310 while (s2 < end2 && isspace(*s2))
311 s2++;
312 } else if (*s1++ != *s2++)
313 return 0;
316 /* If we reached the end on one side only, lines don't match. */
317 return s1 == end1 && s2 == end2;
320 static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
322 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
323 img->line_allocated[img->nr].len = len;
324 img->line_allocated[img->nr].hash = hash_line(bol, len);
325 img->line_allocated[img->nr].flag = flag;
326 img->nr++;
330 * "buf" has the file contents to be patched (read from various sources).
331 * attach it to "image" and add line-based index to it.
332 * "image" now owns the "buf".
334 static void prepare_image(struct image *image, char *buf, size_t len,
335 int prepare_linetable)
337 const char *cp, *ep;
339 memset(image, 0, sizeof(*image));
340 image->buf = buf;
341 image->len = len;
343 if (!prepare_linetable)
344 return;
346 ep = image->buf + image->len;
347 cp = image->buf;
348 while (cp < ep) {
349 const char *next;
350 for (next = cp; next < ep && *next != '\n'; next++)
352 if (next < ep)
353 next++;
354 add_line_info(image, cp, next - cp, 0);
355 cp = next;
357 image->line = image->line_allocated;
360 static void clear_image(struct image *image)
362 free(image->buf);
363 free(image->line_allocated);
364 memset(image, 0, sizeof(*image));
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 || sb->len >= MAX_APPLY_SIZE)
403 return error_errno("git apply: failed to read");
406 * Make sure that we have some slop in the buffer
407 * so that we can do speculative "memcmp" etc, and
408 * see to it that it is NUL-filled.
410 strbuf_grow(sb, SLOP);
411 memset(sb->buf + sb->len, 0, SLOP);
412 return 0;
415 static unsigned long linelen(const char *buffer, unsigned long size)
417 unsigned long len = 0;
418 while (size--) {
419 len++;
420 if (*buffer++ == '\n')
421 break;
423 return len;
426 static int is_dev_null(const char *str)
428 return skip_prefix(str, "/dev/null", &str) && isspace(*str);
431 #define TERM_SPACE 1
432 #define TERM_TAB 2
434 static int name_terminate(int c, int terminate)
436 if (c == ' ' && !(terminate & TERM_SPACE))
437 return 0;
438 if (c == '\t' && !(terminate & TERM_TAB))
439 return 0;
441 return 1;
444 /* remove double slashes to make --index work with such filenames */
445 static char *squash_slash(char *name)
447 int i = 0, j = 0;
449 if (!name)
450 return NULL;
452 while (name[i]) {
453 if ((name[j++] = name[i++]) == '/')
454 while (name[i] == '/')
455 i++;
457 name[j] = '\0';
458 return name;
461 static char *find_name_gnu(struct strbuf *root,
462 const char *line,
463 int p_value)
465 struct strbuf name = STRBUF_INIT;
466 char *cp;
469 * Proposed "new-style" GNU patch/diff format; see
470 * https://lore.kernel.org/git/7vll0wvb2a.fsf@assigned-by-dhcp.cox.net/
472 if (unquote_c_style(&name, line, NULL)) {
473 strbuf_release(&name);
474 return NULL;
477 for (cp = name.buf; p_value; p_value--) {
478 cp = strchr(cp, '/');
479 if (!cp) {
480 strbuf_release(&name);
481 return NULL;
483 cp++;
486 strbuf_remove(&name, 0, cp - name.buf);
487 if (root->len)
488 strbuf_insert(&name, 0, root->buf, root->len);
489 return squash_slash(strbuf_detach(&name, NULL));
492 static size_t sane_tz_len(const char *line, size_t len)
494 const char *tz, *p;
496 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
497 return 0;
498 tz = line + len - strlen(" +0500");
500 if (tz[1] != '+' && tz[1] != '-')
501 return 0;
503 for (p = tz + 2; p != line + len; p++)
504 if (!isdigit(*p))
505 return 0;
507 return line + len - tz;
510 static size_t tz_with_colon_len(const char *line, size_t len)
512 const char *tz, *p;
514 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
515 return 0;
516 tz = line + len - strlen(" +08:00");
518 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
519 return 0;
520 p = tz + 2;
521 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
522 !isdigit(*p++) || !isdigit(*p++))
523 return 0;
525 return line + len - tz;
528 static size_t date_len(const char *line, size_t len)
530 const char *date, *p;
532 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
533 return 0;
534 p = date = line + len - strlen("72-02-05");
536 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
537 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
538 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */
539 return 0;
541 if (date - line >= strlen("19") &&
542 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */
543 date -= strlen("19");
545 return line + len - date;
548 static size_t short_time_len(const char *line, size_t len)
550 const char *time, *p;
552 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
553 return 0;
554 p = time = line + len - strlen(" 07:01:32");
556 /* Permit 1-digit hours? */
557 if (*p++ != ' ' ||
558 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
559 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
560 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */
561 return 0;
563 return line + len - time;
566 static size_t fractional_time_len(const char *line, size_t len)
568 const char *p;
569 size_t n;
571 /* Expected format: 19:41:17.620000023 */
572 if (!len || !isdigit(line[len - 1]))
573 return 0;
574 p = line + len - 1;
576 /* Fractional seconds. */
577 while (p > line && isdigit(*p))
578 p--;
579 if (*p != '.')
580 return 0;
582 /* Hours, minutes, and whole seconds. */
583 n = short_time_len(line, p - line);
584 if (!n)
585 return 0;
587 return line + len - p + n;
590 static size_t trailing_spaces_len(const char *line, size_t len)
592 const char *p;
594 /* Expected format: ' ' x (1 or more) */
595 if (!len || line[len - 1] != ' ')
596 return 0;
598 p = line + len;
599 while (p != line) {
600 p--;
601 if (*p != ' ')
602 return line + len - (p + 1);
605 /* All spaces! */
606 return len;
609 static size_t diff_timestamp_len(const char *line, size_t len)
611 const char *end = line + len;
612 size_t n;
615 * Posix: 2010-07-05 19:41:17
616 * GNU: 2010-07-05 19:41:17.620000023 -0500
619 if (!isdigit(end[-1]))
620 return 0;
622 n = sane_tz_len(line, end - line);
623 if (!n)
624 n = tz_with_colon_len(line, end - line);
625 end -= n;
627 n = short_time_len(line, end - line);
628 if (!n)
629 n = fractional_time_len(line, end - line);
630 end -= n;
632 n = date_len(line, end - line);
633 if (!n) /* No date. Too bad. */
634 return 0;
635 end -= n;
637 if (end == line) /* No space before date. */
638 return 0;
639 if (end[-1] == '\t') { /* Success! */
640 end--;
641 return line + len - end;
643 if (end[-1] != ' ') /* No space before date. */
644 return 0;
646 /* Whitespace damage. */
647 end -= trailing_spaces_len(line, end - line);
648 return line + len - end;
651 static char *find_name_common(struct strbuf *root,
652 const char *line,
653 const char *def,
654 int p_value,
655 const char *end,
656 int terminate)
658 int len;
659 const char *start = NULL;
661 if (p_value == 0)
662 start = line;
663 while (line != end) {
664 char c = *line;
666 if (!end && isspace(c)) {
667 if (c == '\n')
668 break;
669 if (name_terminate(c, terminate))
670 break;
672 line++;
673 if (c == '/' && !--p_value)
674 start = line;
676 if (!start)
677 return squash_slash(xstrdup_or_null(def));
678 len = line - start;
679 if (!len)
680 return squash_slash(xstrdup_or_null(def));
683 * Generally we prefer the shorter name, especially
684 * if the other one is just a variation of that with
685 * something else tacked on to the end (ie "file.orig"
686 * or "file~").
688 if (def) {
689 int deflen = strlen(def);
690 if (deflen < len && !strncmp(start, def, deflen))
691 return squash_slash(xstrdup(def));
694 if (root->len) {
695 char *ret = xstrfmt("%s%.*s", root->buf, len, start);
696 return squash_slash(ret);
699 return squash_slash(xmemdupz(start, len));
702 static char *find_name(struct strbuf *root,
703 const char *line,
704 char *def,
705 int p_value,
706 int terminate)
708 if (*line == '"') {
709 char *name = find_name_gnu(root, line, p_value);
710 if (name)
711 return name;
714 return find_name_common(root, line, def, p_value, NULL, terminate);
717 static char *find_name_traditional(struct strbuf *root,
718 const char *line,
719 char *def,
720 int p_value)
722 size_t len;
723 size_t date_len;
725 if (*line == '"') {
726 char *name = find_name_gnu(root, line, p_value);
727 if (name)
728 return name;
731 len = strchrnul(line, '\n') - line;
732 date_len = diff_timestamp_len(line, len);
733 if (!date_len)
734 return find_name_common(root, line, def, p_value, NULL, TERM_TAB);
735 len -= date_len;
737 return find_name_common(root, line, def, p_value, line + len, 0);
741 * Given the string after "--- " or "+++ ", guess the appropriate
742 * p_value for the given patch.
744 static int guess_p_value(struct apply_state *state, const char *nameline)
746 char *name, *cp;
747 int val = -1;
749 if (is_dev_null(nameline))
750 return -1;
751 name = find_name_traditional(&state->root, nameline, NULL, 0);
752 if (!name)
753 return -1;
754 cp = strchr(name, '/');
755 if (!cp)
756 val = 0;
757 else if (state->prefix) {
759 * Does it begin with "a/$our-prefix" and such? Then this is
760 * very likely to apply to our directory.
762 if (starts_with(name, state->prefix))
763 val = count_slashes(state->prefix);
764 else {
765 cp++;
766 if (starts_with(cp, state->prefix))
767 val = count_slashes(state->prefix) + 1;
770 free(name);
771 return val;
775 * Does the ---/+++ line have the POSIX timestamp after the last HT?
776 * GNU diff puts epoch there to signal a creation/deletion event. Is
777 * this such a timestamp?
779 static int has_epoch_timestamp(const char *nameline)
782 * We are only interested in epoch timestamp; any non-zero
783 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
784 * For the same reason, the date must be either 1969-12-31 or
785 * 1970-01-01, and the seconds part must be "00".
787 const char stamp_regexp[] =
788 "^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?"
790 "([-+][0-2][0-9]:?[0-5][0-9])\n";
791 const char *timestamp = NULL, *cp, *colon;
792 static regex_t *stamp;
793 regmatch_t m[10];
794 int zoneoffset, epoch_hour, hour, minute;
795 int status;
797 for (cp = nameline; *cp != '\n'; cp++) {
798 if (*cp == '\t')
799 timestamp = cp + 1;
801 if (!timestamp)
802 return 0;
805 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
806 * (west of GMT) or 1970-01-01 (east of GMT)
808 if (skip_prefix(timestamp, "1969-12-31 ", &timestamp))
809 epoch_hour = 24;
810 else if (skip_prefix(timestamp, "1970-01-01 ", &timestamp))
811 epoch_hour = 0;
812 else
813 return 0;
815 if (!stamp) {
816 stamp = xmalloc(sizeof(*stamp));
817 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
818 warning(_("Cannot prepare timestamp regexp %s"),
819 stamp_regexp);
820 return 0;
824 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
825 if (status) {
826 if (status != REG_NOMATCH)
827 warning(_("regexec returned %d for input: %s"),
828 status, timestamp);
829 return 0;
832 hour = strtol(timestamp, NULL, 10);
833 minute = strtol(timestamp + m[1].rm_so, NULL, 10);
835 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
836 if (*colon == ':')
837 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
838 else
839 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
840 if (timestamp[m[3].rm_so] == '-')
841 zoneoffset = -zoneoffset;
843 return hour * 60 + minute - zoneoffset == epoch_hour * 60;
847 * Get the name etc info from the ---/+++ lines of a traditional patch header
849 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
850 * files, we can happily check the index for a match, but for creating a
851 * new file we should try to match whatever "patch" does. I have no idea.
853 static int parse_traditional_patch(struct apply_state *state,
854 const char *first,
855 const char *second,
856 struct patch *patch)
858 char *name;
860 first += 4; /* skip "--- " */
861 second += 4; /* skip "+++ " */
862 if (!state->p_value_known) {
863 int p, q;
864 p = guess_p_value(state, first);
865 q = guess_p_value(state, second);
866 if (p < 0) p = q;
867 if (0 <= p && p == q) {
868 state->p_value = p;
869 state->p_value_known = 1;
872 if (is_dev_null(first)) {
873 patch->is_new = 1;
874 patch->is_delete = 0;
875 name = find_name_traditional(&state->root, second, NULL, state->p_value);
876 patch->new_name = name;
877 } else if (is_dev_null(second)) {
878 patch->is_new = 0;
879 patch->is_delete = 1;
880 name = find_name_traditional(&state->root, first, NULL, state->p_value);
881 patch->old_name = name;
882 } else {
883 char *first_name;
884 first_name = find_name_traditional(&state->root, first, NULL, state->p_value);
885 name = find_name_traditional(&state->root, second, first_name, state->p_value);
886 free(first_name);
887 if (has_epoch_timestamp(first)) {
888 patch->is_new = 1;
889 patch->is_delete = 0;
890 patch->new_name = name;
891 } else if (has_epoch_timestamp(second)) {
892 patch->is_new = 0;
893 patch->is_delete = 1;
894 patch->old_name = name;
895 } else {
896 patch->old_name = name;
897 patch->new_name = xstrdup_or_null(name);
900 if (!name)
901 return error(_("unable to find filename in patch at line %d"), state->linenr);
903 return 0;
906 static int gitdiff_hdrend(struct gitdiff_data *state UNUSED,
907 const char *line UNUSED,
908 struct patch *patch UNUSED)
910 return 1;
914 * We're anal about diff header consistency, to make
915 * sure that we don't end up having strange ambiguous
916 * patches floating around.
918 * As a result, gitdiff_{old|new}name() will check
919 * their names against any previous information, just
920 * to make sure..
922 #define DIFF_OLD_NAME 0
923 #define DIFF_NEW_NAME 1
925 static int gitdiff_verify_name(struct gitdiff_data *state,
926 const char *line,
927 int isnull,
928 char **name,
929 int side)
931 if (!*name && !isnull) {
932 *name = find_name(state->root, line, NULL, state->p_value, TERM_TAB);
933 return 0;
936 if (*name) {
937 char *another;
938 if (isnull)
939 return error(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
940 *name, state->linenr);
941 another = find_name(state->root, line, NULL, state->p_value, TERM_TAB);
942 if (!another || strcmp(another, *name)) {
943 free(another);
944 return error((side == DIFF_NEW_NAME) ?
945 _("git apply: bad git-diff - inconsistent new filename on line %d") :
946 _("git apply: bad git-diff - inconsistent old filename on line %d"), state->linenr);
948 free(another);
949 } else {
950 if (!is_dev_null(line))
951 return error(_("git apply: bad git-diff - expected /dev/null on line %d"), state->linenr);
954 return 0;
957 static int gitdiff_oldname(struct gitdiff_data *state,
958 const char *line,
959 struct patch *patch)
961 return gitdiff_verify_name(state, line,
962 patch->is_new, &patch->old_name,
963 DIFF_OLD_NAME);
966 static int gitdiff_newname(struct gitdiff_data *state,
967 const char *line,
968 struct patch *patch)
970 return gitdiff_verify_name(state, line,
971 patch->is_delete, &patch->new_name,
972 DIFF_NEW_NAME);
975 static int parse_mode_line(const char *line, int linenr, unsigned int *mode)
977 char *end;
978 *mode = strtoul(line, &end, 8);
979 if (end == line || !isspace(*end))
980 return error(_("invalid mode on line %d: %s"), linenr, line);
981 return 0;
984 static int gitdiff_oldmode(struct gitdiff_data *state,
985 const char *line,
986 struct patch *patch)
988 return parse_mode_line(line, state->linenr, &patch->old_mode);
991 static int gitdiff_newmode(struct gitdiff_data *state,
992 const char *line,
993 struct patch *patch)
995 return parse_mode_line(line, state->linenr, &patch->new_mode);
998 static int gitdiff_delete(struct gitdiff_data *state,
999 const char *line,
1000 struct patch *patch)
1002 patch->is_delete = 1;
1003 free(patch->old_name);
1004 patch->old_name = xstrdup_or_null(patch->def_name);
1005 return gitdiff_oldmode(state, line, patch);
1008 static int gitdiff_newfile(struct gitdiff_data *state,
1009 const char *line,
1010 struct patch *patch)
1012 patch->is_new = 1;
1013 free(patch->new_name);
1014 patch->new_name = xstrdup_or_null(patch->def_name);
1015 return gitdiff_newmode(state, line, patch);
1018 static int gitdiff_copysrc(struct gitdiff_data *state,
1019 const char *line,
1020 struct patch *patch)
1022 patch->is_copy = 1;
1023 free(patch->old_name);
1024 patch->old_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1025 return 0;
1028 static int gitdiff_copydst(struct gitdiff_data *state,
1029 const char *line,
1030 struct patch *patch)
1032 patch->is_copy = 1;
1033 free(patch->new_name);
1034 patch->new_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1035 return 0;
1038 static int gitdiff_renamesrc(struct gitdiff_data *state,
1039 const char *line,
1040 struct patch *patch)
1042 patch->is_rename = 1;
1043 free(patch->old_name);
1044 patch->old_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1045 return 0;
1048 static int gitdiff_renamedst(struct gitdiff_data *state,
1049 const char *line,
1050 struct patch *patch)
1052 patch->is_rename = 1;
1053 free(patch->new_name);
1054 patch->new_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1055 return 0;
1058 static int gitdiff_similarity(struct gitdiff_data *state UNUSED,
1059 const char *line,
1060 struct patch *patch)
1062 unsigned long val = strtoul(line, NULL, 10);
1063 if (val <= 100)
1064 patch->score = val;
1065 return 0;
1068 static int gitdiff_dissimilarity(struct gitdiff_data *state UNUSED,
1069 const char *line,
1070 struct patch *patch)
1072 unsigned long val = strtoul(line, NULL, 10);
1073 if (val <= 100)
1074 patch->score = val;
1075 return 0;
1078 static int gitdiff_index(struct gitdiff_data *state,
1079 const char *line,
1080 struct patch *patch)
1083 * index line is N hexadecimal, "..", N hexadecimal,
1084 * and optional space with octal mode.
1086 const char *ptr, *eol;
1087 int len;
1088 const unsigned hexsz = the_hash_algo->hexsz;
1090 ptr = strchr(line, '.');
1091 if (!ptr || ptr[1] != '.' || hexsz < ptr - line)
1092 return 0;
1093 len = ptr - line;
1094 memcpy(patch->old_oid_prefix, line, len);
1095 patch->old_oid_prefix[len] = 0;
1097 line = ptr + 2;
1098 ptr = strchr(line, ' ');
1099 eol = strchrnul(line, '\n');
1101 if (!ptr || eol < ptr)
1102 ptr = eol;
1103 len = ptr - line;
1105 if (hexsz < len)
1106 return 0;
1107 memcpy(patch->new_oid_prefix, line, len);
1108 patch->new_oid_prefix[len] = 0;
1109 if (*ptr == ' ')
1110 return gitdiff_oldmode(state, ptr + 1, patch);
1111 return 0;
1115 * This is normal for a diff that doesn't change anything: we'll fall through
1116 * into the next diff. Tell the parser to break out.
1118 static int gitdiff_unrecognized(struct gitdiff_data *state UNUSED,
1119 const char *line UNUSED,
1120 struct patch *patch UNUSED)
1122 return 1;
1126 * Skip p_value leading components from "line"; as we do not accept
1127 * absolute paths, return NULL in that case.
1129 static const char *skip_tree_prefix(int p_value,
1130 const char *line,
1131 int llen)
1133 int nslash;
1134 int i;
1136 if (!p_value)
1137 return (llen && line[0] == '/') ? NULL : line;
1139 nslash = p_value;
1140 for (i = 0; i < llen; i++) {
1141 int ch = line[i];
1142 if (ch == '/' && --nslash <= 0)
1143 return (i == 0) ? NULL : &line[i + 1];
1145 return NULL;
1149 * This is to extract the same name that appears on "diff --git"
1150 * line. We do not find and return anything if it is a rename
1151 * patch, and it is OK because we will find the name elsewhere.
1152 * We need to reliably find name only when it is mode-change only,
1153 * creation or deletion of an empty file. In any of these cases,
1154 * both sides are the same name under a/ and b/ respectively.
1156 static char *git_header_name(int p_value,
1157 const char *line,
1158 int llen)
1160 const char *name;
1161 const char *second = NULL;
1162 size_t len, line_len;
1164 line += strlen("diff --git ");
1165 llen -= strlen("diff --git ");
1167 if (*line == '"') {
1168 const char *cp;
1169 struct strbuf first = STRBUF_INIT;
1170 struct strbuf sp = STRBUF_INIT;
1172 if (unquote_c_style(&first, line, &second))
1173 goto free_and_fail1;
1175 /* strip the a/b prefix including trailing slash */
1176 cp = skip_tree_prefix(p_value, first.buf, first.len);
1177 if (!cp)
1178 goto free_and_fail1;
1179 strbuf_remove(&first, 0, cp - first.buf);
1182 * second points at one past closing dq of name.
1183 * find the second name.
1185 while ((second < line + llen) && isspace(*second))
1186 second++;
1188 if (line + llen <= second)
1189 goto free_and_fail1;
1190 if (*second == '"') {
1191 if (unquote_c_style(&sp, second, NULL))
1192 goto free_and_fail1;
1193 cp = skip_tree_prefix(p_value, sp.buf, sp.len);
1194 if (!cp)
1195 goto free_and_fail1;
1196 /* They must match, otherwise ignore */
1197 if (strcmp(cp, first.buf))
1198 goto free_and_fail1;
1199 strbuf_release(&sp);
1200 return strbuf_detach(&first, NULL);
1203 /* unquoted second */
1204 cp = skip_tree_prefix(p_value, second, line + llen - second);
1205 if (!cp)
1206 goto free_and_fail1;
1207 if (line + llen - cp != first.len ||
1208 memcmp(first.buf, cp, first.len))
1209 goto free_and_fail1;
1210 return strbuf_detach(&first, NULL);
1212 free_and_fail1:
1213 strbuf_release(&first);
1214 strbuf_release(&sp);
1215 return NULL;
1218 /* unquoted first name */
1219 name = skip_tree_prefix(p_value, line, llen);
1220 if (!name)
1221 return NULL;
1224 * since the first name is unquoted, a dq if exists must be
1225 * the beginning of the second name.
1227 for (second = name; second < line + llen; second++) {
1228 if (*second == '"') {
1229 struct strbuf sp = STRBUF_INIT;
1230 const char *np;
1232 if (unquote_c_style(&sp, second, NULL))
1233 goto free_and_fail2;
1235 np = skip_tree_prefix(p_value, sp.buf, sp.len);
1236 if (!np)
1237 goto free_and_fail2;
1239 len = sp.buf + sp.len - np;
1240 if (len < second - name &&
1241 !strncmp(np, name, len) &&
1242 isspace(name[len])) {
1243 /* Good */
1244 strbuf_remove(&sp, 0, np - sp.buf);
1245 return strbuf_detach(&sp, NULL);
1248 free_and_fail2:
1249 strbuf_release(&sp);
1250 return NULL;
1255 * Accept a name only if it shows up twice, exactly the same
1256 * form.
1258 second = strchr(name, '\n');
1259 if (!second)
1260 return NULL;
1261 line_len = second - name;
1262 for (len = 0 ; ; len++) {
1263 switch (name[len]) {
1264 default:
1265 continue;
1266 case '\n':
1267 return NULL;
1268 case '\t': case ' ':
1270 * Is this the separator between the preimage
1271 * and the postimage pathname? Again, we are
1272 * only interested in the case where there is
1273 * no rename, as this is only to set def_name
1274 * and a rename patch has the names elsewhere
1275 * in an unambiguous form.
1277 if (!name[len + 1])
1278 return NULL; /* no postimage name */
1279 second = skip_tree_prefix(p_value, name + len + 1,
1280 line_len - (len + 1));
1281 if (!second)
1282 return NULL;
1284 * Does len bytes starting at "name" and "second"
1285 * (that are separated by one HT or SP we just
1286 * found) exactly match?
1288 if (second[len] == '\n' && !strncmp(name, second, len))
1289 return xmemdupz(name, len);
1294 static int check_header_line(int linenr, struct patch *patch)
1296 int extensions = (patch->is_delete == 1) + (patch->is_new == 1) +
1297 (patch->is_rename == 1) + (patch->is_copy == 1);
1298 if (extensions > 1)
1299 return error(_("inconsistent header lines %d and %d"),
1300 patch->extension_linenr, linenr);
1301 if (extensions && !patch->extension_linenr)
1302 patch->extension_linenr = linenr;
1303 return 0;
1306 int parse_git_diff_header(struct strbuf *root,
1307 int *linenr,
1308 int p_value,
1309 const char *line,
1310 int len,
1311 unsigned int size,
1312 struct patch *patch)
1314 unsigned long offset;
1315 struct gitdiff_data parse_hdr_state;
1317 /* A git diff has explicit new/delete information, so we don't guess */
1318 patch->is_new = 0;
1319 patch->is_delete = 0;
1322 * Some things may not have the old name in the
1323 * rest of the headers anywhere (pure mode changes,
1324 * or removing or adding empty files), so we get
1325 * the default name from the header.
1327 patch->def_name = git_header_name(p_value, line, len);
1328 if (patch->def_name && root->len) {
1329 char *s = xstrfmt("%s%s", root->buf, patch->def_name);
1330 free(patch->def_name);
1331 patch->def_name = s;
1334 line += len;
1335 size -= len;
1336 (*linenr)++;
1337 parse_hdr_state.root = root;
1338 parse_hdr_state.linenr = *linenr;
1339 parse_hdr_state.p_value = p_value;
1341 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, (*linenr)++) {
1342 static const struct opentry {
1343 const char *str;
1344 int (*fn)(struct gitdiff_data *, const char *, struct patch *);
1345 } optable[] = {
1346 { "@@ -", gitdiff_hdrend },
1347 { "--- ", gitdiff_oldname },
1348 { "+++ ", gitdiff_newname },
1349 { "old mode ", gitdiff_oldmode },
1350 { "new mode ", gitdiff_newmode },
1351 { "deleted file mode ", gitdiff_delete },
1352 { "new file mode ", gitdiff_newfile },
1353 { "copy from ", gitdiff_copysrc },
1354 { "copy to ", gitdiff_copydst },
1355 { "rename old ", gitdiff_renamesrc },
1356 { "rename new ", gitdiff_renamedst },
1357 { "rename from ", gitdiff_renamesrc },
1358 { "rename to ", gitdiff_renamedst },
1359 { "similarity index ", gitdiff_similarity },
1360 { "dissimilarity index ", gitdiff_dissimilarity },
1361 { "index ", gitdiff_index },
1362 { "", gitdiff_unrecognized },
1364 int i;
1366 len = linelen(line, size);
1367 if (!len || line[len-1] != '\n')
1368 break;
1369 for (i = 0; i < ARRAY_SIZE(optable); i++) {
1370 const struct opentry *p = optable + i;
1371 int oplen = strlen(p->str);
1372 int res;
1373 if (len < oplen || memcmp(p->str, line, oplen))
1374 continue;
1375 res = p->fn(&parse_hdr_state, line + oplen, patch);
1376 if (res < 0)
1377 return -1;
1378 if (check_header_line(*linenr, patch))
1379 return -1;
1380 if (res > 0)
1381 goto done;
1382 break;
1386 done:
1387 if (!patch->old_name && !patch->new_name) {
1388 if (!patch->def_name) {
1389 error(Q_("git diff header lacks filename information when removing "
1390 "%d leading pathname component (line %d)",
1391 "git diff header lacks filename information when removing "
1392 "%d leading pathname components (line %d)",
1393 parse_hdr_state.p_value),
1394 parse_hdr_state.p_value, *linenr);
1395 return -128;
1397 patch->old_name = xstrdup(patch->def_name);
1398 patch->new_name = xstrdup(patch->def_name);
1400 if ((!patch->new_name && !patch->is_delete) ||
1401 (!patch->old_name && !patch->is_new)) {
1402 error(_("git diff header lacks filename information "
1403 "(line %d)"), *linenr);
1404 return -128;
1406 patch->is_toplevel_relative = 1;
1407 return offset;
1410 static int parse_num(const char *line, unsigned long *p)
1412 char *ptr;
1414 if (!isdigit(*line))
1415 return 0;
1416 *p = strtoul(line, &ptr, 10);
1417 return ptr - line;
1420 static int parse_range(const char *line, int len, int offset, const char *expect,
1421 unsigned long *p1, unsigned long *p2)
1423 int digits, ex;
1425 if (offset < 0 || offset >= len)
1426 return -1;
1427 line += offset;
1428 len -= offset;
1430 digits = parse_num(line, p1);
1431 if (!digits)
1432 return -1;
1434 offset += digits;
1435 line += digits;
1436 len -= digits;
1438 *p2 = 1;
1439 if (*line == ',') {
1440 digits = parse_num(line+1, p2);
1441 if (!digits)
1442 return -1;
1444 offset += digits+1;
1445 line += digits+1;
1446 len -= digits+1;
1449 ex = strlen(expect);
1450 if (ex > len)
1451 return -1;
1452 if (memcmp(line, expect, ex))
1453 return -1;
1455 return offset + ex;
1458 static void recount_diff(const char *line, int size, struct fragment *fragment)
1460 int oldlines = 0, newlines = 0, ret = 0;
1462 if (size < 1) {
1463 warning("recount: ignore empty hunk");
1464 return;
1467 for (;;) {
1468 int len = linelen(line, size);
1469 size -= len;
1470 line += len;
1472 if (size < 1)
1473 break;
1475 switch (*line) {
1476 case ' ': case '\n':
1477 newlines++;
1478 /* fall through */
1479 case '-':
1480 oldlines++;
1481 continue;
1482 case '+':
1483 newlines++;
1484 continue;
1485 case '\\':
1486 continue;
1487 case '@':
1488 ret = size < 3 || !starts_with(line, "@@ ");
1489 break;
1490 case 'd':
1491 ret = size < 5 || !starts_with(line, "diff ");
1492 break;
1493 default:
1494 ret = -1;
1495 break;
1497 if (ret) {
1498 warning(_("recount: unexpected line: %.*s"),
1499 (int)linelen(line, size), line);
1500 return;
1502 break;
1504 fragment->oldlines = oldlines;
1505 fragment->newlines = newlines;
1509 * Parse a unified diff fragment header of the
1510 * form "@@ -a,b +c,d @@"
1512 static int parse_fragment_header(const char *line, int len, struct fragment *fragment)
1514 int offset;
1516 if (!len || line[len-1] != '\n')
1517 return -1;
1519 /* Figure out the number of lines in a fragment */
1520 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1521 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1523 return offset;
1527 * Find file diff header
1529 * Returns:
1530 * -1 if no header was found
1531 * -128 in case of error
1532 * the size of the header in bytes (called "offset") otherwise
1534 static int find_header(struct apply_state *state,
1535 const char *line,
1536 unsigned long size,
1537 int *hdrsize,
1538 struct patch *patch)
1540 unsigned long offset, len;
1542 patch->is_toplevel_relative = 0;
1543 patch->is_rename = patch->is_copy = 0;
1544 patch->is_new = patch->is_delete = -1;
1545 patch->old_mode = patch->new_mode = 0;
1546 patch->old_name = patch->new_name = NULL;
1547 for (offset = 0; size > 0; offset += len, size -= len, line += len, state->linenr++) {
1548 unsigned long nextlen;
1550 len = linelen(line, size);
1551 if (!len)
1552 break;
1554 /* Testing this early allows us to take a few shortcuts.. */
1555 if (len < 6)
1556 continue;
1559 * Make sure we don't find any unconnected patch fragments.
1560 * That's a sign that we didn't find a header, and that a
1561 * patch has become corrupted/broken up.
1563 if (!memcmp("@@ -", line, 4)) {
1564 struct fragment dummy;
1565 if (parse_fragment_header(line, len, &dummy) < 0)
1566 continue;
1567 error(_("patch fragment without header at line %d: %.*s"),
1568 state->linenr, (int)len-1, line);
1569 return -128;
1572 if (size < len + 6)
1573 break;
1576 * Git patch? It might not have a real patch, just a rename
1577 * or mode change, so we handle that specially
1579 if (!memcmp("diff --git ", line, 11)) {
1580 int git_hdr_len = parse_git_diff_header(&state->root, &state->linenr,
1581 state->p_value, line, len,
1582 size, patch);
1583 if (git_hdr_len < 0)
1584 return -128;
1585 if (git_hdr_len <= len)
1586 continue;
1587 *hdrsize = git_hdr_len;
1588 return offset;
1591 /* --- followed by +++ ? */
1592 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1593 continue;
1596 * We only accept unified patches, so we want it to
1597 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1598 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1600 nextlen = linelen(line + len, size - len);
1601 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1602 continue;
1604 /* Ok, we'll consider it a patch */
1605 if (parse_traditional_patch(state, line, line+len, patch))
1606 return -128;
1607 *hdrsize = len + nextlen;
1608 state->linenr += 2;
1609 return offset;
1611 return -1;
1614 static void record_ws_error(struct apply_state *state,
1615 unsigned result,
1616 const char *line,
1617 int len,
1618 int linenr)
1620 char *err;
1622 if (!result)
1623 return;
1625 state->whitespace_error++;
1626 if (state->squelch_whitespace_errors &&
1627 state->squelch_whitespace_errors < state->whitespace_error)
1628 return;
1630 err = whitespace_error_string(result);
1631 if (state->apply_verbosity > verbosity_silent)
1632 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1633 state->patch_input_file, linenr, err, len, line);
1634 free(err);
1637 static void check_whitespace(struct apply_state *state,
1638 const char *line,
1639 int len,
1640 unsigned ws_rule)
1642 unsigned result = ws_check(line + 1, len - 1, ws_rule);
1644 record_ws_error(state, result, line + 1, len - 2, state->linenr);
1648 * Check if the patch has context lines with CRLF or
1649 * the patch wants to remove lines with CRLF.
1651 static void check_old_for_crlf(struct patch *patch, const char *line, int len)
1653 if (len >= 2 && line[len-1] == '\n' && line[len-2] == '\r') {
1654 patch->ws_rule |= WS_CR_AT_EOL;
1655 patch->crlf_in_old = 1;
1661 * Parse a unified diff. Note that this really needs to parse each
1662 * fragment separately, since the only way to know the difference
1663 * between a "---" that is part of a patch, and a "---" that starts
1664 * the next patch is to look at the line counts..
1666 static int parse_fragment(struct apply_state *state,
1667 const char *line,
1668 unsigned long size,
1669 struct patch *patch,
1670 struct fragment *fragment)
1672 int added, deleted;
1673 int len = linelen(line, size), offset;
1674 unsigned long oldlines, newlines;
1675 unsigned long leading, trailing;
1677 offset = parse_fragment_header(line, len, fragment);
1678 if (offset < 0)
1679 return -1;
1680 if (offset > 0 && patch->recount)
1681 recount_diff(line + offset, size - offset, fragment);
1682 oldlines = fragment->oldlines;
1683 newlines = fragment->newlines;
1684 leading = 0;
1685 trailing = 0;
1687 /* Parse the thing.. */
1688 line += len;
1689 size -= len;
1690 state->linenr++;
1691 added = deleted = 0;
1692 for (offset = len;
1693 0 < size;
1694 offset += len, size -= len, line += len, state->linenr++) {
1695 if (!oldlines && !newlines)
1696 break;
1697 len = linelen(line, size);
1698 if (!len || line[len-1] != '\n')
1699 return -1;
1700 switch (*line) {
1701 default:
1702 return -1;
1703 case '\n': /* newer GNU diff, an empty context line */
1704 case ' ':
1705 oldlines--;
1706 newlines--;
1707 if (!deleted && !added)
1708 leading++;
1709 trailing++;
1710 check_old_for_crlf(patch, line, len);
1711 if (!state->apply_in_reverse &&
1712 state->ws_error_action == correct_ws_error)
1713 check_whitespace(state, line, len, patch->ws_rule);
1714 break;
1715 case '-':
1716 if (!state->apply_in_reverse)
1717 check_old_for_crlf(patch, line, len);
1718 if (state->apply_in_reverse &&
1719 state->ws_error_action != nowarn_ws_error)
1720 check_whitespace(state, line, len, patch->ws_rule);
1721 deleted++;
1722 oldlines--;
1723 trailing = 0;
1724 break;
1725 case '+':
1726 if (state->apply_in_reverse)
1727 check_old_for_crlf(patch, line, len);
1728 if (!state->apply_in_reverse &&
1729 state->ws_error_action != nowarn_ws_error)
1730 check_whitespace(state, line, len, patch->ws_rule);
1731 added++;
1732 newlines--;
1733 trailing = 0;
1734 break;
1737 * We allow "\ No newline at end of file". Depending
1738 * on locale settings when the patch was produced we
1739 * don't know what this line looks like. The only
1740 * thing we do know is that it begins with "\ ".
1741 * Checking for 12 is just for sanity check -- any
1742 * l10n of "\ No newline..." is at least that long.
1744 case '\\':
1745 if (len < 12 || memcmp(line, "\\ ", 2))
1746 return -1;
1747 break;
1750 if (oldlines || newlines)
1751 return -1;
1752 if (!patch->recount && !deleted && !added)
1753 return -1;
1755 fragment->leading = leading;
1756 fragment->trailing = trailing;
1759 * If a fragment ends with an incomplete line, we failed to include
1760 * it in the above loop because we hit oldlines == newlines == 0
1761 * before seeing it.
1763 if (12 < size && !memcmp(line, "\\ ", 2))
1764 offset += linelen(line, size);
1766 patch->lines_added += added;
1767 patch->lines_deleted += deleted;
1769 if (0 < patch->is_new && oldlines)
1770 return error(_("new file depends on old contents"));
1771 if (0 < patch->is_delete && newlines)
1772 return error(_("deleted file still has contents"));
1773 return offset;
1777 * We have seen "diff --git a/... b/..." header (or a traditional patch
1778 * header). Read hunks that belong to this patch into fragments and hang
1779 * them to the given patch structure.
1781 * The (fragment->patch, fragment->size) pair points into the memory given
1782 * by the caller, not a copy, when we return.
1784 * Returns:
1785 * -1 in case of error,
1786 * the number of bytes in the patch otherwise.
1788 static int parse_single_patch(struct apply_state *state,
1789 const char *line,
1790 unsigned long size,
1791 struct patch *patch)
1793 unsigned long offset = 0;
1794 unsigned long oldlines = 0, newlines = 0, context = 0;
1795 struct fragment **fragp = &patch->fragments;
1797 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1798 struct fragment *fragment;
1799 int len;
1801 CALLOC_ARRAY(fragment, 1);
1802 fragment->linenr = state->linenr;
1803 len = parse_fragment(state, line, size, patch, fragment);
1804 if (len <= 0) {
1805 free(fragment);
1806 return error(_("corrupt patch at line %d"), state->linenr);
1808 fragment->patch = line;
1809 fragment->size = len;
1810 oldlines += fragment->oldlines;
1811 newlines += fragment->newlines;
1812 context += fragment->leading + fragment->trailing;
1814 *fragp = fragment;
1815 fragp = &fragment->next;
1817 offset += len;
1818 line += len;
1819 size -= len;
1823 * If something was removed (i.e. we have old-lines) it cannot
1824 * be creation, and if something was added it cannot be
1825 * deletion. However, the reverse is not true; --unified=0
1826 * patches that only add are not necessarily creation even
1827 * though they do not have any old lines, and ones that only
1828 * delete are not necessarily deletion.
1830 * Unfortunately, a real creation/deletion patch do _not_ have
1831 * any context line by definition, so we cannot safely tell it
1832 * apart with --unified=0 insanity. At least if the patch has
1833 * more than one hunk it is not creation or deletion.
1835 if (patch->is_new < 0 &&
1836 (oldlines || (patch->fragments && patch->fragments->next)))
1837 patch->is_new = 0;
1838 if (patch->is_delete < 0 &&
1839 (newlines || (patch->fragments && patch->fragments->next)))
1840 patch->is_delete = 0;
1842 if (0 < patch->is_new && oldlines)
1843 return error(_("new file %s depends on old contents"), patch->new_name);
1844 if (0 < patch->is_delete && newlines)
1845 return error(_("deleted file %s still has contents"), patch->old_name);
1846 if (!patch->is_delete && !newlines && context && state->apply_verbosity > verbosity_silent)
1847 fprintf_ln(stderr,
1848 _("** warning: "
1849 "file %s becomes empty but is not deleted"),
1850 patch->new_name);
1852 return offset;
1855 static inline int metadata_changes(struct patch *patch)
1857 return patch->is_rename > 0 ||
1858 patch->is_copy > 0 ||
1859 patch->is_new > 0 ||
1860 patch->is_delete ||
1861 (patch->old_mode && patch->new_mode &&
1862 patch->old_mode != patch->new_mode);
1865 static char *inflate_it(const void *data, unsigned long size,
1866 unsigned long inflated_size)
1868 git_zstream stream;
1869 void *out;
1870 int st;
1872 memset(&stream, 0, sizeof(stream));
1874 stream.next_in = (unsigned char *)data;
1875 stream.avail_in = size;
1876 stream.next_out = out = xmalloc(inflated_size);
1877 stream.avail_out = inflated_size;
1878 git_inflate_init(&stream);
1879 st = git_inflate(&stream, Z_FINISH);
1880 git_inflate_end(&stream);
1881 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1882 free(out);
1883 return NULL;
1885 return out;
1889 * Read a binary hunk and return a new fragment; fragment->patch
1890 * points at an allocated memory that the caller must free, so
1891 * it is marked as "->free_patch = 1".
1893 static struct fragment *parse_binary_hunk(struct apply_state *state,
1894 char **buf_p,
1895 unsigned long *sz_p,
1896 int *status_p,
1897 int *used_p)
1900 * Expect a line that begins with binary patch method ("literal"
1901 * or "delta"), followed by the length of data before deflating.
1902 * a sequence of 'length-byte' followed by base-85 encoded data
1903 * should follow, terminated by a newline.
1905 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1906 * and we would limit the patch line to 66 characters,
1907 * so one line can fit up to 13 groups that would decode
1908 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1909 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1911 int llen, used;
1912 unsigned long size = *sz_p;
1913 char *buffer = *buf_p;
1914 int patch_method;
1915 unsigned long origlen;
1916 char *data = NULL;
1917 int hunk_size = 0;
1918 struct fragment *frag;
1920 llen = linelen(buffer, size);
1921 used = llen;
1923 *status_p = 0;
1925 if (starts_with(buffer, "delta ")) {
1926 patch_method = BINARY_DELTA_DEFLATED;
1927 origlen = strtoul(buffer + 6, NULL, 10);
1929 else if (starts_with(buffer, "literal ")) {
1930 patch_method = BINARY_LITERAL_DEFLATED;
1931 origlen = strtoul(buffer + 8, NULL, 10);
1933 else
1934 return NULL;
1936 state->linenr++;
1937 buffer += llen;
1938 size -= llen;
1939 while (1) {
1940 int byte_length, max_byte_length, newsize;
1941 llen = linelen(buffer, size);
1942 used += llen;
1943 state->linenr++;
1944 if (llen == 1) {
1945 /* consume the blank line */
1946 buffer++;
1947 size--;
1948 break;
1951 * Minimum line is "A00000\n" which is 7-byte long,
1952 * and the line length must be multiple of 5 plus 2.
1954 if ((llen < 7) || (llen-2) % 5)
1955 goto corrupt;
1956 max_byte_length = (llen - 2) / 5 * 4;
1957 byte_length = *buffer;
1958 if ('A' <= byte_length && byte_length <= 'Z')
1959 byte_length = byte_length - 'A' + 1;
1960 else if ('a' <= byte_length && byte_length <= 'z')
1961 byte_length = byte_length - 'a' + 27;
1962 else
1963 goto corrupt;
1964 /* if the input length was not multiple of 4, we would
1965 * have filler at the end but the filler should never
1966 * exceed 3 bytes
1968 if (max_byte_length < byte_length ||
1969 byte_length <= max_byte_length - 4)
1970 goto corrupt;
1971 newsize = hunk_size + byte_length;
1972 data = xrealloc(data, newsize);
1973 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1974 goto corrupt;
1975 hunk_size = newsize;
1976 buffer += llen;
1977 size -= llen;
1980 CALLOC_ARRAY(frag, 1);
1981 frag->patch = inflate_it(data, hunk_size, origlen);
1982 frag->free_patch = 1;
1983 if (!frag->patch)
1984 goto corrupt;
1985 free(data);
1986 frag->size = origlen;
1987 *buf_p = buffer;
1988 *sz_p = size;
1989 *used_p = used;
1990 frag->binary_patch_method = patch_method;
1991 return frag;
1993 corrupt:
1994 free(data);
1995 *status_p = -1;
1996 error(_("corrupt binary patch at line %d: %.*s"),
1997 state->linenr-1, llen-1, buffer);
1998 return NULL;
2002 * Returns:
2003 * -1 in case of error,
2004 * the length of the parsed binary patch otherwise
2006 static int parse_binary(struct apply_state *state,
2007 char *buffer,
2008 unsigned long size,
2009 struct patch *patch)
2012 * We have read "GIT binary patch\n"; what follows is a line
2013 * that says the patch method (currently, either "literal" or
2014 * "delta") and the length of data before deflating; a
2015 * sequence of 'length-byte' followed by base-85 encoded data
2016 * follows.
2018 * When a binary patch is reversible, there is another binary
2019 * hunk in the same format, starting with patch method (either
2020 * "literal" or "delta") with the length of data, and a sequence
2021 * of length-byte + base-85 encoded data, terminated with another
2022 * empty line. This data, when applied to the postimage, produces
2023 * the preimage.
2025 struct fragment *forward;
2026 struct fragment *reverse;
2027 int status;
2028 int used, used_1;
2030 forward = parse_binary_hunk(state, &buffer, &size, &status, &used);
2031 if (!forward && !status)
2032 /* there has to be one hunk (forward hunk) */
2033 return error(_("unrecognized binary patch at line %d"), state->linenr-1);
2034 if (status)
2035 /* otherwise we already gave an error message */
2036 return status;
2038 reverse = parse_binary_hunk(state, &buffer, &size, &status, &used_1);
2039 if (reverse)
2040 used += used_1;
2041 else if (status) {
2043 * Not having reverse hunk is not an error, but having
2044 * a corrupt reverse hunk is.
2046 free((void*) forward->patch);
2047 free(forward);
2048 return status;
2050 forward->next = reverse;
2051 patch->fragments = forward;
2052 patch->is_binary = 1;
2053 return used;
2056 static void prefix_one(struct apply_state *state, char **name)
2058 char *old_name = *name;
2059 if (!old_name)
2060 return;
2061 *name = prefix_filename(state->prefix, *name);
2062 free(old_name);
2065 static void prefix_patch(struct apply_state *state, struct patch *p)
2067 if (!state->prefix || p->is_toplevel_relative)
2068 return;
2069 prefix_one(state, &p->new_name);
2070 prefix_one(state, &p->old_name);
2074 * include/exclude
2077 static void add_name_limit(struct apply_state *state,
2078 const char *name,
2079 int exclude)
2081 struct string_list_item *it;
2083 it = string_list_append(&state->limit_by_name, name);
2084 it->util = exclude ? NULL : (void *) 1;
2087 static int use_patch(struct apply_state *state, struct patch *p)
2089 const char *pathname = p->new_name ? p->new_name : p->old_name;
2090 int i;
2092 /* Paths outside are not touched regardless of "--include" */
2093 if (state->prefix && *state->prefix) {
2094 const char *rest;
2095 if (!skip_prefix(pathname, state->prefix, &rest) || !*rest)
2096 return 0;
2099 /* See if it matches any of exclude/include rule */
2100 for (i = 0; i < state->limit_by_name.nr; i++) {
2101 struct string_list_item *it = &state->limit_by_name.items[i];
2102 if (!wildmatch(it->string, pathname, 0))
2103 return (it->util != NULL);
2107 * If we had any include, a path that does not match any rule is
2108 * not used. Otherwise, we saw bunch of exclude rules (or none)
2109 * and such a path is used.
2111 return !state->has_include;
2115 * Read the patch text in "buffer" that extends for "size" bytes; stop
2116 * reading after seeing a single patch (i.e. changes to a single file).
2117 * Create fragments (i.e. patch hunks) and hang them to the given patch.
2119 * Returns:
2120 * -1 if no header was found or parse_binary() failed,
2121 * -128 on another error,
2122 * the number of bytes consumed otherwise,
2123 * so that the caller can call us again for the next patch.
2125 static int parse_chunk(struct apply_state *state, char *buffer, unsigned long size, struct patch *patch)
2127 int hdrsize, patchsize;
2128 int offset = find_header(state, buffer, size, &hdrsize, patch);
2130 if (offset < 0)
2131 return offset;
2133 prefix_patch(state, patch);
2135 if (!use_patch(state, patch))
2136 patch->ws_rule = 0;
2137 else if (patch->new_name)
2138 patch->ws_rule = whitespace_rule(state->repo->index,
2139 patch->new_name);
2140 else
2141 patch->ws_rule = whitespace_rule(state->repo->index,
2142 patch->old_name);
2144 patchsize = parse_single_patch(state,
2145 buffer + offset + hdrsize,
2146 size - offset - hdrsize,
2147 patch);
2149 if (patchsize < 0)
2150 return -128;
2152 if (!patchsize) {
2153 static const char git_binary[] = "GIT binary patch\n";
2154 int hd = hdrsize + offset;
2155 unsigned long llen = linelen(buffer + hd, size - hd);
2157 if (llen == sizeof(git_binary) - 1 &&
2158 !memcmp(git_binary, buffer + hd, llen)) {
2159 int used;
2160 state->linenr++;
2161 used = parse_binary(state, buffer + hd + llen,
2162 size - hd - llen, patch);
2163 if (used < 0)
2164 return -1;
2165 if (used)
2166 patchsize = used + llen;
2167 else
2168 patchsize = 0;
2170 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
2171 static const char *binhdr[] = {
2172 "Binary files ",
2173 "Files ",
2174 NULL,
2176 int i;
2177 for (i = 0; binhdr[i]; i++) {
2178 int len = strlen(binhdr[i]);
2179 if (len < size - hd &&
2180 !memcmp(binhdr[i], buffer + hd, len)) {
2181 state->linenr++;
2182 patch->is_binary = 1;
2183 patchsize = llen;
2184 break;
2189 /* Empty patch cannot be applied if it is a text patch
2190 * without metadata change. A binary patch appears
2191 * empty to us here.
2193 if ((state->apply || state->check) &&
2194 (!patch->is_binary && !metadata_changes(patch))) {
2195 error(_("patch with only garbage at line %d"), state->linenr);
2196 return -128;
2200 return offset + hdrsize + patchsize;
2203 static void reverse_patches(struct patch *p)
2205 for (; p; p = p->next) {
2206 struct fragment *frag = p->fragments;
2208 SWAP(p->new_name, p->old_name);
2209 SWAP(p->new_mode, p->old_mode);
2210 SWAP(p->is_new, p->is_delete);
2211 SWAP(p->lines_added, p->lines_deleted);
2212 SWAP(p->old_oid_prefix, p->new_oid_prefix);
2214 for (; frag; frag = frag->next) {
2215 SWAP(frag->newpos, frag->oldpos);
2216 SWAP(frag->newlines, frag->oldlines);
2221 static const char pluses[] =
2222 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2223 static const char minuses[]=
2224 "----------------------------------------------------------------------";
2226 static void show_stats(struct apply_state *state, struct patch *patch)
2228 struct strbuf qname = STRBUF_INIT;
2229 char *cp = patch->new_name ? patch->new_name : patch->old_name;
2230 int max, add, del;
2232 quote_c_style(cp, &qname, NULL, 0);
2235 * "scale" the filename
2237 max = state->max_len;
2238 if (max > 50)
2239 max = 50;
2241 if (qname.len > max) {
2242 cp = strchr(qname.buf + qname.len + 3 - max, '/');
2243 if (!cp)
2244 cp = qname.buf + qname.len + 3 - max;
2245 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
2248 if (patch->is_binary) {
2249 printf(" %-*s | Bin\n", max, qname.buf);
2250 strbuf_release(&qname);
2251 return;
2254 printf(" %-*s |", max, qname.buf);
2255 strbuf_release(&qname);
2258 * scale the add/delete
2260 max = max + state->max_change > 70 ? 70 - max : state->max_change;
2261 add = patch->lines_added;
2262 del = patch->lines_deleted;
2264 if (state->max_change > 0) {
2265 int total = ((add + del) * max + state->max_change / 2) / state->max_change;
2266 add = (add * max + state->max_change / 2) / state->max_change;
2267 del = total - add;
2269 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
2270 add, pluses, del, minuses);
2273 static int read_old_data(struct stat *st, struct patch *patch,
2274 const char *path, struct strbuf *buf)
2276 int conv_flags = patch->crlf_in_old ?
2277 CONV_EOL_KEEP_CRLF : CONV_EOL_RENORMALIZE;
2278 switch (st->st_mode & S_IFMT) {
2279 case S_IFLNK:
2280 if (strbuf_readlink(buf, path, st->st_size) < 0)
2281 return error(_("unable to read symlink %s"), path);
2282 return 0;
2283 case S_IFREG:
2284 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
2285 return error(_("unable to open or read %s"), path);
2287 * "git apply" without "--index/--cached" should never look
2288 * at the index; the target file may not have been added to
2289 * the index yet, and we may not even be in any Git repository.
2290 * Pass NULL to convert_to_git() to stress this; the function
2291 * should never look at the index when explicit crlf option
2292 * is given.
2294 convert_to_git(NULL, path, buf->buf, buf->len, buf, conv_flags);
2295 return 0;
2296 default:
2297 return -1;
2302 * Update the preimage, and the common lines in postimage,
2303 * from buffer buf of length len. If postlen is 0 the postimage
2304 * is updated in place, otherwise it's updated on a new buffer
2305 * of length postlen
2308 static void update_pre_post_images(struct image *preimage,
2309 struct image *postimage,
2310 char *buf,
2311 size_t len, size_t postlen)
2313 int i, ctx, reduced;
2314 char *new_buf, *old_buf, *fixed;
2315 struct image fixed_preimage;
2318 * Update the preimage with whitespace fixes. Note that we
2319 * are not losing preimage->buf -- apply_one_fragment() will
2320 * free "oldlines".
2322 prepare_image(&fixed_preimage, buf, len, 1);
2323 assert(postlen
2324 ? fixed_preimage.nr == preimage->nr
2325 : fixed_preimage.nr <= preimage->nr);
2326 for (i = 0; i < fixed_preimage.nr; i++)
2327 fixed_preimage.line[i].flag = preimage->line[i].flag;
2328 free(preimage->line_allocated);
2329 *preimage = fixed_preimage;
2332 * Adjust the common context lines in postimage. This can be
2333 * done in-place when we are shrinking it with whitespace
2334 * fixing, but needs a new buffer when ignoring whitespace or
2335 * expanding leading tabs to spaces.
2337 * We trust the caller to tell us if the update can be done
2338 * in place (postlen==0) or not.
2340 old_buf = postimage->buf;
2341 if (postlen)
2342 new_buf = postimage->buf = xmalloc(postlen);
2343 else
2344 new_buf = old_buf;
2345 fixed = preimage->buf;
2347 for (i = reduced = ctx = 0; i < postimage->nr; i++) {
2348 size_t l_len = postimage->line[i].len;
2349 if (!(postimage->line[i].flag & LINE_COMMON)) {
2350 /* an added line -- no counterparts in preimage */
2351 memmove(new_buf, old_buf, l_len);
2352 old_buf += l_len;
2353 new_buf += l_len;
2354 continue;
2357 /* a common context -- skip it in the original postimage */
2358 old_buf += l_len;
2360 /* and find the corresponding one in the fixed preimage */
2361 while (ctx < preimage->nr &&
2362 !(preimage->line[ctx].flag & LINE_COMMON)) {
2363 fixed += preimage->line[ctx].len;
2364 ctx++;
2368 * preimage is expected to run out, if the caller
2369 * fixed addition of trailing blank lines.
2371 if (preimage->nr <= ctx) {
2372 reduced++;
2373 continue;
2376 /* and copy it in, while fixing the line length */
2377 l_len = preimage->line[ctx].len;
2378 memcpy(new_buf, fixed, l_len);
2379 new_buf += l_len;
2380 fixed += l_len;
2381 postimage->line[i].len = l_len;
2382 ctx++;
2385 if (postlen
2386 ? postlen < new_buf - postimage->buf
2387 : postimage->len < new_buf - postimage->buf)
2388 BUG("caller miscounted postlen: asked %d, orig = %d, used = %d",
2389 (int)postlen, (int) postimage->len, (int)(new_buf - postimage->buf));
2391 /* Fix the length of the whole thing */
2392 postimage->len = new_buf - postimage->buf;
2393 postimage->nr -= reduced;
2396 static int line_by_line_fuzzy_match(struct image *img,
2397 struct image *preimage,
2398 struct image *postimage,
2399 unsigned long current,
2400 int current_lno,
2401 int preimage_limit)
2403 int i;
2404 size_t imgoff = 0;
2405 size_t preoff = 0;
2406 size_t postlen = postimage->len;
2407 size_t extra_chars;
2408 char *buf;
2409 char *preimage_eof;
2410 char *preimage_end;
2411 struct strbuf fixed;
2412 char *fixed_buf;
2413 size_t fixed_len;
2415 for (i = 0; i < preimage_limit; i++) {
2416 size_t prelen = preimage->line[i].len;
2417 size_t imglen = img->line[current_lno+i].len;
2419 if (!fuzzy_matchlines(img->buf + current + imgoff, imglen,
2420 preimage->buf + preoff, prelen))
2421 return 0;
2422 if (preimage->line[i].flag & LINE_COMMON)
2423 postlen += imglen - prelen;
2424 imgoff += imglen;
2425 preoff += prelen;
2429 * Ok, the preimage matches with whitespace fuzz.
2431 * imgoff now holds the true length of the target that
2432 * matches the preimage before the end of the file.
2434 * Count the number of characters in the preimage that fall
2435 * beyond the end of the file and make sure that all of them
2436 * are whitespace characters. (This can only happen if
2437 * we are removing blank lines at the end of the file.)
2439 buf = preimage_eof = preimage->buf + preoff;
2440 for ( ; i < preimage->nr; i++)
2441 preoff += preimage->line[i].len;
2442 preimage_end = preimage->buf + preoff;
2443 for ( ; buf < preimage_end; buf++)
2444 if (!isspace(*buf))
2445 return 0;
2448 * Update the preimage and the common postimage context
2449 * lines to use the same whitespace as the target.
2450 * If whitespace is missing in the target (i.e.
2451 * if the preimage extends beyond the end of the file),
2452 * use the whitespace from the preimage.
2454 extra_chars = preimage_end - preimage_eof;
2455 strbuf_init(&fixed, imgoff + extra_chars);
2456 strbuf_add(&fixed, img->buf + current, imgoff);
2457 strbuf_add(&fixed, preimage_eof, extra_chars);
2458 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2459 update_pre_post_images(preimage, postimage,
2460 fixed_buf, fixed_len, postlen);
2461 return 1;
2464 static int match_fragment(struct apply_state *state,
2465 struct image *img,
2466 struct image *preimage,
2467 struct image *postimage,
2468 unsigned long current,
2469 int current_lno,
2470 unsigned ws_rule,
2471 int match_beginning, int match_end)
2473 int i;
2474 char *fixed_buf, *buf, *orig, *target;
2475 struct strbuf fixed;
2476 size_t fixed_len, postlen;
2477 int preimage_limit;
2479 if (preimage->nr + current_lno <= img->nr) {
2481 * The hunk falls within the boundaries of img.
2483 preimage_limit = preimage->nr;
2484 if (match_end && (preimage->nr + current_lno != img->nr))
2485 return 0;
2486 } else if (state->ws_error_action == correct_ws_error &&
2487 (ws_rule & WS_BLANK_AT_EOF)) {
2489 * This hunk extends beyond the end of img, and we are
2490 * removing blank lines at the end of the file. This
2491 * many lines from the beginning of the preimage must
2492 * match with img, and the remainder of the preimage
2493 * must be blank.
2495 preimage_limit = img->nr - current_lno;
2496 } else {
2498 * The hunk extends beyond the end of the img and
2499 * we are not removing blanks at the end, so we
2500 * should reject the hunk at this position.
2502 return 0;
2505 if (match_beginning && current_lno)
2506 return 0;
2508 /* Quick hash check */
2509 for (i = 0; i < preimage_limit; i++)
2510 if ((img->line[current_lno + i].flag & LINE_PATCHED) ||
2511 (preimage->line[i].hash != img->line[current_lno + i].hash))
2512 return 0;
2514 if (preimage_limit == preimage->nr) {
2516 * Do we have an exact match? If we were told to match
2517 * at the end, size must be exactly at current+fragsize,
2518 * otherwise current+fragsize must be still within the preimage,
2519 * and either case, the old piece should match the preimage
2520 * exactly.
2522 if ((match_end
2523 ? (current + preimage->len == img->len)
2524 : (current + preimage->len <= img->len)) &&
2525 !memcmp(img->buf + current, preimage->buf, preimage->len))
2526 return 1;
2527 } else {
2529 * The preimage extends beyond the end of img, so
2530 * there cannot be an exact match.
2532 * There must be one non-blank context line that match
2533 * a line before the end of img.
2535 char *buf_end;
2537 buf = preimage->buf;
2538 buf_end = buf;
2539 for (i = 0; i < preimage_limit; i++)
2540 buf_end += preimage->line[i].len;
2542 for ( ; buf < buf_end; buf++)
2543 if (!isspace(*buf))
2544 break;
2545 if (buf == buf_end)
2546 return 0;
2550 * No exact match. If we are ignoring whitespace, run a line-by-line
2551 * fuzzy matching. We collect all the line length information because
2552 * we need it to adjust whitespace if we match.
2554 if (state->ws_ignore_action == ignore_ws_change)
2555 return line_by_line_fuzzy_match(img, preimage, postimage,
2556 current, current_lno, preimage_limit);
2558 if (state->ws_error_action != correct_ws_error)
2559 return 0;
2562 * The hunk does not apply byte-by-byte, but the hash says
2563 * it might with whitespace fuzz. We weren't asked to
2564 * ignore whitespace, we were asked to correct whitespace
2565 * errors, so let's try matching after whitespace correction.
2567 * While checking the preimage against the target, whitespace
2568 * errors in both fixed, we count how large the corresponding
2569 * postimage needs to be. The postimage prepared by
2570 * apply_one_fragment() has whitespace errors fixed on added
2571 * lines already, but the common lines were propagated as-is,
2572 * which may become longer when their whitespace errors are
2573 * fixed.
2576 /* First count added lines in postimage */
2577 postlen = 0;
2578 for (i = 0; i < postimage->nr; i++) {
2579 if (!(postimage->line[i].flag & LINE_COMMON))
2580 postlen += postimage->line[i].len;
2584 * The preimage may extend beyond the end of the file,
2585 * but in this loop we will only handle the part of the
2586 * preimage that falls within the file.
2588 strbuf_init(&fixed, preimage->len + 1);
2589 orig = preimage->buf;
2590 target = img->buf + current;
2591 for (i = 0; i < preimage_limit; i++) {
2592 size_t oldlen = preimage->line[i].len;
2593 size_t tgtlen = img->line[current_lno + i].len;
2594 size_t fixstart = fixed.len;
2595 struct strbuf tgtfix;
2596 int match;
2598 /* Try fixing the line in the preimage */
2599 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2601 /* Try fixing the line in the target */
2602 strbuf_init(&tgtfix, tgtlen);
2603 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2606 * If they match, either the preimage was based on
2607 * a version before our tree fixed whitespace breakage,
2608 * or we are lacking a whitespace-fix patch the tree
2609 * the preimage was based on already had (i.e. target
2610 * has whitespace breakage, the preimage doesn't).
2611 * In either case, we are fixing the whitespace breakages
2612 * so we might as well take the fix together with their
2613 * real change.
2615 match = (tgtfix.len == fixed.len - fixstart &&
2616 !memcmp(tgtfix.buf, fixed.buf + fixstart,
2617 fixed.len - fixstart));
2619 /* Add the length if this is common with the postimage */
2620 if (preimage->line[i].flag & LINE_COMMON)
2621 postlen += tgtfix.len;
2623 strbuf_release(&tgtfix);
2624 if (!match)
2625 goto unmatch_exit;
2627 orig += oldlen;
2628 target += tgtlen;
2633 * Now handle the lines in the preimage that falls beyond the
2634 * end of the file (if any). They will only match if they are
2635 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2636 * false).
2638 for ( ; i < preimage->nr; i++) {
2639 size_t fixstart = fixed.len; /* start of the fixed preimage */
2640 size_t oldlen = preimage->line[i].len;
2641 int j;
2643 /* Try fixing the line in the preimage */
2644 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2646 for (j = fixstart; j < fixed.len; j++)
2647 if (!isspace(fixed.buf[j]))
2648 goto unmatch_exit;
2650 orig += oldlen;
2654 * Yes, the preimage is based on an older version that still
2655 * has whitespace breakages unfixed, and fixing them makes the
2656 * hunk match. Update the context lines in the postimage.
2658 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2659 if (postlen < postimage->len)
2660 postlen = 0;
2661 update_pre_post_images(preimage, postimage,
2662 fixed_buf, fixed_len, postlen);
2663 return 1;
2665 unmatch_exit:
2666 strbuf_release(&fixed);
2667 return 0;
2670 static int find_pos(struct apply_state *state,
2671 struct image *img,
2672 struct image *preimage,
2673 struct image *postimage,
2674 int line,
2675 unsigned ws_rule,
2676 int match_beginning, int match_end)
2678 int i;
2679 unsigned long backwards, forwards, current;
2680 int backwards_lno, forwards_lno, current_lno;
2683 * When running with --allow-overlap, it is possible that a hunk is
2684 * seen that pretends to start at the beginning (but no longer does),
2685 * and that *still* needs to match the end. So trust `match_end` more
2686 * than `match_beginning`.
2688 if (state->allow_overlap && match_beginning && match_end &&
2689 img->nr - preimage->nr != 0)
2690 match_beginning = 0;
2693 * If match_beginning or match_end is specified, there is no
2694 * point starting from a wrong line that will never match and
2695 * wander around and wait for a match at the specified end.
2697 if (match_beginning)
2698 line = 0;
2699 else if (match_end)
2700 line = img->nr - preimage->nr;
2703 * Because the comparison is unsigned, the following test
2704 * will also take care of a negative line number that can
2705 * result when match_end and preimage is larger than the target.
2707 if ((size_t) line > img->nr)
2708 line = img->nr;
2710 current = 0;
2711 for (i = 0; i < line; i++)
2712 current += img->line[i].len;
2715 * There's probably some smart way to do this, but I'll leave
2716 * that to the smart and beautiful people. I'm simple and stupid.
2718 backwards = current;
2719 backwards_lno = line;
2720 forwards = current;
2721 forwards_lno = line;
2722 current_lno = line;
2724 for (i = 0; ; i++) {
2725 if (match_fragment(state, img, preimage, postimage,
2726 current, current_lno, ws_rule,
2727 match_beginning, match_end))
2728 return current_lno;
2730 again:
2731 if (backwards_lno == 0 && forwards_lno == img->nr)
2732 break;
2734 if (i & 1) {
2735 if (backwards_lno == 0) {
2736 i++;
2737 goto again;
2739 backwards_lno--;
2740 backwards -= img->line[backwards_lno].len;
2741 current = backwards;
2742 current_lno = backwards_lno;
2743 } else {
2744 if (forwards_lno == img->nr) {
2745 i++;
2746 goto again;
2748 forwards += img->line[forwards_lno].len;
2749 forwards_lno++;
2750 current = forwards;
2751 current_lno = forwards_lno;
2755 return -1;
2758 static void remove_first_line(struct image *img)
2760 img->buf += img->line[0].len;
2761 img->len -= img->line[0].len;
2762 img->line++;
2763 img->nr--;
2766 static void remove_last_line(struct image *img)
2768 img->len -= img->line[--img->nr].len;
2772 * The change from "preimage" and "postimage" has been found to
2773 * apply at applied_pos (counts in line numbers) in "img".
2774 * Update "img" to remove "preimage" and replace it with "postimage".
2776 static void update_image(struct apply_state *state,
2777 struct image *img,
2778 int applied_pos,
2779 struct image *preimage,
2780 struct image *postimage)
2783 * remove the copy of preimage at offset in img
2784 * and replace it with postimage
2786 int i, nr;
2787 size_t remove_count, insert_count, applied_at = 0;
2788 char *result;
2789 int preimage_limit;
2792 * If we are removing blank lines at the end of img,
2793 * the preimage may extend beyond the end.
2794 * If that is the case, we must be careful only to
2795 * remove the part of the preimage that falls within
2796 * the boundaries of img. Initialize preimage_limit
2797 * to the number of lines in the preimage that falls
2798 * within the boundaries.
2800 preimage_limit = preimage->nr;
2801 if (preimage_limit > img->nr - applied_pos)
2802 preimage_limit = img->nr - applied_pos;
2804 for (i = 0; i < applied_pos; i++)
2805 applied_at += img->line[i].len;
2807 remove_count = 0;
2808 for (i = 0; i < preimage_limit; i++)
2809 remove_count += img->line[applied_pos + i].len;
2810 insert_count = postimage->len;
2812 /* Adjust the contents */
2813 result = xmalloc(st_add3(st_sub(img->len, remove_count), insert_count, 1));
2814 memcpy(result, img->buf, applied_at);
2815 memcpy(result + applied_at, postimage->buf, postimage->len);
2816 memcpy(result + applied_at + postimage->len,
2817 img->buf + (applied_at + remove_count),
2818 img->len - (applied_at + remove_count));
2819 free(img->buf);
2820 img->buf = result;
2821 img->len += insert_count - remove_count;
2822 result[img->len] = '\0';
2824 /* Adjust the line table */
2825 nr = img->nr + postimage->nr - preimage_limit;
2826 if (preimage_limit < postimage->nr) {
2828 * NOTE: this knows that we never call remove_first_line()
2829 * on anything other than pre/post image.
2831 REALLOC_ARRAY(img->line, nr);
2832 img->line_allocated = img->line;
2834 if (preimage_limit != postimage->nr)
2835 MOVE_ARRAY(img->line + applied_pos + postimage->nr,
2836 img->line + applied_pos + preimage_limit,
2837 img->nr - (applied_pos + preimage_limit));
2838 COPY_ARRAY(img->line + applied_pos, postimage->line, postimage->nr);
2839 if (!state->allow_overlap)
2840 for (i = 0; i < postimage->nr; i++)
2841 img->line[applied_pos + i].flag |= LINE_PATCHED;
2842 img->nr = nr;
2846 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2847 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2848 * replace the part of "img" with "postimage" text.
2850 static int apply_one_fragment(struct apply_state *state,
2851 struct image *img, struct fragment *frag,
2852 int inaccurate_eof, unsigned ws_rule,
2853 int nth_fragment)
2855 int match_beginning, match_end;
2856 const char *patch = frag->patch;
2857 int size = frag->size;
2858 char *old, *oldlines;
2859 struct strbuf newlines;
2860 int new_blank_lines_at_end = 0;
2861 int found_new_blank_lines_at_end = 0;
2862 int hunk_linenr = frag->linenr;
2863 unsigned long leading, trailing;
2864 int pos, applied_pos;
2865 struct image preimage;
2866 struct image postimage;
2868 memset(&preimage, 0, sizeof(preimage));
2869 memset(&postimage, 0, sizeof(postimage));
2870 oldlines = xmalloc(size);
2871 strbuf_init(&newlines, size);
2873 old = oldlines;
2874 while (size > 0) {
2875 char first;
2876 int len = linelen(patch, size);
2877 int plen;
2878 int added_blank_line = 0;
2879 int is_blank_context = 0;
2880 size_t start;
2882 if (!len)
2883 break;
2886 * "plen" is how much of the line we should use for
2887 * the actual patch data. Normally we just remove the
2888 * first character on the line, but if the line is
2889 * followed by "\ No newline", then we also remove the
2890 * last one (which is the newline, of course).
2892 plen = len - 1;
2893 if (len < size && patch[len] == '\\')
2894 plen--;
2895 first = *patch;
2896 if (state->apply_in_reverse) {
2897 if (first == '-')
2898 first = '+';
2899 else if (first == '+')
2900 first = '-';
2903 switch (first) {
2904 case '\n':
2905 /* Newer GNU diff, empty context line */
2906 if (plen < 0)
2907 /* ... followed by '\No newline'; nothing */
2908 break;
2909 *old++ = '\n';
2910 strbuf_addch(&newlines, '\n');
2911 add_line_info(&preimage, "\n", 1, LINE_COMMON);
2912 add_line_info(&postimage, "\n", 1, LINE_COMMON);
2913 is_blank_context = 1;
2914 break;
2915 case ' ':
2916 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2917 ws_blank_line(patch + 1, plen))
2918 is_blank_context = 1;
2919 /* fallthrough */
2920 case '-':
2921 memcpy(old, patch + 1, plen);
2922 add_line_info(&preimage, old, plen,
2923 (first == ' ' ? LINE_COMMON : 0));
2924 old += plen;
2925 if (first == '-')
2926 break;
2927 /* fallthrough */
2928 case '+':
2929 /* --no-add does not add new lines */
2930 if (first == '+' && state->no_add)
2931 break;
2933 start = newlines.len;
2934 if (first != '+' ||
2935 !state->whitespace_error ||
2936 state->ws_error_action != correct_ws_error) {
2937 strbuf_add(&newlines, patch + 1, plen);
2939 else {
2940 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &state->applied_after_fixing_ws);
2942 add_line_info(&postimage, newlines.buf + start, newlines.len - start,
2943 (first == '+' ? 0 : LINE_COMMON));
2944 if (first == '+' &&
2945 (ws_rule & WS_BLANK_AT_EOF) &&
2946 ws_blank_line(patch + 1, plen))
2947 added_blank_line = 1;
2948 break;
2949 case '@': case '\\':
2950 /* Ignore it, we already handled it */
2951 break;
2952 default:
2953 if (state->apply_verbosity > verbosity_normal)
2954 error(_("invalid start of line: '%c'"), first);
2955 applied_pos = -1;
2956 goto out;
2958 if (added_blank_line) {
2959 if (!new_blank_lines_at_end)
2960 found_new_blank_lines_at_end = hunk_linenr;
2961 new_blank_lines_at_end++;
2963 else if (is_blank_context)
2965 else
2966 new_blank_lines_at_end = 0;
2967 patch += len;
2968 size -= len;
2969 hunk_linenr++;
2971 if (inaccurate_eof &&
2972 old > oldlines && old[-1] == '\n' &&
2973 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
2974 old--;
2975 strbuf_setlen(&newlines, newlines.len - 1);
2976 preimage.line_allocated[preimage.nr - 1].len--;
2977 postimage.line_allocated[postimage.nr - 1].len--;
2980 leading = frag->leading;
2981 trailing = frag->trailing;
2984 * A hunk to change lines at the beginning would begin with
2985 * @@ -1,L +N,M @@
2986 * but we need to be careful. -U0 that inserts before the second
2987 * line also has this pattern.
2989 * And a hunk to add to an empty file would begin with
2990 * @@ -0,0 +N,M @@
2992 * In other words, a hunk that is (frag->oldpos <= 1) with or
2993 * without leading context must match at the beginning.
2995 match_beginning = (!frag->oldpos ||
2996 (frag->oldpos == 1 && !state->unidiff_zero));
2999 * A hunk without trailing lines must match at the end.
3000 * However, we simply cannot tell if a hunk must match end
3001 * from the lack of trailing lines if the patch was generated
3002 * with unidiff without any context.
3004 match_end = !state->unidiff_zero && !trailing;
3006 pos = frag->newpos ? (frag->newpos - 1) : 0;
3007 preimage.buf = oldlines;
3008 preimage.len = old - oldlines;
3009 postimage.buf = newlines.buf;
3010 postimage.len = newlines.len;
3011 preimage.line = preimage.line_allocated;
3012 postimage.line = postimage.line_allocated;
3014 for (;;) {
3016 applied_pos = find_pos(state, img, &preimage, &postimage, pos,
3017 ws_rule, match_beginning, match_end);
3019 if (applied_pos >= 0)
3020 break;
3022 /* Am I at my context limits? */
3023 if ((leading <= state->p_context) && (trailing <= state->p_context))
3024 break;
3025 if (match_beginning || match_end) {
3026 match_beginning = match_end = 0;
3027 continue;
3031 * Reduce the number of context lines; reduce both
3032 * leading and trailing if they are equal otherwise
3033 * just reduce the larger context.
3035 if (leading >= trailing) {
3036 remove_first_line(&preimage);
3037 remove_first_line(&postimage);
3038 pos--;
3039 leading--;
3041 if (trailing > leading) {
3042 remove_last_line(&preimage);
3043 remove_last_line(&postimage);
3044 trailing--;
3048 if (applied_pos >= 0) {
3049 if (new_blank_lines_at_end &&
3050 preimage.nr + applied_pos >= img->nr &&
3051 (ws_rule & WS_BLANK_AT_EOF) &&
3052 state->ws_error_action != nowarn_ws_error) {
3053 record_ws_error(state, WS_BLANK_AT_EOF, "+", 1,
3054 found_new_blank_lines_at_end);
3055 if (state->ws_error_action == correct_ws_error) {
3056 while (new_blank_lines_at_end--)
3057 remove_last_line(&postimage);
3060 * We would want to prevent write_out_results()
3061 * from taking place in apply_patch() that follows
3062 * the callchain led us here, which is:
3063 * apply_patch->check_patch_list->check_patch->
3064 * apply_data->apply_fragments->apply_one_fragment
3066 if (state->ws_error_action == die_on_ws_error)
3067 state->apply = 0;
3070 if (state->apply_verbosity > verbosity_normal && applied_pos != pos) {
3071 int offset = applied_pos - pos;
3072 if (state->apply_in_reverse)
3073 offset = 0 - offset;
3074 fprintf_ln(stderr,
3075 Q_("Hunk #%d succeeded at %d (offset %d line).",
3076 "Hunk #%d succeeded at %d (offset %d lines).",
3077 offset),
3078 nth_fragment, applied_pos + 1, offset);
3082 * Warn if it was necessary to reduce the number
3083 * of context lines.
3085 if ((leading != frag->leading ||
3086 trailing != frag->trailing) && state->apply_verbosity > verbosity_silent)
3087 fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"
3088 " to apply fragment at %d"),
3089 leading, trailing, applied_pos+1);
3090 update_image(state, img, applied_pos, &preimage, &postimage);
3091 } else {
3092 if (state->apply_verbosity > verbosity_normal)
3093 error(_("while searching for:\n%.*s"),
3094 (int)(old - oldlines), oldlines);
3097 out:
3098 free(oldlines);
3099 strbuf_release(&newlines);
3100 free(preimage.line_allocated);
3101 free(postimage.line_allocated);
3103 return (applied_pos < 0);
3106 static int apply_binary_fragment(struct apply_state *state,
3107 struct image *img,
3108 struct patch *patch)
3110 struct fragment *fragment = patch->fragments;
3111 unsigned long len;
3112 void *dst;
3114 if (!fragment)
3115 return error(_("missing binary patch data for '%s'"),
3116 patch->new_name ?
3117 patch->new_name :
3118 patch->old_name);
3120 /* Binary patch is irreversible without the optional second hunk */
3121 if (state->apply_in_reverse) {
3122 if (!fragment->next)
3123 return error(_("cannot reverse-apply a binary patch "
3124 "without the reverse hunk to '%s'"),
3125 patch->new_name
3126 ? patch->new_name : patch->old_name);
3127 fragment = fragment->next;
3129 switch (fragment->binary_patch_method) {
3130 case BINARY_DELTA_DEFLATED:
3131 dst = patch_delta(img->buf, img->len, fragment->patch,
3132 fragment->size, &len);
3133 if (!dst)
3134 return -1;
3135 clear_image(img);
3136 img->buf = dst;
3137 img->len = len;
3138 return 0;
3139 case BINARY_LITERAL_DEFLATED:
3140 clear_image(img);
3141 img->len = fragment->size;
3142 img->buf = xmemdupz(fragment->patch, img->len);
3143 return 0;
3145 return -1;
3149 * Replace "img" with the result of applying the binary patch.
3150 * The binary patch data itself in patch->fragment is still kept
3151 * but the preimage prepared by the caller in "img" is freed here
3152 * or in the helper function apply_binary_fragment() this calls.
3154 static int apply_binary(struct apply_state *state,
3155 struct image *img,
3156 struct patch *patch)
3158 const char *name = patch->old_name ? patch->old_name : patch->new_name;
3159 struct object_id oid;
3160 const unsigned hexsz = the_hash_algo->hexsz;
3163 * For safety, we require patch index line to contain
3164 * full hex textual object ID for old and new, at least for now.
3166 if (strlen(patch->old_oid_prefix) != hexsz ||
3167 strlen(patch->new_oid_prefix) != hexsz ||
3168 get_oid_hex(patch->old_oid_prefix, &oid) ||
3169 get_oid_hex(patch->new_oid_prefix, &oid))
3170 return error(_("cannot apply binary patch to '%s' "
3171 "without full index line"), name);
3173 if (patch->old_name) {
3175 * See if the old one matches what the patch
3176 * applies to.
3178 hash_object_file(the_hash_algo, img->buf, img->len, OBJ_BLOB,
3179 &oid);
3180 if (strcmp(oid_to_hex(&oid), patch->old_oid_prefix))
3181 return error(_("the patch applies to '%s' (%s), "
3182 "which does not match the "
3183 "current contents."),
3184 name, oid_to_hex(&oid));
3186 else {
3187 /* Otherwise, the old one must be empty. */
3188 if (img->len)
3189 return error(_("the patch applies to an empty "
3190 "'%s' but it is not empty"), name);
3193 get_oid_hex(patch->new_oid_prefix, &oid);
3194 if (is_null_oid(&oid)) {
3195 clear_image(img);
3196 return 0; /* deletion patch */
3199 if (has_object(the_repository, &oid, 0)) {
3200 /* We already have the postimage */
3201 enum object_type type;
3202 unsigned long size;
3203 char *result;
3205 result = read_object_file(&oid, &type, &size);
3206 if (!result)
3207 return error(_("the necessary postimage %s for "
3208 "'%s' cannot be read"),
3209 patch->new_oid_prefix, name);
3210 clear_image(img);
3211 img->buf = result;
3212 img->len = size;
3213 } else {
3215 * We have verified buf matches the preimage;
3216 * apply the patch data to it, which is stored
3217 * in the patch->fragments->{patch,size}.
3219 if (apply_binary_fragment(state, img, patch))
3220 return error(_("binary patch does not apply to '%s'"),
3221 name);
3223 /* verify that the result matches */
3224 hash_object_file(the_hash_algo, img->buf, img->len, OBJ_BLOB,
3225 &oid);
3226 if (strcmp(oid_to_hex(&oid), patch->new_oid_prefix))
3227 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3228 name, patch->new_oid_prefix, oid_to_hex(&oid));
3231 return 0;
3234 static int apply_fragments(struct apply_state *state, struct image *img, struct patch *patch)
3236 struct fragment *frag = patch->fragments;
3237 const char *name = patch->old_name ? patch->old_name : patch->new_name;
3238 unsigned ws_rule = patch->ws_rule;
3239 unsigned inaccurate_eof = patch->inaccurate_eof;
3240 int nth = 0;
3242 if (patch->is_binary)
3243 return apply_binary(state, img, patch);
3245 while (frag) {
3246 nth++;
3247 if (apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {
3248 error(_("patch failed: %s:%ld"), name, frag->oldpos);
3249 if (!state->apply_with_reject)
3250 return -1;
3251 frag->rejected = 1;
3253 frag = frag->next;
3255 return 0;
3258 static int read_blob_object(struct strbuf *buf, const struct object_id *oid, unsigned mode)
3260 if (S_ISGITLINK(mode)) {
3261 strbuf_grow(buf, 100);
3262 strbuf_addf(buf, "Subproject commit %s\n", oid_to_hex(oid));
3263 } else {
3264 enum object_type type;
3265 unsigned long sz;
3266 char *result;
3268 result = read_object_file(oid, &type, &sz);
3269 if (!result)
3270 return -1;
3271 /* XXX read_sha1_file NUL-terminates */
3272 strbuf_attach(buf, result, sz, sz + 1);
3274 return 0;
3277 static int read_file_or_gitlink(const struct cache_entry *ce, struct strbuf *buf)
3279 if (!ce)
3280 return 0;
3281 return read_blob_object(buf, &ce->oid, ce->ce_mode);
3284 static struct patch *in_fn_table(struct apply_state *state, const char *name)
3286 struct string_list_item *item;
3288 if (!name)
3289 return NULL;
3291 item = string_list_lookup(&state->fn_table, name);
3292 if (item)
3293 return (struct patch *)item->util;
3295 return NULL;
3299 * item->util in the filename table records the status of the path.
3300 * Usually it points at a patch (whose result records the contents
3301 * of it after applying it), but it could be PATH_WAS_DELETED for a
3302 * path that a previously applied patch has already removed, or
3303 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3305 * The latter is needed to deal with a case where two paths A and B
3306 * are swapped by first renaming A to B and then renaming B to A;
3307 * moving A to B should not be prevented due to presence of B as we
3308 * will remove it in a later patch.
3310 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3311 #define PATH_WAS_DELETED ((struct patch *) -1)
3313 static int to_be_deleted(struct patch *patch)
3315 return patch == PATH_TO_BE_DELETED;
3318 static int was_deleted(struct patch *patch)
3320 return patch == PATH_WAS_DELETED;
3323 static void add_to_fn_table(struct apply_state *state, struct patch *patch)
3325 struct string_list_item *item;
3328 * Always add new_name unless patch is a deletion
3329 * This should cover the cases for normal diffs,
3330 * file creations and copies
3332 if (patch->new_name) {
3333 item = string_list_insert(&state->fn_table, patch->new_name);
3334 item->util = patch;
3338 * store a failure on rename/deletion cases because
3339 * later chunks shouldn't patch old names
3341 if ((patch->new_name == NULL) || (patch->is_rename)) {
3342 item = string_list_insert(&state->fn_table, patch->old_name);
3343 item->util = PATH_WAS_DELETED;
3347 static void prepare_fn_table(struct apply_state *state, struct patch *patch)
3350 * store information about incoming file deletion
3352 while (patch) {
3353 if ((patch->new_name == NULL) || (patch->is_rename)) {
3354 struct string_list_item *item;
3355 item = string_list_insert(&state->fn_table, patch->old_name);
3356 item->util = PATH_TO_BE_DELETED;
3358 patch = patch->next;
3362 static int checkout_target(struct index_state *istate,
3363 struct cache_entry *ce, struct stat *st)
3365 struct checkout costate = CHECKOUT_INIT;
3367 costate.refresh_cache = 1;
3368 costate.istate = istate;
3369 if (checkout_entry(ce, &costate, NULL, NULL) ||
3370 lstat(ce->name, st))
3371 return error(_("cannot checkout %s"), ce->name);
3372 return 0;
3375 static struct patch *previous_patch(struct apply_state *state,
3376 struct patch *patch,
3377 int *gone)
3379 struct patch *previous;
3381 *gone = 0;
3382 if (patch->is_copy || patch->is_rename)
3383 return NULL; /* "git" patches do not depend on the order */
3385 previous = in_fn_table(state, patch->old_name);
3386 if (!previous)
3387 return NULL;
3389 if (to_be_deleted(previous))
3390 return NULL; /* the deletion hasn't happened yet */
3392 if (was_deleted(previous))
3393 *gone = 1;
3395 return previous;
3398 static int verify_index_match(struct apply_state *state,
3399 const struct cache_entry *ce,
3400 struct stat *st)
3402 if (S_ISGITLINK(ce->ce_mode)) {
3403 if (!S_ISDIR(st->st_mode))
3404 return -1;
3405 return 0;
3407 return ie_match_stat(state->repo->index, ce, st,
3408 CE_MATCH_IGNORE_VALID | CE_MATCH_IGNORE_SKIP_WORKTREE);
3411 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3413 static int load_patch_target(struct apply_state *state,
3414 struct strbuf *buf,
3415 const struct cache_entry *ce,
3416 struct stat *st,
3417 struct patch *patch,
3418 const char *name,
3419 unsigned expected_mode)
3421 if (state->cached || state->check_index) {
3422 if (read_file_or_gitlink(ce, buf))
3423 return error(_("failed to read %s"), name);
3424 } else if (name) {
3425 if (S_ISGITLINK(expected_mode)) {
3426 if (ce)
3427 return read_file_or_gitlink(ce, buf);
3428 else
3429 return SUBMODULE_PATCH_WITHOUT_INDEX;
3430 } else if (has_symlink_leading_path(name, strlen(name))) {
3431 return error(_("reading from '%s' beyond a symbolic link"), name);
3432 } else {
3433 if (read_old_data(st, patch, name, buf))
3434 return error(_("failed to read %s"), name);
3437 return 0;
3441 * We are about to apply "patch"; populate the "image" with the
3442 * current version we have, from the working tree or from the index,
3443 * depending on the situation e.g. --cached/--index. If we are
3444 * applying a non-git patch that incrementally updates the tree,
3445 * we read from the result of a previous diff.
3447 static int load_preimage(struct apply_state *state,
3448 struct image *image,
3449 struct patch *patch, struct stat *st,
3450 const struct cache_entry *ce)
3452 struct strbuf buf = STRBUF_INIT;
3453 size_t len;
3454 char *img;
3455 struct patch *previous;
3456 int status;
3458 previous = previous_patch(state, patch, &status);
3459 if (status)
3460 return error(_("path %s has been renamed/deleted"),
3461 patch->old_name);
3462 if (previous) {
3463 /* We have a patched copy in memory; use that. */
3464 strbuf_add(&buf, previous->result, previous->resultsize);
3465 } else {
3466 status = load_patch_target(state, &buf, ce, st, patch,
3467 patch->old_name, patch->old_mode);
3468 if (status < 0)
3469 return status;
3470 else if (status == SUBMODULE_PATCH_WITHOUT_INDEX) {
3472 * There is no way to apply subproject
3473 * patch without looking at the index.
3474 * NEEDSWORK: shouldn't this be flagged
3475 * as an error???
3477 free_fragment_list(patch->fragments);
3478 patch->fragments = NULL;
3479 } else if (status) {
3480 return error(_("failed to read %s"), patch->old_name);
3484 img = strbuf_detach(&buf, &len);
3485 prepare_image(image, img, len, !patch->is_binary);
3486 return 0;
3489 static int resolve_to(struct image *image, const struct object_id *result_id)
3491 unsigned long size;
3492 enum object_type type;
3494 clear_image(image);
3496 image->buf = read_object_file(result_id, &type, &size);
3497 if (!image->buf || type != OBJ_BLOB)
3498 die("unable to read blob object %s", oid_to_hex(result_id));
3499 image->len = size;
3501 return 0;
3504 static int three_way_merge(struct apply_state *state,
3505 struct image *image,
3506 char *path,
3507 const struct object_id *base,
3508 const struct object_id *ours,
3509 const struct object_id *theirs)
3511 mmfile_t base_file, our_file, their_file;
3512 mmbuffer_t result = { NULL };
3513 enum ll_merge_result status;
3515 /* resolve trivial cases first */
3516 if (oideq(base, ours))
3517 return resolve_to(image, theirs);
3518 else if (oideq(base, theirs) || oideq(ours, theirs))
3519 return resolve_to(image, ours);
3521 read_mmblob(&base_file, base);
3522 read_mmblob(&our_file, ours);
3523 read_mmblob(&their_file, theirs);
3524 status = ll_merge(&result, path,
3525 &base_file, "base",
3526 &our_file, "ours",
3527 &their_file, "theirs",
3528 state->repo->index,
3529 NULL);
3530 if (status == LL_MERGE_BINARY_CONFLICT)
3531 warning("Cannot merge binary files: %s (%s vs. %s)",
3532 path, "ours", "theirs");
3533 free(base_file.ptr);
3534 free(our_file.ptr);
3535 free(their_file.ptr);
3536 if (status < 0 || !result.ptr) {
3537 free(result.ptr);
3538 return -1;
3540 clear_image(image);
3541 image->buf = result.ptr;
3542 image->len = result.size;
3544 return status;
3548 * When directly falling back to add/add three-way merge, we read from
3549 * the current contents of the new_name. In no cases other than that
3550 * this function will be called.
3552 static int load_current(struct apply_state *state,
3553 struct image *image,
3554 struct patch *patch)
3556 struct strbuf buf = STRBUF_INIT;
3557 int status, pos;
3558 size_t len;
3559 char *img;
3560 struct stat st;
3561 struct cache_entry *ce;
3562 char *name = patch->new_name;
3563 unsigned mode = patch->new_mode;
3565 if (!patch->is_new)
3566 BUG("patch to %s is not a creation", patch->old_name);
3568 pos = index_name_pos(state->repo->index, name, strlen(name));
3569 if (pos < 0)
3570 return error(_("%s: does not exist in index"), name);
3571 ce = state->repo->index->cache[pos];
3572 if (lstat(name, &st)) {
3573 if (errno != ENOENT)
3574 return error_errno("%s", name);
3575 if (checkout_target(state->repo->index, ce, &st))
3576 return -1;
3578 if (verify_index_match(state, ce, &st))
3579 return error(_("%s: does not match index"), name);
3581 status = load_patch_target(state, &buf, ce, &st, patch, name, mode);
3582 if (status < 0)
3583 return status;
3584 else if (status)
3585 return -1;
3586 img = strbuf_detach(&buf, &len);
3587 prepare_image(image, img, len, !patch->is_binary);
3588 return 0;
3591 static int try_threeway(struct apply_state *state,
3592 struct image *image,
3593 struct patch *patch,
3594 struct stat *st,
3595 const struct cache_entry *ce)
3597 struct object_id pre_oid, post_oid, our_oid;
3598 struct strbuf buf = STRBUF_INIT;
3599 size_t len;
3600 int status;
3601 char *img;
3602 struct image tmp_image;
3604 /* No point falling back to 3-way merge in these cases */
3605 if (patch->is_delete ||
3606 S_ISGITLINK(patch->old_mode) || S_ISGITLINK(patch->new_mode) ||
3607 (patch->is_new && !patch->direct_to_threeway) ||
3608 (patch->is_rename && !patch->lines_added && !patch->lines_deleted))
3609 return -1;
3611 /* Preimage the patch was prepared for */
3612 if (patch->is_new)
3613 write_object_file("", 0, OBJ_BLOB, &pre_oid);
3614 else if (get_oid(patch->old_oid_prefix, &pre_oid) ||
3615 read_blob_object(&buf, &pre_oid, patch->old_mode))
3616 return error(_("repository lacks the necessary blob to perform 3-way merge."));
3618 if (state->apply_verbosity > verbosity_silent && patch->direct_to_threeway)
3619 fprintf(stderr, _("Performing three-way merge...\n"));
3621 img = strbuf_detach(&buf, &len);
3622 prepare_image(&tmp_image, img, len, 1);
3623 /* Apply the patch to get the post image */
3624 if (apply_fragments(state, &tmp_image, patch) < 0) {
3625 clear_image(&tmp_image);
3626 return -1;
3628 /* post_oid is theirs */
3629 write_object_file(tmp_image.buf, tmp_image.len, OBJ_BLOB, &post_oid);
3630 clear_image(&tmp_image);
3632 /* our_oid is ours */
3633 if (patch->is_new) {
3634 if (load_current(state, &tmp_image, patch))
3635 return error(_("cannot read the current contents of '%s'"),
3636 patch->new_name);
3637 } else {
3638 if (load_preimage(state, &tmp_image, patch, st, ce))
3639 return error(_("cannot read the current contents of '%s'"),
3640 patch->old_name);
3642 write_object_file(tmp_image.buf, tmp_image.len, OBJ_BLOB, &our_oid);
3643 clear_image(&tmp_image);
3645 /* in-core three-way merge between post and our using pre as base */
3646 status = three_way_merge(state, image, patch->new_name,
3647 &pre_oid, &our_oid, &post_oid);
3648 if (status < 0) {
3649 if (state->apply_verbosity > verbosity_silent)
3650 fprintf(stderr,
3651 _("Failed to perform three-way merge...\n"));
3652 return status;
3655 if (status) {
3656 patch->conflicted_threeway = 1;
3657 if (patch->is_new)
3658 oidclr(&patch->threeway_stage[0]);
3659 else
3660 oidcpy(&patch->threeway_stage[0], &pre_oid);
3661 oidcpy(&patch->threeway_stage[1], &our_oid);
3662 oidcpy(&patch->threeway_stage[2], &post_oid);
3663 if (state->apply_verbosity > verbosity_silent)
3664 fprintf(stderr,
3665 _("Applied patch to '%s' with conflicts.\n"),
3666 patch->new_name);
3667 } else {
3668 if (state->apply_verbosity > verbosity_silent)
3669 fprintf(stderr,
3670 _("Applied patch to '%s' cleanly.\n"),
3671 patch->new_name);
3673 return 0;
3676 static int apply_data(struct apply_state *state, struct patch *patch,
3677 struct stat *st, const struct cache_entry *ce)
3679 struct image image;
3681 if (load_preimage(state, &image, patch, st, ce) < 0)
3682 return -1;
3684 if (!state->threeway || try_threeway(state, &image, patch, st, ce) < 0) {
3685 if (state->apply_verbosity > verbosity_silent &&
3686 state->threeway && !patch->direct_to_threeway)
3687 fprintf(stderr, _("Falling back to direct application...\n"));
3689 /* Note: with --reject, apply_fragments() returns 0 */
3690 if (patch->direct_to_threeway || apply_fragments(state, &image, patch) < 0)
3691 return -1;
3693 patch->result = image.buf;
3694 patch->resultsize = image.len;
3695 add_to_fn_table(state, patch);
3696 free(image.line_allocated);
3698 if (0 < patch->is_delete && patch->resultsize)
3699 return error(_("removal patch leaves file contents"));
3701 return 0;
3705 * If "patch" that we are looking at modifies or deletes what we have,
3706 * we would want it not to lose any local modification we have, either
3707 * in the working tree or in the index.
3709 * This also decides if a non-git patch is a creation patch or a
3710 * modification to an existing empty file. We do not check the state
3711 * of the current tree for a creation patch in this function; the caller
3712 * check_patch() separately makes sure (and errors out otherwise) that
3713 * the path the patch creates does not exist in the current tree.
3715 static int check_preimage(struct apply_state *state,
3716 struct patch *patch,
3717 struct cache_entry **ce,
3718 struct stat *st)
3720 const char *old_name = patch->old_name;
3721 struct patch *previous = NULL;
3722 int stat_ret = 0, status;
3723 unsigned st_mode = 0;
3725 if (!old_name)
3726 return 0;
3728 assert(patch->is_new <= 0);
3729 previous = previous_patch(state, patch, &status);
3731 if (status)
3732 return error(_("path %s has been renamed/deleted"), old_name);
3733 if (previous) {
3734 st_mode = previous->new_mode;
3735 } else if (!state->cached) {
3736 stat_ret = lstat(old_name, st);
3737 if (stat_ret && errno != ENOENT)
3738 return error_errno("%s", old_name);
3741 if (state->check_index && !previous) {
3742 int pos = index_name_pos(state->repo->index, old_name,
3743 strlen(old_name));
3744 if (pos < 0) {
3745 if (patch->is_new < 0)
3746 goto is_new;
3747 return error(_("%s: does not exist in index"), old_name);
3749 *ce = state->repo->index->cache[pos];
3750 if (stat_ret < 0) {
3751 if (checkout_target(state->repo->index, *ce, st))
3752 return -1;
3754 if (!state->cached && verify_index_match(state, *ce, st))
3755 return error(_("%s: does not match index"), old_name);
3756 if (state->cached)
3757 st_mode = (*ce)->ce_mode;
3758 } else if (stat_ret < 0) {
3759 if (patch->is_new < 0)
3760 goto is_new;
3761 return error_errno("%s", old_name);
3764 if (!state->cached && !previous)
3765 st_mode = ce_mode_from_stat(*ce, st->st_mode);
3767 if (patch->is_new < 0)
3768 patch->is_new = 0;
3769 if (!patch->old_mode)
3770 patch->old_mode = st_mode;
3771 if ((st_mode ^ patch->old_mode) & S_IFMT)
3772 return error(_("%s: wrong type"), old_name);
3773 if (st_mode != patch->old_mode)
3774 warning(_("%s has type %o, expected %o"),
3775 old_name, st_mode, patch->old_mode);
3776 if (!patch->new_mode && !patch->is_delete)
3777 patch->new_mode = st_mode;
3778 return 0;
3780 is_new:
3781 patch->is_new = 1;
3782 patch->is_delete = 0;
3783 FREE_AND_NULL(patch->old_name);
3784 return 0;
3788 #define EXISTS_IN_INDEX 1
3789 #define EXISTS_IN_WORKTREE 2
3790 #define EXISTS_IN_INDEX_AS_ITA 3
3792 static int check_to_create(struct apply_state *state,
3793 const char *new_name,
3794 int ok_if_exists)
3796 struct stat nst;
3798 if (state->check_index && (!ok_if_exists || !state->cached)) {
3799 int pos;
3801 pos = index_name_pos(state->repo->index, new_name, strlen(new_name));
3802 if (pos >= 0) {
3803 struct cache_entry *ce = state->repo->index->cache[pos];
3805 /* allow ITA, as they do not yet exist in the index */
3806 if (!ok_if_exists && !(ce->ce_flags & CE_INTENT_TO_ADD))
3807 return EXISTS_IN_INDEX;
3809 /* ITA entries can never match working tree files */
3810 if (!state->cached && (ce->ce_flags & CE_INTENT_TO_ADD))
3811 return EXISTS_IN_INDEX_AS_ITA;
3815 if (state->cached)
3816 return 0;
3818 if (!lstat(new_name, &nst)) {
3819 if (S_ISDIR(nst.st_mode) || ok_if_exists)
3820 return 0;
3822 * A leading component of new_name might be a symlink
3823 * that is going to be removed with this patch, but
3824 * still pointing at somewhere that has the path.
3825 * In such a case, path "new_name" does not exist as
3826 * far as git is concerned.
3828 if (has_symlink_leading_path(new_name, strlen(new_name)))
3829 return 0;
3831 return EXISTS_IN_WORKTREE;
3832 } else if (!is_missing_file_error(errno)) {
3833 return error_errno("%s", new_name);
3835 return 0;
3838 static void prepare_symlink_changes(struct apply_state *state, struct patch *patch)
3840 for ( ; patch; patch = patch->next) {
3841 if ((patch->old_name && S_ISLNK(patch->old_mode)) &&
3842 (patch->is_rename || patch->is_delete))
3843 /* the symlink at patch->old_name is removed */
3844 strset_add(&state->removed_symlinks, patch->old_name);
3846 if (patch->new_name && S_ISLNK(patch->new_mode))
3847 /* the symlink at patch->new_name is created or remains */
3848 strset_add(&state->kept_symlinks, patch->new_name);
3852 static int path_is_beyond_symlink_1(struct apply_state *state, struct strbuf *name)
3854 do {
3855 while (--name->len && name->buf[name->len] != '/')
3856 ; /* scan backwards */
3857 if (!name->len)
3858 break;
3859 name->buf[name->len] = '\0';
3860 if (strset_contains(&state->kept_symlinks, name->buf))
3861 return 1;
3862 if (strset_contains(&state->removed_symlinks, name->buf))
3864 * This cannot be "return 0", because we may
3865 * see a new one created at a higher level.
3867 continue;
3869 /* otherwise, check the preimage */
3870 if (state->check_index) {
3871 struct cache_entry *ce;
3873 ce = index_file_exists(state->repo->index, name->buf,
3874 name->len, ignore_case);
3875 if (ce && S_ISLNK(ce->ce_mode))
3876 return 1;
3877 } else {
3878 struct stat st;
3879 if (!lstat(name->buf, &st) && S_ISLNK(st.st_mode))
3880 return 1;
3882 } while (1);
3883 return 0;
3886 static int path_is_beyond_symlink(struct apply_state *state, const char *name_)
3888 int ret;
3889 struct strbuf name = STRBUF_INIT;
3891 assert(*name_ != '\0');
3892 strbuf_addstr(&name, name_);
3893 ret = path_is_beyond_symlink_1(state, &name);
3894 strbuf_release(&name);
3896 return ret;
3899 static int check_unsafe_path(struct patch *patch)
3901 const char *old_name = NULL;
3902 const char *new_name = NULL;
3903 if (patch->is_delete)
3904 old_name = patch->old_name;
3905 else if (!patch->is_new && !patch->is_copy)
3906 old_name = patch->old_name;
3907 if (!patch->is_delete)
3908 new_name = patch->new_name;
3910 if (old_name && !verify_path(old_name, patch->old_mode))
3911 return error(_("invalid path '%s'"), old_name);
3912 if (new_name && !verify_path(new_name, patch->new_mode))
3913 return error(_("invalid path '%s'"), new_name);
3914 return 0;
3918 * Check and apply the patch in-core; leave the result in patch->result
3919 * for the caller to write it out to the final destination.
3921 static int check_patch(struct apply_state *state, struct patch *patch)
3923 struct stat st;
3924 const char *old_name = patch->old_name;
3925 const char *new_name = patch->new_name;
3926 const char *name = old_name ? old_name : new_name;
3927 struct cache_entry *ce = NULL;
3928 struct patch *tpatch;
3929 int ok_if_exists;
3930 int status;
3932 patch->rejected = 1; /* we will drop this after we succeed */
3934 status = check_preimage(state, patch, &ce, &st);
3935 if (status)
3936 return status;
3937 old_name = patch->old_name;
3940 * A type-change diff is always split into a patch to delete
3941 * old, immediately followed by a patch to create new (see
3942 * diff.c::run_diff()); in such a case it is Ok that the entry
3943 * to be deleted by the previous patch is still in the working
3944 * tree and in the index.
3946 * A patch to swap-rename between A and B would first rename A
3947 * to B and then rename B to A. While applying the first one,
3948 * the presence of B should not stop A from getting renamed to
3949 * B; ask to_be_deleted() about the later rename. Removal of
3950 * B and rename from A to B is handled the same way by asking
3951 * was_deleted().
3953 if ((tpatch = in_fn_table(state, new_name)) &&
3954 (was_deleted(tpatch) || to_be_deleted(tpatch)))
3955 ok_if_exists = 1;
3956 else
3957 ok_if_exists = 0;
3959 if (new_name &&
3960 ((0 < patch->is_new) || patch->is_rename || patch->is_copy)) {
3961 int err = check_to_create(state, new_name, ok_if_exists);
3963 if (err && state->threeway) {
3964 patch->direct_to_threeway = 1;
3965 } else switch (err) {
3966 case 0:
3967 break; /* happy */
3968 case EXISTS_IN_INDEX:
3969 return error(_("%s: already exists in index"), new_name);
3970 case EXISTS_IN_INDEX_AS_ITA:
3971 return error(_("%s: does not match index"), new_name);
3972 case EXISTS_IN_WORKTREE:
3973 return error(_("%s: already exists in working directory"),
3974 new_name);
3975 default:
3976 return err;
3979 if (!patch->new_mode) {
3980 if (0 < patch->is_new)
3981 patch->new_mode = S_IFREG | 0644;
3982 else
3983 patch->new_mode = patch->old_mode;
3987 if (new_name && old_name) {
3988 int same = !strcmp(old_name, new_name);
3989 if (!patch->new_mode)
3990 patch->new_mode = patch->old_mode;
3991 if ((patch->old_mode ^ patch->new_mode) & S_IFMT) {
3992 if (same)
3993 return error(_("new mode (%o) of %s does not "
3994 "match old mode (%o)"),
3995 patch->new_mode, new_name,
3996 patch->old_mode);
3997 else
3998 return error(_("new mode (%o) of %s does not "
3999 "match old mode (%o) of %s"),
4000 patch->new_mode, new_name,
4001 patch->old_mode, old_name);
4005 if (!state->unsafe_paths && check_unsafe_path(patch))
4006 return -128;
4009 * An attempt to read from or delete a path that is beyond a
4010 * symbolic link will be prevented by load_patch_target() that
4011 * is called at the beginning of apply_data() so we do not
4012 * have to worry about a patch marked with "is_delete" bit
4013 * here. We however need to make sure that the patch result
4014 * is not deposited to a path that is beyond a symbolic link
4015 * here.
4017 if (!patch->is_delete && path_is_beyond_symlink(state, patch->new_name))
4018 return error(_("affected file '%s' is beyond a symbolic link"),
4019 patch->new_name);
4021 if (apply_data(state, patch, &st, ce) < 0)
4022 return error(_("%s: patch does not apply"), name);
4023 patch->rejected = 0;
4024 return 0;
4027 static int check_patch_list(struct apply_state *state, struct patch *patch)
4029 int err = 0;
4031 prepare_symlink_changes(state, patch);
4032 prepare_fn_table(state, patch);
4033 while (patch) {
4034 int res;
4035 if (state->apply_verbosity > verbosity_normal)
4036 say_patch_name(stderr,
4037 _("Checking patch %s..."), patch);
4038 res = check_patch(state, patch);
4039 if (res == -128)
4040 return -128;
4041 err |= res;
4042 patch = patch->next;
4044 return err;
4047 static int read_apply_cache(struct apply_state *state)
4049 if (state->index_file)
4050 return read_index_from(state->repo->index, state->index_file,
4051 get_git_dir());
4052 else
4053 return repo_read_index(state->repo);
4056 /* This function tries to read the object name from the current index */
4057 static int get_current_oid(struct apply_state *state, const char *path,
4058 struct object_id *oid)
4060 int pos;
4062 if (read_apply_cache(state) < 0)
4063 return -1;
4064 pos = index_name_pos(state->repo->index, path, strlen(path));
4065 if (pos < 0)
4066 return -1;
4067 oidcpy(oid, &state->repo->index->cache[pos]->oid);
4068 return 0;
4071 static int preimage_oid_in_gitlink_patch(struct patch *p, struct object_id *oid)
4074 * A usable gitlink patch has only one fragment (hunk) that looks like:
4075 * @@ -1 +1 @@
4076 * -Subproject commit <old sha1>
4077 * +Subproject commit <new sha1>
4078 * or
4079 * @@ -1 +0,0 @@
4080 * -Subproject commit <old sha1>
4081 * for a removal patch.
4083 struct fragment *hunk = p->fragments;
4084 static const char heading[] = "-Subproject commit ";
4085 char *preimage;
4087 if (/* does the patch have only one hunk? */
4088 hunk && !hunk->next &&
4089 /* is its preimage one line? */
4090 hunk->oldpos == 1 && hunk->oldlines == 1 &&
4091 /* does preimage begin with the heading? */
4092 (preimage = memchr(hunk->patch, '\n', hunk->size)) != NULL &&
4093 starts_with(++preimage, heading) &&
4094 /* does it record full SHA-1? */
4095 !get_oid_hex(preimage + sizeof(heading) - 1, oid) &&
4096 preimage[sizeof(heading) + the_hash_algo->hexsz - 1] == '\n' &&
4097 /* does the abbreviated name on the index line agree with it? */
4098 starts_with(preimage + sizeof(heading) - 1, p->old_oid_prefix))
4099 return 0; /* it all looks fine */
4101 /* we may have full object name on the index line */
4102 return get_oid_hex(p->old_oid_prefix, oid);
4105 /* Build an index that contains just the files needed for a 3way merge */
4106 static int build_fake_ancestor(struct apply_state *state, struct patch *list)
4108 struct patch *patch;
4109 struct index_state result = INDEX_STATE_INIT(state->repo);
4110 struct lock_file lock = LOCK_INIT;
4111 int res;
4113 /* Once we start supporting the reverse patch, it may be
4114 * worth showing the new sha1 prefix, but until then...
4116 for (patch = list; patch; patch = patch->next) {
4117 struct object_id oid;
4118 struct cache_entry *ce;
4119 const char *name;
4121 name = patch->old_name ? patch->old_name : patch->new_name;
4122 if (0 < patch->is_new)
4123 continue;
4125 if (S_ISGITLINK(patch->old_mode)) {
4126 if (!preimage_oid_in_gitlink_patch(patch, &oid))
4127 ; /* ok, the textual part looks sane */
4128 else
4129 return error(_("sha1 information is lacking or "
4130 "useless for submodule %s"), name);
4131 } else if (!get_oid_blob(patch->old_oid_prefix, &oid)) {
4132 ; /* ok */
4133 } else if (!patch->lines_added && !patch->lines_deleted) {
4134 /* mode-only change: update the current */
4135 if (get_current_oid(state, patch->old_name, &oid))
4136 return error(_("mode change for %s, which is not "
4137 "in current HEAD"), name);
4138 } else
4139 return error(_("sha1 information is lacking or useless "
4140 "(%s)."), name);
4142 ce = make_cache_entry(&result, patch->old_mode, &oid, name, 0, 0);
4143 if (!ce)
4144 return error(_("make_cache_entry failed for path '%s'"),
4145 name);
4146 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) {
4147 discard_cache_entry(ce);
4148 return error(_("could not add %s to temporary index"),
4149 name);
4153 hold_lock_file_for_update(&lock, state->fake_ancestor, LOCK_DIE_ON_ERROR);
4154 res = write_locked_index(&result, &lock, COMMIT_LOCK);
4155 discard_index(&result);
4157 if (res)
4158 return error(_("could not write temporary index to %s"),
4159 state->fake_ancestor);
4161 return 0;
4164 static void stat_patch_list(struct apply_state *state, struct patch *patch)
4166 int files, adds, dels;
4168 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
4169 files++;
4170 adds += patch->lines_added;
4171 dels += patch->lines_deleted;
4172 show_stats(state, patch);
4175 print_stat_summary(stdout, files, adds, dels);
4178 static void numstat_patch_list(struct apply_state *state,
4179 struct patch *patch)
4181 for ( ; patch; patch = patch->next) {
4182 const char *name;
4183 name = patch->new_name ? patch->new_name : patch->old_name;
4184 if (patch->is_binary)
4185 printf("-\t-\t");
4186 else
4187 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
4188 write_name_quoted(name, stdout, state->line_termination);
4192 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
4194 if (mode)
4195 printf(" %s mode %06o %s\n", newdelete, mode, name);
4196 else
4197 printf(" %s %s\n", newdelete, name);
4200 static void show_mode_change(struct patch *p, int show_name)
4202 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
4203 if (show_name)
4204 printf(" mode change %06o => %06o %s\n",
4205 p->old_mode, p->new_mode, p->new_name);
4206 else
4207 printf(" mode change %06o => %06o\n",
4208 p->old_mode, p->new_mode);
4212 static void show_rename_copy(struct patch *p)
4214 const char *renamecopy = p->is_rename ? "rename" : "copy";
4215 const char *old_name, *new_name;
4217 /* Find common prefix */
4218 old_name = p->old_name;
4219 new_name = p->new_name;
4220 while (1) {
4221 const char *slash_old, *slash_new;
4222 slash_old = strchr(old_name, '/');
4223 slash_new = strchr(new_name, '/');
4224 if (!slash_old ||
4225 !slash_new ||
4226 slash_old - old_name != slash_new - new_name ||
4227 memcmp(old_name, new_name, slash_new - new_name))
4228 break;
4229 old_name = slash_old + 1;
4230 new_name = slash_new + 1;
4232 /* p->old_name through old_name is the common prefix, and old_name and
4233 * new_name through the end of names are renames
4235 if (old_name != p->old_name)
4236 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
4237 (int)(old_name - p->old_name), p->old_name,
4238 old_name, new_name, p->score);
4239 else
4240 printf(" %s %s => %s (%d%%)\n", renamecopy,
4241 p->old_name, p->new_name, p->score);
4242 show_mode_change(p, 0);
4245 static void summary_patch_list(struct patch *patch)
4247 struct patch *p;
4249 for (p = patch; p; p = p->next) {
4250 if (p->is_new)
4251 show_file_mode_name("create", p->new_mode, p->new_name);
4252 else if (p->is_delete)
4253 show_file_mode_name("delete", p->old_mode, p->old_name);
4254 else {
4255 if (p->is_rename || p->is_copy)
4256 show_rename_copy(p);
4257 else {
4258 if (p->score) {
4259 printf(" rewrite %s (%d%%)\n",
4260 p->new_name, p->score);
4261 show_mode_change(p, 0);
4263 else
4264 show_mode_change(p, 1);
4270 static void patch_stats(struct apply_state *state, struct patch *patch)
4272 int lines = patch->lines_added + patch->lines_deleted;
4274 if (lines > state->max_change)
4275 state->max_change = lines;
4276 if (patch->old_name) {
4277 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
4278 if (!len)
4279 len = strlen(patch->old_name);
4280 if (len > state->max_len)
4281 state->max_len = len;
4283 if (patch->new_name) {
4284 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
4285 if (!len)
4286 len = strlen(patch->new_name);
4287 if (len > state->max_len)
4288 state->max_len = len;
4292 static int remove_file(struct apply_state *state, struct patch *patch, int rmdir_empty)
4294 if (state->update_index && !state->ita_only) {
4295 if (remove_file_from_index(state->repo->index, patch->old_name) < 0)
4296 return error(_("unable to remove %s from index"), patch->old_name);
4298 if (!state->cached) {
4299 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
4300 remove_path(patch->old_name);
4303 return 0;
4306 static int add_index_file(struct apply_state *state,
4307 const char *path,
4308 unsigned mode,
4309 void *buf,
4310 unsigned long size)
4312 struct stat st;
4313 struct cache_entry *ce;
4314 int namelen = strlen(path);
4316 ce = make_empty_cache_entry(state->repo->index, namelen);
4317 memcpy(ce->name, path, namelen);
4318 ce->ce_mode = create_ce_mode(mode);
4319 ce->ce_flags = create_ce_flags(0);
4320 ce->ce_namelen = namelen;
4321 if (state->ita_only) {
4322 ce->ce_flags |= CE_INTENT_TO_ADD;
4323 set_object_name_for_intent_to_add_entry(ce);
4324 } else if (S_ISGITLINK(mode)) {
4325 const char *s;
4327 if (!skip_prefix(buf, "Subproject commit ", &s) ||
4328 get_oid_hex(s, &ce->oid)) {
4329 discard_cache_entry(ce);
4330 return error(_("corrupt patch for submodule %s"), path);
4332 } else {
4333 if (!state->cached) {
4334 if (lstat(path, &st) < 0) {
4335 discard_cache_entry(ce);
4336 return error_errno(_("unable to stat newly "
4337 "created file '%s'"),
4338 path);
4340 fill_stat_cache_info(state->repo->index, ce, &st);
4342 if (write_object_file(buf, size, OBJ_BLOB, &ce->oid) < 0) {
4343 discard_cache_entry(ce);
4344 return error(_("unable to create backing store "
4345 "for newly created file %s"), path);
4348 if (add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) < 0) {
4349 discard_cache_entry(ce);
4350 return error(_("unable to add cache entry for %s"), path);
4353 return 0;
4357 * Returns:
4358 * -1 if an unrecoverable error happened
4359 * 0 if everything went well
4360 * 1 if a recoverable error happened
4362 static int try_create_file(struct apply_state *state, const char *path,
4363 unsigned int mode, const char *buf,
4364 unsigned long size)
4366 int fd, res;
4367 struct strbuf nbuf = STRBUF_INIT;
4369 if (S_ISGITLINK(mode)) {
4370 struct stat st;
4371 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
4372 return 0;
4373 return !!mkdir(path, 0777);
4376 if (has_symlinks && S_ISLNK(mode))
4377 /* Although buf:size is counted string, it also is NUL
4378 * terminated.
4380 return !!symlink(buf, path);
4382 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
4383 if (fd < 0)
4384 return 1;
4386 if (convert_to_working_tree(state->repo->index, path, buf, size, &nbuf, NULL)) {
4387 size = nbuf.len;
4388 buf = nbuf.buf;
4391 res = write_in_full(fd, buf, size) < 0;
4392 if (res)
4393 error_errno(_("failed to write to '%s'"), path);
4394 strbuf_release(&nbuf);
4396 if (close(fd) < 0 && !res)
4397 return error_errno(_("closing file '%s'"), path);
4399 return res ? -1 : 0;
4403 * We optimistically assume that the directories exist,
4404 * which is true 99% of the time anyway. If they don't,
4405 * we create them and try again.
4407 * Returns:
4408 * -1 on error
4409 * 0 otherwise
4411 static int create_one_file(struct apply_state *state,
4412 char *path,
4413 unsigned mode,
4414 const char *buf,
4415 unsigned long size)
4417 int res;
4419 if (state->cached)
4420 return 0;
4423 * We already try to detect whether files are beyond a symlink in our
4424 * up-front checks. But in the case where symlinks are created by any
4425 * of the intermediate hunks it can happen that our up-front checks
4426 * didn't yet see the symlink, but at the point of arriving here there
4427 * in fact is one. We thus repeat the check for symlinks here.
4429 * Note that this does not make the up-front check obsolete as the
4430 * failure mode is different:
4432 * - The up-front checks cause us to abort before we have written
4433 * anything into the working directory. So when we exit this way the
4434 * working directory remains clean.
4436 * - The checks here happen in the middle of the action where we have
4437 * already started to apply the patch. The end result will be a dirty
4438 * working directory.
4440 * Ideally, we should update the up-front checks to catch what would
4441 * happen when we apply the patch before we damage the working tree.
4442 * We have all the information necessary to do so. But for now, as a
4443 * part of embargoed security work, having this check would serve as a
4444 * reasonable first step.
4446 if (path_is_beyond_symlink(state, path))
4447 return error(_("affected file '%s' is beyond a symbolic link"), path);
4449 res = try_create_file(state, path, mode, buf, size);
4450 if (res < 0)
4451 return -1;
4452 if (!res)
4453 return 0;
4455 if (errno == ENOENT) {
4456 if (safe_create_leading_directories_no_share(path))
4457 return 0;
4458 res = try_create_file(state, path, mode, buf, size);
4459 if (res < 0)
4460 return -1;
4461 if (!res)
4462 return 0;
4465 if (errno == EEXIST || errno == EACCES) {
4466 /* We may be trying to create a file where a directory
4467 * used to be.
4469 struct stat st;
4470 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
4471 errno = EEXIST;
4474 if (errno == EEXIST) {
4475 unsigned int nr = getpid();
4477 for (;;) {
4478 char newpath[PATH_MAX];
4479 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
4480 res = try_create_file(state, newpath, mode, buf, size);
4481 if (res < 0)
4482 return -1;
4483 if (!res) {
4484 if (!rename(newpath, path))
4485 return 0;
4486 unlink_or_warn(newpath);
4487 break;
4489 if (errno != EEXIST)
4490 break;
4491 ++nr;
4494 return error_errno(_("unable to write file '%s' mode %o"),
4495 path, mode);
4498 static int add_conflicted_stages_file(struct apply_state *state,
4499 struct patch *patch)
4501 int stage, namelen;
4502 unsigned mode;
4503 struct cache_entry *ce;
4505 if (!state->update_index)
4506 return 0;
4507 namelen = strlen(patch->new_name);
4508 mode = patch->new_mode ? patch->new_mode : (S_IFREG | 0644);
4510 remove_file_from_index(state->repo->index, patch->new_name);
4511 for (stage = 1; stage < 4; stage++) {
4512 if (is_null_oid(&patch->threeway_stage[stage - 1]))
4513 continue;
4514 ce = make_empty_cache_entry(state->repo->index, namelen);
4515 memcpy(ce->name, patch->new_name, namelen);
4516 ce->ce_mode = create_ce_mode(mode);
4517 ce->ce_flags = create_ce_flags(stage);
4518 ce->ce_namelen = namelen;
4519 oidcpy(&ce->oid, &patch->threeway_stage[stage - 1]);
4520 if (add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) < 0) {
4521 discard_cache_entry(ce);
4522 return error(_("unable to add cache entry for %s"),
4523 patch->new_name);
4527 return 0;
4530 static int create_file(struct apply_state *state, struct patch *patch)
4532 char *path = patch->new_name;
4533 unsigned mode = patch->new_mode;
4534 unsigned long size = patch->resultsize;
4535 char *buf = patch->result;
4537 if (!mode)
4538 mode = S_IFREG | 0644;
4539 if (create_one_file(state, path, mode, buf, size))
4540 return -1;
4542 if (patch->conflicted_threeway)
4543 return add_conflicted_stages_file(state, patch);
4544 else if (state->update_index)
4545 return add_index_file(state, path, mode, buf, size);
4546 return 0;
4549 /* phase zero is to remove, phase one is to create */
4550 static int write_out_one_result(struct apply_state *state,
4551 struct patch *patch,
4552 int phase)
4554 if (patch->is_delete > 0) {
4555 if (phase == 0)
4556 return remove_file(state, patch, 1);
4557 return 0;
4559 if (patch->is_new > 0 || patch->is_copy) {
4560 if (phase == 1)
4561 return create_file(state, patch);
4562 return 0;
4565 * Rename or modification boils down to the same
4566 * thing: remove the old, write the new
4568 if (phase == 0)
4569 return remove_file(state, patch, patch->is_rename);
4570 if (phase == 1)
4571 return create_file(state, patch);
4572 return 0;
4575 static int write_out_one_reject(struct apply_state *state, struct patch *patch)
4577 FILE *rej;
4578 char namebuf[PATH_MAX];
4579 struct fragment *frag;
4580 int cnt = 0;
4581 struct strbuf sb = STRBUF_INIT;
4583 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
4584 if (!frag->rejected)
4585 continue;
4586 cnt++;
4589 if (!cnt) {
4590 if (state->apply_verbosity > verbosity_normal)
4591 say_patch_name(stderr,
4592 _("Applied patch %s cleanly."), patch);
4593 return 0;
4596 /* This should not happen, because a removal patch that leaves
4597 * contents are marked "rejected" at the patch level.
4599 if (!patch->new_name)
4600 die(_("internal error"));
4602 /* Say this even without --verbose */
4603 strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",
4604 "Applying patch %%s with %d rejects...",
4605 cnt),
4606 cnt);
4607 if (state->apply_verbosity > verbosity_silent)
4608 say_patch_name(stderr, sb.buf, patch);
4609 strbuf_release(&sb);
4611 cnt = strlen(patch->new_name);
4612 if (ARRAY_SIZE(namebuf) <= cnt + 5) {
4613 cnt = ARRAY_SIZE(namebuf) - 5;
4614 warning(_("truncating .rej filename to %.*s.rej"),
4615 cnt - 1, patch->new_name);
4617 memcpy(namebuf, patch->new_name, cnt);
4618 memcpy(namebuf + cnt, ".rej", 5);
4620 rej = fopen(namebuf, "w");
4621 if (!rej)
4622 return error_errno(_("cannot open %s"), namebuf);
4624 /* Normal git tools never deal with .rej, so do not pretend
4625 * this is a git patch by saying --git or giving extended
4626 * headers. While at it, maybe please "kompare" that wants
4627 * the trailing TAB and some garbage at the end of line ;-).
4629 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
4630 patch->new_name, patch->new_name);
4631 for (cnt = 1, frag = patch->fragments;
4632 frag;
4633 cnt++, frag = frag->next) {
4634 if (!frag->rejected) {
4635 if (state->apply_verbosity > verbosity_silent)
4636 fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);
4637 continue;
4639 if (state->apply_verbosity > verbosity_silent)
4640 fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);
4641 fprintf(rej, "%.*s", frag->size, frag->patch);
4642 if (frag->patch[frag->size-1] != '\n')
4643 fputc('\n', rej);
4645 fclose(rej);
4646 return -1;
4650 * Returns:
4651 * -1 if an error happened
4652 * 0 if the patch applied cleanly
4653 * 1 if the patch did not apply cleanly
4655 static int write_out_results(struct apply_state *state, struct patch *list)
4657 int phase;
4658 int errs = 0;
4659 struct patch *l;
4660 struct string_list cpath = STRING_LIST_INIT_DUP;
4662 for (phase = 0; phase < 2; phase++) {
4663 l = list;
4664 while (l) {
4665 if (l->rejected)
4666 errs = 1;
4667 else {
4668 if (write_out_one_result(state, l, phase)) {
4669 string_list_clear(&cpath, 0);
4670 return -1;
4672 if (phase == 1) {
4673 if (write_out_one_reject(state, l))
4674 errs = 1;
4675 if (l->conflicted_threeway) {
4676 string_list_append(&cpath, l->new_name);
4677 errs = 1;
4681 l = l->next;
4685 if (cpath.nr) {
4686 struct string_list_item *item;
4688 string_list_sort(&cpath);
4689 if (state->apply_verbosity > verbosity_silent) {
4690 for_each_string_list_item(item, &cpath)
4691 fprintf(stderr, "U %s\n", item->string);
4693 string_list_clear(&cpath, 0);
4696 * rerere relies on the partially merged result being in the working
4697 * tree with conflict markers, but that isn't written with --cached.
4699 if (!state->cached)
4700 repo_rerere(state->repo, 0);
4703 return errs;
4707 * Try to apply a patch.
4709 * Returns:
4710 * -128 if a bad error happened (like patch unreadable)
4711 * -1 if patch did not apply and user cannot deal with it
4712 * 0 if the patch applied
4713 * 1 if the patch did not apply but user might fix it
4715 static int apply_patch(struct apply_state *state,
4716 int fd,
4717 const char *filename,
4718 int options)
4720 size_t offset;
4721 struct strbuf buf = STRBUF_INIT; /* owns the patch text */
4722 struct patch *list = NULL, **listp = &list;
4723 int skipped_patch = 0;
4724 int res = 0;
4725 int flush_attributes = 0;
4727 state->patch_input_file = filename;
4728 if (read_patch_file(&buf, fd) < 0)
4729 return -128;
4730 offset = 0;
4731 while (offset < buf.len) {
4732 struct patch *patch;
4733 int nr;
4735 CALLOC_ARRAY(patch, 1);
4736 patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF);
4737 patch->recount = !!(options & APPLY_OPT_RECOUNT);
4738 nr = parse_chunk(state, buf.buf + offset, buf.len - offset, patch);
4739 if (nr < 0) {
4740 free_patch(patch);
4741 if (nr == -128) {
4742 res = -128;
4743 goto end;
4745 break;
4747 if (state->apply_in_reverse)
4748 reverse_patches(patch);
4749 if (use_patch(state, patch)) {
4750 patch_stats(state, patch);
4751 if (!list || !state->apply_in_reverse) {
4752 *listp = patch;
4753 listp = &patch->next;
4754 } else {
4755 patch->next = list;
4756 list = patch;
4759 if ((patch->new_name &&
4760 ends_with_path_components(patch->new_name,
4761 GITATTRIBUTES_FILE)) ||
4762 (patch->old_name &&
4763 ends_with_path_components(patch->old_name,
4764 GITATTRIBUTES_FILE)))
4765 flush_attributes = 1;
4767 else {
4768 if (state->apply_verbosity > verbosity_normal)
4769 say_patch_name(stderr, _("Skipped patch '%s'."), patch);
4770 free_patch(patch);
4771 skipped_patch++;
4773 offset += nr;
4776 if (!list && !skipped_patch) {
4777 if (!state->allow_empty) {
4778 error(_("No valid patches in input (allow with \"--allow-empty\")"));
4779 res = -128;
4781 goto end;
4784 if (state->whitespace_error && (state->ws_error_action == die_on_ws_error))
4785 state->apply = 0;
4787 state->update_index = (state->check_index || state->ita_only) && state->apply;
4788 if (state->update_index && !is_lock_file_locked(&state->lock_file)) {
4789 if (state->index_file)
4790 hold_lock_file_for_update(&state->lock_file,
4791 state->index_file,
4792 LOCK_DIE_ON_ERROR);
4793 else
4794 repo_hold_locked_index(state->repo, &state->lock_file,
4795 LOCK_DIE_ON_ERROR);
4798 if (state->check_index && read_apply_cache(state) < 0) {
4799 error(_("unable to read index file"));
4800 res = -128;
4801 goto end;
4804 if (state->check || state->apply) {
4805 int r = check_patch_list(state, list);
4806 if (r == -128) {
4807 res = -128;
4808 goto end;
4810 if (r < 0 && !state->apply_with_reject) {
4811 res = -1;
4812 goto end;
4816 if (state->apply) {
4817 int write_res = write_out_results(state, list);
4818 if (write_res < 0) {
4819 res = -128;
4820 goto end;
4822 if (write_res > 0) {
4823 /* with --3way, we still need to write the index out */
4824 res = state->apply_with_reject ? -1 : 1;
4825 goto end;
4829 if (state->fake_ancestor &&
4830 build_fake_ancestor(state, list)) {
4831 res = -128;
4832 goto end;
4835 if (state->diffstat && state->apply_verbosity > verbosity_silent)
4836 stat_patch_list(state, list);
4838 if (state->numstat && state->apply_verbosity > verbosity_silent)
4839 numstat_patch_list(state, list);
4841 if (state->summary && state->apply_verbosity > verbosity_silent)
4842 summary_patch_list(list);
4844 if (flush_attributes)
4845 reset_parsed_attributes();
4846 end:
4847 free_patch_list(list);
4848 strbuf_release(&buf);
4849 string_list_clear(&state->fn_table, 0);
4850 return res;
4853 static int apply_option_parse_exclude(const struct option *opt,
4854 const char *arg, int unset)
4856 struct apply_state *state = opt->value;
4858 BUG_ON_OPT_NEG(unset);
4860 add_name_limit(state, arg, 1);
4861 return 0;
4864 static int apply_option_parse_include(const struct option *opt,
4865 const char *arg, int unset)
4867 struct apply_state *state = opt->value;
4869 BUG_ON_OPT_NEG(unset);
4871 add_name_limit(state, arg, 0);
4872 state->has_include = 1;
4873 return 0;
4876 static int apply_option_parse_p(const struct option *opt,
4877 const char *arg,
4878 int unset)
4880 struct apply_state *state = opt->value;
4882 BUG_ON_OPT_NEG(unset);
4884 state->p_value = atoi(arg);
4885 state->p_value_known = 1;
4886 return 0;
4889 static int apply_option_parse_space_change(const struct option *opt,
4890 const char *arg, int unset)
4892 struct apply_state *state = opt->value;
4894 BUG_ON_OPT_ARG(arg);
4896 if (unset)
4897 state->ws_ignore_action = ignore_ws_none;
4898 else
4899 state->ws_ignore_action = ignore_ws_change;
4900 return 0;
4903 static int apply_option_parse_whitespace(const struct option *opt,
4904 const char *arg, int unset)
4906 struct apply_state *state = opt->value;
4908 BUG_ON_OPT_NEG(unset);
4910 state->whitespace_option = arg;
4911 if (parse_whitespace_option(state, arg))
4912 return -1;
4913 return 0;
4916 static int apply_option_parse_directory(const struct option *opt,
4917 const char *arg, int unset)
4919 struct apply_state *state = opt->value;
4921 BUG_ON_OPT_NEG(unset);
4923 strbuf_reset(&state->root);
4924 strbuf_addstr(&state->root, arg);
4925 strbuf_complete(&state->root, '/');
4926 return 0;
4929 int apply_all_patches(struct apply_state *state,
4930 int argc,
4931 const char **argv,
4932 int options)
4934 int i;
4935 int res;
4936 int errs = 0;
4937 int read_stdin = 1;
4939 for (i = 0; i < argc; i++) {
4940 const char *arg = argv[i];
4941 char *to_free = NULL;
4942 int fd;
4944 if (!strcmp(arg, "-")) {
4945 res = apply_patch(state, 0, "<stdin>", options);
4946 if (res < 0)
4947 goto end;
4948 errs |= res;
4949 read_stdin = 0;
4950 continue;
4951 } else
4952 arg = to_free = prefix_filename(state->prefix, arg);
4954 fd = open(arg, O_RDONLY);
4955 if (fd < 0) {
4956 error(_("can't open patch '%s': %s"), arg, strerror(errno));
4957 res = -128;
4958 free(to_free);
4959 goto end;
4961 read_stdin = 0;
4962 set_default_whitespace_mode(state);
4963 res = apply_patch(state, fd, arg, options);
4964 close(fd);
4965 free(to_free);
4966 if (res < 0)
4967 goto end;
4968 errs |= res;
4970 set_default_whitespace_mode(state);
4971 if (read_stdin) {
4972 res = apply_patch(state, 0, "<stdin>", options);
4973 if (res < 0)
4974 goto end;
4975 errs |= res;
4978 if (state->whitespace_error) {
4979 if (state->squelch_whitespace_errors &&
4980 state->squelch_whitespace_errors < state->whitespace_error) {
4981 int squelched =
4982 state->whitespace_error - state->squelch_whitespace_errors;
4983 warning(Q_("squelched %d whitespace error",
4984 "squelched %d whitespace errors",
4985 squelched),
4986 squelched);
4988 if (state->ws_error_action == die_on_ws_error) {
4989 error(Q_("%d line adds whitespace errors.",
4990 "%d lines add whitespace errors.",
4991 state->whitespace_error),
4992 state->whitespace_error);
4993 res = -128;
4994 goto end;
4996 if (state->applied_after_fixing_ws && state->apply)
4997 warning(Q_("%d line applied after"
4998 " fixing whitespace errors.",
4999 "%d lines applied after"
5000 " fixing whitespace errors.",
5001 state->applied_after_fixing_ws),
5002 state->applied_after_fixing_ws);
5003 else if (state->whitespace_error)
5004 warning(Q_("%d line adds whitespace errors.",
5005 "%d lines add whitespace errors.",
5006 state->whitespace_error),
5007 state->whitespace_error);
5010 if (state->update_index) {
5011 res = write_locked_index(state->repo->index, &state->lock_file, COMMIT_LOCK);
5012 if (res) {
5013 error(_("Unable to write new index file"));
5014 res = -128;
5015 goto end;
5019 res = !!errs;
5021 end:
5022 rollback_lock_file(&state->lock_file);
5024 if (state->apply_verbosity <= verbosity_silent) {
5025 set_error_routine(state->saved_error_routine);
5026 set_warn_routine(state->saved_warn_routine);
5029 if (res > -1)
5030 return res;
5031 return (res == -1 ? 1 : 128);
5034 int apply_parse_options(int argc, const char **argv,
5035 struct apply_state *state,
5036 int *force_apply, int *options,
5037 const char * const *apply_usage)
5039 struct option builtin_apply_options[] = {
5040 OPT_CALLBACK_F(0, "exclude", state, N_("path"),
5041 N_("don't apply changes matching the given path"),
5042 PARSE_OPT_NONEG, apply_option_parse_exclude),
5043 OPT_CALLBACK_F(0, "include", state, N_("path"),
5044 N_("apply changes matching the given path"),
5045 PARSE_OPT_NONEG, apply_option_parse_include),
5046 OPT_CALLBACK('p', NULL, state, N_("num"),
5047 N_("remove <num> leading slashes from traditional diff paths"),
5048 apply_option_parse_p),
5049 OPT_BOOL(0, "no-add", &state->no_add,
5050 N_("ignore additions made by the patch")),
5051 OPT_BOOL(0, "stat", &state->diffstat,
5052 N_("instead of applying the patch, output diffstat for the input")),
5053 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
5054 OPT_NOOP_NOARG(0, "binary"),
5055 OPT_BOOL(0, "numstat", &state->numstat,
5056 N_("show number of added and deleted lines in decimal notation")),
5057 OPT_BOOL(0, "summary", &state->summary,
5058 N_("instead of applying the patch, output a summary for the input")),
5059 OPT_BOOL(0, "check", &state->check,
5060 N_("instead of applying the patch, see if the patch is applicable")),
5061 OPT_BOOL(0, "index", &state->check_index,
5062 N_("make sure the patch is applicable to the current index")),
5063 OPT_BOOL('N', "intent-to-add", &state->ita_only,
5064 N_("mark new files with `git add --intent-to-add`")),
5065 OPT_BOOL(0, "cached", &state->cached,
5066 N_("apply a patch without touching the working tree")),
5067 OPT_BOOL_F(0, "unsafe-paths", &state->unsafe_paths,
5068 N_("accept a patch that touches outside the working area"),
5069 PARSE_OPT_NOCOMPLETE),
5070 OPT_BOOL(0, "apply", force_apply,
5071 N_("also apply the patch (use with --stat/--summary/--check)")),
5072 OPT_BOOL('3', "3way", &state->threeway,
5073 N_( "attempt three-way merge, fall back on normal patch if that fails")),
5074 OPT_FILENAME(0, "build-fake-ancestor", &state->fake_ancestor,
5075 N_("build a temporary index based on embedded index information")),
5076 /* Think twice before adding "--nul" synonym to this */
5077 OPT_SET_INT('z', NULL, &state->line_termination,
5078 N_("paths are separated with NUL character"), '\0'),
5079 OPT_INTEGER('C', NULL, &state->p_context,
5080 N_("ensure at least <n> lines of context match")),
5081 OPT_CALLBACK(0, "whitespace", state, N_("action"),
5082 N_("detect new or modified lines that have whitespace errors"),
5083 apply_option_parse_whitespace),
5084 OPT_CALLBACK_F(0, "ignore-space-change", state, NULL,
5085 N_("ignore changes in whitespace when finding context"),
5086 PARSE_OPT_NOARG, apply_option_parse_space_change),
5087 OPT_CALLBACK_F(0, "ignore-whitespace", state, NULL,
5088 N_("ignore changes in whitespace when finding context"),
5089 PARSE_OPT_NOARG, apply_option_parse_space_change),
5090 OPT_BOOL('R', "reverse", &state->apply_in_reverse,
5091 N_("apply the patch in reverse")),
5092 OPT_BOOL(0, "unidiff-zero", &state->unidiff_zero,
5093 N_("don't expect at least one line of context")),
5094 OPT_BOOL(0, "reject", &state->apply_with_reject,
5095 N_("leave the rejected hunks in corresponding *.rej files")),
5096 OPT_BOOL(0, "allow-overlap", &state->allow_overlap,
5097 N_("allow overlapping hunks")),
5098 OPT__VERBOSITY(&state->apply_verbosity),
5099 OPT_BIT(0, "inaccurate-eof", options,
5100 N_("tolerate incorrectly detected missing new-line at the end of file"),
5101 APPLY_OPT_INACCURATE_EOF),
5102 OPT_BIT(0, "recount", options,
5103 N_("do not trust the line counts in the hunk headers"),
5104 APPLY_OPT_RECOUNT),
5105 OPT_CALLBACK(0, "directory", state, N_("root"),
5106 N_("prepend <root> to all filenames"),
5107 apply_option_parse_directory),
5108 OPT_BOOL(0, "allow-empty", &state->allow_empty,
5109 N_("don't return error for empty patches")),
5110 OPT_END()
5113 return parse_options(argc, argv, state->prefix, builtin_apply_options, apply_usage, 0);