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
;
157 struct fragment
*next
;
161 * When dealing with a binary patch, we reuse "leading" field
162 * to store the type of the binary hunk, either deflated "delta"
163 * or deflated "literal".
165 #define binary_patch_method leading
166 #define BINARY_DELTA_DEFLATED 1
167 #define BINARY_LITERAL_DEFLATED 2
170 * This represents a "patch" to a file, both metainfo changes
171 * such as creation/deletion, filemode and content changes represented
172 * as a series of fragments.
175 char *new_name
, *old_name
, *def_name
;
176 unsigned int old_mode
, new_mode
;
177 int is_new
, is_delete
; /* -1 = unknown, 0 = false, 1 = true */
180 unsigned long deflate_origlen
;
181 int lines_added
, lines_deleted
;
183 unsigned int is_toplevel_relative
:1;
184 unsigned int inaccurate_eof
:1;
185 unsigned int is_binary
:1;
186 unsigned int is_copy
:1;
187 unsigned int is_rename
:1;
188 unsigned int recount
:1;
189 struct fragment
*fragments
;
192 char old_sha1_prefix
[41];
193 char new_sha1_prefix
[41];
198 * A line in a file, len-bytes long (includes the terminating LF,
199 * except for an incomplete line at the end if the file ends with
200 * one), and its contents hashes to 'hash'.
206 #define LINE_COMMON 1
210 * This represents a "file", which is an array of "lines".
217 struct line
*line_allocated
;
222 * Records filenames that have been touched, in order to handle
223 * the case where more than one patches touch the same file.
226 static struct string_list fn_table
;
228 static uint32_t hash_line(const char *cp
, size_t len
)
232 for (i
= 0, h
= 0; i
< len
; i
++) {
233 if (!isspace(cp
[i
])) {
234 h
= h
* 3 + (cp
[i
] & 0xff);
241 * Compare lines s1 of length n1 and s2 of length n2, ignoring
242 * whitespace difference. Returns 1 if they match, 0 otherwise
244 static int fuzzy_matchlines(const char *s1
, size_t n1
,
245 const char *s2
, size_t n2
)
247 const char *last1
= s1
+ n1
- 1;
248 const char *last2
= s2
+ n2
- 1;
251 if (n1
< 0 || n2
< 0)
254 /* ignore line endings */
255 while ((*last1
== '\r') || (*last1
== '\n'))
257 while ((*last2
== '\r') || (*last2
== '\n'))
260 /* skip leading whitespace */
261 while (isspace(*s1
) && (s1
<= last1
))
263 while (isspace(*s2
) && (s2
<= last2
))
265 /* early return if both lines are empty */
266 if ((s1
> last1
) && (s2
> last2
))
269 result
= *s1
++ - *s2
++;
271 * Skip whitespace inside. We check for whitespace on
272 * both buffers because we don't want "a b" to match
275 if (isspace(*s1
) && isspace(*s2
)) {
276 while (isspace(*s1
) && s1
<= last1
)
278 while (isspace(*s2
) && s2
<= last2
)
282 * If we reached the end on one side only,
286 ((s2
> last2
) && (s1
<= last1
)) ||
287 ((s1
> last1
) && (s2
<= last2
)))
289 if ((s1
> last1
) && (s2
> last2
))
296 static void add_line_info(struct image
*img
, const char *bol
, size_t len
, unsigned flag
)
298 ALLOC_GROW(img
->line_allocated
, img
->nr
+ 1, img
->alloc
);
299 img
->line_allocated
[img
->nr
].len
= len
;
300 img
->line_allocated
[img
->nr
].hash
= hash_line(bol
, len
);
301 img
->line_allocated
[img
->nr
].flag
= flag
;
305 static void prepare_image(struct image
*image
, char *buf
, size_t len
,
306 int prepare_linetable
)
310 memset(image
, 0, sizeof(*image
));
314 if (!prepare_linetable
)
317 ep
= image
->buf
+ image
->len
;
321 for (next
= cp
; next
< ep
&& *next
!= '\n'; next
++)
325 add_line_info(image
, cp
, next
- cp
, 0);
328 image
->line
= image
->line_allocated
;
331 static void clear_image(struct image
*image
)
338 static void say_patch_name(FILE *output
, const char *pre
,
339 struct patch
*patch
, const char *post
)
342 if (patch
->old_name
&& patch
->new_name
&&
343 strcmp(patch
->old_name
, patch
->new_name
)) {
344 quote_c_style(patch
->old_name
, NULL
, output
, 0);
345 fputs(" => ", output
);
346 quote_c_style(patch
->new_name
, NULL
, output
, 0);
348 const char *n
= patch
->new_name
;
351 quote_c_style(n
, NULL
, output
, 0);
356 #define CHUNKSIZE (8192)
359 static void read_patch_file(struct strbuf
*sb
, int fd
)
361 if (strbuf_read(sb
, fd
, 0) < 0)
362 die_errno("git apply: failed to read");
365 * Make sure that we have some slop in the buffer
366 * so that we can do speculative "memcmp" etc, and
367 * see to it that it is NUL-filled.
369 strbuf_grow(sb
, SLOP
);
370 memset(sb
->buf
+ sb
->len
, 0, SLOP
);
373 static unsigned long linelen(const char *buffer
, unsigned long size
)
375 unsigned long len
= 0;
378 if (*buffer
++ == '\n')
384 static int is_dev_null(const char *str
)
386 return !memcmp("/dev/null", str
, 9) && isspace(str
[9]);
392 static int name_terminate(const char *name
, int namelen
, int c
, int terminate
)
394 if (c
== ' ' && !(terminate
& TERM_SPACE
))
396 if (c
== '\t' && !(terminate
& TERM_TAB
))
402 /* remove double slashes to make --index work with such filenames */
403 static char *squash_slash(char *name
)
411 if ((name
[j
++] = name
[i
++]) == '/')
412 while (name
[i
] == '/')
419 static char *find_name(const char *line
, char *def
, int p_value
, int terminate
)
422 const char *start
= NULL
;
428 struct strbuf name
= STRBUF_INIT
;
431 * Proposed "new-style" GNU patch/diff format; see
432 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
434 if (!unquote_c_style(&name
, line
, NULL
)) {
437 for (cp
= name
.buf
; p_value
; p_value
--) {
438 cp
= strchr(cp
, '/');
444 /* name can later be freed, so we need
445 * to memmove, not just return cp
447 strbuf_remove(&name
, 0, cp
- name
.buf
);
450 strbuf_insert(&name
, 0, root
, root_len
);
451 return squash_slash(strbuf_detach(&name
, NULL
));
454 strbuf_release(&name
);
463 if (name_terminate(start
, line
-start
, c
, terminate
))
467 if (c
== '/' && !--p_value
)
471 return squash_slash(def
);
474 return squash_slash(def
);
477 * Generally we prefer the shorter name, especially
478 * if the other one is just a variation of that with
479 * something else tacked on to the end (ie "file.orig"
483 int deflen
= strlen(def
);
484 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
485 return squash_slash(def
);
490 char *ret
= xmalloc(root_len
+ len
+ 1);
492 memcpy(ret
+ root_len
, start
, len
);
493 ret
[root_len
+ len
] = '\0';
494 return squash_slash(ret
);
497 return squash_slash(xmemdupz(start
, len
));
500 static int count_slashes(const char *cp
)
512 * Given the string after "--- " or "+++ ", guess the appropriate
513 * p_value for the given patch.
515 static int guess_p_value(const char *nameline
)
520 if (is_dev_null(nameline
))
522 name
= find_name(nameline
, NULL
, 0, TERM_SPACE
| TERM_TAB
);
525 cp
= strchr(name
, '/');
530 * Does it begin with "a/$our-prefix" and such? Then this is
531 * very likely to apply to our directory.
533 if (!strncmp(name
, prefix
, prefix_length
))
534 val
= count_slashes(prefix
);
537 if (!strncmp(cp
, prefix
, prefix_length
))
538 val
= count_slashes(prefix
) + 1;
546 * Does the ---/+++ line has the POSIX timestamp after the last HT?
547 * GNU diff puts epoch there to signal a creation/deletion event. Is
548 * this such a timestamp?
550 static int has_epoch_timestamp(const char *nameline
)
553 * We are only interested in epoch timestamp; any non-zero
554 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
555 * For the same reason, the date must be either 1969-12-31 or
556 * 1970-01-01, and the seconds part must be "00".
558 const char stamp_regexp
[] =
559 "^(1969-12-31|1970-01-01)"
561 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
563 "([-+][0-2][0-9][0-5][0-9])\n";
564 const char *timestamp
= NULL
, *cp
;
565 static regex_t
*stamp
;
571 for (cp
= nameline
; *cp
!= '\n'; cp
++) {
578 stamp
= xmalloc(sizeof(*stamp
));
579 if (regcomp(stamp
, stamp_regexp
, REG_EXTENDED
)) {
580 warning("Cannot prepare timestamp regexp %s",
586 status
= regexec(stamp
, timestamp
, ARRAY_SIZE(m
), m
, 0);
588 if (status
!= REG_NOMATCH
)
589 warning("regexec returned %d for input: %s",
594 zoneoffset
= strtol(timestamp
+ m
[3].rm_so
+ 1, NULL
, 10);
595 zoneoffset
= (zoneoffset
/ 100) * 60 + (zoneoffset
% 100);
596 if (timestamp
[m
[3].rm_so
] == '-')
597 zoneoffset
= -zoneoffset
;
600 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
601 * (west of GMT) or 1970-01-01 (east of GMT)
603 if ((zoneoffset
< 0 && memcmp(timestamp
, "1969-12-31", 10)) ||
604 (0 <= zoneoffset
&& memcmp(timestamp
, "1970-01-01", 10)))
607 hourminute
= (strtol(timestamp
+ 11, NULL
, 10) * 60 +
608 strtol(timestamp
+ 14, NULL
, 10) -
611 return ((zoneoffset
< 0 && hourminute
== 1440) ||
612 (0 <= zoneoffset
&& !hourminute
));
616 * Get the name etc info from the ---/+++ lines of a traditional patch header
618 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
619 * files, we can happily check the index for a match, but for creating a
620 * new file we should try to match whatever "patch" does. I have no idea.
622 static void parse_traditional_patch(const char *first
, const char *second
, struct patch
*patch
)
626 first
+= 4; /* skip "--- " */
627 second
+= 4; /* skip "+++ " */
628 if (!p_value_known
) {
630 p
= guess_p_value(first
);
631 q
= guess_p_value(second
);
633 if (0 <= p
&& p
== q
) {
638 if (is_dev_null(first
)) {
640 patch
->is_delete
= 0;
641 name
= find_name(second
, NULL
, p_value
, TERM_SPACE
| TERM_TAB
);
642 patch
->new_name
= name
;
643 } else if (is_dev_null(second
)) {
645 patch
->is_delete
= 1;
646 name
= find_name(first
, NULL
, p_value
, TERM_SPACE
| TERM_TAB
);
647 patch
->old_name
= name
;
649 name
= find_name(first
, NULL
, p_value
, TERM_SPACE
| TERM_TAB
);
650 name
= find_name(second
, name
, p_value
, TERM_SPACE
| TERM_TAB
);
651 if (has_epoch_timestamp(first
)) {
653 patch
->is_delete
= 0;
654 patch
->new_name
= name
;
655 } else if (has_epoch_timestamp(second
)) {
657 patch
->is_delete
= 1;
658 patch
->old_name
= name
;
660 patch
->old_name
= patch
->new_name
= name
;
664 die("unable to find filename in patch at line %d", linenr
);
667 static int gitdiff_hdrend(const char *line
, struct patch
*patch
)
673 * We're anal about diff header consistency, to make
674 * sure that we don't end up having strange ambiguous
675 * patches floating around.
677 * As a result, gitdiff_{old|new}name() will check
678 * their names against any previous information, just
681 static char *gitdiff_verify_name(const char *line
, int isnull
, char *orig_name
, const char *oldnew
)
683 if (!orig_name
&& !isnull
)
684 return find_name(line
, NULL
, p_value
, TERM_TAB
);
693 die("git apply: bad git-diff - expected /dev/null, got %s on line %d", name
, linenr
);
694 another
= find_name(line
, NULL
, p_value
, TERM_TAB
);
695 if (!another
|| memcmp(another
, name
, len
+ 1))
696 die("git apply: bad git-diff - inconsistent %s filename on line %d", oldnew
, linenr
);
701 /* expect "/dev/null" */
702 if (memcmp("/dev/null", line
, 9) || line
[9] != '\n')
703 die("git apply: bad git-diff - expected /dev/null on line %d", linenr
);
708 static int gitdiff_oldname(const char *line
, struct patch
*patch
)
710 patch
->old_name
= gitdiff_verify_name(line
, patch
->is_new
, patch
->old_name
, "old");
714 static int gitdiff_newname(const char *line
, struct patch
*patch
)
716 patch
->new_name
= gitdiff_verify_name(line
, patch
->is_delete
, patch
->new_name
, "new");
720 static int gitdiff_oldmode(const char *line
, struct patch
*patch
)
722 patch
->old_mode
= strtoul(line
, NULL
, 8);
726 static int gitdiff_newmode(const char *line
, struct patch
*patch
)
728 patch
->new_mode
= strtoul(line
, NULL
, 8);
732 static int gitdiff_delete(const char *line
, struct patch
*patch
)
734 patch
->is_delete
= 1;
735 patch
->old_name
= patch
->def_name
;
736 return gitdiff_oldmode(line
, patch
);
739 static int gitdiff_newfile(const char *line
, struct patch
*patch
)
742 patch
->new_name
= patch
->def_name
;
743 return gitdiff_newmode(line
, patch
);
746 static int gitdiff_copysrc(const char *line
, struct patch
*patch
)
749 patch
->old_name
= find_name(line
, NULL
, 0, 0);
753 static int gitdiff_copydst(const char *line
, struct patch
*patch
)
756 patch
->new_name
= find_name(line
, NULL
, 0, 0);
760 static int gitdiff_renamesrc(const char *line
, struct patch
*patch
)
762 patch
->is_rename
= 1;
763 patch
->old_name
= find_name(line
, NULL
, 0, 0);
767 static int gitdiff_renamedst(const char *line
, struct patch
*patch
)
769 patch
->is_rename
= 1;
770 patch
->new_name
= find_name(line
, NULL
, 0, 0);
774 static int gitdiff_similarity(const char *line
, struct patch
*patch
)
776 if ((patch
->score
= strtoul(line
, NULL
, 10)) == ULONG_MAX
)
781 static int gitdiff_dissimilarity(const char *line
, struct patch
*patch
)
783 if ((patch
->score
= strtoul(line
, NULL
, 10)) == ULONG_MAX
)
788 static int gitdiff_index(const char *line
, struct patch
*patch
)
791 * index line is N hexadecimal, "..", N hexadecimal,
792 * and optional space with octal mode.
794 const char *ptr
, *eol
;
797 ptr
= strchr(line
, '.');
798 if (!ptr
|| ptr
[1] != '.' || 40 < ptr
- line
)
801 memcpy(patch
->old_sha1_prefix
, line
, len
);
802 patch
->old_sha1_prefix
[len
] = 0;
805 ptr
= strchr(line
, ' ');
806 eol
= strchr(line
, '\n');
808 if (!ptr
|| eol
< ptr
)
814 memcpy(patch
->new_sha1_prefix
, line
, len
);
815 patch
->new_sha1_prefix
[len
] = 0;
817 patch
->old_mode
= strtoul(ptr
+1, NULL
, 8);
822 * This is normal for a diff that doesn't change anything: we'll fall through
823 * into the next diff. Tell the parser to break out.
825 static int gitdiff_unrecognized(const char *line
, struct patch
*patch
)
830 static const char *stop_at_slash(const char *line
, int llen
)
832 int nslash
= p_value
;
835 for (i
= 0; i
< llen
; i
++) {
837 if (ch
== '/' && --nslash
<= 0)
844 * This is to extract the same name that appears on "diff --git"
845 * line. We do not find and return anything if it is a rename
846 * patch, and it is OK because we will find the name elsewhere.
847 * We need to reliably find name only when it is mode-change only,
848 * creation or deletion of an empty file. In any of these cases,
849 * both sides are the same name under a/ and b/ respectively.
851 static char *git_header_name(char *line
, int llen
)
854 const char *second
= NULL
;
857 line
+= strlen("diff --git ");
858 llen
-= strlen("diff --git ");
862 struct strbuf first
= STRBUF_INIT
;
863 struct strbuf sp
= STRBUF_INIT
;
865 if (unquote_c_style(&first
, line
, &second
))
868 /* advance to the first slash */
869 cp
= stop_at_slash(first
.buf
, first
.len
);
870 /* we do not accept absolute paths */
871 if (!cp
|| cp
== first
.buf
)
873 strbuf_remove(&first
, 0, cp
+ 1 - first
.buf
);
876 * second points at one past closing dq of name.
877 * find the second name.
879 while ((second
< line
+ llen
) && isspace(*second
))
882 if (line
+ llen
<= second
)
884 if (*second
== '"') {
885 if (unquote_c_style(&sp
, second
, NULL
))
887 cp
= stop_at_slash(sp
.buf
, sp
.len
);
888 if (!cp
|| cp
== sp
.buf
)
890 /* They must match, otherwise ignore */
891 if (strcmp(cp
+ 1, first
.buf
))
894 return strbuf_detach(&first
, NULL
);
897 /* unquoted second */
898 cp
= stop_at_slash(second
, line
+ llen
- second
);
899 if (!cp
|| cp
== second
)
902 if (line
+ llen
- cp
!= first
.len
+ 1 ||
903 memcmp(first
.buf
, cp
, first
.len
))
905 return strbuf_detach(&first
, NULL
);
908 strbuf_release(&first
);
913 /* unquoted first name */
914 name
= stop_at_slash(line
, llen
);
915 if (!name
|| name
== line
)
920 * since the first name is unquoted, a dq if exists must be
921 * the beginning of the second name.
923 for (second
= name
; second
< line
+ llen
; second
++) {
924 if (*second
== '"') {
925 struct strbuf sp
= STRBUF_INIT
;
928 if (unquote_c_style(&sp
, second
, NULL
))
931 np
= stop_at_slash(sp
.buf
, sp
.len
);
932 if (!np
|| np
== sp
.buf
)
936 len
= sp
.buf
+ sp
.len
- np
;
937 if (len
< second
- name
&&
938 !strncmp(np
, name
, len
) &&
939 isspace(name
[len
])) {
941 strbuf_remove(&sp
, 0, np
- sp
.buf
);
942 return strbuf_detach(&sp
, NULL
);
952 * Accept a name only if it shows up twice, exactly the same
955 for (len
= 0 ; ; len
++) {
970 if (second
[len
] == '\n' && !memcmp(name
, second
, len
)) {
971 return xmemdupz(name
, len
);
977 /* Verify that we recognize the lines following a git header */
978 static int parse_git_header(char *line
, int len
, unsigned int size
, struct patch
*patch
)
980 unsigned long offset
;
982 /* A git diff has explicit new/delete information, so we don't guess */
984 patch
->is_delete
= 0;
987 * Some things may not have the old name in the
988 * rest of the headers anywhere (pure mode changes,
989 * or removing or adding empty files), so we get
990 * the default name from the header.
992 patch
->def_name
= git_header_name(line
, len
);
993 if (patch
->def_name
&& root
) {
994 char *s
= xmalloc(root_len
+ strlen(patch
->def_name
) + 1);
996 strcpy(s
+ root_len
, patch
->def_name
);
997 free(patch
->def_name
);
1004 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1005 static const struct opentry
{
1007 int (*fn
)(const char *, struct patch
*);
1009 { "@@ -", gitdiff_hdrend
},
1010 { "--- ", gitdiff_oldname
},
1011 { "+++ ", gitdiff_newname
},
1012 { "old mode ", gitdiff_oldmode
},
1013 { "new mode ", gitdiff_newmode
},
1014 { "deleted file mode ", gitdiff_delete
},
1015 { "new file mode ", gitdiff_newfile
},
1016 { "copy from ", gitdiff_copysrc
},
1017 { "copy to ", gitdiff_copydst
},
1018 { "rename old ", gitdiff_renamesrc
},
1019 { "rename new ", gitdiff_renamedst
},
1020 { "rename from ", gitdiff_renamesrc
},
1021 { "rename to ", gitdiff_renamedst
},
1022 { "similarity index ", gitdiff_similarity
},
1023 { "dissimilarity index ", gitdiff_dissimilarity
},
1024 { "index ", gitdiff_index
},
1025 { "", gitdiff_unrecognized
},
1029 len
= linelen(line
, size
);
1030 if (!len
|| line
[len
-1] != '\n')
1032 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
1033 const struct opentry
*p
= optable
+ i
;
1034 int oplen
= strlen(p
->str
);
1035 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
1037 if (p
->fn(line
+ oplen
, patch
) < 0)
1046 static int parse_num(const char *line
, unsigned long *p
)
1050 if (!isdigit(*line
))
1052 *p
= strtoul(line
, &ptr
, 10);
1056 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
1057 unsigned long *p1
, unsigned long *p2
)
1061 if (offset
< 0 || offset
>= len
)
1066 digits
= parse_num(line
, p1
);
1076 digits
= parse_num(line
+1, p2
);
1085 ex
= strlen(expect
);
1088 if (memcmp(line
, expect
, ex
))
1094 static void recount_diff(char *line
, int size
, struct fragment
*fragment
)
1096 int oldlines
= 0, newlines
= 0, ret
= 0;
1099 warning("recount: ignore empty hunk");
1104 int len
= linelen(line
, size
);
1112 case ' ': case '\n':
1124 ret
= size
< 3 || prefixcmp(line
, "@@ ");
1127 ret
= size
< 5 || prefixcmp(line
, "diff ");
1134 warning("recount: unexpected line: %.*s",
1135 (int)linelen(line
, size
), line
);
1140 fragment
->oldlines
= oldlines
;
1141 fragment
->newlines
= newlines
;
1145 * Parse a unified diff fragment header of the
1146 * form "@@ -a,b +c,d @@"
1148 static int parse_fragment_header(char *line
, int len
, struct fragment
*fragment
)
1152 if (!len
|| line
[len
-1] != '\n')
1155 /* Figure out the number of lines in a fragment */
1156 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
1157 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
1162 static int find_header(char *line
, unsigned long size
, int *hdrsize
, struct patch
*patch
)
1164 unsigned long offset
, len
;
1166 patch
->is_toplevel_relative
= 0;
1167 patch
->is_rename
= patch
->is_copy
= 0;
1168 patch
->is_new
= patch
->is_delete
= -1;
1169 patch
->old_mode
= patch
->new_mode
= 0;
1170 patch
->old_name
= patch
->new_name
= NULL
;
1171 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1172 unsigned long nextlen
;
1174 len
= linelen(line
, size
);
1178 /* Testing this early allows us to take a few shortcuts.. */
1183 * Make sure we don't find any unconnected patch fragments.
1184 * That's a sign that we didn't find a header, and that a
1185 * patch has become corrupted/broken up.
1187 if (!memcmp("@@ -", line
, 4)) {
1188 struct fragment dummy
;
1189 if (parse_fragment_header(line
, len
, &dummy
) < 0)
1191 die("patch fragment without header at line %d: %.*s",
1192 linenr
, (int)len
-1, line
);
1199 * Git patch? It might not have a real patch, just a rename
1200 * or mode change, so we handle that specially
1202 if (!memcmp("diff --git ", line
, 11)) {
1203 int git_hdr_len
= parse_git_header(line
, len
, size
, patch
);
1204 if (git_hdr_len
<= len
)
1206 if (!patch
->old_name
&& !patch
->new_name
) {
1207 if (!patch
->def_name
)
1208 die("git diff header lacks filename information when removing "
1209 "%d leading pathname components (line %d)" , p_value
, linenr
);
1210 patch
->old_name
= patch
->new_name
= patch
->def_name
;
1212 patch
->is_toplevel_relative
= 1;
1213 *hdrsize
= git_hdr_len
;
1217 /* --- followed by +++ ? */
1218 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
1222 * We only accept unified patches, so we want it to
1223 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1224 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1226 nextlen
= linelen(line
+ len
, size
- len
);
1227 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
1230 /* Ok, we'll consider it a patch */
1231 parse_traditional_patch(line
, line
+len
, patch
);
1232 *hdrsize
= len
+ nextlen
;
1239 static void record_ws_error(unsigned result
, const char *line
, int len
, int linenr
)
1247 if (squelch_whitespace_errors
&&
1248 squelch_whitespace_errors
< whitespace_error
)
1251 err
= whitespace_error_string(result
);
1252 fprintf(stderr
, "%s:%d: %s.\n%.*s\n",
1253 patch_input_file
, linenr
, err
, len
, line
);
1257 static void check_whitespace(const char *line
, int len
, unsigned ws_rule
)
1259 unsigned result
= ws_check(line
+ 1, len
- 1, ws_rule
);
1261 record_ws_error(result
, line
+ 1, len
- 2, linenr
);
1265 * Parse a unified diff. Note that this really needs to parse each
1266 * fragment separately, since the only way to know the difference
1267 * between a "---" that is part of a patch, and a "---" that starts
1268 * the next patch is to look at the line counts..
1270 static int parse_fragment(char *line
, unsigned long size
,
1271 struct patch
*patch
, struct fragment
*fragment
)
1274 int len
= linelen(line
, size
), offset
;
1275 unsigned long oldlines
, newlines
;
1276 unsigned long leading
, trailing
;
1278 offset
= parse_fragment_header(line
, len
, fragment
);
1281 if (offset
> 0 && patch
->recount
)
1282 recount_diff(line
+ offset
, size
- offset
, fragment
);
1283 oldlines
= fragment
->oldlines
;
1284 newlines
= fragment
->newlines
;
1288 /* Parse the thing.. */
1292 added
= deleted
= 0;
1295 offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1296 if (!oldlines
&& !newlines
)
1298 len
= linelen(line
, size
);
1299 if (!len
|| line
[len
-1] != '\n')
1304 case '\n': /* newer GNU diff, an empty context line */
1308 if (!deleted
&& !added
)
1313 if (apply_in_reverse
&&
1314 ws_error_action
!= nowarn_ws_error
)
1315 check_whitespace(line
, len
, patch
->ws_rule
);
1321 if (!apply_in_reverse
&&
1322 ws_error_action
!= nowarn_ws_error
)
1323 check_whitespace(line
, len
, patch
->ws_rule
);
1330 * We allow "\ No newline at end of file". Depending
1331 * on locale settings when the patch was produced we
1332 * don't know what this line looks like. The only
1333 * thing we do know is that it begins with "\ ".
1334 * Checking for 12 is just for sanity check -- any
1335 * l10n of "\ No newline..." is at least that long.
1338 if (len
< 12 || memcmp(line
, "\\ ", 2))
1343 if (oldlines
|| newlines
)
1345 fragment
->leading
= leading
;
1346 fragment
->trailing
= trailing
;
1349 * If a fragment ends with an incomplete line, we failed to include
1350 * it in the above loop because we hit oldlines == newlines == 0
1353 if (12 < size
&& !memcmp(line
, "\\ ", 2))
1354 offset
+= linelen(line
, size
);
1356 patch
->lines_added
+= added
;
1357 patch
->lines_deleted
+= deleted
;
1359 if (0 < patch
->is_new
&& oldlines
)
1360 return error("new file depends on old contents");
1361 if (0 < patch
->is_delete
&& newlines
)
1362 return error("deleted file still has contents");
1366 static int parse_single_patch(char *line
, unsigned long size
, struct patch
*patch
)
1368 unsigned long offset
= 0;
1369 unsigned long oldlines
= 0, newlines
= 0, context
= 0;
1370 struct fragment
**fragp
= &patch
->fragments
;
1372 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
1373 struct fragment
*fragment
;
1376 fragment
= xcalloc(1, sizeof(*fragment
));
1377 fragment
->linenr
= linenr
;
1378 len
= parse_fragment(line
, size
, patch
, fragment
);
1380 die("corrupt patch at line %d", linenr
);
1381 fragment
->patch
= line
;
1382 fragment
->size
= len
;
1383 oldlines
+= fragment
->oldlines
;
1384 newlines
+= fragment
->newlines
;
1385 context
+= fragment
->leading
+ fragment
->trailing
;
1388 fragp
= &fragment
->next
;
1396 * If something was removed (i.e. we have old-lines) it cannot
1397 * be creation, and if something was added it cannot be
1398 * deletion. However, the reverse is not true; --unified=0
1399 * patches that only add are not necessarily creation even
1400 * though they do not have any old lines, and ones that only
1401 * delete are not necessarily deletion.
1403 * Unfortunately, a real creation/deletion patch do _not_ have
1404 * any context line by definition, so we cannot safely tell it
1405 * apart with --unified=0 insanity. At least if the patch has
1406 * more than one hunk it is not creation or deletion.
1408 if (patch
->is_new
< 0 &&
1409 (oldlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1411 if (patch
->is_delete
< 0 &&
1412 (newlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1413 patch
->is_delete
= 0;
1415 if (0 < patch
->is_new
&& oldlines
)
1416 die("new file %s depends on old contents", patch
->new_name
);
1417 if (0 < patch
->is_delete
&& newlines
)
1418 die("deleted file %s still has contents", patch
->old_name
);
1419 if (!patch
->is_delete
&& !newlines
&& context
)
1420 fprintf(stderr
, "** warning: file %s becomes empty but "
1421 "is not deleted\n", patch
->new_name
);
1426 static inline int metadata_changes(struct patch
*patch
)
1428 return patch
->is_rename
> 0 ||
1429 patch
->is_copy
> 0 ||
1430 patch
->is_new
> 0 ||
1432 (patch
->old_mode
&& patch
->new_mode
&&
1433 patch
->old_mode
!= patch
->new_mode
);
1436 static char *inflate_it(const void *data
, unsigned long size
,
1437 unsigned long inflated_size
)
1443 memset(&stream
, 0, sizeof(stream
));
1445 stream
.next_in
= (unsigned char *)data
;
1446 stream
.avail_in
= size
;
1447 stream
.next_out
= out
= xmalloc(inflated_size
);
1448 stream
.avail_out
= inflated_size
;
1449 git_inflate_init(&stream
);
1450 st
= git_inflate(&stream
, Z_FINISH
);
1451 git_inflate_end(&stream
);
1452 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1459 static struct fragment
*parse_binary_hunk(char **buf_p
,
1460 unsigned long *sz_p
,
1465 * Expect a line that begins with binary patch method ("literal"
1466 * or "delta"), followed by the length of data before deflating.
1467 * a sequence of 'length-byte' followed by base-85 encoded data
1468 * should follow, terminated by a newline.
1470 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1471 * and we would limit the patch line to 66 characters,
1472 * so one line can fit up to 13 groups that would decode
1473 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1474 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1477 unsigned long size
= *sz_p
;
1478 char *buffer
= *buf_p
;
1480 unsigned long origlen
;
1483 struct fragment
*frag
;
1485 llen
= linelen(buffer
, size
);
1490 if (!prefixcmp(buffer
, "delta ")) {
1491 patch_method
= BINARY_DELTA_DEFLATED
;
1492 origlen
= strtoul(buffer
+ 6, NULL
, 10);
1494 else if (!prefixcmp(buffer
, "literal ")) {
1495 patch_method
= BINARY_LITERAL_DEFLATED
;
1496 origlen
= strtoul(buffer
+ 8, NULL
, 10);
1504 int byte_length
, max_byte_length
, newsize
;
1505 llen
= linelen(buffer
, size
);
1509 /* consume the blank line */
1515 * Minimum line is "A00000\n" which is 7-byte long,
1516 * and the line length must be multiple of 5 plus 2.
1518 if ((llen
< 7) || (llen
-2) % 5)
1520 max_byte_length
= (llen
- 2) / 5 * 4;
1521 byte_length
= *buffer
;
1522 if ('A' <= byte_length
&& byte_length
<= 'Z')
1523 byte_length
= byte_length
- 'A' + 1;
1524 else if ('a' <= byte_length
&& byte_length
<= 'z')
1525 byte_length
= byte_length
- 'a' + 27;
1528 /* if the input length was not multiple of 4, we would
1529 * have filler at the end but the filler should never
1532 if (max_byte_length
< byte_length
||
1533 byte_length
<= max_byte_length
- 4)
1535 newsize
= hunk_size
+ byte_length
;
1536 data
= xrealloc(data
, newsize
);
1537 if (decode_85(data
+ hunk_size
, buffer
+ 1, byte_length
))
1539 hunk_size
= newsize
;
1544 frag
= xcalloc(1, sizeof(*frag
));
1545 frag
->patch
= inflate_it(data
, hunk_size
, origlen
);
1549 frag
->size
= origlen
;
1553 frag
->binary_patch_method
= patch_method
;
1559 error("corrupt binary patch at line %d: %.*s",
1560 linenr
-1, llen
-1, buffer
);
1564 static int parse_binary(char *buffer
, unsigned long size
, struct patch
*patch
)
1567 * We have read "GIT binary patch\n"; what follows is a line
1568 * that says the patch method (currently, either "literal" or
1569 * "delta") and the length of data before deflating; a
1570 * sequence of 'length-byte' followed by base-85 encoded data
1573 * When a binary patch is reversible, there is another binary
1574 * hunk in the same format, starting with patch method (either
1575 * "literal" or "delta") with the length of data, and a sequence
1576 * of length-byte + base-85 encoded data, terminated with another
1577 * empty line. This data, when applied to the postimage, produces
1580 struct fragment
*forward
;
1581 struct fragment
*reverse
;
1585 forward
= parse_binary_hunk(&buffer
, &size
, &status
, &used
);
1586 if (!forward
&& !status
)
1587 /* there has to be one hunk (forward hunk) */
1588 return error("unrecognized binary patch at line %d", linenr
-1);
1590 /* otherwise we already gave an error message */
1593 reverse
= parse_binary_hunk(&buffer
, &size
, &status
, &used_1
);
1598 * Not having reverse hunk is not an error, but having
1599 * a corrupt reverse hunk is.
1601 free((void*) forward
->patch
);
1605 forward
->next
= reverse
;
1606 patch
->fragments
= forward
;
1607 patch
->is_binary
= 1;
1611 static int parse_chunk(char *buffer
, unsigned long size
, struct patch
*patch
)
1613 int hdrsize
, patchsize
;
1614 int offset
= find_header(buffer
, size
, &hdrsize
, patch
);
1619 patch
->ws_rule
= whitespace_rule(patch
->new_name
1623 patchsize
= parse_single_patch(buffer
+ offset
+ hdrsize
,
1624 size
- offset
- hdrsize
, patch
);
1627 static const char *binhdr
[] = {
1632 static const char git_binary
[] = "GIT binary patch\n";
1634 int hd
= hdrsize
+ offset
;
1635 unsigned long llen
= linelen(buffer
+ hd
, size
- hd
);
1637 if (llen
== sizeof(git_binary
) - 1 &&
1638 !memcmp(git_binary
, buffer
+ hd
, llen
)) {
1641 used
= parse_binary(buffer
+ hd
+ llen
,
1642 size
- hd
- llen
, patch
);
1644 patchsize
= used
+ llen
;
1648 else if (!memcmp(" differ\n", buffer
+ hd
+ llen
- 8, 8)) {
1649 for (i
= 0; binhdr
[i
]; i
++) {
1650 int len
= strlen(binhdr
[i
]);
1651 if (len
< size
- hd
&&
1652 !memcmp(binhdr
[i
], buffer
+ hd
, len
)) {
1654 patch
->is_binary
= 1;
1661 /* Empty patch cannot be applied if it is a text patch
1662 * without metadata change. A binary patch appears
1665 if ((apply
|| check
) &&
1666 (!patch
->is_binary
&& !metadata_changes(patch
)))
1667 die("patch with only garbage at line %d", linenr
);
1670 return offset
+ hdrsize
+ patchsize
;
1673 #define swap(a,b) myswap((a),(b),sizeof(a))
1675 #define myswap(a, b, size) do { \
1676 unsigned char mytmp[size]; \
1677 memcpy(mytmp, &a, size); \
1678 memcpy(&a, &b, size); \
1679 memcpy(&b, mytmp, size); \
1682 static void reverse_patches(struct patch
*p
)
1684 for (; p
; p
= p
->next
) {
1685 struct fragment
*frag
= p
->fragments
;
1687 swap(p
->new_name
, p
->old_name
);
1688 swap(p
->new_mode
, p
->old_mode
);
1689 swap(p
->is_new
, p
->is_delete
);
1690 swap(p
->lines_added
, p
->lines_deleted
);
1691 swap(p
->old_sha1_prefix
, p
->new_sha1_prefix
);
1693 for (; frag
; frag
= frag
->next
) {
1694 swap(frag
->newpos
, frag
->oldpos
);
1695 swap(frag
->newlines
, frag
->oldlines
);
1700 static const char pluses
[] =
1701 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1702 static const char minuses
[]=
1703 "----------------------------------------------------------------------";
1705 static void show_stats(struct patch
*patch
)
1707 struct strbuf qname
= STRBUF_INIT
;
1708 char *cp
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
1711 quote_c_style(cp
, &qname
, NULL
, 0);
1714 * "scale" the filename
1720 if (qname
.len
> max
) {
1721 cp
= strchr(qname
.buf
+ qname
.len
+ 3 - max
, '/');
1723 cp
= qname
.buf
+ qname
.len
+ 3 - max
;
1724 strbuf_splice(&qname
, 0, cp
- qname
.buf
, "...", 3);
1727 if (patch
->is_binary
) {
1728 printf(" %-*s | Bin\n", max
, qname
.buf
);
1729 strbuf_release(&qname
);
1733 printf(" %-*s |", max
, qname
.buf
);
1734 strbuf_release(&qname
);
1737 * scale the add/delete
1739 max
= max
+ max_change
> 70 ? 70 - max
: max_change
;
1740 add
= patch
->lines_added
;
1741 del
= patch
->lines_deleted
;
1743 if (max_change
> 0) {
1744 int total
= ((add
+ del
) * max
+ max_change
/ 2) / max_change
;
1745 add
= (add
* max
+ max_change
/ 2) / max_change
;
1748 printf("%5d %.*s%.*s\n", patch
->lines_added
+ patch
->lines_deleted
,
1749 add
, pluses
, del
, minuses
);
1752 static int read_old_data(struct stat
*st
, const char *path
, struct strbuf
*buf
)
1754 switch (st
->st_mode
& S_IFMT
) {
1756 if (strbuf_readlink(buf
, path
, st
->st_size
) < 0)
1757 return error("unable to read symlink %s", path
);
1760 if (strbuf_read_file(buf
, path
, st
->st_size
) != st
->st_size
)
1761 return error("unable to open or read %s", path
);
1762 convert_to_git(path
, buf
->buf
, buf
->len
, buf
, 0);
1770 * Update the preimage, and the common lines in postimage,
1771 * from buffer buf of length len. If postlen is 0 the postimage
1772 * is updated in place, otherwise it's updated on a new buffer
1776 static void update_pre_post_images(struct image
*preimage
,
1777 struct image
*postimage
,
1779 size_t len
, size_t postlen
)
1782 char *new, *old
, *fixed
;
1783 struct image fixed_preimage
;
1786 * Update the preimage with whitespace fixes. Note that we
1787 * are not losing preimage->buf -- apply_one_fragment() will
1790 prepare_image(&fixed_preimage
, buf
, len
, 1);
1791 assert(fixed_preimage
.nr
== preimage
->nr
);
1792 for (i
= 0; i
< preimage
->nr
; i
++)
1793 fixed_preimage
.line
[i
].flag
= preimage
->line
[i
].flag
;
1794 free(preimage
->line_allocated
);
1795 *preimage
= fixed_preimage
;
1798 * Adjust the common context lines in postimage. This can be
1799 * done in-place when we are just doing whitespace fixing,
1800 * which does not make the string grow, but needs a new buffer
1801 * when ignoring whitespace causes the update, since in this case
1802 * we could have e.g. tabs converted to multiple spaces.
1803 * We trust the caller to tell us if the update can be done
1804 * in place (postlen==0) or not.
1806 old
= postimage
->buf
;
1808 new = postimage
->buf
= xmalloc(postlen
);
1811 fixed
= preimage
->buf
;
1812 for (i
= ctx
= 0; i
< postimage
->nr
; i
++) {
1813 size_t len
= postimage
->line
[i
].len
;
1814 if (!(postimage
->line
[i
].flag
& LINE_COMMON
)) {
1815 /* an added line -- no counterparts in preimage */
1816 memmove(new, old
, len
);
1822 /* a common context -- skip it in the original postimage */
1825 /* and find the corresponding one in the fixed preimage */
1826 while (ctx
< preimage
->nr
&&
1827 !(preimage
->line
[ctx
].flag
& LINE_COMMON
)) {
1828 fixed
+= preimage
->line
[ctx
].len
;
1831 if (preimage
->nr
<= ctx
)
1834 /* and copy it in, while fixing the line length */
1835 len
= preimage
->line
[ctx
].len
;
1836 memcpy(new, fixed
, len
);
1839 postimage
->line
[i
].len
= len
;
1843 /* Fix the length of the whole thing */
1844 postimage
->len
= new - postimage
->buf
;
1847 static int match_fragment(struct image
*img
,
1848 struct image
*preimage
,
1849 struct image
*postimage
,
1853 int match_beginning
, int match_end
)
1856 char *fixed_buf
, *buf
, *orig
, *target
;
1858 if (preimage
->nr
+ try_lno
> img
->nr
)
1861 if (match_beginning
&& try_lno
)
1864 if (match_end
&& preimage
->nr
+ try_lno
!= img
->nr
)
1867 /* Quick hash check */
1868 for (i
= 0; i
< preimage
->nr
; i
++)
1869 if (preimage
->line
[i
].hash
!= img
->line
[try_lno
+ i
].hash
)
1873 * Do we have an exact match? If we were told to match
1874 * at the end, size must be exactly at try+fragsize,
1875 * otherwise try+fragsize must be still within the preimage,
1876 * and either case, the old piece should match the preimage
1880 ? (try + preimage
->len
== img
->len
)
1881 : (try + preimage
->len
<= img
->len
)) &&
1882 !memcmp(img
->buf
+ try, preimage
->buf
, preimage
->len
))
1886 * No exact match. If we are ignoring whitespace, run a line-by-line
1887 * fuzzy matching. We collect all the line length information because
1888 * we need it to adjust whitespace if we match.
1890 if (ws_ignore_action
== ignore_ws_change
) {
1893 size_t postlen
= postimage
->len
;
1894 for (i
= 0; i
< preimage
->nr
; i
++) {
1895 size_t prelen
= preimage
->line
[i
].len
;
1896 size_t imglen
= img
->line
[try_lno
+i
].len
;
1898 if (!fuzzy_matchlines(img
->buf
+ try + imgoff
, imglen
,
1899 preimage
->buf
+ preoff
, prelen
))
1901 if (preimage
->line
[i
].flag
& LINE_COMMON
)
1902 postlen
+= imglen
- prelen
;
1908 * Ok, the preimage matches with whitespace fuzz.
1910 * imgoff now holds the true length of the target that
1911 * matches the preimage. Update the preimage and
1912 * the common postimage context lines to use the same
1913 * whitespace as the target.
1915 fixed_buf
= xmalloc(imgoff
);
1916 memcpy(fixed_buf
, img
->buf
+ try, imgoff
);
1917 update_pre_post_images(preimage
, postimage
,
1918 fixed_buf
, imgoff
, postlen
);
1922 if (ws_error_action
!= correct_ws_error
)
1926 * The hunk does not apply byte-by-byte, but the hash says
1927 * it might with whitespace fuzz. We haven't been asked to
1928 * ignore whitespace, we were asked to correct whitespace
1929 * errors, so let's try matching after whitespace correction.
1931 fixed_buf
= xmalloc(preimage
->len
+ 1);
1933 orig
= preimage
->buf
;
1934 target
= img
->buf
+ try;
1935 for (i
= 0; i
< preimage
->nr
; i
++) {
1936 size_t fixlen
; /* length after fixing the preimage */
1937 size_t oldlen
= preimage
->line
[i
].len
;
1938 size_t tgtlen
= img
->line
[try_lno
+ i
].len
;
1939 size_t tgtfixlen
; /* length after fixing the target line */
1940 char tgtfixbuf
[1024], *tgtfix
;
1943 /* Try fixing the line in the preimage */
1944 fixlen
= ws_fix_copy(buf
, orig
, oldlen
, ws_rule
, NULL
);
1946 /* Try fixing the line in the target */
1947 if (sizeof(tgtfixbuf
) > tgtlen
)
1950 tgtfix
= xmalloc(tgtlen
);
1951 tgtfixlen
= ws_fix_copy(tgtfix
, target
, tgtlen
, ws_rule
, NULL
);
1954 * If they match, either the preimage was based on
1955 * a version before our tree fixed whitespace breakage,
1956 * or we are lacking a whitespace-fix patch the tree
1957 * the preimage was based on already had (i.e. target
1958 * has whitespace breakage, the preimage doesn't).
1959 * In either case, we are fixing the whitespace breakages
1960 * so we might as well take the fix together with their
1963 match
= (tgtfixlen
== fixlen
&& !memcmp(tgtfix
, buf
, fixlen
));
1965 if (tgtfix
!= tgtfixbuf
)
1976 * Yes, the preimage is based on an older version that still
1977 * has whitespace breakages unfixed, and fixing them makes the
1978 * hunk match. Update the context lines in the postimage.
1980 update_pre_post_images(preimage
, postimage
,
1981 fixed_buf
, buf
- fixed_buf
, 0);
1989 static int find_pos(struct image
*img
,
1990 struct image
*preimage
,
1991 struct image
*postimage
,
1994 int match_beginning
, int match_end
)
1997 unsigned long backwards
, forwards
, try;
1998 int backwards_lno
, forwards_lno
, try_lno
;
2000 if (preimage
->nr
> img
->nr
)
2004 * If match_begining or match_end is specified, there is no
2005 * point starting from a wrong line that will never match and
2006 * wander around and wait for a match at the specified end.
2008 if (match_beginning
)
2011 line
= img
->nr
- preimage
->nr
;
2017 for (i
= 0; i
< line
; i
++)
2018 try += img
->line
[i
].len
;
2021 * There's probably some smart way to do this, but I'll leave
2022 * that to the smart and beautiful people. I'm simple and stupid.
2025 backwards_lno
= line
;
2027 forwards_lno
= line
;
2030 for (i
= 0; ; i
++) {
2031 if (match_fragment(img
, preimage
, postimage
,
2032 try, try_lno
, ws_rule
,
2033 match_beginning
, match_end
))
2037 if (backwards_lno
== 0 && forwards_lno
== img
->nr
)
2041 if (backwards_lno
== 0) {
2046 backwards
-= img
->line
[backwards_lno
].len
;
2048 try_lno
= backwards_lno
;
2050 if (forwards_lno
== img
->nr
) {
2054 forwards
+= img
->line
[forwards_lno
].len
;
2057 try_lno
= forwards_lno
;
2064 static void remove_first_line(struct image
*img
)
2066 img
->buf
+= img
->line
[0].len
;
2067 img
->len
-= img
->line
[0].len
;
2072 static void remove_last_line(struct image
*img
)
2074 img
->len
-= img
->line
[--img
->nr
].len
;
2077 static void update_image(struct image
*img
,
2079 struct image
*preimage
,
2080 struct image
*postimage
)
2083 * remove the copy of preimage at offset in img
2084 * and replace it with postimage
2087 size_t remove_count
, insert_count
, applied_at
= 0;
2090 for (i
= 0; i
< applied_pos
; i
++)
2091 applied_at
+= img
->line
[i
].len
;
2094 for (i
= 0; i
< preimage
->nr
; i
++)
2095 remove_count
+= img
->line
[applied_pos
+ i
].len
;
2096 insert_count
= postimage
->len
;
2098 /* Adjust the contents */
2099 result
= xmalloc(img
->len
+ insert_count
- remove_count
+ 1);
2100 memcpy(result
, img
->buf
, applied_at
);
2101 memcpy(result
+ applied_at
, postimage
->buf
, postimage
->len
);
2102 memcpy(result
+ applied_at
+ postimage
->len
,
2103 img
->buf
+ (applied_at
+ remove_count
),
2104 img
->len
- (applied_at
+ remove_count
));
2107 img
->len
+= insert_count
- remove_count
;
2108 result
[img
->len
] = '\0';
2110 /* Adjust the line table */
2111 nr
= img
->nr
+ postimage
->nr
- preimage
->nr
;
2112 if (preimage
->nr
< postimage
->nr
) {
2114 * NOTE: this knows that we never call remove_first_line()
2115 * on anything other than pre/post image.
2117 img
->line
= xrealloc(img
->line
, nr
* sizeof(*img
->line
));
2118 img
->line_allocated
= img
->line
;
2120 if (preimage
->nr
!= postimage
->nr
)
2121 memmove(img
->line
+ applied_pos
+ postimage
->nr
,
2122 img
->line
+ applied_pos
+ preimage
->nr
,
2123 (img
->nr
- (applied_pos
+ preimage
->nr
)) *
2124 sizeof(*img
->line
));
2125 memcpy(img
->line
+ applied_pos
,
2127 postimage
->nr
* sizeof(*img
->line
));
2131 static int apply_one_fragment(struct image
*img
, struct fragment
*frag
,
2132 int inaccurate_eof
, unsigned ws_rule
)
2134 int match_beginning
, match_end
;
2135 const char *patch
= frag
->patch
;
2136 int size
= frag
->size
;
2137 char *old
, *new, *oldlines
, *newlines
;
2138 int new_blank_lines_at_end
= 0;
2139 unsigned long leading
, trailing
;
2140 int pos
, applied_pos
;
2141 struct image preimage
;
2142 struct image postimage
;
2144 memset(&preimage
, 0, sizeof(preimage
));
2145 memset(&postimage
, 0, sizeof(postimage
));
2146 oldlines
= xmalloc(size
);
2147 newlines
= xmalloc(size
);
2153 int len
= linelen(patch
, size
);
2155 int added_blank_line
= 0;
2156 int is_blank_context
= 0;
2162 * "plen" is how much of the line we should use for
2163 * the actual patch data. Normally we just remove the
2164 * first character on the line, but if the line is
2165 * followed by "\ No newline", then we also remove the
2166 * last one (which is the newline, of course).
2169 if (len
< size
&& patch
[len
] == '\\')
2172 if (apply_in_reverse
) {
2175 else if (first
== '+')
2181 /* Newer GNU diff, empty context line */
2183 /* ... followed by '\No newline'; nothing */
2187 add_line_info(&preimage
, "\n", 1, LINE_COMMON
);
2188 add_line_info(&postimage
, "\n", 1, LINE_COMMON
);
2189 is_blank_context
= 1;
2192 if (plen
&& (ws_rule
& WS_BLANK_AT_EOF
) &&
2193 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2194 is_blank_context
= 1;
2196 memcpy(old
, patch
+ 1, plen
);
2197 add_line_info(&preimage
, old
, plen
,
2198 (first
== ' ' ? LINE_COMMON
: 0));
2202 /* Fall-through for ' ' */
2204 /* --no-add does not add new lines */
2205 if (first
== '+' && no_add
)
2209 !whitespace_error
||
2210 ws_error_action
!= correct_ws_error
) {
2211 memcpy(new, patch
+ 1, plen
);
2215 added
= ws_fix_copy(new, patch
+ 1, plen
, ws_rule
, &applied_after_fixing_ws
);
2217 add_line_info(&postimage
, new, added
,
2218 (first
== '+' ? 0 : LINE_COMMON
));
2221 (ws_rule
& WS_BLANK_AT_EOF
) &&
2222 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2223 added_blank_line
= 1;
2225 case '@': case '\\':
2226 /* Ignore it, we already handled it */
2229 if (apply_verbosely
)
2230 error("invalid start of line: '%c'", first
);
2233 if (added_blank_line
)
2234 new_blank_lines_at_end
++;
2235 else if (is_blank_context
)
2238 new_blank_lines_at_end
= 0;
2242 if (inaccurate_eof
&&
2243 old
> oldlines
&& old
[-1] == '\n' &&
2244 new > newlines
&& new[-1] == '\n') {
2249 leading
= frag
->leading
;
2250 trailing
= frag
->trailing
;
2253 * A hunk to change lines at the beginning would begin with
2255 * but we need to be careful. -U0 that inserts before the second
2256 * line also has this pattern.
2258 * And a hunk to add to an empty file would begin with
2261 * In other words, a hunk that is (frag->oldpos <= 1) with or
2262 * without leading context must match at the beginning.
2264 match_beginning
= (!frag
->oldpos
||
2265 (frag
->oldpos
== 1 && !unidiff_zero
));
2268 * A hunk without trailing lines must match at the end.
2269 * However, we simply cannot tell if a hunk must match end
2270 * from the lack of trailing lines if the patch was generated
2271 * with unidiff without any context.
2273 match_end
= !unidiff_zero
&& !trailing
;
2275 pos
= frag
->newpos
? (frag
->newpos
- 1) : 0;
2276 preimage
.buf
= oldlines
;
2277 preimage
.len
= old
- oldlines
;
2278 postimage
.buf
= newlines
;
2279 postimage
.len
= new - newlines
;
2280 preimage
.line
= preimage
.line_allocated
;
2281 postimage
.line
= postimage
.line_allocated
;
2285 applied_pos
= find_pos(img
, &preimage
, &postimage
, pos
,
2286 ws_rule
, match_beginning
, match_end
);
2288 if (applied_pos
>= 0)
2291 /* Am I at my context limits? */
2292 if ((leading
<= p_context
) && (trailing
<= p_context
))
2294 if (match_beginning
|| match_end
) {
2295 match_beginning
= match_end
= 0;
2300 * Reduce the number of context lines; reduce both
2301 * leading and trailing if they are equal otherwise
2302 * just reduce the larger context.
2304 if (leading
>= trailing
) {
2305 remove_first_line(&preimage
);
2306 remove_first_line(&postimage
);
2310 if (trailing
> leading
) {
2311 remove_last_line(&preimage
);
2312 remove_last_line(&postimage
);
2317 if (applied_pos
>= 0) {
2318 if (new_blank_lines_at_end
&&
2319 preimage
.nr
+ applied_pos
== img
->nr
&&
2320 (ws_rule
& WS_BLANK_AT_EOF
) &&
2321 ws_error_action
!= nowarn_ws_error
) {
2322 record_ws_error(WS_BLANK_AT_EOF
, "+", 1, frag
->linenr
);
2323 if (ws_error_action
== correct_ws_error
) {
2324 while (new_blank_lines_at_end
--)
2325 remove_last_line(&postimage
);
2328 * We would want to prevent write_out_results()
2329 * from taking place in apply_patch() that follows
2330 * the callchain led us here, which is:
2331 * apply_patch->check_patch_list->check_patch->
2332 * apply_data->apply_fragments->apply_one_fragment
2334 if (ws_error_action
== die_on_ws_error
)
2339 * Warn if it was necessary to reduce the number
2342 if ((leading
!= frag
->leading
) ||
2343 (trailing
!= frag
->trailing
))
2344 fprintf(stderr
, "Context reduced to (%ld/%ld)"
2345 " to apply fragment at %d\n",
2346 leading
, trailing
, applied_pos
+1);
2347 update_image(img
, applied_pos
, &preimage
, &postimage
);
2349 if (apply_verbosely
)
2350 error("while searching for:\n%.*s",
2351 (int)(old
- oldlines
), oldlines
);
2356 free(preimage
.line_allocated
);
2357 free(postimage
.line_allocated
);
2359 return (applied_pos
< 0);
2362 static int apply_binary_fragment(struct image
*img
, struct patch
*patch
)
2364 struct fragment
*fragment
= patch
->fragments
;
2368 /* Binary patch is irreversible without the optional second hunk */
2369 if (apply_in_reverse
) {
2370 if (!fragment
->next
)
2371 return error("cannot reverse-apply a binary patch "
2372 "without the reverse hunk to '%s'",
2374 ? patch
->new_name
: patch
->old_name
);
2375 fragment
= fragment
->next
;
2377 switch (fragment
->binary_patch_method
) {
2378 case BINARY_DELTA_DEFLATED
:
2379 dst
= patch_delta(img
->buf
, img
->len
, fragment
->patch
,
2380 fragment
->size
, &len
);
2387 case BINARY_LITERAL_DEFLATED
:
2389 img
->len
= fragment
->size
;
2390 img
->buf
= xmalloc(img
->len
+1);
2391 memcpy(img
->buf
, fragment
->patch
, img
->len
);
2392 img
->buf
[img
->len
] = '\0';
2398 static int apply_binary(struct image
*img
, struct patch
*patch
)
2400 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
2401 unsigned char sha1
[20];
2404 * For safety, we require patch index line to contain
2405 * full 40-byte textual SHA1 for old and new, at least for now.
2407 if (strlen(patch
->old_sha1_prefix
) != 40 ||
2408 strlen(patch
->new_sha1_prefix
) != 40 ||
2409 get_sha1_hex(patch
->old_sha1_prefix
, sha1
) ||
2410 get_sha1_hex(patch
->new_sha1_prefix
, sha1
))
2411 return error("cannot apply binary patch to '%s' "
2412 "without full index line", name
);
2414 if (patch
->old_name
) {
2416 * See if the old one matches what the patch
2419 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
2420 if (strcmp(sha1_to_hex(sha1
), patch
->old_sha1_prefix
))
2421 return error("the patch applies to '%s' (%s), "
2422 "which does not match the "
2423 "current contents.",
2424 name
, sha1_to_hex(sha1
));
2427 /* Otherwise, the old one must be empty. */
2429 return error("the patch applies to an empty "
2430 "'%s' but it is not empty", name
);
2433 get_sha1_hex(patch
->new_sha1_prefix
, sha1
);
2434 if (is_null_sha1(sha1
)) {
2436 return 0; /* deletion patch */
2439 if (has_sha1_file(sha1
)) {
2440 /* We already have the postimage */
2441 enum object_type type
;
2445 result
= read_sha1_file(sha1
, &type
, &size
);
2447 return error("the necessary postimage %s for "
2448 "'%s' cannot be read",
2449 patch
->new_sha1_prefix
, name
);
2455 * We have verified buf matches the preimage;
2456 * apply the patch data to it, which is stored
2457 * in the patch->fragments->{patch,size}.
2459 if (apply_binary_fragment(img
, patch
))
2460 return error("binary patch does not apply to '%s'",
2463 /* verify that the result matches */
2464 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
2465 if (strcmp(sha1_to_hex(sha1
), patch
->new_sha1_prefix
))
2466 return error("binary patch to '%s' creates incorrect result (expecting %s, got %s)",
2467 name
, patch
->new_sha1_prefix
, sha1_to_hex(sha1
));
2473 static int apply_fragments(struct image
*img
, struct patch
*patch
)
2475 struct fragment
*frag
= patch
->fragments
;
2476 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
2477 unsigned ws_rule
= patch
->ws_rule
;
2478 unsigned inaccurate_eof
= patch
->inaccurate_eof
;
2480 if (patch
->is_binary
)
2481 return apply_binary(img
, patch
);
2484 if (apply_one_fragment(img
, frag
, inaccurate_eof
, ws_rule
)) {
2485 error("patch failed: %s:%ld", name
, frag
->oldpos
);
2486 if (!apply_with_reject
)
2495 static int read_file_or_gitlink(struct cache_entry
*ce
, struct strbuf
*buf
)
2500 if (S_ISGITLINK(ce
->ce_mode
)) {
2501 strbuf_grow(buf
, 100);
2502 strbuf_addf(buf
, "Subproject commit %s\n", sha1_to_hex(ce
->sha1
));
2504 enum object_type type
;
2508 result
= read_sha1_file(ce
->sha1
, &type
, &sz
);
2511 /* XXX read_sha1_file NUL-terminates */
2512 strbuf_attach(buf
, result
, sz
, sz
+ 1);
2517 static struct patch
*in_fn_table(const char *name
)
2519 struct string_list_item
*item
;
2524 item
= string_list_lookup(name
, &fn_table
);
2526 return (struct patch
*)item
->util
;
2532 * item->util in the filename table records the status of the path.
2533 * Usually it points at a patch (whose result records the contents
2534 * of it after applying it), but it could be PATH_WAS_DELETED for a
2535 * path that a previously applied patch has already removed.
2537 #define PATH_TO_BE_DELETED ((struct patch *) -2)
2538 #define PATH_WAS_DELETED ((struct patch *) -1)
2540 static int to_be_deleted(struct patch
*patch
)
2542 return patch
== PATH_TO_BE_DELETED
;
2545 static int was_deleted(struct patch
*patch
)
2547 return patch
== PATH_WAS_DELETED
;
2550 static void add_to_fn_table(struct patch
*patch
)
2552 struct string_list_item
*item
;
2555 * Always add new_name unless patch is a deletion
2556 * This should cover the cases for normal diffs,
2557 * file creations and copies
2559 if (patch
->new_name
!= NULL
) {
2560 item
= string_list_insert(patch
->new_name
, &fn_table
);
2565 * store a failure on rename/deletion cases because
2566 * later chunks shouldn't patch old names
2568 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
2569 item
= string_list_insert(patch
->old_name
, &fn_table
);
2570 item
->util
= PATH_WAS_DELETED
;
2574 static void prepare_fn_table(struct patch
*patch
)
2577 * store information about incoming file deletion
2580 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
2581 struct string_list_item
*item
;
2582 item
= string_list_insert(patch
->old_name
, &fn_table
);
2583 item
->util
= PATH_TO_BE_DELETED
;
2585 patch
= patch
->next
;
2589 static int apply_data(struct patch
*patch
, struct stat
*st
, struct cache_entry
*ce
)
2591 struct strbuf buf
= STRBUF_INIT
;
2595 struct patch
*tpatch
;
2597 if (!(patch
->is_copy
|| patch
->is_rename
) &&
2598 (tpatch
= in_fn_table(patch
->old_name
)) != NULL
&& !to_be_deleted(tpatch
)) {
2599 if (was_deleted(tpatch
)) {
2600 return error("patch %s has been renamed/deleted",
2603 /* We have a patched copy in memory use that */
2604 strbuf_add(&buf
, tpatch
->result
, tpatch
->resultsize
);
2605 } else if (cached
) {
2606 if (read_file_or_gitlink(ce
, &buf
))
2607 return error("read of %s failed", patch
->old_name
);
2608 } else if (patch
->old_name
) {
2609 if (S_ISGITLINK(patch
->old_mode
)) {
2611 read_file_or_gitlink(ce
, &buf
);
2614 * There is no way to apply subproject
2615 * patch without looking at the index.
2617 patch
->fragments
= NULL
;
2620 if (read_old_data(st
, patch
->old_name
, &buf
))
2621 return error("read of %s failed", patch
->old_name
);
2625 img
= strbuf_detach(&buf
, &len
);
2626 prepare_image(&image
, img
, len
, !patch
->is_binary
);
2628 if (apply_fragments(&image
, patch
) < 0)
2629 return -1; /* note with --reject this succeeds. */
2630 patch
->result
= image
.buf
;
2631 patch
->resultsize
= image
.len
;
2632 add_to_fn_table(patch
);
2633 free(image
.line_allocated
);
2635 if (0 < patch
->is_delete
&& patch
->resultsize
)
2636 return error("removal patch leaves file contents");
2641 static int check_to_create_blob(const char *new_name
, int ok_if_exists
)
2644 if (!lstat(new_name
, &nst
)) {
2645 if (S_ISDIR(nst
.st_mode
) || ok_if_exists
)
2648 * A leading component of new_name might be a symlink
2649 * that is going to be removed with this patch, but
2650 * still pointing at somewhere that has the path.
2651 * In such a case, path "new_name" does not exist as
2652 * far as git is concerned.
2654 if (has_symlink_leading_path(new_name
, strlen(new_name
)))
2657 return error("%s: already exists in working directory", new_name
);
2659 else if ((errno
!= ENOENT
) && (errno
!= ENOTDIR
))
2660 return error("%s: %s", new_name
, strerror(errno
));
2664 static int verify_index_match(struct cache_entry
*ce
, struct stat
*st
)
2666 if (S_ISGITLINK(ce
->ce_mode
)) {
2667 if (!S_ISDIR(st
->st_mode
))
2671 return ce_match_stat(ce
, st
, CE_MATCH_IGNORE_VALID
|CE_MATCH_IGNORE_SKIP_WORKTREE
);
2674 static int check_preimage(struct patch
*patch
, struct cache_entry
**ce
, struct stat
*st
)
2676 const char *old_name
= patch
->old_name
;
2677 struct patch
*tpatch
= NULL
;
2679 unsigned st_mode
= 0;
2682 * Make sure that we do not have local modifications from the
2683 * index when we are looking at the index. Also make sure
2684 * we have the preimage file to be patched in the work tree,
2685 * unless --cached, which tells git to apply only in the index.
2690 assert(patch
->is_new
<= 0);
2692 if (!(patch
->is_copy
|| patch
->is_rename
) &&
2693 (tpatch
= in_fn_table(old_name
)) != NULL
&& !to_be_deleted(tpatch
)) {
2694 if (was_deleted(tpatch
))
2695 return error("%s: has been deleted/renamed", old_name
);
2696 st_mode
= tpatch
->new_mode
;
2697 } else if (!cached
) {
2698 stat_ret
= lstat(old_name
, st
);
2699 if (stat_ret
&& errno
!= ENOENT
)
2700 return error("%s: %s", old_name
, strerror(errno
));
2703 if (to_be_deleted(tpatch
))
2706 if (check_index
&& !tpatch
) {
2707 int pos
= cache_name_pos(old_name
, strlen(old_name
));
2709 if (patch
->is_new
< 0)
2711 return error("%s: does not exist in index", old_name
);
2713 *ce
= active_cache
[pos
];
2715 struct checkout costate
;
2717 costate
.base_dir
= "";
2718 costate
.base_dir_len
= 0;
2721 costate
.not_new
= 0;
2722 costate
.refresh_cache
= 1;
2723 if (checkout_entry(*ce
, &costate
, NULL
) ||
2724 lstat(old_name
, st
))
2727 if (!cached
&& verify_index_match(*ce
, st
))
2728 return error("%s: does not match index", old_name
);
2730 st_mode
= (*ce
)->ce_mode
;
2731 } else if (stat_ret
< 0) {
2732 if (patch
->is_new
< 0)
2734 return error("%s: %s", old_name
, strerror(errno
));
2737 if (!cached
&& !tpatch
)
2738 st_mode
= ce_mode_from_stat(*ce
, st
->st_mode
);
2740 if (patch
->is_new
< 0)
2742 if (!patch
->old_mode
)
2743 patch
->old_mode
= st_mode
;
2744 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
2745 return error("%s: wrong type", old_name
);
2746 if (st_mode
!= patch
->old_mode
)
2747 warning("%s has type %o, expected %o",
2748 old_name
, st_mode
, patch
->old_mode
);
2749 if (!patch
->new_mode
&& !patch
->is_delete
)
2750 patch
->new_mode
= st_mode
;
2755 patch
->is_delete
= 0;
2756 patch
->old_name
= NULL
;
2760 static int check_patch(struct patch
*patch
)
2763 const char *old_name
= patch
->old_name
;
2764 const char *new_name
= patch
->new_name
;
2765 const char *name
= old_name
? old_name
: new_name
;
2766 struct cache_entry
*ce
= NULL
;
2767 struct patch
*tpatch
;
2771 patch
->rejected
= 1; /* we will drop this after we succeed */
2773 status
= check_preimage(patch
, &ce
, &st
);
2776 old_name
= patch
->old_name
;
2778 if ((tpatch
= in_fn_table(new_name
)) &&
2779 (was_deleted(tpatch
) || to_be_deleted(tpatch
)))
2781 * A type-change diff is always split into a patch to
2782 * delete old, immediately followed by a patch to
2783 * create new (see diff.c::run_diff()); in such a case
2784 * it is Ok that the entry to be deleted by the
2785 * previous patch is still in the working tree and in
2793 ((0 < patch
->is_new
) | (0 < patch
->is_rename
) | patch
->is_copy
)) {
2795 cache_name_pos(new_name
, strlen(new_name
)) >= 0 &&
2797 return error("%s: already exists in index", new_name
);
2799 int err
= check_to_create_blob(new_name
, ok_if_exists
);
2803 if (!patch
->new_mode
) {
2804 if (0 < patch
->is_new
)
2805 patch
->new_mode
= S_IFREG
| 0644;
2807 patch
->new_mode
= patch
->old_mode
;
2811 if (new_name
&& old_name
) {
2812 int same
= !strcmp(old_name
, new_name
);
2813 if (!patch
->new_mode
)
2814 patch
->new_mode
= patch
->old_mode
;
2815 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
)
2816 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
2817 patch
->new_mode
, new_name
, patch
->old_mode
,
2818 same
? "" : " of ", same
? "" : old_name
);
2821 if (apply_data(patch
, &st
, ce
) < 0)
2822 return error("%s: patch does not apply", name
);
2823 patch
->rejected
= 0;
2827 static int check_patch_list(struct patch
*patch
)
2831 prepare_fn_table(patch
);
2833 if (apply_verbosely
)
2834 say_patch_name(stderr
,
2835 "Checking patch ", patch
, "...\n");
2836 err
|= check_patch(patch
);
2837 patch
= patch
->next
;
2842 /* This function tries to read the sha1 from the current index */
2843 static int get_current_sha1(const char *path
, unsigned char *sha1
)
2847 if (read_cache() < 0)
2849 pos
= cache_name_pos(path
, strlen(path
));
2852 hashcpy(sha1
, active_cache
[pos
]->sha1
);
2856 /* Build an index that contains the just the files needed for a 3way merge */
2857 static void build_fake_ancestor(struct patch
*list
, const char *filename
)
2859 struct patch
*patch
;
2860 struct index_state result
= { NULL
};
2863 /* Once we start supporting the reverse patch, it may be
2864 * worth showing the new sha1 prefix, but until then...
2866 for (patch
= list
; patch
; patch
= patch
->next
) {
2867 const unsigned char *sha1_ptr
;
2868 unsigned char sha1
[20];
2869 struct cache_entry
*ce
;
2872 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
2873 if (0 < patch
->is_new
)
2875 else if (get_sha1(patch
->old_sha1_prefix
, sha1
))
2876 /* git diff has no index line for mode/type changes */
2877 if (!patch
->lines_added
&& !patch
->lines_deleted
) {
2878 if (get_current_sha1(patch
->new_name
, sha1
) ||
2879 get_current_sha1(patch
->old_name
, sha1
))
2880 die("mode change for %s, which is not "
2881 "in current HEAD", name
);
2884 die("sha1 information is lacking or useless "
2889 ce
= make_cache_entry(patch
->old_mode
, sha1_ptr
, name
, 0, 0);
2891 die("make_cache_entry failed for path '%s'", name
);
2892 if (add_index_entry(&result
, ce
, ADD_CACHE_OK_TO_ADD
))
2893 die ("Could not add %s to temporary index", name
);
2896 fd
= open(filename
, O_WRONLY
| O_CREAT
, 0666);
2897 if (fd
< 0 || write_index(&result
, fd
) || close(fd
))
2898 die ("Could not write temporary index to %s", filename
);
2900 discard_index(&result
);
2903 static void stat_patch_list(struct patch
*patch
)
2905 int files
, adds
, dels
;
2907 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
2909 adds
+= patch
->lines_added
;
2910 dels
+= patch
->lines_deleted
;
2914 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files
, adds
, dels
);
2917 static void numstat_patch_list(struct patch
*patch
)
2919 for ( ; patch
; patch
= patch
->next
) {
2921 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
2922 if (patch
->is_binary
)
2925 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
2926 write_name_quoted(name
, stdout
, line_termination
);
2930 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
2933 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
2935 printf(" %s %s\n", newdelete
, name
);
2938 static void show_mode_change(struct patch
*p
, int show_name
)
2940 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
2942 printf(" mode change %06o => %06o %s\n",
2943 p
->old_mode
, p
->new_mode
, p
->new_name
);
2945 printf(" mode change %06o => %06o\n",
2946 p
->old_mode
, p
->new_mode
);
2950 static void show_rename_copy(struct patch
*p
)
2952 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
2953 const char *old
, *new;
2955 /* Find common prefix */
2959 const char *slash_old
, *slash_new
;
2960 slash_old
= strchr(old
, '/');
2961 slash_new
= strchr(new, '/');
2964 slash_old
- old
!= slash_new
- new ||
2965 memcmp(old
, new, slash_new
- new))
2967 old
= slash_old
+ 1;
2968 new = slash_new
+ 1;
2970 /* p->old_name thru old is the common prefix, and old and new
2971 * through the end of names are renames
2973 if (old
!= p
->old_name
)
2974 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
2975 (int)(old
- p
->old_name
), p
->old_name
,
2976 old
, new, p
->score
);
2978 printf(" %s %s => %s (%d%%)\n", renamecopy
,
2979 p
->old_name
, p
->new_name
, p
->score
);
2980 show_mode_change(p
, 0);
2983 static void summary_patch_list(struct patch
*patch
)
2987 for (p
= patch
; p
; p
= p
->next
) {
2989 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
2990 else if (p
->is_delete
)
2991 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
2993 if (p
->is_rename
|| p
->is_copy
)
2994 show_rename_copy(p
);
2997 printf(" rewrite %s (%d%%)\n",
2998 p
->new_name
, p
->score
);
2999 show_mode_change(p
, 0);
3002 show_mode_change(p
, 1);
3008 static void patch_stats(struct patch
*patch
)
3010 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
3012 if (lines
> max_change
)
3014 if (patch
->old_name
) {
3015 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
3017 len
= strlen(patch
->old_name
);
3021 if (patch
->new_name
) {
3022 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
3024 len
= strlen(patch
->new_name
);
3030 static void remove_file(struct patch
*patch
, int rmdir_empty
)
3033 if (remove_file_from_cache(patch
->old_name
) < 0)
3034 die("unable to remove %s from index", patch
->old_name
);
3037 if (S_ISGITLINK(patch
->old_mode
)) {
3038 if (rmdir(patch
->old_name
))
3039 warning("unable to remove submodule %s",
3041 } else if (!unlink_or_warn(patch
->old_name
) && rmdir_empty
) {
3042 remove_path(patch
->old_name
);
3047 static void add_index_file(const char *path
, unsigned mode
, void *buf
, unsigned long size
)
3050 struct cache_entry
*ce
;
3051 int namelen
= strlen(path
);
3052 unsigned ce_size
= cache_entry_size(namelen
);
3057 ce
= xcalloc(1, ce_size
);
3058 memcpy(ce
->name
, path
, namelen
);
3059 ce
->ce_mode
= create_ce_mode(mode
);
3060 ce
->ce_flags
= namelen
;
3061 if (S_ISGITLINK(mode
)) {
3062 const char *s
= buf
;
3064 if (get_sha1_hex(s
+ strlen("Subproject commit "), ce
->sha1
))
3065 die("corrupt patch for subproject %s", path
);
3068 if (lstat(path
, &st
) < 0)
3069 die_errno("unable to stat newly created file '%s'",
3071 fill_stat_cache_info(ce
, &st
);
3073 if (write_sha1_file(buf
, size
, blob_type
, ce
->sha1
) < 0)
3074 die("unable to create backing store for newly created file %s", path
);
3076 if (add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
) < 0)
3077 die("unable to add cache entry for %s", path
);
3080 static int try_create_file(const char *path
, unsigned int mode
, const char *buf
, unsigned long size
)
3083 struct strbuf nbuf
= STRBUF_INIT
;
3085 if (S_ISGITLINK(mode
)) {
3087 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
))
3089 return mkdir(path
, 0777);
3092 if (has_symlinks
&& S_ISLNK(mode
))
3093 /* Although buf:size is counted string, it also is NUL
3096 return symlink(buf
, path
);
3098 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
3102 if (convert_to_working_tree(path
, buf
, size
, &nbuf
)) {
3106 write_or_die(fd
, buf
, size
);
3107 strbuf_release(&nbuf
);
3110 die_errno("closing file '%s'", path
);
3115 * We optimistically assume that the directories exist,
3116 * which is true 99% of the time anyway. If they don't,
3117 * we create them and try again.
3119 static void create_one_file(char *path
, unsigned mode
, const char *buf
, unsigned long size
)
3123 if (!try_create_file(path
, mode
, buf
, size
))
3126 if (errno
== ENOENT
) {
3127 if (safe_create_leading_directories(path
))
3129 if (!try_create_file(path
, mode
, buf
, size
))
3133 if (errno
== EEXIST
|| errno
== EACCES
) {
3134 /* We may be trying to create a file where a directory
3138 if (!lstat(path
, &st
) && (!S_ISDIR(st
.st_mode
) || !rmdir(path
)))
3142 if (errno
== EEXIST
) {
3143 unsigned int nr
= getpid();
3146 char newpath
[PATH_MAX
];
3147 mksnpath(newpath
, sizeof(newpath
), "%s~%u", path
, nr
);
3148 if (!try_create_file(newpath
, mode
, buf
, size
)) {
3149 if (!rename(newpath
, path
))
3151 unlink_or_warn(newpath
);
3154 if (errno
!= EEXIST
)
3159 die_errno("unable to write file '%s' mode %o", path
, mode
);
3162 static void create_file(struct patch
*patch
)
3164 char *path
= patch
->new_name
;
3165 unsigned mode
= patch
->new_mode
;
3166 unsigned long size
= patch
->resultsize
;
3167 char *buf
= patch
->result
;
3170 mode
= S_IFREG
| 0644;
3171 create_one_file(path
, mode
, buf
, size
);
3172 add_index_file(path
, mode
, buf
, size
);
3175 /* phase zero is to remove, phase one is to create */
3176 static void write_out_one_result(struct patch
*patch
, int phase
)
3178 if (patch
->is_delete
> 0) {
3180 remove_file(patch
, 1);
3183 if (patch
->is_new
> 0 || patch
->is_copy
) {
3189 * Rename or modification boils down to the same
3190 * thing: remove the old, write the new
3193 remove_file(patch
, patch
->is_rename
);
3198 static int write_out_one_reject(struct patch
*patch
)
3201 char namebuf
[PATH_MAX
];
3202 struct fragment
*frag
;
3205 for (cnt
= 0, frag
= patch
->fragments
; frag
; frag
= frag
->next
) {
3206 if (!frag
->rejected
)
3212 if (apply_verbosely
)
3213 say_patch_name(stderr
,
3214 "Applied patch ", patch
, " cleanly.\n");
3218 /* This should not happen, because a removal patch that leaves
3219 * contents are marked "rejected" at the patch level.
3221 if (!patch
->new_name
)
3222 die("internal error");
3224 /* Say this even without --verbose */
3225 say_patch_name(stderr
, "Applying patch ", patch
, " with");
3226 fprintf(stderr
, " %d rejects...\n", cnt
);
3228 cnt
= strlen(patch
->new_name
);
3229 if (ARRAY_SIZE(namebuf
) <= cnt
+ 5) {
3230 cnt
= ARRAY_SIZE(namebuf
) - 5;
3231 warning("truncating .rej filename to %.*s.rej",
3232 cnt
- 1, patch
->new_name
);
3234 memcpy(namebuf
, patch
->new_name
, cnt
);
3235 memcpy(namebuf
+ cnt
, ".rej", 5);
3237 rej
= fopen(namebuf
, "w");
3239 return error("cannot open %s: %s", namebuf
, strerror(errno
));
3241 /* Normal git tools never deal with .rej, so do not pretend
3242 * this is a git patch by saying --git nor give extended
3243 * headers. While at it, maybe please "kompare" that wants
3244 * the trailing TAB and some garbage at the end of line ;-).
3246 fprintf(rej
, "diff a/%s b/%s\t(rejected hunks)\n",
3247 patch
->new_name
, patch
->new_name
);
3248 for (cnt
= 1, frag
= patch
->fragments
;
3250 cnt
++, frag
= frag
->next
) {
3251 if (!frag
->rejected
) {
3252 fprintf(stderr
, "Hunk #%d applied cleanly.\n", cnt
);
3255 fprintf(stderr
, "Rejected hunk #%d.\n", cnt
);
3256 fprintf(rej
, "%.*s", frag
->size
, frag
->patch
);
3257 if (frag
->patch
[frag
->size
-1] != '\n')
3264 static int write_out_results(struct patch
*list
, int skipped_patch
)
3270 if (!list
&& !skipped_patch
)
3271 return error("No changes");
3273 for (phase
= 0; phase
< 2; phase
++) {
3279 write_out_one_result(l
, phase
);
3280 if (phase
== 1 && write_out_one_reject(l
))
3289 static struct lock_file lock_file
;
3291 static struct string_list limit_by_name
;
3292 static int has_include
;
3293 static void add_name_limit(const char *name
, int exclude
)
3295 struct string_list_item
*it
;
3297 it
= string_list_append(name
, &limit_by_name
);
3298 it
->util
= exclude
? NULL
: (void *) 1;
3301 static int use_patch(struct patch
*p
)
3303 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
3306 /* Paths outside are not touched regardless of "--include" */
3307 if (0 < prefix_length
) {
3308 int pathlen
= strlen(pathname
);
3309 if (pathlen
<= prefix_length
||
3310 memcmp(prefix
, pathname
, prefix_length
))
3314 /* See if it matches any of exclude/include rule */
3315 for (i
= 0; i
< limit_by_name
.nr
; i
++) {
3316 struct string_list_item
*it
= &limit_by_name
.items
[i
];
3317 if (!fnmatch(it
->string
, pathname
, 0))
3318 return (it
->util
!= NULL
);
3322 * If we had any include, a path that does not match any rule is
3323 * not used. Otherwise, we saw bunch of exclude rules (or none)
3324 * and such a path is used.
3326 return !has_include
;
3330 static void prefix_one(char **name
)
3332 char *old_name
= *name
;
3335 *name
= xstrdup(prefix_filename(prefix
, prefix_length
, *name
));
3339 static void prefix_patches(struct patch
*p
)
3341 if (!prefix
|| p
->is_toplevel_relative
)
3343 for ( ; p
; p
= p
->next
) {
3344 if (p
->new_name
== p
->old_name
) {
3345 char *prefixed
= p
->new_name
;
3346 prefix_one(&prefixed
);
3347 p
->new_name
= p
->old_name
= prefixed
;
3350 prefix_one(&p
->new_name
);
3351 prefix_one(&p
->old_name
);
3356 #define INACCURATE_EOF (1<<0)
3357 #define RECOUNT (1<<1)
3359 static int apply_patch(int fd
, const char *filename
, int options
)
3362 struct strbuf buf
= STRBUF_INIT
;
3363 struct patch
*list
= NULL
, **listp
= &list
;
3364 int skipped_patch
= 0;
3366 /* FIXME - memory leak when using multiple patch files as inputs */
3367 memset(&fn_table
, 0, sizeof(struct string_list
));
3368 patch_input_file
= filename
;
3369 read_patch_file(&buf
, fd
);
3371 while (offset
< buf
.len
) {
3372 struct patch
*patch
;
3375 patch
= xcalloc(1, sizeof(*patch
));
3376 patch
->inaccurate_eof
= !!(options
& INACCURATE_EOF
);
3377 patch
->recount
= !!(options
& RECOUNT
);
3378 nr
= parse_chunk(buf
.buf
+ offset
, buf
.len
- offset
, patch
);
3381 if (apply_in_reverse
)
3382 reverse_patches(patch
);
3384 prefix_patches(patch
);
3385 if (use_patch(patch
)) {
3388 listp
= &patch
->next
;
3391 /* perhaps free it a bit better? */
3398 if (whitespace_error
&& (ws_error_action
== die_on_ws_error
))
3401 update_index
= check_index
&& apply
;
3402 if (update_index
&& newfd
< 0)
3403 newfd
= hold_locked_index(&lock_file
, 1);
3406 if (read_cache() < 0)
3407 die("unable to read index file");
3410 if ((check
|| apply
) &&
3411 check_patch_list(list
) < 0 &&
3415 if (apply
&& write_out_results(list
, skipped_patch
))
3419 build_fake_ancestor(list
, fake_ancestor
);
3422 stat_patch_list(list
);
3425 numstat_patch_list(list
);
3428 summary_patch_list(list
);
3430 strbuf_release(&buf
);
3434 static int git_apply_config(const char *var
, const char *value
, void *cb
)
3436 if (!strcmp(var
, "apply.whitespace"))
3437 return git_config_string(&apply_default_whitespace
, var
, value
);
3438 else if (!strcmp(var
, "apply.ignorewhitespace"))
3439 return git_config_string(&apply_default_ignorewhitespace
, var
, value
);
3440 return git_default_config(var
, value
, cb
);
3443 static int option_parse_exclude(const struct option
*opt
,
3444 const char *arg
, int unset
)
3446 add_name_limit(arg
, 1);
3450 static int option_parse_include(const struct option
*opt
,
3451 const char *arg
, int unset
)
3453 add_name_limit(arg
, 0);
3458 static int option_parse_p(const struct option
*opt
,
3459 const char *arg
, int unset
)
3461 p_value
= atoi(arg
);
3466 static int option_parse_z(const struct option
*opt
,
3467 const char *arg
, int unset
)
3470 line_termination
= '\n';
3472 line_termination
= 0;
3476 static int option_parse_space_change(const struct option
*opt
,
3477 const char *arg
, int unset
)
3480 ws_ignore_action
= ignore_ws_none
;
3482 ws_ignore_action
= ignore_ws_change
;
3486 static int option_parse_whitespace(const struct option
*opt
,
3487 const char *arg
, int unset
)
3489 const char **whitespace_option
= opt
->value
;
3491 *whitespace_option
= arg
;
3492 parse_whitespace_option(arg
);
3496 static int option_parse_directory(const struct option
*opt
,
3497 const char *arg
, int unset
)
3499 root_len
= strlen(arg
);
3500 if (root_len
&& arg
[root_len
- 1] != '/') {
3502 root
= new_root
= xmalloc(root_len
+ 2);
3503 strcpy(new_root
, arg
);
3504 strcpy(new_root
+ root_len
++, "/");
3510 int cmd_apply(int argc
, const char **argv
, const char *unused_prefix
)
3516 int force_apply
= 0;
3518 const char *whitespace_option
= NULL
;
3520 struct option builtin_apply_options
[] = {
3521 { OPTION_CALLBACK
, 0, "exclude", NULL
, "path",
3522 "don't apply changes matching the given path",
3523 0, option_parse_exclude
},
3524 { OPTION_CALLBACK
, 0, "include", NULL
, "path",
3525 "apply changes matching the given path",
3526 0, option_parse_include
},
3527 { OPTION_CALLBACK
, 'p', NULL
, NULL
, "num",
3528 "remove <num> leading slashes from traditional diff paths",
3529 0, option_parse_p
},
3530 OPT_BOOLEAN(0, "no-add", &no_add
,
3531 "ignore additions made by the patch"),
3532 OPT_BOOLEAN(0, "stat", &diffstat
,
3533 "instead of applying the patch, output diffstat for the input"),
3534 { OPTION_BOOLEAN
, 0, "allow-binary-replacement", &binary
,
3535 NULL
, "old option, now no-op",
3536 PARSE_OPT_HIDDEN
| PARSE_OPT_NOARG
},
3537 { OPTION_BOOLEAN
, 0, "binary", &binary
,
3538 NULL
, "old option, now no-op",
3539 PARSE_OPT_HIDDEN
| PARSE_OPT_NOARG
},
3540 OPT_BOOLEAN(0, "numstat", &numstat
,
3541 "shows number of added and deleted lines in decimal notation"),
3542 OPT_BOOLEAN(0, "summary", &summary
,
3543 "instead of applying the patch, output a summary for the input"),
3544 OPT_BOOLEAN(0, "check", &check
,
3545 "instead of applying the patch, see if the patch is applicable"),
3546 OPT_BOOLEAN(0, "index", &check_index
,
3547 "make sure the patch is applicable to the current index"),
3548 OPT_BOOLEAN(0, "cached", &cached
,
3549 "apply a patch without touching the working tree"),
3550 OPT_BOOLEAN(0, "apply", &force_apply
,
3551 "also apply the patch (use with --stat/--summary/--check)"),
3552 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor
,
3553 "build a temporary index based on embedded index information"),
3554 { OPTION_CALLBACK
, 'z', NULL
, NULL
, NULL
,
3555 "paths are separated with NUL character",
3556 PARSE_OPT_NOARG
, option_parse_z
},
3557 OPT_INTEGER('C', NULL
, &p_context
,
3558 "ensure at least <n> lines of context match"),
3559 { OPTION_CALLBACK
, 0, "whitespace", &whitespace_option
, "action",
3560 "detect new or modified lines that have whitespace errors",
3561 0, option_parse_whitespace
},
3562 { OPTION_CALLBACK
, 0, "ignore-space-change", NULL
, NULL
,
3563 "ignore changes in whitespace when finding context",
3564 PARSE_OPT_NOARG
, option_parse_space_change
},
3565 { OPTION_CALLBACK
, 0, "ignore-whitespace", NULL
, NULL
,
3566 "ignore changes in whitespace when finding context",
3567 PARSE_OPT_NOARG
, option_parse_space_change
},
3568 OPT_BOOLEAN('R', "reverse", &apply_in_reverse
,
3569 "apply the patch in reverse"),
3570 OPT_BOOLEAN(0, "unidiff-zero", &unidiff_zero
,
3571 "don't expect at least one line of context"),
3572 OPT_BOOLEAN(0, "reject", &apply_with_reject
,
3573 "leave the rejected hunks in corresponding *.rej files"),
3574 OPT__VERBOSE(&apply_verbosely
),
3575 OPT_BIT(0, "inaccurate-eof", &options
,
3576 "tolerate incorrectly detected missing new-line at the end of file",
3578 OPT_BIT(0, "recount", &options
,
3579 "do not trust the line counts in the hunk headers",
3581 { OPTION_CALLBACK
, 0, "directory", NULL
, "root",
3582 "prepend <root> to all filenames",
3583 0, option_parse_directory
},
3587 prefix
= setup_git_directory_gently(&is_not_gitdir
);
3588 prefix_length
= prefix
? strlen(prefix
) : 0;
3589 git_config(git_apply_config
, NULL
);
3590 if (apply_default_whitespace
)
3591 parse_whitespace_option(apply_default_whitespace
);
3592 if (apply_default_ignorewhitespace
)
3593 parse_ignorewhitespace_option(apply_default_ignorewhitespace
);
3595 argc
= parse_options(argc
, argv
, prefix
, builtin_apply_options
,
3598 if (apply_with_reject
)
3599 apply
= apply_verbosely
= 1;
3600 if (!force_apply
&& (diffstat
|| numstat
|| summary
|| check
|| fake_ancestor
))
3602 if (check_index
&& is_not_gitdir
)
3603 die("--index outside a repository");
3606 die("--cached outside a repository");
3609 for (i
= 0; i
< argc
; i
++) {
3610 const char *arg
= argv
[i
];
3613 if (!strcmp(arg
, "-")) {
3614 errs
|= apply_patch(0, "<stdin>", options
);
3617 } else if (0 < prefix_length
)
3618 arg
= prefix_filename(prefix
, prefix_length
, arg
);
3620 fd
= open(arg
, O_RDONLY
);
3622 die_errno("can't open patch '%s'", arg
);
3624 set_default_whitespace_mode(whitespace_option
);
3625 errs
|= apply_patch(fd
, arg
, options
);
3628 set_default_whitespace_mode(whitespace_option
);
3630 errs
|= apply_patch(0, "<stdin>", options
);
3631 if (whitespace_error
) {
3632 if (squelch_whitespace_errors
&&
3633 squelch_whitespace_errors
< whitespace_error
) {
3635 whitespace_error
- squelch_whitespace_errors
;
3636 warning("squelched %d "
3637 "whitespace error%s",
3639 squelched
== 1 ? "" : "s");
3641 if (ws_error_action
== die_on_ws_error
)
3642 die("%d line%s add%s whitespace errors.",
3644 whitespace_error
== 1 ? "" : "s",
3645 whitespace_error
== 1 ? "s" : "");
3646 if (applied_after_fixing_ws
&& apply
)
3647 warning("%d line%s applied after"
3648 " fixing whitespace errors.",
3649 applied_after_fixing_ws
,
3650 applied_after_fixing_ws
== 1 ? "" : "s");
3651 else if (whitespace_error
)
3652 warning("%d line%s add%s whitespace errors.",
3654 whitespace_error
== 1 ? "" : "s",
3655 whitespace_error
== 1 ? "s" : "");
3659 if (write_cache(newfd
, active_cache
, active_nr
) ||
3660 commit_locked_index(&lock_file
))
3661 die("Unable to write new index file");