builtin/apply.c: use xstrdup_or_null instead of null_strdup
[git/git-svn.git] / builtin / apply.c
blob4bb31fd6ae1fcee8fa901a289dda1cfcb95aeb52
1 /*
2 * apply.c
4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
8 */
9 #include "cache.h"
10 #include "cache-tree.h"
11 #include "quote.h"
12 #include "blob.h"
13 #include "delta.h"
14 #include "builtin.h"
15 #include "string-list.h"
16 #include "dir.h"
17 #include "diff.h"
18 #include "parse-options.h"
19 #include "xdiff-interface.h"
20 #include "ll-merge.h"
21 #include "rerere.h"
24 * --check turns on checking that the working tree matches the
25 * files that are being modified, but doesn't apply the patch
26 * --stat does just a diffstat, and doesn't actually apply
27 * --numstat does numeric diffstat, and doesn't actually apply
28 * --index-info shows the old and new index info for paths if available.
29 * --index updates the cache as well.
30 * --cached updates only the cache without ever touching the working tree.
32 static const char *prefix;
33 static int prefix_length = -1;
34 static int newfd = -1;
36 static int unidiff_zero;
37 static int p_value = 1;
38 static int p_value_known;
39 static int check_index;
40 static int update_index;
41 static int cached;
42 static int diffstat;
43 static int numstat;
44 static int summary;
45 static int check;
46 static int apply = 1;
47 static int apply_in_reverse;
48 static int apply_with_reject;
49 static int apply_verbosely;
50 static int allow_overlap;
51 static int no_add;
52 static int threeway;
53 static const char *fake_ancestor;
54 static int line_termination = '\n';
55 static unsigned int p_context = UINT_MAX;
56 static const char * const apply_usage[] = {
57 N_("git apply [options] [<patch>...]"),
58 NULL
61 static enum ws_error_action {
62 nowarn_ws_error,
63 warn_on_ws_error,
64 die_on_ws_error,
65 correct_ws_error
66 } ws_error_action = warn_on_ws_error;
67 static int whitespace_error;
68 static int squelch_whitespace_errors = 5;
69 static int applied_after_fixing_ws;
71 static enum ws_ignore {
72 ignore_ws_none,
73 ignore_ws_change
74 } ws_ignore_action = ignore_ws_none;
77 static const char *patch_input_file;
78 static const char *root;
79 static int root_len;
80 static int read_stdin = 1;
81 static int options;
83 static void parse_whitespace_option(const char *option)
85 if (!option) {
86 ws_error_action = warn_on_ws_error;
87 return;
89 if (!strcmp(option, "warn")) {
90 ws_error_action = warn_on_ws_error;
91 return;
93 if (!strcmp(option, "nowarn")) {
94 ws_error_action = nowarn_ws_error;
95 return;
97 if (!strcmp(option, "error")) {
98 ws_error_action = die_on_ws_error;
99 return;
101 if (!strcmp(option, "error-all")) {
102 ws_error_action = die_on_ws_error;
103 squelch_whitespace_errors = 0;
104 return;
106 if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
107 ws_error_action = correct_ws_error;
108 return;
110 die(_("unrecognized whitespace option '%s'"), option);
113 static void parse_ignorewhitespace_option(const char *option)
115 if (!option || !strcmp(option, "no") ||
116 !strcmp(option, "false") || !strcmp(option, "never") ||
117 !strcmp(option, "none")) {
118 ws_ignore_action = ignore_ws_none;
119 return;
121 if (!strcmp(option, "change")) {
122 ws_ignore_action = ignore_ws_change;
123 return;
125 die(_("unrecognized whitespace ignore option '%s'"), option);
128 static void set_default_whitespace_mode(const char *whitespace_option)
130 if (!whitespace_option && !apply_default_whitespace)
131 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error);
135 * For "diff-stat" like behaviour, we keep track of the biggest change
136 * we've seen, and the longest filename. That allows us to do simple
137 * scaling.
139 static int max_change, max_len;
142 * Various "current state", notably line numbers and what
143 * file (and how) we're patching right now.. The "is_xxxx"
144 * things are flags, where -1 means "don't know yet".
146 static int linenr = 1;
149 * This represents one "hunk" from a patch, starting with
150 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
151 * patch text is pointed at by patch, and its byte length
152 * is stored in size. leading and trailing are the number
153 * of context lines.
155 struct fragment {
156 unsigned long leading, trailing;
157 unsigned long oldpos, oldlines;
158 unsigned long newpos, newlines;
160 * 'patch' is usually borrowed from buf in apply_patch(),
161 * but some codepaths store an allocated buffer.
163 const char *patch;
164 unsigned free_patch:1,
165 rejected:1;
166 int size;
167 int linenr;
168 struct fragment *next;
172 * When dealing with a binary patch, we reuse "leading" field
173 * to store the type of the binary hunk, either deflated "delta"
174 * or deflated "literal".
176 #define binary_patch_method leading
177 #define BINARY_DELTA_DEFLATED 1
178 #define BINARY_LITERAL_DEFLATED 2
181 * This represents a "patch" to a file, both metainfo changes
182 * such as creation/deletion, filemode and content changes represented
183 * as a series of fragments.
185 struct patch {
186 char *new_name, *old_name, *def_name;
187 unsigned int old_mode, new_mode;
188 int is_new, is_delete; /* -1 = unknown, 0 = false, 1 = true */
189 int rejected;
190 unsigned ws_rule;
191 int lines_added, lines_deleted;
192 int score;
193 unsigned int is_toplevel_relative:1;
194 unsigned int inaccurate_eof:1;
195 unsigned int is_binary:1;
196 unsigned int is_copy:1;
197 unsigned int is_rename:1;
198 unsigned int recount:1;
199 unsigned int conflicted_threeway:1;
200 unsigned int direct_to_threeway:1;
201 struct fragment *fragments;
202 char *result;
203 size_t resultsize;
204 char old_sha1_prefix[41];
205 char new_sha1_prefix[41];
206 struct patch *next;
208 /* three-way fallback result */
209 unsigned char threeway_stage[3][20];
212 static void free_fragment_list(struct fragment *list)
214 while (list) {
215 struct fragment *next = list->next;
216 if (list->free_patch)
217 free((char *)list->patch);
218 free(list);
219 list = next;
223 static void free_patch(struct patch *patch)
225 free_fragment_list(patch->fragments);
226 free(patch->def_name);
227 free(patch->old_name);
228 free(patch->new_name);
229 free(patch->result);
230 free(patch);
233 static void free_patch_list(struct patch *list)
235 while (list) {
236 struct patch *next = list->next;
237 free_patch(list);
238 list = next;
243 * A line in a file, len-bytes long (includes the terminating LF,
244 * except for an incomplete line at the end if the file ends with
245 * one), and its contents hashes to 'hash'.
247 struct line {
248 size_t len;
249 unsigned hash : 24;
250 unsigned flag : 8;
251 #define LINE_COMMON 1
252 #define LINE_PATCHED 2
256 * This represents a "file", which is an array of "lines".
258 struct image {
259 char *buf;
260 size_t len;
261 size_t nr;
262 size_t alloc;
263 struct line *line_allocated;
264 struct line *line;
268 * Records filenames that have been touched, in order to handle
269 * the case where more than one patches touch the same file.
272 static struct string_list fn_table;
274 static uint32_t hash_line(const char *cp, size_t len)
276 size_t i;
277 uint32_t h;
278 for (i = 0, h = 0; i < len; i++) {
279 if (!isspace(cp[i])) {
280 h = h * 3 + (cp[i] & 0xff);
283 return h;
287 * Compare lines s1 of length n1 and s2 of length n2, ignoring
288 * whitespace difference. Returns 1 if they match, 0 otherwise
290 static int fuzzy_matchlines(const char *s1, size_t n1,
291 const char *s2, size_t n2)
293 const char *last1 = s1 + n1 - 1;
294 const char *last2 = s2 + n2 - 1;
295 int result = 0;
297 /* ignore line endings */
298 while ((*last1 == '\r') || (*last1 == '\n'))
299 last1--;
300 while ((*last2 == '\r') || (*last2 == '\n'))
301 last2--;
303 /* skip leading whitespaces, if both begin with whitespace */
304 if (s1 <= last1 && s2 <= last2 && isspace(*s1) && isspace(*s2)) {
305 while (isspace(*s1) && (s1 <= last1))
306 s1++;
307 while (isspace(*s2) && (s2 <= last2))
308 s2++;
310 /* early return if both lines are empty */
311 if ((s1 > last1) && (s2 > last2))
312 return 1;
313 while (!result) {
314 result = *s1++ - *s2++;
316 * Skip whitespace inside. We check for whitespace on
317 * both buffers because we don't want "a b" to match
318 * "ab"
320 if (isspace(*s1) && isspace(*s2)) {
321 while (isspace(*s1) && s1 <= last1)
322 s1++;
323 while (isspace(*s2) && s2 <= last2)
324 s2++;
327 * If we reached the end on one side only,
328 * lines don't match
330 if (
331 ((s2 > last2) && (s1 <= last1)) ||
332 ((s1 > last1) && (s2 <= last2)))
333 return 0;
334 if ((s1 > last1) && (s2 > last2))
335 break;
338 return !result;
341 static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
343 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
344 img->line_allocated[img->nr].len = len;
345 img->line_allocated[img->nr].hash = hash_line(bol, len);
346 img->line_allocated[img->nr].flag = flag;
347 img->nr++;
351 * "buf" has the file contents to be patched (read from various sources).
352 * attach it to "image" and add line-based index to it.
353 * "image" now owns the "buf".
355 static void prepare_image(struct image *image, char *buf, size_t len,
356 int prepare_linetable)
358 const char *cp, *ep;
360 memset(image, 0, sizeof(*image));
361 image->buf = buf;
362 image->len = len;
364 if (!prepare_linetable)
365 return;
367 ep = image->buf + image->len;
368 cp = image->buf;
369 while (cp < ep) {
370 const char *next;
371 for (next = cp; next < ep && *next != '\n'; next++)
373 if (next < ep)
374 next++;
375 add_line_info(image, cp, next - cp, 0);
376 cp = next;
378 image->line = image->line_allocated;
381 static void clear_image(struct image *image)
383 free(image->buf);
384 free(image->line_allocated);
385 memset(image, 0, sizeof(*image));
388 /* fmt must contain _one_ %s and no other substitution */
389 static void say_patch_name(FILE *output, const char *fmt, struct patch *patch)
391 struct strbuf sb = STRBUF_INIT;
393 if (patch->old_name && patch->new_name &&
394 strcmp(patch->old_name, patch->new_name)) {
395 quote_c_style(patch->old_name, &sb, NULL, 0);
396 strbuf_addstr(&sb, " => ");
397 quote_c_style(patch->new_name, &sb, NULL, 0);
398 } else {
399 const char *n = patch->new_name;
400 if (!n)
401 n = patch->old_name;
402 quote_c_style(n, &sb, NULL, 0);
404 fprintf(output, fmt, sb.buf);
405 fputc('\n', output);
406 strbuf_release(&sb);
409 #define SLOP (16)
411 static void read_patch_file(struct strbuf *sb, int fd)
413 if (strbuf_read(sb, fd, 0) < 0)
414 die_errno("git apply: failed to read");
417 * Make sure that we have some slop in the buffer
418 * so that we can do speculative "memcmp" etc, and
419 * see to it that it is NUL-filled.
421 strbuf_grow(sb, SLOP);
422 memset(sb->buf + sb->len, 0, SLOP);
425 static unsigned long linelen(const char *buffer, unsigned long size)
427 unsigned long len = 0;
428 while (size--) {
429 len++;
430 if (*buffer++ == '\n')
431 break;
433 return len;
436 static int is_dev_null(const char *str)
438 return !memcmp("/dev/null", str, 9) && isspace(str[9]);
441 #define TERM_SPACE 1
442 #define TERM_TAB 2
444 static int name_terminate(const char *name, int namelen, int c, int terminate)
446 if (c == ' ' && !(terminate & TERM_SPACE))
447 return 0;
448 if (c == '\t' && !(terminate & TERM_TAB))
449 return 0;
451 return 1;
454 /* remove double slashes to make --index work with such filenames */
455 static char *squash_slash(char *name)
457 int i = 0, j = 0;
459 if (!name)
460 return NULL;
462 while (name[i]) {
463 if ((name[j++] = name[i++]) == '/')
464 while (name[i] == '/')
465 i++;
467 name[j] = '\0';
468 return name;
471 static char *find_name_gnu(const char *line, const char *def, int p_value)
473 struct strbuf name = STRBUF_INIT;
474 char *cp;
477 * Proposed "new-style" GNU patch/diff format; see
478 * http://marc.info/?l=git&m=112927316408690&w=2
480 if (unquote_c_style(&name, line, NULL)) {
481 strbuf_release(&name);
482 return NULL;
485 for (cp = name.buf; p_value; p_value--) {
486 cp = strchr(cp, '/');
487 if (!cp) {
488 strbuf_release(&name);
489 return NULL;
491 cp++;
494 strbuf_remove(&name, 0, cp - name.buf);
495 if (root)
496 strbuf_insert(&name, 0, root, root_len);
497 return squash_slash(strbuf_detach(&name, NULL));
500 static size_t sane_tz_len(const char *line, size_t len)
502 const char *tz, *p;
504 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
505 return 0;
506 tz = line + len - strlen(" +0500");
508 if (tz[1] != '+' && tz[1] != '-')
509 return 0;
511 for (p = tz + 2; p != line + len; p++)
512 if (!isdigit(*p))
513 return 0;
515 return line + len - tz;
518 static size_t tz_with_colon_len(const char *line, size_t len)
520 const char *tz, *p;
522 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
523 return 0;
524 tz = line + len - strlen(" +08:00");
526 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
527 return 0;
528 p = tz + 2;
529 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
530 !isdigit(*p++) || !isdigit(*p++))
531 return 0;
533 return line + len - tz;
536 static size_t date_len(const char *line, size_t len)
538 const char *date, *p;
540 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
541 return 0;
542 p = date = line + len - strlen("72-02-05");
544 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
545 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
546 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */
547 return 0;
549 if (date - line >= strlen("19") &&
550 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */
551 date -= strlen("19");
553 return line + len - date;
556 static size_t short_time_len(const char *line, size_t len)
558 const char *time, *p;
560 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
561 return 0;
562 p = time = line + len - strlen(" 07:01:32");
564 /* Permit 1-digit hours? */
565 if (*p++ != ' ' ||
566 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
567 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
568 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */
569 return 0;
571 return line + len - time;
574 static size_t fractional_time_len(const char *line, size_t len)
576 const char *p;
577 size_t n;
579 /* Expected format: 19:41:17.620000023 */
580 if (!len || !isdigit(line[len - 1]))
581 return 0;
582 p = line + len - 1;
584 /* Fractional seconds. */
585 while (p > line && isdigit(*p))
586 p--;
587 if (*p != '.')
588 return 0;
590 /* Hours, minutes, and whole seconds. */
591 n = short_time_len(line, p - line);
592 if (!n)
593 return 0;
595 return line + len - p + n;
598 static size_t trailing_spaces_len(const char *line, size_t len)
600 const char *p;
602 /* Expected format: ' ' x (1 or more) */
603 if (!len || line[len - 1] != ' ')
604 return 0;
606 p = line + len;
607 while (p != line) {
608 p--;
609 if (*p != ' ')
610 return line + len - (p + 1);
613 /* All spaces! */
614 return len;
617 static size_t diff_timestamp_len(const char *line, size_t len)
619 const char *end = line + len;
620 size_t n;
623 * Posix: 2010-07-05 19:41:17
624 * GNU: 2010-07-05 19:41:17.620000023 -0500
627 if (!isdigit(end[-1]))
628 return 0;
630 n = sane_tz_len(line, end - line);
631 if (!n)
632 n = tz_with_colon_len(line, end - line);
633 end -= n;
635 n = short_time_len(line, end - line);
636 if (!n)
637 n = fractional_time_len(line, end - line);
638 end -= n;
640 n = date_len(line, end - line);
641 if (!n) /* No date. Too bad. */
642 return 0;
643 end -= n;
645 if (end == line) /* No space before date. */
646 return 0;
647 if (end[-1] == '\t') { /* Success! */
648 end--;
649 return line + len - end;
651 if (end[-1] != ' ') /* No space before date. */
652 return 0;
654 /* Whitespace damage. */
655 end -= trailing_spaces_len(line, end - line);
656 return line + len - end;
659 static char *find_name_common(const char *line, const char *def,
660 int p_value, const char *end, int terminate)
662 int len;
663 const char *start = NULL;
665 if (p_value == 0)
666 start = line;
667 while (line != end) {
668 char c = *line;
670 if (!end && isspace(c)) {
671 if (c == '\n')
672 break;
673 if (name_terminate(start, line-start, c, terminate))
674 break;
676 line++;
677 if (c == '/' && !--p_value)
678 start = line;
680 if (!start)
681 return squash_slash(xstrdup_or_null(def));
682 len = line - start;
683 if (!len)
684 return squash_slash(xstrdup_or_null(def));
687 * Generally we prefer the shorter name, especially
688 * if the other one is just a variation of that with
689 * something else tacked on to the end (ie "file.orig"
690 * or "file~").
692 if (def) {
693 int deflen = strlen(def);
694 if (deflen < len && !strncmp(start, def, deflen))
695 return squash_slash(xstrdup(def));
698 if (root) {
699 char *ret = xmalloc(root_len + len + 1);
700 strcpy(ret, root);
701 memcpy(ret + root_len, start, len);
702 ret[root_len + len] = '\0';
703 return squash_slash(ret);
706 return squash_slash(xmemdupz(start, len));
709 static char *find_name(const char *line, char *def, int p_value, int terminate)
711 if (*line == '"') {
712 char *name = find_name_gnu(line, def, p_value);
713 if (name)
714 return name;
717 return find_name_common(line, def, p_value, NULL, terminate);
720 static char *find_name_traditional(const char *line, char *def, int p_value)
722 size_t len;
723 size_t date_len;
725 if (*line == '"') {
726 char *name = find_name_gnu(line, def, p_value);
727 if (name)
728 return name;
731 len = strchrnul(line, '\n') - line;
732 date_len = diff_timestamp_len(line, len);
733 if (!date_len)
734 return find_name_common(line, def, p_value, NULL, TERM_TAB);
735 len -= date_len;
737 return find_name_common(line, def, p_value, line + len, 0);
740 static int count_slashes(const char *cp)
742 int cnt = 0;
743 char ch;
745 while ((ch = *cp++))
746 if (ch == '/')
747 cnt++;
748 return cnt;
752 * Given the string after "--- " or "+++ ", guess the appropriate
753 * p_value for the given patch.
755 static int guess_p_value(const char *nameline)
757 char *name, *cp;
758 int val = -1;
760 if (is_dev_null(nameline))
761 return -1;
762 name = find_name_traditional(nameline, NULL, 0);
763 if (!name)
764 return -1;
765 cp = strchr(name, '/');
766 if (!cp)
767 val = 0;
768 else if (prefix) {
770 * Does it begin with "a/$our-prefix" and such? Then this is
771 * very likely to apply to our directory.
773 if (!strncmp(name, prefix, prefix_length))
774 val = count_slashes(prefix);
775 else {
776 cp++;
777 if (!strncmp(cp, prefix, prefix_length))
778 val = count_slashes(prefix) + 1;
781 free(name);
782 return val;
786 * Does the ---/+++ line has the POSIX timestamp after the last HT?
787 * GNU diff puts epoch there to signal a creation/deletion event. Is
788 * this such a timestamp?
790 static int has_epoch_timestamp(const char *nameline)
793 * We are only interested in epoch timestamp; any non-zero
794 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
795 * For the same reason, the date must be either 1969-12-31 or
796 * 1970-01-01, and the seconds part must be "00".
798 const char stamp_regexp[] =
799 "^(1969-12-31|1970-01-01)"
801 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
803 "([-+][0-2][0-9]:?[0-5][0-9])\n";
804 const char *timestamp = NULL, *cp, *colon;
805 static regex_t *stamp;
806 regmatch_t m[10];
807 int zoneoffset;
808 int hourminute;
809 int status;
811 for (cp = nameline; *cp != '\n'; cp++) {
812 if (*cp == '\t')
813 timestamp = cp + 1;
815 if (!timestamp)
816 return 0;
817 if (!stamp) {
818 stamp = xmalloc(sizeof(*stamp));
819 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
820 warning(_("Cannot prepare timestamp regexp %s"),
821 stamp_regexp);
822 return 0;
826 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
827 if (status) {
828 if (status != REG_NOMATCH)
829 warning(_("regexec returned %d for input: %s"),
830 status, timestamp);
831 return 0;
834 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
835 if (*colon == ':')
836 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
837 else
838 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
839 if (timestamp[m[3].rm_so] == '-')
840 zoneoffset = -zoneoffset;
843 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
844 * (west of GMT) or 1970-01-01 (east of GMT)
846 if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) ||
847 (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10)))
848 return 0;
850 hourminute = (strtol(timestamp + 11, NULL, 10) * 60 +
851 strtol(timestamp + 14, NULL, 10) -
852 zoneoffset);
854 return ((zoneoffset < 0 && hourminute == 1440) ||
855 (0 <= zoneoffset && !hourminute));
859 * Get the name etc info from the ---/+++ lines of a traditional patch header
861 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
862 * files, we can happily check the index for a match, but for creating a
863 * new file we should try to match whatever "patch" does. I have no idea.
865 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
867 char *name;
869 first += 4; /* skip "--- " */
870 second += 4; /* skip "+++ " */
871 if (!p_value_known) {
872 int p, q;
873 p = guess_p_value(first);
874 q = guess_p_value(second);
875 if (p < 0) p = q;
876 if (0 <= p && p == q) {
877 p_value = p;
878 p_value_known = 1;
881 if (is_dev_null(first)) {
882 patch->is_new = 1;
883 patch->is_delete = 0;
884 name = find_name_traditional(second, NULL, p_value);
885 patch->new_name = name;
886 } else if (is_dev_null(second)) {
887 patch->is_new = 0;
888 patch->is_delete = 1;
889 name = find_name_traditional(first, NULL, p_value);
890 patch->old_name = name;
891 } else {
892 char *first_name;
893 first_name = find_name_traditional(first, NULL, p_value);
894 name = find_name_traditional(second, first_name, p_value);
895 free(first_name);
896 if (has_epoch_timestamp(first)) {
897 patch->is_new = 1;
898 patch->is_delete = 0;
899 patch->new_name = name;
900 } else if (has_epoch_timestamp(second)) {
901 patch->is_new = 0;
902 patch->is_delete = 1;
903 patch->old_name = name;
904 } else {
905 patch->old_name = name;
906 patch->new_name = xstrdup_or_null(name);
909 if (!name)
910 die(_("unable to find filename in patch at line %d"), linenr);
913 static int gitdiff_hdrend(const char *line, struct patch *patch)
915 return -1;
919 * We're anal about diff header consistency, to make
920 * sure that we don't end up having strange ambiguous
921 * patches floating around.
923 * As a result, gitdiff_{old|new}name() will check
924 * their names against any previous information, just
925 * to make sure..
927 #define DIFF_OLD_NAME 0
928 #define DIFF_NEW_NAME 1
930 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, int side)
932 if (!orig_name && !isnull)
933 return find_name(line, NULL, p_value, TERM_TAB);
935 if (orig_name) {
936 int len;
937 const char *name;
938 char *another;
939 name = orig_name;
940 len = strlen(name);
941 if (isnull)
942 die(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"), name, linenr);
943 another = find_name(line, NULL, p_value, TERM_TAB);
944 if (!another || memcmp(another, name, len + 1))
945 die((side == DIFF_NEW_NAME) ?
946 _("git apply: bad git-diff - inconsistent new filename on line %d") :
947 _("git apply: bad git-diff - inconsistent old filename on line %d"), linenr);
948 free(another);
949 return orig_name;
951 else {
952 /* expect "/dev/null" */
953 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
954 die(_("git apply: bad git-diff - expected /dev/null on line %d"), linenr);
955 return NULL;
959 static int gitdiff_oldname(const char *line, struct patch *patch)
961 char *orig = patch->old_name;
962 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name,
963 DIFF_OLD_NAME);
964 if (orig != patch->old_name)
965 free(orig);
966 return 0;
969 static int gitdiff_newname(const char *line, struct patch *patch)
971 char *orig = patch->new_name;
972 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name,
973 DIFF_NEW_NAME);
974 if (orig != patch->new_name)
975 free(orig);
976 return 0;
979 static int gitdiff_oldmode(const char *line, struct patch *patch)
981 patch->old_mode = strtoul(line, NULL, 8);
982 return 0;
985 static int gitdiff_newmode(const char *line, struct patch *patch)
987 patch->new_mode = strtoul(line, NULL, 8);
988 return 0;
991 static int gitdiff_delete(const char *line, struct patch *patch)
993 patch->is_delete = 1;
994 free(patch->old_name);
995 patch->old_name = xstrdup_or_null(patch->def_name);
996 return gitdiff_oldmode(line, patch);
999 static int gitdiff_newfile(const char *line, struct patch *patch)
1001 patch->is_new = 1;
1002 free(patch->new_name);
1003 patch->new_name = xstrdup_or_null(patch->def_name);
1004 return gitdiff_newmode(line, patch);
1007 static int gitdiff_copysrc(const char *line, struct patch *patch)
1009 patch->is_copy = 1;
1010 free(patch->old_name);
1011 patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1012 return 0;
1015 static int gitdiff_copydst(const char *line, struct patch *patch)
1017 patch->is_copy = 1;
1018 free(patch->new_name);
1019 patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1020 return 0;
1023 static int gitdiff_renamesrc(const char *line, struct patch *patch)
1025 patch->is_rename = 1;
1026 free(patch->old_name);
1027 patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1028 return 0;
1031 static int gitdiff_renamedst(const char *line, struct patch *patch)
1033 patch->is_rename = 1;
1034 free(patch->new_name);
1035 patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1036 return 0;
1039 static int gitdiff_similarity(const char *line, struct patch *patch)
1041 unsigned long val = strtoul(line, NULL, 10);
1042 if (val <= 100)
1043 patch->score = val;
1044 return 0;
1047 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
1049 unsigned long val = strtoul(line, NULL, 10);
1050 if (val <= 100)
1051 patch->score = val;
1052 return 0;
1055 static int gitdiff_index(const char *line, struct patch *patch)
1058 * index line is N hexadecimal, "..", N hexadecimal,
1059 * and optional space with octal mode.
1061 const char *ptr, *eol;
1062 int len;
1064 ptr = strchr(line, '.');
1065 if (!ptr || ptr[1] != '.' || 40 < ptr - line)
1066 return 0;
1067 len = ptr - line;
1068 memcpy(patch->old_sha1_prefix, line, len);
1069 patch->old_sha1_prefix[len] = 0;
1071 line = ptr + 2;
1072 ptr = strchr(line, ' ');
1073 eol = strchrnul(line, '\n');
1075 if (!ptr || eol < ptr)
1076 ptr = eol;
1077 len = ptr - line;
1079 if (40 < len)
1080 return 0;
1081 memcpy(patch->new_sha1_prefix, line, len);
1082 patch->new_sha1_prefix[len] = 0;
1083 if (*ptr == ' ')
1084 patch->old_mode = strtoul(ptr+1, NULL, 8);
1085 return 0;
1089 * This is normal for a diff that doesn't change anything: we'll fall through
1090 * into the next diff. Tell the parser to break out.
1092 static int gitdiff_unrecognized(const char *line, struct patch *patch)
1094 return -1;
1098 * Skip p_value leading components from "line"; as we do not accept
1099 * absolute paths, return NULL in that case.
1101 static const char *skip_tree_prefix(const char *line, int llen)
1103 int nslash;
1104 int i;
1106 if (!p_value)
1107 return (llen && line[0] == '/') ? NULL : line;
1109 nslash = p_value;
1110 for (i = 0; i < llen; i++) {
1111 int ch = line[i];
1112 if (ch == '/' && --nslash <= 0)
1113 return (i == 0) ? NULL : &line[i + 1];
1115 return NULL;
1119 * This is to extract the same name that appears on "diff --git"
1120 * line. We do not find and return anything if it is a rename
1121 * patch, and it is OK because we will find the name elsewhere.
1122 * We need to reliably find name only when it is mode-change only,
1123 * creation or deletion of an empty file. In any of these cases,
1124 * both sides are the same name under a/ and b/ respectively.
1126 static char *git_header_name(const char *line, int llen)
1128 const char *name;
1129 const char *second = NULL;
1130 size_t len, line_len;
1132 line += strlen("diff --git ");
1133 llen -= strlen("diff --git ");
1135 if (*line == '"') {
1136 const char *cp;
1137 struct strbuf first = STRBUF_INIT;
1138 struct strbuf sp = STRBUF_INIT;
1140 if (unquote_c_style(&first, line, &second))
1141 goto free_and_fail1;
1143 /* strip the a/b prefix including trailing slash */
1144 cp = skip_tree_prefix(first.buf, first.len);
1145 if (!cp)
1146 goto free_and_fail1;
1147 strbuf_remove(&first, 0, cp - first.buf);
1150 * second points at one past closing dq of name.
1151 * find the second name.
1153 while ((second < line + llen) && isspace(*second))
1154 second++;
1156 if (line + llen <= second)
1157 goto free_and_fail1;
1158 if (*second == '"') {
1159 if (unquote_c_style(&sp, second, NULL))
1160 goto free_and_fail1;
1161 cp = skip_tree_prefix(sp.buf, sp.len);
1162 if (!cp)
1163 goto free_and_fail1;
1164 /* They must match, otherwise ignore */
1165 if (strcmp(cp, first.buf))
1166 goto free_and_fail1;
1167 strbuf_release(&sp);
1168 return strbuf_detach(&first, NULL);
1171 /* unquoted second */
1172 cp = skip_tree_prefix(second, line + llen - second);
1173 if (!cp)
1174 goto free_and_fail1;
1175 if (line + llen - cp != first.len ||
1176 memcmp(first.buf, cp, first.len))
1177 goto free_and_fail1;
1178 return strbuf_detach(&first, NULL);
1180 free_and_fail1:
1181 strbuf_release(&first);
1182 strbuf_release(&sp);
1183 return NULL;
1186 /* unquoted first name */
1187 name = skip_tree_prefix(line, llen);
1188 if (!name)
1189 return NULL;
1192 * since the first name is unquoted, a dq if exists must be
1193 * the beginning of the second name.
1195 for (second = name; second < line + llen; second++) {
1196 if (*second == '"') {
1197 struct strbuf sp = STRBUF_INIT;
1198 const char *np;
1200 if (unquote_c_style(&sp, second, NULL))
1201 goto free_and_fail2;
1203 np = skip_tree_prefix(sp.buf, sp.len);
1204 if (!np)
1205 goto free_and_fail2;
1207 len = sp.buf + sp.len - np;
1208 if (len < second - name &&
1209 !strncmp(np, name, len) &&
1210 isspace(name[len])) {
1211 /* Good */
1212 strbuf_remove(&sp, 0, np - sp.buf);
1213 return strbuf_detach(&sp, NULL);
1216 free_and_fail2:
1217 strbuf_release(&sp);
1218 return NULL;
1223 * Accept a name only if it shows up twice, exactly the same
1224 * form.
1226 second = strchr(name, '\n');
1227 if (!second)
1228 return NULL;
1229 line_len = second - name;
1230 for (len = 0 ; ; len++) {
1231 switch (name[len]) {
1232 default:
1233 continue;
1234 case '\n':
1235 return NULL;
1236 case '\t': case ' ':
1238 * Is this the separator between the preimage
1239 * and the postimage pathname? Again, we are
1240 * only interested in the case where there is
1241 * no rename, as this is only to set def_name
1242 * and a rename patch has the names elsewhere
1243 * in an unambiguous form.
1245 if (!name[len + 1])
1246 return NULL; /* no postimage name */
1247 second = skip_tree_prefix(name + len + 1,
1248 line_len - (len + 1));
1249 if (!second)
1250 return NULL;
1252 * Does len bytes starting at "name" and "second"
1253 * (that are separated by one HT or SP we just
1254 * found) exactly match?
1256 if (second[len] == '\n' && !strncmp(name, second, len))
1257 return xmemdupz(name, len);
1262 /* Verify that we recognize the lines following a git header */
1263 static int parse_git_header(const char *line, int len, unsigned int size, struct patch *patch)
1265 unsigned long offset;
1267 /* A git diff has explicit new/delete information, so we don't guess */
1268 patch->is_new = 0;
1269 patch->is_delete = 0;
1272 * Some things may not have the old name in the
1273 * rest of the headers anywhere (pure mode changes,
1274 * or removing or adding empty files), so we get
1275 * the default name from the header.
1277 patch->def_name = git_header_name(line, len);
1278 if (patch->def_name && root) {
1279 char *s = xstrfmt("%s%s", root, patch->def_name);
1280 free(patch->def_name);
1281 patch->def_name = s;
1284 line += len;
1285 size -= len;
1286 linenr++;
1287 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
1288 static const struct opentry {
1289 const char *str;
1290 int (*fn)(const char *, struct patch *);
1291 } optable[] = {
1292 { "@@ -", gitdiff_hdrend },
1293 { "--- ", gitdiff_oldname },
1294 { "+++ ", gitdiff_newname },
1295 { "old mode ", gitdiff_oldmode },
1296 { "new mode ", gitdiff_newmode },
1297 { "deleted file mode ", gitdiff_delete },
1298 { "new file mode ", gitdiff_newfile },
1299 { "copy from ", gitdiff_copysrc },
1300 { "copy to ", gitdiff_copydst },
1301 { "rename old ", gitdiff_renamesrc },
1302 { "rename new ", gitdiff_renamedst },
1303 { "rename from ", gitdiff_renamesrc },
1304 { "rename to ", gitdiff_renamedst },
1305 { "similarity index ", gitdiff_similarity },
1306 { "dissimilarity index ", gitdiff_dissimilarity },
1307 { "index ", gitdiff_index },
1308 { "", gitdiff_unrecognized },
1310 int i;
1312 len = linelen(line, size);
1313 if (!len || line[len-1] != '\n')
1314 break;
1315 for (i = 0; i < ARRAY_SIZE(optable); i++) {
1316 const struct opentry *p = optable + i;
1317 int oplen = strlen(p->str);
1318 if (len < oplen || memcmp(p->str, line, oplen))
1319 continue;
1320 if (p->fn(line + oplen, patch) < 0)
1321 return offset;
1322 break;
1326 return offset;
1329 static int parse_num(const char *line, unsigned long *p)
1331 char *ptr;
1333 if (!isdigit(*line))
1334 return 0;
1335 *p = strtoul(line, &ptr, 10);
1336 return ptr - line;
1339 static int parse_range(const char *line, int len, int offset, const char *expect,
1340 unsigned long *p1, unsigned long *p2)
1342 int digits, ex;
1344 if (offset < 0 || offset >= len)
1345 return -1;
1346 line += offset;
1347 len -= offset;
1349 digits = parse_num(line, p1);
1350 if (!digits)
1351 return -1;
1353 offset += digits;
1354 line += digits;
1355 len -= digits;
1357 *p2 = 1;
1358 if (*line == ',') {
1359 digits = parse_num(line+1, p2);
1360 if (!digits)
1361 return -1;
1363 offset += digits+1;
1364 line += digits+1;
1365 len -= digits+1;
1368 ex = strlen(expect);
1369 if (ex > len)
1370 return -1;
1371 if (memcmp(line, expect, ex))
1372 return -1;
1374 return offset + ex;
1377 static void recount_diff(const char *line, int size, struct fragment *fragment)
1379 int oldlines = 0, newlines = 0, ret = 0;
1381 if (size < 1) {
1382 warning("recount: ignore empty hunk");
1383 return;
1386 for (;;) {
1387 int len = linelen(line, size);
1388 size -= len;
1389 line += len;
1391 if (size < 1)
1392 break;
1394 switch (*line) {
1395 case ' ': case '\n':
1396 newlines++;
1397 /* fall through */
1398 case '-':
1399 oldlines++;
1400 continue;
1401 case '+':
1402 newlines++;
1403 continue;
1404 case '\\':
1405 continue;
1406 case '@':
1407 ret = size < 3 || !starts_with(line, "@@ ");
1408 break;
1409 case 'd':
1410 ret = size < 5 || !starts_with(line, "diff ");
1411 break;
1412 default:
1413 ret = -1;
1414 break;
1416 if (ret) {
1417 warning(_("recount: unexpected line: %.*s"),
1418 (int)linelen(line, size), line);
1419 return;
1421 break;
1423 fragment->oldlines = oldlines;
1424 fragment->newlines = newlines;
1428 * Parse a unified diff fragment header of the
1429 * form "@@ -a,b +c,d @@"
1431 static int parse_fragment_header(const char *line, int len, struct fragment *fragment)
1433 int offset;
1435 if (!len || line[len-1] != '\n')
1436 return -1;
1438 /* Figure out the number of lines in a fragment */
1439 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1440 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1442 return offset;
1445 static int find_header(const char *line, unsigned long size, int *hdrsize, struct patch *patch)
1447 unsigned long offset, len;
1449 patch->is_toplevel_relative = 0;
1450 patch->is_rename = patch->is_copy = 0;
1451 patch->is_new = patch->is_delete = -1;
1452 patch->old_mode = patch->new_mode = 0;
1453 patch->old_name = patch->new_name = NULL;
1454 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
1455 unsigned long nextlen;
1457 len = linelen(line, size);
1458 if (!len)
1459 break;
1461 /* Testing this early allows us to take a few shortcuts.. */
1462 if (len < 6)
1463 continue;
1466 * Make sure we don't find any unconnected patch fragments.
1467 * That's a sign that we didn't find a header, and that a
1468 * patch has become corrupted/broken up.
1470 if (!memcmp("@@ -", line, 4)) {
1471 struct fragment dummy;
1472 if (parse_fragment_header(line, len, &dummy) < 0)
1473 continue;
1474 die(_("patch fragment without header at line %d: %.*s"),
1475 linenr, (int)len-1, line);
1478 if (size < len + 6)
1479 break;
1482 * Git patch? It might not have a real patch, just a rename
1483 * or mode change, so we handle that specially
1485 if (!memcmp("diff --git ", line, 11)) {
1486 int git_hdr_len = parse_git_header(line, len, size, patch);
1487 if (git_hdr_len <= len)
1488 continue;
1489 if (!patch->old_name && !patch->new_name) {
1490 if (!patch->def_name)
1491 die(Q_("git diff header lacks filename information when removing "
1492 "%d leading pathname component (line %d)",
1493 "git diff header lacks filename information when removing "
1494 "%d leading pathname components (line %d)",
1495 p_value),
1496 p_value, linenr);
1497 patch->old_name = xstrdup(patch->def_name);
1498 patch->new_name = xstrdup(patch->def_name);
1500 if (!patch->is_delete && !patch->new_name)
1501 die("git diff header lacks filename information "
1502 "(line %d)", linenr);
1503 patch->is_toplevel_relative = 1;
1504 *hdrsize = git_hdr_len;
1505 return offset;
1508 /* --- followed by +++ ? */
1509 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1510 continue;
1513 * We only accept unified patches, so we want it to
1514 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1515 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1517 nextlen = linelen(line + len, size - len);
1518 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1519 continue;
1521 /* Ok, we'll consider it a patch */
1522 parse_traditional_patch(line, line+len, patch);
1523 *hdrsize = len + nextlen;
1524 linenr += 2;
1525 return offset;
1527 return -1;
1530 static void record_ws_error(unsigned result, const char *line, int len, int linenr)
1532 char *err;
1534 if (!result)
1535 return;
1537 whitespace_error++;
1538 if (squelch_whitespace_errors &&
1539 squelch_whitespace_errors < whitespace_error)
1540 return;
1542 err = whitespace_error_string(result);
1543 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1544 patch_input_file, linenr, err, len, line);
1545 free(err);
1548 static void check_whitespace(const char *line, int len, unsigned ws_rule)
1550 unsigned result = ws_check(line + 1, len - 1, ws_rule);
1552 record_ws_error(result, line + 1, len - 2, linenr);
1556 * Parse a unified diff. Note that this really needs to parse each
1557 * fragment separately, since the only way to know the difference
1558 * between a "---" that is part of a patch, and a "---" that starts
1559 * the next patch is to look at the line counts..
1561 static int parse_fragment(const char *line, unsigned long size,
1562 struct patch *patch, struct fragment *fragment)
1564 int added, deleted;
1565 int len = linelen(line, size), offset;
1566 unsigned long oldlines, newlines;
1567 unsigned long leading, trailing;
1569 offset = parse_fragment_header(line, len, fragment);
1570 if (offset < 0)
1571 return -1;
1572 if (offset > 0 && patch->recount)
1573 recount_diff(line + offset, size - offset, fragment);
1574 oldlines = fragment->oldlines;
1575 newlines = fragment->newlines;
1576 leading = 0;
1577 trailing = 0;
1579 /* Parse the thing.. */
1580 line += len;
1581 size -= len;
1582 linenr++;
1583 added = deleted = 0;
1584 for (offset = len;
1585 0 < size;
1586 offset += len, size -= len, line += len, linenr++) {
1587 if (!oldlines && !newlines)
1588 break;
1589 len = linelen(line, size);
1590 if (!len || line[len-1] != '\n')
1591 return -1;
1592 switch (*line) {
1593 default:
1594 return -1;
1595 case '\n': /* newer GNU diff, an empty context line */
1596 case ' ':
1597 oldlines--;
1598 newlines--;
1599 if (!deleted && !added)
1600 leading++;
1601 trailing++;
1602 break;
1603 case '-':
1604 if (apply_in_reverse &&
1605 ws_error_action != nowarn_ws_error)
1606 check_whitespace(line, len, patch->ws_rule);
1607 deleted++;
1608 oldlines--;
1609 trailing = 0;
1610 break;
1611 case '+':
1612 if (!apply_in_reverse &&
1613 ws_error_action != nowarn_ws_error)
1614 check_whitespace(line, len, patch->ws_rule);
1615 added++;
1616 newlines--;
1617 trailing = 0;
1618 break;
1621 * We allow "\ No newline at end of file". Depending
1622 * on locale settings when the patch was produced we
1623 * don't know what this line looks like. The only
1624 * thing we do know is that it begins with "\ ".
1625 * Checking for 12 is just for sanity check -- any
1626 * l10n of "\ No newline..." is at least that long.
1628 case '\\':
1629 if (len < 12 || memcmp(line, "\\ ", 2))
1630 return -1;
1631 break;
1634 if (oldlines || newlines)
1635 return -1;
1636 fragment->leading = leading;
1637 fragment->trailing = trailing;
1640 * If a fragment ends with an incomplete line, we failed to include
1641 * it in the above loop because we hit oldlines == newlines == 0
1642 * before seeing it.
1644 if (12 < size && !memcmp(line, "\\ ", 2))
1645 offset += linelen(line, size);
1647 patch->lines_added += added;
1648 patch->lines_deleted += deleted;
1650 if (0 < patch->is_new && oldlines)
1651 return error(_("new file depends on old contents"));
1652 if (0 < patch->is_delete && newlines)
1653 return error(_("deleted file still has contents"));
1654 return offset;
1658 * We have seen "diff --git a/... b/..." header (or a traditional patch
1659 * header). Read hunks that belong to this patch into fragments and hang
1660 * them to the given patch structure.
1662 * The (fragment->patch, fragment->size) pair points into the memory given
1663 * by the caller, not a copy, when we return.
1665 static int parse_single_patch(const char *line, unsigned long size, struct patch *patch)
1667 unsigned long offset = 0;
1668 unsigned long oldlines = 0, newlines = 0, context = 0;
1669 struct fragment **fragp = &patch->fragments;
1671 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1672 struct fragment *fragment;
1673 int len;
1675 fragment = xcalloc(1, sizeof(*fragment));
1676 fragment->linenr = linenr;
1677 len = parse_fragment(line, size, patch, fragment);
1678 if (len <= 0)
1679 die(_("corrupt patch at line %d"), linenr);
1680 fragment->patch = line;
1681 fragment->size = len;
1682 oldlines += fragment->oldlines;
1683 newlines += fragment->newlines;
1684 context += fragment->leading + fragment->trailing;
1686 *fragp = fragment;
1687 fragp = &fragment->next;
1689 offset += len;
1690 line += len;
1691 size -= len;
1695 * If something was removed (i.e. we have old-lines) it cannot
1696 * be creation, and if something was added it cannot be
1697 * deletion. However, the reverse is not true; --unified=0
1698 * patches that only add are not necessarily creation even
1699 * though they do not have any old lines, and ones that only
1700 * delete are not necessarily deletion.
1702 * Unfortunately, a real creation/deletion patch do _not_ have
1703 * any context line by definition, so we cannot safely tell it
1704 * apart with --unified=0 insanity. At least if the patch has
1705 * more than one hunk it is not creation or deletion.
1707 if (patch->is_new < 0 &&
1708 (oldlines || (patch->fragments && patch->fragments->next)))
1709 patch->is_new = 0;
1710 if (patch->is_delete < 0 &&
1711 (newlines || (patch->fragments && patch->fragments->next)))
1712 patch->is_delete = 0;
1714 if (0 < patch->is_new && oldlines)
1715 die(_("new file %s depends on old contents"), patch->new_name);
1716 if (0 < patch->is_delete && newlines)
1717 die(_("deleted file %s still has contents"), patch->old_name);
1718 if (!patch->is_delete && !newlines && context)
1719 fprintf_ln(stderr,
1720 _("** warning: "
1721 "file %s becomes empty but is not deleted"),
1722 patch->new_name);
1724 return offset;
1727 static inline int metadata_changes(struct patch *patch)
1729 return patch->is_rename > 0 ||
1730 patch->is_copy > 0 ||
1731 patch->is_new > 0 ||
1732 patch->is_delete ||
1733 (patch->old_mode && patch->new_mode &&
1734 patch->old_mode != patch->new_mode);
1737 static char *inflate_it(const void *data, unsigned long size,
1738 unsigned long inflated_size)
1740 git_zstream stream;
1741 void *out;
1742 int st;
1744 memset(&stream, 0, sizeof(stream));
1746 stream.next_in = (unsigned char *)data;
1747 stream.avail_in = size;
1748 stream.next_out = out = xmalloc(inflated_size);
1749 stream.avail_out = inflated_size;
1750 git_inflate_init(&stream);
1751 st = git_inflate(&stream, Z_FINISH);
1752 git_inflate_end(&stream);
1753 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1754 free(out);
1755 return NULL;
1757 return out;
1761 * Read a binary hunk and return a new fragment; fragment->patch
1762 * points at an allocated memory that the caller must free, so
1763 * it is marked as "->free_patch = 1".
1765 static struct fragment *parse_binary_hunk(char **buf_p,
1766 unsigned long *sz_p,
1767 int *status_p,
1768 int *used_p)
1771 * Expect a line that begins with binary patch method ("literal"
1772 * or "delta"), followed by the length of data before deflating.
1773 * a sequence of 'length-byte' followed by base-85 encoded data
1774 * should follow, terminated by a newline.
1776 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1777 * and we would limit the patch line to 66 characters,
1778 * so one line can fit up to 13 groups that would decode
1779 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1780 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1782 int llen, used;
1783 unsigned long size = *sz_p;
1784 char *buffer = *buf_p;
1785 int patch_method;
1786 unsigned long origlen;
1787 char *data = NULL;
1788 int hunk_size = 0;
1789 struct fragment *frag;
1791 llen = linelen(buffer, size);
1792 used = llen;
1794 *status_p = 0;
1796 if (starts_with(buffer, "delta ")) {
1797 patch_method = BINARY_DELTA_DEFLATED;
1798 origlen = strtoul(buffer + 6, NULL, 10);
1800 else if (starts_with(buffer, "literal ")) {
1801 patch_method = BINARY_LITERAL_DEFLATED;
1802 origlen = strtoul(buffer + 8, NULL, 10);
1804 else
1805 return NULL;
1807 linenr++;
1808 buffer += llen;
1809 while (1) {
1810 int byte_length, max_byte_length, newsize;
1811 llen = linelen(buffer, size);
1812 used += llen;
1813 linenr++;
1814 if (llen == 1) {
1815 /* consume the blank line */
1816 buffer++;
1817 size--;
1818 break;
1821 * Minimum line is "A00000\n" which is 7-byte long,
1822 * and the line length must be multiple of 5 plus 2.
1824 if ((llen < 7) || (llen-2) % 5)
1825 goto corrupt;
1826 max_byte_length = (llen - 2) / 5 * 4;
1827 byte_length = *buffer;
1828 if ('A' <= byte_length && byte_length <= 'Z')
1829 byte_length = byte_length - 'A' + 1;
1830 else if ('a' <= byte_length && byte_length <= 'z')
1831 byte_length = byte_length - 'a' + 27;
1832 else
1833 goto corrupt;
1834 /* if the input length was not multiple of 4, we would
1835 * have filler at the end but the filler should never
1836 * exceed 3 bytes
1838 if (max_byte_length < byte_length ||
1839 byte_length <= max_byte_length - 4)
1840 goto corrupt;
1841 newsize = hunk_size + byte_length;
1842 data = xrealloc(data, newsize);
1843 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1844 goto corrupt;
1845 hunk_size = newsize;
1846 buffer += llen;
1847 size -= llen;
1850 frag = xcalloc(1, sizeof(*frag));
1851 frag->patch = inflate_it(data, hunk_size, origlen);
1852 frag->free_patch = 1;
1853 if (!frag->patch)
1854 goto corrupt;
1855 free(data);
1856 frag->size = origlen;
1857 *buf_p = buffer;
1858 *sz_p = size;
1859 *used_p = used;
1860 frag->binary_patch_method = patch_method;
1861 return frag;
1863 corrupt:
1864 free(data);
1865 *status_p = -1;
1866 error(_("corrupt binary patch at line %d: %.*s"),
1867 linenr-1, llen-1, buffer);
1868 return NULL;
1871 static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1874 * We have read "GIT binary patch\n"; what follows is a line
1875 * that says the patch method (currently, either "literal" or
1876 * "delta") and the length of data before deflating; a
1877 * sequence of 'length-byte' followed by base-85 encoded data
1878 * follows.
1880 * When a binary patch is reversible, there is another binary
1881 * hunk in the same format, starting with patch method (either
1882 * "literal" or "delta") with the length of data, and a sequence
1883 * of length-byte + base-85 encoded data, terminated with another
1884 * empty line. This data, when applied to the postimage, produces
1885 * the preimage.
1887 struct fragment *forward;
1888 struct fragment *reverse;
1889 int status;
1890 int used, used_1;
1892 forward = parse_binary_hunk(&buffer, &size, &status, &used);
1893 if (!forward && !status)
1894 /* there has to be one hunk (forward hunk) */
1895 return error(_("unrecognized binary patch at line %d"), linenr-1);
1896 if (status)
1897 /* otherwise we already gave an error message */
1898 return status;
1900 reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1901 if (reverse)
1902 used += used_1;
1903 else if (status) {
1905 * Not having reverse hunk is not an error, but having
1906 * a corrupt reverse hunk is.
1908 free((void*) forward->patch);
1909 free(forward);
1910 return status;
1912 forward->next = reverse;
1913 patch->fragments = forward;
1914 patch->is_binary = 1;
1915 return used;
1918 static void prefix_one(char **name)
1920 char *old_name = *name;
1921 if (!old_name)
1922 return;
1923 *name = xstrdup(prefix_filename(prefix, prefix_length, *name));
1924 free(old_name);
1927 static void prefix_patch(struct patch *p)
1929 if (!prefix || p->is_toplevel_relative)
1930 return;
1931 prefix_one(&p->new_name);
1932 prefix_one(&p->old_name);
1936 * include/exclude
1939 static struct string_list limit_by_name;
1940 static int has_include;
1941 static void add_name_limit(const char *name, int exclude)
1943 struct string_list_item *it;
1945 it = string_list_append(&limit_by_name, name);
1946 it->util = exclude ? NULL : (void *) 1;
1949 static int use_patch(struct patch *p)
1951 const char *pathname = p->new_name ? p->new_name : p->old_name;
1952 int i;
1954 /* Paths outside are not touched regardless of "--include" */
1955 if (0 < prefix_length) {
1956 int pathlen = strlen(pathname);
1957 if (pathlen <= prefix_length ||
1958 memcmp(prefix, pathname, prefix_length))
1959 return 0;
1962 /* See if it matches any of exclude/include rule */
1963 for (i = 0; i < limit_by_name.nr; i++) {
1964 struct string_list_item *it = &limit_by_name.items[i];
1965 if (!wildmatch(it->string, pathname, 0, NULL))
1966 return (it->util != NULL);
1970 * If we had any include, a path that does not match any rule is
1971 * not used. Otherwise, we saw bunch of exclude rules (or none)
1972 * and such a path is used.
1974 return !has_include;
1979 * Read the patch text in "buffer" that extends for "size" bytes; stop
1980 * reading after seeing a single patch (i.e. changes to a single file).
1981 * Create fragments (i.e. patch hunks) and hang them to the given patch.
1982 * Return the number of bytes consumed, so that the caller can call us
1983 * again for the next patch.
1985 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
1987 int hdrsize, patchsize;
1988 int offset = find_header(buffer, size, &hdrsize, patch);
1990 if (offset < 0)
1991 return offset;
1993 prefix_patch(patch);
1995 if (!use_patch(patch))
1996 patch->ws_rule = 0;
1997 else
1998 patch->ws_rule = whitespace_rule(patch->new_name
1999 ? patch->new_name
2000 : patch->old_name);
2002 patchsize = parse_single_patch(buffer + offset + hdrsize,
2003 size - offset - hdrsize, patch);
2005 if (!patchsize) {
2006 static const char git_binary[] = "GIT binary patch\n";
2007 int hd = hdrsize + offset;
2008 unsigned long llen = linelen(buffer + hd, size - hd);
2010 if (llen == sizeof(git_binary) - 1 &&
2011 !memcmp(git_binary, buffer + hd, llen)) {
2012 int used;
2013 linenr++;
2014 used = parse_binary(buffer + hd + llen,
2015 size - hd - llen, patch);
2016 if (used)
2017 patchsize = used + llen;
2018 else
2019 patchsize = 0;
2021 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
2022 static const char *binhdr[] = {
2023 "Binary files ",
2024 "Files ",
2025 NULL,
2027 int i;
2028 for (i = 0; binhdr[i]; i++) {
2029 int len = strlen(binhdr[i]);
2030 if (len < size - hd &&
2031 !memcmp(binhdr[i], buffer + hd, len)) {
2032 linenr++;
2033 patch->is_binary = 1;
2034 patchsize = llen;
2035 break;
2040 /* Empty patch cannot be applied if it is a text patch
2041 * without metadata change. A binary patch appears
2042 * empty to us here.
2044 if ((apply || check) &&
2045 (!patch->is_binary && !metadata_changes(patch)))
2046 die(_("patch with only garbage at line %d"), linenr);
2049 return offset + hdrsize + patchsize;
2052 #define swap(a,b) myswap((a),(b),sizeof(a))
2054 #define myswap(a, b, size) do { \
2055 unsigned char mytmp[size]; \
2056 memcpy(mytmp, &a, size); \
2057 memcpy(&a, &b, size); \
2058 memcpy(&b, mytmp, size); \
2059 } while (0)
2061 static void reverse_patches(struct patch *p)
2063 for (; p; p = p->next) {
2064 struct fragment *frag = p->fragments;
2066 swap(p->new_name, p->old_name);
2067 swap(p->new_mode, p->old_mode);
2068 swap(p->is_new, p->is_delete);
2069 swap(p->lines_added, p->lines_deleted);
2070 swap(p->old_sha1_prefix, p->new_sha1_prefix);
2072 for (; frag; frag = frag->next) {
2073 swap(frag->newpos, frag->oldpos);
2074 swap(frag->newlines, frag->oldlines);
2079 static const char pluses[] =
2080 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2081 static const char minuses[]=
2082 "----------------------------------------------------------------------";
2084 static void show_stats(struct patch *patch)
2086 struct strbuf qname = STRBUF_INIT;
2087 char *cp = patch->new_name ? patch->new_name : patch->old_name;
2088 int max, add, del;
2090 quote_c_style(cp, &qname, NULL, 0);
2093 * "scale" the filename
2095 max = max_len;
2096 if (max > 50)
2097 max = 50;
2099 if (qname.len > max) {
2100 cp = strchr(qname.buf + qname.len + 3 - max, '/');
2101 if (!cp)
2102 cp = qname.buf + qname.len + 3 - max;
2103 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
2106 if (patch->is_binary) {
2107 printf(" %-*s | Bin\n", max, qname.buf);
2108 strbuf_release(&qname);
2109 return;
2112 printf(" %-*s |", max, qname.buf);
2113 strbuf_release(&qname);
2116 * scale the add/delete
2118 max = max + max_change > 70 ? 70 - max : max_change;
2119 add = patch->lines_added;
2120 del = patch->lines_deleted;
2122 if (max_change > 0) {
2123 int total = ((add + del) * max + max_change / 2) / max_change;
2124 add = (add * max + max_change / 2) / max_change;
2125 del = total - add;
2127 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
2128 add, pluses, del, minuses);
2131 static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
2133 switch (st->st_mode & S_IFMT) {
2134 case S_IFLNK:
2135 if (strbuf_readlink(buf, path, st->st_size) < 0)
2136 return error(_("unable to read symlink %s"), path);
2137 return 0;
2138 case S_IFREG:
2139 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
2140 return error(_("unable to open or read %s"), path);
2141 convert_to_git(path, buf->buf, buf->len, buf, 0);
2142 return 0;
2143 default:
2144 return -1;
2149 * Update the preimage, and the common lines in postimage,
2150 * from buffer buf of length len. If postlen is 0 the postimage
2151 * is updated in place, otherwise it's updated on a new buffer
2152 * of length postlen
2155 static void update_pre_post_images(struct image *preimage,
2156 struct image *postimage,
2157 char *buf,
2158 size_t len, size_t postlen)
2160 int i, ctx, reduced;
2161 char *new, *old, *fixed;
2162 struct image fixed_preimage;
2165 * Update the preimage with whitespace fixes. Note that we
2166 * are not losing preimage->buf -- apply_one_fragment() will
2167 * free "oldlines".
2169 prepare_image(&fixed_preimage, buf, len, 1);
2170 assert(postlen
2171 ? fixed_preimage.nr == preimage->nr
2172 : fixed_preimage.nr <= preimage->nr);
2173 for (i = 0; i < fixed_preimage.nr; i++)
2174 fixed_preimage.line[i].flag = preimage->line[i].flag;
2175 free(preimage->line_allocated);
2176 *preimage = fixed_preimage;
2179 * Adjust the common context lines in postimage. This can be
2180 * done in-place when we are shrinking it with whitespace
2181 * fixing, but needs a new buffer when ignoring whitespace or
2182 * expanding leading tabs to spaces.
2184 * We trust the caller to tell us if the update can be done
2185 * in place (postlen==0) or not.
2187 old = postimage->buf;
2188 if (postlen)
2189 new = postimage->buf = xmalloc(postlen);
2190 else
2191 new = old;
2192 fixed = preimage->buf;
2194 for (i = reduced = ctx = 0; i < postimage->nr; i++) {
2195 size_t len = postimage->line[i].len;
2196 if (!(postimage->line[i].flag & LINE_COMMON)) {
2197 /* an added line -- no counterparts in preimage */
2198 memmove(new, old, len);
2199 old += len;
2200 new += len;
2201 continue;
2204 /* a common context -- skip it in the original postimage */
2205 old += len;
2207 /* and find the corresponding one in the fixed preimage */
2208 while (ctx < preimage->nr &&
2209 !(preimage->line[ctx].flag & LINE_COMMON)) {
2210 fixed += preimage->line[ctx].len;
2211 ctx++;
2215 * preimage is expected to run out, if the caller
2216 * fixed addition of trailing blank lines.
2218 if (preimage->nr <= ctx) {
2219 reduced++;
2220 continue;
2223 /* and copy it in, while fixing the line length */
2224 len = preimage->line[ctx].len;
2225 memcpy(new, fixed, len);
2226 new += len;
2227 fixed += len;
2228 postimage->line[i].len = len;
2229 ctx++;
2232 /* Fix the length of the whole thing */
2233 postimage->len = new - postimage->buf;
2234 postimage->nr -= reduced;
2237 static int match_fragment(struct image *img,
2238 struct image *preimage,
2239 struct image *postimage,
2240 unsigned long try,
2241 int try_lno,
2242 unsigned ws_rule,
2243 int match_beginning, int match_end)
2245 int i;
2246 char *fixed_buf, *buf, *orig, *target;
2247 struct strbuf fixed;
2248 size_t fixed_len, postlen;
2249 int preimage_limit;
2251 if (preimage->nr + try_lno <= img->nr) {
2253 * The hunk falls within the boundaries of img.
2255 preimage_limit = preimage->nr;
2256 if (match_end && (preimage->nr + try_lno != img->nr))
2257 return 0;
2258 } else if (ws_error_action == correct_ws_error &&
2259 (ws_rule & WS_BLANK_AT_EOF)) {
2261 * This hunk extends beyond the end of img, and we are
2262 * removing blank lines at the end of the file. This
2263 * many lines from the beginning of the preimage must
2264 * match with img, and the remainder of the preimage
2265 * must be blank.
2267 preimage_limit = img->nr - try_lno;
2268 } else {
2270 * The hunk extends beyond the end of the img and
2271 * we are not removing blanks at the end, so we
2272 * should reject the hunk at this position.
2274 return 0;
2277 if (match_beginning && try_lno)
2278 return 0;
2280 /* Quick hash check */
2281 for (i = 0; i < preimage_limit; i++)
2282 if ((img->line[try_lno + i].flag & LINE_PATCHED) ||
2283 (preimage->line[i].hash != img->line[try_lno + i].hash))
2284 return 0;
2286 if (preimage_limit == preimage->nr) {
2288 * Do we have an exact match? If we were told to match
2289 * at the end, size must be exactly at try+fragsize,
2290 * otherwise try+fragsize must be still within the preimage,
2291 * and either case, the old piece should match the preimage
2292 * exactly.
2294 if ((match_end
2295 ? (try + preimage->len == img->len)
2296 : (try + preimage->len <= img->len)) &&
2297 !memcmp(img->buf + try, preimage->buf, preimage->len))
2298 return 1;
2299 } else {
2301 * The preimage extends beyond the end of img, so
2302 * there cannot be an exact match.
2304 * There must be one non-blank context line that match
2305 * a line before the end of img.
2307 char *buf_end;
2309 buf = preimage->buf;
2310 buf_end = buf;
2311 for (i = 0; i < preimage_limit; i++)
2312 buf_end += preimage->line[i].len;
2314 for ( ; buf < buf_end; buf++)
2315 if (!isspace(*buf))
2316 break;
2317 if (buf == buf_end)
2318 return 0;
2322 * No exact match. If we are ignoring whitespace, run a line-by-line
2323 * fuzzy matching. We collect all the line length information because
2324 * we need it to adjust whitespace if we match.
2326 if (ws_ignore_action == ignore_ws_change) {
2327 size_t imgoff = 0;
2328 size_t preoff = 0;
2329 size_t postlen = postimage->len;
2330 size_t extra_chars;
2331 char *preimage_eof;
2332 char *preimage_end;
2333 for (i = 0; i < preimage_limit; i++) {
2334 size_t prelen = preimage->line[i].len;
2335 size_t imglen = img->line[try_lno+i].len;
2337 if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,
2338 preimage->buf + preoff, prelen))
2339 return 0;
2340 if (preimage->line[i].flag & LINE_COMMON)
2341 postlen += imglen - prelen;
2342 imgoff += imglen;
2343 preoff += prelen;
2347 * Ok, the preimage matches with whitespace fuzz.
2349 * imgoff now holds the true length of the target that
2350 * matches the preimage before the end of the file.
2352 * Count the number of characters in the preimage that fall
2353 * beyond the end of the file and make sure that all of them
2354 * are whitespace characters. (This can only happen if
2355 * we are removing blank lines at the end of the file.)
2357 buf = preimage_eof = preimage->buf + preoff;
2358 for ( ; i < preimage->nr; i++)
2359 preoff += preimage->line[i].len;
2360 preimage_end = preimage->buf + preoff;
2361 for ( ; buf < preimage_end; buf++)
2362 if (!isspace(*buf))
2363 return 0;
2366 * Update the preimage and the common postimage context
2367 * lines to use the same whitespace as the target.
2368 * If whitespace is missing in the target (i.e.
2369 * if the preimage extends beyond the end of the file),
2370 * use the whitespace from the preimage.
2372 extra_chars = preimage_end - preimage_eof;
2373 strbuf_init(&fixed, imgoff + extra_chars);
2374 strbuf_add(&fixed, img->buf + try, imgoff);
2375 strbuf_add(&fixed, preimage_eof, extra_chars);
2376 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2377 update_pre_post_images(preimage, postimage,
2378 fixed_buf, fixed_len, postlen);
2379 return 1;
2382 if (ws_error_action != correct_ws_error)
2383 return 0;
2386 * The hunk does not apply byte-by-byte, but the hash says
2387 * it might with whitespace fuzz. We haven't been asked to
2388 * ignore whitespace, we were asked to correct whitespace
2389 * errors, so let's try matching after whitespace correction.
2391 * The preimage may extend beyond the end of the file,
2392 * but in this loop we will only handle the part of the
2393 * preimage that falls within the file.
2395 strbuf_init(&fixed, preimage->len + 1);
2396 orig = preimage->buf;
2397 target = img->buf + try;
2398 postlen = 0;
2399 for (i = 0; i < preimage_limit; i++) {
2400 size_t oldlen = preimage->line[i].len;
2401 size_t tgtlen = img->line[try_lno + i].len;
2402 size_t fixstart = fixed.len;
2403 struct strbuf tgtfix;
2404 int match;
2406 /* Try fixing the line in the preimage */
2407 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2409 /* Try fixing the line in the target */
2410 strbuf_init(&tgtfix, tgtlen);
2411 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2414 * If they match, either the preimage was based on
2415 * a version before our tree fixed whitespace breakage,
2416 * or we are lacking a whitespace-fix patch the tree
2417 * the preimage was based on already had (i.e. target
2418 * has whitespace breakage, the preimage doesn't).
2419 * In either case, we are fixing the whitespace breakages
2420 * so we might as well take the fix together with their
2421 * real change.
2423 match = (tgtfix.len == fixed.len - fixstart &&
2424 !memcmp(tgtfix.buf, fixed.buf + fixstart,
2425 fixed.len - fixstart));
2426 postlen += tgtfix.len;
2428 strbuf_release(&tgtfix);
2429 if (!match)
2430 goto unmatch_exit;
2432 orig += oldlen;
2433 target += tgtlen;
2438 * Now handle the lines in the preimage that falls beyond the
2439 * end of the file (if any). They will only match if they are
2440 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2441 * false).
2443 for ( ; i < preimage->nr; i++) {
2444 size_t fixstart = fixed.len; /* start of the fixed preimage */
2445 size_t oldlen = preimage->line[i].len;
2446 int j;
2448 /* Try fixing the line in the preimage */
2449 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2451 for (j = fixstart; j < fixed.len; j++)
2452 if (!isspace(fixed.buf[j]))
2453 goto unmatch_exit;
2455 orig += oldlen;
2459 * Yes, the preimage is based on an older version that still
2460 * has whitespace breakages unfixed, and fixing them makes the
2461 * hunk match. Update the context lines in the postimage.
2463 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2464 if (postlen < postimage->len)
2465 postlen = 0;
2466 update_pre_post_images(preimage, postimage,
2467 fixed_buf, fixed_len, postlen);
2468 return 1;
2470 unmatch_exit:
2471 strbuf_release(&fixed);
2472 return 0;
2475 static int find_pos(struct image *img,
2476 struct image *preimage,
2477 struct image *postimage,
2478 int line,
2479 unsigned ws_rule,
2480 int match_beginning, int match_end)
2482 int i;
2483 unsigned long backwards, forwards, try;
2484 int backwards_lno, forwards_lno, try_lno;
2487 * If match_beginning or match_end is specified, there is no
2488 * point starting from a wrong line that will never match and
2489 * wander around and wait for a match at the specified end.
2491 if (match_beginning)
2492 line = 0;
2493 else if (match_end)
2494 line = img->nr - preimage->nr;
2497 * Because the comparison is unsigned, the following test
2498 * will also take care of a negative line number that can
2499 * result when match_end and preimage is larger than the target.
2501 if ((size_t) line > img->nr)
2502 line = img->nr;
2504 try = 0;
2505 for (i = 0; i < line; i++)
2506 try += img->line[i].len;
2509 * There's probably some smart way to do this, but I'll leave
2510 * that to the smart and beautiful people. I'm simple and stupid.
2512 backwards = try;
2513 backwards_lno = line;
2514 forwards = try;
2515 forwards_lno = line;
2516 try_lno = line;
2518 for (i = 0; ; i++) {
2519 if (match_fragment(img, preimage, postimage,
2520 try, try_lno, ws_rule,
2521 match_beginning, match_end))
2522 return try_lno;
2524 again:
2525 if (backwards_lno == 0 && forwards_lno == img->nr)
2526 break;
2528 if (i & 1) {
2529 if (backwards_lno == 0) {
2530 i++;
2531 goto again;
2533 backwards_lno--;
2534 backwards -= img->line[backwards_lno].len;
2535 try = backwards;
2536 try_lno = backwards_lno;
2537 } else {
2538 if (forwards_lno == img->nr) {
2539 i++;
2540 goto again;
2542 forwards += img->line[forwards_lno].len;
2543 forwards_lno++;
2544 try = forwards;
2545 try_lno = forwards_lno;
2549 return -1;
2552 static void remove_first_line(struct image *img)
2554 img->buf += img->line[0].len;
2555 img->len -= img->line[0].len;
2556 img->line++;
2557 img->nr--;
2560 static void remove_last_line(struct image *img)
2562 img->len -= img->line[--img->nr].len;
2566 * The change from "preimage" and "postimage" has been found to
2567 * apply at applied_pos (counts in line numbers) in "img".
2568 * Update "img" to remove "preimage" and replace it with "postimage".
2570 static void update_image(struct image *img,
2571 int applied_pos,
2572 struct image *preimage,
2573 struct image *postimage)
2576 * remove the copy of preimage at offset in img
2577 * and replace it with postimage
2579 int i, nr;
2580 size_t remove_count, insert_count, applied_at = 0;
2581 char *result;
2582 int preimage_limit;
2585 * If we are removing blank lines at the end of img,
2586 * the preimage may extend beyond the end.
2587 * If that is the case, we must be careful only to
2588 * remove the part of the preimage that falls within
2589 * the boundaries of img. Initialize preimage_limit
2590 * to the number of lines in the preimage that falls
2591 * within the boundaries.
2593 preimage_limit = preimage->nr;
2594 if (preimage_limit > img->nr - applied_pos)
2595 preimage_limit = img->nr - applied_pos;
2597 for (i = 0; i < applied_pos; i++)
2598 applied_at += img->line[i].len;
2600 remove_count = 0;
2601 for (i = 0; i < preimage_limit; i++)
2602 remove_count += img->line[applied_pos + i].len;
2603 insert_count = postimage->len;
2605 /* Adjust the contents */
2606 result = xmalloc(img->len + insert_count - remove_count + 1);
2607 memcpy(result, img->buf, applied_at);
2608 memcpy(result + applied_at, postimage->buf, postimage->len);
2609 memcpy(result + applied_at + postimage->len,
2610 img->buf + (applied_at + remove_count),
2611 img->len - (applied_at + remove_count));
2612 free(img->buf);
2613 img->buf = result;
2614 img->len += insert_count - remove_count;
2615 result[img->len] = '\0';
2617 /* Adjust the line table */
2618 nr = img->nr + postimage->nr - preimage_limit;
2619 if (preimage_limit < postimage->nr) {
2621 * NOTE: this knows that we never call remove_first_line()
2622 * on anything other than pre/post image.
2624 REALLOC_ARRAY(img->line, nr);
2625 img->line_allocated = img->line;
2627 if (preimage_limit != postimage->nr)
2628 memmove(img->line + applied_pos + postimage->nr,
2629 img->line + applied_pos + preimage_limit,
2630 (img->nr - (applied_pos + preimage_limit)) *
2631 sizeof(*img->line));
2632 memcpy(img->line + applied_pos,
2633 postimage->line,
2634 postimage->nr * sizeof(*img->line));
2635 if (!allow_overlap)
2636 for (i = 0; i < postimage->nr; i++)
2637 img->line[applied_pos + i].flag |= LINE_PATCHED;
2638 img->nr = nr;
2642 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2643 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2644 * replace the part of "img" with "postimage" text.
2646 static int apply_one_fragment(struct image *img, struct fragment *frag,
2647 int inaccurate_eof, unsigned ws_rule,
2648 int nth_fragment)
2650 int match_beginning, match_end;
2651 const char *patch = frag->patch;
2652 int size = frag->size;
2653 char *old, *oldlines;
2654 struct strbuf newlines;
2655 int new_blank_lines_at_end = 0;
2656 int found_new_blank_lines_at_end = 0;
2657 int hunk_linenr = frag->linenr;
2658 unsigned long leading, trailing;
2659 int pos, applied_pos;
2660 struct image preimage;
2661 struct image postimage;
2663 memset(&preimage, 0, sizeof(preimage));
2664 memset(&postimage, 0, sizeof(postimage));
2665 oldlines = xmalloc(size);
2666 strbuf_init(&newlines, size);
2668 old = oldlines;
2669 while (size > 0) {
2670 char first;
2671 int len = linelen(patch, size);
2672 int plen;
2673 int added_blank_line = 0;
2674 int is_blank_context = 0;
2675 size_t start;
2677 if (!len)
2678 break;
2681 * "plen" is how much of the line we should use for
2682 * the actual patch data. Normally we just remove the
2683 * first character on the line, but if the line is
2684 * followed by "\ No newline", then we also remove the
2685 * last one (which is the newline, of course).
2687 plen = len - 1;
2688 if (len < size && patch[len] == '\\')
2689 plen--;
2690 first = *patch;
2691 if (apply_in_reverse) {
2692 if (first == '-')
2693 first = '+';
2694 else if (first == '+')
2695 first = '-';
2698 switch (first) {
2699 case '\n':
2700 /* Newer GNU diff, empty context line */
2701 if (plen < 0)
2702 /* ... followed by '\No newline'; nothing */
2703 break;
2704 *old++ = '\n';
2705 strbuf_addch(&newlines, '\n');
2706 add_line_info(&preimage, "\n", 1, LINE_COMMON);
2707 add_line_info(&postimage, "\n", 1, LINE_COMMON);
2708 is_blank_context = 1;
2709 break;
2710 case ' ':
2711 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2712 ws_blank_line(patch + 1, plen, ws_rule))
2713 is_blank_context = 1;
2714 case '-':
2715 memcpy(old, patch + 1, plen);
2716 add_line_info(&preimage, old, plen,
2717 (first == ' ' ? LINE_COMMON : 0));
2718 old += plen;
2719 if (first == '-')
2720 break;
2721 /* Fall-through for ' ' */
2722 case '+':
2723 /* --no-add does not add new lines */
2724 if (first == '+' && no_add)
2725 break;
2727 start = newlines.len;
2728 if (first != '+' ||
2729 !whitespace_error ||
2730 ws_error_action != correct_ws_error) {
2731 strbuf_add(&newlines, patch + 1, plen);
2733 else {
2734 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &applied_after_fixing_ws);
2736 add_line_info(&postimage, newlines.buf + start, newlines.len - start,
2737 (first == '+' ? 0 : LINE_COMMON));
2738 if (first == '+' &&
2739 (ws_rule & WS_BLANK_AT_EOF) &&
2740 ws_blank_line(patch + 1, plen, ws_rule))
2741 added_blank_line = 1;
2742 break;
2743 case '@': case '\\':
2744 /* Ignore it, we already handled it */
2745 break;
2746 default:
2747 if (apply_verbosely)
2748 error(_("invalid start of line: '%c'"), first);
2749 return -1;
2751 if (added_blank_line) {
2752 if (!new_blank_lines_at_end)
2753 found_new_blank_lines_at_end = hunk_linenr;
2754 new_blank_lines_at_end++;
2756 else if (is_blank_context)
2758 else
2759 new_blank_lines_at_end = 0;
2760 patch += len;
2761 size -= len;
2762 hunk_linenr++;
2764 if (inaccurate_eof &&
2765 old > oldlines && old[-1] == '\n' &&
2766 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
2767 old--;
2768 strbuf_setlen(&newlines, newlines.len - 1);
2771 leading = frag->leading;
2772 trailing = frag->trailing;
2775 * A hunk to change lines at the beginning would begin with
2776 * @@ -1,L +N,M @@
2777 * but we need to be careful. -U0 that inserts before the second
2778 * line also has this pattern.
2780 * And a hunk to add to an empty file would begin with
2781 * @@ -0,0 +N,M @@
2783 * In other words, a hunk that is (frag->oldpos <= 1) with or
2784 * without leading context must match at the beginning.
2786 match_beginning = (!frag->oldpos ||
2787 (frag->oldpos == 1 && !unidiff_zero));
2790 * A hunk without trailing lines must match at the end.
2791 * However, we simply cannot tell if a hunk must match end
2792 * from the lack of trailing lines if the patch was generated
2793 * with unidiff without any context.
2795 match_end = !unidiff_zero && !trailing;
2797 pos = frag->newpos ? (frag->newpos - 1) : 0;
2798 preimage.buf = oldlines;
2799 preimage.len = old - oldlines;
2800 postimage.buf = newlines.buf;
2801 postimage.len = newlines.len;
2802 preimage.line = preimage.line_allocated;
2803 postimage.line = postimage.line_allocated;
2805 for (;;) {
2807 applied_pos = find_pos(img, &preimage, &postimage, pos,
2808 ws_rule, match_beginning, match_end);
2810 if (applied_pos >= 0)
2811 break;
2813 /* Am I at my context limits? */
2814 if ((leading <= p_context) && (trailing <= p_context))
2815 break;
2816 if (match_beginning || match_end) {
2817 match_beginning = match_end = 0;
2818 continue;
2822 * Reduce the number of context lines; reduce both
2823 * leading and trailing if they are equal otherwise
2824 * just reduce the larger context.
2826 if (leading >= trailing) {
2827 remove_first_line(&preimage);
2828 remove_first_line(&postimage);
2829 pos--;
2830 leading--;
2832 if (trailing > leading) {
2833 remove_last_line(&preimage);
2834 remove_last_line(&postimage);
2835 trailing--;
2839 if (applied_pos >= 0) {
2840 if (new_blank_lines_at_end &&
2841 preimage.nr + applied_pos >= img->nr &&
2842 (ws_rule & WS_BLANK_AT_EOF) &&
2843 ws_error_action != nowarn_ws_error) {
2844 record_ws_error(WS_BLANK_AT_EOF, "+", 1,
2845 found_new_blank_lines_at_end);
2846 if (ws_error_action == correct_ws_error) {
2847 while (new_blank_lines_at_end--)
2848 remove_last_line(&postimage);
2851 * We would want to prevent write_out_results()
2852 * from taking place in apply_patch() that follows
2853 * the callchain led us here, which is:
2854 * apply_patch->check_patch_list->check_patch->
2855 * apply_data->apply_fragments->apply_one_fragment
2857 if (ws_error_action == die_on_ws_error)
2858 apply = 0;
2861 if (apply_verbosely && applied_pos != pos) {
2862 int offset = applied_pos - pos;
2863 if (apply_in_reverse)
2864 offset = 0 - offset;
2865 fprintf_ln(stderr,
2866 Q_("Hunk #%d succeeded at %d (offset %d line).",
2867 "Hunk #%d succeeded at %d (offset %d lines).",
2868 offset),
2869 nth_fragment, applied_pos + 1, offset);
2873 * Warn if it was necessary to reduce the number
2874 * of context lines.
2876 if ((leading != frag->leading) ||
2877 (trailing != frag->trailing))
2878 fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"
2879 " to apply fragment at %d"),
2880 leading, trailing, applied_pos+1);
2881 update_image(img, applied_pos, &preimage, &postimage);
2882 } else {
2883 if (apply_verbosely)
2884 error(_("while searching for:\n%.*s"),
2885 (int)(old - oldlines), oldlines);
2888 free(oldlines);
2889 strbuf_release(&newlines);
2890 free(preimage.line_allocated);
2891 free(postimage.line_allocated);
2893 return (applied_pos < 0);
2896 static int apply_binary_fragment(struct image *img, struct patch *patch)
2898 struct fragment *fragment = patch->fragments;
2899 unsigned long len;
2900 void *dst;
2902 if (!fragment)
2903 return error(_("missing binary patch data for '%s'"),
2904 patch->new_name ?
2905 patch->new_name :
2906 patch->old_name);
2908 /* Binary patch is irreversible without the optional second hunk */
2909 if (apply_in_reverse) {
2910 if (!fragment->next)
2911 return error("cannot reverse-apply a binary patch "
2912 "without the reverse hunk to '%s'",
2913 patch->new_name
2914 ? patch->new_name : patch->old_name);
2915 fragment = fragment->next;
2917 switch (fragment->binary_patch_method) {
2918 case BINARY_DELTA_DEFLATED:
2919 dst = patch_delta(img->buf, img->len, fragment->patch,
2920 fragment->size, &len);
2921 if (!dst)
2922 return -1;
2923 clear_image(img);
2924 img->buf = dst;
2925 img->len = len;
2926 return 0;
2927 case BINARY_LITERAL_DEFLATED:
2928 clear_image(img);
2929 img->len = fragment->size;
2930 img->buf = xmemdupz(fragment->patch, img->len);
2931 return 0;
2933 return -1;
2937 * Replace "img" with the result of applying the binary patch.
2938 * The binary patch data itself in patch->fragment is still kept
2939 * but the preimage prepared by the caller in "img" is freed here
2940 * or in the helper function apply_binary_fragment() this calls.
2942 static int apply_binary(struct image *img, struct patch *patch)
2944 const char *name = patch->old_name ? patch->old_name : patch->new_name;
2945 unsigned char sha1[20];
2948 * For safety, we require patch index line to contain
2949 * full 40-byte textual SHA1 for old and new, at least for now.
2951 if (strlen(patch->old_sha1_prefix) != 40 ||
2952 strlen(patch->new_sha1_prefix) != 40 ||
2953 get_sha1_hex(patch->old_sha1_prefix, sha1) ||
2954 get_sha1_hex(patch->new_sha1_prefix, sha1))
2955 return error("cannot apply binary patch to '%s' "
2956 "without full index line", name);
2958 if (patch->old_name) {
2960 * See if the old one matches what the patch
2961 * applies to.
2963 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2964 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
2965 return error("the patch applies to '%s' (%s), "
2966 "which does not match the "
2967 "current contents.",
2968 name, sha1_to_hex(sha1));
2970 else {
2971 /* Otherwise, the old one must be empty. */
2972 if (img->len)
2973 return error("the patch applies to an empty "
2974 "'%s' but it is not empty", name);
2977 get_sha1_hex(patch->new_sha1_prefix, sha1);
2978 if (is_null_sha1(sha1)) {
2979 clear_image(img);
2980 return 0; /* deletion patch */
2983 if (has_sha1_file(sha1)) {
2984 /* We already have the postimage */
2985 enum object_type type;
2986 unsigned long size;
2987 char *result;
2989 result = read_sha1_file(sha1, &type, &size);
2990 if (!result)
2991 return error("the necessary postimage %s for "
2992 "'%s' cannot be read",
2993 patch->new_sha1_prefix, name);
2994 clear_image(img);
2995 img->buf = result;
2996 img->len = size;
2997 } else {
2999 * We have verified buf matches the preimage;
3000 * apply the patch data to it, which is stored
3001 * in the patch->fragments->{patch,size}.
3003 if (apply_binary_fragment(img, patch))
3004 return error(_("binary patch does not apply to '%s'"),
3005 name);
3007 /* verify that the result matches */
3008 hash_sha1_file(img->buf, img->len, blob_type, sha1);
3009 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
3010 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3011 name, patch->new_sha1_prefix, sha1_to_hex(sha1));
3014 return 0;
3017 static int apply_fragments(struct image *img, struct patch *patch)
3019 struct fragment *frag = patch->fragments;
3020 const char *name = patch->old_name ? patch->old_name : patch->new_name;
3021 unsigned ws_rule = patch->ws_rule;
3022 unsigned inaccurate_eof = patch->inaccurate_eof;
3023 int nth = 0;
3025 if (patch->is_binary)
3026 return apply_binary(img, patch);
3028 while (frag) {
3029 nth++;
3030 if (apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {
3031 error(_("patch failed: %s:%ld"), name, frag->oldpos);
3032 if (!apply_with_reject)
3033 return -1;
3034 frag->rejected = 1;
3036 frag = frag->next;
3038 return 0;
3041 static int read_blob_object(struct strbuf *buf, const unsigned char *sha1, unsigned mode)
3043 if (S_ISGITLINK(mode)) {
3044 strbuf_grow(buf, 100);
3045 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(sha1));
3046 } else {
3047 enum object_type type;
3048 unsigned long sz;
3049 char *result;
3051 result = read_sha1_file(sha1, &type, &sz);
3052 if (!result)
3053 return -1;
3054 /* XXX read_sha1_file NUL-terminates */
3055 strbuf_attach(buf, result, sz, sz + 1);
3057 return 0;
3060 static int read_file_or_gitlink(const struct cache_entry *ce, struct strbuf *buf)
3062 if (!ce)
3063 return 0;
3064 return read_blob_object(buf, ce->sha1, ce->ce_mode);
3067 static struct patch *in_fn_table(const char *name)
3069 struct string_list_item *item;
3071 if (name == NULL)
3072 return NULL;
3074 item = string_list_lookup(&fn_table, name);
3075 if (item != NULL)
3076 return (struct patch *)item->util;
3078 return NULL;
3082 * item->util in the filename table records the status of the path.
3083 * Usually it points at a patch (whose result records the contents
3084 * of it after applying it), but it could be PATH_WAS_DELETED for a
3085 * path that a previously applied patch has already removed, or
3086 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3088 * The latter is needed to deal with a case where two paths A and B
3089 * are swapped by first renaming A to B and then renaming B to A;
3090 * moving A to B should not be prevented due to presence of B as we
3091 * will remove it in a later patch.
3093 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3094 #define PATH_WAS_DELETED ((struct patch *) -1)
3096 static int to_be_deleted(struct patch *patch)
3098 return patch == PATH_TO_BE_DELETED;
3101 static int was_deleted(struct patch *patch)
3103 return patch == PATH_WAS_DELETED;
3106 static void add_to_fn_table(struct patch *patch)
3108 struct string_list_item *item;
3111 * Always add new_name unless patch is a deletion
3112 * This should cover the cases for normal diffs,
3113 * file creations and copies
3115 if (patch->new_name != NULL) {
3116 item = string_list_insert(&fn_table, patch->new_name);
3117 item->util = patch;
3121 * store a failure on rename/deletion cases because
3122 * later chunks shouldn't patch old names
3124 if ((patch->new_name == NULL) || (patch->is_rename)) {
3125 item = string_list_insert(&fn_table, patch->old_name);
3126 item->util = PATH_WAS_DELETED;
3130 static void prepare_fn_table(struct patch *patch)
3133 * store information about incoming file deletion
3135 while (patch) {
3136 if ((patch->new_name == NULL) || (patch->is_rename)) {
3137 struct string_list_item *item;
3138 item = string_list_insert(&fn_table, patch->old_name);
3139 item->util = PATH_TO_BE_DELETED;
3141 patch = patch->next;
3145 static int checkout_target(struct index_state *istate,
3146 struct cache_entry *ce, struct stat *st)
3148 struct checkout costate;
3150 memset(&costate, 0, sizeof(costate));
3151 costate.base_dir = "";
3152 costate.refresh_cache = 1;
3153 costate.istate = istate;
3154 if (checkout_entry(ce, &costate, NULL) || lstat(ce->name, st))
3155 return error(_("cannot checkout %s"), ce->name);
3156 return 0;
3159 static struct patch *previous_patch(struct patch *patch, int *gone)
3161 struct patch *previous;
3163 *gone = 0;
3164 if (patch->is_copy || patch->is_rename)
3165 return NULL; /* "git" patches do not depend on the order */
3167 previous = in_fn_table(patch->old_name);
3168 if (!previous)
3169 return NULL;
3171 if (to_be_deleted(previous))
3172 return NULL; /* the deletion hasn't happened yet */
3174 if (was_deleted(previous))
3175 *gone = 1;
3177 return previous;
3180 static int verify_index_match(const struct cache_entry *ce, struct stat *st)
3182 if (S_ISGITLINK(ce->ce_mode)) {
3183 if (!S_ISDIR(st->st_mode))
3184 return -1;
3185 return 0;
3187 return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
3190 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3192 static int load_patch_target(struct strbuf *buf,
3193 const struct cache_entry *ce,
3194 struct stat *st,
3195 const char *name,
3196 unsigned expected_mode)
3198 if (cached) {
3199 if (read_file_or_gitlink(ce, buf))
3200 return error(_("read of %s failed"), name);
3201 } else if (name) {
3202 if (S_ISGITLINK(expected_mode)) {
3203 if (ce)
3204 return read_file_or_gitlink(ce, buf);
3205 else
3206 return SUBMODULE_PATCH_WITHOUT_INDEX;
3207 } else {
3208 if (read_old_data(st, name, buf))
3209 return error(_("read of %s failed"), name);
3212 return 0;
3216 * We are about to apply "patch"; populate the "image" with the
3217 * current version we have, from the working tree or from the index,
3218 * depending on the situation e.g. --cached/--index. If we are
3219 * applying a non-git patch that incrementally updates the tree,
3220 * we read from the result of a previous diff.
3222 static int load_preimage(struct image *image,
3223 struct patch *patch, struct stat *st,
3224 const struct cache_entry *ce)
3226 struct strbuf buf = STRBUF_INIT;
3227 size_t len;
3228 char *img;
3229 struct patch *previous;
3230 int status;
3232 previous = previous_patch(patch, &status);
3233 if (status)
3234 return error(_("path %s has been renamed/deleted"),
3235 patch->old_name);
3236 if (previous) {
3237 /* We have a patched copy in memory; use that. */
3238 strbuf_add(&buf, previous->result, previous->resultsize);
3239 } else {
3240 status = load_patch_target(&buf, ce, st,
3241 patch->old_name, patch->old_mode);
3242 if (status < 0)
3243 return status;
3244 else if (status == SUBMODULE_PATCH_WITHOUT_INDEX) {
3246 * There is no way to apply subproject
3247 * patch without looking at the index.
3248 * NEEDSWORK: shouldn't this be flagged
3249 * as an error???
3251 free_fragment_list(patch->fragments);
3252 patch->fragments = NULL;
3253 } else if (status) {
3254 return error(_("read of %s failed"), patch->old_name);
3258 img = strbuf_detach(&buf, &len);
3259 prepare_image(image, img, len, !patch->is_binary);
3260 return 0;
3263 static int three_way_merge(struct image *image,
3264 char *path,
3265 const unsigned char *base,
3266 const unsigned char *ours,
3267 const unsigned char *theirs)
3269 mmfile_t base_file, our_file, their_file;
3270 mmbuffer_t result = { NULL };
3271 int status;
3273 read_mmblob(&base_file, base);
3274 read_mmblob(&our_file, ours);
3275 read_mmblob(&their_file, theirs);
3276 status = ll_merge(&result, path,
3277 &base_file, "base",
3278 &our_file, "ours",
3279 &their_file, "theirs", NULL);
3280 free(base_file.ptr);
3281 free(our_file.ptr);
3282 free(their_file.ptr);
3283 if (status < 0 || !result.ptr) {
3284 free(result.ptr);
3285 return -1;
3287 clear_image(image);
3288 image->buf = result.ptr;
3289 image->len = result.size;
3291 return status;
3295 * When directly falling back to add/add three-way merge, we read from
3296 * the current contents of the new_name. In no cases other than that
3297 * this function will be called.
3299 static int load_current(struct image *image, struct patch *patch)
3301 struct strbuf buf = STRBUF_INIT;
3302 int status, pos;
3303 size_t len;
3304 char *img;
3305 struct stat st;
3306 struct cache_entry *ce;
3307 char *name = patch->new_name;
3308 unsigned mode = patch->new_mode;
3310 if (!patch->is_new)
3311 die("BUG: patch to %s is not a creation", patch->old_name);
3313 pos = cache_name_pos(name, strlen(name));
3314 if (pos < 0)
3315 return error(_("%s: does not exist in index"), name);
3316 ce = active_cache[pos];
3317 if (lstat(name, &st)) {
3318 if (errno != ENOENT)
3319 return error(_("%s: %s"), name, strerror(errno));
3320 if (checkout_target(&the_index, ce, &st))
3321 return -1;
3323 if (verify_index_match(ce, &st))
3324 return error(_("%s: does not match index"), name);
3326 status = load_patch_target(&buf, ce, &st, name, mode);
3327 if (status < 0)
3328 return status;
3329 else if (status)
3330 return -1;
3331 img = strbuf_detach(&buf, &len);
3332 prepare_image(image, img, len, !patch->is_binary);
3333 return 0;
3336 static int try_threeway(struct image *image, struct patch *patch,
3337 struct stat *st, const struct cache_entry *ce)
3339 unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];
3340 struct strbuf buf = STRBUF_INIT;
3341 size_t len;
3342 int status;
3343 char *img;
3344 struct image tmp_image;
3346 /* No point falling back to 3-way merge in these cases */
3347 if (patch->is_delete ||
3348 S_ISGITLINK(patch->old_mode) || S_ISGITLINK(patch->new_mode))
3349 return -1;
3351 /* Preimage the patch was prepared for */
3352 if (patch->is_new)
3353 write_sha1_file("", 0, blob_type, pre_sha1);
3354 else if (get_sha1(patch->old_sha1_prefix, pre_sha1) ||
3355 read_blob_object(&buf, pre_sha1, patch->old_mode))
3356 return error("repository lacks the necessary blob to fall back on 3-way merge.");
3358 fprintf(stderr, "Falling back to three-way merge...\n");
3360 img = strbuf_detach(&buf, &len);
3361 prepare_image(&tmp_image, img, len, 1);
3362 /* Apply the patch to get the post image */
3363 if (apply_fragments(&tmp_image, patch) < 0) {
3364 clear_image(&tmp_image);
3365 return -1;
3367 /* post_sha1[] is theirs */
3368 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);
3369 clear_image(&tmp_image);
3371 /* our_sha1[] is ours */
3372 if (patch->is_new) {
3373 if (load_current(&tmp_image, patch))
3374 return error("cannot read the current contents of '%s'",
3375 patch->new_name);
3376 } else {
3377 if (load_preimage(&tmp_image, patch, st, ce))
3378 return error("cannot read the current contents of '%s'",
3379 patch->old_name);
3381 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);
3382 clear_image(&tmp_image);
3384 /* in-core three-way merge between post and our using pre as base */
3385 status = three_way_merge(image, patch->new_name,
3386 pre_sha1, our_sha1, post_sha1);
3387 if (status < 0) {
3388 fprintf(stderr, "Failed to fall back on three-way merge...\n");
3389 return status;
3392 if (status) {
3393 patch->conflicted_threeway = 1;
3394 if (patch->is_new)
3395 hashclr(patch->threeway_stage[0]);
3396 else
3397 hashcpy(patch->threeway_stage[0], pre_sha1);
3398 hashcpy(patch->threeway_stage[1], our_sha1);
3399 hashcpy(patch->threeway_stage[2], post_sha1);
3400 fprintf(stderr, "Applied patch to '%s' with conflicts.\n", patch->new_name);
3401 } else {
3402 fprintf(stderr, "Applied patch to '%s' cleanly.\n", patch->new_name);
3404 return 0;
3407 static int apply_data(struct patch *patch, struct stat *st, const struct cache_entry *ce)
3409 struct image image;
3411 if (load_preimage(&image, patch, st, ce) < 0)
3412 return -1;
3414 if (patch->direct_to_threeway ||
3415 apply_fragments(&image, patch) < 0) {
3416 /* Note: with --reject, apply_fragments() returns 0 */
3417 if (!threeway || try_threeway(&image, patch, st, ce) < 0)
3418 return -1;
3420 patch->result = image.buf;
3421 patch->resultsize = image.len;
3422 add_to_fn_table(patch);
3423 free(image.line_allocated);
3425 if (0 < patch->is_delete && patch->resultsize)
3426 return error(_("removal patch leaves file contents"));
3428 return 0;
3432 * If "patch" that we are looking at modifies or deletes what we have,
3433 * we would want it not to lose any local modification we have, either
3434 * in the working tree or in the index.
3436 * This also decides if a non-git patch is a creation patch or a
3437 * modification to an existing empty file. We do not check the state
3438 * of the current tree for a creation patch in this function; the caller
3439 * check_patch() separately makes sure (and errors out otherwise) that
3440 * the path the patch creates does not exist in the current tree.
3442 static int check_preimage(struct patch *patch, struct cache_entry **ce, struct stat *st)
3444 const char *old_name = patch->old_name;
3445 struct patch *previous = NULL;
3446 int stat_ret = 0, status;
3447 unsigned st_mode = 0;
3449 if (!old_name)
3450 return 0;
3452 assert(patch->is_new <= 0);
3453 previous = previous_patch(patch, &status);
3455 if (status)
3456 return error(_("path %s has been renamed/deleted"), old_name);
3457 if (previous) {
3458 st_mode = previous->new_mode;
3459 } else if (!cached) {
3460 stat_ret = lstat(old_name, st);
3461 if (stat_ret && errno != ENOENT)
3462 return error(_("%s: %s"), old_name, strerror(errno));
3465 if (check_index && !previous) {
3466 int pos = cache_name_pos(old_name, strlen(old_name));
3467 if (pos < 0) {
3468 if (patch->is_new < 0)
3469 goto is_new;
3470 return error(_("%s: does not exist in index"), old_name);
3472 *ce = active_cache[pos];
3473 if (stat_ret < 0) {
3474 if (checkout_target(&the_index, *ce, st))
3475 return -1;
3477 if (!cached && verify_index_match(*ce, st))
3478 return error(_("%s: does not match index"), old_name);
3479 if (cached)
3480 st_mode = (*ce)->ce_mode;
3481 } else if (stat_ret < 0) {
3482 if (patch->is_new < 0)
3483 goto is_new;
3484 return error(_("%s: %s"), old_name, strerror(errno));
3487 if (!cached && !previous)
3488 st_mode = ce_mode_from_stat(*ce, st->st_mode);
3490 if (patch->is_new < 0)
3491 patch->is_new = 0;
3492 if (!patch->old_mode)
3493 patch->old_mode = st_mode;
3494 if ((st_mode ^ patch->old_mode) & S_IFMT)
3495 return error(_("%s: wrong type"), old_name);
3496 if (st_mode != patch->old_mode)
3497 warning(_("%s has type %o, expected %o"),
3498 old_name, st_mode, patch->old_mode);
3499 if (!patch->new_mode && !patch->is_delete)
3500 patch->new_mode = st_mode;
3501 return 0;
3503 is_new:
3504 patch->is_new = 1;
3505 patch->is_delete = 0;
3506 free(patch->old_name);
3507 patch->old_name = NULL;
3508 return 0;
3512 #define EXISTS_IN_INDEX 1
3513 #define EXISTS_IN_WORKTREE 2
3515 static int check_to_create(const char *new_name, int ok_if_exists)
3517 struct stat nst;
3519 if (check_index &&
3520 cache_name_pos(new_name, strlen(new_name)) >= 0 &&
3521 !ok_if_exists)
3522 return EXISTS_IN_INDEX;
3523 if (cached)
3524 return 0;
3526 if (!lstat(new_name, &nst)) {
3527 if (S_ISDIR(nst.st_mode) || ok_if_exists)
3528 return 0;
3530 * A leading component of new_name might be a symlink
3531 * that is going to be removed with this patch, but
3532 * still pointing at somewhere that has the path.
3533 * In such a case, path "new_name" does not exist as
3534 * far as git is concerned.
3536 if (has_symlink_leading_path(new_name, strlen(new_name)))
3537 return 0;
3539 return EXISTS_IN_WORKTREE;
3540 } else if ((errno != ENOENT) && (errno != ENOTDIR)) {
3541 return error("%s: %s", new_name, strerror(errno));
3543 return 0;
3547 * Check and apply the patch in-core; leave the result in patch->result
3548 * for the caller to write it out to the final destination.
3550 static int check_patch(struct patch *patch)
3552 struct stat st;
3553 const char *old_name = patch->old_name;
3554 const char *new_name = patch->new_name;
3555 const char *name = old_name ? old_name : new_name;
3556 struct cache_entry *ce = NULL;
3557 struct patch *tpatch;
3558 int ok_if_exists;
3559 int status;
3561 patch->rejected = 1; /* we will drop this after we succeed */
3563 status = check_preimage(patch, &ce, &st);
3564 if (status)
3565 return status;
3566 old_name = patch->old_name;
3569 * A type-change diff is always split into a patch to delete
3570 * old, immediately followed by a patch to create new (see
3571 * diff.c::run_diff()); in such a case it is Ok that the entry
3572 * to be deleted by the previous patch is still in the working
3573 * tree and in the index.
3575 * A patch to swap-rename between A and B would first rename A
3576 * to B and then rename B to A. While applying the first one,
3577 * the presence of B should not stop A from getting renamed to
3578 * B; ask to_be_deleted() about the later rename. Removal of
3579 * B and rename from A to B is handled the same way by asking
3580 * was_deleted().
3582 if ((tpatch = in_fn_table(new_name)) &&
3583 (was_deleted(tpatch) || to_be_deleted(tpatch)))
3584 ok_if_exists = 1;
3585 else
3586 ok_if_exists = 0;
3588 if (new_name &&
3589 ((0 < patch->is_new) || patch->is_rename || patch->is_copy)) {
3590 int err = check_to_create(new_name, ok_if_exists);
3592 if (err && threeway) {
3593 patch->direct_to_threeway = 1;
3594 } else switch (err) {
3595 case 0:
3596 break; /* happy */
3597 case EXISTS_IN_INDEX:
3598 return error(_("%s: already exists in index"), new_name);
3599 break;
3600 case EXISTS_IN_WORKTREE:
3601 return error(_("%s: already exists in working directory"),
3602 new_name);
3603 default:
3604 return err;
3607 if (!patch->new_mode) {
3608 if (0 < patch->is_new)
3609 patch->new_mode = S_IFREG | 0644;
3610 else
3611 patch->new_mode = patch->old_mode;
3615 if (new_name && old_name) {
3616 int same = !strcmp(old_name, new_name);
3617 if (!patch->new_mode)
3618 patch->new_mode = patch->old_mode;
3619 if ((patch->old_mode ^ patch->new_mode) & S_IFMT) {
3620 if (same)
3621 return error(_("new mode (%o) of %s does not "
3622 "match old mode (%o)"),
3623 patch->new_mode, new_name,
3624 patch->old_mode);
3625 else
3626 return error(_("new mode (%o) of %s does not "
3627 "match old mode (%o) of %s"),
3628 patch->new_mode, new_name,
3629 patch->old_mode, old_name);
3633 if (apply_data(patch, &st, ce) < 0)
3634 return error(_("%s: patch does not apply"), name);
3635 patch->rejected = 0;
3636 return 0;
3639 static int check_patch_list(struct patch *patch)
3641 int err = 0;
3643 prepare_fn_table(patch);
3644 while (patch) {
3645 if (apply_verbosely)
3646 say_patch_name(stderr,
3647 _("Checking patch %s..."), patch);
3648 err |= check_patch(patch);
3649 patch = patch->next;
3651 return err;
3654 /* This function tries to read the sha1 from the current index */
3655 static int get_current_sha1(const char *path, unsigned char *sha1)
3657 int pos;
3659 if (read_cache() < 0)
3660 return -1;
3661 pos = cache_name_pos(path, strlen(path));
3662 if (pos < 0)
3663 return -1;
3664 hashcpy(sha1, active_cache[pos]->sha1);
3665 return 0;
3668 static int preimage_sha1_in_gitlink_patch(struct patch *p, unsigned char sha1[20])
3671 * A usable gitlink patch has only one fragment (hunk) that looks like:
3672 * @@ -1 +1 @@
3673 * -Subproject commit <old sha1>
3674 * +Subproject commit <new sha1>
3675 * or
3676 * @@ -1 +0,0 @@
3677 * -Subproject commit <old sha1>
3678 * for a removal patch.
3680 struct fragment *hunk = p->fragments;
3681 static const char heading[] = "-Subproject commit ";
3682 char *preimage;
3684 if (/* does the patch have only one hunk? */
3685 hunk && !hunk->next &&
3686 /* is its preimage one line? */
3687 hunk->oldpos == 1 && hunk->oldlines == 1 &&
3688 /* does preimage begin with the heading? */
3689 (preimage = memchr(hunk->patch, '\n', hunk->size)) != NULL &&
3690 starts_with(++preimage, heading) &&
3691 /* does it record full SHA-1? */
3692 !get_sha1_hex(preimage + sizeof(heading) - 1, sha1) &&
3693 preimage[sizeof(heading) + 40 - 1] == '\n' &&
3694 /* does the abbreviated name on the index line agree with it? */
3695 starts_with(preimage + sizeof(heading) - 1, p->old_sha1_prefix))
3696 return 0; /* it all looks fine */
3698 /* we may have full object name on the index line */
3699 return get_sha1_hex(p->old_sha1_prefix, sha1);
3702 /* Build an index that contains the just the files needed for a 3way merge */
3703 static void build_fake_ancestor(struct patch *list, const char *filename)
3705 struct patch *patch;
3706 struct index_state result = { NULL };
3707 static struct lock_file lock;
3709 /* Once we start supporting the reverse patch, it may be
3710 * worth showing the new sha1 prefix, but until then...
3712 for (patch = list; patch; patch = patch->next) {
3713 unsigned char sha1[20];
3714 struct cache_entry *ce;
3715 const char *name;
3717 name = patch->old_name ? patch->old_name : patch->new_name;
3718 if (0 < patch->is_new)
3719 continue;
3721 if (S_ISGITLINK(patch->old_mode)) {
3722 if (!preimage_sha1_in_gitlink_patch(patch, sha1))
3723 ; /* ok, the textual part looks sane */
3724 else
3725 die("sha1 information is lacking or useless for submoule %s",
3726 name);
3727 } else if (!get_sha1_blob(patch->old_sha1_prefix, sha1)) {
3728 ; /* ok */
3729 } else if (!patch->lines_added && !patch->lines_deleted) {
3730 /* mode-only change: update the current */
3731 if (get_current_sha1(patch->old_name, sha1))
3732 die("mode change for %s, which is not "
3733 "in current HEAD", name);
3734 } else
3735 die("sha1 information is lacking or useless "
3736 "(%s).", name);
3738 ce = make_cache_entry(patch->old_mode, sha1, name, 0, 0);
3739 if (!ce)
3740 die(_("make_cache_entry failed for path '%s'"), name);
3741 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))
3742 die ("Could not add %s to temporary index", name);
3745 hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);
3746 if (write_locked_index(&result, &lock, COMMIT_LOCK))
3747 die ("Could not write temporary index to %s", filename);
3749 discard_index(&result);
3752 static void stat_patch_list(struct patch *patch)
3754 int files, adds, dels;
3756 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
3757 files++;
3758 adds += patch->lines_added;
3759 dels += patch->lines_deleted;
3760 show_stats(patch);
3763 print_stat_summary(stdout, files, adds, dels);
3766 static void numstat_patch_list(struct patch *patch)
3768 for ( ; patch; patch = patch->next) {
3769 const char *name;
3770 name = patch->new_name ? patch->new_name : patch->old_name;
3771 if (patch->is_binary)
3772 printf("-\t-\t");
3773 else
3774 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
3775 write_name_quoted(name, stdout, line_termination);
3779 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
3781 if (mode)
3782 printf(" %s mode %06o %s\n", newdelete, mode, name);
3783 else
3784 printf(" %s %s\n", newdelete, name);
3787 static void show_mode_change(struct patch *p, int show_name)
3789 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
3790 if (show_name)
3791 printf(" mode change %06o => %06o %s\n",
3792 p->old_mode, p->new_mode, p->new_name);
3793 else
3794 printf(" mode change %06o => %06o\n",
3795 p->old_mode, p->new_mode);
3799 static void show_rename_copy(struct patch *p)
3801 const char *renamecopy = p->is_rename ? "rename" : "copy";
3802 const char *old, *new;
3804 /* Find common prefix */
3805 old = p->old_name;
3806 new = p->new_name;
3807 while (1) {
3808 const char *slash_old, *slash_new;
3809 slash_old = strchr(old, '/');
3810 slash_new = strchr(new, '/');
3811 if (!slash_old ||
3812 !slash_new ||
3813 slash_old - old != slash_new - new ||
3814 memcmp(old, new, slash_new - new))
3815 break;
3816 old = slash_old + 1;
3817 new = slash_new + 1;
3819 /* p->old_name thru old is the common prefix, and old and new
3820 * through the end of names are renames
3822 if (old != p->old_name)
3823 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
3824 (int)(old - p->old_name), p->old_name,
3825 old, new, p->score);
3826 else
3827 printf(" %s %s => %s (%d%%)\n", renamecopy,
3828 p->old_name, p->new_name, p->score);
3829 show_mode_change(p, 0);
3832 static void summary_patch_list(struct patch *patch)
3834 struct patch *p;
3836 for (p = patch; p; p = p->next) {
3837 if (p->is_new)
3838 show_file_mode_name("create", p->new_mode, p->new_name);
3839 else if (p->is_delete)
3840 show_file_mode_name("delete", p->old_mode, p->old_name);
3841 else {
3842 if (p->is_rename || p->is_copy)
3843 show_rename_copy(p);
3844 else {
3845 if (p->score) {
3846 printf(" rewrite %s (%d%%)\n",
3847 p->new_name, p->score);
3848 show_mode_change(p, 0);
3850 else
3851 show_mode_change(p, 1);
3857 static void patch_stats(struct patch *patch)
3859 int lines = patch->lines_added + patch->lines_deleted;
3861 if (lines > max_change)
3862 max_change = lines;
3863 if (patch->old_name) {
3864 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
3865 if (!len)
3866 len = strlen(patch->old_name);
3867 if (len > max_len)
3868 max_len = len;
3870 if (patch->new_name) {
3871 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
3872 if (!len)
3873 len = strlen(patch->new_name);
3874 if (len > max_len)
3875 max_len = len;
3879 static void remove_file(struct patch *patch, int rmdir_empty)
3881 if (update_index) {
3882 if (remove_file_from_cache(patch->old_name) < 0)
3883 die(_("unable to remove %s from index"), patch->old_name);
3885 if (!cached) {
3886 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
3887 remove_path(patch->old_name);
3892 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
3894 struct stat st;
3895 struct cache_entry *ce;
3896 int namelen = strlen(path);
3897 unsigned ce_size = cache_entry_size(namelen);
3899 if (!update_index)
3900 return;
3902 ce = xcalloc(1, ce_size);
3903 memcpy(ce->name, path, namelen);
3904 ce->ce_mode = create_ce_mode(mode);
3905 ce->ce_flags = create_ce_flags(0);
3906 ce->ce_namelen = namelen;
3907 if (S_ISGITLINK(mode)) {
3908 const char *s;
3910 if (!skip_prefix(buf, "Subproject commit ", &s) ||
3911 get_sha1_hex(s, ce->sha1))
3912 die(_("corrupt patch for submodule %s"), path);
3913 } else {
3914 if (!cached) {
3915 if (lstat(path, &st) < 0)
3916 die_errno(_("unable to stat newly created file '%s'"),
3917 path);
3918 fill_stat_cache_info(ce, &st);
3920 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
3921 die(_("unable to create backing store for newly created file %s"), path);
3923 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
3924 die(_("unable to add cache entry for %s"), path);
3927 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
3929 int fd;
3930 struct strbuf nbuf = STRBUF_INIT;
3932 if (S_ISGITLINK(mode)) {
3933 struct stat st;
3934 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
3935 return 0;
3936 return mkdir(path, 0777);
3939 if (has_symlinks && S_ISLNK(mode))
3940 /* Although buf:size is counted string, it also is NUL
3941 * terminated.
3943 return symlink(buf, path);
3945 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
3946 if (fd < 0)
3947 return -1;
3949 if (convert_to_working_tree(path, buf, size, &nbuf)) {
3950 size = nbuf.len;
3951 buf = nbuf.buf;
3953 write_or_die(fd, buf, size);
3954 strbuf_release(&nbuf);
3956 if (close(fd) < 0)
3957 die_errno(_("closing file '%s'"), path);
3958 return 0;
3962 * We optimistically assume that the directories exist,
3963 * which is true 99% of the time anyway. If they don't,
3964 * we create them and try again.
3966 static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
3968 if (cached)
3969 return;
3970 if (!try_create_file(path, mode, buf, size))
3971 return;
3973 if (errno == ENOENT) {
3974 if (safe_create_leading_directories(path))
3975 return;
3976 if (!try_create_file(path, mode, buf, size))
3977 return;
3980 if (errno == EEXIST || errno == EACCES) {
3981 /* We may be trying to create a file where a directory
3982 * used to be.
3984 struct stat st;
3985 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
3986 errno = EEXIST;
3989 if (errno == EEXIST) {
3990 unsigned int nr = getpid();
3992 for (;;) {
3993 char newpath[PATH_MAX];
3994 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
3995 if (!try_create_file(newpath, mode, buf, size)) {
3996 if (!rename(newpath, path))
3997 return;
3998 unlink_or_warn(newpath);
3999 break;
4001 if (errno != EEXIST)
4002 break;
4003 ++nr;
4006 die_errno(_("unable to write file '%s' mode %o"), path, mode);
4009 static void add_conflicted_stages_file(struct patch *patch)
4011 int stage, namelen;
4012 unsigned ce_size, mode;
4013 struct cache_entry *ce;
4015 if (!update_index)
4016 return;
4017 namelen = strlen(patch->new_name);
4018 ce_size = cache_entry_size(namelen);
4019 mode = patch->new_mode ? patch->new_mode : (S_IFREG | 0644);
4021 remove_file_from_cache(patch->new_name);
4022 for (stage = 1; stage < 4; stage++) {
4023 if (is_null_sha1(patch->threeway_stage[stage - 1]))
4024 continue;
4025 ce = xcalloc(1, ce_size);
4026 memcpy(ce->name, patch->new_name, namelen);
4027 ce->ce_mode = create_ce_mode(mode);
4028 ce->ce_flags = create_ce_flags(stage);
4029 ce->ce_namelen = namelen;
4030 hashcpy(ce->sha1, patch->threeway_stage[stage - 1]);
4031 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
4032 die(_("unable to add cache entry for %s"), patch->new_name);
4036 static void create_file(struct patch *patch)
4038 char *path = patch->new_name;
4039 unsigned mode = patch->new_mode;
4040 unsigned long size = patch->resultsize;
4041 char *buf = patch->result;
4043 if (!mode)
4044 mode = S_IFREG | 0644;
4045 create_one_file(path, mode, buf, size);
4047 if (patch->conflicted_threeway)
4048 add_conflicted_stages_file(patch);
4049 else
4050 add_index_file(path, mode, buf, size);
4053 /* phase zero is to remove, phase one is to create */
4054 static void write_out_one_result(struct patch *patch, int phase)
4056 if (patch->is_delete > 0) {
4057 if (phase == 0)
4058 remove_file(patch, 1);
4059 return;
4061 if (patch->is_new > 0 || patch->is_copy) {
4062 if (phase == 1)
4063 create_file(patch);
4064 return;
4067 * Rename or modification boils down to the same
4068 * thing: remove the old, write the new
4070 if (phase == 0)
4071 remove_file(patch, patch->is_rename);
4072 if (phase == 1)
4073 create_file(patch);
4076 static int write_out_one_reject(struct patch *patch)
4078 FILE *rej;
4079 char namebuf[PATH_MAX];
4080 struct fragment *frag;
4081 int cnt = 0;
4082 struct strbuf sb = STRBUF_INIT;
4084 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
4085 if (!frag->rejected)
4086 continue;
4087 cnt++;
4090 if (!cnt) {
4091 if (apply_verbosely)
4092 say_patch_name(stderr,
4093 _("Applied patch %s cleanly."), patch);
4094 return 0;
4097 /* This should not happen, because a removal patch that leaves
4098 * contents are marked "rejected" at the patch level.
4100 if (!patch->new_name)
4101 die(_("internal error"));
4103 /* Say this even without --verbose */
4104 strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",
4105 "Applying patch %%s with %d rejects...",
4106 cnt),
4107 cnt);
4108 say_patch_name(stderr, sb.buf, patch);
4109 strbuf_release(&sb);
4111 cnt = strlen(patch->new_name);
4112 if (ARRAY_SIZE(namebuf) <= cnt + 5) {
4113 cnt = ARRAY_SIZE(namebuf) - 5;
4114 warning(_("truncating .rej filename to %.*s.rej"),
4115 cnt - 1, patch->new_name);
4117 memcpy(namebuf, patch->new_name, cnt);
4118 memcpy(namebuf + cnt, ".rej", 5);
4120 rej = fopen(namebuf, "w");
4121 if (!rej)
4122 return error(_("cannot open %s: %s"), namebuf, strerror(errno));
4124 /* Normal git tools never deal with .rej, so do not pretend
4125 * this is a git patch by saying --git or giving extended
4126 * headers. While at it, maybe please "kompare" that wants
4127 * the trailing TAB and some garbage at the end of line ;-).
4129 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
4130 patch->new_name, patch->new_name);
4131 for (cnt = 1, frag = patch->fragments;
4132 frag;
4133 cnt++, frag = frag->next) {
4134 if (!frag->rejected) {
4135 fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);
4136 continue;
4138 fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);
4139 fprintf(rej, "%.*s", frag->size, frag->patch);
4140 if (frag->patch[frag->size-1] != '\n')
4141 fputc('\n', rej);
4143 fclose(rej);
4144 return -1;
4147 static int write_out_results(struct patch *list)
4149 int phase;
4150 int errs = 0;
4151 struct patch *l;
4152 struct string_list cpath = STRING_LIST_INIT_DUP;
4154 for (phase = 0; phase < 2; phase++) {
4155 l = list;
4156 while (l) {
4157 if (l->rejected)
4158 errs = 1;
4159 else {
4160 write_out_one_result(l, phase);
4161 if (phase == 1) {
4162 if (write_out_one_reject(l))
4163 errs = 1;
4164 if (l->conflicted_threeway) {
4165 string_list_append(&cpath, l->new_name);
4166 errs = 1;
4170 l = l->next;
4174 if (cpath.nr) {
4175 struct string_list_item *item;
4177 sort_string_list(&cpath);
4178 for_each_string_list_item(item, &cpath)
4179 fprintf(stderr, "U %s\n", item->string);
4180 string_list_clear(&cpath, 0);
4182 rerere(0);
4185 return errs;
4188 static struct lock_file lock_file;
4190 #define INACCURATE_EOF (1<<0)
4191 #define RECOUNT (1<<1)
4193 static int apply_patch(int fd, const char *filename, int options)
4195 size_t offset;
4196 struct strbuf buf = STRBUF_INIT; /* owns the patch text */
4197 struct patch *list = NULL, **listp = &list;
4198 int skipped_patch = 0;
4200 patch_input_file = filename;
4201 read_patch_file(&buf, fd);
4202 offset = 0;
4203 while (offset < buf.len) {
4204 struct patch *patch;
4205 int nr;
4207 patch = xcalloc(1, sizeof(*patch));
4208 patch->inaccurate_eof = !!(options & INACCURATE_EOF);
4209 patch->recount = !!(options & RECOUNT);
4210 nr = parse_chunk(buf.buf + offset, buf.len - offset, patch);
4211 if (nr < 0)
4212 break;
4213 if (apply_in_reverse)
4214 reverse_patches(patch);
4215 if (use_patch(patch)) {
4216 patch_stats(patch);
4217 *listp = patch;
4218 listp = &patch->next;
4220 else {
4221 free_patch(patch);
4222 skipped_patch++;
4224 offset += nr;
4227 if (!list && !skipped_patch)
4228 die(_("unrecognized input"));
4230 if (whitespace_error && (ws_error_action == die_on_ws_error))
4231 apply = 0;
4233 update_index = check_index && apply;
4234 if (update_index && newfd < 0)
4235 newfd = hold_locked_index(&lock_file, 1);
4237 if (check_index) {
4238 if (read_cache() < 0)
4239 die(_("unable to read index file"));
4242 if ((check || apply) &&
4243 check_patch_list(list) < 0 &&
4244 !apply_with_reject)
4245 exit(1);
4247 if (apply && write_out_results(list)) {
4248 if (apply_with_reject)
4249 exit(1);
4250 /* with --3way, we still need to write the index out */
4251 return 1;
4254 if (fake_ancestor)
4255 build_fake_ancestor(list, fake_ancestor);
4257 if (diffstat)
4258 stat_patch_list(list);
4260 if (numstat)
4261 numstat_patch_list(list);
4263 if (summary)
4264 summary_patch_list(list);
4266 free_patch_list(list);
4267 strbuf_release(&buf);
4268 string_list_clear(&fn_table, 0);
4269 return 0;
4272 static void git_apply_config(void)
4274 git_config_get_string_const("apply.whitespace", &apply_default_whitespace);
4275 git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);
4276 git_config(git_default_config, NULL);
4279 static int option_parse_exclude(const struct option *opt,
4280 const char *arg, int unset)
4282 add_name_limit(arg, 1);
4283 return 0;
4286 static int option_parse_include(const struct option *opt,
4287 const char *arg, int unset)
4289 add_name_limit(arg, 0);
4290 has_include = 1;
4291 return 0;
4294 static int option_parse_p(const struct option *opt,
4295 const char *arg, int unset)
4297 p_value = atoi(arg);
4298 p_value_known = 1;
4299 return 0;
4302 static int option_parse_z(const struct option *opt,
4303 const char *arg, int unset)
4305 if (unset)
4306 line_termination = '\n';
4307 else
4308 line_termination = 0;
4309 return 0;
4312 static int option_parse_space_change(const struct option *opt,
4313 const char *arg, int unset)
4315 if (unset)
4316 ws_ignore_action = ignore_ws_none;
4317 else
4318 ws_ignore_action = ignore_ws_change;
4319 return 0;
4322 static int option_parse_whitespace(const struct option *opt,
4323 const char *arg, int unset)
4325 const char **whitespace_option = opt->value;
4327 *whitespace_option = arg;
4328 parse_whitespace_option(arg);
4329 return 0;
4332 static int option_parse_directory(const struct option *opt,
4333 const char *arg, int unset)
4335 root_len = strlen(arg);
4336 if (root_len && arg[root_len - 1] != '/') {
4337 char *new_root;
4338 root = new_root = xmalloc(root_len + 2);
4339 strcpy(new_root, arg);
4340 strcpy(new_root + root_len++, "/");
4341 } else
4342 root = arg;
4343 return 0;
4346 int cmd_apply(int argc, const char **argv, const char *prefix_)
4348 int i;
4349 int errs = 0;
4350 int is_not_gitdir = !startup_info->have_repository;
4351 int force_apply = 0;
4353 const char *whitespace_option = NULL;
4355 struct option builtin_apply_options[] = {
4356 { OPTION_CALLBACK, 0, "exclude", NULL, N_("path"),
4357 N_("don't apply changes matching the given path"),
4358 0, option_parse_exclude },
4359 { OPTION_CALLBACK, 0, "include", NULL, N_("path"),
4360 N_("apply changes matching the given path"),
4361 0, option_parse_include },
4362 { OPTION_CALLBACK, 'p', NULL, NULL, N_("num"),
4363 N_("remove <num> leading slashes from traditional diff paths"),
4364 0, option_parse_p },
4365 OPT_BOOL(0, "no-add", &no_add,
4366 N_("ignore additions made by the patch")),
4367 OPT_BOOL(0, "stat", &diffstat,
4368 N_("instead of applying the patch, output diffstat for the input")),
4369 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
4370 OPT_NOOP_NOARG(0, "binary"),
4371 OPT_BOOL(0, "numstat", &numstat,
4372 N_("show number of added and deleted lines in decimal notation")),
4373 OPT_BOOL(0, "summary", &summary,
4374 N_("instead of applying the patch, output a summary for the input")),
4375 OPT_BOOL(0, "check", &check,
4376 N_("instead of applying the patch, see if the patch is applicable")),
4377 OPT_BOOL(0, "index", &check_index,
4378 N_("make sure the patch is applicable to the current index")),
4379 OPT_BOOL(0, "cached", &cached,
4380 N_("apply a patch without touching the working tree")),
4381 OPT_BOOL(0, "apply", &force_apply,
4382 N_("also apply the patch (use with --stat/--summary/--check)")),
4383 OPT_BOOL('3', "3way", &threeway,
4384 N_( "attempt three-way merge if a patch does not apply")),
4385 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor,
4386 N_("build a temporary index based on embedded index information")),
4387 { OPTION_CALLBACK, 'z', NULL, NULL, NULL,
4388 N_("paths are separated with NUL character"),
4389 PARSE_OPT_NOARG, option_parse_z },
4390 OPT_INTEGER('C', NULL, &p_context,
4391 N_("ensure at least <n> lines of context match")),
4392 { OPTION_CALLBACK, 0, "whitespace", &whitespace_option, N_("action"),
4393 N_("detect new or modified lines that have whitespace errors"),
4394 0, option_parse_whitespace },
4395 { OPTION_CALLBACK, 0, "ignore-space-change", NULL, NULL,
4396 N_("ignore changes in whitespace when finding context"),
4397 PARSE_OPT_NOARG, option_parse_space_change },
4398 { OPTION_CALLBACK, 0, "ignore-whitespace", NULL, NULL,
4399 N_("ignore changes in whitespace when finding context"),
4400 PARSE_OPT_NOARG, option_parse_space_change },
4401 OPT_BOOL('R', "reverse", &apply_in_reverse,
4402 N_("apply the patch in reverse")),
4403 OPT_BOOL(0, "unidiff-zero", &unidiff_zero,
4404 N_("don't expect at least one line of context")),
4405 OPT_BOOL(0, "reject", &apply_with_reject,
4406 N_("leave the rejected hunks in corresponding *.rej files")),
4407 OPT_BOOL(0, "allow-overlap", &allow_overlap,
4408 N_("allow overlapping hunks")),
4409 OPT__VERBOSE(&apply_verbosely, N_("be verbose")),
4410 OPT_BIT(0, "inaccurate-eof", &options,
4411 N_("tolerate incorrectly detected missing new-line at the end of file"),
4412 INACCURATE_EOF),
4413 OPT_BIT(0, "recount", &options,
4414 N_("do not trust the line counts in the hunk headers"),
4415 RECOUNT),
4416 { OPTION_CALLBACK, 0, "directory", NULL, N_("root"),
4417 N_("prepend <root> to all filenames"),
4418 0, option_parse_directory },
4419 OPT_END()
4422 prefix = prefix_;
4423 prefix_length = prefix ? strlen(prefix) : 0;
4424 git_apply_config();
4425 if (apply_default_whitespace)
4426 parse_whitespace_option(apply_default_whitespace);
4427 if (apply_default_ignorewhitespace)
4428 parse_ignorewhitespace_option(apply_default_ignorewhitespace);
4430 argc = parse_options(argc, argv, prefix, builtin_apply_options,
4431 apply_usage, 0);
4433 if (apply_with_reject && threeway)
4434 die("--reject and --3way cannot be used together.");
4435 if (cached && threeway)
4436 die("--cached and --3way cannot be used together.");
4437 if (threeway) {
4438 if (is_not_gitdir)
4439 die(_("--3way outside a repository"));
4440 check_index = 1;
4442 if (apply_with_reject)
4443 apply = apply_verbosely = 1;
4444 if (!force_apply && (diffstat || numstat || summary || check || fake_ancestor))
4445 apply = 0;
4446 if (check_index && is_not_gitdir)
4447 die(_("--index outside a repository"));
4448 if (cached) {
4449 if (is_not_gitdir)
4450 die(_("--cached outside a repository"));
4451 check_index = 1;
4453 for (i = 0; i < argc; i++) {
4454 const char *arg = argv[i];
4455 int fd;
4457 if (!strcmp(arg, "-")) {
4458 errs |= apply_patch(0, "<stdin>", options);
4459 read_stdin = 0;
4460 continue;
4461 } else if (0 < prefix_length)
4462 arg = prefix_filename(prefix, prefix_length, arg);
4464 fd = open(arg, O_RDONLY);
4465 if (fd < 0)
4466 die_errno(_("can't open patch '%s'"), arg);
4467 read_stdin = 0;
4468 set_default_whitespace_mode(whitespace_option);
4469 errs |= apply_patch(fd, arg, options);
4470 close(fd);
4472 set_default_whitespace_mode(whitespace_option);
4473 if (read_stdin)
4474 errs |= apply_patch(0, "<stdin>", options);
4475 if (whitespace_error) {
4476 if (squelch_whitespace_errors &&
4477 squelch_whitespace_errors < whitespace_error) {
4478 int squelched =
4479 whitespace_error - squelch_whitespace_errors;
4480 warning(Q_("squelched %d whitespace error",
4481 "squelched %d whitespace errors",
4482 squelched),
4483 squelched);
4485 if (ws_error_action == die_on_ws_error)
4486 die(Q_("%d line adds whitespace errors.",
4487 "%d lines add whitespace errors.",
4488 whitespace_error),
4489 whitespace_error);
4490 if (applied_after_fixing_ws && apply)
4491 warning("%d line%s applied after"
4492 " fixing whitespace errors.",
4493 applied_after_fixing_ws,
4494 applied_after_fixing_ws == 1 ? "" : "s");
4495 else if (whitespace_error)
4496 warning(Q_("%d line adds whitespace errors.",
4497 "%d lines add whitespace errors.",
4498 whitespace_error),
4499 whitespace_error);
4502 if (update_index) {
4503 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
4504 die(_("Unable to write new index file"));
4507 return !!errs;