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 whitespaces, if both begin with whitespace */
304 if (s1
<= last1
&& s2
<= last2
&& isspace(*s1
) && isspace(*s2
)) {
305 while (isspace(*s1
) && (s1
<= last1
))
307 while (isspace(*s2
) && (s2
<= last2
))
310 /* early return if both lines are empty */
311 if ((s1
> last1
) && (s2
> last2
))
314 result
= *s1
++ - *s2
++;
316 * Skip whitespace inside. We check for whitespace on
317 * both buffers because we don't want "a b" to match
320 if (isspace(*s1
) && isspace(*s2
)) {
321 while (isspace(*s1
) && s1
<= last1
)
323 while (isspace(*s2
) && s2
<= last2
)
327 * If we reached the end on one side only,
331 ((s2
> last2
) && (s1
<= last1
)) ||
332 ((s1
> last1
) && (s2
<= last2
)))
334 if ((s1
> last1
) && (s2
> last2
))
341 static void add_line_info(struct image
*img
, const char *bol
, size_t len
, unsigned flag
)
343 ALLOC_GROW(img
->line_allocated
, img
->nr
+ 1, img
->alloc
);
344 img
->line_allocated
[img
->nr
].len
= len
;
345 img
->line_allocated
[img
->nr
].hash
= hash_line(bol
, len
);
346 img
->line_allocated
[img
->nr
].flag
= flag
;
351 * "buf" has the file contents to be patched (read from various sources).
352 * attach it to "image" and add line-based index to it.
353 * "image" now owns the "buf".
355 static void prepare_image(struct image
*image
, char *buf
, size_t len
,
356 int prepare_linetable
)
360 memset(image
, 0, sizeof(*image
));
364 if (!prepare_linetable
)
367 ep
= image
->buf
+ image
->len
;
371 for (next
= cp
; next
< ep
&& *next
!= '\n'; next
++)
375 add_line_info(image
, cp
, next
- cp
, 0);
378 image
->line
= image
->line_allocated
;
381 static void clear_image(struct image
*image
)
384 free(image
->line_allocated
);
385 memset(image
, 0, sizeof(*image
));
388 /* fmt must contain _one_ %s and no other substitution */
389 static void say_patch_name(FILE *output
, const char *fmt
, struct patch
*patch
)
391 struct strbuf sb
= STRBUF_INIT
;
393 if (patch
->old_name
&& patch
->new_name
&&
394 strcmp(patch
->old_name
, patch
->new_name
)) {
395 quote_c_style(patch
->old_name
, &sb
, NULL
, 0);
396 strbuf_addstr(&sb
, " => ");
397 quote_c_style(patch
->new_name
, &sb
, NULL
, 0);
399 const char *n
= patch
->new_name
;
402 quote_c_style(n
, &sb
, NULL
, 0);
404 fprintf(output
, fmt
, sb
.buf
);
411 static void read_patch_file(struct strbuf
*sb
, int fd
)
413 if (strbuf_read(sb
, fd
, 0) < 0)
414 die_errno("git apply: failed to read");
417 * Make sure that we have some slop in the buffer
418 * so that we can do speculative "memcmp" etc, and
419 * see to it that it is NUL-filled.
421 strbuf_grow(sb
, SLOP
);
422 memset(sb
->buf
+ sb
->len
, 0, SLOP
);
425 static unsigned long linelen(const char *buffer
, unsigned long size
)
427 unsigned long len
= 0;
430 if (*buffer
++ == '\n')
436 static int is_dev_null(const char *str
)
438 return !memcmp("/dev/null", str
, 9) && isspace(str
[9]);
444 static int name_terminate(const char *name
, int namelen
, int c
, int terminate
)
446 if (c
== ' ' && !(terminate
& TERM_SPACE
))
448 if (c
== '\t' && !(terminate
& TERM_TAB
))
454 /* remove double slashes to make --index work with such filenames */
455 static char *squash_slash(char *name
)
463 if ((name
[j
++] = name
[i
++]) == '/')
464 while (name
[i
] == '/')
471 static char *find_name_gnu(const char *line
, const char *def
, int p_value
)
473 struct strbuf name
= STRBUF_INIT
;
477 * Proposed "new-style" GNU patch/diff format; see
478 * http://marc.info/?l=git&m=112927316408690&w=2
480 if (unquote_c_style(&name
, line
, NULL
)) {
481 strbuf_release(&name
);
485 for (cp
= name
.buf
; p_value
; p_value
--) {
486 cp
= strchr(cp
, '/');
488 strbuf_release(&name
);
494 strbuf_remove(&name
, 0, cp
- name
.buf
);
496 strbuf_insert(&name
, 0, root
, root_len
);
497 return squash_slash(strbuf_detach(&name
, NULL
));
500 static size_t sane_tz_len(const char *line
, size_t len
)
504 if (len
< strlen(" +0500") || line
[len
-strlen(" +0500")] != ' ')
506 tz
= line
+ len
- strlen(" +0500");
508 if (tz
[1] != '+' && tz
[1] != '-')
511 for (p
= tz
+ 2; p
!= line
+ len
; p
++)
515 return line
+ len
- tz
;
518 static size_t tz_with_colon_len(const char *line
, size_t len
)
522 if (len
< strlen(" +08:00") || line
[len
- strlen(":00")] != ':')
524 tz
= line
+ len
- strlen(" +08:00");
526 if (tz
[0] != ' ' || (tz
[1] != '+' && tz
[1] != '-'))
529 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
530 !isdigit(*p
++) || !isdigit(*p
++))
533 return line
+ len
- tz
;
536 static size_t date_len(const char *line
, size_t len
)
538 const char *date
, *p
;
540 if (len
< strlen("72-02-05") || line
[len
-strlen("-05")] != '-')
542 p
= date
= line
+ len
- strlen("72-02-05");
544 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
545 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
546 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a date. */
549 if (date
- line
>= strlen("19") &&
550 isdigit(date
[-1]) && isdigit(date
[-2])) /* 4-digit year */
551 date
-= strlen("19");
553 return line
+ len
- date
;
556 static size_t short_time_len(const char *line
, size_t len
)
558 const char *time
, *p
;
560 if (len
< strlen(" 07:01:32") || line
[len
-strlen(":32")] != ':')
562 p
= time
= line
+ len
- strlen(" 07:01:32");
564 /* Permit 1-digit hours? */
566 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
567 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
568 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a time. */
571 return line
+ len
- time
;
574 static size_t fractional_time_len(const char *line
, size_t len
)
579 /* Expected format: 19:41:17.620000023 */
580 if (!len
|| !isdigit(line
[len
- 1]))
584 /* Fractional seconds. */
585 while (p
> line
&& isdigit(*p
))
590 /* Hours, minutes, and whole seconds. */
591 n
= short_time_len(line
, p
- line
);
595 return line
+ len
- p
+ n
;
598 static size_t trailing_spaces_len(const char *line
, size_t len
)
602 /* Expected format: ' ' x (1 or more) */
603 if (!len
|| line
[len
- 1] != ' ')
610 return line
+ len
- (p
+ 1);
617 static size_t diff_timestamp_len(const char *line
, size_t len
)
619 const char *end
= line
+ len
;
623 * Posix: 2010-07-05 19:41:17
624 * GNU: 2010-07-05 19:41:17.620000023 -0500
627 if (!isdigit(end
[-1]))
630 n
= sane_tz_len(line
, end
- line
);
632 n
= tz_with_colon_len(line
, end
- line
);
635 n
= short_time_len(line
, end
- line
);
637 n
= fractional_time_len(line
, end
- line
);
640 n
= date_len(line
, end
- line
);
641 if (!n
) /* No date. Too bad. */
645 if (end
== line
) /* No space before date. */
647 if (end
[-1] == '\t') { /* Success! */
649 return line
+ len
- end
;
651 if (end
[-1] != ' ') /* No space before date. */
654 /* Whitespace damage. */
655 end
-= trailing_spaces_len(line
, end
- line
);
656 return line
+ len
- end
;
659 static char *find_name_common(const char *line
, const char *def
,
660 int p_value
, const char *end
, int terminate
)
663 const char *start
= NULL
;
667 while (line
!= end
) {
670 if (!end
&& isspace(c
)) {
673 if (name_terminate(start
, line
-start
, c
, terminate
))
677 if (c
== '/' && !--p_value
)
681 return squash_slash(xstrdup_or_null(def
));
684 return squash_slash(xstrdup_or_null(def
));
687 * Generally we prefer the shorter name, especially
688 * if the other one is just a variation of that with
689 * something else tacked on to the end (ie "file.orig"
693 int deflen
= strlen(def
);
694 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
695 return squash_slash(xstrdup(def
));
699 char *ret
= xmalloc(root_len
+ len
+ 1);
701 memcpy(ret
+ root_len
, start
, len
);
702 ret
[root_len
+ len
] = '\0';
703 return squash_slash(ret
);
706 return squash_slash(xmemdupz(start
, len
));
709 static char *find_name(const char *line
, char *def
, int p_value
, int terminate
)
712 char *name
= find_name_gnu(line
, def
, p_value
);
717 return find_name_common(line
, def
, p_value
, NULL
, terminate
);
720 static char *find_name_traditional(const char *line
, char *def
, int p_value
)
726 char *name
= find_name_gnu(line
, def
, p_value
);
731 len
= strchrnul(line
, '\n') - line
;
732 date_len
= diff_timestamp_len(line
, len
);
734 return find_name_common(line
, def
, p_value
, NULL
, TERM_TAB
);
737 return find_name_common(line
, def
, p_value
, line
+ len
, 0);
740 static int count_slashes(const char *cp
)
752 * Given the string after "--- " or "+++ ", guess the appropriate
753 * p_value for the given patch.
755 static int guess_p_value(const char *nameline
)
760 if (is_dev_null(nameline
))
762 name
= find_name_traditional(nameline
, NULL
, 0);
765 cp
= strchr(name
, '/');
770 * Does it begin with "a/$our-prefix" and such? Then this is
771 * very likely to apply to our directory.
773 if (!strncmp(name
, prefix
, prefix_length
))
774 val
= count_slashes(prefix
);
777 if (!strncmp(cp
, prefix
, prefix_length
))
778 val
= count_slashes(prefix
) + 1;
786 * Does the ---/+++ line has the POSIX timestamp after the last HT?
787 * GNU diff puts epoch there to signal a creation/deletion event. Is
788 * this such a timestamp?
790 static int has_epoch_timestamp(const char *nameline
)
793 * We are only interested in epoch timestamp; any non-zero
794 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
795 * For the same reason, the date must be either 1969-12-31 or
796 * 1970-01-01, and the seconds part must be "00".
798 const char stamp_regexp
[] =
799 "^(1969-12-31|1970-01-01)"
801 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
803 "([-+][0-2][0-9]:?[0-5][0-9])\n";
804 const char *timestamp
= NULL
, *cp
, *colon
;
805 static regex_t
*stamp
;
811 for (cp
= nameline
; *cp
!= '\n'; cp
++) {
818 stamp
= xmalloc(sizeof(*stamp
));
819 if (regcomp(stamp
, stamp_regexp
, REG_EXTENDED
)) {
820 warning(_("Cannot prepare timestamp regexp %s"),
826 status
= regexec(stamp
, timestamp
, ARRAY_SIZE(m
), m
, 0);
828 if (status
!= REG_NOMATCH
)
829 warning(_("regexec returned %d for input: %s"),
834 zoneoffset
= strtol(timestamp
+ m
[3].rm_so
+ 1, (char **) &colon
, 10);
836 zoneoffset
= zoneoffset
* 60 + strtol(colon
+ 1, NULL
, 10);
838 zoneoffset
= (zoneoffset
/ 100) * 60 + (zoneoffset
% 100);
839 if (timestamp
[m
[3].rm_so
] == '-')
840 zoneoffset
= -zoneoffset
;
843 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
844 * (west of GMT) or 1970-01-01 (east of GMT)
846 if ((zoneoffset
< 0 && memcmp(timestamp
, "1969-12-31", 10)) ||
847 (0 <= zoneoffset
&& memcmp(timestamp
, "1970-01-01", 10)))
850 hourminute
= (strtol(timestamp
+ 11, NULL
, 10) * 60 +
851 strtol(timestamp
+ 14, NULL
, 10) -
854 return ((zoneoffset
< 0 && hourminute
== 1440) ||
855 (0 <= zoneoffset
&& !hourminute
));
859 * Get the name etc info from the ---/+++ lines of a traditional patch header
861 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
862 * files, we can happily check the index for a match, but for creating a
863 * new file we should try to match whatever "patch" does. I have no idea.
865 static void parse_traditional_patch(const char *first
, const char *second
, struct patch
*patch
)
869 first
+= 4; /* skip "--- " */
870 second
+= 4; /* skip "+++ " */
871 if (!p_value_known
) {
873 p
= guess_p_value(first
);
874 q
= guess_p_value(second
);
876 if (0 <= p
&& p
== q
) {
881 if (is_dev_null(first
)) {
883 patch
->is_delete
= 0;
884 name
= find_name_traditional(second
, NULL
, p_value
);
885 patch
->new_name
= name
;
886 } else if (is_dev_null(second
)) {
888 patch
->is_delete
= 1;
889 name
= find_name_traditional(first
, NULL
, p_value
);
890 patch
->old_name
= name
;
893 first_name
= find_name_traditional(first
, NULL
, p_value
);
894 name
= find_name_traditional(second
, first_name
, p_value
);
896 if (has_epoch_timestamp(first
)) {
898 patch
->is_delete
= 0;
899 patch
->new_name
= name
;
900 } else if (has_epoch_timestamp(second
)) {
902 patch
->is_delete
= 1;
903 patch
->old_name
= name
;
905 patch
->old_name
= name
;
906 patch
->new_name
= xstrdup_or_null(name
);
910 die(_("unable to find filename in patch at line %d"), linenr
);
913 static int gitdiff_hdrend(const char *line
, struct patch
*patch
)
919 * We're anal about diff header consistency, to make
920 * sure that we don't end up having strange ambiguous
921 * patches floating around.
923 * As a result, gitdiff_{old|new}name() will check
924 * their names against any previous information, just
927 #define DIFF_OLD_NAME 0
928 #define DIFF_NEW_NAME 1
930 static char *gitdiff_verify_name(const char *line
, int isnull
, char *orig_name
, int side
)
932 if (!orig_name
&& !isnull
)
933 return find_name(line
, NULL
, p_value
, TERM_TAB
);
942 die(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"), name
, linenr
);
943 another
= find_name(line
, NULL
, p_value
, TERM_TAB
);
944 if (!another
|| memcmp(another
, name
, len
+ 1))
945 die((side
== DIFF_NEW_NAME
) ?
946 _("git apply: bad git-diff - inconsistent new filename on line %d") :
947 _("git apply: bad git-diff - inconsistent old filename on line %d"), linenr
);
952 /* expect "/dev/null" */
953 if (memcmp("/dev/null", line
, 9) || line
[9] != '\n')
954 die(_("git apply: bad git-diff - expected /dev/null on line %d"), linenr
);
959 static int gitdiff_oldname(const char *line
, struct patch
*patch
)
961 char *orig
= patch
->old_name
;
962 patch
->old_name
= gitdiff_verify_name(line
, patch
->is_new
, patch
->old_name
,
964 if (orig
!= patch
->old_name
)
969 static int gitdiff_newname(const char *line
, struct patch
*patch
)
971 char *orig
= patch
->new_name
;
972 patch
->new_name
= gitdiff_verify_name(line
, patch
->is_delete
, patch
->new_name
,
974 if (orig
!= patch
->new_name
)
979 static int gitdiff_oldmode(const char *line
, struct patch
*patch
)
981 patch
->old_mode
= strtoul(line
, NULL
, 8);
985 static int gitdiff_newmode(const char *line
, struct patch
*patch
)
987 patch
->new_mode
= strtoul(line
, NULL
, 8);
991 static int gitdiff_delete(const char *line
, struct patch
*patch
)
993 patch
->is_delete
= 1;
994 free(patch
->old_name
);
995 patch
->old_name
= xstrdup_or_null(patch
->def_name
);
996 return gitdiff_oldmode(line
, patch
);
999 static int gitdiff_newfile(const char *line
, struct patch
*patch
)
1002 free(patch
->new_name
);
1003 patch
->new_name
= xstrdup_or_null(patch
->def_name
);
1004 return gitdiff_newmode(line
, patch
);
1007 static int gitdiff_copysrc(const char *line
, struct patch
*patch
)
1010 free(patch
->old_name
);
1011 patch
->old_name
= find_name(line
, NULL
, p_value
? p_value
- 1 : 0, 0);
1015 static int gitdiff_copydst(const char *line
, struct patch
*patch
)
1018 free(patch
->new_name
);
1019 patch
->new_name
= find_name(line
, NULL
, p_value
? p_value
- 1 : 0, 0);
1023 static int gitdiff_renamesrc(const char *line
, struct patch
*patch
)
1025 patch
->is_rename
= 1;
1026 free(patch
->old_name
);
1027 patch
->old_name
= find_name(line
, NULL
, p_value
? p_value
- 1 : 0, 0);
1031 static int gitdiff_renamedst(const char *line
, struct patch
*patch
)
1033 patch
->is_rename
= 1;
1034 free(patch
->new_name
);
1035 patch
->new_name
= find_name(line
, NULL
, p_value
? p_value
- 1 : 0, 0);
1039 static int gitdiff_similarity(const char *line
, struct patch
*patch
)
1041 unsigned long val
= strtoul(line
, NULL
, 10);
1047 static int gitdiff_dissimilarity(const char *line
, struct patch
*patch
)
1049 unsigned long val
= strtoul(line
, NULL
, 10);
1055 static int gitdiff_index(const char *line
, struct patch
*patch
)
1058 * index line is N hexadecimal, "..", N hexadecimal,
1059 * and optional space with octal mode.
1061 const char *ptr
, *eol
;
1064 ptr
= strchr(line
, '.');
1065 if (!ptr
|| ptr
[1] != '.' || 40 < ptr
- line
)
1068 memcpy(patch
->old_sha1_prefix
, line
, len
);
1069 patch
->old_sha1_prefix
[len
] = 0;
1072 ptr
= strchr(line
, ' ');
1073 eol
= strchrnul(line
, '\n');
1075 if (!ptr
|| eol
< ptr
)
1081 memcpy(patch
->new_sha1_prefix
, line
, len
);
1082 patch
->new_sha1_prefix
[len
] = 0;
1084 patch
->old_mode
= strtoul(ptr
+1, NULL
, 8);
1089 * This is normal for a diff that doesn't change anything: we'll fall through
1090 * into the next diff. Tell the parser to break out.
1092 static int gitdiff_unrecognized(const char *line
, struct patch
*patch
)
1098 * Skip p_value leading components from "line"; as we do not accept
1099 * absolute paths, return NULL in that case.
1101 static const char *skip_tree_prefix(const char *line
, int llen
)
1107 return (llen
&& line
[0] == '/') ? NULL
: line
;
1110 for (i
= 0; i
< llen
; i
++) {
1112 if (ch
== '/' && --nslash
<= 0)
1113 return (i
== 0) ? NULL
: &line
[i
+ 1];
1119 * This is to extract the same name that appears on "diff --git"
1120 * line. We do not find and return anything if it is a rename
1121 * patch, and it is OK because we will find the name elsewhere.
1122 * We need to reliably find name only when it is mode-change only,
1123 * creation or deletion of an empty file. In any of these cases,
1124 * both sides are the same name under a/ and b/ respectively.
1126 static char *git_header_name(const char *line
, int llen
)
1129 const char *second
= NULL
;
1130 size_t len
, line_len
;
1132 line
+= strlen("diff --git ");
1133 llen
-= strlen("diff --git ");
1137 struct strbuf first
= STRBUF_INIT
;
1138 struct strbuf sp
= STRBUF_INIT
;
1140 if (unquote_c_style(&first
, line
, &second
))
1141 goto free_and_fail1
;
1143 /* strip the a/b prefix including trailing slash */
1144 cp
= skip_tree_prefix(first
.buf
, first
.len
);
1146 goto free_and_fail1
;
1147 strbuf_remove(&first
, 0, cp
- first
.buf
);
1150 * second points at one past closing dq of name.
1151 * find the second name.
1153 while ((second
< line
+ llen
) && isspace(*second
))
1156 if (line
+ llen
<= second
)
1157 goto free_and_fail1
;
1158 if (*second
== '"') {
1159 if (unquote_c_style(&sp
, second
, NULL
))
1160 goto free_and_fail1
;
1161 cp
= skip_tree_prefix(sp
.buf
, sp
.len
);
1163 goto free_and_fail1
;
1164 /* They must match, otherwise ignore */
1165 if (strcmp(cp
, first
.buf
))
1166 goto free_and_fail1
;
1167 strbuf_release(&sp
);
1168 return strbuf_detach(&first
, NULL
);
1171 /* unquoted second */
1172 cp
= skip_tree_prefix(second
, line
+ llen
- second
);
1174 goto free_and_fail1
;
1175 if (line
+ llen
- cp
!= first
.len
||
1176 memcmp(first
.buf
, cp
, first
.len
))
1177 goto free_and_fail1
;
1178 return strbuf_detach(&first
, NULL
);
1181 strbuf_release(&first
);
1182 strbuf_release(&sp
);
1186 /* unquoted first name */
1187 name
= skip_tree_prefix(line
, llen
);
1192 * since the first name is unquoted, a dq if exists must be
1193 * the beginning of the second name.
1195 for (second
= name
; second
< line
+ llen
; second
++) {
1196 if (*second
== '"') {
1197 struct strbuf sp
= STRBUF_INIT
;
1200 if (unquote_c_style(&sp
, second
, NULL
))
1201 goto free_and_fail2
;
1203 np
= skip_tree_prefix(sp
.buf
, sp
.len
);
1205 goto free_and_fail2
;
1207 len
= sp
.buf
+ sp
.len
- np
;
1208 if (len
< second
- name
&&
1209 !strncmp(np
, name
, len
) &&
1210 isspace(name
[len
])) {
1212 strbuf_remove(&sp
, 0, np
- sp
.buf
);
1213 return strbuf_detach(&sp
, NULL
);
1217 strbuf_release(&sp
);
1223 * Accept a name only if it shows up twice, exactly the same
1226 second
= strchr(name
, '\n');
1229 line_len
= second
- name
;
1230 for (len
= 0 ; ; len
++) {
1231 switch (name
[len
]) {
1236 case '\t': case ' ':
1238 * Is this the separator between the preimage
1239 * and the postimage pathname? Again, we are
1240 * only interested in the case where there is
1241 * no rename, as this is only to set def_name
1242 * and a rename patch has the names elsewhere
1243 * in an unambiguous form.
1246 return NULL
; /* no postimage name */
1247 second
= skip_tree_prefix(name
+ len
+ 1,
1248 line_len
- (len
+ 1));
1252 * Does len bytes starting at "name" and "second"
1253 * (that are separated by one HT or SP we just
1254 * found) exactly match?
1256 if (second
[len
] == '\n' && !strncmp(name
, second
, len
))
1257 return xmemdupz(name
, len
);
1262 /* Verify that we recognize the lines following a git header */
1263 static int parse_git_header(const char *line
, int len
, unsigned int size
, struct patch
*patch
)
1265 unsigned long offset
;
1267 /* A git diff has explicit new/delete information, so we don't guess */
1269 patch
->is_delete
= 0;
1272 * Some things may not have the old name in the
1273 * rest of the headers anywhere (pure mode changes,
1274 * or removing or adding empty files), so we get
1275 * the default name from the header.
1277 patch
->def_name
= git_header_name(line
, len
);
1278 if (patch
->def_name
&& root
) {
1279 char *s
= xstrfmt("%s%s", root
, patch
->def_name
);
1280 free(patch
->def_name
);
1281 patch
->def_name
= s
;
1287 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1288 static const struct opentry
{
1290 int (*fn
)(const char *, struct patch
*);
1292 { "@@ -", gitdiff_hdrend
},
1293 { "--- ", gitdiff_oldname
},
1294 { "+++ ", gitdiff_newname
},
1295 { "old mode ", gitdiff_oldmode
},
1296 { "new mode ", gitdiff_newmode
},
1297 { "deleted file mode ", gitdiff_delete
},
1298 { "new file mode ", gitdiff_newfile
},
1299 { "copy from ", gitdiff_copysrc
},
1300 { "copy to ", gitdiff_copydst
},
1301 { "rename old ", gitdiff_renamesrc
},
1302 { "rename new ", gitdiff_renamedst
},
1303 { "rename from ", gitdiff_renamesrc
},
1304 { "rename to ", gitdiff_renamedst
},
1305 { "similarity index ", gitdiff_similarity
},
1306 { "dissimilarity index ", gitdiff_dissimilarity
},
1307 { "index ", gitdiff_index
},
1308 { "", gitdiff_unrecognized
},
1312 len
= linelen(line
, size
);
1313 if (!len
|| line
[len
-1] != '\n')
1315 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
1316 const struct opentry
*p
= optable
+ i
;
1317 int oplen
= strlen(p
->str
);
1318 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
1320 if (p
->fn(line
+ oplen
, patch
) < 0)
1329 static int parse_num(const char *line
, unsigned long *p
)
1333 if (!isdigit(*line
))
1335 *p
= strtoul(line
, &ptr
, 10);
1339 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
1340 unsigned long *p1
, unsigned long *p2
)
1344 if (offset
< 0 || offset
>= len
)
1349 digits
= parse_num(line
, p1
);
1359 digits
= parse_num(line
+1, p2
);
1368 ex
= strlen(expect
);
1371 if (memcmp(line
, expect
, ex
))
1377 static void recount_diff(const char *line
, int size
, struct fragment
*fragment
)
1379 int oldlines
= 0, newlines
= 0, ret
= 0;
1382 warning("recount: ignore empty hunk");
1387 int len
= linelen(line
, size
);
1395 case ' ': case '\n':
1407 ret
= size
< 3 || !starts_with(line
, "@@ ");
1410 ret
= size
< 5 || !starts_with(line
, "diff ");
1417 warning(_("recount: unexpected line: %.*s"),
1418 (int)linelen(line
, size
), line
);
1423 fragment
->oldlines
= oldlines
;
1424 fragment
->newlines
= newlines
;
1428 * Parse a unified diff fragment header of the
1429 * form "@@ -a,b +c,d @@"
1431 static int parse_fragment_header(const char *line
, int len
, struct fragment
*fragment
)
1435 if (!len
|| line
[len
-1] != '\n')
1438 /* Figure out the number of lines in a fragment */
1439 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
1440 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
1445 static int find_header(const char *line
, unsigned long size
, int *hdrsize
, struct patch
*patch
)
1447 unsigned long offset
, len
;
1449 patch
->is_toplevel_relative
= 0;
1450 patch
->is_rename
= patch
->is_copy
= 0;
1451 patch
->is_new
= patch
->is_delete
= -1;
1452 patch
->old_mode
= patch
->new_mode
= 0;
1453 patch
->old_name
= patch
->new_name
= NULL
;
1454 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1455 unsigned long nextlen
;
1457 len
= linelen(line
, size
);
1461 /* Testing this early allows us to take a few shortcuts.. */
1466 * Make sure we don't find any unconnected patch fragments.
1467 * That's a sign that we didn't find a header, and that a
1468 * patch has become corrupted/broken up.
1470 if (!memcmp("@@ -", line
, 4)) {
1471 struct fragment dummy
;
1472 if (parse_fragment_header(line
, len
, &dummy
) < 0)
1474 die(_("patch fragment without header at line %d: %.*s"),
1475 linenr
, (int)len
-1, line
);
1482 * Git patch? It might not have a real patch, just a rename
1483 * or mode change, so we handle that specially
1485 if (!memcmp("diff --git ", line
, 11)) {
1486 int git_hdr_len
= parse_git_header(line
, len
, size
, patch
);
1487 if (git_hdr_len
<= len
)
1489 if (!patch
->old_name
&& !patch
->new_name
) {
1490 if (!patch
->def_name
)
1491 die(Q_("git diff header lacks filename information when removing "
1492 "%d leading pathname component (line %d)",
1493 "git diff header lacks filename information when removing "
1494 "%d leading pathname components (line %d)",
1497 patch
->old_name
= xstrdup(patch
->def_name
);
1498 patch
->new_name
= xstrdup(patch
->def_name
);
1500 if (!patch
->is_delete
&& !patch
->new_name
)
1501 die("git diff header lacks filename information "
1502 "(line %d)", linenr
);
1503 patch
->is_toplevel_relative
= 1;
1504 *hdrsize
= git_hdr_len
;
1508 /* --- followed by +++ ? */
1509 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
1513 * We only accept unified patches, so we want it to
1514 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1515 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1517 nextlen
= linelen(line
+ len
, size
- len
);
1518 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
1521 /* Ok, we'll consider it a patch */
1522 parse_traditional_patch(line
, line
+len
, patch
);
1523 *hdrsize
= len
+ nextlen
;
1530 static void record_ws_error(unsigned result
, const char *line
, int len
, int linenr
)
1538 if (squelch_whitespace_errors
&&
1539 squelch_whitespace_errors
< whitespace_error
)
1542 err
= whitespace_error_string(result
);
1543 fprintf(stderr
, "%s:%d: %s.\n%.*s\n",
1544 patch_input_file
, linenr
, err
, len
, line
);
1548 static void check_whitespace(const char *line
, int len
, unsigned ws_rule
)
1550 unsigned result
= ws_check(line
+ 1, len
- 1, ws_rule
);
1552 record_ws_error(result
, line
+ 1, len
- 2, linenr
);
1556 * Parse a unified diff. Note that this really needs to parse each
1557 * fragment separately, since the only way to know the difference
1558 * between a "---" that is part of a patch, and a "---" that starts
1559 * the next patch is to look at the line counts..
1561 static int parse_fragment(const char *line
, unsigned long size
,
1562 struct patch
*patch
, struct fragment
*fragment
)
1565 int len
= linelen(line
, size
), offset
;
1566 unsigned long oldlines
, newlines
;
1567 unsigned long leading
, trailing
;
1569 offset
= parse_fragment_header(line
, len
, fragment
);
1572 if (offset
> 0 && patch
->recount
)
1573 recount_diff(line
+ offset
, size
- offset
, fragment
);
1574 oldlines
= fragment
->oldlines
;
1575 newlines
= fragment
->newlines
;
1579 /* Parse the thing.. */
1583 added
= deleted
= 0;
1586 offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1587 if (!oldlines
&& !newlines
)
1589 len
= linelen(line
, size
);
1590 if (!len
|| line
[len
-1] != '\n')
1595 case '\n': /* newer GNU diff, an empty context line */
1599 if (!deleted
&& !added
)
1604 if (apply_in_reverse
&&
1605 ws_error_action
!= nowarn_ws_error
)
1606 check_whitespace(line
, len
, patch
->ws_rule
);
1612 if (!apply_in_reverse
&&
1613 ws_error_action
!= nowarn_ws_error
)
1614 check_whitespace(line
, len
, patch
->ws_rule
);
1621 * We allow "\ No newline at end of file". Depending
1622 * on locale settings when the patch was produced we
1623 * don't know what this line looks like. The only
1624 * thing we do know is that it begins with "\ ".
1625 * Checking for 12 is just for sanity check -- any
1626 * l10n of "\ No newline..." is at least that long.
1629 if (len
< 12 || memcmp(line
, "\\ ", 2))
1634 if (oldlines
|| newlines
)
1636 fragment
->leading
= leading
;
1637 fragment
->trailing
= trailing
;
1640 * If a fragment ends with an incomplete line, we failed to include
1641 * it in the above loop because we hit oldlines == newlines == 0
1644 if (12 < size
&& !memcmp(line
, "\\ ", 2))
1645 offset
+= linelen(line
, size
);
1647 patch
->lines_added
+= added
;
1648 patch
->lines_deleted
+= deleted
;
1650 if (0 < patch
->is_new
&& oldlines
)
1651 return error(_("new file depends on old contents"));
1652 if (0 < patch
->is_delete
&& newlines
)
1653 return error(_("deleted file still has contents"));
1658 * We have seen "diff --git a/... b/..." header (or a traditional patch
1659 * header). Read hunks that belong to this patch into fragments and hang
1660 * them to the given patch structure.
1662 * The (fragment->patch, fragment->size) pair points into the memory given
1663 * by the caller, not a copy, when we return.
1665 static int parse_single_patch(const char *line
, unsigned long size
, struct patch
*patch
)
1667 unsigned long offset
= 0;
1668 unsigned long oldlines
= 0, newlines
= 0, context
= 0;
1669 struct fragment
**fragp
= &patch
->fragments
;
1671 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
1672 struct fragment
*fragment
;
1675 fragment
= xcalloc(1, sizeof(*fragment
));
1676 fragment
->linenr
= linenr
;
1677 len
= parse_fragment(line
, size
, patch
, fragment
);
1679 die(_("corrupt patch at line %d"), linenr
);
1680 fragment
->patch
= line
;
1681 fragment
->size
= len
;
1682 oldlines
+= fragment
->oldlines
;
1683 newlines
+= fragment
->newlines
;
1684 context
+= fragment
->leading
+ fragment
->trailing
;
1687 fragp
= &fragment
->next
;
1695 * If something was removed (i.e. we have old-lines) it cannot
1696 * be creation, and if something was added it cannot be
1697 * deletion. However, the reverse is not true; --unified=0
1698 * patches that only add are not necessarily creation even
1699 * though they do not have any old lines, and ones that only
1700 * delete are not necessarily deletion.
1702 * Unfortunately, a real creation/deletion patch do _not_ have
1703 * any context line by definition, so we cannot safely tell it
1704 * apart with --unified=0 insanity. At least if the patch has
1705 * more than one hunk it is not creation or deletion.
1707 if (patch
->is_new
< 0 &&
1708 (oldlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1710 if (patch
->is_delete
< 0 &&
1711 (newlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1712 patch
->is_delete
= 0;
1714 if (0 < patch
->is_new
&& oldlines
)
1715 die(_("new file %s depends on old contents"), patch
->new_name
);
1716 if (0 < patch
->is_delete
&& newlines
)
1717 die(_("deleted file %s still has contents"), patch
->old_name
);
1718 if (!patch
->is_delete
&& !newlines
&& context
)
1721 "file %s becomes empty but is not deleted"),
1727 static inline int metadata_changes(struct patch
*patch
)
1729 return patch
->is_rename
> 0 ||
1730 patch
->is_copy
> 0 ||
1731 patch
->is_new
> 0 ||
1733 (patch
->old_mode
&& patch
->new_mode
&&
1734 patch
->old_mode
!= patch
->new_mode
);
1737 static char *inflate_it(const void *data
, unsigned long size
,
1738 unsigned long inflated_size
)
1744 memset(&stream
, 0, sizeof(stream
));
1746 stream
.next_in
= (unsigned char *)data
;
1747 stream
.avail_in
= size
;
1748 stream
.next_out
= out
= xmalloc(inflated_size
);
1749 stream
.avail_out
= inflated_size
;
1750 git_inflate_init(&stream
);
1751 st
= git_inflate(&stream
, Z_FINISH
);
1752 git_inflate_end(&stream
);
1753 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1761 * Read a binary hunk and return a new fragment; fragment->patch
1762 * points at an allocated memory that the caller must free, so
1763 * it is marked as "->free_patch = 1".
1765 static struct fragment
*parse_binary_hunk(char **buf_p
,
1766 unsigned long *sz_p
,
1771 * Expect a line that begins with binary patch method ("literal"
1772 * or "delta"), followed by the length of data before deflating.
1773 * a sequence of 'length-byte' followed by base-85 encoded data
1774 * should follow, terminated by a newline.
1776 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1777 * and we would limit the patch line to 66 characters,
1778 * so one line can fit up to 13 groups that would decode
1779 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1780 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1783 unsigned long size
= *sz_p
;
1784 char *buffer
= *buf_p
;
1786 unsigned long origlen
;
1789 struct fragment
*frag
;
1791 llen
= linelen(buffer
, size
);
1796 if (starts_with(buffer
, "delta ")) {
1797 patch_method
= BINARY_DELTA_DEFLATED
;
1798 origlen
= strtoul(buffer
+ 6, NULL
, 10);
1800 else if (starts_with(buffer
, "literal ")) {
1801 patch_method
= BINARY_LITERAL_DEFLATED
;
1802 origlen
= strtoul(buffer
+ 8, NULL
, 10);
1810 int byte_length
, max_byte_length
, newsize
;
1811 llen
= linelen(buffer
, size
);
1815 /* consume the blank line */
1821 * Minimum line is "A00000\n" which is 7-byte long,
1822 * and the line length must be multiple of 5 plus 2.
1824 if ((llen
< 7) || (llen
-2) % 5)
1826 max_byte_length
= (llen
- 2) / 5 * 4;
1827 byte_length
= *buffer
;
1828 if ('A' <= byte_length
&& byte_length
<= 'Z')
1829 byte_length
= byte_length
- 'A' + 1;
1830 else if ('a' <= byte_length
&& byte_length
<= 'z')
1831 byte_length
= byte_length
- 'a' + 27;
1834 /* if the input length was not multiple of 4, we would
1835 * have filler at the end but the filler should never
1838 if (max_byte_length
< byte_length
||
1839 byte_length
<= max_byte_length
- 4)
1841 newsize
= hunk_size
+ byte_length
;
1842 data
= xrealloc(data
, newsize
);
1843 if (decode_85(data
+ hunk_size
, buffer
+ 1, byte_length
))
1845 hunk_size
= newsize
;
1850 frag
= xcalloc(1, sizeof(*frag
));
1851 frag
->patch
= inflate_it(data
, hunk_size
, origlen
);
1852 frag
->free_patch
= 1;
1856 frag
->size
= origlen
;
1860 frag
->binary_patch_method
= patch_method
;
1866 error(_("corrupt binary patch at line %d: %.*s"),
1867 linenr
-1, llen
-1, buffer
);
1871 static int parse_binary(char *buffer
, unsigned long size
, struct patch
*patch
)
1874 * We have read "GIT binary patch\n"; what follows is a line
1875 * that says the patch method (currently, either "literal" or
1876 * "delta") and the length of data before deflating; a
1877 * sequence of 'length-byte' followed by base-85 encoded data
1880 * When a binary patch is reversible, there is another binary
1881 * hunk in the same format, starting with patch method (either
1882 * "literal" or "delta") with the length of data, and a sequence
1883 * of length-byte + base-85 encoded data, terminated with another
1884 * empty line. This data, when applied to the postimage, produces
1887 struct fragment
*forward
;
1888 struct fragment
*reverse
;
1892 forward
= parse_binary_hunk(&buffer
, &size
, &status
, &used
);
1893 if (!forward
&& !status
)
1894 /* there has to be one hunk (forward hunk) */
1895 return error(_("unrecognized binary patch at line %d"), linenr
-1);
1897 /* otherwise we already gave an error message */
1900 reverse
= parse_binary_hunk(&buffer
, &size
, &status
, &used_1
);
1905 * Not having reverse hunk is not an error, but having
1906 * a corrupt reverse hunk is.
1908 free((void*) forward
->patch
);
1912 forward
->next
= reverse
;
1913 patch
->fragments
= forward
;
1914 patch
->is_binary
= 1;
1918 static void prefix_one(char **name
)
1920 char *old_name
= *name
;
1923 *name
= xstrdup(prefix_filename(prefix
, prefix_length
, *name
));
1927 static void prefix_patch(struct patch
*p
)
1929 if (!prefix
|| p
->is_toplevel_relative
)
1931 prefix_one(&p
->new_name
);
1932 prefix_one(&p
->old_name
);
1939 static struct string_list limit_by_name
;
1940 static int has_include
;
1941 static void add_name_limit(const char *name
, int exclude
)
1943 struct string_list_item
*it
;
1945 it
= string_list_append(&limit_by_name
, name
);
1946 it
->util
= exclude
? NULL
: (void *) 1;
1949 static int use_patch(struct patch
*p
)
1951 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
1954 /* Paths outside are not touched regardless of "--include" */
1955 if (0 < prefix_length
) {
1956 int pathlen
= strlen(pathname
);
1957 if (pathlen
<= prefix_length
||
1958 memcmp(prefix
, pathname
, prefix_length
))
1962 /* See if it matches any of exclude/include rule */
1963 for (i
= 0; i
< limit_by_name
.nr
; i
++) {
1964 struct string_list_item
*it
= &limit_by_name
.items
[i
];
1965 if (!wildmatch(it
->string
, pathname
, 0, NULL
))
1966 return (it
->util
!= NULL
);
1970 * If we had any include, a path that does not match any rule is
1971 * not used. Otherwise, we saw bunch of exclude rules (or none)
1972 * and such a path is used.
1974 return !has_include
;
1979 * Read the patch text in "buffer" that extends for "size" bytes; stop
1980 * reading after seeing a single patch (i.e. changes to a single file).
1981 * Create fragments (i.e. patch hunks) and hang them to the given patch.
1982 * Return the number of bytes consumed, so that the caller can call us
1983 * again for the next patch.
1985 static int parse_chunk(char *buffer
, unsigned long size
, struct patch
*patch
)
1987 int hdrsize
, patchsize
;
1988 int offset
= find_header(buffer
, size
, &hdrsize
, patch
);
1993 prefix_patch(patch
);
1995 if (!use_patch(patch
))
1998 patch
->ws_rule
= whitespace_rule(patch
->new_name
2002 patchsize
= parse_single_patch(buffer
+ offset
+ hdrsize
,
2003 size
- offset
- hdrsize
, patch
);
2006 static const char git_binary
[] = "GIT binary patch\n";
2007 int hd
= hdrsize
+ offset
;
2008 unsigned long llen
= linelen(buffer
+ hd
, size
- hd
);
2010 if (llen
== sizeof(git_binary
) - 1 &&
2011 !memcmp(git_binary
, buffer
+ hd
, llen
)) {
2014 used
= parse_binary(buffer
+ hd
+ llen
,
2015 size
- hd
- llen
, patch
);
2017 patchsize
= used
+ llen
;
2021 else if (!memcmp(" differ\n", buffer
+ hd
+ llen
- 8, 8)) {
2022 static const char *binhdr
[] = {
2028 for (i
= 0; binhdr
[i
]; i
++) {
2029 int len
= strlen(binhdr
[i
]);
2030 if (len
< size
- hd
&&
2031 !memcmp(binhdr
[i
], buffer
+ hd
, len
)) {
2033 patch
->is_binary
= 1;
2040 /* Empty patch cannot be applied if it is a text patch
2041 * without metadata change. A binary patch appears
2044 if ((apply
|| check
) &&
2045 (!patch
->is_binary
&& !metadata_changes(patch
)))
2046 die(_("patch with only garbage at line %d"), linenr
);
2049 return offset
+ hdrsize
+ patchsize
;
2052 #define swap(a,b) myswap((a),(b),sizeof(a))
2054 #define myswap(a, b, size) do { \
2055 unsigned char mytmp[size]; \
2056 memcpy(mytmp, &a, size); \
2057 memcpy(&a, &b, size); \
2058 memcpy(&b, mytmp, size); \
2061 static void reverse_patches(struct patch
*p
)
2063 for (; p
; p
= p
->next
) {
2064 struct fragment
*frag
= p
->fragments
;
2066 swap(p
->new_name
, p
->old_name
);
2067 swap(p
->new_mode
, p
->old_mode
);
2068 swap(p
->is_new
, p
->is_delete
);
2069 swap(p
->lines_added
, p
->lines_deleted
);
2070 swap(p
->old_sha1_prefix
, p
->new_sha1_prefix
);
2072 for (; frag
; frag
= frag
->next
) {
2073 swap(frag
->newpos
, frag
->oldpos
);
2074 swap(frag
->newlines
, frag
->oldlines
);
2079 static const char pluses
[] =
2080 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2081 static const char minuses
[]=
2082 "----------------------------------------------------------------------";
2084 static void show_stats(struct patch
*patch
)
2086 struct strbuf qname
= STRBUF_INIT
;
2087 char *cp
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
2090 quote_c_style(cp
, &qname
, NULL
, 0);
2093 * "scale" the filename
2099 if (qname
.len
> max
) {
2100 cp
= strchr(qname
.buf
+ qname
.len
+ 3 - max
, '/');
2102 cp
= qname
.buf
+ qname
.len
+ 3 - max
;
2103 strbuf_splice(&qname
, 0, cp
- qname
.buf
, "...", 3);
2106 if (patch
->is_binary
) {
2107 printf(" %-*s | Bin\n", max
, qname
.buf
);
2108 strbuf_release(&qname
);
2112 printf(" %-*s |", max
, qname
.buf
);
2113 strbuf_release(&qname
);
2116 * scale the add/delete
2118 max
= max
+ max_change
> 70 ? 70 - max
: max_change
;
2119 add
= patch
->lines_added
;
2120 del
= patch
->lines_deleted
;
2122 if (max_change
> 0) {
2123 int total
= ((add
+ del
) * max
+ max_change
/ 2) / max_change
;
2124 add
= (add
* max
+ max_change
/ 2) / max_change
;
2127 printf("%5d %.*s%.*s\n", patch
->lines_added
+ patch
->lines_deleted
,
2128 add
, pluses
, del
, minuses
);
2131 static int read_old_data(struct stat
*st
, const char *path
, struct strbuf
*buf
)
2133 switch (st
->st_mode
& S_IFMT
) {
2135 if (strbuf_readlink(buf
, path
, st
->st_size
) < 0)
2136 return error(_("unable to read symlink %s"), path
);
2139 if (strbuf_read_file(buf
, path
, st
->st_size
) != st
->st_size
)
2140 return error(_("unable to open or read %s"), path
);
2141 convert_to_git(path
, buf
->buf
, buf
->len
, buf
, 0);
2149 * Update the preimage, and the common lines in postimage,
2150 * from buffer buf of length len. If postlen is 0 the postimage
2151 * is updated in place, otherwise it's updated on a new buffer
2155 static void update_pre_post_images(struct image
*preimage
,
2156 struct image
*postimage
,
2158 size_t len
, size_t postlen
)
2160 int i
, ctx
, reduced
;
2161 char *new, *old
, *fixed
;
2162 struct image fixed_preimage
;
2165 * Update the preimage with whitespace fixes. Note that we
2166 * are not losing preimage->buf -- apply_one_fragment() will
2169 prepare_image(&fixed_preimage
, buf
, len
, 1);
2171 ? fixed_preimage
.nr
== preimage
->nr
2172 : fixed_preimage
.nr
<= preimage
->nr
);
2173 for (i
= 0; i
< fixed_preimage
.nr
; i
++)
2174 fixed_preimage
.line
[i
].flag
= preimage
->line
[i
].flag
;
2175 free(preimage
->line_allocated
);
2176 *preimage
= fixed_preimage
;
2179 * Adjust the common context lines in postimage. This can be
2180 * done in-place when we are shrinking it with whitespace
2181 * fixing, but needs a new buffer when ignoring whitespace or
2182 * expanding leading tabs to spaces.
2184 * We trust the caller to tell us if the update can be done
2185 * in place (postlen==0) or not.
2187 old
= postimage
->buf
;
2189 new = postimage
->buf
= xmalloc(postlen
);
2192 fixed
= preimage
->buf
;
2194 for (i
= reduced
= ctx
= 0; i
< postimage
->nr
; i
++) {
2195 size_t len
= postimage
->line
[i
].len
;
2196 if (!(postimage
->line
[i
].flag
& LINE_COMMON
)) {
2197 /* an added line -- no counterparts in preimage */
2198 memmove(new, old
, len
);
2204 /* a common context -- skip it in the original postimage */
2207 /* and find the corresponding one in the fixed preimage */
2208 while (ctx
< preimage
->nr
&&
2209 !(preimage
->line
[ctx
].flag
& LINE_COMMON
)) {
2210 fixed
+= preimage
->line
[ctx
].len
;
2215 * preimage is expected to run out, if the caller
2216 * fixed addition of trailing blank lines.
2218 if (preimage
->nr
<= ctx
) {
2223 /* and copy it in, while fixing the line length */
2224 len
= preimage
->line
[ctx
].len
;
2225 memcpy(new, fixed
, len
);
2228 postimage
->line
[i
].len
= len
;
2232 /* Fix the length of the whole thing */
2233 postimage
->len
= new - postimage
->buf
;
2234 postimage
->nr
-= reduced
;
2237 static int match_fragment(struct image
*img
,
2238 struct image
*preimage
,
2239 struct image
*postimage
,
2243 int match_beginning
, int match_end
)
2246 char *fixed_buf
, *buf
, *orig
, *target
;
2247 struct strbuf fixed
;
2248 size_t fixed_len
, postlen
;
2251 if (preimage
->nr
+ try_lno
<= img
->nr
) {
2253 * The hunk falls within the boundaries of img.
2255 preimage_limit
= preimage
->nr
;
2256 if (match_end
&& (preimage
->nr
+ try_lno
!= img
->nr
))
2258 } else if (ws_error_action
== correct_ws_error
&&
2259 (ws_rule
& WS_BLANK_AT_EOF
)) {
2261 * This hunk extends beyond the end of img, and we are
2262 * removing blank lines at the end of the file. This
2263 * many lines from the beginning of the preimage must
2264 * match with img, and the remainder of the preimage
2267 preimage_limit
= img
->nr
- try_lno
;
2270 * The hunk extends beyond the end of the img and
2271 * we are not removing blanks at the end, so we
2272 * should reject the hunk at this position.
2277 if (match_beginning
&& try_lno
)
2280 /* Quick hash check */
2281 for (i
= 0; i
< preimage_limit
; i
++)
2282 if ((img
->line
[try_lno
+ i
].flag
& LINE_PATCHED
) ||
2283 (preimage
->line
[i
].hash
!= img
->line
[try_lno
+ i
].hash
))
2286 if (preimage_limit
== preimage
->nr
) {
2288 * Do we have an exact match? If we were told to match
2289 * at the end, size must be exactly at try+fragsize,
2290 * otherwise try+fragsize must be still within the preimage,
2291 * and either case, the old piece should match the preimage
2295 ? (try + preimage
->len
== img
->len
)
2296 : (try + preimage
->len
<= img
->len
)) &&
2297 !memcmp(img
->buf
+ try, preimage
->buf
, preimage
->len
))
2301 * The preimage extends beyond the end of img, so
2302 * there cannot be an exact match.
2304 * There must be one non-blank context line that match
2305 * a line before the end of img.
2309 buf
= preimage
->buf
;
2311 for (i
= 0; i
< preimage_limit
; i
++)
2312 buf_end
+= preimage
->line
[i
].len
;
2314 for ( ; buf
< buf_end
; buf
++)
2322 * No exact match. If we are ignoring whitespace, run a line-by-line
2323 * fuzzy matching. We collect all the line length information because
2324 * we need it to adjust whitespace if we match.
2326 if (ws_ignore_action
== ignore_ws_change
) {
2329 size_t postlen
= postimage
->len
;
2333 for (i
= 0; i
< preimage_limit
; i
++) {
2334 size_t prelen
= preimage
->line
[i
].len
;
2335 size_t imglen
= img
->line
[try_lno
+i
].len
;
2337 if (!fuzzy_matchlines(img
->buf
+ try + imgoff
, imglen
,
2338 preimage
->buf
+ preoff
, prelen
))
2340 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2341 postlen
+= imglen
- prelen
;
2347 * Ok, the preimage matches with whitespace fuzz.
2349 * imgoff now holds the true length of the target that
2350 * matches the preimage before the end of the file.
2352 * Count the number of characters in the preimage that fall
2353 * beyond the end of the file and make sure that all of them
2354 * are whitespace characters. (This can only happen if
2355 * we are removing blank lines at the end of the file.)
2357 buf
= preimage_eof
= preimage
->buf
+ preoff
;
2358 for ( ; i
< preimage
->nr
; i
++)
2359 preoff
+= preimage
->line
[i
].len
;
2360 preimage_end
= preimage
->buf
+ preoff
;
2361 for ( ; buf
< preimage_end
; buf
++)
2366 * Update the preimage and the common postimage context
2367 * lines to use the same whitespace as the target.
2368 * If whitespace is missing in the target (i.e.
2369 * if the preimage extends beyond the end of the file),
2370 * use the whitespace from the preimage.
2372 extra_chars
= preimage_end
- preimage_eof
;
2373 strbuf_init(&fixed
, imgoff
+ extra_chars
);
2374 strbuf_add(&fixed
, img
->buf
+ try, imgoff
);
2375 strbuf_add(&fixed
, preimage_eof
, extra_chars
);
2376 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2377 update_pre_post_images(preimage
, postimage
,
2378 fixed_buf
, fixed_len
, postlen
);
2382 if (ws_error_action
!= correct_ws_error
)
2386 * The hunk does not apply byte-by-byte, but the hash says
2387 * it might with whitespace fuzz. We haven't been asked to
2388 * ignore whitespace, we were asked to correct whitespace
2389 * errors, so let's try matching after whitespace correction.
2391 * The preimage may extend beyond the end of the file,
2392 * but in this loop we will only handle the part of the
2393 * preimage that falls within the file.
2395 strbuf_init(&fixed
, preimage
->len
+ 1);
2396 orig
= preimage
->buf
;
2397 target
= img
->buf
+ try;
2399 for (i
= 0; i
< preimage_limit
; i
++) {
2400 size_t oldlen
= preimage
->line
[i
].len
;
2401 size_t tgtlen
= img
->line
[try_lno
+ i
].len
;
2402 size_t fixstart
= fixed
.len
;
2403 struct strbuf tgtfix
;
2406 /* Try fixing the line in the preimage */
2407 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2409 /* Try fixing the line in the target */
2410 strbuf_init(&tgtfix
, tgtlen
);
2411 ws_fix_copy(&tgtfix
, target
, tgtlen
, ws_rule
, NULL
);
2414 * If they match, either the preimage was based on
2415 * a version before our tree fixed whitespace breakage,
2416 * or we are lacking a whitespace-fix patch the tree
2417 * the preimage was based on already had (i.e. target
2418 * has whitespace breakage, the preimage doesn't).
2419 * In either case, we are fixing the whitespace breakages
2420 * so we might as well take the fix together with their
2423 match
= (tgtfix
.len
== fixed
.len
- fixstart
&&
2424 !memcmp(tgtfix
.buf
, fixed
.buf
+ fixstart
,
2425 fixed
.len
- fixstart
));
2426 postlen
+= tgtfix
.len
;
2428 strbuf_release(&tgtfix
);
2438 * Now handle the lines in the preimage that falls beyond the
2439 * end of the file (if any). They will only match if they are
2440 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2443 for ( ; i
< preimage
->nr
; i
++) {
2444 size_t fixstart
= fixed
.len
; /* start of the fixed preimage */
2445 size_t oldlen
= preimage
->line
[i
].len
;
2448 /* Try fixing the line in the preimage */
2449 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2451 for (j
= fixstart
; j
< fixed
.len
; j
++)
2452 if (!isspace(fixed
.buf
[j
]))
2459 * Yes, the preimage is based on an older version that still
2460 * has whitespace breakages unfixed, and fixing them makes the
2461 * hunk match. Update the context lines in the postimage.
2463 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2464 if (postlen
< postimage
->len
)
2466 update_pre_post_images(preimage
, postimage
,
2467 fixed_buf
, fixed_len
, postlen
);
2471 strbuf_release(&fixed
);
2475 static int find_pos(struct image
*img
,
2476 struct image
*preimage
,
2477 struct image
*postimage
,
2480 int match_beginning
, int match_end
)
2483 unsigned long backwards
, forwards
, try;
2484 int backwards_lno
, forwards_lno
, try_lno
;
2487 * If match_beginning or match_end is specified, there is no
2488 * point starting from a wrong line that will never match and
2489 * wander around and wait for a match at the specified end.
2491 if (match_beginning
)
2494 line
= img
->nr
- preimage
->nr
;
2497 * Because the comparison is unsigned, the following test
2498 * will also take care of a negative line number that can
2499 * result when match_end and preimage is larger than the target.
2501 if ((size_t) line
> img
->nr
)
2505 for (i
= 0; i
< line
; i
++)
2506 try += img
->line
[i
].len
;
2509 * There's probably some smart way to do this, but I'll leave
2510 * that to the smart and beautiful people. I'm simple and stupid.
2513 backwards_lno
= line
;
2515 forwards_lno
= line
;
2518 for (i
= 0; ; i
++) {
2519 if (match_fragment(img
, preimage
, postimage
,
2520 try, try_lno
, ws_rule
,
2521 match_beginning
, match_end
))
2525 if (backwards_lno
== 0 && forwards_lno
== img
->nr
)
2529 if (backwards_lno
== 0) {
2534 backwards
-= img
->line
[backwards_lno
].len
;
2536 try_lno
= backwards_lno
;
2538 if (forwards_lno
== img
->nr
) {
2542 forwards
+= img
->line
[forwards_lno
].len
;
2545 try_lno
= forwards_lno
;
2552 static void remove_first_line(struct image
*img
)
2554 img
->buf
+= img
->line
[0].len
;
2555 img
->len
-= img
->line
[0].len
;
2560 static void remove_last_line(struct image
*img
)
2562 img
->len
-= img
->line
[--img
->nr
].len
;
2566 * The change from "preimage" and "postimage" has been found to
2567 * apply at applied_pos (counts in line numbers) in "img".
2568 * Update "img" to remove "preimage" and replace it with "postimage".
2570 static void update_image(struct image
*img
,
2572 struct image
*preimage
,
2573 struct image
*postimage
)
2576 * remove the copy of preimage at offset in img
2577 * and replace it with postimage
2580 size_t remove_count
, insert_count
, applied_at
= 0;
2585 * If we are removing blank lines at the end of img,
2586 * the preimage may extend beyond the end.
2587 * If that is the case, we must be careful only to
2588 * remove the part of the preimage that falls within
2589 * the boundaries of img. Initialize preimage_limit
2590 * to the number of lines in the preimage that falls
2591 * within the boundaries.
2593 preimage_limit
= preimage
->nr
;
2594 if (preimage_limit
> img
->nr
- applied_pos
)
2595 preimage_limit
= img
->nr
- applied_pos
;
2597 for (i
= 0; i
< applied_pos
; i
++)
2598 applied_at
+= img
->line
[i
].len
;
2601 for (i
= 0; i
< preimage_limit
; i
++)
2602 remove_count
+= img
->line
[applied_pos
+ i
].len
;
2603 insert_count
= postimage
->len
;
2605 /* Adjust the contents */
2606 result
= xmalloc(img
->len
+ insert_count
- remove_count
+ 1);
2607 memcpy(result
, img
->buf
, applied_at
);
2608 memcpy(result
+ applied_at
, postimage
->buf
, postimage
->len
);
2609 memcpy(result
+ applied_at
+ postimage
->len
,
2610 img
->buf
+ (applied_at
+ remove_count
),
2611 img
->len
- (applied_at
+ remove_count
));
2614 img
->len
+= insert_count
- remove_count
;
2615 result
[img
->len
] = '\0';
2617 /* Adjust the line table */
2618 nr
= img
->nr
+ postimage
->nr
- preimage_limit
;
2619 if (preimage_limit
< postimage
->nr
) {
2621 * NOTE: this knows that we never call remove_first_line()
2622 * on anything other than pre/post image.
2624 REALLOC_ARRAY(img
->line
, nr
);
2625 img
->line_allocated
= img
->line
;
2627 if (preimage_limit
!= postimage
->nr
)
2628 memmove(img
->line
+ applied_pos
+ postimage
->nr
,
2629 img
->line
+ applied_pos
+ preimage_limit
,
2630 (img
->nr
- (applied_pos
+ preimage_limit
)) *
2631 sizeof(*img
->line
));
2632 memcpy(img
->line
+ applied_pos
,
2634 postimage
->nr
* sizeof(*img
->line
));
2636 for (i
= 0; i
< postimage
->nr
; i
++)
2637 img
->line
[applied_pos
+ i
].flag
|= LINE_PATCHED
;
2642 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2643 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2644 * replace the part of "img" with "postimage" text.
2646 static int apply_one_fragment(struct image
*img
, struct fragment
*frag
,
2647 int inaccurate_eof
, unsigned ws_rule
,
2650 int match_beginning
, match_end
;
2651 const char *patch
= frag
->patch
;
2652 int size
= frag
->size
;
2653 char *old
, *oldlines
;
2654 struct strbuf newlines
;
2655 int new_blank_lines_at_end
= 0;
2656 int found_new_blank_lines_at_end
= 0;
2657 int hunk_linenr
= frag
->linenr
;
2658 unsigned long leading
, trailing
;
2659 int pos
, applied_pos
;
2660 struct image preimage
;
2661 struct image postimage
;
2663 memset(&preimage
, 0, sizeof(preimage
));
2664 memset(&postimage
, 0, sizeof(postimage
));
2665 oldlines
= xmalloc(size
);
2666 strbuf_init(&newlines
, size
);
2671 int len
= linelen(patch
, size
);
2673 int added_blank_line
= 0;
2674 int is_blank_context
= 0;
2681 * "plen" is how much of the line we should use for
2682 * the actual patch data. Normally we just remove the
2683 * first character on the line, but if the line is
2684 * followed by "\ No newline", then we also remove the
2685 * last one (which is the newline, of course).
2688 if (len
< size
&& patch
[len
] == '\\')
2691 if (apply_in_reverse
) {
2694 else if (first
== '+')
2700 /* Newer GNU diff, empty context line */
2702 /* ... followed by '\No newline'; nothing */
2705 strbuf_addch(&newlines
, '\n');
2706 add_line_info(&preimage
, "\n", 1, LINE_COMMON
);
2707 add_line_info(&postimage
, "\n", 1, LINE_COMMON
);
2708 is_blank_context
= 1;
2711 if (plen
&& (ws_rule
& WS_BLANK_AT_EOF
) &&
2712 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2713 is_blank_context
= 1;
2715 memcpy(old
, patch
+ 1, plen
);
2716 add_line_info(&preimage
, old
, plen
,
2717 (first
== ' ' ? LINE_COMMON
: 0));
2721 /* Fall-through for ' ' */
2723 /* --no-add does not add new lines */
2724 if (first
== '+' && no_add
)
2727 start
= newlines
.len
;
2729 !whitespace_error
||
2730 ws_error_action
!= correct_ws_error
) {
2731 strbuf_add(&newlines
, patch
+ 1, plen
);
2734 ws_fix_copy(&newlines
, patch
+ 1, plen
, ws_rule
, &applied_after_fixing_ws
);
2736 add_line_info(&postimage
, newlines
.buf
+ start
, newlines
.len
- start
,
2737 (first
== '+' ? 0 : LINE_COMMON
));
2739 (ws_rule
& WS_BLANK_AT_EOF
) &&
2740 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2741 added_blank_line
= 1;
2743 case '@': case '\\':
2744 /* Ignore it, we already handled it */
2747 if (apply_verbosely
)
2748 error(_("invalid start of line: '%c'"), first
);
2751 if (added_blank_line
) {
2752 if (!new_blank_lines_at_end
)
2753 found_new_blank_lines_at_end
= hunk_linenr
;
2754 new_blank_lines_at_end
++;
2756 else if (is_blank_context
)
2759 new_blank_lines_at_end
= 0;
2764 if (inaccurate_eof
&&
2765 old
> oldlines
&& old
[-1] == '\n' &&
2766 newlines
.len
> 0 && newlines
.buf
[newlines
.len
- 1] == '\n') {
2768 strbuf_setlen(&newlines
, newlines
.len
- 1);
2771 leading
= frag
->leading
;
2772 trailing
= frag
->trailing
;
2775 * A hunk to change lines at the beginning would begin with
2777 * but we need to be careful. -U0 that inserts before the second
2778 * line also has this pattern.
2780 * And a hunk to add to an empty file would begin with
2783 * In other words, a hunk that is (frag->oldpos <= 1) with or
2784 * without leading context must match at the beginning.
2786 match_beginning
= (!frag
->oldpos
||
2787 (frag
->oldpos
== 1 && !unidiff_zero
));
2790 * A hunk without trailing lines must match at the end.
2791 * However, we simply cannot tell if a hunk must match end
2792 * from the lack of trailing lines if the patch was generated
2793 * with unidiff without any context.
2795 match_end
= !unidiff_zero
&& !trailing
;
2797 pos
= frag
->newpos
? (frag
->newpos
- 1) : 0;
2798 preimage
.buf
= oldlines
;
2799 preimage
.len
= old
- oldlines
;
2800 postimage
.buf
= newlines
.buf
;
2801 postimage
.len
= newlines
.len
;
2802 preimage
.line
= preimage
.line_allocated
;
2803 postimage
.line
= postimage
.line_allocated
;
2807 applied_pos
= find_pos(img
, &preimage
, &postimage
, pos
,
2808 ws_rule
, match_beginning
, match_end
);
2810 if (applied_pos
>= 0)
2813 /* Am I at my context limits? */
2814 if ((leading
<= p_context
) && (trailing
<= p_context
))
2816 if (match_beginning
|| match_end
) {
2817 match_beginning
= match_end
= 0;
2822 * Reduce the number of context lines; reduce both
2823 * leading and trailing if they are equal otherwise
2824 * just reduce the larger context.
2826 if (leading
>= trailing
) {
2827 remove_first_line(&preimage
);
2828 remove_first_line(&postimage
);
2832 if (trailing
> leading
) {
2833 remove_last_line(&preimage
);
2834 remove_last_line(&postimage
);
2839 if (applied_pos
>= 0) {
2840 if (new_blank_lines_at_end
&&
2841 preimage
.nr
+ applied_pos
>= img
->nr
&&
2842 (ws_rule
& WS_BLANK_AT_EOF
) &&
2843 ws_error_action
!= nowarn_ws_error
) {
2844 record_ws_error(WS_BLANK_AT_EOF
, "+", 1,
2845 found_new_blank_lines_at_end
);
2846 if (ws_error_action
== correct_ws_error
) {
2847 while (new_blank_lines_at_end
--)
2848 remove_last_line(&postimage
);
2851 * We would want to prevent write_out_results()
2852 * from taking place in apply_patch() that follows
2853 * the callchain led us here, which is:
2854 * apply_patch->check_patch_list->check_patch->
2855 * apply_data->apply_fragments->apply_one_fragment
2857 if (ws_error_action
== die_on_ws_error
)
2861 if (apply_verbosely
&& applied_pos
!= pos
) {
2862 int offset
= applied_pos
- pos
;
2863 if (apply_in_reverse
)
2864 offset
= 0 - offset
;
2866 Q_("Hunk #%d succeeded at %d (offset %d line).",
2867 "Hunk #%d succeeded at %d (offset %d lines).",
2869 nth_fragment
, applied_pos
+ 1, offset
);
2873 * Warn if it was necessary to reduce the number
2876 if ((leading
!= frag
->leading
) ||
2877 (trailing
!= frag
->trailing
))
2878 fprintf_ln(stderr
, _("Context reduced to (%ld/%ld)"
2879 " to apply fragment at %d"),
2880 leading
, trailing
, applied_pos
+1);
2881 update_image(img
, applied_pos
, &preimage
, &postimage
);
2883 if (apply_verbosely
)
2884 error(_("while searching for:\n%.*s"),
2885 (int)(old
- oldlines
), oldlines
);
2889 strbuf_release(&newlines
);
2890 free(preimage
.line_allocated
);
2891 free(postimage
.line_allocated
);
2893 return (applied_pos
< 0);
2896 static int apply_binary_fragment(struct image
*img
, struct patch
*patch
)
2898 struct fragment
*fragment
= patch
->fragments
;
2903 return error(_("missing binary patch data for '%s'"),
2908 /* Binary patch is irreversible without the optional second hunk */
2909 if (apply_in_reverse
) {
2910 if (!fragment
->next
)
2911 return error("cannot reverse-apply a binary patch "
2912 "without the reverse hunk to '%s'",
2914 ? patch
->new_name
: patch
->old_name
);
2915 fragment
= fragment
->next
;
2917 switch (fragment
->binary_patch_method
) {
2918 case BINARY_DELTA_DEFLATED
:
2919 dst
= patch_delta(img
->buf
, img
->len
, fragment
->patch
,
2920 fragment
->size
, &len
);
2927 case BINARY_LITERAL_DEFLATED
:
2929 img
->len
= fragment
->size
;
2930 img
->buf
= xmemdupz(fragment
->patch
, img
->len
);
2937 * Replace "img" with the result of applying the binary patch.
2938 * The binary patch data itself in patch->fragment is still kept
2939 * but the preimage prepared by the caller in "img" is freed here
2940 * or in the helper function apply_binary_fragment() this calls.
2942 static int apply_binary(struct image
*img
, struct patch
*patch
)
2944 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
2945 unsigned char sha1
[20];
2948 * For safety, we require patch index line to contain
2949 * full 40-byte textual SHA1 for old and new, at least for now.
2951 if (strlen(patch
->old_sha1_prefix
) != 40 ||
2952 strlen(patch
->new_sha1_prefix
) != 40 ||
2953 get_sha1_hex(patch
->old_sha1_prefix
, sha1
) ||
2954 get_sha1_hex(patch
->new_sha1_prefix
, sha1
))
2955 return error("cannot apply binary patch to '%s' "
2956 "without full index line", name
);
2958 if (patch
->old_name
) {
2960 * See if the old one matches what the patch
2963 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
2964 if (strcmp(sha1_to_hex(sha1
), patch
->old_sha1_prefix
))
2965 return error("the patch applies to '%s' (%s), "
2966 "which does not match the "
2967 "current contents.",
2968 name
, sha1_to_hex(sha1
));
2971 /* Otherwise, the old one must be empty. */
2973 return error("the patch applies to an empty "
2974 "'%s' but it is not empty", name
);
2977 get_sha1_hex(patch
->new_sha1_prefix
, sha1
);
2978 if (is_null_sha1(sha1
)) {
2980 return 0; /* deletion patch */
2983 if (has_sha1_file(sha1
)) {
2984 /* We already have the postimage */
2985 enum object_type type
;
2989 result
= read_sha1_file(sha1
, &type
, &size
);
2991 return error("the necessary postimage %s for "
2992 "'%s' cannot be read",
2993 patch
->new_sha1_prefix
, name
);
2999 * We have verified buf matches the preimage;
3000 * apply the patch data to it, which is stored
3001 * in the patch->fragments->{patch,size}.
3003 if (apply_binary_fragment(img
, patch
))
3004 return error(_("binary patch does not apply to '%s'"),
3007 /* verify that the result matches */
3008 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
3009 if (strcmp(sha1_to_hex(sha1
), patch
->new_sha1_prefix
))
3010 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3011 name
, patch
->new_sha1_prefix
, sha1_to_hex(sha1
));
3017 static int apply_fragments(struct image
*img
, struct patch
*patch
)
3019 struct fragment
*frag
= patch
->fragments
;
3020 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3021 unsigned ws_rule
= patch
->ws_rule
;
3022 unsigned inaccurate_eof
= patch
->inaccurate_eof
;
3025 if (patch
->is_binary
)
3026 return apply_binary(img
, patch
);
3030 if (apply_one_fragment(img
, frag
, inaccurate_eof
, ws_rule
, nth
)) {
3031 error(_("patch failed: %s:%ld"), name
, frag
->oldpos
);
3032 if (!apply_with_reject
)
3041 static int read_blob_object(struct strbuf
*buf
, const unsigned char *sha1
, unsigned mode
)
3043 if (S_ISGITLINK(mode
)) {
3044 strbuf_grow(buf
, 100);
3045 strbuf_addf(buf
, "Subproject commit %s\n", sha1_to_hex(sha1
));
3047 enum object_type type
;
3051 result
= read_sha1_file(sha1
, &type
, &sz
);
3054 /* XXX read_sha1_file NUL-terminates */
3055 strbuf_attach(buf
, result
, sz
, sz
+ 1);
3060 static int read_file_or_gitlink(const struct cache_entry
*ce
, struct strbuf
*buf
)
3064 return read_blob_object(buf
, ce
->sha1
, ce
->ce_mode
);
3067 static struct patch
*in_fn_table(const char *name
)
3069 struct string_list_item
*item
;
3074 item
= string_list_lookup(&fn_table
, name
);
3076 return (struct patch
*)item
->util
;
3082 * item->util in the filename table records the status of the path.
3083 * Usually it points at a patch (whose result records the contents
3084 * of it after applying it), but it could be PATH_WAS_DELETED for a
3085 * path that a previously applied patch has already removed, or
3086 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3088 * The latter is needed to deal with a case where two paths A and B
3089 * are swapped by first renaming A to B and then renaming B to A;
3090 * moving A to B should not be prevented due to presence of B as we
3091 * will remove it in a later patch.
3093 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3094 #define PATH_WAS_DELETED ((struct patch *) -1)
3096 static int to_be_deleted(struct patch
*patch
)
3098 return patch
== PATH_TO_BE_DELETED
;
3101 static int was_deleted(struct patch
*patch
)
3103 return patch
== PATH_WAS_DELETED
;
3106 static void add_to_fn_table(struct patch
*patch
)
3108 struct string_list_item
*item
;
3111 * Always add new_name unless patch is a deletion
3112 * This should cover the cases for normal diffs,
3113 * file creations and copies
3115 if (patch
->new_name
!= NULL
) {
3116 item
= string_list_insert(&fn_table
, patch
->new_name
);
3121 * store a failure on rename/deletion cases because
3122 * later chunks shouldn't patch old names
3124 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3125 item
= string_list_insert(&fn_table
, patch
->old_name
);
3126 item
->util
= PATH_WAS_DELETED
;
3130 static void prepare_fn_table(struct patch
*patch
)
3133 * store information about incoming file deletion
3136 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3137 struct string_list_item
*item
;
3138 item
= string_list_insert(&fn_table
, patch
->old_name
);
3139 item
->util
= PATH_TO_BE_DELETED
;
3141 patch
= patch
->next
;
3145 static int checkout_target(struct index_state
*istate
,
3146 struct cache_entry
*ce
, struct stat
*st
)
3148 struct checkout costate
;
3150 memset(&costate
, 0, sizeof(costate
));
3151 costate
.base_dir
= "";
3152 costate
.refresh_cache
= 1;
3153 costate
.istate
= istate
;
3154 if (checkout_entry(ce
, &costate
, NULL
) || lstat(ce
->name
, st
))
3155 return error(_("cannot checkout %s"), ce
->name
);
3159 static struct patch
*previous_patch(struct patch
*patch
, int *gone
)
3161 struct patch
*previous
;
3164 if (patch
->is_copy
|| patch
->is_rename
)
3165 return NULL
; /* "git" patches do not depend on the order */
3167 previous
= in_fn_table(patch
->old_name
);
3171 if (to_be_deleted(previous
))
3172 return NULL
; /* the deletion hasn't happened yet */
3174 if (was_deleted(previous
))
3180 static int verify_index_match(const struct cache_entry
*ce
, struct stat
*st
)
3182 if (S_ISGITLINK(ce
->ce_mode
)) {
3183 if (!S_ISDIR(st
->st_mode
))
3187 return ce_match_stat(ce
, st
, CE_MATCH_IGNORE_VALID
|CE_MATCH_IGNORE_SKIP_WORKTREE
);
3190 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3192 static int load_patch_target(struct strbuf
*buf
,
3193 const struct cache_entry
*ce
,
3196 unsigned expected_mode
)
3199 if (read_file_or_gitlink(ce
, buf
))
3200 return error(_("read of %s failed"), name
);
3202 if (S_ISGITLINK(expected_mode
)) {
3204 return read_file_or_gitlink(ce
, buf
);
3206 return SUBMODULE_PATCH_WITHOUT_INDEX
;
3208 if (read_old_data(st
, name
, buf
))
3209 return error(_("read of %s failed"), name
);
3216 * We are about to apply "patch"; populate the "image" with the
3217 * current version we have, from the working tree or from the index,
3218 * depending on the situation e.g. --cached/--index. If we are
3219 * applying a non-git patch that incrementally updates the tree,
3220 * we read from the result of a previous diff.
3222 static int load_preimage(struct image
*image
,
3223 struct patch
*patch
, struct stat
*st
,
3224 const struct cache_entry
*ce
)
3226 struct strbuf buf
= STRBUF_INIT
;
3229 struct patch
*previous
;
3232 previous
= previous_patch(patch
, &status
);
3234 return error(_("path %s has been renamed/deleted"),
3237 /* We have a patched copy in memory; use that. */
3238 strbuf_add(&buf
, previous
->result
, previous
->resultsize
);
3240 status
= load_patch_target(&buf
, ce
, st
,
3241 patch
->old_name
, patch
->old_mode
);
3244 else if (status
== SUBMODULE_PATCH_WITHOUT_INDEX
) {
3246 * There is no way to apply subproject
3247 * patch without looking at the index.
3248 * NEEDSWORK: shouldn't this be flagged
3251 free_fragment_list(patch
->fragments
);
3252 patch
->fragments
= NULL
;
3253 } else if (status
) {
3254 return error(_("read of %s failed"), patch
->old_name
);
3258 img
= strbuf_detach(&buf
, &len
);
3259 prepare_image(image
, img
, len
, !patch
->is_binary
);
3263 static int three_way_merge(struct image
*image
,
3265 const unsigned char *base
,
3266 const unsigned char *ours
,
3267 const unsigned char *theirs
)
3269 mmfile_t base_file
, our_file
, their_file
;
3270 mmbuffer_t result
= { NULL
};
3273 read_mmblob(&base_file
, base
);
3274 read_mmblob(&our_file
, ours
);
3275 read_mmblob(&their_file
, theirs
);
3276 status
= ll_merge(&result
, path
,
3279 &their_file
, "theirs", NULL
);
3280 free(base_file
.ptr
);
3282 free(their_file
.ptr
);
3283 if (status
< 0 || !result
.ptr
) {
3288 image
->buf
= result
.ptr
;
3289 image
->len
= result
.size
;
3295 * When directly falling back to add/add three-way merge, we read from
3296 * the current contents of the new_name. In no cases other than that
3297 * this function will be called.
3299 static int load_current(struct image
*image
, struct patch
*patch
)
3301 struct strbuf buf
= STRBUF_INIT
;
3306 struct cache_entry
*ce
;
3307 char *name
= patch
->new_name
;
3308 unsigned mode
= patch
->new_mode
;
3311 die("BUG: patch to %s is not a creation", patch
->old_name
);
3313 pos
= cache_name_pos(name
, strlen(name
));
3315 return error(_("%s: does not exist in index"), name
);
3316 ce
= active_cache
[pos
];
3317 if (lstat(name
, &st
)) {
3318 if (errno
!= ENOENT
)
3319 return error(_("%s: %s"), name
, strerror(errno
));
3320 if (checkout_target(&the_index
, ce
, &st
))
3323 if (verify_index_match(ce
, &st
))
3324 return error(_("%s: does not match index"), name
);
3326 status
= load_patch_target(&buf
, ce
, &st
, name
, mode
);
3331 img
= strbuf_detach(&buf
, &len
);
3332 prepare_image(image
, img
, len
, !patch
->is_binary
);
3336 static int try_threeway(struct image
*image
, struct patch
*patch
,
3337 struct stat
*st
, const struct cache_entry
*ce
)
3339 unsigned char pre_sha1
[20], post_sha1
[20], our_sha1
[20];
3340 struct strbuf buf
= STRBUF_INIT
;
3344 struct image tmp_image
;
3346 /* No point falling back to 3-way merge in these cases */
3347 if (patch
->is_delete
||
3348 S_ISGITLINK(patch
->old_mode
) || S_ISGITLINK(patch
->new_mode
))
3351 /* Preimage the patch was prepared for */
3353 write_sha1_file("", 0, blob_type
, pre_sha1
);
3354 else if (get_sha1(patch
->old_sha1_prefix
, pre_sha1
) ||
3355 read_blob_object(&buf
, pre_sha1
, patch
->old_mode
))
3356 return error("repository lacks the necessary blob to fall back on 3-way merge.");
3358 fprintf(stderr
, "Falling back to three-way merge...\n");
3360 img
= strbuf_detach(&buf
, &len
);
3361 prepare_image(&tmp_image
, img
, len
, 1);
3362 /* Apply the patch to get the post image */
3363 if (apply_fragments(&tmp_image
, patch
) < 0) {
3364 clear_image(&tmp_image
);
3367 /* post_sha1[] is theirs */
3368 write_sha1_file(tmp_image
.buf
, tmp_image
.len
, blob_type
, post_sha1
);
3369 clear_image(&tmp_image
);
3371 /* our_sha1[] is ours */
3372 if (patch
->is_new
) {
3373 if (load_current(&tmp_image
, patch
))
3374 return error("cannot read the current contents of '%s'",
3377 if (load_preimage(&tmp_image
, patch
, st
, ce
))
3378 return error("cannot read the current contents of '%s'",
3381 write_sha1_file(tmp_image
.buf
, tmp_image
.len
, blob_type
, our_sha1
);
3382 clear_image(&tmp_image
);
3384 /* in-core three-way merge between post and our using pre as base */
3385 status
= three_way_merge(image
, patch
->new_name
,
3386 pre_sha1
, our_sha1
, post_sha1
);
3388 fprintf(stderr
, "Failed to fall back on three-way merge...\n");
3393 patch
->conflicted_threeway
= 1;
3395 hashclr(patch
->threeway_stage
[0]);
3397 hashcpy(patch
->threeway_stage
[0], pre_sha1
);
3398 hashcpy(patch
->threeway_stage
[1], our_sha1
);
3399 hashcpy(patch
->threeway_stage
[2], post_sha1
);
3400 fprintf(stderr
, "Applied patch to '%s' with conflicts.\n", patch
->new_name
);
3402 fprintf(stderr
, "Applied patch to '%s' cleanly.\n", patch
->new_name
);
3407 static int apply_data(struct patch
*patch
, struct stat
*st
, const struct cache_entry
*ce
)
3411 if (load_preimage(&image
, patch
, st
, ce
) < 0)
3414 if (patch
->direct_to_threeway
||
3415 apply_fragments(&image
, patch
) < 0) {
3416 /* Note: with --reject, apply_fragments() returns 0 */
3417 if (!threeway
|| try_threeway(&image
, patch
, st
, ce
) < 0)
3420 patch
->result
= image
.buf
;
3421 patch
->resultsize
= image
.len
;
3422 add_to_fn_table(patch
);
3423 free(image
.line_allocated
);
3425 if (0 < patch
->is_delete
&& patch
->resultsize
)
3426 return error(_("removal patch leaves file contents"));
3432 * If "patch" that we are looking at modifies or deletes what we have,
3433 * we would want it not to lose any local modification we have, either
3434 * in the working tree or in the index.
3436 * This also decides if a non-git patch is a creation patch or a
3437 * modification to an existing empty file. We do not check the state
3438 * of the current tree for a creation patch in this function; the caller
3439 * check_patch() separately makes sure (and errors out otherwise) that
3440 * the path the patch creates does not exist in the current tree.
3442 static int check_preimage(struct patch
*patch
, struct cache_entry
**ce
, struct stat
*st
)
3444 const char *old_name
= patch
->old_name
;
3445 struct patch
*previous
= NULL
;
3446 int stat_ret
= 0, status
;
3447 unsigned st_mode
= 0;
3452 assert(patch
->is_new
<= 0);
3453 previous
= previous_patch(patch
, &status
);
3456 return error(_("path %s has been renamed/deleted"), old_name
);
3458 st_mode
= previous
->new_mode
;
3459 } else if (!cached
) {
3460 stat_ret
= lstat(old_name
, st
);
3461 if (stat_ret
&& errno
!= ENOENT
)
3462 return error(_("%s: %s"), old_name
, strerror(errno
));
3465 if (check_index
&& !previous
) {
3466 int pos
= cache_name_pos(old_name
, strlen(old_name
));
3468 if (patch
->is_new
< 0)
3470 return error(_("%s: does not exist in index"), old_name
);
3472 *ce
= active_cache
[pos
];
3474 if (checkout_target(&the_index
, *ce
, st
))
3477 if (!cached
&& verify_index_match(*ce
, st
))
3478 return error(_("%s: does not match index"), old_name
);
3480 st_mode
= (*ce
)->ce_mode
;
3481 } else if (stat_ret
< 0) {
3482 if (patch
->is_new
< 0)
3484 return error(_("%s: %s"), old_name
, strerror(errno
));
3487 if (!cached
&& !previous
)
3488 st_mode
= ce_mode_from_stat(*ce
, st
->st_mode
);
3490 if (patch
->is_new
< 0)
3492 if (!patch
->old_mode
)
3493 patch
->old_mode
= st_mode
;
3494 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
3495 return error(_("%s: wrong type"), old_name
);
3496 if (st_mode
!= patch
->old_mode
)
3497 warning(_("%s has type %o, expected %o"),
3498 old_name
, st_mode
, patch
->old_mode
);
3499 if (!patch
->new_mode
&& !patch
->is_delete
)
3500 patch
->new_mode
= st_mode
;
3505 patch
->is_delete
= 0;
3506 free(patch
->old_name
);
3507 patch
->old_name
= NULL
;
3512 #define EXISTS_IN_INDEX 1
3513 #define EXISTS_IN_WORKTREE 2
3515 static int check_to_create(const char *new_name
, int ok_if_exists
)
3520 cache_name_pos(new_name
, strlen(new_name
)) >= 0 &&
3522 return EXISTS_IN_INDEX
;
3526 if (!lstat(new_name
, &nst
)) {
3527 if (S_ISDIR(nst
.st_mode
) || ok_if_exists
)
3530 * A leading component of new_name might be a symlink
3531 * that is going to be removed with this patch, but
3532 * still pointing at somewhere that has the path.
3533 * In such a case, path "new_name" does not exist as
3534 * far as git is concerned.
3536 if (has_symlink_leading_path(new_name
, strlen(new_name
)))
3539 return EXISTS_IN_WORKTREE
;
3540 } else if ((errno
!= ENOENT
) && (errno
!= ENOTDIR
)) {
3541 return error("%s: %s", new_name
, strerror(errno
));
3547 * Check and apply the patch in-core; leave the result in patch->result
3548 * for the caller to write it out to the final destination.
3550 static int check_patch(struct patch
*patch
)
3553 const char *old_name
= patch
->old_name
;
3554 const char *new_name
= patch
->new_name
;
3555 const char *name
= old_name
? old_name
: new_name
;
3556 struct cache_entry
*ce
= NULL
;
3557 struct patch
*tpatch
;
3561 patch
->rejected
= 1; /* we will drop this after we succeed */
3563 status
= check_preimage(patch
, &ce
, &st
);
3566 old_name
= patch
->old_name
;
3569 * A type-change diff is always split into a patch to delete
3570 * old, immediately followed by a patch to create new (see
3571 * diff.c::run_diff()); in such a case it is Ok that the entry
3572 * to be deleted by the previous patch is still in the working
3573 * tree and in the index.
3575 * A patch to swap-rename between A and B would first rename A
3576 * to B and then rename B to A. While applying the first one,
3577 * the presence of B should not stop A from getting renamed to
3578 * B; ask to_be_deleted() about the later rename. Removal of
3579 * B and rename from A to B is handled the same way by asking
3582 if ((tpatch
= in_fn_table(new_name
)) &&
3583 (was_deleted(tpatch
) || to_be_deleted(tpatch
)))
3589 ((0 < patch
->is_new
) || patch
->is_rename
|| patch
->is_copy
)) {
3590 int err
= check_to_create(new_name
, ok_if_exists
);
3592 if (err
&& threeway
) {
3593 patch
->direct_to_threeway
= 1;
3594 } else switch (err
) {
3597 case EXISTS_IN_INDEX
:
3598 return error(_("%s: already exists in index"), new_name
);
3600 case EXISTS_IN_WORKTREE
:
3601 return error(_("%s: already exists in working directory"),
3607 if (!patch
->new_mode
) {
3608 if (0 < patch
->is_new
)
3609 patch
->new_mode
= S_IFREG
| 0644;
3611 patch
->new_mode
= patch
->old_mode
;
3615 if (new_name
&& old_name
) {
3616 int same
= !strcmp(old_name
, new_name
);
3617 if (!patch
->new_mode
)
3618 patch
->new_mode
= patch
->old_mode
;
3619 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
) {
3621 return error(_("new mode (%o) of %s does not "
3622 "match old mode (%o)"),
3623 patch
->new_mode
, new_name
,
3626 return error(_("new mode (%o) of %s does not "
3627 "match old mode (%o) of %s"),
3628 patch
->new_mode
, new_name
,
3629 patch
->old_mode
, old_name
);
3633 if (apply_data(patch
, &st
, ce
) < 0)
3634 return error(_("%s: patch does not apply"), name
);
3635 patch
->rejected
= 0;
3639 static int check_patch_list(struct patch
*patch
)
3643 prepare_fn_table(patch
);
3645 if (apply_verbosely
)
3646 say_patch_name(stderr
,
3647 _("Checking patch %s..."), patch
);
3648 err
|= check_patch(patch
);
3649 patch
= patch
->next
;
3654 /* This function tries to read the sha1 from the current index */
3655 static int get_current_sha1(const char *path
, unsigned char *sha1
)
3659 if (read_cache() < 0)
3661 pos
= cache_name_pos(path
, strlen(path
));
3664 hashcpy(sha1
, active_cache
[pos
]->sha1
);
3668 static int preimage_sha1_in_gitlink_patch(struct patch
*p
, unsigned char sha1
[20])
3671 * A usable gitlink patch has only one fragment (hunk) that looks like:
3673 * -Subproject commit <old sha1>
3674 * +Subproject commit <new sha1>
3677 * -Subproject commit <old sha1>
3678 * for a removal patch.
3680 struct fragment
*hunk
= p
->fragments
;
3681 static const char heading
[] = "-Subproject commit ";
3684 if (/* does the patch have only one hunk? */
3685 hunk
&& !hunk
->next
&&
3686 /* is its preimage one line? */
3687 hunk
->oldpos
== 1 && hunk
->oldlines
== 1 &&
3688 /* does preimage begin with the heading? */
3689 (preimage
= memchr(hunk
->patch
, '\n', hunk
->size
)) != NULL
&&
3690 starts_with(++preimage
, heading
) &&
3691 /* does it record full SHA-1? */
3692 !get_sha1_hex(preimage
+ sizeof(heading
) - 1, sha1
) &&
3693 preimage
[sizeof(heading
) + 40 - 1] == '\n' &&
3694 /* does the abbreviated name on the index line agree with it? */
3695 starts_with(preimage
+ sizeof(heading
) - 1, p
->old_sha1_prefix
))
3696 return 0; /* it all looks fine */
3698 /* we may have full object name on the index line */
3699 return get_sha1_hex(p
->old_sha1_prefix
, sha1
);
3702 /* Build an index that contains the just the files needed for a 3way merge */
3703 static void build_fake_ancestor(struct patch
*list
, const char *filename
)
3705 struct patch
*patch
;
3706 struct index_state result
= { NULL
};
3707 static struct lock_file lock
;
3709 /* Once we start supporting the reverse patch, it may be
3710 * worth showing the new sha1 prefix, but until then...
3712 for (patch
= list
; patch
; patch
= patch
->next
) {
3713 unsigned char sha1
[20];
3714 struct cache_entry
*ce
;
3717 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3718 if (0 < patch
->is_new
)
3721 if (S_ISGITLINK(patch
->old_mode
)) {
3722 if (!preimage_sha1_in_gitlink_patch(patch
, sha1
))
3723 ; /* ok, the textual part looks sane */
3725 die("sha1 information is lacking or useless for submoule %s",
3727 } else if (!get_sha1_blob(patch
->old_sha1_prefix
, sha1
)) {
3729 } else if (!patch
->lines_added
&& !patch
->lines_deleted
) {
3730 /* mode-only change: update the current */
3731 if (get_current_sha1(patch
->old_name
, sha1
))
3732 die("mode change for %s, which is not "
3733 "in current HEAD", name
);
3735 die("sha1 information is lacking or useless "
3738 ce
= make_cache_entry(patch
->old_mode
, sha1
, name
, 0, 0);
3740 die(_("make_cache_entry failed for path '%s'"), name
);
3741 if (add_index_entry(&result
, ce
, ADD_CACHE_OK_TO_ADD
))
3742 die ("Could not add %s to temporary index", name
);
3745 hold_lock_file_for_update(&lock
, filename
, LOCK_DIE_ON_ERROR
);
3746 if (write_locked_index(&result
, &lock
, COMMIT_LOCK
))
3747 die ("Could not write temporary index to %s", filename
);
3749 discard_index(&result
);
3752 static void stat_patch_list(struct patch
*patch
)
3754 int files
, adds
, dels
;
3756 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
3758 adds
+= patch
->lines_added
;
3759 dels
+= patch
->lines_deleted
;
3763 print_stat_summary(stdout
, files
, adds
, dels
);
3766 static void numstat_patch_list(struct patch
*patch
)
3768 for ( ; patch
; patch
= patch
->next
) {
3770 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
3771 if (patch
->is_binary
)
3774 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
3775 write_name_quoted(name
, stdout
, line_termination
);
3779 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
3782 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
3784 printf(" %s %s\n", newdelete
, name
);
3787 static void show_mode_change(struct patch
*p
, int show_name
)
3789 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
3791 printf(" mode change %06o => %06o %s\n",
3792 p
->old_mode
, p
->new_mode
, p
->new_name
);
3794 printf(" mode change %06o => %06o\n",
3795 p
->old_mode
, p
->new_mode
);
3799 static void show_rename_copy(struct patch
*p
)
3801 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
3802 const char *old
, *new;
3804 /* Find common prefix */
3808 const char *slash_old
, *slash_new
;
3809 slash_old
= strchr(old
, '/');
3810 slash_new
= strchr(new, '/');
3813 slash_old
- old
!= slash_new
- new ||
3814 memcmp(old
, new, slash_new
- new))
3816 old
= slash_old
+ 1;
3817 new = slash_new
+ 1;
3819 /* p->old_name thru old is the common prefix, and old and new
3820 * through the end of names are renames
3822 if (old
!= p
->old_name
)
3823 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
3824 (int)(old
- p
->old_name
), p
->old_name
,
3825 old
, new, p
->score
);
3827 printf(" %s %s => %s (%d%%)\n", renamecopy
,
3828 p
->old_name
, p
->new_name
, p
->score
);
3829 show_mode_change(p
, 0);
3832 static void summary_patch_list(struct patch
*patch
)
3836 for (p
= patch
; p
; p
= p
->next
) {
3838 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
3839 else if (p
->is_delete
)
3840 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
3842 if (p
->is_rename
|| p
->is_copy
)
3843 show_rename_copy(p
);
3846 printf(" rewrite %s (%d%%)\n",
3847 p
->new_name
, p
->score
);
3848 show_mode_change(p
, 0);
3851 show_mode_change(p
, 1);
3857 static void patch_stats(struct patch
*patch
)
3859 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
3861 if (lines
> max_change
)
3863 if (patch
->old_name
) {
3864 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
3866 len
= strlen(patch
->old_name
);
3870 if (patch
->new_name
) {
3871 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
3873 len
= strlen(patch
->new_name
);
3879 static void remove_file(struct patch
*patch
, int rmdir_empty
)
3882 if (remove_file_from_cache(patch
->old_name
) < 0)
3883 die(_("unable to remove %s from index"), patch
->old_name
);
3886 if (!remove_or_warn(patch
->old_mode
, patch
->old_name
) && rmdir_empty
) {
3887 remove_path(patch
->old_name
);
3892 static void add_index_file(const char *path
, unsigned mode
, void *buf
, unsigned long size
)
3895 struct cache_entry
*ce
;
3896 int namelen
= strlen(path
);
3897 unsigned ce_size
= cache_entry_size(namelen
);
3902 ce
= xcalloc(1, ce_size
);
3903 memcpy(ce
->name
, path
, namelen
);
3904 ce
->ce_mode
= create_ce_mode(mode
);
3905 ce
->ce_flags
= create_ce_flags(0);
3906 ce
->ce_namelen
= namelen
;
3907 if (S_ISGITLINK(mode
)) {
3910 if (!skip_prefix(buf
, "Subproject commit ", &s
) ||
3911 get_sha1_hex(s
, ce
->sha1
))
3912 die(_("corrupt patch for submodule %s"), path
);
3915 if (lstat(path
, &st
) < 0)
3916 die_errno(_("unable to stat newly created file '%s'"),
3918 fill_stat_cache_info(ce
, &st
);
3920 if (write_sha1_file(buf
, size
, blob_type
, ce
->sha1
) < 0)
3921 die(_("unable to create backing store for newly created file %s"), path
);
3923 if (add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
) < 0)
3924 die(_("unable to add cache entry for %s"), path
);
3927 static int try_create_file(const char *path
, unsigned int mode
, const char *buf
, unsigned long size
)
3930 struct strbuf nbuf
= STRBUF_INIT
;
3932 if (S_ISGITLINK(mode
)) {
3934 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
))
3936 return mkdir(path
, 0777);
3939 if (has_symlinks
&& S_ISLNK(mode
))
3940 /* Although buf:size is counted string, it also is NUL
3943 return symlink(buf
, path
);
3945 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
3949 if (convert_to_working_tree(path
, buf
, size
, &nbuf
)) {
3953 write_or_die(fd
, buf
, size
);
3954 strbuf_release(&nbuf
);
3957 die_errno(_("closing file '%s'"), path
);
3962 * We optimistically assume that the directories exist,
3963 * which is true 99% of the time anyway. If they don't,
3964 * we create them and try again.
3966 static void create_one_file(char *path
, unsigned mode
, const char *buf
, unsigned long size
)
3970 if (!try_create_file(path
, mode
, buf
, size
))
3973 if (errno
== ENOENT
) {
3974 if (safe_create_leading_directories(path
))
3976 if (!try_create_file(path
, mode
, buf
, size
))
3980 if (errno
== EEXIST
|| errno
== EACCES
) {
3981 /* We may be trying to create a file where a directory
3985 if (!lstat(path
, &st
) && (!S_ISDIR(st
.st_mode
) || !rmdir(path
)))
3989 if (errno
== EEXIST
) {
3990 unsigned int nr
= getpid();
3993 char newpath
[PATH_MAX
];
3994 mksnpath(newpath
, sizeof(newpath
), "%s~%u", path
, nr
);
3995 if (!try_create_file(newpath
, mode
, buf
, size
)) {
3996 if (!rename(newpath
, path
))
3998 unlink_or_warn(newpath
);
4001 if (errno
!= EEXIST
)
4006 die_errno(_("unable to write file '%s' mode %o"), path
, mode
);
4009 static void add_conflicted_stages_file(struct patch
*patch
)
4012 unsigned ce_size
, mode
;
4013 struct cache_entry
*ce
;
4017 namelen
= strlen(patch
->new_name
);
4018 ce_size
= cache_entry_size(namelen
);
4019 mode
= patch
->new_mode
? patch
->new_mode
: (S_IFREG
| 0644);
4021 remove_file_from_cache(patch
->new_name
);
4022 for (stage
= 1; stage
< 4; stage
++) {
4023 if (is_null_sha1(patch
->threeway_stage
[stage
- 1]))
4025 ce
= xcalloc(1, ce_size
);
4026 memcpy(ce
->name
, patch
->new_name
, namelen
);
4027 ce
->ce_mode
= create_ce_mode(mode
);
4028 ce
->ce_flags
= create_ce_flags(stage
);
4029 ce
->ce_namelen
= namelen
;
4030 hashcpy(ce
->sha1
, patch
->threeway_stage
[stage
- 1]);
4031 if (add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
) < 0)
4032 die(_("unable to add cache entry for %s"), patch
->new_name
);
4036 static void create_file(struct patch
*patch
)
4038 char *path
= patch
->new_name
;
4039 unsigned mode
= patch
->new_mode
;
4040 unsigned long size
= patch
->resultsize
;
4041 char *buf
= patch
->result
;
4044 mode
= S_IFREG
| 0644;
4045 create_one_file(path
, mode
, buf
, size
);
4047 if (patch
->conflicted_threeway
)
4048 add_conflicted_stages_file(patch
);
4050 add_index_file(path
, mode
, buf
, size
);
4053 /* phase zero is to remove, phase one is to create */
4054 static void write_out_one_result(struct patch
*patch
, int phase
)
4056 if (patch
->is_delete
> 0) {
4058 remove_file(patch
, 1);
4061 if (patch
->is_new
> 0 || patch
->is_copy
) {
4067 * Rename or modification boils down to the same
4068 * thing: remove the old, write the new
4071 remove_file(patch
, patch
->is_rename
);
4076 static int write_out_one_reject(struct patch
*patch
)
4079 char namebuf
[PATH_MAX
];
4080 struct fragment
*frag
;
4082 struct strbuf sb
= STRBUF_INIT
;
4084 for (cnt
= 0, frag
= patch
->fragments
; frag
; frag
= frag
->next
) {
4085 if (!frag
->rejected
)
4091 if (apply_verbosely
)
4092 say_patch_name(stderr
,
4093 _("Applied patch %s cleanly."), patch
);
4097 /* This should not happen, because a removal patch that leaves
4098 * contents are marked "rejected" at the patch level.
4100 if (!patch
->new_name
)
4101 die(_("internal error"));
4103 /* Say this even without --verbose */
4104 strbuf_addf(&sb
, Q_("Applying patch %%s with %d reject...",
4105 "Applying patch %%s with %d rejects...",
4108 say_patch_name(stderr
, sb
.buf
, patch
);
4109 strbuf_release(&sb
);
4111 cnt
= strlen(patch
->new_name
);
4112 if (ARRAY_SIZE(namebuf
) <= cnt
+ 5) {
4113 cnt
= ARRAY_SIZE(namebuf
) - 5;
4114 warning(_("truncating .rej filename to %.*s.rej"),
4115 cnt
- 1, patch
->new_name
);
4117 memcpy(namebuf
, patch
->new_name
, cnt
);
4118 memcpy(namebuf
+ cnt
, ".rej", 5);
4120 rej
= fopen(namebuf
, "w");
4122 return error(_("cannot open %s: %s"), namebuf
, strerror(errno
));
4124 /* Normal git tools never deal with .rej, so do not pretend
4125 * this is a git patch by saying --git or giving extended
4126 * headers. While at it, maybe please "kompare" that wants
4127 * the trailing TAB and some garbage at the end of line ;-).
4129 fprintf(rej
, "diff a/%s b/%s\t(rejected hunks)\n",
4130 patch
->new_name
, patch
->new_name
);
4131 for (cnt
= 1, frag
= patch
->fragments
;
4133 cnt
++, frag
= frag
->next
) {
4134 if (!frag
->rejected
) {
4135 fprintf_ln(stderr
, _("Hunk #%d applied cleanly."), cnt
);
4138 fprintf_ln(stderr
, _("Rejected hunk #%d."), cnt
);
4139 fprintf(rej
, "%.*s", frag
->size
, frag
->patch
);
4140 if (frag
->patch
[frag
->size
-1] != '\n')
4147 static int write_out_results(struct patch
*list
)
4152 struct string_list cpath
= STRING_LIST_INIT_DUP
;
4154 for (phase
= 0; phase
< 2; phase
++) {
4160 write_out_one_result(l
, phase
);
4162 if (write_out_one_reject(l
))
4164 if (l
->conflicted_threeway
) {
4165 string_list_append(&cpath
, l
->new_name
);
4175 struct string_list_item
*item
;
4177 sort_string_list(&cpath
);
4178 for_each_string_list_item(item
, &cpath
)
4179 fprintf(stderr
, "U %s\n", item
->string
);
4180 string_list_clear(&cpath
, 0);
4188 static struct lock_file lock_file
;
4190 #define INACCURATE_EOF (1<<0)
4191 #define RECOUNT (1<<1)
4193 static int apply_patch(int fd
, const char *filename
, int options
)
4196 struct strbuf buf
= STRBUF_INIT
; /* owns the patch text */
4197 struct patch
*list
= NULL
, **listp
= &list
;
4198 int skipped_patch
= 0;
4200 patch_input_file
= filename
;
4201 read_patch_file(&buf
, fd
);
4203 while (offset
< buf
.len
) {
4204 struct patch
*patch
;
4207 patch
= xcalloc(1, sizeof(*patch
));
4208 patch
->inaccurate_eof
= !!(options
& INACCURATE_EOF
);
4209 patch
->recount
= !!(options
& RECOUNT
);
4210 nr
= parse_chunk(buf
.buf
+ offset
, buf
.len
- offset
, patch
);
4213 if (apply_in_reverse
)
4214 reverse_patches(patch
);
4215 if (use_patch(patch
)) {
4218 listp
= &patch
->next
;
4227 if (!list
&& !skipped_patch
)
4228 die(_("unrecognized input"));
4230 if (whitespace_error
&& (ws_error_action
== die_on_ws_error
))
4233 update_index
= check_index
&& apply
;
4234 if (update_index
&& newfd
< 0)
4235 newfd
= hold_locked_index(&lock_file
, 1);
4238 if (read_cache() < 0)
4239 die(_("unable to read index file"));
4242 if ((check
|| apply
) &&
4243 check_patch_list(list
) < 0 &&
4247 if (apply
&& write_out_results(list
)) {
4248 if (apply_with_reject
)
4250 /* with --3way, we still need to write the index out */
4255 build_fake_ancestor(list
, fake_ancestor
);
4258 stat_patch_list(list
);
4261 numstat_patch_list(list
);
4264 summary_patch_list(list
);
4266 free_patch_list(list
);
4267 strbuf_release(&buf
);
4268 string_list_clear(&fn_table
, 0);
4272 static void git_apply_config(void)
4274 git_config_get_string_const("apply.whitespace", &apply_default_whitespace
);
4275 git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace
);
4276 git_config(git_default_config
, NULL
);
4279 static int option_parse_exclude(const struct option
*opt
,
4280 const char *arg
, int unset
)
4282 add_name_limit(arg
, 1);
4286 static int option_parse_include(const struct option
*opt
,
4287 const char *arg
, int unset
)
4289 add_name_limit(arg
, 0);
4294 static int option_parse_p(const struct option
*opt
,
4295 const char *arg
, int unset
)
4297 p_value
= atoi(arg
);
4302 static int option_parse_z(const struct option
*opt
,
4303 const char *arg
, int unset
)
4306 line_termination
= '\n';
4308 line_termination
= 0;
4312 static int option_parse_space_change(const struct option
*opt
,
4313 const char *arg
, int unset
)
4316 ws_ignore_action
= ignore_ws_none
;
4318 ws_ignore_action
= ignore_ws_change
;
4322 static int option_parse_whitespace(const struct option
*opt
,
4323 const char *arg
, int unset
)
4325 const char **whitespace_option
= opt
->value
;
4327 *whitespace_option
= arg
;
4328 parse_whitespace_option(arg
);
4332 static int option_parse_directory(const struct option
*opt
,
4333 const char *arg
, int unset
)
4335 root_len
= strlen(arg
);
4336 if (root_len
&& arg
[root_len
- 1] != '/') {
4338 root
= new_root
= xmalloc(root_len
+ 2);
4339 strcpy(new_root
, arg
);
4340 strcpy(new_root
+ root_len
++, "/");
4346 int cmd_apply(int argc
, const char **argv
, const char *prefix_
)
4350 int is_not_gitdir
= !startup_info
->have_repository
;
4351 int force_apply
= 0;
4353 const char *whitespace_option
= NULL
;
4355 struct option builtin_apply_options
[] = {
4356 { OPTION_CALLBACK
, 0, "exclude", NULL
, N_("path"),
4357 N_("don't apply changes matching the given path"),
4358 0, option_parse_exclude
},
4359 { OPTION_CALLBACK
, 0, "include", NULL
, N_("path"),
4360 N_("apply changes matching the given path"),
4361 0, option_parse_include
},
4362 { OPTION_CALLBACK
, 'p', NULL
, NULL
, N_("num"),
4363 N_("remove <num> leading slashes from traditional diff paths"),
4364 0, option_parse_p
},
4365 OPT_BOOL(0, "no-add", &no_add
,
4366 N_("ignore additions made by the patch")),
4367 OPT_BOOL(0, "stat", &diffstat
,
4368 N_("instead of applying the patch, output diffstat for the input")),
4369 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
4370 OPT_NOOP_NOARG(0, "binary"),
4371 OPT_BOOL(0, "numstat", &numstat
,
4372 N_("show number of added and deleted lines in decimal notation")),
4373 OPT_BOOL(0, "summary", &summary
,
4374 N_("instead of applying the patch, output a summary for the input")),
4375 OPT_BOOL(0, "check", &check
,
4376 N_("instead of applying the patch, see if the patch is applicable")),
4377 OPT_BOOL(0, "index", &check_index
,
4378 N_("make sure the patch is applicable to the current index")),
4379 OPT_BOOL(0, "cached", &cached
,
4380 N_("apply a patch without touching the working tree")),
4381 OPT_BOOL(0, "apply", &force_apply
,
4382 N_("also apply the patch (use with --stat/--summary/--check)")),
4383 OPT_BOOL('3', "3way", &threeway
,
4384 N_( "attempt three-way merge if a patch does not apply")),
4385 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor
,
4386 N_("build a temporary index based on embedded index information")),
4387 { OPTION_CALLBACK
, 'z', NULL
, NULL
, NULL
,
4388 N_("paths are separated with NUL character"),
4389 PARSE_OPT_NOARG
, option_parse_z
},
4390 OPT_INTEGER('C', NULL
, &p_context
,
4391 N_("ensure at least <n> lines of context match")),
4392 { OPTION_CALLBACK
, 0, "whitespace", &whitespace_option
, N_("action"),
4393 N_("detect new or modified lines that have whitespace errors"),
4394 0, option_parse_whitespace
},
4395 { OPTION_CALLBACK
, 0, "ignore-space-change", NULL
, NULL
,
4396 N_("ignore changes in whitespace when finding context"),
4397 PARSE_OPT_NOARG
, option_parse_space_change
},
4398 { OPTION_CALLBACK
, 0, "ignore-whitespace", NULL
, NULL
,
4399 N_("ignore changes in whitespace when finding context"),
4400 PARSE_OPT_NOARG
, option_parse_space_change
},
4401 OPT_BOOL('R', "reverse", &apply_in_reverse
,
4402 N_("apply the patch in reverse")),
4403 OPT_BOOL(0, "unidiff-zero", &unidiff_zero
,
4404 N_("don't expect at least one line of context")),
4405 OPT_BOOL(0, "reject", &apply_with_reject
,
4406 N_("leave the rejected hunks in corresponding *.rej files")),
4407 OPT_BOOL(0, "allow-overlap", &allow_overlap
,
4408 N_("allow overlapping hunks")),
4409 OPT__VERBOSE(&apply_verbosely
, N_("be verbose")),
4410 OPT_BIT(0, "inaccurate-eof", &options
,
4411 N_("tolerate incorrectly detected missing new-line at the end of file"),
4413 OPT_BIT(0, "recount", &options
,
4414 N_("do not trust the line counts in the hunk headers"),
4416 { OPTION_CALLBACK
, 0, "directory", NULL
, N_("root"),
4417 N_("prepend <root> to all filenames"),
4418 0, option_parse_directory
},
4423 prefix_length
= prefix
? strlen(prefix
) : 0;
4425 if (apply_default_whitespace
)
4426 parse_whitespace_option(apply_default_whitespace
);
4427 if (apply_default_ignorewhitespace
)
4428 parse_ignorewhitespace_option(apply_default_ignorewhitespace
);
4430 argc
= parse_options(argc
, argv
, prefix
, builtin_apply_options
,
4433 if (apply_with_reject
&& threeway
)
4434 die("--reject and --3way cannot be used together.");
4435 if (cached
&& threeway
)
4436 die("--cached and --3way cannot be used together.");
4439 die(_("--3way outside a repository"));
4442 if (apply_with_reject
)
4443 apply
= apply_verbosely
= 1;
4444 if (!force_apply
&& (diffstat
|| numstat
|| summary
|| check
|| fake_ancestor
))
4446 if (check_index
&& is_not_gitdir
)
4447 die(_("--index outside a repository"));
4450 die(_("--cached outside a repository"));
4453 for (i
= 0; i
< argc
; i
++) {
4454 const char *arg
= argv
[i
];
4457 if (!strcmp(arg
, "-")) {
4458 errs
|= apply_patch(0, "<stdin>", options
);
4461 } else if (0 < prefix_length
)
4462 arg
= prefix_filename(prefix
, prefix_length
, arg
);
4464 fd
= open(arg
, O_RDONLY
);
4466 die_errno(_("can't open patch '%s'"), arg
);
4468 set_default_whitespace_mode(whitespace_option
);
4469 errs
|= apply_patch(fd
, arg
, options
);
4472 set_default_whitespace_mode(whitespace_option
);
4474 errs
|= apply_patch(0, "<stdin>", options
);
4475 if (whitespace_error
) {
4476 if (squelch_whitespace_errors
&&
4477 squelch_whitespace_errors
< whitespace_error
) {
4479 whitespace_error
- squelch_whitespace_errors
;
4480 warning(Q_("squelched %d whitespace error",
4481 "squelched %d whitespace errors",
4485 if (ws_error_action
== die_on_ws_error
)
4486 die(Q_("%d line adds whitespace errors.",
4487 "%d lines add whitespace errors.",
4490 if (applied_after_fixing_ws
&& apply
)
4491 warning("%d line%s applied after"
4492 " fixing whitespace errors.",
4493 applied_after_fixing_ws
,
4494 applied_after_fixing_ws
== 1 ? "" : "s");
4495 else if (whitespace_error
)
4496 warning(Q_("%d line adds whitespace errors.",
4497 "%d lines add whitespace errors.",
4503 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
4504 die(_("Unable to write new index file"));