Merge branch 'jc/checkdiff'
[git/dscho.git] / builtin-apply.c
blob985ca3be5ab1ff0e5b4071d2ef19384dc1e9641e
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 "path-list.h"
18 * --check turns on checking that the working tree matches the
19 * files that are being modified, but doesn't apply the patch
20 * --stat does just a diffstat, and doesn't actually apply
21 * --numstat does numeric diffstat, and doesn't actually apply
22 * --index-info shows the old and new index info for paths if available.
23 * --index updates the cache as well.
24 * --cached updates only the cache without ever touching the working tree.
26 static const char *prefix;
27 static int prefix_length = -1;
28 static int newfd = -1;
30 static int unidiff_zero;
31 static int p_value = 1;
32 static int p_value_known;
33 static int check_index;
34 static int update_index;
35 static int cached;
36 static int diffstat;
37 static int numstat;
38 static int summary;
39 static int check;
40 static int apply = 1;
41 static int apply_in_reverse;
42 static int apply_with_reject;
43 static int apply_verbosely;
44 static int no_add;
45 static const char *fake_ancestor;
46 static int line_termination = '\n';
47 static unsigned long p_context = ULONG_MAX;
48 static const char apply_usage[] =
49 "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>...";
51 static enum ws_error_action {
52 nowarn_ws_error,
53 warn_on_ws_error,
54 die_on_ws_error,
55 correct_ws_error,
56 } ws_error_action = warn_on_ws_error;
57 static int whitespace_error;
58 static int squelch_whitespace_errors = 5;
59 static int applied_after_fixing_ws;
60 static const char *patch_input_file;
62 static void parse_whitespace_option(const char *option)
64 if (!option) {
65 ws_error_action = warn_on_ws_error;
66 return;
68 if (!strcmp(option, "warn")) {
69 ws_error_action = warn_on_ws_error;
70 return;
72 if (!strcmp(option, "nowarn")) {
73 ws_error_action = nowarn_ws_error;
74 return;
76 if (!strcmp(option, "error")) {
77 ws_error_action = die_on_ws_error;
78 return;
80 if (!strcmp(option, "error-all")) {
81 ws_error_action = die_on_ws_error;
82 squelch_whitespace_errors = 0;
83 return;
85 if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
86 ws_error_action = correct_ws_error;
87 return;
89 die("unrecognized whitespace option '%s'", option);
92 static void set_default_whitespace_mode(const char *whitespace_option)
94 if (!whitespace_option && !apply_default_whitespace)
95 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error);
99 * For "diff-stat" like behaviour, we keep track of the biggest change
100 * we've seen, and the longest filename. That allows us to do simple
101 * scaling.
103 static int max_change, max_len;
106 * Various "current state", notably line numbers and what
107 * file (and how) we're patching right now.. The "is_xxxx"
108 * things are flags, where -1 means "don't know yet".
110 static int linenr = 1;
113 * This represents one "hunk" from a patch, starting with
114 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
115 * patch text is pointed at by patch, and its byte length
116 * is stored in size. leading and trailing are the number
117 * of context lines.
119 struct fragment {
120 unsigned long leading, trailing;
121 unsigned long oldpos, oldlines;
122 unsigned long newpos, newlines;
123 const char *patch;
124 int size;
125 int rejected;
126 struct fragment *next;
130 * When dealing with a binary patch, we reuse "leading" field
131 * to store the type of the binary hunk, either deflated "delta"
132 * or deflated "literal".
134 #define binary_patch_method leading
135 #define BINARY_DELTA_DEFLATED 1
136 #define BINARY_LITERAL_DEFLATED 2
139 * This represents a "patch" to a file, both metainfo changes
140 * such as creation/deletion, filemode and content changes represented
141 * as a series of fragments.
143 struct patch {
144 char *new_name, *old_name, *def_name;
145 unsigned int old_mode, new_mode;
146 int is_new, is_delete; /* -1 = unknown, 0 = false, 1 = true */
147 int rejected;
148 unsigned ws_rule;
149 unsigned long deflate_origlen;
150 int lines_added, lines_deleted;
151 int score;
152 unsigned int is_toplevel_relative:1;
153 unsigned int inaccurate_eof:1;
154 unsigned int is_binary:1;
155 unsigned int is_copy:1;
156 unsigned int is_rename: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;
190 * Records filenames that have been touched, in order to handle
191 * the case where more than one patches touch the same file.
194 static struct path_list fn_table;
196 static uint32_t hash_line(const char *cp, size_t len)
198 size_t i;
199 uint32_t h;
200 for (i = 0, h = 0; i < len; i++) {
201 if (!isspace(cp[i])) {
202 h = h * 3 + (cp[i] & 0xff);
205 return h;
208 static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
210 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
211 img->line_allocated[img->nr].len = len;
212 img->line_allocated[img->nr].hash = hash_line(bol, len);
213 img->line_allocated[img->nr].flag = flag;
214 img->nr++;
217 static void prepare_image(struct image *image, char *buf, size_t len,
218 int prepare_linetable)
220 const char *cp, *ep;
222 memset(image, 0, sizeof(*image));
223 image->buf = buf;
224 image->len = len;
226 if (!prepare_linetable)
227 return;
229 ep = image->buf + image->len;
230 cp = image->buf;
231 while (cp < ep) {
232 const char *next;
233 for (next = cp; next < ep && *next != '\n'; next++)
235 if (next < ep)
236 next++;
237 add_line_info(image, cp, next - cp, 0);
238 cp = next;
240 image->line = image->line_allocated;
243 static void clear_image(struct image *image)
245 free(image->buf);
246 image->buf = NULL;
247 image->len = 0;
250 static void say_patch_name(FILE *output, const char *pre,
251 struct patch *patch, const char *post)
253 fputs(pre, output);
254 if (patch->old_name && patch->new_name &&
255 strcmp(patch->old_name, patch->new_name)) {
256 quote_c_style(patch->old_name, NULL, output, 0);
257 fputs(" => ", output);
258 quote_c_style(patch->new_name, NULL, output, 0);
259 } else {
260 const char *n = patch->new_name;
261 if (!n)
262 n = patch->old_name;
263 quote_c_style(n, NULL, output, 0);
265 fputs(post, output);
268 #define CHUNKSIZE (8192)
269 #define SLOP (16)
271 static void read_patch_file(struct strbuf *sb, int fd)
273 if (strbuf_read(sb, fd, 0) < 0)
274 die("git-apply: read returned %s", strerror(errno));
277 * Make sure that we have some slop in the buffer
278 * so that we can do speculative "memcmp" etc, and
279 * see to it that it is NUL-filled.
281 strbuf_grow(sb, SLOP);
282 memset(sb->buf + sb->len, 0, SLOP);
285 static unsigned long linelen(const char *buffer, unsigned long size)
287 unsigned long len = 0;
288 while (size--) {
289 len++;
290 if (*buffer++ == '\n')
291 break;
293 return len;
296 static int is_dev_null(const char *str)
298 return !memcmp("/dev/null", str, 9) && isspace(str[9]);
301 #define TERM_SPACE 1
302 #define TERM_TAB 2
304 static int name_terminate(const char *name, int namelen, int c, int terminate)
306 if (c == ' ' && !(terminate & TERM_SPACE))
307 return 0;
308 if (c == '\t' && !(terminate & TERM_TAB))
309 return 0;
311 return 1;
314 static char *find_name(const char *line, char *def, int p_value, int terminate)
316 int len;
317 const char *start = line;
319 if (*line == '"') {
320 struct strbuf name;
323 * Proposed "new-style" GNU patch/diff format; see
324 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
326 strbuf_init(&name, 0);
327 if (!unquote_c_style(&name, line, NULL)) {
328 char *cp;
330 for (cp = name.buf; p_value; p_value--) {
331 cp = strchr(cp, '/');
332 if (!cp)
333 break;
334 cp++;
336 if (cp) {
337 /* name can later be freed, so we need
338 * to memmove, not just return cp
340 strbuf_remove(&name, 0, cp - name.buf);
341 free(def);
342 return strbuf_detach(&name, NULL);
345 strbuf_release(&name);
348 for (;;) {
349 char c = *line;
351 if (isspace(c)) {
352 if (c == '\n')
353 break;
354 if (name_terminate(start, line-start, c, terminate))
355 break;
357 line++;
358 if (c == '/' && !--p_value)
359 start = line;
361 if (!start)
362 return def;
363 len = line - start;
364 if (!len)
365 return def;
368 * Generally we prefer the shorter name, especially
369 * if the other one is just a variation of that with
370 * something else tacked on to the end (ie "file.orig"
371 * or "file~").
373 if (def) {
374 int deflen = strlen(def);
375 if (deflen < len && !strncmp(start, def, deflen))
376 return def;
377 free(def);
380 return xmemdupz(start, len);
383 static int count_slashes(const char *cp)
385 int cnt = 0;
386 char ch;
388 while ((ch = *cp++))
389 if (ch == '/')
390 cnt++;
391 return cnt;
395 * Given the string after "--- " or "+++ ", guess the appropriate
396 * p_value for the given patch.
398 static int guess_p_value(const char *nameline)
400 char *name, *cp;
401 int val = -1;
403 if (is_dev_null(nameline))
404 return -1;
405 name = find_name(nameline, NULL, 0, TERM_SPACE | TERM_TAB);
406 if (!name)
407 return -1;
408 cp = strchr(name, '/');
409 if (!cp)
410 val = 0;
411 else if (prefix) {
413 * Does it begin with "a/$our-prefix" and such? Then this is
414 * very likely to apply to our directory.
416 if (!strncmp(name, prefix, prefix_length))
417 val = count_slashes(prefix);
418 else {
419 cp++;
420 if (!strncmp(cp, prefix, prefix_length))
421 val = count_slashes(prefix) + 1;
424 free(name);
425 return val;
429 * Get the name etc info from the ---/+++ lines of a traditional patch header
431 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
432 * files, we can happily check the index for a match, but for creating a
433 * new file we should try to match whatever "patch" does. I have no idea.
435 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
437 char *name;
439 first += 4; /* skip "--- " */
440 second += 4; /* skip "+++ " */
441 if (!p_value_known) {
442 int p, q;
443 p = guess_p_value(first);
444 q = guess_p_value(second);
445 if (p < 0) p = q;
446 if (0 <= p && p == q) {
447 p_value = p;
448 p_value_known = 1;
451 if (is_dev_null(first)) {
452 patch->is_new = 1;
453 patch->is_delete = 0;
454 name = find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB);
455 patch->new_name = name;
456 } else if (is_dev_null(second)) {
457 patch->is_new = 0;
458 patch->is_delete = 1;
459 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
460 patch->old_name = name;
461 } else {
462 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
463 name = find_name(second, name, p_value, TERM_SPACE | TERM_TAB);
464 patch->old_name = patch->new_name = name;
466 if (!name)
467 die("unable to find filename in patch at line %d", linenr);
470 static int gitdiff_hdrend(const char *line, struct patch *patch)
472 return -1;
476 * We're anal about diff header consistency, to make
477 * sure that we don't end up having strange ambiguous
478 * patches floating around.
480 * As a result, gitdiff_{old|new}name() will check
481 * their names against any previous information, just
482 * to make sure..
484 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
486 if (!orig_name && !isnull)
487 return find_name(line, NULL, p_value, TERM_TAB);
489 if (orig_name) {
490 int len;
491 const char *name;
492 char *another;
493 name = orig_name;
494 len = strlen(name);
495 if (isnull)
496 die("git-apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
497 another = find_name(line, NULL, p_value, TERM_TAB);
498 if (!another || memcmp(another, name, len))
499 die("git-apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
500 free(another);
501 return orig_name;
503 else {
504 /* expect "/dev/null" */
505 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
506 die("git-apply: bad git-diff - expected /dev/null on line %d", linenr);
507 return NULL;
511 static int gitdiff_oldname(const char *line, struct patch *patch)
513 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
514 return 0;
517 static int gitdiff_newname(const char *line, struct patch *patch)
519 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
520 return 0;
523 static int gitdiff_oldmode(const char *line, struct patch *patch)
525 patch->old_mode = strtoul(line, NULL, 8);
526 return 0;
529 static int gitdiff_newmode(const char *line, struct patch *patch)
531 patch->new_mode = strtoul(line, NULL, 8);
532 return 0;
535 static int gitdiff_delete(const char *line, struct patch *patch)
537 patch->is_delete = 1;
538 patch->old_name = patch->def_name;
539 return gitdiff_oldmode(line, patch);
542 static int gitdiff_newfile(const char *line, struct patch *patch)
544 patch->is_new = 1;
545 patch->new_name = patch->def_name;
546 return gitdiff_newmode(line, patch);
549 static int gitdiff_copysrc(const char *line, struct patch *patch)
551 patch->is_copy = 1;
552 patch->old_name = find_name(line, NULL, 0, 0);
553 return 0;
556 static int gitdiff_copydst(const char *line, struct patch *patch)
558 patch->is_copy = 1;
559 patch->new_name = find_name(line, NULL, 0, 0);
560 return 0;
563 static int gitdiff_renamesrc(const char *line, struct patch *patch)
565 patch->is_rename = 1;
566 patch->old_name = find_name(line, NULL, 0, 0);
567 return 0;
570 static int gitdiff_renamedst(const char *line, struct patch *patch)
572 patch->is_rename = 1;
573 patch->new_name = find_name(line, NULL, 0, 0);
574 return 0;
577 static int gitdiff_similarity(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_dissimilarity(const char *line, struct patch *patch)
586 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
587 patch->score = 0;
588 return 0;
591 static int gitdiff_index(const char *line, struct patch *patch)
594 * index line is N hexadecimal, "..", N hexadecimal,
595 * and optional space with octal mode.
597 const char *ptr, *eol;
598 int len;
600 ptr = strchr(line, '.');
601 if (!ptr || ptr[1] != '.' || 40 < ptr - line)
602 return 0;
603 len = ptr - line;
604 memcpy(patch->old_sha1_prefix, line, len);
605 patch->old_sha1_prefix[len] = 0;
607 line = ptr + 2;
608 ptr = strchr(line, ' ');
609 eol = strchr(line, '\n');
611 if (!ptr || eol < ptr)
612 ptr = eol;
613 len = ptr - line;
615 if (40 < len)
616 return 0;
617 memcpy(patch->new_sha1_prefix, line, len);
618 patch->new_sha1_prefix[len] = 0;
619 if (*ptr == ' ')
620 patch->new_mode = patch->old_mode = strtoul(ptr+1, NULL, 8);
621 return 0;
625 * This is normal for a diff that doesn't change anything: we'll fall through
626 * into the next diff. Tell the parser to break out.
628 static int gitdiff_unrecognized(const char *line, struct patch *patch)
630 return -1;
633 static const char *stop_at_slash(const char *line, int llen)
635 int i;
637 for (i = 0; i < llen; i++) {
638 int ch = line[i];
639 if (ch == '/')
640 return line + i;
642 return NULL;
646 * This is to extract the same name that appears on "diff --git"
647 * line. We do not find and return anything if it is a rename
648 * patch, and it is OK because we will find the name elsewhere.
649 * We need to reliably find name only when it is mode-change only,
650 * creation or deletion of an empty file. In any of these cases,
651 * both sides are the same name under a/ and b/ respectively.
653 static char *git_header_name(char *line, int llen)
655 const char *name;
656 const char *second = NULL;
657 size_t len;
659 line += strlen("diff --git ");
660 llen -= strlen("diff --git ");
662 if (*line == '"') {
663 const char *cp;
664 struct strbuf first;
665 struct strbuf sp;
667 strbuf_init(&first, 0);
668 strbuf_init(&sp, 0);
670 if (unquote_c_style(&first, line, &second))
671 goto free_and_fail1;
673 /* advance to the first slash */
674 cp = stop_at_slash(first.buf, first.len);
675 /* we do not accept absolute paths */
676 if (!cp || cp == first.buf)
677 goto free_and_fail1;
678 strbuf_remove(&first, 0, cp + 1 - first.buf);
681 * second points at one past closing dq of name.
682 * find the second name.
684 while ((second < line + llen) && isspace(*second))
685 second++;
687 if (line + llen <= second)
688 goto free_and_fail1;
689 if (*second == '"') {
690 if (unquote_c_style(&sp, second, NULL))
691 goto free_and_fail1;
692 cp = stop_at_slash(sp.buf, sp.len);
693 if (!cp || cp == sp.buf)
694 goto free_and_fail1;
695 /* They must match, otherwise ignore */
696 if (strcmp(cp + 1, first.buf))
697 goto free_and_fail1;
698 strbuf_release(&sp);
699 return strbuf_detach(&first, NULL);
702 /* unquoted second */
703 cp = stop_at_slash(second, line + llen - second);
704 if (!cp || cp == second)
705 goto free_and_fail1;
706 cp++;
707 if (line + llen - cp != first.len + 1 ||
708 memcmp(first.buf, cp, first.len))
709 goto free_and_fail1;
710 return strbuf_detach(&first, NULL);
712 free_and_fail1:
713 strbuf_release(&first);
714 strbuf_release(&sp);
715 return NULL;
718 /* unquoted first name */
719 name = stop_at_slash(line, llen);
720 if (!name || name == line)
721 return NULL;
722 name++;
725 * since the first name is unquoted, a dq if exists must be
726 * the beginning of the second name.
728 for (second = name; second < line + llen; second++) {
729 if (*second == '"') {
730 struct strbuf sp;
731 const char *np;
733 strbuf_init(&sp, 0);
734 if (unquote_c_style(&sp, second, NULL))
735 goto free_and_fail2;
737 np = stop_at_slash(sp.buf, sp.len);
738 if (!np || np == sp.buf)
739 goto free_and_fail2;
740 np++;
742 len = sp.buf + sp.len - np;
743 if (len < second - name &&
744 !strncmp(np, name, len) &&
745 isspace(name[len])) {
746 /* Good */
747 strbuf_remove(&sp, 0, np - sp.buf);
748 return strbuf_detach(&sp, NULL);
751 free_and_fail2:
752 strbuf_release(&sp);
753 return NULL;
758 * Accept a name only if it shows up twice, exactly the same
759 * form.
761 for (len = 0 ; ; len++) {
762 switch (name[len]) {
763 default:
764 continue;
765 case '\n':
766 return NULL;
767 case '\t': case ' ':
768 second = name+len;
769 for (;;) {
770 char c = *second++;
771 if (c == '\n')
772 return NULL;
773 if (c == '/')
774 break;
776 if (second[len] == '\n' && !memcmp(name, second, len)) {
777 return xmemdupz(name, len);
783 /* Verify that we recognize the lines following a git header */
784 static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
786 unsigned long offset;
788 /* A git diff has explicit new/delete information, so we don't guess */
789 patch->is_new = 0;
790 patch->is_delete = 0;
793 * Some things may not have the old name in the
794 * rest of the headers anywhere (pure mode changes,
795 * or removing or adding empty files), so we get
796 * the default name from the header.
798 patch->def_name = git_header_name(line, len);
800 line += len;
801 size -= len;
802 linenr++;
803 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
804 static const struct opentry {
805 const char *str;
806 int (*fn)(const char *, struct patch *);
807 } optable[] = {
808 { "@@ -", gitdiff_hdrend },
809 { "--- ", gitdiff_oldname },
810 { "+++ ", gitdiff_newname },
811 { "old mode ", gitdiff_oldmode },
812 { "new mode ", gitdiff_newmode },
813 { "deleted file mode ", gitdiff_delete },
814 { "new file mode ", gitdiff_newfile },
815 { "copy from ", gitdiff_copysrc },
816 { "copy to ", gitdiff_copydst },
817 { "rename old ", gitdiff_renamesrc },
818 { "rename new ", gitdiff_renamedst },
819 { "rename from ", gitdiff_renamesrc },
820 { "rename to ", gitdiff_renamedst },
821 { "similarity index ", gitdiff_similarity },
822 { "dissimilarity index ", gitdiff_dissimilarity },
823 { "index ", gitdiff_index },
824 { "", gitdiff_unrecognized },
826 int i;
828 len = linelen(line, size);
829 if (!len || line[len-1] != '\n')
830 break;
831 for (i = 0; i < ARRAY_SIZE(optable); i++) {
832 const struct opentry *p = optable + i;
833 int oplen = strlen(p->str);
834 if (len < oplen || memcmp(p->str, line, oplen))
835 continue;
836 if (p->fn(line + oplen, patch) < 0)
837 return offset;
838 break;
842 return offset;
845 static int parse_num(const char *line, unsigned long *p)
847 char *ptr;
849 if (!isdigit(*line))
850 return 0;
851 *p = strtoul(line, &ptr, 10);
852 return ptr - line;
855 static int parse_range(const char *line, int len, int offset, const char *expect,
856 unsigned long *p1, unsigned long *p2)
858 int digits, ex;
860 if (offset < 0 || offset >= len)
861 return -1;
862 line += offset;
863 len -= offset;
865 digits = parse_num(line, p1);
866 if (!digits)
867 return -1;
869 offset += digits;
870 line += digits;
871 len -= digits;
873 *p2 = 1;
874 if (*line == ',') {
875 digits = parse_num(line+1, p2);
876 if (!digits)
877 return -1;
879 offset += digits+1;
880 line += digits+1;
881 len -= digits+1;
884 ex = strlen(expect);
885 if (ex > len)
886 return -1;
887 if (memcmp(line, expect, ex))
888 return -1;
890 return offset + ex;
894 * Parse a unified diff fragment header of the
895 * form "@@ -a,b +c,d @@"
897 static int parse_fragment_header(char *line, int len, struct fragment *fragment)
899 int offset;
901 if (!len || line[len-1] != '\n')
902 return -1;
904 /* Figure out the number of lines in a fragment */
905 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
906 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
908 return offset;
911 static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
913 unsigned long offset, len;
915 patch->is_toplevel_relative = 0;
916 patch->is_rename = patch->is_copy = 0;
917 patch->is_new = patch->is_delete = -1;
918 patch->old_mode = patch->new_mode = 0;
919 patch->old_name = patch->new_name = NULL;
920 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
921 unsigned long nextlen;
923 len = linelen(line, size);
924 if (!len)
925 break;
927 /* Testing this early allows us to take a few shortcuts.. */
928 if (len < 6)
929 continue;
932 * Make sure we don't find any unconnected patch fragments.
933 * That's a sign that we didn't find a header, and that a
934 * patch has become corrupted/broken up.
936 if (!memcmp("@@ -", line, 4)) {
937 struct fragment dummy;
938 if (parse_fragment_header(line, len, &dummy) < 0)
939 continue;
940 die("patch fragment without header at line %d: %.*s",
941 linenr, (int)len-1, line);
944 if (size < len + 6)
945 break;
948 * Git patch? It might not have a real patch, just a rename
949 * or mode change, so we handle that specially
951 if (!memcmp("diff --git ", line, 11)) {
952 int git_hdr_len = parse_git_header(line, len, size, patch);
953 if (git_hdr_len <= len)
954 continue;
955 if (!patch->old_name && !patch->new_name) {
956 if (!patch->def_name)
957 die("git diff header lacks filename information (line %d)", linenr);
958 patch->old_name = patch->new_name = patch->def_name;
960 patch->is_toplevel_relative = 1;
961 *hdrsize = git_hdr_len;
962 return offset;
965 /* --- followed by +++ ? */
966 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
967 continue;
970 * We only accept unified patches, so we want it to
971 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
972 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
974 nextlen = linelen(line + len, size - len);
975 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
976 continue;
978 /* Ok, we'll consider it a patch */
979 parse_traditional_patch(line, line+len, patch);
980 *hdrsize = len + nextlen;
981 linenr += 2;
982 return offset;
984 return -1;
987 static void check_whitespace(const char *line, int len, unsigned ws_rule)
989 char *err;
990 unsigned result = ws_check(line + 1, len - 1, ws_rule);
991 if (!result)
992 return;
994 whitespace_error++;
995 if (squelch_whitespace_errors &&
996 squelch_whitespace_errors < whitespace_error)
998 else {
999 err = whitespace_error_string(result);
1000 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1001 patch_input_file, linenr, err, len - 2, line + 1);
1002 free(err);
1007 * Parse a unified diff. Note that this really needs to parse each
1008 * fragment separately, since the only way to know the difference
1009 * between a "---" that is part of a patch, and a "---" that starts
1010 * the next patch is to look at the line counts..
1012 static int parse_fragment(char *line, unsigned long size,
1013 struct patch *patch, struct fragment *fragment)
1015 int added, deleted;
1016 int len = linelen(line, size), offset;
1017 unsigned long oldlines, newlines;
1018 unsigned long leading, trailing;
1020 offset = parse_fragment_header(line, len, fragment);
1021 if (offset < 0)
1022 return -1;
1023 oldlines = fragment->oldlines;
1024 newlines = fragment->newlines;
1025 leading = 0;
1026 trailing = 0;
1028 /* Parse the thing.. */
1029 line += len;
1030 size -= len;
1031 linenr++;
1032 added = deleted = 0;
1033 for (offset = len;
1034 0 < size;
1035 offset += len, size -= len, line += len, linenr++) {
1036 if (!oldlines && !newlines)
1037 break;
1038 len = linelen(line, size);
1039 if (!len || line[len-1] != '\n')
1040 return -1;
1041 switch (*line) {
1042 default:
1043 return -1;
1044 case '\n': /* newer GNU diff, an empty context line */
1045 case ' ':
1046 oldlines--;
1047 newlines--;
1048 if (!deleted && !added)
1049 leading++;
1050 trailing++;
1051 break;
1052 case '-':
1053 if (apply_in_reverse &&
1054 ws_error_action != nowarn_ws_error)
1055 check_whitespace(line, len, patch->ws_rule);
1056 deleted++;
1057 oldlines--;
1058 trailing = 0;
1059 break;
1060 case '+':
1061 if (!apply_in_reverse &&
1062 ws_error_action != nowarn_ws_error)
1063 check_whitespace(line, len, patch->ws_rule);
1064 added++;
1065 newlines--;
1066 trailing = 0;
1067 break;
1070 * We allow "\ No newline at end of file". Depending
1071 * on locale settings when the patch was produced we
1072 * don't know what this line looks like. The only
1073 * thing we do know is that it begins with "\ ".
1074 * Checking for 12 is just for sanity check -- any
1075 * l10n of "\ No newline..." is at least that long.
1077 case '\\':
1078 if (len < 12 || memcmp(line, "\\ ", 2))
1079 return -1;
1080 break;
1083 if (oldlines || newlines)
1084 return -1;
1085 fragment->leading = leading;
1086 fragment->trailing = trailing;
1089 * If a fragment ends with an incomplete line, we failed to include
1090 * it in the above loop because we hit oldlines == newlines == 0
1091 * before seeing it.
1093 if (12 < size && !memcmp(line, "\\ ", 2))
1094 offset += linelen(line, size);
1096 patch->lines_added += added;
1097 patch->lines_deleted += deleted;
1099 if (0 < patch->is_new && oldlines)
1100 return error("new file depends on old contents");
1101 if (0 < patch->is_delete && newlines)
1102 return error("deleted file still has contents");
1103 return offset;
1106 static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
1108 unsigned long offset = 0;
1109 unsigned long oldlines = 0, newlines = 0, context = 0;
1110 struct fragment **fragp = &patch->fragments;
1112 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1113 struct fragment *fragment;
1114 int len;
1116 fragment = xcalloc(1, sizeof(*fragment));
1117 len = parse_fragment(line, size, patch, fragment);
1118 if (len <= 0)
1119 die("corrupt patch at line %d", linenr);
1120 fragment->patch = line;
1121 fragment->size = len;
1122 oldlines += fragment->oldlines;
1123 newlines += fragment->newlines;
1124 context += fragment->leading + fragment->trailing;
1126 *fragp = fragment;
1127 fragp = &fragment->next;
1129 offset += len;
1130 line += len;
1131 size -= len;
1135 * If something was removed (i.e. we have old-lines) it cannot
1136 * be creation, and if something was added it cannot be
1137 * deletion. However, the reverse is not true; --unified=0
1138 * patches that only add are not necessarily creation even
1139 * though they do not have any old lines, and ones that only
1140 * delete are not necessarily deletion.
1142 * Unfortunately, a real creation/deletion patch do _not_ have
1143 * any context line by definition, so we cannot safely tell it
1144 * apart with --unified=0 insanity. At least if the patch has
1145 * more than one hunk it is not creation or deletion.
1147 if (patch->is_new < 0 &&
1148 (oldlines || (patch->fragments && patch->fragments->next)))
1149 patch->is_new = 0;
1150 if (patch->is_delete < 0 &&
1151 (newlines || (patch->fragments && patch->fragments->next)))
1152 patch->is_delete = 0;
1154 if (0 < patch->is_new && oldlines)
1155 die("new file %s depends on old contents", patch->new_name);
1156 if (0 < patch->is_delete && newlines)
1157 die("deleted file %s still has contents", patch->old_name);
1158 if (!patch->is_delete && !newlines && context)
1159 fprintf(stderr, "** warning: file %s becomes empty but "
1160 "is not deleted\n", patch->new_name);
1162 return offset;
1165 static inline int metadata_changes(struct patch *patch)
1167 return patch->is_rename > 0 ||
1168 patch->is_copy > 0 ||
1169 patch->is_new > 0 ||
1170 patch->is_delete ||
1171 (patch->old_mode && patch->new_mode &&
1172 patch->old_mode != patch->new_mode);
1175 static char *inflate_it(const void *data, unsigned long size,
1176 unsigned long inflated_size)
1178 z_stream stream;
1179 void *out;
1180 int st;
1182 memset(&stream, 0, sizeof(stream));
1184 stream.next_in = (unsigned char *)data;
1185 stream.avail_in = size;
1186 stream.next_out = out = xmalloc(inflated_size);
1187 stream.avail_out = inflated_size;
1188 inflateInit(&stream);
1189 st = inflate(&stream, Z_FINISH);
1190 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1191 free(out);
1192 return NULL;
1194 return out;
1197 static struct fragment *parse_binary_hunk(char **buf_p,
1198 unsigned long *sz_p,
1199 int *status_p,
1200 int *used_p)
1203 * Expect a line that begins with binary patch method ("literal"
1204 * or "delta"), followed by the length of data before deflating.
1205 * a sequence of 'length-byte' followed by base-85 encoded data
1206 * should follow, terminated by a newline.
1208 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1209 * and we would limit the patch line to 66 characters,
1210 * so one line can fit up to 13 groups that would decode
1211 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1212 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1214 int llen, used;
1215 unsigned long size = *sz_p;
1216 char *buffer = *buf_p;
1217 int patch_method;
1218 unsigned long origlen;
1219 char *data = NULL;
1220 int hunk_size = 0;
1221 struct fragment *frag;
1223 llen = linelen(buffer, size);
1224 used = llen;
1226 *status_p = 0;
1228 if (!prefixcmp(buffer, "delta ")) {
1229 patch_method = BINARY_DELTA_DEFLATED;
1230 origlen = strtoul(buffer + 6, NULL, 10);
1232 else if (!prefixcmp(buffer, "literal ")) {
1233 patch_method = BINARY_LITERAL_DEFLATED;
1234 origlen = strtoul(buffer + 8, NULL, 10);
1236 else
1237 return NULL;
1239 linenr++;
1240 buffer += llen;
1241 while (1) {
1242 int byte_length, max_byte_length, newsize;
1243 llen = linelen(buffer, size);
1244 used += llen;
1245 linenr++;
1246 if (llen == 1) {
1247 /* consume the blank line */
1248 buffer++;
1249 size--;
1250 break;
1253 * Minimum line is "A00000\n" which is 7-byte long,
1254 * and the line length must be multiple of 5 plus 2.
1256 if ((llen < 7) || (llen-2) % 5)
1257 goto corrupt;
1258 max_byte_length = (llen - 2) / 5 * 4;
1259 byte_length = *buffer;
1260 if ('A' <= byte_length && byte_length <= 'Z')
1261 byte_length = byte_length - 'A' + 1;
1262 else if ('a' <= byte_length && byte_length <= 'z')
1263 byte_length = byte_length - 'a' + 27;
1264 else
1265 goto corrupt;
1266 /* if the input length was not multiple of 4, we would
1267 * have filler at the end but the filler should never
1268 * exceed 3 bytes
1270 if (max_byte_length < byte_length ||
1271 byte_length <= max_byte_length - 4)
1272 goto corrupt;
1273 newsize = hunk_size + byte_length;
1274 data = xrealloc(data, newsize);
1275 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1276 goto corrupt;
1277 hunk_size = newsize;
1278 buffer += llen;
1279 size -= llen;
1282 frag = xcalloc(1, sizeof(*frag));
1283 frag->patch = inflate_it(data, hunk_size, origlen);
1284 if (!frag->patch)
1285 goto corrupt;
1286 free(data);
1287 frag->size = origlen;
1288 *buf_p = buffer;
1289 *sz_p = size;
1290 *used_p = used;
1291 frag->binary_patch_method = patch_method;
1292 return frag;
1294 corrupt:
1295 free(data);
1296 *status_p = -1;
1297 error("corrupt binary patch at line %d: %.*s",
1298 linenr-1, llen-1, buffer);
1299 return NULL;
1302 static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1305 * We have read "GIT binary patch\n"; what follows is a line
1306 * that says the patch method (currently, either "literal" or
1307 * "delta") and the length of data before deflating; a
1308 * sequence of 'length-byte' followed by base-85 encoded data
1309 * follows.
1311 * When a binary patch is reversible, there is another binary
1312 * hunk in the same format, starting with patch method (either
1313 * "literal" or "delta") with the length of data, and a sequence
1314 * of length-byte + base-85 encoded data, terminated with another
1315 * empty line. This data, when applied to the postimage, produces
1316 * the preimage.
1318 struct fragment *forward;
1319 struct fragment *reverse;
1320 int status;
1321 int used, used_1;
1323 forward = parse_binary_hunk(&buffer, &size, &status, &used);
1324 if (!forward && !status)
1325 /* there has to be one hunk (forward hunk) */
1326 return error("unrecognized binary patch at line %d", linenr-1);
1327 if (status)
1328 /* otherwise we already gave an error message */
1329 return status;
1331 reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1332 if (reverse)
1333 used += used_1;
1334 else if (status) {
1336 * Not having reverse hunk is not an error, but having
1337 * a corrupt reverse hunk is.
1339 free((void*) forward->patch);
1340 free(forward);
1341 return status;
1343 forward->next = reverse;
1344 patch->fragments = forward;
1345 patch->is_binary = 1;
1346 return used;
1349 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
1351 int hdrsize, patchsize;
1352 int offset = find_header(buffer, size, &hdrsize, patch);
1354 if (offset < 0)
1355 return offset;
1357 patch->ws_rule = whitespace_rule(patch->new_name
1358 ? patch->new_name
1359 : patch->old_name);
1361 patchsize = parse_single_patch(buffer + offset + hdrsize,
1362 size - offset - hdrsize, patch);
1364 if (!patchsize) {
1365 static const char *binhdr[] = {
1366 "Binary files ",
1367 "Files ",
1368 NULL,
1370 static const char git_binary[] = "GIT binary patch\n";
1371 int i;
1372 int hd = hdrsize + offset;
1373 unsigned long llen = linelen(buffer + hd, size - hd);
1375 if (llen == sizeof(git_binary) - 1 &&
1376 !memcmp(git_binary, buffer + hd, llen)) {
1377 int used;
1378 linenr++;
1379 used = parse_binary(buffer + hd + llen,
1380 size - hd - llen, patch);
1381 if (used)
1382 patchsize = used + llen;
1383 else
1384 patchsize = 0;
1386 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
1387 for (i = 0; binhdr[i]; i++) {
1388 int len = strlen(binhdr[i]);
1389 if (len < size - hd &&
1390 !memcmp(binhdr[i], buffer + hd, len)) {
1391 linenr++;
1392 patch->is_binary = 1;
1393 patchsize = llen;
1394 break;
1399 /* Empty patch cannot be applied if it is a text patch
1400 * without metadata change. A binary patch appears
1401 * empty to us here.
1403 if ((apply || check) &&
1404 (!patch->is_binary && !metadata_changes(patch)))
1405 die("patch with only garbage at line %d", linenr);
1408 return offset + hdrsize + patchsize;
1411 #define swap(a,b) myswap((a),(b),sizeof(a))
1413 #define myswap(a, b, size) do { \
1414 unsigned char mytmp[size]; \
1415 memcpy(mytmp, &a, size); \
1416 memcpy(&a, &b, size); \
1417 memcpy(&b, mytmp, size); \
1418 } while (0)
1420 static void reverse_patches(struct patch *p)
1422 for (; p; p = p->next) {
1423 struct fragment *frag = p->fragments;
1425 swap(p->new_name, p->old_name);
1426 swap(p->new_mode, p->old_mode);
1427 swap(p->is_new, p->is_delete);
1428 swap(p->lines_added, p->lines_deleted);
1429 swap(p->old_sha1_prefix, p->new_sha1_prefix);
1431 for (; frag; frag = frag->next) {
1432 swap(frag->newpos, frag->oldpos);
1433 swap(frag->newlines, frag->oldlines);
1438 static const char pluses[] =
1439 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1440 static const char minuses[]=
1441 "----------------------------------------------------------------------";
1443 static void show_stats(struct patch *patch)
1445 struct strbuf qname;
1446 char *cp = patch->new_name ? patch->new_name : patch->old_name;
1447 int max, add, del;
1449 strbuf_init(&qname, 0);
1450 quote_c_style(cp, &qname, NULL, 0);
1453 * "scale" the filename
1455 max = max_len;
1456 if (max > 50)
1457 max = 50;
1459 if (qname.len > max) {
1460 cp = strchr(qname.buf + qname.len + 3 - max, '/');
1461 if (!cp)
1462 cp = qname.buf + qname.len + 3 - max;
1463 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
1466 if (patch->is_binary) {
1467 printf(" %-*s | Bin\n", max, qname.buf);
1468 strbuf_release(&qname);
1469 return;
1472 printf(" %-*s |", max, qname.buf);
1473 strbuf_release(&qname);
1476 * scale the add/delete
1478 max = max + max_change > 70 ? 70 - max : max_change;
1479 add = patch->lines_added;
1480 del = patch->lines_deleted;
1482 if (max_change > 0) {
1483 int total = ((add + del) * max + max_change / 2) / max_change;
1484 add = (add * max + max_change / 2) / max_change;
1485 del = total - add;
1487 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
1488 add, pluses, del, minuses);
1491 static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
1493 switch (st->st_mode & S_IFMT) {
1494 case S_IFLNK:
1495 strbuf_grow(buf, st->st_size);
1496 if (readlink(path, buf->buf, st->st_size) != st->st_size)
1497 return -1;
1498 strbuf_setlen(buf, st->st_size);
1499 return 0;
1500 case S_IFREG:
1501 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
1502 return error("unable to open or read %s", path);
1503 convert_to_git(path, buf->buf, buf->len, buf, 0);
1504 return 0;
1505 default:
1506 return -1;
1510 static void update_pre_post_images(struct image *preimage,
1511 struct image *postimage,
1512 char *buf,
1513 size_t len)
1515 int i, ctx;
1516 char *new, *old, *fixed;
1517 struct image fixed_preimage;
1520 * Update the preimage with whitespace fixes. Note that we
1521 * are not losing preimage->buf -- apply_one_fragment() will
1522 * free "oldlines".
1524 prepare_image(&fixed_preimage, buf, len, 1);
1525 assert(fixed_preimage.nr == preimage->nr);
1526 for (i = 0; i < preimage->nr; i++)
1527 fixed_preimage.line[i].flag = preimage->line[i].flag;
1528 free(preimage->line_allocated);
1529 *preimage = fixed_preimage;
1532 * Adjust the common context lines in postimage, in place.
1533 * This is possible because whitespace fixing does not make
1534 * the string grow.
1536 new = old = postimage->buf;
1537 fixed = preimage->buf;
1538 for (i = ctx = 0; i < postimage->nr; i++) {
1539 size_t len = postimage->line[i].len;
1540 if (!(postimage->line[i].flag & LINE_COMMON)) {
1541 /* an added line -- no counterparts in preimage */
1542 memmove(new, old, len);
1543 old += len;
1544 new += len;
1545 continue;
1548 /* a common context -- skip it in the original postimage */
1549 old += len;
1551 /* and find the corresponding one in the fixed preimage */
1552 while (ctx < preimage->nr &&
1553 !(preimage->line[ctx].flag & LINE_COMMON)) {
1554 fixed += preimage->line[ctx].len;
1555 ctx++;
1557 if (preimage->nr <= ctx)
1558 die("oops");
1560 /* and copy it in, while fixing the line length */
1561 len = preimage->line[ctx].len;
1562 memcpy(new, fixed, len);
1563 new += len;
1564 fixed += len;
1565 postimage->line[i].len = len;
1566 ctx++;
1569 /* Fix the length of the whole thing */
1570 postimage->len = new - postimage->buf;
1573 static int match_fragment(struct image *img,
1574 struct image *preimage,
1575 struct image *postimage,
1576 unsigned long try,
1577 int try_lno,
1578 unsigned ws_rule,
1579 int match_beginning, int match_end)
1581 int i;
1582 char *fixed_buf, *buf, *orig, *target;
1584 if (preimage->nr + try_lno > img->nr)
1585 return 0;
1587 if (match_beginning && try_lno)
1588 return 0;
1590 if (match_end && preimage->nr + try_lno != img->nr)
1591 return 0;
1593 /* Quick hash check */
1594 for (i = 0; i < preimage->nr; i++)
1595 if (preimage->line[i].hash != img->line[try_lno + i].hash)
1596 return 0;
1599 * Do we have an exact match? If we were told to match
1600 * at the end, size must be exactly at try+fragsize,
1601 * otherwise try+fragsize must be still within the preimage,
1602 * and either case, the old piece should match the preimage
1603 * exactly.
1605 if ((match_end
1606 ? (try + preimage->len == img->len)
1607 : (try + preimage->len <= img->len)) &&
1608 !memcmp(img->buf + try, preimage->buf, preimage->len))
1609 return 1;
1611 if (ws_error_action != correct_ws_error)
1612 return 0;
1615 * The hunk does not apply byte-by-byte, but the hash says
1616 * it might with whitespace fuzz.
1618 fixed_buf = xmalloc(preimage->len + 1);
1619 buf = fixed_buf;
1620 orig = preimage->buf;
1621 target = img->buf + try;
1622 for (i = 0; i < preimage->nr; i++) {
1623 size_t fixlen; /* length after fixing the preimage */
1624 size_t oldlen = preimage->line[i].len;
1625 size_t tgtlen = img->line[try_lno + i].len;
1626 size_t tgtfixlen; /* length after fixing the target line */
1627 char tgtfixbuf[1024], *tgtfix;
1628 int match;
1630 /* Try fixing the line in the preimage */
1631 fixlen = ws_fix_copy(buf, orig, oldlen, ws_rule, NULL);
1633 /* Try fixing the line in the target */
1634 if (sizeof(tgtfixbuf) < tgtlen)
1635 tgtfix = tgtfixbuf;
1636 else
1637 tgtfix = xmalloc(tgtlen);
1638 tgtfixlen = ws_fix_copy(tgtfix, target, tgtlen, ws_rule, NULL);
1641 * If they match, either the preimage was based on
1642 * a version before our tree fixed whitespace breakage,
1643 * or we are lacking a whitespace-fix patch the tree
1644 * the preimage was based on already had (i.e. target
1645 * has whitespace breakage, the preimage doesn't).
1646 * In either case, we are fixing the whitespace breakages
1647 * so we might as well take the fix together with their
1648 * real change.
1650 match = (tgtfixlen == fixlen && !memcmp(tgtfix, buf, fixlen));
1652 if (tgtfix != tgtfixbuf)
1653 free(tgtfix);
1654 if (!match)
1655 goto unmatch_exit;
1657 orig += oldlen;
1658 buf += fixlen;
1659 target += tgtlen;
1663 * Yes, the preimage is based on an older version that still
1664 * has whitespace breakages unfixed, and fixing them makes the
1665 * hunk match. Update the context lines in the postimage.
1667 update_pre_post_images(preimage, postimage,
1668 fixed_buf, buf - fixed_buf);
1669 return 1;
1671 unmatch_exit:
1672 free(fixed_buf);
1673 return 0;
1676 static int find_pos(struct image *img,
1677 struct image *preimage,
1678 struct image *postimage,
1679 int line,
1680 unsigned ws_rule,
1681 int match_beginning, int match_end)
1683 int i;
1684 unsigned long backwards, forwards, try;
1685 int backwards_lno, forwards_lno, try_lno;
1687 if (preimage->nr > img->nr)
1688 return -1;
1691 * If match_begining or match_end is specified, there is no
1692 * point starting from a wrong line that will never match and
1693 * wander around and wait for a match at the specified end.
1695 if (match_beginning)
1696 line = 0;
1697 else if (match_end)
1698 line = img->nr - preimage->nr;
1700 if (line > img->nr)
1701 line = img->nr;
1703 try = 0;
1704 for (i = 0; i < line; i++)
1705 try += img->line[i].len;
1708 * There's probably some smart way to do this, but I'll leave
1709 * that to the smart and beautiful people. I'm simple and stupid.
1711 backwards = try;
1712 backwards_lno = line;
1713 forwards = try;
1714 forwards_lno = line;
1715 try_lno = line;
1717 for (i = 0; ; i++) {
1718 if (match_fragment(img, preimage, postimage,
1719 try, try_lno, ws_rule,
1720 match_beginning, match_end))
1721 return try_lno;
1723 again:
1724 if (backwards_lno == 0 && forwards_lno == img->nr)
1725 break;
1727 if (i & 1) {
1728 if (backwards_lno == 0) {
1729 i++;
1730 goto again;
1732 backwards_lno--;
1733 backwards -= img->line[backwards_lno].len;
1734 try = backwards;
1735 try_lno = backwards_lno;
1736 } else {
1737 if (forwards_lno == img->nr) {
1738 i++;
1739 goto again;
1741 forwards += img->line[forwards_lno].len;
1742 forwards_lno++;
1743 try = forwards;
1744 try_lno = forwards_lno;
1748 return -1;
1751 static void remove_first_line(struct image *img)
1753 img->buf += img->line[0].len;
1754 img->len -= img->line[0].len;
1755 img->line++;
1756 img->nr--;
1759 static void remove_last_line(struct image *img)
1761 img->len -= img->line[--img->nr].len;
1764 static void update_image(struct image *img,
1765 int applied_pos,
1766 struct image *preimage,
1767 struct image *postimage)
1770 * remove the copy of preimage at offset in img
1771 * and replace it with postimage
1773 int i, nr;
1774 size_t remove_count, insert_count, applied_at = 0;
1775 char *result;
1777 for (i = 0; i < applied_pos; i++)
1778 applied_at += img->line[i].len;
1780 remove_count = 0;
1781 for (i = 0; i < preimage->nr; i++)
1782 remove_count += img->line[applied_pos + i].len;
1783 insert_count = postimage->len;
1785 /* Adjust the contents */
1786 result = xmalloc(img->len + insert_count - remove_count + 1);
1787 memcpy(result, img->buf, applied_at);
1788 memcpy(result + applied_at, postimage->buf, postimage->len);
1789 memcpy(result + applied_at + postimage->len,
1790 img->buf + (applied_at + remove_count),
1791 img->len - (applied_at + remove_count));
1792 free(img->buf);
1793 img->buf = result;
1794 img->len += insert_count - remove_count;
1795 result[img->len] = '\0';
1797 /* Adjust the line table */
1798 nr = img->nr + postimage->nr - preimage->nr;
1799 if (preimage->nr < postimage->nr) {
1801 * NOTE: this knows that we never call remove_first_line()
1802 * on anything other than pre/post image.
1804 img->line = xrealloc(img->line, nr * sizeof(*img->line));
1805 img->line_allocated = img->line;
1807 if (preimage->nr != postimage->nr)
1808 memmove(img->line + applied_pos + postimage->nr,
1809 img->line + applied_pos + preimage->nr,
1810 (img->nr - (applied_pos + preimage->nr)) *
1811 sizeof(*img->line));
1812 memcpy(img->line + applied_pos,
1813 postimage->line,
1814 postimage->nr * sizeof(*img->line));
1815 img->nr = nr;
1818 static int apply_one_fragment(struct image *img, struct fragment *frag,
1819 int inaccurate_eof, unsigned ws_rule)
1821 int match_beginning, match_end;
1822 const char *patch = frag->patch;
1823 int size = frag->size;
1824 char *old, *new, *oldlines, *newlines;
1825 int new_blank_lines_at_end = 0;
1826 unsigned long leading, trailing;
1827 int pos, applied_pos;
1828 struct image preimage;
1829 struct image postimage;
1831 memset(&preimage, 0, sizeof(preimage));
1832 memset(&postimage, 0, sizeof(postimage));
1833 oldlines = xmalloc(size);
1834 newlines = xmalloc(size);
1836 old = oldlines;
1837 new = newlines;
1838 while (size > 0) {
1839 char first;
1840 int len = linelen(patch, size);
1841 int plen, added;
1842 int added_blank_line = 0;
1844 if (!len)
1845 break;
1848 * "plen" is how much of the line we should use for
1849 * the actual patch data. Normally we just remove the
1850 * first character on the line, but if the line is
1851 * followed by "\ No newline", then we also remove the
1852 * last one (which is the newline, of course).
1854 plen = len - 1;
1855 if (len < size && patch[len] == '\\')
1856 plen--;
1857 first = *patch;
1858 if (apply_in_reverse) {
1859 if (first == '-')
1860 first = '+';
1861 else if (first == '+')
1862 first = '-';
1865 switch (first) {
1866 case '\n':
1867 /* Newer GNU diff, empty context line */
1868 if (plen < 0)
1869 /* ... followed by '\No newline'; nothing */
1870 break;
1871 *old++ = '\n';
1872 *new++ = '\n';
1873 add_line_info(&preimage, "\n", 1, LINE_COMMON);
1874 add_line_info(&postimage, "\n", 1, LINE_COMMON);
1875 break;
1876 case ' ':
1877 case '-':
1878 memcpy(old, patch + 1, plen);
1879 add_line_info(&preimage, old, plen,
1880 (first == ' ' ? LINE_COMMON : 0));
1881 old += plen;
1882 if (first == '-')
1883 break;
1884 /* Fall-through for ' ' */
1885 case '+':
1886 /* --no-add does not add new lines */
1887 if (first == '+' && no_add)
1888 break;
1890 if (first != '+' ||
1891 !whitespace_error ||
1892 ws_error_action != correct_ws_error) {
1893 memcpy(new, patch + 1, plen);
1894 added = plen;
1896 else {
1897 added = ws_fix_copy(new, patch + 1, plen, ws_rule, &applied_after_fixing_ws);
1899 add_line_info(&postimage, new, added,
1900 (first == '+' ? 0 : LINE_COMMON));
1901 new += added;
1902 if (first == '+' &&
1903 added == 1 && new[-1] == '\n')
1904 added_blank_line = 1;
1905 break;
1906 case '@': case '\\':
1907 /* Ignore it, we already handled it */
1908 break;
1909 default:
1910 if (apply_verbosely)
1911 error("invalid start of line: '%c'", first);
1912 return -1;
1914 if (added_blank_line)
1915 new_blank_lines_at_end++;
1916 else
1917 new_blank_lines_at_end = 0;
1918 patch += len;
1919 size -= len;
1921 if (inaccurate_eof &&
1922 old > oldlines && old[-1] == '\n' &&
1923 new > newlines && new[-1] == '\n') {
1924 old--;
1925 new--;
1928 leading = frag->leading;
1929 trailing = frag->trailing;
1932 * A hunk to change lines at the beginning would begin with
1933 * @@ -1,L +N,M @@
1935 * And a hunk to add to an empty file would begin with
1936 * @@ -0,0 +N,M @@
1938 * In other words, a hunk that is (frag->oldpos <= 1) with or
1939 * without leading context must match at the beginning.
1941 match_beginning = frag->oldpos <= 1;
1944 * A hunk without trailing lines must match at the end.
1945 * However, we simply cannot tell if a hunk must match end
1946 * from the lack of trailing lines if the patch was generated
1947 * with unidiff without any context.
1949 match_end = !unidiff_zero && !trailing;
1951 pos = frag->newpos ? (frag->newpos - 1) : 0;
1952 preimage.buf = oldlines;
1953 preimage.len = old - oldlines;
1954 postimage.buf = newlines;
1955 postimage.len = new - newlines;
1956 preimage.line = preimage.line_allocated;
1957 postimage.line = postimage.line_allocated;
1959 for (;;) {
1961 applied_pos = find_pos(img, &preimage, &postimage, pos,
1962 ws_rule, match_beginning, match_end);
1964 if (applied_pos >= 0)
1965 break;
1967 /* Am I at my context limits? */
1968 if ((leading <= p_context) && (trailing <= p_context))
1969 break;
1970 if (match_beginning || match_end) {
1971 match_beginning = match_end = 0;
1972 continue;
1976 * Reduce the number of context lines; reduce both
1977 * leading and trailing if they are equal otherwise
1978 * just reduce the larger context.
1980 if (leading >= trailing) {
1981 remove_first_line(&preimage);
1982 remove_first_line(&postimage);
1983 pos--;
1984 leading--;
1986 if (trailing > leading) {
1987 remove_last_line(&preimage);
1988 remove_last_line(&postimage);
1989 trailing--;
1993 if (applied_pos >= 0) {
1994 if (ws_error_action == correct_ws_error &&
1995 new_blank_lines_at_end &&
1996 postimage.nr + applied_pos == img->nr) {
1998 * If the patch application adds blank lines
1999 * at the end, and if the patch applies at the
2000 * end of the image, remove those added blank
2001 * lines.
2003 while (new_blank_lines_at_end--)
2004 remove_last_line(&postimage);
2008 * Warn if it was necessary to reduce the number
2009 * of context lines.
2011 if ((leading != frag->leading) ||
2012 (trailing != frag->trailing))
2013 fprintf(stderr, "Context reduced to (%ld/%ld)"
2014 " to apply fragment at %d\n",
2015 leading, trailing, applied_pos+1);
2016 update_image(img, applied_pos, &preimage, &postimage);
2017 } else {
2018 if (apply_verbosely)
2019 error("while searching for:\n%.*s",
2020 (int)(old - oldlines), oldlines);
2023 free(oldlines);
2024 free(newlines);
2025 free(preimage.line_allocated);
2026 free(postimage.line_allocated);
2028 return (applied_pos < 0);
2031 static int apply_binary_fragment(struct image *img, struct patch *patch)
2033 struct fragment *fragment = patch->fragments;
2034 unsigned long len;
2035 void *dst;
2037 /* Binary patch is irreversible without the optional second hunk */
2038 if (apply_in_reverse) {
2039 if (!fragment->next)
2040 return error("cannot reverse-apply a binary patch "
2041 "without the reverse hunk to '%s'",
2042 patch->new_name
2043 ? patch->new_name : patch->old_name);
2044 fragment = fragment->next;
2046 switch (fragment->binary_patch_method) {
2047 case BINARY_DELTA_DEFLATED:
2048 dst = patch_delta(img->buf, img->len, fragment->patch,
2049 fragment->size, &len);
2050 if (!dst)
2051 return -1;
2052 clear_image(img);
2053 img->buf = dst;
2054 img->len = len;
2055 return 0;
2056 case BINARY_LITERAL_DEFLATED:
2057 clear_image(img);
2058 img->len = fragment->size;
2059 img->buf = xmalloc(img->len+1);
2060 memcpy(img->buf, fragment->patch, img->len);
2061 img->buf[img->len] = '\0';
2062 return 0;
2064 return -1;
2067 static int apply_binary(struct image *img, struct patch *patch)
2069 const char *name = patch->old_name ? patch->old_name : patch->new_name;
2070 unsigned char sha1[20];
2073 * For safety, we require patch index line to contain
2074 * full 40-byte textual SHA1 for old and new, at least for now.
2076 if (strlen(patch->old_sha1_prefix) != 40 ||
2077 strlen(patch->new_sha1_prefix) != 40 ||
2078 get_sha1_hex(patch->old_sha1_prefix, sha1) ||
2079 get_sha1_hex(patch->new_sha1_prefix, sha1))
2080 return error("cannot apply binary patch to '%s' "
2081 "without full index line", name);
2083 if (patch->old_name) {
2085 * See if the old one matches what the patch
2086 * applies to.
2088 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2089 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
2090 return error("the patch applies to '%s' (%s), "
2091 "which does not match the "
2092 "current contents.",
2093 name, sha1_to_hex(sha1));
2095 else {
2096 /* Otherwise, the old one must be empty. */
2097 if (img->len)
2098 return error("the patch applies to an empty "
2099 "'%s' but it is not empty", name);
2102 get_sha1_hex(patch->new_sha1_prefix, sha1);
2103 if (is_null_sha1(sha1)) {
2104 clear_image(img);
2105 return 0; /* deletion patch */
2108 if (has_sha1_file(sha1)) {
2109 /* We already have the postimage */
2110 enum object_type type;
2111 unsigned long size;
2112 char *result;
2114 result = read_sha1_file(sha1, &type, &size);
2115 if (!result)
2116 return error("the necessary postimage %s for "
2117 "'%s' cannot be read",
2118 patch->new_sha1_prefix, name);
2119 clear_image(img);
2120 img->buf = result;
2121 img->len = size;
2122 } else {
2124 * We have verified buf matches the preimage;
2125 * apply the patch data to it, which is stored
2126 * in the patch->fragments->{patch,size}.
2128 if (apply_binary_fragment(img, patch))
2129 return error("binary patch does not apply to '%s'",
2130 name);
2132 /* verify that the result matches */
2133 hash_sha1_file(img->buf, img->len, blob_type, sha1);
2134 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
2135 return error("binary patch to '%s' creates incorrect result (expecting %s, got %s)",
2136 name, patch->new_sha1_prefix, sha1_to_hex(sha1));
2139 return 0;
2142 static int apply_fragments(struct image *img, struct patch *patch)
2144 struct fragment *frag = patch->fragments;
2145 const char *name = patch->old_name ? patch->old_name : patch->new_name;
2146 unsigned ws_rule = patch->ws_rule;
2147 unsigned inaccurate_eof = patch->inaccurate_eof;
2149 if (patch->is_binary)
2150 return apply_binary(img, patch);
2152 while (frag) {
2153 if (apply_one_fragment(img, frag, inaccurate_eof, ws_rule)) {
2154 error("patch failed: %s:%ld", name, frag->oldpos);
2155 if (!apply_with_reject)
2156 return -1;
2157 frag->rejected = 1;
2159 frag = frag->next;
2161 return 0;
2164 static int read_file_or_gitlink(struct cache_entry *ce, struct strbuf *buf)
2166 if (!ce)
2167 return 0;
2169 if (S_ISGITLINK(ce->ce_mode)) {
2170 strbuf_grow(buf, 100);
2171 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(ce->sha1));
2172 } else {
2173 enum object_type type;
2174 unsigned long sz;
2175 char *result;
2177 result = read_sha1_file(ce->sha1, &type, &sz);
2178 if (!result)
2179 return -1;
2180 /* XXX read_sha1_file NUL-terminates */
2181 strbuf_attach(buf, result, sz, sz + 1);
2183 return 0;
2186 static struct patch *in_fn_table(const char *name)
2188 struct path_list_item *item;
2190 if (name == NULL)
2191 return NULL;
2193 item = path_list_lookup(name, &fn_table);
2194 if (item != NULL)
2195 return (struct patch *)item->util;
2197 return NULL;
2200 static void add_to_fn_table(struct patch *patch)
2202 struct path_list_item *item;
2205 * Always add new_name unless patch is a deletion
2206 * This should cover the cases for normal diffs,
2207 * file creations and copies
2209 if (patch->new_name != NULL) {
2210 item = path_list_insert(patch->new_name, &fn_table);
2211 item->util = patch;
2215 * store a failure on rename/deletion cases because
2216 * later chunks shouldn't patch old names
2218 if ((patch->new_name == NULL) || (patch->is_rename)) {
2219 item = path_list_insert(patch->old_name, &fn_table);
2220 item->util = (struct patch *) -1;
2224 static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce)
2226 struct strbuf buf;
2227 struct image image;
2228 size_t len;
2229 char *img;
2230 struct patch *tpatch;
2232 strbuf_init(&buf, 0);
2234 if ((tpatch = in_fn_table(patch->old_name)) != NULL) {
2235 if (tpatch == (struct patch *) -1) {
2236 return error("patch %s has been renamed/deleted",
2237 patch->old_name);
2239 /* We have a patched copy in memory use that */
2240 strbuf_add(&buf, tpatch->result, tpatch->resultsize);
2241 } else if (cached) {
2242 if (read_file_or_gitlink(ce, &buf))
2243 return error("read of %s failed", patch->old_name);
2244 } else if (patch->old_name) {
2245 if (S_ISGITLINK(patch->old_mode)) {
2246 if (ce) {
2247 read_file_or_gitlink(ce, &buf);
2248 } else {
2250 * There is no way to apply subproject
2251 * patch without looking at the index.
2253 patch->fragments = NULL;
2255 } else {
2256 if (read_old_data(st, patch->old_name, &buf))
2257 return error("read of %s failed", patch->old_name);
2261 img = strbuf_detach(&buf, &len);
2262 prepare_image(&image, img, len, !patch->is_binary);
2264 if (apply_fragments(&image, patch) < 0)
2265 return -1; /* note with --reject this succeeds. */
2266 patch->result = image.buf;
2267 patch->resultsize = image.len;
2268 add_to_fn_table(patch);
2269 free(image.line_allocated);
2271 if (0 < patch->is_delete && patch->resultsize)
2272 return error("removal patch leaves file contents");
2274 return 0;
2277 static int check_to_create_blob(const char *new_name, int ok_if_exists)
2279 struct stat nst;
2280 if (!lstat(new_name, &nst)) {
2281 if (S_ISDIR(nst.st_mode) || ok_if_exists)
2282 return 0;
2284 * A leading component of new_name might be a symlink
2285 * that is going to be removed with this patch, but
2286 * still pointing at somewhere that has the path.
2287 * In such a case, path "new_name" does not exist as
2288 * far as git is concerned.
2290 if (has_symlink_leading_path(strlen(new_name), new_name))
2291 return 0;
2293 return error("%s: already exists in working directory", new_name);
2295 else if ((errno != ENOENT) && (errno != ENOTDIR))
2296 return error("%s: %s", new_name, strerror(errno));
2297 return 0;
2300 static int verify_index_match(struct cache_entry *ce, struct stat *st)
2302 if (S_ISGITLINK(ce->ce_mode)) {
2303 if (!S_ISDIR(st->st_mode))
2304 return -1;
2305 return 0;
2307 return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID);
2310 static int check_preimage(struct patch *patch, struct cache_entry **ce, struct stat *st)
2312 const char *old_name = patch->old_name;
2313 struct patch *tpatch;
2314 int stat_ret = 0;
2315 unsigned st_mode = 0;
2318 * Make sure that we do not have local modifications from the
2319 * index when we are looking at the index. Also make sure
2320 * we have the preimage file to be patched in the work tree,
2321 * unless --cached, which tells git to apply only in the index.
2323 if (!old_name)
2324 return 0;
2326 assert(patch->is_new <= 0);
2327 if ((tpatch = in_fn_table(old_name)) != NULL) {
2328 if (tpatch == (struct patch *) -1) {
2329 return error("%s: has been deleted/renamed", old_name);
2331 st_mode = tpatch->new_mode;
2332 } else if (!cached) {
2333 stat_ret = lstat(old_name, st);
2334 if (stat_ret && errno != ENOENT)
2335 return error("%s: %s", old_name, strerror(errno));
2337 if (check_index && !tpatch) {
2338 int pos = cache_name_pos(old_name, strlen(old_name));
2339 if (pos < 0) {
2340 if (patch->is_new < 0)
2341 goto is_new;
2342 return error("%s: does not exist in index", old_name);
2344 *ce = active_cache[pos];
2345 if (stat_ret < 0) {
2346 struct checkout costate;
2347 /* checkout */
2348 costate.base_dir = "";
2349 costate.base_dir_len = 0;
2350 costate.force = 0;
2351 costate.quiet = 0;
2352 costate.not_new = 0;
2353 costate.refresh_cache = 1;
2354 if (checkout_entry(*ce, &costate, NULL) ||
2355 lstat(old_name, st))
2356 return -1;
2358 if (!cached && verify_index_match(*ce, st))
2359 return error("%s: does not match index", old_name);
2360 if (cached)
2361 st_mode = (*ce)->ce_mode;
2362 } else if (stat_ret < 0) {
2363 if (patch->is_new < 0)
2364 goto is_new;
2365 return error("%s: %s", old_name, strerror(errno));
2368 if (!cached)
2369 st_mode = ce_mode_from_stat(*ce, st->st_mode);
2371 if (patch->is_new < 0)
2372 patch->is_new = 0;
2373 if (!patch->old_mode)
2374 patch->old_mode = st_mode;
2375 if ((st_mode ^ patch->old_mode) & S_IFMT)
2376 return error("%s: wrong type", old_name);
2377 if (st_mode != patch->old_mode)
2378 fprintf(stderr, "warning: %s has type %o, expected %o\n",
2379 old_name, st_mode, patch->old_mode);
2380 return 0;
2382 is_new:
2383 patch->is_new = 1;
2384 patch->is_delete = 0;
2385 patch->old_name = NULL;
2386 return 0;
2389 static int check_patch(struct patch *patch)
2391 struct stat st;
2392 const char *old_name = patch->old_name;
2393 const char *new_name = patch->new_name;
2394 const char *name = old_name ? old_name : new_name;
2395 struct cache_entry *ce = NULL;
2396 int ok_if_exists;
2397 int status;
2399 patch->rejected = 1; /* we will drop this after we succeed */
2401 status = check_preimage(patch, &ce, &st);
2402 if (status)
2403 return status;
2404 old_name = patch->old_name;
2406 if (in_fn_table(new_name) == (struct patch *) -1)
2408 * A type-change diff is always split into a patch to
2409 * delete old, immediately followed by a patch to
2410 * create new (see diff.c::run_diff()); in such a case
2411 * it is Ok that the entry to be deleted by the
2412 * previous patch is still in the working tree and in
2413 * the index.
2415 ok_if_exists = 1;
2416 else
2417 ok_if_exists = 0;
2419 if (new_name &&
2420 ((0 < patch->is_new) | (0 < patch->is_rename) | patch->is_copy)) {
2421 if (check_index &&
2422 cache_name_pos(new_name, strlen(new_name)) >= 0 &&
2423 !ok_if_exists)
2424 return error("%s: already exists in index", new_name);
2425 if (!cached) {
2426 int err = check_to_create_blob(new_name, ok_if_exists);
2427 if (err)
2428 return err;
2430 if (!patch->new_mode) {
2431 if (0 < patch->is_new)
2432 patch->new_mode = S_IFREG | 0644;
2433 else
2434 patch->new_mode = patch->old_mode;
2438 if (new_name && old_name) {
2439 int same = !strcmp(old_name, new_name);
2440 if (!patch->new_mode)
2441 patch->new_mode = patch->old_mode;
2442 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
2443 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
2444 patch->new_mode, new_name, patch->old_mode,
2445 same ? "" : " of ", same ? "" : old_name);
2448 if (apply_data(patch, &st, ce) < 0)
2449 return error("%s: patch does not apply", name);
2450 patch->rejected = 0;
2451 return 0;
2454 static int check_patch_list(struct patch *patch)
2456 int err = 0;
2458 while (patch) {
2459 if (apply_verbosely)
2460 say_patch_name(stderr,
2461 "Checking patch ", patch, "...\n");
2462 err |= check_patch(patch);
2463 patch = patch->next;
2465 return err;
2468 /* This function tries to read the sha1 from the current index */
2469 static int get_current_sha1(const char *path, unsigned char *sha1)
2471 int pos;
2473 if (read_cache() < 0)
2474 return -1;
2475 pos = cache_name_pos(path, strlen(path));
2476 if (pos < 0)
2477 return -1;
2478 hashcpy(sha1, active_cache[pos]->sha1);
2479 return 0;
2482 /* Build an index that contains the just the files needed for a 3way merge */
2483 static void build_fake_ancestor(struct patch *list, const char *filename)
2485 struct patch *patch;
2486 struct index_state result = { 0 };
2487 int fd;
2489 /* Once we start supporting the reverse patch, it may be
2490 * worth showing the new sha1 prefix, but until then...
2492 for (patch = list; patch; patch = patch->next) {
2493 const unsigned char *sha1_ptr;
2494 unsigned char sha1[20];
2495 struct cache_entry *ce;
2496 const char *name;
2498 name = patch->old_name ? patch->old_name : patch->new_name;
2499 if (0 < patch->is_new)
2500 continue;
2501 else if (get_sha1(patch->old_sha1_prefix, sha1))
2502 /* git diff has no index line for mode/type changes */
2503 if (!patch->lines_added && !patch->lines_deleted) {
2504 if (get_current_sha1(patch->new_name, sha1) ||
2505 get_current_sha1(patch->old_name, sha1))
2506 die("mode change for %s, which is not "
2507 "in current HEAD", name);
2508 sha1_ptr = sha1;
2509 } else
2510 die("sha1 information is lacking or useless "
2511 "(%s).", name);
2512 else
2513 sha1_ptr = sha1;
2515 ce = make_cache_entry(patch->old_mode, sha1_ptr, name, 0, 0);
2516 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))
2517 die ("Could not add %s to temporary index", name);
2520 fd = open(filename, O_WRONLY | O_CREAT, 0666);
2521 if (fd < 0 || write_index(&result, fd) || close(fd))
2522 die ("Could not write temporary index to %s", filename);
2524 discard_index(&result);
2527 static void stat_patch_list(struct patch *patch)
2529 int files, adds, dels;
2531 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
2532 files++;
2533 adds += patch->lines_added;
2534 dels += patch->lines_deleted;
2535 show_stats(patch);
2538 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
2541 static void numstat_patch_list(struct patch *patch)
2543 for ( ; patch; patch = patch->next) {
2544 const char *name;
2545 name = patch->new_name ? patch->new_name : patch->old_name;
2546 if (patch->is_binary)
2547 printf("-\t-\t");
2548 else
2549 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
2550 write_name_quoted(name, stdout, line_termination);
2554 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
2556 if (mode)
2557 printf(" %s mode %06o %s\n", newdelete, mode, name);
2558 else
2559 printf(" %s %s\n", newdelete, name);
2562 static void show_mode_change(struct patch *p, int show_name)
2564 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
2565 if (show_name)
2566 printf(" mode change %06o => %06o %s\n",
2567 p->old_mode, p->new_mode, p->new_name);
2568 else
2569 printf(" mode change %06o => %06o\n",
2570 p->old_mode, p->new_mode);
2574 static void show_rename_copy(struct patch *p)
2576 const char *renamecopy = p->is_rename ? "rename" : "copy";
2577 const char *old, *new;
2579 /* Find common prefix */
2580 old = p->old_name;
2581 new = p->new_name;
2582 while (1) {
2583 const char *slash_old, *slash_new;
2584 slash_old = strchr(old, '/');
2585 slash_new = strchr(new, '/');
2586 if (!slash_old ||
2587 !slash_new ||
2588 slash_old - old != slash_new - new ||
2589 memcmp(old, new, slash_new - new))
2590 break;
2591 old = slash_old + 1;
2592 new = slash_new + 1;
2594 /* p->old_name thru old is the common prefix, and old and new
2595 * through the end of names are renames
2597 if (old != p->old_name)
2598 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
2599 (int)(old - p->old_name), p->old_name,
2600 old, new, p->score);
2601 else
2602 printf(" %s %s => %s (%d%%)\n", renamecopy,
2603 p->old_name, p->new_name, p->score);
2604 show_mode_change(p, 0);
2607 static void summary_patch_list(struct patch *patch)
2609 struct patch *p;
2611 for (p = patch; p; p = p->next) {
2612 if (p->is_new)
2613 show_file_mode_name("create", p->new_mode, p->new_name);
2614 else if (p->is_delete)
2615 show_file_mode_name("delete", p->old_mode, p->old_name);
2616 else {
2617 if (p->is_rename || p->is_copy)
2618 show_rename_copy(p);
2619 else {
2620 if (p->score) {
2621 printf(" rewrite %s (%d%%)\n",
2622 p->new_name, p->score);
2623 show_mode_change(p, 0);
2625 else
2626 show_mode_change(p, 1);
2632 static void patch_stats(struct patch *patch)
2634 int lines = patch->lines_added + patch->lines_deleted;
2636 if (lines > max_change)
2637 max_change = lines;
2638 if (patch->old_name) {
2639 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
2640 if (!len)
2641 len = strlen(patch->old_name);
2642 if (len > max_len)
2643 max_len = len;
2645 if (patch->new_name) {
2646 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
2647 if (!len)
2648 len = strlen(patch->new_name);
2649 if (len > max_len)
2650 max_len = len;
2654 static void remove_file(struct patch *patch, int rmdir_empty)
2656 if (update_index) {
2657 if (remove_file_from_cache(patch->old_name) < 0)
2658 die("unable to remove %s from index", patch->old_name);
2660 if (!cached) {
2661 if (S_ISGITLINK(patch->old_mode)) {
2662 if (rmdir(patch->old_name))
2663 warning("unable to remove submodule %s",
2664 patch->old_name);
2665 } else if (!unlink(patch->old_name) && rmdir_empty) {
2666 char *name = xstrdup(patch->old_name);
2667 char *end = strrchr(name, '/');
2668 while (end) {
2669 *end = 0;
2670 if (rmdir(name))
2671 break;
2672 end = strrchr(name, '/');
2674 free(name);
2679 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
2681 struct stat st;
2682 struct cache_entry *ce;
2683 int namelen = strlen(path);
2684 unsigned ce_size = cache_entry_size(namelen);
2686 if (!update_index)
2687 return;
2689 ce = xcalloc(1, ce_size);
2690 memcpy(ce->name, path, namelen);
2691 ce->ce_mode = create_ce_mode(mode);
2692 ce->ce_flags = namelen;
2693 if (S_ISGITLINK(mode)) {
2694 const char *s = buf;
2696 if (get_sha1_hex(s + strlen("Subproject commit "), ce->sha1))
2697 die("corrupt patch for subproject %s", path);
2698 } else {
2699 if (!cached) {
2700 if (lstat(path, &st) < 0)
2701 die("unable to stat newly created file %s",
2702 path);
2703 fill_stat_cache_info(ce, &st);
2705 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
2706 die("unable to create backing store for newly created file %s", path);
2708 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
2709 die("unable to add cache entry for %s", path);
2712 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
2714 int fd;
2715 struct strbuf nbuf;
2717 if (S_ISGITLINK(mode)) {
2718 struct stat st;
2719 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
2720 return 0;
2721 return mkdir(path, 0777);
2724 if (has_symlinks && S_ISLNK(mode))
2725 /* Although buf:size is counted string, it also is NUL
2726 * terminated.
2728 return symlink(buf, path);
2730 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
2731 if (fd < 0)
2732 return -1;
2734 strbuf_init(&nbuf, 0);
2735 if (convert_to_working_tree(path, buf, size, &nbuf)) {
2736 size = nbuf.len;
2737 buf = nbuf.buf;
2739 write_or_die(fd, buf, size);
2740 strbuf_release(&nbuf);
2742 if (close(fd) < 0)
2743 die("closing file %s: %s", path, strerror(errno));
2744 return 0;
2748 * We optimistically assume that the directories exist,
2749 * which is true 99% of the time anyway. If they don't,
2750 * we create them and try again.
2752 static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
2754 if (cached)
2755 return;
2756 if (!try_create_file(path, mode, buf, size))
2757 return;
2759 if (errno == ENOENT) {
2760 if (safe_create_leading_directories(path))
2761 return;
2762 if (!try_create_file(path, mode, buf, size))
2763 return;
2766 if (errno == EEXIST || errno == EACCES) {
2767 /* We may be trying to create a file where a directory
2768 * used to be.
2770 struct stat st;
2771 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
2772 errno = EEXIST;
2775 if (errno == EEXIST) {
2776 unsigned int nr = getpid();
2778 for (;;) {
2779 const char *newpath;
2780 newpath = mkpath("%s~%u", path, nr);
2781 if (!try_create_file(newpath, mode, buf, size)) {
2782 if (!rename(newpath, path))
2783 return;
2784 unlink(newpath);
2785 break;
2787 if (errno != EEXIST)
2788 break;
2789 ++nr;
2792 die("unable to write file %s mode %o", path, mode);
2795 static void create_file(struct patch *patch)
2797 char *path = patch->new_name;
2798 unsigned mode = patch->new_mode;
2799 unsigned long size = patch->resultsize;
2800 char *buf = patch->result;
2802 if (!mode)
2803 mode = S_IFREG | 0644;
2804 create_one_file(path, mode, buf, size);
2805 add_index_file(path, mode, buf, size);
2808 /* phase zero is to remove, phase one is to create */
2809 static void write_out_one_result(struct patch *patch, int phase)
2811 if (patch->is_delete > 0) {
2812 if (phase == 0)
2813 remove_file(patch, 1);
2814 return;
2816 if (patch->is_new > 0 || patch->is_copy) {
2817 if (phase == 1)
2818 create_file(patch);
2819 return;
2822 * Rename or modification boils down to the same
2823 * thing: remove the old, write the new
2825 if (phase == 0)
2826 remove_file(patch, patch->is_rename);
2827 if (phase == 1)
2828 create_file(patch);
2831 static int write_out_one_reject(struct patch *patch)
2833 FILE *rej;
2834 char namebuf[PATH_MAX];
2835 struct fragment *frag;
2836 int cnt = 0;
2838 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
2839 if (!frag->rejected)
2840 continue;
2841 cnt++;
2844 if (!cnt) {
2845 if (apply_verbosely)
2846 say_patch_name(stderr,
2847 "Applied patch ", patch, " cleanly.\n");
2848 return 0;
2851 /* This should not happen, because a removal patch that leaves
2852 * contents are marked "rejected" at the patch level.
2854 if (!patch->new_name)
2855 die("internal error");
2857 /* Say this even without --verbose */
2858 say_patch_name(stderr, "Applying patch ", patch, " with");
2859 fprintf(stderr, " %d rejects...\n", cnt);
2861 cnt = strlen(patch->new_name);
2862 if (ARRAY_SIZE(namebuf) <= cnt + 5) {
2863 cnt = ARRAY_SIZE(namebuf) - 5;
2864 fprintf(stderr,
2865 "warning: truncating .rej filename to %.*s.rej",
2866 cnt - 1, patch->new_name);
2868 memcpy(namebuf, patch->new_name, cnt);
2869 memcpy(namebuf + cnt, ".rej", 5);
2871 rej = fopen(namebuf, "w");
2872 if (!rej)
2873 return error("cannot open %s: %s", namebuf, strerror(errno));
2875 /* Normal git tools never deal with .rej, so do not pretend
2876 * this is a git patch by saying --git nor give extended
2877 * headers. While at it, maybe please "kompare" that wants
2878 * the trailing TAB and some garbage at the end of line ;-).
2880 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
2881 patch->new_name, patch->new_name);
2882 for (cnt = 1, frag = patch->fragments;
2883 frag;
2884 cnt++, frag = frag->next) {
2885 if (!frag->rejected) {
2886 fprintf(stderr, "Hunk #%d applied cleanly.\n", cnt);
2887 continue;
2889 fprintf(stderr, "Rejected hunk #%d.\n", cnt);
2890 fprintf(rej, "%.*s", frag->size, frag->patch);
2891 if (frag->patch[frag->size-1] != '\n')
2892 fputc('\n', rej);
2894 fclose(rej);
2895 return -1;
2898 static int write_out_results(struct patch *list, int skipped_patch)
2900 int phase;
2901 int errs = 0;
2902 struct patch *l;
2904 if (!list && !skipped_patch)
2905 return error("No changes");
2907 for (phase = 0; phase < 2; phase++) {
2908 l = list;
2909 while (l) {
2910 if (l->rejected)
2911 errs = 1;
2912 else {
2913 write_out_one_result(l, phase);
2914 if (phase == 1 && write_out_one_reject(l))
2915 errs = 1;
2917 l = l->next;
2920 return errs;
2923 static struct lock_file lock_file;
2925 static struct excludes {
2926 struct excludes *next;
2927 const char *path;
2928 } *excludes;
2930 static int use_patch(struct patch *p)
2932 const char *pathname = p->new_name ? p->new_name : p->old_name;
2933 struct excludes *x = excludes;
2934 while (x) {
2935 if (fnmatch(x->path, pathname, 0) == 0)
2936 return 0;
2937 x = x->next;
2939 if (0 < prefix_length) {
2940 int pathlen = strlen(pathname);
2941 if (pathlen <= prefix_length ||
2942 memcmp(prefix, pathname, prefix_length))
2943 return 0;
2945 return 1;
2948 static void prefix_one(char **name)
2950 char *old_name = *name;
2951 if (!old_name)
2952 return;
2953 *name = xstrdup(prefix_filename(prefix, prefix_length, *name));
2954 free(old_name);
2957 static void prefix_patches(struct patch *p)
2959 if (!prefix || p->is_toplevel_relative)
2960 return;
2961 for ( ; p; p = p->next) {
2962 if (p->new_name == p->old_name) {
2963 char *prefixed = p->new_name;
2964 prefix_one(&prefixed);
2965 p->new_name = p->old_name = prefixed;
2967 else {
2968 prefix_one(&p->new_name);
2969 prefix_one(&p->old_name);
2974 static int apply_patch(int fd, const char *filename, int inaccurate_eof)
2976 size_t offset;
2977 struct strbuf buf;
2978 struct patch *list = NULL, **listp = &list;
2979 int skipped_patch = 0;
2981 /* FIXME - memory leak when using multiple patch files as inputs */
2982 memset(&fn_table, 0, sizeof(struct path_list));
2983 strbuf_init(&buf, 0);
2984 patch_input_file = filename;
2985 read_patch_file(&buf, fd);
2986 offset = 0;
2987 while (offset < buf.len) {
2988 struct patch *patch;
2989 int nr;
2991 patch = xcalloc(1, sizeof(*patch));
2992 patch->inaccurate_eof = inaccurate_eof;
2993 nr = parse_chunk(buf.buf + offset, buf.len - offset, patch);
2994 if (nr < 0)
2995 break;
2996 if (apply_in_reverse)
2997 reverse_patches(patch);
2998 if (prefix)
2999 prefix_patches(patch);
3000 if (use_patch(patch)) {
3001 patch_stats(patch);
3002 *listp = patch;
3003 listp = &patch->next;
3005 else {
3006 /* perhaps free it a bit better? */
3007 free(patch);
3008 skipped_patch++;
3010 offset += nr;
3013 if (whitespace_error && (ws_error_action == die_on_ws_error))
3014 apply = 0;
3016 update_index = check_index && apply;
3017 if (update_index && newfd < 0)
3018 newfd = hold_locked_index(&lock_file, 1);
3020 if (check_index) {
3021 if (read_cache() < 0)
3022 die("unable to read index file");
3025 if ((check || apply) &&
3026 check_patch_list(list) < 0 &&
3027 !apply_with_reject)
3028 exit(1);
3030 if (apply && write_out_results(list, skipped_patch))
3031 exit(1);
3033 if (fake_ancestor)
3034 build_fake_ancestor(list, fake_ancestor);
3036 if (diffstat)
3037 stat_patch_list(list);
3039 if (numstat)
3040 numstat_patch_list(list);
3042 if (summary)
3043 summary_patch_list(list);
3045 strbuf_release(&buf);
3046 return 0;
3049 static int git_apply_config(const char *var, const char *value, void *cb)
3051 if (!strcmp(var, "apply.whitespace"))
3052 return git_config_string(&apply_default_whitespace, var, value);
3053 return git_default_config(var, value, cb);
3057 int cmd_apply(int argc, const char **argv, const char *unused_prefix)
3059 int i;
3060 int read_stdin = 1;
3061 int inaccurate_eof = 0;
3062 int errs = 0;
3063 int is_not_gitdir;
3065 const char *whitespace_option = NULL;
3067 prefix = setup_git_directory_gently(&is_not_gitdir);
3068 prefix_length = prefix ? strlen(prefix) : 0;
3069 git_config(git_apply_config, NULL);
3070 if (apply_default_whitespace)
3071 parse_whitespace_option(apply_default_whitespace);
3073 for (i = 1; i < argc; i++) {
3074 const char *arg = argv[i];
3075 char *end;
3076 int fd;
3078 if (!strcmp(arg, "-")) {
3079 errs |= apply_patch(0, "<stdin>", inaccurate_eof);
3080 read_stdin = 0;
3081 continue;
3083 if (!prefixcmp(arg, "--exclude=")) {
3084 struct excludes *x = xmalloc(sizeof(*x));
3085 x->path = arg + 10;
3086 x->next = excludes;
3087 excludes = x;
3088 continue;
3090 if (!prefixcmp(arg, "-p")) {
3091 p_value = atoi(arg + 2);
3092 p_value_known = 1;
3093 continue;
3095 if (!strcmp(arg, "--no-add")) {
3096 no_add = 1;
3097 continue;
3099 if (!strcmp(arg, "--stat")) {
3100 apply = 0;
3101 diffstat = 1;
3102 continue;
3104 if (!strcmp(arg, "--allow-binary-replacement") ||
3105 !strcmp(arg, "--binary")) {
3106 continue; /* now no-op */
3108 if (!strcmp(arg, "--numstat")) {
3109 apply = 0;
3110 numstat = 1;
3111 continue;
3113 if (!strcmp(arg, "--summary")) {
3114 apply = 0;
3115 summary = 1;
3116 continue;
3118 if (!strcmp(arg, "--check")) {
3119 apply = 0;
3120 check = 1;
3121 continue;
3123 if (!strcmp(arg, "--index")) {
3124 if (is_not_gitdir)
3125 die("--index outside a repository");
3126 check_index = 1;
3127 continue;
3129 if (!strcmp(arg, "--cached")) {
3130 if (is_not_gitdir)
3131 die("--cached outside a repository");
3132 check_index = 1;
3133 cached = 1;
3134 continue;
3136 if (!strcmp(arg, "--apply")) {
3137 apply = 1;
3138 continue;
3140 if (!strcmp(arg, "--build-fake-ancestor")) {
3141 apply = 0;
3142 if (++i >= argc)
3143 die ("need a filename");
3144 fake_ancestor = argv[i];
3145 continue;
3147 if (!strcmp(arg, "-z")) {
3148 line_termination = 0;
3149 continue;
3151 if (!prefixcmp(arg, "-C")) {
3152 p_context = strtoul(arg + 2, &end, 0);
3153 if (*end != '\0')
3154 die("unrecognized context count '%s'", arg + 2);
3155 continue;
3157 if (!prefixcmp(arg, "--whitespace=")) {
3158 whitespace_option = arg + 13;
3159 parse_whitespace_option(arg + 13);
3160 continue;
3162 if (!strcmp(arg, "-R") || !strcmp(arg, "--reverse")) {
3163 apply_in_reverse = 1;
3164 continue;
3166 if (!strcmp(arg, "--unidiff-zero")) {
3167 unidiff_zero = 1;
3168 continue;
3170 if (!strcmp(arg, "--reject")) {
3171 apply = apply_with_reject = apply_verbosely = 1;
3172 continue;
3174 if (!strcmp(arg, "-v") || !strcmp(arg, "--verbose")) {
3175 apply_verbosely = 1;
3176 continue;
3178 if (!strcmp(arg, "--inaccurate-eof")) {
3179 inaccurate_eof = 1;
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, inaccurate_eof);
3191 close(fd);
3193 set_default_whitespace_mode(whitespace_option);
3194 if (read_stdin)
3195 errs |= apply_patch(0, "<stdin>", inaccurate_eof);
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;