builtin/apply: move 'apply_in_reverse' global into 'struct apply_state'
[git/git-svn.git] / builtin / apply.c
blob796d9909105c2029fc6cb88d23a8f0a05fa595b6
1 /*
2 * apply.c
4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
8 */
9 #include "cache.h"
10 #include "lockfile.h"
11 #include "cache-tree.h"
12 #include "quote.h"
13 #include "blob.h"
14 #include "delta.h"
15 #include "builtin.h"
16 #include "string-list.h"
17 #include "dir.h"
18 #include "diff.h"
19 #include "parse-options.h"
20 #include "xdiff-interface.h"
21 #include "ll-merge.h"
22 #include "rerere.h"
24 struct apply_state {
25 const char *prefix;
26 int prefix_length;
28 /* These control what gets looked at and modified */
29 int check; /* preimage must match working tree, don't actually apply */
30 int check_index; /* preimage must match the indexed version */
32 /* These boolean parameters control how the apply is done */
33 int apply_in_reverse;
34 int unidiff_zero;
38 * --stat does just a diffstat, and doesn't actually apply
39 * --numstat does numeric diffstat, and doesn't actually apply
40 * --index-info shows the old and new index info for paths if available.
41 * --cached updates only the cache without ever touching the working tree.
43 static int newfd = -1;
45 static int state_p_value = 1;
46 static int p_value_known;
47 static int update_index;
48 static int cached;
49 static int diffstat;
50 static int numstat;
51 static int summary;
52 static int apply = 1;
53 static int apply_with_reject;
54 static int apply_verbosely;
55 static int allow_overlap;
56 static int no_add;
57 static int threeway;
58 static int unsafe_paths;
59 static const char *fake_ancestor;
60 static int line_termination = '\n';
61 static unsigned int p_context = UINT_MAX;
62 static const char * const apply_usage[] = {
63 N_("git apply [<options>] [<patch>...]"),
64 NULL
67 static enum ws_error_action {
68 nowarn_ws_error,
69 warn_on_ws_error,
70 die_on_ws_error,
71 correct_ws_error
72 } ws_error_action = warn_on_ws_error;
73 static int whitespace_error;
74 static int squelch_whitespace_errors = 5;
75 static int applied_after_fixing_ws;
77 static enum ws_ignore {
78 ignore_ws_none,
79 ignore_ws_change
80 } ws_ignore_action = ignore_ws_none;
83 static const char *patch_input_file;
84 static struct strbuf root = STRBUF_INIT;
86 static void parse_whitespace_option(const char *option)
88 if (!option) {
89 ws_error_action = warn_on_ws_error;
90 return;
92 if (!strcmp(option, "warn")) {
93 ws_error_action = warn_on_ws_error;
94 return;
96 if (!strcmp(option, "nowarn")) {
97 ws_error_action = nowarn_ws_error;
98 return;
100 if (!strcmp(option, "error")) {
101 ws_error_action = die_on_ws_error;
102 return;
104 if (!strcmp(option, "error-all")) {
105 ws_error_action = die_on_ws_error;
106 squelch_whitespace_errors = 0;
107 return;
109 if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
110 ws_error_action = correct_ws_error;
111 return;
113 die(_("unrecognized whitespace option '%s'"), option);
116 static void parse_ignorewhitespace_option(const char *option)
118 if (!option || !strcmp(option, "no") ||
119 !strcmp(option, "false") || !strcmp(option, "never") ||
120 !strcmp(option, "none")) {
121 ws_ignore_action = ignore_ws_none;
122 return;
124 if (!strcmp(option, "change")) {
125 ws_ignore_action = ignore_ws_change;
126 return;
128 die(_("unrecognized whitespace ignore option '%s'"), option);
131 static void set_default_whitespace_mode(const char *whitespace_option)
133 if (!whitespace_option && !apply_default_whitespace)
134 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error);
138 * For "diff-stat" like behaviour, we keep track of the biggest change
139 * we've seen, and the longest filename. That allows us to do simple
140 * scaling.
142 static int max_change, max_len;
145 * Various "current state", notably line numbers and what
146 * file (and how) we're patching right now.. The "is_xxxx"
147 * things are flags, where -1 means "don't know yet".
149 static int state_linenr = 1;
152 * This represents one "hunk" from a patch, starting with
153 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
154 * patch text is pointed at by patch, and its byte length
155 * is stored in size. leading and trailing are the number
156 * of context lines.
158 struct fragment {
159 unsigned long leading, trailing;
160 unsigned long oldpos, oldlines;
161 unsigned long newpos, newlines;
163 * 'patch' is usually borrowed from buf in apply_patch(),
164 * but some codepaths store an allocated buffer.
166 const char *patch;
167 unsigned free_patch:1,
168 rejected:1;
169 int size;
170 int linenr;
171 struct fragment *next;
175 * When dealing with a binary patch, we reuse "leading" field
176 * to store the type of the binary hunk, either deflated "delta"
177 * or deflated "literal".
179 #define binary_patch_method leading
180 #define BINARY_DELTA_DEFLATED 1
181 #define BINARY_LITERAL_DEFLATED 2
184 * This represents a "patch" to a file, both metainfo changes
185 * such as creation/deletion, filemode and content changes represented
186 * as a series of fragments.
188 struct patch {
189 char *new_name, *old_name, *def_name;
190 unsigned int old_mode, new_mode;
191 int is_new, is_delete; /* -1 = unknown, 0 = false, 1 = true */
192 int rejected;
193 unsigned ws_rule;
194 int lines_added, lines_deleted;
195 int score;
196 unsigned int is_toplevel_relative:1;
197 unsigned int inaccurate_eof:1;
198 unsigned int is_binary:1;
199 unsigned int is_copy:1;
200 unsigned int is_rename:1;
201 unsigned int recount:1;
202 unsigned int conflicted_threeway:1;
203 unsigned int direct_to_threeway:1;
204 struct fragment *fragments;
205 char *result;
206 size_t resultsize;
207 char old_sha1_prefix[41];
208 char new_sha1_prefix[41];
209 struct patch *next;
211 /* three-way fallback result */
212 struct object_id threeway_stage[3];
215 static void free_fragment_list(struct fragment *list)
217 while (list) {
218 struct fragment *next = list->next;
219 if (list->free_patch)
220 free((char *)list->patch);
221 free(list);
222 list = next;
226 static void free_patch(struct patch *patch)
228 free_fragment_list(patch->fragments);
229 free(patch->def_name);
230 free(patch->old_name);
231 free(patch->new_name);
232 free(patch->result);
233 free(patch);
236 static void free_patch_list(struct patch *list)
238 while (list) {
239 struct patch *next = list->next;
240 free_patch(list);
241 list = next;
246 * A line in a file, len-bytes long (includes the terminating LF,
247 * except for an incomplete line at the end if the file ends with
248 * one), and its contents hashes to 'hash'.
250 struct line {
251 size_t len;
252 unsigned hash : 24;
253 unsigned flag : 8;
254 #define LINE_COMMON 1
255 #define LINE_PATCHED 2
259 * This represents a "file", which is an array of "lines".
261 struct image {
262 char *buf;
263 size_t len;
264 size_t nr;
265 size_t alloc;
266 struct line *line_allocated;
267 struct line *line;
271 * Records filenames that have been touched, in order to handle
272 * the case where more than one patches touch the same file.
275 static struct string_list fn_table;
277 static uint32_t hash_line(const char *cp, size_t len)
279 size_t i;
280 uint32_t h;
281 for (i = 0, h = 0; i < len; i++) {
282 if (!isspace(cp[i])) {
283 h = h * 3 + (cp[i] & 0xff);
286 return h;
290 * Compare lines s1 of length n1 and s2 of length n2, ignoring
291 * whitespace difference. Returns 1 if they match, 0 otherwise
293 static int fuzzy_matchlines(const char *s1, size_t n1,
294 const char *s2, size_t n2)
296 const char *last1 = s1 + n1 - 1;
297 const char *last2 = s2 + n2 - 1;
298 int result = 0;
300 /* ignore line endings */
301 while ((*last1 == '\r') || (*last1 == '\n'))
302 last1--;
303 while ((*last2 == '\r') || (*last2 == '\n'))
304 last2--;
306 /* skip leading whitespaces, if both begin with whitespace */
307 if (s1 <= last1 && s2 <= last2 && isspace(*s1) && isspace(*s2)) {
308 while (isspace(*s1) && (s1 <= last1))
309 s1++;
310 while (isspace(*s2) && (s2 <= last2))
311 s2++;
313 /* early return if both lines are empty */
314 if ((s1 > last1) && (s2 > last2))
315 return 1;
316 while (!result) {
317 result = *s1++ - *s2++;
319 * Skip whitespace inside. We check for whitespace on
320 * both buffers because we don't want "a b" to match
321 * "ab"
323 if (isspace(*s1) && isspace(*s2)) {
324 while (isspace(*s1) && s1 <= last1)
325 s1++;
326 while (isspace(*s2) && s2 <= last2)
327 s2++;
330 * If we reached the end on one side only,
331 * lines don't match
333 if (
334 ((s2 > last2) && (s1 <= last1)) ||
335 ((s1 > last1) && (s2 <= last2)))
336 return 0;
337 if ((s1 > last1) && (s2 > last2))
338 break;
341 return !result;
344 static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
346 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
347 img->line_allocated[img->nr].len = len;
348 img->line_allocated[img->nr].hash = hash_line(bol, len);
349 img->line_allocated[img->nr].flag = flag;
350 img->nr++;
354 * "buf" has the file contents to be patched (read from various sources).
355 * attach it to "image" and add line-based index to it.
356 * "image" now owns the "buf".
358 static void prepare_image(struct image *image, char *buf, size_t len,
359 int prepare_linetable)
361 const char *cp, *ep;
363 memset(image, 0, sizeof(*image));
364 image->buf = buf;
365 image->len = len;
367 if (!prepare_linetable)
368 return;
370 ep = image->buf + image->len;
371 cp = image->buf;
372 while (cp < ep) {
373 const char *next;
374 for (next = cp; next < ep && *next != '\n'; next++)
376 if (next < ep)
377 next++;
378 add_line_info(image, cp, next - cp, 0);
379 cp = next;
381 image->line = image->line_allocated;
384 static void clear_image(struct image *image)
386 free(image->buf);
387 free(image->line_allocated);
388 memset(image, 0, sizeof(*image));
391 /* fmt must contain _one_ %s and no other substitution */
392 static void say_patch_name(FILE *output, const char *fmt, struct patch *patch)
394 struct strbuf sb = STRBUF_INIT;
396 if (patch->old_name && patch->new_name &&
397 strcmp(patch->old_name, patch->new_name)) {
398 quote_c_style(patch->old_name, &sb, NULL, 0);
399 strbuf_addstr(&sb, " => ");
400 quote_c_style(patch->new_name, &sb, NULL, 0);
401 } else {
402 const char *n = patch->new_name;
403 if (!n)
404 n = patch->old_name;
405 quote_c_style(n, &sb, NULL, 0);
407 fprintf(output, fmt, sb.buf);
408 fputc('\n', output);
409 strbuf_release(&sb);
412 #define SLOP (16)
414 static void read_patch_file(struct strbuf *sb, int fd)
416 if (strbuf_read(sb, fd, 0) < 0)
417 die_errno("git apply: failed to read");
420 * Make sure that we have some slop in the buffer
421 * so that we can do speculative "memcmp" etc, and
422 * see to it that it is NUL-filled.
424 strbuf_grow(sb, SLOP);
425 memset(sb->buf + sb->len, 0, SLOP);
428 static unsigned long linelen(const char *buffer, unsigned long size)
430 unsigned long len = 0;
431 while (size--) {
432 len++;
433 if (*buffer++ == '\n')
434 break;
436 return len;
439 static int is_dev_null(const char *str)
441 return skip_prefix(str, "/dev/null", &str) && isspace(*str);
444 #define TERM_SPACE 1
445 #define TERM_TAB 2
447 static int name_terminate(const char *name, int namelen, int c, int terminate)
449 if (c == ' ' && !(terminate & TERM_SPACE))
450 return 0;
451 if (c == '\t' && !(terminate & TERM_TAB))
452 return 0;
454 return 1;
457 /* remove double slashes to make --index work with such filenames */
458 static char *squash_slash(char *name)
460 int i = 0, j = 0;
462 if (!name)
463 return NULL;
465 while (name[i]) {
466 if ((name[j++] = name[i++]) == '/')
467 while (name[i] == '/')
468 i++;
470 name[j] = '\0';
471 return name;
474 static char *find_name_gnu(const char *line, const char *def, int p_value)
476 struct strbuf name = STRBUF_INIT;
477 char *cp;
480 * Proposed "new-style" GNU patch/diff format; see
481 * http://marc.info/?l=git&m=112927316408690&w=2
483 if (unquote_c_style(&name, line, NULL)) {
484 strbuf_release(&name);
485 return NULL;
488 for (cp = name.buf; p_value; p_value--) {
489 cp = strchr(cp, '/');
490 if (!cp) {
491 strbuf_release(&name);
492 return NULL;
494 cp++;
497 strbuf_remove(&name, 0, cp - name.buf);
498 if (root.len)
499 strbuf_insert(&name, 0, root.buf, root.len);
500 return squash_slash(strbuf_detach(&name, NULL));
503 static size_t sane_tz_len(const char *line, size_t len)
505 const char *tz, *p;
507 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
508 return 0;
509 tz = line + len - strlen(" +0500");
511 if (tz[1] != '+' && tz[1] != '-')
512 return 0;
514 for (p = tz + 2; p != line + len; p++)
515 if (!isdigit(*p))
516 return 0;
518 return line + len - tz;
521 static size_t tz_with_colon_len(const char *line, size_t len)
523 const char *tz, *p;
525 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
526 return 0;
527 tz = line + len - strlen(" +08:00");
529 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
530 return 0;
531 p = tz + 2;
532 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
533 !isdigit(*p++) || !isdigit(*p++))
534 return 0;
536 return line + len - tz;
539 static size_t date_len(const char *line, size_t len)
541 const char *date, *p;
543 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
544 return 0;
545 p = date = line + len - strlen("72-02-05");
547 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
548 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
549 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */
550 return 0;
552 if (date - line >= strlen("19") &&
553 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */
554 date -= strlen("19");
556 return line + len - date;
559 static size_t short_time_len(const char *line, size_t len)
561 const char *time, *p;
563 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
564 return 0;
565 p = time = line + len - strlen(" 07:01:32");
567 /* Permit 1-digit hours? */
568 if (*p++ != ' ' ||
569 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
570 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
571 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */
572 return 0;
574 return line + len - time;
577 static size_t fractional_time_len(const char *line, size_t len)
579 const char *p;
580 size_t n;
582 /* Expected format: 19:41:17.620000023 */
583 if (!len || !isdigit(line[len - 1]))
584 return 0;
585 p = line + len - 1;
587 /* Fractional seconds. */
588 while (p > line && isdigit(*p))
589 p--;
590 if (*p != '.')
591 return 0;
593 /* Hours, minutes, and whole seconds. */
594 n = short_time_len(line, p - line);
595 if (!n)
596 return 0;
598 return line + len - p + n;
601 static size_t trailing_spaces_len(const char *line, size_t len)
603 const char *p;
605 /* Expected format: ' ' x (1 or more) */
606 if (!len || line[len - 1] != ' ')
607 return 0;
609 p = line + len;
610 while (p != line) {
611 p--;
612 if (*p != ' ')
613 return line + len - (p + 1);
616 /* All spaces! */
617 return len;
620 static size_t diff_timestamp_len(const char *line, size_t len)
622 const char *end = line + len;
623 size_t n;
626 * Posix: 2010-07-05 19:41:17
627 * GNU: 2010-07-05 19:41:17.620000023 -0500
630 if (!isdigit(end[-1]))
631 return 0;
633 n = sane_tz_len(line, end - line);
634 if (!n)
635 n = tz_with_colon_len(line, end - line);
636 end -= n;
638 n = short_time_len(line, end - line);
639 if (!n)
640 n = fractional_time_len(line, end - line);
641 end -= n;
643 n = date_len(line, end - line);
644 if (!n) /* No date. Too bad. */
645 return 0;
646 end -= n;
648 if (end == line) /* No space before date. */
649 return 0;
650 if (end[-1] == '\t') { /* Success! */
651 end--;
652 return line + len - end;
654 if (end[-1] != ' ') /* No space before date. */
655 return 0;
657 /* Whitespace damage. */
658 end -= trailing_spaces_len(line, end - line);
659 return line + len - end;
662 static char *find_name_common(const char *line, const char *def,
663 int p_value, const char *end, int terminate)
665 int len;
666 const char *start = NULL;
668 if (p_value == 0)
669 start = line;
670 while (line != end) {
671 char c = *line;
673 if (!end && isspace(c)) {
674 if (c == '\n')
675 break;
676 if (name_terminate(start, line-start, c, terminate))
677 break;
679 line++;
680 if (c == '/' && !--p_value)
681 start = line;
683 if (!start)
684 return squash_slash(xstrdup_or_null(def));
685 len = line - start;
686 if (!len)
687 return squash_slash(xstrdup_or_null(def));
690 * Generally we prefer the shorter name, especially
691 * if the other one is just a variation of that with
692 * something else tacked on to the end (ie "file.orig"
693 * or "file~").
695 if (def) {
696 int deflen = strlen(def);
697 if (deflen < len && !strncmp(start, def, deflen))
698 return squash_slash(xstrdup(def));
701 if (root.len) {
702 char *ret = xstrfmt("%s%.*s", root.buf, len, start);
703 return squash_slash(ret);
706 return squash_slash(xmemdupz(start, len));
709 static char *find_name(const char *line, char *def, int p_value, int terminate)
711 if (*line == '"') {
712 char *name = find_name_gnu(line, def, p_value);
713 if (name)
714 return name;
717 return find_name_common(line, def, p_value, NULL, terminate);
720 static char *find_name_traditional(const char *line, char *def, int p_value)
722 size_t len;
723 size_t date_len;
725 if (*line == '"') {
726 char *name = find_name_gnu(line, def, p_value);
727 if (name)
728 return name;
731 len = strchrnul(line, '\n') - line;
732 date_len = diff_timestamp_len(line, len);
733 if (!date_len)
734 return find_name_common(line, def, p_value, NULL, TERM_TAB);
735 len -= date_len;
737 return find_name_common(line, def, p_value, line + len, 0);
740 static int count_slashes(const char *cp)
742 int cnt = 0;
743 char ch;
745 while ((ch = *cp++))
746 if (ch == '/')
747 cnt++;
748 return cnt;
752 * Given the string after "--- " or "+++ ", guess the appropriate
753 * p_value for the given patch.
755 static int guess_p_value(struct apply_state *state, const char *nameline)
757 char *name, *cp;
758 int val = -1;
760 if (is_dev_null(nameline))
761 return -1;
762 name = find_name_traditional(nameline, NULL, 0);
763 if (!name)
764 return -1;
765 cp = strchr(name, '/');
766 if (!cp)
767 val = 0;
768 else if (state->prefix) {
770 * Does it begin with "a/$our-prefix" and such? Then this is
771 * very likely to apply to our directory.
773 if (!strncmp(name, state->prefix, state->prefix_length))
774 val = count_slashes(state->prefix);
775 else {
776 cp++;
777 if (!strncmp(cp, state->prefix, state->prefix_length))
778 val = count_slashes(state->prefix) + 1;
781 free(name);
782 return val;
786 * Does the ---/+++ line have the POSIX timestamp after the last HT?
787 * GNU diff puts epoch there to signal a creation/deletion event. Is
788 * this such a timestamp?
790 static int has_epoch_timestamp(const char *nameline)
793 * We are only interested in epoch timestamp; any non-zero
794 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
795 * For the same reason, the date must be either 1969-12-31 or
796 * 1970-01-01, and the seconds part must be "00".
798 const char stamp_regexp[] =
799 "^(1969-12-31|1970-01-01)"
801 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
803 "([-+][0-2][0-9]:?[0-5][0-9])\n";
804 const char *timestamp = NULL, *cp, *colon;
805 static regex_t *stamp;
806 regmatch_t m[10];
807 int zoneoffset;
808 int hourminute;
809 int status;
811 for (cp = nameline; *cp != '\n'; cp++) {
812 if (*cp == '\t')
813 timestamp = cp + 1;
815 if (!timestamp)
816 return 0;
817 if (!stamp) {
818 stamp = xmalloc(sizeof(*stamp));
819 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
820 warning(_("Cannot prepare timestamp regexp %s"),
821 stamp_regexp);
822 return 0;
826 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
827 if (status) {
828 if (status != REG_NOMATCH)
829 warning(_("regexec returned %d for input: %s"),
830 status, timestamp);
831 return 0;
834 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
835 if (*colon == ':')
836 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
837 else
838 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
839 if (timestamp[m[3].rm_so] == '-')
840 zoneoffset = -zoneoffset;
843 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
844 * (west of GMT) or 1970-01-01 (east of GMT)
846 if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) ||
847 (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10)))
848 return 0;
850 hourminute = (strtol(timestamp + 11, NULL, 10) * 60 +
851 strtol(timestamp + 14, NULL, 10) -
852 zoneoffset);
854 return ((zoneoffset < 0 && hourminute == 1440) ||
855 (0 <= zoneoffset && !hourminute));
859 * Get the name etc info from the ---/+++ lines of a traditional patch header
861 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
862 * files, we can happily check the index for a match, but for creating a
863 * new file we should try to match whatever "patch" does. I have no idea.
865 static void parse_traditional_patch(struct apply_state *state,
866 const char *first,
867 const char *second,
868 struct patch *patch)
870 char *name;
872 first += 4; /* skip "--- " */
873 second += 4; /* skip "+++ " */
874 if (!p_value_known) {
875 int p, q;
876 p = guess_p_value(state, first);
877 q = guess_p_value(state, second);
878 if (p < 0) p = q;
879 if (0 <= p && p == q) {
880 state_p_value = p;
881 p_value_known = 1;
884 if (is_dev_null(first)) {
885 patch->is_new = 1;
886 patch->is_delete = 0;
887 name = find_name_traditional(second, NULL, state_p_value);
888 patch->new_name = name;
889 } else if (is_dev_null(second)) {
890 patch->is_new = 0;
891 patch->is_delete = 1;
892 name = find_name_traditional(first, NULL, state_p_value);
893 patch->old_name = name;
894 } else {
895 char *first_name;
896 first_name = find_name_traditional(first, NULL, state_p_value);
897 name = find_name_traditional(second, first_name, state_p_value);
898 free(first_name);
899 if (has_epoch_timestamp(first)) {
900 patch->is_new = 1;
901 patch->is_delete = 0;
902 patch->new_name = name;
903 } else if (has_epoch_timestamp(second)) {
904 patch->is_new = 0;
905 patch->is_delete = 1;
906 patch->old_name = name;
907 } else {
908 patch->old_name = name;
909 patch->new_name = xstrdup_or_null(name);
912 if (!name)
913 die(_("unable to find filename in patch at line %d"), state_linenr);
916 static int gitdiff_hdrend(const char *line, struct patch *patch)
918 return -1;
922 * We're anal about diff header consistency, to make
923 * sure that we don't end up having strange ambiguous
924 * patches floating around.
926 * As a result, gitdiff_{old|new}name() will check
927 * their names against any previous information, just
928 * to make sure..
930 #define DIFF_OLD_NAME 0
931 #define DIFF_NEW_NAME 1
933 static void gitdiff_verify_name(const char *line, int isnull, char **name, int side)
935 if (!*name && !isnull) {
936 *name = find_name(line, NULL, state_p_value, TERM_TAB);
937 return;
940 if (*name) {
941 int len = strlen(*name);
942 char *another;
943 if (isnull)
944 die(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
945 *name, state_linenr);
946 another = find_name(line, NULL, state_p_value, TERM_TAB);
947 if (!another || memcmp(another, *name, len + 1))
948 die((side == DIFF_NEW_NAME) ?
949 _("git apply: bad git-diff - inconsistent new filename on line %d") :
950 _("git apply: bad git-diff - inconsistent old filename on line %d"), state_linenr);
951 free(another);
952 } else {
953 /* expect "/dev/null" */
954 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
955 die(_("git apply: bad git-diff - expected /dev/null on line %d"), state_linenr);
959 static int gitdiff_oldname(const char *line, struct patch *patch)
961 gitdiff_verify_name(line, patch->is_new, &patch->old_name,
962 DIFF_OLD_NAME);
963 return 0;
966 static int gitdiff_newname(const char *line, struct patch *patch)
968 gitdiff_verify_name(line, patch->is_delete, &patch->new_name,
969 DIFF_NEW_NAME);
970 return 0;
973 static int gitdiff_oldmode(const char *line, struct patch *patch)
975 patch->old_mode = strtoul(line, NULL, 8);
976 return 0;
979 static int gitdiff_newmode(const char *line, struct patch *patch)
981 patch->new_mode = strtoul(line, NULL, 8);
982 return 0;
985 static int gitdiff_delete(const char *line, struct patch *patch)
987 patch->is_delete = 1;
988 free(patch->old_name);
989 patch->old_name = xstrdup_or_null(patch->def_name);
990 return gitdiff_oldmode(line, patch);
993 static int gitdiff_newfile(const char *line, struct patch *patch)
995 patch->is_new = 1;
996 free(patch->new_name);
997 patch->new_name = xstrdup_or_null(patch->def_name);
998 return gitdiff_newmode(line, patch);
1001 static int gitdiff_copysrc(const char *line, struct patch *patch)
1003 patch->is_copy = 1;
1004 free(patch->old_name);
1005 patch->old_name = find_name(line, NULL, state_p_value ? state_p_value - 1 : 0, 0);
1006 return 0;
1009 static int gitdiff_copydst(const char *line, struct patch *patch)
1011 patch->is_copy = 1;
1012 free(patch->new_name);
1013 patch->new_name = find_name(line, NULL, state_p_value ? state_p_value - 1 : 0, 0);
1014 return 0;
1017 static int gitdiff_renamesrc(const char *line, struct patch *patch)
1019 patch->is_rename = 1;
1020 free(patch->old_name);
1021 patch->old_name = find_name(line, NULL, state_p_value ? state_p_value - 1 : 0, 0);
1022 return 0;
1025 static int gitdiff_renamedst(const char *line, struct patch *patch)
1027 patch->is_rename = 1;
1028 free(patch->new_name);
1029 patch->new_name = find_name(line, NULL, state_p_value ? state_p_value - 1 : 0, 0);
1030 return 0;
1033 static int gitdiff_similarity(const char *line, struct patch *patch)
1035 unsigned long val = strtoul(line, NULL, 10);
1036 if (val <= 100)
1037 patch->score = val;
1038 return 0;
1041 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
1043 unsigned long val = strtoul(line, NULL, 10);
1044 if (val <= 100)
1045 patch->score = val;
1046 return 0;
1049 static int gitdiff_index(const char *line, struct patch *patch)
1052 * index line is N hexadecimal, "..", N hexadecimal,
1053 * and optional space with octal mode.
1055 const char *ptr, *eol;
1056 int len;
1058 ptr = strchr(line, '.');
1059 if (!ptr || ptr[1] != '.' || 40 < ptr - line)
1060 return 0;
1061 len = ptr - line;
1062 memcpy(patch->old_sha1_prefix, line, len);
1063 patch->old_sha1_prefix[len] = 0;
1065 line = ptr + 2;
1066 ptr = strchr(line, ' ');
1067 eol = strchrnul(line, '\n');
1069 if (!ptr || eol < ptr)
1070 ptr = eol;
1071 len = ptr - line;
1073 if (40 < len)
1074 return 0;
1075 memcpy(patch->new_sha1_prefix, line, len);
1076 patch->new_sha1_prefix[len] = 0;
1077 if (*ptr == ' ')
1078 patch->old_mode = strtoul(ptr+1, NULL, 8);
1079 return 0;
1083 * This is normal for a diff that doesn't change anything: we'll fall through
1084 * into the next diff. Tell the parser to break out.
1086 static int gitdiff_unrecognized(const char *line, struct patch *patch)
1088 return -1;
1092 * Skip p_value leading components from "line"; as we do not accept
1093 * absolute paths, return NULL in that case.
1095 static const char *skip_tree_prefix(const char *line, int llen)
1097 int nslash;
1098 int i;
1100 if (!state_p_value)
1101 return (llen && line[0] == '/') ? NULL : line;
1103 nslash = state_p_value;
1104 for (i = 0; i < llen; i++) {
1105 int ch = line[i];
1106 if (ch == '/' && --nslash <= 0)
1107 return (i == 0) ? NULL : &line[i + 1];
1109 return NULL;
1113 * This is to extract the same name that appears on "diff --git"
1114 * line. We do not find and return anything if it is a rename
1115 * patch, and it is OK because we will find the name elsewhere.
1116 * We need to reliably find name only when it is mode-change only,
1117 * creation or deletion of an empty file. In any of these cases,
1118 * both sides are the same name under a/ and b/ respectively.
1120 static char *git_header_name(const char *line, int llen)
1122 const char *name;
1123 const char *second = NULL;
1124 size_t len, line_len;
1126 line += strlen("diff --git ");
1127 llen -= strlen("diff --git ");
1129 if (*line == '"') {
1130 const char *cp;
1131 struct strbuf first = STRBUF_INIT;
1132 struct strbuf sp = STRBUF_INIT;
1134 if (unquote_c_style(&first, line, &second))
1135 goto free_and_fail1;
1137 /* strip the a/b prefix including trailing slash */
1138 cp = skip_tree_prefix(first.buf, first.len);
1139 if (!cp)
1140 goto free_and_fail1;
1141 strbuf_remove(&first, 0, cp - first.buf);
1144 * second points at one past closing dq of name.
1145 * find the second name.
1147 while ((second < line + llen) && isspace(*second))
1148 second++;
1150 if (line + llen <= second)
1151 goto free_and_fail1;
1152 if (*second == '"') {
1153 if (unquote_c_style(&sp, second, NULL))
1154 goto free_and_fail1;
1155 cp = skip_tree_prefix(sp.buf, sp.len);
1156 if (!cp)
1157 goto free_and_fail1;
1158 /* They must match, otherwise ignore */
1159 if (strcmp(cp, first.buf))
1160 goto free_and_fail1;
1161 strbuf_release(&sp);
1162 return strbuf_detach(&first, NULL);
1165 /* unquoted second */
1166 cp = skip_tree_prefix(second, line + llen - second);
1167 if (!cp)
1168 goto free_and_fail1;
1169 if (line + llen - cp != first.len ||
1170 memcmp(first.buf, cp, first.len))
1171 goto free_and_fail1;
1172 return strbuf_detach(&first, NULL);
1174 free_and_fail1:
1175 strbuf_release(&first);
1176 strbuf_release(&sp);
1177 return NULL;
1180 /* unquoted first name */
1181 name = skip_tree_prefix(line, llen);
1182 if (!name)
1183 return NULL;
1186 * since the first name is unquoted, a dq if exists must be
1187 * the beginning of the second name.
1189 for (second = name; second < line + llen; second++) {
1190 if (*second == '"') {
1191 struct strbuf sp = STRBUF_INIT;
1192 const char *np;
1194 if (unquote_c_style(&sp, second, NULL))
1195 goto free_and_fail2;
1197 np = skip_tree_prefix(sp.buf, sp.len);
1198 if (!np)
1199 goto free_and_fail2;
1201 len = sp.buf + sp.len - np;
1202 if (len < second - name &&
1203 !strncmp(np, name, len) &&
1204 isspace(name[len])) {
1205 /* Good */
1206 strbuf_remove(&sp, 0, np - sp.buf);
1207 return strbuf_detach(&sp, NULL);
1210 free_and_fail2:
1211 strbuf_release(&sp);
1212 return NULL;
1217 * Accept a name only if it shows up twice, exactly the same
1218 * form.
1220 second = strchr(name, '\n');
1221 if (!second)
1222 return NULL;
1223 line_len = second - name;
1224 for (len = 0 ; ; len++) {
1225 switch (name[len]) {
1226 default:
1227 continue;
1228 case '\n':
1229 return NULL;
1230 case '\t': case ' ':
1232 * Is this the separator between the preimage
1233 * and the postimage pathname? Again, we are
1234 * only interested in the case where there is
1235 * no rename, as this is only to set def_name
1236 * and a rename patch has the names elsewhere
1237 * in an unambiguous form.
1239 if (!name[len + 1])
1240 return NULL; /* no postimage name */
1241 second = skip_tree_prefix(name + len + 1,
1242 line_len - (len + 1));
1243 if (!second)
1244 return NULL;
1246 * Does len bytes starting at "name" and "second"
1247 * (that are separated by one HT or SP we just
1248 * found) exactly match?
1250 if (second[len] == '\n' && !strncmp(name, second, len))
1251 return xmemdupz(name, len);
1256 /* Verify that we recognize the lines following a git header */
1257 static int parse_git_header(const char *line, int len, unsigned int size, struct patch *patch)
1259 unsigned long offset;
1261 /* A git diff has explicit new/delete information, so we don't guess */
1262 patch->is_new = 0;
1263 patch->is_delete = 0;
1266 * Some things may not have the old name in the
1267 * rest of the headers anywhere (pure mode changes,
1268 * or removing or adding empty files), so we get
1269 * the default name from the header.
1271 patch->def_name = git_header_name(line, len);
1272 if (patch->def_name && root.len) {
1273 char *s = xstrfmt("%s%s", root.buf, patch->def_name);
1274 free(patch->def_name);
1275 patch->def_name = s;
1278 line += len;
1279 size -= len;
1280 state_linenr++;
1281 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, state_linenr++) {
1282 static const struct opentry {
1283 const char *str;
1284 int (*fn)(const char *, struct patch *);
1285 } optable[] = {
1286 { "@@ -", gitdiff_hdrend },
1287 { "--- ", gitdiff_oldname },
1288 { "+++ ", gitdiff_newname },
1289 { "old mode ", gitdiff_oldmode },
1290 { "new mode ", gitdiff_newmode },
1291 { "deleted file mode ", gitdiff_delete },
1292 { "new file mode ", gitdiff_newfile },
1293 { "copy from ", gitdiff_copysrc },
1294 { "copy to ", gitdiff_copydst },
1295 { "rename old ", gitdiff_renamesrc },
1296 { "rename new ", gitdiff_renamedst },
1297 { "rename from ", gitdiff_renamesrc },
1298 { "rename to ", gitdiff_renamedst },
1299 { "similarity index ", gitdiff_similarity },
1300 { "dissimilarity index ", gitdiff_dissimilarity },
1301 { "index ", gitdiff_index },
1302 { "", gitdiff_unrecognized },
1304 int i;
1306 len = linelen(line, size);
1307 if (!len || line[len-1] != '\n')
1308 break;
1309 for (i = 0; i < ARRAY_SIZE(optable); i++) {
1310 const struct opentry *p = optable + i;
1311 int oplen = strlen(p->str);
1312 if (len < oplen || memcmp(p->str, line, oplen))
1313 continue;
1314 if (p->fn(line + oplen, patch) < 0)
1315 return offset;
1316 break;
1320 return offset;
1323 static int parse_num(const char *line, unsigned long *p)
1325 char *ptr;
1327 if (!isdigit(*line))
1328 return 0;
1329 *p = strtoul(line, &ptr, 10);
1330 return ptr - line;
1333 static int parse_range(const char *line, int len, int offset, const char *expect,
1334 unsigned long *p1, unsigned long *p2)
1336 int digits, ex;
1338 if (offset < 0 || offset >= len)
1339 return -1;
1340 line += offset;
1341 len -= offset;
1343 digits = parse_num(line, p1);
1344 if (!digits)
1345 return -1;
1347 offset += digits;
1348 line += digits;
1349 len -= digits;
1351 *p2 = 1;
1352 if (*line == ',') {
1353 digits = parse_num(line+1, p2);
1354 if (!digits)
1355 return -1;
1357 offset += digits+1;
1358 line += digits+1;
1359 len -= digits+1;
1362 ex = strlen(expect);
1363 if (ex > len)
1364 return -1;
1365 if (memcmp(line, expect, ex))
1366 return -1;
1368 return offset + ex;
1371 static void recount_diff(const char *line, int size, struct fragment *fragment)
1373 int oldlines = 0, newlines = 0, ret = 0;
1375 if (size < 1) {
1376 warning("recount: ignore empty hunk");
1377 return;
1380 for (;;) {
1381 int len = linelen(line, size);
1382 size -= len;
1383 line += len;
1385 if (size < 1)
1386 break;
1388 switch (*line) {
1389 case ' ': case '\n':
1390 newlines++;
1391 /* fall through */
1392 case '-':
1393 oldlines++;
1394 continue;
1395 case '+':
1396 newlines++;
1397 continue;
1398 case '\\':
1399 continue;
1400 case '@':
1401 ret = size < 3 || !starts_with(line, "@@ ");
1402 break;
1403 case 'd':
1404 ret = size < 5 || !starts_with(line, "diff ");
1405 break;
1406 default:
1407 ret = -1;
1408 break;
1410 if (ret) {
1411 warning(_("recount: unexpected line: %.*s"),
1412 (int)linelen(line, size), line);
1413 return;
1415 break;
1417 fragment->oldlines = oldlines;
1418 fragment->newlines = newlines;
1422 * Parse a unified diff fragment header of the
1423 * form "@@ -a,b +c,d @@"
1425 static int parse_fragment_header(const char *line, int len, struct fragment *fragment)
1427 int offset;
1429 if (!len || line[len-1] != '\n')
1430 return -1;
1432 /* Figure out the number of lines in a fragment */
1433 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1434 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1436 return offset;
1439 static int find_header(struct apply_state *state,
1440 const char *line,
1441 unsigned long size,
1442 int *hdrsize,
1443 struct patch *patch)
1445 unsigned long offset, len;
1447 patch->is_toplevel_relative = 0;
1448 patch->is_rename = patch->is_copy = 0;
1449 patch->is_new = patch->is_delete = -1;
1450 patch->old_mode = patch->new_mode = 0;
1451 patch->old_name = patch->new_name = NULL;
1452 for (offset = 0; size > 0; offset += len, size -= len, line += len, state_linenr++) {
1453 unsigned long nextlen;
1455 len = linelen(line, size);
1456 if (!len)
1457 break;
1459 /* Testing this early allows us to take a few shortcuts.. */
1460 if (len < 6)
1461 continue;
1464 * Make sure we don't find any unconnected patch fragments.
1465 * That's a sign that we didn't find a header, and that a
1466 * patch has become corrupted/broken up.
1468 if (!memcmp("@@ -", line, 4)) {
1469 struct fragment dummy;
1470 if (parse_fragment_header(line, len, &dummy) < 0)
1471 continue;
1472 die(_("patch fragment without header at line %d: %.*s"),
1473 state_linenr, (int)len-1, line);
1476 if (size < len + 6)
1477 break;
1480 * Git patch? It might not have a real patch, just a rename
1481 * or mode change, so we handle that specially
1483 if (!memcmp("diff --git ", line, 11)) {
1484 int git_hdr_len = parse_git_header(line, len, size, patch);
1485 if (git_hdr_len <= len)
1486 continue;
1487 if (!patch->old_name && !patch->new_name) {
1488 if (!patch->def_name)
1489 die(Q_("git diff header lacks filename information when removing "
1490 "%d leading pathname component (line %d)",
1491 "git diff header lacks filename information when removing "
1492 "%d leading pathname components (line %d)",
1493 state_p_value),
1494 state_p_value, state_linenr);
1495 patch->old_name = xstrdup(patch->def_name);
1496 patch->new_name = xstrdup(patch->def_name);
1498 if (!patch->is_delete && !patch->new_name)
1499 die("git diff header lacks filename information "
1500 "(line %d)", state_linenr);
1501 patch->is_toplevel_relative = 1;
1502 *hdrsize = git_hdr_len;
1503 return offset;
1506 /* --- followed by +++ ? */
1507 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1508 continue;
1511 * We only accept unified patches, so we want it to
1512 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1513 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1515 nextlen = linelen(line + len, size - len);
1516 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1517 continue;
1519 /* Ok, we'll consider it a patch */
1520 parse_traditional_patch(state, line, line+len, patch);
1521 *hdrsize = len + nextlen;
1522 state_linenr += 2;
1523 return offset;
1525 return -1;
1528 static void record_ws_error(unsigned result, const char *line, int len, int linenr)
1530 char *err;
1532 if (!result)
1533 return;
1535 whitespace_error++;
1536 if (squelch_whitespace_errors &&
1537 squelch_whitespace_errors < whitespace_error)
1538 return;
1540 err = whitespace_error_string(result);
1541 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1542 patch_input_file, linenr, err, len, line);
1543 free(err);
1546 static void check_whitespace(const char *line, int len, unsigned ws_rule)
1548 unsigned result = ws_check(line + 1, len - 1, ws_rule);
1550 record_ws_error(result, line + 1, len - 2, state_linenr);
1554 * Parse a unified diff. Note that this really needs to parse each
1555 * fragment separately, since the only way to know the difference
1556 * between a "---" that is part of a patch, and a "---" that starts
1557 * the next patch is to look at the line counts..
1559 static int parse_fragment(struct apply_state *state,
1560 const char *line,
1561 unsigned long size,
1562 struct patch *patch,
1563 struct fragment *fragment)
1565 int added, deleted;
1566 int len = linelen(line, size), offset;
1567 unsigned long oldlines, newlines;
1568 unsigned long leading, trailing;
1570 offset = parse_fragment_header(line, len, fragment);
1571 if (offset < 0)
1572 return -1;
1573 if (offset > 0 && patch->recount)
1574 recount_diff(line + offset, size - offset, fragment);
1575 oldlines = fragment->oldlines;
1576 newlines = fragment->newlines;
1577 leading = 0;
1578 trailing = 0;
1580 /* Parse the thing.. */
1581 line += len;
1582 size -= len;
1583 state_linenr++;
1584 added = deleted = 0;
1585 for (offset = len;
1586 0 < size;
1587 offset += len, size -= len, line += len, state_linenr++) {
1588 if (!oldlines && !newlines)
1589 break;
1590 len = linelen(line, size);
1591 if (!len || line[len-1] != '\n')
1592 return -1;
1593 switch (*line) {
1594 default:
1595 return -1;
1596 case '\n': /* newer GNU diff, an empty context line */
1597 case ' ':
1598 oldlines--;
1599 newlines--;
1600 if (!deleted && !added)
1601 leading++;
1602 trailing++;
1603 if (!state->apply_in_reverse &&
1604 ws_error_action == correct_ws_error)
1605 check_whitespace(line, len, patch->ws_rule);
1606 break;
1607 case '-':
1608 if (state->apply_in_reverse &&
1609 ws_error_action != nowarn_ws_error)
1610 check_whitespace(line, len, patch->ws_rule);
1611 deleted++;
1612 oldlines--;
1613 trailing = 0;
1614 break;
1615 case '+':
1616 if (!state->apply_in_reverse &&
1617 ws_error_action != nowarn_ws_error)
1618 check_whitespace(line, len, patch->ws_rule);
1619 added++;
1620 newlines--;
1621 trailing = 0;
1622 break;
1625 * We allow "\ No newline at end of file". Depending
1626 * on locale settings when the patch was produced we
1627 * don't know what this line looks like. The only
1628 * thing we do know is that it begins with "\ ".
1629 * Checking for 12 is just for sanity check -- any
1630 * l10n of "\ No newline..." is at least that long.
1632 case '\\':
1633 if (len < 12 || memcmp(line, "\\ ", 2))
1634 return -1;
1635 break;
1638 if (oldlines || newlines)
1639 return -1;
1640 if (!deleted && !added)
1641 return -1;
1643 fragment->leading = leading;
1644 fragment->trailing = trailing;
1647 * If a fragment ends with an incomplete line, we failed to include
1648 * it in the above loop because we hit oldlines == newlines == 0
1649 * before seeing it.
1651 if (12 < size && !memcmp(line, "\\ ", 2))
1652 offset += linelen(line, size);
1654 patch->lines_added += added;
1655 patch->lines_deleted += deleted;
1657 if (0 < patch->is_new && oldlines)
1658 return error(_("new file depends on old contents"));
1659 if (0 < patch->is_delete && newlines)
1660 return error(_("deleted file still has contents"));
1661 return offset;
1665 * We have seen "diff --git a/... b/..." header (or a traditional patch
1666 * header). Read hunks that belong to this patch into fragments and hang
1667 * them to the given patch structure.
1669 * The (fragment->patch, fragment->size) pair points into the memory given
1670 * by the caller, not a copy, when we return.
1672 static int parse_single_patch(struct apply_state *state,
1673 const char *line,
1674 unsigned long size,
1675 struct patch *patch)
1677 unsigned long offset = 0;
1678 unsigned long oldlines = 0, newlines = 0, context = 0;
1679 struct fragment **fragp = &patch->fragments;
1681 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1682 struct fragment *fragment;
1683 int len;
1685 fragment = xcalloc(1, sizeof(*fragment));
1686 fragment->linenr = state_linenr;
1687 len = parse_fragment(state, line, size, patch, fragment);
1688 if (len <= 0)
1689 die(_("corrupt patch at line %d"), state_linenr);
1690 fragment->patch = line;
1691 fragment->size = len;
1692 oldlines += fragment->oldlines;
1693 newlines += fragment->newlines;
1694 context += fragment->leading + fragment->trailing;
1696 *fragp = fragment;
1697 fragp = &fragment->next;
1699 offset += len;
1700 line += len;
1701 size -= len;
1705 * If something was removed (i.e. we have old-lines) it cannot
1706 * be creation, and if something was added it cannot be
1707 * deletion. However, the reverse is not true; --unified=0
1708 * patches that only add are not necessarily creation even
1709 * though they do not have any old lines, and ones that only
1710 * delete are not necessarily deletion.
1712 * Unfortunately, a real creation/deletion patch do _not_ have
1713 * any context line by definition, so we cannot safely tell it
1714 * apart with --unified=0 insanity. At least if the patch has
1715 * more than one hunk it is not creation or deletion.
1717 if (patch->is_new < 0 &&
1718 (oldlines || (patch->fragments && patch->fragments->next)))
1719 patch->is_new = 0;
1720 if (patch->is_delete < 0 &&
1721 (newlines || (patch->fragments && patch->fragments->next)))
1722 patch->is_delete = 0;
1724 if (0 < patch->is_new && oldlines)
1725 die(_("new file %s depends on old contents"), patch->new_name);
1726 if (0 < patch->is_delete && newlines)
1727 die(_("deleted file %s still has contents"), patch->old_name);
1728 if (!patch->is_delete && !newlines && context)
1729 fprintf_ln(stderr,
1730 _("** warning: "
1731 "file %s becomes empty but is not deleted"),
1732 patch->new_name);
1734 return offset;
1737 static inline int metadata_changes(struct patch *patch)
1739 return patch->is_rename > 0 ||
1740 patch->is_copy > 0 ||
1741 patch->is_new > 0 ||
1742 patch->is_delete ||
1743 (patch->old_mode && patch->new_mode &&
1744 patch->old_mode != patch->new_mode);
1747 static char *inflate_it(const void *data, unsigned long size,
1748 unsigned long inflated_size)
1750 git_zstream stream;
1751 void *out;
1752 int st;
1754 memset(&stream, 0, sizeof(stream));
1756 stream.next_in = (unsigned char *)data;
1757 stream.avail_in = size;
1758 stream.next_out = out = xmalloc(inflated_size);
1759 stream.avail_out = inflated_size;
1760 git_inflate_init(&stream);
1761 st = git_inflate(&stream, Z_FINISH);
1762 git_inflate_end(&stream);
1763 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1764 free(out);
1765 return NULL;
1767 return out;
1771 * Read a binary hunk and return a new fragment; fragment->patch
1772 * points at an allocated memory that the caller must free, so
1773 * it is marked as "->free_patch = 1".
1775 static struct fragment *parse_binary_hunk(char **buf_p,
1776 unsigned long *sz_p,
1777 int *status_p,
1778 int *used_p)
1781 * Expect a line that begins with binary patch method ("literal"
1782 * or "delta"), followed by the length of data before deflating.
1783 * a sequence of 'length-byte' followed by base-85 encoded data
1784 * should follow, terminated by a newline.
1786 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1787 * and we would limit the patch line to 66 characters,
1788 * so one line can fit up to 13 groups that would decode
1789 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1790 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1792 int llen, used;
1793 unsigned long size = *sz_p;
1794 char *buffer = *buf_p;
1795 int patch_method;
1796 unsigned long origlen;
1797 char *data = NULL;
1798 int hunk_size = 0;
1799 struct fragment *frag;
1801 llen = linelen(buffer, size);
1802 used = llen;
1804 *status_p = 0;
1806 if (starts_with(buffer, "delta ")) {
1807 patch_method = BINARY_DELTA_DEFLATED;
1808 origlen = strtoul(buffer + 6, NULL, 10);
1810 else if (starts_with(buffer, "literal ")) {
1811 patch_method = BINARY_LITERAL_DEFLATED;
1812 origlen = strtoul(buffer + 8, NULL, 10);
1814 else
1815 return NULL;
1817 state_linenr++;
1818 buffer += llen;
1819 while (1) {
1820 int byte_length, max_byte_length, newsize;
1821 llen = linelen(buffer, size);
1822 used += llen;
1823 state_linenr++;
1824 if (llen == 1) {
1825 /* consume the blank line */
1826 buffer++;
1827 size--;
1828 break;
1831 * Minimum line is "A00000\n" which is 7-byte long,
1832 * and the line length must be multiple of 5 plus 2.
1834 if ((llen < 7) || (llen-2) % 5)
1835 goto corrupt;
1836 max_byte_length = (llen - 2) / 5 * 4;
1837 byte_length = *buffer;
1838 if ('A' <= byte_length && byte_length <= 'Z')
1839 byte_length = byte_length - 'A' + 1;
1840 else if ('a' <= byte_length && byte_length <= 'z')
1841 byte_length = byte_length - 'a' + 27;
1842 else
1843 goto corrupt;
1844 /* if the input length was not multiple of 4, we would
1845 * have filler at the end but the filler should never
1846 * exceed 3 bytes
1848 if (max_byte_length < byte_length ||
1849 byte_length <= max_byte_length - 4)
1850 goto corrupt;
1851 newsize = hunk_size + byte_length;
1852 data = xrealloc(data, newsize);
1853 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1854 goto corrupt;
1855 hunk_size = newsize;
1856 buffer += llen;
1857 size -= llen;
1860 frag = xcalloc(1, sizeof(*frag));
1861 frag->patch = inflate_it(data, hunk_size, origlen);
1862 frag->free_patch = 1;
1863 if (!frag->patch)
1864 goto corrupt;
1865 free(data);
1866 frag->size = origlen;
1867 *buf_p = buffer;
1868 *sz_p = size;
1869 *used_p = used;
1870 frag->binary_patch_method = patch_method;
1871 return frag;
1873 corrupt:
1874 free(data);
1875 *status_p = -1;
1876 error(_("corrupt binary patch at line %d: %.*s"),
1877 state_linenr-1, llen-1, buffer);
1878 return NULL;
1882 * Returns:
1883 * -1 in case of error,
1884 * the length of the parsed binary patch otherwise
1886 static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1889 * We have read "GIT binary patch\n"; what follows is a line
1890 * that says the patch method (currently, either "literal" or
1891 * "delta") and the length of data before deflating; a
1892 * sequence of 'length-byte' followed by base-85 encoded data
1893 * follows.
1895 * When a binary patch is reversible, there is another binary
1896 * hunk in the same format, starting with patch method (either
1897 * "literal" or "delta") with the length of data, and a sequence
1898 * of length-byte + base-85 encoded data, terminated with another
1899 * empty line. This data, when applied to the postimage, produces
1900 * the preimage.
1902 struct fragment *forward;
1903 struct fragment *reverse;
1904 int status;
1905 int used, used_1;
1907 forward = parse_binary_hunk(&buffer, &size, &status, &used);
1908 if (!forward && !status)
1909 /* there has to be one hunk (forward hunk) */
1910 return error(_("unrecognized binary patch at line %d"), state_linenr-1);
1911 if (status)
1912 /* otherwise we already gave an error message */
1913 return status;
1915 reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1916 if (reverse)
1917 used += used_1;
1918 else if (status) {
1920 * Not having reverse hunk is not an error, but having
1921 * a corrupt reverse hunk is.
1923 free((void*) forward->patch);
1924 free(forward);
1925 return status;
1927 forward->next = reverse;
1928 patch->fragments = forward;
1929 patch->is_binary = 1;
1930 return used;
1933 static void prefix_one(struct apply_state *state, char **name)
1935 char *old_name = *name;
1936 if (!old_name)
1937 return;
1938 *name = xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));
1939 free(old_name);
1942 static void prefix_patch(struct apply_state *state, struct patch *p)
1944 if (!state->prefix || p->is_toplevel_relative)
1945 return;
1946 prefix_one(state, &p->new_name);
1947 prefix_one(state, &p->old_name);
1951 * include/exclude
1954 static struct string_list limit_by_name;
1955 static int has_include;
1956 static void add_name_limit(const char *name, int exclude)
1958 struct string_list_item *it;
1960 it = string_list_append(&limit_by_name, name);
1961 it->util = exclude ? NULL : (void *) 1;
1964 static int use_patch(struct apply_state *state, struct patch *p)
1966 const char *pathname = p->new_name ? p->new_name : p->old_name;
1967 int i;
1969 /* Paths outside are not touched regardless of "--include" */
1970 if (0 < state->prefix_length) {
1971 int pathlen = strlen(pathname);
1972 if (pathlen <= state->prefix_length ||
1973 memcmp(state->prefix, pathname, state->prefix_length))
1974 return 0;
1977 /* See if it matches any of exclude/include rule */
1978 for (i = 0; i < limit_by_name.nr; i++) {
1979 struct string_list_item *it = &limit_by_name.items[i];
1980 if (!wildmatch(it->string, pathname, 0, NULL))
1981 return (it->util != NULL);
1985 * If we had any include, a path that does not match any rule is
1986 * not used. Otherwise, we saw bunch of exclude rules (or none)
1987 * and such a path is used.
1989 return !has_include;
1994 * Read the patch text in "buffer" that extends for "size" bytes; stop
1995 * reading after seeing a single patch (i.e. changes to a single file).
1996 * Create fragments (i.e. patch hunks) and hang them to the given patch.
1997 * Return the number of bytes consumed, so that the caller can call us
1998 * again for the next patch.
2000 static int parse_chunk(struct apply_state *state, char *buffer, unsigned long size, struct patch *patch)
2002 int hdrsize, patchsize;
2003 int offset = find_header(state, buffer, size, &hdrsize, patch);
2005 if (offset < 0)
2006 return offset;
2008 prefix_patch(state, patch);
2010 if (!use_patch(state, patch))
2011 patch->ws_rule = 0;
2012 else
2013 patch->ws_rule = whitespace_rule(patch->new_name
2014 ? patch->new_name
2015 : patch->old_name);
2017 patchsize = parse_single_patch(state,
2018 buffer + offset + hdrsize,
2019 size - offset - hdrsize,
2020 patch);
2022 if (!patchsize) {
2023 static const char git_binary[] = "GIT binary patch\n";
2024 int hd = hdrsize + offset;
2025 unsigned long llen = linelen(buffer + hd, size - hd);
2027 if (llen == sizeof(git_binary) - 1 &&
2028 !memcmp(git_binary, buffer + hd, llen)) {
2029 int used;
2030 state_linenr++;
2031 used = parse_binary(buffer + hd + llen,
2032 size - hd - llen, patch);
2033 if (used < 0)
2034 return -1;
2035 if (used)
2036 patchsize = used + llen;
2037 else
2038 patchsize = 0;
2040 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
2041 static const char *binhdr[] = {
2042 "Binary files ",
2043 "Files ",
2044 NULL,
2046 int i;
2047 for (i = 0; binhdr[i]; i++) {
2048 int len = strlen(binhdr[i]);
2049 if (len < size - hd &&
2050 !memcmp(binhdr[i], buffer + hd, len)) {
2051 state_linenr++;
2052 patch->is_binary = 1;
2053 patchsize = llen;
2054 break;
2059 /* Empty patch cannot be applied if it is a text patch
2060 * without metadata change. A binary patch appears
2061 * empty to us here.
2063 if ((apply || state->check) &&
2064 (!patch->is_binary && !metadata_changes(patch)))
2065 die(_("patch with only garbage at line %d"), state_linenr);
2068 return offset + hdrsize + patchsize;
2071 #define swap(a,b) myswap((a),(b),sizeof(a))
2073 #define myswap(a, b, size) do { \
2074 unsigned char mytmp[size]; \
2075 memcpy(mytmp, &a, size); \
2076 memcpy(&a, &b, size); \
2077 memcpy(&b, mytmp, size); \
2078 } while (0)
2080 static void reverse_patches(struct patch *p)
2082 for (; p; p = p->next) {
2083 struct fragment *frag = p->fragments;
2085 swap(p->new_name, p->old_name);
2086 swap(p->new_mode, p->old_mode);
2087 swap(p->is_new, p->is_delete);
2088 swap(p->lines_added, p->lines_deleted);
2089 swap(p->old_sha1_prefix, p->new_sha1_prefix);
2091 for (; frag; frag = frag->next) {
2092 swap(frag->newpos, frag->oldpos);
2093 swap(frag->newlines, frag->oldlines);
2098 static const char pluses[] =
2099 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2100 static const char minuses[]=
2101 "----------------------------------------------------------------------";
2103 static void show_stats(struct patch *patch)
2105 struct strbuf qname = STRBUF_INIT;
2106 char *cp = patch->new_name ? patch->new_name : patch->old_name;
2107 int max, add, del;
2109 quote_c_style(cp, &qname, NULL, 0);
2112 * "scale" the filename
2114 max = max_len;
2115 if (max > 50)
2116 max = 50;
2118 if (qname.len > max) {
2119 cp = strchr(qname.buf + qname.len + 3 - max, '/');
2120 if (!cp)
2121 cp = qname.buf + qname.len + 3 - max;
2122 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
2125 if (patch->is_binary) {
2126 printf(" %-*s | Bin\n", max, qname.buf);
2127 strbuf_release(&qname);
2128 return;
2131 printf(" %-*s |", max, qname.buf);
2132 strbuf_release(&qname);
2135 * scale the add/delete
2137 max = max + max_change > 70 ? 70 - max : max_change;
2138 add = patch->lines_added;
2139 del = patch->lines_deleted;
2141 if (max_change > 0) {
2142 int total = ((add + del) * max + max_change / 2) / max_change;
2143 add = (add * max + max_change / 2) / max_change;
2144 del = total - add;
2146 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
2147 add, pluses, del, minuses);
2150 static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
2152 switch (st->st_mode & S_IFMT) {
2153 case S_IFLNK:
2154 if (strbuf_readlink(buf, path, st->st_size) < 0)
2155 return error(_("unable to read symlink %s"), path);
2156 return 0;
2157 case S_IFREG:
2158 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
2159 return error(_("unable to open or read %s"), path);
2160 convert_to_git(path, buf->buf, buf->len, buf, 0);
2161 return 0;
2162 default:
2163 return -1;
2168 * Update the preimage, and the common lines in postimage,
2169 * from buffer buf of length len. If postlen is 0 the postimage
2170 * is updated in place, otherwise it's updated on a new buffer
2171 * of length postlen
2174 static void update_pre_post_images(struct image *preimage,
2175 struct image *postimage,
2176 char *buf,
2177 size_t len, size_t postlen)
2179 int i, ctx, reduced;
2180 char *new, *old, *fixed;
2181 struct image fixed_preimage;
2184 * Update the preimage with whitespace fixes. Note that we
2185 * are not losing preimage->buf -- apply_one_fragment() will
2186 * free "oldlines".
2188 prepare_image(&fixed_preimage, buf, len, 1);
2189 assert(postlen
2190 ? fixed_preimage.nr == preimage->nr
2191 : fixed_preimage.nr <= preimage->nr);
2192 for (i = 0; i < fixed_preimage.nr; i++)
2193 fixed_preimage.line[i].flag = preimage->line[i].flag;
2194 free(preimage->line_allocated);
2195 *preimage = fixed_preimage;
2198 * Adjust the common context lines in postimage. This can be
2199 * done in-place when we are shrinking it with whitespace
2200 * fixing, but needs a new buffer when ignoring whitespace or
2201 * expanding leading tabs to spaces.
2203 * We trust the caller to tell us if the update can be done
2204 * in place (postlen==0) or not.
2206 old = postimage->buf;
2207 if (postlen)
2208 new = postimage->buf = xmalloc(postlen);
2209 else
2210 new = old;
2211 fixed = preimage->buf;
2213 for (i = reduced = ctx = 0; i < postimage->nr; i++) {
2214 size_t l_len = postimage->line[i].len;
2215 if (!(postimage->line[i].flag & LINE_COMMON)) {
2216 /* an added line -- no counterparts in preimage */
2217 memmove(new, old, l_len);
2218 old += l_len;
2219 new += l_len;
2220 continue;
2223 /* a common context -- skip it in the original postimage */
2224 old += l_len;
2226 /* and find the corresponding one in the fixed preimage */
2227 while (ctx < preimage->nr &&
2228 !(preimage->line[ctx].flag & LINE_COMMON)) {
2229 fixed += preimage->line[ctx].len;
2230 ctx++;
2234 * preimage is expected to run out, if the caller
2235 * fixed addition of trailing blank lines.
2237 if (preimage->nr <= ctx) {
2238 reduced++;
2239 continue;
2242 /* and copy it in, while fixing the line length */
2243 l_len = preimage->line[ctx].len;
2244 memcpy(new, fixed, l_len);
2245 new += l_len;
2246 fixed += l_len;
2247 postimage->line[i].len = l_len;
2248 ctx++;
2251 if (postlen
2252 ? postlen < new - postimage->buf
2253 : postimage->len < new - postimage->buf)
2254 die("BUG: caller miscounted postlen: asked %d, orig = %d, used = %d",
2255 (int)postlen, (int) postimage->len, (int)(new - postimage->buf));
2257 /* Fix the length of the whole thing */
2258 postimage->len = new - postimage->buf;
2259 postimage->nr -= reduced;
2262 static int line_by_line_fuzzy_match(struct image *img,
2263 struct image *preimage,
2264 struct image *postimage,
2265 unsigned long try,
2266 int try_lno,
2267 int preimage_limit)
2269 int i;
2270 size_t imgoff = 0;
2271 size_t preoff = 0;
2272 size_t postlen = postimage->len;
2273 size_t extra_chars;
2274 char *buf;
2275 char *preimage_eof;
2276 char *preimage_end;
2277 struct strbuf fixed;
2278 char *fixed_buf;
2279 size_t fixed_len;
2281 for (i = 0; i < preimage_limit; i++) {
2282 size_t prelen = preimage->line[i].len;
2283 size_t imglen = img->line[try_lno+i].len;
2285 if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,
2286 preimage->buf + preoff, prelen))
2287 return 0;
2288 if (preimage->line[i].flag & LINE_COMMON)
2289 postlen += imglen - prelen;
2290 imgoff += imglen;
2291 preoff += prelen;
2295 * Ok, the preimage matches with whitespace fuzz.
2297 * imgoff now holds the true length of the target that
2298 * matches the preimage before the end of the file.
2300 * Count the number of characters in the preimage that fall
2301 * beyond the end of the file and make sure that all of them
2302 * are whitespace characters. (This can only happen if
2303 * we are removing blank lines at the end of the file.)
2305 buf = preimage_eof = preimage->buf + preoff;
2306 for ( ; i < preimage->nr; i++)
2307 preoff += preimage->line[i].len;
2308 preimage_end = preimage->buf + preoff;
2309 for ( ; buf < preimage_end; buf++)
2310 if (!isspace(*buf))
2311 return 0;
2314 * Update the preimage and the common postimage context
2315 * lines to use the same whitespace as the target.
2316 * If whitespace is missing in the target (i.e.
2317 * if the preimage extends beyond the end of the file),
2318 * use the whitespace from the preimage.
2320 extra_chars = preimage_end - preimage_eof;
2321 strbuf_init(&fixed, imgoff + extra_chars);
2322 strbuf_add(&fixed, img->buf + try, imgoff);
2323 strbuf_add(&fixed, preimage_eof, extra_chars);
2324 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2325 update_pre_post_images(preimage, postimage,
2326 fixed_buf, fixed_len, postlen);
2327 return 1;
2330 static int match_fragment(struct image *img,
2331 struct image *preimage,
2332 struct image *postimage,
2333 unsigned long try,
2334 int try_lno,
2335 unsigned ws_rule,
2336 int match_beginning, int match_end)
2338 int i;
2339 char *fixed_buf, *buf, *orig, *target;
2340 struct strbuf fixed;
2341 size_t fixed_len, postlen;
2342 int preimage_limit;
2344 if (preimage->nr + try_lno <= img->nr) {
2346 * The hunk falls within the boundaries of img.
2348 preimage_limit = preimage->nr;
2349 if (match_end && (preimage->nr + try_lno != img->nr))
2350 return 0;
2351 } else if (ws_error_action == correct_ws_error &&
2352 (ws_rule & WS_BLANK_AT_EOF)) {
2354 * This hunk extends beyond the end of img, and we are
2355 * removing blank lines at the end of the file. This
2356 * many lines from the beginning of the preimage must
2357 * match with img, and the remainder of the preimage
2358 * must be blank.
2360 preimage_limit = img->nr - try_lno;
2361 } else {
2363 * The hunk extends beyond the end of the img and
2364 * we are not removing blanks at the end, so we
2365 * should reject the hunk at this position.
2367 return 0;
2370 if (match_beginning && try_lno)
2371 return 0;
2373 /* Quick hash check */
2374 for (i = 0; i < preimage_limit; i++)
2375 if ((img->line[try_lno + i].flag & LINE_PATCHED) ||
2376 (preimage->line[i].hash != img->line[try_lno + i].hash))
2377 return 0;
2379 if (preimage_limit == preimage->nr) {
2381 * Do we have an exact match? If we were told to match
2382 * at the end, size must be exactly at try+fragsize,
2383 * otherwise try+fragsize must be still within the preimage,
2384 * and either case, the old piece should match the preimage
2385 * exactly.
2387 if ((match_end
2388 ? (try + preimage->len == img->len)
2389 : (try + preimage->len <= img->len)) &&
2390 !memcmp(img->buf + try, preimage->buf, preimage->len))
2391 return 1;
2392 } else {
2394 * The preimage extends beyond the end of img, so
2395 * there cannot be an exact match.
2397 * There must be one non-blank context line that match
2398 * a line before the end of img.
2400 char *buf_end;
2402 buf = preimage->buf;
2403 buf_end = buf;
2404 for (i = 0; i < preimage_limit; i++)
2405 buf_end += preimage->line[i].len;
2407 for ( ; buf < buf_end; buf++)
2408 if (!isspace(*buf))
2409 break;
2410 if (buf == buf_end)
2411 return 0;
2415 * No exact match. If we are ignoring whitespace, run a line-by-line
2416 * fuzzy matching. We collect all the line length information because
2417 * we need it to adjust whitespace if we match.
2419 if (ws_ignore_action == ignore_ws_change)
2420 return line_by_line_fuzzy_match(img, preimage, postimage,
2421 try, try_lno, preimage_limit);
2423 if (ws_error_action != correct_ws_error)
2424 return 0;
2427 * The hunk does not apply byte-by-byte, but the hash says
2428 * it might with whitespace fuzz. We weren't asked to
2429 * ignore whitespace, we were asked to correct whitespace
2430 * errors, so let's try matching after whitespace correction.
2432 * While checking the preimage against the target, whitespace
2433 * errors in both fixed, we count how large the corresponding
2434 * postimage needs to be. The postimage prepared by
2435 * apply_one_fragment() has whitespace errors fixed on added
2436 * lines already, but the common lines were propagated as-is,
2437 * which may become longer when their whitespace errors are
2438 * fixed.
2441 /* First count added lines in postimage */
2442 postlen = 0;
2443 for (i = 0; i < postimage->nr; i++) {
2444 if (!(postimage->line[i].flag & LINE_COMMON))
2445 postlen += postimage->line[i].len;
2449 * The preimage may extend beyond the end of the file,
2450 * but in this loop we will only handle the part of the
2451 * preimage that falls within the file.
2453 strbuf_init(&fixed, preimage->len + 1);
2454 orig = preimage->buf;
2455 target = img->buf + try;
2456 for (i = 0; i < preimage_limit; i++) {
2457 size_t oldlen = preimage->line[i].len;
2458 size_t tgtlen = img->line[try_lno + i].len;
2459 size_t fixstart = fixed.len;
2460 struct strbuf tgtfix;
2461 int match;
2463 /* Try fixing the line in the preimage */
2464 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2466 /* Try fixing the line in the target */
2467 strbuf_init(&tgtfix, tgtlen);
2468 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2471 * If they match, either the preimage was based on
2472 * a version before our tree fixed whitespace breakage,
2473 * or we are lacking a whitespace-fix patch the tree
2474 * the preimage was based on already had (i.e. target
2475 * has whitespace breakage, the preimage doesn't).
2476 * In either case, we are fixing the whitespace breakages
2477 * so we might as well take the fix together with their
2478 * real change.
2480 match = (tgtfix.len == fixed.len - fixstart &&
2481 !memcmp(tgtfix.buf, fixed.buf + fixstart,
2482 fixed.len - fixstart));
2484 /* Add the length if this is common with the postimage */
2485 if (preimage->line[i].flag & LINE_COMMON)
2486 postlen += tgtfix.len;
2488 strbuf_release(&tgtfix);
2489 if (!match)
2490 goto unmatch_exit;
2492 orig += oldlen;
2493 target += tgtlen;
2498 * Now handle the lines in the preimage that falls beyond the
2499 * end of the file (if any). They will only match if they are
2500 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2501 * false).
2503 for ( ; i < preimage->nr; i++) {
2504 size_t fixstart = fixed.len; /* start of the fixed preimage */
2505 size_t oldlen = preimage->line[i].len;
2506 int j;
2508 /* Try fixing the line in the preimage */
2509 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2511 for (j = fixstart; j < fixed.len; j++)
2512 if (!isspace(fixed.buf[j]))
2513 goto unmatch_exit;
2515 orig += oldlen;
2519 * Yes, the preimage is based on an older version that still
2520 * has whitespace breakages unfixed, and fixing them makes the
2521 * hunk match. Update the context lines in the postimage.
2523 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2524 if (postlen < postimage->len)
2525 postlen = 0;
2526 update_pre_post_images(preimage, postimage,
2527 fixed_buf, fixed_len, postlen);
2528 return 1;
2530 unmatch_exit:
2531 strbuf_release(&fixed);
2532 return 0;
2535 static int find_pos(struct image *img,
2536 struct image *preimage,
2537 struct image *postimage,
2538 int line,
2539 unsigned ws_rule,
2540 int match_beginning, int match_end)
2542 int i;
2543 unsigned long backwards, forwards, try;
2544 int backwards_lno, forwards_lno, try_lno;
2547 * If match_beginning or match_end is specified, there is no
2548 * point starting from a wrong line that will never match and
2549 * wander around and wait for a match at the specified end.
2551 if (match_beginning)
2552 line = 0;
2553 else if (match_end)
2554 line = img->nr - preimage->nr;
2557 * Because the comparison is unsigned, the following test
2558 * will also take care of a negative line number that can
2559 * result when match_end and preimage is larger than the target.
2561 if ((size_t) line > img->nr)
2562 line = img->nr;
2564 try = 0;
2565 for (i = 0; i < line; i++)
2566 try += img->line[i].len;
2569 * There's probably some smart way to do this, but I'll leave
2570 * that to the smart and beautiful people. I'm simple and stupid.
2572 backwards = try;
2573 backwards_lno = line;
2574 forwards = try;
2575 forwards_lno = line;
2576 try_lno = line;
2578 for (i = 0; ; i++) {
2579 if (match_fragment(img, preimage, postimage,
2580 try, try_lno, ws_rule,
2581 match_beginning, match_end))
2582 return try_lno;
2584 again:
2585 if (backwards_lno == 0 && forwards_lno == img->nr)
2586 break;
2588 if (i & 1) {
2589 if (backwards_lno == 0) {
2590 i++;
2591 goto again;
2593 backwards_lno--;
2594 backwards -= img->line[backwards_lno].len;
2595 try = backwards;
2596 try_lno = backwards_lno;
2597 } else {
2598 if (forwards_lno == img->nr) {
2599 i++;
2600 goto again;
2602 forwards += img->line[forwards_lno].len;
2603 forwards_lno++;
2604 try = forwards;
2605 try_lno = forwards_lno;
2609 return -1;
2612 static void remove_first_line(struct image *img)
2614 img->buf += img->line[0].len;
2615 img->len -= img->line[0].len;
2616 img->line++;
2617 img->nr--;
2620 static void remove_last_line(struct image *img)
2622 img->len -= img->line[--img->nr].len;
2626 * The change from "preimage" and "postimage" has been found to
2627 * apply at applied_pos (counts in line numbers) in "img".
2628 * Update "img" to remove "preimage" and replace it with "postimage".
2630 static void update_image(struct image *img,
2631 int applied_pos,
2632 struct image *preimage,
2633 struct image *postimage)
2636 * remove the copy of preimage at offset in img
2637 * and replace it with postimage
2639 int i, nr;
2640 size_t remove_count, insert_count, applied_at = 0;
2641 char *result;
2642 int preimage_limit;
2645 * If we are removing blank lines at the end of img,
2646 * the preimage may extend beyond the end.
2647 * If that is the case, we must be careful only to
2648 * remove the part of the preimage that falls within
2649 * the boundaries of img. Initialize preimage_limit
2650 * to the number of lines in the preimage that falls
2651 * within the boundaries.
2653 preimage_limit = preimage->nr;
2654 if (preimage_limit > img->nr - applied_pos)
2655 preimage_limit = img->nr - applied_pos;
2657 for (i = 0; i < applied_pos; i++)
2658 applied_at += img->line[i].len;
2660 remove_count = 0;
2661 for (i = 0; i < preimage_limit; i++)
2662 remove_count += img->line[applied_pos + i].len;
2663 insert_count = postimage->len;
2665 /* Adjust the contents */
2666 result = xmalloc(st_add3(st_sub(img->len, remove_count), insert_count, 1));
2667 memcpy(result, img->buf, applied_at);
2668 memcpy(result + applied_at, postimage->buf, postimage->len);
2669 memcpy(result + applied_at + postimage->len,
2670 img->buf + (applied_at + remove_count),
2671 img->len - (applied_at + remove_count));
2672 free(img->buf);
2673 img->buf = result;
2674 img->len += insert_count - remove_count;
2675 result[img->len] = '\0';
2677 /* Adjust the line table */
2678 nr = img->nr + postimage->nr - preimage_limit;
2679 if (preimage_limit < postimage->nr) {
2681 * NOTE: this knows that we never call remove_first_line()
2682 * on anything other than pre/post image.
2684 REALLOC_ARRAY(img->line, nr);
2685 img->line_allocated = img->line;
2687 if (preimage_limit != postimage->nr)
2688 memmove(img->line + applied_pos + postimage->nr,
2689 img->line + applied_pos + preimage_limit,
2690 (img->nr - (applied_pos + preimage_limit)) *
2691 sizeof(*img->line));
2692 memcpy(img->line + applied_pos,
2693 postimage->line,
2694 postimage->nr * sizeof(*img->line));
2695 if (!allow_overlap)
2696 for (i = 0; i < postimage->nr; i++)
2697 img->line[applied_pos + i].flag |= LINE_PATCHED;
2698 img->nr = nr;
2702 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2703 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2704 * replace the part of "img" with "postimage" text.
2706 static int apply_one_fragment(struct apply_state *state,
2707 struct image *img, struct fragment *frag,
2708 int inaccurate_eof, unsigned ws_rule,
2709 int nth_fragment)
2711 int match_beginning, match_end;
2712 const char *patch = frag->patch;
2713 int size = frag->size;
2714 char *old, *oldlines;
2715 struct strbuf newlines;
2716 int new_blank_lines_at_end = 0;
2717 int found_new_blank_lines_at_end = 0;
2718 int hunk_linenr = frag->linenr;
2719 unsigned long leading, trailing;
2720 int pos, applied_pos;
2721 struct image preimage;
2722 struct image postimage;
2724 memset(&preimage, 0, sizeof(preimage));
2725 memset(&postimage, 0, sizeof(postimage));
2726 oldlines = xmalloc(size);
2727 strbuf_init(&newlines, size);
2729 old = oldlines;
2730 while (size > 0) {
2731 char first;
2732 int len = linelen(patch, size);
2733 int plen;
2734 int added_blank_line = 0;
2735 int is_blank_context = 0;
2736 size_t start;
2738 if (!len)
2739 break;
2742 * "plen" is how much of the line we should use for
2743 * the actual patch data. Normally we just remove the
2744 * first character on the line, but if the line is
2745 * followed by "\ No newline", then we also remove the
2746 * last one (which is the newline, of course).
2748 plen = len - 1;
2749 if (len < size && patch[len] == '\\')
2750 plen--;
2751 first = *patch;
2752 if (state->apply_in_reverse) {
2753 if (first == '-')
2754 first = '+';
2755 else if (first == '+')
2756 first = '-';
2759 switch (first) {
2760 case '\n':
2761 /* Newer GNU diff, empty context line */
2762 if (plen < 0)
2763 /* ... followed by '\No newline'; nothing */
2764 break;
2765 *old++ = '\n';
2766 strbuf_addch(&newlines, '\n');
2767 add_line_info(&preimage, "\n", 1, LINE_COMMON);
2768 add_line_info(&postimage, "\n", 1, LINE_COMMON);
2769 is_blank_context = 1;
2770 break;
2771 case ' ':
2772 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2773 ws_blank_line(patch + 1, plen, ws_rule))
2774 is_blank_context = 1;
2775 case '-':
2776 memcpy(old, patch + 1, plen);
2777 add_line_info(&preimage, old, plen,
2778 (first == ' ' ? LINE_COMMON : 0));
2779 old += plen;
2780 if (first == '-')
2781 break;
2782 /* Fall-through for ' ' */
2783 case '+':
2784 /* --no-add does not add new lines */
2785 if (first == '+' && no_add)
2786 break;
2788 start = newlines.len;
2789 if (first != '+' ||
2790 !whitespace_error ||
2791 ws_error_action != correct_ws_error) {
2792 strbuf_add(&newlines, patch + 1, plen);
2794 else {
2795 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &applied_after_fixing_ws);
2797 add_line_info(&postimage, newlines.buf + start, newlines.len - start,
2798 (first == '+' ? 0 : LINE_COMMON));
2799 if (first == '+' &&
2800 (ws_rule & WS_BLANK_AT_EOF) &&
2801 ws_blank_line(patch + 1, plen, ws_rule))
2802 added_blank_line = 1;
2803 break;
2804 case '@': case '\\':
2805 /* Ignore it, we already handled it */
2806 break;
2807 default:
2808 if (apply_verbosely)
2809 error(_("invalid start of line: '%c'"), first);
2810 applied_pos = -1;
2811 goto out;
2813 if (added_blank_line) {
2814 if (!new_blank_lines_at_end)
2815 found_new_blank_lines_at_end = hunk_linenr;
2816 new_blank_lines_at_end++;
2818 else if (is_blank_context)
2820 else
2821 new_blank_lines_at_end = 0;
2822 patch += len;
2823 size -= len;
2824 hunk_linenr++;
2826 if (inaccurate_eof &&
2827 old > oldlines && old[-1] == '\n' &&
2828 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
2829 old--;
2830 strbuf_setlen(&newlines, newlines.len - 1);
2833 leading = frag->leading;
2834 trailing = frag->trailing;
2837 * A hunk to change lines at the beginning would begin with
2838 * @@ -1,L +N,M @@
2839 * but we need to be careful. -U0 that inserts before the second
2840 * line also has this pattern.
2842 * And a hunk to add to an empty file would begin with
2843 * @@ -0,0 +N,M @@
2845 * In other words, a hunk that is (frag->oldpos <= 1) with or
2846 * without leading context must match at the beginning.
2848 match_beginning = (!frag->oldpos ||
2849 (frag->oldpos == 1 && !state->unidiff_zero));
2852 * A hunk without trailing lines must match at the end.
2853 * However, we simply cannot tell if a hunk must match end
2854 * from the lack of trailing lines if the patch was generated
2855 * with unidiff without any context.
2857 match_end = !state->unidiff_zero && !trailing;
2859 pos = frag->newpos ? (frag->newpos - 1) : 0;
2860 preimage.buf = oldlines;
2861 preimage.len = old - oldlines;
2862 postimage.buf = newlines.buf;
2863 postimage.len = newlines.len;
2864 preimage.line = preimage.line_allocated;
2865 postimage.line = postimage.line_allocated;
2867 for (;;) {
2869 applied_pos = find_pos(img, &preimage, &postimage, pos,
2870 ws_rule, match_beginning, match_end);
2872 if (applied_pos >= 0)
2873 break;
2875 /* Am I at my context limits? */
2876 if ((leading <= p_context) && (trailing <= p_context))
2877 break;
2878 if (match_beginning || match_end) {
2879 match_beginning = match_end = 0;
2880 continue;
2884 * Reduce the number of context lines; reduce both
2885 * leading and trailing if they are equal otherwise
2886 * just reduce the larger context.
2888 if (leading >= trailing) {
2889 remove_first_line(&preimage);
2890 remove_first_line(&postimage);
2891 pos--;
2892 leading--;
2894 if (trailing > leading) {
2895 remove_last_line(&preimage);
2896 remove_last_line(&postimage);
2897 trailing--;
2901 if (applied_pos >= 0) {
2902 if (new_blank_lines_at_end &&
2903 preimage.nr + applied_pos >= img->nr &&
2904 (ws_rule & WS_BLANK_AT_EOF) &&
2905 ws_error_action != nowarn_ws_error) {
2906 record_ws_error(WS_BLANK_AT_EOF, "+", 1,
2907 found_new_blank_lines_at_end);
2908 if (ws_error_action == correct_ws_error) {
2909 while (new_blank_lines_at_end--)
2910 remove_last_line(&postimage);
2913 * We would want to prevent write_out_results()
2914 * from taking place in apply_patch() that follows
2915 * the callchain led us here, which is:
2916 * apply_patch->check_patch_list->check_patch->
2917 * apply_data->apply_fragments->apply_one_fragment
2919 if (ws_error_action == die_on_ws_error)
2920 apply = 0;
2923 if (apply_verbosely && applied_pos != pos) {
2924 int offset = applied_pos - pos;
2925 if (state->apply_in_reverse)
2926 offset = 0 - offset;
2927 fprintf_ln(stderr,
2928 Q_("Hunk #%d succeeded at %d (offset %d line).",
2929 "Hunk #%d succeeded at %d (offset %d lines).",
2930 offset),
2931 nth_fragment, applied_pos + 1, offset);
2935 * Warn if it was necessary to reduce the number
2936 * of context lines.
2938 if ((leading != frag->leading) ||
2939 (trailing != frag->trailing))
2940 fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"
2941 " to apply fragment at %d"),
2942 leading, trailing, applied_pos+1);
2943 update_image(img, applied_pos, &preimage, &postimage);
2944 } else {
2945 if (apply_verbosely)
2946 error(_("while searching for:\n%.*s"),
2947 (int)(old - oldlines), oldlines);
2950 out:
2951 free(oldlines);
2952 strbuf_release(&newlines);
2953 free(preimage.line_allocated);
2954 free(postimage.line_allocated);
2956 return (applied_pos < 0);
2959 static int apply_binary_fragment(struct apply_state *state,
2960 struct image *img,
2961 struct patch *patch)
2963 struct fragment *fragment = patch->fragments;
2964 unsigned long len;
2965 void *dst;
2967 if (!fragment)
2968 return error(_("missing binary patch data for '%s'"),
2969 patch->new_name ?
2970 patch->new_name :
2971 patch->old_name);
2973 /* Binary patch is irreversible without the optional second hunk */
2974 if (state->apply_in_reverse) {
2975 if (!fragment->next)
2976 return error("cannot reverse-apply a binary patch "
2977 "without the reverse hunk to '%s'",
2978 patch->new_name
2979 ? patch->new_name : patch->old_name);
2980 fragment = fragment->next;
2982 switch (fragment->binary_patch_method) {
2983 case BINARY_DELTA_DEFLATED:
2984 dst = patch_delta(img->buf, img->len, fragment->patch,
2985 fragment->size, &len);
2986 if (!dst)
2987 return -1;
2988 clear_image(img);
2989 img->buf = dst;
2990 img->len = len;
2991 return 0;
2992 case BINARY_LITERAL_DEFLATED:
2993 clear_image(img);
2994 img->len = fragment->size;
2995 img->buf = xmemdupz(fragment->patch, img->len);
2996 return 0;
2998 return -1;
3002 * Replace "img" with the result of applying the binary patch.
3003 * The binary patch data itself in patch->fragment is still kept
3004 * but the preimage prepared by the caller in "img" is freed here
3005 * or in the helper function apply_binary_fragment() this calls.
3007 static int apply_binary(struct apply_state *state,
3008 struct image *img,
3009 struct patch *patch)
3011 const char *name = patch->old_name ? patch->old_name : patch->new_name;
3012 unsigned char sha1[20];
3015 * For safety, we require patch index line to contain
3016 * full 40-byte textual SHA1 for old and new, at least for now.
3018 if (strlen(patch->old_sha1_prefix) != 40 ||
3019 strlen(patch->new_sha1_prefix) != 40 ||
3020 get_sha1_hex(patch->old_sha1_prefix, sha1) ||
3021 get_sha1_hex(patch->new_sha1_prefix, sha1))
3022 return error("cannot apply binary patch to '%s' "
3023 "without full index line", name);
3025 if (patch->old_name) {
3027 * See if the old one matches what the patch
3028 * applies to.
3030 hash_sha1_file(img->buf, img->len, blob_type, sha1);
3031 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
3032 return error("the patch applies to '%s' (%s), "
3033 "which does not match the "
3034 "current contents.",
3035 name, sha1_to_hex(sha1));
3037 else {
3038 /* Otherwise, the old one must be empty. */
3039 if (img->len)
3040 return error("the patch applies to an empty "
3041 "'%s' but it is not empty", name);
3044 get_sha1_hex(patch->new_sha1_prefix, sha1);
3045 if (is_null_sha1(sha1)) {
3046 clear_image(img);
3047 return 0; /* deletion patch */
3050 if (has_sha1_file(sha1)) {
3051 /* We already have the postimage */
3052 enum object_type type;
3053 unsigned long size;
3054 char *result;
3056 result = read_sha1_file(sha1, &type, &size);
3057 if (!result)
3058 return error("the necessary postimage %s for "
3059 "'%s' cannot be read",
3060 patch->new_sha1_prefix, name);
3061 clear_image(img);
3062 img->buf = result;
3063 img->len = size;
3064 } else {
3066 * We have verified buf matches the preimage;
3067 * apply the patch data to it, which is stored
3068 * in the patch->fragments->{patch,size}.
3070 if (apply_binary_fragment(state, img, patch))
3071 return error(_("binary patch does not apply to '%s'"),
3072 name);
3074 /* verify that the result matches */
3075 hash_sha1_file(img->buf, img->len, blob_type, sha1);
3076 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
3077 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3078 name, patch->new_sha1_prefix, sha1_to_hex(sha1));
3081 return 0;
3084 static int apply_fragments(struct apply_state *state, struct image *img, struct patch *patch)
3086 struct fragment *frag = patch->fragments;
3087 const char *name = patch->old_name ? patch->old_name : patch->new_name;
3088 unsigned ws_rule = patch->ws_rule;
3089 unsigned inaccurate_eof = patch->inaccurate_eof;
3090 int nth = 0;
3092 if (patch->is_binary)
3093 return apply_binary(state, img, patch);
3095 while (frag) {
3096 nth++;
3097 if (apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {
3098 error(_("patch failed: %s:%ld"), name, frag->oldpos);
3099 if (!apply_with_reject)
3100 return -1;
3101 frag->rejected = 1;
3103 frag = frag->next;
3105 return 0;
3108 static int read_blob_object(struct strbuf *buf, const unsigned char *sha1, unsigned mode)
3110 if (S_ISGITLINK(mode)) {
3111 strbuf_grow(buf, 100);
3112 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(sha1));
3113 } else {
3114 enum object_type type;
3115 unsigned long sz;
3116 char *result;
3118 result = read_sha1_file(sha1, &type, &sz);
3119 if (!result)
3120 return -1;
3121 /* XXX read_sha1_file NUL-terminates */
3122 strbuf_attach(buf, result, sz, sz + 1);
3124 return 0;
3127 static int read_file_or_gitlink(const struct cache_entry *ce, struct strbuf *buf)
3129 if (!ce)
3130 return 0;
3131 return read_blob_object(buf, ce->sha1, ce->ce_mode);
3134 static struct patch *in_fn_table(const char *name)
3136 struct string_list_item *item;
3138 if (name == NULL)
3139 return NULL;
3141 item = string_list_lookup(&fn_table, name);
3142 if (item != NULL)
3143 return (struct patch *)item->util;
3145 return NULL;
3149 * item->util in the filename table records the status of the path.
3150 * Usually it points at a patch (whose result records the contents
3151 * of it after applying it), but it could be PATH_WAS_DELETED for a
3152 * path that a previously applied patch has already removed, or
3153 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3155 * The latter is needed to deal with a case where two paths A and B
3156 * are swapped by first renaming A to B and then renaming B to A;
3157 * moving A to B should not be prevented due to presence of B as we
3158 * will remove it in a later patch.
3160 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3161 #define PATH_WAS_DELETED ((struct patch *) -1)
3163 static int to_be_deleted(struct patch *patch)
3165 return patch == PATH_TO_BE_DELETED;
3168 static int was_deleted(struct patch *patch)
3170 return patch == PATH_WAS_DELETED;
3173 static void add_to_fn_table(struct patch *patch)
3175 struct string_list_item *item;
3178 * Always add new_name unless patch is a deletion
3179 * This should cover the cases for normal diffs,
3180 * file creations and copies
3182 if (patch->new_name != NULL) {
3183 item = string_list_insert(&fn_table, patch->new_name);
3184 item->util = patch;
3188 * store a failure on rename/deletion cases because
3189 * later chunks shouldn't patch old names
3191 if ((patch->new_name == NULL) || (patch->is_rename)) {
3192 item = string_list_insert(&fn_table, patch->old_name);
3193 item->util = PATH_WAS_DELETED;
3197 static void prepare_fn_table(struct patch *patch)
3200 * store information about incoming file deletion
3202 while (patch) {
3203 if ((patch->new_name == NULL) || (patch->is_rename)) {
3204 struct string_list_item *item;
3205 item = string_list_insert(&fn_table, patch->old_name);
3206 item->util = PATH_TO_BE_DELETED;
3208 patch = patch->next;
3212 static int checkout_target(struct index_state *istate,
3213 struct cache_entry *ce, struct stat *st)
3215 struct checkout costate;
3217 memset(&costate, 0, sizeof(costate));
3218 costate.base_dir = "";
3219 costate.refresh_cache = 1;
3220 costate.istate = istate;
3221 if (checkout_entry(ce, &costate, NULL) || lstat(ce->name, st))
3222 return error(_("cannot checkout %s"), ce->name);
3223 return 0;
3226 static struct patch *previous_patch(struct patch *patch, int *gone)
3228 struct patch *previous;
3230 *gone = 0;
3231 if (patch->is_copy || patch->is_rename)
3232 return NULL; /* "git" patches do not depend on the order */
3234 previous = in_fn_table(patch->old_name);
3235 if (!previous)
3236 return NULL;
3238 if (to_be_deleted(previous))
3239 return NULL; /* the deletion hasn't happened yet */
3241 if (was_deleted(previous))
3242 *gone = 1;
3244 return previous;
3247 static int verify_index_match(const struct cache_entry *ce, struct stat *st)
3249 if (S_ISGITLINK(ce->ce_mode)) {
3250 if (!S_ISDIR(st->st_mode))
3251 return -1;
3252 return 0;
3254 return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
3257 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3259 static int load_patch_target(struct apply_state *state,
3260 struct strbuf *buf,
3261 const struct cache_entry *ce,
3262 struct stat *st,
3263 const char *name,
3264 unsigned expected_mode)
3266 if (cached || state->check_index) {
3267 if (read_file_or_gitlink(ce, buf))
3268 return error(_("read of %s failed"), name);
3269 } else if (name) {
3270 if (S_ISGITLINK(expected_mode)) {
3271 if (ce)
3272 return read_file_or_gitlink(ce, buf);
3273 else
3274 return SUBMODULE_PATCH_WITHOUT_INDEX;
3275 } else if (has_symlink_leading_path(name, strlen(name))) {
3276 return error(_("reading from '%s' beyond a symbolic link"), name);
3277 } else {
3278 if (read_old_data(st, name, buf))
3279 return error(_("read of %s failed"), name);
3282 return 0;
3286 * We are about to apply "patch"; populate the "image" with the
3287 * current version we have, from the working tree or from the index,
3288 * depending on the situation e.g. --cached/--index. If we are
3289 * applying a non-git patch that incrementally updates the tree,
3290 * we read from the result of a previous diff.
3292 static int load_preimage(struct apply_state *state,
3293 struct image *image,
3294 struct patch *patch, struct stat *st,
3295 const struct cache_entry *ce)
3297 struct strbuf buf = STRBUF_INIT;
3298 size_t len;
3299 char *img;
3300 struct patch *previous;
3301 int status;
3303 previous = previous_patch(patch, &status);
3304 if (status)
3305 return error(_("path %s has been renamed/deleted"),
3306 patch->old_name);
3307 if (previous) {
3308 /* We have a patched copy in memory; use that. */
3309 strbuf_add(&buf, previous->result, previous->resultsize);
3310 } else {
3311 status = load_patch_target(state, &buf, ce, st,
3312 patch->old_name, patch->old_mode);
3313 if (status < 0)
3314 return status;
3315 else if (status == SUBMODULE_PATCH_WITHOUT_INDEX) {
3317 * There is no way to apply subproject
3318 * patch without looking at the index.
3319 * NEEDSWORK: shouldn't this be flagged
3320 * as an error???
3322 free_fragment_list(patch->fragments);
3323 patch->fragments = NULL;
3324 } else if (status) {
3325 return error(_("read of %s failed"), patch->old_name);
3329 img = strbuf_detach(&buf, &len);
3330 prepare_image(image, img, len, !patch->is_binary);
3331 return 0;
3334 static int three_way_merge(struct image *image,
3335 char *path,
3336 const unsigned char *base,
3337 const unsigned char *ours,
3338 const unsigned char *theirs)
3340 mmfile_t base_file, our_file, their_file;
3341 mmbuffer_t result = { NULL };
3342 int status;
3344 read_mmblob(&base_file, base);
3345 read_mmblob(&our_file, ours);
3346 read_mmblob(&their_file, theirs);
3347 status = ll_merge(&result, path,
3348 &base_file, "base",
3349 &our_file, "ours",
3350 &their_file, "theirs", NULL);
3351 free(base_file.ptr);
3352 free(our_file.ptr);
3353 free(their_file.ptr);
3354 if (status < 0 || !result.ptr) {
3355 free(result.ptr);
3356 return -1;
3358 clear_image(image);
3359 image->buf = result.ptr;
3360 image->len = result.size;
3362 return status;
3366 * When directly falling back to add/add three-way merge, we read from
3367 * the current contents of the new_name. In no cases other than that
3368 * this function will be called.
3370 static int load_current(struct apply_state *state,
3371 struct image *image,
3372 struct patch *patch)
3374 struct strbuf buf = STRBUF_INIT;
3375 int status, pos;
3376 size_t len;
3377 char *img;
3378 struct stat st;
3379 struct cache_entry *ce;
3380 char *name = patch->new_name;
3381 unsigned mode = patch->new_mode;
3383 if (!patch->is_new)
3384 die("BUG: patch to %s is not a creation", patch->old_name);
3386 pos = cache_name_pos(name, strlen(name));
3387 if (pos < 0)
3388 return error(_("%s: does not exist in index"), name);
3389 ce = active_cache[pos];
3390 if (lstat(name, &st)) {
3391 if (errno != ENOENT)
3392 return error(_("%s: %s"), name, strerror(errno));
3393 if (checkout_target(&the_index, ce, &st))
3394 return -1;
3396 if (verify_index_match(ce, &st))
3397 return error(_("%s: does not match index"), name);
3399 status = load_patch_target(state, &buf, ce, &st, name, mode);
3400 if (status < 0)
3401 return status;
3402 else if (status)
3403 return -1;
3404 img = strbuf_detach(&buf, &len);
3405 prepare_image(image, img, len, !patch->is_binary);
3406 return 0;
3409 static int try_threeway(struct apply_state *state,
3410 struct image *image,
3411 struct patch *patch,
3412 struct stat *st,
3413 const struct cache_entry *ce)
3415 unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];
3416 struct strbuf buf = STRBUF_INIT;
3417 size_t len;
3418 int status;
3419 char *img;
3420 struct image tmp_image;
3422 /* No point falling back to 3-way merge in these cases */
3423 if (patch->is_delete ||
3424 S_ISGITLINK(patch->old_mode) || S_ISGITLINK(patch->new_mode))
3425 return -1;
3427 /* Preimage the patch was prepared for */
3428 if (patch->is_new)
3429 write_sha1_file("", 0, blob_type, pre_sha1);
3430 else if (get_sha1(patch->old_sha1_prefix, pre_sha1) ||
3431 read_blob_object(&buf, pre_sha1, patch->old_mode))
3432 return error("repository lacks the necessary blob to fall back on 3-way merge.");
3434 fprintf(stderr, "Falling back to three-way merge...\n");
3436 img = strbuf_detach(&buf, &len);
3437 prepare_image(&tmp_image, img, len, 1);
3438 /* Apply the patch to get the post image */
3439 if (apply_fragments(state, &tmp_image, patch) < 0) {
3440 clear_image(&tmp_image);
3441 return -1;
3443 /* post_sha1[] is theirs */
3444 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);
3445 clear_image(&tmp_image);
3447 /* our_sha1[] is ours */
3448 if (patch->is_new) {
3449 if (load_current(state, &tmp_image, patch))
3450 return error("cannot read the current contents of '%s'",
3451 patch->new_name);
3452 } else {
3453 if (load_preimage(state, &tmp_image, patch, st, ce))
3454 return error("cannot read the current contents of '%s'",
3455 patch->old_name);
3457 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);
3458 clear_image(&tmp_image);
3460 /* in-core three-way merge between post and our using pre as base */
3461 status = three_way_merge(image, patch->new_name,
3462 pre_sha1, our_sha1, post_sha1);
3463 if (status < 0) {
3464 fprintf(stderr, "Failed to fall back on three-way merge...\n");
3465 return status;
3468 if (status) {
3469 patch->conflicted_threeway = 1;
3470 if (patch->is_new)
3471 oidclr(&patch->threeway_stage[0]);
3472 else
3473 hashcpy(patch->threeway_stage[0].hash, pre_sha1);
3474 hashcpy(patch->threeway_stage[1].hash, our_sha1);
3475 hashcpy(patch->threeway_stage[2].hash, post_sha1);
3476 fprintf(stderr, "Applied patch to '%s' with conflicts.\n", patch->new_name);
3477 } else {
3478 fprintf(stderr, "Applied patch to '%s' cleanly.\n", patch->new_name);
3480 return 0;
3483 static int apply_data(struct apply_state *state, struct patch *patch,
3484 struct stat *st, const struct cache_entry *ce)
3486 struct image image;
3488 if (load_preimage(state, &image, patch, st, ce) < 0)
3489 return -1;
3491 if (patch->direct_to_threeway ||
3492 apply_fragments(state, &image, patch) < 0) {
3493 /* Note: with --reject, apply_fragments() returns 0 */
3494 if (!threeway || try_threeway(state, &image, patch, st, ce) < 0)
3495 return -1;
3497 patch->result = image.buf;
3498 patch->resultsize = image.len;
3499 add_to_fn_table(patch);
3500 free(image.line_allocated);
3502 if (0 < patch->is_delete && patch->resultsize)
3503 return error(_("removal patch leaves file contents"));
3505 return 0;
3509 * If "patch" that we are looking at modifies or deletes what we have,
3510 * we would want it not to lose any local modification we have, either
3511 * in the working tree or in the index.
3513 * This also decides if a non-git patch is a creation patch or a
3514 * modification to an existing empty file. We do not check the state
3515 * of the current tree for a creation patch in this function; the caller
3516 * check_patch() separately makes sure (and errors out otherwise) that
3517 * the path the patch creates does not exist in the current tree.
3519 static int check_preimage(struct apply_state *state,
3520 struct patch *patch,
3521 struct cache_entry **ce,
3522 struct stat *st)
3524 const char *old_name = patch->old_name;
3525 struct patch *previous = NULL;
3526 int stat_ret = 0, status;
3527 unsigned st_mode = 0;
3529 if (!old_name)
3530 return 0;
3532 assert(patch->is_new <= 0);
3533 previous = previous_patch(patch, &status);
3535 if (status)
3536 return error(_("path %s has been renamed/deleted"), old_name);
3537 if (previous) {
3538 st_mode = previous->new_mode;
3539 } else if (!cached) {
3540 stat_ret = lstat(old_name, st);
3541 if (stat_ret && errno != ENOENT)
3542 return error(_("%s: %s"), old_name, strerror(errno));
3545 if (state->check_index && !previous) {
3546 int pos = cache_name_pos(old_name, strlen(old_name));
3547 if (pos < 0) {
3548 if (patch->is_new < 0)
3549 goto is_new;
3550 return error(_("%s: does not exist in index"), old_name);
3552 *ce = active_cache[pos];
3553 if (stat_ret < 0) {
3554 if (checkout_target(&the_index, *ce, st))
3555 return -1;
3557 if (!cached && verify_index_match(*ce, st))
3558 return error(_("%s: does not match index"), old_name);
3559 if (cached)
3560 st_mode = (*ce)->ce_mode;
3561 } else if (stat_ret < 0) {
3562 if (patch->is_new < 0)
3563 goto is_new;
3564 return error(_("%s: %s"), old_name, strerror(errno));
3567 if (!cached && !previous)
3568 st_mode = ce_mode_from_stat(*ce, st->st_mode);
3570 if (patch->is_new < 0)
3571 patch->is_new = 0;
3572 if (!patch->old_mode)
3573 patch->old_mode = st_mode;
3574 if ((st_mode ^ patch->old_mode) & S_IFMT)
3575 return error(_("%s: wrong type"), old_name);
3576 if (st_mode != patch->old_mode)
3577 warning(_("%s has type %o, expected %o"),
3578 old_name, st_mode, patch->old_mode);
3579 if (!patch->new_mode && !patch->is_delete)
3580 patch->new_mode = st_mode;
3581 return 0;
3583 is_new:
3584 patch->is_new = 1;
3585 patch->is_delete = 0;
3586 free(patch->old_name);
3587 patch->old_name = NULL;
3588 return 0;
3592 #define EXISTS_IN_INDEX 1
3593 #define EXISTS_IN_WORKTREE 2
3595 static int check_to_create(struct apply_state *state,
3596 const char *new_name,
3597 int ok_if_exists)
3599 struct stat nst;
3601 if (state->check_index &&
3602 cache_name_pos(new_name, strlen(new_name)) >= 0 &&
3603 !ok_if_exists)
3604 return EXISTS_IN_INDEX;
3605 if (cached)
3606 return 0;
3608 if (!lstat(new_name, &nst)) {
3609 if (S_ISDIR(nst.st_mode) || ok_if_exists)
3610 return 0;
3612 * A leading component of new_name might be a symlink
3613 * that is going to be removed with this patch, but
3614 * still pointing at somewhere that has the path.
3615 * In such a case, path "new_name" does not exist as
3616 * far as git is concerned.
3618 if (has_symlink_leading_path(new_name, strlen(new_name)))
3619 return 0;
3621 return EXISTS_IN_WORKTREE;
3622 } else if ((errno != ENOENT) && (errno != ENOTDIR)) {
3623 return error("%s: %s", new_name, strerror(errno));
3625 return 0;
3629 * We need to keep track of how symlinks in the preimage are
3630 * manipulated by the patches. A patch to add a/b/c where a/b
3631 * is a symlink should not be allowed to affect the directory
3632 * the symlink points at, but if the same patch removes a/b,
3633 * it is perfectly fine, as the patch removes a/b to make room
3634 * to create a directory a/b so that a/b/c can be created.
3636 static struct string_list symlink_changes;
3637 #define SYMLINK_GOES_AWAY 01
3638 #define SYMLINK_IN_RESULT 02
3640 static uintptr_t register_symlink_changes(const char *path, uintptr_t what)
3642 struct string_list_item *ent;
3644 ent = string_list_lookup(&symlink_changes, path);
3645 if (!ent) {
3646 ent = string_list_insert(&symlink_changes, path);
3647 ent->util = (void *)0;
3649 ent->util = (void *)(what | ((uintptr_t)ent->util));
3650 return (uintptr_t)ent->util;
3653 static uintptr_t check_symlink_changes(const char *path)
3655 struct string_list_item *ent;
3657 ent = string_list_lookup(&symlink_changes, path);
3658 if (!ent)
3659 return 0;
3660 return (uintptr_t)ent->util;
3663 static void prepare_symlink_changes(struct patch *patch)
3665 for ( ; patch; patch = patch->next) {
3666 if ((patch->old_name && S_ISLNK(patch->old_mode)) &&
3667 (patch->is_rename || patch->is_delete))
3668 /* the symlink at patch->old_name is removed */
3669 register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);
3671 if (patch->new_name && S_ISLNK(patch->new_mode))
3672 /* the symlink at patch->new_name is created or remains */
3673 register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);
3677 static int path_is_beyond_symlink_1(struct apply_state *state, struct strbuf *name)
3679 do {
3680 unsigned int change;
3682 while (--name->len && name->buf[name->len] != '/')
3683 ; /* scan backwards */
3684 if (!name->len)
3685 break;
3686 name->buf[name->len] = '\0';
3687 change = check_symlink_changes(name->buf);
3688 if (change & SYMLINK_IN_RESULT)
3689 return 1;
3690 if (change & SYMLINK_GOES_AWAY)
3692 * This cannot be "return 0", because we may
3693 * see a new one created at a higher level.
3695 continue;
3697 /* otherwise, check the preimage */
3698 if (state->check_index) {
3699 struct cache_entry *ce;
3701 ce = cache_file_exists(name->buf, name->len, ignore_case);
3702 if (ce && S_ISLNK(ce->ce_mode))
3703 return 1;
3704 } else {
3705 struct stat st;
3706 if (!lstat(name->buf, &st) && S_ISLNK(st.st_mode))
3707 return 1;
3709 } while (1);
3710 return 0;
3713 static int path_is_beyond_symlink(struct apply_state *state, const char *name_)
3715 int ret;
3716 struct strbuf name = STRBUF_INIT;
3718 assert(*name_ != '\0');
3719 strbuf_addstr(&name, name_);
3720 ret = path_is_beyond_symlink_1(state, &name);
3721 strbuf_release(&name);
3723 return ret;
3726 static void die_on_unsafe_path(struct patch *patch)
3728 const char *old_name = NULL;
3729 const char *new_name = NULL;
3730 if (patch->is_delete)
3731 old_name = patch->old_name;
3732 else if (!patch->is_new && !patch->is_copy)
3733 old_name = patch->old_name;
3734 if (!patch->is_delete)
3735 new_name = patch->new_name;
3737 if (old_name && !verify_path(old_name))
3738 die(_("invalid path '%s'"), old_name);
3739 if (new_name && !verify_path(new_name))
3740 die(_("invalid path '%s'"), new_name);
3744 * Check and apply the patch in-core; leave the result in patch->result
3745 * for the caller to write it out to the final destination.
3747 static int check_patch(struct apply_state *state, struct patch *patch)
3749 struct stat st;
3750 const char *old_name = patch->old_name;
3751 const char *new_name = patch->new_name;
3752 const char *name = old_name ? old_name : new_name;
3753 struct cache_entry *ce = NULL;
3754 struct patch *tpatch;
3755 int ok_if_exists;
3756 int status;
3758 patch->rejected = 1; /* we will drop this after we succeed */
3760 status = check_preimage(state, patch, &ce, &st);
3761 if (status)
3762 return status;
3763 old_name = patch->old_name;
3766 * A type-change diff is always split into a patch to delete
3767 * old, immediately followed by a patch to create new (see
3768 * diff.c::run_diff()); in such a case it is Ok that the entry
3769 * to be deleted by the previous patch is still in the working
3770 * tree and in the index.
3772 * A patch to swap-rename between A and B would first rename A
3773 * to B and then rename B to A. While applying the first one,
3774 * the presence of B should not stop A from getting renamed to
3775 * B; ask to_be_deleted() about the later rename. Removal of
3776 * B and rename from A to B is handled the same way by asking
3777 * was_deleted().
3779 if ((tpatch = in_fn_table(new_name)) &&
3780 (was_deleted(tpatch) || to_be_deleted(tpatch)))
3781 ok_if_exists = 1;
3782 else
3783 ok_if_exists = 0;
3785 if (new_name &&
3786 ((0 < patch->is_new) || patch->is_rename || patch->is_copy)) {
3787 int err = check_to_create(state, new_name, ok_if_exists);
3789 if (err && threeway) {
3790 patch->direct_to_threeway = 1;
3791 } else switch (err) {
3792 case 0:
3793 break; /* happy */
3794 case EXISTS_IN_INDEX:
3795 return error(_("%s: already exists in index"), new_name);
3796 break;
3797 case EXISTS_IN_WORKTREE:
3798 return error(_("%s: already exists in working directory"),
3799 new_name);
3800 default:
3801 return err;
3804 if (!patch->new_mode) {
3805 if (0 < patch->is_new)
3806 patch->new_mode = S_IFREG | 0644;
3807 else
3808 patch->new_mode = patch->old_mode;
3812 if (new_name && old_name) {
3813 int same = !strcmp(old_name, new_name);
3814 if (!patch->new_mode)
3815 patch->new_mode = patch->old_mode;
3816 if ((patch->old_mode ^ patch->new_mode) & S_IFMT) {
3817 if (same)
3818 return error(_("new mode (%o) of %s does not "
3819 "match old mode (%o)"),
3820 patch->new_mode, new_name,
3821 patch->old_mode);
3822 else
3823 return error(_("new mode (%o) of %s does not "
3824 "match old mode (%o) of %s"),
3825 patch->new_mode, new_name,
3826 patch->old_mode, old_name);
3830 if (!unsafe_paths)
3831 die_on_unsafe_path(patch);
3834 * An attempt to read from or delete a path that is beyond a
3835 * symbolic link will be prevented by load_patch_target() that
3836 * is called at the beginning of apply_data() so we do not
3837 * have to worry about a patch marked with "is_delete" bit
3838 * here. We however need to make sure that the patch result
3839 * is not deposited to a path that is beyond a symbolic link
3840 * here.
3842 if (!patch->is_delete && path_is_beyond_symlink(state, patch->new_name))
3843 return error(_("affected file '%s' is beyond a symbolic link"),
3844 patch->new_name);
3846 if (apply_data(state, patch, &st, ce) < 0)
3847 return error(_("%s: patch does not apply"), name);
3848 patch->rejected = 0;
3849 return 0;
3852 static int check_patch_list(struct apply_state *state, struct patch *patch)
3854 int err = 0;
3856 prepare_symlink_changes(patch);
3857 prepare_fn_table(patch);
3858 while (patch) {
3859 if (apply_verbosely)
3860 say_patch_name(stderr,
3861 _("Checking patch %s..."), patch);
3862 err |= check_patch(state, patch);
3863 patch = patch->next;
3865 return err;
3868 /* This function tries to read the sha1 from the current index */
3869 static int get_current_sha1(const char *path, unsigned char *sha1)
3871 int pos;
3873 if (read_cache() < 0)
3874 return -1;
3875 pos = cache_name_pos(path, strlen(path));
3876 if (pos < 0)
3877 return -1;
3878 hashcpy(sha1, active_cache[pos]->sha1);
3879 return 0;
3882 static int preimage_sha1_in_gitlink_patch(struct patch *p, unsigned char sha1[20])
3885 * A usable gitlink patch has only one fragment (hunk) that looks like:
3886 * @@ -1 +1 @@
3887 * -Subproject commit <old sha1>
3888 * +Subproject commit <new sha1>
3889 * or
3890 * @@ -1 +0,0 @@
3891 * -Subproject commit <old sha1>
3892 * for a removal patch.
3894 struct fragment *hunk = p->fragments;
3895 static const char heading[] = "-Subproject commit ";
3896 char *preimage;
3898 if (/* does the patch have only one hunk? */
3899 hunk && !hunk->next &&
3900 /* is its preimage one line? */
3901 hunk->oldpos == 1 && hunk->oldlines == 1 &&
3902 /* does preimage begin with the heading? */
3903 (preimage = memchr(hunk->patch, '\n', hunk->size)) != NULL &&
3904 starts_with(++preimage, heading) &&
3905 /* does it record full SHA-1? */
3906 !get_sha1_hex(preimage + sizeof(heading) - 1, sha1) &&
3907 preimage[sizeof(heading) + 40 - 1] == '\n' &&
3908 /* does the abbreviated name on the index line agree with it? */
3909 starts_with(preimage + sizeof(heading) - 1, p->old_sha1_prefix))
3910 return 0; /* it all looks fine */
3912 /* we may have full object name on the index line */
3913 return get_sha1_hex(p->old_sha1_prefix, sha1);
3916 /* Build an index that contains the just the files needed for a 3way merge */
3917 static void build_fake_ancestor(struct patch *list, const char *filename)
3919 struct patch *patch;
3920 struct index_state result = { NULL };
3921 static struct lock_file lock;
3923 /* Once we start supporting the reverse patch, it may be
3924 * worth showing the new sha1 prefix, but until then...
3926 for (patch = list; patch; patch = patch->next) {
3927 unsigned char sha1[20];
3928 struct cache_entry *ce;
3929 const char *name;
3931 name = patch->old_name ? patch->old_name : patch->new_name;
3932 if (0 < patch->is_new)
3933 continue;
3935 if (S_ISGITLINK(patch->old_mode)) {
3936 if (!preimage_sha1_in_gitlink_patch(patch, sha1))
3937 ; /* ok, the textual part looks sane */
3938 else
3939 die("sha1 information is lacking or useless for submodule %s",
3940 name);
3941 } else if (!get_sha1_blob(patch->old_sha1_prefix, sha1)) {
3942 ; /* ok */
3943 } else if (!patch->lines_added && !patch->lines_deleted) {
3944 /* mode-only change: update the current */
3945 if (get_current_sha1(patch->old_name, sha1))
3946 die("mode change for %s, which is not "
3947 "in current HEAD", name);
3948 } else
3949 die("sha1 information is lacking or useless "
3950 "(%s).", name);
3952 ce = make_cache_entry(patch->old_mode, sha1, name, 0, 0);
3953 if (!ce)
3954 die(_("make_cache_entry failed for path '%s'"), name);
3955 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))
3956 die ("Could not add %s to temporary index", name);
3959 hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);
3960 if (write_locked_index(&result, &lock, COMMIT_LOCK))
3961 die ("Could not write temporary index to %s", filename);
3963 discard_index(&result);
3966 static void stat_patch_list(struct patch *patch)
3968 int files, adds, dels;
3970 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
3971 files++;
3972 adds += patch->lines_added;
3973 dels += patch->lines_deleted;
3974 show_stats(patch);
3977 print_stat_summary(stdout, files, adds, dels);
3980 static void numstat_patch_list(struct patch *patch)
3982 for ( ; patch; patch = patch->next) {
3983 const char *name;
3984 name = patch->new_name ? patch->new_name : patch->old_name;
3985 if (patch->is_binary)
3986 printf("-\t-\t");
3987 else
3988 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
3989 write_name_quoted(name, stdout, line_termination);
3993 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
3995 if (mode)
3996 printf(" %s mode %06o %s\n", newdelete, mode, name);
3997 else
3998 printf(" %s %s\n", newdelete, name);
4001 static void show_mode_change(struct patch *p, int show_name)
4003 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
4004 if (show_name)
4005 printf(" mode change %06o => %06o %s\n",
4006 p->old_mode, p->new_mode, p->new_name);
4007 else
4008 printf(" mode change %06o => %06o\n",
4009 p->old_mode, p->new_mode);
4013 static void show_rename_copy(struct patch *p)
4015 const char *renamecopy = p->is_rename ? "rename" : "copy";
4016 const char *old, *new;
4018 /* Find common prefix */
4019 old = p->old_name;
4020 new = p->new_name;
4021 while (1) {
4022 const char *slash_old, *slash_new;
4023 slash_old = strchr(old, '/');
4024 slash_new = strchr(new, '/');
4025 if (!slash_old ||
4026 !slash_new ||
4027 slash_old - old != slash_new - new ||
4028 memcmp(old, new, slash_new - new))
4029 break;
4030 old = slash_old + 1;
4031 new = slash_new + 1;
4033 /* p->old_name thru old is the common prefix, and old and new
4034 * through the end of names are renames
4036 if (old != p->old_name)
4037 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
4038 (int)(old - p->old_name), p->old_name,
4039 old, new, p->score);
4040 else
4041 printf(" %s %s => %s (%d%%)\n", renamecopy,
4042 p->old_name, p->new_name, p->score);
4043 show_mode_change(p, 0);
4046 static void summary_patch_list(struct patch *patch)
4048 struct patch *p;
4050 for (p = patch; p; p = p->next) {
4051 if (p->is_new)
4052 show_file_mode_name("create", p->new_mode, p->new_name);
4053 else if (p->is_delete)
4054 show_file_mode_name("delete", p->old_mode, p->old_name);
4055 else {
4056 if (p->is_rename || p->is_copy)
4057 show_rename_copy(p);
4058 else {
4059 if (p->score) {
4060 printf(" rewrite %s (%d%%)\n",
4061 p->new_name, p->score);
4062 show_mode_change(p, 0);
4064 else
4065 show_mode_change(p, 1);
4071 static void patch_stats(struct patch *patch)
4073 int lines = patch->lines_added + patch->lines_deleted;
4075 if (lines > max_change)
4076 max_change = lines;
4077 if (patch->old_name) {
4078 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
4079 if (!len)
4080 len = strlen(patch->old_name);
4081 if (len > max_len)
4082 max_len = len;
4084 if (patch->new_name) {
4085 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
4086 if (!len)
4087 len = strlen(patch->new_name);
4088 if (len > max_len)
4089 max_len = len;
4093 static void remove_file(struct patch *patch, int rmdir_empty)
4095 if (update_index) {
4096 if (remove_file_from_cache(patch->old_name) < 0)
4097 die(_("unable to remove %s from index"), patch->old_name);
4099 if (!cached) {
4100 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
4101 remove_path(patch->old_name);
4106 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
4108 struct stat st;
4109 struct cache_entry *ce;
4110 int namelen = strlen(path);
4111 unsigned ce_size = cache_entry_size(namelen);
4113 if (!update_index)
4114 return;
4116 ce = xcalloc(1, ce_size);
4117 memcpy(ce->name, path, namelen);
4118 ce->ce_mode = create_ce_mode(mode);
4119 ce->ce_flags = create_ce_flags(0);
4120 ce->ce_namelen = namelen;
4121 if (S_ISGITLINK(mode)) {
4122 const char *s;
4124 if (!skip_prefix(buf, "Subproject commit ", &s) ||
4125 get_sha1_hex(s, ce->sha1))
4126 die(_("corrupt patch for submodule %s"), path);
4127 } else {
4128 if (!cached) {
4129 if (lstat(path, &st) < 0)
4130 die_errno(_("unable to stat newly created file '%s'"),
4131 path);
4132 fill_stat_cache_info(ce, &st);
4134 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
4135 die(_("unable to create backing store for newly created file %s"), path);
4137 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
4138 die(_("unable to add cache entry for %s"), path);
4141 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
4143 int fd;
4144 struct strbuf nbuf = STRBUF_INIT;
4146 if (S_ISGITLINK(mode)) {
4147 struct stat st;
4148 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
4149 return 0;
4150 return mkdir(path, 0777);
4153 if (has_symlinks && S_ISLNK(mode))
4154 /* Although buf:size is counted string, it also is NUL
4155 * terminated.
4157 return symlink(buf, path);
4159 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
4160 if (fd < 0)
4161 return -1;
4163 if (convert_to_working_tree(path, buf, size, &nbuf)) {
4164 size = nbuf.len;
4165 buf = nbuf.buf;
4167 write_or_die(fd, buf, size);
4168 strbuf_release(&nbuf);
4170 if (close(fd) < 0)
4171 die_errno(_("closing file '%s'"), path);
4172 return 0;
4176 * We optimistically assume that the directories exist,
4177 * which is true 99% of the time anyway. If they don't,
4178 * we create them and try again.
4180 static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
4182 if (cached)
4183 return;
4184 if (!try_create_file(path, mode, buf, size))
4185 return;
4187 if (errno == ENOENT) {
4188 if (safe_create_leading_directories(path))
4189 return;
4190 if (!try_create_file(path, mode, buf, size))
4191 return;
4194 if (errno == EEXIST || errno == EACCES) {
4195 /* We may be trying to create a file where a directory
4196 * used to be.
4198 struct stat st;
4199 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
4200 errno = EEXIST;
4203 if (errno == EEXIST) {
4204 unsigned int nr = getpid();
4206 for (;;) {
4207 char newpath[PATH_MAX];
4208 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
4209 if (!try_create_file(newpath, mode, buf, size)) {
4210 if (!rename(newpath, path))
4211 return;
4212 unlink_or_warn(newpath);
4213 break;
4215 if (errno != EEXIST)
4216 break;
4217 ++nr;
4220 die_errno(_("unable to write file '%s' mode %o"), path, mode);
4223 static void add_conflicted_stages_file(struct patch *patch)
4225 int stage, namelen;
4226 unsigned ce_size, mode;
4227 struct cache_entry *ce;
4229 if (!update_index)
4230 return;
4231 namelen = strlen(patch->new_name);
4232 ce_size = cache_entry_size(namelen);
4233 mode = patch->new_mode ? patch->new_mode : (S_IFREG | 0644);
4235 remove_file_from_cache(patch->new_name);
4236 for (stage = 1; stage < 4; stage++) {
4237 if (is_null_oid(&patch->threeway_stage[stage - 1]))
4238 continue;
4239 ce = xcalloc(1, ce_size);
4240 memcpy(ce->name, patch->new_name, namelen);
4241 ce->ce_mode = create_ce_mode(mode);
4242 ce->ce_flags = create_ce_flags(stage);
4243 ce->ce_namelen = namelen;
4244 hashcpy(ce->sha1, patch->threeway_stage[stage - 1].hash);
4245 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
4246 die(_("unable to add cache entry for %s"), patch->new_name);
4250 static void create_file(struct patch *patch)
4252 char *path = patch->new_name;
4253 unsigned mode = patch->new_mode;
4254 unsigned long size = patch->resultsize;
4255 char *buf = patch->result;
4257 if (!mode)
4258 mode = S_IFREG | 0644;
4259 create_one_file(path, mode, buf, size);
4261 if (patch->conflicted_threeway)
4262 add_conflicted_stages_file(patch);
4263 else
4264 add_index_file(path, mode, buf, size);
4267 /* phase zero is to remove, phase one is to create */
4268 static void write_out_one_result(struct patch *patch, int phase)
4270 if (patch->is_delete > 0) {
4271 if (phase == 0)
4272 remove_file(patch, 1);
4273 return;
4275 if (patch->is_new > 0 || patch->is_copy) {
4276 if (phase == 1)
4277 create_file(patch);
4278 return;
4281 * Rename or modification boils down to the same
4282 * thing: remove the old, write the new
4284 if (phase == 0)
4285 remove_file(patch, patch->is_rename);
4286 if (phase == 1)
4287 create_file(patch);
4290 static int write_out_one_reject(struct patch *patch)
4292 FILE *rej;
4293 char namebuf[PATH_MAX];
4294 struct fragment *frag;
4295 int cnt = 0;
4296 struct strbuf sb = STRBUF_INIT;
4298 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
4299 if (!frag->rejected)
4300 continue;
4301 cnt++;
4304 if (!cnt) {
4305 if (apply_verbosely)
4306 say_patch_name(stderr,
4307 _("Applied patch %s cleanly."), patch);
4308 return 0;
4311 /* This should not happen, because a removal patch that leaves
4312 * contents are marked "rejected" at the patch level.
4314 if (!patch->new_name)
4315 die(_("internal error"));
4317 /* Say this even without --verbose */
4318 strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",
4319 "Applying patch %%s with %d rejects...",
4320 cnt),
4321 cnt);
4322 say_patch_name(stderr, sb.buf, patch);
4323 strbuf_release(&sb);
4325 cnt = strlen(patch->new_name);
4326 if (ARRAY_SIZE(namebuf) <= cnt + 5) {
4327 cnt = ARRAY_SIZE(namebuf) - 5;
4328 warning(_("truncating .rej filename to %.*s.rej"),
4329 cnt - 1, patch->new_name);
4331 memcpy(namebuf, patch->new_name, cnt);
4332 memcpy(namebuf + cnt, ".rej", 5);
4334 rej = fopen(namebuf, "w");
4335 if (!rej)
4336 return error(_("cannot open %s: %s"), namebuf, strerror(errno));
4338 /* Normal git tools never deal with .rej, so do not pretend
4339 * this is a git patch by saying --git or giving extended
4340 * headers. While at it, maybe please "kompare" that wants
4341 * the trailing TAB and some garbage at the end of line ;-).
4343 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
4344 patch->new_name, patch->new_name);
4345 for (cnt = 1, frag = patch->fragments;
4346 frag;
4347 cnt++, frag = frag->next) {
4348 if (!frag->rejected) {
4349 fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);
4350 continue;
4352 fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);
4353 fprintf(rej, "%.*s", frag->size, frag->patch);
4354 if (frag->patch[frag->size-1] != '\n')
4355 fputc('\n', rej);
4357 fclose(rej);
4358 return -1;
4361 static int write_out_results(struct patch *list)
4363 int phase;
4364 int errs = 0;
4365 struct patch *l;
4366 struct string_list cpath = STRING_LIST_INIT_DUP;
4368 for (phase = 0; phase < 2; phase++) {
4369 l = list;
4370 while (l) {
4371 if (l->rejected)
4372 errs = 1;
4373 else {
4374 write_out_one_result(l, phase);
4375 if (phase == 1) {
4376 if (write_out_one_reject(l))
4377 errs = 1;
4378 if (l->conflicted_threeway) {
4379 string_list_append(&cpath, l->new_name);
4380 errs = 1;
4384 l = l->next;
4388 if (cpath.nr) {
4389 struct string_list_item *item;
4391 string_list_sort(&cpath);
4392 for_each_string_list_item(item, &cpath)
4393 fprintf(stderr, "U %s\n", item->string);
4394 string_list_clear(&cpath, 0);
4396 rerere(0);
4399 return errs;
4402 static struct lock_file lock_file;
4404 #define INACCURATE_EOF (1<<0)
4405 #define RECOUNT (1<<1)
4407 static int apply_patch(struct apply_state *state,
4408 int fd,
4409 const char *filename,
4410 int options)
4412 size_t offset;
4413 struct strbuf buf = STRBUF_INIT; /* owns the patch text */
4414 struct patch *list = NULL, **listp = &list;
4415 int skipped_patch = 0;
4417 patch_input_file = filename;
4418 read_patch_file(&buf, fd);
4419 offset = 0;
4420 while (offset < buf.len) {
4421 struct patch *patch;
4422 int nr;
4424 patch = xcalloc(1, sizeof(*patch));
4425 patch->inaccurate_eof = !!(options & INACCURATE_EOF);
4426 patch->recount = !!(options & RECOUNT);
4427 nr = parse_chunk(state, buf.buf + offset, buf.len - offset, patch);
4428 if (nr < 0) {
4429 free_patch(patch);
4430 break;
4432 if (state->apply_in_reverse)
4433 reverse_patches(patch);
4434 if (use_patch(state, patch)) {
4435 patch_stats(patch);
4436 *listp = patch;
4437 listp = &patch->next;
4439 else {
4440 if (apply_verbosely)
4441 say_patch_name(stderr, _("Skipped patch '%s'."), patch);
4442 free_patch(patch);
4443 skipped_patch++;
4445 offset += nr;
4448 if (!list && !skipped_patch)
4449 die(_("unrecognized input"));
4451 if (whitespace_error && (ws_error_action == die_on_ws_error))
4452 apply = 0;
4454 update_index = state->check_index && apply;
4455 if (update_index && newfd < 0)
4456 newfd = hold_locked_index(&lock_file, 1);
4458 if (state->check_index) {
4459 if (read_cache() < 0)
4460 die(_("unable to read index file"));
4463 if ((state->check || apply) &&
4464 check_patch_list(state, list) < 0 &&
4465 !apply_with_reject)
4466 exit(1);
4468 if (apply && write_out_results(list)) {
4469 if (apply_with_reject)
4470 exit(1);
4471 /* with --3way, we still need to write the index out */
4472 return 1;
4475 if (fake_ancestor)
4476 build_fake_ancestor(list, fake_ancestor);
4478 if (diffstat)
4479 stat_patch_list(list);
4481 if (numstat)
4482 numstat_patch_list(list);
4484 if (summary)
4485 summary_patch_list(list);
4487 free_patch_list(list);
4488 strbuf_release(&buf);
4489 string_list_clear(&fn_table, 0);
4490 return 0;
4493 static void git_apply_config(void)
4495 git_config_get_string_const("apply.whitespace", &apply_default_whitespace);
4496 git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);
4497 git_config(git_default_config, NULL);
4500 static int option_parse_exclude(const struct option *opt,
4501 const char *arg, int unset)
4503 add_name_limit(arg, 1);
4504 return 0;
4507 static int option_parse_include(const struct option *opt,
4508 const char *arg, int unset)
4510 add_name_limit(arg, 0);
4511 has_include = 1;
4512 return 0;
4515 static int option_parse_p(const struct option *opt,
4516 const char *arg, int unset)
4518 state_p_value = atoi(arg);
4519 p_value_known = 1;
4520 return 0;
4523 static int option_parse_space_change(const struct option *opt,
4524 const char *arg, int unset)
4526 if (unset)
4527 ws_ignore_action = ignore_ws_none;
4528 else
4529 ws_ignore_action = ignore_ws_change;
4530 return 0;
4533 static int option_parse_whitespace(const struct option *opt,
4534 const char *arg, int unset)
4536 const char **whitespace_option = opt->value;
4538 *whitespace_option = arg;
4539 parse_whitespace_option(arg);
4540 return 0;
4543 static int option_parse_directory(const struct option *opt,
4544 const char *arg, int unset)
4546 strbuf_reset(&root);
4547 strbuf_addstr(&root, arg);
4548 strbuf_complete(&root, '/');
4549 return 0;
4552 static void init_apply_state(struct apply_state *state, const char *prefix)
4554 memset(state, 0, sizeof(*state));
4555 state->prefix = prefix;
4556 state->prefix_length = state->prefix ? strlen(state->prefix) : 0;
4558 git_apply_config();
4559 if (apply_default_whitespace)
4560 parse_whitespace_option(apply_default_whitespace);
4561 if (apply_default_ignorewhitespace)
4562 parse_ignorewhitespace_option(apply_default_ignorewhitespace);
4565 static void clear_apply_state(struct apply_state *state)
4567 /* empty for now */
4570 int cmd_apply(int argc, const char **argv, const char *prefix)
4572 int i;
4573 int errs = 0;
4574 int is_not_gitdir = !startup_info->have_repository;
4575 int force_apply = 0;
4576 int options = 0;
4577 int read_stdin = 1;
4578 struct apply_state state;
4580 const char *whitespace_option = NULL;
4582 struct option builtin_apply_options[] = {
4583 { OPTION_CALLBACK, 0, "exclude", NULL, N_("path"),
4584 N_("don't apply changes matching the given path"),
4585 0, option_parse_exclude },
4586 { OPTION_CALLBACK, 0, "include", NULL, N_("path"),
4587 N_("apply changes matching the given path"),
4588 0, option_parse_include },
4589 { OPTION_CALLBACK, 'p', NULL, NULL, N_("num"),
4590 N_("remove <num> leading slashes from traditional diff paths"),
4591 0, option_parse_p },
4592 OPT_BOOL(0, "no-add", &no_add,
4593 N_("ignore additions made by the patch")),
4594 OPT_BOOL(0, "stat", &diffstat,
4595 N_("instead of applying the patch, output diffstat for the input")),
4596 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
4597 OPT_NOOP_NOARG(0, "binary"),
4598 OPT_BOOL(0, "numstat", &numstat,
4599 N_("show number of added and deleted lines in decimal notation")),
4600 OPT_BOOL(0, "summary", &summary,
4601 N_("instead of applying the patch, output a summary for the input")),
4602 OPT_BOOL(0, "check", &state.check,
4603 N_("instead of applying the patch, see if the patch is applicable")),
4604 OPT_BOOL(0, "index", &state.check_index,
4605 N_("make sure the patch is applicable to the current index")),
4606 OPT_BOOL(0, "cached", &cached,
4607 N_("apply a patch without touching the working tree")),
4608 OPT_BOOL(0, "unsafe-paths", &unsafe_paths,
4609 N_("accept a patch that touches outside the working area")),
4610 OPT_BOOL(0, "apply", &force_apply,
4611 N_("also apply the patch (use with --stat/--summary/--check)")),
4612 OPT_BOOL('3', "3way", &threeway,
4613 N_( "attempt three-way merge if a patch does not apply")),
4614 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor,
4615 N_("build a temporary index based on embedded index information")),
4616 /* Think twice before adding "--nul" synonym to this */
4617 OPT_SET_INT('z', NULL, &line_termination,
4618 N_("paths are separated with NUL character"), '\0'),
4619 OPT_INTEGER('C', NULL, &p_context,
4620 N_("ensure at least <n> lines of context match")),
4621 { OPTION_CALLBACK, 0, "whitespace", &whitespace_option, N_("action"),
4622 N_("detect new or modified lines that have whitespace errors"),
4623 0, option_parse_whitespace },
4624 { OPTION_CALLBACK, 0, "ignore-space-change", NULL, NULL,
4625 N_("ignore changes in whitespace when finding context"),
4626 PARSE_OPT_NOARG, option_parse_space_change },
4627 { OPTION_CALLBACK, 0, "ignore-whitespace", NULL, NULL,
4628 N_("ignore changes in whitespace when finding context"),
4629 PARSE_OPT_NOARG, option_parse_space_change },
4630 OPT_BOOL('R', "reverse", &state.apply_in_reverse,
4631 N_("apply the patch in reverse")),
4632 OPT_BOOL(0, "unidiff-zero", &state.unidiff_zero,
4633 N_("don't expect at least one line of context")),
4634 OPT_BOOL(0, "reject", &apply_with_reject,
4635 N_("leave the rejected hunks in corresponding *.rej files")),
4636 OPT_BOOL(0, "allow-overlap", &allow_overlap,
4637 N_("allow overlapping hunks")),
4638 OPT__VERBOSE(&apply_verbosely, N_("be verbose")),
4639 OPT_BIT(0, "inaccurate-eof", &options,
4640 N_("tolerate incorrectly detected missing new-line at the end of file"),
4641 INACCURATE_EOF),
4642 OPT_BIT(0, "recount", &options,
4643 N_("do not trust the line counts in the hunk headers"),
4644 RECOUNT),
4645 { OPTION_CALLBACK, 0, "directory", NULL, N_("root"),
4646 N_("prepend <root> to all filenames"),
4647 0, option_parse_directory },
4648 OPT_END()
4651 init_apply_state(&state, prefix);
4653 argc = parse_options(argc, argv, state.prefix, builtin_apply_options,
4654 apply_usage, 0);
4656 if (apply_with_reject && threeway)
4657 die("--reject and --3way cannot be used together.");
4658 if (cached && threeway)
4659 die("--cached and --3way cannot be used together.");
4660 if (threeway) {
4661 if (is_not_gitdir)
4662 die(_("--3way outside a repository"));
4663 state.check_index = 1;
4665 if (apply_with_reject)
4666 apply = apply_verbosely = 1;
4667 if (!force_apply && (diffstat || numstat || summary || state.check || fake_ancestor))
4668 apply = 0;
4669 if (state.check_index && is_not_gitdir)
4670 die(_("--index outside a repository"));
4671 if (cached) {
4672 if (is_not_gitdir)
4673 die(_("--cached outside a repository"));
4674 state.check_index = 1;
4676 if (state.check_index)
4677 unsafe_paths = 0;
4679 for (i = 0; i < argc; i++) {
4680 const char *arg = argv[i];
4681 int fd;
4683 if (!strcmp(arg, "-")) {
4684 errs |= apply_patch(&state, 0, "<stdin>", options);
4685 read_stdin = 0;
4686 continue;
4687 } else if (0 < state.prefix_length)
4688 arg = prefix_filename(state.prefix,
4689 state.prefix_length,
4690 arg);
4692 fd = open(arg, O_RDONLY);
4693 if (fd < 0)
4694 die_errno(_("can't open patch '%s'"), arg);
4695 read_stdin = 0;
4696 set_default_whitespace_mode(whitespace_option);
4697 errs |= apply_patch(&state, fd, arg, options);
4698 close(fd);
4700 set_default_whitespace_mode(whitespace_option);
4701 if (read_stdin)
4702 errs |= apply_patch(&state, 0, "<stdin>", options);
4703 if (whitespace_error) {
4704 if (squelch_whitespace_errors &&
4705 squelch_whitespace_errors < whitespace_error) {
4706 int squelched =
4707 whitespace_error - squelch_whitespace_errors;
4708 warning(Q_("squelched %d whitespace error",
4709 "squelched %d whitespace errors",
4710 squelched),
4711 squelched);
4713 if (ws_error_action == die_on_ws_error)
4714 die(Q_("%d line adds whitespace errors.",
4715 "%d lines add whitespace errors.",
4716 whitespace_error),
4717 whitespace_error);
4718 if (applied_after_fixing_ws && apply)
4719 warning("%d line%s applied after"
4720 " fixing whitespace errors.",
4721 applied_after_fixing_ws,
4722 applied_after_fixing_ws == 1 ? "" : "s");
4723 else if (whitespace_error)
4724 warning(Q_("%d line adds whitespace errors.",
4725 "%d lines add whitespace errors.",
4726 whitespace_error),
4727 whitespace_error);
4730 if (update_index) {
4731 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
4732 die(_("Unable to write new index file"));
4735 clear_apply_state(&state);
4737 return !!errs;