4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
14 #include "object-store.h"
19 #include "environment.h"
22 #include "xdiff-interface.h"
25 #include "parse-options.h"
39 static void git_apply_config(void)
41 git_config_get_string("apply.whitespace", &apply_default_whitespace
);
42 git_config_get_string("apply.ignorewhitespace", &apply_default_ignorewhitespace
);
43 git_config(git_xmerge_config
, NULL
);
46 static int parse_whitespace_option(struct apply_state
*state
, const char *option
)
49 state
->ws_error_action
= warn_on_ws_error
;
52 if (!strcmp(option
, "warn")) {
53 state
->ws_error_action
= warn_on_ws_error
;
56 if (!strcmp(option
, "nowarn")) {
57 state
->ws_error_action
= nowarn_ws_error
;
60 if (!strcmp(option
, "error")) {
61 state
->ws_error_action
= die_on_ws_error
;
64 if (!strcmp(option
, "error-all")) {
65 state
->ws_error_action
= die_on_ws_error
;
66 state
->squelch_whitespace_errors
= 0;
69 if (!strcmp(option
, "strip") || !strcmp(option
, "fix")) {
70 state
->ws_error_action
= correct_ws_error
;
74 * Please update $__git_whitespacelist in git-completion.bash
75 * when you add new options.
77 return error(_("unrecognized whitespace option '%s'"), option
);
80 static int parse_ignorewhitespace_option(struct apply_state
*state
,
83 if (!option
|| !strcmp(option
, "no") ||
84 !strcmp(option
, "false") || !strcmp(option
, "never") ||
85 !strcmp(option
, "none")) {
86 state
->ws_ignore_action
= ignore_ws_none
;
89 if (!strcmp(option
, "change")) {
90 state
->ws_ignore_action
= ignore_ws_change
;
93 return error(_("unrecognized whitespace ignore option '%s'"), option
);
96 int init_apply_state(struct apply_state
*state
,
97 struct repository
*repo
,
100 memset(state
, 0, sizeof(*state
));
101 state
->prefix
= prefix
;
104 state
->line_termination
= '\n';
106 state
->p_context
= UINT_MAX
;
107 state
->squelch_whitespace_errors
= 5;
108 state
->ws_error_action
= warn_on_ws_error
;
109 state
->ws_ignore_action
= ignore_ws_none
;
111 string_list_init_nodup(&state
->fn_table
);
112 string_list_init_nodup(&state
->limit_by_name
);
113 strset_init(&state
->removed_symlinks
);
114 strset_init(&state
->kept_symlinks
);
115 strbuf_init(&state
->root
, 0);
118 if (apply_default_whitespace
&& parse_whitespace_option(state
, apply_default_whitespace
))
120 if (apply_default_ignorewhitespace
&& parse_ignorewhitespace_option(state
, apply_default_ignorewhitespace
))
125 void clear_apply_state(struct apply_state
*state
)
127 string_list_clear(&state
->limit_by_name
, 0);
128 strset_clear(&state
->removed_symlinks
);
129 strset_clear(&state
->kept_symlinks
);
130 strbuf_release(&state
->root
);
132 /* &state->fn_table is cleared at the end of apply_patch() */
135 static void mute_routine(const char *msg UNUSED
, va_list params UNUSED
)
140 int check_apply_state(struct apply_state
*state
, int force_apply
)
142 int is_not_gitdir
= !startup_info
->have_repository
;
144 if (state
->apply_with_reject
&& state
->threeway
)
145 return error(_("options '%s' and '%s' cannot be used together"), "--reject", "--3way");
146 if (state
->threeway
) {
148 return error(_("'%s' outside a repository"), "--3way");
149 state
->check_index
= 1;
151 if (state
->apply_with_reject
) {
153 if (state
->apply_verbosity
== verbosity_normal
)
154 state
->apply_verbosity
= verbosity_verbose
;
156 if (!force_apply
&& (state
->diffstat
|| state
->numstat
|| state
->summary
|| state
->check
|| state
->fake_ancestor
))
158 if (state
->check_index
&& is_not_gitdir
)
159 return error(_("'%s' outside a repository"), "--index");
162 return error(_("'%s' outside a repository"), "--cached");
163 state
->check_index
= 1;
165 if (state
->ita_only
&& (state
->check_index
|| is_not_gitdir
))
167 if (state
->check_index
)
168 state
->unsafe_paths
= 0;
170 if (state
->apply_verbosity
<= verbosity_silent
) {
171 state
->saved_error_routine
= get_error_routine();
172 state
->saved_warn_routine
= get_warn_routine();
173 set_error_routine(mute_routine
);
174 set_warn_routine(mute_routine
);
180 static void set_default_whitespace_mode(struct apply_state
*state
)
182 if (!state
->whitespace_option
&& !apply_default_whitespace
)
183 state
->ws_error_action
= (state
->apply
? warn_on_ws_error
: nowarn_ws_error
);
187 * This represents one "hunk" from a patch, starting with
188 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
189 * patch text is pointed at by patch, and its byte length
190 * is stored in size. leading and trailing are the number
194 unsigned long leading
, trailing
;
195 unsigned long oldpos
, oldlines
;
196 unsigned long newpos
, newlines
;
198 * 'patch' is usually borrowed from buf in apply_patch(),
199 * but some codepaths store an allocated buffer.
202 unsigned free_patch
:1,
206 struct fragment
*next
;
210 * When dealing with a binary patch, we reuse "leading" field
211 * to store the type of the binary hunk, either deflated "delta"
212 * or deflated "literal".
214 #define binary_patch_method leading
215 #define BINARY_DELTA_DEFLATED 1
216 #define BINARY_LITERAL_DEFLATED 2
218 static void free_fragment_list(struct fragment
*list
)
221 struct fragment
*next
= list
->next
;
222 if (list
->free_patch
)
223 free((char *)list
->patch
);
229 void release_patch(struct patch
*patch
)
231 free_fragment_list(patch
->fragments
);
232 free(patch
->def_name
);
233 free(patch
->old_name
);
234 free(patch
->new_name
);
238 static void free_patch(struct patch
*patch
)
240 release_patch(patch
);
244 static void free_patch_list(struct patch
*list
)
247 struct patch
*next
= list
->next
;
254 * A line in a file, len-bytes long (includes the terminating LF,
255 * except for an incomplete line at the end if the file ends with
256 * one), and its contents hashes to 'hash'.
262 #define LINE_COMMON 1
263 #define LINE_PATCHED 2
267 * This represents a "file", which is an array of "lines".
274 struct line
*line_allocated
;
278 static uint32_t hash_line(const char *cp
, size_t len
)
282 for (i
= 0, h
= 0; i
< len
; i
++) {
283 if (!isspace(cp
[i
])) {
284 h
= h
* 3 + (cp
[i
] & 0xff);
291 * Compare lines s1 of length n1 and s2 of length n2, ignoring
292 * whitespace difference. Returns 1 if they match, 0 otherwise
294 static int fuzzy_matchlines(const char *s1
, size_t n1
,
295 const char *s2
, size_t n2
)
297 const char *end1
= s1
+ n1
;
298 const char *end2
= s2
+ n2
;
300 /* ignore line endings */
301 while (s1
< end1
&& (end1
[-1] == '\r' || end1
[-1] == '\n'))
303 while (s2
< end2
&& (end2
[-1] == '\r' || end2
[-1] == '\n'))
306 while (s1
< end1
&& s2
< end2
) {
309 * Skip whitespace. We check on both buffers
310 * because we don't want "a b" to match "ab".
314 while (s1
< end1
&& isspace(*s1
))
316 while (s2
< end2
&& isspace(*s2
))
318 } else if (*s1
++ != *s2
++)
322 /* If we reached the end on one side only, lines don't match. */
323 return s1
== end1
&& s2
== end2
;
326 static void add_line_info(struct image
*img
, const char *bol
, size_t len
, unsigned flag
)
328 ALLOC_GROW(img
->line_allocated
, img
->nr
+ 1, img
->alloc
);
329 img
->line_allocated
[img
->nr
].len
= len
;
330 img
->line_allocated
[img
->nr
].hash
= hash_line(bol
, len
);
331 img
->line_allocated
[img
->nr
].flag
= flag
;
336 * "buf" has the file contents to be patched (read from various sources).
337 * attach it to "image" and add line-based index to it.
338 * "image" now owns the "buf".
340 static void prepare_image(struct image
*image
, char *buf
, size_t len
,
341 int prepare_linetable
)
345 memset(image
, 0, sizeof(*image
));
349 if (!prepare_linetable
)
352 ep
= image
->buf
+ image
->len
;
356 for (next
= cp
; next
< ep
&& *next
!= '\n'; next
++)
360 add_line_info(image
, cp
, next
- cp
, 0);
363 image
->line
= image
->line_allocated
;
366 static void clear_image(struct image
*image
)
369 free(image
->line_allocated
);
370 memset(image
, 0, sizeof(*image
));
373 /* fmt must contain _one_ %s and no other substitution */
374 static void say_patch_name(FILE *output
, const char *fmt
, struct patch
*patch
)
376 struct strbuf sb
= STRBUF_INIT
;
378 if (patch
->old_name
&& patch
->new_name
&&
379 strcmp(patch
->old_name
, patch
->new_name
)) {
380 quote_c_style(patch
->old_name
, &sb
, NULL
, 0);
381 strbuf_addstr(&sb
, " => ");
382 quote_c_style(patch
->new_name
, &sb
, NULL
, 0);
384 const char *n
= patch
->new_name
;
387 quote_c_style(n
, &sb
, NULL
, 0);
389 fprintf(output
, fmt
, sb
.buf
);
397 * apply.c isn't equipped to handle arbitrarily large patches, because
398 * it intermingles `unsigned long` with `int` for the type used to store
401 * Only process patches that are just shy of 1 GiB large in order to
402 * avoid any truncation or overflow issues.
404 #define MAX_APPLY_SIZE (1024UL * 1024 * 1023)
406 static int read_patch_file(struct strbuf
*sb
, int fd
)
408 if (strbuf_read(sb
, fd
, 0) < 0 || sb
->len
>= MAX_APPLY_SIZE
)
409 return error_errno("git apply: failed to read");
412 * Make sure that we have some slop in the buffer
413 * so that we can do speculative "memcmp" etc, and
414 * see to it that it is NUL-filled.
416 strbuf_grow(sb
, SLOP
);
417 memset(sb
->buf
+ sb
->len
, 0, SLOP
);
421 static unsigned long linelen(const char *buffer
, unsigned long size
)
423 unsigned long len
= 0;
426 if (*buffer
++ == '\n')
432 static int is_dev_null(const char *str
)
434 return skip_prefix(str
, "/dev/null", &str
) && isspace(*str
);
440 static int name_terminate(int c
, int terminate
)
442 if (c
== ' ' && !(terminate
& TERM_SPACE
))
444 if (c
== '\t' && !(terminate
& TERM_TAB
))
450 /* remove double slashes to make --index work with such filenames */
451 static char *squash_slash(char *name
)
459 if ((name
[j
++] = name
[i
++]) == '/')
460 while (name
[i
] == '/')
467 static char *find_name_gnu(struct strbuf
*root
,
471 struct strbuf name
= STRBUF_INIT
;
475 * Proposed "new-style" GNU patch/diff format; see
476 * https://lore.kernel.org/git/7vll0wvb2a.fsf@assigned-by-dhcp.cox.net/
478 if (unquote_c_style(&name
, line
, NULL
)) {
479 strbuf_release(&name
);
483 for (cp
= name
.buf
; p_value
; p_value
--) {
484 cp
= strchr(cp
, '/');
486 strbuf_release(&name
);
492 strbuf_remove(&name
, 0, cp
- name
.buf
);
494 strbuf_insert(&name
, 0, root
->buf
, root
->len
);
495 return squash_slash(strbuf_detach(&name
, NULL
));
498 static size_t sane_tz_len(const char *line
, size_t len
)
502 if (len
< strlen(" +0500") || line
[len
-strlen(" +0500")] != ' ')
504 tz
= line
+ len
- strlen(" +0500");
506 if (tz
[1] != '+' && tz
[1] != '-')
509 for (p
= tz
+ 2; p
!= line
+ len
; p
++)
513 return line
+ len
- tz
;
516 static size_t tz_with_colon_len(const char *line
, size_t len
)
520 if (len
< strlen(" +08:00") || line
[len
- strlen(":00")] != ':')
522 tz
= line
+ len
- strlen(" +08:00");
524 if (tz
[0] != ' ' || (tz
[1] != '+' && tz
[1] != '-'))
527 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
528 !isdigit(*p
++) || !isdigit(*p
++))
531 return line
+ len
- tz
;
534 static size_t date_len(const char *line
, size_t len
)
536 const char *date
, *p
;
538 if (len
< strlen("72-02-05") || line
[len
-strlen("-05")] != '-')
540 p
= date
= line
+ len
- strlen("72-02-05");
542 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
543 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
544 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a date. */
547 if (date
- line
>= strlen("19") &&
548 isdigit(date
[-1]) && isdigit(date
[-2])) /* 4-digit year */
549 date
-= strlen("19");
551 return line
+ len
- date
;
554 static size_t short_time_len(const char *line
, size_t len
)
556 const char *time
, *p
;
558 if (len
< strlen(" 07:01:32") || line
[len
-strlen(":32")] != ':')
560 p
= time
= line
+ len
- strlen(" 07:01:32");
562 /* Permit 1-digit hours? */
564 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
565 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
566 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a time. */
569 return line
+ len
- time
;
572 static size_t fractional_time_len(const char *line
, size_t len
)
577 /* Expected format: 19:41:17.620000023 */
578 if (!len
|| !isdigit(line
[len
- 1]))
582 /* Fractional seconds. */
583 while (p
> line
&& isdigit(*p
))
588 /* Hours, minutes, and whole seconds. */
589 n
= short_time_len(line
, p
- line
);
593 return line
+ len
- p
+ n
;
596 static size_t trailing_spaces_len(const char *line
, size_t len
)
600 /* Expected format: ' ' x (1 or more) */
601 if (!len
|| line
[len
- 1] != ' ')
608 return line
+ len
- (p
+ 1);
615 static size_t diff_timestamp_len(const char *line
, size_t len
)
617 const char *end
= line
+ len
;
621 * Posix: 2010-07-05 19:41:17
622 * GNU: 2010-07-05 19:41:17.620000023 -0500
625 if (!isdigit(end
[-1]))
628 n
= sane_tz_len(line
, end
- line
);
630 n
= tz_with_colon_len(line
, end
- line
);
633 n
= short_time_len(line
, end
- line
);
635 n
= fractional_time_len(line
, end
- line
);
638 n
= date_len(line
, end
- line
);
639 if (!n
) /* No date. Too bad. */
643 if (end
== line
) /* No space before date. */
645 if (end
[-1] == '\t') { /* Success! */
647 return line
+ len
- end
;
649 if (end
[-1] != ' ') /* No space before date. */
652 /* Whitespace damage. */
653 end
-= trailing_spaces_len(line
, end
- line
);
654 return line
+ len
- end
;
657 static char *find_name_common(struct strbuf
*root
,
665 const char *start
= NULL
;
669 while (line
!= end
) {
672 if (!end
&& isspace(c
)) {
675 if (name_terminate(c
, terminate
))
679 if (c
== '/' && !--p_value
)
683 return squash_slash(xstrdup_or_null(def
));
686 return squash_slash(xstrdup_or_null(def
));
689 * Generally we prefer the shorter name, especially
690 * if the other one is just a variation of that with
691 * something else tacked on to the end (ie "file.orig"
695 int deflen
= strlen(def
);
696 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
697 return squash_slash(xstrdup(def
));
701 char *ret
= xstrfmt("%s%.*s", root
->buf
, len
, start
);
702 return squash_slash(ret
);
705 return squash_slash(xmemdupz(start
, len
));
708 static char *find_name(struct strbuf
*root
,
715 char *name
= find_name_gnu(root
, line
, p_value
);
720 return find_name_common(root
, line
, def
, p_value
, NULL
, terminate
);
723 static char *find_name_traditional(struct strbuf
*root
,
732 char *name
= find_name_gnu(root
, line
, p_value
);
737 len
= strchrnul(line
, '\n') - line
;
738 date_len
= diff_timestamp_len(line
, len
);
740 return find_name_common(root
, line
, def
, p_value
, NULL
, TERM_TAB
);
743 return find_name_common(root
, line
, def
, p_value
, line
+ len
, 0);
747 * Given the string after "--- " or "+++ ", guess the appropriate
748 * p_value for the given patch.
750 static int guess_p_value(struct apply_state
*state
, const char *nameline
)
755 if (is_dev_null(nameline
))
757 name
= find_name_traditional(&state
->root
, nameline
, NULL
, 0);
760 cp
= strchr(name
, '/');
763 else if (state
->prefix
) {
765 * Does it begin with "a/$our-prefix" and such? Then this is
766 * very likely to apply to our directory.
768 if (starts_with(name
, state
->prefix
))
769 val
= count_slashes(state
->prefix
);
772 if (starts_with(cp
, state
->prefix
))
773 val
= count_slashes(state
->prefix
) + 1;
781 * Does the ---/+++ line have the POSIX timestamp after the last HT?
782 * GNU diff puts epoch there to signal a creation/deletion event. Is
783 * this such a timestamp?
785 static int has_epoch_timestamp(const char *nameline
)
788 * We are only interested in epoch timestamp; any non-zero
789 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
790 * For the same reason, the date must be either 1969-12-31 or
791 * 1970-01-01, and the seconds part must be "00".
793 const char stamp_regexp
[] =
794 "^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?"
796 "([-+][0-2][0-9]:?[0-5][0-9])\n";
797 const char *timestamp
= NULL
, *cp
, *colon
;
798 static regex_t
*stamp
;
800 int zoneoffset
, epoch_hour
, hour
, minute
;
803 for (cp
= nameline
; *cp
!= '\n'; cp
++) {
811 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
812 * (west of GMT) or 1970-01-01 (east of GMT)
814 if (skip_prefix(timestamp
, "1969-12-31 ", ×tamp
))
816 else if (skip_prefix(timestamp
, "1970-01-01 ", ×tamp
))
822 stamp
= xmalloc(sizeof(*stamp
));
823 if (regcomp(stamp
, stamp_regexp
, REG_EXTENDED
)) {
824 warning(_("Cannot prepare timestamp regexp %s"),
830 status
= regexec(stamp
, timestamp
, ARRAY_SIZE(m
), m
, 0);
832 if (status
!= REG_NOMATCH
)
833 warning(_("regexec returned %d for input: %s"),
838 hour
= strtol(timestamp
, NULL
, 10);
839 minute
= strtol(timestamp
+ m
[1].rm_so
, NULL
, 10);
841 zoneoffset
= strtol(timestamp
+ m
[3].rm_so
+ 1, (char **) &colon
, 10);
843 zoneoffset
= zoneoffset
* 60 + strtol(colon
+ 1, NULL
, 10);
845 zoneoffset
= (zoneoffset
/ 100) * 60 + (zoneoffset
% 100);
846 if (timestamp
[m
[3].rm_so
] == '-')
847 zoneoffset
= -zoneoffset
;
849 return hour
* 60 + minute
- zoneoffset
== epoch_hour
* 60;
853 * Get the name etc info from the ---/+++ lines of a traditional patch header
855 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
856 * files, we can happily check the index for a match, but for creating a
857 * new file we should try to match whatever "patch" does. I have no idea.
859 static int parse_traditional_patch(struct apply_state
*state
,
866 first
+= 4; /* skip "--- " */
867 second
+= 4; /* skip "+++ " */
868 if (!state
->p_value_known
) {
870 p
= guess_p_value(state
, first
);
871 q
= guess_p_value(state
, second
);
873 if (0 <= p
&& p
== q
) {
875 state
->p_value_known
= 1;
878 if (is_dev_null(first
)) {
880 patch
->is_delete
= 0;
881 name
= find_name_traditional(&state
->root
, second
, NULL
, state
->p_value
);
882 patch
->new_name
= name
;
883 } else if (is_dev_null(second
)) {
885 patch
->is_delete
= 1;
886 name
= find_name_traditional(&state
->root
, first
, NULL
, state
->p_value
);
887 patch
->old_name
= name
;
890 first_name
= find_name_traditional(&state
->root
, first
, NULL
, state
->p_value
);
891 name
= find_name_traditional(&state
->root
, second
, first_name
, state
->p_value
);
893 if (has_epoch_timestamp(first
)) {
895 patch
->is_delete
= 0;
896 patch
->new_name
= name
;
897 } else if (has_epoch_timestamp(second
)) {
899 patch
->is_delete
= 1;
900 patch
->old_name
= name
;
902 patch
->old_name
= name
;
903 patch
->new_name
= xstrdup_or_null(name
);
907 return error(_("unable to find filename in patch at line %d"), state
->linenr
);
912 static int gitdiff_hdrend(struct gitdiff_data
*state UNUSED
,
913 const char *line UNUSED
,
914 struct patch
*patch UNUSED
)
920 * We're anal about diff header consistency, to make
921 * sure that we don't end up having strange ambiguous
922 * patches floating around.
924 * As a result, gitdiff_{old|new}name() will check
925 * their names against any previous information, just
928 #define DIFF_OLD_NAME 0
929 #define DIFF_NEW_NAME 1
931 static int gitdiff_verify_name(struct gitdiff_data
*state
,
937 if (!*name
&& !isnull
) {
938 *name
= find_name(state
->root
, line
, NULL
, state
->p_value
, TERM_TAB
);
945 return error(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
946 *name
, state
->linenr
);
947 another
= find_name(state
->root
, line
, NULL
, state
->p_value
, TERM_TAB
);
948 if (!another
|| strcmp(another
, *name
)) {
950 return error((side
== DIFF_NEW_NAME
) ?
951 _("git apply: bad git-diff - inconsistent new filename on line %d") :
952 _("git apply: bad git-diff - inconsistent old filename on line %d"), state
->linenr
);
956 if (!is_dev_null(line
))
957 return error(_("git apply: bad git-diff - expected /dev/null on line %d"), state
->linenr
);
963 static int gitdiff_oldname(struct gitdiff_data
*state
,
967 return gitdiff_verify_name(state
, line
,
968 patch
->is_new
, &patch
->old_name
,
972 static int gitdiff_newname(struct gitdiff_data
*state
,
976 return gitdiff_verify_name(state
, line
,
977 patch
->is_delete
, &patch
->new_name
,
981 static int parse_mode_line(const char *line
, int linenr
, unsigned int *mode
)
984 *mode
= strtoul(line
, &end
, 8);
985 if (end
== line
|| !isspace(*end
))
986 return error(_("invalid mode on line %d: %s"), linenr
, line
);
990 static int gitdiff_oldmode(struct gitdiff_data
*state
,
994 return parse_mode_line(line
, state
->linenr
, &patch
->old_mode
);
997 static int gitdiff_newmode(struct gitdiff_data
*state
,
1001 return parse_mode_line(line
, state
->linenr
, &patch
->new_mode
);
1004 static int gitdiff_delete(struct gitdiff_data
*state
,
1006 struct patch
*patch
)
1008 patch
->is_delete
= 1;
1009 free(patch
->old_name
);
1010 patch
->old_name
= xstrdup_or_null(patch
->def_name
);
1011 return gitdiff_oldmode(state
, line
, patch
);
1014 static int gitdiff_newfile(struct gitdiff_data
*state
,
1016 struct patch
*patch
)
1019 free(patch
->new_name
);
1020 patch
->new_name
= xstrdup_or_null(patch
->def_name
);
1021 return gitdiff_newmode(state
, line
, patch
);
1024 static int gitdiff_copysrc(struct gitdiff_data
*state
,
1026 struct patch
*patch
)
1029 free(patch
->old_name
);
1030 patch
->old_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1034 static int gitdiff_copydst(struct gitdiff_data
*state
,
1036 struct patch
*patch
)
1039 free(patch
->new_name
);
1040 patch
->new_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1044 static int gitdiff_renamesrc(struct gitdiff_data
*state
,
1046 struct patch
*patch
)
1048 patch
->is_rename
= 1;
1049 free(patch
->old_name
);
1050 patch
->old_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1054 static int gitdiff_renamedst(struct gitdiff_data
*state
,
1056 struct patch
*patch
)
1058 patch
->is_rename
= 1;
1059 free(patch
->new_name
);
1060 patch
->new_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1064 static int gitdiff_similarity(struct gitdiff_data
*state UNUSED
,
1066 struct patch
*patch
)
1068 unsigned long val
= strtoul(line
, NULL
, 10);
1074 static int gitdiff_dissimilarity(struct gitdiff_data
*state UNUSED
,
1076 struct patch
*patch
)
1078 unsigned long val
= strtoul(line
, NULL
, 10);
1084 static int gitdiff_index(struct gitdiff_data
*state
,
1086 struct patch
*patch
)
1089 * index line is N hexadecimal, "..", N hexadecimal,
1090 * and optional space with octal mode.
1092 const char *ptr
, *eol
;
1094 const unsigned hexsz
= the_hash_algo
->hexsz
;
1096 ptr
= strchr(line
, '.');
1097 if (!ptr
|| ptr
[1] != '.' || hexsz
< ptr
- line
)
1100 memcpy(patch
->old_oid_prefix
, line
, len
);
1101 patch
->old_oid_prefix
[len
] = 0;
1104 ptr
= strchr(line
, ' ');
1105 eol
= strchrnul(line
, '\n');
1107 if (!ptr
|| eol
< ptr
)
1113 memcpy(patch
->new_oid_prefix
, line
, len
);
1114 patch
->new_oid_prefix
[len
] = 0;
1116 return gitdiff_oldmode(state
, ptr
+ 1, patch
);
1121 * This is normal for a diff that doesn't change anything: we'll fall through
1122 * into the next diff. Tell the parser to break out.
1124 static int gitdiff_unrecognized(struct gitdiff_data
*state UNUSED
,
1125 const char *line UNUSED
,
1126 struct patch
*patch UNUSED
)
1132 * Skip p_value leading components from "line"; as we do not accept
1133 * absolute paths, return NULL in that case.
1135 static const char *skip_tree_prefix(int p_value
,
1143 return (llen
&& line
[0] == '/') ? NULL
: line
;
1146 for (i
= 0; i
< llen
; i
++) {
1148 if (ch
== '/' && --nslash
<= 0)
1149 return (i
== 0) ? NULL
: &line
[i
+ 1];
1155 * This is to extract the same name that appears on "diff --git"
1156 * line. We do not find and return anything if it is a rename
1157 * patch, and it is OK because we will find the name elsewhere.
1158 * We need to reliably find name only when it is mode-change only,
1159 * creation or deletion of an empty file. In any of these cases,
1160 * both sides are the same name under a/ and b/ respectively.
1162 static char *git_header_name(int p_value
,
1167 const char *second
= NULL
;
1168 size_t len
, line_len
;
1170 line
+= strlen("diff --git ");
1171 llen
-= strlen("diff --git ");
1175 struct strbuf first
= STRBUF_INIT
;
1176 struct strbuf sp
= STRBUF_INIT
;
1178 if (unquote_c_style(&first
, line
, &second
))
1179 goto free_and_fail1
;
1181 /* strip the a/b prefix including trailing slash */
1182 cp
= skip_tree_prefix(p_value
, first
.buf
, first
.len
);
1184 goto free_and_fail1
;
1185 strbuf_remove(&first
, 0, cp
- first
.buf
);
1188 * second points at one past closing dq of name.
1189 * find the second name.
1191 while ((second
< line
+ llen
) && isspace(*second
))
1194 if (line
+ llen
<= second
)
1195 goto free_and_fail1
;
1196 if (*second
== '"') {
1197 if (unquote_c_style(&sp
, second
, NULL
))
1198 goto free_and_fail1
;
1199 cp
= skip_tree_prefix(p_value
, sp
.buf
, sp
.len
);
1201 goto free_and_fail1
;
1202 /* They must match, otherwise ignore */
1203 if (strcmp(cp
, first
.buf
))
1204 goto free_and_fail1
;
1205 strbuf_release(&sp
);
1206 return strbuf_detach(&first
, NULL
);
1209 /* unquoted second */
1210 cp
= skip_tree_prefix(p_value
, second
, line
+ llen
- second
);
1212 goto free_and_fail1
;
1213 if (line
+ llen
- cp
!= first
.len
||
1214 memcmp(first
.buf
, cp
, first
.len
))
1215 goto free_and_fail1
;
1216 return strbuf_detach(&first
, NULL
);
1219 strbuf_release(&first
);
1220 strbuf_release(&sp
);
1224 /* unquoted first name */
1225 name
= skip_tree_prefix(p_value
, line
, llen
);
1230 * since the first name is unquoted, a dq if exists must be
1231 * the beginning of the second name.
1233 for (second
= name
; second
< line
+ llen
; second
++) {
1234 if (*second
== '"') {
1235 struct strbuf sp
= STRBUF_INIT
;
1238 if (unquote_c_style(&sp
, second
, NULL
))
1239 goto free_and_fail2
;
1241 np
= skip_tree_prefix(p_value
, sp
.buf
, sp
.len
);
1243 goto free_and_fail2
;
1245 len
= sp
.buf
+ sp
.len
- np
;
1246 if (len
< second
- name
&&
1247 !strncmp(np
, name
, len
) &&
1248 isspace(name
[len
])) {
1250 strbuf_remove(&sp
, 0, np
- sp
.buf
);
1251 return strbuf_detach(&sp
, NULL
);
1255 strbuf_release(&sp
);
1261 * Accept a name only if it shows up twice, exactly the same
1264 second
= strchr(name
, '\n');
1267 line_len
= second
- name
;
1268 for (len
= 0 ; ; len
++) {
1269 switch (name
[len
]) {
1274 case '\t': case ' ':
1276 * Is this the separator between the preimage
1277 * and the postimage pathname? Again, we are
1278 * only interested in the case where there is
1279 * no rename, as this is only to set def_name
1280 * and a rename patch has the names elsewhere
1281 * in an unambiguous form.
1284 return NULL
; /* no postimage name */
1285 second
= skip_tree_prefix(p_value
, name
+ len
+ 1,
1286 line_len
- (len
+ 1));
1290 * Does len bytes starting at "name" and "second"
1291 * (that are separated by one HT or SP we just
1292 * found) exactly match?
1294 if (second
[len
] == '\n' && !strncmp(name
, second
, len
))
1295 return xmemdupz(name
, len
);
1300 static int check_header_line(int linenr
, struct patch
*patch
)
1302 int extensions
= (patch
->is_delete
== 1) + (patch
->is_new
== 1) +
1303 (patch
->is_rename
== 1) + (patch
->is_copy
== 1);
1305 return error(_("inconsistent header lines %d and %d"),
1306 patch
->extension_linenr
, linenr
);
1307 if (extensions
&& !patch
->extension_linenr
)
1308 patch
->extension_linenr
= linenr
;
1312 int parse_git_diff_header(struct strbuf
*root
,
1318 struct patch
*patch
)
1320 unsigned long offset
;
1321 struct gitdiff_data parse_hdr_state
;
1323 /* A git diff has explicit new/delete information, so we don't guess */
1325 patch
->is_delete
= 0;
1328 * Some things may not have the old name in the
1329 * rest of the headers anywhere (pure mode changes,
1330 * or removing or adding empty files), so we get
1331 * the default name from the header.
1333 patch
->def_name
= git_header_name(p_value
, line
, len
);
1334 if (patch
->def_name
&& root
->len
) {
1335 char *s
= xstrfmt("%s%s", root
->buf
, patch
->def_name
);
1336 free(patch
->def_name
);
1337 patch
->def_name
= s
;
1343 parse_hdr_state
.root
= root
;
1344 parse_hdr_state
.linenr
= *linenr
;
1345 parse_hdr_state
.p_value
= p_value
;
1347 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, (*linenr
)++) {
1348 static const struct opentry
{
1350 int (*fn
)(struct gitdiff_data
*, const char *, struct patch
*);
1352 { "@@ -", gitdiff_hdrend
},
1353 { "--- ", gitdiff_oldname
},
1354 { "+++ ", gitdiff_newname
},
1355 { "old mode ", gitdiff_oldmode
},
1356 { "new mode ", gitdiff_newmode
},
1357 { "deleted file mode ", gitdiff_delete
},
1358 { "new file mode ", gitdiff_newfile
},
1359 { "copy from ", gitdiff_copysrc
},
1360 { "copy to ", gitdiff_copydst
},
1361 { "rename old ", gitdiff_renamesrc
},
1362 { "rename new ", gitdiff_renamedst
},
1363 { "rename from ", gitdiff_renamesrc
},
1364 { "rename to ", gitdiff_renamedst
},
1365 { "similarity index ", gitdiff_similarity
},
1366 { "dissimilarity index ", gitdiff_dissimilarity
},
1367 { "index ", gitdiff_index
},
1368 { "", gitdiff_unrecognized
},
1372 len
= linelen(line
, size
);
1373 if (!len
|| line
[len
-1] != '\n')
1375 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
1376 const struct opentry
*p
= optable
+ i
;
1377 int oplen
= strlen(p
->str
);
1379 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
1381 res
= p
->fn(&parse_hdr_state
, line
+ oplen
, patch
);
1384 if (check_header_line(*linenr
, patch
))
1393 if (!patch
->old_name
&& !patch
->new_name
) {
1394 if (!patch
->def_name
) {
1395 error(Q_("git diff header lacks filename information when removing "
1396 "%d leading pathname component (line %d)",
1397 "git diff header lacks filename information when removing "
1398 "%d leading pathname components (line %d)",
1399 parse_hdr_state
.p_value
),
1400 parse_hdr_state
.p_value
, *linenr
);
1403 patch
->old_name
= xstrdup(patch
->def_name
);
1404 patch
->new_name
= xstrdup(patch
->def_name
);
1406 if ((!patch
->new_name
&& !patch
->is_delete
) ||
1407 (!patch
->old_name
&& !patch
->is_new
)) {
1408 error(_("git diff header lacks filename information "
1409 "(line %d)"), *linenr
);
1412 patch
->is_toplevel_relative
= 1;
1416 static int parse_num(const char *line
, unsigned long *p
)
1420 if (!isdigit(*line
))
1422 *p
= strtoul(line
, &ptr
, 10);
1426 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
1427 unsigned long *p1
, unsigned long *p2
)
1431 if (offset
< 0 || offset
>= len
)
1436 digits
= parse_num(line
, p1
);
1446 digits
= parse_num(line
+1, p2
);
1455 ex
= strlen(expect
);
1458 if (memcmp(line
, expect
, ex
))
1464 static void recount_diff(const char *line
, int size
, struct fragment
*fragment
)
1466 int oldlines
= 0, newlines
= 0, ret
= 0;
1469 warning("recount: ignore empty hunk");
1474 int len
= linelen(line
, size
);
1482 case ' ': case '\n':
1494 ret
= size
< 3 || !starts_with(line
, "@@ ");
1497 ret
= size
< 5 || !starts_with(line
, "diff ");
1504 warning(_("recount: unexpected line: %.*s"),
1505 (int)linelen(line
, size
), line
);
1510 fragment
->oldlines
= oldlines
;
1511 fragment
->newlines
= newlines
;
1515 * Parse a unified diff fragment header of the
1516 * form "@@ -a,b +c,d @@"
1518 static int parse_fragment_header(const char *line
, int len
, struct fragment
*fragment
)
1522 if (!len
|| line
[len
-1] != '\n')
1525 /* Figure out the number of lines in a fragment */
1526 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
1527 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
1533 * Find file diff header
1536 * -1 if no header was found
1537 * -128 in case of error
1538 * the size of the header in bytes (called "offset") otherwise
1540 static int find_header(struct apply_state
*state
,
1544 struct patch
*patch
)
1546 unsigned long offset
, len
;
1548 patch
->is_toplevel_relative
= 0;
1549 patch
->is_rename
= patch
->is_copy
= 0;
1550 patch
->is_new
= patch
->is_delete
= -1;
1551 patch
->old_mode
= patch
->new_mode
= 0;
1552 patch
->old_name
= patch
->new_name
= NULL
;
1553 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1554 unsigned long nextlen
;
1556 len
= linelen(line
, size
);
1560 /* Testing this early allows us to take a few shortcuts.. */
1565 * Make sure we don't find any unconnected patch fragments.
1566 * That's a sign that we didn't find a header, and that a
1567 * patch has become corrupted/broken up.
1569 if (!memcmp("@@ -", line
, 4)) {
1570 struct fragment dummy
;
1571 if (parse_fragment_header(line
, len
, &dummy
) < 0)
1573 error(_("patch fragment without header at line %d: %.*s"),
1574 state
->linenr
, (int)len
-1, line
);
1582 * Git patch? It might not have a real patch, just a rename
1583 * or mode change, so we handle that specially
1585 if (!memcmp("diff --git ", line
, 11)) {
1586 int git_hdr_len
= parse_git_diff_header(&state
->root
, &state
->linenr
,
1587 state
->p_value
, line
, len
,
1589 if (git_hdr_len
< 0)
1591 if (git_hdr_len
<= len
)
1593 *hdrsize
= git_hdr_len
;
1597 /* --- followed by +++ ? */
1598 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
1602 * We only accept unified patches, so we want it to
1603 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1604 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1606 nextlen
= linelen(line
+ len
, size
- len
);
1607 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
1610 /* Ok, we'll consider it a patch */
1611 if (parse_traditional_patch(state
, line
, line
+len
, patch
))
1613 *hdrsize
= len
+ nextlen
;
1620 static void record_ws_error(struct apply_state
*state
,
1631 state
->whitespace_error
++;
1632 if (state
->squelch_whitespace_errors
&&
1633 state
->squelch_whitespace_errors
< state
->whitespace_error
)
1636 err
= whitespace_error_string(result
);
1637 if (state
->apply_verbosity
> verbosity_silent
)
1638 fprintf(stderr
, "%s:%d: %s.\n%.*s\n",
1639 state
->patch_input_file
, linenr
, err
, len
, line
);
1643 static void check_whitespace(struct apply_state
*state
,
1648 unsigned result
= ws_check(line
+ 1, len
- 1, ws_rule
);
1650 record_ws_error(state
, result
, line
+ 1, len
- 2, state
->linenr
);
1654 * Check if the patch has context lines with CRLF or
1655 * the patch wants to remove lines with CRLF.
1657 static void check_old_for_crlf(struct patch
*patch
, const char *line
, int len
)
1659 if (len
>= 2 && line
[len
-1] == '\n' && line
[len
-2] == '\r') {
1660 patch
->ws_rule
|= WS_CR_AT_EOL
;
1661 patch
->crlf_in_old
= 1;
1667 * Parse a unified diff. Note that this really needs to parse each
1668 * fragment separately, since the only way to know the difference
1669 * between a "---" that is part of a patch, and a "---" that starts
1670 * the next patch is to look at the line counts..
1672 static int parse_fragment(struct apply_state
*state
,
1675 struct patch
*patch
,
1676 struct fragment
*fragment
)
1679 int len
= linelen(line
, size
), offset
;
1680 unsigned long oldlines
, newlines
;
1681 unsigned long leading
, trailing
;
1683 offset
= parse_fragment_header(line
, len
, fragment
);
1686 if (offset
> 0 && patch
->recount
)
1687 recount_diff(line
+ offset
, size
- offset
, fragment
);
1688 oldlines
= fragment
->oldlines
;
1689 newlines
= fragment
->newlines
;
1693 /* Parse the thing.. */
1697 added
= deleted
= 0;
1700 offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1701 if (!oldlines
&& !newlines
)
1703 len
= linelen(line
, size
);
1704 if (!len
|| line
[len
-1] != '\n')
1709 case '\n': /* newer GNU diff, an empty context line */
1713 if (!deleted
&& !added
)
1716 check_old_for_crlf(patch
, line
, len
);
1717 if (!state
->apply_in_reverse
&&
1718 state
->ws_error_action
== correct_ws_error
)
1719 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1722 if (!state
->apply_in_reverse
)
1723 check_old_for_crlf(patch
, line
, len
);
1724 if (state
->apply_in_reverse
&&
1725 state
->ws_error_action
!= nowarn_ws_error
)
1726 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1732 if (state
->apply_in_reverse
)
1733 check_old_for_crlf(patch
, line
, len
);
1734 if (!state
->apply_in_reverse
&&
1735 state
->ws_error_action
!= nowarn_ws_error
)
1736 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1743 * We allow "\ No newline at end of file". Depending
1744 * on locale settings when the patch was produced we
1745 * don't know what this line looks like. The only
1746 * thing we do know is that it begins with "\ ".
1747 * Checking for 12 is just for sanity check -- any
1748 * l10n of "\ No newline..." is at least that long.
1751 if (len
< 12 || memcmp(line
, "\\ ", 2))
1756 if (oldlines
|| newlines
)
1758 if (!patch
->recount
&& !deleted
&& !added
)
1761 fragment
->leading
= leading
;
1762 fragment
->trailing
= trailing
;
1765 * If a fragment ends with an incomplete line, we failed to include
1766 * it in the above loop because we hit oldlines == newlines == 0
1769 if (12 < size
&& !memcmp(line
, "\\ ", 2))
1770 offset
+= linelen(line
, size
);
1772 patch
->lines_added
+= added
;
1773 patch
->lines_deleted
+= deleted
;
1775 if (0 < patch
->is_new
&& oldlines
)
1776 return error(_("new file depends on old contents"));
1777 if (0 < patch
->is_delete
&& newlines
)
1778 return error(_("deleted file still has contents"));
1783 * We have seen "diff --git a/... b/..." header (or a traditional patch
1784 * header). Read hunks that belong to this patch into fragments and hang
1785 * them to the given patch structure.
1787 * The (fragment->patch, fragment->size) pair points into the memory given
1788 * by the caller, not a copy, when we return.
1791 * -1 in case of error,
1792 * the number of bytes in the patch otherwise.
1794 static int parse_single_patch(struct apply_state
*state
,
1797 struct patch
*patch
)
1799 unsigned long offset
= 0;
1800 unsigned long oldlines
= 0, newlines
= 0, context
= 0;
1801 struct fragment
**fragp
= &patch
->fragments
;
1803 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
1804 struct fragment
*fragment
;
1807 CALLOC_ARRAY(fragment
, 1);
1808 fragment
->linenr
= state
->linenr
;
1809 len
= parse_fragment(state
, line
, size
, patch
, fragment
);
1812 return error(_("corrupt patch at line %d"), state
->linenr
);
1814 fragment
->patch
= line
;
1815 fragment
->size
= len
;
1816 oldlines
+= fragment
->oldlines
;
1817 newlines
+= fragment
->newlines
;
1818 context
+= fragment
->leading
+ fragment
->trailing
;
1821 fragp
= &fragment
->next
;
1829 * If something was removed (i.e. we have old-lines) it cannot
1830 * be creation, and if something was added it cannot be
1831 * deletion. However, the reverse is not true; --unified=0
1832 * patches that only add are not necessarily creation even
1833 * though they do not have any old lines, and ones that only
1834 * delete are not necessarily deletion.
1836 * Unfortunately, a real creation/deletion patch do _not_ have
1837 * any context line by definition, so we cannot safely tell it
1838 * apart with --unified=0 insanity. At least if the patch has
1839 * more than one hunk it is not creation or deletion.
1841 if (patch
->is_new
< 0 &&
1842 (oldlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1844 if (patch
->is_delete
< 0 &&
1845 (newlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1846 patch
->is_delete
= 0;
1848 if (0 < patch
->is_new
&& oldlines
)
1849 return error(_("new file %s depends on old contents"), patch
->new_name
);
1850 if (0 < patch
->is_delete
&& newlines
)
1851 return error(_("deleted file %s still has contents"), patch
->old_name
);
1852 if (!patch
->is_delete
&& !newlines
&& context
&& state
->apply_verbosity
> verbosity_silent
)
1855 "file %s becomes empty but is not deleted"),
1861 static inline int metadata_changes(struct patch
*patch
)
1863 return patch
->is_rename
> 0 ||
1864 patch
->is_copy
> 0 ||
1865 patch
->is_new
> 0 ||
1867 (patch
->old_mode
&& patch
->new_mode
&&
1868 patch
->old_mode
!= patch
->new_mode
);
1871 static char *inflate_it(const void *data
, unsigned long size
,
1872 unsigned long inflated_size
)
1878 memset(&stream
, 0, sizeof(stream
));
1880 stream
.next_in
= (unsigned char *)data
;
1881 stream
.avail_in
= size
;
1882 stream
.next_out
= out
= xmalloc(inflated_size
);
1883 stream
.avail_out
= inflated_size
;
1884 git_inflate_init(&stream
);
1885 st
= git_inflate(&stream
, Z_FINISH
);
1886 git_inflate_end(&stream
);
1887 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1895 * Read a binary hunk and return a new fragment; fragment->patch
1896 * points at an allocated memory that the caller must free, so
1897 * it is marked as "->free_patch = 1".
1899 static struct fragment
*parse_binary_hunk(struct apply_state
*state
,
1901 unsigned long *sz_p
,
1906 * Expect a line that begins with binary patch method ("literal"
1907 * or "delta"), followed by the length of data before deflating.
1908 * a sequence of 'length-byte' followed by base-85 encoded data
1909 * should follow, terminated by a newline.
1911 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1912 * and we would limit the patch line to 66 characters,
1913 * so one line can fit up to 13 groups that would decode
1914 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1915 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1918 unsigned long size
= *sz_p
;
1919 char *buffer
= *buf_p
;
1921 unsigned long origlen
;
1924 struct fragment
*frag
;
1926 llen
= linelen(buffer
, size
);
1931 if (starts_with(buffer
, "delta ")) {
1932 patch_method
= BINARY_DELTA_DEFLATED
;
1933 origlen
= strtoul(buffer
+ 6, NULL
, 10);
1935 else if (starts_with(buffer
, "literal ")) {
1936 patch_method
= BINARY_LITERAL_DEFLATED
;
1937 origlen
= strtoul(buffer
+ 8, NULL
, 10);
1946 int byte_length
, max_byte_length
, newsize
;
1947 llen
= linelen(buffer
, size
);
1951 /* consume the blank line */
1957 * Minimum line is "A00000\n" which is 7-byte long,
1958 * and the line length must be multiple of 5 plus 2.
1960 if ((llen
< 7) || (llen
-2) % 5)
1962 max_byte_length
= (llen
- 2) / 5 * 4;
1963 byte_length
= *buffer
;
1964 if ('A' <= byte_length
&& byte_length
<= 'Z')
1965 byte_length
= byte_length
- 'A' + 1;
1966 else if ('a' <= byte_length
&& byte_length
<= 'z')
1967 byte_length
= byte_length
- 'a' + 27;
1970 /* if the input length was not multiple of 4, we would
1971 * have filler at the end but the filler should never
1974 if (max_byte_length
< byte_length
||
1975 byte_length
<= max_byte_length
- 4)
1977 newsize
= hunk_size
+ byte_length
;
1978 data
= xrealloc(data
, newsize
);
1979 if (decode_85(data
+ hunk_size
, buffer
+ 1, byte_length
))
1981 hunk_size
= newsize
;
1986 CALLOC_ARRAY(frag
, 1);
1987 frag
->patch
= inflate_it(data
, hunk_size
, origlen
);
1988 frag
->free_patch
= 1;
1992 frag
->size
= origlen
;
1996 frag
->binary_patch_method
= patch_method
;
2002 error(_("corrupt binary patch at line %d: %.*s"),
2003 state
->linenr
-1, llen
-1, buffer
);
2009 * -1 in case of error,
2010 * the length of the parsed binary patch otherwise
2012 static int parse_binary(struct apply_state
*state
,
2015 struct patch
*patch
)
2018 * We have read "GIT binary patch\n"; what follows is a line
2019 * that says the patch method (currently, either "literal" or
2020 * "delta") and the length of data before deflating; a
2021 * sequence of 'length-byte' followed by base-85 encoded data
2024 * When a binary patch is reversible, there is another binary
2025 * hunk in the same format, starting with patch method (either
2026 * "literal" or "delta") with the length of data, and a sequence
2027 * of length-byte + base-85 encoded data, terminated with another
2028 * empty line. This data, when applied to the postimage, produces
2031 struct fragment
*forward
;
2032 struct fragment
*reverse
;
2036 forward
= parse_binary_hunk(state
, &buffer
, &size
, &status
, &used
);
2037 if (!forward
&& !status
)
2038 /* there has to be one hunk (forward hunk) */
2039 return error(_("unrecognized binary patch at line %d"), state
->linenr
-1);
2041 /* otherwise we already gave an error message */
2044 reverse
= parse_binary_hunk(state
, &buffer
, &size
, &status
, &used_1
);
2049 * Not having reverse hunk is not an error, but having
2050 * a corrupt reverse hunk is.
2052 free((void*) forward
->patch
);
2056 forward
->next
= reverse
;
2057 patch
->fragments
= forward
;
2058 patch
->is_binary
= 1;
2062 static void prefix_one(struct apply_state
*state
, char **name
)
2064 char *old_name
= *name
;
2067 *name
= prefix_filename(state
->prefix
, *name
);
2071 static void prefix_patch(struct apply_state
*state
, struct patch
*p
)
2073 if (!state
->prefix
|| p
->is_toplevel_relative
)
2075 prefix_one(state
, &p
->new_name
);
2076 prefix_one(state
, &p
->old_name
);
2083 static void add_name_limit(struct apply_state
*state
,
2087 struct string_list_item
*it
;
2089 it
= string_list_append(&state
->limit_by_name
, name
);
2090 it
->util
= exclude
? NULL
: (void *) 1;
2093 static int use_patch(struct apply_state
*state
, struct patch
*p
)
2095 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
2098 /* Paths outside are not touched regardless of "--include" */
2099 if (state
->prefix
&& *state
->prefix
) {
2101 if (!skip_prefix(pathname
, state
->prefix
, &rest
) || !*rest
)
2105 /* See if it matches any of exclude/include rule */
2106 for (i
= 0; i
< state
->limit_by_name
.nr
; i
++) {
2107 struct string_list_item
*it
= &state
->limit_by_name
.items
[i
];
2108 if (!wildmatch(it
->string
, pathname
, 0))
2109 return (it
->util
!= NULL
);
2113 * If we had any include, a path that does not match any rule is
2114 * not used. Otherwise, we saw bunch of exclude rules (or none)
2115 * and such a path is used.
2117 return !state
->has_include
;
2121 * Read the patch text in "buffer" that extends for "size" bytes; stop
2122 * reading after seeing a single patch (i.e. changes to a single file).
2123 * Create fragments (i.e. patch hunks) and hang them to the given patch.
2126 * -1 if no header was found or parse_binary() failed,
2127 * -128 on another error,
2128 * the number of bytes consumed otherwise,
2129 * so that the caller can call us again for the next patch.
2131 static int parse_chunk(struct apply_state
*state
, char *buffer
, unsigned long size
, struct patch
*patch
)
2133 int hdrsize
, patchsize
;
2134 int offset
= find_header(state
, buffer
, size
, &hdrsize
, patch
);
2139 prefix_patch(state
, patch
);
2141 if (!use_patch(state
, patch
))
2143 else if (patch
->new_name
)
2144 patch
->ws_rule
= whitespace_rule(state
->repo
->index
,
2147 patch
->ws_rule
= whitespace_rule(state
->repo
->index
,
2150 patchsize
= parse_single_patch(state
,
2151 buffer
+ offset
+ hdrsize
,
2152 size
- offset
- hdrsize
,
2159 static const char git_binary
[] = "GIT binary patch\n";
2160 int hd
= hdrsize
+ offset
;
2161 unsigned long llen
= linelen(buffer
+ hd
, size
- hd
);
2163 if (llen
== sizeof(git_binary
) - 1 &&
2164 !memcmp(git_binary
, buffer
+ hd
, llen
)) {
2167 used
= parse_binary(state
, buffer
+ hd
+ llen
,
2168 size
- hd
- llen
, patch
);
2172 patchsize
= used
+ llen
;
2176 else if (!memcmp(" differ\n", buffer
+ hd
+ llen
- 8, 8)) {
2177 static const char *binhdr
[] = {
2183 for (i
= 0; binhdr
[i
]; i
++) {
2184 int len
= strlen(binhdr
[i
]);
2185 if (len
< size
- hd
&&
2186 !memcmp(binhdr
[i
], buffer
+ hd
, len
)) {
2188 patch
->is_binary
= 1;
2195 /* Empty patch cannot be applied if it is a text patch
2196 * without metadata change. A binary patch appears
2199 if ((state
->apply
|| state
->check
) &&
2200 (!patch
->is_binary
&& !metadata_changes(patch
))) {
2201 error(_("patch with only garbage at line %d"), state
->linenr
);
2206 return offset
+ hdrsize
+ patchsize
;
2209 static void reverse_patches(struct patch
*p
)
2211 for (; p
; p
= p
->next
) {
2212 struct fragment
*frag
= p
->fragments
;
2214 SWAP(p
->new_name
, p
->old_name
);
2215 SWAP(p
->new_mode
, p
->old_mode
);
2216 SWAP(p
->is_new
, p
->is_delete
);
2217 SWAP(p
->lines_added
, p
->lines_deleted
);
2218 SWAP(p
->old_oid_prefix
, p
->new_oid_prefix
);
2220 for (; frag
; frag
= frag
->next
) {
2221 SWAP(frag
->newpos
, frag
->oldpos
);
2222 SWAP(frag
->newlines
, frag
->oldlines
);
2227 static const char pluses
[] =
2228 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2229 static const char minuses
[]=
2230 "----------------------------------------------------------------------";
2232 static void show_stats(struct apply_state
*state
, struct patch
*patch
)
2234 struct strbuf qname
= STRBUF_INIT
;
2235 char *cp
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
2238 quote_c_style(cp
, &qname
, NULL
, 0);
2241 * "scale" the filename
2243 max
= state
->max_len
;
2247 if (qname
.len
> max
) {
2248 cp
= strchr(qname
.buf
+ qname
.len
+ 3 - max
, '/');
2250 cp
= qname
.buf
+ qname
.len
+ 3 - max
;
2251 strbuf_splice(&qname
, 0, cp
- qname
.buf
, "...", 3);
2254 if (patch
->is_binary
) {
2255 printf(" %-*s | Bin\n", max
, qname
.buf
);
2256 strbuf_release(&qname
);
2260 printf(" %-*s |", max
, qname
.buf
);
2261 strbuf_release(&qname
);
2264 * scale the add/delete
2266 max
= max
+ state
->max_change
> 70 ? 70 - max
: state
->max_change
;
2267 add
= patch
->lines_added
;
2268 del
= patch
->lines_deleted
;
2270 if (state
->max_change
> 0) {
2271 int total
= ((add
+ del
) * max
+ state
->max_change
/ 2) / state
->max_change
;
2272 add
= (add
* max
+ state
->max_change
/ 2) / state
->max_change
;
2275 printf("%5d %.*s%.*s\n", patch
->lines_added
+ patch
->lines_deleted
,
2276 add
, pluses
, del
, minuses
);
2279 static int read_old_data(struct stat
*st
, struct patch
*patch
,
2280 const char *path
, struct strbuf
*buf
)
2282 int conv_flags
= patch
->crlf_in_old
?
2283 CONV_EOL_KEEP_CRLF
: CONV_EOL_RENORMALIZE
;
2284 switch (st
->st_mode
& S_IFMT
) {
2286 if (strbuf_readlink(buf
, path
, st
->st_size
) < 0)
2287 return error(_("unable to read symlink %s"), path
);
2290 if (strbuf_read_file(buf
, path
, st
->st_size
) != st
->st_size
)
2291 return error(_("unable to open or read %s"), path
);
2293 * "git apply" without "--index/--cached" should never look
2294 * at the index; the target file may not have been added to
2295 * the index yet, and we may not even be in any Git repository.
2296 * Pass NULL to convert_to_git() to stress this; the function
2297 * should never look at the index when explicit crlf option
2300 convert_to_git(NULL
, path
, buf
->buf
, buf
->len
, buf
, conv_flags
);
2308 * Update the preimage, and the common lines in postimage,
2309 * from buffer buf of length len. If postlen is 0 the postimage
2310 * is updated in place, otherwise it's updated on a new buffer
2314 static void update_pre_post_images(struct image
*preimage
,
2315 struct image
*postimage
,
2317 size_t len
, size_t postlen
)
2319 int i
, ctx
, reduced
;
2320 char *new_buf
, *old_buf
, *fixed
;
2321 struct image fixed_preimage
;
2324 * Update the preimage with whitespace fixes. Note that we
2325 * are not losing preimage->buf -- apply_one_fragment() will
2328 prepare_image(&fixed_preimage
, buf
, len
, 1);
2330 ? fixed_preimage
.nr
== preimage
->nr
2331 : fixed_preimage
.nr
<= preimage
->nr
);
2332 for (i
= 0; i
< fixed_preimage
.nr
; i
++)
2333 fixed_preimage
.line
[i
].flag
= preimage
->line
[i
].flag
;
2334 free(preimage
->line_allocated
);
2335 *preimage
= fixed_preimage
;
2338 * Adjust the common context lines in postimage. This can be
2339 * done in-place when we are shrinking it with whitespace
2340 * fixing, but needs a new buffer when ignoring whitespace or
2341 * expanding leading tabs to spaces.
2343 * We trust the caller to tell us if the update can be done
2344 * in place (postlen==0) or not.
2346 old_buf
= postimage
->buf
;
2348 new_buf
= postimage
->buf
= xmalloc(postlen
);
2351 fixed
= preimage
->buf
;
2353 for (i
= reduced
= ctx
= 0; i
< postimage
->nr
; i
++) {
2354 size_t l_len
= postimage
->line
[i
].len
;
2355 if (!(postimage
->line
[i
].flag
& LINE_COMMON
)) {
2356 /* an added line -- no counterparts in preimage */
2357 memmove(new_buf
, old_buf
, l_len
);
2363 /* a common context -- skip it in the original postimage */
2366 /* and find the corresponding one in the fixed preimage */
2367 while (ctx
< preimage
->nr
&&
2368 !(preimage
->line
[ctx
].flag
& LINE_COMMON
)) {
2369 fixed
+= preimage
->line
[ctx
].len
;
2374 * preimage is expected to run out, if the caller
2375 * fixed addition of trailing blank lines.
2377 if (preimage
->nr
<= ctx
) {
2382 /* and copy it in, while fixing the line length */
2383 l_len
= preimage
->line
[ctx
].len
;
2384 memcpy(new_buf
, fixed
, l_len
);
2387 postimage
->line
[i
].len
= l_len
;
2392 ? postlen
< new_buf
- postimage
->buf
2393 : postimage
->len
< new_buf
- postimage
->buf
)
2394 BUG("caller miscounted postlen: asked %d, orig = %d, used = %d",
2395 (int)postlen
, (int) postimage
->len
, (int)(new_buf
- postimage
->buf
));
2397 /* Fix the length of the whole thing */
2398 postimage
->len
= new_buf
- postimage
->buf
;
2399 postimage
->nr
-= reduced
;
2402 static int line_by_line_fuzzy_match(struct image
*img
,
2403 struct image
*preimage
,
2404 struct image
*postimage
,
2405 unsigned long current
,
2412 size_t postlen
= postimage
->len
;
2417 struct strbuf fixed
;
2421 for (i
= 0; i
< preimage_limit
; i
++) {
2422 size_t prelen
= preimage
->line
[i
].len
;
2423 size_t imglen
= img
->line
[current_lno
+i
].len
;
2425 if (!fuzzy_matchlines(img
->buf
+ current
+ imgoff
, imglen
,
2426 preimage
->buf
+ preoff
, prelen
))
2428 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2429 postlen
+= imglen
- prelen
;
2435 * Ok, the preimage matches with whitespace fuzz.
2437 * imgoff now holds the true length of the target that
2438 * matches the preimage before the end of the file.
2440 * Count the number of characters in the preimage that fall
2441 * beyond the end of the file and make sure that all of them
2442 * are whitespace characters. (This can only happen if
2443 * we are removing blank lines at the end of the file.)
2445 buf
= preimage_eof
= preimage
->buf
+ preoff
;
2446 for ( ; i
< preimage
->nr
; i
++)
2447 preoff
+= preimage
->line
[i
].len
;
2448 preimage_end
= preimage
->buf
+ preoff
;
2449 for ( ; buf
< preimage_end
; buf
++)
2454 * Update the preimage and the common postimage context
2455 * lines to use the same whitespace as the target.
2456 * If whitespace is missing in the target (i.e.
2457 * if the preimage extends beyond the end of the file),
2458 * use the whitespace from the preimage.
2460 extra_chars
= preimage_end
- preimage_eof
;
2461 strbuf_init(&fixed
, imgoff
+ extra_chars
);
2462 strbuf_add(&fixed
, img
->buf
+ current
, imgoff
);
2463 strbuf_add(&fixed
, preimage_eof
, extra_chars
);
2464 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2465 update_pre_post_images(preimage
, postimage
,
2466 fixed_buf
, fixed_len
, postlen
);
2470 static int match_fragment(struct apply_state
*state
,
2472 struct image
*preimage
,
2473 struct image
*postimage
,
2474 unsigned long current
,
2477 int match_beginning
, int match_end
)
2480 char *fixed_buf
, *buf
, *orig
, *target
;
2481 struct strbuf fixed
;
2482 size_t fixed_len
, postlen
;
2485 if (preimage
->nr
+ current_lno
<= img
->nr
) {
2487 * The hunk falls within the boundaries of img.
2489 preimage_limit
= preimage
->nr
;
2490 if (match_end
&& (preimage
->nr
+ current_lno
!= img
->nr
))
2492 } else if (state
->ws_error_action
== correct_ws_error
&&
2493 (ws_rule
& WS_BLANK_AT_EOF
)) {
2495 * This hunk extends beyond the end of img, and we are
2496 * removing blank lines at the end of the file. This
2497 * many lines from the beginning of the preimage must
2498 * match with img, and the remainder of the preimage
2501 preimage_limit
= img
->nr
- current_lno
;
2504 * The hunk extends beyond the end of the img and
2505 * we are not removing blanks at the end, so we
2506 * should reject the hunk at this position.
2511 if (match_beginning
&& current_lno
)
2514 /* Quick hash check */
2515 for (i
= 0; i
< preimage_limit
; i
++)
2516 if ((img
->line
[current_lno
+ i
].flag
& LINE_PATCHED
) ||
2517 (preimage
->line
[i
].hash
!= img
->line
[current_lno
+ i
].hash
))
2520 if (preimage_limit
== preimage
->nr
) {
2522 * Do we have an exact match? If we were told to match
2523 * at the end, size must be exactly at current+fragsize,
2524 * otherwise current+fragsize must be still within the preimage,
2525 * and either case, the old piece should match the preimage
2529 ? (current
+ preimage
->len
== img
->len
)
2530 : (current
+ preimage
->len
<= img
->len
)) &&
2531 !memcmp(img
->buf
+ current
, preimage
->buf
, preimage
->len
))
2535 * The preimage extends beyond the end of img, so
2536 * there cannot be an exact match.
2538 * There must be one non-blank context line that match
2539 * a line before the end of img.
2543 buf
= preimage
->buf
;
2545 for (i
= 0; i
< preimage_limit
; i
++)
2546 buf_end
+= preimage
->line
[i
].len
;
2548 for ( ; buf
< buf_end
; buf
++)
2556 * No exact match. If we are ignoring whitespace, run a line-by-line
2557 * fuzzy matching. We collect all the line length information because
2558 * we need it to adjust whitespace if we match.
2560 if (state
->ws_ignore_action
== ignore_ws_change
)
2561 return line_by_line_fuzzy_match(img
, preimage
, postimage
,
2562 current
, current_lno
, preimage_limit
);
2564 if (state
->ws_error_action
!= correct_ws_error
)
2568 * The hunk does not apply byte-by-byte, but the hash says
2569 * it might with whitespace fuzz. We weren't asked to
2570 * ignore whitespace, we were asked to correct whitespace
2571 * errors, so let's try matching after whitespace correction.
2573 * While checking the preimage against the target, whitespace
2574 * errors in both fixed, we count how large the corresponding
2575 * postimage needs to be. The postimage prepared by
2576 * apply_one_fragment() has whitespace errors fixed on added
2577 * lines already, but the common lines were propagated as-is,
2578 * which may become longer when their whitespace errors are
2582 /* First count added lines in postimage */
2584 for (i
= 0; i
< postimage
->nr
; i
++) {
2585 if (!(postimage
->line
[i
].flag
& LINE_COMMON
))
2586 postlen
+= postimage
->line
[i
].len
;
2590 * The preimage may extend beyond the end of the file,
2591 * but in this loop we will only handle the part of the
2592 * preimage that falls within the file.
2594 strbuf_init(&fixed
, preimage
->len
+ 1);
2595 orig
= preimage
->buf
;
2596 target
= img
->buf
+ current
;
2597 for (i
= 0; i
< preimage_limit
; i
++) {
2598 size_t oldlen
= preimage
->line
[i
].len
;
2599 size_t tgtlen
= img
->line
[current_lno
+ i
].len
;
2600 size_t fixstart
= fixed
.len
;
2601 struct strbuf tgtfix
;
2604 /* Try fixing the line in the preimage */
2605 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2607 /* Try fixing the line in the target */
2608 strbuf_init(&tgtfix
, tgtlen
);
2609 ws_fix_copy(&tgtfix
, target
, tgtlen
, ws_rule
, NULL
);
2612 * If they match, either the preimage was based on
2613 * a version before our tree fixed whitespace breakage,
2614 * or we are lacking a whitespace-fix patch the tree
2615 * the preimage was based on already had (i.e. target
2616 * has whitespace breakage, the preimage doesn't).
2617 * In either case, we are fixing the whitespace breakages
2618 * so we might as well take the fix together with their
2621 match
= (tgtfix
.len
== fixed
.len
- fixstart
&&
2622 !memcmp(tgtfix
.buf
, fixed
.buf
+ fixstart
,
2623 fixed
.len
- fixstart
));
2625 /* Add the length if this is common with the postimage */
2626 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2627 postlen
+= tgtfix
.len
;
2629 strbuf_release(&tgtfix
);
2639 * Now handle the lines in the preimage that falls beyond the
2640 * end of the file (if any). They will only match if they are
2641 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2644 for ( ; i
< preimage
->nr
; i
++) {
2645 size_t fixstart
= fixed
.len
; /* start of the fixed preimage */
2646 size_t oldlen
= preimage
->line
[i
].len
;
2649 /* Try fixing the line in the preimage */
2650 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2652 for (j
= fixstart
; j
< fixed
.len
; j
++)
2653 if (!isspace(fixed
.buf
[j
]))
2660 * Yes, the preimage is based on an older version that still
2661 * has whitespace breakages unfixed, and fixing them makes the
2662 * hunk match. Update the context lines in the postimage.
2664 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2665 if (postlen
< postimage
->len
)
2667 update_pre_post_images(preimage
, postimage
,
2668 fixed_buf
, fixed_len
, postlen
);
2672 strbuf_release(&fixed
);
2676 static int find_pos(struct apply_state
*state
,
2678 struct image
*preimage
,
2679 struct image
*postimage
,
2682 int match_beginning
, int match_end
)
2685 unsigned long backwards
, forwards
, current
;
2686 int backwards_lno
, forwards_lno
, current_lno
;
2689 * When running with --allow-overlap, it is possible that a hunk is
2690 * seen that pretends to start at the beginning (but no longer does),
2691 * and that *still* needs to match the end. So trust `match_end` more
2692 * than `match_beginning`.
2694 if (state
->allow_overlap
&& match_beginning
&& match_end
&&
2695 img
->nr
- preimage
->nr
!= 0)
2696 match_beginning
= 0;
2699 * If match_beginning or match_end is specified, there is no
2700 * point starting from a wrong line that will never match and
2701 * wander around and wait for a match at the specified end.
2703 if (match_beginning
)
2706 line
= img
->nr
- preimage
->nr
;
2709 * Because the comparison is unsigned, the following test
2710 * will also take care of a negative line number that can
2711 * result when match_end and preimage is larger than the target.
2713 if ((size_t) line
> img
->nr
)
2717 for (i
= 0; i
< line
; i
++)
2718 current
+= img
->line
[i
].len
;
2721 * There's probably some smart way to do this, but I'll leave
2722 * that to the smart and beautiful people. I'm simple and stupid.
2724 backwards
= current
;
2725 backwards_lno
= line
;
2727 forwards_lno
= line
;
2730 for (i
= 0; ; i
++) {
2731 if (match_fragment(state
, img
, preimage
, postimage
,
2732 current
, current_lno
, ws_rule
,
2733 match_beginning
, match_end
))
2737 if (backwards_lno
== 0 && forwards_lno
== img
->nr
)
2741 if (backwards_lno
== 0) {
2746 backwards
-= img
->line
[backwards_lno
].len
;
2747 current
= backwards
;
2748 current_lno
= backwards_lno
;
2750 if (forwards_lno
== img
->nr
) {
2754 forwards
+= img
->line
[forwards_lno
].len
;
2757 current_lno
= forwards_lno
;
2764 static void remove_first_line(struct image
*img
)
2766 img
->buf
+= img
->line
[0].len
;
2767 img
->len
-= img
->line
[0].len
;
2772 static void remove_last_line(struct image
*img
)
2774 img
->len
-= img
->line
[--img
->nr
].len
;
2778 * The change from "preimage" and "postimage" has been found to
2779 * apply at applied_pos (counts in line numbers) in "img".
2780 * Update "img" to remove "preimage" and replace it with "postimage".
2782 static void update_image(struct apply_state
*state
,
2785 struct image
*preimage
,
2786 struct image
*postimage
)
2789 * remove the copy of preimage at offset in img
2790 * and replace it with postimage
2793 size_t remove_count
, insert_count
, applied_at
= 0;
2798 * If we are removing blank lines at the end of img,
2799 * the preimage may extend beyond the end.
2800 * If that is the case, we must be careful only to
2801 * remove the part of the preimage that falls within
2802 * the boundaries of img. Initialize preimage_limit
2803 * to the number of lines in the preimage that falls
2804 * within the boundaries.
2806 preimage_limit
= preimage
->nr
;
2807 if (preimage_limit
> img
->nr
- applied_pos
)
2808 preimage_limit
= img
->nr
- applied_pos
;
2810 for (i
= 0; i
< applied_pos
; i
++)
2811 applied_at
+= img
->line
[i
].len
;
2814 for (i
= 0; i
< preimage_limit
; i
++)
2815 remove_count
+= img
->line
[applied_pos
+ i
].len
;
2816 insert_count
= postimage
->len
;
2818 /* Adjust the contents */
2819 result
= xmalloc(st_add3(st_sub(img
->len
, remove_count
), insert_count
, 1));
2820 memcpy(result
, img
->buf
, applied_at
);
2821 memcpy(result
+ applied_at
, postimage
->buf
, postimage
->len
);
2822 memcpy(result
+ applied_at
+ postimage
->len
,
2823 img
->buf
+ (applied_at
+ remove_count
),
2824 img
->len
- (applied_at
+ remove_count
));
2827 img
->len
+= insert_count
- remove_count
;
2828 result
[img
->len
] = '\0';
2830 /* Adjust the line table */
2831 nr
= img
->nr
+ postimage
->nr
- preimage_limit
;
2832 if (preimage_limit
< postimage
->nr
) {
2834 * NOTE: this knows that we never call remove_first_line()
2835 * on anything other than pre/post image.
2837 REALLOC_ARRAY(img
->line
, nr
);
2838 img
->line_allocated
= img
->line
;
2840 if (preimage_limit
!= postimage
->nr
)
2841 MOVE_ARRAY(img
->line
+ applied_pos
+ postimage
->nr
,
2842 img
->line
+ applied_pos
+ preimage_limit
,
2843 img
->nr
- (applied_pos
+ preimage_limit
));
2844 COPY_ARRAY(img
->line
+ applied_pos
, postimage
->line
, postimage
->nr
);
2845 if (!state
->allow_overlap
)
2846 for (i
= 0; i
< postimage
->nr
; i
++)
2847 img
->line
[applied_pos
+ i
].flag
|= LINE_PATCHED
;
2852 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2853 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2854 * replace the part of "img" with "postimage" text.
2856 static int apply_one_fragment(struct apply_state
*state
,
2857 struct image
*img
, struct fragment
*frag
,
2858 int inaccurate_eof
, unsigned ws_rule
,
2861 int match_beginning
, match_end
;
2862 const char *patch
= frag
->patch
;
2863 int size
= frag
->size
;
2864 char *old
, *oldlines
;
2865 struct strbuf newlines
;
2866 int new_blank_lines_at_end
= 0;
2867 int found_new_blank_lines_at_end
= 0;
2868 int hunk_linenr
= frag
->linenr
;
2869 unsigned long leading
, trailing
;
2870 int pos
, applied_pos
;
2871 struct image preimage
;
2872 struct image postimage
;
2874 memset(&preimage
, 0, sizeof(preimage
));
2875 memset(&postimage
, 0, sizeof(postimage
));
2876 oldlines
= xmalloc(size
);
2877 strbuf_init(&newlines
, size
);
2882 int len
= linelen(patch
, size
);
2884 int added_blank_line
= 0;
2885 int is_blank_context
= 0;
2892 * "plen" is how much of the line we should use for
2893 * the actual patch data. Normally we just remove the
2894 * first character on the line, but if the line is
2895 * followed by "\ No newline", then we also remove the
2896 * last one (which is the newline, of course).
2899 if (len
< size
&& patch
[len
] == '\\')
2902 if (state
->apply_in_reverse
) {
2905 else if (first
== '+')
2911 /* Newer GNU diff, empty context line */
2913 /* ... followed by '\No newline'; nothing */
2916 strbuf_addch(&newlines
, '\n');
2917 add_line_info(&preimage
, "\n", 1, LINE_COMMON
);
2918 add_line_info(&postimage
, "\n", 1, LINE_COMMON
);
2919 is_blank_context
= 1;
2922 if (plen
&& (ws_rule
& WS_BLANK_AT_EOF
) &&
2923 ws_blank_line(patch
+ 1, plen
))
2924 is_blank_context
= 1;
2927 memcpy(old
, patch
+ 1, plen
);
2928 add_line_info(&preimage
, old
, plen
,
2929 (first
== ' ' ? LINE_COMMON
: 0));
2935 /* --no-add does not add new lines */
2936 if (first
== '+' && state
->no_add
)
2939 start
= newlines
.len
;
2941 !state
->whitespace_error
||
2942 state
->ws_error_action
!= correct_ws_error
) {
2943 strbuf_add(&newlines
, patch
+ 1, plen
);
2946 ws_fix_copy(&newlines
, patch
+ 1, plen
, ws_rule
, &state
->applied_after_fixing_ws
);
2948 add_line_info(&postimage
, newlines
.buf
+ start
, newlines
.len
- start
,
2949 (first
== '+' ? 0 : LINE_COMMON
));
2951 (ws_rule
& WS_BLANK_AT_EOF
) &&
2952 ws_blank_line(patch
+ 1, plen
))
2953 added_blank_line
= 1;
2955 case '@': case '\\':
2956 /* Ignore it, we already handled it */
2959 if (state
->apply_verbosity
> verbosity_normal
)
2960 error(_("invalid start of line: '%c'"), first
);
2964 if (added_blank_line
) {
2965 if (!new_blank_lines_at_end
)
2966 found_new_blank_lines_at_end
= hunk_linenr
;
2967 new_blank_lines_at_end
++;
2969 else if (is_blank_context
)
2972 new_blank_lines_at_end
= 0;
2977 if (inaccurate_eof
&&
2978 old
> oldlines
&& old
[-1] == '\n' &&
2979 newlines
.len
> 0 && newlines
.buf
[newlines
.len
- 1] == '\n') {
2981 strbuf_setlen(&newlines
, newlines
.len
- 1);
2982 preimage
.line_allocated
[preimage
.nr
- 1].len
--;
2983 postimage
.line_allocated
[postimage
.nr
- 1].len
--;
2986 leading
= frag
->leading
;
2987 trailing
= frag
->trailing
;
2990 * A hunk to change lines at the beginning would begin with
2992 * but we need to be careful. -U0 that inserts before the second
2993 * line also has this pattern.
2995 * And a hunk to add to an empty file would begin with
2998 * In other words, a hunk that is (frag->oldpos <= 1) with or
2999 * without leading context must match at the beginning.
3001 match_beginning
= (!frag
->oldpos
||
3002 (frag
->oldpos
== 1 && !state
->unidiff_zero
));
3005 * A hunk without trailing lines must match at the end.
3006 * However, we simply cannot tell if a hunk must match end
3007 * from the lack of trailing lines if the patch was generated
3008 * with unidiff without any context.
3010 match_end
= !state
->unidiff_zero
&& !trailing
;
3012 pos
= frag
->newpos
? (frag
->newpos
- 1) : 0;
3013 preimage
.buf
= oldlines
;
3014 preimage
.len
= old
- oldlines
;
3015 postimage
.buf
= newlines
.buf
;
3016 postimage
.len
= newlines
.len
;
3017 preimage
.line
= preimage
.line_allocated
;
3018 postimage
.line
= postimage
.line_allocated
;
3022 applied_pos
= find_pos(state
, img
, &preimage
, &postimage
, pos
,
3023 ws_rule
, match_beginning
, match_end
);
3025 if (applied_pos
>= 0)
3028 /* Am I at my context limits? */
3029 if ((leading
<= state
->p_context
) && (trailing
<= state
->p_context
))
3031 if (match_beginning
|| match_end
) {
3032 match_beginning
= match_end
= 0;
3037 * Reduce the number of context lines; reduce both
3038 * leading and trailing if they are equal otherwise
3039 * just reduce the larger context.
3041 if (leading
>= trailing
) {
3042 remove_first_line(&preimage
);
3043 remove_first_line(&postimage
);
3047 if (trailing
> leading
) {
3048 remove_last_line(&preimage
);
3049 remove_last_line(&postimage
);
3054 if (applied_pos
>= 0) {
3055 if (new_blank_lines_at_end
&&
3056 preimage
.nr
+ applied_pos
>= img
->nr
&&
3057 (ws_rule
& WS_BLANK_AT_EOF
) &&
3058 state
->ws_error_action
!= nowarn_ws_error
) {
3059 record_ws_error(state
, WS_BLANK_AT_EOF
, "+", 1,
3060 found_new_blank_lines_at_end
);
3061 if (state
->ws_error_action
== correct_ws_error
) {
3062 while (new_blank_lines_at_end
--)
3063 remove_last_line(&postimage
);
3066 * We would want to prevent write_out_results()
3067 * from taking place in apply_patch() that follows
3068 * the callchain led us here, which is:
3069 * apply_patch->check_patch_list->check_patch->
3070 * apply_data->apply_fragments->apply_one_fragment
3072 if (state
->ws_error_action
== die_on_ws_error
)
3076 if (state
->apply_verbosity
> verbosity_normal
&& applied_pos
!= pos
) {
3077 int offset
= applied_pos
- pos
;
3078 if (state
->apply_in_reverse
)
3079 offset
= 0 - offset
;
3081 Q_("Hunk #%d succeeded at %d (offset %d line).",
3082 "Hunk #%d succeeded at %d (offset %d lines).",
3084 nth_fragment
, applied_pos
+ 1, offset
);
3088 * Warn if it was necessary to reduce the number
3091 if ((leading
!= frag
->leading
||
3092 trailing
!= frag
->trailing
) && state
->apply_verbosity
> verbosity_silent
)
3093 fprintf_ln(stderr
, _("Context reduced to (%ld/%ld)"
3094 " to apply fragment at %d"),
3095 leading
, trailing
, applied_pos
+1);
3096 update_image(state
, img
, applied_pos
, &preimage
, &postimage
);
3098 if (state
->apply_verbosity
> verbosity_normal
)
3099 error(_("while searching for:\n%.*s"),
3100 (int)(old
- oldlines
), oldlines
);
3105 strbuf_release(&newlines
);
3106 free(preimage
.line_allocated
);
3107 free(postimage
.line_allocated
);
3109 return (applied_pos
< 0);
3112 static int apply_binary_fragment(struct apply_state
*state
,
3114 struct patch
*patch
)
3116 struct fragment
*fragment
= patch
->fragments
;
3121 return error(_("missing binary patch data for '%s'"),
3126 /* Binary patch is irreversible without the optional second hunk */
3127 if (state
->apply_in_reverse
) {
3128 if (!fragment
->next
)
3129 return error(_("cannot reverse-apply a binary patch "
3130 "without the reverse hunk to '%s'"),
3132 ? patch
->new_name
: patch
->old_name
);
3133 fragment
= fragment
->next
;
3135 switch (fragment
->binary_patch_method
) {
3136 case BINARY_DELTA_DEFLATED
:
3137 dst
= patch_delta(img
->buf
, img
->len
, fragment
->patch
,
3138 fragment
->size
, &len
);
3145 case BINARY_LITERAL_DEFLATED
:
3147 img
->len
= fragment
->size
;
3148 img
->buf
= xmemdupz(fragment
->patch
, img
->len
);
3155 * Replace "img" with the result of applying the binary patch.
3156 * The binary patch data itself in patch->fragment is still kept
3157 * but the preimage prepared by the caller in "img" is freed here
3158 * or in the helper function apply_binary_fragment() this calls.
3160 static int apply_binary(struct apply_state
*state
,
3162 struct patch
*patch
)
3164 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3165 struct object_id oid
;
3166 const unsigned hexsz
= the_hash_algo
->hexsz
;
3169 * For safety, we require patch index line to contain
3170 * full hex textual object ID for old and new, at least for now.
3172 if (strlen(patch
->old_oid_prefix
) != hexsz
||
3173 strlen(patch
->new_oid_prefix
) != hexsz
||
3174 get_oid_hex(patch
->old_oid_prefix
, &oid
) ||
3175 get_oid_hex(patch
->new_oid_prefix
, &oid
))
3176 return error(_("cannot apply binary patch to '%s' "
3177 "without full index line"), name
);
3179 if (patch
->old_name
) {
3181 * See if the old one matches what the patch
3184 hash_object_file(the_hash_algo
, img
->buf
, img
->len
, OBJ_BLOB
,
3186 if (strcmp(oid_to_hex(&oid
), patch
->old_oid_prefix
))
3187 return error(_("the patch applies to '%s' (%s), "
3188 "which does not match the "
3189 "current contents."),
3190 name
, oid_to_hex(&oid
));
3193 /* Otherwise, the old one must be empty. */
3195 return error(_("the patch applies to an empty "
3196 "'%s' but it is not empty"), name
);
3199 get_oid_hex(patch
->new_oid_prefix
, &oid
);
3200 if (is_null_oid(&oid
)) {
3202 return 0; /* deletion patch */
3205 if (has_object(the_repository
, &oid
, 0)) {
3206 /* We already have the postimage */
3207 enum object_type type
;
3211 result
= repo_read_object_file(the_repository
, &oid
, &type
,
3214 return error(_("the necessary postimage %s for "
3215 "'%s' cannot be read"),
3216 patch
->new_oid_prefix
, name
);
3222 * We have verified buf matches the preimage;
3223 * apply the patch data to it, which is stored
3224 * in the patch->fragments->{patch,size}.
3226 if (apply_binary_fragment(state
, img
, patch
))
3227 return error(_("binary patch does not apply to '%s'"),
3230 /* verify that the result matches */
3231 hash_object_file(the_hash_algo
, img
->buf
, img
->len
, OBJ_BLOB
,
3233 if (strcmp(oid_to_hex(&oid
), patch
->new_oid_prefix
))
3234 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3235 name
, patch
->new_oid_prefix
, oid_to_hex(&oid
));
3241 static int apply_fragments(struct apply_state
*state
, struct image
*img
, struct patch
*patch
)
3243 struct fragment
*frag
= patch
->fragments
;
3244 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3245 unsigned ws_rule
= patch
->ws_rule
;
3246 unsigned inaccurate_eof
= patch
->inaccurate_eof
;
3249 if (patch
->is_binary
)
3250 return apply_binary(state
, img
, patch
);
3254 if (apply_one_fragment(state
, img
, frag
, inaccurate_eof
, ws_rule
, nth
)) {
3255 error(_("patch failed: %s:%ld"), name
, frag
->oldpos
);
3256 if (!state
->apply_with_reject
)
3265 static int read_blob_object(struct strbuf
*buf
, const struct object_id
*oid
, unsigned mode
)
3267 if (S_ISGITLINK(mode
)) {
3268 strbuf_grow(buf
, 100);
3269 strbuf_addf(buf
, "Subproject commit %s\n", oid_to_hex(oid
));
3271 enum object_type type
;
3275 result
= repo_read_object_file(the_repository
, oid
, &type
,
3279 /* XXX read_sha1_file NUL-terminates */
3280 strbuf_attach(buf
, result
, sz
, sz
+ 1);
3285 static int read_file_or_gitlink(const struct cache_entry
*ce
, struct strbuf
*buf
)
3289 return read_blob_object(buf
, &ce
->oid
, ce
->ce_mode
);
3292 static struct patch
*in_fn_table(struct apply_state
*state
, const char *name
)
3294 struct string_list_item
*item
;
3299 item
= string_list_lookup(&state
->fn_table
, name
);
3301 return (struct patch
*)item
->util
;
3307 * item->util in the filename table records the status of the path.
3308 * Usually it points at a patch (whose result records the contents
3309 * of it after applying it), but it could be PATH_WAS_DELETED for a
3310 * path that a previously applied patch has already removed, or
3311 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3313 * The latter is needed to deal with a case where two paths A and B
3314 * are swapped by first renaming A to B and then renaming B to A;
3315 * moving A to B should not be prevented due to presence of B as we
3316 * will remove it in a later patch.
3318 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3319 #define PATH_WAS_DELETED ((struct patch *) -1)
3321 static int to_be_deleted(struct patch
*patch
)
3323 return patch
== PATH_TO_BE_DELETED
;
3326 static int was_deleted(struct patch
*patch
)
3328 return patch
== PATH_WAS_DELETED
;
3331 static void add_to_fn_table(struct apply_state
*state
, struct patch
*patch
)
3333 struct string_list_item
*item
;
3336 * Always add new_name unless patch is a deletion
3337 * This should cover the cases for normal diffs,
3338 * file creations and copies
3340 if (patch
->new_name
) {
3341 item
= string_list_insert(&state
->fn_table
, patch
->new_name
);
3346 * store a failure on rename/deletion cases because
3347 * later chunks shouldn't patch old names
3349 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3350 item
= string_list_insert(&state
->fn_table
, patch
->old_name
);
3351 item
->util
= PATH_WAS_DELETED
;
3355 static void prepare_fn_table(struct apply_state
*state
, struct patch
*patch
)
3358 * store information about incoming file deletion
3361 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3362 struct string_list_item
*item
;
3363 item
= string_list_insert(&state
->fn_table
, patch
->old_name
);
3364 item
->util
= PATH_TO_BE_DELETED
;
3366 patch
= patch
->next
;
3370 static int checkout_target(struct index_state
*istate
,
3371 struct cache_entry
*ce
, struct stat
*st
)
3373 struct checkout costate
= CHECKOUT_INIT
;
3375 costate
.refresh_cache
= 1;
3376 costate
.istate
= istate
;
3377 if (checkout_entry(ce
, &costate
, NULL
, NULL
) ||
3378 lstat(ce
->name
, st
))
3379 return error(_("cannot checkout %s"), ce
->name
);
3383 static struct patch
*previous_patch(struct apply_state
*state
,
3384 struct patch
*patch
,
3387 struct patch
*previous
;
3390 if (patch
->is_copy
|| patch
->is_rename
)
3391 return NULL
; /* "git" patches do not depend on the order */
3393 previous
= in_fn_table(state
, patch
->old_name
);
3397 if (to_be_deleted(previous
))
3398 return NULL
; /* the deletion hasn't happened yet */
3400 if (was_deleted(previous
))
3406 static int verify_index_match(struct apply_state
*state
,
3407 const struct cache_entry
*ce
,
3410 if (S_ISGITLINK(ce
->ce_mode
)) {
3411 if (!S_ISDIR(st
->st_mode
))
3415 return ie_match_stat(state
->repo
->index
, ce
, st
,
3416 CE_MATCH_IGNORE_VALID
| CE_MATCH_IGNORE_SKIP_WORKTREE
);
3419 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3421 static int load_patch_target(struct apply_state
*state
,
3423 const struct cache_entry
*ce
,
3425 struct patch
*patch
,
3427 unsigned expected_mode
)
3429 if (state
->cached
|| state
->check_index
) {
3430 if (read_file_or_gitlink(ce
, buf
))
3431 return error(_("failed to read %s"), name
);
3433 if (S_ISGITLINK(expected_mode
)) {
3435 return read_file_or_gitlink(ce
, buf
);
3437 return SUBMODULE_PATCH_WITHOUT_INDEX
;
3438 } else if (has_symlink_leading_path(name
, strlen(name
))) {
3439 return error(_("reading from '%s' beyond a symbolic link"), name
);
3441 if (read_old_data(st
, patch
, name
, buf
))
3442 return error(_("failed to read %s"), name
);
3449 * We are about to apply "patch"; populate the "image" with the
3450 * current version we have, from the working tree or from the index,
3451 * depending on the situation e.g. --cached/--index. If we are
3452 * applying a non-git patch that incrementally updates the tree,
3453 * we read from the result of a previous diff.
3455 static int load_preimage(struct apply_state
*state
,
3456 struct image
*image
,
3457 struct patch
*patch
, struct stat
*st
,
3458 const struct cache_entry
*ce
)
3460 struct strbuf buf
= STRBUF_INIT
;
3463 struct patch
*previous
;
3466 previous
= previous_patch(state
, patch
, &status
);
3468 return error(_("path %s has been renamed/deleted"),
3471 /* We have a patched copy in memory; use that. */
3472 strbuf_add(&buf
, previous
->result
, previous
->resultsize
);
3474 status
= load_patch_target(state
, &buf
, ce
, st
, patch
,
3475 patch
->old_name
, patch
->old_mode
);
3478 else if (status
== SUBMODULE_PATCH_WITHOUT_INDEX
) {
3480 * There is no way to apply subproject
3481 * patch without looking at the index.
3482 * NEEDSWORK: shouldn't this be flagged
3485 free_fragment_list(patch
->fragments
);
3486 patch
->fragments
= NULL
;
3487 } else if (status
) {
3488 return error(_("failed to read %s"), patch
->old_name
);
3492 img
= strbuf_detach(&buf
, &len
);
3493 prepare_image(image
, img
, len
, !patch
->is_binary
);
3497 static int resolve_to(struct image
*image
, const struct object_id
*result_id
)
3500 enum object_type type
;
3504 image
->buf
= repo_read_object_file(the_repository
, result_id
, &type
,
3506 if (!image
->buf
|| type
!= OBJ_BLOB
)
3507 die("unable to read blob object %s", oid_to_hex(result_id
));
3513 static int three_way_merge(struct apply_state
*state
,
3514 struct image
*image
,
3516 const struct object_id
*base
,
3517 const struct object_id
*ours
,
3518 const struct object_id
*theirs
)
3520 mmfile_t base_file
, our_file
, their_file
;
3521 mmbuffer_t result
= { NULL
};
3522 enum ll_merge_result status
;
3524 /* resolve trivial cases first */
3525 if (oideq(base
, ours
))
3526 return resolve_to(image
, theirs
);
3527 else if (oideq(base
, theirs
) || oideq(ours
, theirs
))
3528 return resolve_to(image
, ours
);
3530 read_mmblob(&base_file
, base
);
3531 read_mmblob(&our_file
, ours
);
3532 read_mmblob(&their_file
, theirs
);
3533 status
= ll_merge(&result
, path
,
3536 &their_file
, "theirs",
3539 if (status
== LL_MERGE_BINARY_CONFLICT
)
3540 warning("Cannot merge binary files: %s (%s vs. %s)",
3541 path
, "ours", "theirs");
3542 free(base_file
.ptr
);
3544 free(their_file
.ptr
);
3545 if (status
< 0 || !result
.ptr
) {
3550 image
->buf
= result
.ptr
;
3551 image
->len
= result
.size
;
3557 * When directly falling back to add/add three-way merge, we read from
3558 * the current contents of the new_name. In no cases other than that
3559 * this function will be called.
3561 static int load_current(struct apply_state
*state
,
3562 struct image
*image
,
3563 struct patch
*patch
)
3565 struct strbuf buf
= STRBUF_INIT
;
3570 struct cache_entry
*ce
;
3571 char *name
= patch
->new_name
;
3572 unsigned mode
= patch
->new_mode
;
3575 BUG("patch to %s is not a creation", patch
->old_name
);
3577 pos
= index_name_pos(state
->repo
->index
, name
, strlen(name
));
3579 return error(_("%s: does not exist in index"), name
);
3580 ce
= state
->repo
->index
->cache
[pos
];
3581 if (lstat(name
, &st
)) {
3582 if (errno
!= ENOENT
)
3583 return error_errno("%s", name
);
3584 if (checkout_target(state
->repo
->index
, ce
, &st
))
3587 if (verify_index_match(state
, ce
, &st
))
3588 return error(_("%s: does not match index"), name
);
3590 status
= load_patch_target(state
, &buf
, ce
, &st
, patch
, name
, mode
);
3595 img
= strbuf_detach(&buf
, &len
);
3596 prepare_image(image
, img
, len
, !patch
->is_binary
);
3600 static int try_threeway(struct apply_state
*state
,
3601 struct image
*image
,
3602 struct patch
*patch
,
3604 const struct cache_entry
*ce
)
3606 struct object_id pre_oid
, post_oid
, our_oid
;
3607 struct strbuf buf
= STRBUF_INIT
;
3611 struct image tmp_image
;
3613 /* No point falling back to 3-way merge in these cases */
3614 if (patch
->is_delete
||
3615 S_ISGITLINK(patch
->old_mode
) || S_ISGITLINK(patch
->new_mode
) ||
3616 (patch
->is_new
&& !patch
->direct_to_threeway
) ||
3617 (patch
->is_rename
&& !patch
->lines_added
&& !patch
->lines_deleted
))
3620 /* Preimage the patch was prepared for */
3622 write_object_file("", 0, OBJ_BLOB
, &pre_oid
);
3623 else if (repo_get_oid(the_repository
, patch
->old_oid_prefix
, &pre_oid
) ||
3624 read_blob_object(&buf
, &pre_oid
, patch
->old_mode
))
3625 return error(_("repository lacks the necessary blob to perform 3-way merge."));
3627 if (state
->apply_verbosity
> verbosity_silent
&& patch
->direct_to_threeway
)
3628 fprintf(stderr
, _("Performing three-way merge...\n"));
3630 img
= strbuf_detach(&buf
, &len
);
3631 prepare_image(&tmp_image
, img
, len
, 1);
3632 /* Apply the patch to get the post image */
3633 if (apply_fragments(state
, &tmp_image
, patch
) < 0) {
3634 clear_image(&tmp_image
);
3637 /* post_oid is theirs */
3638 write_object_file(tmp_image
.buf
, tmp_image
.len
, OBJ_BLOB
, &post_oid
);
3639 clear_image(&tmp_image
);
3641 /* our_oid is ours */
3642 if (patch
->is_new
) {
3643 if (load_current(state
, &tmp_image
, patch
))
3644 return error(_("cannot read the current contents of '%s'"),
3647 if (load_preimage(state
, &tmp_image
, patch
, st
, ce
))
3648 return error(_("cannot read the current contents of '%s'"),
3651 write_object_file(tmp_image
.buf
, tmp_image
.len
, OBJ_BLOB
, &our_oid
);
3652 clear_image(&tmp_image
);
3654 /* in-core three-way merge between post and our using pre as base */
3655 status
= three_way_merge(state
, image
, patch
->new_name
,
3656 &pre_oid
, &our_oid
, &post_oid
);
3658 if (state
->apply_verbosity
> verbosity_silent
)
3660 _("Failed to perform three-way merge...\n"));
3665 patch
->conflicted_threeway
= 1;
3667 oidclr(&patch
->threeway_stage
[0]);
3669 oidcpy(&patch
->threeway_stage
[0], &pre_oid
);
3670 oidcpy(&patch
->threeway_stage
[1], &our_oid
);
3671 oidcpy(&patch
->threeway_stage
[2], &post_oid
);
3672 if (state
->apply_verbosity
> verbosity_silent
)
3674 _("Applied patch to '%s' with conflicts.\n"),
3677 if (state
->apply_verbosity
> verbosity_silent
)
3679 _("Applied patch to '%s' cleanly.\n"),
3685 static int apply_data(struct apply_state
*state
, struct patch
*patch
,
3686 struct stat
*st
, const struct cache_entry
*ce
)
3690 if (load_preimage(state
, &image
, patch
, st
, ce
) < 0)
3693 if (!state
->threeway
|| try_threeway(state
, &image
, patch
, st
, ce
) < 0) {
3694 if (state
->apply_verbosity
> verbosity_silent
&&
3695 state
->threeway
&& !patch
->direct_to_threeway
)
3696 fprintf(stderr
, _("Falling back to direct application...\n"));
3698 /* Note: with --reject, apply_fragments() returns 0 */
3699 if (patch
->direct_to_threeway
|| apply_fragments(state
, &image
, patch
) < 0)
3702 patch
->result
= image
.buf
;
3703 patch
->resultsize
= image
.len
;
3704 add_to_fn_table(state
, patch
);
3705 free(image
.line_allocated
);
3707 if (0 < patch
->is_delete
&& patch
->resultsize
)
3708 return error(_("removal patch leaves file contents"));
3714 * If "patch" that we are looking at modifies or deletes what we have,
3715 * we would want it not to lose any local modification we have, either
3716 * in the working tree or in the index.
3718 * This also decides if a non-git patch is a creation patch or a
3719 * modification to an existing empty file. We do not check the state
3720 * of the current tree for a creation patch in this function; the caller
3721 * check_patch() separately makes sure (and errors out otherwise) that
3722 * the path the patch creates does not exist in the current tree.
3724 static int check_preimage(struct apply_state
*state
,
3725 struct patch
*patch
,
3726 struct cache_entry
**ce
,
3729 const char *old_name
= patch
->old_name
;
3730 struct patch
*previous
= NULL
;
3731 int stat_ret
= 0, status
;
3732 unsigned st_mode
= 0;
3737 assert(patch
->is_new
<= 0);
3738 previous
= previous_patch(state
, patch
, &status
);
3741 return error(_("path %s has been renamed/deleted"), old_name
);
3743 st_mode
= previous
->new_mode
;
3744 } else if (!state
->cached
) {
3745 stat_ret
= lstat(old_name
, st
);
3746 if (stat_ret
&& errno
!= ENOENT
)
3747 return error_errno("%s", old_name
);
3750 if (state
->check_index
&& !previous
) {
3751 int pos
= index_name_pos(state
->repo
->index
, old_name
,
3754 if (patch
->is_new
< 0)
3756 return error(_("%s: does not exist in index"), old_name
);
3758 *ce
= state
->repo
->index
->cache
[pos
];
3760 if (checkout_target(state
->repo
->index
, *ce
, st
))
3763 if (!state
->cached
&& verify_index_match(state
, *ce
, st
))
3764 return error(_("%s: does not match index"), old_name
);
3766 st_mode
= (*ce
)->ce_mode
;
3767 } else if (stat_ret
< 0) {
3768 if (patch
->is_new
< 0)
3770 return error_errno("%s", old_name
);
3773 if (!state
->cached
&& !previous
)
3774 st_mode
= ce_mode_from_stat(*ce
, st
->st_mode
);
3776 if (patch
->is_new
< 0)
3778 if (!patch
->old_mode
)
3779 patch
->old_mode
= st_mode
;
3780 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
3781 return error(_("%s: wrong type"), old_name
);
3782 if (st_mode
!= patch
->old_mode
)
3783 warning(_("%s has type %o, expected %o"),
3784 old_name
, st_mode
, patch
->old_mode
);
3785 if (!patch
->new_mode
&& !patch
->is_delete
)
3786 patch
->new_mode
= st_mode
;
3791 patch
->is_delete
= 0;
3792 FREE_AND_NULL(patch
->old_name
);
3797 #define EXISTS_IN_INDEX 1
3798 #define EXISTS_IN_WORKTREE 2
3799 #define EXISTS_IN_INDEX_AS_ITA 3
3801 static int check_to_create(struct apply_state
*state
,
3802 const char *new_name
,
3807 if (state
->check_index
&& (!ok_if_exists
|| !state
->cached
)) {
3810 pos
= index_name_pos(state
->repo
->index
, new_name
, strlen(new_name
));
3812 struct cache_entry
*ce
= state
->repo
->index
->cache
[pos
];
3814 /* allow ITA, as they do not yet exist in the index */
3815 if (!ok_if_exists
&& !(ce
->ce_flags
& CE_INTENT_TO_ADD
))
3816 return EXISTS_IN_INDEX
;
3818 /* ITA entries can never match working tree files */
3819 if (!state
->cached
&& (ce
->ce_flags
& CE_INTENT_TO_ADD
))
3820 return EXISTS_IN_INDEX_AS_ITA
;
3827 if (!lstat(new_name
, &nst
)) {
3828 if (S_ISDIR(nst
.st_mode
) || ok_if_exists
)
3831 * A leading component of new_name might be a symlink
3832 * that is going to be removed with this patch, but
3833 * still pointing at somewhere that has the path.
3834 * In such a case, path "new_name" does not exist as
3835 * far as git is concerned.
3837 if (has_symlink_leading_path(new_name
, strlen(new_name
)))
3840 return EXISTS_IN_WORKTREE
;
3841 } else if (!is_missing_file_error(errno
)) {
3842 return error_errno("%s", new_name
);
3847 static void prepare_symlink_changes(struct apply_state
*state
, struct patch
*patch
)
3849 for ( ; patch
; patch
= patch
->next
) {
3850 if ((patch
->old_name
&& S_ISLNK(patch
->old_mode
)) &&
3851 (patch
->is_rename
|| patch
->is_delete
))
3852 /* the symlink at patch->old_name is removed */
3853 strset_add(&state
->removed_symlinks
, patch
->old_name
);
3855 if (patch
->new_name
&& S_ISLNK(patch
->new_mode
))
3856 /* the symlink at patch->new_name is created or remains */
3857 strset_add(&state
->kept_symlinks
, patch
->new_name
);
3861 static int path_is_beyond_symlink_1(struct apply_state
*state
, struct strbuf
*name
)
3864 while (--name
->len
&& name
->buf
[name
->len
] != '/')
3865 ; /* scan backwards */
3868 name
->buf
[name
->len
] = '\0';
3869 if (strset_contains(&state
->kept_symlinks
, name
->buf
))
3871 if (strset_contains(&state
->removed_symlinks
, name
->buf
))
3873 * This cannot be "return 0", because we may
3874 * see a new one created at a higher level.
3878 /* otherwise, check the preimage */
3879 if (state
->check_index
) {
3880 struct cache_entry
*ce
;
3882 ce
= index_file_exists(state
->repo
->index
, name
->buf
,
3883 name
->len
, ignore_case
);
3884 if (ce
&& S_ISLNK(ce
->ce_mode
))
3888 if (!lstat(name
->buf
, &st
) && S_ISLNK(st
.st_mode
))
3895 static int path_is_beyond_symlink(struct apply_state
*state
, const char *name_
)
3898 struct strbuf name
= STRBUF_INIT
;
3900 assert(*name_
!= '\0');
3901 strbuf_addstr(&name
, name_
);
3902 ret
= path_is_beyond_symlink_1(state
, &name
);
3903 strbuf_release(&name
);
3908 static int check_unsafe_path(struct patch
*patch
)
3910 const char *old_name
= NULL
;
3911 const char *new_name
= NULL
;
3912 if (patch
->is_delete
)
3913 old_name
= patch
->old_name
;
3914 else if (!patch
->is_new
&& !patch
->is_copy
)
3915 old_name
= patch
->old_name
;
3916 if (!patch
->is_delete
)
3917 new_name
= patch
->new_name
;
3919 if (old_name
&& !verify_path(old_name
, patch
->old_mode
))
3920 return error(_("invalid path '%s'"), old_name
);
3921 if (new_name
&& !verify_path(new_name
, patch
->new_mode
))
3922 return error(_("invalid path '%s'"), new_name
);
3927 * Check and apply the patch in-core; leave the result in patch->result
3928 * for the caller to write it out to the final destination.
3930 static int check_patch(struct apply_state
*state
, struct patch
*patch
)
3933 const char *old_name
= patch
->old_name
;
3934 const char *new_name
= patch
->new_name
;
3935 const char *name
= old_name
? old_name
: new_name
;
3936 struct cache_entry
*ce
= NULL
;
3937 struct patch
*tpatch
;
3941 patch
->rejected
= 1; /* we will drop this after we succeed */
3943 status
= check_preimage(state
, patch
, &ce
, &st
);
3946 old_name
= patch
->old_name
;
3949 * A type-change diff is always split into a patch to delete
3950 * old, immediately followed by a patch to create new (see
3951 * diff.c::run_diff()); in such a case it is Ok that the entry
3952 * to be deleted by the previous patch is still in the working
3953 * tree and in the index.
3955 * A patch to swap-rename between A and B would first rename A
3956 * to B and then rename B to A. While applying the first one,
3957 * the presence of B should not stop A from getting renamed to
3958 * B; ask to_be_deleted() about the later rename. Removal of
3959 * B and rename from A to B is handled the same way by asking
3962 if ((tpatch
= in_fn_table(state
, new_name
)) &&
3963 (was_deleted(tpatch
) || to_be_deleted(tpatch
)))
3969 ((0 < patch
->is_new
) || patch
->is_rename
|| patch
->is_copy
)) {
3970 int err
= check_to_create(state
, new_name
, ok_if_exists
);
3972 if (err
&& state
->threeway
) {
3973 patch
->direct_to_threeway
= 1;
3974 } else switch (err
) {
3977 case EXISTS_IN_INDEX
:
3978 return error(_("%s: already exists in index"), new_name
);
3979 case EXISTS_IN_INDEX_AS_ITA
:
3980 return error(_("%s: does not match index"), new_name
);
3981 case EXISTS_IN_WORKTREE
:
3982 return error(_("%s: already exists in working directory"),
3988 if (!patch
->new_mode
) {
3989 if (0 < patch
->is_new
)
3990 patch
->new_mode
= S_IFREG
| 0644;
3992 patch
->new_mode
= patch
->old_mode
;
3996 if (new_name
&& old_name
) {
3997 int same
= !strcmp(old_name
, new_name
);
3998 if (!patch
->new_mode
)
3999 patch
->new_mode
= patch
->old_mode
;
4000 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
) {
4002 return error(_("new mode (%o) of %s does not "
4003 "match old mode (%o)"),
4004 patch
->new_mode
, new_name
,
4007 return error(_("new mode (%o) of %s does not "
4008 "match old mode (%o) of %s"),
4009 patch
->new_mode
, new_name
,
4010 patch
->old_mode
, old_name
);
4014 if (!state
->unsafe_paths
&& check_unsafe_path(patch
))
4018 * An attempt to read from or delete a path that is beyond a
4019 * symbolic link will be prevented by load_patch_target() that
4020 * is called at the beginning of apply_data() so we do not
4021 * have to worry about a patch marked with "is_delete" bit
4022 * here. We however need to make sure that the patch result
4023 * is not deposited to a path that is beyond a symbolic link
4026 if (!patch
->is_delete
&& path_is_beyond_symlink(state
, patch
->new_name
))
4027 return error(_("affected file '%s' is beyond a symbolic link"),
4030 if (apply_data(state
, patch
, &st
, ce
) < 0)
4031 return error(_("%s: patch does not apply"), name
);
4032 patch
->rejected
= 0;
4036 static int check_patch_list(struct apply_state
*state
, struct patch
*patch
)
4040 prepare_symlink_changes(state
, patch
);
4041 prepare_fn_table(state
, patch
);
4044 if (state
->apply_verbosity
> verbosity_normal
)
4045 say_patch_name(stderr
,
4046 _("Checking patch %s..."), patch
);
4047 res
= check_patch(state
, patch
);
4051 patch
= patch
->next
;
4056 static int read_apply_cache(struct apply_state
*state
)
4058 if (state
->index_file
)
4059 return read_index_from(state
->repo
->index
, state
->index_file
,
4062 return repo_read_index(state
->repo
);
4065 /* This function tries to read the object name from the current index */
4066 static int get_current_oid(struct apply_state
*state
, const char *path
,
4067 struct object_id
*oid
)
4071 if (read_apply_cache(state
) < 0)
4073 pos
= index_name_pos(state
->repo
->index
, path
, strlen(path
));
4076 oidcpy(oid
, &state
->repo
->index
->cache
[pos
]->oid
);
4080 static int preimage_oid_in_gitlink_patch(struct patch
*p
, struct object_id
*oid
)
4083 * A usable gitlink patch has only one fragment (hunk) that looks like:
4085 * -Subproject commit <old sha1>
4086 * +Subproject commit <new sha1>
4089 * -Subproject commit <old sha1>
4090 * for a removal patch.
4092 struct fragment
*hunk
= p
->fragments
;
4093 static const char heading
[] = "-Subproject commit ";
4096 if (/* does the patch have only one hunk? */
4097 hunk
&& !hunk
->next
&&
4098 /* is its preimage one line? */
4099 hunk
->oldpos
== 1 && hunk
->oldlines
== 1 &&
4100 /* does preimage begin with the heading? */
4101 (preimage
= memchr(hunk
->patch
, '\n', hunk
->size
)) != NULL
&&
4102 starts_with(++preimage
, heading
) &&
4103 /* does it record full SHA-1? */
4104 !get_oid_hex(preimage
+ sizeof(heading
) - 1, oid
) &&
4105 preimage
[sizeof(heading
) + the_hash_algo
->hexsz
- 1] == '\n' &&
4106 /* does the abbreviated name on the index line agree with it? */
4107 starts_with(preimage
+ sizeof(heading
) - 1, p
->old_oid_prefix
))
4108 return 0; /* it all looks fine */
4110 /* we may have full object name on the index line */
4111 return get_oid_hex(p
->old_oid_prefix
, oid
);
4114 /* Build an index that contains just the files needed for a 3way merge */
4115 static int build_fake_ancestor(struct apply_state
*state
, struct patch
*list
)
4117 struct patch
*patch
;
4118 struct index_state result
= INDEX_STATE_INIT(state
->repo
);
4119 struct lock_file lock
= LOCK_INIT
;
4122 /* Once we start supporting the reverse patch, it may be
4123 * worth showing the new sha1 prefix, but until then...
4125 for (patch
= list
; patch
; patch
= patch
->next
) {
4126 struct object_id oid
;
4127 struct cache_entry
*ce
;
4130 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
4131 if (0 < patch
->is_new
)
4134 if (S_ISGITLINK(patch
->old_mode
)) {
4135 if (!preimage_oid_in_gitlink_patch(patch
, &oid
))
4136 ; /* ok, the textual part looks sane */
4138 return error(_("sha1 information is lacking or "
4139 "useless for submodule %s"), name
);
4140 } else if (!repo_get_oid_blob(the_repository
, patch
->old_oid_prefix
, &oid
)) {
4142 } else if (!patch
->lines_added
&& !patch
->lines_deleted
) {
4143 /* mode-only change: update the current */
4144 if (get_current_oid(state
, patch
->old_name
, &oid
))
4145 return error(_("mode change for %s, which is not "
4146 "in current HEAD"), name
);
4148 return error(_("sha1 information is lacking or useless "
4151 ce
= make_cache_entry(&result
, patch
->old_mode
, &oid
, name
, 0, 0);
4153 return error(_("make_cache_entry failed for path '%s'"),
4155 if (add_index_entry(&result
, ce
, ADD_CACHE_OK_TO_ADD
)) {
4156 discard_cache_entry(ce
);
4157 return error(_("could not add %s to temporary index"),
4162 hold_lock_file_for_update(&lock
, state
->fake_ancestor
, LOCK_DIE_ON_ERROR
);
4163 res
= write_locked_index(&result
, &lock
, COMMIT_LOCK
);
4164 discard_index(&result
);
4167 return error(_("could not write temporary index to %s"),
4168 state
->fake_ancestor
);
4173 static void stat_patch_list(struct apply_state
*state
, struct patch
*patch
)
4175 int files
, adds
, dels
;
4177 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
4179 adds
+= patch
->lines_added
;
4180 dels
+= patch
->lines_deleted
;
4181 show_stats(state
, patch
);
4184 print_stat_summary(stdout
, files
, adds
, dels
);
4187 static void numstat_patch_list(struct apply_state
*state
,
4188 struct patch
*patch
)
4190 for ( ; patch
; patch
= patch
->next
) {
4192 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
4193 if (patch
->is_binary
)
4196 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
4197 write_name_quoted(name
, stdout
, state
->line_termination
);
4201 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
4204 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
4206 printf(" %s %s\n", newdelete
, name
);
4209 static void show_mode_change(struct patch
*p
, int show_name
)
4211 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
4213 printf(" mode change %06o => %06o %s\n",
4214 p
->old_mode
, p
->new_mode
, p
->new_name
);
4216 printf(" mode change %06o => %06o\n",
4217 p
->old_mode
, p
->new_mode
);
4221 static void show_rename_copy(struct patch
*p
)
4223 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
4224 const char *old_name
, *new_name
;
4226 /* Find common prefix */
4227 old_name
= p
->old_name
;
4228 new_name
= p
->new_name
;
4230 const char *slash_old
, *slash_new
;
4231 slash_old
= strchr(old_name
, '/');
4232 slash_new
= strchr(new_name
, '/');
4235 slash_old
- old_name
!= slash_new
- new_name
||
4236 memcmp(old_name
, new_name
, slash_new
- new_name
))
4238 old_name
= slash_old
+ 1;
4239 new_name
= slash_new
+ 1;
4241 /* p->old_name through old_name is the common prefix, and old_name and
4242 * new_name through the end of names are renames
4244 if (old_name
!= p
->old_name
)
4245 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
4246 (int)(old_name
- p
->old_name
), p
->old_name
,
4247 old_name
, new_name
, p
->score
);
4249 printf(" %s %s => %s (%d%%)\n", renamecopy
,
4250 p
->old_name
, p
->new_name
, p
->score
);
4251 show_mode_change(p
, 0);
4254 static void summary_patch_list(struct patch
*patch
)
4258 for (p
= patch
; p
; p
= p
->next
) {
4260 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
4261 else if (p
->is_delete
)
4262 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
4264 if (p
->is_rename
|| p
->is_copy
)
4265 show_rename_copy(p
);
4268 printf(" rewrite %s (%d%%)\n",
4269 p
->new_name
, p
->score
);
4270 show_mode_change(p
, 0);
4273 show_mode_change(p
, 1);
4279 static void patch_stats(struct apply_state
*state
, struct patch
*patch
)
4281 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
4283 if (lines
> state
->max_change
)
4284 state
->max_change
= lines
;
4285 if (patch
->old_name
) {
4286 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
4288 len
= strlen(patch
->old_name
);
4289 if (len
> state
->max_len
)
4290 state
->max_len
= len
;
4292 if (patch
->new_name
) {
4293 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
4295 len
= strlen(patch
->new_name
);
4296 if (len
> state
->max_len
)
4297 state
->max_len
= len
;
4301 static int remove_file(struct apply_state
*state
, struct patch
*patch
, int rmdir_empty
)
4303 if (state
->update_index
&& !state
->ita_only
) {
4304 if (remove_file_from_index(state
->repo
->index
, patch
->old_name
) < 0)
4305 return error(_("unable to remove %s from index"), patch
->old_name
);
4307 if (!state
->cached
) {
4308 if (!remove_or_warn(patch
->old_mode
, patch
->old_name
) && rmdir_empty
) {
4309 remove_path(patch
->old_name
);
4315 static int add_index_file(struct apply_state
*state
,
4322 struct cache_entry
*ce
;
4323 int namelen
= strlen(path
);
4325 ce
= make_empty_cache_entry(state
->repo
->index
, namelen
);
4326 memcpy(ce
->name
, path
, namelen
);
4327 ce
->ce_mode
= create_ce_mode(mode
);
4328 ce
->ce_flags
= create_ce_flags(0);
4329 ce
->ce_namelen
= namelen
;
4330 if (state
->ita_only
) {
4331 ce
->ce_flags
|= CE_INTENT_TO_ADD
;
4332 set_object_name_for_intent_to_add_entry(ce
);
4333 } else if (S_ISGITLINK(mode
)) {
4336 if (!skip_prefix(buf
, "Subproject commit ", &s
) ||
4337 get_oid_hex(s
, &ce
->oid
)) {
4338 discard_cache_entry(ce
);
4339 return error(_("corrupt patch for submodule %s"), path
);
4342 if (!state
->cached
) {
4343 if (lstat(path
, &st
) < 0) {
4344 discard_cache_entry(ce
);
4345 return error_errno(_("unable to stat newly "
4346 "created file '%s'"),
4349 fill_stat_cache_info(state
->repo
->index
, ce
, &st
);
4351 if (write_object_file(buf
, size
, OBJ_BLOB
, &ce
->oid
) < 0) {
4352 discard_cache_entry(ce
);
4353 return error(_("unable to create backing store "
4354 "for newly created file %s"), path
);
4357 if (add_index_entry(state
->repo
->index
, ce
, ADD_CACHE_OK_TO_ADD
) < 0) {
4358 discard_cache_entry(ce
);
4359 return error(_("unable to add cache entry for %s"), path
);
4367 * -1 if an unrecoverable error happened
4368 * 0 if everything went well
4369 * 1 if a recoverable error happened
4371 static int try_create_file(struct apply_state
*state
, const char *path
,
4372 unsigned int mode
, const char *buf
,
4376 struct strbuf nbuf
= STRBUF_INIT
;
4378 if (S_ISGITLINK(mode
)) {
4380 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
))
4382 return !!mkdir(path
, 0777);
4385 if (has_symlinks
&& S_ISLNK(mode
))
4386 /* Although buf:size is counted string, it also is NUL
4389 return !!symlink(buf
, path
);
4391 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
4395 if (convert_to_working_tree(state
->repo
->index
, path
, buf
, size
, &nbuf
, NULL
)) {
4400 res
= write_in_full(fd
, buf
, size
) < 0;
4402 error_errno(_("failed to write to '%s'"), path
);
4403 strbuf_release(&nbuf
);
4405 if (close(fd
) < 0 && !res
)
4406 return error_errno(_("closing file '%s'"), path
);
4408 return res
? -1 : 0;
4412 * We optimistically assume that the directories exist,
4413 * which is true 99% of the time anyway. If they don't,
4414 * we create them and try again.
4420 static int create_one_file(struct apply_state
*state
,
4432 * We already try to detect whether files are beyond a symlink in our
4433 * up-front checks. But in the case where symlinks are created by any
4434 * of the intermediate hunks it can happen that our up-front checks
4435 * didn't yet see the symlink, but at the point of arriving here there
4436 * in fact is one. We thus repeat the check for symlinks here.
4438 * Note that this does not make the up-front check obsolete as the
4439 * failure mode is different:
4441 * - The up-front checks cause us to abort before we have written
4442 * anything into the working directory. So when we exit this way the
4443 * working directory remains clean.
4445 * - The checks here happen in the middle of the action where we have
4446 * already started to apply the patch. The end result will be a dirty
4447 * working directory.
4449 * Ideally, we should update the up-front checks to catch what would
4450 * happen when we apply the patch before we damage the working tree.
4451 * We have all the information necessary to do so. But for now, as a
4452 * part of embargoed security work, having this check would serve as a
4453 * reasonable first step.
4455 if (path_is_beyond_symlink(state
, path
))
4456 return error(_("affected file '%s' is beyond a symbolic link"), path
);
4458 res
= try_create_file(state
, path
, mode
, buf
, size
);
4464 if (errno
== ENOENT
) {
4465 if (safe_create_leading_directories_no_share(path
))
4467 res
= try_create_file(state
, path
, mode
, buf
, size
);
4474 if (errno
== EEXIST
|| errno
== EACCES
) {
4475 /* We may be trying to create a file where a directory
4479 if (!lstat(path
, &st
) && (!S_ISDIR(st
.st_mode
) || !rmdir(path
)))
4483 if (errno
== EEXIST
) {
4484 unsigned int nr
= getpid();
4487 char newpath
[PATH_MAX
];
4488 mksnpath(newpath
, sizeof(newpath
), "%s~%u", path
, nr
);
4489 res
= try_create_file(state
, newpath
, mode
, buf
, size
);
4493 if (!rename(newpath
, path
))
4495 unlink_or_warn(newpath
);
4498 if (errno
!= EEXIST
)
4503 return error_errno(_("unable to write file '%s' mode %o"),
4507 static int add_conflicted_stages_file(struct apply_state
*state
,
4508 struct patch
*patch
)
4512 struct cache_entry
*ce
;
4514 if (!state
->update_index
)
4516 namelen
= strlen(patch
->new_name
);
4517 mode
= patch
->new_mode
? patch
->new_mode
: (S_IFREG
| 0644);
4519 remove_file_from_index(state
->repo
->index
, patch
->new_name
);
4520 for (stage
= 1; stage
< 4; stage
++) {
4521 if (is_null_oid(&patch
->threeway_stage
[stage
- 1]))
4523 ce
= make_empty_cache_entry(state
->repo
->index
, namelen
);
4524 memcpy(ce
->name
, patch
->new_name
, namelen
);
4525 ce
->ce_mode
= create_ce_mode(mode
);
4526 ce
->ce_flags
= create_ce_flags(stage
);
4527 ce
->ce_namelen
= namelen
;
4528 oidcpy(&ce
->oid
, &patch
->threeway_stage
[stage
- 1]);
4529 if (add_index_entry(state
->repo
->index
, ce
, ADD_CACHE_OK_TO_ADD
) < 0) {
4530 discard_cache_entry(ce
);
4531 return error(_("unable to add cache entry for %s"),
4539 static int create_file(struct apply_state
*state
, struct patch
*patch
)
4541 char *path
= patch
->new_name
;
4542 unsigned mode
= patch
->new_mode
;
4543 unsigned long size
= patch
->resultsize
;
4544 char *buf
= patch
->result
;
4547 mode
= S_IFREG
| 0644;
4548 if (create_one_file(state
, path
, mode
, buf
, size
))
4551 if (patch
->conflicted_threeway
)
4552 return add_conflicted_stages_file(state
, patch
);
4553 else if (state
->update_index
)
4554 return add_index_file(state
, path
, mode
, buf
, size
);
4558 /* phase zero is to remove, phase one is to create */
4559 static int write_out_one_result(struct apply_state
*state
,
4560 struct patch
*patch
,
4563 if (patch
->is_delete
> 0) {
4565 return remove_file(state
, patch
, 1);
4568 if (patch
->is_new
> 0 || patch
->is_copy
) {
4570 return create_file(state
, patch
);
4574 * Rename or modification boils down to the same
4575 * thing: remove the old, write the new
4578 return remove_file(state
, patch
, patch
->is_rename
);
4580 return create_file(state
, patch
);
4584 static int write_out_one_reject(struct apply_state
*state
, struct patch
*patch
)
4587 char namebuf
[PATH_MAX
];
4588 struct fragment
*frag
;
4590 struct strbuf sb
= STRBUF_INIT
;
4592 for (cnt
= 0, frag
= patch
->fragments
; frag
; frag
= frag
->next
) {
4593 if (!frag
->rejected
)
4599 if (state
->apply_verbosity
> verbosity_normal
)
4600 say_patch_name(stderr
,
4601 _("Applied patch %s cleanly."), patch
);
4605 /* This should not happen, because a removal patch that leaves
4606 * contents are marked "rejected" at the patch level.
4608 if (!patch
->new_name
)
4609 die(_("internal error"));
4611 /* Say this even without --verbose */
4612 strbuf_addf(&sb
, Q_("Applying patch %%s with %d reject...",
4613 "Applying patch %%s with %d rejects...",
4616 if (state
->apply_verbosity
> verbosity_silent
)
4617 say_patch_name(stderr
, sb
.buf
, patch
);
4618 strbuf_release(&sb
);
4620 cnt
= strlen(patch
->new_name
);
4621 if (ARRAY_SIZE(namebuf
) <= cnt
+ 5) {
4622 cnt
= ARRAY_SIZE(namebuf
) - 5;
4623 warning(_("truncating .rej filename to %.*s.rej"),
4624 cnt
- 1, patch
->new_name
);
4626 memcpy(namebuf
, patch
->new_name
, cnt
);
4627 memcpy(namebuf
+ cnt
, ".rej", 5);
4629 rej
= fopen(namebuf
, "w");
4631 return error_errno(_("cannot open %s"), namebuf
);
4633 /* Normal git tools never deal with .rej, so do not pretend
4634 * this is a git patch by saying --git or giving extended
4635 * headers. While at it, maybe please "kompare" that wants
4636 * the trailing TAB and some garbage at the end of line ;-).
4638 fprintf(rej
, "diff a/%s b/%s\t(rejected hunks)\n",
4639 patch
->new_name
, patch
->new_name
);
4640 for (cnt
= 1, frag
= patch
->fragments
;
4642 cnt
++, frag
= frag
->next
) {
4643 if (!frag
->rejected
) {
4644 if (state
->apply_verbosity
> verbosity_silent
)
4645 fprintf_ln(stderr
, _("Hunk #%d applied cleanly."), cnt
);
4648 if (state
->apply_verbosity
> verbosity_silent
)
4649 fprintf_ln(stderr
, _("Rejected hunk #%d."), cnt
);
4650 fprintf(rej
, "%.*s", frag
->size
, frag
->patch
);
4651 if (frag
->patch
[frag
->size
-1] != '\n')
4660 * -1 if an error happened
4661 * 0 if the patch applied cleanly
4662 * 1 if the patch did not apply cleanly
4664 static int write_out_results(struct apply_state
*state
, struct patch
*list
)
4669 struct string_list cpath
= STRING_LIST_INIT_DUP
;
4671 for (phase
= 0; phase
< 2; phase
++) {
4677 if (write_out_one_result(state
, l
, phase
)) {
4678 string_list_clear(&cpath
, 0);
4682 if (write_out_one_reject(state
, l
))
4684 if (l
->conflicted_threeway
) {
4685 string_list_append(&cpath
, l
->new_name
);
4695 struct string_list_item
*item
;
4697 string_list_sort(&cpath
);
4698 if (state
->apply_verbosity
> verbosity_silent
) {
4699 for_each_string_list_item(item
, &cpath
)
4700 fprintf(stderr
, "U %s\n", item
->string
);
4702 string_list_clear(&cpath
, 0);
4705 * rerere relies on the partially merged result being in the working
4706 * tree with conflict markers, but that isn't written with --cached.
4709 repo_rerere(state
->repo
, 0);
4716 * Try to apply a patch.
4719 * -128 if a bad error happened (like patch unreadable)
4720 * -1 if patch did not apply and user cannot deal with it
4721 * 0 if the patch applied
4722 * 1 if the patch did not apply but user might fix it
4724 static int apply_patch(struct apply_state
*state
,
4726 const char *filename
,
4730 struct strbuf buf
= STRBUF_INIT
; /* owns the patch text */
4731 struct patch
*list
= NULL
, **listp
= &list
;
4732 int skipped_patch
= 0;
4734 int flush_attributes
= 0;
4736 state
->patch_input_file
= filename
;
4737 if (read_patch_file(&buf
, fd
) < 0)
4740 while (offset
< buf
.len
) {
4741 struct patch
*patch
;
4744 CALLOC_ARRAY(patch
, 1);
4745 patch
->inaccurate_eof
= !!(options
& APPLY_OPT_INACCURATE_EOF
);
4746 patch
->recount
= !!(options
& APPLY_OPT_RECOUNT
);
4747 nr
= parse_chunk(state
, buf
.buf
+ offset
, buf
.len
- offset
, patch
);
4756 if (state
->apply_in_reverse
)
4757 reverse_patches(patch
);
4758 if (use_patch(state
, patch
)) {
4759 patch_stats(state
, patch
);
4760 if (!list
|| !state
->apply_in_reverse
) {
4762 listp
= &patch
->next
;
4768 if ((patch
->new_name
&&
4769 ends_with_path_components(patch
->new_name
,
4770 GITATTRIBUTES_FILE
)) ||
4772 ends_with_path_components(patch
->old_name
,
4773 GITATTRIBUTES_FILE
)))
4774 flush_attributes
= 1;
4777 if (state
->apply_verbosity
> verbosity_normal
)
4778 say_patch_name(stderr
, _("Skipped patch '%s'."), patch
);
4785 if (!list
&& !skipped_patch
) {
4786 if (!state
->allow_empty
) {
4787 error(_("No valid patches in input (allow with \"--allow-empty\")"));
4793 if (state
->whitespace_error
&& (state
->ws_error_action
== die_on_ws_error
))
4796 state
->update_index
= (state
->check_index
|| state
->ita_only
) && state
->apply
;
4797 if (state
->update_index
&& !is_lock_file_locked(&state
->lock_file
)) {
4798 if (state
->index_file
)
4799 hold_lock_file_for_update(&state
->lock_file
,
4803 repo_hold_locked_index(state
->repo
, &state
->lock_file
,
4807 if (state
->check_index
&& read_apply_cache(state
) < 0) {
4808 error(_("unable to read index file"));
4813 if (state
->check
|| state
->apply
) {
4814 int r
= check_patch_list(state
, list
);
4819 if (r
< 0 && !state
->apply_with_reject
) {
4826 int write_res
= write_out_results(state
, list
);
4827 if (write_res
< 0) {
4831 if (write_res
> 0) {
4832 /* with --3way, we still need to write the index out */
4833 res
= state
->apply_with_reject
? -1 : 1;
4838 if (state
->fake_ancestor
&&
4839 build_fake_ancestor(state
, list
)) {
4844 if (state
->diffstat
&& state
->apply_verbosity
> verbosity_silent
)
4845 stat_patch_list(state
, list
);
4847 if (state
->numstat
&& state
->apply_verbosity
> verbosity_silent
)
4848 numstat_patch_list(state
, list
);
4850 if (state
->summary
&& state
->apply_verbosity
> verbosity_silent
)
4851 summary_patch_list(list
);
4853 if (flush_attributes
)
4854 reset_parsed_attributes();
4856 free_patch_list(list
);
4857 strbuf_release(&buf
);
4858 string_list_clear(&state
->fn_table
, 0);
4862 static int apply_option_parse_exclude(const struct option
*opt
,
4863 const char *arg
, int unset
)
4865 struct apply_state
*state
= opt
->value
;
4867 BUG_ON_OPT_NEG(unset
);
4869 add_name_limit(state
, arg
, 1);
4873 static int apply_option_parse_include(const struct option
*opt
,
4874 const char *arg
, int unset
)
4876 struct apply_state
*state
= opt
->value
;
4878 BUG_ON_OPT_NEG(unset
);
4880 add_name_limit(state
, arg
, 0);
4881 state
->has_include
= 1;
4885 static int apply_option_parse_p(const struct option
*opt
,
4889 struct apply_state
*state
= opt
->value
;
4891 BUG_ON_OPT_NEG(unset
);
4893 state
->p_value
= atoi(arg
);
4894 state
->p_value_known
= 1;
4898 static int apply_option_parse_space_change(const struct option
*opt
,
4899 const char *arg
, int unset
)
4901 struct apply_state
*state
= opt
->value
;
4903 BUG_ON_OPT_ARG(arg
);
4906 state
->ws_ignore_action
= ignore_ws_none
;
4908 state
->ws_ignore_action
= ignore_ws_change
;
4912 static int apply_option_parse_whitespace(const struct option
*opt
,
4913 const char *arg
, int unset
)
4915 struct apply_state
*state
= opt
->value
;
4917 BUG_ON_OPT_NEG(unset
);
4919 state
->whitespace_option
= arg
;
4920 if (parse_whitespace_option(state
, arg
))
4925 static int apply_option_parse_directory(const struct option
*opt
,
4926 const char *arg
, int unset
)
4928 struct apply_state
*state
= opt
->value
;
4930 BUG_ON_OPT_NEG(unset
);
4932 strbuf_reset(&state
->root
);
4933 strbuf_addstr(&state
->root
, arg
);
4934 strbuf_complete(&state
->root
, '/');
4938 int apply_all_patches(struct apply_state
*state
,
4948 for (i
= 0; i
< argc
; i
++) {
4949 const char *arg
= argv
[i
];
4950 char *to_free
= NULL
;
4953 if (!strcmp(arg
, "-")) {
4954 res
= apply_patch(state
, 0, "<stdin>", options
);
4961 arg
= to_free
= prefix_filename(state
->prefix
, arg
);
4963 fd
= open(arg
, O_RDONLY
);
4965 error(_("can't open patch '%s': %s"), arg
, strerror(errno
));
4971 set_default_whitespace_mode(state
);
4972 res
= apply_patch(state
, fd
, arg
, options
);
4979 set_default_whitespace_mode(state
);
4981 res
= apply_patch(state
, 0, "<stdin>", options
);
4987 if (state
->whitespace_error
) {
4988 if (state
->squelch_whitespace_errors
&&
4989 state
->squelch_whitespace_errors
< state
->whitespace_error
) {
4991 state
->whitespace_error
- state
->squelch_whitespace_errors
;
4992 warning(Q_("squelched %d whitespace error",
4993 "squelched %d whitespace errors",
4997 if (state
->ws_error_action
== die_on_ws_error
) {
4998 error(Q_("%d line adds whitespace errors.",
4999 "%d lines add whitespace errors.",
5000 state
->whitespace_error
),
5001 state
->whitespace_error
);
5005 if (state
->applied_after_fixing_ws
&& state
->apply
)
5006 warning(Q_("%d line applied after"
5007 " fixing whitespace errors.",
5008 "%d lines applied after"
5009 " fixing whitespace errors.",
5010 state
->applied_after_fixing_ws
),
5011 state
->applied_after_fixing_ws
);
5012 else if (state
->whitespace_error
)
5013 warning(Q_("%d line adds whitespace errors.",
5014 "%d lines add whitespace errors.",
5015 state
->whitespace_error
),
5016 state
->whitespace_error
);
5019 if (state
->update_index
) {
5020 res
= write_locked_index(state
->repo
->index
, &state
->lock_file
, COMMIT_LOCK
);
5022 error(_("Unable to write new index file"));
5031 rollback_lock_file(&state
->lock_file
);
5033 if (state
->apply_verbosity
<= verbosity_silent
) {
5034 set_error_routine(state
->saved_error_routine
);
5035 set_warn_routine(state
->saved_warn_routine
);
5040 return (res
== -1 ? 1 : 128);
5043 int apply_parse_options(int argc
, const char **argv
,
5044 struct apply_state
*state
,
5045 int *force_apply
, int *options
,
5046 const char * const *apply_usage
)
5048 struct option builtin_apply_options
[] = {
5049 OPT_CALLBACK_F(0, "exclude", state
, N_("path"),
5050 N_("don't apply changes matching the given path"),
5051 PARSE_OPT_NONEG
, apply_option_parse_exclude
),
5052 OPT_CALLBACK_F(0, "include", state
, N_("path"),
5053 N_("apply changes matching the given path"),
5054 PARSE_OPT_NONEG
, apply_option_parse_include
),
5055 OPT_CALLBACK('p', NULL
, state
, N_("num"),
5056 N_("remove <num> leading slashes from traditional diff paths"),
5057 apply_option_parse_p
),
5058 OPT_BOOL(0, "no-add", &state
->no_add
,
5059 N_("ignore additions made by the patch")),
5060 OPT_BOOL(0, "stat", &state
->diffstat
,
5061 N_("instead of applying the patch, output diffstat for the input")),
5062 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
5063 OPT_NOOP_NOARG(0, "binary"),
5064 OPT_BOOL(0, "numstat", &state
->numstat
,
5065 N_("show number of added and deleted lines in decimal notation")),
5066 OPT_BOOL(0, "summary", &state
->summary
,
5067 N_("instead of applying the patch, output a summary for the input")),
5068 OPT_BOOL(0, "check", &state
->check
,
5069 N_("instead of applying the patch, see if the patch is applicable")),
5070 OPT_BOOL(0, "index", &state
->check_index
,
5071 N_("make sure the patch is applicable to the current index")),
5072 OPT_BOOL('N', "intent-to-add", &state
->ita_only
,
5073 N_("mark new files with `git add --intent-to-add`")),
5074 OPT_BOOL(0, "cached", &state
->cached
,
5075 N_("apply a patch without touching the working tree")),
5076 OPT_BOOL_F(0, "unsafe-paths", &state
->unsafe_paths
,
5077 N_("accept a patch that touches outside the working area"),
5078 PARSE_OPT_NOCOMPLETE
),
5079 OPT_BOOL(0, "apply", force_apply
,
5080 N_("also apply the patch (use with --stat/--summary/--check)")),
5081 OPT_BOOL('3', "3way", &state
->threeway
,
5082 N_( "attempt three-way merge, fall back on normal patch if that fails")),
5083 OPT_FILENAME(0, "build-fake-ancestor", &state
->fake_ancestor
,
5084 N_("build a temporary index based on embedded index information")),
5085 /* Think twice before adding "--nul" synonym to this */
5086 OPT_SET_INT('z', NULL
, &state
->line_termination
,
5087 N_("paths are separated with NUL character"), '\0'),
5088 OPT_INTEGER('C', NULL
, &state
->p_context
,
5089 N_("ensure at least <n> lines of context match")),
5090 OPT_CALLBACK(0, "whitespace", state
, N_("action"),
5091 N_("detect new or modified lines that have whitespace errors"),
5092 apply_option_parse_whitespace
),
5093 OPT_CALLBACK_F(0, "ignore-space-change", state
, NULL
,
5094 N_("ignore changes in whitespace when finding context"),
5095 PARSE_OPT_NOARG
, apply_option_parse_space_change
),
5096 OPT_CALLBACK_F(0, "ignore-whitespace", state
, NULL
,
5097 N_("ignore changes in whitespace when finding context"),
5098 PARSE_OPT_NOARG
, apply_option_parse_space_change
),
5099 OPT_BOOL('R', "reverse", &state
->apply_in_reverse
,
5100 N_("apply the patch in reverse")),
5101 OPT_BOOL(0, "unidiff-zero", &state
->unidiff_zero
,
5102 N_("don't expect at least one line of context")),
5103 OPT_BOOL(0, "reject", &state
->apply_with_reject
,
5104 N_("leave the rejected hunks in corresponding *.rej files")),
5105 OPT_BOOL(0, "allow-overlap", &state
->allow_overlap
,
5106 N_("allow overlapping hunks")),
5107 OPT__VERBOSITY(&state
->apply_verbosity
),
5108 OPT_BIT(0, "inaccurate-eof", options
,
5109 N_("tolerate incorrectly detected missing new-line at the end of file"),
5110 APPLY_OPT_INACCURATE_EOF
),
5111 OPT_BIT(0, "recount", options
,
5112 N_("do not trust the line counts in the hunk headers"),
5114 OPT_CALLBACK(0, "directory", state
, N_("root"),
5115 N_("prepend <root> to all filenames"),
5116 apply_option_parse_directory
),
5117 OPT_BOOL(0, "allow-empty", &state
->allow_empty
,
5118 N_("don't return error for empty patches")),
5122 return parse_options(argc
, argv
, state
->prefix
, builtin_apply_options
, apply_usage
, 0);