builtin/apply: move 'fake_ancestor' global into 'struct apply_state'
[git/gitweb.git] / builtin / apply.c
blob59b0f1b00a3f93bb6d7af38ae76045a5c4a0f8e4
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 */
37 int summary; /* just report creation, deletion, etc, and don't actually apply */
39 /* These boolean parameters control how the apply is done */
40 int allow_overlap;
41 int apply_in_reverse;
42 int apply_with_reject;
43 int apply_verbosely;
44 int no_add;
45 int threeway;
46 int unidiff_zero;
47 int unsafe_paths;
49 /* Other non boolean parameters */
50 const char *fake_ancestor;
51 int line_termination;
54 static int newfd = -1;
56 static int state_p_value = 1;
57 static int p_value_known;
58 static int apply = 1;
59 static unsigned int p_context = UINT_MAX;
60 static const char * const apply_usage[] = {
61 N_("git apply [<options>] [<patch>...]"),
62 NULL
65 static enum ws_error_action {
66 nowarn_ws_error,
67 warn_on_ws_error,
68 die_on_ws_error,
69 correct_ws_error
70 } ws_error_action = warn_on_ws_error;
71 static int whitespace_error;
72 static int squelch_whitespace_errors = 5;
73 static int applied_after_fixing_ws;
75 static enum ws_ignore {
76 ignore_ws_none,
77 ignore_ws_change
78 } ws_ignore_action = ignore_ws_none;
81 static const char *patch_input_file;
82 static struct strbuf root = STRBUF_INIT;
84 static void parse_whitespace_option(const char *option)
86 if (!option) {
87 ws_error_action = warn_on_ws_error;
88 return;
90 if (!strcmp(option, "warn")) {
91 ws_error_action = warn_on_ws_error;
92 return;
94 if (!strcmp(option, "nowarn")) {
95 ws_error_action = nowarn_ws_error;
96 return;
98 if (!strcmp(option, "error")) {
99 ws_error_action = die_on_ws_error;
100 return;
102 if (!strcmp(option, "error-all")) {
103 ws_error_action = die_on_ws_error;
104 squelch_whitespace_errors = 0;
105 return;
107 if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
108 ws_error_action = correct_ws_error;
109 return;
111 die(_("unrecognized whitespace option '%s'"), option);
114 static void parse_ignorewhitespace_option(const char *option)
116 if (!option || !strcmp(option, "no") ||
117 !strcmp(option, "false") || !strcmp(option, "never") ||
118 !strcmp(option, "none")) {
119 ws_ignore_action = ignore_ws_none;
120 return;
122 if (!strcmp(option, "change")) {
123 ws_ignore_action = ignore_ws_change;
124 return;
126 die(_("unrecognized whitespace ignore option '%s'"), option);
129 static void set_default_whitespace_mode(const char *whitespace_option)
131 if (!whitespace_option && !apply_default_whitespace)
132 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error);
136 * For "diff-stat" like behaviour, we keep track of the biggest change
137 * we've seen, and the longest filename. That allows us to do simple
138 * scaling.
140 static int max_change, max_len;
143 * Various "current state", notably line numbers and what
144 * file (and how) we're patching right now.. The "is_xxxx"
145 * things are flags, where -1 means "don't know yet".
147 static int state_linenr = 1;
150 * This represents one "hunk" from a patch, starting with
151 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
152 * patch text is pointed at by patch, and its byte length
153 * is stored in size. leading and trailing are the number
154 * of context lines.
156 struct fragment {
157 unsigned long leading, trailing;
158 unsigned long oldpos, oldlines;
159 unsigned long newpos, newlines;
161 * 'patch' is usually borrowed from buf in apply_patch(),
162 * but some codepaths store an allocated buffer.
164 const char *patch;
165 unsigned free_patch:1,
166 rejected:1;
167 int size;
168 int linenr;
169 struct fragment *next;
173 * When dealing with a binary patch, we reuse "leading" field
174 * to store the type of the binary hunk, either deflated "delta"
175 * or deflated "literal".
177 #define binary_patch_method leading
178 #define BINARY_DELTA_DEFLATED 1
179 #define BINARY_LITERAL_DEFLATED 2
182 * This represents a "patch" to a file, both metainfo changes
183 * such as creation/deletion, filemode and content changes represented
184 * as a series of fragments.
186 struct patch {
187 char *new_name, *old_name, *def_name;
188 unsigned int old_mode, new_mode;
189 int is_new, is_delete; /* -1 = unknown, 0 = false, 1 = true */
190 int rejected;
191 unsigned ws_rule;
192 int lines_added, lines_deleted;
193 int score;
194 unsigned int is_toplevel_relative:1;
195 unsigned int inaccurate_eof:1;
196 unsigned int is_binary:1;
197 unsigned int is_copy:1;
198 unsigned int is_rename:1;
199 unsigned int recount:1;
200 unsigned int conflicted_threeway:1;
201 unsigned int direct_to_threeway:1;
202 struct fragment *fragments;
203 char *result;
204 size_t resultsize;
205 char old_sha1_prefix[41];
206 char new_sha1_prefix[41];
207 struct patch *next;
209 /* three-way fallback result */
210 struct object_id threeway_stage[3];
213 static void free_fragment_list(struct fragment *list)
215 while (list) {
216 struct fragment *next = list->next;
217 if (list->free_patch)
218 free((char *)list->patch);
219 free(list);
220 list = next;
224 static void free_patch(struct patch *patch)
226 free_fragment_list(patch->fragments);
227 free(patch->def_name);
228 free(patch->old_name);
229 free(patch->new_name);
230 free(patch->result);
231 free(patch);
234 static void free_patch_list(struct patch *list)
236 while (list) {
237 struct patch *next = list->next;
238 free_patch(list);
239 list = next;
244 * A line in a file, len-bytes long (includes the terminating LF,
245 * except for an incomplete line at the end if the file ends with
246 * one), and its contents hashes to 'hash'.
248 struct line {
249 size_t len;
250 unsigned hash : 24;
251 unsigned flag : 8;
252 #define LINE_COMMON 1
253 #define LINE_PATCHED 2
257 * This represents a "file", which is an array of "lines".
259 struct image {
260 char *buf;
261 size_t len;
262 size_t nr;
263 size_t alloc;
264 struct line *line_allocated;
265 struct line *line;
269 * Records filenames that have been touched, in order to handle
270 * the case where more than one patches touch the same file.
273 static struct string_list fn_table;
275 static uint32_t hash_line(const char *cp, size_t len)
277 size_t i;
278 uint32_t h;
279 for (i = 0, h = 0; i < len; i++) {
280 if (!isspace(cp[i])) {
281 h = h * 3 + (cp[i] & 0xff);
284 return h;
288 * Compare lines s1 of length n1 and s2 of length n2, ignoring
289 * whitespace difference. Returns 1 if they match, 0 otherwise
291 static int fuzzy_matchlines(const char *s1, size_t n1,
292 const char *s2, size_t n2)
294 const char *last1 = s1 + n1 - 1;
295 const char *last2 = s2 + n2 - 1;
296 int result = 0;
298 /* ignore line endings */
299 while ((*last1 == '\r') || (*last1 == '\n'))
300 last1--;
301 while ((*last2 == '\r') || (*last2 == '\n'))
302 last2--;
304 /* skip leading whitespaces, if both begin with whitespace */
305 if (s1 <= last1 && s2 <= last2 && isspace(*s1) && isspace(*s2)) {
306 while (isspace(*s1) && (s1 <= last1))
307 s1++;
308 while (isspace(*s2) && (s2 <= last2))
309 s2++;
311 /* early return if both lines are empty */
312 if ((s1 > last1) && (s2 > last2))
313 return 1;
314 while (!result) {
315 result = *s1++ - *s2++;
317 * Skip whitespace inside. We check for whitespace on
318 * both buffers because we don't want "a b" to match
319 * "ab"
321 if (isspace(*s1) && isspace(*s2)) {
322 while (isspace(*s1) && s1 <= last1)
323 s1++;
324 while (isspace(*s2) && s2 <= last2)
325 s2++;
328 * If we reached the end on one side only,
329 * lines don't match
331 if (
332 ((s2 > last2) && (s1 <= last1)) ||
333 ((s1 > last1) && (s2 <= last2)))
334 return 0;
335 if ((s1 > last1) && (s2 > last2))
336 break;
339 return !result;
342 static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
344 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
345 img->line_allocated[img->nr].len = len;
346 img->line_allocated[img->nr].hash = hash_line(bol, len);
347 img->line_allocated[img->nr].flag = flag;
348 img->nr++;
352 * "buf" has the file contents to be patched (read from various sources).
353 * attach it to "image" and add line-based index to it.
354 * "image" now owns the "buf".
356 static void prepare_image(struct image *image, char *buf, size_t len,
357 int prepare_linetable)
359 const char *cp, *ep;
361 memset(image, 0, sizeof(*image));
362 image->buf = buf;
363 image->len = len;
365 if (!prepare_linetable)
366 return;
368 ep = image->buf + image->len;
369 cp = image->buf;
370 while (cp < ep) {
371 const char *next;
372 for (next = cp; next < ep && *next != '\n'; next++)
374 if (next < ep)
375 next++;
376 add_line_info(image, cp, next - cp, 0);
377 cp = next;
379 image->line = image->line_allocated;
382 static void clear_image(struct image *image)
384 free(image->buf);
385 free(image->line_allocated);
386 memset(image, 0, sizeof(*image));
389 /* fmt must contain _one_ %s and no other substitution */
390 static void say_patch_name(FILE *output, const char *fmt, struct patch *patch)
392 struct strbuf sb = STRBUF_INIT;
394 if (patch->old_name && patch->new_name &&
395 strcmp(patch->old_name, patch->new_name)) {
396 quote_c_style(patch->old_name, &sb, NULL, 0);
397 strbuf_addstr(&sb, " => ");
398 quote_c_style(patch->new_name, &sb, NULL, 0);
399 } else {
400 const char *n = patch->new_name;
401 if (!n)
402 n = patch->old_name;
403 quote_c_style(n, &sb, NULL, 0);
405 fprintf(output, fmt, sb.buf);
406 fputc('\n', output);
407 strbuf_release(&sb);
410 #define SLOP (16)
412 static void read_patch_file(struct strbuf *sb, int fd)
414 if (strbuf_read(sb, fd, 0) < 0)
415 die_errno("git apply: failed to read");
418 * Make sure that we have some slop in the buffer
419 * so that we can do speculative "memcmp" etc, and
420 * see to it that it is NUL-filled.
422 strbuf_grow(sb, SLOP);
423 memset(sb->buf + sb->len, 0, SLOP);
426 static unsigned long linelen(const char *buffer, unsigned long size)
428 unsigned long len = 0;
429 while (size--) {
430 len++;
431 if (*buffer++ == '\n')
432 break;
434 return len;
437 static int is_dev_null(const char *str)
439 return skip_prefix(str, "/dev/null", &str) && isspace(*str);
442 #define TERM_SPACE 1
443 #define TERM_TAB 2
445 static int name_terminate(const char *name, int namelen, int c, int terminate)
447 if (c == ' ' && !(terminate & TERM_SPACE))
448 return 0;
449 if (c == '\t' && !(terminate & TERM_TAB))
450 return 0;
452 return 1;
455 /* remove double slashes to make --index work with such filenames */
456 static char *squash_slash(char *name)
458 int i = 0, j = 0;
460 if (!name)
461 return NULL;
463 while (name[i]) {
464 if ((name[j++] = name[i++]) == '/')
465 while (name[i] == '/')
466 i++;
468 name[j] = '\0';
469 return name;
472 static char *find_name_gnu(const char *line, const char *def, int p_value)
474 struct strbuf name = STRBUF_INIT;
475 char *cp;
478 * Proposed "new-style" GNU patch/diff format; see
479 * http://marc.info/?l=git&m=112927316408690&w=2
481 if (unquote_c_style(&name, line, NULL)) {
482 strbuf_release(&name);
483 return NULL;
486 for (cp = name.buf; p_value; p_value--) {
487 cp = strchr(cp, '/');
488 if (!cp) {
489 strbuf_release(&name);
490 return NULL;
492 cp++;
495 strbuf_remove(&name, 0, cp - name.buf);
496 if (root.len)
497 strbuf_insert(&name, 0, root.buf, root.len);
498 return squash_slash(strbuf_detach(&name, NULL));
501 static size_t sane_tz_len(const char *line, size_t len)
503 const char *tz, *p;
505 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
506 return 0;
507 tz = line + len - strlen(" +0500");
509 if (tz[1] != '+' && tz[1] != '-')
510 return 0;
512 for (p = tz + 2; p != line + len; p++)
513 if (!isdigit(*p))
514 return 0;
516 return line + len - tz;
519 static size_t tz_with_colon_len(const char *line, size_t len)
521 const char *tz, *p;
523 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
524 return 0;
525 tz = line + len - strlen(" +08:00");
527 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
528 return 0;
529 p = tz + 2;
530 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
531 !isdigit(*p++) || !isdigit(*p++))
532 return 0;
534 return line + len - tz;
537 static size_t date_len(const char *line, size_t len)
539 const char *date, *p;
541 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
542 return 0;
543 p = date = line + len - strlen("72-02-05");
545 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
546 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
547 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */
548 return 0;
550 if (date - line >= strlen("19") &&
551 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */
552 date -= strlen("19");
554 return line + len - date;
557 static size_t short_time_len(const char *line, size_t len)
559 const char *time, *p;
561 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
562 return 0;
563 p = time = line + len - strlen(" 07:01:32");
565 /* Permit 1-digit hours? */
566 if (*p++ != ' ' ||
567 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
568 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
569 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */
570 return 0;
572 return line + len - time;
575 static size_t fractional_time_len(const char *line, size_t len)
577 const char *p;
578 size_t n;
580 /* Expected format: 19:41:17.620000023 */
581 if (!len || !isdigit(line[len - 1]))
582 return 0;
583 p = line + len - 1;
585 /* Fractional seconds. */
586 while (p > line && isdigit(*p))
587 p--;
588 if (*p != '.')
589 return 0;
591 /* Hours, minutes, and whole seconds. */
592 n = short_time_len(line, p - line);
593 if (!n)
594 return 0;
596 return line + len - p + n;
599 static size_t trailing_spaces_len(const char *line, size_t len)
601 const char *p;
603 /* Expected format: ' ' x (1 or more) */
604 if (!len || line[len - 1] != ' ')
605 return 0;
607 p = line + len;
608 while (p != line) {
609 p--;
610 if (*p != ' ')
611 return line + len - (p + 1);
614 /* All spaces! */
615 return len;
618 static size_t diff_timestamp_len(const char *line, size_t len)
620 const char *end = line + len;
621 size_t n;
624 * Posix: 2010-07-05 19:41:17
625 * GNU: 2010-07-05 19:41:17.620000023 -0500
628 if (!isdigit(end[-1]))
629 return 0;
631 n = sane_tz_len(line, end - line);
632 if (!n)
633 n = tz_with_colon_len(line, end - line);
634 end -= n;
636 n = short_time_len(line, end - line);
637 if (!n)
638 n = fractional_time_len(line, end - line);
639 end -= n;
641 n = date_len(line, end - line);
642 if (!n) /* No date. Too bad. */
643 return 0;
644 end -= n;
646 if (end == line) /* No space before date. */
647 return 0;
648 if (end[-1] == '\t') { /* Success! */
649 end--;
650 return line + len - end;
652 if (end[-1] != ' ') /* No space before date. */
653 return 0;
655 /* Whitespace damage. */
656 end -= trailing_spaces_len(line, end - line);
657 return line + len - end;
660 static char *find_name_common(const char *line, const char *def,
661 int p_value, const char *end, int terminate)
663 int len;
664 const char *start = NULL;
666 if (p_value == 0)
667 start = line;
668 while (line != end) {
669 char c = *line;
671 if (!end && isspace(c)) {
672 if (c == '\n')
673 break;
674 if (name_terminate(start, line-start, c, terminate))
675 break;
677 line++;
678 if (c == '/' && !--p_value)
679 start = line;
681 if (!start)
682 return squash_slash(xstrdup_or_null(def));
683 len = line - start;
684 if (!len)
685 return squash_slash(xstrdup_or_null(def));
688 * Generally we prefer the shorter name, especially
689 * if the other one is just a variation of that with
690 * something else tacked on to the end (ie "file.orig"
691 * or "file~").
693 if (def) {
694 int deflen = strlen(def);
695 if (deflen < len && !strncmp(start, def, deflen))
696 return squash_slash(xstrdup(def));
699 if (root.len) {
700 char *ret = xstrfmt("%s%.*s", root.buf, len, start);
701 return squash_slash(ret);
704 return squash_slash(xmemdupz(start, len));
707 static char *find_name(const char *line, char *def, int p_value, int terminate)
709 if (*line == '"') {
710 char *name = find_name_gnu(line, def, p_value);
711 if (name)
712 return name;
715 return find_name_common(line, def, p_value, NULL, terminate);
718 static char *find_name_traditional(const char *line, char *def, int p_value)
720 size_t len;
721 size_t date_len;
723 if (*line == '"') {
724 char *name = find_name_gnu(line, def, p_value);
725 if (name)
726 return name;
729 len = strchrnul(line, '\n') - line;
730 date_len = diff_timestamp_len(line, len);
731 if (!date_len)
732 return find_name_common(line, def, p_value, NULL, TERM_TAB);
733 len -= date_len;
735 return find_name_common(line, def, p_value, line + len, 0);
738 static int count_slashes(const char *cp)
740 int cnt = 0;
741 char ch;
743 while ((ch = *cp++))
744 if (ch == '/')
745 cnt++;
746 return cnt;
750 * Given the string after "--- " or "+++ ", guess the appropriate
751 * p_value for the given patch.
753 static int guess_p_value(struct apply_state *state, const char *nameline)
755 char *name, *cp;
756 int val = -1;
758 if (is_dev_null(nameline))
759 return -1;
760 name = find_name_traditional(nameline, NULL, 0);
761 if (!name)
762 return -1;
763 cp = strchr(name, '/');
764 if (!cp)
765 val = 0;
766 else if (state->prefix) {
768 * Does it begin with "a/$our-prefix" and such? Then this is
769 * very likely to apply to our directory.
771 if (!strncmp(name, state->prefix, state->prefix_length))
772 val = count_slashes(state->prefix);
773 else {
774 cp++;
775 if (!strncmp(cp, state->prefix, state->prefix_length))
776 val = count_slashes(state->prefix) + 1;
779 free(name);
780 return val;
784 * Does the ---/+++ line have the POSIX timestamp after the last HT?
785 * GNU diff puts epoch there to signal a creation/deletion event. Is
786 * this such a timestamp?
788 static int has_epoch_timestamp(const char *nameline)
791 * We are only interested in epoch timestamp; any non-zero
792 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
793 * For the same reason, the date must be either 1969-12-31 or
794 * 1970-01-01, and the seconds part must be "00".
796 const char stamp_regexp[] =
797 "^(1969-12-31|1970-01-01)"
799 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
801 "([-+][0-2][0-9]:?[0-5][0-9])\n";
802 const char *timestamp = NULL, *cp, *colon;
803 static regex_t *stamp;
804 regmatch_t m[10];
805 int zoneoffset;
806 int hourminute;
807 int status;
809 for (cp = nameline; *cp != '\n'; cp++) {
810 if (*cp == '\t')
811 timestamp = cp + 1;
813 if (!timestamp)
814 return 0;
815 if (!stamp) {
816 stamp = xmalloc(sizeof(*stamp));
817 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
818 warning(_("Cannot prepare timestamp regexp %s"),
819 stamp_regexp);
820 return 0;
824 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
825 if (status) {
826 if (status != REG_NOMATCH)
827 warning(_("regexec returned %d for input: %s"),
828 status, timestamp);
829 return 0;
832 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
833 if (*colon == ':')
834 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
835 else
836 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
837 if (timestamp[m[3].rm_so] == '-')
838 zoneoffset = -zoneoffset;
841 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
842 * (west of GMT) or 1970-01-01 (east of GMT)
844 if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) ||
845 (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10)))
846 return 0;
848 hourminute = (strtol(timestamp + 11, NULL, 10) * 60 +
849 strtol(timestamp + 14, NULL, 10) -
850 zoneoffset);
852 return ((zoneoffset < 0 && hourminute == 1440) ||
853 (0 <= zoneoffset && !hourminute));
857 * Get the name etc info from the ---/+++ lines of a traditional patch header
859 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
860 * files, we can happily check the index for a match, but for creating a
861 * new file we should try to match whatever "patch" does. I have no idea.
863 static void parse_traditional_patch(struct apply_state *state,
864 const char *first,
865 const char *second,
866 struct patch *patch)
868 char *name;
870 first += 4; /* skip "--- " */
871 second += 4; /* skip "+++ " */
872 if (!p_value_known) {
873 int p, q;
874 p = guess_p_value(state, first);
875 q = guess_p_value(state, second);
876 if (p < 0) p = q;
877 if (0 <= p && p == q) {
878 state_p_value = p;
879 p_value_known = 1;
882 if (is_dev_null(first)) {
883 patch->is_new = 1;
884 patch->is_delete = 0;
885 name = find_name_traditional(second, NULL, state_p_value);
886 patch->new_name = name;
887 } else if (is_dev_null(second)) {
888 patch->is_new = 0;
889 patch->is_delete = 1;
890 name = find_name_traditional(first, NULL, state_p_value);
891 patch->old_name = name;
892 } else {
893 char *first_name;
894 first_name = find_name_traditional(first, NULL, state_p_value);
895 name = find_name_traditional(second, first_name, state_p_value);
896 free(first_name);
897 if (has_epoch_timestamp(first)) {
898 patch->is_new = 1;
899 patch->is_delete = 0;
900 patch->new_name = name;
901 } else if (has_epoch_timestamp(second)) {
902 patch->is_new = 0;
903 patch->is_delete = 1;
904 patch->old_name = name;
905 } else {
906 patch->old_name = name;
907 patch->new_name = xstrdup_or_null(name);
910 if (!name)
911 die(_("unable to find filename in patch at line %d"), state_linenr);
914 static int gitdiff_hdrend(const char *line, struct patch *patch)
916 return -1;
920 * We're anal about diff header consistency, to make
921 * sure that we don't end up having strange ambiguous
922 * patches floating around.
924 * As a result, gitdiff_{old|new}name() will check
925 * their names against any previous information, just
926 * to make sure..
928 #define DIFF_OLD_NAME 0
929 #define DIFF_NEW_NAME 1
931 static void gitdiff_verify_name(const char *line, int isnull, char **name, int side)
933 if (!*name && !isnull) {
934 *name = find_name(line, NULL, state_p_value, TERM_TAB);
935 return;
938 if (*name) {
939 int len = strlen(*name);
940 char *another;
941 if (isnull)
942 die(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
943 *name, state_linenr);
944 another = find_name(line, NULL, state_p_value, TERM_TAB);
945 if (!another || memcmp(another, *name, len + 1))
946 die((side == DIFF_NEW_NAME) ?
947 _("git apply: bad git-diff - inconsistent new filename on line %d") :
948 _("git apply: bad git-diff - inconsistent old filename on line %d"), state_linenr);
949 free(another);
950 } else {
951 /* expect "/dev/null" */
952 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
953 die(_("git apply: bad git-diff - expected /dev/null on line %d"), state_linenr);
957 static int gitdiff_oldname(const char *line, struct patch *patch)
959 gitdiff_verify_name(line, patch->is_new, &patch->old_name,
960 DIFF_OLD_NAME);
961 return 0;
964 static int gitdiff_newname(const char *line, struct patch *patch)
966 gitdiff_verify_name(line, patch->is_delete, &patch->new_name,
967 DIFF_NEW_NAME);
968 return 0;
971 static int gitdiff_oldmode(const char *line, struct patch *patch)
973 patch->old_mode = strtoul(line, NULL, 8);
974 return 0;
977 static int gitdiff_newmode(const char *line, struct patch *patch)
979 patch->new_mode = strtoul(line, NULL, 8);
980 return 0;
983 static int gitdiff_delete(const char *line, struct patch *patch)
985 patch->is_delete = 1;
986 free(patch->old_name);
987 patch->old_name = xstrdup_or_null(patch->def_name);
988 return gitdiff_oldmode(line, patch);
991 static int gitdiff_newfile(const char *line, struct patch *patch)
993 patch->is_new = 1;
994 free(patch->new_name);
995 patch->new_name = xstrdup_or_null(patch->def_name);
996 return gitdiff_newmode(line, patch);
999 static int gitdiff_copysrc(const char *line, struct patch *patch)
1001 patch->is_copy = 1;
1002 free(patch->old_name);
1003 patch->old_name = find_name(line, NULL, state_p_value ? state_p_value - 1 : 0, 0);
1004 return 0;
1007 static int gitdiff_copydst(const char *line, struct patch *patch)
1009 patch->is_copy = 1;
1010 free(patch->new_name);
1011 patch->new_name = find_name(line, NULL, state_p_value ? state_p_value - 1 : 0, 0);
1012 return 0;
1015 static int gitdiff_renamesrc(const char *line, struct patch *patch)
1017 patch->is_rename = 1;
1018 free(patch->old_name);
1019 patch->old_name = find_name(line, NULL, state_p_value ? state_p_value - 1 : 0, 0);
1020 return 0;
1023 static int gitdiff_renamedst(const char *line, struct patch *patch)
1025 patch->is_rename = 1;
1026 free(patch->new_name);
1027 patch->new_name = find_name(line, NULL, state_p_value ? state_p_value - 1 : 0, 0);
1028 return 0;
1031 static int gitdiff_similarity(const char *line, struct patch *patch)
1033 unsigned long val = strtoul(line, NULL, 10);
1034 if (val <= 100)
1035 patch->score = val;
1036 return 0;
1039 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
1041 unsigned long val = strtoul(line, NULL, 10);
1042 if (val <= 100)
1043 patch->score = val;
1044 return 0;
1047 static int gitdiff_index(const char *line, struct patch *patch)
1050 * index line is N hexadecimal, "..", N hexadecimal,
1051 * and optional space with octal mode.
1053 const char *ptr, *eol;
1054 int len;
1056 ptr = strchr(line, '.');
1057 if (!ptr || ptr[1] != '.' || 40 < ptr - line)
1058 return 0;
1059 len = ptr - line;
1060 memcpy(patch->old_sha1_prefix, line, len);
1061 patch->old_sha1_prefix[len] = 0;
1063 line = ptr + 2;
1064 ptr = strchr(line, ' ');
1065 eol = strchrnul(line, '\n');
1067 if (!ptr || eol < ptr)
1068 ptr = eol;
1069 len = ptr - line;
1071 if (40 < len)
1072 return 0;
1073 memcpy(patch->new_sha1_prefix, line, len);
1074 patch->new_sha1_prefix[len] = 0;
1075 if (*ptr == ' ')
1076 patch->old_mode = strtoul(ptr+1, NULL, 8);
1077 return 0;
1081 * This is normal for a diff that doesn't change anything: we'll fall through
1082 * into the next diff. Tell the parser to break out.
1084 static int gitdiff_unrecognized(const char *line, struct patch *patch)
1086 return -1;
1090 * Skip p_value leading components from "line"; as we do not accept
1091 * absolute paths, return NULL in that case.
1093 static const char *skip_tree_prefix(const char *line, int llen)
1095 int nslash;
1096 int i;
1098 if (!state_p_value)
1099 return (llen && line[0] == '/') ? NULL : line;
1101 nslash = state_p_value;
1102 for (i = 0; i < llen; i++) {
1103 int ch = line[i];
1104 if (ch == '/' && --nslash <= 0)
1105 return (i == 0) ? NULL : &line[i + 1];
1107 return NULL;
1111 * This is to extract the same name that appears on "diff --git"
1112 * line. We do not find and return anything if it is a rename
1113 * patch, and it is OK because we will find the name elsewhere.
1114 * We need to reliably find name only when it is mode-change only,
1115 * creation or deletion of an empty file. In any of these cases,
1116 * both sides are the same name under a/ and b/ respectively.
1118 static char *git_header_name(const char *line, int llen)
1120 const char *name;
1121 const char *second = NULL;
1122 size_t len, line_len;
1124 line += strlen("diff --git ");
1125 llen -= strlen("diff --git ");
1127 if (*line == '"') {
1128 const char *cp;
1129 struct strbuf first = STRBUF_INIT;
1130 struct strbuf sp = STRBUF_INIT;
1132 if (unquote_c_style(&first, line, &second))
1133 goto free_and_fail1;
1135 /* strip the a/b prefix including trailing slash */
1136 cp = skip_tree_prefix(first.buf, first.len);
1137 if (!cp)
1138 goto free_and_fail1;
1139 strbuf_remove(&first, 0, cp - first.buf);
1142 * second points at one past closing dq of name.
1143 * find the second name.
1145 while ((second < line + llen) && isspace(*second))
1146 second++;
1148 if (line + llen <= second)
1149 goto free_and_fail1;
1150 if (*second == '"') {
1151 if (unquote_c_style(&sp, second, NULL))
1152 goto free_and_fail1;
1153 cp = skip_tree_prefix(sp.buf, sp.len);
1154 if (!cp)
1155 goto free_and_fail1;
1156 /* They must match, otherwise ignore */
1157 if (strcmp(cp, first.buf))
1158 goto free_and_fail1;
1159 strbuf_release(&sp);
1160 return strbuf_detach(&first, NULL);
1163 /* unquoted second */
1164 cp = skip_tree_prefix(second, line + llen - second);
1165 if (!cp)
1166 goto free_and_fail1;
1167 if (line + llen - cp != first.len ||
1168 memcmp(first.buf, cp, first.len))
1169 goto free_and_fail1;
1170 return strbuf_detach(&first, NULL);
1172 free_and_fail1:
1173 strbuf_release(&first);
1174 strbuf_release(&sp);
1175 return NULL;
1178 /* unquoted first name */
1179 name = skip_tree_prefix(line, llen);
1180 if (!name)
1181 return NULL;
1184 * since the first name is unquoted, a dq if exists must be
1185 * the beginning of the second name.
1187 for (second = name; second < line + llen; second++) {
1188 if (*second == '"') {
1189 struct strbuf sp = STRBUF_INIT;
1190 const char *np;
1192 if (unquote_c_style(&sp, second, NULL))
1193 goto free_and_fail2;
1195 np = skip_tree_prefix(sp.buf, sp.len);
1196 if (!np)
1197 goto free_and_fail2;
1199 len = sp.buf + sp.len - np;
1200 if (len < second - name &&
1201 !strncmp(np, name, len) &&
1202 isspace(name[len])) {
1203 /* Good */
1204 strbuf_remove(&sp, 0, np - sp.buf);
1205 return strbuf_detach(&sp, NULL);
1208 free_and_fail2:
1209 strbuf_release(&sp);
1210 return NULL;
1215 * Accept a name only if it shows up twice, exactly the same
1216 * form.
1218 second = strchr(name, '\n');
1219 if (!second)
1220 return NULL;
1221 line_len = second - name;
1222 for (len = 0 ; ; len++) {
1223 switch (name[len]) {
1224 default:
1225 continue;
1226 case '\n':
1227 return NULL;
1228 case '\t': case ' ':
1230 * Is this the separator between the preimage
1231 * and the postimage pathname? Again, we are
1232 * only interested in the case where there is
1233 * no rename, as this is only to set def_name
1234 * and a rename patch has the names elsewhere
1235 * in an unambiguous form.
1237 if (!name[len + 1])
1238 return NULL; /* no postimage name */
1239 second = skip_tree_prefix(name + len + 1,
1240 line_len - (len + 1));
1241 if (!second)
1242 return NULL;
1244 * Does len bytes starting at "name" and "second"
1245 * (that are separated by one HT or SP we just
1246 * found) exactly match?
1248 if (second[len] == '\n' && !strncmp(name, second, len))
1249 return xmemdupz(name, len);
1254 /* Verify that we recognize the lines following a git header */
1255 static int parse_git_header(const char *line, int len, unsigned int size, struct patch *patch)
1257 unsigned long offset;
1259 /* A git diff has explicit new/delete information, so we don't guess */
1260 patch->is_new = 0;
1261 patch->is_delete = 0;
1264 * Some things may not have the old name in the
1265 * rest of the headers anywhere (pure mode changes,
1266 * or removing or adding empty files), so we get
1267 * the default name from the header.
1269 patch->def_name = git_header_name(line, len);
1270 if (patch->def_name && root.len) {
1271 char *s = xstrfmt("%s%s", root.buf, patch->def_name);
1272 free(patch->def_name);
1273 patch->def_name = s;
1276 line += len;
1277 size -= len;
1278 state_linenr++;
1279 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, state_linenr++) {
1280 static const struct opentry {
1281 const char *str;
1282 int (*fn)(const char *, struct patch *);
1283 } optable[] = {
1284 { "@@ -", gitdiff_hdrend },
1285 { "--- ", gitdiff_oldname },
1286 { "+++ ", gitdiff_newname },
1287 { "old mode ", gitdiff_oldmode },
1288 { "new mode ", gitdiff_newmode },
1289 { "deleted file mode ", gitdiff_delete },
1290 { "new file mode ", gitdiff_newfile },
1291 { "copy from ", gitdiff_copysrc },
1292 { "copy to ", gitdiff_copydst },
1293 { "rename old ", gitdiff_renamesrc },
1294 { "rename new ", gitdiff_renamedst },
1295 { "rename from ", gitdiff_renamesrc },
1296 { "rename to ", gitdiff_renamedst },
1297 { "similarity index ", gitdiff_similarity },
1298 { "dissimilarity index ", gitdiff_dissimilarity },
1299 { "index ", gitdiff_index },
1300 { "", gitdiff_unrecognized },
1302 int i;
1304 len = linelen(line, size);
1305 if (!len || line[len-1] != '\n')
1306 break;
1307 for (i = 0; i < ARRAY_SIZE(optable); i++) {
1308 const struct opentry *p = optable + i;
1309 int oplen = strlen(p->str);
1310 if (len < oplen || memcmp(p->str, line, oplen))
1311 continue;
1312 if (p->fn(line + oplen, patch) < 0)
1313 return offset;
1314 break;
1318 return offset;
1321 static int parse_num(const char *line, unsigned long *p)
1323 char *ptr;
1325 if (!isdigit(*line))
1326 return 0;
1327 *p = strtoul(line, &ptr, 10);
1328 return ptr - line;
1331 static int parse_range(const char *line, int len, int offset, const char *expect,
1332 unsigned long *p1, unsigned long *p2)
1334 int digits, ex;
1336 if (offset < 0 || offset >= len)
1337 return -1;
1338 line += offset;
1339 len -= offset;
1341 digits = parse_num(line, p1);
1342 if (!digits)
1343 return -1;
1345 offset += digits;
1346 line += digits;
1347 len -= digits;
1349 *p2 = 1;
1350 if (*line == ',') {
1351 digits = parse_num(line+1, p2);
1352 if (!digits)
1353 return -1;
1355 offset += digits+1;
1356 line += digits+1;
1357 len -= digits+1;
1360 ex = strlen(expect);
1361 if (ex > len)
1362 return -1;
1363 if (memcmp(line, expect, ex))
1364 return -1;
1366 return offset + ex;
1369 static void recount_diff(const char *line, int size, struct fragment *fragment)
1371 int oldlines = 0, newlines = 0, ret = 0;
1373 if (size < 1) {
1374 warning("recount: ignore empty hunk");
1375 return;
1378 for (;;) {
1379 int len = linelen(line, size);
1380 size -= len;
1381 line += len;
1383 if (size < 1)
1384 break;
1386 switch (*line) {
1387 case ' ': case '\n':
1388 newlines++;
1389 /* fall through */
1390 case '-':
1391 oldlines++;
1392 continue;
1393 case '+':
1394 newlines++;
1395 continue;
1396 case '\\':
1397 continue;
1398 case '@':
1399 ret = size < 3 || !starts_with(line, "@@ ");
1400 break;
1401 case 'd':
1402 ret = size < 5 || !starts_with(line, "diff ");
1403 break;
1404 default:
1405 ret = -1;
1406 break;
1408 if (ret) {
1409 warning(_("recount: unexpected line: %.*s"),
1410 (int)linelen(line, size), line);
1411 return;
1413 break;
1415 fragment->oldlines = oldlines;
1416 fragment->newlines = newlines;
1420 * Parse a unified diff fragment header of the
1421 * form "@@ -a,b +c,d @@"
1423 static int parse_fragment_header(const char *line, int len, struct fragment *fragment)
1425 int offset;
1427 if (!len || line[len-1] != '\n')
1428 return -1;
1430 /* Figure out the number of lines in a fragment */
1431 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1432 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1434 return offset;
1437 static int find_header(struct apply_state *state,
1438 const char *line,
1439 unsigned long size,
1440 int *hdrsize,
1441 struct patch *patch)
1443 unsigned long offset, len;
1445 patch->is_toplevel_relative = 0;
1446 patch->is_rename = patch->is_copy = 0;
1447 patch->is_new = patch->is_delete = -1;
1448 patch->old_mode = patch->new_mode = 0;
1449 patch->old_name = patch->new_name = NULL;
1450 for (offset = 0; size > 0; offset += len, size -= len, line += len, state_linenr++) {
1451 unsigned long nextlen;
1453 len = linelen(line, size);
1454 if (!len)
1455 break;
1457 /* Testing this early allows us to take a few shortcuts.. */
1458 if (len < 6)
1459 continue;
1462 * Make sure we don't find any unconnected patch fragments.
1463 * That's a sign that we didn't find a header, and that a
1464 * patch has become corrupted/broken up.
1466 if (!memcmp("@@ -", line, 4)) {
1467 struct fragment dummy;
1468 if (parse_fragment_header(line, len, &dummy) < 0)
1469 continue;
1470 die(_("patch fragment without header at line %d: %.*s"),
1471 state_linenr, (int)len-1, line);
1474 if (size < len + 6)
1475 break;
1478 * Git patch? It might not have a real patch, just a rename
1479 * or mode change, so we handle that specially
1481 if (!memcmp("diff --git ", line, 11)) {
1482 int git_hdr_len = parse_git_header(line, len, size, patch);
1483 if (git_hdr_len <= len)
1484 continue;
1485 if (!patch->old_name && !patch->new_name) {
1486 if (!patch->def_name)
1487 die(Q_("git diff header lacks filename information when removing "
1488 "%d leading pathname component (line %d)",
1489 "git diff header lacks filename information when removing "
1490 "%d leading pathname components (line %d)",
1491 state_p_value),
1492 state_p_value, state_linenr);
1493 patch->old_name = xstrdup(patch->def_name);
1494 patch->new_name = xstrdup(patch->def_name);
1496 if (!patch->is_delete && !patch->new_name)
1497 die("git diff header lacks filename information "
1498 "(line %d)", state_linenr);
1499 patch->is_toplevel_relative = 1;
1500 *hdrsize = git_hdr_len;
1501 return offset;
1504 /* --- followed by +++ ? */
1505 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1506 continue;
1509 * We only accept unified patches, so we want it to
1510 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1511 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1513 nextlen = linelen(line + len, size - len);
1514 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1515 continue;
1517 /* Ok, we'll consider it a patch */
1518 parse_traditional_patch(state, line, line+len, patch);
1519 *hdrsize = len + nextlen;
1520 state_linenr += 2;
1521 return offset;
1523 return -1;
1526 static void record_ws_error(unsigned result, const char *line, int len, int linenr)
1528 char *err;
1530 if (!result)
1531 return;
1533 whitespace_error++;
1534 if (squelch_whitespace_errors &&
1535 squelch_whitespace_errors < whitespace_error)
1536 return;
1538 err = whitespace_error_string(result);
1539 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1540 patch_input_file, linenr, err, len, line);
1541 free(err);
1544 static void check_whitespace(const char *line, int len, unsigned ws_rule)
1546 unsigned result = ws_check(line + 1, len - 1, ws_rule);
1548 record_ws_error(result, line + 1, len - 2, state_linenr);
1552 * Parse a unified diff. Note that this really needs to parse each
1553 * fragment separately, since the only way to know the difference
1554 * between a "---" that is part of a patch, and a "---" that starts
1555 * the next patch is to look at the line counts..
1557 static int parse_fragment(struct apply_state *state,
1558 const char *line,
1559 unsigned long size,
1560 struct patch *patch,
1561 struct fragment *fragment)
1563 int added, deleted;
1564 int len = linelen(line, size), offset;
1565 unsigned long oldlines, newlines;
1566 unsigned long leading, trailing;
1568 offset = parse_fragment_header(line, len, fragment);
1569 if (offset < 0)
1570 return -1;
1571 if (offset > 0 && patch->recount)
1572 recount_diff(line + offset, size - offset, fragment);
1573 oldlines = fragment->oldlines;
1574 newlines = fragment->newlines;
1575 leading = 0;
1576 trailing = 0;
1578 /* Parse the thing.. */
1579 line += len;
1580 size -= len;
1581 state_linenr++;
1582 added = deleted = 0;
1583 for (offset = len;
1584 0 < size;
1585 offset += len, size -= len, line += len, state_linenr++) {
1586 if (!oldlines && !newlines)
1587 break;
1588 len = linelen(line, size);
1589 if (!len || line[len-1] != '\n')
1590 return -1;
1591 switch (*line) {
1592 default:
1593 return -1;
1594 case '\n': /* newer GNU diff, an empty context line */
1595 case ' ':
1596 oldlines--;
1597 newlines--;
1598 if (!deleted && !added)
1599 leading++;
1600 trailing++;
1601 if (!state->apply_in_reverse &&
1602 ws_error_action == correct_ws_error)
1603 check_whitespace(line, len, patch->ws_rule);
1604 break;
1605 case '-':
1606 if (state->apply_in_reverse &&
1607 ws_error_action != nowarn_ws_error)
1608 check_whitespace(line, len, patch->ws_rule);
1609 deleted++;
1610 oldlines--;
1611 trailing = 0;
1612 break;
1613 case '+':
1614 if (!state->apply_in_reverse &&
1615 ws_error_action != nowarn_ws_error)
1616 check_whitespace(line, len, patch->ws_rule);
1617 added++;
1618 newlines--;
1619 trailing = 0;
1620 break;
1623 * We allow "\ No newline at end of file". Depending
1624 * on locale settings when the patch was produced we
1625 * don't know what this line looks like. The only
1626 * thing we do know is that it begins with "\ ".
1627 * Checking for 12 is just for sanity check -- any
1628 * l10n of "\ No newline..." is at least that long.
1630 case '\\':
1631 if (len < 12 || memcmp(line, "\\ ", 2))
1632 return -1;
1633 break;
1636 if (oldlines || newlines)
1637 return -1;
1638 if (!deleted && !added)
1639 return -1;
1641 fragment->leading = leading;
1642 fragment->trailing = trailing;
1645 * If a fragment ends with an incomplete line, we failed to include
1646 * it in the above loop because we hit oldlines == newlines == 0
1647 * before seeing it.
1649 if (12 < size && !memcmp(line, "\\ ", 2))
1650 offset += linelen(line, size);
1652 patch->lines_added += added;
1653 patch->lines_deleted += deleted;
1655 if (0 < patch->is_new && oldlines)
1656 return error(_("new file depends on old contents"));
1657 if (0 < patch->is_delete && newlines)
1658 return error(_("deleted file still has contents"));
1659 return offset;
1663 * We have seen "diff --git a/... b/..." header (or a traditional patch
1664 * header). Read hunks that belong to this patch into fragments and hang
1665 * them to the given patch structure.
1667 * The (fragment->patch, fragment->size) pair points into the memory given
1668 * by the caller, not a copy, when we return.
1670 static int parse_single_patch(struct apply_state *state,
1671 const char *line,
1672 unsigned long size,
1673 struct patch *patch)
1675 unsigned long offset = 0;
1676 unsigned long oldlines = 0, newlines = 0, context = 0;
1677 struct fragment **fragp = &patch->fragments;
1679 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1680 struct fragment *fragment;
1681 int len;
1683 fragment = xcalloc(1, sizeof(*fragment));
1684 fragment->linenr = state_linenr;
1685 len = parse_fragment(state, line, size, patch, fragment);
1686 if (len <= 0)
1687 die(_("corrupt patch at line %d"), state_linenr);
1688 fragment->patch = line;
1689 fragment->size = len;
1690 oldlines += fragment->oldlines;
1691 newlines += fragment->newlines;
1692 context += fragment->leading + fragment->trailing;
1694 *fragp = fragment;
1695 fragp = &fragment->next;
1697 offset += len;
1698 line += len;
1699 size -= len;
1703 * If something was removed (i.e. we have old-lines) it cannot
1704 * be creation, and if something was added it cannot be
1705 * deletion. However, the reverse is not true; --unified=0
1706 * patches that only add are not necessarily creation even
1707 * though they do not have any old lines, and ones that only
1708 * delete are not necessarily deletion.
1710 * Unfortunately, a real creation/deletion patch do _not_ have
1711 * any context line by definition, so we cannot safely tell it
1712 * apart with --unified=0 insanity. At least if the patch has
1713 * more than one hunk it is not creation or deletion.
1715 if (patch->is_new < 0 &&
1716 (oldlines || (patch->fragments && patch->fragments->next)))
1717 patch->is_new = 0;
1718 if (patch->is_delete < 0 &&
1719 (newlines || (patch->fragments && patch->fragments->next)))
1720 patch->is_delete = 0;
1722 if (0 < patch->is_new && oldlines)
1723 die(_("new file %s depends on old contents"), patch->new_name);
1724 if (0 < patch->is_delete && newlines)
1725 die(_("deleted file %s still has contents"), patch->old_name);
1726 if (!patch->is_delete && !newlines && context)
1727 fprintf_ln(stderr,
1728 _("** warning: "
1729 "file %s becomes empty but is not deleted"),
1730 patch->new_name);
1732 return offset;
1735 static inline int metadata_changes(struct patch *patch)
1737 return patch->is_rename > 0 ||
1738 patch->is_copy > 0 ||
1739 patch->is_new > 0 ||
1740 patch->is_delete ||
1741 (patch->old_mode && patch->new_mode &&
1742 patch->old_mode != patch->new_mode);
1745 static char *inflate_it(const void *data, unsigned long size,
1746 unsigned long inflated_size)
1748 git_zstream stream;
1749 void *out;
1750 int st;
1752 memset(&stream, 0, sizeof(stream));
1754 stream.next_in = (unsigned char *)data;
1755 stream.avail_in = size;
1756 stream.next_out = out = xmalloc(inflated_size);
1757 stream.avail_out = inflated_size;
1758 git_inflate_init(&stream);
1759 st = git_inflate(&stream, Z_FINISH);
1760 git_inflate_end(&stream);
1761 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1762 free(out);
1763 return NULL;
1765 return out;
1769 * Read a binary hunk and return a new fragment; fragment->patch
1770 * points at an allocated memory that the caller must free, so
1771 * it is marked as "->free_patch = 1".
1773 static struct fragment *parse_binary_hunk(char **buf_p,
1774 unsigned long *sz_p,
1775 int *status_p,
1776 int *used_p)
1779 * Expect a line that begins with binary patch method ("literal"
1780 * or "delta"), followed by the length of data before deflating.
1781 * a sequence of 'length-byte' followed by base-85 encoded data
1782 * should follow, terminated by a newline.
1784 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1785 * and we would limit the patch line to 66 characters,
1786 * so one line can fit up to 13 groups that would decode
1787 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1788 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1790 int llen, used;
1791 unsigned long size = *sz_p;
1792 char *buffer = *buf_p;
1793 int patch_method;
1794 unsigned long origlen;
1795 char *data = NULL;
1796 int hunk_size = 0;
1797 struct fragment *frag;
1799 llen = linelen(buffer, size);
1800 used = llen;
1802 *status_p = 0;
1804 if (starts_with(buffer, "delta ")) {
1805 patch_method = BINARY_DELTA_DEFLATED;
1806 origlen = strtoul(buffer + 6, NULL, 10);
1808 else if (starts_with(buffer, "literal ")) {
1809 patch_method = BINARY_LITERAL_DEFLATED;
1810 origlen = strtoul(buffer + 8, NULL, 10);
1812 else
1813 return NULL;
1815 state_linenr++;
1816 buffer += llen;
1817 while (1) {
1818 int byte_length, max_byte_length, newsize;
1819 llen = linelen(buffer, size);
1820 used += llen;
1821 state_linenr++;
1822 if (llen == 1) {
1823 /* consume the blank line */
1824 buffer++;
1825 size--;
1826 break;
1829 * Minimum line is "A00000\n" which is 7-byte long,
1830 * and the line length must be multiple of 5 plus 2.
1832 if ((llen < 7) || (llen-2) % 5)
1833 goto corrupt;
1834 max_byte_length = (llen - 2) / 5 * 4;
1835 byte_length = *buffer;
1836 if ('A' <= byte_length && byte_length <= 'Z')
1837 byte_length = byte_length - 'A' + 1;
1838 else if ('a' <= byte_length && byte_length <= 'z')
1839 byte_length = byte_length - 'a' + 27;
1840 else
1841 goto corrupt;
1842 /* if the input length was not multiple of 4, we would
1843 * have filler at the end but the filler should never
1844 * exceed 3 bytes
1846 if (max_byte_length < byte_length ||
1847 byte_length <= max_byte_length - 4)
1848 goto corrupt;
1849 newsize = hunk_size + byte_length;
1850 data = xrealloc(data, newsize);
1851 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1852 goto corrupt;
1853 hunk_size = newsize;
1854 buffer += llen;
1855 size -= llen;
1858 frag = xcalloc(1, sizeof(*frag));
1859 frag->patch = inflate_it(data, hunk_size, origlen);
1860 frag->free_patch = 1;
1861 if (!frag->patch)
1862 goto corrupt;
1863 free(data);
1864 frag->size = origlen;
1865 *buf_p = buffer;
1866 *sz_p = size;
1867 *used_p = used;
1868 frag->binary_patch_method = patch_method;
1869 return frag;
1871 corrupt:
1872 free(data);
1873 *status_p = -1;
1874 error(_("corrupt binary patch at line %d: %.*s"),
1875 state_linenr-1, llen-1, buffer);
1876 return NULL;
1880 * Returns:
1881 * -1 in case of error,
1882 * the length of the parsed binary patch otherwise
1884 static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1887 * We have read "GIT binary patch\n"; what follows is a line
1888 * that says the patch method (currently, either "literal" or
1889 * "delta") and the length of data before deflating; a
1890 * sequence of 'length-byte' followed by base-85 encoded data
1891 * follows.
1893 * When a binary patch is reversible, there is another binary
1894 * hunk in the same format, starting with patch method (either
1895 * "literal" or "delta") with the length of data, and a sequence
1896 * of length-byte + base-85 encoded data, terminated with another
1897 * empty line. This data, when applied to the postimage, produces
1898 * the preimage.
1900 struct fragment *forward;
1901 struct fragment *reverse;
1902 int status;
1903 int used, used_1;
1905 forward = parse_binary_hunk(&buffer, &size, &status, &used);
1906 if (!forward && !status)
1907 /* there has to be one hunk (forward hunk) */
1908 return error(_("unrecognized binary patch at line %d"), state_linenr-1);
1909 if (status)
1910 /* otherwise we already gave an error message */
1911 return status;
1913 reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1914 if (reverse)
1915 used += used_1;
1916 else if (status) {
1918 * Not having reverse hunk is not an error, but having
1919 * a corrupt reverse hunk is.
1921 free((void*) forward->patch);
1922 free(forward);
1923 return status;
1925 forward->next = reverse;
1926 patch->fragments = forward;
1927 patch->is_binary = 1;
1928 return used;
1931 static void prefix_one(struct apply_state *state, char **name)
1933 char *old_name = *name;
1934 if (!old_name)
1935 return;
1936 *name = xstrdup(prefix_filename(state->prefix, state->prefix_length, *name));
1937 free(old_name);
1940 static void prefix_patch(struct apply_state *state, struct patch *p)
1942 if (!state->prefix || p->is_toplevel_relative)
1943 return;
1944 prefix_one(state, &p->new_name);
1945 prefix_one(state, &p->old_name);
1949 * include/exclude
1952 static struct string_list limit_by_name;
1953 static int has_include;
1954 static void add_name_limit(const char *name, int exclude)
1956 struct string_list_item *it;
1958 it = string_list_append(&limit_by_name, name);
1959 it->util = exclude ? NULL : (void *) 1;
1962 static int use_patch(struct apply_state *state, struct patch *p)
1964 const char *pathname = p->new_name ? p->new_name : p->old_name;
1965 int i;
1967 /* Paths outside are not touched regardless of "--include" */
1968 if (0 < state->prefix_length) {
1969 int pathlen = strlen(pathname);
1970 if (pathlen <= state->prefix_length ||
1971 memcmp(state->prefix, pathname, state->prefix_length))
1972 return 0;
1975 /* See if it matches any of exclude/include rule */
1976 for (i = 0; i < limit_by_name.nr; i++) {
1977 struct string_list_item *it = &limit_by_name.items[i];
1978 if (!wildmatch(it->string, pathname, 0, NULL))
1979 return (it->util != NULL);
1983 * If we had any include, a path that does not match any rule is
1984 * not used. Otherwise, we saw bunch of exclude rules (or none)
1985 * and such a path is used.
1987 return !has_include;
1992 * Read the patch text in "buffer" that extends for "size" bytes; stop
1993 * reading after seeing a single patch (i.e. changes to a single file).
1994 * Create fragments (i.e. patch hunks) and hang them to the given patch.
1995 * Return the number of bytes consumed, so that the caller can call us
1996 * again for the next patch.
1998 static int parse_chunk(struct apply_state *state, char *buffer, unsigned long size, struct patch *patch)
2000 int hdrsize, patchsize;
2001 int offset = find_header(state, buffer, size, &hdrsize, patch);
2003 if (offset < 0)
2004 return offset;
2006 prefix_patch(state, patch);
2008 if (!use_patch(state, patch))
2009 patch->ws_rule = 0;
2010 else
2011 patch->ws_rule = whitespace_rule(patch->new_name
2012 ? patch->new_name
2013 : patch->old_name);
2015 patchsize = parse_single_patch(state,
2016 buffer + offset + hdrsize,
2017 size - offset - hdrsize,
2018 patch);
2020 if (!patchsize) {
2021 static const char git_binary[] = "GIT binary patch\n";
2022 int hd = hdrsize + offset;
2023 unsigned long llen = linelen(buffer + hd, size - hd);
2025 if (llen == sizeof(git_binary) - 1 &&
2026 !memcmp(git_binary, buffer + hd, llen)) {
2027 int used;
2028 state_linenr++;
2029 used = parse_binary(buffer + hd + llen,
2030 size - hd - llen, patch);
2031 if (used < 0)
2032 return -1;
2033 if (used)
2034 patchsize = used + llen;
2035 else
2036 patchsize = 0;
2038 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
2039 static const char *binhdr[] = {
2040 "Binary files ",
2041 "Files ",
2042 NULL,
2044 int i;
2045 for (i = 0; binhdr[i]; i++) {
2046 int len = strlen(binhdr[i]);
2047 if (len < size - hd &&
2048 !memcmp(binhdr[i], buffer + hd, len)) {
2049 state_linenr++;
2050 patch->is_binary = 1;
2051 patchsize = llen;
2052 break;
2057 /* Empty patch cannot be applied if it is a text patch
2058 * without metadata change. A binary patch appears
2059 * empty to us here.
2061 if ((apply || state->check) &&
2062 (!patch->is_binary && !metadata_changes(patch)))
2063 die(_("patch with only garbage at line %d"), state_linenr);
2066 return offset + hdrsize + patchsize;
2069 #define swap(a,b) myswap((a),(b),sizeof(a))
2071 #define myswap(a, b, size) do { \
2072 unsigned char mytmp[size]; \
2073 memcpy(mytmp, &a, size); \
2074 memcpy(&a, &b, size); \
2075 memcpy(&b, mytmp, size); \
2076 } while (0)
2078 static void reverse_patches(struct patch *p)
2080 for (; p; p = p->next) {
2081 struct fragment *frag = p->fragments;
2083 swap(p->new_name, p->old_name);
2084 swap(p->new_mode, p->old_mode);
2085 swap(p->is_new, p->is_delete);
2086 swap(p->lines_added, p->lines_deleted);
2087 swap(p->old_sha1_prefix, p->new_sha1_prefix);
2089 for (; frag; frag = frag->next) {
2090 swap(frag->newpos, frag->oldpos);
2091 swap(frag->newlines, frag->oldlines);
2096 static const char pluses[] =
2097 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2098 static const char minuses[]=
2099 "----------------------------------------------------------------------";
2101 static void show_stats(struct patch *patch)
2103 struct strbuf qname = STRBUF_INIT;
2104 char *cp = patch->new_name ? patch->new_name : patch->old_name;
2105 int max, add, del;
2107 quote_c_style(cp, &qname, NULL, 0);
2110 * "scale" the filename
2112 max = max_len;
2113 if (max > 50)
2114 max = 50;
2116 if (qname.len > max) {
2117 cp = strchr(qname.buf + qname.len + 3 - max, '/');
2118 if (!cp)
2119 cp = qname.buf + qname.len + 3 - max;
2120 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
2123 if (patch->is_binary) {
2124 printf(" %-*s | Bin\n", max, qname.buf);
2125 strbuf_release(&qname);
2126 return;
2129 printf(" %-*s |", max, qname.buf);
2130 strbuf_release(&qname);
2133 * scale the add/delete
2135 max = max + max_change > 70 ? 70 - max : max_change;
2136 add = patch->lines_added;
2137 del = patch->lines_deleted;
2139 if (max_change > 0) {
2140 int total = ((add + del) * max + max_change / 2) / max_change;
2141 add = (add * max + max_change / 2) / max_change;
2142 del = total - add;
2144 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
2145 add, pluses, del, minuses);
2148 static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
2150 switch (st->st_mode & S_IFMT) {
2151 case S_IFLNK:
2152 if (strbuf_readlink(buf, path, st->st_size) < 0)
2153 return error(_("unable to read symlink %s"), path);
2154 return 0;
2155 case S_IFREG:
2156 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
2157 return error(_("unable to open or read %s"), path);
2158 convert_to_git(path, buf->buf, buf->len, buf, 0);
2159 return 0;
2160 default:
2161 return -1;
2166 * Update the preimage, and the common lines in postimage,
2167 * from buffer buf of length len. If postlen is 0 the postimage
2168 * is updated in place, otherwise it's updated on a new buffer
2169 * of length postlen
2172 static void update_pre_post_images(struct image *preimage,
2173 struct image *postimage,
2174 char *buf,
2175 size_t len, size_t postlen)
2177 int i, ctx, reduced;
2178 char *new, *old, *fixed;
2179 struct image fixed_preimage;
2182 * Update the preimage with whitespace fixes. Note that we
2183 * are not losing preimage->buf -- apply_one_fragment() will
2184 * free "oldlines".
2186 prepare_image(&fixed_preimage, buf, len, 1);
2187 assert(postlen
2188 ? fixed_preimage.nr == preimage->nr
2189 : fixed_preimage.nr <= preimage->nr);
2190 for (i = 0; i < fixed_preimage.nr; i++)
2191 fixed_preimage.line[i].flag = preimage->line[i].flag;
2192 free(preimage->line_allocated);
2193 *preimage = fixed_preimage;
2196 * Adjust the common context lines in postimage. This can be
2197 * done in-place when we are shrinking it with whitespace
2198 * fixing, but needs a new buffer when ignoring whitespace or
2199 * expanding leading tabs to spaces.
2201 * We trust the caller to tell us if the update can be done
2202 * in place (postlen==0) or not.
2204 old = postimage->buf;
2205 if (postlen)
2206 new = postimage->buf = xmalloc(postlen);
2207 else
2208 new = old;
2209 fixed = preimage->buf;
2211 for (i = reduced = ctx = 0; i < postimage->nr; i++) {
2212 size_t l_len = postimage->line[i].len;
2213 if (!(postimage->line[i].flag & LINE_COMMON)) {
2214 /* an added line -- no counterparts in preimage */
2215 memmove(new, old, l_len);
2216 old += l_len;
2217 new += l_len;
2218 continue;
2221 /* a common context -- skip it in the original postimage */
2222 old += l_len;
2224 /* and find the corresponding one in the fixed preimage */
2225 while (ctx < preimage->nr &&
2226 !(preimage->line[ctx].flag & LINE_COMMON)) {
2227 fixed += preimage->line[ctx].len;
2228 ctx++;
2232 * preimage is expected to run out, if the caller
2233 * fixed addition of trailing blank lines.
2235 if (preimage->nr <= ctx) {
2236 reduced++;
2237 continue;
2240 /* and copy it in, while fixing the line length */
2241 l_len = preimage->line[ctx].len;
2242 memcpy(new, fixed, l_len);
2243 new += l_len;
2244 fixed += l_len;
2245 postimage->line[i].len = l_len;
2246 ctx++;
2249 if (postlen
2250 ? postlen < new - postimage->buf
2251 : postimage->len < new - postimage->buf)
2252 die("BUG: caller miscounted postlen: asked %d, orig = %d, used = %d",
2253 (int)postlen, (int) postimage->len, (int)(new - postimage->buf));
2255 /* Fix the length of the whole thing */
2256 postimage->len = new - postimage->buf;
2257 postimage->nr -= reduced;
2260 static int line_by_line_fuzzy_match(struct image *img,
2261 struct image *preimage,
2262 struct image *postimage,
2263 unsigned long try,
2264 int try_lno,
2265 int preimage_limit)
2267 int i;
2268 size_t imgoff = 0;
2269 size_t preoff = 0;
2270 size_t postlen = postimage->len;
2271 size_t extra_chars;
2272 char *buf;
2273 char *preimage_eof;
2274 char *preimage_end;
2275 struct strbuf fixed;
2276 char *fixed_buf;
2277 size_t fixed_len;
2279 for (i = 0; i < preimage_limit; i++) {
2280 size_t prelen = preimage->line[i].len;
2281 size_t imglen = img->line[try_lno+i].len;
2283 if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,
2284 preimage->buf + preoff, prelen))
2285 return 0;
2286 if (preimage->line[i].flag & LINE_COMMON)
2287 postlen += imglen - prelen;
2288 imgoff += imglen;
2289 preoff += prelen;
2293 * Ok, the preimage matches with whitespace fuzz.
2295 * imgoff now holds the true length of the target that
2296 * matches the preimage before the end of the file.
2298 * Count the number of characters in the preimage that fall
2299 * beyond the end of the file and make sure that all of them
2300 * are whitespace characters. (This can only happen if
2301 * we are removing blank lines at the end of the file.)
2303 buf = preimage_eof = preimage->buf + preoff;
2304 for ( ; i < preimage->nr; i++)
2305 preoff += preimage->line[i].len;
2306 preimage_end = preimage->buf + preoff;
2307 for ( ; buf < preimage_end; buf++)
2308 if (!isspace(*buf))
2309 return 0;
2312 * Update the preimage and the common postimage context
2313 * lines to use the same whitespace as the target.
2314 * If whitespace is missing in the target (i.e.
2315 * if the preimage extends beyond the end of the file),
2316 * use the whitespace from the preimage.
2318 extra_chars = preimage_end - preimage_eof;
2319 strbuf_init(&fixed, imgoff + extra_chars);
2320 strbuf_add(&fixed, img->buf + try, imgoff);
2321 strbuf_add(&fixed, preimage_eof, extra_chars);
2322 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2323 update_pre_post_images(preimage, postimage,
2324 fixed_buf, fixed_len, postlen);
2325 return 1;
2328 static int match_fragment(struct image *img,
2329 struct image *preimage,
2330 struct image *postimage,
2331 unsigned long try,
2332 int try_lno,
2333 unsigned ws_rule,
2334 int match_beginning, int match_end)
2336 int i;
2337 char *fixed_buf, *buf, *orig, *target;
2338 struct strbuf fixed;
2339 size_t fixed_len, postlen;
2340 int preimage_limit;
2342 if (preimage->nr + try_lno <= img->nr) {
2344 * The hunk falls within the boundaries of img.
2346 preimage_limit = preimage->nr;
2347 if (match_end && (preimage->nr + try_lno != img->nr))
2348 return 0;
2349 } else if (ws_error_action == correct_ws_error &&
2350 (ws_rule & WS_BLANK_AT_EOF)) {
2352 * This hunk extends beyond the end of img, and we are
2353 * removing blank lines at the end of the file. This
2354 * many lines from the beginning of the preimage must
2355 * match with img, and the remainder of the preimage
2356 * must be blank.
2358 preimage_limit = img->nr - try_lno;
2359 } else {
2361 * The hunk extends beyond the end of the img and
2362 * we are not removing blanks at the end, so we
2363 * should reject the hunk at this position.
2365 return 0;
2368 if (match_beginning && try_lno)
2369 return 0;
2371 /* Quick hash check */
2372 for (i = 0; i < preimage_limit; i++)
2373 if ((img->line[try_lno + i].flag & LINE_PATCHED) ||
2374 (preimage->line[i].hash != img->line[try_lno + i].hash))
2375 return 0;
2377 if (preimage_limit == preimage->nr) {
2379 * Do we have an exact match? If we were told to match
2380 * at the end, size must be exactly at try+fragsize,
2381 * otherwise try+fragsize must be still within the preimage,
2382 * and either case, the old piece should match the preimage
2383 * exactly.
2385 if ((match_end
2386 ? (try + preimage->len == img->len)
2387 : (try + preimage->len <= img->len)) &&
2388 !memcmp(img->buf + try, preimage->buf, preimage->len))
2389 return 1;
2390 } else {
2392 * The preimage extends beyond the end of img, so
2393 * there cannot be an exact match.
2395 * There must be one non-blank context line that match
2396 * a line before the end of img.
2398 char *buf_end;
2400 buf = preimage->buf;
2401 buf_end = buf;
2402 for (i = 0; i < preimage_limit; i++)
2403 buf_end += preimage->line[i].len;
2405 for ( ; buf < buf_end; buf++)
2406 if (!isspace(*buf))
2407 break;
2408 if (buf == buf_end)
2409 return 0;
2413 * No exact match. If we are ignoring whitespace, run a line-by-line
2414 * fuzzy matching. We collect all the line length information because
2415 * we need it to adjust whitespace if we match.
2417 if (ws_ignore_action == ignore_ws_change)
2418 return line_by_line_fuzzy_match(img, preimage, postimage,
2419 try, try_lno, preimage_limit);
2421 if (ws_error_action != correct_ws_error)
2422 return 0;
2425 * The hunk does not apply byte-by-byte, but the hash says
2426 * it might with whitespace fuzz. We weren't asked to
2427 * ignore whitespace, we were asked to correct whitespace
2428 * errors, so let's try matching after whitespace correction.
2430 * While checking the preimage against the target, whitespace
2431 * errors in both fixed, we count how large the corresponding
2432 * postimage needs to be. The postimage prepared by
2433 * apply_one_fragment() has whitespace errors fixed on added
2434 * lines already, but the common lines were propagated as-is,
2435 * which may become longer when their whitespace errors are
2436 * fixed.
2439 /* First count added lines in postimage */
2440 postlen = 0;
2441 for (i = 0; i < postimage->nr; i++) {
2442 if (!(postimage->line[i].flag & LINE_COMMON))
2443 postlen += postimage->line[i].len;
2447 * The preimage may extend beyond the end of the file,
2448 * but in this loop we will only handle the part of the
2449 * preimage that falls within the file.
2451 strbuf_init(&fixed, preimage->len + 1);
2452 orig = preimage->buf;
2453 target = img->buf + try;
2454 for (i = 0; i < preimage_limit; i++) {
2455 size_t oldlen = preimage->line[i].len;
2456 size_t tgtlen = img->line[try_lno + i].len;
2457 size_t fixstart = fixed.len;
2458 struct strbuf tgtfix;
2459 int match;
2461 /* Try fixing the line in the preimage */
2462 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2464 /* Try fixing the line in the target */
2465 strbuf_init(&tgtfix, tgtlen);
2466 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2469 * If they match, either the preimage was based on
2470 * a version before our tree fixed whitespace breakage,
2471 * or we are lacking a whitespace-fix patch the tree
2472 * the preimage was based on already had (i.e. target
2473 * has whitespace breakage, the preimage doesn't).
2474 * In either case, we are fixing the whitespace breakages
2475 * so we might as well take the fix together with their
2476 * real change.
2478 match = (tgtfix.len == fixed.len - fixstart &&
2479 !memcmp(tgtfix.buf, fixed.buf + fixstart,
2480 fixed.len - fixstart));
2482 /* Add the length if this is common with the postimage */
2483 if (preimage->line[i].flag & LINE_COMMON)
2484 postlen += tgtfix.len;
2486 strbuf_release(&tgtfix);
2487 if (!match)
2488 goto unmatch_exit;
2490 orig += oldlen;
2491 target += tgtlen;
2496 * Now handle the lines in the preimage that falls beyond the
2497 * end of the file (if any). They will only match if they are
2498 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2499 * false).
2501 for ( ; i < preimage->nr; i++) {
2502 size_t fixstart = fixed.len; /* start of the fixed preimage */
2503 size_t oldlen = preimage->line[i].len;
2504 int j;
2506 /* Try fixing the line in the preimage */
2507 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2509 for (j = fixstart; j < fixed.len; j++)
2510 if (!isspace(fixed.buf[j]))
2511 goto unmatch_exit;
2513 orig += oldlen;
2517 * Yes, the preimage is based on an older version that still
2518 * has whitespace breakages unfixed, and fixing them makes the
2519 * hunk match. Update the context lines in the postimage.
2521 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2522 if (postlen < postimage->len)
2523 postlen = 0;
2524 update_pre_post_images(preimage, postimage,
2525 fixed_buf, fixed_len, postlen);
2526 return 1;
2528 unmatch_exit:
2529 strbuf_release(&fixed);
2530 return 0;
2533 static int find_pos(struct image *img,
2534 struct image *preimage,
2535 struct image *postimage,
2536 int line,
2537 unsigned ws_rule,
2538 int match_beginning, int match_end)
2540 int i;
2541 unsigned long backwards, forwards, try;
2542 int backwards_lno, forwards_lno, try_lno;
2545 * If match_beginning or match_end is specified, there is no
2546 * point starting from a wrong line that will never match and
2547 * wander around and wait for a match at the specified end.
2549 if (match_beginning)
2550 line = 0;
2551 else if (match_end)
2552 line = img->nr - preimage->nr;
2555 * Because the comparison is unsigned, the following test
2556 * will also take care of a negative line number that can
2557 * result when match_end and preimage is larger than the target.
2559 if ((size_t) line > img->nr)
2560 line = img->nr;
2562 try = 0;
2563 for (i = 0; i < line; i++)
2564 try += img->line[i].len;
2567 * There's probably some smart way to do this, but I'll leave
2568 * that to the smart and beautiful people. I'm simple and stupid.
2570 backwards = try;
2571 backwards_lno = line;
2572 forwards = try;
2573 forwards_lno = line;
2574 try_lno = line;
2576 for (i = 0; ; i++) {
2577 if (match_fragment(img, preimage, postimage,
2578 try, try_lno, ws_rule,
2579 match_beginning, match_end))
2580 return try_lno;
2582 again:
2583 if (backwards_lno == 0 && forwards_lno == img->nr)
2584 break;
2586 if (i & 1) {
2587 if (backwards_lno == 0) {
2588 i++;
2589 goto again;
2591 backwards_lno--;
2592 backwards -= img->line[backwards_lno].len;
2593 try = backwards;
2594 try_lno = backwards_lno;
2595 } else {
2596 if (forwards_lno == img->nr) {
2597 i++;
2598 goto again;
2600 forwards += img->line[forwards_lno].len;
2601 forwards_lno++;
2602 try = forwards;
2603 try_lno = forwards_lno;
2607 return -1;
2610 static void remove_first_line(struct image *img)
2612 img->buf += img->line[0].len;
2613 img->len -= img->line[0].len;
2614 img->line++;
2615 img->nr--;
2618 static void remove_last_line(struct image *img)
2620 img->len -= img->line[--img->nr].len;
2624 * The change from "preimage" and "postimage" has been found to
2625 * apply at applied_pos (counts in line numbers) in "img".
2626 * Update "img" to remove "preimage" and replace it with "postimage".
2628 static void update_image(struct apply_state *state,
2629 struct image *img,
2630 int applied_pos,
2631 struct image *preimage,
2632 struct image *postimage)
2635 * remove the copy of preimage at offset in img
2636 * and replace it with postimage
2638 int i, nr;
2639 size_t remove_count, insert_count, applied_at = 0;
2640 char *result;
2641 int preimage_limit;
2644 * If we are removing blank lines at the end of img,
2645 * the preimage may extend beyond the end.
2646 * If that is the case, we must be careful only to
2647 * remove the part of the preimage that falls within
2648 * the boundaries of img. Initialize preimage_limit
2649 * to the number of lines in the preimage that falls
2650 * within the boundaries.
2652 preimage_limit = preimage->nr;
2653 if (preimage_limit > img->nr - applied_pos)
2654 preimage_limit = img->nr - applied_pos;
2656 for (i = 0; i < applied_pos; i++)
2657 applied_at += img->line[i].len;
2659 remove_count = 0;
2660 for (i = 0; i < preimage_limit; i++)
2661 remove_count += img->line[applied_pos + i].len;
2662 insert_count = postimage->len;
2664 /* Adjust the contents */
2665 result = xmalloc(st_add3(st_sub(img->len, remove_count), insert_count, 1));
2666 memcpy(result, img->buf, applied_at);
2667 memcpy(result + applied_at, postimage->buf, postimage->len);
2668 memcpy(result + applied_at + postimage->len,
2669 img->buf + (applied_at + remove_count),
2670 img->len - (applied_at + remove_count));
2671 free(img->buf);
2672 img->buf = result;
2673 img->len += insert_count - remove_count;
2674 result[img->len] = '\0';
2676 /* Adjust the line table */
2677 nr = img->nr + postimage->nr - preimage_limit;
2678 if (preimage_limit < postimage->nr) {
2680 * NOTE: this knows that we never call remove_first_line()
2681 * on anything other than pre/post image.
2683 REALLOC_ARRAY(img->line, nr);
2684 img->line_allocated = img->line;
2686 if (preimage_limit != postimage->nr)
2687 memmove(img->line + applied_pos + postimage->nr,
2688 img->line + applied_pos + preimage_limit,
2689 (img->nr - (applied_pos + preimage_limit)) *
2690 sizeof(*img->line));
2691 memcpy(img->line + applied_pos,
2692 postimage->line,
2693 postimage->nr * sizeof(*img->line));
2694 if (!state->allow_overlap)
2695 for (i = 0; i < postimage->nr; i++)
2696 img->line[applied_pos + i].flag |= LINE_PATCHED;
2697 img->nr = nr;
2701 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2702 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2703 * replace the part of "img" with "postimage" text.
2705 static int apply_one_fragment(struct apply_state *state,
2706 struct image *img, struct fragment *frag,
2707 int inaccurate_eof, unsigned ws_rule,
2708 int nth_fragment)
2710 int match_beginning, match_end;
2711 const char *patch = frag->patch;
2712 int size = frag->size;
2713 char *old, *oldlines;
2714 struct strbuf newlines;
2715 int new_blank_lines_at_end = 0;
2716 int found_new_blank_lines_at_end = 0;
2717 int hunk_linenr = frag->linenr;
2718 unsigned long leading, trailing;
2719 int pos, applied_pos;
2720 struct image preimage;
2721 struct image postimage;
2723 memset(&preimage, 0, sizeof(preimage));
2724 memset(&postimage, 0, sizeof(postimage));
2725 oldlines = xmalloc(size);
2726 strbuf_init(&newlines, size);
2728 old = oldlines;
2729 while (size > 0) {
2730 char first;
2731 int len = linelen(patch, size);
2732 int plen;
2733 int added_blank_line = 0;
2734 int is_blank_context = 0;
2735 size_t start;
2737 if (!len)
2738 break;
2741 * "plen" is how much of the line we should use for
2742 * the actual patch data. Normally we just remove the
2743 * first character on the line, but if the line is
2744 * followed by "\ No newline", then we also remove the
2745 * last one (which is the newline, of course).
2747 plen = len - 1;
2748 if (len < size && patch[len] == '\\')
2749 plen--;
2750 first = *patch;
2751 if (state->apply_in_reverse) {
2752 if (first == '-')
2753 first = '+';
2754 else if (first == '+')
2755 first = '-';
2758 switch (first) {
2759 case '\n':
2760 /* Newer GNU diff, empty context line */
2761 if (plen < 0)
2762 /* ... followed by '\No newline'; nothing */
2763 break;
2764 *old++ = '\n';
2765 strbuf_addch(&newlines, '\n');
2766 add_line_info(&preimage, "\n", 1, LINE_COMMON);
2767 add_line_info(&postimage, "\n", 1, LINE_COMMON);
2768 is_blank_context = 1;
2769 break;
2770 case ' ':
2771 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2772 ws_blank_line(patch + 1, plen, ws_rule))
2773 is_blank_context = 1;
2774 case '-':
2775 memcpy(old, patch + 1, plen);
2776 add_line_info(&preimage, old, plen,
2777 (first == ' ' ? LINE_COMMON : 0));
2778 old += plen;
2779 if (first == '-')
2780 break;
2781 /* Fall-through for ' ' */
2782 case '+':
2783 /* --no-add does not add new lines */
2784 if (first == '+' && state->no_add)
2785 break;
2787 start = newlines.len;
2788 if (first != '+' ||
2789 !whitespace_error ||
2790 ws_error_action != correct_ws_error) {
2791 strbuf_add(&newlines, patch + 1, plen);
2793 else {
2794 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &applied_after_fixing_ws);
2796 add_line_info(&postimage, newlines.buf + start, newlines.len - start,
2797 (first == '+' ? 0 : LINE_COMMON));
2798 if (first == '+' &&
2799 (ws_rule & WS_BLANK_AT_EOF) &&
2800 ws_blank_line(patch + 1, plen, ws_rule))
2801 added_blank_line = 1;
2802 break;
2803 case '@': case '\\':
2804 /* Ignore it, we already handled it */
2805 break;
2806 default:
2807 if (state->apply_verbosely)
2808 error(_("invalid start of line: '%c'"), first);
2809 applied_pos = -1;
2810 goto out;
2812 if (added_blank_line) {
2813 if (!new_blank_lines_at_end)
2814 found_new_blank_lines_at_end = hunk_linenr;
2815 new_blank_lines_at_end++;
2817 else if (is_blank_context)
2819 else
2820 new_blank_lines_at_end = 0;
2821 patch += len;
2822 size -= len;
2823 hunk_linenr++;
2825 if (inaccurate_eof &&
2826 old > oldlines && old[-1] == '\n' &&
2827 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
2828 old--;
2829 strbuf_setlen(&newlines, newlines.len - 1);
2832 leading = frag->leading;
2833 trailing = frag->trailing;
2836 * A hunk to change lines at the beginning would begin with
2837 * @@ -1,L +N,M @@
2838 * but we need to be careful. -U0 that inserts before the second
2839 * line also has this pattern.
2841 * And a hunk to add to an empty file would begin with
2842 * @@ -0,0 +N,M @@
2844 * In other words, a hunk that is (frag->oldpos <= 1) with or
2845 * without leading context must match at the beginning.
2847 match_beginning = (!frag->oldpos ||
2848 (frag->oldpos == 1 && !state->unidiff_zero));
2851 * A hunk without trailing lines must match at the end.
2852 * However, we simply cannot tell if a hunk must match end
2853 * from the lack of trailing lines if the patch was generated
2854 * with unidiff without any context.
2856 match_end = !state->unidiff_zero && !trailing;
2858 pos = frag->newpos ? (frag->newpos - 1) : 0;
2859 preimage.buf = oldlines;
2860 preimage.len = old - oldlines;
2861 postimage.buf = newlines.buf;
2862 postimage.len = newlines.len;
2863 preimage.line = preimage.line_allocated;
2864 postimage.line = postimage.line_allocated;
2866 for (;;) {
2868 applied_pos = find_pos(img, &preimage, &postimage, pos,
2869 ws_rule, match_beginning, match_end);
2871 if (applied_pos >= 0)
2872 break;
2874 /* Am I at my context limits? */
2875 if ((leading <= p_context) && (trailing <= p_context))
2876 break;
2877 if (match_beginning || match_end) {
2878 match_beginning = match_end = 0;
2879 continue;
2883 * Reduce the number of context lines; reduce both
2884 * leading and trailing if they are equal otherwise
2885 * just reduce the larger context.
2887 if (leading >= trailing) {
2888 remove_first_line(&preimage);
2889 remove_first_line(&postimage);
2890 pos--;
2891 leading--;
2893 if (trailing > leading) {
2894 remove_last_line(&preimage);
2895 remove_last_line(&postimage);
2896 trailing--;
2900 if (applied_pos >= 0) {
2901 if (new_blank_lines_at_end &&
2902 preimage.nr + applied_pos >= img->nr &&
2903 (ws_rule & WS_BLANK_AT_EOF) &&
2904 ws_error_action != nowarn_ws_error) {
2905 record_ws_error(WS_BLANK_AT_EOF, "+", 1,
2906 found_new_blank_lines_at_end);
2907 if (ws_error_action == correct_ws_error) {
2908 while (new_blank_lines_at_end--)
2909 remove_last_line(&postimage);
2912 * We would want to prevent write_out_results()
2913 * from taking place in apply_patch() that follows
2914 * the callchain led us here, which is:
2915 * apply_patch->check_patch_list->check_patch->
2916 * apply_data->apply_fragments->apply_one_fragment
2918 if (ws_error_action == die_on_ws_error)
2919 apply = 0;
2922 if (state->apply_verbosely && applied_pos != pos) {
2923 int offset = applied_pos - pos;
2924 if (state->apply_in_reverse)
2925 offset = 0 - offset;
2926 fprintf_ln(stderr,
2927 Q_("Hunk #%d succeeded at %d (offset %d line).",
2928 "Hunk #%d succeeded at %d (offset %d lines).",
2929 offset),
2930 nth_fragment, applied_pos + 1, offset);
2934 * Warn if it was necessary to reduce the number
2935 * of context lines.
2937 if ((leading != frag->leading) ||
2938 (trailing != frag->trailing))
2939 fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"
2940 " to apply fragment at %d"),
2941 leading, trailing, applied_pos+1);
2942 update_image(state, img, applied_pos, &preimage, &postimage);
2943 } else {
2944 if (state->apply_verbosely)
2945 error(_("while searching for:\n%.*s"),
2946 (int)(old - oldlines), oldlines);
2949 out:
2950 free(oldlines);
2951 strbuf_release(&newlines);
2952 free(preimage.line_allocated);
2953 free(postimage.line_allocated);
2955 return (applied_pos < 0);
2958 static int apply_binary_fragment(struct apply_state *state,
2959 struct image *img,
2960 struct patch *patch)
2962 struct fragment *fragment = patch->fragments;
2963 unsigned long len;
2964 void *dst;
2966 if (!fragment)
2967 return error(_("missing binary patch data for '%s'"),
2968 patch->new_name ?
2969 patch->new_name :
2970 patch->old_name);
2972 /* Binary patch is irreversible without the optional second hunk */
2973 if (state->apply_in_reverse) {
2974 if (!fragment->next)
2975 return error("cannot reverse-apply a binary patch "
2976 "without the reverse hunk to '%s'",
2977 patch->new_name
2978 ? patch->new_name : patch->old_name);
2979 fragment = fragment->next;
2981 switch (fragment->binary_patch_method) {
2982 case BINARY_DELTA_DEFLATED:
2983 dst = patch_delta(img->buf, img->len, fragment->patch,
2984 fragment->size, &len);
2985 if (!dst)
2986 return -1;
2987 clear_image(img);
2988 img->buf = dst;
2989 img->len = len;
2990 return 0;
2991 case BINARY_LITERAL_DEFLATED:
2992 clear_image(img);
2993 img->len = fragment->size;
2994 img->buf = xmemdupz(fragment->patch, img->len);
2995 return 0;
2997 return -1;
3001 * Replace "img" with the result of applying the binary patch.
3002 * The binary patch data itself in patch->fragment is still kept
3003 * but the preimage prepared by the caller in "img" is freed here
3004 * or in the helper function apply_binary_fragment() this calls.
3006 static int apply_binary(struct apply_state *state,
3007 struct image *img,
3008 struct patch *patch)
3010 const char *name = patch->old_name ? patch->old_name : patch->new_name;
3011 unsigned char sha1[20];
3014 * For safety, we require patch index line to contain
3015 * full 40-byte textual SHA1 for old and new, at least for now.
3017 if (strlen(patch->old_sha1_prefix) != 40 ||
3018 strlen(patch->new_sha1_prefix) != 40 ||
3019 get_sha1_hex(patch->old_sha1_prefix, sha1) ||
3020 get_sha1_hex(patch->new_sha1_prefix, sha1))
3021 return error("cannot apply binary patch to '%s' "
3022 "without full index line", name);
3024 if (patch->old_name) {
3026 * See if the old one matches what the patch
3027 * applies to.
3029 hash_sha1_file(img->buf, img->len, blob_type, sha1);
3030 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
3031 return error("the patch applies to '%s' (%s), "
3032 "which does not match the "
3033 "current contents.",
3034 name, sha1_to_hex(sha1));
3036 else {
3037 /* Otherwise, the old one must be empty. */
3038 if (img->len)
3039 return error("the patch applies to an empty "
3040 "'%s' but it is not empty", name);
3043 get_sha1_hex(patch->new_sha1_prefix, sha1);
3044 if (is_null_sha1(sha1)) {
3045 clear_image(img);
3046 return 0; /* deletion patch */
3049 if (has_sha1_file(sha1)) {
3050 /* We already have the postimage */
3051 enum object_type type;
3052 unsigned long size;
3053 char *result;
3055 result = read_sha1_file(sha1, &type, &size);
3056 if (!result)
3057 return error("the necessary postimage %s for "
3058 "'%s' cannot be read",
3059 patch->new_sha1_prefix, name);
3060 clear_image(img);
3061 img->buf = result;
3062 img->len = size;
3063 } else {
3065 * We have verified buf matches the preimage;
3066 * apply the patch data to it, which is stored
3067 * in the patch->fragments->{patch,size}.
3069 if (apply_binary_fragment(state, img, patch))
3070 return error(_("binary patch does not apply to '%s'"),
3071 name);
3073 /* verify that the result matches */
3074 hash_sha1_file(img->buf, img->len, blob_type, sha1);
3075 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
3076 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3077 name, patch->new_sha1_prefix, sha1_to_hex(sha1));
3080 return 0;
3083 static int apply_fragments(struct apply_state *state, struct image *img, struct patch *patch)
3085 struct fragment *frag = patch->fragments;
3086 const char *name = patch->old_name ? patch->old_name : patch->new_name;
3087 unsigned ws_rule = patch->ws_rule;
3088 unsigned inaccurate_eof = patch->inaccurate_eof;
3089 int nth = 0;
3091 if (patch->is_binary)
3092 return apply_binary(state, img, patch);
3094 while (frag) {
3095 nth++;
3096 if (apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {
3097 error(_("patch failed: %s:%ld"), name, frag->oldpos);
3098 if (!state->apply_with_reject)
3099 return -1;
3100 frag->rejected = 1;
3102 frag = frag->next;
3104 return 0;
3107 static int read_blob_object(struct strbuf *buf, const unsigned char *sha1, unsigned mode)
3109 if (S_ISGITLINK(mode)) {
3110 strbuf_grow(buf, 100);
3111 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(sha1));
3112 } else {
3113 enum object_type type;
3114 unsigned long sz;
3115 char *result;
3117 result = read_sha1_file(sha1, &type, &sz);
3118 if (!result)
3119 return -1;
3120 /* XXX read_sha1_file NUL-terminates */
3121 strbuf_attach(buf, result, sz, sz + 1);
3123 return 0;
3126 static int read_file_or_gitlink(const struct cache_entry *ce, struct strbuf *buf)
3128 if (!ce)
3129 return 0;
3130 return read_blob_object(buf, ce->sha1, ce->ce_mode);
3133 static struct patch *in_fn_table(const char *name)
3135 struct string_list_item *item;
3137 if (name == NULL)
3138 return NULL;
3140 item = string_list_lookup(&fn_table, name);
3141 if (item != NULL)
3142 return (struct patch *)item->util;
3144 return NULL;
3148 * item->util in the filename table records the status of the path.
3149 * Usually it points at a patch (whose result records the contents
3150 * of it after applying it), but it could be PATH_WAS_DELETED for a
3151 * path that a previously applied patch has already removed, or
3152 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3154 * The latter is needed to deal with a case where two paths A and B
3155 * are swapped by first renaming A to B and then renaming B to A;
3156 * moving A to B should not be prevented due to presence of B as we
3157 * will remove it in a later patch.
3159 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3160 #define PATH_WAS_DELETED ((struct patch *) -1)
3162 static int to_be_deleted(struct patch *patch)
3164 return patch == PATH_TO_BE_DELETED;
3167 static int was_deleted(struct patch *patch)
3169 return patch == PATH_WAS_DELETED;
3172 static void add_to_fn_table(struct patch *patch)
3174 struct string_list_item *item;
3177 * Always add new_name unless patch is a deletion
3178 * This should cover the cases for normal diffs,
3179 * file creations and copies
3181 if (patch->new_name != NULL) {
3182 item = string_list_insert(&fn_table, patch->new_name);
3183 item->util = patch;
3187 * store a failure on rename/deletion cases because
3188 * later chunks shouldn't patch old names
3190 if ((patch->new_name == NULL) || (patch->is_rename)) {
3191 item = string_list_insert(&fn_table, patch->old_name);
3192 item->util = PATH_WAS_DELETED;
3196 static void prepare_fn_table(struct patch *patch)
3199 * store information about incoming file deletion
3201 while (patch) {
3202 if ((patch->new_name == NULL) || (patch->is_rename)) {
3203 struct string_list_item *item;
3204 item = string_list_insert(&fn_table, patch->old_name);
3205 item->util = PATH_TO_BE_DELETED;
3207 patch = patch->next;
3211 static int checkout_target(struct index_state *istate,
3212 struct cache_entry *ce, struct stat *st)
3214 struct checkout costate;
3216 memset(&costate, 0, sizeof(costate));
3217 costate.base_dir = "";
3218 costate.refresh_cache = 1;
3219 costate.istate = istate;
3220 if (checkout_entry(ce, &costate, NULL) || lstat(ce->name, st))
3221 return error(_("cannot checkout %s"), ce->name);
3222 return 0;
3225 static struct patch *previous_patch(struct patch *patch, int *gone)
3227 struct patch *previous;
3229 *gone = 0;
3230 if (patch->is_copy || patch->is_rename)
3231 return NULL; /* "git" patches do not depend on the order */
3233 previous = in_fn_table(patch->old_name);
3234 if (!previous)
3235 return NULL;
3237 if (to_be_deleted(previous))
3238 return NULL; /* the deletion hasn't happened yet */
3240 if (was_deleted(previous))
3241 *gone = 1;
3243 return previous;
3246 static int verify_index_match(const struct cache_entry *ce, struct stat *st)
3248 if (S_ISGITLINK(ce->ce_mode)) {
3249 if (!S_ISDIR(st->st_mode))
3250 return -1;
3251 return 0;
3253 return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
3256 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3258 static int load_patch_target(struct apply_state *state,
3259 struct strbuf *buf,
3260 const struct cache_entry *ce,
3261 struct stat *st,
3262 const char *name,
3263 unsigned expected_mode)
3265 if (state->cached || state->check_index) {
3266 if (read_file_or_gitlink(ce, buf))
3267 return error(_("read of %s failed"), name);
3268 } else if (name) {
3269 if (S_ISGITLINK(expected_mode)) {
3270 if (ce)
3271 return read_file_or_gitlink(ce, buf);
3272 else
3273 return SUBMODULE_PATCH_WITHOUT_INDEX;
3274 } else if (has_symlink_leading_path(name, strlen(name))) {
3275 return error(_("reading from '%s' beyond a symbolic link"), name);
3276 } else {
3277 if (read_old_data(st, name, buf))
3278 return error(_("read of %s failed"), name);
3281 return 0;
3285 * We are about to apply "patch"; populate the "image" with the
3286 * current version we have, from the working tree or from the index,
3287 * depending on the situation e.g. --cached/--index. If we are
3288 * applying a non-git patch that incrementally updates the tree,
3289 * we read from the result of a previous diff.
3291 static int load_preimage(struct apply_state *state,
3292 struct image *image,
3293 struct patch *patch, struct stat *st,
3294 const struct cache_entry *ce)
3296 struct strbuf buf = STRBUF_INIT;
3297 size_t len;
3298 char *img;
3299 struct patch *previous;
3300 int status;
3302 previous = previous_patch(patch, &status);
3303 if (status)
3304 return error(_("path %s has been renamed/deleted"),
3305 patch->old_name);
3306 if (previous) {
3307 /* We have a patched copy in memory; use that. */
3308 strbuf_add(&buf, previous->result, previous->resultsize);
3309 } else {
3310 status = load_patch_target(state, &buf, ce, st,
3311 patch->old_name, patch->old_mode);
3312 if (status < 0)
3313 return status;
3314 else if (status == SUBMODULE_PATCH_WITHOUT_INDEX) {
3316 * There is no way to apply subproject
3317 * patch without looking at the index.
3318 * NEEDSWORK: shouldn't this be flagged
3319 * as an error???
3321 free_fragment_list(patch->fragments);
3322 patch->fragments = NULL;
3323 } else if (status) {
3324 return error(_("read of %s failed"), patch->old_name);
3328 img = strbuf_detach(&buf, &len);
3329 prepare_image(image, img, len, !patch->is_binary);
3330 return 0;
3333 static int three_way_merge(struct image *image,
3334 char *path,
3335 const unsigned char *base,
3336 const unsigned char *ours,
3337 const unsigned char *theirs)
3339 mmfile_t base_file, our_file, their_file;
3340 mmbuffer_t result = { NULL };
3341 int status;
3343 read_mmblob(&base_file, base);
3344 read_mmblob(&our_file, ours);
3345 read_mmblob(&their_file, theirs);
3346 status = ll_merge(&result, path,
3347 &base_file, "base",
3348 &our_file, "ours",
3349 &their_file, "theirs", NULL);
3350 free(base_file.ptr);
3351 free(our_file.ptr);
3352 free(their_file.ptr);
3353 if (status < 0 || !result.ptr) {
3354 free(result.ptr);
3355 return -1;
3357 clear_image(image);
3358 image->buf = result.ptr;
3359 image->len = result.size;
3361 return status;
3365 * When directly falling back to add/add three-way merge, we read from
3366 * the current contents of the new_name. In no cases other than that
3367 * this function will be called.
3369 static int load_current(struct apply_state *state,
3370 struct image *image,
3371 struct patch *patch)
3373 struct strbuf buf = STRBUF_INIT;
3374 int status, pos;
3375 size_t len;
3376 char *img;
3377 struct stat st;
3378 struct cache_entry *ce;
3379 char *name = patch->new_name;
3380 unsigned mode = patch->new_mode;
3382 if (!patch->is_new)
3383 die("BUG: patch to %s is not a creation", patch->old_name);
3385 pos = cache_name_pos(name, strlen(name));
3386 if (pos < 0)
3387 return error(_("%s: does not exist in index"), name);
3388 ce = active_cache[pos];
3389 if (lstat(name, &st)) {
3390 if (errno != ENOENT)
3391 return error(_("%s: %s"), name, strerror(errno));
3392 if (checkout_target(&the_index, ce, &st))
3393 return -1;
3395 if (verify_index_match(ce, &st))
3396 return error(_("%s: does not match index"), name);
3398 status = load_patch_target(state, &buf, ce, &st, name, mode);
3399 if (status < 0)
3400 return status;
3401 else if (status)
3402 return -1;
3403 img = strbuf_detach(&buf, &len);
3404 prepare_image(image, img, len, !patch->is_binary);
3405 return 0;
3408 static int try_threeway(struct apply_state *state,
3409 struct image *image,
3410 struct patch *patch,
3411 struct stat *st,
3412 const struct cache_entry *ce)
3414 unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];
3415 struct strbuf buf = STRBUF_INIT;
3416 size_t len;
3417 int status;
3418 char *img;
3419 struct image tmp_image;
3421 /* No point falling back to 3-way merge in these cases */
3422 if (patch->is_delete ||
3423 S_ISGITLINK(patch->old_mode) || S_ISGITLINK(patch->new_mode))
3424 return -1;
3426 /* Preimage the patch was prepared for */
3427 if (patch->is_new)
3428 write_sha1_file("", 0, blob_type, pre_sha1);
3429 else if (get_sha1(patch->old_sha1_prefix, pre_sha1) ||
3430 read_blob_object(&buf, pre_sha1, patch->old_mode))
3431 return error("repository lacks the necessary blob to fall back on 3-way merge.");
3433 fprintf(stderr, "Falling back to three-way merge...\n");
3435 img = strbuf_detach(&buf, &len);
3436 prepare_image(&tmp_image, img, len, 1);
3437 /* Apply the patch to get the post image */
3438 if (apply_fragments(state, &tmp_image, patch) < 0) {
3439 clear_image(&tmp_image);
3440 return -1;
3442 /* post_sha1[] is theirs */
3443 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);
3444 clear_image(&tmp_image);
3446 /* our_sha1[] is ours */
3447 if (patch->is_new) {
3448 if (load_current(state, &tmp_image, patch))
3449 return error("cannot read the current contents of '%s'",
3450 patch->new_name);
3451 } else {
3452 if (load_preimage(state, &tmp_image, patch, st, ce))
3453 return error("cannot read the current contents of '%s'",
3454 patch->old_name);
3456 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);
3457 clear_image(&tmp_image);
3459 /* in-core three-way merge between post and our using pre as base */
3460 status = three_way_merge(image, patch->new_name,
3461 pre_sha1, our_sha1, post_sha1);
3462 if (status < 0) {
3463 fprintf(stderr, "Failed to fall back on three-way merge...\n");
3464 return status;
3467 if (status) {
3468 patch->conflicted_threeway = 1;
3469 if (patch->is_new)
3470 oidclr(&patch->threeway_stage[0]);
3471 else
3472 hashcpy(patch->threeway_stage[0].hash, pre_sha1);
3473 hashcpy(patch->threeway_stage[1].hash, our_sha1);
3474 hashcpy(patch->threeway_stage[2].hash, post_sha1);
3475 fprintf(stderr, "Applied patch to '%s' with conflicts.\n", patch->new_name);
3476 } else {
3477 fprintf(stderr, "Applied patch to '%s' cleanly.\n", patch->new_name);
3479 return 0;
3482 static int apply_data(struct apply_state *state, struct patch *patch,
3483 struct stat *st, const struct cache_entry *ce)
3485 struct image image;
3487 if (load_preimage(state, &image, patch, st, ce) < 0)
3488 return -1;
3490 if (patch->direct_to_threeway ||
3491 apply_fragments(state, &image, patch) < 0) {
3492 /* Note: with --reject, apply_fragments() returns 0 */
3493 if (!state->threeway || try_threeway(state, &image, patch, st, ce) < 0)
3494 return -1;
3496 patch->result = image.buf;
3497 patch->resultsize = image.len;
3498 add_to_fn_table(patch);
3499 free(image.line_allocated);
3501 if (0 < patch->is_delete && patch->resultsize)
3502 return error(_("removal patch leaves file contents"));
3504 return 0;
3508 * If "patch" that we are looking at modifies or deletes what we have,
3509 * we would want it not to lose any local modification we have, either
3510 * in the working tree or in the index.
3512 * This also decides if a non-git patch is a creation patch or a
3513 * modification to an existing empty file. We do not check the state
3514 * of the current tree for a creation patch in this function; the caller
3515 * check_patch() separately makes sure (and errors out otherwise) that
3516 * the path the patch creates does not exist in the current tree.
3518 static int check_preimage(struct apply_state *state,
3519 struct patch *patch,
3520 struct cache_entry **ce,
3521 struct stat *st)
3523 const char *old_name = patch->old_name;
3524 struct patch *previous = NULL;
3525 int stat_ret = 0, status;
3526 unsigned st_mode = 0;
3528 if (!old_name)
3529 return 0;
3531 assert(patch->is_new <= 0);
3532 previous = previous_patch(patch, &status);
3534 if (status)
3535 return error(_("path %s has been renamed/deleted"), old_name);
3536 if (previous) {
3537 st_mode = previous->new_mode;
3538 } else if (!state->cached) {
3539 stat_ret = lstat(old_name, st);
3540 if (stat_ret && errno != ENOENT)
3541 return error(_("%s: %s"), old_name, strerror(errno));
3544 if (state->check_index && !previous) {
3545 int pos = cache_name_pos(old_name, strlen(old_name));
3546 if (pos < 0) {
3547 if (patch->is_new < 0)
3548 goto is_new;
3549 return error(_("%s: does not exist in index"), old_name);
3551 *ce = active_cache[pos];
3552 if (stat_ret < 0) {
3553 if (checkout_target(&the_index, *ce, st))
3554 return -1;
3556 if (!state->cached && verify_index_match(*ce, st))
3557 return error(_("%s: does not match index"), old_name);
3558 if (state->cached)
3559 st_mode = (*ce)->ce_mode;
3560 } else if (stat_ret < 0) {
3561 if (patch->is_new < 0)
3562 goto is_new;
3563 return error(_("%s: %s"), old_name, strerror(errno));
3566 if (!state->cached && !previous)
3567 st_mode = ce_mode_from_stat(*ce, st->st_mode);
3569 if (patch->is_new < 0)
3570 patch->is_new = 0;
3571 if (!patch->old_mode)
3572 patch->old_mode = st_mode;
3573 if ((st_mode ^ patch->old_mode) & S_IFMT)
3574 return error(_("%s: wrong type"), old_name);
3575 if (st_mode != patch->old_mode)
3576 warning(_("%s has type %o, expected %o"),
3577 old_name, st_mode, patch->old_mode);
3578 if (!patch->new_mode && !patch->is_delete)
3579 patch->new_mode = st_mode;
3580 return 0;
3582 is_new:
3583 patch->is_new = 1;
3584 patch->is_delete = 0;
3585 free(patch->old_name);
3586 patch->old_name = NULL;
3587 return 0;
3591 #define EXISTS_IN_INDEX 1
3592 #define EXISTS_IN_WORKTREE 2
3594 static int check_to_create(struct apply_state *state,
3595 const char *new_name,
3596 int ok_if_exists)
3598 struct stat nst;
3600 if (state->check_index &&
3601 cache_name_pos(new_name, strlen(new_name)) >= 0 &&
3602 !ok_if_exists)
3603 return EXISTS_IN_INDEX;
3604 if (state->cached)
3605 return 0;
3607 if (!lstat(new_name, &nst)) {
3608 if (S_ISDIR(nst.st_mode) || ok_if_exists)
3609 return 0;
3611 * A leading component of new_name might be a symlink
3612 * that is going to be removed with this patch, but
3613 * still pointing at somewhere that has the path.
3614 * In such a case, path "new_name" does not exist as
3615 * far as git is concerned.
3617 if (has_symlink_leading_path(new_name, strlen(new_name)))
3618 return 0;
3620 return EXISTS_IN_WORKTREE;
3621 } else if ((errno != ENOENT) && (errno != ENOTDIR)) {
3622 return error("%s: %s", new_name, strerror(errno));
3624 return 0;
3628 * We need to keep track of how symlinks in the preimage are
3629 * manipulated by the patches. A patch to add a/b/c where a/b
3630 * is a symlink should not be allowed to affect the directory
3631 * the symlink points at, but if the same patch removes a/b,
3632 * it is perfectly fine, as the patch removes a/b to make room
3633 * to create a directory a/b so that a/b/c can be created.
3635 static struct string_list symlink_changes;
3636 #define SYMLINK_GOES_AWAY 01
3637 #define SYMLINK_IN_RESULT 02
3639 static uintptr_t register_symlink_changes(const char *path, uintptr_t what)
3641 struct string_list_item *ent;
3643 ent = string_list_lookup(&symlink_changes, path);
3644 if (!ent) {
3645 ent = string_list_insert(&symlink_changes, path);
3646 ent->util = (void *)0;
3648 ent->util = (void *)(what | ((uintptr_t)ent->util));
3649 return (uintptr_t)ent->util;
3652 static uintptr_t check_symlink_changes(const char *path)
3654 struct string_list_item *ent;
3656 ent = string_list_lookup(&symlink_changes, path);
3657 if (!ent)
3658 return 0;
3659 return (uintptr_t)ent->util;
3662 static void prepare_symlink_changes(struct patch *patch)
3664 for ( ; patch; patch = patch->next) {
3665 if ((patch->old_name && S_ISLNK(patch->old_mode)) &&
3666 (patch->is_rename || patch->is_delete))
3667 /* the symlink at patch->old_name is removed */
3668 register_symlink_changes(patch->old_name, SYMLINK_GOES_AWAY);
3670 if (patch->new_name && S_ISLNK(patch->new_mode))
3671 /* the symlink at patch->new_name is created or remains */
3672 register_symlink_changes(patch->new_name, SYMLINK_IN_RESULT);
3676 static int path_is_beyond_symlink_1(struct apply_state *state, struct strbuf *name)
3678 do {
3679 unsigned int change;
3681 while (--name->len && name->buf[name->len] != '/')
3682 ; /* scan backwards */
3683 if (!name->len)
3684 break;
3685 name->buf[name->len] = '\0';
3686 change = check_symlink_changes(name->buf);
3687 if (change & SYMLINK_IN_RESULT)
3688 return 1;
3689 if (change & SYMLINK_GOES_AWAY)
3691 * This cannot be "return 0", because we may
3692 * see a new one created at a higher level.
3694 continue;
3696 /* otherwise, check the preimage */
3697 if (state->check_index) {
3698 struct cache_entry *ce;
3700 ce = cache_file_exists(name->buf, name->len, ignore_case);
3701 if (ce && S_ISLNK(ce->ce_mode))
3702 return 1;
3703 } else {
3704 struct stat st;
3705 if (!lstat(name->buf, &st) && S_ISLNK(st.st_mode))
3706 return 1;
3708 } while (1);
3709 return 0;
3712 static int path_is_beyond_symlink(struct apply_state *state, const char *name_)
3714 int ret;
3715 struct strbuf name = STRBUF_INIT;
3717 assert(*name_ != '\0');
3718 strbuf_addstr(&name, name_);
3719 ret = path_is_beyond_symlink_1(state, &name);
3720 strbuf_release(&name);
3722 return ret;
3725 static void die_on_unsafe_path(struct patch *patch)
3727 const char *old_name = NULL;
3728 const char *new_name = NULL;
3729 if (patch->is_delete)
3730 old_name = patch->old_name;
3731 else if (!patch->is_new && !patch->is_copy)
3732 old_name = patch->old_name;
3733 if (!patch->is_delete)
3734 new_name = patch->new_name;
3736 if (old_name && !verify_path(old_name))
3737 die(_("invalid path '%s'"), old_name);
3738 if (new_name && !verify_path(new_name))
3739 die(_("invalid path '%s'"), new_name);
3743 * Check and apply the patch in-core; leave the result in patch->result
3744 * for the caller to write it out to the final destination.
3746 static int check_patch(struct apply_state *state, struct patch *patch)
3748 struct stat st;
3749 const char *old_name = patch->old_name;
3750 const char *new_name = patch->new_name;
3751 const char *name = old_name ? old_name : new_name;
3752 struct cache_entry *ce = NULL;
3753 struct patch *tpatch;
3754 int ok_if_exists;
3755 int status;
3757 patch->rejected = 1; /* we will drop this after we succeed */
3759 status = check_preimage(state, patch, &ce, &st);
3760 if (status)
3761 return status;
3762 old_name = patch->old_name;
3765 * A type-change diff is always split into a patch to delete
3766 * old, immediately followed by a patch to create new (see
3767 * diff.c::run_diff()); in such a case it is Ok that the entry
3768 * to be deleted by the previous patch is still in the working
3769 * tree and in the index.
3771 * A patch to swap-rename between A and B would first rename A
3772 * to B and then rename B to A. While applying the first one,
3773 * the presence of B should not stop A from getting renamed to
3774 * B; ask to_be_deleted() about the later rename. Removal of
3775 * B and rename from A to B is handled the same way by asking
3776 * was_deleted().
3778 if ((tpatch = in_fn_table(new_name)) &&
3779 (was_deleted(tpatch) || to_be_deleted(tpatch)))
3780 ok_if_exists = 1;
3781 else
3782 ok_if_exists = 0;
3784 if (new_name &&
3785 ((0 < patch->is_new) || patch->is_rename || patch->is_copy)) {
3786 int err = check_to_create(state, new_name, ok_if_exists);
3788 if (err && state->threeway) {
3789 patch->direct_to_threeway = 1;
3790 } else switch (err) {
3791 case 0:
3792 break; /* happy */
3793 case EXISTS_IN_INDEX:
3794 return error(_("%s: already exists in index"), new_name);
3795 break;
3796 case EXISTS_IN_WORKTREE:
3797 return error(_("%s: already exists in working directory"),
3798 new_name);
3799 default:
3800 return err;
3803 if (!patch->new_mode) {
3804 if (0 < patch->is_new)
3805 patch->new_mode = S_IFREG | 0644;
3806 else
3807 patch->new_mode = patch->old_mode;
3811 if (new_name && old_name) {
3812 int same = !strcmp(old_name, new_name);
3813 if (!patch->new_mode)
3814 patch->new_mode = patch->old_mode;
3815 if ((patch->old_mode ^ patch->new_mode) & S_IFMT) {
3816 if (same)
3817 return error(_("new mode (%o) of %s does not "
3818 "match old mode (%o)"),
3819 patch->new_mode, new_name,
3820 patch->old_mode);
3821 else
3822 return error(_("new mode (%o) of %s does not "
3823 "match old mode (%o) of %s"),
3824 patch->new_mode, new_name,
3825 patch->old_mode, old_name);
3829 if (!state->unsafe_paths)
3830 die_on_unsafe_path(patch);
3833 * An attempt to read from or delete a path that is beyond a
3834 * symbolic link will be prevented by load_patch_target() that
3835 * is called at the beginning of apply_data() so we do not
3836 * have to worry about a patch marked with "is_delete" bit
3837 * here. We however need to make sure that the patch result
3838 * is not deposited to a path that is beyond a symbolic link
3839 * here.
3841 if (!patch->is_delete && path_is_beyond_symlink(state, patch->new_name))
3842 return error(_("affected file '%s' is beyond a symbolic link"),
3843 patch->new_name);
3845 if (apply_data(state, patch, &st, ce) < 0)
3846 return error(_("%s: patch does not apply"), name);
3847 patch->rejected = 0;
3848 return 0;
3851 static int check_patch_list(struct apply_state *state, struct patch *patch)
3853 int err = 0;
3855 prepare_symlink_changes(patch);
3856 prepare_fn_table(patch);
3857 while (patch) {
3858 if (state->apply_verbosely)
3859 say_patch_name(stderr,
3860 _("Checking patch %s..."), patch);
3861 err |= check_patch(state, patch);
3862 patch = patch->next;
3864 return err;
3867 /* This function tries to read the sha1 from the current index */
3868 static int get_current_sha1(const char *path, unsigned char *sha1)
3870 int pos;
3872 if (read_cache() < 0)
3873 return -1;
3874 pos = cache_name_pos(path, strlen(path));
3875 if (pos < 0)
3876 return -1;
3877 hashcpy(sha1, active_cache[pos]->sha1);
3878 return 0;
3881 static int preimage_sha1_in_gitlink_patch(struct patch *p, unsigned char sha1[20])
3884 * A usable gitlink patch has only one fragment (hunk) that looks like:
3885 * @@ -1 +1 @@
3886 * -Subproject commit <old sha1>
3887 * +Subproject commit <new sha1>
3888 * or
3889 * @@ -1 +0,0 @@
3890 * -Subproject commit <old sha1>
3891 * for a removal patch.
3893 struct fragment *hunk = p->fragments;
3894 static const char heading[] = "-Subproject commit ";
3895 char *preimage;
3897 if (/* does the patch have only one hunk? */
3898 hunk && !hunk->next &&
3899 /* is its preimage one line? */
3900 hunk->oldpos == 1 && hunk->oldlines == 1 &&
3901 /* does preimage begin with the heading? */
3902 (preimage = memchr(hunk->patch, '\n', hunk->size)) != NULL &&
3903 starts_with(++preimage, heading) &&
3904 /* does it record full SHA-1? */
3905 !get_sha1_hex(preimage + sizeof(heading) - 1, sha1) &&
3906 preimage[sizeof(heading) + 40 - 1] == '\n' &&
3907 /* does the abbreviated name on the index line agree with it? */
3908 starts_with(preimage + sizeof(heading) - 1, p->old_sha1_prefix))
3909 return 0; /* it all looks fine */
3911 /* we may have full object name on the index line */
3912 return get_sha1_hex(p->old_sha1_prefix, sha1);
3915 /* Build an index that contains the just the files needed for a 3way merge */
3916 static void build_fake_ancestor(struct patch *list, const char *filename)
3918 struct patch *patch;
3919 struct index_state result = { NULL };
3920 static struct lock_file lock;
3922 /* Once we start supporting the reverse patch, it may be
3923 * worth showing the new sha1 prefix, but until then...
3925 for (patch = list; patch; patch = patch->next) {
3926 unsigned char sha1[20];
3927 struct cache_entry *ce;
3928 const char *name;
3930 name = patch->old_name ? patch->old_name : patch->new_name;
3931 if (0 < patch->is_new)
3932 continue;
3934 if (S_ISGITLINK(patch->old_mode)) {
3935 if (!preimage_sha1_in_gitlink_patch(patch, sha1))
3936 ; /* ok, the textual part looks sane */
3937 else
3938 die("sha1 information is lacking or useless for submodule %s",
3939 name);
3940 } else if (!get_sha1_blob(patch->old_sha1_prefix, sha1)) {
3941 ; /* ok */
3942 } else if (!patch->lines_added && !patch->lines_deleted) {
3943 /* mode-only change: update the current */
3944 if (get_current_sha1(patch->old_name, sha1))
3945 die("mode change for %s, which is not "
3946 "in current HEAD", name);
3947 } else
3948 die("sha1 information is lacking or useless "
3949 "(%s).", name);
3951 ce = make_cache_entry(patch->old_mode, sha1, name, 0, 0);
3952 if (!ce)
3953 die(_("make_cache_entry failed for path '%s'"), name);
3954 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))
3955 die ("Could not add %s to temporary index", name);
3958 hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);
3959 if (write_locked_index(&result, &lock, COMMIT_LOCK))
3960 die ("Could not write temporary index to %s", filename);
3962 discard_index(&result);
3965 static void stat_patch_list(struct patch *patch)
3967 int files, adds, dels;
3969 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
3970 files++;
3971 adds += patch->lines_added;
3972 dels += patch->lines_deleted;
3973 show_stats(patch);
3976 print_stat_summary(stdout, files, adds, dels);
3979 static void numstat_patch_list(struct apply_state *state,
3980 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, state->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 (state->fake_ancestor)
4487 build_fake_ancestor(list, state->fake_ancestor);
4489 if (state->diffstat)
4490 stat_patch_list(list);
4492 if (state->numstat)
4493 numstat_patch_list(state, list);
4495 if (state->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;
4568 state->line_termination = '\n';
4570 git_apply_config();
4571 if (apply_default_whitespace)
4572 parse_whitespace_option(apply_default_whitespace);
4573 if (apply_default_ignorewhitespace)
4574 parse_ignorewhitespace_option(apply_default_ignorewhitespace);
4577 static void clear_apply_state(struct apply_state *state)
4579 /* empty for now */
4582 int cmd_apply(int argc, const char **argv, const char *prefix)
4584 int i;
4585 int errs = 0;
4586 int is_not_gitdir = !startup_info->have_repository;
4587 int force_apply = 0;
4588 int options = 0;
4589 int read_stdin = 1;
4590 struct apply_state state;
4592 const char *whitespace_option = NULL;
4594 struct option builtin_apply_options[] = {
4595 { OPTION_CALLBACK, 0, "exclude", NULL, N_("path"),
4596 N_("don't apply changes matching the given path"),
4597 0, option_parse_exclude },
4598 { OPTION_CALLBACK, 0, "include", NULL, N_("path"),
4599 N_("apply changes matching the given path"),
4600 0, option_parse_include },
4601 { OPTION_CALLBACK, 'p', NULL, NULL, N_("num"),
4602 N_("remove <num> leading slashes from traditional diff paths"),
4603 0, option_parse_p },
4604 OPT_BOOL(0, "no-add", &state.no_add,
4605 N_("ignore additions made by the patch")),
4606 OPT_BOOL(0, "stat", &state.diffstat,
4607 N_("instead of applying the patch, output diffstat for the input")),
4608 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
4609 OPT_NOOP_NOARG(0, "binary"),
4610 OPT_BOOL(0, "numstat", &state.numstat,
4611 N_("show number of added and deleted lines in decimal notation")),
4612 OPT_BOOL(0, "summary", &state.summary,
4613 N_("instead of applying the patch, output a summary for the input")),
4614 OPT_BOOL(0, "check", &state.check,
4615 N_("instead of applying the patch, see if the patch is applicable")),
4616 OPT_BOOL(0, "index", &state.check_index,
4617 N_("make sure the patch is applicable to the current index")),
4618 OPT_BOOL(0, "cached", &state.cached,
4619 N_("apply a patch without touching the working tree")),
4620 OPT_BOOL(0, "unsafe-paths", &state.unsafe_paths,
4621 N_("accept a patch that touches outside the working area")),
4622 OPT_BOOL(0, "apply", &force_apply,
4623 N_("also apply the patch (use with --stat/--summary/--check)")),
4624 OPT_BOOL('3', "3way", &state.threeway,
4625 N_( "attempt three-way merge if a patch does not apply")),
4626 OPT_FILENAME(0, "build-fake-ancestor", &state.fake_ancestor,
4627 N_("build a temporary index based on embedded index information")),
4628 /* Think twice before adding "--nul" synonym to this */
4629 OPT_SET_INT('z', NULL, &state.line_termination,
4630 N_("paths are separated with NUL character"), '\0'),
4631 OPT_INTEGER('C', NULL, &p_context,
4632 N_("ensure at least <n> lines of context match")),
4633 { OPTION_CALLBACK, 0, "whitespace", &whitespace_option, N_("action"),
4634 N_("detect new or modified lines that have whitespace errors"),
4635 0, option_parse_whitespace },
4636 { OPTION_CALLBACK, 0, "ignore-space-change", NULL, NULL,
4637 N_("ignore changes in whitespace when finding context"),
4638 PARSE_OPT_NOARG, option_parse_space_change },
4639 { OPTION_CALLBACK, 0, "ignore-whitespace", NULL, NULL,
4640 N_("ignore changes in whitespace when finding context"),
4641 PARSE_OPT_NOARG, option_parse_space_change },
4642 OPT_BOOL('R', "reverse", &state.apply_in_reverse,
4643 N_("apply the patch in reverse")),
4644 OPT_BOOL(0, "unidiff-zero", &state.unidiff_zero,
4645 N_("don't expect at least one line of context")),
4646 OPT_BOOL(0, "reject", &state.apply_with_reject,
4647 N_("leave the rejected hunks in corresponding *.rej files")),
4648 OPT_BOOL(0, "allow-overlap", &state.allow_overlap,
4649 N_("allow overlapping hunks")),
4650 OPT__VERBOSE(&state.apply_verbosely, N_("be verbose")),
4651 OPT_BIT(0, "inaccurate-eof", &options,
4652 N_("tolerate incorrectly detected missing new-line at the end of file"),
4653 INACCURATE_EOF),
4654 OPT_BIT(0, "recount", &options,
4655 N_("do not trust the line counts in the hunk headers"),
4656 RECOUNT),
4657 { OPTION_CALLBACK, 0, "directory", NULL, N_("root"),
4658 N_("prepend <root> to all filenames"),
4659 0, option_parse_directory },
4660 OPT_END()
4663 init_apply_state(&state, prefix);
4665 argc = parse_options(argc, argv, state.prefix, builtin_apply_options,
4666 apply_usage, 0);
4668 if (state.apply_with_reject && state.threeway)
4669 die("--reject and --3way cannot be used together.");
4670 if (state.cached && state.threeway)
4671 die("--cached and --3way cannot be used together.");
4672 if (state.threeway) {
4673 if (is_not_gitdir)
4674 die(_("--3way outside a repository"));
4675 state.check_index = 1;
4677 if (state.apply_with_reject)
4678 apply = state.apply_verbosely = 1;
4679 if (!force_apply && (state.diffstat || state.numstat || state.summary || state.check || state.fake_ancestor))
4680 apply = 0;
4681 if (state.check_index && is_not_gitdir)
4682 die(_("--index outside a repository"));
4683 if (state.cached) {
4684 if (is_not_gitdir)
4685 die(_("--cached outside a repository"));
4686 state.check_index = 1;
4688 if (state.check_index)
4689 state.unsafe_paths = 0;
4691 for (i = 0; i < argc; i++) {
4692 const char *arg = argv[i];
4693 int fd;
4695 if (!strcmp(arg, "-")) {
4696 errs |= apply_patch(&state, 0, "<stdin>", options);
4697 read_stdin = 0;
4698 continue;
4699 } else if (0 < state.prefix_length)
4700 arg = prefix_filename(state.prefix,
4701 state.prefix_length,
4702 arg);
4704 fd = open(arg, O_RDONLY);
4705 if (fd < 0)
4706 die_errno(_("can't open patch '%s'"), arg);
4707 read_stdin = 0;
4708 set_default_whitespace_mode(whitespace_option);
4709 errs |= apply_patch(&state, fd, arg, options);
4710 close(fd);
4712 set_default_whitespace_mode(whitespace_option);
4713 if (read_stdin)
4714 errs |= apply_patch(&state, 0, "<stdin>", options);
4715 if (whitespace_error) {
4716 if (squelch_whitespace_errors &&
4717 squelch_whitespace_errors < whitespace_error) {
4718 int squelched =
4719 whitespace_error - squelch_whitespace_errors;
4720 warning(Q_("squelched %d whitespace error",
4721 "squelched %d whitespace errors",
4722 squelched),
4723 squelched);
4725 if (ws_error_action == die_on_ws_error)
4726 die(Q_("%d line adds whitespace errors.",
4727 "%d lines add whitespace errors.",
4728 whitespace_error),
4729 whitespace_error);
4730 if (applied_after_fixing_ws && apply)
4731 warning("%d line%s applied after"
4732 " fixing whitespace errors.",
4733 applied_after_fixing_ws,
4734 applied_after_fixing_ws == 1 ? "" : "s");
4735 else if (whitespace_error)
4736 warning(Q_("%d line adds whitespace errors.",
4737 "%d lines add whitespace errors.",
4738 whitespace_error),
4739 whitespace_error);
4742 if (state.update_index) {
4743 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
4744 die(_("Unable to write new index file"));
4747 clear_apply_state(&state);
4749 return !!errs;