4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
11 #include "cache-tree.h"
16 #include "string-list.h"
19 #include "parse-options.h"
20 #include "xdiff-interface.h"
24 enum ws_error_action
{
38 * We need to keep track of how symlinks in the preimage are
39 * manipulated by the patches. A patch to add a/b/c where a/b
40 * is a symlink should not be allowed to affect the directory
41 * the symlink points at, but if the same patch removes a/b,
42 * it is perfectly fine, as the patch removes a/b to make room
43 * to create a directory a/b so that a/b/c can be created.
45 * See also "struct string_list symlink_changes" in "struct
48 #define SYMLINK_GOES_AWAY 01
49 #define SYMLINK_IN_RESULT 02
56 * Since lockfile.c keeps a linked list of all created
57 * lock_file structures, it isn't safe to free(lock_file).
59 struct lock_file
*lock_file
;
61 /* These control what gets looked at and modified */
62 int apply
; /* this is not a dry-run */
63 int cached
; /* apply to the index only */
64 int check
; /* preimage must match working tree, don't actually apply */
65 int check_index
; /* preimage must match the indexed version */
66 int update_index
; /* check_index && apply */
68 /* These control cosmetic aspect of the output */
69 int diffstat
; /* just show a diffstat, and don't actually apply */
70 int numstat
; /* just show a numeric diffstat, and don't actually apply */
71 int summary
; /* just report creation, deletion, etc, and don't actually apply */
73 /* These boolean parameters control how the apply is done */
76 int apply_with_reject
;
83 /* Other non boolean parameters */
84 const char *fake_ancestor
;
85 const char *patch_input_file
;
90 unsigned int p_context
;
92 /* Exclude and include path parameters */
93 struct string_list limit_by_name
;
96 /* Various "current state" */
97 int linenr
; /* current line number */
98 struct string_list symlink_changes
; /* we have to track symlinks */
101 * For "diff-stat" like behaviour, we keep track of the biggest change
102 * we've seen, and the longest filename. That allows us to do simple
109 * Records filenames that have been touched, in order to handle
110 * the case where more than one patches touch the same file.
112 struct string_list fn_table
;
114 /* These control whitespace errors */
115 enum ws_error_action ws_error_action
;
116 enum ws_ignore ws_ignore_action
;
117 const char *whitespace_option
;
118 int whitespace_error
;
119 int squelch_whitespace_errors
;
120 int applied_after_fixing_ws
;
123 static int newfd
= -1;
125 static const char * const apply_usage
[] = {
126 N_("git apply [<options>] [<patch>...]"),
130 static void parse_whitespace_option(struct apply_state
*state
, const char *option
)
133 state
->ws_error_action
= warn_on_ws_error
;
136 if (!strcmp(option
, "warn")) {
137 state
->ws_error_action
= warn_on_ws_error
;
140 if (!strcmp(option
, "nowarn")) {
141 state
->ws_error_action
= nowarn_ws_error
;
144 if (!strcmp(option
, "error")) {
145 state
->ws_error_action
= die_on_ws_error
;
148 if (!strcmp(option
, "error-all")) {
149 state
->ws_error_action
= die_on_ws_error
;
150 state
->squelch_whitespace_errors
= 0;
153 if (!strcmp(option
, "strip") || !strcmp(option
, "fix")) {
154 state
->ws_error_action
= correct_ws_error
;
157 die(_("unrecognized whitespace option '%s'"), option
);
160 static void parse_ignorewhitespace_option(struct apply_state
*state
,
163 if (!option
|| !strcmp(option
, "no") ||
164 !strcmp(option
, "false") || !strcmp(option
, "never") ||
165 !strcmp(option
, "none")) {
166 state
->ws_ignore_action
= ignore_ws_none
;
169 if (!strcmp(option
, "change")) {
170 state
->ws_ignore_action
= ignore_ws_change
;
173 die(_("unrecognized whitespace ignore option '%s'"), option
);
176 static void set_default_whitespace_mode(struct apply_state
*state
)
178 if (!state
->whitespace_option
&& !apply_default_whitespace
)
179 state
->ws_error_action
= (state
->apply
? warn_on_ws_error
: nowarn_ws_error
);
183 * This represents one "hunk" from a patch, starting with
184 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
185 * patch text is pointed at by patch, and its byte length
186 * is stored in size. leading and trailing are the number
190 unsigned long leading
, trailing
;
191 unsigned long oldpos
, oldlines
;
192 unsigned long newpos
, newlines
;
194 * 'patch' is usually borrowed from buf in apply_patch(),
195 * but some codepaths store an allocated buffer.
198 unsigned free_patch
:1,
202 struct fragment
*next
;
206 * When dealing with a binary patch, we reuse "leading" field
207 * to store the type of the binary hunk, either deflated "delta"
208 * or deflated "literal".
210 #define binary_patch_method leading
211 #define BINARY_DELTA_DEFLATED 1
212 #define BINARY_LITERAL_DEFLATED 2
215 * This represents a "patch" to a file, both metainfo changes
216 * such as creation/deletion, filemode and content changes represented
217 * as a series of fragments.
220 char *new_name
, *old_name
, *def_name
;
221 unsigned int old_mode
, new_mode
;
222 int is_new
, is_delete
; /* -1 = unknown, 0 = false, 1 = true */
225 int lines_added
, lines_deleted
;
227 unsigned int is_toplevel_relative
:1;
228 unsigned int inaccurate_eof
:1;
229 unsigned int is_binary
:1;
230 unsigned int is_copy
:1;
231 unsigned int is_rename
:1;
232 unsigned int recount
:1;
233 unsigned int conflicted_threeway
:1;
234 unsigned int direct_to_threeway
:1;
235 struct fragment
*fragments
;
238 char old_sha1_prefix
[41];
239 char new_sha1_prefix
[41];
242 /* three-way fallback result */
243 struct object_id threeway_stage
[3];
246 static void free_fragment_list(struct fragment
*list
)
249 struct fragment
*next
= list
->next
;
250 if (list
->free_patch
)
251 free((char *)list
->patch
);
257 static void free_patch(struct patch
*patch
)
259 free_fragment_list(patch
->fragments
);
260 free(patch
->def_name
);
261 free(patch
->old_name
);
262 free(patch
->new_name
);
267 static void free_patch_list(struct patch
*list
)
270 struct patch
*next
= list
->next
;
277 * A line in a file, len-bytes long (includes the terminating LF,
278 * except for an incomplete line at the end if the file ends with
279 * one), and its contents hashes to 'hash'.
285 #define LINE_COMMON 1
286 #define LINE_PATCHED 2
290 * This represents a "file", which is an array of "lines".
297 struct line
*line_allocated
;
301 static uint32_t hash_line(const char *cp
, size_t len
)
305 for (i
= 0, h
= 0; i
< len
; i
++) {
306 if (!isspace(cp
[i
])) {
307 h
= h
* 3 + (cp
[i
] & 0xff);
314 * Compare lines s1 of length n1 and s2 of length n2, ignoring
315 * whitespace difference. Returns 1 if they match, 0 otherwise
317 static int fuzzy_matchlines(const char *s1
, size_t n1
,
318 const char *s2
, size_t n2
)
320 const char *last1
= s1
+ n1
- 1;
321 const char *last2
= s2
+ n2
- 1;
324 /* ignore line endings */
325 while ((*last1
== '\r') || (*last1
== '\n'))
327 while ((*last2
== '\r') || (*last2
== '\n'))
330 /* skip leading whitespaces, if both begin with whitespace */
331 if (s1
<= last1
&& s2
<= last2
&& isspace(*s1
) && isspace(*s2
)) {
332 while (isspace(*s1
) && (s1
<= last1
))
334 while (isspace(*s2
) && (s2
<= last2
))
337 /* early return if both lines are empty */
338 if ((s1
> last1
) && (s2
> last2
))
341 result
= *s1
++ - *s2
++;
343 * Skip whitespace inside. We check for whitespace on
344 * both buffers because we don't want "a b" to match
347 if (isspace(*s1
) && isspace(*s2
)) {
348 while (isspace(*s1
) && s1
<= last1
)
350 while (isspace(*s2
) && s2
<= last2
)
354 * If we reached the end on one side only,
358 ((s2
> last2
) && (s1
<= last1
)) ||
359 ((s1
> last1
) && (s2
<= last2
)))
361 if ((s1
> last1
) && (s2
> last2
))
368 static void add_line_info(struct image
*img
, const char *bol
, size_t len
, unsigned flag
)
370 ALLOC_GROW(img
->line_allocated
, img
->nr
+ 1, img
->alloc
);
371 img
->line_allocated
[img
->nr
].len
= len
;
372 img
->line_allocated
[img
->nr
].hash
= hash_line(bol
, len
);
373 img
->line_allocated
[img
->nr
].flag
= flag
;
378 * "buf" has the file contents to be patched (read from various sources).
379 * attach it to "image" and add line-based index to it.
380 * "image" now owns the "buf".
382 static void prepare_image(struct image
*image
, char *buf
, size_t len
,
383 int prepare_linetable
)
387 memset(image
, 0, sizeof(*image
));
391 if (!prepare_linetable
)
394 ep
= image
->buf
+ image
->len
;
398 for (next
= cp
; next
< ep
&& *next
!= '\n'; next
++)
402 add_line_info(image
, cp
, next
- cp
, 0);
405 image
->line
= image
->line_allocated
;
408 static void clear_image(struct image
*image
)
411 free(image
->line_allocated
);
412 memset(image
, 0, sizeof(*image
));
415 /* fmt must contain _one_ %s and no other substitution */
416 static void say_patch_name(FILE *output
, const char *fmt
, struct patch
*patch
)
418 struct strbuf sb
= STRBUF_INIT
;
420 if (patch
->old_name
&& patch
->new_name
&&
421 strcmp(patch
->old_name
, patch
->new_name
)) {
422 quote_c_style(patch
->old_name
, &sb
, NULL
, 0);
423 strbuf_addstr(&sb
, " => ");
424 quote_c_style(patch
->new_name
, &sb
, NULL
, 0);
426 const char *n
= patch
->new_name
;
429 quote_c_style(n
, &sb
, NULL
, 0);
431 fprintf(output
, fmt
, sb
.buf
);
438 static void read_patch_file(struct strbuf
*sb
, int fd
)
440 if (strbuf_read(sb
, fd
, 0) < 0)
441 die_errno("git apply: failed to read");
444 * Make sure that we have some slop in the buffer
445 * so that we can do speculative "memcmp" etc, and
446 * see to it that it is NUL-filled.
448 strbuf_grow(sb
, SLOP
);
449 memset(sb
->buf
+ sb
->len
, 0, SLOP
);
452 static unsigned long linelen(const char *buffer
, unsigned long size
)
454 unsigned long len
= 0;
457 if (*buffer
++ == '\n')
463 static int is_dev_null(const char *str
)
465 return skip_prefix(str
, "/dev/null", &str
) && isspace(*str
);
471 static int name_terminate(const char *name
, int namelen
, int c
, int terminate
)
473 if (c
== ' ' && !(terminate
& TERM_SPACE
))
475 if (c
== '\t' && !(terminate
& TERM_TAB
))
481 /* remove double slashes to make --index work with such filenames */
482 static char *squash_slash(char *name
)
490 if ((name
[j
++] = name
[i
++]) == '/')
491 while (name
[i
] == '/')
498 static char *find_name_gnu(struct apply_state
*state
,
503 struct strbuf name
= STRBUF_INIT
;
507 * Proposed "new-style" GNU patch/diff format; see
508 * http://marc.info/?l=git&m=112927316408690&w=2
510 if (unquote_c_style(&name
, line
, NULL
)) {
511 strbuf_release(&name
);
515 for (cp
= name
.buf
; p_value
; p_value
--) {
516 cp
= strchr(cp
, '/');
518 strbuf_release(&name
);
524 strbuf_remove(&name
, 0, cp
- name
.buf
);
526 strbuf_insert(&name
, 0, state
->root
.buf
, state
->root
.len
);
527 return squash_slash(strbuf_detach(&name
, NULL
));
530 static size_t sane_tz_len(const char *line
, size_t len
)
534 if (len
< strlen(" +0500") || line
[len
-strlen(" +0500")] != ' ')
536 tz
= line
+ len
- strlen(" +0500");
538 if (tz
[1] != '+' && tz
[1] != '-')
541 for (p
= tz
+ 2; p
!= line
+ len
; p
++)
545 return line
+ len
- tz
;
548 static size_t tz_with_colon_len(const char *line
, size_t len
)
552 if (len
< strlen(" +08:00") || line
[len
- strlen(":00")] != ':')
554 tz
= line
+ len
- strlen(" +08:00");
556 if (tz
[0] != ' ' || (tz
[1] != '+' && tz
[1] != '-'))
559 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
560 !isdigit(*p
++) || !isdigit(*p
++))
563 return line
+ len
- tz
;
566 static size_t date_len(const char *line
, size_t len
)
568 const char *date
, *p
;
570 if (len
< strlen("72-02-05") || line
[len
-strlen("-05")] != '-')
572 p
= date
= line
+ len
- strlen("72-02-05");
574 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
575 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
576 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a date. */
579 if (date
- line
>= strlen("19") &&
580 isdigit(date
[-1]) && isdigit(date
[-2])) /* 4-digit year */
581 date
-= strlen("19");
583 return line
+ len
- date
;
586 static size_t short_time_len(const char *line
, size_t len
)
588 const char *time
, *p
;
590 if (len
< strlen(" 07:01:32") || line
[len
-strlen(":32")] != ':')
592 p
= time
= line
+ len
- strlen(" 07:01:32");
594 /* Permit 1-digit hours? */
596 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
597 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
598 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a time. */
601 return line
+ len
- time
;
604 static size_t fractional_time_len(const char *line
, size_t len
)
609 /* Expected format: 19:41:17.620000023 */
610 if (!len
|| !isdigit(line
[len
- 1]))
614 /* Fractional seconds. */
615 while (p
> line
&& isdigit(*p
))
620 /* Hours, minutes, and whole seconds. */
621 n
= short_time_len(line
, p
- line
);
625 return line
+ len
- p
+ n
;
628 static size_t trailing_spaces_len(const char *line
, size_t len
)
632 /* Expected format: ' ' x (1 or more) */
633 if (!len
|| line
[len
- 1] != ' ')
640 return line
+ len
- (p
+ 1);
647 static size_t diff_timestamp_len(const char *line
, size_t len
)
649 const char *end
= line
+ len
;
653 * Posix: 2010-07-05 19:41:17
654 * GNU: 2010-07-05 19:41:17.620000023 -0500
657 if (!isdigit(end
[-1]))
660 n
= sane_tz_len(line
, end
- line
);
662 n
= tz_with_colon_len(line
, end
- line
);
665 n
= short_time_len(line
, end
- line
);
667 n
= fractional_time_len(line
, end
- line
);
670 n
= date_len(line
, end
- line
);
671 if (!n
) /* No date. Too bad. */
675 if (end
== line
) /* No space before date. */
677 if (end
[-1] == '\t') { /* Success! */
679 return line
+ len
- end
;
681 if (end
[-1] != ' ') /* No space before date. */
684 /* Whitespace damage. */
685 end
-= trailing_spaces_len(line
, end
- line
);
686 return line
+ len
- end
;
689 static char *find_name_common(struct apply_state
*state
,
697 const char *start
= NULL
;
701 while (line
!= end
) {
704 if (!end
&& isspace(c
)) {
707 if (name_terminate(start
, line
-start
, c
, terminate
))
711 if (c
== '/' && !--p_value
)
715 return squash_slash(xstrdup_or_null(def
));
718 return squash_slash(xstrdup_or_null(def
));
721 * Generally we prefer the shorter name, especially
722 * if the other one is just a variation of that with
723 * something else tacked on to the end (ie "file.orig"
727 int deflen
= strlen(def
);
728 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
729 return squash_slash(xstrdup(def
));
732 if (state
->root
.len
) {
733 char *ret
= xstrfmt("%s%.*s", state
->root
.buf
, len
, start
);
734 return squash_slash(ret
);
737 return squash_slash(xmemdupz(start
, len
));
740 static char *find_name(struct apply_state
*state
,
747 char *name
= find_name_gnu(state
, line
, def
, p_value
);
752 return find_name_common(state
, line
, def
, p_value
, NULL
, terminate
);
755 static char *find_name_traditional(struct apply_state
*state
,
764 char *name
= find_name_gnu(state
, line
, def
, p_value
);
769 len
= strchrnul(line
, '\n') - line
;
770 date_len
= diff_timestamp_len(line
, len
);
772 return find_name_common(state
, line
, def
, p_value
, NULL
, TERM_TAB
);
775 return find_name_common(state
, line
, def
, p_value
, line
+ len
, 0);
778 static int count_slashes(const char *cp
)
790 * Given the string after "--- " or "+++ ", guess the appropriate
791 * p_value for the given patch.
793 static int guess_p_value(struct apply_state
*state
, const char *nameline
)
798 if (is_dev_null(nameline
))
800 name
= find_name_traditional(state
, nameline
, NULL
, 0);
803 cp
= strchr(name
, '/');
806 else if (state
->prefix
) {
808 * Does it begin with "a/$our-prefix" and such? Then this is
809 * very likely to apply to our directory.
811 if (!strncmp(name
, state
->prefix
, state
->prefix_length
))
812 val
= count_slashes(state
->prefix
);
815 if (!strncmp(cp
, state
->prefix
, state
->prefix_length
))
816 val
= count_slashes(state
->prefix
) + 1;
824 * Does the ---/+++ line have the POSIX timestamp after the last HT?
825 * GNU diff puts epoch there to signal a creation/deletion event. Is
826 * this such a timestamp?
828 static int has_epoch_timestamp(const char *nameline
)
831 * We are only interested in epoch timestamp; any non-zero
832 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
833 * For the same reason, the date must be either 1969-12-31 or
834 * 1970-01-01, and the seconds part must be "00".
836 const char stamp_regexp
[] =
837 "^(1969-12-31|1970-01-01)"
839 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
841 "([-+][0-2][0-9]:?[0-5][0-9])\n";
842 const char *timestamp
= NULL
, *cp
, *colon
;
843 static regex_t
*stamp
;
849 for (cp
= nameline
; *cp
!= '\n'; cp
++) {
856 stamp
= xmalloc(sizeof(*stamp
));
857 if (regcomp(stamp
, stamp_regexp
, REG_EXTENDED
)) {
858 warning(_("Cannot prepare timestamp regexp %s"),
864 status
= regexec(stamp
, timestamp
, ARRAY_SIZE(m
), m
, 0);
866 if (status
!= REG_NOMATCH
)
867 warning(_("regexec returned %d for input: %s"),
872 zoneoffset
= strtol(timestamp
+ m
[3].rm_so
+ 1, (char **) &colon
, 10);
874 zoneoffset
= zoneoffset
* 60 + strtol(colon
+ 1, NULL
, 10);
876 zoneoffset
= (zoneoffset
/ 100) * 60 + (zoneoffset
% 100);
877 if (timestamp
[m
[3].rm_so
] == '-')
878 zoneoffset
= -zoneoffset
;
881 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
882 * (west of GMT) or 1970-01-01 (east of GMT)
884 if ((zoneoffset
< 0 && memcmp(timestamp
, "1969-12-31", 10)) ||
885 (0 <= zoneoffset
&& memcmp(timestamp
, "1970-01-01", 10)))
888 hourminute
= (strtol(timestamp
+ 11, NULL
, 10) * 60 +
889 strtol(timestamp
+ 14, NULL
, 10) -
892 return ((zoneoffset
< 0 && hourminute
== 1440) ||
893 (0 <= zoneoffset
&& !hourminute
));
897 * Get the name etc info from the ---/+++ lines of a traditional patch header
899 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
900 * files, we can happily check the index for a match, but for creating a
901 * new file we should try to match whatever "patch" does. I have no idea.
903 static void parse_traditional_patch(struct apply_state
*state
,
910 first
+= 4; /* skip "--- " */
911 second
+= 4; /* skip "+++ " */
912 if (!state
->p_value_known
) {
914 p
= guess_p_value(state
, first
);
915 q
= guess_p_value(state
, second
);
917 if (0 <= p
&& p
== q
) {
919 state
->p_value_known
= 1;
922 if (is_dev_null(first
)) {
924 patch
->is_delete
= 0;
925 name
= find_name_traditional(state
, second
, NULL
, state
->p_value
);
926 patch
->new_name
= name
;
927 } else if (is_dev_null(second
)) {
929 patch
->is_delete
= 1;
930 name
= find_name_traditional(state
, first
, NULL
, state
->p_value
);
931 patch
->old_name
= name
;
934 first_name
= find_name_traditional(state
, first
, NULL
, state
->p_value
);
935 name
= find_name_traditional(state
, second
, first_name
, state
->p_value
);
937 if (has_epoch_timestamp(first
)) {
939 patch
->is_delete
= 0;
940 patch
->new_name
= name
;
941 } else if (has_epoch_timestamp(second
)) {
943 patch
->is_delete
= 1;
944 patch
->old_name
= name
;
946 patch
->old_name
= name
;
947 patch
->new_name
= xstrdup_or_null(name
);
951 die(_("unable to find filename in patch at line %d"), state
->linenr
);
954 static int gitdiff_hdrend(struct apply_state
*state
,
962 * We're anal about diff header consistency, to make
963 * sure that we don't end up having strange ambiguous
964 * patches floating around.
966 * As a result, gitdiff_{old|new}name() will check
967 * their names against any previous information, just
970 #define DIFF_OLD_NAME 0
971 #define DIFF_NEW_NAME 1
973 static void gitdiff_verify_name(struct apply_state
*state
,
979 if (!*name
&& !isnull
) {
980 *name
= find_name(state
, line
, NULL
, state
->p_value
, TERM_TAB
);
985 int len
= strlen(*name
);
988 die(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
989 *name
, state
->linenr
);
990 another
= find_name(state
, line
, NULL
, state
->p_value
, TERM_TAB
);
991 if (!another
|| memcmp(another
, *name
, len
+ 1))
992 die((side
== DIFF_NEW_NAME
) ?
993 _("git apply: bad git-diff - inconsistent new filename on line %d") :
994 _("git apply: bad git-diff - inconsistent old filename on line %d"), state
->linenr
);
997 /* expect "/dev/null" */
998 if (memcmp("/dev/null", line
, 9) || line
[9] != '\n')
999 die(_("git apply: bad git-diff - expected /dev/null on line %d"), state
->linenr
);
1003 static int gitdiff_oldname(struct apply_state
*state
,
1005 struct patch
*patch
)
1007 gitdiff_verify_name(state
, line
,
1008 patch
->is_new
, &patch
->old_name
,
1013 static int gitdiff_newname(struct apply_state
*state
,
1015 struct patch
*patch
)
1017 gitdiff_verify_name(state
, line
,
1018 patch
->is_delete
, &patch
->new_name
,
1023 static int gitdiff_oldmode(struct apply_state
*state
,
1025 struct patch
*patch
)
1027 patch
->old_mode
= strtoul(line
, NULL
, 8);
1031 static int gitdiff_newmode(struct apply_state
*state
,
1033 struct patch
*patch
)
1035 patch
->new_mode
= strtoul(line
, NULL
, 8);
1039 static int gitdiff_delete(struct apply_state
*state
,
1041 struct patch
*patch
)
1043 patch
->is_delete
= 1;
1044 free(patch
->old_name
);
1045 patch
->old_name
= xstrdup_or_null(patch
->def_name
);
1046 return gitdiff_oldmode(state
, line
, patch
);
1049 static int gitdiff_newfile(struct apply_state
*state
,
1051 struct patch
*patch
)
1054 free(patch
->new_name
);
1055 patch
->new_name
= xstrdup_or_null(patch
->def_name
);
1056 return gitdiff_newmode(state
, line
, patch
);
1059 static int gitdiff_copysrc(struct apply_state
*state
,
1061 struct patch
*patch
)
1064 free(patch
->old_name
);
1065 patch
->old_name
= find_name(state
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1069 static int gitdiff_copydst(struct apply_state
*state
,
1071 struct patch
*patch
)
1074 free(patch
->new_name
);
1075 patch
->new_name
= find_name(state
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1079 static int gitdiff_renamesrc(struct apply_state
*state
,
1081 struct patch
*patch
)
1083 patch
->is_rename
= 1;
1084 free(patch
->old_name
);
1085 patch
->old_name
= find_name(state
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1089 static int gitdiff_renamedst(struct apply_state
*state
,
1091 struct patch
*patch
)
1093 patch
->is_rename
= 1;
1094 free(patch
->new_name
);
1095 patch
->new_name
= find_name(state
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1099 static int gitdiff_similarity(struct apply_state
*state
,
1101 struct patch
*patch
)
1103 unsigned long val
= strtoul(line
, NULL
, 10);
1109 static int gitdiff_dissimilarity(struct apply_state
*state
,
1111 struct patch
*patch
)
1113 unsigned long val
= strtoul(line
, NULL
, 10);
1119 static int gitdiff_index(struct apply_state
*state
,
1121 struct patch
*patch
)
1124 * index line is N hexadecimal, "..", N hexadecimal,
1125 * and optional space with octal mode.
1127 const char *ptr
, *eol
;
1130 ptr
= strchr(line
, '.');
1131 if (!ptr
|| ptr
[1] != '.' || 40 < ptr
- line
)
1134 memcpy(patch
->old_sha1_prefix
, line
, len
);
1135 patch
->old_sha1_prefix
[len
] = 0;
1138 ptr
= strchr(line
, ' ');
1139 eol
= strchrnul(line
, '\n');
1141 if (!ptr
|| eol
< ptr
)
1147 memcpy(patch
->new_sha1_prefix
, line
, len
);
1148 patch
->new_sha1_prefix
[len
] = 0;
1150 patch
->old_mode
= strtoul(ptr
+1, NULL
, 8);
1155 * This is normal for a diff that doesn't change anything: we'll fall through
1156 * into the next diff. Tell the parser to break out.
1158 static int gitdiff_unrecognized(struct apply_state
*state
,
1160 struct patch
*patch
)
1166 * Skip p_value leading components from "line"; as we do not accept
1167 * absolute paths, return NULL in that case.
1169 static const char *skip_tree_prefix(struct apply_state
*state
,
1176 if (!state
->p_value
)
1177 return (llen
&& line
[0] == '/') ? NULL
: line
;
1179 nslash
= state
->p_value
;
1180 for (i
= 0; i
< llen
; i
++) {
1182 if (ch
== '/' && --nslash
<= 0)
1183 return (i
== 0) ? NULL
: &line
[i
+ 1];
1189 * This is to extract the same name that appears on "diff --git"
1190 * line. We do not find and return anything if it is a rename
1191 * patch, and it is OK because we will find the name elsewhere.
1192 * We need to reliably find name only when it is mode-change only,
1193 * creation or deletion of an empty file. In any of these cases,
1194 * both sides are the same name under a/ and b/ respectively.
1196 static char *git_header_name(struct apply_state
*state
,
1201 const char *second
= NULL
;
1202 size_t len
, line_len
;
1204 line
+= strlen("diff --git ");
1205 llen
-= strlen("diff --git ");
1209 struct strbuf first
= STRBUF_INIT
;
1210 struct strbuf sp
= STRBUF_INIT
;
1212 if (unquote_c_style(&first
, line
, &second
))
1213 goto free_and_fail1
;
1215 /* strip the a/b prefix including trailing slash */
1216 cp
= skip_tree_prefix(state
, first
.buf
, first
.len
);
1218 goto free_and_fail1
;
1219 strbuf_remove(&first
, 0, cp
- first
.buf
);
1222 * second points at one past closing dq of name.
1223 * find the second name.
1225 while ((second
< line
+ llen
) && isspace(*second
))
1228 if (line
+ llen
<= second
)
1229 goto free_and_fail1
;
1230 if (*second
== '"') {
1231 if (unquote_c_style(&sp
, second
, NULL
))
1232 goto free_and_fail1
;
1233 cp
= skip_tree_prefix(state
, sp
.buf
, sp
.len
);
1235 goto free_and_fail1
;
1236 /* They must match, otherwise ignore */
1237 if (strcmp(cp
, first
.buf
))
1238 goto free_and_fail1
;
1239 strbuf_release(&sp
);
1240 return strbuf_detach(&first
, NULL
);
1243 /* unquoted second */
1244 cp
= skip_tree_prefix(state
, second
, line
+ llen
- second
);
1246 goto free_and_fail1
;
1247 if (line
+ llen
- cp
!= first
.len
||
1248 memcmp(first
.buf
, cp
, first
.len
))
1249 goto free_and_fail1
;
1250 return strbuf_detach(&first
, NULL
);
1253 strbuf_release(&first
);
1254 strbuf_release(&sp
);
1258 /* unquoted first name */
1259 name
= skip_tree_prefix(state
, line
, llen
);
1264 * since the first name is unquoted, a dq if exists must be
1265 * the beginning of the second name.
1267 for (second
= name
; second
< line
+ llen
; second
++) {
1268 if (*second
== '"') {
1269 struct strbuf sp
= STRBUF_INIT
;
1272 if (unquote_c_style(&sp
, second
, NULL
))
1273 goto free_and_fail2
;
1275 np
= skip_tree_prefix(state
, sp
.buf
, sp
.len
);
1277 goto free_and_fail2
;
1279 len
= sp
.buf
+ sp
.len
- np
;
1280 if (len
< second
- name
&&
1281 !strncmp(np
, name
, len
) &&
1282 isspace(name
[len
])) {
1284 strbuf_remove(&sp
, 0, np
- sp
.buf
);
1285 return strbuf_detach(&sp
, NULL
);
1289 strbuf_release(&sp
);
1295 * Accept a name only if it shows up twice, exactly the same
1298 second
= strchr(name
, '\n');
1301 line_len
= second
- name
;
1302 for (len
= 0 ; ; len
++) {
1303 switch (name
[len
]) {
1308 case '\t': case ' ':
1310 * Is this the separator between the preimage
1311 * and the postimage pathname? Again, we are
1312 * only interested in the case where there is
1313 * no rename, as this is only to set def_name
1314 * and a rename patch has the names elsewhere
1315 * in an unambiguous form.
1318 return NULL
; /* no postimage name */
1319 second
= skip_tree_prefix(state
, name
+ len
+ 1,
1320 line_len
- (len
+ 1));
1324 * Does len bytes starting at "name" and "second"
1325 * (that are separated by one HT or SP we just
1326 * found) exactly match?
1328 if (second
[len
] == '\n' && !strncmp(name
, second
, len
))
1329 return xmemdupz(name
, len
);
1334 /* Verify that we recognize the lines following a git header */
1335 static int parse_git_header(struct apply_state
*state
,
1339 struct patch
*patch
)
1341 unsigned long offset
;
1343 /* A git diff has explicit new/delete information, so we don't guess */
1345 patch
->is_delete
= 0;
1348 * Some things may not have the old name in the
1349 * rest of the headers anywhere (pure mode changes,
1350 * or removing or adding empty files), so we get
1351 * the default name from the header.
1353 patch
->def_name
= git_header_name(state
, line
, len
);
1354 if (patch
->def_name
&& state
->root
.len
) {
1355 char *s
= xstrfmt("%s%s", state
->root
.buf
, patch
->def_name
);
1356 free(patch
->def_name
);
1357 patch
->def_name
= s
;
1363 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1364 static const struct opentry
{
1366 int (*fn
)(struct apply_state
*, const char *, struct patch
*);
1368 { "@@ -", gitdiff_hdrend
},
1369 { "--- ", gitdiff_oldname
},
1370 { "+++ ", gitdiff_newname
},
1371 { "old mode ", gitdiff_oldmode
},
1372 { "new mode ", gitdiff_newmode
},
1373 { "deleted file mode ", gitdiff_delete
},
1374 { "new file mode ", gitdiff_newfile
},
1375 { "copy from ", gitdiff_copysrc
},
1376 { "copy to ", gitdiff_copydst
},
1377 { "rename old ", gitdiff_renamesrc
},
1378 { "rename new ", gitdiff_renamedst
},
1379 { "rename from ", gitdiff_renamesrc
},
1380 { "rename to ", gitdiff_renamedst
},
1381 { "similarity index ", gitdiff_similarity
},
1382 { "dissimilarity index ", gitdiff_dissimilarity
},
1383 { "index ", gitdiff_index
},
1384 { "", gitdiff_unrecognized
},
1388 len
= linelen(line
, size
);
1389 if (!len
|| line
[len
-1] != '\n')
1391 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
1392 const struct opentry
*p
= optable
+ i
;
1393 int oplen
= strlen(p
->str
);
1394 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
1396 if (p
->fn(state
, line
+ oplen
, patch
) < 0)
1405 static int parse_num(const char *line
, unsigned long *p
)
1409 if (!isdigit(*line
))
1411 *p
= strtoul(line
, &ptr
, 10);
1415 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
1416 unsigned long *p1
, unsigned long *p2
)
1420 if (offset
< 0 || offset
>= len
)
1425 digits
= parse_num(line
, p1
);
1435 digits
= parse_num(line
+1, p2
);
1444 ex
= strlen(expect
);
1447 if (memcmp(line
, expect
, ex
))
1453 static void recount_diff(const char *line
, int size
, struct fragment
*fragment
)
1455 int oldlines
= 0, newlines
= 0, ret
= 0;
1458 warning("recount: ignore empty hunk");
1463 int len
= linelen(line
, size
);
1471 case ' ': case '\n':
1483 ret
= size
< 3 || !starts_with(line
, "@@ ");
1486 ret
= size
< 5 || !starts_with(line
, "diff ");
1493 warning(_("recount: unexpected line: %.*s"),
1494 (int)linelen(line
, size
), line
);
1499 fragment
->oldlines
= oldlines
;
1500 fragment
->newlines
= newlines
;
1504 * Parse a unified diff fragment header of the
1505 * form "@@ -a,b +c,d @@"
1507 static int parse_fragment_header(const char *line
, int len
, struct fragment
*fragment
)
1511 if (!len
|| line
[len
-1] != '\n')
1514 /* Figure out the number of lines in a fragment */
1515 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
1516 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
1521 static int find_header(struct apply_state
*state
,
1525 struct patch
*patch
)
1527 unsigned long offset
, len
;
1529 patch
->is_toplevel_relative
= 0;
1530 patch
->is_rename
= patch
->is_copy
= 0;
1531 patch
->is_new
= patch
->is_delete
= -1;
1532 patch
->old_mode
= patch
->new_mode
= 0;
1533 patch
->old_name
= patch
->new_name
= NULL
;
1534 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1535 unsigned long nextlen
;
1537 len
= linelen(line
, size
);
1541 /* Testing this early allows us to take a few shortcuts.. */
1546 * Make sure we don't find any unconnected patch fragments.
1547 * That's a sign that we didn't find a header, and that a
1548 * patch has become corrupted/broken up.
1550 if (!memcmp("@@ -", line
, 4)) {
1551 struct fragment dummy
;
1552 if (parse_fragment_header(line
, len
, &dummy
) < 0)
1554 die(_("patch fragment without header at line %d: %.*s"),
1555 state
->linenr
, (int)len
-1, line
);
1562 * Git patch? It might not have a real patch, just a rename
1563 * or mode change, so we handle that specially
1565 if (!memcmp("diff --git ", line
, 11)) {
1566 int git_hdr_len
= parse_git_header(state
, line
, len
, size
, patch
);
1567 if (git_hdr_len
<= len
)
1569 if (!patch
->old_name
&& !patch
->new_name
) {
1570 if (!patch
->def_name
)
1571 die(Q_("git diff header lacks filename information when removing "
1572 "%d leading pathname component (line %d)",
1573 "git diff header lacks filename information when removing "
1574 "%d leading pathname components (line %d)",
1576 state
->p_value
, state
->linenr
);
1577 patch
->old_name
= xstrdup(patch
->def_name
);
1578 patch
->new_name
= xstrdup(patch
->def_name
);
1580 if (!patch
->is_delete
&& !patch
->new_name
)
1581 die("git diff header lacks filename information "
1582 "(line %d)", state
->linenr
);
1583 patch
->is_toplevel_relative
= 1;
1584 *hdrsize
= git_hdr_len
;
1588 /* --- followed by +++ ? */
1589 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
1593 * We only accept unified patches, so we want it to
1594 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1595 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1597 nextlen
= linelen(line
+ len
, size
- len
);
1598 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
1601 /* Ok, we'll consider it a patch */
1602 parse_traditional_patch(state
, line
, line
+len
, patch
);
1603 *hdrsize
= len
+ nextlen
;
1610 static void record_ws_error(struct apply_state
*state
,
1621 state
->whitespace_error
++;
1622 if (state
->squelch_whitespace_errors
&&
1623 state
->squelch_whitespace_errors
< state
->whitespace_error
)
1626 err
= whitespace_error_string(result
);
1627 fprintf(stderr
, "%s:%d: %s.\n%.*s\n",
1628 state
->patch_input_file
, linenr
, err
, len
, line
);
1632 static void check_whitespace(struct apply_state
*state
,
1637 unsigned result
= ws_check(line
+ 1, len
- 1, ws_rule
);
1639 record_ws_error(state
, result
, line
+ 1, len
- 2, state
->linenr
);
1643 * Parse a unified diff. Note that this really needs to parse each
1644 * fragment separately, since the only way to know the difference
1645 * between a "---" that is part of a patch, and a "---" that starts
1646 * the next patch is to look at the line counts..
1648 static int parse_fragment(struct apply_state
*state
,
1651 struct patch
*patch
,
1652 struct fragment
*fragment
)
1655 int len
= linelen(line
, size
), offset
;
1656 unsigned long oldlines
, newlines
;
1657 unsigned long leading
, trailing
;
1659 offset
= parse_fragment_header(line
, len
, fragment
);
1662 if (offset
> 0 && patch
->recount
)
1663 recount_diff(line
+ offset
, size
- offset
, fragment
);
1664 oldlines
= fragment
->oldlines
;
1665 newlines
= fragment
->newlines
;
1669 /* Parse the thing.. */
1673 added
= deleted
= 0;
1676 offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1677 if (!oldlines
&& !newlines
)
1679 len
= linelen(line
, size
);
1680 if (!len
|| line
[len
-1] != '\n')
1685 case '\n': /* newer GNU diff, an empty context line */
1689 if (!deleted
&& !added
)
1692 if (!state
->apply_in_reverse
&&
1693 state
->ws_error_action
== correct_ws_error
)
1694 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1697 if (state
->apply_in_reverse
&&
1698 state
->ws_error_action
!= nowarn_ws_error
)
1699 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1705 if (!state
->apply_in_reverse
&&
1706 state
->ws_error_action
!= nowarn_ws_error
)
1707 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1714 * We allow "\ No newline at end of file". Depending
1715 * on locale settings when the patch was produced we
1716 * don't know what this line looks like. The only
1717 * thing we do know is that it begins with "\ ".
1718 * Checking for 12 is just for sanity check -- any
1719 * l10n of "\ No newline..." is at least that long.
1722 if (len
< 12 || memcmp(line
, "\\ ", 2))
1727 if (oldlines
|| newlines
)
1729 if (!deleted
&& !added
)
1732 fragment
->leading
= leading
;
1733 fragment
->trailing
= trailing
;
1736 * If a fragment ends with an incomplete line, we failed to include
1737 * it in the above loop because we hit oldlines == newlines == 0
1740 if (12 < size
&& !memcmp(line
, "\\ ", 2))
1741 offset
+= linelen(line
, size
);
1743 patch
->lines_added
+= added
;
1744 patch
->lines_deleted
+= deleted
;
1746 if (0 < patch
->is_new
&& oldlines
)
1747 return error(_("new file depends on old contents"));
1748 if (0 < patch
->is_delete
&& newlines
)
1749 return error(_("deleted file still has contents"));
1754 * We have seen "diff --git a/... b/..." header (or a traditional patch
1755 * header). Read hunks that belong to this patch into fragments and hang
1756 * them to the given patch structure.
1758 * The (fragment->patch, fragment->size) pair points into the memory given
1759 * by the caller, not a copy, when we return.
1761 static int parse_single_patch(struct apply_state
*state
,
1764 struct patch
*patch
)
1766 unsigned long offset
= 0;
1767 unsigned long oldlines
= 0, newlines
= 0, context
= 0;
1768 struct fragment
**fragp
= &patch
->fragments
;
1770 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
1771 struct fragment
*fragment
;
1774 fragment
= xcalloc(1, sizeof(*fragment
));
1775 fragment
->linenr
= state
->linenr
;
1776 len
= parse_fragment(state
, line
, size
, patch
, fragment
);
1778 die(_("corrupt patch at line %d"), state
->linenr
);
1779 fragment
->patch
= line
;
1780 fragment
->size
= len
;
1781 oldlines
+= fragment
->oldlines
;
1782 newlines
+= fragment
->newlines
;
1783 context
+= fragment
->leading
+ fragment
->trailing
;
1786 fragp
= &fragment
->next
;
1794 * If something was removed (i.e. we have old-lines) it cannot
1795 * be creation, and if something was added it cannot be
1796 * deletion. However, the reverse is not true; --unified=0
1797 * patches that only add are not necessarily creation even
1798 * though they do not have any old lines, and ones that only
1799 * delete are not necessarily deletion.
1801 * Unfortunately, a real creation/deletion patch do _not_ have
1802 * any context line by definition, so we cannot safely tell it
1803 * apart with --unified=0 insanity. At least if the patch has
1804 * more than one hunk it is not creation or deletion.
1806 if (patch
->is_new
< 0 &&
1807 (oldlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1809 if (patch
->is_delete
< 0 &&
1810 (newlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1811 patch
->is_delete
= 0;
1813 if (0 < patch
->is_new
&& oldlines
)
1814 die(_("new file %s depends on old contents"), patch
->new_name
);
1815 if (0 < patch
->is_delete
&& newlines
)
1816 die(_("deleted file %s still has contents"), patch
->old_name
);
1817 if (!patch
->is_delete
&& !newlines
&& context
)
1820 "file %s becomes empty but is not deleted"),
1826 static inline int metadata_changes(struct patch
*patch
)
1828 return patch
->is_rename
> 0 ||
1829 patch
->is_copy
> 0 ||
1830 patch
->is_new
> 0 ||
1832 (patch
->old_mode
&& patch
->new_mode
&&
1833 patch
->old_mode
!= patch
->new_mode
);
1836 static char *inflate_it(const void *data
, unsigned long size
,
1837 unsigned long inflated_size
)
1843 memset(&stream
, 0, sizeof(stream
));
1845 stream
.next_in
= (unsigned char *)data
;
1846 stream
.avail_in
= size
;
1847 stream
.next_out
= out
= xmalloc(inflated_size
);
1848 stream
.avail_out
= inflated_size
;
1849 git_inflate_init(&stream
);
1850 st
= git_inflate(&stream
, Z_FINISH
);
1851 git_inflate_end(&stream
);
1852 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1860 * Read a binary hunk and return a new fragment; fragment->patch
1861 * points at an allocated memory that the caller must free, so
1862 * it is marked as "->free_patch = 1".
1864 static struct fragment
*parse_binary_hunk(struct apply_state
*state
,
1866 unsigned long *sz_p
,
1871 * Expect a line that begins with binary patch method ("literal"
1872 * or "delta"), followed by the length of data before deflating.
1873 * a sequence of 'length-byte' followed by base-85 encoded data
1874 * should follow, terminated by a newline.
1876 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1877 * and we would limit the patch line to 66 characters,
1878 * so one line can fit up to 13 groups that would decode
1879 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1880 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1883 unsigned long size
= *sz_p
;
1884 char *buffer
= *buf_p
;
1886 unsigned long origlen
;
1889 struct fragment
*frag
;
1891 llen
= linelen(buffer
, size
);
1896 if (starts_with(buffer
, "delta ")) {
1897 patch_method
= BINARY_DELTA_DEFLATED
;
1898 origlen
= strtoul(buffer
+ 6, NULL
, 10);
1900 else if (starts_with(buffer
, "literal ")) {
1901 patch_method
= BINARY_LITERAL_DEFLATED
;
1902 origlen
= strtoul(buffer
+ 8, NULL
, 10);
1910 int byte_length
, max_byte_length
, newsize
;
1911 llen
= linelen(buffer
, size
);
1915 /* consume the blank line */
1921 * Minimum line is "A00000\n" which is 7-byte long,
1922 * and the line length must be multiple of 5 plus 2.
1924 if ((llen
< 7) || (llen
-2) % 5)
1926 max_byte_length
= (llen
- 2) / 5 * 4;
1927 byte_length
= *buffer
;
1928 if ('A' <= byte_length
&& byte_length
<= 'Z')
1929 byte_length
= byte_length
- 'A' + 1;
1930 else if ('a' <= byte_length
&& byte_length
<= 'z')
1931 byte_length
= byte_length
- 'a' + 27;
1934 /* if the input length was not multiple of 4, we would
1935 * have filler at the end but the filler should never
1938 if (max_byte_length
< byte_length
||
1939 byte_length
<= max_byte_length
- 4)
1941 newsize
= hunk_size
+ byte_length
;
1942 data
= xrealloc(data
, newsize
);
1943 if (decode_85(data
+ hunk_size
, buffer
+ 1, byte_length
))
1945 hunk_size
= newsize
;
1950 frag
= xcalloc(1, sizeof(*frag
));
1951 frag
->patch
= inflate_it(data
, hunk_size
, origlen
);
1952 frag
->free_patch
= 1;
1956 frag
->size
= origlen
;
1960 frag
->binary_patch_method
= patch_method
;
1966 error(_("corrupt binary patch at line %d: %.*s"),
1967 state
->linenr
-1, llen
-1, buffer
);
1973 * -1 in case of error,
1974 * the length of the parsed binary patch otherwise
1976 static int parse_binary(struct apply_state
*state
,
1979 struct patch
*patch
)
1982 * We have read "GIT binary patch\n"; what follows is a line
1983 * that says the patch method (currently, either "literal" or
1984 * "delta") and the length of data before deflating; a
1985 * sequence of 'length-byte' followed by base-85 encoded data
1988 * When a binary patch is reversible, there is another binary
1989 * hunk in the same format, starting with patch method (either
1990 * "literal" or "delta") with the length of data, and a sequence
1991 * of length-byte + base-85 encoded data, terminated with another
1992 * empty line. This data, when applied to the postimage, produces
1995 struct fragment
*forward
;
1996 struct fragment
*reverse
;
2000 forward
= parse_binary_hunk(state
, &buffer
, &size
, &status
, &used
);
2001 if (!forward
&& !status
)
2002 /* there has to be one hunk (forward hunk) */
2003 return error(_("unrecognized binary patch at line %d"), state
->linenr
-1);
2005 /* otherwise we already gave an error message */
2008 reverse
= parse_binary_hunk(state
, &buffer
, &size
, &status
, &used_1
);
2013 * Not having reverse hunk is not an error, but having
2014 * a corrupt reverse hunk is.
2016 free((void*) forward
->patch
);
2020 forward
->next
= reverse
;
2021 patch
->fragments
= forward
;
2022 patch
->is_binary
= 1;
2026 static void prefix_one(struct apply_state
*state
, char **name
)
2028 char *old_name
= *name
;
2031 *name
= xstrdup(prefix_filename(state
->prefix
, state
->prefix_length
, *name
));
2035 static void prefix_patch(struct apply_state
*state
, struct patch
*p
)
2037 if (!state
->prefix
|| p
->is_toplevel_relative
)
2039 prefix_one(state
, &p
->new_name
);
2040 prefix_one(state
, &p
->old_name
);
2047 static void add_name_limit(struct apply_state
*state
,
2051 struct string_list_item
*it
;
2053 it
= string_list_append(&state
->limit_by_name
, name
);
2054 it
->util
= exclude
? NULL
: (void *) 1;
2057 static int use_patch(struct apply_state
*state
, struct patch
*p
)
2059 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
2062 /* Paths outside are not touched regardless of "--include" */
2063 if (0 < state
->prefix_length
) {
2064 int pathlen
= strlen(pathname
);
2065 if (pathlen
<= state
->prefix_length
||
2066 memcmp(state
->prefix
, pathname
, state
->prefix_length
))
2070 /* See if it matches any of exclude/include rule */
2071 for (i
= 0; i
< state
->limit_by_name
.nr
; i
++) {
2072 struct string_list_item
*it
= &state
->limit_by_name
.items
[i
];
2073 if (!wildmatch(it
->string
, pathname
, 0, NULL
))
2074 return (it
->util
!= NULL
);
2078 * If we had any include, a path that does not match any rule is
2079 * not used. Otherwise, we saw bunch of exclude rules (or none)
2080 * and such a path is used.
2082 return !state
->has_include
;
2087 * Read the patch text in "buffer" that extends for "size" bytes; stop
2088 * reading after seeing a single patch (i.e. changes to a single file).
2089 * Create fragments (i.e. patch hunks) and hang them to the given patch.
2090 * Return the number of bytes consumed, so that the caller can call us
2091 * again for the next patch.
2093 static int parse_chunk(struct apply_state
*state
, char *buffer
, unsigned long size
, struct patch
*patch
)
2095 int hdrsize
, patchsize
;
2096 int offset
= find_header(state
, buffer
, size
, &hdrsize
, patch
);
2101 prefix_patch(state
, patch
);
2103 if (!use_patch(state
, patch
))
2106 patch
->ws_rule
= whitespace_rule(patch
->new_name
2110 patchsize
= parse_single_patch(state
,
2111 buffer
+ offset
+ hdrsize
,
2112 size
- offset
- hdrsize
,
2116 static const char git_binary
[] = "GIT binary patch\n";
2117 int hd
= hdrsize
+ offset
;
2118 unsigned long llen
= linelen(buffer
+ hd
, size
- hd
);
2120 if (llen
== sizeof(git_binary
) - 1 &&
2121 !memcmp(git_binary
, buffer
+ hd
, llen
)) {
2124 used
= parse_binary(state
, buffer
+ hd
+ llen
,
2125 size
- hd
- llen
, patch
);
2129 patchsize
= used
+ llen
;
2133 else if (!memcmp(" differ\n", buffer
+ hd
+ llen
- 8, 8)) {
2134 static const char *binhdr
[] = {
2140 for (i
= 0; binhdr
[i
]; i
++) {
2141 int len
= strlen(binhdr
[i
]);
2142 if (len
< size
- hd
&&
2143 !memcmp(binhdr
[i
], buffer
+ hd
, len
)) {
2145 patch
->is_binary
= 1;
2152 /* Empty patch cannot be applied if it is a text patch
2153 * without metadata change. A binary patch appears
2156 if ((state
->apply
|| state
->check
) &&
2157 (!patch
->is_binary
&& !metadata_changes(patch
)))
2158 die(_("patch with only garbage at line %d"), state
->linenr
);
2161 return offset
+ hdrsize
+ patchsize
;
2164 #define swap(a,b) myswap((a),(b),sizeof(a))
2166 #define myswap(a, b, size) do { \
2167 unsigned char mytmp[size]; \
2168 memcpy(mytmp, &a, size); \
2169 memcpy(&a, &b, size); \
2170 memcpy(&b, mytmp, size); \
2173 static void reverse_patches(struct patch
*p
)
2175 for (; p
; p
= p
->next
) {
2176 struct fragment
*frag
= p
->fragments
;
2178 swap(p
->new_name
, p
->old_name
);
2179 swap(p
->new_mode
, p
->old_mode
);
2180 swap(p
->is_new
, p
->is_delete
);
2181 swap(p
->lines_added
, p
->lines_deleted
);
2182 swap(p
->old_sha1_prefix
, p
->new_sha1_prefix
);
2184 for (; frag
; frag
= frag
->next
) {
2185 swap(frag
->newpos
, frag
->oldpos
);
2186 swap(frag
->newlines
, frag
->oldlines
);
2191 static const char pluses
[] =
2192 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2193 static const char minuses
[]=
2194 "----------------------------------------------------------------------";
2196 static void show_stats(struct apply_state
*state
, struct patch
*patch
)
2198 struct strbuf qname
= STRBUF_INIT
;
2199 char *cp
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
2202 quote_c_style(cp
, &qname
, NULL
, 0);
2205 * "scale" the filename
2207 max
= state
->max_len
;
2211 if (qname
.len
> max
) {
2212 cp
= strchr(qname
.buf
+ qname
.len
+ 3 - max
, '/');
2214 cp
= qname
.buf
+ qname
.len
+ 3 - max
;
2215 strbuf_splice(&qname
, 0, cp
- qname
.buf
, "...", 3);
2218 if (patch
->is_binary
) {
2219 printf(" %-*s | Bin\n", max
, qname
.buf
);
2220 strbuf_release(&qname
);
2224 printf(" %-*s |", max
, qname
.buf
);
2225 strbuf_release(&qname
);
2228 * scale the add/delete
2230 max
= max
+ state
->max_change
> 70 ? 70 - max
: state
->max_change
;
2231 add
= patch
->lines_added
;
2232 del
= patch
->lines_deleted
;
2234 if (state
->max_change
> 0) {
2235 int total
= ((add
+ del
) * max
+ state
->max_change
/ 2) / state
->max_change
;
2236 add
= (add
* max
+ state
->max_change
/ 2) / state
->max_change
;
2239 printf("%5d %.*s%.*s\n", patch
->lines_added
+ patch
->lines_deleted
,
2240 add
, pluses
, del
, minuses
);
2243 static int read_old_data(struct stat
*st
, const char *path
, struct strbuf
*buf
)
2245 switch (st
->st_mode
& S_IFMT
) {
2247 if (strbuf_readlink(buf
, path
, st
->st_size
) < 0)
2248 return error(_("unable to read symlink %s"), path
);
2251 if (strbuf_read_file(buf
, path
, st
->st_size
) != st
->st_size
)
2252 return error(_("unable to open or read %s"), path
);
2253 convert_to_git(path
, buf
->buf
, buf
->len
, buf
, 0);
2261 * Update the preimage, and the common lines in postimage,
2262 * from buffer buf of length len. If postlen is 0 the postimage
2263 * is updated in place, otherwise it's updated on a new buffer
2267 static void update_pre_post_images(struct image
*preimage
,
2268 struct image
*postimage
,
2270 size_t len
, size_t postlen
)
2272 int i
, ctx
, reduced
;
2273 char *new, *old
, *fixed
;
2274 struct image fixed_preimage
;
2277 * Update the preimage with whitespace fixes. Note that we
2278 * are not losing preimage->buf -- apply_one_fragment() will
2281 prepare_image(&fixed_preimage
, buf
, len
, 1);
2283 ? fixed_preimage
.nr
== preimage
->nr
2284 : fixed_preimage
.nr
<= preimage
->nr
);
2285 for (i
= 0; i
< fixed_preimage
.nr
; i
++)
2286 fixed_preimage
.line
[i
].flag
= preimage
->line
[i
].flag
;
2287 free(preimage
->line_allocated
);
2288 *preimage
= fixed_preimage
;
2291 * Adjust the common context lines in postimage. This can be
2292 * done in-place when we are shrinking it with whitespace
2293 * fixing, but needs a new buffer when ignoring whitespace or
2294 * expanding leading tabs to spaces.
2296 * We trust the caller to tell us if the update can be done
2297 * in place (postlen==0) or not.
2299 old
= postimage
->buf
;
2301 new = postimage
->buf
= xmalloc(postlen
);
2304 fixed
= preimage
->buf
;
2306 for (i
= reduced
= ctx
= 0; i
< postimage
->nr
; i
++) {
2307 size_t l_len
= postimage
->line
[i
].len
;
2308 if (!(postimage
->line
[i
].flag
& LINE_COMMON
)) {
2309 /* an added line -- no counterparts in preimage */
2310 memmove(new, old
, l_len
);
2316 /* a common context -- skip it in the original postimage */
2319 /* and find the corresponding one in the fixed preimage */
2320 while (ctx
< preimage
->nr
&&
2321 !(preimage
->line
[ctx
].flag
& LINE_COMMON
)) {
2322 fixed
+= preimage
->line
[ctx
].len
;
2327 * preimage is expected to run out, if the caller
2328 * fixed addition of trailing blank lines.
2330 if (preimage
->nr
<= ctx
) {
2335 /* and copy it in, while fixing the line length */
2336 l_len
= preimage
->line
[ctx
].len
;
2337 memcpy(new, fixed
, l_len
);
2340 postimage
->line
[i
].len
= l_len
;
2345 ? postlen
< new - postimage
->buf
2346 : postimage
->len
< new - postimage
->buf
)
2347 die("BUG: caller miscounted postlen: asked %d, orig = %d, used = %d",
2348 (int)postlen
, (int) postimage
->len
, (int)(new - postimage
->buf
));
2350 /* Fix the length of the whole thing */
2351 postimage
->len
= new - postimage
->buf
;
2352 postimage
->nr
-= reduced
;
2355 static int line_by_line_fuzzy_match(struct image
*img
,
2356 struct image
*preimage
,
2357 struct image
*postimage
,
2365 size_t postlen
= postimage
->len
;
2370 struct strbuf fixed
;
2374 for (i
= 0; i
< preimage_limit
; i
++) {
2375 size_t prelen
= preimage
->line
[i
].len
;
2376 size_t imglen
= img
->line
[try_lno
+i
].len
;
2378 if (!fuzzy_matchlines(img
->buf
+ try + imgoff
, imglen
,
2379 preimage
->buf
+ preoff
, prelen
))
2381 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2382 postlen
+= imglen
- prelen
;
2388 * Ok, the preimage matches with whitespace fuzz.
2390 * imgoff now holds the true length of the target that
2391 * matches the preimage before the end of the file.
2393 * Count the number of characters in the preimage that fall
2394 * beyond the end of the file and make sure that all of them
2395 * are whitespace characters. (This can only happen if
2396 * we are removing blank lines at the end of the file.)
2398 buf
= preimage_eof
= preimage
->buf
+ preoff
;
2399 for ( ; i
< preimage
->nr
; i
++)
2400 preoff
+= preimage
->line
[i
].len
;
2401 preimage_end
= preimage
->buf
+ preoff
;
2402 for ( ; buf
< preimage_end
; buf
++)
2407 * Update the preimage and the common postimage context
2408 * lines to use the same whitespace as the target.
2409 * If whitespace is missing in the target (i.e.
2410 * if the preimage extends beyond the end of the file),
2411 * use the whitespace from the preimage.
2413 extra_chars
= preimage_end
- preimage_eof
;
2414 strbuf_init(&fixed
, imgoff
+ extra_chars
);
2415 strbuf_add(&fixed
, img
->buf
+ try, imgoff
);
2416 strbuf_add(&fixed
, preimage_eof
, extra_chars
);
2417 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2418 update_pre_post_images(preimage
, postimage
,
2419 fixed_buf
, fixed_len
, postlen
);
2423 static int match_fragment(struct apply_state
*state
,
2425 struct image
*preimage
,
2426 struct image
*postimage
,
2430 int match_beginning
, int match_end
)
2433 char *fixed_buf
, *buf
, *orig
, *target
;
2434 struct strbuf fixed
;
2435 size_t fixed_len
, postlen
;
2438 if (preimage
->nr
+ try_lno
<= img
->nr
) {
2440 * The hunk falls within the boundaries of img.
2442 preimage_limit
= preimage
->nr
;
2443 if (match_end
&& (preimage
->nr
+ try_lno
!= img
->nr
))
2445 } else if (state
->ws_error_action
== correct_ws_error
&&
2446 (ws_rule
& WS_BLANK_AT_EOF
)) {
2448 * This hunk extends beyond the end of img, and we are
2449 * removing blank lines at the end of the file. This
2450 * many lines from the beginning of the preimage must
2451 * match with img, and the remainder of the preimage
2454 preimage_limit
= img
->nr
- try_lno
;
2457 * The hunk extends beyond the end of the img and
2458 * we are not removing blanks at the end, so we
2459 * should reject the hunk at this position.
2464 if (match_beginning
&& try_lno
)
2467 /* Quick hash check */
2468 for (i
= 0; i
< preimage_limit
; i
++)
2469 if ((img
->line
[try_lno
+ i
].flag
& LINE_PATCHED
) ||
2470 (preimage
->line
[i
].hash
!= img
->line
[try_lno
+ i
].hash
))
2473 if (preimage_limit
== preimage
->nr
) {
2475 * Do we have an exact match? If we were told to match
2476 * at the end, size must be exactly at try+fragsize,
2477 * otherwise try+fragsize must be still within the preimage,
2478 * and either case, the old piece should match the preimage
2482 ? (try + preimage
->len
== img
->len
)
2483 : (try + preimage
->len
<= img
->len
)) &&
2484 !memcmp(img
->buf
+ try, preimage
->buf
, preimage
->len
))
2488 * The preimage extends beyond the end of img, so
2489 * there cannot be an exact match.
2491 * There must be one non-blank context line that match
2492 * a line before the end of img.
2496 buf
= preimage
->buf
;
2498 for (i
= 0; i
< preimage_limit
; i
++)
2499 buf_end
+= preimage
->line
[i
].len
;
2501 for ( ; buf
< buf_end
; buf
++)
2509 * No exact match. If we are ignoring whitespace, run a line-by-line
2510 * fuzzy matching. We collect all the line length information because
2511 * we need it to adjust whitespace if we match.
2513 if (state
->ws_ignore_action
== ignore_ws_change
)
2514 return line_by_line_fuzzy_match(img
, preimage
, postimage
,
2515 try, try_lno
, preimage_limit
);
2517 if (state
->ws_error_action
!= correct_ws_error
)
2521 * The hunk does not apply byte-by-byte, but the hash says
2522 * it might with whitespace fuzz. We weren't asked to
2523 * ignore whitespace, we were asked to correct whitespace
2524 * errors, so let's try matching after whitespace correction.
2526 * While checking the preimage against the target, whitespace
2527 * errors in both fixed, we count how large the corresponding
2528 * postimage needs to be. The postimage prepared by
2529 * apply_one_fragment() has whitespace errors fixed on added
2530 * lines already, but the common lines were propagated as-is,
2531 * which may become longer when their whitespace errors are
2535 /* First count added lines in postimage */
2537 for (i
= 0; i
< postimage
->nr
; i
++) {
2538 if (!(postimage
->line
[i
].flag
& LINE_COMMON
))
2539 postlen
+= postimage
->line
[i
].len
;
2543 * The preimage may extend beyond the end of the file,
2544 * but in this loop we will only handle the part of the
2545 * preimage that falls within the file.
2547 strbuf_init(&fixed
, preimage
->len
+ 1);
2548 orig
= preimage
->buf
;
2549 target
= img
->buf
+ try;
2550 for (i
= 0; i
< preimage_limit
; i
++) {
2551 size_t oldlen
= preimage
->line
[i
].len
;
2552 size_t tgtlen
= img
->line
[try_lno
+ i
].len
;
2553 size_t fixstart
= fixed
.len
;
2554 struct strbuf tgtfix
;
2557 /* Try fixing the line in the preimage */
2558 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2560 /* Try fixing the line in the target */
2561 strbuf_init(&tgtfix
, tgtlen
);
2562 ws_fix_copy(&tgtfix
, target
, tgtlen
, ws_rule
, NULL
);
2565 * If they match, either the preimage was based on
2566 * a version before our tree fixed whitespace breakage,
2567 * or we are lacking a whitespace-fix patch the tree
2568 * the preimage was based on already had (i.e. target
2569 * has whitespace breakage, the preimage doesn't).
2570 * In either case, we are fixing the whitespace breakages
2571 * so we might as well take the fix together with their
2574 match
= (tgtfix
.len
== fixed
.len
- fixstart
&&
2575 !memcmp(tgtfix
.buf
, fixed
.buf
+ fixstart
,
2576 fixed
.len
- fixstart
));
2578 /* Add the length if this is common with the postimage */
2579 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2580 postlen
+= tgtfix
.len
;
2582 strbuf_release(&tgtfix
);
2592 * Now handle the lines in the preimage that falls beyond the
2593 * end of the file (if any). They will only match if they are
2594 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2597 for ( ; i
< preimage
->nr
; i
++) {
2598 size_t fixstart
= fixed
.len
; /* start of the fixed preimage */
2599 size_t oldlen
= preimage
->line
[i
].len
;
2602 /* Try fixing the line in the preimage */
2603 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2605 for (j
= fixstart
; j
< fixed
.len
; j
++)
2606 if (!isspace(fixed
.buf
[j
]))
2613 * Yes, the preimage is based on an older version that still
2614 * has whitespace breakages unfixed, and fixing them makes the
2615 * hunk match. Update the context lines in the postimage.
2617 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2618 if (postlen
< postimage
->len
)
2620 update_pre_post_images(preimage
, postimage
,
2621 fixed_buf
, fixed_len
, postlen
);
2625 strbuf_release(&fixed
);
2629 static int find_pos(struct apply_state
*state
,
2631 struct image
*preimage
,
2632 struct image
*postimage
,
2635 int match_beginning
, int match_end
)
2638 unsigned long backwards
, forwards
, try;
2639 int backwards_lno
, forwards_lno
, try_lno
;
2642 * If match_beginning or match_end is specified, there is no
2643 * point starting from a wrong line that will never match and
2644 * wander around and wait for a match at the specified end.
2646 if (match_beginning
)
2649 line
= img
->nr
- preimage
->nr
;
2652 * Because the comparison is unsigned, the following test
2653 * will also take care of a negative line number that can
2654 * result when match_end and preimage is larger than the target.
2656 if ((size_t) line
> img
->nr
)
2660 for (i
= 0; i
< line
; i
++)
2661 try += img
->line
[i
].len
;
2664 * There's probably some smart way to do this, but I'll leave
2665 * that to the smart and beautiful people. I'm simple and stupid.
2668 backwards_lno
= line
;
2670 forwards_lno
= line
;
2673 for (i
= 0; ; i
++) {
2674 if (match_fragment(state
, img
, preimage
, postimage
,
2675 try, try_lno
, ws_rule
,
2676 match_beginning
, match_end
))
2680 if (backwards_lno
== 0 && forwards_lno
== img
->nr
)
2684 if (backwards_lno
== 0) {
2689 backwards
-= img
->line
[backwards_lno
].len
;
2691 try_lno
= backwards_lno
;
2693 if (forwards_lno
== img
->nr
) {
2697 forwards
+= img
->line
[forwards_lno
].len
;
2700 try_lno
= forwards_lno
;
2707 static void remove_first_line(struct image
*img
)
2709 img
->buf
+= img
->line
[0].len
;
2710 img
->len
-= img
->line
[0].len
;
2715 static void remove_last_line(struct image
*img
)
2717 img
->len
-= img
->line
[--img
->nr
].len
;
2721 * The change from "preimage" and "postimage" has been found to
2722 * apply at applied_pos (counts in line numbers) in "img".
2723 * Update "img" to remove "preimage" and replace it with "postimage".
2725 static void update_image(struct apply_state
*state
,
2728 struct image
*preimage
,
2729 struct image
*postimage
)
2732 * remove the copy of preimage at offset in img
2733 * and replace it with postimage
2736 size_t remove_count
, insert_count
, applied_at
= 0;
2741 * If we are removing blank lines at the end of img,
2742 * the preimage may extend beyond the end.
2743 * If that is the case, we must be careful only to
2744 * remove the part of the preimage that falls within
2745 * the boundaries of img. Initialize preimage_limit
2746 * to the number of lines in the preimage that falls
2747 * within the boundaries.
2749 preimage_limit
= preimage
->nr
;
2750 if (preimage_limit
> img
->nr
- applied_pos
)
2751 preimage_limit
= img
->nr
- applied_pos
;
2753 for (i
= 0; i
< applied_pos
; i
++)
2754 applied_at
+= img
->line
[i
].len
;
2757 for (i
= 0; i
< preimage_limit
; i
++)
2758 remove_count
+= img
->line
[applied_pos
+ i
].len
;
2759 insert_count
= postimage
->len
;
2761 /* Adjust the contents */
2762 result
= xmalloc(st_add3(st_sub(img
->len
, remove_count
), insert_count
, 1));
2763 memcpy(result
, img
->buf
, applied_at
);
2764 memcpy(result
+ applied_at
, postimage
->buf
, postimage
->len
);
2765 memcpy(result
+ applied_at
+ postimage
->len
,
2766 img
->buf
+ (applied_at
+ remove_count
),
2767 img
->len
- (applied_at
+ remove_count
));
2770 img
->len
+= insert_count
- remove_count
;
2771 result
[img
->len
] = '\0';
2773 /* Adjust the line table */
2774 nr
= img
->nr
+ postimage
->nr
- preimage_limit
;
2775 if (preimage_limit
< postimage
->nr
) {
2777 * NOTE: this knows that we never call remove_first_line()
2778 * on anything other than pre/post image.
2780 REALLOC_ARRAY(img
->line
, nr
);
2781 img
->line_allocated
= img
->line
;
2783 if (preimage_limit
!= postimage
->nr
)
2784 memmove(img
->line
+ applied_pos
+ postimage
->nr
,
2785 img
->line
+ applied_pos
+ preimage_limit
,
2786 (img
->nr
- (applied_pos
+ preimage_limit
)) *
2787 sizeof(*img
->line
));
2788 memcpy(img
->line
+ applied_pos
,
2790 postimage
->nr
* sizeof(*img
->line
));
2791 if (!state
->allow_overlap
)
2792 for (i
= 0; i
< postimage
->nr
; i
++)
2793 img
->line
[applied_pos
+ i
].flag
|= LINE_PATCHED
;
2798 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2799 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2800 * replace the part of "img" with "postimage" text.
2802 static int apply_one_fragment(struct apply_state
*state
,
2803 struct image
*img
, struct fragment
*frag
,
2804 int inaccurate_eof
, unsigned ws_rule
,
2807 int match_beginning
, match_end
;
2808 const char *patch
= frag
->patch
;
2809 int size
= frag
->size
;
2810 char *old
, *oldlines
;
2811 struct strbuf newlines
;
2812 int new_blank_lines_at_end
= 0;
2813 int found_new_blank_lines_at_end
= 0;
2814 int hunk_linenr
= frag
->linenr
;
2815 unsigned long leading
, trailing
;
2816 int pos
, applied_pos
;
2817 struct image preimage
;
2818 struct image postimage
;
2820 memset(&preimage
, 0, sizeof(preimage
));
2821 memset(&postimage
, 0, sizeof(postimage
));
2822 oldlines
= xmalloc(size
);
2823 strbuf_init(&newlines
, size
);
2828 int len
= linelen(patch
, size
);
2830 int added_blank_line
= 0;
2831 int is_blank_context
= 0;
2838 * "plen" is how much of the line we should use for
2839 * the actual patch data. Normally we just remove the
2840 * first character on the line, but if the line is
2841 * followed by "\ No newline", then we also remove the
2842 * last one (which is the newline, of course).
2845 if (len
< size
&& patch
[len
] == '\\')
2848 if (state
->apply_in_reverse
) {
2851 else if (first
== '+')
2857 /* Newer GNU diff, empty context line */
2859 /* ... followed by '\No newline'; nothing */
2862 strbuf_addch(&newlines
, '\n');
2863 add_line_info(&preimage
, "\n", 1, LINE_COMMON
);
2864 add_line_info(&postimage
, "\n", 1, LINE_COMMON
);
2865 is_blank_context
= 1;
2868 if (plen
&& (ws_rule
& WS_BLANK_AT_EOF
) &&
2869 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2870 is_blank_context
= 1;
2872 memcpy(old
, patch
+ 1, plen
);
2873 add_line_info(&preimage
, old
, plen
,
2874 (first
== ' ' ? LINE_COMMON
: 0));
2878 /* Fall-through for ' ' */
2880 /* --no-add does not add new lines */
2881 if (first
== '+' && state
->no_add
)
2884 start
= newlines
.len
;
2886 !state
->whitespace_error
||
2887 state
->ws_error_action
!= correct_ws_error
) {
2888 strbuf_add(&newlines
, patch
+ 1, plen
);
2891 ws_fix_copy(&newlines
, patch
+ 1, plen
, ws_rule
, &state
->applied_after_fixing_ws
);
2893 add_line_info(&postimage
, newlines
.buf
+ start
, newlines
.len
- start
,
2894 (first
== '+' ? 0 : LINE_COMMON
));
2896 (ws_rule
& WS_BLANK_AT_EOF
) &&
2897 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2898 added_blank_line
= 1;
2900 case '@': case '\\':
2901 /* Ignore it, we already handled it */
2904 if (state
->apply_verbosely
)
2905 error(_("invalid start of line: '%c'"), first
);
2909 if (added_blank_line
) {
2910 if (!new_blank_lines_at_end
)
2911 found_new_blank_lines_at_end
= hunk_linenr
;
2912 new_blank_lines_at_end
++;
2914 else if (is_blank_context
)
2917 new_blank_lines_at_end
= 0;
2922 if (inaccurate_eof
&&
2923 old
> oldlines
&& old
[-1] == '\n' &&
2924 newlines
.len
> 0 && newlines
.buf
[newlines
.len
- 1] == '\n') {
2926 strbuf_setlen(&newlines
, newlines
.len
- 1);
2929 leading
= frag
->leading
;
2930 trailing
= frag
->trailing
;
2933 * A hunk to change lines at the beginning would begin with
2935 * but we need to be careful. -U0 that inserts before the second
2936 * line also has this pattern.
2938 * And a hunk to add to an empty file would begin with
2941 * In other words, a hunk that is (frag->oldpos <= 1) with or
2942 * without leading context must match at the beginning.
2944 match_beginning
= (!frag
->oldpos
||
2945 (frag
->oldpos
== 1 && !state
->unidiff_zero
));
2948 * A hunk without trailing lines must match at the end.
2949 * However, we simply cannot tell if a hunk must match end
2950 * from the lack of trailing lines if the patch was generated
2951 * with unidiff without any context.
2953 match_end
= !state
->unidiff_zero
&& !trailing
;
2955 pos
= frag
->newpos
? (frag
->newpos
- 1) : 0;
2956 preimage
.buf
= oldlines
;
2957 preimage
.len
= old
- oldlines
;
2958 postimage
.buf
= newlines
.buf
;
2959 postimage
.len
= newlines
.len
;
2960 preimage
.line
= preimage
.line_allocated
;
2961 postimage
.line
= postimage
.line_allocated
;
2965 applied_pos
= find_pos(state
, img
, &preimage
, &postimage
, pos
,
2966 ws_rule
, match_beginning
, match_end
);
2968 if (applied_pos
>= 0)
2971 /* Am I at my context limits? */
2972 if ((leading
<= state
->p_context
) && (trailing
<= state
->p_context
))
2974 if (match_beginning
|| match_end
) {
2975 match_beginning
= match_end
= 0;
2980 * Reduce the number of context lines; reduce both
2981 * leading and trailing if they are equal otherwise
2982 * just reduce the larger context.
2984 if (leading
>= trailing
) {
2985 remove_first_line(&preimage
);
2986 remove_first_line(&postimage
);
2990 if (trailing
> leading
) {
2991 remove_last_line(&preimage
);
2992 remove_last_line(&postimage
);
2997 if (applied_pos
>= 0) {
2998 if (new_blank_lines_at_end
&&
2999 preimage
.nr
+ applied_pos
>= img
->nr
&&
3000 (ws_rule
& WS_BLANK_AT_EOF
) &&
3001 state
->ws_error_action
!= nowarn_ws_error
) {
3002 record_ws_error(state
, WS_BLANK_AT_EOF
, "+", 1,
3003 found_new_blank_lines_at_end
);
3004 if (state
->ws_error_action
== correct_ws_error
) {
3005 while (new_blank_lines_at_end
--)
3006 remove_last_line(&postimage
);
3009 * We would want to prevent write_out_results()
3010 * from taking place in apply_patch() that follows
3011 * the callchain led us here, which is:
3012 * apply_patch->check_patch_list->check_patch->
3013 * apply_data->apply_fragments->apply_one_fragment
3015 if (state
->ws_error_action
== die_on_ws_error
)
3019 if (state
->apply_verbosely
&& applied_pos
!= pos
) {
3020 int offset
= applied_pos
- pos
;
3021 if (state
->apply_in_reverse
)
3022 offset
= 0 - offset
;
3024 Q_("Hunk #%d succeeded at %d (offset %d line).",
3025 "Hunk #%d succeeded at %d (offset %d lines).",
3027 nth_fragment
, applied_pos
+ 1, offset
);
3031 * Warn if it was necessary to reduce the number
3034 if ((leading
!= frag
->leading
) ||
3035 (trailing
!= frag
->trailing
))
3036 fprintf_ln(stderr
, _("Context reduced to (%ld/%ld)"
3037 " to apply fragment at %d"),
3038 leading
, trailing
, applied_pos
+1);
3039 update_image(state
, img
, applied_pos
, &preimage
, &postimage
);
3041 if (state
->apply_verbosely
)
3042 error(_("while searching for:\n%.*s"),
3043 (int)(old
- oldlines
), oldlines
);
3048 strbuf_release(&newlines
);
3049 free(preimage
.line_allocated
);
3050 free(postimage
.line_allocated
);
3052 return (applied_pos
< 0);
3055 static int apply_binary_fragment(struct apply_state
*state
,
3057 struct patch
*patch
)
3059 struct fragment
*fragment
= patch
->fragments
;
3064 return error(_("missing binary patch data for '%s'"),
3069 /* Binary patch is irreversible without the optional second hunk */
3070 if (state
->apply_in_reverse
) {
3071 if (!fragment
->next
)
3072 return error("cannot reverse-apply a binary patch "
3073 "without the reverse hunk to '%s'",
3075 ? patch
->new_name
: patch
->old_name
);
3076 fragment
= fragment
->next
;
3078 switch (fragment
->binary_patch_method
) {
3079 case BINARY_DELTA_DEFLATED
:
3080 dst
= patch_delta(img
->buf
, img
->len
, fragment
->patch
,
3081 fragment
->size
, &len
);
3088 case BINARY_LITERAL_DEFLATED
:
3090 img
->len
= fragment
->size
;
3091 img
->buf
= xmemdupz(fragment
->patch
, img
->len
);
3098 * Replace "img" with the result of applying the binary patch.
3099 * The binary patch data itself in patch->fragment is still kept
3100 * but the preimage prepared by the caller in "img" is freed here
3101 * or in the helper function apply_binary_fragment() this calls.
3103 static int apply_binary(struct apply_state
*state
,
3105 struct patch
*patch
)
3107 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3108 unsigned char sha1
[20];
3111 * For safety, we require patch index line to contain
3112 * full 40-byte textual SHA1 for old and new, at least for now.
3114 if (strlen(patch
->old_sha1_prefix
) != 40 ||
3115 strlen(patch
->new_sha1_prefix
) != 40 ||
3116 get_sha1_hex(patch
->old_sha1_prefix
, sha1
) ||
3117 get_sha1_hex(patch
->new_sha1_prefix
, sha1
))
3118 return error("cannot apply binary patch to '%s' "
3119 "without full index line", name
);
3121 if (patch
->old_name
) {
3123 * See if the old one matches what the patch
3126 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
3127 if (strcmp(sha1_to_hex(sha1
), patch
->old_sha1_prefix
))
3128 return error("the patch applies to '%s' (%s), "
3129 "which does not match the "
3130 "current contents.",
3131 name
, sha1_to_hex(sha1
));
3134 /* Otherwise, the old one must be empty. */
3136 return error("the patch applies to an empty "
3137 "'%s' but it is not empty", name
);
3140 get_sha1_hex(patch
->new_sha1_prefix
, sha1
);
3141 if (is_null_sha1(sha1
)) {
3143 return 0; /* deletion patch */
3146 if (has_sha1_file(sha1
)) {
3147 /* We already have the postimage */
3148 enum object_type type
;
3152 result
= read_sha1_file(sha1
, &type
, &size
);
3154 return error("the necessary postimage %s for "
3155 "'%s' cannot be read",
3156 patch
->new_sha1_prefix
, name
);
3162 * We have verified buf matches the preimage;
3163 * apply the patch data to it, which is stored
3164 * in the patch->fragments->{patch,size}.
3166 if (apply_binary_fragment(state
, img
, patch
))
3167 return error(_("binary patch does not apply to '%s'"),
3170 /* verify that the result matches */
3171 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
3172 if (strcmp(sha1_to_hex(sha1
), patch
->new_sha1_prefix
))
3173 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3174 name
, patch
->new_sha1_prefix
, sha1_to_hex(sha1
));
3180 static int apply_fragments(struct apply_state
*state
, struct image
*img
, struct patch
*patch
)
3182 struct fragment
*frag
= patch
->fragments
;
3183 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3184 unsigned ws_rule
= patch
->ws_rule
;
3185 unsigned inaccurate_eof
= patch
->inaccurate_eof
;
3188 if (patch
->is_binary
)
3189 return apply_binary(state
, img
, patch
);
3193 if (apply_one_fragment(state
, img
, frag
, inaccurate_eof
, ws_rule
, nth
)) {
3194 error(_("patch failed: %s:%ld"), name
, frag
->oldpos
);
3195 if (!state
->apply_with_reject
)
3204 static int read_blob_object(struct strbuf
*buf
, const unsigned char *sha1
, unsigned mode
)
3206 if (S_ISGITLINK(mode
)) {
3207 strbuf_grow(buf
, 100);
3208 strbuf_addf(buf
, "Subproject commit %s\n", sha1_to_hex(sha1
));
3210 enum object_type type
;
3214 result
= read_sha1_file(sha1
, &type
, &sz
);
3217 /* XXX read_sha1_file NUL-terminates */
3218 strbuf_attach(buf
, result
, sz
, sz
+ 1);
3223 static int read_file_or_gitlink(const struct cache_entry
*ce
, struct strbuf
*buf
)
3227 return read_blob_object(buf
, ce
->sha1
, ce
->ce_mode
);
3230 static struct patch
*in_fn_table(struct apply_state
*state
, const char *name
)
3232 struct string_list_item
*item
;
3237 item
= string_list_lookup(&state
->fn_table
, name
);
3239 return (struct patch
*)item
->util
;
3245 * item->util in the filename table records the status of the path.
3246 * Usually it points at a patch (whose result records the contents
3247 * of it after applying it), but it could be PATH_WAS_DELETED for a
3248 * path that a previously applied patch has already removed, or
3249 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3251 * The latter is needed to deal with a case where two paths A and B
3252 * are swapped by first renaming A to B and then renaming B to A;
3253 * moving A to B should not be prevented due to presence of B as we
3254 * will remove it in a later patch.
3256 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3257 #define PATH_WAS_DELETED ((struct patch *) -1)
3259 static int to_be_deleted(struct patch
*patch
)
3261 return patch
== PATH_TO_BE_DELETED
;
3264 static int was_deleted(struct patch
*patch
)
3266 return patch
== PATH_WAS_DELETED
;
3269 static void add_to_fn_table(struct apply_state
*state
, struct patch
*patch
)
3271 struct string_list_item
*item
;
3274 * Always add new_name unless patch is a deletion
3275 * This should cover the cases for normal diffs,
3276 * file creations and copies
3278 if (patch
->new_name
!= NULL
) {
3279 item
= string_list_insert(&state
->fn_table
, patch
->new_name
);
3284 * store a failure on rename/deletion cases because
3285 * later chunks shouldn't patch old names
3287 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3288 item
= string_list_insert(&state
->fn_table
, patch
->old_name
);
3289 item
->util
= PATH_WAS_DELETED
;
3293 static void prepare_fn_table(struct apply_state
*state
, struct patch
*patch
)
3296 * store information about incoming file deletion
3299 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3300 struct string_list_item
*item
;
3301 item
= string_list_insert(&state
->fn_table
, patch
->old_name
);
3302 item
->util
= PATH_TO_BE_DELETED
;
3304 patch
= patch
->next
;
3308 static int checkout_target(struct index_state
*istate
,
3309 struct cache_entry
*ce
, struct stat
*st
)
3311 struct checkout costate
;
3313 memset(&costate
, 0, sizeof(costate
));
3314 costate
.base_dir
= "";
3315 costate
.refresh_cache
= 1;
3316 costate
.istate
= istate
;
3317 if (checkout_entry(ce
, &costate
, NULL
) || lstat(ce
->name
, st
))
3318 return error(_("cannot checkout %s"), ce
->name
);
3322 static struct patch
*previous_patch(struct apply_state
*state
,
3323 struct patch
*patch
,
3326 struct patch
*previous
;
3329 if (patch
->is_copy
|| patch
->is_rename
)
3330 return NULL
; /* "git" patches do not depend on the order */
3332 previous
= in_fn_table(state
, patch
->old_name
);
3336 if (to_be_deleted(previous
))
3337 return NULL
; /* the deletion hasn't happened yet */
3339 if (was_deleted(previous
))
3345 static int verify_index_match(const struct cache_entry
*ce
, struct stat
*st
)
3347 if (S_ISGITLINK(ce
->ce_mode
)) {
3348 if (!S_ISDIR(st
->st_mode
))
3352 return ce_match_stat(ce
, st
, CE_MATCH_IGNORE_VALID
|CE_MATCH_IGNORE_SKIP_WORKTREE
);
3355 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3357 static int load_patch_target(struct apply_state
*state
,
3359 const struct cache_entry
*ce
,
3362 unsigned expected_mode
)
3364 if (state
->cached
|| state
->check_index
) {
3365 if (read_file_or_gitlink(ce
, buf
))
3366 return error(_("read of %s failed"), name
);
3368 if (S_ISGITLINK(expected_mode
)) {
3370 return read_file_or_gitlink(ce
, buf
);
3372 return SUBMODULE_PATCH_WITHOUT_INDEX
;
3373 } else if (has_symlink_leading_path(name
, strlen(name
))) {
3374 return error(_("reading from '%s' beyond a symbolic link"), name
);
3376 if (read_old_data(st
, name
, buf
))
3377 return error(_("read of %s failed"), name
);
3384 * We are about to apply "patch"; populate the "image" with the
3385 * current version we have, from the working tree or from the index,
3386 * depending on the situation e.g. --cached/--index. If we are
3387 * applying a non-git patch that incrementally updates the tree,
3388 * we read from the result of a previous diff.
3390 static int load_preimage(struct apply_state
*state
,
3391 struct image
*image
,
3392 struct patch
*patch
, struct stat
*st
,
3393 const struct cache_entry
*ce
)
3395 struct strbuf buf
= STRBUF_INIT
;
3398 struct patch
*previous
;
3401 previous
= previous_patch(state
, patch
, &status
);
3403 return error(_("path %s has been renamed/deleted"),
3406 /* We have a patched copy in memory; use that. */
3407 strbuf_add(&buf
, previous
->result
, previous
->resultsize
);
3409 status
= load_patch_target(state
, &buf
, ce
, st
,
3410 patch
->old_name
, patch
->old_mode
);
3413 else if (status
== SUBMODULE_PATCH_WITHOUT_INDEX
) {
3415 * There is no way to apply subproject
3416 * patch without looking at the index.
3417 * NEEDSWORK: shouldn't this be flagged
3420 free_fragment_list(patch
->fragments
);
3421 patch
->fragments
= NULL
;
3422 } else if (status
) {
3423 return error(_("read of %s failed"), patch
->old_name
);
3427 img
= strbuf_detach(&buf
, &len
);
3428 prepare_image(image
, img
, len
, !patch
->is_binary
);
3432 static int three_way_merge(struct image
*image
,
3434 const unsigned char *base
,
3435 const unsigned char *ours
,
3436 const unsigned char *theirs
)
3438 mmfile_t base_file
, our_file
, their_file
;
3439 mmbuffer_t result
= { NULL
};
3442 read_mmblob(&base_file
, base
);
3443 read_mmblob(&our_file
, ours
);
3444 read_mmblob(&their_file
, theirs
);
3445 status
= ll_merge(&result
, path
,
3448 &their_file
, "theirs", NULL
);
3449 free(base_file
.ptr
);
3451 free(their_file
.ptr
);
3452 if (status
< 0 || !result
.ptr
) {
3457 image
->buf
= result
.ptr
;
3458 image
->len
= result
.size
;
3464 * When directly falling back to add/add three-way merge, we read from
3465 * the current contents of the new_name. In no cases other than that
3466 * this function will be called.
3468 static int load_current(struct apply_state
*state
,
3469 struct image
*image
,
3470 struct patch
*patch
)
3472 struct strbuf buf
= STRBUF_INIT
;
3477 struct cache_entry
*ce
;
3478 char *name
= patch
->new_name
;
3479 unsigned mode
= patch
->new_mode
;
3482 die("BUG: patch to %s is not a creation", patch
->old_name
);
3484 pos
= cache_name_pos(name
, strlen(name
));
3486 return error(_("%s: does not exist in index"), name
);
3487 ce
= active_cache
[pos
];
3488 if (lstat(name
, &st
)) {
3489 if (errno
!= ENOENT
)
3490 return error(_("%s: %s"), name
, strerror(errno
));
3491 if (checkout_target(&the_index
, ce
, &st
))
3494 if (verify_index_match(ce
, &st
))
3495 return error(_("%s: does not match index"), name
);
3497 status
= load_patch_target(state
, &buf
, ce
, &st
, name
, mode
);
3502 img
= strbuf_detach(&buf
, &len
);
3503 prepare_image(image
, img
, len
, !patch
->is_binary
);
3507 static int try_threeway(struct apply_state
*state
,
3508 struct image
*image
,
3509 struct patch
*patch
,
3511 const struct cache_entry
*ce
)
3513 unsigned char pre_sha1
[20], post_sha1
[20], our_sha1
[20];
3514 struct strbuf buf
= STRBUF_INIT
;
3518 struct image tmp_image
;
3520 /* No point falling back to 3-way merge in these cases */
3521 if (patch
->is_delete
||
3522 S_ISGITLINK(patch
->old_mode
) || S_ISGITLINK(patch
->new_mode
))
3525 /* Preimage the patch was prepared for */
3527 write_sha1_file("", 0, blob_type
, pre_sha1
);
3528 else if (get_sha1(patch
->old_sha1_prefix
, pre_sha1
) ||
3529 read_blob_object(&buf
, pre_sha1
, patch
->old_mode
))
3530 return error("repository lacks the necessary blob to fall back on 3-way merge.");
3532 fprintf(stderr
, "Falling back to three-way merge...\n");
3534 img
= strbuf_detach(&buf
, &len
);
3535 prepare_image(&tmp_image
, img
, len
, 1);
3536 /* Apply the patch to get the post image */
3537 if (apply_fragments(state
, &tmp_image
, patch
) < 0) {
3538 clear_image(&tmp_image
);
3541 /* post_sha1[] is theirs */
3542 write_sha1_file(tmp_image
.buf
, tmp_image
.len
, blob_type
, post_sha1
);
3543 clear_image(&tmp_image
);
3545 /* our_sha1[] is ours */
3546 if (patch
->is_new
) {
3547 if (load_current(state
, &tmp_image
, patch
))
3548 return error("cannot read the current contents of '%s'",
3551 if (load_preimage(state
, &tmp_image
, patch
, st
, ce
))
3552 return error("cannot read the current contents of '%s'",
3555 write_sha1_file(tmp_image
.buf
, tmp_image
.len
, blob_type
, our_sha1
);
3556 clear_image(&tmp_image
);
3558 /* in-core three-way merge between post and our using pre as base */
3559 status
= three_way_merge(image
, patch
->new_name
,
3560 pre_sha1
, our_sha1
, post_sha1
);
3562 fprintf(stderr
, "Failed to fall back on three-way merge...\n");
3567 patch
->conflicted_threeway
= 1;
3569 oidclr(&patch
->threeway_stage
[0]);
3571 hashcpy(patch
->threeway_stage
[0].hash
, pre_sha1
);
3572 hashcpy(patch
->threeway_stage
[1].hash
, our_sha1
);
3573 hashcpy(patch
->threeway_stage
[2].hash
, post_sha1
);
3574 fprintf(stderr
, "Applied patch to '%s' with conflicts.\n", patch
->new_name
);
3576 fprintf(stderr
, "Applied patch to '%s' cleanly.\n", patch
->new_name
);
3581 static int apply_data(struct apply_state
*state
, struct patch
*patch
,
3582 struct stat
*st
, const struct cache_entry
*ce
)
3586 if (load_preimage(state
, &image
, patch
, st
, ce
) < 0)
3589 if (patch
->direct_to_threeway
||
3590 apply_fragments(state
, &image
, patch
) < 0) {
3591 /* Note: with --reject, apply_fragments() returns 0 */
3592 if (!state
->threeway
|| try_threeway(state
, &image
, patch
, st
, ce
) < 0)
3595 patch
->result
= image
.buf
;
3596 patch
->resultsize
= image
.len
;
3597 add_to_fn_table(state
, patch
);
3598 free(image
.line_allocated
);
3600 if (0 < patch
->is_delete
&& patch
->resultsize
)
3601 return error(_("removal patch leaves file contents"));
3607 * If "patch" that we are looking at modifies or deletes what we have,
3608 * we would want it not to lose any local modification we have, either
3609 * in the working tree or in the index.
3611 * This also decides if a non-git patch is a creation patch or a
3612 * modification to an existing empty file. We do not check the state
3613 * of the current tree for a creation patch in this function; the caller
3614 * check_patch() separately makes sure (and errors out otherwise) that
3615 * the path the patch creates does not exist in the current tree.
3617 static int check_preimage(struct apply_state
*state
,
3618 struct patch
*patch
,
3619 struct cache_entry
**ce
,
3622 const char *old_name
= patch
->old_name
;
3623 struct patch
*previous
= NULL
;
3624 int stat_ret
= 0, status
;
3625 unsigned st_mode
= 0;
3630 assert(patch
->is_new
<= 0);
3631 previous
= previous_patch(state
, patch
, &status
);
3634 return error(_("path %s has been renamed/deleted"), old_name
);
3636 st_mode
= previous
->new_mode
;
3637 } else if (!state
->cached
) {
3638 stat_ret
= lstat(old_name
, st
);
3639 if (stat_ret
&& errno
!= ENOENT
)
3640 return error(_("%s: %s"), old_name
, strerror(errno
));
3643 if (state
->check_index
&& !previous
) {
3644 int pos
= cache_name_pos(old_name
, strlen(old_name
));
3646 if (patch
->is_new
< 0)
3648 return error(_("%s: does not exist in index"), old_name
);
3650 *ce
= active_cache
[pos
];
3652 if (checkout_target(&the_index
, *ce
, st
))
3655 if (!state
->cached
&& verify_index_match(*ce
, st
))
3656 return error(_("%s: does not match index"), old_name
);
3658 st_mode
= (*ce
)->ce_mode
;
3659 } else if (stat_ret
< 0) {
3660 if (patch
->is_new
< 0)
3662 return error(_("%s: %s"), old_name
, strerror(errno
));
3665 if (!state
->cached
&& !previous
)
3666 st_mode
= ce_mode_from_stat(*ce
, st
->st_mode
);
3668 if (patch
->is_new
< 0)
3670 if (!patch
->old_mode
)
3671 patch
->old_mode
= st_mode
;
3672 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
3673 return error(_("%s: wrong type"), old_name
);
3674 if (st_mode
!= patch
->old_mode
)
3675 warning(_("%s has type %o, expected %o"),
3676 old_name
, st_mode
, patch
->old_mode
);
3677 if (!patch
->new_mode
&& !patch
->is_delete
)
3678 patch
->new_mode
= st_mode
;
3683 patch
->is_delete
= 0;
3684 free(patch
->old_name
);
3685 patch
->old_name
= NULL
;
3690 #define EXISTS_IN_INDEX 1
3691 #define EXISTS_IN_WORKTREE 2
3693 static int check_to_create(struct apply_state
*state
,
3694 const char *new_name
,
3699 if (state
->check_index
&&
3700 cache_name_pos(new_name
, strlen(new_name
)) >= 0 &&
3702 return EXISTS_IN_INDEX
;
3706 if (!lstat(new_name
, &nst
)) {
3707 if (S_ISDIR(nst
.st_mode
) || ok_if_exists
)
3710 * A leading component of new_name might be a symlink
3711 * that is going to be removed with this patch, but
3712 * still pointing at somewhere that has the path.
3713 * In such a case, path "new_name" does not exist as
3714 * far as git is concerned.
3716 if (has_symlink_leading_path(new_name
, strlen(new_name
)))
3719 return EXISTS_IN_WORKTREE
;
3720 } else if ((errno
!= ENOENT
) && (errno
!= ENOTDIR
)) {
3721 return error("%s: %s", new_name
, strerror(errno
));
3726 static uintptr_t register_symlink_changes(struct apply_state
*state
,
3730 struct string_list_item
*ent
;
3732 ent
= string_list_lookup(&state
->symlink_changes
, path
);
3734 ent
= string_list_insert(&state
->symlink_changes
, path
);
3735 ent
->util
= (void *)0;
3737 ent
->util
= (void *)(what
| ((uintptr_t)ent
->util
));
3738 return (uintptr_t)ent
->util
;
3741 static uintptr_t check_symlink_changes(struct apply_state
*state
, const char *path
)
3743 struct string_list_item
*ent
;
3745 ent
= string_list_lookup(&state
->symlink_changes
, path
);
3748 return (uintptr_t)ent
->util
;
3751 static void prepare_symlink_changes(struct apply_state
*state
, struct patch
*patch
)
3753 for ( ; patch
; patch
= patch
->next
) {
3754 if ((patch
->old_name
&& S_ISLNK(patch
->old_mode
)) &&
3755 (patch
->is_rename
|| patch
->is_delete
))
3756 /* the symlink at patch->old_name is removed */
3757 register_symlink_changes(state
, patch
->old_name
, SYMLINK_GOES_AWAY
);
3759 if (patch
->new_name
&& S_ISLNK(patch
->new_mode
))
3760 /* the symlink at patch->new_name is created or remains */
3761 register_symlink_changes(state
, patch
->new_name
, SYMLINK_IN_RESULT
);
3765 static int path_is_beyond_symlink_1(struct apply_state
*state
, struct strbuf
*name
)
3768 unsigned int change
;
3770 while (--name
->len
&& name
->buf
[name
->len
] != '/')
3771 ; /* scan backwards */
3774 name
->buf
[name
->len
] = '\0';
3775 change
= check_symlink_changes(state
, name
->buf
);
3776 if (change
& SYMLINK_IN_RESULT
)
3778 if (change
& SYMLINK_GOES_AWAY
)
3780 * This cannot be "return 0", because we may
3781 * see a new one created at a higher level.
3785 /* otherwise, check the preimage */
3786 if (state
->check_index
) {
3787 struct cache_entry
*ce
;
3789 ce
= cache_file_exists(name
->buf
, name
->len
, ignore_case
);
3790 if (ce
&& S_ISLNK(ce
->ce_mode
))
3794 if (!lstat(name
->buf
, &st
) && S_ISLNK(st
.st_mode
))
3801 static int path_is_beyond_symlink(struct apply_state
*state
, const char *name_
)
3804 struct strbuf name
= STRBUF_INIT
;
3806 assert(*name_
!= '\0');
3807 strbuf_addstr(&name
, name_
);
3808 ret
= path_is_beyond_symlink_1(state
, &name
);
3809 strbuf_release(&name
);
3814 static void die_on_unsafe_path(struct patch
*patch
)
3816 const char *old_name
= NULL
;
3817 const char *new_name
= NULL
;
3818 if (patch
->is_delete
)
3819 old_name
= patch
->old_name
;
3820 else if (!patch
->is_new
&& !patch
->is_copy
)
3821 old_name
= patch
->old_name
;
3822 if (!patch
->is_delete
)
3823 new_name
= patch
->new_name
;
3825 if (old_name
&& !verify_path(old_name
))
3826 die(_("invalid path '%s'"), old_name
);
3827 if (new_name
&& !verify_path(new_name
))
3828 die(_("invalid path '%s'"), new_name
);
3832 * Check and apply the patch in-core; leave the result in patch->result
3833 * for the caller to write it out to the final destination.
3835 static int check_patch(struct apply_state
*state
, struct patch
*patch
)
3838 const char *old_name
= patch
->old_name
;
3839 const char *new_name
= patch
->new_name
;
3840 const char *name
= old_name
? old_name
: new_name
;
3841 struct cache_entry
*ce
= NULL
;
3842 struct patch
*tpatch
;
3846 patch
->rejected
= 1; /* we will drop this after we succeed */
3848 status
= check_preimage(state
, patch
, &ce
, &st
);
3851 old_name
= patch
->old_name
;
3854 * A type-change diff is always split into a patch to delete
3855 * old, immediately followed by a patch to create new (see
3856 * diff.c::run_diff()); in such a case it is Ok that the entry
3857 * to be deleted by the previous patch is still in the working
3858 * tree and in the index.
3860 * A patch to swap-rename between A and B would first rename A
3861 * to B and then rename B to A. While applying the first one,
3862 * the presence of B should not stop A from getting renamed to
3863 * B; ask to_be_deleted() about the later rename. Removal of
3864 * B and rename from A to B is handled the same way by asking
3867 if ((tpatch
= in_fn_table(state
, new_name
)) &&
3868 (was_deleted(tpatch
) || to_be_deleted(tpatch
)))
3874 ((0 < patch
->is_new
) || patch
->is_rename
|| patch
->is_copy
)) {
3875 int err
= check_to_create(state
, new_name
, ok_if_exists
);
3877 if (err
&& state
->threeway
) {
3878 patch
->direct_to_threeway
= 1;
3879 } else switch (err
) {
3882 case EXISTS_IN_INDEX
:
3883 return error(_("%s: already exists in index"), new_name
);
3885 case EXISTS_IN_WORKTREE
:
3886 return error(_("%s: already exists in working directory"),
3892 if (!patch
->new_mode
) {
3893 if (0 < patch
->is_new
)
3894 patch
->new_mode
= S_IFREG
| 0644;
3896 patch
->new_mode
= patch
->old_mode
;
3900 if (new_name
&& old_name
) {
3901 int same
= !strcmp(old_name
, new_name
);
3902 if (!patch
->new_mode
)
3903 patch
->new_mode
= patch
->old_mode
;
3904 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
) {
3906 return error(_("new mode (%o) of %s does not "
3907 "match old mode (%o)"),
3908 patch
->new_mode
, new_name
,
3911 return error(_("new mode (%o) of %s does not "
3912 "match old mode (%o) of %s"),
3913 patch
->new_mode
, new_name
,
3914 patch
->old_mode
, old_name
);
3918 if (!state
->unsafe_paths
)
3919 die_on_unsafe_path(patch
);
3922 * An attempt to read from or delete a path that is beyond a
3923 * symbolic link will be prevented by load_patch_target() that
3924 * is called at the beginning of apply_data() so we do not
3925 * have to worry about a patch marked with "is_delete" bit
3926 * here. We however need to make sure that the patch result
3927 * is not deposited to a path that is beyond a symbolic link
3930 if (!patch
->is_delete
&& path_is_beyond_symlink(state
, patch
->new_name
))
3931 return error(_("affected file '%s' is beyond a symbolic link"),
3934 if (apply_data(state
, patch
, &st
, ce
) < 0)
3935 return error(_("%s: patch does not apply"), name
);
3936 patch
->rejected
= 0;
3940 static int check_patch_list(struct apply_state
*state
, struct patch
*patch
)
3944 prepare_symlink_changes(state
, patch
);
3945 prepare_fn_table(state
, patch
);
3947 if (state
->apply_verbosely
)
3948 say_patch_name(stderr
,
3949 _("Checking patch %s..."), patch
);
3950 err
|= check_patch(state
, patch
);
3951 patch
= patch
->next
;
3956 /* This function tries to read the sha1 from the current index */
3957 static int get_current_sha1(const char *path
, unsigned char *sha1
)
3961 if (read_cache() < 0)
3963 pos
= cache_name_pos(path
, strlen(path
));
3966 hashcpy(sha1
, active_cache
[pos
]->sha1
);
3970 static int preimage_sha1_in_gitlink_patch(struct patch
*p
, unsigned char sha1
[20])
3973 * A usable gitlink patch has only one fragment (hunk) that looks like:
3975 * -Subproject commit <old sha1>
3976 * +Subproject commit <new sha1>
3979 * -Subproject commit <old sha1>
3980 * for a removal patch.
3982 struct fragment
*hunk
= p
->fragments
;
3983 static const char heading
[] = "-Subproject commit ";
3986 if (/* does the patch have only one hunk? */
3987 hunk
&& !hunk
->next
&&
3988 /* is its preimage one line? */
3989 hunk
->oldpos
== 1 && hunk
->oldlines
== 1 &&
3990 /* does preimage begin with the heading? */
3991 (preimage
= memchr(hunk
->patch
, '\n', hunk
->size
)) != NULL
&&
3992 starts_with(++preimage
, heading
) &&
3993 /* does it record full SHA-1? */
3994 !get_sha1_hex(preimage
+ sizeof(heading
) - 1, sha1
) &&
3995 preimage
[sizeof(heading
) + 40 - 1] == '\n' &&
3996 /* does the abbreviated name on the index line agree with it? */
3997 starts_with(preimage
+ sizeof(heading
) - 1, p
->old_sha1_prefix
))
3998 return 0; /* it all looks fine */
4000 /* we may have full object name on the index line */
4001 return get_sha1_hex(p
->old_sha1_prefix
, sha1
);
4004 /* Build an index that contains the just the files needed for a 3way merge */
4005 static void build_fake_ancestor(struct patch
*list
, const char *filename
)
4007 struct patch
*patch
;
4008 struct index_state result
= { NULL
};
4009 static struct lock_file lock
;
4011 /* Once we start supporting the reverse patch, it may be
4012 * worth showing the new sha1 prefix, but until then...
4014 for (patch
= list
; patch
; patch
= patch
->next
) {
4015 unsigned char sha1
[20];
4016 struct cache_entry
*ce
;
4019 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
4020 if (0 < patch
->is_new
)
4023 if (S_ISGITLINK(patch
->old_mode
)) {
4024 if (!preimage_sha1_in_gitlink_patch(patch
, sha1
))
4025 ; /* ok, the textual part looks sane */
4027 die("sha1 information is lacking or useless for submodule %s",
4029 } else if (!get_sha1_blob(patch
->old_sha1_prefix
, sha1
)) {
4031 } else if (!patch
->lines_added
&& !patch
->lines_deleted
) {
4032 /* mode-only change: update the current */
4033 if (get_current_sha1(patch
->old_name
, sha1
))
4034 die("mode change for %s, which is not "
4035 "in current HEAD", name
);
4037 die("sha1 information is lacking or useless "
4040 ce
= make_cache_entry(patch
->old_mode
, sha1
, name
, 0, 0);
4042 die(_("make_cache_entry failed for path '%s'"), name
);
4043 if (add_index_entry(&result
, ce
, ADD_CACHE_OK_TO_ADD
))
4044 die ("Could not add %s to temporary index", name
);
4047 hold_lock_file_for_update(&lock
, filename
, LOCK_DIE_ON_ERROR
);
4048 if (write_locked_index(&result
, &lock
, COMMIT_LOCK
))
4049 die ("Could not write temporary index to %s", filename
);
4051 discard_index(&result
);
4054 static void stat_patch_list(struct apply_state
*state
, struct patch
*patch
)
4056 int files
, adds
, dels
;
4058 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
4060 adds
+= patch
->lines_added
;
4061 dels
+= patch
->lines_deleted
;
4062 show_stats(state
, patch
);
4065 print_stat_summary(stdout
, files
, adds
, dels
);
4068 static void numstat_patch_list(struct apply_state
*state
,
4069 struct patch
*patch
)
4071 for ( ; patch
; patch
= patch
->next
) {
4073 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
4074 if (patch
->is_binary
)
4077 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
4078 write_name_quoted(name
, stdout
, state
->line_termination
);
4082 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
4085 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
4087 printf(" %s %s\n", newdelete
, name
);
4090 static void show_mode_change(struct patch
*p
, int show_name
)
4092 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
4094 printf(" mode change %06o => %06o %s\n",
4095 p
->old_mode
, p
->new_mode
, p
->new_name
);
4097 printf(" mode change %06o => %06o\n",
4098 p
->old_mode
, p
->new_mode
);
4102 static void show_rename_copy(struct patch
*p
)
4104 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
4105 const char *old
, *new;
4107 /* Find common prefix */
4111 const char *slash_old
, *slash_new
;
4112 slash_old
= strchr(old
, '/');
4113 slash_new
= strchr(new, '/');
4116 slash_old
- old
!= slash_new
- new ||
4117 memcmp(old
, new, slash_new
- new))
4119 old
= slash_old
+ 1;
4120 new = slash_new
+ 1;
4122 /* p->old_name thru old is the common prefix, and old and new
4123 * through the end of names are renames
4125 if (old
!= p
->old_name
)
4126 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
4127 (int)(old
- p
->old_name
), p
->old_name
,
4128 old
, new, p
->score
);
4130 printf(" %s %s => %s (%d%%)\n", renamecopy
,
4131 p
->old_name
, p
->new_name
, p
->score
);
4132 show_mode_change(p
, 0);
4135 static void summary_patch_list(struct patch
*patch
)
4139 for (p
= patch
; p
; p
= p
->next
) {
4141 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
4142 else if (p
->is_delete
)
4143 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
4145 if (p
->is_rename
|| p
->is_copy
)
4146 show_rename_copy(p
);
4149 printf(" rewrite %s (%d%%)\n",
4150 p
->new_name
, p
->score
);
4151 show_mode_change(p
, 0);
4154 show_mode_change(p
, 1);
4160 static void patch_stats(struct apply_state
*state
, struct patch
*patch
)
4162 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
4164 if (lines
> state
->max_change
)
4165 state
->max_change
= lines
;
4166 if (patch
->old_name
) {
4167 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
4169 len
= strlen(patch
->old_name
);
4170 if (len
> state
->max_len
)
4171 state
->max_len
= len
;
4173 if (patch
->new_name
) {
4174 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
4176 len
= strlen(patch
->new_name
);
4177 if (len
> state
->max_len
)
4178 state
->max_len
= len
;
4182 static void remove_file(struct apply_state
*state
, struct patch
*patch
, int rmdir_empty
)
4184 if (state
->update_index
) {
4185 if (remove_file_from_cache(patch
->old_name
) < 0)
4186 die(_("unable to remove %s from index"), patch
->old_name
);
4188 if (!state
->cached
) {
4189 if (!remove_or_warn(patch
->old_mode
, patch
->old_name
) && rmdir_empty
) {
4190 remove_path(patch
->old_name
);
4195 static void add_index_file(struct apply_state
*state
,
4202 struct cache_entry
*ce
;
4203 int namelen
= strlen(path
);
4204 unsigned ce_size
= cache_entry_size(namelen
);
4206 if (!state
->update_index
)
4209 ce
= xcalloc(1, ce_size
);
4210 memcpy(ce
->name
, path
, namelen
);
4211 ce
->ce_mode
= create_ce_mode(mode
);
4212 ce
->ce_flags
= create_ce_flags(0);
4213 ce
->ce_namelen
= namelen
;
4214 if (S_ISGITLINK(mode
)) {
4217 if (!skip_prefix(buf
, "Subproject commit ", &s
) ||
4218 get_sha1_hex(s
, ce
->sha1
))
4219 die(_("corrupt patch for submodule %s"), path
);
4221 if (!state
->cached
) {
4222 if (lstat(path
, &st
) < 0)
4223 die_errno(_("unable to stat newly created file '%s'"),
4225 fill_stat_cache_info(ce
, &st
);
4227 if (write_sha1_file(buf
, size
, blob_type
, ce
->sha1
) < 0)
4228 die(_("unable to create backing store for newly created file %s"), path
);
4230 if (add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
) < 0)
4231 die(_("unable to add cache entry for %s"), path
);
4234 static int try_create_file(const char *path
, unsigned int mode
, const char *buf
, unsigned long size
)
4237 struct strbuf nbuf
= STRBUF_INIT
;
4239 if (S_ISGITLINK(mode
)) {
4241 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
))
4243 return mkdir(path
, 0777);
4246 if (has_symlinks
&& S_ISLNK(mode
))
4247 /* Although buf:size is counted string, it also is NUL
4250 return symlink(buf
, path
);
4252 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
4256 if (convert_to_working_tree(path
, buf
, size
, &nbuf
)) {
4260 write_or_die(fd
, buf
, size
);
4261 strbuf_release(&nbuf
);
4264 die_errno(_("closing file '%s'"), path
);
4269 * We optimistically assume that the directories exist,
4270 * which is true 99% of the time anyway. If they don't,
4271 * we create them and try again.
4273 static void create_one_file(struct apply_state
*state
,
4281 if (!try_create_file(path
, mode
, buf
, size
))
4284 if (errno
== ENOENT
) {
4285 if (safe_create_leading_directories(path
))
4287 if (!try_create_file(path
, mode
, buf
, size
))
4291 if (errno
== EEXIST
|| errno
== EACCES
) {
4292 /* We may be trying to create a file where a directory
4296 if (!lstat(path
, &st
) && (!S_ISDIR(st
.st_mode
) || !rmdir(path
)))
4300 if (errno
== EEXIST
) {
4301 unsigned int nr
= getpid();
4304 char newpath
[PATH_MAX
];
4305 mksnpath(newpath
, sizeof(newpath
), "%s~%u", path
, nr
);
4306 if (!try_create_file(newpath
, mode
, buf
, size
)) {
4307 if (!rename(newpath
, path
))
4309 unlink_or_warn(newpath
);
4312 if (errno
!= EEXIST
)
4317 die_errno(_("unable to write file '%s' mode %o"), path
, mode
);
4320 static void add_conflicted_stages_file(struct apply_state
*state
,
4321 struct patch
*patch
)
4324 unsigned ce_size
, mode
;
4325 struct cache_entry
*ce
;
4327 if (!state
->update_index
)
4329 namelen
= strlen(patch
->new_name
);
4330 ce_size
= cache_entry_size(namelen
);
4331 mode
= patch
->new_mode
? patch
->new_mode
: (S_IFREG
| 0644);
4333 remove_file_from_cache(patch
->new_name
);
4334 for (stage
= 1; stage
< 4; stage
++) {
4335 if (is_null_oid(&patch
->threeway_stage
[stage
- 1]))
4337 ce
= xcalloc(1, ce_size
);
4338 memcpy(ce
->name
, patch
->new_name
, namelen
);
4339 ce
->ce_mode
= create_ce_mode(mode
);
4340 ce
->ce_flags
= create_ce_flags(stage
);
4341 ce
->ce_namelen
= namelen
;
4342 hashcpy(ce
->sha1
, patch
->threeway_stage
[stage
- 1].hash
);
4343 if (add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
) < 0)
4344 die(_("unable to add cache entry for %s"), patch
->new_name
);
4348 static void create_file(struct apply_state
*state
, struct patch
*patch
)
4350 char *path
= patch
->new_name
;
4351 unsigned mode
= patch
->new_mode
;
4352 unsigned long size
= patch
->resultsize
;
4353 char *buf
= patch
->result
;
4356 mode
= S_IFREG
| 0644;
4357 create_one_file(state
, path
, mode
, buf
, size
);
4359 if (patch
->conflicted_threeway
)
4360 add_conflicted_stages_file(state
, patch
);
4362 add_index_file(state
, path
, mode
, buf
, size
);
4365 /* phase zero is to remove, phase one is to create */
4366 static void write_out_one_result(struct apply_state
*state
,
4367 struct patch
*patch
,
4370 if (patch
->is_delete
> 0) {
4372 remove_file(state
, patch
, 1);
4375 if (patch
->is_new
> 0 || patch
->is_copy
) {
4377 create_file(state
, patch
);
4381 * Rename or modification boils down to the same
4382 * thing: remove the old, write the new
4385 remove_file(state
, patch
, patch
->is_rename
);
4387 create_file(state
, patch
);
4390 static int write_out_one_reject(struct apply_state
*state
, struct patch
*patch
)
4393 char namebuf
[PATH_MAX
];
4394 struct fragment
*frag
;
4396 struct strbuf sb
= STRBUF_INIT
;
4398 for (cnt
= 0, frag
= patch
->fragments
; frag
; frag
= frag
->next
) {
4399 if (!frag
->rejected
)
4405 if (state
->apply_verbosely
)
4406 say_patch_name(stderr
,
4407 _("Applied patch %s cleanly."), patch
);
4411 /* This should not happen, because a removal patch that leaves
4412 * contents are marked "rejected" at the patch level.
4414 if (!patch
->new_name
)
4415 die(_("internal error"));
4417 /* Say this even without --verbose */
4418 strbuf_addf(&sb
, Q_("Applying patch %%s with %d reject...",
4419 "Applying patch %%s with %d rejects...",
4422 say_patch_name(stderr
, sb
.buf
, patch
);
4423 strbuf_release(&sb
);
4425 cnt
= strlen(patch
->new_name
);
4426 if (ARRAY_SIZE(namebuf
) <= cnt
+ 5) {
4427 cnt
= ARRAY_SIZE(namebuf
) - 5;
4428 warning(_("truncating .rej filename to %.*s.rej"),
4429 cnt
- 1, patch
->new_name
);
4431 memcpy(namebuf
, patch
->new_name
, cnt
);
4432 memcpy(namebuf
+ cnt
, ".rej", 5);
4434 rej
= fopen(namebuf
, "w");
4436 return error(_("cannot open %s: %s"), namebuf
, strerror(errno
));
4438 /* Normal git tools never deal with .rej, so do not pretend
4439 * this is a git patch by saying --git or giving extended
4440 * headers. While at it, maybe please "kompare" that wants
4441 * the trailing TAB and some garbage at the end of line ;-).
4443 fprintf(rej
, "diff a/%s b/%s\t(rejected hunks)\n",
4444 patch
->new_name
, patch
->new_name
);
4445 for (cnt
= 1, frag
= patch
->fragments
;
4447 cnt
++, frag
= frag
->next
) {
4448 if (!frag
->rejected
) {
4449 fprintf_ln(stderr
, _("Hunk #%d applied cleanly."), cnt
);
4452 fprintf_ln(stderr
, _("Rejected hunk #%d."), cnt
);
4453 fprintf(rej
, "%.*s", frag
->size
, frag
->patch
);
4454 if (frag
->patch
[frag
->size
-1] != '\n')
4461 static int write_out_results(struct apply_state
*state
, struct patch
*list
)
4466 struct string_list cpath
= STRING_LIST_INIT_DUP
;
4468 for (phase
= 0; phase
< 2; phase
++) {
4474 write_out_one_result(state
, l
, phase
);
4476 if (write_out_one_reject(state
, l
))
4478 if (l
->conflicted_threeway
) {
4479 string_list_append(&cpath
, l
->new_name
);
4489 struct string_list_item
*item
;
4491 string_list_sort(&cpath
);
4492 for_each_string_list_item(item
, &cpath
)
4493 fprintf(stderr
, "U %s\n", item
->string
);
4494 string_list_clear(&cpath
, 0);
4502 static struct lock_file lock_file
;
4504 #define INACCURATE_EOF (1<<0)
4505 #define RECOUNT (1<<1)
4507 static int apply_patch(struct apply_state
*state
,
4509 const char *filename
,
4513 struct strbuf buf
= STRBUF_INIT
; /* owns the patch text */
4514 struct patch
*list
= NULL
, **listp
= &list
;
4515 int skipped_patch
= 0;
4517 state
->patch_input_file
= filename
;
4518 read_patch_file(&buf
, fd
);
4520 while (offset
< buf
.len
) {
4521 struct patch
*patch
;
4524 patch
= xcalloc(1, sizeof(*patch
));
4525 patch
->inaccurate_eof
= !!(options
& INACCURATE_EOF
);
4526 patch
->recount
= !!(options
& RECOUNT
);
4527 nr
= parse_chunk(state
, buf
.buf
+ offset
, buf
.len
- offset
, patch
);
4532 if (state
->apply_in_reverse
)
4533 reverse_patches(patch
);
4534 if (use_patch(state
, patch
)) {
4535 patch_stats(state
, patch
);
4537 listp
= &patch
->next
;
4540 if (state
->apply_verbosely
)
4541 say_patch_name(stderr
, _("Skipped patch '%s'."), patch
);
4548 if (!list
&& !skipped_patch
)
4549 die(_("unrecognized input"));
4551 if (state
->whitespace_error
&& (state
->ws_error_action
== die_on_ws_error
))
4554 state
->update_index
= state
->check_index
&& state
->apply
;
4555 if (state
->update_index
&& newfd
< 0)
4556 newfd
= hold_locked_index(state
->lock_file
, 1);
4558 if (state
->check_index
) {
4559 if (read_cache() < 0)
4560 die(_("unable to read index file"));
4563 if ((state
->check
|| state
->apply
) &&
4564 check_patch_list(state
, list
) < 0 &&
4565 !state
->apply_with_reject
)
4568 if (state
->apply
&& write_out_results(state
, list
)) {
4569 if (state
->apply_with_reject
)
4571 /* with --3way, we still need to write the index out */
4575 if (state
->fake_ancestor
)
4576 build_fake_ancestor(list
, state
->fake_ancestor
);
4578 if (state
->diffstat
)
4579 stat_patch_list(state
, list
);
4582 numstat_patch_list(state
, list
);
4585 summary_patch_list(list
);
4587 free_patch_list(list
);
4588 strbuf_release(&buf
);
4589 string_list_clear(&state
->fn_table
, 0);
4593 static void git_apply_config(void)
4595 git_config_get_string_const("apply.whitespace", &apply_default_whitespace
);
4596 git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace
);
4597 git_config(git_default_config
, NULL
);
4600 static int option_parse_exclude(const struct option
*opt
,
4601 const char *arg
, int unset
)
4603 struct apply_state
*state
= opt
->value
;
4604 add_name_limit(state
, arg
, 1);
4608 static int option_parse_include(const struct option
*opt
,
4609 const char *arg
, int unset
)
4611 struct apply_state
*state
= opt
->value
;
4612 add_name_limit(state
, arg
, 0);
4613 state
->has_include
= 1;
4617 static int option_parse_p(const struct option
*opt
,
4621 struct apply_state
*state
= opt
->value
;
4622 state
->p_value
= atoi(arg
);
4623 state
->p_value_known
= 1;
4627 static int option_parse_space_change(const struct option
*opt
,
4628 const char *arg
, int unset
)
4630 struct apply_state
*state
= opt
->value
;
4632 state
->ws_ignore_action
= ignore_ws_none
;
4634 state
->ws_ignore_action
= ignore_ws_change
;
4638 static int option_parse_whitespace(const struct option
*opt
,
4639 const char *arg
, int unset
)
4641 struct apply_state
*state
= opt
->value
;
4642 state
->whitespace_option
= arg
;
4643 parse_whitespace_option(state
, arg
);
4647 static int option_parse_directory(const struct option
*opt
,
4648 const char *arg
, int unset
)
4650 struct apply_state
*state
= opt
->value
;
4651 strbuf_reset(&state
->root
);
4652 strbuf_addstr(&state
->root
, arg
);
4653 strbuf_complete(&state
->root
, '/');
4657 static void init_apply_state(struct apply_state
*state
,
4659 struct lock_file
*lock_file
)
4661 memset(state
, 0, sizeof(*state
));
4662 state
->prefix
= prefix
;
4663 state
->prefix_length
= state
->prefix
? strlen(state
->prefix
) : 0;
4664 state
->lock_file
= lock_file
;
4666 state
->line_termination
= '\n';
4668 state
->p_context
= UINT_MAX
;
4669 state
->squelch_whitespace_errors
= 5;
4670 state
->ws_error_action
= warn_on_ws_error
;
4671 state
->ws_ignore_action
= ignore_ws_none
;
4673 strbuf_init(&state
->root
, 0);
4676 if (apply_default_whitespace
)
4677 parse_whitespace_option(state
, apply_default_whitespace
);
4678 if (apply_default_ignorewhitespace
)
4679 parse_ignorewhitespace_option(state
, apply_default_ignorewhitespace
);
4682 static void clear_apply_state(struct apply_state
*state
)
4684 string_list_clear(&state
->limit_by_name
, 0);
4685 string_list_clear(&state
->symlink_changes
, 0);
4686 strbuf_release(&state
->root
);
4688 /* &state->fn_table is cleared at the end of apply_patch() */
4691 static void check_apply_state(struct apply_state
*state
, int force_apply
)
4693 int is_not_gitdir
= !startup_info
->have_repository
;
4695 if (state
->apply_with_reject
&& state
->threeway
)
4696 die("--reject and --3way cannot be used together.");
4697 if (state
->cached
&& state
->threeway
)
4698 die("--cached and --3way cannot be used together.");
4699 if (state
->threeway
) {
4701 die(_("--3way outside a repository"));
4702 state
->check_index
= 1;
4704 if (state
->apply_with_reject
)
4705 state
->apply
= state
->apply_verbosely
= 1;
4706 if (!force_apply
&& (state
->diffstat
|| state
->numstat
|| state
->summary
|| state
->check
|| state
->fake_ancestor
))
4708 if (state
->check_index
&& is_not_gitdir
)
4709 die(_("--index outside a repository"));
4710 if (state
->cached
) {
4712 die(_("--cached outside a repository"));
4713 state
->check_index
= 1;
4715 if (state
->check_index
)
4716 state
->unsafe_paths
= 0;
4717 if (!state
->lock_file
)
4718 die("BUG: state->lock_file should not be NULL");
4721 static int apply_all_patches(struct apply_state
*state
,
4730 for (i
= 0; i
< argc
; i
++) {
4731 const char *arg
= argv
[i
];
4734 if (!strcmp(arg
, "-")) {
4735 errs
|= apply_patch(state
, 0, "<stdin>", options
);
4738 } else if (0 < state
->prefix_length
)
4739 arg
= prefix_filename(state
->prefix
,
4740 state
->prefix_length
,
4743 fd
= open(arg
, O_RDONLY
);
4745 die_errno(_("can't open patch '%s'"), arg
);
4747 set_default_whitespace_mode(state
);
4748 errs
|= apply_patch(state
, fd
, arg
, options
);
4751 set_default_whitespace_mode(state
);
4753 errs
|= apply_patch(state
, 0, "<stdin>", options
);
4755 if (state
->whitespace_error
) {
4756 if (state
->squelch_whitespace_errors
&&
4757 state
->squelch_whitespace_errors
< state
->whitespace_error
) {
4759 state
->whitespace_error
- state
->squelch_whitespace_errors
;
4760 warning(Q_("squelched %d whitespace error",
4761 "squelched %d whitespace errors",
4765 if (state
->ws_error_action
== die_on_ws_error
)
4766 die(Q_("%d line adds whitespace errors.",
4767 "%d lines add whitespace errors.",
4768 state
->whitespace_error
),
4769 state
->whitespace_error
);
4770 if (state
->applied_after_fixing_ws
&& state
->apply
)
4771 warning("%d line%s applied after"
4772 " fixing whitespace errors.",
4773 state
->applied_after_fixing_ws
,
4774 state
->applied_after_fixing_ws
== 1 ? "" : "s");
4775 else if (state
->whitespace_error
)
4776 warning(Q_("%d line adds whitespace errors.",
4777 "%d lines add whitespace errors.",
4778 state
->whitespace_error
),
4779 state
->whitespace_error
);
4782 if (state
->update_index
) {
4783 if (write_locked_index(&the_index
, state
->lock_file
, COMMIT_LOCK
))
4784 die(_("Unable to write new index file"));
4790 int cmd_apply(int argc
, const char **argv
, const char *prefix
)
4792 int force_apply
= 0;
4795 struct apply_state state
;
4797 struct option builtin_apply_options
[] = {
4798 { OPTION_CALLBACK
, 0, "exclude", &state
, N_("path"),
4799 N_("don't apply changes matching the given path"),
4800 0, option_parse_exclude
},
4801 { OPTION_CALLBACK
, 0, "include", &state
, N_("path"),
4802 N_("apply changes matching the given path"),
4803 0, option_parse_include
},
4804 { OPTION_CALLBACK
, 'p', NULL
, &state
, N_("num"),
4805 N_("remove <num> leading slashes from traditional diff paths"),
4806 0, option_parse_p
},
4807 OPT_BOOL(0, "no-add", &state
.no_add
,
4808 N_("ignore additions made by the patch")),
4809 OPT_BOOL(0, "stat", &state
.diffstat
,
4810 N_("instead of applying the patch, output diffstat for the input")),
4811 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
4812 OPT_NOOP_NOARG(0, "binary"),
4813 OPT_BOOL(0, "numstat", &state
.numstat
,
4814 N_("show number of added and deleted lines in decimal notation")),
4815 OPT_BOOL(0, "summary", &state
.summary
,
4816 N_("instead of applying the patch, output a summary for the input")),
4817 OPT_BOOL(0, "check", &state
.check
,
4818 N_("instead of applying the patch, see if the patch is applicable")),
4819 OPT_BOOL(0, "index", &state
.check_index
,
4820 N_("make sure the patch is applicable to the current index")),
4821 OPT_BOOL(0, "cached", &state
.cached
,
4822 N_("apply a patch without touching the working tree")),
4823 OPT_BOOL(0, "unsafe-paths", &state
.unsafe_paths
,
4824 N_("accept a patch that touches outside the working area")),
4825 OPT_BOOL(0, "apply", &force_apply
,
4826 N_("also apply the patch (use with --stat/--summary/--check)")),
4827 OPT_BOOL('3', "3way", &state
.threeway
,
4828 N_( "attempt three-way merge if a patch does not apply")),
4829 OPT_FILENAME(0, "build-fake-ancestor", &state
.fake_ancestor
,
4830 N_("build a temporary index based on embedded index information")),
4831 /* Think twice before adding "--nul" synonym to this */
4832 OPT_SET_INT('z', NULL
, &state
.line_termination
,
4833 N_("paths are separated with NUL character"), '\0'),
4834 OPT_INTEGER('C', NULL
, &state
.p_context
,
4835 N_("ensure at least <n> lines of context match")),
4836 { OPTION_CALLBACK
, 0, "whitespace", &state
, N_("action"),
4837 N_("detect new or modified lines that have whitespace errors"),
4838 0, option_parse_whitespace
},
4839 { OPTION_CALLBACK
, 0, "ignore-space-change", &state
, NULL
,
4840 N_("ignore changes in whitespace when finding context"),
4841 PARSE_OPT_NOARG
, option_parse_space_change
},
4842 { OPTION_CALLBACK
, 0, "ignore-whitespace", &state
, NULL
,
4843 N_("ignore changes in whitespace when finding context"),
4844 PARSE_OPT_NOARG
, option_parse_space_change
},
4845 OPT_BOOL('R', "reverse", &state
.apply_in_reverse
,
4846 N_("apply the patch in reverse")),
4847 OPT_BOOL(0, "unidiff-zero", &state
.unidiff_zero
,
4848 N_("don't expect at least one line of context")),
4849 OPT_BOOL(0, "reject", &state
.apply_with_reject
,
4850 N_("leave the rejected hunks in corresponding *.rej files")),
4851 OPT_BOOL(0, "allow-overlap", &state
.allow_overlap
,
4852 N_("allow overlapping hunks")),
4853 OPT__VERBOSE(&state
.apply_verbosely
, N_("be verbose")),
4854 OPT_BIT(0, "inaccurate-eof", &options
,
4855 N_("tolerate incorrectly detected missing new-line at the end of file"),
4857 OPT_BIT(0, "recount", &options
,
4858 N_("do not trust the line counts in the hunk headers"),
4860 { OPTION_CALLBACK
, 0, "directory", &state
, N_("root"),
4861 N_("prepend <root> to all filenames"),
4862 0, option_parse_directory
},
4866 init_apply_state(&state
, prefix
, &lock_file
);
4868 argc
= parse_options(argc
, argv
, state
.prefix
, builtin_apply_options
,
4871 check_apply_state(&state
, force_apply
);
4873 ret
= apply_all_patches(&state
, argc
, argv
, options
);
4875 clear_apply_state(&state
);