4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
10 #include "cache-tree.h"
17 * --check turns on checking that the working tree matches the
18 * files that are being modified, but doesn't apply the patch
19 * --stat does just a diffstat, and doesn't actually apply
20 * --numstat does numeric diffstat, and doesn't actually apply
21 * --index-info shows the old and new index info for paths if available.
22 * --index updates the cache as well.
23 * --cached updates only the cache without ever touching the working tree.
25 static const char *prefix
;
26 static int prefix_length
= -1;
27 static int newfd
= -1;
29 static int unidiff_zero
;
30 static int p_value
= 1;
31 static int p_value_known
;
32 static int check_index
;
33 static int update_index
;
40 static int apply_in_reverse
;
41 static int apply_with_reject
;
42 static int apply_verbosely
;
44 static const char *fake_ancestor
;
45 static int line_termination
= '\n';
46 static unsigned long p_context
= ULONG_MAX
;
47 static const char apply_usage
[] =
48 "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|fix|error|error-all>] <patch>...";
50 static enum ws_error_action
{
55 } ws_error_action
= warn_on_ws_error
;
56 static int whitespace_error
;
57 static int squelch_whitespace_errors
= 5;
58 static int applied_after_fixing_ws
;
59 static const char *patch_input_file
;
61 static void parse_whitespace_option(const char *option
)
64 ws_error_action
= warn_on_ws_error
;
67 if (!strcmp(option
, "warn")) {
68 ws_error_action
= warn_on_ws_error
;
71 if (!strcmp(option
, "nowarn")) {
72 ws_error_action
= nowarn_ws_error
;
75 if (!strcmp(option
, "error")) {
76 ws_error_action
= die_on_ws_error
;
79 if (!strcmp(option
, "error-all")) {
80 ws_error_action
= die_on_ws_error
;
81 squelch_whitespace_errors
= 0;
84 if (!strcmp(option
, "strip") || !strcmp(option
, "fix")) {
85 ws_error_action
= correct_ws_error
;
88 die("unrecognized whitespace option '%s'", option
);
91 static void set_default_whitespace_mode(const char *whitespace_option
)
93 if (!whitespace_option
&& !apply_default_whitespace
)
94 ws_error_action
= (apply
? warn_on_ws_error
: nowarn_ws_error
);
98 * For "diff-stat" like behaviour, we keep track of the biggest change
99 * we've seen, and the longest filename. That allows us to do simple
102 static int max_change
, max_len
;
105 * Various "current state", notably line numbers and what
106 * file (and how) we're patching right now.. The "is_xxxx"
107 * things are flags, where -1 means "don't know yet".
109 static int linenr
= 1;
112 * This represents one "hunk" from a patch, starting with
113 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
114 * patch text is pointed at by patch, and its byte length
115 * is stored in size. leading and trailing are the number
119 unsigned long leading
, trailing
;
120 unsigned long oldpos
, oldlines
;
121 unsigned long newpos
, newlines
;
125 struct fragment
*next
;
129 * When dealing with a binary patch, we reuse "leading" field
130 * to store the type of the binary hunk, either deflated "delta"
131 * or deflated "literal".
133 #define binary_patch_method leading
134 #define BINARY_DELTA_DEFLATED 1
135 #define BINARY_LITERAL_DEFLATED 2
138 * This represents a "patch" to a file, both metainfo changes
139 * such as creation/deletion, filemode and content changes represented
140 * as a series of fragments.
143 char *new_name
, *old_name
, *def_name
;
144 unsigned int old_mode
, new_mode
;
145 int is_new
, is_delete
; /* -1 = unknown, 0 = false, 1 = true */
148 unsigned long deflate_origlen
;
149 int lines_added
, lines_deleted
;
151 unsigned int is_toplevel_relative
:1;
152 unsigned int inaccurate_eof
:1;
153 unsigned int is_binary
:1;
154 unsigned int is_copy
:1;
155 unsigned int is_rename
:1;
156 unsigned int recount
:1;
157 struct fragment
*fragments
;
160 char old_sha1_prefix
[41];
161 char new_sha1_prefix
[41];
166 * A line in a file, len-bytes long (includes the terminating LF,
167 * except for an incomplete line at the end if the file ends with
168 * one), and its contents hashes to 'hash'.
174 #define LINE_COMMON 1
178 * This represents a "file", which is an array of "lines".
185 struct line
*line_allocated
;
189 static uint32_t hash_line(const char *cp
, size_t len
)
193 for (i
= 0, h
= 0; i
< len
; i
++) {
194 if (!isspace(cp
[i
])) {
195 h
= h
* 3 + (cp
[i
] & 0xff);
201 static void add_line_info(struct image
*img
, const char *bol
, size_t len
, unsigned flag
)
203 ALLOC_GROW(img
->line_allocated
, img
->nr
+ 1, img
->alloc
);
204 img
->line_allocated
[img
->nr
].len
= len
;
205 img
->line_allocated
[img
->nr
].hash
= hash_line(bol
, len
);
206 img
->line_allocated
[img
->nr
].flag
= flag
;
210 static void prepare_image(struct image
*image
, char *buf
, size_t len
,
211 int prepare_linetable
)
215 memset(image
, 0, sizeof(*image
));
219 if (!prepare_linetable
)
222 ep
= image
->buf
+ image
->len
;
226 for (next
= cp
; next
< ep
&& *next
!= '\n'; next
++)
230 add_line_info(image
, cp
, next
- cp
, 0);
233 image
->line
= image
->line_allocated
;
236 static void clear_image(struct image
*image
)
243 static void say_patch_name(FILE *output
, const char *pre
,
244 struct patch
*patch
, const char *post
)
247 if (patch
->old_name
&& patch
->new_name
&&
248 strcmp(patch
->old_name
, patch
->new_name
)) {
249 quote_c_style(patch
->old_name
, NULL
, output
, 0);
250 fputs(" => ", output
);
251 quote_c_style(patch
->new_name
, NULL
, output
, 0);
253 const char *n
= patch
->new_name
;
256 quote_c_style(n
, NULL
, output
, 0);
261 #define CHUNKSIZE (8192)
264 static void read_patch_file(struct strbuf
*sb
, int fd
)
266 if (strbuf_read(sb
, fd
, 0) < 0)
267 die("git-apply: read returned %s", strerror(errno
));
270 * Make sure that we have some slop in the buffer
271 * so that we can do speculative "memcmp" etc, and
272 * see to it that it is NUL-filled.
274 strbuf_grow(sb
, SLOP
);
275 memset(sb
->buf
+ sb
->len
, 0, SLOP
);
278 static unsigned long linelen(const char *buffer
, unsigned long size
)
280 unsigned long len
= 0;
283 if (*buffer
++ == '\n')
289 static int is_dev_null(const char *str
)
291 return !memcmp("/dev/null", str
, 9) && isspace(str
[9]);
297 static int name_terminate(const char *name
, int namelen
, int c
, int terminate
)
299 if (c
== ' ' && !(terminate
& TERM_SPACE
))
301 if (c
== '\t' && !(terminate
& TERM_TAB
))
307 static char *find_name(const char *line
, char *def
, int p_value
, int terminate
)
310 const char *start
= line
;
316 * Proposed "new-style" GNU patch/diff format; see
317 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
319 strbuf_init(&name
, 0);
320 if (!unquote_c_style(&name
, line
, NULL
)) {
323 for (cp
= name
.buf
; p_value
; p_value
--) {
324 cp
= strchr(cp
, '/');
330 /* name can later be freed, so we need
331 * to memmove, not just return cp
333 strbuf_remove(&name
, 0, cp
- name
.buf
);
335 return strbuf_detach(&name
, NULL
);
338 strbuf_release(&name
);
347 if (name_terminate(start
, line
-start
, c
, terminate
))
351 if (c
== '/' && !--p_value
)
361 * Generally we prefer the shorter name, especially
362 * if the other one is just a variation of that with
363 * something else tacked on to the end (ie "file.orig"
367 int deflen
= strlen(def
);
368 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
373 return xmemdupz(start
, len
);
376 static int count_slashes(const char *cp
)
388 * Given the string after "--- " or "+++ ", guess the appropriate
389 * p_value for the given patch.
391 static int guess_p_value(const char *nameline
)
396 if (is_dev_null(nameline
))
398 name
= find_name(nameline
, NULL
, 0, TERM_SPACE
| TERM_TAB
);
401 cp
= strchr(name
, '/');
406 * Does it begin with "a/$our-prefix" and such? Then this is
407 * very likely to apply to our directory.
409 if (!strncmp(name
, prefix
, prefix_length
))
410 val
= count_slashes(prefix
);
413 if (!strncmp(cp
, prefix
, prefix_length
))
414 val
= count_slashes(prefix
) + 1;
422 * Get the name etc info from the ---/+++ lines of a traditional patch header
424 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
425 * files, we can happily check the index for a match, but for creating a
426 * new file we should try to match whatever "patch" does. I have no idea.
428 static void parse_traditional_patch(const char *first
, const char *second
, struct patch
*patch
)
432 first
+= 4; /* skip "--- " */
433 second
+= 4; /* skip "+++ " */
434 if (!p_value_known
) {
436 p
= guess_p_value(first
);
437 q
= guess_p_value(second
);
439 if (0 <= p
&& p
== q
) {
444 if (is_dev_null(first
)) {
446 patch
->is_delete
= 0;
447 name
= find_name(second
, NULL
, p_value
, TERM_SPACE
| TERM_TAB
);
448 patch
->new_name
= name
;
449 } else if (is_dev_null(second
)) {
451 patch
->is_delete
= 1;
452 name
= find_name(first
, NULL
, p_value
, TERM_SPACE
| TERM_TAB
);
453 patch
->old_name
= name
;
455 name
= find_name(first
, NULL
, p_value
, TERM_SPACE
| TERM_TAB
);
456 name
= find_name(second
, name
, p_value
, TERM_SPACE
| TERM_TAB
);
457 patch
->old_name
= patch
->new_name
= name
;
460 die("unable to find filename in patch at line %d", linenr
);
463 static int gitdiff_hdrend(const char *line
, struct patch
*patch
)
469 * We're anal about diff header consistency, to make
470 * sure that we don't end up having strange ambiguous
471 * patches floating around.
473 * As a result, gitdiff_{old|new}name() will check
474 * their names against any previous information, just
477 static char *gitdiff_verify_name(const char *line
, int isnull
, char *orig_name
, const char *oldnew
)
479 if (!orig_name
&& !isnull
)
480 return find_name(line
, NULL
, p_value
, TERM_TAB
);
489 die("git-apply: bad git-diff - expected /dev/null, got %s on line %d", name
, linenr
);
490 another
= find_name(line
, NULL
, p_value
, TERM_TAB
);
491 if (!another
|| memcmp(another
, name
, len
))
492 die("git-apply: bad git-diff - inconsistent %s filename on line %d", oldnew
, linenr
);
497 /* expect "/dev/null" */
498 if (memcmp("/dev/null", line
, 9) || line
[9] != '\n')
499 die("git-apply: bad git-diff - expected /dev/null on line %d", linenr
);
504 static int gitdiff_oldname(const char *line
, struct patch
*patch
)
506 patch
->old_name
= gitdiff_verify_name(line
, patch
->is_new
, patch
->old_name
, "old");
510 static int gitdiff_newname(const char *line
, struct patch
*patch
)
512 patch
->new_name
= gitdiff_verify_name(line
, patch
->is_delete
, patch
->new_name
, "new");
516 static int gitdiff_oldmode(const char *line
, struct patch
*patch
)
518 patch
->old_mode
= strtoul(line
, NULL
, 8);
522 static int gitdiff_newmode(const char *line
, struct patch
*patch
)
524 patch
->new_mode
= strtoul(line
, NULL
, 8);
528 static int gitdiff_delete(const char *line
, struct patch
*patch
)
530 patch
->is_delete
= 1;
531 patch
->old_name
= patch
->def_name
;
532 return gitdiff_oldmode(line
, patch
);
535 static int gitdiff_newfile(const char *line
, struct patch
*patch
)
538 patch
->new_name
= patch
->def_name
;
539 return gitdiff_newmode(line
, patch
);
542 static int gitdiff_copysrc(const char *line
, struct patch
*patch
)
545 patch
->old_name
= find_name(line
, NULL
, 0, 0);
549 static int gitdiff_copydst(const char *line
, struct patch
*patch
)
552 patch
->new_name
= find_name(line
, NULL
, 0, 0);
556 static int gitdiff_renamesrc(const char *line
, struct patch
*patch
)
558 patch
->is_rename
= 1;
559 patch
->old_name
= find_name(line
, NULL
, 0, 0);
563 static int gitdiff_renamedst(const char *line
, struct patch
*patch
)
565 patch
->is_rename
= 1;
566 patch
->new_name
= find_name(line
, NULL
, 0, 0);
570 static int gitdiff_similarity(const char *line
, struct patch
*patch
)
572 if ((patch
->score
= strtoul(line
, NULL
, 10)) == ULONG_MAX
)
577 static int gitdiff_dissimilarity(const char *line
, struct patch
*patch
)
579 if ((patch
->score
= strtoul(line
, NULL
, 10)) == ULONG_MAX
)
584 static int gitdiff_index(const char *line
, struct patch
*patch
)
587 * index line is N hexadecimal, "..", N hexadecimal,
588 * and optional space with octal mode.
590 const char *ptr
, *eol
;
593 ptr
= strchr(line
, '.');
594 if (!ptr
|| ptr
[1] != '.' || 40 < ptr
- line
)
597 memcpy(patch
->old_sha1_prefix
, line
, len
);
598 patch
->old_sha1_prefix
[len
] = 0;
601 ptr
= strchr(line
, ' ');
602 eol
= strchr(line
, '\n');
604 if (!ptr
|| eol
< ptr
)
610 memcpy(patch
->new_sha1_prefix
, line
, len
);
611 patch
->new_sha1_prefix
[len
] = 0;
613 patch
->new_mode
= patch
->old_mode
= strtoul(ptr
+1, NULL
, 8);
618 * This is normal for a diff that doesn't change anything: we'll fall through
619 * into the next diff. Tell the parser to break out.
621 static int gitdiff_unrecognized(const char *line
, struct patch
*patch
)
626 static const char *stop_at_slash(const char *line
, int llen
)
630 for (i
= 0; i
< llen
; i
++) {
639 * This is to extract the same name that appears on "diff --git"
640 * line. We do not find and return anything if it is a rename
641 * patch, and it is OK because we will find the name elsewhere.
642 * We need to reliably find name only when it is mode-change only,
643 * creation or deletion of an empty file. In any of these cases,
644 * both sides are the same name under a/ and b/ respectively.
646 static char *git_header_name(char *line
, int llen
)
649 const char *second
= NULL
;
652 line
+= strlen("diff --git ");
653 llen
-= strlen("diff --git ");
660 strbuf_init(&first
, 0);
663 if (unquote_c_style(&first
, line
, &second
))
666 /* advance to the first slash */
667 cp
= stop_at_slash(first
.buf
, first
.len
);
668 /* we do not accept absolute paths */
669 if (!cp
|| cp
== first
.buf
)
671 strbuf_remove(&first
, 0, cp
+ 1 - first
.buf
);
674 * second points at one past closing dq of name.
675 * find the second name.
677 while ((second
< line
+ llen
) && isspace(*second
))
680 if (line
+ llen
<= second
)
682 if (*second
== '"') {
683 if (unquote_c_style(&sp
, second
, NULL
))
685 cp
= stop_at_slash(sp
.buf
, sp
.len
);
686 if (!cp
|| cp
== sp
.buf
)
688 /* They must match, otherwise ignore */
689 if (strcmp(cp
+ 1, first
.buf
))
692 return strbuf_detach(&first
, NULL
);
695 /* unquoted second */
696 cp
= stop_at_slash(second
, line
+ llen
- second
);
697 if (!cp
|| cp
== second
)
700 if (line
+ llen
- cp
!= first
.len
+ 1 ||
701 memcmp(first
.buf
, cp
, first
.len
))
703 return strbuf_detach(&first
, NULL
);
706 strbuf_release(&first
);
711 /* unquoted first name */
712 name
= stop_at_slash(line
, llen
);
713 if (!name
|| name
== line
)
718 * since the first name is unquoted, a dq if exists must be
719 * the beginning of the second name.
721 for (second
= name
; second
< line
+ llen
; second
++) {
722 if (*second
== '"') {
727 if (unquote_c_style(&sp
, second
, NULL
))
730 np
= stop_at_slash(sp
.buf
, sp
.len
);
731 if (!np
|| np
== sp
.buf
)
735 len
= sp
.buf
+ sp
.len
- np
;
736 if (len
< second
- name
&&
737 !strncmp(np
, name
, len
) &&
738 isspace(name
[len
])) {
740 strbuf_remove(&sp
, 0, np
- sp
.buf
);
741 return strbuf_detach(&sp
, NULL
);
751 * Accept a name only if it shows up twice, exactly the same
754 for (len
= 0 ; ; len
++) {
769 if (second
[len
] == '\n' && !memcmp(name
, second
, len
)) {
770 return xmemdupz(name
, len
);
776 /* Verify that we recognize the lines following a git header */
777 static int parse_git_header(char *line
, int len
, unsigned int size
, struct patch
*patch
)
779 unsigned long offset
;
781 /* A git diff has explicit new/delete information, so we don't guess */
783 patch
->is_delete
= 0;
786 * Some things may not have the old name in the
787 * rest of the headers anywhere (pure mode changes,
788 * or removing or adding empty files), so we get
789 * the default name from the header.
791 patch
->def_name
= git_header_name(line
, len
);
796 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
797 static const struct opentry
{
799 int (*fn
)(const char *, struct patch
*);
801 { "@@ -", gitdiff_hdrend
},
802 { "--- ", gitdiff_oldname
},
803 { "+++ ", gitdiff_newname
},
804 { "old mode ", gitdiff_oldmode
},
805 { "new mode ", gitdiff_newmode
},
806 { "deleted file mode ", gitdiff_delete
},
807 { "new file mode ", gitdiff_newfile
},
808 { "copy from ", gitdiff_copysrc
},
809 { "copy to ", gitdiff_copydst
},
810 { "rename old ", gitdiff_renamesrc
},
811 { "rename new ", gitdiff_renamedst
},
812 { "rename from ", gitdiff_renamesrc
},
813 { "rename to ", gitdiff_renamedst
},
814 { "similarity index ", gitdiff_similarity
},
815 { "dissimilarity index ", gitdiff_dissimilarity
},
816 { "index ", gitdiff_index
},
817 { "", gitdiff_unrecognized
},
821 len
= linelen(line
, size
);
822 if (!len
|| line
[len
-1] != '\n')
824 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
825 const struct opentry
*p
= optable
+ i
;
826 int oplen
= strlen(p
->str
);
827 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
829 if (p
->fn(line
+ oplen
, patch
) < 0)
838 static int parse_num(const char *line
, unsigned long *p
)
844 *p
= strtoul(line
, &ptr
, 10);
848 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
849 unsigned long *p1
, unsigned long *p2
)
853 if (offset
< 0 || offset
>= len
)
858 digits
= parse_num(line
, p1
);
868 digits
= parse_num(line
+1, p2
);
880 if (memcmp(line
, expect
, ex
))
886 static void recount_diff(char *line
, int size
, struct fragment
*fragment
)
888 int oldlines
= 0, newlines
= 0, ret
= 0;
891 warning("recount: ignore empty hunk");
896 int len
= linelen(line
, size
);
916 ret
= size
< 3 || prefixcmp(line
, "@@ ");
919 ret
= size
< 5 || prefixcmp(line
, "diff ");
926 warning("recount: unexpected line: %.*s",
927 (int)linelen(line
, size
), line
);
932 fragment
->oldlines
= oldlines
;
933 fragment
->newlines
= newlines
;
937 * Parse a unified diff fragment header of the
938 * form "@@ -a,b +c,d @@"
940 static int parse_fragment_header(char *line
, int len
, struct fragment
*fragment
)
944 if (!len
|| line
[len
-1] != '\n')
947 /* Figure out the number of lines in a fragment */
948 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
949 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
954 static int find_header(char *line
, unsigned long size
, int *hdrsize
, struct patch
*patch
)
956 unsigned long offset
, len
;
958 patch
->is_toplevel_relative
= 0;
959 patch
->is_rename
= patch
->is_copy
= 0;
960 patch
->is_new
= patch
->is_delete
= -1;
961 patch
->old_mode
= patch
->new_mode
= 0;
962 patch
->old_name
= patch
->new_name
= NULL
;
963 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
964 unsigned long nextlen
;
966 len
= linelen(line
, size
);
970 /* Testing this early allows us to take a few shortcuts.. */
975 * Make sure we don't find any unconnected patch fragments.
976 * That's a sign that we didn't find a header, and that a
977 * patch has become corrupted/broken up.
979 if (!memcmp("@@ -", line
, 4)) {
980 struct fragment dummy
;
981 if (parse_fragment_header(line
, len
, &dummy
) < 0)
983 die("patch fragment without header at line %d: %.*s",
984 linenr
, (int)len
-1, line
);
991 * Git patch? It might not have a real patch, just a rename
992 * or mode change, so we handle that specially
994 if (!memcmp("diff --git ", line
, 11)) {
995 int git_hdr_len
= parse_git_header(line
, len
, size
, patch
);
996 if (git_hdr_len
<= len
)
998 if (!patch
->old_name
&& !patch
->new_name
) {
999 if (!patch
->def_name
)
1000 die("git diff header lacks filename information (line %d)", linenr
);
1001 patch
->old_name
= patch
->new_name
= patch
->def_name
;
1003 patch
->is_toplevel_relative
= 1;
1004 *hdrsize
= git_hdr_len
;
1008 /* --- followed by +++ ? */
1009 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
1013 * We only accept unified patches, so we want it to
1014 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1015 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1017 nextlen
= linelen(line
+ len
, size
- len
);
1018 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
1021 /* Ok, we'll consider it a patch */
1022 parse_traditional_patch(line
, line
+len
, patch
);
1023 *hdrsize
= len
+ nextlen
;
1030 static void check_whitespace(const char *line
, int len
, unsigned ws_rule
)
1033 unsigned result
= check_and_emit_line(line
+ 1, len
- 1, ws_rule
,
1034 NULL
, NULL
, NULL
, NULL
);
1039 if (squelch_whitespace_errors
&&
1040 squelch_whitespace_errors
< whitespace_error
)
1043 err
= whitespace_error_string(result
);
1044 fprintf(stderr
, "%s:%d: %s.\n%.*s\n",
1045 patch_input_file
, linenr
, err
, len
- 2, line
+ 1);
1051 * Parse a unified diff. Note that this really needs to parse each
1052 * fragment separately, since the only way to know the difference
1053 * between a "---" that is part of a patch, and a "---" that starts
1054 * the next patch is to look at the line counts..
1056 static int parse_fragment(char *line
, unsigned long size
,
1057 struct patch
*patch
, struct fragment
*fragment
)
1060 int len
= linelen(line
, size
), offset
;
1061 unsigned long oldlines
, newlines
;
1062 unsigned long leading
, trailing
;
1064 offset
= parse_fragment_header(line
, len
, fragment
);
1067 if (offset
> 0 && patch
->recount
)
1068 recount_diff(line
+ offset
, size
- offset
, fragment
);
1069 oldlines
= fragment
->oldlines
;
1070 newlines
= fragment
->newlines
;
1074 /* Parse the thing.. */
1078 added
= deleted
= 0;
1081 offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1082 if (!oldlines
&& !newlines
)
1084 len
= linelen(line
, size
);
1085 if (!len
|| line
[len
-1] != '\n')
1090 case '\n': /* newer GNU diff, an empty context line */
1094 if (!deleted
&& !added
)
1099 if (apply_in_reverse
&&
1100 ws_error_action
!= nowarn_ws_error
)
1101 check_whitespace(line
, len
, patch
->ws_rule
);
1107 if (!apply_in_reverse
&&
1108 ws_error_action
!= nowarn_ws_error
)
1109 check_whitespace(line
, len
, patch
->ws_rule
);
1116 * We allow "\ No newline at end of file". Depending
1117 * on locale settings when the patch was produced we
1118 * don't know what this line looks like. The only
1119 * thing we do know is that it begins with "\ ".
1120 * Checking for 12 is just for sanity check -- any
1121 * l10n of "\ No newline..." is at least that long.
1124 if (len
< 12 || memcmp(line
, "\\ ", 2))
1129 if (oldlines
|| newlines
)
1131 fragment
->leading
= leading
;
1132 fragment
->trailing
= trailing
;
1135 * If a fragment ends with an incomplete line, we failed to include
1136 * it in the above loop because we hit oldlines == newlines == 0
1139 if (12 < size
&& !memcmp(line
, "\\ ", 2))
1140 offset
+= linelen(line
, size
);
1142 patch
->lines_added
+= added
;
1143 patch
->lines_deleted
+= deleted
;
1145 if (0 < patch
->is_new
&& oldlines
)
1146 return error("new file depends on old contents");
1147 if (0 < patch
->is_delete
&& newlines
)
1148 return error("deleted file still has contents");
1152 static int parse_single_patch(char *line
, unsigned long size
, struct patch
*patch
)
1154 unsigned long offset
= 0;
1155 unsigned long oldlines
= 0, newlines
= 0, context
= 0;
1156 struct fragment
**fragp
= &patch
->fragments
;
1158 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
1159 struct fragment
*fragment
;
1162 fragment
= xcalloc(1, sizeof(*fragment
));
1163 len
= parse_fragment(line
, size
, patch
, fragment
);
1165 die("corrupt patch at line %d", linenr
);
1166 fragment
->patch
= line
;
1167 fragment
->size
= len
;
1168 oldlines
+= fragment
->oldlines
;
1169 newlines
+= fragment
->newlines
;
1170 context
+= fragment
->leading
+ fragment
->trailing
;
1173 fragp
= &fragment
->next
;
1181 * If something was removed (i.e. we have old-lines) it cannot
1182 * be creation, and if something was added it cannot be
1183 * deletion. However, the reverse is not true; --unified=0
1184 * patches that only add are not necessarily creation even
1185 * though they do not have any old lines, and ones that only
1186 * delete are not necessarily deletion.
1188 * Unfortunately, a real creation/deletion patch do _not_ have
1189 * any context line by definition, so we cannot safely tell it
1190 * apart with --unified=0 insanity. At least if the patch has
1191 * more than one hunk it is not creation or deletion.
1193 if (patch
->is_new
< 0 &&
1194 (oldlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1196 if (patch
->is_delete
< 0 &&
1197 (newlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1198 patch
->is_delete
= 0;
1200 if (0 < patch
->is_new
&& oldlines
)
1201 die("new file %s depends on old contents", patch
->new_name
);
1202 if (0 < patch
->is_delete
&& newlines
)
1203 die("deleted file %s still has contents", patch
->old_name
);
1204 if (!patch
->is_delete
&& !newlines
&& context
)
1205 fprintf(stderr
, "** warning: file %s becomes empty but "
1206 "is not deleted\n", patch
->new_name
);
1211 static inline int metadata_changes(struct patch
*patch
)
1213 return patch
->is_rename
> 0 ||
1214 patch
->is_copy
> 0 ||
1215 patch
->is_new
> 0 ||
1217 (patch
->old_mode
&& patch
->new_mode
&&
1218 patch
->old_mode
!= patch
->new_mode
);
1221 static char *inflate_it(const void *data
, unsigned long size
,
1222 unsigned long inflated_size
)
1228 memset(&stream
, 0, sizeof(stream
));
1230 stream
.next_in
= (unsigned char *)data
;
1231 stream
.avail_in
= size
;
1232 stream
.next_out
= out
= xmalloc(inflated_size
);
1233 stream
.avail_out
= inflated_size
;
1234 inflateInit(&stream
);
1235 st
= inflate(&stream
, Z_FINISH
);
1236 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1243 static struct fragment
*parse_binary_hunk(char **buf_p
,
1244 unsigned long *sz_p
,
1249 * Expect a line that begins with binary patch method ("literal"
1250 * or "delta"), followed by the length of data before deflating.
1251 * a sequence of 'length-byte' followed by base-85 encoded data
1252 * should follow, terminated by a newline.
1254 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1255 * and we would limit the patch line to 66 characters,
1256 * so one line can fit up to 13 groups that would decode
1257 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1258 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1261 unsigned long size
= *sz_p
;
1262 char *buffer
= *buf_p
;
1264 unsigned long origlen
;
1267 struct fragment
*frag
;
1269 llen
= linelen(buffer
, size
);
1274 if (!prefixcmp(buffer
, "delta ")) {
1275 patch_method
= BINARY_DELTA_DEFLATED
;
1276 origlen
= strtoul(buffer
+ 6, NULL
, 10);
1278 else if (!prefixcmp(buffer
, "literal ")) {
1279 patch_method
= BINARY_LITERAL_DEFLATED
;
1280 origlen
= strtoul(buffer
+ 8, NULL
, 10);
1288 int byte_length
, max_byte_length
, newsize
;
1289 llen
= linelen(buffer
, size
);
1293 /* consume the blank line */
1299 * Minimum line is "A00000\n" which is 7-byte long,
1300 * and the line length must be multiple of 5 plus 2.
1302 if ((llen
< 7) || (llen
-2) % 5)
1304 max_byte_length
= (llen
- 2) / 5 * 4;
1305 byte_length
= *buffer
;
1306 if ('A' <= byte_length
&& byte_length
<= 'Z')
1307 byte_length
= byte_length
- 'A' + 1;
1308 else if ('a' <= byte_length
&& byte_length
<= 'z')
1309 byte_length
= byte_length
- 'a' + 27;
1312 /* if the input length was not multiple of 4, we would
1313 * have filler at the end but the filler should never
1316 if (max_byte_length
< byte_length
||
1317 byte_length
<= max_byte_length
- 4)
1319 newsize
= hunk_size
+ byte_length
;
1320 data
= xrealloc(data
, newsize
);
1321 if (decode_85(data
+ hunk_size
, buffer
+ 1, byte_length
))
1323 hunk_size
= newsize
;
1328 frag
= xcalloc(1, sizeof(*frag
));
1329 frag
->patch
= inflate_it(data
, hunk_size
, origlen
);
1333 frag
->size
= origlen
;
1337 frag
->binary_patch_method
= patch_method
;
1343 error("corrupt binary patch at line %d: %.*s",
1344 linenr
-1, llen
-1, buffer
);
1348 static int parse_binary(char *buffer
, unsigned long size
, struct patch
*patch
)
1351 * We have read "GIT binary patch\n"; what follows is a line
1352 * that says the patch method (currently, either "literal" or
1353 * "delta") and the length of data before deflating; a
1354 * sequence of 'length-byte' followed by base-85 encoded data
1357 * When a binary patch is reversible, there is another binary
1358 * hunk in the same format, starting with patch method (either
1359 * "literal" or "delta") with the length of data, and a sequence
1360 * of length-byte + base-85 encoded data, terminated with another
1361 * empty line. This data, when applied to the postimage, produces
1364 struct fragment
*forward
;
1365 struct fragment
*reverse
;
1369 forward
= parse_binary_hunk(&buffer
, &size
, &status
, &used
);
1370 if (!forward
&& !status
)
1371 /* there has to be one hunk (forward hunk) */
1372 return error("unrecognized binary patch at line %d", linenr
-1);
1374 /* otherwise we already gave an error message */
1377 reverse
= parse_binary_hunk(&buffer
, &size
, &status
, &used_1
);
1382 * Not having reverse hunk is not an error, but having
1383 * a corrupt reverse hunk is.
1385 free((void*) forward
->patch
);
1389 forward
->next
= reverse
;
1390 patch
->fragments
= forward
;
1391 patch
->is_binary
= 1;
1395 static int parse_chunk(char *buffer
, unsigned long size
, struct patch
*patch
)
1397 int hdrsize
, patchsize
;
1398 int offset
= find_header(buffer
, size
, &hdrsize
, patch
);
1403 patch
->ws_rule
= whitespace_rule(patch
->new_name
1407 patchsize
= parse_single_patch(buffer
+ offset
+ hdrsize
,
1408 size
- offset
- hdrsize
, patch
);
1411 static const char *binhdr
[] = {
1416 static const char git_binary
[] = "GIT binary patch\n";
1418 int hd
= hdrsize
+ offset
;
1419 unsigned long llen
= linelen(buffer
+ hd
, size
- hd
);
1421 if (llen
== sizeof(git_binary
) - 1 &&
1422 !memcmp(git_binary
, buffer
+ hd
, llen
)) {
1425 used
= parse_binary(buffer
+ hd
+ llen
,
1426 size
- hd
- llen
, patch
);
1428 patchsize
= used
+ llen
;
1432 else if (!memcmp(" differ\n", buffer
+ hd
+ llen
- 8, 8)) {
1433 for (i
= 0; binhdr
[i
]; i
++) {
1434 int len
= strlen(binhdr
[i
]);
1435 if (len
< size
- hd
&&
1436 !memcmp(binhdr
[i
], buffer
+ hd
, len
)) {
1438 patch
->is_binary
= 1;
1445 /* Empty patch cannot be applied if it is a text patch
1446 * without metadata change. A binary patch appears
1449 if ((apply
|| check
) &&
1450 (!patch
->is_binary
&& !metadata_changes(patch
)))
1451 die("patch with only garbage at line %d", linenr
);
1454 return offset
+ hdrsize
+ patchsize
;
1457 #define swap(a,b) myswap((a),(b),sizeof(a))
1459 #define myswap(a, b, size) do { \
1460 unsigned char mytmp[size]; \
1461 memcpy(mytmp, &a, size); \
1462 memcpy(&a, &b, size); \
1463 memcpy(&b, mytmp, size); \
1466 static void reverse_patches(struct patch
*p
)
1468 for (; p
; p
= p
->next
) {
1469 struct fragment
*frag
= p
->fragments
;
1471 swap(p
->new_name
, p
->old_name
);
1472 swap(p
->new_mode
, p
->old_mode
);
1473 swap(p
->is_new
, p
->is_delete
);
1474 swap(p
->lines_added
, p
->lines_deleted
);
1475 swap(p
->old_sha1_prefix
, p
->new_sha1_prefix
);
1477 for (; frag
; frag
= frag
->next
) {
1478 swap(frag
->newpos
, frag
->oldpos
);
1479 swap(frag
->newlines
, frag
->oldlines
);
1484 static const char pluses
[] =
1485 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1486 static const char minuses
[]=
1487 "----------------------------------------------------------------------";
1489 static void show_stats(struct patch
*patch
)
1491 struct strbuf qname
;
1492 char *cp
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
1495 strbuf_init(&qname
, 0);
1496 quote_c_style(cp
, &qname
, NULL
, 0);
1499 * "scale" the filename
1505 if (qname
.len
> max
) {
1506 cp
= strchr(qname
.buf
+ qname
.len
+ 3 - max
, '/');
1508 cp
= qname
.buf
+ qname
.len
+ 3 - max
;
1509 strbuf_splice(&qname
, 0, cp
- qname
.buf
, "...", 3);
1512 if (patch
->is_binary
) {
1513 printf(" %-*s | Bin\n", max
, qname
.buf
);
1514 strbuf_release(&qname
);
1518 printf(" %-*s |", max
, qname
.buf
);
1519 strbuf_release(&qname
);
1522 * scale the add/delete
1524 max
= max
+ max_change
> 70 ? 70 - max
: max_change
;
1525 add
= patch
->lines_added
;
1526 del
= patch
->lines_deleted
;
1528 if (max_change
> 0) {
1529 int total
= ((add
+ del
) * max
+ max_change
/ 2) / max_change
;
1530 add
= (add
* max
+ max_change
/ 2) / max_change
;
1533 printf("%5d %.*s%.*s\n", patch
->lines_added
+ patch
->lines_deleted
,
1534 add
, pluses
, del
, minuses
);
1537 static int read_old_data(struct stat
*st
, const char *path
, struct strbuf
*buf
)
1539 switch (st
->st_mode
& S_IFMT
) {
1541 strbuf_grow(buf
, st
->st_size
);
1542 if (readlink(path
, buf
->buf
, st
->st_size
) != st
->st_size
)
1544 strbuf_setlen(buf
, st
->st_size
);
1547 if (strbuf_read_file(buf
, path
, st
->st_size
) != st
->st_size
)
1548 return error("unable to open or read %s", path
);
1549 convert_to_git(path
, buf
->buf
, buf
->len
, buf
, 0);
1556 static void update_pre_post_images(struct image
*preimage
,
1557 struct image
*postimage
,
1562 char *new, *old
, *fixed
;
1563 struct image fixed_preimage
;
1566 * Update the preimage with whitespace fixes. Note that we
1567 * are not losing preimage->buf -- apply_one_fragment() will
1570 prepare_image(&fixed_preimage
, buf
, len
, 1);
1571 assert(fixed_preimage
.nr
== preimage
->nr
);
1572 for (i
= 0; i
< preimage
->nr
; i
++)
1573 fixed_preimage
.line
[i
].flag
= preimage
->line
[i
].flag
;
1574 free(preimage
->line_allocated
);
1575 *preimage
= fixed_preimage
;
1578 * Adjust the common context lines in postimage, in place.
1579 * This is possible because whitespace fixing does not make
1582 new = old
= postimage
->buf
;
1583 fixed
= preimage
->buf
;
1584 for (i
= ctx
= 0; i
< postimage
->nr
; i
++) {
1585 size_t len
= postimage
->line
[i
].len
;
1586 if (!(postimage
->line
[i
].flag
& LINE_COMMON
)) {
1587 /* an added line -- no counterparts in preimage */
1588 memmove(new, old
, len
);
1594 /* a common context -- skip it in the original postimage */
1597 /* and find the corresponding one in the fixed preimage */
1598 while (ctx
< preimage
->nr
&&
1599 !(preimage
->line
[ctx
].flag
& LINE_COMMON
)) {
1600 fixed
+= preimage
->line
[ctx
].len
;
1603 if (preimage
->nr
<= ctx
)
1606 /* and copy it in, while fixing the line length */
1607 len
= preimage
->line
[ctx
].len
;
1608 memcpy(new, fixed
, len
);
1611 postimage
->line
[i
].len
= len
;
1615 /* Fix the length of the whole thing */
1616 postimage
->len
= new - postimage
->buf
;
1619 static int match_fragment(struct image
*img
,
1620 struct image
*preimage
,
1621 struct image
*postimage
,
1625 int match_beginning
, int match_end
)
1628 char *fixed_buf
, *buf
, *orig
, *target
;
1630 if (preimage
->nr
+ try_lno
> img
->nr
)
1633 if (match_beginning
&& try_lno
)
1636 if (match_end
&& preimage
->nr
+ try_lno
!= img
->nr
)
1639 /* Quick hash check */
1640 for (i
= 0; i
< preimage
->nr
; i
++)
1641 if (preimage
->line
[i
].hash
!= img
->line
[try_lno
+ i
].hash
)
1645 * Do we have an exact match? If we were told to match
1646 * at the end, size must be exactly at try+fragsize,
1647 * otherwise try+fragsize must be still within the preimage,
1648 * and either case, the old piece should match the preimage
1652 ? (try + preimage
->len
== img
->len
)
1653 : (try + preimage
->len
<= img
->len
)) &&
1654 !memcmp(img
->buf
+ try, preimage
->buf
, preimage
->len
))
1657 if (ws_error_action
!= correct_ws_error
)
1661 * The hunk does not apply byte-by-byte, but the hash says
1662 * it might with whitespace fuzz.
1664 fixed_buf
= xmalloc(preimage
->len
+ 1);
1666 orig
= preimage
->buf
;
1667 target
= img
->buf
+ try;
1668 for (i
= 0; i
< preimage
->nr
; i
++) {
1669 size_t fixlen
; /* length after fixing the preimage */
1670 size_t oldlen
= preimage
->line
[i
].len
;
1671 size_t tgtlen
= img
->line
[try_lno
+ i
].len
;
1672 size_t tgtfixlen
; /* length after fixing the target line */
1673 char tgtfixbuf
[1024], *tgtfix
;
1676 /* Try fixing the line in the preimage */
1677 fixlen
= ws_fix_copy(buf
, orig
, oldlen
, ws_rule
, NULL
);
1679 /* Try fixing the line in the target */
1680 if (sizeof(tgtfixbuf
) < tgtlen
)
1683 tgtfix
= xmalloc(tgtlen
);
1684 tgtfixlen
= ws_fix_copy(tgtfix
, target
, tgtlen
, ws_rule
, NULL
);
1687 * If they match, either the preimage was based on
1688 * a version before our tree fixed whitespace breakage,
1689 * or we are lacking a whitespace-fix patch the tree
1690 * the preimage was based on already had (i.e. target
1691 * has whitespace breakage, the preimage doesn't).
1692 * In either case, we are fixing the whitespace breakages
1693 * so we might as well take the fix together with their
1696 match
= (tgtfixlen
== fixlen
&& !memcmp(tgtfix
, buf
, fixlen
));
1698 if (tgtfix
!= tgtfixbuf
)
1709 * Yes, the preimage is based on an older version that still
1710 * has whitespace breakages unfixed, and fixing them makes the
1711 * hunk match. Update the context lines in the postimage.
1713 update_pre_post_images(preimage
, postimage
,
1714 fixed_buf
, buf
- fixed_buf
);
1722 static int find_pos(struct image
*img
,
1723 struct image
*preimage
,
1724 struct image
*postimage
,
1727 int match_beginning
, int match_end
)
1730 unsigned long backwards
, forwards
, try;
1731 int backwards_lno
, forwards_lno
, try_lno
;
1733 if (preimage
->nr
> img
->nr
)
1737 * If match_begining or match_end is specified, there is no
1738 * point starting from a wrong line that will never match and
1739 * wander around and wait for a match at the specified end.
1741 if (match_beginning
)
1744 line
= img
->nr
- preimage
->nr
;
1750 for (i
= 0; i
< line
; i
++)
1751 try += img
->line
[i
].len
;
1754 * There's probably some smart way to do this, but I'll leave
1755 * that to the smart and beautiful people. I'm simple and stupid.
1758 backwards_lno
= line
;
1760 forwards_lno
= line
;
1763 for (i
= 0; ; i
++) {
1764 if (match_fragment(img
, preimage
, postimage
,
1765 try, try_lno
, ws_rule
,
1766 match_beginning
, match_end
))
1770 if (backwards_lno
== 0 && forwards_lno
== img
->nr
)
1774 if (backwards_lno
== 0) {
1779 backwards
-= img
->line
[backwards_lno
].len
;
1781 try_lno
= backwards_lno
;
1783 if (forwards_lno
== img
->nr
) {
1787 forwards
+= img
->line
[forwards_lno
].len
;
1790 try_lno
= forwards_lno
;
1797 static void remove_first_line(struct image
*img
)
1799 img
->buf
+= img
->line
[0].len
;
1800 img
->len
-= img
->line
[0].len
;
1805 static void remove_last_line(struct image
*img
)
1807 img
->len
-= img
->line
[--img
->nr
].len
;
1810 static void update_image(struct image
*img
,
1812 struct image
*preimage
,
1813 struct image
*postimage
)
1816 * remove the copy of preimage at offset in img
1817 * and replace it with postimage
1820 size_t remove_count
, insert_count
, applied_at
= 0;
1823 for (i
= 0; i
< applied_pos
; i
++)
1824 applied_at
+= img
->line
[i
].len
;
1827 for (i
= 0; i
< preimage
->nr
; i
++)
1828 remove_count
+= img
->line
[applied_pos
+ i
].len
;
1829 insert_count
= postimage
->len
;
1831 /* Adjust the contents */
1832 result
= xmalloc(img
->len
+ insert_count
- remove_count
+ 1);
1833 memcpy(result
, img
->buf
, applied_at
);
1834 memcpy(result
+ applied_at
, postimage
->buf
, postimage
->len
);
1835 memcpy(result
+ applied_at
+ postimage
->len
,
1836 img
->buf
+ (applied_at
+ remove_count
),
1837 img
->len
- (applied_at
+ remove_count
));
1840 img
->len
+= insert_count
- remove_count
;
1841 result
[img
->len
] = '\0';
1843 /* Adjust the line table */
1844 nr
= img
->nr
+ postimage
->nr
- preimage
->nr
;
1845 if (preimage
->nr
< postimage
->nr
) {
1847 * NOTE: this knows that we never call remove_first_line()
1848 * on anything other than pre/post image.
1850 img
->line
= xrealloc(img
->line
, nr
* sizeof(*img
->line
));
1851 img
->line_allocated
= img
->line
;
1853 if (preimage
->nr
!= postimage
->nr
)
1854 memmove(img
->line
+ applied_pos
+ postimage
->nr
,
1855 img
->line
+ applied_pos
+ preimage
->nr
,
1856 (img
->nr
- (applied_pos
+ preimage
->nr
)) *
1857 sizeof(*img
->line
));
1858 memcpy(img
->line
+ applied_pos
,
1860 postimage
->nr
* sizeof(*img
->line
));
1864 static int apply_one_fragment(struct image
*img
, struct fragment
*frag
,
1865 int inaccurate_eof
, unsigned ws_rule
)
1867 int match_beginning
, match_end
;
1868 const char *patch
= frag
->patch
;
1869 int size
= frag
->size
;
1870 char *old
, *new, *oldlines
, *newlines
;
1871 int new_blank_lines_at_end
= 0;
1872 unsigned long leading
, trailing
;
1873 int pos
, applied_pos
;
1874 struct image preimage
;
1875 struct image postimage
;
1877 memset(&preimage
, 0, sizeof(preimage
));
1878 memset(&postimage
, 0, sizeof(postimage
));
1879 oldlines
= xmalloc(size
);
1880 newlines
= xmalloc(size
);
1886 int len
= linelen(patch
, size
);
1888 int added_blank_line
= 0;
1894 * "plen" is how much of the line we should use for
1895 * the actual patch data. Normally we just remove the
1896 * first character on the line, but if the line is
1897 * followed by "\ No newline", then we also remove the
1898 * last one (which is the newline, of course).
1901 if (len
< size
&& patch
[len
] == '\\')
1904 if (apply_in_reverse
) {
1907 else if (first
== '+')
1913 /* Newer GNU diff, empty context line */
1915 /* ... followed by '\No newline'; nothing */
1919 add_line_info(&preimage
, "\n", 1, LINE_COMMON
);
1920 add_line_info(&postimage
, "\n", 1, LINE_COMMON
);
1924 memcpy(old
, patch
+ 1, plen
);
1925 add_line_info(&preimage
, old
, plen
,
1926 (first
== ' ' ? LINE_COMMON
: 0));
1930 /* Fall-through for ' ' */
1932 /* --no-add does not add new lines */
1933 if (first
== '+' && no_add
)
1937 !whitespace_error
||
1938 ws_error_action
!= correct_ws_error
) {
1939 memcpy(new, patch
+ 1, plen
);
1943 added
= ws_fix_copy(new, patch
+ 1, plen
, ws_rule
, &applied_after_fixing_ws
);
1945 add_line_info(&postimage
, new, added
,
1946 (first
== '+' ? 0 : LINE_COMMON
));
1949 added
== 1 && new[-1] == '\n')
1950 added_blank_line
= 1;
1952 case '@': case '\\':
1953 /* Ignore it, we already handled it */
1956 if (apply_verbosely
)
1957 error("invalid start of line: '%c'", first
);
1960 if (added_blank_line
)
1961 new_blank_lines_at_end
++;
1963 new_blank_lines_at_end
= 0;
1967 if (inaccurate_eof
&&
1968 old
> oldlines
&& old
[-1] == '\n' &&
1969 new > newlines
&& new[-1] == '\n') {
1974 leading
= frag
->leading
;
1975 trailing
= frag
->trailing
;
1978 * A hunk to change lines at the beginning would begin with
1981 * And a hunk to add to an empty file would begin with
1984 * In other words, a hunk that is (frag->oldpos <= 1) with or
1985 * without leading context must match at the beginning.
1987 match_beginning
= frag
->oldpos
<= 1;
1990 * A hunk without trailing lines must match at the end.
1991 * However, we simply cannot tell if a hunk must match end
1992 * from the lack of trailing lines if the patch was generated
1993 * with unidiff without any context.
1995 match_end
= !unidiff_zero
&& !trailing
;
1997 pos
= frag
->newpos
? (frag
->newpos
- 1) : 0;
1998 preimage
.buf
= oldlines
;
1999 preimage
.len
= old
- oldlines
;
2000 postimage
.buf
= newlines
;
2001 postimage
.len
= new - newlines
;
2002 preimage
.line
= preimage
.line_allocated
;
2003 postimage
.line
= postimage
.line_allocated
;
2007 applied_pos
= find_pos(img
, &preimage
, &postimage
, pos
,
2008 ws_rule
, match_beginning
, match_end
);
2010 if (applied_pos
>= 0)
2013 /* Am I at my context limits? */
2014 if ((leading
<= p_context
) && (trailing
<= p_context
))
2016 if (match_beginning
|| match_end
) {
2017 match_beginning
= match_end
= 0;
2022 * Reduce the number of context lines; reduce both
2023 * leading and trailing if they are equal otherwise
2024 * just reduce the larger context.
2026 if (leading
>= trailing
) {
2027 remove_first_line(&preimage
);
2028 remove_first_line(&postimage
);
2032 if (trailing
> leading
) {
2033 remove_last_line(&preimage
);
2034 remove_last_line(&postimage
);
2039 if (applied_pos
>= 0) {
2040 if (ws_error_action
== correct_ws_error
&&
2041 new_blank_lines_at_end
&&
2042 postimage
.nr
+ applied_pos
== img
->nr
) {
2044 * If the patch application adds blank lines
2045 * at the end, and if the patch applies at the
2046 * end of the image, remove those added blank
2049 while (new_blank_lines_at_end
--)
2050 remove_last_line(&postimage
);
2054 * Warn if it was necessary to reduce the number
2057 if ((leading
!= frag
->leading
) ||
2058 (trailing
!= frag
->trailing
))
2059 fprintf(stderr
, "Context reduced to (%ld/%ld)"
2060 " to apply fragment at %d\n",
2061 leading
, trailing
, applied_pos
+1);
2062 update_image(img
, applied_pos
, &preimage
, &postimage
);
2064 if (apply_verbosely
)
2065 error("while searching for:\n%.*s",
2066 (int)(old
- oldlines
), oldlines
);
2071 free(preimage
.line_allocated
);
2072 free(postimage
.line_allocated
);
2074 return (applied_pos
< 0);
2077 static int apply_binary_fragment(struct image
*img
, struct patch
*patch
)
2079 struct fragment
*fragment
= patch
->fragments
;
2083 /* Binary patch is irreversible without the optional second hunk */
2084 if (apply_in_reverse
) {
2085 if (!fragment
->next
)
2086 return error("cannot reverse-apply a binary patch "
2087 "without the reverse hunk to '%s'",
2089 ? patch
->new_name
: patch
->old_name
);
2090 fragment
= fragment
->next
;
2092 switch (fragment
->binary_patch_method
) {
2093 case BINARY_DELTA_DEFLATED
:
2094 dst
= patch_delta(img
->buf
, img
->len
, fragment
->patch
,
2095 fragment
->size
, &len
);
2102 case BINARY_LITERAL_DEFLATED
:
2104 img
->len
= fragment
->size
;
2105 img
->buf
= xmalloc(img
->len
+1);
2106 memcpy(img
->buf
, fragment
->patch
, img
->len
);
2107 img
->buf
[img
->len
] = '\0';
2113 static int apply_binary(struct image
*img
, struct patch
*patch
)
2115 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
2116 unsigned char sha1
[20];
2119 * For safety, we require patch index line to contain
2120 * full 40-byte textual SHA1 for old and new, at least for now.
2122 if (strlen(patch
->old_sha1_prefix
) != 40 ||
2123 strlen(patch
->new_sha1_prefix
) != 40 ||
2124 get_sha1_hex(patch
->old_sha1_prefix
, sha1
) ||
2125 get_sha1_hex(patch
->new_sha1_prefix
, sha1
))
2126 return error("cannot apply binary patch to '%s' "
2127 "without full index line", name
);
2129 if (patch
->old_name
) {
2131 * See if the old one matches what the patch
2134 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
2135 if (strcmp(sha1_to_hex(sha1
), patch
->old_sha1_prefix
))
2136 return error("the patch applies to '%s' (%s), "
2137 "which does not match the "
2138 "current contents.",
2139 name
, sha1_to_hex(sha1
));
2142 /* Otherwise, the old one must be empty. */
2144 return error("the patch applies to an empty "
2145 "'%s' but it is not empty", name
);
2148 get_sha1_hex(patch
->new_sha1_prefix
, sha1
);
2149 if (is_null_sha1(sha1
)) {
2151 return 0; /* deletion patch */
2154 if (has_sha1_file(sha1
)) {
2155 /* We already have the postimage */
2156 enum object_type type
;
2160 result
= read_sha1_file(sha1
, &type
, &size
);
2162 return error("the necessary postimage %s for "
2163 "'%s' cannot be read",
2164 patch
->new_sha1_prefix
, name
);
2170 * We have verified buf matches the preimage;
2171 * apply the patch data to it, which is stored
2172 * in the patch->fragments->{patch,size}.
2174 if (apply_binary_fragment(img
, patch
))
2175 return error("binary patch does not apply to '%s'",
2178 /* verify that the result matches */
2179 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
2180 if (strcmp(sha1_to_hex(sha1
), patch
->new_sha1_prefix
))
2181 return error("binary patch to '%s' creates incorrect result (expecting %s, got %s)",
2182 name
, patch
->new_sha1_prefix
, sha1_to_hex(sha1
));
2188 static int apply_fragments(struct image
*img
, struct patch
*patch
)
2190 struct fragment
*frag
= patch
->fragments
;
2191 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
2192 unsigned ws_rule
= patch
->ws_rule
;
2193 unsigned inaccurate_eof
= patch
->inaccurate_eof
;
2195 if (patch
->is_binary
)
2196 return apply_binary(img
, patch
);
2199 if (apply_one_fragment(img
, frag
, inaccurate_eof
, ws_rule
)) {
2200 error("patch failed: %s:%ld", name
, frag
->oldpos
);
2201 if (!apply_with_reject
)
2210 static int read_file_or_gitlink(struct cache_entry
*ce
, struct strbuf
*buf
)
2215 if (S_ISGITLINK(ce
->ce_mode
)) {
2216 strbuf_grow(buf
, 100);
2217 strbuf_addf(buf
, "Subproject commit %s\n", sha1_to_hex(ce
->sha1
));
2219 enum object_type type
;
2223 result
= read_sha1_file(ce
->sha1
, &type
, &sz
);
2226 /* XXX read_sha1_file NUL-terminates */
2227 strbuf_attach(buf
, result
, sz
, sz
+ 1);
2232 static int apply_data(struct patch
*patch
, struct stat
*st
, struct cache_entry
*ce
)
2239 strbuf_init(&buf
, 0);
2241 if (read_file_or_gitlink(ce
, &buf
))
2242 return error("read of %s failed", patch
->old_name
);
2243 } else if (patch
->old_name
) {
2244 if (S_ISGITLINK(patch
->old_mode
)) {
2246 read_file_or_gitlink(ce
, &buf
);
2249 * There is no way to apply subproject
2250 * patch without looking at the index.
2252 patch
->fragments
= NULL
;
2255 if (read_old_data(st
, patch
->old_name
, &buf
))
2256 return error("read of %s failed", patch
->old_name
);
2260 img
= strbuf_detach(&buf
, &len
);
2261 prepare_image(&image
, img
, len
, !patch
->is_binary
);
2263 if (apply_fragments(&image
, patch
) < 0)
2264 return -1; /* note with --reject this succeeds. */
2265 patch
->result
= image
.buf
;
2266 patch
->resultsize
= image
.len
;
2267 free(image
.line_allocated
);
2269 if (0 < patch
->is_delete
&& patch
->resultsize
)
2270 return error("removal patch leaves file contents");
2275 static int check_to_create_blob(const char *new_name
, int ok_if_exists
)
2278 if (!lstat(new_name
, &nst
)) {
2279 if (S_ISDIR(nst
.st_mode
) || ok_if_exists
)
2282 * A leading component of new_name might be a symlink
2283 * that is going to be removed with this patch, but
2284 * still pointing at somewhere that has the path.
2285 * In such a case, path "new_name" does not exist as
2286 * far as git is concerned.
2288 if (has_symlink_leading_path(strlen(new_name
), new_name
))
2291 return error("%s: already exists in working directory", new_name
);
2293 else if ((errno
!= ENOENT
) && (errno
!= ENOTDIR
))
2294 return error("%s: %s", new_name
, strerror(errno
));
2298 static int verify_index_match(struct cache_entry
*ce
, struct stat
*st
)
2300 if (S_ISGITLINK(ce
->ce_mode
)) {
2301 if (!S_ISDIR(st
->st_mode
))
2305 return ce_match_stat(ce
, st
, CE_MATCH_IGNORE_VALID
);
2308 static int check_preimage(struct patch
*patch
, struct cache_entry
**ce
, struct stat
*st
)
2310 const char *old_name
= patch
->old_name
;
2312 unsigned st_mode
= 0;
2315 * Make sure that we do not have local modifications from the
2316 * index when we are looking at the index. Also make sure
2317 * we have the preimage file to be patched in the work tree,
2318 * unless --cached, which tells git to apply only in the index.
2323 assert(patch
->is_new
<= 0);
2325 stat_ret
= lstat(old_name
, st
);
2326 if (stat_ret
&& errno
!= ENOENT
)
2327 return error("%s: %s", old_name
, strerror(errno
));
2330 int pos
= cache_name_pos(old_name
, strlen(old_name
));
2332 if (patch
->is_new
< 0)
2334 return error("%s: does not exist in index", old_name
);
2336 *ce
= active_cache
[pos
];
2338 struct checkout costate
;
2340 costate
.base_dir
= "";
2341 costate
.base_dir_len
= 0;
2344 costate
.not_new
= 0;
2345 costate
.refresh_cache
= 1;
2346 if (checkout_entry(*ce
, &costate
, NULL
) ||
2347 lstat(old_name
, st
))
2350 if (!cached
&& verify_index_match(*ce
, st
))
2351 return error("%s: does not match index", old_name
);
2353 st_mode
= (*ce
)->ce_mode
;
2354 } else if (stat_ret
< 0) {
2355 if (patch
->is_new
< 0)
2357 return error("%s: %s", old_name
, strerror(errno
));
2361 st_mode
= ce_mode_from_stat(*ce
, st
->st_mode
);
2363 if (patch
->is_new
< 0)
2365 if (!patch
->old_mode
)
2366 patch
->old_mode
= st_mode
;
2367 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
2368 return error("%s: wrong type", old_name
);
2369 if (st_mode
!= patch
->old_mode
)
2370 fprintf(stderr
, "warning: %s has type %o, expected %o\n",
2371 old_name
, st_mode
, patch
->old_mode
);
2376 patch
->is_delete
= 0;
2377 patch
->old_name
= NULL
;
2381 static int check_patch(struct patch
*patch
, struct patch
*prev_patch
)
2384 const char *old_name
= patch
->old_name
;
2385 const char *new_name
= patch
->new_name
;
2386 const char *name
= old_name
? old_name
: new_name
;
2387 struct cache_entry
*ce
= NULL
;
2391 patch
->rejected
= 1; /* we will drop this after we succeed */
2393 status
= check_preimage(patch
, &ce
, &st
);
2396 old_name
= patch
->old_name
;
2398 if (new_name
&& prev_patch
&& 0 < prev_patch
->is_delete
&&
2399 !strcmp(prev_patch
->old_name
, new_name
))
2401 * A type-change diff is always split into a patch to
2402 * delete old, immediately followed by a patch to
2403 * create new (see diff.c::run_diff()); in such a case
2404 * it is Ok that the entry to be deleted by the
2405 * previous patch is still in the working tree and in
2413 ((0 < patch
->is_new
) | (0 < patch
->is_rename
) | patch
->is_copy
)) {
2415 cache_name_pos(new_name
, strlen(new_name
)) >= 0 &&
2417 return error("%s: already exists in index", new_name
);
2419 int err
= check_to_create_blob(new_name
, ok_if_exists
);
2423 if (!patch
->new_mode
) {
2424 if (0 < patch
->is_new
)
2425 patch
->new_mode
= S_IFREG
| 0644;
2427 patch
->new_mode
= patch
->old_mode
;
2431 if (new_name
&& old_name
) {
2432 int same
= !strcmp(old_name
, new_name
);
2433 if (!patch
->new_mode
)
2434 patch
->new_mode
= patch
->old_mode
;
2435 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
)
2436 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
2437 patch
->new_mode
, new_name
, patch
->old_mode
,
2438 same
? "" : " of ", same
? "" : old_name
);
2441 if (apply_data(patch
, &st
, ce
) < 0)
2442 return error("%s: patch does not apply", name
);
2443 patch
->rejected
= 0;
2447 static int check_patch_list(struct patch
*patch
)
2449 struct patch
*prev_patch
= NULL
;
2452 for (prev_patch
= NULL
; patch
; patch
= patch
->next
) {
2453 if (apply_verbosely
)
2454 say_patch_name(stderr
,
2455 "Checking patch ", patch
, "...\n");
2456 err
|= check_patch(patch
, prev_patch
);
2462 /* This function tries to read the sha1 from the current index */
2463 static int get_current_sha1(const char *path
, unsigned char *sha1
)
2467 if (read_cache() < 0)
2469 pos
= cache_name_pos(path
, strlen(path
));
2472 hashcpy(sha1
, active_cache
[pos
]->sha1
);
2476 /* Build an index that contains the just the files needed for a 3way merge */
2477 static void build_fake_ancestor(struct patch
*list
, const char *filename
)
2479 struct patch
*patch
;
2480 struct index_state result
= { 0 };
2483 /* Once we start supporting the reverse patch, it may be
2484 * worth showing the new sha1 prefix, but until then...
2486 for (patch
= list
; patch
; patch
= patch
->next
) {
2487 const unsigned char *sha1_ptr
;
2488 unsigned char sha1
[20];
2489 struct cache_entry
*ce
;
2492 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
2493 if (0 < patch
->is_new
)
2495 else if (get_sha1(patch
->old_sha1_prefix
, sha1
))
2496 /* git diff has no index line for mode/type changes */
2497 if (!patch
->lines_added
&& !patch
->lines_deleted
) {
2498 if (get_current_sha1(patch
->new_name
, sha1
) ||
2499 get_current_sha1(patch
->old_name
, sha1
))
2500 die("mode change for %s, which is not "
2501 "in current HEAD", name
);
2504 die("sha1 information is lacking or useless "
2509 ce
= make_cache_entry(patch
->old_mode
, sha1_ptr
, name
, 0, 0);
2510 if (add_index_entry(&result
, ce
, ADD_CACHE_OK_TO_ADD
))
2511 die ("Could not add %s to temporary index", name
);
2514 fd
= open(filename
, O_WRONLY
| O_CREAT
, 0666);
2515 if (fd
< 0 || write_index(&result
, fd
) || close(fd
))
2516 die ("Could not write temporary index to %s", filename
);
2518 discard_index(&result
);
2521 static void stat_patch_list(struct patch
*patch
)
2523 int files
, adds
, dels
;
2525 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
2527 adds
+= patch
->lines_added
;
2528 dels
+= patch
->lines_deleted
;
2532 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files
, adds
, dels
);
2535 static void numstat_patch_list(struct patch
*patch
)
2537 for ( ; patch
; patch
= patch
->next
) {
2539 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
2540 if (patch
->is_binary
)
2543 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
2544 write_name_quoted(name
, stdout
, line_termination
);
2548 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
2551 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
2553 printf(" %s %s\n", newdelete
, name
);
2556 static void show_mode_change(struct patch
*p
, int show_name
)
2558 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
2560 printf(" mode change %06o => %06o %s\n",
2561 p
->old_mode
, p
->new_mode
, p
->new_name
);
2563 printf(" mode change %06o => %06o\n",
2564 p
->old_mode
, p
->new_mode
);
2568 static void show_rename_copy(struct patch
*p
)
2570 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
2571 const char *old
, *new;
2573 /* Find common prefix */
2577 const char *slash_old
, *slash_new
;
2578 slash_old
= strchr(old
, '/');
2579 slash_new
= strchr(new, '/');
2582 slash_old
- old
!= slash_new
- new ||
2583 memcmp(old
, new, slash_new
- new))
2585 old
= slash_old
+ 1;
2586 new = slash_new
+ 1;
2588 /* p->old_name thru old is the common prefix, and old and new
2589 * through the end of names are renames
2591 if (old
!= p
->old_name
)
2592 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
2593 (int)(old
- p
->old_name
), p
->old_name
,
2594 old
, new, p
->score
);
2596 printf(" %s %s => %s (%d%%)\n", renamecopy
,
2597 p
->old_name
, p
->new_name
, p
->score
);
2598 show_mode_change(p
, 0);
2601 static void summary_patch_list(struct patch
*patch
)
2605 for (p
= patch
; p
; p
= p
->next
) {
2607 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
2608 else if (p
->is_delete
)
2609 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
2611 if (p
->is_rename
|| p
->is_copy
)
2612 show_rename_copy(p
);
2615 printf(" rewrite %s (%d%%)\n",
2616 p
->new_name
, p
->score
);
2617 show_mode_change(p
, 0);
2620 show_mode_change(p
, 1);
2626 static void patch_stats(struct patch
*patch
)
2628 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
2630 if (lines
> max_change
)
2632 if (patch
->old_name
) {
2633 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
2635 len
= strlen(patch
->old_name
);
2639 if (patch
->new_name
) {
2640 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
2642 len
= strlen(patch
->new_name
);
2648 static void remove_file(struct patch
*patch
, int rmdir_empty
)
2651 if (remove_file_from_cache(patch
->old_name
) < 0)
2652 die("unable to remove %s from index", patch
->old_name
);
2655 if (S_ISGITLINK(patch
->old_mode
)) {
2656 if (rmdir(patch
->old_name
))
2657 warning("unable to remove submodule %s",
2659 } else if (!unlink(patch
->old_name
) && rmdir_empty
) {
2660 char *name
= xstrdup(patch
->old_name
);
2661 char *end
= strrchr(name
, '/');
2666 end
= strrchr(name
, '/');
2673 static void add_index_file(const char *path
, unsigned mode
, void *buf
, unsigned long size
)
2676 struct cache_entry
*ce
;
2677 int namelen
= strlen(path
);
2678 unsigned ce_size
= cache_entry_size(namelen
);
2683 ce
= xcalloc(1, ce_size
);
2684 memcpy(ce
->name
, path
, namelen
);
2685 ce
->ce_mode
= create_ce_mode(mode
);
2686 ce
->ce_flags
= namelen
;
2687 if (S_ISGITLINK(mode
)) {
2688 const char *s
= buf
;
2690 if (get_sha1_hex(s
+ strlen("Subproject commit "), ce
->sha1
))
2691 die("corrupt patch for subproject %s", path
);
2694 if (lstat(path
, &st
) < 0)
2695 die("unable to stat newly created file %s",
2697 fill_stat_cache_info(ce
, &st
);
2699 if (write_sha1_file(buf
, size
, blob_type
, ce
->sha1
) < 0)
2700 die("unable to create backing store for newly created file %s", path
);
2702 if (add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
) < 0)
2703 die("unable to add cache entry for %s", path
);
2706 static int try_create_file(const char *path
, unsigned int mode
, const char *buf
, unsigned long size
)
2711 if (S_ISGITLINK(mode
)) {
2713 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
))
2715 return mkdir(path
, 0777);
2718 if (has_symlinks
&& S_ISLNK(mode
))
2719 /* Although buf:size is counted string, it also is NUL
2722 return symlink(buf
, path
);
2724 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
2728 strbuf_init(&nbuf
, 0);
2729 if (convert_to_working_tree(path
, buf
, size
, &nbuf
)) {
2733 write_or_die(fd
, buf
, size
);
2734 strbuf_release(&nbuf
);
2737 die("closing file %s: %s", path
, strerror(errno
));
2742 * We optimistically assume that the directories exist,
2743 * which is true 99% of the time anyway. If they don't,
2744 * we create them and try again.
2746 static void create_one_file(char *path
, unsigned mode
, const char *buf
, unsigned long size
)
2750 if (!try_create_file(path
, mode
, buf
, size
))
2753 if (errno
== ENOENT
) {
2754 if (safe_create_leading_directories(path
))
2756 if (!try_create_file(path
, mode
, buf
, size
))
2760 if (errno
== EEXIST
|| errno
== EACCES
) {
2761 /* We may be trying to create a file where a directory
2765 if (!lstat(path
, &st
) && (!S_ISDIR(st
.st_mode
) || !rmdir(path
)))
2769 if (errno
== EEXIST
) {
2770 unsigned int nr
= getpid();
2773 const char *newpath
;
2774 newpath
= mkpath("%s~%u", path
, nr
);
2775 if (!try_create_file(newpath
, mode
, buf
, size
)) {
2776 if (!rename(newpath
, path
))
2781 if (errno
!= EEXIST
)
2786 die("unable to write file %s mode %o", path
, mode
);
2789 static void create_file(struct patch
*patch
)
2791 char *path
= patch
->new_name
;
2792 unsigned mode
= patch
->new_mode
;
2793 unsigned long size
= patch
->resultsize
;
2794 char *buf
= patch
->result
;
2797 mode
= S_IFREG
| 0644;
2798 create_one_file(path
, mode
, buf
, size
);
2799 add_index_file(path
, mode
, buf
, size
);
2802 /* phase zero is to remove, phase one is to create */
2803 static void write_out_one_result(struct patch
*patch
, int phase
)
2805 if (patch
->is_delete
> 0) {
2807 remove_file(patch
, 1);
2810 if (patch
->is_new
> 0 || patch
->is_copy
) {
2816 * Rename or modification boils down to the same
2817 * thing: remove the old, write the new
2820 remove_file(patch
, patch
->is_rename
);
2825 static int write_out_one_reject(struct patch
*patch
)
2828 char namebuf
[PATH_MAX
];
2829 struct fragment
*frag
;
2832 for (cnt
= 0, frag
= patch
->fragments
; frag
; frag
= frag
->next
) {
2833 if (!frag
->rejected
)
2839 if (apply_verbosely
)
2840 say_patch_name(stderr
,
2841 "Applied patch ", patch
, " cleanly.\n");
2845 /* This should not happen, because a removal patch that leaves
2846 * contents are marked "rejected" at the patch level.
2848 if (!patch
->new_name
)
2849 die("internal error");
2851 /* Say this even without --verbose */
2852 say_patch_name(stderr
, "Applying patch ", patch
, " with");
2853 fprintf(stderr
, " %d rejects...\n", cnt
);
2855 cnt
= strlen(patch
->new_name
);
2856 if (ARRAY_SIZE(namebuf
) <= cnt
+ 5) {
2857 cnt
= ARRAY_SIZE(namebuf
) - 5;
2859 "warning: truncating .rej filename to %.*s.rej",
2860 cnt
- 1, patch
->new_name
);
2862 memcpy(namebuf
, patch
->new_name
, cnt
);
2863 memcpy(namebuf
+ cnt
, ".rej", 5);
2865 rej
= fopen(namebuf
, "w");
2867 return error("cannot open %s: %s", namebuf
, strerror(errno
));
2869 /* Normal git tools never deal with .rej, so do not pretend
2870 * this is a git patch by saying --git nor give extended
2871 * headers. While at it, maybe please "kompare" that wants
2872 * the trailing TAB and some garbage at the end of line ;-).
2874 fprintf(rej
, "diff a/%s b/%s\t(rejected hunks)\n",
2875 patch
->new_name
, patch
->new_name
);
2876 for (cnt
= 1, frag
= patch
->fragments
;
2878 cnt
++, frag
= frag
->next
) {
2879 if (!frag
->rejected
) {
2880 fprintf(stderr
, "Hunk #%d applied cleanly.\n", cnt
);
2883 fprintf(stderr
, "Rejected hunk #%d.\n", cnt
);
2884 fprintf(rej
, "%.*s", frag
->size
, frag
->patch
);
2885 if (frag
->patch
[frag
->size
-1] != '\n')
2892 static int write_out_results(struct patch
*list
, int skipped_patch
)
2898 if (!list
&& !skipped_patch
)
2899 return error("No changes");
2901 for (phase
= 0; phase
< 2; phase
++) {
2907 write_out_one_result(l
, phase
);
2908 if (phase
== 1 && write_out_one_reject(l
))
2917 static struct lock_file lock_file
;
2919 static struct excludes
{
2920 struct excludes
*next
;
2924 static int use_patch(struct patch
*p
)
2926 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
2927 struct excludes
*x
= excludes
;
2929 if (fnmatch(x
->path
, pathname
, 0) == 0)
2933 if (0 < prefix_length
) {
2934 int pathlen
= strlen(pathname
);
2935 if (pathlen
<= prefix_length
||
2936 memcmp(prefix
, pathname
, prefix_length
))
2942 static void prefix_one(char **name
)
2944 char *old_name
= *name
;
2947 *name
= xstrdup(prefix_filename(prefix
, prefix_length
, *name
));
2951 static void prefix_patches(struct patch
*p
)
2953 if (!prefix
|| p
->is_toplevel_relative
)
2955 for ( ; p
; p
= p
->next
) {
2956 if (p
->new_name
== p
->old_name
) {
2957 char *prefixed
= p
->new_name
;
2958 prefix_one(&prefixed
);
2959 p
->new_name
= p
->old_name
= prefixed
;
2962 prefix_one(&p
->new_name
);
2963 prefix_one(&p
->old_name
);
2968 #define INACCURATE_EOF (1<<0)
2969 #define RECOUNT (1<<1)
2971 static int apply_patch(int fd
, const char *filename
, int options
)
2975 struct patch
*list
= NULL
, **listp
= &list
;
2976 int skipped_patch
= 0;
2978 strbuf_init(&buf
, 0);
2979 patch_input_file
= filename
;
2980 read_patch_file(&buf
, fd
);
2982 while (offset
< buf
.len
) {
2983 struct patch
*patch
;
2986 patch
= xcalloc(1, sizeof(*patch
));
2987 patch
->inaccurate_eof
= !!(options
& INACCURATE_EOF
);
2988 patch
->recount
= !!(options
& RECOUNT
);
2989 nr
= parse_chunk(buf
.buf
+ offset
, buf
.len
- offset
, patch
);
2992 if (apply_in_reverse
)
2993 reverse_patches(patch
);
2995 prefix_patches(patch
);
2996 if (use_patch(patch
)) {
2999 listp
= &patch
->next
;
3002 /* perhaps free it a bit better? */
3009 if (whitespace_error
&& (ws_error_action
== die_on_ws_error
))
3012 update_index
= check_index
&& apply
;
3013 if (update_index
&& newfd
< 0)
3014 newfd
= hold_locked_index(&lock_file
, 1);
3017 if (read_cache() < 0)
3018 die("unable to read index file");
3021 if ((check
|| apply
) &&
3022 check_patch_list(list
) < 0 &&
3026 if (apply
&& write_out_results(list
, skipped_patch
))
3030 build_fake_ancestor(list
, fake_ancestor
);
3033 stat_patch_list(list
);
3036 numstat_patch_list(list
);
3039 summary_patch_list(list
);
3041 strbuf_release(&buf
);
3045 static int git_apply_config(const char *var
, const char *value
, void *cb
)
3047 if (!strcmp(var
, "apply.whitespace"))
3048 return git_config_string(&apply_default_whitespace
, var
, value
);
3049 return git_default_config(var
, value
, cb
);
3053 int cmd_apply(int argc
, const char **argv
, const char *unused_prefix
)
3061 const char *whitespace_option
= NULL
;
3063 prefix
= setup_git_directory_gently(&is_not_gitdir
);
3064 prefix_length
= prefix
? strlen(prefix
) : 0;
3065 git_config(git_apply_config
, NULL
);
3066 if (apply_default_whitespace
)
3067 parse_whitespace_option(apply_default_whitespace
);
3069 for (i
= 1; i
< argc
; i
++) {
3070 const char *arg
= argv
[i
];
3074 if (!strcmp(arg
, "-")) {
3075 errs
|= apply_patch(0, "<stdin>", options
);
3079 if (!prefixcmp(arg
, "--exclude=")) {
3080 struct excludes
*x
= xmalloc(sizeof(*x
));
3086 if (!prefixcmp(arg
, "-p")) {
3087 p_value
= atoi(arg
+ 2);
3091 if (!strcmp(arg
, "--no-add")) {
3095 if (!strcmp(arg
, "--stat")) {
3100 if (!strcmp(arg
, "--allow-binary-replacement") ||
3101 !strcmp(arg
, "--binary")) {
3102 continue; /* now no-op */
3104 if (!strcmp(arg
, "--numstat")) {
3109 if (!strcmp(arg
, "--summary")) {
3114 if (!strcmp(arg
, "--check")) {
3119 if (!strcmp(arg
, "--index")) {
3121 die("--index outside a repository");
3125 if (!strcmp(arg
, "--cached")) {
3127 die("--cached outside a repository");
3132 if (!strcmp(arg
, "--apply")) {
3136 if (!strcmp(arg
, "--build-fake-ancestor")) {
3139 die ("need a filename");
3140 fake_ancestor
= argv
[i
];
3143 if (!strcmp(arg
, "-z")) {
3144 line_termination
= 0;
3147 if (!prefixcmp(arg
, "-C")) {
3148 p_context
= strtoul(arg
+ 2, &end
, 0);
3150 die("unrecognized context count '%s'", arg
+ 2);
3153 if (!prefixcmp(arg
, "--whitespace=")) {
3154 whitespace_option
= arg
+ 13;
3155 parse_whitespace_option(arg
+ 13);
3158 if (!strcmp(arg
, "-R") || !strcmp(arg
, "--reverse")) {
3159 apply_in_reverse
= 1;
3162 if (!strcmp(arg
, "--unidiff-zero")) {
3166 if (!strcmp(arg
, "--reject")) {
3167 apply
= apply_with_reject
= apply_verbosely
= 1;
3170 if (!strcmp(arg
, "-v") || !strcmp(arg
, "--verbose")) {
3171 apply_verbosely
= 1;
3174 if (!strcmp(arg
, "--inaccurate-eof")) {
3175 options
|= INACCURATE_EOF
;
3178 if (!strcmp(arg
, "--recount")) {
3182 if (0 < prefix_length
)
3183 arg
= prefix_filename(prefix
, prefix_length
, arg
);
3185 fd
= open(arg
, O_RDONLY
);
3187 die("can't open patch '%s': %s", arg
, strerror(errno
));
3189 set_default_whitespace_mode(whitespace_option
);
3190 errs
|= apply_patch(fd
, arg
, options
);
3193 set_default_whitespace_mode(whitespace_option
);
3195 errs
|= apply_patch(0, "<stdin>", options
);
3196 if (whitespace_error
) {
3197 if (squelch_whitespace_errors
&&
3198 squelch_whitespace_errors
< whitespace_error
) {
3200 whitespace_error
- squelch_whitespace_errors
;
3201 fprintf(stderr
, "warning: squelched %d "
3202 "whitespace error%s\n",
3204 squelched
== 1 ? "" : "s");
3206 if (ws_error_action
== die_on_ws_error
)
3207 die("%d line%s add%s whitespace errors.",
3209 whitespace_error
== 1 ? "" : "s",
3210 whitespace_error
== 1 ? "s" : "");
3211 if (applied_after_fixing_ws
&& apply
)
3212 fprintf(stderr
, "warning: %d line%s applied after"
3213 " fixing whitespace errors.\n",
3214 applied_after_fixing_ws
,
3215 applied_after_fixing_ws
== 1 ? "" : "s");
3216 else if (whitespace_error
)
3217 fprintf(stderr
, "warning: %d line%s add%s whitespace errors.\n",
3219 whitespace_error
== 1 ? "" : "s",
3220 whitespace_error
== 1 ? "s" : "");
3224 if (write_cache(newfd
, active_cache
, active_nr
) ||
3225 commit_locked_index(&lock_file
))
3226 die("Unable to write new index file");