Merge branch 'jc/cat-file-batch-commands'
[alt-git.git] / apply.c
blobd19c26d332e7908b364be4e2eddea4c2f1bde0b5
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 "config.h"
12 #include "object-store.h"
13 #include "blob.h"
14 #include "delta.h"
15 #include "diff.h"
16 #include "dir.h"
17 #include "xdiff-interface.h"
18 #include "ll-merge.h"
19 #include "lockfile.h"
20 #include "parse-options.h"
21 #include "quote.h"
22 #include "rerere.h"
23 #include "apply.h"
24 #include "entry.h"
26 struct gitdiff_data {
27 struct strbuf *root;
28 int linenr;
29 int p_value;
32 static void git_apply_config(void)
34 git_config_get_string("apply.whitespace", &apply_default_whitespace);
35 git_config_get_string("apply.ignorewhitespace", &apply_default_ignorewhitespace);
36 git_config(git_xmerge_config, NULL);
39 static int parse_whitespace_option(struct apply_state *state, const char *option)
41 if (!option) {
42 state->ws_error_action = warn_on_ws_error;
43 return 0;
45 if (!strcmp(option, "warn")) {
46 state->ws_error_action = warn_on_ws_error;
47 return 0;
49 if (!strcmp(option, "nowarn")) {
50 state->ws_error_action = nowarn_ws_error;
51 return 0;
53 if (!strcmp(option, "error")) {
54 state->ws_error_action = die_on_ws_error;
55 return 0;
57 if (!strcmp(option, "error-all")) {
58 state->ws_error_action = die_on_ws_error;
59 state->squelch_whitespace_errors = 0;
60 return 0;
62 if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
63 state->ws_error_action = correct_ws_error;
64 return 0;
67 * Please update $__git_whitespacelist in git-completion.bash
68 * when you add new options.
70 return error(_("unrecognized whitespace option '%s'"), option);
73 static int parse_ignorewhitespace_option(struct apply_state *state,
74 const char *option)
76 if (!option || !strcmp(option, "no") ||
77 !strcmp(option, "false") || !strcmp(option, "never") ||
78 !strcmp(option, "none")) {
79 state->ws_ignore_action = ignore_ws_none;
80 return 0;
82 if (!strcmp(option, "change")) {
83 state->ws_ignore_action = ignore_ws_change;
84 return 0;
86 return error(_("unrecognized whitespace ignore option '%s'"), option);
89 int init_apply_state(struct apply_state *state,
90 struct repository *repo,
91 const char *prefix)
93 memset(state, 0, sizeof(*state));
94 state->prefix = prefix;
95 state->repo = repo;
96 state->apply = 1;
97 state->line_termination = '\n';
98 state->p_value = 1;
99 state->p_context = UINT_MAX;
100 state->squelch_whitespace_errors = 5;
101 state->ws_error_action = warn_on_ws_error;
102 state->ws_ignore_action = ignore_ws_none;
103 state->linenr = 1;
104 string_list_init_nodup(&state->fn_table);
105 string_list_init_nodup(&state->limit_by_name);
106 strset_init(&state->removed_symlinks);
107 strset_init(&state->kept_symlinks);
108 strbuf_init(&state->root, 0);
110 git_apply_config();
111 if (apply_default_whitespace && parse_whitespace_option(state, apply_default_whitespace))
112 return -1;
113 if (apply_default_ignorewhitespace && parse_ignorewhitespace_option(state, apply_default_ignorewhitespace))
114 return -1;
115 return 0;
118 void clear_apply_state(struct apply_state *state)
120 string_list_clear(&state->limit_by_name, 0);
121 strset_clear(&state->removed_symlinks);
122 strset_clear(&state->kept_symlinks);
123 strbuf_release(&state->root);
125 /* &state->fn_table is cleared at the end of apply_patch() */
128 static void mute_routine(const char *msg, va_list params)
130 /* do nothing */
133 int check_apply_state(struct apply_state *state, int force_apply)
135 int is_not_gitdir = !startup_info->have_repository;
137 if (state->apply_with_reject && state->threeway)
138 return error(_("options '%s' and '%s' cannot be used together"), "--reject", "--3way");
139 if (state->threeway) {
140 if (is_not_gitdir)
141 return error(_("'%s' outside a repository"), "--3way");
142 state->check_index = 1;
144 if (state->apply_with_reject) {
145 state->apply = 1;
146 if (state->apply_verbosity == verbosity_normal)
147 state->apply_verbosity = verbosity_verbose;
149 if (!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor))
150 state->apply = 0;
151 if (state->check_index && is_not_gitdir)
152 return error(_("'%s' outside a repository"), "--index");
153 if (state->cached) {
154 if (is_not_gitdir)
155 return error(_("'%s' outside a repository"), "--cached");
156 state->check_index = 1;
158 if (state->ita_only && (state->check_index || is_not_gitdir))
159 state->ita_only = 0;
160 if (state->check_index)
161 state->unsafe_paths = 0;
163 if (state->apply_verbosity <= verbosity_silent) {
164 state->saved_error_routine = get_error_routine();
165 state->saved_warn_routine = get_warn_routine();
166 set_error_routine(mute_routine);
167 set_warn_routine(mute_routine);
170 return 0;
173 static void set_default_whitespace_mode(struct apply_state *state)
175 if (!state->whitespace_option && !apply_default_whitespace)
176 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error);
180 * This represents one "hunk" from a patch, starting with
181 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
182 * patch text is pointed at by patch, and its byte length
183 * is stored in size. leading and trailing are the number
184 * of context lines.
186 struct fragment {
187 unsigned long leading, trailing;
188 unsigned long oldpos, oldlines;
189 unsigned long newpos, newlines;
191 * 'patch' is usually borrowed from buf in apply_patch(),
192 * but some codepaths store an allocated buffer.
194 const char *patch;
195 unsigned free_patch:1,
196 rejected:1;
197 int size;
198 int linenr;
199 struct fragment *next;
203 * When dealing with a binary patch, we reuse "leading" field
204 * to store the type of the binary hunk, either deflated "delta"
205 * or deflated "literal".
207 #define binary_patch_method leading
208 #define BINARY_DELTA_DEFLATED 1
209 #define BINARY_LITERAL_DEFLATED 2
211 static void free_fragment_list(struct fragment *list)
213 while (list) {
214 struct fragment *next = list->next;
215 if (list->free_patch)
216 free((char *)list->patch);
217 free(list);
218 list = next;
222 void release_patch(struct patch *patch)
224 free_fragment_list(patch->fragments);
225 free(patch->def_name);
226 free(patch->old_name);
227 free(patch->new_name);
228 free(patch->result);
231 static void free_patch(struct patch *patch)
233 release_patch(patch);
234 free(patch);
237 static void free_patch_list(struct patch *list)
239 while (list) {
240 struct patch *next = list->next;
241 free_patch(list);
242 list = next;
247 * A line in a file, len-bytes long (includes the terminating LF,
248 * except for an incomplete line at the end if the file ends with
249 * one), and its contents hashes to 'hash'.
251 struct line {
252 size_t len;
253 unsigned hash : 24;
254 unsigned flag : 8;
255 #define LINE_COMMON 1
256 #define LINE_PATCHED 2
260 * This represents a "file", which is an array of "lines".
262 struct image {
263 char *buf;
264 size_t len;
265 size_t nr;
266 size_t alloc;
267 struct line *line_allocated;
268 struct line *line;
271 static uint32_t hash_line(const char *cp, size_t len)
273 size_t i;
274 uint32_t h;
275 for (i = 0, h = 0; i < len; i++) {
276 if (!isspace(cp[i])) {
277 h = h * 3 + (cp[i] & 0xff);
280 return h;
284 * Compare lines s1 of length n1 and s2 of length n2, ignoring
285 * whitespace difference. Returns 1 if they match, 0 otherwise
287 static int fuzzy_matchlines(const char *s1, size_t n1,
288 const char *s2, size_t n2)
290 const char *end1 = s1 + n1;
291 const char *end2 = s2 + n2;
293 /* ignore line endings */
294 while (s1 < end1 && (end1[-1] == '\r' || end1[-1] == '\n'))
295 end1--;
296 while (s2 < end2 && (end2[-1] == '\r' || end2[-1] == '\n'))
297 end2--;
299 while (s1 < end1 && s2 < end2) {
300 if (isspace(*s1)) {
302 * Skip whitespace. We check on both buffers
303 * because we don't want "a b" to match "ab".
305 if (!isspace(*s2))
306 return 0;
307 while (s1 < end1 && isspace(*s1))
308 s1++;
309 while (s2 < end2 && isspace(*s2))
310 s2++;
311 } else if (*s1++ != *s2++)
312 return 0;
315 /* If we reached the end on one side only, lines don't match. */
316 return s1 == end1 && s2 == end2;
319 static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
321 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
322 img->line_allocated[img->nr].len = len;
323 img->line_allocated[img->nr].hash = hash_line(bol, len);
324 img->line_allocated[img->nr].flag = flag;
325 img->nr++;
329 * "buf" has the file contents to be patched (read from various sources).
330 * attach it to "image" and add line-based index to it.
331 * "image" now owns the "buf".
333 static void prepare_image(struct image *image, char *buf, size_t len,
334 int prepare_linetable)
336 const char *cp, *ep;
338 memset(image, 0, sizeof(*image));
339 image->buf = buf;
340 image->len = len;
342 if (!prepare_linetable)
343 return;
345 ep = image->buf + image->len;
346 cp = image->buf;
347 while (cp < ep) {
348 const char *next;
349 for (next = cp; next < ep && *next != '\n'; next++)
351 if (next < ep)
352 next++;
353 add_line_info(image, cp, next - cp, 0);
354 cp = next;
356 image->line = image->line_allocated;
359 static void clear_image(struct image *image)
361 free(image->buf);
362 free(image->line_allocated);
363 memset(image, 0, sizeof(*image));
366 /* fmt must contain _one_ %s and no other substitution */
367 static void say_patch_name(FILE *output, const char *fmt, struct patch *patch)
369 struct strbuf sb = STRBUF_INIT;
371 if (patch->old_name && patch->new_name &&
372 strcmp(patch->old_name, patch->new_name)) {
373 quote_c_style(patch->old_name, &sb, NULL, 0);
374 strbuf_addstr(&sb, " => ");
375 quote_c_style(patch->new_name, &sb, NULL, 0);
376 } else {
377 const char *n = patch->new_name;
378 if (!n)
379 n = patch->old_name;
380 quote_c_style(n, &sb, NULL, 0);
382 fprintf(output, fmt, sb.buf);
383 fputc('\n', output);
384 strbuf_release(&sb);
387 #define SLOP (16)
389 static int read_patch_file(struct strbuf *sb, int fd)
391 if (strbuf_read(sb, fd, 0) < 0)
392 return error_errno("git apply: failed to read");
395 * Make sure that we have some slop in the buffer
396 * so that we can do speculative "memcmp" etc, and
397 * see to it that it is NUL-filled.
399 strbuf_grow(sb, SLOP);
400 memset(sb->buf + sb->len, 0, SLOP);
401 return 0;
404 static unsigned long linelen(const char *buffer, unsigned long size)
406 unsigned long len = 0;
407 while (size--) {
408 len++;
409 if (*buffer++ == '\n')
410 break;
412 return len;
415 static int is_dev_null(const char *str)
417 return skip_prefix(str, "/dev/null", &str) && isspace(*str);
420 #define TERM_SPACE 1
421 #define TERM_TAB 2
423 static int name_terminate(int c, int terminate)
425 if (c == ' ' && !(terminate & TERM_SPACE))
426 return 0;
427 if (c == '\t' && !(terminate & TERM_TAB))
428 return 0;
430 return 1;
433 /* remove double slashes to make --index work with such filenames */
434 static char *squash_slash(char *name)
436 int i = 0, j = 0;
438 if (!name)
439 return NULL;
441 while (name[i]) {
442 if ((name[j++] = name[i++]) == '/')
443 while (name[i] == '/')
444 i++;
446 name[j] = '\0';
447 return name;
450 static char *find_name_gnu(struct strbuf *root,
451 const char *line,
452 int p_value)
454 struct strbuf name = STRBUF_INIT;
455 char *cp;
458 * Proposed "new-style" GNU patch/diff format; see
459 * https://lore.kernel.org/git/7vll0wvb2a.fsf@assigned-by-dhcp.cox.net/
461 if (unquote_c_style(&name, line, NULL)) {
462 strbuf_release(&name);
463 return NULL;
466 for (cp = name.buf; p_value; p_value--) {
467 cp = strchr(cp, '/');
468 if (!cp) {
469 strbuf_release(&name);
470 return NULL;
472 cp++;
475 strbuf_remove(&name, 0, cp - name.buf);
476 if (root->len)
477 strbuf_insert(&name, 0, root->buf, root->len);
478 return squash_slash(strbuf_detach(&name, NULL));
481 static size_t sane_tz_len(const char *line, size_t len)
483 const char *tz, *p;
485 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
486 return 0;
487 tz = line + len - strlen(" +0500");
489 if (tz[1] != '+' && tz[1] != '-')
490 return 0;
492 for (p = tz + 2; p != line + len; p++)
493 if (!isdigit(*p))
494 return 0;
496 return line + len - tz;
499 static size_t tz_with_colon_len(const char *line, size_t len)
501 const char *tz, *p;
503 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
504 return 0;
505 tz = line + len - strlen(" +08:00");
507 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
508 return 0;
509 p = tz + 2;
510 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
511 !isdigit(*p++) || !isdigit(*p++))
512 return 0;
514 return line + len - tz;
517 static size_t date_len(const char *line, size_t len)
519 const char *date, *p;
521 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
522 return 0;
523 p = date = line + len - strlen("72-02-05");
525 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
526 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
527 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */
528 return 0;
530 if (date - line >= strlen("19") &&
531 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */
532 date -= strlen("19");
534 return line + len - date;
537 static size_t short_time_len(const char *line, size_t len)
539 const char *time, *p;
541 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
542 return 0;
543 p = time = line + len - strlen(" 07:01:32");
545 /* Permit 1-digit hours? */
546 if (*p++ != ' ' ||
547 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
548 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
549 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */
550 return 0;
552 return line + len - time;
555 static size_t fractional_time_len(const char *line, size_t len)
557 const char *p;
558 size_t n;
560 /* Expected format: 19:41:17.620000023 */
561 if (!len || !isdigit(line[len - 1]))
562 return 0;
563 p = line + len - 1;
565 /* Fractional seconds. */
566 while (p > line && isdigit(*p))
567 p--;
568 if (*p != '.')
569 return 0;
571 /* Hours, minutes, and whole seconds. */
572 n = short_time_len(line, p - line);
573 if (!n)
574 return 0;
576 return line + len - p + n;
579 static size_t trailing_spaces_len(const char *line, size_t len)
581 const char *p;
583 /* Expected format: ' ' x (1 or more) */
584 if (!len || line[len - 1] != ' ')
585 return 0;
587 p = line + len;
588 while (p != line) {
589 p--;
590 if (*p != ' ')
591 return line + len - (p + 1);
594 /* All spaces! */
595 return len;
598 static size_t diff_timestamp_len(const char *line, size_t len)
600 const char *end = line + len;
601 size_t n;
604 * Posix: 2010-07-05 19:41:17
605 * GNU: 2010-07-05 19:41:17.620000023 -0500
608 if (!isdigit(end[-1]))
609 return 0;
611 n = sane_tz_len(line, end - line);
612 if (!n)
613 n = tz_with_colon_len(line, end - line);
614 end -= n;
616 n = short_time_len(line, end - line);
617 if (!n)
618 n = fractional_time_len(line, end - line);
619 end -= n;
621 n = date_len(line, end - line);
622 if (!n) /* No date. Too bad. */
623 return 0;
624 end -= n;
626 if (end == line) /* No space before date. */
627 return 0;
628 if (end[-1] == '\t') { /* Success! */
629 end--;
630 return line + len - end;
632 if (end[-1] != ' ') /* No space before date. */
633 return 0;
635 /* Whitespace damage. */
636 end -= trailing_spaces_len(line, end - line);
637 return line + len - end;
640 static char *find_name_common(struct strbuf *root,
641 const char *line,
642 const char *def,
643 int p_value,
644 const char *end,
645 int terminate)
647 int len;
648 const char *start = NULL;
650 if (p_value == 0)
651 start = line;
652 while (line != end) {
653 char c = *line;
655 if (!end && isspace(c)) {
656 if (c == '\n')
657 break;
658 if (name_terminate(c, terminate))
659 break;
661 line++;
662 if (c == '/' && !--p_value)
663 start = line;
665 if (!start)
666 return squash_slash(xstrdup_or_null(def));
667 len = line - start;
668 if (!len)
669 return squash_slash(xstrdup_or_null(def));
672 * Generally we prefer the shorter name, especially
673 * if the other one is just a variation of that with
674 * something else tacked on to the end (ie "file.orig"
675 * or "file~").
677 if (def) {
678 int deflen = strlen(def);
679 if (deflen < len && !strncmp(start, def, deflen))
680 return squash_slash(xstrdup(def));
683 if (root->len) {
684 char *ret = xstrfmt("%s%.*s", root->buf, len, start);
685 return squash_slash(ret);
688 return squash_slash(xmemdupz(start, len));
691 static char *find_name(struct strbuf *root,
692 const char *line,
693 char *def,
694 int p_value,
695 int terminate)
697 if (*line == '"') {
698 char *name = find_name_gnu(root, line, p_value);
699 if (name)
700 return name;
703 return find_name_common(root, line, def, p_value, NULL, terminate);
706 static char *find_name_traditional(struct strbuf *root,
707 const char *line,
708 char *def,
709 int p_value)
711 size_t len;
712 size_t date_len;
714 if (*line == '"') {
715 char *name = find_name_gnu(root, line, p_value);
716 if (name)
717 return name;
720 len = strchrnul(line, '\n') - line;
721 date_len = diff_timestamp_len(line, len);
722 if (!date_len)
723 return find_name_common(root, line, def, p_value, NULL, TERM_TAB);
724 len -= date_len;
726 return find_name_common(root, line, def, p_value, line + len, 0);
730 * Given the string after "--- " or "+++ ", guess the appropriate
731 * p_value for the given patch.
733 static int guess_p_value(struct apply_state *state, const char *nameline)
735 char *name, *cp;
736 int val = -1;
738 if (is_dev_null(nameline))
739 return -1;
740 name = find_name_traditional(&state->root, nameline, NULL, 0);
741 if (!name)
742 return -1;
743 cp = strchr(name, '/');
744 if (!cp)
745 val = 0;
746 else if (state->prefix) {
748 * Does it begin with "a/$our-prefix" and such? Then this is
749 * very likely to apply to our directory.
751 if (starts_with(name, state->prefix))
752 val = count_slashes(state->prefix);
753 else {
754 cp++;
755 if (starts_with(cp, state->prefix))
756 val = count_slashes(state->prefix) + 1;
759 free(name);
760 return val;
764 * Does the ---/+++ line have the POSIX timestamp after the last HT?
765 * GNU diff puts epoch there to signal a creation/deletion event. Is
766 * this such a timestamp?
768 static int has_epoch_timestamp(const char *nameline)
771 * We are only interested in epoch timestamp; any non-zero
772 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
773 * For the same reason, the date must be either 1969-12-31 or
774 * 1970-01-01, and the seconds part must be "00".
776 const char stamp_regexp[] =
777 "^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?"
779 "([-+][0-2][0-9]:?[0-5][0-9])\n";
780 const char *timestamp = NULL, *cp, *colon;
781 static regex_t *stamp;
782 regmatch_t m[10];
783 int zoneoffset, epoch_hour, hour, minute;
784 int status;
786 for (cp = nameline; *cp != '\n'; cp++) {
787 if (*cp == '\t')
788 timestamp = cp + 1;
790 if (!timestamp)
791 return 0;
794 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
795 * (west of GMT) or 1970-01-01 (east of GMT)
797 if (skip_prefix(timestamp, "1969-12-31 ", &timestamp))
798 epoch_hour = 24;
799 else if (skip_prefix(timestamp, "1970-01-01 ", &timestamp))
800 epoch_hour = 0;
801 else
802 return 0;
804 if (!stamp) {
805 stamp = xmalloc(sizeof(*stamp));
806 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
807 warning(_("Cannot prepare timestamp regexp %s"),
808 stamp_regexp);
809 return 0;
813 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
814 if (status) {
815 if (status != REG_NOMATCH)
816 warning(_("regexec returned %d for input: %s"),
817 status, timestamp);
818 return 0;
821 hour = strtol(timestamp, NULL, 10);
822 minute = strtol(timestamp + m[1].rm_so, NULL, 10);
824 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
825 if (*colon == ':')
826 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
827 else
828 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
829 if (timestamp[m[3].rm_so] == '-')
830 zoneoffset = -zoneoffset;
832 return hour * 60 + minute - zoneoffset == epoch_hour * 60;
836 * Get the name etc info from the ---/+++ lines of a traditional patch header
838 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
839 * files, we can happily check the index for a match, but for creating a
840 * new file we should try to match whatever "patch" does. I have no idea.
842 static int parse_traditional_patch(struct apply_state *state,
843 const char *first,
844 const char *second,
845 struct patch *patch)
847 char *name;
849 first += 4; /* skip "--- " */
850 second += 4; /* skip "+++ " */
851 if (!state->p_value_known) {
852 int p, q;
853 p = guess_p_value(state, first);
854 q = guess_p_value(state, second);
855 if (p < 0) p = q;
856 if (0 <= p && p == q) {
857 state->p_value = p;
858 state->p_value_known = 1;
861 if (is_dev_null(first)) {
862 patch->is_new = 1;
863 patch->is_delete = 0;
864 name = find_name_traditional(&state->root, second, NULL, state->p_value);
865 patch->new_name = name;
866 } else if (is_dev_null(second)) {
867 patch->is_new = 0;
868 patch->is_delete = 1;
869 name = find_name_traditional(&state->root, first, NULL, state->p_value);
870 patch->old_name = name;
871 } else {
872 char *first_name;
873 first_name = find_name_traditional(&state->root, first, NULL, state->p_value);
874 name = find_name_traditional(&state->root, second, first_name, state->p_value);
875 free(first_name);
876 if (has_epoch_timestamp(first)) {
877 patch->is_new = 1;
878 patch->is_delete = 0;
879 patch->new_name = name;
880 } else if (has_epoch_timestamp(second)) {
881 patch->is_new = 0;
882 patch->is_delete = 1;
883 patch->old_name = name;
884 } else {
885 patch->old_name = name;
886 patch->new_name = xstrdup_or_null(name);
889 if (!name)
890 return error(_("unable to find filename in patch at line %d"), state->linenr);
892 return 0;
895 static int gitdiff_hdrend(struct gitdiff_data *state,
896 const char *line,
897 struct patch *patch)
899 return 1;
903 * We're anal about diff header consistency, to make
904 * sure that we don't end up having strange ambiguous
905 * patches floating around.
907 * As a result, gitdiff_{old|new}name() will check
908 * their names against any previous information, just
909 * to make sure..
911 #define DIFF_OLD_NAME 0
912 #define DIFF_NEW_NAME 1
914 static int gitdiff_verify_name(struct gitdiff_data *state,
915 const char *line,
916 int isnull,
917 char **name,
918 int side)
920 if (!*name && !isnull) {
921 *name = find_name(state->root, line, NULL, state->p_value, TERM_TAB);
922 return 0;
925 if (*name) {
926 char *another;
927 if (isnull)
928 return error(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
929 *name, state->linenr);
930 another = find_name(state->root, line, NULL, state->p_value, TERM_TAB);
931 if (!another || strcmp(another, *name)) {
932 free(another);
933 return error((side == DIFF_NEW_NAME) ?
934 _("git apply: bad git-diff - inconsistent new filename on line %d") :
935 _("git apply: bad git-diff - inconsistent old filename on line %d"), state->linenr);
937 free(another);
938 } else {
939 if (!is_dev_null(line))
940 return error(_("git apply: bad git-diff - expected /dev/null on line %d"), state->linenr);
943 return 0;
946 static int gitdiff_oldname(struct gitdiff_data *state,
947 const char *line,
948 struct patch *patch)
950 return gitdiff_verify_name(state, line,
951 patch->is_new, &patch->old_name,
952 DIFF_OLD_NAME);
955 static int gitdiff_newname(struct gitdiff_data *state,
956 const char *line,
957 struct patch *patch)
959 return gitdiff_verify_name(state, line,
960 patch->is_delete, &patch->new_name,
961 DIFF_NEW_NAME);
964 static int parse_mode_line(const char *line, int linenr, unsigned int *mode)
966 char *end;
967 *mode = strtoul(line, &end, 8);
968 if (end == line || !isspace(*end))
969 return error(_("invalid mode on line %d: %s"), linenr, line);
970 return 0;
973 static int gitdiff_oldmode(struct gitdiff_data *state,
974 const char *line,
975 struct patch *patch)
977 return parse_mode_line(line, state->linenr, &patch->old_mode);
980 static int gitdiff_newmode(struct gitdiff_data *state,
981 const char *line,
982 struct patch *patch)
984 return parse_mode_line(line, state->linenr, &patch->new_mode);
987 static int gitdiff_delete(struct gitdiff_data *state,
988 const char *line,
989 struct patch *patch)
991 patch->is_delete = 1;
992 free(patch->old_name);
993 patch->old_name = xstrdup_or_null(patch->def_name);
994 return gitdiff_oldmode(state, line, patch);
997 static int gitdiff_newfile(struct gitdiff_data *state,
998 const char *line,
999 struct patch *patch)
1001 patch->is_new = 1;
1002 free(patch->new_name);
1003 patch->new_name = xstrdup_or_null(patch->def_name);
1004 return gitdiff_newmode(state, line, patch);
1007 static int gitdiff_copysrc(struct gitdiff_data *state,
1008 const char *line,
1009 struct patch *patch)
1011 patch->is_copy = 1;
1012 free(patch->old_name);
1013 patch->old_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1014 return 0;
1017 static int gitdiff_copydst(struct gitdiff_data *state,
1018 const char *line,
1019 struct patch *patch)
1021 patch->is_copy = 1;
1022 free(patch->new_name);
1023 patch->new_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1024 return 0;
1027 static int gitdiff_renamesrc(struct gitdiff_data *state,
1028 const char *line,
1029 struct patch *patch)
1031 patch->is_rename = 1;
1032 free(patch->old_name);
1033 patch->old_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1034 return 0;
1037 static int gitdiff_renamedst(struct gitdiff_data *state,
1038 const char *line,
1039 struct patch *patch)
1041 patch->is_rename = 1;
1042 free(patch->new_name);
1043 patch->new_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
1044 return 0;
1047 static int gitdiff_similarity(struct gitdiff_data *state,
1048 const char *line,
1049 struct patch *patch)
1051 unsigned long val = strtoul(line, NULL, 10);
1052 if (val <= 100)
1053 patch->score = val;
1054 return 0;
1057 static int gitdiff_dissimilarity(struct gitdiff_data *state,
1058 const char *line,
1059 struct patch *patch)
1061 unsigned long val = strtoul(line, NULL, 10);
1062 if (val <= 100)
1063 patch->score = val;
1064 return 0;
1067 static int gitdiff_index(struct gitdiff_data *state,
1068 const char *line,
1069 struct patch *patch)
1072 * index line is N hexadecimal, "..", N hexadecimal,
1073 * and optional space with octal mode.
1075 const char *ptr, *eol;
1076 int len;
1077 const unsigned hexsz = the_hash_algo->hexsz;
1079 ptr = strchr(line, '.');
1080 if (!ptr || ptr[1] != '.' || hexsz < ptr - line)
1081 return 0;
1082 len = ptr - line;
1083 memcpy(patch->old_oid_prefix, line, len);
1084 patch->old_oid_prefix[len] = 0;
1086 line = ptr + 2;
1087 ptr = strchr(line, ' ');
1088 eol = strchrnul(line, '\n');
1090 if (!ptr || eol < ptr)
1091 ptr = eol;
1092 len = ptr - line;
1094 if (hexsz < len)
1095 return 0;
1096 memcpy(patch->new_oid_prefix, line, len);
1097 patch->new_oid_prefix[len] = 0;
1098 if (*ptr == ' ')
1099 return gitdiff_oldmode(state, ptr + 1, patch);
1100 return 0;
1104 * This is normal for a diff that doesn't change anything: we'll fall through
1105 * into the next diff. Tell the parser to break out.
1107 static int gitdiff_unrecognized(struct gitdiff_data *state,
1108 const char *line,
1109 struct patch *patch)
1111 return 1;
1115 * Skip p_value leading components from "line"; as we do not accept
1116 * absolute paths, return NULL in that case.
1118 static const char *skip_tree_prefix(int p_value,
1119 const char *line,
1120 int llen)
1122 int nslash;
1123 int i;
1125 if (!p_value)
1126 return (llen && line[0] == '/') ? NULL : line;
1128 nslash = p_value;
1129 for (i = 0; i < llen; i++) {
1130 int ch = line[i];
1131 if (ch == '/' && --nslash <= 0)
1132 return (i == 0) ? NULL : &line[i + 1];
1134 return NULL;
1138 * This is to extract the same name that appears on "diff --git"
1139 * line. We do not find and return anything if it is a rename
1140 * patch, and it is OK because we will find the name elsewhere.
1141 * We need to reliably find name only when it is mode-change only,
1142 * creation or deletion of an empty file. In any of these cases,
1143 * both sides are the same name under a/ and b/ respectively.
1145 static char *git_header_name(int p_value,
1146 const char *line,
1147 int llen)
1149 const char *name;
1150 const char *second = NULL;
1151 size_t len, line_len;
1153 line += strlen("diff --git ");
1154 llen -= strlen("diff --git ");
1156 if (*line == '"') {
1157 const char *cp;
1158 struct strbuf first = STRBUF_INIT;
1159 struct strbuf sp = STRBUF_INIT;
1161 if (unquote_c_style(&first, line, &second))
1162 goto free_and_fail1;
1164 /* strip the a/b prefix including trailing slash */
1165 cp = skip_tree_prefix(p_value, first.buf, first.len);
1166 if (!cp)
1167 goto free_and_fail1;
1168 strbuf_remove(&first, 0, cp - first.buf);
1171 * second points at one past closing dq of name.
1172 * find the second name.
1174 while ((second < line + llen) && isspace(*second))
1175 second++;
1177 if (line + llen <= second)
1178 goto free_and_fail1;
1179 if (*second == '"') {
1180 if (unquote_c_style(&sp, second, NULL))
1181 goto free_and_fail1;
1182 cp = skip_tree_prefix(p_value, sp.buf, sp.len);
1183 if (!cp)
1184 goto free_and_fail1;
1185 /* They must match, otherwise ignore */
1186 if (strcmp(cp, first.buf))
1187 goto free_and_fail1;
1188 strbuf_release(&sp);
1189 return strbuf_detach(&first, NULL);
1192 /* unquoted second */
1193 cp = skip_tree_prefix(p_value, second, line + llen - second);
1194 if (!cp)
1195 goto free_and_fail1;
1196 if (line + llen - cp != first.len ||
1197 memcmp(first.buf, cp, first.len))
1198 goto free_and_fail1;
1199 return strbuf_detach(&first, NULL);
1201 free_and_fail1:
1202 strbuf_release(&first);
1203 strbuf_release(&sp);
1204 return NULL;
1207 /* unquoted first name */
1208 name = skip_tree_prefix(p_value, line, llen);
1209 if (!name)
1210 return NULL;
1213 * since the first name is unquoted, a dq if exists must be
1214 * the beginning of the second name.
1216 for (second = name; second < line + llen; second++) {
1217 if (*second == '"') {
1218 struct strbuf sp = STRBUF_INIT;
1219 const char *np;
1221 if (unquote_c_style(&sp, second, NULL))
1222 goto free_and_fail2;
1224 np = skip_tree_prefix(p_value, sp.buf, sp.len);
1225 if (!np)
1226 goto free_and_fail2;
1228 len = sp.buf + sp.len - np;
1229 if (len < second - name &&
1230 !strncmp(np, name, len) &&
1231 isspace(name[len])) {
1232 /* Good */
1233 strbuf_remove(&sp, 0, np - sp.buf);
1234 return strbuf_detach(&sp, NULL);
1237 free_and_fail2:
1238 strbuf_release(&sp);
1239 return NULL;
1244 * Accept a name only if it shows up twice, exactly the same
1245 * form.
1247 second = strchr(name, '\n');
1248 if (!second)
1249 return NULL;
1250 line_len = second - name;
1251 for (len = 0 ; ; len++) {
1252 switch (name[len]) {
1253 default:
1254 continue;
1255 case '\n':
1256 return NULL;
1257 case '\t': case ' ':
1259 * Is this the separator between the preimage
1260 * and the postimage pathname? Again, we are
1261 * only interested in the case where there is
1262 * no rename, as this is only to set def_name
1263 * and a rename patch has the names elsewhere
1264 * in an unambiguous form.
1266 if (!name[len + 1])
1267 return NULL; /* no postimage name */
1268 second = skip_tree_prefix(p_value, name + len + 1,
1269 line_len - (len + 1));
1270 if (!second)
1271 return NULL;
1273 * Does len bytes starting at "name" and "second"
1274 * (that are separated by one HT or SP we just
1275 * found) exactly match?
1277 if (second[len] == '\n' && !strncmp(name, second, len))
1278 return xmemdupz(name, len);
1283 static int check_header_line(int linenr, struct patch *patch)
1285 int extensions = (patch->is_delete == 1) + (patch->is_new == 1) +
1286 (patch->is_rename == 1) + (patch->is_copy == 1);
1287 if (extensions > 1)
1288 return error(_("inconsistent header lines %d and %d"),
1289 patch->extension_linenr, linenr);
1290 if (extensions && !patch->extension_linenr)
1291 patch->extension_linenr = linenr;
1292 return 0;
1295 int parse_git_diff_header(struct strbuf *root,
1296 int *linenr,
1297 int p_value,
1298 const char *line,
1299 int len,
1300 unsigned int size,
1301 struct patch *patch)
1303 unsigned long offset;
1304 struct gitdiff_data parse_hdr_state;
1306 /* A git diff has explicit new/delete information, so we don't guess */
1307 patch->is_new = 0;
1308 patch->is_delete = 0;
1311 * Some things may not have the old name in the
1312 * rest of the headers anywhere (pure mode changes,
1313 * or removing or adding empty files), so we get
1314 * the default name from the header.
1316 patch->def_name = git_header_name(p_value, line, len);
1317 if (patch->def_name && root->len) {
1318 char *s = xstrfmt("%s%s", root->buf, patch->def_name);
1319 free(patch->def_name);
1320 patch->def_name = s;
1323 line += len;
1324 size -= len;
1325 (*linenr)++;
1326 parse_hdr_state.root = root;
1327 parse_hdr_state.linenr = *linenr;
1328 parse_hdr_state.p_value = p_value;
1330 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, (*linenr)++) {
1331 static const struct opentry {
1332 const char *str;
1333 int (*fn)(struct gitdiff_data *, const char *, struct patch *);
1334 } optable[] = {
1335 { "@@ -", gitdiff_hdrend },
1336 { "--- ", gitdiff_oldname },
1337 { "+++ ", gitdiff_newname },
1338 { "old mode ", gitdiff_oldmode },
1339 { "new mode ", gitdiff_newmode },
1340 { "deleted file mode ", gitdiff_delete },
1341 { "new file mode ", gitdiff_newfile },
1342 { "copy from ", gitdiff_copysrc },
1343 { "copy to ", gitdiff_copydst },
1344 { "rename old ", gitdiff_renamesrc },
1345 { "rename new ", gitdiff_renamedst },
1346 { "rename from ", gitdiff_renamesrc },
1347 { "rename to ", gitdiff_renamedst },
1348 { "similarity index ", gitdiff_similarity },
1349 { "dissimilarity index ", gitdiff_dissimilarity },
1350 { "index ", gitdiff_index },
1351 { "", gitdiff_unrecognized },
1353 int i;
1355 len = linelen(line, size);
1356 if (!len || line[len-1] != '\n')
1357 break;
1358 for (i = 0; i < ARRAY_SIZE(optable); i++) {
1359 const struct opentry *p = optable + i;
1360 int oplen = strlen(p->str);
1361 int res;
1362 if (len < oplen || memcmp(p->str, line, oplen))
1363 continue;
1364 res = p->fn(&parse_hdr_state, line + oplen, patch);
1365 if (res < 0)
1366 return -1;
1367 if (check_header_line(*linenr, patch))
1368 return -1;
1369 if (res > 0)
1370 goto done;
1371 break;
1375 done:
1376 if (!patch->old_name && !patch->new_name) {
1377 if (!patch->def_name) {
1378 error(Q_("git diff header lacks filename information when removing "
1379 "%d leading pathname component (line %d)",
1380 "git diff header lacks filename information when removing "
1381 "%d leading pathname components (line %d)",
1382 parse_hdr_state.p_value),
1383 parse_hdr_state.p_value, *linenr);
1384 return -128;
1386 patch->old_name = xstrdup(patch->def_name);
1387 patch->new_name = xstrdup(patch->def_name);
1389 if ((!patch->new_name && !patch->is_delete) ||
1390 (!patch->old_name && !patch->is_new)) {
1391 error(_("git diff header lacks filename information "
1392 "(line %d)"), *linenr);
1393 return -128;
1395 patch->is_toplevel_relative = 1;
1396 return offset;
1399 static int parse_num(const char *line, unsigned long *p)
1401 char *ptr;
1403 if (!isdigit(*line))
1404 return 0;
1405 *p = strtoul(line, &ptr, 10);
1406 return ptr - line;
1409 static int parse_range(const char *line, int len, int offset, const char *expect,
1410 unsigned long *p1, unsigned long *p2)
1412 int digits, ex;
1414 if (offset < 0 || offset >= len)
1415 return -1;
1416 line += offset;
1417 len -= offset;
1419 digits = parse_num(line, p1);
1420 if (!digits)
1421 return -1;
1423 offset += digits;
1424 line += digits;
1425 len -= digits;
1427 *p2 = 1;
1428 if (*line == ',') {
1429 digits = parse_num(line+1, p2);
1430 if (!digits)
1431 return -1;
1433 offset += digits+1;
1434 line += digits+1;
1435 len -= digits+1;
1438 ex = strlen(expect);
1439 if (ex > len)
1440 return -1;
1441 if (memcmp(line, expect, ex))
1442 return -1;
1444 return offset + ex;
1447 static void recount_diff(const char *line, int size, struct fragment *fragment)
1449 int oldlines = 0, newlines = 0, ret = 0;
1451 if (size < 1) {
1452 warning("recount: ignore empty hunk");
1453 return;
1456 for (;;) {
1457 int len = linelen(line, size);
1458 size -= len;
1459 line += len;
1461 if (size < 1)
1462 break;
1464 switch (*line) {
1465 case ' ': case '\n':
1466 newlines++;
1467 /* fall through */
1468 case '-':
1469 oldlines++;
1470 continue;
1471 case '+':
1472 newlines++;
1473 continue;
1474 case '\\':
1475 continue;
1476 case '@':
1477 ret = size < 3 || !starts_with(line, "@@ ");
1478 break;
1479 case 'd':
1480 ret = size < 5 || !starts_with(line, "diff ");
1481 break;
1482 default:
1483 ret = -1;
1484 break;
1486 if (ret) {
1487 warning(_("recount: unexpected line: %.*s"),
1488 (int)linelen(line, size), line);
1489 return;
1491 break;
1493 fragment->oldlines = oldlines;
1494 fragment->newlines = newlines;
1498 * Parse a unified diff fragment header of the
1499 * form "@@ -a,b +c,d @@"
1501 static int parse_fragment_header(const char *line, int len, struct fragment *fragment)
1503 int offset;
1505 if (!len || line[len-1] != '\n')
1506 return -1;
1508 /* Figure out the number of lines in a fragment */
1509 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1510 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1512 return offset;
1516 * Find file diff header
1518 * Returns:
1519 * -1 if no header was found
1520 * -128 in case of error
1521 * the size of the header in bytes (called "offset") otherwise
1523 static int find_header(struct apply_state *state,
1524 const char *line,
1525 unsigned long size,
1526 int *hdrsize,
1527 struct patch *patch)
1529 unsigned long offset, len;
1531 patch->is_toplevel_relative = 0;
1532 patch->is_rename = patch->is_copy = 0;
1533 patch->is_new = patch->is_delete = -1;
1534 patch->old_mode = patch->new_mode = 0;
1535 patch->old_name = patch->new_name = NULL;
1536 for (offset = 0; size > 0; offset += len, size -= len, line += len, state->linenr++) {
1537 unsigned long nextlen;
1539 len = linelen(line, size);
1540 if (!len)
1541 break;
1543 /* Testing this early allows us to take a few shortcuts.. */
1544 if (len < 6)
1545 continue;
1548 * Make sure we don't find any unconnected patch fragments.
1549 * That's a sign that we didn't find a header, and that a
1550 * patch has become corrupted/broken up.
1552 if (!memcmp("@@ -", line, 4)) {
1553 struct fragment dummy;
1554 if (parse_fragment_header(line, len, &dummy) < 0)
1555 continue;
1556 error(_("patch fragment without header at line %d: %.*s"),
1557 state->linenr, (int)len-1, line);
1558 return -128;
1561 if (size < len + 6)
1562 break;
1565 * Git patch? It might not have a real patch, just a rename
1566 * or mode change, so we handle that specially
1568 if (!memcmp("diff --git ", line, 11)) {
1569 int git_hdr_len = parse_git_diff_header(&state->root, &state->linenr,
1570 state->p_value, line, len,
1571 size, patch);
1572 if (git_hdr_len < 0)
1573 return -128;
1574 if (git_hdr_len <= len)
1575 continue;
1576 *hdrsize = git_hdr_len;
1577 return offset;
1580 /* --- followed by +++ ? */
1581 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1582 continue;
1585 * We only accept unified patches, so we want it to
1586 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1587 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1589 nextlen = linelen(line + len, size - len);
1590 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1591 continue;
1593 /* Ok, we'll consider it a patch */
1594 if (parse_traditional_patch(state, line, line+len, patch))
1595 return -128;
1596 *hdrsize = len + nextlen;
1597 state->linenr += 2;
1598 return offset;
1600 return -1;
1603 static void record_ws_error(struct apply_state *state,
1604 unsigned result,
1605 const char *line,
1606 int len,
1607 int linenr)
1609 char *err;
1611 if (!result)
1612 return;
1614 state->whitespace_error++;
1615 if (state->squelch_whitespace_errors &&
1616 state->squelch_whitespace_errors < state->whitespace_error)
1617 return;
1619 err = whitespace_error_string(result);
1620 if (state->apply_verbosity > verbosity_silent)
1621 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1622 state->patch_input_file, linenr, err, len, line);
1623 free(err);
1626 static void check_whitespace(struct apply_state *state,
1627 const char *line,
1628 int len,
1629 unsigned ws_rule)
1631 unsigned result = ws_check(line + 1, len - 1, ws_rule);
1633 record_ws_error(state, result, line + 1, len - 2, state->linenr);
1637 * Check if the patch has context lines with CRLF or
1638 * the patch wants to remove lines with CRLF.
1640 static void check_old_for_crlf(struct patch *patch, const char *line, int len)
1642 if (len >= 2 && line[len-1] == '\n' && line[len-2] == '\r') {
1643 patch->ws_rule |= WS_CR_AT_EOL;
1644 patch->crlf_in_old = 1;
1650 * Parse a unified diff. Note that this really needs to parse each
1651 * fragment separately, since the only way to know the difference
1652 * between a "---" that is part of a patch, and a "---" that starts
1653 * the next patch is to look at the line counts..
1655 static int parse_fragment(struct apply_state *state,
1656 const char *line,
1657 unsigned long size,
1658 struct patch *patch,
1659 struct fragment *fragment)
1661 int added, deleted;
1662 int len = linelen(line, size), offset;
1663 unsigned long oldlines, newlines;
1664 unsigned long leading, trailing;
1666 offset = parse_fragment_header(line, len, fragment);
1667 if (offset < 0)
1668 return -1;
1669 if (offset > 0 && patch->recount)
1670 recount_diff(line + offset, size - offset, fragment);
1671 oldlines = fragment->oldlines;
1672 newlines = fragment->newlines;
1673 leading = 0;
1674 trailing = 0;
1676 /* Parse the thing.. */
1677 line += len;
1678 size -= len;
1679 state->linenr++;
1680 added = deleted = 0;
1681 for (offset = len;
1682 0 < size;
1683 offset += len, size -= len, line += len, state->linenr++) {
1684 if (!oldlines && !newlines)
1685 break;
1686 len = linelen(line, size);
1687 if (!len || line[len-1] != '\n')
1688 return -1;
1689 switch (*line) {
1690 default:
1691 return -1;
1692 case '\n': /* newer GNU diff, an empty context line */
1693 case ' ':
1694 oldlines--;
1695 newlines--;
1696 if (!deleted && !added)
1697 leading++;
1698 trailing++;
1699 check_old_for_crlf(patch, line, len);
1700 if (!state->apply_in_reverse &&
1701 state->ws_error_action == correct_ws_error)
1702 check_whitespace(state, line, len, patch->ws_rule);
1703 break;
1704 case '-':
1705 if (!state->apply_in_reverse)
1706 check_old_for_crlf(patch, line, len);
1707 if (state->apply_in_reverse &&
1708 state->ws_error_action != nowarn_ws_error)
1709 check_whitespace(state, line, len, patch->ws_rule);
1710 deleted++;
1711 oldlines--;
1712 trailing = 0;
1713 break;
1714 case '+':
1715 if (state->apply_in_reverse)
1716 check_old_for_crlf(patch, line, len);
1717 if (!state->apply_in_reverse &&
1718 state->ws_error_action != nowarn_ws_error)
1719 check_whitespace(state, line, len, patch->ws_rule);
1720 added++;
1721 newlines--;
1722 trailing = 0;
1723 break;
1726 * We allow "\ No newline at end of file". Depending
1727 * on locale settings when the patch was produced we
1728 * don't know what this line looks like. The only
1729 * thing we do know is that it begins with "\ ".
1730 * Checking for 12 is just for sanity check -- any
1731 * l10n of "\ No newline..." is at least that long.
1733 case '\\':
1734 if (len < 12 || memcmp(line, "\\ ", 2))
1735 return -1;
1736 break;
1739 if (oldlines || newlines)
1740 return -1;
1741 if (!patch->recount && !deleted && !added)
1742 return -1;
1744 fragment->leading = leading;
1745 fragment->trailing = trailing;
1748 * If a fragment ends with an incomplete line, we failed to include
1749 * it in the above loop because we hit oldlines == newlines == 0
1750 * before seeing it.
1752 if (12 < size && !memcmp(line, "\\ ", 2))
1753 offset += linelen(line, size);
1755 patch->lines_added += added;
1756 patch->lines_deleted += deleted;
1758 if (0 < patch->is_new && oldlines)
1759 return error(_("new file depends on old contents"));
1760 if (0 < patch->is_delete && newlines)
1761 return error(_("deleted file still has contents"));
1762 return offset;
1766 * We have seen "diff --git a/... b/..." header (or a traditional patch
1767 * header). Read hunks that belong to this patch into fragments and hang
1768 * them to the given patch structure.
1770 * The (fragment->patch, fragment->size) pair points into the memory given
1771 * by the caller, not a copy, when we return.
1773 * Returns:
1774 * -1 in case of error,
1775 * the number of bytes in the patch otherwise.
1777 static int parse_single_patch(struct apply_state *state,
1778 const char *line,
1779 unsigned long size,
1780 struct patch *patch)
1782 unsigned long offset = 0;
1783 unsigned long oldlines = 0, newlines = 0, context = 0;
1784 struct fragment **fragp = &patch->fragments;
1786 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1787 struct fragment *fragment;
1788 int len;
1790 CALLOC_ARRAY(fragment, 1);
1791 fragment->linenr = state->linenr;
1792 len = parse_fragment(state, line, size, patch, fragment);
1793 if (len <= 0) {
1794 free(fragment);
1795 return error(_("corrupt patch at line %d"), state->linenr);
1797 fragment->patch = line;
1798 fragment->size = len;
1799 oldlines += fragment->oldlines;
1800 newlines += fragment->newlines;
1801 context += fragment->leading + fragment->trailing;
1803 *fragp = fragment;
1804 fragp = &fragment->next;
1806 offset += len;
1807 line += len;
1808 size -= len;
1812 * If something was removed (i.e. we have old-lines) it cannot
1813 * be creation, and if something was added it cannot be
1814 * deletion. However, the reverse is not true; --unified=0
1815 * patches that only add are not necessarily creation even
1816 * though they do not have any old lines, and ones that only
1817 * delete are not necessarily deletion.
1819 * Unfortunately, a real creation/deletion patch do _not_ have
1820 * any context line by definition, so we cannot safely tell it
1821 * apart with --unified=0 insanity. At least if the patch has
1822 * more than one hunk it is not creation or deletion.
1824 if (patch->is_new < 0 &&
1825 (oldlines || (patch->fragments && patch->fragments->next)))
1826 patch->is_new = 0;
1827 if (patch->is_delete < 0 &&
1828 (newlines || (patch->fragments && patch->fragments->next)))
1829 patch->is_delete = 0;
1831 if (0 < patch->is_new && oldlines)
1832 return error(_("new file %s depends on old contents"), patch->new_name);
1833 if (0 < patch->is_delete && newlines)
1834 return error(_("deleted file %s still has contents"), patch->old_name);
1835 if (!patch->is_delete && !newlines && context && state->apply_verbosity > verbosity_silent)
1836 fprintf_ln(stderr,
1837 _("** warning: "
1838 "file %s becomes empty but is not deleted"),
1839 patch->new_name);
1841 return offset;
1844 static inline int metadata_changes(struct patch *patch)
1846 return patch->is_rename > 0 ||
1847 patch->is_copy > 0 ||
1848 patch->is_new > 0 ||
1849 patch->is_delete ||
1850 (patch->old_mode && patch->new_mode &&
1851 patch->old_mode != patch->new_mode);
1854 static char *inflate_it(const void *data, unsigned long size,
1855 unsigned long inflated_size)
1857 git_zstream stream;
1858 void *out;
1859 int st;
1861 memset(&stream, 0, sizeof(stream));
1863 stream.next_in = (unsigned char *)data;
1864 stream.avail_in = size;
1865 stream.next_out = out = xmalloc(inflated_size);
1866 stream.avail_out = inflated_size;
1867 git_inflate_init(&stream);
1868 st = git_inflate(&stream, Z_FINISH);
1869 git_inflate_end(&stream);
1870 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1871 free(out);
1872 return NULL;
1874 return out;
1878 * Read a binary hunk and return a new fragment; fragment->patch
1879 * points at an allocated memory that the caller must free, so
1880 * it is marked as "->free_patch = 1".
1882 static struct fragment *parse_binary_hunk(struct apply_state *state,
1883 char **buf_p,
1884 unsigned long *sz_p,
1885 int *status_p,
1886 int *used_p)
1889 * Expect a line that begins with binary patch method ("literal"
1890 * or "delta"), followed by the length of data before deflating.
1891 * a sequence of 'length-byte' followed by base-85 encoded data
1892 * should follow, terminated by a newline.
1894 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1895 * and we would limit the patch line to 66 characters,
1896 * so one line can fit up to 13 groups that would decode
1897 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1898 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1900 int llen, used;
1901 unsigned long size = *sz_p;
1902 char *buffer = *buf_p;
1903 int patch_method;
1904 unsigned long origlen;
1905 char *data = NULL;
1906 int hunk_size = 0;
1907 struct fragment *frag;
1909 llen = linelen(buffer, size);
1910 used = llen;
1912 *status_p = 0;
1914 if (starts_with(buffer, "delta ")) {
1915 patch_method = BINARY_DELTA_DEFLATED;
1916 origlen = strtoul(buffer + 6, NULL, 10);
1918 else if (starts_with(buffer, "literal ")) {
1919 patch_method = BINARY_LITERAL_DEFLATED;
1920 origlen = strtoul(buffer + 8, NULL, 10);
1922 else
1923 return NULL;
1925 state->linenr++;
1926 buffer += llen;
1927 size -= llen;
1928 while (1) {
1929 int byte_length, max_byte_length, newsize;
1930 llen = linelen(buffer, size);
1931 used += llen;
1932 state->linenr++;
1933 if (llen == 1) {
1934 /* consume the blank line */
1935 buffer++;
1936 size--;
1937 break;
1940 * Minimum line is "A00000\n" which is 7-byte long,
1941 * and the line length must be multiple of 5 plus 2.
1943 if ((llen < 7) || (llen-2) % 5)
1944 goto corrupt;
1945 max_byte_length = (llen - 2) / 5 * 4;
1946 byte_length = *buffer;
1947 if ('A' <= byte_length && byte_length <= 'Z')
1948 byte_length = byte_length - 'A' + 1;
1949 else if ('a' <= byte_length && byte_length <= 'z')
1950 byte_length = byte_length - 'a' + 27;
1951 else
1952 goto corrupt;
1953 /* if the input length was not multiple of 4, we would
1954 * have filler at the end but the filler should never
1955 * exceed 3 bytes
1957 if (max_byte_length < byte_length ||
1958 byte_length <= max_byte_length - 4)
1959 goto corrupt;
1960 newsize = hunk_size + byte_length;
1961 data = xrealloc(data, newsize);
1962 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1963 goto corrupt;
1964 hunk_size = newsize;
1965 buffer += llen;
1966 size -= llen;
1969 CALLOC_ARRAY(frag, 1);
1970 frag->patch = inflate_it(data, hunk_size, origlen);
1971 frag->free_patch = 1;
1972 if (!frag->patch)
1973 goto corrupt;
1974 free(data);
1975 frag->size = origlen;
1976 *buf_p = buffer;
1977 *sz_p = size;
1978 *used_p = used;
1979 frag->binary_patch_method = patch_method;
1980 return frag;
1982 corrupt:
1983 free(data);
1984 *status_p = -1;
1985 error(_("corrupt binary patch at line %d: %.*s"),
1986 state->linenr-1, llen-1, buffer);
1987 return NULL;
1991 * Returns:
1992 * -1 in case of error,
1993 * the length of the parsed binary patch otherwise
1995 static int parse_binary(struct apply_state *state,
1996 char *buffer,
1997 unsigned long size,
1998 struct patch *patch)
2001 * We have read "GIT binary patch\n"; what follows is a line
2002 * that says the patch method (currently, either "literal" or
2003 * "delta") and the length of data before deflating; a
2004 * sequence of 'length-byte' followed by base-85 encoded data
2005 * follows.
2007 * When a binary patch is reversible, there is another binary
2008 * hunk in the same format, starting with patch method (either
2009 * "literal" or "delta") with the length of data, and a sequence
2010 * of length-byte + base-85 encoded data, terminated with another
2011 * empty line. This data, when applied to the postimage, produces
2012 * the preimage.
2014 struct fragment *forward;
2015 struct fragment *reverse;
2016 int status;
2017 int used, used_1;
2019 forward = parse_binary_hunk(state, &buffer, &size, &status, &used);
2020 if (!forward && !status)
2021 /* there has to be one hunk (forward hunk) */
2022 return error(_("unrecognized binary patch at line %d"), state->linenr-1);
2023 if (status)
2024 /* otherwise we already gave an error message */
2025 return status;
2027 reverse = parse_binary_hunk(state, &buffer, &size, &status, &used_1);
2028 if (reverse)
2029 used += used_1;
2030 else if (status) {
2032 * Not having reverse hunk is not an error, but having
2033 * a corrupt reverse hunk is.
2035 free((void*) forward->patch);
2036 free(forward);
2037 return status;
2039 forward->next = reverse;
2040 patch->fragments = forward;
2041 patch->is_binary = 1;
2042 return used;
2045 static void prefix_one(struct apply_state *state, char **name)
2047 char *old_name = *name;
2048 if (!old_name)
2049 return;
2050 *name = prefix_filename(state->prefix, *name);
2051 free(old_name);
2054 static void prefix_patch(struct apply_state *state, struct patch *p)
2056 if (!state->prefix || p->is_toplevel_relative)
2057 return;
2058 prefix_one(state, &p->new_name);
2059 prefix_one(state, &p->old_name);
2063 * include/exclude
2066 static void add_name_limit(struct apply_state *state,
2067 const char *name,
2068 int exclude)
2070 struct string_list_item *it;
2072 it = string_list_append(&state->limit_by_name, name);
2073 it->util = exclude ? NULL : (void *) 1;
2076 static int use_patch(struct apply_state *state, struct patch *p)
2078 const char *pathname = p->new_name ? p->new_name : p->old_name;
2079 int i;
2081 /* Paths outside are not touched regardless of "--include" */
2082 if (state->prefix && *state->prefix) {
2083 const char *rest;
2084 if (!skip_prefix(pathname, state->prefix, &rest) || !*rest)
2085 return 0;
2088 /* See if it matches any of exclude/include rule */
2089 for (i = 0; i < state->limit_by_name.nr; i++) {
2090 struct string_list_item *it = &state->limit_by_name.items[i];
2091 if (!wildmatch(it->string, pathname, 0))
2092 return (it->util != NULL);
2096 * If we had any include, a path that does not match any rule is
2097 * not used. Otherwise, we saw bunch of exclude rules (or none)
2098 * and such a path is used.
2100 return !state->has_include;
2104 * Read the patch text in "buffer" that extends for "size" bytes; stop
2105 * reading after seeing a single patch (i.e. changes to a single file).
2106 * Create fragments (i.e. patch hunks) and hang them to the given patch.
2108 * Returns:
2109 * -1 if no header was found or parse_binary() failed,
2110 * -128 on another error,
2111 * the number of bytes consumed otherwise,
2112 * so that the caller can call us again for the next patch.
2114 static int parse_chunk(struct apply_state *state, char *buffer, unsigned long size, struct patch *patch)
2116 int hdrsize, patchsize;
2117 int offset = find_header(state, buffer, size, &hdrsize, patch);
2119 if (offset < 0)
2120 return offset;
2122 prefix_patch(state, patch);
2124 if (!use_patch(state, patch))
2125 patch->ws_rule = 0;
2126 else if (patch->new_name)
2127 patch->ws_rule = whitespace_rule(state->repo->index,
2128 patch->new_name);
2129 else
2130 patch->ws_rule = whitespace_rule(state->repo->index,
2131 patch->old_name);
2133 patchsize = parse_single_patch(state,
2134 buffer + offset + hdrsize,
2135 size - offset - hdrsize,
2136 patch);
2138 if (patchsize < 0)
2139 return -128;
2141 if (!patchsize) {
2142 static const char git_binary[] = "GIT binary patch\n";
2143 int hd = hdrsize + offset;
2144 unsigned long llen = linelen(buffer + hd, size - hd);
2146 if (llen == sizeof(git_binary) - 1 &&
2147 !memcmp(git_binary, buffer + hd, llen)) {
2148 int used;
2149 state->linenr++;
2150 used = parse_binary(state, buffer + hd + llen,
2151 size - hd - llen, patch);
2152 if (used < 0)
2153 return -1;
2154 if (used)
2155 patchsize = used + llen;
2156 else
2157 patchsize = 0;
2159 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
2160 static const char *binhdr[] = {
2161 "Binary files ",
2162 "Files ",
2163 NULL,
2165 int i;
2166 for (i = 0; binhdr[i]; i++) {
2167 int len = strlen(binhdr[i]);
2168 if (len < size - hd &&
2169 !memcmp(binhdr[i], buffer + hd, len)) {
2170 state->linenr++;
2171 patch->is_binary = 1;
2172 patchsize = llen;
2173 break;
2178 /* Empty patch cannot be applied if it is a text patch
2179 * without metadata change. A binary patch appears
2180 * empty to us here.
2182 if ((state->apply || state->check) &&
2183 (!patch->is_binary && !metadata_changes(patch))) {
2184 error(_("patch with only garbage at line %d"), state->linenr);
2185 return -128;
2189 return offset + hdrsize + patchsize;
2192 static void reverse_patches(struct patch *p)
2194 for (; p; p = p->next) {
2195 struct fragment *frag = p->fragments;
2197 SWAP(p->new_name, p->old_name);
2198 SWAP(p->new_mode, p->old_mode);
2199 SWAP(p->is_new, p->is_delete);
2200 SWAP(p->lines_added, p->lines_deleted);
2201 SWAP(p->old_oid_prefix, p->new_oid_prefix);
2203 for (; frag; frag = frag->next) {
2204 SWAP(frag->newpos, frag->oldpos);
2205 SWAP(frag->newlines, frag->oldlines);
2210 static const char pluses[] =
2211 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2212 static const char minuses[]=
2213 "----------------------------------------------------------------------";
2215 static void show_stats(struct apply_state *state, struct patch *patch)
2217 struct strbuf qname = STRBUF_INIT;
2218 char *cp = patch->new_name ? patch->new_name : patch->old_name;
2219 int max, add, del;
2221 quote_c_style(cp, &qname, NULL, 0);
2224 * "scale" the filename
2226 max = state->max_len;
2227 if (max > 50)
2228 max = 50;
2230 if (qname.len > max) {
2231 cp = strchr(qname.buf + qname.len + 3 - max, '/');
2232 if (!cp)
2233 cp = qname.buf + qname.len + 3 - max;
2234 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
2237 if (patch->is_binary) {
2238 printf(" %-*s | Bin\n", max, qname.buf);
2239 strbuf_release(&qname);
2240 return;
2243 printf(" %-*s |", max, qname.buf);
2244 strbuf_release(&qname);
2247 * scale the add/delete
2249 max = max + state->max_change > 70 ? 70 - max : state->max_change;
2250 add = patch->lines_added;
2251 del = patch->lines_deleted;
2253 if (state->max_change > 0) {
2254 int total = ((add + del) * max + state->max_change / 2) / state->max_change;
2255 add = (add * max + state->max_change / 2) / state->max_change;
2256 del = total - add;
2258 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
2259 add, pluses, del, minuses);
2262 static int read_old_data(struct stat *st, struct patch *patch,
2263 const char *path, struct strbuf *buf)
2265 int conv_flags = patch->crlf_in_old ?
2266 CONV_EOL_KEEP_CRLF : CONV_EOL_RENORMALIZE;
2267 switch (st->st_mode & S_IFMT) {
2268 case S_IFLNK:
2269 if (strbuf_readlink(buf, path, st->st_size) < 0)
2270 return error(_("unable to read symlink %s"), path);
2271 return 0;
2272 case S_IFREG:
2273 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
2274 return error(_("unable to open or read %s"), path);
2276 * "git apply" without "--index/--cached" should never look
2277 * at the index; the target file may not have been added to
2278 * the index yet, and we may not even be in any Git repository.
2279 * Pass NULL to convert_to_git() to stress this; the function
2280 * should never look at the index when explicit crlf option
2281 * is given.
2283 convert_to_git(NULL, path, buf->buf, buf->len, buf, conv_flags);
2284 return 0;
2285 default:
2286 return -1;
2291 * Update the preimage, and the common lines in postimage,
2292 * from buffer buf of length len. If postlen is 0 the postimage
2293 * is updated in place, otherwise it's updated on a new buffer
2294 * of length postlen
2297 static void update_pre_post_images(struct image *preimage,
2298 struct image *postimage,
2299 char *buf,
2300 size_t len, size_t postlen)
2302 int i, ctx, reduced;
2303 char *new_buf, *old_buf, *fixed;
2304 struct image fixed_preimage;
2307 * Update the preimage with whitespace fixes. Note that we
2308 * are not losing preimage->buf -- apply_one_fragment() will
2309 * free "oldlines".
2311 prepare_image(&fixed_preimage, buf, len, 1);
2312 assert(postlen
2313 ? fixed_preimage.nr == preimage->nr
2314 : fixed_preimage.nr <= preimage->nr);
2315 for (i = 0; i < fixed_preimage.nr; i++)
2316 fixed_preimage.line[i].flag = preimage->line[i].flag;
2317 free(preimage->line_allocated);
2318 *preimage = fixed_preimage;
2321 * Adjust the common context lines in postimage. This can be
2322 * done in-place when we are shrinking it with whitespace
2323 * fixing, but needs a new buffer when ignoring whitespace or
2324 * expanding leading tabs to spaces.
2326 * We trust the caller to tell us if the update can be done
2327 * in place (postlen==0) or not.
2329 old_buf = postimage->buf;
2330 if (postlen)
2331 new_buf = postimage->buf = xmalloc(postlen);
2332 else
2333 new_buf = old_buf;
2334 fixed = preimage->buf;
2336 for (i = reduced = ctx = 0; i < postimage->nr; i++) {
2337 size_t l_len = postimage->line[i].len;
2338 if (!(postimage->line[i].flag & LINE_COMMON)) {
2339 /* an added line -- no counterparts in preimage */
2340 memmove(new_buf, old_buf, l_len);
2341 old_buf += l_len;
2342 new_buf += l_len;
2343 continue;
2346 /* a common context -- skip it in the original postimage */
2347 old_buf += l_len;
2349 /* and find the corresponding one in the fixed preimage */
2350 while (ctx < preimage->nr &&
2351 !(preimage->line[ctx].flag & LINE_COMMON)) {
2352 fixed += preimage->line[ctx].len;
2353 ctx++;
2357 * preimage is expected to run out, if the caller
2358 * fixed addition of trailing blank lines.
2360 if (preimage->nr <= ctx) {
2361 reduced++;
2362 continue;
2365 /* and copy it in, while fixing the line length */
2366 l_len = preimage->line[ctx].len;
2367 memcpy(new_buf, fixed, l_len);
2368 new_buf += l_len;
2369 fixed += l_len;
2370 postimage->line[i].len = l_len;
2371 ctx++;
2374 if (postlen
2375 ? postlen < new_buf - postimage->buf
2376 : postimage->len < new_buf - postimage->buf)
2377 BUG("caller miscounted postlen: asked %d, orig = %d, used = %d",
2378 (int)postlen, (int) postimage->len, (int)(new_buf - postimage->buf));
2380 /* Fix the length of the whole thing */
2381 postimage->len = new_buf - postimage->buf;
2382 postimage->nr -= reduced;
2385 static int line_by_line_fuzzy_match(struct image *img,
2386 struct image *preimage,
2387 struct image *postimage,
2388 unsigned long current,
2389 int current_lno,
2390 int preimage_limit)
2392 int i;
2393 size_t imgoff = 0;
2394 size_t preoff = 0;
2395 size_t postlen = postimage->len;
2396 size_t extra_chars;
2397 char *buf;
2398 char *preimage_eof;
2399 char *preimage_end;
2400 struct strbuf fixed;
2401 char *fixed_buf;
2402 size_t fixed_len;
2404 for (i = 0; i < preimage_limit; i++) {
2405 size_t prelen = preimage->line[i].len;
2406 size_t imglen = img->line[current_lno+i].len;
2408 if (!fuzzy_matchlines(img->buf + current + imgoff, imglen,
2409 preimage->buf + preoff, prelen))
2410 return 0;
2411 if (preimage->line[i].flag & LINE_COMMON)
2412 postlen += imglen - prelen;
2413 imgoff += imglen;
2414 preoff += prelen;
2418 * Ok, the preimage matches with whitespace fuzz.
2420 * imgoff now holds the true length of the target that
2421 * matches the preimage before the end of the file.
2423 * Count the number of characters in the preimage that fall
2424 * beyond the end of the file and make sure that all of them
2425 * are whitespace characters. (This can only happen if
2426 * we are removing blank lines at the end of the file.)
2428 buf = preimage_eof = preimage->buf + preoff;
2429 for ( ; i < preimage->nr; i++)
2430 preoff += preimage->line[i].len;
2431 preimage_end = preimage->buf + preoff;
2432 for ( ; buf < preimage_end; buf++)
2433 if (!isspace(*buf))
2434 return 0;
2437 * Update the preimage and the common postimage context
2438 * lines to use the same whitespace as the target.
2439 * If whitespace is missing in the target (i.e.
2440 * if the preimage extends beyond the end of the file),
2441 * use the whitespace from the preimage.
2443 extra_chars = preimage_end - preimage_eof;
2444 strbuf_init(&fixed, imgoff + extra_chars);
2445 strbuf_add(&fixed, img->buf + current, imgoff);
2446 strbuf_add(&fixed, preimage_eof, extra_chars);
2447 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2448 update_pre_post_images(preimage, postimage,
2449 fixed_buf, fixed_len, postlen);
2450 return 1;
2453 static int match_fragment(struct apply_state *state,
2454 struct image *img,
2455 struct image *preimage,
2456 struct image *postimage,
2457 unsigned long current,
2458 int current_lno,
2459 unsigned ws_rule,
2460 int match_beginning, int match_end)
2462 int i;
2463 char *fixed_buf, *buf, *orig, *target;
2464 struct strbuf fixed;
2465 size_t fixed_len, postlen;
2466 int preimage_limit;
2468 if (preimage->nr + current_lno <= img->nr) {
2470 * The hunk falls within the boundaries of img.
2472 preimage_limit = preimage->nr;
2473 if (match_end && (preimage->nr + current_lno != img->nr))
2474 return 0;
2475 } else if (state->ws_error_action == correct_ws_error &&
2476 (ws_rule & WS_BLANK_AT_EOF)) {
2478 * This hunk extends beyond the end of img, and we are
2479 * removing blank lines at the end of the file. This
2480 * many lines from the beginning of the preimage must
2481 * match with img, and the remainder of the preimage
2482 * must be blank.
2484 preimage_limit = img->nr - current_lno;
2485 } else {
2487 * The hunk extends beyond the end of the img and
2488 * we are not removing blanks at the end, so we
2489 * should reject the hunk at this position.
2491 return 0;
2494 if (match_beginning && current_lno)
2495 return 0;
2497 /* Quick hash check */
2498 for (i = 0; i < preimage_limit; i++)
2499 if ((img->line[current_lno + i].flag & LINE_PATCHED) ||
2500 (preimage->line[i].hash != img->line[current_lno + i].hash))
2501 return 0;
2503 if (preimage_limit == preimage->nr) {
2505 * Do we have an exact match? If we were told to match
2506 * at the end, size must be exactly at current+fragsize,
2507 * otherwise current+fragsize must be still within the preimage,
2508 * and either case, the old piece should match the preimage
2509 * exactly.
2511 if ((match_end
2512 ? (current + preimage->len == img->len)
2513 : (current + preimage->len <= img->len)) &&
2514 !memcmp(img->buf + current, preimage->buf, preimage->len))
2515 return 1;
2516 } else {
2518 * The preimage extends beyond the end of img, so
2519 * there cannot be an exact match.
2521 * There must be one non-blank context line that match
2522 * a line before the end of img.
2524 char *buf_end;
2526 buf = preimage->buf;
2527 buf_end = buf;
2528 for (i = 0; i < preimage_limit; i++)
2529 buf_end += preimage->line[i].len;
2531 for ( ; buf < buf_end; buf++)
2532 if (!isspace(*buf))
2533 break;
2534 if (buf == buf_end)
2535 return 0;
2539 * No exact match. If we are ignoring whitespace, run a line-by-line
2540 * fuzzy matching. We collect all the line length information because
2541 * we need it to adjust whitespace if we match.
2543 if (state->ws_ignore_action == ignore_ws_change)
2544 return line_by_line_fuzzy_match(img, preimage, postimage,
2545 current, current_lno, preimage_limit);
2547 if (state->ws_error_action != correct_ws_error)
2548 return 0;
2551 * The hunk does not apply byte-by-byte, but the hash says
2552 * it might with whitespace fuzz. We weren't asked to
2553 * ignore whitespace, we were asked to correct whitespace
2554 * errors, so let's try matching after whitespace correction.
2556 * While checking the preimage against the target, whitespace
2557 * errors in both fixed, we count how large the corresponding
2558 * postimage needs to be. The postimage prepared by
2559 * apply_one_fragment() has whitespace errors fixed on added
2560 * lines already, but the common lines were propagated as-is,
2561 * which may become longer when their whitespace errors are
2562 * fixed.
2565 /* First count added lines in postimage */
2566 postlen = 0;
2567 for (i = 0; i < postimage->nr; i++) {
2568 if (!(postimage->line[i].flag & LINE_COMMON))
2569 postlen += postimage->line[i].len;
2573 * The preimage may extend beyond the end of the file,
2574 * but in this loop we will only handle the part of the
2575 * preimage that falls within the file.
2577 strbuf_init(&fixed, preimage->len + 1);
2578 orig = preimage->buf;
2579 target = img->buf + current;
2580 for (i = 0; i < preimage_limit; i++) {
2581 size_t oldlen = preimage->line[i].len;
2582 size_t tgtlen = img->line[current_lno + i].len;
2583 size_t fixstart = fixed.len;
2584 struct strbuf tgtfix;
2585 int match;
2587 /* Try fixing the line in the preimage */
2588 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2590 /* Try fixing the line in the target */
2591 strbuf_init(&tgtfix, tgtlen);
2592 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2595 * If they match, either the preimage was based on
2596 * a version before our tree fixed whitespace breakage,
2597 * or we are lacking a whitespace-fix patch the tree
2598 * the preimage was based on already had (i.e. target
2599 * has whitespace breakage, the preimage doesn't).
2600 * In either case, we are fixing the whitespace breakages
2601 * so we might as well take the fix together with their
2602 * real change.
2604 match = (tgtfix.len == fixed.len - fixstart &&
2605 !memcmp(tgtfix.buf, fixed.buf + fixstart,
2606 fixed.len - fixstart));
2608 /* Add the length if this is common with the postimage */
2609 if (preimage->line[i].flag & LINE_COMMON)
2610 postlen += tgtfix.len;
2612 strbuf_release(&tgtfix);
2613 if (!match)
2614 goto unmatch_exit;
2616 orig += oldlen;
2617 target += tgtlen;
2622 * Now handle the lines in the preimage that falls beyond the
2623 * end of the file (if any). They will only match if they are
2624 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2625 * false).
2627 for ( ; i < preimage->nr; i++) {
2628 size_t fixstart = fixed.len; /* start of the fixed preimage */
2629 size_t oldlen = preimage->line[i].len;
2630 int j;
2632 /* Try fixing the line in the preimage */
2633 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2635 for (j = fixstart; j < fixed.len; j++)
2636 if (!isspace(fixed.buf[j]))
2637 goto unmatch_exit;
2639 orig += oldlen;
2643 * Yes, the preimage is based on an older version that still
2644 * has whitespace breakages unfixed, and fixing them makes the
2645 * hunk match. Update the context lines in the postimage.
2647 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2648 if (postlen < postimage->len)
2649 postlen = 0;
2650 update_pre_post_images(preimage, postimage,
2651 fixed_buf, fixed_len, postlen);
2652 return 1;
2654 unmatch_exit:
2655 strbuf_release(&fixed);
2656 return 0;
2659 static int find_pos(struct apply_state *state,
2660 struct image *img,
2661 struct image *preimage,
2662 struct image *postimage,
2663 int line,
2664 unsigned ws_rule,
2665 int match_beginning, int match_end)
2667 int i;
2668 unsigned long backwards, forwards, current;
2669 int backwards_lno, forwards_lno, current_lno;
2672 * When running with --allow-overlap, it is possible that a hunk is
2673 * seen that pretends to start at the beginning (but no longer does),
2674 * and that *still* needs to match the end. So trust `match_end` more
2675 * than `match_beginning`.
2677 if (state->allow_overlap && match_beginning && match_end &&
2678 img->nr - preimage->nr != 0)
2679 match_beginning = 0;
2682 * If match_beginning or match_end is specified, there is no
2683 * point starting from a wrong line that will never match and
2684 * wander around and wait for a match at the specified end.
2686 if (match_beginning)
2687 line = 0;
2688 else if (match_end)
2689 line = img->nr - preimage->nr;
2692 * Because the comparison is unsigned, the following test
2693 * will also take care of a negative line number that can
2694 * result when match_end and preimage is larger than the target.
2696 if ((size_t) line > img->nr)
2697 line = img->nr;
2699 current = 0;
2700 for (i = 0; i < line; i++)
2701 current += img->line[i].len;
2704 * There's probably some smart way to do this, but I'll leave
2705 * that to the smart and beautiful people. I'm simple and stupid.
2707 backwards = current;
2708 backwards_lno = line;
2709 forwards = current;
2710 forwards_lno = line;
2711 current_lno = line;
2713 for (i = 0; ; i++) {
2714 if (match_fragment(state, img, preimage, postimage,
2715 current, current_lno, ws_rule,
2716 match_beginning, match_end))
2717 return current_lno;
2719 again:
2720 if (backwards_lno == 0 && forwards_lno == img->nr)
2721 break;
2723 if (i & 1) {
2724 if (backwards_lno == 0) {
2725 i++;
2726 goto again;
2728 backwards_lno--;
2729 backwards -= img->line[backwards_lno].len;
2730 current = backwards;
2731 current_lno = backwards_lno;
2732 } else {
2733 if (forwards_lno == img->nr) {
2734 i++;
2735 goto again;
2737 forwards += img->line[forwards_lno].len;
2738 forwards_lno++;
2739 current = forwards;
2740 current_lno = forwards_lno;
2744 return -1;
2747 static void remove_first_line(struct image *img)
2749 img->buf += img->line[0].len;
2750 img->len -= img->line[0].len;
2751 img->line++;
2752 img->nr--;
2755 static void remove_last_line(struct image *img)
2757 img->len -= img->line[--img->nr].len;
2761 * The change from "preimage" and "postimage" has been found to
2762 * apply at applied_pos (counts in line numbers) in "img".
2763 * Update "img" to remove "preimage" and replace it with "postimage".
2765 static void update_image(struct apply_state *state,
2766 struct image *img,
2767 int applied_pos,
2768 struct image *preimage,
2769 struct image *postimage)
2772 * remove the copy of preimage at offset in img
2773 * and replace it with postimage
2775 int i, nr;
2776 size_t remove_count, insert_count, applied_at = 0;
2777 char *result;
2778 int preimage_limit;
2781 * If we are removing blank lines at the end of img,
2782 * the preimage may extend beyond the end.
2783 * If that is the case, we must be careful only to
2784 * remove the part of the preimage that falls within
2785 * the boundaries of img. Initialize preimage_limit
2786 * to the number of lines in the preimage that falls
2787 * within the boundaries.
2789 preimage_limit = preimage->nr;
2790 if (preimage_limit > img->nr - applied_pos)
2791 preimage_limit = img->nr - applied_pos;
2793 for (i = 0; i < applied_pos; i++)
2794 applied_at += img->line[i].len;
2796 remove_count = 0;
2797 for (i = 0; i < preimage_limit; i++)
2798 remove_count += img->line[applied_pos + i].len;
2799 insert_count = postimage->len;
2801 /* Adjust the contents */
2802 result = xmalloc(st_add3(st_sub(img->len, remove_count), insert_count, 1));
2803 memcpy(result, img->buf, applied_at);
2804 memcpy(result + applied_at, postimage->buf, postimage->len);
2805 memcpy(result + applied_at + postimage->len,
2806 img->buf + (applied_at + remove_count),
2807 img->len - (applied_at + remove_count));
2808 free(img->buf);
2809 img->buf = result;
2810 img->len += insert_count - remove_count;
2811 result[img->len] = '\0';
2813 /* Adjust the line table */
2814 nr = img->nr + postimage->nr - preimage_limit;
2815 if (preimage_limit < postimage->nr) {
2817 * NOTE: this knows that we never call remove_first_line()
2818 * on anything other than pre/post image.
2820 REALLOC_ARRAY(img->line, nr);
2821 img->line_allocated = img->line;
2823 if (preimage_limit != postimage->nr)
2824 MOVE_ARRAY(img->line + applied_pos + postimage->nr,
2825 img->line + applied_pos + preimage_limit,
2826 img->nr - (applied_pos + preimage_limit));
2827 COPY_ARRAY(img->line + applied_pos, postimage->line, postimage->nr);
2828 if (!state->allow_overlap)
2829 for (i = 0; i < postimage->nr; i++)
2830 img->line[applied_pos + i].flag |= LINE_PATCHED;
2831 img->nr = nr;
2835 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2836 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2837 * replace the part of "img" with "postimage" text.
2839 static int apply_one_fragment(struct apply_state *state,
2840 struct image *img, struct fragment *frag,
2841 int inaccurate_eof, unsigned ws_rule,
2842 int nth_fragment)
2844 int match_beginning, match_end;
2845 const char *patch = frag->patch;
2846 int size = frag->size;
2847 char *old, *oldlines;
2848 struct strbuf newlines;
2849 int new_blank_lines_at_end = 0;
2850 int found_new_blank_lines_at_end = 0;
2851 int hunk_linenr = frag->linenr;
2852 unsigned long leading, trailing;
2853 int pos, applied_pos;
2854 struct image preimage;
2855 struct image postimage;
2857 memset(&preimage, 0, sizeof(preimage));
2858 memset(&postimage, 0, sizeof(postimage));
2859 oldlines = xmalloc(size);
2860 strbuf_init(&newlines, size);
2862 old = oldlines;
2863 while (size > 0) {
2864 char first;
2865 int len = linelen(patch, size);
2866 int plen;
2867 int added_blank_line = 0;
2868 int is_blank_context = 0;
2869 size_t start;
2871 if (!len)
2872 break;
2875 * "plen" is how much of the line we should use for
2876 * the actual patch data. Normally we just remove the
2877 * first character on the line, but if the line is
2878 * followed by "\ No newline", then we also remove the
2879 * last one (which is the newline, of course).
2881 plen = len - 1;
2882 if (len < size && patch[len] == '\\')
2883 plen--;
2884 first = *patch;
2885 if (state->apply_in_reverse) {
2886 if (first == '-')
2887 first = '+';
2888 else if (first == '+')
2889 first = '-';
2892 switch (first) {
2893 case '\n':
2894 /* Newer GNU diff, empty context line */
2895 if (plen < 0)
2896 /* ... followed by '\No newline'; nothing */
2897 break;
2898 *old++ = '\n';
2899 strbuf_addch(&newlines, '\n');
2900 add_line_info(&preimage, "\n", 1, LINE_COMMON);
2901 add_line_info(&postimage, "\n", 1, LINE_COMMON);
2902 is_blank_context = 1;
2903 break;
2904 case ' ':
2905 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2906 ws_blank_line(patch + 1, plen, ws_rule))
2907 is_blank_context = 1;
2908 /* fallthrough */
2909 case '-':
2910 memcpy(old, patch + 1, plen);
2911 add_line_info(&preimage, old, plen,
2912 (first == ' ' ? LINE_COMMON : 0));
2913 old += plen;
2914 if (first == '-')
2915 break;
2916 /* fallthrough */
2917 case '+':
2918 /* --no-add does not add new lines */
2919 if (first == '+' && state->no_add)
2920 break;
2922 start = newlines.len;
2923 if (first != '+' ||
2924 !state->whitespace_error ||
2925 state->ws_error_action != correct_ws_error) {
2926 strbuf_add(&newlines, patch + 1, plen);
2928 else {
2929 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &state->applied_after_fixing_ws);
2931 add_line_info(&postimage, newlines.buf + start, newlines.len - start,
2932 (first == '+' ? 0 : LINE_COMMON));
2933 if (first == '+' &&
2934 (ws_rule & WS_BLANK_AT_EOF) &&
2935 ws_blank_line(patch + 1, plen, ws_rule))
2936 added_blank_line = 1;
2937 break;
2938 case '@': case '\\':
2939 /* Ignore it, we already handled it */
2940 break;
2941 default:
2942 if (state->apply_verbosity > verbosity_normal)
2943 error(_("invalid start of line: '%c'"), first);
2944 applied_pos = -1;
2945 goto out;
2947 if (added_blank_line) {
2948 if (!new_blank_lines_at_end)
2949 found_new_blank_lines_at_end = hunk_linenr;
2950 new_blank_lines_at_end++;
2952 else if (is_blank_context)
2954 else
2955 new_blank_lines_at_end = 0;
2956 patch += len;
2957 size -= len;
2958 hunk_linenr++;
2960 if (inaccurate_eof &&
2961 old > oldlines && old[-1] == '\n' &&
2962 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
2963 old--;
2964 strbuf_setlen(&newlines, newlines.len - 1);
2965 preimage.line_allocated[preimage.nr - 1].len--;
2966 postimage.line_allocated[postimage.nr - 1].len--;
2969 leading = frag->leading;
2970 trailing = frag->trailing;
2973 * A hunk to change lines at the beginning would begin with
2974 * @@ -1,L +N,M @@
2975 * but we need to be careful. -U0 that inserts before the second
2976 * line also has this pattern.
2978 * And a hunk to add to an empty file would begin with
2979 * @@ -0,0 +N,M @@
2981 * In other words, a hunk that is (frag->oldpos <= 1) with or
2982 * without leading context must match at the beginning.
2984 match_beginning = (!frag->oldpos ||
2985 (frag->oldpos == 1 && !state->unidiff_zero));
2988 * A hunk without trailing lines must match at the end.
2989 * However, we simply cannot tell if a hunk must match end
2990 * from the lack of trailing lines if the patch was generated
2991 * with unidiff without any context.
2993 match_end = !state->unidiff_zero && !trailing;
2995 pos = frag->newpos ? (frag->newpos - 1) : 0;
2996 preimage.buf = oldlines;
2997 preimage.len = old - oldlines;
2998 postimage.buf = newlines.buf;
2999 postimage.len = newlines.len;
3000 preimage.line = preimage.line_allocated;
3001 postimage.line = postimage.line_allocated;
3003 for (;;) {
3005 applied_pos = find_pos(state, img, &preimage, &postimage, pos,
3006 ws_rule, match_beginning, match_end);
3008 if (applied_pos >= 0)
3009 break;
3011 /* Am I at my context limits? */
3012 if ((leading <= state->p_context) && (trailing <= state->p_context))
3013 break;
3014 if (match_beginning || match_end) {
3015 match_beginning = match_end = 0;
3016 continue;
3020 * Reduce the number of context lines; reduce both
3021 * leading and trailing if they are equal otherwise
3022 * just reduce the larger context.
3024 if (leading >= trailing) {
3025 remove_first_line(&preimage);
3026 remove_first_line(&postimage);
3027 pos--;
3028 leading--;
3030 if (trailing > leading) {
3031 remove_last_line(&preimage);
3032 remove_last_line(&postimage);
3033 trailing--;
3037 if (applied_pos >= 0) {
3038 if (new_blank_lines_at_end &&
3039 preimage.nr + applied_pos >= img->nr &&
3040 (ws_rule & WS_BLANK_AT_EOF) &&
3041 state->ws_error_action != nowarn_ws_error) {
3042 record_ws_error(state, WS_BLANK_AT_EOF, "+", 1,
3043 found_new_blank_lines_at_end);
3044 if (state->ws_error_action == correct_ws_error) {
3045 while (new_blank_lines_at_end--)
3046 remove_last_line(&postimage);
3049 * We would want to prevent write_out_results()
3050 * from taking place in apply_patch() that follows
3051 * the callchain led us here, which is:
3052 * apply_patch->check_patch_list->check_patch->
3053 * apply_data->apply_fragments->apply_one_fragment
3055 if (state->ws_error_action == die_on_ws_error)
3056 state->apply = 0;
3059 if (state->apply_verbosity > verbosity_normal && applied_pos != pos) {
3060 int offset = applied_pos - pos;
3061 if (state->apply_in_reverse)
3062 offset = 0 - offset;
3063 fprintf_ln(stderr,
3064 Q_("Hunk #%d succeeded at %d (offset %d line).",
3065 "Hunk #%d succeeded at %d (offset %d lines).",
3066 offset),
3067 nth_fragment, applied_pos + 1, offset);
3071 * Warn if it was necessary to reduce the number
3072 * of context lines.
3074 if ((leading != frag->leading ||
3075 trailing != frag->trailing) && state->apply_verbosity > verbosity_silent)
3076 fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"
3077 " to apply fragment at %d"),
3078 leading, trailing, applied_pos+1);
3079 update_image(state, img, applied_pos, &preimage, &postimage);
3080 } else {
3081 if (state->apply_verbosity > verbosity_normal)
3082 error(_("while searching for:\n%.*s"),
3083 (int)(old - oldlines), oldlines);
3086 out:
3087 free(oldlines);
3088 strbuf_release(&newlines);
3089 free(preimage.line_allocated);
3090 free(postimage.line_allocated);
3092 return (applied_pos < 0);
3095 static int apply_binary_fragment(struct apply_state *state,
3096 struct image *img,
3097 struct patch *patch)
3099 struct fragment *fragment = patch->fragments;
3100 unsigned long len;
3101 void *dst;
3103 if (!fragment)
3104 return error(_("missing binary patch data for '%s'"),
3105 patch->new_name ?
3106 patch->new_name :
3107 patch->old_name);
3109 /* Binary patch is irreversible without the optional second hunk */
3110 if (state->apply_in_reverse) {
3111 if (!fragment->next)
3112 return error(_("cannot reverse-apply a binary patch "
3113 "without the reverse hunk to '%s'"),
3114 patch->new_name
3115 ? patch->new_name : patch->old_name);
3116 fragment = fragment->next;
3118 switch (fragment->binary_patch_method) {
3119 case BINARY_DELTA_DEFLATED:
3120 dst = patch_delta(img->buf, img->len, fragment->patch,
3121 fragment->size, &len);
3122 if (!dst)
3123 return -1;
3124 clear_image(img);
3125 img->buf = dst;
3126 img->len = len;
3127 return 0;
3128 case BINARY_LITERAL_DEFLATED:
3129 clear_image(img);
3130 img->len = fragment->size;
3131 img->buf = xmemdupz(fragment->patch, img->len);
3132 return 0;
3134 return -1;
3138 * Replace "img" with the result of applying the binary patch.
3139 * The binary patch data itself in patch->fragment is still kept
3140 * but the preimage prepared by the caller in "img" is freed here
3141 * or in the helper function apply_binary_fragment() this calls.
3143 static int apply_binary(struct apply_state *state,
3144 struct image *img,
3145 struct patch *patch)
3147 const char *name = patch->old_name ? patch->old_name : patch->new_name;
3148 struct object_id oid;
3149 const unsigned hexsz = the_hash_algo->hexsz;
3152 * For safety, we require patch index line to contain
3153 * full hex textual object ID for old and new, at least for now.
3155 if (strlen(patch->old_oid_prefix) != hexsz ||
3156 strlen(patch->new_oid_prefix) != hexsz ||
3157 get_oid_hex(patch->old_oid_prefix, &oid) ||
3158 get_oid_hex(patch->new_oid_prefix, &oid))
3159 return error(_("cannot apply binary patch to '%s' "
3160 "without full index line"), name);
3162 if (patch->old_name) {
3164 * See if the old one matches what the patch
3165 * applies to.
3167 hash_object_file(the_hash_algo, img->buf, img->len, OBJ_BLOB,
3168 &oid);
3169 if (strcmp(oid_to_hex(&oid), patch->old_oid_prefix))
3170 return error(_("the patch applies to '%s' (%s), "
3171 "which does not match the "
3172 "current contents."),
3173 name, oid_to_hex(&oid));
3175 else {
3176 /* Otherwise, the old one must be empty. */
3177 if (img->len)
3178 return error(_("the patch applies to an empty "
3179 "'%s' but it is not empty"), name);
3182 get_oid_hex(patch->new_oid_prefix, &oid);
3183 if (is_null_oid(&oid)) {
3184 clear_image(img);
3185 return 0; /* deletion patch */
3188 if (has_object(the_repository, &oid, 0)) {
3189 /* We already have the postimage */
3190 enum object_type type;
3191 unsigned long size;
3192 char *result;
3194 result = read_object_file(&oid, &type, &size);
3195 if (!result)
3196 return error(_("the necessary postimage %s for "
3197 "'%s' cannot be read"),
3198 patch->new_oid_prefix, name);
3199 clear_image(img);
3200 img->buf = result;
3201 img->len = size;
3202 } else {
3204 * We have verified buf matches the preimage;
3205 * apply the patch data to it, which is stored
3206 * in the patch->fragments->{patch,size}.
3208 if (apply_binary_fragment(state, img, patch))
3209 return error(_("binary patch does not apply to '%s'"),
3210 name);
3212 /* verify that the result matches */
3213 hash_object_file(the_hash_algo, img->buf, img->len, OBJ_BLOB,
3214 &oid);
3215 if (strcmp(oid_to_hex(&oid), patch->new_oid_prefix))
3216 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3217 name, patch->new_oid_prefix, oid_to_hex(&oid));
3220 return 0;
3223 static int apply_fragments(struct apply_state *state, struct image *img, struct patch *patch)
3225 struct fragment *frag = patch->fragments;
3226 const char *name = patch->old_name ? patch->old_name : patch->new_name;
3227 unsigned ws_rule = patch->ws_rule;
3228 unsigned inaccurate_eof = patch->inaccurate_eof;
3229 int nth = 0;
3231 if (patch->is_binary)
3232 return apply_binary(state, img, patch);
3234 while (frag) {
3235 nth++;
3236 if (apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {
3237 error(_("patch failed: %s:%ld"), name, frag->oldpos);
3238 if (!state->apply_with_reject)
3239 return -1;
3240 frag->rejected = 1;
3242 frag = frag->next;
3244 return 0;
3247 static int read_blob_object(struct strbuf *buf, const struct object_id *oid, unsigned mode)
3249 if (S_ISGITLINK(mode)) {
3250 strbuf_grow(buf, 100);
3251 strbuf_addf(buf, "Subproject commit %s\n", oid_to_hex(oid));
3252 } else {
3253 enum object_type type;
3254 unsigned long sz;
3255 char *result;
3257 result = read_object_file(oid, &type, &sz);
3258 if (!result)
3259 return -1;
3260 /* XXX read_sha1_file NUL-terminates */
3261 strbuf_attach(buf, result, sz, sz + 1);
3263 return 0;
3266 static int read_file_or_gitlink(const struct cache_entry *ce, struct strbuf *buf)
3268 if (!ce)
3269 return 0;
3270 return read_blob_object(buf, &ce->oid, ce->ce_mode);
3273 static struct patch *in_fn_table(struct apply_state *state, const char *name)
3275 struct string_list_item *item;
3277 if (name == NULL)
3278 return NULL;
3280 item = string_list_lookup(&state->fn_table, name);
3281 if (item != NULL)
3282 return (struct patch *)item->util;
3284 return NULL;
3288 * item->util in the filename table records the status of the path.
3289 * Usually it points at a patch (whose result records the contents
3290 * of it after applying it), but it could be PATH_WAS_DELETED for a
3291 * path that a previously applied patch has already removed, or
3292 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3294 * The latter is needed to deal with a case where two paths A and B
3295 * are swapped by first renaming A to B and then renaming B to A;
3296 * moving A to B should not be prevented due to presence of B as we
3297 * will remove it in a later patch.
3299 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3300 #define PATH_WAS_DELETED ((struct patch *) -1)
3302 static int to_be_deleted(struct patch *patch)
3304 return patch == PATH_TO_BE_DELETED;
3307 static int was_deleted(struct patch *patch)
3309 return patch == PATH_WAS_DELETED;
3312 static void add_to_fn_table(struct apply_state *state, struct patch *patch)
3314 struct string_list_item *item;
3317 * Always add new_name unless patch is a deletion
3318 * This should cover the cases for normal diffs,
3319 * file creations and copies
3321 if (patch->new_name != NULL) {
3322 item = string_list_insert(&state->fn_table, patch->new_name);
3323 item->util = patch;
3327 * store a failure on rename/deletion cases because
3328 * later chunks shouldn't patch old names
3330 if ((patch->new_name == NULL) || (patch->is_rename)) {
3331 item = string_list_insert(&state->fn_table, patch->old_name);
3332 item->util = PATH_WAS_DELETED;
3336 static void prepare_fn_table(struct apply_state *state, struct patch *patch)
3339 * store information about incoming file deletion
3341 while (patch) {
3342 if ((patch->new_name == NULL) || (patch->is_rename)) {
3343 struct string_list_item *item;
3344 item = string_list_insert(&state->fn_table, patch->old_name);
3345 item->util = PATH_TO_BE_DELETED;
3347 patch = patch->next;
3351 static int checkout_target(struct index_state *istate,
3352 struct cache_entry *ce, struct stat *st)
3354 struct checkout costate = CHECKOUT_INIT;
3356 costate.refresh_cache = 1;
3357 costate.istate = istate;
3358 if (checkout_entry(ce, &costate, NULL, NULL) ||
3359 lstat(ce->name, st))
3360 return error(_("cannot checkout %s"), ce->name);
3361 return 0;
3364 static struct patch *previous_patch(struct apply_state *state,
3365 struct patch *patch,
3366 int *gone)
3368 struct patch *previous;
3370 *gone = 0;
3371 if (patch->is_copy || patch->is_rename)
3372 return NULL; /* "git" patches do not depend on the order */
3374 previous = in_fn_table(state, patch->old_name);
3375 if (!previous)
3376 return NULL;
3378 if (to_be_deleted(previous))
3379 return NULL; /* the deletion hasn't happened yet */
3381 if (was_deleted(previous))
3382 *gone = 1;
3384 return previous;
3387 static int verify_index_match(struct apply_state *state,
3388 const struct cache_entry *ce,
3389 struct stat *st)
3391 if (S_ISGITLINK(ce->ce_mode)) {
3392 if (!S_ISDIR(st->st_mode))
3393 return -1;
3394 return 0;
3396 return ie_match_stat(state->repo->index, ce, st,
3397 CE_MATCH_IGNORE_VALID | CE_MATCH_IGNORE_SKIP_WORKTREE);
3400 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3402 static int load_patch_target(struct apply_state *state,
3403 struct strbuf *buf,
3404 const struct cache_entry *ce,
3405 struct stat *st,
3406 struct patch *patch,
3407 const char *name,
3408 unsigned expected_mode)
3410 if (state->cached || state->check_index) {
3411 if (read_file_or_gitlink(ce, buf))
3412 return error(_("failed to read %s"), name);
3413 } else if (name) {
3414 if (S_ISGITLINK(expected_mode)) {
3415 if (ce)
3416 return read_file_or_gitlink(ce, buf);
3417 else
3418 return SUBMODULE_PATCH_WITHOUT_INDEX;
3419 } else if (has_symlink_leading_path(name, strlen(name))) {
3420 return error(_("reading from '%s' beyond a symbolic link"), name);
3421 } else {
3422 if (read_old_data(st, patch, name, buf))
3423 return error(_("failed to read %s"), name);
3426 return 0;
3430 * We are about to apply "patch"; populate the "image" with the
3431 * current version we have, from the working tree or from the index,
3432 * depending on the situation e.g. --cached/--index. If we are
3433 * applying a non-git patch that incrementally updates the tree,
3434 * we read from the result of a previous diff.
3436 static int load_preimage(struct apply_state *state,
3437 struct image *image,
3438 struct patch *patch, struct stat *st,
3439 const struct cache_entry *ce)
3441 struct strbuf buf = STRBUF_INIT;
3442 size_t len;
3443 char *img;
3444 struct patch *previous;
3445 int status;
3447 previous = previous_patch(state, patch, &status);
3448 if (status)
3449 return error(_("path %s has been renamed/deleted"),
3450 patch->old_name);
3451 if (previous) {
3452 /* We have a patched copy in memory; use that. */
3453 strbuf_add(&buf, previous->result, previous->resultsize);
3454 } else {
3455 status = load_patch_target(state, &buf, ce, st, patch,
3456 patch->old_name, patch->old_mode);
3457 if (status < 0)
3458 return status;
3459 else if (status == SUBMODULE_PATCH_WITHOUT_INDEX) {
3461 * There is no way to apply subproject
3462 * patch without looking at the index.
3463 * NEEDSWORK: shouldn't this be flagged
3464 * as an error???
3466 free_fragment_list(patch->fragments);
3467 patch->fragments = NULL;
3468 } else if (status) {
3469 return error(_("failed to read %s"), patch->old_name);
3473 img = strbuf_detach(&buf, &len);
3474 prepare_image(image, img, len, !patch->is_binary);
3475 return 0;
3478 static int resolve_to(struct image *image, const struct object_id *result_id)
3480 unsigned long size;
3481 enum object_type type;
3483 clear_image(image);
3485 image->buf = read_object_file(result_id, &type, &size);
3486 if (!image->buf || type != OBJ_BLOB)
3487 die("unable to read blob object %s", oid_to_hex(result_id));
3488 image->len = size;
3490 return 0;
3493 static int three_way_merge(struct apply_state *state,
3494 struct image *image,
3495 char *path,
3496 const struct object_id *base,
3497 const struct object_id *ours,
3498 const struct object_id *theirs)
3500 mmfile_t base_file, our_file, their_file;
3501 mmbuffer_t result = { NULL };
3502 enum ll_merge_result status;
3504 /* resolve trivial cases first */
3505 if (oideq(base, ours))
3506 return resolve_to(image, theirs);
3507 else if (oideq(base, theirs) || oideq(ours, theirs))
3508 return resolve_to(image, ours);
3510 read_mmblob(&base_file, base);
3511 read_mmblob(&our_file, ours);
3512 read_mmblob(&their_file, theirs);
3513 status = ll_merge(&result, path,
3514 &base_file, "base",
3515 &our_file, "ours",
3516 &their_file, "theirs",
3517 state->repo->index,
3518 NULL);
3519 if (status == LL_MERGE_BINARY_CONFLICT)
3520 warning("Cannot merge binary files: %s (%s vs. %s)",
3521 path, "ours", "theirs");
3522 free(base_file.ptr);
3523 free(our_file.ptr);
3524 free(their_file.ptr);
3525 if (status < 0 || !result.ptr) {
3526 free(result.ptr);
3527 return -1;
3529 clear_image(image);
3530 image->buf = result.ptr;
3531 image->len = result.size;
3533 return status;
3537 * When directly falling back to add/add three-way merge, we read from
3538 * the current contents of the new_name. In no cases other than that
3539 * this function will be called.
3541 static int load_current(struct apply_state *state,
3542 struct image *image,
3543 struct patch *patch)
3545 struct strbuf buf = STRBUF_INIT;
3546 int status, pos;
3547 size_t len;
3548 char *img;
3549 struct stat st;
3550 struct cache_entry *ce;
3551 char *name = patch->new_name;
3552 unsigned mode = patch->new_mode;
3554 if (!patch->is_new)
3555 BUG("patch to %s is not a creation", patch->old_name);
3557 pos = index_name_pos(state->repo->index, name, strlen(name));
3558 if (pos < 0)
3559 return error(_("%s: does not exist in index"), name);
3560 ce = state->repo->index->cache[pos];
3561 if (lstat(name, &st)) {
3562 if (errno != ENOENT)
3563 return error_errno("%s", name);
3564 if (checkout_target(state->repo->index, ce, &st))
3565 return -1;
3567 if (verify_index_match(state, ce, &st))
3568 return error(_("%s: does not match index"), name);
3570 status = load_patch_target(state, &buf, ce, &st, patch, name, mode);
3571 if (status < 0)
3572 return status;
3573 else if (status)
3574 return -1;
3575 img = strbuf_detach(&buf, &len);
3576 prepare_image(image, img, len, !patch->is_binary);
3577 return 0;
3580 static int try_threeway(struct apply_state *state,
3581 struct image *image,
3582 struct patch *patch,
3583 struct stat *st,
3584 const struct cache_entry *ce)
3586 struct object_id pre_oid, post_oid, our_oid;
3587 struct strbuf buf = STRBUF_INIT;
3588 size_t len;
3589 int status;
3590 char *img;
3591 struct image tmp_image;
3593 /* No point falling back to 3-way merge in these cases */
3594 if (patch->is_delete ||
3595 S_ISGITLINK(patch->old_mode) || S_ISGITLINK(patch->new_mode) ||
3596 (patch->is_new && !patch->direct_to_threeway) ||
3597 (patch->is_rename && !patch->lines_added && !patch->lines_deleted))
3598 return -1;
3600 /* Preimage the patch was prepared for */
3601 if (patch->is_new)
3602 write_object_file("", 0, OBJ_BLOB, &pre_oid);
3603 else if (get_oid(patch->old_oid_prefix, &pre_oid) ||
3604 read_blob_object(&buf, &pre_oid, patch->old_mode))
3605 return error(_("repository lacks the necessary blob to perform 3-way merge."));
3607 if (state->apply_verbosity > verbosity_silent && patch->direct_to_threeway)
3608 fprintf(stderr, _("Performing three-way merge...\n"));
3610 img = strbuf_detach(&buf, &len);
3611 prepare_image(&tmp_image, img, len, 1);
3612 /* Apply the patch to get the post image */
3613 if (apply_fragments(state, &tmp_image, patch) < 0) {
3614 clear_image(&tmp_image);
3615 return -1;
3617 /* post_oid is theirs */
3618 write_object_file(tmp_image.buf, tmp_image.len, OBJ_BLOB, &post_oid);
3619 clear_image(&tmp_image);
3621 /* our_oid is ours */
3622 if (patch->is_new) {
3623 if (load_current(state, &tmp_image, patch))
3624 return error(_("cannot read the current contents of '%s'"),
3625 patch->new_name);
3626 } else {
3627 if (load_preimage(state, &tmp_image, patch, st, ce))
3628 return error(_("cannot read the current contents of '%s'"),
3629 patch->old_name);
3631 write_object_file(tmp_image.buf, tmp_image.len, OBJ_BLOB, &our_oid);
3632 clear_image(&tmp_image);
3634 /* in-core three-way merge between post and our using pre as base */
3635 status = three_way_merge(state, image, patch->new_name,
3636 &pre_oid, &our_oid, &post_oid);
3637 if (status < 0) {
3638 if (state->apply_verbosity > verbosity_silent)
3639 fprintf(stderr,
3640 _("Failed to perform three-way merge...\n"));
3641 return status;
3644 if (status) {
3645 patch->conflicted_threeway = 1;
3646 if (patch->is_new)
3647 oidclr(&patch->threeway_stage[0]);
3648 else
3649 oidcpy(&patch->threeway_stage[0], &pre_oid);
3650 oidcpy(&patch->threeway_stage[1], &our_oid);
3651 oidcpy(&patch->threeway_stage[2], &post_oid);
3652 if (state->apply_verbosity > verbosity_silent)
3653 fprintf(stderr,
3654 _("Applied patch to '%s' with conflicts.\n"),
3655 patch->new_name);
3656 } else {
3657 if (state->apply_verbosity > verbosity_silent)
3658 fprintf(stderr,
3659 _("Applied patch to '%s' cleanly.\n"),
3660 patch->new_name);
3662 return 0;
3665 static int apply_data(struct apply_state *state, struct patch *patch,
3666 struct stat *st, const struct cache_entry *ce)
3668 struct image image;
3670 if (load_preimage(state, &image, patch, st, ce) < 0)
3671 return -1;
3673 if (!state->threeway || try_threeway(state, &image, patch, st, ce) < 0) {
3674 if (state->apply_verbosity > verbosity_silent &&
3675 state->threeway && !patch->direct_to_threeway)
3676 fprintf(stderr, _("Falling back to direct application...\n"));
3678 /* Note: with --reject, apply_fragments() returns 0 */
3679 if (patch->direct_to_threeway || apply_fragments(state, &image, patch) < 0)
3680 return -1;
3682 patch->result = image.buf;
3683 patch->resultsize = image.len;
3684 add_to_fn_table(state, patch);
3685 free(image.line_allocated);
3687 if (0 < patch->is_delete && patch->resultsize)
3688 return error(_("removal patch leaves file contents"));
3690 return 0;
3694 * If "patch" that we are looking at modifies or deletes what we have,
3695 * we would want it not to lose any local modification we have, either
3696 * in the working tree or in the index.
3698 * This also decides if a non-git patch is a creation patch or a
3699 * modification to an existing empty file. We do not check the state
3700 * of the current tree for a creation patch in this function; the caller
3701 * check_patch() separately makes sure (and errors out otherwise) that
3702 * the path the patch creates does not exist in the current tree.
3704 static int check_preimage(struct apply_state *state,
3705 struct patch *patch,
3706 struct cache_entry **ce,
3707 struct stat *st)
3709 const char *old_name = patch->old_name;
3710 struct patch *previous = NULL;
3711 int stat_ret = 0, status;
3712 unsigned st_mode = 0;
3714 if (!old_name)
3715 return 0;
3717 assert(patch->is_new <= 0);
3718 previous = previous_patch(state, patch, &status);
3720 if (status)
3721 return error(_("path %s has been renamed/deleted"), old_name);
3722 if (previous) {
3723 st_mode = previous->new_mode;
3724 } else if (!state->cached) {
3725 stat_ret = lstat(old_name, st);
3726 if (stat_ret && errno != ENOENT)
3727 return error_errno("%s", old_name);
3730 if (state->check_index && !previous) {
3731 int pos = index_name_pos(state->repo->index, old_name,
3732 strlen(old_name));
3733 if (pos < 0) {
3734 if (patch->is_new < 0)
3735 goto is_new;
3736 return error(_("%s: does not exist in index"), old_name);
3738 *ce = state->repo->index->cache[pos];
3739 if (stat_ret < 0) {
3740 if (checkout_target(state->repo->index, *ce, st))
3741 return -1;
3743 if (!state->cached && verify_index_match(state, *ce, st))
3744 return error(_("%s: does not match index"), old_name);
3745 if (state->cached)
3746 st_mode = (*ce)->ce_mode;
3747 } else if (stat_ret < 0) {
3748 if (patch->is_new < 0)
3749 goto is_new;
3750 return error_errno("%s", old_name);
3753 if (!state->cached && !previous)
3754 st_mode = ce_mode_from_stat(*ce, st->st_mode);
3756 if (patch->is_new < 0)
3757 patch->is_new = 0;
3758 if (!patch->old_mode)
3759 patch->old_mode = st_mode;
3760 if ((st_mode ^ patch->old_mode) & S_IFMT)
3761 return error(_("%s: wrong type"), old_name);
3762 if (st_mode != patch->old_mode)
3763 warning(_("%s has type %o, expected %o"),
3764 old_name, st_mode, patch->old_mode);
3765 if (!patch->new_mode && !patch->is_delete)
3766 patch->new_mode = st_mode;
3767 return 0;
3769 is_new:
3770 patch->is_new = 1;
3771 patch->is_delete = 0;
3772 FREE_AND_NULL(patch->old_name);
3773 return 0;
3777 #define EXISTS_IN_INDEX 1
3778 #define EXISTS_IN_WORKTREE 2
3779 #define EXISTS_IN_INDEX_AS_ITA 3
3781 static int check_to_create(struct apply_state *state,
3782 const char *new_name,
3783 int ok_if_exists)
3785 struct stat nst;
3787 if (state->check_index && (!ok_if_exists || !state->cached)) {
3788 int pos;
3790 pos = index_name_pos(state->repo->index, new_name, strlen(new_name));
3791 if (pos >= 0) {
3792 struct cache_entry *ce = state->repo->index->cache[pos];
3794 /* allow ITA, as they do not yet exist in the index */
3795 if (!ok_if_exists && !(ce->ce_flags & CE_INTENT_TO_ADD))
3796 return EXISTS_IN_INDEX;
3798 /* ITA entries can never match working tree files */
3799 if (!state->cached && (ce->ce_flags & CE_INTENT_TO_ADD))
3800 return EXISTS_IN_INDEX_AS_ITA;
3804 if (state->cached)
3805 return 0;
3807 if (!lstat(new_name, &nst)) {
3808 if (S_ISDIR(nst.st_mode) || ok_if_exists)
3809 return 0;
3811 * A leading component of new_name might be a symlink
3812 * that is going to be removed with this patch, but
3813 * still pointing at somewhere that has the path.
3814 * In such a case, path "new_name" does not exist as
3815 * far as git is concerned.
3817 if (has_symlink_leading_path(new_name, strlen(new_name)))
3818 return 0;
3820 return EXISTS_IN_WORKTREE;
3821 } else if (!is_missing_file_error(errno)) {
3822 return error_errno("%s", new_name);
3824 return 0;
3827 static void prepare_symlink_changes(struct apply_state *state, struct patch *patch)
3829 for ( ; patch; patch = patch->next) {
3830 if ((patch->old_name && S_ISLNK(patch->old_mode)) &&
3831 (patch->is_rename || patch->is_delete))
3832 /* the symlink at patch->old_name is removed */
3833 strset_add(&state->removed_symlinks, patch->old_name);
3835 if (patch->new_name && S_ISLNK(patch->new_mode))
3836 /* the symlink at patch->new_name is created or remains */
3837 strset_add(&state->kept_symlinks, patch->new_name);
3841 static int path_is_beyond_symlink_1(struct apply_state *state, struct strbuf *name)
3843 do {
3844 while (--name->len && name->buf[name->len] != '/')
3845 ; /* scan backwards */
3846 if (!name->len)
3847 break;
3848 name->buf[name->len] = '\0';
3849 if (strset_contains(&state->kept_symlinks, name->buf))
3850 return 1;
3851 if (strset_contains(&state->removed_symlinks, name->buf))
3853 * This cannot be "return 0", because we may
3854 * see a new one created at a higher level.
3856 continue;
3858 /* otherwise, check the preimage */
3859 if (state->check_index) {
3860 struct cache_entry *ce;
3862 ce = index_file_exists(state->repo->index, name->buf,
3863 name->len, ignore_case);
3864 if (ce && S_ISLNK(ce->ce_mode))
3865 return 1;
3866 } else {
3867 struct stat st;
3868 if (!lstat(name->buf, &st) && S_ISLNK(st.st_mode))
3869 return 1;
3871 } while (1);
3872 return 0;
3875 static int path_is_beyond_symlink(struct apply_state *state, const char *name_)
3877 int ret;
3878 struct strbuf name = STRBUF_INIT;
3880 assert(*name_ != '\0');
3881 strbuf_addstr(&name, name_);
3882 ret = path_is_beyond_symlink_1(state, &name);
3883 strbuf_release(&name);
3885 return ret;
3888 static int check_unsafe_path(struct patch *patch)
3890 const char *old_name = NULL;
3891 const char *new_name = NULL;
3892 if (patch->is_delete)
3893 old_name = patch->old_name;
3894 else if (!patch->is_new && !patch->is_copy)
3895 old_name = patch->old_name;
3896 if (!patch->is_delete)
3897 new_name = patch->new_name;
3899 if (old_name && !verify_path(old_name, patch->old_mode))
3900 return error(_("invalid path '%s'"), old_name);
3901 if (new_name && !verify_path(new_name, patch->new_mode))
3902 return error(_("invalid path '%s'"), new_name);
3903 return 0;
3907 * Check and apply the patch in-core; leave the result in patch->result
3908 * for the caller to write it out to the final destination.
3910 static int check_patch(struct apply_state *state, struct patch *patch)
3912 struct stat st;
3913 const char *old_name = patch->old_name;
3914 const char *new_name = patch->new_name;
3915 const char *name = old_name ? old_name : new_name;
3916 struct cache_entry *ce = NULL;
3917 struct patch *tpatch;
3918 int ok_if_exists;
3919 int status;
3921 patch->rejected = 1; /* we will drop this after we succeed */
3923 status = check_preimage(state, patch, &ce, &st);
3924 if (status)
3925 return status;
3926 old_name = patch->old_name;
3929 * A type-change diff is always split into a patch to delete
3930 * old, immediately followed by a patch to create new (see
3931 * diff.c::run_diff()); in such a case it is Ok that the entry
3932 * to be deleted by the previous patch is still in the working
3933 * tree and in the index.
3935 * A patch to swap-rename between A and B would first rename A
3936 * to B and then rename B to A. While applying the first one,
3937 * the presence of B should not stop A from getting renamed to
3938 * B; ask to_be_deleted() about the later rename. Removal of
3939 * B and rename from A to B is handled the same way by asking
3940 * was_deleted().
3942 if ((tpatch = in_fn_table(state, new_name)) &&
3943 (was_deleted(tpatch) || to_be_deleted(tpatch)))
3944 ok_if_exists = 1;
3945 else
3946 ok_if_exists = 0;
3948 if (new_name &&
3949 ((0 < patch->is_new) || patch->is_rename || patch->is_copy)) {
3950 int err = check_to_create(state, new_name, ok_if_exists);
3952 if (err && state->threeway) {
3953 patch->direct_to_threeway = 1;
3954 } else switch (err) {
3955 case 0:
3956 break; /* happy */
3957 case EXISTS_IN_INDEX:
3958 return error(_("%s: already exists in index"), new_name);
3959 case EXISTS_IN_INDEX_AS_ITA:
3960 return error(_("%s: does not match index"), new_name);
3961 case EXISTS_IN_WORKTREE:
3962 return error(_("%s: already exists in working directory"),
3963 new_name);
3964 default:
3965 return err;
3968 if (!patch->new_mode) {
3969 if (0 < patch->is_new)
3970 patch->new_mode = S_IFREG | 0644;
3971 else
3972 patch->new_mode = patch->old_mode;
3976 if (new_name && old_name) {
3977 int same = !strcmp(old_name, new_name);
3978 if (!patch->new_mode)
3979 patch->new_mode = patch->old_mode;
3980 if ((patch->old_mode ^ patch->new_mode) & S_IFMT) {
3981 if (same)
3982 return error(_("new mode (%o) of %s does not "
3983 "match old mode (%o)"),
3984 patch->new_mode, new_name,
3985 patch->old_mode);
3986 else
3987 return error(_("new mode (%o) of %s does not "
3988 "match old mode (%o) of %s"),
3989 patch->new_mode, new_name,
3990 patch->old_mode, old_name);
3994 if (!state->unsafe_paths && check_unsafe_path(patch))
3995 return -128;
3998 * An attempt to read from or delete a path that is beyond a
3999 * symbolic link will be prevented by load_patch_target() that
4000 * is called at the beginning of apply_data() so we do not
4001 * have to worry about a patch marked with "is_delete" bit
4002 * here. We however need to make sure that the patch result
4003 * is not deposited to a path that is beyond a symbolic link
4004 * here.
4006 if (!patch->is_delete && path_is_beyond_symlink(state, patch->new_name))
4007 return error(_("affected file '%s' is beyond a symbolic link"),
4008 patch->new_name);
4010 if (apply_data(state, patch, &st, ce) < 0)
4011 return error(_("%s: patch does not apply"), name);
4012 patch->rejected = 0;
4013 return 0;
4016 static int check_patch_list(struct apply_state *state, struct patch *patch)
4018 int err = 0;
4020 prepare_symlink_changes(state, patch);
4021 prepare_fn_table(state, patch);
4022 while (patch) {
4023 int res;
4024 if (state->apply_verbosity > verbosity_normal)
4025 say_patch_name(stderr,
4026 _("Checking patch %s..."), patch);
4027 res = check_patch(state, patch);
4028 if (res == -128)
4029 return -128;
4030 err |= res;
4031 patch = patch->next;
4033 return err;
4036 static int read_apply_cache(struct apply_state *state)
4038 if (state->index_file)
4039 return read_index_from(state->repo->index, state->index_file,
4040 get_git_dir());
4041 else
4042 return repo_read_index(state->repo);
4045 /* This function tries to read the object name from the current index */
4046 static int get_current_oid(struct apply_state *state, const char *path,
4047 struct object_id *oid)
4049 int pos;
4051 if (read_apply_cache(state) < 0)
4052 return -1;
4053 pos = index_name_pos(state->repo->index, path, strlen(path));
4054 if (pos < 0)
4055 return -1;
4056 oidcpy(oid, &state->repo->index->cache[pos]->oid);
4057 return 0;
4060 static int preimage_oid_in_gitlink_patch(struct patch *p, struct object_id *oid)
4063 * A usable gitlink patch has only one fragment (hunk) that looks like:
4064 * @@ -1 +1 @@
4065 * -Subproject commit <old sha1>
4066 * +Subproject commit <new sha1>
4067 * or
4068 * @@ -1 +0,0 @@
4069 * -Subproject commit <old sha1>
4070 * for a removal patch.
4072 struct fragment *hunk = p->fragments;
4073 static const char heading[] = "-Subproject commit ";
4074 char *preimage;
4076 if (/* does the patch have only one hunk? */
4077 hunk && !hunk->next &&
4078 /* is its preimage one line? */
4079 hunk->oldpos == 1 && hunk->oldlines == 1 &&
4080 /* does preimage begin with the heading? */
4081 (preimage = memchr(hunk->patch, '\n', hunk->size)) != NULL &&
4082 starts_with(++preimage, heading) &&
4083 /* does it record full SHA-1? */
4084 !get_oid_hex(preimage + sizeof(heading) - 1, oid) &&
4085 preimage[sizeof(heading) + the_hash_algo->hexsz - 1] == '\n' &&
4086 /* does the abbreviated name on the index line agree with it? */
4087 starts_with(preimage + sizeof(heading) - 1, p->old_oid_prefix))
4088 return 0; /* it all looks fine */
4090 /* we may have full object name on the index line */
4091 return get_oid_hex(p->old_oid_prefix, oid);
4094 /* Build an index that contains just the files needed for a 3way merge */
4095 static int build_fake_ancestor(struct apply_state *state, struct patch *list)
4097 struct patch *patch;
4098 struct index_state result = { NULL };
4099 struct lock_file lock = LOCK_INIT;
4100 int res;
4102 /* Once we start supporting the reverse patch, it may be
4103 * worth showing the new sha1 prefix, but until then...
4105 for (patch = list; patch; patch = patch->next) {
4106 struct object_id oid;
4107 struct cache_entry *ce;
4108 const char *name;
4110 name = patch->old_name ? patch->old_name : patch->new_name;
4111 if (0 < patch->is_new)
4112 continue;
4114 if (S_ISGITLINK(patch->old_mode)) {
4115 if (!preimage_oid_in_gitlink_patch(patch, &oid))
4116 ; /* ok, the textual part looks sane */
4117 else
4118 return error(_("sha1 information is lacking or "
4119 "useless for submodule %s"), name);
4120 } else if (!get_oid_blob(patch->old_oid_prefix, &oid)) {
4121 ; /* ok */
4122 } else if (!patch->lines_added && !patch->lines_deleted) {
4123 /* mode-only change: update the current */
4124 if (get_current_oid(state, patch->old_name, &oid))
4125 return error(_("mode change for %s, which is not "
4126 "in current HEAD"), name);
4127 } else
4128 return error(_("sha1 information is lacking or useless "
4129 "(%s)."), name);
4131 ce = make_cache_entry(&result, patch->old_mode, &oid, name, 0, 0);
4132 if (!ce)
4133 return error(_("make_cache_entry failed for path '%s'"),
4134 name);
4135 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) {
4136 discard_cache_entry(ce);
4137 return error(_("could not add %s to temporary index"),
4138 name);
4142 hold_lock_file_for_update(&lock, state->fake_ancestor, LOCK_DIE_ON_ERROR);
4143 res = write_locked_index(&result, &lock, COMMIT_LOCK);
4144 discard_index(&result);
4146 if (res)
4147 return error(_("could not write temporary index to %s"),
4148 state->fake_ancestor);
4150 return 0;
4153 static void stat_patch_list(struct apply_state *state, struct patch *patch)
4155 int files, adds, dels;
4157 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
4158 files++;
4159 adds += patch->lines_added;
4160 dels += patch->lines_deleted;
4161 show_stats(state, patch);
4164 print_stat_summary(stdout, files, adds, dels);
4167 static void numstat_patch_list(struct apply_state *state,
4168 struct patch *patch)
4170 for ( ; patch; patch = patch->next) {
4171 const char *name;
4172 name = patch->new_name ? patch->new_name : patch->old_name;
4173 if (patch->is_binary)
4174 printf("-\t-\t");
4175 else
4176 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
4177 write_name_quoted(name, stdout, state->line_termination);
4181 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
4183 if (mode)
4184 printf(" %s mode %06o %s\n", newdelete, mode, name);
4185 else
4186 printf(" %s %s\n", newdelete, name);
4189 static void show_mode_change(struct patch *p, int show_name)
4191 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
4192 if (show_name)
4193 printf(" mode change %06o => %06o %s\n",
4194 p->old_mode, p->new_mode, p->new_name);
4195 else
4196 printf(" mode change %06o => %06o\n",
4197 p->old_mode, p->new_mode);
4201 static void show_rename_copy(struct patch *p)
4203 const char *renamecopy = p->is_rename ? "rename" : "copy";
4204 const char *old_name, *new_name;
4206 /* Find common prefix */
4207 old_name = p->old_name;
4208 new_name = p->new_name;
4209 while (1) {
4210 const char *slash_old, *slash_new;
4211 slash_old = strchr(old_name, '/');
4212 slash_new = strchr(new_name, '/');
4213 if (!slash_old ||
4214 !slash_new ||
4215 slash_old - old_name != slash_new - new_name ||
4216 memcmp(old_name, new_name, slash_new - new_name))
4217 break;
4218 old_name = slash_old + 1;
4219 new_name = slash_new + 1;
4221 /* p->old_name through old_name is the common prefix, and old_name and
4222 * new_name through the end of names are renames
4224 if (old_name != p->old_name)
4225 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
4226 (int)(old_name - p->old_name), p->old_name,
4227 old_name, new_name, p->score);
4228 else
4229 printf(" %s %s => %s (%d%%)\n", renamecopy,
4230 p->old_name, p->new_name, p->score);
4231 show_mode_change(p, 0);
4234 static void summary_patch_list(struct patch *patch)
4236 struct patch *p;
4238 for (p = patch; p; p = p->next) {
4239 if (p->is_new)
4240 show_file_mode_name("create", p->new_mode, p->new_name);
4241 else if (p->is_delete)
4242 show_file_mode_name("delete", p->old_mode, p->old_name);
4243 else {
4244 if (p->is_rename || p->is_copy)
4245 show_rename_copy(p);
4246 else {
4247 if (p->score) {
4248 printf(" rewrite %s (%d%%)\n",
4249 p->new_name, p->score);
4250 show_mode_change(p, 0);
4252 else
4253 show_mode_change(p, 1);
4259 static void patch_stats(struct apply_state *state, struct patch *patch)
4261 int lines = patch->lines_added + patch->lines_deleted;
4263 if (lines > state->max_change)
4264 state->max_change = lines;
4265 if (patch->old_name) {
4266 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
4267 if (!len)
4268 len = strlen(patch->old_name);
4269 if (len > state->max_len)
4270 state->max_len = len;
4272 if (patch->new_name) {
4273 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
4274 if (!len)
4275 len = strlen(patch->new_name);
4276 if (len > state->max_len)
4277 state->max_len = len;
4281 static int remove_file(struct apply_state *state, struct patch *patch, int rmdir_empty)
4283 if (state->update_index && !state->ita_only) {
4284 if (remove_file_from_index(state->repo->index, patch->old_name) < 0)
4285 return error(_("unable to remove %s from index"), patch->old_name);
4287 if (!state->cached) {
4288 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
4289 remove_path(patch->old_name);
4292 return 0;
4295 static int add_index_file(struct apply_state *state,
4296 const char *path,
4297 unsigned mode,
4298 void *buf,
4299 unsigned long size)
4301 struct stat st;
4302 struct cache_entry *ce;
4303 int namelen = strlen(path);
4305 ce = make_empty_cache_entry(state->repo->index, namelen);
4306 memcpy(ce->name, path, namelen);
4307 ce->ce_mode = create_ce_mode(mode);
4308 ce->ce_flags = create_ce_flags(0);
4309 ce->ce_namelen = namelen;
4310 if (state->ita_only) {
4311 ce->ce_flags |= CE_INTENT_TO_ADD;
4312 set_object_name_for_intent_to_add_entry(ce);
4313 } else if (S_ISGITLINK(mode)) {
4314 const char *s;
4316 if (!skip_prefix(buf, "Subproject commit ", &s) ||
4317 get_oid_hex(s, &ce->oid)) {
4318 discard_cache_entry(ce);
4319 return error(_("corrupt patch for submodule %s"), path);
4321 } else {
4322 if (!state->cached) {
4323 if (lstat(path, &st) < 0) {
4324 discard_cache_entry(ce);
4325 return error_errno(_("unable to stat newly "
4326 "created file '%s'"),
4327 path);
4329 fill_stat_cache_info(state->repo->index, ce, &st);
4331 if (write_object_file(buf, size, OBJ_BLOB, &ce->oid) < 0) {
4332 discard_cache_entry(ce);
4333 return error(_("unable to create backing store "
4334 "for newly created file %s"), path);
4337 if (add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) < 0) {
4338 discard_cache_entry(ce);
4339 return error(_("unable to add cache entry for %s"), path);
4342 return 0;
4346 * Returns:
4347 * -1 if an unrecoverable error happened
4348 * 0 if everything went well
4349 * 1 if a recoverable error happened
4351 static int try_create_file(struct apply_state *state, const char *path,
4352 unsigned int mode, const char *buf,
4353 unsigned long size)
4355 int fd, res;
4356 struct strbuf nbuf = STRBUF_INIT;
4358 if (S_ISGITLINK(mode)) {
4359 struct stat st;
4360 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
4361 return 0;
4362 return !!mkdir(path, 0777);
4365 if (has_symlinks && S_ISLNK(mode))
4366 /* Although buf:size is counted string, it also is NUL
4367 * terminated.
4369 return !!symlink(buf, path);
4371 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
4372 if (fd < 0)
4373 return 1;
4375 if (convert_to_working_tree(state->repo->index, path, buf, size, &nbuf, NULL)) {
4376 size = nbuf.len;
4377 buf = nbuf.buf;
4380 res = write_in_full(fd, buf, size) < 0;
4381 if (res)
4382 error_errno(_("failed to write to '%s'"), path);
4383 strbuf_release(&nbuf);
4385 if (close(fd) < 0 && !res)
4386 return error_errno(_("closing file '%s'"), path);
4388 return res ? -1 : 0;
4392 * We optimistically assume that the directories exist,
4393 * which is true 99% of the time anyway. If they don't,
4394 * we create them and try again.
4396 * Returns:
4397 * -1 on error
4398 * 0 otherwise
4400 static int create_one_file(struct apply_state *state,
4401 char *path,
4402 unsigned mode,
4403 const char *buf,
4404 unsigned long size)
4406 int res;
4408 if (state->cached)
4409 return 0;
4411 res = try_create_file(state, path, mode, buf, size);
4412 if (res < 0)
4413 return -1;
4414 if (!res)
4415 return 0;
4417 if (errno == ENOENT) {
4418 if (safe_create_leading_directories_no_share(path))
4419 return 0;
4420 res = try_create_file(state, path, mode, buf, size);
4421 if (res < 0)
4422 return -1;
4423 if (!res)
4424 return 0;
4427 if (errno == EEXIST || errno == EACCES) {
4428 /* We may be trying to create a file where a directory
4429 * used to be.
4431 struct stat st;
4432 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
4433 errno = EEXIST;
4436 if (errno == EEXIST) {
4437 unsigned int nr = getpid();
4439 for (;;) {
4440 char newpath[PATH_MAX];
4441 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
4442 res = try_create_file(state, newpath, mode, buf, size);
4443 if (res < 0)
4444 return -1;
4445 if (!res) {
4446 if (!rename(newpath, path))
4447 return 0;
4448 unlink_or_warn(newpath);
4449 break;
4451 if (errno != EEXIST)
4452 break;
4453 ++nr;
4456 return error_errno(_("unable to write file '%s' mode %o"),
4457 path, mode);
4460 static int add_conflicted_stages_file(struct apply_state *state,
4461 struct patch *patch)
4463 int stage, namelen;
4464 unsigned mode;
4465 struct cache_entry *ce;
4467 if (!state->update_index)
4468 return 0;
4469 namelen = strlen(patch->new_name);
4470 mode = patch->new_mode ? patch->new_mode : (S_IFREG | 0644);
4472 remove_file_from_index(state->repo->index, patch->new_name);
4473 for (stage = 1; stage < 4; stage++) {
4474 if (is_null_oid(&patch->threeway_stage[stage - 1]))
4475 continue;
4476 ce = make_empty_cache_entry(state->repo->index, namelen);
4477 memcpy(ce->name, patch->new_name, namelen);
4478 ce->ce_mode = create_ce_mode(mode);
4479 ce->ce_flags = create_ce_flags(stage);
4480 ce->ce_namelen = namelen;
4481 oidcpy(&ce->oid, &patch->threeway_stage[stage - 1]);
4482 if (add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) < 0) {
4483 discard_cache_entry(ce);
4484 return error(_("unable to add cache entry for %s"),
4485 patch->new_name);
4489 return 0;
4492 static int create_file(struct apply_state *state, struct patch *patch)
4494 char *path = patch->new_name;
4495 unsigned mode = patch->new_mode;
4496 unsigned long size = patch->resultsize;
4497 char *buf = patch->result;
4499 if (!mode)
4500 mode = S_IFREG | 0644;
4501 if (create_one_file(state, path, mode, buf, size))
4502 return -1;
4504 if (patch->conflicted_threeway)
4505 return add_conflicted_stages_file(state, patch);
4506 else if (state->update_index)
4507 return add_index_file(state, path, mode, buf, size);
4508 return 0;
4511 /* phase zero is to remove, phase one is to create */
4512 static int write_out_one_result(struct apply_state *state,
4513 struct patch *patch,
4514 int phase)
4516 if (patch->is_delete > 0) {
4517 if (phase == 0)
4518 return remove_file(state, patch, 1);
4519 return 0;
4521 if (patch->is_new > 0 || patch->is_copy) {
4522 if (phase == 1)
4523 return create_file(state, patch);
4524 return 0;
4527 * Rename or modification boils down to the same
4528 * thing: remove the old, write the new
4530 if (phase == 0)
4531 return remove_file(state, patch, patch->is_rename);
4532 if (phase == 1)
4533 return create_file(state, patch);
4534 return 0;
4537 static int write_out_one_reject(struct apply_state *state, struct patch *patch)
4539 FILE *rej;
4540 char namebuf[PATH_MAX];
4541 struct fragment *frag;
4542 int cnt = 0;
4543 struct strbuf sb = STRBUF_INIT;
4545 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
4546 if (!frag->rejected)
4547 continue;
4548 cnt++;
4551 if (!cnt) {
4552 if (state->apply_verbosity > verbosity_normal)
4553 say_patch_name(stderr,
4554 _("Applied patch %s cleanly."), patch);
4555 return 0;
4558 /* This should not happen, because a removal patch that leaves
4559 * contents are marked "rejected" at the patch level.
4561 if (!patch->new_name)
4562 die(_("internal error"));
4564 /* Say this even without --verbose */
4565 strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",
4566 "Applying patch %%s with %d rejects...",
4567 cnt),
4568 cnt);
4569 if (state->apply_verbosity > verbosity_silent)
4570 say_patch_name(stderr, sb.buf, patch);
4571 strbuf_release(&sb);
4573 cnt = strlen(patch->new_name);
4574 if (ARRAY_SIZE(namebuf) <= cnt + 5) {
4575 cnt = ARRAY_SIZE(namebuf) - 5;
4576 warning(_("truncating .rej filename to %.*s.rej"),
4577 cnt - 1, patch->new_name);
4579 memcpy(namebuf, patch->new_name, cnt);
4580 memcpy(namebuf + cnt, ".rej", 5);
4582 rej = fopen(namebuf, "w");
4583 if (!rej)
4584 return error_errno(_("cannot open %s"), namebuf);
4586 /* Normal git tools never deal with .rej, so do not pretend
4587 * this is a git patch by saying --git or giving extended
4588 * headers. While at it, maybe please "kompare" that wants
4589 * the trailing TAB and some garbage at the end of line ;-).
4591 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
4592 patch->new_name, patch->new_name);
4593 for (cnt = 1, frag = patch->fragments;
4594 frag;
4595 cnt++, frag = frag->next) {
4596 if (!frag->rejected) {
4597 if (state->apply_verbosity > verbosity_silent)
4598 fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);
4599 continue;
4601 if (state->apply_verbosity > verbosity_silent)
4602 fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);
4603 fprintf(rej, "%.*s", frag->size, frag->patch);
4604 if (frag->patch[frag->size-1] != '\n')
4605 fputc('\n', rej);
4607 fclose(rej);
4608 return -1;
4612 * Returns:
4613 * -1 if an error happened
4614 * 0 if the patch applied cleanly
4615 * 1 if the patch did not apply cleanly
4617 static int write_out_results(struct apply_state *state, struct patch *list)
4619 int phase;
4620 int errs = 0;
4621 struct patch *l;
4622 struct string_list cpath = STRING_LIST_INIT_DUP;
4624 for (phase = 0; phase < 2; phase++) {
4625 l = list;
4626 while (l) {
4627 if (l->rejected)
4628 errs = 1;
4629 else {
4630 if (write_out_one_result(state, l, phase)) {
4631 string_list_clear(&cpath, 0);
4632 return -1;
4634 if (phase == 1) {
4635 if (write_out_one_reject(state, l))
4636 errs = 1;
4637 if (l->conflicted_threeway) {
4638 string_list_append(&cpath, l->new_name);
4639 errs = 1;
4643 l = l->next;
4647 if (cpath.nr) {
4648 struct string_list_item *item;
4650 string_list_sort(&cpath);
4651 if (state->apply_verbosity > verbosity_silent) {
4652 for_each_string_list_item(item, &cpath)
4653 fprintf(stderr, "U %s\n", item->string);
4655 string_list_clear(&cpath, 0);
4658 * rerere relies on the partially merged result being in the working
4659 * tree with conflict markers, but that isn't written with --cached.
4661 if (!state->cached)
4662 repo_rerere(state->repo, 0);
4665 return errs;
4669 * Try to apply a patch.
4671 * Returns:
4672 * -128 if a bad error happened (like patch unreadable)
4673 * -1 if patch did not apply and user cannot deal with it
4674 * 0 if the patch applied
4675 * 1 if the patch did not apply but user might fix it
4677 static int apply_patch(struct apply_state *state,
4678 int fd,
4679 const char *filename,
4680 int options)
4682 size_t offset;
4683 struct strbuf buf = STRBUF_INIT; /* owns the patch text */
4684 struct patch *list = NULL, **listp = &list;
4685 int skipped_patch = 0;
4686 int res = 0;
4687 int flush_attributes = 0;
4689 state->patch_input_file = filename;
4690 if (read_patch_file(&buf, fd) < 0)
4691 return -128;
4692 offset = 0;
4693 while (offset < buf.len) {
4694 struct patch *patch;
4695 int nr;
4697 CALLOC_ARRAY(patch, 1);
4698 patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF);
4699 patch->recount = !!(options & APPLY_OPT_RECOUNT);
4700 nr = parse_chunk(state, buf.buf + offset, buf.len - offset, patch);
4701 if (nr < 0) {
4702 free_patch(patch);
4703 if (nr == -128) {
4704 res = -128;
4705 goto end;
4707 break;
4709 if (state->apply_in_reverse)
4710 reverse_patches(patch);
4711 if (use_patch(state, patch)) {
4712 patch_stats(state, patch);
4713 if (!list || !state->apply_in_reverse) {
4714 *listp = patch;
4715 listp = &patch->next;
4716 } else {
4717 patch->next = list;
4718 list = patch;
4721 if ((patch->new_name &&
4722 ends_with_path_components(patch->new_name,
4723 GITATTRIBUTES_FILE)) ||
4724 (patch->old_name &&
4725 ends_with_path_components(patch->old_name,
4726 GITATTRIBUTES_FILE)))
4727 flush_attributes = 1;
4729 else {
4730 if (state->apply_verbosity > verbosity_normal)
4731 say_patch_name(stderr, _("Skipped patch '%s'."), patch);
4732 free_patch(patch);
4733 skipped_patch++;
4735 offset += nr;
4738 if (!list && !skipped_patch) {
4739 if (!state->allow_empty) {
4740 error(_("No valid patches in input (allow with \"--allow-empty\")"));
4741 res = -128;
4743 goto end;
4746 if (state->whitespace_error && (state->ws_error_action == die_on_ws_error))
4747 state->apply = 0;
4749 state->update_index = (state->check_index || state->ita_only) && state->apply;
4750 if (state->update_index && !is_lock_file_locked(&state->lock_file)) {
4751 if (state->index_file)
4752 hold_lock_file_for_update(&state->lock_file,
4753 state->index_file,
4754 LOCK_DIE_ON_ERROR);
4755 else
4756 repo_hold_locked_index(state->repo, &state->lock_file,
4757 LOCK_DIE_ON_ERROR);
4760 if (state->check_index && read_apply_cache(state) < 0) {
4761 error(_("unable to read index file"));
4762 res = -128;
4763 goto end;
4766 if (state->check || state->apply) {
4767 int r = check_patch_list(state, list);
4768 if (r == -128) {
4769 res = -128;
4770 goto end;
4772 if (r < 0 && !state->apply_with_reject) {
4773 res = -1;
4774 goto end;
4778 if (state->apply) {
4779 int write_res = write_out_results(state, list);
4780 if (write_res < 0) {
4781 res = -128;
4782 goto end;
4784 if (write_res > 0) {
4785 /* with --3way, we still need to write the index out */
4786 res = state->apply_with_reject ? -1 : 1;
4787 goto end;
4791 if (state->fake_ancestor &&
4792 build_fake_ancestor(state, list)) {
4793 res = -128;
4794 goto end;
4797 if (state->diffstat && state->apply_verbosity > verbosity_silent)
4798 stat_patch_list(state, list);
4800 if (state->numstat && state->apply_verbosity > verbosity_silent)
4801 numstat_patch_list(state, list);
4803 if (state->summary && state->apply_verbosity > verbosity_silent)
4804 summary_patch_list(list);
4806 if (flush_attributes)
4807 reset_parsed_attributes();
4808 end:
4809 free_patch_list(list);
4810 strbuf_release(&buf);
4811 string_list_clear(&state->fn_table, 0);
4812 return res;
4815 static int apply_option_parse_exclude(const struct option *opt,
4816 const char *arg, int unset)
4818 struct apply_state *state = opt->value;
4820 BUG_ON_OPT_NEG(unset);
4822 add_name_limit(state, arg, 1);
4823 return 0;
4826 static int apply_option_parse_include(const struct option *opt,
4827 const char *arg, int unset)
4829 struct apply_state *state = opt->value;
4831 BUG_ON_OPT_NEG(unset);
4833 add_name_limit(state, arg, 0);
4834 state->has_include = 1;
4835 return 0;
4838 static int apply_option_parse_p(const struct option *opt,
4839 const char *arg,
4840 int unset)
4842 struct apply_state *state = opt->value;
4844 BUG_ON_OPT_NEG(unset);
4846 state->p_value = atoi(arg);
4847 state->p_value_known = 1;
4848 return 0;
4851 static int apply_option_parse_space_change(const struct option *opt,
4852 const char *arg, int unset)
4854 struct apply_state *state = opt->value;
4856 BUG_ON_OPT_ARG(arg);
4858 if (unset)
4859 state->ws_ignore_action = ignore_ws_none;
4860 else
4861 state->ws_ignore_action = ignore_ws_change;
4862 return 0;
4865 static int apply_option_parse_whitespace(const struct option *opt,
4866 const char *arg, int unset)
4868 struct apply_state *state = opt->value;
4870 BUG_ON_OPT_NEG(unset);
4872 state->whitespace_option = arg;
4873 if (parse_whitespace_option(state, arg))
4874 return -1;
4875 return 0;
4878 static int apply_option_parse_directory(const struct option *opt,
4879 const char *arg, int unset)
4881 struct apply_state *state = opt->value;
4883 BUG_ON_OPT_NEG(unset);
4885 strbuf_reset(&state->root);
4886 strbuf_addstr(&state->root, arg);
4887 strbuf_complete(&state->root, '/');
4888 return 0;
4891 int apply_all_patches(struct apply_state *state,
4892 int argc,
4893 const char **argv,
4894 int options)
4896 int i;
4897 int res;
4898 int errs = 0;
4899 int read_stdin = 1;
4901 for (i = 0; i < argc; i++) {
4902 const char *arg = argv[i];
4903 char *to_free = NULL;
4904 int fd;
4906 if (!strcmp(arg, "-")) {
4907 res = apply_patch(state, 0, "<stdin>", options);
4908 if (res < 0)
4909 goto end;
4910 errs |= res;
4911 read_stdin = 0;
4912 continue;
4913 } else
4914 arg = to_free = prefix_filename(state->prefix, arg);
4916 fd = open(arg, O_RDONLY);
4917 if (fd < 0) {
4918 error(_("can't open patch '%s': %s"), arg, strerror(errno));
4919 res = -128;
4920 free(to_free);
4921 goto end;
4923 read_stdin = 0;
4924 set_default_whitespace_mode(state);
4925 res = apply_patch(state, fd, arg, options);
4926 close(fd);
4927 free(to_free);
4928 if (res < 0)
4929 goto end;
4930 errs |= res;
4932 set_default_whitespace_mode(state);
4933 if (read_stdin) {
4934 res = apply_patch(state, 0, "<stdin>", options);
4935 if (res < 0)
4936 goto end;
4937 errs |= res;
4940 if (state->whitespace_error) {
4941 if (state->squelch_whitespace_errors &&
4942 state->squelch_whitespace_errors < state->whitespace_error) {
4943 int squelched =
4944 state->whitespace_error - state->squelch_whitespace_errors;
4945 warning(Q_("squelched %d whitespace error",
4946 "squelched %d whitespace errors",
4947 squelched),
4948 squelched);
4950 if (state->ws_error_action == die_on_ws_error) {
4951 error(Q_("%d line adds whitespace errors.",
4952 "%d lines add whitespace errors.",
4953 state->whitespace_error),
4954 state->whitespace_error);
4955 res = -128;
4956 goto end;
4958 if (state->applied_after_fixing_ws && state->apply)
4959 warning(Q_("%d line applied after"
4960 " fixing whitespace errors.",
4961 "%d lines applied after"
4962 " fixing whitespace errors.",
4963 state->applied_after_fixing_ws),
4964 state->applied_after_fixing_ws);
4965 else if (state->whitespace_error)
4966 warning(Q_("%d line adds whitespace errors.",
4967 "%d lines add whitespace errors.",
4968 state->whitespace_error),
4969 state->whitespace_error);
4972 if (state->update_index) {
4973 res = write_locked_index(state->repo->index, &state->lock_file, COMMIT_LOCK);
4974 if (res) {
4975 error(_("Unable to write new index file"));
4976 res = -128;
4977 goto end;
4981 res = !!errs;
4983 end:
4984 rollback_lock_file(&state->lock_file);
4986 if (state->apply_verbosity <= verbosity_silent) {
4987 set_error_routine(state->saved_error_routine);
4988 set_warn_routine(state->saved_warn_routine);
4991 if (res > -1)
4992 return res;
4993 return (res == -1 ? 1 : 128);
4996 int apply_parse_options(int argc, const char **argv,
4997 struct apply_state *state,
4998 int *force_apply, int *options,
4999 const char * const *apply_usage)
5001 struct option builtin_apply_options[] = {
5002 OPT_CALLBACK_F(0, "exclude", state, N_("path"),
5003 N_("don't apply changes matching the given path"),
5004 PARSE_OPT_NONEG, apply_option_parse_exclude),
5005 OPT_CALLBACK_F(0, "include", state, N_("path"),
5006 N_("apply changes matching the given path"),
5007 PARSE_OPT_NONEG, apply_option_parse_include),
5008 OPT_CALLBACK('p', NULL, state, N_("num"),
5009 N_("remove <num> leading slashes from traditional diff paths"),
5010 apply_option_parse_p),
5011 OPT_BOOL(0, "no-add", &state->no_add,
5012 N_("ignore additions made by the patch")),
5013 OPT_BOOL(0, "stat", &state->diffstat,
5014 N_("instead of applying the patch, output diffstat for the input")),
5015 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
5016 OPT_NOOP_NOARG(0, "binary"),
5017 OPT_BOOL(0, "numstat", &state->numstat,
5018 N_("show number of added and deleted lines in decimal notation")),
5019 OPT_BOOL(0, "summary", &state->summary,
5020 N_("instead of applying the patch, output a summary for the input")),
5021 OPT_BOOL(0, "check", &state->check,
5022 N_("instead of applying the patch, see if the patch is applicable")),
5023 OPT_BOOL(0, "index", &state->check_index,
5024 N_("make sure the patch is applicable to the current index")),
5025 OPT_BOOL('N', "intent-to-add", &state->ita_only,
5026 N_("mark new files with `git add --intent-to-add`")),
5027 OPT_BOOL(0, "cached", &state->cached,
5028 N_("apply a patch without touching the working tree")),
5029 OPT_BOOL_F(0, "unsafe-paths", &state->unsafe_paths,
5030 N_("accept a patch that touches outside the working area"),
5031 PARSE_OPT_NOCOMPLETE),
5032 OPT_BOOL(0, "apply", force_apply,
5033 N_("also apply the patch (use with --stat/--summary/--check)")),
5034 OPT_BOOL('3', "3way", &state->threeway,
5035 N_( "attempt three-way merge, fall back on normal patch if that fails")),
5036 OPT_FILENAME(0, "build-fake-ancestor", &state->fake_ancestor,
5037 N_("build a temporary index based on embedded index information")),
5038 /* Think twice before adding "--nul" synonym to this */
5039 OPT_SET_INT('z', NULL, &state->line_termination,
5040 N_("paths are separated with NUL character"), '\0'),
5041 OPT_INTEGER('C', NULL, &state->p_context,
5042 N_("ensure at least <n> lines of context match")),
5043 OPT_CALLBACK(0, "whitespace", state, N_("action"),
5044 N_("detect new or modified lines that have whitespace errors"),
5045 apply_option_parse_whitespace),
5046 OPT_CALLBACK_F(0, "ignore-space-change", state, NULL,
5047 N_("ignore changes in whitespace when finding context"),
5048 PARSE_OPT_NOARG, apply_option_parse_space_change),
5049 OPT_CALLBACK_F(0, "ignore-whitespace", state, NULL,
5050 N_("ignore changes in whitespace when finding context"),
5051 PARSE_OPT_NOARG, apply_option_parse_space_change),
5052 OPT_BOOL('R', "reverse", &state->apply_in_reverse,
5053 N_("apply the patch in reverse")),
5054 OPT_BOOL(0, "unidiff-zero", &state->unidiff_zero,
5055 N_("don't expect at least one line of context")),
5056 OPT_BOOL(0, "reject", &state->apply_with_reject,
5057 N_("leave the rejected hunks in corresponding *.rej files")),
5058 OPT_BOOL(0, "allow-overlap", &state->allow_overlap,
5059 N_("allow overlapping hunks")),
5060 OPT__VERBOSITY(&state->apply_verbosity),
5061 OPT_BIT(0, "inaccurate-eof", options,
5062 N_("tolerate incorrectly detected missing new-line at the end of file"),
5063 APPLY_OPT_INACCURATE_EOF),
5064 OPT_BIT(0, "recount", options,
5065 N_("do not trust the line counts in the hunk headers"),
5066 APPLY_OPT_RECOUNT),
5067 OPT_CALLBACK(0, "directory", state, N_("root"),
5068 N_("prepend <root> to all filenames"),
5069 apply_option_parse_directory),
5070 OPT_BOOL(0, "allow-empty", &state->allow_empty,
5071 N_("don't return error for empty patches")),
5072 OPT_END()
5075 return parse_options(argc, argv, state->prefix, builtin_apply_options, apply_usage, 0);