4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
14 #include "object-store.h"
19 #include "environment.h"
22 #include "xdiff-interface.h"
25 #include "object-name.h"
26 #include "object-file.h"
27 #include "parse-options.h"
41 static void git_apply_config(void)
43 git_config_get_string("apply.whitespace", &apply_default_whitespace
);
44 git_config_get_string("apply.ignorewhitespace", &apply_default_ignorewhitespace
);
45 git_config(git_xmerge_config
, NULL
);
48 static int parse_whitespace_option(struct apply_state
*state
, const char *option
)
51 state
->ws_error_action
= warn_on_ws_error
;
54 if (!strcmp(option
, "warn")) {
55 state
->ws_error_action
= warn_on_ws_error
;
58 if (!strcmp(option
, "nowarn")) {
59 state
->ws_error_action
= nowarn_ws_error
;
62 if (!strcmp(option
, "error")) {
63 state
->ws_error_action
= die_on_ws_error
;
66 if (!strcmp(option
, "error-all")) {
67 state
->ws_error_action
= die_on_ws_error
;
68 state
->squelch_whitespace_errors
= 0;
71 if (!strcmp(option
, "strip") || !strcmp(option
, "fix")) {
72 state
->ws_error_action
= correct_ws_error
;
76 * Please update $__git_whitespacelist in git-completion.bash
77 * when you add new options.
79 return error(_("unrecognized whitespace option '%s'"), option
);
82 static int parse_ignorewhitespace_option(struct apply_state
*state
,
85 if (!option
|| !strcmp(option
, "no") ||
86 !strcmp(option
, "false") || !strcmp(option
, "never") ||
87 !strcmp(option
, "none")) {
88 state
->ws_ignore_action
= ignore_ws_none
;
91 if (!strcmp(option
, "change")) {
92 state
->ws_ignore_action
= ignore_ws_change
;
95 return error(_("unrecognized whitespace ignore option '%s'"), option
);
98 int init_apply_state(struct apply_state
*state
,
99 struct repository
*repo
,
102 memset(state
, 0, sizeof(*state
));
103 state
->prefix
= prefix
;
106 state
->line_termination
= '\n';
108 state
->p_context
= UINT_MAX
;
109 state
->squelch_whitespace_errors
= 5;
110 state
->ws_error_action
= warn_on_ws_error
;
111 state
->ws_ignore_action
= ignore_ws_none
;
113 string_list_init_nodup(&state
->fn_table
);
114 string_list_init_nodup(&state
->limit_by_name
);
115 strset_init(&state
->removed_symlinks
);
116 strset_init(&state
->kept_symlinks
);
117 strbuf_init(&state
->root
, 0);
120 if (apply_default_whitespace
&& parse_whitespace_option(state
, apply_default_whitespace
))
122 if (apply_default_ignorewhitespace
&& parse_ignorewhitespace_option(state
, apply_default_ignorewhitespace
))
127 void clear_apply_state(struct apply_state
*state
)
129 string_list_clear(&state
->limit_by_name
, 0);
130 strset_clear(&state
->removed_symlinks
);
131 strset_clear(&state
->kept_symlinks
);
132 strbuf_release(&state
->root
);
134 /* &state->fn_table is cleared at the end of apply_patch() */
137 static void mute_routine(const char *msg UNUSED
, va_list params UNUSED
)
142 int check_apply_state(struct apply_state
*state
, int force_apply
)
144 int is_not_gitdir
= !startup_info
->have_repository
;
146 if (state
->apply_with_reject
&& state
->threeway
)
147 return error(_("options '%s' and '%s' cannot be used together"), "--reject", "--3way");
148 if (state
->threeway
) {
150 return error(_("'%s' outside a repository"), "--3way");
151 state
->check_index
= 1;
153 if (state
->apply_with_reject
) {
155 if (state
->apply_verbosity
== verbosity_normal
)
156 state
->apply_verbosity
= verbosity_verbose
;
158 if (!force_apply
&& (state
->diffstat
|| state
->numstat
|| state
->summary
|| state
->check
|| state
->fake_ancestor
))
160 if (state
->check_index
&& is_not_gitdir
)
161 return error(_("'%s' outside a repository"), "--index");
164 return error(_("'%s' outside a repository"), "--cached");
165 state
->check_index
= 1;
167 if (state
->ita_only
&& (state
->check_index
|| is_not_gitdir
))
169 if (state
->check_index
)
170 state
->unsafe_paths
= 0;
172 if (state
->apply_verbosity
<= verbosity_silent
) {
173 state
->saved_error_routine
= get_error_routine();
174 state
->saved_warn_routine
= get_warn_routine();
175 set_error_routine(mute_routine
);
176 set_warn_routine(mute_routine
);
182 static void set_default_whitespace_mode(struct apply_state
*state
)
184 if (!state
->whitespace_option
&& !apply_default_whitespace
)
185 state
->ws_error_action
= (state
->apply
? warn_on_ws_error
: nowarn_ws_error
);
189 * This represents one "hunk" from a patch, starting with
190 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
191 * patch text is pointed at by patch, and its byte length
192 * is stored in size. leading and trailing are the number
196 unsigned long leading
, trailing
;
197 unsigned long oldpos
, oldlines
;
198 unsigned long newpos
, newlines
;
200 * 'patch' is usually borrowed from buf in apply_patch(),
201 * but some codepaths store an allocated buffer.
204 unsigned free_patch
:1,
208 struct fragment
*next
;
212 * When dealing with a binary patch, we reuse "leading" field
213 * to store the type of the binary hunk, either deflated "delta"
214 * or deflated "literal".
216 #define binary_patch_method leading
217 #define BINARY_DELTA_DEFLATED 1
218 #define BINARY_LITERAL_DEFLATED 2
220 static void free_fragment_list(struct fragment
*list
)
223 struct fragment
*next
= list
->next
;
224 if (list
->free_patch
)
225 free((char *)list
->patch
);
231 void release_patch(struct patch
*patch
)
233 free_fragment_list(patch
->fragments
);
234 free(patch
->def_name
);
235 free(patch
->old_name
);
236 free(patch
->new_name
);
240 static void free_patch(struct patch
*patch
)
242 release_patch(patch
);
246 static void free_patch_list(struct patch
*list
)
249 struct patch
*next
= list
->next
;
256 * A line in a file, len-bytes long (includes the terminating LF,
257 * except for an incomplete line at the end if the file ends with
258 * one), and its contents hashes to 'hash'.
264 #define LINE_COMMON 1
265 #define LINE_PATCHED 2
269 * This represents a "file", which is an array of "lines".
276 struct line
*line_allocated
;
280 static uint32_t hash_line(const char *cp
, size_t len
)
284 for (i
= 0, h
= 0; i
< len
; i
++) {
285 if (!isspace(cp
[i
])) {
286 h
= h
* 3 + (cp
[i
] & 0xff);
293 * Compare lines s1 of length n1 and s2 of length n2, ignoring
294 * whitespace difference. Returns 1 if they match, 0 otherwise
296 static int fuzzy_matchlines(const char *s1
, size_t n1
,
297 const char *s2
, size_t n2
)
299 const char *end1
= s1
+ n1
;
300 const char *end2
= s2
+ n2
;
302 /* ignore line endings */
303 while (s1
< end1
&& (end1
[-1] == '\r' || end1
[-1] == '\n'))
305 while (s2
< end2
&& (end2
[-1] == '\r' || end2
[-1] == '\n'))
308 while (s1
< end1
&& s2
< end2
) {
311 * Skip whitespace. We check on both buffers
312 * because we don't want "a b" to match "ab".
316 while (s1
< end1
&& isspace(*s1
))
318 while (s2
< end2
&& isspace(*s2
))
320 } else if (*s1
++ != *s2
++)
324 /* If we reached the end on one side only, lines don't match. */
325 return s1
== end1
&& s2
== end2
;
328 static void add_line_info(struct image
*img
, const char *bol
, size_t len
, unsigned flag
)
330 ALLOC_GROW(img
->line_allocated
, img
->nr
+ 1, img
->alloc
);
331 img
->line_allocated
[img
->nr
].len
= len
;
332 img
->line_allocated
[img
->nr
].hash
= hash_line(bol
, len
);
333 img
->line_allocated
[img
->nr
].flag
= flag
;
338 * "buf" has the file contents to be patched (read from various sources).
339 * attach it to "image" and add line-based index to it.
340 * "image" now owns the "buf".
342 static void prepare_image(struct image
*image
, char *buf
, size_t len
,
343 int prepare_linetable
)
347 memset(image
, 0, sizeof(*image
));
351 if (!prepare_linetable
)
354 ep
= image
->buf
+ image
->len
;
358 for (next
= cp
; next
< ep
&& *next
!= '\n'; next
++)
362 add_line_info(image
, cp
, next
- cp
, 0);
365 image
->line
= image
->line_allocated
;
368 static void clear_image(struct image
*image
)
371 free(image
->line_allocated
);
372 memset(image
, 0, sizeof(*image
));
375 /* fmt must contain _one_ %s and no other substitution */
376 static void say_patch_name(FILE *output
, const char *fmt
, struct patch
*patch
)
378 struct strbuf sb
= STRBUF_INIT
;
380 if (patch
->old_name
&& patch
->new_name
&&
381 strcmp(patch
->old_name
, patch
->new_name
)) {
382 quote_c_style(patch
->old_name
, &sb
, NULL
, 0);
383 strbuf_addstr(&sb
, " => ");
384 quote_c_style(patch
->new_name
, &sb
, NULL
, 0);
386 const char *n
= patch
->new_name
;
389 quote_c_style(n
, &sb
, NULL
, 0);
391 fprintf(output
, fmt
, sb
.buf
);
399 * apply.c isn't equipped to handle arbitrarily large patches, because
400 * it intermingles `unsigned long` with `int` for the type used to store
403 * Only process patches that are just shy of 1 GiB large in order to
404 * avoid any truncation or overflow issues.
406 #define MAX_APPLY_SIZE (1024UL * 1024 * 1023)
408 static int read_patch_file(struct strbuf
*sb
, int fd
)
410 if (strbuf_read(sb
, fd
, 0) < 0 || sb
->len
>= MAX_APPLY_SIZE
)
411 return error_errno("git apply: failed to read");
414 * Make sure that we have some slop in the buffer
415 * so that we can do speculative "memcmp" etc, and
416 * see to it that it is NUL-filled.
418 strbuf_grow(sb
, SLOP
);
419 memset(sb
->buf
+ sb
->len
, 0, SLOP
);
423 static unsigned long linelen(const char *buffer
, unsigned long size
)
425 unsigned long len
= 0;
428 if (*buffer
++ == '\n')
434 static int is_dev_null(const char *str
)
436 return skip_prefix(str
, "/dev/null", &str
) && isspace(*str
);
442 static int name_terminate(int c
, int terminate
)
444 if (c
== ' ' && !(terminate
& TERM_SPACE
))
446 if (c
== '\t' && !(terminate
& TERM_TAB
))
452 /* remove double slashes to make --index work with such filenames */
453 static char *squash_slash(char *name
)
461 if ((name
[j
++] = name
[i
++]) == '/')
462 while (name
[i
] == '/')
469 static char *find_name_gnu(struct strbuf
*root
,
473 struct strbuf name
= STRBUF_INIT
;
477 * Proposed "new-style" GNU patch/diff format; see
478 * https://lore.kernel.org/git/7vll0wvb2a.fsf@assigned-by-dhcp.cox.net/
480 if (unquote_c_style(&name
, line
, NULL
)) {
481 strbuf_release(&name
);
485 for (cp
= name
.buf
; p_value
; p_value
--) {
486 cp
= strchr(cp
, '/');
488 strbuf_release(&name
);
494 strbuf_remove(&name
, 0, cp
- name
.buf
);
496 strbuf_insert(&name
, 0, root
->buf
, root
->len
);
497 return squash_slash(strbuf_detach(&name
, NULL
));
500 static size_t sane_tz_len(const char *line
, size_t len
)
504 if (len
< strlen(" +0500") || line
[len
-strlen(" +0500")] != ' ')
506 tz
= line
+ len
- strlen(" +0500");
508 if (tz
[1] != '+' && tz
[1] != '-')
511 for (p
= tz
+ 2; p
!= line
+ len
; p
++)
515 return line
+ len
- tz
;
518 static size_t tz_with_colon_len(const char *line
, size_t len
)
522 if (len
< strlen(" +08:00") || line
[len
- strlen(":00")] != ':')
524 tz
= line
+ len
- strlen(" +08:00");
526 if (tz
[0] != ' ' || (tz
[1] != '+' && tz
[1] != '-'))
529 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
530 !isdigit(*p
++) || !isdigit(*p
++))
533 return line
+ len
- tz
;
536 static size_t date_len(const char *line
, size_t len
)
538 const char *date
, *p
;
540 if (len
< strlen("72-02-05") || line
[len
-strlen("-05")] != '-')
542 p
= date
= line
+ len
- strlen("72-02-05");
544 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
545 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
546 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a date. */
549 if (date
- line
>= strlen("19") &&
550 isdigit(date
[-1]) && isdigit(date
[-2])) /* 4-digit year */
551 date
-= strlen("19");
553 return line
+ len
- date
;
556 static size_t short_time_len(const char *line
, size_t len
)
558 const char *time
, *p
;
560 if (len
< strlen(" 07:01:32") || line
[len
-strlen(":32")] != ':')
562 p
= time
= line
+ len
- strlen(" 07:01:32");
564 /* Permit 1-digit hours? */
566 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
567 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
568 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a time. */
571 return line
+ len
- time
;
574 static size_t fractional_time_len(const char *line
, size_t len
)
579 /* Expected format: 19:41:17.620000023 */
580 if (!len
|| !isdigit(line
[len
- 1]))
584 /* Fractional seconds. */
585 while (p
> line
&& isdigit(*p
))
590 /* Hours, minutes, and whole seconds. */
591 n
= short_time_len(line
, p
- line
);
595 return line
+ len
- p
+ n
;
598 static size_t trailing_spaces_len(const char *line
, size_t len
)
602 /* Expected format: ' ' x (1 or more) */
603 if (!len
|| line
[len
- 1] != ' ')
610 return line
+ len
- (p
+ 1);
617 static size_t diff_timestamp_len(const char *line
, size_t len
)
619 const char *end
= line
+ len
;
623 * Posix: 2010-07-05 19:41:17
624 * GNU: 2010-07-05 19:41:17.620000023 -0500
627 if (!isdigit(end
[-1]))
630 n
= sane_tz_len(line
, end
- line
);
632 n
= tz_with_colon_len(line
, end
- line
);
635 n
= short_time_len(line
, end
- line
);
637 n
= fractional_time_len(line
, end
- line
);
640 n
= date_len(line
, end
- line
);
641 if (!n
) /* No date. Too bad. */
645 if (end
== line
) /* No space before date. */
647 if (end
[-1] == '\t') { /* Success! */
649 return line
+ len
- end
;
651 if (end
[-1] != ' ') /* No space before date. */
654 /* Whitespace damage. */
655 end
-= trailing_spaces_len(line
, end
- line
);
656 return line
+ len
- end
;
659 static char *find_name_common(struct strbuf
*root
,
667 const char *start
= NULL
;
671 while (line
!= end
) {
674 if (!end
&& isspace(c
)) {
677 if (name_terminate(c
, terminate
))
681 if (c
== '/' && !--p_value
)
685 return squash_slash(xstrdup_or_null(def
));
688 return squash_slash(xstrdup_or_null(def
));
691 * Generally we prefer the shorter name, especially
692 * if the other one is just a variation of that with
693 * something else tacked on to the end (ie "file.orig"
697 int deflen
= strlen(def
);
698 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
699 return squash_slash(xstrdup(def
));
703 char *ret
= xstrfmt("%s%.*s", root
->buf
, len
, start
);
704 return squash_slash(ret
);
707 return squash_slash(xmemdupz(start
, len
));
710 static char *find_name(struct strbuf
*root
,
717 char *name
= find_name_gnu(root
, line
, p_value
);
722 return find_name_common(root
, line
, def
, p_value
, NULL
, terminate
);
725 static char *find_name_traditional(struct strbuf
*root
,
734 char *name
= find_name_gnu(root
, line
, p_value
);
739 len
= strchrnul(line
, '\n') - line
;
740 date_len
= diff_timestamp_len(line
, len
);
742 return find_name_common(root
, line
, def
, p_value
, NULL
, TERM_TAB
);
745 return find_name_common(root
, line
, def
, p_value
, line
+ len
, 0);
749 * Given the string after "--- " or "+++ ", guess the appropriate
750 * p_value for the given patch.
752 static int guess_p_value(struct apply_state
*state
, const char *nameline
)
757 if (is_dev_null(nameline
))
759 name
= find_name_traditional(&state
->root
, nameline
, NULL
, 0);
762 cp
= strchr(name
, '/');
765 else if (state
->prefix
) {
767 * Does it begin with "a/$our-prefix" and such? Then this is
768 * very likely to apply to our directory.
770 if (starts_with(name
, state
->prefix
))
771 val
= count_slashes(state
->prefix
);
774 if (starts_with(cp
, state
->prefix
))
775 val
= count_slashes(state
->prefix
) + 1;
783 * Does the ---/+++ line have the POSIX timestamp after the last HT?
784 * GNU diff puts epoch there to signal a creation/deletion event. Is
785 * this such a timestamp?
787 static int has_epoch_timestamp(const char *nameline
)
790 * We are only interested in epoch timestamp; any non-zero
791 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
792 * For the same reason, the date must be either 1969-12-31 or
793 * 1970-01-01, and the seconds part must be "00".
795 const char stamp_regexp
[] =
796 "^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?"
798 "([-+][0-2][0-9]:?[0-5][0-9])\n";
799 const char *timestamp
= NULL
, *cp
, *colon
;
800 static regex_t
*stamp
;
802 int zoneoffset
, epoch_hour
, hour
, minute
;
805 for (cp
= nameline
; *cp
!= '\n'; cp
++) {
813 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
814 * (west of GMT) or 1970-01-01 (east of GMT)
816 if (skip_prefix(timestamp
, "1969-12-31 ", ×tamp
))
818 else if (skip_prefix(timestamp
, "1970-01-01 ", ×tamp
))
824 stamp
= xmalloc(sizeof(*stamp
));
825 if (regcomp(stamp
, stamp_regexp
, REG_EXTENDED
)) {
826 warning(_("Cannot prepare timestamp regexp %s"),
832 status
= regexec(stamp
, timestamp
, ARRAY_SIZE(m
), m
, 0);
834 if (status
!= REG_NOMATCH
)
835 warning(_("regexec returned %d for input: %s"),
840 hour
= strtol(timestamp
, NULL
, 10);
841 minute
= strtol(timestamp
+ m
[1].rm_so
, NULL
, 10);
843 zoneoffset
= strtol(timestamp
+ m
[3].rm_so
+ 1, (char **) &colon
, 10);
845 zoneoffset
= zoneoffset
* 60 + strtol(colon
+ 1, NULL
, 10);
847 zoneoffset
= (zoneoffset
/ 100) * 60 + (zoneoffset
% 100);
848 if (timestamp
[m
[3].rm_so
] == '-')
849 zoneoffset
= -zoneoffset
;
851 return hour
* 60 + minute
- zoneoffset
== epoch_hour
* 60;
855 * Get the name etc info from the ---/+++ lines of a traditional patch header
857 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
858 * files, we can happily check the index for a match, but for creating a
859 * new file we should try to match whatever "patch" does. I have no idea.
861 static int parse_traditional_patch(struct apply_state
*state
,
868 first
+= 4; /* skip "--- " */
869 second
+= 4; /* skip "+++ " */
870 if (!state
->p_value_known
) {
872 p
= guess_p_value(state
, first
);
873 q
= guess_p_value(state
, second
);
875 if (0 <= p
&& p
== q
) {
877 state
->p_value_known
= 1;
880 if (is_dev_null(first
)) {
882 patch
->is_delete
= 0;
883 name
= find_name_traditional(&state
->root
, second
, NULL
, state
->p_value
);
884 patch
->new_name
= name
;
885 } else if (is_dev_null(second
)) {
887 patch
->is_delete
= 1;
888 name
= find_name_traditional(&state
->root
, first
, NULL
, state
->p_value
);
889 patch
->old_name
= name
;
892 first_name
= find_name_traditional(&state
->root
, first
, NULL
, state
->p_value
);
893 name
= find_name_traditional(&state
->root
, second
, first_name
, state
->p_value
);
895 if (has_epoch_timestamp(first
)) {
897 patch
->is_delete
= 0;
898 patch
->new_name
= name
;
899 } else if (has_epoch_timestamp(second
)) {
901 patch
->is_delete
= 1;
902 patch
->old_name
= name
;
904 patch
->old_name
= name
;
905 patch
->new_name
= xstrdup_or_null(name
);
909 return error(_("unable to find filename in patch at line %d"), state
->linenr
);
914 static int gitdiff_hdrend(struct gitdiff_data
*state UNUSED
,
915 const char *line UNUSED
,
916 struct patch
*patch UNUSED
)
922 * We're anal about diff header consistency, to make
923 * sure that we don't end up having strange ambiguous
924 * patches floating around.
926 * As a result, gitdiff_{old|new}name() will check
927 * their names against any previous information, just
930 #define DIFF_OLD_NAME 0
931 #define DIFF_NEW_NAME 1
933 static int gitdiff_verify_name(struct gitdiff_data
*state
,
939 if (!*name
&& !isnull
) {
940 *name
= find_name(state
->root
, line
, NULL
, state
->p_value
, TERM_TAB
);
947 return error(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
948 *name
, state
->linenr
);
949 another
= find_name(state
->root
, line
, NULL
, state
->p_value
, TERM_TAB
);
950 if (!another
|| strcmp(another
, *name
)) {
952 return error((side
== DIFF_NEW_NAME
) ?
953 _("git apply: bad git-diff - inconsistent new filename on line %d") :
954 _("git apply: bad git-diff - inconsistent old filename on line %d"), state
->linenr
);
958 if (!is_dev_null(line
))
959 return error(_("git apply: bad git-diff - expected /dev/null on line %d"), state
->linenr
);
965 static int gitdiff_oldname(struct gitdiff_data
*state
,
969 return gitdiff_verify_name(state
, line
,
970 patch
->is_new
, &patch
->old_name
,
974 static int gitdiff_newname(struct gitdiff_data
*state
,
978 return gitdiff_verify_name(state
, line
,
979 patch
->is_delete
, &patch
->new_name
,
983 static int parse_mode_line(const char *line
, int linenr
, unsigned int *mode
)
986 *mode
= strtoul(line
, &end
, 8);
987 if (end
== line
|| !isspace(*end
))
988 return error(_("invalid mode on line %d: %s"), linenr
, line
);
992 static int gitdiff_oldmode(struct gitdiff_data
*state
,
996 return parse_mode_line(line
, state
->linenr
, &patch
->old_mode
);
999 static int gitdiff_newmode(struct gitdiff_data
*state
,
1001 struct patch
*patch
)
1003 return parse_mode_line(line
, state
->linenr
, &patch
->new_mode
);
1006 static int gitdiff_delete(struct gitdiff_data
*state
,
1008 struct patch
*patch
)
1010 patch
->is_delete
= 1;
1011 free(patch
->old_name
);
1012 patch
->old_name
= xstrdup_or_null(patch
->def_name
);
1013 return gitdiff_oldmode(state
, line
, patch
);
1016 static int gitdiff_newfile(struct gitdiff_data
*state
,
1018 struct patch
*patch
)
1021 free(patch
->new_name
);
1022 patch
->new_name
= xstrdup_or_null(patch
->def_name
);
1023 return gitdiff_newmode(state
, line
, patch
);
1026 static int gitdiff_copysrc(struct gitdiff_data
*state
,
1028 struct patch
*patch
)
1031 free(patch
->old_name
);
1032 patch
->old_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1036 static int gitdiff_copydst(struct gitdiff_data
*state
,
1038 struct patch
*patch
)
1041 free(patch
->new_name
);
1042 patch
->new_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1046 static int gitdiff_renamesrc(struct gitdiff_data
*state
,
1048 struct patch
*patch
)
1050 patch
->is_rename
= 1;
1051 free(patch
->old_name
);
1052 patch
->old_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1056 static int gitdiff_renamedst(struct gitdiff_data
*state
,
1058 struct patch
*patch
)
1060 patch
->is_rename
= 1;
1061 free(patch
->new_name
);
1062 patch
->new_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1066 static int gitdiff_similarity(struct gitdiff_data
*state UNUSED
,
1068 struct patch
*patch
)
1070 unsigned long val
= strtoul(line
, NULL
, 10);
1076 static int gitdiff_dissimilarity(struct gitdiff_data
*state UNUSED
,
1078 struct patch
*patch
)
1080 unsigned long val
= strtoul(line
, NULL
, 10);
1086 static int gitdiff_index(struct gitdiff_data
*state
,
1088 struct patch
*patch
)
1091 * index line is N hexadecimal, "..", N hexadecimal,
1092 * and optional space with octal mode.
1094 const char *ptr
, *eol
;
1096 const unsigned hexsz
= the_hash_algo
->hexsz
;
1098 ptr
= strchr(line
, '.');
1099 if (!ptr
|| ptr
[1] != '.' || hexsz
< ptr
- line
)
1102 memcpy(patch
->old_oid_prefix
, line
, len
);
1103 patch
->old_oid_prefix
[len
] = 0;
1106 ptr
= strchr(line
, ' ');
1107 eol
= strchrnul(line
, '\n');
1109 if (!ptr
|| eol
< ptr
)
1115 memcpy(patch
->new_oid_prefix
, line
, len
);
1116 patch
->new_oid_prefix
[len
] = 0;
1118 return gitdiff_oldmode(state
, ptr
+ 1, patch
);
1123 * This is normal for a diff that doesn't change anything: we'll fall through
1124 * into the next diff. Tell the parser to break out.
1126 static int gitdiff_unrecognized(struct gitdiff_data
*state UNUSED
,
1127 const char *line UNUSED
,
1128 struct patch
*patch UNUSED
)
1134 * Skip p_value leading components from "line"; as we do not accept
1135 * absolute paths, return NULL in that case.
1137 static const char *skip_tree_prefix(int p_value
,
1145 return (llen
&& line
[0] == '/') ? NULL
: line
;
1148 for (i
= 0; i
< llen
; i
++) {
1150 if (ch
== '/' && --nslash
<= 0)
1151 return (i
== 0) ? NULL
: &line
[i
+ 1];
1157 * This is to extract the same name that appears on "diff --git"
1158 * line. We do not find and return anything if it is a rename
1159 * patch, and it is OK because we will find the name elsewhere.
1160 * We need to reliably find name only when it is mode-change only,
1161 * creation or deletion of an empty file. In any of these cases,
1162 * both sides are the same name under a/ and b/ respectively.
1164 static char *git_header_name(int p_value
,
1169 const char *second
= NULL
;
1170 size_t len
, line_len
;
1172 line
+= strlen("diff --git ");
1173 llen
-= strlen("diff --git ");
1177 struct strbuf first
= STRBUF_INIT
;
1178 struct strbuf sp
= STRBUF_INIT
;
1180 if (unquote_c_style(&first
, line
, &second
))
1181 goto free_and_fail1
;
1183 /* strip the a/b prefix including trailing slash */
1184 cp
= skip_tree_prefix(p_value
, first
.buf
, first
.len
);
1186 goto free_and_fail1
;
1187 strbuf_remove(&first
, 0, cp
- first
.buf
);
1190 * second points at one past closing dq of name.
1191 * find the second name.
1193 while ((second
< line
+ llen
) && isspace(*second
))
1196 if (line
+ llen
<= second
)
1197 goto free_and_fail1
;
1198 if (*second
== '"') {
1199 if (unquote_c_style(&sp
, second
, NULL
))
1200 goto free_and_fail1
;
1201 cp
= skip_tree_prefix(p_value
, sp
.buf
, sp
.len
);
1203 goto free_and_fail1
;
1204 /* They must match, otherwise ignore */
1205 if (strcmp(cp
, first
.buf
))
1206 goto free_and_fail1
;
1207 strbuf_release(&sp
);
1208 return strbuf_detach(&first
, NULL
);
1211 /* unquoted second */
1212 cp
= skip_tree_prefix(p_value
, second
, line
+ llen
- second
);
1214 goto free_and_fail1
;
1215 if (line
+ llen
- cp
!= first
.len
||
1216 memcmp(first
.buf
, cp
, first
.len
))
1217 goto free_and_fail1
;
1218 return strbuf_detach(&first
, NULL
);
1221 strbuf_release(&first
);
1222 strbuf_release(&sp
);
1226 /* unquoted first name */
1227 name
= skip_tree_prefix(p_value
, line
, llen
);
1232 * since the first name is unquoted, a dq if exists must be
1233 * the beginning of the second name.
1235 for (second
= name
; second
< line
+ llen
; second
++) {
1236 if (*second
== '"') {
1237 struct strbuf sp
= STRBUF_INIT
;
1240 if (unquote_c_style(&sp
, second
, NULL
))
1241 goto free_and_fail2
;
1243 np
= skip_tree_prefix(p_value
, sp
.buf
, sp
.len
);
1245 goto free_and_fail2
;
1247 len
= sp
.buf
+ sp
.len
- np
;
1248 if (len
< second
- name
&&
1249 !strncmp(np
, name
, len
) &&
1250 isspace(name
[len
])) {
1252 strbuf_remove(&sp
, 0, np
- sp
.buf
);
1253 return strbuf_detach(&sp
, NULL
);
1257 strbuf_release(&sp
);
1263 * Accept a name only if it shows up twice, exactly the same
1266 second
= strchr(name
, '\n');
1269 line_len
= second
- name
;
1270 for (len
= 0 ; ; len
++) {
1271 switch (name
[len
]) {
1276 case '\t': case ' ':
1278 * Is this the separator between the preimage
1279 * and the postimage pathname? Again, we are
1280 * only interested in the case where there is
1281 * no rename, as this is only to set def_name
1282 * and a rename patch has the names elsewhere
1283 * in an unambiguous form.
1286 return NULL
; /* no postimage name */
1287 second
= skip_tree_prefix(p_value
, name
+ len
+ 1,
1288 line_len
- (len
+ 1));
1292 * Does len bytes starting at "name" and "second"
1293 * (that are separated by one HT or SP we just
1294 * found) exactly match?
1296 if (second
[len
] == '\n' && !strncmp(name
, second
, len
))
1297 return xmemdupz(name
, len
);
1302 static int check_header_line(int linenr
, struct patch
*patch
)
1304 int extensions
= (patch
->is_delete
== 1) + (patch
->is_new
== 1) +
1305 (patch
->is_rename
== 1) + (patch
->is_copy
== 1);
1307 return error(_("inconsistent header lines %d and %d"),
1308 patch
->extension_linenr
, linenr
);
1309 if (extensions
&& !patch
->extension_linenr
)
1310 patch
->extension_linenr
= linenr
;
1314 int parse_git_diff_header(struct strbuf
*root
,
1320 struct patch
*patch
)
1322 unsigned long offset
;
1323 struct gitdiff_data parse_hdr_state
;
1325 /* A git diff has explicit new/delete information, so we don't guess */
1327 patch
->is_delete
= 0;
1330 * Some things may not have the old name in the
1331 * rest of the headers anywhere (pure mode changes,
1332 * or removing or adding empty files), so we get
1333 * the default name from the header.
1335 patch
->def_name
= git_header_name(p_value
, line
, len
);
1336 if (patch
->def_name
&& root
->len
) {
1337 char *s
= xstrfmt("%s%s", root
->buf
, patch
->def_name
);
1338 free(patch
->def_name
);
1339 patch
->def_name
= s
;
1345 parse_hdr_state
.root
= root
;
1346 parse_hdr_state
.linenr
= *linenr
;
1347 parse_hdr_state
.p_value
= p_value
;
1349 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, (*linenr
)++) {
1350 static const struct opentry
{
1352 int (*fn
)(struct gitdiff_data
*, const char *, struct patch
*);
1354 { "@@ -", gitdiff_hdrend
},
1355 { "--- ", gitdiff_oldname
},
1356 { "+++ ", gitdiff_newname
},
1357 { "old mode ", gitdiff_oldmode
},
1358 { "new mode ", gitdiff_newmode
},
1359 { "deleted file mode ", gitdiff_delete
},
1360 { "new file mode ", gitdiff_newfile
},
1361 { "copy from ", gitdiff_copysrc
},
1362 { "copy to ", gitdiff_copydst
},
1363 { "rename old ", gitdiff_renamesrc
},
1364 { "rename new ", gitdiff_renamedst
},
1365 { "rename from ", gitdiff_renamesrc
},
1366 { "rename to ", gitdiff_renamedst
},
1367 { "similarity index ", gitdiff_similarity
},
1368 { "dissimilarity index ", gitdiff_dissimilarity
},
1369 { "index ", gitdiff_index
},
1370 { "", gitdiff_unrecognized
},
1374 len
= linelen(line
, size
);
1375 if (!len
|| line
[len
-1] != '\n')
1377 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
1378 const struct opentry
*p
= optable
+ i
;
1379 int oplen
= strlen(p
->str
);
1381 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
1383 res
= p
->fn(&parse_hdr_state
, line
+ oplen
, patch
);
1386 if (check_header_line(*linenr
, patch
))
1395 if (!patch
->old_name
&& !patch
->new_name
) {
1396 if (!patch
->def_name
) {
1397 error(Q_("git diff header lacks filename information when removing "
1398 "%d leading pathname component (line %d)",
1399 "git diff header lacks filename information when removing "
1400 "%d leading pathname components (line %d)",
1401 parse_hdr_state
.p_value
),
1402 parse_hdr_state
.p_value
, *linenr
);
1405 patch
->old_name
= xstrdup(patch
->def_name
);
1406 patch
->new_name
= xstrdup(patch
->def_name
);
1408 if ((!patch
->new_name
&& !patch
->is_delete
) ||
1409 (!patch
->old_name
&& !patch
->is_new
)) {
1410 error(_("git diff header lacks filename information "
1411 "(line %d)"), *linenr
);
1414 patch
->is_toplevel_relative
= 1;
1418 static int parse_num(const char *line
, unsigned long *p
)
1422 if (!isdigit(*line
))
1424 *p
= strtoul(line
, &ptr
, 10);
1428 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
1429 unsigned long *p1
, unsigned long *p2
)
1433 if (offset
< 0 || offset
>= len
)
1438 digits
= parse_num(line
, p1
);
1448 digits
= parse_num(line
+1, p2
);
1457 ex
= strlen(expect
);
1460 if (memcmp(line
, expect
, ex
))
1466 static void recount_diff(const char *line
, int size
, struct fragment
*fragment
)
1468 int oldlines
= 0, newlines
= 0, ret
= 0;
1471 warning("recount: ignore empty hunk");
1476 int len
= linelen(line
, size
);
1484 case ' ': case '\n':
1496 ret
= size
< 3 || !starts_with(line
, "@@ ");
1499 ret
= size
< 5 || !starts_with(line
, "diff ");
1506 warning(_("recount: unexpected line: %.*s"),
1507 (int)linelen(line
, size
), line
);
1512 fragment
->oldlines
= oldlines
;
1513 fragment
->newlines
= newlines
;
1517 * Parse a unified diff fragment header of the
1518 * form "@@ -a,b +c,d @@"
1520 static int parse_fragment_header(const char *line
, int len
, struct fragment
*fragment
)
1524 if (!len
|| line
[len
-1] != '\n')
1527 /* Figure out the number of lines in a fragment */
1528 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
1529 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
1535 * Find file diff header
1538 * -1 if no header was found
1539 * -128 in case of error
1540 * the size of the header in bytes (called "offset") otherwise
1542 static int find_header(struct apply_state
*state
,
1546 struct patch
*patch
)
1548 unsigned long offset
, len
;
1550 patch
->is_toplevel_relative
= 0;
1551 patch
->is_rename
= patch
->is_copy
= 0;
1552 patch
->is_new
= patch
->is_delete
= -1;
1553 patch
->old_mode
= patch
->new_mode
= 0;
1554 patch
->old_name
= patch
->new_name
= NULL
;
1555 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1556 unsigned long nextlen
;
1558 len
= linelen(line
, size
);
1562 /* Testing this early allows us to take a few shortcuts.. */
1567 * Make sure we don't find any unconnected patch fragments.
1568 * That's a sign that we didn't find a header, and that a
1569 * patch has become corrupted/broken up.
1571 if (!memcmp("@@ -", line
, 4)) {
1572 struct fragment dummy
;
1573 if (parse_fragment_header(line
, len
, &dummy
) < 0)
1575 error(_("patch fragment without header at line %d: %.*s"),
1576 state
->linenr
, (int)len
-1, line
);
1584 * Git patch? It might not have a real patch, just a rename
1585 * or mode change, so we handle that specially
1587 if (!memcmp("diff --git ", line
, 11)) {
1588 int git_hdr_len
= parse_git_diff_header(&state
->root
, &state
->linenr
,
1589 state
->p_value
, line
, len
,
1591 if (git_hdr_len
< 0)
1593 if (git_hdr_len
<= len
)
1595 *hdrsize
= git_hdr_len
;
1599 /* --- followed by +++ ? */
1600 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
1604 * We only accept unified patches, so we want it to
1605 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1606 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1608 nextlen
= linelen(line
+ len
, size
- len
);
1609 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
1612 /* Ok, we'll consider it a patch */
1613 if (parse_traditional_patch(state
, line
, line
+len
, patch
))
1615 *hdrsize
= len
+ nextlen
;
1622 static void record_ws_error(struct apply_state
*state
,
1633 state
->whitespace_error
++;
1634 if (state
->squelch_whitespace_errors
&&
1635 state
->squelch_whitespace_errors
< state
->whitespace_error
)
1638 err
= whitespace_error_string(result
);
1639 if (state
->apply_verbosity
> verbosity_silent
)
1640 fprintf(stderr
, "%s:%d: %s.\n%.*s\n",
1641 state
->patch_input_file
, linenr
, err
, len
, line
);
1645 static void check_whitespace(struct apply_state
*state
,
1650 unsigned result
= ws_check(line
+ 1, len
- 1, ws_rule
);
1652 record_ws_error(state
, result
, line
+ 1, len
- 2, state
->linenr
);
1656 * Check if the patch has context lines with CRLF or
1657 * the patch wants to remove lines with CRLF.
1659 static void check_old_for_crlf(struct patch
*patch
, const char *line
, int len
)
1661 if (len
>= 2 && line
[len
-1] == '\n' && line
[len
-2] == '\r') {
1662 patch
->ws_rule
|= WS_CR_AT_EOL
;
1663 patch
->crlf_in_old
= 1;
1669 * Parse a unified diff. Note that this really needs to parse each
1670 * fragment separately, since the only way to know the difference
1671 * between a "---" that is part of a patch, and a "---" that starts
1672 * the next patch is to look at the line counts..
1674 static int parse_fragment(struct apply_state
*state
,
1677 struct patch
*patch
,
1678 struct fragment
*fragment
)
1681 int len
= linelen(line
, size
), offset
;
1682 unsigned long oldlines
, newlines
;
1683 unsigned long leading
, trailing
;
1685 offset
= parse_fragment_header(line
, len
, fragment
);
1688 if (offset
> 0 && patch
->recount
)
1689 recount_diff(line
+ offset
, size
- offset
, fragment
);
1690 oldlines
= fragment
->oldlines
;
1691 newlines
= fragment
->newlines
;
1695 /* Parse the thing.. */
1699 added
= deleted
= 0;
1702 offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1703 if (!oldlines
&& !newlines
)
1705 len
= linelen(line
, size
);
1706 if (!len
|| line
[len
-1] != '\n')
1711 case '\n': /* newer GNU diff, an empty context line */
1715 if (!deleted
&& !added
)
1718 check_old_for_crlf(patch
, line
, len
);
1719 if (!state
->apply_in_reverse
&&
1720 state
->ws_error_action
== correct_ws_error
)
1721 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1724 if (!state
->apply_in_reverse
)
1725 check_old_for_crlf(patch
, line
, len
);
1726 if (state
->apply_in_reverse
&&
1727 state
->ws_error_action
!= nowarn_ws_error
)
1728 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1734 if (state
->apply_in_reverse
)
1735 check_old_for_crlf(patch
, line
, len
);
1736 if (!state
->apply_in_reverse
&&
1737 state
->ws_error_action
!= nowarn_ws_error
)
1738 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1745 * We allow "\ No newline at end of file". Depending
1746 * on locale settings when the patch was produced we
1747 * don't know what this line looks like. The only
1748 * thing we do know is that it begins with "\ ".
1749 * Checking for 12 is just for sanity check -- any
1750 * l10n of "\ No newline..." is at least that long.
1753 if (len
< 12 || memcmp(line
, "\\ ", 2))
1758 if (oldlines
|| newlines
)
1760 if (!patch
->recount
&& !deleted
&& !added
)
1763 fragment
->leading
= leading
;
1764 fragment
->trailing
= trailing
;
1767 * If a fragment ends with an incomplete line, we failed to include
1768 * it in the above loop because we hit oldlines == newlines == 0
1771 if (12 < size
&& !memcmp(line
, "\\ ", 2))
1772 offset
+= linelen(line
, size
);
1774 patch
->lines_added
+= added
;
1775 patch
->lines_deleted
+= deleted
;
1777 if (0 < patch
->is_new
&& oldlines
)
1778 return error(_("new file depends on old contents"));
1779 if (0 < patch
->is_delete
&& newlines
)
1780 return error(_("deleted file still has contents"));
1785 * We have seen "diff --git a/... b/..." header (or a traditional patch
1786 * header). Read hunks that belong to this patch into fragments and hang
1787 * them to the given patch structure.
1789 * The (fragment->patch, fragment->size) pair points into the memory given
1790 * by the caller, not a copy, when we return.
1793 * -1 in case of error,
1794 * the number of bytes in the patch otherwise.
1796 static int parse_single_patch(struct apply_state
*state
,
1799 struct patch
*patch
)
1801 unsigned long offset
= 0;
1802 unsigned long oldlines
= 0, newlines
= 0, context
= 0;
1803 struct fragment
**fragp
= &patch
->fragments
;
1805 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
1806 struct fragment
*fragment
;
1809 CALLOC_ARRAY(fragment
, 1);
1810 fragment
->linenr
= state
->linenr
;
1811 len
= parse_fragment(state
, line
, size
, patch
, fragment
);
1814 return error(_("corrupt patch at line %d"), state
->linenr
);
1816 fragment
->patch
= line
;
1817 fragment
->size
= len
;
1818 oldlines
+= fragment
->oldlines
;
1819 newlines
+= fragment
->newlines
;
1820 context
+= fragment
->leading
+ fragment
->trailing
;
1823 fragp
= &fragment
->next
;
1831 * If something was removed (i.e. we have old-lines) it cannot
1832 * be creation, and if something was added it cannot be
1833 * deletion. However, the reverse is not true; --unified=0
1834 * patches that only add are not necessarily creation even
1835 * though they do not have any old lines, and ones that only
1836 * delete are not necessarily deletion.
1838 * Unfortunately, a real creation/deletion patch do _not_ have
1839 * any context line by definition, so we cannot safely tell it
1840 * apart with --unified=0 insanity. At least if the patch has
1841 * more than one hunk it is not creation or deletion.
1843 if (patch
->is_new
< 0 &&
1844 (oldlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1846 if (patch
->is_delete
< 0 &&
1847 (newlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1848 patch
->is_delete
= 0;
1850 if (0 < patch
->is_new
&& oldlines
)
1851 return error(_("new file %s depends on old contents"), patch
->new_name
);
1852 if (0 < patch
->is_delete
&& newlines
)
1853 return error(_("deleted file %s still has contents"), patch
->old_name
);
1854 if (!patch
->is_delete
&& !newlines
&& context
&& state
->apply_verbosity
> verbosity_silent
)
1857 "file %s becomes empty but is not deleted"),
1863 static inline int metadata_changes(struct patch
*patch
)
1865 return patch
->is_rename
> 0 ||
1866 patch
->is_copy
> 0 ||
1867 patch
->is_new
> 0 ||
1869 (patch
->old_mode
&& patch
->new_mode
&&
1870 patch
->old_mode
!= patch
->new_mode
);
1873 static char *inflate_it(const void *data
, unsigned long size
,
1874 unsigned long inflated_size
)
1880 memset(&stream
, 0, sizeof(stream
));
1882 stream
.next_in
= (unsigned char *)data
;
1883 stream
.avail_in
= size
;
1884 stream
.next_out
= out
= xmalloc(inflated_size
);
1885 stream
.avail_out
= inflated_size
;
1886 git_inflate_init(&stream
);
1887 st
= git_inflate(&stream
, Z_FINISH
);
1888 git_inflate_end(&stream
);
1889 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1897 * Read a binary hunk and return a new fragment; fragment->patch
1898 * points at an allocated memory that the caller must free, so
1899 * it is marked as "->free_patch = 1".
1901 static struct fragment
*parse_binary_hunk(struct apply_state
*state
,
1903 unsigned long *sz_p
,
1908 * Expect a line that begins with binary patch method ("literal"
1909 * or "delta"), followed by the length of data before deflating.
1910 * a sequence of 'length-byte' followed by base-85 encoded data
1911 * should follow, terminated by a newline.
1913 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1914 * and we would limit the patch line to 66 characters,
1915 * so one line can fit up to 13 groups that would decode
1916 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1917 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1920 unsigned long size
= *sz_p
;
1921 char *buffer
= *buf_p
;
1923 unsigned long origlen
;
1926 struct fragment
*frag
;
1928 llen
= linelen(buffer
, size
);
1933 if (starts_with(buffer
, "delta ")) {
1934 patch_method
= BINARY_DELTA_DEFLATED
;
1935 origlen
= strtoul(buffer
+ 6, NULL
, 10);
1937 else if (starts_with(buffer
, "literal ")) {
1938 patch_method
= BINARY_LITERAL_DEFLATED
;
1939 origlen
= strtoul(buffer
+ 8, NULL
, 10);
1948 int byte_length
, max_byte_length
, newsize
;
1949 llen
= linelen(buffer
, size
);
1953 /* consume the blank line */
1959 * Minimum line is "A00000\n" which is 7-byte long,
1960 * and the line length must be multiple of 5 plus 2.
1962 if ((llen
< 7) || (llen
-2) % 5)
1964 max_byte_length
= (llen
- 2) / 5 * 4;
1965 byte_length
= *buffer
;
1966 if ('A' <= byte_length
&& byte_length
<= 'Z')
1967 byte_length
= byte_length
- 'A' + 1;
1968 else if ('a' <= byte_length
&& byte_length
<= 'z')
1969 byte_length
= byte_length
- 'a' + 27;
1972 /* if the input length was not multiple of 4, we would
1973 * have filler at the end but the filler should never
1976 if (max_byte_length
< byte_length
||
1977 byte_length
<= max_byte_length
- 4)
1979 newsize
= hunk_size
+ byte_length
;
1980 data
= xrealloc(data
, newsize
);
1981 if (decode_85(data
+ hunk_size
, buffer
+ 1, byte_length
))
1983 hunk_size
= newsize
;
1988 CALLOC_ARRAY(frag
, 1);
1989 frag
->patch
= inflate_it(data
, hunk_size
, origlen
);
1990 frag
->free_patch
= 1;
1994 frag
->size
= origlen
;
1998 frag
->binary_patch_method
= patch_method
;
2004 error(_("corrupt binary patch at line %d: %.*s"),
2005 state
->linenr
-1, llen
-1, buffer
);
2011 * -1 in case of error,
2012 * the length of the parsed binary patch otherwise
2014 static int parse_binary(struct apply_state
*state
,
2017 struct patch
*patch
)
2020 * We have read "GIT binary patch\n"; what follows is a line
2021 * that says the patch method (currently, either "literal" or
2022 * "delta") and the length of data before deflating; a
2023 * sequence of 'length-byte' followed by base-85 encoded data
2026 * When a binary patch is reversible, there is another binary
2027 * hunk in the same format, starting with patch method (either
2028 * "literal" or "delta") with the length of data, and a sequence
2029 * of length-byte + base-85 encoded data, terminated with another
2030 * empty line. This data, when applied to the postimage, produces
2033 struct fragment
*forward
;
2034 struct fragment
*reverse
;
2038 forward
= parse_binary_hunk(state
, &buffer
, &size
, &status
, &used
);
2039 if (!forward
&& !status
)
2040 /* there has to be one hunk (forward hunk) */
2041 return error(_("unrecognized binary patch at line %d"), state
->linenr
-1);
2043 /* otherwise we already gave an error message */
2046 reverse
= parse_binary_hunk(state
, &buffer
, &size
, &status
, &used_1
);
2051 * Not having reverse hunk is not an error, but having
2052 * a corrupt reverse hunk is.
2054 free((void*) forward
->patch
);
2058 forward
->next
= reverse
;
2059 patch
->fragments
= forward
;
2060 patch
->is_binary
= 1;
2064 static void prefix_one(struct apply_state
*state
, char **name
)
2066 char *old_name
= *name
;
2069 *name
= prefix_filename(state
->prefix
, *name
);
2073 static void prefix_patch(struct apply_state
*state
, struct patch
*p
)
2075 if (!state
->prefix
|| p
->is_toplevel_relative
)
2077 prefix_one(state
, &p
->new_name
);
2078 prefix_one(state
, &p
->old_name
);
2085 static void add_name_limit(struct apply_state
*state
,
2089 struct string_list_item
*it
;
2091 it
= string_list_append(&state
->limit_by_name
, name
);
2092 it
->util
= exclude
? NULL
: (void *) 1;
2095 static int use_patch(struct apply_state
*state
, struct patch
*p
)
2097 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
2100 /* Paths outside are not touched regardless of "--include" */
2101 if (state
->prefix
&& *state
->prefix
) {
2103 if (!skip_prefix(pathname
, state
->prefix
, &rest
) || !*rest
)
2107 /* See if it matches any of exclude/include rule */
2108 for (i
= 0; i
< state
->limit_by_name
.nr
; i
++) {
2109 struct string_list_item
*it
= &state
->limit_by_name
.items
[i
];
2110 if (!wildmatch(it
->string
, pathname
, 0))
2111 return (it
->util
!= NULL
);
2115 * If we had any include, a path that does not match any rule is
2116 * not used. Otherwise, we saw bunch of exclude rules (or none)
2117 * and such a path is used.
2119 return !state
->has_include
;
2123 * Read the patch text in "buffer" that extends for "size" bytes; stop
2124 * reading after seeing a single patch (i.e. changes to a single file).
2125 * Create fragments (i.e. patch hunks) and hang them to the given patch.
2128 * -1 if no header was found or parse_binary() failed,
2129 * -128 on another error,
2130 * the number of bytes consumed otherwise,
2131 * so that the caller can call us again for the next patch.
2133 static int parse_chunk(struct apply_state
*state
, char *buffer
, unsigned long size
, struct patch
*patch
)
2135 int hdrsize
, patchsize
;
2136 int offset
= find_header(state
, buffer
, size
, &hdrsize
, patch
);
2141 prefix_patch(state
, patch
);
2143 if (!use_patch(state
, patch
))
2145 else if (patch
->new_name
)
2146 patch
->ws_rule
= whitespace_rule(state
->repo
->index
,
2149 patch
->ws_rule
= whitespace_rule(state
->repo
->index
,
2152 patchsize
= parse_single_patch(state
,
2153 buffer
+ offset
+ hdrsize
,
2154 size
- offset
- hdrsize
,
2161 static const char git_binary
[] = "GIT binary patch\n";
2162 int hd
= hdrsize
+ offset
;
2163 unsigned long llen
= linelen(buffer
+ hd
, size
- hd
);
2165 if (llen
== sizeof(git_binary
) - 1 &&
2166 !memcmp(git_binary
, buffer
+ hd
, llen
)) {
2169 used
= parse_binary(state
, buffer
+ hd
+ llen
,
2170 size
- hd
- llen
, patch
);
2174 patchsize
= used
+ llen
;
2178 else if (!memcmp(" differ\n", buffer
+ hd
+ llen
- 8, 8)) {
2179 static const char *binhdr
[] = {
2185 for (i
= 0; binhdr
[i
]; i
++) {
2186 int len
= strlen(binhdr
[i
]);
2187 if (len
< size
- hd
&&
2188 !memcmp(binhdr
[i
], buffer
+ hd
, len
)) {
2190 patch
->is_binary
= 1;
2197 /* Empty patch cannot be applied if it is a text patch
2198 * without metadata change. A binary patch appears
2201 if ((state
->apply
|| state
->check
) &&
2202 (!patch
->is_binary
&& !metadata_changes(patch
))) {
2203 error(_("patch with only garbage at line %d"), state
->linenr
);
2208 return offset
+ hdrsize
+ patchsize
;
2211 static void reverse_patches(struct patch
*p
)
2213 for (; p
; p
= p
->next
) {
2214 struct fragment
*frag
= p
->fragments
;
2216 SWAP(p
->new_name
, p
->old_name
);
2217 SWAP(p
->new_mode
, p
->old_mode
);
2218 SWAP(p
->is_new
, p
->is_delete
);
2219 SWAP(p
->lines_added
, p
->lines_deleted
);
2220 SWAP(p
->old_oid_prefix
, p
->new_oid_prefix
);
2222 for (; frag
; frag
= frag
->next
) {
2223 SWAP(frag
->newpos
, frag
->oldpos
);
2224 SWAP(frag
->newlines
, frag
->oldlines
);
2229 static const char pluses
[] =
2230 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2231 static const char minuses
[]=
2232 "----------------------------------------------------------------------";
2234 static void show_stats(struct apply_state
*state
, struct patch
*patch
)
2236 struct strbuf qname
= STRBUF_INIT
;
2237 char *cp
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
2240 quote_c_style(cp
, &qname
, NULL
, 0);
2243 * "scale" the filename
2245 max
= state
->max_len
;
2249 if (qname
.len
> max
) {
2250 cp
= strchr(qname
.buf
+ qname
.len
+ 3 - max
, '/');
2252 cp
= qname
.buf
+ qname
.len
+ 3 - max
;
2253 strbuf_splice(&qname
, 0, cp
- qname
.buf
, "...", 3);
2256 if (patch
->is_binary
) {
2257 printf(" %-*s | Bin\n", max
, qname
.buf
);
2258 strbuf_release(&qname
);
2262 printf(" %-*s |", max
, qname
.buf
);
2263 strbuf_release(&qname
);
2266 * scale the add/delete
2268 max
= max
+ state
->max_change
> 70 ? 70 - max
: state
->max_change
;
2269 add
= patch
->lines_added
;
2270 del
= patch
->lines_deleted
;
2272 if (state
->max_change
> 0) {
2273 int total
= ((add
+ del
) * max
+ state
->max_change
/ 2) / state
->max_change
;
2274 add
= (add
* max
+ state
->max_change
/ 2) / state
->max_change
;
2277 printf("%5d %.*s%.*s\n", patch
->lines_added
+ patch
->lines_deleted
,
2278 add
, pluses
, del
, minuses
);
2281 static int read_old_data(struct stat
*st
, struct patch
*patch
,
2282 const char *path
, struct strbuf
*buf
)
2284 int conv_flags
= patch
->crlf_in_old
?
2285 CONV_EOL_KEEP_CRLF
: CONV_EOL_RENORMALIZE
;
2286 switch (st
->st_mode
& S_IFMT
) {
2288 if (strbuf_readlink(buf
, path
, st
->st_size
) < 0)
2289 return error(_("unable to read symlink %s"), path
);
2292 if (strbuf_read_file(buf
, path
, st
->st_size
) != st
->st_size
)
2293 return error(_("unable to open or read %s"), path
);
2295 * "git apply" without "--index/--cached" should never look
2296 * at the index; the target file may not have been added to
2297 * the index yet, and we may not even be in any Git repository.
2298 * Pass NULL to convert_to_git() to stress this; the function
2299 * should never look at the index when explicit crlf option
2302 convert_to_git(NULL
, path
, buf
->buf
, buf
->len
, buf
, conv_flags
);
2310 * Update the preimage, and the common lines in postimage,
2311 * from buffer buf of length len. If postlen is 0 the postimage
2312 * is updated in place, otherwise it's updated on a new buffer
2316 static void update_pre_post_images(struct image
*preimage
,
2317 struct image
*postimage
,
2319 size_t len
, size_t postlen
)
2321 int i
, ctx
, reduced
;
2322 char *new_buf
, *old_buf
, *fixed
;
2323 struct image fixed_preimage
;
2326 * Update the preimage with whitespace fixes. Note that we
2327 * are not losing preimage->buf -- apply_one_fragment() will
2330 prepare_image(&fixed_preimage
, buf
, len
, 1);
2332 ? fixed_preimage
.nr
== preimage
->nr
2333 : fixed_preimage
.nr
<= preimage
->nr
);
2334 for (i
= 0; i
< fixed_preimage
.nr
; i
++)
2335 fixed_preimage
.line
[i
].flag
= preimage
->line
[i
].flag
;
2336 free(preimage
->line_allocated
);
2337 *preimage
= fixed_preimage
;
2340 * Adjust the common context lines in postimage. This can be
2341 * done in-place when we are shrinking it with whitespace
2342 * fixing, but needs a new buffer when ignoring whitespace or
2343 * expanding leading tabs to spaces.
2345 * We trust the caller to tell us if the update can be done
2346 * in place (postlen==0) or not.
2348 old_buf
= postimage
->buf
;
2350 new_buf
= postimage
->buf
= xmalloc(postlen
);
2353 fixed
= preimage
->buf
;
2355 for (i
= reduced
= ctx
= 0; i
< postimage
->nr
; i
++) {
2356 size_t l_len
= postimage
->line
[i
].len
;
2357 if (!(postimage
->line
[i
].flag
& LINE_COMMON
)) {
2358 /* an added line -- no counterparts in preimage */
2359 memmove(new_buf
, old_buf
, l_len
);
2365 /* a common context -- skip it in the original postimage */
2368 /* and find the corresponding one in the fixed preimage */
2369 while (ctx
< preimage
->nr
&&
2370 !(preimage
->line
[ctx
].flag
& LINE_COMMON
)) {
2371 fixed
+= preimage
->line
[ctx
].len
;
2376 * preimage is expected to run out, if the caller
2377 * fixed addition of trailing blank lines.
2379 if (preimage
->nr
<= ctx
) {
2384 /* and copy it in, while fixing the line length */
2385 l_len
= preimage
->line
[ctx
].len
;
2386 memcpy(new_buf
, fixed
, l_len
);
2389 postimage
->line
[i
].len
= l_len
;
2394 ? postlen
< new_buf
- postimage
->buf
2395 : postimage
->len
< new_buf
- postimage
->buf
)
2396 BUG("caller miscounted postlen: asked %d, orig = %d, used = %d",
2397 (int)postlen
, (int) postimage
->len
, (int)(new_buf
- postimage
->buf
));
2399 /* Fix the length of the whole thing */
2400 postimage
->len
= new_buf
- postimage
->buf
;
2401 postimage
->nr
-= reduced
;
2404 static int line_by_line_fuzzy_match(struct image
*img
,
2405 struct image
*preimage
,
2406 struct image
*postimage
,
2407 unsigned long current
,
2414 size_t postlen
= postimage
->len
;
2419 struct strbuf fixed
;
2423 for (i
= 0; i
< preimage_limit
; i
++) {
2424 size_t prelen
= preimage
->line
[i
].len
;
2425 size_t imglen
= img
->line
[current_lno
+i
].len
;
2427 if (!fuzzy_matchlines(img
->buf
+ current
+ imgoff
, imglen
,
2428 preimage
->buf
+ preoff
, prelen
))
2430 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2431 postlen
+= imglen
- prelen
;
2437 * Ok, the preimage matches with whitespace fuzz.
2439 * imgoff now holds the true length of the target that
2440 * matches the preimage before the end of the file.
2442 * Count the number of characters in the preimage that fall
2443 * beyond the end of the file and make sure that all of them
2444 * are whitespace characters. (This can only happen if
2445 * we are removing blank lines at the end of the file.)
2447 buf
= preimage_eof
= preimage
->buf
+ preoff
;
2448 for ( ; i
< preimage
->nr
; i
++)
2449 preoff
+= preimage
->line
[i
].len
;
2450 preimage_end
= preimage
->buf
+ preoff
;
2451 for ( ; buf
< preimage_end
; buf
++)
2456 * Update the preimage and the common postimage context
2457 * lines to use the same whitespace as the target.
2458 * If whitespace is missing in the target (i.e.
2459 * if the preimage extends beyond the end of the file),
2460 * use the whitespace from the preimage.
2462 extra_chars
= preimage_end
- preimage_eof
;
2463 strbuf_init(&fixed
, imgoff
+ extra_chars
);
2464 strbuf_add(&fixed
, img
->buf
+ current
, imgoff
);
2465 strbuf_add(&fixed
, preimage_eof
, extra_chars
);
2466 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2467 update_pre_post_images(preimage
, postimage
,
2468 fixed_buf
, fixed_len
, postlen
);
2472 static int match_fragment(struct apply_state
*state
,
2474 struct image
*preimage
,
2475 struct image
*postimage
,
2476 unsigned long current
,
2479 int match_beginning
, int match_end
)
2482 char *fixed_buf
, *buf
, *orig
, *target
;
2483 struct strbuf fixed
;
2484 size_t fixed_len
, postlen
;
2487 if (preimage
->nr
+ current_lno
<= img
->nr
) {
2489 * The hunk falls within the boundaries of img.
2491 preimage_limit
= preimage
->nr
;
2492 if (match_end
&& (preimage
->nr
+ current_lno
!= img
->nr
))
2494 } else if (state
->ws_error_action
== correct_ws_error
&&
2495 (ws_rule
& WS_BLANK_AT_EOF
)) {
2497 * This hunk extends beyond the end of img, and we are
2498 * removing blank lines at the end of the file. This
2499 * many lines from the beginning of the preimage must
2500 * match with img, and the remainder of the preimage
2503 preimage_limit
= img
->nr
- current_lno
;
2506 * The hunk extends beyond the end of the img and
2507 * we are not removing blanks at the end, so we
2508 * should reject the hunk at this position.
2513 if (match_beginning
&& current_lno
)
2516 /* Quick hash check */
2517 for (i
= 0; i
< preimage_limit
; i
++)
2518 if ((img
->line
[current_lno
+ i
].flag
& LINE_PATCHED
) ||
2519 (preimage
->line
[i
].hash
!= img
->line
[current_lno
+ i
].hash
))
2522 if (preimage_limit
== preimage
->nr
) {
2524 * Do we have an exact match? If we were told to match
2525 * at the end, size must be exactly at current+fragsize,
2526 * otherwise current+fragsize must be still within the preimage,
2527 * and either case, the old piece should match the preimage
2531 ? (current
+ preimage
->len
== img
->len
)
2532 : (current
+ preimage
->len
<= img
->len
)) &&
2533 !memcmp(img
->buf
+ current
, preimage
->buf
, preimage
->len
))
2537 * The preimage extends beyond the end of img, so
2538 * there cannot be an exact match.
2540 * There must be one non-blank context line that match
2541 * a line before the end of img.
2545 buf
= preimage
->buf
;
2547 for (i
= 0; i
< preimage_limit
; i
++)
2548 buf_end
+= preimage
->line
[i
].len
;
2550 for ( ; buf
< buf_end
; buf
++)
2558 * No exact match. If we are ignoring whitespace, run a line-by-line
2559 * fuzzy matching. We collect all the line length information because
2560 * we need it to adjust whitespace if we match.
2562 if (state
->ws_ignore_action
== ignore_ws_change
)
2563 return line_by_line_fuzzy_match(img
, preimage
, postimage
,
2564 current
, current_lno
, preimage_limit
);
2566 if (state
->ws_error_action
!= correct_ws_error
)
2570 * The hunk does not apply byte-by-byte, but the hash says
2571 * it might with whitespace fuzz. We weren't asked to
2572 * ignore whitespace, we were asked to correct whitespace
2573 * errors, so let's try matching after whitespace correction.
2575 * While checking the preimage against the target, whitespace
2576 * errors in both fixed, we count how large the corresponding
2577 * postimage needs to be. The postimage prepared by
2578 * apply_one_fragment() has whitespace errors fixed on added
2579 * lines already, but the common lines were propagated as-is,
2580 * which may become longer when their whitespace errors are
2584 /* First count added lines in postimage */
2586 for (i
= 0; i
< postimage
->nr
; i
++) {
2587 if (!(postimage
->line
[i
].flag
& LINE_COMMON
))
2588 postlen
+= postimage
->line
[i
].len
;
2592 * The preimage may extend beyond the end of the file,
2593 * but in this loop we will only handle the part of the
2594 * preimage that falls within the file.
2596 strbuf_init(&fixed
, preimage
->len
+ 1);
2597 orig
= preimage
->buf
;
2598 target
= img
->buf
+ current
;
2599 for (i
= 0; i
< preimage_limit
; i
++) {
2600 size_t oldlen
= preimage
->line
[i
].len
;
2601 size_t tgtlen
= img
->line
[current_lno
+ i
].len
;
2602 size_t fixstart
= fixed
.len
;
2603 struct strbuf tgtfix
;
2606 /* Try fixing the line in the preimage */
2607 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2609 /* Try fixing the line in the target */
2610 strbuf_init(&tgtfix
, tgtlen
);
2611 ws_fix_copy(&tgtfix
, target
, tgtlen
, ws_rule
, NULL
);
2614 * If they match, either the preimage was based on
2615 * a version before our tree fixed whitespace breakage,
2616 * or we are lacking a whitespace-fix patch the tree
2617 * the preimage was based on already had (i.e. target
2618 * has whitespace breakage, the preimage doesn't).
2619 * In either case, we are fixing the whitespace breakages
2620 * so we might as well take the fix together with their
2623 match
= (tgtfix
.len
== fixed
.len
- fixstart
&&
2624 !memcmp(tgtfix
.buf
, fixed
.buf
+ fixstart
,
2625 fixed
.len
- fixstart
));
2627 /* Add the length if this is common with the postimage */
2628 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2629 postlen
+= tgtfix
.len
;
2631 strbuf_release(&tgtfix
);
2641 * Now handle the lines in the preimage that falls beyond the
2642 * end of the file (if any). They will only match if they are
2643 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2646 for ( ; i
< preimage
->nr
; i
++) {
2647 size_t fixstart
= fixed
.len
; /* start of the fixed preimage */
2648 size_t oldlen
= preimage
->line
[i
].len
;
2651 /* Try fixing the line in the preimage */
2652 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2654 for (j
= fixstart
; j
< fixed
.len
; j
++)
2655 if (!isspace(fixed
.buf
[j
]))
2662 * Yes, the preimage is based on an older version that still
2663 * has whitespace breakages unfixed, and fixing them makes the
2664 * hunk match. Update the context lines in the postimage.
2666 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2667 if (postlen
< postimage
->len
)
2669 update_pre_post_images(preimage
, postimage
,
2670 fixed_buf
, fixed_len
, postlen
);
2674 strbuf_release(&fixed
);
2678 static int find_pos(struct apply_state
*state
,
2680 struct image
*preimage
,
2681 struct image
*postimage
,
2684 int match_beginning
, int match_end
)
2687 unsigned long backwards
, forwards
, current
;
2688 int backwards_lno
, forwards_lno
, current_lno
;
2691 * When running with --allow-overlap, it is possible that a hunk is
2692 * seen that pretends to start at the beginning (but no longer does),
2693 * and that *still* needs to match the end. So trust `match_end` more
2694 * than `match_beginning`.
2696 if (state
->allow_overlap
&& match_beginning
&& match_end
&&
2697 img
->nr
- preimage
->nr
!= 0)
2698 match_beginning
= 0;
2701 * If match_beginning or match_end is specified, there is no
2702 * point starting from a wrong line that will never match and
2703 * wander around and wait for a match at the specified end.
2705 if (match_beginning
)
2708 line
= img
->nr
- preimage
->nr
;
2711 * Because the comparison is unsigned, the following test
2712 * will also take care of a negative line number that can
2713 * result when match_end and preimage is larger than the target.
2715 if ((size_t) line
> img
->nr
)
2719 for (i
= 0; i
< line
; i
++)
2720 current
+= img
->line
[i
].len
;
2723 * There's probably some smart way to do this, but I'll leave
2724 * that to the smart and beautiful people. I'm simple and stupid.
2726 backwards
= current
;
2727 backwards_lno
= line
;
2729 forwards_lno
= line
;
2732 for (i
= 0; ; i
++) {
2733 if (match_fragment(state
, img
, preimage
, postimage
,
2734 current
, current_lno
, ws_rule
,
2735 match_beginning
, match_end
))
2739 if (backwards_lno
== 0 && forwards_lno
== img
->nr
)
2743 if (backwards_lno
== 0) {
2748 backwards
-= img
->line
[backwards_lno
].len
;
2749 current
= backwards
;
2750 current_lno
= backwards_lno
;
2752 if (forwards_lno
== img
->nr
) {
2756 forwards
+= img
->line
[forwards_lno
].len
;
2759 current_lno
= forwards_lno
;
2766 static void remove_first_line(struct image
*img
)
2768 img
->buf
+= img
->line
[0].len
;
2769 img
->len
-= img
->line
[0].len
;
2774 static void remove_last_line(struct image
*img
)
2776 img
->len
-= img
->line
[--img
->nr
].len
;
2780 * The change from "preimage" and "postimage" has been found to
2781 * apply at applied_pos (counts in line numbers) in "img".
2782 * Update "img" to remove "preimage" and replace it with "postimage".
2784 static void update_image(struct apply_state
*state
,
2787 struct image
*preimage
,
2788 struct image
*postimage
)
2791 * remove the copy of preimage at offset in img
2792 * and replace it with postimage
2795 size_t remove_count
, insert_count
, applied_at
= 0;
2800 * If we are removing blank lines at the end of img,
2801 * the preimage may extend beyond the end.
2802 * If that is the case, we must be careful only to
2803 * remove the part of the preimage that falls within
2804 * the boundaries of img. Initialize preimage_limit
2805 * to the number of lines in the preimage that falls
2806 * within the boundaries.
2808 preimage_limit
= preimage
->nr
;
2809 if (preimage_limit
> img
->nr
- applied_pos
)
2810 preimage_limit
= img
->nr
- applied_pos
;
2812 for (i
= 0; i
< applied_pos
; i
++)
2813 applied_at
+= img
->line
[i
].len
;
2816 for (i
= 0; i
< preimage_limit
; i
++)
2817 remove_count
+= img
->line
[applied_pos
+ i
].len
;
2818 insert_count
= postimage
->len
;
2820 /* Adjust the contents */
2821 result
= xmalloc(st_add3(st_sub(img
->len
, remove_count
), insert_count
, 1));
2822 memcpy(result
, img
->buf
, applied_at
);
2823 memcpy(result
+ applied_at
, postimage
->buf
, postimage
->len
);
2824 memcpy(result
+ applied_at
+ postimage
->len
,
2825 img
->buf
+ (applied_at
+ remove_count
),
2826 img
->len
- (applied_at
+ remove_count
));
2829 img
->len
+= insert_count
- remove_count
;
2830 result
[img
->len
] = '\0';
2832 /* Adjust the line table */
2833 nr
= img
->nr
+ postimage
->nr
- preimage_limit
;
2834 if (preimage_limit
< postimage
->nr
) {
2836 * NOTE: this knows that we never call remove_first_line()
2837 * on anything other than pre/post image.
2839 REALLOC_ARRAY(img
->line
, nr
);
2840 img
->line_allocated
= img
->line
;
2842 if (preimage_limit
!= postimage
->nr
)
2843 MOVE_ARRAY(img
->line
+ applied_pos
+ postimage
->nr
,
2844 img
->line
+ applied_pos
+ preimage_limit
,
2845 img
->nr
- (applied_pos
+ preimage_limit
));
2846 COPY_ARRAY(img
->line
+ applied_pos
, postimage
->line
, postimage
->nr
);
2847 if (!state
->allow_overlap
)
2848 for (i
= 0; i
< postimage
->nr
; i
++)
2849 img
->line
[applied_pos
+ i
].flag
|= LINE_PATCHED
;
2854 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2855 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2856 * replace the part of "img" with "postimage" text.
2858 static int apply_one_fragment(struct apply_state
*state
,
2859 struct image
*img
, struct fragment
*frag
,
2860 int inaccurate_eof
, unsigned ws_rule
,
2863 int match_beginning
, match_end
;
2864 const char *patch
= frag
->patch
;
2865 int size
= frag
->size
;
2866 char *old
, *oldlines
;
2867 struct strbuf newlines
;
2868 int new_blank_lines_at_end
= 0;
2869 int found_new_blank_lines_at_end
= 0;
2870 int hunk_linenr
= frag
->linenr
;
2871 unsigned long leading
, trailing
;
2872 int pos
, applied_pos
;
2873 struct image preimage
;
2874 struct image postimage
;
2876 memset(&preimage
, 0, sizeof(preimage
));
2877 memset(&postimage
, 0, sizeof(postimage
));
2878 oldlines
= xmalloc(size
);
2879 strbuf_init(&newlines
, size
);
2884 int len
= linelen(patch
, size
);
2886 int added_blank_line
= 0;
2887 int is_blank_context
= 0;
2894 * "plen" is how much of the line we should use for
2895 * the actual patch data. Normally we just remove the
2896 * first character on the line, but if the line is
2897 * followed by "\ No newline", then we also remove the
2898 * last one (which is the newline, of course).
2901 if (len
< size
&& patch
[len
] == '\\')
2904 if (state
->apply_in_reverse
) {
2907 else if (first
== '+')
2913 /* Newer GNU diff, empty context line */
2915 /* ... followed by '\No newline'; nothing */
2918 strbuf_addch(&newlines
, '\n');
2919 add_line_info(&preimage
, "\n", 1, LINE_COMMON
);
2920 add_line_info(&postimage
, "\n", 1, LINE_COMMON
);
2921 is_blank_context
= 1;
2924 if (plen
&& (ws_rule
& WS_BLANK_AT_EOF
) &&
2925 ws_blank_line(patch
+ 1, plen
))
2926 is_blank_context
= 1;
2929 memcpy(old
, patch
+ 1, plen
);
2930 add_line_info(&preimage
, old
, plen
,
2931 (first
== ' ' ? LINE_COMMON
: 0));
2937 /* --no-add does not add new lines */
2938 if (first
== '+' && state
->no_add
)
2941 start
= newlines
.len
;
2943 !state
->whitespace_error
||
2944 state
->ws_error_action
!= correct_ws_error
) {
2945 strbuf_add(&newlines
, patch
+ 1, plen
);
2948 ws_fix_copy(&newlines
, patch
+ 1, plen
, ws_rule
, &state
->applied_after_fixing_ws
);
2950 add_line_info(&postimage
, newlines
.buf
+ start
, newlines
.len
- start
,
2951 (first
== '+' ? 0 : LINE_COMMON
));
2953 (ws_rule
& WS_BLANK_AT_EOF
) &&
2954 ws_blank_line(patch
+ 1, plen
))
2955 added_blank_line
= 1;
2957 case '@': case '\\':
2958 /* Ignore it, we already handled it */
2961 if (state
->apply_verbosity
> verbosity_normal
)
2962 error(_("invalid start of line: '%c'"), first
);
2966 if (added_blank_line
) {
2967 if (!new_blank_lines_at_end
)
2968 found_new_blank_lines_at_end
= hunk_linenr
;
2969 new_blank_lines_at_end
++;
2971 else if (is_blank_context
)
2974 new_blank_lines_at_end
= 0;
2979 if (inaccurate_eof
&&
2980 old
> oldlines
&& old
[-1] == '\n' &&
2981 newlines
.len
> 0 && newlines
.buf
[newlines
.len
- 1] == '\n') {
2983 strbuf_setlen(&newlines
, newlines
.len
- 1);
2984 preimage
.line_allocated
[preimage
.nr
- 1].len
--;
2985 postimage
.line_allocated
[postimage
.nr
- 1].len
--;
2988 leading
= frag
->leading
;
2989 trailing
= frag
->trailing
;
2992 * A hunk to change lines at the beginning would begin with
2994 * but we need to be careful. -U0 that inserts before the second
2995 * line also has this pattern.
2997 * And a hunk to add to an empty file would begin with
3000 * In other words, a hunk that is (frag->oldpos <= 1) with or
3001 * without leading context must match at the beginning.
3003 match_beginning
= (!frag
->oldpos
||
3004 (frag
->oldpos
== 1 && !state
->unidiff_zero
));
3007 * A hunk without trailing lines must match at the end.
3008 * However, we simply cannot tell if a hunk must match end
3009 * from the lack of trailing lines if the patch was generated
3010 * with unidiff without any context.
3012 match_end
= !state
->unidiff_zero
&& !trailing
;
3014 pos
= frag
->newpos
? (frag
->newpos
- 1) : 0;
3015 preimage
.buf
= oldlines
;
3016 preimage
.len
= old
- oldlines
;
3017 postimage
.buf
= newlines
.buf
;
3018 postimage
.len
= newlines
.len
;
3019 preimage
.line
= preimage
.line_allocated
;
3020 postimage
.line
= postimage
.line_allocated
;
3024 applied_pos
= find_pos(state
, img
, &preimage
, &postimage
, pos
,
3025 ws_rule
, match_beginning
, match_end
);
3027 if (applied_pos
>= 0)
3030 /* Am I at my context limits? */
3031 if ((leading
<= state
->p_context
) && (trailing
<= state
->p_context
))
3033 if (match_beginning
|| match_end
) {
3034 match_beginning
= match_end
= 0;
3039 * Reduce the number of context lines; reduce both
3040 * leading and trailing if they are equal otherwise
3041 * just reduce the larger context.
3043 if (leading
>= trailing
) {
3044 remove_first_line(&preimage
);
3045 remove_first_line(&postimage
);
3049 if (trailing
> leading
) {
3050 remove_last_line(&preimage
);
3051 remove_last_line(&postimage
);
3056 if (applied_pos
>= 0) {
3057 if (new_blank_lines_at_end
&&
3058 preimage
.nr
+ applied_pos
>= img
->nr
&&
3059 (ws_rule
& WS_BLANK_AT_EOF
) &&
3060 state
->ws_error_action
!= nowarn_ws_error
) {
3061 record_ws_error(state
, WS_BLANK_AT_EOF
, "+", 1,
3062 found_new_blank_lines_at_end
);
3063 if (state
->ws_error_action
== correct_ws_error
) {
3064 while (new_blank_lines_at_end
--)
3065 remove_last_line(&postimage
);
3068 * We would want to prevent write_out_results()
3069 * from taking place in apply_patch() that follows
3070 * the callchain led us here, which is:
3071 * apply_patch->check_patch_list->check_patch->
3072 * apply_data->apply_fragments->apply_one_fragment
3074 if (state
->ws_error_action
== die_on_ws_error
)
3078 if (state
->apply_verbosity
> verbosity_normal
&& applied_pos
!= pos
) {
3079 int offset
= applied_pos
- pos
;
3080 if (state
->apply_in_reverse
)
3081 offset
= 0 - offset
;
3083 Q_("Hunk #%d succeeded at %d (offset %d line).",
3084 "Hunk #%d succeeded at %d (offset %d lines).",
3086 nth_fragment
, applied_pos
+ 1, offset
);
3090 * Warn if it was necessary to reduce the number
3093 if ((leading
!= frag
->leading
||
3094 trailing
!= frag
->trailing
) && state
->apply_verbosity
> verbosity_silent
)
3095 fprintf_ln(stderr
, _("Context reduced to (%ld/%ld)"
3096 " to apply fragment at %d"),
3097 leading
, trailing
, applied_pos
+1);
3098 update_image(state
, img
, applied_pos
, &preimage
, &postimage
);
3100 if (state
->apply_verbosity
> verbosity_normal
)
3101 error(_("while searching for:\n%.*s"),
3102 (int)(old
- oldlines
), oldlines
);
3107 strbuf_release(&newlines
);
3108 free(preimage
.line_allocated
);
3109 free(postimage
.line_allocated
);
3111 return (applied_pos
< 0);
3114 static int apply_binary_fragment(struct apply_state
*state
,
3116 struct patch
*patch
)
3118 struct fragment
*fragment
= patch
->fragments
;
3123 return error(_("missing binary patch data for '%s'"),
3128 /* Binary patch is irreversible without the optional second hunk */
3129 if (state
->apply_in_reverse
) {
3130 if (!fragment
->next
)
3131 return error(_("cannot reverse-apply a binary patch "
3132 "without the reverse hunk to '%s'"),
3134 ? patch
->new_name
: patch
->old_name
);
3135 fragment
= fragment
->next
;
3137 switch (fragment
->binary_patch_method
) {
3138 case BINARY_DELTA_DEFLATED
:
3139 dst
= patch_delta(img
->buf
, img
->len
, fragment
->patch
,
3140 fragment
->size
, &len
);
3147 case BINARY_LITERAL_DEFLATED
:
3149 img
->len
= fragment
->size
;
3150 img
->buf
= xmemdupz(fragment
->patch
, img
->len
);
3157 * Replace "img" with the result of applying the binary patch.
3158 * The binary patch data itself in patch->fragment is still kept
3159 * but the preimage prepared by the caller in "img" is freed here
3160 * or in the helper function apply_binary_fragment() this calls.
3162 static int apply_binary(struct apply_state
*state
,
3164 struct patch
*patch
)
3166 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3167 struct object_id oid
;
3168 const unsigned hexsz
= the_hash_algo
->hexsz
;
3171 * For safety, we require patch index line to contain
3172 * full hex textual object ID for old and new, at least for now.
3174 if (strlen(patch
->old_oid_prefix
) != hexsz
||
3175 strlen(patch
->new_oid_prefix
) != hexsz
||
3176 get_oid_hex(patch
->old_oid_prefix
, &oid
) ||
3177 get_oid_hex(patch
->new_oid_prefix
, &oid
))
3178 return error(_("cannot apply binary patch to '%s' "
3179 "without full index line"), name
);
3181 if (patch
->old_name
) {
3183 * See if the old one matches what the patch
3186 hash_object_file(the_hash_algo
, img
->buf
, img
->len
, OBJ_BLOB
,
3188 if (strcmp(oid_to_hex(&oid
), patch
->old_oid_prefix
))
3189 return error(_("the patch applies to '%s' (%s), "
3190 "which does not match the "
3191 "current contents."),
3192 name
, oid_to_hex(&oid
));
3195 /* Otherwise, the old one must be empty. */
3197 return error(_("the patch applies to an empty "
3198 "'%s' but it is not empty"), name
);
3201 get_oid_hex(patch
->new_oid_prefix
, &oid
);
3202 if (is_null_oid(&oid
)) {
3204 return 0; /* deletion patch */
3207 if (has_object(the_repository
, &oid
, 0)) {
3208 /* We already have the postimage */
3209 enum object_type type
;
3213 result
= repo_read_object_file(the_repository
, &oid
, &type
,
3216 return error(_("the necessary postimage %s for "
3217 "'%s' cannot be read"),
3218 patch
->new_oid_prefix
, name
);
3224 * We have verified buf matches the preimage;
3225 * apply the patch data to it, which is stored
3226 * in the patch->fragments->{patch,size}.
3228 if (apply_binary_fragment(state
, img
, patch
))
3229 return error(_("binary patch does not apply to '%s'"),
3232 /* verify that the result matches */
3233 hash_object_file(the_hash_algo
, img
->buf
, img
->len
, OBJ_BLOB
,
3235 if (strcmp(oid_to_hex(&oid
), patch
->new_oid_prefix
))
3236 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3237 name
, patch
->new_oid_prefix
, oid_to_hex(&oid
));
3243 static int apply_fragments(struct apply_state
*state
, struct image
*img
, struct patch
*patch
)
3245 struct fragment
*frag
= patch
->fragments
;
3246 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3247 unsigned ws_rule
= patch
->ws_rule
;
3248 unsigned inaccurate_eof
= patch
->inaccurate_eof
;
3251 if (patch
->is_binary
)
3252 return apply_binary(state
, img
, patch
);
3256 if (apply_one_fragment(state
, img
, frag
, inaccurate_eof
, ws_rule
, nth
)) {
3257 error(_("patch failed: %s:%ld"), name
, frag
->oldpos
);
3258 if (!state
->apply_with_reject
)
3267 static int read_blob_object(struct strbuf
*buf
, const struct object_id
*oid
, unsigned mode
)
3269 if (S_ISGITLINK(mode
)) {
3270 strbuf_grow(buf
, 100);
3271 strbuf_addf(buf
, "Subproject commit %s\n", oid_to_hex(oid
));
3273 enum object_type type
;
3277 result
= repo_read_object_file(the_repository
, oid
, &type
,
3281 /* XXX read_sha1_file NUL-terminates */
3282 strbuf_attach(buf
, result
, sz
, sz
+ 1);
3287 static int read_file_or_gitlink(const struct cache_entry
*ce
, struct strbuf
*buf
)
3291 return read_blob_object(buf
, &ce
->oid
, ce
->ce_mode
);
3294 static struct patch
*in_fn_table(struct apply_state
*state
, const char *name
)
3296 struct string_list_item
*item
;
3301 item
= string_list_lookup(&state
->fn_table
, name
);
3303 return (struct patch
*)item
->util
;
3309 * item->util in the filename table records the status of the path.
3310 * Usually it points at a patch (whose result records the contents
3311 * of it after applying it), but it could be PATH_WAS_DELETED for a
3312 * path that a previously applied patch has already removed, or
3313 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3315 * The latter is needed to deal with a case where two paths A and B
3316 * are swapped by first renaming A to B and then renaming B to A;
3317 * moving A to B should not be prevented due to presence of B as we
3318 * will remove it in a later patch.
3320 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3321 #define PATH_WAS_DELETED ((struct patch *) -1)
3323 static int to_be_deleted(struct patch
*patch
)
3325 return patch
== PATH_TO_BE_DELETED
;
3328 static int was_deleted(struct patch
*patch
)
3330 return patch
== PATH_WAS_DELETED
;
3333 static void add_to_fn_table(struct apply_state
*state
, struct patch
*patch
)
3335 struct string_list_item
*item
;
3338 * Always add new_name unless patch is a deletion
3339 * This should cover the cases for normal diffs,
3340 * file creations and copies
3342 if (patch
->new_name
) {
3343 item
= string_list_insert(&state
->fn_table
, patch
->new_name
);
3348 * store a failure on rename/deletion cases because
3349 * later chunks shouldn't patch old names
3351 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3352 item
= string_list_insert(&state
->fn_table
, patch
->old_name
);
3353 item
->util
= PATH_WAS_DELETED
;
3357 static void prepare_fn_table(struct apply_state
*state
, struct patch
*patch
)
3360 * store information about incoming file deletion
3363 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3364 struct string_list_item
*item
;
3365 item
= string_list_insert(&state
->fn_table
, patch
->old_name
);
3366 item
->util
= PATH_TO_BE_DELETED
;
3368 patch
= patch
->next
;
3372 static int checkout_target(struct index_state
*istate
,
3373 struct cache_entry
*ce
, struct stat
*st
)
3375 struct checkout costate
= CHECKOUT_INIT
;
3377 costate
.refresh_cache
= 1;
3378 costate
.istate
= istate
;
3379 if (checkout_entry(ce
, &costate
, NULL
, NULL
) ||
3380 lstat(ce
->name
, st
))
3381 return error(_("cannot checkout %s"), ce
->name
);
3385 static struct patch
*previous_patch(struct apply_state
*state
,
3386 struct patch
*patch
,
3389 struct patch
*previous
;
3392 if (patch
->is_copy
|| patch
->is_rename
)
3393 return NULL
; /* "git" patches do not depend on the order */
3395 previous
= in_fn_table(state
, patch
->old_name
);
3399 if (to_be_deleted(previous
))
3400 return NULL
; /* the deletion hasn't happened yet */
3402 if (was_deleted(previous
))
3408 static int verify_index_match(struct apply_state
*state
,
3409 const struct cache_entry
*ce
,
3412 if (S_ISGITLINK(ce
->ce_mode
)) {
3413 if (!S_ISDIR(st
->st_mode
))
3417 return ie_match_stat(state
->repo
->index
, ce
, st
,
3418 CE_MATCH_IGNORE_VALID
| CE_MATCH_IGNORE_SKIP_WORKTREE
);
3421 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3423 static int load_patch_target(struct apply_state
*state
,
3425 const struct cache_entry
*ce
,
3427 struct patch
*patch
,
3429 unsigned expected_mode
)
3431 if (state
->cached
|| state
->check_index
) {
3432 if (read_file_or_gitlink(ce
, buf
))
3433 return error(_("failed to read %s"), name
);
3435 if (S_ISGITLINK(expected_mode
)) {
3437 return read_file_or_gitlink(ce
, buf
);
3439 return SUBMODULE_PATCH_WITHOUT_INDEX
;
3440 } else if (has_symlink_leading_path(name
, strlen(name
))) {
3441 return error(_("reading from '%s' beyond a symbolic link"), name
);
3443 if (read_old_data(st
, patch
, name
, buf
))
3444 return error(_("failed to read %s"), name
);
3451 * We are about to apply "patch"; populate the "image" with the
3452 * current version we have, from the working tree or from the index,
3453 * depending on the situation e.g. --cached/--index. If we are
3454 * applying a non-git patch that incrementally updates the tree,
3455 * we read from the result of a previous diff.
3457 static int load_preimage(struct apply_state
*state
,
3458 struct image
*image
,
3459 struct patch
*patch
, struct stat
*st
,
3460 const struct cache_entry
*ce
)
3462 struct strbuf buf
= STRBUF_INIT
;
3465 struct patch
*previous
;
3468 previous
= previous_patch(state
, patch
, &status
);
3470 return error(_("path %s has been renamed/deleted"),
3473 /* We have a patched copy in memory; use that. */
3474 strbuf_add(&buf
, previous
->result
, previous
->resultsize
);
3476 status
= load_patch_target(state
, &buf
, ce
, st
, patch
,
3477 patch
->old_name
, patch
->old_mode
);
3480 else if (status
== SUBMODULE_PATCH_WITHOUT_INDEX
) {
3482 * There is no way to apply subproject
3483 * patch without looking at the index.
3484 * NEEDSWORK: shouldn't this be flagged
3487 free_fragment_list(patch
->fragments
);
3488 patch
->fragments
= NULL
;
3489 } else if (status
) {
3490 return error(_("failed to read %s"), patch
->old_name
);
3494 img
= strbuf_detach(&buf
, &len
);
3495 prepare_image(image
, img
, len
, !patch
->is_binary
);
3499 static int resolve_to(struct image
*image
, const struct object_id
*result_id
)
3502 enum object_type type
;
3506 image
->buf
= repo_read_object_file(the_repository
, result_id
, &type
,
3508 if (!image
->buf
|| type
!= OBJ_BLOB
)
3509 die("unable to read blob object %s", oid_to_hex(result_id
));
3515 static int three_way_merge(struct apply_state
*state
,
3516 struct image
*image
,
3518 const struct object_id
*base
,
3519 const struct object_id
*ours
,
3520 const struct object_id
*theirs
)
3522 mmfile_t base_file
, our_file
, their_file
;
3523 mmbuffer_t result
= { NULL
};
3524 enum ll_merge_result status
;
3526 /* resolve trivial cases first */
3527 if (oideq(base
, ours
))
3528 return resolve_to(image
, theirs
);
3529 else if (oideq(base
, theirs
) || oideq(ours
, theirs
))
3530 return resolve_to(image
, ours
);
3532 read_mmblob(&base_file
, base
);
3533 read_mmblob(&our_file
, ours
);
3534 read_mmblob(&their_file
, theirs
);
3535 status
= ll_merge(&result
, path
,
3538 &their_file
, "theirs",
3541 if (status
== LL_MERGE_BINARY_CONFLICT
)
3542 warning("Cannot merge binary files: %s (%s vs. %s)",
3543 path
, "ours", "theirs");
3544 free(base_file
.ptr
);
3546 free(their_file
.ptr
);
3547 if (status
< 0 || !result
.ptr
) {
3552 image
->buf
= result
.ptr
;
3553 image
->len
= result
.size
;
3559 * When directly falling back to add/add three-way merge, we read from
3560 * the current contents of the new_name. In no cases other than that
3561 * this function will be called.
3563 static int load_current(struct apply_state
*state
,
3564 struct image
*image
,
3565 struct patch
*patch
)
3567 struct strbuf buf
= STRBUF_INIT
;
3572 struct cache_entry
*ce
;
3573 char *name
= patch
->new_name
;
3574 unsigned mode
= patch
->new_mode
;
3577 BUG("patch to %s is not a creation", patch
->old_name
);
3579 pos
= index_name_pos(state
->repo
->index
, name
, strlen(name
));
3581 return error(_("%s: does not exist in index"), name
);
3582 ce
= state
->repo
->index
->cache
[pos
];
3583 if (lstat(name
, &st
)) {
3584 if (errno
!= ENOENT
)
3585 return error_errno("%s", name
);
3586 if (checkout_target(state
->repo
->index
, ce
, &st
))
3589 if (verify_index_match(state
, ce
, &st
))
3590 return error(_("%s: does not match index"), name
);
3592 status
= load_patch_target(state
, &buf
, ce
, &st
, patch
, name
, mode
);
3597 img
= strbuf_detach(&buf
, &len
);
3598 prepare_image(image
, img
, len
, !patch
->is_binary
);
3602 static int try_threeway(struct apply_state
*state
,
3603 struct image
*image
,
3604 struct patch
*patch
,
3606 const struct cache_entry
*ce
)
3608 struct object_id pre_oid
, post_oid
, our_oid
;
3609 struct strbuf buf
= STRBUF_INIT
;
3613 struct image tmp_image
;
3615 /* No point falling back to 3-way merge in these cases */
3616 if (patch
->is_delete
||
3617 S_ISGITLINK(patch
->old_mode
) || S_ISGITLINK(patch
->new_mode
) ||
3618 (patch
->is_new
&& !patch
->direct_to_threeway
) ||
3619 (patch
->is_rename
&& !patch
->lines_added
&& !patch
->lines_deleted
))
3622 /* Preimage the patch was prepared for */
3624 write_object_file("", 0, OBJ_BLOB
, &pre_oid
);
3625 else if (repo_get_oid(the_repository
, patch
->old_oid_prefix
, &pre_oid
) ||
3626 read_blob_object(&buf
, &pre_oid
, patch
->old_mode
))
3627 return error(_("repository lacks the necessary blob to perform 3-way merge."));
3629 if (state
->apply_verbosity
> verbosity_silent
&& patch
->direct_to_threeway
)
3630 fprintf(stderr
, _("Performing three-way merge...\n"));
3632 img
= strbuf_detach(&buf
, &len
);
3633 prepare_image(&tmp_image
, img
, len
, 1);
3634 /* Apply the patch to get the post image */
3635 if (apply_fragments(state
, &tmp_image
, patch
) < 0) {
3636 clear_image(&tmp_image
);
3639 /* post_oid is theirs */
3640 write_object_file(tmp_image
.buf
, tmp_image
.len
, OBJ_BLOB
, &post_oid
);
3641 clear_image(&tmp_image
);
3643 /* our_oid is ours */
3644 if (patch
->is_new
) {
3645 if (load_current(state
, &tmp_image
, patch
))
3646 return error(_("cannot read the current contents of '%s'"),
3649 if (load_preimage(state
, &tmp_image
, patch
, st
, ce
))
3650 return error(_("cannot read the current contents of '%s'"),
3653 write_object_file(tmp_image
.buf
, tmp_image
.len
, OBJ_BLOB
, &our_oid
);
3654 clear_image(&tmp_image
);
3656 /* in-core three-way merge between post and our using pre as base */
3657 status
= three_way_merge(state
, image
, patch
->new_name
,
3658 &pre_oid
, &our_oid
, &post_oid
);
3660 if (state
->apply_verbosity
> verbosity_silent
)
3662 _("Failed to perform three-way merge...\n"));
3667 patch
->conflicted_threeway
= 1;
3669 oidclr(&patch
->threeway_stage
[0]);
3671 oidcpy(&patch
->threeway_stage
[0], &pre_oid
);
3672 oidcpy(&patch
->threeway_stage
[1], &our_oid
);
3673 oidcpy(&patch
->threeway_stage
[2], &post_oid
);
3674 if (state
->apply_verbosity
> verbosity_silent
)
3676 _("Applied patch to '%s' with conflicts.\n"),
3679 if (state
->apply_verbosity
> verbosity_silent
)
3681 _("Applied patch to '%s' cleanly.\n"),
3687 static int apply_data(struct apply_state
*state
, struct patch
*patch
,
3688 struct stat
*st
, const struct cache_entry
*ce
)
3692 if (load_preimage(state
, &image
, patch
, st
, ce
) < 0)
3695 if (!state
->threeway
|| try_threeway(state
, &image
, patch
, st
, ce
) < 0) {
3696 if (state
->apply_verbosity
> verbosity_silent
&&
3697 state
->threeway
&& !patch
->direct_to_threeway
)
3698 fprintf(stderr
, _("Falling back to direct application...\n"));
3700 /* Note: with --reject, apply_fragments() returns 0 */
3701 if (patch
->direct_to_threeway
|| apply_fragments(state
, &image
, patch
) < 0)
3704 patch
->result
= image
.buf
;
3705 patch
->resultsize
= image
.len
;
3706 add_to_fn_table(state
, patch
);
3707 free(image
.line_allocated
);
3709 if (0 < patch
->is_delete
&& patch
->resultsize
)
3710 return error(_("removal patch leaves file contents"));
3716 * If "patch" that we are looking at modifies or deletes what we have,
3717 * we would want it not to lose any local modification we have, either
3718 * in the working tree or in the index.
3720 * This also decides if a non-git patch is a creation patch or a
3721 * modification to an existing empty file. We do not check the state
3722 * of the current tree for a creation patch in this function; the caller
3723 * check_patch() separately makes sure (and errors out otherwise) that
3724 * the path the patch creates does not exist in the current tree.
3726 static int check_preimage(struct apply_state
*state
,
3727 struct patch
*patch
,
3728 struct cache_entry
**ce
,
3731 const char *old_name
= patch
->old_name
;
3732 struct patch
*previous
= NULL
;
3733 int stat_ret
= 0, status
;
3734 unsigned st_mode
= 0;
3739 assert(patch
->is_new
<= 0);
3740 previous
= previous_patch(state
, patch
, &status
);
3743 return error(_("path %s has been renamed/deleted"), old_name
);
3745 st_mode
= previous
->new_mode
;
3746 } else if (!state
->cached
) {
3747 stat_ret
= lstat(old_name
, st
);
3748 if (stat_ret
&& errno
!= ENOENT
)
3749 return error_errno("%s", old_name
);
3752 if (state
->check_index
&& !previous
) {
3753 int pos
= index_name_pos(state
->repo
->index
, old_name
,
3756 if (patch
->is_new
< 0)
3758 return error(_("%s: does not exist in index"), old_name
);
3760 *ce
= state
->repo
->index
->cache
[pos
];
3762 if (checkout_target(state
->repo
->index
, *ce
, st
))
3765 if (!state
->cached
&& verify_index_match(state
, *ce
, st
))
3766 return error(_("%s: does not match index"), old_name
);
3768 st_mode
= (*ce
)->ce_mode
;
3769 } else if (stat_ret
< 0) {
3770 if (patch
->is_new
< 0)
3772 return error_errno("%s", old_name
);
3775 if (!state
->cached
&& !previous
)
3776 st_mode
= ce_mode_from_stat(*ce
, st
->st_mode
);
3778 if (patch
->is_new
< 0)
3780 if (!patch
->old_mode
)
3781 patch
->old_mode
= st_mode
;
3782 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
3783 return error(_("%s: wrong type"), old_name
);
3784 if (st_mode
!= patch
->old_mode
)
3785 warning(_("%s has type %o, expected %o"),
3786 old_name
, st_mode
, patch
->old_mode
);
3787 if (!patch
->new_mode
&& !patch
->is_delete
)
3788 patch
->new_mode
= st_mode
;
3793 patch
->is_delete
= 0;
3794 FREE_AND_NULL(patch
->old_name
);
3799 #define EXISTS_IN_INDEX 1
3800 #define EXISTS_IN_WORKTREE 2
3801 #define EXISTS_IN_INDEX_AS_ITA 3
3803 static int check_to_create(struct apply_state
*state
,
3804 const char *new_name
,
3809 if (state
->check_index
&& (!ok_if_exists
|| !state
->cached
)) {
3812 pos
= index_name_pos(state
->repo
->index
, new_name
, strlen(new_name
));
3814 struct cache_entry
*ce
= state
->repo
->index
->cache
[pos
];
3816 /* allow ITA, as they do not yet exist in the index */
3817 if (!ok_if_exists
&& !(ce
->ce_flags
& CE_INTENT_TO_ADD
))
3818 return EXISTS_IN_INDEX
;
3820 /* ITA entries can never match working tree files */
3821 if (!state
->cached
&& (ce
->ce_flags
& CE_INTENT_TO_ADD
))
3822 return EXISTS_IN_INDEX_AS_ITA
;
3829 if (!lstat(new_name
, &nst
)) {
3830 if (S_ISDIR(nst
.st_mode
) || ok_if_exists
)
3833 * A leading component of new_name might be a symlink
3834 * that is going to be removed with this patch, but
3835 * still pointing at somewhere that has the path.
3836 * In such a case, path "new_name" does not exist as
3837 * far as git is concerned.
3839 if (has_symlink_leading_path(new_name
, strlen(new_name
)))
3842 return EXISTS_IN_WORKTREE
;
3843 } else if (!is_missing_file_error(errno
)) {
3844 return error_errno("%s", new_name
);
3849 static void prepare_symlink_changes(struct apply_state
*state
, struct patch
*patch
)
3851 for ( ; patch
; patch
= patch
->next
) {
3852 if ((patch
->old_name
&& S_ISLNK(patch
->old_mode
)) &&
3853 (patch
->is_rename
|| patch
->is_delete
))
3854 /* the symlink at patch->old_name is removed */
3855 strset_add(&state
->removed_symlinks
, patch
->old_name
);
3857 if (patch
->new_name
&& S_ISLNK(patch
->new_mode
))
3858 /* the symlink at patch->new_name is created or remains */
3859 strset_add(&state
->kept_symlinks
, patch
->new_name
);
3863 static int path_is_beyond_symlink_1(struct apply_state
*state
, struct strbuf
*name
)
3866 while (--name
->len
&& name
->buf
[name
->len
] != '/')
3867 ; /* scan backwards */
3870 name
->buf
[name
->len
] = '\0';
3871 if (strset_contains(&state
->kept_symlinks
, name
->buf
))
3873 if (strset_contains(&state
->removed_symlinks
, name
->buf
))
3875 * This cannot be "return 0", because we may
3876 * see a new one created at a higher level.
3880 /* otherwise, check the preimage */
3881 if (state
->check_index
) {
3882 struct cache_entry
*ce
;
3884 ce
= index_file_exists(state
->repo
->index
, name
->buf
,
3885 name
->len
, ignore_case
);
3886 if (ce
&& S_ISLNK(ce
->ce_mode
))
3890 if (!lstat(name
->buf
, &st
) && S_ISLNK(st
.st_mode
))
3897 static int path_is_beyond_symlink(struct apply_state
*state
, const char *name_
)
3900 struct strbuf name
= STRBUF_INIT
;
3902 assert(*name_
!= '\0');
3903 strbuf_addstr(&name
, name_
);
3904 ret
= path_is_beyond_symlink_1(state
, &name
);
3905 strbuf_release(&name
);
3910 static int check_unsafe_path(struct patch
*patch
)
3912 const char *old_name
= NULL
;
3913 const char *new_name
= NULL
;
3914 if (patch
->is_delete
)
3915 old_name
= patch
->old_name
;
3916 else if (!patch
->is_new
&& !patch
->is_copy
)
3917 old_name
= patch
->old_name
;
3918 if (!patch
->is_delete
)
3919 new_name
= patch
->new_name
;
3921 if (old_name
&& !verify_path(old_name
, patch
->old_mode
))
3922 return error(_("invalid path '%s'"), old_name
);
3923 if (new_name
&& !verify_path(new_name
, patch
->new_mode
))
3924 return error(_("invalid path '%s'"), new_name
);
3929 * Check and apply the patch in-core; leave the result in patch->result
3930 * for the caller to write it out to the final destination.
3932 static int check_patch(struct apply_state
*state
, struct patch
*patch
)
3935 const char *old_name
= patch
->old_name
;
3936 const char *new_name
= patch
->new_name
;
3937 const char *name
= old_name
? old_name
: new_name
;
3938 struct cache_entry
*ce
= NULL
;
3939 struct patch
*tpatch
;
3943 patch
->rejected
= 1; /* we will drop this after we succeed */
3945 status
= check_preimage(state
, patch
, &ce
, &st
);
3948 old_name
= patch
->old_name
;
3951 * A type-change diff is always split into a patch to delete
3952 * old, immediately followed by a patch to create new (see
3953 * diff.c::run_diff()); in such a case it is Ok that the entry
3954 * to be deleted by the previous patch is still in the working
3955 * tree and in the index.
3957 * A patch to swap-rename between A and B would first rename A
3958 * to B and then rename B to A. While applying the first one,
3959 * the presence of B should not stop A from getting renamed to
3960 * B; ask to_be_deleted() about the later rename. Removal of
3961 * B and rename from A to B is handled the same way by asking
3964 if ((tpatch
= in_fn_table(state
, new_name
)) &&
3965 (was_deleted(tpatch
) || to_be_deleted(tpatch
)))
3971 ((0 < patch
->is_new
) || patch
->is_rename
|| patch
->is_copy
)) {
3972 int err
= check_to_create(state
, new_name
, ok_if_exists
);
3974 if (err
&& state
->threeway
) {
3975 patch
->direct_to_threeway
= 1;
3976 } else switch (err
) {
3979 case EXISTS_IN_INDEX
:
3980 return error(_("%s: already exists in index"), new_name
);
3981 case EXISTS_IN_INDEX_AS_ITA
:
3982 return error(_("%s: does not match index"), new_name
);
3983 case EXISTS_IN_WORKTREE
:
3984 return error(_("%s: already exists in working directory"),
3990 if (!patch
->new_mode
) {
3991 if (0 < patch
->is_new
)
3992 patch
->new_mode
= S_IFREG
| 0644;
3994 patch
->new_mode
= patch
->old_mode
;
3998 if (new_name
&& old_name
) {
3999 int same
= !strcmp(old_name
, new_name
);
4000 if (!patch
->new_mode
)
4001 patch
->new_mode
= patch
->old_mode
;
4002 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
) {
4004 return error(_("new mode (%o) of %s does not "
4005 "match old mode (%o)"),
4006 patch
->new_mode
, new_name
,
4009 return error(_("new mode (%o) of %s does not "
4010 "match old mode (%o) of %s"),
4011 patch
->new_mode
, new_name
,
4012 patch
->old_mode
, old_name
);
4016 if (!state
->unsafe_paths
&& check_unsafe_path(patch
))
4020 * An attempt to read from or delete a path that is beyond a
4021 * symbolic link will be prevented by load_patch_target() that
4022 * is called at the beginning of apply_data() so we do not
4023 * have to worry about a patch marked with "is_delete" bit
4024 * here. We however need to make sure that the patch result
4025 * is not deposited to a path that is beyond a symbolic link
4028 if (!patch
->is_delete
&& path_is_beyond_symlink(state
, patch
->new_name
))
4029 return error(_("affected file '%s' is beyond a symbolic link"),
4032 if (apply_data(state
, patch
, &st
, ce
) < 0)
4033 return error(_("%s: patch does not apply"), name
);
4034 patch
->rejected
= 0;
4038 static int check_patch_list(struct apply_state
*state
, struct patch
*patch
)
4042 prepare_symlink_changes(state
, patch
);
4043 prepare_fn_table(state
, patch
);
4046 if (state
->apply_verbosity
> verbosity_normal
)
4047 say_patch_name(stderr
,
4048 _("Checking patch %s..."), patch
);
4049 res
= check_patch(state
, patch
);
4053 patch
= patch
->next
;
4058 static int read_apply_cache(struct apply_state
*state
)
4060 if (state
->index_file
)
4061 return read_index_from(state
->repo
->index
, state
->index_file
,
4064 return repo_read_index(state
->repo
);
4067 /* This function tries to read the object name from the current index */
4068 static int get_current_oid(struct apply_state
*state
, const char *path
,
4069 struct object_id
*oid
)
4073 if (read_apply_cache(state
) < 0)
4075 pos
= index_name_pos(state
->repo
->index
, path
, strlen(path
));
4078 oidcpy(oid
, &state
->repo
->index
->cache
[pos
]->oid
);
4082 static int preimage_oid_in_gitlink_patch(struct patch
*p
, struct object_id
*oid
)
4085 * A usable gitlink patch has only one fragment (hunk) that looks like:
4087 * -Subproject commit <old sha1>
4088 * +Subproject commit <new sha1>
4091 * -Subproject commit <old sha1>
4092 * for a removal patch.
4094 struct fragment
*hunk
= p
->fragments
;
4095 static const char heading
[] = "-Subproject commit ";
4098 if (/* does the patch have only one hunk? */
4099 hunk
&& !hunk
->next
&&
4100 /* is its preimage one line? */
4101 hunk
->oldpos
== 1 && hunk
->oldlines
== 1 &&
4102 /* does preimage begin with the heading? */
4103 (preimage
= memchr(hunk
->patch
, '\n', hunk
->size
)) != NULL
&&
4104 starts_with(++preimage
, heading
) &&
4105 /* does it record full SHA-1? */
4106 !get_oid_hex(preimage
+ sizeof(heading
) - 1, oid
) &&
4107 preimage
[sizeof(heading
) + the_hash_algo
->hexsz
- 1] == '\n' &&
4108 /* does the abbreviated name on the index line agree with it? */
4109 starts_with(preimage
+ sizeof(heading
) - 1, p
->old_oid_prefix
))
4110 return 0; /* it all looks fine */
4112 /* we may have full object name on the index line */
4113 return get_oid_hex(p
->old_oid_prefix
, oid
);
4116 /* Build an index that contains just the files needed for a 3way merge */
4117 static int build_fake_ancestor(struct apply_state
*state
, struct patch
*list
)
4119 struct patch
*patch
;
4120 struct index_state result
= INDEX_STATE_INIT(state
->repo
);
4121 struct lock_file lock
= LOCK_INIT
;
4124 /* Once we start supporting the reverse patch, it may be
4125 * worth showing the new sha1 prefix, but until then...
4127 for (patch
= list
; patch
; patch
= patch
->next
) {
4128 struct object_id oid
;
4129 struct cache_entry
*ce
;
4132 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
4133 if (0 < patch
->is_new
)
4136 if (S_ISGITLINK(patch
->old_mode
)) {
4137 if (!preimage_oid_in_gitlink_patch(patch
, &oid
))
4138 ; /* ok, the textual part looks sane */
4140 return error(_("sha1 information is lacking or "
4141 "useless for submodule %s"), name
);
4142 } else if (!repo_get_oid_blob(the_repository
, patch
->old_oid_prefix
, &oid
)) {
4144 } else if (!patch
->lines_added
&& !patch
->lines_deleted
) {
4145 /* mode-only change: update the current */
4146 if (get_current_oid(state
, patch
->old_name
, &oid
))
4147 return error(_("mode change for %s, which is not "
4148 "in current HEAD"), name
);
4150 return error(_("sha1 information is lacking or useless "
4153 ce
= make_cache_entry(&result
, patch
->old_mode
, &oid
, name
, 0, 0);
4155 return error(_("make_cache_entry failed for path '%s'"),
4157 if (add_index_entry(&result
, ce
, ADD_CACHE_OK_TO_ADD
)) {
4158 discard_cache_entry(ce
);
4159 return error(_("could not add %s to temporary index"),
4164 hold_lock_file_for_update(&lock
, state
->fake_ancestor
, LOCK_DIE_ON_ERROR
);
4165 res
= write_locked_index(&result
, &lock
, COMMIT_LOCK
);
4166 discard_index(&result
);
4169 return error(_("could not write temporary index to %s"),
4170 state
->fake_ancestor
);
4175 static void stat_patch_list(struct apply_state
*state
, struct patch
*patch
)
4177 int files
, adds
, dels
;
4179 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
4181 adds
+= patch
->lines_added
;
4182 dels
+= patch
->lines_deleted
;
4183 show_stats(state
, patch
);
4186 print_stat_summary(stdout
, files
, adds
, dels
);
4189 static void numstat_patch_list(struct apply_state
*state
,
4190 struct patch
*patch
)
4192 for ( ; patch
; patch
= patch
->next
) {
4194 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
4195 if (patch
->is_binary
)
4198 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
4199 write_name_quoted(name
, stdout
, state
->line_termination
);
4203 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
4206 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
4208 printf(" %s %s\n", newdelete
, name
);
4211 static void show_mode_change(struct patch
*p
, int show_name
)
4213 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
4215 printf(" mode change %06o => %06o %s\n",
4216 p
->old_mode
, p
->new_mode
, p
->new_name
);
4218 printf(" mode change %06o => %06o\n",
4219 p
->old_mode
, p
->new_mode
);
4223 static void show_rename_copy(struct patch
*p
)
4225 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
4226 const char *old_name
, *new_name
;
4228 /* Find common prefix */
4229 old_name
= p
->old_name
;
4230 new_name
= p
->new_name
;
4232 const char *slash_old
, *slash_new
;
4233 slash_old
= strchr(old_name
, '/');
4234 slash_new
= strchr(new_name
, '/');
4237 slash_old
- old_name
!= slash_new
- new_name
||
4238 memcmp(old_name
, new_name
, slash_new
- new_name
))
4240 old_name
= slash_old
+ 1;
4241 new_name
= slash_new
+ 1;
4243 /* p->old_name through old_name is the common prefix, and old_name and
4244 * new_name through the end of names are renames
4246 if (old_name
!= p
->old_name
)
4247 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
4248 (int)(old_name
- p
->old_name
), p
->old_name
,
4249 old_name
, new_name
, p
->score
);
4251 printf(" %s %s => %s (%d%%)\n", renamecopy
,
4252 p
->old_name
, p
->new_name
, p
->score
);
4253 show_mode_change(p
, 0);
4256 static void summary_patch_list(struct patch
*patch
)
4260 for (p
= patch
; p
; p
= p
->next
) {
4262 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
4263 else if (p
->is_delete
)
4264 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
4266 if (p
->is_rename
|| p
->is_copy
)
4267 show_rename_copy(p
);
4270 printf(" rewrite %s (%d%%)\n",
4271 p
->new_name
, p
->score
);
4272 show_mode_change(p
, 0);
4275 show_mode_change(p
, 1);
4281 static void patch_stats(struct apply_state
*state
, struct patch
*patch
)
4283 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
4285 if (lines
> state
->max_change
)
4286 state
->max_change
= lines
;
4287 if (patch
->old_name
) {
4288 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
4290 len
= strlen(patch
->old_name
);
4291 if (len
> state
->max_len
)
4292 state
->max_len
= len
;
4294 if (patch
->new_name
) {
4295 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
4297 len
= strlen(patch
->new_name
);
4298 if (len
> state
->max_len
)
4299 state
->max_len
= len
;
4303 static int remove_file(struct apply_state
*state
, struct patch
*patch
, int rmdir_empty
)
4305 if (state
->update_index
&& !state
->ita_only
) {
4306 if (remove_file_from_index(state
->repo
->index
, patch
->old_name
) < 0)
4307 return error(_("unable to remove %s from index"), patch
->old_name
);
4309 if (!state
->cached
) {
4310 if (!remove_or_warn(patch
->old_mode
, patch
->old_name
) && rmdir_empty
) {
4311 remove_path(patch
->old_name
);
4317 static int add_index_file(struct apply_state
*state
,
4324 struct cache_entry
*ce
;
4325 int namelen
= strlen(path
);
4327 ce
= make_empty_cache_entry(state
->repo
->index
, namelen
);
4328 memcpy(ce
->name
, path
, namelen
);
4329 ce
->ce_mode
= create_ce_mode(mode
);
4330 ce
->ce_flags
= create_ce_flags(0);
4331 ce
->ce_namelen
= namelen
;
4332 if (state
->ita_only
) {
4333 ce
->ce_flags
|= CE_INTENT_TO_ADD
;
4334 set_object_name_for_intent_to_add_entry(ce
);
4335 } else if (S_ISGITLINK(mode
)) {
4338 if (!skip_prefix(buf
, "Subproject commit ", &s
) ||
4339 get_oid_hex(s
, &ce
->oid
)) {
4340 discard_cache_entry(ce
);
4341 return error(_("corrupt patch for submodule %s"), path
);
4344 if (!state
->cached
) {
4345 if (lstat(path
, &st
) < 0) {
4346 discard_cache_entry(ce
);
4347 return error_errno(_("unable to stat newly "
4348 "created file '%s'"),
4351 fill_stat_cache_info(state
->repo
->index
, ce
, &st
);
4353 if (write_object_file(buf
, size
, OBJ_BLOB
, &ce
->oid
) < 0) {
4354 discard_cache_entry(ce
);
4355 return error(_("unable to create backing store "
4356 "for newly created file %s"), path
);
4359 if (add_index_entry(state
->repo
->index
, ce
, ADD_CACHE_OK_TO_ADD
) < 0) {
4360 discard_cache_entry(ce
);
4361 return error(_("unable to add cache entry for %s"), path
);
4369 * -1 if an unrecoverable error happened
4370 * 0 if everything went well
4371 * 1 if a recoverable error happened
4373 static int try_create_file(struct apply_state
*state
, const char *path
,
4374 unsigned int mode
, const char *buf
,
4378 struct strbuf nbuf
= STRBUF_INIT
;
4380 if (S_ISGITLINK(mode
)) {
4382 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
))
4384 return !!mkdir(path
, 0777);
4387 if (has_symlinks
&& S_ISLNK(mode
))
4388 /* Although buf:size is counted string, it also is NUL
4391 return !!symlink(buf
, path
);
4393 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
4397 if (convert_to_working_tree(state
->repo
->index
, path
, buf
, size
, &nbuf
, NULL
)) {
4402 res
= write_in_full(fd
, buf
, size
) < 0;
4404 error_errno(_("failed to write to '%s'"), path
);
4405 strbuf_release(&nbuf
);
4407 if (close(fd
) < 0 && !res
)
4408 return error_errno(_("closing file '%s'"), path
);
4410 return res
? -1 : 0;
4414 * We optimistically assume that the directories exist,
4415 * which is true 99% of the time anyway. If they don't,
4416 * we create them and try again.
4422 static int create_one_file(struct apply_state
*state
,
4434 * We already try to detect whether files are beyond a symlink in our
4435 * up-front checks. But in the case where symlinks are created by any
4436 * of the intermediate hunks it can happen that our up-front checks
4437 * didn't yet see the symlink, but at the point of arriving here there
4438 * in fact is one. We thus repeat the check for symlinks here.
4440 * Note that this does not make the up-front check obsolete as the
4441 * failure mode is different:
4443 * - The up-front checks cause us to abort before we have written
4444 * anything into the working directory. So when we exit this way the
4445 * working directory remains clean.
4447 * - The checks here happen in the middle of the action where we have
4448 * already started to apply the patch. The end result will be a dirty
4449 * working directory.
4451 * Ideally, we should update the up-front checks to catch what would
4452 * happen when we apply the patch before we damage the working tree.
4453 * We have all the information necessary to do so. But for now, as a
4454 * part of embargoed security work, having this check would serve as a
4455 * reasonable first step.
4457 if (path_is_beyond_symlink(state
, path
))
4458 return error(_("affected file '%s' is beyond a symbolic link"), path
);
4460 res
= try_create_file(state
, path
, mode
, buf
, size
);
4466 if (errno
== ENOENT
) {
4467 if (safe_create_leading_directories_no_share(path
))
4469 res
= try_create_file(state
, path
, mode
, buf
, size
);
4476 if (errno
== EEXIST
|| errno
== EACCES
) {
4477 /* We may be trying to create a file where a directory
4481 if (!lstat(path
, &st
) && (!S_ISDIR(st
.st_mode
) || !rmdir(path
)))
4485 if (errno
== EEXIST
) {
4486 unsigned int nr
= getpid();
4489 char newpath
[PATH_MAX
];
4490 mksnpath(newpath
, sizeof(newpath
), "%s~%u", path
, nr
);
4491 res
= try_create_file(state
, newpath
, mode
, buf
, size
);
4495 if (!rename(newpath
, path
))
4497 unlink_or_warn(newpath
);
4500 if (errno
!= EEXIST
)
4505 return error_errno(_("unable to write file '%s' mode %o"),
4509 static int add_conflicted_stages_file(struct apply_state
*state
,
4510 struct patch
*patch
)
4514 struct cache_entry
*ce
;
4516 if (!state
->update_index
)
4518 namelen
= strlen(patch
->new_name
);
4519 mode
= patch
->new_mode
? patch
->new_mode
: (S_IFREG
| 0644);
4521 remove_file_from_index(state
->repo
->index
, patch
->new_name
);
4522 for (stage
= 1; stage
< 4; stage
++) {
4523 if (is_null_oid(&patch
->threeway_stage
[stage
- 1]))
4525 ce
= make_empty_cache_entry(state
->repo
->index
, namelen
);
4526 memcpy(ce
->name
, patch
->new_name
, namelen
);
4527 ce
->ce_mode
= create_ce_mode(mode
);
4528 ce
->ce_flags
= create_ce_flags(stage
);
4529 ce
->ce_namelen
= namelen
;
4530 oidcpy(&ce
->oid
, &patch
->threeway_stage
[stage
- 1]);
4531 if (add_index_entry(state
->repo
->index
, ce
, ADD_CACHE_OK_TO_ADD
) < 0) {
4532 discard_cache_entry(ce
);
4533 return error(_("unable to add cache entry for %s"),
4541 static int create_file(struct apply_state
*state
, struct patch
*patch
)
4543 char *path
= patch
->new_name
;
4544 unsigned mode
= patch
->new_mode
;
4545 unsigned long size
= patch
->resultsize
;
4546 char *buf
= patch
->result
;
4549 mode
= S_IFREG
| 0644;
4550 if (create_one_file(state
, path
, mode
, buf
, size
))
4553 if (patch
->conflicted_threeway
)
4554 return add_conflicted_stages_file(state
, patch
);
4555 else if (state
->update_index
)
4556 return add_index_file(state
, path
, mode
, buf
, size
);
4560 /* phase zero is to remove, phase one is to create */
4561 static int write_out_one_result(struct apply_state
*state
,
4562 struct patch
*patch
,
4565 if (patch
->is_delete
> 0) {
4567 return remove_file(state
, patch
, 1);
4570 if (patch
->is_new
> 0 || patch
->is_copy
) {
4572 return create_file(state
, patch
);
4576 * Rename or modification boils down to the same
4577 * thing: remove the old, write the new
4580 return remove_file(state
, patch
, patch
->is_rename
);
4582 return create_file(state
, patch
);
4586 static int write_out_one_reject(struct apply_state
*state
, struct patch
*patch
)
4589 char namebuf
[PATH_MAX
];
4590 struct fragment
*frag
;
4592 struct strbuf sb
= STRBUF_INIT
;
4594 for (cnt
= 0, frag
= patch
->fragments
; frag
; frag
= frag
->next
) {
4595 if (!frag
->rejected
)
4601 if (state
->apply_verbosity
> verbosity_normal
)
4602 say_patch_name(stderr
,
4603 _("Applied patch %s cleanly."), patch
);
4607 /* This should not happen, because a removal patch that leaves
4608 * contents are marked "rejected" at the patch level.
4610 if (!patch
->new_name
)
4611 die(_("internal error"));
4613 /* Say this even without --verbose */
4614 strbuf_addf(&sb
, Q_("Applying patch %%s with %d reject...",
4615 "Applying patch %%s with %d rejects...",
4618 if (state
->apply_verbosity
> verbosity_silent
)
4619 say_patch_name(stderr
, sb
.buf
, patch
);
4620 strbuf_release(&sb
);
4622 cnt
= strlen(patch
->new_name
);
4623 if (ARRAY_SIZE(namebuf
) <= cnt
+ 5) {
4624 cnt
= ARRAY_SIZE(namebuf
) - 5;
4625 warning(_("truncating .rej filename to %.*s.rej"),
4626 cnt
- 1, patch
->new_name
);
4628 memcpy(namebuf
, patch
->new_name
, cnt
);
4629 memcpy(namebuf
+ cnt
, ".rej", 5);
4631 fd
= open(namebuf
, O_CREAT
| O_EXCL
| O_WRONLY
, 0666);
4633 if (errno
!= EEXIST
)
4634 return error_errno(_("cannot open %s"), namebuf
);
4635 if (unlink(namebuf
))
4636 return error_errno(_("cannot unlink '%s'"), namebuf
);
4637 fd
= open(namebuf
, O_CREAT
| O_EXCL
| O_WRONLY
, 0666);
4639 return error_errno(_("cannot open %s"), namebuf
);
4641 rej
= fdopen(fd
, "w");
4643 return error_errno(_("cannot open %s"), namebuf
);
4645 /* Normal git tools never deal with .rej, so do not pretend
4646 * this is a git patch by saying --git or giving extended
4647 * headers. While at it, maybe please "kompare" that wants
4648 * the trailing TAB and some garbage at the end of line ;-).
4650 fprintf(rej
, "diff a/%s b/%s\t(rejected hunks)\n",
4651 patch
->new_name
, patch
->new_name
);
4652 for (cnt
= 1, frag
= patch
->fragments
;
4654 cnt
++, frag
= frag
->next
) {
4655 if (!frag
->rejected
) {
4656 if (state
->apply_verbosity
> verbosity_silent
)
4657 fprintf_ln(stderr
, _("Hunk #%d applied cleanly."), cnt
);
4660 if (state
->apply_verbosity
> verbosity_silent
)
4661 fprintf_ln(stderr
, _("Rejected hunk #%d."), cnt
);
4662 fprintf(rej
, "%.*s", frag
->size
, frag
->patch
);
4663 if (frag
->patch
[frag
->size
-1] != '\n')
4672 * -1 if an error happened
4673 * 0 if the patch applied cleanly
4674 * 1 if the patch did not apply cleanly
4676 static int write_out_results(struct apply_state
*state
, struct patch
*list
)
4681 struct string_list cpath
= STRING_LIST_INIT_DUP
;
4683 for (phase
= 0; phase
< 2; phase
++) {
4689 if (write_out_one_result(state
, l
, phase
)) {
4690 string_list_clear(&cpath
, 0);
4694 if (write_out_one_reject(state
, l
))
4696 if (l
->conflicted_threeway
) {
4697 string_list_append(&cpath
, l
->new_name
);
4707 struct string_list_item
*item
;
4709 string_list_sort(&cpath
);
4710 if (state
->apply_verbosity
> verbosity_silent
) {
4711 for_each_string_list_item(item
, &cpath
)
4712 fprintf(stderr
, "U %s\n", item
->string
);
4714 string_list_clear(&cpath
, 0);
4717 * rerere relies on the partially merged result being in the working
4718 * tree with conflict markers, but that isn't written with --cached.
4721 repo_rerere(state
->repo
, 0);
4728 * Try to apply a patch.
4731 * -128 if a bad error happened (like patch unreadable)
4732 * -1 if patch did not apply and user cannot deal with it
4733 * 0 if the patch applied
4734 * 1 if the patch did not apply but user might fix it
4736 static int apply_patch(struct apply_state
*state
,
4738 const char *filename
,
4742 struct strbuf buf
= STRBUF_INIT
; /* owns the patch text */
4743 struct patch
*list
= NULL
, **listp
= &list
;
4744 int skipped_patch
= 0;
4746 int flush_attributes
= 0;
4748 state
->patch_input_file
= filename
;
4749 if (read_patch_file(&buf
, fd
) < 0)
4752 while (offset
< buf
.len
) {
4753 struct patch
*patch
;
4756 CALLOC_ARRAY(patch
, 1);
4757 patch
->inaccurate_eof
= !!(options
& APPLY_OPT_INACCURATE_EOF
);
4758 patch
->recount
= !!(options
& APPLY_OPT_RECOUNT
);
4759 nr
= parse_chunk(state
, buf
.buf
+ offset
, buf
.len
- offset
, patch
);
4768 if (state
->apply_in_reverse
)
4769 reverse_patches(patch
);
4770 if (use_patch(state
, patch
)) {
4771 patch_stats(state
, patch
);
4772 if (!list
|| !state
->apply_in_reverse
) {
4774 listp
= &patch
->next
;
4780 if ((patch
->new_name
&&
4781 ends_with_path_components(patch
->new_name
,
4782 GITATTRIBUTES_FILE
)) ||
4784 ends_with_path_components(patch
->old_name
,
4785 GITATTRIBUTES_FILE
)))
4786 flush_attributes
= 1;
4789 if (state
->apply_verbosity
> verbosity_normal
)
4790 say_patch_name(stderr
, _("Skipped patch '%s'."), patch
);
4797 if (!list
&& !skipped_patch
) {
4798 if (!state
->allow_empty
) {
4799 error(_("No valid patches in input (allow with \"--allow-empty\")"));
4805 if (state
->whitespace_error
&& (state
->ws_error_action
== die_on_ws_error
))
4808 state
->update_index
= (state
->check_index
|| state
->ita_only
) && state
->apply
;
4809 if (state
->update_index
&& !is_lock_file_locked(&state
->lock_file
)) {
4810 if (state
->index_file
)
4811 hold_lock_file_for_update(&state
->lock_file
,
4815 repo_hold_locked_index(state
->repo
, &state
->lock_file
,
4819 if (state
->check_index
&& read_apply_cache(state
) < 0) {
4820 error(_("unable to read index file"));
4825 if (state
->check
|| state
->apply
) {
4826 int r
= check_patch_list(state
, list
);
4831 if (r
< 0 && !state
->apply_with_reject
) {
4838 int write_res
= write_out_results(state
, list
);
4839 if (write_res
< 0) {
4843 if (write_res
> 0) {
4844 /* with --3way, we still need to write the index out */
4845 res
= state
->apply_with_reject
? -1 : 1;
4850 if (state
->fake_ancestor
&&
4851 build_fake_ancestor(state
, list
)) {
4856 if (state
->diffstat
&& state
->apply_verbosity
> verbosity_silent
)
4857 stat_patch_list(state
, list
);
4859 if (state
->numstat
&& state
->apply_verbosity
> verbosity_silent
)
4860 numstat_patch_list(state
, list
);
4862 if (state
->summary
&& state
->apply_verbosity
> verbosity_silent
)
4863 summary_patch_list(list
);
4865 if (flush_attributes
)
4866 reset_parsed_attributes();
4868 free_patch_list(list
);
4869 strbuf_release(&buf
);
4870 string_list_clear(&state
->fn_table
, 0);
4874 static int apply_option_parse_exclude(const struct option
*opt
,
4875 const char *arg
, int unset
)
4877 struct apply_state
*state
= opt
->value
;
4879 BUG_ON_OPT_NEG(unset
);
4881 add_name_limit(state
, arg
, 1);
4885 static int apply_option_parse_include(const struct option
*opt
,
4886 const char *arg
, int unset
)
4888 struct apply_state
*state
= opt
->value
;
4890 BUG_ON_OPT_NEG(unset
);
4892 add_name_limit(state
, arg
, 0);
4893 state
->has_include
= 1;
4897 static int apply_option_parse_p(const struct option
*opt
,
4901 struct apply_state
*state
= opt
->value
;
4903 BUG_ON_OPT_NEG(unset
);
4905 state
->p_value
= atoi(arg
);
4906 state
->p_value_known
= 1;
4910 static int apply_option_parse_space_change(const struct option
*opt
,
4911 const char *arg
, int unset
)
4913 struct apply_state
*state
= opt
->value
;
4915 BUG_ON_OPT_ARG(arg
);
4918 state
->ws_ignore_action
= ignore_ws_none
;
4920 state
->ws_ignore_action
= ignore_ws_change
;
4924 static int apply_option_parse_whitespace(const struct option
*opt
,
4925 const char *arg
, int unset
)
4927 struct apply_state
*state
= opt
->value
;
4929 BUG_ON_OPT_NEG(unset
);
4931 state
->whitespace_option
= arg
;
4932 if (parse_whitespace_option(state
, arg
))
4937 static int apply_option_parse_directory(const struct option
*opt
,
4938 const char *arg
, int unset
)
4940 struct apply_state
*state
= opt
->value
;
4942 BUG_ON_OPT_NEG(unset
);
4944 strbuf_reset(&state
->root
);
4945 strbuf_addstr(&state
->root
, arg
);
4946 strbuf_complete(&state
->root
, '/');
4950 int apply_all_patches(struct apply_state
*state
,
4960 for (i
= 0; i
< argc
; i
++) {
4961 const char *arg
= argv
[i
];
4962 char *to_free
= NULL
;
4965 if (!strcmp(arg
, "-")) {
4966 res
= apply_patch(state
, 0, "<stdin>", options
);
4973 arg
= to_free
= prefix_filename(state
->prefix
, arg
);
4975 fd
= open(arg
, O_RDONLY
);
4977 error(_("can't open patch '%s': %s"), arg
, strerror(errno
));
4983 set_default_whitespace_mode(state
);
4984 res
= apply_patch(state
, fd
, arg
, options
);
4991 set_default_whitespace_mode(state
);
4993 res
= apply_patch(state
, 0, "<stdin>", options
);
4999 if (state
->whitespace_error
) {
5000 if (state
->squelch_whitespace_errors
&&
5001 state
->squelch_whitespace_errors
< state
->whitespace_error
) {
5003 state
->whitespace_error
- state
->squelch_whitespace_errors
;
5004 warning(Q_("squelched %d whitespace error",
5005 "squelched %d whitespace errors",
5009 if (state
->ws_error_action
== die_on_ws_error
) {
5010 error(Q_("%d line adds whitespace errors.",
5011 "%d lines add whitespace errors.",
5012 state
->whitespace_error
),
5013 state
->whitespace_error
);
5017 if (state
->applied_after_fixing_ws
&& state
->apply
)
5018 warning(Q_("%d line applied after"
5019 " fixing whitespace errors.",
5020 "%d lines applied after"
5021 " fixing whitespace errors.",
5022 state
->applied_after_fixing_ws
),
5023 state
->applied_after_fixing_ws
);
5024 else if (state
->whitespace_error
)
5025 warning(Q_("%d line adds whitespace errors.",
5026 "%d lines add whitespace errors.",
5027 state
->whitespace_error
),
5028 state
->whitespace_error
);
5031 if (state
->update_index
) {
5032 res
= write_locked_index(state
->repo
->index
, &state
->lock_file
, COMMIT_LOCK
);
5034 error(_("Unable to write new index file"));
5043 rollback_lock_file(&state
->lock_file
);
5045 if (state
->apply_verbosity
<= verbosity_silent
) {
5046 set_error_routine(state
->saved_error_routine
);
5047 set_warn_routine(state
->saved_warn_routine
);
5052 return (res
== -1 ? 1 : 128);
5055 int apply_parse_options(int argc
, const char **argv
,
5056 struct apply_state
*state
,
5057 int *force_apply
, int *options
,
5058 const char * const *apply_usage
)
5060 struct option builtin_apply_options
[] = {
5061 OPT_CALLBACK_F(0, "exclude", state
, N_("path"),
5062 N_("don't apply changes matching the given path"),
5063 PARSE_OPT_NONEG
, apply_option_parse_exclude
),
5064 OPT_CALLBACK_F(0, "include", state
, N_("path"),
5065 N_("apply changes matching the given path"),
5066 PARSE_OPT_NONEG
, apply_option_parse_include
),
5067 OPT_CALLBACK('p', NULL
, state
, N_("num"),
5068 N_("remove <num> leading slashes from traditional diff paths"),
5069 apply_option_parse_p
),
5070 OPT_BOOL(0, "no-add", &state
->no_add
,
5071 N_("ignore additions made by the patch")),
5072 OPT_BOOL(0, "stat", &state
->diffstat
,
5073 N_("instead of applying the patch, output diffstat for the input")),
5074 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
5075 OPT_NOOP_NOARG(0, "binary"),
5076 OPT_BOOL(0, "numstat", &state
->numstat
,
5077 N_("show number of added and deleted lines in decimal notation")),
5078 OPT_BOOL(0, "summary", &state
->summary
,
5079 N_("instead of applying the patch, output a summary for the input")),
5080 OPT_BOOL(0, "check", &state
->check
,
5081 N_("instead of applying the patch, see if the patch is applicable")),
5082 OPT_BOOL(0, "index", &state
->check_index
,
5083 N_("make sure the patch is applicable to the current index")),
5084 OPT_BOOL('N', "intent-to-add", &state
->ita_only
,
5085 N_("mark new files with `git add --intent-to-add`")),
5086 OPT_BOOL(0, "cached", &state
->cached
,
5087 N_("apply a patch without touching the working tree")),
5088 OPT_BOOL_F(0, "unsafe-paths", &state
->unsafe_paths
,
5089 N_("accept a patch that touches outside the working area"),
5090 PARSE_OPT_NOCOMPLETE
),
5091 OPT_BOOL(0, "apply", force_apply
,
5092 N_("also apply the patch (use with --stat/--summary/--check)")),
5093 OPT_BOOL('3', "3way", &state
->threeway
,
5094 N_( "attempt three-way merge, fall back on normal patch if that fails")),
5095 OPT_FILENAME(0, "build-fake-ancestor", &state
->fake_ancestor
,
5096 N_("build a temporary index based on embedded index information")),
5097 /* Think twice before adding "--nul" synonym to this */
5098 OPT_SET_INT('z', NULL
, &state
->line_termination
,
5099 N_("paths are separated with NUL character"), '\0'),
5100 OPT_INTEGER('C', NULL
, &state
->p_context
,
5101 N_("ensure at least <n> lines of context match")),
5102 OPT_CALLBACK(0, "whitespace", state
, N_("action"),
5103 N_("detect new or modified lines that have whitespace errors"),
5104 apply_option_parse_whitespace
),
5105 OPT_CALLBACK_F(0, "ignore-space-change", state
, NULL
,
5106 N_("ignore changes in whitespace when finding context"),
5107 PARSE_OPT_NOARG
, apply_option_parse_space_change
),
5108 OPT_CALLBACK_F(0, "ignore-whitespace", state
, NULL
,
5109 N_("ignore changes in whitespace when finding context"),
5110 PARSE_OPT_NOARG
, apply_option_parse_space_change
),
5111 OPT_BOOL('R', "reverse", &state
->apply_in_reverse
,
5112 N_("apply the patch in reverse")),
5113 OPT_BOOL(0, "unidiff-zero", &state
->unidiff_zero
,
5114 N_("don't expect at least one line of context")),
5115 OPT_BOOL(0, "reject", &state
->apply_with_reject
,
5116 N_("leave the rejected hunks in corresponding *.rej files")),
5117 OPT_BOOL(0, "allow-overlap", &state
->allow_overlap
,
5118 N_("allow overlapping hunks")),
5119 OPT__VERBOSITY(&state
->apply_verbosity
),
5120 OPT_BIT(0, "inaccurate-eof", options
,
5121 N_("tolerate incorrectly detected missing new-line at the end of file"),
5122 APPLY_OPT_INACCURATE_EOF
),
5123 OPT_BIT(0, "recount", options
,
5124 N_("do not trust the line counts in the hunk headers"),
5126 OPT_CALLBACK(0, "directory", state
, N_("root"),
5127 N_("prepend <root> to all filenames"),
5128 apply_option_parse_directory
),
5129 OPT_BOOL(0, "allow-empty", &state
->allow_empty
,
5130 N_("don't return error for empty patches")),
5134 return parse_options(argc
, argv
, state
->prefix
, builtin_apply_options
, apply_usage
, 0);