builtin/apply: move 'numstat' global into 'struct apply_state'
[git.git] / builtin / apply.c
blob47a45a71d51889d99cf2c442d6b5923384b9f78d
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 cached; /* apply to the index only */
30 int check; /* preimage must match working tree, don't actually apply */
31 int check_index; /* preimage must match the indexed version */
32 int update_index; /* check_index && apply */
34 /* These control cosmetic aspect of the output */
35 int diffstat; /* just show a diffstat, and don't actually apply */
36 int numstat; /* just show a numeric diffstat, and don't actually apply */
38 /* These boolean parameters control how the apply is done */
39 int allow_overlap;
40 int apply_in_reverse;
41 int apply_with_reject;
42 int apply_verbosely;
43 int unidiff_zero;
47 * --index-info shows the old and new index info for paths if available.
49 static int newfd = -1;
51 static int state_p_value = 1;
52 static int p_value_known;
53 static int summary;
54 static int apply = 1;
55 static int no_add;
56 static int threeway;
57 static int unsafe_paths;
58 static const char *fake_ancestor;
59 static int line_termination = '\n';
60 static unsigned int p_context = UINT_MAX;
61 static const char * const apply_usage[] = {
62 N_("git apply [<options>] [<patch>...]"),
63 NULL
66 static enum ws_error_action {
67 nowarn_ws_error,
68 warn_on_ws_error,
69 die_on_ws_error,
70 correct_ws_error
71 } ws_error_action = warn_on_ws_error;
72 static int whitespace_error;
73 static int squelch_whitespace_errors = 5;
74 static int applied_after_fixing_ws;
76 static enum ws_ignore {
77 ignore_ws_none,
78 ignore_ws_change
79 } ws_ignore_action = ignore_ws_none;
82 static const char *patch_input_file;
83 static struct strbuf root = STRBUF_INIT;
85 static void parse_whitespace_option(const char *option)
87 if (!option) {
88 ws_error_action = warn_on_ws_error;
89 return;
91 if (!strcmp(option, "warn")) {
92 ws_error_action = warn_on_ws_error;
93 return;
95 if (!strcmp(option, "nowarn")) {
96 ws_error_action = nowarn_ws_error;
97 return;
99 if (!strcmp(option, "error")) {
100 ws_error_action = die_on_ws_error;
101 return;
103 if (!strcmp(option, "error-all")) {
104 ws_error_action = die_on_ws_error;
105 squelch_whitespace_errors = 0;
106 return;
108 if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
109 ws_error_action = correct_ws_error;
110 return;
112 die(_("unrecognized whitespace option '%s'"), option);
115 static void parse_ignorewhitespace_option(const char *option)
117 if (!option || !strcmp(option, "no") ||
118 !strcmp(option, "false") || !strcmp(option, "never") ||
119 !strcmp(option, "none")) {
120 ws_ignore_action = ignore_ws_none;
121 return;
123 if (!strcmp(option, "change")) {
124 ws_ignore_action = ignore_ws_change;
125 return;
127 die(_("unrecognized whitespace ignore option '%s'"), option);
130 static void set_default_whitespace_mode(const char *whitespace_option)
132 if (!whitespace_option && !apply_default_whitespace)
133 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error);
137 * For "diff-stat" like behaviour, we keep track of the biggest change
138 * we've seen, and the longest filename. That allows us to do simple
139 * scaling.
141 static int max_change, max_len;
144 * Various "current state", notably line numbers and what
145 * file (and how) we're patching right now.. The "is_xxxx"
146 * things are flags, where -1 means "don't know yet".
148 static int state_linenr = 1;
151 * This represents one "hunk" from a patch, starting with
152 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
153 * patch text is pointed at by patch, and its byte length
154 * is stored in size. leading and trailing are the number
155 * of context lines.
157 struct fragment {
158 unsigned long leading, trailing;
159 unsigned long oldpos, oldlines;
160 unsigned long newpos, newlines;
162 * 'patch' is usually borrowed from buf in apply_patch(),
163 * but some codepaths store an allocated buffer.
165 const char *patch;
166 unsigned free_patch:1,
167 rejected:1;
168 int size;
169 int linenr;
170 struct fragment *next;
174 * When dealing with a binary patch, we reuse "leading" field
175 * to store the type of the binary hunk, either deflated "delta"
176 * or deflated "literal".
178 #define binary_patch_method leading
179 #define BINARY_DELTA_DEFLATED 1
180 #define BINARY_LITERAL_DEFLATED 2
183 * This represents a "patch" to a file, both metainfo changes
184 * such as creation/deletion, filemode and content changes represented
185 * as a series of fragments.
187 struct patch {
188 char *new_name, *old_name, *def_name;
189 unsigned int old_mode, new_mode;
190 int is_new, is_delete; /* -1 = unknown, 0 = false, 1 = true */
191 int rejected;
192 unsigned ws_rule;
193 int lines_added, lines_deleted;
194 int score;
195 unsigned int is_toplevel_relative:1;
196 unsigned int inaccurate_eof:1;
197 unsigned int is_binary:1;
198 unsigned int is_copy:1;
199 unsigned int is_rename:1;
200 unsigned int recount:1;
201 unsigned int conflicted_threeway:1;
202 unsigned int direct_to_threeway:1;
203 struct fragment *fragments;
204 char *result;
205 size_t resultsize;
206 char old_sha1_prefix[41];
207 char new_sha1_prefix[41];
208 struct patch *next;
210 /* three-way fallback result */
211 struct object_id threeway_stage[3];
214 static void free_fragment_list(struct fragment *list)
216 while (list) {
217 struct fragment *next = list->next;
218 if (list->free_patch)
219 free((char *)list->patch);
220 free(list);
221 list = next;
225 static void free_patch(struct patch *patch)
227 free_fragment_list(patch->fragments);
228 free(patch->def_name);
229 free(patch->old_name);
230 free(patch->new_name);
231 free(patch->result);
232 free(patch);
235 static void free_patch_list(struct patch *list)
237 while (list) {
238 struct patch *next = list->next;
239 free_patch(list);
240 list = next;
245 * A line in a file, len-bytes long (includes the terminating LF,
246 * except for an incomplete line at the end if the file ends with
247 * one), and its contents hashes to 'hash'.
249 struct line {
250 size_t len;
251 unsigned hash : 24;
252 unsigned flag : 8;
253 #define LINE_COMMON 1
254 #define LINE_PATCHED 2
258 * This represents a "file", which is an array of "lines".
260 struct image {
261 char *buf;
262 size_t len;
263 size_t nr;
264 size_t alloc;
265 struct line *line_allocated;
266 struct line *line;
270 * Records filenames that have been touched, in order to handle
271 * the case where more than one patches touch the same file.
274 static struct string_list fn_table;
276 static uint32_t hash_line(const char *cp, size_t len)
278 size_t i;
279 uint32_t h;
280 for (i = 0, h = 0; i < len; i++) {
281 if (!isspace(cp[i])) {
282 h = h * 3 + (cp[i] & 0xff);
285 return h;
289 * Compare lines s1 of length n1 and s2 of length n2, ignoring
290 * whitespace difference. Returns 1 if they match, 0 otherwise
292 static int fuzzy_matchlines(const char *s1, size_t n1,
293 const char *s2, size_t n2)
295 const char *last1 = s1 + n1 - 1;
296 const char *last2 = s2 + n2 - 1;
297 int result = 0;
299 /* ignore line endings */
300 while ((*last1 == '\r') || (*last1 == '\n'))
301 last1--;
302 while ((*last2 == '\r') || (*last2 == '\n'))
303 last2--;
305 /* skip leading whitespaces, if both begin with whitespace */
306 if (s1 <= last1 && s2 <= last2 && isspace(*s1) && isspace(*s2)) {
307 while (isspace(*s1) && (s1 <= last1))
308 s1++;
309 while (isspace(*s2) && (s2 <= last2))
310 s2++;
312 /* early return if both lines are empty */
313 if ((s1 > last1) && (s2 > last2))
314 return 1;
315 while (!result) {
316 result = *s1++ - *s2++;
318 * Skip whitespace inside. We check for whitespace on
319 * both buffers because we don't want "a b" to match
320 * "ab"
322 if (isspace(*s1) && isspace(*s2)) {
323 while (isspace(*s1) && s1 <= last1)
324 s1++;
325 while (isspace(*s2) && s2 <= last2)
326 s2++;
329 * If we reached the end on one side only,
330 * lines don't match
332 if (
333 ((s2 > last2) && (s1 <= last1)) ||
334 ((s1 > last1) && (s2 <= last2)))
335 return 0;
336 if ((s1 > last1) && (s2 > last2))
337 break;
340 return !result;
343 static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
345 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
346 img->line_allocated[img->nr].len = len;
347 img->line_allocated[img->nr].hash = hash_line(bol, len);
348 img->line_allocated[img->nr].flag = flag;
349 img->nr++;
353 * "buf" has the file contents to be patched (read from various sources).
354 * attach it to "image" and add line-based index to it.
355 * "image" now owns the "buf".
357 static void prepare_image(struct image *image, char *buf, size_t len,
358 int prepare_linetable)
360 const char *cp, *ep;
362 memset(image, 0, sizeof(*image));
363 image->buf = buf;
364 image->len = len;
366 if (!prepare_linetable)
367 return;
369 ep = image->buf + image->len;
370 cp = image->buf;
371 while (cp < ep) {
372 const char *next;
373 for (next = cp; next < ep && *next != '\n'; next++)
375 if (next < ep)
376 next++;
377 add_line_info(image, cp, next - cp, 0);
378 cp = next;
380 image->line = image->line_allocated;
383 static void clear_image(struct image *image)
385 free(image->buf);
386 free(image->line_allocated);
387 memset(image, 0, sizeof(*image));
390 /* fmt must contain _one_ %s and no other substitution */
391 static void say_patch_name(FILE *output, const char *fmt, struct patch *patch)
393 struct strbuf sb = STRBUF_INIT;
395 if (patch->old_name && patch->new_name &&
396 strcmp(patch->old_name, patch->new_name)) {
397 quote_c_style(patch->old_name, &sb, NULL, 0);
398 strbuf_addstr(&sb, " => ");
399 quote_c_style(patch->new_name, &sb, NULL, 0);
400 } else {
401 const char *n = patch->new_name;
402 if (!n)
403 n = patch->old_name;
404 quote_c_style(n, &sb, NULL, 0);
406 fprintf(output, fmt, sb.buf);
407 fputc('\n', output);
408 strbuf_release(&sb);
411 #define SLOP (16)
413 static void read_patch_file(struct strbuf *sb, int fd)
415 if (strbuf_read(sb, fd, 0) < 0)
416 die_errno("git apply: failed to read");
419 * Make sure that we have some slop in the buffer
420 * so that we can do speculative "memcmp" etc, and
421 * see to it that it is NUL-filled.
423 strbuf_grow(sb, SLOP);
424 memset(sb->buf + sb->len, 0, SLOP);
427 static unsigned long linelen(const char *buffer, unsigned long size)
429 unsigned long len = 0;
430 while (size--) {
431 len++;
432 if (*buffer++ == '\n')
433 break;
435 return len;
438 static int is_dev_null(const char *str)
440 return skip_prefix(str, "/dev/null", &str) && isspace(*str);
443 #define TERM_SPACE 1
444 #define TERM_TAB 2
446 static int name_terminate(const char *name, int namelen, int c, int terminate)
448 if (c == ' ' && !(terminate & TERM_SPACE))
449 return 0;
450 if (c == '\t' && !(terminate & TERM_TAB))
451 return 0;
453 return 1;
456 /* remove double slashes to make --index work with such filenames */
457 static char *squash_slash(char *name)
459 int i = 0, j = 0;
461 if (!name)
462 return NULL;
464 while (name[i]) {
465 if ((name[j++] = name[i++]) == '/')
466 while (name[i] == '/')
467 i++;
469 name[j] = '\0';
470 return name;
473 static char *find_name_gnu(const char *line, const char *def, int p_value)
475 struct strbuf name = STRBUF_INIT;
476 char *cp;
479 * Proposed "new-style" GNU patch/diff format; see
480 * http://marc.info/?l=git&m=112927316408690&w=2
482 if (unquote_c_style(&name, line, NULL)) {
483 strbuf_release(&name);
484 return NULL;
487 for (cp = name.buf; p_value; p_value--) {
488 cp = strchr(cp, '/');
489 if (!cp) {
490 strbuf_release(&name);
491 return NULL;
493 cp++;
496 strbuf_remove(&name, 0, cp - name.buf);
497 if (root.len)
498 strbuf_insert(&name, 0, root.buf, root.len);
499 return squash_slash(strbuf_detach(&name, NULL));
502 static size_t sane_tz_len(const char *line, size_t len)
504 const char *tz, *p;
506 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
507 return 0;
508 tz = line + len - strlen(" +0500");
510 if (tz[1] != '+' && tz[1] != '-')
511 return 0;
513 for (p = tz + 2; p != line + len; p++)
514 if (!isdigit(*p))
515 return 0;
517 return line + len - tz;
520 static size_t tz_with_colon_len(const char *line, size_t len)
522 const char *tz, *p;
524 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
525 return 0;
526 tz = line + len - strlen(" +08:00");
528 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
529 return 0;
530 p = tz + 2;
531 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
532 !isdigit(*p++) || !isdigit(*p++))
533 return 0;
535 return line + len - tz;
538 static size_t date_len(const char *line, size_t len)
540 const char *date, *p;
542 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
543 return 0;
544 p = date = line + len - strlen("72-02-05");
546 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
547 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
548 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */
549 return 0;
551 if (date - line >= strlen("19") &&
552 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */
553 date -= strlen("19");
555 return line + len - date;
558 static size_t short_time_len(const char *line, size_t len)
560 const char *time, *p;
562 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
563 return 0;
564 p = time = line + len - strlen(" 07:01:32");
566 /* Permit 1-digit hours? */
567 if (*p++ != ' ' ||
568 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
569 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
570 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */
571 return 0;
573 return line + len - time;
576 static size_t fractional_time_len(const char *line, size_t len)
578 const char *p;
579 size_t n;
581 /* Expected format: 19:41:17.620000023 */
582 if (!len || !isdigit(line[len - 1]))
583 return 0;
584 p = line + len - 1;
586 /* Fractional seconds. */
587 while (p > line && isdigit(*p))
588 p--;
589 if (*p != '.')
590 return 0;
592 /* Hours, minutes, and whole seconds. */
593 n = short_time_len(line, p - line);
594 if (!n)
595 return 0;
597 return line + len - p + n;
600 static size_t trailing_spaces_len(const char *line, size_t len)
602 const char *p;
604 /* Expected format: ' ' x (1 or more) */
605 if (!len || line[len - 1] != ' ')
606 return 0;
608 p = line + len;
609 while (p != line) {
610 p--;
611 if (*p != ' ')
612 return line + len - (p + 1);
615 /* All spaces! */
616 return len;
619 static size_t diff_timestamp_len(const char *line, size_t len)
621 const char *end = line + len;
622 size_t n;
625 * Posix: 2010-07-05 19:41:17
626 * GNU: 2010-07-05 19:41:17.620000023 -0500
629 if (!isdigit(end[-1]))
630 return 0;
632 n = sane_tz_len(line, end - line);
633 if (!n)
634 n = tz_with_colon_len(line, end - line);
635 end -= n;
637 n = short_time_len(line, end - line);
638 if (!n)
639 n = fractional_time_len(line, end - line);
640 end -= n;
642 n = date_len(line, end - line);
643 if (!n) /* No date. Too bad. */
644 return 0;
645 end -= n;
647 if (end == line) /* No space before date. */
648 return 0;
649 if (end[-1] == '\t') { /* Success! */
650 end--;
651 return line + len - end;
653 if (end[-1] != ' ') /* No space before date. */
654 return 0;
656 /* Whitespace damage. */
657 end -= trailing_spaces_len(line, end - line);
658 return line + len - end;
661 static char *find_name_common(const char *line, const char *def,
662 int p_value, const char *end, int terminate)
664 int len;
665 const char *start = NULL;
667 if (p_value == 0)
668 start = line;
669 while (line != end) {
670 char c = *line;
672 if (!end && isspace(c)) {
673 if (c == '\n')
674 break;
675 if (name_terminate(start, line-start, c, terminate))
676 break;
678 line++;
679 if (c == '/' && !--p_value)
680 start = line;
682 if (!start)
683 return squash_slash(xstrdup_or_null(def));
684 len = line - start;
685 if (!len)
686 return squash_slash(xstrdup_or_null(def));
689 * Generally we prefer the shorter name, especially
690 * if the other one is just a variation of that with
691 * something else tacked on to the end (ie "file.orig"
692 * or "file~").
694 if (def) {
695 int deflen = strlen(def);
696 if (deflen < len && !strncmp(start, def, deflen))
697 return squash_slash(xstrdup(def));
700 if (root.len) {
701 char *ret = xstrfmt("%s%.*s", root.buf, len, start);
702 return squash_slash(ret);
705 return squash_slash(xmemdupz(start, len));
708 static char *find_name(const char *line, char *def, int p_value, int terminate)
710 if (*line == '"') {
711 char *name = find_name_gnu(line, def, p_value);
712 if (name)
713 return name;
716 return find_name_common(line, def, p_value, NULL, terminate);
719 static char *find_name_traditional(const char *line, char *def, int p_value)
721 size_t len;
722 size_t date_len;
724 if (*line == '"') {
725 char *name = find_name_gnu(line, def, p_value);
726 if (name)
727 return name;
730 len = strchrnul(line, '\n') - line;
731 date_len = diff_timestamp_len(line, len);
732 if (!date_len)
733 return find_name_common(line, def, p_value, NULL, TERM_TAB);
734 len -= date_len;
736 return find_name_common(line, def, p_value, line + len, 0);
739 static int count_slashes(const char *cp)
741 int cnt = 0;
742 char ch;
744 while ((ch = *cp++))
745 if (ch == '/')
746 cnt++;
747 return cnt;
751 * Given the string after "--- " or "+++ ", guess the appropriate
752 * p_value for the given patch.
754 static int guess_p_value(struct apply_state *state, const char *nameline)
756 char *name, *cp;
757 int val = -1;
759 if (is_dev_null(nameline))
760 return -1;
761 name = find_name_traditional(nameline, NULL, 0);
762 if (!name)
763 return -1;
764 cp = strchr(name, '/');
765 if (!cp)
766 val = 0;
767 else if (state->prefix) {
769 * Does it begin with "a/$our-prefix" and such? Then this is
770 * very likely to apply to our directory.
772 if (!strncmp(name, state->prefix, state->prefix_length))
773 val = count_slashes(state->prefix);
774 else {
775 cp++;
776 if (!strncmp(cp, state->prefix, state->prefix_length))
777 val = count_slashes(state->prefix) + 1;
780 free(name);
781 return val;
785 * Does the ---/+++ line have the POSIX timestamp after the last HT?
786 * GNU diff puts epoch there to signal a creation/deletion event. Is
787 * this such a timestamp?
789 static int has_epoch_timestamp(const char *nameline)
792 * We are only interested in epoch timestamp; any non-zero
793 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
794 * For the same reason, the date must be either 1969-12-31 or
795 * 1970-01-01, and the seconds part must be "00".
797 const char stamp_regexp[] =
798 "^(1969-12-31|1970-01-01)"
800 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
802 "([-+][0-2][0-9]:?[0-5][0-9])\n";
803 const char *timestamp = NULL, *cp, *colon;
804 static regex_t *stamp;
805 regmatch_t m[10];
806 int zoneoffset;
807 int hourminute;
808 int status;
810 for (cp = nameline; *cp != '\n'; cp++) {
811 if (*cp == '\t')
812 timestamp = cp + 1;
814 if (!timestamp)
815 return 0;
816 if (!stamp) {
817 stamp = xmalloc(sizeof(*stamp));
818 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
819 warning(_("Cannot prepare timestamp regexp %s"),
820 stamp_regexp);
821 return 0;
825 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
826 if (status) {
827 if (status != REG_NOMATCH)
828 warning(_("regexec returned %d for input: %s"),
829 status, timestamp);
830 return 0;
833 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
834 if (*colon == ':')
835 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
836 else
837 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
838 if (timestamp[m[3].rm_so] == '-')
839 zoneoffset = -zoneoffset;
842 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
843 * (west of GMT) or 1970-01-01 (east of GMT)
845 if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) ||
846 (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10)))
847 return 0;
849 hourminute = (strtol(timestamp + 11, NULL, 10) * 60 +
850 strtol(timestamp + 14, NULL, 10) -
851 zoneoffset);
853 return ((zoneoffset < 0 && hourminute == 1440) ||
854 (0 <= zoneoffset && !hourminute));
858 * Get the name etc info from the ---/+++ lines of a traditional patch header
860 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
861 * files, we can happily check the index for a match, but for creating a
862 * new file we should try to match whatever "patch" does. I have no idea.
864 static void parse_traditional_patch(struct apply_state *state,
865 const char *first,
866 const char *second,
867 struct patch *patch)
869 char *name;
871 first += 4; /* skip "--- " */
872 second += 4; /* skip "+++ " */
873 if (!p_value_known) {
874 int p, q;
875 p = guess_p_value(state, first);
876 q = guess_p_value(state, second);
877 if (p < 0) p = q;
878 if (0 <= p && p == q) {
879 state_p_value = p;
880 p_value_known = 1;
883 if (is_dev_null(first)) {
884 patch->is_new = 1;
885 patch->is_delete = 0;
886 name = find_name_traditional(second, NULL, state_p_value);
887 patch->new_name = name;
888 } else if (is_dev_null(second)) {
889 patch->is_new = 0;
890 patch->is_delete = 1;
891 name = find_name_traditional(first, NULL, state_p_value);
892 patch->old_name = name;
893 } else {
894 char *first_name;
895 first_name = find_name_traditional(first, NULL, state_p_value);
896 name = find_name_traditional(second, first_name, state_p_value);
897 free(first_name);
898 if (has_epoch_timestamp(first)) {
899 patch->is_new = 1;
900 patch->is_delete = 0;
901 patch->new_name = name;
902 } else if (has_epoch_timestamp(second)) {
903 patch->is_new = 0;
904 patch->is_delete = 1;
905 patch->old_name = name;
906 } else {
907 patch->old_name = name;
908 patch->new_name = xstrdup_or_null(name);
911 if (!name)
912 die(_("unable to find filename in patch at line %d"), state_linenr);
915 static int gitdiff_hdrend(const char *line, struct patch *patch)
917 return -1;
921 * We're anal about diff header consistency, to make
922 * sure that we don't end up having strange ambiguous
923 * patches floating around.
925 * As a result, gitdiff_{old|new}name() will check
926 * their names against any previous information, just
927 * to make sure..
929 #define DIFF_OLD_NAME 0
930 #define DIFF_NEW_NAME 1
932 static void gitdiff_verify_name(const char *line, int isnull, char **name, int side)
934 if (!*name && !isnull) {
935 *name = find_name(line, NULL, state_p_value, TERM_TAB);
936 return;
939 if (*name) {
940 int len = strlen(*name);
941 char *another;
942 if (isnull)
943 die(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
944 *name, state_linenr);
945 another = find_name(line, NULL, state_p_value, TERM_TAB);
946 if (!another || memcmp(another, *name, len + 1))
947 die((side == DIFF_NEW_NAME) ?
948 _("git apply: bad git-diff - inconsistent new filename on line %d") :
949 _("git apply: bad git-diff - inconsistent old filename on line %d"), state_linenr);
950 free(another);
951 } else {
952 /* expect "/dev/null" */
953 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
954 die(_("git apply: bad git-diff - expected /dev/null on line %d"), state_linenr);
958 static int gitdiff_oldname(const char *line, struct patch *patch)
960 gitdiff_verify_name(line, patch->is_new, &patch->old_name,
961 DIFF_OLD_NAME);
962 return 0;
965 static int gitdiff_newname(const char *line, struct patch *patch)
967 gitdiff_verify_name(line, patch->is_delete, &patch->new_name,
968 DIFF_NEW_NAME);
969 return 0;
972 static int gitdiff_oldmode(const char *line, struct patch *patch)
974 patch->old_mode = strtoul(line, NULL, 8);
975 return 0;
978 static int gitdiff_newmode(const char *line, struct patch *patch)
980 patch->new_mode = strtoul(line, NULL, 8);
981 return 0;
984 static int gitdiff_delete(const char *line, struct patch *patch)
986 patch->is_delete = 1;
987 free(patch->old_name);
988 patch->old_name = xstrdup_or_null(patch->def_name);
989 return gitdiff_oldmode(line, patch);
992 static int gitdiff_newfile(const char *line, struct patch *patch)
994 patch->is_new = 1;
995 free(patch->new_name);
996 patch->new_name = xstrdup_or_null(patch->def_name);
997 return gitdiff_newmode(line, patch);
1000 static int gitdiff_copysrc(const char *line, struct patch *patch)
1002 patch->is_copy = 1;
1003 free(patch->old_name);
1004 patch->old_name = find_name(line, NULL, state_p_value ? state_p_value - 1 : 0, 0);
1005 return 0;
1008 static int gitdiff_copydst(const char *line, struct patch *patch)
1010 patch->is_copy = 1;
1011 free(patch->new_name);
1012 patch->new_name = find_name(line, NULL, state_p_value ? state_p_value - 1 : 0, 0);
1013 return 0;
1016 static int gitdiff_renamesrc(const char *line, struct patch *patch)
1018 patch->is_rename = 1;
1019 free(patch->old_name);
1020 patch->old_name = find_name(line, NULL, state_p_value ? state_p_value - 1 : 0, 0);
1021 return 0;
1024 static int gitdiff_renamedst(const char *line, struct patch *patch)
1026 patch->is_rename = 1;
1027 free(patch->new_name);
1028 patch->new_name = find_name(line, NULL, state_p_value ? state_p_value - 1 : 0, 0);
1029 return 0;
1032 static int gitdiff_similarity(const char *line, struct patch *patch)
1034 unsigned long val = strtoul(line, NULL, 10);
1035 if (val <= 100)
1036 patch->score = val;
1037 return 0;
1040 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
1042 unsigned long val = strtoul(line, NULL, 10);
1043 if (val <= 100)
1044 patch->score = val;
1045 return 0;
1048 static int gitdiff_index(const char *line, struct patch *patch)
1051 * index line is N hexadecimal, "..", N hexadecimal,
1052 * and optional space with octal mode.
1054 const char *ptr, *eol;
1055 int len;
1057 ptr = strchr(line, '.');
1058 if (!ptr || ptr[1] != '.' || 40 < ptr - line)
1059 return 0;
1060 len = ptr - line;
1061 memcpy(patch->old_sha1_prefix, line, len);
1062 patch->old_sha1_prefix[len] = 0;
1064 line = ptr + 2;
1065 ptr = strchr(line, ' ');
1066 eol = strchrnul(line, '\n');
1068 if (!ptr || eol < ptr)
1069 ptr = eol;
1070 len = ptr - line;
1072 if (40 < len)
1073 return 0;
1074 memcpy(patch->new_sha1_prefix, line, len);
1075 patch->new_sha1_prefix[len] = 0;
1076 if (*ptr == ' ')
1077 patch->old_mode = strtoul(ptr+1, NULL, 8);
1078 return 0;
1082 * This is normal for a diff that doesn't change anything: we'll fall through
1083 * into the next diff. Tell the parser to break out.
1085 static int gitdiff_unrecognized(const char *line, struct patch *patch)
1087 return -1;
1091 * Skip p_value leading components from "line"; as we do not accept
1092 * absolute paths, return NULL in that case.
1094 static const char *skip_tree_prefix(const char *line, int llen)
1096 int nslash;
1097 int i;
1099 if (!state_p_value)
1100 return (llen && line[0] == '/') ? NULL : line;
1102 nslash = state_p_value;
1103 for (i = 0; i < llen; i++) {
1104 int ch = line[i];
1105 if (ch == '/' && --nslash <= 0)
1106 return (i == 0) ? NULL : &line[i + 1];
1108 return NULL;
1112 * This is to extract the same name that appears on "diff --git"
1113 * line. We do not find and return anything if it is a rename
1114 * patch, and it is OK because we will find the name elsewhere.
1115 * We need to reliably find name only when it is mode-change only,
1116 * creation or deletion of an empty file. In any of these cases,
1117 * both sides are the same name under a/ and b/ respectively.
1119 static char *git_header_name(const char *line, int llen)
1121 const char *name;
1122 const char *second = NULL;
1123 size_t len, line_len;
1125 line += strlen("diff --git ");
1126 llen -= strlen("diff --git ");
1128 if (*line == '"') {
1129 const char *cp;
1130 struct strbuf first = STRBUF_INIT;
1131 struct strbuf sp = STRBUF_INIT;
1133 if (unquote_c_style(&first, line, &second))
1134 goto free_and_fail1;
1136 /* strip the a/b prefix including trailing slash */
1137 cp = skip_tree_prefix(first.buf, first.len);
1138 if (!cp)
1139 goto free_and_fail1;
1140 strbuf_remove(&first, 0, cp - first.buf);
1143 * second points at one past closing dq of name.
1144 * find the second name.
1146 while ((second < line + llen) && isspace(*second))
1147 second++;
1149 if (line + llen <= second)
1150 goto free_and_fail1;
1151 if (*second == '"') {
1152 if (unquote_c_style(&sp, second, NULL))
1153 goto free_and_fail1;
1154 cp = skip_tree_prefix(sp.buf, sp.len);
1155 if (!cp)
1156 goto free_and_fail1;
1157 /* They must match, otherwise ignore */
1158 if (strcmp(cp, first.buf))
1159 goto free_and_fail1;
1160 strbuf_release(&sp);
1161 return strbuf_detach(&first, NULL);
1164 /* unquoted second */
1165 cp = skip_tree_prefix(second, line + llen - second);
1166 if (!cp)
1167 goto free_and_fail1;
1168 if (line + llen - cp != first.len ||
1169 memcmp(first.buf, cp, first.len))
1170 goto free_and_fail1;
1171 return strbuf_detach(&first, NULL);
1173 free_and_fail1:
1174 strbuf_release(&first);
1175 strbuf_release(&sp);
1176 return NULL;
1179 /* unquoted first name */
1180 name = skip_tree_prefix(line, llen);
1181 if (!name)
1182 return NULL;
1185 * since the first name is unquoted, a dq if exists must be
1186 * the beginning of the second name.
1188 for (second = name; second < line + llen; second++) {
1189 if (*second == '"') {
1190 struct strbuf sp = STRBUF_INIT;
1191 const char *np;
1193 if (unquote_c_style(&sp, second, NULL))
1194 goto free_and_fail2;
1196 np = skip_tree_prefix(sp.buf, sp.len);
1197 if (!np)
1198 goto free_and_fail2;
1200 len = sp.buf + sp.len - np;
1201 if (len < second - name &&
1202 !strncmp(np, name, len) &&
1203 isspace(name[len])) {
1204 /* Good */
1205 strbuf_remove(&sp, 0, np - sp.buf);
1206 return strbuf_detach(&sp, NULL);
1209 free_and_fail2:
1210 strbuf_release(&sp);
1211 return NULL;
1216 * Accept a name only if it shows up twice, exactly the same
1217 * form.
1219 second = strchr(name, '\n');
1220 if (!second)
1221 return NULL;
1222 line_len = second - name;
1223 for (len = 0 ; ; len++) {
1224 switch (name[len]) {
1225 default:
1226 continue;
1227 case '\n':
1228 return NULL;
1229 case '\t': case ' ':
1231 * Is this the separator between the preimage
1232 * and the postimage pathname? Again, we are
1233 * only interested in the case where there is
1234 * no rename, as this is only to set def_name
1235 * and a rename patch has the names elsewhere
1236 * in an unambiguous form.
1238 if (!name[len + 1])
1239 return NULL; /* no postimage name */
1240 second = skip_tree_prefix(name + len + 1,
1241 line_len - (len + 1));
1242 if (!second)
1243 return NULL;
1245 * Does len bytes starting at "name" and "second"
1246 * (that are separated by one HT or SP we just
1247 * found) exactly match?
1249 if (second[len] == '\n' && !strncmp(name, second, len))
1250 return xmemdupz(name, len);
1255 /* Verify that we recognize the lines following a git header */
1256 static int parse_git_header(const char *line, int len, unsigned int size, struct patch *patch)
1258 unsigned long offset;
1260 /* A git diff has explicit new/delete information, so we don't guess */
1261 patch->is_new = 0;
1262 patch->is_delete = 0;
1265 * Some things may not have the old name in the
1266 * rest of the headers anywhere (pure mode changes,
1267 * or removing or adding empty files), so we get
1268 * the default name from the header.
1270 patch->def_name = git_header_name(line, len);
1271 if (patch->def_name && root.len) {
1272 char *s = xstrfmt("%s%s", root.buf, patch->def_name);
1273 free(patch->def_name);
1274 patch->def_name = s;
1277 line += len;
1278 size -= len;
1279 state_linenr++;
1280 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, state_linenr++) {
1281 static const struct opentry {
1282 const char *str;
1283 int (*fn)(const char *, struct patch *);
1284 } optable[] = {
1285 { "@@ -", gitdiff_hdrend },
1286 { "--- ", gitdiff_oldname },
1287 { "+++ ", gitdiff_newname },
1288 { "old mode ", gitdiff_oldmode },
1289 { "new mode ", gitdiff_newmode },
1290 { "deleted file mode ", gitdiff_delete },
1291 { "new file mode ", gitdiff_newfile },
1292 { "copy from ", gitdiff_copysrc },
1293 { "copy to ", gitdiff_copydst },
1294 { "rename old ", gitdiff_renamesrc },
1295 { "rename new ", gitdiff_renamedst },
1296 { "rename from ", gitdiff_renamesrc },
1297 { "rename to ", gitdiff_renamedst },
1298 { "similarity index ", gitdiff_similarity },
1299 { "dissimilarity index ", gitdiff_dissimilarity },
1300 { "index ", gitdiff_index },
1301 { "", gitdiff_unrecognized },
1303 int i;
1305 len = linelen(line, size);
1306 if (!len || line[len-1] != '\n')
1307 break;
1308 for (i = 0; i < ARRAY_SIZE(optable); i++) {
1309 const struct opentry *p = optable + i;
1310 int oplen = strlen(p->str);
1311 if (len < oplen || memcmp(p->str, line, oplen))
1312 continue;
1313 if (p->fn(line + oplen, patch) < 0)
1314 return offset;
1315 break;
1319 return offset;
1322 static int parse_num(const char *line, unsigned long *p)
1324 char *ptr;
1326 if (!isdigit(*line))
1327 return 0;
1328 *p = strtoul(line, &ptr, 10);
1329 return ptr - line;
1332 static int parse_range(const char *line, int len, int offset, const char *expect,
1333 unsigned long *p1, unsigned long *p2)
1335 int digits, ex;
1337 if (offset < 0 || offset >= len)
1338 return -1;
1339 line += offset;
1340 len -= offset;
1342 digits = parse_num(line, p1);
1343 if (!digits)
1344 return -1;
1346 offset += digits;
1347 line += digits;
1348 len -= digits;
1350 *p2 = 1;
1351 if (*line == ',') {
1352 digits = parse_num(line+1, p2);
1353 if (!digits)
1354 return -1;
1356 offset += digits+1;
1357 line += digits+1;
1358 len -= digits+1;
1361 ex = strlen(expect);
1362 if (ex > len)
1363 return -1;
1364 if (memcmp(line, expect, ex))
1365 return -1;
1367 return offset + ex;
1370 static void recount_diff(const char *line, int size, struct fragment *fragment)
1372 int oldlines = 0, newlines = 0, ret = 0;
1374 if (size < 1) {
1375 warning("recount: ignore empty hunk");
1376 return;
1379 for (;;) {
1380 int len = linelen(line, size);
1381 size -= len;
1382 line += len;
1384 if (size < 1)
1385 break;
1387 switch (*line) {
1388 case ' ': case '\n':
1389 newlines++;
1390 /* fall through */
1391 case '-':
1392 oldlines++;
1393 continue;
1394 case '+':
1395 newlines++;
1396 continue;
1397 case '\\':
1398 continue;
1399 case '@':
1400 ret = size < 3 || !starts_with(line, "@@ ");
1401 break;
1402 case 'd':
1403 ret = size < 5 || !starts_with(line, "diff ");
1404 break;
1405 default:
1406 ret = -1;
1407 break;
1409 if (ret) {
1410 warning(_("recount: unexpected line: %.*s"),
1411 (int)linelen(line, size), line);
1412 return;
1414 break;
1416 fragment->oldlines = oldlines;
1417 fragment->newlines = newlines;
1421 * Parse a unified diff fragment header of the
1422 * form "@@ -a,b +c,d @@"
1424 static int parse_fragment_header(const char *line, int len, struct fragment *fragment)
1426 int offset;
1428 if (!len || line[len-1] != '\n')
1429 return -1;
1431 /* Figure out the number of lines in a fragment */
1432 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1433 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1435 return offset;
1438 static int find_header(struct apply_state *state,
1439 const char *line,
1440 unsigned long size,
1441 int *hdrsize,
1442 struct patch *patch)
1444 unsigned long offset, len;
1446 patch->is_toplevel_relative = 0;
1447 patch->is_rename = patch->is_copy = 0;
1448 patch->is_new = patch->is_delete = -1;
1449 patch->old_mode = patch->new_mode = 0;
1450 patch->old_name = patch->new_name = NULL;
1451 for (offset = 0; size > 0; offset += len, size -= len, line += len, state_linenr++) {
1452 unsigned long nextlen;
1454 len = linelen(line, size);
1455 if (!len)
1456 break;
1458 /* Testing this early allows us to take a few shortcuts.. */
1459 if (len < 6)
1460 continue;
1463 * Make sure we don't find any unconnected patch fragments.
1464 * That's a sign that we didn't find a header, and that a
1465 * patch has become corrupted/broken up.
1467 if (!memcmp("@@ -", line, 4)) {
1468 struct fragment dummy;
1469 if (parse_fragment_header(line, len, &dummy) < 0)
1470 continue;
1471 die(_("patch fragment without header at line %d: %.*s"),
1472 state_linenr, (int)len-1, line);
1475 if (size < len + 6)
1476 break;
1479 * Git patch? It might not have a real patch, just a rename
1480 * or mode change, so we handle that specially
1482 if (!memcmp("diff --git ", line, 11)) {
1483 int git_hdr_len = parse_git_header(line, len, size, patch);
1484 if (git_hdr_len <= len)
1485 continue;
1486 if (!patch->old_name && !patch->new_name) {
1487 if (!patch->def_name)
1488 die(Q_("git diff header lacks filename information when removing "
1489 "%d leading pathname component (line %d)",
1490 "git diff header lacks filename information when removing "
1491 "%d leading pathname components (line %d)",
1492 state_p_value),
1493 state_p_value, state_linenr);
1494 patch->old_name = xstrdup(patch->def_name);
1495 patch->new_name = xstrdup(patch->def_name);
1497 if (!patch->is_delete && !patch->new_name)
1498 die("git diff header lacks filename information "
1499 "(line %d)", state_linenr);
1500 patch->is_toplevel_relative = 1;
1501 *hdrsize = git_hdr_len;
1502 return offset;
1505 /* --- followed by +++ ? */
1506 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1507 continue;
1510 * We only accept unified patches, so we want it to
1511 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1512 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1514 nextlen = linelen(line + len, size - len);
1515 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1516 continue;
1518 /* Ok, we'll consider it a patch */
1519 parse_traditional_patch(state, line, line+len, patch);
1520 *hdrsize = len + nextlen;
1521 state_linenr += 2;
1522 return offset;
1524 return -1;
1527 static void record_ws_error(unsigned result, const char *line, int len, int linenr)
1529 char *err;
1531 if (!result)
1532 return;
1534 whitespace_error++;
1535 if (squelch_whitespace_errors &&
1536 squelch_whitespace_errors < whitespace_error)
1537 return;
1539 err = whitespace_error_string(result);
1540 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1541 patch_input_file, linenr, err, len, line);
1542 free(err);
1545 static void check_whitespace(const char *line, int len, unsigned ws_rule)
1547 unsigned result = ws_check(line + 1, len - 1, ws_rule);
1549 record_ws_error(result, line + 1, len - 2, state_linenr);
1553 * Parse a unified diff. Note that this really needs to parse each
1554 * fragment separately, since the only way to know the difference
1555 * between a "---" that is part of a patch, and a "---" that starts
1556 * the next patch is to look at the line counts..
1558 static int parse_fragment(struct apply_state *state,
1559 const char *line,
1560 unsigned long size,
1561 struct patch *patch,
1562 struct fragment *fragment)
1564 int added, deleted;
1565 int len = linelen(line, size), offset;
1566 unsigned long oldlines, newlines;
1567 unsigned long leading, trailing;
1569 offset = parse_fragment_header(line, len, fragment);
1570 if (offset < 0)
1571 return -1;
1572 if (offset > 0 && patch->recount)
1573 recount_diff(line + offset, size - offset, fragment);
1574 oldlines = fragment->oldlines;
1575 newlines = fragment->newlines;
1576 leading = 0;
1577 trailing = 0;
1579 /* Parse the thing.. */
1580 line += len;
1581 size -= len;
1582 state_linenr++;
1583 added = deleted = 0;
1584 for (offset = len;
1585 0 < size;
1586 offset += len, size -= len, line += len, state_linenr++) {
1587 if (!oldlines && !newlines)
1588 break;
1589 len = linelen(line, size);
1590 if (!len || line[len-1] != '\n')
1591 return -1;
1592 switch (*line) {
1593 default:
1594 return -1;
1595 case '\n': /* newer GNU diff, an empty context line */
1596 case ' ':
1597 oldlines--;
1598 newlines--;
1599 if (!deleted && !added)
1600 leading++;
1601 trailing++;
1602 if (!state->apply_in_reverse &&
1603 ws_error_action == correct_ws_error)
1604 check_whitespace(line, len, patch->ws_rule);
1605 break;
1606 case '-':
1607 if (state->apply_in_reverse &&
1608 ws_error_action != nowarn_ws_error)
1609 check_whitespace(line, len, patch->ws_rule);
1610 deleted++;
1611 oldlines--;
1612 trailing = 0;
1613 break;
1614 case '+':
1615 if (!state->apply_in_reverse &&
1616 ws_error_action != nowarn_ws_error)
1617 check_whitespace(line, len, patch->ws_rule);
1618 added++;
1619 newlines--;
1620 trailing = 0;
1621 break;
1624 * We allow "\ No newline at end of file". Depending
1625 * on locale settings when the patch was produced we
1626 * don't know what this line looks like. The only
1627 * thing we do know is that it begins with "\ ".
1628 * Checking for 12 is just for sanity check -- any
1629 * l10n of "\ No newline..." is at least that long.
1631 case '\\':
1632 if (len < 12 || memcmp(line, "\\ ", 2))
1633 return -1;
1634 break;
1637 if (oldlines || newlines)
1638 return -1;
1639 if (!deleted && !added)
1640 return -1;
1642 fragment->leading = leading;
1643 fragment->trailing = trailing;
1646 * If a fragment ends with an incomplete line, we failed to include
1647 * it in the above loop because we hit oldlines == newlines == 0
1648 * before seeing it.
1650 if (12 < size && !memcmp(line, "\\ ", 2))
1651 offset += linelen(line, size);
1653 patch->lines_added += added;
1654 patch->lines_deleted += deleted;
1656 if (0 < patch->is_new && oldlines)
1657 return error(_("new file depends on old contents"));
1658 if (0 < patch->is_delete && newlines)
1659 return error(_("deleted file still has contents"));
1660 return offset;
1664 * We have seen "diff --git a/... b/..." header (or a traditional patch
1665 * header). Read hunks that belong to this patch into fragments and hang
1666 * them to the given patch structure.
1668 * The (fragment->patch, fragment->size) pair points into the memory given
1669 * by the caller, not a copy, when we return.
1671 static int parse_single_patch(struct apply_state *state,
1672 const char *line,
1673 unsigned long size,
1674 struct patch *patch)
1676 unsigned long offset = 0;
1677 unsigned long oldlines = 0, newlines = 0, context = 0;
1678 struct fragment **fragp = &patch->fragments;
1680 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1681 struct fragment *fragment;
1682 int len;
1684 fragment = xcalloc(1, sizeof(*fragment));
1685 fragment->linenr = state_linenr;
1686 len = parse_fragment(state, line, size, patch, fragment);
1687 if (len <= 0)
1688 die(_("corrupt patch at line %d"), state_linenr);
1689 fragment->patch = line;
1690 fragment->size = len;
1691 oldlines += fragment->oldlines;
1692 newlines += fragment->newlines;
1693 context += fragment->leading + fragment->trailing;
1695 *fragp = fragment;
1696 fragp = &fragment->next;
1698 offset += len;
1699 line += len;
1700 size -= len;
1704 * If something was removed (i.e. we have old-lines) it cannot
1705 * be creation, and if something was added it cannot be
1706 * deletion. However, the reverse is not true; --unified=0
1707 * patches that only add are not necessarily creation even
1708 * though they do not have any old lines, and ones that only
1709 * delete are not necessarily deletion.
1711 * Unfortunately, a real creation/deletion patch do _not_ have
1712 * any context line by definition, so we cannot safely tell it
1713 * apart with --unified=0 insanity. At least if the patch has
1714 * more than one hunk it is not creation or deletion.
1716 if (patch->is_new < 0 &&
1717 (oldlines || (patch->fragments && patch->fragments->next)))
1718 patch->is_new = 0;
1719 if (patch->is_delete < 0 &&
1720 (newlines || (patch->fragments && patch->fragments->next)))
1721 patch->is_delete = 0;
1723 if (0 < patch->is_new && oldlines)
1724 die(_("new file %s depends on old contents"), patch->new_name);
1725 if (0 < patch->is_delete && newlines)
1726 die(_("deleted file %s still has contents"), patch->old_name);
1727 if (!patch->is_delete && !newlines && context)
1728 fprintf_ln(stderr,
1729 _("** warning: "
1730 "file %s becomes empty but is not deleted"),
1731 patch->new_name);
1733 return offset;
1736 static inline int metadata_changes(struct patch *patch)
1738 return patch->is_rename > 0 ||
1739 patch->is_copy > 0 ||
1740 patch->is_new > 0 ||
1741 patch->is_delete ||
1742 (patch->old_mode && patch->new_mode &&
1743 patch->old_mode != patch->new_mode);
1746 static char *inflate_it(const void *data, unsigned long size,
1747 unsigned long inflated_size)
1749 git_zstream stream;
1750 void *out;
1751 int st;
1753 memset(&stream, 0, sizeof(stream));
1755 stream.next_in = (unsigned char *)data;
1756 stream.avail_in = size;
1757 stream.next_out = out = xmalloc(inflated_size);
1758 stream.avail_out = inflated_size;
1759 git_inflate_init(&stream);
1760 st = git_inflate(&stream, Z_FINISH);
1761 git_inflate_end(&stream);
1762 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1763 free(out);
1764 return NULL;
1766 return out;
1770 * Read a binary hunk and return a new fragment; fragment->patch
1771 * points at an allocated memory that the caller must free, so
1772 * it is marked as "->free_patch = 1".
1774 static struct fragment *parse_binary_hunk(char **buf_p,
1775 unsigned long *sz_p,
1776 int *status_p,
1777 int *used_p)
1780 * Expect a line that begins with binary patch method ("literal"
1781 * or "delta"), followed by the length of data before deflating.
1782 * a sequence of 'length-byte' followed by base-85 encoded data
1783 * should follow, terminated by a newline.
1785 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1786 * and we would limit the patch line to 66 characters,
1787 * so one line can fit up to 13 groups that would decode
1788 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1789 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1791 int llen, used;
1792 unsigned long size = *sz_p;
1793 char *buffer = *buf_p;
1794 int patch_method;
1795 unsigned long origlen;
1796 char *data = NULL;
1797 int hunk_size = 0;
1798 struct fragment *frag;
1800 llen = linelen(buffer, size);
1801 used = llen;
1803 *status_p = 0;
1805 if (starts_with(buffer, "delta ")) {
1806 patch_method = BINARY_DELTA_DEFLATED;
1807 origlen = strtoul(buffer + 6, NULL, 10);
1809 else if (starts_with(buffer, "literal ")) {
1810 patch_method = BINARY_LITERAL_DEFLATED;
1811 origlen = strtoul(buffer + 8, NULL, 10);
1813 else
1814 return NULL;
1816 state_linenr++;
1817 buffer += llen;
1818 while (1) {
1819 int byte_length, max_byte_length, newsize;
1820 llen = linelen(buffer, size);
1821 used += llen;
1822 state_linenr++;
1823 if (llen == 1) {
1824 /* consume the blank line */
1825 buffer++;
1826 size--;
1827 break;
1830 * Minimum line is "A00000\n" which is 7-byte long,
1831 * and the line length must be multiple of 5 plus 2.
1833 if ((llen < 7) || (llen-2) % 5)
1834 goto corrupt;
1835 max_byte_length = (llen - 2) / 5 * 4;
1836 byte_length = *buffer;
1837 if ('A' <= byte_length && byte_length <= 'Z')
1838 byte_length = byte_length - 'A' + 1;
1839 else if ('a' <= byte_length && byte_length <= 'z')
1840 byte_length = byte_length - 'a' + 27;
1841 else
1842 goto corrupt;
1843 /* if the input length was not multiple of 4, we would
1844 * have filler at the end but the filler should never
1845 * exceed 3 bytes
1847 if (max_byte_length < byte_length ||
1848 byte_length <= max_byte_length - 4)
1849 goto corrupt;
1850 newsize = hunk_size + byte_length;
1851 data = xrealloc(data, newsize);
1852 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1853 goto corrupt;
1854 hunk_size = newsize;
1855 buffer += llen;
1856 size -= llen;
1859 frag = xcalloc(1, sizeof(*frag));
1860 frag->patch = inflate_it(data, hunk_size, origlen);
1861 frag->free_patch = 1;
1862 if (!frag->patch)
1863 goto corrupt;
1864 free(data);
1865 frag->size = origlen;
1866 *buf_p = buffer;
1867 *sz_p = size;
1868 *used_p = used;
1869 frag->binary_patch_method = patch_method;
1870 return frag;
1872 corrupt:
1873 free(data);
1874 *status_p = -1;
1875 error(_("corrupt binary patch at line %d: %.*s"),
1876 state_linenr-1, llen-1, buffer);
1877 return NULL;
1881 * Returns:
1882 * -1 in case of error,
1883 * the length of the parsed binary patch otherwise
1885 static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1888 * We have read "GIT binary patch\n"; what follows is a line
1889 * that says the patch method (currently, either "literal" or
1890 * "delta") and the length of data before deflating; a
1891 * sequence of 'length-byte' followed by base-85 encoded data
1892 * follows.
1894 * When a binary patch is reversible, there is another binary
1895 * hunk in the same format, starting with patch method (either
1896 * "literal" or "delta") with the length of data, and a sequence
1897 * of length-byte + base-85 encoded data, terminated with another
1898 * empty line. This data, when applied to the postimage, produces
1899 * the preimage.
1901 struct fragment *forward;
1902 struct fragment *reverse;
1903 int status;
1904 int used, used_1;
1906 forward = parse_binary_hunk(&buffer, &size, &status, &used);
1907 if (!forward && !status)
1908 /* there has to be one hunk (forward hunk) */
1909 return error(_("unrecognized binary patch at line %d"), state_linenr-1);
1910 if (status)
1911 /* otherwise we already gave an error message */
1912 return status;
1914 reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1915 if (reverse)
1916 used += used_1;
1917 else if (status) {
1919 * Not having reverse hunk is not an error, but having
1920 * a corrupt reverse hunk is.
1922 free((void*) forward->patch);
1923 free(forward);
1924 return status;
1926 forward->next = reverse;
1927 patch->fragments = forward;
1928 patch->is_binary = 1;
1929 return used;
1932 static void prefix_one(struct apply_state *state, char **name)
1934 char *old_name = *name;
1935 if (!old_name)
1936 return;
1937 *name = xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));
1938 free(old_name);
1941 static void prefix_patch(struct apply_state *state, struct patch *p)
1943 if (!state->prefix || p->is_toplevel_relative)
1944 return;
1945 prefix_one(state, &p->new_name);
1946 prefix_one(state, &p->old_name);
1950 * include/exclude
1953 static struct string_list limit_by_name;
1954 static int has_include;
1955 static void add_name_limit(const char *name, int exclude)
1957 struct string_list_item *it;
1959 it = string_list_append(&limit_by_name, name);
1960 it->util = exclude ? NULL : (void *) 1;
1963 static int use_patch(struct apply_state *state, struct patch *p)
1965 const char *pathname = p->new_name ? p->new_name : p->old_name;
1966 int i;
1968 /* Paths outside are not touched regardless of "--include" */
1969 if (0 < state->prefix_length) {
1970 int pathlen = strlen(pathname);
1971 if (pathlen <= state->prefix_length ||
1972 memcmp(state->prefix, pathname, state->prefix_length))
1973 return 0;
1976 /* See if it matches any of exclude/include rule */
1977 for (i = 0; i < limit_by_name.nr; i++) {
1978 struct string_list_item *it = &limit_by_name.items[i];
1979 if (!wildmatch(it->string, pathname, 0, NULL))
1980 return (it->util != NULL);
1984 * If we had any include, a path that does not match any rule is
1985 * not used. Otherwise, we saw bunch of exclude rules (or none)
1986 * and such a path is used.
1988 return !has_include;
1993 * Read the patch text in "buffer" that extends for "size" bytes; stop
1994 * reading after seeing a single patch (i.e. changes to a single file).
1995 * Create fragments (i.e. patch hunks) and hang them to the given patch.
1996 * Return the number of bytes consumed, so that the caller can call us
1997 * again for the next patch.
1999 static int parse_chunk(struct apply_state *state, char *buffer, unsigned long size, struct patch *patch)
2001 int hdrsize, patchsize;
2002 int offset = find_header(state, buffer, size, &hdrsize, patch);
2004 if (offset < 0)
2005 return offset;
2007 prefix_patch(state, patch);
2009 if (!use_patch(state, patch))
2010 patch->ws_rule = 0;
2011 else
2012 patch->ws_rule = whitespace_rule(patch->new_name
2013 ? patch->new_name
2014 : patch->old_name);
2016 patchsize = parse_single_patch(state,
2017 buffer + offset + hdrsize,
2018 size - offset - hdrsize,
2019 patch);
2021 if (!patchsize) {
2022 static const char git_binary[] = "GIT binary patch\n";
2023 int hd = hdrsize + offset;
2024 unsigned long llen = linelen(buffer + hd, size - hd);
2026 if (llen == sizeof(git_binary) - 1 &&
2027 !memcmp(git_binary, buffer + hd, llen)) {
2028 int used;
2029 state_linenr++;
2030 used = parse_binary(buffer + hd + llen,
2031 size - hd - llen, patch);
2032 if (used < 0)
2033 return -1;
2034 if (used)
2035 patchsize = used + llen;
2036 else
2037 patchsize = 0;
2039 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
2040 static const char *binhdr[] = {
2041 "Binary files ",
2042 "Files ",
2043 NULL,
2045 int i;
2046 for (i = 0; binhdr[i]; i++) {
2047 int len = strlen(binhdr[i]);
2048 if (len < size - hd &&
2049 !memcmp(binhdr[i], buffer + hd, len)) {
2050 state_linenr++;
2051 patch->is_binary = 1;
2052 patchsize = llen;
2053 break;
2058 /* Empty patch cannot be applied if it is a text patch
2059 * without metadata change. A binary patch appears
2060 * empty to us here.
2062 if ((apply || state->check) &&
2063 (!patch->is_binary && !metadata_changes(patch)))
2064 die(_("patch with only garbage at line %d"), state_linenr);
2067 return offset + hdrsize + patchsize;
2070 #define swap(a,b) myswap((a),(b),sizeof(a))
2072 #define myswap(a, b, size) do { \
2073 unsigned char mytmp[size]; \
2074 memcpy(mytmp, &a, size); \
2075 memcpy(&a, &b, size); \
2076 memcpy(&b, mytmp, size); \
2077 } while (0)
2079 static void reverse_patches(struct patch *p)
2081 for (; p; p = p->next) {
2082 struct fragment *frag = p->fragments;
2084 swap(p->new_name, p->old_name);
2085 swap(p->new_mode, p->old_mode);
2086 swap(p->is_new, p->is_delete);
2087 swap(p->lines_added, p->lines_deleted);
2088 swap(p->old_sha1_prefix, p->new_sha1_prefix);
2090 for (; frag; frag = frag->next) {
2091 swap(frag->newpos, frag->oldpos);
2092 swap(frag->newlines, frag->oldlines);
2097 static const char pluses[] =
2098 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2099 static const char minuses[]=
2100 "----------------------------------------------------------------------";
2102 static void show_stats(struct patch *patch)
2104 struct strbuf qname = STRBUF_INIT;
2105 char *cp = patch->new_name ? patch->new_name : patch->old_name;
2106 int max, add, del;
2108 quote_c_style(cp, &qname, NULL, 0);
2111 * "scale" the filename
2113 max = max_len;
2114 if (max > 50)
2115 max = 50;
2117 if (qname.len > max) {
2118 cp = strchr(qname.buf + qname.len + 3 - max, '/');
2119 if (!cp)
2120 cp = qname.buf + qname.len + 3 - max;
2121 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
2124 if (patch->is_binary) {
2125 printf(" %-*s | Bin\n", max, qname.buf);
2126 strbuf_release(&qname);
2127 return;
2130 printf(" %-*s |", max, qname.buf);
2131 strbuf_release(&qname);
2134 * scale the add/delete
2136 max = max + max_change > 70 ? 70 - max : max_change;
2137 add = patch->lines_added;
2138 del = patch->lines_deleted;
2140 if (max_change > 0) {
2141 int total = ((add + del) * max + max_change / 2) / max_change;
2142 add = (add * max + max_change / 2) / max_change;
2143 del = total - add;
2145 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
2146 add, pluses, del, minuses);
2149 static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
2151 switch (st->st_mode & S_IFMT) {
2152 case S_IFLNK:
2153 if (strbuf_readlink(buf, path, st->st_size) < 0)
2154 return error(_("unable to read symlink %s"), path);
2155 return 0;
2156 case S_IFREG:
2157 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
2158 return error(_("unable to open or read %s"), path);
2159 convert_to_git(path, buf->buf, buf->len, buf, 0);
2160 return 0;
2161 default:
2162 return -1;
2167 * Update the preimage, and the common lines in postimage,
2168 * from buffer buf of length len. If postlen is 0 the postimage
2169 * is updated in place, otherwise it's updated on a new buffer
2170 * of length postlen
2173 static void update_pre_post_images(struct image *preimage,
2174 struct image *postimage,
2175 char *buf,
2176 size_t len, size_t postlen)
2178 int i, ctx, reduced;
2179 char *new, *old, *fixed;
2180 struct image fixed_preimage;
2183 * Update the preimage with whitespace fixes. Note that we
2184 * are not losing preimage->buf -- apply_one_fragment() will
2185 * free "oldlines".
2187 prepare_image(&fixed_preimage, buf, len, 1);
2188 assert(postlen
2189 ? fixed_preimage.nr == preimage->nr
2190 : fixed_preimage.nr <= preimage->nr);
2191 for (i = 0; i < fixed_preimage.nr; i++)
2192 fixed_preimage.line[i].flag = preimage->line[i].flag;
2193 free(preimage->line_allocated);
2194 *preimage = fixed_preimage;
2197 * Adjust the common context lines in postimage. This can be
2198 * done in-place when we are shrinking it with whitespace
2199 * fixing, but needs a new buffer when ignoring whitespace or
2200 * expanding leading tabs to spaces.
2202 * We trust the caller to tell us if the update can be done
2203 * in place (postlen==0) or not.
2205 old = postimage->buf;
2206 if (postlen)
2207 new = postimage->buf = xmalloc(postlen);
2208 else
2209 new = old;
2210 fixed = preimage->buf;
2212 for (i = reduced = ctx = 0; i < postimage->nr; i++) {
2213 size_t l_len = postimage->line[i].len;
2214 if (!(postimage->line[i].flag & LINE_COMMON)) {
2215 /* an added line -- no counterparts in preimage */
2216 memmove(new, old, l_len);
2217 old += l_len;
2218 new += l_len;
2219 continue;
2222 /* a common context -- skip it in the original postimage */
2223 old += l_len;
2225 /* and find the corresponding one in the fixed preimage */
2226 while (ctx < preimage->nr &&
2227 !(preimage->line[ctx].flag & LINE_COMMON)) {
2228 fixed += preimage->line[ctx].len;
2229 ctx++;
2233 * preimage is expected to run out, if the caller
2234 * fixed addition of trailing blank lines.
2236 if (preimage->nr <= ctx) {
2237 reduced++;
2238 continue;
2241 /* and copy it in, while fixing the line length */
2242 l_len = preimage->line[ctx].len;
2243 memcpy(new, fixed, l_len);
2244 new += l_len;
2245 fixed += l_len;
2246 postimage->line[i].len = l_len;
2247 ctx++;
2250 if (postlen
2251 ? postlen < new - postimage->buf
2252 : postimage->len < new - postimage->buf)
2253 die("BUG: caller miscounted postlen: asked %d, orig = %d, used = %d",
2254 (int)postlen, (int) postimage->len, (int)(new - postimage->buf));
2256 /* Fix the length of the whole thing */
2257 postimage->len = new - postimage->buf;
2258 postimage->nr -= reduced;
2261 static int line_by_line_fuzzy_match(struct image *img,
2262 struct image *preimage,
2263 struct image *postimage,
2264 unsigned long try,
2265 int try_lno,
2266 int preimage_limit)
2268 int i;
2269 size_t imgoff = 0;
2270 size_t preoff = 0;
2271 size_t postlen = postimage->len;
2272 size_t extra_chars;
2273 char *buf;
2274 char *preimage_eof;
2275 char *preimage_end;
2276 struct strbuf fixed;
2277 char *fixed_buf;
2278 size_t fixed_len;
2280 for (i = 0; i < preimage_limit; i++) {
2281 size_t prelen = preimage->line[i].len;
2282 size_t imglen = img->line[try_lno+i].len;
2284 if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,
2285 preimage->buf + preoff, prelen))
2286 return 0;
2287 if (preimage->line[i].flag & LINE_COMMON)
2288 postlen += imglen - prelen;
2289 imgoff += imglen;
2290 preoff += prelen;
2294 * Ok, the preimage matches with whitespace fuzz.
2296 * imgoff now holds the true length of the target that
2297 * matches the preimage before the end of the file.
2299 * Count the number of characters in the preimage that fall
2300 * beyond the end of the file and make sure that all of them
2301 * are whitespace characters. (This can only happen if
2302 * we are removing blank lines at the end of the file.)
2304 buf = preimage_eof = preimage->buf + preoff;
2305 for ( ; i < preimage->nr; i++)
2306 preoff += preimage->line[i].len;
2307 preimage_end = preimage->buf + preoff;
2308 for ( ; buf < preimage_end; buf++)
2309 if (!isspace(*buf))
2310 return 0;
2313 * Update the preimage and the common postimage context
2314 * lines to use the same whitespace as the target.
2315 * If whitespace is missing in the target (i.e.
2316 * if the preimage extends beyond the end of the file),
2317 * use the whitespace from the preimage.
2319 extra_chars = preimage_end - preimage_eof;
2320 strbuf_init(&fixed, imgoff + extra_chars);
2321 strbuf_add(&fixed, img->buf + try, imgoff);
2322 strbuf_add(&fixed, preimage_eof, extra_chars);
2323 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2324 update_pre_post_images(preimage, postimage,
2325 fixed_buf, fixed_len, postlen);
2326 return 1;
2329 static int match_fragment(struct image *img,
2330 struct image *preimage,
2331 struct image *postimage,
2332 unsigned long try,
2333 int try_lno,
2334 unsigned ws_rule,
2335 int match_beginning, int match_end)
2337 int i;
2338 char *fixed_buf, *buf, *orig, *target;
2339 struct strbuf fixed;
2340 size_t fixed_len, postlen;
2341 int preimage_limit;
2343 if (preimage->nr + try_lno <= img->nr) {
2345 * The hunk falls within the boundaries of img.
2347 preimage_limit = preimage->nr;
2348 if (match_end && (preimage->nr + try_lno != img->nr))
2349 return 0;
2350 } else if (ws_error_action == correct_ws_error &&
2351 (ws_rule & WS_BLANK_AT_EOF)) {
2353 * This hunk extends beyond the end of img, and we are
2354 * removing blank lines at the end of the file. This
2355 * many lines from the beginning of the preimage must
2356 * match with img, and the remainder of the preimage
2357 * must be blank.
2359 preimage_limit = img->nr - try_lno;
2360 } else {
2362 * The hunk extends beyond the end of the img and
2363 * we are not removing blanks at the end, so we
2364 * should reject the hunk at this position.
2366 return 0;
2369 if (match_beginning && try_lno)
2370 return 0;
2372 /* Quick hash check */
2373 for (i = 0; i < preimage_limit; i++)
2374 if ((img->line[try_lno + i].flag & LINE_PATCHED) ||
2375 (preimage->line[i].hash != img->line[try_lno + i].hash))
2376 return 0;
2378 if (preimage_limit == preimage->nr) {
2380 * Do we have an exact match? If we were told to match
2381 * at the end, size must be exactly at try+fragsize,
2382 * otherwise try+fragsize must be still within the preimage,
2383 * and either case, the old piece should match the preimage
2384 * exactly.
2386 if ((match_end
2387 ? (try + preimage->len == img->len)
2388 : (try + preimage->len <= img->len)) &&
2389 !memcmp(img->buf + try, preimage->buf, preimage->len))
2390 return 1;
2391 } else {
2393 * The preimage extends beyond the end of img, so
2394 * there cannot be an exact match.
2396 * There must be one non-blank context line that match
2397 * a line before the end of img.
2399 char *buf_end;
2401 buf = preimage->buf;
2402 buf_end = buf;
2403 for (i = 0; i < preimage_limit; i++)
2404 buf_end += preimage->line[i].len;
2406 for ( ; buf < buf_end; buf++)
2407 if (!isspace(*buf))
2408 break;
2409 if (buf == buf_end)
2410 return 0;
2414 * No exact match. If we are ignoring whitespace, run a line-by-line
2415 * fuzzy matching. We collect all the line length information because
2416 * we need it to adjust whitespace if we match.
2418 if (ws_ignore_action == ignore_ws_change)
2419 return line_by_line_fuzzy_match(img, preimage, postimage,
2420 try, try_lno, preimage_limit);
2422 if (ws_error_action != correct_ws_error)
2423 return 0;
2426 * The hunk does not apply byte-by-byte, but the hash says
2427 * it might with whitespace fuzz. We weren't asked to
2428 * ignore whitespace, we were asked to correct whitespace
2429 * errors, so let's try matching after whitespace correction.
2431 * While checking the preimage against the target, whitespace
2432 * errors in both fixed, we count how large the corresponding
2433 * postimage needs to be. The postimage prepared by
2434 * apply_one_fragment() has whitespace errors fixed on added
2435 * lines already, but the common lines were propagated as-is,
2436 * which may become longer when their whitespace errors are
2437 * fixed.
2440 /* First count added lines in postimage */
2441 postlen = 0;
2442 for (i = 0; i < postimage->nr; i++) {
2443 if (!(postimage->line[i].flag & LINE_COMMON))
2444 postlen += postimage->line[i].len;
2448 * The preimage may extend beyond the end of the file,
2449 * but in this loop we will only handle the part of the
2450 * preimage that falls within the file.
2452 strbuf_init(&fixed, preimage->len + 1);
2453 orig = preimage->buf;
2454 target = img->buf + try;
2455 for (i = 0; i < preimage_limit; i++) {
2456 size_t oldlen = preimage->line[i].len;
2457 size_t tgtlen = img->line[try_lno + i].len;
2458 size_t fixstart = fixed.len;
2459 struct strbuf tgtfix;
2460 int match;
2462 /* Try fixing the line in the preimage */
2463 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2465 /* Try fixing the line in the target */
2466 strbuf_init(&tgtfix, tgtlen);
2467 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2470 * If they match, either the preimage was based on
2471 * a version before our tree fixed whitespace breakage,
2472 * or we are lacking a whitespace-fix patch the tree
2473 * the preimage was based on already had (i.e. target
2474 * has whitespace breakage, the preimage doesn't).
2475 * In either case, we are fixing the whitespace breakages
2476 * so we might as well take the fix together with their
2477 * real change.
2479 match = (tgtfix.len == fixed.len - fixstart &&
2480 !memcmp(tgtfix.buf, fixed.buf + fixstart,
2481 fixed.len - fixstart));
2483 /* Add the length if this is common with the postimage */
2484 if (preimage->line[i].flag & LINE_COMMON)
2485 postlen += tgtfix.len;
2487 strbuf_release(&tgtfix);
2488 if (!match)
2489 goto unmatch_exit;
2491 orig += oldlen;
2492 target += tgtlen;
2497 * Now handle the lines in the preimage that falls beyond the
2498 * end of the file (if any). They will only match if they are
2499 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2500 * false).
2502 for ( ; i < preimage->nr; i++) {
2503 size_t fixstart = fixed.len; /* start of the fixed preimage */
2504 size_t oldlen = preimage->line[i].len;
2505 int j;
2507 /* Try fixing the line in the preimage */
2508 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2510 for (j = fixstart; j < fixed.len; j++)
2511 if (!isspace(fixed.buf[j]))
2512 goto unmatch_exit;
2514 orig += oldlen;
2518 * Yes, the preimage is based on an older version that still
2519 * has whitespace breakages unfixed, and fixing them makes the
2520 * hunk match. Update the context lines in the postimage.
2522 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2523 if (postlen < postimage->len)
2524 postlen = 0;
2525 update_pre_post_images(preimage, postimage,
2526 fixed_buf, fixed_len, postlen);
2527 return 1;
2529 unmatch_exit:
2530 strbuf_release(&fixed);
2531 return 0;
2534 static int find_pos(struct image *img,
2535 struct image *preimage,
2536 struct image *postimage,
2537 int line,
2538 unsigned ws_rule,
2539 int match_beginning, int match_end)
2541 int i;
2542 unsigned long backwards, forwards, try;
2543 int backwards_lno, forwards_lno, try_lno;
2546 * If match_beginning or match_end is specified, there is no
2547 * point starting from a wrong line that will never match and
2548 * wander around and wait for a match at the specified end.
2550 if (match_beginning)
2551 line = 0;
2552 else if (match_end)
2553 line = img->nr - preimage->nr;
2556 * Because the comparison is unsigned, the following test
2557 * will also take care of a negative line number that can
2558 * result when match_end and preimage is larger than the target.
2560 if ((size_t) line > img->nr)
2561 line = img->nr;
2563 try = 0;
2564 for (i = 0; i < line; i++)
2565 try += img->line[i].len;
2568 * There's probably some smart way to do this, but I'll leave
2569 * that to the smart and beautiful people. I'm simple and stupid.
2571 backwards = try;
2572 backwards_lno = line;
2573 forwards = try;
2574 forwards_lno = line;
2575 try_lno = line;
2577 for (i = 0; ; i++) {
2578 if (match_fragment(img, preimage, postimage,
2579 try, try_lno, ws_rule,
2580 match_beginning, match_end))
2581 return try_lno;
2583 again:
2584 if (backwards_lno == 0 && forwards_lno == img->nr)
2585 break;
2587 if (i & 1) {
2588 if (backwards_lno == 0) {
2589 i++;
2590 goto again;
2592 backwards_lno--;
2593 backwards -= img->line[backwards_lno].len;
2594 try = backwards;
2595 try_lno = backwards_lno;
2596 } else {
2597 if (forwards_lno == img->nr) {
2598 i++;
2599 goto again;
2601 forwards += img->line[forwards_lno].len;
2602 forwards_lno++;
2603 try = forwards;
2604 try_lno = forwards_lno;
2608 return -1;
2611 static void remove_first_line(struct image *img)
2613 img->buf += img->line[0].len;
2614 img->len -= img->line[0].len;
2615 img->line++;
2616 img->nr--;
2619 static void remove_last_line(struct image *img)
2621 img->len -= img->line[--img->nr].len;
2625 * The change from "preimage" and "postimage" has been found to
2626 * apply at applied_pos (counts in line numbers) in "img".
2627 * Update "img" to remove "preimage" and replace it with "postimage".
2629 static void update_image(struct apply_state *state,
2630 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 (!state->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 (state->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 (state->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(state, img, applied_pos, &preimage, &postimage);
2944 } else {
2945 if (state->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 (!state->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 (state->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 (!state->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 (!state->cached && verify_index_match(*ce, st))
3558 return error(_("%s: does not match index"), old_name);
3559 if (state->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 (!state->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 (state->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 (state->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 apply_state *state, struct patch *patch, int rmdir_empty)
4095 if (state->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 (!state->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(struct apply_state *state,
4107 const char *path,
4108 unsigned mode,
4109 void *buf,
4110 unsigned long size)
4112 struct stat st;
4113 struct cache_entry *ce;
4114 int namelen = strlen(path);
4115 unsigned ce_size = cache_entry_size(namelen);
4117 if (!state->update_index)
4118 return;
4120 ce = xcalloc(1, ce_size);
4121 memcpy(ce->name, path, namelen);
4122 ce->ce_mode = create_ce_mode(mode);
4123 ce->ce_flags = create_ce_flags(0);
4124 ce->ce_namelen = namelen;
4125 if (S_ISGITLINK(mode)) {
4126 const char *s;
4128 if (!skip_prefix(buf, "Subproject commit ", &s) ||
4129 get_sha1_hex(s, ce->sha1))
4130 die(_("corrupt patch for submodule %s"), path);
4131 } else {
4132 if (!state->cached) {
4133 if (lstat(path, &st) < 0)
4134 die_errno(_("unable to stat newly created file '%s'"),
4135 path);
4136 fill_stat_cache_info(ce, &st);
4138 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
4139 die(_("unable to create backing store for newly created file %s"), path);
4141 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
4142 die(_("unable to add cache entry for %s"), path);
4145 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
4147 int fd;
4148 struct strbuf nbuf = STRBUF_INIT;
4150 if (S_ISGITLINK(mode)) {
4151 struct stat st;
4152 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
4153 return 0;
4154 return mkdir(path, 0777);
4157 if (has_symlinks && S_ISLNK(mode))
4158 /* Although buf:size is counted string, it also is NUL
4159 * terminated.
4161 return symlink(buf, path);
4163 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
4164 if (fd < 0)
4165 return -1;
4167 if (convert_to_working_tree(path, buf, size, &nbuf)) {
4168 size = nbuf.len;
4169 buf = nbuf.buf;
4171 write_or_die(fd, buf, size);
4172 strbuf_release(&nbuf);
4174 if (close(fd) < 0)
4175 die_errno(_("closing file '%s'"), path);
4176 return 0;
4180 * We optimistically assume that the directories exist,
4181 * which is true 99% of the time anyway. If they don't,
4182 * we create them and try again.
4184 static void create_one_file(struct apply_state *state,
4185 char *path,
4186 unsigned mode,
4187 const char *buf,
4188 unsigned long size)
4190 if (state->cached)
4191 return;
4192 if (!try_create_file(path, mode, buf, size))
4193 return;
4195 if (errno == ENOENT) {
4196 if (safe_create_leading_directories(path))
4197 return;
4198 if (!try_create_file(path, mode, buf, size))
4199 return;
4202 if (errno == EEXIST || errno == EACCES) {
4203 /* We may be trying to create a file where a directory
4204 * used to be.
4206 struct stat st;
4207 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
4208 errno = EEXIST;
4211 if (errno == EEXIST) {
4212 unsigned int nr = getpid();
4214 for (;;) {
4215 char newpath[PATH_MAX];
4216 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
4217 if (!try_create_file(newpath, mode, buf, size)) {
4218 if (!rename(newpath, path))
4219 return;
4220 unlink_or_warn(newpath);
4221 break;
4223 if (errno != EEXIST)
4224 break;
4225 ++nr;
4228 die_errno(_("unable to write file '%s' mode %o"), path, mode);
4231 static void add_conflicted_stages_file(struct apply_state *state,
4232 struct patch *patch)
4234 int stage, namelen;
4235 unsigned ce_size, mode;
4236 struct cache_entry *ce;
4238 if (!state->update_index)
4239 return;
4240 namelen = strlen(patch->new_name);
4241 ce_size = cache_entry_size(namelen);
4242 mode = patch->new_mode ? patch->new_mode : (S_IFREG | 0644);
4244 remove_file_from_cache(patch->new_name);
4245 for (stage = 1; stage < 4; stage++) {
4246 if (is_null_oid(&patch->threeway_stage[stage - 1]))
4247 continue;
4248 ce = xcalloc(1, ce_size);
4249 memcpy(ce->name, patch->new_name, namelen);
4250 ce->ce_mode = create_ce_mode(mode);
4251 ce->ce_flags = create_ce_flags(stage);
4252 ce->ce_namelen = namelen;
4253 hashcpy(ce->sha1, patch->threeway_stage[stage - 1].hash);
4254 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
4255 die(_("unable to add cache entry for %s"), patch->new_name);
4259 static void create_file(struct apply_state *state, struct patch *patch)
4261 char *path = patch->new_name;
4262 unsigned mode = patch->new_mode;
4263 unsigned long size = patch->resultsize;
4264 char *buf = patch->result;
4266 if (!mode)
4267 mode = S_IFREG | 0644;
4268 create_one_file(state, path, mode, buf, size);
4270 if (patch->conflicted_threeway)
4271 add_conflicted_stages_file(state, patch);
4272 else
4273 add_index_file(state, path, mode, buf, size);
4276 /* phase zero is to remove, phase one is to create */
4277 static void write_out_one_result(struct apply_state *state,
4278 struct patch *patch,
4279 int phase)
4281 if (patch->is_delete > 0) {
4282 if (phase == 0)
4283 remove_file(state, patch, 1);
4284 return;
4286 if (patch->is_new > 0 || patch->is_copy) {
4287 if (phase == 1)
4288 create_file(state, patch);
4289 return;
4292 * Rename or modification boils down to the same
4293 * thing: remove the old, write the new
4295 if (phase == 0)
4296 remove_file(state, patch, patch->is_rename);
4297 if (phase == 1)
4298 create_file(state, patch);
4301 static int write_out_one_reject(struct apply_state *state, struct patch *patch)
4303 FILE *rej;
4304 char namebuf[PATH_MAX];
4305 struct fragment *frag;
4306 int cnt = 0;
4307 struct strbuf sb = STRBUF_INIT;
4309 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
4310 if (!frag->rejected)
4311 continue;
4312 cnt++;
4315 if (!cnt) {
4316 if (state->apply_verbosely)
4317 say_patch_name(stderr,
4318 _("Applied patch %s cleanly."), patch);
4319 return 0;
4322 /* This should not happen, because a removal patch that leaves
4323 * contents are marked "rejected" at the patch level.
4325 if (!patch->new_name)
4326 die(_("internal error"));
4328 /* Say this even without --verbose */
4329 strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",
4330 "Applying patch %%s with %d rejects...",
4331 cnt),
4332 cnt);
4333 say_patch_name(stderr, sb.buf, patch);
4334 strbuf_release(&sb);
4336 cnt = strlen(patch->new_name);
4337 if (ARRAY_SIZE(namebuf) <= cnt + 5) {
4338 cnt = ARRAY_SIZE(namebuf) - 5;
4339 warning(_("truncating .rej filename to %.*s.rej"),
4340 cnt - 1, patch->new_name);
4342 memcpy(namebuf, patch->new_name, cnt);
4343 memcpy(namebuf + cnt, ".rej", 5);
4345 rej = fopen(namebuf, "w");
4346 if (!rej)
4347 return error(_("cannot open %s: %s"), namebuf, strerror(errno));
4349 /* Normal git tools never deal with .rej, so do not pretend
4350 * this is a git patch by saying --git or giving extended
4351 * headers. While at it, maybe please "kompare" that wants
4352 * the trailing TAB and some garbage at the end of line ;-).
4354 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
4355 patch->new_name, patch->new_name);
4356 for (cnt = 1, frag = patch->fragments;
4357 frag;
4358 cnt++, frag = frag->next) {
4359 if (!frag->rejected) {
4360 fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);
4361 continue;
4363 fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);
4364 fprintf(rej, "%.*s", frag->size, frag->patch);
4365 if (frag->patch[frag->size-1] != '\n')
4366 fputc('\n', rej);
4368 fclose(rej);
4369 return -1;
4372 static int write_out_results(struct apply_state *state, struct patch *list)
4374 int phase;
4375 int errs = 0;
4376 struct patch *l;
4377 struct string_list cpath = STRING_LIST_INIT_DUP;
4379 for (phase = 0; phase < 2; phase++) {
4380 l = list;
4381 while (l) {
4382 if (l->rejected)
4383 errs = 1;
4384 else {
4385 write_out_one_result(state, l, phase);
4386 if (phase == 1) {
4387 if (write_out_one_reject(state, l))
4388 errs = 1;
4389 if (l->conflicted_threeway) {
4390 string_list_append(&cpath, l->new_name);
4391 errs = 1;
4395 l = l->next;
4399 if (cpath.nr) {
4400 struct string_list_item *item;
4402 string_list_sort(&cpath);
4403 for_each_string_list_item(item, &cpath)
4404 fprintf(stderr, "U %s\n", item->string);
4405 string_list_clear(&cpath, 0);
4407 rerere(0);
4410 return errs;
4413 static struct lock_file lock_file;
4415 #define INACCURATE_EOF (1<<0)
4416 #define RECOUNT (1<<1)
4418 static int apply_patch(struct apply_state *state,
4419 int fd,
4420 const char *filename,
4421 int options)
4423 size_t offset;
4424 struct strbuf buf = STRBUF_INIT; /* owns the patch text */
4425 struct patch *list = NULL, **listp = &list;
4426 int skipped_patch = 0;
4428 patch_input_file = filename;
4429 read_patch_file(&buf, fd);
4430 offset = 0;
4431 while (offset < buf.len) {
4432 struct patch *patch;
4433 int nr;
4435 patch = xcalloc(1, sizeof(*patch));
4436 patch->inaccurate_eof = !!(options & INACCURATE_EOF);
4437 patch->recount = !!(options & RECOUNT);
4438 nr = parse_chunk(state, buf.buf + offset, buf.len - offset, patch);
4439 if (nr < 0) {
4440 free_patch(patch);
4441 break;
4443 if (state->apply_in_reverse)
4444 reverse_patches(patch);
4445 if (use_patch(state, patch)) {
4446 patch_stats(patch);
4447 *listp = patch;
4448 listp = &patch->next;
4450 else {
4451 if (state->apply_verbosely)
4452 say_patch_name(stderr, _("Skipped patch '%s'."), patch);
4453 free_patch(patch);
4454 skipped_patch++;
4456 offset += nr;
4459 if (!list && !skipped_patch)
4460 die(_("unrecognized input"));
4462 if (whitespace_error && (ws_error_action == die_on_ws_error))
4463 apply = 0;
4465 state->update_index = state->check_index && apply;
4466 if (state->update_index && newfd < 0)
4467 newfd = hold_locked_index(&lock_file, 1);
4469 if (state->check_index) {
4470 if (read_cache() < 0)
4471 die(_("unable to read index file"));
4474 if ((state->check || apply) &&
4475 check_patch_list(state, list) < 0 &&
4476 !state->apply_with_reject)
4477 exit(1);
4479 if (apply && write_out_results(state, list)) {
4480 if (state->apply_with_reject)
4481 exit(1);
4482 /* with --3way, we still need to write the index out */
4483 return 1;
4486 if (fake_ancestor)
4487 build_fake_ancestor(list, fake_ancestor);
4489 if (state->diffstat)
4490 stat_patch_list(list);
4492 if (state->numstat)
4493 numstat_patch_list(list);
4495 if (summary)
4496 summary_patch_list(list);
4498 free_patch_list(list);
4499 strbuf_release(&buf);
4500 string_list_clear(&fn_table, 0);
4501 return 0;
4504 static void git_apply_config(void)
4506 git_config_get_string_const("apply.whitespace", &apply_default_whitespace);
4507 git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);
4508 git_config(git_default_config, NULL);
4511 static int option_parse_exclude(const struct option *opt,
4512 const char *arg, int unset)
4514 add_name_limit(arg, 1);
4515 return 0;
4518 static int option_parse_include(const struct option *opt,
4519 const char *arg, int unset)
4521 add_name_limit(arg, 0);
4522 has_include = 1;
4523 return 0;
4526 static int option_parse_p(const struct option *opt,
4527 const char *arg, int unset)
4529 state_p_value = atoi(arg);
4530 p_value_known = 1;
4531 return 0;
4534 static int option_parse_space_change(const struct option *opt,
4535 const char *arg, int unset)
4537 if (unset)
4538 ws_ignore_action = ignore_ws_none;
4539 else
4540 ws_ignore_action = ignore_ws_change;
4541 return 0;
4544 static int option_parse_whitespace(const struct option *opt,
4545 const char *arg, int unset)
4547 const char **whitespace_option = opt->value;
4549 *whitespace_option = arg;
4550 parse_whitespace_option(arg);
4551 return 0;
4554 static int option_parse_directory(const struct option *opt,
4555 const char *arg, int unset)
4557 strbuf_reset(&root);
4558 strbuf_addstr(&root, arg);
4559 strbuf_complete(&root, '/');
4560 return 0;
4563 static void init_apply_state(struct apply_state *state, const char *prefix)
4565 memset(state, 0, sizeof(*state));
4566 state->prefix = prefix;
4567 state->prefix_length = state->prefix ? strlen(state->prefix) : 0;
4569 git_apply_config();
4570 if (apply_default_whitespace)
4571 parse_whitespace_option(apply_default_whitespace);
4572 if (apply_default_ignorewhitespace)
4573 parse_ignorewhitespace_option(apply_default_ignorewhitespace);
4576 static void clear_apply_state(struct apply_state *state)
4578 /* empty for now */
4581 int cmd_apply(int argc, const char **argv, const char *prefix)
4583 int i;
4584 int errs = 0;
4585 int is_not_gitdir = !startup_info->have_repository;
4586 int force_apply = 0;
4587 int options = 0;
4588 int read_stdin = 1;
4589 struct apply_state state;
4591 const char *whitespace_option = NULL;
4593 struct option builtin_apply_options[] = {
4594 { OPTION_CALLBACK, 0, "exclude", NULL, N_("path"),
4595 N_("don't apply changes matching the given path"),
4596 0, option_parse_exclude },
4597 { OPTION_CALLBACK, 0, "include", NULL, N_("path"),
4598 N_("apply changes matching the given path"),
4599 0, option_parse_include },
4600 { OPTION_CALLBACK, 'p', NULL, NULL, N_("num"),
4601 N_("remove <num> leading slashes from traditional diff paths"),
4602 0, option_parse_p },
4603 OPT_BOOL(0, "no-add", &no_add,
4604 N_("ignore additions made by the patch")),
4605 OPT_BOOL(0, "stat", &state.diffstat,
4606 N_("instead of applying the patch, output diffstat for the input")),
4607 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
4608 OPT_NOOP_NOARG(0, "binary"),
4609 OPT_BOOL(0, "numstat", &state.numstat,
4610 N_("show number of added and deleted lines in decimal notation")),
4611 OPT_BOOL(0, "summary", &summary,
4612 N_("instead of applying the patch, output a summary for the input")),
4613 OPT_BOOL(0, "check", &state.check,
4614 N_("instead of applying the patch, see if the patch is applicable")),
4615 OPT_BOOL(0, "index", &state.check_index,
4616 N_("make sure the patch is applicable to the current index")),
4617 OPT_BOOL(0, "cached", &state.cached,
4618 N_("apply a patch without touching the working tree")),
4619 OPT_BOOL(0, "unsafe-paths", &unsafe_paths,
4620 N_("accept a patch that touches outside the working area")),
4621 OPT_BOOL(0, "apply", &force_apply,
4622 N_("also apply the patch (use with --stat/--summary/--check)")),
4623 OPT_BOOL('3', "3way", &threeway,
4624 N_( "attempt three-way merge if a patch does not apply")),
4625 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor,
4626 N_("build a temporary index based on embedded index information")),
4627 /* Think twice before adding "--nul" synonym to this */
4628 OPT_SET_INT('z', NULL, &line_termination,
4629 N_("paths are separated with NUL character"), '\0'),
4630 OPT_INTEGER('C', NULL, &p_context,
4631 N_("ensure at least <n> lines of context match")),
4632 { OPTION_CALLBACK, 0, "whitespace", &whitespace_option, N_("action"),
4633 N_("detect new or modified lines that have whitespace errors"),
4634 0, option_parse_whitespace },
4635 { OPTION_CALLBACK, 0, "ignore-space-change", NULL, NULL,
4636 N_("ignore changes in whitespace when finding context"),
4637 PARSE_OPT_NOARG, option_parse_space_change },
4638 { OPTION_CALLBACK, 0, "ignore-whitespace", NULL, NULL,
4639 N_("ignore changes in whitespace when finding context"),
4640 PARSE_OPT_NOARG, option_parse_space_change },
4641 OPT_BOOL('R', "reverse", &state.apply_in_reverse,
4642 N_("apply the patch in reverse")),
4643 OPT_BOOL(0, "unidiff-zero", &state.unidiff_zero,
4644 N_("don't expect at least one line of context")),
4645 OPT_BOOL(0, "reject", &state.apply_with_reject,
4646 N_("leave the rejected hunks in corresponding *.rej files")),
4647 OPT_BOOL(0, "allow-overlap", &state.allow_overlap,
4648 N_("allow overlapping hunks")),
4649 OPT__VERBOSE(&state.apply_verbosely, N_("be verbose")),
4650 OPT_BIT(0, "inaccurate-eof", &options,
4651 N_("tolerate incorrectly detected missing new-line at the end of file"),
4652 INACCURATE_EOF),
4653 OPT_BIT(0, "recount", &options,
4654 N_("do not trust the line counts in the hunk headers"),
4655 RECOUNT),
4656 { OPTION_CALLBACK, 0, "directory", NULL, N_("root"),
4657 N_("prepend <root> to all filenames"),
4658 0, option_parse_directory },
4659 OPT_END()
4662 init_apply_state(&state, prefix);
4664 argc = parse_options(argc, argv, state.prefix, builtin_apply_options,
4665 apply_usage, 0);
4667 if (state.apply_with_reject && threeway)
4668 die("--reject and --3way cannot be used together.");
4669 if (state.cached && threeway)
4670 die("--cached and --3way cannot be used together.");
4671 if (threeway) {
4672 if (is_not_gitdir)
4673 die(_("--3way outside a repository"));
4674 state.check_index = 1;
4676 if (state.apply_with_reject)
4677 apply = state.apply_verbosely = 1;
4678 if (!force_apply && (state.diffstat || state.numstat || summary || state.check || fake_ancestor))
4679 apply = 0;
4680 if (state.check_index && is_not_gitdir)
4681 die(_("--index outside a repository"));
4682 if (state.cached) {
4683 if (is_not_gitdir)
4684 die(_("--cached outside a repository"));
4685 state.check_index = 1;
4687 if (state.check_index)
4688 unsafe_paths = 0;
4690 for (i = 0; i < argc; i++) {
4691 const char *arg = argv[i];
4692 int fd;
4694 if (!strcmp(arg, "-")) {
4695 errs |= apply_patch(&state, 0, "<stdin>", options);
4696 read_stdin = 0;
4697 continue;
4698 } else if (0 < state.prefix_length)
4699 arg = prefix_filename(state.prefix,
4700 state.prefix_length,
4701 arg);
4703 fd = open(arg, O_RDONLY);
4704 if (fd < 0)
4705 die_errno(_("can't open patch '%s'"), arg);
4706 read_stdin = 0;
4707 set_default_whitespace_mode(whitespace_option);
4708 errs |= apply_patch(&state, fd, arg, options);
4709 close(fd);
4711 set_default_whitespace_mode(whitespace_option);
4712 if (read_stdin)
4713 errs |= apply_patch(&state, 0, "<stdin>", options);
4714 if (whitespace_error) {
4715 if (squelch_whitespace_errors &&
4716 squelch_whitespace_errors < whitespace_error) {
4717 int squelched =
4718 whitespace_error - squelch_whitespace_errors;
4719 warning(Q_("squelched %d whitespace error",
4720 "squelched %d whitespace errors",
4721 squelched),
4722 squelched);
4724 if (ws_error_action == die_on_ws_error)
4725 die(Q_("%d line adds whitespace errors.",
4726 "%d lines add whitespace errors.",
4727 whitespace_error),
4728 whitespace_error);
4729 if (applied_after_fixing_ws && apply)
4730 warning("%d line%s applied after"
4731 " fixing whitespace errors.",
4732 applied_after_fixing_ws,
4733 applied_after_fixing_ws == 1 ? "" : "s");
4734 else if (whitespace_error)
4735 warning(Q_("%d line adds whitespace errors.",
4736 "%d lines add whitespace errors.",
4737 whitespace_error),
4738 whitespace_error);
4741 if (state.update_index) {
4742 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
4743 die(_("Unable to write new index file"));
4746 clear_apply_state(&state);
4748 return !!errs;