4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
10 #include "cache-tree.h"
15 #include "string-list.h"
17 #include "parse-options.h"
20 * --check turns on checking that the working tree matches the
21 * files that are being modified, but doesn't apply the patch
22 * --stat does just a diffstat, and doesn't actually apply
23 * --numstat does numeric diffstat, and doesn't actually apply
24 * --index-info shows the old and new index info for paths if available.
25 * --index updates the cache as well.
26 * --cached updates only the cache without ever touching the working tree.
28 static const char *prefix
;
29 static int prefix_length
= -1;
30 static int newfd
= -1;
32 static int unidiff_zero
;
33 static int p_value
= 1;
34 static int p_value_known
;
35 static int check_index
;
36 static int update_index
;
43 static int apply_in_reverse
;
44 static int apply_with_reject
;
45 static int apply_verbosely
;
47 static const char *fake_ancestor
;
48 static int line_termination
= '\n';
49 static unsigned int p_context
= UINT_MAX
;
50 static const char * const apply_usage
[] = {
51 "git apply [options] [<patch>...]",
55 static enum ws_error_action
{
60 } ws_error_action
= warn_on_ws_error
;
61 static int whitespace_error
;
62 static int squelch_whitespace_errors
= 5;
63 static int applied_after_fixing_ws
;
65 static enum ws_ignore
{
68 } ws_ignore_action
= ignore_ws_none
;
71 static const char *patch_input_file
;
72 static const char *root
;
74 static int read_stdin
= 1;
77 static void parse_whitespace_option(const char *option
)
80 ws_error_action
= warn_on_ws_error
;
83 if (!strcmp(option
, "warn")) {
84 ws_error_action
= warn_on_ws_error
;
87 if (!strcmp(option
, "nowarn")) {
88 ws_error_action
= nowarn_ws_error
;
91 if (!strcmp(option
, "error")) {
92 ws_error_action
= die_on_ws_error
;
95 if (!strcmp(option
, "error-all")) {
96 ws_error_action
= die_on_ws_error
;
97 squelch_whitespace_errors
= 0;
100 if (!strcmp(option
, "strip") || !strcmp(option
, "fix")) {
101 ws_error_action
= correct_ws_error
;
104 die("unrecognized whitespace option '%s'", option
);
107 static void parse_ignorewhitespace_option(const char *option
)
109 if (!option
|| !strcmp(option
, "no") ||
110 !strcmp(option
, "false") || !strcmp(option
, "never") ||
111 !strcmp(option
, "none")) {
112 ws_ignore_action
= ignore_ws_none
;
115 if (!strcmp(option
, "change")) {
116 ws_ignore_action
= ignore_ws_change
;
119 die("unrecognized whitespace ignore option '%s'", option
);
122 static void set_default_whitespace_mode(const char *whitespace_option
)
124 if (!whitespace_option
&& !apply_default_whitespace
)
125 ws_error_action
= (apply
? warn_on_ws_error
: nowarn_ws_error
);
129 * For "diff-stat" like behaviour, we keep track of the biggest change
130 * we've seen, and the longest filename. That allows us to do simple
133 static int max_change
, max_len
;
136 * Various "current state", notably line numbers and what
137 * file (and how) we're patching right now.. The "is_xxxx"
138 * things are flags, where -1 means "don't know yet".
140 static int linenr
= 1;
143 * This represents one "hunk" from a patch, starting with
144 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
145 * patch text is pointed at by patch, and its byte length
146 * is stored in size. leading and trailing are the number
150 unsigned long leading
, trailing
;
151 unsigned long oldpos
, oldlines
;
152 unsigned long newpos
, newlines
;
156 struct fragment
*next
;
160 * When dealing with a binary patch, we reuse "leading" field
161 * to store the type of the binary hunk, either deflated "delta"
162 * or deflated "literal".
164 #define binary_patch_method leading
165 #define BINARY_DELTA_DEFLATED 1
166 #define BINARY_LITERAL_DEFLATED 2
169 * This represents a "patch" to a file, both metainfo changes
170 * such as creation/deletion, filemode and content changes represented
171 * as a series of fragments.
174 char *new_name
, *old_name
, *def_name
;
175 unsigned int old_mode
, new_mode
;
176 int is_new
, is_delete
; /* -1 = unknown, 0 = false, 1 = true */
179 unsigned long deflate_origlen
;
180 int lines_added
, lines_deleted
;
182 unsigned int is_toplevel_relative
:1;
183 unsigned int inaccurate_eof
:1;
184 unsigned int is_binary
:1;
185 unsigned int is_copy
:1;
186 unsigned int is_rename
:1;
187 unsigned int recount
:1;
188 struct fragment
*fragments
;
191 char old_sha1_prefix
[41];
192 char new_sha1_prefix
[41];
197 * A line in a file, len-bytes long (includes the terminating LF,
198 * except for an incomplete line at the end if the file ends with
199 * one), and its contents hashes to 'hash'.
205 #define LINE_COMMON 1
209 * This represents a "file", which is an array of "lines".
216 struct line
*line_allocated
;
221 * Records filenames that have been touched, in order to handle
222 * the case where more than one patches touch the same file.
225 static struct string_list fn_table
;
227 static uint32_t hash_line(const char *cp
, size_t len
)
231 for (i
= 0, h
= 0; i
< len
; i
++) {
232 if (!isspace(cp
[i
])) {
233 h
= h
* 3 + (cp
[i
] & 0xff);
240 * Compare lines s1 of length n1 and s2 of length n2, ignoring
241 * whitespace difference. Returns 1 if they match, 0 otherwise
243 static int fuzzy_matchlines(const char *s1
, size_t n1
,
244 const char *s2
, size_t n2
)
246 const char *last1
= s1
+ n1
- 1;
247 const char *last2
= s2
+ n2
- 1;
250 if (n1
< 0 || n2
< 0)
253 /* ignore line endings */
254 while ((*last1
== '\r') || (*last1
== '\n'))
256 while ((*last2
== '\r') || (*last2
== '\n'))
259 /* skip leading whitespace */
260 while (isspace(*s1
) && (s1
<= last1
))
262 while (isspace(*s2
) && (s2
<= last2
))
264 /* early return if both lines are empty */
265 if ((s1
> last1
) && (s2
> last2
))
268 result
= *s1
++ - *s2
++;
270 * Skip whitespace inside. We check for whitespace on
271 * both buffers because we don't want "a b" to match
274 if (isspace(*s1
) && isspace(*s2
)) {
275 while (isspace(*s1
) && s1
<= last1
)
277 while (isspace(*s2
) && s2
<= last2
)
281 * If we reached the end on one side only,
285 ((s2
> last2
) && (s1
<= last1
)) ||
286 ((s1
> last1
) && (s2
<= last2
)))
288 if ((s1
> last1
) && (s2
> last2
))
295 static void add_line_info(struct image
*img
, const char *bol
, size_t len
, unsigned flag
)
297 ALLOC_GROW(img
->line_allocated
, img
->nr
+ 1, img
->alloc
);
298 img
->line_allocated
[img
->nr
].len
= len
;
299 img
->line_allocated
[img
->nr
].hash
= hash_line(bol
, len
);
300 img
->line_allocated
[img
->nr
].flag
= flag
;
304 static void prepare_image(struct image
*image
, char *buf
, size_t len
,
305 int prepare_linetable
)
309 memset(image
, 0, sizeof(*image
));
313 if (!prepare_linetable
)
316 ep
= image
->buf
+ image
->len
;
320 for (next
= cp
; next
< ep
&& *next
!= '\n'; next
++)
324 add_line_info(image
, cp
, next
- cp
, 0);
327 image
->line
= image
->line_allocated
;
330 static void clear_image(struct image
*image
)
337 static void say_patch_name(FILE *output
, const char *pre
,
338 struct patch
*patch
, const char *post
)
341 if (patch
->old_name
&& patch
->new_name
&&
342 strcmp(patch
->old_name
, patch
->new_name
)) {
343 quote_c_style(patch
->old_name
, NULL
, output
, 0);
344 fputs(" => ", output
);
345 quote_c_style(patch
->new_name
, NULL
, output
, 0);
347 const char *n
= patch
->new_name
;
350 quote_c_style(n
, NULL
, output
, 0);
355 #define CHUNKSIZE (8192)
358 static void read_patch_file(struct strbuf
*sb
, int fd
)
360 if (strbuf_read(sb
, fd
, 0) < 0)
361 die_errno("git apply: failed to read");
364 * Make sure that we have some slop in the buffer
365 * so that we can do speculative "memcmp" etc, and
366 * see to it that it is NUL-filled.
368 strbuf_grow(sb
, SLOP
);
369 memset(sb
->buf
+ sb
->len
, 0, SLOP
);
372 static unsigned long linelen(const char *buffer
, unsigned long size
)
374 unsigned long len
= 0;
377 if (*buffer
++ == '\n')
383 static int is_dev_null(const char *str
)
385 return !memcmp("/dev/null", str
, 9) && isspace(str
[9]);
391 static int name_terminate(const char *name
, int namelen
, int c
, int terminate
)
393 if (c
== ' ' && !(terminate
& TERM_SPACE
))
395 if (c
== '\t' && !(terminate
& TERM_TAB
))
401 /* remove double slashes to make --index work with such filenames */
402 static char *squash_slash(char *name
)
407 if ((name
[j
++] = name
[i
++]) == '/')
408 while (name
[i
] == '/')
415 static char *find_name(const char *line
, char *def
, int p_value
, int terminate
)
418 const char *start
= line
;
421 struct strbuf name
= STRBUF_INIT
;
424 * Proposed "new-style" GNU patch/diff format; see
425 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
427 if (!unquote_c_style(&name
, line
, NULL
)) {
430 for (cp
= name
.buf
; p_value
; p_value
--) {
431 cp
= strchr(cp
, '/');
437 /* name can later be freed, so we need
438 * to memmove, not just return cp
440 strbuf_remove(&name
, 0, cp
- name
.buf
);
443 strbuf_insert(&name
, 0, root
, root_len
);
444 return squash_slash(strbuf_detach(&name
, NULL
));
447 strbuf_release(&name
);
456 if (name_terminate(start
, line
-start
, c
, terminate
))
460 if (c
== '/' && !--p_value
)
464 return squash_slash(def
);
467 return squash_slash(def
);
470 * Generally we prefer the shorter name, especially
471 * if the other one is just a variation of that with
472 * something else tacked on to the end (ie "file.orig"
476 int deflen
= strlen(def
);
477 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
478 return squash_slash(def
);
483 char *ret
= xmalloc(root_len
+ len
+ 1);
485 memcpy(ret
+ root_len
, start
, len
);
486 ret
[root_len
+ len
] = '\0';
487 return squash_slash(ret
);
490 return squash_slash(xmemdupz(start
, len
));
493 static int count_slashes(const char *cp
)
505 * Given the string after "--- " or "+++ ", guess the appropriate
506 * p_value for the given patch.
508 static int guess_p_value(const char *nameline
)
513 if (is_dev_null(nameline
))
515 name
= find_name(nameline
, NULL
, 0, TERM_SPACE
| TERM_TAB
);
518 cp
= strchr(name
, '/');
523 * Does it begin with "a/$our-prefix" and such? Then this is
524 * very likely to apply to our directory.
526 if (!strncmp(name
, prefix
, prefix_length
))
527 val
= count_slashes(prefix
);
530 if (!strncmp(cp
, prefix
, prefix_length
))
531 val
= count_slashes(prefix
) + 1;
539 * Does the ---/+++ line has the POSIX timestamp after the last HT?
540 * GNU diff puts epoch there to signal a creation/deletion event. Is
541 * this such a timestamp?
543 static int has_epoch_timestamp(const char *nameline
)
546 * We are only interested in epoch timestamp; any non-zero
547 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
548 * For the same reason, the date must be either 1969-12-31 or
549 * 1970-01-01, and the seconds part must be "00".
551 const char stamp_regexp
[] =
552 "^(1969-12-31|1970-01-01)"
554 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
556 "([-+][0-2][0-9][0-5][0-9])\n";
557 const char *timestamp
= NULL
, *cp
;
558 static regex_t
*stamp
;
564 for (cp
= nameline
; *cp
!= '\n'; cp
++) {
571 stamp
= xmalloc(sizeof(*stamp
));
572 if (regcomp(stamp
, stamp_regexp
, REG_EXTENDED
)) {
573 warning("Cannot prepare timestamp regexp %s",
579 status
= regexec(stamp
, timestamp
, ARRAY_SIZE(m
), m
, 0);
581 if (status
!= REG_NOMATCH
)
582 warning("regexec returned %d for input: %s",
587 zoneoffset
= strtol(timestamp
+ m
[3].rm_so
+ 1, NULL
, 10);
588 zoneoffset
= (zoneoffset
/ 100) * 60 + (zoneoffset
% 100);
589 if (timestamp
[m
[3].rm_so
] == '-')
590 zoneoffset
= -zoneoffset
;
593 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
594 * (west of GMT) or 1970-01-01 (east of GMT)
596 if ((zoneoffset
< 0 && memcmp(timestamp
, "1969-12-31", 10)) ||
597 (0 <= zoneoffset
&& memcmp(timestamp
, "1970-01-01", 10)))
600 hourminute
= (strtol(timestamp
+ 11, NULL
, 10) * 60 +
601 strtol(timestamp
+ 14, NULL
, 10) -
604 return ((zoneoffset
< 0 && hourminute
== 1440) ||
605 (0 <= zoneoffset
&& !hourminute
));
609 * Get the name etc info from the ---/+++ lines of a traditional patch header
611 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
612 * files, we can happily check the index for a match, but for creating a
613 * new file we should try to match whatever "patch" does. I have no idea.
615 static void parse_traditional_patch(const char *first
, const char *second
, struct patch
*patch
)
619 first
+= 4; /* skip "--- " */
620 second
+= 4; /* skip "+++ " */
621 if (!p_value_known
) {
623 p
= guess_p_value(first
);
624 q
= guess_p_value(second
);
626 if (0 <= p
&& p
== q
) {
631 if (is_dev_null(first
)) {
633 patch
->is_delete
= 0;
634 name
= find_name(second
, NULL
, p_value
, TERM_SPACE
| TERM_TAB
);
635 patch
->new_name
= name
;
636 } else if (is_dev_null(second
)) {
638 patch
->is_delete
= 1;
639 name
= find_name(first
, NULL
, p_value
, TERM_SPACE
| TERM_TAB
);
640 patch
->old_name
= name
;
642 name
= find_name(first
, NULL
, p_value
, TERM_SPACE
| TERM_TAB
);
643 name
= find_name(second
, name
, p_value
, TERM_SPACE
| TERM_TAB
);
644 if (has_epoch_timestamp(first
)) {
646 patch
->is_delete
= 0;
647 patch
->new_name
= name
;
648 } else if (has_epoch_timestamp(second
)) {
650 patch
->is_delete
= 1;
651 patch
->old_name
= name
;
653 patch
->old_name
= patch
->new_name
= name
;
657 die("unable to find filename in patch at line %d", linenr
);
660 static int gitdiff_hdrend(const char *line
, struct patch
*patch
)
666 * We're anal about diff header consistency, to make
667 * sure that we don't end up having strange ambiguous
668 * patches floating around.
670 * As a result, gitdiff_{old|new}name() will check
671 * their names against any previous information, just
674 static char *gitdiff_verify_name(const char *line
, int isnull
, char *orig_name
, const char *oldnew
)
676 if (!orig_name
&& !isnull
)
677 return find_name(line
, NULL
, p_value
, TERM_TAB
);
686 die("git apply: bad git-diff - expected /dev/null, got %s on line %d", name
, linenr
);
687 another
= find_name(line
, NULL
, p_value
, TERM_TAB
);
688 if (!another
|| memcmp(another
, name
, len
))
689 die("git apply: bad git-diff - inconsistent %s filename on line %d", oldnew
, linenr
);
694 /* expect "/dev/null" */
695 if (memcmp("/dev/null", line
, 9) || line
[9] != '\n')
696 die("git apply: bad git-diff - expected /dev/null on line %d", linenr
);
701 static int gitdiff_oldname(const char *line
, struct patch
*patch
)
703 patch
->old_name
= gitdiff_verify_name(line
, patch
->is_new
, patch
->old_name
, "old");
707 static int gitdiff_newname(const char *line
, struct patch
*patch
)
709 patch
->new_name
= gitdiff_verify_name(line
, patch
->is_delete
, patch
->new_name
, "new");
713 static int gitdiff_oldmode(const char *line
, struct patch
*patch
)
715 patch
->old_mode
= strtoul(line
, NULL
, 8);
719 static int gitdiff_newmode(const char *line
, struct patch
*patch
)
721 patch
->new_mode
= strtoul(line
, NULL
, 8);
725 static int gitdiff_delete(const char *line
, struct patch
*patch
)
727 patch
->is_delete
= 1;
728 patch
->old_name
= patch
->def_name
;
729 return gitdiff_oldmode(line
, patch
);
732 static int gitdiff_newfile(const char *line
, struct patch
*patch
)
735 patch
->new_name
= patch
->def_name
;
736 return gitdiff_newmode(line
, patch
);
739 static int gitdiff_copysrc(const char *line
, struct patch
*patch
)
742 patch
->old_name
= find_name(line
, NULL
, 0, 0);
746 static int gitdiff_copydst(const char *line
, struct patch
*patch
)
749 patch
->new_name
= find_name(line
, NULL
, 0, 0);
753 static int gitdiff_renamesrc(const char *line
, struct patch
*patch
)
755 patch
->is_rename
= 1;
756 patch
->old_name
= find_name(line
, NULL
, 0, 0);
760 static int gitdiff_renamedst(const char *line
, struct patch
*patch
)
762 patch
->is_rename
= 1;
763 patch
->new_name
= find_name(line
, NULL
, 0, 0);
767 static int gitdiff_similarity(const char *line
, struct patch
*patch
)
769 if ((patch
->score
= strtoul(line
, NULL
, 10)) == ULONG_MAX
)
774 static int gitdiff_dissimilarity(const char *line
, struct patch
*patch
)
776 if ((patch
->score
= strtoul(line
, NULL
, 10)) == ULONG_MAX
)
781 static int gitdiff_index(const char *line
, struct patch
*patch
)
784 * index line is N hexadecimal, "..", N hexadecimal,
785 * and optional space with octal mode.
787 const char *ptr
, *eol
;
790 ptr
= strchr(line
, '.');
791 if (!ptr
|| ptr
[1] != '.' || 40 < ptr
- line
)
794 memcpy(patch
->old_sha1_prefix
, line
, len
);
795 patch
->old_sha1_prefix
[len
] = 0;
798 ptr
= strchr(line
, ' ');
799 eol
= strchr(line
, '\n');
801 if (!ptr
|| eol
< ptr
)
807 memcpy(patch
->new_sha1_prefix
, line
, len
);
808 patch
->new_sha1_prefix
[len
] = 0;
810 patch
->old_mode
= strtoul(ptr
+1, NULL
, 8);
815 * This is normal for a diff that doesn't change anything: we'll fall through
816 * into the next diff. Tell the parser to break out.
818 static int gitdiff_unrecognized(const char *line
, struct patch
*patch
)
823 static const char *stop_at_slash(const char *line
, int llen
)
827 for (i
= 0; i
< llen
; i
++) {
836 * This is to extract the same name that appears on "diff --git"
837 * line. We do not find and return anything if it is a rename
838 * patch, and it is OK because we will find the name elsewhere.
839 * We need to reliably find name only when it is mode-change only,
840 * creation or deletion of an empty file. In any of these cases,
841 * both sides are the same name under a/ and b/ respectively.
843 static char *git_header_name(char *line
, int llen
)
846 const char *second
= NULL
;
849 line
+= strlen("diff --git ");
850 llen
-= strlen("diff --git ");
854 struct strbuf first
= STRBUF_INIT
;
855 struct strbuf sp
= STRBUF_INIT
;
857 if (unquote_c_style(&first
, line
, &second
))
860 /* advance to the first slash */
861 cp
= stop_at_slash(first
.buf
, first
.len
);
862 /* we do not accept absolute paths */
863 if (!cp
|| cp
== first
.buf
)
865 strbuf_remove(&first
, 0, cp
+ 1 - first
.buf
);
868 * second points at one past closing dq of name.
869 * find the second name.
871 while ((second
< line
+ llen
) && isspace(*second
))
874 if (line
+ llen
<= second
)
876 if (*second
== '"') {
877 if (unquote_c_style(&sp
, second
, NULL
))
879 cp
= stop_at_slash(sp
.buf
, sp
.len
);
880 if (!cp
|| cp
== sp
.buf
)
882 /* They must match, otherwise ignore */
883 if (strcmp(cp
+ 1, first
.buf
))
886 return strbuf_detach(&first
, NULL
);
889 /* unquoted second */
890 cp
= stop_at_slash(second
, line
+ llen
- second
);
891 if (!cp
|| cp
== second
)
894 if (line
+ llen
- cp
!= first
.len
+ 1 ||
895 memcmp(first
.buf
, cp
, first
.len
))
897 return strbuf_detach(&first
, NULL
);
900 strbuf_release(&first
);
905 /* unquoted first name */
906 name
= stop_at_slash(line
, llen
);
907 if (!name
|| name
== line
)
912 * since the first name is unquoted, a dq if exists must be
913 * the beginning of the second name.
915 for (second
= name
; second
< line
+ llen
; second
++) {
916 if (*second
== '"') {
917 struct strbuf sp
= STRBUF_INIT
;
920 if (unquote_c_style(&sp
, second
, NULL
))
923 np
= stop_at_slash(sp
.buf
, sp
.len
);
924 if (!np
|| np
== sp
.buf
)
928 len
= sp
.buf
+ sp
.len
- np
;
929 if (len
< second
- name
&&
930 !strncmp(np
, name
, len
) &&
931 isspace(name
[len
])) {
933 strbuf_remove(&sp
, 0, np
- sp
.buf
);
934 return strbuf_detach(&sp
, NULL
);
944 * Accept a name only if it shows up twice, exactly the same
947 for (len
= 0 ; ; len
++) {
962 if (second
[len
] == '\n' && !memcmp(name
, second
, len
)) {
963 return xmemdupz(name
, len
);
969 /* Verify that we recognize the lines following a git header */
970 static int parse_git_header(char *line
, int len
, unsigned int size
, struct patch
*patch
)
972 unsigned long offset
;
974 /* A git diff has explicit new/delete information, so we don't guess */
976 patch
->is_delete
= 0;
979 * Some things may not have the old name in the
980 * rest of the headers anywhere (pure mode changes,
981 * or removing or adding empty files), so we get
982 * the default name from the header.
984 patch
->def_name
= git_header_name(line
, len
);
985 if (patch
->def_name
&& root
) {
986 char *s
= xmalloc(root_len
+ strlen(patch
->def_name
) + 1);
988 strcpy(s
+ root_len
, patch
->def_name
);
989 free(patch
->def_name
);
996 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
997 static const struct opentry
{
999 int (*fn
)(const char *, struct patch
*);
1001 { "@@ -", gitdiff_hdrend
},
1002 { "--- ", gitdiff_oldname
},
1003 { "+++ ", gitdiff_newname
},
1004 { "old mode ", gitdiff_oldmode
},
1005 { "new mode ", gitdiff_newmode
},
1006 { "deleted file mode ", gitdiff_delete
},
1007 { "new file mode ", gitdiff_newfile
},
1008 { "copy from ", gitdiff_copysrc
},
1009 { "copy to ", gitdiff_copydst
},
1010 { "rename old ", gitdiff_renamesrc
},
1011 { "rename new ", gitdiff_renamedst
},
1012 { "rename from ", gitdiff_renamesrc
},
1013 { "rename to ", gitdiff_renamedst
},
1014 { "similarity index ", gitdiff_similarity
},
1015 { "dissimilarity index ", gitdiff_dissimilarity
},
1016 { "index ", gitdiff_index
},
1017 { "", gitdiff_unrecognized
},
1021 len
= linelen(line
, size
);
1022 if (!len
|| line
[len
-1] != '\n')
1024 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
1025 const struct opentry
*p
= optable
+ i
;
1026 int oplen
= strlen(p
->str
);
1027 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
1029 if (p
->fn(line
+ oplen
, patch
) < 0)
1038 static int parse_num(const char *line
, unsigned long *p
)
1042 if (!isdigit(*line
))
1044 *p
= strtoul(line
, &ptr
, 10);
1048 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
1049 unsigned long *p1
, unsigned long *p2
)
1053 if (offset
< 0 || offset
>= len
)
1058 digits
= parse_num(line
, p1
);
1068 digits
= parse_num(line
+1, p2
);
1077 ex
= strlen(expect
);
1080 if (memcmp(line
, expect
, ex
))
1086 static void recount_diff(char *line
, int size
, struct fragment
*fragment
)
1088 int oldlines
= 0, newlines
= 0, ret
= 0;
1091 warning("recount: ignore empty hunk");
1096 int len
= linelen(line
, size
);
1104 case ' ': case '\n':
1116 ret
= size
< 3 || prefixcmp(line
, "@@ ");
1119 ret
= size
< 5 || prefixcmp(line
, "diff ");
1126 warning("recount: unexpected line: %.*s",
1127 (int)linelen(line
, size
), line
);
1132 fragment
->oldlines
= oldlines
;
1133 fragment
->newlines
= newlines
;
1137 * Parse a unified diff fragment header of the
1138 * form "@@ -a,b +c,d @@"
1140 static int parse_fragment_header(char *line
, int len
, struct fragment
*fragment
)
1144 if (!len
|| line
[len
-1] != '\n')
1147 /* Figure out the number of lines in a fragment */
1148 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
1149 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
1154 static int find_header(char *line
, unsigned long size
, int *hdrsize
, struct patch
*patch
)
1156 unsigned long offset
, len
;
1158 patch
->is_toplevel_relative
= 0;
1159 patch
->is_rename
= patch
->is_copy
= 0;
1160 patch
->is_new
= patch
->is_delete
= -1;
1161 patch
->old_mode
= patch
->new_mode
= 0;
1162 patch
->old_name
= patch
->new_name
= NULL
;
1163 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1164 unsigned long nextlen
;
1166 len
= linelen(line
, size
);
1170 /* Testing this early allows us to take a few shortcuts.. */
1175 * Make sure we don't find any unconnected patch fragments.
1176 * That's a sign that we didn't find a header, and that a
1177 * patch has become corrupted/broken up.
1179 if (!memcmp("@@ -", line
, 4)) {
1180 struct fragment dummy
;
1181 if (parse_fragment_header(line
, len
, &dummy
) < 0)
1183 die("patch fragment without header at line %d: %.*s",
1184 linenr
, (int)len
-1, line
);
1191 * Git patch? It might not have a real patch, just a rename
1192 * or mode change, so we handle that specially
1194 if (!memcmp("diff --git ", line
, 11)) {
1195 int git_hdr_len
= parse_git_header(line
, len
, size
, patch
);
1196 if (git_hdr_len
<= len
)
1198 if (!patch
->old_name
&& !patch
->new_name
) {
1199 if (!patch
->def_name
)
1200 die("git diff header lacks filename information (line %d)", linenr
);
1201 patch
->old_name
= patch
->new_name
= patch
->def_name
;
1203 patch
->is_toplevel_relative
= 1;
1204 *hdrsize
= git_hdr_len
;
1208 /* --- followed by +++ ? */
1209 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
1213 * We only accept unified patches, so we want it to
1214 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1215 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1217 nextlen
= linelen(line
+ len
, size
- len
);
1218 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
1221 /* Ok, we'll consider it a patch */
1222 parse_traditional_patch(line
, line
+len
, patch
);
1223 *hdrsize
= len
+ nextlen
;
1230 static void check_whitespace(const char *line
, int len
, unsigned ws_rule
)
1233 unsigned result
= ws_check(line
+ 1, len
- 1, ws_rule
);
1238 if (squelch_whitespace_errors
&&
1239 squelch_whitespace_errors
< whitespace_error
)
1242 err
= whitespace_error_string(result
);
1243 fprintf(stderr
, "%s:%d: %s.\n%.*s\n",
1244 patch_input_file
, linenr
, err
, len
- 2, line
+ 1);
1250 * Parse a unified diff. Note that this really needs to parse each
1251 * fragment separately, since the only way to know the difference
1252 * between a "---" that is part of a patch, and a "---" that starts
1253 * the next patch is to look at the line counts..
1255 static int parse_fragment(char *line
, unsigned long size
,
1256 struct patch
*patch
, struct fragment
*fragment
)
1259 int len
= linelen(line
, size
), offset
;
1260 unsigned long oldlines
, newlines
;
1261 unsigned long leading
, trailing
;
1263 offset
= parse_fragment_header(line
, len
, fragment
);
1266 if (offset
> 0 && patch
->recount
)
1267 recount_diff(line
+ offset
, size
- offset
, fragment
);
1268 oldlines
= fragment
->oldlines
;
1269 newlines
= fragment
->newlines
;
1273 /* Parse the thing.. */
1277 added
= deleted
= 0;
1280 offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1281 if (!oldlines
&& !newlines
)
1283 len
= linelen(line
, size
);
1284 if (!len
|| line
[len
-1] != '\n')
1289 case '\n': /* newer GNU diff, an empty context line */
1293 if (!deleted
&& !added
)
1298 if (apply_in_reverse
&&
1299 ws_error_action
!= nowarn_ws_error
)
1300 check_whitespace(line
, len
, patch
->ws_rule
);
1306 if (!apply_in_reverse
&&
1307 ws_error_action
!= nowarn_ws_error
)
1308 check_whitespace(line
, len
, patch
->ws_rule
);
1315 * We allow "\ No newline at end of file". Depending
1316 * on locale settings when the patch was produced we
1317 * don't know what this line looks like. The only
1318 * thing we do know is that it begins with "\ ".
1319 * Checking for 12 is just for sanity check -- any
1320 * l10n of "\ No newline..." is at least that long.
1323 if (len
< 12 || memcmp(line
, "\\ ", 2))
1328 if (oldlines
|| newlines
)
1330 fragment
->leading
= leading
;
1331 fragment
->trailing
= trailing
;
1334 * If a fragment ends with an incomplete line, we failed to include
1335 * it in the above loop because we hit oldlines == newlines == 0
1338 if (12 < size
&& !memcmp(line
, "\\ ", 2))
1339 offset
+= linelen(line
, size
);
1341 patch
->lines_added
+= added
;
1342 patch
->lines_deleted
+= deleted
;
1344 if (0 < patch
->is_new
&& oldlines
)
1345 return error("new file depends on old contents");
1346 if (0 < patch
->is_delete
&& newlines
)
1347 return error("deleted file still has contents");
1351 static int parse_single_patch(char *line
, unsigned long size
, struct patch
*patch
)
1353 unsigned long offset
= 0;
1354 unsigned long oldlines
= 0, newlines
= 0, context
= 0;
1355 struct fragment
**fragp
= &patch
->fragments
;
1357 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
1358 struct fragment
*fragment
;
1361 fragment
= xcalloc(1, sizeof(*fragment
));
1362 len
= parse_fragment(line
, size
, patch
, fragment
);
1364 die("corrupt patch at line %d", linenr
);
1365 fragment
->patch
= line
;
1366 fragment
->size
= len
;
1367 oldlines
+= fragment
->oldlines
;
1368 newlines
+= fragment
->newlines
;
1369 context
+= fragment
->leading
+ fragment
->trailing
;
1372 fragp
= &fragment
->next
;
1380 * If something was removed (i.e. we have old-lines) it cannot
1381 * be creation, and if something was added it cannot be
1382 * deletion. However, the reverse is not true; --unified=0
1383 * patches that only add are not necessarily creation even
1384 * though they do not have any old lines, and ones that only
1385 * delete are not necessarily deletion.
1387 * Unfortunately, a real creation/deletion patch do _not_ have
1388 * any context line by definition, so we cannot safely tell it
1389 * apart with --unified=0 insanity. At least if the patch has
1390 * more than one hunk it is not creation or deletion.
1392 if (patch
->is_new
< 0 &&
1393 (oldlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1395 if (patch
->is_delete
< 0 &&
1396 (newlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1397 patch
->is_delete
= 0;
1399 if (0 < patch
->is_new
&& oldlines
)
1400 die("new file %s depends on old contents", patch
->new_name
);
1401 if (0 < patch
->is_delete
&& newlines
)
1402 die("deleted file %s still has contents", patch
->old_name
);
1403 if (!patch
->is_delete
&& !newlines
&& context
)
1404 fprintf(stderr
, "** warning: file %s becomes empty but "
1405 "is not deleted\n", patch
->new_name
);
1410 static inline int metadata_changes(struct patch
*patch
)
1412 return patch
->is_rename
> 0 ||
1413 patch
->is_copy
> 0 ||
1414 patch
->is_new
> 0 ||
1416 (patch
->old_mode
&& patch
->new_mode
&&
1417 patch
->old_mode
!= patch
->new_mode
);
1420 static char *inflate_it(const void *data
, unsigned long size
,
1421 unsigned long inflated_size
)
1427 memset(&stream
, 0, sizeof(stream
));
1429 stream
.next_in
= (unsigned char *)data
;
1430 stream
.avail_in
= size
;
1431 stream
.next_out
= out
= xmalloc(inflated_size
);
1432 stream
.avail_out
= inflated_size
;
1433 git_inflate_init(&stream
);
1434 st
= git_inflate(&stream
, Z_FINISH
);
1435 git_inflate_end(&stream
);
1436 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1443 static struct fragment
*parse_binary_hunk(char **buf_p
,
1444 unsigned long *sz_p
,
1449 * Expect a line that begins with binary patch method ("literal"
1450 * or "delta"), followed by the length of data before deflating.
1451 * a sequence of 'length-byte' followed by base-85 encoded data
1452 * should follow, terminated by a newline.
1454 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1455 * and we would limit the patch line to 66 characters,
1456 * so one line can fit up to 13 groups that would decode
1457 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1458 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1461 unsigned long size
= *sz_p
;
1462 char *buffer
= *buf_p
;
1464 unsigned long origlen
;
1467 struct fragment
*frag
;
1469 llen
= linelen(buffer
, size
);
1474 if (!prefixcmp(buffer
, "delta ")) {
1475 patch_method
= BINARY_DELTA_DEFLATED
;
1476 origlen
= strtoul(buffer
+ 6, NULL
, 10);
1478 else if (!prefixcmp(buffer
, "literal ")) {
1479 patch_method
= BINARY_LITERAL_DEFLATED
;
1480 origlen
= strtoul(buffer
+ 8, NULL
, 10);
1488 int byte_length
, max_byte_length
, newsize
;
1489 llen
= linelen(buffer
, size
);
1493 /* consume the blank line */
1499 * Minimum line is "A00000\n" which is 7-byte long,
1500 * and the line length must be multiple of 5 plus 2.
1502 if ((llen
< 7) || (llen
-2) % 5)
1504 max_byte_length
= (llen
- 2) / 5 * 4;
1505 byte_length
= *buffer
;
1506 if ('A' <= byte_length
&& byte_length
<= 'Z')
1507 byte_length
= byte_length
- 'A' + 1;
1508 else if ('a' <= byte_length
&& byte_length
<= 'z')
1509 byte_length
= byte_length
- 'a' + 27;
1512 /* if the input length was not multiple of 4, we would
1513 * have filler at the end but the filler should never
1516 if (max_byte_length
< byte_length
||
1517 byte_length
<= max_byte_length
- 4)
1519 newsize
= hunk_size
+ byte_length
;
1520 data
= xrealloc(data
, newsize
);
1521 if (decode_85(data
+ hunk_size
, buffer
+ 1, byte_length
))
1523 hunk_size
= newsize
;
1528 frag
= xcalloc(1, sizeof(*frag
));
1529 frag
->patch
= inflate_it(data
, hunk_size
, origlen
);
1533 frag
->size
= origlen
;
1537 frag
->binary_patch_method
= patch_method
;
1543 error("corrupt binary patch at line %d: %.*s",
1544 linenr
-1, llen
-1, buffer
);
1548 static int parse_binary(char *buffer
, unsigned long size
, struct patch
*patch
)
1551 * We have read "GIT binary patch\n"; what follows is a line
1552 * that says the patch method (currently, either "literal" or
1553 * "delta") and the length of data before deflating; a
1554 * sequence of 'length-byte' followed by base-85 encoded data
1557 * When a binary patch is reversible, there is another binary
1558 * hunk in the same format, starting with patch method (either
1559 * "literal" or "delta") with the length of data, and a sequence
1560 * of length-byte + base-85 encoded data, terminated with another
1561 * empty line. This data, when applied to the postimage, produces
1564 struct fragment
*forward
;
1565 struct fragment
*reverse
;
1569 forward
= parse_binary_hunk(&buffer
, &size
, &status
, &used
);
1570 if (!forward
&& !status
)
1571 /* there has to be one hunk (forward hunk) */
1572 return error("unrecognized binary patch at line %d", linenr
-1);
1574 /* otherwise we already gave an error message */
1577 reverse
= parse_binary_hunk(&buffer
, &size
, &status
, &used_1
);
1582 * Not having reverse hunk is not an error, but having
1583 * a corrupt reverse hunk is.
1585 free((void*) forward
->patch
);
1589 forward
->next
= reverse
;
1590 patch
->fragments
= forward
;
1591 patch
->is_binary
= 1;
1595 static int parse_chunk(char *buffer
, unsigned long size
, struct patch
*patch
)
1597 int hdrsize
, patchsize
;
1598 int offset
= find_header(buffer
, size
, &hdrsize
, patch
);
1603 patch
->ws_rule
= whitespace_rule(patch
->new_name
1607 patchsize
= parse_single_patch(buffer
+ offset
+ hdrsize
,
1608 size
- offset
- hdrsize
, patch
);
1611 static const char *binhdr
[] = {
1616 static const char git_binary
[] = "GIT binary patch\n";
1618 int hd
= hdrsize
+ offset
;
1619 unsigned long llen
= linelen(buffer
+ hd
, size
- hd
);
1621 if (llen
== sizeof(git_binary
) - 1 &&
1622 !memcmp(git_binary
, buffer
+ hd
, llen
)) {
1625 used
= parse_binary(buffer
+ hd
+ llen
,
1626 size
- hd
- llen
, patch
);
1628 patchsize
= used
+ llen
;
1632 else if (!memcmp(" differ\n", buffer
+ hd
+ llen
- 8, 8)) {
1633 for (i
= 0; binhdr
[i
]; i
++) {
1634 int len
= strlen(binhdr
[i
]);
1635 if (len
< size
- hd
&&
1636 !memcmp(binhdr
[i
], buffer
+ hd
, len
)) {
1638 patch
->is_binary
= 1;
1645 /* Empty patch cannot be applied if it is a text patch
1646 * without metadata change. A binary patch appears
1649 if ((apply
|| check
) &&
1650 (!patch
->is_binary
&& !metadata_changes(patch
)))
1651 die("patch with only garbage at line %d", linenr
);
1654 return offset
+ hdrsize
+ patchsize
;
1657 #define swap(a,b) myswap((a),(b),sizeof(a))
1659 #define myswap(a, b, size) do { \
1660 unsigned char mytmp[size]; \
1661 memcpy(mytmp, &a, size); \
1662 memcpy(&a, &b, size); \
1663 memcpy(&b, mytmp, size); \
1666 static void reverse_patches(struct patch
*p
)
1668 for (; p
; p
= p
->next
) {
1669 struct fragment
*frag
= p
->fragments
;
1671 swap(p
->new_name
, p
->old_name
);
1672 swap(p
->new_mode
, p
->old_mode
);
1673 swap(p
->is_new
, p
->is_delete
);
1674 swap(p
->lines_added
, p
->lines_deleted
);
1675 swap(p
->old_sha1_prefix
, p
->new_sha1_prefix
);
1677 for (; frag
; frag
= frag
->next
) {
1678 swap(frag
->newpos
, frag
->oldpos
);
1679 swap(frag
->newlines
, frag
->oldlines
);
1684 static const char pluses
[] =
1685 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1686 static const char minuses
[]=
1687 "----------------------------------------------------------------------";
1689 static void show_stats(struct patch
*patch
)
1691 struct strbuf qname
= STRBUF_INIT
;
1692 char *cp
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
1695 quote_c_style(cp
, &qname
, NULL
, 0);
1698 * "scale" the filename
1704 if (qname
.len
> max
) {
1705 cp
= strchr(qname
.buf
+ qname
.len
+ 3 - max
, '/');
1707 cp
= qname
.buf
+ qname
.len
+ 3 - max
;
1708 strbuf_splice(&qname
, 0, cp
- qname
.buf
, "...", 3);
1711 if (patch
->is_binary
) {
1712 printf(" %-*s | Bin\n", max
, qname
.buf
);
1713 strbuf_release(&qname
);
1717 printf(" %-*s |", max
, qname
.buf
);
1718 strbuf_release(&qname
);
1721 * scale the add/delete
1723 max
= max
+ max_change
> 70 ? 70 - max
: max_change
;
1724 add
= patch
->lines_added
;
1725 del
= patch
->lines_deleted
;
1727 if (max_change
> 0) {
1728 int total
= ((add
+ del
) * max
+ max_change
/ 2) / max_change
;
1729 add
= (add
* max
+ max_change
/ 2) / max_change
;
1732 printf("%5d %.*s%.*s\n", patch
->lines_added
+ patch
->lines_deleted
,
1733 add
, pluses
, del
, minuses
);
1736 static int read_old_data(struct stat
*st
, const char *path
, struct strbuf
*buf
)
1738 switch (st
->st_mode
& S_IFMT
) {
1740 if (strbuf_readlink(buf
, path
, st
->st_size
) < 0)
1741 return error("unable to read symlink %s", path
);
1744 if (strbuf_read_file(buf
, path
, st
->st_size
) != st
->st_size
)
1745 return error("unable to open or read %s", path
);
1746 convert_to_git(path
, buf
->buf
, buf
->len
, buf
, 0);
1754 * Update the preimage, and the common lines in postimage,
1755 * from buffer buf of length len. If postlen is 0 the postimage
1756 * is updated in place, otherwise it's updated on a new buffer
1760 static void update_pre_post_images(struct image
*preimage
,
1761 struct image
*postimage
,
1763 size_t len
, size_t postlen
)
1766 char *new, *old
, *fixed
;
1767 struct image fixed_preimage
;
1770 * Update the preimage with whitespace fixes. Note that we
1771 * are not losing preimage->buf -- apply_one_fragment() will
1774 prepare_image(&fixed_preimage
, buf
, len
, 1);
1775 assert(fixed_preimage
.nr
== preimage
->nr
);
1776 for (i
= 0; i
< preimage
->nr
; i
++)
1777 fixed_preimage
.line
[i
].flag
= preimage
->line
[i
].flag
;
1778 free(preimage
->line_allocated
);
1779 *preimage
= fixed_preimage
;
1782 * Adjust the common context lines in postimage. This can be
1783 * done in-place when we are just doing whitespace fixing,
1784 * which does not make the string grow, but needs a new buffer
1785 * when ignoring whitespace causes the update, since in this case
1786 * we could have e.g. tabs converted to multiple spaces.
1787 * We trust the caller to tell us if the update can be done
1788 * in place (postlen==0) or not.
1790 old
= postimage
->buf
;
1792 new = postimage
->buf
= xmalloc(postlen
);
1795 fixed
= preimage
->buf
;
1796 for (i
= ctx
= 0; i
< postimage
->nr
; i
++) {
1797 size_t len
= postimage
->line
[i
].len
;
1798 if (!(postimage
->line
[i
].flag
& LINE_COMMON
)) {
1799 /* an added line -- no counterparts in preimage */
1800 memmove(new, old
, len
);
1806 /* a common context -- skip it in the original postimage */
1809 /* and find the corresponding one in the fixed preimage */
1810 while (ctx
< preimage
->nr
&&
1811 !(preimage
->line
[ctx
].flag
& LINE_COMMON
)) {
1812 fixed
+= preimage
->line
[ctx
].len
;
1815 if (preimage
->nr
<= ctx
)
1818 /* and copy it in, while fixing the line length */
1819 len
= preimage
->line
[ctx
].len
;
1820 memcpy(new, fixed
, len
);
1823 postimage
->line
[i
].len
= len
;
1827 /* Fix the length of the whole thing */
1828 postimage
->len
= new - postimage
->buf
;
1831 static int match_fragment(struct image
*img
,
1832 struct image
*preimage
,
1833 struct image
*postimage
,
1837 int match_beginning
, int match_end
)
1840 char *fixed_buf
, *buf
, *orig
, *target
;
1842 if (preimage
->nr
+ try_lno
> img
->nr
)
1845 if (match_beginning
&& try_lno
)
1848 if (match_end
&& preimage
->nr
+ try_lno
!= img
->nr
)
1851 /* Quick hash check */
1852 for (i
= 0; i
< preimage
->nr
; i
++)
1853 if (preimage
->line
[i
].hash
!= img
->line
[try_lno
+ i
].hash
)
1857 * Do we have an exact match? If we were told to match
1858 * at the end, size must be exactly at try+fragsize,
1859 * otherwise try+fragsize must be still within the preimage,
1860 * and either case, the old piece should match the preimage
1864 ? (try + preimage
->len
== img
->len
)
1865 : (try + preimage
->len
<= img
->len
)) &&
1866 !memcmp(img
->buf
+ try, preimage
->buf
, preimage
->len
))
1870 * No exact match. If we are ignoring whitespace, run a line-by-line
1871 * fuzzy matching. We collect all the line length information because
1872 * we need it to adjust whitespace if we match.
1874 if (ws_ignore_action
== ignore_ws_change
) {
1877 size_t postlen
= postimage
->len
;
1878 size_t imglen
[preimage
->nr
];
1879 for (i
= 0; i
< preimage
->nr
; i
++) {
1880 size_t prelen
= preimage
->line
[i
].len
;
1882 imglen
[i
] = img
->line
[try_lno
+i
].len
;
1883 if (!fuzzy_matchlines(
1884 img
->buf
+ try + imgoff
, imglen
[i
],
1885 preimage
->buf
+ preoff
, prelen
))
1887 if (preimage
->line
[i
].flag
& LINE_COMMON
)
1888 postlen
+= imglen
[i
] - prelen
;
1889 imgoff
+= imglen
[i
];
1894 * Ok, the preimage matches with whitespace fuzz. Update it and
1895 * the common postimage lines to use the same whitespace as the
1896 * target. imgoff now holds the true length of the target that
1897 * matches the preimage, and we need to update the line lengths
1898 * of the preimage to match the target ones.
1900 fixed_buf
= xmalloc(imgoff
);
1901 memcpy(fixed_buf
, img
->buf
+ try, imgoff
);
1902 for (i
= 0; i
< preimage
->nr
; i
++)
1903 preimage
->line
[i
].len
= imglen
[i
];
1906 * Update the preimage buffer and the postimage context lines.
1908 update_pre_post_images(preimage
, postimage
,
1909 fixed_buf
, imgoff
, postlen
);
1913 if (ws_error_action
!= correct_ws_error
)
1917 * The hunk does not apply byte-by-byte, but the hash says
1918 * it might with whitespace fuzz. We haven't been asked to
1919 * ignore whitespace, we were asked to correct whitespace
1920 * errors, so let's try matching after whitespace correction.
1922 fixed_buf
= xmalloc(preimage
->len
+ 1);
1924 orig
= preimage
->buf
;
1925 target
= img
->buf
+ try;
1926 for (i
= 0; i
< preimage
->nr
; i
++) {
1927 size_t fixlen
; /* length after fixing the preimage */
1928 size_t oldlen
= preimage
->line
[i
].len
;
1929 size_t tgtlen
= img
->line
[try_lno
+ i
].len
;
1930 size_t tgtfixlen
; /* length after fixing the target line */
1931 char tgtfixbuf
[1024], *tgtfix
;
1934 /* Try fixing the line in the preimage */
1935 fixlen
= ws_fix_copy(buf
, orig
, oldlen
, ws_rule
, NULL
);
1937 /* Try fixing the line in the target */
1938 if (sizeof(tgtfixbuf
) > tgtlen
)
1941 tgtfix
= xmalloc(tgtlen
);
1942 tgtfixlen
= ws_fix_copy(tgtfix
, target
, tgtlen
, ws_rule
, NULL
);
1945 * If they match, either the preimage was based on
1946 * a version before our tree fixed whitespace breakage,
1947 * or we are lacking a whitespace-fix patch the tree
1948 * the preimage was based on already had (i.e. target
1949 * has whitespace breakage, the preimage doesn't).
1950 * In either case, we are fixing the whitespace breakages
1951 * so we might as well take the fix together with their
1954 match
= (tgtfixlen
== fixlen
&& !memcmp(tgtfix
, buf
, fixlen
));
1956 if (tgtfix
!= tgtfixbuf
)
1967 * Yes, the preimage is based on an older version that still
1968 * has whitespace breakages unfixed, and fixing them makes the
1969 * hunk match. Update the context lines in the postimage.
1971 update_pre_post_images(preimage
, postimage
,
1972 fixed_buf
, buf
- fixed_buf
, 0);
1980 static int find_pos(struct image
*img
,
1981 struct image
*preimage
,
1982 struct image
*postimage
,
1985 int match_beginning
, int match_end
)
1988 unsigned long backwards
, forwards
, try;
1989 int backwards_lno
, forwards_lno
, try_lno
;
1991 if (preimage
->nr
> img
->nr
)
1995 * If match_begining or match_end is specified, there is no
1996 * point starting from a wrong line that will never match and
1997 * wander around and wait for a match at the specified end.
1999 if (match_beginning
)
2002 line
= img
->nr
- preimage
->nr
;
2008 for (i
= 0; i
< line
; i
++)
2009 try += img
->line
[i
].len
;
2012 * There's probably some smart way to do this, but I'll leave
2013 * that to the smart and beautiful people. I'm simple and stupid.
2016 backwards_lno
= line
;
2018 forwards_lno
= line
;
2021 for (i
= 0; ; i
++) {
2022 if (match_fragment(img
, preimage
, postimage
,
2023 try, try_lno
, ws_rule
,
2024 match_beginning
, match_end
))
2028 if (backwards_lno
== 0 && forwards_lno
== img
->nr
)
2032 if (backwards_lno
== 0) {
2037 backwards
-= img
->line
[backwards_lno
].len
;
2039 try_lno
= backwards_lno
;
2041 if (forwards_lno
== img
->nr
) {
2045 forwards
+= img
->line
[forwards_lno
].len
;
2048 try_lno
= forwards_lno
;
2055 static void remove_first_line(struct image
*img
)
2057 img
->buf
+= img
->line
[0].len
;
2058 img
->len
-= img
->line
[0].len
;
2063 static void remove_last_line(struct image
*img
)
2065 img
->len
-= img
->line
[--img
->nr
].len
;
2068 static void update_image(struct image
*img
,
2070 struct image
*preimage
,
2071 struct image
*postimage
)
2074 * remove the copy of preimage at offset in img
2075 * and replace it with postimage
2078 size_t remove_count
, insert_count
, applied_at
= 0;
2081 for (i
= 0; i
< applied_pos
; i
++)
2082 applied_at
+= img
->line
[i
].len
;
2085 for (i
= 0; i
< preimage
->nr
; i
++)
2086 remove_count
+= img
->line
[applied_pos
+ i
].len
;
2087 insert_count
= postimage
->len
;
2089 /* Adjust the contents */
2090 result
= xmalloc(img
->len
+ insert_count
- remove_count
+ 1);
2091 memcpy(result
, img
->buf
, applied_at
);
2092 memcpy(result
+ applied_at
, postimage
->buf
, postimage
->len
);
2093 memcpy(result
+ applied_at
+ postimage
->len
,
2094 img
->buf
+ (applied_at
+ remove_count
),
2095 img
->len
- (applied_at
+ remove_count
));
2098 img
->len
+= insert_count
- remove_count
;
2099 result
[img
->len
] = '\0';
2101 /* Adjust the line table */
2102 nr
= img
->nr
+ postimage
->nr
- preimage
->nr
;
2103 if (preimage
->nr
< postimage
->nr
) {
2105 * NOTE: this knows that we never call remove_first_line()
2106 * on anything other than pre/post image.
2108 img
->line
= xrealloc(img
->line
, nr
* sizeof(*img
->line
));
2109 img
->line_allocated
= img
->line
;
2111 if (preimage
->nr
!= postimage
->nr
)
2112 memmove(img
->line
+ applied_pos
+ postimage
->nr
,
2113 img
->line
+ applied_pos
+ preimage
->nr
,
2114 (img
->nr
- (applied_pos
+ preimage
->nr
)) *
2115 sizeof(*img
->line
));
2116 memcpy(img
->line
+ applied_pos
,
2118 postimage
->nr
* sizeof(*img
->line
));
2122 static int apply_one_fragment(struct image
*img
, struct fragment
*frag
,
2123 int inaccurate_eof
, unsigned ws_rule
)
2125 int match_beginning
, match_end
;
2126 const char *patch
= frag
->patch
;
2127 int size
= frag
->size
;
2128 char *old
, *new, *oldlines
, *newlines
;
2129 int new_blank_lines_at_end
= 0;
2130 unsigned long leading
, trailing
;
2131 int pos
, applied_pos
;
2132 struct image preimage
;
2133 struct image postimage
;
2135 memset(&preimage
, 0, sizeof(preimage
));
2136 memset(&postimage
, 0, sizeof(postimage
));
2137 oldlines
= xmalloc(size
);
2138 newlines
= xmalloc(size
);
2144 int len
= linelen(patch
, size
);
2146 int added_blank_line
= 0;
2152 * "plen" is how much of the line we should use for
2153 * the actual patch data. Normally we just remove the
2154 * first character on the line, but if the line is
2155 * followed by "\ No newline", then we also remove the
2156 * last one (which is the newline, of course).
2159 if (len
< size
&& patch
[len
] == '\\')
2162 if (apply_in_reverse
) {
2165 else if (first
== '+')
2171 /* Newer GNU diff, empty context line */
2173 /* ... followed by '\No newline'; nothing */
2177 add_line_info(&preimage
, "\n", 1, LINE_COMMON
);
2178 add_line_info(&postimage
, "\n", 1, LINE_COMMON
);
2182 memcpy(old
, patch
+ 1, plen
);
2183 add_line_info(&preimage
, old
, plen
,
2184 (first
== ' ' ? LINE_COMMON
: 0));
2188 /* Fall-through for ' ' */
2190 /* --no-add does not add new lines */
2191 if (first
== '+' && no_add
)
2195 !whitespace_error
||
2196 ws_error_action
!= correct_ws_error
) {
2197 memcpy(new, patch
+ 1, plen
);
2201 added
= ws_fix_copy(new, patch
+ 1, plen
, ws_rule
, &applied_after_fixing_ws
);
2203 add_line_info(&postimage
, new, added
,
2204 (first
== '+' ? 0 : LINE_COMMON
));
2207 added
== 1 && new[-1] == '\n')
2208 added_blank_line
= 1;
2210 case '@': case '\\':
2211 /* Ignore it, we already handled it */
2214 if (apply_verbosely
)
2215 error("invalid start of line: '%c'", first
);
2218 if (added_blank_line
)
2219 new_blank_lines_at_end
++;
2221 new_blank_lines_at_end
= 0;
2225 if (inaccurate_eof
&&
2226 old
> oldlines
&& old
[-1] == '\n' &&
2227 new > newlines
&& new[-1] == '\n') {
2232 leading
= frag
->leading
;
2233 trailing
= frag
->trailing
;
2236 * A hunk to change lines at the beginning would begin with
2238 * but we need to be careful. -U0 that inserts before the second
2239 * line also has this pattern.
2241 * And a hunk to add to an empty file would begin with
2244 * In other words, a hunk that is (frag->oldpos <= 1) with or
2245 * without leading context must match at the beginning.
2247 match_beginning
= (!frag
->oldpos
||
2248 (frag
->oldpos
== 1 && !unidiff_zero
));
2251 * A hunk without trailing lines must match at the end.
2252 * However, we simply cannot tell if a hunk must match end
2253 * from the lack of trailing lines if the patch was generated
2254 * with unidiff without any context.
2256 match_end
= !unidiff_zero
&& !trailing
;
2258 pos
= frag
->newpos
? (frag
->newpos
- 1) : 0;
2259 preimage
.buf
= oldlines
;
2260 preimage
.len
= old
- oldlines
;
2261 postimage
.buf
= newlines
;
2262 postimage
.len
= new - newlines
;
2263 preimage
.line
= preimage
.line_allocated
;
2264 postimage
.line
= postimage
.line_allocated
;
2268 applied_pos
= find_pos(img
, &preimage
, &postimage
, pos
,
2269 ws_rule
, match_beginning
, match_end
);
2271 if (applied_pos
>= 0)
2274 /* Am I at my context limits? */
2275 if ((leading
<= p_context
) && (trailing
<= p_context
))
2277 if (match_beginning
|| match_end
) {
2278 match_beginning
= match_end
= 0;
2283 * Reduce the number of context lines; reduce both
2284 * leading and trailing if they are equal otherwise
2285 * just reduce the larger context.
2287 if (leading
>= trailing
) {
2288 remove_first_line(&preimage
);
2289 remove_first_line(&postimage
);
2293 if (trailing
> leading
) {
2294 remove_last_line(&preimage
);
2295 remove_last_line(&postimage
);
2300 if (applied_pos
>= 0) {
2301 if (ws_error_action
== correct_ws_error
&&
2302 new_blank_lines_at_end
&&
2303 postimage
.nr
+ applied_pos
== img
->nr
) {
2305 * If the patch application adds blank lines
2306 * at the end, and if the patch applies at the
2307 * end of the image, remove those added blank
2310 while (new_blank_lines_at_end
--)
2311 remove_last_line(&postimage
);
2315 * Warn if it was necessary to reduce the number
2318 if ((leading
!= frag
->leading
) ||
2319 (trailing
!= frag
->trailing
))
2320 fprintf(stderr
, "Context reduced to (%ld/%ld)"
2321 " to apply fragment at %d\n",
2322 leading
, trailing
, applied_pos
+1);
2323 update_image(img
, applied_pos
, &preimage
, &postimage
);
2325 if (apply_verbosely
)
2326 error("while searching for:\n%.*s",
2327 (int)(old
- oldlines
), oldlines
);
2332 free(preimage
.line_allocated
);
2333 free(postimage
.line_allocated
);
2335 return (applied_pos
< 0);
2338 static int apply_binary_fragment(struct image
*img
, struct patch
*patch
)
2340 struct fragment
*fragment
= patch
->fragments
;
2344 /* Binary patch is irreversible without the optional second hunk */
2345 if (apply_in_reverse
) {
2346 if (!fragment
->next
)
2347 return error("cannot reverse-apply a binary patch "
2348 "without the reverse hunk to '%s'",
2350 ? patch
->new_name
: patch
->old_name
);
2351 fragment
= fragment
->next
;
2353 switch (fragment
->binary_patch_method
) {
2354 case BINARY_DELTA_DEFLATED
:
2355 dst
= patch_delta(img
->buf
, img
->len
, fragment
->patch
,
2356 fragment
->size
, &len
);
2363 case BINARY_LITERAL_DEFLATED
:
2365 img
->len
= fragment
->size
;
2366 img
->buf
= xmalloc(img
->len
+1);
2367 memcpy(img
->buf
, fragment
->patch
, img
->len
);
2368 img
->buf
[img
->len
] = '\0';
2374 static int apply_binary(struct image
*img
, struct patch
*patch
)
2376 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
2377 unsigned char sha1
[20];
2380 * For safety, we require patch index line to contain
2381 * full 40-byte textual SHA1 for old and new, at least for now.
2383 if (strlen(patch
->old_sha1_prefix
) != 40 ||
2384 strlen(patch
->new_sha1_prefix
) != 40 ||
2385 get_sha1_hex(patch
->old_sha1_prefix
, sha1
) ||
2386 get_sha1_hex(patch
->new_sha1_prefix
, sha1
))
2387 return error("cannot apply binary patch to '%s' "
2388 "without full index line", name
);
2390 if (patch
->old_name
) {
2392 * See if the old one matches what the patch
2395 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
2396 if (strcmp(sha1_to_hex(sha1
), patch
->old_sha1_prefix
))
2397 return error("the patch applies to '%s' (%s), "
2398 "which does not match the "
2399 "current contents.",
2400 name
, sha1_to_hex(sha1
));
2403 /* Otherwise, the old one must be empty. */
2405 return error("the patch applies to an empty "
2406 "'%s' but it is not empty", name
);
2409 get_sha1_hex(patch
->new_sha1_prefix
, sha1
);
2410 if (is_null_sha1(sha1
)) {
2412 return 0; /* deletion patch */
2415 if (has_sha1_file(sha1
)) {
2416 /* We already have the postimage */
2417 enum object_type type
;
2421 result
= read_sha1_file(sha1
, &type
, &size
);
2423 return error("the necessary postimage %s for "
2424 "'%s' cannot be read",
2425 patch
->new_sha1_prefix
, name
);
2431 * We have verified buf matches the preimage;
2432 * apply the patch data to it, which is stored
2433 * in the patch->fragments->{patch,size}.
2435 if (apply_binary_fragment(img
, patch
))
2436 return error("binary patch does not apply to '%s'",
2439 /* verify that the result matches */
2440 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
2441 if (strcmp(sha1_to_hex(sha1
), patch
->new_sha1_prefix
))
2442 return error("binary patch to '%s' creates incorrect result (expecting %s, got %s)",
2443 name
, patch
->new_sha1_prefix
, sha1_to_hex(sha1
));
2449 static int apply_fragments(struct image
*img
, struct patch
*patch
)
2451 struct fragment
*frag
= patch
->fragments
;
2452 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
2453 unsigned ws_rule
= patch
->ws_rule
;
2454 unsigned inaccurate_eof
= patch
->inaccurate_eof
;
2456 if (patch
->is_binary
)
2457 return apply_binary(img
, patch
);
2460 if (apply_one_fragment(img
, frag
, inaccurate_eof
, ws_rule
)) {
2461 error("patch failed: %s:%ld", name
, frag
->oldpos
);
2462 if (!apply_with_reject
)
2471 static int read_file_or_gitlink(struct cache_entry
*ce
, struct strbuf
*buf
)
2476 if (S_ISGITLINK(ce
->ce_mode
)) {
2477 strbuf_grow(buf
, 100);
2478 strbuf_addf(buf
, "Subproject commit %s\n", sha1_to_hex(ce
->sha1
));
2480 enum object_type type
;
2484 result
= read_sha1_file(ce
->sha1
, &type
, &sz
);
2487 /* XXX read_sha1_file NUL-terminates */
2488 strbuf_attach(buf
, result
, sz
, sz
+ 1);
2493 static struct patch
*in_fn_table(const char *name
)
2495 struct string_list_item
*item
;
2500 item
= string_list_lookup(name
, &fn_table
);
2502 return (struct patch
*)item
->util
;
2508 * item->util in the filename table records the status of the path.
2509 * Usually it points at a patch (whose result records the contents
2510 * of it after applying it), but it could be PATH_WAS_DELETED for a
2511 * path that a previously applied patch has already removed.
2513 #define PATH_TO_BE_DELETED ((struct patch *) -2)
2514 #define PATH_WAS_DELETED ((struct patch *) -1)
2516 static int to_be_deleted(struct patch
*patch
)
2518 return patch
== PATH_TO_BE_DELETED
;
2521 static int was_deleted(struct patch
*patch
)
2523 return patch
== PATH_WAS_DELETED
;
2526 static void add_to_fn_table(struct patch
*patch
)
2528 struct string_list_item
*item
;
2531 * Always add new_name unless patch is a deletion
2532 * This should cover the cases for normal diffs,
2533 * file creations and copies
2535 if (patch
->new_name
!= NULL
) {
2536 item
= string_list_insert(patch
->new_name
, &fn_table
);
2541 * store a failure on rename/deletion cases because
2542 * later chunks shouldn't patch old names
2544 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
2545 item
= string_list_insert(patch
->old_name
, &fn_table
);
2546 item
->util
= PATH_WAS_DELETED
;
2550 static void prepare_fn_table(struct patch
*patch
)
2553 * store information about incoming file deletion
2556 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
2557 struct string_list_item
*item
;
2558 item
= string_list_insert(patch
->old_name
, &fn_table
);
2559 item
->util
= PATH_TO_BE_DELETED
;
2561 patch
= patch
->next
;
2565 static int apply_data(struct patch
*patch
, struct stat
*st
, struct cache_entry
*ce
)
2567 struct strbuf buf
= STRBUF_INIT
;
2571 struct patch
*tpatch
;
2573 if (!(patch
->is_copy
|| patch
->is_rename
) &&
2574 (tpatch
= in_fn_table(patch
->old_name
)) != NULL
&& !to_be_deleted(tpatch
)) {
2575 if (was_deleted(tpatch
)) {
2576 return error("patch %s has been renamed/deleted",
2579 /* We have a patched copy in memory use that */
2580 strbuf_add(&buf
, tpatch
->result
, tpatch
->resultsize
);
2581 } else if (cached
) {
2582 if (read_file_or_gitlink(ce
, &buf
))
2583 return error("read of %s failed", patch
->old_name
);
2584 } else if (patch
->old_name
) {
2585 if (S_ISGITLINK(patch
->old_mode
)) {
2587 read_file_or_gitlink(ce
, &buf
);
2590 * There is no way to apply subproject
2591 * patch without looking at the index.
2593 patch
->fragments
= NULL
;
2596 if (read_old_data(st
, patch
->old_name
, &buf
))
2597 return error("read of %s failed", patch
->old_name
);
2601 img
= strbuf_detach(&buf
, &len
);
2602 prepare_image(&image
, img
, len
, !patch
->is_binary
);
2604 if (apply_fragments(&image
, patch
) < 0)
2605 return -1; /* note with --reject this succeeds. */
2606 patch
->result
= image
.buf
;
2607 patch
->resultsize
= image
.len
;
2608 add_to_fn_table(patch
);
2609 free(image
.line_allocated
);
2611 if (0 < patch
->is_delete
&& patch
->resultsize
)
2612 return error("removal patch leaves file contents");
2617 static int check_to_create_blob(const char *new_name
, int ok_if_exists
)
2620 if (!lstat(new_name
, &nst
)) {
2621 if (S_ISDIR(nst
.st_mode
) || ok_if_exists
)
2624 * A leading component of new_name might be a symlink
2625 * that is going to be removed with this patch, but
2626 * still pointing at somewhere that has the path.
2627 * In such a case, path "new_name" does not exist as
2628 * far as git is concerned.
2630 if (has_symlink_leading_path(new_name
, strlen(new_name
)))
2633 return error("%s: already exists in working directory", new_name
);
2635 else if ((errno
!= ENOENT
) && (errno
!= ENOTDIR
))
2636 return error("%s: %s", new_name
, strerror(errno
));
2640 static int verify_index_match(struct cache_entry
*ce
, struct stat
*st
)
2642 if (S_ISGITLINK(ce
->ce_mode
)) {
2643 if (!S_ISDIR(st
->st_mode
))
2647 return ce_match_stat(ce
, st
, CE_MATCH_IGNORE_VALID
);
2650 static int check_preimage(struct patch
*patch
, struct cache_entry
**ce
, struct stat
*st
)
2652 const char *old_name
= patch
->old_name
;
2653 struct patch
*tpatch
= NULL
;
2655 unsigned st_mode
= 0;
2658 * Make sure that we do not have local modifications from the
2659 * index when we are looking at the index. Also make sure
2660 * we have the preimage file to be patched in the work tree,
2661 * unless --cached, which tells git to apply only in the index.
2666 assert(patch
->is_new
<= 0);
2668 if (!(patch
->is_copy
|| patch
->is_rename
) &&
2669 (tpatch
= in_fn_table(old_name
)) != NULL
&& !to_be_deleted(tpatch
)) {
2670 if (was_deleted(tpatch
))
2671 return error("%s: has been deleted/renamed", old_name
);
2672 st_mode
= tpatch
->new_mode
;
2673 } else if (!cached
) {
2674 stat_ret
= lstat(old_name
, st
);
2675 if (stat_ret
&& errno
!= ENOENT
)
2676 return error("%s: %s", old_name
, strerror(errno
));
2679 if (to_be_deleted(tpatch
))
2682 if (check_index
&& !tpatch
) {
2683 int pos
= cache_name_pos(old_name
, strlen(old_name
));
2685 if (patch
->is_new
< 0)
2687 return error("%s: does not exist in index", old_name
);
2689 *ce
= active_cache
[pos
];
2691 struct checkout costate
;
2693 costate
.base_dir
= "";
2694 costate
.base_dir_len
= 0;
2697 costate
.not_new
= 0;
2698 costate
.refresh_cache
= 1;
2699 if (checkout_entry(*ce
, &costate
, NULL
) ||
2700 lstat(old_name
, st
))
2703 if (!cached
&& verify_index_match(*ce
, st
))
2704 return error("%s: does not match index", old_name
);
2706 st_mode
= (*ce
)->ce_mode
;
2707 } else if (stat_ret
< 0) {
2708 if (patch
->is_new
< 0)
2710 return error("%s: %s", old_name
, strerror(errno
));
2713 if (!cached
&& !tpatch
)
2714 st_mode
= ce_mode_from_stat(*ce
, st
->st_mode
);
2716 if (patch
->is_new
< 0)
2718 if (!patch
->old_mode
)
2719 patch
->old_mode
= st_mode
;
2720 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
2721 return error("%s: wrong type", old_name
);
2722 if (st_mode
!= patch
->old_mode
)
2723 warning("%s has type %o, expected %o",
2724 old_name
, st_mode
, patch
->old_mode
);
2725 if (!patch
->new_mode
&& !patch
->is_delete
)
2726 patch
->new_mode
= st_mode
;
2731 patch
->is_delete
= 0;
2732 patch
->old_name
= NULL
;
2736 static int check_patch(struct patch
*patch
)
2739 const char *old_name
= patch
->old_name
;
2740 const char *new_name
= patch
->new_name
;
2741 const char *name
= old_name
? old_name
: new_name
;
2742 struct cache_entry
*ce
= NULL
;
2743 struct patch
*tpatch
;
2747 patch
->rejected
= 1; /* we will drop this after we succeed */
2749 status
= check_preimage(patch
, &ce
, &st
);
2752 old_name
= patch
->old_name
;
2754 if ((tpatch
= in_fn_table(new_name
)) &&
2755 (was_deleted(tpatch
) || to_be_deleted(tpatch
)))
2757 * A type-change diff is always split into a patch to
2758 * delete old, immediately followed by a patch to
2759 * create new (see diff.c::run_diff()); in such a case
2760 * it is Ok that the entry to be deleted by the
2761 * previous patch is still in the working tree and in
2769 ((0 < patch
->is_new
) | (0 < patch
->is_rename
) | patch
->is_copy
)) {
2771 cache_name_pos(new_name
, strlen(new_name
)) >= 0 &&
2773 return error("%s: already exists in index", new_name
);
2775 int err
= check_to_create_blob(new_name
, ok_if_exists
);
2779 if (!patch
->new_mode
) {
2780 if (0 < patch
->is_new
)
2781 patch
->new_mode
= S_IFREG
| 0644;
2783 patch
->new_mode
= patch
->old_mode
;
2787 if (new_name
&& old_name
) {
2788 int same
= !strcmp(old_name
, new_name
);
2789 if (!patch
->new_mode
)
2790 patch
->new_mode
= patch
->old_mode
;
2791 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
)
2792 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
2793 patch
->new_mode
, new_name
, patch
->old_mode
,
2794 same
? "" : " of ", same
? "" : old_name
);
2797 if (apply_data(patch
, &st
, ce
) < 0)
2798 return error("%s: patch does not apply", name
);
2799 patch
->rejected
= 0;
2803 static int check_patch_list(struct patch
*patch
)
2807 prepare_fn_table(patch
);
2809 if (apply_verbosely
)
2810 say_patch_name(stderr
,
2811 "Checking patch ", patch
, "...\n");
2812 err
|= check_patch(patch
);
2813 patch
= patch
->next
;
2818 /* This function tries to read the sha1 from the current index */
2819 static int get_current_sha1(const char *path
, unsigned char *sha1
)
2823 if (read_cache() < 0)
2825 pos
= cache_name_pos(path
, strlen(path
));
2828 hashcpy(sha1
, active_cache
[pos
]->sha1
);
2832 /* Build an index that contains the just the files needed for a 3way merge */
2833 static void build_fake_ancestor(struct patch
*list
, const char *filename
)
2835 struct patch
*patch
;
2836 struct index_state result
= { NULL
};
2839 /* Once we start supporting the reverse patch, it may be
2840 * worth showing the new sha1 prefix, but until then...
2842 for (patch
= list
; patch
; patch
= patch
->next
) {
2843 const unsigned char *sha1_ptr
;
2844 unsigned char sha1
[20];
2845 struct cache_entry
*ce
;
2848 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
2849 if (0 < patch
->is_new
)
2851 else if (get_sha1(patch
->old_sha1_prefix
, sha1
))
2852 /* git diff has no index line for mode/type changes */
2853 if (!patch
->lines_added
&& !patch
->lines_deleted
) {
2854 if (get_current_sha1(patch
->new_name
, sha1
) ||
2855 get_current_sha1(patch
->old_name
, sha1
))
2856 die("mode change for %s, which is not "
2857 "in current HEAD", name
);
2860 die("sha1 information is lacking or useless "
2865 ce
= make_cache_entry(patch
->old_mode
, sha1_ptr
, name
, 0, 0);
2867 die("make_cache_entry failed for path '%s'", name
);
2868 if (add_index_entry(&result
, ce
, ADD_CACHE_OK_TO_ADD
))
2869 die ("Could not add %s to temporary index", name
);
2872 fd
= open(filename
, O_WRONLY
| O_CREAT
, 0666);
2873 if (fd
< 0 || write_index(&result
, fd
) || close(fd
))
2874 die ("Could not write temporary index to %s", filename
);
2876 discard_index(&result
);
2879 static void stat_patch_list(struct patch
*patch
)
2881 int files
, adds
, dels
;
2883 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
2885 adds
+= patch
->lines_added
;
2886 dels
+= patch
->lines_deleted
;
2890 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files
, adds
, dels
);
2893 static void numstat_patch_list(struct patch
*patch
)
2895 for ( ; patch
; patch
= patch
->next
) {
2897 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
2898 if (patch
->is_binary
)
2901 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
2902 write_name_quoted(name
, stdout
, line_termination
);
2906 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
2909 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
2911 printf(" %s %s\n", newdelete
, name
);
2914 static void show_mode_change(struct patch
*p
, int show_name
)
2916 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
2918 printf(" mode change %06o => %06o %s\n",
2919 p
->old_mode
, p
->new_mode
, p
->new_name
);
2921 printf(" mode change %06o => %06o\n",
2922 p
->old_mode
, p
->new_mode
);
2926 static void show_rename_copy(struct patch
*p
)
2928 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
2929 const char *old
, *new;
2931 /* Find common prefix */
2935 const char *slash_old
, *slash_new
;
2936 slash_old
= strchr(old
, '/');
2937 slash_new
= strchr(new, '/');
2940 slash_old
- old
!= slash_new
- new ||
2941 memcmp(old
, new, slash_new
- new))
2943 old
= slash_old
+ 1;
2944 new = slash_new
+ 1;
2946 /* p->old_name thru old is the common prefix, and old and new
2947 * through the end of names are renames
2949 if (old
!= p
->old_name
)
2950 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
2951 (int)(old
- p
->old_name
), p
->old_name
,
2952 old
, new, p
->score
);
2954 printf(" %s %s => %s (%d%%)\n", renamecopy
,
2955 p
->old_name
, p
->new_name
, p
->score
);
2956 show_mode_change(p
, 0);
2959 static void summary_patch_list(struct patch
*patch
)
2963 for (p
= patch
; p
; p
= p
->next
) {
2965 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
2966 else if (p
->is_delete
)
2967 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
2969 if (p
->is_rename
|| p
->is_copy
)
2970 show_rename_copy(p
);
2973 printf(" rewrite %s (%d%%)\n",
2974 p
->new_name
, p
->score
);
2975 show_mode_change(p
, 0);
2978 show_mode_change(p
, 1);
2984 static void patch_stats(struct patch
*patch
)
2986 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
2988 if (lines
> max_change
)
2990 if (patch
->old_name
) {
2991 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
2993 len
= strlen(patch
->old_name
);
2997 if (patch
->new_name
) {
2998 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
3000 len
= strlen(patch
->new_name
);
3006 static void remove_file(struct patch
*patch
, int rmdir_empty
)
3009 if (remove_file_from_cache(patch
->old_name
) < 0)
3010 die("unable to remove %s from index", patch
->old_name
);
3013 if (S_ISGITLINK(patch
->old_mode
)) {
3014 if (rmdir(patch
->old_name
))
3015 warning("unable to remove submodule %s",
3017 } else if (!unlink_or_warn(patch
->old_name
) && rmdir_empty
) {
3018 remove_path(patch
->old_name
);
3023 static void add_index_file(const char *path
, unsigned mode
, void *buf
, unsigned long size
)
3026 struct cache_entry
*ce
;
3027 int namelen
= strlen(path
);
3028 unsigned ce_size
= cache_entry_size(namelen
);
3033 ce
= xcalloc(1, ce_size
);
3034 memcpy(ce
->name
, path
, namelen
);
3035 ce
->ce_mode
= create_ce_mode(mode
);
3036 ce
->ce_flags
= namelen
;
3037 if (S_ISGITLINK(mode
)) {
3038 const char *s
= buf
;
3040 if (get_sha1_hex(s
+ strlen("Subproject commit "), ce
->sha1
))
3041 die("corrupt patch for subproject %s", path
);
3044 if (lstat(path
, &st
) < 0)
3045 die_errno("unable to stat newly created file '%s'",
3047 fill_stat_cache_info(ce
, &st
);
3049 if (write_sha1_file(buf
, size
, blob_type
, ce
->sha1
) < 0)
3050 die("unable to create backing store for newly created file %s", path
);
3052 if (add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
) < 0)
3053 die("unable to add cache entry for %s", path
);
3056 static int try_create_file(const char *path
, unsigned int mode
, const char *buf
, unsigned long size
)
3059 struct strbuf nbuf
= STRBUF_INIT
;
3061 if (S_ISGITLINK(mode
)) {
3063 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
))
3065 return mkdir(path
, 0777);
3068 if (has_symlinks
&& S_ISLNK(mode
))
3069 /* Although buf:size is counted string, it also is NUL
3072 return symlink(buf
, path
);
3074 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
3078 if (convert_to_working_tree(path
, buf
, size
, &nbuf
)) {
3082 write_or_die(fd
, buf
, size
);
3083 strbuf_release(&nbuf
);
3086 die_errno("closing file '%s'", path
);
3091 * We optimistically assume that the directories exist,
3092 * which is true 99% of the time anyway. If they don't,
3093 * we create them and try again.
3095 static void create_one_file(char *path
, unsigned mode
, const char *buf
, unsigned long size
)
3099 if (!try_create_file(path
, mode
, buf
, size
))
3102 if (errno
== ENOENT
) {
3103 if (safe_create_leading_directories(path
))
3105 if (!try_create_file(path
, mode
, buf
, size
))
3109 if (errno
== EEXIST
|| errno
== EACCES
) {
3110 /* We may be trying to create a file where a directory
3114 if (!lstat(path
, &st
) && (!S_ISDIR(st
.st_mode
) || !rmdir(path
)))
3118 if (errno
== EEXIST
) {
3119 unsigned int nr
= getpid();
3122 char newpath
[PATH_MAX
];
3123 mksnpath(newpath
, sizeof(newpath
), "%s~%u", path
, nr
);
3124 if (!try_create_file(newpath
, mode
, buf
, size
)) {
3125 if (!rename(newpath
, path
))
3127 unlink_or_warn(newpath
);
3130 if (errno
!= EEXIST
)
3135 die_errno("unable to write file '%s' mode %o", path
, mode
);
3138 static void create_file(struct patch
*patch
)
3140 char *path
= patch
->new_name
;
3141 unsigned mode
= patch
->new_mode
;
3142 unsigned long size
= patch
->resultsize
;
3143 char *buf
= patch
->result
;
3146 mode
= S_IFREG
| 0644;
3147 create_one_file(path
, mode
, buf
, size
);
3148 add_index_file(path
, mode
, buf
, size
);
3151 /* phase zero is to remove, phase one is to create */
3152 static void write_out_one_result(struct patch
*patch
, int phase
)
3154 if (patch
->is_delete
> 0) {
3156 remove_file(patch
, 1);
3159 if (patch
->is_new
> 0 || patch
->is_copy
) {
3165 * Rename or modification boils down to the same
3166 * thing: remove the old, write the new
3169 remove_file(patch
, patch
->is_rename
);
3174 static int write_out_one_reject(struct patch
*patch
)
3177 char namebuf
[PATH_MAX
];
3178 struct fragment
*frag
;
3181 for (cnt
= 0, frag
= patch
->fragments
; frag
; frag
= frag
->next
) {
3182 if (!frag
->rejected
)
3188 if (apply_verbosely
)
3189 say_patch_name(stderr
,
3190 "Applied patch ", patch
, " cleanly.\n");
3194 /* This should not happen, because a removal patch that leaves
3195 * contents are marked "rejected" at the patch level.
3197 if (!patch
->new_name
)
3198 die("internal error");
3200 /* Say this even without --verbose */
3201 say_patch_name(stderr
, "Applying patch ", patch
, " with");
3202 fprintf(stderr
, " %d rejects...\n", cnt
);
3204 cnt
= strlen(patch
->new_name
);
3205 if (ARRAY_SIZE(namebuf
) <= cnt
+ 5) {
3206 cnt
= ARRAY_SIZE(namebuf
) - 5;
3207 warning("truncating .rej filename to %.*s.rej",
3208 cnt
- 1, patch
->new_name
);
3210 memcpy(namebuf
, patch
->new_name
, cnt
);
3211 memcpy(namebuf
+ cnt
, ".rej", 5);
3213 rej
= fopen(namebuf
, "w");
3215 return error("cannot open %s: %s", namebuf
, strerror(errno
));
3217 /* Normal git tools never deal with .rej, so do not pretend
3218 * this is a git patch by saying --git nor give extended
3219 * headers. While at it, maybe please "kompare" that wants
3220 * the trailing TAB and some garbage at the end of line ;-).
3222 fprintf(rej
, "diff a/%s b/%s\t(rejected hunks)\n",
3223 patch
->new_name
, patch
->new_name
);
3224 for (cnt
= 1, frag
= patch
->fragments
;
3226 cnt
++, frag
= frag
->next
) {
3227 if (!frag
->rejected
) {
3228 fprintf(stderr
, "Hunk #%d applied cleanly.\n", cnt
);
3231 fprintf(stderr
, "Rejected hunk #%d.\n", cnt
);
3232 fprintf(rej
, "%.*s", frag
->size
, frag
->patch
);
3233 if (frag
->patch
[frag
->size
-1] != '\n')
3240 static int write_out_results(struct patch
*list
, int skipped_patch
)
3246 if (!list
&& !skipped_patch
)
3247 return error("No changes");
3249 for (phase
= 0; phase
< 2; phase
++) {
3255 write_out_one_result(l
, phase
);
3256 if (phase
== 1 && write_out_one_reject(l
))
3265 static struct lock_file lock_file
;
3267 static struct string_list limit_by_name
;
3268 static int has_include
;
3269 static void add_name_limit(const char *name
, int exclude
)
3271 struct string_list_item
*it
;
3273 it
= string_list_append(name
, &limit_by_name
);
3274 it
->util
= exclude
? NULL
: (void *) 1;
3277 static int use_patch(struct patch
*p
)
3279 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
3282 /* Paths outside are not touched regardless of "--include" */
3283 if (0 < prefix_length
) {
3284 int pathlen
= strlen(pathname
);
3285 if (pathlen
<= prefix_length
||
3286 memcmp(prefix
, pathname
, prefix_length
))
3290 /* See if it matches any of exclude/include rule */
3291 for (i
= 0; i
< limit_by_name
.nr
; i
++) {
3292 struct string_list_item
*it
= &limit_by_name
.items
[i
];
3293 if (!fnmatch(it
->string
, pathname
, 0))
3294 return (it
->util
!= NULL
);
3298 * If we had any include, a path that does not match any rule is
3299 * not used. Otherwise, we saw bunch of exclude rules (or none)
3300 * and such a path is used.
3302 return !has_include
;
3306 static void prefix_one(char **name
)
3308 char *old_name
= *name
;
3311 *name
= xstrdup(prefix_filename(prefix
, prefix_length
, *name
));
3315 static void prefix_patches(struct patch
*p
)
3317 if (!prefix
|| p
->is_toplevel_relative
)
3319 for ( ; p
; p
= p
->next
) {
3320 if (p
->new_name
== p
->old_name
) {
3321 char *prefixed
= p
->new_name
;
3322 prefix_one(&prefixed
);
3323 p
->new_name
= p
->old_name
= prefixed
;
3326 prefix_one(&p
->new_name
);
3327 prefix_one(&p
->old_name
);
3332 #define INACCURATE_EOF (1<<0)
3333 #define RECOUNT (1<<1)
3335 static int apply_patch(int fd
, const char *filename
, int options
)
3338 struct strbuf buf
= STRBUF_INIT
;
3339 struct patch
*list
= NULL
, **listp
= &list
;
3340 int skipped_patch
= 0;
3342 /* FIXME - memory leak when using multiple patch files as inputs */
3343 memset(&fn_table
, 0, sizeof(struct string_list
));
3344 patch_input_file
= filename
;
3345 read_patch_file(&buf
, fd
);
3347 while (offset
< buf
.len
) {
3348 struct patch
*patch
;
3351 patch
= xcalloc(1, sizeof(*patch
));
3352 patch
->inaccurate_eof
= !!(options
& INACCURATE_EOF
);
3353 patch
->recount
= !!(options
& RECOUNT
);
3354 nr
= parse_chunk(buf
.buf
+ offset
, buf
.len
- offset
, patch
);
3357 if (apply_in_reverse
)
3358 reverse_patches(patch
);
3360 prefix_patches(patch
);
3361 if (use_patch(patch
)) {
3364 listp
= &patch
->next
;
3367 /* perhaps free it a bit better? */
3374 if (whitespace_error
&& (ws_error_action
== die_on_ws_error
))
3377 update_index
= check_index
&& apply
;
3378 if (update_index
&& newfd
< 0)
3379 newfd
= hold_locked_index(&lock_file
, 1);
3382 if (read_cache() < 0)
3383 die("unable to read index file");
3386 if ((check
|| apply
) &&
3387 check_patch_list(list
) < 0 &&
3391 if (apply
&& write_out_results(list
, skipped_patch
))
3395 build_fake_ancestor(list
, fake_ancestor
);
3398 stat_patch_list(list
);
3401 numstat_patch_list(list
);
3404 summary_patch_list(list
);
3406 strbuf_release(&buf
);
3410 static int git_apply_config(const char *var
, const char *value
, void *cb
)
3412 if (!strcmp(var
, "apply.whitespace"))
3413 return git_config_string(&apply_default_whitespace
, var
, value
);
3414 else if (!strcmp(var
, "apply.ignorewhitespace"))
3415 return git_config_string(&apply_default_ignorewhitespace
, var
, value
);
3416 return git_default_config(var
, value
, cb
);
3419 static int option_parse_exclude(const struct option
*opt
,
3420 const char *arg
, int unset
)
3422 add_name_limit(arg
, 1);
3426 static int option_parse_include(const struct option
*opt
,
3427 const char *arg
, int unset
)
3429 add_name_limit(arg
, 0);
3434 static int option_parse_p(const struct option
*opt
,
3435 const char *arg
, int unset
)
3437 p_value
= atoi(arg
);
3442 static int option_parse_z(const struct option
*opt
,
3443 const char *arg
, int unset
)
3446 line_termination
= '\n';
3448 line_termination
= 0;
3452 static int option_parse_space_change(const struct option
*opt
,
3453 const char *arg
, int unset
)
3456 ws_ignore_action
= ignore_ws_none
;
3458 ws_ignore_action
= ignore_ws_change
;
3462 static int option_parse_whitespace(const struct option
*opt
,
3463 const char *arg
, int unset
)
3465 const char **whitespace_option
= opt
->value
;
3467 *whitespace_option
= arg
;
3468 parse_whitespace_option(arg
);
3472 static int option_parse_directory(const struct option
*opt
,
3473 const char *arg
, int unset
)
3475 root_len
= strlen(arg
);
3476 if (root_len
&& arg
[root_len
- 1] != '/') {
3478 root
= new_root
= xmalloc(root_len
+ 2);
3479 strcpy(new_root
, arg
);
3480 strcpy(new_root
+ root_len
++, "/");
3486 int cmd_apply(int argc
, const char **argv
, const char *unused_prefix
)
3492 int force_apply
= 0;
3494 const char *whitespace_option
= NULL
;
3496 struct option builtin_apply_options
[] = {
3497 { OPTION_CALLBACK
, 0, "exclude", NULL
, "path",
3498 "don't apply changes matching the given path",
3499 0, option_parse_exclude
},
3500 { OPTION_CALLBACK
, 0, "include", NULL
, "path",
3501 "apply changes matching the given path",
3502 0, option_parse_include
},
3503 { OPTION_CALLBACK
, 'p', NULL
, NULL
, "num",
3504 "remove <num> leading slashes from traditional diff paths",
3505 0, option_parse_p
},
3506 OPT_BOOLEAN(0, "no-add", &no_add
,
3507 "ignore additions made by the patch"),
3508 OPT_BOOLEAN(0, "stat", &diffstat
,
3509 "instead of applying the patch, output diffstat for the input"),
3510 { OPTION_BOOLEAN
, 0, "allow-binary-replacement", &binary
,
3511 NULL
, "old option, now no-op",
3512 PARSE_OPT_HIDDEN
| PARSE_OPT_NOARG
},
3513 { OPTION_BOOLEAN
, 0, "binary", &binary
,
3514 NULL
, "old option, now no-op",
3515 PARSE_OPT_HIDDEN
| PARSE_OPT_NOARG
},
3516 OPT_BOOLEAN(0, "numstat", &numstat
,
3517 "shows number of added and deleted lines in decimal notation"),
3518 OPT_BOOLEAN(0, "summary", &summary
,
3519 "instead of applying the patch, output a summary for the input"),
3520 OPT_BOOLEAN(0, "check", &check
,
3521 "instead of applying the patch, see if the patch is applicable"),
3522 OPT_BOOLEAN(0, "index", &check_index
,
3523 "make sure the patch is applicable to the current index"),
3524 OPT_BOOLEAN(0, "cached", &cached
,
3525 "apply a patch without touching the working tree"),
3526 OPT_BOOLEAN(0, "apply", &force_apply
,
3527 "also apply the patch (use with --stat/--summary/--check)"),
3528 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor
,
3529 "build a temporary index based on embedded index information"),
3530 { OPTION_CALLBACK
, 'z', NULL
, NULL
, NULL
,
3531 "paths are separated with NUL character",
3532 PARSE_OPT_NOARG
, option_parse_z
},
3533 OPT_INTEGER('C', NULL
, &p_context
,
3534 "ensure at least <n> lines of context match"),
3535 { OPTION_CALLBACK
, 0, "whitespace", &whitespace_option
, "action",
3536 "detect new or modified lines that have whitespace errors",
3537 0, option_parse_whitespace
},
3538 { OPTION_CALLBACK
, 0, "ignore-space-change", NULL
, NULL
,
3539 "ignore changes in whitespace when finding context",
3540 PARSE_OPT_NOARG
, option_parse_space_change
},
3541 { OPTION_CALLBACK
, 0, "ignore-whitespace", NULL
, NULL
,
3542 "ignore changes in whitespace when finding context",
3543 PARSE_OPT_NOARG
, option_parse_space_change
},
3544 OPT_BOOLEAN('R', "reverse", &apply_in_reverse
,
3545 "apply the patch in reverse"),
3546 OPT_BOOLEAN(0, "unidiff-zero", &unidiff_zero
,
3547 "don't expect at least one line of context"),
3548 OPT_BOOLEAN(0, "reject", &apply_with_reject
,
3549 "leave the rejected hunks in corresponding *.rej files"),
3550 OPT__VERBOSE(&apply_verbosely
),
3551 OPT_BIT(0, "inaccurate-eof", &options
,
3552 "tolerate incorrectly detected missing new-line at the end of file",
3554 OPT_BIT(0, "recount", &options
,
3555 "do not trust the line counts in the hunk headers",
3557 { OPTION_CALLBACK
, 0, "directory", NULL
, "root",
3558 "prepend <root> to all filenames",
3559 0, option_parse_directory
},
3563 prefix
= setup_git_directory_gently(&is_not_gitdir
);
3564 prefix_length
= prefix
? strlen(prefix
) : 0;
3565 git_config(git_apply_config
, NULL
);
3566 if (apply_default_whitespace
)
3567 parse_whitespace_option(apply_default_whitespace
);
3568 if (apply_default_ignorewhitespace
)
3569 parse_ignorewhitespace_option(apply_default_ignorewhitespace
);
3571 argc
= parse_options(argc
, argv
, prefix
, builtin_apply_options
,
3574 if (apply_with_reject
)
3575 apply
= apply_verbosely
= 1;
3576 if (!force_apply
&& (diffstat
|| numstat
|| summary
|| check
|| fake_ancestor
))
3578 if (check_index
&& is_not_gitdir
)
3579 die("--index outside a repository");
3582 die("--cached outside a repository");
3585 for (i
= 0; i
< argc
; i
++) {
3586 const char *arg
= argv
[i
];
3589 if (!strcmp(arg
, "-")) {
3590 errs
|= apply_patch(0, "<stdin>", options
);
3593 } else if (0 < prefix_length
)
3594 arg
= prefix_filename(prefix
, prefix_length
, arg
);
3596 fd
= open(arg
, O_RDONLY
);
3598 die_errno("can't open patch '%s'", arg
);
3600 set_default_whitespace_mode(whitespace_option
);
3601 errs
|= apply_patch(fd
, arg
, options
);
3604 set_default_whitespace_mode(whitespace_option
);
3606 errs
|= apply_patch(0, "<stdin>", options
);
3607 if (whitespace_error
) {
3608 if (squelch_whitespace_errors
&&
3609 squelch_whitespace_errors
< whitespace_error
) {
3611 whitespace_error
- squelch_whitespace_errors
;
3612 warning("squelched %d "
3613 "whitespace error%s",
3615 squelched
== 1 ? "" : "s");
3617 if (ws_error_action
== die_on_ws_error
)
3618 die("%d line%s add%s whitespace errors.",
3620 whitespace_error
== 1 ? "" : "s",
3621 whitespace_error
== 1 ? "s" : "");
3622 if (applied_after_fixing_ws
&& apply
)
3623 warning("%d line%s applied after"
3624 " fixing whitespace errors.",
3625 applied_after_fixing_ws
,
3626 applied_after_fixing_ws
== 1 ? "" : "s");
3627 else if (whitespace_error
)
3628 warning("%d line%s add%s whitespace errors.",
3630 whitespace_error
== 1 ? "" : "s",
3631 whitespace_error
== 1 ? "s" : "");
3635 if (write_cache(newfd
, active_cache
, active_nr
) ||
3636 commit_locked_index(&lock_file
))
3637 die("Unable to write new index file");