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"
18 #include "parse-options.h"
19 #include "xdiff-interface.h"
24 * --check turns on checking that the working tree matches the
25 * files that are being modified, but doesn't apply the patch
26 * --stat does just a diffstat, and doesn't actually apply
27 * --numstat does numeric diffstat, and doesn't actually apply
28 * --index-info shows the old and new index info for paths if available.
29 * --index updates the cache as well.
30 * --cached updates only the cache without ever touching the working tree.
32 static const char *prefix
;
33 static int prefix_length
= -1;
34 static int newfd
= -1;
36 static int unidiff_zero
;
37 static int p_value
= 1;
38 static int p_value_known
;
39 static int check_index
;
40 static int update_index
;
47 static int apply_in_reverse
;
48 static int apply_with_reject
;
49 static int apply_verbosely
;
50 static int allow_overlap
;
53 static const char *fake_ancestor
;
54 static int line_termination
= '\n';
55 static unsigned int p_context
= UINT_MAX
;
56 static const char * const apply_usage
[] = {
57 N_("git apply [options] [<patch>...]"),
61 static enum ws_error_action
{
66 } ws_error_action
= warn_on_ws_error
;
67 static int whitespace_error
;
68 static int squelch_whitespace_errors
= 5;
69 static int applied_after_fixing_ws
;
71 static enum ws_ignore
{
74 } ws_ignore_action
= ignore_ws_none
;
77 static const char *patch_input_file
;
78 static const char *root
;
80 static int read_stdin
= 1;
83 static void parse_whitespace_option(const char *option
)
86 ws_error_action
= warn_on_ws_error
;
89 if (!strcmp(option
, "warn")) {
90 ws_error_action
= warn_on_ws_error
;
93 if (!strcmp(option
, "nowarn")) {
94 ws_error_action
= nowarn_ws_error
;
97 if (!strcmp(option
, "error")) {
98 ws_error_action
= die_on_ws_error
;
101 if (!strcmp(option
, "error-all")) {
102 ws_error_action
= die_on_ws_error
;
103 squelch_whitespace_errors
= 0;
106 if (!strcmp(option
, "strip") || !strcmp(option
, "fix")) {
107 ws_error_action
= correct_ws_error
;
110 die(_("unrecognized whitespace option '%s'"), option
);
113 static void parse_ignorewhitespace_option(const char *option
)
115 if (!option
|| !strcmp(option
, "no") ||
116 !strcmp(option
, "false") || !strcmp(option
, "never") ||
117 !strcmp(option
, "none")) {
118 ws_ignore_action
= ignore_ws_none
;
121 if (!strcmp(option
, "change")) {
122 ws_ignore_action
= ignore_ws_change
;
125 die(_("unrecognized whitespace ignore option '%s'"), option
);
128 static void set_default_whitespace_mode(const char *whitespace_option
)
130 if (!whitespace_option
&& !apply_default_whitespace
)
131 ws_error_action
= (apply
? warn_on_ws_error
: nowarn_ws_error
);
135 * For "diff-stat" like behaviour, we keep track of the biggest change
136 * we've seen, and the longest filename. That allows us to do simple
139 static int max_change
, max_len
;
142 * Various "current state", notably line numbers and what
143 * file (and how) we're patching right now.. The "is_xxxx"
144 * things are flags, where -1 means "don't know yet".
146 static int linenr
= 1;
149 * This represents one "hunk" from a patch, starting with
150 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
151 * patch text is pointed at by patch, and its byte length
152 * is stored in size. leading and trailing are the number
156 unsigned long leading
, trailing
;
157 unsigned long oldpos
, oldlines
;
158 unsigned long newpos
, newlines
;
160 * 'patch' is usually borrowed from buf in apply_patch(),
161 * but some codepaths store an allocated buffer.
164 unsigned free_patch
:1,
168 struct fragment
*next
;
172 * When dealing with a binary patch, we reuse "leading" field
173 * to store the type of the binary hunk, either deflated "delta"
174 * or deflated "literal".
176 #define binary_patch_method leading
177 #define BINARY_DELTA_DEFLATED 1
178 #define BINARY_LITERAL_DEFLATED 2
181 * This represents a "patch" to a file, both metainfo changes
182 * such as creation/deletion, filemode and content changes represented
183 * as a series of fragments.
186 char *new_name
, *old_name
, *def_name
;
187 unsigned int old_mode
, new_mode
;
188 int is_new
, is_delete
; /* -1 = unknown, 0 = false, 1 = true */
191 int lines_added
, lines_deleted
;
193 unsigned int is_toplevel_relative
:1;
194 unsigned int inaccurate_eof
:1;
195 unsigned int is_binary
:1;
196 unsigned int is_copy
:1;
197 unsigned int is_rename
:1;
198 unsigned int recount
:1;
199 unsigned int conflicted_threeway
:1;
200 unsigned int direct_to_threeway
:1;
201 struct fragment
*fragments
;
204 char old_sha1_prefix
[41];
205 char new_sha1_prefix
[41];
208 /* three-way fallback result */
209 unsigned char threeway_stage
[3][20];
212 static void free_fragment_list(struct fragment
*list
)
215 struct fragment
*next
= list
->next
;
216 if (list
->free_patch
)
217 free((char *)list
->patch
);
223 static void free_patch(struct patch
*patch
)
225 free_fragment_list(patch
->fragments
);
226 free(patch
->def_name
);
227 free(patch
->old_name
);
228 free(patch
->new_name
);
233 static void free_patch_list(struct patch
*list
)
236 struct patch
*next
= list
->next
;
243 * A line in a file, len-bytes long (includes the terminating LF,
244 * except for an incomplete line at the end if the file ends with
245 * one), and its contents hashes to 'hash'.
251 #define LINE_COMMON 1
252 #define LINE_PATCHED 2
256 * This represents a "file", which is an array of "lines".
263 struct line
*line_allocated
;
268 * Records filenames that have been touched, in order to handle
269 * the case where more than one patches touch the same file.
272 static struct string_list fn_table
;
274 static uint32_t hash_line(const char *cp
, size_t len
)
278 for (i
= 0, h
= 0; i
< len
; i
++) {
279 if (!isspace(cp
[i
])) {
280 h
= h
* 3 + (cp
[i
] & 0xff);
287 * Compare lines s1 of length n1 and s2 of length n2, ignoring
288 * whitespace difference. Returns 1 if they match, 0 otherwise
290 static int fuzzy_matchlines(const char *s1
, size_t n1
,
291 const char *s2
, size_t n2
)
293 const char *last1
= s1
+ n1
- 1;
294 const char *last2
= s2
+ n2
- 1;
297 /* ignore line endings */
298 while ((*last1
== '\r') || (*last1
== '\n'))
300 while ((*last2
== '\r') || (*last2
== '\n'))
303 /* skip leading whitespace */
304 while (isspace(*s1
) && (s1
<= last1
))
306 while (isspace(*s2
) && (s2
<= last2
))
308 /* early return if both lines are empty */
309 if ((s1
> last1
) && (s2
> last2
))
312 result
= *s1
++ - *s2
++;
314 * Skip whitespace inside. We check for whitespace on
315 * both buffers because we don't want "a b" to match
318 if (isspace(*s1
) && isspace(*s2
)) {
319 while (isspace(*s1
) && s1
<= last1
)
321 while (isspace(*s2
) && s2
<= last2
)
325 * If we reached the end on one side only,
329 ((s2
> last2
) && (s1
<= last1
)) ||
330 ((s1
> last1
) && (s2
<= last2
)))
332 if ((s1
> last1
) && (s2
> last2
))
339 static void add_line_info(struct image
*img
, const char *bol
, size_t len
, unsigned flag
)
341 ALLOC_GROW(img
->line_allocated
, img
->nr
+ 1, img
->alloc
);
342 img
->line_allocated
[img
->nr
].len
= len
;
343 img
->line_allocated
[img
->nr
].hash
= hash_line(bol
, len
);
344 img
->line_allocated
[img
->nr
].flag
= flag
;
349 * "buf" has the file contents to be patched (read from various sources).
350 * attach it to "image" and add line-based index to it.
351 * "image" now owns the "buf".
353 static void prepare_image(struct image
*image
, char *buf
, size_t len
,
354 int prepare_linetable
)
358 memset(image
, 0, sizeof(*image
));
362 if (!prepare_linetable
)
365 ep
= image
->buf
+ image
->len
;
369 for (next
= cp
; next
< ep
&& *next
!= '\n'; next
++)
373 add_line_info(image
, cp
, next
- cp
, 0);
376 image
->line
= image
->line_allocated
;
379 static void clear_image(struct image
*image
)
382 free(image
->line_allocated
);
383 memset(image
, 0, sizeof(*image
));
386 /* fmt must contain _one_ %s and no other substitution */
387 static void say_patch_name(FILE *output
, const char *fmt
, struct patch
*patch
)
389 struct strbuf sb
= STRBUF_INIT
;
391 if (patch
->old_name
&& patch
->new_name
&&
392 strcmp(patch
->old_name
, patch
->new_name
)) {
393 quote_c_style(patch
->old_name
, &sb
, NULL
, 0);
394 strbuf_addstr(&sb
, " => ");
395 quote_c_style(patch
->new_name
, &sb
, NULL
, 0);
397 const char *n
= patch
->new_name
;
400 quote_c_style(n
, &sb
, NULL
, 0);
402 fprintf(output
, fmt
, sb
.buf
);
409 static void read_patch_file(struct strbuf
*sb
, int fd
)
411 if (strbuf_read(sb
, fd
, 0) < 0)
412 die_errno("git apply: failed to read");
415 * Make sure that we have some slop in the buffer
416 * so that we can do speculative "memcmp" etc, and
417 * see to it that it is NUL-filled.
419 strbuf_grow(sb
, SLOP
);
420 memset(sb
->buf
+ sb
->len
, 0, SLOP
);
423 static unsigned long linelen(const char *buffer
, unsigned long size
)
425 unsigned long len
= 0;
428 if (*buffer
++ == '\n')
434 static int is_dev_null(const char *str
)
436 return !memcmp("/dev/null", str
, 9) && isspace(str
[9]);
442 static int name_terminate(const char *name
, int namelen
, int c
, int terminate
)
444 if (c
== ' ' && !(terminate
& TERM_SPACE
))
446 if (c
== '\t' && !(terminate
& TERM_TAB
))
452 /* remove double slashes to make --index work with such filenames */
453 static char *squash_slash(char *name
)
461 if ((name
[j
++] = name
[i
++]) == '/')
462 while (name
[i
] == '/')
469 static char *find_name_gnu(const char *line
, const char *def
, int p_value
)
471 struct strbuf name
= STRBUF_INIT
;
475 * Proposed "new-style" GNU patch/diff format; see
476 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
478 if (unquote_c_style(&name
, line
, NULL
)) {
479 strbuf_release(&name
);
483 for (cp
= name
.buf
; p_value
; p_value
--) {
484 cp
= strchr(cp
, '/');
486 strbuf_release(&name
);
492 strbuf_remove(&name
, 0, cp
- name
.buf
);
494 strbuf_insert(&name
, 0, root
, root_len
);
495 return squash_slash(strbuf_detach(&name
, NULL
));
498 static size_t sane_tz_len(const char *line
, size_t len
)
502 if (len
< strlen(" +0500") || line
[len
-strlen(" +0500")] != ' ')
504 tz
= line
+ len
- strlen(" +0500");
506 if (tz
[1] != '+' && tz
[1] != '-')
509 for (p
= tz
+ 2; p
!= line
+ len
; p
++)
513 return line
+ len
- tz
;
516 static size_t tz_with_colon_len(const char *line
, size_t len
)
520 if (len
< strlen(" +08:00") || line
[len
- strlen(":00")] != ':')
522 tz
= line
+ len
- strlen(" +08:00");
524 if (tz
[0] != ' ' || (tz
[1] != '+' && tz
[1] != '-'))
527 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
528 !isdigit(*p
++) || !isdigit(*p
++))
531 return line
+ len
- tz
;
534 static size_t date_len(const char *line
, size_t len
)
536 const char *date
, *p
;
538 if (len
< strlen("72-02-05") || line
[len
-strlen("-05")] != '-')
540 p
= date
= line
+ len
- strlen("72-02-05");
542 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
543 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
544 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a date. */
547 if (date
- line
>= strlen("19") &&
548 isdigit(date
[-1]) && isdigit(date
[-2])) /* 4-digit year */
549 date
-= strlen("19");
551 return line
+ len
- date
;
554 static size_t short_time_len(const char *line
, size_t len
)
556 const char *time
, *p
;
558 if (len
< strlen(" 07:01:32") || line
[len
-strlen(":32")] != ':')
560 p
= time
= line
+ len
- strlen(" 07:01:32");
562 /* Permit 1-digit hours? */
564 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
565 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
566 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a time. */
569 return line
+ len
- time
;
572 static size_t fractional_time_len(const char *line
, size_t len
)
577 /* Expected format: 19:41:17.620000023 */
578 if (!len
|| !isdigit(line
[len
- 1]))
582 /* Fractional seconds. */
583 while (p
> line
&& isdigit(*p
))
588 /* Hours, minutes, and whole seconds. */
589 n
= short_time_len(line
, p
- line
);
593 return line
+ len
- p
+ n
;
596 static size_t trailing_spaces_len(const char *line
, size_t len
)
600 /* Expected format: ' ' x (1 or more) */
601 if (!len
|| line
[len
- 1] != ' ')
608 return line
+ len
- (p
+ 1);
615 static size_t diff_timestamp_len(const char *line
, size_t len
)
617 const char *end
= line
+ len
;
621 * Posix: 2010-07-05 19:41:17
622 * GNU: 2010-07-05 19:41:17.620000023 -0500
625 if (!isdigit(end
[-1]))
628 n
= sane_tz_len(line
, end
- line
);
630 n
= tz_with_colon_len(line
, end
- line
);
633 n
= short_time_len(line
, end
- line
);
635 n
= fractional_time_len(line
, end
- line
);
638 n
= date_len(line
, end
- line
);
639 if (!n
) /* No date. Too bad. */
643 if (end
== line
) /* No space before date. */
645 if (end
[-1] == '\t') { /* Success! */
647 return line
+ len
- end
;
649 if (end
[-1] != ' ') /* No space before date. */
652 /* Whitespace damage. */
653 end
-= trailing_spaces_len(line
, end
- line
);
654 return line
+ len
- end
;
657 static char *null_strdup(const char *s
)
659 return s
? xstrdup(s
) : NULL
;
662 static char *find_name_common(const char *line
, const char *def
,
663 int p_value
, const char *end
, int terminate
)
666 const char *start
= NULL
;
670 while (line
!= end
) {
673 if (!end
&& isspace(c
)) {
676 if (name_terminate(start
, line
-start
, c
, terminate
))
680 if (c
== '/' && !--p_value
)
684 return squash_slash(null_strdup(def
));
687 return squash_slash(null_strdup(def
));
690 * Generally we prefer the shorter name, especially
691 * if the other one is just a variation of that with
692 * something else tacked on to the end (ie "file.orig"
696 int deflen
= strlen(def
);
697 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
698 return squash_slash(xstrdup(def
));
702 char *ret
= xmalloc(root_len
+ len
+ 1);
704 memcpy(ret
+ root_len
, start
, len
);
705 ret
[root_len
+ len
] = '\0';
706 return squash_slash(ret
);
709 return squash_slash(xmemdupz(start
, len
));
712 static char *find_name(const char *line
, char *def
, int p_value
, int terminate
)
715 char *name
= find_name_gnu(line
, def
, p_value
);
720 return find_name_common(line
, def
, p_value
, NULL
, terminate
);
723 static char *find_name_traditional(const char *line
, char *def
, int p_value
)
725 size_t len
= strlen(line
);
729 char *name
= find_name_gnu(line
, def
, p_value
);
734 len
= strchrnul(line
, '\n') - line
;
735 date_len
= diff_timestamp_len(line
, len
);
737 return find_name_common(line
, def
, p_value
, NULL
, TERM_TAB
);
740 return find_name_common(line
, def
, p_value
, line
+ len
, 0);
743 static int count_slashes(const char *cp
)
755 * Given the string after "--- " or "+++ ", guess the appropriate
756 * p_value for the given patch.
758 static int guess_p_value(const char *nameline
)
763 if (is_dev_null(nameline
))
765 name
= find_name_traditional(nameline
, NULL
, 0);
768 cp
= strchr(name
, '/');
773 * Does it begin with "a/$our-prefix" and such? Then this is
774 * very likely to apply to our directory.
776 if (!strncmp(name
, prefix
, prefix_length
))
777 val
= count_slashes(prefix
);
780 if (!strncmp(cp
, prefix
, prefix_length
))
781 val
= count_slashes(prefix
) + 1;
789 * Does the ---/+++ line has the POSIX timestamp after the last HT?
790 * GNU diff puts epoch there to signal a creation/deletion event. Is
791 * this such a timestamp?
793 static int has_epoch_timestamp(const char *nameline
)
796 * We are only interested in epoch timestamp; any non-zero
797 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
798 * For the same reason, the date must be either 1969-12-31 or
799 * 1970-01-01, and the seconds part must be "00".
801 const char stamp_regexp
[] =
802 "^(1969-12-31|1970-01-01)"
804 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
806 "([-+][0-2][0-9]:?[0-5][0-9])\n";
807 const char *timestamp
= NULL
, *cp
, *colon
;
808 static regex_t
*stamp
;
814 for (cp
= nameline
; *cp
!= '\n'; cp
++) {
821 stamp
= xmalloc(sizeof(*stamp
));
822 if (regcomp(stamp
, stamp_regexp
, REG_EXTENDED
)) {
823 warning(_("Cannot prepare timestamp regexp %s"),
829 status
= regexec(stamp
, timestamp
, ARRAY_SIZE(m
), m
, 0);
831 if (status
!= REG_NOMATCH
)
832 warning(_("regexec returned %d for input: %s"),
837 zoneoffset
= strtol(timestamp
+ m
[3].rm_so
+ 1, (char **) &colon
, 10);
839 zoneoffset
= zoneoffset
* 60 + strtol(colon
+ 1, NULL
, 10);
841 zoneoffset
= (zoneoffset
/ 100) * 60 + (zoneoffset
% 100);
842 if (timestamp
[m
[3].rm_so
] == '-')
843 zoneoffset
= -zoneoffset
;
846 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
847 * (west of GMT) or 1970-01-01 (east of GMT)
849 if ((zoneoffset
< 0 && memcmp(timestamp
, "1969-12-31", 10)) ||
850 (0 <= zoneoffset
&& memcmp(timestamp
, "1970-01-01", 10)))
853 hourminute
= (strtol(timestamp
+ 11, NULL
, 10) * 60 +
854 strtol(timestamp
+ 14, NULL
, 10) -
857 return ((zoneoffset
< 0 && hourminute
== 1440) ||
858 (0 <= zoneoffset
&& !hourminute
));
862 * Get the name etc info from the ---/+++ lines of a traditional patch header
864 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
865 * files, we can happily check the index for a match, but for creating a
866 * new file we should try to match whatever "patch" does. I have no idea.
868 static void parse_traditional_patch(const char *first
, const char *second
, struct patch
*patch
)
872 first
+= 4; /* skip "--- " */
873 second
+= 4; /* skip "+++ " */
874 if (!p_value_known
) {
876 p
= guess_p_value(first
);
877 q
= guess_p_value(second
);
879 if (0 <= p
&& p
== q
) {
884 if (is_dev_null(first
)) {
886 patch
->is_delete
= 0;
887 name
= find_name_traditional(second
, NULL
, p_value
);
888 patch
->new_name
= name
;
889 } else if (is_dev_null(second
)) {
891 patch
->is_delete
= 1;
892 name
= find_name_traditional(first
, NULL
, p_value
);
893 patch
->old_name
= name
;
896 first_name
= find_name_traditional(first
, NULL
, p_value
);
897 name
= find_name_traditional(second
, first_name
, p_value
);
899 if (has_epoch_timestamp(first
)) {
901 patch
->is_delete
= 0;
902 patch
->new_name
= name
;
903 } else if (has_epoch_timestamp(second
)) {
905 patch
->is_delete
= 1;
906 patch
->old_name
= name
;
908 patch
->old_name
= name
;
909 patch
->new_name
= xstrdup(name
);
913 die(_("unable to find filename in patch at line %d"), linenr
);
916 static int gitdiff_hdrend(const char *line
, struct patch
*patch
)
922 * We're anal about diff header consistency, to make
923 * sure that we don't end up having strange ambiguous
924 * patches floating around.
926 * As a result, gitdiff_{old|new}name() will check
927 * their names against any previous information, just
930 #define DIFF_OLD_NAME 0
931 #define DIFF_NEW_NAME 1
933 static char *gitdiff_verify_name(const char *line
, int isnull
, char *orig_name
, int side
)
935 if (!orig_name
&& !isnull
)
936 return find_name(line
, NULL
, p_value
, TERM_TAB
);
945 die(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"), name
, linenr
);
946 another
= find_name(line
, NULL
, p_value
, TERM_TAB
);
947 if (!another
|| memcmp(another
, name
, len
+ 1))
948 die((side
== DIFF_NEW_NAME
) ?
949 _("git apply: bad git-diff - inconsistent new filename on line %d") :
950 _("git apply: bad git-diff - inconsistent old filename on line %d"), linenr
);
955 /* expect "/dev/null" */
956 if (memcmp("/dev/null", line
, 9) || line
[9] != '\n')
957 die(_("git apply: bad git-diff - expected /dev/null on line %d"), linenr
);
962 static int gitdiff_oldname(const char *line
, struct patch
*patch
)
964 char *orig
= patch
->old_name
;
965 patch
->old_name
= gitdiff_verify_name(line
, patch
->is_new
, patch
->old_name
,
967 if (orig
!= patch
->old_name
)
972 static int gitdiff_newname(const char *line
, struct patch
*patch
)
974 char *orig
= patch
->new_name
;
975 patch
->new_name
= gitdiff_verify_name(line
, patch
->is_delete
, patch
->new_name
,
977 if (orig
!= patch
->new_name
)
982 static int gitdiff_oldmode(const char *line
, struct patch
*patch
)
984 patch
->old_mode
= strtoul(line
, NULL
, 8);
988 static int gitdiff_newmode(const char *line
, struct patch
*patch
)
990 patch
->new_mode
= strtoul(line
, NULL
, 8);
994 static int gitdiff_delete(const char *line
, struct patch
*patch
)
996 patch
->is_delete
= 1;
997 free(patch
->old_name
);
998 patch
->old_name
= null_strdup(patch
->def_name
);
999 return gitdiff_oldmode(line
, patch
);
1002 static int gitdiff_newfile(const char *line
, struct patch
*patch
)
1005 free(patch
->new_name
);
1006 patch
->new_name
= null_strdup(patch
->def_name
);
1007 return gitdiff_newmode(line
, patch
);
1010 static int gitdiff_copysrc(const char *line
, struct patch
*patch
)
1013 free(patch
->old_name
);
1014 patch
->old_name
= find_name(line
, NULL
, p_value
? p_value
- 1 : 0, 0);
1018 static int gitdiff_copydst(const char *line
, struct patch
*patch
)
1021 free(patch
->new_name
);
1022 patch
->new_name
= find_name(line
, NULL
, p_value
? p_value
- 1 : 0, 0);
1026 static int gitdiff_renamesrc(const char *line
, struct patch
*patch
)
1028 patch
->is_rename
= 1;
1029 free(patch
->old_name
);
1030 patch
->old_name
= find_name(line
, NULL
, p_value
? p_value
- 1 : 0, 0);
1034 static int gitdiff_renamedst(const char *line
, struct patch
*patch
)
1036 patch
->is_rename
= 1;
1037 free(patch
->new_name
);
1038 patch
->new_name
= find_name(line
, NULL
, p_value
? p_value
- 1 : 0, 0);
1042 static int gitdiff_similarity(const char *line
, struct patch
*patch
)
1044 if ((patch
->score
= strtoul(line
, NULL
, 10)) == ULONG_MAX
)
1049 static int gitdiff_dissimilarity(const char *line
, struct patch
*patch
)
1051 if ((patch
->score
= strtoul(line
, NULL
, 10)) == ULONG_MAX
)
1056 static int gitdiff_index(const char *line
, struct patch
*patch
)
1059 * index line is N hexadecimal, "..", N hexadecimal,
1060 * and optional space with octal mode.
1062 const char *ptr
, *eol
;
1065 ptr
= strchr(line
, '.');
1066 if (!ptr
|| ptr
[1] != '.' || 40 < ptr
- line
)
1069 memcpy(patch
->old_sha1_prefix
, line
, len
);
1070 patch
->old_sha1_prefix
[len
] = 0;
1073 ptr
= strchr(line
, ' ');
1074 eol
= strchr(line
, '\n');
1076 if (!ptr
|| eol
< ptr
)
1082 memcpy(patch
->new_sha1_prefix
, line
, len
);
1083 patch
->new_sha1_prefix
[len
] = 0;
1085 patch
->old_mode
= strtoul(ptr
+1, NULL
, 8);
1090 * This is normal for a diff that doesn't change anything: we'll fall through
1091 * into the next diff. Tell the parser to break out.
1093 static int gitdiff_unrecognized(const char *line
, struct patch
*patch
)
1098 static const char *stop_at_slash(const char *line
, int llen
)
1100 int nslash
= p_value
;
1103 for (i
= 0; i
< llen
; i
++) {
1105 if (ch
== '/' && --nslash
<= 0)
1112 * This is to extract the same name that appears on "diff --git"
1113 * line. We do not find and return anything if it is a rename
1114 * patch, and it is OK because we will find the name elsewhere.
1115 * We need to reliably find name only when it is mode-change only,
1116 * creation or deletion of an empty file. In any of these cases,
1117 * both sides are the same name under a/ and b/ respectively.
1119 static char *git_header_name(const char *line
, int llen
)
1122 const char *second
= NULL
;
1123 size_t len
, line_len
;
1125 line
+= strlen("diff --git ");
1126 llen
-= strlen("diff --git ");
1130 struct strbuf first
= STRBUF_INIT
;
1131 struct strbuf sp
= STRBUF_INIT
;
1133 if (unquote_c_style(&first
, line
, &second
))
1134 goto free_and_fail1
;
1136 /* advance to the first slash */
1137 cp
= stop_at_slash(first
.buf
, first
.len
);
1138 /* we do not accept absolute paths */
1139 if (!cp
|| cp
== first
.buf
)
1140 goto free_and_fail1
;
1141 strbuf_remove(&first
, 0, cp
+ 1 - first
.buf
);
1144 * second points at one past closing dq of name.
1145 * find the second name.
1147 while ((second
< line
+ llen
) && isspace(*second
))
1150 if (line
+ llen
<= second
)
1151 goto free_and_fail1
;
1152 if (*second
== '"') {
1153 if (unquote_c_style(&sp
, second
, NULL
))
1154 goto free_and_fail1
;
1155 cp
= stop_at_slash(sp
.buf
, sp
.len
);
1156 if (!cp
|| cp
== sp
.buf
)
1157 goto free_and_fail1
;
1158 /* They must match, otherwise ignore */
1159 if (strcmp(cp
+ 1, first
.buf
))
1160 goto free_and_fail1
;
1161 strbuf_release(&sp
);
1162 return strbuf_detach(&first
, NULL
);
1165 /* unquoted second */
1166 cp
= stop_at_slash(second
, line
+ llen
- second
);
1167 if (!cp
|| cp
== second
)
1168 goto free_and_fail1
;
1170 if (line
+ llen
- cp
!= first
.len
+ 1 ||
1171 memcmp(first
.buf
, cp
, first
.len
))
1172 goto free_and_fail1
;
1173 return strbuf_detach(&first
, NULL
);
1176 strbuf_release(&first
);
1177 strbuf_release(&sp
);
1181 /* unquoted first name */
1182 name
= stop_at_slash(line
, llen
);
1183 if (!name
|| name
== line
)
1188 * since the first name is unquoted, a dq if exists must be
1189 * the beginning of the second name.
1191 for (second
= name
; second
< line
+ llen
; second
++) {
1192 if (*second
== '"') {
1193 struct strbuf sp
= STRBUF_INIT
;
1196 if (unquote_c_style(&sp
, second
, NULL
))
1197 goto free_and_fail2
;
1199 np
= stop_at_slash(sp
.buf
, sp
.len
);
1200 if (!np
|| np
== sp
.buf
)
1201 goto free_and_fail2
;
1204 len
= sp
.buf
+ sp
.len
- np
;
1205 if (len
< second
- name
&&
1206 !strncmp(np
, name
, len
) &&
1207 isspace(name
[len
])) {
1209 strbuf_remove(&sp
, 0, np
- sp
.buf
);
1210 return strbuf_detach(&sp
, NULL
);
1214 strbuf_release(&sp
);
1220 * Accept a name only if it shows up twice, exactly the same
1223 second
= strchr(name
, '\n');
1226 line_len
= second
- name
;
1227 for (len
= 0 ; ; len
++) {
1228 switch (name
[len
]) {
1233 case '\t': case ' ':
1234 second
= stop_at_slash(name
+ len
, line_len
- len
);
1238 if (second
[len
] == '\n' && !strncmp(name
, second
, len
)) {
1239 return xmemdupz(name
, len
);
1245 /* Verify that we recognize the lines following a git header */
1246 static int parse_git_header(const char *line
, int len
, unsigned int size
, struct patch
*patch
)
1248 unsigned long offset
;
1250 /* A git diff has explicit new/delete information, so we don't guess */
1252 patch
->is_delete
= 0;
1255 * Some things may not have the old name in the
1256 * rest of the headers anywhere (pure mode changes,
1257 * or removing or adding empty files), so we get
1258 * the default name from the header.
1260 patch
->def_name
= git_header_name(line
, len
);
1261 if (patch
->def_name
&& root
) {
1262 char *s
= xmalloc(root_len
+ strlen(patch
->def_name
) + 1);
1264 strcpy(s
+ root_len
, patch
->def_name
);
1265 free(patch
->def_name
);
1266 patch
->def_name
= s
;
1272 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1273 static const struct opentry
{
1275 int (*fn
)(const char *, struct patch
*);
1277 { "@@ -", gitdiff_hdrend
},
1278 { "--- ", gitdiff_oldname
},
1279 { "+++ ", gitdiff_newname
},
1280 { "old mode ", gitdiff_oldmode
},
1281 { "new mode ", gitdiff_newmode
},
1282 { "deleted file mode ", gitdiff_delete
},
1283 { "new file mode ", gitdiff_newfile
},
1284 { "copy from ", gitdiff_copysrc
},
1285 { "copy to ", gitdiff_copydst
},
1286 { "rename old ", gitdiff_renamesrc
},
1287 { "rename new ", gitdiff_renamedst
},
1288 { "rename from ", gitdiff_renamesrc
},
1289 { "rename to ", gitdiff_renamedst
},
1290 { "similarity index ", gitdiff_similarity
},
1291 { "dissimilarity index ", gitdiff_dissimilarity
},
1292 { "index ", gitdiff_index
},
1293 { "", gitdiff_unrecognized
},
1297 len
= linelen(line
, size
);
1298 if (!len
|| line
[len
-1] != '\n')
1300 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
1301 const struct opentry
*p
= optable
+ i
;
1302 int oplen
= strlen(p
->str
);
1303 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
1305 if (p
->fn(line
+ oplen
, patch
) < 0)
1314 static int parse_num(const char *line
, unsigned long *p
)
1318 if (!isdigit(*line
))
1320 *p
= strtoul(line
, &ptr
, 10);
1324 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
1325 unsigned long *p1
, unsigned long *p2
)
1329 if (offset
< 0 || offset
>= len
)
1334 digits
= parse_num(line
, p1
);
1344 digits
= parse_num(line
+1, p2
);
1353 ex
= strlen(expect
);
1356 if (memcmp(line
, expect
, ex
))
1362 static void recount_diff(const char *line
, int size
, struct fragment
*fragment
)
1364 int oldlines
= 0, newlines
= 0, ret
= 0;
1367 warning("recount: ignore empty hunk");
1372 int len
= linelen(line
, size
);
1380 case ' ': case '\n':
1392 ret
= size
< 3 || prefixcmp(line
, "@@ ");
1395 ret
= size
< 5 || prefixcmp(line
, "diff ");
1402 warning(_("recount: unexpected line: %.*s"),
1403 (int)linelen(line
, size
), line
);
1408 fragment
->oldlines
= oldlines
;
1409 fragment
->newlines
= newlines
;
1413 * Parse a unified diff fragment header of the
1414 * form "@@ -a,b +c,d @@"
1416 static int parse_fragment_header(const char *line
, int len
, struct fragment
*fragment
)
1420 if (!len
|| line
[len
-1] != '\n')
1423 /* Figure out the number of lines in a fragment */
1424 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
1425 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
1430 static int find_header(const char *line
, unsigned long size
, int *hdrsize
, struct patch
*patch
)
1432 unsigned long offset
, len
;
1434 patch
->is_toplevel_relative
= 0;
1435 patch
->is_rename
= patch
->is_copy
= 0;
1436 patch
->is_new
= patch
->is_delete
= -1;
1437 patch
->old_mode
= patch
->new_mode
= 0;
1438 patch
->old_name
= patch
->new_name
= NULL
;
1439 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1440 unsigned long nextlen
;
1442 len
= linelen(line
, size
);
1446 /* Testing this early allows us to take a few shortcuts.. */
1451 * Make sure we don't find any unconnected patch fragments.
1452 * That's a sign that we didn't find a header, and that a
1453 * patch has become corrupted/broken up.
1455 if (!memcmp("@@ -", line
, 4)) {
1456 struct fragment dummy
;
1457 if (parse_fragment_header(line
, len
, &dummy
) < 0)
1459 die(_("patch fragment without header at line %d: %.*s"),
1460 linenr
, (int)len
-1, line
);
1467 * Git patch? It might not have a real patch, just a rename
1468 * or mode change, so we handle that specially
1470 if (!memcmp("diff --git ", line
, 11)) {
1471 int git_hdr_len
= parse_git_header(line
, len
, size
, patch
);
1472 if (git_hdr_len
<= len
)
1474 if (!patch
->old_name
&& !patch
->new_name
) {
1475 if (!patch
->def_name
)
1476 die(Q_("git diff header lacks filename information when removing "
1477 "%d leading pathname component (line %d)",
1478 "git diff header lacks filename information when removing "
1479 "%d leading pathname components (line %d)",
1482 patch
->old_name
= xstrdup(patch
->def_name
);
1483 patch
->new_name
= xstrdup(patch
->def_name
);
1485 if (!patch
->is_delete
&& !patch
->new_name
)
1486 die("git diff header lacks filename information "
1487 "(line %d)", linenr
);
1488 patch
->is_toplevel_relative
= 1;
1489 *hdrsize
= git_hdr_len
;
1493 /* --- followed by +++ ? */
1494 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
1498 * We only accept unified patches, so we want it to
1499 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1500 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1502 nextlen
= linelen(line
+ len
, size
- len
);
1503 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
1506 /* Ok, we'll consider it a patch */
1507 parse_traditional_patch(line
, line
+len
, patch
);
1508 *hdrsize
= len
+ nextlen
;
1515 static void record_ws_error(unsigned result
, const char *line
, int len
, int linenr
)
1523 if (squelch_whitespace_errors
&&
1524 squelch_whitespace_errors
< whitespace_error
)
1527 err
= whitespace_error_string(result
);
1528 fprintf(stderr
, "%s:%d: %s.\n%.*s\n",
1529 patch_input_file
, linenr
, err
, len
, line
);
1533 static void check_whitespace(const char *line
, int len
, unsigned ws_rule
)
1535 unsigned result
= ws_check(line
+ 1, len
- 1, ws_rule
);
1537 record_ws_error(result
, line
+ 1, len
- 2, linenr
);
1541 * Parse a unified diff. Note that this really needs to parse each
1542 * fragment separately, since the only way to know the difference
1543 * between a "---" that is part of a patch, and a "---" that starts
1544 * the next patch is to look at the line counts..
1546 static int parse_fragment(const char *line
, unsigned long size
,
1547 struct patch
*patch
, struct fragment
*fragment
)
1550 int len
= linelen(line
, size
), offset
;
1551 unsigned long oldlines
, newlines
;
1552 unsigned long leading
, trailing
;
1554 offset
= parse_fragment_header(line
, len
, fragment
);
1557 if (offset
> 0 && patch
->recount
)
1558 recount_diff(line
+ offset
, size
- offset
, fragment
);
1559 oldlines
= fragment
->oldlines
;
1560 newlines
= fragment
->newlines
;
1564 /* Parse the thing.. */
1568 added
= deleted
= 0;
1571 offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1572 if (!oldlines
&& !newlines
)
1574 len
= linelen(line
, size
);
1575 if (!len
|| line
[len
-1] != '\n')
1580 case '\n': /* newer GNU diff, an empty context line */
1584 if (!deleted
&& !added
)
1589 if (apply_in_reverse
&&
1590 ws_error_action
!= nowarn_ws_error
)
1591 check_whitespace(line
, len
, patch
->ws_rule
);
1597 if (!apply_in_reverse
&&
1598 ws_error_action
!= nowarn_ws_error
)
1599 check_whitespace(line
, len
, patch
->ws_rule
);
1606 * We allow "\ No newline at end of file". Depending
1607 * on locale settings when the patch was produced we
1608 * don't know what this line looks like. The only
1609 * thing we do know is that it begins with "\ ".
1610 * Checking for 12 is just for sanity check -- any
1611 * l10n of "\ No newline..." is at least that long.
1614 if (len
< 12 || memcmp(line
, "\\ ", 2))
1619 if (oldlines
|| newlines
)
1621 fragment
->leading
= leading
;
1622 fragment
->trailing
= trailing
;
1625 * If a fragment ends with an incomplete line, we failed to include
1626 * it in the above loop because we hit oldlines == newlines == 0
1629 if (12 < size
&& !memcmp(line
, "\\ ", 2))
1630 offset
+= linelen(line
, size
);
1632 patch
->lines_added
+= added
;
1633 patch
->lines_deleted
+= deleted
;
1635 if (0 < patch
->is_new
&& oldlines
)
1636 return error(_("new file depends on old contents"));
1637 if (0 < patch
->is_delete
&& newlines
)
1638 return error(_("deleted file still has contents"));
1643 * We have seen "diff --git a/... b/..." header (or a traditional patch
1644 * header). Read hunks that belong to this patch into fragments and hang
1645 * them to the given patch structure.
1647 * The (fragment->patch, fragment->size) pair points into the memory given
1648 * by the caller, not a copy, when we return.
1650 static int parse_single_patch(const char *line
, unsigned long size
, struct patch
*patch
)
1652 unsigned long offset
= 0;
1653 unsigned long oldlines
= 0, newlines
= 0, context
= 0;
1654 struct fragment
**fragp
= &patch
->fragments
;
1656 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
1657 struct fragment
*fragment
;
1660 fragment
= xcalloc(1, sizeof(*fragment
));
1661 fragment
->linenr
= linenr
;
1662 len
= parse_fragment(line
, size
, patch
, fragment
);
1664 die(_("corrupt patch at line %d"), linenr
);
1665 fragment
->patch
= line
;
1666 fragment
->size
= len
;
1667 oldlines
+= fragment
->oldlines
;
1668 newlines
+= fragment
->newlines
;
1669 context
+= fragment
->leading
+ fragment
->trailing
;
1672 fragp
= &fragment
->next
;
1680 * If something was removed (i.e. we have old-lines) it cannot
1681 * be creation, and if something was added it cannot be
1682 * deletion. However, the reverse is not true; --unified=0
1683 * patches that only add are not necessarily creation even
1684 * though they do not have any old lines, and ones that only
1685 * delete are not necessarily deletion.
1687 * Unfortunately, a real creation/deletion patch do _not_ have
1688 * any context line by definition, so we cannot safely tell it
1689 * apart with --unified=0 insanity. At least if the patch has
1690 * more than one hunk it is not creation or deletion.
1692 if (patch
->is_new
< 0 &&
1693 (oldlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1695 if (patch
->is_delete
< 0 &&
1696 (newlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1697 patch
->is_delete
= 0;
1699 if (0 < patch
->is_new
&& oldlines
)
1700 die(_("new file %s depends on old contents"), patch
->new_name
);
1701 if (0 < patch
->is_delete
&& newlines
)
1702 die(_("deleted file %s still has contents"), patch
->old_name
);
1703 if (!patch
->is_delete
&& !newlines
&& context
)
1706 "file %s becomes empty but is not deleted"),
1712 static inline int metadata_changes(struct patch
*patch
)
1714 return patch
->is_rename
> 0 ||
1715 patch
->is_copy
> 0 ||
1716 patch
->is_new
> 0 ||
1718 (patch
->old_mode
&& patch
->new_mode
&&
1719 patch
->old_mode
!= patch
->new_mode
);
1722 static char *inflate_it(const void *data
, unsigned long size
,
1723 unsigned long inflated_size
)
1729 memset(&stream
, 0, sizeof(stream
));
1731 stream
.next_in
= (unsigned char *)data
;
1732 stream
.avail_in
= size
;
1733 stream
.next_out
= out
= xmalloc(inflated_size
);
1734 stream
.avail_out
= inflated_size
;
1735 git_inflate_init(&stream
);
1736 st
= git_inflate(&stream
, Z_FINISH
);
1737 git_inflate_end(&stream
);
1738 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1746 * Read a binary hunk and return a new fragment; fragment->patch
1747 * points at an allocated memory that the caller must free, so
1748 * it is marked as "->free_patch = 1".
1750 static struct fragment
*parse_binary_hunk(char **buf_p
,
1751 unsigned long *sz_p
,
1756 * Expect a line that begins with binary patch method ("literal"
1757 * or "delta"), followed by the length of data before deflating.
1758 * a sequence of 'length-byte' followed by base-85 encoded data
1759 * should follow, terminated by a newline.
1761 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1762 * and we would limit the patch line to 66 characters,
1763 * so one line can fit up to 13 groups that would decode
1764 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1765 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1768 unsigned long size
= *sz_p
;
1769 char *buffer
= *buf_p
;
1771 unsigned long origlen
;
1774 struct fragment
*frag
;
1776 llen
= linelen(buffer
, size
);
1781 if (!prefixcmp(buffer
, "delta ")) {
1782 patch_method
= BINARY_DELTA_DEFLATED
;
1783 origlen
= strtoul(buffer
+ 6, NULL
, 10);
1785 else if (!prefixcmp(buffer
, "literal ")) {
1786 patch_method
= BINARY_LITERAL_DEFLATED
;
1787 origlen
= strtoul(buffer
+ 8, NULL
, 10);
1795 int byte_length
, max_byte_length
, newsize
;
1796 llen
= linelen(buffer
, size
);
1800 /* consume the blank line */
1806 * Minimum line is "A00000\n" which is 7-byte long,
1807 * and the line length must be multiple of 5 plus 2.
1809 if ((llen
< 7) || (llen
-2) % 5)
1811 max_byte_length
= (llen
- 2) / 5 * 4;
1812 byte_length
= *buffer
;
1813 if ('A' <= byte_length
&& byte_length
<= 'Z')
1814 byte_length
= byte_length
- 'A' + 1;
1815 else if ('a' <= byte_length
&& byte_length
<= 'z')
1816 byte_length
= byte_length
- 'a' + 27;
1819 /* if the input length was not multiple of 4, we would
1820 * have filler at the end but the filler should never
1823 if (max_byte_length
< byte_length
||
1824 byte_length
<= max_byte_length
- 4)
1826 newsize
= hunk_size
+ byte_length
;
1827 data
= xrealloc(data
, newsize
);
1828 if (decode_85(data
+ hunk_size
, buffer
+ 1, byte_length
))
1830 hunk_size
= newsize
;
1835 frag
= xcalloc(1, sizeof(*frag
));
1836 frag
->patch
= inflate_it(data
, hunk_size
, origlen
);
1837 frag
->free_patch
= 1;
1841 frag
->size
= origlen
;
1845 frag
->binary_patch_method
= patch_method
;
1851 error(_("corrupt binary patch at line %d: %.*s"),
1852 linenr
-1, llen
-1, buffer
);
1856 static int parse_binary(char *buffer
, unsigned long size
, struct patch
*patch
)
1859 * We have read "GIT binary patch\n"; what follows is a line
1860 * that says the patch method (currently, either "literal" or
1861 * "delta") and the length of data before deflating; a
1862 * sequence of 'length-byte' followed by base-85 encoded data
1865 * When a binary patch is reversible, there is another binary
1866 * hunk in the same format, starting with patch method (either
1867 * "literal" or "delta") with the length of data, and a sequence
1868 * of length-byte + base-85 encoded data, terminated with another
1869 * empty line. This data, when applied to the postimage, produces
1872 struct fragment
*forward
;
1873 struct fragment
*reverse
;
1877 forward
= parse_binary_hunk(&buffer
, &size
, &status
, &used
);
1878 if (!forward
&& !status
)
1879 /* there has to be one hunk (forward hunk) */
1880 return error(_("unrecognized binary patch at line %d"), linenr
-1);
1882 /* otherwise we already gave an error message */
1885 reverse
= parse_binary_hunk(&buffer
, &size
, &status
, &used_1
);
1890 * Not having reverse hunk is not an error, but having
1891 * a corrupt reverse hunk is.
1893 free((void*) forward
->patch
);
1897 forward
->next
= reverse
;
1898 patch
->fragments
= forward
;
1899 patch
->is_binary
= 1;
1904 * Read the patch text in "buffer" taht extends for "size" bytes; stop
1905 * reading after seeing a single patch (i.e. changes to a single file).
1906 * Create fragments (i.e. patch hunks) and hang them to the given patch.
1907 * Return the number of bytes consumed, so that the caller can call us
1908 * again for the next patch.
1910 static int parse_chunk(char *buffer
, unsigned long size
, struct patch
*patch
)
1912 int hdrsize
, patchsize
;
1913 int offset
= find_header(buffer
, size
, &hdrsize
, patch
);
1918 patch
->ws_rule
= whitespace_rule(patch
->new_name
1922 patchsize
= parse_single_patch(buffer
+ offset
+ hdrsize
,
1923 size
- offset
- hdrsize
, patch
);
1926 static const char *binhdr
[] = {
1931 static const char git_binary
[] = "GIT binary patch\n";
1933 int hd
= hdrsize
+ offset
;
1934 unsigned long llen
= linelen(buffer
+ hd
, size
- hd
);
1936 if (llen
== sizeof(git_binary
) - 1 &&
1937 !memcmp(git_binary
, buffer
+ hd
, llen
)) {
1940 used
= parse_binary(buffer
+ hd
+ llen
,
1941 size
- hd
- llen
, patch
);
1943 patchsize
= used
+ llen
;
1947 else if (!memcmp(" differ\n", buffer
+ hd
+ llen
- 8, 8)) {
1948 for (i
= 0; binhdr
[i
]; i
++) {
1949 int len
= strlen(binhdr
[i
]);
1950 if (len
< size
- hd
&&
1951 !memcmp(binhdr
[i
], buffer
+ hd
, len
)) {
1953 patch
->is_binary
= 1;
1960 /* Empty patch cannot be applied if it is a text patch
1961 * without metadata change. A binary patch appears
1964 if ((apply
|| check
) &&
1965 (!patch
->is_binary
&& !metadata_changes(patch
)))
1966 die(_("patch with only garbage at line %d"), linenr
);
1969 return offset
+ hdrsize
+ patchsize
;
1972 #define swap(a,b) myswap((a),(b),sizeof(a))
1974 #define myswap(a, b, size) do { \
1975 unsigned char mytmp[size]; \
1976 memcpy(mytmp, &a, size); \
1977 memcpy(&a, &b, size); \
1978 memcpy(&b, mytmp, size); \
1981 static void reverse_patches(struct patch
*p
)
1983 for (; p
; p
= p
->next
) {
1984 struct fragment
*frag
= p
->fragments
;
1986 swap(p
->new_name
, p
->old_name
);
1987 swap(p
->new_mode
, p
->old_mode
);
1988 swap(p
->is_new
, p
->is_delete
);
1989 swap(p
->lines_added
, p
->lines_deleted
);
1990 swap(p
->old_sha1_prefix
, p
->new_sha1_prefix
);
1992 for (; frag
; frag
= frag
->next
) {
1993 swap(frag
->newpos
, frag
->oldpos
);
1994 swap(frag
->newlines
, frag
->oldlines
);
1999 static const char pluses
[] =
2000 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2001 static const char minuses
[]=
2002 "----------------------------------------------------------------------";
2004 static void show_stats(struct patch
*patch
)
2006 struct strbuf qname
= STRBUF_INIT
;
2007 char *cp
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
2010 quote_c_style(cp
, &qname
, NULL
, 0);
2013 * "scale" the filename
2019 if (qname
.len
> max
) {
2020 cp
= strchr(qname
.buf
+ qname
.len
+ 3 - max
, '/');
2022 cp
= qname
.buf
+ qname
.len
+ 3 - max
;
2023 strbuf_splice(&qname
, 0, cp
- qname
.buf
, "...", 3);
2026 if (patch
->is_binary
) {
2027 printf(" %-*s | Bin\n", max
, qname
.buf
);
2028 strbuf_release(&qname
);
2032 printf(" %-*s |", max
, qname
.buf
);
2033 strbuf_release(&qname
);
2036 * scale the add/delete
2038 max
= max
+ max_change
> 70 ? 70 - max
: max_change
;
2039 add
= patch
->lines_added
;
2040 del
= patch
->lines_deleted
;
2042 if (max_change
> 0) {
2043 int total
= ((add
+ del
) * max
+ max_change
/ 2) / max_change
;
2044 add
= (add
* max
+ max_change
/ 2) / max_change
;
2047 printf("%5d %.*s%.*s\n", patch
->lines_added
+ patch
->lines_deleted
,
2048 add
, pluses
, del
, minuses
);
2051 static int read_old_data(struct stat
*st
, const char *path
, struct strbuf
*buf
)
2053 switch (st
->st_mode
& S_IFMT
) {
2055 if (strbuf_readlink(buf
, path
, st
->st_size
) < 0)
2056 return error(_("unable to read symlink %s"), path
);
2059 if (strbuf_read_file(buf
, path
, st
->st_size
) != st
->st_size
)
2060 return error(_("unable to open or read %s"), path
);
2061 convert_to_git(path
, buf
->buf
, buf
->len
, buf
, 0);
2069 * Update the preimage, and the common lines in postimage,
2070 * from buffer buf of length len. If postlen is 0 the postimage
2071 * is updated in place, otherwise it's updated on a new buffer
2075 static void update_pre_post_images(struct image
*preimage
,
2076 struct image
*postimage
,
2078 size_t len
, size_t postlen
)
2081 char *new, *old
, *fixed
;
2082 struct image fixed_preimage
;
2085 * Update the preimage with whitespace fixes. Note that we
2086 * are not losing preimage->buf -- apply_one_fragment() will
2089 prepare_image(&fixed_preimage
, buf
, len
, 1);
2090 assert(fixed_preimage
.nr
== preimage
->nr
);
2091 for (i
= 0; i
< preimage
->nr
; i
++)
2092 fixed_preimage
.line
[i
].flag
= preimage
->line
[i
].flag
;
2093 free(preimage
->line_allocated
);
2094 *preimage
= fixed_preimage
;
2097 * Adjust the common context lines in postimage. This can be
2098 * done in-place when we are just doing whitespace fixing,
2099 * which does not make the string grow, but needs a new buffer
2100 * when ignoring whitespace causes the update, since in this case
2101 * we could have e.g. tabs converted to multiple spaces.
2102 * We trust the caller to tell us if the update can be done
2103 * in place (postlen==0) or not.
2105 old
= postimage
->buf
;
2107 new = postimage
->buf
= xmalloc(postlen
);
2110 fixed
= preimage
->buf
;
2111 for (i
= ctx
= 0; i
< postimage
->nr
; i
++) {
2112 size_t len
= postimage
->line
[i
].len
;
2113 if (!(postimage
->line
[i
].flag
& LINE_COMMON
)) {
2114 /* an added line -- no counterparts in preimage */
2115 memmove(new, old
, len
);
2121 /* a common context -- skip it in the original postimage */
2124 /* and find the corresponding one in the fixed preimage */
2125 while (ctx
< preimage
->nr
&&
2126 !(preimage
->line
[ctx
].flag
& LINE_COMMON
)) {
2127 fixed
+= preimage
->line
[ctx
].len
;
2130 if (preimage
->nr
<= ctx
)
2133 /* and copy it in, while fixing the line length */
2134 len
= preimage
->line
[ctx
].len
;
2135 memcpy(new, fixed
, len
);
2138 postimage
->line
[i
].len
= len
;
2142 /* Fix the length of the whole thing */
2143 postimage
->len
= new - postimage
->buf
;
2146 static int match_fragment(struct image
*img
,
2147 struct image
*preimage
,
2148 struct image
*postimage
,
2152 int match_beginning
, int match_end
)
2155 char *fixed_buf
, *buf
, *orig
, *target
;
2156 struct strbuf fixed
;
2160 if (preimage
->nr
+ try_lno
<= img
->nr
) {
2162 * The hunk falls within the boundaries of img.
2164 preimage_limit
= preimage
->nr
;
2165 if (match_end
&& (preimage
->nr
+ try_lno
!= img
->nr
))
2167 } else if (ws_error_action
== correct_ws_error
&&
2168 (ws_rule
& WS_BLANK_AT_EOF
)) {
2170 * This hunk extends beyond the end of img, and we are
2171 * removing blank lines at the end of the file. This
2172 * many lines from the beginning of the preimage must
2173 * match with img, and the remainder of the preimage
2176 preimage_limit
= img
->nr
- try_lno
;
2179 * The hunk extends beyond the end of the img and
2180 * we are not removing blanks at the end, so we
2181 * should reject the hunk at this position.
2186 if (match_beginning
&& try_lno
)
2189 /* Quick hash check */
2190 for (i
= 0; i
< preimage_limit
; i
++)
2191 if ((img
->line
[try_lno
+ i
].flag
& LINE_PATCHED
) ||
2192 (preimage
->line
[i
].hash
!= img
->line
[try_lno
+ i
].hash
))
2195 if (preimage_limit
== preimage
->nr
) {
2197 * Do we have an exact match? If we were told to match
2198 * at the end, size must be exactly at try+fragsize,
2199 * otherwise try+fragsize must be still within the preimage,
2200 * and either case, the old piece should match the preimage
2204 ? (try + preimage
->len
== img
->len
)
2205 : (try + preimage
->len
<= img
->len
)) &&
2206 !memcmp(img
->buf
+ try, preimage
->buf
, preimage
->len
))
2210 * The preimage extends beyond the end of img, so
2211 * there cannot be an exact match.
2213 * There must be one non-blank context line that match
2214 * a line before the end of img.
2218 buf
= preimage
->buf
;
2220 for (i
= 0; i
< preimage_limit
; i
++)
2221 buf_end
+= preimage
->line
[i
].len
;
2223 for ( ; buf
< buf_end
; buf
++)
2231 * No exact match. If we are ignoring whitespace, run a line-by-line
2232 * fuzzy matching. We collect all the line length information because
2233 * we need it to adjust whitespace if we match.
2235 if (ws_ignore_action
== ignore_ws_change
) {
2238 size_t postlen
= postimage
->len
;
2242 for (i
= 0; i
< preimage_limit
; i
++) {
2243 size_t prelen
= preimage
->line
[i
].len
;
2244 size_t imglen
= img
->line
[try_lno
+i
].len
;
2246 if (!fuzzy_matchlines(img
->buf
+ try + imgoff
, imglen
,
2247 preimage
->buf
+ preoff
, prelen
))
2249 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2250 postlen
+= imglen
- prelen
;
2256 * Ok, the preimage matches with whitespace fuzz.
2258 * imgoff now holds the true length of the target that
2259 * matches the preimage before the end of the file.
2261 * Count the number of characters in the preimage that fall
2262 * beyond the end of the file and make sure that all of them
2263 * are whitespace characters. (This can only happen if
2264 * we are removing blank lines at the end of the file.)
2266 buf
= preimage_eof
= preimage
->buf
+ preoff
;
2267 for ( ; i
< preimage
->nr
; i
++)
2268 preoff
+= preimage
->line
[i
].len
;
2269 preimage_end
= preimage
->buf
+ preoff
;
2270 for ( ; buf
< preimage_end
; buf
++)
2275 * Update the preimage and the common postimage context
2276 * lines to use the same whitespace as the target.
2277 * If whitespace is missing in the target (i.e.
2278 * if the preimage extends beyond the end of the file),
2279 * use the whitespace from the preimage.
2281 extra_chars
= preimage_end
- preimage_eof
;
2282 strbuf_init(&fixed
, imgoff
+ extra_chars
);
2283 strbuf_add(&fixed
, img
->buf
+ try, imgoff
);
2284 strbuf_add(&fixed
, preimage_eof
, extra_chars
);
2285 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2286 update_pre_post_images(preimage
, postimage
,
2287 fixed_buf
, fixed_len
, postlen
);
2291 if (ws_error_action
!= correct_ws_error
)
2295 * The hunk does not apply byte-by-byte, but the hash says
2296 * it might with whitespace fuzz. We haven't been asked to
2297 * ignore whitespace, we were asked to correct whitespace
2298 * errors, so let's try matching after whitespace correction.
2300 * The preimage may extend beyond the end of the file,
2301 * but in this loop we will only handle the part of the
2302 * preimage that falls within the file.
2304 strbuf_init(&fixed
, preimage
->len
+ 1);
2305 orig
= preimage
->buf
;
2306 target
= img
->buf
+ try;
2307 for (i
= 0; i
< preimage_limit
; i
++) {
2308 size_t oldlen
= preimage
->line
[i
].len
;
2309 size_t tgtlen
= img
->line
[try_lno
+ i
].len
;
2310 size_t fixstart
= fixed
.len
;
2311 struct strbuf tgtfix
;
2314 /* Try fixing the line in the preimage */
2315 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2317 /* Try fixing the line in the target */
2318 strbuf_init(&tgtfix
, tgtlen
);
2319 ws_fix_copy(&tgtfix
, target
, tgtlen
, ws_rule
, NULL
);
2322 * If they match, either the preimage was based on
2323 * a version before our tree fixed whitespace breakage,
2324 * or we are lacking a whitespace-fix patch the tree
2325 * the preimage was based on already had (i.e. target
2326 * has whitespace breakage, the preimage doesn't).
2327 * In either case, we are fixing the whitespace breakages
2328 * so we might as well take the fix together with their
2331 match
= (tgtfix
.len
== fixed
.len
- fixstart
&&
2332 !memcmp(tgtfix
.buf
, fixed
.buf
+ fixstart
,
2333 fixed
.len
- fixstart
));
2335 strbuf_release(&tgtfix
);
2345 * Now handle the lines in the preimage that falls beyond the
2346 * end of the file (if any). They will only match if they are
2347 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2350 for ( ; i
< preimage
->nr
; i
++) {
2351 size_t fixstart
= fixed
.len
; /* start of the fixed preimage */
2352 size_t oldlen
= preimage
->line
[i
].len
;
2355 /* Try fixing the line in the preimage */
2356 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2358 for (j
= fixstart
; j
< fixed
.len
; j
++)
2359 if (!isspace(fixed
.buf
[j
]))
2366 * Yes, the preimage is based on an older version that still
2367 * has whitespace breakages unfixed, and fixing them makes the
2368 * hunk match. Update the context lines in the postimage.
2370 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2371 update_pre_post_images(preimage
, postimage
,
2372 fixed_buf
, fixed_len
, 0);
2376 strbuf_release(&fixed
);
2380 static int find_pos(struct image
*img
,
2381 struct image
*preimage
,
2382 struct image
*postimage
,
2385 int match_beginning
, int match_end
)
2388 unsigned long backwards
, forwards
, try;
2389 int backwards_lno
, forwards_lno
, try_lno
;
2392 * If match_beginning or match_end is specified, there is no
2393 * point starting from a wrong line that will never match and
2394 * wander around and wait for a match at the specified end.
2396 if (match_beginning
)
2399 line
= img
->nr
- preimage
->nr
;
2402 * Because the comparison is unsigned, the following test
2403 * will also take care of a negative line number that can
2404 * result when match_end and preimage is larger than the target.
2406 if ((size_t) line
> img
->nr
)
2410 for (i
= 0; i
< line
; i
++)
2411 try += img
->line
[i
].len
;
2414 * There's probably some smart way to do this, but I'll leave
2415 * that to the smart and beautiful people. I'm simple and stupid.
2418 backwards_lno
= line
;
2420 forwards_lno
= line
;
2423 for (i
= 0; ; i
++) {
2424 if (match_fragment(img
, preimage
, postimage
,
2425 try, try_lno
, ws_rule
,
2426 match_beginning
, match_end
))
2430 if (backwards_lno
== 0 && forwards_lno
== img
->nr
)
2434 if (backwards_lno
== 0) {
2439 backwards
-= img
->line
[backwards_lno
].len
;
2441 try_lno
= backwards_lno
;
2443 if (forwards_lno
== img
->nr
) {
2447 forwards
+= img
->line
[forwards_lno
].len
;
2450 try_lno
= forwards_lno
;
2457 static void remove_first_line(struct image
*img
)
2459 img
->buf
+= img
->line
[0].len
;
2460 img
->len
-= img
->line
[0].len
;
2465 static void remove_last_line(struct image
*img
)
2467 img
->len
-= img
->line
[--img
->nr
].len
;
2471 * The change from "preimage" and "postimage" has been found to
2472 * apply at applied_pos (counts in line numbers) in "img".
2473 * Update "img" to remove "preimage" and replace it with "postimage".
2475 static void update_image(struct image
*img
,
2477 struct image
*preimage
,
2478 struct image
*postimage
)
2481 * remove the copy of preimage at offset in img
2482 * and replace it with postimage
2485 size_t remove_count
, insert_count
, applied_at
= 0;
2490 * If we are removing blank lines at the end of img,
2491 * the preimage may extend beyond the end.
2492 * If that is the case, we must be careful only to
2493 * remove the part of the preimage that falls within
2494 * the boundaries of img. Initialize preimage_limit
2495 * to the number of lines in the preimage that falls
2496 * within the boundaries.
2498 preimage_limit
= preimage
->nr
;
2499 if (preimage_limit
> img
->nr
- applied_pos
)
2500 preimage_limit
= img
->nr
- applied_pos
;
2502 for (i
= 0; i
< applied_pos
; i
++)
2503 applied_at
+= img
->line
[i
].len
;
2506 for (i
= 0; i
< preimage_limit
; i
++)
2507 remove_count
+= img
->line
[applied_pos
+ i
].len
;
2508 insert_count
= postimage
->len
;
2510 /* Adjust the contents */
2511 result
= xmalloc(img
->len
+ insert_count
- remove_count
+ 1);
2512 memcpy(result
, img
->buf
, applied_at
);
2513 memcpy(result
+ applied_at
, postimage
->buf
, postimage
->len
);
2514 memcpy(result
+ applied_at
+ postimage
->len
,
2515 img
->buf
+ (applied_at
+ remove_count
),
2516 img
->len
- (applied_at
+ remove_count
));
2519 img
->len
+= insert_count
- remove_count
;
2520 result
[img
->len
] = '\0';
2522 /* Adjust the line table */
2523 nr
= img
->nr
+ postimage
->nr
- preimage_limit
;
2524 if (preimage_limit
< postimage
->nr
) {
2526 * NOTE: this knows that we never call remove_first_line()
2527 * on anything other than pre/post image.
2529 img
->line
= xrealloc(img
->line
, nr
* sizeof(*img
->line
));
2530 img
->line_allocated
= img
->line
;
2532 if (preimage_limit
!= postimage
->nr
)
2533 memmove(img
->line
+ applied_pos
+ postimage
->nr
,
2534 img
->line
+ applied_pos
+ preimage_limit
,
2535 (img
->nr
- (applied_pos
+ preimage_limit
)) *
2536 sizeof(*img
->line
));
2537 memcpy(img
->line
+ applied_pos
,
2539 postimage
->nr
* sizeof(*img
->line
));
2541 for (i
= 0; i
< postimage
->nr
; i
++)
2542 img
->line
[applied_pos
+ i
].flag
|= LINE_PATCHED
;
2547 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2548 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2549 * replace the part of "img" with "postimage" text.
2551 static int apply_one_fragment(struct image
*img
, struct fragment
*frag
,
2552 int inaccurate_eof
, unsigned ws_rule
,
2555 int match_beginning
, match_end
;
2556 const char *patch
= frag
->patch
;
2557 int size
= frag
->size
;
2558 char *old
, *oldlines
;
2559 struct strbuf newlines
;
2560 int new_blank_lines_at_end
= 0;
2561 int found_new_blank_lines_at_end
= 0;
2562 int hunk_linenr
= frag
->linenr
;
2563 unsigned long leading
, trailing
;
2564 int pos
, applied_pos
;
2565 struct image preimage
;
2566 struct image postimage
;
2568 memset(&preimage
, 0, sizeof(preimage
));
2569 memset(&postimage
, 0, sizeof(postimage
));
2570 oldlines
= xmalloc(size
);
2571 strbuf_init(&newlines
, size
);
2576 int len
= linelen(patch
, size
);
2578 int added_blank_line
= 0;
2579 int is_blank_context
= 0;
2586 * "plen" is how much of the line we should use for
2587 * the actual patch data. Normally we just remove the
2588 * first character on the line, but if the line is
2589 * followed by "\ No newline", then we also remove the
2590 * last one (which is the newline, of course).
2593 if (len
< size
&& patch
[len
] == '\\')
2596 if (apply_in_reverse
) {
2599 else if (first
== '+')
2605 /* Newer GNU diff, empty context line */
2607 /* ... followed by '\No newline'; nothing */
2610 strbuf_addch(&newlines
, '\n');
2611 add_line_info(&preimage
, "\n", 1, LINE_COMMON
);
2612 add_line_info(&postimage
, "\n", 1, LINE_COMMON
);
2613 is_blank_context
= 1;
2616 if (plen
&& (ws_rule
& WS_BLANK_AT_EOF
) &&
2617 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2618 is_blank_context
= 1;
2620 memcpy(old
, patch
+ 1, plen
);
2621 add_line_info(&preimage
, old
, plen
,
2622 (first
== ' ' ? LINE_COMMON
: 0));
2626 /* Fall-through for ' ' */
2628 /* --no-add does not add new lines */
2629 if (first
== '+' && no_add
)
2632 start
= newlines
.len
;
2634 !whitespace_error
||
2635 ws_error_action
!= correct_ws_error
) {
2636 strbuf_add(&newlines
, patch
+ 1, plen
);
2639 ws_fix_copy(&newlines
, patch
+ 1, plen
, ws_rule
, &applied_after_fixing_ws
);
2641 add_line_info(&postimage
, newlines
.buf
+ start
, newlines
.len
- start
,
2642 (first
== '+' ? 0 : LINE_COMMON
));
2644 (ws_rule
& WS_BLANK_AT_EOF
) &&
2645 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2646 added_blank_line
= 1;
2648 case '@': case '\\':
2649 /* Ignore it, we already handled it */
2652 if (apply_verbosely
)
2653 error(_("invalid start of line: '%c'"), first
);
2656 if (added_blank_line
) {
2657 if (!new_blank_lines_at_end
)
2658 found_new_blank_lines_at_end
= hunk_linenr
;
2659 new_blank_lines_at_end
++;
2661 else if (is_blank_context
)
2664 new_blank_lines_at_end
= 0;
2669 if (inaccurate_eof
&&
2670 old
> oldlines
&& old
[-1] == '\n' &&
2671 newlines
.len
> 0 && newlines
.buf
[newlines
.len
- 1] == '\n') {
2673 strbuf_setlen(&newlines
, newlines
.len
- 1);
2676 leading
= frag
->leading
;
2677 trailing
= frag
->trailing
;
2680 * A hunk to change lines at the beginning would begin with
2682 * but we need to be careful. -U0 that inserts before the second
2683 * line also has this pattern.
2685 * And a hunk to add to an empty file would begin with
2688 * In other words, a hunk that is (frag->oldpos <= 1) with or
2689 * without leading context must match at the beginning.
2691 match_beginning
= (!frag
->oldpos
||
2692 (frag
->oldpos
== 1 && !unidiff_zero
));
2695 * A hunk without trailing lines must match at the end.
2696 * However, we simply cannot tell if a hunk must match end
2697 * from the lack of trailing lines if the patch was generated
2698 * with unidiff without any context.
2700 match_end
= !unidiff_zero
&& !trailing
;
2702 pos
= frag
->newpos
? (frag
->newpos
- 1) : 0;
2703 preimage
.buf
= oldlines
;
2704 preimage
.len
= old
- oldlines
;
2705 postimage
.buf
= newlines
.buf
;
2706 postimage
.len
= newlines
.len
;
2707 preimage
.line
= preimage
.line_allocated
;
2708 postimage
.line
= postimage
.line_allocated
;
2712 applied_pos
= find_pos(img
, &preimage
, &postimage
, pos
,
2713 ws_rule
, match_beginning
, match_end
);
2715 if (applied_pos
>= 0)
2718 /* Am I at my context limits? */
2719 if ((leading
<= p_context
) && (trailing
<= p_context
))
2721 if (match_beginning
|| match_end
) {
2722 match_beginning
= match_end
= 0;
2727 * Reduce the number of context lines; reduce both
2728 * leading and trailing if they are equal otherwise
2729 * just reduce the larger context.
2731 if (leading
>= trailing
) {
2732 remove_first_line(&preimage
);
2733 remove_first_line(&postimage
);
2737 if (trailing
> leading
) {
2738 remove_last_line(&preimage
);
2739 remove_last_line(&postimage
);
2744 if (applied_pos
>= 0) {
2745 if (new_blank_lines_at_end
&&
2746 preimage
.nr
+ applied_pos
>= img
->nr
&&
2747 (ws_rule
& WS_BLANK_AT_EOF
) &&
2748 ws_error_action
!= nowarn_ws_error
) {
2749 record_ws_error(WS_BLANK_AT_EOF
, "+", 1,
2750 found_new_blank_lines_at_end
);
2751 if (ws_error_action
== correct_ws_error
) {
2752 while (new_blank_lines_at_end
--)
2753 remove_last_line(&postimage
);
2756 * We would want to prevent write_out_results()
2757 * from taking place in apply_patch() that follows
2758 * the callchain led us here, which is:
2759 * apply_patch->check_patch_list->check_patch->
2760 * apply_data->apply_fragments->apply_one_fragment
2762 if (ws_error_action
== die_on_ws_error
)
2766 if (apply_verbosely
&& applied_pos
!= pos
) {
2767 int offset
= applied_pos
- pos
;
2768 if (apply_in_reverse
)
2769 offset
= 0 - offset
;
2771 Q_("Hunk #%d succeeded at %d (offset %d line).",
2772 "Hunk #%d succeeded at %d (offset %d lines).",
2774 nth_fragment
, applied_pos
+ 1, offset
);
2778 * Warn if it was necessary to reduce the number
2781 if ((leading
!= frag
->leading
) ||
2782 (trailing
!= frag
->trailing
))
2783 fprintf_ln(stderr
, _("Context reduced to (%ld/%ld)"
2784 " to apply fragment at %d"),
2785 leading
, trailing
, applied_pos
+1);
2786 update_image(img
, applied_pos
, &preimage
, &postimage
);
2788 if (apply_verbosely
)
2789 error(_("while searching for:\n%.*s"),
2790 (int)(old
- oldlines
), oldlines
);
2794 strbuf_release(&newlines
);
2795 free(preimage
.line_allocated
);
2796 free(postimage
.line_allocated
);
2798 return (applied_pos
< 0);
2801 static int apply_binary_fragment(struct image
*img
, struct patch
*patch
)
2803 struct fragment
*fragment
= patch
->fragments
;
2808 return error(_("missing binary patch data for '%s'"),
2813 /* Binary patch is irreversible without the optional second hunk */
2814 if (apply_in_reverse
) {
2815 if (!fragment
->next
)
2816 return error("cannot reverse-apply a binary patch "
2817 "without the reverse hunk to '%s'",
2819 ? patch
->new_name
: patch
->old_name
);
2820 fragment
= fragment
->next
;
2822 switch (fragment
->binary_patch_method
) {
2823 case BINARY_DELTA_DEFLATED
:
2824 dst
= patch_delta(img
->buf
, img
->len
, fragment
->patch
,
2825 fragment
->size
, &len
);
2832 case BINARY_LITERAL_DEFLATED
:
2834 img
->len
= fragment
->size
;
2835 img
->buf
= xmalloc(img
->len
+1);
2836 memcpy(img
->buf
, fragment
->patch
, img
->len
);
2837 img
->buf
[img
->len
] = '\0';
2844 * Replace "img" with the result of applying the binary patch.
2845 * The binary patch data itself in patch->fragment is still kept
2846 * but the preimage prepared by the caller in "img" is freed here
2847 * or in the helper function apply_binary_fragment() this calls.
2849 static int apply_binary(struct image
*img
, struct patch
*patch
)
2851 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
2852 unsigned char sha1
[20];
2855 * For safety, we require patch index line to contain
2856 * full 40-byte textual SHA1 for old and new, at least for now.
2858 if (strlen(patch
->old_sha1_prefix
) != 40 ||
2859 strlen(patch
->new_sha1_prefix
) != 40 ||
2860 get_sha1_hex(patch
->old_sha1_prefix
, sha1
) ||
2861 get_sha1_hex(patch
->new_sha1_prefix
, sha1
))
2862 return error("cannot apply binary patch to '%s' "
2863 "without full index line", name
);
2865 if (patch
->old_name
) {
2867 * See if the old one matches what the patch
2870 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
2871 if (strcmp(sha1_to_hex(sha1
), patch
->old_sha1_prefix
))
2872 return error("the patch applies to '%s' (%s), "
2873 "which does not match the "
2874 "current contents.",
2875 name
, sha1_to_hex(sha1
));
2878 /* Otherwise, the old one must be empty. */
2880 return error("the patch applies to an empty "
2881 "'%s' but it is not empty", name
);
2884 get_sha1_hex(patch
->new_sha1_prefix
, sha1
);
2885 if (is_null_sha1(sha1
)) {
2887 return 0; /* deletion patch */
2890 if (has_sha1_file(sha1
)) {
2891 /* We already have the postimage */
2892 enum object_type type
;
2896 result
= read_sha1_file(sha1
, &type
, &size
);
2898 return error("the necessary postimage %s for "
2899 "'%s' cannot be read",
2900 patch
->new_sha1_prefix
, name
);
2906 * We have verified buf matches the preimage;
2907 * apply the patch data to it, which is stored
2908 * in the patch->fragments->{patch,size}.
2910 if (apply_binary_fragment(img
, patch
))
2911 return error(_("binary patch does not apply to '%s'"),
2914 /* verify that the result matches */
2915 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
2916 if (strcmp(sha1_to_hex(sha1
), patch
->new_sha1_prefix
))
2917 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
2918 name
, patch
->new_sha1_prefix
, sha1_to_hex(sha1
));
2924 static int apply_fragments(struct image
*img
, struct patch
*patch
)
2926 struct fragment
*frag
= patch
->fragments
;
2927 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
2928 unsigned ws_rule
= patch
->ws_rule
;
2929 unsigned inaccurate_eof
= patch
->inaccurate_eof
;
2932 if (patch
->is_binary
)
2933 return apply_binary(img
, patch
);
2937 if (apply_one_fragment(img
, frag
, inaccurate_eof
, ws_rule
, nth
)) {
2938 error(_("patch failed: %s:%ld"), name
, frag
->oldpos
);
2939 if (!apply_with_reject
)
2948 static int read_blob_object(struct strbuf
*buf
, const unsigned char *sha1
, unsigned mode
)
2950 if (S_ISGITLINK(mode
)) {
2951 strbuf_grow(buf
, 100);
2952 strbuf_addf(buf
, "Subproject commit %s\n", sha1_to_hex(sha1
));
2954 enum object_type type
;
2958 result
= read_sha1_file(sha1
, &type
, &sz
);
2961 /* XXX read_sha1_file NUL-terminates */
2962 strbuf_attach(buf
, result
, sz
, sz
+ 1);
2967 static int read_file_or_gitlink(struct cache_entry
*ce
, struct strbuf
*buf
)
2971 return read_blob_object(buf
, ce
->sha1
, ce
->ce_mode
);
2974 static struct patch
*in_fn_table(const char *name
)
2976 struct string_list_item
*item
;
2981 item
= string_list_lookup(&fn_table
, name
);
2983 return (struct patch
*)item
->util
;
2989 * item->util in the filename table records the status of the path.
2990 * Usually it points at a patch (whose result records the contents
2991 * of it after applying it), but it could be PATH_WAS_DELETED for a
2992 * path that a previously applied patch has already removed, or
2993 * PATH_TO_BE_DELETED for a path that a later patch would remove.
2995 * The latter is needed to deal with a case where two paths A and B
2996 * are swapped by first renaming A to B and then renaming B to A;
2997 * moving A to B should not be prevented due to presense of B as we
2998 * will remove it in a later patch.
3000 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3001 #define PATH_WAS_DELETED ((struct patch *) -1)
3003 static int to_be_deleted(struct patch
*patch
)
3005 return patch
== PATH_TO_BE_DELETED
;
3008 static int was_deleted(struct patch
*patch
)
3010 return patch
== PATH_WAS_DELETED
;
3013 static void add_to_fn_table(struct patch
*patch
)
3015 struct string_list_item
*item
;
3018 * Always add new_name unless patch is a deletion
3019 * This should cover the cases for normal diffs,
3020 * file creations and copies
3022 if (patch
->new_name
!= NULL
) {
3023 item
= string_list_insert(&fn_table
, patch
->new_name
);
3028 * store a failure on rename/deletion cases because
3029 * later chunks shouldn't patch old names
3031 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3032 item
= string_list_insert(&fn_table
, patch
->old_name
);
3033 item
->util
= PATH_WAS_DELETED
;
3037 static void prepare_fn_table(struct patch
*patch
)
3040 * store information about incoming file deletion
3043 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3044 struct string_list_item
*item
;
3045 item
= string_list_insert(&fn_table
, patch
->old_name
);
3046 item
->util
= PATH_TO_BE_DELETED
;
3048 patch
= patch
->next
;
3052 static int checkout_target(struct cache_entry
*ce
, struct stat
*st
)
3054 struct checkout costate
;
3056 memset(&costate
, 0, sizeof(costate
));
3057 costate
.base_dir
= "";
3058 costate
.refresh_cache
= 1;
3059 if (checkout_entry(ce
, &costate
, NULL
) || lstat(ce
->name
, st
))
3060 return error(_("cannot checkout %s"), ce
->name
);
3064 static struct patch
*previous_patch(struct patch
*patch
, int *gone
)
3066 struct patch
*previous
;
3069 if (patch
->is_copy
|| patch
->is_rename
)
3070 return NULL
; /* "git" patches do not depend on the order */
3072 previous
= in_fn_table(patch
->old_name
);
3076 if (to_be_deleted(previous
))
3077 return NULL
; /* the deletion hasn't happened yet */
3079 if (was_deleted(previous
))
3085 static int verify_index_match(struct cache_entry
*ce
, struct stat
*st
)
3087 if (S_ISGITLINK(ce
->ce_mode
)) {
3088 if (!S_ISDIR(st
->st_mode
))
3092 return ce_match_stat(ce
, st
, CE_MATCH_IGNORE_VALID
|CE_MATCH_IGNORE_SKIP_WORKTREE
);
3095 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3097 static int load_patch_target(struct strbuf
*buf
,
3098 struct cache_entry
*ce
,
3101 unsigned expected_mode
)
3104 if (read_file_or_gitlink(ce
, buf
))
3105 return error(_("read of %s failed"), name
);
3107 if (S_ISGITLINK(expected_mode
)) {
3109 return read_file_or_gitlink(ce
, buf
);
3111 return SUBMODULE_PATCH_WITHOUT_INDEX
;
3113 if (read_old_data(st
, name
, buf
))
3114 return error(_("read of %s failed"), name
);
3121 * We are about to apply "patch"; populate the "image" with the
3122 * current version we have, from the working tree or from the index,
3123 * depending on the situation e.g. --cached/--index. If we are
3124 * applying a non-git patch that incrementally updates the tree,
3125 * we read from the result of a previous diff.
3127 static int load_preimage(struct image
*image
,
3128 struct patch
*patch
, struct stat
*st
, struct cache_entry
*ce
)
3130 struct strbuf buf
= STRBUF_INIT
;
3133 struct patch
*previous
;
3136 previous
= previous_patch(patch
, &status
);
3138 return error(_("path %s has been renamed/deleted"),
3141 /* We have a patched copy in memory; use that. */
3142 strbuf_add(&buf
, previous
->result
, previous
->resultsize
);
3144 status
= load_patch_target(&buf
, ce
, st
,
3145 patch
->old_name
, patch
->old_mode
);
3148 else if (status
== SUBMODULE_PATCH_WITHOUT_INDEX
) {
3150 * There is no way to apply subproject
3151 * patch without looking at the index.
3152 * NEEDSWORK: shouldn't this be flagged
3155 free_fragment_list(patch
->fragments
);
3156 patch
->fragments
= NULL
;
3157 } else if (status
) {
3158 return error(_("read of %s failed"), patch
->old_name
);
3162 img
= strbuf_detach(&buf
, &len
);
3163 prepare_image(image
, img
, len
, !patch
->is_binary
);
3167 static int three_way_merge(struct image
*image
,
3169 const unsigned char *base
,
3170 const unsigned char *ours
,
3171 const unsigned char *theirs
)
3173 mmfile_t base_file
, our_file
, their_file
;
3174 mmbuffer_t result
= { NULL
};
3177 read_mmblob(&base_file
, base
);
3178 read_mmblob(&our_file
, ours
);
3179 read_mmblob(&their_file
, theirs
);
3180 status
= ll_merge(&result
, path
,
3183 &their_file
, "theirs", NULL
);
3184 free(base_file
.ptr
);
3186 free(their_file
.ptr
);
3187 if (status
< 0 || !result
.ptr
) {
3192 image
->buf
= result
.ptr
;
3193 image
->len
= result
.size
;
3199 * When directly falling back to add/add three-way merge, we read from
3200 * the current contents of the new_name. In no cases other than that
3201 * this function will be called.
3203 static int load_current(struct image
*image
, struct patch
*patch
)
3205 struct strbuf buf
= STRBUF_INIT
;
3210 struct cache_entry
*ce
;
3211 char *name
= patch
->new_name
;
3212 unsigned mode
= patch
->new_mode
;
3215 die("BUG: patch to %s is not a creation", patch
->old_name
);
3217 pos
= cache_name_pos(name
, strlen(name
));
3219 return error(_("%s: does not exist in index"), name
);
3220 ce
= active_cache
[pos
];
3221 if (lstat(name
, &st
)) {
3222 if (errno
!= ENOENT
)
3223 return error(_("%s: %s"), name
, strerror(errno
));
3224 if (checkout_target(ce
, &st
))
3227 if (verify_index_match(ce
, &st
))
3228 return error(_("%s: does not match index"), name
);
3230 status
= load_patch_target(&buf
, ce
, &st
, name
, mode
);
3235 img
= strbuf_detach(&buf
, &len
);
3236 prepare_image(image
, img
, len
, !patch
->is_binary
);
3240 static int try_threeway(struct image
*image
, struct patch
*patch
,
3241 struct stat
*st
, struct cache_entry
*ce
)
3243 unsigned char pre_sha1
[20], post_sha1
[20], our_sha1
[20];
3244 struct strbuf buf
= STRBUF_INIT
;
3248 struct image tmp_image
;
3250 /* No point falling back to 3-way merge in these cases */
3251 if (patch
->is_delete
||
3252 S_ISGITLINK(patch
->old_mode
) || S_ISGITLINK(patch
->new_mode
))
3255 /* Preimage the patch was prepared for */
3257 write_sha1_file("", 0, blob_type
, pre_sha1
);
3258 else if (get_sha1(patch
->old_sha1_prefix
, pre_sha1
) ||
3259 read_blob_object(&buf
, pre_sha1
, patch
->old_mode
))
3260 return error("repository lacks the necessary blob to fall back on 3-way merge.");
3262 fprintf(stderr
, "Falling back to three-way merge...\n");
3264 img
= strbuf_detach(&buf
, &len
);
3265 prepare_image(&tmp_image
, img
, len
, 1);
3266 /* Apply the patch to get the post image */
3267 if (apply_fragments(&tmp_image
, patch
) < 0) {
3268 clear_image(&tmp_image
);
3271 /* post_sha1[] is theirs */
3272 write_sha1_file(tmp_image
.buf
, tmp_image
.len
, blob_type
, post_sha1
);
3273 clear_image(&tmp_image
);
3275 /* our_sha1[] is ours */
3276 if (patch
->is_new
) {
3277 if (load_current(&tmp_image
, patch
))
3278 return error("cannot read the current contents of '%s'",
3281 if (load_preimage(&tmp_image
, patch
, st
, ce
))
3282 return error("cannot read the current contents of '%s'",
3285 write_sha1_file(tmp_image
.buf
, tmp_image
.len
, blob_type
, our_sha1
);
3286 clear_image(&tmp_image
);
3288 /* in-core three-way merge between post and our using pre as base */
3289 status
= three_way_merge(image
, patch
->new_name
,
3290 pre_sha1
, our_sha1
, post_sha1
);
3292 fprintf(stderr
, "Failed to fall back on three-way merge...\n");
3297 patch
->conflicted_threeway
= 1;
3299 hashclr(patch
->threeway_stage
[0]);
3301 hashcpy(patch
->threeway_stage
[0], pre_sha1
);
3302 hashcpy(patch
->threeway_stage
[1], our_sha1
);
3303 hashcpy(patch
->threeway_stage
[2], post_sha1
);
3304 fprintf(stderr
, "Applied patch to '%s' with conflicts.\n", patch
->new_name
);
3306 fprintf(stderr
, "Applied patch to '%s' cleanly.\n", patch
->new_name
);
3311 static int apply_data(struct patch
*patch
, struct stat
*st
, struct cache_entry
*ce
)
3315 if (load_preimage(&image
, patch
, st
, ce
) < 0)
3318 if (patch
->direct_to_threeway
||
3319 apply_fragments(&image
, patch
) < 0) {
3320 /* Note: with --reject, apply_fragments() returns 0 */
3321 if (!threeway
|| try_threeway(&image
, patch
, st
, ce
) < 0)
3324 patch
->result
= image
.buf
;
3325 patch
->resultsize
= image
.len
;
3326 add_to_fn_table(patch
);
3327 free(image
.line_allocated
);
3329 if (0 < patch
->is_delete
&& patch
->resultsize
)
3330 return error(_("removal patch leaves file contents"));
3336 * If "patch" that we are looking at modifies or deletes what we have,
3337 * we would want it not to lose any local modification we have, either
3338 * in the working tree or in the index.
3340 * This also decides if a non-git patch is a creation patch or a
3341 * modification to an existing empty file. We do not check the state
3342 * of the current tree for a creation patch in this function; the caller
3343 * check_patch() separately makes sure (and errors out otherwise) that
3344 * the path the patch creates does not exist in the current tree.
3346 static int check_preimage(struct patch
*patch
, struct cache_entry
**ce
, struct stat
*st
)
3348 const char *old_name
= patch
->old_name
;
3349 struct patch
*previous
= NULL
;
3350 int stat_ret
= 0, status
;
3351 unsigned st_mode
= 0;
3356 assert(patch
->is_new
<= 0);
3357 previous
= previous_patch(patch
, &status
);
3360 return error(_("path %s has been renamed/deleted"), old_name
);
3362 st_mode
= previous
->new_mode
;
3363 } else if (!cached
) {
3364 stat_ret
= lstat(old_name
, st
);
3365 if (stat_ret
&& errno
!= ENOENT
)
3366 return error(_("%s: %s"), old_name
, strerror(errno
));
3369 if (check_index
&& !previous
) {
3370 int pos
= cache_name_pos(old_name
, strlen(old_name
));
3372 if (patch
->is_new
< 0)
3374 return error(_("%s: does not exist in index"), old_name
);
3376 *ce
= active_cache
[pos
];
3378 if (checkout_target(*ce
, st
))
3381 if (!cached
&& verify_index_match(*ce
, st
))
3382 return error(_("%s: does not match index"), old_name
);
3384 st_mode
= (*ce
)->ce_mode
;
3385 } else if (stat_ret
< 0) {
3386 if (patch
->is_new
< 0)
3388 return error(_("%s: %s"), old_name
, strerror(errno
));
3391 if (!cached
&& !previous
)
3392 st_mode
= ce_mode_from_stat(*ce
, st
->st_mode
);
3394 if (patch
->is_new
< 0)
3396 if (!patch
->old_mode
)
3397 patch
->old_mode
= st_mode
;
3398 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
3399 return error(_("%s: wrong type"), old_name
);
3400 if (st_mode
!= patch
->old_mode
)
3401 warning(_("%s has type %o, expected %o"),
3402 old_name
, st_mode
, patch
->old_mode
);
3403 if (!patch
->new_mode
&& !patch
->is_delete
)
3404 patch
->new_mode
= st_mode
;
3409 patch
->is_delete
= 0;
3410 free(patch
->old_name
);
3411 patch
->old_name
= NULL
;
3416 #define EXISTS_IN_INDEX 1
3417 #define EXISTS_IN_WORKTREE 2
3419 static int check_to_create(const char *new_name
, int ok_if_exists
)
3424 cache_name_pos(new_name
, strlen(new_name
)) >= 0 &&
3426 return EXISTS_IN_INDEX
;
3430 if (!lstat(new_name
, &nst
)) {
3431 if (S_ISDIR(nst
.st_mode
) || ok_if_exists
)
3434 * A leading component of new_name might be a symlink
3435 * that is going to be removed with this patch, but
3436 * still pointing at somewhere that has the path.
3437 * In such a case, path "new_name" does not exist as
3438 * far as git is concerned.
3440 if (has_symlink_leading_path(new_name
, strlen(new_name
)))
3443 return EXISTS_IN_WORKTREE
;
3444 } else if ((errno
!= ENOENT
) && (errno
!= ENOTDIR
)) {
3445 return error("%s: %s", new_name
, strerror(errno
));
3451 * Check and apply the patch in-core; leave the result in patch->result
3452 * for the caller to write it out to the final destination.
3454 static int check_patch(struct patch
*patch
)
3457 const char *old_name
= patch
->old_name
;
3458 const char *new_name
= patch
->new_name
;
3459 const char *name
= old_name
? old_name
: new_name
;
3460 struct cache_entry
*ce
= NULL
;
3461 struct patch
*tpatch
;
3465 patch
->rejected
= 1; /* we will drop this after we succeed */
3467 status
= check_preimage(patch
, &ce
, &st
);
3470 old_name
= patch
->old_name
;
3473 * A type-change diff is always split into a patch to delete
3474 * old, immediately followed by a patch to create new (see
3475 * diff.c::run_diff()); in such a case it is Ok that the entry
3476 * to be deleted by the previous patch is still in the working
3477 * tree and in the index.
3479 * A patch to swap-rename between A and B would first rename A
3480 * to B and then rename B to A. While applying the first one,
3481 * the presense of B should not stop A from getting renamed to
3482 * B; ask to_be_deleted() about the later rename. Removal of
3483 * B and rename from A to B is handled the same way by asking
3486 if ((tpatch
= in_fn_table(new_name
)) &&
3487 (was_deleted(tpatch
) || to_be_deleted(tpatch
)))
3493 ((0 < patch
->is_new
) | (0 < patch
->is_rename
) | patch
->is_copy
)) {
3494 int err
= check_to_create(new_name
, ok_if_exists
);
3496 if (err
&& threeway
) {
3497 patch
->direct_to_threeway
= 1;
3498 } else switch (err
) {
3501 case EXISTS_IN_INDEX
:
3502 return error(_("%s: already exists in index"), new_name
);
3504 case EXISTS_IN_WORKTREE
:
3505 return error(_("%s: already exists in working directory"),
3511 if (!patch
->new_mode
) {
3512 if (0 < patch
->is_new
)
3513 patch
->new_mode
= S_IFREG
| 0644;
3515 patch
->new_mode
= patch
->old_mode
;
3519 if (new_name
&& old_name
) {
3520 int same
= !strcmp(old_name
, new_name
);
3521 if (!patch
->new_mode
)
3522 patch
->new_mode
= patch
->old_mode
;
3523 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
) {
3525 return error(_("new mode (%o) of %s does not "
3526 "match old mode (%o)"),
3527 patch
->new_mode
, new_name
,
3530 return error(_("new mode (%o) of %s does not "
3531 "match old mode (%o) of %s"),
3532 patch
->new_mode
, new_name
,
3533 patch
->old_mode
, old_name
);
3537 if (apply_data(patch
, &st
, ce
) < 0)
3538 return error(_("%s: patch does not apply"), name
);
3539 patch
->rejected
= 0;
3543 static int check_patch_list(struct patch
*patch
)
3547 prepare_fn_table(patch
);
3549 if (apply_verbosely
)
3550 say_patch_name(stderr
,
3551 _("Checking patch %s..."), patch
);
3552 err
|= check_patch(patch
);
3553 patch
= patch
->next
;
3558 /* This function tries to read the sha1 from the current index */
3559 static int get_current_sha1(const char *path
, unsigned char *sha1
)
3563 if (read_cache() < 0)
3565 pos
= cache_name_pos(path
, strlen(path
));
3568 hashcpy(sha1
, active_cache
[pos
]->sha1
);
3572 /* Build an index that contains the just the files needed for a 3way merge */
3573 static void build_fake_ancestor(struct patch
*list
, const char *filename
)
3575 struct patch
*patch
;
3576 struct index_state result
= { NULL
};
3579 /* Once we start supporting the reverse patch, it may be
3580 * worth showing the new sha1 prefix, but until then...
3582 for (patch
= list
; patch
; patch
= patch
->next
) {
3583 const unsigned char *sha1_ptr
;
3584 unsigned char sha1
[20];
3585 struct cache_entry
*ce
;
3588 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3589 if (0 < patch
->is_new
)
3591 else if (get_sha1_blob(patch
->old_sha1_prefix
, sha1
))
3592 /* git diff has no index line for mode/type changes */
3593 if (!patch
->lines_added
&& !patch
->lines_deleted
) {
3594 if (get_current_sha1(patch
->old_name
, sha1
))
3595 die("mode change for %s, which is not "
3596 "in current HEAD", name
);
3599 die("sha1 information is lacking or useless "
3604 ce
= make_cache_entry(patch
->old_mode
, sha1_ptr
, name
, 0, 0);
3606 die(_("make_cache_entry failed for path '%s'"), name
);
3607 if (add_index_entry(&result
, ce
, ADD_CACHE_OK_TO_ADD
))
3608 die ("Could not add %s to temporary index", name
);
3611 fd
= open(filename
, O_WRONLY
| O_CREAT
, 0666);
3612 if (fd
< 0 || write_index(&result
, fd
) || close(fd
))
3613 die ("Could not write temporary index to %s", filename
);
3615 discard_index(&result
);
3618 static void stat_patch_list(struct patch
*patch
)
3620 int files
, adds
, dels
;
3622 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
3624 adds
+= patch
->lines_added
;
3625 dels
+= patch
->lines_deleted
;
3629 print_stat_summary(stdout
, files
, adds
, dels
);
3632 static void numstat_patch_list(struct patch
*patch
)
3634 for ( ; patch
; patch
= patch
->next
) {
3636 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
3637 if (patch
->is_binary
)
3640 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
3641 write_name_quoted(name
, stdout
, line_termination
);
3645 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
3648 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
3650 printf(" %s %s\n", newdelete
, name
);
3653 static void show_mode_change(struct patch
*p
, int show_name
)
3655 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
3657 printf(" mode change %06o => %06o %s\n",
3658 p
->old_mode
, p
->new_mode
, p
->new_name
);
3660 printf(" mode change %06o => %06o\n",
3661 p
->old_mode
, p
->new_mode
);
3665 static void show_rename_copy(struct patch
*p
)
3667 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
3668 const char *old
, *new;
3670 /* Find common prefix */
3674 const char *slash_old
, *slash_new
;
3675 slash_old
= strchr(old
, '/');
3676 slash_new
= strchr(new, '/');
3679 slash_old
- old
!= slash_new
- new ||
3680 memcmp(old
, new, slash_new
- new))
3682 old
= slash_old
+ 1;
3683 new = slash_new
+ 1;
3685 /* p->old_name thru old is the common prefix, and old and new
3686 * through the end of names are renames
3688 if (old
!= p
->old_name
)
3689 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
3690 (int)(old
- p
->old_name
), p
->old_name
,
3691 old
, new, p
->score
);
3693 printf(" %s %s => %s (%d%%)\n", renamecopy
,
3694 p
->old_name
, p
->new_name
, p
->score
);
3695 show_mode_change(p
, 0);
3698 static void summary_patch_list(struct patch
*patch
)
3702 for (p
= patch
; p
; p
= p
->next
) {
3704 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
3705 else if (p
->is_delete
)
3706 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
3708 if (p
->is_rename
|| p
->is_copy
)
3709 show_rename_copy(p
);
3712 printf(" rewrite %s (%d%%)\n",
3713 p
->new_name
, p
->score
);
3714 show_mode_change(p
, 0);
3717 show_mode_change(p
, 1);
3723 static void patch_stats(struct patch
*patch
)
3725 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
3727 if (lines
> max_change
)
3729 if (patch
->old_name
) {
3730 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
3732 len
= strlen(patch
->old_name
);
3736 if (patch
->new_name
) {
3737 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
3739 len
= strlen(patch
->new_name
);
3745 static void remove_file(struct patch
*patch
, int rmdir_empty
)
3748 if (remove_file_from_cache(patch
->old_name
) < 0)
3749 die(_("unable to remove %s from index"), patch
->old_name
);
3752 if (!remove_or_warn(patch
->old_mode
, patch
->old_name
) && rmdir_empty
) {
3753 remove_path(patch
->old_name
);
3758 static void add_index_file(const char *path
, unsigned mode
, void *buf
, unsigned long size
)
3761 struct cache_entry
*ce
;
3762 int namelen
= strlen(path
);
3763 unsigned ce_size
= cache_entry_size(namelen
);
3768 ce
= xcalloc(1, ce_size
);
3769 memcpy(ce
->name
, path
, namelen
);
3770 ce
->ce_mode
= create_ce_mode(mode
);
3771 ce
->ce_flags
= create_ce_flags(0);
3772 ce
->ce_namelen
= namelen
;
3773 if (S_ISGITLINK(mode
)) {
3774 const char *s
= buf
;
3776 if (get_sha1_hex(s
+ strlen("Subproject commit "), ce
->sha1
))
3777 die(_("corrupt patch for subproject %s"), path
);
3780 if (lstat(path
, &st
) < 0)
3781 die_errno(_("unable to stat newly created file '%s'"),
3783 fill_stat_cache_info(ce
, &st
);
3785 if (write_sha1_file(buf
, size
, blob_type
, ce
->sha1
) < 0)
3786 die(_("unable to create backing store for newly created file %s"), path
);
3788 if (add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
) < 0)
3789 die(_("unable to add cache entry for %s"), path
);
3792 static int try_create_file(const char *path
, unsigned int mode
, const char *buf
, unsigned long size
)
3795 struct strbuf nbuf
= STRBUF_INIT
;
3797 if (S_ISGITLINK(mode
)) {
3799 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
))
3801 return mkdir(path
, 0777);
3804 if (has_symlinks
&& S_ISLNK(mode
))
3805 /* Although buf:size is counted string, it also is NUL
3808 return symlink(buf
, path
);
3810 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
3814 if (convert_to_working_tree(path
, buf
, size
, &nbuf
)) {
3818 write_or_die(fd
, buf
, size
);
3819 strbuf_release(&nbuf
);
3822 die_errno(_("closing file '%s'"), path
);
3827 * We optimistically assume that the directories exist,
3828 * which is true 99% of the time anyway. If they don't,
3829 * we create them and try again.
3831 static void create_one_file(char *path
, unsigned mode
, const char *buf
, unsigned long size
)
3835 if (!try_create_file(path
, mode
, buf
, size
))
3838 if (errno
== ENOENT
) {
3839 if (safe_create_leading_directories(path
))
3841 if (!try_create_file(path
, mode
, buf
, size
))
3845 if (errno
== EEXIST
|| errno
== EACCES
) {
3846 /* We may be trying to create a file where a directory
3850 if (!lstat(path
, &st
) && (!S_ISDIR(st
.st_mode
) || !rmdir(path
)))
3854 if (errno
== EEXIST
) {
3855 unsigned int nr
= getpid();
3858 char newpath
[PATH_MAX
];
3859 mksnpath(newpath
, sizeof(newpath
), "%s~%u", path
, nr
);
3860 if (!try_create_file(newpath
, mode
, buf
, size
)) {
3861 if (!rename(newpath
, path
))
3863 unlink_or_warn(newpath
);
3866 if (errno
!= EEXIST
)
3871 die_errno(_("unable to write file '%s' mode %o"), path
, mode
);
3874 static void add_conflicted_stages_file(struct patch
*patch
)
3877 unsigned ce_size
, mode
;
3878 struct cache_entry
*ce
;
3882 namelen
= strlen(patch
->new_name
);
3883 ce_size
= cache_entry_size(namelen
);
3884 mode
= patch
->new_mode
? patch
->new_mode
: (S_IFREG
| 0644);
3886 remove_file_from_cache(patch
->new_name
);
3887 for (stage
= 1; stage
< 4; stage
++) {
3888 if (is_null_sha1(patch
->threeway_stage
[stage
- 1]))
3890 ce
= xcalloc(1, ce_size
);
3891 memcpy(ce
->name
, patch
->new_name
, namelen
);
3892 ce
->ce_mode
= create_ce_mode(mode
);
3893 ce
->ce_flags
= create_ce_flags(stage
);
3894 ce
->ce_namelen
= namelen
;
3895 hashcpy(ce
->sha1
, patch
->threeway_stage
[stage
- 1]);
3896 if (add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
) < 0)
3897 die(_("unable to add cache entry for %s"), patch
->new_name
);
3901 static void create_file(struct patch
*patch
)
3903 char *path
= patch
->new_name
;
3904 unsigned mode
= patch
->new_mode
;
3905 unsigned long size
= patch
->resultsize
;
3906 char *buf
= patch
->result
;
3909 mode
= S_IFREG
| 0644;
3910 create_one_file(path
, mode
, buf
, size
);
3912 if (patch
->conflicted_threeway
)
3913 add_conflicted_stages_file(patch
);
3915 add_index_file(path
, mode
, buf
, size
);
3918 /* phase zero is to remove, phase one is to create */
3919 static void write_out_one_result(struct patch
*patch
, int phase
)
3921 if (patch
->is_delete
> 0) {
3923 remove_file(patch
, 1);
3926 if (patch
->is_new
> 0 || patch
->is_copy
) {
3932 * Rename or modification boils down to the same
3933 * thing: remove the old, write the new
3936 remove_file(patch
, patch
->is_rename
);
3941 static int write_out_one_reject(struct patch
*patch
)
3944 char namebuf
[PATH_MAX
];
3945 struct fragment
*frag
;
3947 struct strbuf sb
= STRBUF_INIT
;
3949 for (cnt
= 0, frag
= patch
->fragments
; frag
; frag
= frag
->next
) {
3950 if (!frag
->rejected
)
3956 if (apply_verbosely
)
3957 say_patch_name(stderr
,
3958 _("Applied patch %s cleanly."), patch
);
3962 /* This should not happen, because a removal patch that leaves
3963 * contents are marked "rejected" at the patch level.
3965 if (!patch
->new_name
)
3966 die(_("internal error"));
3968 /* Say this even without --verbose */
3969 strbuf_addf(&sb
, Q_("Applying patch %%s with %d reject...",
3970 "Applying patch %%s with %d rejects...",
3973 say_patch_name(stderr
, sb
.buf
, patch
);
3974 strbuf_release(&sb
);
3976 cnt
= strlen(patch
->new_name
);
3977 if (ARRAY_SIZE(namebuf
) <= cnt
+ 5) {
3978 cnt
= ARRAY_SIZE(namebuf
) - 5;
3979 warning(_("truncating .rej filename to %.*s.rej"),
3980 cnt
- 1, patch
->new_name
);
3982 memcpy(namebuf
, patch
->new_name
, cnt
);
3983 memcpy(namebuf
+ cnt
, ".rej", 5);
3985 rej
= fopen(namebuf
, "w");
3987 return error(_("cannot open %s: %s"), namebuf
, strerror(errno
));
3989 /* Normal git tools never deal with .rej, so do not pretend
3990 * this is a git patch by saying --git nor give extended
3991 * headers. While at it, maybe please "kompare" that wants
3992 * the trailing TAB and some garbage at the end of line ;-).
3994 fprintf(rej
, "diff a/%s b/%s\t(rejected hunks)\n",
3995 patch
->new_name
, patch
->new_name
);
3996 for (cnt
= 1, frag
= patch
->fragments
;
3998 cnt
++, frag
= frag
->next
) {
3999 if (!frag
->rejected
) {
4000 fprintf_ln(stderr
, _("Hunk #%d applied cleanly."), cnt
);
4003 fprintf_ln(stderr
, _("Rejected hunk #%d."), cnt
);
4004 fprintf(rej
, "%.*s", frag
->size
, frag
->patch
);
4005 if (frag
->patch
[frag
->size
-1] != '\n')
4012 static int write_out_results(struct patch
*list
)
4017 struct string_list cpath
= STRING_LIST_INIT_DUP
;
4019 for (phase
= 0; phase
< 2; phase
++) {
4025 write_out_one_result(l
, phase
);
4027 if (write_out_one_reject(l
))
4029 if (l
->conflicted_threeway
) {
4030 string_list_append(&cpath
, l
->new_name
);
4040 struct string_list_item
*item
;
4042 sort_string_list(&cpath
);
4043 for_each_string_list_item(item
, &cpath
)
4044 fprintf(stderr
, "U %s\n", item
->string
);
4045 string_list_clear(&cpath
, 0);
4053 static struct lock_file lock_file
;
4055 static struct string_list limit_by_name
;
4056 static int has_include
;
4057 static void add_name_limit(const char *name
, int exclude
)
4059 struct string_list_item
*it
;
4061 it
= string_list_append(&limit_by_name
, name
);
4062 it
->util
= exclude
? NULL
: (void *) 1;
4065 static int use_patch(struct patch
*p
)
4067 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
4070 /* Paths outside are not touched regardless of "--include" */
4071 if (0 < prefix_length
) {
4072 int pathlen
= strlen(pathname
);
4073 if (pathlen
<= prefix_length
||
4074 memcmp(prefix
, pathname
, prefix_length
))
4078 /* See if it matches any of exclude/include rule */
4079 for (i
= 0; i
< limit_by_name
.nr
; i
++) {
4080 struct string_list_item
*it
= &limit_by_name
.items
[i
];
4081 if (!fnmatch(it
->string
, pathname
, 0))
4082 return (it
->util
!= NULL
);
4086 * If we had any include, a path that does not match any rule is
4087 * not used. Otherwise, we saw bunch of exclude rules (or none)
4088 * and such a path is used.
4090 return !has_include
;
4094 static void prefix_one(char **name
)
4096 char *old_name
= *name
;
4099 *name
= xstrdup(prefix_filename(prefix
, prefix_length
, *name
));
4103 static void prefix_patches(struct patch
*p
)
4105 if (!prefix
|| p
->is_toplevel_relative
)
4107 for ( ; p
; p
= p
->next
) {
4108 prefix_one(&p
->new_name
);
4109 prefix_one(&p
->old_name
);
4113 #define INACCURATE_EOF (1<<0)
4114 #define RECOUNT (1<<1)
4116 static int apply_patch(int fd
, const char *filename
, int options
)
4119 struct strbuf buf
= STRBUF_INIT
; /* owns the patch text */
4120 struct patch
*list
= NULL
, **listp
= &list
;
4121 int skipped_patch
= 0;
4123 patch_input_file
= filename
;
4124 read_patch_file(&buf
, fd
);
4126 while (offset
< buf
.len
) {
4127 struct patch
*patch
;
4130 patch
= xcalloc(1, sizeof(*patch
));
4131 patch
->inaccurate_eof
= !!(options
& INACCURATE_EOF
);
4132 patch
->recount
= !!(options
& RECOUNT
);
4133 nr
= parse_chunk(buf
.buf
+ offset
, buf
.len
- offset
, patch
);
4136 if (apply_in_reverse
)
4137 reverse_patches(patch
);
4139 prefix_patches(patch
);
4140 if (use_patch(patch
)) {
4143 listp
= &patch
->next
;
4152 if (!list
&& !skipped_patch
)
4153 die(_("unrecognized input"));
4155 if (whitespace_error
&& (ws_error_action
== die_on_ws_error
))
4158 update_index
= check_index
&& apply
;
4159 if (update_index
&& newfd
< 0)
4160 newfd
= hold_locked_index(&lock_file
, 1);
4163 if (read_cache() < 0)
4164 die(_("unable to read index file"));
4167 if ((check
|| apply
) &&
4168 check_patch_list(list
) < 0 &&
4172 if (apply
&& write_out_results(list
)) {
4173 if (apply_with_reject
)
4175 /* with --3way, we still need to write the index out */
4180 build_fake_ancestor(list
, fake_ancestor
);
4183 stat_patch_list(list
);
4186 numstat_patch_list(list
);
4189 summary_patch_list(list
);
4191 free_patch_list(list
);
4192 strbuf_release(&buf
);
4193 string_list_clear(&fn_table
, 0);
4197 static int git_apply_config(const char *var
, const char *value
, void *cb
)
4199 if (!strcmp(var
, "apply.whitespace"))
4200 return git_config_string(&apply_default_whitespace
, var
, value
);
4201 else if (!strcmp(var
, "apply.ignorewhitespace"))
4202 return git_config_string(&apply_default_ignorewhitespace
, var
, value
);
4203 return git_default_config(var
, value
, cb
);
4206 static int option_parse_exclude(const struct option
*opt
,
4207 const char *arg
, int unset
)
4209 add_name_limit(arg
, 1);
4213 static int option_parse_include(const struct option
*opt
,
4214 const char *arg
, int unset
)
4216 add_name_limit(arg
, 0);
4221 static int option_parse_p(const struct option
*opt
,
4222 const char *arg
, int unset
)
4224 p_value
= atoi(arg
);
4229 static int option_parse_z(const struct option
*opt
,
4230 const char *arg
, int unset
)
4233 line_termination
= '\n';
4235 line_termination
= 0;
4239 static int option_parse_space_change(const struct option
*opt
,
4240 const char *arg
, int unset
)
4243 ws_ignore_action
= ignore_ws_none
;
4245 ws_ignore_action
= ignore_ws_change
;
4249 static int option_parse_whitespace(const struct option
*opt
,
4250 const char *arg
, int unset
)
4252 const char **whitespace_option
= opt
->value
;
4254 *whitespace_option
= arg
;
4255 parse_whitespace_option(arg
);
4259 static int option_parse_directory(const struct option
*opt
,
4260 const char *arg
, int unset
)
4262 root_len
= strlen(arg
);
4263 if (root_len
&& arg
[root_len
- 1] != '/') {
4265 root
= new_root
= xmalloc(root_len
+ 2);
4266 strcpy(new_root
, arg
);
4267 strcpy(new_root
+ root_len
++, "/");
4273 int cmd_apply(int argc
, const char **argv
, const char *prefix_
)
4277 int is_not_gitdir
= !startup_info
->have_repository
;
4278 int force_apply
= 0;
4280 const char *whitespace_option
= NULL
;
4282 struct option builtin_apply_options
[] = {
4283 { OPTION_CALLBACK
, 0, "exclude", NULL
, N_("path"),
4284 N_("don't apply changes matching the given path"),
4285 0, option_parse_exclude
},
4286 { OPTION_CALLBACK
, 0, "include", NULL
, N_("path"),
4287 N_("apply changes matching the given path"),
4288 0, option_parse_include
},
4289 { OPTION_CALLBACK
, 'p', NULL
, NULL
, N_("num"),
4290 N_("remove <num> leading slashes from traditional diff paths"),
4291 0, option_parse_p
},
4292 OPT_BOOLEAN(0, "no-add", &no_add
,
4293 N_("ignore additions made by the patch")),
4294 OPT_BOOLEAN(0, "stat", &diffstat
,
4295 N_("instead of applying the patch, output diffstat for the input")),
4296 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
4297 OPT_NOOP_NOARG(0, "binary"),
4298 OPT_BOOLEAN(0, "numstat", &numstat
,
4299 N_("shows number of added and deleted lines in decimal notation")),
4300 OPT_BOOLEAN(0, "summary", &summary
,
4301 N_("instead of applying the patch, output a summary for the input")),
4302 OPT_BOOLEAN(0, "check", &check
,
4303 N_("instead of applying the patch, see if the patch is applicable")),
4304 OPT_BOOLEAN(0, "index", &check_index
,
4305 N_("make sure the patch is applicable to the current index")),
4306 OPT_BOOLEAN(0, "cached", &cached
,
4307 N_("apply a patch without touching the working tree")),
4308 OPT_BOOLEAN(0, "apply", &force_apply
,
4309 N_("also apply the patch (use with --stat/--summary/--check)")),
4310 OPT_BOOL('3', "3way", &threeway
,
4311 N_( "attempt three-way merge if a patch does not apply")),
4312 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor
,
4313 N_("build a temporary index based on embedded index information")),
4314 { OPTION_CALLBACK
, 'z', NULL
, NULL
, NULL
,
4315 N_("paths are separated with NUL character"),
4316 PARSE_OPT_NOARG
, option_parse_z
},
4317 OPT_INTEGER('C', NULL
, &p_context
,
4318 N_("ensure at least <n> lines of context match")),
4319 { OPTION_CALLBACK
, 0, "whitespace", &whitespace_option
, N_("action"),
4320 N_("detect new or modified lines that have whitespace errors"),
4321 0, option_parse_whitespace
},
4322 { OPTION_CALLBACK
, 0, "ignore-space-change", NULL
, NULL
,
4323 N_("ignore changes in whitespace when finding context"),
4324 PARSE_OPT_NOARG
, option_parse_space_change
},
4325 { OPTION_CALLBACK
, 0, "ignore-whitespace", NULL
, NULL
,
4326 N_("ignore changes in whitespace when finding context"),
4327 PARSE_OPT_NOARG
, option_parse_space_change
},
4328 OPT_BOOLEAN('R', "reverse", &apply_in_reverse
,
4329 N_("apply the patch in reverse")),
4330 OPT_BOOLEAN(0, "unidiff-zero", &unidiff_zero
,
4331 N_("don't expect at least one line of context")),
4332 OPT_BOOLEAN(0, "reject", &apply_with_reject
,
4333 N_("leave the rejected hunks in corresponding *.rej files")),
4334 OPT_BOOLEAN(0, "allow-overlap", &allow_overlap
,
4335 N_("allow overlapping hunks")),
4336 OPT__VERBOSE(&apply_verbosely
, N_("be verbose")),
4337 OPT_BIT(0, "inaccurate-eof", &options
,
4338 N_("tolerate incorrectly detected missing new-line at the end of file"),
4340 OPT_BIT(0, "recount", &options
,
4341 N_("do not trust the line counts in the hunk headers"),
4343 { OPTION_CALLBACK
, 0, "directory", NULL
, N_("root"),
4344 N_("prepend <root> to all filenames"),
4345 0, option_parse_directory
},
4350 prefix_length
= prefix
? strlen(prefix
) : 0;
4351 git_config(git_apply_config
, NULL
);
4352 if (apply_default_whitespace
)
4353 parse_whitespace_option(apply_default_whitespace
);
4354 if (apply_default_ignorewhitespace
)
4355 parse_ignorewhitespace_option(apply_default_ignorewhitespace
);
4357 argc
= parse_options(argc
, argv
, prefix
, builtin_apply_options
,
4360 if (apply_with_reject
&& threeway
)
4361 die("--reject and --3way cannot be used together.");
4362 if (cached
&& threeway
)
4363 die("--cached and --3way cannot be used together.");
4366 die(_("--3way outside a repository"));
4369 if (apply_with_reject
)
4370 apply
= apply_verbosely
= 1;
4371 if (!force_apply
&& (diffstat
|| numstat
|| summary
|| check
|| fake_ancestor
))
4373 if (check_index
&& is_not_gitdir
)
4374 die(_("--index outside a repository"));
4377 die(_("--cached outside a repository"));
4380 for (i
= 0; i
< argc
; i
++) {
4381 const char *arg
= argv
[i
];
4384 if (!strcmp(arg
, "-")) {
4385 errs
|= apply_patch(0, "<stdin>", options
);
4388 } else if (0 < prefix_length
)
4389 arg
= prefix_filename(prefix
, prefix_length
, arg
);
4391 fd
= open(arg
, O_RDONLY
);
4393 die_errno(_("can't open patch '%s'"), arg
);
4395 set_default_whitespace_mode(whitespace_option
);
4396 errs
|= apply_patch(fd
, arg
, options
);
4399 set_default_whitespace_mode(whitespace_option
);
4401 errs
|= apply_patch(0, "<stdin>", options
);
4402 if (whitespace_error
) {
4403 if (squelch_whitespace_errors
&&
4404 squelch_whitespace_errors
< whitespace_error
) {
4406 whitespace_error
- squelch_whitespace_errors
;
4407 warning(Q_("squelched %d whitespace error",
4408 "squelched %d whitespace errors",
4412 if (ws_error_action
== die_on_ws_error
)
4413 die(Q_("%d line adds whitespace errors.",
4414 "%d lines add whitespace errors.",
4417 if (applied_after_fixing_ws
&& apply
)
4418 warning("%d line%s applied after"
4419 " fixing whitespace errors.",
4420 applied_after_fixing_ws
,
4421 applied_after_fixing_ws
== 1 ? "" : "s");
4422 else if (whitespace_error
)
4423 warning(Q_("%d line adds whitespace errors.",
4424 "%d lines add whitespace errors.",
4430 if (write_cache(newfd
, active_cache
, active_nr
) ||
4431 commit_locked_index(&lock_file
))
4432 die(_("Unable to write new index file"));