apply: fall back on three-way merge
[git/mingw.git] / builtin / apply.c
blob5a7201fc86db9462c901481f8cb2b394604977b5
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 "cache-tree.h"
11 #include "quote.h"
12 #include "blob.h"
13 #include "delta.h"
14 #include "builtin.h"
15 #include "string-list.h"
16 #include "dir.h"
17 #include "diff.h"
18 #include "parse-options.h"
21 * --check turns on checking that the working tree matches the
22 * files that are being modified, but doesn't apply the patch
23 * --stat does just a diffstat, and doesn't actually apply
24 * --numstat does numeric diffstat, and doesn't actually apply
25 * --index-info shows the old and new index info for paths if available.
26 * --index updates the cache as well.
27 * --cached updates only the cache without ever touching the working tree.
29 static const char *prefix;
30 static int prefix_length = -1;
31 static int newfd = -1;
33 static int unidiff_zero;
34 static int p_value = 1;
35 static int p_value_known;
36 static int check_index;
37 static int update_index;
38 static int cached;
39 static int diffstat;
40 static int numstat;
41 static int summary;
42 static int check;
43 static int apply = 1;
44 static int apply_in_reverse;
45 static int apply_with_reject;
46 static int apply_verbosely;
47 static int allow_overlap;
48 static int no_add;
49 static int threeway;
50 static const char *fake_ancestor;
51 static int line_termination = '\n';
52 static unsigned int p_context = UINT_MAX;
53 static const char * const apply_usage[] = {
54 "git apply [options] [<patch>...]",
55 NULL
58 static enum ws_error_action {
59 nowarn_ws_error,
60 warn_on_ws_error,
61 die_on_ws_error,
62 correct_ws_error
63 } ws_error_action = warn_on_ws_error;
64 static int whitespace_error;
65 static int squelch_whitespace_errors = 5;
66 static int applied_after_fixing_ws;
68 static enum ws_ignore {
69 ignore_ws_none,
70 ignore_ws_change
71 } ws_ignore_action = ignore_ws_none;
74 static const char *patch_input_file;
75 static const char *root;
76 static int root_len;
77 static int read_stdin = 1;
78 static int options;
80 static void parse_whitespace_option(const char *option)
82 if (!option) {
83 ws_error_action = warn_on_ws_error;
84 return;
86 if (!strcmp(option, "warn")) {
87 ws_error_action = warn_on_ws_error;
88 return;
90 if (!strcmp(option, "nowarn")) {
91 ws_error_action = nowarn_ws_error;
92 return;
94 if (!strcmp(option, "error")) {
95 ws_error_action = die_on_ws_error;
96 return;
98 if (!strcmp(option, "error-all")) {
99 ws_error_action = die_on_ws_error;
100 squelch_whitespace_errors = 0;
101 return;
103 if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
104 ws_error_action = correct_ws_error;
105 return;
107 die(_("unrecognized whitespace option '%s'"), option);
110 static void parse_ignorewhitespace_option(const char *option)
112 if (!option || !strcmp(option, "no") ||
113 !strcmp(option, "false") || !strcmp(option, "never") ||
114 !strcmp(option, "none")) {
115 ws_ignore_action = ignore_ws_none;
116 return;
118 if (!strcmp(option, "change")) {
119 ws_ignore_action = ignore_ws_change;
120 return;
122 die(_("unrecognized whitespace ignore option '%s'"), option);
125 static void set_default_whitespace_mode(const char *whitespace_option)
127 if (!whitespace_option && !apply_default_whitespace)
128 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error);
132 * For "diff-stat" like behaviour, we keep track of the biggest change
133 * we've seen, and the longest filename. That allows us to do simple
134 * scaling.
136 static int max_change, max_len;
139 * Various "current state", notably line numbers and what
140 * file (and how) we're patching right now.. The "is_xxxx"
141 * things are flags, where -1 means "don't know yet".
143 static int linenr = 1;
146 * This represents one "hunk" from a patch, starting with
147 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
148 * patch text is pointed at by patch, and its byte length
149 * is stored in size. leading and trailing are the number
150 * of context lines.
152 struct fragment {
153 unsigned long leading, trailing;
154 unsigned long oldpos, oldlines;
155 unsigned long newpos, newlines;
157 * 'patch' is usually borrowed from buf in apply_patch(),
158 * but some codepaths store an allocated buffer.
160 const char *patch;
161 unsigned free_patch:1,
162 rejected:1;
163 int size;
164 int linenr;
165 struct fragment *next;
169 * When dealing with a binary patch, we reuse "leading" field
170 * to store the type of the binary hunk, either deflated "delta"
171 * or deflated "literal".
173 #define binary_patch_method leading
174 #define BINARY_DELTA_DEFLATED 1
175 #define BINARY_LITERAL_DEFLATED 2
178 * This represents a "patch" to a file, both metainfo changes
179 * such as creation/deletion, filemode and content changes represented
180 * as a series of fragments.
182 struct patch {
183 char *new_name, *old_name, *def_name;
184 unsigned int old_mode, new_mode;
185 int is_new, is_delete; /* -1 = unknown, 0 = false, 1 = true */
186 int rejected;
187 unsigned ws_rule;
188 unsigned long deflate_origlen;
189 int lines_added, lines_deleted;
190 int score;
191 unsigned int is_toplevel_relative:1;
192 unsigned int inaccurate_eof:1;
193 unsigned int is_binary:1;
194 unsigned int is_copy:1;
195 unsigned int is_rename:1;
196 unsigned int recount:1;
197 struct fragment *fragments;
198 char *result;
199 size_t resultsize;
200 char old_sha1_prefix[41];
201 char new_sha1_prefix[41];
202 struct patch *next;
205 static void free_fragment_list(struct fragment *list)
207 while (list) {
208 struct fragment *next = list->next;
209 if (list->free_patch)
210 free((char *)list->patch);
211 free(list);
212 list = next;
216 static void free_patch(struct patch *patch)
218 free_fragment_list(patch->fragments);
219 free(patch->def_name);
220 free(patch->old_name);
221 free(patch->new_name);
222 free(patch->result);
223 free(patch);
226 static void free_patch_list(struct patch *list)
228 while (list) {
229 struct patch *next = list->next;
230 free_patch(list);
231 list = next;
236 * A line in a file, len-bytes long (includes the terminating LF,
237 * except for an incomplete line at the end if the file ends with
238 * one), and its contents hashes to 'hash'.
240 struct line {
241 size_t len;
242 unsigned hash : 24;
243 unsigned flag : 8;
244 #define LINE_COMMON 1
245 #define LINE_PATCHED 2
249 * This represents a "file", which is an array of "lines".
251 struct image {
252 char *buf;
253 size_t len;
254 size_t nr;
255 size_t alloc;
256 struct line *line_allocated;
257 struct line *line;
261 * Records filenames that have been touched, in order to handle
262 * the case where more than one patches touch the same file.
265 static struct string_list fn_table;
267 static uint32_t hash_line(const char *cp, size_t len)
269 size_t i;
270 uint32_t h;
271 for (i = 0, h = 0; i < len; i++) {
272 if (!isspace(cp[i])) {
273 h = h * 3 + (cp[i] & 0xff);
276 return h;
280 * Compare lines s1 of length n1 and s2 of length n2, ignoring
281 * whitespace difference. Returns 1 if they match, 0 otherwise
283 static int fuzzy_matchlines(const char *s1, size_t n1,
284 const char *s2, size_t n2)
286 const char *last1 = s1 + n1 - 1;
287 const char *last2 = s2 + n2 - 1;
288 int result = 0;
290 /* ignore line endings */
291 while ((*last1 == '\r') || (*last1 == '\n'))
292 last1--;
293 while ((*last2 == '\r') || (*last2 == '\n'))
294 last2--;
296 /* skip leading whitespace */
297 while (isspace(*s1) && (s1 <= last1))
298 s1++;
299 while (isspace(*s2) && (s2 <= last2))
300 s2++;
301 /* early return if both lines are empty */
302 if ((s1 > last1) && (s2 > last2))
303 return 1;
304 while (!result) {
305 result = *s1++ - *s2++;
307 * Skip whitespace inside. We check for whitespace on
308 * both buffers because we don't want "a b" to match
309 * "ab"
311 if (isspace(*s1) && isspace(*s2)) {
312 while (isspace(*s1) && s1 <= last1)
313 s1++;
314 while (isspace(*s2) && s2 <= last2)
315 s2++;
318 * If we reached the end on one side only,
319 * lines don't match
321 if (
322 ((s2 > last2) && (s1 <= last1)) ||
323 ((s1 > last1) && (s2 <= last2)))
324 return 0;
325 if ((s1 > last1) && (s2 > last2))
326 break;
329 return !result;
332 static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
334 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
335 img->line_allocated[img->nr].len = len;
336 img->line_allocated[img->nr].hash = hash_line(bol, len);
337 img->line_allocated[img->nr].flag = flag;
338 img->nr++;
342 * "buf" has the file contents to be patched (read from various sources).
343 * attach it to "image" and add line-based index to it.
344 * "image" now owns the "buf".
346 static void prepare_image(struct image *image, char *buf, size_t len,
347 int prepare_linetable)
349 const char *cp, *ep;
351 memset(image, 0, sizeof(*image));
352 image->buf = buf;
353 image->len = len;
355 if (!prepare_linetable)
356 return;
358 ep = image->buf + image->len;
359 cp = image->buf;
360 while (cp < ep) {
361 const char *next;
362 for (next = cp; next < ep && *next != '\n'; next++)
364 if (next < ep)
365 next++;
366 add_line_info(image, cp, next - cp, 0);
367 cp = next;
369 image->line = image->line_allocated;
372 static void clear_image(struct image *image)
374 free(image->buf);
375 free(image->line_allocated);
376 memset(image, 0, sizeof(*image));
379 /* fmt must contain _one_ %s and no other substitution */
380 static void say_patch_name(FILE *output, const char *fmt, struct patch *patch)
382 struct strbuf sb = STRBUF_INIT;
384 if (patch->old_name && patch->new_name &&
385 strcmp(patch->old_name, patch->new_name)) {
386 quote_c_style(patch->old_name, &sb, NULL, 0);
387 strbuf_addstr(&sb, " => ");
388 quote_c_style(patch->new_name, &sb, NULL, 0);
389 } else {
390 const char *n = patch->new_name;
391 if (!n)
392 n = patch->old_name;
393 quote_c_style(n, &sb, NULL, 0);
395 fprintf(output, fmt, sb.buf);
396 fputc('\n', output);
397 strbuf_release(&sb);
400 #define SLOP (16)
402 static void read_patch_file(struct strbuf *sb, int fd)
404 if (strbuf_read(sb, fd, 0) < 0)
405 die_errno("git apply: failed to read");
408 * Make sure that we have some slop in the buffer
409 * so that we can do speculative "memcmp" etc, and
410 * see to it that it is NUL-filled.
412 strbuf_grow(sb, SLOP);
413 memset(sb->buf + sb->len, 0, SLOP);
416 static unsigned long linelen(const char *buffer, unsigned long size)
418 unsigned long len = 0;
419 while (size--) {
420 len++;
421 if (*buffer++ == '\n')
422 break;
424 return len;
427 static int is_dev_null(const char *str)
429 return !memcmp("/dev/null", str, 9) && isspace(str[9]);
432 #define TERM_SPACE 1
433 #define TERM_TAB 2
435 static int name_terminate(const char *name, int namelen, int c, int terminate)
437 if (c == ' ' && !(terminate & TERM_SPACE))
438 return 0;
439 if (c == '\t' && !(terminate & TERM_TAB))
440 return 0;
442 return 1;
445 /* remove double slashes to make --index work with such filenames */
446 static char *squash_slash(char *name)
448 int i = 0, j = 0;
450 if (!name)
451 return NULL;
453 while (name[i]) {
454 if ((name[j++] = name[i++]) == '/')
455 while (name[i] == '/')
456 i++;
458 name[j] = '\0';
459 return name;
462 static char *find_name_gnu(const char *line, const char *def, int p_value)
464 struct strbuf name = STRBUF_INIT;
465 char *cp;
468 * Proposed "new-style" GNU patch/diff format; see
469 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
471 if (unquote_c_style(&name, line, NULL)) {
472 strbuf_release(&name);
473 return NULL;
476 for (cp = name.buf; p_value; p_value--) {
477 cp = strchr(cp, '/');
478 if (!cp) {
479 strbuf_release(&name);
480 return NULL;
482 cp++;
485 strbuf_remove(&name, 0, cp - name.buf);
486 if (root)
487 strbuf_insert(&name, 0, root, root_len);
488 return squash_slash(strbuf_detach(&name, NULL));
491 static size_t sane_tz_len(const char *line, size_t len)
493 const char *tz, *p;
495 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
496 return 0;
497 tz = line + len - strlen(" +0500");
499 if (tz[1] != '+' && tz[1] != '-')
500 return 0;
502 for (p = tz + 2; p != line + len; p++)
503 if (!isdigit(*p))
504 return 0;
506 return line + len - tz;
509 static size_t tz_with_colon_len(const char *line, size_t len)
511 const char *tz, *p;
513 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
514 return 0;
515 tz = line + len - strlen(" +08:00");
517 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
518 return 0;
519 p = tz + 2;
520 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
521 !isdigit(*p++) || !isdigit(*p++))
522 return 0;
524 return line + len - tz;
527 static size_t date_len(const char *line, size_t len)
529 const char *date, *p;
531 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
532 return 0;
533 p = date = line + len - strlen("72-02-05");
535 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
536 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
537 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */
538 return 0;
540 if (date - line >= strlen("19") &&
541 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */
542 date -= strlen("19");
544 return line + len - date;
547 static size_t short_time_len(const char *line, size_t len)
549 const char *time, *p;
551 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
552 return 0;
553 p = time = line + len - strlen(" 07:01:32");
555 /* Permit 1-digit hours? */
556 if (*p++ != ' ' ||
557 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
558 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
559 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */
560 return 0;
562 return line + len - time;
565 static size_t fractional_time_len(const char *line, size_t len)
567 const char *p;
568 size_t n;
570 /* Expected format: 19:41:17.620000023 */
571 if (!len || !isdigit(line[len - 1]))
572 return 0;
573 p = line + len - 1;
575 /* Fractional seconds. */
576 while (p > line && isdigit(*p))
577 p--;
578 if (*p != '.')
579 return 0;
581 /* Hours, minutes, and whole seconds. */
582 n = short_time_len(line, p - line);
583 if (!n)
584 return 0;
586 return line + len - p + n;
589 static size_t trailing_spaces_len(const char *line, size_t len)
591 const char *p;
593 /* Expected format: ' ' x (1 or more) */
594 if (!len || line[len - 1] != ' ')
595 return 0;
597 p = line + len;
598 while (p != line) {
599 p--;
600 if (*p != ' ')
601 return line + len - (p + 1);
604 /* All spaces! */
605 return len;
608 static size_t diff_timestamp_len(const char *line, size_t len)
610 const char *end = line + len;
611 size_t n;
614 * Posix: 2010-07-05 19:41:17
615 * GNU: 2010-07-05 19:41:17.620000023 -0500
618 if (!isdigit(end[-1]))
619 return 0;
621 n = sane_tz_len(line, end - line);
622 if (!n)
623 n = tz_with_colon_len(line, end - line);
624 end -= n;
626 n = short_time_len(line, end - line);
627 if (!n)
628 n = fractional_time_len(line, end - line);
629 end -= n;
631 n = date_len(line, end - line);
632 if (!n) /* No date. Too bad. */
633 return 0;
634 end -= n;
636 if (end == line) /* No space before date. */
637 return 0;
638 if (end[-1] == '\t') { /* Success! */
639 end--;
640 return line + len - end;
642 if (end[-1] != ' ') /* No space before date. */
643 return 0;
645 /* Whitespace damage. */
646 end -= trailing_spaces_len(line, end - line);
647 return line + len - end;
650 static char *null_strdup(const char *s)
652 return s ? xstrdup(s) : NULL;
655 static char *find_name_common(const char *line, const char *def,
656 int p_value, const char *end, int terminate)
658 int len;
659 const char *start = NULL;
661 if (p_value == 0)
662 start = line;
663 while (line != end) {
664 char c = *line;
666 if (!end && isspace(c)) {
667 if (c == '\n')
668 break;
669 if (name_terminate(start, line-start, c, terminate))
670 break;
672 line++;
673 if (c == '/' && !--p_value)
674 start = line;
676 if (!start)
677 return squash_slash(null_strdup(def));
678 len = line - start;
679 if (!len)
680 return squash_slash(null_strdup(def));
683 * Generally we prefer the shorter name, especially
684 * if the other one is just a variation of that with
685 * something else tacked on to the end (ie "file.orig"
686 * or "file~").
688 if (def) {
689 int deflen = strlen(def);
690 if (deflen < len && !strncmp(start, def, deflen))
691 return squash_slash(xstrdup(def));
694 if (root) {
695 char *ret = xmalloc(root_len + len + 1);
696 strcpy(ret, root);
697 memcpy(ret + root_len, start, len);
698 ret[root_len + len] = '\0';
699 return squash_slash(ret);
702 return squash_slash(xmemdupz(start, len));
705 static char *find_name(const char *line, char *def, int p_value, int terminate)
707 if (*line == '"') {
708 char *name = find_name_gnu(line, def, p_value);
709 if (name)
710 return name;
713 return find_name_common(line, def, p_value, NULL, terminate);
716 static char *find_name_traditional(const char *line, char *def, int p_value)
718 size_t len = strlen(line);
719 size_t date_len;
721 if (*line == '"') {
722 char *name = find_name_gnu(line, def, p_value);
723 if (name)
724 return name;
727 len = strchrnul(line, '\n') - line;
728 date_len = diff_timestamp_len(line, len);
729 if (!date_len)
730 return find_name_common(line, def, p_value, NULL, TERM_TAB);
731 len -= date_len;
733 return find_name_common(line, def, p_value, line + len, 0);
736 static int count_slashes(const char *cp)
738 int cnt = 0;
739 char ch;
741 while ((ch = *cp++))
742 if (ch == '/')
743 cnt++;
744 return cnt;
748 * Given the string after "--- " or "+++ ", guess the appropriate
749 * p_value for the given patch.
751 static int guess_p_value(const char *nameline)
753 char *name, *cp;
754 int val = -1;
756 if (is_dev_null(nameline))
757 return -1;
758 name = find_name_traditional(nameline, NULL, 0);
759 if (!name)
760 return -1;
761 cp = strchr(name, '/');
762 if (!cp)
763 val = 0;
764 else if (prefix) {
766 * Does it begin with "a/$our-prefix" and such? Then this is
767 * very likely to apply to our directory.
769 if (!strncmp(name, prefix, prefix_length))
770 val = count_slashes(prefix);
771 else {
772 cp++;
773 if (!strncmp(cp, prefix, prefix_length))
774 val = count_slashes(prefix) + 1;
777 free(name);
778 return val;
782 * Does the ---/+++ line has the POSIX timestamp after the last HT?
783 * GNU diff puts epoch there to signal a creation/deletion event. Is
784 * this such a timestamp?
786 static int has_epoch_timestamp(const char *nameline)
789 * We are only interested in epoch timestamp; any non-zero
790 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
791 * For the same reason, the date must be either 1969-12-31 or
792 * 1970-01-01, and the seconds part must be "00".
794 const char stamp_regexp[] =
795 "^(1969-12-31|1970-01-01)"
797 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
799 "([-+][0-2][0-9]:?[0-5][0-9])\n";
800 const char *timestamp = NULL, *cp, *colon;
801 static regex_t *stamp;
802 regmatch_t m[10];
803 int zoneoffset;
804 int hourminute;
805 int status;
807 for (cp = nameline; *cp != '\n'; cp++) {
808 if (*cp == '\t')
809 timestamp = cp + 1;
811 if (!timestamp)
812 return 0;
813 if (!stamp) {
814 stamp = xmalloc(sizeof(*stamp));
815 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
816 warning(_("Cannot prepare timestamp regexp %s"),
817 stamp_regexp);
818 return 0;
822 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
823 if (status) {
824 if (status != REG_NOMATCH)
825 warning(_("regexec returned %d for input: %s"),
826 status, timestamp);
827 return 0;
830 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
831 if (*colon == ':')
832 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
833 else
834 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
835 if (timestamp[m[3].rm_so] == '-')
836 zoneoffset = -zoneoffset;
839 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
840 * (west of GMT) or 1970-01-01 (east of GMT)
842 if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) ||
843 (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10)))
844 return 0;
846 hourminute = (strtol(timestamp + 11, NULL, 10) * 60 +
847 strtol(timestamp + 14, NULL, 10) -
848 zoneoffset);
850 return ((zoneoffset < 0 && hourminute == 1440) ||
851 (0 <= zoneoffset && !hourminute));
855 * Get the name etc info from the ---/+++ lines of a traditional patch header
857 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
858 * files, we can happily check the index for a match, but for creating a
859 * new file we should try to match whatever "patch" does. I have no idea.
861 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
863 char *name;
865 first += 4; /* skip "--- " */
866 second += 4; /* skip "+++ " */
867 if (!p_value_known) {
868 int p, q;
869 p = guess_p_value(first);
870 q = guess_p_value(second);
871 if (p < 0) p = q;
872 if (0 <= p && p == q) {
873 p_value = p;
874 p_value_known = 1;
877 if (is_dev_null(first)) {
878 patch->is_new = 1;
879 patch->is_delete = 0;
880 name = find_name_traditional(second, NULL, p_value);
881 patch->new_name = name;
882 } else if (is_dev_null(second)) {
883 patch->is_new = 0;
884 patch->is_delete = 1;
885 name = find_name_traditional(first, NULL, p_value);
886 patch->old_name = name;
887 } else {
888 char *first_name;
889 first_name = find_name_traditional(first, NULL, p_value);
890 name = find_name_traditional(second, first_name, p_value);
891 free(first_name);
892 if (has_epoch_timestamp(first)) {
893 patch->is_new = 1;
894 patch->is_delete = 0;
895 patch->new_name = name;
896 } else if (has_epoch_timestamp(second)) {
897 patch->is_new = 0;
898 patch->is_delete = 1;
899 patch->old_name = name;
900 } else {
901 patch->old_name = name;
902 patch->new_name = xstrdup(name);
905 if (!name)
906 die(_("unable to find filename in patch at line %d"), linenr);
909 static int gitdiff_hdrend(const char *line, struct patch *patch)
911 return -1;
915 * We're anal about diff header consistency, to make
916 * sure that we don't end up having strange ambiguous
917 * patches floating around.
919 * As a result, gitdiff_{old|new}name() will check
920 * their names against any previous information, just
921 * to make sure..
923 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
925 if (!orig_name && !isnull)
926 return find_name(line, NULL, p_value, TERM_TAB);
928 if (orig_name) {
929 int len;
930 const char *name;
931 char *another;
932 name = orig_name;
933 len = strlen(name);
934 if (isnull)
935 die(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"), name, linenr);
936 another = find_name(line, NULL, p_value, TERM_TAB);
937 if (!another || memcmp(another, name, len + 1))
938 die(_("git apply: bad git-diff - inconsistent %s filename on line %d"), oldnew, linenr);
939 free(another);
940 return orig_name;
942 else {
943 /* expect "/dev/null" */
944 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
945 die(_("git apply: bad git-diff - expected /dev/null on line %d"), linenr);
946 return NULL;
950 static int gitdiff_oldname(const char *line, struct patch *patch)
952 char *orig = patch->old_name;
953 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
954 if (orig != patch->old_name)
955 free(orig);
956 return 0;
959 static int gitdiff_newname(const char *line, struct patch *patch)
961 char *orig = patch->new_name;
962 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
963 if (orig != patch->new_name)
964 free(orig);
965 return 0;
968 static int gitdiff_oldmode(const char *line, struct patch *patch)
970 patch->old_mode = strtoul(line, NULL, 8);
971 return 0;
974 static int gitdiff_newmode(const char *line, struct patch *patch)
976 patch->new_mode = strtoul(line, NULL, 8);
977 return 0;
980 static int gitdiff_delete(const char *line, struct patch *patch)
982 patch->is_delete = 1;
983 free(patch->old_name);
984 patch->old_name = null_strdup(patch->def_name);
985 return gitdiff_oldmode(line, patch);
988 static int gitdiff_newfile(const char *line, struct patch *patch)
990 patch->is_new = 1;
991 free(patch->new_name);
992 patch->new_name = null_strdup(patch->def_name);
993 return gitdiff_newmode(line, patch);
996 static int gitdiff_copysrc(const char *line, struct patch *patch)
998 patch->is_copy = 1;
999 free(patch->old_name);
1000 patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1001 return 0;
1004 static int gitdiff_copydst(const char *line, struct patch *patch)
1006 patch->is_copy = 1;
1007 free(patch->new_name);
1008 patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1009 return 0;
1012 static int gitdiff_renamesrc(const char *line, struct patch *patch)
1014 patch->is_rename = 1;
1015 free(patch->old_name);
1016 patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1017 return 0;
1020 static int gitdiff_renamedst(const char *line, struct patch *patch)
1022 patch->is_rename = 1;
1023 free(patch->new_name);
1024 patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1025 return 0;
1028 static int gitdiff_similarity(const char *line, struct patch *patch)
1030 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
1031 patch->score = 0;
1032 return 0;
1035 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
1037 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
1038 patch->score = 0;
1039 return 0;
1042 static int gitdiff_index(const char *line, struct patch *patch)
1045 * index line is N hexadecimal, "..", N hexadecimal,
1046 * and optional space with octal mode.
1048 const char *ptr, *eol;
1049 int len;
1051 ptr = strchr(line, '.');
1052 if (!ptr || ptr[1] != '.' || 40 < ptr - line)
1053 return 0;
1054 len = ptr - line;
1055 memcpy(patch->old_sha1_prefix, line, len);
1056 patch->old_sha1_prefix[len] = 0;
1058 line = ptr + 2;
1059 ptr = strchr(line, ' ');
1060 eol = strchr(line, '\n');
1062 if (!ptr || eol < ptr)
1063 ptr = eol;
1064 len = ptr - line;
1066 if (40 < len)
1067 return 0;
1068 memcpy(patch->new_sha1_prefix, line, len);
1069 patch->new_sha1_prefix[len] = 0;
1070 if (*ptr == ' ')
1071 patch->old_mode = strtoul(ptr+1, NULL, 8);
1072 return 0;
1076 * This is normal for a diff that doesn't change anything: we'll fall through
1077 * into the next diff. Tell the parser to break out.
1079 static int gitdiff_unrecognized(const char *line, struct patch *patch)
1081 return -1;
1084 static const char *stop_at_slash(const char *line, int llen)
1086 int nslash = p_value;
1087 int i;
1089 for (i = 0; i < llen; i++) {
1090 int ch = line[i];
1091 if (ch == '/' && --nslash <= 0)
1092 return &line[i];
1094 return NULL;
1098 * This is to extract the same name that appears on "diff --git"
1099 * line. We do not find and return anything if it is a rename
1100 * patch, and it is OK because we will find the name elsewhere.
1101 * We need to reliably find name only when it is mode-change only,
1102 * creation or deletion of an empty file. In any of these cases,
1103 * both sides are the same name under a/ and b/ respectively.
1105 static char *git_header_name(const char *line, int llen)
1107 const char *name;
1108 const char *second = NULL;
1109 size_t len, line_len;
1111 line += strlen("diff --git ");
1112 llen -= strlen("diff --git ");
1114 if (*line == '"') {
1115 const char *cp;
1116 struct strbuf first = STRBUF_INIT;
1117 struct strbuf sp = STRBUF_INIT;
1119 if (unquote_c_style(&first, line, &second))
1120 goto free_and_fail1;
1122 /* advance to the first slash */
1123 cp = stop_at_slash(first.buf, first.len);
1124 /* we do not accept absolute paths */
1125 if (!cp || cp == first.buf)
1126 goto free_and_fail1;
1127 strbuf_remove(&first, 0, cp + 1 - first.buf);
1130 * second points at one past closing dq of name.
1131 * find the second name.
1133 while ((second < line + llen) && isspace(*second))
1134 second++;
1136 if (line + llen <= second)
1137 goto free_and_fail1;
1138 if (*second == '"') {
1139 if (unquote_c_style(&sp, second, NULL))
1140 goto free_and_fail1;
1141 cp = stop_at_slash(sp.buf, sp.len);
1142 if (!cp || cp == sp.buf)
1143 goto free_and_fail1;
1144 /* They must match, otherwise ignore */
1145 if (strcmp(cp + 1, first.buf))
1146 goto free_and_fail1;
1147 strbuf_release(&sp);
1148 return strbuf_detach(&first, NULL);
1151 /* unquoted second */
1152 cp = stop_at_slash(second, line + llen - second);
1153 if (!cp || cp == second)
1154 goto free_and_fail1;
1155 cp++;
1156 if (line + llen - cp != first.len + 1 ||
1157 memcmp(first.buf, cp, first.len))
1158 goto free_and_fail1;
1159 return strbuf_detach(&first, NULL);
1161 free_and_fail1:
1162 strbuf_release(&first);
1163 strbuf_release(&sp);
1164 return NULL;
1167 /* unquoted first name */
1168 name = stop_at_slash(line, llen);
1169 if (!name || name == line)
1170 return NULL;
1171 name++;
1174 * since the first name is unquoted, a dq if exists must be
1175 * the beginning of the second name.
1177 for (second = name; second < line + llen; second++) {
1178 if (*second == '"') {
1179 struct strbuf sp = STRBUF_INIT;
1180 const char *np;
1182 if (unquote_c_style(&sp, second, NULL))
1183 goto free_and_fail2;
1185 np = stop_at_slash(sp.buf, sp.len);
1186 if (!np || np == sp.buf)
1187 goto free_and_fail2;
1188 np++;
1190 len = sp.buf + sp.len - np;
1191 if (len < second - name &&
1192 !strncmp(np, name, len) &&
1193 isspace(name[len])) {
1194 /* Good */
1195 strbuf_remove(&sp, 0, np - sp.buf);
1196 return strbuf_detach(&sp, NULL);
1199 free_and_fail2:
1200 strbuf_release(&sp);
1201 return NULL;
1206 * Accept a name only if it shows up twice, exactly the same
1207 * form.
1209 second = strchr(name, '\n');
1210 if (!second)
1211 return NULL;
1212 line_len = second - name;
1213 for (len = 0 ; ; len++) {
1214 switch (name[len]) {
1215 default:
1216 continue;
1217 case '\n':
1218 return NULL;
1219 case '\t': case ' ':
1220 second = stop_at_slash(name + len, line_len - len);
1221 if (!second)
1222 return NULL;
1223 second++;
1224 if (second[len] == '\n' && !strncmp(name, second, len)) {
1225 return xmemdupz(name, len);
1231 /* Verify that we recognize the lines following a git header */
1232 static int parse_git_header(const char *line, int len, unsigned int size, struct patch *patch)
1234 unsigned long offset;
1236 /* A git diff has explicit new/delete information, so we don't guess */
1237 patch->is_new = 0;
1238 patch->is_delete = 0;
1241 * Some things may not have the old name in the
1242 * rest of the headers anywhere (pure mode changes,
1243 * or removing or adding empty files), so we get
1244 * the default name from the header.
1246 patch->def_name = git_header_name(line, len);
1247 if (patch->def_name && root) {
1248 char *s = xmalloc(root_len + strlen(patch->def_name) + 1);
1249 strcpy(s, root);
1250 strcpy(s + root_len, patch->def_name);
1251 free(patch->def_name);
1252 patch->def_name = s;
1255 line += len;
1256 size -= len;
1257 linenr++;
1258 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
1259 static const struct opentry {
1260 const char *str;
1261 int (*fn)(const char *, struct patch *);
1262 } optable[] = {
1263 { "@@ -", gitdiff_hdrend },
1264 { "--- ", gitdiff_oldname },
1265 { "+++ ", gitdiff_newname },
1266 { "old mode ", gitdiff_oldmode },
1267 { "new mode ", gitdiff_newmode },
1268 { "deleted file mode ", gitdiff_delete },
1269 { "new file mode ", gitdiff_newfile },
1270 { "copy from ", gitdiff_copysrc },
1271 { "copy to ", gitdiff_copydst },
1272 { "rename old ", gitdiff_renamesrc },
1273 { "rename new ", gitdiff_renamedst },
1274 { "rename from ", gitdiff_renamesrc },
1275 { "rename to ", gitdiff_renamedst },
1276 { "similarity index ", gitdiff_similarity },
1277 { "dissimilarity index ", gitdiff_dissimilarity },
1278 { "index ", gitdiff_index },
1279 { "", gitdiff_unrecognized },
1281 int i;
1283 len = linelen(line, size);
1284 if (!len || line[len-1] != '\n')
1285 break;
1286 for (i = 0; i < ARRAY_SIZE(optable); i++) {
1287 const struct opentry *p = optable + i;
1288 int oplen = strlen(p->str);
1289 if (len < oplen || memcmp(p->str, line, oplen))
1290 continue;
1291 if (p->fn(line + oplen, patch) < 0)
1292 return offset;
1293 break;
1297 return offset;
1300 static int parse_num(const char *line, unsigned long *p)
1302 char *ptr;
1304 if (!isdigit(*line))
1305 return 0;
1306 *p = strtoul(line, &ptr, 10);
1307 return ptr - line;
1310 static int parse_range(const char *line, int len, int offset, const char *expect,
1311 unsigned long *p1, unsigned long *p2)
1313 int digits, ex;
1315 if (offset < 0 || offset >= len)
1316 return -1;
1317 line += offset;
1318 len -= offset;
1320 digits = parse_num(line, p1);
1321 if (!digits)
1322 return -1;
1324 offset += digits;
1325 line += digits;
1326 len -= digits;
1328 *p2 = 1;
1329 if (*line == ',') {
1330 digits = parse_num(line+1, p2);
1331 if (!digits)
1332 return -1;
1334 offset += digits+1;
1335 line += digits+1;
1336 len -= digits+1;
1339 ex = strlen(expect);
1340 if (ex > len)
1341 return -1;
1342 if (memcmp(line, expect, ex))
1343 return -1;
1345 return offset + ex;
1348 static void recount_diff(const char *line, int size, struct fragment *fragment)
1350 int oldlines = 0, newlines = 0, ret = 0;
1352 if (size < 1) {
1353 warning("recount: ignore empty hunk");
1354 return;
1357 for (;;) {
1358 int len = linelen(line, size);
1359 size -= len;
1360 line += len;
1362 if (size < 1)
1363 break;
1365 switch (*line) {
1366 case ' ': case '\n':
1367 newlines++;
1368 /* fall through */
1369 case '-':
1370 oldlines++;
1371 continue;
1372 case '+':
1373 newlines++;
1374 continue;
1375 case '\\':
1376 continue;
1377 case '@':
1378 ret = size < 3 || prefixcmp(line, "@@ ");
1379 break;
1380 case 'd':
1381 ret = size < 5 || prefixcmp(line, "diff ");
1382 break;
1383 default:
1384 ret = -1;
1385 break;
1387 if (ret) {
1388 warning(_("recount: unexpected line: %.*s"),
1389 (int)linelen(line, size), line);
1390 return;
1392 break;
1394 fragment->oldlines = oldlines;
1395 fragment->newlines = newlines;
1399 * Parse a unified diff fragment header of the
1400 * form "@@ -a,b +c,d @@"
1402 static int parse_fragment_header(const char *line, int len, struct fragment *fragment)
1404 int offset;
1406 if (!len || line[len-1] != '\n')
1407 return -1;
1409 /* Figure out the number of lines in a fragment */
1410 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1411 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1413 return offset;
1416 static int find_header(const char *line, unsigned long size, int *hdrsize, struct patch *patch)
1418 unsigned long offset, len;
1420 patch->is_toplevel_relative = 0;
1421 patch->is_rename = patch->is_copy = 0;
1422 patch->is_new = patch->is_delete = -1;
1423 patch->old_mode = patch->new_mode = 0;
1424 patch->old_name = patch->new_name = NULL;
1425 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
1426 unsigned long nextlen;
1428 len = linelen(line, size);
1429 if (!len)
1430 break;
1432 /* Testing this early allows us to take a few shortcuts.. */
1433 if (len < 6)
1434 continue;
1437 * Make sure we don't find any unconnected patch fragments.
1438 * That's a sign that we didn't find a header, and that a
1439 * patch has become corrupted/broken up.
1441 if (!memcmp("@@ -", line, 4)) {
1442 struct fragment dummy;
1443 if (parse_fragment_header(line, len, &dummy) < 0)
1444 continue;
1445 die(_("patch fragment without header at line %d: %.*s"),
1446 linenr, (int)len-1, line);
1449 if (size < len + 6)
1450 break;
1453 * Git patch? It might not have a real patch, just a rename
1454 * or mode change, so we handle that specially
1456 if (!memcmp("diff --git ", line, 11)) {
1457 int git_hdr_len = parse_git_header(line, len, size, patch);
1458 if (git_hdr_len <= len)
1459 continue;
1460 if (!patch->old_name && !patch->new_name) {
1461 if (!patch->def_name)
1462 die(Q_("git diff header lacks filename information when removing "
1463 "%d leading pathname component (line %d)",
1464 "git diff header lacks filename information when removing "
1465 "%d leading pathname components (line %d)",
1466 p_value),
1467 p_value, linenr);
1468 patch->old_name = xstrdup(patch->def_name);
1469 patch->new_name = xstrdup(patch->def_name);
1471 if (!patch->is_delete && !patch->new_name)
1472 die("git diff header lacks filename information "
1473 "(line %d)", linenr);
1474 patch->is_toplevel_relative = 1;
1475 *hdrsize = git_hdr_len;
1476 return offset;
1479 /* --- followed by +++ ? */
1480 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1481 continue;
1484 * We only accept unified patches, so we want it to
1485 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1486 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1488 nextlen = linelen(line + len, size - len);
1489 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1490 continue;
1492 /* Ok, we'll consider it a patch */
1493 parse_traditional_patch(line, line+len, patch);
1494 *hdrsize = len + nextlen;
1495 linenr += 2;
1496 return offset;
1498 return -1;
1501 static void record_ws_error(unsigned result, const char *line, int len, int linenr)
1503 char *err;
1505 if (!result)
1506 return;
1508 whitespace_error++;
1509 if (squelch_whitespace_errors &&
1510 squelch_whitespace_errors < whitespace_error)
1511 return;
1513 err = whitespace_error_string(result);
1514 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1515 patch_input_file, linenr, err, len, line);
1516 free(err);
1519 static void check_whitespace(const char *line, int len, unsigned ws_rule)
1521 unsigned result = ws_check(line + 1, len - 1, ws_rule);
1523 record_ws_error(result, line + 1, len - 2, linenr);
1527 * Parse a unified diff. Note that this really needs to parse each
1528 * fragment separately, since the only way to know the difference
1529 * between a "---" that is part of a patch, and a "---" that starts
1530 * the next patch is to look at the line counts..
1532 static int parse_fragment(const char *line, unsigned long size,
1533 struct patch *patch, struct fragment *fragment)
1535 int added, deleted;
1536 int len = linelen(line, size), offset;
1537 unsigned long oldlines, newlines;
1538 unsigned long leading, trailing;
1540 offset = parse_fragment_header(line, len, fragment);
1541 if (offset < 0)
1542 return -1;
1543 if (offset > 0 && patch->recount)
1544 recount_diff(line + offset, size - offset, fragment);
1545 oldlines = fragment->oldlines;
1546 newlines = fragment->newlines;
1547 leading = 0;
1548 trailing = 0;
1550 /* Parse the thing.. */
1551 line += len;
1552 size -= len;
1553 linenr++;
1554 added = deleted = 0;
1555 for (offset = len;
1556 0 < size;
1557 offset += len, size -= len, line += len, linenr++) {
1558 if (!oldlines && !newlines)
1559 break;
1560 len = linelen(line, size);
1561 if (!len || line[len-1] != '\n')
1562 return -1;
1563 switch (*line) {
1564 default:
1565 return -1;
1566 case '\n': /* newer GNU diff, an empty context line */
1567 case ' ':
1568 oldlines--;
1569 newlines--;
1570 if (!deleted && !added)
1571 leading++;
1572 trailing++;
1573 break;
1574 case '-':
1575 if (apply_in_reverse &&
1576 ws_error_action != nowarn_ws_error)
1577 check_whitespace(line, len, patch->ws_rule);
1578 deleted++;
1579 oldlines--;
1580 trailing = 0;
1581 break;
1582 case '+':
1583 if (!apply_in_reverse &&
1584 ws_error_action != nowarn_ws_error)
1585 check_whitespace(line, len, patch->ws_rule);
1586 added++;
1587 newlines--;
1588 trailing = 0;
1589 break;
1592 * We allow "\ No newline at end of file". Depending
1593 * on locale settings when the patch was produced we
1594 * don't know what this line looks like. The only
1595 * thing we do know is that it begins with "\ ".
1596 * Checking for 12 is just for sanity check -- any
1597 * l10n of "\ No newline..." is at least that long.
1599 case '\\':
1600 if (len < 12 || memcmp(line, "\\ ", 2))
1601 return -1;
1602 break;
1605 if (oldlines || newlines)
1606 return -1;
1607 fragment->leading = leading;
1608 fragment->trailing = trailing;
1611 * If a fragment ends with an incomplete line, we failed to include
1612 * it in the above loop because we hit oldlines == newlines == 0
1613 * before seeing it.
1615 if (12 < size && !memcmp(line, "\\ ", 2))
1616 offset += linelen(line, size);
1618 patch->lines_added += added;
1619 patch->lines_deleted += deleted;
1621 if (0 < patch->is_new && oldlines)
1622 return error(_("new file depends on old contents"));
1623 if (0 < patch->is_delete && newlines)
1624 return error(_("deleted file still has contents"));
1625 return offset;
1629 * We have seen "diff --git a/... b/..." header (or a traditional patch
1630 * header). Read hunks that belong to this patch into fragments and hang
1631 * them to the given patch structure.
1633 * The (fragment->patch, fragment->size) pair points into the memory given
1634 * by the caller, not a copy, when we return.
1636 static int parse_single_patch(const char *line, unsigned long size, struct patch *patch)
1638 unsigned long offset = 0;
1639 unsigned long oldlines = 0, newlines = 0, context = 0;
1640 struct fragment **fragp = &patch->fragments;
1642 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1643 struct fragment *fragment;
1644 int len;
1646 fragment = xcalloc(1, sizeof(*fragment));
1647 fragment->linenr = linenr;
1648 len = parse_fragment(line, size, patch, fragment);
1649 if (len <= 0)
1650 die(_("corrupt patch at line %d"), linenr);
1651 fragment->patch = line;
1652 fragment->size = len;
1653 oldlines += fragment->oldlines;
1654 newlines += fragment->newlines;
1655 context += fragment->leading + fragment->trailing;
1657 *fragp = fragment;
1658 fragp = &fragment->next;
1660 offset += len;
1661 line += len;
1662 size -= len;
1666 * If something was removed (i.e. we have old-lines) it cannot
1667 * be creation, and if something was added it cannot be
1668 * deletion. However, the reverse is not true; --unified=0
1669 * patches that only add are not necessarily creation even
1670 * though they do not have any old lines, and ones that only
1671 * delete are not necessarily deletion.
1673 * Unfortunately, a real creation/deletion patch do _not_ have
1674 * any context line by definition, so we cannot safely tell it
1675 * apart with --unified=0 insanity. At least if the patch has
1676 * more than one hunk it is not creation or deletion.
1678 if (patch->is_new < 0 &&
1679 (oldlines || (patch->fragments && patch->fragments->next)))
1680 patch->is_new = 0;
1681 if (patch->is_delete < 0 &&
1682 (newlines || (patch->fragments && patch->fragments->next)))
1683 patch->is_delete = 0;
1685 if (0 < patch->is_new && oldlines)
1686 die(_("new file %s depends on old contents"), patch->new_name);
1687 if (0 < patch->is_delete && newlines)
1688 die(_("deleted file %s still has contents"), patch->old_name);
1689 if (!patch->is_delete && !newlines && context)
1690 fprintf_ln(stderr,
1691 _("** warning: "
1692 "file %s becomes empty but is not deleted"),
1693 patch->new_name);
1695 return offset;
1698 static inline int metadata_changes(struct patch *patch)
1700 return patch->is_rename > 0 ||
1701 patch->is_copy > 0 ||
1702 patch->is_new > 0 ||
1703 patch->is_delete ||
1704 (patch->old_mode && patch->new_mode &&
1705 patch->old_mode != patch->new_mode);
1708 static char *inflate_it(const void *data, unsigned long size,
1709 unsigned long inflated_size)
1711 git_zstream stream;
1712 void *out;
1713 int st;
1715 memset(&stream, 0, sizeof(stream));
1717 stream.next_in = (unsigned char *)data;
1718 stream.avail_in = size;
1719 stream.next_out = out = xmalloc(inflated_size);
1720 stream.avail_out = inflated_size;
1721 git_inflate_init(&stream);
1722 st = git_inflate(&stream, Z_FINISH);
1723 git_inflate_end(&stream);
1724 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1725 free(out);
1726 return NULL;
1728 return out;
1732 * Read a binary hunk and return a new fragment; fragment->patch
1733 * points at an allocated memory that the caller must free, so
1734 * it is marked as "->free_patch = 1".
1736 static struct fragment *parse_binary_hunk(char **buf_p,
1737 unsigned long *sz_p,
1738 int *status_p,
1739 int *used_p)
1742 * Expect a line that begins with binary patch method ("literal"
1743 * or "delta"), followed by the length of data before deflating.
1744 * a sequence of 'length-byte' followed by base-85 encoded data
1745 * should follow, terminated by a newline.
1747 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1748 * and we would limit the patch line to 66 characters,
1749 * so one line can fit up to 13 groups that would decode
1750 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1751 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1753 int llen, used;
1754 unsigned long size = *sz_p;
1755 char *buffer = *buf_p;
1756 int patch_method;
1757 unsigned long origlen;
1758 char *data = NULL;
1759 int hunk_size = 0;
1760 struct fragment *frag;
1762 llen = linelen(buffer, size);
1763 used = llen;
1765 *status_p = 0;
1767 if (!prefixcmp(buffer, "delta ")) {
1768 patch_method = BINARY_DELTA_DEFLATED;
1769 origlen = strtoul(buffer + 6, NULL, 10);
1771 else if (!prefixcmp(buffer, "literal ")) {
1772 patch_method = BINARY_LITERAL_DEFLATED;
1773 origlen = strtoul(buffer + 8, NULL, 10);
1775 else
1776 return NULL;
1778 linenr++;
1779 buffer += llen;
1780 while (1) {
1781 int byte_length, max_byte_length, newsize;
1782 llen = linelen(buffer, size);
1783 used += llen;
1784 linenr++;
1785 if (llen == 1) {
1786 /* consume the blank line */
1787 buffer++;
1788 size--;
1789 break;
1792 * Minimum line is "A00000\n" which is 7-byte long,
1793 * and the line length must be multiple of 5 plus 2.
1795 if ((llen < 7) || (llen-2) % 5)
1796 goto corrupt;
1797 max_byte_length = (llen - 2) / 5 * 4;
1798 byte_length = *buffer;
1799 if ('A' <= byte_length && byte_length <= 'Z')
1800 byte_length = byte_length - 'A' + 1;
1801 else if ('a' <= byte_length && byte_length <= 'z')
1802 byte_length = byte_length - 'a' + 27;
1803 else
1804 goto corrupt;
1805 /* if the input length was not multiple of 4, we would
1806 * have filler at the end but the filler should never
1807 * exceed 3 bytes
1809 if (max_byte_length < byte_length ||
1810 byte_length <= max_byte_length - 4)
1811 goto corrupt;
1812 newsize = hunk_size + byte_length;
1813 data = xrealloc(data, newsize);
1814 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1815 goto corrupt;
1816 hunk_size = newsize;
1817 buffer += llen;
1818 size -= llen;
1821 frag = xcalloc(1, sizeof(*frag));
1822 frag->patch = inflate_it(data, hunk_size, origlen);
1823 frag->free_patch = 1;
1824 if (!frag->patch)
1825 goto corrupt;
1826 free(data);
1827 frag->size = origlen;
1828 *buf_p = buffer;
1829 *sz_p = size;
1830 *used_p = used;
1831 frag->binary_patch_method = patch_method;
1832 return frag;
1834 corrupt:
1835 free(data);
1836 *status_p = -1;
1837 error(_("corrupt binary patch at line %d: %.*s"),
1838 linenr-1, llen-1, buffer);
1839 return NULL;
1842 static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1845 * We have read "GIT binary patch\n"; what follows is a line
1846 * that says the patch method (currently, either "literal" or
1847 * "delta") and the length of data before deflating; a
1848 * sequence of 'length-byte' followed by base-85 encoded data
1849 * follows.
1851 * When a binary patch is reversible, there is another binary
1852 * hunk in the same format, starting with patch method (either
1853 * "literal" or "delta") with the length of data, and a sequence
1854 * of length-byte + base-85 encoded data, terminated with another
1855 * empty line. This data, when applied to the postimage, produces
1856 * the preimage.
1858 struct fragment *forward;
1859 struct fragment *reverse;
1860 int status;
1861 int used, used_1;
1863 forward = parse_binary_hunk(&buffer, &size, &status, &used);
1864 if (!forward && !status)
1865 /* there has to be one hunk (forward hunk) */
1866 return error(_("unrecognized binary patch at line %d"), linenr-1);
1867 if (status)
1868 /* otherwise we already gave an error message */
1869 return status;
1871 reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1872 if (reverse)
1873 used += used_1;
1874 else if (status) {
1876 * Not having reverse hunk is not an error, but having
1877 * a corrupt reverse hunk is.
1879 free((void*) forward->patch);
1880 free(forward);
1881 return status;
1883 forward->next = reverse;
1884 patch->fragments = forward;
1885 patch->is_binary = 1;
1886 return used;
1890 * Read the patch text in "buffer" taht extends for "size" bytes; stop
1891 * reading after seeing a single patch (i.e. changes to a single file).
1892 * Create fragments (i.e. patch hunks) and hang them to the given patch.
1893 * Return the number of bytes consumed, so that the caller can call us
1894 * again for the next patch.
1896 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
1898 int hdrsize, patchsize;
1899 int offset = find_header(buffer, size, &hdrsize, patch);
1901 if (offset < 0)
1902 return offset;
1904 patch->ws_rule = whitespace_rule(patch->new_name
1905 ? patch->new_name
1906 : patch->old_name);
1908 patchsize = parse_single_patch(buffer + offset + hdrsize,
1909 size - offset - hdrsize, patch);
1911 if (!patchsize) {
1912 static const char *binhdr[] = {
1913 "Binary files ",
1914 "Files ",
1915 NULL,
1917 static const char git_binary[] = "GIT binary patch\n";
1918 int i;
1919 int hd = hdrsize + offset;
1920 unsigned long llen = linelen(buffer + hd, size - hd);
1922 if (llen == sizeof(git_binary) - 1 &&
1923 !memcmp(git_binary, buffer + hd, llen)) {
1924 int used;
1925 linenr++;
1926 used = parse_binary(buffer + hd + llen,
1927 size - hd - llen, patch);
1928 if (used)
1929 patchsize = used + llen;
1930 else
1931 patchsize = 0;
1933 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
1934 for (i = 0; binhdr[i]; i++) {
1935 int len = strlen(binhdr[i]);
1936 if (len < size - hd &&
1937 !memcmp(binhdr[i], buffer + hd, len)) {
1938 linenr++;
1939 patch->is_binary = 1;
1940 patchsize = llen;
1941 break;
1946 /* Empty patch cannot be applied if it is a text patch
1947 * without metadata change. A binary patch appears
1948 * empty to us here.
1950 if ((apply || check) &&
1951 (!patch->is_binary && !metadata_changes(patch)))
1952 die(_("patch with only garbage at line %d"), linenr);
1955 return offset + hdrsize + patchsize;
1958 #define swap(a,b) myswap((a),(b),sizeof(a))
1960 #define myswap(a, b, size) do { \
1961 unsigned char mytmp[size]; \
1962 memcpy(mytmp, &a, size); \
1963 memcpy(&a, &b, size); \
1964 memcpy(&b, mytmp, size); \
1965 } while (0)
1967 static void reverse_patches(struct patch *p)
1969 for (; p; p = p->next) {
1970 struct fragment *frag = p->fragments;
1972 swap(p->new_name, p->old_name);
1973 swap(p->new_mode, p->old_mode);
1974 swap(p->is_new, p->is_delete);
1975 swap(p->lines_added, p->lines_deleted);
1976 swap(p->old_sha1_prefix, p->new_sha1_prefix);
1978 for (; frag; frag = frag->next) {
1979 swap(frag->newpos, frag->oldpos);
1980 swap(frag->newlines, frag->oldlines);
1985 static const char pluses[] =
1986 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1987 static const char minuses[]=
1988 "----------------------------------------------------------------------";
1990 static void show_stats(struct patch *patch)
1992 struct strbuf qname = STRBUF_INIT;
1993 char *cp = patch->new_name ? patch->new_name : patch->old_name;
1994 int max, add, del;
1996 quote_c_style(cp, &qname, NULL, 0);
1999 * "scale" the filename
2001 max = max_len;
2002 if (max > 50)
2003 max = 50;
2005 if (qname.len > max) {
2006 cp = strchr(qname.buf + qname.len + 3 - max, '/');
2007 if (!cp)
2008 cp = qname.buf + qname.len + 3 - max;
2009 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
2012 if (patch->is_binary) {
2013 printf(" %-*s | Bin\n", max, qname.buf);
2014 strbuf_release(&qname);
2015 return;
2018 printf(" %-*s |", max, qname.buf);
2019 strbuf_release(&qname);
2022 * scale the add/delete
2024 max = max + max_change > 70 ? 70 - max : max_change;
2025 add = patch->lines_added;
2026 del = patch->lines_deleted;
2028 if (max_change > 0) {
2029 int total = ((add + del) * max + max_change / 2) / max_change;
2030 add = (add * max + max_change / 2) / max_change;
2031 del = total - add;
2033 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
2034 add, pluses, del, minuses);
2037 static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
2039 switch (st->st_mode & S_IFMT) {
2040 case S_IFLNK:
2041 if (strbuf_readlink(buf, path, st->st_size) < 0)
2042 return error(_("unable to read symlink %s"), path);
2043 return 0;
2044 case S_IFREG:
2045 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
2046 return error(_("unable to open or read %s"), path);
2047 convert_to_git(path, buf->buf, buf->len, buf, 0);
2048 return 0;
2049 default:
2050 return -1;
2055 * Update the preimage, and the common lines in postimage,
2056 * from buffer buf of length len. If postlen is 0 the postimage
2057 * is updated in place, otherwise it's updated on a new buffer
2058 * of length postlen
2061 static void update_pre_post_images(struct image *preimage,
2062 struct image *postimage,
2063 char *buf,
2064 size_t len, size_t postlen)
2066 int i, ctx;
2067 char *new, *old, *fixed;
2068 struct image fixed_preimage;
2071 * Update the preimage with whitespace fixes. Note that we
2072 * are not losing preimage->buf -- apply_one_fragment() will
2073 * free "oldlines".
2075 prepare_image(&fixed_preimage, buf, len, 1);
2076 assert(fixed_preimage.nr == preimage->nr);
2077 for (i = 0; i < preimage->nr; i++)
2078 fixed_preimage.line[i].flag = preimage->line[i].flag;
2079 free(preimage->line_allocated);
2080 *preimage = fixed_preimage;
2083 * Adjust the common context lines in postimage. This can be
2084 * done in-place when we are just doing whitespace fixing,
2085 * which does not make the string grow, but needs a new buffer
2086 * when ignoring whitespace causes the update, since in this case
2087 * we could have e.g. tabs converted to multiple spaces.
2088 * We trust the caller to tell us if the update can be done
2089 * in place (postlen==0) or not.
2091 old = postimage->buf;
2092 if (postlen)
2093 new = postimage->buf = xmalloc(postlen);
2094 else
2095 new = old;
2096 fixed = preimage->buf;
2097 for (i = ctx = 0; i < postimage->nr; i++) {
2098 size_t len = postimage->line[i].len;
2099 if (!(postimage->line[i].flag & LINE_COMMON)) {
2100 /* an added line -- no counterparts in preimage */
2101 memmove(new, old, len);
2102 old += len;
2103 new += len;
2104 continue;
2107 /* a common context -- skip it in the original postimage */
2108 old += len;
2110 /* and find the corresponding one in the fixed preimage */
2111 while (ctx < preimage->nr &&
2112 !(preimage->line[ctx].flag & LINE_COMMON)) {
2113 fixed += preimage->line[ctx].len;
2114 ctx++;
2116 if (preimage->nr <= ctx)
2117 die(_("oops"));
2119 /* and copy it in, while fixing the line length */
2120 len = preimage->line[ctx].len;
2121 memcpy(new, fixed, len);
2122 new += len;
2123 fixed += len;
2124 postimage->line[i].len = len;
2125 ctx++;
2128 /* Fix the length of the whole thing */
2129 postimage->len = new - postimage->buf;
2132 static int match_fragment(struct image *img,
2133 struct image *preimage,
2134 struct image *postimage,
2135 unsigned long try,
2136 int try_lno,
2137 unsigned ws_rule,
2138 int match_beginning, int match_end)
2140 int i;
2141 char *fixed_buf, *buf, *orig, *target;
2142 struct strbuf fixed;
2143 size_t fixed_len;
2144 int preimage_limit;
2146 if (preimage->nr + try_lno <= img->nr) {
2148 * The hunk falls within the boundaries of img.
2150 preimage_limit = preimage->nr;
2151 if (match_end && (preimage->nr + try_lno != img->nr))
2152 return 0;
2153 } else if (ws_error_action == correct_ws_error &&
2154 (ws_rule & WS_BLANK_AT_EOF)) {
2156 * This hunk extends beyond the end of img, and we are
2157 * removing blank lines at the end of the file. This
2158 * many lines from the beginning of the preimage must
2159 * match with img, and the remainder of the preimage
2160 * must be blank.
2162 preimage_limit = img->nr - try_lno;
2163 } else {
2165 * The hunk extends beyond the end of the img and
2166 * we are not removing blanks at the end, so we
2167 * should reject the hunk at this position.
2169 return 0;
2172 if (match_beginning && try_lno)
2173 return 0;
2175 /* Quick hash check */
2176 for (i = 0; i < preimage_limit; i++)
2177 if ((img->line[try_lno + i].flag & LINE_PATCHED) ||
2178 (preimage->line[i].hash != img->line[try_lno + i].hash))
2179 return 0;
2181 if (preimage_limit == preimage->nr) {
2183 * Do we have an exact match? If we were told to match
2184 * at the end, size must be exactly at try+fragsize,
2185 * otherwise try+fragsize must be still within the preimage,
2186 * and either case, the old piece should match the preimage
2187 * exactly.
2189 if ((match_end
2190 ? (try + preimage->len == img->len)
2191 : (try + preimage->len <= img->len)) &&
2192 !memcmp(img->buf + try, preimage->buf, preimage->len))
2193 return 1;
2194 } else {
2196 * The preimage extends beyond the end of img, so
2197 * there cannot be an exact match.
2199 * There must be one non-blank context line that match
2200 * a line before the end of img.
2202 char *buf_end;
2204 buf = preimage->buf;
2205 buf_end = buf;
2206 for (i = 0; i < preimage_limit; i++)
2207 buf_end += preimage->line[i].len;
2209 for ( ; buf < buf_end; buf++)
2210 if (!isspace(*buf))
2211 break;
2212 if (buf == buf_end)
2213 return 0;
2217 * No exact match. If we are ignoring whitespace, run a line-by-line
2218 * fuzzy matching. We collect all the line length information because
2219 * we need it to adjust whitespace if we match.
2221 if (ws_ignore_action == ignore_ws_change) {
2222 size_t imgoff = 0;
2223 size_t preoff = 0;
2224 size_t postlen = postimage->len;
2225 size_t extra_chars;
2226 char *preimage_eof;
2227 char *preimage_end;
2228 for (i = 0; i < preimage_limit; i++) {
2229 size_t prelen = preimage->line[i].len;
2230 size_t imglen = img->line[try_lno+i].len;
2232 if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,
2233 preimage->buf + preoff, prelen))
2234 return 0;
2235 if (preimage->line[i].flag & LINE_COMMON)
2236 postlen += imglen - prelen;
2237 imgoff += imglen;
2238 preoff += prelen;
2242 * Ok, the preimage matches with whitespace fuzz.
2244 * imgoff now holds the true length of the target that
2245 * matches the preimage before the end of the file.
2247 * Count the number of characters in the preimage that fall
2248 * beyond the end of the file and make sure that all of them
2249 * are whitespace characters. (This can only happen if
2250 * we are removing blank lines at the end of the file.)
2252 buf = preimage_eof = preimage->buf + preoff;
2253 for ( ; i < preimage->nr; i++)
2254 preoff += preimage->line[i].len;
2255 preimage_end = preimage->buf + preoff;
2256 for ( ; buf < preimage_end; buf++)
2257 if (!isspace(*buf))
2258 return 0;
2261 * Update the preimage and the common postimage context
2262 * lines to use the same whitespace as the target.
2263 * If whitespace is missing in the target (i.e.
2264 * if the preimage extends beyond the end of the file),
2265 * use the whitespace from the preimage.
2267 extra_chars = preimage_end - preimage_eof;
2268 strbuf_init(&fixed, imgoff + extra_chars);
2269 strbuf_add(&fixed, img->buf + try, imgoff);
2270 strbuf_add(&fixed, preimage_eof, extra_chars);
2271 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2272 update_pre_post_images(preimage, postimage,
2273 fixed_buf, fixed_len, postlen);
2274 return 1;
2277 if (ws_error_action != correct_ws_error)
2278 return 0;
2281 * The hunk does not apply byte-by-byte, but the hash says
2282 * it might with whitespace fuzz. We haven't been asked to
2283 * ignore whitespace, we were asked to correct whitespace
2284 * errors, so let's try matching after whitespace correction.
2286 * The preimage may extend beyond the end of the file,
2287 * but in this loop we will only handle the part of the
2288 * preimage that falls within the file.
2290 strbuf_init(&fixed, preimage->len + 1);
2291 orig = preimage->buf;
2292 target = img->buf + try;
2293 for (i = 0; i < preimage_limit; i++) {
2294 size_t oldlen = preimage->line[i].len;
2295 size_t tgtlen = img->line[try_lno + i].len;
2296 size_t fixstart = fixed.len;
2297 struct strbuf tgtfix;
2298 int match;
2300 /* Try fixing the line in the preimage */
2301 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2303 /* Try fixing the line in the target */
2304 strbuf_init(&tgtfix, tgtlen);
2305 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2308 * If they match, either the preimage was based on
2309 * a version before our tree fixed whitespace breakage,
2310 * or we are lacking a whitespace-fix patch the tree
2311 * the preimage was based on already had (i.e. target
2312 * has whitespace breakage, the preimage doesn't).
2313 * In either case, we are fixing the whitespace breakages
2314 * so we might as well take the fix together with their
2315 * real change.
2317 match = (tgtfix.len == fixed.len - fixstart &&
2318 !memcmp(tgtfix.buf, fixed.buf + fixstart,
2319 fixed.len - fixstart));
2321 strbuf_release(&tgtfix);
2322 if (!match)
2323 goto unmatch_exit;
2325 orig += oldlen;
2326 target += tgtlen;
2331 * Now handle the lines in the preimage that falls beyond the
2332 * end of the file (if any). They will only match if they are
2333 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2334 * false).
2336 for ( ; i < preimage->nr; i++) {
2337 size_t fixstart = fixed.len; /* start of the fixed preimage */
2338 size_t oldlen = preimage->line[i].len;
2339 int j;
2341 /* Try fixing the line in the preimage */
2342 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2344 for (j = fixstart; j < fixed.len; j++)
2345 if (!isspace(fixed.buf[j]))
2346 goto unmatch_exit;
2348 orig += oldlen;
2352 * Yes, the preimage is based on an older version that still
2353 * has whitespace breakages unfixed, and fixing them makes the
2354 * hunk match. Update the context lines in the postimage.
2356 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2357 update_pre_post_images(preimage, postimage,
2358 fixed_buf, fixed_len, 0);
2359 return 1;
2361 unmatch_exit:
2362 strbuf_release(&fixed);
2363 return 0;
2366 static int find_pos(struct image *img,
2367 struct image *preimage,
2368 struct image *postimage,
2369 int line,
2370 unsigned ws_rule,
2371 int match_beginning, int match_end)
2373 int i;
2374 unsigned long backwards, forwards, try;
2375 int backwards_lno, forwards_lno, try_lno;
2378 * If match_beginning or match_end is specified, there is no
2379 * point starting from a wrong line that will never match and
2380 * wander around and wait for a match at the specified end.
2382 if (match_beginning)
2383 line = 0;
2384 else if (match_end)
2385 line = img->nr - preimage->nr;
2388 * Because the comparison is unsigned, the following test
2389 * will also take care of a negative line number that can
2390 * result when match_end and preimage is larger than the target.
2392 if ((size_t) line > img->nr)
2393 line = img->nr;
2395 try = 0;
2396 for (i = 0; i < line; i++)
2397 try += img->line[i].len;
2400 * There's probably some smart way to do this, but I'll leave
2401 * that to the smart and beautiful people. I'm simple and stupid.
2403 backwards = try;
2404 backwards_lno = line;
2405 forwards = try;
2406 forwards_lno = line;
2407 try_lno = line;
2409 for (i = 0; ; i++) {
2410 if (match_fragment(img, preimage, postimage,
2411 try, try_lno, ws_rule,
2412 match_beginning, match_end))
2413 return try_lno;
2415 again:
2416 if (backwards_lno == 0 && forwards_lno == img->nr)
2417 break;
2419 if (i & 1) {
2420 if (backwards_lno == 0) {
2421 i++;
2422 goto again;
2424 backwards_lno--;
2425 backwards -= img->line[backwards_lno].len;
2426 try = backwards;
2427 try_lno = backwards_lno;
2428 } else {
2429 if (forwards_lno == img->nr) {
2430 i++;
2431 goto again;
2433 forwards += img->line[forwards_lno].len;
2434 forwards_lno++;
2435 try = forwards;
2436 try_lno = forwards_lno;
2440 return -1;
2443 static void remove_first_line(struct image *img)
2445 img->buf += img->line[0].len;
2446 img->len -= img->line[0].len;
2447 img->line++;
2448 img->nr--;
2451 static void remove_last_line(struct image *img)
2453 img->len -= img->line[--img->nr].len;
2457 * The change from "preimage" and "postimage" has been found to
2458 * apply at applied_pos (counts in line numbers) in "img".
2459 * Update "img" to remove "preimage" and replace it with "postimage".
2461 static void update_image(struct image *img,
2462 int applied_pos,
2463 struct image *preimage,
2464 struct image *postimage)
2467 * remove the copy of preimage at offset in img
2468 * and replace it with postimage
2470 int i, nr;
2471 size_t remove_count, insert_count, applied_at = 0;
2472 char *result;
2473 int preimage_limit;
2476 * If we are removing blank lines at the end of img,
2477 * the preimage may extend beyond the end.
2478 * If that is the case, we must be careful only to
2479 * remove the part of the preimage that falls within
2480 * the boundaries of img. Initialize preimage_limit
2481 * to the number of lines in the preimage that falls
2482 * within the boundaries.
2484 preimage_limit = preimage->nr;
2485 if (preimage_limit > img->nr - applied_pos)
2486 preimage_limit = img->nr - applied_pos;
2488 for (i = 0; i < applied_pos; i++)
2489 applied_at += img->line[i].len;
2491 remove_count = 0;
2492 for (i = 0; i < preimage_limit; i++)
2493 remove_count += img->line[applied_pos + i].len;
2494 insert_count = postimage->len;
2496 /* Adjust the contents */
2497 result = xmalloc(img->len + insert_count - remove_count + 1);
2498 memcpy(result, img->buf, applied_at);
2499 memcpy(result + applied_at, postimage->buf, postimage->len);
2500 memcpy(result + applied_at + postimage->len,
2501 img->buf + (applied_at + remove_count),
2502 img->len - (applied_at + remove_count));
2503 free(img->buf);
2504 img->buf = result;
2505 img->len += insert_count - remove_count;
2506 result[img->len] = '\0';
2508 /* Adjust the line table */
2509 nr = img->nr + postimage->nr - preimage_limit;
2510 if (preimage_limit < postimage->nr) {
2512 * NOTE: this knows that we never call remove_first_line()
2513 * on anything other than pre/post image.
2515 img->line = xrealloc(img->line, nr * sizeof(*img->line));
2516 img->line_allocated = img->line;
2518 if (preimage_limit != postimage->nr)
2519 memmove(img->line + applied_pos + postimage->nr,
2520 img->line + applied_pos + preimage_limit,
2521 (img->nr - (applied_pos + preimage_limit)) *
2522 sizeof(*img->line));
2523 memcpy(img->line + applied_pos,
2524 postimage->line,
2525 postimage->nr * sizeof(*img->line));
2526 if (!allow_overlap)
2527 for (i = 0; i < postimage->nr; i++)
2528 img->line[applied_pos + i].flag |= LINE_PATCHED;
2529 img->nr = nr;
2533 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2534 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2535 * replace the part of "img" with "postimage" text.
2537 static int apply_one_fragment(struct image *img, struct fragment *frag,
2538 int inaccurate_eof, unsigned ws_rule,
2539 int nth_fragment)
2541 int match_beginning, match_end;
2542 const char *patch = frag->patch;
2543 int size = frag->size;
2544 char *old, *oldlines;
2545 struct strbuf newlines;
2546 int new_blank_lines_at_end = 0;
2547 int found_new_blank_lines_at_end = 0;
2548 int hunk_linenr = frag->linenr;
2549 unsigned long leading, trailing;
2550 int pos, applied_pos;
2551 struct image preimage;
2552 struct image postimage;
2554 memset(&preimage, 0, sizeof(preimage));
2555 memset(&postimage, 0, sizeof(postimage));
2556 oldlines = xmalloc(size);
2557 strbuf_init(&newlines, size);
2559 old = oldlines;
2560 while (size > 0) {
2561 char first;
2562 int len = linelen(patch, size);
2563 int plen;
2564 int added_blank_line = 0;
2565 int is_blank_context = 0;
2566 size_t start;
2568 if (!len)
2569 break;
2572 * "plen" is how much of the line we should use for
2573 * the actual patch data. Normally we just remove the
2574 * first character on the line, but if the line is
2575 * followed by "\ No newline", then we also remove the
2576 * last one (which is the newline, of course).
2578 plen = len - 1;
2579 if (len < size && patch[len] == '\\')
2580 plen--;
2581 first = *patch;
2582 if (apply_in_reverse) {
2583 if (first == '-')
2584 first = '+';
2585 else if (first == '+')
2586 first = '-';
2589 switch (first) {
2590 case '\n':
2591 /* Newer GNU diff, empty context line */
2592 if (plen < 0)
2593 /* ... followed by '\No newline'; nothing */
2594 break;
2595 *old++ = '\n';
2596 strbuf_addch(&newlines, '\n');
2597 add_line_info(&preimage, "\n", 1, LINE_COMMON);
2598 add_line_info(&postimage, "\n", 1, LINE_COMMON);
2599 is_blank_context = 1;
2600 break;
2601 case ' ':
2602 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2603 ws_blank_line(patch + 1, plen, ws_rule))
2604 is_blank_context = 1;
2605 case '-':
2606 memcpy(old, patch + 1, plen);
2607 add_line_info(&preimage, old, plen,
2608 (first == ' ' ? LINE_COMMON : 0));
2609 old += plen;
2610 if (first == '-')
2611 break;
2612 /* Fall-through for ' ' */
2613 case '+':
2614 /* --no-add does not add new lines */
2615 if (first == '+' && no_add)
2616 break;
2618 start = newlines.len;
2619 if (first != '+' ||
2620 !whitespace_error ||
2621 ws_error_action != correct_ws_error) {
2622 strbuf_add(&newlines, patch + 1, plen);
2624 else {
2625 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &applied_after_fixing_ws);
2627 add_line_info(&postimage, newlines.buf + start, newlines.len - start,
2628 (first == '+' ? 0 : LINE_COMMON));
2629 if (first == '+' &&
2630 (ws_rule & WS_BLANK_AT_EOF) &&
2631 ws_blank_line(patch + 1, plen, ws_rule))
2632 added_blank_line = 1;
2633 break;
2634 case '@': case '\\':
2635 /* Ignore it, we already handled it */
2636 break;
2637 default:
2638 if (apply_verbosely)
2639 error(_("invalid start of line: '%c'"), first);
2640 return -1;
2642 if (added_blank_line) {
2643 if (!new_blank_lines_at_end)
2644 found_new_blank_lines_at_end = hunk_linenr;
2645 new_blank_lines_at_end++;
2647 else if (is_blank_context)
2649 else
2650 new_blank_lines_at_end = 0;
2651 patch += len;
2652 size -= len;
2653 hunk_linenr++;
2655 if (inaccurate_eof &&
2656 old > oldlines && old[-1] == '\n' &&
2657 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
2658 old--;
2659 strbuf_setlen(&newlines, newlines.len - 1);
2662 leading = frag->leading;
2663 trailing = frag->trailing;
2666 * A hunk to change lines at the beginning would begin with
2667 * @@ -1,L +N,M @@
2668 * but we need to be careful. -U0 that inserts before the second
2669 * line also has this pattern.
2671 * And a hunk to add to an empty file would begin with
2672 * @@ -0,0 +N,M @@
2674 * In other words, a hunk that is (frag->oldpos <= 1) with or
2675 * without leading context must match at the beginning.
2677 match_beginning = (!frag->oldpos ||
2678 (frag->oldpos == 1 && !unidiff_zero));
2681 * A hunk without trailing lines must match at the end.
2682 * However, we simply cannot tell if a hunk must match end
2683 * from the lack of trailing lines if the patch was generated
2684 * with unidiff without any context.
2686 match_end = !unidiff_zero && !trailing;
2688 pos = frag->newpos ? (frag->newpos - 1) : 0;
2689 preimage.buf = oldlines;
2690 preimage.len = old - oldlines;
2691 postimage.buf = newlines.buf;
2692 postimage.len = newlines.len;
2693 preimage.line = preimage.line_allocated;
2694 postimage.line = postimage.line_allocated;
2696 for (;;) {
2698 applied_pos = find_pos(img, &preimage, &postimage, pos,
2699 ws_rule, match_beginning, match_end);
2701 if (applied_pos >= 0)
2702 break;
2704 /* Am I at my context limits? */
2705 if ((leading <= p_context) && (trailing <= p_context))
2706 break;
2707 if (match_beginning || match_end) {
2708 match_beginning = match_end = 0;
2709 continue;
2713 * Reduce the number of context lines; reduce both
2714 * leading and trailing if they are equal otherwise
2715 * just reduce the larger context.
2717 if (leading >= trailing) {
2718 remove_first_line(&preimage);
2719 remove_first_line(&postimage);
2720 pos--;
2721 leading--;
2723 if (trailing > leading) {
2724 remove_last_line(&preimage);
2725 remove_last_line(&postimage);
2726 trailing--;
2730 if (applied_pos >= 0) {
2731 if (new_blank_lines_at_end &&
2732 preimage.nr + applied_pos >= img->nr &&
2733 (ws_rule & WS_BLANK_AT_EOF) &&
2734 ws_error_action != nowarn_ws_error) {
2735 record_ws_error(WS_BLANK_AT_EOF, "+", 1,
2736 found_new_blank_lines_at_end);
2737 if (ws_error_action == correct_ws_error) {
2738 while (new_blank_lines_at_end--)
2739 remove_last_line(&postimage);
2742 * We would want to prevent write_out_results()
2743 * from taking place in apply_patch() that follows
2744 * the callchain led us here, which is:
2745 * apply_patch->check_patch_list->check_patch->
2746 * apply_data->apply_fragments->apply_one_fragment
2748 if (ws_error_action == die_on_ws_error)
2749 apply = 0;
2752 if (apply_verbosely && applied_pos != pos) {
2753 int offset = applied_pos - pos;
2754 if (apply_in_reverse)
2755 offset = 0 - offset;
2756 fprintf_ln(stderr,
2757 Q_("Hunk #%d succeeded at %d (offset %d line).",
2758 "Hunk #%d succeeded at %d (offset %d lines).",
2759 offset),
2760 nth_fragment, applied_pos + 1, offset);
2764 * Warn if it was necessary to reduce the number
2765 * of context lines.
2767 if ((leading != frag->leading) ||
2768 (trailing != frag->trailing))
2769 fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"
2770 " to apply fragment at %d"),
2771 leading, trailing, applied_pos+1);
2772 update_image(img, applied_pos, &preimage, &postimage);
2773 } else {
2774 if (apply_verbosely)
2775 error(_("while searching for:\n%.*s"),
2776 (int)(old - oldlines), oldlines);
2779 free(oldlines);
2780 strbuf_release(&newlines);
2781 free(preimage.line_allocated);
2782 free(postimage.line_allocated);
2784 return (applied_pos < 0);
2787 static int apply_binary_fragment(struct image *img, struct patch *patch)
2789 struct fragment *fragment = patch->fragments;
2790 unsigned long len;
2791 void *dst;
2793 if (!fragment)
2794 return error(_("missing binary patch data for '%s'"),
2795 patch->new_name ?
2796 patch->new_name :
2797 patch->old_name);
2799 /* Binary patch is irreversible without the optional second hunk */
2800 if (apply_in_reverse) {
2801 if (!fragment->next)
2802 return error("cannot reverse-apply a binary patch "
2803 "without the reverse hunk to '%s'",
2804 patch->new_name
2805 ? patch->new_name : patch->old_name);
2806 fragment = fragment->next;
2808 switch (fragment->binary_patch_method) {
2809 case BINARY_DELTA_DEFLATED:
2810 dst = patch_delta(img->buf, img->len, fragment->patch,
2811 fragment->size, &len);
2812 if (!dst)
2813 return -1;
2814 clear_image(img);
2815 img->buf = dst;
2816 img->len = len;
2817 return 0;
2818 case BINARY_LITERAL_DEFLATED:
2819 clear_image(img);
2820 img->len = fragment->size;
2821 img->buf = xmalloc(img->len+1);
2822 memcpy(img->buf, fragment->patch, img->len);
2823 img->buf[img->len] = '\0';
2824 return 0;
2826 return -1;
2830 * Replace "img" with the result of applying the binary patch.
2831 * The binary patch data itself in patch->fragment is still kept
2832 * but the preimage prepared by the caller in "img" is freed here
2833 * or in the helper function apply_binary_fragment() this calls.
2835 static int apply_binary(struct image *img, struct patch *patch)
2837 const char *name = patch->old_name ? patch->old_name : patch->new_name;
2838 unsigned char sha1[20];
2841 * For safety, we require patch index line to contain
2842 * full 40-byte textual SHA1 for old and new, at least for now.
2844 if (strlen(patch->old_sha1_prefix) != 40 ||
2845 strlen(patch->new_sha1_prefix) != 40 ||
2846 get_sha1_hex(patch->old_sha1_prefix, sha1) ||
2847 get_sha1_hex(patch->new_sha1_prefix, sha1))
2848 return error("cannot apply binary patch to '%s' "
2849 "without full index line", name);
2851 if (patch->old_name) {
2853 * See if the old one matches what the patch
2854 * applies to.
2856 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2857 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
2858 return error("the patch applies to '%s' (%s), "
2859 "which does not match the "
2860 "current contents.",
2861 name, sha1_to_hex(sha1));
2863 else {
2864 /* Otherwise, the old one must be empty. */
2865 if (img->len)
2866 return error("the patch applies to an empty "
2867 "'%s' but it is not empty", name);
2870 get_sha1_hex(patch->new_sha1_prefix, sha1);
2871 if (is_null_sha1(sha1)) {
2872 clear_image(img);
2873 return 0; /* deletion patch */
2876 if (has_sha1_file(sha1)) {
2877 /* We already have the postimage */
2878 enum object_type type;
2879 unsigned long size;
2880 char *result;
2882 result = read_sha1_file(sha1, &type, &size);
2883 if (!result)
2884 return error("the necessary postimage %s for "
2885 "'%s' cannot be read",
2886 patch->new_sha1_prefix, name);
2887 clear_image(img);
2888 img->buf = result;
2889 img->len = size;
2890 } else {
2892 * We have verified buf matches the preimage;
2893 * apply the patch data to it, which is stored
2894 * in the patch->fragments->{patch,size}.
2896 if (apply_binary_fragment(img, patch))
2897 return error(_("binary patch does not apply to '%s'"),
2898 name);
2900 /* verify that the result matches */
2901 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2902 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
2903 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
2904 name, patch->new_sha1_prefix, sha1_to_hex(sha1));
2907 return 0;
2910 static int apply_fragments(struct image *img, struct patch *patch)
2912 struct fragment *frag = patch->fragments;
2913 const char *name = patch->old_name ? patch->old_name : patch->new_name;
2914 unsigned ws_rule = patch->ws_rule;
2915 unsigned inaccurate_eof = patch->inaccurate_eof;
2916 int nth = 0;
2918 if (patch->is_binary)
2919 return apply_binary(img, patch);
2921 while (frag) {
2922 nth++;
2923 if (apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {
2924 error(_("patch failed: %s:%ld"), name, frag->oldpos);
2925 if (!apply_with_reject)
2926 return -1;
2927 frag->rejected = 1;
2929 frag = frag->next;
2931 return 0;
2934 static int read_blob_object(struct strbuf *buf, const unsigned char *sha1, unsigned mode)
2936 if (S_ISGITLINK(mode)) {
2937 strbuf_grow(buf, 100);
2938 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(sha1));
2939 } else {
2940 enum object_type type;
2941 unsigned long sz;
2942 char *result;
2944 result = read_sha1_file(sha1, &type, &sz);
2945 if (!result)
2946 return -1;
2947 /* XXX read_sha1_file NUL-terminates */
2948 strbuf_attach(buf, result, sz, sz + 1);
2950 return 0;
2953 static int read_file_or_gitlink(struct cache_entry *ce, struct strbuf *buf)
2955 if (!ce)
2956 return 0;
2957 return read_blob_object(buf, ce->sha1, ce->ce_mode);
2960 static struct patch *in_fn_table(const char *name)
2962 struct string_list_item *item;
2964 if (name == NULL)
2965 return NULL;
2967 item = string_list_lookup(&fn_table, name);
2968 if (item != NULL)
2969 return (struct patch *)item->util;
2971 return NULL;
2975 * item->util in the filename table records the status of the path.
2976 * Usually it points at a patch (whose result records the contents
2977 * of it after applying it), but it could be PATH_WAS_DELETED for a
2978 * path that a previously applied patch has already removed, or
2979 * PATH_TO_BE_DELETED for a path that a later patch would remove.
2981 * The latter is needed to deal with a case where two paths A and B
2982 * are swapped by first renaming A to B and then renaming B to A;
2983 * moving A to B should not be prevented due to presense of B as we
2984 * will remove it in a later patch.
2986 #define PATH_TO_BE_DELETED ((struct patch *) -2)
2987 #define PATH_WAS_DELETED ((struct patch *) -1)
2989 static int to_be_deleted(struct patch *patch)
2991 return patch == PATH_TO_BE_DELETED;
2994 static int was_deleted(struct patch *patch)
2996 return patch == PATH_WAS_DELETED;
2999 static void add_to_fn_table(struct patch *patch)
3001 struct string_list_item *item;
3004 * Always add new_name unless patch is a deletion
3005 * This should cover the cases for normal diffs,
3006 * file creations and copies
3008 if (patch->new_name != NULL) {
3009 item = string_list_insert(&fn_table, patch->new_name);
3010 item->util = patch;
3014 * store a failure on rename/deletion cases because
3015 * later chunks shouldn't patch old names
3017 if ((patch->new_name == NULL) || (patch->is_rename)) {
3018 item = string_list_insert(&fn_table, patch->old_name);
3019 item->util = PATH_WAS_DELETED;
3023 static void prepare_fn_table(struct patch *patch)
3026 * store information about incoming file deletion
3028 while (patch) {
3029 if ((patch->new_name == NULL) || (patch->is_rename)) {
3030 struct string_list_item *item;
3031 item = string_list_insert(&fn_table, patch->old_name);
3032 item->util = PATH_TO_BE_DELETED;
3034 patch = patch->next;
3038 static int checkout_target(struct cache_entry *ce, struct stat *st)
3040 struct checkout costate;
3042 memset(&costate, 0, sizeof(costate));
3043 costate.base_dir = "";
3044 costate.refresh_cache = 1;
3045 if (checkout_entry(ce, &costate, NULL) || lstat(ce->name, st))
3046 return error(_("cannot checkout %s"), ce->name);
3047 return 0;
3050 static struct patch *previous_patch(struct patch *patch, int *gone)
3052 struct patch *previous;
3054 *gone = 0;
3055 if (patch->is_copy || patch->is_rename)
3056 return NULL; /* "git" patches do not depend on the order */
3058 previous = in_fn_table(patch->old_name);
3059 if (!previous)
3060 return NULL;
3062 if (to_be_deleted(previous))
3063 return NULL; /* the deletion hasn't happened yet */
3065 if (was_deleted(previous))
3066 *gone = 1;
3068 return previous;
3071 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3073 static int load_patch_target(struct strbuf *buf,
3074 struct cache_entry *ce,
3075 struct stat *st,
3076 const char *name,
3077 unsigned expected_mode)
3079 if (cached) {
3080 if (read_file_or_gitlink(ce, buf))
3081 return error(_("read of %s failed"), name);
3082 } else if (name) {
3083 if (S_ISGITLINK(expected_mode)) {
3084 if (ce)
3085 return read_file_or_gitlink(ce, buf);
3086 else
3087 return SUBMODULE_PATCH_WITHOUT_INDEX;
3088 } else {
3089 if (read_old_data(st, name, buf))
3090 return error(_("read of %s failed"), name);
3093 return 0;
3097 * We are about to apply "patch"; populate the "image" with the
3098 * current version we have, from the working tree or from the index,
3099 * depending on the situation e.g. --cached/--index. If we are
3100 * applying a non-git patch that incrementally updates the tree,
3101 * we read from the result of a previous diff.
3103 static int load_preimage(struct image *image,
3104 struct patch *patch, struct stat *st, struct cache_entry *ce)
3106 struct strbuf buf = STRBUF_INIT;
3107 size_t len;
3108 char *img;
3109 struct patch *previous;
3110 int status;
3112 previous = previous_patch(patch, &status);
3113 if (status)
3114 return error(_("path %s has been renamed/deleted"),
3115 patch->old_name);
3116 if (previous) {
3117 /* We have a patched copy in memory; use that. */
3118 strbuf_add(&buf, previous->result, previous->resultsize);
3119 } else {
3120 status = load_patch_target(&buf, ce, st,
3121 patch->old_name, patch->old_mode);
3122 if (status < 0)
3123 return status;
3124 else if (status == SUBMODULE_PATCH_WITHOUT_INDEX) {
3126 * There is no way to apply subproject
3127 * patch without looking at the index.
3128 * NEEDSWORK: shouldn't this be flagged
3129 * as an error???
3131 free_fragment_list(patch->fragments);
3132 patch->fragments = NULL;
3133 } else if (status) {
3134 return error(_("read of %s failed"), patch->old_name);
3138 img = strbuf_detach(&buf, &len);
3139 prepare_image(image, img, len, !patch->is_binary);
3140 return 0;
3143 static int three_way_merge(struct image *image,
3144 char *path,
3145 const unsigned char *base,
3146 const unsigned char *ours,
3147 const unsigned char *theirs)
3149 return -1; /* for now */
3152 static int try_threeway(struct image *image, struct patch *patch,
3153 struct stat *st, struct cache_entry *ce)
3155 unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];
3156 struct strbuf buf = STRBUF_INIT;
3157 size_t len;
3158 char *img;
3159 struct image tmp_image;
3161 /* No point falling back to 3-way merge in these cases */
3162 if (patch->is_new || patch->is_delete ||
3163 S_ISGITLINK(patch->old_mode) || S_ISGITLINK(patch->new_mode))
3164 return -1;
3166 /* Preimage the patch was prepared for */
3167 if (get_sha1(patch->old_sha1_prefix, pre_sha1) ||
3168 read_blob_object(&buf, pre_sha1, patch->old_mode))
3169 return error("repository lacks the necessary blob to fall back on 3-way merge.");
3170 img = strbuf_detach(&buf, &len);
3171 prepare_image(&tmp_image, img, len, 1);
3172 /* Apply the patch to get the post image */
3173 if (apply_fragments(&tmp_image, patch) < 0) {
3174 clear_image(&tmp_image);
3175 return -1;
3177 /* post_sha1[] is theirs */
3178 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);
3179 clear_image(&tmp_image);
3181 /* our_sha1[] is ours */
3182 if (load_preimage(&tmp_image, patch, st, ce))
3183 return error("cannot read the current contents of '%s'",
3184 patch->old_name);
3185 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);
3186 clear_image(&tmp_image);
3188 /* in-core three-way merge between post and our using pre as base */
3189 return three_way_merge(image,
3190 patch->new_name, pre_sha1, our_sha1, post_sha1);
3193 static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce)
3195 struct image image;
3197 if (load_preimage(&image, patch, st, ce) < 0)
3198 return -1;
3200 if (apply_fragments(&image, patch) < 0) {
3201 /* Note: with --reject, apply_fragments() returns 0 */
3202 if (!threeway || try_threeway(&image, patch, st, ce) < 0)
3203 return -1;
3205 patch->result = image.buf;
3206 patch->resultsize = image.len;
3207 add_to_fn_table(patch);
3208 free(image.line_allocated);
3210 if (0 < patch->is_delete && patch->resultsize)
3211 return error(_("removal patch leaves file contents"));
3213 return 0;
3216 static int verify_index_match(struct cache_entry *ce, struct stat *st)
3218 if (S_ISGITLINK(ce->ce_mode)) {
3219 if (!S_ISDIR(st->st_mode))
3220 return -1;
3221 return 0;
3223 return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
3227 * If "patch" that we are looking at modifies or deletes what we have,
3228 * we would want it not to lose any local modification we have, either
3229 * in the working tree or in the index.
3231 * This also decides if a non-git patch is a creation patch or a
3232 * modification to an existing empty file. We do not check the state
3233 * of the current tree for a creation patch in this function; the caller
3234 * check_patch() separately makes sure (and errors out otherwise) that
3235 * the path the patch creates does not exist in the current tree.
3237 static int check_preimage(struct patch *patch, struct cache_entry **ce, struct stat *st)
3239 const char *old_name = patch->old_name;
3240 struct patch *previous = NULL;
3241 int stat_ret = 0, status;
3242 unsigned st_mode = 0;
3244 if (!old_name)
3245 return 0;
3247 assert(patch->is_new <= 0);
3248 previous = previous_patch(patch, &status);
3250 if (status)
3251 return error(_("path %s has been renamed/deleted"), old_name);
3252 if (previous) {
3253 st_mode = previous->new_mode;
3254 } else if (!cached) {
3255 stat_ret = lstat(old_name, st);
3256 if (stat_ret && errno != ENOENT)
3257 return error(_("%s: %s"), old_name, strerror(errno));
3260 if (check_index && !previous) {
3261 int pos = cache_name_pos(old_name, strlen(old_name));
3262 if (pos < 0) {
3263 if (patch->is_new < 0)
3264 goto is_new;
3265 return error(_("%s: does not exist in index"), old_name);
3267 *ce = active_cache[pos];
3268 if (stat_ret < 0) {
3269 if (checkout_target(*ce, st))
3270 return -1;
3272 if (!cached && verify_index_match(*ce, st))
3273 return error(_("%s: does not match index"), old_name);
3274 if (cached)
3275 st_mode = (*ce)->ce_mode;
3276 } else if (stat_ret < 0) {
3277 if (patch->is_new < 0)
3278 goto is_new;
3279 return error(_("%s: %s"), old_name, strerror(errno));
3282 if (!cached && !previous)
3283 st_mode = ce_mode_from_stat(*ce, st->st_mode);
3285 if (patch->is_new < 0)
3286 patch->is_new = 0;
3287 if (!patch->old_mode)
3288 patch->old_mode = st_mode;
3289 if ((st_mode ^ patch->old_mode) & S_IFMT)
3290 return error(_("%s: wrong type"), old_name);
3291 if (st_mode != patch->old_mode)
3292 warning(_("%s has type %o, expected %o"),
3293 old_name, st_mode, patch->old_mode);
3294 if (!patch->new_mode && !patch->is_delete)
3295 patch->new_mode = st_mode;
3296 return 0;
3298 is_new:
3299 patch->is_new = 1;
3300 patch->is_delete = 0;
3301 free(patch->old_name);
3302 patch->old_name = NULL;
3303 return 0;
3307 #define EXISTS_IN_INDEX 1
3308 #define EXISTS_IN_WORKTREE 2
3310 static int check_to_create(const char *new_name, int ok_if_exists)
3312 struct stat nst;
3314 if (check_index &&
3315 cache_name_pos(new_name, strlen(new_name)) >= 0 &&
3316 !ok_if_exists)
3317 return EXISTS_IN_INDEX;
3318 if (cached)
3319 return 0;
3321 if (!lstat(new_name, &nst)) {
3322 if (S_ISDIR(nst.st_mode) || ok_if_exists)
3323 return 0;
3325 * A leading component of new_name might be a symlink
3326 * that is going to be removed with this patch, but
3327 * still pointing at somewhere that has the path.
3328 * In such a case, path "new_name" does not exist as
3329 * far as git is concerned.
3331 if (has_symlink_leading_path(new_name, strlen(new_name)))
3332 return 0;
3334 return EXISTS_IN_WORKTREE;
3335 } else if ((errno != ENOENT) && (errno != ENOTDIR)) {
3336 return error("%s: %s", new_name, strerror(errno));
3338 return 0;
3342 * Check and apply the patch in-core; leave the result in patch->result
3343 * for the caller to write it out to the final destination.
3345 static int check_patch(struct patch *patch)
3347 struct stat st;
3348 const char *old_name = patch->old_name;
3349 const char *new_name = patch->new_name;
3350 const char *name = old_name ? old_name : new_name;
3351 struct cache_entry *ce = NULL;
3352 struct patch *tpatch;
3353 int ok_if_exists;
3354 int status;
3356 patch->rejected = 1; /* we will drop this after we succeed */
3358 status = check_preimage(patch, &ce, &st);
3359 if (status)
3360 return status;
3361 old_name = patch->old_name;
3364 * A type-change diff is always split into a patch to delete
3365 * old, immediately followed by a patch to create new (see
3366 * diff.c::run_diff()); in such a case it is Ok that the entry
3367 * to be deleted by the previous patch is still in the working
3368 * tree and in the index.
3370 * A patch to swap-rename between A and B would first rename A
3371 * to B and then rename B to A. While applying the first one,
3372 * the presense of B should not stop A from getting renamed to
3373 * B; ask to_be_deleted() about the later rename. Removal of
3374 * B and rename from A to B is handled the same way by asking
3375 * was_deleted().
3377 if ((tpatch = in_fn_table(new_name)) &&
3378 (was_deleted(tpatch) || to_be_deleted(tpatch)))
3379 ok_if_exists = 1;
3380 else
3381 ok_if_exists = 0;
3383 if (new_name &&
3384 ((0 < patch->is_new) | (0 < patch->is_rename) | patch->is_copy)) {
3385 int err = check_to_create(new_name, ok_if_exists);
3387 switch (err) {
3388 case 0:
3389 break; /* happy */
3390 case EXISTS_IN_INDEX:
3391 return error(_("%s: already exists in index"), new_name);
3392 break;
3393 case EXISTS_IN_WORKTREE:
3394 return error(_("%s: already exists in working directory"),
3395 new_name);
3396 default:
3397 return err;
3400 if (!patch->new_mode) {
3401 if (0 < patch->is_new)
3402 patch->new_mode = S_IFREG | 0644;
3403 else
3404 patch->new_mode = patch->old_mode;
3408 if (new_name && old_name) {
3409 int same = !strcmp(old_name, new_name);
3410 if (!patch->new_mode)
3411 patch->new_mode = patch->old_mode;
3412 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
3413 return error(_("new mode (%o) of %s does not match old mode (%o)%s%s"),
3414 patch->new_mode, new_name, patch->old_mode,
3415 same ? "" : " of ", same ? "" : old_name);
3418 if (apply_data(patch, &st, ce) < 0)
3419 return error(_("%s: patch does not apply"), name);
3420 patch->rejected = 0;
3421 return 0;
3424 static int check_patch_list(struct patch *patch)
3426 int err = 0;
3428 prepare_fn_table(patch);
3429 while (patch) {
3430 if (apply_verbosely)
3431 say_patch_name(stderr,
3432 _("Checking patch %s..."), patch);
3433 err |= check_patch(patch);
3434 patch = patch->next;
3436 return err;
3439 /* This function tries to read the sha1 from the current index */
3440 static int get_current_sha1(const char *path, unsigned char *sha1)
3442 int pos;
3444 if (read_cache() < 0)
3445 return -1;
3446 pos = cache_name_pos(path, strlen(path));
3447 if (pos < 0)
3448 return -1;
3449 hashcpy(sha1, active_cache[pos]->sha1);
3450 return 0;
3453 /* Build an index that contains the just the files needed for a 3way merge */
3454 static void build_fake_ancestor(struct patch *list, const char *filename)
3456 struct patch *patch;
3457 struct index_state result = { NULL };
3458 int fd;
3460 /* Once we start supporting the reverse patch, it may be
3461 * worth showing the new sha1 prefix, but until then...
3463 for (patch = list; patch; patch = patch->next) {
3464 const unsigned char *sha1_ptr;
3465 unsigned char sha1[20];
3466 struct cache_entry *ce;
3467 const char *name;
3469 name = patch->old_name ? patch->old_name : patch->new_name;
3470 if (0 < patch->is_new)
3471 continue;
3472 else if (get_sha1(patch->old_sha1_prefix, sha1))
3473 /* git diff has no index line for mode/type changes */
3474 if (!patch->lines_added && !patch->lines_deleted) {
3475 if (get_current_sha1(patch->old_name, sha1))
3476 die("mode change for %s, which is not "
3477 "in current HEAD", name);
3478 sha1_ptr = sha1;
3479 } else
3480 die("sha1 information is lacking or useless "
3481 "(%s).", name);
3482 else
3483 sha1_ptr = sha1;
3485 ce = make_cache_entry(patch->old_mode, sha1_ptr, name, 0, 0);
3486 if (!ce)
3487 die(_("make_cache_entry failed for path '%s'"), name);
3488 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))
3489 die ("Could not add %s to temporary index", name);
3492 fd = open(filename, O_WRONLY | O_CREAT, 0666);
3493 if (fd < 0 || write_index(&result, fd) || close(fd))
3494 die ("Could not write temporary index to %s", filename);
3496 discard_index(&result);
3499 static void stat_patch_list(struct patch *patch)
3501 int files, adds, dels;
3503 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
3504 files++;
3505 adds += patch->lines_added;
3506 dels += patch->lines_deleted;
3507 show_stats(patch);
3510 print_stat_summary(stdout, files, adds, dels);
3513 static void numstat_patch_list(struct patch *patch)
3515 for ( ; patch; patch = patch->next) {
3516 const char *name;
3517 name = patch->new_name ? patch->new_name : patch->old_name;
3518 if (patch->is_binary)
3519 printf("-\t-\t");
3520 else
3521 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
3522 write_name_quoted(name, stdout, line_termination);
3526 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
3528 if (mode)
3529 printf(" %s mode %06o %s\n", newdelete, mode, name);
3530 else
3531 printf(" %s %s\n", newdelete, name);
3534 static void show_mode_change(struct patch *p, int show_name)
3536 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
3537 if (show_name)
3538 printf(" mode change %06o => %06o %s\n",
3539 p->old_mode, p->new_mode, p->new_name);
3540 else
3541 printf(" mode change %06o => %06o\n",
3542 p->old_mode, p->new_mode);
3546 static void show_rename_copy(struct patch *p)
3548 const char *renamecopy = p->is_rename ? "rename" : "copy";
3549 const char *old, *new;
3551 /* Find common prefix */
3552 old = p->old_name;
3553 new = p->new_name;
3554 while (1) {
3555 const char *slash_old, *slash_new;
3556 slash_old = strchr(old, '/');
3557 slash_new = strchr(new, '/');
3558 if (!slash_old ||
3559 !slash_new ||
3560 slash_old - old != slash_new - new ||
3561 memcmp(old, new, slash_new - new))
3562 break;
3563 old = slash_old + 1;
3564 new = slash_new + 1;
3566 /* p->old_name thru old is the common prefix, and old and new
3567 * through the end of names are renames
3569 if (old != p->old_name)
3570 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
3571 (int)(old - p->old_name), p->old_name,
3572 old, new, p->score);
3573 else
3574 printf(" %s %s => %s (%d%%)\n", renamecopy,
3575 p->old_name, p->new_name, p->score);
3576 show_mode_change(p, 0);
3579 static void summary_patch_list(struct patch *patch)
3581 struct patch *p;
3583 for (p = patch; p; p = p->next) {
3584 if (p->is_new)
3585 show_file_mode_name("create", p->new_mode, p->new_name);
3586 else if (p->is_delete)
3587 show_file_mode_name("delete", p->old_mode, p->old_name);
3588 else {
3589 if (p->is_rename || p->is_copy)
3590 show_rename_copy(p);
3591 else {
3592 if (p->score) {
3593 printf(" rewrite %s (%d%%)\n",
3594 p->new_name, p->score);
3595 show_mode_change(p, 0);
3597 else
3598 show_mode_change(p, 1);
3604 static void patch_stats(struct patch *patch)
3606 int lines = patch->lines_added + patch->lines_deleted;
3608 if (lines > max_change)
3609 max_change = lines;
3610 if (patch->old_name) {
3611 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
3612 if (!len)
3613 len = strlen(patch->old_name);
3614 if (len > max_len)
3615 max_len = len;
3617 if (patch->new_name) {
3618 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
3619 if (!len)
3620 len = strlen(patch->new_name);
3621 if (len > max_len)
3622 max_len = len;
3626 static void remove_file(struct patch *patch, int rmdir_empty)
3628 if (update_index) {
3629 if (remove_file_from_cache(patch->old_name) < 0)
3630 die(_("unable to remove %s from index"), patch->old_name);
3632 if (!cached) {
3633 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
3634 remove_path(patch->old_name);
3639 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
3641 struct stat st;
3642 struct cache_entry *ce;
3643 int namelen = strlen(path);
3644 unsigned ce_size = cache_entry_size(namelen);
3646 if (!update_index)
3647 return;
3649 ce = xcalloc(1, ce_size);
3650 memcpy(ce->name, path, namelen);
3651 ce->ce_mode = create_ce_mode(mode);
3652 ce->ce_flags = namelen;
3653 if (S_ISGITLINK(mode)) {
3654 const char *s = buf;
3656 if (get_sha1_hex(s + strlen("Subproject commit "), ce->sha1))
3657 die(_("corrupt patch for subproject %s"), path);
3658 } else {
3659 if (!cached) {
3660 if (lstat(path, &st) < 0)
3661 die_errno(_("unable to stat newly created file '%s'"),
3662 path);
3663 fill_stat_cache_info(ce, &st);
3665 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
3666 die(_("unable to create backing store for newly created file %s"), path);
3668 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
3669 die(_("unable to add cache entry for %s"), path);
3672 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
3674 int fd;
3675 struct strbuf nbuf = STRBUF_INIT;
3677 if (S_ISGITLINK(mode)) {
3678 struct stat st;
3679 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
3680 return 0;
3681 return mkdir(path, 0777);
3684 if (has_symlinks && S_ISLNK(mode))
3685 /* Although buf:size is counted string, it also is NUL
3686 * terminated.
3688 return symlink(buf, path);
3690 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
3691 if (fd < 0)
3692 return -1;
3694 if (convert_to_working_tree(path, buf, size, &nbuf)) {
3695 size = nbuf.len;
3696 buf = nbuf.buf;
3698 write_or_die(fd, buf, size);
3699 strbuf_release(&nbuf);
3701 if (close(fd) < 0)
3702 die_errno(_("closing file '%s'"), path);
3703 return 0;
3707 * We optimistically assume that the directories exist,
3708 * which is true 99% of the time anyway. If they don't,
3709 * we create them and try again.
3711 static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
3713 if (cached)
3714 return;
3715 if (!try_create_file(path, mode, buf, size))
3716 return;
3718 if (errno == ENOENT) {
3719 if (safe_create_leading_directories(path))
3720 return;
3721 if (!try_create_file(path, mode, buf, size))
3722 return;
3725 if (errno == EEXIST || errno == EACCES) {
3726 /* We may be trying to create a file where a directory
3727 * used to be.
3729 struct stat st;
3730 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
3731 errno = EEXIST;
3734 if (errno == EEXIST) {
3735 unsigned int nr = getpid();
3737 for (;;) {
3738 char newpath[PATH_MAX];
3739 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
3740 if (!try_create_file(newpath, mode, buf, size)) {
3741 if (!rename(newpath, path))
3742 return;
3743 unlink_or_warn(newpath);
3744 break;
3746 if (errno != EEXIST)
3747 break;
3748 ++nr;
3751 die_errno(_("unable to write file '%s' mode %o"), path, mode);
3754 static void create_file(struct patch *patch)
3756 char *path = patch->new_name;
3757 unsigned mode = patch->new_mode;
3758 unsigned long size = patch->resultsize;
3759 char *buf = patch->result;
3761 if (!mode)
3762 mode = S_IFREG | 0644;
3763 create_one_file(path, mode, buf, size);
3764 add_index_file(path, mode, buf, size);
3767 /* phase zero is to remove, phase one is to create */
3768 static void write_out_one_result(struct patch *patch, int phase)
3770 if (patch->is_delete > 0) {
3771 if (phase == 0)
3772 remove_file(patch, 1);
3773 return;
3775 if (patch->is_new > 0 || patch->is_copy) {
3776 if (phase == 1)
3777 create_file(patch);
3778 return;
3781 * Rename or modification boils down to the same
3782 * thing: remove the old, write the new
3784 if (phase == 0)
3785 remove_file(patch, patch->is_rename);
3786 if (phase == 1)
3787 create_file(patch);
3790 static int write_out_one_reject(struct patch *patch)
3792 FILE *rej;
3793 char namebuf[PATH_MAX];
3794 struct fragment *frag;
3795 int cnt = 0;
3796 struct strbuf sb = STRBUF_INIT;
3798 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
3799 if (!frag->rejected)
3800 continue;
3801 cnt++;
3804 if (!cnt) {
3805 if (apply_verbosely)
3806 say_patch_name(stderr,
3807 _("Applied patch %s cleanly."), patch);
3808 return 0;
3811 /* This should not happen, because a removal patch that leaves
3812 * contents are marked "rejected" at the patch level.
3814 if (!patch->new_name)
3815 die(_("internal error"));
3817 /* Say this even without --verbose */
3818 strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",
3819 "Applying patch %%s with %d rejects...",
3820 cnt),
3821 cnt);
3822 say_patch_name(stderr, sb.buf, patch);
3823 strbuf_release(&sb);
3825 cnt = strlen(patch->new_name);
3826 if (ARRAY_SIZE(namebuf) <= cnt + 5) {
3827 cnt = ARRAY_SIZE(namebuf) - 5;
3828 warning(_("truncating .rej filename to %.*s.rej"),
3829 cnt - 1, patch->new_name);
3831 memcpy(namebuf, patch->new_name, cnt);
3832 memcpy(namebuf + cnt, ".rej", 5);
3834 rej = fopen(namebuf, "w");
3835 if (!rej)
3836 return error(_("cannot open %s: %s"), namebuf, strerror(errno));
3838 /* Normal git tools never deal with .rej, so do not pretend
3839 * this is a git patch by saying --git nor give extended
3840 * headers. While at it, maybe please "kompare" that wants
3841 * the trailing TAB and some garbage at the end of line ;-).
3843 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
3844 patch->new_name, patch->new_name);
3845 for (cnt = 1, frag = patch->fragments;
3846 frag;
3847 cnt++, frag = frag->next) {
3848 if (!frag->rejected) {
3849 fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);
3850 continue;
3852 fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);
3853 fprintf(rej, "%.*s", frag->size, frag->patch);
3854 if (frag->patch[frag->size-1] != '\n')
3855 fputc('\n', rej);
3857 fclose(rej);
3858 return -1;
3861 static int write_out_results(struct patch *list)
3863 int phase;
3864 int errs = 0;
3865 struct patch *l;
3867 for (phase = 0; phase < 2; phase++) {
3868 l = list;
3869 while (l) {
3870 if (l->rejected)
3871 errs = 1;
3872 else {
3873 write_out_one_result(l, phase);
3874 if (phase == 1 && write_out_one_reject(l))
3875 errs = 1;
3877 l = l->next;
3880 return errs;
3883 static struct lock_file lock_file;
3885 static struct string_list limit_by_name;
3886 static int has_include;
3887 static void add_name_limit(const char *name, int exclude)
3889 struct string_list_item *it;
3891 it = string_list_append(&limit_by_name, name);
3892 it->util = exclude ? NULL : (void *) 1;
3895 static int use_patch(struct patch *p)
3897 const char *pathname = p->new_name ? p->new_name : p->old_name;
3898 int i;
3900 /* Paths outside are not touched regardless of "--include" */
3901 if (0 < prefix_length) {
3902 int pathlen = strlen(pathname);
3903 if (pathlen <= prefix_length ||
3904 memcmp(prefix, pathname, prefix_length))
3905 return 0;
3908 /* See if it matches any of exclude/include rule */
3909 for (i = 0; i < limit_by_name.nr; i++) {
3910 struct string_list_item *it = &limit_by_name.items[i];
3911 if (!fnmatch(it->string, pathname, 0))
3912 return (it->util != NULL);
3916 * If we had any include, a path that does not match any rule is
3917 * not used. Otherwise, we saw bunch of exclude rules (or none)
3918 * and such a path is used.
3920 return !has_include;
3924 static void prefix_one(char **name)
3926 char *old_name = *name;
3927 if (!old_name)
3928 return;
3929 *name = xstrdup(prefix_filename(prefix, prefix_length, *name));
3930 free(old_name);
3933 static void prefix_patches(struct patch *p)
3935 if (!prefix || p->is_toplevel_relative)
3936 return;
3937 for ( ; p; p = p->next) {
3938 prefix_one(&p->new_name);
3939 prefix_one(&p->old_name);
3943 #define INACCURATE_EOF (1<<0)
3944 #define RECOUNT (1<<1)
3946 static int apply_patch(int fd, const char *filename, int options)
3948 size_t offset;
3949 struct strbuf buf = STRBUF_INIT; /* owns the patch text */
3950 struct patch *list = NULL, **listp = &list;
3951 int skipped_patch = 0;
3953 patch_input_file = filename;
3954 read_patch_file(&buf, fd);
3955 offset = 0;
3956 while (offset < buf.len) {
3957 struct patch *patch;
3958 int nr;
3960 patch = xcalloc(1, sizeof(*patch));
3961 patch->inaccurate_eof = !!(options & INACCURATE_EOF);
3962 patch->recount = !!(options & RECOUNT);
3963 nr = parse_chunk(buf.buf + offset, buf.len - offset, patch);
3964 if (nr < 0)
3965 break;
3966 if (apply_in_reverse)
3967 reverse_patches(patch);
3968 if (prefix)
3969 prefix_patches(patch);
3970 if (use_patch(patch)) {
3971 patch_stats(patch);
3972 *listp = patch;
3973 listp = &patch->next;
3975 else {
3976 free_patch(patch);
3977 skipped_patch++;
3979 offset += nr;
3982 if (!list && !skipped_patch)
3983 die(_("unrecognized input"));
3985 if (whitespace_error && (ws_error_action == die_on_ws_error))
3986 apply = 0;
3988 update_index = check_index && apply;
3989 if (update_index && newfd < 0)
3990 newfd = hold_locked_index(&lock_file, 1);
3992 if (check_index) {
3993 if (read_cache() < 0)
3994 die(_("unable to read index file"));
3997 if ((check || apply) &&
3998 check_patch_list(list) < 0 &&
3999 !apply_with_reject)
4000 exit(1);
4002 if (apply && write_out_results(list))
4003 exit(1);
4005 if (fake_ancestor)
4006 build_fake_ancestor(list, fake_ancestor);
4008 if (diffstat)
4009 stat_patch_list(list);
4011 if (numstat)
4012 numstat_patch_list(list);
4014 if (summary)
4015 summary_patch_list(list);
4017 free_patch_list(list);
4018 strbuf_release(&buf);
4019 string_list_clear(&fn_table, 0);
4020 return 0;
4023 static int git_apply_config(const char *var, const char *value, void *cb)
4025 if (!strcmp(var, "apply.whitespace"))
4026 return git_config_string(&apply_default_whitespace, var, value);
4027 else if (!strcmp(var, "apply.ignorewhitespace"))
4028 return git_config_string(&apply_default_ignorewhitespace, var, value);
4029 return git_default_config(var, value, cb);
4032 static int option_parse_exclude(const struct option *opt,
4033 const char *arg, int unset)
4035 add_name_limit(arg, 1);
4036 return 0;
4039 static int option_parse_include(const struct option *opt,
4040 const char *arg, int unset)
4042 add_name_limit(arg, 0);
4043 has_include = 1;
4044 return 0;
4047 static int option_parse_p(const struct option *opt,
4048 const char *arg, int unset)
4050 p_value = atoi(arg);
4051 p_value_known = 1;
4052 return 0;
4055 static int option_parse_z(const struct option *opt,
4056 const char *arg, int unset)
4058 if (unset)
4059 line_termination = '\n';
4060 else
4061 line_termination = 0;
4062 return 0;
4065 static int option_parse_space_change(const struct option *opt,
4066 const char *arg, int unset)
4068 if (unset)
4069 ws_ignore_action = ignore_ws_none;
4070 else
4071 ws_ignore_action = ignore_ws_change;
4072 return 0;
4075 static int option_parse_whitespace(const struct option *opt,
4076 const char *arg, int unset)
4078 const char **whitespace_option = opt->value;
4080 *whitespace_option = arg;
4081 parse_whitespace_option(arg);
4082 return 0;
4085 static int option_parse_directory(const struct option *opt,
4086 const char *arg, int unset)
4088 root_len = strlen(arg);
4089 if (root_len && arg[root_len - 1] != '/') {
4090 char *new_root;
4091 root = new_root = xmalloc(root_len + 2);
4092 strcpy(new_root, arg);
4093 strcpy(new_root + root_len++, "/");
4094 } else
4095 root = arg;
4096 return 0;
4099 int cmd_apply(int argc, const char **argv, const char *prefix_)
4101 int i;
4102 int errs = 0;
4103 int is_not_gitdir = !startup_info->have_repository;
4104 int force_apply = 0;
4106 const char *whitespace_option = NULL;
4108 struct option builtin_apply_options[] = {
4109 { OPTION_CALLBACK, 0, "exclude", NULL, "path",
4110 "don't apply changes matching the given path",
4111 0, option_parse_exclude },
4112 { OPTION_CALLBACK, 0, "include", NULL, "path",
4113 "apply changes matching the given path",
4114 0, option_parse_include },
4115 { OPTION_CALLBACK, 'p', NULL, NULL, "num",
4116 "remove <num> leading slashes from traditional diff paths",
4117 0, option_parse_p },
4118 OPT_BOOLEAN(0, "no-add", &no_add,
4119 "ignore additions made by the patch"),
4120 OPT_BOOLEAN(0, "stat", &diffstat,
4121 "instead of applying the patch, output diffstat for the input"),
4122 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
4123 OPT_NOOP_NOARG(0, "binary"),
4124 OPT_BOOLEAN(0, "numstat", &numstat,
4125 "shows number of added and deleted lines in decimal notation"),
4126 OPT_BOOLEAN(0, "summary", &summary,
4127 "instead of applying the patch, output a summary for the input"),
4128 OPT_BOOLEAN(0, "check", &check,
4129 "instead of applying the patch, see if the patch is applicable"),
4130 OPT_BOOLEAN(0, "index", &check_index,
4131 "make sure the patch is applicable to the current index"),
4132 OPT_BOOLEAN(0, "cached", &cached,
4133 "apply a patch without touching the working tree"),
4134 OPT_BOOLEAN(0, "apply", &force_apply,
4135 "also apply the patch (use with --stat/--summary/--check)"),
4136 OPT_BOOL('3', "3way", &threeway,
4137 "attempt three-way merge if a patch does not apply"),
4138 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor,
4139 "build a temporary index based on embedded index information"),
4140 { OPTION_CALLBACK, 'z', NULL, NULL, NULL,
4141 "paths are separated with NUL character",
4142 PARSE_OPT_NOARG, option_parse_z },
4143 OPT_INTEGER('C', NULL, &p_context,
4144 "ensure at least <n> lines of context match"),
4145 { OPTION_CALLBACK, 0, "whitespace", &whitespace_option, "action",
4146 "detect new or modified lines that have whitespace errors",
4147 0, option_parse_whitespace },
4148 { OPTION_CALLBACK, 0, "ignore-space-change", NULL, NULL,
4149 "ignore changes in whitespace when finding context",
4150 PARSE_OPT_NOARG, option_parse_space_change },
4151 { OPTION_CALLBACK, 0, "ignore-whitespace", NULL, NULL,
4152 "ignore changes in whitespace when finding context",
4153 PARSE_OPT_NOARG, option_parse_space_change },
4154 OPT_BOOLEAN('R', "reverse", &apply_in_reverse,
4155 "apply the patch in reverse"),
4156 OPT_BOOLEAN(0, "unidiff-zero", &unidiff_zero,
4157 "don't expect at least one line of context"),
4158 OPT_BOOLEAN(0, "reject", &apply_with_reject,
4159 "leave the rejected hunks in corresponding *.rej files"),
4160 OPT_BOOLEAN(0, "allow-overlap", &allow_overlap,
4161 "allow overlapping hunks"),
4162 OPT__VERBOSE(&apply_verbosely, "be verbose"),
4163 OPT_BIT(0, "inaccurate-eof", &options,
4164 "tolerate incorrectly detected missing new-line at the end of file",
4165 INACCURATE_EOF),
4166 OPT_BIT(0, "recount", &options,
4167 "do not trust the line counts in the hunk headers",
4168 RECOUNT),
4169 { OPTION_CALLBACK, 0, "directory", NULL, "root",
4170 "prepend <root> to all filenames",
4171 0, option_parse_directory },
4172 OPT_END()
4175 prefix = prefix_;
4176 prefix_length = prefix ? strlen(prefix) : 0;
4177 git_config(git_apply_config, NULL);
4178 if (apply_default_whitespace)
4179 parse_whitespace_option(apply_default_whitespace);
4180 if (apply_default_ignorewhitespace)
4181 parse_ignorewhitespace_option(apply_default_ignorewhitespace);
4183 argc = parse_options(argc, argv, prefix, builtin_apply_options,
4184 apply_usage, 0);
4186 if (apply_with_reject && threeway)
4187 die("--reject and --3way cannot be used together.");
4188 if (cached && threeway)
4189 die("--cached and --3way cannot be used together.");
4190 if (threeway) {
4191 if (is_not_gitdir)
4192 die(_("--3way outside a repository"));
4193 check_index = 1;
4195 if (apply_with_reject)
4196 apply = apply_verbosely = 1;
4197 if (!force_apply && (diffstat || numstat || summary || check || fake_ancestor))
4198 apply = 0;
4199 if (check_index && is_not_gitdir)
4200 die(_("--index outside a repository"));
4201 if (cached) {
4202 if (is_not_gitdir)
4203 die(_("--cached outside a repository"));
4204 check_index = 1;
4206 for (i = 0; i < argc; i++) {
4207 const char *arg = argv[i];
4208 int fd;
4210 if (!strcmp(arg, "-")) {
4211 errs |= apply_patch(0, "<stdin>", options);
4212 read_stdin = 0;
4213 continue;
4214 } else if (0 < prefix_length)
4215 arg = prefix_filename(prefix, prefix_length, arg);
4217 fd = open(arg, O_RDONLY);
4218 if (fd < 0)
4219 die_errno(_("can't open patch '%s'"), arg);
4220 read_stdin = 0;
4221 set_default_whitespace_mode(whitespace_option);
4222 errs |= apply_patch(fd, arg, options);
4223 close(fd);
4225 set_default_whitespace_mode(whitespace_option);
4226 if (read_stdin)
4227 errs |= apply_patch(0, "<stdin>", options);
4228 if (whitespace_error) {
4229 if (squelch_whitespace_errors &&
4230 squelch_whitespace_errors < whitespace_error) {
4231 int squelched =
4232 whitespace_error - squelch_whitespace_errors;
4233 warning(Q_("squelched %d whitespace error",
4234 "squelched %d whitespace errors",
4235 squelched),
4236 squelched);
4238 if (ws_error_action == die_on_ws_error)
4239 die(Q_("%d line adds whitespace errors.",
4240 "%d lines add whitespace errors.",
4241 whitespace_error),
4242 whitespace_error);
4243 if (applied_after_fixing_ws && apply)
4244 warning("%d line%s applied after"
4245 " fixing whitespace errors.",
4246 applied_after_fixing_ws,
4247 applied_after_fixing_ws == 1 ? "" : "s");
4248 else if (whitespace_error)
4249 warning(Q_("%d line adds whitespace errors.",
4250 "%d lines add whitespace errors.",
4251 whitespace_error),
4252 whitespace_error);
4255 if (update_index) {
4256 if (write_cache(newfd, active_cache, active_nr) ||
4257 commit_locked_index(&lock_file))
4258 die(_("Unable to write new index file"));
4261 return !!errs;