Fix pack-index issue on 64-bit platforms a bit more portably.
[git/git-svn.git] / apply.c
blobca36391bb20672214705d2a4a188f69f97201256
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 <fnmatch.h>
10 #include "cache.h"
11 #include "quote.h"
12 #include "blob.h"
14 // --check turns on checking that the working tree matches the
15 // files that are being modified, but doesn't apply the patch
16 // --stat does just a diffstat, and doesn't actually apply
17 // --numstat does numeric diffstat, and doesn't actually apply
18 // --index-info shows the old and new index info for paths if available.
20 static const char *prefix;
21 static int prefix_length = -1;
22 static int newfd = -1;
24 static int p_value = 1;
25 static int allow_binary_replacement = 0;
26 static int check_index = 0;
27 static int write_index = 0;
28 static int diffstat = 0;
29 static int numstat = 0;
30 static int summary = 0;
31 static int check = 0;
32 static int apply = 1;
33 static int no_add = 0;
34 static int show_index_info = 0;
35 static int line_termination = '\n';
36 static unsigned long p_context = -1;
37 static const char apply_usage[] =
38 "git-apply [--stat] [--numstat] [--summary] [--check] [--index] [--apply] [--no-add] [--index-info] [--allow-binary-replacement] [-z] [-pNUM] [-CNUM] [--whitespace=<nowarn|warn|error|error-all|strip>] <patch>...";
40 static enum whitespace_eol {
41 nowarn_whitespace,
42 warn_on_whitespace,
43 error_on_whitespace,
44 strip_whitespace,
45 } new_whitespace = warn_on_whitespace;
46 static int whitespace_error = 0;
47 static int squelch_whitespace_errors = 5;
48 static int applied_after_stripping = 0;
49 static const char *patch_input_file = NULL;
51 static void parse_whitespace_option(const char *option)
53 if (!option) {
54 new_whitespace = warn_on_whitespace;
55 return;
57 if (!strcmp(option, "warn")) {
58 new_whitespace = warn_on_whitespace;
59 return;
61 if (!strcmp(option, "nowarn")) {
62 new_whitespace = nowarn_whitespace;
63 return;
65 if (!strcmp(option, "error")) {
66 new_whitespace = error_on_whitespace;
67 return;
69 if (!strcmp(option, "error-all")) {
70 new_whitespace = error_on_whitespace;
71 squelch_whitespace_errors = 0;
72 return;
74 if (!strcmp(option, "strip")) {
75 new_whitespace = strip_whitespace;
76 return;
78 die("unrecognized whitespace option '%s'", option);
81 static void set_default_whitespace_mode(const char *whitespace_option)
83 if (!whitespace_option && !apply_default_whitespace) {
84 new_whitespace = (apply
85 ? warn_on_whitespace
86 : nowarn_whitespace);
91 * For "diff-stat" like behaviour, we keep track of the biggest change
92 * we've seen, and the longest filename. That allows us to do simple
93 * scaling.
95 static int max_change, max_len;
98 * Various "current state", notably line numbers and what
99 * file (and how) we're patching right now.. The "is_xxxx"
100 * things are flags, where -1 means "don't know yet".
102 static int linenr = 1;
104 struct fragment {
105 unsigned long leading, trailing;
106 unsigned long oldpos, oldlines;
107 unsigned long newpos, newlines;
108 const char *patch;
109 int size;
110 struct fragment *next;
113 struct patch {
114 char *new_name, *old_name, *def_name;
115 unsigned int old_mode, new_mode;
116 int is_rename, is_copy, is_new, is_delete, is_binary;
117 int lines_added, lines_deleted;
118 int score;
119 struct fragment *fragments;
120 char *result;
121 unsigned long resultsize;
122 char old_sha1_prefix[41];
123 char new_sha1_prefix[41];
124 struct patch *next;
127 #define CHUNKSIZE (8192)
128 #define SLOP (16)
130 static void *read_patch_file(int fd, unsigned long *sizep)
132 unsigned long size = 0, alloc = CHUNKSIZE;
133 void *buffer = xmalloc(alloc);
135 for (;;) {
136 int nr = alloc - size;
137 if (nr < 1024) {
138 alloc += CHUNKSIZE;
139 buffer = xrealloc(buffer, alloc);
140 nr = alloc - size;
142 nr = xread(fd, buffer + size, nr);
143 if (!nr)
144 break;
145 if (nr < 0)
146 die("git-apply: read returned %s", strerror(errno));
147 size += nr;
149 *sizep = size;
152 * Make sure that we have some slop in the buffer
153 * so that we can do speculative "memcmp" etc, and
154 * see to it that it is NUL-filled.
156 if (alloc < size + SLOP)
157 buffer = xrealloc(buffer, size + SLOP);
158 memset(buffer + size, 0, SLOP);
159 return buffer;
162 static unsigned long linelen(const char *buffer, unsigned long size)
164 unsigned long len = 0;
165 while (size--) {
166 len++;
167 if (*buffer++ == '\n')
168 break;
170 return len;
173 static int is_dev_null(const char *str)
175 return !memcmp("/dev/null", str, 9) && isspace(str[9]);
178 #define TERM_SPACE 1
179 #define TERM_TAB 2
181 static int name_terminate(const char *name, int namelen, int c, int terminate)
183 if (c == ' ' && !(terminate & TERM_SPACE))
184 return 0;
185 if (c == '\t' && !(terminate & TERM_TAB))
186 return 0;
188 return 1;
191 static char * find_name(const char *line, char *def, int p_value, int terminate)
193 int len;
194 const char *start = line;
195 char *name;
197 if (*line == '"') {
198 /* Proposed "new-style" GNU patch/diff format; see
199 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
201 name = unquote_c_style(line, NULL);
202 if (name) {
203 char *cp = name;
204 while (p_value) {
205 cp = strchr(name, '/');
206 if (!cp)
207 break;
208 cp++;
209 p_value--;
211 if (cp) {
212 /* name can later be freed, so we need
213 * to memmove, not just return cp
215 memmove(name, cp, strlen(cp) + 1);
216 free(def);
217 return name;
219 else {
220 free(name);
221 name = NULL;
226 for (;;) {
227 char c = *line;
229 if (isspace(c)) {
230 if (c == '\n')
231 break;
232 if (name_terminate(start, line-start, c, terminate))
233 break;
235 line++;
236 if (c == '/' && !--p_value)
237 start = line;
239 if (!start)
240 return def;
241 len = line - start;
242 if (!len)
243 return def;
246 * Generally we prefer the shorter name, especially
247 * if the other one is just a variation of that with
248 * something else tacked on to the end (ie "file.orig"
249 * or "file~").
251 if (def) {
252 int deflen = strlen(def);
253 if (deflen < len && !strncmp(start, def, deflen))
254 return def;
257 name = xmalloc(len + 1);
258 memcpy(name, start, len);
259 name[len] = 0;
260 free(def);
261 return name;
265 * Get the name etc info from the --/+++ lines of a traditional patch header
267 * NOTE! This hardcodes "-p1" behaviour in filename detection.
269 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
270 * files, we can happily check the index for a match, but for creating a
271 * new file we should try to match whatever "patch" does. I have no idea.
273 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
275 char *name;
277 first += 4; // skip "--- "
278 second += 4; // skip "+++ "
279 if (is_dev_null(first)) {
280 patch->is_new = 1;
281 patch->is_delete = 0;
282 name = find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB);
283 patch->new_name = name;
284 } else if (is_dev_null(second)) {
285 patch->is_new = 0;
286 patch->is_delete = 1;
287 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
288 patch->old_name = name;
289 } else {
290 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
291 name = find_name(second, name, p_value, TERM_SPACE | TERM_TAB);
292 patch->old_name = patch->new_name = name;
294 if (!name)
295 die("unable to find filename in patch at line %d", linenr);
298 static int gitdiff_hdrend(const char *line, struct patch *patch)
300 return -1;
304 * We're anal about diff header consistency, to make
305 * sure that we don't end up having strange ambiguous
306 * patches floating around.
308 * As a result, gitdiff_{old|new}name() will check
309 * their names against any previous information, just
310 * to make sure..
312 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
314 if (!orig_name && !isnull)
315 return find_name(line, NULL, 1, 0);
317 if (orig_name) {
318 int len;
319 const char *name;
320 char *another;
321 name = orig_name;
322 len = strlen(name);
323 if (isnull)
324 die("git-apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
325 another = find_name(line, NULL, 1, 0);
326 if (!another || memcmp(another, name, len))
327 die("git-apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
328 free(another);
329 return orig_name;
331 else {
332 /* expect "/dev/null" */
333 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
334 die("git-apply: bad git-diff - expected /dev/null on line %d", linenr);
335 return NULL;
339 static int gitdiff_oldname(const char *line, struct patch *patch)
341 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
342 return 0;
345 static int gitdiff_newname(const char *line, struct patch *patch)
347 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
348 return 0;
351 static int gitdiff_oldmode(const char *line, struct patch *patch)
353 patch->old_mode = strtoul(line, NULL, 8);
354 return 0;
357 static int gitdiff_newmode(const char *line, struct patch *patch)
359 patch->new_mode = strtoul(line, NULL, 8);
360 return 0;
363 static int gitdiff_delete(const char *line, struct patch *patch)
365 patch->is_delete = 1;
366 patch->old_name = patch->def_name;
367 return gitdiff_oldmode(line, patch);
370 static int gitdiff_newfile(const char *line, struct patch *patch)
372 patch->is_new = 1;
373 patch->new_name = patch->def_name;
374 return gitdiff_newmode(line, patch);
377 static int gitdiff_copysrc(const char *line, struct patch *patch)
379 patch->is_copy = 1;
380 patch->old_name = find_name(line, NULL, 0, 0);
381 return 0;
384 static int gitdiff_copydst(const char *line, struct patch *patch)
386 patch->is_copy = 1;
387 patch->new_name = find_name(line, NULL, 0, 0);
388 return 0;
391 static int gitdiff_renamesrc(const char *line, struct patch *patch)
393 patch->is_rename = 1;
394 patch->old_name = find_name(line, NULL, 0, 0);
395 return 0;
398 static int gitdiff_renamedst(const char *line, struct patch *patch)
400 patch->is_rename = 1;
401 patch->new_name = find_name(line, NULL, 0, 0);
402 return 0;
405 static int gitdiff_similarity(const char *line, struct patch *patch)
407 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
408 patch->score = 0;
409 return 0;
412 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
414 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
415 patch->score = 0;
416 return 0;
419 static int gitdiff_index(const char *line, struct patch *patch)
421 /* index line is N hexadecimal, "..", N hexadecimal,
422 * and optional space with octal mode.
424 const char *ptr, *eol;
425 int len;
427 ptr = strchr(line, '.');
428 if (!ptr || ptr[1] != '.' || 40 < ptr - line)
429 return 0;
430 len = ptr - line;
431 memcpy(patch->old_sha1_prefix, line, len);
432 patch->old_sha1_prefix[len] = 0;
434 line = ptr + 2;
435 ptr = strchr(line, ' ');
436 eol = strchr(line, '\n');
438 if (!ptr || eol < ptr)
439 ptr = eol;
440 len = ptr - line;
442 if (40 < len)
443 return 0;
444 memcpy(patch->new_sha1_prefix, line, len);
445 patch->new_sha1_prefix[len] = 0;
446 if (*ptr == ' ')
447 patch->new_mode = patch->old_mode = strtoul(ptr+1, NULL, 8);
448 return 0;
452 * This is normal for a diff that doesn't change anything: we'll fall through
453 * into the next diff. Tell the parser to break out.
455 static int gitdiff_unrecognized(const char *line, struct patch *patch)
457 return -1;
460 static const char *stop_at_slash(const char *line, int llen)
462 int i;
464 for (i = 0; i < llen; i++) {
465 int ch = line[i];
466 if (ch == '/')
467 return line + i;
469 return NULL;
472 /* This is to extract the same name that appears on "diff --git"
473 * line. We do not find and return anything if it is a rename
474 * patch, and it is OK because we will find the name elsewhere.
475 * We need to reliably find name only when it is mode-change only,
476 * creation or deletion of an empty file. In any of these cases,
477 * both sides are the same name under a/ and b/ respectively.
479 static char *git_header_name(char *line, int llen)
481 int len;
482 const char *name;
483 const char *second = NULL;
485 line += strlen("diff --git ");
486 llen -= strlen("diff --git ");
488 if (*line == '"') {
489 const char *cp;
490 char *first = unquote_c_style(line, &second);
491 if (!first)
492 return NULL;
494 /* advance to the first slash */
495 cp = stop_at_slash(first, strlen(first));
496 if (!cp || cp == first) {
497 /* we do not accept absolute paths */
498 free_first_and_fail:
499 free(first);
500 return NULL;
502 len = strlen(cp+1);
503 memmove(first, cp+1, len+1); /* including NUL */
505 /* second points at one past closing dq of name.
506 * find the second name.
508 while ((second < line + llen) && isspace(*second))
509 second++;
511 if (line + llen <= second)
512 goto free_first_and_fail;
513 if (*second == '"') {
514 char *sp = unquote_c_style(second, NULL);
515 if (!sp)
516 goto free_first_and_fail;
517 cp = stop_at_slash(sp, strlen(sp));
518 if (!cp || cp == sp) {
519 free_both_and_fail:
520 free(sp);
521 goto free_first_and_fail;
523 /* They must match, otherwise ignore */
524 if (strcmp(cp+1, first))
525 goto free_both_and_fail;
526 free(sp);
527 return first;
530 /* unquoted second */
531 cp = stop_at_slash(second, line + llen - second);
532 if (!cp || cp == second)
533 goto free_first_and_fail;
534 cp++;
535 if (line + llen - cp != len + 1 ||
536 memcmp(first, cp, len))
537 goto free_first_and_fail;
538 return first;
541 /* unquoted first name */
542 name = stop_at_slash(line, llen);
543 if (!name || name == line)
544 return NULL;
546 name++;
548 /* since the first name is unquoted, a dq if exists must be
549 * the beginning of the second name.
551 for (second = name; second < line + llen; second++) {
552 if (*second == '"') {
553 const char *cp = second;
554 const char *np;
555 char *sp = unquote_c_style(second, NULL);
557 if (!sp)
558 return NULL;
559 np = stop_at_slash(sp, strlen(sp));
560 if (!np || np == sp) {
561 free_second_and_fail:
562 free(sp);
563 return NULL;
565 np++;
566 len = strlen(np);
567 if (len < cp - name &&
568 !strncmp(np, name, len) &&
569 isspace(name[len])) {
570 /* Good */
571 memmove(sp, np, len + 1);
572 return sp;
574 goto free_second_and_fail;
579 * Accept a name only if it shows up twice, exactly the same
580 * form.
582 for (len = 0 ; ; len++) {
583 char c = name[len];
585 switch (c) {
586 default:
587 continue;
588 case '\n':
589 return NULL;
590 case '\t': case ' ':
591 second = name+len;
592 for (;;) {
593 char c = *second++;
594 if (c == '\n')
595 return NULL;
596 if (c == '/')
597 break;
599 if (second[len] == '\n' && !memcmp(name, second, len)) {
600 char *ret = xmalloc(len + 1);
601 memcpy(ret, name, len);
602 ret[len] = 0;
603 return ret;
607 return NULL;
610 /* Verify that we recognize the lines following a git header */
611 static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
613 unsigned long offset;
615 /* A git diff has explicit new/delete information, so we don't guess */
616 patch->is_new = 0;
617 patch->is_delete = 0;
620 * Some things may not have the old name in the
621 * rest of the headers anywhere (pure mode changes,
622 * or removing or adding empty files), so we get
623 * the default name from the header.
625 patch->def_name = git_header_name(line, len);
627 line += len;
628 size -= len;
629 linenr++;
630 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
631 static const struct opentry {
632 const char *str;
633 int (*fn)(const char *, struct patch *);
634 } optable[] = {
635 { "@@ -", gitdiff_hdrend },
636 { "--- ", gitdiff_oldname },
637 { "+++ ", gitdiff_newname },
638 { "old mode ", gitdiff_oldmode },
639 { "new mode ", gitdiff_newmode },
640 { "deleted file mode ", gitdiff_delete },
641 { "new file mode ", gitdiff_newfile },
642 { "copy from ", gitdiff_copysrc },
643 { "copy to ", gitdiff_copydst },
644 { "rename old ", gitdiff_renamesrc },
645 { "rename new ", gitdiff_renamedst },
646 { "rename from ", gitdiff_renamesrc },
647 { "rename to ", gitdiff_renamedst },
648 { "similarity index ", gitdiff_similarity },
649 { "dissimilarity index ", gitdiff_dissimilarity },
650 { "index ", gitdiff_index },
651 { "", gitdiff_unrecognized },
653 int i;
655 len = linelen(line, size);
656 if (!len || line[len-1] != '\n')
657 break;
658 for (i = 0; i < ARRAY_SIZE(optable); i++) {
659 const struct opentry *p = optable + i;
660 int oplen = strlen(p->str);
661 if (len < oplen || memcmp(p->str, line, oplen))
662 continue;
663 if (p->fn(line + oplen, patch) < 0)
664 return offset;
665 break;
669 return offset;
672 static int parse_num(const char *line, unsigned long *p)
674 char *ptr;
676 if (!isdigit(*line))
677 return 0;
678 *p = strtoul(line, &ptr, 10);
679 return ptr - line;
682 static int parse_range(const char *line, int len, int offset, const char *expect,
683 unsigned long *p1, unsigned long *p2)
685 int digits, ex;
687 if (offset < 0 || offset >= len)
688 return -1;
689 line += offset;
690 len -= offset;
692 digits = parse_num(line, p1);
693 if (!digits)
694 return -1;
696 offset += digits;
697 line += digits;
698 len -= digits;
700 *p2 = 1;
701 if (*line == ',') {
702 digits = parse_num(line+1, p2);
703 if (!digits)
704 return -1;
706 offset += digits+1;
707 line += digits+1;
708 len -= digits+1;
711 ex = strlen(expect);
712 if (ex > len)
713 return -1;
714 if (memcmp(line, expect, ex))
715 return -1;
717 return offset + ex;
721 * Parse a unified diff fragment header of the
722 * form "@@ -a,b +c,d @@"
724 static int parse_fragment_header(char *line, int len, struct fragment *fragment)
726 int offset;
728 if (!len || line[len-1] != '\n')
729 return -1;
731 /* Figure out the number of lines in a fragment */
732 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
733 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
735 return offset;
738 static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
740 unsigned long offset, len;
742 patch->is_rename = patch->is_copy = 0;
743 patch->is_new = patch->is_delete = -1;
744 patch->old_mode = patch->new_mode = 0;
745 patch->old_name = patch->new_name = NULL;
746 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
747 unsigned long nextlen;
749 len = linelen(line, size);
750 if (!len)
751 break;
753 /* Testing this early allows us to take a few shortcuts.. */
754 if (len < 6)
755 continue;
758 * Make sure we don't find any unconnected patch fragmants.
759 * That's a sign that we didn't find a header, and that a
760 * patch has become corrupted/broken up.
762 if (!memcmp("@@ -", line, 4)) {
763 struct fragment dummy;
764 if (parse_fragment_header(line, len, &dummy) < 0)
765 continue;
766 error("patch fragment without header at line %d: %.*s", linenr, (int)len-1, line);
769 if (size < len + 6)
770 break;
773 * Git patch? It might not have a real patch, just a rename
774 * or mode change, so we handle that specially
776 if (!memcmp("diff --git ", line, 11)) {
777 int git_hdr_len = parse_git_header(line, len, size, patch);
778 if (git_hdr_len <= len)
779 continue;
780 if (!patch->old_name && !patch->new_name) {
781 if (!patch->def_name)
782 die("git diff header lacks filename information (line %d)", linenr);
783 patch->old_name = patch->new_name = patch->def_name;
785 *hdrsize = git_hdr_len;
786 return offset;
789 /** --- followed by +++ ? */
790 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
791 continue;
794 * We only accept unified patches, so we want it to
795 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
796 * minimum
798 nextlen = linelen(line + len, size - len);
799 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
800 continue;
802 /* Ok, we'll consider it a patch */
803 parse_traditional_patch(line, line+len, patch);
804 *hdrsize = len + nextlen;
805 linenr += 2;
806 return offset;
808 return -1;
812 * Parse a unified diff. Note that this really needs
813 * to parse each fragment separately, since the only
814 * way to know the difference between a "---" that is
815 * part of a patch, and a "---" that starts the next
816 * patch is to look at the line counts..
818 static int parse_fragment(char *line, unsigned long size, struct patch *patch, struct fragment *fragment)
820 int added, deleted;
821 int len = linelen(line, size), offset;
822 unsigned long oldlines, newlines;
823 unsigned long leading, trailing;
825 offset = parse_fragment_header(line, len, fragment);
826 if (offset < 0)
827 return -1;
828 oldlines = fragment->oldlines;
829 newlines = fragment->newlines;
830 leading = 0;
831 trailing = 0;
833 if (patch->is_new < 0) {
834 patch->is_new = !oldlines;
835 if (!oldlines)
836 patch->old_name = NULL;
838 if (patch->is_delete < 0) {
839 patch->is_delete = !newlines;
840 if (!newlines)
841 patch->new_name = NULL;
844 if (patch->is_new && oldlines)
845 return error("new file depends on old contents");
846 if (patch->is_delete != !newlines) {
847 if (newlines)
848 return error("deleted file still has contents");
849 fprintf(stderr, "** warning: file %s becomes empty but is not deleted\n", patch->new_name);
852 /* Parse the thing.. */
853 line += len;
854 size -= len;
855 linenr++;
856 added = deleted = 0;
857 for (offset = len; size > 0; offset += len, size -= len, line += len, linenr++) {
858 if (!oldlines && !newlines)
859 break;
860 len = linelen(line, size);
861 if (!len || line[len-1] != '\n')
862 return -1;
863 switch (*line) {
864 default:
865 return -1;
866 case ' ':
867 oldlines--;
868 newlines--;
869 if (!deleted && !added)
870 leading++;
871 trailing++;
872 break;
873 case '-':
874 deleted++;
875 oldlines--;
876 trailing = 0;
877 break;
878 case '+':
880 * We know len is at least two, since we have a '+' and
881 * we checked that the last character was a '\n' above.
882 * That is, an addition of an empty line would check
883 * the '+' here. Sneaky...
885 if ((new_whitespace != nowarn_whitespace) &&
886 isspace(line[len-2])) {
887 whitespace_error++;
888 if (squelch_whitespace_errors &&
889 squelch_whitespace_errors <
890 whitespace_error)
892 else {
893 fprintf(stderr, "Adds trailing whitespace.\n%s:%d:%.*s\n",
894 patch_input_file,
895 linenr, len-2, line+1);
898 added++;
899 newlines--;
900 trailing = 0;
901 break;
903 /* We allow "\ No newline at end of file". Depending
904 * on locale settings when the patch was produced we
905 * don't know what this line looks like. The only
906 * thing we do know is that it begins with "\ ".
907 * Checking for 12 is just for sanity check -- any
908 * l10n of "\ No newline..." is at least that long.
910 case '\\':
911 if (len < 12 || memcmp(line, "\\ ", 2))
912 return -1;
913 break;
916 if (oldlines || newlines)
917 return -1;
918 fragment->leading = leading;
919 fragment->trailing = trailing;
921 /* If a fragment ends with an incomplete line, we failed to include
922 * it in the above loop because we hit oldlines == newlines == 0
923 * before seeing it.
925 if (12 < size && !memcmp(line, "\\ ", 2))
926 offset += linelen(line, size);
928 patch->lines_added += added;
929 patch->lines_deleted += deleted;
930 return offset;
933 static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
935 unsigned long offset = 0;
936 struct fragment **fragp = &patch->fragments;
938 while (size > 4 && !memcmp(line, "@@ -", 4)) {
939 struct fragment *fragment;
940 int len;
942 fragment = xcalloc(1, sizeof(*fragment));
943 len = parse_fragment(line, size, patch, fragment);
944 if (len <= 0)
945 die("corrupt patch at line %d", linenr);
947 fragment->patch = line;
948 fragment->size = len;
950 *fragp = fragment;
951 fragp = &fragment->next;
953 offset += len;
954 line += len;
955 size -= len;
957 return offset;
960 static inline int metadata_changes(struct patch *patch)
962 return patch->is_rename > 0 ||
963 patch->is_copy > 0 ||
964 patch->is_new > 0 ||
965 patch->is_delete ||
966 (patch->old_mode && patch->new_mode &&
967 patch->old_mode != patch->new_mode);
970 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
972 int hdrsize, patchsize;
973 int offset = find_header(buffer, size, &hdrsize, patch);
975 if (offset < 0)
976 return offset;
978 patchsize = parse_single_patch(buffer + offset + hdrsize, size - offset - hdrsize, patch);
980 if (!patchsize) {
981 static const char *binhdr[] = {
982 "Binary files ",
983 "Files ",
984 NULL,
986 int i;
987 int hd = hdrsize + offset;
988 unsigned long llen = linelen(buffer + hd, size - hd);
990 if (!memcmp(" differ\n", buffer + hd + llen - 8, 8))
991 for (i = 0; binhdr[i]; i++) {
992 int len = strlen(binhdr[i]);
993 if (len < size - hd &&
994 !memcmp(binhdr[i], buffer + hd, len)) {
995 patch->is_binary = 1;
996 break;
1000 /* Empty patch cannot be applied if:
1001 * - it is a binary patch and we do not do binary_replace, or
1002 * - text patch without metadata change
1004 if ((apply || check) &&
1005 (patch->is_binary
1006 ? !allow_binary_replacement
1007 : !metadata_changes(patch)))
1008 die("patch with only garbage at line %d", linenr);
1011 return offset + hdrsize + patchsize;
1014 static const char pluses[] = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1015 static const char minuses[]= "----------------------------------------------------------------------";
1017 static void show_stats(struct patch *patch)
1019 const char *prefix = "";
1020 char *name = patch->new_name;
1021 char *qname = NULL;
1022 int len, max, add, del, total;
1024 if (!name)
1025 name = patch->old_name;
1027 if (0 < (len = quote_c_style(name, NULL, NULL, 0))) {
1028 qname = xmalloc(len + 1);
1029 quote_c_style(name, qname, NULL, 0);
1030 name = qname;
1034 * "scale" the filename
1036 len = strlen(name);
1037 max = max_len;
1038 if (max > 50)
1039 max = 50;
1040 if (len > max) {
1041 char *slash;
1042 prefix = "...";
1043 max -= 3;
1044 name += len - max;
1045 slash = strchr(name, '/');
1046 if (slash)
1047 name = slash;
1049 len = max;
1052 * scale the add/delete
1054 max = max_change;
1055 if (max + len > 70)
1056 max = 70 - len;
1058 add = patch->lines_added;
1059 del = patch->lines_deleted;
1060 total = add + del;
1062 if (max_change > 0) {
1063 total = (total * max + max_change / 2) / max_change;
1064 add = (add * max + max_change / 2) / max_change;
1065 del = total - add;
1067 if (patch->is_binary)
1068 printf(" %s%-*s | Bin\n", prefix, len, name);
1069 else
1070 printf(" %s%-*s |%5d %.*s%.*s\n", prefix,
1071 len, name, patch->lines_added + patch->lines_deleted,
1072 add, pluses, del, minuses);
1073 if (qname)
1074 free(qname);
1077 static int read_old_data(struct stat *st, const char *path, void *buf, unsigned long size)
1079 int fd;
1080 unsigned long got;
1082 switch (st->st_mode & S_IFMT) {
1083 case S_IFLNK:
1084 return readlink(path, buf, size);
1085 case S_IFREG:
1086 fd = open(path, O_RDONLY);
1087 if (fd < 0)
1088 return error("unable to open %s", path);
1089 got = 0;
1090 for (;;) {
1091 int ret = xread(fd, buf + got, size - got);
1092 if (ret <= 0)
1093 break;
1094 got += ret;
1096 close(fd);
1097 return got;
1099 default:
1100 return -1;
1104 static int find_offset(const char *buf, unsigned long size, const char *fragment, unsigned long fragsize, int line, int *lines)
1106 int i;
1107 unsigned long start, backwards, forwards;
1109 if (fragsize > size)
1110 return -1;
1112 start = 0;
1113 if (line > 1) {
1114 unsigned long offset = 0;
1115 i = line-1;
1116 while (offset + fragsize <= size) {
1117 if (buf[offset++] == '\n') {
1118 start = offset;
1119 if (!--i)
1120 break;
1125 /* Exact line number? */
1126 if (!memcmp(buf + start, fragment, fragsize))
1127 return start;
1130 * There's probably some smart way to do this, but I'll leave
1131 * that to the smart and beautiful people. I'm simple and stupid.
1133 backwards = start;
1134 forwards = start;
1135 for (i = 0; ; i++) {
1136 unsigned long try;
1137 int n;
1139 /* "backward" */
1140 if (i & 1) {
1141 if (!backwards) {
1142 if (forwards + fragsize > size)
1143 break;
1144 continue;
1146 do {
1147 --backwards;
1148 } while (backwards && buf[backwards-1] != '\n');
1149 try = backwards;
1150 } else {
1151 while (forwards + fragsize <= size) {
1152 if (buf[forwards++] == '\n')
1153 break;
1155 try = forwards;
1158 if (try + fragsize > size)
1159 continue;
1160 if (memcmp(buf + try, fragment, fragsize))
1161 continue;
1162 n = (i >> 1)+1;
1163 if (i & 1)
1164 n = -n;
1165 *lines = n;
1166 return try;
1170 * We should start searching forward and backward.
1172 return -1;
1175 static void remove_first_line(const char **rbuf, int *rsize)
1177 const char *buf = *rbuf;
1178 int size = *rsize;
1179 unsigned long offset;
1180 offset = 0;
1181 while (offset <= size) {
1182 if (buf[offset++] == '\n')
1183 break;
1185 *rsize = size - offset;
1186 *rbuf = buf + offset;
1189 static void remove_last_line(const char **rbuf, int *rsize)
1191 const char *buf = *rbuf;
1192 int size = *rsize;
1193 unsigned long offset;
1194 offset = size - 1;
1195 while (offset > 0) {
1196 if (buf[--offset] == '\n')
1197 break;
1199 *rsize = offset + 1;
1202 struct buffer_desc {
1203 char *buffer;
1204 unsigned long size;
1205 unsigned long alloc;
1208 static int apply_line(char *output, const char *patch, int plen)
1210 /* plen is number of bytes to be copied from patch,
1211 * starting at patch+1 (patch[0] is '+'). Typically
1212 * patch[plen] is '\n'.
1214 int add_nl_to_tail = 0;
1215 if ((new_whitespace == strip_whitespace) &&
1216 1 < plen && isspace(patch[plen-1])) {
1217 if (patch[plen] == '\n')
1218 add_nl_to_tail = 1;
1219 plen--;
1220 while (0 < plen && isspace(patch[plen]))
1221 plen--;
1222 applied_after_stripping++;
1224 memcpy(output, patch + 1, plen);
1225 if (add_nl_to_tail)
1226 output[plen++] = '\n';
1227 return plen;
1230 static int apply_one_fragment(struct buffer_desc *desc, struct fragment *frag)
1232 char *buf = desc->buffer;
1233 const char *patch = frag->patch;
1234 int offset, size = frag->size;
1235 char *old = xmalloc(size);
1236 char *new = xmalloc(size);
1237 const char *oldlines, *newlines;
1238 int oldsize = 0, newsize = 0;
1239 unsigned long leading, trailing;
1240 int pos, lines;
1242 while (size > 0) {
1243 int len = linelen(patch, size);
1244 int plen;
1246 if (!len)
1247 break;
1250 * "plen" is how much of the line we should use for
1251 * the actual patch data. Normally we just remove the
1252 * first character on the line, but if the line is
1253 * followed by "\ No newline", then we also remove the
1254 * last one (which is the newline, of course).
1256 plen = len-1;
1257 if (len < size && patch[len] == '\\')
1258 plen--;
1259 switch (*patch) {
1260 case ' ':
1261 case '-':
1262 memcpy(old + oldsize, patch + 1, plen);
1263 oldsize += plen;
1264 if (*patch == '-')
1265 break;
1266 /* Fall-through for ' ' */
1267 case '+':
1268 if (*patch != '+' || !no_add)
1269 newsize += apply_line(new + newsize, patch,
1270 plen);
1271 break;
1272 case '@': case '\\':
1273 /* Ignore it, we already handled it */
1274 break;
1275 default:
1276 return -1;
1278 patch += len;
1279 size -= len;
1282 #ifdef NO_ACCURATE_DIFF
1283 if (oldsize > 0 && old[oldsize - 1] == '\n' &&
1284 newsize > 0 && new[newsize - 1] == '\n') {
1285 oldsize--;
1286 newsize--;
1288 #endif
1290 oldlines = old;
1291 newlines = new;
1292 leading = frag->leading;
1293 trailing = frag->trailing;
1294 lines = 0;
1295 pos = frag->newpos;
1296 for (;;) {
1297 offset = find_offset(buf, desc->size, oldlines, oldsize, pos, &lines);
1298 if (offset >= 0) {
1299 int diff = newsize - oldsize;
1300 unsigned long size = desc->size + diff;
1301 unsigned long alloc = desc->alloc;
1303 /* Warn if it was necessary to reduce the number
1304 * of context lines.
1306 if ((leading != frag->leading) || (trailing != frag->trailing))
1307 fprintf(stderr, "Context reduced to (%ld/%ld) to apply fragment at %d\n",
1308 leading, trailing, pos + lines);
1310 if (size > alloc) {
1311 alloc = size + 8192;
1312 desc->alloc = alloc;
1313 buf = xrealloc(buf, alloc);
1314 desc->buffer = buf;
1316 desc->size = size;
1317 memmove(buf + offset + newsize, buf + offset + oldsize, size - offset - newsize);
1318 memcpy(buf + offset, newlines, newsize);
1319 offset = 0;
1321 break;
1324 /* Am I at my context limits? */
1325 if ((leading <= p_context) && (trailing <= p_context))
1326 break;
1327 /* Reduce the number of context lines
1328 * Reduce both leading and trailing if they are equal
1329 * otherwise just reduce the larger context.
1331 if (leading >= trailing) {
1332 remove_first_line(&oldlines, &oldsize);
1333 remove_first_line(&newlines, &newsize);
1334 pos--;
1335 leading--;
1337 if (trailing > leading) {
1338 remove_last_line(&oldlines, &oldsize);
1339 remove_last_line(&newlines, &newsize);
1340 trailing--;
1344 free(old);
1345 free(new);
1346 return offset;
1349 static int apply_fragments(struct buffer_desc *desc, struct patch *patch)
1351 struct fragment *frag = patch->fragments;
1352 const char *name = patch->old_name ? patch->old_name : patch->new_name;
1354 if (patch->is_binary) {
1355 unsigned char sha1[20];
1357 if (!allow_binary_replacement)
1358 return error("cannot apply binary patch to '%s' "
1359 "without --allow-binary-replacement",
1360 name);
1362 /* For safety, we require patch index line to contain
1363 * full 40-byte textual SHA1 for old and new, at least for now.
1365 if (strlen(patch->old_sha1_prefix) != 40 ||
1366 strlen(patch->new_sha1_prefix) != 40 ||
1367 get_sha1_hex(patch->old_sha1_prefix, sha1) ||
1368 get_sha1_hex(patch->new_sha1_prefix, sha1))
1369 return error("cannot apply binary patch to '%s' "
1370 "without full index line", name);
1372 if (patch->old_name) {
1373 unsigned char hdr[50];
1374 int hdrlen;
1376 /* See if the old one matches what the patch
1377 * applies to.
1379 write_sha1_file_prepare(desc->buffer, desc->size,
1380 blob_type, sha1, hdr, &hdrlen);
1381 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
1382 return error("the patch applies to '%s' (%s), "
1383 "which does not match the "
1384 "current contents.",
1385 name, sha1_to_hex(sha1));
1387 else {
1388 /* Otherwise, the old one must be empty. */
1389 if (desc->size)
1390 return error("the patch applies to an empty "
1391 "'%s' but it is not empty", name);
1394 /* For now, we do not record post-image data in the patch,
1395 * and require the object already present in the recipient's
1396 * object database.
1398 if (desc->buffer) {
1399 free(desc->buffer);
1400 desc->alloc = desc->size = 0;
1402 get_sha1_hex(patch->new_sha1_prefix, sha1);
1404 if (memcmp(sha1, null_sha1, 20)) {
1405 char type[10];
1406 unsigned long size;
1408 desc->buffer = read_sha1_file(sha1, type, &size);
1409 if (!desc->buffer)
1410 return error("the necessary postimage %s for "
1411 "'%s' does not exist",
1412 patch->new_sha1_prefix, name);
1413 desc->alloc = desc->size = size;
1416 return 0;
1419 while (frag) {
1420 if (apply_one_fragment(desc, frag) < 0)
1421 return error("patch failed: %s:%ld",
1422 name, frag->oldpos);
1423 frag = frag->next;
1425 return 0;
1428 static int apply_data(struct patch *patch, struct stat *st)
1430 char *buf;
1431 unsigned long size, alloc;
1432 struct buffer_desc desc;
1434 size = 0;
1435 alloc = 0;
1436 buf = NULL;
1437 if (patch->old_name) {
1438 size = st->st_size;
1439 alloc = size + 8192;
1440 buf = xmalloc(alloc);
1441 if (read_old_data(st, patch->old_name, buf, alloc) != size)
1442 return error("read of %s failed", patch->old_name);
1445 desc.size = size;
1446 desc.alloc = alloc;
1447 desc.buffer = buf;
1448 if (apply_fragments(&desc, patch) < 0)
1449 return -1;
1450 patch->result = desc.buffer;
1451 patch->resultsize = desc.size;
1453 if (patch->is_delete && patch->resultsize)
1454 return error("removal patch leaves file contents");
1456 return 0;
1459 static int check_patch(struct patch *patch)
1461 struct stat st;
1462 const char *old_name = patch->old_name;
1463 const char *new_name = patch->new_name;
1464 const char *name = old_name ? old_name : new_name;
1466 if (old_name) {
1467 int changed;
1468 int stat_ret = lstat(old_name, &st);
1470 if (check_index) {
1471 int pos = cache_name_pos(old_name, strlen(old_name));
1472 if (pos < 0)
1473 return error("%s: does not exist in index",
1474 old_name);
1475 if (stat_ret < 0) {
1476 struct checkout costate;
1477 if (errno != ENOENT)
1478 return error("%s: %s", old_name,
1479 strerror(errno));
1480 /* checkout */
1481 costate.base_dir = "";
1482 costate.base_dir_len = 0;
1483 costate.force = 0;
1484 costate.quiet = 0;
1485 costate.not_new = 0;
1486 costate.refresh_cache = 1;
1487 if (checkout_entry(active_cache[pos],
1488 &costate,
1489 NULL) ||
1490 lstat(old_name, &st))
1491 return -1;
1494 changed = ce_match_stat(active_cache[pos], &st, 1);
1495 if (changed)
1496 return error("%s: does not match index",
1497 old_name);
1499 else if (stat_ret < 0)
1500 return error("%s: %s", old_name, strerror(errno));
1502 if (patch->is_new < 0)
1503 patch->is_new = 0;
1504 st.st_mode = ntohl(create_ce_mode(st.st_mode));
1505 if (!patch->old_mode)
1506 patch->old_mode = st.st_mode;
1507 if ((st.st_mode ^ patch->old_mode) & S_IFMT)
1508 return error("%s: wrong type", old_name);
1509 if (st.st_mode != patch->old_mode)
1510 fprintf(stderr, "warning: %s has type %o, expected %o\n",
1511 old_name, st.st_mode, patch->old_mode);
1514 if (new_name && (patch->is_new | patch->is_rename | patch->is_copy)) {
1515 if (check_index && cache_name_pos(new_name, strlen(new_name)) >= 0)
1516 return error("%s: already exists in index", new_name);
1517 if (!lstat(new_name, &st))
1518 return error("%s: already exists in working directory", new_name);
1519 if (errno != ENOENT)
1520 return error("%s: %s", new_name, strerror(errno));
1521 if (!patch->new_mode) {
1522 if (patch->is_new)
1523 patch->new_mode = S_IFREG | 0644;
1524 else
1525 patch->new_mode = patch->old_mode;
1529 if (new_name && old_name) {
1530 int same = !strcmp(old_name, new_name);
1531 if (!patch->new_mode)
1532 patch->new_mode = patch->old_mode;
1533 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
1534 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
1535 patch->new_mode, new_name, patch->old_mode,
1536 same ? "" : " of ", same ? "" : old_name);
1539 if (apply_data(patch, &st) < 0)
1540 return error("%s: patch does not apply", name);
1541 return 0;
1544 static int check_patch_list(struct patch *patch)
1546 int error = 0;
1548 for (;patch ; patch = patch->next)
1549 error |= check_patch(patch);
1550 return error;
1553 static inline int is_null_sha1(const unsigned char *sha1)
1555 return !memcmp(sha1, null_sha1, 20);
1558 static void show_index_list(struct patch *list)
1560 struct patch *patch;
1562 /* Once we start supporting the reverse patch, it may be
1563 * worth showing the new sha1 prefix, but until then...
1565 for (patch = list; patch; patch = patch->next) {
1566 const unsigned char *sha1_ptr;
1567 unsigned char sha1[20];
1568 const char *name;
1570 name = patch->old_name ? patch->old_name : patch->new_name;
1571 if (patch->is_new)
1572 sha1_ptr = null_sha1;
1573 else if (get_sha1(patch->old_sha1_prefix, sha1))
1574 die("sha1 information is lacking or useless (%s).",
1575 name);
1576 else
1577 sha1_ptr = sha1;
1579 printf("%06o %s ",patch->old_mode, sha1_to_hex(sha1_ptr));
1580 if (line_termination && quote_c_style(name, NULL, NULL, 0))
1581 quote_c_style(name, NULL, stdout, 0);
1582 else
1583 fputs(name, stdout);
1584 putchar(line_termination);
1588 static void stat_patch_list(struct patch *patch)
1590 int files, adds, dels;
1592 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
1593 files++;
1594 adds += patch->lines_added;
1595 dels += patch->lines_deleted;
1596 show_stats(patch);
1599 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
1602 static void numstat_patch_list(struct patch *patch)
1604 for ( ; patch; patch = patch->next) {
1605 const char *name;
1606 name = patch->old_name ? patch->old_name : patch->new_name;
1607 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
1608 if (line_termination && quote_c_style(name, NULL, NULL, 0))
1609 quote_c_style(name, NULL, stdout, 0);
1610 else
1611 fputs(name, stdout);
1612 putchar('\n');
1616 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
1618 if (mode)
1619 printf(" %s mode %06o %s\n", newdelete, mode, name);
1620 else
1621 printf(" %s %s\n", newdelete, name);
1624 static void show_mode_change(struct patch *p, int show_name)
1626 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
1627 if (show_name)
1628 printf(" mode change %06o => %06o %s\n",
1629 p->old_mode, p->new_mode, p->new_name);
1630 else
1631 printf(" mode change %06o => %06o\n",
1632 p->old_mode, p->new_mode);
1636 static void show_rename_copy(struct patch *p)
1638 const char *renamecopy = p->is_rename ? "rename" : "copy";
1639 const char *old, *new;
1641 /* Find common prefix */
1642 old = p->old_name;
1643 new = p->new_name;
1644 while (1) {
1645 const char *slash_old, *slash_new;
1646 slash_old = strchr(old, '/');
1647 slash_new = strchr(new, '/');
1648 if (!slash_old ||
1649 !slash_new ||
1650 slash_old - old != slash_new - new ||
1651 memcmp(old, new, slash_new - new))
1652 break;
1653 old = slash_old + 1;
1654 new = slash_new + 1;
1656 /* p->old_name thru old is the common prefix, and old and new
1657 * through the end of names are renames
1659 if (old != p->old_name)
1660 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
1661 (int)(old - p->old_name), p->old_name,
1662 old, new, p->score);
1663 else
1664 printf(" %s %s => %s (%d%%)\n", renamecopy,
1665 p->old_name, p->new_name, p->score);
1666 show_mode_change(p, 0);
1669 static void summary_patch_list(struct patch *patch)
1671 struct patch *p;
1673 for (p = patch; p; p = p->next) {
1674 if (p->is_new)
1675 show_file_mode_name("create", p->new_mode, p->new_name);
1676 else if (p->is_delete)
1677 show_file_mode_name("delete", p->old_mode, p->old_name);
1678 else {
1679 if (p->is_rename || p->is_copy)
1680 show_rename_copy(p);
1681 else {
1682 if (p->score) {
1683 printf(" rewrite %s (%d%%)\n",
1684 p->new_name, p->score);
1685 show_mode_change(p, 0);
1687 else
1688 show_mode_change(p, 1);
1694 static void patch_stats(struct patch *patch)
1696 int lines = patch->lines_added + patch->lines_deleted;
1698 if (lines > max_change)
1699 max_change = lines;
1700 if (patch->old_name) {
1701 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
1702 if (!len)
1703 len = strlen(patch->old_name);
1704 if (len > max_len)
1705 max_len = len;
1707 if (patch->new_name) {
1708 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
1709 if (!len)
1710 len = strlen(patch->new_name);
1711 if (len > max_len)
1712 max_len = len;
1716 static void remove_file(struct patch *patch)
1718 if (write_index) {
1719 if (remove_file_from_cache(patch->old_name) < 0)
1720 die("unable to remove %s from index", patch->old_name);
1722 unlink(patch->old_name);
1725 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
1727 struct stat st;
1728 struct cache_entry *ce;
1729 int namelen = strlen(path);
1730 unsigned ce_size = cache_entry_size(namelen);
1732 if (!write_index)
1733 return;
1735 ce = xcalloc(1, ce_size);
1736 memcpy(ce->name, path, namelen);
1737 ce->ce_mode = create_ce_mode(mode);
1738 ce->ce_flags = htons(namelen);
1739 if (lstat(path, &st) < 0)
1740 die("unable to stat newly created file %s", path);
1741 fill_stat_cache_info(ce, &st);
1742 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
1743 die("unable to create backing store for newly created file %s", path);
1744 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
1745 die("unable to add cache entry for %s", path);
1748 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
1750 int fd;
1752 if (S_ISLNK(mode))
1753 return symlink(buf, path);
1754 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
1755 if (fd < 0)
1756 return -1;
1757 while (size) {
1758 int written = xwrite(fd, buf, size);
1759 if (written < 0)
1760 die("writing file %s: %s", path, strerror(errno));
1761 if (!written)
1762 die("out of space writing file %s", path);
1763 buf += written;
1764 size -= written;
1766 if (close(fd) < 0)
1767 die("closing file %s: %s", path, strerror(errno));
1768 return 0;
1772 * We optimistically assume that the directories exist,
1773 * which is true 99% of the time anyway. If they don't,
1774 * we create them and try again.
1776 static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
1778 if (!try_create_file(path, mode, buf, size))
1779 return;
1781 if (errno == ENOENT) {
1782 if (safe_create_leading_directories(path))
1783 return;
1784 if (!try_create_file(path, mode, buf, size))
1785 return;
1788 if (errno == EEXIST) {
1789 unsigned int nr = getpid();
1791 for (;;) {
1792 const char *newpath;
1793 newpath = mkpath("%s~%u", path, nr);
1794 if (!try_create_file(newpath, mode, buf, size)) {
1795 if (!rename(newpath, path))
1796 return;
1797 unlink(newpath);
1798 break;
1800 if (errno != EEXIST)
1801 break;
1802 ++nr;
1805 die("unable to write file %s mode %o", path, mode);
1808 static void create_file(struct patch *patch)
1810 char *path = patch->new_name;
1811 unsigned mode = patch->new_mode;
1812 unsigned long size = patch->resultsize;
1813 char *buf = patch->result;
1815 if (!mode)
1816 mode = S_IFREG | 0644;
1817 create_one_file(path, mode, buf, size);
1818 add_index_file(path, mode, buf, size);
1821 static void write_out_one_result(struct patch *patch)
1823 if (patch->is_delete > 0) {
1824 remove_file(patch);
1825 return;
1827 if (patch->is_new > 0 || patch->is_copy) {
1828 create_file(patch);
1829 return;
1832 * Rename or modification boils down to the same
1833 * thing: remove the old, write the new
1835 remove_file(patch);
1836 create_file(patch);
1839 static void write_out_results(struct patch *list, int skipped_patch)
1841 if (!list && !skipped_patch)
1842 die("No changes");
1844 while (list) {
1845 write_out_one_result(list);
1846 list = list->next;
1850 static struct cache_file cache_file;
1852 static struct excludes {
1853 struct excludes *next;
1854 const char *path;
1855 } *excludes;
1857 static int use_patch(struct patch *p)
1859 const char *pathname = p->new_name ? p->new_name : p->old_name;
1860 struct excludes *x = excludes;
1861 while (x) {
1862 if (fnmatch(x->path, pathname, 0) == 0)
1863 return 0;
1864 x = x->next;
1866 if (0 < prefix_length) {
1867 int pathlen = strlen(pathname);
1868 if (pathlen <= prefix_length ||
1869 memcmp(prefix, pathname, prefix_length))
1870 return 0;
1872 return 1;
1875 static int apply_patch(int fd, const char *filename)
1877 unsigned long offset, size;
1878 char *buffer = read_patch_file(fd, &size);
1879 struct patch *list = NULL, **listp = &list;
1880 int skipped_patch = 0;
1882 patch_input_file = filename;
1883 if (!buffer)
1884 return -1;
1885 offset = 0;
1886 while (size > 0) {
1887 struct patch *patch;
1888 int nr;
1890 patch = xcalloc(1, sizeof(*patch));
1891 nr = parse_chunk(buffer + offset, size, patch);
1892 if (nr < 0)
1893 break;
1894 if (use_patch(patch)) {
1895 patch_stats(patch);
1896 *listp = patch;
1897 listp = &patch->next;
1898 } else {
1899 /* perhaps free it a bit better? */
1900 free(patch);
1901 skipped_patch++;
1903 offset += nr;
1904 size -= nr;
1907 if (whitespace_error && (new_whitespace == error_on_whitespace))
1908 apply = 0;
1910 write_index = check_index && apply;
1911 if (write_index && newfd < 0)
1912 newfd = hold_index_file_for_update(&cache_file, get_index_file());
1913 if (check_index) {
1914 if (read_cache() < 0)
1915 die("unable to read index file");
1918 if ((check || apply) && check_patch_list(list) < 0)
1919 exit(1);
1921 if (apply)
1922 write_out_results(list, skipped_patch);
1924 if (show_index_info)
1925 show_index_list(list);
1927 if (diffstat)
1928 stat_patch_list(list);
1930 if (numstat)
1931 numstat_patch_list(list);
1933 if (summary)
1934 summary_patch_list(list);
1936 free(buffer);
1937 return 0;
1940 static int git_apply_config(const char *var, const char *value)
1942 if (!strcmp(var, "apply.whitespace")) {
1943 apply_default_whitespace = strdup(value);
1944 return 0;
1946 return git_default_config(var, value);
1950 int main(int argc, char **argv)
1952 int i;
1953 int read_stdin = 1;
1954 const char *whitespace_option = NULL;
1956 for (i = 1; i < argc; i++) {
1957 const char *arg = argv[i];
1958 char *end;
1959 int fd;
1961 if (!strcmp(arg, "-")) {
1962 apply_patch(0, "<stdin>");
1963 read_stdin = 0;
1964 continue;
1966 if (!strncmp(arg, "--exclude=", 10)) {
1967 struct excludes *x = xmalloc(sizeof(*x));
1968 x->path = arg + 10;
1969 x->next = excludes;
1970 excludes = x;
1971 continue;
1973 if (!strncmp(arg, "-p", 2)) {
1974 p_value = atoi(arg + 2);
1975 continue;
1977 if (!strcmp(arg, "--no-add")) {
1978 no_add = 1;
1979 continue;
1981 if (!strcmp(arg, "--stat")) {
1982 apply = 0;
1983 diffstat = 1;
1984 continue;
1986 if (!strcmp(arg, "--allow-binary-replacement")) {
1987 allow_binary_replacement = 1;
1988 continue;
1990 if (!strcmp(arg, "--numstat")) {
1991 apply = 0;
1992 numstat = 1;
1993 continue;
1995 if (!strcmp(arg, "--summary")) {
1996 apply = 0;
1997 summary = 1;
1998 continue;
2000 if (!strcmp(arg, "--check")) {
2001 apply = 0;
2002 check = 1;
2003 continue;
2005 if (!strcmp(arg, "--index")) {
2006 check_index = 1;
2007 continue;
2009 if (!strcmp(arg, "--apply")) {
2010 apply = 1;
2011 continue;
2013 if (!strcmp(arg, "--index-info")) {
2014 apply = 0;
2015 show_index_info = 1;
2016 continue;
2018 if (!strcmp(arg, "-z")) {
2019 line_termination = 0;
2020 continue;
2022 if (!strncmp(arg, "-C", 2)) {
2023 p_context = strtoul(arg + 2, &end, 0);
2024 if (*end != '\0')
2025 die("unrecognized context count '%s'", arg + 2);
2026 continue;
2028 if (!strncmp(arg, "--whitespace=", 13)) {
2029 whitespace_option = arg + 13;
2030 parse_whitespace_option(arg + 13);
2031 continue;
2034 if (check_index && prefix_length < 0) {
2035 prefix = setup_git_directory();
2036 prefix_length = prefix ? strlen(prefix) : 0;
2037 git_config(git_apply_config);
2038 if (!whitespace_option && apply_default_whitespace)
2039 parse_whitespace_option(apply_default_whitespace);
2041 if (0 < prefix_length)
2042 arg = prefix_filename(prefix, prefix_length, arg);
2044 fd = open(arg, O_RDONLY);
2045 if (fd < 0)
2046 usage(apply_usage);
2047 read_stdin = 0;
2048 set_default_whitespace_mode(whitespace_option);
2049 apply_patch(fd, arg);
2050 close(fd);
2052 set_default_whitespace_mode(whitespace_option);
2053 if (read_stdin)
2054 apply_patch(0, "<stdin>");
2055 if (whitespace_error) {
2056 if (squelch_whitespace_errors &&
2057 squelch_whitespace_errors < whitespace_error) {
2058 int squelched =
2059 whitespace_error - squelch_whitespace_errors;
2060 fprintf(stderr, "warning: squelched %d whitespace error%s\n",
2061 squelched,
2062 squelched == 1 ? "" : "s");
2064 if (new_whitespace == error_on_whitespace)
2065 die("%d line%s add%s trailing whitespaces.",
2066 whitespace_error,
2067 whitespace_error == 1 ? "" : "s",
2068 whitespace_error == 1 ? "s" : "");
2069 if (applied_after_stripping)
2070 fprintf(stderr, "warning: %d line%s applied after"
2071 " stripping trailing whitespaces.\n",
2072 applied_after_stripping,
2073 applied_after_stripping == 1 ? "" : "s");
2074 else if (whitespace_error)
2075 fprintf(stderr, "warning: %d line%s add%s trailing"
2076 " whitespaces.\n",
2077 whitespace_error,
2078 whitespace_error == 1 ? "" : "s",
2079 whitespace_error == 1 ? "s" : "");
2082 if (write_index) {
2083 if (write_cache(newfd, active_cache, active_nr) ||
2084 commit_index_file(&cache_file))
2085 die("Unable to write new cachefile");
2088 return 0;