4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
11 #include "cache-tree.h"
18 * --check turns on checking that the working tree matches the
19 * files that are being modified, but doesn't apply the patch
20 * --stat does just a diffstat, and doesn't actually apply
21 * --numstat does numeric diffstat, and doesn't actually apply
22 * --index-info shows the old and new index info for paths if available.
23 * --index updates the cache as well.
24 * --cached updates only the cache without ever touching the working tree.
26 static const char *prefix
;
27 static int prefix_length
= -1;
28 static int newfd
= -1;
30 static int p_value
= 1;
31 static int check_index
;
32 static int write_index
;
39 static int apply_in_reverse
;
40 static int apply_with_reject
;
41 static int apply_verbosely
;
43 static int show_index_info
;
44 static int line_termination
= '\n';
45 static unsigned long p_context
= -1;
46 static const char apply_usage
[] =
47 "git-apply [--stat] [--numstat] [--summary] [--check] [--index] [--cached] [--apply] [--no-add] [--index-info] [--allow-binary-replacement] [--reverse] [--reject] [--verbose] [-z] [-pNUM] [-CNUM] [--whitespace=<nowarn|warn|error|error-all|strip>] <patch>...";
49 static enum whitespace_eol
{
54 } new_whitespace
= warn_on_whitespace
;
55 static int whitespace_error
;
56 static int squelch_whitespace_errors
= 5;
57 static int applied_after_stripping
;
58 static const char *patch_input_file
;
60 static void parse_whitespace_option(const char *option
)
63 new_whitespace
= warn_on_whitespace
;
66 if (!strcmp(option
, "warn")) {
67 new_whitespace
= warn_on_whitespace
;
70 if (!strcmp(option
, "nowarn")) {
71 new_whitespace
= nowarn_whitespace
;
74 if (!strcmp(option
, "error")) {
75 new_whitespace
= error_on_whitespace
;
78 if (!strcmp(option
, "error-all")) {
79 new_whitespace
= error_on_whitespace
;
80 squelch_whitespace_errors
= 0;
83 if (!strcmp(option
, "strip")) {
84 new_whitespace
= strip_whitespace
;
87 die("unrecognized whitespace option '%s'", option
);
90 static void set_default_whitespace_mode(const char *whitespace_option
)
92 if (!whitespace_option
&& !apply_default_whitespace
) {
93 new_whitespace
= (apply
100 * For "diff-stat" like behaviour, we keep track of the biggest change
101 * we've seen, and the longest filename. That allows us to do simple
104 static int max_change
, max_len
;
107 * Various "current state", notably line numbers and what
108 * file (and how) we're patching right now.. The "is_xxxx"
109 * things are flags, where -1 means "don't know yet".
111 static int linenr
= 1;
114 * This represents one "hunk" from a patch, starting with
115 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
116 * patch text is pointed at by patch, and its byte length
117 * is stored in size. leading and trailing are the number
121 unsigned long leading
, trailing
;
122 unsigned long oldpos
, oldlines
;
123 unsigned long newpos
, newlines
;
127 struct fragment
*next
;
131 * When dealing with a binary patch, we reuse "leading" field
132 * to store the type of the binary hunk, either deflated "delta"
133 * or deflated "literal".
135 #define binary_patch_method leading
136 #define BINARY_DELTA_DEFLATED 1
137 #define BINARY_LITERAL_DEFLATED 2
140 char *new_name
, *old_name
, *def_name
;
141 unsigned int old_mode
, new_mode
;
142 int is_rename
, is_copy
, is_new
, is_delete
, is_binary
;
144 unsigned long deflate_origlen
;
145 int lines_added
, lines_deleted
;
147 int inaccurate_eof
:1;
148 struct fragment
*fragments
;
150 unsigned long resultsize
;
151 char old_sha1_prefix
[41];
152 char new_sha1_prefix
[41];
156 static void say_patch_name(FILE *output
, const char *pre
, struct patch
*patch
, const char *post
)
159 if (patch
->old_name
&& patch
->new_name
&&
160 strcmp(patch
->old_name
, patch
->new_name
)) {
161 write_name_quoted(NULL
, 0, patch
->old_name
, 1, output
);
162 fputs(" => ", output
);
163 write_name_quoted(NULL
, 0, patch
->new_name
, 1, output
);
166 const char *n
= patch
->new_name
;
169 write_name_quoted(NULL
, 0, n
, 1, output
);
174 #define CHUNKSIZE (8192)
177 static void *read_patch_file(int fd
, unsigned long *sizep
)
179 unsigned long size
= 0, alloc
= CHUNKSIZE
;
180 void *buffer
= xmalloc(alloc
);
183 int nr
= alloc
- size
;
186 buffer
= xrealloc(buffer
, alloc
);
189 nr
= xread(fd
, (char *) buffer
+ size
, nr
);
193 die("git-apply: read returned %s", strerror(errno
));
199 * Make sure that we have some slop in the buffer
200 * so that we can do speculative "memcmp" etc, and
201 * see to it that it is NUL-filled.
203 if (alloc
< size
+ SLOP
)
204 buffer
= xrealloc(buffer
, size
+ SLOP
);
205 memset((char *) buffer
+ size
, 0, SLOP
);
209 static unsigned long linelen(const char *buffer
, unsigned long size
)
211 unsigned long len
= 0;
214 if (*buffer
++ == '\n')
220 static int is_dev_null(const char *str
)
222 return !memcmp("/dev/null", str
, 9) && isspace(str
[9]);
228 static int name_terminate(const char *name
, int namelen
, int c
, int terminate
)
230 if (c
== ' ' && !(terminate
& TERM_SPACE
))
232 if (c
== '\t' && !(terminate
& TERM_TAB
))
238 static char * find_name(const char *line
, char *def
, int p_value
, int terminate
)
241 const char *start
= line
;
245 /* Proposed "new-style" GNU patch/diff format; see
246 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
248 name
= unquote_c_style(line
, NULL
);
252 cp
= strchr(name
, '/');
259 /* name can later be freed, so we need
260 * to memmove, not just return cp
262 memmove(name
, cp
, strlen(cp
) + 1);
279 if (name_terminate(start
, line
-start
, c
, terminate
))
283 if (c
== '/' && !--p_value
)
293 * Generally we prefer the shorter name, especially
294 * if the other one is just a variation of that with
295 * something else tacked on to the end (ie "file.orig"
299 int deflen
= strlen(def
);
300 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
304 name
= xmalloc(len
+ 1);
305 memcpy(name
, start
, len
);
312 * Get the name etc info from the --/+++ lines of a traditional patch header
314 * NOTE! This hardcodes "-p1" behaviour in filename detection.
316 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
317 * files, we can happily check the index for a match, but for creating a
318 * new file we should try to match whatever "patch" does. I have no idea.
320 static void parse_traditional_patch(const char *first
, const char *second
, struct patch
*patch
)
324 first
+= 4; /* skip "--- " */
325 second
+= 4; /* skip "+++ " */
326 if (is_dev_null(first
)) {
328 patch
->is_delete
= 0;
329 name
= find_name(second
, NULL
, p_value
, TERM_SPACE
| TERM_TAB
);
330 patch
->new_name
= name
;
331 } else if (is_dev_null(second
)) {
333 patch
->is_delete
= 1;
334 name
= find_name(first
, NULL
, p_value
, TERM_SPACE
| TERM_TAB
);
335 patch
->old_name
= name
;
337 name
= find_name(first
, NULL
, p_value
, TERM_SPACE
| TERM_TAB
);
338 name
= find_name(second
, name
, p_value
, TERM_SPACE
| TERM_TAB
);
339 patch
->old_name
= patch
->new_name
= name
;
342 die("unable to find filename in patch at line %d", linenr
);
345 static int gitdiff_hdrend(const char *line
, struct patch
*patch
)
351 * We're anal about diff header consistency, to make
352 * sure that we don't end up having strange ambiguous
353 * patches floating around.
355 * As a result, gitdiff_{old|new}name() will check
356 * their names against any previous information, just
359 static char *gitdiff_verify_name(const char *line
, int isnull
, char *orig_name
, const char *oldnew
)
361 if (!orig_name
&& !isnull
)
362 return find_name(line
, NULL
, 1, 0);
371 die("git-apply: bad git-diff - expected /dev/null, got %s on line %d", name
, linenr
);
372 another
= find_name(line
, NULL
, 1, 0);
373 if (!another
|| memcmp(another
, name
, len
))
374 die("git-apply: bad git-diff - inconsistent %s filename on line %d", oldnew
, linenr
);
379 /* expect "/dev/null" */
380 if (memcmp("/dev/null", line
, 9) || line
[9] != '\n')
381 die("git-apply: bad git-diff - expected /dev/null on line %d", linenr
);
386 static int gitdiff_oldname(const char *line
, struct patch
*patch
)
388 patch
->old_name
= gitdiff_verify_name(line
, patch
->is_new
, patch
->old_name
, "old");
392 static int gitdiff_newname(const char *line
, struct patch
*patch
)
394 patch
->new_name
= gitdiff_verify_name(line
, patch
->is_delete
, patch
->new_name
, "new");
398 static int gitdiff_oldmode(const char *line
, struct patch
*patch
)
400 patch
->old_mode
= strtoul(line
, NULL
, 8);
404 static int gitdiff_newmode(const char *line
, struct patch
*patch
)
406 patch
->new_mode
= strtoul(line
, NULL
, 8);
410 static int gitdiff_delete(const char *line
, struct patch
*patch
)
412 patch
->is_delete
= 1;
413 patch
->old_name
= patch
->def_name
;
414 return gitdiff_oldmode(line
, patch
);
417 static int gitdiff_newfile(const char *line
, struct patch
*patch
)
420 patch
->new_name
= patch
->def_name
;
421 return gitdiff_newmode(line
, patch
);
424 static int gitdiff_copysrc(const char *line
, struct patch
*patch
)
427 patch
->old_name
= find_name(line
, NULL
, 0, 0);
431 static int gitdiff_copydst(const char *line
, struct patch
*patch
)
434 patch
->new_name
= find_name(line
, NULL
, 0, 0);
438 static int gitdiff_renamesrc(const char *line
, struct patch
*patch
)
440 patch
->is_rename
= 1;
441 patch
->old_name
= find_name(line
, NULL
, 0, 0);
445 static int gitdiff_renamedst(const char *line
, struct patch
*patch
)
447 patch
->is_rename
= 1;
448 patch
->new_name
= find_name(line
, NULL
, 0, 0);
452 static int gitdiff_similarity(const char *line
, struct patch
*patch
)
454 if ((patch
->score
= strtoul(line
, NULL
, 10)) == ULONG_MAX
)
459 static int gitdiff_dissimilarity(const char *line
, struct patch
*patch
)
461 if ((patch
->score
= strtoul(line
, NULL
, 10)) == ULONG_MAX
)
466 static int gitdiff_index(const char *line
, struct patch
*patch
)
468 /* index line is N hexadecimal, "..", N hexadecimal,
469 * and optional space with octal mode.
471 const char *ptr
, *eol
;
474 ptr
= strchr(line
, '.');
475 if (!ptr
|| ptr
[1] != '.' || 40 < ptr
- line
)
478 memcpy(patch
->old_sha1_prefix
, line
, len
);
479 patch
->old_sha1_prefix
[len
] = 0;
482 ptr
= strchr(line
, ' ');
483 eol
= strchr(line
, '\n');
485 if (!ptr
|| eol
< ptr
)
491 memcpy(patch
->new_sha1_prefix
, line
, len
);
492 patch
->new_sha1_prefix
[len
] = 0;
494 patch
->new_mode
= patch
->old_mode
= strtoul(ptr
+1, NULL
, 8);
499 * This is normal for a diff that doesn't change anything: we'll fall through
500 * into the next diff. Tell the parser to break out.
502 static int gitdiff_unrecognized(const char *line
, struct patch
*patch
)
507 static const char *stop_at_slash(const char *line
, int llen
)
511 for (i
= 0; i
< llen
; i
++) {
519 /* This is to extract the same name that appears on "diff --git"
520 * line. We do not find and return anything if it is a rename
521 * patch, and it is OK because we will find the name elsewhere.
522 * We need to reliably find name only when it is mode-change only,
523 * creation or deletion of an empty file. In any of these cases,
524 * both sides are the same name under a/ and b/ respectively.
526 static char *git_header_name(char *line
, int llen
)
530 const char *second
= NULL
;
532 line
+= strlen("diff --git ");
533 llen
-= strlen("diff --git ");
537 char *first
= unquote_c_style(line
, &second
);
541 /* advance to the first slash */
542 cp
= stop_at_slash(first
, strlen(first
));
543 if (!cp
|| cp
== first
) {
544 /* we do not accept absolute paths */
550 memmove(first
, cp
+1, len
+1); /* including NUL */
552 /* second points at one past closing dq of name.
553 * find the second name.
555 while ((second
< line
+ llen
) && isspace(*second
))
558 if (line
+ llen
<= second
)
559 goto free_first_and_fail
;
560 if (*second
== '"') {
561 char *sp
= unquote_c_style(second
, NULL
);
563 goto free_first_and_fail
;
564 cp
= stop_at_slash(sp
, strlen(sp
));
565 if (!cp
|| cp
== sp
) {
568 goto free_first_and_fail
;
570 /* They must match, otherwise ignore */
571 if (strcmp(cp
+1, first
))
572 goto free_both_and_fail
;
577 /* unquoted second */
578 cp
= stop_at_slash(second
, line
+ llen
- second
);
579 if (!cp
|| cp
== second
)
580 goto free_first_and_fail
;
582 if (line
+ llen
- cp
!= len
+ 1 ||
583 memcmp(first
, cp
, len
))
584 goto free_first_and_fail
;
588 /* unquoted first name */
589 name
= stop_at_slash(line
, llen
);
590 if (!name
|| name
== line
)
595 /* since the first name is unquoted, a dq if exists must be
596 * the beginning of the second name.
598 for (second
= name
; second
< line
+ llen
; second
++) {
599 if (*second
== '"') {
600 const char *cp
= second
;
602 char *sp
= unquote_c_style(second
, NULL
);
606 np
= stop_at_slash(sp
, strlen(sp
));
607 if (!np
|| np
== sp
) {
608 free_second_and_fail
:
614 if (len
< cp
- name
&&
615 !strncmp(np
, name
, len
) &&
616 isspace(name
[len
])) {
618 memmove(sp
, np
, len
+ 1);
621 goto free_second_and_fail
;
626 * Accept a name only if it shows up twice, exactly the same
629 for (len
= 0 ; ; len
++) {
644 if (second
[len
] == '\n' && !memcmp(name
, second
, len
)) {
645 char *ret
= xmalloc(len
+ 1);
646 memcpy(ret
, name
, len
);
655 /* Verify that we recognize the lines following a git header */
656 static int parse_git_header(char *line
, int len
, unsigned int size
, struct patch
*patch
)
658 unsigned long offset
;
660 /* A git diff has explicit new/delete information, so we don't guess */
662 patch
->is_delete
= 0;
665 * Some things may not have the old name in the
666 * rest of the headers anywhere (pure mode changes,
667 * or removing or adding empty files), so we get
668 * the default name from the header.
670 patch
->def_name
= git_header_name(line
, len
);
675 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
676 static const struct opentry
{
678 int (*fn
)(const char *, struct patch
*);
680 { "@@ -", gitdiff_hdrend
},
681 { "--- ", gitdiff_oldname
},
682 { "+++ ", gitdiff_newname
},
683 { "old mode ", gitdiff_oldmode
},
684 { "new mode ", gitdiff_newmode
},
685 { "deleted file mode ", gitdiff_delete
},
686 { "new file mode ", gitdiff_newfile
},
687 { "copy from ", gitdiff_copysrc
},
688 { "copy to ", gitdiff_copydst
},
689 { "rename old ", gitdiff_renamesrc
},
690 { "rename new ", gitdiff_renamedst
},
691 { "rename from ", gitdiff_renamesrc
},
692 { "rename to ", gitdiff_renamedst
},
693 { "similarity index ", gitdiff_similarity
},
694 { "dissimilarity index ", gitdiff_dissimilarity
},
695 { "index ", gitdiff_index
},
696 { "", gitdiff_unrecognized
},
700 len
= linelen(line
, size
);
701 if (!len
|| line
[len
-1] != '\n')
703 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
704 const struct opentry
*p
= optable
+ i
;
705 int oplen
= strlen(p
->str
);
706 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
708 if (p
->fn(line
+ oplen
, patch
) < 0)
717 static int parse_num(const char *line
, unsigned long *p
)
723 *p
= strtoul(line
, &ptr
, 10);
727 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
728 unsigned long *p1
, unsigned long *p2
)
732 if (offset
< 0 || offset
>= len
)
737 digits
= parse_num(line
, p1
);
747 digits
= parse_num(line
+1, p2
);
759 if (memcmp(line
, expect
, ex
))
766 * Parse a unified diff fragment header of the
767 * form "@@ -a,b +c,d @@"
769 static int parse_fragment_header(char *line
, int len
, struct fragment
*fragment
)
773 if (!len
|| line
[len
-1] != '\n')
776 /* Figure out the number of lines in a fragment */
777 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
778 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
783 static int find_header(char *line
, unsigned long size
, int *hdrsize
, struct patch
*patch
)
785 unsigned long offset
, len
;
787 patch
->is_rename
= patch
->is_copy
= 0;
788 patch
->is_new
= patch
->is_delete
= -1;
789 patch
->old_mode
= patch
->new_mode
= 0;
790 patch
->old_name
= patch
->new_name
= NULL
;
791 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
792 unsigned long nextlen
;
794 len
= linelen(line
, size
);
798 /* Testing this early allows us to take a few shortcuts.. */
803 * Make sure we don't find any unconnected patch fragments.
804 * That's a sign that we didn't find a header, and that a
805 * patch has become corrupted/broken up.
807 if (!memcmp("@@ -", line
, 4)) {
808 struct fragment dummy
;
809 if (parse_fragment_header(line
, len
, &dummy
) < 0)
811 error("patch fragment without header at line %d: %.*s", linenr
, (int)len
-1, line
);
818 * Git patch? It might not have a real patch, just a rename
819 * or mode change, so we handle that specially
821 if (!memcmp("diff --git ", line
, 11)) {
822 int git_hdr_len
= parse_git_header(line
, len
, size
, patch
);
823 if (git_hdr_len
<= len
)
825 if (!patch
->old_name
&& !patch
->new_name
) {
826 if (!patch
->def_name
)
827 die("git diff header lacks filename information (line %d)", linenr
);
828 patch
->old_name
= patch
->new_name
= patch
->def_name
;
830 *hdrsize
= git_hdr_len
;
834 /** --- followed by +++ ? */
835 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
839 * We only accept unified patches, so we want it to
840 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
843 nextlen
= linelen(line
+ len
, size
- len
);
844 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
847 /* Ok, we'll consider it a patch */
848 parse_traditional_patch(line
, line
+len
, patch
);
849 *hdrsize
= len
+ nextlen
;
857 * Parse a unified diff. Note that this really needs
858 * to parse each fragment separately, since the only
859 * way to know the difference between a "---" that is
860 * part of a patch, and a "---" that starts the next
861 * patch is to look at the line counts..
863 static int parse_fragment(char *line
, unsigned long size
, struct patch
*patch
, struct fragment
*fragment
)
866 int len
= linelen(line
, size
), offset
;
867 unsigned long oldlines
, newlines
;
868 unsigned long leading
, trailing
;
870 offset
= parse_fragment_header(line
, len
, fragment
);
873 oldlines
= fragment
->oldlines
;
874 newlines
= fragment
->newlines
;
878 if (patch
->is_new
< 0) {
879 patch
->is_new
= !oldlines
;
881 patch
->old_name
= NULL
;
883 if (patch
->is_delete
< 0) {
884 patch
->is_delete
= !newlines
;
886 patch
->new_name
= NULL
;
889 if (patch
->is_new
&& oldlines
)
890 return error("new file depends on old contents");
891 if (patch
->is_delete
!= !newlines
) {
893 return error("deleted file still has contents");
894 fprintf(stderr
, "** warning: file %s becomes empty but is not deleted\n", patch
->new_name
);
897 /* Parse the thing.. */
902 for (offset
= len
; size
> 0; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
903 if (!oldlines
&& !newlines
)
905 len
= linelen(line
, size
);
906 if (!len
|| line
[len
-1] != '\n')
914 if (!deleted
&& !added
)
925 * We know len is at least two, since we have a '+' and
926 * we checked that the last character was a '\n' above.
927 * That is, an addition of an empty line would check
928 * the '+' here. Sneaky...
930 if ((new_whitespace
!= nowarn_whitespace
) &&
931 isspace(line
[len
-2])) {
933 if (squelch_whitespace_errors
&&
934 squelch_whitespace_errors
<
938 fprintf(stderr
, "Adds trailing whitespace.\n%s:%d:%.*s\n",
940 linenr
, len
-2, line
+1);
948 /* We allow "\ No newline at end of file". Depending
949 * on locale settings when the patch was produced we
950 * don't know what this line looks like. The only
951 * thing we do know is that it begins with "\ ".
952 * Checking for 12 is just for sanity check -- any
953 * l10n of "\ No newline..." is at least that long.
956 if (len
< 12 || memcmp(line
, "\\ ", 2))
961 if (oldlines
|| newlines
)
963 fragment
->leading
= leading
;
964 fragment
->trailing
= trailing
;
966 /* If a fragment ends with an incomplete line, we failed to include
967 * it in the above loop because we hit oldlines == newlines == 0
970 if (12 < size
&& !memcmp(line
, "\\ ", 2))
971 offset
+= linelen(line
, size
);
973 patch
->lines_added
+= added
;
974 patch
->lines_deleted
+= deleted
;
978 static int parse_single_patch(char *line
, unsigned long size
, struct patch
*patch
)
980 unsigned long offset
= 0;
981 struct fragment
**fragp
= &patch
->fragments
;
983 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
984 struct fragment
*fragment
;
987 fragment
= xcalloc(1, sizeof(*fragment
));
988 len
= parse_fragment(line
, size
, patch
, fragment
);
990 die("corrupt patch at line %d", linenr
);
992 fragment
->patch
= line
;
993 fragment
->size
= len
;
996 fragp
= &fragment
->next
;
1005 static inline int metadata_changes(struct patch
*patch
)
1007 return patch
->is_rename
> 0 ||
1008 patch
->is_copy
> 0 ||
1009 patch
->is_new
> 0 ||
1011 (patch
->old_mode
&& patch
->new_mode
&&
1012 patch
->old_mode
!= patch
->new_mode
);
1015 static char *inflate_it(const void *data
, unsigned long size
,
1016 unsigned long inflated_size
)
1022 memset(&stream
, 0, sizeof(stream
));
1024 stream
.next_in
= (unsigned char *)data
;
1025 stream
.avail_in
= size
;
1026 stream
.next_out
= out
= xmalloc(inflated_size
);
1027 stream
.avail_out
= inflated_size
;
1028 inflateInit(&stream
);
1029 st
= inflate(&stream
, Z_FINISH
);
1030 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1037 static struct fragment
*parse_binary_hunk(char **buf_p
,
1038 unsigned long *sz_p
,
1042 /* Expect a line that begins with binary patch method ("literal"
1043 * or "delta"), followed by the length of data before deflating.
1044 * a sequence of 'length-byte' followed by base-85 encoded data
1045 * should follow, terminated by a newline.
1047 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1048 * and we would limit the patch line to 66 characters,
1049 * so one line can fit up to 13 groups that would decode
1050 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1051 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1054 unsigned long size
= *sz_p
;
1055 char *buffer
= *buf_p
;
1057 unsigned long origlen
;
1060 struct fragment
*frag
;
1062 llen
= linelen(buffer
, size
);
1067 if (!strncmp(buffer
, "delta ", 6)) {
1068 patch_method
= BINARY_DELTA_DEFLATED
;
1069 origlen
= strtoul(buffer
+ 6, NULL
, 10);
1071 else if (!strncmp(buffer
, "literal ", 8)) {
1072 patch_method
= BINARY_LITERAL_DEFLATED
;
1073 origlen
= strtoul(buffer
+ 8, NULL
, 10);
1081 int byte_length
, max_byte_length
, newsize
;
1082 llen
= linelen(buffer
, size
);
1086 /* consume the blank line */
1091 /* Minimum line is "A00000\n" which is 7-byte long,
1092 * and the line length must be multiple of 5 plus 2.
1094 if ((llen
< 7) || (llen
-2) % 5)
1096 max_byte_length
= (llen
- 2) / 5 * 4;
1097 byte_length
= *buffer
;
1098 if ('A' <= byte_length
&& byte_length
<= 'Z')
1099 byte_length
= byte_length
- 'A' + 1;
1100 else if ('a' <= byte_length
&& byte_length
<= 'z')
1101 byte_length
= byte_length
- 'a' + 27;
1104 /* if the input length was not multiple of 4, we would
1105 * have filler at the end but the filler should never
1108 if (max_byte_length
< byte_length
||
1109 byte_length
<= max_byte_length
- 4)
1111 newsize
= hunk_size
+ byte_length
;
1112 data
= xrealloc(data
, newsize
);
1113 if (decode_85(data
+ hunk_size
, buffer
+ 1, byte_length
))
1115 hunk_size
= newsize
;
1120 frag
= xcalloc(1, sizeof(*frag
));
1121 frag
->patch
= inflate_it(data
, hunk_size
, origlen
);
1125 frag
->size
= origlen
;
1129 frag
->binary_patch_method
= patch_method
;
1135 error("corrupt binary patch at line %d: %.*s",
1136 linenr
-1, llen
-1, buffer
);
1140 static int parse_binary(char *buffer
, unsigned long size
, struct patch
*patch
)
1142 /* We have read "GIT binary patch\n"; what follows is a line
1143 * that says the patch method (currently, either "literal" or
1144 * "delta") and the length of data before deflating; a
1145 * sequence of 'length-byte' followed by base-85 encoded data
1148 * When a binary patch is reversible, there is another binary
1149 * hunk in the same format, starting with patch method (either
1150 * "literal" or "delta") with the length of data, and a sequence
1151 * of length-byte + base-85 encoded data, terminated with another
1152 * empty line. This data, when applied to the postimage, produces
1155 struct fragment
*forward
;
1156 struct fragment
*reverse
;
1160 forward
= parse_binary_hunk(&buffer
, &size
, &status
, &used
);
1161 if (!forward
&& !status
)
1162 /* there has to be one hunk (forward hunk) */
1163 return error("unrecognized binary patch at line %d", linenr
-1);
1165 /* otherwise we already gave an error message */
1168 reverse
= parse_binary_hunk(&buffer
, &size
, &status
, &used_1
);
1172 /* not having reverse hunk is not an error, but having
1173 * a corrupt reverse hunk is.
1175 free((void*) forward
->patch
);
1179 forward
->next
= reverse
;
1180 patch
->fragments
= forward
;
1181 patch
->is_binary
= 1;
1185 static int parse_chunk(char *buffer
, unsigned long size
, struct patch
*patch
)
1187 int hdrsize
, patchsize
;
1188 int offset
= find_header(buffer
, size
, &hdrsize
, patch
);
1193 patchsize
= parse_single_patch(buffer
+ offset
+ hdrsize
, size
- offset
- hdrsize
, patch
);
1196 static const char *binhdr
[] = {
1201 static const char git_binary
[] = "GIT binary patch\n";
1203 int hd
= hdrsize
+ offset
;
1204 unsigned long llen
= linelen(buffer
+ hd
, size
- hd
);
1206 if (llen
== sizeof(git_binary
) - 1 &&
1207 !memcmp(git_binary
, buffer
+ hd
, llen
)) {
1210 used
= parse_binary(buffer
+ hd
+ llen
,
1211 size
- hd
- llen
, patch
);
1213 patchsize
= used
+ llen
;
1217 else if (!memcmp(" differ\n", buffer
+ hd
+ llen
- 8, 8)) {
1218 for (i
= 0; binhdr
[i
]; i
++) {
1219 int len
= strlen(binhdr
[i
]);
1220 if (len
< size
- hd
&&
1221 !memcmp(binhdr
[i
], buffer
+ hd
, len
)) {
1223 patch
->is_binary
= 1;
1230 /* Empty patch cannot be applied if it is a text patch
1231 * without metadata change. A binary patch appears
1234 if ((apply
|| check
) &&
1235 (!patch
->is_binary
&& !metadata_changes(patch
)))
1236 die("patch with only garbage at line %d", linenr
);
1239 return offset
+ hdrsize
+ patchsize
;
1242 #define swap(a,b) myswap((a),(b),sizeof(a))
1244 #define myswap(a, b, size) do { \
1245 unsigned char mytmp[size]; \
1246 memcpy(mytmp, &a, size); \
1247 memcpy(&a, &b, size); \
1248 memcpy(&b, mytmp, size); \
1251 static void reverse_patches(struct patch
*p
)
1253 for (; p
; p
= p
->next
) {
1254 struct fragment
*frag
= p
->fragments
;
1256 swap(p
->new_name
, p
->old_name
);
1257 swap(p
->new_mode
, p
->old_mode
);
1258 swap(p
->is_new
, p
->is_delete
);
1259 swap(p
->lines_added
, p
->lines_deleted
);
1260 swap(p
->old_sha1_prefix
, p
->new_sha1_prefix
);
1262 for (; frag
; frag
= frag
->next
) {
1263 swap(frag
->newpos
, frag
->oldpos
);
1264 swap(frag
->newlines
, frag
->oldlines
);
1269 static const char pluses
[] = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1270 static const char minuses
[]= "----------------------------------------------------------------------";
1272 static void show_stats(struct patch
*patch
)
1274 const char *prefix
= "";
1275 char *name
= patch
->new_name
;
1277 int len
, max
, add
, del
, total
;
1280 name
= patch
->old_name
;
1282 if (0 < (len
= quote_c_style(name
, NULL
, NULL
, 0))) {
1283 qname
= xmalloc(len
+ 1);
1284 quote_c_style(name
, qname
, NULL
, 0);
1289 * "scale" the filename
1300 slash
= strchr(name
, '/');
1307 * scale the add/delete
1313 add
= patch
->lines_added
;
1314 del
= patch
->lines_deleted
;
1317 if (max_change
> 0) {
1318 total
= (total
* max
+ max_change
/ 2) / max_change
;
1319 add
= (add
* max
+ max_change
/ 2) / max_change
;
1322 if (patch
->is_binary
)
1323 printf(" %s%-*s | Bin\n", prefix
, len
, name
);
1325 printf(" %s%-*s |%5d %.*s%.*s\n", prefix
,
1326 len
, name
, patch
->lines_added
+ patch
->lines_deleted
,
1327 add
, pluses
, del
, minuses
);
1331 static int read_old_data(struct stat
*st
, const char *path
, void *buf
, unsigned long size
)
1336 switch (st
->st_mode
& S_IFMT
) {
1338 return readlink(path
, buf
, size
);
1340 fd
= open(path
, O_RDONLY
);
1342 return error("unable to open %s", path
);
1345 int ret
= xread(fd
, (char *) buf
+ got
, size
- got
);
1358 static int find_offset(const char *buf
, unsigned long size
, const char *fragment
, unsigned long fragsize
, int line
, int *lines
)
1361 unsigned long start
, backwards
, forwards
;
1363 if (fragsize
> size
)
1368 unsigned long offset
= 0;
1370 while (offset
+ fragsize
<= size
) {
1371 if (buf
[offset
++] == '\n') {
1379 /* Exact line number? */
1380 if (!memcmp(buf
+ start
, fragment
, fragsize
))
1384 * There's probably some smart way to do this, but I'll leave
1385 * that to the smart and beautiful people. I'm simple and stupid.
1389 for (i
= 0; ; i
++) {
1396 if (forwards
+ fragsize
> size
)
1402 } while (backwards
&& buf
[backwards
-1] != '\n');
1405 while (forwards
+ fragsize
<= size
) {
1406 if (buf
[forwards
++] == '\n')
1412 if (try + fragsize
> size
)
1414 if (memcmp(buf
+ try, fragment
, fragsize
))
1424 * We should start searching forward and backward.
1429 static void remove_first_line(const char **rbuf
, int *rsize
)
1431 const char *buf
= *rbuf
;
1433 unsigned long offset
;
1435 while (offset
<= size
) {
1436 if (buf
[offset
++] == '\n')
1439 *rsize
= size
- offset
;
1440 *rbuf
= buf
+ offset
;
1443 static void remove_last_line(const char **rbuf
, int *rsize
)
1445 const char *buf
= *rbuf
;
1447 unsigned long offset
;
1449 while (offset
> 0) {
1450 if (buf
[--offset
] == '\n')
1453 *rsize
= offset
+ 1;
1456 struct buffer_desc
{
1459 unsigned long alloc
;
1462 static int apply_line(char *output
, const char *patch
, int plen
)
1464 /* plen is number of bytes to be copied from patch,
1465 * starting at patch+1 (patch[0] is '+'). Typically
1466 * patch[plen] is '\n'.
1468 int add_nl_to_tail
= 0;
1469 if ((new_whitespace
== strip_whitespace
) &&
1470 1 < plen
&& isspace(patch
[plen
-1])) {
1471 if (patch
[plen
] == '\n')
1474 while (0 < plen
&& isspace(patch
[plen
]))
1476 applied_after_stripping
++;
1478 memcpy(output
, patch
+ 1, plen
);
1480 output
[plen
++] = '\n';
1484 static int apply_one_fragment(struct buffer_desc
*desc
, struct fragment
*frag
, int inaccurate_eof
)
1486 int match_beginning
, match_end
;
1487 char *buf
= desc
->buffer
;
1488 const char *patch
= frag
->patch
;
1489 int offset
, size
= frag
->size
;
1490 char *old
= xmalloc(size
);
1491 char *new = xmalloc(size
);
1492 const char *oldlines
, *newlines
;
1493 int oldsize
= 0, newsize
= 0;
1494 unsigned long leading
, trailing
;
1499 int len
= linelen(patch
, size
);
1506 * "plen" is how much of the line we should use for
1507 * the actual patch data. Normally we just remove the
1508 * first character on the line, but if the line is
1509 * followed by "\ No newline", then we also remove the
1510 * last one (which is the newline, of course).
1513 if (len
< size
&& patch
[len
] == '\\')
1516 if (apply_in_reverse
) {
1519 else if (first
== '+')
1525 memcpy(old
+ oldsize
, patch
+ 1, plen
);
1529 /* Fall-through for ' ' */
1531 if (first
!= '+' || !no_add
)
1532 newsize
+= apply_line(new + newsize
, patch
,
1535 case '@': case '\\':
1536 /* Ignore it, we already handled it */
1545 if (inaccurate_eof
&& oldsize
> 0 && old
[oldsize
- 1] == '\n' &&
1546 newsize
> 0 && new[newsize
- 1] == '\n') {
1553 leading
= frag
->leading
;
1554 trailing
= frag
->trailing
;
1557 * If we don't have any leading/trailing data in the patch,
1558 * we want it to match at the beginning/end of the file.
1560 match_beginning
= !leading
&& (frag
->oldpos
== 1);
1561 match_end
= !trailing
;
1566 offset
= find_offset(buf
, desc
->size
,
1567 oldlines
, oldsize
, pos
, &lines
);
1568 if (match_end
&& offset
+ oldsize
!= desc
->size
)
1570 if (match_beginning
&& offset
)
1573 int diff
= newsize
- oldsize
;
1574 unsigned long size
= desc
->size
+ diff
;
1575 unsigned long alloc
= desc
->alloc
;
1577 /* Warn if it was necessary to reduce the number
1580 if ((leading
!= frag
->leading
) ||
1581 (trailing
!= frag
->trailing
))
1582 fprintf(stderr
, "Context reduced to (%ld/%ld)"
1583 " to apply fragment at %d\n",
1584 leading
, trailing
, pos
+ lines
);
1587 alloc
= size
+ 8192;
1588 desc
->alloc
= alloc
;
1589 buf
= xrealloc(buf
, alloc
);
1593 memmove(buf
+ offset
+ newsize
,
1594 buf
+ offset
+ oldsize
,
1595 size
- offset
- newsize
);
1596 memcpy(buf
+ offset
, newlines
, newsize
);
1602 /* Am I at my context limits? */
1603 if ((leading
<= p_context
) && (trailing
<= p_context
))
1605 if (match_beginning
|| match_end
) {
1606 match_beginning
= match_end
= 0;
1609 /* Reduce the number of context lines
1610 * Reduce both leading and trailing if they are equal
1611 * otherwise just reduce the larger context.
1613 if (leading
>= trailing
) {
1614 remove_first_line(&oldlines
, &oldsize
);
1615 remove_first_line(&newlines
, &newsize
);
1619 if (trailing
> leading
) {
1620 remove_last_line(&oldlines
, &oldsize
);
1621 remove_last_line(&newlines
, &newsize
);
1631 static int apply_binary_fragment(struct buffer_desc
*desc
, struct patch
*patch
)
1633 unsigned long dst_size
;
1634 struct fragment
*fragment
= patch
->fragments
;
1638 /* Binary patch is irreversible without the optional second hunk */
1639 if (apply_in_reverse
) {
1640 if (!fragment
->next
)
1641 return error("cannot reverse-apply a binary patch "
1642 "without the reverse hunk to '%s'",
1644 ? patch
->new_name
: patch
->old_name
);
1645 fragment
= fragment
->next
;
1647 data
= (void*) fragment
->patch
;
1648 switch (fragment
->binary_patch_method
) {
1649 case BINARY_DELTA_DEFLATED
:
1650 result
= patch_delta(desc
->buffer
, desc
->size
,
1655 desc
->buffer
= result
;
1657 case BINARY_LITERAL_DEFLATED
:
1659 desc
->buffer
= data
;
1660 dst_size
= fragment
->size
;
1665 desc
->size
= desc
->alloc
= dst_size
;
1669 static int apply_binary(struct buffer_desc
*desc
, struct patch
*patch
)
1671 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
1672 unsigned char sha1
[20];
1673 unsigned char hdr
[50];
1676 /* For safety, we require patch index line to contain
1677 * full 40-byte textual SHA1 for old and new, at least for now.
1679 if (strlen(patch
->old_sha1_prefix
) != 40 ||
1680 strlen(patch
->new_sha1_prefix
) != 40 ||
1681 get_sha1_hex(patch
->old_sha1_prefix
, sha1
) ||
1682 get_sha1_hex(patch
->new_sha1_prefix
, sha1
))
1683 return error("cannot apply binary patch to '%s' "
1684 "without full index line", name
);
1686 if (patch
->old_name
) {
1687 /* See if the old one matches what the patch
1690 write_sha1_file_prepare(desc
->buffer
, desc
->size
,
1691 blob_type
, sha1
, hdr
, &hdrlen
);
1692 if (strcmp(sha1_to_hex(sha1
), patch
->old_sha1_prefix
))
1693 return error("the patch applies to '%s' (%s), "
1694 "which does not match the "
1695 "current contents.",
1696 name
, sha1_to_hex(sha1
));
1699 /* Otherwise, the old one must be empty. */
1701 return error("the patch applies to an empty "
1702 "'%s' but it is not empty", name
);
1705 get_sha1_hex(patch
->new_sha1_prefix
, sha1
);
1706 if (is_null_sha1(sha1
)) {
1708 desc
->alloc
= desc
->size
= 0;
1709 desc
->buffer
= NULL
;
1710 return 0; /* deletion patch */
1713 if (has_sha1_file(sha1
)) {
1714 /* We already have the postimage */
1719 desc
->buffer
= read_sha1_file(sha1
, type
, &size
);
1721 return error("the necessary postimage %s for "
1722 "'%s' cannot be read",
1723 patch
->new_sha1_prefix
, name
);
1724 desc
->alloc
= desc
->size
= size
;
1727 /* We have verified desc matches the preimage;
1728 * apply the patch data to it, which is stored
1729 * in the patch->fragments->{patch,size}.
1731 if (apply_binary_fragment(desc
, patch
))
1732 return error("binary patch does not apply to '%s'",
1735 /* verify that the result matches */
1736 write_sha1_file_prepare(desc
->buffer
, desc
->size
, blob_type
,
1737 sha1
, hdr
, &hdrlen
);
1738 if (strcmp(sha1_to_hex(sha1
), patch
->new_sha1_prefix
))
1739 return error("binary patch to '%s' creates incorrect result (expecting %s, got %s)", name
, patch
->new_sha1_prefix
, sha1_to_hex(sha1
));
1745 static int apply_fragments(struct buffer_desc
*desc
, struct patch
*patch
)
1747 struct fragment
*frag
= patch
->fragments
;
1748 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
1750 if (patch
->is_binary
)
1751 return apply_binary(desc
, patch
);
1754 if (apply_one_fragment(desc
, frag
, patch
->inaccurate_eof
)) {
1755 error("patch failed: %s:%ld", name
, frag
->oldpos
);
1756 if (!apply_with_reject
)
1765 static int apply_data(struct patch
*patch
, struct stat
*st
, struct cache_entry
*ce
)
1768 unsigned long size
, alloc
;
1769 struct buffer_desc desc
;
1777 buf
= read_sha1_file(ce
->sha1
, type
, &size
);
1779 return error("read of %s failed",
1784 else if (patch
->old_name
) {
1786 alloc
= size
+ 8192;
1787 buf
= xmalloc(alloc
);
1788 if (read_old_data(st
, patch
->old_name
, buf
, alloc
) != size
)
1789 return error("read of %s failed", patch
->old_name
);
1796 if (apply_fragments(&desc
, patch
) < 0)
1797 return -1; /* note with --reject this succeeds. */
1799 /* NUL terminate the result */
1800 if (desc
.alloc
<= desc
.size
)
1801 desc
.buffer
= xrealloc(desc
.buffer
, desc
.size
+ 1);
1802 desc
.buffer
[desc
.size
] = 0;
1804 patch
->result
= desc
.buffer
;
1805 patch
->resultsize
= desc
.size
;
1807 if (patch
->is_delete
&& patch
->resultsize
)
1808 return error("removal patch leaves file contents");
1813 static int check_patch(struct patch
*patch
, struct patch
*prev_patch
)
1816 const char *old_name
= patch
->old_name
;
1817 const char *new_name
= patch
->new_name
;
1818 const char *name
= old_name
? old_name
: new_name
;
1819 struct cache_entry
*ce
= NULL
;
1822 patch
->rejected
= 1; /* we will drop this after we succeed */
1826 unsigned st_mode
= 0;
1829 stat_ret
= lstat(old_name
, &st
);
1831 int pos
= cache_name_pos(old_name
, strlen(old_name
));
1833 return error("%s: does not exist in index",
1835 ce
= active_cache
[pos
];
1837 struct checkout costate
;
1838 if (errno
!= ENOENT
)
1839 return error("%s: %s", old_name
,
1842 costate
.base_dir
= "";
1843 costate
.base_dir_len
= 0;
1846 costate
.not_new
= 0;
1847 costate
.refresh_cache
= 1;
1848 if (checkout_entry(ce
,
1851 lstat(old_name
, &st
))
1855 changed
= ce_match_stat(ce
, &st
, 1);
1857 return error("%s: does not match index",
1860 st_mode
= ntohl(ce
->ce_mode
);
1862 else if (stat_ret
< 0)
1863 return error("%s: %s", old_name
, strerror(errno
));
1866 st_mode
= ntohl(create_ce_mode(st
.st_mode
));
1868 if (patch
->is_new
< 0)
1870 if (!patch
->old_mode
)
1871 patch
->old_mode
= st_mode
;
1872 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
1873 return error("%s: wrong type", old_name
);
1874 if (st_mode
!= patch
->old_mode
)
1875 fprintf(stderr
, "warning: %s has type %o, expected %o\n",
1876 old_name
, st_mode
, patch
->old_mode
);
1879 if (new_name
&& prev_patch
&& prev_patch
->is_delete
&&
1880 !strcmp(prev_patch
->old_name
, new_name
))
1881 /* A type-change diff is always split into a patch to
1882 * delete old, immediately followed by a patch to
1883 * create new (see diff.c::run_diff()); in such a case
1884 * it is Ok that the entry to be deleted by the
1885 * previous patch is still in the working tree and in
1892 if (new_name
&& (patch
->is_new
| patch
->is_rename
| patch
->is_copy
)) {
1894 cache_name_pos(new_name
, strlen(new_name
)) >= 0 &&
1896 return error("%s: already exists in index", new_name
);
1899 if (!lstat(new_name
, &nst
)) {
1900 if (S_ISDIR(nst
.st_mode
) || ok_if_exists
)
1903 return error("%s: already exists in working directory", new_name
);
1905 else if ((errno
!= ENOENT
) && (errno
!= ENOTDIR
))
1906 return error("%s: %s", new_name
, strerror(errno
));
1908 if (!patch
->new_mode
) {
1910 patch
->new_mode
= S_IFREG
| 0644;
1912 patch
->new_mode
= patch
->old_mode
;
1916 if (new_name
&& old_name
) {
1917 int same
= !strcmp(old_name
, new_name
);
1918 if (!patch
->new_mode
)
1919 patch
->new_mode
= patch
->old_mode
;
1920 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
)
1921 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
1922 patch
->new_mode
, new_name
, patch
->old_mode
,
1923 same
? "" : " of ", same
? "" : old_name
);
1926 if (apply_data(patch
, &st
, ce
) < 0)
1927 return error("%s: patch does not apply", name
);
1928 patch
->rejected
= 0;
1932 static int check_patch_list(struct patch
*patch
)
1934 struct patch
*prev_patch
= NULL
;
1937 for (prev_patch
= NULL
; patch
; patch
= patch
->next
) {
1938 if (apply_verbosely
)
1939 say_patch_name(stderr
,
1940 "Checking patch ", patch
, "...\n");
1941 err
|= check_patch(patch
, prev_patch
);
1947 static void show_index_list(struct patch
*list
)
1949 struct patch
*patch
;
1951 /* Once we start supporting the reverse patch, it may be
1952 * worth showing the new sha1 prefix, but until then...
1954 for (patch
= list
; patch
; patch
= patch
->next
) {
1955 const unsigned char *sha1_ptr
;
1956 unsigned char sha1
[20];
1959 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
1961 sha1_ptr
= null_sha1
;
1962 else if (get_sha1(patch
->old_sha1_prefix
, sha1
))
1963 die("sha1 information is lacking or useless (%s).",
1968 printf("%06o %s ",patch
->old_mode
, sha1_to_hex(sha1_ptr
));
1969 if (line_termination
&& quote_c_style(name
, NULL
, NULL
, 0))
1970 quote_c_style(name
, NULL
, stdout
, 0);
1972 fputs(name
, stdout
);
1973 putchar(line_termination
);
1977 static void stat_patch_list(struct patch
*patch
)
1979 int files
, adds
, dels
;
1981 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
1983 adds
+= patch
->lines_added
;
1984 dels
+= patch
->lines_deleted
;
1988 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files
, adds
, dels
);
1991 static void numstat_patch_list(struct patch
*patch
)
1993 for ( ; patch
; patch
= patch
->next
) {
1995 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
1996 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
1997 if (line_termination
&& quote_c_style(name
, NULL
, NULL
, 0))
1998 quote_c_style(name
, NULL
, stdout
, 0);
2000 fputs(name
, stdout
);
2005 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
2008 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
2010 printf(" %s %s\n", newdelete
, name
);
2013 static void show_mode_change(struct patch
*p
, int show_name
)
2015 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
2017 printf(" mode change %06o => %06o %s\n",
2018 p
->old_mode
, p
->new_mode
, p
->new_name
);
2020 printf(" mode change %06o => %06o\n",
2021 p
->old_mode
, p
->new_mode
);
2025 static void show_rename_copy(struct patch
*p
)
2027 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
2028 const char *old
, *new;
2030 /* Find common prefix */
2034 const char *slash_old
, *slash_new
;
2035 slash_old
= strchr(old
, '/');
2036 slash_new
= strchr(new, '/');
2039 slash_old
- old
!= slash_new
- new ||
2040 memcmp(old
, new, slash_new
- new))
2042 old
= slash_old
+ 1;
2043 new = slash_new
+ 1;
2045 /* p->old_name thru old is the common prefix, and old and new
2046 * through the end of names are renames
2048 if (old
!= p
->old_name
)
2049 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
2050 (int)(old
- p
->old_name
), p
->old_name
,
2051 old
, new, p
->score
);
2053 printf(" %s %s => %s (%d%%)\n", renamecopy
,
2054 p
->old_name
, p
->new_name
, p
->score
);
2055 show_mode_change(p
, 0);
2058 static void summary_patch_list(struct patch
*patch
)
2062 for (p
= patch
; p
; p
= p
->next
) {
2064 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
2065 else if (p
->is_delete
)
2066 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
2068 if (p
->is_rename
|| p
->is_copy
)
2069 show_rename_copy(p
);
2072 printf(" rewrite %s (%d%%)\n",
2073 p
->new_name
, p
->score
);
2074 show_mode_change(p
, 0);
2077 show_mode_change(p
, 1);
2083 static void patch_stats(struct patch
*patch
)
2085 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
2087 if (lines
> max_change
)
2089 if (patch
->old_name
) {
2090 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
2092 len
= strlen(patch
->old_name
);
2096 if (patch
->new_name
) {
2097 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
2099 len
= strlen(patch
->new_name
);
2105 static void remove_file(struct patch
*patch
)
2108 if (remove_file_from_cache(patch
->old_name
) < 0)
2109 die("unable to remove %s from index", patch
->old_name
);
2110 cache_tree_invalidate_path(active_cache_tree
, patch
->old_name
);
2113 unlink(patch
->old_name
);
2116 static void add_index_file(const char *path
, unsigned mode
, void *buf
, unsigned long size
)
2119 struct cache_entry
*ce
;
2120 int namelen
= strlen(path
);
2121 unsigned ce_size
= cache_entry_size(namelen
);
2126 ce
= xcalloc(1, ce_size
);
2127 memcpy(ce
->name
, path
, namelen
);
2128 ce
->ce_mode
= create_ce_mode(mode
);
2129 ce
->ce_flags
= htons(namelen
);
2131 if (lstat(path
, &st
) < 0)
2132 die("unable to stat newly created file %s", path
);
2133 fill_stat_cache_info(ce
, &st
);
2135 if (write_sha1_file(buf
, size
, blob_type
, ce
->sha1
) < 0)
2136 die("unable to create backing store for newly created file %s", path
);
2137 if (add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
) < 0)
2138 die("unable to add cache entry for %s", path
);
2141 static int try_create_file(const char *path
, unsigned int mode
, const char *buf
, unsigned long size
)
2146 /* Although buf:size is counted string, it also is NUL
2149 return symlink(buf
, path
);
2150 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
2154 int written
= xwrite(fd
, buf
, size
);
2156 die("writing file %s: %s", path
, strerror(errno
));
2158 die("out of space writing file %s", path
);
2163 die("closing file %s: %s", path
, strerror(errno
));
2168 * We optimistically assume that the directories exist,
2169 * which is true 99% of the time anyway. If they don't,
2170 * we create them and try again.
2172 static void create_one_file(char *path
, unsigned mode
, const char *buf
, unsigned long size
)
2176 if (!try_create_file(path
, mode
, buf
, size
))
2179 if (errno
== ENOENT
) {
2180 if (safe_create_leading_directories(path
))
2182 if (!try_create_file(path
, mode
, buf
, size
))
2186 if (errno
== EEXIST
|| errno
== EACCES
) {
2187 /* We may be trying to create a file where a directory
2192 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
) && !rmdir(path
))
2196 if (errno
== EEXIST
) {
2197 unsigned int nr
= getpid();
2200 const char *newpath
;
2201 newpath
= mkpath("%s~%u", path
, nr
);
2202 if (!try_create_file(newpath
, mode
, buf
, size
)) {
2203 if (!rename(newpath
, path
))
2208 if (errno
!= EEXIST
)
2213 die("unable to write file %s mode %o", path
, mode
);
2216 static void create_file(struct patch
*patch
)
2218 char *path
= patch
->new_name
;
2219 unsigned mode
= patch
->new_mode
;
2220 unsigned long size
= patch
->resultsize
;
2221 char *buf
= patch
->result
;
2224 mode
= S_IFREG
| 0644;
2225 create_one_file(path
, mode
, buf
, size
);
2226 add_index_file(path
, mode
, buf
, size
);
2227 cache_tree_invalidate_path(active_cache_tree
, path
);
2230 /* phase zero is to remove, phase one is to create */
2231 static void write_out_one_result(struct patch
*patch
, int phase
)
2233 if (patch
->is_delete
> 0) {
2238 if (patch
->is_new
> 0 || patch
->is_copy
) {
2244 * Rename or modification boils down to the same
2245 * thing: remove the old, write the new
2253 static int write_out_one_reject(struct patch
*patch
)
2256 char namebuf
[PATH_MAX
];
2257 struct fragment
*frag
;
2260 for (cnt
= 0, frag
= patch
->fragments
; frag
; frag
= frag
->next
) {
2261 if (!frag
->rejected
)
2267 if (apply_verbosely
)
2268 say_patch_name(stderr
,
2269 "Applied patch ", patch
, " cleanly.\n");
2273 /* This should not happen, because a removal patch that leaves
2274 * contents are marked "rejected" at the patch level.
2276 if (!patch
->new_name
)
2277 die("internal error");
2279 /* Say this even without --verbose */
2280 say_patch_name(stderr
, "Applying patch ", patch
, " with");
2281 fprintf(stderr
, " %d rejects...\n", cnt
);
2283 cnt
= strlen(patch
->new_name
);
2284 if (ARRAY_SIZE(namebuf
) <= cnt
+ 5) {
2285 cnt
= ARRAY_SIZE(namebuf
) - 5;
2287 "warning: truncating .rej filename to %.*s.rej",
2288 cnt
- 1, patch
->new_name
);
2290 memcpy(namebuf
, patch
->new_name
, cnt
);
2291 memcpy(namebuf
+ cnt
, ".rej", 5);
2293 rej
= fopen(namebuf
, "w");
2295 return error("cannot open %s: %s", namebuf
, strerror(errno
));
2297 /* Normal git tools never deal with .rej, so do not pretend
2298 * this is a git patch by saying --git nor give extended
2299 * headers. While at it, maybe please "kompare" that wants
2300 * the trailing TAB and some garbage at the end of line ;-).
2302 fprintf(rej
, "diff a/%s b/%s\t(rejected hunks)\n",
2303 patch
->new_name
, patch
->new_name
);
2304 for (cnt
= 1, frag
= patch
->fragments
;
2306 cnt
++, frag
= frag
->next
) {
2307 if (!frag
->rejected
) {
2308 fprintf(stderr
, "Hunk #%d applied cleanly.\n", cnt
);
2311 fprintf(stderr
, "Rejected hunk #%d.\n", cnt
);
2312 fprintf(rej
, "%.*s", frag
->size
, frag
->patch
);
2313 if (frag
->patch
[frag
->size
-1] != '\n')
2320 static int write_out_results(struct patch
*list
, int skipped_patch
)
2326 if (!list
&& !skipped_patch
)
2327 return error("No changes");
2329 for (phase
= 0; phase
< 2; phase
++) {
2335 write_out_one_result(l
, phase
);
2336 if (phase
== 1 && write_out_one_reject(l
))
2345 static struct lock_file lock_file
;
2347 static struct excludes
{
2348 struct excludes
*next
;
2352 static int use_patch(struct patch
*p
)
2354 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
2355 struct excludes
*x
= excludes
;
2357 if (fnmatch(x
->path
, pathname
, 0) == 0)
2361 if (0 < prefix_length
) {
2362 int pathlen
= strlen(pathname
);
2363 if (pathlen
<= prefix_length
||
2364 memcmp(prefix
, pathname
, prefix_length
))
2370 static int apply_patch(int fd
, const char *filename
, int inaccurate_eof
)
2372 unsigned long offset
, size
;
2373 char *buffer
= read_patch_file(fd
, &size
);
2374 struct patch
*list
= NULL
, **listp
= &list
;
2375 int skipped_patch
= 0;
2377 patch_input_file
= filename
;
2382 struct patch
*patch
;
2385 patch
= xcalloc(1, sizeof(*patch
));
2386 patch
->inaccurate_eof
= inaccurate_eof
;
2387 nr
= parse_chunk(buffer
+ offset
, size
, patch
);
2390 if (apply_in_reverse
)
2391 reverse_patches(patch
);
2392 if (use_patch(patch
)) {
2395 listp
= &patch
->next
;
2397 /* perhaps free it a bit better? */
2405 if (whitespace_error
&& (new_whitespace
== error_on_whitespace
))
2408 write_index
= check_index
&& apply
;
2409 if (write_index
&& newfd
< 0)
2410 newfd
= hold_lock_file_for_update(&lock_file
,
2411 get_index_file(), 1);
2413 if (read_cache() < 0)
2414 die("unable to read index file");
2417 if ((check
|| apply
) &&
2418 check_patch_list(list
) < 0 &&
2422 if (apply
&& write_out_results(list
, skipped_patch
))
2425 if (show_index_info
)
2426 show_index_list(list
);
2429 stat_patch_list(list
);
2432 numstat_patch_list(list
);
2435 summary_patch_list(list
);
2441 static int git_apply_config(const char *var
, const char *value
)
2443 if (!strcmp(var
, "apply.whitespace")) {
2444 apply_default_whitespace
= xstrdup(value
);
2447 return git_default_config(var
, value
);
2451 int cmd_apply(int argc
, const char **argv
, const char *prefix
)
2455 int inaccurate_eof
= 0;
2458 const char *whitespace_option
= NULL
;
2460 for (i
= 1; i
< argc
; i
++) {
2461 const char *arg
= argv
[i
];
2465 if (!strcmp(arg
, "-")) {
2466 errs
|= apply_patch(0, "<stdin>", inaccurate_eof
);
2470 if (!strncmp(arg
, "--exclude=", 10)) {
2471 struct excludes
*x
= xmalloc(sizeof(*x
));
2477 if (!strncmp(arg
, "-p", 2)) {
2478 p_value
= atoi(arg
+ 2);
2481 if (!strcmp(arg
, "--no-add")) {
2485 if (!strcmp(arg
, "--stat")) {
2490 if (!strcmp(arg
, "--allow-binary-replacement") ||
2491 !strcmp(arg
, "--binary")) {
2492 continue; /* now no-op */
2494 if (!strcmp(arg
, "--numstat")) {
2499 if (!strcmp(arg
, "--summary")) {
2504 if (!strcmp(arg
, "--check")) {
2509 if (!strcmp(arg
, "--index")) {
2513 if (!strcmp(arg
, "--cached")) {
2518 if (!strcmp(arg
, "--apply")) {
2522 if (!strcmp(arg
, "--index-info")) {
2524 show_index_info
= 1;
2527 if (!strcmp(arg
, "-z")) {
2528 line_termination
= 0;
2531 if (!strncmp(arg
, "-C", 2)) {
2532 p_context
= strtoul(arg
+ 2, &end
, 0);
2534 die("unrecognized context count '%s'", arg
+ 2);
2537 if (!strncmp(arg
, "--whitespace=", 13)) {
2538 whitespace_option
= arg
+ 13;
2539 parse_whitespace_option(arg
+ 13);
2542 if (!strcmp(arg
, "-R") || !strcmp(arg
, "--reverse")) {
2543 apply_in_reverse
= 1;
2546 if (!strcmp(arg
, "--reject")) {
2547 apply
= apply_with_reject
= apply_verbosely
= 1;
2550 if (!strcmp(arg
, "--verbose")) {
2551 apply_verbosely
= 1;
2554 if (!strcmp(arg
, "--inaccurate-eof")) {
2559 if (check_index
&& prefix_length
< 0) {
2560 prefix
= setup_git_directory();
2561 prefix_length
= prefix
? strlen(prefix
) : 0;
2562 git_config(git_apply_config
);
2563 if (!whitespace_option
&& apply_default_whitespace
)
2564 parse_whitespace_option(apply_default_whitespace
);
2566 if (0 < prefix_length
)
2567 arg
= prefix_filename(prefix
, prefix_length
, arg
);
2569 fd
= open(arg
, O_RDONLY
);
2573 set_default_whitespace_mode(whitespace_option
);
2574 errs
|= apply_patch(fd
, arg
, inaccurate_eof
);
2577 set_default_whitespace_mode(whitespace_option
);
2579 errs
|= apply_patch(0, "<stdin>", inaccurate_eof
);
2580 if (whitespace_error
) {
2581 if (squelch_whitespace_errors
&&
2582 squelch_whitespace_errors
< whitespace_error
) {
2584 whitespace_error
- squelch_whitespace_errors
;
2585 fprintf(stderr
, "warning: squelched %d "
2586 "whitespace error%s\n",
2588 squelched
== 1 ? "" : "s");
2590 if (new_whitespace
== error_on_whitespace
)
2591 die("%d line%s add%s trailing whitespaces.",
2593 whitespace_error
== 1 ? "" : "s",
2594 whitespace_error
== 1 ? "s" : "");
2595 if (applied_after_stripping
)
2596 fprintf(stderr
, "warning: %d line%s applied after"
2597 " stripping trailing whitespaces.\n",
2598 applied_after_stripping
,
2599 applied_after_stripping
== 1 ? "" : "s");
2600 else if (whitespace_error
)
2601 fprintf(stderr
, "warning: %d line%s add%s trailing"
2604 whitespace_error
== 1 ? "" : "s",
2605 whitespace_error
== 1 ? "s" : "");
2609 if (write_cache(newfd
, active_cache
, active_nr
) ||
2610 close(newfd
) || commit_lock_file(&lock_file
))
2611 die("Unable to write new index file");