i18n: branch: mark parseopt strings for translation
[git/jnareb-git.git] / builtin / apply.c
blobd453c833782c6aae4dd04fb9f9f68c3a8211d3d5
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 unsigned long deflate_origlen;
192 int lines_added, lines_deleted;
193 int score;
194 unsigned int is_toplevel_relative:1;
195 unsigned int inaccurate_eof:1;
196 unsigned int is_binary:1;
197 unsigned int is_copy:1;
198 unsigned int is_rename:1;
199 unsigned int recount:1;
200 unsigned int conflicted_threeway:1;
201 unsigned int direct_to_threeway:1;
202 struct fragment *fragments;
203 char *result;
204 size_t resultsize;
205 char old_sha1_prefix[41];
206 char new_sha1_prefix[41];
207 struct patch *next;
209 /* three-way fallback result */
210 unsigned char threeway_stage[3][20];
213 static void free_fragment_list(struct fragment *list)
215 while (list) {
216 struct fragment *next = list->next;
217 if (list->free_patch)
218 free((char *)list->patch);
219 free(list);
220 list = next;
224 static void free_patch(struct patch *patch)
226 free_fragment_list(patch->fragments);
227 free(patch->def_name);
228 free(patch->old_name);
229 free(patch->new_name);
230 free(patch->result);
231 free(patch);
234 static void free_patch_list(struct patch *list)
236 while (list) {
237 struct patch *next = list->next;
238 free_patch(list);
239 list = next;
244 * A line in a file, len-bytes long (includes the terminating LF,
245 * except for an incomplete line at the end if the file ends with
246 * one), and its contents hashes to 'hash'.
248 struct line {
249 size_t len;
250 unsigned hash : 24;
251 unsigned flag : 8;
252 #define LINE_COMMON 1
253 #define LINE_PATCHED 2
257 * This represents a "file", which is an array of "lines".
259 struct image {
260 char *buf;
261 size_t len;
262 size_t nr;
263 size_t alloc;
264 struct line *line_allocated;
265 struct line *line;
269 * Records filenames that have been touched, in order to handle
270 * the case where more than one patches touch the same file.
273 static struct string_list fn_table;
275 static uint32_t hash_line(const char *cp, size_t len)
277 size_t i;
278 uint32_t h;
279 for (i = 0, h = 0; i < len; i++) {
280 if (!isspace(cp[i])) {
281 h = h * 3 + (cp[i] & 0xff);
284 return h;
288 * Compare lines s1 of length n1 and s2 of length n2, ignoring
289 * whitespace difference. Returns 1 if they match, 0 otherwise
291 static int fuzzy_matchlines(const char *s1, size_t n1,
292 const char *s2, size_t n2)
294 const char *last1 = s1 + n1 - 1;
295 const char *last2 = s2 + n2 - 1;
296 int result = 0;
298 /* ignore line endings */
299 while ((*last1 == '\r') || (*last1 == '\n'))
300 last1--;
301 while ((*last2 == '\r') || (*last2 == '\n'))
302 last2--;
304 /* skip leading whitespace */
305 while (isspace(*s1) && (s1 <= last1))
306 s1++;
307 while (isspace(*s2) && (s2 <= last2))
308 s2++;
309 /* early return if both lines are empty */
310 if ((s1 > last1) && (s2 > last2))
311 return 1;
312 while (!result) {
313 result = *s1++ - *s2++;
315 * Skip whitespace inside. We check for whitespace on
316 * both buffers because we don't want "a b" to match
317 * "ab"
319 if (isspace(*s1) && isspace(*s2)) {
320 while (isspace(*s1) && s1 <= last1)
321 s1++;
322 while (isspace(*s2) && s2 <= last2)
323 s2++;
326 * If we reached the end on one side only,
327 * lines don't match
329 if (
330 ((s2 > last2) && (s1 <= last1)) ||
331 ((s1 > last1) && (s2 <= last2)))
332 return 0;
333 if ((s1 > last1) && (s2 > last2))
334 break;
337 return !result;
340 static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
342 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
343 img->line_allocated[img->nr].len = len;
344 img->line_allocated[img->nr].hash = hash_line(bol, len);
345 img->line_allocated[img->nr].flag = flag;
346 img->nr++;
350 * "buf" has the file contents to be patched (read from various sources).
351 * attach it to "image" and add line-based index to it.
352 * "image" now owns the "buf".
354 static void prepare_image(struct image *image, char *buf, size_t len,
355 int prepare_linetable)
357 const char *cp, *ep;
359 memset(image, 0, sizeof(*image));
360 image->buf = buf;
361 image->len = len;
363 if (!prepare_linetable)
364 return;
366 ep = image->buf + image->len;
367 cp = image->buf;
368 while (cp < ep) {
369 const char *next;
370 for (next = cp; next < ep && *next != '\n'; next++)
372 if (next < ep)
373 next++;
374 add_line_info(image, cp, next - cp, 0);
375 cp = next;
377 image->line = image->line_allocated;
380 static void clear_image(struct image *image)
382 free(image->buf);
383 free(image->line_allocated);
384 memset(image, 0, sizeof(*image));
387 /* fmt must contain _one_ %s and no other substitution */
388 static void say_patch_name(FILE *output, const char *fmt, struct patch *patch)
390 struct strbuf sb = STRBUF_INIT;
392 if (patch->old_name && patch->new_name &&
393 strcmp(patch->old_name, patch->new_name)) {
394 quote_c_style(patch->old_name, &sb, NULL, 0);
395 strbuf_addstr(&sb, " => ");
396 quote_c_style(patch->new_name, &sb, NULL, 0);
397 } else {
398 const char *n = patch->new_name;
399 if (!n)
400 n = patch->old_name;
401 quote_c_style(n, &sb, NULL, 0);
403 fprintf(output, fmt, sb.buf);
404 fputc('\n', output);
405 strbuf_release(&sb);
408 #define SLOP (16)
410 static void read_patch_file(struct strbuf *sb, int fd)
412 if (strbuf_read(sb, fd, 0) < 0)
413 die_errno("git apply: failed to read");
416 * Make sure that we have some slop in the buffer
417 * so that we can do speculative "memcmp" etc, and
418 * see to it that it is NUL-filled.
420 strbuf_grow(sb, SLOP);
421 memset(sb->buf + sb->len, 0, SLOP);
424 static unsigned long linelen(const char *buffer, unsigned long size)
426 unsigned long len = 0;
427 while (size--) {
428 len++;
429 if (*buffer++ == '\n')
430 break;
432 return len;
435 static int is_dev_null(const char *str)
437 return !memcmp("/dev/null", str, 9) && isspace(str[9]);
440 #define TERM_SPACE 1
441 #define TERM_TAB 2
443 static int name_terminate(const char *name, int namelen, int c, int terminate)
445 if (c == ' ' && !(terminate & TERM_SPACE))
446 return 0;
447 if (c == '\t' && !(terminate & TERM_TAB))
448 return 0;
450 return 1;
453 /* remove double slashes to make --index work with such filenames */
454 static char *squash_slash(char *name)
456 int i = 0, j = 0;
458 if (!name)
459 return NULL;
461 while (name[i]) {
462 if ((name[j++] = name[i++]) == '/')
463 while (name[i] == '/')
464 i++;
466 name[j] = '\0';
467 return name;
470 static char *find_name_gnu(const char *line, const char *def, int p_value)
472 struct strbuf name = STRBUF_INIT;
473 char *cp;
476 * Proposed "new-style" GNU patch/diff format; see
477 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
479 if (unquote_c_style(&name, line, NULL)) {
480 strbuf_release(&name);
481 return NULL;
484 for (cp = name.buf; p_value; p_value--) {
485 cp = strchr(cp, '/');
486 if (!cp) {
487 strbuf_release(&name);
488 return NULL;
490 cp++;
493 strbuf_remove(&name, 0, cp - name.buf);
494 if (root)
495 strbuf_insert(&name, 0, root, root_len);
496 return squash_slash(strbuf_detach(&name, NULL));
499 static size_t sane_tz_len(const char *line, size_t len)
501 const char *tz, *p;
503 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
504 return 0;
505 tz = line + len - strlen(" +0500");
507 if (tz[1] != '+' && tz[1] != '-')
508 return 0;
510 for (p = tz + 2; p != line + len; p++)
511 if (!isdigit(*p))
512 return 0;
514 return line + len - tz;
517 static size_t tz_with_colon_len(const char *line, size_t len)
519 const char *tz, *p;
521 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
522 return 0;
523 tz = line + len - strlen(" +08:00");
525 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
526 return 0;
527 p = tz + 2;
528 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
529 !isdigit(*p++) || !isdigit(*p++))
530 return 0;
532 return line + len - tz;
535 static size_t date_len(const char *line, size_t len)
537 const char *date, *p;
539 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
540 return 0;
541 p = date = line + len - strlen("72-02-05");
543 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
544 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
545 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */
546 return 0;
548 if (date - line >= strlen("19") &&
549 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */
550 date -= strlen("19");
552 return line + len - date;
555 static size_t short_time_len(const char *line, size_t len)
557 const char *time, *p;
559 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
560 return 0;
561 p = time = line + len - strlen(" 07:01:32");
563 /* Permit 1-digit hours? */
564 if (*p++ != ' ' ||
565 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
566 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
567 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */
568 return 0;
570 return line + len - time;
573 static size_t fractional_time_len(const char *line, size_t len)
575 const char *p;
576 size_t n;
578 /* Expected format: 19:41:17.620000023 */
579 if (!len || !isdigit(line[len - 1]))
580 return 0;
581 p = line + len - 1;
583 /* Fractional seconds. */
584 while (p > line && isdigit(*p))
585 p--;
586 if (*p != '.')
587 return 0;
589 /* Hours, minutes, and whole seconds. */
590 n = short_time_len(line, p - line);
591 if (!n)
592 return 0;
594 return line + len - p + n;
597 static size_t trailing_spaces_len(const char *line, size_t len)
599 const char *p;
601 /* Expected format: ' ' x (1 or more) */
602 if (!len || line[len - 1] != ' ')
603 return 0;
605 p = line + len;
606 while (p != line) {
607 p--;
608 if (*p != ' ')
609 return line + len - (p + 1);
612 /* All spaces! */
613 return len;
616 static size_t diff_timestamp_len(const char *line, size_t len)
618 const char *end = line + len;
619 size_t n;
622 * Posix: 2010-07-05 19:41:17
623 * GNU: 2010-07-05 19:41:17.620000023 -0500
626 if (!isdigit(end[-1]))
627 return 0;
629 n = sane_tz_len(line, end - line);
630 if (!n)
631 n = tz_with_colon_len(line, end - line);
632 end -= n;
634 n = short_time_len(line, end - line);
635 if (!n)
636 n = fractional_time_len(line, end - line);
637 end -= n;
639 n = date_len(line, end - line);
640 if (!n) /* No date. Too bad. */
641 return 0;
642 end -= n;
644 if (end == line) /* No space before date. */
645 return 0;
646 if (end[-1] == '\t') { /* Success! */
647 end--;
648 return line + len - end;
650 if (end[-1] != ' ') /* No space before date. */
651 return 0;
653 /* Whitespace damage. */
654 end -= trailing_spaces_len(line, end - line);
655 return line + len - end;
658 static char *null_strdup(const char *s)
660 return s ? xstrdup(s) : NULL;
663 static char *find_name_common(const char *line, const char *def,
664 int p_value, const char *end, int terminate)
666 int len;
667 const char *start = NULL;
669 if (p_value == 0)
670 start = line;
671 while (line != end) {
672 char c = *line;
674 if (!end && isspace(c)) {
675 if (c == '\n')
676 break;
677 if (name_terminate(start, line-start, c, terminate))
678 break;
680 line++;
681 if (c == '/' && !--p_value)
682 start = line;
684 if (!start)
685 return squash_slash(null_strdup(def));
686 len = line - start;
687 if (!len)
688 return squash_slash(null_strdup(def));
691 * Generally we prefer the shorter name, especially
692 * if the other one is just a variation of that with
693 * something else tacked on to the end (ie "file.orig"
694 * or "file~").
696 if (def) {
697 int deflen = strlen(def);
698 if (deflen < len && !strncmp(start, def, deflen))
699 return squash_slash(xstrdup(def));
702 if (root) {
703 char *ret = xmalloc(root_len + len + 1);
704 strcpy(ret, root);
705 memcpy(ret + root_len, start, len);
706 ret[root_len + len] = '\0';
707 return squash_slash(ret);
710 return squash_slash(xmemdupz(start, len));
713 static char *find_name(const char *line, char *def, int p_value, int terminate)
715 if (*line == '"') {
716 char *name = find_name_gnu(line, def, p_value);
717 if (name)
718 return name;
721 return find_name_common(line, def, p_value, NULL, terminate);
724 static char *find_name_traditional(const char *line, char *def, int p_value)
726 size_t len = strlen(line);
727 size_t date_len;
729 if (*line == '"') {
730 char *name = find_name_gnu(line, def, p_value);
731 if (name)
732 return name;
735 len = strchrnul(line, '\n') - line;
736 date_len = diff_timestamp_len(line, len);
737 if (!date_len)
738 return find_name_common(line, def, p_value, NULL, TERM_TAB);
739 len -= date_len;
741 return find_name_common(line, def, p_value, line + len, 0);
744 static int count_slashes(const char *cp)
746 int cnt = 0;
747 char ch;
749 while ((ch = *cp++))
750 if (ch == '/')
751 cnt++;
752 return cnt;
756 * Given the string after "--- " or "+++ ", guess the appropriate
757 * p_value for the given patch.
759 static int guess_p_value(const char *nameline)
761 char *name, *cp;
762 int val = -1;
764 if (is_dev_null(nameline))
765 return -1;
766 name = find_name_traditional(nameline, NULL, 0);
767 if (!name)
768 return -1;
769 cp = strchr(name, '/');
770 if (!cp)
771 val = 0;
772 else if (prefix) {
774 * Does it begin with "a/$our-prefix" and such? Then this is
775 * very likely to apply to our directory.
777 if (!strncmp(name, prefix, prefix_length))
778 val = count_slashes(prefix);
779 else {
780 cp++;
781 if (!strncmp(cp, prefix, prefix_length))
782 val = count_slashes(prefix) + 1;
785 free(name);
786 return val;
790 * Does the ---/+++ line has the POSIX timestamp after the last HT?
791 * GNU diff puts epoch there to signal a creation/deletion event. Is
792 * this such a timestamp?
794 static int has_epoch_timestamp(const char *nameline)
797 * We are only interested in epoch timestamp; any non-zero
798 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
799 * For the same reason, the date must be either 1969-12-31 or
800 * 1970-01-01, and the seconds part must be "00".
802 const char stamp_regexp[] =
803 "^(1969-12-31|1970-01-01)"
805 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
807 "([-+][0-2][0-9]:?[0-5][0-9])\n";
808 const char *timestamp = NULL, *cp, *colon;
809 static regex_t *stamp;
810 regmatch_t m[10];
811 int zoneoffset;
812 int hourminute;
813 int status;
815 for (cp = nameline; *cp != '\n'; cp++) {
816 if (*cp == '\t')
817 timestamp = cp + 1;
819 if (!timestamp)
820 return 0;
821 if (!stamp) {
822 stamp = xmalloc(sizeof(*stamp));
823 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
824 warning(_("Cannot prepare timestamp regexp %s"),
825 stamp_regexp);
826 return 0;
830 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
831 if (status) {
832 if (status != REG_NOMATCH)
833 warning(_("regexec returned %d for input: %s"),
834 status, timestamp);
835 return 0;
838 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
839 if (*colon == ':')
840 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
841 else
842 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
843 if (timestamp[m[3].rm_so] == '-')
844 zoneoffset = -zoneoffset;
847 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
848 * (west of GMT) or 1970-01-01 (east of GMT)
850 if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) ||
851 (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10)))
852 return 0;
854 hourminute = (strtol(timestamp + 11, NULL, 10) * 60 +
855 strtol(timestamp + 14, NULL, 10) -
856 zoneoffset);
858 return ((zoneoffset < 0 && hourminute == 1440) ||
859 (0 <= zoneoffset && !hourminute));
863 * Get the name etc info from the ---/+++ lines of a traditional patch header
865 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
866 * files, we can happily check the index for a match, but for creating a
867 * new file we should try to match whatever "patch" does. I have no idea.
869 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
871 char *name;
873 first += 4; /* skip "--- " */
874 second += 4; /* skip "+++ " */
875 if (!p_value_known) {
876 int p, q;
877 p = guess_p_value(first);
878 q = guess_p_value(second);
879 if (p < 0) p = q;
880 if (0 <= p && p == q) {
881 p_value = p;
882 p_value_known = 1;
885 if (is_dev_null(first)) {
886 patch->is_new = 1;
887 patch->is_delete = 0;
888 name = find_name_traditional(second, NULL, p_value);
889 patch->new_name = name;
890 } else if (is_dev_null(second)) {
891 patch->is_new = 0;
892 patch->is_delete = 1;
893 name = find_name_traditional(first, NULL, p_value);
894 patch->old_name = name;
895 } else {
896 char *first_name;
897 first_name = find_name_traditional(first, NULL, p_value);
898 name = find_name_traditional(second, first_name, p_value);
899 free(first_name);
900 if (has_epoch_timestamp(first)) {
901 patch->is_new = 1;
902 patch->is_delete = 0;
903 patch->new_name = name;
904 } else if (has_epoch_timestamp(second)) {
905 patch->is_new = 0;
906 patch->is_delete = 1;
907 patch->old_name = name;
908 } else {
909 patch->old_name = name;
910 patch->new_name = xstrdup(name);
913 if (!name)
914 die(_("unable to find filename in patch at line %d"), linenr);
917 static int gitdiff_hdrend(const char *line, struct patch *patch)
919 return -1;
923 * We're anal about diff header consistency, to make
924 * sure that we don't end up having strange ambiguous
925 * patches floating around.
927 * As a result, gitdiff_{old|new}name() will check
928 * their names against any previous information, just
929 * to make sure..
931 #define DIFF_OLD_NAME 0
932 #define DIFF_NEW_NAME 1
934 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, int side)
936 if (!orig_name && !isnull)
937 return find_name(line, NULL, p_value, TERM_TAB);
939 if (orig_name) {
940 int len;
941 const char *name;
942 char *another;
943 name = orig_name;
944 len = strlen(name);
945 if (isnull)
946 die(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"), name, linenr);
947 another = find_name(line, NULL, p_value, TERM_TAB);
948 if (!another || memcmp(another, name, len + 1))
949 die((side == DIFF_NEW_NAME) ?
950 _("git apply: bad git-diff - inconsistent new filename on line %d") :
951 _("git apply: bad git-diff - inconsistent old filename on line %d"), linenr);
952 free(another);
953 return orig_name;
955 else {
956 /* expect "/dev/null" */
957 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
958 die(_("git apply: bad git-diff - expected /dev/null on line %d"), linenr);
959 return NULL;
963 static int gitdiff_oldname(const char *line, struct patch *patch)
965 char *orig = patch->old_name;
966 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name,
967 DIFF_OLD_NAME);
968 if (orig != patch->old_name)
969 free(orig);
970 return 0;
973 static int gitdiff_newname(const char *line, struct patch *patch)
975 char *orig = patch->new_name;
976 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name,
977 DIFF_NEW_NAME);
978 if (orig != patch->new_name)
979 free(orig);
980 return 0;
983 static int gitdiff_oldmode(const char *line, struct patch *patch)
985 patch->old_mode = strtoul(line, NULL, 8);
986 return 0;
989 static int gitdiff_newmode(const char *line, struct patch *patch)
991 patch->new_mode = strtoul(line, NULL, 8);
992 return 0;
995 static int gitdiff_delete(const char *line, struct patch *patch)
997 patch->is_delete = 1;
998 free(patch->old_name);
999 patch->old_name = null_strdup(patch->def_name);
1000 return gitdiff_oldmode(line, patch);
1003 static int gitdiff_newfile(const char *line, struct patch *patch)
1005 patch->is_new = 1;
1006 free(patch->new_name);
1007 patch->new_name = null_strdup(patch->def_name);
1008 return gitdiff_newmode(line, patch);
1011 static int gitdiff_copysrc(const char *line, struct patch *patch)
1013 patch->is_copy = 1;
1014 free(patch->old_name);
1015 patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1016 return 0;
1019 static int gitdiff_copydst(const char *line, struct patch *patch)
1021 patch->is_copy = 1;
1022 free(patch->new_name);
1023 patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1024 return 0;
1027 static int gitdiff_renamesrc(const char *line, struct patch *patch)
1029 patch->is_rename = 1;
1030 free(patch->old_name);
1031 patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1032 return 0;
1035 static int gitdiff_renamedst(const char *line, struct patch *patch)
1037 patch->is_rename = 1;
1038 free(patch->new_name);
1039 patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
1040 return 0;
1043 static int gitdiff_similarity(const char *line, struct patch *patch)
1045 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
1046 patch->score = 0;
1047 return 0;
1050 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
1052 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
1053 patch->score = 0;
1054 return 0;
1057 static int gitdiff_index(const char *line, struct patch *patch)
1060 * index line is N hexadecimal, "..", N hexadecimal,
1061 * and optional space with octal mode.
1063 const char *ptr, *eol;
1064 int len;
1066 ptr = strchr(line, '.');
1067 if (!ptr || ptr[1] != '.' || 40 < ptr - line)
1068 return 0;
1069 len = ptr - line;
1070 memcpy(patch->old_sha1_prefix, line, len);
1071 patch->old_sha1_prefix[len] = 0;
1073 line = ptr + 2;
1074 ptr = strchr(line, ' ');
1075 eol = strchr(line, '\n');
1077 if (!ptr || eol < ptr)
1078 ptr = eol;
1079 len = ptr - line;
1081 if (40 < len)
1082 return 0;
1083 memcpy(patch->new_sha1_prefix, line, len);
1084 patch->new_sha1_prefix[len] = 0;
1085 if (*ptr == ' ')
1086 patch->old_mode = strtoul(ptr+1, NULL, 8);
1087 return 0;
1091 * This is normal for a diff that doesn't change anything: we'll fall through
1092 * into the next diff. Tell the parser to break out.
1094 static int gitdiff_unrecognized(const char *line, struct patch *patch)
1096 return -1;
1099 static const char *stop_at_slash(const char *line, int llen)
1101 int nslash = p_value;
1102 int i;
1104 for (i = 0; i < llen; i++) {
1105 int ch = line[i];
1106 if (ch == '/' && --nslash <= 0)
1107 return &line[i];
1109 return NULL;
1113 * This is to extract the same name that appears on "diff --git"
1114 * line. We do not find and return anything if it is a rename
1115 * patch, and it is OK because we will find the name elsewhere.
1116 * We need to reliably find name only when it is mode-change only,
1117 * creation or deletion of an empty file. In any of these cases,
1118 * both sides are the same name under a/ and b/ respectively.
1120 static char *git_header_name(const char *line, int llen)
1122 const char *name;
1123 const char *second = NULL;
1124 size_t len, line_len;
1126 line += strlen("diff --git ");
1127 llen -= strlen("diff --git ");
1129 if (*line == '"') {
1130 const char *cp;
1131 struct strbuf first = STRBUF_INIT;
1132 struct strbuf sp = STRBUF_INIT;
1134 if (unquote_c_style(&first, line, &second))
1135 goto free_and_fail1;
1137 /* advance to the first slash */
1138 cp = stop_at_slash(first.buf, first.len);
1139 /* we do not accept absolute paths */
1140 if (!cp || cp == first.buf)
1141 goto free_and_fail1;
1142 strbuf_remove(&first, 0, cp + 1 - first.buf);
1145 * second points at one past closing dq of name.
1146 * find the second name.
1148 while ((second < line + llen) && isspace(*second))
1149 second++;
1151 if (line + llen <= second)
1152 goto free_and_fail1;
1153 if (*second == '"') {
1154 if (unquote_c_style(&sp, second, NULL))
1155 goto free_and_fail1;
1156 cp = stop_at_slash(sp.buf, sp.len);
1157 if (!cp || cp == sp.buf)
1158 goto free_and_fail1;
1159 /* They must match, otherwise ignore */
1160 if (strcmp(cp + 1, first.buf))
1161 goto free_and_fail1;
1162 strbuf_release(&sp);
1163 return strbuf_detach(&first, NULL);
1166 /* unquoted second */
1167 cp = stop_at_slash(second, line + llen - second);
1168 if (!cp || cp == second)
1169 goto free_and_fail1;
1170 cp++;
1171 if (line + llen - cp != first.len + 1 ||
1172 memcmp(first.buf, cp, first.len))
1173 goto free_and_fail1;
1174 return strbuf_detach(&first, NULL);
1176 free_and_fail1:
1177 strbuf_release(&first);
1178 strbuf_release(&sp);
1179 return NULL;
1182 /* unquoted first name */
1183 name = stop_at_slash(line, llen);
1184 if (!name || name == line)
1185 return NULL;
1186 name++;
1189 * since the first name is unquoted, a dq if exists must be
1190 * the beginning of the second name.
1192 for (second = name; second < line + llen; second++) {
1193 if (*second == '"') {
1194 struct strbuf sp = STRBUF_INIT;
1195 const char *np;
1197 if (unquote_c_style(&sp, second, NULL))
1198 goto free_and_fail2;
1200 np = stop_at_slash(sp.buf, sp.len);
1201 if (!np || np == sp.buf)
1202 goto free_and_fail2;
1203 np++;
1205 len = sp.buf + sp.len - np;
1206 if (len < second - name &&
1207 !strncmp(np, name, len) &&
1208 isspace(name[len])) {
1209 /* Good */
1210 strbuf_remove(&sp, 0, np - sp.buf);
1211 return strbuf_detach(&sp, NULL);
1214 free_and_fail2:
1215 strbuf_release(&sp);
1216 return NULL;
1221 * Accept a name only if it shows up twice, exactly the same
1222 * form.
1224 second = strchr(name, '\n');
1225 if (!second)
1226 return NULL;
1227 line_len = second - name;
1228 for (len = 0 ; ; len++) {
1229 switch (name[len]) {
1230 default:
1231 continue;
1232 case '\n':
1233 return NULL;
1234 case '\t': case ' ':
1235 second = stop_at_slash(name + len, line_len - len);
1236 if (!second)
1237 return NULL;
1238 second++;
1239 if (second[len] == '\n' && !strncmp(name, second, len)) {
1240 return xmemdupz(name, len);
1246 /* Verify that we recognize the lines following a git header */
1247 static int parse_git_header(const char *line, int len, unsigned int size, struct patch *patch)
1249 unsigned long offset;
1251 /* A git diff has explicit new/delete information, so we don't guess */
1252 patch->is_new = 0;
1253 patch->is_delete = 0;
1256 * Some things may not have the old name in the
1257 * rest of the headers anywhere (pure mode changes,
1258 * or removing or adding empty files), so we get
1259 * the default name from the header.
1261 patch->def_name = git_header_name(line, len);
1262 if (patch->def_name && root) {
1263 char *s = xmalloc(root_len + strlen(patch->def_name) + 1);
1264 strcpy(s, root);
1265 strcpy(s + root_len, patch->def_name);
1266 free(patch->def_name);
1267 patch->def_name = s;
1270 line += len;
1271 size -= len;
1272 linenr++;
1273 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
1274 static const struct opentry {
1275 const char *str;
1276 int (*fn)(const char *, struct patch *);
1277 } optable[] = {
1278 { "@@ -", gitdiff_hdrend },
1279 { "--- ", gitdiff_oldname },
1280 { "+++ ", gitdiff_newname },
1281 { "old mode ", gitdiff_oldmode },
1282 { "new mode ", gitdiff_newmode },
1283 { "deleted file mode ", gitdiff_delete },
1284 { "new file mode ", gitdiff_newfile },
1285 { "copy from ", gitdiff_copysrc },
1286 { "copy to ", gitdiff_copydst },
1287 { "rename old ", gitdiff_renamesrc },
1288 { "rename new ", gitdiff_renamedst },
1289 { "rename from ", gitdiff_renamesrc },
1290 { "rename to ", gitdiff_renamedst },
1291 { "similarity index ", gitdiff_similarity },
1292 { "dissimilarity index ", gitdiff_dissimilarity },
1293 { "index ", gitdiff_index },
1294 { "", gitdiff_unrecognized },
1296 int i;
1298 len = linelen(line, size);
1299 if (!len || line[len-1] != '\n')
1300 break;
1301 for (i = 0; i < ARRAY_SIZE(optable); i++) {
1302 const struct opentry *p = optable + i;
1303 int oplen = strlen(p->str);
1304 if (len < oplen || memcmp(p->str, line, oplen))
1305 continue;
1306 if (p->fn(line + oplen, patch) < 0)
1307 return offset;
1308 break;
1312 return offset;
1315 static int parse_num(const char *line, unsigned long *p)
1317 char *ptr;
1319 if (!isdigit(*line))
1320 return 0;
1321 *p = strtoul(line, &ptr, 10);
1322 return ptr - line;
1325 static int parse_range(const char *line, int len, int offset, const char *expect,
1326 unsigned long *p1, unsigned long *p2)
1328 int digits, ex;
1330 if (offset < 0 || offset >= len)
1331 return -1;
1332 line += offset;
1333 len -= offset;
1335 digits = parse_num(line, p1);
1336 if (!digits)
1337 return -1;
1339 offset += digits;
1340 line += digits;
1341 len -= digits;
1343 *p2 = 1;
1344 if (*line == ',') {
1345 digits = parse_num(line+1, p2);
1346 if (!digits)
1347 return -1;
1349 offset += digits+1;
1350 line += digits+1;
1351 len -= digits+1;
1354 ex = strlen(expect);
1355 if (ex > len)
1356 return -1;
1357 if (memcmp(line, expect, ex))
1358 return -1;
1360 return offset + ex;
1363 static void recount_diff(const char *line, int size, struct fragment *fragment)
1365 int oldlines = 0, newlines = 0, ret = 0;
1367 if (size < 1) {
1368 warning("recount: ignore empty hunk");
1369 return;
1372 for (;;) {
1373 int len = linelen(line, size);
1374 size -= len;
1375 line += len;
1377 if (size < 1)
1378 break;
1380 switch (*line) {
1381 case ' ': case '\n':
1382 newlines++;
1383 /* fall through */
1384 case '-':
1385 oldlines++;
1386 continue;
1387 case '+':
1388 newlines++;
1389 continue;
1390 case '\\':
1391 continue;
1392 case '@':
1393 ret = size < 3 || prefixcmp(line, "@@ ");
1394 break;
1395 case 'd':
1396 ret = size < 5 || prefixcmp(line, "diff ");
1397 break;
1398 default:
1399 ret = -1;
1400 break;
1402 if (ret) {
1403 warning(_("recount: unexpected line: %.*s"),
1404 (int)linelen(line, size), line);
1405 return;
1407 break;
1409 fragment->oldlines = oldlines;
1410 fragment->newlines = newlines;
1414 * Parse a unified diff fragment header of the
1415 * form "@@ -a,b +c,d @@"
1417 static int parse_fragment_header(const char *line, int len, struct fragment *fragment)
1419 int offset;
1421 if (!len || line[len-1] != '\n')
1422 return -1;
1424 /* Figure out the number of lines in a fragment */
1425 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1426 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1428 return offset;
1431 static int find_header(const char *line, unsigned long size, int *hdrsize, struct patch *patch)
1433 unsigned long offset, len;
1435 patch->is_toplevel_relative = 0;
1436 patch->is_rename = patch->is_copy = 0;
1437 patch->is_new = patch->is_delete = -1;
1438 patch->old_mode = patch->new_mode = 0;
1439 patch->old_name = patch->new_name = NULL;
1440 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
1441 unsigned long nextlen;
1443 len = linelen(line, size);
1444 if (!len)
1445 break;
1447 /* Testing this early allows us to take a few shortcuts.. */
1448 if (len < 6)
1449 continue;
1452 * Make sure we don't find any unconnected patch fragments.
1453 * That's a sign that we didn't find a header, and that a
1454 * patch has become corrupted/broken up.
1456 if (!memcmp("@@ -", line, 4)) {
1457 struct fragment dummy;
1458 if (parse_fragment_header(line, len, &dummy) < 0)
1459 continue;
1460 die(_("patch fragment without header at line %d: %.*s"),
1461 linenr, (int)len-1, line);
1464 if (size < len + 6)
1465 break;
1468 * Git patch? It might not have a real patch, just a rename
1469 * or mode change, so we handle that specially
1471 if (!memcmp("diff --git ", line, 11)) {
1472 int git_hdr_len = parse_git_header(line, len, size, patch);
1473 if (git_hdr_len <= len)
1474 continue;
1475 if (!patch->old_name && !patch->new_name) {
1476 if (!patch->def_name)
1477 die(Q_("git diff header lacks filename information when removing "
1478 "%d leading pathname component (line %d)",
1479 "git diff header lacks filename information when removing "
1480 "%d leading pathname components (line %d)",
1481 p_value),
1482 p_value, linenr);
1483 patch->old_name = xstrdup(patch->def_name);
1484 patch->new_name = xstrdup(patch->def_name);
1486 if (!patch->is_delete && !patch->new_name)
1487 die("git diff header lacks filename information "
1488 "(line %d)", linenr);
1489 patch->is_toplevel_relative = 1;
1490 *hdrsize = git_hdr_len;
1491 return offset;
1494 /* --- followed by +++ ? */
1495 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1496 continue;
1499 * We only accept unified patches, so we want it to
1500 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1501 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1503 nextlen = linelen(line + len, size - len);
1504 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1505 continue;
1507 /* Ok, we'll consider it a patch */
1508 parse_traditional_patch(line, line+len, patch);
1509 *hdrsize = len + nextlen;
1510 linenr += 2;
1511 return offset;
1513 return -1;
1516 static void record_ws_error(unsigned result, const char *line, int len, int linenr)
1518 char *err;
1520 if (!result)
1521 return;
1523 whitespace_error++;
1524 if (squelch_whitespace_errors &&
1525 squelch_whitespace_errors < whitespace_error)
1526 return;
1528 err = whitespace_error_string(result);
1529 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1530 patch_input_file, linenr, err, len, line);
1531 free(err);
1534 static void check_whitespace(const char *line, int len, unsigned ws_rule)
1536 unsigned result = ws_check(line + 1, len - 1, ws_rule);
1538 record_ws_error(result, line + 1, len - 2, linenr);
1542 * Parse a unified diff. Note that this really needs to parse each
1543 * fragment separately, since the only way to know the difference
1544 * between a "---" that is part of a patch, and a "---" that starts
1545 * the next patch is to look at the line counts..
1547 static int parse_fragment(const char *line, unsigned long size,
1548 struct patch *patch, struct fragment *fragment)
1550 int added, deleted;
1551 int len = linelen(line, size), offset;
1552 unsigned long oldlines, newlines;
1553 unsigned long leading, trailing;
1555 offset = parse_fragment_header(line, len, fragment);
1556 if (offset < 0)
1557 return -1;
1558 if (offset > 0 && patch->recount)
1559 recount_diff(line + offset, size - offset, fragment);
1560 oldlines = fragment->oldlines;
1561 newlines = fragment->newlines;
1562 leading = 0;
1563 trailing = 0;
1565 /* Parse the thing.. */
1566 line += len;
1567 size -= len;
1568 linenr++;
1569 added = deleted = 0;
1570 for (offset = len;
1571 0 < size;
1572 offset += len, size -= len, line += len, linenr++) {
1573 if (!oldlines && !newlines)
1574 break;
1575 len = linelen(line, size);
1576 if (!len || line[len-1] != '\n')
1577 return -1;
1578 switch (*line) {
1579 default:
1580 return -1;
1581 case '\n': /* newer GNU diff, an empty context line */
1582 case ' ':
1583 oldlines--;
1584 newlines--;
1585 if (!deleted && !added)
1586 leading++;
1587 trailing++;
1588 break;
1589 case '-':
1590 if (apply_in_reverse &&
1591 ws_error_action != nowarn_ws_error)
1592 check_whitespace(line, len, patch->ws_rule);
1593 deleted++;
1594 oldlines--;
1595 trailing = 0;
1596 break;
1597 case '+':
1598 if (!apply_in_reverse &&
1599 ws_error_action != nowarn_ws_error)
1600 check_whitespace(line, len, patch->ws_rule);
1601 added++;
1602 newlines--;
1603 trailing = 0;
1604 break;
1607 * We allow "\ No newline at end of file". Depending
1608 * on locale settings when the patch was produced we
1609 * don't know what this line looks like. The only
1610 * thing we do know is that it begins with "\ ".
1611 * Checking for 12 is just for sanity check -- any
1612 * l10n of "\ No newline..." is at least that long.
1614 case '\\':
1615 if (len < 12 || memcmp(line, "\\ ", 2))
1616 return -1;
1617 break;
1620 if (oldlines || newlines)
1621 return -1;
1622 fragment->leading = leading;
1623 fragment->trailing = trailing;
1626 * If a fragment ends with an incomplete line, we failed to include
1627 * it in the above loop because we hit oldlines == newlines == 0
1628 * before seeing it.
1630 if (12 < size && !memcmp(line, "\\ ", 2))
1631 offset += linelen(line, size);
1633 patch->lines_added += added;
1634 patch->lines_deleted += deleted;
1636 if (0 < patch->is_new && oldlines)
1637 return error(_("new file depends on old contents"));
1638 if (0 < patch->is_delete && newlines)
1639 return error(_("deleted file still has contents"));
1640 return offset;
1644 * We have seen "diff --git a/... b/..." header (or a traditional patch
1645 * header). Read hunks that belong to this patch into fragments and hang
1646 * them to the given patch structure.
1648 * The (fragment->patch, fragment->size) pair points into the memory given
1649 * by the caller, not a copy, when we return.
1651 static int parse_single_patch(const char *line, unsigned long size, struct patch *patch)
1653 unsigned long offset = 0;
1654 unsigned long oldlines = 0, newlines = 0, context = 0;
1655 struct fragment **fragp = &patch->fragments;
1657 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1658 struct fragment *fragment;
1659 int len;
1661 fragment = xcalloc(1, sizeof(*fragment));
1662 fragment->linenr = linenr;
1663 len = parse_fragment(line, size, patch, fragment);
1664 if (len <= 0)
1665 die(_("corrupt patch at line %d"), linenr);
1666 fragment->patch = line;
1667 fragment->size = len;
1668 oldlines += fragment->oldlines;
1669 newlines += fragment->newlines;
1670 context += fragment->leading + fragment->trailing;
1672 *fragp = fragment;
1673 fragp = &fragment->next;
1675 offset += len;
1676 line += len;
1677 size -= len;
1681 * If something was removed (i.e. we have old-lines) it cannot
1682 * be creation, and if something was added it cannot be
1683 * deletion. However, the reverse is not true; --unified=0
1684 * patches that only add are not necessarily creation even
1685 * though they do not have any old lines, and ones that only
1686 * delete are not necessarily deletion.
1688 * Unfortunately, a real creation/deletion patch do _not_ have
1689 * any context line by definition, so we cannot safely tell it
1690 * apart with --unified=0 insanity. At least if the patch has
1691 * more than one hunk it is not creation or deletion.
1693 if (patch->is_new < 0 &&
1694 (oldlines || (patch->fragments && patch->fragments->next)))
1695 patch->is_new = 0;
1696 if (patch->is_delete < 0 &&
1697 (newlines || (patch->fragments && patch->fragments->next)))
1698 patch->is_delete = 0;
1700 if (0 < patch->is_new && oldlines)
1701 die(_("new file %s depends on old contents"), patch->new_name);
1702 if (0 < patch->is_delete && newlines)
1703 die(_("deleted file %s still has contents"), patch->old_name);
1704 if (!patch->is_delete && !newlines && context)
1705 fprintf_ln(stderr,
1706 _("** warning: "
1707 "file %s becomes empty but is not deleted"),
1708 patch->new_name);
1710 return offset;
1713 static inline int metadata_changes(struct patch *patch)
1715 return patch->is_rename > 0 ||
1716 patch->is_copy > 0 ||
1717 patch->is_new > 0 ||
1718 patch->is_delete ||
1719 (patch->old_mode && patch->new_mode &&
1720 patch->old_mode != patch->new_mode);
1723 static char *inflate_it(const void *data, unsigned long size,
1724 unsigned long inflated_size)
1726 git_zstream stream;
1727 void *out;
1728 int st;
1730 memset(&stream, 0, sizeof(stream));
1732 stream.next_in = (unsigned char *)data;
1733 stream.avail_in = size;
1734 stream.next_out = out = xmalloc(inflated_size);
1735 stream.avail_out = inflated_size;
1736 git_inflate_init(&stream);
1737 st = git_inflate(&stream, Z_FINISH);
1738 git_inflate_end(&stream);
1739 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1740 free(out);
1741 return NULL;
1743 return out;
1747 * Read a binary hunk and return a new fragment; fragment->patch
1748 * points at an allocated memory that the caller must free, so
1749 * it is marked as "->free_patch = 1".
1751 static struct fragment *parse_binary_hunk(char **buf_p,
1752 unsigned long *sz_p,
1753 int *status_p,
1754 int *used_p)
1757 * Expect a line that begins with binary patch method ("literal"
1758 * or "delta"), followed by the length of data before deflating.
1759 * a sequence of 'length-byte' followed by base-85 encoded data
1760 * should follow, terminated by a newline.
1762 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1763 * and we would limit the patch line to 66 characters,
1764 * so one line can fit up to 13 groups that would decode
1765 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1766 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1768 int llen, used;
1769 unsigned long size = *sz_p;
1770 char *buffer = *buf_p;
1771 int patch_method;
1772 unsigned long origlen;
1773 char *data = NULL;
1774 int hunk_size = 0;
1775 struct fragment *frag;
1777 llen = linelen(buffer, size);
1778 used = llen;
1780 *status_p = 0;
1782 if (!prefixcmp(buffer, "delta ")) {
1783 patch_method = BINARY_DELTA_DEFLATED;
1784 origlen = strtoul(buffer + 6, NULL, 10);
1786 else if (!prefixcmp(buffer, "literal ")) {
1787 patch_method = BINARY_LITERAL_DEFLATED;
1788 origlen = strtoul(buffer + 8, NULL, 10);
1790 else
1791 return NULL;
1793 linenr++;
1794 buffer += llen;
1795 while (1) {
1796 int byte_length, max_byte_length, newsize;
1797 llen = linelen(buffer, size);
1798 used += llen;
1799 linenr++;
1800 if (llen == 1) {
1801 /* consume the blank line */
1802 buffer++;
1803 size--;
1804 break;
1807 * Minimum line is "A00000\n" which is 7-byte long,
1808 * and the line length must be multiple of 5 plus 2.
1810 if ((llen < 7) || (llen-2) % 5)
1811 goto corrupt;
1812 max_byte_length = (llen - 2) / 5 * 4;
1813 byte_length = *buffer;
1814 if ('A' <= byte_length && byte_length <= 'Z')
1815 byte_length = byte_length - 'A' + 1;
1816 else if ('a' <= byte_length && byte_length <= 'z')
1817 byte_length = byte_length - 'a' + 27;
1818 else
1819 goto corrupt;
1820 /* if the input length was not multiple of 4, we would
1821 * have filler at the end but the filler should never
1822 * exceed 3 bytes
1824 if (max_byte_length < byte_length ||
1825 byte_length <= max_byte_length - 4)
1826 goto corrupt;
1827 newsize = hunk_size + byte_length;
1828 data = xrealloc(data, newsize);
1829 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1830 goto corrupt;
1831 hunk_size = newsize;
1832 buffer += llen;
1833 size -= llen;
1836 frag = xcalloc(1, sizeof(*frag));
1837 frag->patch = inflate_it(data, hunk_size, origlen);
1838 frag->free_patch = 1;
1839 if (!frag->patch)
1840 goto corrupt;
1841 free(data);
1842 frag->size = origlen;
1843 *buf_p = buffer;
1844 *sz_p = size;
1845 *used_p = used;
1846 frag->binary_patch_method = patch_method;
1847 return frag;
1849 corrupt:
1850 free(data);
1851 *status_p = -1;
1852 error(_("corrupt binary patch at line %d: %.*s"),
1853 linenr-1, llen-1, buffer);
1854 return NULL;
1857 static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1860 * We have read "GIT binary patch\n"; what follows is a line
1861 * that says the patch method (currently, either "literal" or
1862 * "delta") and the length of data before deflating; a
1863 * sequence of 'length-byte' followed by base-85 encoded data
1864 * follows.
1866 * When a binary patch is reversible, there is another binary
1867 * hunk in the same format, starting with patch method (either
1868 * "literal" or "delta") with the length of data, and a sequence
1869 * of length-byte + base-85 encoded data, terminated with another
1870 * empty line. This data, when applied to the postimage, produces
1871 * the preimage.
1873 struct fragment *forward;
1874 struct fragment *reverse;
1875 int status;
1876 int used, used_1;
1878 forward = parse_binary_hunk(&buffer, &size, &status, &used);
1879 if (!forward && !status)
1880 /* there has to be one hunk (forward hunk) */
1881 return error(_("unrecognized binary patch at line %d"), linenr-1);
1882 if (status)
1883 /* otherwise we already gave an error message */
1884 return status;
1886 reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1887 if (reverse)
1888 used += used_1;
1889 else if (status) {
1891 * Not having reverse hunk is not an error, but having
1892 * a corrupt reverse hunk is.
1894 free((void*) forward->patch);
1895 free(forward);
1896 return status;
1898 forward->next = reverse;
1899 patch->fragments = forward;
1900 patch->is_binary = 1;
1901 return used;
1905 * Read the patch text in "buffer" taht extends for "size" bytes; stop
1906 * reading after seeing a single patch (i.e. changes to a single file).
1907 * Create fragments (i.e. patch hunks) and hang them to the given patch.
1908 * Return the number of bytes consumed, so that the caller can call us
1909 * again for the next patch.
1911 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
1913 int hdrsize, patchsize;
1914 int offset = find_header(buffer, size, &hdrsize, patch);
1916 if (offset < 0)
1917 return offset;
1919 patch->ws_rule = whitespace_rule(patch->new_name
1920 ? patch->new_name
1921 : patch->old_name);
1923 patchsize = parse_single_patch(buffer + offset + hdrsize,
1924 size - offset - hdrsize, patch);
1926 if (!patchsize) {
1927 static const char *binhdr[] = {
1928 "Binary files ",
1929 "Files ",
1930 NULL,
1932 static const char git_binary[] = "GIT binary patch\n";
1933 int i;
1934 int hd = hdrsize + offset;
1935 unsigned long llen = linelen(buffer + hd, size - hd);
1937 if (llen == sizeof(git_binary) - 1 &&
1938 !memcmp(git_binary, buffer + hd, llen)) {
1939 int used;
1940 linenr++;
1941 used = parse_binary(buffer + hd + llen,
1942 size - hd - llen, patch);
1943 if (used)
1944 patchsize = used + llen;
1945 else
1946 patchsize = 0;
1948 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
1949 for (i = 0; binhdr[i]; i++) {
1950 int len = strlen(binhdr[i]);
1951 if (len < size - hd &&
1952 !memcmp(binhdr[i], buffer + hd, len)) {
1953 linenr++;
1954 patch->is_binary = 1;
1955 patchsize = llen;
1956 break;
1961 /* Empty patch cannot be applied if it is a text patch
1962 * without metadata change. A binary patch appears
1963 * empty to us here.
1965 if ((apply || check) &&
1966 (!patch->is_binary && !metadata_changes(patch)))
1967 die(_("patch with only garbage at line %d"), linenr);
1970 return offset + hdrsize + patchsize;
1973 #define swap(a,b) myswap((a),(b),sizeof(a))
1975 #define myswap(a, b, size) do { \
1976 unsigned char mytmp[size]; \
1977 memcpy(mytmp, &a, size); \
1978 memcpy(&a, &b, size); \
1979 memcpy(&b, mytmp, size); \
1980 } while (0)
1982 static void reverse_patches(struct patch *p)
1984 for (; p; p = p->next) {
1985 struct fragment *frag = p->fragments;
1987 swap(p->new_name, p->old_name);
1988 swap(p->new_mode, p->old_mode);
1989 swap(p->is_new, p->is_delete);
1990 swap(p->lines_added, p->lines_deleted);
1991 swap(p->old_sha1_prefix, p->new_sha1_prefix);
1993 for (; frag; frag = frag->next) {
1994 swap(frag->newpos, frag->oldpos);
1995 swap(frag->newlines, frag->oldlines);
2000 static const char pluses[] =
2001 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2002 static const char minuses[]=
2003 "----------------------------------------------------------------------";
2005 static void show_stats(struct patch *patch)
2007 struct strbuf qname = STRBUF_INIT;
2008 char *cp = patch->new_name ? patch->new_name : patch->old_name;
2009 int max, add, del;
2011 quote_c_style(cp, &qname, NULL, 0);
2014 * "scale" the filename
2016 max = max_len;
2017 if (max > 50)
2018 max = 50;
2020 if (qname.len > max) {
2021 cp = strchr(qname.buf + qname.len + 3 - max, '/');
2022 if (!cp)
2023 cp = qname.buf + qname.len + 3 - max;
2024 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
2027 if (patch->is_binary) {
2028 printf(" %-*s | Bin\n", max, qname.buf);
2029 strbuf_release(&qname);
2030 return;
2033 printf(" %-*s |", max, qname.buf);
2034 strbuf_release(&qname);
2037 * scale the add/delete
2039 max = max + max_change > 70 ? 70 - max : max_change;
2040 add = patch->lines_added;
2041 del = patch->lines_deleted;
2043 if (max_change > 0) {
2044 int total = ((add + del) * max + max_change / 2) / max_change;
2045 add = (add * max + max_change / 2) / max_change;
2046 del = total - add;
2048 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
2049 add, pluses, del, minuses);
2052 static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
2054 switch (st->st_mode & S_IFMT) {
2055 case S_IFLNK:
2056 if (strbuf_readlink(buf, path, st->st_size) < 0)
2057 return error(_("unable to read symlink %s"), path);
2058 return 0;
2059 case S_IFREG:
2060 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
2061 return error(_("unable to open or read %s"), path);
2062 convert_to_git(path, buf->buf, buf->len, buf, 0);
2063 return 0;
2064 default:
2065 return -1;
2070 * Update the preimage, and the common lines in postimage,
2071 * from buffer buf of length len. If postlen is 0 the postimage
2072 * is updated in place, otherwise it's updated on a new buffer
2073 * of length postlen
2076 static void update_pre_post_images(struct image *preimage,
2077 struct image *postimage,
2078 char *buf,
2079 size_t len, size_t postlen)
2081 int i, ctx;
2082 char *new, *old, *fixed;
2083 struct image fixed_preimage;
2086 * Update the preimage with whitespace fixes. Note that we
2087 * are not losing preimage->buf -- apply_one_fragment() will
2088 * free "oldlines".
2090 prepare_image(&fixed_preimage, buf, len, 1);
2091 assert(fixed_preimage.nr == preimage->nr);
2092 for (i = 0; i < preimage->nr; i++)
2093 fixed_preimage.line[i].flag = preimage->line[i].flag;
2094 free(preimage->line_allocated);
2095 *preimage = fixed_preimage;
2098 * Adjust the common context lines in postimage. This can be
2099 * done in-place when we are just doing whitespace fixing,
2100 * which does not make the string grow, but needs a new buffer
2101 * when ignoring whitespace causes the update, since in this case
2102 * we could have e.g. tabs converted to multiple spaces.
2103 * We trust the caller to tell us if the update can be done
2104 * in place (postlen==0) or not.
2106 old = postimage->buf;
2107 if (postlen)
2108 new = postimage->buf = xmalloc(postlen);
2109 else
2110 new = old;
2111 fixed = preimage->buf;
2112 for (i = ctx = 0; i < postimage->nr; i++) {
2113 size_t len = postimage->line[i].len;
2114 if (!(postimage->line[i].flag & LINE_COMMON)) {
2115 /* an added line -- no counterparts in preimage */
2116 memmove(new, old, len);
2117 old += len;
2118 new += len;
2119 continue;
2122 /* a common context -- skip it in the original postimage */
2123 old += len;
2125 /* and find the corresponding one in the fixed preimage */
2126 while (ctx < preimage->nr &&
2127 !(preimage->line[ctx].flag & LINE_COMMON)) {
2128 fixed += preimage->line[ctx].len;
2129 ctx++;
2131 if (preimage->nr <= ctx)
2132 die(_("oops"));
2134 /* and copy it in, while fixing the line length */
2135 len = preimage->line[ctx].len;
2136 memcpy(new, fixed, len);
2137 new += len;
2138 fixed += len;
2139 postimage->line[i].len = len;
2140 ctx++;
2143 /* Fix the length of the whole thing */
2144 postimage->len = new - postimage->buf;
2147 static int match_fragment(struct image *img,
2148 struct image *preimage,
2149 struct image *postimage,
2150 unsigned long try,
2151 int try_lno,
2152 unsigned ws_rule,
2153 int match_beginning, int match_end)
2155 int i;
2156 char *fixed_buf, *buf, *orig, *target;
2157 struct strbuf fixed;
2158 size_t fixed_len;
2159 int preimage_limit;
2161 if (preimage->nr + try_lno <= img->nr) {
2163 * The hunk falls within the boundaries of img.
2165 preimage_limit = preimage->nr;
2166 if (match_end && (preimage->nr + try_lno != img->nr))
2167 return 0;
2168 } else if (ws_error_action == correct_ws_error &&
2169 (ws_rule & WS_BLANK_AT_EOF)) {
2171 * This hunk extends beyond the end of img, and we are
2172 * removing blank lines at the end of the file. This
2173 * many lines from the beginning of the preimage must
2174 * match with img, and the remainder of the preimage
2175 * must be blank.
2177 preimage_limit = img->nr - try_lno;
2178 } else {
2180 * The hunk extends beyond the end of the img and
2181 * we are not removing blanks at the end, so we
2182 * should reject the hunk at this position.
2184 return 0;
2187 if (match_beginning && try_lno)
2188 return 0;
2190 /* Quick hash check */
2191 for (i = 0; i < preimage_limit; i++)
2192 if ((img->line[try_lno + i].flag & LINE_PATCHED) ||
2193 (preimage->line[i].hash != img->line[try_lno + i].hash))
2194 return 0;
2196 if (preimage_limit == preimage->nr) {
2198 * Do we have an exact match? If we were told to match
2199 * at the end, size must be exactly at try+fragsize,
2200 * otherwise try+fragsize must be still within the preimage,
2201 * and either case, the old piece should match the preimage
2202 * exactly.
2204 if ((match_end
2205 ? (try + preimage->len == img->len)
2206 : (try + preimage->len <= img->len)) &&
2207 !memcmp(img->buf + try, preimage->buf, preimage->len))
2208 return 1;
2209 } else {
2211 * The preimage extends beyond the end of img, so
2212 * there cannot be an exact match.
2214 * There must be one non-blank context line that match
2215 * a line before the end of img.
2217 char *buf_end;
2219 buf = preimage->buf;
2220 buf_end = buf;
2221 for (i = 0; i < preimage_limit; i++)
2222 buf_end += preimage->line[i].len;
2224 for ( ; buf < buf_end; buf++)
2225 if (!isspace(*buf))
2226 break;
2227 if (buf == buf_end)
2228 return 0;
2232 * No exact match. If we are ignoring whitespace, run a line-by-line
2233 * fuzzy matching. We collect all the line length information because
2234 * we need it to adjust whitespace if we match.
2236 if (ws_ignore_action == ignore_ws_change) {
2237 size_t imgoff = 0;
2238 size_t preoff = 0;
2239 size_t postlen = postimage->len;
2240 size_t extra_chars;
2241 char *preimage_eof;
2242 char *preimage_end;
2243 for (i = 0; i < preimage_limit; i++) {
2244 size_t prelen = preimage->line[i].len;
2245 size_t imglen = img->line[try_lno+i].len;
2247 if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,
2248 preimage->buf + preoff, prelen))
2249 return 0;
2250 if (preimage->line[i].flag & LINE_COMMON)
2251 postlen += imglen - prelen;
2252 imgoff += imglen;
2253 preoff += prelen;
2257 * Ok, the preimage matches with whitespace fuzz.
2259 * imgoff now holds the true length of the target that
2260 * matches the preimage before the end of the file.
2262 * Count the number of characters in the preimage that fall
2263 * beyond the end of the file and make sure that all of them
2264 * are whitespace characters. (This can only happen if
2265 * we are removing blank lines at the end of the file.)
2267 buf = preimage_eof = preimage->buf + preoff;
2268 for ( ; i < preimage->nr; i++)
2269 preoff += preimage->line[i].len;
2270 preimage_end = preimage->buf + preoff;
2271 for ( ; buf < preimage_end; buf++)
2272 if (!isspace(*buf))
2273 return 0;
2276 * Update the preimage and the common postimage context
2277 * lines to use the same whitespace as the target.
2278 * If whitespace is missing in the target (i.e.
2279 * if the preimage extends beyond the end of the file),
2280 * use the whitespace from the preimage.
2282 extra_chars = preimage_end - preimage_eof;
2283 strbuf_init(&fixed, imgoff + extra_chars);
2284 strbuf_add(&fixed, img->buf + try, imgoff);
2285 strbuf_add(&fixed, preimage_eof, extra_chars);
2286 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2287 update_pre_post_images(preimage, postimage,
2288 fixed_buf, fixed_len, postlen);
2289 return 1;
2292 if (ws_error_action != correct_ws_error)
2293 return 0;
2296 * The hunk does not apply byte-by-byte, but the hash says
2297 * it might with whitespace fuzz. We haven't been asked to
2298 * ignore whitespace, we were asked to correct whitespace
2299 * errors, so let's try matching after whitespace correction.
2301 * The preimage may extend beyond the end of the file,
2302 * but in this loop we will only handle the part of the
2303 * preimage that falls within the file.
2305 strbuf_init(&fixed, preimage->len + 1);
2306 orig = preimage->buf;
2307 target = img->buf + try;
2308 for (i = 0; i < preimage_limit; i++) {
2309 size_t oldlen = preimage->line[i].len;
2310 size_t tgtlen = img->line[try_lno + i].len;
2311 size_t fixstart = fixed.len;
2312 struct strbuf tgtfix;
2313 int match;
2315 /* Try fixing the line in the preimage */
2316 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2318 /* Try fixing the line in the target */
2319 strbuf_init(&tgtfix, tgtlen);
2320 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2323 * If they match, either the preimage was based on
2324 * a version before our tree fixed whitespace breakage,
2325 * or we are lacking a whitespace-fix patch the tree
2326 * the preimage was based on already had (i.e. target
2327 * has whitespace breakage, the preimage doesn't).
2328 * In either case, we are fixing the whitespace breakages
2329 * so we might as well take the fix together with their
2330 * real change.
2332 match = (tgtfix.len == fixed.len - fixstart &&
2333 !memcmp(tgtfix.buf, fixed.buf + fixstart,
2334 fixed.len - fixstart));
2336 strbuf_release(&tgtfix);
2337 if (!match)
2338 goto unmatch_exit;
2340 orig += oldlen;
2341 target += tgtlen;
2346 * Now handle the lines in the preimage that falls beyond the
2347 * end of the file (if any). They will only match if they are
2348 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2349 * false).
2351 for ( ; i < preimage->nr; i++) {
2352 size_t fixstart = fixed.len; /* start of the fixed preimage */
2353 size_t oldlen = preimage->line[i].len;
2354 int j;
2356 /* Try fixing the line in the preimage */
2357 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2359 for (j = fixstart; j < fixed.len; j++)
2360 if (!isspace(fixed.buf[j]))
2361 goto unmatch_exit;
2363 orig += oldlen;
2367 * Yes, the preimage is based on an older version that still
2368 * has whitespace breakages unfixed, and fixing them makes the
2369 * hunk match. Update the context lines in the postimage.
2371 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2372 update_pre_post_images(preimage, postimage,
2373 fixed_buf, fixed_len, 0);
2374 return 1;
2376 unmatch_exit:
2377 strbuf_release(&fixed);
2378 return 0;
2381 static int find_pos(struct image *img,
2382 struct image *preimage,
2383 struct image *postimage,
2384 int line,
2385 unsigned ws_rule,
2386 int match_beginning, int match_end)
2388 int i;
2389 unsigned long backwards, forwards, try;
2390 int backwards_lno, forwards_lno, try_lno;
2393 * If match_beginning or match_end is specified, there is no
2394 * point starting from a wrong line that will never match and
2395 * wander around and wait for a match at the specified end.
2397 if (match_beginning)
2398 line = 0;
2399 else if (match_end)
2400 line = img->nr - preimage->nr;
2403 * Because the comparison is unsigned, the following test
2404 * will also take care of a negative line number that can
2405 * result when match_end and preimage is larger than the target.
2407 if ((size_t) line > img->nr)
2408 line = img->nr;
2410 try = 0;
2411 for (i = 0; i < line; i++)
2412 try += img->line[i].len;
2415 * There's probably some smart way to do this, but I'll leave
2416 * that to the smart and beautiful people. I'm simple and stupid.
2418 backwards = try;
2419 backwards_lno = line;
2420 forwards = try;
2421 forwards_lno = line;
2422 try_lno = line;
2424 for (i = 0; ; i++) {
2425 if (match_fragment(img, preimage, postimage,
2426 try, try_lno, ws_rule,
2427 match_beginning, match_end))
2428 return try_lno;
2430 again:
2431 if (backwards_lno == 0 && forwards_lno == img->nr)
2432 break;
2434 if (i & 1) {
2435 if (backwards_lno == 0) {
2436 i++;
2437 goto again;
2439 backwards_lno--;
2440 backwards -= img->line[backwards_lno].len;
2441 try = backwards;
2442 try_lno = backwards_lno;
2443 } else {
2444 if (forwards_lno == img->nr) {
2445 i++;
2446 goto again;
2448 forwards += img->line[forwards_lno].len;
2449 forwards_lno++;
2450 try = forwards;
2451 try_lno = forwards_lno;
2455 return -1;
2458 static void remove_first_line(struct image *img)
2460 img->buf += img->line[0].len;
2461 img->len -= img->line[0].len;
2462 img->line++;
2463 img->nr--;
2466 static void remove_last_line(struct image *img)
2468 img->len -= img->line[--img->nr].len;
2472 * The change from "preimage" and "postimage" has been found to
2473 * apply at applied_pos (counts in line numbers) in "img".
2474 * Update "img" to remove "preimage" and replace it with "postimage".
2476 static void update_image(struct image *img,
2477 int applied_pos,
2478 struct image *preimage,
2479 struct image *postimage)
2482 * remove the copy of preimage at offset in img
2483 * and replace it with postimage
2485 int i, nr;
2486 size_t remove_count, insert_count, applied_at = 0;
2487 char *result;
2488 int preimage_limit;
2491 * If we are removing blank lines at the end of img,
2492 * the preimage may extend beyond the end.
2493 * If that is the case, we must be careful only to
2494 * remove the part of the preimage that falls within
2495 * the boundaries of img. Initialize preimage_limit
2496 * to the number of lines in the preimage that falls
2497 * within the boundaries.
2499 preimage_limit = preimage->nr;
2500 if (preimage_limit > img->nr - applied_pos)
2501 preimage_limit = img->nr - applied_pos;
2503 for (i = 0; i < applied_pos; i++)
2504 applied_at += img->line[i].len;
2506 remove_count = 0;
2507 for (i = 0; i < preimage_limit; i++)
2508 remove_count += img->line[applied_pos + i].len;
2509 insert_count = postimage->len;
2511 /* Adjust the contents */
2512 result = xmalloc(img->len + insert_count - remove_count + 1);
2513 memcpy(result, img->buf, applied_at);
2514 memcpy(result + applied_at, postimage->buf, postimage->len);
2515 memcpy(result + applied_at + postimage->len,
2516 img->buf + (applied_at + remove_count),
2517 img->len - (applied_at + remove_count));
2518 free(img->buf);
2519 img->buf = result;
2520 img->len += insert_count - remove_count;
2521 result[img->len] = '\0';
2523 /* Adjust the line table */
2524 nr = img->nr + postimage->nr - preimage_limit;
2525 if (preimage_limit < postimage->nr) {
2527 * NOTE: this knows that we never call remove_first_line()
2528 * on anything other than pre/post image.
2530 img->line = xrealloc(img->line, nr * sizeof(*img->line));
2531 img->line_allocated = img->line;
2533 if (preimage_limit != postimage->nr)
2534 memmove(img->line + applied_pos + postimage->nr,
2535 img->line + applied_pos + preimage_limit,
2536 (img->nr - (applied_pos + preimage_limit)) *
2537 sizeof(*img->line));
2538 memcpy(img->line + applied_pos,
2539 postimage->line,
2540 postimage->nr * sizeof(*img->line));
2541 if (!allow_overlap)
2542 for (i = 0; i < postimage->nr; i++)
2543 img->line[applied_pos + i].flag |= LINE_PATCHED;
2544 img->nr = nr;
2548 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2549 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2550 * replace the part of "img" with "postimage" text.
2552 static int apply_one_fragment(struct image *img, struct fragment *frag,
2553 int inaccurate_eof, unsigned ws_rule,
2554 int nth_fragment)
2556 int match_beginning, match_end;
2557 const char *patch = frag->patch;
2558 int size = frag->size;
2559 char *old, *oldlines;
2560 struct strbuf newlines;
2561 int new_blank_lines_at_end = 0;
2562 int found_new_blank_lines_at_end = 0;
2563 int hunk_linenr = frag->linenr;
2564 unsigned long leading, trailing;
2565 int pos, applied_pos;
2566 struct image preimage;
2567 struct image postimage;
2569 memset(&preimage, 0, sizeof(preimage));
2570 memset(&postimage, 0, sizeof(postimage));
2571 oldlines = xmalloc(size);
2572 strbuf_init(&newlines, size);
2574 old = oldlines;
2575 while (size > 0) {
2576 char first;
2577 int len = linelen(patch, size);
2578 int plen;
2579 int added_blank_line = 0;
2580 int is_blank_context = 0;
2581 size_t start;
2583 if (!len)
2584 break;
2587 * "plen" is how much of the line we should use for
2588 * the actual patch data. Normally we just remove the
2589 * first character on the line, but if the line is
2590 * followed by "\ No newline", then we also remove the
2591 * last one (which is the newline, of course).
2593 plen = len - 1;
2594 if (len < size && patch[len] == '\\')
2595 plen--;
2596 first = *patch;
2597 if (apply_in_reverse) {
2598 if (first == '-')
2599 first = '+';
2600 else if (first == '+')
2601 first = '-';
2604 switch (first) {
2605 case '\n':
2606 /* Newer GNU diff, empty context line */
2607 if (plen < 0)
2608 /* ... followed by '\No newline'; nothing */
2609 break;
2610 *old++ = '\n';
2611 strbuf_addch(&newlines, '\n');
2612 add_line_info(&preimage, "\n", 1, LINE_COMMON);
2613 add_line_info(&postimage, "\n", 1, LINE_COMMON);
2614 is_blank_context = 1;
2615 break;
2616 case ' ':
2617 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2618 ws_blank_line(patch + 1, plen, ws_rule))
2619 is_blank_context = 1;
2620 case '-':
2621 memcpy(old, patch + 1, plen);
2622 add_line_info(&preimage, old, plen,
2623 (first == ' ' ? LINE_COMMON : 0));
2624 old += plen;
2625 if (first == '-')
2626 break;
2627 /* Fall-through for ' ' */
2628 case '+':
2629 /* --no-add does not add new lines */
2630 if (first == '+' && no_add)
2631 break;
2633 start = newlines.len;
2634 if (first != '+' ||
2635 !whitespace_error ||
2636 ws_error_action != correct_ws_error) {
2637 strbuf_add(&newlines, patch + 1, plen);
2639 else {
2640 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &applied_after_fixing_ws);
2642 add_line_info(&postimage, newlines.buf + start, newlines.len - start,
2643 (first == '+' ? 0 : LINE_COMMON));
2644 if (first == '+' &&
2645 (ws_rule & WS_BLANK_AT_EOF) &&
2646 ws_blank_line(patch + 1, plen, ws_rule))
2647 added_blank_line = 1;
2648 break;
2649 case '@': case '\\':
2650 /* Ignore it, we already handled it */
2651 break;
2652 default:
2653 if (apply_verbosely)
2654 error(_("invalid start of line: '%c'"), first);
2655 return -1;
2657 if (added_blank_line) {
2658 if (!new_blank_lines_at_end)
2659 found_new_blank_lines_at_end = hunk_linenr;
2660 new_blank_lines_at_end++;
2662 else if (is_blank_context)
2664 else
2665 new_blank_lines_at_end = 0;
2666 patch += len;
2667 size -= len;
2668 hunk_linenr++;
2670 if (inaccurate_eof &&
2671 old > oldlines && old[-1] == '\n' &&
2672 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
2673 old--;
2674 strbuf_setlen(&newlines, newlines.len - 1);
2677 leading = frag->leading;
2678 trailing = frag->trailing;
2681 * A hunk to change lines at the beginning would begin with
2682 * @@ -1,L +N,M @@
2683 * but we need to be careful. -U0 that inserts before the second
2684 * line also has this pattern.
2686 * And a hunk to add to an empty file would begin with
2687 * @@ -0,0 +N,M @@
2689 * In other words, a hunk that is (frag->oldpos <= 1) with or
2690 * without leading context must match at the beginning.
2692 match_beginning = (!frag->oldpos ||
2693 (frag->oldpos == 1 && !unidiff_zero));
2696 * A hunk without trailing lines must match at the end.
2697 * However, we simply cannot tell if a hunk must match end
2698 * from the lack of trailing lines if the patch was generated
2699 * with unidiff without any context.
2701 match_end = !unidiff_zero && !trailing;
2703 pos = frag->newpos ? (frag->newpos - 1) : 0;
2704 preimage.buf = oldlines;
2705 preimage.len = old - oldlines;
2706 postimage.buf = newlines.buf;
2707 postimage.len = newlines.len;
2708 preimage.line = preimage.line_allocated;
2709 postimage.line = postimage.line_allocated;
2711 for (;;) {
2713 applied_pos = find_pos(img, &preimage, &postimage, pos,
2714 ws_rule, match_beginning, match_end);
2716 if (applied_pos >= 0)
2717 break;
2719 /* Am I at my context limits? */
2720 if ((leading <= p_context) && (trailing <= p_context))
2721 break;
2722 if (match_beginning || match_end) {
2723 match_beginning = match_end = 0;
2724 continue;
2728 * Reduce the number of context lines; reduce both
2729 * leading and trailing if they are equal otherwise
2730 * just reduce the larger context.
2732 if (leading >= trailing) {
2733 remove_first_line(&preimage);
2734 remove_first_line(&postimage);
2735 pos--;
2736 leading--;
2738 if (trailing > leading) {
2739 remove_last_line(&preimage);
2740 remove_last_line(&postimage);
2741 trailing--;
2745 if (applied_pos >= 0) {
2746 if (new_blank_lines_at_end &&
2747 preimage.nr + applied_pos >= img->nr &&
2748 (ws_rule & WS_BLANK_AT_EOF) &&
2749 ws_error_action != nowarn_ws_error) {
2750 record_ws_error(WS_BLANK_AT_EOF, "+", 1,
2751 found_new_blank_lines_at_end);
2752 if (ws_error_action == correct_ws_error) {
2753 while (new_blank_lines_at_end--)
2754 remove_last_line(&postimage);
2757 * We would want to prevent write_out_results()
2758 * from taking place in apply_patch() that follows
2759 * the callchain led us here, which is:
2760 * apply_patch->check_patch_list->check_patch->
2761 * apply_data->apply_fragments->apply_one_fragment
2763 if (ws_error_action == die_on_ws_error)
2764 apply = 0;
2767 if (apply_verbosely && applied_pos != pos) {
2768 int offset = applied_pos - pos;
2769 if (apply_in_reverse)
2770 offset = 0 - offset;
2771 fprintf_ln(stderr,
2772 Q_("Hunk #%d succeeded at %d (offset %d line).",
2773 "Hunk #%d succeeded at %d (offset %d lines).",
2774 offset),
2775 nth_fragment, applied_pos + 1, offset);
2779 * Warn if it was necessary to reduce the number
2780 * of context lines.
2782 if ((leading != frag->leading) ||
2783 (trailing != frag->trailing))
2784 fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"
2785 " to apply fragment at %d"),
2786 leading, trailing, applied_pos+1);
2787 update_image(img, applied_pos, &preimage, &postimage);
2788 } else {
2789 if (apply_verbosely)
2790 error(_("while searching for:\n%.*s"),
2791 (int)(old - oldlines), oldlines);
2794 free(oldlines);
2795 strbuf_release(&newlines);
2796 free(preimage.line_allocated);
2797 free(postimage.line_allocated);
2799 return (applied_pos < 0);
2802 static int apply_binary_fragment(struct image *img, struct patch *patch)
2804 struct fragment *fragment = patch->fragments;
2805 unsigned long len;
2806 void *dst;
2808 if (!fragment)
2809 return error(_("missing binary patch data for '%s'"),
2810 patch->new_name ?
2811 patch->new_name :
2812 patch->old_name);
2814 /* Binary patch is irreversible without the optional second hunk */
2815 if (apply_in_reverse) {
2816 if (!fragment->next)
2817 return error("cannot reverse-apply a binary patch "
2818 "without the reverse hunk to '%s'",
2819 patch->new_name
2820 ? patch->new_name : patch->old_name);
2821 fragment = fragment->next;
2823 switch (fragment->binary_patch_method) {
2824 case BINARY_DELTA_DEFLATED:
2825 dst = patch_delta(img->buf, img->len, fragment->patch,
2826 fragment->size, &len);
2827 if (!dst)
2828 return -1;
2829 clear_image(img);
2830 img->buf = dst;
2831 img->len = len;
2832 return 0;
2833 case BINARY_LITERAL_DEFLATED:
2834 clear_image(img);
2835 img->len = fragment->size;
2836 img->buf = xmalloc(img->len+1);
2837 memcpy(img->buf, fragment->patch, img->len);
2838 img->buf[img->len] = '\0';
2839 return 0;
2841 return -1;
2845 * Replace "img" with the result of applying the binary patch.
2846 * The binary patch data itself in patch->fragment is still kept
2847 * but the preimage prepared by the caller in "img" is freed here
2848 * or in the helper function apply_binary_fragment() this calls.
2850 static int apply_binary(struct image *img, struct patch *patch)
2852 const char *name = patch->old_name ? patch->old_name : patch->new_name;
2853 unsigned char sha1[20];
2856 * For safety, we require patch index line to contain
2857 * full 40-byte textual SHA1 for old and new, at least for now.
2859 if (strlen(patch->old_sha1_prefix) != 40 ||
2860 strlen(patch->new_sha1_prefix) != 40 ||
2861 get_sha1_hex(patch->old_sha1_prefix, sha1) ||
2862 get_sha1_hex(patch->new_sha1_prefix, sha1))
2863 return error("cannot apply binary patch to '%s' "
2864 "without full index line", name);
2866 if (patch->old_name) {
2868 * See if the old one matches what the patch
2869 * applies to.
2871 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2872 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
2873 return error("the patch applies to '%s' (%s), "
2874 "which does not match the "
2875 "current contents.",
2876 name, sha1_to_hex(sha1));
2878 else {
2879 /* Otherwise, the old one must be empty. */
2880 if (img->len)
2881 return error("the patch applies to an empty "
2882 "'%s' but it is not empty", name);
2885 get_sha1_hex(patch->new_sha1_prefix, sha1);
2886 if (is_null_sha1(sha1)) {
2887 clear_image(img);
2888 return 0; /* deletion patch */
2891 if (has_sha1_file(sha1)) {
2892 /* We already have the postimage */
2893 enum object_type type;
2894 unsigned long size;
2895 char *result;
2897 result = read_sha1_file(sha1, &type, &size);
2898 if (!result)
2899 return error("the necessary postimage %s for "
2900 "'%s' cannot be read",
2901 patch->new_sha1_prefix, name);
2902 clear_image(img);
2903 img->buf = result;
2904 img->len = size;
2905 } else {
2907 * We have verified buf matches the preimage;
2908 * apply the patch data to it, which is stored
2909 * in the patch->fragments->{patch,size}.
2911 if (apply_binary_fragment(img, patch))
2912 return error(_("binary patch does not apply to '%s'"),
2913 name);
2915 /* verify that the result matches */
2916 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2917 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
2918 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
2919 name, patch->new_sha1_prefix, sha1_to_hex(sha1));
2922 return 0;
2925 static int apply_fragments(struct image *img, struct patch *patch)
2927 struct fragment *frag = patch->fragments;
2928 const char *name = patch->old_name ? patch->old_name : patch->new_name;
2929 unsigned ws_rule = patch->ws_rule;
2930 unsigned inaccurate_eof = patch->inaccurate_eof;
2931 int nth = 0;
2933 if (patch->is_binary)
2934 return apply_binary(img, patch);
2936 while (frag) {
2937 nth++;
2938 if (apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {
2939 error(_("patch failed: %s:%ld"), name, frag->oldpos);
2940 if (!apply_with_reject)
2941 return -1;
2942 frag->rejected = 1;
2944 frag = frag->next;
2946 return 0;
2949 static int read_blob_object(struct strbuf *buf, const unsigned char *sha1, unsigned mode)
2951 if (S_ISGITLINK(mode)) {
2952 strbuf_grow(buf, 100);
2953 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(sha1));
2954 } else {
2955 enum object_type type;
2956 unsigned long sz;
2957 char *result;
2959 result = read_sha1_file(sha1, &type, &sz);
2960 if (!result)
2961 return -1;
2962 /* XXX read_sha1_file NUL-terminates */
2963 strbuf_attach(buf, result, sz, sz + 1);
2965 return 0;
2968 static int read_file_or_gitlink(struct cache_entry *ce, struct strbuf *buf)
2970 if (!ce)
2971 return 0;
2972 return read_blob_object(buf, ce->sha1, ce->ce_mode);
2975 static struct patch *in_fn_table(const char *name)
2977 struct string_list_item *item;
2979 if (name == NULL)
2980 return NULL;
2982 item = string_list_lookup(&fn_table, name);
2983 if (item != NULL)
2984 return (struct patch *)item->util;
2986 return NULL;
2990 * item->util in the filename table records the status of the path.
2991 * Usually it points at a patch (whose result records the contents
2992 * of it after applying it), but it could be PATH_WAS_DELETED for a
2993 * path that a previously applied patch has already removed, or
2994 * PATH_TO_BE_DELETED for a path that a later patch would remove.
2996 * The latter is needed to deal with a case where two paths A and B
2997 * are swapped by first renaming A to B and then renaming B to A;
2998 * moving A to B should not be prevented due to presense of B as we
2999 * will remove it in a later patch.
3001 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3002 #define PATH_WAS_DELETED ((struct patch *) -1)
3004 static int to_be_deleted(struct patch *patch)
3006 return patch == PATH_TO_BE_DELETED;
3009 static int was_deleted(struct patch *patch)
3011 return patch == PATH_WAS_DELETED;
3014 static void add_to_fn_table(struct patch *patch)
3016 struct string_list_item *item;
3019 * Always add new_name unless patch is a deletion
3020 * This should cover the cases for normal diffs,
3021 * file creations and copies
3023 if (patch->new_name != NULL) {
3024 item = string_list_insert(&fn_table, patch->new_name);
3025 item->util = patch;
3029 * store a failure on rename/deletion cases because
3030 * later chunks shouldn't patch old names
3032 if ((patch->new_name == NULL) || (patch->is_rename)) {
3033 item = string_list_insert(&fn_table, patch->old_name);
3034 item->util = PATH_WAS_DELETED;
3038 static void prepare_fn_table(struct patch *patch)
3041 * store information about incoming file deletion
3043 while (patch) {
3044 if ((patch->new_name == NULL) || (patch->is_rename)) {
3045 struct string_list_item *item;
3046 item = string_list_insert(&fn_table, patch->old_name);
3047 item->util = PATH_TO_BE_DELETED;
3049 patch = patch->next;
3053 static int checkout_target(struct cache_entry *ce, struct stat *st)
3055 struct checkout costate;
3057 memset(&costate, 0, sizeof(costate));
3058 costate.base_dir = "";
3059 costate.refresh_cache = 1;
3060 if (checkout_entry(ce, &costate, NULL) || lstat(ce->name, st))
3061 return error(_("cannot checkout %s"), ce->name);
3062 return 0;
3065 static struct patch *previous_patch(struct patch *patch, int *gone)
3067 struct patch *previous;
3069 *gone = 0;
3070 if (patch->is_copy || patch->is_rename)
3071 return NULL; /* "git" patches do not depend on the order */
3073 previous = in_fn_table(patch->old_name);
3074 if (!previous)
3075 return NULL;
3077 if (to_be_deleted(previous))
3078 return NULL; /* the deletion hasn't happened yet */
3080 if (was_deleted(previous))
3081 *gone = 1;
3083 return previous;
3086 static int verify_index_match(struct cache_entry *ce, struct stat *st)
3088 if (S_ISGITLINK(ce->ce_mode)) {
3089 if (!S_ISDIR(st->st_mode))
3090 return -1;
3091 return 0;
3093 return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
3096 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3098 static int load_patch_target(struct strbuf *buf,
3099 struct cache_entry *ce,
3100 struct stat *st,
3101 const char *name,
3102 unsigned expected_mode)
3104 if (cached) {
3105 if (read_file_or_gitlink(ce, buf))
3106 return error(_("read of %s failed"), name);
3107 } else if (name) {
3108 if (S_ISGITLINK(expected_mode)) {
3109 if (ce)
3110 return read_file_or_gitlink(ce, buf);
3111 else
3112 return SUBMODULE_PATCH_WITHOUT_INDEX;
3113 } else {
3114 if (read_old_data(st, name, buf))
3115 return error(_("read of %s failed"), name);
3118 return 0;
3122 * We are about to apply "patch"; populate the "image" with the
3123 * current version we have, from the working tree or from the index,
3124 * depending on the situation e.g. --cached/--index. If we are
3125 * applying a non-git patch that incrementally updates the tree,
3126 * we read from the result of a previous diff.
3128 static int load_preimage(struct image *image,
3129 struct patch *patch, struct stat *st, struct cache_entry *ce)
3131 struct strbuf buf = STRBUF_INIT;
3132 size_t len;
3133 char *img;
3134 struct patch *previous;
3135 int status;
3137 previous = previous_patch(patch, &status);
3138 if (status)
3139 return error(_("path %s has been renamed/deleted"),
3140 patch->old_name);
3141 if (previous) {
3142 /* We have a patched copy in memory; use that. */
3143 strbuf_add(&buf, previous->result, previous->resultsize);
3144 } else {
3145 status = load_patch_target(&buf, ce, st,
3146 patch->old_name, patch->old_mode);
3147 if (status < 0)
3148 return status;
3149 else if (status == SUBMODULE_PATCH_WITHOUT_INDEX) {
3151 * There is no way to apply subproject
3152 * patch without looking at the index.
3153 * NEEDSWORK: shouldn't this be flagged
3154 * as an error???
3156 free_fragment_list(patch->fragments);
3157 patch->fragments = NULL;
3158 } else if (status) {
3159 return error(_("read of %s failed"), patch->old_name);
3163 img = strbuf_detach(&buf, &len);
3164 prepare_image(image, img, len, !patch->is_binary);
3165 return 0;
3168 static int three_way_merge(struct image *image,
3169 char *path,
3170 const unsigned char *base,
3171 const unsigned char *ours,
3172 const unsigned char *theirs)
3174 mmfile_t base_file, our_file, their_file;
3175 mmbuffer_t result = { NULL };
3176 int status;
3178 read_mmblob(&base_file, base);
3179 read_mmblob(&our_file, ours);
3180 read_mmblob(&their_file, theirs);
3181 status = ll_merge(&result, path,
3182 &base_file, "base",
3183 &our_file, "ours",
3184 &their_file, "theirs", NULL);
3185 free(base_file.ptr);
3186 free(our_file.ptr);
3187 free(their_file.ptr);
3188 if (status < 0 || !result.ptr) {
3189 free(result.ptr);
3190 return -1;
3192 clear_image(image);
3193 image->buf = result.ptr;
3194 image->len = result.size;
3196 return status;
3200 * When directly falling back to add/add three-way merge, we read from
3201 * the current contents of the new_name. In no cases other than that
3202 * this function will be called.
3204 static int load_current(struct image *image, struct patch *patch)
3206 struct strbuf buf = STRBUF_INIT;
3207 int status, pos;
3208 size_t len;
3209 char *img;
3210 struct stat st;
3211 struct cache_entry *ce;
3212 char *name = patch->new_name;
3213 unsigned mode = patch->new_mode;
3215 if (!patch->is_new)
3216 die("BUG: patch to %s is not a creation", patch->old_name);
3218 pos = cache_name_pos(name, strlen(name));
3219 if (pos < 0)
3220 return error(_("%s: does not exist in index"), name);
3221 ce = active_cache[pos];
3222 if (lstat(name, &st)) {
3223 if (errno != ENOENT)
3224 return error(_("%s: %s"), name, strerror(errno));
3225 if (checkout_target(ce, &st))
3226 return -1;
3228 if (verify_index_match(ce, &st))
3229 return error(_("%s: does not match index"), name);
3231 status = load_patch_target(&buf, ce, &st, name, mode);
3232 if (status < 0)
3233 return status;
3234 else if (status)
3235 return -1;
3236 img = strbuf_detach(&buf, &len);
3237 prepare_image(image, img, len, !patch->is_binary);
3238 return 0;
3241 static int try_threeway(struct image *image, struct patch *patch,
3242 struct stat *st, struct cache_entry *ce)
3244 unsigned char pre_sha1[20], post_sha1[20], our_sha1[20];
3245 struct strbuf buf = STRBUF_INIT;
3246 size_t len;
3247 int status;
3248 char *img;
3249 struct image tmp_image;
3251 /* No point falling back to 3-way merge in these cases */
3252 if (patch->is_delete ||
3253 S_ISGITLINK(patch->old_mode) || S_ISGITLINK(patch->new_mode))
3254 return -1;
3256 /* Preimage the patch was prepared for */
3257 if (patch->is_new)
3258 write_sha1_file("", 0, blob_type, pre_sha1);
3259 else if (get_sha1(patch->old_sha1_prefix, pre_sha1) ||
3260 read_blob_object(&buf, pre_sha1, patch->old_mode))
3261 return error("repository lacks the necessary blob to fall back on 3-way merge.");
3263 fprintf(stderr, "Falling back to three-way merge...\n");
3265 img = strbuf_detach(&buf, &len);
3266 prepare_image(&tmp_image, img, len, 1);
3267 /* Apply the patch to get the post image */
3268 if (apply_fragments(&tmp_image, patch) < 0) {
3269 clear_image(&tmp_image);
3270 return -1;
3272 /* post_sha1[] is theirs */
3273 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_sha1);
3274 clear_image(&tmp_image);
3276 /* our_sha1[] is ours */
3277 if (patch->is_new) {
3278 if (load_current(&tmp_image, patch))
3279 return error("cannot read the current contents of '%s'",
3280 patch->new_name);
3281 } else {
3282 if (load_preimage(&tmp_image, patch, st, ce))
3283 return error("cannot read the current contents of '%s'",
3284 patch->old_name);
3286 write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_sha1);
3287 clear_image(&tmp_image);
3289 /* in-core three-way merge between post and our using pre as base */
3290 status = three_way_merge(image, patch->new_name,
3291 pre_sha1, our_sha1, post_sha1);
3292 if (status < 0) {
3293 fprintf(stderr, "Failed to fall back on three-way merge...\n");
3294 return status;
3297 if (status) {
3298 patch->conflicted_threeway = 1;
3299 if (patch->is_new)
3300 hashclr(patch->threeway_stage[0]);
3301 else
3302 hashcpy(patch->threeway_stage[0], pre_sha1);
3303 hashcpy(patch->threeway_stage[1], our_sha1);
3304 hashcpy(patch->threeway_stage[2], post_sha1);
3305 fprintf(stderr, "Applied patch to '%s' with conflicts.\n", patch->new_name);
3306 } else {
3307 fprintf(stderr, "Applied patch to '%s' cleanly.\n", patch->new_name);
3309 return 0;
3312 static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce)
3314 struct image image;
3316 if (load_preimage(&image, patch, st, ce) < 0)
3317 return -1;
3319 if (patch->direct_to_threeway ||
3320 apply_fragments(&image, patch) < 0) {
3321 /* Note: with --reject, apply_fragments() returns 0 */
3322 if (!threeway || try_threeway(&image, patch, st, ce) < 0)
3323 return -1;
3325 patch->result = image.buf;
3326 patch->resultsize = image.len;
3327 add_to_fn_table(patch);
3328 free(image.line_allocated);
3330 if (0 < patch->is_delete && patch->resultsize)
3331 return error(_("removal patch leaves file contents"));
3333 return 0;
3337 * If "patch" that we are looking at modifies or deletes what we have,
3338 * we would want it not to lose any local modification we have, either
3339 * in the working tree or in the index.
3341 * This also decides if a non-git patch is a creation patch or a
3342 * modification to an existing empty file. We do not check the state
3343 * of the current tree for a creation patch in this function; the caller
3344 * check_patch() separately makes sure (and errors out otherwise) that
3345 * the path the patch creates does not exist in the current tree.
3347 static int check_preimage(struct patch *patch, struct cache_entry **ce, struct stat *st)
3349 const char *old_name = patch->old_name;
3350 struct patch *previous = NULL;
3351 int stat_ret = 0, status;
3352 unsigned st_mode = 0;
3354 if (!old_name)
3355 return 0;
3357 assert(patch->is_new <= 0);
3358 previous = previous_patch(patch, &status);
3360 if (status)
3361 return error(_("path %s has been renamed/deleted"), old_name);
3362 if (previous) {
3363 st_mode = previous->new_mode;
3364 } else if (!cached) {
3365 stat_ret = lstat(old_name, st);
3366 if (stat_ret && errno != ENOENT)
3367 return error(_("%s: %s"), old_name, strerror(errno));
3370 if (check_index && !previous) {
3371 int pos = cache_name_pos(old_name, strlen(old_name));
3372 if (pos < 0) {
3373 if (patch->is_new < 0)
3374 goto is_new;
3375 return error(_("%s: does not exist in index"), old_name);
3377 *ce = active_cache[pos];
3378 if (stat_ret < 0) {
3379 if (checkout_target(*ce, st))
3380 return -1;
3382 if (!cached && verify_index_match(*ce, st))
3383 return error(_("%s: does not match index"), old_name);
3384 if (cached)
3385 st_mode = (*ce)->ce_mode;
3386 } else if (stat_ret < 0) {
3387 if (patch->is_new < 0)
3388 goto is_new;
3389 return error(_("%s: %s"), old_name, strerror(errno));
3392 if (!cached && !previous)
3393 st_mode = ce_mode_from_stat(*ce, st->st_mode);
3395 if (patch->is_new < 0)
3396 patch->is_new = 0;
3397 if (!patch->old_mode)
3398 patch->old_mode = st_mode;
3399 if ((st_mode ^ patch->old_mode) & S_IFMT)
3400 return error(_("%s: wrong type"), old_name);
3401 if (st_mode != patch->old_mode)
3402 warning(_("%s has type %o, expected %o"),
3403 old_name, st_mode, patch->old_mode);
3404 if (!patch->new_mode && !patch->is_delete)
3405 patch->new_mode = st_mode;
3406 return 0;
3408 is_new:
3409 patch->is_new = 1;
3410 patch->is_delete = 0;
3411 free(patch->old_name);
3412 patch->old_name = NULL;
3413 return 0;
3417 #define EXISTS_IN_INDEX 1
3418 #define EXISTS_IN_WORKTREE 2
3420 static int check_to_create(const char *new_name, int ok_if_exists)
3422 struct stat nst;
3424 if (check_index &&
3425 cache_name_pos(new_name, strlen(new_name)) >= 0 &&
3426 !ok_if_exists)
3427 return EXISTS_IN_INDEX;
3428 if (cached)
3429 return 0;
3431 if (!lstat(new_name, &nst)) {
3432 if (S_ISDIR(nst.st_mode) || ok_if_exists)
3433 return 0;
3435 * A leading component of new_name might be a symlink
3436 * that is going to be removed with this patch, but
3437 * still pointing at somewhere that has the path.
3438 * In such a case, path "new_name" does not exist as
3439 * far as git is concerned.
3441 if (has_symlink_leading_path(new_name, strlen(new_name)))
3442 return 0;
3444 return EXISTS_IN_WORKTREE;
3445 } else if ((errno != ENOENT) && (errno != ENOTDIR)) {
3446 return error("%s: %s", new_name, strerror(errno));
3448 return 0;
3452 * Check and apply the patch in-core; leave the result in patch->result
3453 * for the caller to write it out to the final destination.
3455 static int check_patch(struct patch *patch)
3457 struct stat st;
3458 const char *old_name = patch->old_name;
3459 const char *new_name = patch->new_name;
3460 const char *name = old_name ? old_name : new_name;
3461 struct cache_entry *ce = NULL;
3462 struct patch *tpatch;
3463 int ok_if_exists;
3464 int status;
3466 patch->rejected = 1; /* we will drop this after we succeed */
3468 status = check_preimage(patch, &ce, &st);
3469 if (status)
3470 return status;
3471 old_name = patch->old_name;
3474 * A type-change diff is always split into a patch to delete
3475 * old, immediately followed by a patch to create new (see
3476 * diff.c::run_diff()); in such a case it is Ok that the entry
3477 * to be deleted by the previous patch is still in the working
3478 * tree and in the index.
3480 * A patch to swap-rename between A and B would first rename A
3481 * to B and then rename B to A. While applying the first one,
3482 * the presense of B should not stop A from getting renamed to
3483 * B; ask to_be_deleted() about the later rename. Removal of
3484 * B and rename from A to B is handled the same way by asking
3485 * was_deleted().
3487 if ((tpatch = in_fn_table(new_name)) &&
3488 (was_deleted(tpatch) || to_be_deleted(tpatch)))
3489 ok_if_exists = 1;
3490 else
3491 ok_if_exists = 0;
3493 if (new_name &&
3494 ((0 < patch->is_new) | (0 < patch->is_rename) | patch->is_copy)) {
3495 int err = check_to_create(new_name, ok_if_exists);
3497 if (err && threeway) {
3498 patch->direct_to_threeway = 1;
3499 } else switch (err) {
3500 case 0:
3501 break; /* happy */
3502 case EXISTS_IN_INDEX:
3503 return error(_("%s: already exists in index"), new_name);
3504 break;
3505 case EXISTS_IN_WORKTREE:
3506 return error(_("%s: already exists in working directory"),
3507 new_name);
3508 default:
3509 return err;
3512 if (!patch->new_mode) {
3513 if (0 < patch->is_new)
3514 patch->new_mode = S_IFREG | 0644;
3515 else
3516 patch->new_mode = patch->old_mode;
3520 if (new_name && old_name) {
3521 int same = !strcmp(old_name, new_name);
3522 if (!patch->new_mode)
3523 patch->new_mode = patch->old_mode;
3524 if ((patch->old_mode ^ patch->new_mode) & S_IFMT) {
3525 if (same)
3526 return error(_("new mode (%o) of %s does not "
3527 "match old mode (%o)"),
3528 patch->new_mode, new_name,
3529 patch->old_mode);
3530 else
3531 return error(_("new mode (%o) of %s does not "
3532 "match old mode (%o) of %s"),
3533 patch->new_mode, new_name,
3534 patch->old_mode, old_name);
3538 if (apply_data(patch, &st, ce) < 0)
3539 return error(_("%s: patch does not apply"), name);
3540 patch->rejected = 0;
3541 return 0;
3544 static int check_patch_list(struct patch *patch)
3546 int err = 0;
3548 prepare_fn_table(patch);
3549 while (patch) {
3550 if (apply_verbosely)
3551 say_patch_name(stderr,
3552 _("Checking patch %s..."), patch);
3553 err |= check_patch(patch);
3554 patch = patch->next;
3556 return err;
3559 /* This function tries to read the sha1 from the current index */
3560 static int get_current_sha1(const char *path, unsigned char *sha1)
3562 int pos;
3564 if (read_cache() < 0)
3565 return -1;
3566 pos = cache_name_pos(path, strlen(path));
3567 if (pos < 0)
3568 return -1;
3569 hashcpy(sha1, active_cache[pos]->sha1);
3570 return 0;
3573 /* Build an index that contains the just the files needed for a 3way merge */
3574 static void build_fake_ancestor(struct patch *list, const char *filename)
3576 struct patch *patch;
3577 struct index_state result = { NULL };
3578 int fd;
3580 /* Once we start supporting the reverse patch, it may be
3581 * worth showing the new sha1 prefix, but until then...
3583 for (patch = list; patch; patch = patch->next) {
3584 const unsigned char *sha1_ptr;
3585 unsigned char sha1[20];
3586 struct cache_entry *ce;
3587 const char *name;
3589 name = patch->old_name ? patch->old_name : patch->new_name;
3590 if (0 < patch->is_new)
3591 continue;
3592 else if (get_sha1_blob(patch->old_sha1_prefix, sha1))
3593 /* git diff has no index line for mode/type changes */
3594 if (!patch->lines_added && !patch->lines_deleted) {
3595 if (get_current_sha1(patch->old_name, sha1))
3596 die("mode change for %s, which is not "
3597 "in current HEAD", name);
3598 sha1_ptr = sha1;
3599 } else
3600 die("sha1 information is lacking or useless "
3601 "(%s).", name);
3602 else
3603 sha1_ptr = sha1;
3605 ce = make_cache_entry(patch->old_mode, sha1_ptr, name, 0, 0);
3606 if (!ce)
3607 die(_("make_cache_entry failed for path '%s'"), name);
3608 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))
3609 die ("Could not add %s to temporary index", name);
3612 fd = open(filename, O_WRONLY | O_CREAT, 0666);
3613 if (fd < 0 || write_index(&result, fd) || close(fd))
3614 die ("Could not write temporary index to %s", filename);
3616 discard_index(&result);
3619 static void stat_patch_list(struct patch *patch)
3621 int files, adds, dels;
3623 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
3624 files++;
3625 adds += patch->lines_added;
3626 dels += patch->lines_deleted;
3627 show_stats(patch);
3630 print_stat_summary(stdout, files, adds, dels);
3633 static void numstat_patch_list(struct patch *patch)
3635 for ( ; patch; patch = patch->next) {
3636 const char *name;
3637 name = patch->new_name ? patch->new_name : patch->old_name;
3638 if (patch->is_binary)
3639 printf("-\t-\t");
3640 else
3641 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
3642 write_name_quoted(name, stdout, line_termination);
3646 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
3648 if (mode)
3649 printf(" %s mode %06o %s\n", newdelete, mode, name);
3650 else
3651 printf(" %s %s\n", newdelete, name);
3654 static void show_mode_change(struct patch *p, int show_name)
3656 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
3657 if (show_name)
3658 printf(" mode change %06o => %06o %s\n",
3659 p->old_mode, p->new_mode, p->new_name);
3660 else
3661 printf(" mode change %06o => %06o\n",
3662 p->old_mode, p->new_mode);
3666 static void show_rename_copy(struct patch *p)
3668 const char *renamecopy = p->is_rename ? "rename" : "copy";
3669 const char *old, *new;
3671 /* Find common prefix */
3672 old = p->old_name;
3673 new = p->new_name;
3674 while (1) {
3675 const char *slash_old, *slash_new;
3676 slash_old = strchr(old, '/');
3677 slash_new = strchr(new, '/');
3678 if (!slash_old ||
3679 !slash_new ||
3680 slash_old - old != slash_new - new ||
3681 memcmp(old, new, slash_new - new))
3682 break;
3683 old = slash_old + 1;
3684 new = slash_new + 1;
3686 /* p->old_name thru old is the common prefix, and old and new
3687 * through the end of names are renames
3689 if (old != p->old_name)
3690 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
3691 (int)(old - p->old_name), p->old_name,
3692 old, new, p->score);
3693 else
3694 printf(" %s %s => %s (%d%%)\n", renamecopy,
3695 p->old_name, p->new_name, p->score);
3696 show_mode_change(p, 0);
3699 static void summary_patch_list(struct patch *patch)
3701 struct patch *p;
3703 for (p = patch; p; p = p->next) {
3704 if (p->is_new)
3705 show_file_mode_name("create", p->new_mode, p->new_name);
3706 else if (p->is_delete)
3707 show_file_mode_name("delete", p->old_mode, p->old_name);
3708 else {
3709 if (p->is_rename || p->is_copy)
3710 show_rename_copy(p);
3711 else {
3712 if (p->score) {
3713 printf(" rewrite %s (%d%%)\n",
3714 p->new_name, p->score);
3715 show_mode_change(p, 0);
3717 else
3718 show_mode_change(p, 1);
3724 static void patch_stats(struct patch *patch)
3726 int lines = patch->lines_added + patch->lines_deleted;
3728 if (lines > max_change)
3729 max_change = lines;
3730 if (patch->old_name) {
3731 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
3732 if (!len)
3733 len = strlen(patch->old_name);
3734 if (len > max_len)
3735 max_len = len;
3737 if (patch->new_name) {
3738 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
3739 if (!len)
3740 len = strlen(patch->new_name);
3741 if (len > max_len)
3742 max_len = len;
3746 static void remove_file(struct patch *patch, int rmdir_empty)
3748 if (update_index) {
3749 if (remove_file_from_cache(patch->old_name) < 0)
3750 die(_("unable to remove %s from index"), patch->old_name);
3752 if (!cached) {
3753 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
3754 remove_path(patch->old_name);
3759 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
3761 struct stat st;
3762 struct cache_entry *ce;
3763 int namelen = strlen(path);
3764 unsigned ce_size = cache_entry_size(namelen);
3766 if (!update_index)
3767 return;
3769 ce = xcalloc(1, ce_size);
3770 memcpy(ce->name, path, namelen);
3771 ce->ce_mode = create_ce_mode(mode);
3772 ce->ce_flags = create_ce_flags(0);
3773 ce->ce_namelen = namelen;
3774 if (S_ISGITLINK(mode)) {
3775 const char *s = buf;
3777 if (get_sha1_hex(s + strlen("Subproject commit "), ce->sha1))
3778 die(_("corrupt patch for subproject %s"), path);
3779 } else {
3780 if (!cached) {
3781 if (lstat(path, &st) < 0)
3782 die_errno(_("unable to stat newly created file '%s'"),
3783 path);
3784 fill_stat_cache_info(ce, &st);
3786 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
3787 die(_("unable to create backing store for newly created file %s"), path);
3789 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
3790 die(_("unable to add cache entry for %s"), path);
3793 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
3795 int fd;
3796 struct strbuf nbuf = STRBUF_INIT;
3798 if (S_ISGITLINK(mode)) {
3799 struct stat st;
3800 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
3801 return 0;
3802 return mkdir(path, 0777);
3805 if (has_symlinks && S_ISLNK(mode))
3806 /* Although buf:size is counted string, it also is NUL
3807 * terminated.
3809 return symlink(buf, path);
3811 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
3812 if (fd < 0)
3813 return -1;
3815 if (convert_to_working_tree(path, buf, size, &nbuf)) {
3816 size = nbuf.len;
3817 buf = nbuf.buf;
3819 write_or_die(fd, buf, size);
3820 strbuf_release(&nbuf);
3822 if (close(fd) < 0)
3823 die_errno(_("closing file '%s'"), path);
3824 return 0;
3828 * We optimistically assume that the directories exist,
3829 * which is true 99% of the time anyway. If they don't,
3830 * we create them and try again.
3832 static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
3834 if (cached)
3835 return;
3836 if (!try_create_file(path, mode, buf, size))
3837 return;
3839 if (errno == ENOENT) {
3840 if (safe_create_leading_directories(path))
3841 return;
3842 if (!try_create_file(path, mode, buf, size))
3843 return;
3846 if (errno == EEXIST || errno == EACCES) {
3847 /* We may be trying to create a file where a directory
3848 * used to be.
3850 struct stat st;
3851 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
3852 errno = EEXIST;
3855 if (errno == EEXIST) {
3856 unsigned int nr = getpid();
3858 for (;;) {
3859 char newpath[PATH_MAX];
3860 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
3861 if (!try_create_file(newpath, mode, buf, size)) {
3862 if (!rename(newpath, path))
3863 return;
3864 unlink_or_warn(newpath);
3865 break;
3867 if (errno != EEXIST)
3868 break;
3869 ++nr;
3872 die_errno(_("unable to write file '%s' mode %o"), path, mode);
3875 static void add_conflicted_stages_file(struct patch *patch)
3877 int stage, namelen;
3878 unsigned ce_size, mode;
3879 struct cache_entry *ce;
3881 if (!update_index)
3882 return;
3883 namelen = strlen(patch->new_name);
3884 ce_size = cache_entry_size(namelen);
3885 mode = patch->new_mode ? patch->new_mode : (S_IFREG | 0644);
3887 remove_file_from_cache(patch->new_name);
3888 for (stage = 1; stage < 4; stage++) {
3889 if (is_null_sha1(patch->threeway_stage[stage - 1]))
3890 continue;
3891 ce = xcalloc(1, ce_size);
3892 memcpy(ce->name, patch->new_name, namelen);
3893 ce->ce_mode = create_ce_mode(mode);
3894 ce->ce_flags = create_ce_flags(stage);
3895 ce->ce_namelen = namelen;
3896 hashcpy(ce->sha1, patch->threeway_stage[stage - 1]);
3897 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
3898 die(_("unable to add cache entry for %s"), patch->new_name);
3902 static void create_file(struct patch *patch)
3904 char *path = patch->new_name;
3905 unsigned mode = patch->new_mode;
3906 unsigned long size = patch->resultsize;
3907 char *buf = patch->result;
3909 if (!mode)
3910 mode = S_IFREG | 0644;
3911 create_one_file(path, mode, buf, size);
3913 if (patch->conflicted_threeway)
3914 add_conflicted_stages_file(patch);
3915 else
3916 add_index_file(path, mode, buf, size);
3919 /* phase zero is to remove, phase one is to create */
3920 static void write_out_one_result(struct patch *patch, int phase)
3922 if (patch->is_delete > 0) {
3923 if (phase == 0)
3924 remove_file(patch, 1);
3925 return;
3927 if (patch->is_new > 0 || patch->is_copy) {
3928 if (phase == 1)
3929 create_file(patch);
3930 return;
3933 * Rename or modification boils down to the same
3934 * thing: remove the old, write the new
3936 if (phase == 0)
3937 remove_file(patch, patch->is_rename);
3938 if (phase == 1)
3939 create_file(patch);
3942 static int write_out_one_reject(struct patch *patch)
3944 FILE *rej;
3945 char namebuf[PATH_MAX];
3946 struct fragment *frag;
3947 int cnt = 0;
3948 struct strbuf sb = STRBUF_INIT;
3950 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
3951 if (!frag->rejected)
3952 continue;
3953 cnt++;
3956 if (!cnt) {
3957 if (apply_verbosely)
3958 say_patch_name(stderr,
3959 _("Applied patch %s cleanly."), patch);
3960 return 0;
3963 /* This should not happen, because a removal patch that leaves
3964 * contents are marked "rejected" at the patch level.
3966 if (!patch->new_name)
3967 die(_("internal error"));
3969 /* Say this even without --verbose */
3970 strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",
3971 "Applying patch %%s with %d rejects...",
3972 cnt),
3973 cnt);
3974 say_patch_name(stderr, sb.buf, patch);
3975 strbuf_release(&sb);
3977 cnt = strlen(patch->new_name);
3978 if (ARRAY_SIZE(namebuf) <= cnt + 5) {
3979 cnt = ARRAY_SIZE(namebuf) - 5;
3980 warning(_("truncating .rej filename to %.*s.rej"),
3981 cnt - 1, patch->new_name);
3983 memcpy(namebuf, patch->new_name, cnt);
3984 memcpy(namebuf + cnt, ".rej", 5);
3986 rej = fopen(namebuf, "w");
3987 if (!rej)
3988 return error(_("cannot open %s: %s"), namebuf, strerror(errno));
3990 /* Normal git tools never deal with .rej, so do not pretend
3991 * this is a git patch by saying --git nor give extended
3992 * headers. While at it, maybe please "kompare" that wants
3993 * the trailing TAB and some garbage at the end of line ;-).
3995 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
3996 patch->new_name, patch->new_name);
3997 for (cnt = 1, frag = patch->fragments;
3998 frag;
3999 cnt++, frag = frag->next) {
4000 if (!frag->rejected) {
4001 fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);
4002 continue;
4004 fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);
4005 fprintf(rej, "%.*s", frag->size, frag->patch);
4006 if (frag->patch[frag->size-1] != '\n')
4007 fputc('\n', rej);
4009 fclose(rej);
4010 return -1;
4013 static int write_out_results(struct patch *list)
4015 int phase;
4016 int errs = 0;
4017 struct patch *l;
4018 struct string_list cpath = STRING_LIST_INIT_DUP;
4020 for (phase = 0; phase < 2; phase++) {
4021 l = list;
4022 while (l) {
4023 if (l->rejected)
4024 errs = 1;
4025 else {
4026 write_out_one_result(l, phase);
4027 if (phase == 1) {
4028 if (write_out_one_reject(l))
4029 errs = 1;
4030 if (l->conflicted_threeway) {
4031 string_list_append(&cpath, l->new_name);
4032 errs = 1;
4036 l = l->next;
4040 if (cpath.nr) {
4041 struct string_list_item *item;
4043 sort_string_list(&cpath);
4044 for_each_string_list_item(item, &cpath)
4045 fprintf(stderr, "U %s\n", item->string);
4046 string_list_clear(&cpath, 0);
4048 rerere(0);
4051 return errs;
4054 static struct lock_file lock_file;
4056 static struct string_list limit_by_name;
4057 static int has_include;
4058 static void add_name_limit(const char *name, int exclude)
4060 struct string_list_item *it;
4062 it = string_list_append(&limit_by_name, name);
4063 it->util = exclude ? NULL : (void *) 1;
4066 static int use_patch(struct patch *p)
4068 const char *pathname = p->new_name ? p->new_name : p->old_name;
4069 int i;
4071 /* Paths outside are not touched regardless of "--include" */
4072 if (0 < prefix_length) {
4073 int pathlen = strlen(pathname);
4074 if (pathlen <= prefix_length ||
4075 memcmp(prefix, pathname, prefix_length))
4076 return 0;
4079 /* See if it matches any of exclude/include rule */
4080 for (i = 0; i < limit_by_name.nr; i++) {
4081 struct string_list_item *it = &limit_by_name.items[i];
4082 if (!fnmatch(it->string, pathname, 0))
4083 return (it->util != NULL);
4087 * If we had any include, a path that does not match any rule is
4088 * not used. Otherwise, we saw bunch of exclude rules (or none)
4089 * and such a path is used.
4091 return !has_include;
4095 static void prefix_one(char **name)
4097 char *old_name = *name;
4098 if (!old_name)
4099 return;
4100 *name = xstrdup(prefix_filename(prefix, prefix_length, *name));
4101 free(old_name);
4104 static void prefix_patches(struct patch *p)
4106 if (!prefix || p->is_toplevel_relative)
4107 return;
4108 for ( ; p; p = p->next) {
4109 prefix_one(&p->new_name);
4110 prefix_one(&p->old_name);
4114 #define INACCURATE_EOF (1<<0)
4115 #define RECOUNT (1<<1)
4117 static int apply_patch(int fd, const char *filename, int options)
4119 size_t offset;
4120 struct strbuf buf = STRBUF_INIT; /* owns the patch text */
4121 struct patch *list = NULL, **listp = &list;
4122 int skipped_patch = 0;
4124 patch_input_file = filename;
4125 read_patch_file(&buf, fd);
4126 offset = 0;
4127 while (offset < buf.len) {
4128 struct patch *patch;
4129 int nr;
4131 patch = xcalloc(1, sizeof(*patch));
4132 patch->inaccurate_eof = !!(options & INACCURATE_EOF);
4133 patch->recount = !!(options & RECOUNT);
4134 nr = parse_chunk(buf.buf + offset, buf.len - offset, patch);
4135 if (nr < 0)
4136 break;
4137 if (apply_in_reverse)
4138 reverse_patches(patch);
4139 if (prefix)
4140 prefix_patches(patch);
4141 if (use_patch(patch)) {
4142 patch_stats(patch);
4143 *listp = patch;
4144 listp = &patch->next;
4146 else {
4147 free_patch(patch);
4148 skipped_patch++;
4150 offset += nr;
4153 if (!list && !skipped_patch)
4154 die(_("unrecognized input"));
4156 if (whitespace_error && (ws_error_action == die_on_ws_error))
4157 apply = 0;
4159 update_index = check_index && apply;
4160 if (update_index && newfd < 0)
4161 newfd = hold_locked_index(&lock_file, 1);
4163 if (check_index) {
4164 if (read_cache() < 0)
4165 die(_("unable to read index file"));
4168 if ((check || apply) &&
4169 check_patch_list(list) < 0 &&
4170 !apply_with_reject)
4171 exit(1);
4173 if (apply && write_out_results(list)) {
4174 if (apply_with_reject)
4175 exit(1);
4176 /* with --3way, we still need to write the index out */
4177 return 1;
4180 if (fake_ancestor)
4181 build_fake_ancestor(list, fake_ancestor);
4183 if (diffstat)
4184 stat_patch_list(list);
4186 if (numstat)
4187 numstat_patch_list(list);
4189 if (summary)
4190 summary_patch_list(list);
4192 free_patch_list(list);
4193 strbuf_release(&buf);
4194 string_list_clear(&fn_table, 0);
4195 return 0;
4198 static int git_apply_config(const char *var, const char *value, void *cb)
4200 if (!strcmp(var, "apply.whitespace"))
4201 return git_config_string(&apply_default_whitespace, var, value);
4202 else if (!strcmp(var, "apply.ignorewhitespace"))
4203 return git_config_string(&apply_default_ignorewhitespace, var, value);
4204 return git_default_config(var, value, cb);
4207 static int option_parse_exclude(const struct option *opt,
4208 const char *arg, int unset)
4210 add_name_limit(arg, 1);
4211 return 0;
4214 static int option_parse_include(const struct option *opt,
4215 const char *arg, int unset)
4217 add_name_limit(arg, 0);
4218 has_include = 1;
4219 return 0;
4222 static int option_parse_p(const struct option *opt,
4223 const char *arg, int unset)
4225 p_value = atoi(arg);
4226 p_value_known = 1;
4227 return 0;
4230 static int option_parse_z(const struct option *opt,
4231 const char *arg, int unset)
4233 if (unset)
4234 line_termination = '\n';
4235 else
4236 line_termination = 0;
4237 return 0;
4240 static int option_parse_space_change(const struct option *opt,
4241 const char *arg, int unset)
4243 if (unset)
4244 ws_ignore_action = ignore_ws_none;
4245 else
4246 ws_ignore_action = ignore_ws_change;
4247 return 0;
4250 static int option_parse_whitespace(const struct option *opt,
4251 const char *arg, int unset)
4253 const char **whitespace_option = opt->value;
4255 *whitespace_option = arg;
4256 parse_whitespace_option(arg);
4257 return 0;
4260 static int option_parse_directory(const struct option *opt,
4261 const char *arg, int unset)
4263 root_len = strlen(arg);
4264 if (root_len && arg[root_len - 1] != '/') {
4265 char *new_root;
4266 root = new_root = xmalloc(root_len + 2);
4267 strcpy(new_root, arg);
4268 strcpy(new_root + root_len++, "/");
4269 } else
4270 root = arg;
4271 return 0;
4274 int cmd_apply(int argc, const char **argv, const char *prefix_)
4276 int i;
4277 int errs = 0;
4278 int is_not_gitdir = !startup_info->have_repository;
4279 int force_apply = 0;
4281 const char *whitespace_option = NULL;
4283 struct option builtin_apply_options[] = {
4284 { OPTION_CALLBACK, 0, "exclude", NULL, N_("path"),
4285 N_("don't apply changes matching the given path"),
4286 0, option_parse_exclude },
4287 { OPTION_CALLBACK, 0, "include", NULL, N_("path"),
4288 N_("apply changes matching the given path"),
4289 0, option_parse_include },
4290 { OPTION_CALLBACK, 'p', NULL, NULL, N_("num"),
4291 N_("remove <num> leading slashes from traditional diff paths"),
4292 0, option_parse_p },
4293 OPT_BOOLEAN(0, "no-add", &no_add,
4294 N_("ignore additions made by the patch")),
4295 OPT_BOOLEAN(0, "stat", &diffstat,
4296 N_("instead of applying the patch, output diffstat for the input")),
4297 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
4298 OPT_NOOP_NOARG(0, "binary"),
4299 OPT_BOOLEAN(0, "numstat", &numstat,
4300 N_("shows number of added and deleted lines in decimal notation")),
4301 OPT_BOOLEAN(0, "summary", &summary,
4302 N_("instead of applying the patch, output a summary for the input")),
4303 OPT_BOOLEAN(0, "check", &check,
4304 N_("instead of applying the patch, see if the patch is applicable")),
4305 OPT_BOOLEAN(0, "index", &check_index,
4306 N_("make sure the patch is applicable to the current index")),
4307 OPT_BOOLEAN(0, "cached", &cached,
4308 N_("apply a patch without touching the working tree")),
4309 OPT_BOOLEAN(0, "apply", &force_apply,
4310 N_("also apply the patch (use with --stat/--summary/--check)")),
4311 OPT_BOOL('3', "3way", &threeway,
4312 N_( "attempt three-way merge if a patch does not apply")),
4313 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor,
4314 N_("build a temporary index based on embedded index information")),
4315 { OPTION_CALLBACK, 'z', NULL, NULL, NULL,
4316 N_("paths are separated with NUL character"),
4317 PARSE_OPT_NOARG, option_parse_z },
4318 OPT_INTEGER('C', NULL, &p_context,
4319 N_("ensure at least <n> lines of context match")),
4320 { OPTION_CALLBACK, 0, "whitespace", &whitespace_option, N_("action"),
4321 N_("detect new or modified lines that have whitespace errors"),
4322 0, option_parse_whitespace },
4323 { OPTION_CALLBACK, 0, "ignore-space-change", NULL, NULL,
4324 N_("ignore changes in whitespace when finding context"),
4325 PARSE_OPT_NOARG, option_parse_space_change },
4326 { OPTION_CALLBACK, 0, "ignore-whitespace", NULL, NULL,
4327 N_("ignore changes in whitespace when finding context"),
4328 PARSE_OPT_NOARG, option_parse_space_change },
4329 OPT_BOOLEAN('R', "reverse", &apply_in_reverse,
4330 N_("apply the patch in reverse")),
4331 OPT_BOOLEAN(0, "unidiff-zero", &unidiff_zero,
4332 N_("don't expect at least one line of context")),
4333 OPT_BOOLEAN(0, "reject", &apply_with_reject,
4334 N_("leave the rejected hunks in corresponding *.rej files")),
4335 OPT_BOOLEAN(0, "allow-overlap", &allow_overlap,
4336 N_("allow overlapping hunks")),
4337 OPT__VERBOSE(&apply_verbosely, N_("be verbose")),
4338 OPT_BIT(0, "inaccurate-eof", &options,
4339 N_("tolerate incorrectly detected missing new-line at the end of file"),
4340 INACCURATE_EOF),
4341 OPT_BIT(0, "recount", &options,
4342 N_("do not trust the line counts in the hunk headers"),
4343 RECOUNT),
4344 { OPTION_CALLBACK, 0, "directory", NULL, N_("root"),
4345 N_("prepend <root> to all filenames"),
4346 0, option_parse_directory },
4347 OPT_END()
4350 prefix = prefix_;
4351 prefix_length = prefix ? strlen(prefix) : 0;
4352 git_config(git_apply_config, NULL);
4353 if (apply_default_whitespace)
4354 parse_whitespace_option(apply_default_whitespace);
4355 if (apply_default_ignorewhitespace)
4356 parse_ignorewhitespace_option(apply_default_ignorewhitespace);
4358 argc = parse_options(argc, argv, prefix, builtin_apply_options,
4359 apply_usage, 0);
4361 if (apply_with_reject && threeway)
4362 die("--reject and --3way cannot be used together.");
4363 if (cached && threeway)
4364 die("--cached and --3way cannot be used together.");
4365 if (threeway) {
4366 if (is_not_gitdir)
4367 die(_("--3way outside a repository"));
4368 check_index = 1;
4370 if (apply_with_reject)
4371 apply = apply_verbosely = 1;
4372 if (!force_apply && (diffstat || numstat || summary || check || fake_ancestor))
4373 apply = 0;
4374 if (check_index && is_not_gitdir)
4375 die(_("--index outside a repository"));
4376 if (cached) {
4377 if (is_not_gitdir)
4378 die(_("--cached outside a repository"));
4379 check_index = 1;
4381 for (i = 0; i < argc; i++) {
4382 const char *arg = argv[i];
4383 int fd;
4385 if (!strcmp(arg, "-")) {
4386 errs |= apply_patch(0, "<stdin>", options);
4387 read_stdin = 0;
4388 continue;
4389 } else if (0 < prefix_length)
4390 arg = prefix_filename(prefix, prefix_length, arg);
4392 fd = open(arg, O_RDONLY);
4393 if (fd < 0)
4394 die_errno(_("can't open patch '%s'"), arg);
4395 read_stdin = 0;
4396 set_default_whitespace_mode(whitespace_option);
4397 errs |= apply_patch(fd, arg, options);
4398 close(fd);
4400 set_default_whitespace_mode(whitespace_option);
4401 if (read_stdin)
4402 errs |= apply_patch(0, "<stdin>", options);
4403 if (whitespace_error) {
4404 if (squelch_whitespace_errors &&
4405 squelch_whitespace_errors < whitespace_error) {
4406 int squelched =
4407 whitespace_error - squelch_whitespace_errors;
4408 warning(Q_("squelched %d whitespace error",
4409 "squelched %d whitespace errors",
4410 squelched),
4411 squelched);
4413 if (ws_error_action == die_on_ws_error)
4414 die(Q_("%d line adds whitespace errors.",
4415 "%d lines add whitespace errors.",
4416 whitespace_error),
4417 whitespace_error);
4418 if (applied_after_fixing_ws && apply)
4419 warning("%d line%s applied after"
4420 " fixing whitespace errors.",
4421 applied_after_fixing_ws,
4422 applied_after_fixing_ws == 1 ? "" : "s");
4423 else if (whitespace_error)
4424 warning(Q_("%d line adds whitespace errors.",
4425 "%d lines add whitespace errors.",
4426 whitespace_error),
4427 whitespace_error);
4430 if (update_index) {
4431 if (write_cache(newfd, active_cache, active_nr) ||
4432 commit_locked_index(&lock_file))
4433 die(_("Unable to write new index file"));
4436 return !!errs;