Allow git-apply to recount the lines in a hunk (AKA recountdiff)
[git/platforms.git] / builtin-apply.c
blob64cf8af8f6a04bb738f85f55c35d07f0b5da78ed
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"
17 * --check turns on checking that the working tree matches the
18 * files that are being modified, but doesn't apply the patch
19 * --stat does just a diffstat, and doesn't actually apply
20 * --numstat does numeric diffstat, and doesn't actually apply
21 * --index-info shows the old and new index info for paths if available.
22 * --index updates the cache as well.
23 * --cached updates only the cache without ever touching the working tree.
25 static const char *prefix;
26 static int prefix_length = -1;
27 static int newfd = -1;
29 static int unidiff_zero;
30 static int p_value = 1;
31 static int p_value_known;
32 static int check_index;
33 static int update_index;
34 static int cached;
35 static int diffstat;
36 static int numstat;
37 static int summary;
38 static int check;
39 static int apply = 1;
40 static int apply_in_reverse;
41 static int apply_with_reject;
42 static int apply_verbosely;
43 static int no_add;
44 static const char *fake_ancestor;
45 static int line_termination = '\n';
46 static unsigned long p_context = ULONG_MAX;
47 static const char apply_usage[] =
48 "git-apply [--stat] [--numstat] [--summary] [--check] [--index] [--cached] [--apply] [--no-add] [--index-info] [--allow-binary-replacement] [--reverse] [--reject] [--verbose] [-z] [-pNUM] [-CNUM] [--whitespace=<nowarn|warn|fix|error|error-all>] <patch>...";
50 static enum ws_error_action {
51 nowarn_ws_error,
52 warn_on_ws_error,
53 die_on_ws_error,
54 correct_ws_error,
55 } ws_error_action = warn_on_ws_error;
56 static int whitespace_error;
57 static int squelch_whitespace_errors = 5;
58 static int applied_after_fixing_ws;
59 static const char *patch_input_file;
61 static void parse_whitespace_option(const char *option)
63 if (!option) {
64 ws_error_action = warn_on_ws_error;
65 return;
67 if (!strcmp(option, "warn")) {
68 ws_error_action = warn_on_ws_error;
69 return;
71 if (!strcmp(option, "nowarn")) {
72 ws_error_action = nowarn_ws_error;
73 return;
75 if (!strcmp(option, "error")) {
76 ws_error_action = die_on_ws_error;
77 return;
79 if (!strcmp(option, "error-all")) {
80 ws_error_action = die_on_ws_error;
81 squelch_whitespace_errors = 0;
82 return;
84 if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
85 ws_error_action = correct_ws_error;
86 return;
88 die("unrecognized whitespace option '%s'", option);
91 static void set_default_whitespace_mode(const char *whitespace_option)
93 if (!whitespace_option && !apply_default_whitespace)
94 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error);
98 * For "diff-stat" like behaviour, we keep track of the biggest change
99 * we've seen, and the longest filename. That allows us to do simple
100 * scaling.
102 static int max_change, max_len;
105 * Various "current state", notably line numbers and what
106 * file (and how) we're patching right now.. The "is_xxxx"
107 * things are flags, where -1 means "don't know yet".
109 static int linenr = 1;
112 * This represents one "hunk" from a patch, starting with
113 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
114 * patch text is pointed at by patch, and its byte length
115 * is stored in size. leading and trailing are the number
116 * of context lines.
118 struct fragment {
119 unsigned long leading, trailing;
120 unsigned long oldpos, oldlines;
121 unsigned long newpos, newlines;
122 const char *patch;
123 int size;
124 int rejected;
125 struct fragment *next;
129 * When dealing with a binary patch, we reuse "leading" field
130 * to store the type of the binary hunk, either deflated "delta"
131 * or deflated "literal".
133 #define binary_patch_method leading
134 #define BINARY_DELTA_DEFLATED 1
135 #define BINARY_LITERAL_DEFLATED 2
138 * This represents a "patch" to a file, both metainfo changes
139 * such as creation/deletion, filemode and content changes represented
140 * as a series of fragments.
142 struct patch {
143 char *new_name, *old_name, *def_name;
144 unsigned int old_mode, new_mode;
145 int is_new, is_delete; /* -1 = unknown, 0 = false, 1 = true */
146 int rejected;
147 unsigned ws_rule;
148 unsigned long deflate_origlen;
149 int lines_added, lines_deleted;
150 int score;
151 unsigned int is_toplevel_relative:1;
152 unsigned int inaccurate_eof:1;
153 unsigned int is_binary:1;
154 unsigned int is_copy:1;
155 unsigned int is_rename:1;
156 unsigned int recount:1;
157 struct fragment *fragments;
158 char *result;
159 size_t resultsize;
160 char old_sha1_prefix[41];
161 char new_sha1_prefix[41];
162 struct patch *next;
166 * A line in a file, len-bytes long (includes the terminating LF,
167 * except for an incomplete line at the end if the file ends with
168 * one), and its contents hashes to 'hash'.
170 struct line {
171 size_t len;
172 unsigned hash : 24;
173 unsigned flag : 8;
174 #define LINE_COMMON 1
178 * This represents a "file", which is an array of "lines".
180 struct image {
181 char *buf;
182 size_t len;
183 size_t nr;
184 size_t alloc;
185 struct line *line_allocated;
186 struct line *line;
189 static uint32_t hash_line(const char *cp, size_t len)
191 size_t i;
192 uint32_t h;
193 for (i = 0, h = 0; i < len; i++) {
194 if (!isspace(cp[i])) {
195 h = h * 3 + (cp[i] & 0xff);
198 return h;
201 static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
203 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
204 img->line_allocated[img->nr].len = len;
205 img->line_allocated[img->nr].hash = hash_line(bol, len);
206 img->line_allocated[img->nr].flag = flag;
207 img->nr++;
210 static void prepare_image(struct image *image, char *buf, size_t len,
211 int prepare_linetable)
213 const char *cp, *ep;
215 memset(image, 0, sizeof(*image));
216 image->buf = buf;
217 image->len = len;
219 if (!prepare_linetable)
220 return;
222 ep = image->buf + image->len;
223 cp = image->buf;
224 while (cp < ep) {
225 const char *next;
226 for (next = cp; next < ep && *next != '\n'; next++)
228 if (next < ep)
229 next++;
230 add_line_info(image, cp, next - cp, 0);
231 cp = next;
233 image->line = image->line_allocated;
236 static void clear_image(struct image *image)
238 free(image->buf);
239 image->buf = NULL;
240 image->len = 0;
243 static void say_patch_name(FILE *output, const char *pre,
244 struct patch *patch, const char *post)
246 fputs(pre, output);
247 if (patch->old_name && patch->new_name &&
248 strcmp(patch->old_name, patch->new_name)) {
249 quote_c_style(patch->old_name, NULL, output, 0);
250 fputs(" => ", output);
251 quote_c_style(patch->new_name, NULL, output, 0);
252 } else {
253 const char *n = patch->new_name;
254 if (!n)
255 n = patch->old_name;
256 quote_c_style(n, NULL, output, 0);
258 fputs(post, output);
261 #define CHUNKSIZE (8192)
262 #define SLOP (16)
264 static void read_patch_file(struct strbuf *sb, int fd)
266 if (strbuf_read(sb, fd, 0) < 0)
267 die("git-apply: read returned %s", strerror(errno));
270 * Make sure that we have some slop in the buffer
271 * so that we can do speculative "memcmp" etc, and
272 * see to it that it is NUL-filled.
274 strbuf_grow(sb, SLOP);
275 memset(sb->buf + sb->len, 0, SLOP);
278 static unsigned long linelen(const char *buffer, unsigned long size)
280 unsigned long len = 0;
281 while (size--) {
282 len++;
283 if (*buffer++ == '\n')
284 break;
286 return len;
289 static int is_dev_null(const char *str)
291 return !memcmp("/dev/null", str, 9) && isspace(str[9]);
294 #define TERM_SPACE 1
295 #define TERM_TAB 2
297 static int name_terminate(const char *name, int namelen, int c, int terminate)
299 if (c == ' ' && !(terminate & TERM_SPACE))
300 return 0;
301 if (c == '\t' && !(terminate & TERM_TAB))
302 return 0;
304 return 1;
307 static char *find_name(const char *line, char *def, int p_value, int terminate)
309 int len;
310 const char *start = line;
312 if (*line == '"') {
313 struct strbuf name;
316 * Proposed "new-style" GNU patch/diff format; see
317 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
319 strbuf_init(&name, 0);
320 if (!unquote_c_style(&name, line, NULL)) {
321 char *cp;
323 for (cp = name.buf; p_value; p_value--) {
324 cp = strchr(cp, '/');
325 if (!cp)
326 break;
327 cp++;
329 if (cp) {
330 /* name can later be freed, so we need
331 * to memmove, not just return cp
333 strbuf_remove(&name, 0, cp - name.buf);
334 free(def);
335 return strbuf_detach(&name, NULL);
338 strbuf_release(&name);
341 for (;;) {
342 char c = *line;
344 if (isspace(c)) {
345 if (c == '\n')
346 break;
347 if (name_terminate(start, line-start, c, terminate))
348 break;
350 line++;
351 if (c == '/' && !--p_value)
352 start = line;
354 if (!start)
355 return def;
356 len = line - start;
357 if (!len)
358 return def;
361 * Generally we prefer the shorter name, especially
362 * if the other one is just a variation of that with
363 * something else tacked on to the end (ie "file.orig"
364 * or "file~").
366 if (def) {
367 int deflen = strlen(def);
368 if (deflen < len && !strncmp(start, def, deflen))
369 return def;
370 free(def);
373 return xmemdupz(start, len);
376 static int count_slashes(const char *cp)
378 int cnt = 0;
379 char ch;
381 while ((ch = *cp++))
382 if (ch == '/')
383 cnt++;
384 return cnt;
388 * Given the string after "--- " or "+++ ", guess the appropriate
389 * p_value for the given patch.
391 static int guess_p_value(const char *nameline)
393 char *name, *cp;
394 int val = -1;
396 if (is_dev_null(nameline))
397 return -1;
398 name = find_name(nameline, NULL, 0, TERM_SPACE | TERM_TAB);
399 if (!name)
400 return -1;
401 cp = strchr(name, '/');
402 if (!cp)
403 val = 0;
404 else if (prefix) {
406 * Does it begin with "a/$our-prefix" and such? Then this is
407 * very likely to apply to our directory.
409 if (!strncmp(name, prefix, prefix_length))
410 val = count_slashes(prefix);
411 else {
412 cp++;
413 if (!strncmp(cp, prefix, prefix_length))
414 val = count_slashes(prefix) + 1;
417 free(name);
418 return val;
422 * Get the name etc info from the ---/+++ lines of a traditional patch header
424 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
425 * files, we can happily check the index for a match, but for creating a
426 * new file we should try to match whatever "patch" does. I have no idea.
428 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
430 char *name;
432 first += 4; /* skip "--- " */
433 second += 4; /* skip "+++ " */
434 if (!p_value_known) {
435 int p, q;
436 p = guess_p_value(first);
437 q = guess_p_value(second);
438 if (p < 0) p = q;
439 if (0 <= p && p == q) {
440 p_value = p;
441 p_value_known = 1;
444 if (is_dev_null(first)) {
445 patch->is_new = 1;
446 patch->is_delete = 0;
447 name = find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB);
448 patch->new_name = name;
449 } else if (is_dev_null(second)) {
450 patch->is_new = 0;
451 patch->is_delete = 1;
452 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
453 patch->old_name = name;
454 } else {
455 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
456 name = find_name(second, name, p_value, TERM_SPACE | TERM_TAB);
457 patch->old_name = patch->new_name = name;
459 if (!name)
460 die("unable to find filename in patch at line %d", linenr);
463 static int gitdiff_hdrend(const char *line, struct patch *patch)
465 return -1;
469 * We're anal about diff header consistency, to make
470 * sure that we don't end up having strange ambiguous
471 * patches floating around.
473 * As a result, gitdiff_{old|new}name() will check
474 * their names against any previous information, just
475 * to make sure..
477 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
479 if (!orig_name && !isnull)
480 return find_name(line, NULL, p_value, TERM_TAB);
482 if (orig_name) {
483 int len;
484 const char *name;
485 char *another;
486 name = orig_name;
487 len = strlen(name);
488 if (isnull)
489 die("git-apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
490 another = find_name(line, NULL, p_value, TERM_TAB);
491 if (!another || memcmp(another, name, len))
492 die("git-apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
493 free(another);
494 return orig_name;
496 else {
497 /* expect "/dev/null" */
498 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
499 die("git-apply: bad git-diff - expected /dev/null on line %d", linenr);
500 return NULL;
504 static int gitdiff_oldname(const char *line, struct patch *patch)
506 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
507 return 0;
510 static int gitdiff_newname(const char *line, struct patch *patch)
512 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
513 return 0;
516 static int gitdiff_oldmode(const char *line, struct patch *patch)
518 patch->old_mode = strtoul(line, NULL, 8);
519 return 0;
522 static int gitdiff_newmode(const char *line, struct patch *patch)
524 patch->new_mode = strtoul(line, NULL, 8);
525 return 0;
528 static int gitdiff_delete(const char *line, struct patch *patch)
530 patch->is_delete = 1;
531 patch->old_name = patch->def_name;
532 return gitdiff_oldmode(line, patch);
535 static int gitdiff_newfile(const char *line, struct patch *patch)
537 patch->is_new = 1;
538 patch->new_name = patch->def_name;
539 return gitdiff_newmode(line, patch);
542 static int gitdiff_copysrc(const char *line, struct patch *patch)
544 patch->is_copy = 1;
545 patch->old_name = find_name(line, NULL, 0, 0);
546 return 0;
549 static int gitdiff_copydst(const char *line, struct patch *patch)
551 patch->is_copy = 1;
552 patch->new_name = find_name(line, NULL, 0, 0);
553 return 0;
556 static int gitdiff_renamesrc(const char *line, struct patch *patch)
558 patch->is_rename = 1;
559 patch->old_name = find_name(line, NULL, 0, 0);
560 return 0;
563 static int gitdiff_renamedst(const char *line, struct patch *patch)
565 patch->is_rename = 1;
566 patch->new_name = find_name(line, NULL, 0, 0);
567 return 0;
570 static int gitdiff_similarity(const char *line, struct patch *patch)
572 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
573 patch->score = 0;
574 return 0;
577 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
579 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
580 patch->score = 0;
581 return 0;
584 static int gitdiff_index(const char *line, struct patch *patch)
587 * index line is N hexadecimal, "..", N hexadecimal,
588 * and optional space with octal mode.
590 const char *ptr, *eol;
591 int len;
593 ptr = strchr(line, '.');
594 if (!ptr || ptr[1] != '.' || 40 < ptr - line)
595 return 0;
596 len = ptr - line;
597 memcpy(patch->old_sha1_prefix, line, len);
598 patch->old_sha1_prefix[len] = 0;
600 line = ptr + 2;
601 ptr = strchr(line, ' ');
602 eol = strchr(line, '\n');
604 if (!ptr || eol < ptr)
605 ptr = eol;
606 len = ptr - line;
608 if (40 < len)
609 return 0;
610 memcpy(patch->new_sha1_prefix, line, len);
611 patch->new_sha1_prefix[len] = 0;
612 if (*ptr == ' ')
613 patch->new_mode = patch->old_mode = strtoul(ptr+1, NULL, 8);
614 return 0;
618 * This is normal for a diff that doesn't change anything: we'll fall through
619 * into the next diff. Tell the parser to break out.
621 static int gitdiff_unrecognized(const char *line, struct patch *patch)
623 return -1;
626 static const char *stop_at_slash(const char *line, int llen)
628 int i;
630 for (i = 0; i < llen; i++) {
631 int ch = line[i];
632 if (ch == '/')
633 return line + i;
635 return NULL;
639 * This is to extract the same name that appears on "diff --git"
640 * line. We do not find and return anything if it is a rename
641 * patch, and it is OK because we will find the name elsewhere.
642 * We need to reliably find name only when it is mode-change only,
643 * creation or deletion of an empty file. In any of these cases,
644 * both sides are the same name under a/ and b/ respectively.
646 static char *git_header_name(char *line, int llen)
648 const char *name;
649 const char *second = NULL;
650 size_t len;
652 line += strlen("diff --git ");
653 llen -= strlen("diff --git ");
655 if (*line == '"') {
656 const char *cp;
657 struct strbuf first;
658 struct strbuf sp;
660 strbuf_init(&first, 0);
661 strbuf_init(&sp, 0);
663 if (unquote_c_style(&first, line, &second))
664 goto free_and_fail1;
666 /* advance to the first slash */
667 cp = stop_at_slash(first.buf, first.len);
668 /* we do not accept absolute paths */
669 if (!cp || cp == first.buf)
670 goto free_and_fail1;
671 strbuf_remove(&first, 0, cp + 1 - first.buf);
674 * second points at one past closing dq of name.
675 * find the second name.
677 while ((second < line + llen) && isspace(*second))
678 second++;
680 if (line + llen <= second)
681 goto free_and_fail1;
682 if (*second == '"') {
683 if (unquote_c_style(&sp, second, NULL))
684 goto free_and_fail1;
685 cp = stop_at_slash(sp.buf, sp.len);
686 if (!cp || cp == sp.buf)
687 goto free_and_fail1;
688 /* They must match, otherwise ignore */
689 if (strcmp(cp + 1, first.buf))
690 goto free_and_fail1;
691 strbuf_release(&sp);
692 return strbuf_detach(&first, NULL);
695 /* unquoted second */
696 cp = stop_at_slash(second, line + llen - second);
697 if (!cp || cp == second)
698 goto free_and_fail1;
699 cp++;
700 if (line + llen - cp != first.len + 1 ||
701 memcmp(first.buf, cp, first.len))
702 goto free_and_fail1;
703 return strbuf_detach(&first, NULL);
705 free_and_fail1:
706 strbuf_release(&first);
707 strbuf_release(&sp);
708 return NULL;
711 /* unquoted first name */
712 name = stop_at_slash(line, llen);
713 if (!name || name == line)
714 return NULL;
715 name++;
718 * since the first name is unquoted, a dq if exists must be
719 * the beginning of the second name.
721 for (second = name; second < line + llen; second++) {
722 if (*second == '"') {
723 struct strbuf sp;
724 const char *np;
726 strbuf_init(&sp, 0);
727 if (unquote_c_style(&sp, second, NULL))
728 goto free_and_fail2;
730 np = stop_at_slash(sp.buf, sp.len);
731 if (!np || np == sp.buf)
732 goto free_and_fail2;
733 np++;
735 len = sp.buf + sp.len - np;
736 if (len < second - name &&
737 !strncmp(np, name, len) &&
738 isspace(name[len])) {
739 /* Good */
740 strbuf_remove(&sp, 0, np - sp.buf);
741 return strbuf_detach(&sp, NULL);
744 free_and_fail2:
745 strbuf_release(&sp);
746 return NULL;
751 * Accept a name only if it shows up twice, exactly the same
752 * form.
754 for (len = 0 ; ; len++) {
755 switch (name[len]) {
756 default:
757 continue;
758 case '\n':
759 return NULL;
760 case '\t': case ' ':
761 second = name+len;
762 for (;;) {
763 char c = *second++;
764 if (c == '\n')
765 return NULL;
766 if (c == '/')
767 break;
769 if (second[len] == '\n' && !memcmp(name, second, len)) {
770 return xmemdupz(name, len);
776 /* Verify that we recognize the lines following a git header */
777 static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
779 unsigned long offset;
781 /* A git diff has explicit new/delete information, so we don't guess */
782 patch->is_new = 0;
783 patch->is_delete = 0;
786 * Some things may not have the old name in the
787 * rest of the headers anywhere (pure mode changes,
788 * or removing or adding empty files), so we get
789 * the default name from the header.
791 patch->def_name = git_header_name(line, len);
793 line += len;
794 size -= len;
795 linenr++;
796 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
797 static const struct opentry {
798 const char *str;
799 int (*fn)(const char *, struct patch *);
800 } optable[] = {
801 { "@@ -", gitdiff_hdrend },
802 { "--- ", gitdiff_oldname },
803 { "+++ ", gitdiff_newname },
804 { "old mode ", gitdiff_oldmode },
805 { "new mode ", gitdiff_newmode },
806 { "deleted file mode ", gitdiff_delete },
807 { "new file mode ", gitdiff_newfile },
808 { "copy from ", gitdiff_copysrc },
809 { "copy to ", gitdiff_copydst },
810 { "rename old ", gitdiff_renamesrc },
811 { "rename new ", gitdiff_renamedst },
812 { "rename from ", gitdiff_renamesrc },
813 { "rename to ", gitdiff_renamedst },
814 { "similarity index ", gitdiff_similarity },
815 { "dissimilarity index ", gitdiff_dissimilarity },
816 { "index ", gitdiff_index },
817 { "", gitdiff_unrecognized },
819 int i;
821 len = linelen(line, size);
822 if (!len || line[len-1] != '\n')
823 break;
824 for (i = 0; i < ARRAY_SIZE(optable); i++) {
825 const struct opentry *p = optable + i;
826 int oplen = strlen(p->str);
827 if (len < oplen || memcmp(p->str, line, oplen))
828 continue;
829 if (p->fn(line + oplen, patch) < 0)
830 return offset;
831 break;
835 return offset;
838 static int parse_num(const char *line, unsigned long *p)
840 char *ptr;
842 if (!isdigit(*line))
843 return 0;
844 *p = strtoul(line, &ptr, 10);
845 return ptr - line;
848 static int parse_range(const char *line, int len, int offset, const char *expect,
849 unsigned long *p1, unsigned long *p2)
851 int digits, ex;
853 if (offset < 0 || offset >= len)
854 return -1;
855 line += offset;
856 len -= offset;
858 digits = parse_num(line, p1);
859 if (!digits)
860 return -1;
862 offset += digits;
863 line += digits;
864 len -= digits;
866 *p2 = 1;
867 if (*line == ',') {
868 digits = parse_num(line+1, p2);
869 if (!digits)
870 return -1;
872 offset += digits+1;
873 line += digits+1;
874 len -= digits+1;
877 ex = strlen(expect);
878 if (ex > len)
879 return -1;
880 if (memcmp(line, expect, ex))
881 return -1;
883 return offset + ex;
886 static void recount_diff(char *line, int size, struct fragment *fragment)
888 int oldlines = 0, newlines = 0, ret = 0;
890 if (size < 1) {
891 warning("recount: ignore empty hunk");
892 return;
895 for (;;) {
896 int len = linelen(line, size);
897 size -= len;
898 line += len;
900 if (size < 1)
901 break;
903 switch (*line) {
904 case ' ': case '\n':
905 newlines++;
906 /* fall through */
907 case '-':
908 oldlines++;
909 continue;
910 case '+':
911 newlines++;
912 continue;
913 case '\\':
914 break;
915 case '@':
916 ret = size < 3 || prefixcmp(line, "@@ ");
917 break;
918 case 'd':
919 ret = size < 5 || prefixcmp(line, "diff ");
920 break;
921 default:
922 ret = -1;
923 break;
925 if (ret) {
926 warning("recount: unexpected line: %.*s",
927 (int)linelen(line, size), line);
928 return;
930 break;
932 fragment->oldlines = oldlines;
933 fragment->newlines = newlines;
937 * Parse a unified diff fragment header of the
938 * form "@@ -a,b +c,d @@"
940 static int parse_fragment_header(char *line, int len, struct fragment *fragment)
942 int offset;
944 if (!len || line[len-1] != '\n')
945 return -1;
947 /* Figure out the number of lines in a fragment */
948 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
949 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
951 return offset;
954 static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
956 unsigned long offset, len;
958 patch->is_toplevel_relative = 0;
959 patch->is_rename = patch->is_copy = 0;
960 patch->is_new = patch->is_delete = -1;
961 patch->old_mode = patch->new_mode = 0;
962 patch->old_name = patch->new_name = NULL;
963 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
964 unsigned long nextlen;
966 len = linelen(line, size);
967 if (!len)
968 break;
970 /* Testing this early allows us to take a few shortcuts.. */
971 if (len < 6)
972 continue;
975 * Make sure we don't find any unconnected patch fragments.
976 * That's a sign that we didn't find a header, and that a
977 * patch has become corrupted/broken up.
979 if (!memcmp("@@ -", line, 4)) {
980 struct fragment dummy;
981 if (parse_fragment_header(line, len, &dummy) < 0)
982 continue;
983 die("patch fragment without header at line %d: %.*s",
984 linenr, (int)len-1, line);
987 if (size < len + 6)
988 break;
991 * Git patch? It might not have a real patch, just a rename
992 * or mode change, so we handle that specially
994 if (!memcmp("diff --git ", line, 11)) {
995 int git_hdr_len = parse_git_header(line, len, size, patch);
996 if (git_hdr_len <= len)
997 continue;
998 if (!patch->old_name && !patch->new_name) {
999 if (!patch->def_name)
1000 die("git diff header lacks filename information (line %d)", linenr);
1001 patch->old_name = patch->new_name = patch->def_name;
1003 patch->is_toplevel_relative = 1;
1004 *hdrsize = git_hdr_len;
1005 return offset;
1008 /* --- followed by +++ ? */
1009 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1010 continue;
1013 * We only accept unified patches, so we want it to
1014 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1015 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1017 nextlen = linelen(line + len, size - len);
1018 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1019 continue;
1021 /* Ok, we'll consider it a patch */
1022 parse_traditional_patch(line, line+len, patch);
1023 *hdrsize = len + nextlen;
1024 linenr += 2;
1025 return offset;
1027 return -1;
1030 static void check_whitespace(const char *line, int len, unsigned ws_rule)
1032 char *err;
1033 unsigned result = check_and_emit_line(line + 1, len - 1, ws_rule,
1034 NULL, NULL, NULL, NULL);
1035 if (!result)
1036 return;
1038 whitespace_error++;
1039 if (squelch_whitespace_errors &&
1040 squelch_whitespace_errors < whitespace_error)
1042 else {
1043 err = whitespace_error_string(result);
1044 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1045 patch_input_file, linenr, err, len - 2, line + 1);
1046 free(err);
1051 * Parse a unified diff. Note that this really needs to parse each
1052 * fragment separately, since the only way to know the difference
1053 * between a "---" that is part of a patch, and a "---" that starts
1054 * the next patch is to look at the line counts..
1056 static int parse_fragment(char *line, unsigned long size,
1057 struct patch *patch, struct fragment *fragment)
1059 int added, deleted;
1060 int len = linelen(line, size), offset;
1061 unsigned long oldlines, newlines;
1062 unsigned long leading, trailing;
1064 offset = parse_fragment_header(line, len, fragment);
1065 if (offset < 0)
1066 return -1;
1067 if (offset > 0 && patch->recount)
1068 recount_diff(line + offset, size - offset, fragment);
1069 oldlines = fragment->oldlines;
1070 newlines = fragment->newlines;
1071 leading = 0;
1072 trailing = 0;
1074 /* Parse the thing.. */
1075 line += len;
1076 size -= len;
1077 linenr++;
1078 added = deleted = 0;
1079 for (offset = len;
1080 0 < size;
1081 offset += len, size -= len, line += len, linenr++) {
1082 if (!oldlines && !newlines)
1083 break;
1084 len = linelen(line, size);
1085 if (!len || line[len-1] != '\n')
1086 return -1;
1087 switch (*line) {
1088 default:
1089 return -1;
1090 case '\n': /* newer GNU diff, an empty context line */
1091 case ' ':
1092 oldlines--;
1093 newlines--;
1094 if (!deleted && !added)
1095 leading++;
1096 trailing++;
1097 break;
1098 case '-':
1099 if (apply_in_reverse &&
1100 ws_error_action != nowarn_ws_error)
1101 check_whitespace(line, len, patch->ws_rule);
1102 deleted++;
1103 oldlines--;
1104 trailing = 0;
1105 break;
1106 case '+':
1107 if (!apply_in_reverse &&
1108 ws_error_action != nowarn_ws_error)
1109 check_whitespace(line, len, patch->ws_rule);
1110 added++;
1111 newlines--;
1112 trailing = 0;
1113 break;
1116 * We allow "\ No newline at end of file". Depending
1117 * on locale settings when the patch was produced we
1118 * don't know what this line looks like. The only
1119 * thing we do know is that it begins with "\ ".
1120 * Checking for 12 is just for sanity check -- any
1121 * l10n of "\ No newline..." is at least that long.
1123 case '\\':
1124 if (len < 12 || memcmp(line, "\\ ", 2))
1125 return -1;
1126 break;
1129 if (oldlines || newlines)
1130 return -1;
1131 fragment->leading = leading;
1132 fragment->trailing = trailing;
1135 * If a fragment ends with an incomplete line, we failed to include
1136 * it in the above loop because we hit oldlines == newlines == 0
1137 * before seeing it.
1139 if (12 < size && !memcmp(line, "\\ ", 2))
1140 offset += linelen(line, size);
1142 patch->lines_added += added;
1143 patch->lines_deleted += deleted;
1145 if (0 < patch->is_new && oldlines)
1146 return error("new file depends on old contents");
1147 if (0 < patch->is_delete && newlines)
1148 return error("deleted file still has contents");
1149 return offset;
1152 static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
1154 unsigned long offset = 0;
1155 unsigned long oldlines = 0, newlines = 0, context = 0;
1156 struct fragment **fragp = &patch->fragments;
1158 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1159 struct fragment *fragment;
1160 int len;
1162 fragment = xcalloc(1, sizeof(*fragment));
1163 len = parse_fragment(line, size, patch, fragment);
1164 if (len <= 0)
1165 die("corrupt patch at line %d", linenr);
1166 fragment->patch = line;
1167 fragment->size = len;
1168 oldlines += fragment->oldlines;
1169 newlines += fragment->newlines;
1170 context += fragment->leading + fragment->trailing;
1172 *fragp = fragment;
1173 fragp = &fragment->next;
1175 offset += len;
1176 line += len;
1177 size -= len;
1181 * If something was removed (i.e. we have old-lines) it cannot
1182 * be creation, and if something was added it cannot be
1183 * deletion. However, the reverse is not true; --unified=0
1184 * patches that only add are not necessarily creation even
1185 * though they do not have any old lines, and ones that only
1186 * delete are not necessarily deletion.
1188 * Unfortunately, a real creation/deletion patch do _not_ have
1189 * any context line by definition, so we cannot safely tell it
1190 * apart with --unified=0 insanity. At least if the patch has
1191 * more than one hunk it is not creation or deletion.
1193 if (patch->is_new < 0 &&
1194 (oldlines || (patch->fragments && patch->fragments->next)))
1195 patch->is_new = 0;
1196 if (patch->is_delete < 0 &&
1197 (newlines || (patch->fragments && patch->fragments->next)))
1198 patch->is_delete = 0;
1200 if (0 < patch->is_new && oldlines)
1201 die("new file %s depends on old contents", patch->new_name);
1202 if (0 < patch->is_delete && newlines)
1203 die("deleted file %s still has contents", patch->old_name);
1204 if (!patch->is_delete && !newlines && context)
1205 fprintf(stderr, "** warning: file %s becomes empty but "
1206 "is not deleted\n", patch->new_name);
1208 return offset;
1211 static inline int metadata_changes(struct patch *patch)
1213 return patch->is_rename > 0 ||
1214 patch->is_copy > 0 ||
1215 patch->is_new > 0 ||
1216 patch->is_delete ||
1217 (patch->old_mode && patch->new_mode &&
1218 patch->old_mode != patch->new_mode);
1221 static char *inflate_it(const void *data, unsigned long size,
1222 unsigned long inflated_size)
1224 z_stream stream;
1225 void *out;
1226 int st;
1228 memset(&stream, 0, sizeof(stream));
1230 stream.next_in = (unsigned char *)data;
1231 stream.avail_in = size;
1232 stream.next_out = out = xmalloc(inflated_size);
1233 stream.avail_out = inflated_size;
1234 inflateInit(&stream);
1235 st = inflate(&stream, Z_FINISH);
1236 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1237 free(out);
1238 return NULL;
1240 return out;
1243 static struct fragment *parse_binary_hunk(char **buf_p,
1244 unsigned long *sz_p,
1245 int *status_p,
1246 int *used_p)
1249 * Expect a line that begins with binary patch method ("literal"
1250 * or "delta"), followed by the length of data before deflating.
1251 * a sequence of 'length-byte' followed by base-85 encoded data
1252 * should follow, terminated by a newline.
1254 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1255 * and we would limit the patch line to 66 characters,
1256 * so one line can fit up to 13 groups that would decode
1257 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1258 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1260 int llen, used;
1261 unsigned long size = *sz_p;
1262 char *buffer = *buf_p;
1263 int patch_method;
1264 unsigned long origlen;
1265 char *data = NULL;
1266 int hunk_size = 0;
1267 struct fragment *frag;
1269 llen = linelen(buffer, size);
1270 used = llen;
1272 *status_p = 0;
1274 if (!prefixcmp(buffer, "delta ")) {
1275 patch_method = BINARY_DELTA_DEFLATED;
1276 origlen = strtoul(buffer + 6, NULL, 10);
1278 else if (!prefixcmp(buffer, "literal ")) {
1279 patch_method = BINARY_LITERAL_DEFLATED;
1280 origlen = strtoul(buffer + 8, NULL, 10);
1282 else
1283 return NULL;
1285 linenr++;
1286 buffer += llen;
1287 while (1) {
1288 int byte_length, max_byte_length, newsize;
1289 llen = linelen(buffer, size);
1290 used += llen;
1291 linenr++;
1292 if (llen == 1) {
1293 /* consume the blank line */
1294 buffer++;
1295 size--;
1296 break;
1299 * Minimum line is "A00000\n" which is 7-byte long,
1300 * and the line length must be multiple of 5 plus 2.
1302 if ((llen < 7) || (llen-2) % 5)
1303 goto corrupt;
1304 max_byte_length = (llen - 2) / 5 * 4;
1305 byte_length = *buffer;
1306 if ('A' <= byte_length && byte_length <= 'Z')
1307 byte_length = byte_length - 'A' + 1;
1308 else if ('a' <= byte_length && byte_length <= 'z')
1309 byte_length = byte_length - 'a' + 27;
1310 else
1311 goto corrupt;
1312 /* if the input length was not multiple of 4, we would
1313 * have filler at the end but the filler should never
1314 * exceed 3 bytes
1316 if (max_byte_length < byte_length ||
1317 byte_length <= max_byte_length - 4)
1318 goto corrupt;
1319 newsize = hunk_size + byte_length;
1320 data = xrealloc(data, newsize);
1321 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1322 goto corrupt;
1323 hunk_size = newsize;
1324 buffer += llen;
1325 size -= llen;
1328 frag = xcalloc(1, sizeof(*frag));
1329 frag->patch = inflate_it(data, hunk_size, origlen);
1330 if (!frag->patch)
1331 goto corrupt;
1332 free(data);
1333 frag->size = origlen;
1334 *buf_p = buffer;
1335 *sz_p = size;
1336 *used_p = used;
1337 frag->binary_patch_method = patch_method;
1338 return frag;
1340 corrupt:
1341 free(data);
1342 *status_p = -1;
1343 error("corrupt binary patch at line %d: %.*s",
1344 linenr-1, llen-1, buffer);
1345 return NULL;
1348 static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1351 * We have read "GIT binary patch\n"; what follows is a line
1352 * that says the patch method (currently, either "literal" or
1353 * "delta") and the length of data before deflating; a
1354 * sequence of 'length-byte' followed by base-85 encoded data
1355 * follows.
1357 * When a binary patch is reversible, there is another binary
1358 * hunk in the same format, starting with patch method (either
1359 * "literal" or "delta") with the length of data, and a sequence
1360 * of length-byte + base-85 encoded data, terminated with another
1361 * empty line. This data, when applied to the postimage, produces
1362 * the preimage.
1364 struct fragment *forward;
1365 struct fragment *reverse;
1366 int status;
1367 int used, used_1;
1369 forward = parse_binary_hunk(&buffer, &size, &status, &used);
1370 if (!forward && !status)
1371 /* there has to be one hunk (forward hunk) */
1372 return error("unrecognized binary patch at line %d", linenr-1);
1373 if (status)
1374 /* otherwise we already gave an error message */
1375 return status;
1377 reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1378 if (reverse)
1379 used += used_1;
1380 else if (status) {
1382 * Not having reverse hunk is not an error, but having
1383 * a corrupt reverse hunk is.
1385 free((void*) forward->patch);
1386 free(forward);
1387 return status;
1389 forward->next = reverse;
1390 patch->fragments = forward;
1391 patch->is_binary = 1;
1392 return used;
1395 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
1397 int hdrsize, patchsize;
1398 int offset = find_header(buffer, size, &hdrsize, patch);
1400 if (offset < 0)
1401 return offset;
1403 patch->ws_rule = whitespace_rule(patch->new_name
1404 ? patch->new_name
1405 : patch->old_name);
1407 patchsize = parse_single_patch(buffer + offset + hdrsize,
1408 size - offset - hdrsize, patch);
1410 if (!patchsize) {
1411 static const char *binhdr[] = {
1412 "Binary files ",
1413 "Files ",
1414 NULL,
1416 static const char git_binary[] = "GIT binary patch\n";
1417 int i;
1418 int hd = hdrsize + offset;
1419 unsigned long llen = linelen(buffer + hd, size - hd);
1421 if (llen == sizeof(git_binary) - 1 &&
1422 !memcmp(git_binary, buffer + hd, llen)) {
1423 int used;
1424 linenr++;
1425 used = parse_binary(buffer + hd + llen,
1426 size - hd - llen, patch);
1427 if (used)
1428 patchsize = used + llen;
1429 else
1430 patchsize = 0;
1432 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
1433 for (i = 0; binhdr[i]; i++) {
1434 int len = strlen(binhdr[i]);
1435 if (len < size - hd &&
1436 !memcmp(binhdr[i], buffer + hd, len)) {
1437 linenr++;
1438 patch->is_binary = 1;
1439 patchsize = llen;
1440 break;
1445 /* Empty patch cannot be applied if it is a text patch
1446 * without metadata change. A binary patch appears
1447 * empty to us here.
1449 if ((apply || check) &&
1450 (!patch->is_binary && !metadata_changes(patch)))
1451 die("patch with only garbage at line %d", linenr);
1454 return offset + hdrsize + patchsize;
1457 #define swap(a,b) myswap((a),(b),sizeof(a))
1459 #define myswap(a, b, size) do { \
1460 unsigned char mytmp[size]; \
1461 memcpy(mytmp, &a, size); \
1462 memcpy(&a, &b, size); \
1463 memcpy(&b, mytmp, size); \
1464 } while (0)
1466 static void reverse_patches(struct patch *p)
1468 for (; p; p = p->next) {
1469 struct fragment *frag = p->fragments;
1471 swap(p->new_name, p->old_name);
1472 swap(p->new_mode, p->old_mode);
1473 swap(p->is_new, p->is_delete);
1474 swap(p->lines_added, p->lines_deleted);
1475 swap(p->old_sha1_prefix, p->new_sha1_prefix);
1477 for (; frag; frag = frag->next) {
1478 swap(frag->newpos, frag->oldpos);
1479 swap(frag->newlines, frag->oldlines);
1484 static const char pluses[] =
1485 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1486 static const char minuses[]=
1487 "----------------------------------------------------------------------";
1489 static void show_stats(struct patch *patch)
1491 struct strbuf qname;
1492 char *cp = patch->new_name ? patch->new_name : patch->old_name;
1493 int max, add, del;
1495 strbuf_init(&qname, 0);
1496 quote_c_style(cp, &qname, NULL, 0);
1499 * "scale" the filename
1501 max = max_len;
1502 if (max > 50)
1503 max = 50;
1505 if (qname.len > max) {
1506 cp = strchr(qname.buf + qname.len + 3 - max, '/');
1507 if (!cp)
1508 cp = qname.buf + qname.len + 3 - max;
1509 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
1512 if (patch->is_binary) {
1513 printf(" %-*s | Bin\n", max, qname.buf);
1514 strbuf_release(&qname);
1515 return;
1518 printf(" %-*s |", max, qname.buf);
1519 strbuf_release(&qname);
1522 * scale the add/delete
1524 max = max + max_change > 70 ? 70 - max : max_change;
1525 add = patch->lines_added;
1526 del = patch->lines_deleted;
1528 if (max_change > 0) {
1529 int total = ((add + del) * max + max_change / 2) / max_change;
1530 add = (add * max + max_change / 2) / max_change;
1531 del = total - add;
1533 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
1534 add, pluses, del, minuses);
1537 static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
1539 switch (st->st_mode & S_IFMT) {
1540 case S_IFLNK:
1541 strbuf_grow(buf, st->st_size);
1542 if (readlink(path, buf->buf, st->st_size) != st->st_size)
1543 return -1;
1544 strbuf_setlen(buf, st->st_size);
1545 return 0;
1546 case S_IFREG:
1547 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
1548 return error("unable to open or read %s", path);
1549 convert_to_git(path, buf->buf, buf->len, buf, 0);
1550 return 0;
1551 default:
1552 return -1;
1556 static void update_pre_post_images(struct image *preimage,
1557 struct image *postimage,
1558 char *buf,
1559 size_t len)
1561 int i, ctx;
1562 char *new, *old, *fixed;
1563 struct image fixed_preimage;
1566 * Update the preimage with whitespace fixes. Note that we
1567 * are not losing preimage->buf -- apply_one_fragment() will
1568 * free "oldlines".
1570 prepare_image(&fixed_preimage, buf, len, 1);
1571 assert(fixed_preimage.nr == preimage->nr);
1572 for (i = 0; i < preimage->nr; i++)
1573 fixed_preimage.line[i].flag = preimage->line[i].flag;
1574 free(preimage->line_allocated);
1575 *preimage = fixed_preimage;
1578 * Adjust the common context lines in postimage, in place.
1579 * This is possible because whitespace fixing does not make
1580 * the string grow.
1582 new = old = postimage->buf;
1583 fixed = preimage->buf;
1584 for (i = ctx = 0; i < postimage->nr; i++) {
1585 size_t len = postimage->line[i].len;
1586 if (!(postimage->line[i].flag & LINE_COMMON)) {
1587 /* an added line -- no counterparts in preimage */
1588 memmove(new, old, len);
1589 old += len;
1590 new += len;
1591 continue;
1594 /* a common context -- skip it in the original postimage */
1595 old += len;
1597 /* and find the corresponding one in the fixed preimage */
1598 while (ctx < preimage->nr &&
1599 !(preimage->line[ctx].flag & LINE_COMMON)) {
1600 fixed += preimage->line[ctx].len;
1601 ctx++;
1603 if (preimage->nr <= ctx)
1604 die("oops");
1606 /* and copy it in, while fixing the line length */
1607 len = preimage->line[ctx].len;
1608 memcpy(new, fixed, len);
1609 new += len;
1610 fixed += len;
1611 postimage->line[i].len = len;
1612 ctx++;
1615 /* Fix the length of the whole thing */
1616 postimage->len = new - postimage->buf;
1619 static int match_fragment(struct image *img,
1620 struct image *preimage,
1621 struct image *postimage,
1622 unsigned long try,
1623 int try_lno,
1624 unsigned ws_rule,
1625 int match_beginning, int match_end)
1627 int i;
1628 char *fixed_buf, *buf, *orig, *target;
1630 if (preimage->nr + try_lno > img->nr)
1631 return 0;
1633 if (match_beginning && try_lno)
1634 return 0;
1636 if (match_end && preimage->nr + try_lno != img->nr)
1637 return 0;
1639 /* Quick hash check */
1640 for (i = 0; i < preimage->nr; i++)
1641 if (preimage->line[i].hash != img->line[try_lno + i].hash)
1642 return 0;
1645 * Do we have an exact match? If we were told to match
1646 * at the end, size must be exactly at try+fragsize,
1647 * otherwise try+fragsize must be still within the preimage,
1648 * and either case, the old piece should match the preimage
1649 * exactly.
1651 if ((match_end
1652 ? (try + preimage->len == img->len)
1653 : (try + preimage->len <= img->len)) &&
1654 !memcmp(img->buf + try, preimage->buf, preimage->len))
1655 return 1;
1657 if (ws_error_action != correct_ws_error)
1658 return 0;
1661 * The hunk does not apply byte-by-byte, but the hash says
1662 * it might with whitespace fuzz.
1664 fixed_buf = xmalloc(preimage->len + 1);
1665 buf = fixed_buf;
1666 orig = preimage->buf;
1667 target = img->buf + try;
1668 for (i = 0; i < preimage->nr; i++) {
1669 size_t fixlen; /* length after fixing the preimage */
1670 size_t oldlen = preimage->line[i].len;
1671 size_t tgtlen = img->line[try_lno + i].len;
1672 size_t tgtfixlen; /* length after fixing the target line */
1673 char tgtfixbuf[1024], *tgtfix;
1674 int match;
1676 /* Try fixing the line in the preimage */
1677 fixlen = ws_fix_copy(buf, orig, oldlen, ws_rule, NULL);
1679 /* Try fixing the line in the target */
1680 if (sizeof(tgtfixbuf) < tgtlen)
1681 tgtfix = tgtfixbuf;
1682 else
1683 tgtfix = xmalloc(tgtlen);
1684 tgtfixlen = ws_fix_copy(tgtfix, target, tgtlen, ws_rule, NULL);
1687 * If they match, either the preimage was based on
1688 * a version before our tree fixed whitespace breakage,
1689 * or we are lacking a whitespace-fix patch the tree
1690 * the preimage was based on already had (i.e. target
1691 * has whitespace breakage, the preimage doesn't).
1692 * In either case, we are fixing the whitespace breakages
1693 * so we might as well take the fix together with their
1694 * real change.
1696 match = (tgtfixlen == fixlen && !memcmp(tgtfix, buf, fixlen));
1698 if (tgtfix != tgtfixbuf)
1699 free(tgtfix);
1700 if (!match)
1701 goto unmatch_exit;
1703 orig += oldlen;
1704 buf += fixlen;
1705 target += tgtlen;
1709 * Yes, the preimage is based on an older version that still
1710 * has whitespace breakages unfixed, and fixing them makes the
1711 * hunk match. Update the context lines in the postimage.
1713 update_pre_post_images(preimage, postimage,
1714 fixed_buf, buf - fixed_buf);
1715 return 1;
1717 unmatch_exit:
1718 free(fixed_buf);
1719 return 0;
1722 static int find_pos(struct image *img,
1723 struct image *preimage,
1724 struct image *postimage,
1725 int line,
1726 unsigned ws_rule,
1727 int match_beginning, int match_end)
1729 int i;
1730 unsigned long backwards, forwards, try;
1731 int backwards_lno, forwards_lno, try_lno;
1733 if (preimage->nr > img->nr)
1734 return -1;
1737 * If match_begining or match_end is specified, there is no
1738 * point starting from a wrong line that will never match and
1739 * wander around and wait for a match at the specified end.
1741 if (match_beginning)
1742 line = 0;
1743 else if (match_end)
1744 line = img->nr - preimage->nr;
1746 if (line > img->nr)
1747 line = img->nr;
1749 try = 0;
1750 for (i = 0; i < line; i++)
1751 try += img->line[i].len;
1754 * There's probably some smart way to do this, but I'll leave
1755 * that to the smart and beautiful people. I'm simple and stupid.
1757 backwards = try;
1758 backwards_lno = line;
1759 forwards = try;
1760 forwards_lno = line;
1761 try_lno = line;
1763 for (i = 0; ; i++) {
1764 if (match_fragment(img, preimage, postimage,
1765 try, try_lno, ws_rule,
1766 match_beginning, match_end))
1767 return try_lno;
1769 again:
1770 if (backwards_lno == 0 && forwards_lno == img->nr)
1771 break;
1773 if (i & 1) {
1774 if (backwards_lno == 0) {
1775 i++;
1776 goto again;
1778 backwards_lno--;
1779 backwards -= img->line[backwards_lno].len;
1780 try = backwards;
1781 try_lno = backwards_lno;
1782 } else {
1783 if (forwards_lno == img->nr) {
1784 i++;
1785 goto again;
1787 forwards += img->line[forwards_lno].len;
1788 forwards_lno++;
1789 try = forwards;
1790 try_lno = forwards_lno;
1794 return -1;
1797 static void remove_first_line(struct image *img)
1799 img->buf += img->line[0].len;
1800 img->len -= img->line[0].len;
1801 img->line++;
1802 img->nr--;
1805 static void remove_last_line(struct image *img)
1807 img->len -= img->line[--img->nr].len;
1810 static void update_image(struct image *img,
1811 int applied_pos,
1812 struct image *preimage,
1813 struct image *postimage)
1816 * remove the copy of preimage at offset in img
1817 * and replace it with postimage
1819 int i, nr;
1820 size_t remove_count, insert_count, applied_at = 0;
1821 char *result;
1823 for (i = 0; i < applied_pos; i++)
1824 applied_at += img->line[i].len;
1826 remove_count = 0;
1827 for (i = 0; i < preimage->nr; i++)
1828 remove_count += img->line[applied_pos + i].len;
1829 insert_count = postimage->len;
1831 /* Adjust the contents */
1832 result = xmalloc(img->len + insert_count - remove_count + 1);
1833 memcpy(result, img->buf, applied_at);
1834 memcpy(result + applied_at, postimage->buf, postimage->len);
1835 memcpy(result + applied_at + postimage->len,
1836 img->buf + (applied_at + remove_count),
1837 img->len - (applied_at + remove_count));
1838 free(img->buf);
1839 img->buf = result;
1840 img->len += insert_count - remove_count;
1841 result[img->len] = '\0';
1843 /* Adjust the line table */
1844 nr = img->nr + postimage->nr - preimage->nr;
1845 if (preimage->nr < postimage->nr) {
1847 * NOTE: this knows that we never call remove_first_line()
1848 * on anything other than pre/post image.
1850 img->line = xrealloc(img->line, nr * sizeof(*img->line));
1851 img->line_allocated = img->line;
1853 if (preimage->nr != postimage->nr)
1854 memmove(img->line + applied_pos + postimage->nr,
1855 img->line + applied_pos + preimage->nr,
1856 (img->nr - (applied_pos + preimage->nr)) *
1857 sizeof(*img->line));
1858 memcpy(img->line + applied_pos,
1859 postimage->line,
1860 postimage->nr * sizeof(*img->line));
1861 img->nr = nr;
1864 static int apply_one_fragment(struct image *img, struct fragment *frag,
1865 int inaccurate_eof, unsigned ws_rule)
1867 int match_beginning, match_end;
1868 const char *patch = frag->patch;
1869 int size = frag->size;
1870 char *old, *new, *oldlines, *newlines;
1871 int new_blank_lines_at_end = 0;
1872 unsigned long leading, trailing;
1873 int pos, applied_pos;
1874 struct image preimage;
1875 struct image postimage;
1877 memset(&preimage, 0, sizeof(preimage));
1878 memset(&postimage, 0, sizeof(postimage));
1879 oldlines = xmalloc(size);
1880 newlines = xmalloc(size);
1882 old = oldlines;
1883 new = newlines;
1884 while (size > 0) {
1885 char first;
1886 int len = linelen(patch, size);
1887 int plen, added;
1888 int added_blank_line = 0;
1890 if (!len)
1891 break;
1894 * "plen" is how much of the line we should use for
1895 * the actual patch data. Normally we just remove the
1896 * first character on the line, but if the line is
1897 * followed by "\ No newline", then we also remove the
1898 * last one (which is the newline, of course).
1900 plen = len - 1;
1901 if (len < size && patch[len] == '\\')
1902 plen--;
1903 first = *patch;
1904 if (apply_in_reverse) {
1905 if (first == '-')
1906 first = '+';
1907 else if (first == '+')
1908 first = '-';
1911 switch (first) {
1912 case '\n':
1913 /* Newer GNU diff, empty context line */
1914 if (plen < 0)
1915 /* ... followed by '\No newline'; nothing */
1916 break;
1917 *old++ = '\n';
1918 *new++ = '\n';
1919 add_line_info(&preimage, "\n", 1, LINE_COMMON);
1920 add_line_info(&postimage, "\n", 1, LINE_COMMON);
1921 break;
1922 case ' ':
1923 case '-':
1924 memcpy(old, patch + 1, plen);
1925 add_line_info(&preimage, old, plen,
1926 (first == ' ' ? LINE_COMMON : 0));
1927 old += plen;
1928 if (first == '-')
1929 break;
1930 /* Fall-through for ' ' */
1931 case '+':
1932 /* --no-add does not add new lines */
1933 if (first == '+' && no_add)
1934 break;
1936 if (first != '+' ||
1937 !whitespace_error ||
1938 ws_error_action != correct_ws_error) {
1939 memcpy(new, patch + 1, plen);
1940 added = plen;
1942 else {
1943 added = ws_fix_copy(new, patch + 1, plen, ws_rule, &applied_after_fixing_ws);
1945 add_line_info(&postimage, new, added,
1946 (first == '+' ? 0 : LINE_COMMON));
1947 new += added;
1948 if (first == '+' &&
1949 added == 1 && new[-1] == '\n')
1950 added_blank_line = 1;
1951 break;
1952 case '@': case '\\':
1953 /* Ignore it, we already handled it */
1954 break;
1955 default:
1956 if (apply_verbosely)
1957 error("invalid start of line: '%c'", first);
1958 return -1;
1960 if (added_blank_line)
1961 new_blank_lines_at_end++;
1962 else
1963 new_blank_lines_at_end = 0;
1964 patch += len;
1965 size -= len;
1967 if (inaccurate_eof &&
1968 old > oldlines && old[-1] == '\n' &&
1969 new > newlines && new[-1] == '\n') {
1970 old--;
1971 new--;
1974 leading = frag->leading;
1975 trailing = frag->trailing;
1978 * A hunk to change lines at the beginning would begin with
1979 * @@ -1,L +N,M @@
1981 * And a hunk to add to an empty file would begin with
1982 * @@ -0,0 +N,M @@
1984 * In other words, a hunk that is (frag->oldpos <= 1) with or
1985 * without leading context must match at the beginning.
1987 match_beginning = frag->oldpos <= 1;
1990 * A hunk without trailing lines must match at the end.
1991 * However, we simply cannot tell if a hunk must match end
1992 * from the lack of trailing lines if the patch was generated
1993 * with unidiff without any context.
1995 match_end = !unidiff_zero && !trailing;
1997 pos = frag->newpos ? (frag->newpos - 1) : 0;
1998 preimage.buf = oldlines;
1999 preimage.len = old - oldlines;
2000 postimage.buf = newlines;
2001 postimage.len = new - newlines;
2002 preimage.line = preimage.line_allocated;
2003 postimage.line = postimage.line_allocated;
2005 for (;;) {
2007 applied_pos = find_pos(img, &preimage, &postimage, pos,
2008 ws_rule, match_beginning, match_end);
2010 if (applied_pos >= 0)
2011 break;
2013 /* Am I at my context limits? */
2014 if ((leading <= p_context) && (trailing <= p_context))
2015 break;
2016 if (match_beginning || match_end) {
2017 match_beginning = match_end = 0;
2018 continue;
2022 * Reduce the number of context lines; reduce both
2023 * leading and trailing if they are equal otherwise
2024 * just reduce the larger context.
2026 if (leading >= trailing) {
2027 remove_first_line(&preimage);
2028 remove_first_line(&postimage);
2029 pos--;
2030 leading--;
2032 if (trailing > leading) {
2033 remove_last_line(&preimage);
2034 remove_last_line(&postimage);
2035 trailing--;
2039 if (applied_pos >= 0) {
2040 if (ws_error_action == correct_ws_error &&
2041 new_blank_lines_at_end &&
2042 postimage.nr + applied_pos == img->nr) {
2044 * If the patch application adds blank lines
2045 * at the end, and if the patch applies at the
2046 * end of the image, remove those added blank
2047 * lines.
2049 while (new_blank_lines_at_end--)
2050 remove_last_line(&postimage);
2054 * Warn if it was necessary to reduce the number
2055 * of context lines.
2057 if ((leading != frag->leading) ||
2058 (trailing != frag->trailing))
2059 fprintf(stderr, "Context reduced to (%ld/%ld)"
2060 " to apply fragment at %d\n",
2061 leading, trailing, applied_pos+1);
2062 update_image(img, applied_pos, &preimage, &postimage);
2063 } else {
2064 if (apply_verbosely)
2065 error("while searching for:\n%.*s",
2066 (int)(old - oldlines), oldlines);
2069 free(oldlines);
2070 free(newlines);
2071 free(preimage.line_allocated);
2072 free(postimage.line_allocated);
2074 return (applied_pos < 0);
2077 static int apply_binary_fragment(struct image *img, struct patch *patch)
2079 struct fragment *fragment = patch->fragments;
2080 unsigned long len;
2081 void *dst;
2083 /* Binary patch is irreversible without the optional second hunk */
2084 if (apply_in_reverse) {
2085 if (!fragment->next)
2086 return error("cannot reverse-apply a binary patch "
2087 "without the reverse hunk to '%s'",
2088 patch->new_name
2089 ? patch->new_name : patch->old_name);
2090 fragment = fragment->next;
2092 switch (fragment->binary_patch_method) {
2093 case BINARY_DELTA_DEFLATED:
2094 dst = patch_delta(img->buf, img->len, fragment->patch,
2095 fragment->size, &len);
2096 if (!dst)
2097 return -1;
2098 clear_image(img);
2099 img->buf = dst;
2100 img->len = len;
2101 return 0;
2102 case BINARY_LITERAL_DEFLATED:
2103 clear_image(img);
2104 img->len = fragment->size;
2105 img->buf = xmalloc(img->len+1);
2106 memcpy(img->buf, fragment->patch, img->len);
2107 img->buf[img->len] = '\0';
2108 return 0;
2110 return -1;
2113 static int apply_binary(struct image *img, struct patch *patch)
2115 const char *name = patch->old_name ? patch->old_name : patch->new_name;
2116 unsigned char sha1[20];
2119 * For safety, we require patch index line to contain
2120 * full 40-byte textual SHA1 for old and new, at least for now.
2122 if (strlen(patch->old_sha1_prefix) != 40 ||
2123 strlen(patch->new_sha1_prefix) != 40 ||
2124 get_sha1_hex(patch->old_sha1_prefix, sha1) ||
2125 get_sha1_hex(patch->new_sha1_prefix, sha1))
2126 return error("cannot apply binary patch to '%s' "
2127 "without full index line", name);
2129 if (patch->old_name) {
2131 * See if the old one matches what the patch
2132 * applies to.
2134 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2135 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
2136 return error("the patch applies to '%s' (%s), "
2137 "which does not match the "
2138 "current contents.",
2139 name, sha1_to_hex(sha1));
2141 else {
2142 /* Otherwise, the old one must be empty. */
2143 if (img->len)
2144 return error("the patch applies to an empty "
2145 "'%s' but it is not empty", name);
2148 get_sha1_hex(patch->new_sha1_prefix, sha1);
2149 if (is_null_sha1(sha1)) {
2150 clear_image(img);
2151 return 0; /* deletion patch */
2154 if (has_sha1_file(sha1)) {
2155 /* We already have the postimage */
2156 enum object_type type;
2157 unsigned long size;
2158 char *result;
2160 result = read_sha1_file(sha1, &type, &size);
2161 if (!result)
2162 return error("the necessary postimage %s for "
2163 "'%s' cannot be read",
2164 patch->new_sha1_prefix, name);
2165 clear_image(img);
2166 img->buf = result;
2167 img->len = size;
2168 } else {
2170 * We have verified buf matches the preimage;
2171 * apply the patch data to it, which is stored
2172 * in the patch->fragments->{patch,size}.
2174 if (apply_binary_fragment(img, patch))
2175 return error("binary patch does not apply to '%s'",
2176 name);
2178 /* verify that the result matches */
2179 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2180 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
2181 return error("binary patch to '%s' creates incorrect result (expecting %s, got %s)",
2182 name, patch->new_sha1_prefix, sha1_to_hex(sha1));
2185 return 0;
2188 static int apply_fragments(struct image *img, struct patch *patch)
2190 struct fragment *frag = patch->fragments;
2191 const char *name = patch->old_name ? patch->old_name : patch->new_name;
2192 unsigned ws_rule = patch->ws_rule;
2193 unsigned inaccurate_eof = patch->inaccurate_eof;
2195 if (patch->is_binary)
2196 return apply_binary(img, patch);
2198 while (frag) {
2199 if (apply_one_fragment(img, frag, inaccurate_eof, ws_rule)) {
2200 error("patch failed: %s:%ld", name, frag->oldpos);
2201 if (!apply_with_reject)
2202 return -1;
2203 frag->rejected = 1;
2205 frag = frag->next;
2207 return 0;
2210 static int read_file_or_gitlink(struct cache_entry *ce, struct strbuf *buf)
2212 if (!ce)
2213 return 0;
2215 if (S_ISGITLINK(ce->ce_mode)) {
2216 strbuf_grow(buf, 100);
2217 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(ce->sha1));
2218 } else {
2219 enum object_type type;
2220 unsigned long sz;
2221 char *result;
2223 result = read_sha1_file(ce->sha1, &type, &sz);
2224 if (!result)
2225 return -1;
2226 /* XXX read_sha1_file NUL-terminates */
2227 strbuf_attach(buf, result, sz, sz + 1);
2229 return 0;
2232 static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce)
2234 struct strbuf buf;
2235 struct image image;
2236 size_t len;
2237 char *img;
2239 strbuf_init(&buf, 0);
2240 if (cached) {
2241 if (read_file_or_gitlink(ce, &buf))
2242 return error("read of %s failed", patch->old_name);
2243 } else if (patch->old_name) {
2244 if (S_ISGITLINK(patch->old_mode)) {
2245 if (ce) {
2246 read_file_or_gitlink(ce, &buf);
2247 } else {
2249 * There is no way to apply subproject
2250 * patch without looking at the index.
2252 patch->fragments = NULL;
2254 } else {
2255 if (read_old_data(st, patch->old_name, &buf))
2256 return error("read of %s failed", patch->old_name);
2260 img = strbuf_detach(&buf, &len);
2261 prepare_image(&image, img, len, !patch->is_binary);
2263 if (apply_fragments(&image, patch) < 0)
2264 return -1; /* note with --reject this succeeds. */
2265 patch->result = image.buf;
2266 patch->resultsize = image.len;
2267 free(image.line_allocated);
2269 if (0 < patch->is_delete && patch->resultsize)
2270 return error("removal patch leaves file contents");
2272 return 0;
2275 static int check_to_create_blob(const char *new_name, int ok_if_exists)
2277 struct stat nst;
2278 if (!lstat(new_name, &nst)) {
2279 if (S_ISDIR(nst.st_mode) || ok_if_exists)
2280 return 0;
2282 * A leading component of new_name might be a symlink
2283 * that is going to be removed with this patch, but
2284 * still pointing at somewhere that has the path.
2285 * In such a case, path "new_name" does not exist as
2286 * far as git is concerned.
2288 if (has_symlink_leading_path(strlen(new_name), new_name))
2289 return 0;
2291 return error("%s: already exists in working directory", new_name);
2293 else if ((errno != ENOENT) && (errno != ENOTDIR))
2294 return error("%s: %s", new_name, strerror(errno));
2295 return 0;
2298 static int verify_index_match(struct cache_entry *ce, struct stat *st)
2300 if (S_ISGITLINK(ce->ce_mode)) {
2301 if (!S_ISDIR(st->st_mode))
2302 return -1;
2303 return 0;
2305 return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID);
2308 static int check_preimage(struct patch *patch, struct cache_entry **ce, struct stat *st)
2310 const char *old_name = patch->old_name;
2311 int stat_ret = 0;
2312 unsigned st_mode = 0;
2315 * Make sure that we do not have local modifications from the
2316 * index when we are looking at the index. Also make sure
2317 * we have the preimage file to be patched in the work tree,
2318 * unless --cached, which tells git to apply only in the index.
2320 if (!old_name)
2321 return 0;
2323 assert(patch->is_new <= 0);
2324 if (!cached) {
2325 stat_ret = lstat(old_name, st);
2326 if (stat_ret && errno != ENOENT)
2327 return error("%s: %s", old_name, strerror(errno));
2329 if (check_index) {
2330 int pos = cache_name_pos(old_name, strlen(old_name));
2331 if (pos < 0) {
2332 if (patch->is_new < 0)
2333 goto is_new;
2334 return error("%s: does not exist in index", old_name);
2336 *ce = active_cache[pos];
2337 if (stat_ret < 0) {
2338 struct checkout costate;
2339 /* checkout */
2340 costate.base_dir = "";
2341 costate.base_dir_len = 0;
2342 costate.force = 0;
2343 costate.quiet = 0;
2344 costate.not_new = 0;
2345 costate.refresh_cache = 1;
2346 if (checkout_entry(*ce, &costate, NULL) ||
2347 lstat(old_name, st))
2348 return -1;
2350 if (!cached && verify_index_match(*ce, st))
2351 return error("%s: does not match index", old_name);
2352 if (cached)
2353 st_mode = (*ce)->ce_mode;
2354 } else if (stat_ret < 0) {
2355 if (patch->is_new < 0)
2356 goto is_new;
2357 return error("%s: %s", old_name, strerror(errno));
2360 if (!cached)
2361 st_mode = ce_mode_from_stat(*ce, st->st_mode);
2363 if (patch->is_new < 0)
2364 patch->is_new = 0;
2365 if (!patch->old_mode)
2366 patch->old_mode = st_mode;
2367 if ((st_mode ^ patch->old_mode) & S_IFMT)
2368 return error("%s: wrong type", old_name);
2369 if (st_mode != patch->old_mode)
2370 fprintf(stderr, "warning: %s has type %o, expected %o\n",
2371 old_name, st_mode, patch->old_mode);
2372 return 0;
2374 is_new:
2375 patch->is_new = 1;
2376 patch->is_delete = 0;
2377 patch->old_name = NULL;
2378 return 0;
2381 static int check_patch(struct patch *patch, struct patch *prev_patch)
2383 struct stat st;
2384 const char *old_name = patch->old_name;
2385 const char *new_name = patch->new_name;
2386 const char *name = old_name ? old_name : new_name;
2387 struct cache_entry *ce = NULL;
2388 int ok_if_exists;
2389 int status;
2391 patch->rejected = 1; /* we will drop this after we succeed */
2393 status = check_preimage(patch, &ce, &st);
2394 if (status)
2395 return status;
2396 old_name = patch->old_name;
2398 if (new_name && prev_patch && 0 < prev_patch->is_delete &&
2399 !strcmp(prev_patch->old_name, new_name))
2401 * A type-change diff is always split into a patch to
2402 * delete old, immediately followed by a patch to
2403 * create new (see diff.c::run_diff()); in such a case
2404 * it is Ok that the entry to be deleted by the
2405 * previous patch is still in the working tree and in
2406 * the index.
2408 ok_if_exists = 1;
2409 else
2410 ok_if_exists = 0;
2412 if (new_name &&
2413 ((0 < patch->is_new) | (0 < patch->is_rename) | patch->is_copy)) {
2414 if (check_index &&
2415 cache_name_pos(new_name, strlen(new_name)) >= 0 &&
2416 !ok_if_exists)
2417 return error("%s: already exists in index", new_name);
2418 if (!cached) {
2419 int err = check_to_create_blob(new_name, ok_if_exists);
2420 if (err)
2421 return err;
2423 if (!patch->new_mode) {
2424 if (0 < patch->is_new)
2425 patch->new_mode = S_IFREG | 0644;
2426 else
2427 patch->new_mode = patch->old_mode;
2431 if (new_name && old_name) {
2432 int same = !strcmp(old_name, new_name);
2433 if (!patch->new_mode)
2434 patch->new_mode = patch->old_mode;
2435 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
2436 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
2437 patch->new_mode, new_name, patch->old_mode,
2438 same ? "" : " of ", same ? "" : old_name);
2441 if (apply_data(patch, &st, ce) < 0)
2442 return error("%s: patch does not apply", name);
2443 patch->rejected = 0;
2444 return 0;
2447 static int check_patch_list(struct patch *patch)
2449 struct patch *prev_patch = NULL;
2450 int err = 0;
2452 for (prev_patch = NULL; patch ; patch = patch->next) {
2453 if (apply_verbosely)
2454 say_patch_name(stderr,
2455 "Checking patch ", patch, "...\n");
2456 err |= check_patch(patch, prev_patch);
2457 prev_patch = patch;
2459 return err;
2462 /* This function tries to read the sha1 from the current index */
2463 static int get_current_sha1(const char *path, unsigned char *sha1)
2465 int pos;
2467 if (read_cache() < 0)
2468 return -1;
2469 pos = cache_name_pos(path, strlen(path));
2470 if (pos < 0)
2471 return -1;
2472 hashcpy(sha1, active_cache[pos]->sha1);
2473 return 0;
2476 /* Build an index that contains the just the files needed for a 3way merge */
2477 static void build_fake_ancestor(struct patch *list, const char *filename)
2479 struct patch *patch;
2480 struct index_state result = { 0 };
2481 int fd;
2483 /* Once we start supporting the reverse patch, it may be
2484 * worth showing the new sha1 prefix, but until then...
2486 for (patch = list; patch; patch = patch->next) {
2487 const unsigned char *sha1_ptr;
2488 unsigned char sha1[20];
2489 struct cache_entry *ce;
2490 const char *name;
2492 name = patch->old_name ? patch->old_name : patch->new_name;
2493 if (0 < patch->is_new)
2494 continue;
2495 else if (get_sha1(patch->old_sha1_prefix, sha1))
2496 /* git diff has no index line for mode/type changes */
2497 if (!patch->lines_added && !patch->lines_deleted) {
2498 if (get_current_sha1(patch->new_name, sha1) ||
2499 get_current_sha1(patch->old_name, sha1))
2500 die("mode change for %s, which is not "
2501 "in current HEAD", name);
2502 sha1_ptr = sha1;
2503 } else
2504 die("sha1 information is lacking or useless "
2505 "(%s).", name);
2506 else
2507 sha1_ptr = sha1;
2509 ce = make_cache_entry(patch->old_mode, sha1_ptr, name, 0, 0);
2510 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))
2511 die ("Could not add %s to temporary index", name);
2514 fd = open(filename, O_WRONLY | O_CREAT, 0666);
2515 if (fd < 0 || write_index(&result, fd) || close(fd))
2516 die ("Could not write temporary index to %s", filename);
2518 discard_index(&result);
2521 static void stat_patch_list(struct patch *patch)
2523 int files, adds, dels;
2525 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
2526 files++;
2527 adds += patch->lines_added;
2528 dels += patch->lines_deleted;
2529 show_stats(patch);
2532 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
2535 static void numstat_patch_list(struct patch *patch)
2537 for ( ; patch; patch = patch->next) {
2538 const char *name;
2539 name = patch->new_name ? patch->new_name : patch->old_name;
2540 if (patch->is_binary)
2541 printf("-\t-\t");
2542 else
2543 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
2544 write_name_quoted(name, stdout, line_termination);
2548 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
2550 if (mode)
2551 printf(" %s mode %06o %s\n", newdelete, mode, name);
2552 else
2553 printf(" %s %s\n", newdelete, name);
2556 static void show_mode_change(struct patch *p, int show_name)
2558 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
2559 if (show_name)
2560 printf(" mode change %06o => %06o %s\n",
2561 p->old_mode, p->new_mode, p->new_name);
2562 else
2563 printf(" mode change %06o => %06o\n",
2564 p->old_mode, p->new_mode);
2568 static void show_rename_copy(struct patch *p)
2570 const char *renamecopy = p->is_rename ? "rename" : "copy";
2571 const char *old, *new;
2573 /* Find common prefix */
2574 old = p->old_name;
2575 new = p->new_name;
2576 while (1) {
2577 const char *slash_old, *slash_new;
2578 slash_old = strchr(old, '/');
2579 slash_new = strchr(new, '/');
2580 if (!slash_old ||
2581 !slash_new ||
2582 slash_old - old != slash_new - new ||
2583 memcmp(old, new, slash_new - new))
2584 break;
2585 old = slash_old + 1;
2586 new = slash_new + 1;
2588 /* p->old_name thru old is the common prefix, and old and new
2589 * through the end of names are renames
2591 if (old != p->old_name)
2592 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
2593 (int)(old - p->old_name), p->old_name,
2594 old, new, p->score);
2595 else
2596 printf(" %s %s => %s (%d%%)\n", renamecopy,
2597 p->old_name, p->new_name, p->score);
2598 show_mode_change(p, 0);
2601 static void summary_patch_list(struct patch *patch)
2603 struct patch *p;
2605 for (p = patch; p; p = p->next) {
2606 if (p->is_new)
2607 show_file_mode_name("create", p->new_mode, p->new_name);
2608 else if (p->is_delete)
2609 show_file_mode_name("delete", p->old_mode, p->old_name);
2610 else {
2611 if (p->is_rename || p->is_copy)
2612 show_rename_copy(p);
2613 else {
2614 if (p->score) {
2615 printf(" rewrite %s (%d%%)\n",
2616 p->new_name, p->score);
2617 show_mode_change(p, 0);
2619 else
2620 show_mode_change(p, 1);
2626 static void patch_stats(struct patch *patch)
2628 int lines = patch->lines_added + patch->lines_deleted;
2630 if (lines > max_change)
2631 max_change = lines;
2632 if (patch->old_name) {
2633 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
2634 if (!len)
2635 len = strlen(patch->old_name);
2636 if (len > max_len)
2637 max_len = len;
2639 if (patch->new_name) {
2640 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
2641 if (!len)
2642 len = strlen(patch->new_name);
2643 if (len > max_len)
2644 max_len = len;
2648 static void remove_file(struct patch *patch, int rmdir_empty)
2650 if (update_index) {
2651 if (remove_file_from_cache(patch->old_name) < 0)
2652 die("unable to remove %s from index", patch->old_name);
2654 if (!cached) {
2655 if (S_ISGITLINK(patch->old_mode)) {
2656 if (rmdir(patch->old_name))
2657 warning("unable to remove submodule %s",
2658 patch->old_name);
2659 } else if (!unlink(patch->old_name) && rmdir_empty) {
2660 char *name = xstrdup(patch->old_name);
2661 char *end = strrchr(name, '/');
2662 while (end) {
2663 *end = 0;
2664 if (rmdir(name))
2665 break;
2666 end = strrchr(name, '/');
2668 free(name);
2673 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
2675 struct stat st;
2676 struct cache_entry *ce;
2677 int namelen = strlen(path);
2678 unsigned ce_size = cache_entry_size(namelen);
2680 if (!update_index)
2681 return;
2683 ce = xcalloc(1, ce_size);
2684 memcpy(ce->name, path, namelen);
2685 ce->ce_mode = create_ce_mode(mode);
2686 ce->ce_flags = namelen;
2687 if (S_ISGITLINK(mode)) {
2688 const char *s = buf;
2690 if (get_sha1_hex(s + strlen("Subproject commit "), ce->sha1))
2691 die("corrupt patch for subproject %s", path);
2692 } else {
2693 if (!cached) {
2694 if (lstat(path, &st) < 0)
2695 die("unable to stat newly created file %s",
2696 path);
2697 fill_stat_cache_info(ce, &st);
2699 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
2700 die("unable to create backing store for newly created file %s", path);
2702 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
2703 die("unable to add cache entry for %s", path);
2706 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
2708 int fd;
2709 struct strbuf nbuf;
2711 if (S_ISGITLINK(mode)) {
2712 struct stat st;
2713 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
2714 return 0;
2715 return mkdir(path, 0777);
2718 if (has_symlinks && S_ISLNK(mode))
2719 /* Although buf:size is counted string, it also is NUL
2720 * terminated.
2722 return symlink(buf, path);
2724 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
2725 if (fd < 0)
2726 return -1;
2728 strbuf_init(&nbuf, 0);
2729 if (convert_to_working_tree(path, buf, size, &nbuf)) {
2730 size = nbuf.len;
2731 buf = nbuf.buf;
2733 write_or_die(fd, buf, size);
2734 strbuf_release(&nbuf);
2736 if (close(fd) < 0)
2737 die("closing file %s: %s", path, strerror(errno));
2738 return 0;
2742 * We optimistically assume that the directories exist,
2743 * which is true 99% of the time anyway. If they don't,
2744 * we create them and try again.
2746 static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
2748 if (cached)
2749 return;
2750 if (!try_create_file(path, mode, buf, size))
2751 return;
2753 if (errno == ENOENT) {
2754 if (safe_create_leading_directories(path))
2755 return;
2756 if (!try_create_file(path, mode, buf, size))
2757 return;
2760 if (errno == EEXIST || errno == EACCES) {
2761 /* We may be trying to create a file where a directory
2762 * used to be.
2764 struct stat st;
2765 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
2766 errno = EEXIST;
2769 if (errno == EEXIST) {
2770 unsigned int nr = getpid();
2772 for (;;) {
2773 const char *newpath;
2774 newpath = mkpath("%s~%u", path, nr);
2775 if (!try_create_file(newpath, mode, buf, size)) {
2776 if (!rename(newpath, path))
2777 return;
2778 unlink(newpath);
2779 break;
2781 if (errno != EEXIST)
2782 break;
2783 ++nr;
2786 die("unable to write file %s mode %o", path, mode);
2789 static void create_file(struct patch *patch)
2791 char *path = patch->new_name;
2792 unsigned mode = patch->new_mode;
2793 unsigned long size = patch->resultsize;
2794 char *buf = patch->result;
2796 if (!mode)
2797 mode = S_IFREG | 0644;
2798 create_one_file(path, mode, buf, size);
2799 add_index_file(path, mode, buf, size);
2802 /* phase zero is to remove, phase one is to create */
2803 static void write_out_one_result(struct patch *patch, int phase)
2805 if (patch->is_delete > 0) {
2806 if (phase == 0)
2807 remove_file(patch, 1);
2808 return;
2810 if (patch->is_new > 0 || patch->is_copy) {
2811 if (phase == 1)
2812 create_file(patch);
2813 return;
2816 * Rename or modification boils down to the same
2817 * thing: remove the old, write the new
2819 if (phase == 0)
2820 remove_file(patch, patch->is_rename);
2821 if (phase == 1)
2822 create_file(patch);
2825 static int write_out_one_reject(struct patch *patch)
2827 FILE *rej;
2828 char namebuf[PATH_MAX];
2829 struct fragment *frag;
2830 int cnt = 0;
2832 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
2833 if (!frag->rejected)
2834 continue;
2835 cnt++;
2838 if (!cnt) {
2839 if (apply_verbosely)
2840 say_patch_name(stderr,
2841 "Applied patch ", patch, " cleanly.\n");
2842 return 0;
2845 /* This should not happen, because a removal patch that leaves
2846 * contents are marked "rejected" at the patch level.
2848 if (!patch->new_name)
2849 die("internal error");
2851 /* Say this even without --verbose */
2852 say_patch_name(stderr, "Applying patch ", patch, " with");
2853 fprintf(stderr, " %d rejects...\n", cnt);
2855 cnt = strlen(patch->new_name);
2856 if (ARRAY_SIZE(namebuf) <= cnt + 5) {
2857 cnt = ARRAY_SIZE(namebuf) - 5;
2858 fprintf(stderr,
2859 "warning: truncating .rej filename to %.*s.rej",
2860 cnt - 1, patch->new_name);
2862 memcpy(namebuf, patch->new_name, cnt);
2863 memcpy(namebuf + cnt, ".rej", 5);
2865 rej = fopen(namebuf, "w");
2866 if (!rej)
2867 return error("cannot open %s: %s", namebuf, strerror(errno));
2869 /* Normal git tools never deal with .rej, so do not pretend
2870 * this is a git patch by saying --git nor give extended
2871 * headers. While at it, maybe please "kompare" that wants
2872 * the trailing TAB and some garbage at the end of line ;-).
2874 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
2875 patch->new_name, patch->new_name);
2876 for (cnt = 1, frag = patch->fragments;
2877 frag;
2878 cnt++, frag = frag->next) {
2879 if (!frag->rejected) {
2880 fprintf(stderr, "Hunk #%d applied cleanly.\n", cnt);
2881 continue;
2883 fprintf(stderr, "Rejected hunk #%d.\n", cnt);
2884 fprintf(rej, "%.*s", frag->size, frag->patch);
2885 if (frag->patch[frag->size-1] != '\n')
2886 fputc('\n', rej);
2888 fclose(rej);
2889 return -1;
2892 static int write_out_results(struct patch *list, int skipped_patch)
2894 int phase;
2895 int errs = 0;
2896 struct patch *l;
2898 if (!list && !skipped_patch)
2899 return error("No changes");
2901 for (phase = 0; phase < 2; phase++) {
2902 l = list;
2903 while (l) {
2904 if (l->rejected)
2905 errs = 1;
2906 else {
2907 write_out_one_result(l, phase);
2908 if (phase == 1 && write_out_one_reject(l))
2909 errs = 1;
2911 l = l->next;
2914 return errs;
2917 static struct lock_file lock_file;
2919 static struct excludes {
2920 struct excludes *next;
2921 const char *path;
2922 } *excludes;
2924 static int use_patch(struct patch *p)
2926 const char *pathname = p->new_name ? p->new_name : p->old_name;
2927 struct excludes *x = excludes;
2928 while (x) {
2929 if (fnmatch(x->path, pathname, 0) == 0)
2930 return 0;
2931 x = x->next;
2933 if (0 < prefix_length) {
2934 int pathlen = strlen(pathname);
2935 if (pathlen <= prefix_length ||
2936 memcmp(prefix, pathname, prefix_length))
2937 return 0;
2939 return 1;
2942 static void prefix_one(char **name)
2944 char *old_name = *name;
2945 if (!old_name)
2946 return;
2947 *name = xstrdup(prefix_filename(prefix, prefix_length, *name));
2948 free(old_name);
2951 static void prefix_patches(struct patch *p)
2953 if (!prefix || p->is_toplevel_relative)
2954 return;
2955 for ( ; p; p = p->next) {
2956 if (p->new_name == p->old_name) {
2957 char *prefixed = p->new_name;
2958 prefix_one(&prefixed);
2959 p->new_name = p->old_name = prefixed;
2961 else {
2962 prefix_one(&p->new_name);
2963 prefix_one(&p->old_name);
2968 #define INACCURATE_EOF (1<<0)
2969 #define RECOUNT (1<<1)
2971 static int apply_patch(int fd, const char *filename, int options)
2973 size_t offset;
2974 struct strbuf buf;
2975 struct patch *list = NULL, **listp = &list;
2976 int skipped_patch = 0;
2978 strbuf_init(&buf, 0);
2979 patch_input_file = filename;
2980 read_patch_file(&buf, fd);
2981 offset = 0;
2982 while (offset < buf.len) {
2983 struct patch *patch;
2984 int nr;
2986 patch = xcalloc(1, sizeof(*patch));
2987 patch->inaccurate_eof = !!(options & INACCURATE_EOF);
2988 patch->recount = !!(options & RECOUNT);
2989 nr = parse_chunk(buf.buf + offset, buf.len - offset, patch);
2990 if (nr < 0)
2991 break;
2992 if (apply_in_reverse)
2993 reverse_patches(patch);
2994 if (prefix)
2995 prefix_patches(patch);
2996 if (use_patch(patch)) {
2997 patch_stats(patch);
2998 *listp = patch;
2999 listp = &patch->next;
3001 else {
3002 /* perhaps free it a bit better? */
3003 free(patch);
3004 skipped_patch++;
3006 offset += nr;
3009 if (whitespace_error && (ws_error_action == die_on_ws_error))
3010 apply = 0;
3012 update_index = check_index && apply;
3013 if (update_index && newfd < 0)
3014 newfd = hold_locked_index(&lock_file, 1);
3016 if (check_index) {
3017 if (read_cache() < 0)
3018 die("unable to read index file");
3021 if ((check || apply) &&
3022 check_patch_list(list) < 0 &&
3023 !apply_with_reject)
3024 exit(1);
3026 if (apply && write_out_results(list, skipped_patch))
3027 exit(1);
3029 if (fake_ancestor)
3030 build_fake_ancestor(list, fake_ancestor);
3032 if (diffstat)
3033 stat_patch_list(list);
3035 if (numstat)
3036 numstat_patch_list(list);
3038 if (summary)
3039 summary_patch_list(list);
3041 strbuf_release(&buf);
3042 return 0;
3045 static int git_apply_config(const char *var, const char *value, void *cb)
3047 if (!strcmp(var, "apply.whitespace"))
3048 return git_config_string(&apply_default_whitespace, var, value);
3049 return git_default_config(var, value, cb);
3053 int cmd_apply(int argc, const char **argv, const char *unused_prefix)
3055 int i;
3056 int read_stdin = 1;
3057 int options = 0;
3058 int errs = 0;
3059 int is_not_gitdir;
3061 const char *whitespace_option = NULL;
3063 prefix = setup_git_directory_gently(&is_not_gitdir);
3064 prefix_length = prefix ? strlen(prefix) : 0;
3065 git_config(git_apply_config, NULL);
3066 if (apply_default_whitespace)
3067 parse_whitespace_option(apply_default_whitespace);
3069 for (i = 1; i < argc; i++) {
3070 const char *arg = argv[i];
3071 char *end;
3072 int fd;
3074 if (!strcmp(arg, "-")) {
3075 errs |= apply_patch(0, "<stdin>", options);
3076 read_stdin = 0;
3077 continue;
3079 if (!prefixcmp(arg, "--exclude=")) {
3080 struct excludes *x = xmalloc(sizeof(*x));
3081 x->path = arg + 10;
3082 x->next = excludes;
3083 excludes = x;
3084 continue;
3086 if (!prefixcmp(arg, "-p")) {
3087 p_value = atoi(arg + 2);
3088 p_value_known = 1;
3089 continue;
3091 if (!strcmp(arg, "--no-add")) {
3092 no_add = 1;
3093 continue;
3095 if (!strcmp(arg, "--stat")) {
3096 apply = 0;
3097 diffstat = 1;
3098 continue;
3100 if (!strcmp(arg, "--allow-binary-replacement") ||
3101 !strcmp(arg, "--binary")) {
3102 continue; /* now no-op */
3104 if (!strcmp(arg, "--numstat")) {
3105 apply = 0;
3106 numstat = 1;
3107 continue;
3109 if (!strcmp(arg, "--summary")) {
3110 apply = 0;
3111 summary = 1;
3112 continue;
3114 if (!strcmp(arg, "--check")) {
3115 apply = 0;
3116 check = 1;
3117 continue;
3119 if (!strcmp(arg, "--index")) {
3120 if (is_not_gitdir)
3121 die("--index outside a repository");
3122 check_index = 1;
3123 continue;
3125 if (!strcmp(arg, "--cached")) {
3126 if (is_not_gitdir)
3127 die("--cached outside a repository");
3128 check_index = 1;
3129 cached = 1;
3130 continue;
3132 if (!strcmp(arg, "--apply")) {
3133 apply = 1;
3134 continue;
3136 if (!strcmp(arg, "--build-fake-ancestor")) {
3137 apply = 0;
3138 if (++i >= argc)
3139 die ("need a filename");
3140 fake_ancestor = argv[i];
3141 continue;
3143 if (!strcmp(arg, "-z")) {
3144 line_termination = 0;
3145 continue;
3147 if (!prefixcmp(arg, "-C")) {
3148 p_context = strtoul(arg + 2, &end, 0);
3149 if (*end != '\0')
3150 die("unrecognized context count '%s'", arg + 2);
3151 continue;
3153 if (!prefixcmp(arg, "--whitespace=")) {
3154 whitespace_option = arg + 13;
3155 parse_whitespace_option(arg + 13);
3156 continue;
3158 if (!strcmp(arg, "-R") || !strcmp(arg, "--reverse")) {
3159 apply_in_reverse = 1;
3160 continue;
3162 if (!strcmp(arg, "--unidiff-zero")) {
3163 unidiff_zero = 1;
3164 continue;
3166 if (!strcmp(arg, "--reject")) {
3167 apply = apply_with_reject = apply_verbosely = 1;
3168 continue;
3170 if (!strcmp(arg, "-v") || !strcmp(arg, "--verbose")) {
3171 apply_verbosely = 1;
3172 continue;
3174 if (!strcmp(arg, "--inaccurate-eof")) {
3175 options |= INACCURATE_EOF;
3176 continue;
3178 if (!strcmp(arg, "--recount")) {
3179 options |= RECOUNT;
3180 continue;
3182 if (0 < prefix_length)
3183 arg = prefix_filename(prefix, prefix_length, arg);
3185 fd = open(arg, O_RDONLY);
3186 if (fd < 0)
3187 die("can't open patch '%s': %s", arg, strerror(errno));
3188 read_stdin = 0;
3189 set_default_whitespace_mode(whitespace_option);
3190 errs |= apply_patch(fd, arg, options);
3191 close(fd);
3193 set_default_whitespace_mode(whitespace_option);
3194 if (read_stdin)
3195 errs |= apply_patch(0, "<stdin>", options);
3196 if (whitespace_error) {
3197 if (squelch_whitespace_errors &&
3198 squelch_whitespace_errors < whitespace_error) {
3199 int squelched =
3200 whitespace_error - squelch_whitespace_errors;
3201 fprintf(stderr, "warning: squelched %d "
3202 "whitespace error%s\n",
3203 squelched,
3204 squelched == 1 ? "" : "s");
3206 if (ws_error_action == die_on_ws_error)
3207 die("%d line%s add%s whitespace errors.",
3208 whitespace_error,
3209 whitespace_error == 1 ? "" : "s",
3210 whitespace_error == 1 ? "s" : "");
3211 if (applied_after_fixing_ws && apply)
3212 fprintf(stderr, "warning: %d line%s applied after"
3213 " fixing whitespace errors.\n",
3214 applied_after_fixing_ws,
3215 applied_after_fixing_ws == 1 ? "" : "s");
3216 else if (whitespace_error)
3217 fprintf(stderr, "warning: %d line%s add%s whitespace errors.\n",
3218 whitespace_error,
3219 whitespace_error == 1 ? "" : "s",
3220 whitespace_error == 1 ? "s" : "");
3223 if (update_index) {
3224 if (write_cache(newfd, active_cache, active_nr) ||
3225 commit_locked_index(&lock_file))
3226 die("Unable to write new index file");
3229 return !!errs;