4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
14 #include "object-store.h"
21 #include "xdiff-interface.h"
24 #include "parse-options.h"
37 static void git_apply_config(void)
39 git_config_get_string("apply.whitespace", &apply_default_whitespace
);
40 git_config_get_string("apply.ignorewhitespace", &apply_default_ignorewhitespace
);
41 git_config(git_xmerge_config
, NULL
);
44 static int parse_whitespace_option(struct apply_state
*state
, const char *option
)
47 state
->ws_error_action
= warn_on_ws_error
;
50 if (!strcmp(option
, "warn")) {
51 state
->ws_error_action
= warn_on_ws_error
;
54 if (!strcmp(option
, "nowarn")) {
55 state
->ws_error_action
= nowarn_ws_error
;
58 if (!strcmp(option
, "error")) {
59 state
->ws_error_action
= die_on_ws_error
;
62 if (!strcmp(option
, "error-all")) {
63 state
->ws_error_action
= die_on_ws_error
;
64 state
->squelch_whitespace_errors
= 0;
67 if (!strcmp(option
, "strip") || !strcmp(option
, "fix")) {
68 state
->ws_error_action
= correct_ws_error
;
72 * Please update $__git_whitespacelist in git-completion.bash
73 * when you add new options.
75 return error(_("unrecognized whitespace option '%s'"), option
);
78 static int parse_ignorewhitespace_option(struct apply_state
*state
,
81 if (!option
|| !strcmp(option
, "no") ||
82 !strcmp(option
, "false") || !strcmp(option
, "never") ||
83 !strcmp(option
, "none")) {
84 state
->ws_ignore_action
= ignore_ws_none
;
87 if (!strcmp(option
, "change")) {
88 state
->ws_ignore_action
= ignore_ws_change
;
91 return error(_("unrecognized whitespace ignore option '%s'"), option
);
94 int init_apply_state(struct apply_state
*state
,
95 struct repository
*repo
,
98 memset(state
, 0, sizeof(*state
));
99 state
->prefix
= prefix
;
102 state
->line_termination
= '\n';
104 state
->p_context
= UINT_MAX
;
105 state
->squelch_whitespace_errors
= 5;
106 state
->ws_error_action
= warn_on_ws_error
;
107 state
->ws_ignore_action
= ignore_ws_none
;
109 string_list_init_nodup(&state
->fn_table
);
110 string_list_init_nodup(&state
->limit_by_name
);
111 strset_init(&state
->removed_symlinks
);
112 strset_init(&state
->kept_symlinks
);
113 strbuf_init(&state
->root
, 0);
116 if (apply_default_whitespace
&& parse_whitespace_option(state
, apply_default_whitespace
))
118 if (apply_default_ignorewhitespace
&& parse_ignorewhitespace_option(state
, apply_default_ignorewhitespace
))
123 void clear_apply_state(struct apply_state
*state
)
125 string_list_clear(&state
->limit_by_name
, 0);
126 strset_clear(&state
->removed_symlinks
);
127 strset_clear(&state
->kept_symlinks
);
128 strbuf_release(&state
->root
);
130 /* &state->fn_table is cleared at the end of apply_patch() */
133 static void mute_routine(const char *msg UNUSED
, va_list params UNUSED
)
138 int check_apply_state(struct apply_state
*state
, int force_apply
)
140 int is_not_gitdir
= !startup_info
->have_repository
;
142 if (state
->apply_with_reject
&& state
->threeway
)
143 return error(_("options '%s' and '%s' cannot be used together"), "--reject", "--3way");
144 if (state
->threeway
) {
146 return error(_("'%s' outside a repository"), "--3way");
147 state
->check_index
= 1;
149 if (state
->apply_with_reject
) {
151 if (state
->apply_verbosity
== verbosity_normal
)
152 state
->apply_verbosity
= verbosity_verbose
;
154 if (!force_apply
&& (state
->diffstat
|| state
->numstat
|| state
->summary
|| state
->check
|| state
->fake_ancestor
))
156 if (state
->check_index
&& is_not_gitdir
)
157 return error(_("'%s' outside a repository"), "--index");
160 return error(_("'%s' outside a repository"), "--cached");
161 state
->check_index
= 1;
163 if (state
->ita_only
&& (state
->check_index
|| is_not_gitdir
))
165 if (state
->check_index
)
166 state
->unsafe_paths
= 0;
168 if (state
->apply_verbosity
<= verbosity_silent
) {
169 state
->saved_error_routine
= get_error_routine();
170 state
->saved_warn_routine
= get_warn_routine();
171 set_error_routine(mute_routine
);
172 set_warn_routine(mute_routine
);
178 static void set_default_whitespace_mode(struct apply_state
*state
)
180 if (!state
->whitespace_option
&& !apply_default_whitespace
)
181 state
->ws_error_action
= (state
->apply
? warn_on_ws_error
: nowarn_ws_error
);
185 * This represents one "hunk" from a patch, starting with
186 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
187 * patch text is pointed at by patch, and its byte length
188 * is stored in size. leading and trailing are the number
192 unsigned long leading
, trailing
;
193 unsigned long oldpos
, oldlines
;
194 unsigned long newpos
, newlines
;
196 * 'patch' is usually borrowed from buf in apply_patch(),
197 * but some codepaths store an allocated buffer.
200 unsigned free_patch
:1,
204 struct fragment
*next
;
208 * When dealing with a binary patch, we reuse "leading" field
209 * to store the type of the binary hunk, either deflated "delta"
210 * or deflated "literal".
212 #define binary_patch_method leading
213 #define BINARY_DELTA_DEFLATED 1
214 #define BINARY_LITERAL_DEFLATED 2
216 static void free_fragment_list(struct fragment
*list
)
219 struct fragment
*next
= list
->next
;
220 if (list
->free_patch
)
221 free((char *)list
->patch
);
227 void release_patch(struct patch
*patch
)
229 free_fragment_list(patch
->fragments
);
230 free(patch
->def_name
);
231 free(patch
->old_name
);
232 free(patch
->new_name
);
236 static void free_patch(struct patch
*patch
)
238 release_patch(patch
);
242 static void free_patch_list(struct patch
*list
)
245 struct patch
*next
= list
->next
;
252 * A line in a file, len-bytes long (includes the terminating LF,
253 * except for an incomplete line at the end if the file ends with
254 * one), and its contents hashes to 'hash'.
260 #define LINE_COMMON 1
261 #define LINE_PATCHED 2
265 * This represents a "file", which is an array of "lines".
272 struct line
*line_allocated
;
276 static uint32_t hash_line(const char *cp
, size_t len
)
280 for (i
= 0, h
= 0; i
< len
; i
++) {
281 if (!isspace(cp
[i
])) {
282 h
= h
* 3 + (cp
[i
] & 0xff);
289 * Compare lines s1 of length n1 and s2 of length n2, ignoring
290 * whitespace difference. Returns 1 if they match, 0 otherwise
292 static int fuzzy_matchlines(const char *s1
, size_t n1
,
293 const char *s2
, size_t n2
)
295 const char *end1
= s1
+ n1
;
296 const char *end2
= s2
+ n2
;
298 /* ignore line endings */
299 while (s1
< end1
&& (end1
[-1] == '\r' || end1
[-1] == '\n'))
301 while (s2
< end2
&& (end2
[-1] == '\r' || end2
[-1] == '\n'))
304 while (s1
< end1
&& s2
< end2
) {
307 * Skip whitespace. We check on both buffers
308 * because we don't want "a b" to match "ab".
312 while (s1
< end1
&& isspace(*s1
))
314 while (s2
< end2
&& isspace(*s2
))
316 } else if (*s1
++ != *s2
++)
320 /* If we reached the end on one side only, lines don't match. */
321 return s1
== end1
&& s2
== end2
;
324 static void add_line_info(struct image
*img
, const char *bol
, size_t len
, unsigned flag
)
326 ALLOC_GROW(img
->line_allocated
, img
->nr
+ 1, img
->alloc
);
327 img
->line_allocated
[img
->nr
].len
= len
;
328 img
->line_allocated
[img
->nr
].hash
= hash_line(bol
, len
);
329 img
->line_allocated
[img
->nr
].flag
= flag
;
334 * "buf" has the file contents to be patched (read from various sources).
335 * attach it to "image" and add line-based index to it.
336 * "image" now owns the "buf".
338 static void prepare_image(struct image
*image
, char *buf
, size_t len
,
339 int prepare_linetable
)
343 memset(image
, 0, sizeof(*image
));
347 if (!prepare_linetable
)
350 ep
= image
->buf
+ image
->len
;
354 for (next
= cp
; next
< ep
&& *next
!= '\n'; next
++)
358 add_line_info(image
, cp
, next
- cp
, 0);
361 image
->line
= image
->line_allocated
;
364 static void clear_image(struct image
*image
)
367 free(image
->line_allocated
);
368 memset(image
, 0, sizeof(*image
));
371 /* fmt must contain _one_ %s and no other substitution */
372 static void say_patch_name(FILE *output
, const char *fmt
, struct patch
*patch
)
374 struct strbuf sb
= STRBUF_INIT
;
376 if (patch
->old_name
&& patch
->new_name
&&
377 strcmp(patch
->old_name
, patch
->new_name
)) {
378 quote_c_style(patch
->old_name
, &sb
, NULL
, 0);
379 strbuf_addstr(&sb
, " => ");
380 quote_c_style(patch
->new_name
, &sb
, NULL
, 0);
382 const char *n
= patch
->new_name
;
385 quote_c_style(n
, &sb
, NULL
, 0);
387 fprintf(output
, fmt
, sb
.buf
);
395 * apply.c isn't equipped to handle arbitrarily large patches, because
396 * it intermingles `unsigned long` with `int` for the type used to store
399 * Only process patches that are just shy of 1 GiB large in order to
400 * avoid any truncation or overflow issues.
402 #define MAX_APPLY_SIZE (1024UL * 1024 * 1023)
404 static int read_patch_file(struct strbuf
*sb
, int fd
)
406 if (strbuf_read(sb
, fd
, 0) < 0 || sb
->len
>= MAX_APPLY_SIZE
)
407 return error_errno("git apply: failed to read");
410 * Make sure that we have some slop in the buffer
411 * so that we can do speculative "memcmp" etc, and
412 * see to it that it is NUL-filled.
414 strbuf_grow(sb
, SLOP
);
415 memset(sb
->buf
+ sb
->len
, 0, SLOP
);
419 static unsigned long linelen(const char *buffer
, unsigned long size
)
421 unsigned long len
= 0;
424 if (*buffer
++ == '\n')
430 static int is_dev_null(const char *str
)
432 return skip_prefix(str
, "/dev/null", &str
) && isspace(*str
);
438 static int name_terminate(int c
, int terminate
)
440 if (c
== ' ' && !(terminate
& TERM_SPACE
))
442 if (c
== '\t' && !(terminate
& TERM_TAB
))
448 /* remove double slashes to make --index work with such filenames */
449 static char *squash_slash(char *name
)
457 if ((name
[j
++] = name
[i
++]) == '/')
458 while (name
[i
] == '/')
465 static char *find_name_gnu(struct strbuf
*root
,
469 struct strbuf name
= STRBUF_INIT
;
473 * Proposed "new-style" GNU patch/diff format; see
474 * https://lore.kernel.org/git/7vll0wvb2a.fsf@assigned-by-dhcp.cox.net/
476 if (unquote_c_style(&name
, line
, NULL
)) {
477 strbuf_release(&name
);
481 for (cp
= name
.buf
; p_value
; p_value
--) {
482 cp
= strchr(cp
, '/');
484 strbuf_release(&name
);
490 strbuf_remove(&name
, 0, cp
- name
.buf
);
492 strbuf_insert(&name
, 0, root
->buf
, root
->len
);
493 return squash_slash(strbuf_detach(&name
, NULL
));
496 static size_t sane_tz_len(const char *line
, size_t len
)
500 if (len
< strlen(" +0500") || line
[len
-strlen(" +0500")] != ' ')
502 tz
= line
+ len
- strlen(" +0500");
504 if (tz
[1] != '+' && tz
[1] != '-')
507 for (p
= tz
+ 2; p
!= line
+ len
; p
++)
511 return line
+ len
- tz
;
514 static size_t tz_with_colon_len(const char *line
, size_t len
)
518 if (len
< strlen(" +08:00") || line
[len
- strlen(":00")] != ':')
520 tz
= line
+ len
- strlen(" +08:00");
522 if (tz
[0] != ' ' || (tz
[1] != '+' && tz
[1] != '-'))
525 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
526 !isdigit(*p
++) || !isdigit(*p
++))
529 return line
+ len
- tz
;
532 static size_t date_len(const char *line
, size_t len
)
534 const char *date
, *p
;
536 if (len
< strlen("72-02-05") || line
[len
-strlen("-05")] != '-')
538 p
= date
= line
+ len
- strlen("72-02-05");
540 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
541 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
542 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a date. */
545 if (date
- line
>= strlen("19") &&
546 isdigit(date
[-1]) && isdigit(date
[-2])) /* 4-digit year */
547 date
-= strlen("19");
549 return line
+ len
- date
;
552 static size_t short_time_len(const char *line
, size_t len
)
554 const char *time
, *p
;
556 if (len
< strlen(" 07:01:32") || line
[len
-strlen(":32")] != ':')
558 p
= time
= line
+ len
- strlen(" 07:01:32");
560 /* Permit 1-digit hours? */
562 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
563 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
564 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a time. */
567 return line
+ len
- time
;
570 static size_t fractional_time_len(const char *line
, size_t len
)
575 /* Expected format: 19:41:17.620000023 */
576 if (!len
|| !isdigit(line
[len
- 1]))
580 /* Fractional seconds. */
581 while (p
> line
&& isdigit(*p
))
586 /* Hours, minutes, and whole seconds. */
587 n
= short_time_len(line
, p
- line
);
591 return line
+ len
- p
+ n
;
594 static size_t trailing_spaces_len(const char *line
, size_t len
)
598 /* Expected format: ' ' x (1 or more) */
599 if (!len
|| line
[len
- 1] != ' ')
606 return line
+ len
- (p
+ 1);
613 static size_t diff_timestamp_len(const char *line
, size_t len
)
615 const char *end
= line
+ len
;
619 * Posix: 2010-07-05 19:41:17
620 * GNU: 2010-07-05 19:41:17.620000023 -0500
623 if (!isdigit(end
[-1]))
626 n
= sane_tz_len(line
, end
- line
);
628 n
= tz_with_colon_len(line
, end
- line
);
631 n
= short_time_len(line
, end
- line
);
633 n
= fractional_time_len(line
, end
- line
);
636 n
= date_len(line
, end
- line
);
637 if (!n
) /* No date. Too bad. */
641 if (end
== line
) /* No space before date. */
643 if (end
[-1] == '\t') { /* Success! */
645 return line
+ len
- end
;
647 if (end
[-1] != ' ') /* No space before date. */
650 /* Whitespace damage. */
651 end
-= trailing_spaces_len(line
, end
- line
);
652 return line
+ len
- end
;
655 static char *find_name_common(struct strbuf
*root
,
663 const char *start
= NULL
;
667 while (line
!= end
) {
670 if (!end
&& isspace(c
)) {
673 if (name_terminate(c
, terminate
))
677 if (c
== '/' && !--p_value
)
681 return squash_slash(xstrdup_or_null(def
));
684 return squash_slash(xstrdup_or_null(def
));
687 * Generally we prefer the shorter name, especially
688 * if the other one is just a variation of that with
689 * something else tacked on to the end (ie "file.orig"
693 int deflen
= strlen(def
);
694 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
695 return squash_slash(xstrdup(def
));
699 char *ret
= xstrfmt("%s%.*s", root
->buf
, len
, start
);
700 return squash_slash(ret
);
703 return squash_slash(xmemdupz(start
, len
));
706 static char *find_name(struct strbuf
*root
,
713 char *name
= find_name_gnu(root
, line
, p_value
);
718 return find_name_common(root
, line
, def
, p_value
, NULL
, terminate
);
721 static char *find_name_traditional(struct strbuf
*root
,
730 char *name
= find_name_gnu(root
, line
, p_value
);
735 len
= strchrnul(line
, '\n') - line
;
736 date_len
= diff_timestamp_len(line
, len
);
738 return find_name_common(root
, line
, def
, p_value
, NULL
, TERM_TAB
);
741 return find_name_common(root
, line
, def
, p_value
, line
+ len
, 0);
745 * Given the string after "--- " or "+++ ", guess the appropriate
746 * p_value for the given patch.
748 static int guess_p_value(struct apply_state
*state
, const char *nameline
)
753 if (is_dev_null(nameline
))
755 name
= find_name_traditional(&state
->root
, nameline
, NULL
, 0);
758 cp
= strchr(name
, '/');
761 else if (state
->prefix
) {
763 * Does it begin with "a/$our-prefix" and such? Then this is
764 * very likely to apply to our directory.
766 if (starts_with(name
, state
->prefix
))
767 val
= count_slashes(state
->prefix
);
770 if (starts_with(cp
, state
->prefix
))
771 val
= count_slashes(state
->prefix
) + 1;
779 * Does the ---/+++ line have the POSIX timestamp after the last HT?
780 * GNU diff puts epoch there to signal a creation/deletion event. Is
781 * this such a timestamp?
783 static int has_epoch_timestamp(const char *nameline
)
786 * We are only interested in epoch timestamp; any non-zero
787 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
788 * For the same reason, the date must be either 1969-12-31 or
789 * 1970-01-01, and the seconds part must be "00".
791 const char stamp_regexp
[] =
792 "^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?"
794 "([-+][0-2][0-9]:?[0-5][0-9])\n";
795 const char *timestamp
= NULL
, *cp
, *colon
;
796 static regex_t
*stamp
;
798 int zoneoffset
, epoch_hour
, hour
, minute
;
801 for (cp
= nameline
; *cp
!= '\n'; cp
++) {
809 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
810 * (west of GMT) or 1970-01-01 (east of GMT)
812 if (skip_prefix(timestamp
, "1969-12-31 ", ×tamp
))
814 else if (skip_prefix(timestamp
, "1970-01-01 ", ×tamp
))
820 stamp
= xmalloc(sizeof(*stamp
));
821 if (regcomp(stamp
, stamp_regexp
, REG_EXTENDED
)) {
822 warning(_("Cannot prepare timestamp regexp %s"),
828 status
= regexec(stamp
, timestamp
, ARRAY_SIZE(m
), m
, 0);
830 if (status
!= REG_NOMATCH
)
831 warning(_("regexec returned %d for input: %s"),
836 hour
= strtol(timestamp
, NULL
, 10);
837 minute
= strtol(timestamp
+ m
[1].rm_so
, NULL
, 10);
839 zoneoffset
= strtol(timestamp
+ m
[3].rm_so
+ 1, (char **) &colon
, 10);
841 zoneoffset
= zoneoffset
* 60 + strtol(colon
+ 1, NULL
, 10);
843 zoneoffset
= (zoneoffset
/ 100) * 60 + (zoneoffset
% 100);
844 if (timestamp
[m
[3].rm_so
] == '-')
845 zoneoffset
= -zoneoffset
;
847 return hour
* 60 + minute
- zoneoffset
== epoch_hour
* 60;
851 * Get the name etc info from the ---/+++ lines of a traditional patch header
853 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
854 * files, we can happily check the index for a match, but for creating a
855 * new file we should try to match whatever "patch" does. I have no idea.
857 static int parse_traditional_patch(struct apply_state
*state
,
864 first
+= 4; /* skip "--- " */
865 second
+= 4; /* skip "+++ " */
866 if (!state
->p_value_known
) {
868 p
= guess_p_value(state
, first
);
869 q
= guess_p_value(state
, second
);
871 if (0 <= p
&& p
== q
) {
873 state
->p_value_known
= 1;
876 if (is_dev_null(first
)) {
878 patch
->is_delete
= 0;
879 name
= find_name_traditional(&state
->root
, second
, NULL
, state
->p_value
);
880 patch
->new_name
= name
;
881 } else if (is_dev_null(second
)) {
883 patch
->is_delete
= 1;
884 name
= find_name_traditional(&state
->root
, first
, NULL
, state
->p_value
);
885 patch
->old_name
= name
;
888 first_name
= find_name_traditional(&state
->root
, first
, NULL
, state
->p_value
);
889 name
= find_name_traditional(&state
->root
, second
, first_name
, state
->p_value
);
891 if (has_epoch_timestamp(first
)) {
893 patch
->is_delete
= 0;
894 patch
->new_name
= name
;
895 } else if (has_epoch_timestamp(second
)) {
897 patch
->is_delete
= 1;
898 patch
->old_name
= name
;
900 patch
->old_name
= name
;
901 patch
->new_name
= xstrdup_or_null(name
);
905 return error(_("unable to find filename in patch at line %d"), state
->linenr
);
910 static int gitdiff_hdrend(struct gitdiff_data
*state UNUSED
,
911 const char *line UNUSED
,
912 struct patch
*patch UNUSED
)
918 * We're anal about diff header consistency, to make
919 * sure that we don't end up having strange ambiguous
920 * patches floating around.
922 * As a result, gitdiff_{old|new}name() will check
923 * their names against any previous information, just
926 #define DIFF_OLD_NAME 0
927 #define DIFF_NEW_NAME 1
929 static int gitdiff_verify_name(struct gitdiff_data
*state
,
935 if (!*name
&& !isnull
) {
936 *name
= find_name(state
->root
, line
, NULL
, state
->p_value
, TERM_TAB
);
943 return error(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
944 *name
, state
->linenr
);
945 another
= find_name(state
->root
, line
, NULL
, state
->p_value
, TERM_TAB
);
946 if (!another
|| strcmp(another
, *name
)) {
948 return error((side
== DIFF_NEW_NAME
) ?
949 _("git apply: bad git-diff - inconsistent new filename on line %d") :
950 _("git apply: bad git-diff - inconsistent old filename on line %d"), state
->linenr
);
954 if (!is_dev_null(line
))
955 return error(_("git apply: bad git-diff - expected /dev/null on line %d"), state
->linenr
);
961 static int gitdiff_oldname(struct gitdiff_data
*state
,
965 return gitdiff_verify_name(state
, line
,
966 patch
->is_new
, &patch
->old_name
,
970 static int gitdiff_newname(struct gitdiff_data
*state
,
974 return gitdiff_verify_name(state
, line
,
975 patch
->is_delete
, &patch
->new_name
,
979 static int parse_mode_line(const char *line
, int linenr
, unsigned int *mode
)
982 *mode
= strtoul(line
, &end
, 8);
983 if (end
== line
|| !isspace(*end
))
984 return error(_("invalid mode on line %d: %s"), linenr
, line
);
988 static int gitdiff_oldmode(struct gitdiff_data
*state
,
992 return parse_mode_line(line
, state
->linenr
, &patch
->old_mode
);
995 static int gitdiff_newmode(struct gitdiff_data
*state
,
999 return parse_mode_line(line
, state
->linenr
, &patch
->new_mode
);
1002 static int gitdiff_delete(struct gitdiff_data
*state
,
1004 struct patch
*patch
)
1006 patch
->is_delete
= 1;
1007 free(patch
->old_name
);
1008 patch
->old_name
= xstrdup_or_null(patch
->def_name
);
1009 return gitdiff_oldmode(state
, line
, patch
);
1012 static int gitdiff_newfile(struct gitdiff_data
*state
,
1014 struct patch
*patch
)
1017 free(patch
->new_name
);
1018 patch
->new_name
= xstrdup_or_null(patch
->def_name
);
1019 return gitdiff_newmode(state
, line
, patch
);
1022 static int gitdiff_copysrc(struct gitdiff_data
*state
,
1024 struct patch
*patch
)
1027 free(patch
->old_name
);
1028 patch
->old_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1032 static int gitdiff_copydst(struct gitdiff_data
*state
,
1034 struct patch
*patch
)
1037 free(patch
->new_name
);
1038 patch
->new_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1042 static int gitdiff_renamesrc(struct gitdiff_data
*state
,
1044 struct patch
*patch
)
1046 patch
->is_rename
= 1;
1047 free(patch
->old_name
);
1048 patch
->old_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1052 static int gitdiff_renamedst(struct gitdiff_data
*state
,
1054 struct patch
*patch
)
1056 patch
->is_rename
= 1;
1057 free(patch
->new_name
);
1058 patch
->new_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1062 static int gitdiff_similarity(struct gitdiff_data
*state UNUSED
,
1064 struct patch
*patch
)
1066 unsigned long val
= strtoul(line
, NULL
, 10);
1072 static int gitdiff_dissimilarity(struct gitdiff_data
*state UNUSED
,
1074 struct patch
*patch
)
1076 unsigned long val
= strtoul(line
, NULL
, 10);
1082 static int gitdiff_index(struct gitdiff_data
*state
,
1084 struct patch
*patch
)
1087 * index line is N hexadecimal, "..", N hexadecimal,
1088 * and optional space with octal mode.
1090 const char *ptr
, *eol
;
1092 const unsigned hexsz
= the_hash_algo
->hexsz
;
1094 ptr
= strchr(line
, '.');
1095 if (!ptr
|| ptr
[1] != '.' || hexsz
< ptr
- line
)
1098 memcpy(patch
->old_oid_prefix
, line
, len
);
1099 patch
->old_oid_prefix
[len
] = 0;
1102 ptr
= strchr(line
, ' ');
1103 eol
= strchrnul(line
, '\n');
1105 if (!ptr
|| eol
< ptr
)
1111 memcpy(patch
->new_oid_prefix
, line
, len
);
1112 patch
->new_oid_prefix
[len
] = 0;
1114 return gitdiff_oldmode(state
, ptr
+ 1, patch
);
1119 * This is normal for a diff that doesn't change anything: we'll fall through
1120 * into the next diff. Tell the parser to break out.
1122 static int gitdiff_unrecognized(struct gitdiff_data
*state UNUSED
,
1123 const char *line UNUSED
,
1124 struct patch
*patch UNUSED
)
1130 * Skip p_value leading components from "line"; as we do not accept
1131 * absolute paths, return NULL in that case.
1133 static const char *skip_tree_prefix(int p_value
,
1141 return (llen
&& line
[0] == '/') ? NULL
: line
;
1144 for (i
= 0; i
< llen
; i
++) {
1146 if (ch
== '/' && --nslash
<= 0)
1147 return (i
== 0) ? NULL
: &line
[i
+ 1];
1153 * This is to extract the same name that appears on "diff --git"
1154 * line. We do not find and return anything if it is a rename
1155 * patch, and it is OK because we will find the name elsewhere.
1156 * We need to reliably find name only when it is mode-change only,
1157 * creation or deletion of an empty file. In any of these cases,
1158 * both sides are the same name under a/ and b/ respectively.
1160 static char *git_header_name(int p_value
,
1165 const char *second
= NULL
;
1166 size_t len
, line_len
;
1168 line
+= strlen("diff --git ");
1169 llen
-= strlen("diff --git ");
1173 struct strbuf first
= STRBUF_INIT
;
1174 struct strbuf sp
= STRBUF_INIT
;
1176 if (unquote_c_style(&first
, line
, &second
))
1177 goto free_and_fail1
;
1179 /* strip the a/b prefix including trailing slash */
1180 cp
= skip_tree_prefix(p_value
, first
.buf
, first
.len
);
1182 goto free_and_fail1
;
1183 strbuf_remove(&first
, 0, cp
- first
.buf
);
1186 * second points at one past closing dq of name.
1187 * find the second name.
1189 while ((second
< line
+ llen
) && isspace(*second
))
1192 if (line
+ llen
<= second
)
1193 goto free_and_fail1
;
1194 if (*second
== '"') {
1195 if (unquote_c_style(&sp
, second
, NULL
))
1196 goto free_and_fail1
;
1197 cp
= skip_tree_prefix(p_value
, sp
.buf
, sp
.len
);
1199 goto free_and_fail1
;
1200 /* They must match, otherwise ignore */
1201 if (strcmp(cp
, first
.buf
))
1202 goto free_and_fail1
;
1203 strbuf_release(&sp
);
1204 return strbuf_detach(&first
, NULL
);
1207 /* unquoted second */
1208 cp
= skip_tree_prefix(p_value
, second
, line
+ llen
- second
);
1210 goto free_and_fail1
;
1211 if (line
+ llen
- cp
!= first
.len
||
1212 memcmp(first
.buf
, cp
, first
.len
))
1213 goto free_and_fail1
;
1214 return strbuf_detach(&first
, NULL
);
1217 strbuf_release(&first
);
1218 strbuf_release(&sp
);
1222 /* unquoted first name */
1223 name
= skip_tree_prefix(p_value
, line
, llen
);
1228 * since the first name is unquoted, a dq if exists must be
1229 * the beginning of the second name.
1231 for (second
= name
; second
< line
+ llen
; second
++) {
1232 if (*second
== '"') {
1233 struct strbuf sp
= STRBUF_INIT
;
1236 if (unquote_c_style(&sp
, second
, NULL
))
1237 goto free_and_fail2
;
1239 np
= skip_tree_prefix(p_value
, sp
.buf
, sp
.len
);
1241 goto free_and_fail2
;
1243 len
= sp
.buf
+ sp
.len
- np
;
1244 if (len
< second
- name
&&
1245 !strncmp(np
, name
, len
) &&
1246 isspace(name
[len
])) {
1248 strbuf_remove(&sp
, 0, np
- sp
.buf
);
1249 return strbuf_detach(&sp
, NULL
);
1253 strbuf_release(&sp
);
1259 * Accept a name only if it shows up twice, exactly the same
1262 second
= strchr(name
, '\n');
1265 line_len
= second
- name
;
1266 for (len
= 0 ; ; len
++) {
1267 switch (name
[len
]) {
1272 case '\t': case ' ':
1274 * Is this the separator between the preimage
1275 * and the postimage pathname? Again, we are
1276 * only interested in the case where there is
1277 * no rename, as this is only to set def_name
1278 * and a rename patch has the names elsewhere
1279 * in an unambiguous form.
1282 return NULL
; /* no postimage name */
1283 second
= skip_tree_prefix(p_value
, name
+ len
+ 1,
1284 line_len
- (len
+ 1));
1288 * Does len bytes starting at "name" and "second"
1289 * (that are separated by one HT or SP we just
1290 * found) exactly match?
1292 if (second
[len
] == '\n' && !strncmp(name
, second
, len
))
1293 return xmemdupz(name
, len
);
1298 static int check_header_line(int linenr
, struct patch
*patch
)
1300 int extensions
= (patch
->is_delete
== 1) + (patch
->is_new
== 1) +
1301 (patch
->is_rename
== 1) + (patch
->is_copy
== 1);
1303 return error(_("inconsistent header lines %d and %d"),
1304 patch
->extension_linenr
, linenr
);
1305 if (extensions
&& !patch
->extension_linenr
)
1306 patch
->extension_linenr
= linenr
;
1310 int parse_git_diff_header(struct strbuf
*root
,
1316 struct patch
*patch
)
1318 unsigned long offset
;
1319 struct gitdiff_data parse_hdr_state
;
1321 /* A git diff has explicit new/delete information, so we don't guess */
1323 patch
->is_delete
= 0;
1326 * Some things may not have the old name in the
1327 * rest of the headers anywhere (pure mode changes,
1328 * or removing or adding empty files), so we get
1329 * the default name from the header.
1331 patch
->def_name
= git_header_name(p_value
, line
, len
);
1332 if (patch
->def_name
&& root
->len
) {
1333 char *s
= xstrfmt("%s%s", root
->buf
, patch
->def_name
);
1334 free(patch
->def_name
);
1335 patch
->def_name
= s
;
1341 parse_hdr_state
.root
= root
;
1342 parse_hdr_state
.linenr
= *linenr
;
1343 parse_hdr_state
.p_value
= p_value
;
1345 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, (*linenr
)++) {
1346 static const struct opentry
{
1348 int (*fn
)(struct gitdiff_data
*, const char *, struct patch
*);
1350 { "@@ -", gitdiff_hdrend
},
1351 { "--- ", gitdiff_oldname
},
1352 { "+++ ", gitdiff_newname
},
1353 { "old mode ", gitdiff_oldmode
},
1354 { "new mode ", gitdiff_newmode
},
1355 { "deleted file mode ", gitdiff_delete
},
1356 { "new file mode ", gitdiff_newfile
},
1357 { "copy from ", gitdiff_copysrc
},
1358 { "copy to ", gitdiff_copydst
},
1359 { "rename old ", gitdiff_renamesrc
},
1360 { "rename new ", gitdiff_renamedst
},
1361 { "rename from ", gitdiff_renamesrc
},
1362 { "rename to ", gitdiff_renamedst
},
1363 { "similarity index ", gitdiff_similarity
},
1364 { "dissimilarity index ", gitdiff_dissimilarity
},
1365 { "index ", gitdiff_index
},
1366 { "", gitdiff_unrecognized
},
1370 len
= linelen(line
, size
);
1371 if (!len
|| line
[len
-1] != '\n')
1373 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
1374 const struct opentry
*p
= optable
+ i
;
1375 int oplen
= strlen(p
->str
);
1377 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
1379 res
= p
->fn(&parse_hdr_state
, line
+ oplen
, patch
);
1382 if (check_header_line(*linenr
, patch
))
1391 if (!patch
->old_name
&& !patch
->new_name
) {
1392 if (!patch
->def_name
) {
1393 error(Q_("git diff header lacks filename information when removing "
1394 "%d leading pathname component (line %d)",
1395 "git diff header lacks filename information when removing "
1396 "%d leading pathname components (line %d)",
1397 parse_hdr_state
.p_value
),
1398 parse_hdr_state
.p_value
, *linenr
);
1401 patch
->old_name
= xstrdup(patch
->def_name
);
1402 patch
->new_name
= xstrdup(patch
->def_name
);
1404 if ((!patch
->new_name
&& !patch
->is_delete
) ||
1405 (!patch
->old_name
&& !patch
->is_new
)) {
1406 error(_("git diff header lacks filename information "
1407 "(line %d)"), *linenr
);
1410 patch
->is_toplevel_relative
= 1;
1414 static int parse_num(const char *line
, unsigned long *p
)
1418 if (!isdigit(*line
))
1420 *p
= strtoul(line
, &ptr
, 10);
1424 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
1425 unsigned long *p1
, unsigned long *p2
)
1429 if (offset
< 0 || offset
>= len
)
1434 digits
= parse_num(line
, p1
);
1444 digits
= parse_num(line
+1, p2
);
1453 ex
= strlen(expect
);
1456 if (memcmp(line
, expect
, ex
))
1462 static void recount_diff(const char *line
, int size
, struct fragment
*fragment
)
1464 int oldlines
= 0, newlines
= 0, ret
= 0;
1467 warning("recount: ignore empty hunk");
1472 int len
= linelen(line
, size
);
1480 case ' ': case '\n':
1492 ret
= size
< 3 || !starts_with(line
, "@@ ");
1495 ret
= size
< 5 || !starts_with(line
, "diff ");
1502 warning(_("recount: unexpected line: %.*s"),
1503 (int)linelen(line
, size
), line
);
1508 fragment
->oldlines
= oldlines
;
1509 fragment
->newlines
= newlines
;
1513 * Parse a unified diff fragment header of the
1514 * form "@@ -a,b +c,d @@"
1516 static int parse_fragment_header(const char *line
, int len
, struct fragment
*fragment
)
1520 if (!len
|| line
[len
-1] != '\n')
1523 /* Figure out the number of lines in a fragment */
1524 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
1525 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
1531 * Find file diff header
1534 * -1 if no header was found
1535 * -128 in case of error
1536 * the size of the header in bytes (called "offset") otherwise
1538 static int find_header(struct apply_state
*state
,
1542 struct patch
*patch
)
1544 unsigned long offset
, len
;
1546 patch
->is_toplevel_relative
= 0;
1547 patch
->is_rename
= patch
->is_copy
= 0;
1548 patch
->is_new
= patch
->is_delete
= -1;
1549 patch
->old_mode
= patch
->new_mode
= 0;
1550 patch
->old_name
= patch
->new_name
= NULL
;
1551 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1552 unsigned long nextlen
;
1554 len
= linelen(line
, size
);
1558 /* Testing this early allows us to take a few shortcuts.. */
1563 * Make sure we don't find any unconnected patch fragments.
1564 * That's a sign that we didn't find a header, and that a
1565 * patch has become corrupted/broken up.
1567 if (!memcmp("@@ -", line
, 4)) {
1568 struct fragment dummy
;
1569 if (parse_fragment_header(line
, len
, &dummy
) < 0)
1571 error(_("patch fragment without header at line %d: %.*s"),
1572 state
->linenr
, (int)len
-1, line
);
1580 * Git patch? It might not have a real patch, just a rename
1581 * or mode change, so we handle that specially
1583 if (!memcmp("diff --git ", line
, 11)) {
1584 int git_hdr_len
= parse_git_diff_header(&state
->root
, &state
->linenr
,
1585 state
->p_value
, line
, len
,
1587 if (git_hdr_len
< 0)
1589 if (git_hdr_len
<= len
)
1591 *hdrsize
= git_hdr_len
;
1595 /* --- followed by +++ ? */
1596 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
1600 * We only accept unified patches, so we want it to
1601 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1602 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1604 nextlen
= linelen(line
+ len
, size
- len
);
1605 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
1608 /* Ok, we'll consider it a patch */
1609 if (parse_traditional_patch(state
, line
, line
+len
, patch
))
1611 *hdrsize
= len
+ nextlen
;
1618 static void record_ws_error(struct apply_state
*state
,
1629 state
->whitespace_error
++;
1630 if (state
->squelch_whitespace_errors
&&
1631 state
->squelch_whitespace_errors
< state
->whitespace_error
)
1634 err
= whitespace_error_string(result
);
1635 if (state
->apply_verbosity
> verbosity_silent
)
1636 fprintf(stderr
, "%s:%d: %s.\n%.*s\n",
1637 state
->patch_input_file
, linenr
, err
, len
, line
);
1641 static void check_whitespace(struct apply_state
*state
,
1646 unsigned result
= ws_check(line
+ 1, len
- 1, ws_rule
);
1648 record_ws_error(state
, result
, line
+ 1, len
- 2, state
->linenr
);
1652 * Check if the patch has context lines with CRLF or
1653 * the patch wants to remove lines with CRLF.
1655 static void check_old_for_crlf(struct patch
*patch
, const char *line
, int len
)
1657 if (len
>= 2 && line
[len
-1] == '\n' && line
[len
-2] == '\r') {
1658 patch
->ws_rule
|= WS_CR_AT_EOL
;
1659 patch
->crlf_in_old
= 1;
1665 * Parse a unified diff. Note that this really needs to parse each
1666 * fragment separately, since the only way to know the difference
1667 * between a "---" that is part of a patch, and a "---" that starts
1668 * the next patch is to look at the line counts..
1670 static int parse_fragment(struct apply_state
*state
,
1673 struct patch
*patch
,
1674 struct fragment
*fragment
)
1677 int len
= linelen(line
, size
), offset
;
1678 unsigned long oldlines
, newlines
;
1679 unsigned long leading
, trailing
;
1681 offset
= parse_fragment_header(line
, len
, fragment
);
1684 if (offset
> 0 && patch
->recount
)
1685 recount_diff(line
+ offset
, size
- offset
, fragment
);
1686 oldlines
= fragment
->oldlines
;
1687 newlines
= fragment
->newlines
;
1691 /* Parse the thing.. */
1695 added
= deleted
= 0;
1698 offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1699 if (!oldlines
&& !newlines
)
1701 len
= linelen(line
, size
);
1702 if (!len
|| line
[len
-1] != '\n')
1707 case '\n': /* newer GNU diff, an empty context line */
1711 if (!deleted
&& !added
)
1714 check_old_for_crlf(patch
, line
, len
);
1715 if (!state
->apply_in_reverse
&&
1716 state
->ws_error_action
== correct_ws_error
)
1717 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1720 if (!state
->apply_in_reverse
)
1721 check_old_for_crlf(patch
, line
, len
);
1722 if (state
->apply_in_reverse
&&
1723 state
->ws_error_action
!= nowarn_ws_error
)
1724 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1730 if (state
->apply_in_reverse
)
1731 check_old_for_crlf(patch
, line
, len
);
1732 if (!state
->apply_in_reverse
&&
1733 state
->ws_error_action
!= nowarn_ws_error
)
1734 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1741 * We allow "\ No newline at end of file". Depending
1742 * on locale settings when the patch was produced we
1743 * don't know what this line looks like. The only
1744 * thing we do know is that it begins with "\ ".
1745 * Checking for 12 is just for sanity check -- any
1746 * l10n of "\ No newline..." is at least that long.
1749 if (len
< 12 || memcmp(line
, "\\ ", 2))
1754 if (oldlines
|| newlines
)
1756 if (!patch
->recount
&& !deleted
&& !added
)
1759 fragment
->leading
= leading
;
1760 fragment
->trailing
= trailing
;
1763 * If a fragment ends with an incomplete line, we failed to include
1764 * it in the above loop because we hit oldlines == newlines == 0
1767 if (12 < size
&& !memcmp(line
, "\\ ", 2))
1768 offset
+= linelen(line
, size
);
1770 patch
->lines_added
+= added
;
1771 patch
->lines_deleted
+= deleted
;
1773 if (0 < patch
->is_new
&& oldlines
)
1774 return error(_("new file depends on old contents"));
1775 if (0 < patch
->is_delete
&& newlines
)
1776 return error(_("deleted file still has contents"));
1781 * We have seen "diff --git a/... b/..." header (or a traditional patch
1782 * header). Read hunks that belong to this patch into fragments and hang
1783 * them to the given patch structure.
1785 * The (fragment->patch, fragment->size) pair points into the memory given
1786 * by the caller, not a copy, when we return.
1789 * -1 in case of error,
1790 * the number of bytes in the patch otherwise.
1792 static int parse_single_patch(struct apply_state
*state
,
1795 struct patch
*patch
)
1797 unsigned long offset
= 0;
1798 unsigned long oldlines
= 0, newlines
= 0, context
= 0;
1799 struct fragment
**fragp
= &patch
->fragments
;
1801 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
1802 struct fragment
*fragment
;
1805 CALLOC_ARRAY(fragment
, 1);
1806 fragment
->linenr
= state
->linenr
;
1807 len
= parse_fragment(state
, line
, size
, patch
, fragment
);
1810 return error(_("corrupt patch at line %d"), state
->linenr
);
1812 fragment
->patch
= line
;
1813 fragment
->size
= len
;
1814 oldlines
+= fragment
->oldlines
;
1815 newlines
+= fragment
->newlines
;
1816 context
+= fragment
->leading
+ fragment
->trailing
;
1819 fragp
= &fragment
->next
;
1827 * If something was removed (i.e. we have old-lines) it cannot
1828 * be creation, and if something was added it cannot be
1829 * deletion. However, the reverse is not true; --unified=0
1830 * patches that only add are not necessarily creation even
1831 * though they do not have any old lines, and ones that only
1832 * delete are not necessarily deletion.
1834 * Unfortunately, a real creation/deletion patch do _not_ have
1835 * any context line by definition, so we cannot safely tell it
1836 * apart with --unified=0 insanity. At least if the patch has
1837 * more than one hunk it is not creation or deletion.
1839 if (patch
->is_new
< 0 &&
1840 (oldlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1842 if (patch
->is_delete
< 0 &&
1843 (newlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1844 patch
->is_delete
= 0;
1846 if (0 < patch
->is_new
&& oldlines
)
1847 return error(_("new file %s depends on old contents"), patch
->new_name
);
1848 if (0 < patch
->is_delete
&& newlines
)
1849 return error(_("deleted file %s still has contents"), patch
->old_name
);
1850 if (!patch
->is_delete
&& !newlines
&& context
&& state
->apply_verbosity
> verbosity_silent
)
1853 "file %s becomes empty but is not deleted"),
1859 static inline int metadata_changes(struct patch
*patch
)
1861 return patch
->is_rename
> 0 ||
1862 patch
->is_copy
> 0 ||
1863 patch
->is_new
> 0 ||
1865 (patch
->old_mode
&& patch
->new_mode
&&
1866 patch
->old_mode
!= patch
->new_mode
);
1869 static char *inflate_it(const void *data
, unsigned long size
,
1870 unsigned long inflated_size
)
1876 memset(&stream
, 0, sizeof(stream
));
1878 stream
.next_in
= (unsigned char *)data
;
1879 stream
.avail_in
= size
;
1880 stream
.next_out
= out
= xmalloc(inflated_size
);
1881 stream
.avail_out
= inflated_size
;
1882 git_inflate_init(&stream
);
1883 st
= git_inflate(&stream
, Z_FINISH
);
1884 git_inflate_end(&stream
);
1885 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1893 * Read a binary hunk and return a new fragment; fragment->patch
1894 * points at an allocated memory that the caller must free, so
1895 * it is marked as "->free_patch = 1".
1897 static struct fragment
*parse_binary_hunk(struct apply_state
*state
,
1899 unsigned long *sz_p
,
1904 * Expect a line that begins with binary patch method ("literal"
1905 * or "delta"), followed by the length of data before deflating.
1906 * a sequence of 'length-byte' followed by base-85 encoded data
1907 * should follow, terminated by a newline.
1909 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1910 * and we would limit the patch line to 66 characters,
1911 * so one line can fit up to 13 groups that would decode
1912 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1913 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1916 unsigned long size
= *sz_p
;
1917 char *buffer
= *buf_p
;
1919 unsigned long origlen
;
1922 struct fragment
*frag
;
1924 llen
= linelen(buffer
, size
);
1929 if (starts_with(buffer
, "delta ")) {
1930 patch_method
= BINARY_DELTA_DEFLATED
;
1931 origlen
= strtoul(buffer
+ 6, NULL
, 10);
1933 else if (starts_with(buffer
, "literal ")) {
1934 patch_method
= BINARY_LITERAL_DEFLATED
;
1935 origlen
= strtoul(buffer
+ 8, NULL
, 10);
1944 int byte_length
, max_byte_length
, newsize
;
1945 llen
= linelen(buffer
, size
);
1949 /* consume the blank line */
1955 * Minimum line is "A00000\n" which is 7-byte long,
1956 * and the line length must be multiple of 5 plus 2.
1958 if ((llen
< 7) || (llen
-2) % 5)
1960 max_byte_length
= (llen
- 2) / 5 * 4;
1961 byte_length
= *buffer
;
1962 if ('A' <= byte_length
&& byte_length
<= 'Z')
1963 byte_length
= byte_length
- 'A' + 1;
1964 else if ('a' <= byte_length
&& byte_length
<= 'z')
1965 byte_length
= byte_length
- 'a' + 27;
1968 /* if the input length was not multiple of 4, we would
1969 * have filler at the end but the filler should never
1972 if (max_byte_length
< byte_length
||
1973 byte_length
<= max_byte_length
- 4)
1975 newsize
= hunk_size
+ byte_length
;
1976 data
= xrealloc(data
, newsize
);
1977 if (decode_85(data
+ hunk_size
, buffer
+ 1, byte_length
))
1979 hunk_size
= newsize
;
1984 CALLOC_ARRAY(frag
, 1);
1985 frag
->patch
= inflate_it(data
, hunk_size
, origlen
);
1986 frag
->free_patch
= 1;
1990 frag
->size
= origlen
;
1994 frag
->binary_patch_method
= patch_method
;
2000 error(_("corrupt binary patch at line %d: %.*s"),
2001 state
->linenr
-1, llen
-1, buffer
);
2007 * -1 in case of error,
2008 * the length of the parsed binary patch otherwise
2010 static int parse_binary(struct apply_state
*state
,
2013 struct patch
*patch
)
2016 * We have read "GIT binary patch\n"; what follows is a line
2017 * that says the patch method (currently, either "literal" or
2018 * "delta") and the length of data before deflating; a
2019 * sequence of 'length-byte' followed by base-85 encoded data
2022 * When a binary patch is reversible, there is another binary
2023 * hunk in the same format, starting with patch method (either
2024 * "literal" or "delta") with the length of data, and a sequence
2025 * of length-byte + base-85 encoded data, terminated with another
2026 * empty line. This data, when applied to the postimage, produces
2029 struct fragment
*forward
;
2030 struct fragment
*reverse
;
2034 forward
= parse_binary_hunk(state
, &buffer
, &size
, &status
, &used
);
2035 if (!forward
&& !status
)
2036 /* there has to be one hunk (forward hunk) */
2037 return error(_("unrecognized binary patch at line %d"), state
->linenr
-1);
2039 /* otherwise we already gave an error message */
2042 reverse
= parse_binary_hunk(state
, &buffer
, &size
, &status
, &used_1
);
2047 * Not having reverse hunk is not an error, but having
2048 * a corrupt reverse hunk is.
2050 free((void*) forward
->patch
);
2054 forward
->next
= reverse
;
2055 patch
->fragments
= forward
;
2056 patch
->is_binary
= 1;
2060 static void prefix_one(struct apply_state
*state
, char **name
)
2062 char *old_name
= *name
;
2065 *name
= prefix_filename(state
->prefix
, *name
);
2069 static void prefix_patch(struct apply_state
*state
, struct patch
*p
)
2071 if (!state
->prefix
|| p
->is_toplevel_relative
)
2073 prefix_one(state
, &p
->new_name
);
2074 prefix_one(state
, &p
->old_name
);
2081 static void add_name_limit(struct apply_state
*state
,
2085 struct string_list_item
*it
;
2087 it
= string_list_append(&state
->limit_by_name
, name
);
2088 it
->util
= exclude
? NULL
: (void *) 1;
2091 static int use_patch(struct apply_state
*state
, struct patch
*p
)
2093 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
2096 /* Paths outside are not touched regardless of "--include" */
2097 if (state
->prefix
&& *state
->prefix
) {
2099 if (!skip_prefix(pathname
, state
->prefix
, &rest
) || !*rest
)
2103 /* See if it matches any of exclude/include rule */
2104 for (i
= 0; i
< state
->limit_by_name
.nr
; i
++) {
2105 struct string_list_item
*it
= &state
->limit_by_name
.items
[i
];
2106 if (!wildmatch(it
->string
, pathname
, 0))
2107 return (it
->util
!= NULL
);
2111 * If we had any include, a path that does not match any rule is
2112 * not used. Otherwise, we saw bunch of exclude rules (or none)
2113 * and such a path is used.
2115 return !state
->has_include
;
2119 * Read the patch text in "buffer" that extends for "size" bytes; stop
2120 * reading after seeing a single patch (i.e. changes to a single file).
2121 * Create fragments (i.e. patch hunks) and hang them to the given patch.
2124 * -1 if no header was found or parse_binary() failed,
2125 * -128 on another error,
2126 * the number of bytes consumed otherwise,
2127 * so that the caller can call us again for the next patch.
2129 static int parse_chunk(struct apply_state
*state
, char *buffer
, unsigned long size
, struct patch
*patch
)
2131 int hdrsize
, patchsize
;
2132 int offset
= find_header(state
, buffer
, size
, &hdrsize
, patch
);
2137 prefix_patch(state
, patch
);
2139 if (!use_patch(state
, patch
))
2141 else if (patch
->new_name
)
2142 patch
->ws_rule
= whitespace_rule(state
->repo
->index
,
2145 patch
->ws_rule
= whitespace_rule(state
->repo
->index
,
2148 patchsize
= parse_single_patch(state
,
2149 buffer
+ offset
+ hdrsize
,
2150 size
- offset
- hdrsize
,
2157 static const char git_binary
[] = "GIT binary patch\n";
2158 int hd
= hdrsize
+ offset
;
2159 unsigned long llen
= linelen(buffer
+ hd
, size
- hd
);
2161 if (llen
== sizeof(git_binary
) - 1 &&
2162 !memcmp(git_binary
, buffer
+ hd
, llen
)) {
2165 used
= parse_binary(state
, buffer
+ hd
+ llen
,
2166 size
- hd
- llen
, patch
);
2170 patchsize
= used
+ llen
;
2174 else if (!memcmp(" differ\n", buffer
+ hd
+ llen
- 8, 8)) {
2175 static const char *binhdr
[] = {
2181 for (i
= 0; binhdr
[i
]; i
++) {
2182 int len
= strlen(binhdr
[i
]);
2183 if (len
< size
- hd
&&
2184 !memcmp(binhdr
[i
], buffer
+ hd
, len
)) {
2186 patch
->is_binary
= 1;
2193 /* Empty patch cannot be applied if it is a text patch
2194 * without metadata change. A binary patch appears
2197 if ((state
->apply
|| state
->check
) &&
2198 (!patch
->is_binary
&& !metadata_changes(patch
))) {
2199 error(_("patch with only garbage at line %d"), state
->linenr
);
2204 return offset
+ hdrsize
+ patchsize
;
2207 static void reverse_patches(struct patch
*p
)
2209 for (; p
; p
= p
->next
) {
2210 struct fragment
*frag
= p
->fragments
;
2212 SWAP(p
->new_name
, p
->old_name
);
2213 SWAP(p
->new_mode
, p
->old_mode
);
2214 SWAP(p
->is_new
, p
->is_delete
);
2215 SWAP(p
->lines_added
, p
->lines_deleted
);
2216 SWAP(p
->old_oid_prefix
, p
->new_oid_prefix
);
2218 for (; frag
; frag
= frag
->next
) {
2219 SWAP(frag
->newpos
, frag
->oldpos
);
2220 SWAP(frag
->newlines
, frag
->oldlines
);
2225 static const char pluses
[] =
2226 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2227 static const char minuses
[]=
2228 "----------------------------------------------------------------------";
2230 static void show_stats(struct apply_state
*state
, struct patch
*patch
)
2232 struct strbuf qname
= STRBUF_INIT
;
2233 char *cp
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
2236 quote_c_style(cp
, &qname
, NULL
, 0);
2239 * "scale" the filename
2241 max
= state
->max_len
;
2245 if (qname
.len
> max
) {
2246 cp
= strchr(qname
.buf
+ qname
.len
+ 3 - max
, '/');
2248 cp
= qname
.buf
+ qname
.len
+ 3 - max
;
2249 strbuf_splice(&qname
, 0, cp
- qname
.buf
, "...", 3);
2252 if (patch
->is_binary
) {
2253 printf(" %-*s | Bin\n", max
, qname
.buf
);
2254 strbuf_release(&qname
);
2258 printf(" %-*s |", max
, qname
.buf
);
2259 strbuf_release(&qname
);
2262 * scale the add/delete
2264 max
= max
+ state
->max_change
> 70 ? 70 - max
: state
->max_change
;
2265 add
= patch
->lines_added
;
2266 del
= patch
->lines_deleted
;
2268 if (state
->max_change
> 0) {
2269 int total
= ((add
+ del
) * max
+ state
->max_change
/ 2) / state
->max_change
;
2270 add
= (add
* max
+ state
->max_change
/ 2) / state
->max_change
;
2273 printf("%5d %.*s%.*s\n", patch
->lines_added
+ patch
->lines_deleted
,
2274 add
, pluses
, del
, minuses
);
2277 static int read_old_data(struct stat
*st
, struct patch
*patch
,
2278 const char *path
, struct strbuf
*buf
)
2280 int conv_flags
= patch
->crlf_in_old
?
2281 CONV_EOL_KEEP_CRLF
: CONV_EOL_RENORMALIZE
;
2282 switch (st
->st_mode
& S_IFMT
) {
2284 if (strbuf_readlink(buf
, path
, st
->st_size
) < 0)
2285 return error(_("unable to read symlink %s"), path
);
2288 if (strbuf_read_file(buf
, path
, st
->st_size
) != st
->st_size
)
2289 return error(_("unable to open or read %s"), path
);
2291 * "git apply" without "--index/--cached" should never look
2292 * at the index; the target file may not have been added to
2293 * the index yet, and we may not even be in any Git repository.
2294 * Pass NULL to convert_to_git() to stress this; the function
2295 * should never look at the index when explicit crlf option
2298 convert_to_git(NULL
, path
, buf
->buf
, buf
->len
, buf
, conv_flags
);
2306 * Update the preimage, and the common lines in postimage,
2307 * from buffer buf of length len. If postlen is 0 the postimage
2308 * is updated in place, otherwise it's updated on a new buffer
2312 static void update_pre_post_images(struct image
*preimage
,
2313 struct image
*postimage
,
2315 size_t len
, size_t postlen
)
2317 int i
, ctx
, reduced
;
2318 char *new_buf
, *old_buf
, *fixed
;
2319 struct image fixed_preimage
;
2322 * Update the preimage with whitespace fixes. Note that we
2323 * are not losing preimage->buf -- apply_one_fragment() will
2326 prepare_image(&fixed_preimage
, buf
, len
, 1);
2328 ? fixed_preimage
.nr
== preimage
->nr
2329 : fixed_preimage
.nr
<= preimage
->nr
);
2330 for (i
= 0; i
< fixed_preimage
.nr
; i
++)
2331 fixed_preimage
.line
[i
].flag
= preimage
->line
[i
].flag
;
2332 free(preimage
->line_allocated
);
2333 *preimage
= fixed_preimage
;
2336 * Adjust the common context lines in postimage. This can be
2337 * done in-place when we are shrinking it with whitespace
2338 * fixing, but needs a new buffer when ignoring whitespace or
2339 * expanding leading tabs to spaces.
2341 * We trust the caller to tell us if the update can be done
2342 * in place (postlen==0) or not.
2344 old_buf
= postimage
->buf
;
2346 new_buf
= postimage
->buf
= xmalloc(postlen
);
2349 fixed
= preimage
->buf
;
2351 for (i
= reduced
= ctx
= 0; i
< postimage
->nr
; i
++) {
2352 size_t l_len
= postimage
->line
[i
].len
;
2353 if (!(postimage
->line
[i
].flag
& LINE_COMMON
)) {
2354 /* an added line -- no counterparts in preimage */
2355 memmove(new_buf
, old_buf
, l_len
);
2361 /* a common context -- skip it in the original postimage */
2364 /* and find the corresponding one in the fixed preimage */
2365 while (ctx
< preimage
->nr
&&
2366 !(preimage
->line
[ctx
].flag
& LINE_COMMON
)) {
2367 fixed
+= preimage
->line
[ctx
].len
;
2372 * preimage is expected to run out, if the caller
2373 * fixed addition of trailing blank lines.
2375 if (preimage
->nr
<= ctx
) {
2380 /* and copy it in, while fixing the line length */
2381 l_len
= preimage
->line
[ctx
].len
;
2382 memcpy(new_buf
, fixed
, l_len
);
2385 postimage
->line
[i
].len
= l_len
;
2390 ? postlen
< new_buf
- postimage
->buf
2391 : postimage
->len
< new_buf
- postimage
->buf
)
2392 BUG("caller miscounted postlen: asked %d, orig = %d, used = %d",
2393 (int)postlen
, (int) postimage
->len
, (int)(new_buf
- postimage
->buf
));
2395 /* Fix the length of the whole thing */
2396 postimage
->len
= new_buf
- postimage
->buf
;
2397 postimage
->nr
-= reduced
;
2400 static int line_by_line_fuzzy_match(struct image
*img
,
2401 struct image
*preimage
,
2402 struct image
*postimage
,
2403 unsigned long current
,
2410 size_t postlen
= postimage
->len
;
2415 struct strbuf fixed
;
2419 for (i
= 0; i
< preimage_limit
; i
++) {
2420 size_t prelen
= preimage
->line
[i
].len
;
2421 size_t imglen
= img
->line
[current_lno
+i
].len
;
2423 if (!fuzzy_matchlines(img
->buf
+ current
+ imgoff
, imglen
,
2424 preimage
->buf
+ preoff
, prelen
))
2426 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2427 postlen
+= imglen
- prelen
;
2433 * Ok, the preimage matches with whitespace fuzz.
2435 * imgoff now holds the true length of the target that
2436 * matches the preimage before the end of the file.
2438 * Count the number of characters in the preimage that fall
2439 * beyond the end of the file and make sure that all of them
2440 * are whitespace characters. (This can only happen if
2441 * we are removing blank lines at the end of the file.)
2443 buf
= preimage_eof
= preimage
->buf
+ preoff
;
2444 for ( ; i
< preimage
->nr
; i
++)
2445 preoff
+= preimage
->line
[i
].len
;
2446 preimage_end
= preimage
->buf
+ preoff
;
2447 for ( ; buf
< preimage_end
; buf
++)
2452 * Update the preimage and the common postimage context
2453 * lines to use the same whitespace as the target.
2454 * If whitespace is missing in the target (i.e.
2455 * if the preimage extends beyond the end of the file),
2456 * use the whitespace from the preimage.
2458 extra_chars
= preimage_end
- preimage_eof
;
2459 strbuf_init(&fixed
, imgoff
+ extra_chars
);
2460 strbuf_add(&fixed
, img
->buf
+ current
, imgoff
);
2461 strbuf_add(&fixed
, preimage_eof
, extra_chars
);
2462 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2463 update_pre_post_images(preimage
, postimage
,
2464 fixed_buf
, fixed_len
, postlen
);
2468 static int match_fragment(struct apply_state
*state
,
2470 struct image
*preimage
,
2471 struct image
*postimage
,
2472 unsigned long current
,
2475 int match_beginning
, int match_end
)
2478 char *fixed_buf
, *buf
, *orig
, *target
;
2479 struct strbuf fixed
;
2480 size_t fixed_len
, postlen
;
2483 if (preimage
->nr
+ current_lno
<= img
->nr
) {
2485 * The hunk falls within the boundaries of img.
2487 preimage_limit
= preimage
->nr
;
2488 if (match_end
&& (preimage
->nr
+ current_lno
!= img
->nr
))
2490 } else if (state
->ws_error_action
== correct_ws_error
&&
2491 (ws_rule
& WS_BLANK_AT_EOF
)) {
2493 * This hunk extends beyond the end of img, and we are
2494 * removing blank lines at the end of the file. This
2495 * many lines from the beginning of the preimage must
2496 * match with img, and the remainder of the preimage
2499 preimage_limit
= img
->nr
- current_lno
;
2502 * The hunk extends beyond the end of the img and
2503 * we are not removing blanks at the end, so we
2504 * should reject the hunk at this position.
2509 if (match_beginning
&& current_lno
)
2512 /* Quick hash check */
2513 for (i
= 0; i
< preimage_limit
; i
++)
2514 if ((img
->line
[current_lno
+ i
].flag
& LINE_PATCHED
) ||
2515 (preimage
->line
[i
].hash
!= img
->line
[current_lno
+ i
].hash
))
2518 if (preimage_limit
== preimage
->nr
) {
2520 * Do we have an exact match? If we were told to match
2521 * at the end, size must be exactly at current+fragsize,
2522 * otherwise current+fragsize must be still within the preimage,
2523 * and either case, the old piece should match the preimage
2527 ? (current
+ preimage
->len
== img
->len
)
2528 : (current
+ preimage
->len
<= img
->len
)) &&
2529 !memcmp(img
->buf
+ current
, preimage
->buf
, preimage
->len
))
2533 * The preimage extends beyond the end of img, so
2534 * there cannot be an exact match.
2536 * There must be one non-blank context line that match
2537 * a line before the end of img.
2541 buf
= preimage
->buf
;
2543 for (i
= 0; i
< preimage_limit
; i
++)
2544 buf_end
+= preimage
->line
[i
].len
;
2546 for ( ; buf
< buf_end
; buf
++)
2554 * No exact match. If we are ignoring whitespace, run a line-by-line
2555 * fuzzy matching. We collect all the line length information because
2556 * we need it to adjust whitespace if we match.
2558 if (state
->ws_ignore_action
== ignore_ws_change
)
2559 return line_by_line_fuzzy_match(img
, preimage
, postimage
,
2560 current
, current_lno
, preimage_limit
);
2562 if (state
->ws_error_action
!= correct_ws_error
)
2566 * The hunk does not apply byte-by-byte, but the hash says
2567 * it might with whitespace fuzz. We weren't asked to
2568 * ignore whitespace, we were asked to correct whitespace
2569 * errors, so let's try matching after whitespace correction.
2571 * While checking the preimage against the target, whitespace
2572 * errors in both fixed, we count how large the corresponding
2573 * postimage needs to be. The postimage prepared by
2574 * apply_one_fragment() has whitespace errors fixed on added
2575 * lines already, but the common lines were propagated as-is,
2576 * which may become longer when their whitespace errors are
2580 /* First count added lines in postimage */
2582 for (i
= 0; i
< postimage
->nr
; i
++) {
2583 if (!(postimage
->line
[i
].flag
& LINE_COMMON
))
2584 postlen
+= postimage
->line
[i
].len
;
2588 * The preimage may extend beyond the end of the file,
2589 * but in this loop we will only handle the part of the
2590 * preimage that falls within the file.
2592 strbuf_init(&fixed
, preimage
->len
+ 1);
2593 orig
= preimage
->buf
;
2594 target
= img
->buf
+ current
;
2595 for (i
= 0; i
< preimage_limit
; i
++) {
2596 size_t oldlen
= preimage
->line
[i
].len
;
2597 size_t tgtlen
= img
->line
[current_lno
+ i
].len
;
2598 size_t fixstart
= fixed
.len
;
2599 struct strbuf tgtfix
;
2602 /* Try fixing the line in the preimage */
2603 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2605 /* Try fixing the line in the target */
2606 strbuf_init(&tgtfix
, tgtlen
);
2607 ws_fix_copy(&tgtfix
, target
, tgtlen
, ws_rule
, NULL
);
2610 * If they match, either the preimage was based on
2611 * a version before our tree fixed whitespace breakage,
2612 * or we are lacking a whitespace-fix patch the tree
2613 * the preimage was based on already had (i.e. target
2614 * has whitespace breakage, the preimage doesn't).
2615 * In either case, we are fixing the whitespace breakages
2616 * so we might as well take the fix together with their
2619 match
= (tgtfix
.len
== fixed
.len
- fixstart
&&
2620 !memcmp(tgtfix
.buf
, fixed
.buf
+ fixstart
,
2621 fixed
.len
- fixstart
));
2623 /* Add the length if this is common with the postimage */
2624 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2625 postlen
+= tgtfix
.len
;
2627 strbuf_release(&tgtfix
);
2637 * Now handle the lines in the preimage that falls beyond the
2638 * end of the file (if any). They will only match if they are
2639 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2642 for ( ; i
< preimage
->nr
; i
++) {
2643 size_t fixstart
= fixed
.len
; /* start of the fixed preimage */
2644 size_t oldlen
= preimage
->line
[i
].len
;
2647 /* Try fixing the line in the preimage */
2648 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2650 for (j
= fixstart
; j
< fixed
.len
; j
++)
2651 if (!isspace(fixed
.buf
[j
]))
2658 * Yes, the preimage is based on an older version that still
2659 * has whitespace breakages unfixed, and fixing them makes the
2660 * hunk match. Update the context lines in the postimage.
2662 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2663 if (postlen
< postimage
->len
)
2665 update_pre_post_images(preimage
, postimage
,
2666 fixed_buf
, fixed_len
, postlen
);
2670 strbuf_release(&fixed
);
2674 static int find_pos(struct apply_state
*state
,
2676 struct image
*preimage
,
2677 struct image
*postimage
,
2680 int match_beginning
, int match_end
)
2683 unsigned long backwards
, forwards
, current
;
2684 int backwards_lno
, forwards_lno
, current_lno
;
2687 * When running with --allow-overlap, it is possible that a hunk is
2688 * seen that pretends to start at the beginning (but no longer does),
2689 * and that *still* needs to match the end. So trust `match_end` more
2690 * than `match_beginning`.
2692 if (state
->allow_overlap
&& match_beginning
&& match_end
&&
2693 img
->nr
- preimage
->nr
!= 0)
2694 match_beginning
= 0;
2697 * If match_beginning or match_end is specified, there is no
2698 * point starting from a wrong line that will never match and
2699 * wander around and wait for a match at the specified end.
2701 if (match_beginning
)
2704 line
= img
->nr
- preimage
->nr
;
2707 * Because the comparison is unsigned, the following test
2708 * will also take care of a negative line number that can
2709 * result when match_end and preimage is larger than the target.
2711 if ((size_t) line
> img
->nr
)
2715 for (i
= 0; i
< line
; i
++)
2716 current
+= img
->line
[i
].len
;
2719 * There's probably some smart way to do this, but I'll leave
2720 * that to the smart and beautiful people. I'm simple and stupid.
2722 backwards
= current
;
2723 backwards_lno
= line
;
2725 forwards_lno
= line
;
2728 for (i
= 0; ; i
++) {
2729 if (match_fragment(state
, img
, preimage
, postimage
,
2730 current
, current_lno
, ws_rule
,
2731 match_beginning
, match_end
))
2735 if (backwards_lno
== 0 && forwards_lno
== img
->nr
)
2739 if (backwards_lno
== 0) {
2744 backwards
-= img
->line
[backwards_lno
].len
;
2745 current
= backwards
;
2746 current_lno
= backwards_lno
;
2748 if (forwards_lno
== img
->nr
) {
2752 forwards
+= img
->line
[forwards_lno
].len
;
2755 current_lno
= forwards_lno
;
2762 static void remove_first_line(struct image
*img
)
2764 img
->buf
+= img
->line
[0].len
;
2765 img
->len
-= img
->line
[0].len
;
2770 static void remove_last_line(struct image
*img
)
2772 img
->len
-= img
->line
[--img
->nr
].len
;
2776 * The change from "preimage" and "postimage" has been found to
2777 * apply at applied_pos (counts in line numbers) in "img".
2778 * Update "img" to remove "preimage" and replace it with "postimage".
2780 static void update_image(struct apply_state
*state
,
2783 struct image
*preimage
,
2784 struct image
*postimage
)
2787 * remove the copy of preimage at offset in img
2788 * and replace it with postimage
2791 size_t remove_count
, insert_count
, applied_at
= 0;
2796 * If we are removing blank lines at the end of img,
2797 * the preimage may extend beyond the end.
2798 * If that is the case, we must be careful only to
2799 * remove the part of the preimage that falls within
2800 * the boundaries of img. Initialize preimage_limit
2801 * to the number of lines in the preimage that falls
2802 * within the boundaries.
2804 preimage_limit
= preimage
->nr
;
2805 if (preimage_limit
> img
->nr
- applied_pos
)
2806 preimage_limit
= img
->nr
- applied_pos
;
2808 for (i
= 0; i
< applied_pos
; i
++)
2809 applied_at
+= img
->line
[i
].len
;
2812 for (i
= 0; i
< preimage_limit
; i
++)
2813 remove_count
+= img
->line
[applied_pos
+ i
].len
;
2814 insert_count
= postimage
->len
;
2816 /* Adjust the contents */
2817 result
= xmalloc(st_add3(st_sub(img
->len
, remove_count
), insert_count
, 1));
2818 memcpy(result
, img
->buf
, applied_at
);
2819 memcpy(result
+ applied_at
, postimage
->buf
, postimage
->len
);
2820 memcpy(result
+ applied_at
+ postimage
->len
,
2821 img
->buf
+ (applied_at
+ remove_count
),
2822 img
->len
- (applied_at
+ remove_count
));
2825 img
->len
+= insert_count
- remove_count
;
2826 result
[img
->len
] = '\0';
2828 /* Adjust the line table */
2829 nr
= img
->nr
+ postimage
->nr
- preimage_limit
;
2830 if (preimage_limit
< postimage
->nr
) {
2832 * NOTE: this knows that we never call remove_first_line()
2833 * on anything other than pre/post image.
2835 REALLOC_ARRAY(img
->line
, nr
);
2836 img
->line_allocated
= img
->line
;
2838 if (preimage_limit
!= postimage
->nr
)
2839 MOVE_ARRAY(img
->line
+ applied_pos
+ postimage
->nr
,
2840 img
->line
+ applied_pos
+ preimage_limit
,
2841 img
->nr
- (applied_pos
+ preimage_limit
));
2842 COPY_ARRAY(img
->line
+ applied_pos
, postimage
->line
, postimage
->nr
);
2843 if (!state
->allow_overlap
)
2844 for (i
= 0; i
< postimage
->nr
; i
++)
2845 img
->line
[applied_pos
+ i
].flag
|= LINE_PATCHED
;
2850 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2851 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2852 * replace the part of "img" with "postimage" text.
2854 static int apply_one_fragment(struct apply_state
*state
,
2855 struct image
*img
, struct fragment
*frag
,
2856 int inaccurate_eof
, unsigned ws_rule
,
2859 int match_beginning
, match_end
;
2860 const char *patch
= frag
->patch
;
2861 int size
= frag
->size
;
2862 char *old
, *oldlines
;
2863 struct strbuf newlines
;
2864 int new_blank_lines_at_end
= 0;
2865 int found_new_blank_lines_at_end
= 0;
2866 int hunk_linenr
= frag
->linenr
;
2867 unsigned long leading
, trailing
;
2868 int pos
, applied_pos
;
2869 struct image preimage
;
2870 struct image postimage
;
2872 memset(&preimage
, 0, sizeof(preimage
));
2873 memset(&postimage
, 0, sizeof(postimage
));
2874 oldlines
= xmalloc(size
);
2875 strbuf_init(&newlines
, size
);
2880 int len
= linelen(patch
, size
);
2882 int added_blank_line
= 0;
2883 int is_blank_context
= 0;
2890 * "plen" is how much of the line we should use for
2891 * the actual patch data. Normally we just remove the
2892 * first character on the line, but if the line is
2893 * followed by "\ No newline", then we also remove the
2894 * last one (which is the newline, of course).
2897 if (len
< size
&& patch
[len
] == '\\')
2900 if (state
->apply_in_reverse
) {
2903 else if (first
== '+')
2909 /* Newer GNU diff, empty context line */
2911 /* ... followed by '\No newline'; nothing */
2914 strbuf_addch(&newlines
, '\n');
2915 add_line_info(&preimage
, "\n", 1, LINE_COMMON
);
2916 add_line_info(&postimage
, "\n", 1, LINE_COMMON
);
2917 is_blank_context
= 1;
2920 if (plen
&& (ws_rule
& WS_BLANK_AT_EOF
) &&
2921 ws_blank_line(patch
+ 1, plen
))
2922 is_blank_context
= 1;
2925 memcpy(old
, patch
+ 1, plen
);
2926 add_line_info(&preimage
, old
, plen
,
2927 (first
== ' ' ? LINE_COMMON
: 0));
2933 /* --no-add does not add new lines */
2934 if (first
== '+' && state
->no_add
)
2937 start
= newlines
.len
;
2939 !state
->whitespace_error
||
2940 state
->ws_error_action
!= correct_ws_error
) {
2941 strbuf_add(&newlines
, patch
+ 1, plen
);
2944 ws_fix_copy(&newlines
, patch
+ 1, plen
, ws_rule
, &state
->applied_after_fixing_ws
);
2946 add_line_info(&postimage
, newlines
.buf
+ start
, newlines
.len
- start
,
2947 (first
== '+' ? 0 : LINE_COMMON
));
2949 (ws_rule
& WS_BLANK_AT_EOF
) &&
2950 ws_blank_line(patch
+ 1, plen
))
2951 added_blank_line
= 1;
2953 case '@': case '\\':
2954 /* Ignore it, we already handled it */
2957 if (state
->apply_verbosity
> verbosity_normal
)
2958 error(_("invalid start of line: '%c'"), first
);
2962 if (added_blank_line
) {
2963 if (!new_blank_lines_at_end
)
2964 found_new_blank_lines_at_end
= hunk_linenr
;
2965 new_blank_lines_at_end
++;
2967 else if (is_blank_context
)
2970 new_blank_lines_at_end
= 0;
2975 if (inaccurate_eof
&&
2976 old
> oldlines
&& old
[-1] == '\n' &&
2977 newlines
.len
> 0 && newlines
.buf
[newlines
.len
- 1] == '\n') {
2979 strbuf_setlen(&newlines
, newlines
.len
- 1);
2980 preimage
.line_allocated
[preimage
.nr
- 1].len
--;
2981 postimage
.line_allocated
[postimage
.nr
- 1].len
--;
2984 leading
= frag
->leading
;
2985 trailing
= frag
->trailing
;
2988 * A hunk to change lines at the beginning would begin with
2990 * but we need to be careful. -U0 that inserts before the second
2991 * line also has this pattern.
2993 * And a hunk to add to an empty file would begin with
2996 * In other words, a hunk that is (frag->oldpos <= 1) with or
2997 * without leading context must match at the beginning.
2999 match_beginning
= (!frag
->oldpos
||
3000 (frag
->oldpos
== 1 && !state
->unidiff_zero
));
3003 * A hunk without trailing lines must match at the end.
3004 * However, we simply cannot tell if a hunk must match end
3005 * from the lack of trailing lines if the patch was generated
3006 * with unidiff without any context.
3008 match_end
= !state
->unidiff_zero
&& !trailing
;
3010 pos
= frag
->newpos
? (frag
->newpos
- 1) : 0;
3011 preimage
.buf
= oldlines
;
3012 preimage
.len
= old
- oldlines
;
3013 postimage
.buf
= newlines
.buf
;
3014 postimage
.len
= newlines
.len
;
3015 preimage
.line
= preimage
.line_allocated
;
3016 postimage
.line
= postimage
.line_allocated
;
3020 applied_pos
= find_pos(state
, img
, &preimage
, &postimage
, pos
,
3021 ws_rule
, match_beginning
, match_end
);
3023 if (applied_pos
>= 0)
3026 /* Am I at my context limits? */
3027 if ((leading
<= state
->p_context
) && (trailing
<= state
->p_context
))
3029 if (match_beginning
|| match_end
) {
3030 match_beginning
= match_end
= 0;
3035 * Reduce the number of context lines; reduce both
3036 * leading and trailing if they are equal otherwise
3037 * just reduce the larger context.
3039 if (leading
>= trailing
) {
3040 remove_first_line(&preimage
);
3041 remove_first_line(&postimage
);
3045 if (trailing
> leading
) {
3046 remove_last_line(&preimage
);
3047 remove_last_line(&postimage
);
3052 if (applied_pos
>= 0) {
3053 if (new_blank_lines_at_end
&&
3054 preimage
.nr
+ applied_pos
>= img
->nr
&&
3055 (ws_rule
& WS_BLANK_AT_EOF
) &&
3056 state
->ws_error_action
!= nowarn_ws_error
) {
3057 record_ws_error(state
, WS_BLANK_AT_EOF
, "+", 1,
3058 found_new_blank_lines_at_end
);
3059 if (state
->ws_error_action
== correct_ws_error
) {
3060 while (new_blank_lines_at_end
--)
3061 remove_last_line(&postimage
);
3064 * We would want to prevent write_out_results()
3065 * from taking place in apply_patch() that follows
3066 * the callchain led us here, which is:
3067 * apply_patch->check_patch_list->check_patch->
3068 * apply_data->apply_fragments->apply_one_fragment
3070 if (state
->ws_error_action
== die_on_ws_error
)
3074 if (state
->apply_verbosity
> verbosity_normal
&& applied_pos
!= pos
) {
3075 int offset
= applied_pos
- pos
;
3076 if (state
->apply_in_reverse
)
3077 offset
= 0 - offset
;
3079 Q_("Hunk #%d succeeded at %d (offset %d line).",
3080 "Hunk #%d succeeded at %d (offset %d lines).",
3082 nth_fragment
, applied_pos
+ 1, offset
);
3086 * Warn if it was necessary to reduce the number
3089 if ((leading
!= frag
->leading
||
3090 trailing
!= frag
->trailing
) && state
->apply_verbosity
> verbosity_silent
)
3091 fprintf_ln(stderr
, _("Context reduced to (%ld/%ld)"
3092 " to apply fragment at %d"),
3093 leading
, trailing
, applied_pos
+1);
3094 update_image(state
, img
, applied_pos
, &preimage
, &postimage
);
3096 if (state
->apply_verbosity
> verbosity_normal
)
3097 error(_("while searching for:\n%.*s"),
3098 (int)(old
- oldlines
), oldlines
);
3103 strbuf_release(&newlines
);
3104 free(preimage
.line_allocated
);
3105 free(postimage
.line_allocated
);
3107 return (applied_pos
< 0);
3110 static int apply_binary_fragment(struct apply_state
*state
,
3112 struct patch
*patch
)
3114 struct fragment
*fragment
= patch
->fragments
;
3119 return error(_("missing binary patch data for '%s'"),
3124 /* Binary patch is irreversible without the optional second hunk */
3125 if (state
->apply_in_reverse
) {
3126 if (!fragment
->next
)
3127 return error(_("cannot reverse-apply a binary patch "
3128 "without the reverse hunk to '%s'"),
3130 ? patch
->new_name
: patch
->old_name
);
3131 fragment
= fragment
->next
;
3133 switch (fragment
->binary_patch_method
) {
3134 case BINARY_DELTA_DEFLATED
:
3135 dst
= patch_delta(img
->buf
, img
->len
, fragment
->patch
,
3136 fragment
->size
, &len
);
3143 case BINARY_LITERAL_DEFLATED
:
3145 img
->len
= fragment
->size
;
3146 img
->buf
= xmemdupz(fragment
->patch
, img
->len
);
3153 * Replace "img" with the result of applying the binary patch.
3154 * The binary patch data itself in patch->fragment is still kept
3155 * but the preimage prepared by the caller in "img" is freed here
3156 * or in the helper function apply_binary_fragment() this calls.
3158 static int apply_binary(struct apply_state
*state
,
3160 struct patch
*patch
)
3162 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3163 struct object_id oid
;
3164 const unsigned hexsz
= the_hash_algo
->hexsz
;
3167 * For safety, we require patch index line to contain
3168 * full hex textual object ID for old and new, at least for now.
3170 if (strlen(patch
->old_oid_prefix
) != hexsz
||
3171 strlen(patch
->new_oid_prefix
) != hexsz
||
3172 get_oid_hex(patch
->old_oid_prefix
, &oid
) ||
3173 get_oid_hex(patch
->new_oid_prefix
, &oid
))
3174 return error(_("cannot apply binary patch to '%s' "
3175 "without full index line"), name
);
3177 if (patch
->old_name
) {
3179 * See if the old one matches what the patch
3182 hash_object_file(the_hash_algo
, img
->buf
, img
->len
, OBJ_BLOB
,
3184 if (strcmp(oid_to_hex(&oid
), patch
->old_oid_prefix
))
3185 return error(_("the patch applies to '%s' (%s), "
3186 "which does not match the "
3187 "current contents."),
3188 name
, oid_to_hex(&oid
));
3191 /* Otherwise, the old one must be empty. */
3193 return error(_("the patch applies to an empty "
3194 "'%s' but it is not empty"), name
);
3197 get_oid_hex(patch
->new_oid_prefix
, &oid
);
3198 if (is_null_oid(&oid
)) {
3200 return 0; /* deletion patch */
3203 if (has_object(the_repository
, &oid
, 0)) {
3204 /* We already have the postimage */
3205 enum object_type type
;
3209 result
= read_object_file(&oid
, &type
, &size
);
3211 return error(_("the necessary postimage %s for "
3212 "'%s' cannot be read"),
3213 patch
->new_oid_prefix
, name
);
3219 * We have verified buf matches the preimage;
3220 * apply the patch data to it, which is stored
3221 * in the patch->fragments->{patch,size}.
3223 if (apply_binary_fragment(state
, img
, patch
))
3224 return error(_("binary patch does not apply to '%s'"),
3227 /* verify that the result matches */
3228 hash_object_file(the_hash_algo
, img
->buf
, img
->len
, OBJ_BLOB
,
3230 if (strcmp(oid_to_hex(&oid
), patch
->new_oid_prefix
))
3231 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3232 name
, patch
->new_oid_prefix
, oid_to_hex(&oid
));
3238 static int apply_fragments(struct apply_state
*state
, struct image
*img
, struct patch
*patch
)
3240 struct fragment
*frag
= patch
->fragments
;
3241 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3242 unsigned ws_rule
= patch
->ws_rule
;
3243 unsigned inaccurate_eof
= patch
->inaccurate_eof
;
3246 if (patch
->is_binary
)
3247 return apply_binary(state
, img
, patch
);
3251 if (apply_one_fragment(state
, img
, frag
, inaccurate_eof
, ws_rule
, nth
)) {
3252 error(_("patch failed: %s:%ld"), name
, frag
->oldpos
);
3253 if (!state
->apply_with_reject
)
3262 static int read_blob_object(struct strbuf
*buf
, const struct object_id
*oid
, unsigned mode
)
3264 if (S_ISGITLINK(mode
)) {
3265 strbuf_grow(buf
, 100);
3266 strbuf_addf(buf
, "Subproject commit %s\n", oid_to_hex(oid
));
3268 enum object_type type
;
3272 result
= read_object_file(oid
, &type
, &sz
);
3275 /* XXX read_sha1_file NUL-terminates */
3276 strbuf_attach(buf
, result
, sz
, sz
+ 1);
3281 static int read_file_or_gitlink(const struct cache_entry
*ce
, struct strbuf
*buf
)
3285 return read_blob_object(buf
, &ce
->oid
, ce
->ce_mode
);
3288 static struct patch
*in_fn_table(struct apply_state
*state
, const char *name
)
3290 struct string_list_item
*item
;
3295 item
= string_list_lookup(&state
->fn_table
, name
);
3297 return (struct patch
*)item
->util
;
3303 * item->util in the filename table records the status of the path.
3304 * Usually it points at a patch (whose result records the contents
3305 * of it after applying it), but it could be PATH_WAS_DELETED for a
3306 * path that a previously applied patch has already removed, or
3307 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3309 * The latter is needed to deal with a case where two paths A and B
3310 * are swapped by first renaming A to B and then renaming B to A;
3311 * moving A to B should not be prevented due to presence of B as we
3312 * will remove it in a later patch.
3314 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3315 #define PATH_WAS_DELETED ((struct patch *) -1)
3317 static int to_be_deleted(struct patch
*patch
)
3319 return patch
== PATH_TO_BE_DELETED
;
3322 static int was_deleted(struct patch
*patch
)
3324 return patch
== PATH_WAS_DELETED
;
3327 static void add_to_fn_table(struct apply_state
*state
, struct patch
*patch
)
3329 struct string_list_item
*item
;
3332 * Always add new_name unless patch is a deletion
3333 * This should cover the cases for normal diffs,
3334 * file creations and copies
3336 if (patch
->new_name
) {
3337 item
= string_list_insert(&state
->fn_table
, patch
->new_name
);
3342 * store a failure on rename/deletion cases because
3343 * later chunks shouldn't patch old names
3345 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3346 item
= string_list_insert(&state
->fn_table
, patch
->old_name
);
3347 item
->util
= PATH_WAS_DELETED
;
3351 static void prepare_fn_table(struct apply_state
*state
, struct patch
*patch
)
3354 * store information about incoming file deletion
3357 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3358 struct string_list_item
*item
;
3359 item
= string_list_insert(&state
->fn_table
, patch
->old_name
);
3360 item
->util
= PATH_TO_BE_DELETED
;
3362 patch
= patch
->next
;
3366 static int checkout_target(struct index_state
*istate
,
3367 struct cache_entry
*ce
, struct stat
*st
)
3369 struct checkout costate
= CHECKOUT_INIT
;
3371 costate
.refresh_cache
= 1;
3372 costate
.istate
= istate
;
3373 if (checkout_entry(ce
, &costate
, NULL
, NULL
) ||
3374 lstat(ce
->name
, st
))
3375 return error(_("cannot checkout %s"), ce
->name
);
3379 static struct patch
*previous_patch(struct apply_state
*state
,
3380 struct patch
*patch
,
3383 struct patch
*previous
;
3386 if (patch
->is_copy
|| patch
->is_rename
)
3387 return NULL
; /* "git" patches do not depend on the order */
3389 previous
= in_fn_table(state
, patch
->old_name
);
3393 if (to_be_deleted(previous
))
3394 return NULL
; /* the deletion hasn't happened yet */
3396 if (was_deleted(previous
))
3402 static int verify_index_match(struct apply_state
*state
,
3403 const struct cache_entry
*ce
,
3406 if (S_ISGITLINK(ce
->ce_mode
)) {
3407 if (!S_ISDIR(st
->st_mode
))
3411 return ie_match_stat(state
->repo
->index
, ce
, st
,
3412 CE_MATCH_IGNORE_VALID
| CE_MATCH_IGNORE_SKIP_WORKTREE
);
3415 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3417 static int load_patch_target(struct apply_state
*state
,
3419 const struct cache_entry
*ce
,
3421 struct patch
*patch
,
3423 unsigned expected_mode
)
3425 if (state
->cached
|| state
->check_index
) {
3426 if (read_file_or_gitlink(ce
, buf
))
3427 return error(_("failed to read %s"), name
);
3429 if (S_ISGITLINK(expected_mode
)) {
3431 return read_file_or_gitlink(ce
, buf
);
3433 return SUBMODULE_PATCH_WITHOUT_INDEX
;
3434 } else if (has_symlink_leading_path(name
, strlen(name
))) {
3435 return error(_("reading from '%s' beyond a symbolic link"), name
);
3437 if (read_old_data(st
, patch
, name
, buf
))
3438 return error(_("failed to read %s"), name
);
3445 * We are about to apply "patch"; populate the "image" with the
3446 * current version we have, from the working tree or from the index,
3447 * depending on the situation e.g. --cached/--index. If we are
3448 * applying a non-git patch that incrementally updates the tree,
3449 * we read from the result of a previous diff.
3451 static int load_preimage(struct apply_state
*state
,
3452 struct image
*image
,
3453 struct patch
*patch
, struct stat
*st
,
3454 const struct cache_entry
*ce
)
3456 struct strbuf buf
= STRBUF_INIT
;
3459 struct patch
*previous
;
3462 previous
= previous_patch(state
, patch
, &status
);
3464 return error(_("path %s has been renamed/deleted"),
3467 /* We have a patched copy in memory; use that. */
3468 strbuf_add(&buf
, previous
->result
, previous
->resultsize
);
3470 status
= load_patch_target(state
, &buf
, ce
, st
, patch
,
3471 patch
->old_name
, patch
->old_mode
);
3474 else if (status
== SUBMODULE_PATCH_WITHOUT_INDEX
) {
3476 * There is no way to apply subproject
3477 * patch without looking at the index.
3478 * NEEDSWORK: shouldn't this be flagged
3481 free_fragment_list(patch
->fragments
);
3482 patch
->fragments
= NULL
;
3483 } else if (status
) {
3484 return error(_("failed to read %s"), patch
->old_name
);
3488 img
= strbuf_detach(&buf
, &len
);
3489 prepare_image(image
, img
, len
, !patch
->is_binary
);
3493 static int resolve_to(struct image
*image
, const struct object_id
*result_id
)
3496 enum object_type type
;
3500 image
->buf
= read_object_file(result_id
, &type
, &size
);
3501 if (!image
->buf
|| type
!= OBJ_BLOB
)
3502 die("unable to read blob object %s", oid_to_hex(result_id
));
3508 static int three_way_merge(struct apply_state
*state
,
3509 struct image
*image
,
3511 const struct object_id
*base
,
3512 const struct object_id
*ours
,
3513 const struct object_id
*theirs
)
3515 mmfile_t base_file
, our_file
, their_file
;
3516 mmbuffer_t result
= { NULL
};
3517 enum ll_merge_result status
;
3519 /* resolve trivial cases first */
3520 if (oideq(base
, ours
))
3521 return resolve_to(image
, theirs
);
3522 else if (oideq(base
, theirs
) || oideq(ours
, theirs
))
3523 return resolve_to(image
, ours
);
3525 read_mmblob(&base_file
, base
);
3526 read_mmblob(&our_file
, ours
);
3527 read_mmblob(&their_file
, theirs
);
3528 status
= ll_merge(&result
, path
,
3531 &their_file
, "theirs",
3534 if (status
== LL_MERGE_BINARY_CONFLICT
)
3535 warning("Cannot merge binary files: %s (%s vs. %s)",
3536 path
, "ours", "theirs");
3537 free(base_file
.ptr
);
3539 free(their_file
.ptr
);
3540 if (status
< 0 || !result
.ptr
) {
3545 image
->buf
= result
.ptr
;
3546 image
->len
= result
.size
;
3552 * When directly falling back to add/add three-way merge, we read from
3553 * the current contents of the new_name. In no cases other than that
3554 * this function will be called.
3556 static int load_current(struct apply_state
*state
,
3557 struct image
*image
,
3558 struct patch
*patch
)
3560 struct strbuf buf
= STRBUF_INIT
;
3565 struct cache_entry
*ce
;
3566 char *name
= patch
->new_name
;
3567 unsigned mode
= patch
->new_mode
;
3570 BUG("patch to %s is not a creation", patch
->old_name
);
3572 pos
= index_name_pos(state
->repo
->index
, name
, strlen(name
));
3574 return error(_("%s: does not exist in index"), name
);
3575 ce
= state
->repo
->index
->cache
[pos
];
3576 if (lstat(name
, &st
)) {
3577 if (errno
!= ENOENT
)
3578 return error_errno("%s", name
);
3579 if (checkout_target(state
->repo
->index
, ce
, &st
))
3582 if (verify_index_match(state
, ce
, &st
))
3583 return error(_("%s: does not match index"), name
);
3585 status
= load_patch_target(state
, &buf
, ce
, &st
, patch
, name
, mode
);
3590 img
= strbuf_detach(&buf
, &len
);
3591 prepare_image(image
, img
, len
, !patch
->is_binary
);
3595 static int try_threeway(struct apply_state
*state
,
3596 struct image
*image
,
3597 struct patch
*patch
,
3599 const struct cache_entry
*ce
)
3601 struct object_id pre_oid
, post_oid
, our_oid
;
3602 struct strbuf buf
= STRBUF_INIT
;
3606 struct image tmp_image
;
3608 /* No point falling back to 3-way merge in these cases */
3609 if (patch
->is_delete
||
3610 S_ISGITLINK(patch
->old_mode
) || S_ISGITLINK(patch
->new_mode
) ||
3611 (patch
->is_new
&& !patch
->direct_to_threeway
) ||
3612 (patch
->is_rename
&& !patch
->lines_added
&& !patch
->lines_deleted
))
3615 /* Preimage the patch was prepared for */
3617 write_object_file("", 0, OBJ_BLOB
, &pre_oid
);
3618 else if (get_oid(patch
->old_oid_prefix
, &pre_oid
) ||
3619 read_blob_object(&buf
, &pre_oid
, patch
->old_mode
))
3620 return error(_("repository lacks the necessary blob to perform 3-way merge."));
3622 if (state
->apply_verbosity
> verbosity_silent
&& patch
->direct_to_threeway
)
3623 fprintf(stderr
, _("Performing three-way merge...\n"));
3625 img
= strbuf_detach(&buf
, &len
);
3626 prepare_image(&tmp_image
, img
, len
, 1);
3627 /* Apply the patch to get the post image */
3628 if (apply_fragments(state
, &tmp_image
, patch
) < 0) {
3629 clear_image(&tmp_image
);
3632 /* post_oid is theirs */
3633 write_object_file(tmp_image
.buf
, tmp_image
.len
, OBJ_BLOB
, &post_oid
);
3634 clear_image(&tmp_image
);
3636 /* our_oid is ours */
3637 if (patch
->is_new
) {
3638 if (load_current(state
, &tmp_image
, patch
))
3639 return error(_("cannot read the current contents of '%s'"),
3642 if (load_preimage(state
, &tmp_image
, patch
, st
, ce
))
3643 return error(_("cannot read the current contents of '%s'"),
3646 write_object_file(tmp_image
.buf
, tmp_image
.len
, OBJ_BLOB
, &our_oid
);
3647 clear_image(&tmp_image
);
3649 /* in-core three-way merge between post and our using pre as base */
3650 status
= three_way_merge(state
, image
, patch
->new_name
,
3651 &pre_oid
, &our_oid
, &post_oid
);
3653 if (state
->apply_verbosity
> verbosity_silent
)
3655 _("Failed to perform three-way merge...\n"));
3660 patch
->conflicted_threeway
= 1;
3662 oidclr(&patch
->threeway_stage
[0]);
3664 oidcpy(&patch
->threeway_stage
[0], &pre_oid
);
3665 oidcpy(&patch
->threeway_stage
[1], &our_oid
);
3666 oidcpy(&patch
->threeway_stage
[2], &post_oid
);
3667 if (state
->apply_verbosity
> verbosity_silent
)
3669 _("Applied patch to '%s' with conflicts.\n"),
3672 if (state
->apply_verbosity
> verbosity_silent
)
3674 _("Applied patch to '%s' cleanly.\n"),
3680 static int apply_data(struct apply_state
*state
, struct patch
*patch
,
3681 struct stat
*st
, const struct cache_entry
*ce
)
3685 if (load_preimage(state
, &image
, patch
, st
, ce
) < 0)
3688 if (!state
->threeway
|| try_threeway(state
, &image
, patch
, st
, ce
) < 0) {
3689 if (state
->apply_verbosity
> verbosity_silent
&&
3690 state
->threeway
&& !patch
->direct_to_threeway
)
3691 fprintf(stderr
, _("Falling back to direct application...\n"));
3693 /* Note: with --reject, apply_fragments() returns 0 */
3694 if (patch
->direct_to_threeway
|| apply_fragments(state
, &image
, patch
) < 0)
3697 patch
->result
= image
.buf
;
3698 patch
->resultsize
= image
.len
;
3699 add_to_fn_table(state
, patch
);
3700 free(image
.line_allocated
);
3702 if (0 < patch
->is_delete
&& patch
->resultsize
)
3703 return error(_("removal patch leaves file contents"));
3709 * If "patch" that we are looking at modifies or deletes what we have,
3710 * we would want it not to lose any local modification we have, either
3711 * in the working tree or in the index.
3713 * This also decides if a non-git patch is a creation patch or a
3714 * modification to an existing empty file. We do not check the state
3715 * of the current tree for a creation patch in this function; the caller
3716 * check_patch() separately makes sure (and errors out otherwise) that
3717 * the path the patch creates does not exist in the current tree.
3719 static int check_preimage(struct apply_state
*state
,
3720 struct patch
*patch
,
3721 struct cache_entry
**ce
,
3724 const char *old_name
= patch
->old_name
;
3725 struct patch
*previous
= NULL
;
3726 int stat_ret
= 0, status
;
3727 unsigned st_mode
= 0;
3732 assert(patch
->is_new
<= 0);
3733 previous
= previous_patch(state
, patch
, &status
);
3736 return error(_("path %s has been renamed/deleted"), old_name
);
3738 st_mode
= previous
->new_mode
;
3739 } else if (!state
->cached
) {
3740 stat_ret
= lstat(old_name
, st
);
3741 if (stat_ret
&& errno
!= ENOENT
)
3742 return error_errno("%s", old_name
);
3745 if (state
->check_index
&& !previous
) {
3746 int pos
= index_name_pos(state
->repo
->index
, old_name
,
3749 if (patch
->is_new
< 0)
3751 return error(_("%s: does not exist in index"), old_name
);
3753 *ce
= state
->repo
->index
->cache
[pos
];
3755 if (checkout_target(state
->repo
->index
, *ce
, st
))
3758 if (!state
->cached
&& verify_index_match(state
, *ce
, st
))
3759 return error(_("%s: does not match index"), old_name
);
3761 st_mode
= (*ce
)->ce_mode
;
3762 } else if (stat_ret
< 0) {
3763 if (patch
->is_new
< 0)
3765 return error_errno("%s", old_name
);
3768 if (!state
->cached
&& !previous
)
3769 st_mode
= ce_mode_from_stat(*ce
, st
->st_mode
);
3771 if (patch
->is_new
< 0)
3773 if (!patch
->old_mode
)
3774 patch
->old_mode
= st_mode
;
3775 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
3776 return error(_("%s: wrong type"), old_name
);
3777 if (st_mode
!= patch
->old_mode
)
3778 warning(_("%s has type %o, expected %o"),
3779 old_name
, st_mode
, patch
->old_mode
);
3780 if (!patch
->new_mode
&& !patch
->is_delete
)
3781 patch
->new_mode
= st_mode
;
3786 patch
->is_delete
= 0;
3787 FREE_AND_NULL(patch
->old_name
);
3792 #define EXISTS_IN_INDEX 1
3793 #define EXISTS_IN_WORKTREE 2
3794 #define EXISTS_IN_INDEX_AS_ITA 3
3796 static int check_to_create(struct apply_state
*state
,
3797 const char *new_name
,
3802 if (state
->check_index
&& (!ok_if_exists
|| !state
->cached
)) {
3805 pos
= index_name_pos(state
->repo
->index
, new_name
, strlen(new_name
));
3807 struct cache_entry
*ce
= state
->repo
->index
->cache
[pos
];
3809 /* allow ITA, as they do not yet exist in the index */
3810 if (!ok_if_exists
&& !(ce
->ce_flags
& CE_INTENT_TO_ADD
))
3811 return EXISTS_IN_INDEX
;
3813 /* ITA entries can never match working tree files */
3814 if (!state
->cached
&& (ce
->ce_flags
& CE_INTENT_TO_ADD
))
3815 return EXISTS_IN_INDEX_AS_ITA
;
3822 if (!lstat(new_name
, &nst
)) {
3823 if (S_ISDIR(nst
.st_mode
) || ok_if_exists
)
3826 * A leading component of new_name might be a symlink
3827 * that is going to be removed with this patch, but
3828 * still pointing at somewhere that has the path.
3829 * In such a case, path "new_name" does not exist as
3830 * far as git is concerned.
3832 if (has_symlink_leading_path(new_name
, strlen(new_name
)))
3835 return EXISTS_IN_WORKTREE
;
3836 } else if (!is_missing_file_error(errno
)) {
3837 return error_errno("%s", new_name
);
3842 static void prepare_symlink_changes(struct apply_state
*state
, struct patch
*patch
)
3844 for ( ; patch
; patch
= patch
->next
) {
3845 if ((patch
->old_name
&& S_ISLNK(patch
->old_mode
)) &&
3846 (patch
->is_rename
|| patch
->is_delete
))
3847 /* the symlink at patch->old_name is removed */
3848 strset_add(&state
->removed_symlinks
, patch
->old_name
);
3850 if (patch
->new_name
&& S_ISLNK(patch
->new_mode
))
3851 /* the symlink at patch->new_name is created or remains */
3852 strset_add(&state
->kept_symlinks
, patch
->new_name
);
3856 static int path_is_beyond_symlink_1(struct apply_state
*state
, struct strbuf
*name
)
3859 while (--name
->len
&& name
->buf
[name
->len
] != '/')
3860 ; /* scan backwards */
3863 name
->buf
[name
->len
] = '\0';
3864 if (strset_contains(&state
->kept_symlinks
, name
->buf
))
3866 if (strset_contains(&state
->removed_symlinks
, name
->buf
))
3868 * This cannot be "return 0", because we may
3869 * see a new one created at a higher level.
3873 /* otherwise, check the preimage */
3874 if (state
->check_index
) {
3875 struct cache_entry
*ce
;
3877 ce
= index_file_exists(state
->repo
->index
, name
->buf
,
3878 name
->len
, ignore_case
);
3879 if (ce
&& S_ISLNK(ce
->ce_mode
))
3883 if (!lstat(name
->buf
, &st
) && S_ISLNK(st
.st_mode
))
3890 static int path_is_beyond_symlink(struct apply_state
*state
, const char *name_
)
3893 struct strbuf name
= STRBUF_INIT
;
3895 assert(*name_
!= '\0');
3896 strbuf_addstr(&name
, name_
);
3897 ret
= path_is_beyond_symlink_1(state
, &name
);
3898 strbuf_release(&name
);
3903 static int check_unsafe_path(struct patch
*patch
)
3905 const char *old_name
= NULL
;
3906 const char *new_name
= NULL
;
3907 if (patch
->is_delete
)
3908 old_name
= patch
->old_name
;
3909 else if (!patch
->is_new
&& !patch
->is_copy
)
3910 old_name
= patch
->old_name
;
3911 if (!patch
->is_delete
)
3912 new_name
= patch
->new_name
;
3914 if (old_name
&& !verify_path(old_name
, patch
->old_mode
))
3915 return error(_("invalid path '%s'"), old_name
);
3916 if (new_name
&& !verify_path(new_name
, patch
->new_mode
))
3917 return error(_("invalid path '%s'"), new_name
);
3922 * Check and apply the patch in-core; leave the result in patch->result
3923 * for the caller to write it out to the final destination.
3925 static int check_patch(struct apply_state
*state
, struct patch
*patch
)
3928 const char *old_name
= patch
->old_name
;
3929 const char *new_name
= patch
->new_name
;
3930 const char *name
= old_name
? old_name
: new_name
;
3931 struct cache_entry
*ce
= NULL
;
3932 struct patch
*tpatch
;
3936 patch
->rejected
= 1; /* we will drop this after we succeed */
3938 status
= check_preimage(state
, patch
, &ce
, &st
);
3941 old_name
= patch
->old_name
;
3944 * A type-change diff is always split into a patch to delete
3945 * old, immediately followed by a patch to create new (see
3946 * diff.c::run_diff()); in such a case it is Ok that the entry
3947 * to be deleted by the previous patch is still in the working
3948 * tree and in the index.
3950 * A patch to swap-rename between A and B would first rename A
3951 * to B and then rename B to A. While applying the first one,
3952 * the presence of B should not stop A from getting renamed to
3953 * B; ask to_be_deleted() about the later rename. Removal of
3954 * B and rename from A to B is handled the same way by asking
3957 if ((tpatch
= in_fn_table(state
, new_name
)) &&
3958 (was_deleted(tpatch
) || to_be_deleted(tpatch
)))
3964 ((0 < patch
->is_new
) || patch
->is_rename
|| patch
->is_copy
)) {
3965 int err
= check_to_create(state
, new_name
, ok_if_exists
);
3967 if (err
&& state
->threeway
) {
3968 patch
->direct_to_threeway
= 1;
3969 } else switch (err
) {
3972 case EXISTS_IN_INDEX
:
3973 return error(_("%s: already exists in index"), new_name
);
3974 case EXISTS_IN_INDEX_AS_ITA
:
3975 return error(_("%s: does not match index"), new_name
);
3976 case EXISTS_IN_WORKTREE
:
3977 return error(_("%s: already exists in working directory"),
3983 if (!patch
->new_mode
) {
3984 if (0 < patch
->is_new
)
3985 patch
->new_mode
= S_IFREG
| 0644;
3987 patch
->new_mode
= patch
->old_mode
;
3991 if (new_name
&& old_name
) {
3992 int same
= !strcmp(old_name
, new_name
);
3993 if (!patch
->new_mode
)
3994 patch
->new_mode
= patch
->old_mode
;
3995 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
) {
3997 return error(_("new mode (%o) of %s does not "
3998 "match old mode (%o)"),
3999 patch
->new_mode
, new_name
,
4002 return error(_("new mode (%o) of %s does not "
4003 "match old mode (%o) of %s"),
4004 patch
->new_mode
, new_name
,
4005 patch
->old_mode
, old_name
);
4009 if (!state
->unsafe_paths
&& check_unsafe_path(patch
))
4013 * An attempt to read from or delete a path that is beyond a
4014 * symbolic link will be prevented by load_patch_target() that
4015 * is called at the beginning of apply_data() so we do not
4016 * have to worry about a patch marked with "is_delete" bit
4017 * here. We however need to make sure that the patch result
4018 * is not deposited to a path that is beyond a symbolic link
4021 if (!patch
->is_delete
&& path_is_beyond_symlink(state
, patch
->new_name
))
4022 return error(_("affected file '%s' is beyond a symbolic link"),
4025 if (apply_data(state
, patch
, &st
, ce
) < 0)
4026 return error(_("%s: patch does not apply"), name
);
4027 patch
->rejected
= 0;
4031 static int check_patch_list(struct apply_state
*state
, struct patch
*patch
)
4035 prepare_symlink_changes(state
, patch
);
4036 prepare_fn_table(state
, patch
);
4039 if (state
->apply_verbosity
> verbosity_normal
)
4040 say_patch_name(stderr
,
4041 _("Checking patch %s..."), patch
);
4042 res
= check_patch(state
, patch
);
4046 patch
= patch
->next
;
4051 static int read_apply_cache(struct apply_state
*state
)
4053 if (state
->index_file
)
4054 return read_index_from(state
->repo
->index
, state
->index_file
,
4057 return repo_read_index(state
->repo
);
4060 /* This function tries to read the object name from the current index */
4061 static int get_current_oid(struct apply_state
*state
, const char *path
,
4062 struct object_id
*oid
)
4066 if (read_apply_cache(state
) < 0)
4068 pos
= index_name_pos(state
->repo
->index
, path
, strlen(path
));
4071 oidcpy(oid
, &state
->repo
->index
->cache
[pos
]->oid
);
4075 static int preimage_oid_in_gitlink_patch(struct patch
*p
, struct object_id
*oid
)
4078 * A usable gitlink patch has only one fragment (hunk) that looks like:
4080 * -Subproject commit <old sha1>
4081 * +Subproject commit <new sha1>
4084 * -Subproject commit <old sha1>
4085 * for a removal patch.
4087 struct fragment
*hunk
= p
->fragments
;
4088 static const char heading
[] = "-Subproject commit ";
4091 if (/* does the patch have only one hunk? */
4092 hunk
&& !hunk
->next
&&
4093 /* is its preimage one line? */
4094 hunk
->oldpos
== 1 && hunk
->oldlines
== 1 &&
4095 /* does preimage begin with the heading? */
4096 (preimage
= memchr(hunk
->patch
, '\n', hunk
->size
)) != NULL
&&
4097 starts_with(++preimage
, heading
) &&
4098 /* does it record full SHA-1? */
4099 !get_oid_hex(preimage
+ sizeof(heading
) - 1, oid
) &&
4100 preimage
[sizeof(heading
) + the_hash_algo
->hexsz
- 1] == '\n' &&
4101 /* does the abbreviated name on the index line agree with it? */
4102 starts_with(preimage
+ sizeof(heading
) - 1, p
->old_oid_prefix
))
4103 return 0; /* it all looks fine */
4105 /* we may have full object name on the index line */
4106 return get_oid_hex(p
->old_oid_prefix
, oid
);
4109 /* Build an index that contains just the files needed for a 3way merge */
4110 static int build_fake_ancestor(struct apply_state
*state
, struct patch
*list
)
4112 struct patch
*patch
;
4113 struct index_state result
= INDEX_STATE_INIT(state
->repo
);
4114 struct lock_file lock
= LOCK_INIT
;
4117 /* Once we start supporting the reverse patch, it may be
4118 * worth showing the new sha1 prefix, but until then...
4120 for (patch
= list
; patch
; patch
= patch
->next
) {
4121 struct object_id oid
;
4122 struct cache_entry
*ce
;
4125 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
4126 if (0 < patch
->is_new
)
4129 if (S_ISGITLINK(patch
->old_mode
)) {
4130 if (!preimage_oid_in_gitlink_patch(patch
, &oid
))
4131 ; /* ok, the textual part looks sane */
4133 return error(_("sha1 information is lacking or "
4134 "useless for submodule %s"), name
);
4135 } else if (!get_oid_blob(patch
->old_oid_prefix
, &oid
)) {
4137 } else if (!patch
->lines_added
&& !patch
->lines_deleted
) {
4138 /* mode-only change: update the current */
4139 if (get_current_oid(state
, patch
->old_name
, &oid
))
4140 return error(_("mode change for %s, which is not "
4141 "in current HEAD"), name
);
4143 return error(_("sha1 information is lacking or useless "
4146 ce
= make_cache_entry(&result
, patch
->old_mode
, &oid
, name
, 0, 0);
4148 return error(_("make_cache_entry failed for path '%s'"),
4150 if (add_index_entry(&result
, ce
, ADD_CACHE_OK_TO_ADD
)) {
4151 discard_cache_entry(ce
);
4152 return error(_("could not add %s to temporary index"),
4157 hold_lock_file_for_update(&lock
, state
->fake_ancestor
, LOCK_DIE_ON_ERROR
);
4158 res
= write_locked_index(&result
, &lock
, COMMIT_LOCK
);
4159 discard_index(&result
);
4162 return error(_("could not write temporary index to %s"),
4163 state
->fake_ancestor
);
4168 static void stat_patch_list(struct apply_state
*state
, struct patch
*patch
)
4170 int files
, adds
, dels
;
4172 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
4174 adds
+= patch
->lines_added
;
4175 dels
+= patch
->lines_deleted
;
4176 show_stats(state
, patch
);
4179 print_stat_summary(stdout
, files
, adds
, dels
);
4182 static void numstat_patch_list(struct apply_state
*state
,
4183 struct patch
*patch
)
4185 for ( ; patch
; patch
= patch
->next
) {
4187 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
4188 if (patch
->is_binary
)
4191 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
4192 write_name_quoted(name
, stdout
, state
->line_termination
);
4196 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
4199 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
4201 printf(" %s %s\n", newdelete
, name
);
4204 static void show_mode_change(struct patch
*p
, int show_name
)
4206 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
4208 printf(" mode change %06o => %06o %s\n",
4209 p
->old_mode
, p
->new_mode
, p
->new_name
);
4211 printf(" mode change %06o => %06o\n",
4212 p
->old_mode
, p
->new_mode
);
4216 static void show_rename_copy(struct patch
*p
)
4218 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
4219 const char *old_name
, *new_name
;
4221 /* Find common prefix */
4222 old_name
= p
->old_name
;
4223 new_name
= p
->new_name
;
4225 const char *slash_old
, *slash_new
;
4226 slash_old
= strchr(old_name
, '/');
4227 slash_new
= strchr(new_name
, '/');
4230 slash_old
- old_name
!= slash_new
- new_name
||
4231 memcmp(old_name
, new_name
, slash_new
- new_name
))
4233 old_name
= slash_old
+ 1;
4234 new_name
= slash_new
+ 1;
4236 /* p->old_name through old_name is the common prefix, and old_name and
4237 * new_name through the end of names are renames
4239 if (old_name
!= p
->old_name
)
4240 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
4241 (int)(old_name
- p
->old_name
), p
->old_name
,
4242 old_name
, new_name
, p
->score
);
4244 printf(" %s %s => %s (%d%%)\n", renamecopy
,
4245 p
->old_name
, p
->new_name
, p
->score
);
4246 show_mode_change(p
, 0);
4249 static void summary_patch_list(struct patch
*patch
)
4253 for (p
= patch
; p
; p
= p
->next
) {
4255 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
4256 else if (p
->is_delete
)
4257 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
4259 if (p
->is_rename
|| p
->is_copy
)
4260 show_rename_copy(p
);
4263 printf(" rewrite %s (%d%%)\n",
4264 p
->new_name
, p
->score
);
4265 show_mode_change(p
, 0);
4268 show_mode_change(p
, 1);
4274 static void patch_stats(struct apply_state
*state
, struct patch
*patch
)
4276 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
4278 if (lines
> state
->max_change
)
4279 state
->max_change
= lines
;
4280 if (patch
->old_name
) {
4281 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
4283 len
= strlen(patch
->old_name
);
4284 if (len
> state
->max_len
)
4285 state
->max_len
= len
;
4287 if (patch
->new_name
) {
4288 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
4290 len
= strlen(patch
->new_name
);
4291 if (len
> state
->max_len
)
4292 state
->max_len
= len
;
4296 static int remove_file(struct apply_state
*state
, struct patch
*patch
, int rmdir_empty
)
4298 if (state
->update_index
&& !state
->ita_only
) {
4299 if (remove_file_from_index(state
->repo
->index
, patch
->old_name
) < 0)
4300 return error(_("unable to remove %s from index"), patch
->old_name
);
4302 if (!state
->cached
) {
4303 if (!remove_or_warn(patch
->old_mode
, patch
->old_name
) && rmdir_empty
) {
4304 remove_path(patch
->old_name
);
4310 static int add_index_file(struct apply_state
*state
,
4317 struct cache_entry
*ce
;
4318 int namelen
= strlen(path
);
4320 ce
= make_empty_cache_entry(state
->repo
->index
, namelen
);
4321 memcpy(ce
->name
, path
, namelen
);
4322 ce
->ce_mode
= create_ce_mode(mode
);
4323 ce
->ce_flags
= create_ce_flags(0);
4324 ce
->ce_namelen
= namelen
;
4325 if (state
->ita_only
) {
4326 ce
->ce_flags
|= CE_INTENT_TO_ADD
;
4327 set_object_name_for_intent_to_add_entry(ce
);
4328 } else if (S_ISGITLINK(mode
)) {
4331 if (!skip_prefix(buf
, "Subproject commit ", &s
) ||
4332 get_oid_hex(s
, &ce
->oid
)) {
4333 discard_cache_entry(ce
);
4334 return error(_("corrupt patch for submodule %s"), path
);
4337 if (!state
->cached
) {
4338 if (lstat(path
, &st
) < 0) {
4339 discard_cache_entry(ce
);
4340 return error_errno(_("unable to stat newly "
4341 "created file '%s'"),
4344 fill_stat_cache_info(state
->repo
->index
, ce
, &st
);
4346 if (write_object_file(buf
, size
, OBJ_BLOB
, &ce
->oid
) < 0) {
4347 discard_cache_entry(ce
);
4348 return error(_("unable to create backing store "
4349 "for newly created file %s"), path
);
4352 if (add_index_entry(state
->repo
->index
, ce
, ADD_CACHE_OK_TO_ADD
) < 0) {
4353 discard_cache_entry(ce
);
4354 return error(_("unable to add cache entry for %s"), path
);
4362 * -1 if an unrecoverable error happened
4363 * 0 if everything went well
4364 * 1 if a recoverable error happened
4366 static int try_create_file(struct apply_state
*state
, const char *path
,
4367 unsigned int mode
, const char *buf
,
4371 struct strbuf nbuf
= STRBUF_INIT
;
4373 if (S_ISGITLINK(mode
)) {
4375 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
))
4377 return !!mkdir(path
, 0777);
4380 if (has_symlinks
&& S_ISLNK(mode
))
4381 /* Although buf:size is counted string, it also is NUL
4384 return !!symlink(buf
, path
);
4386 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
4390 if (convert_to_working_tree(state
->repo
->index
, path
, buf
, size
, &nbuf
, NULL
)) {
4395 res
= write_in_full(fd
, buf
, size
) < 0;
4397 error_errno(_("failed to write to '%s'"), path
);
4398 strbuf_release(&nbuf
);
4400 if (close(fd
) < 0 && !res
)
4401 return error_errno(_("closing file '%s'"), path
);
4403 return res
? -1 : 0;
4407 * We optimistically assume that the directories exist,
4408 * which is true 99% of the time anyway. If they don't,
4409 * we create them and try again.
4415 static int create_one_file(struct apply_state
*state
,
4427 * We already try to detect whether files are beyond a symlink in our
4428 * up-front checks. But in the case where symlinks are created by any
4429 * of the intermediate hunks it can happen that our up-front checks
4430 * didn't yet see the symlink, but at the point of arriving here there
4431 * in fact is one. We thus repeat the check for symlinks here.
4433 * Note that this does not make the up-front check obsolete as the
4434 * failure mode is different:
4436 * - The up-front checks cause us to abort before we have written
4437 * anything into the working directory. So when we exit this way the
4438 * working directory remains clean.
4440 * - The checks here happen in the middle of the action where we have
4441 * already started to apply the patch. The end result will be a dirty
4442 * working directory.
4444 * Ideally, we should update the up-front checks to catch what would
4445 * happen when we apply the patch before we damage the working tree.
4446 * We have all the information necessary to do so. But for now, as a
4447 * part of embargoed security work, having this check would serve as a
4448 * reasonable first step.
4450 if (path_is_beyond_symlink(state
, path
))
4451 return error(_("affected file '%s' is beyond a symbolic link"), path
);
4453 res
= try_create_file(state
, path
, mode
, buf
, size
);
4459 if (errno
== ENOENT
) {
4460 if (safe_create_leading_directories_no_share(path
))
4462 res
= try_create_file(state
, path
, mode
, buf
, size
);
4469 if (errno
== EEXIST
|| errno
== EACCES
) {
4470 /* We may be trying to create a file where a directory
4474 if (!lstat(path
, &st
) && (!S_ISDIR(st
.st_mode
) || !rmdir(path
)))
4478 if (errno
== EEXIST
) {
4479 unsigned int nr
= getpid();
4482 char newpath
[PATH_MAX
];
4483 mksnpath(newpath
, sizeof(newpath
), "%s~%u", path
, nr
);
4484 res
= try_create_file(state
, newpath
, mode
, buf
, size
);
4488 if (!rename(newpath
, path
))
4490 unlink_or_warn(newpath
);
4493 if (errno
!= EEXIST
)
4498 return error_errno(_("unable to write file '%s' mode %o"),
4502 static int add_conflicted_stages_file(struct apply_state
*state
,
4503 struct patch
*patch
)
4507 struct cache_entry
*ce
;
4509 if (!state
->update_index
)
4511 namelen
= strlen(patch
->new_name
);
4512 mode
= patch
->new_mode
? patch
->new_mode
: (S_IFREG
| 0644);
4514 remove_file_from_index(state
->repo
->index
, patch
->new_name
);
4515 for (stage
= 1; stage
< 4; stage
++) {
4516 if (is_null_oid(&patch
->threeway_stage
[stage
- 1]))
4518 ce
= make_empty_cache_entry(state
->repo
->index
, namelen
);
4519 memcpy(ce
->name
, patch
->new_name
, namelen
);
4520 ce
->ce_mode
= create_ce_mode(mode
);
4521 ce
->ce_flags
= create_ce_flags(stage
);
4522 ce
->ce_namelen
= namelen
;
4523 oidcpy(&ce
->oid
, &patch
->threeway_stage
[stage
- 1]);
4524 if (add_index_entry(state
->repo
->index
, ce
, ADD_CACHE_OK_TO_ADD
) < 0) {
4525 discard_cache_entry(ce
);
4526 return error(_("unable to add cache entry for %s"),
4534 static int create_file(struct apply_state
*state
, struct patch
*patch
)
4536 char *path
= patch
->new_name
;
4537 unsigned mode
= patch
->new_mode
;
4538 unsigned long size
= patch
->resultsize
;
4539 char *buf
= patch
->result
;
4542 mode
= S_IFREG
| 0644;
4543 if (create_one_file(state
, path
, mode
, buf
, size
))
4546 if (patch
->conflicted_threeway
)
4547 return add_conflicted_stages_file(state
, patch
);
4548 else if (state
->update_index
)
4549 return add_index_file(state
, path
, mode
, buf
, size
);
4553 /* phase zero is to remove, phase one is to create */
4554 static int write_out_one_result(struct apply_state
*state
,
4555 struct patch
*patch
,
4558 if (patch
->is_delete
> 0) {
4560 return remove_file(state
, patch
, 1);
4563 if (patch
->is_new
> 0 || patch
->is_copy
) {
4565 return create_file(state
, patch
);
4569 * Rename or modification boils down to the same
4570 * thing: remove the old, write the new
4573 return remove_file(state
, patch
, patch
->is_rename
);
4575 return create_file(state
, patch
);
4579 static int write_out_one_reject(struct apply_state
*state
, struct patch
*patch
)
4582 char namebuf
[PATH_MAX
];
4583 struct fragment
*frag
;
4585 struct strbuf sb
= STRBUF_INIT
;
4587 for (cnt
= 0, frag
= patch
->fragments
; frag
; frag
= frag
->next
) {
4588 if (!frag
->rejected
)
4594 if (state
->apply_verbosity
> verbosity_normal
)
4595 say_patch_name(stderr
,
4596 _("Applied patch %s cleanly."), patch
);
4600 /* This should not happen, because a removal patch that leaves
4601 * contents are marked "rejected" at the patch level.
4603 if (!patch
->new_name
)
4604 die(_("internal error"));
4606 /* Say this even without --verbose */
4607 strbuf_addf(&sb
, Q_("Applying patch %%s with %d reject...",
4608 "Applying patch %%s with %d rejects...",
4611 if (state
->apply_verbosity
> verbosity_silent
)
4612 say_patch_name(stderr
, sb
.buf
, patch
);
4613 strbuf_release(&sb
);
4615 cnt
= strlen(patch
->new_name
);
4616 if (ARRAY_SIZE(namebuf
) <= cnt
+ 5) {
4617 cnt
= ARRAY_SIZE(namebuf
) - 5;
4618 warning(_("truncating .rej filename to %.*s.rej"),
4619 cnt
- 1, patch
->new_name
);
4621 memcpy(namebuf
, patch
->new_name
, cnt
);
4622 memcpy(namebuf
+ cnt
, ".rej", 5);
4624 rej
= fopen(namebuf
, "w");
4626 return error_errno(_("cannot open %s"), namebuf
);
4628 /* Normal git tools never deal with .rej, so do not pretend
4629 * this is a git patch by saying --git or giving extended
4630 * headers. While at it, maybe please "kompare" that wants
4631 * the trailing TAB and some garbage at the end of line ;-).
4633 fprintf(rej
, "diff a/%s b/%s\t(rejected hunks)\n",
4634 patch
->new_name
, patch
->new_name
);
4635 for (cnt
= 1, frag
= patch
->fragments
;
4637 cnt
++, frag
= frag
->next
) {
4638 if (!frag
->rejected
) {
4639 if (state
->apply_verbosity
> verbosity_silent
)
4640 fprintf_ln(stderr
, _("Hunk #%d applied cleanly."), cnt
);
4643 if (state
->apply_verbosity
> verbosity_silent
)
4644 fprintf_ln(stderr
, _("Rejected hunk #%d."), cnt
);
4645 fprintf(rej
, "%.*s", frag
->size
, frag
->patch
);
4646 if (frag
->patch
[frag
->size
-1] != '\n')
4655 * -1 if an error happened
4656 * 0 if the patch applied cleanly
4657 * 1 if the patch did not apply cleanly
4659 static int write_out_results(struct apply_state
*state
, struct patch
*list
)
4664 struct string_list cpath
= STRING_LIST_INIT_DUP
;
4666 for (phase
= 0; phase
< 2; phase
++) {
4672 if (write_out_one_result(state
, l
, phase
)) {
4673 string_list_clear(&cpath
, 0);
4677 if (write_out_one_reject(state
, l
))
4679 if (l
->conflicted_threeway
) {
4680 string_list_append(&cpath
, l
->new_name
);
4690 struct string_list_item
*item
;
4692 string_list_sort(&cpath
);
4693 if (state
->apply_verbosity
> verbosity_silent
) {
4694 for_each_string_list_item(item
, &cpath
)
4695 fprintf(stderr
, "U %s\n", item
->string
);
4697 string_list_clear(&cpath
, 0);
4700 * rerere relies on the partially merged result being in the working
4701 * tree with conflict markers, but that isn't written with --cached.
4704 repo_rerere(state
->repo
, 0);
4711 * Try to apply a patch.
4714 * -128 if a bad error happened (like patch unreadable)
4715 * -1 if patch did not apply and user cannot deal with it
4716 * 0 if the patch applied
4717 * 1 if the patch did not apply but user might fix it
4719 static int apply_patch(struct apply_state
*state
,
4721 const char *filename
,
4725 struct strbuf buf
= STRBUF_INIT
; /* owns the patch text */
4726 struct patch
*list
= NULL
, **listp
= &list
;
4727 int skipped_patch
= 0;
4729 int flush_attributes
= 0;
4731 state
->patch_input_file
= filename
;
4732 if (read_patch_file(&buf
, fd
) < 0)
4735 while (offset
< buf
.len
) {
4736 struct patch
*patch
;
4739 CALLOC_ARRAY(patch
, 1);
4740 patch
->inaccurate_eof
= !!(options
& APPLY_OPT_INACCURATE_EOF
);
4741 patch
->recount
= !!(options
& APPLY_OPT_RECOUNT
);
4742 nr
= parse_chunk(state
, buf
.buf
+ offset
, buf
.len
- offset
, patch
);
4751 if (state
->apply_in_reverse
)
4752 reverse_patches(patch
);
4753 if (use_patch(state
, patch
)) {
4754 patch_stats(state
, patch
);
4755 if (!list
|| !state
->apply_in_reverse
) {
4757 listp
= &patch
->next
;
4763 if ((patch
->new_name
&&
4764 ends_with_path_components(patch
->new_name
,
4765 GITATTRIBUTES_FILE
)) ||
4767 ends_with_path_components(patch
->old_name
,
4768 GITATTRIBUTES_FILE
)))
4769 flush_attributes
= 1;
4772 if (state
->apply_verbosity
> verbosity_normal
)
4773 say_patch_name(stderr
, _("Skipped patch '%s'."), patch
);
4780 if (!list
&& !skipped_patch
) {
4781 if (!state
->allow_empty
) {
4782 error(_("No valid patches in input (allow with \"--allow-empty\")"));
4788 if (state
->whitespace_error
&& (state
->ws_error_action
== die_on_ws_error
))
4791 state
->update_index
= (state
->check_index
|| state
->ita_only
) && state
->apply
;
4792 if (state
->update_index
&& !is_lock_file_locked(&state
->lock_file
)) {
4793 if (state
->index_file
)
4794 hold_lock_file_for_update(&state
->lock_file
,
4798 repo_hold_locked_index(state
->repo
, &state
->lock_file
,
4802 if (state
->check_index
&& read_apply_cache(state
) < 0) {
4803 error(_("unable to read index file"));
4808 if (state
->check
|| state
->apply
) {
4809 int r
= check_patch_list(state
, list
);
4814 if (r
< 0 && !state
->apply_with_reject
) {
4821 int write_res
= write_out_results(state
, list
);
4822 if (write_res
< 0) {
4826 if (write_res
> 0) {
4827 /* with --3way, we still need to write the index out */
4828 res
= state
->apply_with_reject
? -1 : 1;
4833 if (state
->fake_ancestor
&&
4834 build_fake_ancestor(state
, list
)) {
4839 if (state
->diffstat
&& state
->apply_verbosity
> verbosity_silent
)
4840 stat_patch_list(state
, list
);
4842 if (state
->numstat
&& state
->apply_verbosity
> verbosity_silent
)
4843 numstat_patch_list(state
, list
);
4845 if (state
->summary
&& state
->apply_verbosity
> verbosity_silent
)
4846 summary_patch_list(list
);
4848 if (flush_attributes
)
4849 reset_parsed_attributes();
4851 free_patch_list(list
);
4852 strbuf_release(&buf
);
4853 string_list_clear(&state
->fn_table
, 0);
4857 static int apply_option_parse_exclude(const struct option
*opt
,
4858 const char *arg
, int unset
)
4860 struct apply_state
*state
= opt
->value
;
4862 BUG_ON_OPT_NEG(unset
);
4864 add_name_limit(state
, arg
, 1);
4868 static int apply_option_parse_include(const struct option
*opt
,
4869 const char *arg
, int unset
)
4871 struct apply_state
*state
= opt
->value
;
4873 BUG_ON_OPT_NEG(unset
);
4875 add_name_limit(state
, arg
, 0);
4876 state
->has_include
= 1;
4880 static int apply_option_parse_p(const struct option
*opt
,
4884 struct apply_state
*state
= opt
->value
;
4886 BUG_ON_OPT_NEG(unset
);
4888 state
->p_value
= atoi(arg
);
4889 state
->p_value_known
= 1;
4893 static int apply_option_parse_space_change(const struct option
*opt
,
4894 const char *arg
, int unset
)
4896 struct apply_state
*state
= opt
->value
;
4898 BUG_ON_OPT_ARG(arg
);
4901 state
->ws_ignore_action
= ignore_ws_none
;
4903 state
->ws_ignore_action
= ignore_ws_change
;
4907 static int apply_option_parse_whitespace(const struct option
*opt
,
4908 const char *arg
, int unset
)
4910 struct apply_state
*state
= opt
->value
;
4912 BUG_ON_OPT_NEG(unset
);
4914 state
->whitespace_option
= arg
;
4915 if (parse_whitespace_option(state
, arg
))
4920 static int apply_option_parse_directory(const struct option
*opt
,
4921 const char *arg
, int unset
)
4923 struct apply_state
*state
= opt
->value
;
4925 BUG_ON_OPT_NEG(unset
);
4927 strbuf_reset(&state
->root
);
4928 strbuf_addstr(&state
->root
, arg
);
4929 strbuf_complete(&state
->root
, '/');
4933 int apply_all_patches(struct apply_state
*state
,
4943 for (i
= 0; i
< argc
; i
++) {
4944 const char *arg
= argv
[i
];
4945 char *to_free
= NULL
;
4948 if (!strcmp(arg
, "-")) {
4949 res
= apply_patch(state
, 0, "<stdin>", options
);
4956 arg
= to_free
= prefix_filename(state
->prefix
, arg
);
4958 fd
= open(arg
, O_RDONLY
);
4960 error(_("can't open patch '%s': %s"), arg
, strerror(errno
));
4966 set_default_whitespace_mode(state
);
4967 res
= apply_patch(state
, fd
, arg
, options
);
4974 set_default_whitespace_mode(state
);
4976 res
= apply_patch(state
, 0, "<stdin>", options
);
4982 if (state
->whitespace_error
) {
4983 if (state
->squelch_whitespace_errors
&&
4984 state
->squelch_whitespace_errors
< state
->whitespace_error
) {
4986 state
->whitespace_error
- state
->squelch_whitespace_errors
;
4987 warning(Q_("squelched %d whitespace error",
4988 "squelched %d whitespace errors",
4992 if (state
->ws_error_action
== die_on_ws_error
) {
4993 error(Q_("%d line adds whitespace errors.",
4994 "%d lines add whitespace errors.",
4995 state
->whitespace_error
),
4996 state
->whitespace_error
);
5000 if (state
->applied_after_fixing_ws
&& state
->apply
)
5001 warning(Q_("%d line applied after"
5002 " fixing whitespace errors.",
5003 "%d lines applied after"
5004 " fixing whitespace errors.",
5005 state
->applied_after_fixing_ws
),
5006 state
->applied_after_fixing_ws
);
5007 else if (state
->whitespace_error
)
5008 warning(Q_("%d line adds whitespace errors.",
5009 "%d lines add whitespace errors.",
5010 state
->whitespace_error
),
5011 state
->whitespace_error
);
5014 if (state
->update_index
) {
5015 res
= write_locked_index(state
->repo
->index
, &state
->lock_file
, COMMIT_LOCK
);
5017 error(_("Unable to write new index file"));
5026 rollback_lock_file(&state
->lock_file
);
5028 if (state
->apply_verbosity
<= verbosity_silent
) {
5029 set_error_routine(state
->saved_error_routine
);
5030 set_warn_routine(state
->saved_warn_routine
);
5035 return (res
== -1 ? 1 : 128);
5038 int apply_parse_options(int argc
, const char **argv
,
5039 struct apply_state
*state
,
5040 int *force_apply
, int *options
,
5041 const char * const *apply_usage
)
5043 struct option builtin_apply_options
[] = {
5044 OPT_CALLBACK_F(0, "exclude", state
, N_("path"),
5045 N_("don't apply changes matching the given path"),
5046 PARSE_OPT_NONEG
, apply_option_parse_exclude
),
5047 OPT_CALLBACK_F(0, "include", state
, N_("path"),
5048 N_("apply changes matching the given path"),
5049 PARSE_OPT_NONEG
, apply_option_parse_include
),
5050 OPT_CALLBACK('p', NULL
, state
, N_("num"),
5051 N_("remove <num> leading slashes from traditional diff paths"),
5052 apply_option_parse_p
),
5053 OPT_BOOL(0, "no-add", &state
->no_add
,
5054 N_("ignore additions made by the patch")),
5055 OPT_BOOL(0, "stat", &state
->diffstat
,
5056 N_("instead of applying the patch, output diffstat for the input")),
5057 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
5058 OPT_NOOP_NOARG(0, "binary"),
5059 OPT_BOOL(0, "numstat", &state
->numstat
,
5060 N_("show number of added and deleted lines in decimal notation")),
5061 OPT_BOOL(0, "summary", &state
->summary
,
5062 N_("instead of applying the patch, output a summary for the input")),
5063 OPT_BOOL(0, "check", &state
->check
,
5064 N_("instead of applying the patch, see if the patch is applicable")),
5065 OPT_BOOL(0, "index", &state
->check_index
,
5066 N_("make sure the patch is applicable to the current index")),
5067 OPT_BOOL('N', "intent-to-add", &state
->ita_only
,
5068 N_("mark new files with `git add --intent-to-add`")),
5069 OPT_BOOL(0, "cached", &state
->cached
,
5070 N_("apply a patch without touching the working tree")),
5071 OPT_BOOL_F(0, "unsafe-paths", &state
->unsafe_paths
,
5072 N_("accept a patch that touches outside the working area"),
5073 PARSE_OPT_NOCOMPLETE
),
5074 OPT_BOOL(0, "apply", force_apply
,
5075 N_("also apply the patch (use with --stat/--summary/--check)")),
5076 OPT_BOOL('3', "3way", &state
->threeway
,
5077 N_( "attempt three-way merge, fall back on normal patch if that fails")),
5078 OPT_FILENAME(0, "build-fake-ancestor", &state
->fake_ancestor
,
5079 N_("build a temporary index based on embedded index information")),
5080 /* Think twice before adding "--nul" synonym to this */
5081 OPT_SET_INT('z', NULL
, &state
->line_termination
,
5082 N_("paths are separated with NUL character"), '\0'),
5083 OPT_INTEGER('C', NULL
, &state
->p_context
,
5084 N_("ensure at least <n> lines of context match")),
5085 OPT_CALLBACK(0, "whitespace", state
, N_("action"),
5086 N_("detect new or modified lines that have whitespace errors"),
5087 apply_option_parse_whitespace
),
5088 OPT_CALLBACK_F(0, "ignore-space-change", state
, NULL
,
5089 N_("ignore changes in whitespace when finding context"),
5090 PARSE_OPT_NOARG
, apply_option_parse_space_change
),
5091 OPT_CALLBACK_F(0, "ignore-whitespace", state
, NULL
,
5092 N_("ignore changes in whitespace when finding context"),
5093 PARSE_OPT_NOARG
, apply_option_parse_space_change
),
5094 OPT_BOOL('R', "reverse", &state
->apply_in_reverse
,
5095 N_("apply the patch in reverse")),
5096 OPT_BOOL(0, "unidiff-zero", &state
->unidiff_zero
,
5097 N_("don't expect at least one line of context")),
5098 OPT_BOOL(0, "reject", &state
->apply_with_reject
,
5099 N_("leave the rejected hunks in corresponding *.rej files")),
5100 OPT_BOOL(0, "allow-overlap", &state
->allow_overlap
,
5101 N_("allow overlapping hunks")),
5102 OPT__VERBOSITY(&state
->apply_verbosity
),
5103 OPT_BIT(0, "inaccurate-eof", options
,
5104 N_("tolerate incorrectly detected missing new-line at the end of file"),
5105 APPLY_OPT_INACCURATE_EOF
),
5106 OPT_BIT(0, "recount", options
,
5107 N_("do not trust the line counts in the hunk headers"),
5109 OPT_CALLBACK(0, "directory", state
, N_("root"),
5110 N_("prepend <root> to all filenames"),
5111 apply_option_parse_directory
),
5112 OPT_BOOL(0, "allow-empty", &state
->allow_empty
,
5113 N_("don't return error for empty patches")),
5117 return parse_options(argc
, argv
, state
->prefix
, builtin_apply_options
, apply_usage
, 0);