4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
10 #include "cache-tree.h"
15 #include "string-list.h"
17 #include "parse-options.h"
20 * --check turns on checking that the working tree matches the
21 * files that are being modified, but doesn't apply the patch
22 * --stat does just a diffstat, and doesn't actually apply
23 * --numstat does numeric diffstat, and doesn't actually apply
24 * --index-info shows the old and new index info for paths if available.
25 * --index updates the cache as well.
26 * --cached updates only the cache without ever touching the working tree.
28 static const char *prefix
;
29 static int prefix_length
= -1;
30 static int newfd
= -1;
32 static int unidiff_zero
;
33 static int p_value
= 1;
34 static int p_value_known
;
35 static int check_index
;
36 static int update_index
;
43 static int apply_in_reverse
;
44 static int apply_with_reject
;
45 static int apply_verbosely
;
47 static const char *fake_ancestor
;
48 static int line_termination
= '\n';
49 static unsigned int p_context
= UINT_MAX
;
50 static const char * const apply_usage
[] = {
51 "git apply [options] [<patch>...]",
55 static enum ws_error_action
{
60 } ws_error_action
= warn_on_ws_error
;
61 static int whitespace_error
;
62 static int squelch_whitespace_errors
= 5;
63 static int applied_after_fixing_ws
;
65 static enum ws_ignore
{
68 } ws_ignore_action
= ignore_ws_none
;
71 static const char *patch_input_file
;
72 static const char *root
;
74 static int read_stdin
= 1;
77 static void parse_whitespace_option(const char *option
)
80 ws_error_action
= warn_on_ws_error
;
83 if (!strcmp(option
, "warn")) {
84 ws_error_action
= warn_on_ws_error
;
87 if (!strcmp(option
, "nowarn")) {
88 ws_error_action
= nowarn_ws_error
;
91 if (!strcmp(option
, "error")) {
92 ws_error_action
= die_on_ws_error
;
95 if (!strcmp(option
, "error-all")) {
96 ws_error_action
= die_on_ws_error
;
97 squelch_whitespace_errors
= 0;
100 if (!strcmp(option
, "strip") || !strcmp(option
, "fix")) {
101 ws_error_action
= correct_ws_error
;
104 die("unrecognized whitespace option '%s'", option
);
107 static void parse_ignorewhitespace_option(const char *option
)
109 if (!option
|| !strcmp(option
, "no") ||
110 !strcmp(option
, "false") || !strcmp(option
, "never") ||
111 !strcmp(option
, "none")) {
112 ws_ignore_action
= ignore_ws_none
;
115 if (!strcmp(option
, "change")) {
116 ws_ignore_action
= ignore_ws_change
;
119 die("unrecognized whitespace ignore option '%s'", option
);
122 static void set_default_whitespace_mode(const char *whitespace_option
)
124 if (!whitespace_option
&& !apply_default_whitespace
)
125 ws_error_action
= (apply
? warn_on_ws_error
: nowarn_ws_error
);
129 * For "diff-stat" like behaviour, we keep track of the biggest change
130 * we've seen, and the longest filename. That allows us to do simple
133 static int max_change
, max_len
;
136 * Various "current state", notably line numbers and what
137 * file (and how) we're patching right now.. The "is_xxxx"
138 * things are flags, where -1 means "don't know yet".
140 static int linenr
= 1;
143 * This represents one "hunk" from a patch, starting with
144 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
145 * patch text is pointed at by patch, and its byte length
146 * is stored in size. leading and trailing are the number
150 unsigned long leading
, trailing
;
151 unsigned long oldpos
, oldlines
;
152 unsigned long newpos
, newlines
;
156 struct fragment
*next
;
160 * When dealing with a binary patch, we reuse "leading" field
161 * to store the type of the binary hunk, either deflated "delta"
162 * or deflated "literal".
164 #define binary_patch_method leading
165 #define BINARY_DELTA_DEFLATED 1
166 #define BINARY_LITERAL_DEFLATED 2
169 * This represents a "patch" to a file, both metainfo changes
170 * such as creation/deletion, filemode and content changes represented
171 * as a series of fragments.
174 char *new_name
, *old_name
, *def_name
;
175 unsigned int old_mode
, new_mode
;
176 int is_new
, is_delete
; /* -1 = unknown, 0 = false, 1 = true */
179 unsigned long deflate_origlen
;
180 int lines_added
, lines_deleted
;
182 unsigned int is_toplevel_relative
:1;
183 unsigned int inaccurate_eof
:1;
184 unsigned int is_binary
:1;
185 unsigned int is_copy
:1;
186 unsigned int is_rename
:1;
187 unsigned int recount
:1;
188 struct fragment
*fragments
;
191 char old_sha1_prefix
[41];
192 char new_sha1_prefix
[41];
197 * A line in a file, len-bytes long (includes the terminating LF,
198 * except for an incomplete line at the end if the file ends with
199 * one), and its contents hashes to 'hash'.
205 #define LINE_COMMON 1
209 * This represents a "file", which is an array of "lines".
216 struct line
*line_allocated
;
221 * Records filenames that have been touched, in order to handle
222 * the case where more than one patches touch the same file.
225 static struct string_list fn_table
;
227 static uint32_t hash_line(const char *cp
, size_t len
)
231 for (i
= 0, h
= 0; i
< len
; i
++) {
232 if (!isspace(cp
[i
])) {
233 h
= h
* 3 + (cp
[i
] & 0xff);
240 * Compare lines s1 of length n1 and s2 of length n2, ignoring
241 * whitespace difference. Returns 1 if they match, 0 otherwise
243 static int fuzzy_matchlines(const char *s1
, size_t n1
,
244 const char *s2
, size_t n2
)
246 const char *last1
= s1
+ n1
- 1;
247 const char *last2
= s2
+ n2
- 1;
250 if (n1
< 0 || n2
< 0)
253 /* ignore line endings */
254 while ((*last1
== '\r') || (*last1
== '\n'))
256 while ((*last2
== '\r') || (*last2
== '\n'))
259 /* skip leading whitespace */
260 while (isspace(*s1
) && (s1
<= last1
))
262 while (isspace(*s2
) && (s2
<= last2
))
264 /* early return if both lines are empty */
265 if ((s1
> last1
) && (s2
> last2
))
268 result
= *s1
++ - *s2
++;
270 * Skip whitespace inside. We check for whitespace on
271 * both buffers because we don't want "a b" to match
274 if (isspace(*s1
) && isspace(*s2
)) {
275 while (isspace(*s1
) && s1
<= last1
)
277 while (isspace(*s2
) && s2
<= last2
)
281 * If we reached the end on one side only,
285 ((s2
> last2
) && (s1
<= last1
)) ||
286 ((s1
> last1
) && (s2
<= last2
)))
288 if ((s1
> last1
) && (s2
> last2
))
295 static void add_line_info(struct image
*img
, const char *bol
, size_t len
, unsigned flag
)
297 ALLOC_GROW(img
->line_allocated
, img
->nr
+ 1, img
->alloc
);
298 img
->line_allocated
[img
->nr
].len
= len
;
299 img
->line_allocated
[img
->nr
].hash
= hash_line(bol
, len
);
300 img
->line_allocated
[img
->nr
].flag
= flag
;
304 static void prepare_image(struct image
*image
, char *buf
, size_t len
,
305 int prepare_linetable
)
309 memset(image
, 0, sizeof(*image
));
313 if (!prepare_linetable
)
316 ep
= image
->buf
+ image
->len
;
320 for (next
= cp
; next
< ep
&& *next
!= '\n'; next
++)
324 add_line_info(image
, cp
, next
- cp
, 0);
327 image
->line
= image
->line_allocated
;
330 static void clear_image(struct image
*image
)
337 static void say_patch_name(FILE *output
, const char *pre
,
338 struct patch
*patch
, const char *post
)
341 if (patch
->old_name
&& patch
->new_name
&&
342 strcmp(patch
->old_name
, patch
->new_name
)) {
343 quote_c_style(patch
->old_name
, NULL
, output
, 0);
344 fputs(" => ", output
);
345 quote_c_style(patch
->new_name
, NULL
, output
, 0);
347 const char *n
= patch
->new_name
;
350 quote_c_style(n
, NULL
, output
, 0);
355 #define CHUNKSIZE (8192)
358 static void read_patch_file(struct strbuf
*sb
, int fd
)
360 if (strbuf_read(sb
, fd
, 0) < 0)
361 die_errno("git apply: failed to read");
364 * Make sure that we have some slop in the buffer
365 * so that we can do speculative "memcmp" etc, and
366 * see to it that it is NUL-filled.
368 strbuf_grow(sb
, SLOP
);
369 memset(sb
->buf
+ sb
->len
, 0, SLOP
);
372 static unsigned long linelen(const char *buffer
, unsigned long size
)
374 unsigned long len
= 0;
377 if (*buffer
++ == '\n')
383 static int is_dev_null(const char *str
)
385 return !memcmp("/dev/null", str
, 9) && isspace(str
[9]);
391 static int name_terminate(const char *name
, int namelen
, int c
, int terminate
)
393 if (c
== ' ' && !(terminate
& TERM_SPACE
))
395 if (c
== '\t' && !(terminate
& TERM_TAB
))
401 /* remove double slashes to make --index work with such filenames */
402 static char *squash_slash(char *name
)
407 if ((name
[j
++] = name
[i
++]) == '/')
408 while (name
[i
] == '/')
415 static char *find_name(const char *line
, char *def
, int p_value
, int terminate
)
418 const char *start
= line
;
421 struct strbuf name
= STRBUF_INIT
;
424 * Proposed "new-style" GNU patch/diff format; see
425 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
427 if (!unquote_c_style(&name
, line
, NULL
)) {
430 for (cp
= name
.buf
; p_value
; p_value
--) {
431 cp
= strchr(cp
, '/');
437 /* name can later be freed, so we need
438 * to memmove, not just return cp
440 strbuf_remove(&name
, 0, cp
- name
.buf
);
443 strbuf_insert(&name
, 0, root
, root_len
);
444 return squash_slash(strbuf_detach(&name
, NULL
));
447 strbuf_release(&name
);
456 if (name_terminate(start
, line
-start
, c
, terminate
))
460 if (c
== '/' && !--p_value
)
464 return squash_slash(def
);
467 return squash_slash(def
);
470 * Generally we prefer the shorter name, especially
471 * if the other one is just a variation of that with
472 * something else tacked on to the end (ie "file.orig"
476 int deflen
= strlen(def
);
477 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
478 return squash_slash(def
);
483 char *ret
= xmalloc(root_len
+ len
+ 1);
485 memcpy(ret
+ root_len
, start
, len
);
486 ret
[root_len
+ len
] = '\0';
487 return squash_slash(ret
);
490 return squash_slash(xmemdupz(start
, len
));
493 static int count_slashes(const char *cp
)
505 * Given the string after "--- " or "+++ ", guess the appropriate
506 * p_value for the given patch.
508 static int guess_p_value(const char *nameline
)
513 if (is_dev_null(nameline
))
515 name
= find_name(nameline
, NULL
, 0, TERM_SPACE
| TERM_TAB
);
518 cp
= strchr(name
, '/');
523 * Does it begin with "a/$our-prefix" and such? Then this is
524 * very likely to apply to our directory.
526 if (!strncmp(name
, prefix
, prefix_length
))
527 val
= count_slashes(prefix
);
530 if (!strncmp(cp
, prefix
, prefix_length
))
531 val
= count_slashes(prefix
) + 1;
539 * Get the name etc info from the ---/+++ lines of a traditional patch header
541 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
542 * files, we can happily check the index for a match, but for creating a
543 * new file we should try to match whatever "patch" does. I have no idea.
545 static void parse_traditional_patch(const char *first
, const char *second
, struct patch
*patch
)
549 first
+= 4; /* skip "--- " */
550 second
+= 4; /* skip "+++ " */
551 if (!p_value_known
) {
553 p
= guess_p_value(first
);
554 q
= guess_p_value(second
);
556 if (0 <= p
&& p
== q
) {
561 if (is_dev_null(first
)) {
563 patch
->is_delete
= 0;
564 name
= find_name(second
, NULL
, p_value
, TERM_SPACE
| TERM_TAB
);
565 patch
->new_name
= name
;
566 } else if (is_dev_null(second
)) {
568 patch
->is_delete
= 1;
569 name
= find_name(first
, NULL
, p_value
, TERM_SPACE
| TERM_TAB
);
570 patch
->old_name
= name
;
572 name
= find_name(first
, NULL
, p_value
, TERM_SPACE
| TERM_TAB
);
573 name
= find_name(second
, name
, p_value
, TERM_SPACE
| TERM_TAB
);
574 patch
->old_name
= patch
->new_name
= name
;
577 die("unable to find filename in patch at line %d", linenr
);
580 static int gitdiff_hdrend(const char *line
, struct patch
*patch
)
586 * We're anal about diff header consistency, to make
587 * sure that we don't end up having strange ambiguous
588 * patches floating around.
590 * As a result, gitdiff_{old|new}name() will check
591 * their names against any previous information, just
594 static char *gitdiff_verify_name(const char *line
, int isnull
, char *orig_name
, const char *oldnew
)
596 if (!orig_name
&& !isnull
)
597 return find_name(line
, NULL
, p_value
, TERM_TAB
);
606 die("git apply: bad git-diff - expected /dev/null, got %s on line %d", name
, linenr
);
607 another
= find_name(line
, NULL
, p_value
, TERM_TAB
);
608 if (!another
|| memcmp(another
, name
, len
))
609 die("git apply: bad git-diff - inconsistent %s filename on line %d", oldnew
, linenr
);
614 /* expect "/dev/null" */
615 if (memcmp("/dev/null", line
, 9) || line
[9] != '\n')
616 die("git apply: bad git-diff - expected /dev/null on line %d", linenr
);
621 static int gitdiff_oldname(const char *line
, struct patch
*patch
)
623 patch
->old_name
= gitdiff_verify_name(line
, patch
->is_new
, patch
->old_name
, "old");
627 static int gitdiff_newname(const char *line
, struct patch
*patch
)
629 patch
->new_name
= gitdiff_verify_name(line
, patch
->is_delete
, patch
->new_name
, "new");
633 static int gitdiff_oldmode(const char *line
, struct patch
*patch
)
635 patch
->old_mode
= strtoul(line
, NULL
, 8);
639 static int gitdiff_newmode(const char *line
, struct patch
*patch
)
641 patch
->new_mode
= strtoul(line
, NULL
, 8);
645 static int gitdiff_delete(const char *line
, struct patch
*patch
)
647 patch
->is_delete
= 1;
648 patch
->old_name
= patch
->def_name
;
649 return gitdiff_oldmode(line
, patch
);
652 static int gitdiff_newfile(const char *line
, struct patch
*patch
)
655 patch
->new_name
= patch
->def_name
;
656 return gitdiff_newmode(line
, patch
);
659 static int gitdiff_copysrc(const char *line
, struct patch
*patch
)
662 patch
->old_name
= find_name(line
, NULL
, 0, 0);
666 static int gitdiff_copydst(const char *line
, struct patch
*patch
)
669 patch
->new_name
= find_name(line
, NULL
, 0, 0);
673 static int gitdiff_renamesrc(const char *line
, struct patch
*patch
)
675 patch
->is_rename
= 1;
676 patch
->old_name
= find_name(line
, NULL
, 0, 0);
680 static int gitdiff_renamedst(const char *line
, struct patch
*patch
)
682 patch
->is_rename
= 1;
683 patch
->new_name
= find_name(line
, NULL
, 0, 0);
687 static int gitdiff_similarity(const char *line
, struct patch
*patch
)
689 if ((patch
->score
= strtoul(line
, NULL
, 10)) == ULONG_MAX
)
694 static int gitdiff_dissimilarity(const char *line
, struct patch
*patch
)
696 if ((patch
->score
= strtoul(line
, NULL
, 10)) == ULONG_MAX
)
701 static int gitdiff_index(const char *line
, struct patch
*patch
)
704 * index line is N hexadecimal, "..", N hexadecimal,
705 * and optional space with octal mode.
707 const char *ptr
, *eol
;
710 ptr
= strchr(line
, '.');
711 if (!ptr
|| ptr
[1] != '.' || 40 < ptr
- line
)
714 memcpy(patch
->old_sha1_prefix
, line
, len
);
715 patch
->old_sha1_prefix
[len
] = 0;
718 ptr
= strchr(line
, ' ');
719 eol
= strchr(line
, '\n');
721 if (!ptr
|| eol
< ptr
)
727 memcpy(patch
->new_sha1_prefix
, line
, len
);
728 patch
->new_sha1_prefix
[len
] = 0;
730 patch
->old_mode
= strtoul(ptr
+1, NULL
, 8);
735 * This is normal for a diff that doesn't change anything: we'll fall through
736 * into the next diff. Tell the parser to break out.
738 static int gitdiff_unrecognized(const char *line
, struct patch
*patch
)
743 static const char *stop_at_slash(const char *line
, int llen
)
747 for (i
= 0; i
< llen
; i
++) {
756 * This is to extract the same name that appears on "diff --git"
757 * line. We do not find and return anything if it is a rename
758 * patch, and it is OK because we will find the name elsewhere.
759 * We need to reliably find name only when it is mode-change only,
760 * creation or deletion of an empty file. In any of these cases,
761 * both sides are the same name under a/ and b/ respectively.
763 static char *git_header_name(char *line
, int llen
)
766 const char *second
= NULL
;
769 line
+= strlen("diff --git ");
770 llen
-= strlen("diff --git ");
774 struct strbuf first
= STRBUF_INIT
;
775 struct strbuf sp
= STRBUF_INIT
;
777 if (unquote_c_style(&first
, line
, &second
))
780 /* advance to the first slash */
781 cp
= stop_at_slash(first
.buf
, first
.len
);
782 /* we do not accept absolute paths */
783 if (!cp
|| cp
== first
.buf
)
785 strbuf_remove(&first
, 0, cp
+ 1 - first
.buf
);
788 * second points at one past closing dq of name.
789 * find the second name.
791 while ((second
< line
+ llen
) && isspace(*second
))
794 if (line
+ llen
<= second
)
796 if (*second
== '"') {
797 if (unquote_c_style(&sp
, second
, NULL
))
799 cp
= stop_at_slash(sp
.buf
, sp
.len
);
800 if (!cp
|| cp
== sp
.buf
)
802 /* They must match, otherwise ignore */
803 if (strcmp(cp
+ 1, first
.buf
))
806 return strbuf_detach(&first
, NULL
);
809 /* unquoted second */
810 cp
= stop_at_slash(second
, line
+ llen
- second
);
811 if (!cp
|| cp
== second
)
814 if (line
+ llen
- cp
!= first
.len
+ 1 ||
815 memcmp(first
.buf
, cp
, first
.len
))
817 return strbuf_detach(&first
, NULL
);
820 strbuf_release(&first
);
825 /* unquoted first name */
826 name
= stop_at_slash(line
, llen
);
827 if (!name
|| name
== line
)
832 * since the first name is unquoted, a dq if exists must be
833 * the beginning of the second name.
835 for (second
= name
; second
< line
+ llen
; second
++) {
836 if (*second
== '"') {
837 struct strbuf sp
= STRBUF_INIT
;
840 if (unquote_c_style(&sp
, second
, NULL
))
843 np
= stop_at_slash(sp
.buf
, sp
.len
);
844 if (!np
|| np
== sp
.buf
)
848 len
= sp
.buf
+ sp
.len
- np
;
849 if (len
< second
- name
&&
850 !strncmp(np
, name
, len
) &&
851 isspace(name
[len
])) {
853 strbuf_remove(&sp
, 0, np
- sp
.buf
);
854 return strbuf_detach(&sp
, NULL
);
864 * Accept a name only if it shows up twice, exactly the same
867 for (len
= 0 ; ; len
++) {
882 if (second
[len
] == '\n' && !memcmp(name
, second
, len
)) {
883 return xmemdupz(name
, len
);
889 /* Verify that we recognize the lines following a git header */
890 static int parse_git_header(char *line
, int len
, unsigned int size
, struct patch
*patch
)
892 unsigned long offset
;
894 /* A git diff has explicit new/delete information, so we don't guess */
896 patch
->is_delete
= 0;
899 * Some things may not have the old name in the
900 * rest of the headers anywhere (pure mode changes,
901 * or removing or adding empty files), so we get
902 * the default name from the header.
904 patch
->def_name
= git_header_name(line
, len
);
905 if (patch
->def_name
&& root
) {
906 char *s
= xmalloc(root_len
+ strlen(patch
->def_name
) + 1);
908 strcpy(s
+ root_len
, patch
->def_name
);
909 free(patch
->def_name
);
916 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
917 static const struct opentry
{
919 int (*fn
)(const char *, struct patch
*);
921 { "@@ -", gitdiff_hdrend
},
922 { "--- ", gitdiff_oldname
},
923 { "+++ ", gitdiff_newname
},
924 { "old mode ", gitdiff_oldmode
},
925 { "new mode ", gitdiff_newmode
},
926 { "deleted file mode ", gitdiff_delete
},
927 { "new file mode ", gitdiff_newfile
},
928 { "copy from ", gitdiff_copysrc
},
929 { "copy to ", gitdiff_copydst
},
930 { "rename old ", gitdiff_renamesrc
},
931 { "rename new ", gitdiff_renamedst
},
932 { "rename from ", gitdiff_renamesrc
},
933 { "rename to ", gitdiff_renamedst
},
934 { "similarity index ", gitdiff_similarity
},
935 { "dissimilarity index ", gitdiff_dissimilarity
},
936 { "index ", gitdiff_index
},
937 { "", gitdiff_unrecognized
},
941 len
= linelen(line
, size
);
942 if (!len
|| line
[len
-1] != '\n')
944 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
945 const struct opentry
*p
= optable
+ i
;
946 int oplen
= strlen(p
->str
);
947 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
949 if (p
->fn(line
+ oplen
, patch
) < 0)
958 static int parse_num(const char *line
, unsigned long *p
)
964 *p
= strtoul(line
, &ptr
, 10);
968 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
969 unsigned long *p1
, unsigned long *p2
)
973 if (offset
< 0 || offset
>= len
)
978 digits
= parse_num(line
, p1
);
988 digits
= parse_num(line
+1, p2
);
1000 if (memcmp(line
, expect
, ex
))
1006 static void recount_diff(char *line
, int size
, struct fragment
*fragment
)
1008 int oldlines
= 0, newlines
= 0, ret
= 0;
1011 warning("recount: ignore empty hunk");
1016 int len
= linelen(line
, size
);
1024 case ' ': case '\n':
1036 ret
= size
< 3 || prefixcmp(line
, "@@ ");
1039 ret
= size
< 5 || prefixcmp(line
, "diff ");
1046 warning("recount: unexpected line: %.*s",
1047 (int)linelen(line
, size
), line
);
1052 fragment
->oldlines
= oldlines
;
1053 fragment
->newlines
= newlines
;
1057 * Parse a unified diff fragment header of the
1058 * form "@@ -a,b +c,d @@"
1060 static int parse_fragment_header(char *line
, int len
, struct fragment
*fragment
)
1064 if (!len
|| line
[len
-1] != '\n')
1067 /* Figure out the number of lines in a fragment */
1068 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
1069 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
1074 static int find_header(char *line
, unsigned long size
, int *hdrsize
, struct patch
*patch
)
1076 unsigned long offset
, len
;
1078 patch
->is_toplevel_relative
= 0;
1079 patch
->is_rename
= patch
->is_copy
= 0;
1080 patch
->is_new
= patch
->is_delete
= -1;
1081 patch
->old_mode
= patch
->new_mode
= 0;
1082 patch
->old_name
= patch
->new_name
= NULL
;
1083 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1084 unsigned long nextlen
;
1086 len
= linelen(line
, size
);
1090 /* Testing this early allows us to take a few shortcuts.. */
1095 * Make sure we don't find any unconnected patch fragments.
1096 * That's a sign that we didn't find a header, and that a
1097 * patch has become corrupted/broken up.
1099 if (!memcmp("@@ -", line
, 4)) {
1100 struct fragment dummy
;
1101 if (parse_fragment_header(line
, len
, &dummy
) < 0)
1103 die("patch fragment without header at line %d: %.*s",
1104 linenr
, (int)len
-1, line
);
1111 * Git patch? It might not have a real patch, just a rename
1112 * or mode change, so we handle that specially
1114 if (!memcmp("diff --git ", line
, 11)) {
1115 int git_hdr_len
= parse_git_header(line
, len
, size
, patch
);
1116 if (git_hdr_len
<= len
)
1118 if (!patch
->old_name
&& !patch
->new_name
) {
1119 if (!patch
->def_name
)
1120 die("git diff header lacks filename information (line %d)", linenr
);
1121 patch
->old_name
= patch
->new_name
= patch
->def_name
;
1123 patch
->is_toplevel_relative
= 1;
1124 *hdrsize
= git_hdr_len
;
1128 /* --- followed by +++ ? */
1129 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
1133 * We only accept unified patches, so we want it to
1134 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1135 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1137 nextlen
= linelen(line
+ len
, size
- len
);
1138 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
1141 /* Ok, we'll consider it a patch */
1142 parse_traditional_patch(line
, line
+len
, patch
);
1143 *hdrsize
= len
+ nextlen
;
1150 static void check_whitespace(const char *line
, int len
, unsigned ws_rule
)
1153 unsigned result
= ws_check(line
+ 1, len
- 1, ws_rule
);
1158 if (squelch_whitespace_errors
&&
1159 squelch_whitespace_errors
< whitespace_error
)
1162 err
= whitespace_error_string(result
);
1163 fprintf(stderr
, "%s:%d: %s.\n%.*s\n",
1164 patch_input_file
, linenr
, err
, len
- 2, line
+ 1);
1170 * Parse a unified diff. Note that this really needs to parse each
1171 * fragment separately, since the only way to know the difference
1172 * between a "---" that is part of a patch, and a "---" that starts
1173 * the next patch is to look at the line counts..
1175 static int parse_fragment(char *line
, unsigned long size
,
1176 struct patch
*patch
, struct fragment
*fragment
)
1179 int len
= linelen(line
, size
), offset
;
1180 unsigned long oldlines
, newlines
;
1181 unsigned long leading
, trailing
;
1183 offset
= parse_fragment_header(line
, len
, fragment
);
1186 if (offset
> 0 && patch
->recount
)
1187 recount_diff(line
+ offset
, size
- offset
, fragment
);
1188 oldlines
= fragment
->oldlines
;
1189 newlines
= fragment
->newlines
;
1193 /* Parse the thing.. */
1197 added
= deleted
= 0;
1200 offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1201 if (!oldlines
&& !newlines
)
1203 len
= linelen(line
, size
);
1204 if (!len
|| line
[len
-1] != '\n')
1209 case '\n': /* newer GNU diff, an empty context line */
1213 if (!deleted
&& !added
)
1218 if (apply_in_reverse
&&
1219 ws_error_action
!= nowarn_ws_error
)
1220 check_whitespace(line
, len
, patch
->ws_rule
);
1226 if (!apply_in_reverse
&&
1227 ws_error_action
!= nowarn_ws_error
)
1228 check_whitespace(line
, len
, patch
->ws_rule
);
1235 * We allow "\ No newline at end of file". Depending
1236 * on locale settings when the patch was produced we
1237 * don't know what this line looks like. The only
1238 * thing we do know is that it begins with "\ ".
1239 * Checking for 12 is just for sanity check -- any
1240 * l10n of "\ No newline..." is at least that long.
1243 if (len
< 12 || memcmp(line
, "\\ ", 2))
1248 if (oldlines
|| newlines
)
1250 fragment
->leading
= leading
;
1251 fragment
->trailing
= trailing
;
1254 * If a fragment ends with an incomplete line, we failed to include
1255 * it in the above loop because we hit oldlines == newlines == 0
1258 if (12 < size
&& !memcmp(line
, "\\ ", 2))
1259 offset
+= linelen(line
, size
);
1261 patch
->lines_added
+= added
;
1262 patch
->lines_deleted
+= deleted
;
1264 if (0 < patch
->is_new
&& oldlines
)
1265 return error("new file depends on old contents");
1266 if (0 < patch
->is_delete
&& newlines
)
1267 return error("deleted file still has contents");
1271 static int parse_single_patch(char *line
, unsigned long size
, struct patch
*patch
)
1273 unsigned long offset
= 0;
1274 unsigned long oldlines
= 0, newlines
= 0, context
= 0;
1275 struct fragment
**fragp
= &patch
->fragments
;
1277 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
1278 struct fragment
*fragment
;
1281 fragment
= xcalloc(1, sizeof(*fragment
));
1282 len
= parse_fragment(line
, size
, patch
, fragment
);
1284 die("corrupt patch at line %d", linenr
);
1285 fragment
->patch
= line
;
1286 fragment
->size
= len
;
1287 oldlines
+= fragment
->oldlines
;
1288 newlines
+= fragment
->newlines
;
1289 context
+= fragment
->leading
+ fragment
->trailing
;
1292 fragp
= &fragment
->next
;
1300 * If something was removed (i.e. we have old-lines) it cannot
1301 * be creation, and if something was added it cannot be
1302 * deletion. However, the reverse is not true; --unified=0
1303 * patches that only add are not necessarily creation even
1304 * though they do not have any old lines, and ones that only
1305 * delete are not necessarily deletion.
1307 * Unfortunately, a real creation/deletion patch do _not_ have
1308 * any context line by definition, so we cannot safely tell it
1309 * apart with --unified=0 insanity. At least if the patch has
1310 * more than one hunk it is not creation or deletion.
1312 if (patch
->is_new
< 0 &&
1313 (oldlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1315 if (patch
->is_delete
< 0 &&
1316 (newlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1317 patch
->is_delete
= 0;
1319 if (0 < patch
->is_new
&& oldlines
)
1320 die("new file %s depends on old contents", patch
->new_name
);
1321 if (0 < patch
->is_delete
&& newlines
)
1322 die("deleted file %s still has contents", patch
->old_name
);
1323 if (!patch
->is_delete
&& !newlines
&& context
)
1324 fprintf(stderr
, "** warning: file %s becomes empty but "
1325 "is not deleted\n", patch
->new_name
);
1330 static inline int metadata_changes(struct patch
*patch
)
1332 return patch
->is_rename
> 0 ||
1333 patch
->is_copy
> 0 ||
1334 patch
->is_new
> 0 ||
1336 (patch
->old_mode
&& patch
->new_mode
&&
1337 patch
->old_mode
!= patch
->new_mode
);
1340 static char *inflate_it(const void *data
, unsigned long size
,
1341 unsigned long inflated_size
)
1347 memset(&stream
, 0, sizeof(stream
));
1349 stream
.next_in
= (unsigned char *)data
;
1350 stream
.avail_in
= size
;
1351 stream
.next_out
= out
= xmalloc(inflated_size
);
1352 stream
.avail_out
= inflated_size
;
1353 git_inflate_init(&stream
);
1354 st
= git_inflate(&stream
, Z_FINISH
);
1355 git_inflate_end(&stream
);
1356 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1363 static struct fragment
*parse_binary_hunk(char **buf_p
,
1364 unsigned long *sz_p
,
1369 * Expect a line that begins with binary patch method ("literal"
1370 * or "delta"), followed by the length of data before deflating.
1371 * a sequence of 'length-byte' followed by base-85 encoded data
1372 * should follow, terminated by a newline.
1374 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1375 * and we would limit the patch line to 66 characters,
1376 * so one line can fit up to 13 groups that would decode
1377 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1378 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1381 unsigned long size
= *sz_p
;
1382 char *buffer
= *buf_p
;
1384 unsigned long origlen
;
1387 struct fragment
*frag
;
1389 llen
= linelen(buffer
, size
);
1394 if (!prefixcmp(buffer
, "delta ")) {
1395 patch_method
= BINARY_DELTA_DEFLATED
;
1396 origlen
= strtoul(buffer
+ 6, NULL
, 10);
1398 else if (!prefixcmp(buffer
, "literal ")) {
1399 patch_method
= BINARY_LITERAL_DEFLATED
;
1400 origlen
= strtoul(buffer
+ 8, NULL
, 10);
1408 int byte_length
, max_byte_length
, newsize
;
1409 llen
= linelen(buffer
, size
);
1413 /* consume the blank line */
1419 * Minimum line is "A00000\n" which is 7-byte long,
1420 * and the line length must be multiple of 5 plus 2.
1422 if ((llen
< 7) || (llen
-2) % 5)
1424 max_byte_length
= (llen
- 2) / 5 * 4;
1425 byte_length
= *buffer
;
1426 if ('A' <= byte_length
&& byte_length
<= 'Z')
1427 byte_length
= byte_length
- 'A' + 1;
1428 else if ('a' <= byte_length
&& byte_length
<= 'z')
1429 byte_length
= byte_length
- 'a' + 27;
1432 /* if the input length was not multiple of 4, we would
1433 * have filler at the end but the filler should never
1436 if (max_byte_length
< byte_length
||
1437 byte_length
<= max_byte_length
- 4)
1439 newsize
= hunk_size
+ byte_length
;
1440 data
= xrealloc(data
, newsize
);
1441 if (decode_85(data
+ hunk_size
, buffer
+ 1, byte_length
))
1443 hunk_size
= newsize
;
1448 frag
= xcalloc(1, sizeof(*frag
));
1449 frag
->patch
= inflate_it(data
, hunk_size
, origlen
);
1453 frag
->size
= origlen
;
1457 frag
->binary_patch_method
= patch_method
;
1463 error("corrupt binary patch at line %d: %.*s",
1464 linenr
-1, llen
-1, buffer
);
1468 static int parse_binary(char *buffer
, unsigned long size
, struct patch
*patch
)
1471 * We have read "GIT binary patch\n"; what follows is a line
1472 * that says the patch method (currently, either "literal" or
1473 * "delta") and the length of data before deflating; a
1474 * sequence of 'length-byte' followed by base-85 encoded data
1477 * When a binary patch is reversible, there is another binary
1478 * hunk in the same format, starting with patch method (either
1479 * "literal" or "delta") with the length of data, and a sequence
1480 * of length-byte + base-85 encoded data, terminated with another
1481 * empty line. This data, when applied to the postimage, produces
1484 struct fragment
*forward
;
1485 struct fragment
*reverse
;
1489 forward
= parse_binary_hunk(&buffer
, &size
, &status
, &used
);
1490 if (!forward
&& !status
)
1491 /* there has to be one hunk (forward hunk) */
1492 return error("unrecognized binary patch at line %d", linenr
-1);
1494 /* otherwise we already gave an error message */
1497 reverse
= parse_binary_hunk(&buffer
, &size
, &status
, &used_1
);
1502 * Not having reverse hunk is not an error, but having
1503 * a corrupt reverse hunk is.
1505 free((void*) forward
->patch
);
1509 forward
->next
= reverse
;
1510 patch
->fragments
= forward
;
1511 patch
->is_binary
= 1;
1515 static int parse_chunk(char *buffer
, unsigned long size
, struct patch
*patch
)
1517 int hdrsize
, patchsize
;
1518 int offset
= find_header(buffer
, size
, &hdrsize
, patch
);
1523 patch
->ws_rule
= whitespace_rule(patch
->new_name
1527 patchsize
= parse_single_patch(buffer
+ offset
+ hdrsize
,
1528 size
- offset
- hdrsize
, patch
);
1531 static const char *binhdr
[] = {
1536 static const char git_binary
[] = "GIT binary patch\n";
1538 int hd
= hdrsize
+ offset
;
1539 unsigned long llen
= linelen(buffer
+ hd
, size
- hd
);
1541 if (llen
== sizeof(git_binary
) - 1 &&
1542 !memcmp(git_binary
, buffer
+ hd
, llen
)) {
1545 used
= parse_binary(buffer
+ hd
+ llen
,
1546 size
- hd
- llen
, patch
);
1548 patchsize
= used
+ llen
;
1552 else if (!memcmp(" differ\n", buffer
+ hd
+ llen
- 8, 8)) {
1553 for (i
= 0; binhdr
[i
]; i
++) {
1554 int len
= strlen(binhdr
[i
]);
1555 if (len
< size
- hd
&&
1556 !memcmp(binhdr
[i
], buffer
+ hd
, len
)) {
1558 patch
->is_binary
= 1;
1565 /* Empty patch cannot be applied if it is a text patch
1566 * without metadata change. A binary patch appears
1569 if ((apply
|| check
) &&
1570 (!patch
->is_binary
&& !metadata_changes(patch
)))
1571 die("patch with only garbage at line %d", linenr
);
1574 return offset
+ hdrsize
+ patchsize
;
1577 #define swap(a,b) myswap((a),(b),sizeof(a))
1579 #define myswap(a, b, size) do { \
1580 unsigned char mytmp[size]; \
1581 memcpy(mytmp, &a, size); \
1582 memcpy(&a, &b, size); \
1583 memcpy(&b, mytmp, size); \
1586 static void reverse_patches(struct patch
*p
)
1588 for (; p
; p
= p
->next
) {
1589 struct fragment
*frag
= p
->fragments
;
1591 swap(p
->new_name
, p
->old_name
);
1592 swap(p
->new_mode
, p
->old_mode
);
1593 swap(p
->is_new
, p
->is_delete
);
1594 swap(p
->lines_added
, p
->lines_deleted
);
1595 swap(p
->old_sha1_prefix
, p
->new_sha1_prefix
);
1597 for (; frag
; frag
= frag
->next
) {
1598 swap(frag
->newpos
, frag
->oldpos
);
1599 swap(frag
->newlines
, frag
->oldlines
);
1604 static const char pluses
[] =
1605 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1606 static const char minuses
[]=
1607 "----------------------------------------------------------------------";
1609 static void show_stats(struct patch
*patch
)
1611 struct strbuf qname
= STRBUF_INIT
;
1612 char *cp
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
1615 quote_c_style(cp
, &qname
, NULL
, 0);
1618 * "scale" the filename
1624 if (qname
.len
> max
) {
1625 cp
= strchr(qname
.buf
+ qname
.len
+ 3 - max
, '/');
1627 cp
= qname
.buf
+ qname
.len
+ 3 - max
;
1628 strbuf_splice(&qname
, 0, cp
- qname
.buf
, "...", 3);
1631 if (patch
->is_binary
) {
1632 printf(" %-*s | Bin\n", max
, qname
.buf
);
1633 strbuf_release(&qname
);
1637 printf(" %-*s |", max
, qname
.buf
);
1638 strbuf_release(&qname
);
1641 * scale the add/delete
1643 max
= max
+ max_change
> 70 ? 70 - max
: max_change
;
1644 add
= patch
->lines_added
;
1645 del
= patch
->lines_deleted
;
1647 if (max_change
> 0) {
1648 int total
= ((add
+ del
) * max
+ max_change
/ 2) / max_change
;
1649 add
= (add
* max
+ max_change
/ 2) / max_change
;
1652 printf("%5d %.*s%.*s\n", patch
->lines_added
+ patch
->lines_deleted
,
1653 add
, pluses
, del
, minuses
);
1656 static int read_old_data(struct stat
*st
, const char *path
, struct strbuf
*buf
)
1658 switch (st
->st_mode
& S_IFMT
) {
1660 if (strbuf_readlink(buf
, path
, st
->st_size
) < 0)
1661 return error("unable to read symlink %s", path
);
1664 if (strbuf_read_file(buf
, path
, st
->st_size
) != st
->st_size
)
1665 return error("unable to open or read %s", path
);
1666 convert_to_git(path
, buf
->buf
, buf
->len
, buf
, 0);
1674 * Update the preimage, and the common lines in postimage,
1675 * from buffer buf of length len. If postlen is 0 the postimage
1676 * is updated in place, otherwise it's updated on a new buffer
1680 static void update_pre_post_images(struct image
*preimage
,
1681 struct image
*postimage
,
1683 size_t len
, size_t postlen
)
1686 char *new, *old
, *fixed
;
1687 struct image fixed_preimage
;
1690 * Update the preimage with whitespace fixes. Note that we
1691 * are not losing preimage->buf -- apply_one_fragment() will
1694 prepare_image(&fixed_preimage
, buf
, len
, 1);
1695 assert(fixed_preimage
.nr
== preimage
->nr
);
1696 for (i
= 0; i
< preimage
->nr
; i
++)
1697 fixed_preimage
.line
[i
].flag
= preimage
->line
[i
].flag
;
1698 free(preimage
->line_allocated
);
1699 *preimage
= fixed_preimage
;
1702 * Adjust the common context lines in postimage. This can be
1703 * done in-place when we are just doing whitespace fixing,
1704 * which does not make the string grow, but needs a new buffer
1705 * when ignoring whitespace causes the update, since in this case
1706 * we could have e.g. tabs converted to multiple spaces.
1707 * We trust the caller to tell us if the update can be done
1708 * in place (postlen==0) or not.
1710 old
= postimage
->buf
;
1712 new = postimage
->buf
= xmalloc(postlen
);
1715 fixed
= preimage
->buf
;
1716 for (i
= ctx
= 0; i
< postimage
->nr
; i
++) {
1717 size_t len
= postimage
->line
[i
].len
;
1718 if (!(postimage
->line
[i
].flag
& LINE_COMMON
)) {
1719 /* an added line -- no counterparts in preimage */
1720 memmove(new, old
, len
);
1726 /* a common context -- skip it in the original postimage */
1729 /* and find the corresponding one in the fixed preimage */
1730 while (ctx
< preimage
->nr
&&
1731 !(preimage
->line
[ctx
].flag
& LINE_COMMON
)) {
1732 fixed
+= preimage
->line
[ctx
].len
;
1735 if (preimage
->nr
<= ctx
)
1738 /* and copy it in, while fixing the line length */
1739 len
= preimage
->line
[ctx
].len
;
1740 memcpy(new, fixed
, len
);
1743 postimage
->line
[i
].len
= len
;
1747 /* Fix the length of the whole thing */
1748 postimage
->len
= new - postimage
->buf
;
1751 static int match_fragment(struct image
*img
,
1752 struct image
*preimage
,
1753 struct image
*postimage
,
1757 int match_beginning
, int match_end
)
1760 char *fixed_buf
, *buf
, *orig
, *target
;
1762 if (preimage
->nr
+ try_lno
> img
->nr
)
1765 if (match_beginning
&& try_lno
)
1768 if (match_end
&& preimage
->nr
+ try_lno
!= img
->nr
)
1771 /* Quick hash check */
1772 for (i
= 0; i
< preimage
->nr
; i
++)
1773 if (preimage
->line
[i
].hash
!= img
->line
[try_lno
+ i
].hash
)
1777 * Do we have an exact match? If we were told to match
1778 * at the end, size must be exactly at try+fragsize,
1779 * otherwise try+fragsize must be still within the preimage,
1780 * and either case, the old piece should match the preimage
1784 ? (try + preimage
->len
== img
->len
)
1785 : (try + preimage
->len
<= img
->len
)) &&
1786 !memcmp(img
->buf
+ try, preimage
->buf
, preimage
->len
))
1790 * No exact match. If we are ignoring whitespace, run a line-by-line
1791 * fuzzy matching. We collect all the line length information because
1792 * we need it to adjust whitespace if we match.
1794 if (ws_ignore_action
== ignore_ws_change
) {
1797 size_t postlen
= postimage
->len
;
1798 size_t imglen
[preimage
->nr
];
1799 for (i
= 0; i
< preimage
->nr
; i
++) {
1800 size_t prelen
= preimage
->line
[i
].len
;
1802 imglen
[i
] = img
->line
[try_lno
+i
].len
;
1803 if (!fuzzy_matchlines(
1804 img
->buf
+ try + imgoff
, imglen
[i
],
1805 preimage
->buf
+ preoff
, prelen
))
1807 if (preimage
->line
[i
].flag
& LINE_COMMON
)
1808 postlen
+= imglen
[i
] - prelen
;
1809 imgoff
+= imglen
[i
];
1814 * Ok, the preimage matches with whitespace fuzz. Update it and
1815 * the common postimage lines to use the same whitespace as the
1816 * target. imgoff now holds the true length of the target that
1817 * matches the preimage, and we need to update the line lengths
1818 * of the preimage to match the target ones.
1820 fixed_buf
= xmalloc(imgoff
);
1821 memcpy(fixed_buf
, img
->buf
+ try, imgoff
);
1822 for (i
= 0; i
< preimage
->nr
; i
++)
1823 preimage
->line
[i
].len
= imglen
[i
];
1826 * Update the preimage buffer and the postimage context lines.
1828 update_pre_post_images(preimage
, postimage
,
1829 fixed_buf
, imgoff
, postlen
);
1833 if (ws_error_action
!= correct_ws_error
)
1837 * The hunk does not apply byte-by-byte, but the hash says
1838 * it might with whitespace fuzz. We haven't been asked to
1839 * ignore whitespace, we were asked to correct whitespace
1840 * errors, so let's try matching after whitespace correction.
1842 fixed_buf
= xmalloc(preimage
->len
+ 1);
1844 orig
= preimage
->buf
;
1845 target
= img
->buf
+ try;
1846 for (i
= 0; i
< preimage
->nr
; i
++) {
1847 size_t fixlen
; /* length after fixing the preimage */
1848 size_t oldlen
= preimage
->line
[i
].len
;
1849 size_t tgtlen
= img
->line
[try_lno
+ i
].len
;
1850 size_t tgtfixlen
; /* length after fixing the target line */
1851 char tgtfixbuf
[1024], *tgtfix
;
1854 /* Try fixing the line in the preimage */
1855 fixlen
= ws_fix_copy(buf
, orig
, oldlen
, ws_rule
, NULL
);
1857 /* Try fixing the line in the target */
1858 if (sizeof(tgtfixbuf
) > tgtlen
)
1861 tgtfix
= xmalloc(tgtlen
);
1862 tgtfixlen
= ws_fix_copy(tgtfix
, target
, tgtlen
, ws_rule
, NULL
);
1865 * If they match, either the preimage was based on
1866 * a version before our tree fixed whitespace breakage,
1867 * or we are lacking a whitespace-fix patch the tree
1868 * the preimage was based on already had (i.e. target
1869 * has whitespace breakage, the preimage doesn't).
1870 * In either case, we are fixing the whitespace breakages
1871 * so we might as well take the fix together with their
1874 match
= (tgtfixlen
== fixlen
&& !memcmp(tgtfix
, buf
, fixlen
));
1876 if (tgtfix
!= tgtfixbuf
)
1887 * Yes, the preimage is based on an older version that still
1888 * has whitespace breakages unfixed, and fixing them makes the
1889 * hunk match. Update the context lines in the postimage.
1891 update_pre_post_images(preimage
, postimage
,
1892 fixed_buf
, buf
- fixed_buf
, 0);
1900 static int find_pos(struct image
*img
,
1901 struct image
*preimage
,
1902 struct image
*postimage
,
1905 int match_beginning
, int match_end
)
1908 unsigned long backwards
, forwards
, try;
1909 int backwards_lno
, forwards_lno
, try_lno
;
1911 if (preimage
->nr
> img
->nr
)
1915 * If match_begining or match_end is specified, there is no
1916 * point starting from a wrong line that will never match and
1917 * wander around and wait for a match at the specified end.
1919 if (match_beginning
)
1922 line
= img
->nr
- preimage
->nr
;
1928 for (i
= 0; i
< line
; i
++)
1929 try += img
->line
[i
].len
;
1932 * There's probably some smart way to do this, but I'll leave
1933 * that to the smart and beautiful people. I'm simple and stupid.
1936 backwards_lno
= line
;
1938 forwards_lno
= line
;
1941 for (i
= 0; ; i
++) {
1942 if (match_fragment(img
, preimage
, postimage
,
1943 try, try_lno
, ws_rule
,
1944 match_beginning
, match_end
))
1948 if (backwards_lno
== 0 && forwards_lno
== img
->nr
)
1952 if (backwards_lno
== 0) {
1957 backwards
-= img
->line
[backwards_lno
].len
;
1959 try_lno
= backwards_lno
;
1961 if (forwards_lno
== img
->nr
) {
1965 forwards
+= img
->line
[forwards_lno
].len
;
1968 try_lno
= forwards_lno
;
1975 static void remove_first_line(struct image
*img
)
1977 img
->buf
+= img
->line
[0].len
;
1978 img
->len
-= img
->line
[0].len
;
1983 static void remove_last_line(struct image
*img
)
1985 img
->len
-= img
->line
[--img
->nr
].len
;
1988 static void update_image(struct image
*img
,
1990 struct image
*preimage
,
1991 struct image
*postimage
)
1994 * remove the copy of preimage at offset in img
1995 * and replace it with postimage
1998 size_t remove_count
, insert_count
, applied_at
= 0;
2001 for (i
= 0; i
< applied_pos
; i
++)
2002 applied_at
+= img
->line
[i
].len
;
2005 for (i
= 0; i
< preimage
->nr
; i
++)
2006 remove_count
+= img
->line
[applied_pos
+ i
].len
;
2007 insert_count
= postimage
->len
;
2009 /* Adjust the contents */
2010 result
= xmalloc(img
->len
+ insert_count
- remove_count
+ 1);
2011 memcpy(result
, img
->buf
, applied_at
);
2012 memcpy(result
+ applied_at
, postimage
->buf
, postimage
->len
);
2013 memcpy(result
+ applied_at
+ postimage
->len
,
2014 img
->buf
+ (applied_at
+ remove_count
),
2015 img
->len
- (applied_at
+ remove_count
));
2018 img
->len
+= insert_count
- remove_count
;
2019 result
[img
->len
] = '\0';
2021 /* Adjust the line table */
2022 nr
= img
->nr
+ postimage
->nr
- preimage
->nr
;
2023 if (preimage
->nr
< postimage
->nr
) {
2025 * NOTE: this knows that we never call remove_first_line()
2026 * on anything other than pre/post image.
2028 img
->line
= xrealloc(img
->line
, nr
* sizeof(*img
->line
));
2029 img
->line_allocated
= img
->line
;
2031 if (preimage
->nr
!= postimage
->nr
)
2032 memmove(img
->line
+ applied_pos
+ postimage
->nr
,
2033 img
->line
+ applied_pos
+ preimage
->nr
,
2034 (img
->nr
- (applied_pos
+ preimage
->nr
)) *
2035 sizeof(*img
->line
));
2036 memcpy(img
->line
+ applied_pos
,
2038 postimage
->nr
* sizeof(*img
->line
));
2042 static int apply_one_fragment(struct image
*img
, struct fragment
*frag
,
2043 int inaccurate_eof
, unsigned ws_rule
)
2045 int match_beginning
, match_end
;
2046 const char *patch
= frag
->patch
;
2047 int size
= frag
->size
;
2048 char *old
, *new, *oldlines
, *newlines
;
2049 int new_blank_lines_at_end
= 0;
2050 unsigned long leading
, trailing
;
2051 int pos
, applied_pos
;
2052 struct image preimage
;
2053 struct image postimage
;
2055 memset(&preimage
, 0, sizeof(preimage
));
2056 memset(&postimage
, 0, sizeof(postimage
));
2057 oldlines
= xmalloc(size
);
2058 newlines
= xmalloc(size
);
2064 int len
= linelen(patch
, size
);
2066 int added_blank_line
= 0;
2072 * "plen" is how much of the line we should use for
2073 * the actual patch data. Normally we just remove the
2074 * first character on the line, but if the line is
2075 * followed by "\ No newline", then we also remove the
2076 * last one (which is the newline, of course).
2079 if (len
< size
&& patch
[len
] == '\\')
2082 if (apply_in_reverse
) {
2085 else if (first
== '+')
2091 /* Newer GNU diff, empty context line */
2093 /* ... followed by '\No newline'; nothing */
2097 add_line_info(&preimage
, "\n", 1, LINE_COMMON
);
2098 add_line_info(&postimage
, "\n", 1, LINE_COMMON
);
2102 memcpy(old
, patch
+ 1, plen
);
2103 add_line_info(&preimage
, old
, plen
,
2104 (first
== ' ' ? LINE_COMMON
: 0));
2108 /* Fall-through for ' ' */
2110 /* --no-add does not add new lines */
2111 if (first
== '+' && no_add
)
2115 !whitespace_error
||
2116 ws_error_action
!= correct_ws_error
) {
2117 memcpy(new, patch
+ 1, plen
);
2121 added
= ws_fix_copy(new, patch
+ 1, plen
, ws_rule
, &applied_after_fixing_ws
);
2123 add_line_info(&postimage
, new, added
,
2124 (first
== '+' ? 0 : LINE_COMMON
));
2127 added
== 1 && new[-1] == '\n')
2128 added_blank_line
= 1;
2130 case '@': case '\\':
2131 /* Ignore it, we already handled it */
2134 if (apply_verbosely
)
2135 error("invalid start of line: '%c'", first
);
2138 if (added_blank_line
)
2139 new_blank_lines_at_end
++;
2141 new_blank_lines_at_end
= 0;
2145 if (inaccurate_eof
&&
2146 old
> oldlines
&& old
[-1] == '\n' &&
2147 new > newlines
&& new[-1] == '\n') {
2152 leading
= frag
->leading
;
2153 trailing
= frag
->trailing
;
2156 * A hunk to change lines at the beginning would begin with
2158 * but we need to be careful. -U0 that inserts before the second
2159 * line also has this pattern.
2161 * And a hunk to add to an empty file would begin with
2164 * In other words, a hunk that is (frag->oldpos <= 1) with or
2165 * without leading context must match at the beginning.
2167 match_beginning
= (!frag
->oldpos
||
2168 (frag
->oldpos
== 1 && !unidiff_zero
));
2171 * A hunk without trailing lines must match at the end.
2172 * However, we simply cannot tell if a hunk must match end
2173 * from the lack of trailing lines if the patch was generated
2174 * with unidiff without any context.
2176 match_end
= !unidiff_zero
&& !trailing
;
2178 pos
= frag
->newpos
? (frag
->newpos
- 1) : 0;
2179 preimage
.buf
= oldlines
;
2180 preimage
.len
= old
- oldlines
;
2181 postimage
.buf
= newlines
;
2182 postimage
.len
= new - newlines
;
2183 preimage
.line
= preimage
.line_allocated
;
2184 postimage
.line
= postimage
.line_allocated
;
2188 applied_pos
= find_pos(img
, &preimage
, &postimage
, pos
,
2189 ws_rule
, match_beginning
, match_end
);
2191 if (applied_pos
>= 0)
2194 /* Am I at my context limits? */
2195 if ((leading
<= p_context
) && (trailing
<= p_context
))
2197 if (match_beginning
|| match_end
) {
2198 match_beginning
= match_end
= 0;
2203 * Reduce the number of context lines; reduce both
2204 * leading and trailing if they are equal otherwise
2205 * just reduce the larger context.
2207 if (leading
>= trailing
) {
2208 remove_first_line(&preimage
);
2209 remove_first_line(&postimage
);
2213 if (trailing
> leading
) {
2214 remove_last_line(&preimage
);
2215 remove_last_line(&postimage
);
2220 if (applied_pos
>= 0) {
2221 if (ws_error_action
== correct_ws_error
&&
2222 new_blank_lines_at_end
&&
2223 postimage
.nr
+ applied_pos
== img
->nr
) {
2225 * If the patch application adds blank lines
2226 * at the end, and if the patch applies at the
2227 * end of the image, remove those added blank
2230 while (new_blank_lines_at_end
--)
2231 remove_last_line(&postimage
);
2235 * Warn if it was necessary to reduce the number
2238 if ((leading
!= frag
->leading
) ||
2239 (trailing
!= frag
->trailing
))
2240 fprintf(stderr
, "Context reduced to (%ld/%ld)"
2241 " to apply fragment at %d\n",
2242 leading
, trailing
, applied_pos
+1);
2243 update_image(img
, applied_pos
, &preimage
, &postimage
);
2245 if (apply_verbosely
)
2246 error("while searching for:\n%.*s",
2247 (int)(old
- oldlines
), oldlines
);
2252 free(preimage
.line_allocated
);
2253 free(postimage
.line_allocated
);
2255 return (applied_pos
< 0);
2258 static int apply_binary_fragment(struct image
*img
, struct patch
*patch
)
2260 struct fragment
*fragment
= patch
->fragments
;
2264 /* Binary patch is irreversible without the optional second hunk */
2265 if (apply_in_reverse
) {
2266 if (!fragment
->next
)
2267 return error("cannot reverse-apply a binary patch "
2268 "without the reverse hunk to '%s'",
2270 ? patch
->new_name
: patch
->old_name
);
2271 fragment
= fragment
->next
;
2273 switch (fragment
->binary_patch_method
) {
2274 case BINARY_DELTA_DEFLATED
:
2275 dst
= patch_delta(img
->buf
, img
->len
, fragment
->patch
,
2276 fragment
->size
, &len
);
2283 case BINARY_LITERAL_DEFLATED
:
2285 img
->len
= fragment
->size
;
2286 img
->buf
= xmalloc(img
->len
+1);
2287 memcpy(img
->buf
, fragment
->patch
, img
->len
);
2288 img
->buf
[img
->len
] = '\0';
2294 static int apply_binary(struct image
*img
, struct patch
*patch
)
2296 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
2297 unsigned char sha1
[20];
2300 * For safety, we require patch index line to contain
2301 * full 40-byte textual SHA1 for old and new, at least for now.
2303 if (strlen(patch
->old_sha1_prefix
) != 40 ||
2304 strlen(patch
->new_sha1_prefix
) != 40 ||
2305 get_sha1_hex(patch
->old_sha1_prefix
, sha1
) ||
2306 get_sha1_hex(patch
->new_sha1_prefix
, sha1
))
2307 return error("cannot apply binary patch to '%s' "
2308 "without full index line", name
);
2310 if (patch
->old_name
) {
2312 * See if the old one matches what the patch
2315 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
2316 if (strcmp(sha1_to_hex(sha1
), patch
->old_sha1_prefix
))
2317 return error("the patch applies to '%s' (%s), "
2318 "which does not match the "
2319 "current contents.",
2320 name
, sha1_to_hex(sha1
));
2323 /* Otherwise, the old one must be empty. */
2325 return error("the patch applies to an empty "
2326 "'%s' but it is not empty", name
);
2329 get_sha1_hex(patch
->new_sha1_prefix
, sha1
);
2330 if (is_null_sha1(sha1
)) {
2332 return 0; /* deletion patch */
2335 if (has_sha1_file(sha1
)) {
2336 /* We already have the postimage */
2337 enum object_type type
;
2341 result
= read_sha1_file(sha1
, &type
, &size
);
2343 return error("the necessary postimage %s for "
2344 "'%s' cannot be read",
2345 patch
->new_sha1_prefix
, name
);
2351 * We have verified buf matches the preimage;
2352 * apply the patch data to it, which is stored
2353 * in the patch->fragments->{patch,size}.
2355 if (apply_binary_fragment(img
, patch
))
2356 return error("binary patch does not apply to '%s'",
2359 /* verify that the result matches */
2360 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
2361 if (strcmp(sha1_to_hex(sha1
), patch
->new_sha1_prefix
))
2362 return error("binary patch to '%s' creates incorrect result (expecting %s, got %s)",
2363 name
, patch
->new_sha1_prefix
, sha1_to_hex(sha1
));
2369 static int apply_fragments(struct image
*img
, struct patch
*patch
)
2371 struct fragment
*frag
= patch
->fragments
;
2372 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
2373 unsigned ws_rule
= patch
->ws_rule
;
2374 unsigned inaccurate_eof
= patch
->inaccurate_eof
;
2376 if (patch
->is_binary
)
2377 return apply_binary(img
, patch
);
2380 if (apply_one_fragment(img
, frag
, inaccurate_eof
, ws_rule
)) {
2381 error("patch failed: %s:%ld", name
, frag
->oldpos
);
2382 if (!apply_with_reject
)
2391 static int read_file_or_gitlink(struct cache_entry
*ce
, struct strbuf
*buf
)
2396 if (S_ISGITLINK(ce
->ce_mode
)) {
2397 strbuf_grow(buf
, 100);
2398 strbuf_addf(buf
, "Subproject commit %s\n", sha1_to_hex(ce
->sha1
));
2400 enum object_type type
;
2404 result
= read_sha1_file(ce
->sha1
, &type
, &sz
);
2407 /* XXX read_sha1_file NUL-terminates */
2408 strbuf_attach(buf
, result
, sz
, sz
+ 1);
2413 static struct patch
*in_fn_table(const char *name
)
2415 struct string_list_item
*item
;
2420 item
= string_list_lookup(name
, &fn_table
);
2422 return (struct patch
*)item
->util
;
2428 * item->util in the filename table records the status of the path.
2429 * Usually it points at a patch (whose result records the contents
2430 * of it after applying it), but it could be PATH_WAS_DELETED for a
2431 * path that a previously applied patch has already removed.
2433 #define PATH_TO_BE_DELETED ((struct patch *) -2)
2434 #define PATH_WAS_DELETED ((struct patch *) -1)
2436 static int to_be_deleted(struct patch
*patch
)
2438 return patch
== PATH_TO_BE_DELETED
;
2441 static int was_deleted(struct patch
*patch
)
2443 return patch
== PATH_WAS_DELETED
;
2446 static void add_to_fn_table(struct patch
*patch
)
2448 struct string_list_item
*item
;
2451 * Always add new_name unless patch is a deletion
2452 * This should cover the cases for normal diffs,
2453 * file creations and copies
2455 if (patch
->new_name
!= NULL
) {
2456 item
= string_list_insert(patch
->new_name
, &fn_table
);
2461 * store a failure on rename/deletion cases because
2462 * later chunks shouldn't patch old names
2464 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
2465 item
= string_list_insert(patch
->old_name
, &fn_table
);
2466 item
->util
= PATH_WAS_DELETED
;
2470 static void prepare_fn_table(struct patch
*patch
)
2473 * store information about incoming file deletion
2476 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
2477 struct string_list_item
*item
;
2478 item
= string_list_insert(patch
->old_name
, &fn_table
);
2479 item
->util
= PATH_TO_BE_DELETED
;
2481 patch
= patch
->next
;
2485 static int apply_data(struct patch
*patch
, struct stat
*st
, struct cache_entry
*ce
)
2487 struct strbuf buf
= STRBUF_INIT
;
2491 struct patch
*tpatch
;
2493 if (!(patch
->is_copy
|| patch
->is_rename
) &&
2494 (tpatch
= in_fn_table(patch
->old_name
)) != NULL
&& !to_be_deleted(tpatch
)) {
2495 if (was_deleted(tpatch
)) {
2496 return error("patch %s has been renamed/deleted",
2499 /* We have a patched copy in memory use that */
2500 strbuf_add(&buf
, tpatch
->result
, tpatch
->resultsize
);
2501 } else if (cached
) {
2502 if (read_file_or_gitlink(ce
, &buf
))
2503 return error("read of %s failed", patch
->old_name
);
2504 } else if (patch
->old_name
) {
2505 if (S_ISGITLINK(patch
->old_mode
)) {
2507 read_file_or_gitlink(ce
, &buf
);
2510 * There is no way to apply subproject
2511 * patch without looking at the index.
2513 patch
->fragments
= NULL
;
2516 if (read_old_data(st
, patch
->old_name
, &buf
))
2517 return error("read of %s failed", patch
->old_name
);
2521 img
= strbuf_detach(&buf
, &len
);
2522 prepare_image(&image
, img
, len
, !patch
->is_binary
);
2524 if (apply_fragments(&image
, patch
) < 0)
2525 return -1; /* note with --reject this succeeds. */
2526 patch
->result
= image
.buf
;
2527 patch
->resultsize
= image
.len
;
2528 add_to_fn_table(patch
);
2529 free(image
.line_allocated
);
2531 if (0 < patch
->is_delete
&& patch
->resultsize
)
2532 return error("removal patch leaves file contents");
2537 static int check_to_create_blob(const char *new_name
, int ok_if_exists
)
2540 if (!lstat(new_name
, &nst
)) {
2541 if (S_ISDIR(nst
.st_mode
) || ok_if_exists
)
2544 * A leading component of new_name might be a symlink
2545 * that is going to be removed with this patch, but
2546 * still pointing at somewhere that has the path.
2547 * In such a case, path "new_name" does not exist as
2548 * far as git is concerned.
2550 if (has_symlink_leading_path(new_name
, strlen(new_name
)))
2553 return error("%s: already exists in working directory", new_name
);
2555 else if ((errno
!= ENOENT
) && (errno
!= ENOTDIR
))
2556 return error("%s: %s", new_name
, strerror(errno
));
2560 static int verify_index_match(struct cache_entry
*ce
, struct stat
*st
)
2562 if (S_ISGITLINK(ce
->ce_mode
)) {
2563 if (!S_ISDIR(st
->st_mode
))
2567 return ce_match_stat(ce
, st
, CE_MATCH_IGNORE_VALID
);
2570 static int check_preimage(struct patch
*patch
, struct cache_entry
**ce
, struct stat
*st
)
2572 const char *old_name
= patch
->old_name
;
2573 struct patch
*tpatch
= NULL
;
2575 unsigned st_mode
= 0;
2578 * Make sure that we do not have local modifications from the
2579 * index when we are looking at the index. Also make sure
2580 * we have the preimage file to be patched in the work tree,
2581 * unless --cached, which tells git to apply only in the index.
2586 assert(patch
->is_new
<= 0);
2588 if (!(patch
->is_copy
|| patch
->is_rename
) &&
2589 (tpatch
= in_fn_table(old_name
)) != NULL
&& !to_be_deleted(tpatch
)) {
2590 if (was_deleted(tpatch
))
2591 return error("%s: has been deleted/renamed", old_name
);
2592 st_mode
= tpatch
->new_mode
;
2593 } else if (!cached
) {
2594 stat_ret
= lstat(old_name
, st
);
2595 if (stat_ret
&& errno
!= ENOENT
)
2596 return error("%s: %s", old_name
, strerror(errno
));
2599 if (to_be_deleted(tpatch
))
2602 if (check_index
&& !tpatch
) {
2603 int pos
= cache_name_pos(old_name
, strlen(old_name
));
2605 if (patch
->is_new
< 0)
2607 return error("%s: does not exist in index", old_name
);
2609 *ce
= active_cache
[pos
];
2611 struct checkout costate
;
2613 costate
.base_dir
= "";
2614 costate
.base_dir_len
= 0;
2617 costate
.not_new
= 0;
2618 costate
.refresh_cache
= 1;
2619 if (checkout_entry(*ce
, &costate
, NULL
) ||
2620 lstat(old_name
, st
))
2623 if (!cached
&& verify_index_match(*ce
, st
))
2624 return error("%s: does not match index", old_name
);
2626 st_mode
= (*ce
)->ce_mode
;
2627 } else if (stat_ret
< 0) {
2628 if (patch
->is_new
< 0)
2630 return error("%s: %s", old_name
, strerror(errno
));
2633 if (!cached
&& !tpatch
)
2634 st_mode
= ce_mode_from_stat(*ce
, st
->st_mode
);
2636 if (patch
->is_new
< 0)
2638 if (!patch
->old_mode
)
2639 patch
->old_mode
= st_mode
;
2640 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
2641 return error("%s: wrong type", old_name
);
2642 if (st_mode
!= patch
->old_mode
)
2643 warning("%s has type %o, expected %o",
2644 old_name
, st_mode
, patch
->old_mode
);
2645 if (!patch
->new_mode
&& !patch
->is_delete
)
2646 patch
->new_mode
= st_mode
;
2651 patch
->is_delete
= 0;
2652 patch
->old_name
= NULL
;
2656 static int check_patch(struct patch
*patch
)
2659 const char *old_name
= patch
->old_name
;
2660 const char *new_name
= patch
->new_name
;
2661 const char *name
= old_name
? old_name
: new_name
;
2662 struct cache_entry
*ce
= NULL
;
2663 struct patch
*tpatch
;
2667 patch
->rejected
= 1; /* we will drop this after we succeed */
2669 status
= check_preimage(patch
, &ce
, &st
);
2672 old_name
= patch
->old_name
;
2674 if ((tpatch
= in_fn_table(new_name
)) &&
2675 (was_deleted(tpatch
) || to_be_deleted(tpatch
)))
2677 * A type-change diff is always split into a patch to
2678 * delete old, immediately followed by a patch to
2679 * create new (see diff.c::run_diff()); in such a case
2680 * it is Ok that the entry to be deleted by the
2681 * previous patch is still in the working tree and in
2689 ((0 < patch
->is_new
) | (0 < patch
->is_rename
) | patch
->is_copy
)) {
2691 cache_name_pos(new_name
, strlen(new_name
)) >= 0 &&
2693 return error("%s: already exists in index", new_name
);
2695 int err
= check_to_create_blob(new_name
, ok_if_exists
);
2699 if (!patch
->new_mode
) {
2700 if (0 < patch
->is_new
)
2701 patch
->new_mode
= S_IFREG
| 0644;
2703 patch
->new_mode
= patch
->old_mode
;
2707 if (new_name
&& old_name
) {
2708 int same
= !strcmp(old_name
, new_name
);
2709 if (!patch
->new_mode
)
2710 patch
->new_mode
= patch
->old_mode
;
2711 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
)
2712 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
2713 patch
->new_mode
, new_name
, patch
->old_mode
,
2714 same
? "" : " of ", same
? "" : old_name
);
2717 if (apply_data(patch
, &st
, ce
) < 0)
2718 return error("%s: patch does not apply", name
);
2719 patch
->rejected
= 0;
2723 static int check_patch_list(struct patch
*patch
)
2727 prepare_fn_table(patch
);
2729 if (apply_verbosely
)
2730 say_patch_name(stderr
,
2731 "Checking patch ", patch
, "...\n");
2732 err
|= check_patch(patch
);
2733 patch
= patch
->next
;
2738 /* This function tries to read the sha1 from the current index */
2739 static int get_current_sha1(const char *path
, unsigned char *sha1
)
2743 if (read_cache() < 0)
2745 pos
= cache_name_pos(path
, strlen(path
));
2748 hashcpy(sha1
, active_cache
[pos
]->sha1
);
2752 /* Build an index that contains the just the files needed for a 3way merge */
2753 static void build_fake_ancestor(struct patch
*list
, const char *filename
)
2755 struct patch
*patch
;
2756 struct index_state result
= { NULL
};
2759 /* Once we start supporting the reverse patch, it may be
2760 * worth showing the new sha1 prefix, but until then...
2762 for (patch
= list
; patch
; patch
= patch
->next
) {
2763 const unsigned char *sha1_ptr
;
2764 unsigned char sha1
[20];
2765 struct cache_entry
*ce
;
2768 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
2769 if (0 < patch
->is_new
)
2771 else if (get_sha1(patch
->old_sha1_prefix
, sha1
))
2772 /* git diff has no index line for mode/type changes */
2773 if (!patch
->lines_added
&& !patch
->lines_deleted
) {
2774 if (get_current_sha1(patch
->new_name
, sha1
) ||
2775 get_current_sha1(patch
->old_name
, sha1
))
2776 die("mode change for %s, which is not "
2777 "in current HEAD", name
);
2780 die("sha1 information is lacking or useless "
2785 ce
= make_cache_entry(patch
->old_mode
, sha1_ptr
, name
, 0, 0);
2787 die("make_cache_entry failed for path '%s'", name
);
2788 if (add_index_entry(&result
, ce
, ADD_CACHE_OK_TO_ADD
))
2789 die ("Could not add %s to temporary index", name
);
2792 fd
= open(filename
, O_WRONLY
| O_CREAT
, 0666);
2793 if (fd
< 0 || write_index(&result
, fd
) || close(fd
))
2794 die ("Could not write temporary index to %s", filename
);
2796 discard_index(&result
);
2799 static void stat_patch_list(struct patch
*patch
)
2801 int files
, adds
, dels
;
2803 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
2805 adds
+= patch
->lines_added
;
2806 dels
+= patch
->lines_deleted
;
2810 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files
, adds
, dels
);
2813 static void numstat_patch_list(struct patch
*patch
)
2815 for ( ; patch
; patch
= patch
->next
) {
2817 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
2818 if (patch
->is_binary
)
2821 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
2822 write_name_quoted(name
, stdout
, line_termination
);
2826 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
2829 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
2831 printf(" %s %s\n", newdelete
, name
);
2834 static void show_mode_change(struct patch
*p
, int show_name
)
2836 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
2838 printf(" mode change %06o => %06o %s\n",
2839 p
->old_mode
, p
->new_mode
, p
->new_name
);
2841 printf(" mode change %06o => %06o\n",
2842 p
->old_mode
, p
->new_mode
);
2846 static void show_rename_copy(struct patch
*p
)
2848 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
2849 const char *old
, *new;
2851 /* Find common prefix */
2855 const char *slash_old
, *slash_new
;
2856 slash_old
= strchr(old
, '/');
2857 slash_new
= strchr(new, '/');
2860 slash_old
- old
!= slash_new
- new ||
2861 memcmp(old
, new, slash_new
- new))
2863 old
= slash_old
+ 1;
2864 new = slash_new
+ 1;
2866 /* p->old_name thru old is the common prefix, and old and new
2867 * through the end of names are renames
2869 if (old
!= p
->old_name
)
2870 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
2871 (int)(old
- p
->old_name
), p
->old_name
,
2872 old
, new, p
->score
);
2874 printf(" %s %s => %s (%d%%)\n", renamecopy
,
2875 p
->old_name
, p
->new_name
, p
->score
);
2876 show_mode_change(p
, 0);
2879 static void summary_patch_list(struct patch
*patch
)
2883 for (p
= patch
; p
; p
= p
->next
) {
2885 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
2886 else if (p
->is_delete
)
2887 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
2889 if (p
->is_rename
|| p
->is_copy
)
2890 show_rename_copy(p
);
2893 printf(" rewrite %s (%d%%)\n",
2894 p
->new_name
, p
->score
);
2895 show_mode_change(p
, 0);
2898 show_mode_change(p
, 1);
2904 static void patch_stats(struct patch
*patch
)
2906 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
2908 if (lines
> max_change
)
2910 if (patch
->old_name
) {
2911 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
2913 len
= strlen(patch
->old_name
);
2917 if (patch
->new_name
) {
2918 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
2920 len
= strlen(patch
->new_name
);
2926 static void remove_file(struct patch
*patch
, int rmdir_empty
)
2929 if (remove_file_from_cache(patch
->old_name
) < 0)
2930 die("unable to remove %s from index", patch
->old_name
);
2933 if (S_ISGITLINK(patch
->old_mode
)) {
2934 if (rmdir(patch
->old_name
))
2935 warning("unable to remove submodule %s",
2937 } else if (!unlink_or_warn(patch
->old_name
) && rmdir_empty
) {
2938 remove_path(patch
->old_name
);
2943 static void add_index_file(const char *path
, unsigned mode
, void *buf
, unsigned long size
)
2946 struct cache_entry
*ce
;
2947 int namelen
= strlen(path
);
2948 unsigned ce_size
= cache_entry_size(namelen
);
2953 ce
= xcalloc(1, ce_size
);
2954 memcpy(ce
->name
, path
, namelen
);
2955 ce
->ce_mode
= create_ce_mode(mode
);
2956 ce
->ce_flags
= namelen
;
2957 if (S_ISGITLINK(mode
)) {
2958 const char *s
= buf
;
2960 if (get_sha1_hex(s
+ strlen("Subproject commit "), ce
->sha1
))
2961 die("corrupt patch for subproject %s", path
);
2964 if (lstat(path
, &st
) < 0)
2965 die_errno("unable to stat newly created file '%s'",
2967 fill_stat_cache_info(ce
, &st
);
2969 if (write_sha1_file(buf
, size
, blob_type
, ce
->sha1
) < 0)
2970 die("unable to create backing store for newly created file %s", path
);
2972 if (add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
) < 0)
2973 die("unable to add cache entry for %s", path
);
2976 static int try_create_file(const char *path
, unsigned int mode
, const char *buf
, unsigned long size
)
2979 struct strbuf nbuf
= STRBUF_INIT
;
2981 if (S_ISGITLINK(mode
)) {
2983 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
))
2985 return mkdir(path
, 0777);
2988 if (has_symlinks
&& S_ISLNK(mode
))
2989 /* Although buf:size is counted string, it also is NUL
2992 return symlink(buf
, path
);
2994 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
2998 if (convert_to_working_tree(path
, buf
, size
, &nbuf
)) {
3002 write_or_die(fd
, buf
, size
);
3003 strbuf_release(&nbuf
);
3006 die_errno("closing file '%s'", path
);
3011 * We optimistically assume that the directories exist,
3012 * which is true 99% of the time anyway. If they don't,
3013 * we create them and try again.
3015 static void create_one_file(char *path
, unsigned mode
, const char *buf
, unsigned long size
)
3019 if (!try_create_file(path
, mode
, buf
, size
))
3022 if (errno
== ENOENT
) {
3023 if (safe_create_leading_directories(path
))
3025 if (!try_create_file(path
, mode
, buf
, size
))
3029 if (errno
== EEXIST
|| errno
== EACCES
) {
3030 /* We may be trying to create a file where a directory
3034 if (!lstat(path
, &st
) && (!S_ISDIR(st
.st_mode
) || !rmdir(path
)))
3038 if (errno
== EEXIST
) {
3039 unsigned int nr
= getpid();
3042 char newpath
[PATH_MAX
];
3043 mksnpath(newpath
, sizeof(newpath
), "%s~%u", path
, nr
);
3044 if (!try_create_file(newpath
, mode
, buf
, size
)) {
3045 if (!rename(newpath
, path
))
3047 unlink_or_warn(newpath
);
3050 if (errno
!= EEXIST
)
3055 die_errno("unable to write file '%s' mode %o", path
, mode
);
3058 static void create_file(struct patch
*patch
)
3060 char *path
= patch
->new_name
;
3061 unsigned mode
= patch
->new_mode
;
3062 unsigned long size
= patch
->resultsize
;
3063 char *buf
= patch
->result
;
3066 mode
= S_IFREG
| 0644;
3067 create_one_file(path
, mode
, buf
, size
);
3068 add_index_file(path
, mode
, buf
, size
);
3071 /* phase zero is to remove, phase one is to create */
3072 static void write_out_one_result(struct patch
*patch
, int phase
)
3074 if (patch
->is_delete
> 0) {
3076 remove_file(patch
, 1);
3079 if (patch
->is_new
> 0 || patch
->is_copy
) {
3085 * Rename or modification boils down to the same
3086 * thing: remove the old, write the new
3089 remove_file(patch
, patch
->is_rename
);
3094 static int write_out_one_reject(struct patch
*patch
)
3097 char namebuf
[PATH_MAX
];
3098 struct fragment
*frag
;
3101 for (cnt
= 0, frag
= patch
->fragments
; frag
; frag
= frag
->next
) {
3102 if (!frag
->rejected
)
3108 if (apply_verbosely
)
3109 say_patch_name(stderr
,
3110 "Applied patch ", patch
, " cleanly.\n");
3114 /* This should not happen, because a removal patch that leaves
3115 * contents are marked "rejected" at the patch level.
3117 if (!patch
->new_name
)
3118 die("internal error");
3120 /* Say this even without --verbose */
3121 say_patch_name(stderr
, "Applying patch ", patch
, " with");
3122 fprintf(stderr
, " %d rejects...\n", cnt
);
3124 cnt
= strlen(patch
->new_name
);
3125 if (ARRAY_SIZE(namebuf
) <= cnt
+ 5) {
3126 cnt
= ARRAY_SIZE(namebuf
) - 5;
3127 warning("truncating .rej filename to %.*s.rej",
3128 cnt
- 1, patch
->new_name
);
3130 memcpy(namebuf
, patch
->new_name
, cnt
);
3131 memcpy(namebuf
+ cnt
, ".rej", 5);
3133 rej
= fopen(namebuf
, "w");
3135 return error("cannot open %s: %s", namebuf
, strerror(errno
));
3137 /* Normal git tools never deal with .rej, so do not pretend
3138 * this is a git patch by saying --git nor give extended
3139 * headers. While at it, maybe please "kompare" that wants
3140 * the trailing TAB and some garbage at the end of line ;-).
3142 fprintf(rej
, "diff a/%s b/%s\t(rejected hunks)\n",
3143 patch
->new_name
, patch
->new_name
);
3144 for (cnt
= 1, frag
= patch
->fragments
;
3146 cnt
++, frag
= frag
->next
) {
3147 if (!frag
->rejected
) {
3148 fprintf(stderr
, "Hunk #%d applied cleanly.\n", cnt
);
3151 fprintf(stderr
, "Rejected hunk #%d.\n", cnt
);
3152 fprintf(rej
, "%.*s", frag
->size
, frag
->patch
);
3153 if (frag
->patch
[frag
->size
-1] != '\n')
3160 static int write_out_results(struct patch
*list
, int skipped_patch
)
3166 if (!list
&& !skipped_patch
)
3167 return error("No changes");
3169 for (phase
= 0; phase
< 2; phase
++) {
3175 write_out_one_result(l
, phase
);
3176 if (phase
== 1 && write_out_one_reject(l
))
3185 static struct lock_file lock_file
;
3187 static struct string_list limit_by_name
;
3188 static int has_include
;
3189 static void add_name_limit(const char *name
, int exclude
)
3191 struct string_list_item
*it
;
3193 it
= string_list_append(name
, &limit_by_name
);
3194 it
->util
= exclude
? NULL
: (void *) 1;
3197 static int use_patch(struct patch
*p
)
3199 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
3202 /* Paths outside are not touched regardless of "--include" */
3203 if (0 < prefix_length
) {
3204 int pathlen
= strlen(pathname
);
3205 if (pathlen
<= prefix_length
||
3206 memcmp(prefix
, pathname
, prefix_length
))
3210 /* See if it matches any of exclude/include rule */
3211 for (i
= 0; i
< limit_by_name
.nr
; i
++) {
3212 struct string_list_item
*it
= &limit_by_name
.items
[i
];
3213 if (!fnmatch(it
->string
, pathname
, 0))
3214 return (it
->util
!= NULL
);
3218 * If we had any include, a path that does not match any rule is
3219 * not used. Otherwise, we saw bunch of exclude rules (or none)
3220 * and such a path is used.
3222 return !has_include
;
3226 static void prefix_one(char **name
)
3228 char *old_name
= *name
;
3231 *name
= xstrdup(prefix_filename(prefix
, prefix_length
, *name
));
3235 static void prefix_patches(struct patch
*p
)
3237 if (!prefix
|| p
->is_toplevel_relative
)
3239 for ( ; p
; p
= p
->next
) {
3240 if (p
->new_name
== p
->old_name
) {
3241 char *prefixed
= p
->new_name
;
3242 prefix_one(&prefixed
);
3243 p
->new_name
= p
->old_name
= prefixed
;
3246 prefix_one(&p
->new_name
);
3247 prefix_one(&p
->old_name
);
3252 #define INACCURATE_EOF (1<<0)
3253 #define RECOUNT (1<<1)
3255 static int apply_patch(int fd
, const char *filename
, int options
)
3258 struct strbuf buf
= STRBUF_INIT
;
3259 struct patch
*list
= NULL
, **listp
= &list
;
3260 int skipped_patch
= 0;
3262 /* FIXME - memory leak when using multiple patch files as inputs */
3263 memset(&fn_table
, 0, sizeof(struct string_list
));
3264 patch_input_file
= filename
;
3265 read_patch_file(&buf
, fd
);
3267 while (offset
< buf
.len
) {
3268 struct patch
*patch
;
3271 patch
= xcalloc(1, sizeof(*patch
));
3272 patch
->inaccurate_eof
= !!(options
& INACCURATE_EOF
);
3273 patch
->recount
= !!(options
& RECOUNT
);
3274 nr
= parse_chunk(buf
.buf
+ offset
, buf
.len
- offset
, patch
);
3277 if (apply_in_reverse
)
3278 reverse_patches(patch
);
3280 prefix_patches(patch
);
3281 if (use_patch(patch
)) {
3284 listp
= &patch
->next
;
3287 /* perhaps free it a bit better? */
3294 if (whitespace_error
&& (ws_error_action
== die_on_ws_error
))
3297 update_index
= check_index
&& apply
;
3298 if (update_index
&& newfd
< 0)
3299 newfd
= hold_locked_index(&lock_file
, 1);
3302 if (read_cache() < 0)
3303 die("unable to read index file");
3306 if ((check
|| apply
) &&
3307 check_patch_list(list
) < 0 &&
3311 if (apply
&& write_out_results(list
, skipped_patch
))
3315 build_fake_ancestor(list
, fake_ancestor
);
3318 stat_patch_list(list
);
3321 numstat_patch_list(list
);
3324 summary_patch_list(list
);
3326 strbuf_release(&buf
);
3330 static int git_apply_config(const char *var
, const char *value
, void *cb
)
3332 if (!strcmp(var
, "apply.whitespace"))
3333 return git_config_string(&apply_default_whitespace
, var
, value
);
3334 else if (!strcmp(var
, "apply.ignorewhitespace"))
3335 return git_config_string(&apply_default_ignorewhitespace
, var
, value
);
3336 return git_default_config(var
, value
, cb
);
3339 static int option_parse_exclude(const struct option
*opt
,
3340 const char *arg
, int unset
)
3342 add_name_limit(arg
, 1);
3346 static int option_parse_include(const struct option
*opt
,
3347 const char *arg
, int unset
)
3349 add_name_limit(arg
, 0);
3354 static int option_parse_p(const struct option
*opt
,
3355 const char *arg
, int unset
)
3357 p_value
= atoi(arg
);
3362 static int option_parse_z(const struct option
*opt
,
3363 const char *arg
, int unset
)
3366 line_termination
= '\n';
3368 line_termination
= 0;
3372 static int option_parse_space_change(const struct option
*opt
,
3373 const char *arg
, int unset
)
3376 ws_ignore_action
= ignore_ws_none
;
3378 ws_ignore_action
= ignore_ws_change
;
3382 static int option_parse_whitespace(const struct option
*opt
,
3383 const char *arg
, int unset
)
3385 const char **whitespace_option
= opt
->value
;
3387 *whitespace_option
= arg
;
3388 parse_whitespace_option(arg
);
3392 static int option_parse_directory(const struct option
*opt
,
3393 const char *arg
, int unset
)
3395 root_len
= strlen(arg
);
3396 if (root_len
&& arg
[root_len
- 1] != '/') {
3398 root
= new_root
= xmalloc(root_len
+ 2);
3399 strcpy(new_root
, arg
);
3400 strcpy(new_root
+ root_len
++, "/");
3406 int cmd_apply(int argc
, const char **argv
, const char *unused_prefix
)
3412 int force_apply
= 0;
3414 const char *whitespace_option
= NULL
;
3416 struct option builtin_apply_options
[] = {
3417 { OPTION_CALLBACK
, 0, "exclude", NULL
, "path",
3418 "don't apply changes matching the given path",
3419 0, option_parse_exclude
},
3420 { OPTION_CALLBACK
, 0, "include", NULL
, "path",
3421 "apply changes matching the given path",
3422 0, option_parse_include
},
3423 { OPTION_CALLBACK
, 'p', NULL
, NULL
, "num",
3424 "remove <num> leading slashes from traditional diff paths",
3425 0, option_parse_p
},
3426 OPT_BOOLEAN(0, "no-add", &no_add
,
3427 "ignore additions made by the patch"),
3428 OPT_BOOLEAN(0, "stat", &diffstat
,
3429 "instead of applying the patch, output diffstat for the input"),
3430 { OPTION_BOOLEAN
, 0, "allow-binary-replacement", &binary
,
3431 NULL
, "old option, now no-op",
3432 PARSE_OPT_HIDDEN
| PARSE_OPT_NOARG
},
3433 { OPTION_BOOLEAN
, 0, "binary", &binary
,
3434 NULL
, "old option, now no-op",
3435 PARSE_OPT_HIDDEN
| PARSE_OPT_NOARG
},
3436 OPT_BOOLEAN(0, "numstat", &numstat
,
3437 "shows number of added and deleted lines in decimal notation"),
3438 OPT_BOOLEAN(0, "summary", &summary
,
3439 "instead of applying the patch, output a summary for the input"),
3440 OPT_BOOLEAN(0, "check", &check
,
3441 "instead of applying the patch, see if the patch is applicable"),
3442 OPT_BOOLEAN(0, "index", &check_index
,
3443 "make sure the patch is applicable to the current index"),
3444 OPT_BOOLEAN(0, "cached", &cached
,
3445 "apply a patch without touching the working tree"),
3446 OPT_BOOLEAN(0, "apply", &force_apply
,
3447 "also apply the patch (use with --stat/--summary/--check)"),
3448 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor
,
3449 "build a temporary index based on embedded index information"),
3450 { OPTION_CALLBACK
, 'z', NULL
, NULL
, NULL
,
3451 "paths are separated with NUL character",
3452 PARSE_OPT_NOARG
, option_parse_z
},
3453 OPT_INTEGER('C', NULL
, &p_context
,
3454 "ensure at least <n> lines of context match"),
3455 { OPTION_CALLBACK
, 0, "whitespace", &whitespace_option
, "action",
3456 "detect new or modified lines that have whitespace errors",
3457 0, option_parse_whitespace
},
3458 { OPTION_CALLBACK
, 0, "ignore-space-change", NULL
, NULL
,
3459 "ignore changes in whitespace when finding context",
3460 PARSE_OPT_NOARG
, option_parse_space_change
},
3461 { OPTION_CALLBACK
, 0, "ignore-whitespace", NULL
, NULL
,
3462 "ignore changes in whitespace when finding context",
3463 PARSE_OPT_NOARG
, option_parse_space_change
},
3464 OPT_BOOLEAN('R', "reverse", &apply_in_reverse
,
3465 "apply the patch in reverse"),
3466 OPT_BOOLEAN(0, "unidiff-zero", &unidiff_zero
,
3467 "don't expect at least one line of context"),
3468 OPT_BOOLEAN(0, "reject", &apply_with_reject
,
3469 "leave the rejected hunks in corresponding *.rej files"),
3470 OPT__VERBOSE(&apply_verbosely
),
3471 OPT_BIT(0, "inaccurate-eof", &options
,
3472 "tolerate incorrectly detected missing new-line at the end of file",
3474 OPT_BIT(0, "recount", &options
,
3475 "do not trust the line counts in the hunk headers",
3477 { OPTION_CALLBACK
, 0, "directory", NULL
, "root",
3478 "prepend <root> to all filenames",
3479 0, option_parse_directory
},
3483 prefix
= setup_git_directory_gently(&is_not_gitdir
);
3484 prefix_length
= prefix
? strlen(prefix
) : 0;
3485 git_config(git_apply_config
, NULL
);
3486 if (apply_default_whitespace
)
3487 parse_whitespace_option(apply_default_whitespace
);
3488 if (apply_default_ignorewhitespace
)
3489 parse_ignorewhitespace_option(apply_default_ignorewhitespace
);
3491 argc
= parse_options(argc
, argv
, prefix
, builtin_apply_options
,
3494 if (apply_with_reject
)
3495 apply
= apply_verbosely
= 1;
3496 if (!force_apply
&& (diffstat
|| numstat
|| summary
|| check
|| fake_ancestor
))
3498 if (check_index
&& is_not_gitdir
)
3499 die("--index outside a repository");
3502 die("--cached outside a repository");
3505 for (i
= 0; i
< argc
; i
++) {
3506 const char *arg
= argv
[i
];
3509 if (!strcmp(arg
, "-")) {
3510 errs
|= apply_patch(0, "<stdin>", options
);
3513 } else if (0 < prefix_length
)
3514 arg
= prefix_filename(prefix
, prefix_length
, arg
);
3516 fd
= open(arg
, O_RDONLY
);
3518 die_errno("can't open patch '%s'", arg
);
3520 set_default_whitespace_mode(whitespace_option
);
3521 errs
|= apply_patch(fd
, arg
, options
);
3524 set_default_whitespace_mode(whitespace_option
);
3526 errs
|= apply_patch(0, "<stdin>", options
);
3527 if (whitespace_error
) {
3528 if (squelch_whitespace_errors
&&
3529 squelch_whitespace_errors
< whitespace_error
) {
3531 whitespace_error
- squelch_whitespace_errors
;
3532 warning("squelched %d "
3533 "whitespace error%s",
3535 squelched
== 1 ? "" : "s");
3537 if (ws_error_action
== die_on_ws_error
)
3538 die("%d line%s add%s whitespace errors.",
3540 whitespace_error
== 1 ? "" : "s",
3541 whitespace_error
== 1 ? "s" : "");
3542 if (applied_after_fixing_ws
&& apply
)
3543 warning("%d line%s applied after"
3544 " fixing whitespace errors.",
3545 applied_after_fixing_ws
,
3546 applied_after_fixing_ws
== 1 ? "" : "s");
3547 else if (whitespace_error
)
3548 warning("%d line%s add%s whitespace errors.",
3550 whitespace_error
== 1 ? "" : "s",
3551 whitespace_error
== 1 ? "s" : "");
3555 if (write_cache(newfd
, active_cache
, active_nr
) ||
3556 commit_locked_index(&lock_file
))
3557 die("Unable to write new index file");