Merge branch 'ah/usage-strings'
[git.git] / builtin / apply.c
blob23bda9628795016353d6feaf2b9699e48837f62c
1 /*
2 * apply.c
4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
8 */
9 #include "cache.h"
10 #include "lockfile.h"
11 #include "cache-tree.h"
12 #include "quote.h"
13 #include "blob.h"
14 #include "delta.h"
15 #include "builtin.h"
16 #include "string-list.h"
17 #include "dir.h"
18 #include "diff.h"
19 #include "parse-options.h"
20 #include "xdiff-interface.h"
21 #include "ll-merge.h"
22 #include "rerere.h"
25 * --check turns on checking that the working tree matches the
26 * files that are being modified, but doesn't apply the patch
27 * --stat does just a diffstat, and doesn't actually apply
28 * --numstat does numeric diffstat, and doesn't actually apply
29 * --index-info shows the old and new index info for paths if available.
30 * --index updates the cache as well.
31 * --cached updates only the cache without ever touching the working tree.
33 static const char *prefix;
34 static int prefix_length = -1;
35 static int newfd = -1;
37 static int unidiff_zero;
38 static int p_value = 1;
39 static int p_value_known;
40 static int check_index;
41 static int update_index;
42 static int cached;
43 static int diffstat;
44 static int numstat;
45 static int summary;
46 static int check;
47 static int apply = 1;
48 static int apply_in_reverse;
49 static int apply_with_reject;
50 static int apply_verbosely;
51 static int allow_overlap;
52 static int no_add;
53 static int threeway;
54 static const char *fake_ancestor;
55 static int line_termination = '\n';
56 static unsigned int p_context = UINT_MAX;
57 static const char * const apply_usage[] = {
58 N_("git apply [<options>] [<patch>...]"),
59 NULL
62 static enum ws_error_action {
63 nowarn_ws_error,
64 warn_on_ws_error,
65 die_on_ws_error,
66 correct_ws_error
67 } ws_error_action = warn_on_ws_error;
68 static int whitespace_error;
69 static int squelch_whitespace_errors = 5;
70 static int applied_after_fixing_ws;
72 static enum ws_ignore {
73 ignore_ws_none,
74 ignore_ws_change
75 } ws_ignore_action = ignore_ws_none;
78 static const char *patch_input_file;
79 static const char *root;
80 static int root_len;
81 static int read_stdin = 1;
82 static int options;
84 static void parse_whitespace_option(const char *option)
86 if (!option) {
87 ws_error_action = warn_on_ws_error;
88 return;
90 if (!strcmp(option, "warn")) {
91 ws_error_action = warn_on_ws_error;
92 return;
94 if (!strcmp(option, "nowarn")) {
95 ws_error_action = nowarn_ws_error;
96 return;
98 if (!strcmp(option, "error")) {
99 ws_error_action = die_on_ws_error;
100 return;
102 if (!strcmp(option, "error-all")) {
103 ws_error_action = die_on_ws_error;
104 squelch_whitespace_errors = 0;
105 return;
107 if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
108 ws_error_action = correct_ws_error;
109 return;
111 die(_("unrecognized whitespace option '%s'"), option);
114 static void parse_ignorewhitespace_option(const char *option)
116 if (!option || !strcmp(option, "no") ||
117 !strcmp(option, "false") || !strcmp(option, "never") ||
118 !strcmp(option, "none")) {
119 ws_ignore_action = ignore_ws_none;
120 return;
122 if (!strcmp(option, "change")) {
123 ws_ignore_action = ignore_ws_change;
124 return;
126 die(_("unrecognized whitespace ignore option '%s'"), option);
129 static void set_default_whitespace_mode(const char *whitespace_option)
131 if (!whitespace_option && !apply_default_whitespace)
132 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error);
136 * For "diff-stat" like behaviour, we keep track of the biggest change
137 * we've seen, and the longest filename. That allows us to do simple
138 * scaling.
140 static int max_change, max_len;
143 * Various "current state", notably line numbers and what
144 * file (and how) we're patching right now.. The "is_xxxx"
145 * things are flags, where -1 means "don't know yet".
147 static int linenr = 1;
150 * This represents one "hunk" from a patch, starting with
151 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
152 * patch text is pointed at by patch, and its byte length
153 * is stored in size. leading and trailing are the number
154 * of context lines.
156 struct fragment {
157 unsigned long leading, trailing;
158 unsigned long oldpos, oldlines;
159 unsigned long newpos, newlines;
161 * 'patch' is usually borrowed from buf in apply_patch(),
162 * but some codepaths store an allocated buffer.
164 const char *patch;
165 unsigned free_patch:1,
166 rejected:1;
167 int size;
168 int linenr;
169 struct fragment *next;
173 * When dealing with a binary patch, we reuse "leading" field
174 * to store the type of the binary hunk, either deflated "delta"
175 * or deflated "literal".
177 #define binary_patch_method leading
178 #define BINARY_DELTA_DEFLATED 1
179 #define BINARY_LITERAL_DEFLATED 2
182 * This represents a "patch" to a file, both metainfo changes
183 * such as creation/deletion, filemode and content changes represented
184 * as a series of fragments.
186 struct patch {
187 char *new_name, *old_name, *def_name;
188 unsigned int old_mode, new_mode;
189 int is_new, is_delete; /* -1 = unknown, 0 = false, 1 = true */
190 int rejected;
191 unsigned ws_rule;
192 int lines_added, lines_deleted;
193 int score;
194 unsigned int is_toplevel_relative:1;
195 unsigned int inaccurate_eof:1;
196 unsigned int is_binary:1;
197 unsigned int is_copy:1;
198 unsigned int is_rename:1;
199 unsigned int recount:1;
200 unsigned int conflicted_threeway:1;
201 unsigned int direct_to_threeway:1;
202 struct fragment *fragments;
203 char *result;
204 size_t resultsize;
205 char old_sha1_prefix[41];
206 char new_sha1_prefix[41];
207 struct patch *next;
209 /* three-way fallback result */
210 unsigned char threeway_stage[3][20];
213 static void free_fragment_list(struct fragment *list)
215 while (list) {
216 struct fragment *next = list->next;
217 if (list->free_patch)
218 free((char *)list->patch);
219 free(list);
220 list = next;
224 static void free_patch(struct patch *patch)
226 free_fragment_list(patch->fragments);
227 free(patch->def_name);
228 free(patch->old_name);
229 free(patch->new_name);
230 free(patch->result);
231 free(patch);
234 static void free_patch_list(struct patch *list)
236 while (list) {
237 struct patch *next = list->next;
238 free_patch(list);
239 list = next;
244 * A line in a file, len-bytes long (includes the terminating LF,
245 * except for an incomplete line at the end if the file ends with
246 * one), and its contents hashes to 'hash'.
248 struct line {
249 size_t len;
250 unsigned hash : 24;
251 unsigned flag : 8;
252 #define LINE_COMMON 1
253 #define LINE_PATCHED 2
257 * This represents a "file", which is an array of "lines".
259 struct image {
260 char *buf;
261 size_t len;
262 size_t nr;
263 size_t alloc;
264 struct line *line_allocated;
265 struct line *line;
269 * Records filenames that have been touched, in order to handle
270 * the case where more than one patches touch the same file.
273 static struct string_list fn_table;
275 static uint32_t hash_line(const char *cp, size_t len)
277 size_t i;
278 uint32_t h;
279 for (i = 0, h = 0; i < len; i++) {
280 if (!isspace(cp[i])) {
281 h = h * 3 + (cp[i] & 0xff);
284 return h;
288 * Compare lines s1 of length n1 and s2 of length n2, ignoring
289 * whitespace difference. Returns 1 if they match, 0 otherwise
291 static int fuzzy_matchlines(const char *s1, size_t n1,
292 const char *s2, size_t n2)
294 const char *last1 = s1 + n1 - 1;
295 const char *last2 = s2 + n2 - 1;
296 int result = 0;
298 /* ignore line endings */
299 while ((*last1 == '\r') || (*last1 == '\n'))
300 last1--;
301 while ((*last2 == '\r') || (*last2 == '\n'))
302 last2--;
304 /* skip leading whitespaces, if both begin with whitespace */
305 if (s1 <= last1 && s2 <= last2 && isspace(*s1) && isspace(*s2)) {
306 while (isspace(*s1) && (s1 <= last1))
307 s1++;
308 while (isspace(*s2) && (s2 <= last2))
309 s2++;
311 /* early return if both lines are empty */
312 if ((s1 > last1) && (s2 > last2))
313 return 1;
314 while (!result) {
315 result = *s1++ - *s2++;
317 * Skip whitespace inside. We check for whitespace on
318 * both buffers because we don't want "a b" to match
319 * "ab"
321 if (isspace(*s1) && isspace(*s2)) {
322 while (isspace(*s1) && s1 <= last1)
323 s1++;
324 while (isspace(*s2) && s2 <= last2)
325 s2++;
328 * If we reached the end on one side only,
329 * lines don't match
331 if (
332 ((s2 > last2) && (s1 <= last1)) ||
333 ((s1 > last1) && (s2 <= last2)))
334 return 0;
335 if ((s1 > last1) && (s2 > last2))
336 break;
339 return !result;
342 static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
344 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
345 img->line_allocated[img->nr].len = len;
346 img->line_allocated[img->nr].hash = hash_line(bol, len);
347 img->line_allocated[img->nr].flag = flag;
348 img->nr++;
352 * "buf" has the file contents to be patched (read from various sources).
353 * attach it to "image" and add line-based index to it.
354 * "image" now owns the "buf".
356 static void prepare_image(struct image *image, char *buf, size_t len,
357 int prepare_linetable)
359 const char *cp, *ep;
361 memset(image, 0, sizeof(*image));
362 image->buf = buf;
363 image->len = len;
365 if (!prepare_linetable)
366 return;
368 ep = image->buf + image->len;
369 cp = image->buf;
370 while (cp < ep) {
371 const char *next;
372 for (next = cp; next < ep && *next != '\n'; next++)
374 if (next < ep)
375 next++;
376 add_line_info(image, cp, next - cp, 0);
377 cp = next;
379 image->line = image->line_allocated;
382 static void clear_image(struct image *image)
384 free(image->buf);
385 free(image->line_allocated);
386 memset(image, 0, sizeof(*image));
389 /* fmt must contain _one_ %s and no other substitution */
390 static void say_patch_name(FILE *output, const char *fmt, struct patch *patch)
392 struct strbuf sb = STRBUF_INIT;
394 if (patch->old_name && patch->new_name &&
395 strcmp(patch->old_name, patch->new_name)) {
396 quote_c_style(patch->old_name, &sb, NULL, 0);
397 strbuf_addstr(&sb, " => ");
398 quote_c_style(patch->new_name, &sb, NULL, 0);
399 } else {
400 const char *n = patch->new_name;
401 if (!n)
402 n = patch->old_name;
403 quote_c_style(n, &sb, NULL, 0);
405 fprintf(output, fmt, sb.buf);
406 fputc('\n', output);
407 strbuf_release(&sb);
410 #define SLOP (16)
412 static void read_patch_file(struct strbuf *sb, int fd)
414 if (strbuf_read(sb, fd, 0) < 0)
415 die_errno("git apply: failed to read");
418 * Make sure that we have some slop in the buffer
419 * so that we can do speculative "memcmp" etc, and
420 * see to it that it is NUL-filled.
422 strbuf_grow(sb, SLOP);
423 memset(sb->buf + sb->len, 0, SLOP);
426 static unsigned long linelen(const char *buffer, unsigned long size)
428 unsigned long len = 0;
429 while (size--) {
430 len++;
431 if (*buffer++ == '\n')
432 break;
434 return len;
437 static int is_dev_null(const char *str)
439 return skip_prefix(str, "/dev/null", &str) && isspace(*str);
442 #define TERM_SPACE 1
443 #define TERM_TAB 2
445 static int name_terminate(const char *name, int namelen, int c, int terminate)
447 if (c == ' ' && !(terminate & TERM_SPACE))
448 return 0;
449 if (c == '\t' && !(terminate & TERM_TAB))
450 return 0;
452 return 1;
455 /* remove double slashes to make --index work with such filenames */
456 static char *squash_slash(char *name)
458 int i = 0, j = 0;
460 if (!name)
461 return NULL;
463 while (name[i]) {
464 if ((name[j++] = name[i++]) == '/')
465 while (name[i] == '/')
466 i++;
468 name[j] = '\0';
469 return name;
472 static char *find_name_gnu(const char *line, const char *def, int p_value)
474 struct strbuf name = STRBUF_INIT;
475 char *cp;
478 * Proposed "new-style" GNU patch/diff format; see
479 * http://marc.info/?l=git&m=112927316408690&w=2
481 if (unquote_c_style(&name, line, NULL)) {
482 strbuf_release(&name);
483 return NULL;
486 for (cp = name.buf; p_value; p_value--) {
487 cp = strchr(cp, '/');
488 if (!cp) {
489 strbuf_release(&name);
490 return NULL;
492 cp++;
495 strbuf_remove(&name, 0, cp - name.buf);
496 if (root)
497 strbuf_insert(&name, 0, root, root_len);
498 return squash_slash(strbuf_detach(&name, NULL));
501 static size_t sane_tz_len(const char *line, size_t len)
503 const char *tz, *p;
505 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
506 return 0;
507 tz = line + len - strlen(" +0500");
509 if (tz[1] != '+' && tz[1] != '-')
510 return 0;
512 for (p = tz + 2; p != line + len; p++)
513 if (!isdigit(*p))
514 return 0;
516 return line + len - tz;
519 static size_t tz_with_colon_len(const char *line, size_t len)
521 const char *tz, *p;
523 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
524 return 0;
525 tz = line + len - strlen(" +08:00");
527 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
528 return 0;
529 p = tz + 2;
530 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
531 !isdigit(*p++) || !isdigit(*p++))
532 return 0;
534 return line + len - tz;
537 static size_t date_len(const char *line, size_t len)
539 const char *date, *p;
541 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
542 return 0;
543 p = date = line + len - strlen("72-02-05");
545 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
546 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
547 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */
548 return 0;
550 if (date - line >= strlen("19") &&
551 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */
552 date -= strlen("19");
554 return line + len - date;
557 static size_t short_time_len(const char *line, size_t len)
559 const char *time, *p;
561 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
562 return 0;
563 p = time = line + len - strlen(" 07:01:32");
565 /* Permit 1-digit hours? */
566 if (*p++ != ' ' ||
567 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
568 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
569 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */
570 return 0;
572 return line + len - time;
575 static size_t fractional_time_len(const char *line, size_t len)
577 const char *p;
578 size_t n;
580 /* Expected format: 19:41:17.620000023 */
581 if (!len || !isdigit(line[len - 1]))
582 return 0;
583 p = line + len - 1;
585 /* Fractional seconds. */
586 while (p > line && isdigit(*p))
587 p--;
588 if (*p != '.')
589 return 0;
591 /* Hours, minutes, and whole seconds. */
592 n = short_time_len(line, p - line);
593 if (!n)
594 return 0;
596 return line + len - p + n;
599 static size_t trailing_spaces_len(const char *line, size_t len)
601 const char *p;
603 /* Expected format: ' ' x (1 or more) */
604 if (!len || line[len - 1] != ' ')
605 return 0;
607 p = line + len;
608 while (p != line) {
609 p--;
610 if (*p != ' ')
611 return line + len - (p + 1);
614 /* All spaces! */
615 return len;
618 static size_t diff_timestamp_len(const char *line, size_t len)
620 const char *end = line + len;
621 size_t n;
624 * Posix: 2010-07-05 19:41:17
625 * GNU: 2010-07-05 19:41:17.620000023 -0500
628 if (!isdigit(end[-1]))
629 return 0;
631 n = sane_tz_len(line, end - line);
632 if (!n)
633 n = tz_with_colon_len(line, end - line);
634 end -= n;
636 n = short_time_len(line, end - line);
637 if (!n)
638 n = fractional_time_len(line, end - line);
639 end -= n;
641 n = date_len(line, end - line);
642 if (!n) /* No date. Too bad. */
643 return 0;
644 end -= n;
646 if (end == line) /* No space before date. */
647 return 0;
648 if (end[-1] == '\t') { /* Success! */
649 end--;
650 return line + len - end;
652 if (end[-1] != ' ') /* No space before date. */
653 return 0;
655 /* Whitespace damage. */
656 end -= trailing_spaces_len(line, end - line);
657 return line + len - end;
660 static char *find_name_common(const char *line, const char *def,
661 int p_value, const char *end, int terminate)
663 int len;
664 const char *start = NULL;
666 if (p_value == 0)
667 start = line;
668 while (line != end) {
669 char c = *line;
671 if (!end && isspace(c)) {
672 if (c == '\n')
673 break;
674 if (name_terminate(start, line-start, c, terminate))
675 break;
677 line++;
678 if (c == '/' && !--p_value)
679 start = line;
681 if (!start)
682 return squash_slash(xstrdup_or_null(def));
683 len = line - start;
684 if (!len)
685 return squash_slash(xstrdup_or_null(def));
688 * Generally we prefer the shorter name, especially
689 * if the other one is just a variation of that with
690 * something else tacked on to the end (ie "file.orig"
691 * or "file~").
693 if (def) {
694 int deflen = strlen(def);
695 if (deflen < len && !strncmp(start, def, deflen))
696 return squash_slash(xstrdup(def));
699 if (root) {
700 char *ret = xmalloc(root_len + len + 1);
701 strcpy(ret, root);
702 memcpy(ret + root_len, start, len);
703 ret[root_len + len] = '\0';
704 return squash_slash(ret);
707 return squash_slash(xmemdupz(start, len));
710 static char *find_name(const char *line, char *def, int p_value, int terminate)
712 if (*line == '"') {
713 char *name = find_name_gnu(line, def, p_value);
714 if (name)
715 return name;
718 return find_name_common(line, def, p_value, NULL, terminate);
721 static char *find_name_traditional(const char *line, char *def, int p_value)
723 size_t len;
724 size_t date_len;
726 if (*line == '"') {
727 char *name = find_name_gnu(line, def, p_value);
728 if (name)
729 return name;
732 len = strchrnul(line, '\n') - line;
733 date_len = diff_timestamp_len(line, len);
734 if (!date_len)
735 return find_name_common(line, def, p_value, NULL, TERM_TAB);
736 len -= date_len;
738 return find_name_common(line, def, p_value, line + len, 0);
741 static int count_slashes(const char *cp)
743 int cnt = 0;
744 char ch;
746 while ((ch = *cp++))
747 if (ch == '/')
748 cnt++;
749 return cnt;
753 * Given the string after "--- " or "+++ ", guess the appropriate
754 * p_value for the given patch.
756 static int guess_p_value(const char *nameline)
758 char *name, *cp;
759 int val = -1;
761 if (is_dev_null(nameline))
762 return -1;
763 name = find_name_traditional(nameline, NULL, 0);
764 if (!name)
765 return -1;
766 cp = strchr(name, '/');
767 if (!cp)
768 val = 0;
769 else if (prefix) {
771 * Does it begin with "a/$our-prefix" and such? Then this is
772 * very likely to apply to our directory.
774 if (!strncmp(name, prefix, prefix_length))
775 val = count_slashes(prefix);
776 else {
777 cp++;
778 if (!strncmp(cp, prefix, prefix_length))
779 val = count_slashes(prefix) + 1;
782 free(name);
783 return val;
787 * Does the ---/+++ line has the POSIX timestamp after the last HT?
788 * GNU diff puts epoch there to signal a creation/deletion event. Is
789 * this such a timestamp?
791 static int has_epoch_timestamp(const char *nameline)
794 * We are only interested in epoch timestamp; any non-zero
795 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
796 * For the same reason, the date must be either 1969-12-31 or
797 * 1970-01-01, and the seconds part must be "00".
799 const char stamp_regexp[] =
800 "^(1969-12-31|1970-01-01)"
802 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
804 "([-+][0-2][0-9]:?[0-5][0-9])\n";
805 const char *timestamp = NULL, *cp, *colon;
806 static regex_t *stamp;
807 regmatch_t m[10];
808 int zoneoffset;
809 int hourminute;
810 int status;
812 for (cp = nameline; *cp != '\n'; cp++) {
813 if (*cp == '\t')
814 timestamp = cp + 1;
816 if (!timestamp)
817 return 0;
818 if (!stamp) {
819 stamp = xmalloc(sizeof(*stamp));
820 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
821 warning(_("Cannot prepare timestamp regexp %s"),
822 stamp_regexp);
823 return 0;
827 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
828 if (status) {
829 if (status != REG_NOMATCH)
830 warning(_("regexec returned %d for input: %s"),
831 status, timestamp);
832 return 0;
835 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
836 if (*colon == ':')
837 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
838 else
839 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
840 if (timestamp[m[3].rm_so] == '-')
841 zoneoffset = -zoneoffset;
844 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
845 * (west of GMT) or 1970-01-01 (east of GMT)
847 if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) ||
848 (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10)))
849 return 0;
851 hourminute = (strtol(timestamp + 11, NULL, 10) * 60 +
852 strtol(timestamp + 14, NULL, 10) -
853 zoneoffset);
855 return ((zoneoffset < 0 && hourminute == 1440) ||
856 (0 <= zoneoffset && !hourminute));
860 * Get the name etc info from the ---/+++ lines of a traditional patch header
862 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
863 * files, we can happily check the index for a match, but for creating a
864 * new file we should try to match whatever "patch" does. I have no idea.
866 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
868 char *name;
870 first += 4; /* skip "--- " */
871 second += 4; /* skip "+++ " */
872 if (!p_value_known) {
873 int p, q;
874 p = guess_p_value(first);
875 q = guess_p_value(second);
876 if (p < 0) p = q;
877 if (0 <= p && p == q) {
878 p_value = p;
879 p_value_known = 1;
882 if (is_dev_null(first)) {
883 patch->is_new = 1;
884 patch->is_delete = 0;
885 name = find_name_traditional(second, NULL, p_value);
886 patch->new_name = name;
887 } else if (is_dev_null(second)) {
888 patch->is_new = 0;
889 patch->is_delete = 1;
890 name = find_name_traditional(first, NULL, p_value);
891 patch->old_name = name;
892 } else {
893 char *first_name;
894 first_name = find_name_traditional(first, NULL, p_value);
895 name = find_name_traditional(second, first_name, p_value);
896 free(first_name);
897 if (has_epoch_timestamp(first)) {
898 patch->is_new = 1;
899 patch->is_delete = 0;
900 patch->new_name = name;
901 } else if (has_epoch_timestamp(second)) {
902 patch->is_new = 0;
903 patch->is_delete = 1;
904 patch->old_name = name;
905 } else {
906 patch->old_name = name;
907 patch->new_name = xstrdup_or_null(name);
910 if (!name)
911 die(_("unable to find filename in patch at line %d"), linenr);
914 static int gitdiff_hdrend(const char *line, struct patch *patch)
916 return -1;
920 * We're anal about diff header consistency, to make
921 * sure that we don't end up having strange ambiguous
922 * patches floating around.
924 * As a result, gitdiff_{old|new}name() will check
925 * their names against any previous information, just
926 * to make sure..
928 #define DIFF_OLD_NAME 0
929 #define DIFF_NEW_NAME 1
931 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, int side)
933 if (!orig_name && !isnull)
934 return find_name(line, NULL, p_value, TERM_TAB);
936 if (orig_name) {
937 int len;
938 const char *name;
939 char *another;
940 name = orig_name;
941 len = strlen(name);
942 if (isnull)
943 die(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"), name, linenr);
944 another = find_name(line, NULL, p_value, TERM_TAB);
945 if (!another || memcmp(another, name, len + 1))
946 die((side == DIFF_NEW_NAME) ?
947 _("git apply: bad git-diff - inconsistent new filename on line %d") :
948 _("git apply: bad git-diff - inconsistent old filename on line %d"), linenr);
949 free(another);
950 return orig_name;
952 else {
953 /* expect "/dev/null" */
954 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
955 die(_("git apply: bad git-diff - expected /dev/null on line %d"), linenr);
956 return NULL;
960 static int gitdiff_oldname(const char *line, struct patch *patch)
962 char *orig = patch->old_name;
963 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name,
964 DIFF_OLD_NAME);
965 if (orig != patch->old_name)
966 free(orig);
967 return 0;
970 static int gitdiff_newname(const char *line, struct patch *patch)
972 char *orig = patch->new_name;
973 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name,
974 DIFF_NEW_NAME);
975 if (orig != patch->new_name)
976 free(orig);
977 return 0;
980 static int gitdiff_oldmode(const char *line, struct patch *patch)
982 patch->old_mode = strtoul(line, NULL, 8);
983 return 0;
986 static int gitdiff_newmode(const char *line, struct patch *patch)
988 patch->new_mode = strtoul(line, NULL, 8);
989 return 0;
992 static int gitdiff_delete(const char *line, struct patch *patch)
994 patch->is_delete = 1;
995 free(patch->old_name);
996 patch->old_name = xstrdup_or_null(patch->def_name);
997 return gitdiff_oldmode(line, patch);
1000 static int gitdiff_newfile(const char *line, struct patch *patch)
1002 patch->is_new = 1;
1003 free(patch->new_name);
1004 patch->new_name = xstrdup_or_null(patch->def_name);
1005 return gitdiff_newmode(line, patch);
1008 static int gitdiff_copysrc(const char *line, struct patch *patch)
1010 patch->is_copy = 1;
1011 free(patch->old_name);
1012 patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1013 return 0;
1016 static int gitdiff_copydst(const char *line, struct patch *patch)
1018 patch->is_copy = 1;
1019 free(patch->new_name);
1020 patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1021 return 0;
1024 static int gitdiff_renamesrc(const char *line, struct patch *patch)
1026 patch->is_rename = 1;
1027 free(patch->old_name);
1028 patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1029 return 0;
1032 static int gitdiff_renamedst(const char *line, struct patch *patch)
1034 patch->is_rename = 1;
1035 free(patch->new_name);
1036 patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1037 return 0;
1040 static int gitdiff_similarity(const char *line, struct patch *patch)
1042 unsigned long val = strtoul(line, NULL, 10);
1043 if (val <= 100)
1044 patch->score = val;
1045 return 0;
1048 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
1050 unsigned long val = strtoul(line, NULL, 10);
1051 if (val <= 100)
1052 patch->score = val;
1053 return 0;
1056 static int gitdiff_index(const char *line, struct patch *patch)
1059 * index line is N hexadecimal, "..", N hexadecimal,
1060 * and optional space with octal mode.
1062 const char *ptr, *eol;
1063 int len;
1065 ptr = strchr(line, '.');
1066 if (!ptr || ptr[1] != '.' || 40 < ptr - line)
1067 return 0;
1068 len = ptr - line;
1069 memcpy(patch->old_sha1_prefix, line, len);
1070 patch->old_sha1_prefix[len] = 0;
1072 line = ptr + 2;
1073 ptr = strchr(line, ' ');
1074 eol = strchrnul(line, '\n');
1076 if (!ptr || eol < ptr)
1077 ptr = eol;
1078 len = ptr - line;
1080 if (40 < len)
1081 return 0;
1082 memcpy(patch->new_sha1_prefix, line, len);
1083 patch->new_sha1_prefix[len] = 0;
1084 if (*ptr == ' ')
1085 patch->old_mode = strtoul(ptr+1, NULL, 8);
1086 return 0;
1090 * This is normal for a diff that doesn't change anything: we'll fall through
1091 * into the next diff. Tell the parser to break out.
1093 static int gitdiff_unrecognized(const char *line, struct patch *patch)
1095 return -1;
1099 * Skip p_value leading components from "line"; as we do not accept
1100 * absolute paths, return NULL in that case.
1102 static const char *skip_tree_prefix(const char *line, int llen)
1104 int nslash;
1105 int i;
1107 if (!p_value)
1108 return (llen && line[0] == '/') ? NULL : line;
1110 nslash = p_value;
1111 for (i = 0; i < llen; i++) {
1112 int ch = line[i];
1113 if (ch == '/' && --nslash <= 0)
1114 return (i == 0) ? NULL : &line[i + 1];
1116 return NULL;
1120 * This is to extract the same name that appears on "diff --git"
1121 * line. We do not find and return anything if it is a rename
1122 * patch, and it is OK because we will find the name elsewhere.
1123 * We need to reliably find name only when it is mode-change only,
1124 * creation or deletion of an empty file. In any of these cases,
1125 * both sides are the same name under a/ and b/ respectively.
1127 static char *git_header_name(const char *line, int llen)
1129 const char *name;
1130 const char *second = NULL;
1131 size_t len, line_len;
1133 line += strlen("diff --git ");
1134 llen -= strlen("diff --git ");
1136 if (*line == '"') {
1137 const char *cp;
1138 struct strbuf first = STRBUF_INIT;
1139 struct strbuf sp = STRBUF_INIT;
1141 if (unquote_c_style(&first, line, &second))
1142 goto free_and_fail1;
1144 /* strip the a/b prefix including trailing slash */
1145 cp = skip_tree_prefix(first.buf, first.len);
1146 if (!cp)
1147 goto free_and_fail1;
1148 strbuf_remove(&first, 0, cp - first.buf);
1151 * second points at one past closing dq of name.
1152 * find the second name.
1154 while ((second < line + llen) && isspace(*second))
1155 second++;
1157 if (line + llen <= second)
1158 goto free_and_fail1;
1159 if (*second == '"') {
1160 if (unquote_c_style(&sp, second, NULL))
1161 goto free_and_fail1;
1162 cp = skip_tree_prefix(sp.buf, sp.len);
1163 if (!cp)
1164 goto free_and_fail1;
1165 /* They must match, otherwise ignore */
1166 if (strcmp(cp, first.buf))
1167 goto free_and_fail1;
1168 strbuf_release(&sp);
1169 return strbuf_detach(&first, NULL);
1172 /* unquoted second */
1173 cp = skip_tree_prefix(second, line + llen - second);
1174 if (!cp)
1175 goto free_and_fail1;
1176 if (line + llen - cp != first.len ||
1177 memcmp(first.buf, cp, first.len))
1178 goto free_and_fail1;
1179 return strbuf_detach(&first, NULL);
1181 free_and_fail1:
1182 strbuf_release(&first);
1183 strbuf_release(&sp);
1184 return NULL;
1187 /* unquoted first name */
1188 name = skip_tree_prefix(line, llen);
1189 if (!name)
1190 return NULL;
1193 * since the first name is unquoted, a dq if exists must be
1194 * the beginning of the second name.
1196 for (second = name; second < line + llen; second++) {
1197 if (*second == '"') {
1198 struct strbuf sp = STRBUF_INIT;
1199 const char *np;
1201 if (unquote_c_style(&sp, second, NULL))
1202 goto free_and_fail2;
1204 np = skip_tree_prefix(sp.buf, sp.len);
1205 if (!np)
1206 goto free_and_fail2;
1208 len = sp.buf + sp.len - np;
1209 if (len < second - name &&
1210 !strncmp(np, name, len) &&
1211 isspace(name[len])) {
1212 /* Good */
1213 strbuf_remove(&sp, 0, np - sp.buf);
1214 return strbuf_detach(&sp, NULL);
1217 free_and_fail2:
1218 strbuf_release(&sp);
1219 return NULL;
1224 * Accept a name only if it shows up twice, exactly the same
1225 * form.
1227 second = strchr(name, '\n');
1228 if (!second)
1229 return NULL;
1230 line_len = second - name;
1231 for (len = 0 ; ; len++) {
1232 switch (name[len]) {
1233 default:
1234 continue;
1235 case '\n':
1236 return NULL;
1237 case '\t': case ' ':
1239 * Is this the separator between the preimage
1240 * and the postimage pathname? Again, we are
1241 * only interested in the case where there is
1242 * no rename, as this is only to set def_name
1243 * and a rename patch has the names elsewhere
1244 * in an unambiguous form.
1246 if (!name[len + 1])
1247 return NULL; /* no postimage name */
1248 second = skip_tree_prefix(name + len + 1,
1249 line_len - (len + 1));
1250 if (!second)
1251 return NULL;
1253 * Does len bytes starting at "name" and "second"
1254 * (that are separated by one HT or SP we just
1255 * found) exactly match?
1257 if (second[len] == '\n' && !strncmp(name, second, len))
1258 return xmemdupz(name, len);
1263 /* Verify that we recognize the lines following a git header */
1264 static int parse_git_header(const char *line, int len, unsigned int size, struct patch *patch)
1266 unsigned long offset;
1268 /* A git diff has explicit new/delete information, so we don't guess */
1269 patch->is_new = 0;
1270 patch->is_delete = 0;
1273 * Some things may not have the old name in the
1274 * rest of the headers anywhere (pure mode changes,
1275 * or removing or adding empty files), so we get
1276 * the default name from the header.
1278 patch->def_name = git_header_name(line, len);
1279 if (patch->def_name && root) {
1280 char *s = xstrfmt("%s%s", root, patch->def_name);
1281 free(patch->def_name);
1282 patch->def_name = s;
1285 line += len;
1286 size -= len;
1287 linenr++;
1288 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
1289 static const struct opentry {
1290 const char *str;
1291 int (*fn)(const char *, struct patch *);
1292 } optable[] = {
1293 { "@@ -", gitdiff_hdrend },
1294 { "--- ", gitdiff_oldname },
1295 { "+++ ", gitdiff_newname },
1296 { "old mode ", gitdiff_oldmode },
1297 { "new mode ", gitdiff_newmode },
1298 { "deleted file mode ", gitdiff_delete },
1299 { "new file mode ", gitdiff_newfile },
1300 { "copy from ", gitdiff_copysrc },
1301 { "copy to ", gitdiff_copydst },
1302 { "rename old ", gitdiff_renamesrc },
1303 { "rename new ", gitdiff_renamedst },
1304 { "rename from ", gitdiff_renamesrc },
1305 { "rename to ", gitdiff_renamedst },
1306 { "similarity index ", gitdiff_similarity },
1307 { "dissimilarity index ", gitdiff_dissimilarity },
1308 { "index ", gitdiff_index },
1309 { "", gitdiff_unrecognized },
1311 int i;
1313 len = linelen(line, size);
1314 if (!len || line[len-1] != '\n')
1315 break;
1316 for (i = 0; i < ARRAY_SIZE(optable); i++) {
1317 const struct opentry *p = optable + i;
1318 int oplen = strlen(p->str);
1319 if (len < oplen || memcmp(p->str, line, oplen))
1320 continue;
1321 if (p->fn(line + oplen, patch) < 0)
1322 return offset;
1323 break;
1327 return offset;
1330 static int parse_num(const char *line, unsigned long *p)
1332 char *ptr;
1334 if (!isdigit(*line))
1335 return 0;
1336 *p = strtoul(line, &ptr, 10);
1337 return ptr - line;
1340 static int parse_range(const char *line, int len, int offset, const char *expect,
1341 unsigned long *p1, unsigned long *p2)
1343 int digits, ex;
1345 if (offset < 0 || offset >= len)
1346 return -1;
1347 line += offset;
1348 len -= offset;
1350 digits = parse_num(line, p1);
1351 if (!digits)
1352 return -1;
1354 offset += digits;
1355 line += digits;
1356 len -= digits;
1358 *p2 = 1;
1359 if (*line == ',') {
1360 digits = parse_num(line+1, p2);
1361 if (!digits)
1362 return -1;
1364 offset += digits+1;
1365 line += digits+1;
1366 len -= digits+1;
1369 ex = strlen(expect);
1370 if (ex > len)
1371 return -1;
1372 if (memcmp(line, expect, ex))
1373 return -1;
1375 return offset + ex;
1378 static void recount_diff(const char *line, int size, struct fragment *fragment)
1380 int oldlines = 0, newlines = 0, ret = 0;
1382 if (size < 1) {
1383 warning("recount: ignore empty hunk");
1384 return;
1387 for (;;) {
1388 int len = linelen(line, size);
1389 size -= len;
1390 line += len;
1392 if (size < 1)
1393 break;
1395 switch (*line) {
1396 case ' ': case '\n':
1397 newlines++;
1398 /* fall through */
1399 case '-':
1400 oldlines++;
1401 continue;
1402 case '+':
1403 newlines++;
1404 continue;
1405 case '\\':
1406 continue;
1407 case '@':
1408 ret = size < 3 || !starts_with(line, "@@ ");
1409 break;
1410 case 'd':
1411 ret = size < 5 || !starts_with(line, "diff ");
1412 break;
1413 default:
1414 ret = -1;
1415 break;
1417 if (ret) {
1418 warning(_("recount: unexpected line: %.*s"),
1419 (int)linelen(line, size), line);
1420 return;
1422 break;
1424 fragment->oldlines = oldlines;
1425 fragment->newlines = newlines;
1429 * Parse a unified diff fragment header of the
1430 * form "@@ -a,b +c,d @@"
1432 static int parse_fragment_header(const char *line, int len, struct fragment *fragment)
1434 int offset;
1436 if (!len || line[len-1] != '\n')
1437 return -1;
1439 /* Figure out the number of lines in a fragment */
1440 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1441 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1443 return offset;
1446 static int find_header(const char *line, unsigned long size, int *hdrsize, struct patch *patch)
1448 unsigned long offset, len;
1450 patch->is_toplevel_relative = 0;
1451 patch->is_rename = patch->is_copy = 0;
1452 patch->is_new = patch->is_delete = -1;
1453 patch->old_mode = patch->new_mode = 0;
1454 patch->old_name = patch->new_name = NULL;
1455 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
1456 unsigned long nextlen;
1458 len = linelen(line, size);
1459 if (!len)
1460 break;
1462 /* Testing this early allows us to take a few shortcuts.. */
1463 if (len < 6)
1464 continue;
1467 * Make sure we don't find any unconnected patch fragments.
1468 * That's a sign that we didn't find a header, and that a
1469 * patch has become corrupted/broken up.
1471 if (!memcmp("@@ -", line, 4)) {
1472 struct fragment dummy;
1473 if (parse_fragment_header(line, len, &dummy) < 0)
1474 continue;
1475 die(_("patch fragment without header at line %d: %.*s"),
1476 linenr, (int)len-1, line);
1479 if (size < len + 6)
1480 break;
1483 * Git patch? It might not have a real patch, just a rename
1484 * or mode change, so we handle that specially
1486 if (!memcmp("diff --git ", line, 11)) {
1487 int git_hdr_len = parse_git_header(line, len, size, patch);
1488 if (git_hdr_len <= len)
1489 continue;
1490 if (!patch->old_name && !patch->new_name) {
1491 if (!patch->def_name)
1492 die(Q_("git diff header lacks filename information when removing "
1493 "%d leading pathname component (line %d)",
1494 "git diff header lacks filename information when removing "
1495 "%d leading pathname components (line %d)",
1496 p_value),
1497 p_value, linenr);
1498 patch->old_name = xstrdup(patch->def_name);
1499 patch->new_name = xstrdup(patch->def_name);
1501 if (!patch->is_delete && !patch->new_name)
1502 die("git diff header lacks filename information "
1503 "(line %d)", linenr);
1504 patch->is_toplevel_relative = 1;
1505 *hdrsize = git_hdr_len;
1506 return offset;
1509 /* --- followed by +++ ? */
1510 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1511 continue;
1514 * We only accept unified patches, so we want it to
1515 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1516 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1518 nextlen = linelen(line + len, size - len);
1519 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1520 continue;
1522 /* Ok, we'll consider it a patch */
1523 parse_traditional_patch(line, line+len, patch);
1524 *hdrsize = len + nextlen;
1525 linenr += 2;
1526 return offset;
1528 return -1;
1531 static void record_ws_error(unsigned result, const char *line, int len, int linenr)
1533 char *err;
1535 if (!result)
1536 return;
1538 whitespace_error++;
1539 if (squelch_whitespace_errors &&
1540 squelch_whitespace_errors < whitespace_error)
1541 return;
1543 err = whitespace_error_string(result);
1544 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1545 patch_input_file, linenr, err, len, line);
1546 free(err);
1549 static void check_whitespace(const char *line, int len, unsigned ws_rule)
1551 unsigned result = ws_check(line + 1, len - 1, ws_rule);
1553 record_ws_error(result, line + 1, len - 2, linenr);
1557 * Parse a unified diff. Note that this really needs to parse each
1558 * fragment separately, since the only way to know the difference
1559 * between a "---" that is part of a patch, and a "---" that starts
1560 * the next patch is to look at the line counts..
1562 static int parse_fragment(const char *line, unsigned long size,
1563 struct patch *patch, struct fragment *fragment)
1565 int added, deleted;
1566 int len = linelen(line, size), offset;
1567 unsigned long oldlines, newlines;
1568 unsigned long leading, trailing;
1570 offset = parse_fragment_header(line, len, fragment);
1571 if (offset < 0)
1572 return -1;
1573 if (offset > 0 && patch->recount)
1574 recount_diff(line + offset, size - offset, fragment);
1575 oldlines = fragment->oldlines;
1576 newlines = fragment->newlines;
1577 leading = 0;
1578 trailing = 0;
1580 /* Parse the thing.. */
1581 line += len;
1582 size -= len;
1583 linenr++;
1584 added = deleted = 0;
1585 for (offset = len;
1586 0 < size;
1587 offset += len, size -= len, line += len, linenr++) {
1588 if (!oldlines && !newlines)
1589 break;
1590 len = linelen(line, size);
1591 if (!len || line[len-1] != '\n')
1592 return -1;
1593 switch (*line) {
1594 default:
1595 return -1;
1596 case '\n': /* newer GNU diff, an empty context line */
1597 case ' ':
1598 oldlines--;
1599 newlines--;
1600 if (!deleted && !added)
1601 leading++;
1602 trailing++;
1603 break;
1604 case '-':
1605 if (apply_in_reverse &&
1606 ws_error_action != nowarn_ws_error)
1607 check_whitespace(line, len, patch->ws_rule);
1608 deleted++;
1609 oldlines--;
1610 trailing = 0;
1611 break;
1612 case '+':
1613 if (!apply_in_reverse &&
1614 ws_error_action != nowarn_ws_error)
1615 check_whitespace(line, len, patch->ws_rule);
1616 added++;
1617 newlines--;
1618 trailing = 0;
1619 break;
1622 * We allow "\ No newline at end of file". Depending
1623 * on locale settings when the patch was produced we
1624 * don't know what this line looks like. The only
1625 * thing we do know is that it begins with "\ ".
1626 * Checking for 12 is just for sanity check -- any
1627 * l10n of "\ No newline..." is at least that long.
1629 case '\\':
1630 if (len < 12 || memcmp(line, "\\ ", 2))
1631 return -1;
1632 break;
1635 if (oldlines || newlines)
1636 return -1;
1637 fragment->leading = leading;
1638 fragment->trailing = trailing;
1641 * If a fragment ends with an incomplete line, we failed to include
1642 * it in the above loop because we hit oldlines == newlines == 0
1643 * before seeing it.
1645 if (12 < size && !memcmp(line, "\\ ", 2))
1646 offset += linelen(line, size);
1648 patch->lines_added += added;
1649 patch->lines_deleted += deleted;
1651 if (0 < patch->is_new && oldlines)
1652 return error(_("new file depends on old contents"));
1653 if (0 < patch->is_delete && newlines)
1654 return error(_("deleted file still has contents"));
1655 return offset;
1659 * We have seen "diff --git a/... b/..." header (or a traditional patch
1660 * header). Read hunks that belong to this patch into fragments and hang
1661 * them to the given patch structure.
1663 * The (fragment->patch, fragment->size) pair points into the memory given
1664 * by the caller, not a copy, when we return.
1666 static int parse_single_patch(const char *line, unsigned long size, struct patch *patch)
1668 unsigned long offset = 0;
1669 unsigned long oldlines = 0, newlines = 0, context = 0;
1670 struct fragment **fragp = &patch->fragments;
1672 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1673 struct fragment *fragment;
1674 int len;
1676 fragment = xcalloc(1, sizeof(*fragment));
1677 fragment->linenr = linenr;
1678 len = parse_fragment(line, size, patch, fragment);
1679 if (len <= 0)
1680 die(_("corrupt patch at line %d"), linenr);
1681 fragment->patch = line;
1682 fragment->size = len;
1683 oldlines += fragment->oldlines;
1684 newlines += fragment->newlines;
1685 context += fragment->leading + fragment->trailing;
1687 *fragp = fragment;
1688 fragp = &fragment->next;
1690 offset += len;
1691 line += len;
1692 size -= len;
1696 * If something was removed (i.e. we have old-lines) it cannot
1697 * be creation, and if something was added it cannot be
1698 * deletion. However, the reverse is not true; --unified=0
1699 * patches that only add are not necessarily creation even
1700 * though they do not have any old lines, and ones that only
1701 * delete are not necessarily deletion.
1703 * Unfortunately, a real creation/deletion patch do _not_ have
1704 * any context line by definition, so we cannot safely tell it
1705 * apart with --unified=0 insanity. At least if the patch has
1706 * more than one hunk it is not creation or deletion.
1708 if (patch->is_new < 0 &&
1709 (oldlines || (patch->fragments && patch->fragments->next)))
1710 patch->is_new = 0;
1711 if (patch->is_delete < 0 &&
1712 (newlines || (patch->fragments && patch->fragments->next)))
1713 patch->is_delete = 0;
1715 if (0 < patch->is_new && oldlines)
1716 die(_("new file %s depends on old contents"), patch->new_name);
1717 if (0 < patch->is_delete && newlines)
1718 die(_("deleted file %s still has contents"), patch->old_name);
1719 if (!patch->is_delete && !newlines && context)
1720 fprintf_ln(stderr,
1721 _("** warning: "
1722 "file %s becomes empty but is not deleted"),
1723 patch->new_name);
1725 return offset;
1728 static inline int metadata_changes(struct patch *patch)
1730 return patch->is_rename > 0 ||
1731 patch->is_copy > 0 ||
1732 patch->is_new > 0 ||
1733 patch->is_delete ||
1734 (patch->old_mode && patch->new_mode &&
1735 patch->old_mode != patch->new_mode);
1738 static char *inflate_it(const void *data, unsigned long size,
1739 unsigned long inflated_size)
1741 git_zstream stream;
1742 void *out;
1743 int st;
1745 memset(&stream, 0, sizeof(stream));
1747 stream.next_in = (unsigned char *)data;
1748 stream.avail_in = size;
1749 stream.next_out = out = xmalloc(inflated_size);
1750 stream.avail_out = inflated_size;
1751 git_inflate_init(&stream);
1752 st = git_inflate(&stream, Z_FINISH);
1753 git_inflate_end(&stream);
1754 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1755 free(out);
1756 return NULL;
1758 return out;
1762 * Read a binary hunk and return a new fragment; fragment->patch
1763 * points at an allocated memory that the caller must free, so
1764 * it is marked as "->free_patch = 1".
1766 static struct fragment *parse_binary_hunk(char **buf_p,
1767 unsigned long *sz_p,
1768 int *status_p,
1769 int *used_p)
1772 * Expect a line that begins with binary patch method ("literal"
1773 * or "delta"), followed by the length of data before deflating.
1774 * a sequence of 'length-byte' followed by base-85 encoded data
1775 * should follow, terminated by a newline.
1777 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1778 * and we would limit the patch line to 66 characters,
1779 * so one line can fit up to 13 groups that would decode
1780 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1781 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1783 int llen, used;
1784 unsigned long size = *sz_p;
1785 char *buffer = *buf_p;
1786 int patch_method;
1787 unsigned long origlen;
1788 char *data = NULL;
1789 int hunk_size = 0;
1790 struct fragment *frag;
1792 llen = linelen(buffer, size);
1793 used = llen;
1795 *status_p = 0;
1797 if (starts_with(buffer, "delta ")) {
1798 patch_method = BINARY_DELTA_DEFLATED;
1799 origlen = strtoul(buffer + 6, NULL, 10);
1801 else if (starts_with(buffer, "literal ")) {
1802 patch_method = BINARY_LITERAL_DEFLATED;
1803 origlen = strtoul(buffer + 8, NULL, 10);
1805 else
1806 return NULL;
1808 linenr++;
1809 buffer += llen;
1810 while (1) {
1811 int byte_length, max_byte_length, newsize;
1812 llen = linelen(buffer, size);
1813 used += llen;
1814 linenr++;
1815 if (llen == 1) {
1816 /* consume the blank line */
1817 buffer++;
1818 size--;
1819 break;
1822 * Minimum line is "A00000\n" which is 7-byte long,
1823 * and the line length must be multiple of 5 plus 2.
1825 if ((llen < 7) || (llen-2) % 5)
1826 goto corrupt;
1827 max_byte_length = (llen - 2) / 5 * 4;
1828 byte_length = *buffer;
1829 if ('A' <= byte_length && byte_length <= 'Z')
1830 byte_length = byte_length - 'A' + 1;
1831 else if ('a' <= byte_length && byte_length <= 'z')
1832 byte_length = byte_length - 'a' + 27;
1833 else
1834 goto corrupt;
1835 /* if the input length was not multiple of 4, we would
1836 * have filler at the end but the filler should never
1837 * exceed 3 bytes
1839 if (max_byte_length < byte_length ||
1840 byte_length <= max_byte_length - 4)
1841 goto corrupt;
1842 newsize = hunk_size + byte_length;
1843 data = xrealloc(data, newsize);
1844 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1845 goto corrupt;
1846 hunk_size = newsize;
1847 buffer += llen;
1848 size -= llen;
1851 frag = xcalloc(1, sizeof(*frag));
1852 frag->patch = inflate_it(data, hunk_size, origlen);
1853 frag->free_patch = 1;
1854 if (!frag->patch)
1855 goto corrupt;
1856 free(data);
1857 frag->size = origlen;
1858 *buf_p = buffer;
1859 *sz_p = size;
1860 *used_p = used;
1861 frag->binary_patch_method = patch_method;
1862 return frag;
1864 corrupt:
1865 free(data);
1866 *status_p = -1;
1867 error(_("corrupt binary patch at line %d: %.*s"),
1868 linenr-1, llen-1, buffer);
1869 return NULL;
1872 static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1875 * We have read "GIT binary patch\n"; what follows is a line
1876 * that says the patch method (currently, either "literal" or
1877 * "delta") and the length of data before deflating; a
1878 * sequence of 'length-byte' followed by base-85 encoded data
1879 * follows.
1881 * When a binary patch is reversible, there is another binary
1882 * hunk in the same format, starting with patch method (either
1883 * "literal" or "delta") with the length of data, and a sequence
1884 * of length-byte + base-85 encoded data, terminated with another
1885 * empty line. This data, when applied to the postimage, produces
1886 * the preimage.
1888 struct fragment *forward;
1889 struct fragment *reverse;
1890 int status;
1891 int used, used_1;
1893 forward = parse_binary_hunk(&buffer, &size, &status, &used);
1894 if (!forward && !status)
1895 /* there has to be one hunk (forward hunk) */
1896 return error(_("unrecognized binary patch at line %d"), linenr-1);
1897 if (status)
1898 /* otherwise we already gave an error message */
1899 return status;
1901 reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1902 if (reverse)
1903 used += used_1;
1904 else if (status) {
1906 * Not having reverse hunk is not an error, but having
1907 * a corrupt reverse hunk is.
1909 free((void*) forward->patch);
1910 free(forward);
1911 return status;
1913 forward->next = reverse;
1914 patch->fragments = forward;
1915 patch->is_binary = 1;
1916 return used;
1919 static void prefix_one(char **name)
1921 char *old_name = *name;
1922 if (!old_name)
1923 return;
1924 *name = xstrdup(prefix_filename(prefix, prefix_length, *name));
1925 free(old_name);
1928 static void prefix_patch(struct patch *p)
1930 if (!prefix || p->is_toplevel_relative)
1931 return;
1932 prefix_one(&p->new_name);
1933 prefix_one(&p->old_name);
1937 * include/exclude
1940 static struct string_list limit_by_name;
1941 static int has_include;
1942 static void add_name_limit(const char *name, int exclude)
1944 struct string_list_item *it;
1946 it = string_list_append(&limit_by_name, name);
1947 it->util = exclude ? NULL : (void *) 1;
1950 static int use_patch(struct patch *p)
1952 const char *pathname = p->new_name ? p->new_name : p->old_name;
1953 int i;
1955 /* Paths outside are not touched regardless of "--include" */
1956 if (0 < prefix_length) {
1957 int pathlen = strlen(pathname);
1958 if (pathlen <= prefix_length ||
1959 memcmp(prefix, pathname, prefix_length))
1960 return 0;
1963 /* See if it matches any of exclude/include rule */
1964 for (i = 0; i < limit_by_name.nr; i++) {
1965 struct string_list_item *it = &limit_by_name.items[i];
1966 if (!wildmatch(it->string, pathname, 0, NULL))
1967 return (it->util != NULL);
1971 * If we had any include, a path that does not match any rule is
1972 * not used. Otherwise, we saw bunch of exclude rules (or none)
1973 * and such a path is used.
1975 return !has_include;
1980 * Read the patch text in "buffer" that extends for "size" bytes; stop
1981 * reading after seeing a single patch (i.e. changes to a single file).
1982 * Create fragments (i.e. patch hunks) and hang them to the given patch.
1983 * Return the number of bytes consumed, so that the caller can call us
1984 * again for the next patch.
1986 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
1988 int hdrsize, patchsize;
1989 int offset = find_header(buffer, size, &hdrsize, patch);
1991 if (offset < 0)
1992 return offset;
1994 prefix_patch(patch);
1996 if (!use_patch(patch))
1997 patch->ws_rule = 0;
1998 else
1999 patch->ws_rule = whitespace_rule(patch->new_name
2000 ? patch->new_name
2001 : patch->old_name);
2003 patchsize = parse_single_patch(buffer + offset + hdrsize,
2004 size - offset - hdrsize, patch);
2006 if (!patchsize) {
2007 static const char git_binary[] = "GIT binary patch\n";
2008 int hd = hdrsize + offset;
2009 unsigned long llen = linelen(buffer + hd, size - hd);
2011 if (llen == sizeof(git_binary) - 1 &&
2012 !memcmp(git_binary, buffer + hd, llen)) {
2013 int used;
2014 linenr++;
2015 used = parse_binary(buffer + hd + llen,
2016 size - hd - llen, patch);
2017 if (used)
2018 patchsize = used + llen;
2019 else
2020 patchsize = 0;
2022 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
2023 static const char *binhdr[] = {
2024 "Binary files ",
2025 "Files ",
2026 NULL,
2028 int i;
2029 for (i = 0; binhdr[i]; i++) {
2030 int len = strlen(binhdr[i]);
2031 if (len < size - hd &&
2032 !memcmp(binhdr[i], buffer + hd, len)) {
2033 linenr++;
2034 patch->is_binary = 1;
2035 patchsize = llen;
2036 break;
2041 /* Empty patch cannot be applied if it is a text patch
2042 * without metadata change. A binary patch appears
2043 * empty to us here.
2045 if ((apply || check) &&
2046 (!patch->is_binary && !metadata_changes(patch)))
2047 die(_("patch with only garbage at line %d"), linenr);
2050 return offset + hdrsize + patchsize;
2053 #define swap(a,b) myswap((a),(b),sizeof(a))
2055 #define myswap(a, b, size) do { \
2056 unsigned char mytmp[size]; \
2057 memcpy(mytmp, &a, size); \
2058 memcpy(&a, &b, size); \
2059 memcpy(&b, mytmp, size); \
2060 } while (0)
2062 static void reverse_patches(struct patch *p)
2064 for (; p; p = p->next) {
2065 struct fragment *frag = p->fragments;
2067 swap(p->new_name, p->old_name);
2068 swap(p->new_mode, p->old_mode);
2069 swap(p->is_new, p->is_delete);
2070 swap(p->lines_added, p->lines_deleted);
2071 swap(p->old_sha1_prefix, p->new_sha1_prefix);
2073 for (; frag; frag = frag->next) {
2074 swap(frag->newpos, frag->oldpos);
2075 swap(frag->newlines, frag->oldlines);
2080 static const char pluses[] =
2081 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2082 static const char minuses[]=
2083 "----------------------------------------------------------------------";
2085 static void show_stats(struct patch *patch)
2087 struct strbuf qname = STRBUF_INIT;
2088 char *cp = patch->new_name ? patch->new_name : patch->old_name;
2089 int max, add, del;
2091 quote_c_style(cp, &qname, NULL, 0);
2094 * "scale" the filename
2096 max = max_len;
2097 if (max > 50)
2098 max = 50;
2100 if (qname.len > max) {
2101 cp = strchr(qname.buf + qname.len + 3 - max, '/');
2102 if (!cp)
2103 cp = qname.buf + qname.len + 3 - max;
2104 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
2107 if (patch->is_binary) {
2108 printf(" %-*s | Bin\n", max, qname.buf);
2109 strbuf_release(&qname);
2110 return;
2113 printf(" %-*s |", max, qname.buf);
2114 strbuf_release(&qname);
2117 * scale the add/delete
2119 max = max + max_change > 70 ? 70 - max : max_change;
2120 add = patch->lines_added;
2121 del = patch->lines_deleted;
2123 if (max_change > 0) {
2124 int total = ((add + del) * max + max_change / 2) / max_change;
2125 add = (add * max + max_change / 2) / max_change;
2126 del = total - add;
2128 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
2129 add, pluses, del, minuses);
2132 static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
2134 switch (st->st_mode & S_IFMT) {
2135 case S_IFLNK:
2136 if (strbuf_readlink(buf, path, st->st_size) < 0)
2137 return error(_("unable to read symlink %s"), path);
2138 return 0;
2139 case S_IFREG:
2140 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
2141 return error(_("unable to open or read %s"), path);
2142 convert_to_git(path, buf->buf, buf->len, buf, 0);
2143 return 0;
2144 default:
2145 return -1;
2150 * Update the preimage, and the common lines in postimage,
2151 * from buffer buf of length len. If postlen is 0 the postimage
2152 * is updated in place, otherwise it's updated on a new buffer
2153 * of length postlen
2156 static void update_pre_post_images(struct image *preimage,
2157 struct image *postimage,
2158 char *buf,
2159 size_t len, size_t postlen)
2161 int i, ctx, reduced;
2162 char *new, *old, *fixed;
2163 struct image fixed_preimage;
2166 * Update the preimage with whitespace fixes. Note that we
2167 * are not losing preimage->buf -- apply_one_fragment() will
2168 * free "oldlines".
2170 prepare_image(&fixed_preimage, buf, len, 1);
2171 assert(postlen
2172 ? fixed_preimage.nr == preimage->nr
2173 : fixed_preimage.nr <= preimage->nr);
2174 for (i = 0; i < fixed_preimage.nr; i++)
2175 fixed_preimage.line[i].flag = preimage->line[i].flag;
2176 free(preimage->line_allocated);
2177 *preimage = fixed_preimage;
2180 * Adjust the common context lines in postimage. This can be
2181 * done in-place when we are shrinking it with whitespace
2182 * fixing, but needs a new buffer when ignoring whitespace or
2183 * expanding leading tabs to spaces.
2185 * We trust the caller to tell us if the update can be done
2186 * in place (postlen==0) or not.
2188 old = postimage->buf;
2189 if (postlen)
2190 new = postimage->buf = xmalloc(postlen);
2191 else
2192 new = old;
2193 fixed = preimage->buf;
2195 for (i = reduced = ctx = 0; i < postimage->nr; i++) {
2196 size_t len = postimage->line[i].len;
2197 if (!(postimage->line[i].flag & LINE_COMMON)) {
2198 /* an added line -- no counterparts in preimage */
2199 memmove(new, old, len);
2200 old += len;
2201 new += len;
2202 continue;
2205 /* a common context -- skip it in the original postimage */
2206 old += len;
2208 /* and find the corresponding one in the fixed preimage */
2209 while (ctx < preimage->nr &&
2210 !(preimage->line[ctx].flag & LINE_COMMON)) {
2211 fixed += preimage->line[ctx].len;
2212 ctx++;
2216 * preimage is expected to run out, if the caller
2217 * fixed addition of trailing blank lines.
2219 if (preimage->nr <= ctx) {
2220 reduced++;
2221 continue;
2224 /* and copy it in, while fixing the line length */
2225 len = preimage->line[ctx].len;
2226 memcpy(new, fixed, len);
2227 new += len;
2228 fixed += len;
2229 postimage->line[i].len = len;
2230 ctx++;
2233 /* Fix the length of the whole thing */
2234 postimage->len = new - postimage->buf;
2235 postimage->nr -= reduced;
2238 static int match_fragment(struct image *img,
2239 struct image *preimage,
2240 struct image *postimage,
2241 unsigned long try,
2242 int try_lno,
2243 unsigned ws_rule,
2244 int match_beginning, int match_end)
2246 int i;
2247 char *fixed_buf, *buf, *orig, *target;
2248 struct strbuf fixed;
2249 size_t fixed_len, postlen;
2250 int preimage_limit;
2252 if (preimage->nr + try_lno <= img->nr) {
2254 * The hunk falls within the boundaries of img.
2256 preimage_limit = preimage->nr;
2257 if (match_end && (preimage->nr + try_lno != img->nr))
2258 return 0;
2259 } else if (ws_error_action == correct_ws_error &&
2260 (ws_rule & WS_BLANK_AT_EOF)) {
2262 * This hunk extends beyond the end of img, and we are
2263 * removing blank lines at the end of the file. This
2264 * many lines from the beginning of the preimage must
2265 * match with img, and the remainder of the preimage
2266 * must be blank.
2268 preimage_limit = img->nr - try_lno;
2269 } else {
2271 * The hunk extends beyond the end of the img and
2272 * we are not removing blanks at the end, so we
2273 * should reject the hunk at this position.
2275 return 0;
2278 if (match_beginning && try_lno)
2279 return 0;
2281 /* Quick hash check */
2282 for (i = 0; i < preimage_limit; i++)
2283 if ((img->line[try_lno + i].flag & LINE_PATCHED) ||
2284 (preimage->line[i].hash != img->line[try_lno + i].hash))
2285 return 0;
2287 if (preimage_limit == preimage->nr) {
2289 * Do we have an exact match? If we were told to match
2290 * at the end, size must be exactly at try+fragsize,
2291 * otherwise try+fragsize must be still within the preimage,
2292 * and either case, the old piece should match the preimage
2293 * exactly.
2295 if ((match_end
2296 ? (try + preimage->len == img->len)
2297 : (try + preimage->len <= img->len)) &&
2298 !memcmp(img->buf + try, preimage->buf, preimage->len))
2299 return 1;
2300 } else {
2302 * The preimage extends beyond the end of img, so
2303 * there cannot be an exact match.
2305 * There must be one non-blank context line that match
2306 * a line before the end of img.
2308 char *buf_end;
2310 buf = preimage->buf;
2311 buf_end = buf;
2312 for (i = 0; i < preimage_limit; i++)
2313 buf_end += preimage->line[i].len;
2315 for ( ; buf < buf_end; buf++)
2316 if (!isspace(*buf))
2317 break;
2318 if (buf == buf_end)
2319 return 0;
2323 * No exact match. If we are ignoring whitespace, run a line-by-line
2324 * fuzzy matching. We collect all the line length information because
2325 * we need it to adjust whitespace if we match.
2327 if (ws_ignore_action == ignore_ws_change) {
2328 size_t imgoff = 0;
2329 size_t preoff = 0;
2330 size_t postlen = postimage->len;
2331 size_t extra_chars;
2332 char *preimage_eof;
2333 char *preimage_end;
2334 for (i = 0; i < preimage_limit; i++) {
2335 size_t prelen = preimage->line[i].len;
2336 size_t imglen = img->line[try_lno+i].len;
2338 if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,
2339 preimage->buf + preoff, prelen))
2340 return 0;
2341 if (preimage->line[i].flag & LINE_COMMON)
2342 postlen += imglen - prelen;
2343 imgoff += imglen;
2344 preoff += prelen;
2348 * Ok, the preimage matches with whitespace fuzz.
2350 * imgoff now holds the true length of the target that
2351 * matches the preimage before the end of the file.
2353 * Count the number of characters in the preimage that fall
2354 * beyond the end of the file and make sure that all of them
2355 * are whitespace characters. (This can only happen if
2356 * we are removing blank lines at the end of the file.)
2358 buf = preimage_eof = preimage->buf + preoff;
2359 for ( ; i < preimage->nr; i++)
2360 preoff += preimage->line[i].len;
2361 preimage_end = preimage->buf + preoff;
2362 for ( ; buf < preimage_end; buf++)
2363 if (!isspace(*buf))
2364 return 0;
2367 * Update the preimage and the common postimage context
2368 * lines to use the same whitespace as the target.
2369 * If whitespace is missing in the target (i.e.
2370 * if the preimage extends beyond the end of the file),
2371 * use the whitespace from the preimage.
2373 extra_chars = preimage_end - preimage_eof;
2374 strbuf_init(&fixed, imgoff + extra_chars);
2375 strbuf_add(&fixed, img->buf + try, imgoff);
2376 strbuf_add(&fixed, preimage_eof, extra_chars);
2377 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2378 update_pre_post_images(preimage, postimage,
2379 fixed_buf, fixed_len, postlen);
2380 return 1;
2383 if (ws_error_action != correct_ws_error)
2384 return 0;
2387 * The hunk does not apply byte-by-byte, but the hash says
2388 * it might with whitespace fuzz. We haven't been asked to
2389 * ignore whitespace, we were asked to correct whitespace
2390 * errors, so let's try matching after whitespace correction.
2392 * The preimage may extend beyond the end of the file,
2393 * but in this loop we will only handle the part of the
2394 * preimage that falls within the file.
2396 strbuf_init(&fixed, preimage->len + 1);
2397 orig = preimage->buf;
2398 target = img->buf + try;
2399 postlen = 0;
2400 for (i = 0; i < preimage_limit; i++) {
2401 size_t oldlen = preimage->line[i].len;
2402 size_t tgtlen = img->line[try_lno + i].len;
2403 size_t fixstart = fixed.len;
2404 struct strbuf tgtfix;
2405 int match;
2407 /* Try fixing the line in the preimage */
2408 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2410 /* Try fixing the line in the target */
2411 strbuf_init(&tgtfix, tgtlen);
2412 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2415 * If they match, either the preimage was based on
2416 * a version before our tree fixed whitespace breakage,
2417 * or we are lacking a whitespace-fix patch the tree
2418 * the preimage was based on already had (i.e. target
2419 * has whitespace breakage, the preimage doesn't).
2420 * In either case, we are fixing the whitespace breakages
2421 * so we might as well take the fix together with their
2422 * real change.
2424 match = (tgtfix.len == fixed.len - fixstart &&
2425 !memcmp(tgtfix.buf, fixed.buf + fixstart,
2426 fixed.len - fixstart));
2427 postlen += tgtfix.len;
2429 strbuf_release(&tgtfix);
2430 if (!match)
2431 goto unmatch_exit;
2433 orig += oldlen;
2434 target += tgtlen;
2439 * Now handle the lines in the preimage that falls beyond the
2440 * end of the file (if any). They will only match if they are
2441 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2442 * false).
2444 for ( ; i < preimage->nr; i++) {
2445 size_t fixstart = fixed.len; /* start of the fixed preimage */
2446 size_t oldlen = preimage->line[i].len;
2447 int j;
2449 /* Try fixing the line in the preimage */
2450 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2452 for (j = fixstart; j < fixed.len; j++)
2453 if (!isspace(fixed.buf[j]))
2454 goto unmatch_exit;
2456 orig += oldlen;
2460 * Yes, the preimage is based on an older version that still
2461 * has whitespace breakages unfixed, and fixing them makes the
2462 * hunk match. Update the context lines in the postimage.
2464 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2465 if (postlen < postimage->len)
2466 postlen = 0;
2467 update_pre_post_images(preimage, postimage,
2468 fixed_buf, fixed_len, postlen);
2469 return 1;
2471 unmatch_exit:
2472 strbuf_release(&fixed);
2473 return 0;
2476 static int find_pos(struct image *img,
2477 struct image *preimage,
2478 struct image *postimage,
2479 int line,
2480 unsigned ws_rule,
2481 int match_beginning, int match_end)
2483 int i;
2484 unsigned long backwards, forwards, try;
2485 int backwards_lno, forwards_lno, try_lno;
2488 * If match_beginning or match_end is specified, there is no
2489 * point starting from a wrong line that will never match and
2490 * wander around and wait for a match at the specified end.
2492 if (match_beginning)
2493 line = 0;
2494 else if (match_end)
2495 line = img->nr - preimage->nr;
2498 * Because the comparison is unsigned, the following test
2499 * will also take care of a negative line number that can
2500 * result when match_end and preimage is larger than the target.
2502 if ((size_t) line > img->nr)
2503 line = img->nr;
2505 try = 0;
2506 for (i = 0; i < line; i++)
2507 try += img->line[i].len;
2510 * There's probably some smart way to do this, but I'll leave
2511 * that to the smart and beautiful people. I'm simple and stupid.
2513 backwards = try;
2514 backwards_lno = line;
2515 forwards = try;
2516 forwards_lno = line;
2517 try_lno = line;
2519 for (i = 0; ; i++) {
2520 if (match_fragment(img, preimage, postimage,
2521 try, try_lno, ws_rule,
2522 match_beginning, match_end))
2523 return try_lno;
2525 again:
2526 if (backwards_lno == 0 && forwards_lno == img->nr)
2527 break;
2529 if (i & 1) {
2530 if (backwards_lno == 0) {
2531 i++;
2532 goto again;
2534 backwards_lno--;
2535 backwards -= img->line[backwards_lno].len;
2536 try = backwards;
2537 try_lno = backwards_lno;
2538 } else {
2539 if (forwards_lno == img->nr) {
2540 i++;
2541 goto again;
2543 forwards += img->line[forwards_lno].len;
2544 forwards_lno++;
2545 try = forwards;
2546 try_lno = forwards_lno;
2550 return -1;
2553 static void remove_first_line(struct image *img)
2555 img->buf += img->line[0].len;
2556 img->len -= img->line[0].len;
2557 img->line++;
2558 img->nr--;
2561 static void remove_last_line(struct image *img)
2563 img->len -= img->line[--img->nr].len;
2567 * The change from "preimage" and "postimage" has been found to
2568 * apply at applied_pos (counts in line numbers) in "img".
2569 * Update "img" to remove "preimage" and replace it with "postimage".
2571 static void update_image(struct image *img,
2572 int applied_pos,
2573 struct image *preimage,
2574 struct image *postimage)
2577 * remove the copy of preimage at offset in img
2578 * and replace it with postimage
2580 int i, nr;
2581 size_t remove_count, insert_count, applied_at = 0;
2582 char *result;
2583 int preimage_limit;
2586 * If we are removing blank lines at the end of img,
2587 * the preimage may extend beyond the end.
2588 * If that is the case, we must be careful only to
2589 * remove the part of the preimage that falls within
2590 * the boundaries of img. Initialize preimage_limit
2591 * to the number of lines in the preimage that falls
2592 * within the boundaries.
2594 preimage_limit = preimage->nr;
2595 if (preimage_limit > img->nr - applied_pos)
2596 preimage_limit = img->nr - applied_pos;
2598 for (i = 0; i < applied_pos; i++)
2599 applied_at += img->line[i].len;
2601 remove_count = 0;
2602 for (i = 0; i < preimage_limit; i++)
2603 remove_count += img->line[applied_pos + i].len;
2604 insert_count = postimage->len;
2606 /* Adjust the contents */
2607 result = xmalloc(img->len + insert_count - remove_count + 1);
2608 memcpy(result, img->buf, applied_at);
2609 memcpy(result + applied_at, postimage->buf, postimage->len);
2610 memcpy(result + applied_at + postimage->len,
2611 img->buf + (applied_at + remove_count),
2612 img->len - (applied_at + remove_count));
2613 free(img->buf);
2614 img->buf = result;
2615 img->len += insert_count - remove_count;
2616 result[img->len] = '\0';
2618 /* Adjust the line table */
2619 nr = img->nr + postimage->nr - preimage_limit;
2620 if (preimage_limit < postimage->nr) {
2622 * NOTE: this knows that we never call remove_first_line()
2623 * on anything other than pre/post image.
2625 REALLOC_ARRAY(img->line, nr);
2626 img->line_allocated = img->line;
2628 if (preimage_limit != postimage->nr)
2629 memmove(img->line + applied_pos + postimage->nr,
2630 img->line + applied_pos + preimage_limit,
2631 (img->nr - (applied_pos + preimage_limit)) *
2632 sizeof(*img->line));
2633 memcpy(img->line + applied_pos,
2634 postimage->line,
2635 postimage->nr * sizeof(*img->line));
2636 if (!allow_overlap)
2637 for (i = 0; i < postimage->nr; i++)
2638 img->line[applied_pos + i].flag |= LINE_PATCHED;
2639 img->nr = nr;
2643 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2644 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2645 * replace the part of "img" with "postimage" text.
2647 static int apply_one_fragment(struct image *img, struct fragment *frag,
2648 int inaccurate_eof, unsigned ws_rule,
2649 int nth_fragment)
2651 int match_beginning, match_end;
2652 const char *patch = frag->patch;
2653 int size = frag->size;
2654 char *old, *oldlines;
2655 struct strbuf newlines;
2656 int new_blank_lines_at_end = 0;
2657 int found_new_blank_lines_at_end = 0;
2658 int hunk_linenr = frag->linenr;
2659 unsigned long leading, trailing;
2660 int pos, applied_pos;
2661 struct image preimage;
2662 struct image postimage;
2664 memset(&preimage, 0, sizeof(preimage));
2665 memset(&postimage, 0, sizeof(postimage));
2666 oldlines = xmalloc(size);
2667 strbuf_init(&newlines, size);
2669 old = oldlines;
2670 while (size > 0) {
2671 char first;
2672 int len = linelen(patch, size);
2673 int plen;
2674 int added_blank_line = 0;
2675 int is_blank_context = 0;
2676 size_t start;
2678 if (!len)
2679 break;
2682 * "plen" is how much of the line we should use for
2683 * the actual patch data. Normally we just remove the
2684 * first character on the line, but if the line is
2685 * followed by "\ No newline", then we also remove the
2686 * last one (which is the newline, of course).
2688 plen = len - 1;
2689 if (len < size && patch[len] == '\\')
2690 plen--;
2691 first = *patch;
2692 if (apply_in_reverse) {
2693 if (first == '-')
2694 first = '+';
2695 else if (first == '+')
2696 first = '-';
2699 switch (first) {
2700 case '\n':
2701 /* Newer GNU diff, empty context line */
2702 if (plen < 0)
2703 /* ... followed by '\No newline'; nothing */
2704 break;
2705 *old++ = '\n';
2706 strbuf_addch(&newlines, '\n');
2707 add_line_info(&preimage, "\n", 1, LINE_COMMON);
2708 add_line_info(&postimage, "\n", 1, LINE_COMMON);
2709 is_blank_context = 1;
2710 break;
2711 case ' ':
2712 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2713 ws_blank_line(patch + 1, plen, ws_rule))
2714 is_blank_context = 1;
2715 case '-':
2716 memcpy(old, patch + 1, plen);
2717 add_line_info(&preimage, old, plen,
2718 (first == ' ' ? LINE_COMMON : 0));
2719 old += plen;
2720 if (first == '-')
2721 break;
2722 /* Fall-through for ' ' */
2723 case '+':
2724 /* --no-add does not add new lines */
2725 if (first == '+' && no_add)
2726 break;
2728 start = newlines.len;
2729 if (first != '+' ||
2730 !whitespace_error ||
2731 ws_error_action != correct_ws_error) {
2732 strbuf_add(&newlines, patch + 1, plen);
2734 else {
2735 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &applied_after_fixing_ws);
2737 add_line_info(&postimage, newlines.buf + start, newlines.len - start,
2738 (first == '+' ? 0 : LINE_COMMON));
2739 if (first == '+' &&
2740 (ws_rule & WS_BLANK_AT_EOF) &&
2741 ws_blank_line(patch + 1, plen, ws_rule))
2742 added_blank_line = 1;
2743 break;
2744 case '@': case '\\':
2745 /* Ignore it, we already handled it */
2746 break;
2747 default:
2748 if (apply_verbosely)
2749 error(_("invalid start of line: '%c'"), first);
2750 return -1;
2752 if (added_blank_line) {
2753 if (!new_blank_lines_at_end)
2754 found_new_blank_lines_at_end = hunk_linenr;
2755 new_blank_lines_at_end++;
2757 else if (is_blank_context)
2759 else
2760 new_blank_lines_at_end = 0;
2761 patch += len;
2762 size -= len;
2763 hunk_linenr++;
2765 if (inaccurate_eof &&
2766 old > oldlines && old[-1] == '\n' &&
2767 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
2768 old--;
2769 strbuf_setlen(&newlines, newlines.len - 1);
2772 leading = frag->leading;
2773 trailing = frag->trailing;
2776 * A hunk to change lines at the beginning would begin with
2777 * @@ -1,L +N,M @@
2778 * but we need to be careful. -U0 that inserts before the second
2779 * line also has this pattern.
2781 * And a hunk to add to an empty file would begin with
2782 * @@ -0,0 +N,M @@
2784 * In other words, a hunk that is (frag->oldpos <= 1) with or
2785 * without leading context must match at the beginning.
2787 match_beginning = (!frag->oldpos ||
2788 (frag->oldpos == 1 && !unidiff_zero));
2791 * A hunk without trailing lines must match at the end.
2792 * However, we simply cannot tell if a hunk must match end
2793 * from the lack of trailing lines if the patch was generated
2794 * with unidiff without any context.
2796 match_end = !unidiff_zero && !trailing;
2798 pos = frag->newpos ? (frag->newpos - 1) : 0;
2799 preimage.buf = oldlines;
2800 preimage.len = old - oldlines;
2801 postimage.buf = newlines.buf;
2802 postimage.len = newlines.len;
2803 preimage.line = preimage.line_allocated;
2804 postimage.line = postimage.line_allocated;
2806 for (;;) {
2808 applied_pos = find_pos(img, &preimage, &postimage, pos,
2809 ws_rule, match_beginning, match_end);
2811 if (applied_pos >= 0)
2812 break;
2814 /* Am I at my context limits? */
2815 if ((leading <= p_context) && (trailing <= p_context))
2816 break;
2817 if (match_beginning || match_end) {
2818 match_beginning = match_end = 0;
2819 continue;
2823 * Reduce the number of context lines; reduce both
2824 * leading and trailing if they are equal otherwise
2825 * just reduce the larger context.
2827 if (leading >= trailing) {
2828 remove_first_line(&preimage);
2829 remove_first_line(&postimage);
2830 pos--;
2831 leading--;
2833 if (trailing > leading) {
2834 remove_last_line(&preimage);
2835 remove_last_line(&postimage);
2836 trailing--;
2840 if (applied_pos >= 0) {
2841 if (new_blank_lines_at_end &&
2842 preimage.nr + applied_pos >= img->nr &&
2843 (ws_rule & WS_BLANK_AT_EOF) &&
2844 ws_error_action != nowarn_ws_error) {
2845 record_ws_error(WS_BLANK_AT_EOF, "+", 1,
2846 found_new_blank_lines_at_end);
2847 if (ws_error_action == correct_ws_error) {
2848 while (new_blank_lines_at_end--)
2849 remove_last_line(&postimage);
2852 * We would want to prevent write_out_results()
2853 * from taking place in apply_patch() that follows
2854 * the callchain led us here, which is:
2855 * apply_patch->check_patch_list->check_patch->
2856 * apply_data->apply_fragments->apply_one_fragment
2858 if (ws_error_action == die_on_ws_error)
2859 apply = 0;
2862 if (apply_verbosely && applied_pos != pos) {
2863 int offset = applied_pos - pos;
2864 if (apply_in_reverse)
2865 offset = 0 - offset;
2866 fprintf_ln(stderr,
2867 Q_("Hunk #%d succeeded at %d (offset %d line).",
2868 "Hunk #%d succeeded at %d (offset %d lines).",
2869 offset),
2870 nth_fragment, applied_pos + 1, offset);
2874 * Warn if it was necessary to reduce the number
2875 * of context lines.
2877 if ((leading != frag->leading) ||
2878 (trailing != frag->trailing))
2879 fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"
2880 " to apply fragment at %d"),
2881 leading, trailing, applied_pos+1);
2882 update_image(img, applied_pos, &preimage, &postimage);
2883 } else {
2884 if (apply_verbosely)
2885 error(_("while searching for:\n%.*s"),
2886 (int)(old - oldlines), oldlines);
2889 free(oldlines);
2890 strbuf_release(&newlines);
2891 free(preimage.line_allocated);
2892 free(postimage.line_allocated);
2894 return (applied_pos < 0);
2897 static int apply_binary_fragment(struct image *img, struct patch *patch)
2899 struct fragment *fragment = patch->fragments;
2900 unsigned long len;
2901 void *dst;
2903 if (!fragment)
2904 return error(_("missing binary patch data for '%s'"),
2905 patch->new_name ?
2906 patch->new_name :
2907 patch->old_name);
2909 /* Binary patch is irreversible without the optional second hunk */
2910 if (apply_in_reverse) {
2911 if (!fragment->next)
2912 return error("cannot reverse-apply a binary patch "
2913 "without the reverse hunk to '%s'",
2914 patch->new_name
2915 ? patch->new_name : patch->old_name);
2916 fragment = fragment->next;
2918 switch (fragment->binary_patch_method) {
2919 case BINARY_DELTA_DEFLATED:
2920 dst = patch_delta(img->buf, img->len, fragment->patch,
2921 fragment->size, &len);
2922 if (!dst)
2923 return -1;
2924 clear_image(img);
2925 img->buf = dst;
2926 img->len = len;
2927 return 0;
2928 case BINARY_LITERAL_DEFLATED:
2929 clear_image(img);
2930 img->len = fragment->size;
2931 img->buf = xmemdupz(fragment->patch, img->len);
2932 return 0;
2934 return -1;
2938 * Replace "img" with the result of applying the binary patch.
2939 * The binary patch data itself in patch->fragment is still kept
2940 * but the preimage prepared by the caller in "img" is freed here
2941 * or in the helper function apply_binary_fragment() this calls.
2943 static int apply_binary(struct image *img, struct patch *patch)
2945 const char *name = patch->old_name ? patch->old_name : patch->new_name;
2946 unsigned char sha1[20];
2949 * For safety, we require patch index line to contain
2950 * full 40-byte textual SHA1 for old and new, at least for now.
2952 if (strlen(patch->old_sha1_prefix) != 40 ||
2953 strlen(patch->new_sha1_prefix) != 40 ||
2954 get_sha1_hex(patch->old_sha1_prefix, sha1) ||
2955 get_sha1_hex(patch->new_sha1_prefix, sha1))
2956 return error("cannot apply binary patch to '%s' "
2957 "without full index line", name);
2959 if (patch->old_name) {
2961 * See if the old one matches what the patch
2962 * applies to.
2964 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2965 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
2966 return error("the patch applies to '%s' (%s), "
2967 "which does not match the "
2968 "current contents.",
2969 name, sha1_to_hex(sha1));
2971 else {
2972 /* Otherwise, the old one must be empty. */
2973 if (img->len)
2974 return error("the patch applies to an empty "
2975 "'%s' but it is not empty", name);
2978 get_sha1_hex(patch->new_sha1_prefix, sha1);
2979 if (is_null_sha1(sha1)) {
2980 clear_image(img);
2981 return 0; /* deletion patch */
2984 if (has_sha1_file(sha1)) {
2985 /* We already have the postimage */
2986 enum object_type type;
2987 unsigned long size;
2988 char *result;
2990 result = read_sha1_file(sha1, &type, &size);
2991 if (!result)
2992 return error("the necessary postimage %s for "
2993 "'%s' cannot be read",
2994 patch->new_sha1_prefix, name);
2995 clear_image(img);
2996 img->buf = result;
2997 img->len = size;
2998 } else {
3000 * We have verified buf matches the preimage;
3001 * apply the patch data to it, which is stored
3002 * in the patch->fragments->{patch,size}.
3004 if (apply_binary_fragment(img, patch))
3005 return error(_("binary patch does not apply to '%s'"),
3006 name);
3008 /* verify that the result matches */
3009 hash_sha1_file(img->buf, img->len, blob_type, sha1);
3010 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
3011 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3012 name, patch->new_sha1_prefix, sha1_to_hex(sha1));
3015 return 0;
3018 static int apply_fragments(struct image *img, struct patch *patch)
3020 struct fragment *frag = patch->fragments;
3021 const char *name = patch->old_name ? patch->old_name : patch->new_name;
3022 unsigned ws_rule = patch->ws_rule;
3023 unsigned inaccurate_eof = patch->inaccurate_eof;
3024 int nth = 0;
3026 if (patch->is_binary)
3027 return apply_binary(img, patch);
3029 while (frag) {
3030 nth++;
3031 if (apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {
3032 error(_("patch failed: %s:%ld"), name, frag->oldpos);
3033 if (!apply_with_reject)
3034 return -1;
3035 frag->rejected = 1;
3037 frag = frag->next;
3039 return 0;
3042 static int read_blob_object(struct strbuf *buf, const unsigned char *sha1, unsigned mode)
3044 if (S_ISGITLINK(mode)) {
3045 strbuf_grow(buf, 100);
3046 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(sha1));
3047 } else {
3048 enum object_type type;
3049 unsigned long sz;
3050 char *result;
3052 result = read_sha1_file(sha1, &type, &sz);
3053 if (!result)
3054 return -1;
3055 /* XXX read_sha1_file NUL-terminates */
3056 strbuf_attach(buf, result, sz, sz + 1);
3058 return 0;
3061 static int read_file_or_gitlink(const struct cache_entry *ce, struct strbuf *buf)
3063 if (!ce)
3064 return 0;
3065 return read_blob_object(buf, ce->sha1, ce->ce_mode);
3068 static struct patch *in_fn_table(const char *name)
3070 struct string_list_item *item;
3072 if (name == NULL)
3073 return NULL;
3075 item = string_list_lookup(&fn_table, name);
3076 if (item != NULL)
3077 return (struct patch *)item->util;
3079 return NULL;
3083 * item->util in the filename table records the status of the path.
3084 * Usually it points at a patch (whose result records the contents
3085 * of it after applying it), but it could be PATH_WAS_DELETED for a
3086 * path that a previously applied patch has already removed, or
3087 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3089 * The latter is needed to deal with a case where two paths A and B
3090 * are swapped by first renaming A to B and then renaming B to A;
3091 * moving A to B should not be prevented due to presence of B as we
3092 * will remove it in a later patch.
3094 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3095 #define PATH_WAS_DELETED ((struct patch *) -1)
3097 static int to_be_deleted(struct patch *patch)
3099 return patch == PATH_TO_BE_DELETED;
3102 static int was_deleted(struct patch *patch)
3104 return patch == PATH_WAS_DELETED;
3107 static void add_to_fn_table(struct patch *patch)
3109 struct string_list_item *item;
3112 * Always add new_name unless patch is a deletion
3113 * This should cover the cases for normal diffs,
3114 * file creations and copies
3116 if (patch->new_name != NULL) {
3117 item = string_list_insert(&fn_table, patch->new_name);
3118 item->util = patch;
3122 * store a failure on rename/deletion cases because
3123 * later chunks shouldn't patch old names
3125 if ((patch->new_name == NULL) || (patch->is_rename)) {
3126 item = string_list_insert(&fn_table, patch->old_name);
3127 item->util = PATH_WAS_DELETED;
3131 static void prepare_fn_table(struct patch *patch)
3134 * store information about incoming file deletion
3136 while (patch) {
3137 if ((patch->new_name == NULL) || (patch->is_rename)) {
3138 struct string_list_item *item;
3139 item = string_list_insert(&fn_table, patch->old_name);
3140 item->util = PATH_TO_BE_DELETED;
3142 patch = patch->next;
3146 static int checkout_target(struct index_state *istate,
3147 struct cache_entry *ce, struct stat *st)
3149 struct checkout costate;
3151 memset(&costate, 0, sizeof(costate));
3152 costate.base_dir = "";
3153 costate.refresh_cache = 1;
3154 costate.istate = istate;
3155 if (checkout_entry(ce, &costate, NULL) || lstat(ce->name, st))
3156 return error(_("cannot checkout %s"), ce->name);
3157 return 0;
3160 static struct patch *previous_patch(struct patch *patch, int *gone)
3162 struct patch *previous;
3164 *gone = 0;
3165 if (patch->is_copy || patch->is_rename)
3166 return NULL; /* "git" patches do not depend on the order */
3168 previous = in_fn_table(patch->old_name);
3169 if (!previous)
3170 return NULL;
3172 if (to_be_deleted(previous))
3173 return NULL; /* the deletion hasn't happened yet */
3175 if (was_deleted(previous))
3176 *gone = 1;
3178 return previous;
3181 static int verify_index_match(const struct cache_entry *ce, struct stat *st)
3183 if (S_ISGITLINK(ce->ce_mode)) {
3184 if (!S_ISDIR(st->st_mode))
3185 return -1;
3186 return 0;
3188 return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
3191 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3193 static int load_patch_target(struct strbuf *buf,
3194 const struct cache_entry *ce,
3195 struct stat *st,
3196 const char *name,
3197 unsigned expected_mode)
3199 if (cached) {
3200 if (read_file_or_gitlink(ce, buf))
3201 return error(_("read of %s failed"), name);
3202 } else if (name) {
3203 if (S_ISGITLINK(expected_mode)) {
3204 if (ce)
3205 return read_file_or_gitlink(ce, buf);
3206 else
3207 return SUBMODULE_PATCH_WITHOUT_INDEX;
3208 } else {
3209 if (read_old_data(st, name, buf))
3210 return error(_("read of %s failed"), name);
3213 return 0;
3217 * We are about to apply "patch"; populate the "image" with the
3218 * current version we have, from the working tree or from the index,
3219 * depending on the situation e.g. --cached/--index. If we are
3220 * applying a non-git patch that incrementally updates the tree,
3221 * we read from the result of a previous diff.
3223 static int load_preimage(struct image *image,
3224 struct patch *patch, struct stat *st,
3225 const struct cache_entry *ce)
3227 struct strbuf buf = STRBUF_INIT;
3228 size_t len;
3229 char *img;
3230 struct patch *previous;
3231 int status;
3233 previous = previous_patch(patch, &status);
3234 if (status)
3235 return error(_("path %s has been renamed/deleted"),
3236 patch->old_name);
3237 if (previous) {
3238 /* We have a patched copy in memory; use that. */
3239 strbuf_add(&buf, previous->result, previous->resultsize);
3240 } else {
3241 status = load_patch_target(&buf, ce, st,
3242 patch->old_name, patch->old_mode);
3243 if (status < 0)
3244 return status;
3245 else if (status == SUBMODULE_PATCH_WITHOUT_INDEX) {
3247 * There is no way to apply subproject
3248 * patch without looking at the index.
3249 * NEEDSWORK: shouldn't this be flagged
3250 * as an error???
3252 free_fragment_list(patch->fragments);
3253 patch->fragments = NULL;
3254 } else if (status) {
3255 return error(_("read of %s failed"), patch->old_name);
3259 img = strbuf_detach(&buf, &len);
3260 prepare_image(image, img, len, !patch->is_binary);
3261 return 0;
3264 static int three_way_merge(struct image *image,
3265 char *path,
3266 const unsigned char *base,
3267 const unsigned char *ours,
3268 const unsigned char *theirs)
3270 mmfile_t base_file, our_file, their_file;
3271 mmbuffer_t result = { NULL };
3272 int status;
3274 read_mmblob(&base_file, base);
3275 read_mmblob(&our_file, ours);
3276 read_mmblob(&their_file, theirs);
3277 status = ll_merge(&result, path,
3278 &base_file, "base",
3279 &our_file, "ours",
3280 &their_file, "theirs", NULL);
3281 free(base_file.ptr);
3282 free(our_file.ptr);
3283 free(their_file.ptr);
3284 if (status < 0 || !result.ptr) {
3285 free(result.ptr);
3286 return -1;
3288 clear_image(image);
3289 image->buf = result.ptr;
3290 image->len = result.size;
3292 return status;
3296 * When directly falling back to add/add three-way merge, we read from
3297 * the current contents of the new_name. In no cases other than that
3298 * this function will be called.
3300 static int load_current(struct image *image, struct patch *patch)
3302 struct strbuf buf = STRBUF_INIT;
3303 int status, pos;
3304 size_t len;
3305 char *img;
3306 struct stat st;
3307 struct cache_entry *ce;
3308 char *name = patch->new_name;
3309 unsigned mode = patch->new_mode;
3311 if (!patch->is_new)
3312 die("BUG: patch to %s is not a creation", patch->old_name);
3314 pos = cache_name_pos(name, strlen(name));
3315 if (pos < 0)
3316 return error(_("%s: does not exist in index"), name);
3317 ce = active_cache[pos];
3318 if (lstat(name, &st)) {
3319 if (errno != ENOENT)
3320 return error(_("%s: %s"), name, strerror(errno));
3321 if (checkout_target(&the_index, ce, &st))
3322 return -1;
3324 if (verify_index_match(ce, &st))
3325 return error(_("%s: does not match index"), name);
3327 status = load_patch_target(&buf, ce, &st, name, mode);
3328 if (status < 0)
3329 return status;
3330 else if (status)
3331 return -1;
3332 img = strbuf_detach(&buf, &len);
3333 prepare_image(image, img, len, !patch->is_binary);
3334 return 0;
3337 static int try_threeway(struct image *image, struct patch *patch,
3338 struct stat *st, const struct cache_entry *ce)
3340 unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];
3341 struct strbuf buf = STRBUF_INIT;
3342 size_t len;
3343 int status;
3344 char *img;
3345 struct image tmp_image;
3347 /* No point falling back to 3-way merge in these cases */
3348 if (patch->is_delete ||
3349 S_ISGITLINK(patch->old_mode) || S_ISGITLINK(patch->new_mode))
3350 return -1;
3352 /* Preimage the patch was prepared for */
3353 if (patch->is_new)
3354 write_sha1_file("", 0, blob_type, pre_sha1);
3355 else if (get_sha1(patch->old_sha1_prefix, pre_sha1) ||
3356 read_blob_object(&buf, pre_sha1, patch->old_mode))
3357 return error("repository lacks the necessary blob to fall back on 3-way merge.");
3359 fprintf(stderr, "Falling back to three-way merge...\n");
3361 img = strbuf_detach(&buf, &len);
3362 prepare_image(&tmp_image, img, len, 1);
3363 /* Apply the patch to get the post image */
3364 if (apply_fragments(&tmp_image, patch) < 0) {
3365 clear_image(&tmp_image);
3366 return -1;
3368 /* post_sha1[] is theirs */
3369 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);
3370 clear_image(&tmp_image);
3372 /* our_sha1[] is ours */
3373 if (patch->is_new) {
3374 if (load_current(&tmp_image, patch))
3375 return error("cannot read the current contents of '%s'",
3376 patch->new_name);
3377 } else {
3378 if (load_preimage(&tmp_image, patch, st, ce))
3379 return error("cannot read the current contents of '%s'",
3380 patch->old_name);
3382 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);
3383 clear_image(&tmp_image);
3385 /* in-core three-way merge between post and our using pre as base */
3386 status = three_way_merge(image, patch->new_name,
3387 pre_sha1, our_sha1, post_sha1);
3388 if (status < 0) {
3389 fprintf(stderr, "Failed to fall back on three-way merge...\n");
3390 return status;
3393 if (status) {
3394 patch->conflicted_threeway = 1;
3395 if (patch->is_new)
3396 hashclr(patch->threeway_stage[0]);
3397 else
3398 hashcpy(patch->threeway_stage[0], pre_sha1);
3399 hashcpy(patch->threeway_stage[1], our_sha1);
3400 hashcpy(patch->threeway_stage[2], post_sha1);
3401 fprintf(stderr, "Applied patch to '%s' with conflicts.\n", patch->new_name);
3402 } else {
3403 fprintf(stderr, "Applied patch to '%s' cleanly.\n", patch->new_name);
3405 return 0;
3408 static int apply_data(struct patch *patch, struct stat *st, const struct cache_entry *ce)
3410 struct image image;
3412 if (load_preimage(&image, patch, st, ce) < 0)
3413 return -1;
3415 if (patch->direct_to_threeway ||
3416 apply_fragments(&image, patch) < 0) {
3417 /* Note: with --reject, apply_fragments() returns 0 */
3418 if (!threeway || try_threeway(&image, patch, st, ce) < 0)
3419 return -1;
3421 patch->result = image.buf;
3422 patch->resultsize = image.len;
3423 add_to_fn_table(patch);
3424 free(image.line_allocated);
3426 if (0 < patch->is_delete && patch->resultsize)
3427 return error(_("removal patch leaves file contents"));
3429 return 0;
3433 * If "patch" that we are looking at modifies or deletes what we have,
3434 * we would want it not to lose any local modification we have, either
3435 * in the working tree or in the index.
3437 * This also decides if a non-git patch is a creation patch or a
3438 * modification to an existing empty file. We do not check the state
3439 * of the current tree for a creation patch in this function; the caller
3440 * check_patch() separately makes sure (and errors out otherwise) that
3441 * the path the patch creates does not exist in the current tree.
3443 static int check_preimage(struct patch *patch, struct cache_entry **ce, struct stat *st)
3445 const char *old_name = patch->old_name;
3446 struct patch *previous = NULL;
3447 int stat_ret = 0, status;
3448 unsigned st_mode = 0;
3450 if (!old_name)
3451 return 0;
3453 assert(patch->is_new <= 0);
3454 previous = previous_patch(patch, &status);
3456 if (status)
3457 return error(_("path %s has been renamed/deleted"), old_name);
3458 if (previous) {
3459 st_mode = previous->new_mode;
3460 } else if (!cached) {
3461 stat_ret = lstat(old_name, st);
3462 if (stat_ret && errno != ENOENT)
3463 return error(_("%s: %s"), old_name, strerror(errno));
3466 if (check_index && !previous) {
3467 int pos = cache_name_pos(old_name, strlen(old_name));
3468 if (pos < 0) {
3469 if (patch->is_new < 0)
3470 goto is_new;
3471 return error(_("%s: does not exist in index"), old_name);
3473 *ce = active_cache[pos];
3474 if (stat_ret < 0) {
3475 if (checkout_target(&the_index, *ce, st))
3476 return -1;
3478 if (!cached && verify_index_match(*ce, st))
3479 return error(_("%s: does not match index"), old_name);
3480 if (cached)
3481 st_mode = (*ce)->ce_mode;
3482 } else if (stat_ret < 0) {
3483 if (patch->is_new < 0)
3484 goto is_new;
3485 return error(_("%s: %s"), old_name, strerror(errno));
3488 if (!cached && !previous)
3489 st_mode = ce_mode_from_stat(*ce, st->st_mode);
3491 if (patch->is_new < 0)
3492 patch->is_new = 0;
3493 if (!patch->old_mode)
3494 patch->old_mode = st_mode;
3495 if ((st_mode ^ patch->old_mode) & S_IFMT)
3496 return error(_("%s: wrong type"), old_name);
3497 if (st_mode != patch->old_mode)
3498 warning(_("%s has type %o, expected %o"),
3499 old_name, st_mode, patch->old_mode);
3500 if (!patch->new_mode && !patch->is_delete)
3501 patch->new_mode = st_mode;
3502 return 0;
3504 is_new:
3505 patch->is_new = 1;
3506 patch->is_delete = 0;
3507 free(patch->old_name);
3508 patch->old_name = NULL;
3509 return 0;
3513 #define EXISTS_IN_INDEX 1
3514 #define EXISTS_IN_WORKTREE 2
3516 static int check_to_create(const char *new_name, int ok_if_exists)
3518 struct stat nst;
3520 if (check_index &&
3521 cache_name_pos(new_name, strlen(new_name)) >= 0 &&
3522 !ok_if_exists)
3523 return EXISTS_IN_INDEX;
3524 if (cached)
3525 return 0;
3527 if (!lstat(new_name, &nst)) {
3528 if (S_ISDIR(nst.st_mode) || ok_if_exists)
3529 return 0;
3531 * A leading component of new_name might be a symlink
3532 * that is going to be removed with this patch, but
3533 * still pointing at somewhere that has the path.
3534 * In such a case, path "new_name" does not exist as
3535 * far as git is concerned.
3537 if (has_symlink_leading_path(new_name, strlen(new_name)))
3538 return 0;
3540 return EXISTS_IN_WORKTREE;
3541 } else if ((errno != ENOENT) && (errno != ENOTDIR)) {
3542 return error("%s: %s", new_name, strerror(errno));
3544 return 0;
3548 * Check and apply the patch in-core; leave the result in patch->result
3549 * for the caller to write it out to the final destination.
3551 static int check_patch(struct patch *patch)
3553 struct stat st;
3554 const char *old_name = patch->old_name;
3555 const char *new_name = patch->new_name;
3556 const char *name = old_name ? old_name : new_name;
3557 struct cache_entry *ce = NULL;
3558 struct patch *tpatch;
3559 int ok_if_exists;
3560 int status;
3562 patch->rejected = 1; /* we will drop this after we succeed */
3564 status = check_preimage(patch, &ce, &st);
3565 if (status)
3566 return status;
3567 old_name = patch->old_name;
3570 * A type-change diff is always split into a patch to delete
3571 * old, immediately followed by a patch to create new (see
3572 * diff.c::run_diff()); in such a case it is Ok that the entry
3573 * to be deleted by the previous patch is still in the working
3574 * tree and in the index.
3576 * A patch to swap-rename between A and B would first rename A
3577 * to B and then rename B to A. While applying the first one,
3578 * the presence of B should not stop A from getting renamed to
3579 * B; ask to_be_deleted() about the later rename. Removal of
3580 * B and rename from A to B is handled the same way by asking
3581 * was_deleted().
3583 if ((tpatch = in_fn_table(new_name)) &&
3584 (was_deleted(tpatch) || to_be_deleted(tpatch)))
3585 ok_if_exists = 1;
3586 else
3587 ok_if_exists = 0;
3589 if (new_name &&
3590 ((0 < patch->is_new) || patch->is_rename || patch->is_copy)) {
3591 int err = check_to_create(new_name, ok_if_exists);
3593 if (err && threeway) {
3594 patch->direct_to_threeway = 1;
3595 } else switch (err) {
3596 case 0:
3597 break; /* happy */
3598 case EXISTS_IN_INDEX:
3599 return error(_("%s: already exists in index"), new_name);
3600 break;
3601 case EXISTS_IN_WORKTREE:
3602 return error(_("%s: already exists in working directory"),
3603 new_name);
3604 default:
3605 return err;
3608 if (!patch->new_mode) {
3609 if (0 < patch->is_new)
3610 patch->new_mode = S_IFREG | 0644;
3611 else
3612 patch->new_mode = patch->old_mode;
3616 if (new_name && old_name) {
3617 int same = !strcmp(old_name, new_name);
3618 if (!patch->new_mode)
3619 patch->new_mode = patch->old_mode;
3620 if ((patch->old_mode ^ patch->new_mode) & S_IFMT) {
3621 if (same)
3622 return error(_("new mode (%o) of %s does not "
3623 "match old mode (%o)"),
3624 patch->new_mode, new_name,
3625 patch->old_mode);
3626 else
3627 return error(_("new mode (%o) of %s does not "
3628 "match old mode (%o) of %s"),
3629 patch->new_mode, new_name,
3630 patch->old_mode, old_name);
3634 if (apply_data(patch, &st, ce) < 0)
3635 return error(_("%s: patch does not apply"), name);
3636 patch->rejected = 0;
3637 return 0;
3640 static int check_patch_list(struct patch *patch)
3642 int err = 0;
3644 prepare_fn_table(patch);
3645 while (patch) {
3646 if (apply_verbosely)
3647 say_patch_name(stderr,
3648 _("Checking patch %s..."), patch);
3649 err |= check_patch(patch);
3650 patch = patch->next;
3652 return err;
3655 /* This function tries to read the sha1 from the current index */
3656 static int get_current_sha1(const char *path, unsigned char *sha1)
3658 int pos;
3660 if (read_cache() < 0)
3661 return -1;
3662 pos = cache_name_pos(path, strlen(path));
3663 if (pos < 0)
3664 return -1;
3665 hashcpy(sha1, active_cache[pos]->sha1);
3666 return 0;
3669 static int preimage_sha1_in_gitlink_patch(struct patch *p, unsigned char sha1[20])
3672 * A usable gitlink patch has only one fragment (hunk) that looks like:
3673 * @@ -1 +1 @@
3674 * -Subproject commit <old sha1>
3675 * +Subproject commit <new sha1>
3676 * or
3677 * @@ -1 +0,0 @@
3678 * -Subproject commit <old sha1>
3679 * for a removal patch.
3681 struct fragment *hunk = p->fragments;
3682 static const char heading[] = "-Subproject commit ";
3683 char *preimage;
3685 if (/* does the patch have only one hunk? */
3686 hunk && !hunk->next &&
3687 /* is its preimage one line? */
3688 hunk->oldpos == 1 && hunk->oldlines == 1 &&
3689 /* does preimage begin with the heading? */
3690 (preimage = memchr(hunk->patch, '\n', hunk->size)) != NULL &&
3691 starts_with(++preimage, heading) &&
3692 /* does it record full SHA-1? */
3693 !get_sha1_hex(preimage + sizeof(heading) - 1, sha1) &&
3694 preimage[sizeof(heading) + 40 - 1] == '\n' &&
3695 /* does the abbreviated name on the index line agree with it? */
3696 starts_with(preimage + sizeof(heading) - 1, p->old_sha1_prefix))
3697 return 0; /* it all looks fine */
3699 /* we may have full object name on the index line */
3700 return get_sha1_hex(p->old_sha1_prefix, sha1);
3703 /* Build an index that contains the just the files needed for a 3way merge */
3704 static void build_fake_ancestor(struct patch *list, const char *filename)
3706 struct patch *patch;
3707 struct index_state result = { NULL };
3708 static struct lock_file lock;
3710 /* Once we start supporting the reverse patch, it may be
3711 * worth showing the new sha1 prefix, but until then...
3713 for (patch = list; patch; patch = patch->next) {
3714 unsigned char sha1[20];
3715 struct cache_entry *ce;
3716 const char *name;
3718 name = patch->old_name ? patch->old_name : patch->new_name;
3719 if (0 < patch->is_new)
3720 continue;
3722 if (S_ISGITLINK(patch->old_mode)) {
3723 if (!preimage_sha1_in_gitlink_patch(patch, sha1))
3724 ; /* ok, the textual part looks sane */
3725 else
3726 die("sha1 information is lacking or useless for submodule %s",
3727 name);
3728 } else if (!get_sha1_blob(patch->old_sha1_prefix, sha1)) {
3729 ; /* ok */
3730 } else if (!patch->lines_added && !patch->lines_deleted) {
3731 /* mode-only change: update the current */
3732 if (get_current_sha1(patch->old_name, sha1))
3733 die("mode change for %s, which is not "
3734 "in current HEAD", name);
3735 } else
3736 die("sha1 information is lacking or useless "
3737 "(%s).", name);
3739 ce = make_cache_entry(patch->old_mode, sha1, name, 0, 0);
3740 if (!ce)
3741 die(_("make_cache_entry failed for path '%s'"), name);
3742 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))
3743 die ("Could not add %s to temporary index", name);
3746 hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);
3747 if (write_locked_index(&result, &lock, COMMIT_LOCK))
3748 die ("Could not write temporary index to %s", filename);
3750 discard_index(&result);
3753 static void stat_patch_list(struct patch *patch)
3755 int files, adds, dels;
3757 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
3758 files++;
3759 adds += patch->lines_added;
3760 dels += patch->lines_deleted;
3761 show_stats(patch);
3764 print_stat_summary(stdout, files, adds, dels);
3767 static void numstat_patch_list(struct patch *patch)
3769 for ( ; patch; patch = patch->next) {
3770 const char *name;
3771 name = patch->new_name ? patch->new_name : patch->old_name;
3772 if (patch->is_binary)
3773 printf("-\t-\t");
3774 else
3775 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
3776 write_name_quoted(name, stdout, line_termination);
3780 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
3782 if (mode)
3783 printf(" %s mode %06o %s\n", newdelete, mode, name);
3784 else
3785 printf(" %s %s\n", newdelete, name);
3788 static void show_mode_change(struct patch *p, int show_name)
3790 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
3791 if (show_name)
3792 printf(" mode change %06o => %06o %s\n",
3793 p->old_mode, p->new_mode, p->new_name);
3794 else
3795 printf(" mode change %06o => %06o\n",
3796 p->old_mode, p->new_mode);
3800 static void show_rename_copy(struct patch *p)
3802 const char *renamecopy = p->is_rename ? "rename" : "copy";
3803 const char *old, *new;
3805 /* Find common prefix */
3806 old = p->old_name;
3807 new = p->new_name;
3808 while (1) {
3809 const char *slash_old, *slash_new;
3810 slash_old = strchr(old, '/');
3811 slash_new = strchr(new, '/');
3812 if (!slash_old ||
3813 !slash_new ||
3814 slash_old - old != slash_new - new ||
3815 memcmp(old, new, slash_new - new))
3816 break;
3817 old = slash_old + 1;
3818 new = slash_new + 1;
3820 /* p->old_name thru old is the common prefix, and old and new
3821 * through the end of names are renames
3823 if (old != p->old_name)
3824 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
3825 (int)(old - p->old_name), p->old_name,
3826 old, new, p->score);
3827 else
3828 printf(" %s %s => %s (%d%%)\n", renamecopy,
3829 p->old_name, p->new_name, p->score);
3830 show_mode_change(p, 0);
3833 static void summary_patch_list(struct patch *patch)
3835 struct patch *p;
3837 for (p = patch; p; p = p->next) {
3838 if (p->is_new)
3839 show_file_mode_name("create", p->new_mode, p->new_name);
3840 else if (p->is_delete)
3841 show_file_mode_name("delete", p->old_mode, p->old_name);
3842 else {
3843 if (p->is_rename || p->is_copy)
3844 show_rename_copy(p);
3845 else {
3846 if (p->score) {
3847 printf(" rewrite %s (%d%%)\n",
3848 p->new_name, p->score);
3849 show_mode_change(p, 0);
3851 else
3852 show_mode_change(p, 1);
3858 static void patch_stats(struct patch *patch)
3860 int lines = patch->lines_added + patch->lines_deleted;
3862 if (lines > max_change)
3863 max_change = lines;
3864 if (patch->old_name) {
3865 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
3866 if (!len)
3867 len = strlen(patch->old_name);
3868 if (len > max_len)
3869 max_len = len;
3871 if (patch->new_name) {
3872 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
3873 if (!len)
3874 len = strlen(patch->new_name);
3875 if (len > max_len)
3876 max_len = len;
3880 static void remove_file(struct patch *patch, int rmdir_empty)
3882 if (update_index) {
3883 if (remove_file_from_cache(patch->old_name) < 0)
3884 die(_("unable to remove %s from index"), patch->old_name);
3886 if (!cached) {
3887 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
3888 remove_path(patch->old_name);
3893 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
3895 struct stat st;
3896 struct cache_entry *ce;
3897 int namelen = strlen(path);
3898 unsigned ce_size = cache_entry_size(namelen);
3900 if (!update_index)
3901 return;
3903 ce = xcalloc(1, ce_size);
3904 memcpy(ce->name, path, namelen);
3905 ce->ce_mode = create_ce_mode(mode);
3906 ce->ce_flags = create_ce_flags(0);
3907 ce->ce_namelen = namelen;
3908 if (S_ISGITLINK(mode)) {
3909 const char *s;
3911 if (!skip_prefix(buf, "Subproject commit ", &s) ||
3912 get_sha1_hex(s, ce->sha1))
3913 die(_("corrupt patch for submodule %s"), path);
3914 } else {
3915 if (!cached) {
3916 if (lstat(path, &st) < 0)
3917 die_errno(_("unable to stat newly created file '%s'"),
3918 path);
3919 fill_stat_cache_info(ce, &st);
3921 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
3922 die(_("unable to create backing store for newly created file %s"), path);
3924 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
3925 die(_("unable to add cache entry for %s"), path);
3928 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
3930 int fd;
3931 struct strbuf nbuf = STRBUF_INIT;
3933 if (S_ISGITLINK(mode)) {
3934 struct stat st;
3935 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
3936 return 0;
3937 return mkdir(path, 0777);
3940 if (has_symlinks && S_ISLNK(mode))
3941 /* Although buf:size is counted string, it also is NUL
3942 * terminated.
3944 return symlink(buf, path);
3946 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
3947 if (fd < 0)
3948 return -1;
3950 if (convert_to_working_tree(path, buf, size, &nbuf)) {
3951 size = nbuf.len;
3952 buf = nbuf.buf;
3954 write_or_die(fd, buf, size);
3955 strbuf_release(&nbuf);
3957 if (close(fd) < 0)
3958 die_errno(_("closing file '%s'"), path);
3959 return 0;
3963 * We optimistically assume that the directories exist,
3964 * which is true 99% of the time anyway. If they don't,
3965 * we create them and try again.
3967 static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
3969 if (cached)
3970 return;
3971 if (!try_create_file(path, mode, buf, size))
3972 return;
3974 if (errno == ENOENT) {
3975 if (safe_create_leading_directories(path))
3976 return;
3977 if (!try_create_file(path, mode, buf, size))
3978 return;
3981 if (errno == EEXIST || errno == EACCES) {
3982 /* We may be trying to create a file where a directory
3983 * used to be.
3985 struct stat st;
3986 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
3987 errno = EEXIST;
3990 if (errno == EEXIST) {
3991 unsigned int nr = getpid();
3993 for (;;) {
3994 char newpath[PATH_MAX];
3995 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
3996 if (!try_create_file(newpath, mode, buf, size)) {
3997 if (!rename(newpath, path))
3998 return;
3999 unlink_or_warn(newpath);
4000 break;
4002 if (errno != EEXIST)
4003 break;
4004 ++nr;
4007 die_errno(_("unable to write file '%s' mode %o"), path, mode);
4010 static void add_conflicted_stages_file(struct patch *patch)
4012 int stage, namelen;
4013 unsigned ce_size, mode;
4014 struct cache_entry *ce;
4016 if (!update_index)
4017 return;
4018 namelen = strlen(patch->new_name);
4019 ce_size = cache_entry_size(namelen);
4020 mode = patch->new_mode ? patch->new_mode : (S_IFREG | 0644);
4022 remove_file_from_cache(patch->new_name);
4023 for (stage = 1; stage < 4; stage++) {
4024 if (is_null_sha1(patch->threeway_stage[stage - 1]))
4025 continue;
4026 ce = xcalloc(1, ce_size);
4027 memcpy(ce->name, patch->new_name, namelen);
4028 ce->ce_mode = create_ce_mode(mode);
4029 ce->ce_flags = create_ce_flags(stage);
4030 ce->ce_namelen = namelen;
4031 hashcpy(ce->sha1, patch->threeway_stage[stage - 1]);
4032 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
4033 die(_("unable to add cache entry for %s"), patch->new_name);
4037 static void create_file(struct patch *patch)
4039 char *path = patch->new_name;
4040 unsigned mode = patch->new_mode;
4041 unsigned long size = patch->resultsize;
4042 char *buf = patch->result;
4044 if (!mode)
4045 mode = S_IFREG | 0644;
4046 create_one_file(path, mode, buf, size);
4048 if (patch->conflicted_threeway)
4049 add_conflicted_stages_file(patch);
4050 else
4051 add_index_file(path, mode, buf, size);
4054 /* phase zero is to remove, phase one is to create */
4055 static void write_out_one_result(struct patch *patch, int phase)
4057 if (patch->is_delete > 0) {
4058 if (phase == 0)
4059 remove_file(patch, 1);
4060 return;
4062 if (patch->is_new > 0 || patch->is_copy) {
4063 if (phase == 1)
4064 create_file(patch);
4065 return;
4068 * Rename or modification boils down to the same
4069 * thing: remove the old, write the new
4071 if (phase == 0)
4072 remove_file(patch, patch->is_rename);
4073 if (phase == 1)
4074 create_file(patch);
4077 static int write_out_one_reject(struct patch *patch)
4079 FILE *rej;
4080 char namebuf[PATH_MAX];
4081 struct fragment *frag;
4082 int cnt = 0;
4083 struct strbuf sb = STRBUF_INIT;
4085 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
4086 if (!frag->rejected)
4087 continue;
4088 cnt++;
4091 if (!cnt) {
4092 if (apply_verbosely)
4093 say_patch_name(stderr,
4094 _("Applied patch %s cleanly."), patch);
4095 return 0;
4098 /* This should not happen, because a removal patch that leaves
4099 * contents are marked "rejected" at the patch level.
4101 if (!patch->new_name)
4102 die(_("internal error"));
4104 /* Say this even without --verbose */
4105 strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",
4106 "Applying patch %%s with %d rejects...",
4107 cnt),
4108 cnt);
4109 say_patch_name(stderr, sb.buf, patch);
4110 strbuf_release(&sb);
4112 cnt = strlen(patch->new_name);
4113 if (ARRAY_SIZE(namebuf) <= cnt + 5) {
4114 cnt = ARRAY_SIZE(namebuf) - 5;
4115 warning(_("truncating .rej filename to %.*s.rej"),
4116 cnt - 1, patch->new_name);
4118 memcpy(namebuf, patch->new_name, cnt);
4119 memcpy(namebuf + cnt, ".rej", 5);
4121 rej = fopen(namebuf, "w");
4122 if (!rej)
4123 return error(_("cannot open %s: %s"), namebuf, strerror(errno));
4125 /* Normal git tools never deal with .rej, so do not pretend
4126 * this is a git patch by saying --git or giving extended
4127 * headers. While at it, maybe please "kompare" that wants
4128 * the trailing TAB and some garbage at the end of line ;-).
4130 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
4131 patch->new_name, patch->new_name);
4132 for (cnt = 1, frag = patch->fragments;
4133 frag;
4134 cnt++, frag = frag->next) {
4135 if (!frag->rejected) {
4136 fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);
4137 continue;
4139 fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);
4140 fprintf(rej, "%.*s", frag->size, frag->patch);
4141 if (frag->patch[frag->size-1] != '\n')
4142 fputc('\n', rej);
4144 fclose(rej);
4145 return -1;
4148 static int write_out_results(struct patch *list)
4150 int phase;
4151 int errs = 0;
4152 struct patch *l;
4153 struct string_list cpath = STRING_LIST_INIT_DUP;
4155 for (phase = 0; phase < 2; phase++) {
4156 l = list;
4157 while (l) {
4158 if (l->rejected)
4159 errs = 1;
4160 else {
4161 write_out_one_result(l, phase);
4162 if (phase == 1) {
4163 if (write_out_one_reject(l))
4164 errs = 1;
4165 if (l->conflicted_threeway) {
4166 string_list_append(&cpath, l->new_name);
4167 errs = 1;
4171 l = l->next;
4175 if (cpath.nr) {
4176 struct string_list_item *item;
4178 string_list_sort(&cpath);
4179 for_each_string_list_item(item, &cpath)
4180 fprintf(stderr, "U %s\n", item->string);
4181 string_list_clear(&cpath, 0);
4183 rerere(0);
4186 return errs;
4189 static struct lock_file lock_file;
4191 #define INACCURATE_EOF (1<<0)
4192 #define RECOUNT (1<<1)
4194 static int apply_patch(int fd, const char *filename, int options)
4196 size_t offset;
4197 struct strbuf buf = STRBUF_INIT; /* owns the patch text */
4198 struct patch *list = NULL, **listp = &list;
4199 int skipped_patch = 0;
4201 patch_input_file = filename;
4202 read_patch_file(&buf, fd);
4203 offset = 0;
4204 while (offset < buf.len) {
4205 struct patch *patch;
4206 int nr;
4208 patch = xcalloc(1, sizeof(*patch));
4209 patch->inaccurate_eof = !!(options & INACCURATE_EOF);
4210 patch->recount = !!(options & RECOUNT);
4211 nr = parse_chunk(buf.buf + offset, buf.len - offset, patch);
4212 if (nr < 0)
4213 break;
4214 if (apply_in_reverse)
4215 reverse_patches(patch);
4216 if (use_patch(patch)) {
4217 patch_stats(patch);
4218 *listp = patch;
4219 listp = &patch->next;
4221 else {
4222 free_patch(patch);
4223 skipped_patch++;
4225 offset += nr;
4228 if (!list && !skipped_patch)
4229 die(_("unrecognized input"));
4231 if (whitespace_error && (ws_error_action == die_on_ws_error))
4232 apply = 0;
4234 update_index = check_index && apply;
4235 if (update_index && newfd < 0)
4236 newfd = hold_locked_index(&lock_file, 1);
4238 if (check_index) {
4239 if (read_cache() < 0)
4240 die(_("unable to read index file"));
4243 if ((check || apply) &&
4244 check_patch_list(list) < 0 &&
4245 !apply_with_reject)
4246 exit(1);
4248 if (apply && write_out_results(list)) {
4249 if (apply_with_reject)
4250 exit(1);
4251 /* with --3way, we still need to write the index out */
4252 return 1;
4255 if (fake_ancestor)
4256 build_fake_ancestor(list, fake_ancestor);
4258 if (diffstat)
4259 stat_patch_list(list);
4261 if (numstat)
4262 numstat_patch_list(list);
4264 if (summary)
4265 summary_patch_list(list);
4267 free_patch_list(list);
4268 strbuf_release(&buf);
4269 string_list_clear(&fn_table, 0);
4270 return 0;
4273 static void git_apply_config(void)
4275 git_config_get_string_const("apply.whitespace", &apply_default_whitespace);
4276 git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);
4277 git_config(git_default_config, NULL);
4280 static int option_parse_exclude(const struct option *opt,
4281 const char *arg, int unset)
4283 add_name_limit(arg, 1);
4284 return 0;
4287 static int option_parse_include(const struct option *opt,
4288 const char *arg, int unset)
4290 add_name_limit(arg, 0);
4291 has_include = 1;
4292 return 0;
4295 static int option_parse_p(const struct option *opt,
4296 const char *arg, int unset)
4298 p_value = atoi(arg);
4299 p_value_known = 1;
4300 return 0;
4303 static int option_parse_z(const struct option *opt,
4304 const char *arg, int unset)
4306 if (unset)
4307 line_termination = '\n';
4308 else
4309 line_termination = 0;
4310 return 0;
4313 static int option_parse_space_change(const struct option *opt,
4314 const char *arg, int unset)
4316 if (unset)
4317 ws_ignore_action = ignore_ws_none;
4318 else
4319 ws_ignore_action = ignore_ws_change;
4320 return 0;
4323 static int option_parse_whitespace(const struct option *opt,
4324 const char *arg, int unset)
4326 const char **whitespace_option = opt->value;
4328 *whitespace_option = arg;
4329 parse_whitespace_option(arg);
4330 return 0;
4333 static int option_parse_directory(const struct option *opt,
4334 const char *arg, int unset)
4336 root_len = strlen(arg);
4337 if (root_len && arg[root_len - 1] != '/') {
4338 char *new_root;
4339 root = new_root = xmalloc(root_len + 2);
4340 strcpy(new_root, arg);
4341 strcpy(new_root + root_len++, "/");
4342 } else
4343 root = arg;
4344 return 0;
4347 int cmd_apply(int argc, const char **argv, const char *prefix_)
4349 int i;
4350 int errs = 0;
4351 int is_not_gitdir = !startup_info->have_repository;
4352 int force_apply = 0;
4354 const char *whitespace_option = NULL;
4356 struct option builtin_apply_options[] = {
4357 { OPTION_CALLBACK, 0, "exclude", NULL, N_("path"),
4358 N_("don't apply changes matching the given path"),
4359 0, option_parse_exclude },
4360 { OPTION_CALLBACK, 0, "include", NULL, N_("path"),
4361 N_("apply changes matching the given path"),
4362 0, option_parse_include },
4363 { OPTION_CALLBACK, 'p', NULL, NULL, N_("num"),
4364 N_("remove <num> leading slashes from traditional diff paths"),
4365 0, option_parse_p },
4366 OPT_BOOL(0, "no-add", &no_add,
4367 N_("ignore additions made by the patch")),
4368 OPT_BOOL(0, "stat", &diffstat,
4369 N_("instead of applying the patch, output diffstat for the input")),
4370 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
4371 OPT_NOOP_NOARG(0, "binary"),
4372 OPT_BOOL(0, "numstat", &numstat,
4373 N_("show number of added and deleted lines in decimal notation")),
4374 OPT_BOOL(0, "summary", &summary,
4375 N_("instead of applying the patch, output a summary for the input")),
4376 OPT_BOOL(0, "check", &check,
4377 N_("instead of applying the patch, see if the patch is applicable")),
4378 OPT_BOOL(0, "index", &check_index,
4379 N_("make sure the patch is applicable to the current index")),
4380 OPT_BOOL(0, "cached", &cached,
4381 N_("apply a patch without touching the working tree")),
4382 OPT_BOOL(0, "apply", &force_apply,
4383 N_("also apply the patch (use with --stat/--summary/--check)")),
4384 OPT_BOOL('3', "3way", &threeway,
4385 N_( "attempt three-way merge if a patch does not apply")),
4386 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor,
4387 N_("build a temporary index based on embedded index information")),
4388 { OPTION_CALLBACK, 'z', NULL, NULL, NULL,
4389 N_("paths are separated with NUL character"),
4390 PARSE_OPT_NOARG, option_parse_z },
4391 OPT_INTEGER('C', NULL, &p_context,
4392 N_("ensure at least <n> lines of context match")),
4393 { OPTION_CALLBACK, 0, "whitespace", &whitespace_option, N_("action"),
4394 N_("detect new or modified lines that have whitespace errors"),
4395 0, option_parse_whitespace },
4396 { OPTION_CALLBACK, 0, "ignore-space-change", NULL, NULL,
4397 N_("ignore changes in whitespace when finding context"),
4398 PARSE_OPT_NOARG, option_parse_space_change },
4399 { OPTION_CALLBACK, 0, "ignore-whitespace", NULL, NULL,
4400 N_("ignore changes in whitespace when finding context"),
4401 PARSE_OPT_NOARG, option_parse_space_change },
4402 OPT_BOOL('R', "reverse", &apply_in_reverse,
4403 N_("apply the patch in reverse")),
4404 OPT_BOOL(0, "unidiff-zero", &unidiff_zero,
4405 N_("don't expect at least one line of context")),
4406 OPT_BOOL(0, "reject", &apply_with_reject,
4407 N_("leave the rejected hunks in corresponding *.rej files")),
4408 OPT_BOOL(0, "allow-overlap", &allow_overlap,
4409 N_("allow overlapping hunks")),
4410 OPT__VERBOSE(&apply_verbosely, N_("be verbose")),
4411 OPT_BIT(0, "inaccurate-eof", &options,
4412 N_("tolerate incorrectly detected missing new-line at the end of file"),
4413 INACCURATE_EOF),
4414 OPT_BIT(0, "recount", &options,
4415 N_("do not trust the line counts in the hunk headers"),
4416 RECOUNT),
4417 { OPTION_CALLBACK, 0, "directory", NULL, N_("root"),
4418 N_("prepend <root> to all filenames"),
4419 0, option_parse_directory },
4420 OPT_END()
4423 prefix = prefix_;
4424 prefix_length = prefix ? strlen(prefix) : 0;
4425 git_apply_config();
4426 if (apply_default_whitespace)
4427 parse_whitespace_option(apply_default_whitespace);
4428 if (apply_default_ignorewhitespace)
4429 parse_ignorewhitespace_option(apply_default_ignorewhitespace);
4431 argc = parse_options(argc, argv, prefix, builtin_apply_options,
4432 apply_usage, 0);
4434 if (apply_with_reject && threeway)
4435 die("--reject and --3way cannot be used together.");
4436 if (cached && threeway)
4437 die("--cached and --3way cannot be used together.");
4438 if (threeway) {
4439 if (is_not_gitdir)
4440 die(_("--3way outside a repository"));
4441 check_index = 1;
4443 if (apply_with_reject)
4444 apply = apply_verbosely = 1;
4445 if (!force_apply && (diffstat || numstat || summary || check || fake_ancestor))
4446 apply = 0;
4447 if (check_index && is_not_gitdir)
4448 die(_("--index outside a repository"));
4449 if (cached) {
4450 if (is_not_gitdir)
4451 die(_("--cached outside a repository"));
4452 check_index = 1;
4454 for (i = 0; i < argc; i++) {
4455 const char *arg = argv[i];
4456 int fd;
4458 if (!strcmp(arg, "-")) {
4459 errs |= apply_patch(0, "<stdin>", options);
4460 read_stdin = 0;
4461 continue;
4462 } else if (0 < prefix_length)
4463 arg = prefix_filename(prefix, prefix_length, arg);
4465 fd = open(arg, O_RDONLY);
4466 if (fd < 0)
4467 die_errno(_("can't open patch '%s'"), arg);
4468 read_stdin = 0;
4469 set_default_whitespace_mode(whitespace_option);
4470 errs |= apply_patch(fd, arg, options);
4471 close(fd);
4473 set_default_whitespace_mode(whitespace_option);
4474 if (read_stdin)
4475 errs |= apply_patch(0, "<stdin>", options);
4476 if (whitespace_error) {
4477 if (squelch_whitespace_errors &&
4478 squelch_whitespace_errors < whitespace_error) {
4479 int squelched =
4480 whitespace_error - squelch_whitespace_errors;
4481 warning(Q_("squelched %d whitespace error",
4482 "squelched %d whitespace errors",
4483 squelched),
4484 squelched);
4486 if (ws_error_action == die_on_ws_error)
4487 die(Q_("%d line adds whitespace errors.",
4488 "%d lines add whitespace errors.",
4489 whitespace_error),
4490 whitespace_error);
4491 if (applied_after_fixing_ws && apply)
4492 warning("%d line%s applied after"
4493 " fixing whitespace errors.",
4494 applied_after_fixing_ws,
4495 applied_after_fixing_ws == 1 ? "" : "s");
4496 else if (whitespace_error)
4497 warning(Q_("%d line adds whitespace errors.",
4498 "%d lines add whitespace errors.",
4499 whitespace_error),
4500 whitespace_error);
4503 if (update_index) {
4504 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
4505 die(_("Unable to write new index file"));
4508 return !!errs;