apply: move verify_index_match() higher
[git/mingw/4msysgit.git] / builtin / apply.c
blob682852c716f5c2a60ad23ee063c8d4df4ffb8283
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"
19 #include "xdiff-interface.h"
20 #include "ll-merge.h"
23 * --check turns on checking that the working tree matches the
24 * files that are being modified, but doesn't apply the patch
25 * --stat does just a diffstat, and doesn't actually apply
26 * --numstat does numeric diffstat, and doesn't actually apply
27 * --index-info shows the old and new index info for paths if available.
28 * --index updates the cache as well.
29 * --cached updates only the cache without ever touching the working tree.
31 static const char *prefix;
32 static int prefix_length = -1;
33 static int newfd = -1;
35 static int unidiff_zero;
36 static int p_value = 1;
37 static int p_value_known;
38 static int check_index;
39 static int update_index;
40 static int cached;
41 static int diffstat;
42 static int numstat;
43 static int summary;
44 static int check;
45 static int apply = 1;
46 static int apply_in_reverse;
47 static int apply_with_reject;
48 static int apply_verbosely;
49 static int allow_overlap;
50 static int no_add;
51 static int threeway;
52 static const char *fake_ancestor;
53 static int line_termination = '\n';
54 static unsigned int p_context = UINT_MAX;
55 static const char * const apply_usage[] = {
56 "git apply [options] [<patch>...]",
57 NULL
60 static enum ws_error_action {
61 nowarn_ws_error,
62 warn_on_ws_error,
63 die_on_ws_error,
64 correct_ws_error
65 } ws_error_action = warn_on_ws_error;
66 static int whitespace_error;
67 static int squelch_whitespace_errors = 5;
68 static int applied_after_fixing_ws;
70 static enum ws_ignore {
71 ignore_ws_none,
72 ignore_ws_change
73 } ws_ignore_action = ignore_ws_none;
76 static const char *patch_input_file;
77 static const char *root;
78 static int root_len;
79 static int read_stdin = 1;
80 static int options;
82 static void parse_whitespace_option(const char *option)
84 if (!option) {
85 ws_error_action = warn_on_ws_error;
86 return;
88 if (!strcmp(option, "warn")) {
89 ws_error_action = warn_on_ws_error;
90 return;
92 if (!strcmp(option, "nowarn")) {
93 ws_error_action = nowarn_ws_error;
94 return;
96 if (!strcmp(option, "error")) {
97 ws_error_action = die_on_ws_error;
98 return;
100 if (!strcmp(option, "error-all")) {
101 ws_error_action = die_on_ws_error;
102 squelch_whitespace_errors = 0;
103 return;
105 if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
106 ws_error_action = correct_ws_error;
107 return;
109 die(_("unrecognized whitespace option '%s'"), option);
112 static void parse_ignorewhitespace_option(const char *option)
114 if (!option || !strcmp(option, "no") ||
115 !strcmp(option, "false") || !strcmp(option, "never") ||
116 !strcmp(option, "none")) {
117 ws_ignore_action = ignore_ws_none;
118 return;
120 if (!strcmp(option, "change")) {
121 ws_ignore_action = ignore_ws_change;
122 return;
124 die(_("unrecognized whitespace ignore option '%s'"), option);
127 static void set_default_whitespace_mode(const char *whitespace_option)
129 if (!whitespace_option && !apply_default_whitespace)
130 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error);
134 * For "diff-stat" like behaviour, we keep track of the biggest change
135 * we've seen, and the longest filename. That allows us to do simple
136 * scaling.
138 static int max_change, max_len;
141 * Various "current state", notably line numbers and what
142 * file (and how) we're patching right now.. The "is_xxxx"
143 * things are flags, where -1 means "don't know yet".
145 static int linenr = 1;
148 * This represents one "hunk" from a patch, starting with
149 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
150 * patch text is pointed at by patch, and its byte length
151 * is stored in size. leading and trailing are the number
152 * of context lines.
154 struct fragment {
155 unsigned long leading, trailing;
156 unsigned long oldpos, oldlines;
157 unsigned long newpos, newlines;
159 * 'patch' is usually borrowed from buf in apply_patch(),
160 * but some codepaths store an allocated buffer.
162 const char *patch;
163 unsigned free_patch:1,
164 rejected:1;
165 int size;
166 int linenr;
167 struct fragment *next;
171 * When dealing with a binary patch, we reuse "leading" field
172 * to store the type of the binary hunk, either deflated "delta"
173 * or deflated "literal".
175 #define binary_patch_method leading
176 #define BINARY_DELTA_DEFLATED 1
177 #define BINARY_LITERAL_DEFLATED 2
180 * This represents a "patch" to a file, both metainfo changes
181 * such as creation/deletion, filemode and content changes represented
182 * as a series of fragments.
184 struct patch {
185 char *new_name, *old_name, *def_name;
186 unsigned int old_mode, new_mode;
187 int is_new, is_delete; /* -1 = unknown, 0 = false, 1 = true */
188 int rejected;
189 unsigned ws_rule;
190 unsigned long deflate_origlen;
191 int lines_added, lines_deleted;
192 int score;
193 unsigned int is_toplevel_relative:1;
194 unsigned int inaccurate_eof:1;
195 unsigned int is_binary:1;
196 unsigned int is_copy:1;
197 unsigned int is_rename:1;
198 unsigned int recount:1;
199 unsigned int conflicted_threeway:1;
200 struct fragment *fragments;
201 char *result;
202 size_t resultsize;
203 char old_sha1_prefix[41];
204 char new_sha1_prefix[41];
205 struct patch *next;
207 /* three-way fallback result */
208 unsigned char threeway_stage[3][20];
211 static void free_fragment_list(struct fragment *list)
213 while (list) {
214 struct fragment *next = list->next;
215 if (list->free_patch)
216 free((char *)list->patch);
217 free(list);
218 list = next;
222 static void free_patch(struct patch *patch)
224 free_fragment_list(patch->fragments);
225 free(patch->def_name);
226 free(patch->old_name);
227 free(patch->new_name);
228 free(patch->result);
229 free(patch);
232 static void free_patch_list(struct patch *list)
234 while (list) {
235 struct patch *next = list->next;
236 free_patch(list);
237 list = next;
242 * A line in a file, len-bytes long (includes the terminating LF,
243 * except for an incomplete line at the end if the file ends with
244 * one), and its contents hashes to 'hash'.
246 struct line {
247 size_t len;
248 unsigned hash : 24;
249 unsigned flag : 8;
250 #define LINE_COMMON 1
251 #define LINE_PATCHED 2
255 * This represents a "file", which is an array of "lines".
257 struct image {
258 char *buf;
259 size_t len;
260 size_t nr;
261 size_t alloc;
262 struct line *line_allocated;
263 struct line *line;
267 * Records filenames that have been touched, in order to handle
268 * the case where more than one patches touch the same file.
271 static struct string_list fn_table;
273 static uint32_t hash_line(const char *cp, size_t len)
275 size_t i;
276 uint32_t h;
277 for (i = 0, h = 0; i < len; i++) {
278 if (!isspace(cp[i])) {
279 h = h * 3 + (cp[i] & 0xff);
282 return h;
286 * Compare lines s1 of length n1 and s2 of length n2, ignoring
287 * whitespace difference. Returns 1 if they match, 0 otherwise
289 static int fuzzy_matchlines(const char *s1, size_t n1,
290 const char *s2, size_t n2)
292 const char *last1 = s1 + n1 - 1;
293 const char *last2 = s2 + n2 - 1;
294 int result = 0;
296 /* ignore line endings */
297 while ((*last1 == '\r') || (*last1 == '\n'))
298 last1--;
299 while ((*last2 == '\r') || (*last2 == '\n'))
300 last2--;
302 /* skip leading whitespace */
303 while (isspace(*s1) && (s1 <= last1))
304 s1++;
305 while (isspace(*s2) && (s2 <= last2))
306 s2++;
307 /* early return if both lines are empty */
308 if ((s1 > last1) && (s2 > last2))
309 return 1;
310 while (!result) {
311 result = *s1++ - *s2++;
313 * Skip whitespace inside. We check for whitespace on
314 * both buffers because we don't want "a b" to match
315 * "ab"
317 if (isspace(*s1) && isspace(*s2)) {
318 while (isspace(*s1) && s1 <= last1)
319 s1++;
320 while (isspace(*s2) && s2 <= last2)
321 s2++;
324 * If we reached the end on one side only,
325 * lines don't match
327 if (
328 ((s2 > last2) && (s1 <= last1)) ||
329 ((s1 > last1) && (s2 <= last2)))
330 return 0;
331 if ((s1 > last1) && (s2 > last2))
332 break;
335 return !result;
338 static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
340 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
341 img->line_allocated[img->nr].len = len;
342 img->line_allocated[img->nr].hash = hash_line(bol, len);
343 img->line_allocated[img->nr].flag = flag;
344 img->nr++;
348 * "buf" has the file contents to be patched (read from various sources).
349 * attach it to "image" and add line-based index to it.
350 * "image" now owns the "buf".
352 static void prepare_image(struct image *image, char *buf, size_t len,
353 int prepare_linetable)
355 const char *cp, *ep;
357 memset(image, 0, sizeof(*image));
358 image->buf = buf;
359 image->len = len;
361 if (!prepare_linetable)
362 return;
364 ep = image->buf + image->len;
365 cp = image->buf;
366 while (cp < ep) {
367 const char *next;
368 for (next = cp; next < ep && *next != '\n'; next++)
370 if (next < ep)
371 next++;
372 add_line_info(image, cp, next - cp, 0);
373 cp = next;
375 image->line = image->line_allocated;
378 static void clear_image(struct image *image)
380 free(image->buf);
381 free(image->line_allocated);
382 memset(image, 0, sizeof(*image));
385 /* fmt must contain _one_ %s and no other substitution */
386 static void say_patch_name(FILE *output, const char *fmt, struct patch *patch)
388 struct strbuf sb = STRBUF_INIT;
390 if (patch->old_name && patch->new_name &&
391 strcmp(patch->old_name, patch->new_name)) {
392 quote_c_style(patch->old_name, &sb, NULL, 0);
393 strbuf_addstr(&sb, " => ");
394 quote_c_style(patch->new_name, &sb, NULL, 0);
395 } else {
396 const char *n = patch->new_name;
397 if (!n)
398 n = patch->old_name;
399 quote_c_style(n, &sb, NULL, 0);
401 fprintf(output, fmt, sb.buf);
402 fputc('\n', output);
403 strbuf_release(&sb);
406 #define SLOP (16)
408 static void read_patch_file(struct strbuf *sb, int fd)
410 if (strbuf_read(sb, fd, 0) < 0)
411 die_errno("git apply: failed to read");
414 * Make sure that we have some slop in the buffer
415 * so that we can do speculative "memcmp" etc, and
416 * see to it that it is NUL-filled.
418 strbuf_grow(sb, SLOP);
419 memset(sb->buf + sb->len, 0, SLOP);
422 static unsigned long linelen(const char *buffer, unsigned long size)
424 unsigned long len = 0;
425 while (size--) {
426 len++;
427 if (*buffer++ == '\n')
428 break;
430 return len;
433 static int is_dev_null(const char *str)
435 return !memcmp("/dev/null", str, 9) && isspace(str[9]);
438 #define TERM_SPACE 1
439 #define TERM_TAB 2
441 static int name_terminate(const char *name, int namelen, int c, int terminate)
443 if (c == ' ' && !(terminate & TERM_SPACE))
444 return 0;
445 if (c == '\t' && !(terminate & TERM_TAB))
446 return 0;
448 return 1;
451 /* remove double slashes to make --index work with such filenames */
452 static char *squash_slash(char *name)
454 int i = 0, j = 0;
456 if (!name)
457 return NULL;
459 while (name[i]) {
460 if ((name[j++] = name[i++]) == '/')
461 while (name[i] == '/')
462 i++;
464 name[j] = '\0';
465 return name;
468 static char *find_name_gnu(const char *line, const char *def, int p_value)
470 struct strbuf name = STRBUF_INIT;
471 char *cp;
474 * Proposed "new-style" GNU patch/diff format; see
475 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
477 if (unquote_c_style(&name, line, NULL)) {
478 strbuf_release(&name);
479 return NULL;
482 for (cp = name.buf; p_value; p_value--) {
483 cp = strchr(cp, '/');
484 if (!cp) {
485 strbuf_release(&name);
486 return NULL;
488 cp++;
491 strbuf_remove(&name, 0, cp - name.buf);
492 if (root)
493 strbuf_insert(&name, 0, root, root_len);
494 return squash_slash(strbuf_detach(&name, NULL));
497 static size_t sane_tz_len(const char *line, size_t len)
499 const char *tz, *p;
501 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
502 return 0;
503 tz = line + len - strlen(" +0500");
505 if (tz[1] != '+' && tz[1] != '-')
506 return 0;
508 for (p = tz + 2; p != line + len; p++)
509 if (!isdigit(*p))
510 return 0;
512 return line + len - tz;
515 static size_t tz_with_colon_len(const char *line, size_t len)
517 const char *tz, *p;
519 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
520 return 0;
521 tz = line + len - strlen(" +08:00");
523 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
524 return 0;
525 p = tz + 2;
526 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
527 !isdigit(*p++) || !isdigit(*p++))
528 return 0;
530 return line + len - tz;
533 static size_t date_len(const char *line, size_t len)
535 const char *date, *p;
537 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
538 return 0;
539 p = date = line + len - strlen("72-02-05");
541 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
542 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
543 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */
544 return 0;
546 if (date - line >= strlen("19") &&
547 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */
548 date -= strlen("19");
550 return line + len - date;
553 static size_t short_time_len(const char *line, size_t len)
555 const char *time, *p;
557 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
558 return 0;
559 p = time = line + len - strlen(" 07:01:32");
561 /* Permit 1-digit hours? */
562 if (*p++ != ' ' ||
563 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
564 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
565 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */
566 return 0;
568 return line + len - time;
571 static size_t fractional_time_len(const char *line, size_t len)
573 const char *p;
574 size_t n;
576 /* Expected format: 19:41:17.620000023 */
577 if (!len || !isdigit(line[len - 1]))
578 return 0;
579 p = line + len - 1;
581 /* Fractional seconds. */
582 while (p > line && isdigit(*p))
583 p--;
584 if (*p != '.')
585 return 0;
587 /* Hours, minutes, and whole seconds. */
588 n = short_time_len(line, p - line);
589 if (!n)
590 return 0;
592 return line + len - p + n;
595 static size_t trailing_spaces_len(const char *line, size_t len)
597 const char *p;
599 /* Expected format: ' ' x (1 or more) */
600 if (!len || line[len - 1] != ' ')
601 return 0;
603 p = line + len;
604 while (p != line) {
605 p--;
606 if (*p != ' ')
607 return line + len - (p + 1);
610 /* All spaces! */
611 return len;
614 static size_t diff_timestamp_len(const char *line, size_t len)
616 const char *end = line + len;
617 size_t n;
620 * Posix: 2010-07-05 19:41:17
621 * GNU: 2010-07-05 19:41:17.620000023 -0500
624 if (!isdigit(end[-1]))
625 return 0;
627 n = sane_tz_len(line, end - line);
628 if (!n)
629 n = tz_with_colon_len(line, end - line);
630 end -= n;
632 n = short_time_len(line, end - line);
633 if (!n)
634 n = fractional_time_len(line, end - line);
635 end -= n;
637 n = date_len(line, end - line);
638 if (!n) /* No date. Too bad. */
639 return 0;
640 end -= n;
642 if (end == line) /* No space before date. */
643 return 0;
644 if (end[-1] == '\t') { /* Success! */
645 end--;
646 return line + len - end;
648 if (end[-1] != ' ') /* No space before date. */
649 return 0;
651 /* Whitespace damage. */
652 end -= trailing_spaces_len(line, end - line);
653 return line + len - end;
656 static char *null_strdup(const char *s)
658 return s ? xstrdup(s) : NULL;
661 static char *find_name_common(const char *line, const char *def,
662 int p_value, const char *end, int terminate)
664 int len;
665 const char *start = NULL;
667 if (p_value == 0)
668 start = line;
669 while (line != end) {
670 char c = *line;
672 if (!end && isspace(c)) {
673 if (c == '\n')
674 break;
675 if (name_terminate(start, line-start, c, terminate))
676 break;
678 line++;
679 if (c == '/' && !--p_value)
680 start = line;
682 if (!start)
683 return squash_slash(null_strdup(def));
684 len = line - start;
685 if (!len)
686 return squash_slash(null_strdup(def));
689 * Generally we prefer the shorter name, especially
690 * if the other one is just a variation of that with
691 * something else tacked on to the end (ie "file.orig"
692 * or "file~").
694 if (def) {
695 int deflen = strlen(def);
696 if (deflen < len && !strncmp(start, def, deflen))
697 return squash_slash(xstrdup(def));
700 if (root) {
701 char *ret = xmalloc(root_len + len + 1);
702 strcpy(ret, root);
703 memcpy(ret + root_len, start, len);
704 ret[root_len + len] = '\0';
705 return squash_slash(ret);
708 return squash_slash(xmemdupz(start, len));
711 static char *find_name(const char *line, char *def, int p_value, int terminate)
713 if (*line == '"') {
714 char *name = find_name_gnu(line, def, p_value);
715 if (name)
716 return name;
719 return find_name_common(line, def, p_value, NULL, terminate);
722 static char *find_name_traditional(const char *line, char *def, int p_value)
724 size_t len = strlen(line);
725 size_t date_len;
727 if (*line == '"') {
728 char *name = find_name_gnu(line, def, p_value);
729 if (name)
730 return name;
733 len = strchrnul(line, '\n') - line;
734 date_len = diff_timestamp_len(line, len);
735 if (!date_len)
736 return find_name_common(line, def, p_value, NULL, TERM_TAB);
737 len -= date_len;
739 return find_name_common(line, def, p_value, line + len, 0);
742 static int count_slashes(const char *cp)
744 int cnt = 0;
745 char ch;
747 while ((ch = *cp++))
748 if (ch == '/')
749 cnt++;
750 return cnt;
754 * Given the string after "--- " or "+++ ", guess the appropriate
755 * p_value for the given patch.
757 static int guess_p_value(const char *nameline)
759 char *name, *cp;
760 int val = -1;
762 if (is_dev_null(nameline))
763 return -1;
764 name = find_name_traditional(nameline, NULL, 0);
765 if (!name)
766 return -1;
767 cp = strchr(name, '/');
768 if (!cp)
769 val = 0;
770 else if (prefix) {
772 * Does it begin with "a/$our-prefix" and such? Then this is
773 * very likely to apply to our directory.
775 if (!strncmp(name, prefix, prefix_length))
776 val = count_slashes(prefix);
777 else {
778 cp++;
779 if (!strncmp(cp, prefix, prefix_length))
780 val = count_slashes(prefix) + 1;
783 free(name);
784 return val;
788 * Does the ---/+++ line has the POSIX timestamp after the last HT?
789 * GNU diff puts epoch there to signal a creation/deletion event. Is
790 * this such a timestamp?
792 static int has_epoch_timestamp(const char *nameline)
795 * We are only interested in epoch timestamp; any non-zero
796 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
797 * For the same reason, the date must be either 1969-12-31 or
798 * 1970-01-01, and the seconds part must be "00".
800 const char stamp_regexp[] =
801 "^(1969-12-31|1970-01-01)"
803 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
805 "([-+][0-2][0-9]:?[0-5][0-9])\n";
806 const char *timestamp = NULL, *cp, *colon;
807 static regex_t *stamp;
808 regmatch_t m[10];
809 int zoneoffset;
810 int hourminute;
811 int status;
813 for (cp = nameline; *cp != '\n'; cp++) {
814 if (*cp == '\t')
815 timestamp = cp + 1;
817 if (!timestamp)
818 return 0;
819 if (!stamp) {
820 stamp = xmalloc(sizeof(*stamp));
821 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
822 warning(_("Cannot prepare timestamp regexp %s"),
823 stamp_regexp);
824 return 0;
828 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
829 if (status) {
830 if (status != REG_NOMATCH)
831 warning(_("regexec returned %d for input: %s"),
832 status, timestamp);
833 return 0;
836 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
837 if (*colon == ':')
838 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
839 else
840 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
841 if (timestamp[m[3].rm_so] == '-')
842 zoneoffset = -zoneoffset;
845 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
846 * (west of GMT) or 1970-01-01 (east of GMT)
848 if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) ||
849 (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10)))
850 return 0;
852 hourminute = (strtol(timestamp + 11, NULL, 10) * 60 +
853 strtol(timestamp + 14, NULL, 10) -
854 zoneoffset);
856 return ((zoneoffset < 0 && hourminute == 1440) ||
857 (0 <= zoneoffset && !hourminute));
861 * Get the name etc info from the ---/+++ lines of a traditional patch header
863 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
864 * files, we can happily check the index for a match, but for creating a
865 * new file we should try to match whatever "patch" does. I have no idea.
867 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
869 char *name;
871 first += 4; /* skip "--- " */
872 second += 4; /* skip "+++ " */
873 if (!p_value_known) {
874 int p, q;
875 p = guess_p_value(first);
876 q = guess_p_value(second);
877 if (p < 0) p = q;
878 if (0 <= p && p == q) {
879 p_value = p;
880 p_value_known = 1;
883 if (is_dev_null(first)) {
884 patch->is_new = 1;
885 patch->is_delete = 0;
886 name = find_name_traditional(second, NULL, p_value);
887 patch->new_name = name;
888 } else if (is_dev_null(second)) {
889 patch->is_new = 0;
890 patch->is_delete = 1;
891 name = find_name_traditional(first, NULL, p_value);
892 patch->old_name = name;
893 } else {
894 char *first_name;
895 first_name = find_name_traditional(first, NULL, p_value);
896 name = find_name_traditional(second, first_name, p_value);
897 free(first_name);
898 if (has_epoch_timestamp(first)) {
899 patch->is_new = 1;
900 patch->is_delete = 0;
901 patch->new_name = name;
902 } else if (has_epoch_timestamp(second)) {
903 patch->is_new = 0;
904 patch->is_delete = 1;
905 patch->old_name = name;
906 } else {
907 patch->old_name = name;
908 patch->new_name = xstrdup(name);
911 if (!name)
912 die(_("unable to find filename in patch at line %d"), linenr);
915 static int gitdiff_hdrend(const char *line, struct patch *patch)
917 return -1;
921 * We're anal about diff header consistency, to make
922 * sure that we don't end up having strange ambiguous
923 * patches floating around.
925 * As a result, gitdiff_{old|new}name() will check
926 * their names against any previous information, just
927 * to make sure..
929 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
931 if (!orig_name && !isnull)
932 return find_name(line, NULL, p_value, TERM_TAB);
934 if (orig_name) {
935 int len;
936 const char *name;
937 char *another;
938 name = orig_name;
939 len = strlen(name);
940 if (isnull)
941 die(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"), name, linenr);
942 another = find_name(line, NULL, p_value, TERM_TAB);
943 if (!another || memcmp(another, name, len + 1))
944 die(_("git apply: bad git-diff - inconsistent %s filename on line %d"), oldnew, linenr);
945 free(another);
946 return orig_name;
948 else {
949 /* expect "/dev/null" */
950 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
951 die(_("git apply: bad git-diff - expected /dev/null on line %d"), linenr);
952 return NULL;
956 static int gitdiff_oldname(const char *line, struct patch *patch)
958 char *orig = patch->old_name;
959 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
960 if (orig != patch->old_name)
961 free(orig);
962 return 0;
965 static int gitdiff_newname(const char *line, struct patch *patch)
967 char *orig = patch->new_name;
968 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
969 if (orig != patch->new_name)
970 free(orig);
971 return 0;
974 static int gitdiff_oldmode(const char *line, struct patch *patch)
976 patch->old_mode = strtoul(line, NULL, 8);
977 return 0;
980 static int gitdiff_newmode(const char *line, struct patch *patch)
982 patch->new_mode = strtoul(line, NULL, 8);
983 return 0;
986 static int gitdiff_delete(const char *line, struct patch *patch)
988 patch->is_delete = 1;
989 free(patch->old_name);
990 patch->old_name = null_strdup(patch->def_name);
991 return gitdiff_oldmode(line, patch);
994 static int gitdiff_newfile(const char *line, struct patch *patch)
996 patch->is_new = 1;
997 free(patch->new_name);
998 patch->new_name = null_strdup(patch->def_name);
999 return gitdiff_newmode(line, patch);
1002 static int gitdiff_copysrc(const char *line, struct patch *patch)
1004 patch->is_copy = 1;
1005 free(patch->old_name);
1006 patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1007 return 0;
1010 static int gitdiff_copydst(const char *line, struct patch *patch)
1012 patch->is_copy = 1;
1013 free(patch->new_name);
1014 patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1015 return 0;
1018 static int gitdiff_renamesrc(const char *line, struct patch *patch)
1020 patch->is_rename = 1;
1021 free(patch->old_name);
1022 patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1023 return 0;
1026 static int gitdiff_renamedst(const char *line, struct patch *patch)
1028 patch->is_rename = 1;
1029 free(patch->new_name);
1030 patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1031 return 0;
1034 static int gitdiff_similarity(const char *line, struct patch *patch)
1036 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
1037 patch->score = 0;
1038 return 0;
1041 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
1043 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
1044 patch->score = 0;
1045 return 0;
1048 static int gitdiff_index(const char *line, struct patch *patch)
1051 * index line is N hexadecimal, "..", N hexadecimal,
1052 * and optional space with octal mode.
1054 const char *ptr, *eol;
1055 int len;
1057 ptr = strchr(line, '.');
1058 if (!ptr || ptr[1] != '.' || 40 < ptr - line)
1059 return 0;
1060 len = ptr - line;
1061 memcpy(patch->old_sha1_prefix, line, len);
1062 patch->old_sha1_prefix[len] = 0;
1064 line = ptr + 2;
1065 ptr = strchr(line, ' ');
1066 eol = strchr(line, '\n');
1068 if (!ptr || eol < ptr)
1069 ptr = eol;
1070 len = ptr - line;
1072 if (40 < len)
1073 return 0;
1074 memcpy(patch->new_sha1_prefix, line, len);
1075 patch->new_sha1_prefix[len] = 0;
1076 if (*ptr == ' ')
1077 patch->old_mode = strtoul(ptr+1, NULL, 8);
1078 return 0;
1082 * This is normal for a diff that doesn't change anything: we'll fall through
1083 * into the next diff. Tell the parser to break out.
1085 static int gitdiff_unrecognized(const char *line, struct patch *patch)
1087 return -1;
1090 static const char *stop_at_slash(const char *line, int llen)
1092 int nslash = p_value;
1093 int i;
1095 for (i = 0; i < llen; i++) {
1096 int ch = line[i];
1097 if (ch == '/' && --nslash <= 0)
1098 return &line[i];
1100 return NULL;
1104 * This is to extract the same name that appears on "diff --git"
1105 * line. We do not find and return anything if it is a rename
1106 * patch, and it is OK because we will find the name elsewhere.
1107 * We need to reliably find name only when it is mode-change only,
1108 * creation or deletion of an empty file. In any of these cases,
1109 * both sides are the same name under a/ and b/ respectively.
1111 static char *git_header_name(const char *line, int llen)
1113 const char *name;
1114 const char *second = NULL;
1115 size_t len, line_len;
1117 line += strlen("diff --git ");
1118 llen -= strlen("diff --git ");
1120 if (*line == '"') {
1121 const char *cp;
1122 struct strbuf first = STRBUF_INIT;
1123 struct strbuf sp = STRBUF_INIT;
1125 if (unquote_c_style(&first, line, &second))
1126 goto free_and_fail1;
1128 /* advance to the first slash */
1129 cp = stop_at_slash(first.buf, first.len);
1130 /* we do not accept absolute paths */
1131 if (!cp || cp == first.buf)
1132 goto free_and_fail1;
1133 strbuf_remove(&first, 0, cp + 1 - first.buf);
1136 * second points at one past closing dq of name.
1137 * find the second name.
1139 while ((second < line + llen) && isspace(*second))
1140 second++;
1142 if (line + llen <= second)
1143 goto free_and_fail1;
1144 if (*second == '"') {
1145 if (unquote_c_style(&sp, second, NULL))
1146 goto free_and_fail1;
1147 cp = stop_at_slash(sp.buf, sp.len);
1148 if (!cp || cp == sp.buf)
1149 goto free_and_fail1;
1150 /* They must match, otherwise ignore */
1151 if (strcmp(cp + 1, first.buf))
1152 goto free_and_fail1;
1153 strbuf_release(&sp);
1154 return strbuf_detach(&first, NULL);
1157 /* unquoted second */
1158 cp = stop_at_slash(second, line + llen - second);
1159 if (!cp || cp == second)
1160 goto free_and_fail1;
1161 cp++;
1162 if (line + llen - cp != first.len + 1 ||
1163 memcmp(first.buf, cp, first.len))
1164 goto free_and_fail1;
1165 return strbuf_detach(&first, NULL);
1167 free_and_fail1:
1168 strbuf_release(&first);
1169 strbuf_release(&sp);
1170 return NULL;
1173 /* unquoted first name */
1174 name = stop_at_slash(line, llen);
1175 if (!name || name == line)
1176 return NULL;
1177 name++;
1180 * since the first name is unquoted, a dq if exists must be
1181 * the beginning of the second name.
1183 for (second = name; second < line + llen; second++) {
1184 if (*second == '"') {
1185 struct strbuf sp = STRBUF_INIT;
1186 const char *np;
1188 if (unquote_c_style(&sp, second, NULL))
1189 goto free_and_fail2;
1191 np = stop_at_slash(sp.buf, sp.len);
1192 if (!np || np == sp.buf)
1193 goto free_and_fail2;
1194 np++;
1196 len = sp.buf + sp.len - np;
1197 if (len < second - name &&
1198 !strncmp(np, name, len) &&
1199 isspace(name[len])) {
1200 /* Good */
1201 strbuf_remove(&sp, 0, np - sp.buf);
1202 return strbuf_detach(&sp, NULL);
1205 free_and_fail2:
1206 strbuf_release(&sp);
1207 return NULL;
1212 * Accept a name only if it shows up twice, exactly the same
1213 * form.
1215 second = strchr(name, '\n');
1216 if (!second)
1217 return NULL;
1218 line_len = second - name;
1219 for (len = 0 ; ; len++) {
1220 switch (name[len]) {
1221 default:
1222 continue;
1223 case '\n':
1224 return NULL;
1225 case '\t': case ' ':
1226 second = stop_at_slash(name + len, line_len - len);
1227 if (!second)
1228 return NULL;
1229 second++;
1230 if (second[len] == '\n' && !strncmp(name, second, len)) {
1231 return xmemdupz(name, len);
1237 /* Verify that we recognize the lines following a git header */
1238 static int parse_git_header(const char *line, int len, unsigned int size, struct patch *patch)
1240 unsigned long offset;
1242 /* A git diff has explicit new/delete information, so we don't guess */
1243 patch->is_new = 0;
1244 patch->is_delete = 0;
1247 * Some things may not have the old name in the
1248 * rest of the headers anywhere (pure mode changes,
1249 * or removing or adding empty files), so we get
1250 * the default name from the header.
1252 patch->def_name = git_header_name(line, len);
1253 if (patch->def_name && root) {
1254 char *s = xmalloc(root_len + strlen(patch->def_name) + 1);
1255 strcpy(s, root);
1256 strcpy(s + root_len, patch->def_name);
1257 free(patch->def_name);
1258 patch->def_name = s;
1261 line += len;
1262 size -= len;
1263 linenr++;
1264 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
1265 static const struct opentry {
1266 const char *str;
1267 int (*fn)(const char *, struct patch *);
1268 } optable[] = {
1269 { "@@ -", gitdiff_hdrend },
1270 { "--- ", gitdiff_oldname },
1271 { "+++ ", gitdiff_newname },
1272 { "old mode ", gitdiff_oldmode },
1273 { "new mode ", gitdiff_newmode },
1274 { "deleted file mode ", gitdiff_delete },
1275 { "new file mode ", gitdiff_newfile },
1276 { "copy from ", gitdiff_copysrc },
1277 { "copy to ", gitdiff_copydst },
1278 { "rename old ", gitdiff_renamesrc },
1279 { "rename new ", gitdiff_renamedst },
1280 { "rename from ", gitdiff_renamesrc },
1281 { "rename to ", gitdiff_renamedst },
1282 { "similarity index ", gitdiff_similarity },
1283 { "dissimilarity index ", gitdiff_dissimilarity },
1284 { "index ", gitdiff_index },
1285 { "", gitdiff_unrecognized },
1287 int i;
1289 len = linelen(line, size);
1290 if (!len || line[len-1] != '\n')
1291 break;
1292 for (i = 0; i < ARRAY_SIZE(optable); i++) {
1293 const struct opentry *p = optable + i;
1294 int oplen = strlen(p->str);
1295 if (len < oplen || memcmp(p->str, line, oplen))
1296 continue;
1297 if (p->fn(line + oplen, patch) < 0)
1298 return offset;
1299 break;
1303 return offset;
1306 static int parse_num(const char *line, unsigned long *p)
1308 char *ptr;
1310 if (!isdigit(*line))
1311 return 0;
1312 *p = strtoul(line, &ptr, 10);
1313 return ptr - line;
1316 static int parse_range(const char *line, int len, int offset, const char *expect,
1317 unsigned long *p1, unsigned long *p2)
1319 int digits, ex;
1321 if (offset < 0 || offset >= len)
1322 return -1;
1323 line += offset;
1324 len -= offset;
1326 digits = parse_num(line, p1);
1327 if (!digits)
1328 return -1;
1330 offset += digits;
1331 line += digits;
1332 len -= digits;
1334 *p2 = 1;
1335 if (*line == ',') {
1336 digits = parse_num(line+1, p2);
1337 if (!digits)
1338 return -1;
1340 offset += digits+1;
1341 line += digits+1;
1342 len -= digits+1;
1345 ex = strlen(expect);
1346 if (ex > len)
1347 return -1;
1348 if (memcmp(line, expect, ex))
1349 return -1;
1351 return offset + ex;
1354 static void recount_diff(const char *line, int size, struct fragment *fragment)
1356 int oldlines = 0, newlines = 0, ret = 0;
1358 if (size < 1) {
1359 warning("recount: ignore empty hunk");
1360 return;
1363 for (;;) {
1364 int len = linelen(line, size);
1365 size -= len;
1366 line += len;
1368 if (size < 1)
1369 break;
1371 switch (*line) {
1372 case ' ': case '\n':
1373 newlines++;
1374 /* fall through */
1375 case '-':
1376 oldlines++;
1377 continue;
1378 case '+':
1379 newlines++;
1380 continue;
1381 case '\\':
1382 continue;
1383 case '@':
1384 ret = size < 3 || prefixcmp(line, "@@ ");
1385 break;
1386 case 'd':
1387 ret = size < 5 || prefixcmp(line, "diff ");
1388 break;
1389 default:
1390 ret = -1;
1391 break;
1393 if (ret) {
1394 warning(_("recount: unexpected line: %.*s"),
1395 (int)linelen(line, size), line);
1396 return;
1398 break;
1400 fragment->oldlines = oldlines;
1401 fragment->newlines = newlines;
1405 * Parse a unified diff fragment header of the
1406 * form "@@ -a,b +c,d @@"
1408 static int parse_fragment_header(const char *line, int len, struct fragment *fragment)
1410 int offset;
1412 if (!len || line[len-1] != '\n')
1413 return -1;
1415 /* Figure out the number of lines in a fragment */
1416 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1417 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1419 return offset;
1422 static int find_header(const char *line, unsigned long size, int *hdrsize, struct patch *patch)
1424 unsigned long offset, len;
1426 patch->is_toplevel_relative = 0;
1427 patch->is_rename = patch->is_copy = 0;
1428 patch->is_new = patch->is_delete = -1;
1429 patch->old_mode = patch->new_mode = 0;
1430 patch->old_name = patch->new_name = NULL;
1431 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
1432 unsigned long nextlen;
1434 len = linelen(line, size);
1435 if (!len)
1436 break;
1438 /* Testing this early allows us to take a few shortcuts.. */
1439 if (len < 6)
1440 continue;
1443 * Make sure we don't find any unconnected patch fragments.
1444 * That's a sign that we didn't find a header, and that a
1445 * patch has become corrupted/broken up.
1447 if (!memcmp("@@ -", line, 4)) {
1448 struct fragment dummy;
1449 if (parse_fragment_header(line, len, &dummy) < 0)
1450 continue;
1451 die(_("patch fragment without header at line %d: %.*s"),
1452 linenr, (int)len-1, line);
1455 if (size < len + 6)
1456 break;
1459 * Git patch? It might not have a real patch, just a rename
1460 * or mode change, so we handle that specially
1462 if (!memcmp("diff --git ", line, 11)) {
1463 int git_hdr_len = parse_git_header(line, len, size, patch);
1464 if (git_hdr_len <= len)
1465 continue;
1466 if (!patch->old_name && !patch->new_name) {
1467 if (!patch->def_name)
1468 die(Q_("git diff header lacks filename information when removing "
1469 "%d leading pathname component (line %d)",
1470 "git diff header lacks filename information when removing "
1471 "%d leading pathname components (line %d)",
1472 p_value),
1473 p_value, linenr);
1474 patch->old_name = xstrdup(patch->def_name);
1475 patch->new_name = xstrdup(patch->def_name);
1477 if (!patch->is_delete && !patch->new_name)
1478 die("git diff header lacks filename information "
1479 "(line %d)", linenr);
1480 patch->is_toplevel_relative = 1;
1481 *hdrsize = git_hdr_len;
1482 return offset;
1485 /* --- followed by +++ ? */
1486 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1487 continue;
1490 * We only accept unified patches, so we want it to
1491 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1492 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1494 nextlen = linelen(line + len, size - len);
1495 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1496 continue;
1498 /* Ok, we'll consider it a patch */
1499 parse_traditional_patch(line, line+len, patch);
1500 *hdrsize = len + nextlen;
1501 linenr += 2;
1502 return offset;
1504 return -1;
1507 static void record_ws_error(unsigned result, const char *line, int len, int linenr)
1509 char *err;
1511 if (!result)
1512 return;
1514 whitespace_error++;
1515 if (squelch_whitespace_errors &&
1516 squelch_whitespace_errors < whitespace_error)
1517 return;
1519 err = whitespace_error_string(result);
1520 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1521 patch_input_file, linenr, err, len, line);
1522 free(err);
1525 static void check_whitespace(const char *line, int len, unsigned ws_rule)
1527 unsigned result = ws_check(line + 1, len - 1, ws_rule);
1529 record_ws_error(result, line + 1, len - 2, linenr);
1533 * Parse a unified diff. Note that this really needs to parse each
1534 * fragment separately, since the only way to know the difference
1535 * between a "---" that is part of a patch, and a "---" that starts
1536 * the next patch is to look at the line counts..
1538 static int parse_fragment(const char *line, unsigned long size,
1539 struct patch *patch, struct fragment *fragment)
1541 int added, deleted;
1542 int len = linelen(line, size), offset;
1543 unsigned long oldlines, newlines;
1544 unsigned long leading, trailing;
1546 offset = parse_fragment_header(line, len, fragment);
1547 if (offset < 0)
1548 return -1;
1549 if (offset > 0 && patch->recount)
1550 recount_diff(line + offset, size - offset, fragment);
1551 oldlines = fragment->oldlines;
1552 newlines = fragment->newlines;
1553 leading = 0;
1554 trailing = 0;
1556 /* Parse the thing.. */
1557 line += len;
1558 size -= len;
1559 linenr++;
1560 added = deleted = 0;
1561 for (offset = len;
1562 0 < size;
1563 offset += len, size -= len, line += len, linenr++) {
1564 if (!oldlines && !newlines)
1565 break;
1566 len = linelen(line, size);
1567 if (!len || line[len-1] != '\n')
1568 return -1;
1569 switch (*line) {
1570 default:
1571 return -1;
1572 case '\n': /* newer GNU diff, an empty context line */
1573 case ' ':
1574 oldlines--;
1575 newlines--;
1576 if (!deleted && !added)
1577 leading++;
1578 trailing++;
1579 break;
1580 case '-':
1581 if (apply_in_reverse &&
1582 ws_error_action != nowarn_ws_error)
1583 check_whitespace(line, len, patch->ws_rule);
1584 deleted++;
1585 oldlines--;
1586 trailing = 0;
1587 break;
1588 case '+':
1589 if (!apply_in_reverse &&
1590 ws_error_action != nowarn_ws_error)
1591 check_whitespace(line, len, patch->ws_rule);
1592 added++;
1593 newlines--;
1594 trailing = 0;
1595 break;
1598 * We allow "\ No newline at end of file". Depending
1599 * on locale settings when the patch was produced we
1600 * don't know what this line looks like. The only
1601 * thing we do know is that it begins with "\ ".
1602 * Checking for 12 is just for sanity check -- any
1603 * l10n of "\ No newline..." is at least that long.
1605 case '\\':
1606 if (len < 12 || memcmp(line, "\\ ", 2))
1607 return -1;
1608 break;
1611 if (oldlines || newlines)
1612 return -1;
1613 fragment->leading = leading;
1614 fragment->trailing = trailing;
1617 * If a fragment ends with an incomplete line, we failed to include
1618 * it in the above loop because we hit oldlines == newlines == 0
1619 * before seeing it.
1621 if (12 < size && !memcmp(line, "\\ ", 2))
1622 offset += linelen(line, size);
1624 patch->lines_added += added;
1625 patch->lines_deleted += deleted;
1627 if (0 < patch->is_new && oldlines)
1628 return error(_("new file depends on old contents"));
1629 if (0 < patch->is_delete && newlines)
1630 return error(_("deleted file still has contents"));
1631 return offset;
1635 * We have seen "diff --git a/... b/..." header (or a traditional patch
1636 * header). Read hunks that belong to this patch into fragments and hang
1637 * them to the given patch structure.
1639 * The (fragment->patch, fragment->size) pair points into the memory given
1640 * by the caller, not a copy, when we return.
1642 static int parse_single_patch(const char *line, unsigned long size, struct patch *patch)
1644 unsigned long offset = 0;
1645 unsigned long oldlines = 0, newlines = 0, context = 0;
1646 struct fragment **fragp = &patch->fragments;
1648 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1649 struct fragment *fragment;
1650 int len;
1652 fragment = xcalloc(1, sizeof(*fragment));
1653 fragment->linenr = linenr;
1654 len = parse_fragment(line, size, patch, fragment);
1655 if (len <= 0)
1656 die(_("corrupt patch at line %d"), linenr);
1657 fragment->patch = line;
1658 fragment->size = len;
1659 oldlines += fragment->oldlines;
1660 newlines += fragment->newlines;
1661 context += fragment->leading + fragment->trailing;
1663 *fragp = fragment;
1664 fragp = &fragment->next;
1666 offset += len;
1667 line += len;
1668 size -= len;
1672 * If something was removed (i.e. we have old-lines) it cannot
1673 * be creation, and if something was added it cannot be
1674 * deletion. However, the reverse is not true; --unified=0
1675 * patches that only add are not necessarily creation even
1676 * though they do not have any old lines, and ones that only
1677 * delete are not necessarily deletion.
1679 * Unfortunately, a real creation/deletion patch do _not_ have
1680 * any context line by definition, so we cannot safely tell it
1681 * apart with --unified=0 insanity. At least if the patch has
1682 * more than one hunk it is not creation or deletion.
1684 if (patch->is_new < 0 &&
1685 (oldlines || (patch->fragments && patch->fragments->next)))
1686 patch->is_new = 0;
1687 if (patch->is_delete < 0 &&
1688 (newlines || (patch->fragments && patch->fragments->next)))
1689 patch->is_delete = 0;
1691 if (0 < patch->is_new && oldlines)
1692 die(_("new file %s depends on old contents"), patch->new_name);
1693 if (0 < patch->is_delete && newlines)
1694 die(_("deleted file %s still has contents"), patch->old_name);
1695 if (!patch->is_delete && !newlines && context)
1696 fprintf_ln(stderr,
1697 _("** warning: "
1698 "file %s becomes empty but is not deleted"),
1699 patch->new_name);
1701 return offset;
1704 static inline int metadata_changes(struct patch *patch)
1706 return patch->is_rename > 0 ||
1707 patch->is_copy > 0 ||
1708 patch->is_new > 0 ||
1709 patch->is_delete ||
1710 (patch->old_mode && patch->new_mode &&
1711 patch->old_mode != patch->new_mode);
1714 static char *inflate_it(const void *data, unsigned long size,
1715 unsigned long inflated_size)
1717 git_zstream stream;
1718 void *out;
1719 int st;
1721 memset(&stream, 0, sizeof(stream));
1723 stream.next_in = (unsigned char *)data;
1724 stream.avail_in = size;
1725 stream.next_out = out = xmalloc(inflated_size);
1726 stream.avail_out = inflated_size;
1727 git_inflate_init(&stream);
1728 st = git_inflate(&stream, Z_FINISH);
1729 git_inflate_end(&stream);
1730 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1731 free(out);
1732 return NULL;
1734 return out;
1738 * Read a binary hunk and return a new fragment; fragment->patch
1739 * points at an allocated memory that the caller must free, so
1740 * it is marked as "->free_patch = 1".
1742 static struct fragment *parse_binary_hunk(char **buf_p,
1743 unsigned long *sz_p,
1744 int *status_p,
1745 int *used_p)
1748 * Expect a line that begins with binary patch method ("literal"
1749 * or "delta"), followed by the length of data before deflating.
1750 * a sequence of 'length-byte' followed by base-85 encoded data
1751 * should follow, terminated by a newline.
1753 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1754 * and we would limit the patch line to 66 characters,
1755 * so one line can fit up to 13 groups that would decode
1756 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1757 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1759 int llen, used;
1760 unsigned long size = *sz_p;
1761 char *buffer = *buf_p;
1762 int patch_method;
1763 unsigned long origlen;
1764 char *data = NULL;
1765 int hunk_size = 0;
1766 struct fragment *frag;
1768 llen = linelen(buffer, size);
1769 used = llen;
1771 *status_p = 0;
1773 if (!prefixcmp(buffer, "delta ")) {
1774 patch_method = BINARY_DELTA_DEFLATED;
1775 origlen = strtoul(buffer + 6, NULL, 10);
1777 else if (!prefixcmp(buffer, "literal ")) {
1778 patch_method = BINARY_LITERAL_DEFLATED;
1779 origlen = strtoul(buffer + 8, NULL, 10);
1781 else
1782 return NULL;
1784 linenr++;
1785 buffer += llen;
1786 while (1) {
1787 int byte_length, max_byte_length, newsize;
1788 llen = linelen(buffer, size);
1789 used += llen;
1790 linenr++;
1791 if (llen == 1) {
1792 /* consume the blank line */
1793 buffer++;
1794 size--;
1795 break;
1798 * Minimum line is "A00000\n" which is 7-byte long,
1799 * and the line length must be multiple of 5 plus 2.
1801 if ((llen < 7) || (llen-2) % 5)
1802 goto corrupt;
1803 max_byte_length = (llen - 2) / 5 * 4;
1804 byte_length = *buffer;
1805 if ('A' <= byte_length && byte_length <= 'Z')
1806 byte_length = byte_length - 'A' + 1;
1807 else if ('a' <= byte_length && byte_length <= 'z')
1808 byte_length = byte_length - 'a' + 27;
1809 else
1810 goto corrupt;
1811 /* if the input length was not multiple of 4, we would
1812 * have filler at the end but the filler should never
1813 * exceed 3 bytes
1815 if (max_byte_length < byte_length ||
1816 byte_length <= max_byte_length - 4)
1817 goto corrupt;
1818 newsize = hunk_size + byte_length;
1819 data = xrealloc(data, newsize);
1820 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1821 goto corrupt;
1822 hunk_size = newsize;
1823 buffer += llen;
1824 size -= llen;
1827 frag = xcalloc(1, sizeof(*frag));
1828 frag->patch = inflate_it(data, hunk_size, origlen);
1829 frag->free_patch = 1;
1830 if (!frag->patch)
1831 goto corrupt;
1832 free(data);
1833 frag->size = origlen;
1834 *buf_p = buffer;
1835 *sz_p = size;
1836 *used_p = used;
1837 frag->binary_patch_method = patch_method;
1838 return frag;
1840 corrupt:
1841 free(data);
1842 *status_p = -1;
1843 error(_("corrupt binary patch at line %d: %.*s"),
1844 linenr-1, llen-1, buffer);
1845 return NULL;
1848 static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1851 * We have read "GIT binary patch\n"; what follows is a line
1852 * that says the patch method (currently, either "literal" or
1853 * "delta") and the length of data before deflating; a
1854 * sequence of 'length-byte' followed by base-85 encoded data
1855 * follows.
1857 * When a binary patch is reversible, there is another binary
1858 * hunk in the same format, starting with patch method (either
1859 * "literal" or "delta") with the length of data, and a sequence
1860 * of length-byte + base-85 encoded data, terminated with another
1861 * empty line. This data, when applied to the postimage, produces
1862 * the preimage.
1864 struct fragment *forward;
1865 struct fragment *reverse;
1866 int status;
1867 int used, used_1;
1869 forward = parse_binary_hunk(&buffer, &size, &status, &used);
1870 if (!forward && !status)
1871 /* there has to be one hunk (forward hunk) */
1872 return error(_("unrecognized binary patch at line %d"), linenr-1);
1873 if (status)
1874 /* otherwise we already gave an error message */
1875 return status;
1877 reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1878 if (reverse)
1879 used += used_1;
1880 else if (status) {
1882 * Not having reverse hunk is not an error, but having
1883 * a corrupt reverse hunk is.
1885 free((void*) forward->patch);
1886 free(forward);
1887 return status;
1889 forward->next = reverse;
1890 patch->fragments = forward;
1891 patch->is_binary = 1;
1892 return used;
1896 * Read the patch text in "buffer" taht extends for "size" bytes; stop
1897 * reading after seeing a single patch (i.e. changes to a single file).
1898 * Create fragments (i.e. patch hunks) and hang them to the given patch.
1899 * Return the number of bytes consumed, so that the caller can call us
1900 * again for the next patch.
1902 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
1904 int hdrsize, patchsize;
1905 int offset = find_header(buffer, size, &hdrsize, patch);
1907 if (offset < 0)
1908 return offset;
1910 patch->ws_rule = whitespace_rule(patch->new_name
1911 ? patch->new_name
1912 : patch->old_name);
1914 patchsize = parse_single_patch(buffer + offset + hdrsize,
1915 size - offset - hdrsize, patch);
1917 if (!patchsize) {
1918 static const char *binhdr[] = {
1919 "Binary files ",
1920 "Files ",
1921 NULL,
1923 static const char git_binary[] = "GIT binary patch\n";
1924 int i;
1925 int hd = hdrsize + offset;
1926 unsigned long llen = linelen(buffer + hd, size - hd);
1928 if (llen == sizeof(git_binary) - 1 &&
1929 !memcmp(git_binary, buffer + hd, llen)) {
1930 int used;
1931 linenr++;
1932 used = parse_binary(buffer + hd + llen,
1933 size - hd - llen, patch);
1934 if (used)
1935 patchsize = used + llen;
1936 else
1937 patchsize = 0;
1939 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
1940 for (i = 0; binhdr[i]; i++) {
1941 int len = strlen(binhdr[i]);
1942 if (len < size - hd &&
1943 !memcmp(binhdr[i], buffer + hd, len)) {
1944 linenr++;
1945 patch->is_binary = 1;
1946 patchsize = llen;
1947 break;
1952 /* Empty patch cannot be applied if it is a text patch
1953 * without metadata change. A binary patch appears
1954 * empty to us here.
1956 if ((apply || check) &&
1957 (!patch->is_binary && !metadata_changes(patch)))
1958 die(_("patch with only garbage at line %d"), linenr);
1961 return offset + hdrsize + patchsize;
1964 #define swap(a,b) myswap((a),(b),sizeof(a))
1966 #define myswap(a, b, size) do { \
1967 unsigned char mytmp[size]; \
1968 memcpy(mytmp, &a, size); \
1969 memcpy(&a, &b, size); \
1970 memcpy(&b, mytmp, size); \
1971 } while (0)
1973 static void reverse_patches(struct patch *p)
1975 for (; p; p = p->next) {
1976 struct fragment *frag = p->fragments;
1978 swap(p->new_name, p->old_name);
1979 swap(p->new_mode, p->old_mode);
1980 swap(p->is_new, p->is_delete);
1981 swap(p->lines_added, p->lines_deleted);
1982 swap(p->old_sha1_prefix, p->new_sha1_prefix);
1984 for (; frag; frag = frag->next) {
1985 swap(frag->newpos, frag->oldpos);
1986 swap(frag->newlines, frag->oldlines);
1991 static const char pluses[] =
1992 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1993 static const char minuses[]=
1994 "----------------------------------------------------------------------";
1996 static void show_stats(struct patch *patch)
1998 struct strbuf qname = STRBUF_INIT;
1999 char *cp = patch->new_name ? patch->new_name : patch->old_name;
2000 int max, add, del;
2002 quote_c_style(cp, &qname, NULL, 0);
2005 * "scale" the filename
2007 max = max_len;
2008 if (max > 50)
2009 max = 50;
2011 if (qname.len > max) {
2012 cp = strchr(qname.buf + qname.len + 3 - max, '/');
2013 if (!cp)
2014 cp = qname.buf + qname.len + 3 - max;
2015 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
2018 if (patch->is_binary) {
2019 printf(" %-*s | Bin\n", max, qname.buf);
2020 strbuf_release(&qname);
2021 return;
2024 printf(" %-*s |", max, qname.buf);
2025 strbuf_release(&qname);
2028 * scale the add/delete
2030 max = max + max_change > 70 ? 70 - max : max_change;
2031 add = patch->lines_added;
2032 del = patch->lines_deleted;
2034 if (max_change > 0) {
2035 int total = ((add + del) * max + max_change / 2) / max_change;
2036 add = (add * max + max_change / 2) / max_change;
2037 del = total - add;
2039 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
2040 add, pluses, del, minuses);
2043 static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
2045 switch (st->st_mode & S_IFMT) {
2046 case S_IFLNK:
2047 if (strbuf_readlink(buf, path, st->st_size) < 0)
2048 return error(_("unable to read symlink %s"), path);
2049 return 0;
2050 case S_IFREG:
2051 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
2052 return error(_("unable to open or read %s"), path);
2053 convert_to_git(path, buf->buf, buf->len, buf, 0);
2054 return 0;
2055 default:
2056 return -1;
2061 * Update the preimage, and the common lines in postimage,
2062 * from buffer buf of length len. If postlen is 0 the postimage
2063 * is updated in place, otherwise it's updated on a new buffer
2064 * of length postlen
2067 static void update_pre_post_images(struct image *preimage,
2068 struct image *postimage,
2069 char *buf,
2070 size_t len, size_t postlen)
2072 int i, ctx;
2073 char *new, *old, *fixed;
2074 struct image fixed_preimage;
2077 * Update the preimage with whitespace fixes. Note that we
2078 * are not losing preimage->buf -- apply_one_fragment() will
2079 * free "oldlines".
2081 prepare_image(&fixed_preimage, buf, len, 1);
2082 assert(fixed_preimage.nr == preimage->nr);
2083 for (i = 0; i < preimage->nr; i++)
2084 fixed_preimage.line[i].flag = preimage->line[i].flag;
2085 free(preimage->line_allocated);
2086 *preimage = fixed_preimage;
2089 * Adjust the common context lines in postimage. This can be
2090 * done in-place when we are just doing whitespace fixing,
2091 * which does not make the string grow, but needs a new buffer
2092 * when ignoring whitespace causes the update, since in this case
2093 * we could have e.g. tabs converted to multiple spaces.
2094 * We trust the caller to tell us if the update can be done
2095 * in place (postlen==0) or not.
2097 old = postimage->buf;
2098 if (postlen)
2099 new = postimage->buf = xmalloc(postlen);
2100 else
2101 new = old;
2102 fixed = preimage->buf;
2103 for (i = ctx = 0; i < postimage->nr; i++) {
2104 size_t len = postimage->line[i].len;
2105 if (!(postimage->line[i].flag & LINE_COMMON)) {
2106 /* an added line -- no counterparts in preimage */
2107 memmove(new, old, len);
2108 old += len;
2109 new += len;
2110 continue;
2113 /* a common context -- skip it in the original postimage */
2114 old += len;
2116 /* and find the corresponding one in the fixed preimage */
2117 while (ctx < preimage->nr &&
2118 !(preimage->line[ctx].flag & LINE_COMMON)) {
2119 fixed += preimage->line[ctx].len;
2120 ctx++;
2122 if (preimage->nr <= ctx)
2123 die(_("oops"));
2125 /* and copy it in, while fixing the line length */
2126 len = preimage->line[ctx].len;
2127 memcpy(new, fixed, len);
2128 new += len;
2129 fixed += len;
2130 postimage->line[i].len = len;
2131 ctx++;
2134 /* Fix the length of the whole thing */
2135 postimage->len = new - postimage->buf;
2138 static int match_fragment(struct image *img,
2139 struct image *preimage,
2140 struct image *postimage,
2141 unsigned long try,
2142 int try_lno,
2143 unsigned ws_rule,
2144 int match_beginning, int match_end)
2146 int i;
2147 char *fixed_buf, *buf, *orig, *target;
2148 struct strbuf fixed;
2149 size_t fixed_len;
2150 int preimage_limit;
2152 if (preimage->nr + try_lno <= img->nr) {
2154 * The hunk falls within the boundaries of img.
2156 preimage_limit = preimage->nr;
2157 if (match_end && (preimage->nr + try_lno != img->nr))
2158 return 0;
2159 } else if (ws_error_action == correct_ws_error &&
2160 (ws_rule & WS_BLANK_AT_EOF)) {
2162 * This hunk extends beyond the end of img, and we are
2163 * removing blank lines at the end of the file. This
2164 * many lines from the beginning of the preimage must
2165 * match with img, and the remainder of the preimage
2166 * must be blank.
2168 preimage_limit = img->nr - try_lno;
2169 } else {
2171 * The hunk extends beyond the end of the img and
2172 * we are not removing blanks at the end, so we
2173 * should reject the hunk at this position.
2175 return 0;
2178 if (match_beginning && try_lno)
2179 return 0;
2181 /* Quick hash check */
2182 for (i = 0; i < preimage_limit; i++)
2183 if ((img->line[try_lno + i].flag & LINE_PATCHED) ||
2184 (preimage->line[i].hash != img->line[try_lno + i].hash))
2185 return 0;
2187 if (preimage_limit == preimage->nr) {
2189 * Do we have an exact match? If we were told to match
2190 * at the end, size must be exactly at try+fragsize,
2191 * otherwise try+fragsize must be still within the preimage,
2192 * and either case, the old piece should match the preimage
2193 * exactly.
2195 if ((match_end
2196 ? (try + preimage->len == img->len)
2197 : (try + preimage->len <= img->len)) &&
2198 !memcmp(img->buf + try, preimage->buf, preimage->len))
2199 return 1;
2200 } else {
2202 * The preimage extends beyond the end of img, so
2203 * there cannot be an exact match.
2205 * There must be one non-blank context line that match
2206 * a line before the end of img.
2208 char *buf_end;
2210 buf = preimage->buf;
2211 buf_end = buf;
2212 for (i = 0; i < preimage_limit; i++)
2213 buf_end += preimage->line[i].len;
2215 for ( ; buf < buf_end; buf++)
2216 if (!isspace(*buf))
2217 break;
2218 if (buf == buf_end)
2219 return 0;
2223 * No exact match. If we are ignoring whitespace, run a line-by-line
2224 * fuzzy matching. We collect all the line length information because
2225 * we need it to adjust whitespace if we match.
2227 if (ws_ignore_action == ignore_ws_change) {
2228 size_t imgoff = 0;
2229 size_t preoff = 0;
2230 size_t postlen = postimage->len;
2231 size_t extra_chars;
2232 char *preimage_eof;
2233 char *preimage_end;
2234 for (i = 0; i < preimage_limit; i++) {
2235 size_t prelen = preimage->line[i].len;
2236 size_t imglen = img->line[try_lno+i].len;
2238 if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,
2239 preimage->buf + preoff, prelen))
2240 return 0;
2241 if (preimage->line[i].flag & LINE_COMMON)
2242 postlen += imglen - prelen;
2243 imgoff += imglen;
2244 preoff += prelen;
2248 * Ok, the preimage matches with whitespace fuzz.
2250 * imgoff now holds the true length of the target that
2251 * matches the preimage before the end of the file.
2253 * Count the number of characters in the preimage that fall
2254 * beyond the end of the file and make sure that all of them
2255 * are whitespace characters. (This can only happen if
2256 * we are removing blank lines at the end of the file.)
2258 buf = preimage_eof = preimage->buf + preoff;
2259 for ( ; i < preimage->nr; i++)
2260 preoff += preimage->line[i].len;
2261 preimage_end = preimage->buf + preoff;
2262 for ( ; buf < preimage_end; buf++)
2263 if (!isspace(*buf))
2264 return 0;
2267 * Update the preimage and the common postimage context
2268 * lines to use the same whitespace as the target.
2269 * If whitespace is missing in the target (i.e.
2270 * if the preimage extends beyond the end of the file),
2271 * use the whitespace from the preimage.
2273 extra_chars = preimage_end - preimage_eof;
2274 strbuf_init(&fixed, imgoff + extra_chars);
2275 strbuf_add(&fixed, img->buf + try, imgoff);
2276 strbuf_add(&fixed, preimage_eof, extra_chars);
2277 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2278 update_pre_post_images(preimage, postimage,
2279 fixed_buf, fixed_len, postlen);
2280 return 1;
2283 if (ws_error_action != correct_ws_error)
2284 return 0;
2287 * The hunk does not apply byte-by-byte, but the hash says
2288 * it might with whitespace fuzz. We haven't been asked to
2289 * ignore whitespace, we were asked to correct whitespace
2290 * errors, so let's try matching after whitespace correction.
2292 * The preimage may extend beyond the end of the file,
2293 * but in this loop we will only handle the part of the
2294 * preimage that falls within the file.
2296 strbuf_init(&fixed, preimage->len + 1);
2297 orig = preimage->buf;
2298 target = img->buf + try;
2299 for (i = 0; i < preimage_limit; i++) {
2300 size_t oldlen = preimage->line[i].len;
2301 size_t tgtlen = img->line[try_lno + i].len;
2302 size_t fixstart = fixed.len;
2303 struct strbuf tgtfix;
2304 int match;
2306 /* Try fixing the line in the preimage */
2307 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2309 /* Try fixing the line in the target */
2310 strbuf_init(&tgtfix, tgtlen);
2311 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2314 * If they match, either the preimage was based on
2315 * a version before our tree fixed whitespace breakage,
2316 * or we are lacking a whitespace-fix patch the tree
2317 * the preimage was based on already had (i.e. target
2318 * has whitespace breakage, the preimage doesn't).
2319 * In either case, we are fixing the whitespace breakages
2320 * so we might as well take the fix together with their
2321 * real change.
2323 match = (tgtfix.len == fixed.len - fixstart &&
2324 !memcmp(tgtfix.buf, fixed.buf + fixstart,
2325 fixed.len - fixstart));
2327 strbuf_release(&tgtfix);
2328 if (!match)
2329 goto unmatch_exit;
2331 orig += oldlen;
2332 target += tgtlen;
2337 * Now handle the lines in the preimage that falls beyond the
2338 * end of the file (if any). They will only match if they are
2339 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2340 * false).
2342 for ( ; i < preimage->nr; i++) {
2343 size_t fixstart = fixed.len; /* start of the fixed preimage */
2344 size_t oldlen = preimage->line[i].len;
2345 int j;
2347 /* Try fixing the line in the preimage */
2348 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2350 for (j = fixstart; j < fixed.len; j++)
2351 if (!isspace(fixed.buf[j]))
2352 goto unmatch_exit;
2354 orig += oldlen;
2358 * Yes, the preimage is based on an older version that still
2359 * has whitespace breakages unfixed, and fixing them makes the
2360 * hunk match. Update the context lines in the postimage.
2362 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2363 update_pre_post_images(preimage, postimage,
2364 fixed_buf, fixed_len, 0);
2365 return 1;
2367 unmatch_exit:
2368 strbuf_release(&fixed);
2369 return 0;
2372 static int find_pos(struct image *img,
2373 struct image *preimage,
2374 struct image *postimage,
2375 int line,
2376 unsigned ws_rule,
2377 int match_beginning, int match_end)
2379 int i;
2380 unsigned long backwards, forwards, try;
2381 int backwards_lno, forwards_lno, try_lno;
2384 * If match_beginning or match_end is specified, there is no
2385 * point starting from a wrong line that will never match and
2386 * wander around and wait for a match at the specified end.
2388 if (match_beginning)
2389 line = 0;
2390 else if (match_end)
2391 line = img->nr - preimage->nr;
2394 * Because the comparison is unsigned, the following test
2395 * will also take care of a negative line number that can
2396 * result when match_end and preimage is larger than the target.
2398 if ((size_t) line > img->nr)
2399 line = img->nr;
2401 try = 0;
2402 for (i = 0; i < line; i++)
2403 try += img->line[i].len;
2406 * There's probably some smart way to do this, but I'll leave
2407 * that to the smart and beautiful people. I'm simple and stupid.
2409 backwards = try;
2410 backwards_lno = line;
2411 forwards = try;
2412 forwards_lno = line;
2413 try_lno = line;
2415 for (i = 0; ; i++) {
2416 if (match_fragment(img, preimage, postimage,
2417 try, try_lno, ws_rule,
2418 match_beginning, match_end))
2419 return try_lno;
2421 again:
2422 if (backwards_lno == 0 && forwards_lno == img->nr)
2423 break;
2425 if (i & 1) {
2426 if (backwards_lno == 0) {
2427 i++;
2428 goto again;
2430 backwards_lno--;
2431 backwards -= img->line[backwards_lno].len;
2432 try = backwards;
2433 try_lno = backwards_lno;
2434 } else {
2435 if (forwards_lno == img->nr) {
2436 i++;
2437 goto again;
2439 forwards += img->line[forwards_lno].len;
2440 forwards_lno++;
2441 try = forwards;
2442 try_lno = forwards_lno;
2446 return -1;
2449 static void remove_first_line(struct image *img)
2451 img->buf += img->line[0].len;
2452 img->len -= img->line[0].len;
2453 img->line++;
2454 img->nr--;
2457 static void remove_last_line(struct image *img)
2459 img->len -= img->line[--img->nr].len;
2463 * The change from "preimage" and "postimage" has been found to
2464 * apply at applied_pos (counts in line numbers) in "img".
2465 * Update "img" to remove "preimage" and replace it with "postimage".
2467 static void update_image(struct image *img,
2468 int applied_pos,
2469 struct image *preimage,
2470 struct image *postimage)
2473 * remove the copy of preimage at offset in img
2474 * and replace it with postimage
2476 int i, nr;
2477 size_t remove_count, insert_count, applied_at = 0;
2478 char *result;
2479 int preimage_limit;
2482 * If we are removing blank lines at the end of img,
2483 * the preimage may extend beyond the end.
2484 * If that is the case, we must be careful only to
2485 * remove the part of the preimage that falls within
2486 * the boundaries of img. Initialize preimage_limit
2487 * to the number of lines in the preimage that falls
2488 * within the boundaries.
2490 preimage_limit = preimage->nr;
2491 if (preimage_limit > img->nr - applied_pos)
2492 preimage_limit = img->nr - applied_pos;
2494 for (i = 0; i < applied_pos; i++)
2495 applied_at += img->line[i].len;
2497 remove_count = 0;
2498 for (i = 0; i < preimage_limit; i++)
2499 remove_count += img->line[applied_pos + i].len;
2500 insert_count = postimage->len;
2502 /* Adjust the contents */
2503 result = xmalloc(img->len + insert_count - remove_count + 1);
2504 memcpy(result, img->buf, applied_at);
2505 memcpy(result + applied_at, postimage->buf, postimage->len);
2506 memcpy(result + applied_at + postimage->len,
2507 img->buf + (applied_at + remove_count),
2508 img->len - (applied_at + remove_count));
2509 free(img->buf);
2510 img->buf = result;
2511 img->len += insert_count - remove_count;
2512 result[img->len] = '\0';
2514 /* Adjust the line table */
2515 nr = img->nr + postimage->nr - preimage_limit;
2516 if (preimage_limit < postimage->nr) {
2518 * NOTE: this knows that we never call remove_first_line()
2519 * on anything other than pre/post image.
2521 img->line = xrealloc(img->line, nr * sizeof(*img->line));
2522 img->line_allocated = img->line;
2524 if (preimage_limit != postimage->nr)
2525 memmove(img->line + applied_pos + postimage->nr,
2526 img->line + applied_pos + preimage_limit,
2527 (img->nr - (applied_pos + preimage_limit)) *
2528 sizeof(*img->line));
2529 memcpy(img->line + applied_pos,
2530 postimage->line,
2531 postimage->nr * sizeof(*img->line));
2532 if (!allow_overlap)
2533 for (i = 0; i < postimage->nr; i++)
2534 img->line[applied_pos + i].flag |= LINE_PATCHED;
2535 img->nr = nr;
2539 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2540 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2541 * replace the part of "img" with "postimage" text.
2543 static int apply_one_fragment(struct image *img, struct fragment *frag,
2544 int inaccurate_eof, unsigned ws_rule,
2545 int nth_fragment)
2547 int match_beginning, match_end;
2548 const char *patch = frag->patch;
2549 int size = frag->size;
2550 char *old, *oldlines;
2551 struct strbuf newlines;
2552 int new_blank_lines_at_end = 0;
2553 int found_new_blank_lines_at_end = 0;
2554 int hunk_linenr = frag->linenr;
2555 unsigned long leading, trailing;
2556 int pos, applied_pos;
2557 struct image preimage;
2558 struct image postimage;
2560 memset(&preimage, 0, sizeof(preimage));
2561 memset(&postimage, 0, sizeof(postimage));
2562 oldlines = xmalloc(size);
2563 strbuf_init(&newlines, size);
2565 old = oldlines;
2566 while (size > 0) {
2567 char first;
2568 int len = linelen(patch, size);
2569 int plen;
2570 int added_blank_line = 0;
2571 int is_blank_context = 0;
2572 size_t start;
2574 if (!len)
2575 break;
2578 * "plen" is how much of the line we should use for
2579 * the actual patch data. Normally we just remove the
2580 * first character on the line, but if the line is
2581 * followed by "\ No newline", then we also remove the
2582 * last one (which is the newline, of course).
2584 plen = len - 1;
2585 if (len < size && patch[len] == '\\')
2586 plen--;
2587 first = *patch;
2588 if (apply_in_reverse) {
2589 if (first == '-')
2590 first = '+';
2591 else if (first == '+')
2592 first = '-';
2595 switch (first) {
2596 case '\n':
2597 /* Newer GNU diff, empty context line */
2598 if (plen < 0)
2599 /* ... followed by '\No newline'; nothing */
2600 break;
2601 *old++ = '\n';
2602 strbuf_addch(&newlines, '\n');
2603 add_line_info(&preimage, "\n", 1, LINE_COMMON);
2604 add_line_info(&postimage, "\n", 1, LINE_COMMON);
2605 is_blank_context = 1;
2606 break;
2607 case ' ':
2608 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2609 ws_blank_line(patch + 1, plen, ws_rule))
2610 is_blank_context = 1;
2611 case '-':
2612 memcpy(old, patch + 1, plen);
2613 add_line_info(&preimage, old, plen,
2614 (first == ' ' ? LINE_COMMON : 0));
2615 old += plen;
2616 if (first == '-')
2617 break;
2618 /* Fall-through for ' ' */
2619 case '+':
2620 /* --no-add does not add new lines */
2621 if (first == '+' && no_add)
2622 break;
2624 start = newlines.len;
2625 if (first != '+' ||
2626 !whitespace_error ||
2627 ws_error_action != correct_ws_error) {
2628 strbuf_add(&newlines, patch + 1, plen);
2630 else {
2631 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &applied_after_fixing_ws);
2633 add_line_info(&postimage, newlines.buf + start, newlines.len - start,
2634 (first == '+' ? 0 : LINE_COMMON));
2635 if (first == '+' &&
2636 (ws_rule & WS_BLANK_AT_EOF) &&
2637 ws_blank_line(patch + 1, plen, ws_rule))
2638 added_blank_line = 1;
2639 break;
2640 case '@': case '\\':
2641 /* Ignore it, we already handled it */
2642 break;
2643 default:
2644 if (apply_verbosely)
2645 error(_("invalid start of line: '%c'"), first);
2646 return -1;
2648 if (added_blank_line) {
2649 if (!new_blank_lines_at_end)
2650 found_new_blank_lines_at_end = hunk_linenr;
2651 new_blank_lines_at_end++;
2653 else if (is_blank_context)
2655 else
2656 new_blank_lines_at_end = 0;
2657 patch += len;
2658 size -= len;
2659 hunk_linenr++;
2661 if (inaccurate_eof &&
2662 old > oldlines && old[-1] == '\n' &&
2663 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
2664 old--;
2665 strbuf_setlen(&newlines, newlines.len - 1);
2668 leading = frag->leading;
2669 trailing = frag->trailing;
2672 * A hunk to change lines at the beginning would begin with
2673 * @@ -1,L +N,M @@
2674 * but we need to be careful. -U0 that inserts before the second
2675 * line also has this pattern.
2677 * And a hunk to add to an empty file would begin with
2678 * @@ -0,0 +N,M @@
2680 * In other words, a hunk that is (frag->oldpos <= 1) with or
2681 * without leading context must match at the beginning.
2683 match_beginning = (!frag->oldpos ||
2684 (frag->oldpos == 1 && !unidiff_zero));
2687 * A hunk without trailing lines must match at the end.
2688 * However, we simply cannot tell if a hunk must match end
2689 * from the lack of trailing lines if the patch was generated
2690 * with unidiff without any context.
2692 match_end = !unidiff_zero && !trailing;
2694 pos = frag->newpos ? (frag->newpos - 1) : 0;
2695 preimage.buf = oldlines;
2696 preimage.len = old - oldlines;
2697 postimage.buf = newlines.buf;
2698 postimage.len = newlines.len;
2699 preimage.line = preimage.line_allocated;
2700 postimage.line = postimage.line_allocated;
2702 for (;;) {
2704 applied_pos = find_pos(img, &preimage, &postimage, pos,
2705 ws_rule, match_beginning, match_end);
2707 if (applied_pos >= 0)
2708 break;
2710 /* Am I at my context limits? */
2711 if ((leading <= p_context) && (trailing <= p_context))
2712 break;
2713 if (match_beginning || match_end) {
2714 match_beginning = match_end = 0;
2715 continue;
2719 * Reduce the number of context lines; reduce both
2720 * leading and trailing if they are equal otherwise
2721 * just reduce the larger context.
2723 if (leading >= trailing) {
2724 remove_first_line(&preimage);
2725 remove_first_line(&postimage);
2726 pos--;
2727 leading--;
2729 if (trailing > leading) {
2730 remove_last_line(&preimage);
2731 remove_last_line(&postimage);
2732 trailing--;
2736 if (applied_pos >= 0) {
2737 if (new_blank_lines_at_end &&
2738 preimage.nr + applied_pos >= img->nr &&
2739 (ws_rule & WS_BLANK_AT_EOF) &&
2740 ws_error_action != nowarn_ws_error) {
2741 record_ws_error(WS_BLANK_AT_EOF, "+", 1,
2742 found_new_blank_lines_at_end);
2743 if (ws_error_action == correct_ws_error) {
2744 while (new_blank_lines_at_end--)
2745 remove_last_line(&postimage);
2748 * We would want to prevent write_out_results()
2749 * from taking place in apply_patch() that follows
2750 * the callchain led us here, which is:
2751 * apply_patch->check_patch_list->check_patch->
2752 * apply_data->apply_fragments->apply_one_fragment
2754 if (ws_error_action == die_on_ws_error)
2755 apply = 0;
2758 if (apply_verbosely && applied_pos != pos) {
2759 int offset = applied_pos - pos;
2760 if (apply_in_reverse)
2761 offset = 0 - offset;
2762 fprintf_ln(stderr,
2763 Q_("Hunk #%d succeeded at %d (offset %d line).",
2764 "Hunk #%d succeeded at %d (offset %d lines).",
2765 offset),
2766 nth_fragment, applied_pos + 1, offset);
2770 * Warn if it was necessary to reduce the number
2771 * of context lines.
2773 if ((leading != frag->leading) ||
2774 (trailing != frag->trailing))
2775 fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"
2776 " to apply fragment at %d"),
2777 leading, trailing, applied_pos+1);
2778 update_image(img, applied_pos, &preimage, &postimage);
2779 } else {
2780 if (apply_verbosely)
2781 error(_("while searching for:\n%.*s"),
2782 (int)(old - oldlines), oldlines);
2785 free(oldlines);
2786 strbuf_release(&newlines);
2787 free(preimage.line_allocated);
2788 free(postimage.line_allocated);
2790 return (applied_pos < 0);
2793 static int apply_binary_fragment(struct image *img, struct patch *patch)
2795 struct fragment *fragment = patch->fragments;
2796 unsigned long len;
2797 void *dst;
2799 if (!fragment)
2800 return error(_("missing binary patch data for '%s'"),
2801 patch->new_name ?
2802 patch->new_name :
2803 patch->old_name);
2805 /* Binary patch is irreversible without the optional second hunk */
2806 if (apply_in_reverse) {
2807 if (!fragment->next)
2808 return error("cannot reverse-apply a binary patch "
2809 "without the reverse hunk to '%s'",
2810 patch->new_name
2811 ? patch->new_name : patch->old_name);
2812 fragment = fragment->next;
2814 switch (fragment->binary_patch_method) {
2815 case BINARY_DELTA_DEFLATED:
2816 dst = patch_delta(img->buf, img->len, fragment->patch,
2817 fragment->size, &len);
2818 if (!dst)
2819 return -1;
2820 clear_image(img);
2821 img->buf = dst;
2822 img->len = len;
2823 return 0;
2824 case BINARY_LITERAL_DEFLATED:
2825 clear_image(img);
2826 img->len = fragment->size;
2827 img->buf = xmalloc(img->len+1);
2828 memcpy(img->buf, fragment->patch, img->len);
2829 img->buf[img->len] = '\0';
2830 return 0;
2832 return -1;
2836 * Replace "img" with the result of applying the binary patch.
2837 * The binary patch data itself in patch->fragment is still kept
2838 * but the preimage prepared by the caller in "img" is freed here
2839 * or in the helper function apply_binary_fragment() this calls.
2841 static int apply_binary(struct image *img, struct patch *patch)
2843 const char *name = patch->old_name ? patch->old_name : patch->new_name;
2844 unsigned char sha1[20];
2847 * For safety, we require patch index line to contain
2848 * full 40-byte textual SHA1 for old and new, at least for now.
2850 if (strlen(patch->old_sha1_prefix) != 40 ||
2851 strlen(patch->new_sha1_prefix) != 40 ||
2852 get_sha1_hex(patch->old_sha1_prefix, sha1) ||
2853 get_sha1_hex(patch->new_sha1_prefix, sha1))
2854 return error("cannot apply binary patch to '%s' "
2855 "without full index line", name);
2857 if (patch->old_name) {
2859 * See if the old one matches what the patch
2860 * applies to.
2862 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2863 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
2864 return error("the patch applies to '%s' (%s), "
2865 "which does not match the "
2866 "current contents.",
2867 name, sha1_to_hex(sha1));
2869 else {
2870 /* Otherwise, the old one must be empty. */
2871 if (img->len)
2872 return error("the patch applies to an empty "
2873 "'%s' but it is not empty", name);
2876 get_sha1_hex(patch->new_sha1_prefix, sha1);
2877 if (is_null_sha1(sha1)) {
2878 clear_image(img);
2879 return 0; /* deletion patch */
2882 if (has_sha1_file(sha1)) {
2883 /* We already have the postimage */
2884 enum object_type type;
2885 unsigned long size;
2886 char *result;
2888 result = read_sha1_file(sha1, &type, &size);
2889 if (!result)
2890 return error("the necessary postimage %s for "
2891 "'%s' cannot be read",
2892 patch->new_sha1_prefix, name);
2893 clear_image(img);
2894 img->buf = result;
2895 img->len = size;
2896 } else {
2898 * We have verified buf matches the preimage;
2899 * apply the patch data to it, which is stored
2900 * in the patch->fragments->{patch,size}.
2902 if (apply_binary_fragment(img, patch))
2903 return error(_("binary patch does not apply to '%s'"),
2904 name);
2906 /* verify that the result matches */
2907 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2908 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
2909 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
2910 name, patch->new_sha1_prefix, sha1_to_hex(sha1));
2913 return 0;
2916 static int apply_fragments(struct image *img, struct patch *patch)
2918 struct fragment *frag = patch->fragments;
2919 const char *name = patch->old_name ? patch->old_name : patch->new_name;
2920 unsigned ws_rule = patch->ws_rule;
2921 unsigned inaccurate_eof = patch->inaccurate_eof;
2922 int nth = 0;
2924 if (patch->is_binary)
2925 return apply_binary(img, patch);
2927 while (frag) {
2928 nth++;
2929 if (apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {
2930 error(_("patch failed: %s:%ld"), name, frag->oldpos);
2931 if (!apply_with_reject)
2932 return -1;
2933 frag->rejected = 1;
2935 frag = frag->next;
2937 return 0;
2940 static int read_blob_object(struct strbuf *buf, const unsigned char *sha1, unsigned mode)
2942 if (S_ISGITLINK(mode)) {
2943 strbuf_grow(buf, 100);
2944 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(sha1));
2945 } else {
2946 enum object_type type;
2947 unsigned long sz;
2948 char *result;
2950 result = read_sha1_file(sha1, &type, &sz);
2951 if (!result)
2952 return -1;
2953 /* XXX read_sha1_file NUL-terminates */
2954 strbuf_attach(buf, result, sz, sz + 1);
2956 return 0;
2959 static int read_file_or_gitlink(struct cache_entry *ce, struct strbuf *buf)
2961 if (!ce)
2962 return 0;
2963 return read_blob_object(buf, ce->sha1, ce->ce_mode);
2966 static struct patch *in_fn_table(const char *name)
2968 struct string_list_item *item;
2970 if (name == NULL)
2971 return NULL;
2973 item = string_list_lookup(&fn_table, name);
2974 if (item != NULL)
2975 return (struct patch *)item->util;
2977 return NULL;
2981 * item->util in the filename table records the status of the path.
2982 * Usually it points at a patch (whose result records the contents
2983 * of it after applying it), but it could be PATH_WAS_DELETED for a
2984 * path that a previously applied patch has already removed, or
2985 * PATH_TO_BE_DELETED for a path that a later patch would remove.
2987 * The latter is needed to deal with a case where two paths A and B
2988 * are swapped by first renaming A to B and then renaming B to A;
2989 * moving A to B should not be prevented due to presense of B as we
2990 * will remove it in a later patch.
2992 #define PATH_TO_BE_DELETED ((struct patch *) -2)
2993 #define PATH_WAS_DELETED ((struct patch *) -1)
2995 static int to_be_deleted(struct patch *patch)
2997 return patch == PATH_TO_BE_DELETED;
3000 static int was_deleted(struct patch *patch)
3002 return patch == PATH_WAS_DELETED;
3005 static void add_to_fn_table(struct patch *patch)
3007 struct string_list_item *item;
3010 * Always add new_name unless patch is a deletion
3011 * This should cover the cases for normal diffs,
3012 * file creations and copies
3014 if (patch->new_name != NULL) {
3015 item = string_list_insert(&fn_table, patch->new_name);
3016 item->util = patch;
3020 * store a failure on rename/deletion cases because
3021 * later chunks shouldn't patch old names
3023 if ((patch->new_name == NULL) || (patch->is_rename)) {
3024 item = string_list_insert(&fn_table, patch->old_name);
3025 item->util = PATH_WAS_DELETED;
3029 static void prepare_fn_table(struct patch *patch)
3032 * store information about incoming file deletion
3034 while (patch) {
3035 if ((patch->new_name == NULL) || (patch->is_rename)) {
3036 struct string_list_item *item;
3037 item = string_list_insert(&fn_table, patch->old_name);
3038 item->util = PATH_TO_BE_DELETED;
3040 patch = patch->next;
3044 static int checkout_target(struct cache_entry *ce, struct stat *st)
3046 struct checkout costate;
3048 memset(&costate, 0, sizeof(costate));
3049 costate.base_dir = "";
3050 costate.refresh_cache = 1;
3051 if (checkout_entry(ce, &costate, NULL) || lstat(ce->name, st))
3052 return error(_("cannot checkout %s"), ce->name);
3053 return 0;
3056 static struct patch *previous_patch(struct patch *patch, int *gone)
3058 struct patch *previous;
3060 *gone = 0;
3061 if (patch->is_copy || patch->is_rename)
3062 return NULL; /* "git" patches do not depend on the order */
3064 previous = in_fn_table(patch->old_name);
3065 if (!previous)
3066 return NULL;
3068 if (to_be_deleted(previous))
3069 return NULL; /* the deletion hasn't happened yet */
3071 if (was_deleted(previous))
3072 *gone = 1;
3074 return previous;
3077 static int verify_index_match(struct cache_entry *ce, struct stat *st)
3079 if (S_ISGITLINK(ce->ce_mode)) {
3080 if (!S_ISDIR(st->st_mode))
3081 return -1;
3082 return 0;
3084 return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
3087 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3089 static int load_patch_target(struct strbuf *buf,
3090 struct cache_entry *ce,
3091 struct stat *st,
3092 const char *name,
3093 unsigned expected_mode)
3095 if (cached) {
3096 if (read_file_or_gitlink(ce, buf))
3097 return error(_("read of %s failed"), name);
3098 } else if (name) {
3099 if (S_ISGITLINK(expected_mode)) {
3100 if (ce)
3101 return read_file_or_gitlink(ce, buf);
3102 else
3103 return SUBMODULE_PATCH_WITHOUT_INDEX;
3104 } else {
3105 if (read_old_data(st, name, buf))
3106 return error(_("read of %s failed"), name);
3109 return 0;
3113 * We are about to apply "patch"; populate the "image" with the
3114 * current version we have, from the working tree or from the index,
3115 * depending on the situation e.g. --cached/--index. If we are
3116 * applying a non-git patch that incrementally updates the tree,
3117 * we read from the result of a previous diff.
3119 static int load_preimage(struct image *image,
3120 struct patch *patch, struct stat *st, struct cache_entry *ce)
3122 struct strbuf buf = STRBUF_INIT;
3123 size_t len;
3124 char *img;
3125 struct patch *previous;
3126 int status;
3128 previous = previous_patch(patch, &status);
3129 if (status)
3130 return error(_("path %s has been renamed/deleted"),
3131 patch->old_name);
3132 if (previous) {
3133 /* We have a patched copy in memory; use that. */
3134 strbuf_add(&buf, previous->result, previous->resultsize);
3135 } else {
3136 status = load_patch_target(&buf, ce, st,
3137 patch->old_name, patch->old_mode);
3138 if (status < 0)
3139 return status;
3140 else if (status == SUBMODULE_PATCH_WITHOUT_INDEX) {
3142 * There is no way to apply subproject
3143 * patch without looking at the index.
3144 * NEEDSWORK: shouldn't this be flagged
3145 * as an error???
3147 free_fragment_list(patch->fragments);
3148 patch->fragments = NULL;
3149 } else if (status) {
3150 return error(_("read of %s failed"), patch->old_name);
3154 img = strbuf_detach(&buf, &len);
3155 prepare_image(image, img, len, !patch->is_binary);
3156 return 0;
3159 static int three_way_merge(struct image *image,
3160 char *path,
3161 const unsigned char *base,
3162 const unsigned char *ours,
3163 const unsigned char *theirs)
3165 mmfile_t base_file, our_file, their_file;
3166 mmbuffer_t result = { NULL };
3167 int status;
3169 read_mmblob(&base_file, base);
3170 read_mmblob(&our_file, ours);
3171 read_mmblob(&their_file, theirs);
3172 status = ll_merge(&result, path,
3173 &base_file, "base",
3174 &our_file, "ours",
3175 &their_file, "theirs", NULL);
3176 free(base_file.ptr);
3177 free(our_file.ptr);
3178 free(their_file.ptr);
3179 if (status < 0 || !result.ptr) {
3180 free(result.ptr);
3181 return -1;
3183 clear_image(image);
3184 image->buf = result.ptr;
3185 image->len = result.size;
3187 return status;
3190 static int try_threeway(struct image *image, struct patch *patch,
3191 struct stat *st, struct cache_entry *ce)
3193 unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];
3194 struct strbuf buf = STRBUF_INIT;
3195 size_t len;
3196 int status;
3197 char *img;
3198 struct image tmp_image;
3200 /* No point falling back to 3-way merge in these cases */
3201 if (patch->is_new || patch->is_delete ||
3202 S_ISGITLINK(patch->old_mode) || S_ISGITLINK(patch->new_mode))
3203 return -1;
3205 /* Preimage the patch was prepared for */
3206 if (get_sha1(patch->old_sha1_prefix, pre_sha1) ||
3207 read_blob_object(&buf, pre_sha1, patch->old_mode))
3208 return error("repository lacks the necessary blob to fall back on 3-way merge.");
3210 fprintf(stderr, "Falling back to three-way merge...\n");
3212 img = strbuf_detach(&buf, &len);
3213 prepare_image(&tmp_image, img, len, 1);
3214 /* Apply the patch to get the post image */
3215 if (apply_fragments(&tmp_image, patch) < 0) {
3216 clear_image(&tmp_image);
3217 return -1;
3219 /* post_sha1[] is theirs */
3220 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);
3221 clear_image(&tmp_image);
3223 /* our_sha1[] is ours */
3224 if (load_preimage(&tmp_image, patch, st, ce))
3225 return error("cannot read the current contents of '%s'",
3226 patch->old_name);
3227 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);
3228 clear_image(&tmp_image);
3230 /* in-core three-way merge between post and our using pre as base */
3231 status = three_way_merge(image, patch->new_name,
3232 pre_sha1, our_sha1, post_sha1);
3233 if (status < 0) {
3234 fprintf(stderr, "Failed to fall back on three-way merge...\n");
3235 return status;
3238 if (status) {
3239 patch->conflicted_threeway = 1;
3240 hashcpy(patch->threeway_stage[0], pre_sha1);
3241 hashcpy(patch->threeway_stage[1], our_sha1);
3242 hashcpy(patch->threeway_stage[2], post_sha1);
3243 fprintf(stderr, "Applied patch to '%s' with conflicts.\n", patch->new_name);
3244 } else {
3245 fprintf(stderr, "Applied patch to '%s' cleanly.\n", patch->new_name);
3247 return 0;
3250 static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce)
3252 struct image image;
3254 if (load_preimage(&image, patch, st, ce) < 0)
3255 return -1;
3257 if (apply_fragments(&image, patch) < 0) {
3258 /* Note: with --reject, apply_fragments() returns 0 */
3259 if (!threeway || try_threeway(&image, patch, st, ce) < 0)
3260 return -1;
3262 patch->result = image.buf;
3263 patch->resultsize = image.len;
3264 add_to_fn_table(patch);
3265 free(image.line_allocated);
3267 if (0 < patch->is_delete && patch->resultsize)
3268 return error(_("removal patch leaves file contents"));
3270 return 0;
3274 * If "patch" that we are looking at modifies or deletes what we have,
3275 * we would want it not to lose any local modification we have, either
3276 * in the working tree or in the index.
3278 * This also decides if a non-git patch is a creation patch or a
3279 * modification to an existing empty file. We do not check the state
3280 * of the current tree for a creation patch in this function; the caller
3281 * check_patch() separately makes sure (and errors out otherwise) that
3282 * the path the patch creates does not exist in the current tree.
3284 static int check_preimage(struct patch *patch, struct cache_entry **ce, struct stat *st)
3286 const char *old_name = patch->old_name;
3287 struct patch *previous = NULL;
3288 int stat_ret = 0, status;
3289 unsigned st_mode = 0;
3291 if (!old_name)
3292 return 0;
3294 assert(patch->is_new <= 0);
3295 previous = previous_patch(patch, &status);
3297 if (status)
3298 return error(_("path %s has been renamed/deleted"), old_name);
3299 if (previous) {
3300 st_mode = previous->new_mode;
3301 } else if (!cached) {
3302 stat_ret = lstat(old_name, st);
3303 if (stat_ret && errno != ENOENT)
3304 return error(_("%s: %s"), old_name, strerror(errno));
3307 if (check_index && !previous) {
3308 int pos = cache_name_pos(old_name, strlen(old_name));
3309 if (pos < 0) {
3310 if (patch->is_new < 0)
3311 goto is_new;
3312 return error(_("%s: does not exist in index"), old_name);
3314 *ce = active_cache[pos];
3315 if (stat_ret < 0) {
3316 if (checkout_target(*ce, st))
3317 return -1;
3319 if (!cached && verify_index_match(*ce, st))
3320 return error(_("%s: does not match index"), old_name);
3321 if (cached)
3322 st_mode = (*ce)->ce_mode;
3323 } else if (stat_ret < 0) {
3324 if (patch->is_new < 0)
3325 goto is_new;
3326 return error(_("%s: %s"), old_name, strerror(errno));
3329 if (!cached && !previous)
3330 st_mode = ce_mode_from_stat(*ce, st->st_mode);
3332 if (patch->is_new < 0)
3333 patch->is_new = 0;
3334 if (!patch->old_mode)
3335 patch->old_mode = st_mode;
3336 if ((st_mode ^ patch->old_mode) & S_IFMT)
3337 return error(_("%s: wrong type"), old_name);
3338 if (st_mode != patch->old_mode)
3339 warning(_("%s has type %o, expected %o"),
3340 old_name, st_mode, patch->old_mode);
3341 if (!patch->new_mode && !patch->is_delete)
3342 patch->new_mode = st_mode;
3343 return 0;
3345 is_new:
3346 patch->is_new = 1;
3347 patch->is_delete = 0;
3348 free(patch->old_name);
3349 patch->old_name = NULL;
3350 return 0;
3354 #define EXISTS_IN_INDEX 1
3355 #define EXISTS_IN_WORKTREE 2
3357 static int check_to_create(const char *new_name, int ok_if_exists)
3359 struct stat nst;
3361 if (check_index &&
3362 cache_name_pos(new_name, strlen(new_name)) >= 0 &&
3363 !ok_if_exists)
3364 return EXISTS_IN_INDEX;
3365 if (cached)
3366 return 0;
3368 if (!lstat(new_name, &nst)) {
3369 if (S_ISDIR(nst.st_mode) || ok_if_exists)
3370 return 0;
3372 * A leading component of new_name might be a symlink
3373 * that is going to be removed with this patch, but
3374 * still pointing at somewhere that has the path.
3375 * In such a case, path "new_name" does not exist as
3376 * far as git is concerned.
3378 if (has_symlink_leading_path(new_name, strlen(new_name)))
3379 return 0;
3381 return EXISTS_IN_WORKTREE;
3382 } else if ((errno != ENOENT) && (errno != ENOTDIR)) {
3383 return error("%s: %s", new_name, strerror(errno));
3385 return 0;
3389 * Check and apply the patch in-core; leave the result in patch->result
3390 * for the caller to write it out to the final destination.
3392 static int check_patch(struct patch *patch)
3394 struct stat st;
3395 const char *old_name = patch->old_name;
3396 const char *new_name = patch->new_name;
3397 const char *name = old_name ? old_name : new_name;
3398 struct cache_entry *ce = NULL;
3399 struct patch *tpatch;
3400 int ok_if_exists;
3401 int status;
3403 patch->rejected = 1; /* we will drop this after we succeed */
3405 status = check_preimage(patch, &ce, &st);
3406 if (status)
3407 return status;
3408 old_name = patch->old_name;
3411 * A type-change diff is always split into a patch to delete
3412 * old, immediately followed by a patch to create new (see
3413 * diff.c::run_diff()); in such a case it is Ok that the entry
3414 * to be deleted by the previous patch is still in the working
3415 * tree and in the index.
3417 * A patch to swap-rename between A and B would first rename A
3418 * to B and then rename B to A. While applying the first one,
3419 * the presense of B should not stop A from getting renamed to
3420 * B; ask to_be_deleted() about the later rename. Removal of
3421 * B and rename from A to B is handled the same way by asking
3422 * was_deleted().
3424 if ((tpatch = in_fn_table(new_name)) &&
3425 (was_deleted(tpatch) || to_be_deleted(tpatch)))
3426 ok_if_exists = 1;
3427 else
3428 ok_if_exists = 0;
3430 if (new_name &&
3431 ((0 < patch->is_new) | (0 < patch->is_rename) | patch->is_copy)) {
3432 int err = check_to_create(new_name, ok_if_exists);
3434 switch (err) {
3435 case 0:
3436 break; /* happy */
3437 case EXISTS_IN_INDEX:
3438 return error(_("%s: already exists in index"), new_name);
3439 break;
3440 case EXISTS_IN_WORKTREE:
3441 return error(_("%s: already exists in working directory"),
3442 new_name);
3443 default:
3444 return err;
3447 if (!patch->new_mode) {
3448 if (0 < patch->is_new)
3449 patch->new_mode = S_IFREG | 0644;
3450 else
3451 patch->new_mode = patch->old_mode;
3455 if (new_name && old_name) {
3456 int same = !strcmp(old_name, new_name);
3457 if (!patch->new_mode)
3458 patch->new_mode = patch->old_mode;
3459 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
3460 return error(_("new mode (%o) of %s does not match old mode (%o)%s%s"),
3461 patch->new_mode, new_name, patch->old_mode,
3462 same ? "" : " of ", same ? "" : old_name);
3465 if (apply_data(patch, &st, ce) < 0)
3466 return error(_("%s: patch does not apply"), name);
3467 patch->rejected = 0;
3468 return 0;
3471 static int check_patch_list(struct patch *patch)
3473 int err = 0;
3475 prepare_fn_table(patch);
3476 while (patch) {
3477 if (apply_verbosely)
3478 say_patch_name(stderr,
3479 _("Checking patch %s..."), patch);
3480 err |= check_patch(patch);
3481 patch = patch->next;
3483 return err;
3486 /* This function tries to read the sha1 from the current index */
3487 static int get_current_sha1(const char *path, unsigned char *sha1)
3489 int pos;
3491 if (read_cache() < 0)
3492 return -1;
3493 pos = cache_name_pos(path, strlen(path));
3494 if (pos < 0)
3495 return -1;
3496 hashcpy(sha1, active_cache[pos]->sha1);
3497 return 0;
3500 /* Build an index that contains the just the files needed for a 3way merge */
3501 static void build_fake_ancestor(struct patch *list, const char *filename)
3503 struct patch *patch;
3504 struct index_state result = { NULL };
3505 int fd;
3507 /* Once we start supporting the reverse patch, it may be
3508 * worth showing the new sha1 prefix, but until then...
3510 for (patch = list; patch; patch = patch->next) {
3511 const unsigned char *sha1_ptr;
3512 unsigned char sha1[20];
3513 struct cache_entry *ce;
3514 const char *name;
3516 name = patch->old_name ? patch->old_name : patch->new_name;
3517 if (0 < patch->is_new)
3518 continue;
3519 else if (get_sha1(patch->old_sha1_prefix, sha1))
3520 /* git diff has no index line for mode/type changes */
3521 if (!patch->lines_added && !patch->lines_deleted) {
3522 if (get_current_sha1(patch->old_name, sha1))
3523 die("mode change for %s, which is not "
3524 "in current HEAD", name);
3525 sha1_ptr = sha1;
3526 } else
3527 die("sha1 information is lacking or useless "
3528 "(%s).", name);
3529 else
3530 sha1_ptr = sha1;
3532 ce = make_cache_entry(patch->old_mode, sha1_ptr, name, 0, 0);
3533 if (!ce)
3534 die(_("make_cache_entry failed for path '%s'"), name);
3535 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))
3536 die ("Could not add %s to temporary index", name);
3539 fd = open(filename, O_WRONLY | O_CREAT, 0666);
3540 if (fd < 0 || write_index(&result, fd) || close(fd))
3541 die ("Could not write temporary index to %s", filename);
3543 discard_index(&result);
3546 static void stat_patch_list(struct patch *patch)
3548 int files, adds, dels;
3550 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
3551 files++;
3552 adds += patch->lines_added;
3553 dels += patch->lines_deleted;
3554 show_stats(patch);
3557 print_stat_summary(stdout, files, adds, dels);
3560 static void numstat_patch_list(struct patch *patch)
3562 for ( ; patch; patch = patch->next) {
3563 const char *name;
3564 name = patch->new_name ? patch->new_name : patch->old_name;
3565 if (patch->is_binary)
3566 printf("-\t-\t");
3567 else
3568 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
3569 write_name_quoted(name, stdout, line_termination);
3573 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
3575 if (mode)
3576 printf(" %s mode %06o %s\n", newdelete, mode, name);
3577 else
3578 printf(" %s %s\n", newdelete, name);
3581 static void show_mode_change(struct patch *p, int show_name)
3583 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
3584 if (show_name)
3585 printf(" mode change %06o => %06o %s\n",
3586 p->old_mode, p->new_mode, p->new_name);
3587 else
3588 printf(" mode change %06o => %06o\n",
3589 p->old_mode, p->new_mode);
3593 static void show_rename_copy(struct patch *p)
3595 const char *renamecopy = p->is_rename ? "rename" : "copy";
3596 const char *old, *new;
3598 /* Find common prefix */
3599 old = p->old_name;
3600 new = p->new_name;
3601 while (1) {
3602 const char *slash_old, *slash_new;
3603 slash_old = strchr(old, '/');
3604 slash_new = strchr(new, '/');
3605 if (!slash_old ||
3606 !slash_new ||
3607 slash_old - old != slash_new - new ||
3608 memcmp(old, new, slash_new - new))
3609 break;
3610 old = slash_old + 1;
3611 new = slash_new + 1;
3613 /* p->old_name thru old is the common prefix, and old and new
3614 * through the end of names are renames
3616 if (old != p->old_name)
3617 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
3618 (int)(old - p->old_name), p->old_name,
3619 old, new, p->score);
3620 else
3621 printf(" %s %s => %s (%d%%)\n", renamecopy,
3622 p->old_name, p->new_name, p->score);
3623 show_mode_change(p, 0);
3626 static void summary_patch_list(struct patch *patch)
3628 struct patch *p;
3630 for (p = patch; p; p = p->next) {
3631 if (p->is_new)
3632 show_file_mode_name("create", p->new_mode, p->new_name);
3633 else if (p->is_delete)
3634 show_file_mode_name("delete", p->old_mode, p->old_name);
3635 else {
3636 if (p->is_rename || p->is_copy)
3637 show_rename_copy(p);
3638 else {
3639 if (p->score) {
3640 printf(" rewrite %s (%d%%)\n",
3641 p->new_name, p->score);
3642 show_mode_change(p, 0);
3644 else
3645 show_mode_change(p, 1);
3651 static void patch_stats(struct patch *patch)
3653 int lines = patch->lines_added + patch->lines_deleted;
3655 if (lines > max_change)
3656 max_change = lines;
3657 if (patch->old_name) {
3658 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
3659 if (!len)
3660 len = strlen(patch->old_name);
3661 if (len > max_len)
3662 max_len = len;
3664 if (patch->new_name) {
3665 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
3666 if (!len)
3667 len = strlen(patch->new_name);
3668 if (len > max_len)
3669 max_len = len;
3673 static void remove_file(struct patch *patch, int rmdir_empty)
3675 if (update_index) {
3676 if (remove_file_from_cache(patch->old_name) < 0)
3677 die(_("unable to remove %s from index"), patch->old_name);
3679 if (!cached) {
3680 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
3681 remove_path(patch->old_name);
3686 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
3688 struct stat st;
3689 struct cache_entry *ce;
3690 int namelen = strlen(path);
3691 unsigned ce_size = cache_entry_size(namelen);
3693 if (!update_index)
3694 return;
3696 ce = xcalloc(1, ce_size);
3697 memcpy(ce->name, path, namelen);
3698 ce->ce_mode = create_ce_mode(mode);
3699 ce->ce_flags = namelen;
3700 if (S_ISGITLINK(mode)) {
3701 const char *s = buf;
3703 if (get_sha1_hex(s + strlen("Subproject commit "), ce->sha1))
3704 die(_("corrupt patch for subproject %s"), path);
3705 } else {
3706 if (!cached) {
3707 if (lstat(path, &st) < 0)
3708 die_errno(_("unable to stat newly created file '%s'"),
3709 path);
3710 fill_stat_cache_info(ce, &st);
3712 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
3713 die(_("unable to create backing store for newly created file %s"), path);
3715 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
3716 die(_("unable to add cache entry for %s"), path);
3719 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
3721 int fd;
3722 struct strbuf nbuf = STRBUF_INIT;
3724 if (S_ISGITLINK(mode)) {
3725 struct stat st;
3726 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
3727 return 0;
3728 return mkdir(path, 0777);
3731 if (has_symlinks && S_ISLNK(mode))
3732 /* Although buf:size is counted string, it also is NUL
3733 * terminated.
3735 return symlink(buf, path);
3737 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
3738 if (fd < 0)
3739 return -1;
3741 if (convert_to_working_tree(path, buf, size, &nbuf)) {
3742 size = nbuf.len;
3743 buf = nbuf.buf;
3745 write_or_die(fd, buf, size);
3746 strbuf_release(&nbuf);
3748 if (close(fd) < 0)
3749 die_errno(_("closing file '%s'"), path);
3750 return 0;
3754 * We optimistically assume that the directories exist,
3755 * which is true 99% of the time anyway. If they don't,
3756 * we create them and try again.
3758 static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
3760 if (cached)
3761 return;
3762 if (!try_create_file(path, mode, buf, size))
3763 return;
3765 if (errno == ENOENT) {
3766 if (safe_create_leading_directories(path))
3767 return;
3768 if (!try_create_file(path, mode, buf, size))
3769 return;
3772 if (errno == EEXIST || errno == EACCES) {
3773 /* We may be trying to create a file where a directory
3774 * used to be.
3776 struct stat st;
3777 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
3778 errno = EEXIST;
3781 if (errno == EEXIST) {
3782 unsigned int nr = getpid();
3784 for (;;) {
3785 char newpath[PATH_MAX];
3786 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
3787 if (!try_create_file(newpath, mode, buf, size)) {
3788 if (!rename(newpath, path))
3789 return;
3790 unlink_or_warn(newpath);
3791 break;
3793 if (errno != EEXIST)
3794 break;
3795 ++nr;
3798 die_errno(_("unable to write file '%s' mode %o"), path, mode);
3801 static void create_file(struct patch *patch)
3803 char *path = patch->new_name;
3804 unsigned mode = patch->new_mode;
3805 unsigned long size = patch->resultsize;
3806 char *buf = patch->result;
3808 if (!mode)
3809 mode = S_IFREG | 0644;
3810 create_one_file(path, mode, buf, size);
3811 add_index_file(path, mode, buf, size);
3814 /* phase zero is to remove, phase one is to create */
3815 static void write_out_one_result(struct patch *patch, int phase)
3817 if (patch->is_delete > 0) {
3818 if (phase == 0)
3819 remove_file(patch, 1);
3820 return;
3822 if (patch->is_new > 0 || patch->is_copy) {
3823 if (phase == 1)
3824 create_file(patch);
3825 return;
3828 * Rename or modification boils down to the same
3829 * thing: remove the old, write the new
3831 if (phase == 0)
3832 remove_file(patch, patch->is_rename);
3833 if (phase == 1)
3834 create_file(patch);
3837 static int write_out_one_reject(struct patch *patch)
3839 FILE *rej;
3840 char namebuf[PATH_MAX];
3841 struct fragment *frag;
3842 int cnt = 0;
3843 struct strbuf sb = STRBUF_INIT;
3845 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
3846 if (!frag->rejected)
3847 continue;
3848 cnt++;
3851 if (!cnt) {
3852 if (apply_verbosely)
3853 say_patch_name(stderr,
3854 _("Applied patch %s cleanly."), patch);
3855 return 0;
3858 /* This should not happen, because a removal patch that leaves
3859 * contents are marked "rejected" at the patch level.
3861 if (!patch->new_name)
3862 die(_("internal error"));
3864 /* Say this even without --verbose */
3865 strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",
3866 "Applying patch %%s with %d rejects...",
3867 cnt),
3868 cnt);
3869 say_patch_name(stderr, sb.buf, patch);
3870 strbuf_release(&sb);
3872 cnt = strlen(patch->new_name);
3873 if (ARRAY_SIZE(namebuf) <= cnt + 5) {
3874 cnt = ARRAY_SIZE(namebuf) - 5;
3875 warning(_("truncating .rej filename to %.*s.rej"),
3876 cnt - 1, patch->new_name);
3878 memcpy(namebuf, patch->new_name, cnt);
3879 memcpy(namebuf + cnt, ".rej", 5);
3881 rej = fopen(namebuf, "w");
3882 if (!rej)
3883 return error(_("cannot open %s: %s"), namebuf, strerror(errno));
3885 /* Normal git tools never deal with .rej, so do not pretend
3886 * this is a git patch by saying --git nor give extended
3887 * headers. While at it, maybe please "kompare" that wants
3888 * the trailing TAB and some garbage at the end of line ;-).
3890 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
3891 patch->new_name, patch->new_name);
3892 for (cnt = 1, frag = patch->fragments;
3893 frag;
3894 cnt++, frag = frag->next) {
3895 if (!frag->rejected) {
3896 fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);
3897 continue;
3899 fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);
3900 fprintf(rej, "%.*s", frag->size, frag->patch);
3901 if (frag->patch[frag->size-1] != '\n')
3902 fputc('\n', rej);
3904 fclose(rej);
3905 return -1;
3908 static int write_out_results(struct patch *list)
3910 int phase;
3911 int errs = 0;
3912 struct patch *l;
3914 for (phase = 0; phase < 2; phase++) {
3915 l = list;
3916 while (l) {
3917 if (l->rejected)
3918 errs = 1;
3919 else {
3920 write_out_one_result(l, phase);
3921 if (phase == 1 && write_out_one_reject(l))
3922 errs = 1;
3924 l = l->next;
3927 return errs;
3930 static struct lock_file lock_file;
3932 static struct string_list limit_by_name;
3933 static int has_include;
3934 static void add_name_limit(const char *name, int exclude)
3936 struct string_list_item *it;
3938 it = string_list_append(&limit_by_name, name);
3939 it->util = exclude ? NULL : (void *) 1;
3942 static int use_patch(struct patch *p)
3944 const char *pathname = p->new_name ? p->new_name : p->old_name;
3945 int i;
3947 /* Paths outside are not touched regardless of "--include" */
3948 if (0 < prefix_length) {
3949 int pathlen = strlen(pathname);
3950 if (pathlen <= prefix_length ||
3951 memcmp(prefix, pathname, prefix_length))
3952 return 0;
3955 /* See if it matches any of exclude/include rule */
3956 for (i = 0; i < limit_by_name.nr; i++) {
3957 struct string_list_item *it = &limit_by_name.items[i];
3958 if (!fnmatch(it->string, pathname, 0))
3959 return (it->util != NULL);
3963 * If we had any include, a path that does not match any rule is
3964 * not used. Otherwise, we saw bunch of exclude rules (or none)
3965 * and such a path is used.
3967 return !has_include;
3971 static void prefix_one(char **name)
3973 char *old_name = *name;
3974 if (!old_name)
3975 return;
3976 *name = xstrdup(prefix_filename(prefix, prefix_length, *name));
3977 free(old_name);
3980 static void prefix_patches(struct patch *p)
3982 if (!prefix || p->is_toplevel_relative)
3983 return;
3984 for ( ; p; p = p->next) {
3985 prefix_one(&p->new_name);
3986 prefix_one(&p->old_name);
3990 #define INACCURATE_EOF (1<<0)
3991 #define RECOUNT (1<<1)
3993 static int apply_patch(int fd, const char *filename, int options)
3995 size_t offset;
3996 struct strbuf buf = STRBUF_INIT; /* owns the patch text */
3997 struct patch *list = NULL, **listp = &list;
3998 int skipped_patch = 0;
4000 patch_input_file = filename;
4001 read_patch_file(&buf, fd);
4002 offset = 0;
4003 while (offset < buf.len) {
4004 struct patch *patch;
4005 int nr;
4007 patch = xcalloc(1, sizeof(*patch));
4008 patch->inaccurate_eof = !!(options & INACCURATE_EOF);
4009 patch->recount = !!(options & RECOUNT);
4010 nr = parse_chunk(buf.buf + offset, buf.len - offset, patch);
4011 if (nr < 0)
4012 break;
4013 if (apply_in_reverse)
4014 reverse_patches(patch);
4015 if (prefix)
4016 prefix_patches(patch);
4017 if (use_patch(patch)) {
4018 patch_stats(patch);
4019 *listp = patch;
4020 listp = &patch->next;
4022 else {
4023 free_patch(patch);
4024 skipped_patch++;
4026 offset += nr;
4029 if (!list && !skipped_patch)
4030 die(_("unrecognized input"));
4032 if (whitespace_error && (ws_error_action == die_on_ws_error))
4033 apply = 0;
4035 update_index = check_index && apply;
4036 if (update_index && newfd < 0)
4037 newfd = hold_locked_index(&lock_file, 1);
4039 if (check_index) {
4040 if (read_cache() < 0)
4041 die(_("unable to read index file"));
4044 if ((check || apply) &&
4045 check_patch_list(list) < 0 &&
4046 !apply_with_reject)
4047 exit(1);
4049 if (apply && write_out_results(list))
4050 exit(1);
4052 if (fake_ancestor)
4053 build_fake_ancestor(list, fake_ancestor);
4055 if (diffstat)
4056 stat_patch_list(list);
4058 if (numstat)
4059 numstat_patch_list(list);
4061 if (summary)
4062 summary_patch_list(list);
4064 free_patch_list(list);
4065 strbuf_release(&buf);
4066 string_list_clear(&fn_table, 0);
4067 return 0;
4070 static int git_apply_config(const char *var, const char *value, void *cb)
4072 if (!strcmp(var, "apply.whitespace"))
4073 return git_config_string(&apply_default_whitespace, var, value);
4074 else if (!strcmp(var, "apply.ignorewhitespace"))
4075 return git_config_string(&apply_default_ignorewhitespace, var, value);
4076 return git_default_config(var, value, cb);
4079 static int option_parse_exclude(const struct option *opt,
4080 const char *arg, int unset)
4082 add_name_limit(arg, 1);
4083 return 0;
4086 static int option_parse_include(const struct option *opt,
4087 const char *arg, int unset)
4089 add_name_limit(arg, 0);
4090 has_include = 1;
4091 return 0;
4094 static int option_parse_p(const struct option *opt,
4095 const char *arg, int unset)
4097 p_value = atoi(arg);
4098 p_value_known = 1;
4099 return 0;
4102 static int option_parse_z(const struct option *opt,
4103 const char *arg, int unset)
4105 if (unset)
4106 line_termination = '\n';
4107 else
4108 line_termination = 0;
4109 return 0;
4112 static int option_parse_space_change(const struct option *opt,
4113 const char *arg, int unset)
4115 if (unset)
4116 ws_ignore_action = ignore_ws_none;
4117 else
4118 ws_ignore_action = ignore_ws_change;
4119 return 0;
4122 static int option_parse_whitespace(const struct option *opt,
4123 const char *arg, int unset)
4125 const char **whitespace_option = opt->value;
4127 *whitespace_option = arg;
4128 parse_whitespace_option(arg);
4129 return 0;
4132 static int option_parse_directory(const struct option *opt,
4133 const char *arg, int unset)
4135 root_len = strlen(arg);
4136 if (root_len && arg[root_len - 1] != '/') {
4137 char *new_root;
4138 root = new_root = xmalloc(root_len + 2);
4139 strcpy(new_root, arg);
4140 strcpy(new_root + root_len++, "/");
4141 } else
4142 root = arg;
4143 return 0;
4146 int cmd_apply(int argc, const char **argv, const char *prefix_)
4148 int i;
4149 int errs = 0;
4150 int is_not_gitdir = !startup_info->have_repository;
4151 int force_apply = 0;
4153 const char *whitespace_option = NULL;
4155 struct option builtin_apply_options[] = {
4156 { OPTION_CALLBACK, 0, "exclude", NULL, "path",
4157 "don't apply changes matching the given path",
4158 0, option_parse_exclude },
4159 { OPTION_CALLBACK, 0, "include", NULL, "path",
4160 "apply changes matching the given path",
4161 0, option_parse_include },
4162 { OPTION_CALLBACK, 'p', NULL, NULL, "num",
4163 "remove <num> leading slashes from traditional diff paths",
4164 0, option_parse_p },
4165 OPT_BOOLEAN(0, "no-add", &no_add,
4166 "ignore additions made by the patch"),
4167 OPT_BOOLEAN(0, "stat", &diffstat,
4168 "instead of applying the patch, output diffstat for the input"),
4169 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
4170 OPT_NOOP_NOARG(0, "binary"),
4171 OPT_BOOLEAN(0, "numstat", &numstat,
4172 "shows number of added and deleted lines in decimal notation"),
4173 OPT_BOOLEAN(0, "summary", &summary,
4174 "instead of applying the patch, output a summary for the input"),
4175 OPT_BOOLEAN(0, "check", &check,
4176 "instead of applying the patch, see if the patch is applicable"),
4177 OPT_BOOLEAN(0, "index", &check_index,
4178 "make sure the patch is applicable to the current index"),
4179 OPT_BOOLEAN(0, "cached", &cached,
4180 "apply a patch without touching the working tree"),
4181 OPT_BOOLEAN(0, "apply", &force_apply,
4182 "also apply the patch (use with --stat/--summary/--check)"),
4183 OPT_BOOL('3', "3way", &threeway,
4184 "attempt three-way merge if a patch does not apply"),
4185 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor,
4186 "build a temporary index based on embedded index information"),
4187 { OPTION_CALLBACK, 'z', NULL, NULL, NULL,
4188 "paths are separated with NUL character",
4189 PARSE_OPT_NOARG, option_parse_z },
4190 OPT_INTEGER('C', NULL, &p_context,
4191 "ensure at least <n> lines of context match"),
4192 { OPTION_CALLBACK, 0, "whitespace", &whitespace_option, "action",
4193 "detect new or modified lines that have whitespace errors",
4194 0, option_parse_whitespace },
4195 { OPTION_CALLBACK, 0, "ignore-space-change", NULL, NULL,
4196 "ignore changes in whitespace when finding context",
4197 PARSE_OPT_NOARG, option_parse_space_change },
4198 { OPTION_CALLBACK, 0, "ignore-whitespace", NULL, NULL,
4199 "ignore changes in whitespace when finding context",
4200 PARSE_OPT_NOARG, option_parse_space_change },
4201 OPT_BOOLEAN('R', "reverse", &apply_in_reverse,
4202 "apply the patch in reverse"),
4203 OPT_BOOLEAN(0, "unidiff-zero", &unidiff_zero,
4204 "don't expect at least one line of context"),
4205 OPT_BOOLEAN(0, "reject", &apply_with_reject,
4206 "leave the rejected hunks in corresponding *.rej files"),
4207 OPT_BOOLEAN(0, "allow-overlap", &allow_overlap,
4208 "allow overlapping hunks"),
4209 OPT__VERBOSE(&apply_verbosely, "be verbose"),
4210 OPT_BIT(0, "inaccurate-eof", &options,
4211 "tolerate incorrectly detected missing new-line at the end of file",
4212 INACCURATE_EOF),
4213 OPT_BIT(0, "recount", &options,
4214 "do not trust the line counts in the hunk headers",
4215 RECOUNT),
4216 { OPTION_CALLBACK, 0, "directory", NULL, "root",
4217 "prepend <root> to all filenames",
4218 0, option_parse_directory },
4219 OPT_END()
4222 prefix = prefix_;
4223 prefix_length = prefix ? strlen(prefix) : 0;
4224 git_config(git_apply_config, NULL);
4225 if (apply_default_whitespace)
4226 parse_whitespace_option(apply_default_whitespace);
4227 if (apply_default_ignorewhitespace)
4228 parse_ignorewhitespace_option(apply_default_ignorewhitespace);
4230 argc = parse_options(argc, argv, prefix, builtin_apply_options,
4231 apply_usage, 0);
4233 if (apply_with_reject && threeway)
4234 die("--reject and --3way cannot be used together.");
4235 if (cached && threeway)
4236 die("--cached and --3way cannot be used together.");
4237 if (threeway) {
4238 if (is_not_gitdir)
4239 die(_("--3way outside a repository"));
4240 check_index = 1;
4242 if (apply_with_reject)
4243 apply = apply_verbosely = 1;
4244 if (!force_apply && (diffstat || numstat || summary || check || fake_ancestor))
4245 apply = 0;
4246 if (check_index && is_not_gitdir)
4247 die(_("--index outside a repository"));
4248 if (cached) {
4249 if (is_not_gitdir)
4250 die(_("--cached outside a repository"));
4251 check_index = 1;
4253 for (i = 0; i < argc; i++) {
4254 const char *arg = argv[i];
4255 int fd;
4257 if (!strcmp(arg, "-")) {
4258 errs |= apply_patch(0, "<stdin>", options);
4259 read_stdin = 0;
4260 continue;
4261 } else if (0 < prefix_length)
4262 arg = prefix_filename(prefix, prefix_length, arg);
4264 fd = open(arg, O_RDONLY);
4265 if (fd < 0)
4266 die_errno(_("can't open patch '%s'"), arg);
4267 read_stdin = 0;
4268 set_default_whitespace_mode(whitespace_option);
4269 errs |= apply_patch(fd, arg, options);
4270 close(fd);
4272 set_default_whitespace_mode(whitespace_option);
4273 if (read_stdin)
4274 errs |= apply_patch(0, "<stdin>", options);
4275 if (whitespace_error) {
4276 if (squelch_whitespace_errors &&
4277 squelch_whitespace_errors < whitespace_error) {
4278 int squelched =
4279 whitespace_error - squelch_whitespace_errors;
4280 warning(Q_("squelched %d whitespace error",
4281 "squelched %d whitespace errors",
4282 squelched),
4283 squelched);
4285 if (ws_error_action == die_on_ws_error)
4286 die(Q_("%d line adds whitespace errors.",
4287 "%d lines add whitespace errors.",
4288 whitespace_error),
4289 whitespace_error);
4290 if (applied_after_fixing_ws && apply)
4291 warning("%d line%s applied after"
4292 " fixing whitespace errors.",
4293 applied_after_fixing_ws,
4294 applied_after_fixing_ws == 1 ? "" : "s");
4295 else if (whitespace_error)
4296 warning(Q_("%d line adds whitespace errors.",
4297 "%d lines add whitespace errors.",
4298 whitespace_error),
4299 whitespace_error);
4302 if (update_index) {
4303 if (write_cache(newfd, active_cache, active_nr) ||
4304 commit_locked_index(&lock_file))
4305 die(_("Unable to write new index file"));
4308 return !!errs;