4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
10 #define USE_THE_REPOSITORY_VARIABLE
12 #include "git-compat-util.h"
16 #include "object-store-ll.h"
20 #include "environment.h"
23 #include "xdiff-interface.h"
26 #include "name-hash.h"
27 #include "object-name.h"
28 #include "object-file.h"
29 #include "parse-options.h"
32 #include "read-cache.h"
33 #include "repository.h"
39 #include "wildmatch.h"
48 static void git_apply_config(void)
50 git_config_get_string("apply.whitespace", &apply_default_whitespace
);
51 git_config_get_string("apply.ignorewhitespace", &apply_default_ignorewhitespace
);
52 git_config(git_xmerge_config
, NULL
);
55 static int parse_whitespace_option(struct apply_state
*state
, const char *option
)
58 state
->ws_error_action
= warn_on_ws_error
;
61 if (!strcmp(option
, "warn")) {
62 state
->ws_error_action
= warn_on_ws_error
;
65 if (!strcmp(option
, "nowarn")) {
66 state
->ws_error_action
= nowarn_ws_error
;
69 if (!strcmp(option
, "error")) {
70 state
->ws_error_action
= die_on_ws_error
;
73 if (!strcmp(option
, "error-all")) {
74 state
->ws_error_action
= die_on_ws_error
;
75 state
->squelch_whitespace_errors
= 0;
78 if (!strcmp(option
, "strip") || !strcmp(option
, "fix")) {
79 state
->ws_error_action
= correct_ws_error
;
83 * Please update $__git_whitespacelist in git-completion.bash,
84 * Documentation/git-apply.txt, and Documentation/git-am.txt
85 * when you add new options.
87 return error(_("unrecognized whitespace option '%s'"), option
);
90 static int parse_ignorewhitespace_option(struct apply_state
*state
,
93 if (!option
|| !strcmp(option
, "no") ||
94 !strcmp(option
, "false") || !strcmp(option
, "never") ||
95 !strcmp(option
, "none")) {
96 state
->ws_ignore_action
= ignore_ws_none
;
99 if (!strcmp(option
, "change")) {
100 state
->ws_ignore_action
= ignore_ws_change
;
103 return error(_("unrecognized whitespace ignore option '%s'"), option
);
106 int init_apply_state(struct apply_state
*state
,
107 struct repository
*repo
,
110 memset(state
, 0, sizeof(*state
));
111 state
->prefix
= prefix
;
114 state
->line_termination
= '\n';
116 state
->p_context
= UINT_MAX
;
117 state
->squelch_whitespace_errors
= 5;
118 state
->ws_error_action
= warn_on_ws_error
;
119 state
->ws_ignore_action
= ignore_ws_none
;
121 string_list_init_nodup(&state
->fn_table
);
122 string_list_init_nodup(&state
->limit_by_name
);
123 strset_init(&state
->removed_symlinks
);
124 strset_init(&state
->kept_symlinks
);
125 strbuf_init(&state
->root
, 0);
128 if (apply_default_whitespace
&& parse_whitespace_option(state
, apply_default_whitespace
))
130 if (apply_default_ignorewhitespace
&& parse_ignorewhitespace_option(state
, apply_default_ignorewhitespace
))
135 void clear_apply_state(struct apply_state
*state
)
137 string_list_clear(&state
->limit_by_name
, 0);
138 strset_clear(&state
->removed_symlinks
);
139 strset_clear(&state
->kept_symlinks
);
140 strbuf_release(&state
->root
);
141 FREE_AND_NULL(state
->fake_ancestor
);
143 /* &state->fn_table is cleared at the end of apply_patch() */
146 static void mute_routine(const char *msg UNUSED
, va_list params UNUSED
)
151 int check_apply_state(struct apply_state
*state
, int force_apply
)
153 int is_not_gitdir
= !startup_info
->have_repository
;
155 if (state
->apply_with_reject
&& state
->threeway
)
156 return error(_("options '%s' and '%s' cannot be used together"), "--reject", "--3way");
157 if (state
->threeway
) {
159 return error(_("'%s' outside a repository"), "--3way");
160 state
->check_index
= 1;
162 if (state
->apply_with_reject
) {
164 if (state
->apply_verbosity
== verbosity_normal
)
165 state
->apply_verbosity
= verbosity_verbose
;
167 if (!force_apply
&& (state
->diffstat
|| state
->numstat
|| state
->summary
|| state
->check
|| state
->fake_ancestor
))
169 if (state
->check_index
&& is_not_gitdir
)
170 return error(_("'%s' outside a repository"), "--index");
173 return error(_("'%s' outside a repository"), "--cached");
174 state
->check_index
= 1;
176 if (state
->ita_only
&& (state
->check_index
|| is_not_gitdir
))
178 if (state
->check_index
)
179 state
->unsafe_paths
= 0;
181 if (state
->apply_verbosity
<= verbosity_silent
) {
182 state
->saved_error_routine
= get_error_routine();
183 state
->saved_warn_routine
= get_warn_routine();
184 set_error_routine(mute_routine
);
185 set_warn_routine(mute_routine
);
191 static void set_default_whitespace_mode(struct apply_state
*state
)
193 if (!state
->whitespace_option
&& !apply_default_whitespace
)
194 state
->ws_error_action
= (state
->apply
? warn_on_ws_error
: nowarn_ws_error
);
198 * This represents one "hunk" from a patch, starting with
199 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
200 * patch text is pointed at by patch, and its byte length
201 * is stored in size. leading and trailing are the number
205 unsigned long leading
, trailing
;
206 unsigned long oldpos
, oldlines
;
207 unsigned long newpos
, newlines
;
209 * 'patch' is usually borrowed from buf in apply_patch(),
210 * but some codepaths store an allocated buffer.
213 unsigned free_patch
:1,
217 struct fragment
*next
;
221 * When dealing with a binary patch, we reuse "leading" field
222 * to store the type of the binary hunk, either deflated "delta"
223 * or deflated "literal".
225 #define binary_patch_method leading
226 #define BINARY_DELTA_DEFLATED 1
227 #define BINARY_LITERAL_DEFLATED 2
229 static void free_fragment_list(struct fragment
*list
)
232 struct fragment
*next
= list
->next
;
233 if (list
->free_patch
)
234 free((char *)list
->patch
);
240 void release_patch(struct patch
*patch
)
242 free_fragment_list(patch
->fragments
);
243 free(patch
->def_name
);
244 free(patch
->old_name
);
245 free(patch
->new_name
);
249 static void free_patch(struct patch
*patch
)
251 release_patch(patch
);
255 static void free_patch_list(struct patch
*list
)
258 struct patch
*next
= list
->next
;
265 * A line in a file, len-bytes long (includes the terminating LF,
266 * except for an incomplete line at the end if the file ends with
267 * one), and its contents hashes to 'hash'.
273 #define LINE_COMMON 1
274 #define LINE_PATCHED 2
278 * This represents a "file", which is an array of "lines".
285 struct line
*line_allocated
;
289 static uint32_t hash_line(const char *cp
, size_t len
)
293 for (i
= 0, h
= 0; i
< len
; i
++) {
294 if (!isspace(cp
[i
])) {
295 h
= h
* 3 + (cp
[i
] & 0xff);
302 * Compare lines s1 of length n1 and s2 of length n2, ignoring
303 * whitespace difference. Returns 1 if they match, 0 otherwise
305 static int fuzzy_matchlines(const char *s1
, size_t n1
,
306 const char *s2
, size_t n2
)
308 const char *end1
= s1
+ n1
;
309 const char *end2
= s2
+ n2
;
311 /* ignore line endings */
312 while (s1
< end1
&& (end1
[-1] == '\r' || end1
[-1] == '\n'))
314 while (s2
< end2
&& (end2
[-1] == '\r' || end2
[-1] == '\n'))
317 while (s1
< end1
&& s2
< end2
) {
320 * Skip whitespace. We check on both buffers
321 * because we don't want "a b" to match "ab".
325 while (s1
< end1
&& isspace(*s1
))
327 while (s2
< end2
&& isspace(*s2
))
329 } else if (*s1
++ != *s2
++)
333 /* If we reached the end on one side only, lines don't match. */
334 return s1
== end1
&& s2
== end2
;
337 static void add_line_info(struct image
*img
, const char *bol
, size_t len
, unsigned flag
)
339 ALLOC_GROW(img
->line_allocated
, img
->nr
+ 1, img
->alloc
);
340 img
->line_allocated
[img
->nr
].len
= len
;
341 img
->line_allocated
[img
->nr
].hash
= hash_line(bol
, len
);
342 img
->line_allocated
[img
->nr
].flag
= flag
;
347 * "buf" has the file contents to be patched (read from various sources).
348 * attach it to "image" and add line-based index to it.
349 * "image" now owns the "buf".
351 static void prepare_image(struct image
*image
, char *buf
, size_t len
,
352 int prepare_linetable
)
356 memset(image
, 0, sizeof(*image
));
360 if (!prepare_linetable
)
363 ep
= image
->buf
+ image
->len
;
367 for (next
= cp
; next
< ep
&& *next
!= '\n'; next
++)
371 add_line_info(image
, cp
, next
- cp
, 0);
374 image
->line
= image
->line_allocated
;
377 static void clear_image(struct image
*image
)
380 free(image
->line_allocated
);
381 memset(image
, 0, sizeof(*image
));
384 /* fmt must contain _one_ %s and no other substitution */
385 static void say_patch_name(FILE *output
, const char *fmt
, struct patch
*patch
)
387 struct strbuf sb
= STRBUF_INIT
;
389 if (patch
->old_name
&& patch
->new_name
&&
390 strcmp(patch
->old_name
, patch
->new_name
)) {
391 quote_c_style(patch
->old_name
, &sb
, NULL
, 0);
392 strbuf_addstr(&sb
, " => ");
393 quote_c_style(patch
->new_name
, &sb
, NULL
, 0);
395 const char *n
= patch
->new_name
;
398 quote_c_style(n
, &sb
, NULL
, 0);
400 fprintf(output
, fmt
, sb
.buf
);
408 * apply.c isn't equipped to handle arbitrarily large patches, because
409 * it intermingles `unsigned long` with `int` for the type used to store
412 * Only process patches that are just shy of 1 GiB large in order to
413 * avoid any truncation or overflow issues.
415 #define MAX_APPLY_SIZE (1024UL * 1024 * 1023)
417 static int read_patch_file(struct strbuf
*sb
, int fd
)
419 if (strbuf_read(sb
, fd
, 0) < 0)
420 return error_errno(_("failed to read patch"));
421 else if (sb
->len
>= MAX_APPLY_SIZE
)
422 return error(_("patch too large"));
424 * Make sure that we have some slop in the buffer
425 * so that we can do speculative "memcmp" etc, and
426 * see to it that it is NUL-filled.
428 strbuf_grow(sb
, SLOP
);
429 memset(sb
->buf
+ sb
->len
, 0, SLOP
);
433 static unsigned long linelen(const char *buffer
, unsigned long size
)
435 unsigned long len
= 0;
438 if (*buffer
++ == '\n')
444 static int is_dev_null(const char *str
)
446 return skip_prefix(str
, "/dev/null", &str
) && isspace(*str
);
452 static int name_terminate(int c
, int terminate
)
454 if (c
== ' ' && !(terminate
& TERM_SPACE
))
456 if (c
== '\t' && !(terminate
& TERM_TAB
))
462 /* remove double slashes to make --index work with such filenames */
463 static char *squash_slash(char *name
)
471 if ((name
[j
++] = name
[i
++]) == '/')
472 while (name
[i
] == '/')
479 static char *find_name_gnu(struct strbuf
*root
,
483 struct strbuf name
= STRBUF_INIT
;
487 * Proposed "new-style" GNU patch/diff format; see
488 * https://lore.kernel.org/git/7vll0wvb2a.fsf@assigned-by-dhcp.cox.net/
490 if (unquote_c_style(&name
, line
, NULL
)) {
491 strbuf_release(&name
);
495 for (cp
= name
.buf
; p_value
; p_value
--) {
496 cp
= strchr(cp
, '/');
498 strbuf_release(&name
);
504 strbuf_remove(&name
, 0, cp
- name
.buf
);
506 strbuf_insert(&name
, 0, root
->buf
, root
->len
);
507 return squash_slash(strbuf_detach(&name
, NULL
));
510 static size_t sane_tz_len(const char *line
, size_t len
)
514 if (len
< strlen(" +0500") || line
[len
-strlen(" +0500")] != ' ')
516 tz
= line
+ len
- strlen(" +0500");
518 if (tz
[1] != '+' && tz
[1] != '-')
521 for (p
= tz
+ 2; p
!= line
+ len
; p
++)
525 return line
+ len
- tz
;
528 static size_t tz_with_colon_len(const char *line
, size_t len
)
532 if (len
< strlen(" +08:00") || line
[len
- strlen(":00")] != ':')
534 tz
= line
+ len
- strlen(" +08:00");
536 if (tz
[0] != ' ' || (tz
[1] != '+' && tz
[1] != '-'))
539 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
540 !isdigit(*p
++) || !isdigit(*p
++))
543 return line
+ len
- tz
;
546 static size_t date_len(const char *line
, size_t len
)
548 const char *date
, *p
;
550 if (len
< strlen("72-02-05") || line
[len
-strlen("-05")] != '-')
552 p
= date
= line
+ len
- strlen("72-02-05");
554 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
555 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
556 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a date. */
559 if (date
- line
>= strlen("19") &&
560 isdigit(date
[-1]) && isdigit(date
[-2])) /* 4-digit year */
561 date
-= strlen("19");
563 return line
+ len
- date
;
566 static size_t short_time_len(const char *line
, size_t len
)
568 const char *time
, *p
;
570 if (len
< strlen(" 07:01:32") || line
[len
-strlen(":32")] != ':')
572 p
= time
= line
+ len
- strlen(" 07:01:32");
574 /* Permit 1-digit hours? */
576 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
577 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
578 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a time. */
581 return line
+ len
- time
;
584 static size_t fractional_time_len(const char *line
, size_t len
)
589 /* Expected format: 19:41:17.620000023 */
590 if (!len
|| !isdigit(line
[len
- 1]))
594 /* Fractional seconds. */
595 while (p
> line
&& isdigit(*p
))
600 /* Hours, minutes, and whole seconds. */
601 n
= short_time_len(line
, p
- line
);
605 return line
+ len
- p
+ n
;
608 static size_t trailing_spaces_len(const char *line
, size_t len
)
612 /* Expected format: ' ' x (1 or more) */
613 if (!len
|| line
[len
- 1] != ' ')
620 return line
+ len
- (p
+ 1);
627 static size_t diff_timestamp_len(const char *line
, size_t len
)
629 const char *end
= line
+ len
;
633 * Posix: 2010-07-05 19:41:17
634 * GNU: 2010-07-05 19:41:17.620000023 -0500
637 if (!isdigit(end
[-1]))
640 n
= sane_tz_len(line
, end
- line
);
642 n
= tz_with_colon_len(line
, end
- line
);
645 n
= short_time_len(line
, end
- line
);
647 n
= fractional_time_len(line
, end
- line
);
650 n
= date_len(line
, end
- line
);
651 if (!n
) /* No date. Too bad. */
655 if (end
== line
) /* No space before date. */
657 if (end
[-1] == '\t') { /* Success! */
659 return line
+ len
- end
;
661 if (end
[-1] != ' ') /* No space before date. */
664 /* Whitespace damage. */
665 end
-= trailing_spaces_len(line
, end
- line
);
666 return line
+ len
- end
;
669 static char *find_name_common(struct strbuf
*root
,
677 const char *start
= NULL
;
681 while (line
!= end
) {
684 if (!end
&& isspace(c
)) {
687 if (name_terminate(c
, terminate
))
691 if (c
== '/' && !--p_value
)
695 return squash_slash(xstrdup_or_null(def
));
698 return squash_slash(xstrdup_or_null(def
));
701 * Generally we prefer the shorter name, especially
702 * if the other one is just a variation of that with
703 * something else tacked on to the end (ie "file.orig"
707 int deflen
= strlen(def
);
708 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
709 return squash_slash(xstrdup(def
));
713 char *ret
= xstrfmt("%s%.*s", root
->buf
, len
, start
);
714 return squash_slash(ret
);
717 return squash_slash(xmemdupz(start
, len
));
720 static char *find_name(struct strbuf
*root
,
727 char *name
= find_name_gnu(root
, line
, p_value
);
732 return find_name_common(root
, line
, def
, p_value
, NULL
, terminate
);
735 static char *find_name_traditional(struct strbuf
*root
,
744 char *name
= find_name_gnu(root
, line
, p_value
);
749 len
= strchrnul(line
, '\n') - line
;
750 date_len
= diff_timestamp_len(line
, len
);
752 return find_name_common(root
, line
, def
, p_value
, NULL
, TERM_TAB
);
755 return find_name_common(root
, line
, def
, p_value
, line
+ len
, 0);
759 * Given the string after "--- " or "+++ ", guess the appropriate
760 * p_value for the given patch.
762 static int guess_p_value(struct apply_state
*state
, const char *nameline
)
767 if (is_dev_null(nameline
))
769 name
= find_name_traditional(&state
->root
, nameline
, NULL
, 0);
772 cp
= strchr(name
, '/');
775 else if (state
->prefix
) {
777 * Does it begin with "a/$our-prefix" and such? Then this is
778 * very likely to apply to our directory.
780 if (starts_with(name
, state
->prefix
))
781 val
= count_slashes(state
->prefix
);
784 if (starts_with(cp
, state
->prefix
))
785 val
= count_slashes(state
->prefix
) + 1;
793 * Does the ---/+++ line have the POSIX timestamp after the last HT?
794 * GNU diff puts epoch there to signal a creation/deletion event. Is
795 * this such a timestamp?
797 static int has_epoch_timestamp(const char *nameline
)
800 * We are only interested in epoch timestamp; any non-zero
801 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
802 * For the same reason, the date must be either 1969-12-31 or
803 * 1970-01-01, and the seconds part must be "00".
805 const char stamp_regexp
[] =
806 "^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?"
808 "([-+][0-2][0-9]:?[0-5][0-9])\n";
809 const char *timestamp
= NULL
, *cp
, *colon
;
810 static regex_t
*stamp
;
812 int zoneoffset
, epoch_hour
, hour
, minute
;
815 for (cp
= nameline
; *cp
!= '\n'; cp
++) {
823 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
824 * (west of GMT) or 1970-01-01 (east of GMT)
826 if (skip_prefix(timestamp
, "1969-12-31 ", ×tamp
))
828 else if (skip_prefix(timestamp
, "1970-01-01 ", ×tamp
))
834 stamp
= xmalloc(sizeof(*stamp
));
835 if (regcomp(stamp
, stamp_regexp
, REG_EXTENDED
)) {
836 warning(_("Cannot prepare timestamp regexp %s"),
842 status
= regexec(stamp
, timestamp
, ARRAY_SIZE(m
), m
, 0);
844 if (status
!= REG_NOMATCH
)
845 warning(_("regexec returned %d for input: %s"),
850 hour
= strtol(timestamp
, NULL
, 10);
851 minute
= strtol(timestamp
+ m
[1].rm_so
, NULL
, 10);
853 zoneoffset
= strtol(timestamp
+ m
[3].rm_so
+ 1, (char **) &colon
, 10);
855 zoneoffset
= zoneoffset
* 60 + strtol(colon
+ 1, NULL
, 10);
857 zoneoffset
= (zoneoffset
/ 100) * 60 + (zoneoffset
% 100);
858 if (timestamp
[m
[3].rm_so
] == '-')
859 zoneoffset
= -zoneoffset
;
861 return hour
* 60 + minute
- zoneoffset
== epoch_hour
* 60;
865 * Get the name etc info from the ---/+++ lines of a traditional patch header
867 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
868 * files, we can happily check the index for a match, but for creating a
869 * new file we should try to match whatever "patch" does. I have no idea.
871 static int parse_traditional_patch(struct apply_state
*state
,
878 first
+= 4; /* skip "--- " */
879 second
+= 4; /* skip "+++ " */
880 if (!state
->p_value_known
) {
882 p
= guess_p_value(state
, first
);
883 q
= guess_p_value(state
, second
);
885 if (0 <= p
&& p
== q
) {
887 state
->p_value_known
= 1;
890 if (is_dev_null(first
)) {
892 patch
->is_delete
= 0;
893 name
= find_name_traditional(&state
->root
, second
, NULL
, state
->p_value
);
894 patch
->new_name
= name
;
895 } else if (is_dev_null(second
)) {
897 patch
->is_delete
= 1;
898 name
= find_name_traditional(&state
->root
, first
, NULL
, state
->p_value
);
899 patch
->old_name
= name
;
902 first_name
= find_name_traditional(&state
->root
, first
, NULL
, state
->p_value
);
903 name
= find_name_traditional(&state
->root
, second
, first_name
, state
->p_value
);
905 if (has_epoch_timestamp(first
)) {
907 patch
->is_delete
= 0;
908 patch
->new_name
= name
;
909 } else if (has_epoch_timestamp(second
)) {
911 patch
->is_delete
= 1;
912 patch
->old_name
= name
;
914 patch
->old_name
= name
;
915 patch
->new_name
= xstrdup_or_null(name
);
919 return error(_("unable to find filename in patch at line %d"), state
->linenr
);
924 static int gitdiff_hdrend(struct gitdiff_data
*state UNUSED
,
925 const char *line UNUSED
,
926 struct patch
*patch UNUSED
)
932 * We're anal about diff header consistency, to make
933 * sure that we don't end up having strange ambiguous
934 * patches floating around.
936 * As a result, gitdiff_{old|new}name() will check
937 * their names against any previous information, just
940 #define DIFF_OLD_NAME 0
941 #define DIFF_NEW_NAME 1
943 static int gitdiff_verify_name(struct gitdiff_data
*state
,
949 if (!*name
&& !isnull
) {
950 *name
= find_name(state
->root
, line
, NULL
, state
->p_value
, TERM_TAB
);
957 return error(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
958 *name
, state
->linenr
);
959 another
= find_name(state
->root
, line
, NULL
, state
->p_value
, TERM_TAB
);
960 if (!another
|| strcmp(another
, *name
)) {
962 return error((side
== DIFF_NEW_NAME
) ?
963 _("git apply: bad git-diff - inconsistent new filename on line %d") :
964 _("git apply: bad git-diff - inconsistent old filename on line %d"), state
->linenr
);
968 if (!is_dev_null(line
))
969 return error(_("git apply: bad git-diff - expected /dev/null on line %d"), state
->linenr
);
975 static int gitdiff_oldname(struct gitdiff_data
*state
,
979 return gitdiff_verify_name(state
, line
,
980 patch
->is_new
, &patch
->old_name
,
984 static int gitdiff_newname(struct gitdiff_data
*state
,
988 return gitdiff_verify_name(state
, line
,
989 patch
->is_delete
, &patch
->new_name
,
993 static int parse_mode_line(const char *line
, int linenr
, unsigned int *mode
)
996 *mode
= strtoul(line
, &end
, 8);
997 if (end
== line
|| !isspace(*end
))
998 return error(_("invalid mode on line %d: %s"), linenr
, line
);
999 *mode
= canon_mode(*mode
);
1003 static int gitdiff_oldmode(struct gitdiff_data
*state
,
1005 struct patch
*patch
)
1007 return parse_mode_line(line
, state
->linenr
, &patch
->old_mode
);
1010 static int gitdiff_newmode(struct gitdiff_data
*state
,
1012 struct patch
*patch
)
1014 return parse_mode_line(line
, state
->linenr
, &patch
->new_mode
);
1017 static int gitdiff_delete(struct gitdiff_data
*state
,
1019 struct patch
*patch
)
1021 patch
->is_delete
= 1;
1022 free(patch
->old_name
);
1023 patch
->old_name
= xstrdup_or_null(patch
->def_name
);
1024 return gitdiff_oldmode(state
, line
, patch
);
1027 static int gitdiff_newfile(struct gitdiff_data
*state
,
1029 struct patch
*patch
)
1032 free(patch
->new_name
);
1033 patch
->new_name
= xstrdup_or_null(patch
->def_name
);
1034 return gitdiff_newmode(state
, line
, patch
);
1037 static int gitdiff_copysrc(struct gitdiff_data
*state
,
1039 struct patch
*patch
)
1042 free(patch
->old_name
);
1043 patch
->old_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1047 static int gitdiff_copydst(struct gitdiff_data
*state
,
1049 struct patch
*patch
)
1052 free(patch
->new_name
);
1053 patch
->new_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1057 static int gitdiff_renamesrc(struct gitdiff_data
*state
,
1059 struct patch
*patch
)
1061 patch
->is_rename
= 1;
1062 free(patch
->old_name
);
1063 patch
->old_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1067 static int gitdiff_renamedst(struct gitdiff_data
*state
,
1069 struct patch
*patch
)
1071 patch
->is_rename
= 1;
1072 free(patch
->new_name
);
1073 patch
->new_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1077 static int gitdiff_similarity(struct gitdiff_data
*state UNUSED
,
1079 struct patch
*patch
)
1081 unsigned long val
= strtoul(line
, NULL
, 10);
1087 static int gitdiff_dissimilarity(struct gitdiff_data
*state UNUSED
,
1089 struct patch
*patch
)
1091 unsigned long val
= strtoul(line
, NULL
, 10);
1097 static int gitdiff_index(struct gitdiff_data
*state
,
1099 struct patch
*patch
)
1102 * index line is N hexadecimal, "..", N hexadecimal,
1103 * and optional space with octal mode.
1105 const char *ptr
, *eol
;
1107 const unsigned hexsz
= the_hash_algo
->hexsz
;
1109 ptr
= strchr(line
, '.');
1110 if (!ptr
|| ptr
[1] != '.' || hexsz
< ptr
- line
)
1113 memcpy(patch
->old_oid_prefix
, line
, len
);
1114 patch
->old_oid_prefix
[len
] = 0;
1117 ptr
= strchr(line
, ' ');
1118 eol
= strchrnul(line
, '\n');
1120 if (!ptr
|| eol
< ptr
)
1126 memcpy(patch
->new_oid_prefix
, line
, len
);
1127 patch
->new_oid_prefix
[len
] = 0;
1129 return gitdiff_oldmode(state
, ptr
+ 1, patch
);
1134 * This is normal for a diff that doesn't change anything: we'll fall through
1135 * into the next diff. Tell the parser to break out.
1137 static int gitdiff_unrecognized(struct gitdiff_data
*state UNUSED
,
1138 const char *line UNUSED
,
1139 struct patch
*patch UNUSED
)
1145 * Skip p_value leading components from "line"; as we do not accept
1146 * absolute paths, return NULL in that case.
1148 static const char *skip_tree_prefix(int p_value
,
1156 return (llen
&& line
[0] == '/') ? NULL
: line
;
1159 for (i
= 0; i
< llen
; i
++) {
1161 if (ch
== '/' && --nslash
<= 0)
1162 return (i
== 0) ? NULL
: &line
[i
+ 1];
1168 * This is to extract the same name that appears on "diff --git"
1169 * line. We do not find and return anything if it is a rename
1170 * patch, and it is OK because we will find the name elsewhere.
1171 * We need to reliably find name only when it is mode-change only,
1172 * creation or deletion of an empty file. In any of these cases,
1173 * both sides are the same name under a/ and b/ respectively.
1175 static char *git_header_name(int p_value
,
1180 const char *second
= NULL
;
1181 size_t len
, line_len
;
1183 line
+= strlen("diff --git ");
1184 llen
-= strlen("diff --git ");
1188 struct strbuf first
= STRBUF_INIT
;
1189 struct strbuf sp
= STRBUF_INIT
;
1191 if (unquote_c_style(&first
, line
, &second
))
1192 goto free_and_fail1
;
1194 /* strip the a/b prefix including trailing slash */
1195 cp
= skip_tree_prefix(p_value
, first
.buf
, first
.len
);
1197 goto free_and_fail1
;
1198 strbuf_remove(&first
, 0, cp
- first
.buf
);
1201 * second points at one past closing dq of name.
1202 * find the second name.
1204 while ((second
< line
+ llen
) && isspace(*second
))
1207 if (line
+ llen
<= second
)
1208 goto free_and_fail1
;
1209 if (*second
== '"') {
1210 if (unquote_c_style(&sp
, second
, NULL
))
1211 goto free_and_fail1
;
1212 cp
= skip_tree_prefix(p_value
, sp
.buf
, sp
.len
);
1214 goto free_and_fail1
;
1215 /* They must match, otherwise ignore */
1216 if (strcmp(cp
, first
.buf
))
1217 goto free_and_fail1
;
1218 strbuf_release(&sp
);
1219 return strbuf_detach(&first
, NULL
);
1222 /* unquoted second */
1223 cp
= skip_tree_prefix(p_value
, second
, line
+ llen
- second
);
1225 goto free_and_fail1
;
1226 if (line
+ llen
- cp
!= first
.len
||
1227 memcmp(first
.buf
, cp
, first
.len
))
1228 goto free_and_fail1
;
1229 return strbuf_detach(&first
, NULL
);
1232 strbuf_release(&first
);
1233 strbuf_release(&sp
);
1237 /* unquoted first name */
1238 name
= skip_tree_prefix(p_value
, line
, llen
);
1243 * since the first name is unquoted, a dq if exists must be
1244 * the beginning of the second name.
1246 for (second
= name
; second
< line
+ llen
; second
++) {
1247 if (*second
== '"') {
1248 struct strbuf sp
= STRBUF_INIT
;
1251 if (unquote_c_style(&sp
, second
, NULL
))
1252 goto free_and_fail2
;
1254 np
= skip_tree_prefix(p_value
, sp
.buf
, sp
.len
);
1256 goto free_and_fail2
;
1258 len
= sp
.buf
+ sp
.len
- np
;
1259 if (len
< second
- name
&&
1260 !strncmp(np
, name
, len
) &&
1261 isspace(name
[len
])) {
1263 strbuf_remove(&sp
, 0, np
- sp
.buf
);
1264 return strbuf_detach(&sp
, NULL
);
1268 strbuf_release(&sp
);
1274 * Accept a name only if it shows up twice, exactly the same
1277 second
= strchr(name
, '\n');
1280 line_len
= second
- name
;
1281 for (len
= 0 ; ; len
++) {
1282 switch (name
[len
]) {
1287 case '\t': case ' ':
1289 * Is this the separator between the preimage
1290 * and the postimage pathname? Again, we are
1291 * only interested in the case where there is
1292 * no rename, as this is only to set def_name
1293 * and a rename patch has the names elsewhere
1294 * in an unambiguous form.
1297 return NULL
; /* no postimage name */
1298 second
= skip_tree_prefix(p_value
, name
+ len
+ 1,
1299 line_len
- (len
+ 1));
1301 * If we are at the SP at the end of a directory,
1302 * skip_tree_prefix() may return NULL as that makes
1303 * it appears as if we have an absolute path.
1304 * Keep going to find another SP.
1310 * Does len bytes starting at "name" and "second"
1311 * (that are separated by one HT or SP we just
1312 * found) exactly match?
1314 if (second
[len
] == '\n' && !strncmp(name
, second
, len
))
1315 return xmemdupz(name
, len
);
1320 static int check_header_line(int linenr
, struct patch
*patch
)
1322 int extensions
= (patch
->is_delete
== 1) + (patch
->is_new
== 1) +
1323 (patch
->is_rename
== 1) + (patch
->is_copy
== 1);
1325 return error(_("inconsistent header lines %d and %d"),
1326 patch
->extension_linenr
, linenr
);
1327 if (extensions
&& !patch
->extension_linenr
)
1328 patch
->extension_linenr
= linenr
;
1332 int parse_git_diff_header(struct strbuf
*root
,
1338 struct patch
*patch
)
1340 unsigned long offset
;
1341 struct gitdiff_data parse_hdr_state
;
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(p_value
, line
, len
);
1354 if (patch
->def_name
&& root
->len
) {
1355 char *s
= xstrfmt("%s%s", root
->buf
, patch
->def_name
);
1356 free(patch
->def_name
);
1357 patch
->def_name
= s
;
1363 parse_hdr_state
.root
= root
;
1364 parse_hdr_state
.linenr
= *linenr
;
1365 parse_hdr_state
.p_value
= p_value
;
1367 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, (*linenr
)++) {
1368 static const struct opentry
{
1370 int (*fn
)(struct gitdiff_data
*, const char *, struct patch
*);
1372 { "@@ -", gitdiff_hdrend
},
1373 { "--- ", gitdiff_oldname
},
1374 { "+++ ", gitdiff_newname
},
1375 { "old mode ", gitdiff_oldmode
},
1376 { "new mode ", gitdiff_newmode
},
1377 { "deleted file mode ", gitdiff_delete
},
1378 { "new file mode ", gitdiff_newfile
},
1379 { "copy from ", gitdiff_copysrc
},
1380 { "copy to ", gitdiff_copydst
},
1381 { "rename old ", gitdiff_renamesrc
},
1382 { "rename new ", gitdiff_renamedst
},
1383 { "rename from ", gitdiff_renamesrc
},
1384 { "rename to ", gitdiff_renamedst
},
1385 { "similarity index ", gitdiff_similarity
},
1386 { "dissimilarity index ", gitdiff_dissimilarity
},
1387 { "index ", gitdiff_index
},
1388 { "", gitdiff_unrecognized
},
1392 len
= linelen(line
, size
);
1393 if (!len
|| line
[len
-1] != '\n')
1395 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
1396 const struct opentry
*p
= optable
+ i
;
1397 int oplen
= strlen(p
->str
);
1399 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
1401 res
= p
->fn(&parse_hdr_state
, line
+ oplen
, patch
);
1404 if (check_header_line(*linenr
, patch
))
1413 if (!patch
->old_name
&& !patch
->new_name
) {
1414 if (!patch
->def_name
) {
1415 error(Q_("git diff header lacks filename information when removing "
1416 "%d leading pathname component (line %d)",
1417 "git diff header lacks filename information when removing "
1418 "%d leading pathname components (line %d)",
1419 parse_hdr_state
.p_value
),
1420 parse_hdr_state
.p_value
, *linenr
);
1423 patch
->old_name
= xstrdup(patch
->def_name
);
1424 patch
->new_name
= xstrdup(patch
->def_name
);
1426 if ((!patch
->new_name
&& !patch
->is_delete
) ||
1427 (!patch
->old_name
&& !patch
->is_new
)) {
1428 error(_("git diff header lacks filename information "
1429 "(line %d)"), *linenr
);
1432 patch
->is_toplevel_relative
= 1;
1436 static int parse_num(const char *line
, unsigned long *p
)
1440 if (!isdigit(*line
))
1442 *p
= strtoul(line
, &ptr
, 10);
1446 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
1447 unsigned long *p1
, unsigned long *p2
)
1451 if (offset
< 0 || offset
>= len
)
1456 digits
= parse_num(line
, p1
);
1466 digits
= parse_num(line
+1, p2
);
1475 ex
= strlen(expect
);
1478 if (memcmp(line
, expect
, ex
))
1484 static void recount_diff(const char *line
, int size
, struct fragment
*fragment
)
1486 int oldlines
= 0, newlines
= 0, ret
= 0;
1489 warning("recount: ignore empty hunk");
1494 int len
= linelen(line
, size
);
1502 case ' ': case '\n':
1514 ret
= size
< 3 || !starts_with(line
, "@@ ");
1517 ret
= size
< 5 || !starts_with(line
, "diff ");
1524 warning(_("recount: unexpected line: %.*s"),
1525 (int)linelen(line
, size
), line
);
1530 fragment
->oldlines
= oldlines
;
1531 fragment
->newlines
= newlines
;
1535 * Parse a unified diff fragment header of the
1536 * form "@@ -a,b +c,d @@"
1538 static int parse_fragment_header(const char *line
, int len
, struct fragment
*fragment
)
1542 if (!len
|| line
[len
-1] != '\n')
1545 /* Figure out the number of lines in a fragment */
1546 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
1547 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
1553 * Find file diff header
1556 * -1 if no header was found
1557 * -128 in case of error
1558 * the size of the header in bytes (called "offset") otherwise
1560 static int find_header(struct apply_state
*state
,
1564 struct patch
*patch
)
1566 unsigned long offset
, len
;
1568 patch
->is_toplevel_relative
= 0;
1569 patch
->is_rename
= patch
->is_copy
= 0;
1570 patch
->is_new
= patch
->is_delete
= -1;
1571 patch
->old_mode
= patch
->new_mode
= 0;
1572 patch
->old_name
= patch
->new_name
= NULL
;
1573 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1574 unsigned long nextlen
;
1576 len
= linelen(line
, size
);
1580 /* Testing this early allows us to take a few shortcuts.. */
1585 * Make sure we don't find any unconnected patch fragments.
1586 * That's a sign that we didn't find a header, and that a
1587 * patch has become corrupted/broken up.
1589 if (!memcmp("@@ -", line
, 4)) {
1590 struct fragment dummy
;
1591 if (parse_fragment_header(line
, len
, &dummy
) < 0)
1593 error(_("patch fragment without header at line %d: %.*s"),
1594 state
->linenr
, (int)len
-1, line
);
1602 * Git patch? It might not have a real patch, just a rename
1603 * or mode change, so we handle that specially
1605 if (!memcmp("diff --git ", line
, 11)) {
1606 int git_hdr_len
= parse_git_diff_header(&state
->root
, &state
->linenr
,
1607 state
->p_value
, line
, len
,
1609 if (git_hdr_len
< 0)
1611 if (git_hdr_len
<= len
)
1613 *hdrsize
= git_hdr_len
;
1617 /* --- followed by +++ ? */
1618 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
1622 * We only accept unified patches, so we want it to
1623 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1624 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1626 nextlen
= linelen(line
+ len
, size
- len
);
1627 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
1630 /* Ok, we'll consider it a patch */
1631 if (parse_traditional_patch(state
, line
, line
+len
, patch
))
1633 *hdrsize
= len
+ nextlen
;
1640 static void record_ws_error(struct apply_state
*state
,
1651 state
->whitespace_error
++;
1652 if (state
->squelch_whitespace_errors
&&
1653 state
->squelch_whitespace_errors
< state
->whitespace_error
)
1656 err
= whitespace_error_string(result
);
1657 if (state
->apply_verbosity
> verbosity_silent
)
1658 fprintf(stderr
, "%s:%d: %s.\n%.*s\n",
1659 state
->patch_input_file
, linenr
, err
, len
, line
);
1663 static void check_whitespace(struct apply_state
*state
,
1668 unsigned result
= ws_check(line
+ 1, len
- 1, ws_rule
);
1670 record_ws_error(state
, result
, line
+ 1, len
- 2, state
->linenr
);
1674 * Check if the patch has context lines with CRLF or
1675 * the patch wants to remove lines with CRLF.
1677 static void check_old_for_crlf(struct patch
*patch
, const char *line
, int len
)
1679 if (len
>= 2 && line
[len
-1] == '\n' && line
[len
-2] == '\r') {
1680 patch
->ws_rule
|= WS_CR_AT_EOL
;
1681 patch
->crlf_in_old
= 1;
1687 * Parse a unified diff. Note that this really needs to parse each
1688 * fragment separately, since the only way to know the difference
1689 * between a "---" that is part of a patch, and a "---" that starts
1690 * the next patch is to look at the line counts..
1692 static int parse_fragment(struct apply_state
*state
,
1695 struct patch
*patch
,
1696 struct fragment
*fragment
)
1699 int len
= linelen(line
, size
), offset
;
1700 unsigned long oldlines
, newlines
;
1701 unsigned long leading
, trailing
;
1703 offset
= parse_fragment_header(line
, len
, fragment
);
1706 if (offset
> 0 && patch
->recount
)
1707 recount_diff(line
+ offset
, size
- offset
, fragment
);
1708 oldlines
= fragment
->oldlines
;
1709 newlines
= fragment
->newlines
;
1713 /* Parse the thing.. */
1717 added
= deleted
= 0;
1720 offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1721 if (!oldlines
&& !newlines
)
1723 len
= linelen(line
, size
);
1724 if (!len
|| line
[len
-1] != '\n')
1729 case '\n': /* newer GNU diff, an empty context line */
1733 if (!deleted
&& !added
)
1736 check_old_for_crlf(patch
, line
, len
);
1737 if (!state
->apply_in_reverse
&&
1738 state
->ws_error_action
== correct_ws_error
)
1739 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1742 if (!state
->apply_in_reverse
)
1743 check_old_for_crlf(patch
, line
, len
);
1744 if (state
->apply_in_reverse
&&
1745 state
->ws_error_action
!= nowarn_ws_error
)
1746 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1752 if (state
->apply_in_reverse
)
1753 check_old_for_crlf(patch
, line
, len
);
1754 if (!state
->apply_in_reverse
&&
1755 state
->ws_error_action
!= nowarn_ws_error
)
1756 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1763 * We allow "\ No newline at end of file". Depending
1764 * on locale settings when the patch was produced we
1765 * don't know what this line looks like. The only
1766 * thing we do know is that it begins with "\ ".
1767 * Checking for 12 is just for sanity check -- any
1768 * l10n of "\ No newline..." is at least that long.
1771 if (len
< 12 || memcmp(line
, "\\ ", 2))
1776 if (oldlines
|| newlines
)
1778 if (!patch
->recount
&& !deleted
&& !added
)
1781 fragment
->leading
= leading
;
1782 fragment
->trailing
= trailing
;
1785 * If a fragment ends with an incomplete line, we failed to include
1786 * it in the above loop because we hit oldlines == newlines == 0
1789 if (12 < size
&& !memcmp(line
, "\\ ", 2))
1790 offset
+= linelen(line
, size
);
1792 patch
->lines_added
+= added
;
1793 patch
->lines_deleted
+= deleted
;
1795 if (0 < patch
->is_new
&& oldlines
)
1796 return error(_("new file depends on old contents"));
1797 if (0 < patch
->is_delete
&& newlines
)
1798 return error(_("deleted file still has contents"));
1803 * We have seen "diff --git a/... b/..." header (or a traditional patch
1804 * header). Read hunks that belong to this patch into fragments and hang
1805 * them to the given patch structure.
1807 * The (fragment->patch, fragment->size) pair points into the memory given
1808 * by the caller, not a copy, when we return.
1811 * -1 in case of error,
1812 * the number of bytes in the patch otherwise.
1814 static int parse_single_patch(struct apply_state
*state
,
1817 struct patch
*patch
)
1819 unsigned long offset
= 0;
1820 unsigned long oldlines
= 0, newlines
= 0, context
= 0;
1821 struct fragment
**fragp
= &patch
->fragments
;
1823 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
1824 struct fragment
*fragment
;
1827 CALLOC_ARRAY(fragment
, 1);
1828 fragment
->linenr
= state
->linenr
;
1829 len
= parse_fragment(state
, line
, size
, patch
, fragment
);
1832 return error(_("corrupt patch at line %d"), state
->linenr
);
1834 fragment
->patch
= line
;
1835 fragment
->size
= len
;
1836 oldlines
+= fragment
->oldlines
;
1837 newlines
+= fragment
->newlines
;
1838 context
+= fragment
->leading
+ fragment
->trailing
;
1841 fragp
= &fragment
->next
;
1849 * If something was removed (i.e. we have old-lines) it cannot
1850 * be creation, and if something was added it cannot be
1851 * deletion. However, the reverse is not true; --unified=0
1852 * patches that only add are not necessarily creation even
1853 * though they do not have any old lines, and ones that only
1854 * delete are not necessarily deletion.
1856 * Unfortunately, a real creation/deletion patch do _not_ have
1857 * any context line by definition, so we cannot safely tell it
1858 * apart with --unified=0 insanity. At least if the patch has
1859 * more than one hunk it is not creation or deletion.
1861 if (patch
->is_new
< 0 &&
1862 (oldlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1864 if (patch
->is_delete
< 0 &&
1865 (newlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1866 patch
->is_delete
= 0;
1868 if (0 < patch
->is_new
&& oldlines
)
1869 return error(_("new file %s depends on old contents"), patch
->new_name
);
1870 if (0 < patch
->is_delete
&& newlines
)
1871 return error(_("deleted file %s still has contents"), patch
->old_name
);
1872 if (!patch
->is_delete
&& !newlines
&& context
&& state
->apply_verbosity
> verbosity_silent
)
1875 "file %s becomes empty but is not deleted"),
1881 static inline int metadata_changes(struct patch
*patch
)
1883 return patch
->is_rename
> 0 ||
1884 patch
->is_copy
> 0 ||
1885 patch
->is_new
> 0 ||
1887 (patch
->old_mode
&& patch
->new_mode
&&
1888 patch
->old_mode
!= patch
->new_mode
);
1891 static char *inflate_it(const void *data
, unsigned long size
,
1892 unsigned long inflated_size
)
1898 memset(&stream
, 0, sizeof(stream
));
1900 stream
.next_in
= (unsigned char *)data
;
1901 stream
.avail_in
= size
;
1902 stream
.next_out
= out
= xmalloc(inflated_size
);
1903 stream
.avail_out
= inflated_size
;
1904 git_inflate_init(&stream
);
1905 st
= git_inflate(&stream
, Z_FINISH
);
1906 git_inflate_end(&stream
);
1907 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1915 * Read a binary hunk and return a new fragment; fragment->patch
1916 * points at an allocated memory that the caller must free, so
1917 * it is marked as "->free_patch = 1".
1919 static struct fragment
*parse_binary_hunk(struct apply_state
*state
,
1921 unsigned long *sz_p
,
1926 * Expect a line that begins with binary patch method ("literal"
1927 * or "delta"), followed by the length of data before deflating.
1928 * a sequence of 'length-byte' followed by base-85 encoded data
1929 * should follow, terminated by a newline.
1931 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1932 * and we would limit the patch line to 66 characters,
1933 * so one line can fit up to 13 groups that would decode
1934 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1935 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1938 unsigned long size
= *sz_p
;
1939 char *buffer
= *buf_p
;
1941 unsigned long origlen
;
1944 struct fragment
*frag
;
1946 llen
= linelen(buffer
, size
);
1951 if (starts_with(buffer
, "delta ")) {
1952 patch_method
= BINARY_DELTA_DEFLATED
;
1953 origlen
= strtoul(buffer
+ 6, NULL
, 10);
1955 else if (starts_with(buffer
, "literal ")) {
1956 patch_method
= BINARY_LITERAL_DEFLATED
;
1957 origlen
= strtoul(buffer
+ 8, NULL
, 10);
1966 int byte_length
, max_byte_length
, newsize
;
1967 llen
= linelen(buffer
, size
);
1971 /* consume the blank line */
1977 * Minimum line is "A00000\n" which is 7-byte long,
1978 * and the line length must be multiple of 5 plus 2.
1980 if ((llen
< 7) || (llen
-2) % 5)
1982 max_byte_length
= (llen
- 2) / 5 * 4;
1983 byte_length
= *buffer
;
1984 if ('A' <= byte_length
&& byte_length
<= 'Z')
1985 byte_length
= byte_length
- 'A' + 1;
1986 else if ('a' <= byte_length
&& byte_length
<= 'z')
1987 byte_length
= byte_length
- 'a' + 27;
1990 /* if the input length was not multiple of 4, we would
1991 * have filler at the end but the filler should never
1994 if (max_byte_length
< byte_length
||
1995 byte_length
<= max_byte_length
- 4)
1997 newsize
= hunk_size
+ byte_length
;
1998 data
= xrealloc(data
, newsize
);
1999 if (decode_85(data
+ hunk_size
, buffer
+ 1, byte_length
))
2001 hunk_size
= newsize
;
2006 CALLOC_ARRAY(frag
, 1);
2007 frag
->patch
= inflate_it(data
, hunk_size
, origlen
);
2008 frag
->free_patch
= 1;
2012 frag
->size
= origlen
;
2016 frag
->binary_patch_method
= patch_method
;
2022 error(_("corrupt binary patch at line %d: %.*s"),
2023 state
->linenr
-1, llen
-1, buffer
);
2029 * -1 in case of error,
2030 * the length of the parsed binary patch otherwise
2032 static int parse_binary(struct apply_state
*state
,
2035 struct patch
*patch
)
2038 * We have read "GIT binary patch\n"; what follows is a line
2039 * that says the patch method (currently, either "literal" or
2040 * "delta") and the length of data before deflating; a
2041 * sequence of 'length-byte' followed by base-85 encoded data
2044 * When a binary patch is reversible, there is another binary
2045 * hunk in the same format, starting with patch method (either
2046 * "literal" or "delta") with the length of data, and a sequence
2047 * of length-byte + base-85 encoded data, terminated with another
2048 * empty line. This data, when applied to the postimage, produces
2051 struct fragment
*forward
;
2052 struct fragment
*reverse
;
2056 forward
= parse_binary_hunk(state
, &buffer
, &size
, &status
, &used
);
2057 if (!forward
&& !status
)
2058 /* there has to be one hunk (forward hunk) */
2059 return error(_("unrecognized binary patch at line %d"), state
->linenr
-1);
2061 /* otherwise we already gave an error message */
2064 reverse
= parse_binary_hunk(state
, &buffer
, &size
, &status
, &used_1
);
2069 * Not having reverse hunk is not an error, but having
2070 * a corrupt reverse hunk is.
2072 free((void*) forward
->patch
);
2076 forward
->next
= reverse
;
2077 patch
->fragments
= forward
;
2078 patch
->is_binary
= 1;
2082 static void prefix_one(struct apply_state
*state
, char **name
)
2084 char *old_name
= *name
;
2087 *name
= prefix_filename(state
->prefix
, *name
);
2091 static void prefix_patch(struct apply_state
*state
, struct patch
*p
)
2093 if (!state
->prefix
|| p
->is_toplevel_relative
)
2095 prefix_one(state
, &p
->new_name
);
2096 prefix_one(state
, &p
->old_name
);
2103 static void add_name_limit(struct apply_state
*state
,
2107 struct string_list_item
*it
;
2109 it
= string_list_append(&state
->limit_by_name
, name
);
2110 it
->util
= exclude
? NULL
: (void *) 1;
2113 static int use_patch(struct apply_state
*state
, struct patch
*p
)
2115 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
2118 /* Paths outside are not touched regardless of "--include" */
2119 if (state
->prefix
&& *state
->prefix
) {
2121 if (!skip_prefix(pathname
, state
->prefix
, &rest
) || !*rest
)
2125 /* See if it matches any of exclude/include rule */
2126 for (i
= 0; i
< state
->limit_by_name
.nr
; i
++) {
2127 struct string_list_item
*it
= &state
->limit_by_name
.items
[i
];
2128 if (!wildmatch(it
->string
, pathname
, 0))
2129 return (it
->util
!= NULL
);
2133 * If we had any include, a path that does not match any rule is
2134 * not used. Otherwise, we saw bunch of exclude rules (or none)
2135 * and such a path is used.
2137 return !state
->has_include
;
2141 * Read the patch text in "buffer" that extends for "size" bytes; stop
2142 * reading after seeing a single patch (i.e. changes to a single file).
2143 * Create fragments (i.e. patch hunks) and hang them to the given patch.
2146 * -1 if no header was found or parse_binary() failed,
2147 * -128 on another error,
2148 * the number of bytes consumed otherwise,
2149 * so that the caller can call us again for the next patch.
2151 static int parse_chunk(struct apply_state
*state
, char *buffer
, unsigned long size
, struct patch
*patch
)
2153 int hdrsize
, patchsize
;
2154 int offset
= find_header(state
, buffer
, size
, &hdrsize
, patch
);
2159 prefix_patch(state
, patch
);
2161 if (!use_patch(state
, patch
))
2163 else if (patch
->new_name
)
2164 patch
->ws_rule
= whitespace_rule(state
->repo
->index
,
2167 patch
->ws_rule
= whitespace_rule(state
->repo
->index
,
2170 patchsize
= parse_single_patch(state
,
2171 buffer
+ offset
+ hdrsize
,
2172 size
- offset
- hdrsize
,
2179 static const char git_binary
[] = "GIT binary patch\n";
2180 int hd
= hdrsize
+ offset
;
2181 unsigned long llen
= linelen(buffer
+ hd
, size
- hd
);
2183 if (llen
== sizeof(git_binary
) - 1 &&
2184 !memcmp(git_binary
, buffer
+ hd
, llen
)) {
2187 used
= parse_binary(state
, buffer
+ hd
+ llen
,
2188 size
- hd
- llen
, patch
);
2192 patchsize
= used
+ llen
;
2196 else if (!memcmp(" differ\n", buffer
+ hd
+ llen
- 8, 8)) {
2197 static const char *binhdr
[] = {
2203 for (i
= 0; binhdr
[i
]; i
++) {
2204 int len
= strlen(binhdr
[i
]);
2205 if (len
< size
- hd
&&
2206 !memcmp(binhdr
[i
], buffer
+ hd
, len
)) {
2208 patch
->is_binary
= 1;
2215 /* Empty patch cannot be applied if it is a text patch
2216 * without metadata change. A binary patch appears
2219 if ((state
->apply
|| state
->check
) &&
2220 (!patch
->is_binary
&& !metadata_changes(patch
))) {
2221 error(_("patch with only garbage at line %d"), state
->linenr
);
2226 return offset
+ hdrsize
+ patchsize
;
2229 static void reverse_patches(struct patch
*p
)
2231 for (; p
; p
= p
->next
) {
2232 struct fragment
*frag
= p
->fragments
;
2234 SWAP(p
->new_name
, p
->old_name
);
2236 SWAP(p
->new_mode
, p
->old_mode
);
2237 SWAP(p
->is_new
, p
->is_delete
);
2238 SWAP(p
->lines_added
, p
->lines_deleted
);
2239 SWAP(p
->old_oid_prefix
, p
->new_oid_prefix
);
2241 for (; frag
; frag
= frag
->next
) {
2242 SWAP(frag
->newpos
, frag
->oldpos
);
2243 SWAP(frag
->newlines
, frag
->oldlines
);
2248 static const char pluses
[] =
2249 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2250 static const char minuses
[]=
2251 "----------------------------------------------------------------------";
2253 static void show_stats(struct apply_state
*state
, struct patch
*patch
)
2255 struct strbuf qname
= STRBUF_INIT
;
2256 char *cp
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
2259 quote_c_style(cp
, &qname
, NULL
, 0);
2262 * "scale" the filename
2264 max
= state
->max_len
;
2268 if (qname
.len
> max
) {
2269 cp
= strchr(qname
.buf
+ qname
.len
+ 3 - max
, '/');
2271 cp
= qname
.buf
+ qname
.len
+ 3 - max
;
2272 strbuf_splice(&qname
, 0, cp
- qname
.buf
, "...", 3);
2275 if (patch
->is_binary
) {
2276 printf(" %-*s | Bin\n", max
, qname
.buf
);
2277 strbuf_release(&qname
);
2281 printf(" %-*s |", max
, qname
.buf
);
2282 strbuf_release(&qname
);
2285 * scale the add/delete
2287 max
= max
+ state
->max_change
> 70 ? 70 - max
: state
->max_change
;
2288 add
= patch
->lines_added
;
2289 del
= patch
->lines_deleted
;
2291 if (state
->max_change
> 0) {
2292 int total
= ((add
+ del
) * max
+ state
->max_change
/ 2) / state
->max_change
;
2293 add
= (add
* max
+ state
->max_change
/ 2) / state
->max_change
;
2296 printf("%5d %.*s%.*s\n", patch
->lines_added
+ patch
->lines_deleted
,
2297 add
, pluses
, del
, minuses
);
2300 static int read_old_data(struct stat
*st
, struct patch
*patch
,
2301 const char *path
, struct strbuf
*buf
)
2303 int conv_flags
= patch
->crlf_in_old
?
2304 CONV_EOL_KEEP_CRLF
: CONV_EOL_RENORMALIZE
;
2305 switch (st
->st_mode
& S_IFMT
) {
2307 if (strbuf_readlink(buf
, path
, st
->st_size
) < 0)
2308 return error(_("unable to read symlink %s"), path
);
2311 if (strbuf_read_file(buf
, path
, st
->st_size
) != st
->st_size
)
2312 return error(_("unable to open or read %s"), path
);
2314 * "git apply" without "--index/--cached" should never look
2315 * at the index; the target file may not have been added to
2316 * the index yet, and we may not even be in any Git repository.
2317 * Pass NULL to convert_to_git() to stress this; the function
2318 * should never look at the index when explicit crlf option
2321 convert_to_git(NULL
, path
, buf
->buf
, buf
->len
, buf
, conv_flags
);
2329 * Update the preimage, and the common lines in postimage,
2330 * from buffer buf of length len. If postlen is 0 the postimage
2331 * is updated in place, otherwise it's updated on a new buffer
2335 static void update_pre_post_images(struct image
*preimage
,
2336 struct image
*postimage
,
2338 size_t len
, size_t postlen
)
2340 int i
, ctx
, reduced
;
2341 char *new_buf
, *old_buf
, *fixed
;
2342 struct image fixed_preimage
;
2345 * Update the preimage with whitespace fixes. Note that we
2346 * are not losing preimage->buf -- apply_one_fragment() will
2349 prepare_image(&fixed_preimage
, buf
, len
, 1);
2351 ? fixed_preimage
.nr
== preimage
->nr
2352 : fixed_preimage
.nr
<= preimage
->nr
);
2353 for (i
= 0; i
< fixed_preimage
.nr
; i
++)
2354 fixed_preimage
.line
[i
].flag
= preimage
->line
[i
].flag
;
2355 free(preimage
->line_allocated
);
2356 *preimage
= fixed_preimage
;
2359 * Adjust the common context lines in postimage. This can be
2360 * done in-place when we are shrinking it with whitespace
2361 * fixing, but needs a new buffer when ignoring whitespace or
2362 * expanding leading tabs to spaces.
2364 * We trust the caller to tell us if the update can be done
2365 * in place (postlen==0) or not.
2367 old_buf
= postimage
->buf
;
2369 new_buf
= postimage
->buf
= xmalloc(postlen
);
2372 fixed
= preimage
->buf
;
2374 for (i
= reduced
= ctx
= 0; i
< postimage
->nr
; i
++) {
2375 size_t l_len
= postimage
->line
[i
].len
;
2376 if (!(postimage
->line
[i
].flag
& LINE_COMMON
)) {
2377 /* an added line -- no counterparts in preimage */
2378 memmove(new_buf
, old_buf
, l_len
);
2384 /* a common context -- skip it in the original postimage */
2387 /* and find the corresponding one in the fixed preimage */
2388 while (ctx
< preimage
->nr
&&
2389 !(preimage
->line
[ctx
].flag
& LINE_COMMON
)) {
2390 fixed
+= preimage
->line
[ctx
].len
;
2395 * preimage is expected to run out, if the caller
2396 * fixed addition of trailing blank lines.
2398 if (preimage
->nr
<= ctx
) {
2403 /* and copy it in, while fixing the line length */
2404 l_len
= preimage
->line
[ctx
].len
;
2405 memcpy(new_buf
, fixed
, l_len
);
2408 postimage
->line
[i
].len
= l_len
;
2413 ? postlen
< new_buf
- postimage
->buf
2414 : postimage
->len
< new_buf
- postimage
->buf
)
2415 BUG("caller miscounted postlen: asked %d, orig = %d, used = %d",
2416 (int)postlen
, (int) postimage
->len
, (int)(new_buf
- postimage
->buf
));
2418 /* Fix the length of the whole thing */
2419 postimage
->len
= new_buf
- postimage
->buf
;
2420 postimage
->nr
-= reduced
;
2423 static int line_by_line_fuzzy_match(struct image
*img
,
2424 struct image
*preimage
,
2425 struct image
*postimage
,
2426 unsigned long current
,
2433 size_t postlen
= postimage
->len
;
2438 struct strbuf fixed
;
2442 for (i
= 0; i
< preimage_limit
; i
++) {
2443 size_t prelen
= preimage
->line
[i
].len
;
2444 size_t imglen
= img
->line
[current_lno
+i
].len
;
2446 if (!fuzzy_matchlines(img
->buf
+ current
+ imgoff
, imglen
,
2447 preimage
->buf
+ preoff
, prelen
))
2449 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2450 postlen
+= imglen
- prelen
;
2456 * Ok, the preimage matches with whitespace fuzz.
2458 * imgoff now holds the true length of the target that
2459 * matches the preimage before the end of the file.
2461 * Count the number of characters in the preimage that fall
2462 * beyond the end of the file and make sure that all of them
2463 * are whitespace characters. (This can only happen if
2464 * we are removing blank lines at the end of the file.)
2466 buf
= preimage_eof
= preimage
->buf
+ preoff
;
2467 for ( ; i
< preimage
->nr
; i
++)
2468 preoff
+= preimage
->line
[i
].len
;
2469 preimage_end
= preimage
->buf
+ preoff
;
2470 for ( ; buf
< preimage_end
; buf
++)
2475 * Update the preimage and the common postimage context
2476 * lines to use the same whitespace as the target.
2477 * If whitespace is missing in the target (i.e.
2478 * if the preimage extends beyond the end of the file),
2479 * use the whitespace from the preimage.
2481 extra_chars
= preimage_end
- preimage_eof
;
2482 strbuf_init(&fixed
, imgoff
+ extra_chars
);
2483 strbuf_add(&fixed
, img
->buf
+ current
, imgoff
);
2484 strbuf_add(&fixed
, preimage_eof
, extra_chars
);
2485 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2486 update_pre_post_images(preimage
, postimage
,
2487 fixed_buf
, fixed_len
, postlen
);
2491 static int match_fragment(struct apply_state
*state
,
2493 struct image
*preimage
,
2494 struct image
*postimage
,
2495 unsigned long current
,
2498 int match_beginning
, int match_end
)
2501 const char *orig
, *target
;
2502 struct strbuf fixed
= STRBUF_INIT
;
2507 if (preimage
->nr
+ current_lno
<= img
->nr
) {
2509 * The hunk falls within the boundaries of img.
2511 preimage_limit
= preimage
->nr
;
2512 if (match_end
&& (preimage
->nr
+ current_lno
!= img
->nr
)) {
2516 } else if (state
->ws_error_action
== correct_ws_error
&&
2517 (ws_rule
& WS_BLANK_AT_EOF
)) {
2519 * This hunk extends beyond the end of img, and we are
2520 * removing blank lines at the end of the file. This
2521 * many lines from the beginning of the preimage must
2522 * match with img, and the remainder of the preimage
2525 preimage_limit
= img
->nr
- current_lno
;
2528 * The hunk extends beyond the end of the img and
2529 * we are not removing blanks at the end, so we
2530 * should reject the hunk at this position.
2536 if (match_beginning
&& current_lno
) {
2541 /* Quick hash check */
2542 for (i
= 0; i
< preimage_limit
; i
++) {
2543 if ((img
->line
[current_lno
+ i
].flag
& LINE_PATCHED
) ||
2544 (preimage
->line
[i
].hash
!= img
->line
[current_lno
+ i
].hash
)) {
2550 if (preimage_limit
== preimage
->nr
) {
2552 * Do we have an exact match? If we were told to match
2553 * at the end, size must be exactly at current+fragsize,
2554 * otherwise current+fragsize must be still within the preimage,
2555 * and either case, the old piece should match the preimage
2559 ? (current
+ preimage
->len
== img
->len
)
2560 : (current
+ preimage
->len
<= img
->len
)) &&
2561 !memcmp(img
->buf
+ current
, preimage
->buf
, preimage
->len
)) {
2567 * The preimage extends beyond the end of img, so
2568 * there cannot be an exact match.
2570 * There must be one non-blank context line that match
2571 * a line before the end of img.
2573 const char *buf
, *buf_end
;
2575 buf
= preimage
->buf
;
2577 for (i
= 0; i
< preimage_limit
; i
++)
2578 buf_end
+= preimage
->line
[i
].len
;
2580 for ( ; buf
< buf_end
; buf
++)
2583 if (buf
== buf_end
) {
2590 * No exact match. If we are ignoring whitespace, run a line-by-line
2591 * fuzzy matching. We collect all the line length information because
2592 * we need it to adjust whitespace if we match.
2594 if (state
->ws_ignore_action
== ignore_ws_change
) {
2595 ret
= line_by_line_fuzzy_match(img
, preimage
, postimage
,
2596 current
, current_lno
, preimage_limit
);
2600 if (state
->ws_error_action
!= correct_ws_error
) {
2606 * The hunk does not apply byte-by-byte, but the hash says
2607 * it might with whitespace fuzz. We weren't asked to
2608 * ignore whitespace, we were asked to correct whitespace
2609 * errors, so let's try matching after whitespace correction.
2611 * While checking the preimage against the target, whitespace
2612 * errors in both fixed, we count how large the corresponding
2613 * postimage needs to be. The postimage prepared by
2614 * apply_one_fragment() has whitespace errors fixed on added
2615 * lines already, but the common lines were propagated as-is,
2616 * which may become longer when their whitespace errors are
2620 /* First count added lines in postimage */
2622 for (i
= 0; i
< postimage
->nr
; i
++) {
2623 if (!(postimage
->line
[i
].flag
& LINE_COMMON
))
2624 postlen
+= postimage
->line
[i
].len
;
2628 * The preimage may extend beyond the end of the file,
2629 * but in this loop we will only handle the part of the
2630 * preimage that falls within the file.
2632 strbuf_grow(&fixed
, preimage
->len
+ 1);
2633 orig
= preimage
->buf
;
2634 target
= img
->buf
+ current
;
2635 for (i
= 0; i
< preimage_limit
; i
++) {
2636 size_t oldlen
= preimage
->line
[i
].len
;
2637 size_t tgtlen
= img
->line
[current_lno
+ i
].len
;
2638 size_t fixstart
= fixed
.len
;
2639 struct strbuf tgtfix
;
2642 /* Try fixing the line in the preimage */
2643 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2645 /* Try fixing the line in the target */
2646 strbuf_init(&tgtfix
, tgtlen
);
2647 ws_fix_copy(&tgtfix
, target
, tgtlen
, ws_rule
, NULL
);
2650 * If they match, either the preimage was based on
2651 * a version before our tree fixed whitespace breakage,
2652 * or we are lacking a whitespace-fix patch the tree
2653 * the preimage was based on already had (i.e. target
2654 * has whitespace breakage, the preimage doesn't).
2655 * In either case, we are fixing the whitespace breakages
2656 * so we might as well take the fix together with their
2659 match
= (tgtfix
.len
== fixed
.len
- fixstart
&&
2660 !memcmp(tgtfix
.buf
, fixed
.buf
+ fixstart
,
2661 fixed
.len
- fixstart
));
2663 /* Add the length if this is common with the postimage */
2664 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2665 postlen
+= tgtfix
.len
;
2667 strbuf_release(&tgtfix
);
2679 * Now handle the lines in the preimage that falls beyond the
2680 * end of the file (if any). They will only match if they are
2681 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2684 for ( ; i
< preimage
->nr
; i
++) {
2685 size_t fixstart
= fixed
.len
; /* start of the fixed preimage */
2686 size_t oldlen
= preimage
->line
[i
].len
;
2689 /* Try fixing the line in the preimage */
2690 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2692 for (j
= fixstart
; j
< fixed
.len
; j
++) {
2693 if (!isspace(fixed
.buf
[j
])) {
2704 * Yes, the preimage is based on an older version that still
2705 * has whitespace breakages unfixed, and fixing them makes the
2706 * hunk match. Update the context lines in the postimage.
2708 if (postlen
< postimage
->len
)
2710 update_pre_post_images(preimage
, postimage
,
2711 fixed
.buf
, fixed
.len
, postlen
);
2716 strbuf_release(&fixed
);
2720 static int find_pos(struct apply_state
*state
,
2722 struct image
*preimage
,
2723 struct image
*postimage
,
2726 int match_beginning
, int match_end
)
2729 unsigned long backwards
, forwards
, current
;
2730 int backwards_lno
, forwards_lno
, current_lno
;
2733 * When running with --allow-overlap, it is possible that a hunk is
2734 * seen that pretends to start at the beginning (but no longer does),
2735 * and that *still* needs to match the end. So trust `match_end` more
2736 * than `match_beginning`.
2738 if (state
->allow_overlap
&& match_beginning
&& match_end
&&
2739 img
->nr
- preimage
->nr
!= 0)
2740 match_beginning
= 0;
2743 * If match_beginning or match_end is specified, there is no
2744 * point starting from a wrong line that will never match and
2745 * wander around and wait for a match at the specified end.
2747 if (match_beginning
)
2750 line
= img
->nr
- preimage
->nr
;
2753 * Because the comparison is unsigned, the following test
2754 * will also take care of a negative line number that can
2755 * result when match_end and preimage is larger than the target.
2757 if ((size_t) line
> img
->nr
)
2761 for (i
= 0; i
< line
; i
++)
2762 current
+= img
->line
[i
].len
;
2765 * There's probably some smart way to do this, but I'll leave
2766 * that to the smart and beautiful people. I'm simple and stupid.
2768 backwards
= current
;
2769 backwards_lno
= line
;
2771 forwards_lno
= line
;
2774 for (i
= 0; ; i
++) {
2775 if (match_fragment(state
, img
, preimage
, postimage
,
2776 current
, current_lno
, ws_rule
,
2777 match_beginning
, match_end
))
2781 if (backwards_lno
== 0 && forwards_lno
== img
->nr
)
2785 if (backwards_lno
== 0) {
2790 backwards
-= img
->line
[backwards_lno
].len
;
2791 current
= backwards
;
2792 current_lno
= backwards_lno
;
2794 if (forwards_lno
== img
->nr
) {
2798 forwards
+= img
->line
[forwards_lno
].len
;
2801 current_lno
= forwards_lno
;
2808 static void remove_first_line(struct image
*img
)
2810 img
->buf
+= img
->line
[0].len
;
2811 img
->len
-= img
->line
[0].len
;
2816 static void remove_last_line(struct image
*img
)
2818 img
->len
-= img
->line
[--img
->nr
].len
;
2822 * The change from "preimage" and "postimage" has been found to
2823 * apply at applied_pos (counts in line numbers) in "img".
2824 * Update "img" to remove "preimage" and replace it with "postimage".
2826 static void update_image(struct apply_state
*state
,
2829 struct image
*preimage
,
2830 struct image
*postimage
)
2833 * remove the copy of preimage at offset in img
2834 * and replace it with postimage
2837 size_t remove_count
, insert_count
, applied_at
= 0;
2842 * If we are removing blank lines at the end of img,
2843 * the preimage may extend beyond the end.
2844 * If that is the case, we must be careful only to
2845 * remove the part of the preimage that falls within
2846 * the boundaries of img. Initialize preimage_limit
2847 * to the number of lines in the preimage that falls
2848 * within the boundaries.
2850 preimage_limit
= preimage
->nr
;
2851 if (preimage_limit
> img
->nr
- applied_pos
)
2852 preimage_limit
= img
->nr
- applied_pos
;
2854 for (i
= 0; i
< applied_pos
; i
++)
2855 applied_at
+= img
->line
[i
].len
;
2858 for (i
= 0; i
< preimage_limit
; i
++)
2859 remove_count
+= img
->line
[applied_pos
+ i
].len
;
2860 insert_count
= postimage
->len
;
2862 /* Adjust the contents */
2863 result
= xmalloc(st_add3(st_sub(img
->len
, remove_count
), insert_count
, 1));
2864 memcpy(result
, img
->buf
, applied_at
);
2865 memcpy(result
+ applied_at
, postimage
->buf
, postimage
->len
);
2866 memcpy(result
+ applied_at
+ postimage
->len
,
2867 img
->buf
+ (applied_at
+ remove_count
),
2868 img
->len
- (applied_at
+ remove_count
));
2871 img
->len
+= insert_count
- remove_count
;
2872 result
[img
->len
] = '\0';
2874 /* Adjust the line table */
2875 nr
= img
->nr
+ postimage
->nr
- preimage_limit
;
2876 if (preimage_limit
< postimage
->nr
) {
2878 * NOTE: this knows that we never call remove_first_line()
2879 * on anything other than pre/post image.
2881 REALLOC_ARRAY(img
->line
, nr
);
2882 img
->line_allocated
= img
->line
;
2884 if (preimage_limit
!= postimage
->nr
)
2885 MOVE_ARRAY(img
->line
+ applied_pos
+ postimage
->nr
,
2886 img
->line
+ applied_pos
+ preimage_limit
,
2887 img
->nr
- (applied_pos
+ preimage_limit
));
2888 COPY_ARRAY(img
->line
+ applied_pos
, postimage
->line
, postimage
->nr
);
2889 if (!state
->allow_overlap
)
2890 for (i
= 0; i
< postimage
->nr
; i
++)
2891 img
->line
[applied_pos
+ i
].flag
|= LINE_PATCHED
;
2896 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2897 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2898 * replace the part of "img" with "postimage" text.
2900 static int apply_one_fragment(struct apply_state
*state
,
2901 struct image
*img
, struct fragment
*frag
,
2902 int inaccurate_eof
, unsigned ws_rule
,
2905 int match_beginning
, match_end
;
2906 const char *patch
= frag
->patch
;
2907 int size
= frag
->size
;
2908 char *old
, *oldlines
;
2909 struct strbuf newlines
;
2910 int new_blank_lines_at_end
= 0;
2911 int found_new_blank_lines_at_end
= 0;
2912 int hunk_linenr
= frag
->linenr
;
2913 unsigned long leading
, trailing
;
2914 int pos
, applied_pos
;
2915 struct image preimage
;
2916 struct image postimage
;
2918 memset(&preimage
, 0, sizeof(preimage
));
2919 memset(&postimage
, 0, sizeof(postimage
));
2920 oldlines
= xmalloc(size
);
2921 strbuf_init(&newlines
, size
);
2926 int len
= linelen(patch
, size
);
2928 int added_blank_line
= 0;
2929 int is_blank_context
= 0;
2936 * "plen" is how much of the line we should use for
2937 * the actual patch data. Normally we just remove the
2938 * first character on the line, but if the line is
2939 * followed by "\ No newline", then we also remove the
2940 * last one (which is the newline, of course).
2943 if (len
< size
&& patch
[len
] == '\\')
2946 if (state
->apply_in_reverse
) {
2949 else if (first
== '+')
2955 /* Newer GNU diff, empty context line */
2957 /* ... followed by '\No newline'; nothing */
2960 strbuf_addch(&newlines
, '\n');
2961 add_line_info(&preimage
, "\n", 1, LINE_COMMON
);
2962 add_line_info(&postimage
, "\n", 1, LINE_COMMON
);
2963 is_blank_context
= 1;
2966 if (plen
&& (ws_rule
& WS_BLANK_AT_EOF
) &&
2967 ws_blank_line(patch
+ 1, plen
))
2968 is_blank_context
= 1;
2971 memcpy(old
, patch
+ 1, plen
);
2972 add_line_info(&preimage
, old
, plen
,
2973 (first
== ' ' ? LINE_COMMON
: 0));
2979 /* --no-add does not add new lines */
2980 if (first
== '+' && state
->no_add
)
2983 start
= newlines
.len
;
2985 !state
->whitespace_error
||
2986 state
->ws_error_action
!= correct_ws_error
) {
2987 strbuf_add(&newlines
, patch
+ 1, plen
);
2990 ws_fix_copy(&newlines
, patch
+ 1, plen
, ws_rule
, &state
->applied_after_fixing_ws
);
2992 add_line_info(&postimage
, newlines
.buf
+ start
, newlines
.len
- start
,
2993 (first
== '+' ? 0 : LINE_COMMON
));
2995 (ws_rule
& WS_BLANK_AT_EOF
) &&
2996 ws_blank_line(patch
+ 1, plen
))
2997 added_blank_line
= 1;
2999 case '@': case '\\':
3000 /* Ignore it, we already handled it */
3003 if (state
->apply_verbosity
> verbosity_normal
)
3004 error(_("invalid start of line: '%c'"), first
);
3008 if (added_blank_line
) {
3009 if (!new_blank_lines_at_end
)
3010 found_new_blank_lines_at_end
= hunk_linenr
;
3011 new_blank_lines_at_end
++;
3013 else if (is_blank_context
)
3016 new_blank_lines_at_end
= 0;
3021 if (inaccurate_eof
&&
3022 old
> oldlines
&& old
[-1] == '\n' &&
3023 newlines
.len
> 0 && newlines
.buf
[newlines
.len
- 1] == '\n') {
3025 strbuf_setlen(&newlines
, newlines
.len
- 1);
3026 preimage
.line_allocated
[preimage
.nr
- 1].len
--;
3027 postimage
.line_allocated
[postimage
.nr
- 1].len
--;
3030 leading
= frag
->leading
;
3031 trailing
= frag
->trailing
;
3034 * A hunk to change lines at the beginning would begin with
3036 * but we need to be careful. -U0 that inserts before the second
3037 * line also has this pattern.
3039 * And a hunk to add to an empty file would begin with
3042 * In other words, a hunk that is (frag->oldpos <= 1) with or
3043 * without leading context must match at the beginning.
3045 match_beginning
= (!frag
->oldpos
||
3046 (frag
->oldpos
== 1 && !state
->unidiff_zero
));
3049 * A hunk without trailing lines must match at the end.
3050 * However, we simply cannot tell if a hunk must match end
3051 * from the lack of trailing lines if the patch was generated
3052 * with unidiff without any context.
3054 match_end
= !state
->unidiff_zero
&& !trailing
;
3056 pos
= frag
->newpos
? (frag
->newpos
- 1) : 0;
3057 preimage
.buf
= oldlines
;
3058 preimage
.len
= old
- oldlines
;
3059 postimage
.buf
= newlines
.buf
;
3060 postimage
.len
= newlines
.len
;
3061 preimage
.line
= preimage
.line_allocated
;
3062 postimage
.line
= postimage
.line_allocated
;
3066 applied_pos
= find_pos(state
, img
, &preimage
, &postimage
, pos
,
3067 ws_rule
, match_beginning
, match_end
);
3069 if (applied_pos
>= 0)
3072 /* Am I at my context limits? */
3073 if ((leading
<= state
->p_context
) && (trailing
<= state
->p_context
))
3075 if (match_beginning
|| match_end
) {
3076 match_beginning
= match_end
= 0;
3081 * Reduce the number of context lines; reduce both
3082 * leading and trailing if they are equal otherwise
3083 * just reduce the larger context.
3085 if (leading
>= trailing
) {
3086 remove_first_line(&preimage
);
3087 remove_first_line(&postimage
);
3091 if (trailing
> leading
) {
3092 remove_last_line(&preimage
);
3093 remove_last_line(&postimage
);
3098 if (applied_pos
>= 0) {
3099 if (new_blank_lines_at_end
&&
3100 preimage
.nr
+ applied_pos
>= img
->nr
&&
3101 (ws_rule
& WS_BLANK_AT_EOF
) &&
3102 state
->ws_error_action
!= nowarn_ws_error
) {
3103 record_ws_error(state
, WS_BLANK_AT_EOF
, "+", 1,
3104 found_new_blank_lines_at_end
);
3105 if (state
->ws_error_action
== correct_ws_error
) {
3106 while (new_blank_lines_at_end
--)
3107 remove_last_line(&postimage
);
3110 * We would want to prevent write_out_results()
3111 * from taking place in apply_patch() that follows
3112 * the callchain led us here, which is:
3113 * apply_patch->check_patch_list->check_patch->
3114 * apply_data->apply_fragments->apply_one_fragment
3116 if (state
->ws_error_action
== die_on_ws_error
)
3120 if (state
->apply_verbosity
> verbosity_normal
&& applied_pos
!= pos
) {
3121 int offset
= applied_pos
- pos
;
3122 if (state
->apply_in_reverse
)
3123 offset
= 0 - offset
;
3125 Q_("Hunk #%d succeeded at %d (offset %d line).",
3126 "Hunk #%d succeeded at %d (offset %d lines).",
3128 nth_fragment
, applied_pos
+ 1, offset
);
3132 * Warn if it was necessary to reduce the number
3135 if ((leading
!= frag
->leading
||
3136 trailing
!= frag
->trailing
) && state
->apply_verbosity
> verbosity_silent
)
3137 fprintf_ln(stderr
, _("Context reduced to (%ld/%ld)"
3138 " to apply fragment at %d"),
3139 leading
, trailing
, applied_pos
+1);
3140 update_image(state
, img
, applied_pos
, &preimage
, &postimage
);
3142 if (state
->apply_verbosity
> verbosity_normal
)
3143 error(_("while searching for:\n%.*s"),
3144 (int)(old
- oldlines
), oldlines
);
3149 strbuf_release(&newlines
);
3150 free(preimage
.line_allocated
);
3151 free(postimage
.line_allocated
);
3153 return (applied_pos
< 0);
3156 static int apply_binary_fragment(struct apply_state
*state
,
3158 struct patch
*patch
)
3160 struct fragment
*fragment
= patch
->fragments
;
3165 return error(_("missing binary patch data for '%s'"),
3170 /* Binary patch is irreversible without the optional second hunk */
3171 if (state
->apply_in_reverse
) {
3172 if (!fragment
->next
)
3173 return error(_("cannot reverse-apply a binary patch "
3174 "without the reverse hunk to '%s'"),
3176 ? patch
->new_name
: patch
->old_name
);
3177 fragment
= fragment
->next
;
3179 switch (fragment
->binary_patch_method
) {
3180 case BINARY_DELTA_DEFLATED
:
3181 dst
= patch_delta(img
->buf
, img
->len
, fragment
->patch
,
3182 fragment
->size
, &len
);
3189 case BINARY_LITERAL_DEFLATED
:
3191 img
->len
= fragment
->size
;
3192 img
->buf
= xmemdupz(fragment
->patch
, img
->len
);
3199 * Replace "img" with the result of applying the binary patch.
3200 * The binary patch data itself in patch->fragment is still kept
3201 * but the preimage prepared by the caller in "img" is freed here
3202 * or in the helper function apply_binary_fragment() this calls.
3204 static int apply_binary(struct apply_state
*state
,
3206 struct patch
*patch
)
3208 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3209 struct object_id oid
;
3210 const unsigned hexsz
= the_hash_algo
->hexsz
;
3213 * For safety, we require patch index line to contain
3214 * full hex textual object ID for old and new, at least for now.
3216 if (strlen(patch
->old_oid_prefix
) != hexsz
||
3217 strlen(patch
->new_oid_prefix
) != hexsz
||
3218 get_oid_hex(patch
->old_oid_prefix
, &oid
) ||
3219 get_oid_hex(patch
->new_oid_prefix
, &oid
))
3220 return error(_("cannot apply binary patch to '%s' "
3221 "without full index line"), name
);
3223 if (patch
->old_name
) {
3225 * See if the old one matches what the patch
3228 hash_object_file(the_hash_algo
, img
->buf
, img
->len
, OBJ_BLOB
,
3230 if (strcmp(oid_to_hex(&oid
), patch
->old_oid_prefix
))
3231 return error(_("the patch applies to '%s' (%s), "
3232 "which does not match the "
3233 "current contents."),
3234 name
, oid_to_hex(&oid
));
3237 /* Otherwise, the old one must be empty. */
3239 return error(_("the patch applies to an empty "
3240 "'%s' but it is not empty"), name
);
3243 get_oid_hex(patch
->new_oid_prefix
, &oid
);
3244 if (is_null_oid(&oid
)) {
3246 return 0; /* deletion patch */
3249 if (has_object(the_repository
, &oid
, 0)) {
3250 /* We already have the postimage */
3251 enum object_type type
;
3255 result
= repo_read_object_file(the_repository
, &oid
, &type
,
3258 return error(_("the necessary postimage %s for "
3259 "'%s' cannot be read"),
3260 patch
->new_oid_prefix
, name
);
3266 * We have verified buf matches the preimage;
3267 * apply the patch data to it, which is stored
3268 * in the patch->fragments->{patch,size}.
3270 if (apply_binary_fragment(state
, img
, patch
))
3271 return error(_("binary patch does not apply to '%s'"),
3274 /* verify that the result matches */
3275 hash_object_file(the_hash_algo
, img
->buf
, img
->len
, OBJ_BLOB
,
3277 if (strcmp(oid_to_hex(&oid
), patch
->new_oid_prefix
))
3278 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3279 name
, patch
->new_oid_prefix
, oid_to_hex(&oid
));
3285 static int apply_fragments(struct apply_state
*state
, struct image
*img
, struct patch
*patch
)
3287 struct fragment
*frag
= patch
->fragments
;
3288 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3289 unsigned ws_rule
= patch
->ws_rule
;
3290 unsigned inaccurate_eof
= patch
->inaccurate_eof
;
3293 if (patch
->is_binary
)
3294 return apply_binary(state
, img
, patch
);
3298 if (apply_one_fragment(state
, img
, frag
, inaccurate_eof
, ws_rule
, nth
)) {
3299 error(_("patch failed: %s:%ld"), name
, frag
->oldpos
);
3300 if (!state
->apply_with_reject
)
3309 static int read_blob_object(struct strbuf
*buf
, const struct object_id
*oid
, unsigned mode
)
3311 if (S_ISGITLINK(mode
)) {
3312 strbuf_grow(buf
, 100);
3313 strbuf_addf(buf
, "Subproject commit %s\n", oid_to_hex(oid
));
3315 enum object_type type
;
3319 result
= repo_read_object_file(the_repository
, oid
, &type
,
3323 /* XXX read_sha1_file NUL-terminates */
3324 strbuf_attach(buf
, result
, sz
, sz
+ 1);
3329 static int read_file_or_gitlink(const struct cache_entry
*ce
, struct strbuf
*buf
)
3333 return read_blob_object(buf
, &ce
->oid
, ce
->ce_mode
);
3336 static struct patch
*in_fn_table(struct apply_state
*state
, const char *name
)
3338 struct string_list_item
*item
;
3343 item
= string_list_lookup(&state
->fn_table
, name
);
3345 return (struct patch
*)item
->util
;
3351 * item->util in the filename table records the status of the path.
3352 * Usually it points at a patch (whose result records the contents
3353 * of it after applying it), but it could be PATH_WAS_DELETED for a
3354 * path that a previously applied patch has already removed, or
3355 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3357 * The latter is needed to deal with a case where two paths A and B
3358 * are swapped by first renaming A to B and then renaming B to A;
3359 * moving A to B should not be prevented due to presence of B as we
3360 * will remove it in a later patch.
3362 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3363 #define PATH_WAS_DELETED ((struct patch *) -1)
3365 static int to_be_deleted(struct patch
*patch
)
3367 return patch
== PATH_TO_BE_DELETED
;
3370 static int was_deleted(struct patch
*patch
)
3372 return patch
== PATH_WAS_DELETED
;
3375 static void add_to_fn_table(struct apply_state
*state
, struct patch
*patch
)
3377 struct string_list_item
*item
;
3380 * Always add new_name unless patch is a deletion
3381 * This should cover the cases for normal diffs,
3382 * file creations and copies
3384 if (patch
->new_name
) {
3385 item
= string_list_insert(&state
->fn_table
, patch
->new_name
);
3390 * store a failure on rename/deletion cases because
3391 * later chunks shouldn't patch old names
3393 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3394 item
= string_list_insert(&state
->fn_table
, patch
->old_name
);
3395 item
->util
= PATH_WAS_DELETED
;
3399 static void prepare_fn_table(struct apply_state
*state
, struct patch
*patch
)
3402 * store information about incoming file deletion
3405 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3406 struct string_list_item
*item
;
3407 item
= string_list_insert(&state
->fn_table
, patch
->old_name
);
3408 item
->util
= PATH_TO_BE_DELETED
;
3410 patch
= patch
->next
;
3414 static int checkout_target(struct index_state
*istate
,
3415 struct cache_entry
*ce
, struct stat
*st
)
3417 struct checkout costate
= CHECKOUT_INIT
;
3419 costate
.refresh_cache
= 1;
3420 costate
.istate
= istate
;
3421 if (checkout_entry(ce
, &costate
, NULL
, NULL
) ||
3422 lstat(ce
->name
, st
))
3423 return error(_("cannot checkout %s"), ce
->name
);
3427 static struct patch
*previous_patch(struct apply_state
*state
,
3428 struct patch
*patch
,
3431 struct patch
*previous
;
3434 if (patch
->is_copy
|| patch
->is_rename
)
3435 return NULL
; /* "git" patches do not depend on the order */
3437 previous
= in_fn_table(state
, patch
->old_name
);
3441 if (to_be_deleted(previous
))
3442 return NULL
; /* the deletion hasn't happened yet */
3444 if (was_deleted(previous
))
3450 static int verify_index_match(struct apply_state
*state
,
3451 const struct cache_entry
*ce
,
3454 if (S_ISGITLINK(ce
->ce_mode
)) {
3455 if (!S_ISDIR(st
->st_mode
))
3459 return ie_match_stat(state
->repo
->index
, ce
, st
,
3460 CE_MATCH_IGNORE_VALID
| CE_MATCH_IGNORE_SKIP_WORKTREE
);
3463 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3465 static int load_patch_target(struct apply_state
*state
,
3467 const struct cache_entry
*ce
,
3469 struct patch
*patch
,
3471 unsigned expected_mode
)
3473 if (state
->cached
|| state
->check_index
) {
3474 if (read_file_or_gitlink(ce
, buf
))
3475 return error(_("failed to read %s"), name
);
3477 if (S_ISGITLINK(expected_mode
)) {
3479 return read_file_or_gitlink(ce
, buf
);
3481 return SUBMODULE_PATCH_WITHOUT_INDEX
;
3482 } else if (has_symlink_leading_path(name
, strlen(name
))) {
3483 return error(_("reading from '%s' beyond a symbolic link"), name
);
3485 if (read_old_data(st
, patch
, name
, buf
))
3486 return error(_("failed to read %s"), name
);
3493 * We are about to apply "patch"; populate the "image" with the
3494 * current version we have, from the working tree or from the index,
3495 * depending on the situation e.g. --cached/--index. If we are
3496 * applying a non-git patch that incrementally updates the tree,
3497 * we read from the result of a previous diff.
3499 static int load_preimage(struct apply_state
*state
,
3500 struct image
*image
,
3501 struct patch
*patch
, struct stat
*st
,
3502 const struct cache_entry
*ce
)
3504 struct strbuf buf
= STRBUF_INIT
;
3507 struct patch
*previous
;
3510 previous
= previous_patch(state
, patch
, &status
);
3512 return error(_("path %s has been renamed/deleted"),
3515 /* We have a patched copy in memory; use that. */
3516 strbuf_add(&buf
, previous
->result
, previous
->resultsize
);
3518 status
= load_patch_target(state
, &buf
, ce
, st
, patch
,
3519 patch
->old_name
, patch
->old_mode
);
3522 else if (status
== SUBMODULE_PATCH_WITHOUT_INDEX
) {
3524 * There is no way to apply subproject
3525 * patch without looking at the index.
3526 * NEEDSWORK: shouldn't this be flagged
3529 free_fragment_list(patch
->fragments
);
3530 patch
->fragments
= NULL
;
3531 } else if (status
) {
3532 return error(_("failed to read %s"), patch
->old_name
);
3536 img
= strbuf_detach(&buf
, &len
);
3537 prepare_image(image
, img
, len
, !patch
->is_binary
);
3541 static int resolve_to(struct image
*image
, const struct object_id
*result_id
)
3544 enum object_type type
;
3548 image
->buf
= repo_read_object_file(the_repository
, result_id
, &type
,
3550 if (!image
->buf
|| type
!= OBJ_BLOB
)
3551 die("unable to read blob object %s", oid_to_hex(result_id
));
3557 static int three_way_merge(struct apply_state
*state
,
3558 struct image
*image
,
3560 const struct object_id
*base
,
3561 const struct object_id
*ours
,
3562 const struct object_id
*theirs
)
3564 mmfile_t base_file
, our_file
, their_file
;
3565 struct ll_merge_options merge_opts
= LL_MERGE_OPTIONS_INIT
;
3566 mmbuffer_t result
= { NULL
};
3567 enum ll_merge_result status
;
3569 /* resolve trivial cases first */
3570 if (oideq(base
, ours
))
3571 return resolve_to(image
, theirs
);
3572 else if (oideq(base
, theirs
) || oideq(ours
, theirs
))
3573 return resolve_to(image
, ours
);
3575 read_mmblob(&base_file
, base
);
3576 read_mmblob(&our_file
, ours
);
3577 read_mmblob(&their_file
, theirs
);
3578 merge_opts
.variant
= state
->merge_variant
;
3579 status
= ll_merge(&result
, path
,
3582 &their_file
, "theirs",
3585 if (status
== LL_MERGE_BINARY_CONFLICT
)
3586 warning("Cannot merge binary files: %s (%s vs. %s)",
3587 path
, "ours", "theirs");
3588 free(base_file
.ptr
);
3590 free(their_file
.ptr
);
3591 if (status
< 0 || !result
.ptr
) {
3596 image
->buf
= result
.ptr
;
3597 image
->len
= result
.size
;
3603 * When directly falling back to add/add three-way merge, we read from
3604 * the current contents of the new_name. In no cases other than that
3605 * this function will be called.
3607 static int load_current(struct apply_state
*state
,
3608 struct image
*image
,
3609 struct patch
*patch
)
3611 struct strbuf buf
= STRBUF_INIT
;
3616 struct cache_entry
*ce
;
3617 char *name
= patch
->new_name
;
3618 unsigned mode
= patch
->new_mode
;
3621 BUG("patch to %s is not a creation", patch
->old_name
);
3623 pos
= index_name_pos(state
->repo
->index
, name
, strlen(name
));
3625 return error(_("%s: does not exist in index"), name
);
3626 ce
= state
->repo
->index
->cache
[pos
];
3627 if (lstat(name
, &st
)) {
3628 if (errno
!= ENOENT
)
3629 return error_errno("%s", name
);
3630 if (checkout_target(state
->repo
->index
, ce
, &st
))
3633 if (verify_index_match(state
, ce
, &st
))
3634 return error(_("%s: does not match index"), name
);
3636 status
= load_patch_target(state
, &buf
, ce
, &st
, patch
, name
, mode
);
3641 img
= strbuf_detach(&buf
, &len
);
3642 prepare_image(image
, img
, len
, !patch
->is_binary
);
3646 static int try_threeway(struct apply_state
*state
,
3647 struct image
*image
,
3648 struct patch
*patch
,
3650 const struct cache_entry
*ce
)
3652 struct object_id pre_oid
, post_oid
, our_oid
;
3653 struct strbuf buf
= STRBUF_INIT
;
3657 struct image tmp_image
;
3659 /* No point falling back to 3-way merge in these cases */
3660 if (patch
->is_delete
||
3661 S_ISGITLINK(patch
->old_mode
) || S_ISGITLINK(patch
->new_mode
) ||
3662 (patch
->is_new
&& !patch
->direct_to_threeway
) ||
3663 (patch
->is_rename
&& !patch
->lines_added
&& !patch
->lines_deleted
))
3666 /* Preimage the patch was prepared for */
3668 write_object_file("", 0, OBJ_BLOB
, &pre_oid
);
3669 else if (repo_get_oid(the_repository
, patch
->old_oid_prefix
, &pre_oid
) ||
3670 read_blob_object(&buf
, &pre_oid
, patch
->old_mode
))
3671 return error(_("repository lacks the necessary blob to perform 3-way merge."));
3673 if (state
->apply_verbosity
> verbosity_silent
&& patch
->direct_to_threeway
)
3674 fprintf(stderr
, _("Performing three-way merge...\n"));
3676 img
= strbuf_detach(&buf
, &len
);
3677 prepare_image(&tmp_image
, img
, len
, 1);
3678 /* Apply the patch to get the post image */
3679 if (apply_fragments(state
, &tmp_image
, patch
) < 0) {
3680 clear_image(&tmp_image
);
3683 /* post_oid is theirs */
3684 write_object_file(tmp_image
.buf
, tmp_image
.len
, OBJ_BLOB
, &post_oid
);
3685 clear_image(&tmp_image
);
3687 /* our_oid is ours */
3688 if (patch
->is_new
) {
3689 if (load_current(state
, &tmp_image
, patch
))
3690 return error(_("cannot read the current contents of '%s'"),
3693 if (load_preimage(state
, &tmp_image
, patch
, st
, ce
))
3694 return error(_("cannot read the current contents of '%s'"),
3697 write_object_file(tmp_image
.buf
, tmp_image
.len
, OBJ_BLOB
, &our_oid
);
3698 clear_image(&tmp_image
);
3700 /* in-core three-way merge between post and our using pre as base */
3701 status
= three_way_merge(state
, image
, patch
->new_name
,
3702 &pre_oid
, &our_oid
, &post_oid
);
3704 if (state
->apply_verbosity
> verbosity_silent
)
3706 _("Failed to perform three-way merge...\n"));
3711 patch
->conflicted_threeway
= 1;
3713 oidclr(&patch
->threeway_stage
[0], the_repository
->hash_algo
);
3715 oidcpy(&patch
->threeway_stage
[0], &pre_oid
);
3716 oidcpy(&patch
->threeway_stage
[1], &our_oid
);
3717 oidcpy(&patch
->threeway_stage
[2], &post_oid
);
3718 if (state
->apply_verbosity
> verbosity_silent
)
3720 _("Applied patch to '%s' with conflicts.\n"),
3723 if (state
->apply_verbosity
> verbosity_silent
)
3725 _("Applied patch to '%s' cleanly.\n"),
3731 static int apply_data(struct apply_state
*state
, struct patch
*patch
,
3732 struct stat
*st
, const struct cache_entry
*ce
)
3736 if (load_preimage(state
, &image
, patch
, st
, ce
) < 0)
3739 if (!state
->threeway
|| try_threeway(state
, &image
, patch
, st
, ce
) < 0) {
3740 if (state
->apply_verbosity
> verbosity_silent
&&
3741 state
->threeway
&& !patch
->direct_to_threeway
)
3742 fprintf(stderr
, _("Falling back to direct application...\n"));
3744 /* Note: with --reject, apply_fragments() returns 0 */
3745 if (patch
->direct_to_threeway
|| apply_fragments(state
, &image
, patch
) < 0) {
3746 clear_image(&image
);
3750 patch
->result
= image
.buf
;
3751 patch
->resultsize
= image
.len
;
3752 add_to_fn_table(state
, patch
);
3753 free(image
.line_allocated
);
3755 if (0 < patch
->is_delete
&& patch
->resultsize
)
3756 return error(_("removal patch leaves file contents"));
3762 * If "patch" that we are looking at modifies or deletes what we have,
3763 * we would want it not to lose any local modification we have, either
3764 * in the working tree or in the index.
3766 * This also decides if a non-git patch is a creation patch or a
3767 * modification to an existing empty file. We do not check the state
3768 * of the current tree for a creation patch in this function; the caller
3769 * check_patch() separately makes sure (and errors out otherwise) that
3770 * the path the patch creates does not exist in the current tree.
3772 static int check_preimage(struct apply_state
*state
,
3773 struct patch
*patch
,
3774 struct cache_entry
**ce
,
3777 const char *old_name
= patch
->old_name
;
3778 struct patch
*previous
= NULL
;
3779 int stat_ret
= 0, status
;
3780 unsigned st_mode
= 0;
3785 assert(patch
->is_new
<= 0);
3786 previous
= previous_patch(state
, patch
, &status
);
3789 return error(_("path %s has been renamed/deleted"), old_name
);
3791 st_mode
= previous
->new_mode
;
3792 } else if (!state
->cached
) {
3793 stat_ret
= lstat(old_name
, st
);
3794 if (stat_ret
&& errno
!= ENOENT
)
3795 return error_errno("%s", old_name
);
3798 if (state
->check_index
&& !previous
) {
3799 int pos
= index_name_pos(state
->repo
->index
, old_name
,
3802 if (patch
->is_new
< 0)
3804 return error(_("%s: does not exist in index"), old_name
);
3806 *ce
= state
->repo
->index
->cache
[pos
];
3808 if (checkout_target(state
->repo
->index
, *ce
, st
))
3811 if (!state
->cached
&& verify_index_match(state
, *ce
, st
))
3812 return error(_("%s: does not match index"), old_name
);
3814 st_mode
= (*ce
)->ce_mode
;
3815 } else if (stat_ret
< 0) {
3816 if (patch
->is_new
< 0)
3818 return error_errno("%s", old_name
);
3821 if (!state
->cached
&& !previous
) {
3822 if (*ce
&& !(*ce
)->ce_mode
)
3823 BUG("ce_mode == 0 for path '%s'", old_name
);
3825 if (trust_executable_bit
)
3826 st_mode
= ce_mode_from_stat(*ce
, st
->st_mode
);
3828 st_mode
= (*ce
)->ce_mode
;
3830 st_mode
= patch
->old_mode
;
3833 if (patch
->is_new
< 0)
3835 if (!patch
->old_mode
)
3836 patch
->old_mode
= st_mode
;
3837 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
3838 return error(_("%s: wrong type"), old_name
);
3839 if (st_mode
!= patch
->old_mode
)
3840 warning(_("%s has type %o, expected %o"),
3841 old_name
, st_mode
, patch
->old_mode
);
3842 if (!patch
->new_mode
&& !patch
->is_delete
)
3843 patch
->new_mode
= st_mode
;
3848 patch
->is_delete
= 0;
3849 FREE_AND_NULL(patch
->old_name
);
3854 #define EXISTS_IN_INDEX 1
3855 #define EXISTS_IN_WORKTREE 2
3856 #define EXISTS_IN_INDEX_AS_ITA 3
3858 static int check_to_create(struct apply_state
*state
,
3859 const char *new_name
,
3864 if (state
->check_index
&& (!ok_if_exists
|| !state
->cached
)) {
3867 pos
= index_name_pos(state
->repo
->index
, new_name
, strlen(new_name
));
3869 struct cache_entry
*ce
= state
->repo
->index
->cache
[pos
];
3871 /* allow ITA, as they do not yet exist in the index */
3872 if (!ok_if_exists
&& !(ce
->ce_flags
& CE_INTENT_TO_ADD
))
3873 return EXISTS_IN_INDEX
;
3875 /* ITA entries can never match working tree files */
3876 if (!state
->cached
&& (ce
->ce_flags
& CE_INTENT_TO_ADD
))
3877 return EXISTS_IN_INDEX_AS_ITA
;
3884 if (!lstat(new_name
, &nst
)) {
3885 if (S_ISDIR(nst
.st_mode
) || ok_if_exists
)
3888 * A leading component of new_name might be a symlink
3889 * that is going to be removed with this patch, but
3890 * still pointing at somewhere that has the path.
3891 * In such a case, path "new_name" does not exist as
3892 * far as git is concerned.
3894 if (has_symlink_leading_path(new_name
, strlen(new_name
)))
3897 return EXISTS_IN_WORKTREE
;
3898 } else if (!is_missing_file_error(errno
)) {
3899 return error_errno("%s", new_name
);
3904 static void prepare_symlink_changes(struct apply_state
*state
, struct patch
*patch
)
3906 for ( ; patch
; patch
= patch
->next
) {
3907 if ((patch
->old_name
&& S_ISLNK(patch
->old_mode
)) &&
3908 (patch
->is_rename
|| patch
->is_delete
))
3909 /* the symlink at patch->old_name is removed */
3910 strset_add(&state
->removed_symlinks
, patch
->old_name
);
3912 if (patch
->new_name
&& S_ISLNK(patch
->new_mode
))
3913 /* the symlink at patch->new_name is created or remains */
3914 strset_add(&state
->kept_symlinks
, patch
->new_name
);
3918 static int path_is_beyond_symlink_1(struct apply_state
*state
, struct strbuf
*name
)
3921 while (--name
->len
&& name
->buf
[name
->len
] != '/')
3922 ; /* scan backwards */
3925 name
->buf
[name
->len
] = '\0';
3926 if (strset_contains(&state
->kept_symlinks
, name
->buf
))
3928 if (strset_contains(&state
->removed_symlinks
, name
->buf
))
3930 * This cannot be "return 0", because we may
3931 * see a new one created at a higher level.
3935 /* otherwise, check the preimage */
3936 if (state
->check_index
) {
3937 struct cache_entry
*ce
;
3939 ce
= index_file_exists(state
->repo
->index
, name
->buf
,
3940 name
->len
, ignore_case
);
3941 if (ce
&& S_ISLNK(ce
->ce_mode
))
3945 if (!lstat(name
->buf
, &st
) && S_ISLNK(st
.st_mode
))
3952 static int path_is_beyond_symlink(struct apply_state
*state
, const char *name_
)
3955 struct strbuf name
= STRBUF_INIT
;
3957 assert(*name_
!= '\0');
3958 strbuf_addstr(&name
, name_
);
3959 ret
= path_is_beyond_symlink_1(state
, &name
);
3960 strbuf_release(&name
);
3965 static int check_unsafe_path(struct patch
*patch
)
3967 const char *old_name
= NULL
;
3968 const char *new_name
= NULL
;
3969 if (patch
->is_delete
)
3970 old_name
= patch
->old_name
;
3971 else if (!patch
->is_new
&& !patch
->is_copy
)
3972 old_name
= patch
->old_name
;
3973 if (!patch
->is_delete
)
3974 new_name
= patch
->new_name
;
3976 if (old_name
&& !verify_path(old_name
, patch
->old_mode
))
3977 return error(_("invalid path '%s'"), old_name
);
3978 if (new_name
&& !verify_path(new_name
, patch
->new_mode
))
3979 return error(_("invalid path '%s'"), new_name
);
3984 * Check and apply the patch in-core; leave the result in patch->result
3985 * for the caller to write it out to the final destination.
3987 static int check_patch(struct apply_state
*state
, struct patch
*patch
)
3990 const char *old_name
= patch
->old_name
;
3991 const char *new_name
= patch
->new_name
;
3992 const char *name
= old_name
? old_name
: new_name
;
3993 struct cache_entry
*ce
= NULL
;
3994 struct patch
*tpatch
;
3998 patch
->rejected
= 1; /* we will drop this after we succeed */
4000 status
= check_preimage(state
, patch
, &ce
, &st
);
4003 old_name
= patch
->old_name
;
4006 * A type-change diff is always split into a patch to delete
4007 * old, immediately followed by a patch to create new (see
4008 * diff.c::run_diff()); in such a case it is Ok that the entry
4009 * to be deleted by the previous patch is still in the working
4010 * tree and in the index.
4012 * A patch to swap-rename between A and B would first rename A
4013 * to B and then rename B to A. While applying the first one,
4014 * the presence of B should not stop A from getting renamed to
4015 * B; ask to_be_deleted() about the later rename. Removal of
4016 * B and rename from A to B is handled the same way by asking
4019 if ((tpatch
= in_fn_table(state
, new_name
)) &&
4020 (was_deleted(tpatch
) || to_be_deleted(tpatch
)))
4026 ((0 < patch
->is_new
) || patch
->is_rename
|| patch
->is_copy
)) {
4027 int err
= check_to_create(state
, new_name
, ok_if_exists
);
4029 if (err
&& state
->threeway
) {
4030 patch
->direct_to_threeway
= 1;
4031 } else switch (err
) {
4034 case EXISTS_IN_INDEX
:
4035 return error(_("%s: already exists in index"), new_name
);
4036 case EXISTS_IN_INDEX_AS_ITA
:
4037 return error(_("%s: does not match index"), new_name
);
4038 case EXISTS_IN_WORKTREE
:
4039 return error(_("%s: already exists in working directory"),
4045 if (!patch
->new_mode
) {
4046 if (0 < patch
->is_new
)
4047 patch
->new_mode
= S_IFREG
| 0644;
4049 patch
->new_mode
= patch
->old_mode
;
4053 if (new_name
&& old_name
) {
4054 int same
= !strcmp(old_name
, new_name
);
4055 if (!patch
->new_mode
)
4056 patch
->new_mode
= patch
->old_mode
;
4057 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
) {
4059 return error(_("new mode (%o) of %s does not "
4060 "match old mode (%o)"),
4061 patch
->new_mode
, new_name
,
4064 return error(_("new mode (%o) of %s does not "
4065 "match old mode (%o) of %s"),
4066 patch
->new_mode
, new_name
,
4067 patch
->old_mode
, old_name
);
4071 if (!state
->unsafe_paths
&& check_unsafe_path(patch
))
4075 * An attempt to read from or delete a path that is beyond a
4076 * symbolic link will be prevented by load_patch_target() that
4077 * is called at the beginning of apply_data() so we do not
4078 * have to worry about a patch marked with "is_delete" bit
4079 * here. We however need to make sure that the patch result
4080 * is not deposited to a path that is beyond a symbolic link
4083 if (!patch
->is_delete
&& path_is_beyond_symlink(state
, patch
->new_name
))
4084 return error(_("affected file '%s' is beyond a symbolic link"),
4087 if (apply_data(state
, patch
, &st
, ce
) < 0)
4088 return error(_("%s: patch does not apply"), name
);
4089 patch
->rejected
= 0;
4093 static int check_patch_list(struct apply_state
*state
, struct patch
*patch
)
4097 prepare_symlink_changes(state
, patch
);
4098 prepare_fn_table(state
, patch
);
4101 if (state
->apply_verbosity
> verbosity_normal
)
4102 say_patch_name(stderr
,
4103 _("Checking patch %s..."), patch
);
4104 res
= check_patch(state
, patch
);
4108 patch
= patch
->next
;
4113 static int read_apply_cache(struct apply_state
*state
)
4115 if (state
->index_file
)
4116 return read_index_from(state
->repo
->index
, state
->index_file
,
4117 repo_get_git_dir(the_repository
));
4119 return repo_read_index(state
->repo
);
4122 /* This function tries to read the object name from the current index */
4123 static int get_current_oid(struct apply_state
*state
, const char *path
,
4124 struct object_id
*oid
)
4128 if (read_apply_cache(state
) < 0)
4130 pos
= index_name_pos(state
->repo
->index
, path
, strlen(path
));
4133 oidcpy(oid
, &state
->repo
->index
->cache
[pos
]->oid
);
4137 static int preimage_oid_in_gitlink_patch(struct patch
*p
, struct object_id
*oid
)
4140 * A usable gitlink patch has only one fragment (hunk) that looks like:
4142 * -Subproject commit <old sha1>
4143 * +Subproject commit <new sha1>
4146 * -Subproject commit <old sha1>
4147 * for a removal patch.
4149 struct fragment
*hunk
= p
->fragments
;
4150 static const char heading
[] = "-Subproject commit ";
4153 if (/* does the patch have only one hunk? */
4154 hunk
&& !hunk
->next
&&
4155 /* is its preimage one line? */
4156 hunk
->oldpos
== 1 && hunk
->oldlines
== 1 &&
4157 /* does preimage begin with the heading? */
4158 (preimage
= memchr(hunk
->patch
, '\n', hunk
->size
)) != NULL
&&
4159 starts_with(++preimage
, heading
) &&
4160 /* does it record full SHA-1? */
4161 !get_oid_hex(preimage
+ sizeof(heading
) - 1, oid
) &&
4162 preimage
[sizeof(heading
) + the_hash_algo
->hexsz
- 1] == '\n' &&
4163 /* does the abbreviated name on the index line agree with it? */
4164 starts_with(preimage
+ sizeof(heading
) - 1, p
->old_oid_prefix
))
4165 return 0; /* it all looks fine */
4167 /* we may have full object name on the index line */
4168 return get_oid_hex(p
->old_oid_prefix
, oid
);
4171 /* Build an index that contains just the files needed for a 3way merge */
4172 static int build_fake_ancestor(struct apply_state
*state
, struct patch
*list
)
4174 struct patch
*patch
;
4175 struct index_state result
= INDEX_STATE_INIT(state
->repo
);
4176 struct lock_file lock
= LOCK_INIT
;
4179 /* Once we start supporting the reverse patch, it may be
4180 * worth showing the new sha1 prefix, but until then...
4182 for (patch
= list
; patch
; patch
= patch
->next
) {
4183 struct object_id oid
;
4184 struct cache_entry
*ce
;
4187 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
4188 if (0 < patch
->is_new
)
4191 if (S_ISGITLINK(patch
->old_mode
)) {
4192 if (!preimage_oid_in_gitlink_patch(patch
, &oid
))
4193 ; /* ok, the textual part looks sane */
4195 return error(_("sha1 information is lacking or "
4196 "useless for submodule %s"), name
);
4197 } else if (!repo_get_oid_blob(the_repository
, patch
->old_oid_prefix
, &oid
)) {
4199 } else if (!patch
->lines_added
&& !patch
->lines_deleted
) {
4200 /* mode-only change: update the current */
4201 if (get_current_oid(state
, patch
->old_name
, &oid
))
4202 return error(_("mode change for %s, which is not "
4203 "in current HEAD"), name
);
4205 return error(_("sha1 information is lacking or useless "
4208 ce
= make_cache_entry(&result
, patch
->old_mode
, &oid
, name
, 0, 0);
4210 return error(_("make_cache_entry failed for path '%s'"),
4212 if (add_index_entry(&result
, ce
, ADD_CACHE_OK_TO_ADD
)) {
4213 discard_cache_entry(ce
);
4214 return error(_("could not add %s to temporary index"),
4219 hold_lock_file_for_update(&lock
, state
->fake_ancestor
, LOCK_DIE_ON_ERROR
);
4220 res
= write_locked_index(&result
, &lock
, COMMIT_LOCK
);
4221 discard_index(&result
);
4224 return error(_("could not write temporary index to %s"),
4225 state
->fake_ancestor
);
4230 static void stat_patch_list(struct apply_state
*state
, struct patch
*patch
)
4232 int files
, adds
, dels
;
4234 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
4236 adds
+= patch
->lines_added
;
4237 dels
+= patch
->lines_deleted
;
4238 show_stats(state
, patch
);
4241 print_stat_summary(stdout
, files
, adds
, dels
);
4244 static void numstat_patch_list(struct apply_state
*state
,
4245 struct patch
*patch
)
4247 for ( ; patch
; patch
= patch
->next
) {
4249 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
4250 if (patch
->is_binary
)
4253 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
4254 write_name_quoted(name
, stdout
, state
->line_termination
);
4258 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
4261 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
4263 printf(" %s %s\n", newdelete
, name
);
4266 static void show_mode_change(struct patch
*p
, int show_name
)
4268 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
4270 printf(" mode change %06o => %06o %s\n",
4271 p
->old_mode
, p
->new_mode
, p
->new_name
);
4273 printf(" mode change %06o => %06o\n",
4274 p
->old_mode
, p
->new_mode
);
4278 static void show_rename_copy(struct patch
*p
)
4280 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
4281 const char *old_name
, *new_name
;
4283 /* Find common prefix */
4284 old_name
= p
->old_name
;
4285 new_name
= p
->new_name
;
4287 const char *slash_old
, *slash_new
;
4288 slash_old
= strchr(old_name
, '/');
4289 slash_new
= strchr(new_name
, '/');
4292 slash_old
- old_name
!= slash_new
- new_name
||
4293 memcmp(old_name
, new_name
, slash_new
- new_name
))
4295 old_name
= slash_old
+ 1;
4296 new_name
= slash_new
+ 1;
4298 /* p->old_name through old_name is the common prefix, and old_name and
4299 * new_name through the end of names are renames
4301 if (old_name
!= p
->old_name
)
4302 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
4303 (int)(old_name
- p
->old_name
), p
->old_name
,
4304 old_name
, new_name
, p
->score
);
4306 printf(" %s %s => %s (%d%%)\n", renamecopy
,
4307 p
->old_name
, p
->new_name
, p
->score
);
4308 show_mode_change(p
, 0);
4311 static void summary_patch_list(struct patch
*patch
)
4315 for (p
= patch
; p
; p
= p
->next
) {
4317 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
4318 else if (p
->is_delete
)
4319 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
4321 if (p
->is_rename
|| p
->is_copy
)
4322 show_rename_copy(p
);
4325 printf(" rewrite %s (%d%%)\n",
4326 p
->new_name
, p
->score
);
4327 show_mode_change(p
, 0);
4330 show_mode_change(p
, 1);
4336 static void patch_stats(struct apply_state
*state
, struct patch
*patch
)
4338 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
4340 if (lines
> state
->max_change
)
4341 state
->max_change
= lines
;
4342 if (patch
->old_name
) {
4343 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
4345 len
= strlen(patch
->old_name
);
4346 if (len
> state
->max_len
)
4347 state
->max_len
= len
;
4349 if (patch
->new_name
) {
4350 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
4352 len
= strlen(patch
->new_name
);
4353 if (len
> state
->max_len
)
4354 state
->max_len
= len
;
4358 static int remove_file(struct apply_state
*state
, struct patch
*patch
, int rmdir_empty
)
4360 if (state
->update_index
&& !state
->ita_only
) {
4361 if (remove_file_from_index(state
->repo
->index
, patch
->old_name
) < 0)
4362 return error(_("unable to remove %s from index"), patch
->old_name
);
4364 if (!state
->cached
) {
4365 if (!remove_or_warn(patch
->old_mode
, patch
->old_name
) && rmdir_empty
) {
4366 remove_path(patch
->old_name
);
4372 static int add_index_file(struct apply_state
*state
,
4379 struct cache_entry
*ce
;
4380 int namelen
= strlen(path
);
4382 ce
= make_empty_cache_entry(state
->repo
->index
, namelen
);
4383 memcpy(ce
->name
, path
, namelen
);
4384 ce
->ce_mode
= create_ce_mode(mode
);
4385 ce
->ce_flags
= create_ce_flags(0);
4386 ce
->ce_namelen
= namelen
;
4387 if (state
->ita_only
) {
4388 ce
->ce_flags
|= CE_INTENT_TO_ADD
;
4389 set_object_name_for_intent_to_add_entry(ce
);
4390 } else if (S_ISGITLINK(mode
)) {
4393 if (!skip_prefix(buf
, "Subproject commit ", &s
) ||
4394 get_oid_hex(s
, &ce
->oid
)) {
4395 discard_cache_entry(ce
);
4396 return error(_("corrupt patch for submodule %s"), path
);
4399 if (!state
->cached
) {
4400 if (lstat(path
, &st
) < 0) {
4401 discard_cache_entry(ce
);
4402 return error_errno(_("unable to stat newly "
4403 "created file '%s'"),
4406 fill_stat_cache_info(state
->repo
->index
, ce
, &st
);
4408 if (write_object_file(buf
, size
, OBJ_BLOB
, &ce
->oid
) < 0) {
4409 discard_cache_entry(ce
);
4410 return error(_("unable to create backing store "
4411 "for newly created file %s"), path
);
4414 if (add_index_entry(state
->repo
->index
, ce
, ADD_CACHE_OK_TO_ADD
) < 0) {
4415 discard_cache_entry(ce
);
4416 return error(_("unable to add cache entry for %s"), path
);
4424 * -1 if an unrecoverable error happened
4425 * 0 if everything went well
4426 * 1 if a recoverable error happened
4428 static int try_create_file(struct apply_state
*state
, const char *path
,
4429 unsigned int mode
, const char *buf
,
4433 struct strbuf nbuf
= STRBUF_INIT
;
4435 if (S_ISGITLINK(mode
)) {
4437 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
))
4439 return !!mkdir(path
, 0777);
4442 if (has_symlinks
&& S_ISLNK(mode
))
4443 /* Although buf:size is counted string, it also is NUL
4446 return !!symlink(buf
, path
);
4448 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
4452 if (convert_to_working_tree(state
->repo
->index
, path
, buf
, size
, &nbuf
, NULL
)) {
4457 res
= write_in_full(fd
, buf
, size
) < 0;
4459 error_errno(_("failed to write to '%s'"), path
);
4460 strbuf_release(&nbuf
);
4462 if (close(fd
) < 0 && !res
)
4463 return error_errno(_("closing file '%s'"), path
);
4465 return res
? -1 : 0;
4469 * We optimistically assume that the directories exist,
4470 * which is true 99% of the time anyway. If they don't,
4471 * we create them and try again.
4477 static int create_one_file(struct apply_state
*state
,
4483 char *newpath
= NULL
;
4490 * We already try to detect whether files are beyond a symlink in our
4491 * up-front checks. But in the case where symlinks are created by any
4492 * of the intermediate hunks it can happen that our up-front checks
4493 * didn't yet see the symlink, but at the point of arriving here there
4494 * in fact is one. We thus repeat the check for symlinks here.
4496 * Note that this does not make the up-front check obsolete as the
4497 * failure mode is different:
4499 * - The up-front checks cause us to abort before we have written
4500 * anything into the working directory. So when we exit this way the
4501 * working directory remains clean.
4503 * - The checks here happen in the middle of the action where we have
4504 * already started to apply the patch. The end result will be a dirty
4505 * working directory.
4507 * Ideally, we should update the up-front checks to catch what would
4508 * happen when we apply the patch before we damage the working tree.
4509 * We have all the information necessary to do so. But for now, as a
4510 * part of embargoed security work, having this check would serve as a
4511 * reasonable first step.
4513 if (path_is_beyond_symlink(state
, path
))
4514 return error(_("affected file '%s' is beyond a symbolic link"), path
);
4516 res
= try_create_file(state
, path
, mode
, buf
, size
);
4522 if (errno
== ENOENT
) {
4523 if (safe_create_leading_directories_no_share(path
))
4525 res
= try_create_file(state
, path
, mode
, buf
, size
);
4532 if (errno
== EEXIST
|| errno
== EACCES
) {
4533 /* We may be trying to create a file where a directory
4537 if (!lstat(path
, &st
) && (!S_ISDIR(st
.st_mode
) || !rmdir(path
)))
4541 if (errno
== EEXIST
) {
4542 unsigned int nr
= getpid();
4545 newpath
= mkpathdup("%s~%u", path
, nr
);
4546 res
= try_create_file(state
, newpath
, mode
, buf
, size
);
4550 if (!rename(newpath
, path
))
4552 unlink_or_warn(newpath
);
4555 if (errno
!= EEXIST
)
4558 FREE_AND_NULL(newpath
);
4561 res
= error_errno(_("unable to write file '%s' mode %o"), path
, mode
);
4567 static int add_conflicted_stages_file(struct apply_state
*state
,
4568 struct patch
*patch
)
4572 struct cache_entry
*ce
;
4574 if (!state
->update_index
)
4576 namelen
= strlen(patch
->new_name
);
4577 mode
= patch
->new_mode
? patch
->new_mode
: (S_IFREG
| 0644);
4579 remove_file_from_index(state
->repo
->index
, patch
->new_name
);
4580 for (stage
= 1; stage
< 4; stage
++) {
4581 if (is_null_oid(&patch
->threeway_stage
[stage
- 1]))
4583 ce
= make_empty_cache_entry(state
->repo
->index
, namelen
);
4584 memcpy(ce
->name
, patch
->new_name
, namelen
);
4585 ce
->ce_mode
= create_ce_mode(mode
);
4586 ce
->ce_flags
= create_ce_flags(stage
);
4587 ce
->ce_namelen
= namelen
;
4588 oidcpy(&ce
->oid
, &patch
->threeway_stage
[stage
- 1]);
4589 if (add_index_entry(state
->repo
->index
, ce
, ADD_CACHE_OK_TO_ADD
) < 0) {
4590 discard_cache_entry(ce
);
4591 return error(_("unable to add cache entry for %s"),
4599 static int create_file(struct apply_state
*state
, struct patch
*patch
)
4601 char *path
= patch
->new_name
;
4602 unsigned mode
= patch
->new_mode
;
4603 unsigned long size
= patch
->resultsize
;
4604 char *buf
= patch
->result
;
4607 mode
= S_IFREG
| 0644;
4608 if (create_one_file(state
, path
, mode
, buf
, size
))
4611 if (patch
->conflicted_threeway
)
4612 return add_conflicted_stages_file(state
, patch
);
4613 else if (state
->update_index
)
4614 return add_index_file(state
, path
, mode
, buf
, size
);
4618 /* phase zero is to remove, phase one is to create */
4619 static int write_out_one_result(struct apply_state
*state
,
4620 struct patch
*patch
,
4623 if (patch
->is_delete
> 0) {
4625 return remove_file(state
, patch
, 1);
4628 if (patch
->is_new
> 0 || patch
->is_copy
) {
4630 return create_file(state
, patch
);
4634 * Rename or modification boils down to the same
4635 * thing: remove the old, write the new
4638 return remove_file(state
, patch
, patch
->is_rename
);
4640 return create_file(state
, patch
);
4644 static int write_out_one_reject(struct apply_state
*state
, struct patch
*patch
)
4648 struct fragment
*frag
;
4650 struct strbuf sb
= STRBUF_INIT
;
4652 for (cnt
= 0, frag
= patch
->fragments
; frag
; frag
= frag
->next
) {
4653 if (!frag
->rejected
)
4659 if (state
->apply_verbosity
> verbosity_normal
)
4660 say_patch_name(stderr
,
4661 _("Applied patch %s cleanly."), patch
);
4665 /* This should not happen, because a removal patch that leaves
4666 * contents are marked "rejected" at the patch level.
4668 if (!patch
->new_name
)
4669 die(_("internal error"));
4671 /* Say this even without --verbose */
4672 strbuf_addf(&sb
, Q_("Applying patch %%s with %d reject...",
4673 "Applying patch %%s with %d rejects...",
4676 if (state
->apply_verbosity
> verbosity_silent
)
4677 say_patch_name(stderr
, sb
.buf
, patch
);
4678 strbuf_release(&sb
);
4680 namebuf
= xstrfmt("%s.rej", patch
->new_name
);
4682 fd
= open(namebuf
, O_CREAT
| O_EXCL
| O_WRONLY
, 0666);
4684 if (errno
!= EEXIST
) {
4685 error_errno(_("cannot open %s"), namebuf
);
4688 if (unlink(namebuf
)) {
4689 error_errno(_("cannot unlink '%s'"), namebuf
);
4692 fd
= open(namebuf
, O_CREAT
| O_EXCL
| O_WRONLY
, 0666);
4694 error_errno(_("cannot open %s"), namebuf
);
4698 rej
= fdopen(fd
, "w");
4700 error_errno(_("cannot open %s"), namebuf
);
4705 /* Normal git tools never deal with .rej, so do not pretend
4706 * this is a git patch by saying --git or giving extended
4707 * headers. While at it, maybe please "kompare" that wants
4708 * the trailing TAB and some garbage at the end of line ;-).
4710 fprintf(rej
, "diff a/%s b/%s\t(rejected hunks)\n",
4711 patch
->new_name
, patch
->new_name
);
4712 for (cnt
= 1, frag
= patch
->fragments
;
4714 cnt
++, frag
= frag
->next
) {
4715 if (!frag
->rejected
) {
4716 if (state
->apply_verbosity
> verbosity_silent
)
4717 fprintf_ln(stderr
, _("Hunk #%d applied cleanly."), cnt
);
4720 if (state
->apply_verbosity
> verbosity_silent
)
4721 fprintf_ln(stderr
, _("Rejected hunk #%d."), cnt
);
4722 fprintf(rej
, "%.*s", frag
->size
, frag
->patch
);
4723 if (frag
->patch
[frag
->size
-1] != '\n')
4734 * -1 if an error happened
4735 * 0 if the patch applied cleanly
4736 * 1 if the patch did not apply cleanly
4738 static int write_out_results(struct apply_state
*state
, struct patch
*list
)
4743 struct string_list cpath
= STRING_LIST_INIT_DUP
;
4745 for (phase
= 0; phase
< 2; phase
++) {
4751 if (write_out_one_result(state
, l
, phase
)) {
4752 string_list_clear(&cpath
, 0);
4756 if (write_out_one_reject(state
, l
))
4758 if (l
->conflicted_threeway
) {
4759 string_list_append(&cpath
, l
->new_name
);
4769 struct string_list_item
*item
;
4771 string_list_sort(&cpath
);
4772 if (state
->apply_verbosity
> verbosity_silent
) {
4773 for_each_string_list_item(item
, &cpath
)
4774 fprintf(stderr
, "U %s\n", item
->string
);
4776 string_list_clear(&cpath
, 0);
4779 * rerere relies on the partially merged result being in the working
4780 * tree with conflict markers, but that isn't written with --cached.
4783 repo_rerere(state
->repo
, 0);
4790 * Try to apply a patch.
4793 * -128 if a bad error happened (like patch unreadable)
4794 * -1 if patch did not apply and user cannot deal with it
4795 * 0 if the patch applied
4796 * 1 if the patch did not apply but user might fix it
4798 static int apply_patch(struct apply_state
*state
,
4800 const char *filename
,
4804 struct strbuf buf
= STRBUF_INIT
; /* owns the patch text */
4805 struct patch
*list
= NULL
, **listp
= &list
;
4806 int skipped_patch
= 0;
4808 int flush_attributes
= 0;
4810 state
->patch_input_file
= filename
;
4811 if (read_patch_file(&buf
, fd
) < 0)
4814 while (offset
< buf
.len
) {
4815 struct patch
*patch
;
4818 CALLOC_ARRAY(patch
, 1);
4819 patch
->inaccurate_eof
= !!(options
& APPLY_OPT_INACCURATE_EOF
);
4820 patch
->recount
= !!(options
& APPLY_OPT_RECOUNT
);
4821 nr
= parse_chunk(state
, buf
.buf
+ offset
, buf
.len
- offset
, patch
);
4830 if (state
->apply_in_reverse
)
4831 reverse_patches(patch
);
4832 if (use_patch(state
, patch
)) {
4833 patch_stats(state
, patch
);
4834 if (!list
|| !state
->apply_in_reverse
) {
4836 listp
= &patch
->next
;
4842 if ((patch
->new_name
&&
4843 ends_with_path_components(patch
->new_name
,
4844 GITATTRIBUTES_FILE
)) ||
4846 ends_with_path_components(patch
->old_name
,
4847 GITATTRIBUTES_FILE
)))
4848 flush_attributes
= 1;
4851 if (state
->apply_verbosity
> verbosity_normal
)
4852 say_patch_name(stderr
, _("Skipped patch '%s'."), patch
);
4859 if (!list
&& !skipped_patch
) {
4860 if (!state
->allow_empty
) {
4861 error(_("No valid patches in input (allow with \"--allow-empty\")"));
4867 if (state
->whitespace_error
&& (state
->ws_error_action
== die_on_ws_error
))
4870 state
->update_index
= (state
->check_index
|| state
->ita_only
) && state
->apply
;
4871 if (state
->update_index
&& !is_lock_file_locked(&state
->lock_file
)) {
4872 if (state
->index_file
)
4873 hold_lock_file_for_update(&state
->lock_file
,
4877 repo_hold_locked_index(state
->repo
, &state
->lock_file
,
4881 if (state
->check_index
&& read_apply_cache(state
) < 0) {
4882 error(_("unable to read index file"));
4887 if (state
->check
|| state
->apply
) {
4888 int r
= check_patch_list(state
, list
);
4893 if (r
< 0 && !state
->apply_with_reject
) {
4900 int write_res
= write_out_results(state
, list
);
4901 if (write_res
< 0) {
4905 if (write_res
> 0) {
4906 /* with --3way, we still need to write the index out */
4907 res
= state
->apply_with_reject
? -1 : 1;
4912 if (state
->fake_ancestor
&&
4913 build_fake_ancestor(state
, list
)) {
4918 if (state
->diffstat
&& state
->apply_verbosity
> verbosity_silent
)
4919 stat_patch_list(state
, list
);
4921 if (state
->numstat
&& state
->apply_verbosity
> verbosity_silent
)
4922 numstat_patch_list(state
, list
);
4924 if (state
->summary
&& state
->apply_verbosity
> verbosity_silent
)
4925 summary_patch_list(list
);
4927 if (flush_attributes
)
4928 reset_parsed_attributes();
4930 free_patch_list(list
);
4931 strbuf_release(&buf
);
4932 string_list_clear(&state
->fn_table
, 0);
4936 static int apply_option_parse_exclude(const struct option
*opt
,
4937 const char *arg
, int unset
)
4939 struct apply_state
*state
= opt
->value
;
4941 BUG_ON_OPT_NEG(unset
);
4943 add_name_limit(state
, arg
, 1);
4947 static int apply_option_parse_include(const struct option
*opt
,
4948 const char *arg
, int unset
)
4950 struct apply_state
*state
= opt
->value
;
4952 BUG_ON_OPT_NEG(unset
);
4954 add_name_limit(state
, arg
, 0);
4955 state
->has_include
= 1;
4959 static int apply_option_parse_p(const struct option
*opt
,
4963 struct apply_state
*state
= opt
->value
;
4965 BUG_ON_OPT_NEG(unset
);
4967 state
->p_value
= atoi(arg
);
4968 state
->p_value_known
= 1;
4972 static int apply_option_parse_space_change(const struct option
*opt
,
4973 const char *arg
, int unset
)
4975 struct apply_state
*state
= opt
->value
;
4977 BUG_ON_OPT_ARG(arg
);
4980 state
->ws_ignore_action
= ignore_ws_none
;
4982 state
->ws_ignore_action
= ignore_ws_change
;
4986 static int apply_option_parse_whitespace(const struct option
*opt
,
4987 const char *arg
, int unset
)
4989 struct apply_state
*state
= opt
->value
;
4991 BUG_ON_OPT_NEG(unset
);
4993 state
->whitespace_option
= arg
;
4994 if (parse_whitespace_option(state
, arg
))
4999 static int apply_option_parse_directory(const struct option
*opt
,
5000 const char *arg
, int unset
)
5002 struct apply_state
*state
= opt
->value
;
5004 BUG_ON_OPT_NEG(unset
);
5006 strbuf_reset(&state
->root
);
5007 strbuf_addstr(&state
->root
, arg
);
5008 strbuf_complete(&state
->root
, '/');
5012 int apply_all_patches(struct apply_state
*state
,
5022 for (i
= 0; i
< argc
; i
++) {
5023 const char *arg
= argv
[i
];
5024 char *to_free
= NULL
;
5027 if (!strcmp(arg
, "-")) {
5028 res
= apply_patch(state
, 0, "<stdin>", options
);
5035 arg
= to_free
= prefix_filename(state
->prefix
, arg
);
5037 fd
= open(arg
, O_RDONLY
);
5039 error(_("can't open patch '%s': %s"), arg
, strerror(errno
));
5045 set_default_whitespace_mode(state
);
5046 res
= apply_patch(state
, fd
, arg
, options
);
5053 set_default_whitespace_mode(state
);
5055 res
= apply_patch(state
, 0, "<stdin>", options
);
5061 if (state
->whitespace_error
) {
5062 if (state
->squelch_whitespace_errors
&&
5063 state
->squelch_whitespace_errors
< state
->whitespace_error
) {
5065 state
->whitespace_error
- state
->squelch_whitespace_errors
;
5066 warning(Q_("squelched %d whitespace error",
5067 "squelched %d whitespace errors",
5071 if (state
->ws_error_action
== die_on_ws_error
) {
5072 error(Q_("%d line adds whitespace errors.",
5073 "%d lines add whitespace errors.",
5074 state
->whitespace_error
),
5075 state
->whitespace_error
);
5079 if (state
->applied_after_fixing_ws
&& state
->apply
)
5080 warning(Q_("%d line applied after"
5081 " fixing whitespace errors.",
5082 "%d lines applied after"
5083 " fixing whitespace errors.",
5084 state
->applied_after_fixing_ws
),
5085 state
->applied_after_fixing_ws
);
5086 else if (state
->whitespace_error
)
5087 warning(Q_("%d line adds whitespace errors.",
5088 "%d lines add whitespace errors.",
5089 state
->whitespace_error
),
5090 state
->whitespace_error
);
5093 if (state
->update_index
) {
5094 res
= write_locked_index(state
->repo
->index
, &state
->lock_file
, COMMIT_LOCK
);
5096 error(_("Unable to write new index file"));
5105 rollback_lock_file(&state
->lock_file
);
5107 if (state
->apply_verbosity
<= verbosity_silent
) {
5108 set_error_routine(state
->saved_error_routine
);
5109 set_warn_routine(state
->saved_warn_routine
);
5114 return (res
== -1 ? 1 : 128);
5117 int apply_parse_options(int argc
, const char **argv
,
5118 struct apply_state
*state
,
5119 int *force_apply
, int *options
,
5120 const char * const *apply_usage
)
5122 struct option builtin_apply_options
[] = {
5123 OPT_CALLBACK_F(0, "exclude", state
, N_("path"),
5124 N_("don't apply changes matching the given path"),
5125 PARSE_OPT_NONEG
, apply_option_parse_exclude
),
5126 OPT_CALLBACK_F(0, "include", state
, N_("path"),
5127 N_("apply changes matching the given path"),
5128 PARSE_OPT_NONEG
, apply_option_parse_include
),
5129 OPT_CALLBACK('p', NULL
, state
, N_("num"),
5130 N_("remove <num> leading slashes from traditional diff paths"),
5131 apply_option_parse_p
),
5132 OPT_BOOL(0, "no-add", &state
->no_add
,
5133 N_("ignore additions made by the patch")),
5134 OPT_BOOL(0, "stat", &state
->diffstat
,
5135 N_("instead of applying the patch, output diffstat for the input")),
5136 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
5137 OPT_NOOP_NOARG(0, "binary"),
5138 OPT_BOOL(0, "numstat", &state
->numstat
,
5139 N_("show number of added and deleted lines in decimal notation")),
5140 OPT_BOOL(0, "summary", &state
->summary
,
5141 N_("instead of applying the patch, output a summary for the input")),
5142 OPT_BOOL(0, "check", &state
->check
,
5143 N_("instead of applying the patch, see if the patch is applicable")),
5144 OPT_BOOL(0, "index", &state
->check_index
,
5145 N_("make sure the patch is applicable to the current index")),
5146 OPT_BOOL('N', "intent-to-add", &state
->ita_only
,
5147 N_("mark new files with `git add --intent-to-add`")),
5148 OPT_BOOL(0, "cached", &state
->cached
,
5149 N_("apply a patch without touching the working tree")),
5150 OPT_BOOL_F(0, "unsafe-paths", &state
->unsafe_paths
,
5151 N_("accept a patch that touches outside the working area"),
5152 PARSE_OPT_NOCOMPLETE
),
5153 OPT_BOOL(0, "apply", force_apply
,
5154 N_("also apply the patch (use with --stat/--summary/--check)")),
5155 OPT_BOOL('3', "3way", &state
->threeway
,
5156 N_( "attempt three-way merge, fall back on normal patch if that fails")),
5157 OPT_SET_INT_F(0, "ours", &state
->merge_variant
,
5158 N_("for conflicts, use our version"),
5159 XDL_MERGE_FAVOR_OURS
, PARSE_OPT_NONEG
),
5160 OPT_SET_INT_F(0, "theirs", &state
->merge_variant
,
5161 N_("for conflicts, use their version"),
5162 XDL_MERGE_FAVOR_THEIRS
, PARSE_OPT_NONEG
),
5163 OPT_SET_INT_F(0, "union", &state
->merge_variant
,
5164 N_("for conflicts, use a union version"),
5165 XDL_MERGE_FAVOR_UNION
, PARSE_OPT_NONEG
),
5166 OPT_FILENAME(0, "build-fake-ancestor", &state
->fake_ancestor
,
5167 N_("build a temporary index based on embedded index information")),
5168 /* Think twice before adding "--nul" synonym to this */
5169 OPT_SET_INT('z', NULL
, &state
->line_termination
,
5170 N_("paths are separated with NUL character"), '\0'),
5171 OPT_INTEGER('C', NULL
, &state
->p_context
,
5172 N_("ensure at least <n> lines of context match")),
5173 OPT_CALLBACK(0, "whitespace", state
, N_("action"),
5174 N_("detect new or modified lines that have whitespace errors"),
5175 apply_option_parse_whitespace
),
5176 OPT_CALLBACK_F(0, "ignore-space-change", state
, NULL
,
5177 N_("ignore changes in whitespace when finding context"),
5178 PARSE_OPT_NOARG
, apply_option_parse_space_change
),
5179 OPT_CALLBACK_F(0, "ignore-whitespace", state
, NULL
,
5180 N_("ignore changes in whitespace when finding context"),
5181 PARSE_OPT_NOARG
, apply_option_parse_space_change
),
5182 OPT_BOOL('R', "reverse", &state
->apply_in_reverse
,
5183 N_("apply the patch in reverse")),
5184 OPT_BOOL(0, "unidiff-zero", &state
->unidiff_zero
,
5185 N_("don't expect at least one line of context")),
5186 OPT_BOOL(0, "reject", &state
->apply_with_reject
,
5187 N_("leave the rejected hunks in corresponding *.rej files")),
5188 OPT_BOOL(0, "allow-overlap", &state
->allow_overlap
,
5189 N_("allow overlapping hunks")),
5190 OPT__VERBOSITY(&state
->apply_verbosity
),
5191 OPT_BIT(0, "inaccurate-eof", options
,
5192 N_("tolerate incorrectly detected missing new-line at the end of file"),
5193 APPLY_OPT_INACCURATE_EOF
),
5194 OPT_BIT(0, "recount", options
,
5195 N_("do not trust the line counts in the hunk headers"),
5197 OPT_CALLBACK(0, "directory", state
, N_("root"),
5198 N_("prepend <root> to all filenames"),
5199 apply_option_parse_directory
),
5200 OPT_BOOL(0, "allow-empty", &state
->allow_empty
,
5201 N_("don't return error for empty patches")),
5205 argc
= parse_options(argc
, argv
, state
->prefix
, builtin_apply_options
, apply_usage
, 0);
5207 if (state
->merge_variant
&& !state
->threeway
)
5208 die(_("--ours, --theirs, and --union require --3way"));