4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
10 #define USE_THE_REPOSITORY_VARIABLE
11 #define DISABLE_SIGN_COMPARE_WARNINGS
13 #include "git-compat-util.h"
17 #include "object-store-ll.h"
21 #include "environment.h"
24 #include "xdiff-interface.h"
27 #include "name-hash.h"
28 #include "object-name.h"
29 #include "object-file.h"
30 #include "parse-options.h"
33 #include "read-cache.h"
34 #include "repository.h"
40 #include "wildmatch.h"
49 static void git_apply_config(void)
51 git_config_get_string("apply.whitespace", &apply_default_whitespace
);
52 git_config_get_string("apply.ignorewhitespace", &apply_default_ignorewhitespace
);
53 git_config(git_xmerge_config
, NULL
);
56 static int parse_whitespace_option(struct apply_state
*state
, const char *option
)
59 state
->ws_error_action
= warn_on_ws_error
;
62 if (!strcmp(option
, "warn")) {
63 state
->ws_error_action
= warn_on_ws_error
;
66 if (!strcmp(option
, "nowarn")) {
67 state
->ws_error_action
= nowarn_ws_error
;
70 if (!strcmp(option
, "error")) {
71 state
->ws_error_action
= die_on_ws_error
;
74 if (!strcmp(option
, "error-all")) {
75 state
->ws_error_action
= die_on_ws_error
;
76 state
->squelch_whitespace_errors
= 0;
79 if (!strcmp(option
, "strip") || !strcmp(option
, "fix")) {
80 state
->ws_error_action
= correct_ws_error
;
84 * Please update $__git_whitespacelist in git-completion.bash,
85 * Documentation/git-apply.txt, and Documentation/git-am.txt
86 * when you add new options.
88 return error(_("unrecognized whitespace option '%s'"), option
);
91 static int parse_ignorewhitespace_option(struct apply_state
*state
,
94 if (!option
|| !strcmp(option
, "no") ||
95 !strcmp(option
, "false") || !strcmp(option
, "never") ||
96 !strcmp(option
, "none")) {
97 state
->ws_ignore_action
= ignore_ws_none
;
100 if (!strcmp(option
, "change")) {
101 state
->ws_ignore_action
= ignore_ws_change
;
104 return error(_("unrecognized whitespace ignore option '%s'"), option
);
107 int init_apply_state(struct apply_state
*state
,
108 struct repository
*repo
,
111 memset(state
, 0, sizeof(*state
));
112 state
->prefix
= prefix
;
115 state
->line_termination
= '\n';
117 state
->p_context
= UINT_MAX
;
118 state
->squelch_whitespace_errors
= 5;
119 state
->ws_error_action
= warn_on_ws_error
;
120 state
->ws_ignore_action
= ignore_ws_none
;
122 string_list_init_nodup(&state
->fn_table
);
123 string_list_init_nodup(&state
->limit_by_name
);
124 strset_init(&state
->removed_symlinks
);
125 strset_init(&state
->kept_symlinks
);
126 strbuf_init(&state
->root
, 0);
129 if (apply_default_whitespace
&& parse_whitespace_option(state
, apply_default_whitespace
))
131 if (apply_default_ignorewhitespace
&& parse_ignorewhitespace_option(state
, apply_default_ignorewhitespace
))
136 void clear_apply_state(struct apply_state
*state
)
138 string_list_clear(&state
->limit_by_name
, 0);
139 strset_clear(&state
->removed_symlinks
);
140 strset_clear(&state
->kept_symlinks
);
141 strbuf_release(&state
->root
);
142 FREE_AND_NULL(state
->fake_ancestor
);
144 /* &state->fn_table is cleared at the end of apply_patch() */
147 static void mute_routine(const char *msg UNUSED
, va_list params UNUSED
)
152 int check_apply_state(struct apply_state
*state
, int force_apply
)
154 int is_not_gitdir
= !startup_info
->have_repository
;
156 if (state
->apply_with_reject
&& state
->threeway
)
157 return error(_("options '%s' and '%s' cannot be used together"), "--reject", "--3way");
158 if (state
->threeway
) {
160 return error(_("'%s' outside a repository"), "--3way");
161 state
->check_index
= 1;
163 if (state
->apply_with_reject
) {
165 if (state
->apply_verbosity
== verbosity_normal
)
166 state
->apply_verbosity
= verbosity_verbose
;
168 if (!force_apply
&& (state
->diffstat
|| state
->numstat
|| state
->summary
|| state
->check
|| state
->fake_ancestor
))
170 if (state
->check_index
&& is_not_gitdir
)
171 return error(_("'%s' outside a repository"), "--index");
174 return error(_("'%s' outside a repository"), "--cached");
175 state
->check_index
= 1;
177 if (state
->ita_only
&& (state
->check_index
|| is_not_gitdir
))
179 if (state
->check_index
)
180 state
->unsafe_paths
= 0;
182 if (state
->apply_verbosity
<= verbosity_silent
) {
183 state
->saved_error_routine
= get_error_routine();
184 state
->saved_warn_routine
= get_warn_routine();
185 set_error_routine(mute_routine
);
186 set_warn_routine(mute_routine
);
192 static void set_default_whitespace_mode(struct apply_state
*state
)
194 if (!state
->whitespace_option
&& !apply_default_whitespace
)
195 state
->ws_error_action
= (state
->apply
? warn_on_ws_error
: nowarn_ws_error
);
199 * This represents one "hunk" from a patch, starting with
200 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
201 * patch text is pointed at by patch, and its byte length
202 * is stored in size. leading and trailing are the number
206 unsigned long leading
, trailing
;
207 unsigned long oldpos
, oldlines
;
208 unsigned long newpos
, newlines
;
210 * 'patch' is usually borrowed from buf in apply_patch(),
211 * but some codepaths store an allocated buffer.
214 unsigned free_patch
:1,
218 struct fragment
*next
;
222 * When dealing with a binary patch, we reuse "leading" field
223 * to store the type of the binary hunk, either deflated "delta"
224 * or deflated "literal".
226 #define binary_patch_method leading
227 #define BINARY_DELTA_DEFLATED 1
228 #define BINARY_LITERAL_DEFLATED 2
230 static void free_fragment_list(struct fragment
*list
)
233 struct fragment
*next
= list
->next
;
234 if (list
->free_patch
)
235 free((char *)list
->patch
);
241 void release_patch(struct patch
*patch
)
243 free_fragment_list(patch
->fragments
);
244 free(patch
->def_name
);
245 free(patch
->old_name
);
246 free(patch
->new_name
);
250 static void free_patch(struct patch
*patch
)
252 release_patch(patch
);
256 static void free_patch_list(struct patch
*list
)
259 struct patch
*next
= list
->next
;
266 * A line in a file, len-bytes long (includes the terminating LF,
267 * except for an incomplete line at the end if the file ends with
268 * one), and its contents hashes to 'hash'.
274 #define LINE_COMMON 1
275 #define LINE_PATCHED 2
279 * This represents a "file", which is an array of "lines".
284 size_t line_nr
, line_alloc
;
286 #define IMAGE_INIT { \
287 .buf = STRBUF_INIT, \
290 static void image_init(struct image
*image
)
292 struct image empty
= IMAGE_INIT
;
293 memcpy(image
, &empty
, sizeof(*image
));
296 static void image_clear(struct image
*image
)
298 strbuf_release(&image
->buf
);
303 static uint32_t hash_line(const char *cp
, size_t len
)
307 for (i
= 0, h
= 0; i
< len
; i
++) {
308 if (!isspace(cp
[i
])) {
309 h
= h
* 3 + (cp
[i
] & 0xff);
315 static void image_add_line(struct image
*img
, const char *bol
, size_t len
, unsigned flag
)
317 ALLOC_GROW(img
->line
, img
->line_nr
+ 1, img
->line_alloc
);
318 img
->line
[img
->line_nr
].len
= len
;
319 img
->line
[img
->line_nr
].hash
= hash_line(bol
, len
);
320 img
->line
[img
->line_nr
].flag
= flag
;
325 * "buf" has the file contents to be patched (read from various sources).
326 * attach it to "image" and add line-based index to it.
327 * "image" now owns the "buf".
329 static void image_prepare(struct image
*image
, char *buf
, size_t len
,
330 int prepare_linetable
)
335 strbuf_attach(&image
->buf
, buf
, len
, len
+ 1);
337 if (!prepare_linetable
)
340 ep
= image
->buf
.buf
+ image
->buf
.len
;
344 for (next
= cp
; next
< ep
&& *next
!= '\n'; next
++)
348 image_add_line(image
, cp
, next
- cp
, 0);
353 static void image_remove_first_line(struct image
*img
)
355 strbuf_remove(&img
->buf
, 0, img
->line
[0].len
);
358 MOVE_ARRAY(img
->line
, img
->line
+ 1, img
->line_nr
);
361 static void image_remove_last_line(struct image
*img
)
363 size_t last_line_len
= img
->line
[img
->line_nr
- 1].len
;
364 strbuf_setlen(&img
->buf
, img
->buf
.len
- last_line_len
);
368 /* fmt must contain _one_ %s and no other substitution */
369 static void say_patch_name(FILE *output
, const char *fmt
, struct patch
*patch
)
371 struct strbuf sb
= STRBUF_INIT
;
373 if (patch
->old_name
&& patch
->new_name
&&
374 strcmp(patch
->old_name
, patch
->new_name
)) {
375 quote_c_style(patch
->old_name
, &sb
, NULL
, 0);
376 strbuf_addstr(&sb
, " => ");
377 quote_c_style(patch
->new_name
, &sb
, NULL
, 0);
379 const char *n
= patch
->new_name
;
382 quote_c_style(n
, &sb
, NULL
, 0);
384 fprintf(output
, fmt
, sb
.buf
);
392 * apply.c isn't equipped to handle arbitrarily large patches, because
393 * it intermingles `unsigned long` with `int` for the type used to store
396 * Only process patches that are just shy of 1 GiB large in order to
397 * avoid any truncation or overflow issues.
399 #define MAX_APPLY_SIZE (1024UL * 1024 * 1023)
401 static int read_patch_file(struct strbuf
*sb
, int fd
)
403 if (strbuf_read(sb
, fd
, 0) < 0)
404 return error_errno(_("failed to read patch"));
405 else if (sb
->len
>= MAX_APPLY_SIZE
)
406 return error(_("patch too large"));
408 * Make sure that we have some slop in the buffer
409 * so that we can do speculative "memcmp" etc, and
410 * see to it that it is NUL-filled.
412 strbuf_grow(sb
, SLOP
);
413 memset(sb
->buf
+ sb
->len
, 0, SLOP
);
417 static unsigned long linelen(const char *buffer
, unsigned long size
)
419 unsigned long len
= 0;
422 if (*buffer
++ == '\n')
428 static int is_dev_null(const char *str
)
430 return skip_prefix(str
, "/dev/null", &str
) && isspace(*str
);
436 static int name_terminate(int c
, int terminate
)
438 if (c
== ' ' && !(terminate
& TERM_SPACE
))
440 if (c
== '\t' && !(terminate
& TERM_TAB
))
446 /* remove double slashes to make --index work with such filenames */
447 static char *squash_slash(char *name
)
455 if ((name
[j
++] = name
[i
++]) == '/')
456 while (name
[i
] == '/')
463 static char *find_name_gnu(struct strbuf
*root
,
467 struct strbuf name
= STRBUF_INIT
;
471 * Proposed "new-style" GNU patch/diff format; see
472 * https://lore.kernel.org/git/7vll0wvb2a.fsf@assigned-by-dhcp.cox.net/
474 if (unquote_c_style(&name
, line
, NULL
)) {
475 strbuf_release(&name
);
479 for (cp
= name
.buf
; p_value
; p_value
--) {
480 cp
= strchr(cp
, '/');
482 strbuf_release(&name
);
488 strbuf_remove(&name
, 0, cp
- name
.buf
);
490 strbuf_insert(&name
, 0, root
->buf
, root
->len
);
491 return squash_slash(strbuf_detach(&name
, NULL
));
494 static size_t sane_tz_len(const char *line
, size_t len
)
498 if (len
< strlen(" +0500") || line
[len
-strlen(" +0500")] != ' ')
500 tz
= line
+ len
- strlen(" +0500");
502 if (tz
[1] != '+' && tz
[1] != '-')
505 for (p
= tz
+ 2; p
!= line
+ len
; p
++)
509 return line
+ len
- tz
;
512 static size_t tz_with_colon_len(const char *line
, size_t len
)
516 if (len
< strlen(" +08:00") || line
[len
- strlen(":00")] != ':')
518 tz
= line
+ len
- strlen(" +08:00");
520 if (tz
[0] != ' ' || (tz
[1] != '+' && tz
[1] != '-'))
523 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
524 !isdigit(*p
++) || !isdigit(*p
++))
527 return line
+ len
- tz
;
530 static size_t date_len(const char *line
, size_t len
)
532 const char *date
, *p
;
534 if (len
< strlen("72-02-05") || line
[len
-strlen("-05")] != '-')
536 p
= date
= line
+ len
- strlen("72-02-05");
538 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
539 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
540 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a date. */
543 if (date
- line
>= strlen("19") &&
544 isdigit(date
[-1]) && isdigit(date
[-2])) /* 4-digit year */
545 date
-= strlen("19");
547 return line
+ len
- date
;
550 static size_t short_time_len(const char *line
, size_t len
)
552 const char *time
, *p
;
554 if (len
< strlen(" 07:01:32") || line
[len
-strlen(":32")] != ':')
556 p
= time
= line
+ len
- strlen(" 07:01:32");
558 /* Permit 1-digit hours? */
560 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
561 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
562 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a time. */
565 return line
+ len
- time
;
568 static size_t fractional_time_len(const char *line
, size_t len
)
573 /* Expected format: 19:41:17.620000023 */
574 if (!len
|| !isdigit(line
[len
- 1]))
578 /* Fractional seconds. */
579 while (p
> line
&& isdigit(*p
))
584 /* Hours, minutes, and whole seconds. */
585 n
= short_time_len(line
, p
- line
);
589 return line
+ len
- p
+ n
;
592 static size_t trailing_spaces_len(const char *line
, size_t len
)
596 /* Expected format: ' ' x (1 or more) */
597 if (!len
|| line
[len
- 1] != ' ')
604 return line
+ len
- (p
+ 1);
611 static size_t diff_timestamp_len(const char *line
, size_t len
)
613 const char *end
= line
+ len
;
617 * Posix: 2010-07-05 19:41:17
618 * GNU: 2010-07-05 19:41:17.620000023 -0500
621 if (!isdigit(end
[-1]))
624 n
= sane_tz_len(line
, end
- line
);
626 n
= tz_with_colon_len(line
, end
- line
);
629 n
= short_time_len(line
, end
- line
);
631 n
= fractional_time_len(line
, end
- line
);
634 n
= date_len(line
, end
- line
);
635 if (!n
) /* No date. Too bad. */
639 if (end
== line
) /* No space before date. */
641 if (end
[-1] == '\t') { /* Success! */
643 return line
+ len
- end
;
645 if (end
[-1] != ' ') /* No space before date. */
648 /* Whitespace damage. */
649 end
-= trailing_spaces_len(line
, end
- line
);
650 return line
+ len
- end
;
653 static char *find_name_common(struct strbuf
*root
,
661 const char *start
= NULL
;
665 while (line
!= end
) {
668 if (!end
&& isspace(c
)) {
671 if (name_terminate(c
, terminate
))
675 if (c
== '/' && !--p_value
)
679 return squash_slash(xstrdup_or_null(def
));
682 return squash_slash(xstrdup_or_null(def
));
685 * Generally we prefer the shorter name, especially
686 * if the other one is just a variation of that with
687 * something else tacked on to the end (ie "file.orig"
691 int deflen
= strlen(def
);
692 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
693 return squash_slash(xstrdup(def
));
697 char *ret
= xstrfmt("%s%.*s", root
->buf
, len
, start
);
698 return squash_slash(ret
);
701 return squash_slash(xmemdupz(start
, len
));
704 static char *find_name(struct strbuf
*root
,
711 char *name
= find_name_gnu(root
, line
, p_value
);
716 return find_name_common(root
, line
, def
, p_value
, NULL
, terminate
);
719 static char *find_name_traditional(struct strbuf
*root
,
728 char *name
= find_name_gnu(root
, line
, p_value
);
733 len
= strchrnul(line
, '\n') - line
;
734 date_len
= diff_timestamp_len(line
, len
);
736 return find_name_common(root
, line
, def
, p_value
, NULL
, TERM_TAB
);
739 return find_name_common(root
, line
, def
, p_value
, line
+ len
, 0);
743 * Given the string after "--- " or "+++ ", guess the appropriate
744 * p_value for the given patch.
746 static int guess_p_value(struct apply_state
*state
, const char *nameline
)
751 if (is_dev_null(nameline
))
753 name
= find_name_traditional(&state
->root
, nameline
, NULL
, 0);
756 cp
= strchr(name
, '/');
759 else if (state
->prefix
) {
761 * Does it begin with "a/$our-prefix" and such? Then this is
762 * very likely to apply to our directory.
764 if (starts_with(name
, state
->prefix
))
765 val
= count_slashes(state
->prefix
);
768 if (starts_with(cp
, state
->prefix
))
769 val
= count_slashes(state
->prefix
) + 1;
777 * Does the ---/+++ line have the POSIX timestamp after the last HT?
778 * GNU diff puts epoch there to signal a creation/deletion event. Is
779 * this such a timestamp?
781 static int has_epoch_timestamp(const char *nameline
)
784 * We are only interested in epoch timestamp; any non-zero
785 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
786 * For the same reason, the date must be either 1969-12-31 or
787 * 1970-01-01, and the seconds part must be "00".
789 const char stamp_regexp
[] =
790 "^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?"
792 "([-+][0-2][0-9]:?[0-5][0-9])\n";
793 const char *timestamp
= NULL
, *cp
, *colon
;
794 static regex_t
*stamp
;
796 int zoneoffset
, epoch_hour
, hour
, minute
;
799 for (cp
= nameline
; *cp
!= '\n'; cp
++) {
807 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
808 * (west of GMT) or 1970-01-01 (east of GMT)
810 if (skip_prefix(timestamp
, "1969-12-31 ", ×tamp
))
812 else if (skip_prefix(timestamp
, "1970-01-01 ", ×tamp
))
818 stamp
= xmalloc(sizeof(*stamp
));
819 if (regcomp(stamp
, stamp_regexp
, REG_EXTENDED
)) {
820 warning(_("Cannot prepare timestamp regexp %s"),
826 status
= regexec(stamp
, timestamp
, ARRAY_SIZE(m
), m
, 0);
828 if (status
!= REG_NOMATCH
)
829 warning(_("regexec returned %d for input: %s"),
834 hour
= strtol(timestamp
, NULL
, 10);
835 minute
= strtol(timestamp
+ m
[1].rm_so
, NULL
, 10);
837 zoneoffset
= strtol(timestamp
+ m
[3].rm_so
+ 1, (char **) &colon
, 10);
839 zoneoffset
= zoneoffset
* 60 + strtol(colon
+ 1, NULL
, 10);
841 zoneoffset
= (zoneoffset
/ 100) * 60 + (zoneoffset
% 100);
842 if (timestamp
[m
[3].rm_so
] == '-')
843 zoneoffset
= -zoneoffset
;
845 return hour
* 60 + minute
- zoneoffset
== epoch_hour
* 60;
849 * Get the name etc info from the ---/+++ lines of a traditional patch header
851 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
852 * files, we can happily check the index for a match, but for creating a
853 * new file we should try to match whatever "patch" does. I have no idea.
855 static int parse_traditional_patch(struct apply_state
*state
,
862 first
+= 4; /* skip "--- " */
863 second
+= 4; /* skip "+++ " */
864 if (!state
->p_value_known
) {
866 p
= guess_p_value(state
, first
);
867 q
= guess_p_value(state
, second
);
869 if (0 <= p
&& p
== q
) {
871 state
->p_value_known
= 1;
874 if (is_dev_null(first
)) {
876 patch
->is_delete
= 0;
877 name
= find_name_traditional(&state
->root
, second
, NULL
, state
->p_value
);
878 patch
->new_name
= name
;
879 } else if (is_dev_null(second
)) {
881 patch
->is_delete
= 1;
882 name
= find_name_traditional(&state
->root
, first
, NULL
, state
->p_value
);
883 patch
->old_name
= name
;
886 first_name
= find_name_traditional(&state
->root
, first
, NULL
, state
->p_value
);
887 name
= find_name_traditional(&state
->root
, second
, first_name
, state
->p_value
);
889 if (has_epoch_timestamp(first
)) {
891 patch
->is_delete
= 0;
892 patch
->new_name
= name
;
893 } else if (has_epoch_timestamp(second
)) {
895 patch
->is_delete
= 1;
896 patch
->old_name
= name
;
898 patch
->old_name
= name
;
899 patch
->new_name
= xstrdup_or_null(name
);
903 return error(_("unable to find filename in patch at line %d"), state
->linenr
);
908 static int gitdiff_hdrend(struct gitdiff_data
*state UNUSED
,
909 const char *line UNUSED
,
910 struct patch
*patch UNUSED
)
916 * We're anal about diff header consistency, to make
917 * sure that we don't end up having strange ambiguous
918 * patches floating around.
920 * As a result, gitdiff_{old|new}name() will check
921 * their names against any previous information, just
924 #define DIFF_OLD_NAME 0
925 #define DIFF_NEW_NAME 1
927 static int gitdiff_verify_name(struct gitdiff_data
*state
,
933 if (!*name
&& !isnull
) {
934 *name
= find_name(state
->root
, line
, NULL
, state
->p_value
, TERM_TAB
);
941 return error(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
942 *name
, state
->linenr
);
943 another
= find_name(state
->root
, line
, NULL
, state
->p_value
, TERM_TAB
);
944 if (!another
|| strcmp(another
, *name
)) {
946 return error((side
== DIFF_NEW_NAME
) ?
947 _("git apply: bad git-diff - inconsistent new filename on line %d") :
948 _("git apply: bad git-diff - inconsistent old filename on line %d"), state
->linenr
);
952 if (!is_dev_null(line
))
953 return error(_("git apply: bad git-diff - expected /dev/null on line %d"), state
->linenr
);
959 static int gitdiff_oldname(struct gitdiff_data
*state
,
963 return gitdiff_verify_name(state
, line
,
964 patch
->is_new
, &patch
->old_name
,
968 static int gitdiff_newname(struct gitdiff_data
*state
,
972 return gitdiff_verify_name(state
, line
,
973 patch
->is_delete
, &patch
->new_name
,
977 static int parse_mode_line(const char *line
, int linenr
, unsigned int *mode
)
980 *mode
= strtoul(line
, &end
, 8);
981 if (end
== line
|| !isspace(*end
))
982 return error(_("invalid mode on line %d: %s"), linenr
, line
);
983 *mode
= canon_mode(*mode
);
987 static int gitdiff_oldmode(struct gitdiff_data
*state
,
991 return parse_mode_line(line
, state
->linenr
, &patch
->old_mode
);
994 static int gitdiff_newmode(struct gitdiff_data
*state
,
998 return parse_mode_line(line
, state
->linenr
, &patch
->new_mode
);
1001 static int gitdiff_delete(struct gitdiff_data
*state
,
1003 struct patch
*patch
)
1005 patch
->is_delete
= 1;
1006 free(patch
->old_name
);
1007 patch
->old_name
= xstrdup_or_null(patch
->def_name
);
1008 return gitdiff_oldmode(state
, line
, patch
);
1011 static int gitdiff_newfile(struct gitdiff_data
*state
,
1013 struct patch
*patch
)
1016 free(patch
->new_name
);
1017 patch
->new_name
= xstrdup_or_null(patch
->def_name
);
1018 return gitdiff_newmode(state
, line
, patch
);
1021 static int gitdiff_copysrc(struct gitdiff_data
*state
,
1023 struct patch
*patch
)
1026 free(patch
->old_name
);
1027 patch
->old_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1031 static int gitdiff_copydst(struct gitdiff_data
*state
,
1033 struct patch
*patch
)
1036 free(patch
->new_name
);
1037 patch
->new_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1041 static int gitdiff_renamesrc(struct gitdiff_data
*state
,
1043 struct patch
*patch
)
1045 patch
->is_rename
= 1;
1046 free(patch
->old_name
);
1047 patch
->old_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1051 static int gitdiff_renamedst(struct gitdiff_data
*state
,
1053 struct patch
*patch
)
1055 patch
->is_rename
= 1;
1056 free(patch
->new_name
);
1057 patch
->new_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1061 static int gitdiff_similarity(struct gitdiff_data
*state UNUSED
,
1063 struct patch
*patch
)
1065 unsigned long val
= strtoul(line
, NULL
, 10);
1071 static int gitdiff_dissimilarity(struct gitdiff_data
*state UNUSED
,
1073 struct patch
*patch
)
1075 unsigned long val
= strtoul(line
, NULL
, 10);
1081 static int gitdiff_index(struct gitdiff_data
*state
,
1083 struct patch
*patch
)
1086 * index line is N hexadecimal, "..", N hexadecimal,
1087 * and optional space with octal mode.
1089 const char *ptr
, *eol
;
1091 const unsigned hexsz
= the_hash_algo
->hexsz
;
1093 ptr
= strchr(line
, '.');
1094 if (!ptr
|| ptr
[1] != '.' || hexsz
< ptr
- line
)
1097 memcpy(patch
->old_oid_prefix
, line
, len
);
1098 patch
->old_oid_prefix
[len
] = 0;
1101 ptr
= strchr(line
, ' ');
1102 eol
= strchrnul(line
, '\n');
1104 if (!ptr
|| eol
< ptr
)
1110 memcpy(patch
->new_oid_prefix
, line
, len
);
1111 patch
->new_oid_prefix
[len
] = 0;
1113 return gitdiff_oldmode(state
, ptr
+ 1, patch
);
1118 * This is normal for a diff that doesn't change anything: we'll fall through
1119 * into the next diff. Tell the parser to break out.
1121 static int gitdiff_unrecognized(struct gitdiff_data
*state UNUSED
,
1122 const char *line UNUSED
,
1123 struct patch
*patch UNUSED
)
1129 * Skip p_value leading components from "line"; as we do not accept
1130 * absolute paths, return NULL in that case.
1132 static const char *skip_tree_prefix(int p_value
,
1140 return (llen
&& line
[0] == '/') ? NULL
: line
;
1143 for (i
= 0; i
< llen
; i
++) {
1145 if (ch
== '/' && --nslash
<= 0)
1146 return (i
== 0) ? NULL
: &line
[i
+ 1];
1152 * This is to extract the same name that appears on "diff --git"
1153 * line. We do not find and return anything if it is a rename
1154 * patch, and it is OK because we will find the name elsewhere.
1155 * We need to reliably find name only when it is mode-change only,
1156 * creation or deletion of an empty file. In any of these cases,
1157 * both sides are the same name under a/ and b/ respectively.
1159 static char *git_header_name(int p_value
,
1164 const char *second
= NULL
;
1165 size_t len
, line_len
;
1167 line
+= strlen("diff --git ");
1168 llen
-= strlen("diff --git ");
1172 struct strbuf first
= STRBUF_INIT
;
1173 struct strbuf sp
= STRBUF_INIT
;
1175 if (unquote_c_style(&first
, line
, &second
))
1176 goto free_and_fail1
;
1178 /* strip the a/b prefix including trailing slash */
1179 cp
= skip_tree_prefix(p_value
, first
.buf
, first
.len
);
1181 goto free_and_fail1
;
1182 strbuf_remove(&first
, 0, cp
- first
.buf
);
1185 * second points at one past closing dq of name.
1186 * find the second name.
1188 while ((second
< line
+ llen
) && isspace(*second
))
1191 if (line
+ llen
<= second
)
1192 goto free_and_fail1
;
1193 if (*second
== '"') {
1194 if (unquote_c_style(&sp
, second
, NULL
))
1195 goto free_and_fail1
;
1196 cp
= skip_tree_prefix(p_value
, sp
.buf
, sp
.len
);
1198 goto free_and_fail1
;
1199 /* They must match, otherwise ignore */
1200 if (strcmp(cp
, first
.buf
))
1201 goto free_and_fail1
;
1202 strbuf_release(&sp
);
1203 return strbuf_detach(&first
, NULL
);
1206 /* unquoted second */
1207 cp
= skip_tree_prefix(p_value
, second
, line
+ llen
- second
);
1209 goto free_and_fail1
;
1210 if (line
+ llen
- cp
!= first
.len
||
1211 memcmp(first
.buf
, cp
, first
.len
))
1212 goto free_and_fail1
;
1213 return strbuf_detach(&first
, NULL
);
1216 strbuf_release(&first
);
1217 strbuf_release(&sp
);
1221 /* unquoted first name */
1222 name
= skip_tree_prefix(p_value
, line
, llen
);
1227 * since the first name is unquoted, a dq if exists must be
1228 * the beginning of the second name.
1230 for (second
= name
; second
< line
+ llen
; second
++) {
1231 if (*second
== '"') {
1232 struct strbuf sp
= STRBUF_INIT
;
1235 if (unquote_c_style(&sp
, second
, NULL
))
1236 goto free_and_fail2
;
1238 np
= skip_tree_prefix(p_value
, sp
.buf
, sp
.len
);
1240 goto free_and_fail2
;
1242 len
= sp
.buf
+ sp
.len
- np
;
1243 if (len
< second
- name
&&
1244 !strncmp(np
, name
, len
) &&
1245 isspace(name
[len
])) {
1247 strbuf_remove(&sp
, 0, np
- sp
.buf
);
1248 return strbuf_detach(&sp
, NULL
);
1252 strbuf_release(&sp
);
1258 * Accept a name only if it shows up twice, exactly the same
1261 second
= strchr(name
, '\n');
1264 line_len
= second
- name
;
1265 for (len
= 0 ; ; len
++) {
1266 switch (name
[len
]) {
1271 case '\t': case ' ':
1273 * Is this the separator between the preimage
1274 * and the postimage pathname? Again, we are
1275 * only interested in the case where there is
1276 * no rename, as this is only to set def_name
1277 * and a rename patch has the names elsewhere
1278 * in an unambiguous form.
1281 return NULL
; /* no postimage name */
1282 second
= skip_tree_prefix(p_value
, name
+ len
+ 1,
1283 line_len
- (len
+ 1));
1285 * If we are at the SP at the end of a directory,
1286 * skip_tree_prefix() may return NULL as that makes
1287 * it appears as if we have an absolute path.
1288 * Keep going to find another SP.
1294 * Does len bytes starting at "name" and "second"
1295 * (that are separated by one HT or SP we just
1296 * found) exactly match?
1298 if (second
[len
] == '\n' && !strncmp(name
, second
, len
))
1299 return xmemdupz(name
, len
);
1304 static int check_header_line(int linenr
, struct patch
*patch
)
1306 int extensions
= (patch
->is_delete
== 1) + (patch
->is_new
== 1) +
1307 (patch
->is_rename
== 1) + (patch
->is_copy
== 1);
1309 return error(_("inconsistent header lines %d and %d"),
1310 patch
->extension_linenr
, linenr
);
1311 if (extensions
&& !patch
->extension_linenr
)
1312 patch
->extension_linenr
= linenr
;
1316 int parse_git_diff_header(struct strbuf
*root
,
1322 struct patch
*patch
)
1324 unsigned long offset
;
1325 struct gitdiff_data parse_hdr_state
;
1327 /* A git diff has explicit new/delete information, so we don't guess */
1329 patch
->is_delete
= 0;
1332 * Some things may not have the old name in the
1333 * rest of the headers anywhere (pure mode changes,
1334 * or removing or adding empty files), so we get
1335 * the default name from the header.
1337 patch
->def_name
= git_header_name(p_value
, line
, len
);
1338 if (patch
->def_name
&& root
->len
) {
1339 char *s
= xstrfmt("%s%s", root
->buf
, patch
->def_name
);
1340 free(patch
->def_name
);
1341 patch
->def_name
= s
;
1347 parse_hdr_state
.root
= root
;
1348 parse_hdr_state
.linenr
= *linenr
;
1349 parse_hdr_state
.p_value
= p_value
;
1351 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, (*linenr
)++) {
1352 static const struct opentry
{
1354 int (*fn
)(struct gitdiff_data
*, const char *, struct patch
*);
1356 { "@@ -", gitdiff_hdrend
},
1357 { "--- ", gitdiff_oldname
},
1358 { "+++ ", gitdiff_newname
},
1359 { "old mode ", gitdiff_oldmode
},
1360 { "new mode ", gitdiff_newmode
},
1361 { "deleted file mode ", gitdiff_delete
},
1362 { "new file mode ", gitdiff_newfile
},
1363 { "copy from ", gitdiff_copysrc
},
1364 { "copy to ", gitdiff_copydst
},
1365 { "rename old ", gitdiff_renamesrc
},
1366 { "rename new ", gitdiff_renamedst
},
1367 { "rename from ", gitdiff_renamesrc
},
1368 { "rename to ", gitdiff_renamedst
},
1369 { "similarity index ", gitdiff_similarity
},
1370 { "dissimilarity index ", gitdiff_dissimilarity
},
1371 { "index ", gitdiff_index
},
1372 { "", gitdiff_unrecognized
},
1376 len
= linelen(line
, size
);
1377 if (!len
|| line
[len
-1] != '\n')
1379 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
1380 const struct opentry
*p
= optable
+ i
;
1381 int oplen
= strlen(p
->str
);
1383 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
1385 res
= p
->fn(&parse_hdr_state
, line
+ oplen
, patch
);
1388 if (check_header_line(*linenr
, patch
))
1397 if (!patch
->old_name
&& !patch
->new_name
) {
1398 if (!patch
->def_name
) {
1399 error(Q_("git diff header lacks filename information when removing "
1400 "%d leading pathname component (line %d)",
1401 "git diff header lacks filename information when removing "
1402 "%d leading pathname components (line %d)",
1403 parse_hdr_state
.p_value
),
1404 parse_hdr_state
.p_value
, *linenr
);
1407 patch
->old_name
= xstrdup(patch
->def_name
);
1408 patch
->new_name
= xstrdup(patch
->def_name
);
1410 if ((!patch
->new_name
&& !patch
->is_delete
) ||
1411 (!patch
->old_name
&& !patch
->is_new
)) {
1412 error(_("git diff header lacks filename information "
1413 "(line %d)"), *linenr
);
1416 patch
->is_toplevel_relative
= 1;
1420 static int parse_num(const char *line
, unsigned long *p
)
1424 if (!isdigit(*line
))
1426 *p
= strtoul(line
, &ptr
, 10);
1430 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
1431 unsigned long *p1
, unsigned long *p2
)
1435 if (offset
< 0 || offset
>= len
)
1440 digits
= parse_num(line
, p1
);
1450 digits
= parse_num(line
+1, p2
);
1459 ex
= strlen(expect
);
1462 if (memcmp(line
, expect
, ex
))
1468 static void recount_diff(const char *line
, int size
, struct fragment
*fragment
)
1470 int oldlines
= 0, newlines
= 0, ret
= 0;
1473 warning("recount: ignore empty hunk");
1478 int len
= linelen(line
, size
);
1486 case ' ': case '\n':
1498 ret
= size
< 3 || !starts_with(line
, "@@ ");
1501 ret
= size
< 5 || !starts_with(line
, "diff ");
1508 warning(_("recount: unexpected line: %.*s"),
1509 (int)linelen(line
, size
), line
);
1514 fragment
->oldlines
= oldlines
;
1515 fragment
->newlines
= newlines
;
1519 * Parse a unified diff fragment header of the
1520 * form "@@ -a,b +c,d @@"
1522 static int parse_fragment_header(const char *line
, int len
, struct fragment
*fragment
)
1526 if (!len
|| line
[len
-1] != '\n')
1529 /* Figure out the number of lines in a fragment */
1530 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
1531 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
1537 * Find file diff header
1540 * -1 if no header was found
1541 * -128 in case of error
1542 * the size of the header in bytes (called "offset") otherwise
1544 static int find_header(struct apply_state
*state
,
1548 struct patch
*patch
)
1550 unsigned long offset
, len
;
1552 patch
->is_toplevel_relative
= 0;
1553 patch
->is_rename
= patch
->is_copy
= 0;
1554 patch
->is_new
= patch
->is_delete
= -1;
1555 patch
->old_mode
= patch
->new_mode
= 0;
1556 patch
->old_name
= patch
->new_name
= NULL
;
1557 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1558 unsigned long nextlen
;
1560 len
= linelen(line
, size
);
1564 /* Testing this early allows us to take a few shortcuts.. */
1569 * Make sure we don't find any unconnected patch fragments.
1570 * That's a sign that we didn't find a header, and that a
1571 * patch has become corrupted/broken up.
1573 if (!memcmp("@@ -", line
, 4)) {
1574 struct fragment dummy
;
1575 if (parse_fragment_header(line
, len
, &dummy
) < 0)
1577 error(_("patch fragment without header at line %d: %.*s"),
1578 state
->linenr
, (int)len
-1, line
);
1586 * Git patch? It might not have a real patch, just a rename
1587 * or mode change, so we handle that specially
1589 if (!memcmp("diff --git ", line
, 11)) {
1590 int git_hdr_len
= parse_git_diff_header(&state
->root
, &state
->linenr
,
1591 state
->p_value
, line
, len
,
1593 if (git_hdr_len
< 0)
1595 if (git_hdr_len
<= len
)
1597 *hdrsize
= git_hdr_len
;
1601 /* --- followed by +++ ? */
1602 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
1606 * We only accept unified patches, so we want it to
1607 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1608 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1610 nextlen
= linelen(line
+ len
, size
- len
);
1611 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
1614 /* Ok, we'll consider it a patch */
1615 if (parse_traditional_patch(state
, line
, line
+len
, patch
))
1617 *hdrsize
= len
+ nextlen
;
1624 static void record_ws_error(struct apply_state
*state
,
1635 state
->whitespace_error
++;
1636 if (state
->squelch_whitespace_errors
&&
1637 state
->squelch_whitespace_errors
< state
->whitespace_error
)
1640 err
= whitespace_error_string(result
);
1641 if (state
->apply_verbosity
> verbosity_silent
)
1642 fprintf(stderr
, "%s:%d: %s.\n%.*s\n",
1643 state
->patch_input_file
, linenr
, err
, len
, line
);
1647 static void check_whitespace(struct apply_state
*state
,
1652 unsigned result
= ws_check(line
+ 1, len
- 1, ws_rule
);
1654 record_ws_error(state
, result
, line
+ 1, len
- 2, state
->linenr
);
1658 * Check if the patch has context lines with CRLF or
1659 * the patch wants to remove lines with CRLF.
1661 static void check_old_for_crlf(struct patch
*patch
, const char *line
, int len
)
1663 if (len
>= 2 && line
[len
-1] == '\n' && line
[len
-2] == '\r') {
1664 patch
->ws_rule
|= WS_CR_AT_EOL
;
1665 patch
->crlf_in_old
= 1;
1671 * Parse a unified diff. Note that this really needs to parse each
1672 * fragment separately, since the only way to know the difference
1673 * between a "---" that is part of a patch, and a "---" that starts
1674 * the next patch is to look at the line counts..
1676 static int parse_fragment(struct apply_state
*state
,
1679 struct patch
*patch
,
1680 struct fragment
*fragment
)
1683 int len
= linelen(line
, size
), offset
;
1684 unsigned long oldlines
, newlines
;
1685 unsigned long leading
, trailing
;
1687 offset
= parse_fragment_header(line
, len
, fragment
);
1690 if (offset
> 0 && patch
->recount
)
1691 recount_diff(line
+ offset
, size
- offset
, fragment
);
1692 oldlines
= fragment
->oldlines
;
1693 newlines
= fragment
->newlines
;
1697 /* Parse the thing.. */
1701 added
= deleted
= 0;
1704 offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1705 if (!oldlines
&& !newlines
)
1707 len
= linelen(line
, size
);
1708 if (!len
|| line
[len
-1] != '\n')
1713 case '\n': /* newer GNU diff, an empty context line */
1717 if (!deleted
&& !added
)
1720 check_old_for_crlf(patch
, line
, len
);
1721 if (!state
->apply_in_reverse
&&
1722 state
->ws_error_action
== correct_ws_error
)
1723 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1726 if (!state
->apply_in_reverse
)
1727 check_old_for_crlf(patch
, line
, len
);
1728 if (state
->apply_in_reverse
&&
1729 state
->ws_error_action
!= nowarn_ws_error
)
1730 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1736 if (state
->apply_in_reverse
)
1737 check_old_for_crlf(patch
, line
, len
);
1738 if (!state
->apply_in_reverse
&&
1739 state
->ws_error_action
!= nowarn_ws_error
)
1740 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1747 * We allow "\ No newline at end of file". Depending
1748 * on locale settings when the patch was produced we
1749 * don't know what this line looks like. The only
1750 * thing we do know is that it begins with "\ ".
1751 * Checking for 12 is just for sanity check -- any
1752 * l10n of "\ No newline..." is at least that long.
1755 if (len
< 12 || memcmp(line
, "\\ ", 2))
1760 if (oldlines
|| newlines
)
1762 if (!patch
->recount
&& !deleted
&& !added
)
1765 fragment
->leading
= leading
;
1766 fragment
->trailing
= trailing
;
1769 * If a fragment ends with an incomplete line, we failed to include
1770 * it in the above loop because we hit oldlines == newlines == 0
1773 if (12 < size
&& !memcmp(line
, "\\ ", 2))
1774 offset
+= linelen(line
, size
);
1776 patch
->lines_added
+= added
;
1777 patch
->lines_deleted
+= deleted
;
1779 if (0 < patch
->is_new
&& oldlines
)
1780 return error(_("new file depends on old contents"));
1781 if (0 < patch
->is_delete
&& newlines
)
1782 return error(_("deleted file still has contents"));
1787 * We have seen "diff --git a/... b/..." header (or a traditional patch
1788 * header). Read hunks that belong to this patch into fragments and hang
1789 * them to the given patch structure.
1791 * The (fragment->patch, fragment->size) pair points into the memory given
1792 * by the caller, not a copy, when we return.
1795 * -1 in case of error,
1796 * the number of bytes in the patch otherwise.
1798 static int parse_single_patch(struct apply_state
*state
,
1801 struct patch
*patch
)
1803 unsigned long offset
= 0;
1804 unsigned long oldlines
= 0, newlines
= 0, context
= 0;
1805 struct fragment
**fragp
= &patch
->fragments
;
1807 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
1808 struct fragment
*fragment
;
1811 CALLOC_ARRAY(fragment
, 1);
1812 fragment
->linenr
= state
->linenr
;
1813 len
= parse_fragment(state
, line
, size
, patch
, fragment
);
1816 return error(_("corrupt patch at line %d"), state
->linenr
);
1818 fragment
->patch
= line
;
1819 fragment
->size
= len
;
1820 oldlines
+= fragment
->oldlines
;
1821 newlines
+= fragment
->newlines
;
1822 context
+= fragment
->leading
+ fragment
->trailing
;
1825 fragp
= &fragment
->next
;
1833 * If something was removed (i.e. we have old-lines) it cannot
1834 * be creation, and if something was added it cannot be
1835 * deletion. However, the reverse is not true; --unified=0
1836 * patches that only add are not necessarily creation even
1837 * though they do not have any old lines, and ones that only
1838 * delete are not necessarily deletion.
1840 * Unfortunately, a real creation/deletion patch do _not_ have
1841 * any context line by definition, so we cannot safely tell it
1842 * apart with --unified=0 insanity. At least if the patch has
1843 * more than one hunk it is not creation or deletion.
1845 if (patch
->is_new
< 0 &&
1846 (oldlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1848 if (patch
->is_delete
< 0 &&
1849 (newlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1850 patch
->is_delete
= 0;
1852 if (0 < patch
->is_new
&& oldlines
)
1853 return error(_("new file %s depends on old contents"), patch
->new_name
);
1854 if (0 < patch
->is_delete
&& newlines
)
1855 return error(_("deleted file %s still has contents"), patch
->old_name
);
1856 if (!patch
->is_delete
&& !newlines
&& context
&& state
->apply_verbosity
> verbosity_silent
)
1859 "file %s becomes empty but is not deleted"),
1865 static inline int metadata_changes(struct patch
*patch
)
1867 return patch
->is_rename
> 0 ||
1868 patch
->is_copy
> 0 ||
1869 patch
->is_new
> 0 ||
1871 (patch
->old_mode
&& patch
->new_mode
&&
1872 patch
->old_mode
!= patch
->new_mode
);
1875 static char *inflate_it(const void *data
, unsigned long size
,
1876 unsigned long inflated_size
)
1882 memset(&stream
, 0, sizeof(stream
));
1884 stream
.next_in
= (unsigned char *)data
;
1885 stream
.avail_in
= size
;
1886 stream
.next_out
= out
= xmalloc(inflated_size
);
1887 stream
.avail_out
= inflated_size
;
1888 git_inflate_init(&stream
);
1889 st
= git_inflate(&stream
, Z_FINISH
);
1890 git_inflate_end(&stream
);
1891 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1899 * Read a binary hunk and return a new fragment; fragment->patch
1900 * points at an allocated memory that the caller must free, so
1901 * it is marked as "->free_patch = 1".
1903 static struct fragment
*parse_binary_hunk(struct apply_state
*state
,
1905 unsigned long *sz_p
,
1910 * Expect a line that begins with binary patch method ("literal"
1911 * or "delta"), followed by the length of data before deflating.
1912 * a sequence of 'length-byte' followed by base-85 encoded data
1913 * should follow, terminated by a newline.
1915 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1916 * and we would limit the patch line to 66 characters,
1917 * so one line can fit up to 13 groups that would decode
1918 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1919 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1922 unsigned long size
= *sz_p
;
1923 char *buffer
= *buf_p
;
1925 unsigned long origlen
;
1928 struct fragment
*frag
;
1930 llen
= linelen(buffer
, size
);
1935 if (starts_with(buffer
, "delta ")) {
1936 patch_method
= BINARY_DELTA_DEFLATED
;
1937 origlen
= strtoul(buffer
+ 6, NULL
, 10);
1939 else if (starts_with(buffer
, "literal ")) {
1940 patch_method
= BINARY_LITERAL_DEFLATED
;
1941 origlen
= strtoul(buffer
+ 8, NULL
, 10);
1950 int byte_length
, max_byte_length
, newsize
;
1951 llen
= linelen(buffer
, size
);
1955 /* consume the blank line */
1961 * Minimum line is "A00000\n" which is 7-byte long,
1962 * and the line length must be multiple of 5 plus 2.
1964 if ((llen
< 7) || (llen
-2) % 5)
1966 max_byte_length
= (llen
- 2) / 5 * 4;
1967 byte_length
= *buffer
;
1968 if ('A' <= byte_length
&& byte_length
<= 'Z')
1969 byte_length
= byte_length
- 'A' + 1;
1970 else if ('a' <= byte_length
&& byte_length
<= 'z')
1971 byte_length
= byte_length
- 'a' + 27;
1974 /* if the input length was not multiple of 4, we would
1975 * have filler at the end but the filler should never
1978 if (max_byte_length
< byte_length
||
1979 byte_length
<= max_byte_length
- 4)
1981 newsize
= hunk_size
+ byte_length
;
1982 data
= xrealloc(data
, newsize
);
1983 if (decode_85(data
+ hunk_size
, buffer
+ 1, byte_length
))
1985 hunk_size
= newsize
;
1990 CALLOC_ARRAY(frag
, 1);
1991 frag
->patch
= inflate_it(data
, hunk_size
, origlen
);
1992 frag
->free_patch
= 1;
1996 frag
->size
= origlen
;
2000 frag
->binary_patch_method
= patch_method
;
2006 error(_("corrupt binary patch at line %d: %.*s"),
2007 state
->linenr
-1, llen
-1, buffer
);
2013 * -1 in case of error,
2014 * the length of the parsed binary patch otherwise
2016 static int parse_binary(struct apply_state
*state
,
2019 struct patch
*patch
)
2022 * We have read "GIT binary patch\n"; what follows is a line
2023 * that says the patch method (currently, either "literal" or
2024 * "delta") and the length of data before deflating; a
2025 * sequence of 'length-byte' followed by base-85 encoded data
2028 * When a binary patch is reversible, there is another binary
2029 * hunk in the same format, starting with patch method (either
2030 * "literal" or "delta") with the length of data, and a sequence
2031 * of length-byte + base-85 encoded data, terminated with another
2032 * empty line. This data, when applied to the postimage, produces
2035 struct fragment
*forward
;
2036 struct fragment
*reverse
;
2040 forward
= parse_binary_hunk(state
, &buffer
, &size
, &status
, &used
);
2041 if (!forward
&& !status
)
2042 /* there has to be one hunk (forward hunk) */
2043 return error(_("unrecognized binary patch at line %d"), state
->linenr
-1);
2045 /* otherwise we already gave an error message */
2048 reverse
= parse_binary_hunk(state
, &buffer
, &size
, &status
, &used_1
);
2053 * Not having reverse hunk is not an error, but having
2054 * a corrupt reverse hunk is.
2056 free((void*) forward
->patch
);
2060 forward
->next
= reverse
;
2061 patch
->fragments
= forward
;
2062 patch
->is_binary
= 1;
2066 static void prefix_one(struct apply_state
*state
, char **name
)
2068 char *old_name
= *name
;
2071 *name
= prefix_filename(state
->prefix
, *name
);
2075 static void prefix_patch(struct apply_state
*state
, struct patch
*p
)
2077 if (!state
->prefix
|| p
->is_toplevel_relative
)
2079 prefix_one(state
, &p
->new_name
);
2080 prefix_one(state
, &p
->old_name
);
2087 static void add_name_limit(struct apply_state
*state
,
2091 struct string_list_item
*it
;
2093 it
= string_list_append(&state
->limit_by_name
, name
);
2094 it
->util
= exclude
? NULL
: (void *) 1;
2097 static int use_patch(struct apply_state
*state
, struct patch
*p
)
2099 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
2102 /* Paths outside are not touched regardless of "--include" */
2103 if (state
->prefix
&& *state
->prefix
) {
2105 if (!skip_prefix(pathname
, state
->prefix
, &rest
) || !*rest
)
2109 /* See if it matches any of exclude/include rule */
2110 for (i
= 0; i
< state
->limit_by_name
.nr
; i
++) {
2111 struct string_list_item
*it
= &state
->limit_by_name
.items
[i
];
2112 if (!wildmatch(it
->string
, pathname
, 0))
2113 return (it
->util
!= NULL
);
2117 * If we had any include, a path that does not match any rule is
2118 * not used. Otherwise, we saw bunch of exclude rules (or none)
2119 * and such a path is used.
2121 return !state
->has_include
;
2125 * Read the patch text in "buffer" that extends for "size" bytes; stop
2126 * reading after seeing a single patch (i.e. changes to a single file).
2127 * Create fragments (i.e. patch hunks) and hang them to the given patch.
2130 * -1 if no header was found or parse_binary() failed,
2131 * -128 on another error,
2132 * the number of bytes consumed otherwise,
2133 * so that the caller can call us again for the next patch.
2135 static int parse_chunk(struct apply_state
*state
, char *buffer
, unsigned long size
, struct patch
*patch
)
2137 int hdrsize
, patchsize
;
2138 int offset
= find_header(state
, buffer
, size
, &hdrsize
, patch
);
2143 prefix_patch(state
, patch
);
2145 if (!use_patch(state
, patch
))
2147 else if (patch
->new_name
)
2148 patch
->ws_rule
= whitespace_rule(state
->repo
->index
,
2151 patch
->ws_rule
= whitespace_rule(state
->repo
->index
,
2154 patchsize
= parse_single_patch(state
,
2155 buffer
+ offset
+ hdrsize
,
2156 size
- offset
- hdrsize
,
2163 static const char git_binary
[] = "GIT binary patch\n";
2164 int hd
= hdrsize
+ offset
;
2165 unsigned long llen
= linelen(buffer
+ hd
, size
- hd
);
2167 if (llen
== sizeof(git_binary
) - 1 &&
2168 !memcmp(git_binary
, buffer
+ hd
, llen
)) {
2171 used
= parse_binary(state
, buffer
+ hd
+ llen
,
2172 size
- hd
- llen
, patch
);
2176 patchsize
= used
+ llen
;
2180 else if (!memcmp(" differ\n", buffer
+ hd
+ llen
- 8, 8)) {
2181 static const char *binhdr
[] = {
2187 for (i
= 0; binhdr
[i
]; i
++) {
2188 int len
= strlen(binhdr
[i
]);
2189 if (len
< size
- hd
&&
2190 !memcmp(binhdr
[i
], buffer
+ hd
, len
)) {
2192 patch
->is_binary
= 1;
2199 /* Empty patch cannot be applied if it is a text patch
2200 * without metadata change. A binary patch appears
2203 if ((state
->apply
|| state
->check
) &&
2204 (!patch
->is_binary
&& !metadata_changes(patch
))) {
2205 error(_("patch with only garbage at line %d"), state
->linenr
);
2210 return offset
+ hdrsize
+ patchsize
;
2213 static void reverse_patches(struct patch
*p
)
2215 for (; p
; p
= p
->next
) {
2216 struct fragment
*frag
= p
->fragments
;
2218 SWAP(p
->new_name
, p
->old_name
);
2220 SWAP(p
->new_mode
, p
->old_mode
);
2221 SWAP(p
->is_new
, p
->is_delete
);
2222 SWAP(p
->lines_added
, p
->lines_deleted
);
2223 SWAP(p
->old_oid_prefix
, p
->new_oid_prefix
);
2225 for (; frag
; frag
= frag
->next
) {
2226 SWAP(frag
->newpos
, frag
->oldpos
);
2227 SWAP(frag
->newlines
, frag
->oldlines
);
2232 static const char pluses
[] =
2233 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2234 static const char minuses
[]=
2235 "----------------------------------------------------------------------";
2237 static void show_stats(struct apply_state
*state
, struct patch
*patch
)
2239 struct strbuf qname
= STRBUF_INIT
;
2240 char *cp
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
2243 quote_c_style(cp
, &qname
, NULL
, 0);
2246 * "scale" the filename
2248 max
= state
->max_len
;
2252 if (qname
.len
> max
) {
2253 cp
= strchr(qname
.buf
+ qname
.len
+ 3 - max
, '/');
2255 cp
= qname
.buf
+ qname
.len
+ 3 - max
;
2256 strbuf_splice(&qname
, 0, cp
- qname
.buf
, "...", 3);
2259 if (patch
->is_binary
) {
2260 printf(" %-*s | Bin\n", max
, qname
.buf
);
2261 strbuf_release(&qname
);
2265 printf(" %-*s |", max
, qname
.buf
);
2266 strbuf_release(&qname
);
2269 * scale the add/delete
2271 max
= max
+ state
->max_change
> 70 ? 70 - max
: state
->max_change
;
2272 add
= patch
->lines_added
;
2273 del
= patch
->lines_deleted
;
2275 if (state
->max_change
> 0) {
2276 int total
= ((add
+ del
) * max
+ state
->max_change
/ 2) / state
->max_change
;
2277 add
= (add
* max
+ state
->max_change
/ 2) / state
->max_change
;
2280 printf("%5d %.*s%.*s\n", patch
->lines_added
+ patch
->lines_deleted
,
2281 add
, pluses
, del
, minuses
);
2284 static int read_old_data(struct stat
*st
, struct patch
*patch
,
2285 const char *path
, struct strbuf
*buf
)
2287 int conv_flags
= patch
->crlf_in_old
?
2288 CONV_EOL_KEEP_CRLF
: CONV_EOL_RENORMALIZE
;
2289 switch (st
->st_mode
& S_IFMT
) {
2291 if (strbuf_readlink(buf
, path
, st
->st_size
) < 0)
2292 return error(_("unable to read symlink %s"), path
);
2295 if (strbuf_read_file(buf
, path
, st
->st_size
) != st
->st_size
)
2296 return error(_("unable to open or read %s"), path
);
2298 * "git apply" without "--index/--cached" should never look
2299 * at the index; the target file may not have been added to
2300 * the index yet, and we may not even be in any Git repository.
2301 * Pass NULL to convert_to_git() to stress this; the function
2302 * should never look at the index when explicit crlf option
2305 convert_to_git(NULL
, path
, buf
->buf
, buf
->len
, buf
, conv_flags
);
2313 * Update the preimage, and the common lines in postimage,
2314 * from buffer buf of length len.
2316 static void update_pre_post_images(struct image
*preimage
,
2317 struct image
*postimage
,
2318 char *buf
, size_t len
)
2320 struct image fixed_preimage
= IMAGE_INIT
;
2321 size_t insert_pos
= 0;
2322 int i
, ctx
, reduced
;
2326 * Update the preimage with whitespace fixes. Note that we
2327 * are not losing preimage->buf -- apply_one_fragment() will
2330 image_prepare(&fixed_preimage
, buf
, len
, 1);
2331 for (i
= 0; i
< fixed_preimage
.line_nr
; i
++)
2332 fixed_preimage
.line
[i
].flag
= preimage
->line
[i
].flag
;
2333 image_clear(preimage
);
2334 *preimage
= fixed_preimage
;
2335 fixed
= preimage
->buf
.buf
;
2338 * Adjust the common context lines in postimage.
2340 for (i
= reduced
= ctx
= 0; i
< postimage
->line_nr
; i
++) {
2341 size_t l_len
= postimage
->line
[i
].len
;
2343 if (!(postimage
->line
[i
].flag
& LINE_COMMON
)) {
2344 /* an added line -- no counterparts in preimage */
2345 insert_pos
+= l_len
;
2349 /* and find the corresponding one in the fixed preimage */
2350 while (ctx
< preimage
->line_nr
&&
2351 !(preimage
->line
[ctx
].flag
& LINE_COMMON
)) {
2352 fixed
+= preimage
->line
[ctx
].len
;
2357 * preimage is expected to run out, if the caller
2358 * fixed addition of trailing blank lines.
2360 if (preimage
->line_nr
<= ctx
) {
2365 /* and copy it in, while fixing the line length */
2366 l_len
= preimage
->line
[ctx
].len
;
2367 strbuf_splice(&postimage
->buf
, insert_pos
, postimage
->line
[i
].len
,
2369 insert_pos
+= l_len
;
2371 postimage
->line
[i
].len
= l_len
;
2375 /* Fix the length of the whole thing */
2376 postimage
->line_nr
-= reduced
;
2380 * Compare lines s1 of length n1 and s2 of length n2, ignoring
2381 * whitespace difference. Returns 1 if they match, 0 otherwise
2383 static int fuzzy_matchlines(const char *s1
, size_t n1
,
2384 const char *s2
, size_t n2
)
2386 const char *end1
= s1
+ n1
;
2387 const char *end2
= s2
+ n2
;
2389 /* ignore line endings */
2390 while (s1
< end1
&& (end1
[-1] == '\r' || end1
[-1] == '\n'))
2392 while (s2
< end2
&& (end2
[-1] == '\r' || end2
[-1] == '\n'))
2395 while (s1
< end1
&& s2
< end2
) {
2398 * Skip whitespace. We check on both buffers
2399 * because we don't want "a b" to match "ab".
2403 while (s1
< end1
&& isspace(*s1
))
2405 while (s2
< end2
&& isspace(*s2
))
2407 } else if (*s1
++ != *s2
++)
2411 /* If we reached the end on one side only, lines don't match. */
2412 return s1
== end1
&& s2
== end2
;
2415 static int line_by_line_fuzzy_match(struct image
*img
,
2416 struct image
*preimage
,
2417 struct image
*postimage
,
2418 unsigned long current
,
2429 struct strbuf fixed
;
2433 for (i
= 0; i
< preimage_limit
; i
++) {
2434 size_t prelen
= preimage
->line
[i
].len
;
2435 size_t imglen
= img
->line
[current_lno
+i
].len
;
2437 if (!fuzzy_matchlines(img
->buf
.buf
+ current
+ imgoff
, imglen
,
2438 preimage
->buf
.buf
+ preoff
, prelen
))
2445 * Ok, the preimage matches with whitespace fuzz.
2447 * imgoff now holds the true length of the target that
2448 * matches the preimage before the end of the file.
2450 * Count the number of characters in the preimage that fall
2451 * beyond the end of the file and make sure that all of them
2452 * are whitespace characters. (This can only happen if
2453 * we are removing blank lines at the end of the file.)
2455 buf
= preimage_eof
= preimage
->buf
.buf
+ preoff
;
2456 for ( ; i
< preimage
->line_nr
; i
++)
2457 preoff
+= preimage
->line
[i
].len
;
2458 preimage_end
= preimage
->buf
.buf
+ preoff
;
2459 for ( ; buf
< preimage_end
; buf
++)
2464 * Update the preimage and the common postimage context
2465 * lines to use the same whitespace as the target.
2466 * If whitespace is missing in the target (i.e.
2467 * if the preimage extends beyond the end of the file),
2468 * use the whitespace from the preimage.
2470 extra_chars
= preimage_end
- preimage_eof
;
2471 strbuf_init(&fixed
, imgoff
+ extra_chars
);
2472 strbuf_add(&fixed
, img
->buf
.buf
+ current
, imgoff
);
2473 strbuf_add(&fixed
, preimage_eof
, extra_chars
);
2474 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2475 update_pre_post_images(preimage
, postimage
,
2476 fixed_buf
, fixed_len
);
2480 static int match_fragment(struct apply_state
*state
,
2482 struct image
*preimage
,
2483 struct image
*postimage
,
2484 unsigned long current
,
2487 int match_beginning
, int match_end
)
2490 const char *orig
, *target
;
2491 struct strbuf fixed
= STRBUF_INIT
;
2497 if (preimage
->line_nr
+ current_lno
<= img
->line_nr
) {
2499 * The hunk falls within the boundaries of img.
2501 preimage_limit
= preimage
->line_nr
;
2502 if (match_end
&& (preimage
->line_nr
+ current_lno
!= img
->line_nr
)) {
2506 } else if (state
->ws_error_action
== correct_ws_error
&&
2507 (ws_rule
& WS_BLANK_AT_EOF
)) {
2509 * This hunk extends beyond the end of img, and we are
2510 * removing blank lines at the end of the file. This
2511 * many lines from the beginning of the preimage must
2512 * match with img, and the remainder of the preimage
2515 preimage_limit
= img
->line_nr
- current_lno
;
2518 * The hunk extends beyond the end of the img and
2519 * we are not removing blanks at the end, so we
2520 * should reject the hunk at this position.
2526 if (match_beginning
&& current_lno
) {
2531 /* Quick hash check */
2532 for (i
= 0; i
< preimage_limit
; i
++) {
2533 if ((img
->line
[current_lno
+ i
].flag
& LINE_PATCHED
) ||
2534 (preimage
->line
[i
].hash
!= img
->line
[current_lno
+ i
].hash
)) {
2540 if (preimage_limit
== preimage
->line_nr
) {
2542 * Do we have an exact match? If we were told to match
2543 * at the end, size must be exactly at current+fragsize,
2544 * otherwise current+fragsize must be still within the preimage,
2545 * and either case, the old piece should match the preimage
2549 ? (current
+ preimage
->buf
.len
== img
->buf
.len
)
2550 : (current
+ preimage
->buf
.len
<= img
->buf
.len
)) &&
2551 !memcmp(img
->buf
.buf
+ current
, preimage
->buf
.buf
, preimage
->buf
.len
)) {
2557 * The preimage extends beyond the end of img, so
2558 * there cannot be an exact match.
2560 * There must be one non-blank context line that match
2561 * a line before the end of img.
2563 const char *buf
, *buf_end
;
2565 buf
= preimage
->buf
.buf
;
2567 for (i
= 0; i
< preimage_limit
; i
++)
2568 buf_end
+= preimage
->line
[i
].len
;
2570 for ( ; buf
< buf_end
; buf
++)
2573 if (buf
== buf_end
) {
2580 * No exact match. If we are ignoring whitespace, run a line-by-line
2581 * fuzzy matching. We collect all the line length information because
2582 * we need it to adjust whitespace if we match.
2584 if (state
->ws_ignore_action
== ignore_ws_change
) {
2585 ret
= line_by_line_fuzzy_match(img
, preimage
, postimage
,
2586 current
, current_lno
, preimage_limit
);
2590 if (state
->ws_error_action
!= correct_ws_error
) {
2596 * The hunk does not apply byte-by-byte, but the hash says
2597 * it might with whitespace fuzz. We weren't asked to
2598 * ignore whitespace, we were asked to correct whitespace
2599 * errors, so let's try matching after whitespace correction.
2601 * While checking the preimage against the target, whitespace
2602 * errors in both fixed, we count how large the corresponding
2603 * postimage needs to be. The postimage prepared by
2604 * apply_one_fragment() has whitespace errors fixed on added
2605 * lines already, but the common lines were propagated as-is,
2606 * which may become longer when their whitespace errors are
2611 * The preimage may extend beyond the end of the file,
2612 * but in this loop we will only handle the part of the
2613 * preimage that falls within the file.
2615 strbuf_grow(&fixed
, preimage
->buf
.len
+ 1);
2616 orig
= preimage
->buf
.buf
;
2617 target
= img
->buf
.buf
+ current
;
2618 for (i
= 0; i
< preimage_limit
; i
++) {
2619 size_t oldlen
= preimage
->line
[i
].len
;
2620 size_t tgtlen
= img
->line
[current_lno
+ i
].len
;
2621 size_t fixstart
= fixed
.len
;
2622 struct strbuf tgtfix
;
2625 /* Try fixing the line in the preimage */
2626 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2628 /* Try fixing the line in the target */
2629 strbuf_init(&tgtfix
, tgtlen
);
2630 ws_fix_copy(&tgtfix
, target
, tgtlen
, ws_rule
, NULL
);
2633 * If they match, either the preimage was based on
2634 * a version before our tree fixed whitespace breakage,
2635 * or we are lacking a whitespace-fix patch the tree
2636 * the preimage was based on already had (i.e. target
2637 * has whitespace breakage, the preimage doesn't).
2638 * In either case, we are fixing the whitespace breakages
2639 * so we might as well take the fix together with their
2642 match
= (tgtfix
.len
== fixed
.len
- fixstart
&&
2643 !memcmp(tgtfix
.buf
, fixed
.buf
+ fixstart
,
2644 fixed
.len
- fixstart
));
2646 strbuf_release(&tgtfix
);
2658 * Now handle the lines in the preimage that falls beyond the
2659 * end of the file (if any). They will only match if they are
2660 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2663 for ( ; i
< preimage
->line_nr
; i
++) {
2664 size_t fixstart
= fixed
.len
; /* start of the fixed preimage */
2665 size_t oldlen
= preimage
->line
[i
].len
;
2668 /* Try fixing the line in the preimage */
2669 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2671 for (j
= fixstart
; j
< fixed
.len
; j
++) {
2672 if (!isspace(fixed
.buf
[j
])) {
2683 * Yes, the preimage is based on an older version that still
2684 * has whitespace breakages unfixed, and fixing them makes the
2685 * hunk match. Update the context lines in the postimage.
2687 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2688 update_pre_post_images(preimage
, postimage
,
2689 fixed_buf
, fixed_len
);
2694 strbuf_release(&fixed
);
2698 static int find_pos(struct apply_state
*state
,
2700 struct image
*preimage
,
2701 struct image
*postimage
,
2704 int match_beginning
, int match_end
)
2707 unsigned long backwards
, forwards
, current
;
2708 int backwards_lno
, forwards_lno
, current_lno
;
2711 * When running with --allow-overlap, it is possible that a hunk is
2712 * seen that pretends to start at the beginning (but no longer does),
2713 * and that *still* needs to match the end. So trust `match_end` more
2714 * than `match_beginning`.
2716 if (state
->allow_overlap
&& match_beginning
&& match_end
&&
2717 img
->line_nr
- preimage
->line_nr
!= 0)
2718 match_beginning
= 0;
2721 * If match_beginning or match_end is specified, there is no
2722 * point starting from a wrong line that will never match and
2723 * wander around and wait for a match at the specified end.
2725 if (match_beginning
)
2728 line
= img
->line_nr
- preimage
->line_nr
;
2731 * Because the comparison is unsigned, the following test
2732 * will also take care of a negative line number that can
2733 * result when match_end and preimage is larger than the target.
2735 if ((size_t) line
> img
->line_nr
)
2736 line
= img
->line_nr
;
2739 for (i
= 0; i
< line
; i
++)
2740 current
+= img
->line
[i
].len
;
2743 * There's probably some smart way to do this, but I'll leave
2744 * that to the smart and beautiful people. I'm simple and stupid.
2746 backwards
= current
;
2747 backwards_lno
= line
;
2749 forwards_lno
= line
;
2752 for (i
= 0; ; i
++) {
2753 if (match_fragment(state
, img
, preimage
, postimage
,
2754 current
, current_lno
, ws_rule
,
2755 match_beginning
, match_end
))
2759 if (backwards_lno
== 0 && forwards_lno
== img
->line_nr
)
2763 if (backwards_lno
== 0) {
2768 backwards
-= img
->line
[backwards_lno
].len
;
2769 current
= backwards
;
2770 current_lno
= backwards_lno
;
2772 if (forwards_lno
== img
->line_nr
) {
2776 forwards
+= img
->line
[forwards_lno
].len
;
2779 current_lno
= forwards_lno
;
2787 * The change from "preimage" and "postimage" has been found to
2788 * apply at applied_pos (counts in line numbers) in "img".
2789 * Update "img" to remove "preimage" and replace it with "postimage".
2791 static void update_image(struct apply_state
*state
,
2794 struct image
*preimage
,
2795 struct image
*postimage
)
2798 * remove the copy of preimage at offset in img
2799 * and replace it with postimage
2802 size_t remove_count
, insert_count
, applied_at
= 0;
2803 size_t result_alloc
;
2808 * If we are removing blank lines at the end of img,
2809 * the preimage may extend beyond the end.
2810 * If that is the case, we must be careful only to
2811 * remove the part of the preimage that falls within
2812 * the boundaries of img. Initialize preimage_limit
2813 * to the number of lines in the preimage that falls
2814 * within the boundaries.
2816 preimage_limit
= preimage
->line_nr
;
2817 if (preimage_limit
> img
->line_nr
- applied_pos
)
2818 preimage_limit
= img
->line_nr
- applied_pos
;
2820 for (i
= 0; i
< applied_pos
; i
++)
2821 applied_at
+= img
->line
[i
].len
;
2824 for (i
= 0; i
< preimage_limit
; i
++)
2825 remove_count
+= img
->line
[applied_pos
+ i
].len
;
2826 insert_count
= postimage
->buf
.len
;
2828 /* Adjust the contents */
2829 result_alloc
= st_add3(st_sub(img
->buf
.len
, remove_count
), insert_count
, 1);
2830 result
= xmalloc(result_alloc
);
2831 memcpy(result
, img
->buf
.buf
, applied_at
);
2832 memcpy(result
+ applied_at
, postimage
->buf
.buf
, postimage
->buf
.len
);
2833 memcpy(result
+ applied_at
+ postimage
->buf
.len
,
2834 img
->buf
.buf
+ (applied_at
+ remove_count
),
2835 img
->buf
.len
- (applied_at
+ remove_count
));
2836 strbuf_attach(&img
->buf
, result
, postimage
->buf
.len
+ img
->buf
.len
- remove_count
,
2839 /* Adjust the line table */
2840 nr
= img
->line_nr
+ postimage
->line_nr
- preimage_limit
;
2841 if (preimage_limit
< postimage
->line_nr
)
2843 * NOTE: this knows that we never call image_remove_first_line()
2844 * on anything other than pre/post image.
2846 REALLOC_ARRAY(img
->line
, nr
);
2847 if (preimage_limit
!= postimage
->line_nr
)
2848 MOVE_ARRAY(img
->line
+ applied_pos
+ postimage
->line_nr
,
2849 img
->line
+ applied_pos
+ preimage_limit
,
2850 img
->line_nr
- (applied_pos
+ preimage_limit
));
2851 COPY_ARRAY(img
->line
+ applied_pos
, postimage
->line
, postimage
->line_nr
);
2852 if (!state
->allow_overlap
)
2853 for (i
= 0; i
< postimage
->line_nr
; i
++)
2854 img
->line
[applied_pos
+ i
].flag
|= LINE_PATCHED
;
2859 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2860 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2861 * replace the part of "img" with "postimage" text.
2863 static int apply_one_fragment(struct apply_state
*state
,
2864 struct image
*img
, struct fragment
*frag
,
2865 int inaccurate_eof
, unsigned ws_rule
,
2868 int match_beginning
, match_end
;
2869 const char *patch
= frag
->patch
;
2870 int size
= frag
->size
;
2871 char *old
, *oldlines
;
2872 struct strbuf newlines
;
2873 int new_blank_lines_at_end
= 0;
2874 int found_new_blank_lines_at_end
= 0;
2875 int hunk_linenr
= frag
->linenr
;
2876 unsigned long leading
, trailing
;
2877 int pos
, applied_pos
;
2878 struct image preimage
= IMAGE_INIT
;
2879 struct image postimage
= IMAGE_INIT
;
2881 oldlines
= xmalloc(size
);
2882 strbuf_init(&newlines
, size
);
2887 int len
= linelen(patch
, size
);
2889 int added_blank_line
= 0;
2890 int is_blank_context
= 0;
2897 * "plen" is how much of the line we should use for
2898 * the actual patch data. Normally we just remove the
2899 * first character on the line, but if the line is
2900 * followed by "\ No newline", then we also remove the
2901 * last one (which is the newline, of course).
2904 if (len
< size
&& patch
[len
] == '\\')
2907 if (state
->apply_in_reverse
) {
2910 else if (first
== '+')
2916 /* Newer GNU diff, empty context line */
2918 /* ... followed by '\No newline'; nothing */
2921 strbuf_addch(&newlines
, '\n');
2922 image_add_line(&preimage
, "\n", 1, LINE_COMMON
);
2923 image_add_line(&postimage
, "\n", 1, LINE_COMMON
);
2924 is_blank_context
= 1;
2927 if (plen
&& (ws_rule
& WS_BLANK_AT_EOF
) &&
2928 ws_blank_line(patch
+ 1, plen
))
2929 is_blank_context
= 1;
2932 memcpy(old
, patch
+ 1, plen
);
2933 image_add_line(&preimage
, old
, plen
,
2934 (first
== ' ' ? LINE_COMMON
: 0));
2940 /* --no-add does not add new lines */
2941 if (first
== '+' && state
->no_add
)
2944 start
= newlines
.len
;
2946 !state
->whitespace_error
||
2947 state
->ws_error_action
!= correct_ws_error
) {
2948 strbuf_add(&newlines
, patch
+ 1, plen
);
2951 ws_fix_copy(&newlines
, patch
+ 1, plen
, ws_rule
, &state
->applied_after_fixing_ws
);
2953 image_add_line(&postimage
, newlines
.buf
+ start
, newlines
.len
- start
,
2954 (first
== '+' ? 0 : LINE_COMMON
));
2956 (ws_rule
& WS_BLANK_AT_EOF
) &&
2957 ws_blank_line(patch
+ 1, plen
))
2958 added_blank_line
= 1;
2960 case '@': case '\\':
2961 /* Ignore it, we already handled it */
2964 if (state
->apply_verbosity
> verbosity_normal
)
2965 error(_("invalid start of line: '%c'"), first
);
2969 if (added_blank_line
) {
2970 if (!new_blank_lines_at_end
)
2971 found_new_blank_lines_at_end
= hunk_linenr
;
2972 new_blank_lines_at_end
++;
2974 else if (is_blank_context
)
2977 new_blank_lines_at_end
= 0;
2982 if (inaccurate_eof
&&
2983 old
> oldlines
&& old
[-1] == '\n' &&
2984 newlines
.len
> 0 && newlines
.buf
[newlines
.len
- 1] == '\n') {
2986 strbuf_setlen(&newlines
, newlines
.len
- 1);
2987 preimage
.line
[preimage
.line_nr
- 1].len
--;
2988 postimage
.line
[postimage
.line_nr
- 1].len
--;
2991 leading
= frag
->leading
;
2992 trailing
= frag
->trailing
;
2995 * A hunk to change lines at the beginning would begin with
2997 * but we need to be careful. -U0 that inserts before the second
2998 * line also has this pattern.
3000 * And a hunk to add to an empty file would begin with
3003 * In other words, a hunk that is (frag->oldpos <= 1) with or
3004 * without leading context must match at the beginning.
3006 match_beginning
= (!frag
->oldpos
||
3007 (frag
->oldpos
== 1 && !state
->unidiff_zero
));
3010 * A hunk without trailing lines must match at the end.
3011 * However, we simply cannot tell if a hunk must match end
3012 * from the lack of trailing lines if the patch was generated
3013 * with unidiff without any context.
3015 match_end
= !state
->unidiff_zero
&& !trailing
;
3017 pos
= frag
->newpos
? (frag
->newpos
- 1) : 0;
3018 strbuf_add(&preimage
.buf
, oldlines
, old
- oldlines
);
3019 strbuf_swap(&postimage
.buf
, &newlines
);
3023 applied_pos
= find_pos(state
, img
, &preimage
, &postimage
, pos
,
3024 ws_rule
, match_beginning
, match_end
);
3026 if (applied_pos
>= 0)
3029 /* Am I at my context limits? */
3030 if ((leading
<= state
->p_context
) && (trailing
<= state
->p_context
))
3032 if (match_beginning
|| match_end
) {
3033 match_beginning
= match_end
= 0;
3038 * Reduce the number of context lines; reduce both
3039 * leading and trailing if they are equal otherwise
3040 * just reduce the larger context.
3042 if (leading
>= trailing
) {
3043 image_remove_first_line(&preimage
);
3044 image_remove_first_line(&postimage
);
3048 if (trailing
> leading
) {
3049 image_remove_last_line(&preimage
);
3050 image_remove_last_line(&postimage
);
3055 if (applied_pos
>= 0) {
3056 if (new_blank_lines_at_end
&&
3057 preimage
.line_nr
+ applied_pos
>= img
->line_nr
&&
3058 (ws_rule
& WS_BLANK_AT_EOF
) &&
3059 state
->ws_error_action
!= nowarn_ws_error
) {
3060 record_ws_error(state
, WS_BLANK_AT_EOF
, "+", 1,
3061 found_new_blank_lines_at_end
);
3062 if (state
->ws_error_action
== correct_ws_error
) {
3063 while (new_blank_lines_at_end
--)
3064 image_remove_last_line(&postimage
);
3067 * We would want to prevent write_out_results()
3068 * from taking place in apply_patch() that follows
3069 * the callchain led us here, which is:
3070 * apply_patch->check_patch_list->check_patch->
3071 * apply_data->apply_fragments->apply_one_fragment
3073 if (state
->ws_error_action
== die_on_ws_error
)
3077 if (state
->apply_verbosity
> verbosity_normal
&& applied_pos
!= pos
) {
3078 int offset
= applied_pos
- pos
;
3079 if (state
->apply_in_reverse
)
3080 offset
= 0 - offset
;
3082 Q_("Hunk #%d succeeded at %d (offset %d line).",
3083 "Hunk #%d succeeded at %d (offset %d lines).",
3085 nth_fragment
, applied_pos
+ 1, offset
);
3089 * Warn if it was necessary to reduce the number
3092 if ((leading
!= frag
->leading
||
3093 trailing
!= frag
->trailing
) && state
->apply_verbosity
> verbosity_silent
)
3094 fprintf_ln(stderr
, _("Context reduced to (%ld/%ld)"
3095 " to apply fragment at %d"),
3096 leading
, trailing
, applied_pos
+1);
3097 update_image(state
, img
, applied_pos
, &preimage
, &postimage
);
3099 if (state
->apply_verbosity
> verbosity_normal
)
3100 error(_("while searching for:\n%.*s"),
3101 (int)(old
- oldlines
), oldlines
);
3106 strbuf_release(&newlines
);
3107 image_clear(&preimage
);
3108 image_clear(&postimage
);
3110 return (applied_pos
< 0);
3113 static int apply_binary_fragment(struct apply_state
*state
,
3115 struct patch
*patch
)
3117 struct fragment
*fragment
= patch
->fragments
;
3122 return error(_("missing binary patch data for '%s'"),
3127 /* Binary patch is irreversible without the optional second hunk */
3128 if (state
->apply_in_reverse
) {
3129 if (!fragment
->next
)
3130 return error(_("cannot reverse-apply a binary patch "
3131 "without the reverse hunk to '%s'"),
3133 ? patch
->new_name
: patch
->old_name
);
3134 fragment
= fragment
->next
;
3136 switch (fragment
->binary_patch_method
) {
3137 case BINARY_DELTA_DEFLATED
:
3138 dst
= patch_delta(img
->buf
.buf
, img
->buf
.len
, fragment
->patch
,
3139 fragment
->size
, &len
);
3143 strbuf_attach(&img
->buf
, dst
, len
, len
+ 1);
3145 case BINARY_LITERAL_DEFLATED
:
3147 strbuf_add(&img
->buf
, fragment
->patch
, fragment
->size
);
3154 * Replace "img" with the result of applying the binary patch.
3155 * The binary patch data itself in patch->fragment is still kept
3156 * but the preimage prepared by the caller in "img" is freed here
3157 * or in the helper function apply_binary_fragment() this calls.
3159 static int apply_binary(struct apply_state
*state
,
3161 struct patch
*patch
)
3163 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3164 struct object_id oid
;
3165 const unsigned hexsz
= the_hash_algo
->hexsz
;
3168 * For safety, we require patch index line to contain
3169 * full hex textual object ID for old and new, at least for now.
3171 if (strlen(patch
->old_oid_prefix
) != hexsz
||
3172 strlen(patch
->new_oid_prefix
) != hexsz
||
3173 get_oid_hex(patch
->old_oid_prefix
, &oid
) ||
3174 get_oid_hex(patch
->new_oid_prefix
, &oid
))
3175 return error(_("cannot apply binary patch to '%s' "
3176 "without full index line"), name
);
3178 if (patch
->old_name
) {
3180 * See if the old one matches what the patch
3183 hash_object_file(the_hash_algo
, img
->buf
.buf
, img
->buf
.len
,
3185 if (strcmp(oid_to_hex(&oid
), patch
->old_oid_prefix
))
3186 return error(_("the patch applies to '%s' (%s), "
3187 "which does not match the "
3188 "current contents."),
3189 name
, oid_to_hex(&oid
));
3192 /* Otherwise, the old one must be empty. */
3194 return error(_("the patch applies to an empty "
3195 "'%s' but it is not empty"), name
);
3198 get_oid_hex(patch
->new_oid_prefix
, &oid
);
3199 if (is_null_oid(&oid
)) {
3201 return 0; /* deletion patch */
3204 if (has_object(the_repository
, &oid
, 0)) {
3205 /* We already have the postimage */
3206 enum object_type type
;
3210 result
= repo_read_object_file(the_repository
, &oid
, &type
,
3213 return error(_("the necessary postimage %s for "
3214 "'%s' cannot be read"),
3215 patch
->new_oid_prefix
, name
);
3217 strbuf_attach(&img
->buf
, result
, size
, size
+ 1);
3220 * We have verified buf matches the preimage;
3221 * apply the patch data to it, which is stored
3222 * in the patch->fragments->{patch,size}.
3224 if (apply_binary_fragment(state
, img
, patch
))
3225 return error(_("binary patch does not apply to '%s'"),
3228 /* verify that the result matches */
3229 hash_object_file(the_hash_algo
, img
->buf
.buf
, img
->buf
.len
, OBJ_BLOB
,
3231 if (strcmp(oid_to_hex(&oid
), patch
->new_oid_prefix
))
3232 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3233 name
, patch
->new_oid_prefix
, oid_to_hex(&oid
));
3239 static int apply_fragments(struct apply_state
*state
, struct image
*img
, struct patch
*patch
)
3241 struct fragment
*frag
= patch
->fragments
;
3242 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3243 unsigned ws_rule
= patch
->ws_rule
;
3244 unsigned inaccurate_eof
= patch
->inaccurate_eof
;
3247 if (patch
->is_binary
)
3248 return apply_binary(state
, img
, patch
);
3252 if (apply_one_fragment(state
, img
, frag
, inaccurate_eof
, ws_rule
, nth
)) {
3253 error(_("patch failed: %s:%ld"), name
, frag
->oldpos
);
3254 if (!state
->apply_with_reject
)
3263 static int read_blob_object(struct strbuf
*buf
, const struct object_id
*oid
, unsigned mode
)
3265 if (S_ISGITLINK(mode
)) {
3266 strbuf_grow(buf
, 100);
3267 strbuf_addf(buf
, "Subproject commit %s\n", oid_to_hex(oid
));
3269 enum object_type type
;
3273 result
= repo_read_object_file(the_repository
, oid
, &type
,
3277 /* XXX read_sha1_file NUL-terminates */
3278 strbuf_attach(buf
, result
, sz
, sz
+ 1);
3283 static int read_file_or_gitlink(const struct cache_entry
*ce
, struct strbuf
*buf
)
3287 return read_blob_object(buf
, &ce
->oid
, ce
->ce_mode
);
3290 static struct patch
*in_fn_table(struct apply_state
*state
, const char *name
)
3292 struct string_list_item
*item
;
3297 item
= string_list_lookup(&state
->fn_table
, name
);
3299 return (struct patch
*)item
->util
;
3305 * item->util in the filename table records the status of the path.
3306 * Usually it points at a patch (whose result records the contents
3307 * of it after applying it), but it could be PATH_WAS_DELETED for a
3308 * path that a previously applied patch has already removed, or
3309 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3311 * The latter is needed to deal with a case where two paths A and B
3312 * are swapped by first renaming A to B and then renaming B to A;
3313 * moving A to B should not be prevented due to presence of B as we
3314 * will remove it in a later patch.
3316 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3317 #define PATH_WAS_DELETED ((struct patch *) -1)
3319 static int to_be_deleted(struct patch
*patch
)
3321 return patch
== PATH_TO_BE_DELETED
;
3324 static int was_deleted(struct patch
*patch
)
3326 return patch
== PATH_WAS_DELETED
;
3329 static void add_to_fn_table(struct apply_state
*state
, struct patch
*patch
)
3331 struct string_list_item
*item
;
3334 * Always add new_name unless patch is a deletion
3335 * This should cover the cases for normal diffs,
3336 * file creations and copies
3338 if (patch
->new_name
) {
3339 item
= string_list_insert(&state
->fn_table
, patch
->new_name
);
3344 * store a failure on rename/deletion cases because
3345 * later chunks shouldn't patch old names
3347 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3348 item
= string_list_insert(&state
->fn_table
, patch
->old_name
);
3349 item
->util
= PATH_WAS_DELETED
;
3353 static void prepare_fn_table(struct apply_state
*state
, struct patch
*patch
)
3356 * store information about incoming file deletion
3359 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3360 struct string_list_item
*item
;
3361 item
= string_list_insert(&state
->fn_table
, patch
->old_name
);
3362 item
->util
= PATH_TO_BE_DELETED
;
3364 patch
= patch
->next
;
3368 static int checkout_target(struct index_state
*istate
,
3369 struct cache_entry
*ce
, struct stat
*st
)
3371 struct checkout costate
= CHECKOUT_INIT
;
3373 costate
.refresh_cache
= 1;
3374 costate
.istate
= istate
;
3375 if (checkout_entry(ce
, &costate
, NULL
, NULL
) ||
3376 lstat(ce
->name
, st
))
3377 return error(_("cannot checkout %s"), ce
->name
);
3381 static struct patch
*previous_patch(struct apply_state
*state
,
3382 struct patch
*patch
,
3385 struct patch
*previous
;
3388 if (patch
->is_copy
|| patch
->is_rename
)
3389 return NULL
; /* "git" patches do not depend on the order */
3391 previous
= in_fn_table(state
, patch
->old_name
);
3395 if (to_be_deleted(previous
))
3396 return NULL
; /* the deletion hasn't happened yet */
3398 if (was_deleted(previous
))
3404 static int verify_index_match(struct apply_state
*state
,
3405 const struct cache_entry
*ce
,
3408 if (S_ISGITLINK(ce
->ce_mode
)) {
3409 if (!S_ISDIR(st
->st_mode
))
3413 return ie_match_stat(state
->repo
->index
, ce
, st
,
3414 CE_MATCH_IGNORE_VALID
| CE_MATCH_IGNORE_SKIP_WORKTREE
);
3417 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3419 static int load_patch_target(struct apply_state
*state
,
3421 const struct cache_entry
*ce
,
3423 struct patch
*patch
,
3425 unsigned expected_mode
)
3427 if (state
->cached
|| state
->check_index
) {
3428 if (read_file_or_gitlink(ce
, buf
))
3429 return error(_("failed to read %s"), name
);
3431 if (S_ISGITLINK(expected_mode
)) {
3433 return read_file_or_gitlink(ce
, buf
);
3435 return SUBMODULE_PATCH_WITHOUT_INDEX
;
3436 } else if (has_symlink_leading_path(name
, strlen(name
))) {
3437 return error(_("reading from '%s' beyond a symbolic link"), name
);
3439 if (read_old_data(st
, patch
, name
, buf
))
3440 return error(_("failed to read %s"), name
);
3447 * We are about to apply "patch"; populate the "image" with the
3448 * current version we have, from the working tree or from the index,
3449 * depending on the situation e.g. --cached/--index. If we are
3450 * applying a non-git patch that incrementally updates the tree,
3451 * we read from the result of a previous diff.
3453 static int load_preimage(struct apply_state
*state
,
3454 struct image
*image
,
3455 struct patch
*patch
, struct stat
*st
,
3456 const struct cache_entry
*ce
)
3458 struct strbuf buf
= STRBUF_INIT
;
3461 struct patch
*previous
;
3464 previous
= previous_patch(state
, patch
, &status
);
3466 return error(_("path %s has been renamed/deleted"),
3469 /* We have a patched copy in memory; use that. */
3470 strbuf_add(&buf
, previous
->result
, previous
->resultsize
);
3472 status
= load_patch_target(state
, &buf
, ce
, st
, patch
,
3473 patch
->old_name
, patch
->old_mode
);
3476 else if (status
== SUBMODULE_PATCH_WITHOUT_INDEX
) {
3478 * There is no way to apply subproject
3479 * patch without looking at the index.
3480 * NEEDSWORK: shouldn't this be flagged
3483 free_fragment_list(patch
->fragments
);
3484 patch
->fragments
= NULL
;
3485 } else if (status
) {
3486 return error(_("failed to read %s"), patch
->old_name
);
3490 img
= strbuf_detach(&buf
, &len
);
3491 image_prepare(image
, img
, len
, !patch
->is_binary
);
3495 static int resolve_to(struct image
*image
, const struct object_id
*result_id
)
3498 enum object_type type
;
3503 data
= repo_read_object_file(the_repository
, result_id
, &type
, &size
);
3504 if (!data
|| type
!= OBJ_BLOB
)
3505 die("unable to read blob object %s", oid_to_hex(result_id
));
3506 strbuf_attach(&image
->buf
, data
, size
, size
+ 1);
3511 static int three_way_merge(struct apply_state
*state
,
3512 struct image
*image
,
3514 const struct object_id
*base
,
3515 const struct object_id
*ours
,
3516 const struct object_id
*theirs
)
3518 mmfile_t base_file
, our_file
, their_file
;
3519 struct ll_merge_options merge_opts
= LL_MERGE_OPTIONS_INIT
;
3520 mmbuffer_t result
= { NULL
};
3521 enum ll_merge_result status
;
3523 /* resolve trivial cases first */
3524 if (oideq(base
, ours
))
3525 return resolve_to(image
, theirs
);
3526 else if (oideq(base
, theirs
) || oideq(ours
, theirs
))
3527 return resolve_to(image
, ours
);
3529 read_mmblob(&base_file
, base
);
3530 read_mmblob(&our_file
, ours
);
3531 read_mmblob(&their_file
, theirs
);
3532 merge_opts
.variant
= state
->merge_variant
;
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 strbuf_attach(&image
->buf
, result
.ptr
, result
.size
, result
.size
);
3556 * When directly falling back to add/add three-way merge, we read from
3557 * the current contents of the new_name. In no cases other than that
3558 * this function will be called.
3560 static int load_current(struct apply_state
*state
,
3561 struct image
*image
,
3562 struct patch
*patch
)
3564 struct strbuf buf
= STRBUF_INIT
;
3569 struct cache_entry
*ce
;
3570 char *name
= patch
->new_name
;
3571 unsigned mode
= patch
->new_mode
;
3574 BUG("patch to %s is not a creation", patch
->old_name
);
3576 pos
= index_name_pos(state
->repo
->index
, name
, strlen(name
));
3578 return error(_("%s: does not exist in index"), name
);
3579 ce
= state
->repo
->index
->cache
[pos
];
3580 if (lstat(name
, &st
)) {
3581 if (errno
!= ENOENT
)
3582 return error_errno("%s", name
);
3583 if (checkout_target(state
->repo
->index
, ce
, &st
))
3586 if (verify_index_match(state
, ce
, &st
))
3587 return error(_("%s: does not match index"), name
);
3589 status
= load_patch_target(state
, &buf
, ce
, &st
, patch
, name
, mode
);
3594 img
= strbuf_detach(&buf
, &len
);
3595 image_prepare(image
, img
, len
, !patch
->is_binary
);
3599 static int try_threeway(struct apply_state
*state
,
3600 struct image
*image
,
3601 struct patch
*patch
,
3603 const struct cache_entry
*ce
)
3605 struct object_id pre_oid
, post_oid
, our_oid
;
3606 struct strbuf buf
= STRBUF_INIT
;
3610 struct image tmp_image
= IMAGE_INIT
;
3612 /* No point falling back to 3-way merge in these cases */
3613 if (patch
->is_delete
||
3614 S_ISGITLINK(patch
->old_mode
) || S_ISGITLINK(patch
->new_mode
) ||
3615 (patch
->is_new
&& !patch
->direct_to_threeway
) ||
3616 (patch
->is_rename
&& !patch
->lines_added
&& !patch
->lines_deleted
))
3619 /* Preimage the patch was prepared for */
3621 write_object_file("", 0, OBJ_BLOB
, &pre_oid
);
3622 else if (repo_get_oid(the_repository
, patch
->old_oid_prefix
, &pre_oid
) ||
3623 read_blob_object(&buf
, &pre_oid
, patch
->old_mode
))
3624 return error(_("repository lacks the necessary blob to perform 3-way merge."));
3626 if (state
->apply_verbosity
> verbosity_silent
&& patch
->direct_to_threeway
)
3627 fprintf(stderr
, _("Performing three-way merge...\n"));
3629 img
= strbuf_detach(&buf
, &len
);
3630 image_prepare(&tmp_image
, img
, len
, 1);
3631 /* Apply the patch to get the post image */
3632 if (apply_fragments(state
, &tmp_image
, patch
) < 0) {
3633 image_clear(&tmp_image
);
3636 /* post_oid is theirs */
3637 write_object_file(tmp_image
.buf
.buf
, tmp_image
.buf
.len
, OBJ_BLOB
, &post_oid
);
3638 image_clear(&tmp_image
);
3640 /* our_oid is ours */
3641 if (patch
->is_new
) {
3642 if (load_current(state
, &tmp_image
, patch
))
3643 return error(_("cannot read the current contents of '%s'"),
3646 if (load_preimage(state
, &tmp_image
, patch
, st
, ce
))
3647 return error(_("cannot read the current contents of '%s'"),
3650 write_object_file(tmp_image
.buf
.buf
, tmp_image
.buf
.len
, OBJ_BLOB
, &our_oid
);
3651 image_clear(&tmp_image
);
3653 /* in-core three-way merge between post and our using pre as base */
3654 status
= three_way_merge(state
, image
, patch
->new_name
,
3655 &pre_oid
, &our_oid
, &post_oid
);
3657 if (state
->apply_verbosity
> verbosity_silent
)
3659 _("Failed to perform three-way merge...\n"));
3664 patch
->conflicted_threeway
= 1;
3666 oidclr(&patch
->threeway_stage
[0], the_repository
->hash_algo
);
3668 oidcpy(&patch
->threeway_stage
[0], &pre_oid
);
3669 oidcpy(&patch
->threeway_stage
[1], &our_oid
);
3670 oidcpy(&patch
->threeway_stage
[2], &post_oid
);
3671 if (state
->apply_verbosity
> verbosity_silent
)
3673 _("Applied patch to '%s' with conflicts.\n"),
3676 if (state
->apply_verbosity
> verbosity_silent
)
3678 _("Applied patch to '%s' cleanly.\n"),
3684 static int apply_data(struct apply_state
*state
, struct patch
*patch
,
3685 struct stat
*st
, const struct cache_entry
*ce
)
3687 struct image image
= IMAGE_INIT
;
3689 if (load_preimage(state
, &image
, patch
, st
, ce
) < 0)
3692 if (!state
->threeway
|| try_threeway(state
, &image
, patch
, st
, ce
) < 0) {
3693 if (state
->apply_verbosity
> verbosity_silent
&&
3694 state
->threeway
&& !patch
->direct_to_threeway
)
3695 fprintf(stderr
, _("Falling back to direct application...\n"));
3697 /* Note: with --reject, apply_fragments() returns 0 */
3698 if (patch
->direct_to_threeway
|| apply_fragments(state
, &image
, patch
) < 0) {
3699 image_clear(&image
);
3703 patch
->result
= strbuf_detach(&image
.buf
, &patch
->resultsize
);
3704 add_to_fn_table(state
, patch
);
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 if (*ce
&& !(*ce
)->ce_mode
)
3775 BUG("ce_mode == 0 for path '%s'", old_name
);
3777 if (trust_executable_bit
)
3778 st_mode
= ce_mode_from_stat(*ce
, st
->st_mode
);
3780 st_mode
= (*ce
)->ce_mode
;
3782 st_mode
= patch
->old_mode
;
3785 if (patch
->is_new
< 0)
3787 if (!patch
->old_mode
)
3788 patch
->old_mode
= st_mode
;
3789 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
3790 return error(_("%s: wrong type"), old_name
);
3791 if (st_mode
!= patch
->old_mode
)
3792 warning(_("%s has type %o, expected %o"),
3793 old_name
, st_mode
, patch
->old_mode
);
3794 if (!patch
->new_mode
&& !patch
->is_delete
)
3795 patch
->new_mode
= st_mode
;
3800 patch
->is_delete
= 0;
3801 FREE_AND_NULL(patch
->old_name
);
3806 #define EXISTS_IN_INDEX 1
3807 #define EXISTS_IN_WORKTREE 2
3808 #define EXISTS_IN_INDEX_AS_ITA 3
3810 static int check_to_create(struct apply_state
*state
,
3811 const char *new_name
,
3816 if (state
->check_index
&& (!ok_if_exists
|| !state
->cached
)) {
3819 pos
= index_name_pos(state
->repo
->index
, new_name
, strlen(new_name
));
3821 struct cache_entry
*ce
= state
->repo
->index
->cache
[pos
];
3823 /* allow ITA, as they do not yet exist in the index */
3824 if (!ok_if_exists
&& !(ce
->ce_flags
& CE_INTENT_TO_ADD
))
3825 return EXISTS_IN_INDEX
;
3827 /* ITA entries can never match working tree files */
3828 if (!state
->cached
&& (ce
->ce_flags
& CE_INTENT_TO_ADD
))
3829 return EXISTS_IN_INDEX_AS_ITA
;
3836 if (!lstat(new_name
, &nst
)) {
3837 if (S_ISDIR(nst
.st_mode
) || ok_if_exists
)
3840 * A leading component of new_name might be a symlink
3841 * that is going to be removed with this patch, but
3842 * still pointing at somewhere that has the path.
3843 * In such a case, path "new_name" does not exist as
3844 * far as git is concerned.
3846 if (has_symlink_leading_path(new_name
, strlen(new_name
)))
3849 return EXISTS_IN_WORKTREE
;
3850 } else if (!is_missing_file_error(errno
)) {
3851 return error_errno("%s", new_name
);
3856 static void prepare_symlink_changes(struct apply_state
*state
, struct patch
*patch
)
3858 for ( ; patch
; patch
= patch
->next
) {
3859 if ((patch
->old_name
&& S_ISLNK(patch
->old_mode
)) &&
3860 (patch
->is_rename
|| patch
->is_delete
))
3861 /* the symlink at patch->old_name is removed */
3862 strset_add(&state
->removed_symlinks
, patch
->old_name
);
3864 if (patch
->new_name
&& S_ISLNK(patch
->new_mode
))
3865 /* the symlink at patch->new_name is created or remains */
3866 strset_add(&state
->kept_symlinks
, patch
->new_name
);
3870 static int path_is_beyond_symlink_1(struct apply_state
*state
, struct strbuf
*name
)
3873 while (--name
->len
&& name
->buf
[name
->len
] != '/')
3874 ; /* scan backwards */
3877 name
->buf
[name
->len
] = '\0';
3878 if (strset_contains(&state
->kept_symlinks
, name
->buf
))
3880 if (strset_contains(&state
->removed_symlinks
, name
->buf
))
3882 * This cannot be "return 0", because we may
3883 * see a new one created at a higher level.
3887 /* otherwise, check the preimage */
3888 if (state
->check_index
) {
3889 struct cache_entry
*ce
;
3891 ce
= index_file_exists(state
->repo
->index
, name
->buf
,
3892 name
->len
, ignore_case
);
3893 if (ce
&& S_ISLNK(ce
->ce_mode
))
3897 if (!lstat(name
->buf
, &st
) && S_ISLNK(st
.st_mode
))
3904 static int path_is_beyond_symlink(struct apply_state
*state
, const char *name_
)
3907 struct strbuf name
= STRBUF_INIT
;
3909 assert(*name_
!= '\0');
3910 strbuf_addstr(&name
, name_
);
3911 ret
= path_is_beyond_symlink_1(state
, &name
);
3912 strbuf_release(&name
);
3917 static int check_unsafe_path(struct patch
*patch
)
3919 const char *old_name
= NULL
;
3920 const char *new_name
= NULL
;
3921 if (patch
->is_delete
)
3922 old_name
= patch
->old_name
;
3923 else if (!patch
->is_new
&& !patch
->is_copy
)
3924 old_name
= patch
->old_name
;
3925 if (!patch
->is_delete
)
3926 new_name
= patch
->new_name
;
3928 if (old_name
&& !verify_path(old_name
, patch
->old_mode
))
3929 return error(_("invalid path '%s'"), old_name
);
3930 if (new_name
&& !verify_path(new_name
, patch
->new_mode
))
3931 return error(_("invalid path '%s'"), new_name
);
3936 * Check and apply the patch in-core; leave the result in patch->result
3937 * for the caller to write it out to the final destination.
3939 static int check_patch(struct apply_state
*state
, struct patch
*patch
)
3942 const char *old_name
= patch
->old_name
;
3943 const char *new_name
= patch
->new_name
;
3944 const char *name
= old_name
? old_name
: new_name
;
3945 struct cache_entry
*ce
= NULL
;
3946 struct patch
*tpatch
;
3950 patch
->rejected
= 1; /* we will drop this after we succeed */
3952 status
= check_preimage(state
, patch
, &ce
, &st
);
3955 old_name
= patch
->old_name
;
3958 * A type-change diff is always split into a patch to delete
3959 * old, immediately followed by a patch to create new (see
3960 * diff.c::run_diff()); in such a case it is Ok that the entry
3961 * to be deleted by the previous patch is still in the working
3962 * tree and in the index.
3964 * A patch to swap-rename between A and B would first rename A
3965 * to B and then rename B to A. While applying the first one,
3966 * the presence of B should not stop A from getting renamed to
3967 * B; ask to_be_deleted() about the later rename. Removal of
3968 * B and rename from A to B is handled the same way by asking
3971 if ((tpatch
= in_fn_table(state
, new_name
)) &&
3972 (was_deleted(tpatch
) || to_be_deleted(tpatch
)))
3978 ((0 < patch
->is_new
) || patch
->is_rename
|| patch
->is_copy
)) {
3979 int err
= check_to_create(state
, new_name
, ok_if_exists
);
3981 if (err
&& state
->threeway
) {
3982 patch
->direct_to_threeway
= 1;
3983 } else switch (err
) {
3986 case EXISTS_IN_INDEX
:
3987 return error(_("%s: already exists in index"), new_name
);
3988 case EXISTS_IN_INDEX_AS_ITA
:
3989 return error(_("%s: does not match index"), new_name
);
3990 case EXISTS_IN_WORKTREE
:
3991 return error(_("%s: already exists in working directory"),
3997 if (!patch
->new_mode
) {
3998 if (0 < patch
->is_new
)
3999 patch
->new_mode
= S_IFREG
| 0644;
4001 patch
->new_mode
= patch
->old_mode
;
4005 if (new_name
&& old_name
) {
4006 int same
= !strcmp(old_name
, new_name
);
4007 if (!patch
->new_mode
)
4008 patch
->new_mode
= patch
->old_mode
;
4009 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
) {
4011 return error(_("new mode (%o) of %s does not "
4012 "match old mode (%o)"),
4013 patch
->new_mode
, new_name
,
4016 return error(_("new mode (%o) of %s does not "
4017 "match old mode (%o) of %s"),
4018 patch
->new_mode
, new_name
,
4019 patch
->old_mode
, old_name
);
4023 if (!state
->unsafe_paths
&& check_unsafe_path(patch
))
4027 * An attempt to read from or delete a path that is beyond a
4028 * symbolic link will be prevented by load_patch_target() that
4029 * is called at the beginning of apply_data() so we do not
4030 * have to worry about a patch marked with "is_delete" bit
4031 * here. We however need to make sure that the patch result
4032 * is not deposited to a path that is beyond a symbolic link
4035 if (!patch
->is_delete
&& path_is_beyond_symlink(state
, patch
->new_name
))
4036 return error(_("affected file '%s' is beyond a symbolic link"),
4039 if (apply_data(state
, patch
, &st
, ce
) < 0)
4040 return error(_("%s: patch does not apply"), name
);
4041 patch
->rejected
= 0;
4045 static int check_patch_list(struct apply_state
*state
, struct patch
*patch
)
4049 prepare_symlink_changes(state
, patch
);
4050 prepare_fn_table(state
, patch
);
4053 if (state
->apply_verbosity
> verbosity_normal
)
4054 say_patch_name(stderr
,
4055 _("Checking patch %s..."), patch
);
4056 res
= check_patch(state
, patch
);
4060 patch
= patch
->next
;
4065 static int read_apply_cache(struct apply_state
*state
)
4067 if (state
->index_file
)
4068 return read_index_from(state
->repo
->index
, state
->index_file
,
4069 repo_get_git_dir(the_repository
));
4071 return repo_read_index(state
->repo
);
4074 /* This function tries to read the object name from the current index */
4075 static int get_current_oid(struct apply_state
*state
, const char *path
,
4076 struct object_id
*oid
)
4080 if (read_apply_cache(state
) < 0)
4082 pos
= index_name_pos(state
->repo
->index
, path
, strlen(path
));
4085 oidcpy(oid
, &state
->repo
->index
->cache
[pos
]->oid
);
4089 static int preimage_oid_in_gitlink_patch(struct patch
*p
, struct object_id
*oid
)
4092 * A usable gitlink patch has only one fragment (hunk) that looks like:
4094 * -Subproject commit <old sha1>
4095 * +Subproject commit <new sha1>
4098 * -Subproject commit <old sha1>
4099 * for a removal patch.
4101 struct fragment
*hunk
= p
->fragments
;
4102 static const char heading
[] = "-Subproject commit ";
4105 if (/* does the patch have only one hunk? */
4106 hunk
&& !hunk
->next
&&
4107 /* is its preimage one line? */
4108 hunk
->oldpos
== 1 && hunk
->oldlines
== 1 &&
4109 /* does preimage begin with the heading? */
4110 (preimage
= memchr(hunk
->patch
, '\n', hunk
->size
)) != NULL
&&
4111 starts_with(++preimage
, heading
) &&
4112 /* does it record full SHA-1? */
4113 !get_oid_hex(preimage
+ sizeof(heading
) - 1, oid
) &&
4114 preimage
[sizeof(heading
) + the_hash_algo
->hexsz
- 1] == '\n' &&
4115 /* does the abbreviated name on the index line agree with it? */
4116 starts_with(preimage
+ sizeof(heading
) - 1, p
->old_oid_prefix
))
4117 return 0; /* it all looks fine */
4119 /* we may have full object name on the index line */
4120 return get_oid_hex(p
->old_oid_prefix
, oid
);
4123 /* Build an index that contains just the files needed for a 3way merge */
4124 static int build_fake_ancestor(struct apply_state
*state
, struct patch
*list
)
4126 struct patch
*patch
;
4127 struct index_state result
= INDEX_STATE_INIT(state
->repo
);
4128 struct lock_file lock
= LOCK_INIT
;
4131 /* Once we start supporting the reverse patch, it may be
4132 * worth showing the new sha1 prefix, but until then...
4134 for (patch
= list
; patch
; patch
= patch
->next
) {
4135 struct object_id oid
;
4136 struct cache_entry
*ce
;
4139 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
4140 if (0 < patch
->is_new
)
4143 if (S_ISGITLINK(patch
->old_mode
)) {
4144 if (!preimage_oid_in_gitlink_patch(patch
, &oid
))
4145 ; /* ok, the textual part looks sane */
4147 return error(_("sha1 information is lacking or "
4148 "useless for submodule %s"), name
);
4149 } else if (!repo_get_oid_blob(the_repository
, patch
->old_oid_prefix
, &oid
)) {
4151 } else if (!patch
->lines_added
&& !patch
->lines_deleted
) {
4152 /* mode-only change: update the current */
4153 if (get_current_oid(state
, patch
->old_name
, &oid
))
4154 return error(_("mode change for %s, which is not "
4155 "in current HEAD"), name
);
4157 return error(_("sha1 information is lacking or useless "
4160 ce
= make_cache_entry(&result
, patch
->old_mode
, &oid
, name
, 0, 0);
4162 return error(_("make_cache_entry failed for path '%s'"),
4164 if (add_index_entry(&result
, ce
, ADD_CACHE_OK_TO_ADD
)) {
4165 discard_cache_entry(ce
);
4166 return error(_("could not add %s to temporary index"),
4171 hold_lock_file_for_update(&lock
, state
->fake_ancestor
, LOCK_DIE_ON_ERROR
);
4172 res
= write_locked_index(&result
, &lock
, COMMIT_LOCK
);
4173 discard_index(&result
);
4176 return error(_("could not write temporary index to %s"),
4177 state
->fake_ancestor
);
4182 static void stat_patch_list(struct apply_state
*state
, struct patch
*patch
)
4184 int files
, adds
, dels
;
4186 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
4188 adds
+= patch
->lines_added
;
4189 dels
+= patch
->lines_deleted
;
4190 show_stats(state
, patch
);
4193 print_stat_summary(stdout
, files
, adds
, dels
);
4196 static void numstat_patch_list(struct apply_state
*state
,
4197 struct patch
*patch
)
4199 for ( ; patch
; patch
= patch
->next
) {
4201 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
4202 if (patch
->is_binary
)
4205 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
4206 write_name_quoted(name
, stdout
, state
->line_termination
);
4210 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
4213 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
4215 printf(" %s %s\n", newdelete
, name
);
4218 static void show_mode_change(struct patch
*p
, int show_name
)
4220 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
4222 printf(" mode change %06o => %06o %s\n",
4223 p
->old_mode
, p
->new_mode
, p
->new_name
);
4225 printf(" mode change %06o => %06o\n",
4226 p
->old_mode
, p
->new_mode
);
4230 static void show_rename_copy(struct patch
*p
)
4232 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
4233 const char *old_name
, *new_name
;
4235 /* Find common prefix */
4236 old_name
= p
->old_name
;
4237 new_name
= p
->new_name
;
4239 const char *slash_old
, *slash_new
;
4240 slash_old
= strchr(old_name
, '/');
4241 slash_new
= strchr(new_name
, '/');
4244 slash_old
- old_name
!= slash_new
- new_name
||
4245 memcmp(old_name
, new_name
, slash_new
- new_name
))
4247 old_name
= slash_old
+ 1;
4248 new_name
= slash_new
+ 1;
4250 /* p->old_name through old_name is the common prefix, and old_name and
4251 * new_name through the end of names are renames
4253 if (old_name
!= p
->old_name
)
4254 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
4255 (int)(old_name
- p
->old_name
), p
->old_name
,
4256 old_name
, new_name
, p
->score
);
4258 printf(" %s %s => %s (%d%%)\n", renamecopy
,
4259 p
->old_name
, p
->new_name
, p
->score
);
4260 show_mode_change(p
, 0);
4263 static void summary_patch_list(struct patch
*patch
)
4267 for (p
= patch
; p
; p
= p
->next
) {
4269 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
4270 else if (p
->is_delete
)
4271 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
4273 if (p
->is_rename
|| p
->is_copy
)
4274 show_rename_copy(p
);
4277 printf(" rewrite %s (%d%%)\n",
4278 p
->new_name
, p
->score
);
4279 show_mode_change(p
, 0);
4282 show_mode_change(p
, 1);
4288 static void patch_stats(struct apply_state
*state
, struct patch
*patch
)
4290 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
4292 if (lines
> state
->max_change
)
4293 state
->max_change
= lines
;
4294 if (patch
->old_name
) {
4295 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
4297 len
= strlen(patch
->old_name
);
4298 if (len
> state
->max_len
)
4299 state
->max_len
= len
;
4301 if (patch
->new_name
) {
4302 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
4304 len
= strlen(patch
->new_name
);
4305 if (len
> state
->max_len
)
4306 state
->max_len
= len
;
4310 static int remove_file(struct apply_state
*state
, struct patch
*patch
, int rmdir_empty
)
4312 if (state
->update_index
&& !state
->ita_only
) {
4313 if (remove_file_from_index(state
->repo
->index
, patch
->old_name
) < 0)
4314 return error(_("unable to remove %s from index"), patch
->old_name
);
4316 if (!state
->cached
) {
4317 if (!remove_or_warn(patch
->old_mode
, patch
->old_name
) && rmdir_empty
) {
4318 remove_path(patch
->old_name
);
4324 static int add_index_file(struct apply_state
*state
,
4331 struct cache_entry
*ce
;
4332 int namelen
= strlen(path
);
4334 ce
= make_empty_cache_entry(state
->repo
->index
, namelen
);
4335 memcpy(ce
->name
, path
, namelen
);
4336 ce
->ce_mode
= create_ce_mode(mode
);
4337 ce
->ce_flags
= create_ce_flags(0);
4338 ce
->ce_namelen
= namelen
;
4339 if (state
->ita_only
) {
4340 ce
->ce_flags
|= CE_INTENT_TO_ADD
;
4341 set_object_name_for_intent_to_add_entry(ce
);
4342 } else if (S_ISGITLINK(mode
)) {
4345 if (!skip_prefix(buf
, "Subproject commit ", &s
) ||
4346 get_oid_hex(s
, &ce
->oid
)) {
4347 discard_cache_entry(ce
);
4348 return error(_("corrupt patch for submodule %s"), path
);
4351 if (!state
->cached
) {
4352 if (lstat(path
, &st
) < 0) {
4353 discard_cache_entry(ce
);
4354 return error_errno(_("unable to stat newly "
4355 "created file '%s'"),
4358 fill_stat_cache_info(state
->repo
->index
, ce
, &st
);
4360 if (write_object_file(buf
, size
, OBJ_BLOB
, &ce
->oid
) < 0) {
4361 discard_cache_entry(ce
);
4362 return error(_("unable to create backing store "
4363 "for newly created file %s"), path
);
4366 if (add_index_entry(state
->repo
->index
, ce
, ADD_CACHE_OK_TO_ADD
) < 0) {
4367 discard_cache_entry(ce
);
4368 return error(_("unable to add cache entry for %s"), path
);
4376 * -1 if an unrecoverable error happened
4377 * 0 if everything went well
4378 * 1 if a recoverable error happened
4380 static int try_create_file(struct apply_state
*state
, const char *path
,
4381 unsigned int mode
, const char *buf
,
4385 struct strbuf nbuf
= STRBUF_INIT
;
4387 if (S_ISGITLINK(mode
)) {
4389 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
))
4391 return !!mkdir(path
, 0777);
4394 if (has_symlinks
&& S_ISLNK(mode
))
4395 /* Although buf:size is counted string, it also is NUL
4398 return !!symlink(buf
, path
);
4400 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
4404 if (convert_to_working_tree(state
->repo
->index
, path
, buf
, size
, &nbuf
, NULL
)) {
4409 res
= write_in_full(fd
, buf
, size
) < 0;
4411 error_errno(_("failed to write to '%s'"), path
);
4412 strbuf_release(&nbuf
);
4414 if (close(fd
) < 0 && !res
)
4415 return error_errno(_("closing file '%s'"), path
);
4417 return res
? -1 : 0;
4421 * We optimistically assume that the directories exist,
4422 * which is true 99% of the time anyway. If they don't,
4423 * we create them and try again.
4429 static int create_one_file(struct apply_state
*state
,
4435 char *newpath
= NULL
;
4442 * We already try to detect whether files are beyond a symlink in our
4443 * up-front checks. But in the case where symlinks are created by any
4444 * of the intermediate hunks it can happen that our up-front checks
4445 * didn't yet see the symlink, but at the point of arriving here there
4446 * in fact is one. We thus repeat the check for symlinks here.
4448 * Note that this does not make the up-front check obsolete as the
4449 * failure mode is different:
4451 * - The up-front checks cause us to abort before we have written
4452 * anything into the working directory. So when we exit this way the
4453 * working directory remains clean.
4455 * - The checks here happen in the middle of the action where we have
4456 * already started to apply the patch. The end result will be a dirty
4457 * working directory.
4459 * Ideally, we should update the up-front checks to catch what would
4460 * happen when we apply the patch before we damage the working tree.
4461 * We have all the information necessary to do so. But for now, as a
4462 * part of embargoed security work, having this check would serve as a
4463 * reasonable first step.
4465 if (path_is_beyond_symlink(state
, path
))
4466 return error(_("affected file '%s' is beyond a symbolic link"), path
);
4468 res
= try_create_file(state
, path
, mode
, buf
, size
);
4474 if (errno
== ENOENT
) {
4475 if (safe_create_leading_directories_no_share(path
))
4477 res
= try_create_file(state
, path
, mode
, buf
, size
);
4484 if (errno
== EEXIST
|| errno
== EACCES
) {
4485 /* We may be trying to create a file where a directory
4489 if (!lstat(path
, &st
) && (!S_ISDIR(st
.st_mode
) || !rmdir(path
)))
4493 if (errno
== EEXIST
) {
4494 unsigned int nr
= getpid();
4497 newpath
= mkpathdup("%s~%u", path
, nr
);
4498 res
= try_create_file(state
, newpath
, mode
, buf
, size
);
4502 if (!rename(newpath
, path
))
4504 unlink_or_warn(newpath
);
4507 if (errno
!= EEXIST
)
4510 FREE_AND_NULL(newpath
);
4513 res
= error_errno(_("unable to write file '%s' mode %o"), path
, mode
);
4519 static int add_conflicted_stages_file(struct apply_state
*state
,
4520 struct patch
*patch
)
4524 struct cache_entry
*ce
;
4526 if (!state
->update_index
)
4528 namelen
= strlen(patch
->new_name
);
4529 mode
= patch
->new_mode
? patch
->new_mode
: (S_IFREG
| 0644);
4531 remove_file_from_index(state
->repo
->index
, patch
->new_name
);
4532 for (stage
= 1; stage
< 4; stage
++) {
4533 if (is_null_oid(&patch
->threeway_stage
[stage
- 1]))
4535 ce
= make_empty_cache_entry(state
->repo
->index
, namelen
);
4536 memcpy(ce
->name
, patch
->new_name
, namelen
);
4537 ce
->ce_mode
= create_ce_mode(mode
);
4538 ce
->ce_flags
= create_ce_flags(stage
);
4539 ce
->ce_namelen
= namelen
;
4540 oidcpy(&ce
->oid
, &patch
->threeway_stage
[stage
- 1]);
4541 if (add_index_entry(state
->repo
->index
, ce
, ADD_CACHE_OK_TO_ADD
) < 0) {
4542 discard_cache_entry(ce
);
4543 return error(_("unable to add cache entry for %s"),
4551 static int create_file(struct apply_state
*state
, struct patch
*patch
)
4553 char *path
= patch
->new_name
;
4554 unsigned mode
= patch
->new_mode
;
4555 unsigned long size
= patch
->resultsize
;
4556 char *buf
= patch
->result
;
4559 mode
= S_IFREG
| 0644;
4560 if (create_one_file(state
, path
, mode
, buf
, size
))
4563 if (patch
->conflicted_threeway
)
4564 return add_conflicted_stages_file(state
, patch
);
4565 else if (state
->update_index
)
4566 return add_index_file(state
, path
, mode
, buf
, size
);
4570 /* phase zero is to remove, phase one is to create */
4571 static int write_out_one_result(struct apply_state
*state
,
4572 struct patch
*patch
,
4575 if (patch
->is_delete
> 0) {
4577 return remove_file(state
, patch
, 1);
4580 if (patch
->is_new
> 0 || patch
->is_copy
) {
4582 return create_file(state
, patch
);
4586 * Rename or modification boils down to the same
4587 * thing: remove the old, write the new
4590 return remove_file(state
, patch
, patch
->is_rename
);
4592 return create_file(state
, patch
);
4596 static int write_out_one_reject(struct apply_state
*state
, struct patch
*patch
)
4600 struct fragment
*frag
;
4602 struct strbuf sb
= STRBUF_INIT
;
4604 for (cnt
= 0, frag
= patch
->fragments
; frag
; frag
= frag
->next
) {
4605 if (!frag
->rejected
)
4611 if (state
->apply_verbosity
> verbosity_normal
)
4612 say_patch_name(stderr
,
4613 _("Applied patch %s cleanly."), patch
);
4617 /* This should not happen, because a removal patch that leaves
4618 * contents are marked "rejected" at the patch level.
4620 if (!patch
->new_name
)
4621 die(_("internal error"));
4623 /* Say this even without --verbose */
4624 strbuf_addf(&sb
, Q_("Applying patch %%s with %d reject...",
4625 "Applying patch %%s with %d rejects...",
4628 if (state
->apply_verbosity
> verbosity_silent
)
4629 say_patch_name(stderr
, sb
.buf
, patch
);
4630 strbuf_release(&sb
);
4632 namebuf
= xstrfmt("%s.rej", patch
->new_name
);
4634 fd
= open(namebuf
, O_CREAT
| O_EXCL
| O_WRONLY
, 0666);
4636 if (errno
!= EEXIST
) {
4637 error_errno(_("cannot open %s"), namebuf
);
4640 if (unlink(namebuf
)) {
4641 error_errno(_("cannot unlink '%s'"), namebuf
);
4644 fd
= open(namebuf
, O_CREAT
| O_EXCL
| O_WRONLY
, 0666);
4646 error_errno(_("cannot open %s"), namebuf
);
4650 rej
= fdopen(fd
, "w");
4652 error_errno(_("cannot open %s"), namebuf
);
4657 /* Normal git tools never deal with .rej, so do not pretend
4658 * this is a git patch by saying --git or giving extended
4659 * headers. While at it, maybe please "kompare" that wants
4660 * the trailing TAB and some garbage at the end of line ;-).
4662 fprintf(rej
, "diff a/%s b/%s\t(rejected hunks)\n",
4663 patch
->new_name
, patch
->new_name
);
4664 for (cnt
= 1, frag
= patch
->fragments
;
4666 cnt
++, frag
= frag
->next
) {
4667 if (!frag
->rejected
) {
4668 if (state
->apply_verbosity
> verbosity_silent
)
4669 fprintf_ln(stderr
, _("Hunk #%d applied cleanly."), cnt
);
4672 if (state
->apply_verbosity
> verbosity_silent
)
4673 fprintf_ln(stderr
, _("Rejected hunk #%d."), cnt
);
4674 fprintf(rej
, "%.*s", frag
->size
, frag
->patch
);
4675 if (frag
->patch
[frag
->size
-1] != '\n')
4686 * -1 if an error happened
4687 * 0 if the patch applied cleanly
4688 * 1 if the patch did not apply cleanly
4690 static int write_out_results(struct apply_state
*state
, struct patch
*list
)
4695 struct string_list cpath
= STRING_LIST_INIT_DUP
;
4697 for (phase
= 0; phase
< 2; phase
++) {
4703 if (write_out_one_result(state
, l
, phase
)) {
4704 string_list_clear(&cpath
, 0);
4708 if (write_out_one_reject(state
, l
))
4710 if (l
->conflicted_threeway
) {
4711 string_list_append(&cpath
, l
->new_name
);
4721 struct string_list_item
*item
;
4723 string_list_sort(&cpath
);
4724 if (state
->apply_verbosity
> verbosity_silent
) {
4725 for_each_string_list_item(item
, &cpath
)
4726 fprintf(stderr
, "U %s\n", item
->string
);
4728 string_list_clear(&cpath
, 0);
4731 * rerere relies on the partially merged result being in the working
4732 * tree with conflict markers, but that isn't written with --cached.
4735 repo_rerere(state
->repo
, 0);
4742 * Try to apply a patch.
4745 * -128 if a bad error happened (like patch unreadable)
4746 * -1 if patch did not apply and user cannot deal with it
4747 * 0 if the patch applied
4748 * 1 if the patch did not apply but user might fix it
4750 static int apply_patch(struct apply_state
*state
,
4752 const char *filename
,
4756 struct strbuf buf
= STRBUF_INIT
; /* owns the patch text */
4757 struct patch
*list
= NULL
, **listp
= &list
;
4758 int skipped_patch
= 0;
4760 int flush_attributes
= 0;
4762 state
->patch_input_file
= filename
;
4763 if (read_patch_file(&buf
, fd
) < 0)
4766 while (offset
< buf
.len
) {
4767 struct patch
*patch
;
4770 CALLOC_ARRAY(patch
, 1);
4771 patch
->inaccurate_eof
= !!(options
& APPLY_OPT_INACCURATE_EOF
);
4772 patch
->recount
= !!(options
& APPLY_OPT_RECOUNT
);
4773 nr
= parse_chunk(state
, buf
.buf
+ offset
, buf
.len
- offset
, patch
);
4782 if (state
->apply_in_reverse
)
4783 reverse_patches(patch
);
4784 if (use_patch(state
, patch
)) {
4785 patch_stats(state
, patch
);
4786 if (!list
|| !state
->apply_in_reverse
) {
4788 listp
= &patch
->next
;
4794 if ((patch
->new_name
&&
4795 ends_with_path_components(patch
->new_name
,
4796 GITATTRIBUTES_FILE
)) ||
4798 ends_with_path_components(patch
->old_name
,
4799 GITATTRIBUTES_FILE
)))
4800 flush_attributes
= 1;
4803 if (state
->apply_verbosity
> verbosity_normal
)
4804 say_patch_name(stderr
, _("Skipped patch '%s'."), patch
);
4811 if (!list
&& !skipped_patch
) {
4812 if (!state
->allow_empty
) {
4813 error(_("No valid patches in input (allow with \"--allow-empty\")"));
4819 if (state
->whitespace_error
&& (state
->ws_error_action
== die_on_ws_error
))
4822 state
->update_index
= (state
->check_index
|| state
->ita_only
) && state
->apply
;
4823 if (state
->update_index
&& !is_lock_file_locked(&state
->lock_file
)) {
4824 if (state
->index_file
)
4825 hold_lock_file_for_update(&state
->lock_file
,
4829 repo_hold_locked_index(state
->repo
, &state
->lock_file
,
4833 if (state
->check_index
&& read_apply_cache(state
) < 0) {
4834 error(_("unable to read index file"));
4839 if (state
->check
|| state
->apply
) {
4840 int r
= check_patch_list(state
, list
);
4845 if (r
< 0 && !state
->apply_with_reject
) {
4852 int write_res
= write_out_results(state
, list
);
4853 if (write_res
< 0) {
4857 if (write_res
> 0) {
4858 /* with --3way, we still need to write the index out */
4859 res
= state
->apply_with_reject
? -1 : 1;
4864 if (state
->fake_ancestor
&&
4865 build_fake_ancestor(state
, list
)) {
4870 if (state
->diffstat
&& state
->apply_verbosity
> verbosity_silent
)
4871 stat_patch_list(state
, list
);
4873 if (state
->numstat
&& state
->apply_verbosity
> verbosity_silent
)
4874 numstat_patch_list(state
, list
);
4876 if (state
->summary
&& state
->apply_verbosity
> verbosity_silent
)
4877 summary_patch_list(list
);
4879 if (flush_attributes
)
4880 reset_parsed_attributes();
4882 free_patch_list(list
);
4883 strbuf_release(&buf
);
4884 string_list_clear(&state
->fn_table
, 0);
4888 static int apply_option_parse_exclude(const struct option
*opt
,
4889 const char *arg
, int unset
)
4891 struct apply_state
*state
= opt
->value
;
4893 BUG_ON_OPT_NEG(unset
);
4895 add_name_limit(state
, arg
, 1);
4899 static int apply_option_parse_include(const struct option
*opt
,
4900 const char *arg
, int unset
)
4902 struct apply_state
*state
= opt
->value
;
4904 BUG_ON_OPT_NEG(unset
);
4906 add_name_limit(state
, arg
, 0);
4907 state
->has_include
= 1;
4911 static int apply_option_parse_p(const struct option
*opt
,
4915 struct apply_state
*state
= opt
->value
;
4917 BUG_ON_OPT_NEG(unset
);
4919 state
->p_value
= atoi(arg
);
4920 state
->p_value_known
= 1;
4924 static int apply_option_parse_space_change(const struct option
*opt
,
4925 const char *arg
, int unset
)
4927 struct apply_state
*state
= opt
->value
;
4929 BUG_ON_OPT_ARG(arg
);
4932 state
->ws_ignore_action
= ignore_ws_none
;
4934 state
->ws_ignore_action
= ignore_ws_change
;
4938 static int apply_option_parse_whitespace(const struct option
*opt
,
4939 const char *arg
, int unset
)
4941 struct apply_state
*state
= opt
->value
;
4943 BUG_ON_OPT_NEG(unset
);
4945 state
->whitespace_option
= arg
;
4946 if (parse_whitespace_option(state
, arg
))
4951 static int apply_option_parse_directory(const struct option
*opt
,
4952 const char *arg
, int unset
)
4954 struct apply_state
*state
= opt
->value
;
4956 BUG_ON_OPT_NEG(unset
);
4958 strbuf_reset(&state
->root
);
4959 strbuf_addstr(&state
->root
, arg
);
4960 strbuf_complete(&state
->root
, '/');
4964 int apply_all_patches(struct apply_state
*state
,
4974 for (i
= 0; i
< argc
; i
++) {
4975 const char *arg
= argv
[i
];
4976 char *to_free
= NULL
;
4979 if (!strcmp(arg
, "-")) {
4980 res
= apply_patch(state
, 0, "<stdin>", options
);
4987 arg
= to_free
= prefix_filename(state
->prefix
, arg
);
4989 fd
= open(arg
, O_RDONLY
);
4991 error(_("can't open patch '%s': %s"), arg
, strerror(errno
));
4997 set_default_whitespace_mode(state
);
4998 res
= apply_patch(state
, fd
, arg
, options
);
5005 set_default_whitespace_mode(state
);
5007 res
= apply_patch(state
, 0, "<stdin>", options
);
5013 if (state
->whitespace_error
) {
5014 if (state
->squelch_whitespace_errors
&&
5015 state
->squelch_whitespace_errors
< state
->whitespace_error
) {
5017 state
->whitespace_error
- state
->squelch_whitespace_errors
;
5018 warning(Q_("squelched %d whitespace error",
5019 "squelched %d whitespace errors",
5023 if (state
->ws_error_action
== die_on_ws_error
) {
5024 error(Q_("%d line adds whitespace errors.",
5025 "%d lines add whitespace errors.",
5026 state
->whitespace_error
),
5027 state
->whitespace_error
);
5031 if (state
->applied_after_fixing_ws
&& state
->apply
)
5032 warning(Q_("%d line applied after"
5033 " fixing whitespace errors.",
5034 "%d lines applied after"
5035 " fixing whitespace errors.",
5036 state
->applied_after_fixing_ws
),
5037 state
->applied_after_fixing_ws
);
5038 else if (state
->whitespace_error
)
5039 warning(Q_("%d line adds whitespace errors.",
5040 "%d lines add whitespace errors.",
5041 state
->whitespace_error
),
5042 state
->whitespace_error
);
5045 if (state
->update_index
) {
5046 res
= write_locked_index(state
->repo
->index
, &state
->lock_file
, COMMIT_LOCK
);
5048 error(_("Unable to write new index file"));
5057 rollback_lock_file(&state
->lock_file
);
5059 if (state
->apply_verbosity
<= verbosity_silent
) {
5060 set_error_routine(state
->saved_error_routine
);
5061 set_warn_routine(state
->saved_warn_routine
);
5066 return (res
== -1 ? 1 : 128);
5069 int apply_parse_options(int argc
, const char **argv
,
5070 struct apply_state
*state
,
5071 int *force_apply
, int *options
,
5072 const char * const *apply_usage
)
5074 struct option builtin_apply_options
[] = {
5075 OPT_CALLBACK_F(0, "exclude", state
, N_("path"),
5076 N_("don't apply changes matching the given path"),
5077 PARSE_OPT_NONEG
, apply_option_parse_exclude
),
5078 OPT_CALLBACK_F(0, "include", state
, N_("path"),
5079 N_("apply changes matching the given path"),
5080 PARSE_OPT_NONEG
, apply_option_parse_include
),
5081 OPT_CALLBACK('p', NULL
, state
, N_("num"),
5082 N_("remove <num> leading slashes from traditional diff paths"),
5083 apply_option_parse_p
),
5084 OPT_BOOL(0, "no-add", &state
->no_add
,
5085 N_("ignore additions made by the patch")),
5086 OPT_BOOL(0, "stat", &state
->diffstat
,
5087 N_("instead of applying the patch, output diffstat for the input")),
5088 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
5089 OPT_NOOP_NOARG(0, "binary"),
5090 OPT_BOOL(0, "numstat", &state
->numstat
,
5091 N_("show number of added and deleted lines in decimal notation")),
5092 OPT_BOOL(0, "summary", &state
->summary
,
5093 N_("instead of applying the patch, output a summary for the input")),
5094 OPT_BOOL(0, "check", &state
->check
,
5095 N_("instead of applying the patch, see if the patch is applicable")),
5096 OPT_BOOL(0, "index", &state
->check_index
,
5097 N_("make sure the patch is applicable to the current index")),
5098 OPT_BOOL('N', "intent-to-add", &state
->ita_only
,
5099 N_("mark new files with `git add --intent-to-add`")),
5100 OPT_BOOL(0, "cached", &state
->cached
,
5101 N_("apply a patch without touching the working tree")),
5102 OPT_BOOL_F(0, "unsafe-paths", &state
->unsafe_paths
,
5103 N_("accept a patch that touches outside the working area"),
5104 PARSE_OPT_NOCOMPLETE
),
5105 OPT_BOOL(0, "apply", force_apply
,
5106 N_("also apply the patch (use with --stat/--summary/--check)")),
5107 OPT_BOOL('3', "3way", &state
->threeway
,
5108 N_( "attempt three-way merge, fall back on normal patch if that fails")),
5109 OPT_SET_INT_F(0, "ours", &state
->merge_variant
,
5110 N_("for conflicts, use our version"),
5111 XDL_MERGE_FAVOR_OURS
, PARSE_OPT_NONEG
),
5112 OPT_SET_INT_F(0, "theirs", &state
->merge_variant
,
5113 N_("for conflicts, use their version"),
5114 XDL_MERGE_FAVOR_THEIRS
, PARSE_OPT_NONEG
),
5115 OPT_SET_INT_F(0, "union", &state
->merge_variant
,
5116 N_("for conflicts, use a union version"),
5117 XDL_MERGE_FAVOR_UNION
, PARSE_OPT_NONEG
),
5118 OPT_FILENAME(0, "build-fake-ancestor", &state
->fake_ancestor
,
5119 N_("build a temporary index based on embedded index information")),
5120 /* Think twice before adding "--nul" synonym to this */
5121 OPT_SET_INT('z', NULL
, &state
->line_termination
,
5122 N_("paths are separated with NUL character"), '\0'),
5123 OPT_INTEGER('C', NULL
, &state
->p_context
,
5124 N_("ensure at least <n> lines of context match")),
5125 OPT_CALLBACK(0, "whitespace", state
, N_("action"),
5126 N_("detect new or modified lines that have whitespace errors"),
5127 apply_option_parse_whitespace
),
5128 OPT_CALLBACK_F(0, "ignore-space-change", state
, NULL
,
5129 N_("ignore changes in whitespace when finding context"),
5130 PARSE_OPT_NOARG
, apply_option_parse_space_change
),
5131 OPT_CALLBACK_F(0, "ignore-whitespace", state
, NULL
,
5132 N_("ignore changes in whitespace when finding context"),
5133 PARSE_OPT_NOARG
, apply_option_parse_space_change
),
5134 OPT_BOOL('R', "reverse", &state
->apply_in_reverse
,
5135 N_("apply the patch in reverse")),
5136 OPT_BOOL(0, "unidiff-zero", &state
->unidiff_zero
,
5137 N_("don't expect at least one line of context")),
5138 OPT_BOOL(0, "reject", &state
->apply_with_reject
,
5139 N_("leave the rejected hunks in corresponding *.rej files")),
5140 OPT_BOOL(0, "allow-overlap", &state
->allow_overlap
,
5141 N_("allow overlapping hunks")),
5142 OPT__VERBOSITY(&state
->apply_verbosity
),
5143 OPT_BIT(0, "inaccurate-eof", options
,
5144 N_("tolerate incorrectly detected missing new-line at the end of file"),
5145 APPLY_OPT_INACCURATE_EOF
),
5146 OPT_BIT(0, "recount", options
,
5147 N_("do not trust the line counts in the hunk headers"),
5149 OPT_CALLBACK(0, "directory", state
, N_("root"),
5150 N_("prepend <root> to all filenames"),
5151 apply_option_parse_directory
),
5152 OPT_BOOL(0, "allow-empty", &state
->allow_empty
,
5153 N_("don't return error for empty patches")),
5157 argc
= parse_options(argc
, argv
, state
->prefix
, builtin_apply_options
, apply_usage
, 0);
5159 if (state
->merge_variant
&& !state
->threeway
)
5160 die(_("--ours, --theirs, and --union require --3way"));