4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
12 #include "object-store.h"
17 #include "xdiff-interface.h"
20 #include "parse-options.h"
31 static void git_apply_config(void)
33 git_config_get_string_const("apply.whitespace", &apply_default_whitespace
);
34 git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace
);
35 git_config(git_xmerge_config
, NULL
);
38 static int parse_whitespace_option(struct apply_state
*state
, const char *option
)
41 state
->ws_error_action
= warn_on_ws_error
;
44 if (!strcmp(option
, "warn")) {
45 state
->ws_error_action
= warn_on_ws_error
;
48 if (!strcmp(option
, "nowarn")) {
49 state
->ws_error_action
= nowarn_ws_error
;
52 if (!strcmp(option
, "error")) {
53 state
->ws_error_action
= die_on_ws_error
;
56 if (!strcmp(option
, "error-all")) {
57 state
->ws_error_action
= die_on_ws_error
;
58 state
->squelch_whitespace_errors
= 0;
61 if (!strcmp(option
, "strip") || !strcmp(option
, "fix")) {
62 state
->ws_error_action
= correct_ws_error
;
66 * Please update $__git_whitespacelist in git-completion.bash
67 * when you add new options.
69 return error(_("unrecognized whitespace option '%s'"), option
);
72 static int parse_ignorewhitespace_option(struct apply_state
*state
,
75 if (!option
|| !strcmp(option
, "no") ||
76 !strcmp(option
, "false") || !strcmp(option
, "never") ||
77 !strcmp(option
, "none")) {
78 state
->ws_ignore_action
= ignore_ws_none
;
81 if (!strcmp(option
, "change")) {
82 state
->ws_ignore_action
= ignore_ws_change
;
85 return error(_("unrecognized whitespace ignore option '%s'"), option
);
88 int init_apply_state(struct apply_state
*state
,
89 struct repository
*repo
,
92 memset(state
, 0, sizeof(*state
));
93 state
->prefix
= prefix
;
96 state
->line_termination
= '\n';
98 state
->p_context
= UINT_MAX
;
99 state
->squelch_whitespace_errors
= 5;
100 state
->ws_error_action
= warn_on_ws_error
;
101 state
->ws_ignore_action
= ignore_ws_none
;
103 string_list_init(&state
->fn_table
, 0);
104 string_list_init(&state
->limit_by_name
, 0);
105 string_list_init(&state
->symlink_changes
, 0);
106 strbuf_init(&state
->root
, 0);
109 if (apply_default_whitespace
&& parse_whitespace_option(state
, apply_default_whitespace
))
111 if (apply_default_ignorewhitespace
&& parse_ignorewhitespace_option(state
, apply_default_ignorewhitespace
))
116 void clear_apply_state(struct apply_state
*state
)
118 string_list_clear(&state
->limit_by_name
, 0);
119 string_list_clear(&state
->symlink_changes
, 0);
120 strbuf_release(&state
->root
);
122 /* &state->fn_table is cleared at the end of apply_patch() */
125 static void mute_routine(const char *msg
, va_list params
)
130 int check_apply_state(struct apply_state
*state
, int force_apply
)
132 int is_not_gitdir
= !startup_info
->have_repository
;
134 if (state
->apply_with_reject
&& state
->threeway
)
135 return error(_("--reject and --3way cannot be used together."));
136 if (state
->cached
&& state
->threeway
)
137 return error(_("--cached and --3way cannot be used together."));
138 if (state
->threeway
) {
140 return error(_("--3way outside a repository"));
141 state
->check_index
= 1;
143 if (state
->apply_with_reject
) {
145 if (state
->apply_verbosity
== verbosity_normal
)
146 state
->apply_verbosity
= verbosity_verbose
;
148 if (!force_apply
&& (state
->diffstat
|| state
->numstat
|| state
->summary
|| state
->check
|| state
->fake_ancestor
))
150 if (state
->check_index
&& is_not_gitdir
)
151 return error(_("--index outside a repository"));
154 return error(_("--cached outside a repository"));
155 state
->check_index
= 1;
157 if (state
->ita_only
&& (state
->check_index
|| is_not_gitdir
))
159 if (state
->check_index
)
160 state
->unsafe_paths
= 0;
162 if (state
->apply_verbosity
<= verbosity_silent
) {
163 state
->saved_error_routine
= get_error_routine();
164 state
->saved_warn_routine
= get_warn_routine();
165 set_error_routine(mute_routine
);
166 set_warn_routine(mute_routine
);
172 static void set_default_whitespace_mode(struct apply_state
*state
)
174 if (!state
->whitespace_option
&& !apply_default_whitespace
)
175 state
->ws_error_action
= (state
->apply
? warn_on_ws_error
: nowarn_ws_error
);
179 * This represents one "hunk" from a patch, starting with
180 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
181 * patch text is pointed at by patch, and its byte length
182 * is stored in size. leading and trailing are the number
186 unsigned long leading
, trailing
;
187 unsigned long oldpos
, oldlines
;
188 unsigned long newpos
, newlines
;
190 * 'patch' is usually borrowed from buf in apply_patch(),
191 * but some codepaths store an allocated buffer.
194 unsigned free_patch
:1,
198 struct fragment
*next
;
202 * When dealing with a binary patch, we reuse "leading" field
203 * to store the type of the binary hunk, either deflated "delta"
204 * or deflated "literal".
206 #define binary_patch_method leading
207 #define BINARY_DELTA_DEFLATED 1
208 #define BINARY_LITERAL_DEFLATED 2
210 static void free_fragment_list(struct fragment
*list
)
213 struct fragment
*next
= list
->next
;
214 if (list
->free_patch
)
215 free((char *)list
->patch
);
221 static void free_patch(struct patch
*patch
)
223 free_fragment_list(patch
->fragments
);
224 free(patch
->def_name
);
225 free(patch
->old_name
);
226 free(patch
->new_name
);
231 static void free_patch_list(struct patch
*list
)
234 struct patch
*next
= list
->next
;
241 * A line in a file, len-bytes long (includes the terminating LF,
242 * except for an incomplete line at the end if the file ends with
243 * one), and its contents hashes to 'hash'.
249 #define LINE_COMMON 1
250 #define LINE_PATCHED 2
254 * This represents a "file", which is an array of "lines".
261 struct line
*line_allocated
;
265 static uint32_t hash_line(const char *cp
, size_t len
)
269 for (i
= 0, h
= 0; i
< len
; i
++) {
270 if (!isspace(cp
[i
])) {
271 h
= h
* 3 + (cp
[i
] & 0xff);
278 * Compare lines s1 of length n1 and s2 of length n2, ignoring
279 * whitespace difference. Returns 1 if they match, 0 otherwise
281 static int fuzzy_matchlines(const char *s1
, size_t n1
,
282 const char *s2
, size_t n2
)
284 const char *end1
= s1
+ n1
;
285 const char *end2
= s2
+ n2
;
287 /* ignore line endings */
288 while (s1
< end1
&& (end1
[-1] == '\r' || end1
[-1] == '\n'))
290 while (s2
< end2
&& (end2
[-1] == '\r' || end2
[-1] == '\n'))
293 while (s1
< end1
&& s2
< end2
) {
296 * Skip whitespace. We check on both buffers
297 * because we don't want "a b" to match "ab".
301 while (s1
< end1
&& isspace(*s1
))
303 while (s2
< end2
&& isspace(*s2
))
305 } else if (*s1
++ != *s2
++)
309 /* If we reached the end on one side only, lines don't match. */
310 return s1
== end1
&& s2
== end2
;
313 static void add_line_info(struct image
*img
, const char *bol
, size_t len
, unsigned flag
)
315 ALLOC_GROW(img
->line_allocated
, img
->nr
+ 1, img
->alloc
);
316 img
->line_allocated
[img
->nr
].len
= len
;
317 img
->line_allocated
[img
->nr
].hash
= hash_line(bol
, len
);
318 img
->line_allocated
[img
->nr
].flag
= flag
;
323 * "buf" has the file contents to be patched (read from various sources).
324 * attach it to "image" and add line-based index to it.
325 * "image" now owns the "buf".
327 static void prepare_image(struct image
*image
, char *buf
, size_t len
,
328 int prepare_linetable
)
332 memset(image
, 0, sizeof(*image
));
336 if (!prepare_linetable
)
339 ep
= image
->buf
+ image
->len
;
343 for (next
= cp
; next
< ep
&& *next
!= '\n'; next
++)
347 add_line_info(image
, cp
, next
- cp
, 0);
350 image
->line
= image
->line_allocated
;
353 static void clear_image(struct image
*image
)
356 free(image
->line_allocated
);
357 memset(image
, 0, sizeof(*image
));
360 /* fmt must contain _one_ %s and no other substitution */
361 static void say_patch_name(FILE *output
, const char *fmt
, struct patch
*patch
)
363 struct strbuf sb
= STRBUF_INIT
;
365 if (patch
->old_name
&& patch
->new_name
&&
366 strcmp(patch
->old_name
, patch
->new_name
)) {
367 quote_c_style(patch
->old_name
, &sb
, NULL
, 0);
368 strbuf_addstr(&sb
, " => ");
369 quote_c_style(patch
->new_name
, &sb
, NULL
, 0);
371 const char *n
= patch
->new_name
;
374 quote_c_style(n
, &sb
, NULL
, 0);
376 fprintf(output
, fmt
, sb
.buf
);
383 static int read_patch_file(struct strbuf
*sb
, int fd
)
385 if (strbuf_read(sb
, fd
, 0) < 0)
386 return error_errno("git apply: failed to read");
389 * Make sure that we have some slop in the buffer
390 * so that we can do speculative "memcmp" etc, and
391 * see to it that it is NUL-filled.
393 strbuf_grow(sb
, SLOP
);
394 memset(sb
->buf
+ sb
->len
, 0, SLOP
);
398 static unsigned long linelen(const char *buffer
, unsigned long size
)
400 unsigned long len
= 0;
403 if (*buffer
++ == '\n')
409 static int is_dev_null(const char *str
)
411 return skip_prefix(str
, "/dev/null", &str
) && isspace(*str
);
417 static int name_terminate(int c
, int terminate
)
419 if (c
== ' ' && !(terminate
& TERM_SPACE
))
421 if (c
== '\t' && !(terminate
& TERM_TAB
))
427 /* remove double slashes to make --index work with such filenames */
428 static char *squash_slash(char *name
)
436 if ((name
[j
++] = name
[i
++]) == '/')
437 while (name
[i
] == '/')
444 static char *find_name_gnu(struct strbuf
*root
,
448 struct strbuf name
= STRBUF_INIT
;
452 * Proposed "new-style" GNU patch/diff format; see
453 * https://lore.kernel.org/git/7vll0wvb2a.fsf@assigned-by-dhcp.cox.net/
455 if (unquote_c_style(&name
, line
, NULL
)) {
456 strbuf_release(&name
);
460 for (cp
= name
.buf
; p_value
; p_value
--) {
461 cp
= strchr(cp
, '/');
463 strbuf_release(&name
);
469 strbuf_remove(&name
, 0, cp
- name
.buf
);
471 strbuf_insert(&name
, 0, root
->buf
, root
->len
);
472 return squash_slash(strbuf_detach(&name
, NULL
));
475 static size_t sane_tz_len(const char *line
, size_t len
)
479 if (len
< strlen(" +0500") || line
[len
-strlen(" +0500")] != ' ')
481 tz
= line
+ len
- strlen(" +0500");
483 if (tz
[1] != '+' && tz
[1] != '-')
486 for (p
= tz
+ 2; p
!= line
+ len
; p
++)
490 return line
+ len
- tz
;
493 static size_t tz_with_colon_len(const char *line
, size_t len
)
497 if (len
< strlen(" +08:00") || line
[len
- strlen(":00")] != ':')
499 tz
= line
+ len
- strlen(" +08:00");
501 if (tz
[0] != ' ' || (tz
[1] != '+' && tz
[1] != '-'))
504 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
505 !isdigit(*p
++) || !isdigit(*p
++))
508 return line
+ len
- tz
;
511 static size_t date_len(const char *line
, size_t len
)
513 const char *date
, *p
;
515 if (len
< strlen("72-02-05") || line
[len
-strlen("-05")] != '-')
517 p
= date
= line
+ len
- strlen("72-02-05");
519 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
520 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
521 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a date. */
524 if (date
- line
>= strlen("19") &&
525 isdigit(date
[-1]) && isdigit(date
[-2])) /* 4-digit year */
526 date
-= strlen("19");
528 return line
+ len
- date
;
531 static size_t short_time_len(const char *line
, size_t len
)
533 const char *time
, *p
;
535 if (len
< strlen(" 07:01:32") || line
[len
-strlen(":32")] != ':')
537 p
= time
= line
+ len
- strlen(" 07:01:32");
539 /* Permit 1-digit hours? */
541 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
542 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
543 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a time. */
546 return line
+ len
- time
;
549 static size_t fractional_time_len(const char *line
, size_t len
)
554 /* Expected format: 19:41:17.620000023 */
555 if (!len
|| !isdigit(line
[len
- 1]))
559 /* Fractional seconds. */
560 while (p
> line
&& isdigit(*p
))
565 /* Hours, minutes, and whole seconds. */
566 n
= short_time_len(line
, p
- line
);
570 return line
+ len
- p
+ n
;
573 static size_t trailing_spaces_len(const char *line
, size_t len
)
577 /* Expected format: ' ' x (1 or more) */
578 if (!len
|| line
[len
- 1] != ' ')
585 return line
+ len
- (p
+ 1);
592 static size_t diff_timestamp_len(const char *line
, size_t len
)
594 const char *end
= line
+ len
;
598 * Posix: 2010-07-05 19:41:17
599 * GNU: 2010-07-05 19:41:17.620000023 -0500
602 if (!isdigit(end
[-1]))
605 n
= sane_tz_len(line
, end
- line
);
607 n
= tz_with_colon_len(line
, end
- line
);
610 n
= short_time_len(line
, end
- line
);
612 n
= fractional_time_len(line
, end
- line
);
615 n
= date_len(line
, end
- line
);
616 if (!n
) /* No date. Too bad. */
620 if (end
== line
) /* No space before date. */
622 if (end
[-1] == '\t') { /* Success! */
624 return line
+ len
- end
;
626 if (end
[-1] != ' ') /* No space before date. */
629 /* Whitespace damage. */
630 end
-= trailing_spaces_len(line
, end
- line
);
631 return line
+ len
- end
;
634 static char *find_name_common(struct strbuf
*root
,
642 const char *start
= NULL
;
646 while (line
!= end
) {
649 if (!end
&& isspace(c
)) {
652 if (name_terminate(c
, terminate
))
656 if (c
== '/' && !--p_value
)
660 return squash_slash(xstrdup_or_null(def
));
663 return squash_slash(xstrdup_or_null(def
));
666 * Generally we prefer the shorter name, especially
667 * if the other one is just a variation of that with
668 * something else tacked on to the end (ie "file.orig"
672 int deflen
= strlen(def
);
673 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
674 return squash_slash(xstrdup(def
));
678 char *ret
= xstrfmt("%s%.*s", root
->buf
, len
, start
);
679 return squash_slash(ret
);
682 return squash_slash(xmemdupz(start
, len
));
685 static char *find_name(struct strbuf
*root
,
692 char *name
= find_name_gnu(root
, line
, p_value
);
697 return find_name_common(root
, line
, def
, p_value
, NULL
, terminate
);
700 static char *find_name_traditional(struct strbuf
*root
,
709 char *name
= find_name_gnu(root
, line
, p_value
);
714 len
= strchrnul(line
, '\n') - line
;
715 date_len
= diff_timestamp_len(line
, len
);
717 return find_name_common(root
, line
, def
, p_value
, NULL
, TERM_TAB
);
720 return find_name_common(root
, line
, def
, p_value
, line
+ len
, 0);
724 * Given the string after "--- " or "+++ ", guess the appropriate
725 * p_value for the given patch.
727 static int guess_p_value(struct apply_state
*state
, const char *nameline
)
732 if (is_dev_null(nameline
))
734 name
= find_name_traditional(&state
->root
, nameline
, NULL
, 0);
737 cp
= strchr(name
, '/');
740 else if (state
->prefix
) {
742 * Does it begin with "a/$our-prefix" and such? Then this is
743 * very likely to apply to our directory.
745 if (starts_with(name
, state
->prefix
))
746 val
= count_slashes(state
->prefix
);
749 if (starts_with(cp
, state
->prefix
))
750 val
= count_slashes(state
->prefix
) + 1;
758 * Does the ---/+++ line have the POSIX timestamp after the last HT?
759 * GNU diff puts epoch there to signal a creation/deletion event. Is
760 * this such a timestamp?
762 static int has_epoch_timestamp(const char *nameline
)
765 * We are only interested in epoch timestamp; any non-zero
766 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
767 * For the same reason, the date must be either 1969-12-31 or
768 * 1970-01-01, and the seconds part must be "00".
770 const char stamp_regexp
[] =
771 "^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?"
773 "([-+][0-2][0-9]:?[0-5][0-9])\n";
774 const char *timestamp
= NULL
, *cp
, *colon
;
775 static regex_t
*stamp
;
777 int zoneoffset
, epoch_hour
, hour
, minute
;
780 for (cp
= nameline
; *cp
!= '\n'; cp
++) {
788 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
789 * (west of GMT) or 1970-01-01 (east of GMT)
791 if (skip_prefix(timestamp
, "1969-12-31 ", ×tamp
))
793 else if (skip_prefix(timestamp
, "1970-01-01 ", ×tamp
))
799 stamp
= xmalloc(sizeof(*stamp
));
800 if (regcomp(stamp
, stamp_regexp
, REG_EXTENDED
)) {
801 warning(_("Cannot prepare timestamp regexp %s"),
807 status
= regexec(stamp
, timestamp
, ARRAY_SIZE(m
), m
, 0);
809 if (status
!= REG_NOMATCH
)
810 warning(_("regexec returned %d for input: %s"),
815 hour
= strtol(timestamp
, NULL
, 10);
816 minute
= strtol(timestamp
+ m
[1].rm_so
, NULL
, 10);
818 zoneoffset
= strtol(timestamp
+ m
[3].rm_so
+ 1, (char **) &colon
, 10);
820 zoneoffset
= zoneoffset
* 60 + strtol(colon
+ 1, NULL
, 10);
822 zoneoffset
= (zoneoffset
/ 100) * 60 + (zoneoffset
% 100);
823 if (timestamp
[m
[3].rm_so
] == '-')
824 zoneoffset
= -zoneoffset
;
826 return hour
* 60 + minute
- zoneoffset
== epoch_hour
* 60;
830 * Get the name etc info from the ---/+++ lines of a traditional patch header
832 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
833 * files, we can happily check the index for a match, but for creating a
834 * new file we should try to match whatever "patch" does. I have no idea.
836 static int parse_traditional_patch(struct apply_state
*state
,
843 first
+= 4; /* skip "--- " */
844 second
+= 4; /* skip "+++ " */
845 if (!state
->p_value_known
) {
847 p
= guess_p_value(state
, first
);
848 q
= guess_p_value(state
, second
);
850 if (0 <= p
&& p
== q
) {
852 state
->p_value_known
= 1;
855 if (is_dev_null(first
)) {
857 patch
->is_delete
= 0;
858 name
= find_name_traditional(&state
->root
, second
, NULL
, state
->p_value
);
859 patch
->new_name
= name
;
860 } else if (is_dev_null(second
)) {
862 patch
->is_delete
= 1;
863 name
= find_name_traditional(&state
->root
, first
, NULL
, state
->p_value
);
864 patch
->old_name
= name
;
867 first_name
= find_name_traditional(&state
->root
, first
, NULL
, state
->p_value
);
868 name
= find_name_traditional(&state
->root
, second
, first_name
, state
->p_value
);
870 if (has_epoch_timestamp(first
)) {
872 patch
->is_delete
= 0;
873 patch
->new_name
= name
;
874 } else if (has_epoch_timestamp(second
)) {
876 patch
->is_delete
= 1;
877 patch
->old_name
= name
;
879 patch
->old_name
= name
;
880 patch
->new_name
= xstrdup_or_null(name
);
884 return error(_("unable to find filename in patch at line %d"), state
->linenr
);
889 static int gitdiff_hdrend(struct gitdiff_data
*state
,
897 * We're anal about diff header consistency, to make
898 * sure that we don't end up having strange ambiguous
899 * patches floating around.
901 * As a result, gitdiff_{old|new}name() will check
902 * their names against any previous information, just
905 #define DIFF_OLD_NAME 0
906 #define DIFF_NEW_NAME 1
908 static int gitdiff_verify_name(struct gitdiff_data
*state
,
914 if (!*name
&& !isnull
) {
915 *name
= find_name(state
->root
, line
, NULL
, state
->p_value
, TERM_TAB
);
922 return error(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
923 *name
, state
->linenr
);
924 another
= find_name(state
->root
, line
, NULL
, state
->p_value
, TERM_TAB
);
925 if (!another
|| strcmp(another
, *name
)) {
927 return error((side
== DIFF_NEW_NAME
) ?
928 _("git apply: bad git-diff - inconsistent new filename on line %d") :
929 _("git apply: bad git-diff - inconsistent old filename on line %d"), state
->linenr
);
933 if (!is_dev_null(line
))
934 return error(_("git apply: bad git-diff - expected /dev/null on line %d"), state
->linenr
);
940 static int gitdiff_oldname(struct gitdiff_data
*state
,
944 return gitdiff_verify_name(state
, line
,
945 patch
->is_new
, &patch
->old_name
,
949 static int gitdiff_newname(struct gitdiff_data
*state
,
953 return gitdiff_verify_name(state
, line
,
954 patch
->is_delete
, &patch
->new_name
,
958 static int parse_mode_line(const char *line
, int linenr
, unsigned int *mode
)
961 *mode
= strtoul(line
, &end
, 8);
962 if (end
== line
|| !isspace(*end
))
963 return error(_("invalid mode on line %d: %s"), linenr
, line
);
967 static int gitdiff_oldmode(struct gitdiff_data
*state
,
971 return parse_mode_line(line
, state
->linenr
, &patch
->old_mode
);
974 static int gitdiff_newmode(struct gitdiff_data
*state
,
978 return parse_mode_line(line
, state
->linenr
, &patch
->new_mode
);
981 static int gitdiff_delete(struct gitdiff_data
*state
,
985 patch
->is_delete
= 1;
986 free(patch
->old_name
);
987 patch
->old_name
= xstrdup_or_null(patch
->def_name
);
988 return gitdiff_oldmode(state
, line
, patch
);
991 static int gitdiff_newfile(struct gitdiff_data
*state
,
996 free(patch
->new_name
);
997 patch
->new_name
= xstrdup_or_null(patch
->def_name
);
998 return gitdiff_newmode(state
, line
, patch
);
1001 static int gitdiff_copysrc(struct gitdiff_data
*state
,
1003 struct patch
*patch
)
1006 free(patch
->old_name
);
1007 patch
->old_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1011 static int gitdiff_copydst(struct gitdiff_data
*state
,
1013 struct patch
*patch
)
1016 free(patch
->new_name
);
1017 patch
->new_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1021 static int gitdiff_renamesrc(struct gitdiff_data
*state
,
1023 struct patch
*patch
)
1025 patch
->is_rename
= 1;
1026 free(patch
->old_name
);
1027 patch
->old_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1031 static int gitdiff_renamedst(struct gitdiff_data
*state
,
1033 struct patch
*patch
)
1035 patch
->is_rename
= 1;
1036 free(patch
->new_name
);
1037 patch
->new_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1041 static int gitdiff_similarity(struct gitdiff_data
*state
,
1043 struct patch
*patch
)
1045 unsigned long val
= strtoul(line
, NULL
, 10);
1051 static int gitdiff_dissimilarity(struct gitdiff_data
*state
,
1053 struct patch
*patch
)
1055 unsigned long val
= strtoul(line
, NULL
, 10);
1061 static int gitdiff_index(struct gitdiff_data
*state
,
1063 struct patch
*patch
)
1066 * index line is N hexadecimal, "..", N hexadecimal,
1067 * and optional space with octal mode.
1069 const char *ptr
, *eol
;
1071 const unsigned hexsz
= the_hash_algo
->hexsz
;
1073 ptr
= strchr(line
, '.');
1074 if (!ptr
|| ptr
[1] != '.' || hexsz
< ptr
- line
)
1077 memcpy(patch
->old_oid_prefix
, line
, len
);
1078 patch
->old_oid_prefix
[len
] = 0;
1081 ptr
= strchr(line
, ' ');
1082 eol
= strchrnul(line
, '\n');
1084 if (!ptr
|| eol
< ptr
)
1090 memcpy(patch
->new_oid_prefix
, line
, len
);
1091 patch
->new_oid_prefix
[len
] = 0;
1093 return gitdiff_oldmode(state
, ptr
+ 1, patch
);
1098 * This is normal for a diff that doesn't change anything: we'll fall through
1099 * into the next diff. Tell the parser to break out.
1101 static int gitdiff_unrecognized(struct gitdiff_data
*state
,
1103 struct patch
*patch
)
1109 * Skip p_value leading components from "line"; as we do not accept
1110 * absolute paths, return NULL in that case.
1112 static const char *skip_tree_prefix(int p_value
,
1120 return (llen
&& line
[0] == '/') ? NULL
: line
;
1123 for (i
= 0; i
< llen
; i
++) {
1125 if (ch
== '/' && --nslash
<= 0)
1126 return (i
== 0) ? NULL
: &line
[i
+ 1];
1132 * This is to extract the same name that appears on "diff --git"
1133 * line. We do not find and return anything if it is a rename
1134 * patch, and it is OK because we will find the name elsewhere.
1135 * We need to reliably find name only when it is mode-change only,
1136 * creation or deletion of an empty file. In any of these cases,
1137 * both sides are the same name under a/ and b/ respectively.
1139 static char *git_header_name(int p_value
,
1144 const char *second
= NULL
;
1145 size_t len
, line_len
;
1147 line
+= strlen("diff --git ");
1148 llen
-= strlen("diff --git ");
1152 struct strbuf first
= STRBUF_INIT
;
1153 struct strbuf sp
= STRBUF_INIT
;
1155 if (unquote_c_style(&first
, line
, &second
))
1156 goto free_and_fail1
;
1158 /* strip the a/b prefix including trailing slash */
1159 cp
= skip_tree_prefix(p_value
, first
.buf
, first
.len
);
1161 goto free_and_fail1
;
1162 strbuf_remove(&first
, 0, cp
- first
.buf
);
1165 * second points at one past closing dq of name.
1166 * find the second name.
1168 while ((second
< line
+ llen
) && isspace(*second
))
1171 if (line
+ llen
<= second
)
1172 goto free_and_fail1
;
1173 if (*second
== '"') {
1174 if (unquote_c_style(&sp
, second
, NULL
))
1175 goto free_and_fail1
;
1176 cp
= skip_tree_prefix(p_value
, sp
.buf
, sp
.len
);
1178 goto free_and_fail1
;
1179 /* They must match, otherwise ignore */
1180 if (strcmp(cp
, first
.buf
))
1181 goto free_and_fail1
;
1182 strbuf_release(&sp
);
1183 return strbuf_detach(&first
, NULL
);
1186 /* unquoted second */
1187 cp
= skip_tree_prefix(p_value
, second
, line
+ llen
- second
);
1189 goto free_and_fail1
;
1190 if (line
+ llen
- cp
!= first
.len
||
1191 memcmp(first
.buf
, cp
, first
.len
))
1192 goto free_and_fail1
;
1193 return strbuf_detach(&first
, NULL
);
1196 strbuf_release(&first
);
1197 strbuf_release(&sp
);
1201 /* unquoted first name */
1202 name
= skip_tree_prefix(p_value
, line
, llen
);
1207 * since the first name is unquoted, a dq if exists must be
1208 * the beginning of the second name.
1210 for (second
= name
; second
< line
+ llen
; second
++) {
1211 if (*second
== '"') {
1212 struct strbuf sp
= STRBUF_INIT
;
1215 if (unquote_c_style(&sp
, second
, NULL
))
1216 goto free_and_fail2
;
1218 np
= skip_tree_prefix(p_value
, sp
.buf
, sp
.len
);
1220 goto free_and_fail2
;
1222 len
= sp
.buf
+ sp
.len
- np
;
1223 if (len
< second
- name
&&
1224 !strncmp(np
, name
, len
) &&
1225 isspace(name
[len
])) {
1227 strbuf_remove(&sp
, 0, np
- sp
.buf
);
1228 return strbuf_detach(&sp
, NULL
);
1232 strbuf_release(&sp
);
1238 * Accept a name only if it shows up twice, exactly the same
1241 second
= strchr(name
, '\n');
1244 line_len
= second
- name
;
1245 for (len
= 0 ; ; len
++) {
1246 switch (name
[len
]) {
1251 case '\t': case ' ':
1253 * Is this the separator between the preimage
1254 * and the postimage pathname? Again, we are
1255 * only interested in the case where there is
1256 * no rename, as this is only to set def_name
1257 * and a rename patch has the names elsewhere
1258 * in an unambiguous form.
1261 return NULL
; /* no postimage name */
1262 second
= skip_tree_prefix(p_value
, name
+ len
+ 1,
1263 line_len
- (len
+ 1));
1267 * Does len bytes starting at "name" and "second"
1268 * (that are separated by one HT or SP we just
1269 * found) exactly match?
1271 if (second
[len
] == '\n' && !strncmp(name
, second
, len
))
1272 return xmemdupz(name
, len
);
1277 static int check_header_line(int linenr
, struct patch
*patch
)
1279 int extensions
= (patch
->is_delete
== 1) + (patch
->is_new
== 1) +
1280 (patch
->is_rename
== 1) + (patch
->is_copy
== 1);
1282 return error(_("inconsistent header lines %d and %d"),
1283 patch
->extension_linenr
, linenr
);
1284 if (extensions
&& !patch
->extension_linenr
)
1285 patch
->extension_linenr
= linenr
;
1289 int parse_git_diff_header(struct strbuf
*root
,
1295 struct patch
*patch
)
1297 unsigned long offset
;
1298 struct gitdiff_data parse_hdr_state
;
1300 /* A git diff has explicit new/delete information, so we don't guess */
1302 patch
->is_delete
= 0;
1305 * Some things may not have the old name in the
1306 * rest of the headers anywhere (pure mode changes,
1307 * or removing or adding empty files), so we get
1308 * the default name from the header.
1310 patch
->def_name
= git_header_name(p_value
, line
, len
);
1311 if (patch
->def_name
&& root
->len
) {
1312 char *s
= xstrfmt("%s%s", root
->buf
, patch
->def_name
);
1313 free(patch
->def_name
);
1314 patch
->def_name
= s
;
1320 parse_hdr_state
.root
= root
;
1321 parse_hdr_state
.linenr
= *linenr
;
1322 parse_hdr_state
.p_value
= p_value
;
1324 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, (*linenr
)++) {
1325 static const struct opentry
{
1327 int (*fn
)(struct gitdiff_data
*, const char *, struct patch
*);
1329 { "@@ -", gitdiff_hdrend
},
1330 { "--- ", gitdiff_oldname
},
1331 { "+++ ", gitdiff_newname
},
1332 { "old mode ", gitdiff_oldmode
},
1333 { "new mode ", gitdiff_newmode
},
1334 { "deleted file mode ", gitdiff_delete
},
1335 { "new file mode ", gitdiff_newfile
},
1336 { "copy from ", gitdiff_copysrc
},
1337 { "copy to ", gitdiff_copydst
},
1338 { "rename old ", gitdiff_renamesrc
},
1339 { "rename new ", gitdiff_renamedst
},
1340 { "rename from ", gitdiff_renamesrc
},
1341 { "rename to ", gitdiff_renamedst
},
1342 { "similarity index ", gitdiff_similarity
},
1343 { "dissimilarity index ", gitdiff_dissimilarity
},
1344 { "index ", gitdiff_index
},
1345 { "", gitdiff_unrecognized
},
1349 len
= linelen(line
, size
);
1350 if (!len
|| line
[len
-1] != '\n')
1352 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
1353 const struct opentry
*p
= optable
+ i
;
1354 int oplen
= strlen(p
->str
);
1356 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
1358 res
= p
->fn(&parse_hdr_state
, line
+ oplen
, patch
);
1361 if (check_header_line(*linenr
, patch
))
1370 if (!patch
->old_name
&& !patch
->new_name
) {
1371 if (!patch
->def_name
) {
1372 error(Q_("git diff header lacks filename information when removing "
1373 "%d leading pathname component (line %d)",
1374 "git diff header lacks filename information when removing "
1375 "%d leading pathname components (line %d)",
1376 parse_hdr_state
.p_value
),
1377 parse_hdr_state
.p_value
, *linenr
);
1380 patch
->old_name
= xstrdup(patch
->def_name
);
1381 patch
->new_name
= xstrdup(patch
->def_name
);
1383 if ((!patch
->new_name
&& !patch
->is_delete
) ||
1384 (!patch
->old_name
&& !patch
->is_new
)) {
1385 error(_("git diff header lacks filename information "
1386 "(line %d)"), *linenr
);
1389 patch
->is_toplevel_relative
= 1;
1393 static int parse_num(const char *line
, unsigned long *p
)
1397 if (!isdigit(*line
))
1399 *p
= strtoul(line
, &ptr
, 10);
1403 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
1404 unsigned long *p1
, unsigned long *p2
)
1408 if (offset
< 0 || offset
>= len
)
1413 digits
= parse_num(line
, p1
);
1423 digits
= parse_num(line
+1, p2
);
1432 ex
= strlen(expect
);
1435 if (memcmp(line
, expect
, ex
))
1441 static void recount_diff(const char *line
, int size
, struct fragment
*fragment
)
1443 int oldlines
= 0, newlines
= 0, ret
= 0;
1446 warning("recount: ignore empty hunk");
1451 int len
= linelen(line
, size
);
1459 case ' ': case '\n':
1471 ret
= size
< 3 || !starts_with(line
, "@@ ");
1474 ret
= size
< 5 || !starts_with(line
, "diff ");
1481 warning(_("recount: unexpected line: %.*s"),
1482 (int)linelen(line
, size
), line
);
1487 fragment
->oldlines
= oldlines
;
1488 fragment
->newlines
= newlines
;
1492 * Parse a unified diff fragment header of the
1493 * form "@@ -a,b +c,d @@"
1495 static int parse_fragment_header(const char *line
, int len
, struct fragment
*fragment
)
1499 if (!len
|| line
[len
-1] != '\n')
1502 /* Figure out the number of lines in a fragment */
1503 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
1504 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
1510 * Find file diff header
1513 * -1 if no header was found
1514 * -128 in case of error
1515 * the size of the header in bytes (called "offset") otherwise
1517 static int find_header(struct apply_state
*state
,
1521 struct patch
*patch
)
1523 unsigned long offset
, len
;
1525 patch
->is_toplevel_relative
= 0;
1526 patch
->is_rename
= patch
->is_copy
= 0;
1527 patch
->is_new
= patch
->is_delete
= -1;
1528 patch
->old_mode
= patch
->new_mode
= 0;
1529 patch
->old_name
= patch
->new_name
= NULL
;
1530 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1531 unsigned long nextlen
;
1533 len
= linelen(line
, size
);
1537 /* Testing this early allows us to take a few shortcuts.. */
1542 * Make sure we don't find any unconnected patch fragments.
1543 * That's a sign that we didn't find a header, and that a
1544 * patch has become corrupted/broken up.
1546 if (!memcmp("@@ -", line
, 4)) {
1547 struct fragment dummy
;
1548 if (parse_fragment_header(line
, len
, &dummy
) < 0)
1550 error(_("patch fragment without header at line %d: %.*s"),
1551 state
->linenr
, (int)len
-1, line
);
1559 * Git patch? It might not have a real patch, just a rename
1560 * or mode change, so we handle that specially
1562 if (!memcmp("diff --git ", line
, 11)) {
1563 int git_hdr_len
= parse_git_diff_header(&state
->root
, &state
->linenr
,
1564 state
->p_value
, line
, len
,
1566 if (git_hdr_len
< 0)
1568 if (git_hdr_len
<= len
)
1570 *hdrsize
= git_hdr_len
;
1574 /* --- followed by +++ ? */
1575 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
1579 * We only accept unified patches, so we want it to
1580 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1581 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1583 nextlen
= linelen(line
+ len
, size
- len
);
1584 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
1587 /* Ok, we'll consider it a patch */
1588 if (parse_traditional_patch(state
, line
, line
+len
, patch
))
1590 *hdrsize
= len
+ nextlen
;
1597 static void record_ws_error(struct apply_state
*state
,
1608 state
->whitespace_error
++;
1609 if (state
->squelch_whitespace_errors
&&
1610 state
->squelch_whitespace_errors
< state
->whitespace_error
)
1613 err
= whitespace_error_string(result
);
1614 if (state
->apply_verbosity
> verbosity_silent
)
1615 fprintf(stderr
, "%s:%d: %s.\n%.*s\n",
1616 state
->patch_input_file
, linenr
, err
, len
, line
);
1620 static void check_whitespace(struct apply_state
*state
,
1625 unsigned result
= ws_check(line
+ 1, len
- 1, ws_rule
);
1627 record_ws_error(state
, result
, line
+ 1, len
- 2, state
->linenr
);
1631 * Check if the patch has context lines with CRLF or
1632 * the patch wants to remove lines with CRLF.
1634 static void check_old_for_crlf(struct patch
*patch
, const char *line
, int len
)
1636 if (len
>= 2 && line
[len
-1] == '\n' && line
[len
-2] == '\r') {
1637 patch
->ws_rule
|= WS_CR_AT_EOL
;
1638 patch
->crlf_in_old
= 1;
1644 * Parse a unified diff. Note that this really needs to parse each
1645 * fragment separately, since the only way to know the difference
1646 * between a "---" that is part of a patch, and a "---" that starts
1647 * the next patch is to look at the line counts..
1649 static int parse_fragment(struct apply_state
*state
,
1652 struct patch
*patch
,
1653 struct fragment
*fragment
)
1656 int len
= linelen(line
, size
), offset
;
1657 unsigned long oldlines
, newlines
;
1658 unsigned long leading
, trailing
;
1660 offset
= parse_fragment_header(line
, len
, fragment
);
1663 if (offset
> 0 && patch
->recount
)
1664 recount_diff(line
+ offset
, size
- offset
, fragment
);
1665 oldlines
= fragment
->oldlines
;
1666 newlines
= fragment
->newlines
;
1670 /* Parse the thing.. */
1674 added
= deleted
= 0;
1677 offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1678 if (!oldlines
&& !newlines
)
1680 len
= linelen(line
, size
);
1681 if (!len
|| line
[len
-1] != '\n')
1686 case '\n': /* newer GNU diff, an empty context line */
1690 if (!deleted
&& !added
)
1693 check_old_for_crlf(patch
, line
, len
);
1694 if (!state
->apply_in_reverse
&&
1695 state
->ws_error_action
== correct_ws_error
)
1696 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1699 if (!state
->apply_in_reverse
)
1700 check_old_for_crlf(patch
, line
, len
);
1701 if (state
->apply_in_reverse
&&
1702 state
->ws_error_action
!= nowarn_ws_error
)
1703 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1709 if (state
->apply_in_reverse
)
1710 check_old_for_crlf(patch
, line
, len
);
1711 if (!state
->apply_in_reverse
&&
1712 state
->ws_error_action
!= nowarn_ws_error
)
1713 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1720 * We allow "\ No newline at end of file". Depending
1721 * on locale settings when the patch was produced we
1722 * don't know what this line looks like. The only
1723 * thing we do know is that it begins with "\ ".
1724 * Checking for 12 is just for sanity check -- any
1725 * l10n of "\ No newline..." is at least that long.
1728 if (len
< 12 || memcmp(line
, "\\ ", 2))
1733 if (oldlines
|| newlines
)
1735 if (!patch
->recount
&& !deleted
&& !added
)
1738 fragment
->leading
= leading
;
1739 fragment
->trailing
= trailing
;
1742 * If a fragment ends with an incomplete line, we failed to include
1743 * it in the above loop because we hit oldlines == newlines == 0
1746 if (12 < size
&& !memcmp(line
, "\\ ", 2))
1747 offset
+= linelen(line
, size
);
1749 patch
->lines_added
+= added
;
1750 patch
->lines_deleted
+= deleted
;
1752 if (0 < patch
->is_new
&& oldlines
)
1753 return error(_("new file depends on old contents"));
1754 if (0 < patch
->is_delete
&& newlines
)
1755 return error(_("deleted file still has contents"));
1760 * We have seen "diff --git a/... b/..." header (or a traditional patch
1761 * header). Read hunks that belong to this patch into fragments and hang
1762 * them to the given patch structure.
1764 * The (fragment->patch, fragment->size) pair points into the memory given
1765 * by the caller, not a copy, when we return.
1768 * -1 in case of error,
1769 * the number of bytes in the patch otherwise.
1771 static int parse_single_patch(struct apply_state
*state
,
1774 struct patch
*patch
)
1776 unsigned long offset
= 0;
1777 unsigned long oldlines
= 0, newlines
= 0, context
= 0;
1778 struct fragment
**fragp
= &patch
->fragments
;
1780 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
1781 struct fragment
*fragment
;
1784 fragment
= xcalloc(1, sizeof(*fragment
));
1785 fragment
->linenr
= state
->linenr
;
1786 len
= parse_fragment(state
, line
, size
, patch
, fragment
);
1789 return error(_("corrupt patch at line %d"), state
->linenr
);
1791 fragment
->patch
= line
;
1792 fragment
->size
= len
;
1793 oldlines
+= fragment
->oldlines
;
1794 newlines
+= fragment
->newlines
;
1795 context
+= fragment
->leading
+ fragment
->trailing
;
1798 fragp
= &fragment
->next
;
1806 * If something was removed (i.e. we have old-lines) it cannot
1807 * be creation, and if something was added it cannot be
1808 * deletion. However, the reverse is not true; --unified=0
1809 * patches that only add are not necessarily creation even
1810 * though they do not have any old lines, and ones that only
1811 * delete are not necessarily deletion.
1813 * Unfortunately, a real creation/deletion patch do _not_ have
1814 * any context line by definition, so we cannot safely tell it
1815 * apart with --unified=0 insanity. At least if the patch has
1816 * more than one hunk it is not creation or deletion.
1818 if (patch
->is_new
< 0 &&
1819 (oldlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1821 if (patch
->is_delete
< 0 &&
1822 (newlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1823 patch
->is_delete
= 0;
1825 if (0 < patch
->is_new
&& oldlines
)
1826 return error(_("new file %s depends on old contents"), patch
->new_name
);
1827 if (0 < patch
->is_delete
&& newlines
)
1828 return error(_("deleted file %s still has contents"), patch
->old_name
);
1829 if (!patch
->is_delete
&& !newlines
&& context
&& state
->apply_verbosity
> verbosity_silent
)
1832 "file %s becomes empty but is not deleted"),
1838 static inline int metadata_changes(struct patch
*patch
)
1840 return patch
->is_rename
> 0 ||
1841 patch
->is_copy
> 0 ||
1842 patch
->is_new
> 0 ||
1844 (patch
->old_mode
&& patch
->new_mode
&&
1845 patch
->old_mode
!= patch
->new_mode
);
1848 static char *inflate_it(const void *data
, unsigned long size
,
1849 unsigned long inflated_size
)
1855 memset(&stream
, 0, sizeof(stream
));
1857 stream
.next_in
= (unsigned char *)data
;
1858 stream
.avail_in
= size
;
1859 stream
.next_out
= out
= xmalloc(inflated_size
);
1860 stream
.avail_out
= inflated_size
;
1861 git_inflate_init(&stream
);
1862 st
= git_inflate(&stream
, Z_FINISH
);
1863 git_inflate_end(&stream
);
1864 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1872 * Read a binary hunk and return a new fragment; fragment->patch
1873 * points at an allocated memory that the caller must free, so
1874 * it is marked as "->free_patch = 1".
1876 static struct fragment
*parse_binary_hunk(struct apply_state
*state
,
1878 unsigned long *sz_p
,
1883 * Expect a line that begins with binary patch method ("literal"
1884 * or "delta"), followed by the length of data before deflating.
1885 * a sequence of 'length-byte' followed by base-85 encoded data
1886 * should follow, terminated by a newline.
1888 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1889 * and we would limit the patch line to 66 characters,
1890 * so one line can fit up to 13 groups that would decode
1891 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1892 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1895 unsigned long size
= *sz_p
;
1896 char *buffer
= *buf_p
;
1898 unsigned long origlen
;
1901 struct fragment
*frag
;
1903 llen
= linelen(buffer
, size
);
1908 if (starts_with(buffer
, "delta ")) {
1909 patch_method
= BINARY_DELTA_DEFLATED
;
1910 origlen
= strtoul(buffer
+ 6, NULL
, 10);
1912 else if (starts_with(buffer
, "literal ")) {
1913 patch_method
= BINARY_LITERAL_DEFLATED
;
1914 origlen
= strtoul(buffer
+ 8, NULL
, 10);
1922 int byte_length
, max_byte_length
, newsize
;
1923 llen
= linelen(buffer
, size
);
1927 /* consume the blank line */
1933 * Minimum line is "A00000\n" which is 7-byte long,
1934 * and the line length must be multiple of 5 plus 2.
1936 if ((llen
< 7) || (llen
-2) % 5)
1938 max_byte_length
= (llen
- 2) / 5 * 4;
1939 byte_length
= *buffer
;
1940 if ('A' <= byte_length
&& byte_length
<= 'Z')
1941 byte_length
= byte_length
- 'A' + 1;
1942 else if ('a' <= byte_length
&& byte_length
<= 'z')
1943 byte_length
= byte_length
- 'a' + 27;
1946 /* if the input length was not multiple of 4, we would
1947 * have filler at the end but the filler should never
1950 if (max_byte_length
< byte_length
||
1951 byte_length
<= max_byte_length
- 4)
1953 newsize
= hunk_size
+ byte_length
;
1954 data
= xrealloc(data
, newsize
);
1955 if (decode_85(data
+ hunk_size
, buffer
+ 1, byte_length
))
1957 hunk_size
= newsize
;
1962 frag
= xcalloc(1, sizeof(*frag
));
1963 frag
->patch
= inflate_it(data
, hunk_size
, origlen
);
1964 frag
->free_patch
= 1;
1968 frag
->size
= origlen
;
1972 frag
->binary_patch_method
= patch_method
;
1978 error(_("corrupt binary patch at line %d: %.*s"),
1979 state
->linenr
-1, llen
-1, buffer
);
1985 * -1 in case of error,
1986 * the length of the parsed binary patch otherwise
1988 static int parse_binary(struct apply_state
*state
,
1991 struct patch
*patch
)
1994 * We have read "GIT binary patch\n"; what follows is a line
1995 * that says the patch method (currently, either "literal" or
1996 * "delta") and the length of data before deflating; a
1997 * sequence of 'length-byte' followed by base-85 encoded data
2000 * When a binary patch is reversible, there is another binary
2001 * hunk in the same format, starting with patch method (either
2002 * "literal" or "delta") with the length of data, and a sequence
2003 * of length-byte + base-85 encoded data, terminated with another
2004 * empty line. This data, when applied to the postimage, produces
2007 struct fragment
*forward
;
2008 struct fragment
*reverse
;
2012 forward
= parse_binary_hunk(state
, &buffer
, &size
, &status
, &used
);
2013 if (!forward
&& !status
)
2014 /* there has to be one hunk (forward hunk) */
2015 return error(_("unrecognized binary patch at line %d"), state
->linenr
-1);
2017 /* otherwise we already gave an error message */
2020 reverse
= parse_binary_hunk(state
, &buffer
, &size
, &status
, &used_1
);
2025 * Not having reverse hunk is not an error, but having
2026 * a corrupt reverse hunk is.
2028 free((void*) forward
->patch
);
2032 forward
->next
= reverse
;
2033 patch
->fragments
= forward
;
2034 patch
->is_binary
= 1;
2038 static void prefix_one(struct apply_state
*state
, char **name
)
2040 char *old_name
= *name
;
2043 *name
= prefix_filename(state
->prefix
, *name
);
2047 static void prefix_patch(struct apply_state
*state
, struct patch
*p
)
2049 if (!state
->prefix
|| p
->is_toplevel_relative
)
2051 prefix_one(state
, &p
->new_name
);
2052 prefix_one(state
, &p
->old_name
);
2059 static void add_name_limit(struct apply_state
*state
,
2063 struct string_list_item
*it
;
2065 it
= string_list_append(&state
->limit_by_name
, name
);
2066 it
->util
= exclude
? NULL
: (void *) 1;
2069 static int use_patch(struct apply_state
*state
, struct patch
*p
)
2071 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
2074 /* Paths outside are not touched regardless of "--include" */
2075 if (state
->prefix
&& *state
->prefix
) {
2077 if (!skip_prefix(pathname
, state
->prefix
, &rest
) || !*rest
)
2081 /* See if it matches any of exclude/include rule */
2082 for (i
= 0; i
< state
->limit_by_name
.nr
; i
++) {
2083 struct string_list_item
*it
= &state
->limit_by_name
.items
[i
];
2084 if (!wildmatch(it
->string
, pathname
, 0))
2085 return (it
->util
!= NULL
);
2089 * If we had any include, a path that does not match any rule is
2090 * not used. Otherwise, we saw bunch of exclude rules (or none)
2091 * and such a path is used.
2093 return !state
->has_include
;
2097 * Read the patch text in "buffer" that extends for "size" bytes; stop
2098 * reading after seeing a single patch (i.e. changes to a single file).
2099 * Create fragments (i.e. patch hunks) and hang them to the given patch.
2102 * -1 if no header was found or parse_binary() failed,
2103 * -128 on another error,
2104 * the number of bytes consumed otherwise,
2105 * so that the caller can call us again for the next patch.
2107 static int parse_chunk(struct apply_state
*state
, char *buffer
, unsigned long size
, struct patch
*patch
)
2109 int hdrsize
, patchsize
;
2110 int offset
= find_header(state
, buffer
, size
, &hdrsize
, patch
);
2115 prefix_patch(state
, patch
);
2117 if (!use_patch(state
, patch
))
2119 else if (patch
->new_name
)
2120 patch
->ws_rule
= whitespace_rule(state
->repo
->index
,
2123 patch
->ws_rule
= whitespace_rule(state
->repo
->index
,
2126 patchsize
= parse_single_patch(state
,
2127 buffer
+ offset
+ hdrsize
,
2128 size
- offset
- hdrsize
,
2135 static const char git_binary
[] = "GIT binary patch\n";
2136 int hd
= hdrsize
+ offset
;
2137 unsigned long llen
= linelen(buffer
+ hd
, size
- hd
);
2139 if (llen
== sizeof(git_binary
) - 1 &&
2140 !memcmp(git_binary
, buffer
+ hd
, llen
)) {
2143 used
= parse_binary(state
, buffer
+ hd
+ llen
,
2144 size
- hd
- llen
, patch
);
2148 patchsize
= used
+ llen
;
2152 else if (!memcmp(" differ\n", buffer
+ hd
+ llen
- 8, 8)) {
2153 static const char *binhdr
[] = {
2159 for (i
= 0; binhdr
[i
]; i
++) {
2160 int len
= strlen(binhdr
[i
]);
2161 if (len
< size
- hd
&&
2162 !memcmp(binhdr
[i
], buffer
+ hd
, len
)) {
2164 patch
->is_binary
= 1;
2171 /* Empty patch cannot be applied if it is a text patch
2172 * without metadata change. A binary patch appears
2175 if ((state
->apply
|| state
->check
) &&
2176 (!patch
->is_binary
&& !metadata_changes(patch
))) {
2177 error(_("patch with only garbage at line %d"), state
->linenr
);
2182 return offset
+ hdrsize
+ patchsize
;
2185 static void reverse_patches(struct patch
*p
)
2187 for (; p
; p
= p
->next
) {
2188 struct fragment
*frag
= p
->fragments
;
2190 SWAP(p
->new_name
, p
->old_name
);
2191 SWAP(p
->new_mode
, p
->old_mode
);
2192 SWAP(p
->is_new
, p
->is_delete
);
2193 SWAP(p
->lines_added
, p
->lines_deleted
);
2194 SWAP(p
->old_oid_prefix
, p
->new_oid_prefix
);
2196 for (; frag
; frag
= frag
->next
) {
2197 SWAP(frag
->newpos
, frag
->oldpos
);
2198 SWAP(frag
->newlines
, frag
->oldlines
);
2203 static const char pluses
[] =
2204 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2205 static const char minuses
[]=
2206 "----------------------------------------------------------------------";
2208 static void show_stats(struct apply_state
*state
, struct patch
*patch
)
2210 struct strbuf qname
= STRBUF_INIT
;
2211 char *cp
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
2214 quote_c_style(cp
, &qname
, NULL
, 0);
2217 * "scale" the filename
2219 max
= state
->max_len
;
2223 if (qname
.len
> max
) {
2224 cp
= strchr(qname
.buf
+ qname
.len
+ 3 - max
, '/');
2226 cp
= qname
.buf
+ qname
.len
+ 3 - max
;
2227 strbuf_splice(&qname
, 0, cp
- qname
.buf
, "...", 3);
2230 if (patch
->is_binary
) {
2231 printf(" %-*s | Bin\n", max
, qname
.buf
);
2232 strbuf_release(&qname
);
2236 printf(" %-*s |", max
, qname
.buf
);
2237 strbuf_release(&qname
);
2240 * scale the add/delete
2242 max
= max
+ state
->max_change
> 70 ? 70 - max
: state
->max_change
;
2243 add
= patch
->lines_added
;
2244 del
= patch
->lines_deleted
;
2246 if (state
->max_change
> 0) {
2247 int total
= ((add
+ del
) * max
+ state
->max_change
/ 2) / state
->max_change
;
2248 add
= (add
* max
+ state
->max_change
/ 2) / state
->max_change
;
2251 printf("%5d %.*s%.*s\n", patch
->lines_added
+ patch
->lines_deleted
,
2252 add
, pluses
, del
, minuses
);
2255 static int read_old_data(struct stat
*st
, struct patch
*patch
,
2256 const char *path
, struct strbuf
*buf
)
2258 int conv_flags
= patch
->crlf_in_old
?
2259 CONV_EOL_KEEP_CRLF
: CONV_EOL_RENORMALIZE
;
2260 switch (st
->st_mode
& S_IFMT
) {
2262 if (strbuf_readlink(buf
, path
, st
->st_size
) < 0)
2263 return error(_("unable to read symlink %s"), path
);
2266 if (strbuf_read_file(buf
, path
, st
->st_size
) != st
->st_size
)
2267 return error(_("unable to open or read %s"), path
);
2269 * "git apply" without "--index/--cached" should never look
2270 * at the index; the target file may not have been added to
2271 * the index yet, and we may not even be in any Git repository.
2272 * Pass NULL to convert_to_git() to stress this; the function
2273 * should never look at the index when explicit crlf option
2276 convert_to_git(NULL
, path
, buf
->buf
, buf
->len
, buf
, conv_flags
);
2284 * Update the preimage, and the common lines in postimage,
2285 * from buffer buf of length len. If postlen is 0 the postimage
2286 * is updated in place, otherwise it's updated on a new buffer
2290 static void update_pre_post_images(struct image
*preimage
,
2291 struct image
*postimage
,
2293 size_t len
, size_t postlen
)
2295 int i
, ctx
, reduced
;
2296 char *new_buf
, *old_buf
, *fixed
;
2297 struct image fixed_preimage
;
2300 * Update the preimage with whitespace fixes. Note that we
2301 * are not losing preimage->buf -- apply_one_fragment() will
2304 prepare_image(&fixed_preimage
, buf
, len
, 1);
2306 ? fixed_preimage
.nr
== preimage
->nr
2307 : fixed_preimage
.nr
<= preimage
->nr
);
2308 for (i
= 0; i
< fixed_preimage
.nr
; i
++)
2309 fixed_preimage
.line
[i
].flag
= preimage
->line
[i
].flag
;
2310 free(preimage
->line_allocated
);
2311 *preimage
= fixed_preimage
;
2314 * Adjust the common context lines in postimage. This can be
2315 * done in-place when we are shrinking it with whitespace
2316 * fixing, but needs a new buffer when ignoring whitespace or
2317 * expanding leading tabs to spaces.
2319 * We trust the caller to tell us if the update can be done
2320 * in place (postlen==0) or not.
2322 old_buf
= postimage
->buf
;
2324 new_buf
= postimage
->buf
= xmalloc(postlen
);
2327 fixed
= preimage
->buf
;
2329 for (i
= reduced
= ctx
= 0; i
< postimage
->nr
; i
++) {
2330 size_t l_len
= postimage
->line
[i
].len
;
2331 if (!(postimage
->line
[i
].flag
& LINE_COMMON
)) {
2332 /* an added line -- no counterparts in preimage */
2333 memmove(new_buf
, old_buf
, l_len
);
2339 /* a common context -- skip it in the original postimage */
2342 /* and find the corresponding one in the fixed preimage */
2343 while (ctx
< preimage
->nr
&&
2344 !(preimage
->line
[ctx
].flag
& LINE_COMMON
)) {
2345 fixed
+= preimage
->line
[ctx
].len
;
2350 * preimage is expected to run out, if the caller
2351 * fixed addition of trailing blank lines.
2353 if (preimage
->nr
<= ctx
) {
2358 /* and copy it in, while fixing the line length */
2359 l_len
= preimage
->line
[ctx
].len
;
2360 memcpy(new_buf
, fixed
, l_len
);
2363 postimage
->line
[i
].len
= l_len
;
2368 ? postlen
< new_buf
- postimage
->buf
2369 : postimage
->len
< new_buf
- postimage
->buf
)
2370 BUG("caller miscounted postlen: asked %d, orig = %d, used = %d",
2371 (int)postlen
, (int) postimage
->len
, (int)(new_buf
- postimage
->buf
));
2373 /* Fix the length of the whole thing */
2374 postimage
->len
= new_buf
- postimage
->buf
;
2375 postimage
->nr
-= reduced
;
2378 static int line_by_line_fuzzy_match(struct image
*img
,
2379 struct image
*preimage
,
2380 struct image
*postimage
,
2381 unsigned long current
,
2388 size_t postlen
= postimage
->len
;
2393 struct strbuf fixed
;
2397 for (i
= 0; i
< preimage_limit
; i
++) {
2398 size_t prelen
= preimage
->line
[i
].len
;
2399 size_t imglen
= img
->line
[current_lno
+i
].len
;
2401 if (!fuzzy_matchlines(img
->buf
+ current
+ imgoff
, imglen
,
2402 preimage
->buf
+ preoff
, prelen
))
2404 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2405 postlen
+= imglen
- prelen
;
2411 * Ok, the preimage matches with whitespace fuzz.
2413 * imgoff now holds the true length of the target that
2414 * matches the preimage before the end of the file.
2416 * Count the number of characters in the preimage that fall
2417 * beyond the end of the file and make sure that all of them
2418 * are whitespace characters. (This can only happen if
2419 * we are removing blank lines at the end of the file.)
2421 buf
= preimage_eof
= preimage
->buf
+ preoff
;
2422 for ( ; i
< preimage
->nr
; i
++)
2423 preoff
+= preimage
->line
[i
].len
;
2424 preimage_end
= preimage
->buf
+ preoff
;
2425 for ( ; buf
< preimage_end
; buf
++)
2430 * Update the preimage and the common postimage context
2431 * lines to use the same whitespace as the target.
2432 * If whitespace is missing in the target (i.e.
2433 * if the preimage extends beyond the end of the file),
2434 * use the whitespace from the preimage.
2436 extra_chars
= preimage_end
- preimage_eof
;
2437 strbuf_init(&fixed
, imgoff
+ extra_chars
);
2438 strbuf_add(&fixed
, img
->buf
+ current
, imgoff
);
2439 strbuf_add(&fixed
, preimage_eof
, extra_chars
);
2440 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2441 update_pre_post_images(preimage
, postimage
,
2442 fixed_buf
, fixed_len
, postlen
);
2446 static int match_fragment(struct apply_state
*state
,
2448 struct image
*preimage
,
2449 struct image
*postimage
,
2450 unsigned long current
,
2453 int match_beginning
, int match_end
)
2456 char *fixed_buf
, *buf
, *orig
, *target
;
2457 struct strbuf fixed
;
2458 size_t fixed_len
, postlen
;
2461 if (preimage
->nr
+ current_lno
<= img
->nr
) {
2463 * The hunk falls within the boundaries of img.
2465 preimage_limit
= preimage
->nr
;
2466 if (match_end
&& (preimage
->nr
+ current_lno
!= img
->nr
))
2468 } else if (state
->ws_error_action
== correct_ws_error
&&
2469 (ws_rule
& WS_BLANK_AT_EOF
)) {
2471 * This hunk extends beyond the end of img, and we are
2472 * removing blank lines at the end of the file. This
2473 * many lines from the beginning of the preimage must
2474 * match with img, and the remainder of the preimage
2477 preimage_limit
= img
->nr
- current_lno
;
2480 * The hunk extends beyond the end of the img and
2481 * we are not removing blanks at the end, so we
2482 * should reject the hunk at this position.
2487 if (match_beginning
&& current_lno
)
2490 /* Quick hash check */
2491 for (i
= 0; i
< preimage_limit
; i
++)
2492 if ((img
->line
[current_lno
+ i
].flag
& LINE_PATCHED
) ||
2493 (preimage
->line
[i
].hash
!= img
->line
[current_lno
+ i
].hash
))
2496 if (preimage_limit
== preimage
->nr
) {
2498 * Do we have an exact match? If we were told to match
2499 * at the end, size must be exactly at current+fragsize,
2500 * otherwise current+fragsize must be still within the preimage,
2501 * and either case, the old piece should match the preimage
2505 ? (current
+ preimage
->len
== img
->len
)
2506 : (current
+ preimage
->len
<= img
->len
)) &&
2507 !memcmp(img
->buf
+ current
, preimage
->buf
, preimage
->len
))
2511 * The preimage extends beyond the end of img, so
2512 * there cannot be an exact match.
2514 * There must be one non-blank context line that match
2515 * a line before the end of img.
2519 buf
= preimage
->buf
;
2521 for (i
= 0; i
< preimage_limit
; i
++)
2522 buf_end
+= preimage
->line
[i
].len
;
2524 for ( ; buf
< buf_end
; buf
++)
2532 * No exact match. If we are ignoring whitespace, run a line-by-line
2533 * fuzzy matching. We collect all the line length information because
2534 * we need it to adjust whitespace if we match.
2536 if (state
->ws_ignore_action
== ignore_ws_change
)
2537 return line_by_line_fuzzy_match(img
, preimage
, postimage
,
2538 current
, current_lno
, preimage_limit
);
2540 if (state
->ws_error_action
!= correct_ws_error
)
2544 * The hunk does not apply byte-by-byte, but the hash says
2545 * it might with whitespace fuzz. We weren't asked to
2546 * ignore whitespace, we were asked to correct whitespace
2547 * errors, so let's try matching after whitespace correction.
2549 * While checking the preimage against the target, whitespace
2550 * errors in both fixed, we count how large the corresponding
2551 * postimage needs to be. The postimage prepared by
2552 * apply_one_fragment() has whitespace errors fixed on added
2553 * lines already, but the common lines were propagated as-is,
2554 * which may become longer when their whitespace errors are
2558 /* First count added lines in postimage */
2560 for (i
= 0; i
< postimage
->nr
; i
++) {
2561 if (!(postimage
->line
[i
].flag
& LINE_COMMON
))
2562 postlen
+= postimage
->line
[i
].len
;
2566 * The preimage may extend beyond the end of the file,
2567 * but in this loop we will only handle the part of the
2568 * preimage that falls within the file.
2570 strbuf_init(&fixed
, preimage
->len
+ 1);
2571 orig
= preimage
->buf
;
2572 target
= img
->buf
+ current
;
2573 for (i
= 0; i
< preimage_limit
; i
++) {
2574 size_t oldlen
= preimage
->line
[i
].len
;
2575 size_t tgtlen
= img
->line
[current_lno
+ i
].len
;
2576 size_t fixstart
= fixed
.len
;
2577 struct strbuf tgtfix
;
2580 /* Try fixing the line in the preimage */
2581 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2583 /* Try fixing the line in the target */
2584 strbuf_init(&tgtfix
, tgtlen
);
2585 ws_fix_copy(&tgtfix
, target
, tgtlen
, ws_rule
, NULL
);
2588 * If they match, either the preimage was based on
2589 * a version before our tree fixed whitespace breakage,
2590 * or we are lacking a whitespace-fix patch the tree
2591 * the preimage was based on already had (i.e. target
2592 * has whitespace breakage, the preimage doesn't).
2593 * In either case, we are fixing the whitespace breakages
2594 * so we might as well take the fix together with their
2597 match
= (tgtfix
.len
== fixed
.len
- fixstart
&&
2598 !memcmp(tgtfix
.buf
, fixed
.buf
+ fixstart
,
2599 fixed
.len
- fixstart
));
2601 /* Add the length if this is common with the postimage */
2602 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2603 postlen
+= tgtfix
.len
;
2605 strbuf_release(&tgtfix
);
2615 * Now handle the lines in the preimage that falls beyond the
2616 * end of the file (if any). They will only match if they are
2617 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2620 for ( ; i
< preimage
->nr
; i
++) {
2621 size_t fixstart
= fixed
.len
; /* start of the fixed preimage */
2622 size_t oldlen
= preimage
->line
[i
].len
;
2625 /* Try fixing the line in the preimage */
2626 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2628 for (j
= fixstart
; j
< fixed
.len
; j
++)
2629 if (!isspace(fixed
.buf
[j
]))
2636 * Yes, the preimage is based on an older version that still
2637 * has whitespace breakages unfixed, and fixing them makes the
2638 * hunk match. Update the context lines in the postimage.
2640 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2641 if (postlen
< postimage
->len
)
2643 update_pre_post_images(preimage
, postimage
,
2644 fixed_buf
, fixed_len
, postlen
);
2648 strbuf_release(&fixed
);
2652 static int find_pos(struct apply_state
*state
,
2654 struct image
*preimage
,
2655 struct image
*postimage
,
2658 int match_beginning
, int match_end
)
2661 unsigned long backwards
, forwards
, current
;
2662 int backwards_lno
, forwards_lno
, current_lno
;
2665 * If match_beginning or match_end is specified, there is no
2666 * point starting from a wrong line that will never match and
2667 * wander around and wait for a match at the specified end.
2669 if (match_beginning
)
2672 line
= img
->nr
- preimage
->nr
;
2675 * Because the comparison is unsigned, the following test
2676 * will also take care of a negative line number that can
2677 * result when match_end and preimage is larger than the target.
2679 if ((size_t) line
> img
->nr
)
2683 for (i
= 0; i
< line
; i
++)
2684 current
+= img
->line
[i
].len
;
2687 * There's probably some smart way to do this, but I'll leave
2688 * that to the smart and beautiful people. I'm simple and stupid.
2690 backwards
= current
;
2691 backwards_lno
= line
;
2693 forwards_lno
= line
;
2696 for (i
= 0; ; i
++) {
2697 if (match_fragment(state
, img
, preimage
, postimage
,
2698 current
, current_lno
, ws_rule
,
2699 match_beginning
, match_end
))
2703 if (backwards_lno
== 0 && forwards_lno
== img
->nr
)
2707 if (backwards_lno
== 0) {
2712 backwards
-= img
->line
[backwards_lno
].len
;
2713 current
= backwards
;
2714 current_lno
= backwards_lno
;
2716 if (forwards_lno
== img
->nr
) {
2720 forwards
+= img
->line
[forwards_lno
].len
;
2723 current_lno
= forwards_lno
;
2730 static void remove_first_line(struct image
*img
)
2732 img
->buf
+= img
->line
[0].len
;
2733 img
->len
-= img
->line
[0].len
;
2738 static void remove_last_line(struct image
*img
)
2740 img
->len
-= img
->line
[--img
->nr
].len
;
2744 * The change from "preimage" and "postimage" has been found to
2745 * apply at applied_pos (counts in line numbers) in "img".
2746 * Update "img" to remove "preimage" and replace it with "postimage".
2748 static void update_image(struct apply_state
*state
,
2751 struct image
*preimage
,
2752 struct image
*postimage
)
2755 * remove the copy of preimage at offset in img
2756 * and replace it with postimage
2759 size_t remove_count
, insert_count
, applied_at
= 0;
2764 * If we are removing blank lines at the end of img,
2765 * the preimage may extend beyond the end.
2766 * If that is the case, we must be careful only to
2767 * remove the part of the preimage that falls within
2768 * the boundaries of img. Initialize preimage_limit
2769 * to the number of lines in the preimage that falls
2770 * within the boundaries.
2772 preimage_limit
= preimage
->nr
;
2773 if (preimage_limit
> img
->nr
- applied_pos
)
2774 preimage_limit
= img
->nr
- applied_pos
;
2776 for (i
= 0; i
< applied_pos
; i
++)
2777 applied_at
+= img
->line
[i
].len
;
2780 for (i
= 0; i
< preimage_limit
; i
++)
2781 remove_count
+= img
->line
[applied_pos
+ i
].len
;
2782 insert_count
= postimage
->len
;
2784 /* Adjust the contents */
2785 result
= xmalloc(st_add3(st_sub(img
->len
, remove_count
), insert_count
, 1));
2786 memcpy(result
, img
->buf
, applied_at
);
2787 memcpy(result
+ applied_at
, postimage
->buf
, postimage
->len
);
2788 memcpy(result
+ applied_at
+ postimage
->len
,
2789 img
->buf
+ (applied_at
+ remove_count
),
2790 img
->len
- (applied_at
+ remove_count
));
2793 img
->len
+= insert_count
- remove_count
;
2794 result
[img
->len
] = '\0';
2796 /* Adjust the line table */
2797 nr
= img
->nr
+ postimage
->nr
- preimage_limit
;
2798 if (preimage_limit
< postimage
->nr
) {
2800 * NOTE: this knows that we never call remove_first_line()
2801 * on anything other than pre/post image.
2803 REALLOC_ARRAY(img
->line
, nr
);
2804 img
->line_allocated
= img
->line
;
2806 if (preimage_limit
!= postimage
->nr
)
2807 MOVE_ARRAY(img
->line
+ applied_pos
+ postimage
->nr
,
2808 img
->line
+ applied_pos
+ preimage_limit
,
2809 img
->nr
- (applied_pos
+ preimage_limit
));
2810 COPY_ARRAY(img
->line
+ applied_pos
, postimage
->line
, postimage
->nr
);
2811 if (!state
->allow_overlap
)
2812 for (i
= 0; i
< postimage
->nr
; i
++)
2813 img
->line
[applied_pos
+ i
].flag
|= LINE_PATCHED
;
2818 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2819 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2820 * replace the part of "img" with "postimage" text.
2822 static int apply_one_fragment(struct apply_state
*state
,
2823 struct image
*img
, struct fragment
*frag
,
2824 int inaccurate_eof
, unsigned ws_rule
,
2827 int match_beginning
, match_end
;
2828 const char *patch
= frag
->patch
;
2829 int size
= frag
->size
;
2830 char *old
, *oldlines
;
2831 struct strbuf newlines
;
2832 int new_blank_lines_at_end
= 0;
2833 int found_new_blank_lines_at_end
= 0;
2834 int hunk_linenr
= frag
->linenr
;
2835 unsigned long leading
, trailing
;
2836 int pos
, applied_pos
;
2837 struct image preimage
;
2838 struct image postimage
;
2840 memset(&preimage
, 0, sizeof(preimage
));
2841 memset(&postimage
, 0, sizeof(postimage
));
2842 oldlines
= xmalloc(size
);
2843 strbuf_init(&newlines
, size
);
2848 int len
= linelen(patch
, size
);
2850 int added_blank_line
= 0;
2851 int is_blank_context
= 0;
2858 * "plen" is how much of the line we should use for
2859 * the actual patch data. Normally we just remove the
2860 * first character on the line, but if the line is
2861 * followed by "\ No newline", then we also remove the
2862 * last one (which is the newline, of course).
2865 if (len
< size
&& patch
[len
] == '\\')
2868 if (state
->apply_in_reverse
) {
2871 else if (first
== '+')
2877 /* Newer GNU diff, empty context line */
2879 /* ... followed by '\No newline'; nothing */
2882 strbuf_addch(&newlines
, '\n');
2883 add_line_info(&preimage
, "\n", 1, LINE_COMMON
);
2884 add_line_info(&postimage
, "\n", 1, LINE_COMMON
);
2885 is_blank_context
= 1;
2888 if (plen
&& (ws_rule
& WS_BLANK_AT_EOF
) &&
2889 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2890 is_blank_context
= 1;
2893 memcpy(old
, patch
+ 1, plen
);
2894 add_line_info(&preimage
, old
, plen
,
2895 (first
== ' ' ? LINE_COMMON
: 0));
2901 /* --no-add does not add new lines */
2902 if (first
== '+' && state
->no_add
)
2905 start
= newlines
.len
;
2907 !state
->whitespace_error
||
2908 state
->ws_error_action
!= correct_ws_error
) {
2909 strbuf_add(&newlines
, patch
+ 1, plen
);
2912 ws_fix_copy(&newlines
, patch
+ 1, plen
, ws_rule
, &state
->applied_after_fixing_ws
);
2914 add_line_info(&postimage
, newlines
.buf
+ start
, newlines
.len
- start
,
2915 (first
== '+' ? 0 : LINE_COMMON
));
2917 (ws_rule
& WS_BLANK_AT_EOF
) &&
2918 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2919 added_blank_line
= 1;
2921 case '@': case '\\':
2922 /* Ignore it, we already handled it */
2925 if (state
->apply_verbosity
> verbosity_normal
)
2926 error(_("invalid start of line: '%c'"), first
);
2930 if (added_blank_line
) {
2931 if (!new_blank_lines_at_end
)
2932 found_new_blank_lines_at_end
= hunk_linenr
;
2933 new_blank_lines_at_end
++;
2935 else if (is_blank_context
)
2938 new_blank_lines_at_end
= 0;
2943 if (inaccurate_eof
&&
2944 old
> oldlines
&& old
[-1] == '\n' &&
2945 newlines
.len
> 0 && newlines
.buf
[newlines
.len
- 1] == '\n') {
2947 strbuf_setlen(&newlines
, newlines
.len
- 1);
2948 preimage
.line_allocated
[preimage
.nr
- 1].len
--;
2949 postimage
.line_allocated
[postimage
.nr
- 1].len
--;
2952 leading
= frag
->leading
;
2953 trailing
= frag
->trailing
;
2956 * A hunk to change lines at the beginning would begin with
2958 * but we need to be careful. -U0 that inserts before the second
2959 * line also has this pattern.
2961 * And a hunk to add to an empty file would begin with
2964 * In other words, a hunk that is (frag->oldpos <= 1) with or
2965 * without leading context must match at the beginning.
2967 match_beginning
= (!frag
->oldpos
||
2968 (frag
->oldpos
== 1 && !state
->unidiff_zero
));
2971 * A hunk without trailing lines must match at the end.
2972 * However, we simply cannot tell if a hunk must match end
2973 * from the lack of trailing lines if the patch was generated
2974 * with unidiff without any context.
2976 match_end
= !state
->unidiff_zero
&& !trailing
;
2978 pos
= frag
->newpos
? (frag
->newpos
- 1) : 0;
2979 preimage
.buf
= oldlines
;
2980 preimage
.len
= old
- oldlines
;
2981 postimage
.buf
= newlines
.buf
;
2982 postimage
.len
= newlines
.len
;
2983 preimage
.line
= preimage
.line_allocated
;
2984 postimage
.line
= postimage
.line_allocated
;
2988 applied_pos
= find_pos(state
, img
, &preimage
, &postimage
, pos
,
2989 ws_rule
, match_beginning
, match_end
);
2991 if (applied_pos
>= 0)
2994 /* Am I at my context limits? */
2995 if ((leading
<= state
->p_context
) && (trailing
<= state
->p_context
))
2997 if (match_beginning
|| match_end
) {
2998 match_beginning
= match_end
= 0;
3003 * Reduce the number of context lines; reduce both
3004 * leading and trailing if they are equal otherwise
3005 * just reduce the larger context.
3007 if (leading
>= trailing
) {
3008 remove_first_line(&preimage
);
3009 remove_first_line(&postimage
);
3013 if (trailing
> leading
) {
3014 remove_last_line(&preimage
);
3015 remove_last_line(&postimage
);
3020 if (applied_pos
>= 0) {
3021 if (new_blank_lines_at_end
&&
3022 preimage
.nr
+ applied_pos
>= img
->nr
&&
3023 (ws_rule
& WS_BLANK_AT_EOF
) &&
3024 state
->ws_error_action
!= nowarn_ws_error
) {
3025 record_ws_error(state
, WS_BLANK_AT_EOF
, "+", 1,
3026 found_new_blank_lines_at_end
);
3027 if (state
->ws_error_action
== correct_ws_error
) {
3028 while (new_blank_lines_at_end
--)
3029 remove_last_line(&postimage
);
3032 * We would want to prevent write_out_results()
3033 * from taking place in apply_patch() that follows
3034 * the callchain led us here, which is:
3035 * apply_patch->check_patch_list->check_patch->
3036 * apply_data->apply_fragments->apply_one_fragment
3038 if (state
->ws_error_action
== die_on_ws_error
)
3042 if (state
->apply_verbosity
> verbosity_normal
&& applied_pos
!= pos
) {
3043 int offset
= applied_pos
- pos
;
3044 if (state
->apply_in_reverse
)
3045 offset
= 0 - offset
;
3047 Q_("Hunk #%d succeeded at %d (offset %d line).",
3048 "Hunk #%d succeeded at %d (offset %d lines).",
3050 nth_fragment
, applied_pos
+ 1, offset
);
3054 * Warn if it was necessary to reduce the number
3057 if ((leading
!= frag
->leading
||
3058 trailing
!= frag
->trailing
) && state
->apply_verbosity
> verbosity_silent
)
3059 fprintf_ln(stderr
, _("Context reduced to (%ld/%ld)"
3060 " to apply fragment at %d"),
3061 leading
, trailing
, applied_pos
+1);
3062 update_image(state
, img
, applied_pos
, &preimage
, &postimage
);
3064 if (state
->apply_verbosity
> verbosity_normal
)
3065 error(_("while searching for:\n%.*s"),
3066 (int)(old
- oldlines
), oldlines
);
3071 strbuf_release(&newlines
);
3072 free(preimage
.line_allocated
);
3073 free(postimage
.line_allocated
);
3075 return (applied_pos
< 0);
3078 static int apply_binary_fragment(struct apply_state
*state
,
3080 struct patch
*patch
)
3082 struct fragment
*fragment
= patch
->fragments
;
3087 return error(_("missing binary patch data for '%s'"),
3092 /* Binary patch is irreversible without the optional second hunk */
3093 if (state
->apply_in_reverse
) {
3094 if (!fragment
->next
)
3095 return error(_("cannot reverse-apply a binary patch "
3096 "without the reverse hunk to '%s'"),
3098 ? patch
->new_name
: patch
->old_name
);
3099 fragment
= fragment
->next
;
3101 switch (fragment
->binary_patch_method
) {
3102 case BINARY_DELTA_DEFLATED
:
3103 dst
= patch_delta(img
->buf
, img
->len
, fragment
->patch
,
3104 fragment
->size
, &len
);
3111 case BINARY_LITERAL_DEFLATED
:
3113 img
->len
= fragment
->size
;
3114 img
->buf
= xmemdupz(fragment
->patch
, img
->len
);
3121 * Replace "img" with the result of applying the binary patch.
3122 * The binary patch data itself in patch->fragment is still kept
3123 * but the preimage prepared by the caller in "img" is freed here
3124 * or in the helper function apply_binary_fragment() this calls.
3126 static int apply_binary(struct apply_state
*state
,
3128 struct patch
*patch
)
3130 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3131 struct object_id oid
;
3132 const unsigned hexsz
= the_hash_algo
->hexsz
;
3135 * For safety, we require patch index line to contain
3136 * full hex textual object ID for old and new, at least for now.
3138 if (strlen(patch
->old_oid_prefix
) != hexsz
||
3139 strlen(patch
->new_oid_prefix
) != hexsz
||
3140 get_oid_hex(patch
->old_oid_prefix
, &oid
) ||
3141 get_oid_hex(patch
->new_oid_prefix
, &oid
))
3142 return error(_("cannot apply binary patch to '%s' "
3143 "without full index line"), name
);
3145 if (patch
->old_name
) {
3147 * See if the old one matches what the patch
3150 hash_object_file(img
->buf
, img
->len
, blob_type
, &oid
);
3151 if (strcmp(oid_to_hex(&oid
), patch
->old_oid_prefix
))
3152 return error(_("the patch applies to '%s' (%s), "
3153 "which does not match the "
3154 "current contents."),
3155 name
, oid_to_hex(&oid
));
3158 /* Otherwise, the old one must be empty. */
3160 return error(_("the patch applies to an empty "
3161 "'%s' but it is not empty"), name
);
3164 get_oid_hex(patch
->new_oid_prefix
, &oid
);
3165 if (is_null_oid(&oid
)) {
3167 return 0; /* deletion patch */
3170 if (has_object_file(&oid
)) {
3171 /* We already have the postimage */
3172 enum object_type type
;
3176 result
= read_object_file(&oid
, &type
, &size
);
3178 return error(_("the necessary postimage %s for "
3179 "'%s' cannot be read"),
3180 patch
->new_oid_prefix
, name
);
3186 * We have verified buf matches the preimage;
3187 * apply the patch data to it, which is stored
3188 * in the patch->fragments->{patch,size}.
3190 if (apply_binary_fragment(state
, img
, patch
))
3191 return error(_("binary patch does not apply to '%s'"),
3194 /* verify that the result matches */
3195 hash_object_file(img
->buf
, img
->len
, blob_type
, &oid
);
3196 if (strcmp(oid_to_hex(&oid
), patch
->new_oid_prefix
))
3197 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3198 name
, patch
->new_oid_prefix
, oid_to_hex(&oid
));
3204 static int apply_fragments(struct apply_state
*state
, struct image
*img
, struct patch
*patch
)
3206 struct fragment
*frag
= patch
->fragments
;
3207 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3208 unsigned ws_rule
= patch
->ws_rule
;
3209 unsigned inaccurate_eof
= patch
->inaccurate_eof
;
3212 if (patch
->is_binary
)
3213 return apply_binary(state
, img
, patch
);
3217 if (apply_one_fragment(state
, img
, frag
, inaccurate_eof
, ws_rule
, nth
)) {
3218 error(_("patch failed: %s:%ld"), name
, frag
->oldpos
);
3219 if (!state
->apply_with_reject
)
3228 static int read_blob_object(struct strbuf
*buf
, const struct object_id
*oid
, unsigned mode
)
3230 if (S_ISGITLINK(mode
)) {
3231 strbuf_grow(buf
, 100);
3232 strbuf_addf(buf
, "Subproject commit %s\n", oid_to_hex(oid
));
3234 enum object_type type
;
3238 result
= read_object_file(oid
, &type
, &sz
);
3241 /* XXX read_sha1_file NUL-terminates */
3242 strbuf_attach(buf
, result
, sz
, sz
+ 1);
3247 static int read_file_or_gitlink(const struct cache_entry
*ce
, struct strbuf
*buf
)
3251 return read_blob_object(buf
, &ce
->oid
, ce
->ce_mode
);
3254 static struct patch
*in_fn_table(struct apply_state
*state
, const char *name
)
3256 struct string_list_item
*item
;
3261 item
= string_list_lookup(&state
->fn_table
, name
);
3263 return (struct patch
*)item
->util
;
3269 * item->util in the filename table records the status of the path.
3270 * Usually it points at a patch (whose result records the contents
3271 * of it after applying it), but it could be PATH_WAS_DELETED for a
3272 * path that a previously applied patch has already removed, or
3273 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3275 * The latter is needed to deal with a case where two paths A and B
3276 * are swapped by first renaming A to B and then renaming B to A;
3277 * moving A to B should not be prevented due to presence of B as we
3278 * will remove it in a later patch.
3280 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3281 #define PATH_WAS_DELETED ((struct patch *) -1)
3283 static int to_be_deleted(struct patch
*patch
)
3285 return patch
== PATH_TO_BE_DELETED
;
3288 static int was_deleted(struct patch
*patch
)
3290 return patch
== PATH_WAS_DELETED
;
3293 static void add_to_fn_table(struct apply_state
*state
, struct patch
*patch
)
3295 struct string_list_item
*item
;
3298 * Always add new_name unless patch is a deletion
3299 * This should cover the cases for normal diffs,
3300 * file creations and copies
3302 if (patch
->new_name
!= NULL
) {
3303 item
= string_list_insert(&state
->fn_table
, patch
->new_name
);
3308 * store a failure on rename/deletion cases because
3309 * later chunks shouldn't patch old names
3311 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3312 item
= string_list_insert(&state
->fn_table
, patch
->old_name
);
3313 item
->util
= PATH_WAS_DELETED
;
3317 static void prepare_fn_table(struct apply_state
*state
, struct patch
*patch
)
3320 * store information about incoming file deletion
3323 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3324 struct string_list_item
*item
;
3325 item
= string_list_insert(&state
->fn_table
, patch
->old_name
);
3326 item
->util
= PATH_TO_BE_DELETED
;
3328 patch
= patch
->next
;
3332 static int checkout_target(struct index_state
*istate
,
3333 struct cache_entry
*ce
, struct stat
*st
)
3335 struct checkout costate
= CHECKOUT_INIT
;
3337 costate
.refresh_cache
= 1;
3338 costate
.istate
= istate
;
3339 if (checkout_entry(ce
, &costate
, NULL
, NULL
) ||
3340 lstat(ce
->name
, st
))
3341 return error(_("cannot checkout %s"), ce
->name
);
3345 static struct patch
*previous_patch(struct apply_state
*state
,
3346 struct patch
*patch
,
3349 struct patch
*previous
;
3352 if (patch
->is_copy
|| patch
->is_rename
)
3353 return NULL
; /* "git" patches do not depend on the order */
3355 previous
= in_fn_table(state
, patch
->old_name
);
3359 if (to_be_deleted(previous
))
3360 return NULL
; /* the deletion hasn't happened yet */
3362 if (was_deleted(previous
))
3368 static int verify_index_match(struct apply_state
*state
,
3369 const struct cache_entry
*ce
,
3372 if (S_ISGITLINK(ce
->ce_mode
)) {
3373 if (!S_ISDIR(st
->st_mode
))
3377 return ie_match_stat(state
->repo
->index
, ce
, st
,
3378 CE_MATCH_IGNORE_VALID
| CE_MATCH_IGNORE_SKIP_WORKTREE
);
3381 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3383 static int load_patch_target(struct apply_state
*state
,
3385 const struct cache_entry
*ce
,
3387 struct patch
*patch
,
3389 unsigned expected_mode
)
3391 if (state
->cached
|| state
->check_index
) {
3392 if (read_file_or_gitlink(ce
, buf
))
3393 return error(_("failed to read %s"), name
);
3395 if (S_ISGITLINK(expected_mode
)) {
3397 return read_file_or_gitlink(ce
, buf
);
3399 return SUBMODULE_PATCH_WITHOUT_INDEX
;
3400 } else if (has_symlink_leading_path(name
, strlen(name
))) {
3401 return error(_("reading from '%s' beyond a symbolic link"), name
);
3403 if (read_old_data(st
, patch
, name
, buf
))
3404 return error(_("failed to read %s"), name
);
3411 * We are about to apply "patch"; populate the "image" with the
3412 * current version we have, from the working tree or from the index,
3413 * depending on the situation e.g. --cached/--index. If we are
3414 * applying a non-git patch that incrementally updates the tree,
3415 * we read from the result of a previous diff.
3417 static int load_preimage(struct apply_state
*state
,
3418 struct image
*image
,
3419 struct patch
*patch
, struct stat
*st
,
3420 const struct cache_entry
*ce
)
3422 struct strbuf buf
= STRBUF_INIT
;
3425 struct patch
*previous
;
3428 previous
= previous_patch(state
, patch
, &status
);
3430 return error(_("path %s has been renamed/deleted"),
3433 /* We have a patched copy in memory; use that. */
3434 strbuf_add(&buf
, previous
->result
, previous
->resultsize
);
3436 status
= load_patch_target(state
, &buf
, ce
, st
, patch
,
3437 patch
->old_name
, patch
->old_mode
);
3440 else if (status
== SUBMODULE_PATCH_WITHOUT_INDEX
) {
3442 * There is no way to apply subproject
3443 * patch without looking at the index.
3444 * NEEDSWORK: shouldn't this be flagged
3447 free_fragment_list(patch
->fragments
);
3448 patch
->fragments
= NULL
;
3449 } else if (status
) {
3450 return error(_("failed to read %s"), patch
->old_name
);
3454 img
= strbuf_detach(&buf
, &len
);
3455 prepare_image(image
, img
, len
, !patch
->is_binary
);
3459 static int three_way_merge(struct apply_state
*state
,
3460 struct image
*image
,
3462 const struct object_id
*base
,
3463 const struct object_id
*ours
,
3464 const struct object_id
*theirs
)
3466 mmfile_t base_file
, our_file
, their_file
;
3467 mmbuffer_t result
= { NULL
};
3470 read_mmblob(&base_file
, base
);
3471 read_mmblob(&our_file
, ours
);
3472 read_mmblob(&their_file
, theirs
);
3473 status
= ll_merge(&result
, path
,
3476 &their_file
, "theirs",
3479 free(base_file
.ptr
);
3481 free(their_file
.ptr
);
3482 if (status
< 0 || !result
.ptr
) {
3487 image
->buf
= result
.ptr
;
3488 image
->len
= result
.size
;
3494 * When directly falling back to add/add three-way merge, we read from
3495 * the current contents of the new_name. In no cases other than that
3496 * this function will be called.
3498 static int load_current(struct apply_state
*state
,
3499 struct image
*image
,
3500 struct patch
*patch
)
3502 struct strbuf buf
= STRBUF_INIT
;
3507 struct cache_entry
*ce
;
3508 char *name
= patch
->new_name
;
3509 unsigned mode
= patch
->new_mode
;
3512 BUG("patch to %s is not a creation", patch
->old_name
);
3514 pos
= index_name_pos(state
->repo
->index
, name
, strlen(name
));
3516 return error(_("%s: does not exist in index"), name
);
3517 ce
= state
->repo
->index
->cache
[pos
];
3518 if (lstat(name
, &st
)) {
3519 if (errno
!= ENOENT
)
3520 return error_errno("%s", name
);
3521 if (checkout_target(state
->repo
->index
, ce
, &st
))
3524 if (verify_index_match(state
, ce
, &st
))
3525 return error(_("%s: does not match index"), name
);
3527 status
= load_patch_target(state
, &buf
, ce
, &st
, patch
, name
, mode
);
3532 img
= strbuf_detach(&buf
, &len
);
3533 prepare_image(image
, img
, len
, !patch
->is_binary
);
3537 static int try_threeway(struct apply_state
*state
,
3538 struct image
*image
,
3539 struct patch
*patch
,
3541 const struct cache_entry
*ce
)
3543 struct object_id pre_oid
, post_oid
, our_oid
;
3544 struct strbuf buf
= STRBUF_INIT
;
3548 struct image tmp_image
;
3550 /* No point falling back to 3-way merge in these cases */
3551 if (patch
->is_delete
||
3552 S_ISGITLINK(patch
->old_mode
) || S_ISGITLINK(patch
->new_mode
))
3555 /* Preimage the patch was prepared for */
3557 write_object_file("", 0, blob_type
, &pre_oid
);
3558 else if (get_oid(patch
->old_oid_prefix
, &pre_oid
) ||
3559 read_blob_object(&buf
, &pre_oid
, patch
->old_mode
))
3560 return error(_("repository lacks the necessary blob to fall back on 3-way merge."));
3562 if (state
->apply_verbosity
> verbosity_silent
)
3563 fprintf(stderr
, _("Falling back to three-way merge...\n"));
3565 img
= strbuf_detach(&buf
, &len
);
3566 prepare_image(&tmp_image
, img
, len
, 1);
3567 /* Apply the patch to get the post image */
3568 if (apply_fragments(state
, &tmp_image
, patch
) < 0) {
3569 clear_image(&tmp_image
);
3572 /* post_oid is theirs */
3573 write_object_file(tmp_image
.buf
, tmp_image
.len
, blob_type
, &post_oid
);
3574 clear_image(&tmp_image
);
3576 /* our_oid is ours */
3577 if (patch
->is_new
) {
3578 if (load_current(state
, &tmp_image
, patch
))
3579 return error(_("cannot read the current contents of '%s'"),
3582 if (load_preimage(state
, &tmp_image
, patch
, st
, ce
))
3583 return error(_("cannot read the current contents of '%s'"),
3586 write_object_file(tmp_image
.buf
, tmp_image
.len
, blob_type
, &our_oid
);
3587 clear_image(&tmp_image
);
3589 /* in-core three-way merge between post and our using pre as base */
3590 status
= three_way_merge(state
, image
, patch
->new_name
,
3591 &pre_oid
, &our_oid
, &post_oid
);
3593 if (state
->apply_verbosity
> verbosity_silent
)
3595 _("Failed to fall back on three-way merge...\n"));
3600 patch
->conflicted_threeway
= 1;
3602 oidclr(&patch
->threeway_stage
[0]);
3604 oidcpy(&patch
->threeway_stage
[0], &pre_oid
);
3605 oidcpy(&patch
->threeway_stage
[1], &our_oid
);
3606 oidcpy(&patch
->threeway_stage
[2], &post_oid
);
3607 if (state
->apply_verbosity
> verbosity_silent
)
3609 _("Applied patch to '%s' with conflicts.\n"),
3612 if (state
->apply_verbosity
> verbosity_silent
)
3614 _("Applied patch to '%s' cleanly.\n"),
3620 static int apply_data(struct apply_state
*state
, struct patch
*patch
,
3621 struct stat
*st
, const struct cache_entry
*ce
)
3625 if (load_preimage(state
, &image
, patch
, st
, ce
) < 0)
3628 if (patch
->direct_to_threeway
||
3629 apply_fragments(state
, &image
, patch
) < 0) {
3630 /* Note: with --reject, apply_fragments() returns 0 */
3631 if (!state
->threeway
|| try_threeway(state
, &image
, patch
, st
, ce
) < 0)
3634 patch
->result
= image
.buf
;
3635 patch
->resultsize
= image
.len
;
3636 add_to_fn_table(state
, patch
);
3637 free(image
.line_allocated
);
3639 if (0 < patch
->is_delete
&& patch
->resultsize
)
3640 return error(_("removal patch leaves file contents"));
3646 * If "patch" that we are looking at modifies or deletes what we have,
3647 * we would want it not to lose any local modification we have, either
3648 * in the working tree or in the index.
3650 * This also decides if a non-git patch is a creation patch or a
3651 * modification to an existing empty file. We do not check the state
3652 * of the current tree for a creation patch in this function; the caller
3653 * check_patch() separately makes sure (and errors out otherwise) that
3654 * the path the patch creates does not exist in the current tree.
3656 static int check_preimage(struct apply_state
*state
,
3657 struct patch
*patch
,
3658 struct cache_entry
**ce
,
3661 const char *old_name
= patch
->old_name
;
3662 struct patch
*previous
= NULL
;
3663 int stat_ret
= 0, status
;
3664 unsigned st_mode
= 0;
3669 assert(patch
->is_new
<= 0);
3670 previous
= previous_patch(state
, patch
, &status
);
3673 return error(_("path %s has been renamed/deleted"), old_name
);
3675 st_mode
= previous
->new_mode
;
3676 } else if (!state
->cached
) {
3677 stat_ret
= lstat(old_name
, st
);
3678 if (stat_ret
&& errno
!= ENOENT
)
3679 return error_errno("%s", old_name
);
3682 if (state
->check_index
&& !previous
) {
3683 int pos
= index_name_pos(state
->repo
->index
, old_name
,
3686 if (patch
->is_new
< 0)
3688 return error(_("%s: does not exist in index"), old_name
);
3690 *ce
= state
->repo
->index
->cache
[pos
];
3692 if (checkout_target(state
->repo
->index
, *ce
, st
))
3695 if (!state
->cached
&& verify_index_match(state
, *ce
, st
))
3696 return error(_("%s: does not match index"), old_name
);
3698 st_mode
= (*ce
)->ce_mode
;
3699 } else if (stat_ret
< 0) {
3700 if (patch
->is_new
< 0)
3702 return error_errno("%s", old_name
);
3705 if (!state
->cached
&& !previous
)
3706 st_mode
= ce_mode_from_stat(*ce
, st
->st_mode
);
3708 if (patch
->is_new
< 0)
3710 if (!patch
->old_mode
)
3711 patch
->old_mode
= st_mode
;
3712 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
3713 return error(_("%s: wrong type"), old_name
);
3714 if (st_mode
!= patch
->old_mode
)
3715 warning(_("%s has type %o, expected %o"),
3716 old_name
, st_mode
, patch
->old_mode
);
3717 if (!patch
->new_mode
&& !patch
->is_delete
)
3718 patch
->new_mode
= st_mode
;
3723 patch
->is_delete
= 0;
3724 FREE_AND_NULL(patch
->old_name
);
3729 #define EXISTS_IN_INDEX 1
3730 #define EXISTS_IN_WORKTREE 2
3732 static int check_to_create(struct apply_state
*state
,
3733 const char *new_name
,
3738 if (state
->check_index
&&
3739 index_name_pos(state
->repo
->index
, new_name
, strlen(new_name
)) >= 0 &&
3741 return EXISTS_IN_INDEX
;
3745 if (!lstat(new_name
, &nst
)) {
3746 if (S_ISDIR(nst
.st_mode
) || ok_if_exists
)
3749 * A leading component of new_name might be a symlink
3750 * that is going to be removed with this patch, but
3751 * still pointing at somewhere that has the path.
3752 * In such a case, path "new_name" does not exist as
3753 * far as git is concerned.
3755 if (has_symlink_leading_path(new_name
, strlen(new_name
)))
3758 return EXISTS_IN_WORKTREE
;
3759 } else if (!is_missing_file_error(errno
)) {
3760 return error_errno("%s", new_name
);
3765 static uintptr_t register_symlink_changes(struct apply_state
*state
,
3769 struct string_list_item
*ent
;
3771 ent
= string_list_lookup(&state
->symlink_changes
, path
);
3773 ent
= string_list_insert(&state
->symlink_changes
, path
);
3774 ent
->util
= (void *)0;
3776 ent
->util
= (void *)(what
| ((uintptr_t)ent
->util
));
3777 return (uintptr_t)ent
->util
;
3780 static uintptr_t check_symlink_changes(struct apply_state
*state
, const char *path
)
3782 struct string_list_item
*ent
;
3784 ent
= string_list_lookup(&state
->symlink_changes
, path
);
3787 return (uintptr_t)ent
->util
;
3790 static void prepare_symlink_changes(struct apply_state
*state
, struct patch
*patch
)
3792 for ( ; patch
; patch
= patch
->next
) {
3793 if ((patch
->old_name
&& S_ISLNK(patch
->old_mode
)) &&
3794 (patch
->is_rename
|| patch
->is_delete
))
3795 /* the symlink at patch->old_name is removed */
3796 register_symlink_changes(state
, patch
->old_name
, APPLY_SYMLINK_GOES_AWAY
);
3798 if (patch
->new_name
&& S_ISLNK(patch
->new_mode
))
3799 /* the symlink at patch->new_name is created or remains */
3800 register_symlink_changes(state
, patch
->new_name
, APPLY_SYMLINK_IN_RESULT
);
3804 static int path_is_beyond_symlink_1(struct apply_state
*state
, struct strbuf
*name
)
3807 unsigned int change
;
3809 while (--name
->len
&& name
->buf
[name
->len
] != '/')
3810 ; /* scan backwards */
3813 name
->buf
[name
->len
] = '\0';
3814 change
= check_symlink_changes(state
, name
->buf
);
3815 if (change
& APPLY_SYMLINK_IN_RESULT
)
3817 if (change
& APPLY_SYMLINK_GOES_AWAY
)
3819 * This cannot be "return 0", because we may
3820 * see a new one created at a higher level.
3824 /* otherwise, check the preimage */
3825 if (state
->check_index
) {
3826 struct cache_entry
*ce
;
3828 ce
= index_file_exists(state
->repo
->index
, name
->buf
,
3829 name
->len
, ignore_case
);
3830 if (ce
&& S_ISLNK(ce
->ce_mode
))
3834 if (!lstat(name
->buf
, &st
) && S_ISLNK(st
.st_mode
))
3841 static int path_is_beyond_symlink(struct apply_state
*state
, const char *name_
)
3844 struct strbuf name
= STRBUF_INIT
;
3846 assert(*name_
!= '\0');
3847 strbuf_addstr(&name
, name_
);
3848 ret
= path_is_beyond_symlink_1(state
, &name
);
3849 strbuf_release(&name
);
3854 static int check_unsafe_path(struct patch
*patch
)
3856 const char *old_name
= NULL
;
3857 const char *new_name
= NULL
;
3858 if (patch
->is_delete
)
3859 old_name
= patch
->old_name
;
3860 else if (!patch
->is_new
&& !patch
->is_copy
)
3861 old_name
= patch
->old_name
;
3862 if (!patch
->is_delete
)
3863 new_name
= patch
->new_name
;
3865 if (old_name
&& !verify_path(old_name
, patch
->old_mode
))
3866 return error(_("invalid path '%s'"), old_name
);
3867 if (new_name
&& !verify_path(new_name
, patch
->new_mode
))
3868 return error(_("invalid path '%s'"), new_name
);
3873 * Check and apply the patch in-core; leave the result in patch->result
3874 * for the caller to write it out to the final destination.
3876 static int check_patch(struct apply_state
*state
, struct patch
*patch
)
3879 const char *old_name
= patch
->old_name
;
3880 const char *new_name
= patch
->new_name
;
3881 const char *name
= old_name
? old_name
: new_name
;
3882 struct cache_entry
*ce
= NULL
;
3883 struct patch
*tpatch
;
3887 patch
->rejected
= 1; /* we will drop this after we succeed */
3889 status
= check_preimage(state
, patch
, &ce
, &st
);
3892 old_name
= patch
->old_name
;
3895 * A type-change diff is always split into a patch to delete
3896 * old, immediately followed by a patch to create new (see
3897 * diff.c::run_diff()); in such a case it is Ok that the entry
3898 * to be deleted by the previous patch is still in the working
3899 * tree and in the index.
3901 * A patch to swap-rename between A and B would first rename A
3902 * to B and then rename B to A. While applying the first one,
3903 * the presence of B should not stop A from getting renamed to
3904 * B; ask to_be_deleted() about the later rename. Removal of
3905 * B and rename from A to B is handled the same way by asking
3908 if ((tpatch
= in_fn_table(state
, new_name
)) &&
3909 (was_deleted(tpatch
) || to_be_deleted(tpatch
)))
3915 ((0 < patch
->is_new
) || patch
->is_rename
|| patch
->is_copy
)) {
3916 int err
= check_to_create(state
, new_name
, ok_if_exists
);
3918 if (err
&& state
->threeway
) {
3919 patch
->direct_to_threeway
= 1;
3920 } else switch (err
) {
3923 case EXISTS_IN_INDEX
:
3924 return error(_("%s: already exists in index"), new_name
);
3926 case EXISTS_IN_WORKTREE
:
3927 return error(_("%s: already exists in working directory"),
3933 if (!patch
->new_mode
) {
3934 if (0 < patch
->is_new
)
3935 patch
->new_mode
= S_IFREG
| 0644;
3937 patch
->new_mode
= patch
->old_mode
;
3941 if (new_name
&& old_name
) {
3942 int same
= !strcmp(old_name
, new_name
);
3943 if (!patch
->new_mode
)
3944 patch
->new_mode
= patch
->old_mode
;
3945 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
) {
3947 return error(_("new mode (%o) of %s does not "
3948 "match old mode (%o)"),
3949 patch
->new_mode
, new_name
,
3952 return error(_("new mode (%o) of %s does not "
3953 "match old mode (%o) of %s"),
3954 patch
->new_mode
, new_name
,
3955 patch
->old_mode
, old_name
);
3959 if (!state
->unsafe_paths
&& check_unsafe_path(patch
))
3963 * An attempt to read from or delete a path that is beyond a
3964 * symbolic link will be prevented by load_patch_target() that
3965 * is called at the beginning of apply_data() so we do not
3966 * have to worry about a patch marked with "is_delete" bit
3967 * here. We however need to make sure that the patch result
3968 * is not deposited to a path that is beyond a symbolic link
3971 if (!patch
->is_delete
&& path_is_beyond_symlink(state
, patch
->new_name
))
3972 return error(_("affected file '%s' is beyond a symbolic link"),
3975 if (apply_data(state
, patch
, &st
, ce
) < 0)
3976 return error(_("%s: patch does not apply"), name
);
3977 patch
->rejected
= 0;
3981 static int check_patch_list(struct apply_state
*state
, struct patch
*patch
)
3985 prepare_symlink_changes(state
, patch
);
3986 prepare_fn_table(state
, patch
);
3989 if (state
->apply_verbosity
> verbosity_normal
)
3990 say_patch_name(stderr
,
3991 _("Checking patch %s..."), patch
);
3992 res
= check_patch(state
, patch
);
3996 patch
= patch
->next
;
4001 static int read_apply_cache(struct apply_state
*state
)
4003 if (state
->index_file
)
4004 return read_index_from(state
->repo
->index
, state
->index_file
,
4007 return repo_read_index(state
->repo
);
4010 /* This function tries to read the object name from the current index */
4011 static int get_current_oid(struct apply_state
*state
, const char *path
,
4012 struct object_id
*oid
)
4016 if (read_apply_cache(state
) < 0)
4018 pos
= index_name_pos(state
->repo
->index
, path
, strlen(path
));
4021 oidcpy(oid
, &state
->repo
->index
->cache
[pos
]->oid
);
4025 static int preimage_oid_in_gitlink_patch(struct patch
*p
, struct object_id
*oid
)
4028 * A usable gitlink patch has only one fragment (hunk) that looks like:
4030 * -Subproject commit <old sha1>
4031 * +Subproject commit <new sha1>
4034 * -Subproject commit <old sha1>
4035 * for a removal patch.
4037 struct fragment
*hunk
= p
->fragments
;
4038 static const char heading
[] = "-Subproject commit ";
4041 if (/* does the patch have only one hunk? */
4042 hunk
&& !hunk
->next
&&
4043 /* is its preimage one line? */
4044 hunk
->oldpos
== 1 && hunk
->oldlines
== 1 &&
4045 /* does preimage begin with the heading? */
4046 (preimage
= memchr(hunk
->patch
, '\n', hunk
->size
)) != NULL
&&
4047 starts_with(++preimage
, heading
) &&
4048 /* does it record full SHA-1? */
4049 !get_oid_hex(preimage
+ sizeof(heading
) - 1, oid
) &&
4050 preimage
[sizeof(heading
) + the_hash_algo
->hexsz
- 1] == '\n' &&
4051 /* does the abbreviated name on the index line agree with it? */
4052 starts_with(preimage
+ sizeof(heading
) - 1, p
->old_oid_prefix
))
4053 return 0; /* it all looks fine */
4055 /* we may have full object name on the index line */
4056 return get_oid_hex(p
->old_oid_prefix
, oid
);
4059 /* Build an index that contains just the files needed for a 3way merge */
4060 static int build_fake_ancestor(struct apply_state
*state
, struct patch
*list
)
4062 struct patch
*patch
;
4063 struct index_state result
= { NULL
};
4064 struct lock_file lock
= LOCK_INIT
;
4067 /* Once we start supporting the reverse patch, it may be
4068 * worth showing the new sha1 prefix, but until then...
4070 for (patch
= list
; patch
; patch
= patch
->next
) {
4071 struct object_id oid
;
4072 struct cache_entry
*ce
;
4075 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
4076 if (0 < patch
->is_new
)
4079 if (S_ISGITLINK(patch
->old_mode
)) {
4080 if (!preimage_oid_in_gitlink_patch(patch
, &oid
))
4081 ; /* ok, the textual part looks sane */
4083 return error(_("sha1 information is lacking or "
4084 "useless for submodule %s"), name
);
4085 } else if (!get_oid_blob(patch
->old_oid_prefix
, &oid
)) {
4087 } else if (!patch
->lines_added
&& !patch
->lines_deleted
) {
4088 /* mode-only change: update the current */
4089 if (get_current_oid(state
, patch
->old_name
, &oid
))
4090 return error(_("mode change for %s, which is not "
4091 "in current HEAD"), name
);
4093 return error(_("sha1 information is lacking or useless "
4096 ce
= make_cache_entry(&result
, patch
->old_mode
, &oid
, name
, 0, 0);
4098 return error(_("make_cache_entry failed for path '%s'"),
4100 if (add_index_entry(&result
, ce
, ADD_CACHE_OK_TO_ADD
)) {
4101 discard_cache_entry(ce
);
4102 return error(_("could not add %s to temporary index"),
4107 hold_lock_file_for_update(&lock
, state
->fake_ancestor
, LOCK_DIE_ON_ERROR
);
4108 res
= write_locked_index(&result
, &lock
, COMMIT_LOCK
);
4109 discard_index(&result
);
4112 return error(_("could not write temporary index to %s"),
4113 state
->fake_ancestor
);
4118 static void stat_patch_list(struct apply_state
*state
, struct patch
*patch
)
4120 int files
, adds
, dels
;
4122 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
4124 adds
+= patch
->lines_added
;
4125 dels
+= patch
->lines_deleted
;
4126 show_stats(state
, patch
);
4129 print_stat_summary(stdout
, files
, adds
, dels
);
4132 static void numstat_patch_list(struct apply_state
*state
,
4133 struct patch
*patch
)
4135 for ( ; patch
; patch
= patch
->next
) {
4137 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
4138 if (patch
->is_binary
)
4141 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
4142 write_name_quoted(name
, stdout
, state
->line_termination
);
4146 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
4149 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
4151 printf(" %s %s\n", newdelete
, name
);
4154 static void show_mode_change(struct patch
*p
, int show_name
)
4156 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
4158 printf(" mode change %06o => %06o %s\n",
4159 p
->old_mode
, p
->new_mode
, p
->new_name
);
4161 printf(" mode change %06o => %06o\n",
4162 p
->old_mode
, p
->new_mode
);
4166 static void show_rename_copy(struct patch
*p
)
4168 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
4169 const char *old_name
, *new_name
;
4171 /* Find common prefix */
4172 old_name
= p
->old_name
;
4173 new_name
= p
->new_name
;
4175 const char *slash_old
, *slash_new
;
4176 slash_old
= strchr(old_name
, '/');
4177 slash_new
= strchr(new_name
, '/');
4180 slash_old
- old_name
!= slash_new
- new_name
||
4181 memcmp(old_name
, new_name
, slash_new
- new_name
))
4183 old_name
= slash_old
+ 1;
4184 new_name
= slash_new
+ 1;
4186 /* p->old_name through old_name is the common prefix, and old_name and
4187 * new_name through the end of names are renames
4189 if (old_name
!= p
->old_name
)
4190 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
4191 (int)(old_name
- p
->old_name
), p
->old_name
,
4192 old_name
, new_name
, p
->score
);
4194 printf(" %s %s => %s (%d%%)\n", renamecopy
,
4195 p
->old_name
, p
->new_name
, p
->score
);
4196 show_mode_change(p
, 0);
4199 static void summary_patch_list(struct patch
*patch
)
4203 for (p
= patch
; p
; p
= p
->next
) {
4205 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
4206 else if (p
->is_delete
)
4207 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
4209 if (p
->is_rename
|| p
->is_copy
)
4210 show_rename_copy(p
);
4213 printf(" rewrite %s (%d%%)\n",
4214 p
->new_name
, p
->score
);
4215 show_mode_change(p
, 0);
4218 show_mode_change(p
, 1);
4224 static void patch_stats(struct apply_state
*state
, struct patch
*patch
)
4226 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
4228 if (lines
> state
->max_change
)
4229 state
->max_change
= lines
;
4230 if (patch
->old_name
) {
4231 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
4233 len
= strlen(patch
->old_name
);
4234 if (len
> state
->max_len
)
4235 state
->max_len
= len
;
4237 if (patch
->new_name
) {
4238 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
4240 len
= strlen(patch
->new_name
);
4241 if (len
> state
->max_len
)
4242 state
->max_len
= len
;
4246 static int remove_file(struct apply_state
*state
, struct patch
*patch
, int rmdir_empty
)
4248 if (state
->update_index
&& !state
->ita_only
) {
4249 if (remove_file_from_index(state
->repo
->index
, patch
->old_name
) < 0)
4250 return error(_("unable to remove %s from index"), patch
->old_name
);
4252 if (!state
->cached
) {
4253 if (!remove_or_warn(patch
->old_mode
, patch
->old_name
) && rmdir_empty
) {
4254 remove_path(patch
->old_name
);
4260 static int add_index_file(struct apply_state
*state
,
4267 struct cache_entry
*ce
;
4268 int namelen
= strlen(path
);
4270 ce
= make_empty_cache_entry(state
->repo
->index
, namelen
);
4271 memcpy(ce
->name
, path
, namelen
);
4272 ce
->ce_mode
= create_ce_mode(mode
);
4273 ce
->ce_flags
= create_ce_flags(0);
4274 ce
->ce_namelen
= namelen
;
4275 if (state
->ita_only
) {
4276 ce
->ce_flags
|= CE_INTENT_TO_ADD
;
4277 set_object_name_for_intent_to_add_entry(ce
);
4278 } else if (S_ISGITLINK(mode
)) {
4281 if (!skip_prefix(buf
, "Subproject commit ", &s
) ||
4282 get_oid_hex(s
, &ce
->oid
)) {
4283 discard_cache_entry(ce
);
4284 return error(_("corrupt patch for submodule %s"), path
);
4287 if (!state
->cached
) {
4288 if (lstat(path
, &st
) < 0) {
4289 discard_cache_entry(ce
);
4290 return error_errno(_("unable to stat newly "
4291 "created file '%s'"),
4294 fill_stat_cache_info(state
->repo
->index
, ce
, &st
);
4296 if (write_object_file(buf
, size
, blob_type
, &ce
->oid
) < 0) {
4297 discard_cache_entry(ce
);
4298 return error(_("unable to create backing store "
4299 "for newly created file %s"), path
);
4302 if (add_index_entry(state
->repo
->index
, ce
, ADD_CACHE_OK_TO_ADD
) < 0) {
4303 discard_cache_entry(ce
);
4304 return error(_("unable to add cache entry for %s"), path
);
4312 * -1 if an unrecoverable error happened
4313 * 0 if everything went well
4314 * 1 if a recoverable error happened
4316 static int try_create_file(struct apply_state
*state
, const char *path
,
4317 unsigned int mode
, const char *buf
,
4321 struct strbuf nbuf
= STRBUF_INIT
;
4323 if (S_ISGITLINK(mode
)) {
4325 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
))
4327 return !!mkdir(path
, 0777);
4330 if (has_symlinks
&& S_ISLNK(mode
))
4331 /* Although buf:size is counted string, it also is NUL
4334 return !!symlink(buf
, path
);
4336 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
4340 if (convert_to_working_tree(state
->repo
->index
, path
, buf
, size
, &nbuf
)) {
4345 res
= write_in_full(fd
, buf
, size
) < 0;
4347 error_errno(_("failed to write to '%s'"), path
);
4348 strbuf_release(&nbuf
);
4350 if (close(fd
) < 0 && !res
)
4351 return error_errno(_("closing file '%s'"), path
);
4353 return res
? -1 : 0;
4357 * We optimistically assume that the directories exist,
4358 * which is true 99% of the time anyway. If they don't,
4359 * we create them and try again.
4365 static int create_one_file(struct apply_state
*state
,
4376 res
= try_create_file(state
, path
, mode
, buf
, size
);
4382 if (errno
== ENOENT
) {
4383 if (safe_create_leading_directories(path
))
4385 res
= try_create_file(state
, path
, mode
, buf
, size
);
4392 if (errno
== EEXIST
|| errno
== EACCES
) {
4393 /* We may be trying to create a file where a directory
4397 if (!lstat(path
, &st
) && (!S_ISDIR(st
.st_mode
) || !rmdir(path
)))
4401 if (errno
== EEXIST
) {
4402 unsigned int nr
= getpid();
4405 char newpath
[PATH_MAX
];
4406 mksnpath(newpath
, sizeof(newpath
), "%s~%u", path
, nr
);
4407 res
= try_create_file(state
, newpath
, mode
, buf
, size
);
4411 if (!rename(newpath
, path
))
4413 unlink_or_warn(newpath
);
4416 if (errno
!= EEXIST
)
4421 return error_errno(_("unable to write file '%s' mode %o"),
4425 static int add_conflicted_stages_file(struct apply_state
*state
,
4426 struct patch
*patch
)
4430 struct cache_entry
*ce
;
4432 if (!state
->update_index
)
4434 namelen
= strlen(patch
->new_name
);
4435 mode
= patch
->new_mode
? patch
->new_mode
: (S_IFREG
| 0644);
4437 remove_file_from_index(state
->repo
->index
, patch
->new_name
);
4438 for (stage
= 1; stage
< 4; stage
++) {
4439 if (is_null_oid(&patch
->threeway_stage
[stage
- 1]))
4441 ce
= make_empty_cache_entry(state
->repo
->index
, namelen
);
4442 memcpy(ce
->name
, patch
->new_name
, namelen
);
4443 ce
->ce_mode
= create_ce_mode(mode
);
4444 ce
->ce_flags
= create_ce_flags(stage
);
4445 ce
->ce_namelen
= namelen
;
4446 oidcpy(&ce
->oid
, &patch
->threeway_stage
[stage
- 1]);
4447 if (add_index_entry(state
->repo
->index
, ce
, ADD_CACHE_OK_TO_ADD
) < 0) {
4448 discard_cache_entry(ce
);
4449 return error(_("unable to add cache entry for %s"),
4457 static int create_file(struct apply_state
*state
, struct patch
*patch
)
4459 char *path
= patch
->new_name
;
4460 unsigned mode
= patch
->new_mode
;
4461 unsigned long size
= patch
->resultsize
;
4462 char *buf
= patch
->result
;
4465 mode
= S_IFREG
| 0644;
4466 if (create_one_file(state
, path
, mode
, buf
, size
))
4469 if (patch
->conflicted_threeway
)
4470 return add_conflicted_stages_file(state
, patch
);
4471 else if (state
->update_index
)
4472 return add_index_file(state
, path
, mode
, buf
, size
);
4476 /* phase zero is to remove, phase one is to create */
4477 static int write_out_one_result(struct apply_state
*state
,
4478 struct patch
*patch
,
4481 if (patch
->is_delete
> 0) {
4483 return remove_file(state
, patch
, 1);
4486 if (patch
->is_new
> 0 || patch
->is_copy
) {
4488 return create_file(state
, patch
);
4492 * Rename or modification boils down to the same
4493 * thing: remove the old, write the new
4496 return remove_file(state
, patch
, patch
->is_rename
);
4498 return create_file(state
, patch
);
4502 static int write_out_one_reject(struct apply_state
*state
, struct patch
*patch
)
4505 char namebuf
[PATH_MAX
];
4506 struct fragment
*frag
;
4508 struct strbuf sb
= STRBUF_INIT
;
4510 for (cnt
= 0, frag
= patch
->fragments
; frag
; frag
= frag
->next
) {
4511 if (!frag
->rejected
)
4517 if (state
->apply_verbosity
> verbosity_normal
)
4518 say_patch_name(stderr
,
4519 _("Applied patch %s cleanly."), patch
);
4523 /* This should not happen, because a removal patch that leaves
4524 * contents are marked "rejected" at the patch level.
4526 if (!patch
->new_name
)
4527 die(_("internal error"));
4529 /* Say this even without --verbose */
4530 strbuf_addf(&sb
, Q_("Applying patch %%s with %d reject...",
4531 "Applying patch %%s with %d rejects...",
4534 if (state
->apply_verbosity
> verbosity_silent
)
4535 say_patch_name(stderr
, sb
.buf
, patch
);
4536 strbuf_release(&sb
);
4538 cnt
= strlen(patch
->new_name
);
4539 if (ARRAY_SIZE(namebuf
) <= cnt
+ 5) {
4540 cnt
= ARRAY_SIZE(namebuf
) - 5;
4541 warning(_("truncating .rej filename to %.*s.rej"),
4542 cnt
- 1, patch
->new_name
);
4544 memcpy(namebuf
, patch
->new_name
, cnt
);
4545 memcpy(namebuf
+ cnt
, ".rej", 5);
4547 rej
= fopen(namebuf
, "w");
4549 return error_errno(_("cannot open %s"), namebuf
);
4551 /* Normal git tools never deal with .rej, so do not pretend
4552 * this is a git patch by saying --git or giving extended
4553 * headers. While at it, maybe please "kompare" that wants
4554 * the trailing TAB and some garbage at the end of line ;-).
4556 fprintf(rej
, "diff a/%s b/%s\t(rejected hunks)\n",
4557 patch
->new_name
, patch
->new_name
);
4558 for (cnt
= 1, frag
= patch
->fragments
;
4560 cnt
++, frag
= frag
->next
) {
4561 if (!frag
->rejected
) {
4562 if (state
->apply_verbosity
> verbosity_silent
)
4563 fprintf_ln(stderr
, _("Hunk #%d applied cleanly."), cnt
);
4566 if (state
->apply_verbosity
> verbosity_silent
)
4567 fprintf_ln(stderr
, _("Rejected hunk #%d."), cnt
);
4568 fprintf(rej
, "%.*s", frag
->size
, frag
->patch
);
4569 if (frag
->patch
[frag
->size
-1] != '\n')
4578 * -1 if an error happened
4579 * 0 if the patch applied cleanly
4580 * 1 if the patch did not apply cleanly
4582 static int write_out_results(struct apply_state
*state
, struct patch
*list
)
4587 struct string_list cpath
= STRING_LIST_INIT_DUP
;
4589 for (phase
= 0; phase
< 2; phase
++) {
4595 if (write_out_one_result(state
, l
, phase
)) {
4596 string_list_clear(&cpath
, 0);
4600 if (write_out_one_reject(state
, l
))
4602 if (l
->conflicted_threeway
) {
4603 string_list_append(&cpath
, l
->new_name
);
4613 struct string_list_item
*item
;
4615 string_list_sort(&cpath
);
4616 if (state
->apply_verbosity
> verbosity_silent
) {
4617 for_each_string_list_item(item
, &cpath
)
4618 fprintf(stderr
, "U %s\n", item
->string
);
4620 string_list_clear(&cpath
, 0);
4622 repo_rerere(state
->repo
, 0);
4629 * Try to apply a patch.
4632 * -128 if a bad error happened (like patch unreadable)
4633 * -1 if patch did not apply and user cannot deal with it
4634 * 0 if the patch applied
4635 * 1 if the patch did not apply but user might fix it
4637 static int apply_patch(struct apply_state
*state
,
4639 const char *filename
,
4643 struct strbuf buf
= STRBUF_INIT
; /* owns the patch text */
4644 struct patch
*list
= NULL
, **listp
= &list
;
4645 int skipped_patch
= 0;
4647 int flush_attributes
= 0;
4649 state
->patch_input_file
= filename
;
4650 if (read_patch_file(&buf
, fd
) < 0)
4653 while (offset
< buf
.len
) {
4654 struct patch
*patch
;
4657 patch
= xcalloc(1, sizeof(*patch
));
4658 patch
->inaccurate_eof
= !!(options
& APPLY_OPT_INACCURATE_EOF
);
4659 patch
->recount
= !!(options
& APPLY_OPT_RECOUNT
);
4660 nr
= parse_chunk(state
, buf
.buf
+ offset
, buf
.len
- offset
, patch
);
4669 if (state
->apply_in_reverse
)
4670 reverse_patches(patch
);
4671 if (use_patch(state
, patch
)) {
4672 patch_stats(state
, patch
);
4674 listp
= &patch
->next
;
4676 if ((patch
->new_name
&&
4677 ends_with_path_components(patch
->new_name
,
4678 GITATTRIBUTES_FILE
)) ||
4680 ends_with_path_components(patch
->old_name
,
4681 GITATTRIBUTES_FILE
)))
4682 flush_attributes
= 1;
4685 if (state
->apply_verbosity
> verbosity_normal
)
4686 say_patch_name(stderr
, _("Skipped patch '%s'."), patch
);
4693 if (!list
&& !skipped_patch
) {
4694 error(_("unrecognized input"));
4699 if (state
->whitespace_error
&& (state
->ws_error_action
== die_on_ws_error
))
4702 state
->update_index
= (state
->check_index
|| state
->ita_only
) && state
->apply
;
4703 if (state
->update_index
&& !is_lock_file_locked(&state
->lock_file
)) {
4704 if (state
->index_file
)
4705 hold_lock_file_for_update(&state
->lock_file
,
4709 repo_hold_locked_index(state
->repo
, &state
->lock_file
,
4713 if (state
->check_index
&& read_apply_cache(state
) < 0) {
4714 error(_("unable to read index file"));
4719 if (state
->check
|| state
->apply
) {
4720 int r
= check_patch_list(state
, list
);
4725 if (r
< 0 && !state
->apply_with_reject
) {
4732 int write_res
= write_out_results(state
, list
);
4733 if (write_res
< 0) {
4737 if (write_res
> 0) {
4738 /* with --3way, we still need to write the index out */
4739 res
= state
->apply_with_reject
? -1 : 1;
4744 if (state
->fake_ancestor
&&
4745 build_fake_ancestor(state
, list
)) {
4750 if (state
->diffstat
&& state
->apply_verbosity
> verbosity_silent
)
4751 stat_patch_list(state
, list
);
4753 if (state
->numstat
&& state
->apply_verbosity
> verbosity_silent
)
4754 numstat_patch_list(state
, list
);
4756 if (state
->summary
&& state
->apply_verbosity
> verbosity_silent
)
4757 summary_patch_list(list
);
4759 if (flush_attributes
)
4760 reset_parsed_attributes();
4762 free_patch_list(list
);
4763 strbuf_release(&buf
);
4764 string_list_clear(&state
->fn_table
, 0);
4768 static int apply_option_parse_exclude(const struct option
*opt
,
4769 const char *arg
, int unset
)
4771 struct apply_state
*state
= opt
->value
;
4773 BUG_ON_OPT_NEG(unset
);
4775 add_name_limit(state
, arg
, 1);
4779 static int apply_option_parse_include(const struct option
*opt
,
4780 const char *arg
, int unset
)
4782 struct apply_state
*state
= opt
->value
;
4784 BUG_ON_OPT_NEG(unset
);
4786 add_name_limit(state
, arg
, 0);
4787 state
->has_include
= 1;
4791 static int apply_option_parse_p(const struct option
*opt
,
4795 struct apply_state
*state
= opt
->value
;
4797 BUG_ON_OPT_NEG(unset
);
4799 state
->p_value
= atoi(arg
);
4800 state
->p_value_known
= 1;
4804 static int apply_option_parse_space_change(const struct option
*opt
,
4805 const char *arg
, int unset
)
4807 struct apply_state
*state
= opt
->value
;
4809 BUG_ON_OPT_ARG(arg
);
4812 state
->ws_ignore_action
= ignore_ws_none
;
4814 state
->ws_ignore_action
= ignore_ws_change
;
4818 static int apply_option_parse_whitespace(const struct option
*opt
,
4819 const char *arg
, int unset
)
4821 struct apply_state
*state
= opt
->value
;
4823 BUG_ON_OPT_NEG(unset
);
4825 state
->whitespace_option
= arg
;
4826 if (parse_whitespace_option(state
, arg
))
4831 static int apply_option_parse_directory(const struct option
*opt
,
4832 const char *arg
, int unset
)
4834 struct apply_state
*state
= opt
->value
;
4836 BUG_ON_OPT_NEG(unset
);
4838 strbuf_reset(&state
->root
);
4839 strbuf_addstr(&state
->root
, arg
);
4840 strbuf_complete(&state
->root
, '/');
4844 int apply_all_patches(struct apply_state
*state
,
4854 for (i
= 0; i
< argc
; i
++) {
4855 const char *arg
= argv
[i
];
4856 char *to_free
= NULL
;
4859 if (!strcmp(arg
, "-")) {
4860 res
= apply_patch(state
, 0, "<stdin>", options
);
4867 arg
= to_free
= prefix_filename(state
->prefix
, arg
);
4869 fd
= open(arg
, O_RDONLY
);
4871 error(_("can't open patch '%s': %s"), arg
, strerror(errno
));
4877 set_default_whitespace_mode(state
);
4878 res
= apply_patch(state
, fd
, arg
, options
);
4885 set_default_whitespace_mode(state
);
4887 res
= apply_patch(state
, 0, "<stdin>", options
);
4893 if (state
->whitespace_error
) {
4894 if (state
->squelch_whitespace_errors
&&
4895 state
->squelch_whitespace_errors
< state
->whitespace_error
) {
4897 state
->whitespace_error
- state
->squelch_whitespace_errors
;
4898 warning(Q_("squelched %d whitespace error",
4899 "squelched %d whitespace errors",
4903 if (state
->ws_error_action
== die_on_ws_error
) {
4904 error(Q_("%d line adds whitespace errors.",
4905 "%d lines add whitespace errors.",
4906 state
->whitespace_error
),
4907 state
->whitespace_error
);
4911 if (state
->applied_after_fixing_ws
&& state
->apply
)
4912 warning(Q_("%d line applied after"
4913 " fixing whitespace errors.",
4914 "%d lines applied after"
4915 " fixing whitespace errors.",
4916 state
->applied_after_fixing_ws
),
4917 state
->applied_after_fixing_ws
);
4918 else if (state
->whitespace_error
)
4919 warning(Q_("%d line adds whitespace errors.",
4920 "%d lines add whitespace errors.",
4921 state
->whitespace_error
),
4922 state
->whitespace_error
);
4925 if (state
->update_index
) {
4926 res
= write_locked_index(state
->repo
->index
, &state
->lock_file
, COMMIT_LOCK
);
4928 error(_("Unable to write new index file"));
4937 rollback_lock_file(&state
->lock_file
);
4939 if (state
->apply_verbosity
<= verbosity_silent
) {
4940 set_error_routine(state
->saved_error_routine
);
4941 set_warn_routine(state
->saved_warn_routine
);
4946 return (res
== -1 ? 1 : 128);
4949 int apply_parse_options(int argc
, const char **argv
,
4950 struct apply_state
*state
,
4951 int *force_apply
, int *options
,
4952 const char * const *apply_usage
)
4954 struct option builtin_apply_options
[] = {
4955 { OPTION_CALLBACK
, 0, "exclude", state
, N_("path"),
4956 N_("don't apply changes matching the given path"),
4957 PARSE_OPT_NONEG
, apply_option_parse_exclude
},
4958 { OPTION_CALLBACK
, 0, "include", state
, N_("path"),
4959 N_("apply changes matching the given path"),
4960 PARSE_OPT_NONEG
, apply_option_parse_include
},
4961 { OPTION_CALLBACK
, 'p', NULL
, state
, N_("num"),
4962 N_("remove <num> leading slashes from traditional diff paths"),
4963 0, apply_option_parse_p
},
4964 OPT_BOOL(0, "no-add", &state
->no_add
,
4965 N_("ignore additions made by the patch")),
4966 OPT_BOOL(0, "stat", &state
->diffstat
,
4967 N_("instead of applying the patch, output diffstat for the input")),
4968 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
4969 OPT_NOOP_NOARG(0, "binary"),
4970 OPT_BOOL(0, "numstat", &state
->numstat
,
4971 N_("show number of added and deleted lines in decimal notation")),
4972 OPT_BOOL(0, "summary", &state
->summary
,
4973 N_("instead of applying the patch, output a summary for the input")),
4974 OPT_BOOL(0, "check", &state
->check
,
4975 N_("instead of applying the patch, see if the patch is applicable")),
4976 OPT_BOOL(0, "index", &state
->check_index
,
4977 N_("make sure the patch is applicable to the current index")),
4978 OPT_BOOL('N', "intent-to-add", &state
->ita_only
,
4979 N_("mark new files with `git add --intent-to-add`")),
4980 OPT_BOOL(0, "cached", &state
->cached
,
4981 N_("apply a patch without touching the working tree")),
4982 OPT_BOOL_F(0, "unsafe-paths", &state
->unsafe_paths
,
4983 N_("accept a patch that touches outside the working area"),
4984 PARSE_OPT_NOCOMPLETE
),
4985 OPT_BOOL(0, "apply", force_apply
,
4986 N_("also apply the patch (use with --stat/--summary/--check)")),
4987 OPT_BOOL('3', "3way", &state
->threeway
,
4988 N_( "attempt three-way merge if a patch does not apply")),
4989 OPT_FILENAME(0, "build-fake-ancestor", &state
->fake_ancestor
,
4990 N_("build a temporary index based on embedded index information")),
4991 /* Think twice before adding "--nul" synonym to this */
4992 OPT_SET_INT('z', NULL
, &state
->line_termination
,
4993 N_("paths are separated with NUL character"), '\0'),
4994 OPT_INTEGER('C', NULL
, &state
->p_context
,
4995 N_("ensure at least <n> lines of context match")),
4996 { OPTION_CALLBACK
, 0, "whitespace", state
, N_("action"),
4997 N_("detect new or modified lines that have whitespace errors"),
4998 0, apply_option_parse_whitespace
},
4999 { OPTION_CALLBACK
, 0, "ignore-space-change", state
, NULL
,
5000 N_("ignore changes in whitespace when finding context"),
5001 PARSE_OPT_NOARG
, apply_option_parse_space_change
},
5002 { OPTION_CALLBACK
, 0, "ignore-whitespace", state
, NULL
,
5003 N_("ignore changes in whitespace when finding context"),
5004 PARSE_OPT_NOARG
, apply_option_parse_space_change
},
5005 OPT_BOOL('R', "reverse", &state
->apply_in_reverse
,
5006 N_("apply the patch in reverse")),
5007 OPT_BOOL(0, "unidiff-zero", &state
->unidiff_zero
,
5008 N_("don't expect at least one line of context")),
5009 OPT_BOOL(0, "reject", &state
->apply_with_reject
,
5010 N_("leave the rejected hunks in corresponding *.rej files")),
5011 OPT_BOOL(0, "allow-overlap", &state
->allow_overlap
,
5012 N_("allow overlapping hunks")),
5013 OPT__VERBOSE(&state
->apply_verbosity
, N_("be verbose")),
5014 OPT_BIT(0, "inaccurate-eof", options
,
5015 N_("tolerate incorrectly detected missing new-line at the end of file"),
5016 APPLY_OPT_INACCURATE_EOF
),
5017 OPT_BIT(0, "recount", options
,
5018 N_("do not trust the line counts in the hunk headers"),
5020 { OPTION_CALLBACK
, 0, "directory", state
, N_("root"),
5021 N_("prepend <root> to all filenames"),
5022 0, apply_option_parse_directory
},
5026 return parse_options(argc
, argv
, state
->prefix
, builtin_apply_options
, apply_usage
, 0);