4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
11 #include "cache-tree.h"
17 // --check turns on checking that the working tree matches the
18 // files that are being modified, but doesn't apply the patch
19 // --stat does just a diffstat, and doesn't actually apply
20 // --numstat does numeric diffstat, and doesn't actually apply
21 // --index-info shows the old and new index info for paths if available.
22 // --index updates the cache as well.
23 // --cached updates only the cache without ever touching the working tree.
25 static const char *prefix
;
26 static int prefix_length
= -1;
27 static int newfd
= -1;
29 static int p_value
= 1;
30 static int allow_binary_replacement
= 0;
31 static int check_index
= 0;
32 static int write_index
= 0;
33 static int cached
= 0;
34 static int diffstat
= 0;
35 static int numstat
= 0;
36 static int summary
= 0;
39 static int no_add
= 0;
40 static int show_index_info
= 0;
41 static int line_termination
= '\n';
42 static unsigned long p_context
= -1;
43 static const char apply_usage
[] =
44 "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>...";
46 static enum whitespace_eol
{
51 } new_whitespace
= warn_on_whitespace
;
52 static int whitespace_error
= 0;
53 static int squelch_whitespace_errors
= 5;
54 static int applied_after_stripping
= 0;
55 static const char *patch_input_file
= NULL
;
57 static void parse_whitespace_option(const char *option
)
60 new_whitespace
= warn_on_whitespace
;
63 if (!strcmp(option
, "warn")) {
64 new_whitespace
= warn_on_whitespace
;
67 if (!strcmp(option
, "nowarn")) {
68 new_whitespace
= nowarn_whitespace
;
71 if (!strcmp(option
, "error")) {
72 new_whitespace
= error_on_whitespace
;
75 if (!strcmp(option
, "error-all")) {
76 new_whitespace
= error_on_whitespace
;
77 squelch_whitespace_errors
= 0;
80 if (!strcmp(option
, "strip")) {
81 new_whitespace
= strip_whitespace
;
84 die("unrecognized whitespace option '%s'", option
);
87 static void set_default_whitespace_mode(const char *whitespace_option
)
89 if (!whitespace_option
&& !apply_default_whitespace
) {
90 new_whitespace
= (apply
97 * For "diff-stat" like behaviour, we keep track of the biggest change
98 * we've seen, and the longest filename. That allows us to do simple
101 static int max_change
, max_len
;
104 * Various "current state", notably line numbers and what
105 * file (and how) we're patching right now.. The "is_xxxx"
106 * things are flags, where -1 means "don't know yet".
108 static int linenr
= 1;
111 unsigned long leading
, trailing
;
112 unsigned long oldpos
, oldlines
;
113 unsigned long newpos
, newlines
;
116 struct fragment
*next
;
120 char *new_name
, *old_name
, *def_name
;
121 unsigned int old_mode
, new_mode
;
122 int is_rename
, is_copy
, is_new
, is_delete
, is_binary
;
123 #define BINARY_DELTA_DEFLATED 1
124 #define BINARY_LITERAL_DEFLATED 2
125 unsigned long deflate_origlen
;
126 int lines_added
, lines_deleted
;
128 struct fragment
*fragments
;
130 unsigned long resultsize
;
131 char old_sha1_prefix
[41];
132 char new_sha1_prefix
[41];
136 #define CHUNKSIZE (8192)
139 static void *read_patch_file(int fd
, unsigned long *sizep
)
141 unsigned long size
= 0, alloc
= CHUNKSIZE
;
142 void *buffer
= xmalloc(alloc
);
145 int nr
= alloc
- size
;
148 buffer
= xrealloc(buffer
, alloc
);
151 nr
= xread(fd
, buffer
+ size
, nr
);
155 die("git-apply: read returned %s", strerror(errno
));
161 * Make sure that we have some slop in the buffer
162 * so that we can do speculative "memcmp" etc, and
163 * see to it that it is NUL-filled.
165 if (alloc
< size
+ SLOP
)
166 buffer
= xrealloc(buffer
, size
+ SLOP
);
167 memset(buffer
+ size
, 0, SLOP
);
171 static unsigned long linelen(const char *buffer
, unsigned long size
)
173 unsigned long len
= 0;
176 if (*buffer
++ == '\n')
182 static int is_dev_null(const char *str
)
184 return !memcmp("/dev/null", str
, 9) && isspace(str
[9]);
190 static int name_terminate(const char *name
, int namelen
, int c
, int terminate
)
192 if (c
== ' ' && !(terminate
& TERM_SPACE
))
194 if (c
== '\t' && !(terminate
& TERM_TAB
))
200 static char * find_name(const char *line
, char *def
, int p_value
, int terminate
)
203 const char *start
= line
;
207 /* Proposed "new-style" GNU patch/diff format; see
208 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
210 name
= unquote_c_style(line
, NULL
);
214 cp
= strchr(name
, '/');
221 /* name can later be freed, so we need
222 * to memmove, not just return cp
224 memmove(name
, cp
, strlen(cp
) + 1);
241 if (name_terminate(start
, line
-start
, c
, terminate
))
245 if (c
== '/' && !--p_value
)
255 * Generally we prefer the shorter name, especially
256 * if the other one is just a variation of that with
257 * something else tacked on to the end (ie "file.orig"
261 int deflen
= strlen(def
);
262 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
266 name
= xmalloc(len
+ 1);
267 memcpy(name
, start
, len
);
274 * Get the name etc info from the --/+++ lines of a traditional patch header
276 * NOTE! This hardcodes "-p1" behaviour in filename detection.
278 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
279 * files, we can happily check the index for a match, but for creating a
280 * new file we should try to match whatever "patch" does. I have no idea.
282 static void parse_traditional_patch(const char *first
, const char *second
, struct patch
*patch
)
286 first
+= 4; // skip "--- "
287 second
+= 4; // skip "+++ "
288 if (is_dev_null(first
)) {
290 patch
->is_delete
= 0;
291 name
= find_name(second
, NULL
, p_value
, TERM_SPACE
| TERM_TAB
);
292 patch
->new_name
= name
;
293 } else if (is_dev_null(second
)) {
295 patch
->is_delete
= 1;
296 name
= find_name(first
, NULL
, p_value
, TERM_SPACE
| TERM_TAB
);
297 patch
->old_name
= name
;
299 name
= find_name(first
, NULL
, p_value
, TERM_SPACE
| TERM_TAB
);
300 name
= find_name(second
, name
, p_value
, TERM_SPACE
| TERM_TAB
);
301 patch
->old_name
= patch
->new_name
= name
;
304 die("unable to find filename in patch at line %d", linenr
);
307 static int gitdiff_hdrend(const char *line
, struct patch
*patch
)
313 * We're anal about diff header consistency, to make
314 * sure that we don't end up having strange ambiguous
315 * patches floating around.
317 * As a result, gitdiff_{old|new}name() will check
318 * their names against any previous information, just
321 static char *gitdiff_verify_name(const char *line
, int isnull
, char *orig_name
, const char *oldnew
)
323 if (!orig_name
&& !isnull
)
324 return find_name(line
, NULL
, 1, 0);
333 die("git-apply: bad git-diff - expected /dev/null, got %s on line %d", name
, linenr
);
334 another
= find_name(line
, NULL
, 1, 0);
335 if (!another
|| memcmp(another
, name
, len
))
336 die("git-apply: bad git-diff - inconsistent %s filename on line %d", oldnew
, linenr
);
341 /* expect "/dev/null" */
342 if (memcmp("/dev/null", line
, 9) || line
[9] != '\n')
343 die("git-apply: bad git-diff - expected /dev/null on line %d", linenr
);
348 static int gitdiff_oldname(const char *line
, struct patch
*patch
)
350 patch
->old_name
= gitdiff_verify_name(line
, patch
->is_new
, patch
->old_name
, "old");
354 static int gitdiff_newname(const char *line
, struct patch
*patch
)
356 patch
->new_name
= gitdiff_verify_name(line
, patch
->is_delete
, patch
->new_name
, "new");
360 static int gitdiff_oldmode(const char *line
, struct patch
*patch
)
362 patch
->old_mode
= strtoul(line
, NULL
, 8);
366 static int gitdiff_newmode(const char *line
, struct patch
*patch
)
368 patch
->new_mode
= strtoul(line
, NULL
, 8);
372 static int gitdiff_delete(const char *line
, struct patch
*patch
)
374 patch
->is_delete
= 1;
375 patch
->old_name
= patch
->def_name
;
376 return gitdiff_oldmode(line
, patch
);
379 static int gitdiff_newfile(const char *line
, struct patch
*patch
)
382 patch
->new_name
= patch
->def_name
;
383 return gitdiff_newmode(line
, patch
);
386 static int gitdiff_copysrc(const char *line
, struct patch
*patch
)
389 patch
->old_name
= find_name(line
, NULL
, 0, 0);
393 static int gitdiff_copydst(const char *line
, struct patch
*patch
)
396 patch
->new_name
= find_name(line
, NULL
, 0, 0);
400 static int gitdiff_renamesrc(const char *line
, struct patch
*patch
)
402 patch
->is_rename
= 1;
403 patch
->old_name
= find_name(line
, NULL
, 0, 0);
407 static int gitdiff_renamedst(const char *line
, struct patch
*patch
)
409 patch
->is_rename
= 1;
410 patch
->new_name
= find_name(line
, NULL
, 0, 0);
414 static int gitdiff_similarity(const char *line
, struct patch
*patch
)
416 if ((patch
->score
= strtoul(line
, NULL
, 10)) == ULONG_MAX
)
421 static int gitdiff_dissimilarity(const char *line
, struct patch
*patch
)
423 if ((patch
->score
= strtoul(line
, NULL
, 10)) == ULONG_MAX
)
428 static int gitdiff_index(const char *line
, struct patch
*patch
)
430 /* index line is N hexadecimal, "..", N hexadecimal,
431 * and optional space with octal mode.
433 const char *ptr
, *eol
;
436 ptr
= strchr(line
, '.');
437 if (!ptr
|| ptr
[1] != '.' || 40 < ptr
- line
)
440 memcpy(patch
->old_sha1_prefix
, line
, len
);
441 patch
->old_sha1_prefix
[len
] = 0;
444 ptr
= strchr(line
, ' ');
445 eol
= strchr(line
, '\n');
447 if (!ptr
|| eol
< ptr
)
453 memcpy(patch
->new_sha1_prefix
, line
, len
);
454 patch
->new_sha1_prefix
[len
] = 0;
456 patch
->new_mode
= patch
->old_mode
= strtoul(ptr
+1, NULL
, 8);
461 * This is normal for a diff that doesn't change anything: we'll fall through
462 * into the next diff. Tell the parser to break out.
464 static int gitdiff_unrecognized(const char *line
, struct patch
*patch
)
469 static const char *stop_at_slash(const char *line
, int llen
)
473 for (i
= 0; i
< llen
; i
++) {
481 /* This is to extract the same name that appears on "diff --git"
482 * line. We do not find and return anything if it is a rename
483 * patch, and it is OK because we will find the name elsewhere.
484 * We need to reliably find name only when it is mode-change only,
485 * creation or deletion of an empty file. In any of these cases,
486 * both sides are the same name under a/ and b/ respectively.
488 static char *git_header_name(char *line
, int llen
)
492 const char *second
= NULL
;
494 line
+= strlen("diff --git ");
495 llen
-= strlen("diff --git ");
499 char *first
= unquote_c_style(line
, &second
);
503 /* advance to the first slash */
504 cp
= stop_at_slash(first
, strlen(first
));
505 if (!cp
|| cp
== first
) {
506 /* we do not accept absolute paths */
512 memmove(first
, cp
+1, len
+1); /* including NUL */
514 /* second points at one past closing dq of name.
515 * find the second name.
517 while ((second
< line
+ llen
) && isspace(*second
))
520 if (line
+ llen
<= second
)
521 goto free_first_and_fail
;
522 if (*second
== '"') {
523 char *sp
= unquote_c_style(second
, NULL
);
525 goto free_first_and_fail
;
526 cp
= stop_at_slash(sp
, strlen(sp
));
527 if (!cp
|| cp
== sp
) {
530 goto free_first_and_fail
;
532 /* They must match, otherwise ignore */
533 if (strcmp(cp
+1, first
))
534 goto free_both_and_fail
;
539 /* unquoted second */
540 cp
= stop_at_slash(second
, line
+ llen
- second
);
541 if (!cp
|| cp
== second
)
542 goto free_first_and_fail
;
544 if (line
+ llen
- cp
!= len
+ 1 ||
545 memcmp(first
, cp
, len
))
546 goto free_first_and_fail
;
550 /* unquoted first name */
551 name
= stop_at_slash(line
, llen
);
552 if (!name
|| name
== line
)
557 /* since the first name is unquoted, a dq if exists must be
558 * the beginning of the second name.
560 for (second
= name
; second
< line
+ llen
; second
++) {
561 if (*second
== '"') {
562 const char *cp
= second
;
564 char *sp
= unquote_c_style(second
, NULL
);
568 np
= stop_at_slash(sp
, strlen(sp
));
569 if (!np
|| np
== sp
) {
570 free_second_and_fail
:
576 if (len
< cp
- name
&&
577 !strncmp(np
, name
, len
) &&
578 isspace(name
[len
])) {
580 memmove(sp
, np
, len
+ 1);
583 goto free_second_and_fail
;
588 * Accept a name only if it shows up twice, exactly the same
591 for (len
= 0 ; ; len
++) {
608 if (second
[len
] == '\n' && !memcmp(name
, second
, len
)) {
609 char *ret
= xmalloc(len
+ 1);
610 memcpy(ret
, name
, len
);
619 /* Verify that we recognize the lines following a git header */
620 static int parse_git_header(char *line
, int len
, unsigned int size
, struct patch
*patch
)
622 unsigned long offset
;
624 /* A git diff has explicit new/delete information, so we don't guess */
626 patch
->is_delete
= 0;
629 * Some things may not have the old name in the
630 * rest of the headers anywhere (pure mode changes,
631 * or removing or adding empty files), so we get
632 * the default name from the header.
634 patch
->def_name
= git_header_name(line
, len
);
639 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
640 static const struct opentry
{
642 int (*fn
)(const char *, struct patch
*);
644 { "@@ -", gitdiff_hdrend
},
645 { "--- ", gitdiff_oldname
},
646 { "+++ ", gitdiff_newname
},
647 { "old mode ", gitdiff_oldmode
},
648 { "new mode ", gitdiff_newmode
},
649 { "deleted file mode ", gitdiff_delete
},
650 { "new file mode ", gitdiff_newfile
},
651 { "copy from ", gitdiff_copysrc
},
652 { "copy to ", gitdiff_copydst
},
653 { "rename old ", gitdiff_renamesrc
},
654 { "rename new ", gitdiff_renamedst
},
655 { "rename from ", gitdiff_renamesrc
},
656 { "rename to ", gitdiff_renamedst
},
657 { "similarity index ", gitdiff_similarity
},
658 { "dissimilarity index ", gitdiff_dissimilarity
},
659 { "index ", gitdiff_index
},
660 { "", gitdiff_unrecognized
},
664 len
= linelen(line
, size
);
665 if (!len
|| line
[len
-1] != '\n')
667 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
668 const struct opentry
*p
= optable
+ i
;
669 int oplen
= strlen(p
->str
);
670 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
672 if (p
->fn(line
+ oplen
, patch
) < 0)
681 static int parse_num(const char *line
, unsigned long *p
)
687 *p
= strtoul(line
, &ptr
, 10);
691 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
692 unsigned long *p1
, unsigned long *p2
)
696 if (offset
< 0 || offset
>= len
)
701 digits
= parse_num(line
, p1
);
711 digits
= parse_num(line
+1, p2
);
723 if (memcmp(line
, expect
, ex
))
730 * Parse a unified diff fragment header of the
731 * form "@@ -a,b +c,d @@"
733 static int parse_fragment_header(char *line
, int len
, struct fragment
*fragment
)
737 if (!len
|| line
[len
-1] != '\n')
740 /* Figure out the number of lines in a fragment */
741 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
742 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
747 static int find_header(char *line
, unsigned long size
, int *hdrsize
, struct patch
*patch
)
749 unsigned long offset
, len
;
751 patch
->is_rename
= patch
->is_copy
= 0;
752 patch
->is_new
= patch
->is_delete
= -1;
753 patch
->old_mode
= patch
->new_mode
= 0;
754 patch
->old_name
= patch
->new_name
= NULL
;
755 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
756 unsigned long nextlen
;
758 len
= linelen(line
, size
);
762 /* Testing this early allows us to take a few shortcuts.. */
767 * Make sure we don't find any unconnected patch fragmants.
768 * That's a sign that we didn't find a header, and that a
769 * patch has become corrupted/broken up.
771 if (!memcmp("@@ -", line
, 4)) {
772 struct fragment dummy
;
773 if (parse_fragment_header(line
, len
, &dummy
) < 0)
775 error("patch fragment without header at line %d: %.*s", linenr
, (int)len
-1, line
);
782 * Git patch? It might not have a real patch, just a rename
783 * or mode change, so we handle that specially
785 if (!memcmp("diff --git ", line
, 11)) {
786 int git_hdr_len
= parse_git_header(line
, len
, size
, patch
);
787 if (git_hdr_len
<= len
)
789 if (!patch
->old_name
&& !patch
->new_name
) {
790 if (!patch
->def_name
)
791 die("git diff header lacks filename information (line %d)", linenr
);
792 patch
->old_name
= patch
->new_name
= patch
->def_name
;
794 *hdrsize
= git_hdr_len
;
798 /** --- followed by +++ ? */
799 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
803 * We only accept unified patches, so we want it to
804 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
807 nextlen
= linelen(line
+ len
, size
- len
);
808 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
811 /* Ok, we'll consider it a patch */
812 parse_traditional_patch(line
, line
+len
, patch
);
813 *hdrsize
= len
+ nextlen
;
821 * Parse a unified diff. Note that this really needs
822 * to parse each fragment separately, since the only
823 * way to know the difference between a "---" that is
824 * part of a patch, and a "---" that starts the next
825 * patch is to look at the line counts..
827 static int parse_fragment(char *line
, unsigned long size
, struct patch
*patch
, struct fragment
*fragment
)
830 int len
= linelen(line
, size
), offset
;
831 unsigned long oldlines
, newlines
;
832 unsigned long leading
, trailing
;
834 offset
= parse_fragment_header(line
, len
, fragment
);
837 oldlines
= fragment
->oldlines
;
838 newlines
= fragment
->newlines
;
842 if (patch
->is_new
< 0) {
843 patch
->is_new
= !oldlines
;
845 patch
->old_name
= NULL
;
847 if (patch
->is_delete
< 0) {
848 patch
->is_delete
= !newlines
;
850 patch
->new_name
= NULL
;
853 if (patch
->is_new
&& oldlines
)
854 return error("new file depends on old contents");
855 if (patch
->is_delete
!= !newlines
) {
857 return error("deleted file still has contents");
858 fprintf(stderr
, "** warning: file %s becomes empty but is not deleted\n", patch
->new_name
);
861 /* Parse the thing.. */
866 for (offset
= len
; size
> 0; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
867 if (!oldlines
&& !newlines
)
869 len
= linelen(line
, size
);
870 if (!len
|| line
[len
-1] != '\n')
878 if (!deleted
&& !added
)
889 * We know len is at least two, since we have a '+' and
890 * we checked that the last character was a '\n' above.
891 * That is, an addition of an empty line would check
892 * the '+' here. Sneaky...
894 if ((new_whitespace
!= nowarn_whitespace
) &&
895 isspace(line
[len
-2])) {
897 if (squelch_whitespace_errors
&&
898 squelch_whitespace_errors
<
902 fprintf(stderr
, "Adds trailing whitespace.\n%s:%d:%.*s\n",
904 linenr
, len
-2, line
+1);
912 /* We allow "\ No newline at end of file". Depending
913 * on locale settings when the patch was produced we
914 * don't know what this line looks like. The only
915 * thing we do know is that it begins with "\ ".
916 * Checking for 12 is just for sanity check -- any
917 * l10n of "\ No newline..." is at least that long.
920 if (len
< 12 || memcmp(line
, "\\ ", 2))
925 if (oldlines
|| newlines
)
927 fragment
->leading
= leading
;
928 fragment
->trailing
= trailing
;
930 /* If a fragment ends with an incomplete line, we failed to include
931 * it in the above loop because we hit oldlines == newlines == 0
934 if (12 < size
&& !memcmp(line
, "\\ ", 2))
935 offset
+= linelen(line
, size
);
937 patch
->lines_added
+= added
;
938 patch
->lines_deleted
+= deleted
;
942 static int parse_single_patch(char *line
, unsigned long size
, struct patch
*patch
)
944 unsigned long offset
= 0;
945 struct fragment
**fragp
= &patch
->fragments
;
947 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
948 struct fragment
*fragment
;
951 fragment
= xcalloc(1, sizeof(*fragment
));
952 len
= parse_fragment(line
, size
, patch
, fragment
);
954 die("corrupt patch at line %d", linenr
);
956 fragment
->patch
= line
;
957 fragment
->size
= len
;
960 fragp
= &fragment
->next
;
969 static inline int metadata_changes(struct patch
*patch
)
971 return patch
->is_rename
> 0 ||
972 patch
->is_copy
> 0 ||
975 (patch
->old_mode
&& patch
->new_mode
&&
976 patch
->old_mode
!= patch
->new_mode
);
979 static int parse_binary(char *buffer
, unsigned long size
, struct patch
*patch
)
981 /* We have read "GIT binary patch\n"; what follows is a line
982 * that says the patch method (currently, either "deflated
983 * literal" or "deflated delta") and the length of data before
984 * deflating; a sequence of 'length-byte' followed by base-85
985 * encoded data follows.
987 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
988 * and we would limit the patch line to 66 characters,
989 * so one line can fit up to 13 groups that would decode
990 * to 52 bytes max. The length byte 'A'-'Z' corresponds
991 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
992 * The end of binary is signalled with an empty line.
995 struct fragment
*fragment
;
998 patch
->fragments
= fragment
= xcalloc(1, sizeof(*fragment
));
1000 /* Grab the type of patch */
1001 llen
= linelen(buffer
, size
);
1005 if (!strncmp(buffer
, "delta ", 6)) {
1006 patch
->is_binary
= BINARY_DELTA_DEFLATED
;
1007 patch
->deflate_origlen
= strtoul(buffer
+ 6, NULL
, 10);
1009 else if (!strncmp(buffer
, "literal ", 8)) {
1010 patch
->is_binary
= BINARY_LITERAL_DEFLATED
;
1011 patch
->deflate_origlen
= strtoul(buffer
+ 8, NULL
, 10);
1014 return error("unrecognized binary patch at line %d: %.*s",
1015 linenr
-1, llen
-1, buffer
);
1018 int byte_length
, max_byte_length
, newsize
;
1019 llen
= linelen(buffer
, size
);
1024 /* Minimum line is "A00000\n" which is 7-byte long,
1025 * and the line length must be multiple of 5 plus 2.
1027 if ((llen
< 7) || (llen
-2) % 5)
1029 max_byte_length
= (llen
- 2) / 5 * 4;
1030 byte_length
= *buffer
;
1031 if ('A' <= byte_length
&& byte_length
<= 'Z')
1032 byte_length
= byte_length
- 'A' + 1;
1033 else if ('a' <= byte_length
&& byte_length
<= 'z')
1034 byte_length
= byte_length
- 'a' + 27;
1037 /* if the input length was not multiple of 4, we would
1038 * have filler at the end but the filler should never
1041 if (max_byte_length
< byte_length
||
1042 byte_length
<= max_byte_length
- 4)
1044 newsize
= fragment
->size
+ byte_length
;
1045 data
= xrealloc(data
, newsize
);
1046 if (decode_85(data
+ fragment
->size
,
1050 fragment
->size
= newsize
;
1054 fragment
->patch
= data
;
1057 return error("corrupt binary patch at line %d: %.*s",
1058 linenr
-1, llen
-1, buffer
);
1061 static int parse_chunk(char *buffer
, unsigned long size
, struct patch
*patch
)
1063 int hdrsize
, patchsize
;
1064 int offset
= find_header(buffer
, size
, &hdrsize
, patch
);
1069 patchsize
= parse_single_patch(buffer
+ offset
+ hdrsize
, size
- offset
- hdrsize
, patch
);
1072 static const char *binhdr
[] = {
1077 static const char git_binary
[] = "GIT binary patch\n";
1079 int hd
= hdrsize
+ offset
;
1080 unsigned long llen
= linelen(buffer
+ hd
, size
- hd
);
1082 if (llen
== sizeof(git_binary
) - 1 &&
1083 !memcmp(git_binary
, buffer
+ hd
, llen
)) {
1086 used
= parse_binary(buffer
+ hd
+ llen
,
1087 size
- hd
- llen
, patch
);
1089 patchsize
= used
+ llen
;
1093 else if (!memcmp(" differ\n", buffer
+ hd
+ llen
- 8, 8)) {
1094 for (i
= 0; binhdr
[i
]; i
++) {
1095 int len
= strlen(binhdr
[i
]);
1096 if (len
< size
- hd
&&
1097 !memcmp(binhdr
[i
], buffer
+ hd
, len
)) {
1099 patch
->is_binary
= 1;
1106 /* Empty patch cannot be applied if:
1107 * - it is a binary patch and we do not do binary_replace, or
1108 * - text patch without metadata change
1110 if ((apply
|| check
) &&
1112 ? !allow_binary_replacement
1113 : !metadata_changes(patch
)))
1114 die("patch with only garbage at line %d", linenr
);
1117 return offset
+ hdrsize
+ patchsize
;
1120 static const char pluses
[] = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1121 static const char minuses
[]= "----------------------------------------------------------------------";
1123 static void show_stats(struct patch
*patch
)
1125 const char *prefix
= "";
1126 char *name
= patch
->new_name
;
1128 int len
, max
, add
, del
, total
;
1131 name
= patch
->old_name
;
1133 if (0 < (len
= quote_c_style(name
, NULL
, NULL
, 0))) {
1134 qname
= xmalloc(len
+ 1);
1135 quote_c_style(name
, qname
, NULL
, 0);
1140 * "scale" the filename
1151 slash
= strchr(name
, '/');
1158 * scale the add/delete
1164 add
= patch
->lines_added
;
1165 del
= patch
->lines_deleted
;
1168 if (max_change
> 0) {
1169 total
= (total
* max
+ max_change
/ 2) / max_change
;
1170 add
= (add
* max
+ max_change
/ 2) / max_change
;
1173 if (patch
->is_binary
)
1174 printf(" %s%-*s | Bin\n", prefix
, len
, name
);
1176 printf(" %s%-*s |%5d %.*s%.*s\n", prefix
,
1177 len
, name
, patch
->lines_added
+ patch
->lines_deleted
,
1178 add
, pluses
, del
, minuses
);
1183 static int read_old_data(struct stat
*st
, const char *path
, void *buf
, unsigned long size
)
1188 switch (st
->st_mode
& S_IFMT
) {
1190 return readlink(path
, buf
, size
);
1192 fd
= open(path
, O_RDONLY
);
1194 return error("unable to open %s", path
);
1197 int ret
= xread(fd
, buf
+ got
, size
- got
);
1210 static int find_offset(const char *buf
, unsigned long size
, const char *fragment
, unsigned long fragsize
, int line
, int *lines
)
1213 unsigned long start
, backwards
, forwards
;
1215 if (fragsize
> size
)
1220 unsigned long offset
= 0;
1222 while (offset
+ fragsize
<= size
) {
1223 if (buf
[offset
++] == '\n') {
1231 /* Exact line number? */
1232 if (!memcmp(buf
+ start
, fragment
, fragsize
))
1236 * There's probably some smart way to do this, but I'll leave
1237 * that to the smart and beautiful people. I'm simple and stupid.
1241 for (i
= 0; ; i
++) {
1248 if (forwards
+ fragsize
> size
)
1254 } while (backwards
&& buf
[backwards
-1] != '\n');
1257 while (forwards
+ fragsize
<= size
) {
1258 if (buf
[forwards
++] == '\n')
1264 if (try + fragsize
> size
)
1266 if (memcmp(buf
+ try, fragment
, fragsize
))
1276 * We should start searching forward and backward.
1281 static void remove_first_line(const char **rbuf
, int *rsize
)
1283 const char *buf
= *rbuf
;
1285 unsigned long offset
;
1287 while (offset
<= size
) {
1288 if (buf
[offset
++] == '\n')
1291 *rsize
= size
- offset
;
1292 *rbuf
= buf
+ offset
;
1295 static void remove_last_line(const char **rbuf
, int *rsize
)
1297 const char *buf
= *rbuf
;
1299 unsigned long offset
;
1301 while (offset
> 0) {
1302 if (buf
[--offset
] == '\n')
1305 *rsize
= offset
+ 1;
1308 struct buffer_desc
{
1311 unsigned long alloc
;
1314 static int apply_line(char *output
, const char *patch
, int plen
)
1316 /* plen is number of bytes to be copied from patch,
1317 * starting at patch+1 (patch[0] is '+'). Typically
1318 * patch[plen] is '\n'.
1320 int add_nl_to_tail
= 0;
1321 if ((new_whitespace
== strip_whitespace
) &&
1322 1 < plen
&& isspace(patch
[plen
-1])) {
1323 if (patch
[plen
] == '\n')
1326 while (0 < plen
&& isspace(patch
[plen
]))
1328 applied_after_stripping
++;
1330 memcpy(output
, patch
+ 1, plen
);
1332 output
[plen
++] = '\n';
1336 static int apply_one_fragment(struct buffer_desc
*desc
, struct fragment
*frag
)
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
;
1349 int len
= linelen(patch
, size
);
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).
1363 if (len
< size
&& patch
[len
] == '\\')
1368 memcpy(old
+ oldsize
, patch
+ 1, plen
);
1372 /* Fall-through for ' ' */
1374 if (*patch
!= '+' || !no_add
)
1375 newsize
+= apply_line(new + newsize
, patch
,
1378 case '@': case '\\':
1379 /* Ignore it, we already handled it */
1388 #ifdef NO_ACCURATE_DIFF
1389 if (oldsize
> 0 && old
[oldsize
- 1] == '\n' &&
1390 newsize
> 0 && new[newsize
- 1] == '\n') {
1398 leading
= frag
->leading
;
1399 trailing
= frag
->trailing
;
1403 offset
= find_offset(buf
, desc
->size
, oldlines
, oldsize
, pos
, &lines
);
1405 int diff
= newsize
- oldsize
;
1406 unsigned long size
= desc
->size
+ diff
;
1407 unsigned long alloc
= desc
->alloc
;
1409 /* Warn if it was necessary to reduce the number
1412 if ((leading
!= frag
->leading
) || (trailing
!= frag
->trailing
))
1413 fprintf(stderr
, "Context reduced to (%ld/%ld) to apply fragment at %d\n",
1414 leading
, trailing
, pos
+ lines
);
1417 alloc
= size
+ 8192;
1418 desc
->alloc
= alloc
;
1419 buf
= xrealloc(buf
, alloc
);
1423 memmove(buf
+ offset
+ newsize
, buf
+ offset
+ oldsize
, size
- offset
- newsize
);
1424 memcpy(buf
+ offset
, newlines
, newsize
);
1430 /* Am I at my context limits? */
1431 if ((leading
<= p_context
) && (trailing
<= p_context
))
1433 /* Reduce the number of context lines
1434 * Reduce both leading and trailing if they are equal
1435 * otherwise just reduce the larger context.
1437 if (leading
>= trailing
) {
1438 remove_first_line(&oldlines
, &oldsize
);
1439 remove_first_line(&newlines
, &newsize
);
1443 if (trailing
> leading
) {
1444 remove_last_line(&oldlines
, &oldsize
);
1445 remove_last_line(&newlines
, &newsize
);
1455 static char *inflate_it(const void *data
, unsigned long size
,
1456 unsigned long inflated_size
)
1462 memset(&stream
, 0, sizeof(stream
));
1464 stream
.next_in
= (unsigned char *)data
;
1465 stream
.avail_in
= size
;
1466 stream
.next_out
= out
= xmalloc(inflated_size
);
1467 stream
.avail_out
= inflated_size
;
1468 inflateInit(&stream
);
1469 st
= inflate(&stream
, Z_FINISH
);
1470 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1477 static int apply_binary_fragment(struct buffer_desc
*desc
, struct patch
*patch
)
1479 unsigned long dst_size
;
1480 struct fragment
*fragment
= patch
->fragments
;
1484 data
= inflate_it(fragment
->patch
, fragment
->size
,
1485 patch
->deflate_origlen
);
1487 return error("corrupt patch data");
1488 switch (patch
->is_binary
) {
1489 case BINARY_DELTA_DEFLATED
:
1490 result
= patch_delta(desc
->buffer
, desc
->size
,
1492 patch
->deflate_origlen
,
1495 desc
->buffer
= result
;
1498 case BINARY_LITERAL_DEFLATED
:
1500 desc
->buffer
= data
;
1501 dst_size
= patch
->deflate_origlen
;
1506 desc
->size
= desc
->alloc
= dst_size
;
1510 static int apply_binary(struct buffer_desc
*desc
, struct patch
*patch
)
1512 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
1513 unsigned char sha1
[20];
1514 unsigned char hdr
[50];
1517 if (!allow_binary_replacement
)
1518 return error("cannot apply binary patch to '%s' "
1519 "without --allow-binary-replacement",
1522 /* For safety, we require patch index line to contain
1523 * full 40-byte textual SHA1 for old and new, at least for now.
1525 if (strlen(patch
->old_sha1_prefix
) != 40 ||
1526 strlen(patch
->new_sha1_prefix
) != 40 ||
1527 get_sha1_hex(patch
->old_sha1_prefix
, sha1
) ||
1528 get_sha1_hex(patch
->new_sha1_prefix
, sha1
))
1529 return error("cannot apply binary patch to '%s' "
1530 "without full index line", name
);
1532 if (patch
->old_name
) {
1533 /* See if the old one matches what the patch
1536 write_sha1_file_prepare(desc
->buffer
, desc
->size
,
1537 blob_type
, sha1
, hdr
, &hdrlen
);
1538 if (strcmp(sha1_to_hex(sha1
), patch
->old_sha1_prefix
))
1539 return error("the patch applies to '%s' (%s), "
1540 "which does not match the "
1541 "current contents.",
1542 name
, sha1_to_hex(sha1
));
1545 /* Otherwise, the old one must be empty. */
1547 return error("the patch applies to an empty "
1548 "'%s' but it is not empty", name
);
1551 get_sha1_hex(patch
->new_sha1_prefix
, sha1
);
1552 if (!memcmp(sha1
, null_sha1
, 20)) {
1554 desc
->alloc
= desc
->size
= 0;
1555 desc
->buffer
= NULL
;
1556 return 0; /* deletion patch */
1559 if (has_sha1_file(sha1
)) {
1560 /* We already have the postimage */
1565 desc
->buffer
= read_sha1_file(sha1
, type
, &size
);
1567 return error("the necessary postimage %s for "
1568 "'%s' cannot be read",
1569 patch
->new_sha1_prefix
, name
);
1570 desc
->alloc
= desc
->size
= size
;
1573 /* We have verified desc matches the preimage;
1574 * apply the patch data to it, which is stored
1575 * in the patch->fragments->{patch,size}.
1577 if (apply_binary_fragment(desc
, patch
))
1578 return error("binary patch does not apply to '%s'",
1581 /* verify that the result matches */
1582 write_sha1_file_prepare(desc
->buffer
, desc
->size
, blob_type
,
1583 sha1
, hdr
, &hdrlen
);
1584 if (strcmp(sha1_to_hex(sha1
), patch
->new_sha1_prefix
))
1585 return error("binary patch to '%s' creates incorrect result", name
);
1591 static int apply_fragments(struct buffer_desc
*desc
, struct patch
*patch
)
1593 struct fragment
*frag
= patch
->fragments
;
1594 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
1596 if (patch
->is_binary
)
1597 return apply_binary(desc
, patch
);
1600 if (apply_one_fragment(desc
, frag
) < 0)
1601 return error("patch failed: %s:%ld",
1602 name
, frag
->oldpos
);
1608 static int apply_data(struct patch
*patch
, struct stat
*st
, struct cache_entry
*ce
)
1611 unsigned long size
, alloc
;
1612 struct buffer_desc desc
;
1620 buf
= read_sha1_file(ce
->sha1
, type
, &size
);
1622 return error("read of %s failed",
1627 else if (patch
->old_name
) {
1629 alloc
= size
+ 8192;
1630 buf
= xmalloc(alloc
);
1631 if (read_old_data(st
, patch
->old_name
, buf
, alloc
) != size
)
1632 return error("read of %s failed", patch
->old_name
);
1638 if (apply_fragments(&desc
, patch
) < 0)
1640 patch
->result
= desc
.buffer
;
1641 patch
->resultsize
= desc
.size
;
1643 if (patch
->is_delete
&& patch
->resultsize
)
1644 return error("removal patch leaves file contents");
1649 static int check_patch(struct patch
*patch
)
1652 const char *old_name
= patch
->old_name
;
1653 const char *new_name
= patch
->new_name
;
1654 const char *name
= old_name
? old_name
: new_name
;
1655 struct cache_entry
*ce
= NULL
;
1660 unsigned st_mode
= 0;
1663 stat_ret
= lstat(old_name
, &st
);
1665 int pos
= cache_name_pos(old_name
, strlen(old_name
));
1667 return error("%s: does not exist in index",
1669 ce
= active_cache
[pos
];
1671 struct checkout costate
;
1672 if (errno
!= ENOENT
)
1673 return error("%s: %s", old_name
,
1676 costate
.base_dir
= "";
1677 costate
.base_dir_len
= 0;
1680 costate
.not_new
= 0;
1681 costate
.refresh_cache
= 1;
1682 if (checkout_entry(ce
,
1685 lstat(old_name
, &st
))
1689 changed
= ce_match_stat(ce
, &st
, 1);
1691 return error("%s: does not match index",
1694 st_mode
= ntohl(ce
->ce_mode
);
1696 else if (stat_ret
< 0)
1697 return error("%s: %s", old_name
, strerror(errno
));
1700 st_mode
= ntohl(create_ce_mode(st
.st_mode
));
1702 if (patch
->is_new
< 0)
1704 if (!patch
->old_mode
)
1705 patch
->old_mode
= st_mode
;
1706 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
1707 return error("%s: wrong type", old_name
);
1708 if (st_mode
!= patch
->old_mode
)
1709 fprintf(stderr
, "warning: %s has type %o, expected %o\n",
1710 old_name
, st_mode
, patch
->old_mode
);
1713 if (new_name
&& (patch
->is_new
| patch
->is_rename
| patch
->is_copy
)) {
1714 if (check_index
&& cache_name_pos(new_name
, strlen(new_name
)) >= 0)
1715 return error("%s: already exists in index", new_name
);
1717 if (!lstat(new_name
, &st
))
1718 return error("%s: already exists in working directory", new_name
);
1719 if (errno
!= ENOENT
)
1720 return error("%s: %s", new_name
, strerror(errno
));
1722 if (!patch
->new_mode
) {
1724 patch
->new_mode
= S_IFREG
| 0644;
1726 patch
->new_mode
= patch
->old_mode
;
1730 if (new_name
&& old_name
) {
1731 int same
= !strcmp(old_name
, new_name
);
1732 if (!patch
->new_mode
)
1733 patch
->new_mode
= patch
->old_mode
;
1734 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
)
1735 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
1736 patch
->new_mode
, new_name
, patch
->old_mode
,
1737 same
? "" : " of ", same
? "" : old_name
);
1740 if (apply_data(patch
, &st
, ce
) < 0)
1741 return error("%s: patch does not apply", name
);
1745 static int check_patch_list(struct patch
*patch
)
1749 for (;patch
; patch
= patch
->next
)
1750 error
|= check_patch(patch
);
1754 static inline int is_null_sha1(const unsigned char *sha1
)
1756 return !memcmp(sha1
, null_sha1
, 20);
1759 static void show_index_list(struct patch
*list
)
1761 struct patch
*patch
;
1763 /* Once we start supporting the reverse patch, it may be
1764 * worth showing the new sha1 prefix, but until then...
1766 for (patch
= list
; patch
; patch
= patch
->next
) {
1767 const unsigned char *sha1_ptr
;
1768 unsigned char sha1
[20];
1771 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
1773 sha1_ptr
= null_sha1
;
1774 else if (get_sha1(patch
->old_sha1_prefix
, sha1
))
1775 die("sha1 information is lacking or useless (%s).",
1780 printf("%06o %s ",patch
->old_mode
, sha1_to_hex(sha1_ptr
));
1781 if (line_termination
&& quote_c_style(name
, NULL
, NULL
, 0))
1782 quote_c_style(name
, NULL
, stdout
, 0);
1784 fputs(name
, stdout
);
1785 putchar(line_termination
);
1789 static void stat_patch_list(struct patch
*patch
)
1791 int files
, adds
, dels
;
1793 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
1795 adds
+= patch
->lines_added
;
1796 dels
+= patch
->lines_deleted
;
1800 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files
, adds
, dels
);
1803 static void numstat_patch_list(struct patch
*patch
)
1805 for ( ; patch
; patch
= patch
->next
) {
1807 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
1808 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
1809 if (line_termination
&& quote_c_style(name
, NULL
, NULL
, 0))
1810 quote_c_style(name
, NULL
, stdout
, 0);
1812 fputs(name
, stdout
);
1817 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
1820 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
1822 printf(" %s %s\n", newdelete
, name
);
1825 static void show_mode_change(struct patch
*p
, int show_name
)
1827 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
1829 printf(" mode change %06o => %06o %s\n",
1830 p
->old_mode
, p
->new_mode
, p
->new_name
);
1832 printf(" mode change %06o => %06o\n",
1833 p
->old_mode
, p
->new_mode
);
1837 static void show_rename_copy(struct patch
*p
)
1839 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
1840 const char *old
, *new;
1842 /* Find common prefix */
1846 const char *slash_old
, *slash_new
;
1847 slash_old
= strchr(old
, '/');
1848 slash_new
= strchr(new, '/');
1851 slash_old
- old
!= slash_new
- new ||
1852 memcmp(old
, new, slash_new
- new))
1854 old
= slash_old
+ 1;
1855 new = slash_new
+ 1;
1857 /* p->old_name thru old is the common prefix, and old and new
1858 * through the end of names are renames
1860 if (old
!= p
->old_name
)
1861 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
1862 (int)(old
- p
->old_name
), p
->old_name
,
1863 old
, new, p
->score
);
1865 printf(" %s %s => %s (%d%%)\n", renamecopy
,
1866 p
->old_name
, p
->new_name
, p
->score
);
1867 show_mode_change(p
, 0);
1870 static void summary_patch_list(struct patch
*patch
)
1874 for (p
= patch
; p
; p
= p
->next
) {
1876 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
1877 else if (p
->is_delete
)
1878 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
1880 if (p
->is_rename
|| p
->is_copy
)
1881 show_rename_copy(p
);
1884 printf(" rewrite %s (%d%%)\n",
1885 p
->new_name
, p
->score
);
1886 show_mode_change(p
, 0);
1889 show_mode_change(p
, 1);
1895 static void patch_stats(struct patch
*patch
)
1897 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
1899 if (lines
> max_change
)
1901 if (patch
->old_name
) {
1902 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
1904 len
= strlen(patch
->old_name
);
1908 if (patch
->new_name
) {
1909 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
1911 len
= strlen(patch
->new_name
);
1917 static void remove_file(struct patch
*patch
)
1920 if (remove_file_from_cache(patch
->old_name
) < 0)
1921 die("unable to remove %s from index", patch
->old_name
);
1922 cache_tree_invalidate_path(active_cache_tree
, patch
->old_name
);
1925 unlink(patch
->old_name
);
1928 static void add_index_file(const char *path
, unsigned mode
, void *buf
, unsigned long size
)
1931 struct cache_entry
*ce
;
1932 int namelen
= strlen(path
);
1933 unsigned ce_size
= cache_entry_size(namelen
);
1938 ce
= xcalloc(1, ce_size
);
1939 memcpy(ce
->name
, path
, namelen
);
1940 ce
->ce_mode
= create_ce_mode(mode
);
1941 ce
->ce_flags
= htons(namelen
);
1943 if (lstat(path
, &st
) < 0)
1944 die("unable to stat newly created file %s", path
);
1945 fill_stat_cache_info(ce
, &st
);
1947 if (write_sha1_file(buf
, size
, blob_type
, ce
->sha1
) < 0)
1948 die("unable to create backing store for newly created file %s", path
);
1949 if (add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
) < 0)
1950 die("unable to add cache entry for %s", path
);
1953 static int try_create_file(const char *path
, unsigned int mode
, const char *buf
, unsigned long size
)
1958 return symlink(buf
, path
);
1959 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
1963 int written
= xwrite(fd
, buf
, size
);
1965 die("writing file %s: %s", path
, strerror(errno
));
1967 die("out of space writing file %s", path
);
1972 die("closing file %s: %s", path
, strerror(errno
));
1977 * We optimistically assume that the directories exist,
1978 * which is true 99% of the time anyway. If they don't,
1979 * we create them and try again.
1981 static void create_one_file(char *path
, unsigned mode
, const char *buf
, unsigned long size
)
1985 if (!try_create_file(path
, mode
, buf
, size
))
1988 if (errno
== ENOENT
) {
1989 if (safe_create_leading_directories(path
))
1991 if (!try_create_file(path
, mode
, buf
, size
))
1995 if (errno
== EEXIST
) {
1996 unsigned int nr
= getpid();
1999 const char *newpath
;
2000 newpath
= mkpath("%s~%u", path
, nr
);
2001 if (!try_create_file(newpath
, mode
, buf
, size
)) {
2002 if (!rename(newpath
, path
))
2007 if (errno
!= EEXIST
)
2012 die("unable to write file %s mode %o", path
, mode
);
2015 static void create_file(struct patch
*patch
)
2017 char *path
= patch
->new_name
;
2018 unsigned mode
= patch
->new_mode
;
2019 unsigned long size
= patch
->resultsize
;
2020 char *buf
= patch
->result
;
2023 mode
= S_IFREG
| 0644;
2024 create_one_file(path
, mode
, buf
, size
);
2025 add_index_file(path
, mode
, buf
, size
);
2026 cache_tree_invalidate_path(active_cache_tree
, path
);
2029 static void write_out_one_result(struct patch
*patch
)
2031 if (patch
->is_delete
> 0) {
2035 if (patch
->is_new
> 0 || patch
->is_copy
) {
2040 * Rename or modification boils down to the same
2041 * thing: remove the old, write the new
2047 static void write_out_results(struct patch
*list
, int skipped_patch
)
2049 if (!list
&& !skipped_patch
)
2053 write_out_one_result(list
);
2058 static struct cache_file cache_file
;
2060 static struct excludes
{
2061 struct excludes
*next
;
2065 static int use_patch(struct patch
*p
)
2067 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
2068 struct excludes
*x
= excludes
;
2070 if (fnmatch(x
->path
, pathname
, 0) == 0)
2074 if (0 < prefix_length
) {
2075 int pathlen
= strlen(pathname
);
2076 if (pathlen
<= prefix_length
||
2077 memcmp(prefix
, pathname
, prefix_length
))
2083 static int apply_patch(int fd
, const char *filename
)
2085 unsigned long offset
, size
;
2086 char *buffer
= read_patch_file(fd
, &size
);
2087 struct patch
*list
= NULL
, **listp
= &list
;
2088 int skipped_patch
= 0;
2090 patch_input_file
= filename
;
2095 struct patch
*patch
;
2098 patch
= xcalloc(1, sizeof(*patch
));
2099 nr
= parse_chunk(buffer
+ offset
, size
, patch
);
2102 if (use_patch(patch
)) {
2105 listp
= &patch
->next
;
2107 /* perhaps free it a bit better? */
2115 if (whitespace_error
&& (new_whitespace
== error_on_whitespace
))
2118 write_index
= check_index
&& apply
;
2119 if (write_index
&& newfd
< 0)
2120 newfd
= hold_index_file_for_update(&cache_file
, get_index_file());
2122 if (read_cache() < 0)
2123 die("unable to read index file");
2126 if ((check
|| apply
) && check_patch_list(list
) < 0)
2130 write_out_results(list
, skipped_patch
);
2132 if (show_index_info
)
2133 show_index_list(list
);
2136 stat_patch_list(list
);
2139 numstat_patch_list(list
);
2142 summary_patch_list(list
);
2148 static int git_apply_config(const char *var
, const char *value
)
2150 if (!strcmp(var
, "apply.whitespace")) {
2151 apply_default_whitespace
= strdup(value
);
2154 return git_default_config(var
, value
);
2158 int cmd_apply(int argc
, const char **argv
, char **envp
)
2162 const char *whitespace_option
= NULL
;
2164 for (i
= 1; i
< argc
; i
++) {
2165 const char *arg
= argv
[i
];
2169 if (!strcmp(arg
, "-")) {
2170 apply_patch(0, "<stdin>");
2174 if (!strncmp(arg
, "--exclude=", 10)) {
2175 struct excludes
*x
= xmalloc(sizeof(*x
));
2181 if (!strncmp(arg
, "-p", 2)) {
2182 p_value
= atoi(arg
+ 2);
2185 if (!strcmp(arg
, "--no-add")) {
2189 if (!strcmp(arg
, "--stat")) {
2194 if (!strcmp(arg
, "--allow-binary-replacement") ||
2195 !strcmp(arg
, "--binary")) {
2196 allow_binary_replacement
= 1;
2199 if (!strcmp(arg
, "--numstat")) {
2204 if (!strcmp(arg
, "--summary")) {
2209 if (!strcmp(arg
, "--check")) {
2214 if (!strcmp(arg
, "--index")) {
2218 if (!strcmp(arg
, "--cached")) {
2223 if (!strcmp(arg
, "--apply")) {
2227 if (!strcmp(arg
, "--index-info")) {
2229 show_index_info
= 1;
2232 if (!strcmp(arg
, "-z")) {
2233 line_termination
= 0;
2236 if (!strncmp(arg
, "-C", 2)) {
2237 p_context
= strtoul(arg
+ 2, &end
, 0);
2239 die("unrecognized context count '%s'", arg
+ 2);
2242 if (!strncmp(arg
, "--whitespace=", 13)) {
2243 whitespace_option
= arg
+ 13;
2244 parse_whitespace_option(arg
+ 13);
2248 if (check_index
&& prefix_length
< 0) {
2249 prefix
= setup_git_directory();
2250 prefix_length
= prefix
? strlen(prefix
) : 0;
2251 git_config(git_apply_config
);
2252 if (!whitespace_option
&& apply_default_whitespace
)
2253 parse_whitespace_option(apply_default_whitespace
);
2255 if (0 < prefix_length
)
2256 arg
= prefix_filename(prefix
, prefix_length
, arg
);
2258 fd
= open(arg
, O_RDONLY
);
2262 set_default_whitespace_mode(whitespace_option
);
2263 apply_patch(fd
, arg
);
2266 set_default_whitespace_mode(whitespace_option
);
2268 apply_patch(0, "<stdin>");
2269 if (whitespace_error
) {
2270 if (squelch_whitespace_errors
&&
2271 squelch_whitespace_errors
< whitespace_error
) {
2273 whitespace_error
- squelch_whitespace_errors
;
2274 fprintf(stderr
, "warning: squelched %d whitespace error%s\n",
2276 squelched
== 1 ? "" : "s");
2278 if (new_whitespace
== error_on_whitespace
)
2279 die("%d line%s add%s trailing whitespaces.",
2281 whitespace_error
== 1 ? "" : "s",
2282 whitespace_error
== 1 ? "s" : "");
2283 if (applied_after_stripping
)
2284 fprintf(stderr
, "warning: %d line%s applied after"
2285 " stripping trailing whitespaces.\n",
2286 applied_after_stripping
,
2287 applied_after_stripping
== 1 ? "" : "s");
2288 else if (whitespace_error
)
2289 fprintf(stderr
, "warning: %d line%s add%s trailing"
2292 whitespace_error
== 1 ? "" : "s",
2293 whitespace_error
== 1 ? "s" : "");
2297 if (write_cache(newfd
, active_cache
, active_nr
) ||
2298 commit_index_file(&cache_file
))
2299 die("Unable to write new cachefile");