Merge branch 'master' into lt/apply
[git/git.git] / builtin-apply.c
1 /*
2 * apply.c
3 *
4 * Copyright (C) Linus Torvalds, 2005
5 *
6 * This applies patches on top of some (arbitrary) version of the SCM.
7 *
8 */
9 #include <fnmatch.h>
10 #include "cache.h"
11 #include "quote.h"
12 #include "blob.h"
13 #include "delta.h"
14 #include "builtin.h"
15
16 // --check turns on checking that the working tree matches the
17 // files that are being modified, but doesn't apply the patch
18 // --stat does just a diffstat, and doesn't actually apply
19 // --numstat does numeric diffstat, and doesn't actually apply
20 // --index-info shows the old and new index info for paths if available.
21 // --index updates the cache as well.
22 // --cached updates only the cache without ever touching the working tree.
23 //
24 static const char *prefix;
25 static int prefix_length = -1;
26 static int newfd = -1;
27
28 static int p_value = 1;
29 static int allow_binary_replacement = 0;
30 static int check_index = 0;
31 static int write_index = 0;
32 static int cached = 0;
33 static int diffstat = 0;
34 static int numstat = 0;
35 static int summary = 0;
36 static int check = 0;
37 static int apply = 1;
38 static int no_add = 0;
39 static int show_index_info = 0;
40 static int line_termination = '\n';
41 static unsigned long p_context = -1;
42 static const char apply_usage[] =
43 "git-apply [--stat] [--numstat] [--summary] [--check] [--index] [--cached] [--apply] [--no-add] [--index-info] [--allow-binary-replacement] [-z] [-pNUM] [-CNUM] [--whitespace=<nowarn|warn|error|error-all|strip>] <patch>...";
44
45 static enum whitespace_eol {
46 nowarn_whitespace,
47 warn_on_whitespace,
48 error_on_whitespace,
49 strip_whitespace,
50 } new_whitespace = warn_on_whitespace;
51 static int whitespace_error = 0;
52 static int squelch_whitespace_errors = 5;
53 static int applied_after_stripping = 0;
54 static const char *patch_input_file = NULL;
55
56 static void parse_whitespace_option(const char *option)
57 {
58 if (!option) {
59 new_whitespace = warn_on_whitespace;
60 return;
61 }
62 if (!strcmp(option, "warn")) {
63 new_whitespace = warn_on_whitespace;
64 return;
65 }
66 if (!strcmp(option, "nowarn")) {
67 new_whitespace = nowarn_whitespace;
68 return;
69 }
70 if (!strcmp(option, "error")) {
71 new_whitespace = error_on_whitespace;
72 return;
73 }
74 if (!strcmp(option, "error-all")) {
75 new_whitespace = error_on_whitespace;
76 squelch_whitespace_errors = 0;
77 return;
78 }
79 if (!strcmp(option, "strip")) {
80 new_whitespace = strip_whitespace;
81 return;
82 }
83 die("unrecognized whitespace option '%s'", option);
84 }
85
86 static void set_default_whitespace_mode(const char *whitespace_option)
87 {
88 if (!whitespace_option && !apply_default_whitespace) {
89 new_whitespace = (apply
90 ? warn_on_whitespace
91 : nowarn_whitespace);
92 }
93 }
94
95 /*
96 * For "diff-stat" like behaviour, we keep track of the biggest change
97 * we've seen, and the longest filename. That allows us to do simple
98 * scaling.
99 */
100 static int max_change, max_len;
101
102 /*
103 * Various "current state", notably line numbers and what
104 * file (and how) we're patching right now.. The "is_xxxx"
105 * things are flags, where -1 means "don't know yet".
106 */
107 static int linenr = 1;
108
109 struct fragment {
110 unsigned long leading, trailing;
111 unsigned long oldpos, oldlines;
112 unsigned long newpos, newlines;
113 const char *patch;
114 int size;
115 struct fragment *next;
116 };
117
118 struct patch {
119 char *new_name, *old_name, *def_name;
120 unsigned int old_mode, new_mode;
121 int is_rename, is_copy, is_new, is_delete, is_binary;
122 #define BINARY_DELTA_DEFLATED 1
123 #define BINARY_LITERAL_DEFLATED 2
124 unsigned long deflate_origlen;
125 int lines_added, lines_deleted;
126 int score;
127 struct fragment *fragments;
128 char *result;
129 unsigned long resultsize;
130 char old_sha1_prefix[41];
131 char new_sha1_prefix[41];
132 struct patch *next;
133 };
134
135 #define CHUNKSIZE (8192)
136 #define SLOP (16)
137
138 static void *read_patch_file(int fd, unsigned long *sizep)
139 {
140 unsigned long size = 0, alloc = CHUNKSIZE;
141 void *buffer = xmalloc(alloc);
142
143 for (;;) {
144 int nr = alloc - size;
145 if (nr < 1024) {
146 alloc += CHUNKSIZE;
147 buffer = xrealloc(buffer, alloc);
148 nr = alloc - size;
149 }
150 nr = xread(fd, buffer + size, nr);
151 if (!nr)
152 break;
153 if (nr < 0)
154 die("git-apply: read returned %s", strerror(errno));
155 size += nr;
156 }
157 *sizep = size;
158
159 /*
160 * Make sure that we have some slop in the buffer
161 * so that we can do speculative "memcmp" etc, and
162 * see to it that it is NUL-filled.
163 */
164 if (alloc < size + SLOP)
165 buffer = xrealloc(buffer, size + SLOP);
166 memset(buffer + size, 0, SLOP);
167 return buffer;
168 }
169
170 static unsigned long linelen(const char *buffer, unsigned long size)
171 {
172 unsigned long len = 0;
173 while (size--) {
174 len++;
175 if (*buffer++ == '\n')
176 break;
177 }
178 return len;
179 }
180
181 static int is_dev_null(const char *str)
182 {
183 return !memcmp("/dev/null", str, 9) && isspace(str[9]);
184 }
185
186 #define TERM_SPACE 1
187 #define TERM_TAB 2
188
189 static int name_terminate(const char *name, int namelen, int c, int terminate)
190 {
191 if (c == ' ' && !(terminate & TERM_SPACE))
192 return 0;
193 if (c == '\t' && !(terminate & TERM_TAB))
194 return 0;
195
196 return 1;
197 }
198
199 static char * find_name(const char *line, char *def, int p_value, int terminate)
200 {
201 int len;
202 const char *start = line;
203 char *name;
204
205 if (*line == '"') {
206 /* Proposed "new-style" GNU patch/diff format; see
207 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
208 */
209 name = unquote_c_style(line, NULL);
210 if (name) {
211 char *cp = name;
212 while (p_value) {
213 cp = strchr(name, '/');
214 if (!cp)
215 break;
216 cp++;
217 p_value--;
218 }
219 if (cp) {
220 /* name can later be freed, so we need
221 * to memmove, not just return cp
222 */
223 memmove(name, cp, strlen(cp) + 1);
224 free(def);
225 return name;
226 }
227 else {
228 free(name);
229 name = NULL;
230 }
231 }
232 }
233
234 for (;;) {
235 char c = *line;
236
237 if (isspace(c)) {
238 if (c == '\n')
239 break;
240 if (name_terminate(start, line-start, c, terminate))
241 break;
242 }
243 line++;
244 if (c == '/' && !--p_value)
245 start = line;
246 }
247 if (!start)
248 return def;
249 len = line - start;
250 if (!len)
251 return def;
252
253 /*
254 * Generally we prefer the shorter name, especially
255 * if the other one is just a variation of that with
256 * something else tacked on to the end (ie "file.orig"
257 * or "file~").
258 */
259 if (def) {
260 int deflen = strlen(def);
261 if (deflen < len && !strncmp(start, def, deflen))
262 return def;
263 }
264
265 name = xmalloc(len + 1);
266 memcpy(name, start, len);
267 name[len] = 0;
268 free(def);
269 return name;
270 }
271
272 /*
273 * Get the name etc info from the --/+++ lines of a traditional patch header
274 *
275 * NOTE! This hardcodes "-p1" behaviour in filename detection.
276 *
277 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
278 * files, we can happily check the index for a match, but for creating a
279 * new file we should try to match whatever "patch" does. I have no idea.
280 */
281 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
282 {
283 char *name;
284
285 first += 4; // skip "--- "
286 second += 4; // skip "+++ "
287 if (is_dev_null(first)) {
288 patch->is_new = 1;
289 patch->is_delete = 0;
290 name = find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB);
291 patch->new_name = name;
292 } else if (is_dev_null(second)) {
293 patch->is_new = 0;
294 patch->is_delete = 1;
295 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
296 patch->old_name = name;
297 } else {
298 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
299 name = find_name(second, name, p_value, TERM_SPACE | TERM_TAB);
300 patch->old_name = patch->new_name = name;
301 }
302 if (!name)
303 die("unable to find filename in patch at line %d", linenr);
304 }
305
306 static int gitdiff_hdrend(const char *line, struct patch *patch)
307 {
308 return -1;
309 }
310
311 /*
312 * We're anal about diff header consistency, to make
313 * sure that we don't end up having strange ambiguous
314 * patches floating around.
315 *
316 * As a result, gitdiff_{old|new}name() will check
317 * their names against any previous information, just
318 * to make sure..
319 */
320 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
321 {
322 if (!orig_name && !isnull)
323 return find_name(line, NULL, 1, 0);
324
325 if (orig_name) {
326 int len;
327 const char *name;
328 char *another;
329 name = orig_name;
330 len = strlen(name);
331 if (isnull)
332 die("git-apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
333 another = find_name(line, NULL, 1, 0);
334 if (!another || memcmp(another, name, len))
335 die("git-apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
336 free(another);
337 return orig_name;
338 }
339 else {
340 /* expect "/dev/null" */
341 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
342 die("git-apply: bad git-diff - expected /dev/null on line %d", linenr);
343 return NULL;
344 }
345 }
346
347 static int gitdiff_oldname(const char *line, struct patch *patch)
348 {
349 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
350 return 0;
351 }
352
353 static int gitdiff_newname(const char *line, struct patch *patch)
354 {
355 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
356 return 0;
357 }
358
359 static int gitdiff_oldmode(const char *line, struct patch *patch)
360 {
361 patch->old_mode = strtoul(line, NULL, 8);
362 return 0;
363 }
364
365 static int gitdiff_newmode(const char *line, struct patch *patch)
366 {
367 patch->new_mode = strtoul(line, NULL, 8);
368 return 0;
369 }
370
371 static int gitdiff_delete(const char *line, struct patch *patch)
372 {
373 patch->is_delete = 1;
374 patch->old_name = patch->def_name;
375 return gitdiff_oldmode(line, patch);
376 }
377
378 static int gitdiff_newfile(const char *line, struct patch *patch)
379 {
380 patch->is_new = 1;
381 patch->new_name = patch->def_name;
382 return gitdiff_newmode(line, patch);
383 }
384
385 static int gitdiff_copysrc(const char *line, struct patch *patch)
386 {
387 patch->is_copy = 1;
388 patch->old_name = find_name(line, NULL, 0, 0);
389 return 0;
390 }
391
392 static int gitdiff_copydst(const char *line, struct patch *patch)
393 {
394 patch->is_copy = 1;
395 patch->new_name = find_name(line, NULL, 0, 0);
396 return 0;
397 }
398
399 static int gitdiff_renamesrc(const char *line, struct patch *patch)
400 {
401 patch->is_rename = 1;
402 patch->old_name = find_name(line, NULL, 0, 0);
403 return 0;
404 }
405
406 static int gitdiff_renamedst(const char *line, struct patch *patch)
407 {
408 patch->is_rename = 1;
409 patch->new_name = find_name(line, NULL, 0, 0);
410 return 0;
411 }
412
413 static int gitdiff_similarity(const char *line, struct patch *patch)
414 {
415 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
416 patch->score = 0;
417 return 0;
418 }
419
420 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
421 {
422 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
423 patch->score = 0;
424 return 0;
425 }
426
427 static int gitdiff_index(const char *line, struct patch *patch)
428 {
429 /* index line is N hexadecimal, "..", N hexadecimal,
430 * and optional space with octal mode.
431 */
432 const char *ptr, *eol;
433 int len;
434
435 ptr = strchr(line, '.');
436 if (!ptr || ptr[1] != '.' || 40 < ptr - line)
437 return 0;
438 len = ptr - line;
439 memcpy(patch->old_sha1_prefix, line, len);
440 patch->old_sha1_prefix[len] = 0;
441
442 line = ptr + 2;
443 ptr = strchr(line, ' ');
444 eol = strchr(line, '\n');
445
446 if (!ptr || eol < ptr)
447 ptr = eol;
448 len = ptr - line;
449
450 if (40 < len)
451 return 0;
452 memcpy(patch->new_sha1_prefix, line, len);
453 patch->new_sha1_prefix[len] = 0;
454 if (*ptr == ' ')
455 patch->new_mode = patch->old_mode = strtoul(ptr+1, NULL, 8);
456 return 0;
457 }
458
459 /*
460 * This is normal for a diff that doesn't change anything: we'll fall through
461 * into the next diff. Tell the parser to break out.
462 */
463 static int gitdiff_unrecognized(const char *line, struct patch *patch)
464 {
465 return -1;
466 }
467
468 static const char *stop_at_slash(const char *line, int llen)
469 {
470 int i;
471
472 for (i = 0; i < llen; i++) {
473 int ch = line[i];
474 if (ch == '/')
475 return line + i;
476 }
477 return NULL;
478 }
479
480 /* This is to extract the same name that appears on "diff --git"
481 * line. We do not find and return anything if it is a rename
482 * patch, and it is OK because we will find the name elsewhere.
483 * We need to reliably find name only when it is mode-change only,
484 * creation or deletion of an empty file. In any of these cases,
485 * both sides are the same name under a/ and b/ respectively.
486 */
487 static char *git_header_name(char *line, int llen)
488 {
489 int len;
490 const char *name;
491 const char *second = NULL;
492
493 line += strlen("diff --git ");
494 llen -= strlen("diff --git ");
495
496 if (*line == '"') {
497 const char *cp;
498 char *first = unquote_c_style(line, &second);
499 if (!first)
500 return NULL;
501
502 /* advance to the first slash */
503 cp = stop_at_slash(first, strlen(first));
504 if (!cp || cp == first) {
505 /* we do not accept absolute paths */
506 free_first_and_fail:
507 free(first);
508 return NULL;
509 }
510 len = strlen(cp+1);
511 memmove(first, cp+1, len+1); /* including NUL */
512
513 /* second points at one past closing dq of name.
514 * find the second name.
515 */
516 while ((second < line + llen) && isspace(*second))
517 second++;
518
519 if (line + llen <= second)
520 goto free_first_and_fail;
521 if (*second == '"') {
522 char *sp = unquote_c_style(second, NULL);
523 if (!sp)
524 goto free_first_and_fail;
525 cp = stop_at_slash(sp, strlen(sp));
526 if (!cp || cp == sp) {
527 free_both_and_fail:
528 free(sp);
529 goto free_first_and_fail;
530 }
531 /* They must match, otherwise ignore */
532 if (strcmp(cp+1, first))
533 goto free_both_and_fail;
534 free(sp);
535 return first;
536 }
537
538 /* unquoted second */
539 cp = stop_at_slash(second, line + llen - second);
540 if (!cp || cp == second)
541 goto free_first_and_fail;
542 cp++;
543 if (line + llen - cp != len + 1 ||
544 memcmp(first, cp, len))
545 goto free_first_and_fail;
546 return first;
547 }
548
549 /* unquoted first name */
550 name = stop_at_slash(line, llen);
551 if (!name || name == line)
552 return NULL;
553
554 name++;
555
556 /* since the first name is unquoted, a dq if exists must be
557 * the beginning of the second name.
558 */
559 for (second = name; second < line + llen; second++) {
560 if (*second == '"') {
561 const char *cp = second;
562 const char *np;
563 char *sp = unquote_c_style(second, NULL);
564
565 if (!sp)
566 return NULL;
567 np = stop_at_slash(sp, strlen(sp));
568 if (!np || np == sp) {
569 free_second_and_fail:
570 free(sp);
571 return NULL;
572 }
573 np++;
574 len = strlen(np);
575 if (len < cp - name &&
576 !strncmp(np, name, len) &&
577 isspace(name[len])) {
578 /* Good */
579 memmove(sp, np, len + 1);
580 return sp;
581 }
582 goto free_second_and_fail;
583 }
584 }
585
586 /*
587 * Accept a name only if it shows up twice, exactly the same
588 * form.
589 */
590 for (len = 0 ; ; len++) {
591 char c = name[len];
592
593 switch (c) {
594 default:
595 continue;
596 case '\n':
597 return NULL;
598 case '\t': case ' ':
599 second = name+len;
600 for (;;) {
601 char c = *second++;
602 if (c == '\n')
603 return NULL;
604 if (c == '/')
605 break;
606 }
607 if (second[len] == '\n' && !memcmp(name, second, len)) {
608 char *ret = xmalloc(len + 1);
609 memcpy(ret, name, len);
610 ret[len] = 0;
611 return ret;
612 }
613 }
614 }
615 return NULL;
616 }
617
618 /* Verify that we recognize the lines following a git header */
619 static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
620 {
621 unsigned long offset;
622
623 /* A git diff has explicit new/delete information, so we don't guess */
624 patch->is_new = 0;
625 patch->is_delete = 0;
626
627 /*
628 * Some things may not have the old name in the
629 * rest of the headers anywhere (pure mode changes,
630 * or removing or adding empty files), so we get
631 * the default name from the header.
632 */
633 patch->def_name = git_header_name(line, len);
634
635 line += len;
636 size -= len;
637 linenr++;
638 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
639 static const struct opentry {
640 const char *str;
641 int (*fn)(const char *, struct patch *);
642 } optable[] = {
643 { "@@ -", gitdiff_hdrend },
644 { "--- ", gitdiff_oldname },
645 { "+++ ", gitdiff_newname },
646 { "old mode ", gitdiff_oldmode },
647 { "new mode ", gitdiff_newmode },
648 { "deleted file mode ", gitdiff_delete },
649 { "new file mode ", gitdiff_newfile },
650 { "copy from ", gitdiff_copysrc },
651 { "copy to ", gitdiff_copydst },
652 { "rename old ", gitdiff_renamesrc },
653 { "rename new ", gitdiff_renamedst },
654 { "rename from ", gitdiff_renamesrc },
655 { "rename to ", gitdiff_renamedst },
656 { "similarity index ", gitdiff_similarity },
657 { "dissimilarity index ", gitdiff_dissimilarity },
658 { "index ", gitdiff_index },
659 { "", gitdiff_unrecognized },
660 };
661 int i;
662
663 len = linelen(line, size);
664 if (!len || line[len-1] != '\n')
665 break;
666 for (i = 0; i < ARRAY_SIZE(optable); i++) {
667 const struct opentry *p = optable + i;
668 int oplen = strlen(p->str);
669 if (len < oplen || memcmp(p->str, line, oplen))
670 continue;
671 if (p->fn(line + oplen, patch) < 0)
672 return offset;
673 break;
674 }
675 }
676
677 return offset;
678 }
679
680 static int parse_num(const char *line, unsigned long *p)
681 {
682 char *ptr;
683
684 if (!isdigit(*line))
685 return 0;
686 *p = strtoul(line, &ptr, 10);
687 return ptr - line;
688 }
689
690 static int parse_range(const char *line, int len, int offset, const char *expect,
691 unsigned long *p1, unsigned long *p2)
692 {
693 int digits, ex;
694
695 if (offset < 0 || offset >= len)
696 return -1;
697 line += offset;
698 len -= offset;
699
700 digits = parse_num(line, p1);
701 if (!digits)
702 return -1;
703
704 offset += digits;
705 line += digits;
706 len -= digits;
707
708 *p2 = 1;
709 if (*line == ',') {
710 digits = parse_num(line+1, p2);
711 if (!digits)
712 return -1;
713
714 offset += digits+1;
715 line += digits+1;
716 len -= digits+1;
717 }
718
719 ex = strlen(expect);
720 if (ex > len)
721 return -1;
722 if (memcmp(line, expect, ex))
723 return -1;
724
725 return offset + ex;
726 }
727
728 /*
729 * Parse a unified diff fragment header of the
730 * form "@@ -a,b +c,d @@"
731 */
732 static int parse_fragment_header(char *line, int len, struct fragment *fragment)
733 {
734 int offset;
735
736 if (!len || line[len-1] != '\n')
737 return -1;
738
739 /* Figure out the number of lines in a fragment */
740 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
741 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
742
743 return offset;
744 }
745
746 static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
747 {
748 unsigned long offset, len;
749
750 patch->is_rename = patch->is_copy = 0;
751 patch->is_new = patch->is_delete = -1;
752 patch->old_mode = patch->new_mode = 0;
753 patch->old_name = patch->new_name = NULL;
754 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
755 unsigned long nextlen;
756
757 len = linelen(line, size);
758 if (!len)
759 break;
760
761 /* Testing this early allows us to take a few shortcuts.. */
762 if (len < 6)
763 continue;
764
765 /*
766 * Make sure we don't find any unconnected patch fragmants.
767 * That's a sign that we didn't find a header, and that a
768 * patch has become corrupted/broken up.
769 */
770 if (!memcmp("@@ -", line, 4)) {
771 struct fragment dummy;
772 if (parse_fragment_header(line, len, &dummy) < 0)
773 continue;
774 error("patch fragment without header at line %d: %.*s", linenr, (int)len-1, line);
775 }
776
777 if (size < len + 6)
778 break;
779
780 /*
781 * Git patch? It might not have a real patch, just a rename
782 * or mode change, so we handle that specially
783 */
784 if (!memcmp("diff --git ", line, 11)) {
785 int git_hdr_len = parse_git_header(line, len, size, patch);
786 if (git_hdr_len <= len)
787 continue;
788 if (!patch->old_name && !patch->new_name) {
789 if (!patch->def_name)
790 die("git diff header lacks filename information (line %d)", linenr);
791 patch->old_name = patch->new_name = patch->def_name;
792 }
793 *hdrsize = git_hdr_len;
794 return offset;
795 }
796
797 /** --- followed by +++ ? */
798 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
799 continue;
800
801 /*
802 * We only accept unified patches, so we want it to
803 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
804 * minimum
805 */
806 nextlen = linelen(line + len, size - len);
807 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
808 continue;
809
810 /* Ok, we'll consider it a patch */
811 parse_traditional_patch(line, line+len, patch);
812 *hdrsize = len + nextlen;
813 linenr += 2;
814 return offset;
815 }
816 return -1;
817 }
818
819 /*
820 * Parse a unified diff. Note that this really needs
821 * to parse each fragment separately, since the only
822 * way to know the difference between a "---" that is
823 * part of a patch, and a "---" that starts the next
824 * patch is to look at the line counts..
825 */
826 static int parse_fragment(char *line, unsigned long size, struct patch *patch, struct fragment *fragment)
827 {
828 int added, deleted;
829 int len = linelen(line, size), offset;
830 unsigned long oldlines, newlines;
831 unsigned long leading, trailing;
832
833 offset = parse_fragment_header(line, len, fragment);
834 if (offset < 0)
835 return -1;
836 oldlines = fragment->oldlines;
837 newlines = fragment->newlines;
838 leading = 0;
839 trailing = 0;
840
841 if (patch->is_new < 0) {
842 patch->is_new = !oldlines;
843 if (!oldlines)
844 patch->old_name = NULL;
845 }
846 if (patch->is_delete < 0) {
847 patch->is_delete = !newlines;
848 if (!newlines)
849 patch->new_name = NULL;
850 }
851
852 if (patch->is_new && oldlines)
853 return error("new file depends on old contents");
854 if (patch->is_delete != !newlines) {
855 if (newlines)
856 return error("deleted file still has contents");
857 fprintf(stderr, "** warning: file %s becomes empty but is not deleted\n", patch->new_name);
858 }
859
860 /* Parse the thing.. */
861 line += len;
862 size -= len;
863 linenr++;
864 added = deleted = 0;
865 for (offset = len; size > 0; offset += len, size -= len, line += len, linenr++) {
866 if (!oldlines && !newlines)
867 break;
868 len = linelen(line, size);
869 if (!len || line[len-1] != '\n')
870 return -1;
871 switch (*line) {
872 default:
873 return -1;
874 case ' ':
875 oldlines--;
876 newlines--;
877 if (!deleted && !added)
878 leading++;
879 trailing++;
880 break;
881 case '-':
882 deleted++;
883 oldlines--;
884 trailing = 0;
885 break;
886 case '+':
887 /*
888 * We know len is at least two, since we have a '+' and
889 * we checked that the last character was a '\n' above.
890 * That is, an addition of an empty line would check
891 * the '+' here. Sneaky...
892 */
893 if ((new_whitespace != nowarn_whitespace) &&
894 isspace(line[len-2])) {
895 whitespace_error++;
896 if (squelch_whitespace_errors &&
897 squelch_whitespace_errors <
898 whitespace_error)
899 ;
900 else {
901 fprintf(stderr, "Adds trailing whitespace.\n%s:%d:%.*s\n",
902 patch_input_file,
903 linenr, len-2, line+1);
904 }
905 }
906 added++;
907 newlines--;
908 trailing = 0;
909 break;
910
911 /* We allow "\ No newline at end of file". Depending
912 * on locale settings when the patch was produced we
913 * don't know what this line looks like. The only
914 * thing we do know is that it begins with "\ ".
915 * Checking for 12 is just for sanity check -- any
916 * l10n of "\ No newline..." is at least that long.
917 */
918 case '\\':
919 if (len < 12 || memcmp(line, "\\ ", 2))
920 return -1;
921 break;
922 }
923 }
924 if (oldlines || newlines)
925 return -1;
926 fragment->leading = leading;
927 fragment->trailing = trailing;
928
929 /* If a fragment ends with an incomplete line, we failed to include
930 * it in the above loop because we hit oldlines == newlines == 0
931 * before seeing it.
932 */
933 if (12 < size && !memcmp(line, "\\ ", 2))
934 offset += linelen(line, size);
935
936 patch->lines_added += added;
937 patch->lines_deleted += deleted;
938 return offset;
939 }
940
941 static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
942 {
943 unsigned long offset = 0;
944 struct fragment **fragp = &patch->fragments;
945
946 while (size > 4 && !memcmp(line, "@@ -", 4)) {
947 struct fragment *fragment;
948 int len;
949
950 fragment = xcalloc(1, sizeof(*fragment));
951 len = parse_fragment(line, size, patch, fragment);
952 if (len <= 0)
953 die("corrupt patch at line %d", linenr);
954
955 fragment->patch = line;
956 fragment->size = len;
957
958 *fragp = fragment;
959 fragp = &fragment->next;
960
961 offset += len;
962 line += len;
963 size -= len;
964 }
965 return offset;
966 }
967
968 static inline int metadata_changes(struct patch *patch)
969 {
970 return patch->is_rename > 0 ||
971 patch->is_copy > 0 ||
972 patch->is_new > 0 ||
973 patch->is_delete ||
974 (patch->old_mode && patch->new_mode &&
975 patch->old_mode != patch->new_mode);
976 }
977
978 static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
979 {
980 /* We have read "GIT binary patch\n"; what follows is a line
981 * that says the patch method (currently, either "deflated
982 * literal" or "deflated delta") and the length of data before
983 * deflating; a sequence of 'length-byte' followed by base-85
984 * encoded data follows.
985 *
986 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
987 * and we would limit the patch line to 66 characters,
988 * so one line can fit up to 13 groups that would decode
989 * to 52 bytes max. The length byte 'A'-'Z' corresponds
990 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
991 * The end of binary is signalled with an empty line.
992 */
993 int llen, used;
994 struct fragment *fragment;
995 char *data = NULL;
996
997 patch->fragments = fragment = xcalloc(1, sizeof(*fragment));
998
999 /* Grab the type of patch */
1000 llen = linelen(buffer, size);
1001 used = llen;
1002 linenr++;
1003
1004 if (!strncmp(buffer, "delta ", 6)) {
1005 patch->is_binary = BINARY_DELTA_DEFLATED;
1006 patch->deflate_origlen = strtoul(buffer + 6, NULL, 10);
1007 }
1008 else if (!strncmp(buffer, "literal ", 8)) {
1009 patch->is_binary = BINARY_LITERAL_DEFLATED;
1010 patch->deflate_origlen = strtoul(buffer + 8, NULL, 10);
1011 }
1012 else
1013 return error("unrecognized binary patch at line %d: %.*s",
1014 linenr-1, llen-1, buffer);
1015 buffer += llen;
1016 while (1) {
1017 int byte_length, max_byte_length, newsize;
1018 llen = linelen(buffer, size);
1019 used += llen;
1020 linenr++;
1021 if (llen == 1)
1022 break;
1023 /* Minimum line is "A00000\n" which is 7-byte long,
1024 * and the line length must be multiple of 5 plus 2.
1025 */
1026 if ((llen < 7) || (llen-2) % 5)
1027 goto corrupt;
1028 max_byte_length = (llen - 2) / 5 * 4;
1029 byte_length = *buffer;
1030 if ('A' <= byte_length && byte_length <= 'Z')
1031 byte_length = byte_length - 'A' + 1;
1032 else if ('a' <= byte_length && byte_length <= 'z')
1033 byte_length = byte_length - 'a' + 27;
1034 else
1035 goto corrupt;
1036 /* if the input length was not multiple of 4, we would
1037 * have filler at the end but the filler should never
1038 * exceed 3 bytes
1039 */
1040 if (max_byte_length < byte_length ||
1041 byte_length <= max_byte_length - 4)
1042 goto corrupt;
1043 newsize = fragment->size + byte_length;
1044 data = xrealloc(data, newsize);
1045 if (decode_85(data + fragment->size,
1046 buffer + 1,
1047 byte_length))
1048 goto corrupt;
1049 fragment->size = newsize;
1050 buffer += llen;
1051 size -= llen;
1052 }
1053 fragment->patch = data;
1054 return used;
1055 corrupt:
1056 return error("corrupt binary patch at line %d: %.*s",
1057 linenr-1, llen-1, buffer);
1058 }
1059
1060 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
1061 {
1062 int hdrsize, patchsize;
1063 int offset = find_header(buffer, size, &hdrsize, patch);
1064
1065 if (offset < 0)
1066 return offset;
1067
1068 patchsize = parse_single_patch(buffer + offset + hdrsize, size - offset - hdrsize, patch);
1069
1070 if (!patchsize) {
1071 static const char *binhdr[] = {
1072 "Binary files ",
1073 "Files ",
1074 NULL,
1075 };
1076 static const char git_binary[] = "GIT binary patch\n";
1077 int i;
1078 int hd = hdrsize + offset;
1079 unsigned long llen = linelen(buffer + hd, size - hd);
1080
1081 if (llen == sizeof(git_binary) - 1 &&
1082 !memcmp(git_binary, buffer + hd, llen)) {
1083 int used;
1084 linenr++;
1085 used = parse_binary(buffer + hd + llen,
1086 size - hd - llen, patch);
1087 if (used)
1088 patchsize = used + llen;
1089 else
1090 patchsize = 0;
1091 }
1092 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
1093 for (i = 0; binhdr[i]; i++) {
1094 int len = strlen(binhdr[i]);
1095 if (len < size - hd &&
1096 !memcmp(binhdr[i], buffer + hd, len)) {
1097 linenr++;
1098 patch->is_binary = 1;
1099 patchsize = llen;
1100 break;
1101 }
1102 }
1103 }
1104
1105 /* Empty patch cannot be applied if:
1106 * - it is a binary patch and we do not do binary_replace, or
1107 * - text patch without metadata change
1108 */
1109 if ((apply || check) &&
1110 (patch->is_binary
1111 ? !allow_binary_replacement
1112 : !metadata_changes(patch)))
1113 die("patch with only garbage at line %d", linenr);
1114 }
1115
1116 return offset + hdrsize + patchsize;
1117 }
1118
1119 static const char pluses[] = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1120 static const char minuses[]= "----------------------------------------------------------------------";
1121
1122 static void show_stats(struct patch *patch)
1123 {
1124 const char *prefix = "";
1125 char *name = patch->new_name;
1126 char *qname = NULL;
1127 int len, max, add, del, total;
1128
1129 if (!name)
1130 name = patch->old_name;
1131
1132 if (0 < (len = quote_c_style(name, NULL, NULL, 0))) {
1133 qname = xmalloc(len + 1);
1134 quote_c_style(name, qname, NULL, 0);
1135 name = qname;
1136 }
1137
1138 /*
1139 * "scale" the filename
1140 */
1141 len = strlen(name);
1142 max = max_len;
1143 if (max > 50)
1144 max = 50;
1145 if (len > max) {
1146 char *slash;
1147 prefix = "...";
1148 max -= 3;
1149 name += len - max;
1150 slash = strchr(name, '/');
1151 if (slash)
1152 name = slash;
1153 }
1154 len = max;
1155
1156 /*
1157 * scale the add/delete
1158 */
1159 max = max_change;
1160 if (max + len > 70)
1161 max = 70 - len;
1162
1163 add = patch->lines_added;
1164 del = patch->lines_deleted;
1165 total = add + del;
1166
1167 if (max_change > 0) {
1168 total = (total * max + max_change / 2) / max_change;
1169 add = (add * max + max_change / 2) / max_change;
1170 del = total - add;
1171 }
1172 if (patch->is_binary)
1173 printf(" %s%-*s | Bin\n", prefix, len, name);
1174 else
1175 printf(" %s%-*s |%5d %.*s%.*s\n", prefix,
1176 len, name, patch->lines_added + patch->lines_deleted,
1177 add, pluses, del, minuses);
1178 if (qname)
1179 free(qname);
1180 }
1181
1182 static int read_old_data(struct stat *st, const char *path, void *buf, unsigned long size)
1183 {
1184 int fd;
1185 unsigned long got;
1186
1187 switch (st->st_mode & S_IFMT) {
1188 case S_IFLNK:
1189 return readlink(path, buf, size);
1190 case S_IFREG:
1191 fd = open(path, O_RDONLY);
1192 if (fd < 0)
1193 return error("unable to open %s", path);
1194 got = 0;
1195 for (;;) {
1196 int ret = xread(fd, buf + got, size - got);
1197 if (ret <= 0)
1198 break;
1199 got += ret;
1200 }
1201 close(fd);
1202 return got;
1203
1204 default:
1205 return -1;
1206 }
1207 }
1208
1209 static int find_offset(const char *buf, unsigned long size, const char *fragment, unsigned long fragsize, int line, int *lines)
1210 {
1211 int i;
1212 unsigned long start, backwards, forwards;
1213
1214 if (fragsize > size)
1215 return -1;
1216
1217 start = 0;
1218 if (line > 1) {
1219 unsigned long offset = 0;
1220 i = line-1;
1221 while (offset + fragsize <= size) {
1222 if (buf[offset++] == '\n') {
1223 start = offset;
1224 if (!--i)
1225 break;
1226 }
1227 }
1228 }
1229
1230 /* Exact line number? */
1231 if (!memcmp(buf + start, fragment, fragsize))
1232 return start;
1233
1234 /*
1235 * There's probably some smart way to do this, but I'll leave
1236 * that to the smart and beautiful people. I'm simple and stupid.
1237 */
1238 backwards = start;
1239 forwards = start;
1240 for (i = 0; ; i++) {
1241 unsigned long try;
1242 int n;
1243
1244 /* "backward" */
1245 if (i & 1) {
1246 if (!backwards) {
1247 if (forwards + fragsize > size)
1248 break;
1249 continue;
1250 }
1251 do {
1252 --backwards;
1253 } while (backwards && buf[backwards-1] != '\n');
1254 try = backwards;
1255 } else {
1256 while (forwards + fragsize <= size) {
1257 if (buf[forwards++] == '\n')
1258 break;
1259 }
1260 try = forwards;
1261 }
1262
1263 if (try + fragsize > size)
1264 continue;
1265 if (memcmp(buf + try, fragment, fragsize))
1266 continue;
1267 n = (i >> 1)+1;
1268 if (i & 1)
1269 n = -n;
1270 *lines = n;
1271 return try;
1272 }
1273
1274 /*
1275 * We should start searching forward and backward.
1276 */
1277 return -1;
1278 }
1279
1280 static void remove_first_line(const char **rbuf, int *rsize)
1281 {
1282 const char *buf = *rbuf;
1283 int size = *rsize;
1284 unsigned long offset;
1285 offset = 0;
1286 while (offset <= size) {
1287 if (buf[offset++] == '\n')
1288 break;
1289 }
1290 *rsize = size - offset;
1291 *rbuf = buf + offset;
1292 }
1293
1294 static void remove_last_line(const char **rbuf, int *rsize)
1295 {
1296 const char *buf = *rbuf;
1297 int size = *rsize;
1298 unsigned long offset;
1299 offset = size - 1;
1300 while (offset > 0) {
1301 if (buf[--offset] == '\n')
1302 break;
1303 }
1304 *rsize = offset + 1;
1305 }
1306
1307 struct buffer_desc {
1308 char *buffer;
1309 unsigned long size;
1310 unsigned long alloc;
1311 };
1312
1313 static int apply_line(char *output, const char *patch, int plen)
1314 {
1315 /* plen is number of bytes to be copied from patch,
1316 * starting at patch+1 (patch[0] is '+'). Typically
1317 * patch[plen] is '\n'.
1318 */
1319 int add_nl_to_tail = 0;
1320 if ((new_whitespace == strip_whitespace) &&
1321 1 < plen && isspace(patch[plen-1])) {
1322 if (patch[plen] == '\n')
1323 add_nl_to_tail = 1;
1324 plen--;
1325 while (0 < plen && isspace(patch[plen]))
1326 plen--;
1327 applied_after_stripping++;
1328 }
1329 memcpy(output, patch + 1, plen);
1330 if (add_nl_to_tail)
1331 output[plen++] = '\n';
1332 return plen;
1333 }
1334
1335 static int apply_one_fragment(struct buffer_desc *desc, struct fragment *frag)
1336 {
1337 int match_beginning, match_end;
1338 char *buf = desc->buffer;
1339 const char *patch = frag->patch;
1340 int offset, size = frag->size;
1341 char *old = xmalloc(size);
1342 char *new = xmalloc(size);
1343 const char *oldlines, *newlines;
1344 int oldsize = 0, newsize = 0;
1345 unsigned long leading, trailing;
1346 int pos, lines;
1347
1348 while (size > 0) {
1349 int len = linelen(patch, size);
1350 int plen;
1351
1352 if (!len)
1353 break;
1354
1355 /*
1356 * "plen" is how much of the line we should use for
1357 * the actual patch data. Normally we just remove the
1358 * first character on the line, but if the line is
1359 * followed by "\ No newline", then we also remove the
1360 * last one (which is the newline, of course).
1361 */
1362 plen = len-1;
1363 if (len < size && patch[len] == '\\')
1364 plen--;
1365 switch (*patch) {
1366 case ' ':
1367 case '-':
1368 memcpy(old + oldsize, patch + 1, plen);
1369 oldsize += plen;
1370 if (*patch == '-')
1371 break;
1372 /* Fall-through for ' ' */
1373 case '+':
1374 if (*patch != '+' || !no_add)
1375 newsize += apply_line(new + newsize, patch,
1376 plen);
1377 break;
1378 case '@': case '\\':
1379 /* Ignore it, we already handled it */
1380 break;
1381 default:
1382 return -1;
1383 }
1384 patch += len;
1385 size -= len;
1386 }
1387
1388 #ifdef NO_ACCURATE_DIFF
1389 if (oldsize > 0 && old[oldsize - 1] == '\n' &&
1390 newsize > 0 && new[newsize - 1] == '\n') {
1391 oldsize--;
1392 newsize--;
1393 }
1394 #endif
1395
1396 oldlines = old;
1397 newlines = new;
1398 leading = frag->leading;
1399 trailing = frag->trailing;
1400
1401 /*
1402 * If we don't have any leading/trailing data in the patch,
1403 * we want it to match at the beginning/end of the file.
1404 */
1405 match_beginning = !leading && (frag->oldpos == 1);
1406 match_end = !trailing;
1407
1408 lines = 0;
1409 pos = frag->newpos;
1410 for (;;) {
1411 offset = find_offset(buf, desc->size, oldlines, oldsize, pos, &lines);
1412 if (match_end && offset + oldsize != desc->size)
1413 offset = -1;
1414 if (match_beginning && offset)
1415 offset = -1;
1416 if (offset >= 0) {
1417 int diff = newsize - oldsize;
1418 unsigned long size = desc->size + diff;
1419 unsigned long alloc = desc->alloc;
1420
1421 /* Warn if it was necessary to reduce the number
1422 * of context lines.
1423 */
1424 if ((leading != frag->leading) || (trailing != frag->trailing))
1425 fprintf(stderr, "Context reduced to (%ld/%ld) to apply fragment at %d\n",
1426 leading, trailing, pos + lines);
1427
1428 if (size > alloc) {
1429 alloc = size + 8192;
1430 desc->alloc = alloc;
1431 buf = xrealloc(buf, alloc);
1432 desc->buffer = buf;
1433 }
1434 desc->size = size;
1435 memmove(buf + offset + newsize, buf + offset + oldsize, size - offset - newsize);
1436 memcpy(buf + offset, newlines, newsize);
1437 offset = 0;
1438
1439 break;
1440 }
1441
1442 /* Am I at my context limits? */
1443 if ((leading <= p_context) && (trailing <= p_context))
1444 break;
1445 if (match_beginning || match_end) {
1446 match_beginning = match_end = 0;
1447 continue;
1448 }
1449 /* Reduce the number of context lines
1450 * Reduce both leading and trailing if they are equal
1451 * otherwise just reduce the larger context.
1452 */
1453 if (leading >= trailing) {
1454 remove_first_line(&oldlines, &oldsize);
1455 remove_first_line(&newlines, &newsize);
1456 pos--;
1457 leading--;
1458 }
1459 if (trailing > leading) {
1460 remove_last_line(&oldlines, &oldsize);
1461 remove_last_line(&newlines, &newsize);
1462 trailing--;
1463 }
1464 }
1465
1466 free(old);
1467 free(new);
1468 return offset;
1469 }
1470
1471 static char *inflate_it(const void *data, unsigned long size,
1472 unsigned long inflated_size)
1473 {
1474 z_stream stream;
1475 void *out;
1476 int st;
1477
1478 memset(&stream, 0, sizeof(stream));
1479
1480 stream.next_in = (unsigned char *)data;
1481 stream.avail_in = size;
1482 stream.next_out = out = xmalloc(inflated_size);
1483 stream.avail_out = inflated_size;
1484 inflateInit(&stream);
1485 st = inflate(&stream, Z_FINISH);
1486 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1487 free(out);
1488 return NULL;
1489 }
1490 return out;
1491 }
1492
1493 static int apply_binary_fragment(struct buffer_desc *desc, struct patch *patch)
1494 {
1495 unsigned long dst_size;
1496 struct fragment *fragment = patch->fragments;
1497 void *data;
1498 void *result;
1499
1500 data = inflate_it(fragment->patch, fragment->size,
1501 patch->deflate_origlen);
1502 if (!data)
1503 return error("corrupt patch data");
1504 switch (patch->is_binary) {
1505 case BINARY_DELTA_DEFLATED:
1506 result = patch_delta(desc->buffer, desc->size,
1507 data,
1508 patch->deflate_origlen,
1509 &dst_size);
1510 free(desc->buffer);
1511 desc->buffer = result;
1512 free(data);
1513 break;
1514 case BINARY_LITERAL_DEFLATED:
1515 free(desc->buffer);
1516 desc->buffer = data;
1517 dst_size = patch->deflate_origlen;
1518 break;
1519 }
1520 if (!desc->buffer)
1521 return -1;
1522 desc->size = desc->alloc = dst_size;
1523 return 0;
1524 }
1525
1526 static int apply_binary(struct buffer_desc *desc, struct patch *patch)
1527 {
1528 const char *name = patch->old_name ? patch->old_name : patch->new_name;
1529 unsigned char sha1[20];
1530 unsigned char hdr[50];
1531 int hdrlen;
1532
1533 if (!allow_binary_replacement)
1534 return error("cannot apply binary patch to '%s' "
1535 "without --allow-binary-replacement",
1536 name);
1537
1538 /* For safety, we require patch index line to contain
1539 * full 40-byte textual SHA1 for old and new, at least for now.
1540 */
1541 if (strlen(patch->old_sha1_prefix) != 40 ||
1542 strlen(patch->new_sha1_prefix) != 40 ||
1543 get_sha1_hex(patch->old_sha1_prefix, sha1) ||
1544 get_sha1_hex(patch->new_sha1_prefix, sha1))
1545 return error("cannot apply binary patch to '%s' "
1546 "without full index line", name);
1547
1548 if (patch->old_name) {
1549 /* See if the old one matches what the patch
1550 * applies to.
1551 */
1552 write_sha1_file_prepare(desc->buffer, desc->size,
1553 blob_type, sha1, hdr, &hdrlen);
1554 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
1555 return error("the patch applies to '%s' (%s), "
1556 "which does not match the "
1557 "current contents.",
1558 name, sha1_to_hex(sha1));
1559 }
1560 else {
1561 /* Otherwise, the old one must be empty. */
1562 if (desc->size)
1563 return error("the patch applies to an empty "
1564 "'%s' but it is not empty", name);
1565 }
1566
1567 get_sha1_hex(patch->new_sha1_prefix, sha1);
1568 if (!memcmp(sha1, null_sha1, 20)) {
1569 free(desc->buffer);
1570 desc->alloc = desc->size = 0;
1571 desc->buffer = NULL;
1572 return 0; /* deletion patch */
1573 }
1574
1575 if (has_sha1_file(sha1)) {
1576 /* We already have the postimage */
1577 char type[10];
1578 unsigned long size;
1579
1580 free(desc->buffer);
1581 desc->buffer = read_sha1_file(sha1, type, &size);
1582 if (!desc->buffer)
1583 return error("the necessary postimage %s for "
1584 "'%s' cannot be read",
1585 patch->new_sha1_prefix, name);
1586 desc->alloc = desc->size = size;
1587 }
1588 else {
1589 /* We have verified desc matches the preimage;
1590 * apply the patch data to it, which is stored
1591 * in the patch->fragments->{patch,size}.
1592 */
1593 if (apply_binary_fragment(desc, patch))
1594 return error("binary patch does not apply to '%s'",
1595 name);
1596
1597 /* verify that the result matches */
1598 write_sha1_file_prepare(desc->buffer, desc->size, blob_type,
1599 sha1, hdr, &hdrlen);
1600 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
1601 return error("binary patch to '%s' creates incorrect result", name);
1602 }
1603
1604 return 0;
1605 }
1606
1607 static int apply_fragments(struct buffer_desc *desc, struct patch *patch)
1608 {
1609 struct fragment *frag = patch->fragments;
1610 const char *name = patch->old_name ? patch->old_name : patch->new_name;
1611
1612 if (patch->is_binary)
1613 return apply_binary(desc, patch);
1614
1615 while (frag) {
1616 if (apply_one_fragment(desc, frag) < 0)
1617 return error("patch failed: %s:%ld",
1618 name, frag->oldpos);
1619 frag = frag->next;
1620 }
1621 return 0;
1622 }
1623
1624 static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce)
1625 {
1626 char *buf;
1627 unsigned long size, alloc;
1628 struct buffer_desc desc;
1629
1630 size = 0;
1631 alloc = 0;
1632 buf = NULL;
1633 if (cached) {
1634 if (ce) {
1635 char type[20];
1636 buf = read_sha1_file(ce->sha1, type, &size);
1637 if (!buf)
1638 return error("read of %s failed",
1639 patch->old_name);
1640 alloc = size;
1641 }
1642 }
1643 else if (patch->old_name) {
1644 size = st->st_size;
1645 alloc = size + 8192;
1646 buf = xmalloc(alloc);
1647 if (read_old_data(st, patch->old_name, buf, alloc) != size)
1648 return error("read of %s failed", patch->old_name);
1649 }
1650
1651 desc.size = size;
1652 desc.alloc = alloc;
1653 desc.buffer = buf;
1654 if (apply_fragments(&desc, patch) < 0)
1655 return -1;
1656 patch->result = desc.buffer;
1657 patch->resultsize = desc.size;
1658
1659 if (patch->is_delete && patch->resultsize)
1660 return error("removal patch leaves file contents");
1661
1662 return 0;
1663 }
1664
1665 static int check_patch(struct patch *patch)
1666 {
1667 struct stat st;
1668 const char *old_name = patch->old_name;
1669 const char *new_name = patch->new_name;
1670 const char *name = old_name ? old_name : new_name;
1671 struct cache_entry *ce = NULL;
1672
1673 if (old_name) {
1674 int changed = 0;
1675 int stat_ret = 0;
1676 unsigned st_mode = 0;
1677
1678 if (!cached)
1679 stat_ret = lstat(old_name, &st);
1680 if (check_index) {
1681 int pos = cache_name_pos(old_name, strlen(old_name));
1682 if (pos < 0)
1683 return error("%s: does not exist in index",
1684 old_name);
1685 ce = active_cache[pos];
1686 if (stat_ret < 0) {
1687 struct checkout costate;
1688 if (errno != ENOENT)
1689 return error("%s: %s", old_name,
1690 strerror(errno));
1691 /* checkout */
1692 costate.base_dir = "";
1693 costate.base_dir_len = 0;
1694 costate.force = 0;
1695 costate.quiet = 0;
1696 costate.not_new = 0;
1697 costate.refresh_cache = 1;
1698 if (checkout_entry(ce,
1699 &costate,
1700 NULL) ||
1701 lstat(old_name, &st))
1702 return -1;
1703 }
1704 if (!cached)
1705 changed = ce_match_stat(ce, &st, 1);
1706 if (changed)
1707 return error("%s: does not match index",
1708 old_name);
1709 if (cached)
1710 st_mode = ntohl(ce->ce_mode);
1711 }
1712 else if (stat_ret < 0)
1713 return error("%s: %s", old_name, strerror(errno));
1714
1715 if (!cached)
1716 st_mode = ntohl(create_ce_mode(st.st_mode));
1717
1718 if (patch->is_new < 0)
1719 patch->is_new = 0;
1720 if (!patch->old_mode)
1721 patch->old_mode = st_mode;
1722 if ((st_mode ^ patch->old_mode) & S_IFMT)
1723 return error("%s: wrong type", old_name);
1724 if (st_mode != patch->old_mode)
1725 fprintf(stderr, "warning: %s has type %o, expected %o\n",
1726 old_name, st_mode, patch->old_mode);
1727 }
1728
1729 if (new_name && (patch->is_new | patch->is_rename | patch->is_copy)) {
1730 if (check_index && cache_name_pos(new_name, strlen(new_name)) >= 0)
1731 return error("%s: already exists in index", new_name);
1732 if (!cached) {
1733 if (!lstat(new_name, &st))
1734 return error("%s: already exists in working directory", new_name);
1735 if (errno != ENOENT)
1736 return error("%s: %s", new_name, strerror(errno));
1737 }
1738 if (!patch->new_mode) {
1739 if (patch->is_new)
1740 patch->new_mode = S_IFREG | 0644;
1741 else
1742 patch->new_mode = patch->old_mode;
1743 }
1744 }
1745
1746 if (new_name && old_name) {
1747 int same = !strcmp(old_name, new_name);
1748 if (!patch->new_mode)
1749 patch->new_mode = patch->old_mode;
1750 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
1751 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
1752 patch->new_mode, new_name, patch->old_mode,
1753 same ? "" : " of ", same ? "" : old_name);
1754 }
1755
1756 if (apply_data(patch, &st, ce) < 0)
1757 return error("%s: patch does not apply", name);
1758 return 0;
1759 }
1760
1761 static int check_patch_list(struct patch *patch)
1762 {
1763 int error = 0;
1764
1765 for (;patch ; patch = patch->next)
1766 error |= check_patch(patch);
1767 return error;
1768 }
1769
1770 static inline int is_null_sha1(const unsigned char *sha1)
1771 {
1772 return !memcmp(sha1, null_sha1, 20);
1773 }
1774
1775 static void show_index_list(struct patch *list)
1776 {
1777 struct patch *patch;
1778
1779 /* Once we start supporting the reverse patch, it may be
1780 * worth showing the new sha1 prefix, but until then...
1781 */
1782 for (patch = list; patch; patch = patch->next) {
1783 const unsigned char *sha1_ptr;
1784 unsigned char sha1[20];
1785 const char *name;
1786
1787 name = patch->old_name ? patch->old_name : patch->new_name;
1788 if (patch->is_new)
1789 sha1_ptr = null_sha1;
1790 else if (get_sha1(patch->old_sha1_prefix, sha1))
1791 die("sha1 information is lacking or useless (%s).",
1792 name);
1793 else
1794 sha1_ptr = sha1;
1795
1796 printf("%06o %s ",patch->old_mode, sha1_to_hex(sha1_ptr));
1797 if (line_termination && quote_c_style(name, NULL, NULL, 0))
1798 quote_c_style(name, NULL, stdout, 0);
1799 else
1800 fputs(name, stdout);
1801 putchar(line_termination);
1802 }
1803 }
1804
1805 static void stat_patch_list(struct patch *patch)
1806 {
1807 int files, adds, dels;
1808
1809 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
1810 files++;
1811 adds += patch->lines_added;
1812 dels += patch->lines_deleted;
1813 show_stats(patch);
1814 }
1815
1816 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
1817 }
1818
1819 static void numstat_patch_list(struct patch *patch)
1820 {
1821 for ( ; patch; patch = patch->next) {
1822 const char *name;
1823 name = patch->new_name ? patch->new_name : patch->old_name;
1824 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
1825 if (line_termination && quote_c_style(name, NULL, NULL, 0))
1826 quote_c_style(name, NULL, stdout, 0);
1827 else
1828 fputs(name, stdout);
1829 putchar('\n');
1830 }
1831 }
1832
1833 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
1834 {
1835 if (mode)
1836 printf(" %s mode %06o %s\n", newdelete, mode, name);
1837 else
1838 printf(" %s %s\n", newdelete, name);
1839 }
1840
1841 static void show_mode_change(struct patch *p, int show_name)
1842 {
1843 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
1844 if (show_name)
1845 printf(" mode change %06o => %06o %s\n",
1846 p->old_mode, p->new_mode, p->new_name);
1847 else
1848 printf(" mode change %06o => %06o\n",
1849 p->old_mode, p->new_mode);
1850 }
1851 }
1852
1853 static void show_rename_copy(struct patch *p)
1854 {
1855 const char *renamecopy = p->is_rename ? "rename" : "copy";
1856 const char *old, *new;
1857
1858 /* Find common prefix */
1859 old = p->old_name;
1860 new = p->new_name;
1861 while (1) {
1862 const char *slash_old, *slash_new;
1863 slash_old = strchr(old, '/');
1864 slash_new = strchr(new, '/');
1865 if (!slash_old ||
1866 !slash_new ||
1867 slash_old - old != slash_new - new ||
1868 memcmp(old, new, slash_new - new))
1869 break;
1870 old = slash_old + 1;
1871 new = slash_new + 1;
1872 }
1873 /* p->old_name thru old is the common prefix, and old and new
1874 * through the end of names are renames
1875 */
1876 if (old != p->old_name)
1877 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
1878 (int)(old - p->old_name), p->old_name,
1879 old, new, p->score);
1880 else
1881 printf(" %s %s => %s (%d%%)\n", renamecopy,
1882 p->old_name, p->new_name, p->score);
1883 show_mode_change(p, 0);
1884 }
1885
1886 static void summary_patch_list(struct patch *patch)
1887 {
1888 struct patch *p;
1889
1890 for (p = patch; p; p = p->next) {
1891 if (p->is_new)
1892 show_file_mode_name("create", p->new_mode, p->new_name);
1893 else if (p->is_delete)
1894 show_file_mode_name("delete", p->old_mode, p->old_name);
1895 else {
1896 if (p->is_rename || p->is_copy)
1897 show_rename_copy(p);
1898 else {
1899 if (p->score) {
1900 printf(" rewrite %s (%d%%)\n",
1901 p->new_name, p->score);
1902 show_mode_change(p, 0);
1903 }
1904 else
1905 show_mode_change(p, 1);
1906 }
1907 }
1908 }
1909 }
1910
1911 static void patch_stats(struct patch *patch)
1912 {
1913 int lines = patch->lines_added + patch->lines_deleted;
1914
1915 if (lines > max_change)
1916 max_change = lines;
1917 if (patch->old_name) {
1918 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
1919 if (!len)
1920 len = strlen(patch->old_name);
1921 if (len > max_len)
1922 max_len = len;
1923 }
1924 if (patch->new_name) {
1925 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
1926 if (!len)
1927 len = strlen(patch->new_name);
1928 if (len > max_len)
1929 max_len = len;
1930 }
1931 }
1932
1933 static void remove_file(struct patch *patch)
1934 {
1935 if (write_index) {
1936 if (remove_file_from_cache(patch->old_name) < 0)
1937 die("unable to remove %s from index", patch->old_name);
1938 }
1939 if (!cached)
1940 unlink(patch->old_name);
1941 }
1942
1943 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
1944 {
1945 struct stat st;
1946 struct cache_entry *ce;
1947 int namelen = strlen(path);
1948 unsigned ce_size = cache_entry_size(namelen);
1949
1950 if (!write_index)
1951 return;
1952
1953 ce = xcalloc(1, ce_size);
1954 memcpy(ce->name, path, namelen);
1955 ce->ce_mode = create_ce_mode(mode);
1956 ce->ce_flags = htons(namelen);
1957 if (!cached) {
1958 if (lstat(path, &st) < 0)
1959 die("unable to stat newly created file %s", path);
1960 fill_stat_cache_info(ce, &st);
1961 }
1962 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
1963 die("unable to create backing store for newly created file %s", path);
1964 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
1965 die("unable to add cache entry for %s", path);
1966 }
1967
1968 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
1969 {
1970 int fd;
1971
1972 if (S_ISLNK(mode))
1973 return symlink(buf, path);
1974 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
1975 if (fd < 0)
1976 return -1;
1977 while (size) {
1978 int written = xwrite(fd, buf, size);
1979 if (written < 0)
1980 die("writing file %s: %s", path, strerror(errno));
1981 if (!written)
1982 die("out of space writing file %s", path);
1983 buf += written;
1984 size -= written;
1985 }
1986 if (close(fd) < 0)
1987 die("closing file %s: %s", path, strerror(errno));
1988 return 0;
1989 }
1990
1991 /*
1992 * We optimistically assume that the directories exist,
1993 * which is true 99% of the time anyway. If they don't,
1994 * we create them and try again.
1995 */
1996 static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
1997 {
1998 if (cached)
1999 return;
2000 if (!try_create_file(path, mode, buf, size))
2001 return;
2002
2003 if (errno == ENOENT) {
2004 if (safe_create_leading_directories(path))
2005 return;
2006 if (!try_create_file(path, mode, buf, size))
2007 return;
2008 }
2009
2010 if (errno == EEXIST) {
2011 unsigned int nr = getpid();
2012
2013 for (;;) {
2014 const char *newpath;
2015 newpath = mkpath("%s~%u", path, nr);
2016 if (!try_create_file(newpath, mode, buf, size)) {
2017 if (!rename(newpath, path))
2018 return;
2019 unlink(newpath);
2020 break;
2021 }
2022 if (errno != EEXIST)
2023 break;
2024 ++nr;
2025 }
2026 }
2027 die("unable to write file %s mode %o", path, mode);
2028 }
2029
2030 static void create_file(struct patch *patch)
2031 {
2032 char *path = patch->new_name;
2033 unsigned mode = patch->new_mode;
2034 unsigned long size = patch->resultsize;
2035 char *buf = patch->result;
2036
2037 if (!mode)
2038 mode = S_IFREG | 0644;
2039 create_one_file(path, mode, buf, size);
2040 add_index_file(path, mode, buf, size);
2041 }
2042
2043 static void write_out_one_result(struct patch *patch)
2044 {
2045 if (patch->is_delete > 0) {
2046 remove_file(patch);
2047 return;
2048 }
2049 if (patch->is_new > 0 || patch->is_copy) {
2050 create_file(patch);
2051 return;
2052 }
2053 /*
2054 * Rename or modification boils down to the same
2055 * thing: remove the old, write the new
2056 */
2057 remove_file(patch);
2058 create_file(patch);
2059 }
2060
2061 static void write_out_results(struct patch *list, int skipped_patch)
2062 {
2063 if (!list && !skipped_patch)
2064 die("No changes");
2065
2066 while (list) {
2067 write_out_one_result(list);
2068 list = list->next;
2069 }
2070 }
2071
2072 static struct cache_file cache_file;
2073
2074 static struct excludes {
2075 struct excludes *next;
2076 const char *path;
2077 } *excludes;
2078
2079 static int use_patch(struct patch *p)
2080 {
2081 const char *pathname = p->new_name ? p->new_name : p->old_name;
2082 struct excludes *x = excludes;
2083 while (x) {
2084 if (fnmatch(x->path, pathname, 0) == 0)
2085 return 0;
2086 x = x->next;
2087 }
2088 if (0 < prefix_length) {
2089 int pathlen = strlen(pathname);
2090 if (pathlen <= prefix_length ||
2091 memcmp(prefix, pathname, prefix_length))
2092 return 0;
2093 }
2094 return 1;
2095 }
2096
2097 static int apply_patch(int fd, const char *filename)
2098 {
2099 unsigned long offset, size;
2100 char *buffer = read_patch_file(fd, &size);
2101 struct patch *list = NULL, **listp = &list;
2102 int skipped_patch = 0;
2103
2104 patch_input_file = filename;
2105 if (!buffer)
2106 return -1;
2107 offset = 0;
2108 while (size > 0) {
2109 struct patch *patch;
2110 int nr;
2111
2112 patch = xcalloc(1, sizeof(*patch));
2113 nr = parse_chunk(buffer + offset, size, patch);
2114 if (nr < 0)
2115 break;
2116 if (use_patch(patch)) {
2117 patch_stats(patch);
2118 *listp = patch;
2119 listp = &patch->next;
2120 } else {
2121 /* perhaps free it a bit better? */
2122 free(patch);
2123 skipped_patch++;
2124 }
2125 offset += nr;
2126 size -= nr;
2127 }
2128
2129 if (whitespace_error && (new_whitespace == error_on_whitespace))
2130 apply = 0;
2131
2132 write_index = check_index && apply;
2133 if (write_index && newfd < 0)
2134 newfd = hold_index_file_for_update(&cache_file, get_index_file());
2135 if (check_index) {
2136 if (read_cache() < 0)
2137 die("unable to read index file");
2138 }
2139
2140 if ((check || apply) && check_patch_list(list) < 0)
2141 exit(1);
2142
2143 if (apply)
2144 write_out_results(list, skipped_patch);
2145
2146 if (show_index_info)
2147 show_index_list(list);
2148
2149 if (diffstat)
2150 stat_patch_list(list);
2151
2152 if (numstat)
2153 numstat_patch_list(list);
2154
2155 if (summary)
2156 summary_patch_list(list);
2157
2158 free(buffer);
2159 return 0;
2160 }
2161
2162 static int git_apply_config(const char *var, const char *value)
2163 {
2164 if (!strcmp(var, "apply.whitespace")) {
2165 apply_default_whitespace = strdup(value);
2166 return 0;
2167 }
2168 return git_default_config(var, value);
2169 }
2170
2171
2172 int cmd_apply(int argc, const char **argv, char **envp)
2173 {
2174 int i;
2175 int read_stdin = 1;
2176 const char *whitespace_option = NULL;
2177
2178 for (i = 1; i < argc; i++) {
2179 const char *arg = argv[i];
2180 char *end;
2181 int fd;
2182
2183 if (!strcmp(arg, "-")) {
2184 apply_patch(0, "<stdin>");
2185 read_stdin = 0;
2186 continue;
2187 }
2188 if (!strncmp(arg, "--exclude=", 10)) {
2189 struct excludes *x = xmalloc(sizeof(*x));
2190 x->path = arg + 10;
2191 x->next = excludes;
2192 excludes = x;
2193 continue;
2194 }
2195 if (!strncmp(arg, "-p", 2)) {
2196 p_value = atoi(arg + 2);
2197 continue;
2198 }
2199 if (!strcmp(arg, "--no-add")) {
2200 no_add = 1;
2201 continue;
2202 }
2203 if (!strcmp(arg, "--stat")) {
2204 apply = 0;
2205 diffstat = 1;
2206 continue;
2207 }
2208 if (!strcmp(arg, "--allow-binary-replacement") ||
2209 !strcmp(arg, "--binary")) {
2210 allow_binary_replacement = 1;
2211 continue;
2212 }
2213 if (!strcmp(arg, "--numstat")) {
2214 apply = 0;
2215 numstat = 1;
2216 continue;
2217 }
2218 if (!strcmp(arg, "--summary")) {
2219 apply = 0;
2220 summary = 1;
2221 continue;
2222 }
2223 if (!strcmp(arg, "--check")) {
2224 apply = 0;
2225 check = 1;
2226 continue;
2227 }
2228 if (!strcmp(arg, "--index")) {
2229 check_index = 1;
2230 continue;
2231 }
2232 if (!strcmp(arg, "--cached")) {
2233 check_index = 1;
2234 cached = 1;
2235 continue;
2236 }
2237 if (!strcmp(arg, "--apply")) {
2238 apply = 1;
2239 continue;
2240 }
2241 if (!strcmp(arg, "--index-info")) {
2242 apply = 0;
2243 show_index_info = 1;
2244 continue;
2245 }
2246 if (!strcmp(arg, "-z")) {
2247 line_termination = 0;
2248 continue;
2249 }
2250 if (!strncmp(arg, "-C", 2)) {
2251 p_context = strtoul(arg + 2, &end, 0);
2252 if (*end != '\0')
2253 die("unrecognized context count '%s'", arg + 2);
2254 continue;
2255 }
2256 if (!strncmp(arg, "--whitespace=", 13)) {
2257 whitespace_option = arg + 13;
2258 parse_whitespace_option(arg + 13);
2259 continue;
2260 }
2261
2262 if (check_index && prefix_length < 0) {
2263 prefix = setup_git_directory();
2264 prefix_length = prefix ? strlen(prefix) : 0;
2265 git_config(git_apply_config);
2266 if (!whitespace_option && apply_default_whitespace)
2267 parse_whitespace_option(apply_default_whitespace);
2268 }
2269 if (0 < prefix_length)
2270 arg = prefix_filename(prefix, prefix_length, arg);
2271
2272 fd = open(arg, O_RDONLY);
2273 if (fd < 0)
2274 usage(apply_usage);
2275 read_stdin = 0;
2276 set_default_whitespace_mode(whitespace_option);
2277 apply_patch(fd, arg);
2278 close(fd);
2279 }
2280 set_default_whitespace_mode(whitespace_option);
2281 if (read_stdin)
2282 apply_patch(0, "<stdin>");
2283 if (whitespace_error) {
2284 if (squelch_whitespace_errors &&
2285 squelch_whitespace_errors < whitespace_error) {
2286 int squelched =
2287 whitespace_error - squelch_whitespace_errors;
2288 fprintf(stderr, "warning: squelched %d whitespace error%s\n",
2289 squelched,
2290 squelched == 1 ? "" : "s");
2291 }
2292 if (new_whitespace == error_on_whitespace)
2293 die("%d line%s add%s trailing whitespaces.",
2294 whitespace_error,
2295 whitespace_error == 1 ? "" : "s",
2296 whitespace_error == 1 ? "s" : "");
2297 if (applied_after_stripping)
2298 fprintf(stderr, "warning: %d line%s applied after"
2299 " stripping trailing whitespaces.\n",
2300 applied_after_stripping,
2301 applied_after_stripping == 1 ? "" : "s");
2302 else if (whitespace_error)
2303 fprintf(stderr, "warning: %d line%s add%s trailing"
2304 " whitespaces.\n",
2305 whitespace_error,
2306 whitespace_error == 1 ? "" : "s",
2307 whitespace_error == 1 ? "s" : "");
2308 }
2309
2310 if (write_index) {
2311 if (write_cache(newfd, active_cache, active_nr) ||
2312 commit_index_file(&cache_file))
2313 die("Unable to write new cachefile");
2314 }
2315
2316 return 0;
2317 }