4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
16 #include "xdiff-interface.h"
19 #include "parse-options.h"
24 static void git_apply_config(void)
26 git_config_get_string_const("apply.whitespace", &apply_default_whitespace
);
27 git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace
);
28 git_config(git_default_config
, NULL
);
31 static int parse_whitespace_option(struct apply_state
*state
, const char *option
)
34 state
->ws_error_action
= warn_on_ws_error
;
37 if (!strcmp(option
, "warn")) {
38 state
->ws_error_action
= warn_on_ws_error
;
41 if (!strcmp(option
, "nowarn")) {
42 state
->ws_error_action
= nowarn_ws_error
;
45 if (!strcmp(option
, "error")) {
46 state
->ws_error_action
= die_on_ws_error
;
49 if (!strcmp(option
, "error-all")) {
50 state
->ws_error_action
= die_on_ws_error
;
51 state
->squelch_whitespace_errors
= 0;
54 if (!strcmp(option
, "strip") || !strcmp(option
, "fix")) {
55 state
->ws_error_action
= correct_ws_error
;
58 return error(_("unrecognized whitespace option '%s'"), option
);
61 static int parse_ignorewhitespace_option(struct apply_state
*state
,
64 if (!option
|| !strcmp(option
, "no") ||
65 !strcmp(option
, "false") || !strcmp(option
, "never") ||
66 !strcmp(option
, "none")) {
67 state
->ws_ignore_action
= ignore_ws_none
;
70 if (!strcmp(option
, "change")) {
71 state
->ws_ignore_action
= ignore_ws_change
;
74 return error(_("unrecognized whitespace ignore option '%s'"), option
);
77 int init_apply_state(struct apply_state
*state
,
80 memset(state
, 0, sizeof(*state
));
81 state
->prefix
= prefix
;
84 state
->line_termination
= '\n';
86 state
->p_context
= UINT_MAX
;
87 state
->squelch_whitespace_errors
= 5;
88 state
->ws_error_action
= warn_on_ws_error
;
89 state
->ws_ignore_action
= ignore_ws_none
;
91 string_list_init(&state
->fn_table
, 0);
92 string_list_init(&state
->limit_by_name
, 0);
93 string_list_init(&state
->symlink_changes
, 0);
94 strbuf_init(&state
->root
, 0);
97 if (apply_default_whitespace
&& parse_whitespace_option(state
, apply_default_whitespace
))
99 if (apply_default_ignorewhitespace
&& parse_ignorewhitespace_option(state
, apply_default_ignorewhitespace
))
104 void clear_apply_state(struct apply_state
*state
)
106 string_list_clear(&state
->limit_by_name
, 0);
107 string_list_clear(&state
->symlink_changes
, 0);
108 strbuf_release(&state
->root
);
110 /* &state->fn_table is cleared at the end of apply_patch() */
113 static void mute_routine(const char *msg
, va_list params
)
118 int check_apply_state(struct apply_state
*state
, int force_apply
)
120 int is_not_gitdir
= !startup_info
->have_repository
;
122 if (state
->apply_with_reject
&& state
->threeway
)
123 return error(_("--reject and --3way cannot be used together."));
124 if (state
->cached
&& state
->threeway
)
125 return error(_("--cached and --3way cannot be used together."));
126 if (state
->threeway
) {
128 return error(_("--3way outside a repository"));
129 state
->check_index
= 1;
131 if (state
->apply_with_reject
) {
133 if (state
->apply_verbosity
== verbosity_normal
)
134 state
->apply_verbosity
= verbosity_verbose
;
136 if (!force_apply
&& (state
->diffstat
|| state
->numstat
|| state
->summary
|| state
->check
|| state
->fake_ancestor
))
138 if (state
->check_index
&& is_not_gitdir
)
139 return error(_("--index outside a repository"));
142 return error(_("--cached outside a repository"));
143 state
->check_index
= 1;
145 if (state
->check_index
)
146 state
->unsafe_paths
= 0;
148 if (state
->apply_verbosity
<= verbosity_silent
) {
149 state
->saved_error_routine
= get_error_routine();
150 state
->saved_warn_routine
= get_warn_routine();
151 set_error_routine(mute_routine
);
152 set_warn_routine(mute_routine
);
158 static void set_default_whitespace_mode(struct apply_state
*state
)
160 if (!state
->whitespace_option
&& !apply_default_whitespace
)
161 state
->ws_error_action
= (state
->apply
? warn_on_ws_error
: nowarn_ws_error
);
165 * This represents one "hunk" from a patch, starting with
166 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
167 * patch text is pointed at by patch, and its byte length
168 * is stored in size. leading and trailing are the number
172 unsigned long leading
, trailing
;
173 unsigned long oldpos
, oldlines
;
174 unsigned long newpos
, newlines
;
176 * 'patch' is usually borrowed from buf in apply_patch(),
177 * but some codepaths store an allocated buffer.
180 unsigned free_patch
:1,
184 struct fragment
*next
;
188 * When dealing with a binary patch, we reuse "leading" field
189 * to store the type of the binary hunk, either deflated "delta"
190 * or deflated "literal".
192 #define binary_patch_method leading
193 #define BINARY_DELTA_DEFLATED 1
194 #define BINARY_LITERAL_DEFLATED 2
197 * This represents a "patch" to a file, both metainfo changes
198 * such as creation/deletion, filemode and content changes represented
199 * as a series of fragments.
202 char *new_name
, *old_name
, *def_name
;
203 unsigned int old_mode
, new_mode
;
204 int is_new
, is_delete
; /* -1 = unknown, 0 = false, 1 = true */
207 int lines_added
, lines_deleted
;
209 int extension_linenr
; /* first line specifying delete/new/rename/copy */
210 unsigned int is_toplevel_relative
:1;
211 unsigned int inaccurate_eof
:1;
212 unsigned int is_binary
:1;
213 unsigned int is_copy
:1;
214 unsigned int is_rename
:1;
215 unsigned int recount
:1;
216 unsigned int conflicted_threeway
:1;
217 unsigned int direct_to_threeway
:1;
218 unsigned int crlf_in_old
:1;
219 struct fragment
*fragments
;
222 char old_sha1_prefix
[41];
223 char new_sha1_prefix
[41];
226 /* three-way fallback result */
227 struct object_id threeway_stage
[3];
230 static void free_fragment_list(struct fragment
*list
)
233 struct fragment
*next
= list
->next
;
234 if (list
->free_patch
)
235 free((char *)list
->patch
);
241 static void free_patch(struct patch
*patch
)
243 free_fragment_list(patch
->fragments
);
244 free(patch
->def_name
);
245 free(patch
->old_name
);
246 free(patch
->new_name
);
251 static void free_patch_list(struct patch
*list
)
254 struct patch
*next
= list
->next
;
261 * A line in a file, len-bytes long (includes the terminating LF,
262 * except for an incomplete line at the end if the file ends with
263 * one), and its contents hashes to 'hash'.
269 #define LINE_COMMON 1
270 #define LINE_PATCHED 2
274 * This represents a "file", which is an array of "lines".
281 struct line
*line_allocated
;
285 static uint32_t hash_line(const char *cp
, size_t len
)
289 for (i
= 0, h
= 0; i
< len
; i
++) {
290 if (!isspace(cp
[i
])) {
291 h
= h
* 3 + (cp
[i
] & 0xff);
298 * Compare lines s1 of length n1 and s2 of length n2, ignoring
299 * whitespace difference. Returns 1 if they match, 0 otherwise
301 static int fuzzy_matchlines(const char *s1
, size_t n1
,
302 const char *s2
, size_t n2
)
304 const char *last1
= s1
+ n1
- 1;
305 const char *last2
= s2
+ n2
- 1;
308 /* ignore line endings */
309 while ((*last1
== '\r') || (*last1
== '\n'))
311 while ((*last2
== '\r') || (*last2
== '\n'))
314 /* skip leading whitespaces, if both begin with whitespace */
315 if (s1
<= last1
&& s2
<= last2
&& isspace(*s1
) && isspace(*s2
)) {
316 while (isspace(*s1
) && (s1
<= last1
))
318 while (isspace(*s2
) && (s2
<= last2
))
321 /* early return if both lines are empty */
322 if ((s1
> last1
) && (s2
> last2
))
325 result
= *s1
++ - *s2
++;
327 * Skip whitespace inside. We check for whitespace on
328 * both buffers because we don't want "a b" to match
331 if (isspace(*s1
) && isspace(*s2
)) {
332 while (isspace(*s1
) && s1
<= last1
)
334 while (isspace(*s2
) && s2
<= last2
)
338 * If we reached the end on one side only,
342 ((s2
> last2
) && (s1
<= last1
)) ||
343 ((s1
> last1
) && (s2
<= last2
)))
345 if ((s1
> last1
) && (s2
> last2
))
352 static void add_line_info(struct image
*img
, const char *bol
, size_t len
, unsigned flag
)
354 ALLOC_GROW(img
->line_allocated
, img
->nr
+ 1, img
->alloc
);
355 img
->line_allocated
[img
->nr
].len
= len
;
356 img
->line_allocated
[img
->nr
].hash
= hash_line(bol
, len
);
357 img
->line_allocated
[img
->nr
].flag
= flag
;
362 * "buf" has the file contents to be patched (read from various sources).
363 * attach it to "image" and add line-based index to it.
364 * "image" now owns the "buf".
366 static void prepare_image(struct image
*image
, char *buf
, size_t len
,
367 int prepare_linetable
)
371 memset(image
, 0, sizeof(*image
));
375 if (!prepare_linetable
)
378 ep
= image
->buf
+ image
->len
;
382 for (next
= cp
; next
< ep
&& *next
!= '\n'; next
++)
386 add_line_info(image
, cp
, next
- cp
, 0);
389 image
->line
= image
->line_allocated
;
392 static void clear_image(struct image
*image
)
395 free(image
->line_allocated
);
396 memset(image
, 0, sizeof(*image
));
399 /* fmt must contain _one_ %s and no other substitution */
400 static void say_patch_name(FILE *output
, const char *fmt
, struct patch
*patch
)
402 struct strbuf sb
= STRBUF_INIT
;
404 if (patch
->old_name
&& patch
->new_name
&&
405 strcmp(patch
->old_name
, patch
->new_name
)) {
406 quote_c_style(patch
->old_name
, &sb
, NULL
, 0);
407 strbuf_addstr(&sb
, " => ");
408 quote_c_style(patch
->new_name
, &sb
, NULL
, 0);
410 const char *n
= patch
->new_name
;
413 quote_c_style(n
, &sb
, NULL
, 0);
415 fprintf(output
, fmt
, sb
.buf
);
422 static int read_patch_file(struct strbuf
*sb
, int fd
)
424 if (strbuf_read(sb
, fd
, 0) < 0)
425 return error_errno("git apply: failed to read");
428 * Make sure that we have some slop in the buffer
429 * so that we can do speculative "memcmp" etc, and
430 * see to it that it is NUL-filled.
432 strbuf_grow(sb
, SLOP
);
433 memset(sb
->buf
+ sb
->len
, 0, SLOP
);
437 static unsigned long linelen(const char *buffer
, unsigned long size
)
439 unsigned long len
= 0;
442 if (*buffer
++ == '\n')
448 static int is_dev_null(const char *str
)
450 return skip_prefix(str
, "/dev/null", &str
) && isspace(*str
);
456 static int name_terminate(int c
, int terminate
)
458 if (c
== ' ' && !(terminate
& TERM_SPACE
))
460 if (c
== '\t' && !(terminate
& TERM_TAB
))
466 /* remove double slashes to make --index work with such filenames */
467 static char *squash_slash(char *name
)
475 if ((name
[j
++] = name
[i
++]) == '/')
476 while (name
[i
] == '/')
483 static char *find_name_gnu(struct apply_state
*state
,
488 struct strbuf name
= STRBUF_INIT
;
492 * Proposed "new-style" GNU patch/diff format; see
493 * http://marc.info/?l=git&m=112927316408690&w=2
495 if (unquote_c_style(&name
, line
, NULL
)) {
496 strbuf_release(&name
);
500 for (cp
= name
.buf
; p_value
; p_value
--) {
501 cp
= strchr(cp
, '/');
503 strbuf_release(&name
);
509 strbuf_remove(&name
, 0, cp
- name
.buf
);
511 strbuf_insert(&name
, 0, state
->root
.buf
, state
->root
.len
);
512 return squash_slash(strbuf_detach(&name
, NULL
));
515 static size_t sane_tz_len(const char *line
, size_t len
)
519 if (len
< strlen(" +0500") || line
[len
-strlen(" +0500")] != ' ')
521 tz
= line
+ len
- strlen(" +0500");
523 if (tz
[1] != '+' && tz
[1] != '-')
526 for (p
= tz
+ 2; p
!= line
+ len
; p
++)
530 return line
+ len
- tz
;
533 static size_t tz_with_colon_len(const char *line
, size_t len
)
537 if (len
< strlen(" +08:00") || line
[len
- strlen(":00")] != ':')
539 tz
= line
+ len
- strlen(" +08:00");
541 if (tz
[0] != ' ' || (tz
[1] != '+' && tz
[1] != '-'))
544 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
545 !isdigit(*p
++) || !isdigit(*p
++))
548 return line
+ len
- tz
;
551 static size_t date_len(const char *line
, size_t len
)
553 const char *date
, *p
;
555 if (len
< strlen("72-02-05") || line
[len
-strlen("-05")] != '-')
557 p
= date
= line
+ len
- strlen("72-02-05");
559 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
560 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
561 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a date. */
564 if (date
- line
>= strlen("19") &&
565 isdigit(date
[-1]) && isdigit(date
[-2])) /* 4-digit year */
566 date
-= strlen("19");
568 return line
+ len
- date
;
571 static size_t short_time_len(const char *line
, size_t len
)
573 const char *time
, *p
;
575 if (len
< strlen(" 07:01:32") || line
[len
-strlen(":32")] != ':')
577 p
= time
= line
+ len
- strlen(" 07:01:32");
579 /* Permit 1-digit hours? */
581 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
582 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
583 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a time. */
586 return line
+ len
- time
;
589 static size_t fractional_time_len(const char *line
, size_t len
)
594 /* Expected format: 19:41:17.620000023 */
595 if (!len
|| !isdigit(line
[len
- 1]))
599 /* Fractional seconds. */
600 while (p
> line
&& isdigit(*p
))
605 /* Hours, minutes, and whole seconds. */
606 n
= short_time_len(line
, p
- line
);
610 return line
+ len
- p
+ n
;
613 static size_t trailing_spaces_len(const char *line
, size_t len
)
617 /* Expected format: ' ' x (1 or more) */
618 if (!len
|| line
[len
- 1] != ' ')
625 return line
+ len
- (p
+ 1);
632 static size_t diff_timestamp_len(const char *line
, size_t len
)
634 const char *end
= line
+ len
;
638 * Posix: 2010-07-05 19:41:17
639 * GNU: 2010-07-05 19:41:17.620000023 -0500
642 if (!isdigit(end
[-1]))
645 n
= sane_tz_len(line
, end
- line
);
647 n
= tz_with_colon_len(line
, end
- line
);
650 n
= short_time_len(line
, end
- line
);
652 n
= fractional_time_len(line
, end
- line
);
655 n
= date_len(line
, end
- line
);
656 if (!n
) /* No date. Too bad. */
660 if (end
== line
) /* No space before date. */
662 if (end
[-1] == '\t') { /* Success! */
664 return line
+ len
- end
;
666 if (end
[-1] != ' ') /* No space before date. */
669 /* Whitespace damage. */
670 end
-= trailing_spaces_len(line
, end
- line
);
671 return line
+ len
- end
;
674 static char *find_name_common(struct apply_state
*state
,
682 const char *start
= NULL
;
686 while (line
!= end
) {
689 if (!end
&& isspace(c
)) {
692 if (name_terminate(c
, terminate
))
696 if (c
== '/' && !--p_value
)
700 return squash_slash(xstrdup_or_null(def
));
703 return squash_slash(xstrdup_or_null(def
));
706 * Generally we prefer the shorter name, especially
707 * if the other one is just a variation of that with
708 * something else tacked on to the end (ie "file.orig"
712 int deflen
= strlen(def
);
713 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
714 return squash_slash(xstrdup(def
));
717 if (state
->root
.len
) {
718 char *ret
= xstrfmt("%s%.*s", state
->root
.buf
, len
, start
);
719 return squash_slash(ret
);
722 return squash_slash(xmemdupz(start
, len
));
725 static char *find_name(struct apply_state
*state
,
732 char *name
= find_name_gnu(state
, line
, def
, p_value
);
737 return find_name_common(state
, line
, def
, p_value
, NULL
, terminate
);
740 static char *find_name_traditional(struct apply_state
*state
,
749 char *name
= find_name_gnu(state
, line
, def
, p_value
);
754 len
= strchrnul(line
, '\n') - line
;
755 date_len
= diff_timestamp_len(line
, len
);
757 return find_name_common(state
, line
, def
, p_value
, NULL
, TERM_TAB
);
760 return find_name_common(state
, line
, def
, p_value
, line
+ len
, 0);
764 * Given the string after "--- " or "+++ ", guess the appropriate
765 * p_value for the given patch.
767 static int guess_p_value(struct apply_state
*state
, const char *nameline
)
772 if (is_dev_null(nameline
))
774 name
= find_name_traditional(state
, nameline
, NULL
, 0);
777 cp
= strchr(name
, '/');
780 else if (state
->prefix
) {
782 * Does it begin with "a/$our-prefix" and such? Then this is
783 * very likely to apply to our directory.
785 if (starts_with(name
, state
->prefix
))
786 val
= count_slashes(state
->prefix
);
789 if (starts_with(cp
, state
->prefix
))
790 val
= count_slashes(state
->prefix
) + 1;
798 * Does the ---/+++ line have the POSIX timestamp after the last HT?
799 * GNU diff puts epoch there to signal a creation/deletion event. Is
800 * this such a timestamp?
802 static int has_epoch_timestamp(const char *nameline
)
805 * We are only interested in epoch timestamp; any non-zero
806 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
807 * For the same reason, the date must be either 1969-12-31 or
808 * 1970-01-01, and the seconds part must be "00".
810 const char stamp_regexp
[] =
811 "^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?"
813 "([-+][0-2][0-9]:?[0-5][0-9])\n";
814 const char *timestamp
= NULL
, *cp
, *colon
;
815 static regex_t
*stamp
;
817 int zoneoffset
, epoch_hour
, hour
, minute
;
820 for (cp
= nameline
; *cp
!= '\n'; cp
++) {
828 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
829 * (west of GMT) or 1970-01-01 (east of GMT)
831 if (skip_prefix(timestamp
, "1969-12-31 ", ×tamp
))
833 else if (skip_prefix(timestamp
, "1970-01-01 ", ×tamp
))
839 stamp
= xmalloc(sizeof(*stamp
));
840 if (regcomp(stamp
, stamp_regexp
, REG_EXTENDED
)) {
841 warning(_("Cannot prepare timestamp regexp %s"),
847 status
= regexec(stamp
, timestamp
, ARRAY_SIZE(m
), m
, 0);
849 if (status
!= REG_NOMATCH
)
850 warning(_("regexec returned %d for input: %s"),
855 hour
= strtol(timestamp
, NULL
, 10);
856 minute
= strtol(timestamp
+ m
[1].rm_so
, NULL
, 10);
858 zoneoffset
= strtol(timestamp
+ m
[3].rm_so
+ 1, (char **) &colon
, 10);
860 zoneoffset
= zoneoffset
* 60 + strtol(colon
+ 1, NULL
, 10);
862 zoneoffset
= (zoneoffset
/ 100) * 60 + (zoneoffset
% 100);
863 if (timestamp
[m
[3].rm_so
] == '-')
864 zoneoffset
= -zoneoffset
;
866 return hour
* 60 + minute
- zoneoffset
== epoch_hour
* 60;
870 * Get the name etc info from the ---/+++ lines of a traditional patch header
872 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
873 * files, we can happily check the index for a match, but for creating a
874 * new file we should try to match whatever "patch" does. I have no idea.
876 static int parse_traditional_patch(struct apply_state
*state
,
883 first
+= 4; /* skip "--- " */
884 second
+= 4; /* skip "+++ " */
885 if (!state
->p_value_known
) {
887 p
= guess_p_value(state
, first
);
888 q
= guess_p_value(state
, second
);
890 if (0 <= p
&& p
== q
) {
892 state
->p_value_known
= 1;
895 if (is_dev_null(first
)) {
897 patch
->is_delete
= 0;
898 name
= find_name_traditional(state
, second
, NULL
, state
->p_value
);
899 patch
->new_name
= name
;
900 } else if (is_dev_null(second
)) {
902 patch
->is_delete
= 1;
903 name
= find_name_traditional(state
, first
, NULL
, state
->p_value
);
904 patch
->old_name
= name
;
907 first_name
= find_name_traditional(state
, first
, NULL
, state
->p_value
);
908 name
= find_name_traditional(state
, second
, first_name
, state
->p_value
);
910 if (has_epoch_timestamp(first
)) {
912 patch
->is_delete
= 0;
913 patch
->new_name
= name
;
914 } else if (has_epoch_timestamp(second
)) {
916 patch
->is_delete
= 1;
917 patch
->old_name
= name
;
919 patch
->old_name
= name
;
920 patch
->new_name
= xstrdup_or_null(name
);
924 return error(_("unable to find filename in patch at line %d"), state
->linenr
);
929 static int gitdiff_hdrend(struct apply_state
*state
,
937 * We're anal about diff header consistency, to make
938 * sure that we don't end up having strange ambiguous
939 * patches floating around.
941 * As a result, gitdiff_{old|new}name() will check
942 * their names against any previous information, just
945 #define DIFF_OLD_NAME 0
946 #define DIFF_NEW_NAME 1
948 static int gitdiff_verify_name(struct apply_state
*state
,
954 if (!*name
&& !isnull
) {
955 *name
= find_name(state
, line
, NULL
, state
->p_value
, TERM_TAB
);
962 return error(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
963 *name
, state
->linenr
);
964 another
= find_name(state
, line
, NULL
, state
->p_value
, TERM_TAB
);
965 if (!another
|| strcmp(another
, *name
)) {
967 return error((side
== DIFF_NEW_NAME
) ?
968 _("git apply: bad git-diff - inconsistent new filename on line %d") :
969 _("git apply: bad git-diff - inconsistent old filename on line %d"), state
->linenr
);
973 if (!starts_with(line
, "/dev/null\n"))
974 return error(_("git apply: bad git-diff - expected /dev/null on line %d"), state
->linenr
);
980 static int gitdiff_oldname(struct apply_state
*state
,
984 return gitdiff_verify_name(state
, line
,
985 patch
->is_new
, &patch
->old_name
,
989 static int gitdiff_newname(struct apply_state
*state
,
993 return gitdiff_verify_name(state
, line
,
994 patch
->is_delete
, &patch
->new_name
,
998 static int parse_mode_line(const char *line
, int linenr
, unsigned int *mode
)
1001 *mode
= strtoul(line
, &end
, 8);
1002 if (end
== line
|| !isspace(*end
))
1003 return error(_("invalid mode on line %d: %s"), linenr
, line
);
1007 static int gitdiff_oldmode(struct apply_state
*state
,
1009 struct patch
*patch
)
1011 return parse_mode_line(line
, state
->linenr
, &patch
->old_mode
);
1014 static int gitdiff_newmode(struct apply_state
*state
,
1016 struct patch
*patch
)
1018 return parse_mode_line(line
, state
->linenr
, &patch
->new_mode
);
1021 static int gitdiff_delete(struct apply_state
*state
,
1023 struct patch
*patch
)
1025 patch
->is_delete
= 1;
1026 free(patch
->old_name
);
1027 patch
->old_name
= xstrdup_or_null(patch
->def_name
);
1028 return gitdiff_oldmode(state
, line
, patch
);
1031 static int gitdiff_newfile(struct apply_state
*state
,
1033 struct patch
*patch
)
1036 free(patch
->new_name
);
1037 patch
->new_name
= xstrdup_or_null(patch
->def_name
);
1038 return gitdiff_newmode(state
, line
, patch
);
1041 static int gitdiff_copysrc(struct apply_state
*state
,
1043 struct patch
*patch
)
1046 free(patch
->old_name
);
1047 patch
->old_name
= find_name(state
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1051 static int gitdiff_copydst(struct apply_state
*state
,
1053 struct patch
*patch
)
1056 free(patch
->new_name
);
1057 patch
->new_name
= find_name(state
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1061 static int gitdiff_renamesrc(struct apply_state
*state
,
1063 struct patch
*patch
)
1065 patch
->is_rename
= 1;
1066 free(patch
->old_name
);
1067 patch
->old_name
= find_name(state
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1071 static int gitdiff_renamedst(struct apply_state
*state
,
1073 struct patch
*patch
)
1075 patch
->is_rename
= 1;
1076 free(patch
->new_name
);
1077 patch
->new_name
= find_name(state
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1081 static int gitdiff_similarity(struct apply_state
*state
,
1083 struct patch
*patch
)
1085 unsigned long val
= strtoul(line
, NULL
, 10);
1091 static int gitdiff_dissimilarity(struct apply_state
*state
,
1093 struct patch
*patch
)
1095 unsigned long val
= strtoul(line
, NULL
, 10);
1101 static int gitdiff_index(struct apply_state
*state
,
1103 struct patch
*patch
)
1106 * index line is N hexadecimal, "..", N hexadecimal,
1107 * and optional space with octal mode.
1109 const char *ptr
, *eol
;
1112 ptr
= strchr(line
, '.');
1113 if (!ptr
|| ptr
[1] != '.' || 40 < ptr
- line
)
1116 memcpy(patch
->old_sha1_prefix
, line
, len
);
1117 patch
->old_sha1_prefix
[len
] = 0;
1120 ptr
= strchr(line
, ' ');
1121 eol
= strchrnul(line
, '\n');
1123 if (!ptr
|| eol
< ptr
)
1129 memcpy(patch
->new_sha1_prefix
, line
, len
);
1130 patch
->new_sha1_prefix
[len
] = 0;
1132 return gitdiff_oldmode(state
, ptr
+ 1, patch
);
1137 * This is normal for a diff that doesn't change anything: we'll fall through
1138 * into the next diff. Tell the parser to break out.
1140 static int gitdiff_unrecognized(struct apply_state
*state
,
1142 struct patch
*patch
)
1148 * Skip p_value leading components from "line"; as we do not accept
1149 * absolute paths, return NULL in that case.
1151 static const char *skip_tree_prefix(struct apply_state
*state
,
1158 if (!state
->p_value
)
1159 return (llen
&& line
[0] == '/') ? NULL
: line
;
1161 nslash
= state
->p_value
;
1162 for (i
= 0; i
< llen
; i
++) {
1164 if (ch
== '/' && --nslash
<= 0)
1165 return (i
== 0) ? NULL
: &line
[i
+ 1];
1171 * This is to extract the same name that appears on "diff --git"
1172 * line. We do not find and return anything if it is a rename
1173 * patch, and it is OK because we will find the name elsewhere.
1174 * We need to reliably find name only when it is mode-change only,
1175 * creation or deletion of an empty file. In any of these cases,
1176 * both sides are the same name under a/ and b/ respectively.
1178 static char *git_header_name(struct apply_state
*state
,
1183 const char *second
= NULL
;
1184 size_t len
, line_len
;
1186 line
+= strlen("diff --git ");
1187 llen
-= strlen("diff --git ");
1191 struct strbuf first
= STRBUF_INIT
;
1192 struct strbuf sp
= STRBUF_INIT
;
1194 if (unquote_c_style(&first
, line
, &second
))
1195 goto free_and_fail1
;
1197 /* strip the a/b prefix including trailing slash */
1198 cp
= skip_tree_prefix(state
, first
.buf
, first
.len
);
1200 goto free_and_fail1
;
1201 strbuf_remove(&first
, 0, cp
- first
.buf
);
1204 * second points at one past closing dq of name.
1205 * find the second name.
1207 while ((second
< line
+ llen
) && isspace(*second
))
1210 if (line
+ llen
<= second
)
1211 goto free_and_fail1
;
1212 if (*second
== '"') {
1213 if (unquote_c_style(&sp
, second
, NULL
))
1214 goto free_and_fail1
;
1215 cp
= skip_tree_prefix(state
, sp
.buf
, sp
.len
);
1217 goto free_and_fail1
;
1218 /* They must match, otherwise ignore */
1219 if (strcmp(cp
, first
.buf
))
1220 goto free_and_fail1
;
1221 strbuf_release(&sp
);
1222 return strbuf_detach(&first
, NULL
);
1225 /* unquoted second */
1226 cp
= skip_tree_prefix(state
, second
, line
+ llen
- second
);
1228 goto free_and_fail1
;
1229 if (line
+ llen
- cp
!= first
.len
||
1230 memcmp(first
.buf
, cp
, first
.len
))
1231 goto free_and_fail1
;
1232 return strbuf_detach(&first
, NULL
);
1235 strbuf_release(&first
);
1236 strbuf_release(&sp
);
1240 /* unquoted first name */
1241 name
= skip_tree_prefix(state
, line
, llen
);
1246 * since the first name is unquoted, a dq if exists must be
1247 * the beginning of the second name.
1249 for (second
= name
; second
< line
+ llen
; second
++) {
1250 if (*second
== '"') {
1251 struct strbuf sp
= STRBUF_INIT
;
1254 if (unquote_c_style(&sp
, second
, NULL
))
1255 goto free_and_fail2
;
1257 np
= skip_tree_prefix(state
, sp
.buf
, sp
.len
);
1259 goto free_and_fail2
;
1261 len
= sp
.buf
+ sp
.len
- np
;
1262 if (len
< second
- name
&&
1263 !strncmp(np
, name
, len
) &&
1264 isspace(name
[len
])) {
1266 strbuf_remove(&sp
, 0, np
- sp
.buf
);
1267 return strbuf_detach(&sp
, NULL
);
1271 strbuf_release(&sp
);
1277 * Accept a name only if it shows up twice, exactly the same
1280 second
= strchr(name
, '\n');
1283 line_len
= second
- name
;
1284 for (len
= 0 ; ; len
++) {
1285 switch (name
[len
]) {
1290 case '\t': case ' ':
1292 * Is this the separator between the preimage
1293 * and the postimage pathname? Again, we are
1294 * only interested in the case where there is
1295 * no rename, as this is only to set def_name
1296 * and a rename patch has the names elsewhere
1297 * in an unambiguous form.
1300 return NULL
; /* no postimage name */
1301 second
= skip_tree_prefix(state
, name
+ len
+ 1,
1302 line_len
- (len
+ 1));
1306 * Does len bytes starting at "name" and "second"
1307 * (that are separated by one HT or SP we just
1308 * found) exactly match?
1310 if (second
[len
] == '\n' && !strncmp(name
, second
, len
))
1311 return xmemdupz(name
, len
);
1316 static int check_header_line(struct apply_state
*state
, struct patch
*patch
)
1318 int extensions
= (patch
->is_delete
== 1) + (patch
->is_new
== 1) +
1319 (patch
->is_rename
== 1) + (patch
->is_copy
== 1);
1321 return error(_("inconsistent header lines %d and %d"),
1322 patch
->extension_linenr
, state
->linenr
);
1323 if (extensions
&& !patch
->extension_linenr
)
1324 patch
->extension_linenr
= state
->linenr
;
1328 /* Verify that we recognize the lines following a git header */
1329 static int parse_git_header(struct apply_state
*state
,
1333 struct patch
*patch
)
1335 unsigned long offset
;
1337 /* A git diff has explicit new/delete information, so we don't guess */
1339 patch
->is_delete
= 0;
1342 * Some things may not have the old name in the
1343 * rest of the headers anywhere (pure mode changes,
1344 * or removing or adding empty files), so we get
1345 * the default name from the header.
1347 patch
->def_name
= git_header_name(state
, line
, len
);
1348 if (patch
->def_name
&& state
->root
.len
) {
1349 char *s
= xstrfmt("%s%s", state
->root
.buf
, patch
->def_name
);
1350 free(patch
->def_name
);
1351 patch
->def_name
= s
;
1357 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1358 static const struct opentry
{
1360 int (*fn
)(struct apply_state
*, const char *, struct patch
*);
1362 { "@@ -", gitdiff_hdrend
},
1363 { "--- ", gitdiff_oldname
},
1364 { "+++ ", gitdiff_newname
},
1365 { "old mode ", gitdiff_oldmode
},
1366 { "new mode ", gitdiff_newmode
},
1367 { "deleted file mode ", gitdiff_delete
},
1368 { "new file mode ", gitdiff_newfile
},
1369 { "copy from ", gitdiff_copysrc
},
1370 { "copy to ", gitdiff_copydst
},
1371 { "rename old ", gitdiff_renamesrc
},
1372 { "rename new ", gitdiff_renamedst
},
1373 { "rename from ", gitdiff_renamesrc
},
1374 { "rename to ", gitdiff_renamedst
},
1375 { "similarity index ", gitdiff_similarity
},
1376 { "dissimilarity index ", gitdiff_dissimilarity
},
1377 { "index ", gitdiff_index
},
1378 { "", gitdiff_unrecognized
},
1382 len
= linelen(line
, size
);
1383 if (!len
|| line
[len
-1] != '\n')
1385 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
1386 const struct opentry
*p
= optable
+ i
;
1387 int oplen
= strlen(p
->str
);
1389 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
1391 res
= p
->fn(state
, line
+ oplen
, patch
);
1394 if (check_header_line(state
, patch
))
1405 static int parse_num(const char *line
, unsigned long *p
)
1409 if (!isdigit(*line
))
1411 *p
= strtoul(line
, &ptr
, 10);
1415 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
1416 unsigned long *p1
, unsigned long *p2
)
1420 if (offset
< 0 || offset
>= len
)
1425 digits
= parse_num(line
, p1
);
1435 digits
= parse_num(line
+1, p2
);
1444 ex
= strlen(expect
);
1447 if (memcmp(line
, expect
, ex
))
1453 static void recount_diff(const char *line
, int size
, struct fragment
*fragment
)
1455 int oldlines
= 0, newlines
= 0, ret
= 0;
1458 warning("recount: ignore empty hunk");
1463 int len
= linelen(line
, size
);
1471 case ' ': case '\n':
1483 ret
= size
< 3 || !starts_with(line
, "@@ ");
1486 ret
= size
< 5 || !starts_with(line
, "diff ");
1493 warning(_("recount: unexpected line: %.*s"),
1494 (int)linelen(line
, size
), line
);
1499 fragment
->oldlines
= oldlines
;
1500 fragment
->newlines
= newlines
;
1504 * Parse a unified diff fragment header of the
1505 * form "@@ -a,b +c,d @@"
1507 static int parse_fragment_header(const char *line
, int len
, struct fragment
*fragment
)
1511 if (!len
|| line
[len
-1] != '\n')
1514 /* Figure out the number of lines in a fragment */
1515 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
1516 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
1522 * Find file diff header
1525 * -1 if no header was found
1526 * -128 in case of error
1527 * the size of the header in bytes (called "offset") otherwise
1529 static int find_header(struct apply_state
*state
,
1533 struct patch
*patch
)
1535 unsigned long offset
, len
;
1537 patch
->is_toplevel_relative
= 0;
1538 patch
->is_rename
= patch
->is_copy
= 0;
1539 patch
->is_new
= patch
->is_delete
= -1;
1540 patch
->old_mode
= patch
->new_mode
= 0;
1541 patch
->old_name
= patch
->new_name
= NULL
;
1542 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1543 unsigned long nextlen
;
1545 len
= linelen(line
, size
);
1549 /* Testing this early allows us to take a few shortcuts.. */
1554 * Make sure we don't find any unconnected patch fragments.
1555 * That's a sign that we didn't find a header, and that a
1556 * patch has become corrupted/broken up.
1558 if (!memcmp("@@ -", line
, 4)) {
1559 struct fragment dummy
;
1560 if (parse_fragment_header(line
, len
, &dummy
) < 0)
1562 error(_("patch fragment without header at line %d: %.*s"),
1563 state
->linenr
, (int)len
-1, line
);
1571 * Git patch? It might not have a real patch, just a rename
1572 * or mode change, so we handle that specially
1574 if (!memcmp("diff --git ", line
, 11)) {
1575 int git_hdr_len
= parse_git_header(state
, line
, len
, size
, patch
);
1576 if (git_hdr_len
< 0)
1578 if (git_hdr_len
<= len
)
1580 if (!patch
->old_name
&& !patch
->new_name
) {
1581 if (!patch
->def_name
) {
1582 error(Q_("git diff header lacks filename information when removing "
1583 "%d leading pathname component (line %d)",
1584 "git diff header lacks filename information when removing "
1585 "%d leading pathname components (line %d)",
1587 state
->p_value
, state
->linenr
);
1590 patch
->old_name
= xstrdup(patch
->def_name
);
1591 patch
->new_name
= xstrdup(patch
->def_name
);
1593 if ((!patch
->new_name
&& !patch
->is_delete
) ||
1594 (!patch
->old_name
&& !patch
->is_new
)) {
1595 error(_("git diff header lacks filename information "
1596 "(line %d)"), state
->linenr
);
1599 patch
->is_toplevel_relative
= 1;
1600 *hdrsize
= git_hdr_len
;
1604 /* --- followed by +++ ? */
1605 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
1609 * We only accept unified patches, so we want it to
1610 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1611 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1613 nextlen
= linelen(line
+ len
, size
- len
);
1614 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
1617 /* Ok, we'll consider it a patch */
1618 if (parse_traditional_patch(state
, line
, line
+len
, patch
))
1620 *hdrsize
= len
+ nextlen
;
1627 static void record_ws_error(struct apply_state
*state
,
1638 state
->whitespace_error
++;
1639 if (state
->squelch_whitespace_errors
&&
1640 state
->squelch_whitespace_errors
< state
->whitespace_error
)
1643 err
= whitespace_error_string(result
);
1644 if (state
->apply_verbosity
> verbosity_silent
)
1645 fprintf(stderr
, "%s:%d: %s.\n%.*s\n",
1646 state
->patch_input_file
, linenr
, err
, len
, line
);
1650 static void check_whitespace(struct apply_state
*state
,
1655 unsigned result
= ws_check(line
+ 1, len
- 1, ws_rule
);
1657 record_ws_error(state
, result
, line
+ 1, len
- 2, state
->linenr
);
1661 * Check if the patch has context lines with CRLF or
1662 * the patch wants to remove lines with CRLF.
1664 static void check_old_for_crlf(struct patch
*patch
, const char *line
, int len
)
1666 if (len
>= 2 && line
[len
-1] == '\n' && line
[len
-2] == '\r') {
1667 patch
->ws_rule
|= WS_CR_AT_EOL
;
1668 patch
->crlf_in_old
= 1;
1674 * Parse a unified diff. Note that this really needs to parse each
1675 * fragment separately, since the only way to know the difference
1676 * between a "---" that is part of a patch, and a "---" that starts
1677 * the next patch is to look at the line counts..
1679 static int parse_fragment(struct apply_state
*state
,
1682 struct patch
*patch
,
1683 struct fragment
*fragment
)
1686 int len
= linelen(line
, size
), offset
;
1687 unsigned long oldlines
, newlines
;
1688 unsigned long leading
, trailing
;
1690 offset
= parse_fragment_header(line
, len
, fragment
);
1693 if (offset
> 0 && patch
->recount
)
1694 recount_diff(line
+ offset
, size
- offset
, fragment
);
1695 oldlines
= fragment
->oldlines
;
1696 newlines
= fragment
->newlines
;
1700 /* Parse the thing.. */
1704 added
= deleted
= 0;
1707 offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1708 if (!oldlines
&& !newlines
)
1710 len
= linelen(line
, size
);
1711 if (!len
|| line
[len
-1] != '\n')
1716 case '\n': /* newer GNU diff, an empty context line */
1720 if (!deleted
&& !added
)
1723 check_old_for_crlf(patch
, line
, len
);
1724 if (!state
->apply_in_reverse
&&
1725 state
->ws_error_action
== correct_ws_error
)
1726 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1729 if (!state
->apply_in_reverse
)
1730 check_old_for_crlf(patch
, line
, len
);
1731 if (state
->apply_in_reverse
&&
1732 state
->ws_error_action
!= nowarn_ws_error
)
1733 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1739 if (state
->apply_in_reverse
)
1740 check_old_for_crlf(patch
, line
, len
);
1741 if (!state
->apply_in_reverse
&&
1742 state
->ws_error_action
!= nowarn_ws_error
)
1743 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1750 * We allow "\ No newline at end of file". Depending
1751 * on locale settings when the patch was produced we
1752 * don't know what this line looks like. The only
1753 * thing we do know is that it begins with "\ ".
1754 * Checking for 12 is just for sanity check -- any
1755 * l10n of "\ No newline..." is at least that long.
1758 if (len
< 12 || memcmp(line
, "\\ ", 2))
1763 if (oldlines
|| newlines
)
1765 if (!deleted
&& !added
)
1768 fragment
->leading
= leading
;
1769 fragment
->trailing
= trailing
;
1772 * If a fragment ends with an incomplete line, we failed to include
1773 * it in the above loop because we hit oldlines == newlines == 0
1776 if (12 < size
&& !memcmp(line
, "\\ ", 2))
1777 offset
+= linelen(line
, size
);
1779 patch
->lines_added
+= added
;
1780 patch
->lines_deleted
+= deleted
;
1782 if (0 < patch
->is_new
&& oldlines
)
1783 return error(_("new file depends on old contents"));
1784 if (0 < patch
->is_delete
&& newlines
)
1785 return error(_("deleted file still has contents"));
1790 * We have seen "diff --git a/... b/..." header (or a traditional patch
1791 * header). Read hunks that belong to this patch into fragments and hang
1792 * them to the given patch structure.
1794 * The (fragment->patch, fragment->size) pair points into the memory given
1795 * by the caller, not a copy, when we return.
1798 * -1 in case of error,
1799 * the number of bytes in the patch otherwise.
1801 static int parse_single_patch(struct apply_state
*state
,
1804 struct patch
*patch
)
1806 unsigned long offset
= 0;
1807 unsigned long oldlines
= 0, newlines
= 0, context
= 0;
1808 struct fragment
**fragp
= &patch
->fragments
;
1810 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
1811 struct fragment
*fragment
;
1814 fragment
= xcalloc(1, sizeof(*fragment
));
1815 fragment
->linenr
= state
->linenr
;
1816 len
= parse_fragment(state
, line
, size
, patch
, fragment
);
1819 return error(_("corrupt patch at line %d"), state
->linenr
);
1821 fragment
->patch
= line
;
1822 fragment
->size
= len
;
1823 oldlines
+= fragment
->oldlines
;
1824 newlines
+= fragment
->newlines
;
1825 context
+= fragment
->leading
+ fragment
->trailing
;
1828 fragp
= &fragment
->next
;
1836 * If something was removed (i.e. we have old-lines) it cannot
1837 * be creation, and if something was added it cannot be
1838 * deletion. However, the reverse is not true; --unified=0
1839 * patches that only add are not necessarily creation even
1840 * though they do not have any old lines, and ones that only
1841 * delete are not necessarily deletion.
1843 * Unfortunately, a real creation/deletion patch do _not_ have
1844 * any context line by definition, so we cannot safely tell it
1845 * apart with --unified=0 insanity. At least if the patch has
1846 * more than one hunk it is not creation or deletion.
1848 if (patch
->is_new
< 0 &&
1849 (oldlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1851 if (patch
->is_delete
< 0 &&
1852 (newlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1853 patch
->is_delete
= 0;
1855 if (0 < patch
->is_new
&& oldlines
)
1856 return error(_("new file %s depends on old contents"), patch
->new_name
);
1857 if (0 < patch
->is_delete
&& newlines
)
1858 return error(_("deleted file %s still has contents"), patch
->old_name
);
1859 if (!patch
->is_delete
&& !newlines
&& context
&& state
->apply_verbosity
> verbosity_silent
)
1862 "file %s becomes empty but is not deleted"),
1868 static inline int metadata_changes(struct patch
*patch
)
1870 return patch
->is_rename
> 0 ||
1871 patch
->is_copy
> 0 ||
1872 patch
->is_new
> 0 ||
1874 (patch
->old_mode
&& patch
->new_mode
&&
1875 patch
->old_mode
!= patch
->new_mode
);
1878 static char *inflate_it(const void *data
, unsigned long size
,
1879 unsigned long inflated_size
)
1885 memset(&stream
, 0, sizeof(stream
));
1887 stream
.next_in
= (unsigned char *)data
;
1888 stream
.avail_in
= size
;
1889 stream
.next_out
= out
= xmalloc(inflated_size
);
1890 stream
.avail_out
= inflated_size
;
1891 git_inflate_init(&stream
);
1892 st
= git_inflate(&stream
, Z_FINISH
);
1893 git_inflate_end(&stream
);
1894 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1902 * Read a binary hunk and return a new fragment; fragment->patch
1903 * points at an allocated memory that the caller must free, so
1904 * it is marked as "->free_patch = 1".
1906 static struct fragment
*parse_binary_hunk(struct apply_state
*state
,
1908 unsigned long *sz_p
,
1913 * Expect a line that begins with binary patch method ("literal"
1914 * or "delta"), followed by the length of data before deflating.
1915 * a sequence of 'length-byte' followed by base-85 encoded data
1916 * should follow, terminated by a newline.
1918 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1919 * and we would limit the patch line to 66 characters,
1920 * so one line can fit up to 13 groups that would decode
1921 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1922 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1925 unsigned long size
= *sz_p
;
1926 char *buffer
= *buf_p
;
1928 unsigned long origlen
;
1931 struct fragment
*frag
;
1933 llen
= linelen(buffer
, size
);
1938 if (starts_with(buffer
, "delta ")) {
1939 patch_method
= BINARY_DELTA_DEFLATED
;
1940 origlen
= strtoul(buffer
+ 6, NULL
, 10);
1942 else if (starts_with(buffer
, "literal ")) {
1943 patch_method
= BINARY_LITERAL_DEFLATED
;
1944 origlen
= strtoul(buffer
+ 8, NULL
, 10);
1952 int byte_length
, max_byte_length
, newsize
;
1953 llen
= linelen(buffer
, size
);
1957 /* consume the blank line */
1963 * Minimum line is "A00000\n" which is 7-byte long,
1964 * and the line length must be multiple of 5 plus 2.
1966 if ((llen
< 7) || (llen
-2) % 5)
1968 max_byte_length
= (llen
- 2) / 5 * 4;
1969 byte_length
= *buffer
;
1970 if ('A' <= byte_length
&& byte_length
<= 'Z')
1971 byte_length
= byte_length
- 'A' + 1;
1972 else if ('a' <= byte_length
&& byte_length
<= 'z')
1973 byte_length
= byte_length
- 'a' + 27;
1976 /* if the input length was not multiple of 4, we would
1977 * have filler at the end but the filler should never
1980 if (max_byte_length
< byte_length
||
1981 byte_length
<= max_byte_length
- 4)
1983 newsize
= hunk_size
+ byte_length
;
1984 data
= xrealloc(data
, newsize
);
1985 if (decode_85(data
+ hunk_size
, buffer
+ 1, byte_length
))
1987 hunk_size
= newsize
;
1992 frag
= xcalloc(1, sizeof(*frag
));
1993 frag
->patch
= inflate_it(data
, hunk_size
, origlen
);
1994 frag
->free_patch
= 1;
1998 frag
->size
= origlen
;
2002 frag
->binary_patch_method
= patch_method
;
2008 error(_("corrupt binary patch at line %d: %.*s"),
2009 state
->linenr
-1, llen
-1, buffer
);
2015 * -1 in case of error,
2016 * the length of the parsed binary patch otherwise
2018 static int parse_binary(struct apply_state
*state
,
2021 struct patch
*patch
)
2024 * We have read "GIT binary patch\n"; what follows is a line
2025 * that says the patch method (currently, either "literal" or
2026 * "delta") and the length of data before deflating; a
2027 * sequence of 'length-byte' followed by base-85 encoded data
2030 * When a binary patch is reversible, there is another binary
2031 * hunk in the same format, starting with patch method (either
2032 * "literal" or "delta") with the length of data, and a sequence
2033 * of length-byte + base-85 encoded data, terminated with another
2034 * empty line. This data, when applied to the postimage, produces
2037 struct fragment
*forward
;
2038 struct fragment
*reverse
;
2042 forward
= parse_binary_hunk(state
, &buffer
, &size
, &status
, &used
);
2043 if (!forward
&& !status
)
2044 /* there has to be one hunk (forward hunk) */
2045 return error(_("unrecognized binary patch at line %d"), state
->linenr
-1);
2047 /* otherwise we already gave an error message */
2050 reverse
= parse_binary_hunk(state
, &buffer
, &size
, &status
, &used_1
);
2055 * Not having reverse hunk is not an error, but having
2056 * a corrupt reverse hunk is.
2058 free((void*) forward
->patch
);
2062 forward
->next
= reverse
;
2063 patch
->fragments
= forward
;
2064 patch
->is_binary
= 1;
2068 static void prefix_one(struct apply_state
*state
, char **name
)
2070 char *old_name
= *name
;
2073 *name
= prefix_filename(state
->prefix
, *name
);
2077 static void prefix_patch(struct apply_state
*state
, struct patch
*p
)
2079 if (!state
->prefix
|| p
->is_toplevel_relative
)
2081 prefix_one(state
, &p
->new_name
);
2082 prefix_one(state
, &p
->old_name
);
2089 static void add_name_limit(struct apply_state
*state
,
2093 struct string_list_item
*it
;
2095 it
= string_list_append(&state
->limit_by_name
, name
);
2096 it
->util
= exclude
? NULL
: (void *) 1;
2099 static int use_patch(struct apply_state
*state
, struct patch
*p
)
2101 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
2104 /* Paths outside are not touched regardless of "--include" */
2105 if (state
->prefix
&& *state
->prefix
) {
2107 if (!skip_prefix(pathname
, state
->prefix
, &rest
) || !*rest
)
2111 /* See if it matches any of exclude/include rule */
2112 for (i
= 0; i
< state
->limit_by_name
.nr
; i
++) {
2113 struct string_list_item
*it
= &state
->limit_by_name
.items
[i
];
2114 if (!wildmatch(it
->string
, pathname
, 0))
2115 return (it
->util
!= NULL
);
2119 * If we had any include, a path that does not match any rule is
2120 * not used. Otherwise, we saw bunch of exclude rules (or none)
2121 * and such a path is used.
2123 return !state
->has_include
;
2127 * Read the patch text in "buffer" that extends for "size" bytes; stop
2128 * reading after seeing a single patch (i.e. changes to a single file).
2129 * Create fragments (i.e. patch hunks) and hang them to the given patch.
2132 * -1 if no header was found or parse_binary() failed,
2133 * -128 on another error,
2134 * the number of bytes consumed otherwise,
2135 * so that the caller can call us again for the next patch.
2137 static int parse_chunk(struct apply_state
*state
, char *buffer
, unsigned long size
, struct patch
*patch
)
2139 int hdrsize
, patchsize
;
2140 int offset
= find_header(state
, buffer
, size
, &hdrsize
, patch
);
2145 prefix_patch(state
, patch
);
2147 if (!use_patch(state
, patch
))
2150 patch
->ws_rule
= whitespace_rule(patch
->new_name
2154 patchsize
= parse_single_patch(state
,
2155 buffer
+ offset
+ hdrsize
,
2156 size
- offset
- hdrsize
,
2163 static const char git_binary
[] = "GIT binary patch\n";
2164 int hd
= hdrsize
+ offset
;
2165 unsigned long llen
= linelen(buffer
+ hd
, size
- hd
);
2167 if (llen
== sizeof(git_binary
) - 1 &&
2168 !memcmp(git_binary
, buffer
+ hd
, llen
)) {
2171 used
= parse_binary(state
, buffer
+ hd
+ llen
,
2172 size
- hd
- llen
, patch
);
2176 patchsize
= used
+ llen
;
2180 else if (!memcmp(" differ\n", buffer
+ hd
+ llen
- 8, 8)) {
2181 static const char *binhdr
[] = {
2187 for (i
= 0; binhdr
[i
]; i
++) {
2188 int len
= strlen(binhdr
[i
]);
2189 if (len
< size
- hd
&&
2190 !memcmp(binhdr
[i
], buffer
+ hd
, len
)) {
2192 patch
->is_binary
= 1;
2199 /* Empty patch cannot be applied if it is a text patch
2200 * without metadata change. A binary patch appears
2203 if ((state
->apply
|| state
->check
) &&
2204 (!patch
->is_binary
&& !metadata_changes(patch
))) {
2205 error(_("patch with only garbage at line %d"), state
->linenr
);
2210 return offset
+ hdrsize
+ patchsize
;
2213 static void reverse_patches(struct patch
*p
)
2215 for (; p
; p
= p
->next
) {
2216 struct fragment
*frag
= p
->fragments
;
2218 SWAP(p
->new_name
, p
->old_name
);
2219 SWAP(p
->new_mode
, p
->old_mode
);
2220 SWAP(p
->is_new
, p
->is_delete
);
2221 SWAP(p
->lines_added
, p
->lines_deleted
);
2222 SWAP(p
->old_sha1_prefix
, p
->new_sha1_prefix
);
2224 for (; frag
; frag
= frag
->next
) {
2225 SWAP(frag
->newpos
, frag
->oldpos
);
2226 SWAP(frag
->newlines
, frag
->oldlines
);
2231 static const char pluses
[] =
2232 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2233 static const char minuses
[]=
2234 "----------------------------------------------------------------------";
2236 static void show_stats(struct apply_state
*state
, struct patch
*patch
)
2238 struct strbuf qname
= STRBUF_INIT
;
2239 char *cp
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
2242 quote_c_style(cp
, &qname
, NULL
, 0);
2245 * "scale" the filename
2247 max
= state
->max_len
;
2251 if (qname
.len
> max
) {
2252 cp
= strchr(qname
.buf
+ qname
.len
+ 3 - max
, '/');
2254 cp
= qname
.buf
+ qname
.len
+ 3 - max
;
2255 strbuf_splice(&qname
, 0, cp
- qname
.buf
, "...", 3);
2258 if (patch
->is_binary
) {
2259 printf(" %-*s | Bin\n", max
, qname
.buf
);
2260 strbuf_release(&qname
);
2264 printf(" %-*s |", max
, qname
.buf
);
2265 strbuf_release(&qname
);
2268 * scale the add/delete
2270 max
= max
+ state
->max_change
> 70 ? 70 - max
: state
->max_change
;
2271 add
= patch
->lines_added
;
2272 del
= patch
->lines_deleted
;
2274 if (state
->max_change
> 0) {
2275 int total
= ((add
+ del
) * max
+ state
->max_change
/ 2) / state
->max_change
;
2276 add
= (add
* max
+ state
->max_change
/ 2) / state
->max_change
;
2279 printf("%5d %.*s%.*s\n", patch
->lines_added
+ patch
->lines_deleted
,
2280 add
, pluses
, del
, minuses
);
2283 static int read_old_data(struct stat
*st
, struct patch
*patch
,
2284 const char *path
, struct strbuf
*buf
)
2286 enum safe_crlf safe_crlf
= patch
->crlf_in_old
?
2287 SAFE_CRLF_KEEP_CRLF
: SAFE_CRLF_RENORMALIZE
;
2288 switch (st
->st_mode
& S_IFMT
) {
2290 if (strbuf_readlink(buf
, path
, st
->st_size
) < 0)
2291 return error(_("unable to read symlink %s"), path
);
2294 if (strbuf_read_file(buf
, path
, st
->st_size
) != st
->st_size
)
2295 return error(_("unable to open or read %s"), path
);
2297 * "git apply" without "--index/--cached" should never look
2298 * at the index; the target file may not have been added to
2299 * the index yet, and we may not even be in any Git repository.
2300 * Pass NULL to convert_to_git() to stress this; the function
2301 * should never look at the index when explicit crlf option
2304 convert_to_git(NULL
, path
, buf
->buf
, buf
->len
, buf
, safe_crlf
);
2312 * Update the preimage, and the common lines in postimage,
2313 * from buffer buf of length len. If postlen is 0 the postimage
2314 * is updated in place, otherwise it's updated on a new buffer
2318 static void update_pre_post_images(struct image
*preimage
,
2319 struct image
*postimage
,
2321 size_t len
, size_t postlen
)
2323 int i
, ctx
, reduced
;
2324 char *new, *old
, *fixed
;
2325 struct image fixed_preimage
;
2328 * Update the preimage with whitespace fixes. Note that we
2329 * are not losing preimage->buf -- apply_one_fragment() will
2332 prepare_image(&fixed_preimage
, buf
, len
, 1);
2334 ? fixed_preimage
.nr
== preimage
->nr
2335 : fixed_preimage
.nr
<= preimage
->nr
);
2336 for (i
= 0; i
< fixed_preimage
.nr
; i
++)
2337 fixed_preimage
.line
[i
].flag
= preimage
->line
[i
].flag
;
2338 free(preimage
->line_allocated
);
2339 *preimage
= fixed_preimage
;
2342 * Adjust the common context lines in postimage. This can be
2343 * done in-place when we are shrinking it with whitespace
2344 * fixing, but needs a new buffer when ignoring whitespace or
2345 * expanding leading tabs to spaces.
2347 * We trust the caller to tell us if the update can be done
2348 * in place (postlen==0) or not.
2350 old
= postimage
->buf
;
2352 new = postimage
->buf
= xmalloc(postlen
);
2355 fixed
= preimage
->buf
;
2357 for (i
= reduced
= ctx
= 0; i
< postimage
->nr
; i
++) {
2358 size_t l_len
= postimage
->line
[i
].len
;
2359 if (!(postimage
->line
[i
].flag
& LINE_COMMON
)) {
2360 /* an added line -- no counterparts in preimage */
2361 memmove(new, old
, l_len
);
2367 /* a common context -- skip it in the original postimage */
2370 /* and find the corresponding one in the fixed preimage */
2371 while (ctx
< preimage
->nr
&&
2372 !(preimage
->line
[ctx
].flag
& LINE_COMMON
)) {
2373 fixed
+= preimage
->line
[ctx
].len
;
2378 * preimage is expected to run out, if the caller
2379 * fixed addition of trailing blank lines.
2381 if (preimage
->nr
<= ctx
) {
2386 /* and copy it in, while fixing the line length */
2387 l_len
= preimage
->line
[ctx
].len
;
2388 memcpy(new, fixed
, l_len
);
2391 postimage
->line
[i
].len
= l_len
;
2396 ? postlen
< new - postimage
->buf
2397 : postimage
->len
< new - postimage
->buf
)
2398 die("BUG: caller miscounted postlen: asked %d, orig = %d, used = %d",
2399 (int)postlen
, (int) postimage
->len
, (int)(new - postimage
->buf
));
2401 /* Fix the length of the whole thing */
2402 postimage
->len
= new - postimage
->buf
;
2403 postimage
->nr
-= reduced
;
2406 static int line_by_line_fuzzy_match(struct image
*img
,
2407 struct image
*preimage
,
2408 struct image
*postimage
,
2416 size_t postlen
= postimage
->len
;
2421 struct strbuf fixed
;
2425 for (i
= 0; i
< preimage_limit
; i
++) {
2426 size_t prelen
= preimage
->line
[i
].len
;
2427 size_t imglen
= img
->line
[try_lno
+i
].len
;
2429 if (!fuzzy_matchlines(img
->buf
+ try + imgoff
, imglen
,
2430 preimage
->buf
+ preoff
, prelen
))
2432 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2433 postlen
+= imglen
- prelen
;
2439 * Ok, the preimage matches with whitespace fuzz.
2441 * imgoff now holds the true length of the target that
2442 * matches the preimage before the end of the file.
2444 * Count the number of characters in the preimage that fall
2445 * beyond the end of the file and make sure that all of them
2446 * are whitespace characters. (This can only happen if
2447 * we are removing blank lines at the end of the file.)
2449 buf
= preimage_eof
= preimage
->buf
+ preoff
;
2450 for ( ; i
< preimage
->nr
; i
++)
2451 preoff
+= preimage
->line
[i
].len
;
2452 preimage_end
= preimage
->buf
+ preoff
;
2453 for ( ; buf
< preimage_end
; buf
++)
2458 * Update the preimage and the common postimage context
2459 * lines to use the same whitespace as the target.
2460 * If whitespace is missing in the target (i.e.
2461 * if the preimage extends beyond the end of the file),
2462 * use the whitespace from the preimage.
2464 extra_chars
= preimage_end
- preimage_eof
;
2465 strbuf_init(&fixed
, imgoff
+ extra_chars
);
2466 strbuf_add(&fixed
, img
->buf
+ try, imgoff
);
2467 strbuf_add(&fixed
, preimage_eof
, extra_chars
);
2468 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2469 update_pre_post_images(preimage
, postimage
,
2470 fixed_buf
, fixed_len
, postlen
);
2474 static int match_fragment(struct apply_state
*state
,
2476 struct image
*preimage
,
2477 struct image
*postimage
,
2481 int match_beginning
, int match_end
)
2484 char *fixed_buf
, *buf
, *orig
, *target
;
2485 struct strbuf fixed
;
2486 size_t fixed_len
, postlen
;
2489 if (preimage
->nr
+ try_lno
<= img
->nr
) {
2491 * The hunk falls within the boundaries of img.
2493 preimage_limit
= preimage
->nr
;
2494 if (match_end
&& (preimage
->nr
+ try_lno
!= img
->nr
))
2496 } else if (state
->ws_error_action
== correct_ws_error
&&
2497 (ws_rule
& WS_BLANK_AT_EOF
)) {
2499 * This hunk extends beyond the end of img, and we are
2500 * removing blank lines at the end of the file. This
2501 * many lines from the beginning of the preimage must
2502 * match with img, and the remainder of the preimage
2505 preimage_limit
= img
->nr
- try_lno
;
2508 * The hunk extends beyond the end of the img and
2509 * we are not removing blanks at the end, so we
2510 * should reject the hunk at this position.
2515 if (match_beginning
&& try_lno
)
2518 /* Quick hash check */
2519 for (i
= 0; i
< preimage_limit
; i
++)
2520 if ((img
->line
[try_lno
+ i
].flag
& LINE_PATCHED
) ||
2521 (preimage
->line
[i
].hash
!= img
->line
[try_lno
+ i
].hash
))
2524 if (preimage_limit
== preimage
->nr
) {
2526 * Do we have an exact match? If we were told to match
2527 * at the end, size must be exactly at try+fragsize,
2528 * otherwise try+fragsize must be still within the preimage,
2529 * and either case, the old piece should match the preimage
2533 ? (try + preimage
->len
== img
->len
)
2534 : (try + preimage
->len
<= img
->len
)) &&
2535 !memcmp(img
->buf
+ try, preimage
->buf
, preimage
->len
))
2539 * The preimage extends beyond the end of img, so
2540 * there cannot be an exact match.
2542 * There must be one non-blank context line that match
2543 * a line before the end of img.
2547 buf
= preimage
->buf
;
2549 for (i
= 0; i
< preimage_limit
; i
++)
2550 buf_end
+= preimage
->line
[i
].len
;
2552 for ( ; buf
< buf_end
; buf
++)
2560 * No exact match. If we are ignoring whitespace, run a line-by-line
2561 * fuzzy matching. We collect all the line length information because
2562 * we need it to adjust whitespace if we match.
2564 if (state
->ws_ignore_action
== ignore_ws_change
)
2565 return line_by_line_fuzzy_match(img
, preimage
, postimage
,
2566 try, try_lno
, preimage_limit
);
2568 if (state
->ws_error_action
!= correct_ws_error
)
2572 * The hunk does not apply byte-by-byte, but the hash says
2573 * it might with whitespace fuzz. We weren't asked to
2574 * ignore whitespace, we were asked to correct whitespace
2575 * errors, so let's try matching after whitespace correction.
2577 * While checking the preimage against the target, whitespace
2578 * errors in both fixed, we count how large the corresponding
2579 * postimage needs to be. The postimage prepared by
2580 * apply_one_fragment() has whitespace errors fixed on added
2581 * lines already, but the common lines were propagated as-is,
2582 * which may become longer when their whitespace errors are
2586 /* First count added lines in postimage */
2588 for (i
= 0; i
< postimage
->nr
; i
++) {
2589 if (!(postimage
->line
[i
].flag
& LINE_COMMON
))
2590 postlen
+= postimage
->line
[i
].len
;
2594 * The preimage may extend beyond the end of the file,
2595 * but in this loop we will only handle the part of the
2596 * preimage that falls within the file.
2598 strbuf_init(&fixed
, preimage
->len
+ 1);
2599 orig
= preimage
->buf
;
2600 target
= img
->buf
+ try;
2601 for (i
= 0; i
< preimage_limit
; i
++) {
2602 size_t oldlen
= preimage
->line
[i
].len
;
2603 size_t tgtlen
= img
->line
[try_lno
+ i
].len
;
2604 size_t fixstart
= fixed
.len
;
2605 struct strbuf tgtfix
;
2608 /* Try fixing the line in the preimage */
2609 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2611 /* Try fixing the line in the target */
2612 strbuf_init(&tgtfix
, tgtlen
);
2613 ws_fix_copy(&tgtfix
, target
, tgtlen
, ws_rule
, NULL
);
2616 * If they match, either the preimage was based on
2617 * a version before our tree fixed whitespace breakage,
2618 * or we are lacking a whitespace-fix patch the tree
2619 * the preimage was based on already had (i.e. target
2620 * has whitespace breakage, the preimage doesn't).
2621 * In either case, we are fixing the whitespace breakages
2622 * so we might as well take the fix together with their
2625 match
= (tgtfix
.len
== fixed
.len
- fixstart
&&
2626 !memcmp(tgtfix
.buf
, fixed
.buf
+ fixstart
,
2627 fixed
.len
- fixstart
));
2629 /* Add the length if this is common with the postimage */
2630 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2631 postlen
+= tgtfix
.len
;
2633 strbuf_release(&tgtfix
);
2643 * Now handle the lines in the preimage that falls beyond the
2644 * end of the file (if any). They will only match if they are
2645 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2648 for ( ; i
< preimage
->nr
; i
++) {
2649 size_t fixstart
= fixed
.len
; /* start of the fixed preimage */
2650 size_t oldlen
= preimage
->line
[i
].len
;
2653 /* Try fixing the line in the preimage */
2654 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2656 for (j
= fixstart
; j
< fixed
.len
; j
++)
2657 if (!isspace(fixed
.buf
[j
]))
2664 * Yes, the preimage is based on an older version that still
2665 * has whitespace breakages unfixed, and fixing them makes the
2666 * hunk match. Update the context lines in the postimage.
2668 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2669 if (postlen
< postimage
->len
)
2671 update_pre_post_images(preimage
, postimage
,
2672 fixed_buf
, fixed_len
, postlen
);
2676 strbuf_release(&fixed
);
2680 static int find_pos(struct apply_state
*state
,
2682 struct image
*preimage
,
2683 struct image
*postimage
,
2686 int match_beginning
, int match_end
)
2689 unsigned long backwards
, forwards
, try;
2690 int backwards_lno
, forwards_lno
, try_lno
;
2693 * If match_beginning or match_end is specified, there is no
2694 * point starting from a wrong line that will never match and
2695 * wander around and wait for a match at the specified end.
2697 if (match_beginning
)
2700 line
= img
->nr
- preimage
->nr
;
2703 * Because the comparison is unsigned, the following test
2704 * will also take care of a negative line number that can
2705 * result when match_end and preimage is larger than the target.
2707 if ((size_t) line
> img
->nr
)
2711 for (i
= 0; i
< line
; i
++)
2712 try += img
->line
[i
].len
;
2715 * There's probably some smart way to do this, but I'll leave
2716 * that to the smart and beautiful people. I'm simple and stupid.
2719 backwards_lno
= line
;
2721 forwards_lno
= line
;
2724 for (i
= 0; ; i
++) {
2725 if (match_fragment(state
, img
, preimage
, postimage
,
2726 try, try_lno
, ws_rule
,
2727 match_beginning
, match_end
))
2731 if (backwards_lno
== 0 && forwards_lno
== img
->nr
)
2735 if (backwards_lno
== 0) {
2740 backwards
-= img
->line
[backwards_lno
].len
;
2742 try_lno
= backwards_lno
;
2744 if (forwards_lno
== img
->nr
) {
2748 forwards
+= img
->line
[forwards_lno
].len
;
2751 try_lno
= forwards_lno
;
2758 static void remove_first_line(struct image
*img
)
2760 img
->buf
+= img
->line
[0].len
;
2761 img
->len
-= img
->line
[0].len
;
2766 static void remove_last_line(struct image
*img
)
2768 img
->len
-= img
->line
[--img
->nr
].len
;
2772 * The change from "preimage" and "postimage" has been found to
2773 * apply at applied_pos (counts in line numbers) in "img".
2774 * Update "img" to remove "preimage" and replace it with "postimage".
2776 static void update_image(struct apply_state
*state
,
2779 struct image
*preimage
,
2780 struct image
*postimage
)
2783 * remove the copy of preimage at offset in img
2784 * and replace it with postimage
2787 size_t remove_count
, insert_count
, applied_at
= 0;
2792 * If we are removing blank lines at the end of img,
2793 * the preimage may extend beyond the end.
2794 * If that is the case, we must be careful only to
2795 * remove the part of the preimage that falls within
2796 * the boundaries of img. Initialize preimage_limit
2797 * to the number of lines in the preimage that falls
2798 * within the boundaries.
2800 preimage_limit
= preimage
->nr
;
2801 if (preimage_limit
> img
->nr
- applied_pos
)
2802 preimage_limit
= img
->nr
- applied_pos
;
2804 for (i
= 0; i
< applied_pos
; i
++)
2805 applied_at
+= img
->line
[i
].len
;
2808 for (i
= 0; i
< preimage_limit
; i
++)
2809 remove_count
+= img
->line
[applied_pos
+ i
].len
;
2810 insert_count
= postimage
->len
;
2812 /* Adjust the contents */
2813 result
= xmalloc(st_add3(st_sub(img
->len
, remove_count
), insert_count
, 1));
2814 memcpy(result
, img
->buf
, applied_at
);
2815 memcpy(result
+ applied_at
, postimage
->buf
, postimage
->len
);
2816 memcpy(result
+ applied_at
+ postimage
->len
,
2817 img
->buf
+ (applied_at
+ remove_count
),
2818 img
->len
- (applied_at
+ remove_count
));
2821 img
->len
+= insert_count
- remove_count
;
2822 result
[img
->len
] = '\0';
2824 /* Adjust the line table */
2825 nr
= img
->nr
+ postimage
->nr
- preimage_limit
;
2826 if (preimage_limit
< postimage
->nr
) {
2828 * NOTE: this knows that we never call remove_first_line()
2829 * on anything other than pre/post image.
2831 REALLOC_ARRAY(img
->line
, nr
);
2832 img
->line_allocated
= img
->line
;
2834 if (preimage_limit
!= postimage
->nr
)
2835 MOVE_ARRAY(img
->line
+ applied_pos
+ postimage
->nr
,
2836 img
->line
+ applied_pos
+ preimage_limit
,
2837 img
->nr
- (applied_pos
+ preimage_limit
));
2838 COPY_ARRAY(img
->line
+ applied_pos
, postimage
->line
, postimage
->nr
);
2839 if (!state
->allow_overlap
)
2840 for (i
= 0; i
< postimage
->nr
; i
++)
2841 img
->line
[applied_pos
+ i
].flag
|= LINE_PATCHED
;
2846 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2847 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2848 * replace the part of "img" with "postimage" text.
2850 static int apply_one_fragment(struct apply_state
*state
,
2851 struct image
*img
, struct fragment
*frag
,
2852 int inaccurate_eof
, unsigned ws_rule
,
2855 int match_beginning
, match_end
;
2856 const char *patch
= frag
->patch
;
2857 int size
= frag
->size
;
2858 char *old
, *oldlines
;
2859 struct strbuf newlines
;
2860 int new_blank_lines_at_end
= 0;
2861 int found_new_blank_lines_at_end
= 0;
2862 int hunk_linenr
= frag
->linenr
;
2863 unsigned long leading
, trailing
;
2864 int pos
, applied_pos
;
2865 struct image preimage
;
2866 struct image postimage
;
2868 memset(&preimage
, 0, sizeof(preimage
));
2869 memset(&postimage
, 0, sizeof(postimage
));
2870 oldlines
= xmalloc(size
);
2871 strbuf_init(&newlines
, size
);
2876 int len
= linelen(patch
, size
);
2878 int added_blank_line
= 0;
2879 int is_blank_context
= 0;
2886 * "plen" is how much of the line we should use for
2887 * the actual patch data. Normally we just remove the
2888 * first character on the line, but if the line is
2889 * followed by "\ No newline", then we also remove the
2890 * last one (which is the newline, of course).
2893 if (len
< size
&& patch
[len
] == '\\')
2896 if (state
->apply_in_reverse
) {
2899 else if (first
== '+')
2905 /* Newer GNU diff, empty context line */
2907 /* ... followed by '\No newline'; nothing */
2910 strbuf_addch(&newlines
, '\n');
2911 add_line_info(&preimage
, "\n", 1, LINE_COMMON
);
2912 add_line_info(&postimage
, "\n", 1, LINE_COMMON
);
2913 is_blank_context
= 1;
2916 if (plen
&& (ws_rule
& WS_BLANK_AT_EOF
) &&
2917 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2918 is_blank_context
= 1;
2921 memcpy(old
, patch
+ 1, plen
);
2922 add_line_info(&preimage
, old
, plen
,
2923 (first
== ' ' ? LINE_COMMON
: 0));
2929 /* --no-add does not add new lines */
2930 if (first
== '+' && state
->no_add
)
2933 start
= newlines
.len
;
2935 !state
->whitespace_error
||
2936 state
->ws_error_action
!= correct_ws_error
) {
2937 strbuf_add(&newlines
, patch
+ 1, plen
);
2940 ws_fix_copy(&newlines
, patch
+ 1, plen
, ws_rule
, &state
->applied_after_fixing_ws
);
2942 add_line_info(&postimage
, newlines
.buf
+ start
, newlines
.len
- start
,
2943 (first
== '+' ? 0 : LINE_COMMON
));
2945 (ws_rule
& WS_BLANK_AT_EOF
) &&
2946 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2947 added_blank_line
= 1;
2949 case '@': case '\\':
2950 /* Ignore it, we already handled it */
2953 if (state
->apply_verbosity
> verbosity_normal
)
2954 error(_("invalid start of line: '%c'"), first
);
2958 if (added_blank_line
) {
2959 if (!new_blank_lines_at_end
)
2960 found_new_blank_lines_at_end
= hunk_linenr
;
2961 new_blank_lines_at_end
++;
2963 else if (is_blank_context
)
2966 new_blank_lines_at_end
= 0;
2971 if (inaccurate_eof
&&
2972 old
> oldlines
&& old
[-1] == '\n' &&
2973 newlines
.len
> 0 && newlines
.buf
[newlines
.len
- 1] == '\n') {
2975 strbuf_setlen(&newlines
, newlines
.len
- 1);
2978 leading
= frag
->leading
;
2979 trailing
= frag
->trailing
;
2982 * A hunk to change lines at the beginning would begin with
2984 * but we need to be careful. -U0 that inserts before the second
2985 * line also has this pattern.
2987 * And a hunk to add to an empty file would begin with
2990 * In other words, a hunk that is (frag->oldpos <= 1) with or
2991 * without leading context must match at the beginning.
2993 match_beginning
= (!frag
->oldpos
||
2994 (frag
->oldpos
== 1 && !state
->unidiff_zero
));
2997 * A hunk without trailing lines must match at the end.
2998 * However, we simply cannot tell if a hunk must match end
2999 * from the lack of trailing lines if the patch was generated
3000 * with unidiff without any context.
3002 match_end
= !state
->unidiff_zero
&& !trailing
;
3004 pos
= frag
->newpos
? (frag
->newpos
- 1) : 0;
3005 preimage
.buf
= oldlines
;
3006 preimage
.len
= old
- oldlines
;
3007 postimage
.buf
= newlines
.buf
;
3008 postimage
.len
= newlines
.len
;
3009 preimage
.line
= preimage
.line_allocated
;
3010 postimage
.line
= postimage
.line_allocated
;
3014 applied_pos
= find_pos(state
, img
, &preimage
, &postimage
, pos
,
3015 ws_rule
, match_beginning
, match_end
);
3017 if (applied_pos
>= 0)
3020 /* Am I at my context limits? */
3021 if ((leading
<= state
->p_context
) && (trailing
<= state
->p_context
))
3023 if (match_beginning
|| match_end
) {
3024 match_beginning
= match_end
= 0;
3029 * Reduce the number of context lines; reduce both
3030 * leading and trailing if they are equal otherwise
3031 * just reduce the larger context.
3033 if (leading
>= trailing
) {
3034 remove_first_line(&preimage
);
3035 remove_first_line(&postimage
);
3039 if (trailing
> leading
) {
3040 remove_last_line(&preimage
);
3041 remove_last_line(&postimage
);
3046 if (applied_pos
>= 0) {
3047 if (new_blank_lines_at_end
&&
3048 preimage
.nr
+ applied_pos
>= img
->nr
&&
3049 (ws_rule
& WS_BLANK_AT_EOF
) &&
3050 state
->ws_error_action
!= nowarn_ws_error
) {
3051 record_ws_error(state
, WS_BLANK_AT_EOF
, "+", 1,
3052 found_new_blank_lines_at_end
);
3053 if (state
->ws_error_action
== correct_ws_error
) {
3054 while (new_blank_lines_at_end
--)
3055 remove_last_line(&postimage
);
3058 * We would want to prevent write_out_results()
3059 * from taking place in apply_patch() that follows
3060 * the callchain led us here, which is:
3061 * apply_patch->check_patch_list->check_patch->
3062 * apply_data->apply_fragments->apply_one_fragment
3064 if (state
->ws_error_action
== die_on_ws_error
)
3068 if (state
->apply_verbosity
> verbosity_normal
&& applied_pos
!= pos
) {
3069 int offset
= applied_pos
- pos
;
3070 if (state
->apply_in_reverse
)
3071 offset
= 0 - offset
;
3073 Q_("Hunk #%d succeeded at %d (offset %d line).",
3074 "Hunk #%d succeeded at %d (offset %d lines).",
3076 nth_fragment
, applied_pos
+ 1, offset
);
3080 * Warn if it was necessary to reduce the number
3083 if ((leading
!= frag
->leading
||
3084 trailing
!= frag
->trailing
) && state
->apply_verbosity
> verbosity_silent
)
3085 fprintf_ln(stderr
, _("Context reduced to (%ld/%ld)"
3086 " to apply fragment at %d"),
3087 leading
, trailing
, applied_pos
+1);
3088 update_image(state
, img
, applied_pos
, &preimage
, &postimage
);
3090 if (state
->apply_verbosity
> verbosity_normal
)
3091 error(_("while searching for:\n%.*s"),
3092 (int)(old
- oldlines
), oldlines
);
3097 strbuf_release(&newlines
);
3098 free(preimage
.line_allocated
);
3099 free(postimage
.line_allocated
);
3101 return (applied_pos
< 0);
3104 static int apply_binary_fragment(struct apply_state
*state
,
3106 struct patch
*patch
)
3108 struct fragment
*fragment
= patch
->fragments
;
3113 return error(_("missing binary patch data for '%s'"),
3118 /* Binary patch is irreversible without the optional second hunk */
3119 if (state
->apply_in_reverse
) {
3120 if (!fragment
->next
)
3121 return error(_("cannot reverse-apply a binary patch "
3122 "without the reverse hunk to '%s'"),
3124 ? patch
->new_name
: patch
->old_name
);
3125 fragment
= fragment
->next
;
3127 switch (fragment
->binary_patch_method
) {
3128 case BINARY_DELTA_DEFLATED
:
3129 dst
= patch_delta(img
->buf
, img
->len
, fragment
->patch
,
3130 fragment
->size
, &len
);
3137 case BINARY_LITERAL_DEFLATED
:
3139 img
->len
= fragment
->size
;
3140 img
->buf
= xmemdupz(fragment
->patch
, img
->len
);
3147 * Replace "img" with the result of applying the binary patch.
3148 * The binary patch data itself in patch->fragment is still kept
3149 * but the preimage prepared by the caller in "img" is freed here
3150 * or in the helper function apply_binary_fragment() this calls.
3152 static int apply_binary(struct apply_state
*state
,
3154 struct patch
*patch
)
3156 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3157 struct object_id oid
;
3160 * For safety, we require patch index line to contain
3161 * full 40-byte textual SHA1 for old and new, at least for now.
3163 if (strlen(patch
->old_sha1_prefix
) != 40 ||
3164 strlen(patch
->new_sha1_prefix
) != 40 ||
3165 get_oid_hex(patch
->old_sha1_prefix
, &oid
) ||
3166 get_oid_hex(patch
->new_sha1_prefix
, &oid
))
3167 return error(_("cannot apply binary patch to '%s' "
3168 "without full index line"), name
);
3170 if (patch
->old_name
) {
3172 * See if the old one matches what the patch
3175 hash_sha1_file(img
->buf
, img
->len
, blob_type
, oid
.hash
);
3176 if (strcmp(oid_to_hex(&oid
), patch
->old_sha1_prefix
))
3177 return error(_("the patch applies to '%s' (%s), "
3178 "which does not match the "
3179 "current contents."),
3180 name
, oid_to_hex(&oid
));
3183 /* Otherwise, the old one must be empty. */
3185 return error(_("the patch applies to an empty "
3186 "'%s' but it is not empty"), name
);
3189 get_oid_hex(patch
->new_sha1_prefix
, &oid
);
3190 if (is_null_oid(&oid
)) {
3192 return 0; /* deletion patch */
3195 if (has_sha1_file(oid
.hash
)) {
3196 /* We already have the postimage */
3197 enum object_type type
;
3201 result
= read_sha1_file(oid
.hash
, &type
, &size
);
3203 return error(_("the necessary postimage %s for "
3204 "'%s' cannot be read"),
3205 patch
->new_sha1_prefix
, name
);
3211 * We have verified buf matches the preimage;
3212 * apply the patch data to it, which is stored
3213 * in the patch->fragments->{patch,size}.
3215 if (apply_binary_fragment(state
, img
, patch
))
3216 return error(_("binary patch does not apply to '%s'"),
3219 /* verify that the result matches */
3220 hash_sha1_file(img
->buf
, img
->len
, blob_type
, oid
.hash
);
3221 if (strcmp(oid_to_hex(&oid
), patch
->new_sha1_prefix
))
3222 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3223 name
, patch
->new_sha1_prefix
, oid_to_hex(&oid
));
3229 static int apply_fragments(struct apply_state
*state
, struct image
*img
, struct patch
*patch
)
3231 struct fragment
*frag
= patch
->fragments
;
3232 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3233 unsigned ws_rule
= patch
->ws_rule
;
3234 unsigned inaccurate_eof
= patch
->inaccurate_eof
;
3237 if (patch
->is_binary
)
3238 return apply_binary(state
, img
, patch
);
3242 if (apply_one_fragment(state
, img
, frag
, inaccurate_eof
, ws_rule
, nth
)) {
3243 error(_("patch failed: %s:%ld"), name
, frag
->oldpos
);
3244 if (!state
->apply_with_reject
)
3253 static int read_blob_object(struct strbuf
*buf
, const struct object_id
*oid
, unsigned mode
)
3255 if (S_ISGITLINK(mode
)) {
3256 strbuf_grow(buf
, 100);
3257 strbuf_addf(buf
, "Subproject commit %s\n", oid_to_hex(oid
));
3259 enum object_type type
;
3263 result
= read_sha1_file(oid
->hash
, &type
, &sz
);
3266 /* XXX read_sha1_file NUL-terminates */
3267 strbuf_attach(buf
, result
, sz
, sz
+ 1);
3272 static int read_file_or_gitlink(const struct cache_entry
*ce
, struct strbuf
*buf
)
3276 return read_blob_object(buf
, &ce
->oid
, ce
->ce_mode
);
3279 static struct patch
*in_fn_table(struct apply_state
*state
, const char *name
)
3281 struct string_list_item
*item
;
3286 item
= string_list_lookup(&state
->fn_table
, name
);
3288 return (struct patch
*)item
->util
;
3294 * item->util in the filename table records the status of the path.
3295 * Usually it points at a patch (whose result records the contents
3296 * of it after applying it), but it could be PATH_WAS_DELETED for a
3297 * path that a previously applied patch has already removed, or
3298 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3300 * The latter is needed to deal with a case where two paths A and B
3301 * are swapped by first renaming A to B and then renaming B to A;
3302 * moving A to B should not be prevented due to presence of B as we
3303 * will remove it in a later patch.
3305 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3306 #define PATH_WAS_DELETED ((struct patch *) -1)
3308 static int to_be_deleted(struct patch
*patch
)
3310 return patch
== PATH_TO_BE_DELETED
;
3313 static int was_deleted(struct patch
*patch
)
3315 return patch
== PATH_WAS_DELETED
;
3318 static void add_to_fn_table(struct apply_state
*state
, struct patch
*patch
)
3320 struct string_list_item
*item
;
3323 * Always add new_name unless patch is a deletion
3324 * This should cover the cases for normal diffs,
3325 * file creations and copies
3327 if (patch
->new_name
!= NULL
) {
3328 item
= string_list_insert(&state
->fn_table
, patch
->new_name
);
3333 * store a failure on rename/deletion cases because
3334 * later chunks shouldn't patch old names
3336 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3337 item
= string_list_insert(&state
->fn_table
, patch
->old_name
);
3338 item
->util
= PATH_WAS_DELETED
;
3342 static void prepare_fn_table(struct apply_state
*state
, struct patch
*patch
)
3345 * store information about incoming file deletion
3348 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3349 struct string_list_item
*item
;
3350 item
= string_list_insert(&state
->fn_table
, patch
->old_name
);
3351 item
->util
= PATH_TO_BE_DELETED
;
3353 patch
= patch
->next
;
3357 static int checkout_target(struct index_state
*istate
,
3358 struct cache_entry
*ce
, struct stat
*st
)
3360 struct checkout costate
= CHECKOUT_INIT
;
3362 costate
.refresh_cache
= 1;
3363 costate
.istate
= istate
;
3364 if (checkout_entry(ce
, &costate
, NULL
) || lstat(ce
->name
, st
))
3365 return error(_("cannot checkout %s"), ce
->name
);
3369 static struct patch
*previous_patch(struct apply_state
*state
,
3370 struct patch
*patch
,
3373 struct patch
*previous
;
3376 if (patch
->is_copy
|| patch
->is_rename
)
3377 return NULL
; /* "git" patches do not depend on the order */
3379 previous
= in_fn_table(state
, patch
->old_name
);
3383 if (to_be_deleted(previous
))
3384 return NULL
; /* the deletion hasn't happened yet */
3386 if (was_deleted(previous
))
3392 static int verify_index_match(const struct cache_entry
*ce
, struct stat
*st
)
3394 if (S_ISGITLINK(ce
->ce_mode
)) {
3395 if (!S_ISDIR(st
->st_mode
))
3399 return ce_match_stat(ce
, st
, CE_MATCH_IGNORE_VALID
|CE_MATCH_IGNORE_SKIP_WORKTREE
);
3402 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3404 static int load_patch_target(struct apply_state
*state
,
3406 const struct cache_entry
*ce
,
3408 struct patch
*patch
,
3410 unsigned expected_mode
)
3412 if (state
->cached
|| state
->check_index
) {
3413 if (read_file_or_gitlink(ce
, buf
))
3414 return error(_("failed to read %s"), name
);
3416 if (S_ISGITLINK(expected_mode
)) {
3418 return read_file_or_gitlink(ce
, buf
);
3420 return SUBMODULE_PATCH_WITHOUT_INDEX
;
3421 } else if (has_symlink_leading_path(name
, strlen(name
))) {
3422 return error(_("reading from '%s' beyond a symbolic link"), name
);
3424 if (read_old_data(st
, patch
, name
, buf
))
3425 return error(_("failed to read %s"), name
);
3432 * We are about to apply "patch"; populate the "image" with the
3433 * current version we have, from the working tree or from the index,
3434 * depending on the situation e.g. --cached/--index. If we are
3435 * applying a non-git patch that incrementally updates the tree,
3436 * we read from the result of a previous diff.
3438 static int load_preimage(struct apply_state
*state
,
3439 struct image
*image
,
3440 struct patch
*patch
, struct stat
*st
,
3441 const struct cache_entry
*ce
)
3443 struct strbuf buf
= STRBUF_INIT
;
3446 struct patch
*previous
;
3449 previous
= previous_patch(state
, patch
, &status
);
3451 return error(_("path %s has been renamed/deleted"),
3454 /* We have a patched copy in memory; use that. */
3455 strbuf_add(&buf
, previous
->result
, previous
->resultsize
);
3457 status
= load_patch_target(state
, &buf
, ce
, st
, patch
,
3458 patch
->old_name
, patch
->old_mode
);
3461 else if (status
== SUBMODULE_PATCH_WITHOUT_INDEX
) {
3463 * There is no way to apply subproject
3464 * patch without looking at the index.
3465 * NEEDSWORK: shouldn't this be flagged
3468 free_fragment_list(patch
->fragments
);
3469 patch
->fragments
= NULL
;
3470 } else if (status
) {
3471 return error(_("failed to read %s"), patch
->old_name
);
3475 img
= strbuf_detach(&buf
, &len
);
3476 prepare_image(image
, img
, len
, !patch
->is_binary
);
3480 static int three_way_merge(struct image
*image
,
3482 const struct object_id
*base
,
3483 const struct object_id
*ours
,
3484 const struct object_id
*theirs
)
3486 mmfile_t base_file
, our_file
, their_file
;
3487 mmbuffer_t result
= { NULL
};
3490 read_mmblob(&base_file
, base
);
3491 read_mmblob(&our_file
, ours
);
3492 read_mmblob(&their_file
, theirs
);
3493 status
= ll_merge(&result
, path
,
3496 &their_file
, "theirs", NULL
);
3497 free(base_file
.ptr
);
3499 free(their_file
.ptr
);
3500 if (status
< 0 || !result
.ptr
) {
3505 image
->buf
= result
.ptr
;
3506 image
->len
= result
.size
;
3512 * When directly falling back to add/add three-way merge, we read from
3513 * the current contents of the new_name. In no cases other than that
3514 * this function will be called.
3516 static int load_current(struct apply_state
*state
,
3517 struct image
*image
,
3518 struct patch
*patch
)
3520 struct strbuf buf
= STRBUF_INIT
;
3525 struct cache_entry
*ce
;
3526 char *name
= patch
->new_name
;
3527 unsigned mode
= patch
->new_mode
;
3530 die("BUG: patch to %s is not a creation", patch
->old_name
);
3532 pos
= cache_name_pos(name
, strlen(name
));
3534 return error(_("%s: does not exist in index"), name
);
3535 ce
= active_cache
[pos
];
3536 if (lstat(name
, &st
)) {
3537 if (errno
!= ENOENT
)
3538 return error_errno("%s", name
);
3539 if (checkout_target(&the_index
, ce
, &st
))
3542 if (verify_index_match(ce
, &st
))
3543 return error(_("%s: does not match index"), name
);
3545 status
= load_patch_target(state
, &buf
, ce
, &st
, patch
, name
, mode
);
3550 img
= strbuf_detach(&buf
, &len
);
3551 prepare_image(image
, img
, len
, !patch
->is_binary
);
3555 static int try_threeway(struct apply_state
*state
,
3556 struct image
*image
,
3557 struct patch
*patch
,
3559 const struct cache_entry
*ce
)
3561 struct object_id pre_oid
, post_oid
, our_oid
;
3562 struct strbuf buf
= STRBUF_INIT
;
3566 struct image tmp_image
;
3568 /* No point falling back to 3-way merge in these cases */
3569 if (patch
->is_delete
||
3570 S_ISGITLINK(patch
->old_mode
) || S_ISGITLINK(patch
->new_mode
))
3573 /* Preimage the patch was prepared for */
3575 write_sha1_file("", 0, blob_type
, pre_oid
.hash
);
3576 else if (get_oid(patch
->old_sha1_prefix
, &pre_oid
) ||
3577 read_blob_object(&buf
, &pre_oid
, patch
->old_mode
))
3578 return error(_("repository lacks the necessary blob to fall back on 3-way merge."));
3580 if (state
->apply_verbosity
> verbosity_silent
)
3581 fprintf(stderr
, _("Falling back to three-way merge...\n"));
3583 img
= strbuf_detach(&buf
, &len
);
3584 prepare_image(&tmp_image
, img
, len
, 1);
3585 /* Apply the patch to get the post image */
3586 if (apply_fragments(state
, &tmp_image
, patch
) < 0) {
3587 clear_image(&tmp_image
);
3590 /* post_oid is theirs */
3591 write_sha1_file(tmp_image
.buf
, tmp_image
.len
, blob_type
, post_oid
.hash
);
3592 clear_image(&tmp_image
);
3594 /* our_oid is ours */
3595 if (patch
->is_new
) {
3596 if (load_current(state
, &tmp_image
, patch
))
3597 return error(_("cannot read the current contents of '%s'"),
3600 if (load_preimage(state
, &tmp_image
, patch
, st
, ce
))
3601 return error(_("cannot read the current contents of '%s'"),
3604 write_sha1_file(tmp_image
.buf
, tmp_image
.len
, blob_type
, our_oid
.hash
);
3605 clear_image(&tmp_image
);
3607 /* in-core three-way merge between post and our using pre as base */
3608 status
= three_way_merge(image
, patch
->new_name
,
3609 &pre_oid
, &our_oid
, &post_oid
);
3611 if (state
->apply_verbosity
> verbosity_silent
)
3613 _("Failed to fall back on three-way merge...\n"));
3618 patch
->conflicted_threeway
= 1;
3620 oidclr(&patch
->threeway_stage
[0]);
3622 oidcpy(&patch
->threeway_stage
[0], &pre_oid
);
3623 oidcpy(&patch
->threeway_stage
[1], &our_oid
);
3624 oidcpy(&patch
->threeway_stage
[2], &post_oid
);
3625 if (state
->apply_verbosity
> verbosity_silent
)
3627 _("Applied patch to '%s' with conflicts.\n"),
3630 if (state
->apply_verbosity
> verbosity_silent
)
3632 _("Applied patch to '%s' cleanly.\n"),
3638 static int apply_data(struct apply_state
*state
, struct patch
*patch
,
3639 struct stat
*st
, const struct cache_entry
*ce
)
3643 if (load_preimage(state
, &image
, patch
, st
, ce
) < 0)
3646 if (patch
->direct_to_threeway
||
3647 apply_fragments(state
, &image
, patch
) < 0) {
3648 /* Note: with --reject, apply_fragments() returns 0 */
3649 if (!state
->threeway
|| try_threeway(state
, &image
, patch
, st
, ce
) < 0)
3652 patch
->result
= image
.buf
;
3653 patch
->resultsize
= image
.len
;
3654 add_to_fn_table(state
, patch
);
3655 free(image
.line_allocated
);
3657 if (0 < patch
->is_delete
&& patch
->resultsize
)
3658 return error(_("removal patch leaves file contents"));
3664 * If "patch" that we are looking at modifies or deletes what we have,
3665 * we would want it not to lose any local modification we have, either
3666 * in the working tree or in the index.
3668 * This also decides if a non-git patch is a creation patch or a
3669 * modification to an existing empty file. We do not check the state
3670 * of the current tree for a creation patch in this function; the caller
3671 * check_patch() separately makes sure (and errors out otherwise) that
3672 * the path the patch creates does not exist in the current tree.
3674 static int check_preimage(struct apply_state
*state
,
3675 struct patch
*patch
,
3676 struct cache_entry
**ce
,
3679 const char *old_name
= patch
->old_name
;
3680 struct patch
*previous
= NULL
;
3681 int stat_ret
= 0, status
;
3682 unsigned st_mode
= 0;
3687 assert(patch
->is_new
<= 0);
3688 previous
= previous_patch(state
, patch
, &status
);
3691 return error(_("path %s has been renamed/deleted"), old_name
);
3693 st_mode
= previous
->new_mode
;
3694 } else if (!state
->cached
) {
3695 stat_ret
= lstat(old_name
, st
);
3696 if (stat_ret
&& errno
!= ENOENT
)
3697 return error_errno("%s", old_name
);
3700 if (state
->check_index
&& !previous
) {
3701 int pos
= cache_name_pos(old_name
, strlen(old_name
));
3703 if (patch
->is_new
< 0)
3705 return error(_("%s: does not exist in index"), old_name
);
3707 *ce
= active_cache
[pos
];
3709 if (checkout_target(&the_index
, *ce
, st
))
3712 if (!state
->cached
&& verify_index_match(*ce
, st
))
3713 return error(_("%s: does not match index"), old_name
);
3715 st_mode
= (*ce
)->ce_mode
;
3716 } else if (stat_ret
< 0) {
3717 if (patch
->is_new
< 0)
3719 return error_errno("%s", old_name
);
3722 if (!state
->cached
&& !previous
)
3723 st_mode
= ce_mode_from_stat(*ce
, st
->st_mode
);
3725 if (patch
->is_new
< 0)
3727 if (!patch
->old_mode
)
3728 patch
->old_mode
= st_mode
;
3729 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
3730 return error(_("%s: wrong type"), old_name
);
3731 if (st_mode
!= patch
->old_mode
)
3732 warning(_("%s has type %o, expected %o"),
3733 old_name
, st_mode
, patch
->old_mode
);
3734 if (!patch
->new_mode
&& !patch
->is_delete
)
3735 patch
->new_mode
= st_mode
;
3740 patch
->is_delete
= 0;
3741 FREE_AND_NULL(patch
->old_name
);
3746 #define EXISTS_IN_INDEX 1
3747 #define EXISTS_IN_WORKTREE 2
3749 static int check_to_create(struct apply_state
*state
,
3750 const char *new_name
,
3755 if (state
->check_index
&&
3756 cache_name_pos(new_name
, strlen(new_name
)) >= 0 &&
3758 return EXISTS_IN_INDEX
;
3762 if (!lstat(new_name
, &nst
)) {
3763 if (S_ISDIR(nst
.st_mode
) || ok_if_exists
)
3766 * A leading component of new_name might be a symlink
3767 * that is going to be removed with this patch, but
3768 * still pointing at somewhere that has the path.
3769 * In such a case, path "new_name" does not exist as
3770 * far as git is concerned.
3772 if (has_symlink_leading_path(new_name
, strlen(new_name
)))
3775 return EXISTS_IN_WORKTREE
;
3776 } else if (!is_missing_file_error(errno
)) {
3777 return error_errno("%s", new_name
);
3782 static uintptr_t register_symlink_changes(struct apply_state
*state
,
3786 struct string_list_item
*ent
;
3788 ent
= string_list_lookup(&state
->symlink_changes
, path
);
3790 ent
= string_list_insert(&state
->symlink_changes
, path
);
3791 ent
->util
= (void *)0;
3793 ent
->util
= (void *)(what
| ((uintptr_t)ent
->util
));
3794 return (uintptr_t)ent
->util
;
3797 static uintptr_t check_symlink_changes(struct apply_state
*state
, const char *path
)
3799 struct string_list_item
*ent
;
3801 ent
= string_list_lookup(&state
->symlink_changes
, path
);
3804 return (uintptr_t)ent
->util
;
3807 static void prepare_symlink_changes(struct apply_state
*state
, struct patch
*patch
)
3809 for ( ; patch
; patch
= patch
->next
) {
3810 if ((patch
->old_name
&& S_ISLNK(patch
->old_mode
)) &&
3811 (patch
->is_rename
|| patch
->is_delete
))
3812 /* the symlink at patch->old_name is removed */
3813 register_symlink_changes(state
, patch
->old_name
, APPLY_SYMLINK_GOES_AWAY
);
3815 if (patch
->new_name
&& S_ISLNK(patch
->new_mode
))
3816 /* the symlink at patch->new_name is created or remains */
3817 register_symlink_changes(state
, patch
->new_name
, APPLY_SYMLINK_IN_RESULT
);
3821 static int path_is_beyond_symlink_1(struct apply_state
*state
, struct strbuf
*name
)
3824 unsigned int change
;
3826 while (--name
->len
&& name
->buf
[name
->len
] != '/')
3827 ; /* scan backwards */
3830 name
->buf
[name
->len
] = '\0';
3831 change
= check_symlink_changes(state
, name
->buf
);
3832 if (change
& APPLY_SYMLINK_IN_RESULT
)
3834 if (change
& APPLY_SYMLINK_GOES_AWAY
)
3836 * This cannot be "return 0", because we may
3837 * see a new one created at a higher level.
3841 /* otherwise, check the preimage */
3842 if (state
->check_index
) {
3843 struct cache_entry
*ce
;
3845 ce
= cache_file_exists(name
->buf
, name
->len
, ignore_case
);
3846 if (ce
&& S_ISLNK(ce
->ce_mode
))
3850 if (!lstat(name
->buf
, &st
) && S_ISLNK(st
.st_mode
))
3857 static int path_is_beyond_symlink(struct apply_state
*state
, const char *name_
)
3860 struct strbuf name
= STRBUF_INIT
;
3862 assert(*name_
!= '\0');
3863 strbuf_addstr(&name
, name_
);
3864 ret
= path_is_beyond_symlink_1(state
, &name
);
3865 strbuf_release(&name
);
3870 static int check_unsafe_path(struct patch
*patch
)
3872 const char *old_name
= NULL
;
3873 const char *new_name
= NULL
;
3874 if (patch
->is_delete
)
3875 old_name
= patch
->old_name
;
3876 else if (!patch
->is_new
&& !patch
->is_copy
)
3877 old_name
= patch
->old_name
;
3878 if (!patch
->is_delete
)
3879 new_name
= patch
->new_name
;
3881 if (old_name
&& !verify_path(old_name
))
3882 return error(_("invalid path '%s'"), old_name
);
3883 if (new_name
&& !verify_path(new_name
))
3884 return error(_("invalid path '%s'"), new_name
);
3889 * Check and apply the patch in-core; leave the result in patch->result
3890 * for the caller to write it out to the final destination.
3892 static int check_patch(struct apply_state
*state
, struct patch
*patch
)
3895 const char *old_name
= patch
->old_name
;
3896 const char *new_name
= patch
->new_name
;
3897 const char *name
= old_name
? old_name
: new_name
;
3898 struct cache_entry
*ce
= NULL
;
3899 struct patch
*tpatch
;
3903 patch
->rejected
= 1; /* we will drop this after we succeed */
3905 status
= check_preimage(state
, patch
, &ce
, &st
);
3908 old_name
= patch
->old_name
;
3911 * A type-change diff is always split into a patch to delete
3912 * old, immediately followed by a patch to create new (see
3913 * diff.c::run_diff()); in such a case it is Ok that the entry
3914 * to be deleted by the previous patch is still in the working
3915 * tree and in the index.
3917 * A patch to swap-rename between A and B would first rename A
3918 * to B and then rename B to A. While applying the first one,
3919 * the presence of B should not stop A from getting renamed to
3920 * B; ask to_be_deleted() about the later rename. Removal of
3921 * B and rename from A to B is handled the same way by asking
3924 if ((tpatch
= in_fn_table(state
, new_name
)) &&
3925 (was_deleted(tpatch
) || to_be_deleted(tpatch
)))
3931 ((0 < patch
->is_new
) || patch
->is_rename
|| patch
->is_copy
)) {
3932 int err
= check_to_create(state
, new_name
, ok_if_exists
);
3934 if (err
&& state
->threeway
) {
3935 patch
->direct_to_threeway
= 1;
3936 } else switch (err
) {
3939 case EXISTS_IN_INDEX
:
3940 return error(_("%s: already exists in index"), new_name
);
3942 case EXISTS_IN_WORKTREE
:
3943 return error(_("%s: already exists in working directory"),
3949 if (!patch
->new_mode
) {
3950 if (0 < patch
->is_new
)
3951 patch
->new_mode
= S_IFREG
| 0644;
3953 patch
->new_mode
= patch
->old_mode
;
3957 if (new_name
&& old_name
) {
3958 int same
= !strcmp(old_name
, new_name
);
3959 if (!patch
->new_mode
)
3960 patch
->new_mode
= patch
->old_mode
;
3961 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
) {
3963 return error(_("new mode (%o) of %s does not "
3964 "match old mode (%o)"),
3965 patch
->new_mode
, new_name
,
3968 return error(_("new mode (%o) of %s does not "
3969 "match old mode (%o) of %s"),
3970 patch
->new_mode
, new_name
,
3971 patch
->old_mode
, old_name
);
3975 if (!state
->unsafe_paths
&& check_unsafe_path(patch
))
3979 * An attempt to read from or delete a path that is beyond a
3980 * symbolic link will be prevented by load_patch_target() that
3981 * is called at the beginning of apply_data() so we do not
3982 * have to worry about a patch marked with "is_delete" bit
3983 * here. We however need to make sure that the patch result
3984 * is not deposited to a path that is beyond a symbolic link
3987 if (!patch
->is_delete
&& path_is_beyond_symlink(state
, patch
->new_name
))
3988 return error(_("affected file '%s' is beyond a symbolic link"),
3991 if (apply_data(state
, patch
, &st
, ce
) < 0)
3992 return error(_("%s: patch does not apply"), name
);
3993 patch
->rejected
= 0;
3997 static int check_patch_list(struct apply_state
*state
, struct patch
*patch
)
4001 prepare_symlink_changes(state
, patch
);
4002 prepare_fn_table(state
, patch
);
4005 if (state
->apply_verbosity
> verbosity_normal
)
4006 say_patch_name(stderr
,
4007 _("Checking patch %s..."), patch
);
4008 res
= check_patch(state
, patch
);
4012 patch
= patch
->next
;
4017 static int read_apply_cache(struct apply_state
*state
)
4019 if (state
->index_file
)
4020 return read_cache_from(state
->index_file
);
4022 return read_cache();
4025 /* This function tries to read the object name from the current index */
4026 static int get_current_oid(struct apply_state
*state
, const char *path
,
4027 struct object_id
*oid
)
4031 if (read_apply_cache(state
) < 0)
4033 pos
= cache_name_pos(path
, strlen(path
));
4036 oidcpy(oid
, &active_cache
[pos
]->oid
);
4040 static int preimage_oid_in_gitlink_patch(struct patch
*p
, struct object_id
*oid
)
4043 * A usable gitlink patch has only one fragment (hunk) that looks like:
4045 * -Subproject commit <old sha1>
4046 * +Subproject commit <new sha1>
4049 * -Subproject commit <old sha1>
4050 * for a removal patch.
4052 struct fragment
*hunk
= p
->fragments
;
4053 static const char heading
[] = "-Subproject commit ";
4056 if (/* does the patch have only one hunk? */
4057 hunk
&& !hunk
->next
&&
4058 /* is its preimage one line? */
4059 hunk
->oldpos
== 1 && hunk
->oldlines
== 1 &&
4060 /* does preimage begin with the heading? */
4061 (preimage
= memchr(hunk
->patch
, '\n', hunk
->size
)) != NULL
&&
4062 starts_with(++preimage
, heading
) &&
4063 /* does it record full SHA-1? */
4064 !get_oid_hex(preimage
+ sizeof(heading
) - 1, oid
) &&
4065 preimage
[sizeof(heading
) + GIT_SHA1_HEXSZ
- 1] == '\n' &&
4066 /* does the abbreviated name on the index line agree with it? */
4067 starts_with(preimage
+ sizeof(heading
) - 1, p
->old_sha1_prefix
))
4068 return 0; /* it all looks fine */
4070 /* we may have full object name on the index line */
4071 return get_oid_hex(p
->old_sha1_prefix
, oid
);
4074 /* Build an index that contains the just the files needed for a 3way merge */
4075 static int build_fake_ancestor(struct apply_state
*state
, struct patch
*list
)
4077 struct patch
*patch
;
4078 struct index_state result
= { NULL
};
4079 static struct lock_file lock
;
4082 /* Once we start supporting the reverse patch, it may be
4083 * worth showing the new sha1 prefix, but until then...
4085 for (patch
= list
; patch
; patch
= patch
->next
) {
4086 struct object_id oid
;
4087 struct cache_entry
*ce
;
4090 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
4091 if (0 < patch
->is_new
)
4094 if (S_ISGITLINK(patch
->old_mode
)) {
4095 if (!preimage_oid_in_gitlink_patch(patch
, &oid
))
4096 ; /* ok, the textual part looks sane */
4098 return error(_("sha1 information is lacking or "
4099 "useless for submodule %s"), name
);
4100 } else if (!get_oid_blob(patch
->old_sha1_prefix
, &oid
)) {
4102 } else if (!patch
->lines_added
&& !patch
->lines_deleted
) {
4103 /* mode-only change: update the current */
4104 if (get_current_oid(state
, patch
->old_name
, &oid
))
4105 return error(_("mode change for %s, which is not "
4106 "in current HEAD"), name
);
4108 return error(_("sha1 information is lacking or useless "
4111 ce
= make_cache_entry(patch
->old_mode
, oid
.hash
, name
, 0, 0);
4113 return error(_("make_cache_entry failed for path '%s'"),
4115 if (add_index_entry(&result
, ce
, ADD_CACHE_OK_TO_ADD
)) {
4117 return error(_("could not add %s to temporary index"),
4122 hold_lock_file_for_update(&lock
, state
->fake_ancestor
, LOCK_DIE_ON_ERROR
);
4123 res
= write_locked_index(&result
, &lock
, COMMIT_LOCK
);
4124 discard_index(&result
);
4127 return error(_("could not write temporary index to %s"),
4128 state
->fake_ancestor
);
4133 static void stat_patch_list(struct apply_state
*state
, struct patch
*patch
)
4135 int files
, adds
, dels
;
4137 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
4139 adds
+= patch
->lines_added
;
4140 dels
+= patch
->lines_deleted
;
4141 show_stats(state
, patch
);
4144 print_stat_summary(stdout
, files
, adds
, dels
);
4147 static void numstat_patch_list(struct apply_state
*state
,
4148 struct patch
*patch
)
4150 for ( ; patch
; patch
= patch
->next
) {
4152 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
4153 if (patch
->is_binary
)
4156 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
4157 write_name_quoted(name
, stdout
, state
->line_termination
);
4161 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
4164 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
4166 printf(" %s %s\n", newdelete
, name
);
4169 static void show_mode_change(struct patch
*p
, int show_name
)
4171 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
4173 printf(" mode change %06o => %06o %s\n",
4174 p
->old_mode
, p
->new_mode
, p
->new_name
);
4176 printf(" mode change %06o => %06o\n",
4177 p
->old_mode
, p
->new_mode
);
4181 static void show_rename_copy(struct patch
*p
)
4183 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
4184 const char *old
, *new;
4186 /* Find common prefix */
4190 const char *slash_old
, *slash_new
;
4191 slash_old
= strchr(old
, '/');
4192 slash_new
= strchr(new, '/');
4195 slash_old
- old
!= slash_new
- new ||
4196 memcmp(old
, new, slash_new
- new))
4198 old
= slash_old
+ 1;
4199 new = slash_new
+ 1;
4201 /* p->old_name thru old is the common prefix, and old and new
4202 * through the end of names are renames
4204 if (old
!= p
->old_name
)
4205 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
4206 (int)(old
- p
->old_name
), p
->old_name
,
4207 old
, new, p
->score
);
4209 printf(" %s %s => %s (%d%%)\n", renamecopy
,
4210 p
->old_name
, p
->new_name
, p
->score
);
4211 show_mode_change(p
, 0);
4214 static void summary_patch_list(struct patch
*patch
)
4218 for (p
= patch
; p
; p
= p
->next
) {
4220 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
4221 else if (p
->is_delete
)
4222 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
4224 if (p
->is_rename
|| p
->is_copy
)
4225 show_rename_copy(p
);
4228 printf(" rewrite %s (%d%%)\n",
4229 p
->new_name
, p
->score
);
4230 show_mode_change(p
, 0);
4233 show_mode_change(p
, 1);
4239 static void patch_stats(struct apply_state
*state
, struct patch
*patch
)
4241 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
4243 if (lines
> state
->max_change
)
4244 state
->max_change
= lines
;
4245 if (patch
->old_name
) {
4246 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
4248 len
= strlen(patch
->old_name
);
4249 if (len
> state
->max_len
)
4250 state
->max_len
= len
;
4252 if (patch
->new_name
) {
4253 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
4255 len
= strlen(patch
->new_name
);
4256 if (len
> state
->max_len
)
4257 state
->max_len
= len
;
4261 static int remove_file(struct apply_state
*state
, struct patch
*patch
, int rmdir_empty
)
4263 if (state
->update_index
) {
4264 if (remove_file_from_cache(patch
->old_name
) < 0)
4265 return error(_("unable to remove %s from index"), patch
->old_name
);
4267 if (!state
->cached
) {
4268 if (!remove_or_warn(patch
->old_mode
, patch
->old_name
) && rmdir_empty
) {
4269 remove_path(patch
->old_name
);
4275 static int add_index_file(struct apply_state
*state
,
4282 struct cache_entry
*ce
;
4283 int namelen
= strlen(path
);
4284 unsigned ce_size
= cache_entry_size(namelen
);
4286 if (!state
->update_index
)
4289 ce
= xcalloc(1, ce_size
);
4290 memcpy(ce
->name
, path
, namelen
);
4291 ce
->ce_mode
= create_ce_mode(mode
);
4292 ce
->ce_flags
= create_ce_flags(0);
4293 ce
->ce_namelen
= namelen
;
4294 if (S_ISGITLINK(mode
)) {
4297 if (!skip_prefix(buf
, "Subproject commit ", &s
) ||
4298 get_oid_hex(s
, &ce
->oid
)) {
4300 return error(_("corrupt patch for submodule %s"), path
);
4303 if (!state
->cached
) {
4304 if (lstat(path
, &st
) < 0) {
4306 return error_errno(_("unable to stat newly "
4307 "created file '%s'"),
4310 fill_stat_cache_info(ce
, &st
);
4312 if (write_sha1_file(buf
, size
, blob_type
, ce
->oid
.hash
) < 0) {
4314 return error(_("unable to create backing store "
4315 "for newly created file %s"), path
);
4318 if (add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
) < 0) {
4320 return error(_("unable to add cache entry for %s"), path
);
4328 * -1 if an unrecoverable error happened
4329 * 0 if everything went well
4330 * 1 if a recoverable error happened
4332 static int try_create_file(const char *path
, unsigned int mode
, const char *buf
, unsigned long size
)
4335 struct strbuf nbuf
= STRBUF_INIT
;
4337 if (S_ISGITLINK(mode
)) {
4339 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
))
4341 return !!mkdir(path
, 0777);
4344 if (has_symlinks
&& S_ISLNK(mode
))
4345 /* Although buf:size is counted string, it also is NUL
4348 return !!symlink(buf
, path
);
4350 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
4354 if (convert_to_working_tree(path
, buf
, size
, &nbuf
)) {
4359 res
= write_in_full(fd
, buf
, size
) < 0;
4361 error_errno(_("failed to write to '%s'"), path
);
4362 strbuf_release(&nbuf
);
4364 if (close(fd
) < 0 && !res
)
4365 return error_errno(_("closing file '%s'"), path
);
4367 return res
? -1 : 0;
4371 * We optimistically assume that the directories exist,
4372 * which is true 99% of the time anyway. If they don't,
4373 * we create them and try again.
4379 static int create_one_file(struct apply_state
*state
,
4390 res
= try_create_file(path
, mode
, buf
, size
);
4396 if (errno
== ENOENT
) {
4397 if (safe_create_leading_directories(path
))
4399 res
= try_create_file(path
, mode
, buf
, size
);
4406 if (errno
== EEXIST
|| errno
== EACCES
) {
4407 /* We may be trying to create a file where a directory
4411 if (!lstat(path
, &st
) && (!S_ISDIR(st
.st_mode
) || !rmdir(path
)))
4415 if (errno
== EEXIST
) {
4416 unsigned int nr
= getpid();
4419 char newpath
[PATH_MAX
];
4420 mksnpath(newpath
, sizeof(newpath
), "%s~%u", path
, nr
);
4421 res
= try_create_file(newpath
, mode
, buf
, size
);
4425 if (!rename(newpath
, path
))
4427 unlink_or_warn(newpath
);
4430 if (errno
!= EEXIST
)
4435 return error_errno(_("unable to write file '%s' mode %o"),
4439 static int add_conflicted_stages_file(struct apply_state
*state
,
4440 struct patch
*patch
)
4443 unsigned ce_size
, mode
;
4444 struct cache_entry
*ce
;
4446 if (!state
->update_index
)
4448 namelen
= strlen(patch
->new_name
);
4449 ce_size
= cache_entry_size(namelen
);
4450 mode
= patch
->new_mode
? patch
->new_mode
: (S_IFREG
| 0644);
4452 remove_file_from_cache(patch
->new_name
);
4453 for (stage
= 1; stage
< 4; stage
++) {
4454 if (is_null_oid(&patch
->threeway_stage
[stage
- 1]))
4456 ce
= xcalloc(1, ce_size
);
4457 memcpy(ce
->name
, patch
->new_name
, namelen
);
4458 ce
->ce_mode
= create_ce_mode(mode
);
4459 ce
->ce_flags
= create_ce_flags(stage
);
4460 ce
->ce_namelen
= namelen
;
4461 oidcpy(&ce
->oid
, &patch
->threeway_stage
[stage
- 1]);
4462 if (add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
) < 0) {
4464 return error(_("unable to add cache entry for %s"),
4472 static int create_file(struct apply_state
*state
, struct patch
*patch
)
4474 char *path
= patch
->new_name
;
4475 unsigned mode
= patch
->new_mode
;
4476 unsigned long size
= patch
->resultsize
;
4477 char *buf
= patch
->result
;
4480 mode
= S_IFREG
| 0644;
4481 if (create_one_file(state
, path
, mode
, buf
, size
))
4484 if (patch
->conflicted_threeway
)
4485 return add_conflicted_stages_file(state
, patch
);
4487 return add_index_file(state
, path
, mode
, buf
, size
);
4490 /* phase zero is to remove, phase one is to create */
4491 static int write_out_one_result(struct apply_state
*state
,
4492 struct patch
*patch
,
4495 if (patch
->is_delete
> 0) {
4497 return remove_file(state
, patch
, 1);
4500 if (patch
->is_new
> 0 || patch
->is_copy
) {
4502 return create_file(state
, patch
);
4506 * Rename or modification boils down to the same
4507 * thing: remove the old, write the new
4510 return remove_file(state
, patch
, patch
->is_rename
);
4512 return create_file(state
, patch
);
4516 static int write_out_one_reject(struct apply_state
*state
, struct patch
*patch
)
4519 char namebuf
[PATH_MAX
];
4520 struct fragment
*frag
;
4522 struct strbuf sb
= STRBUF_INIT
;
4524 for (cnt
= 0, frag
= patch
->fragments
; frag
; frag
= frag
->next
) {
4525 if (!frag
->rejected
)
4531 if (state
->apply_verbosity
> verbosity_normal
)
4532 say_patch_name(stderr
,
4533 _("Applied patch %s cleanly."), patch
);
4537 /* This should not happen, because a removal patch that leaves
4538 * contents are marked "rejected" at the patch level.
4540 if (!patch
->new_name
)
4541 die(_("internal error"));
4543 /* Say this even without --verbose */
4544 strbuf_addf(&sb
, Q_("Applying patch %%s with %d reject...",
4545 "Applying patch %%s with %d rejects...",
4548 if (state
->apply_verbosity
> verbosity_silent
)
4549 say_patch_name(stderr
, sb
.buf
, patch
);
4550 strbuf_release(&sb
);
4552 cnt
= strlen(patch
->new_name
);
4553 if (ARRAY_SIZE(namebuf
) <= cnt
+ 5) {
4554 cnt
= ARRAY_SIZE(namebuf
) - 5;
4555 warning(_("truncating .rej filename to %.*s.rej"),
4556 cnt
- 1, patch
->new_name
);
4558 memcpy(namebuf
, patch
->new_name
, cnt
);
4559 memcpy(namebuf
+ cnt
, ".rej", 5);
4561 rej
= fopen(namebuf
, "w");
4563 return error_errno(_("cannot open %s"), namebuf
);
4565 /* Normal git tools never deal with .rej, so do not pretend
4566 * this is a git patch by saying --git or giving extended
4567 * headers. While at it, maybe please "kompare" that wants
4568 * the trailing TAB and some garbage at the end of line ;-).
4570 fprintf(rej
, "diff a/%s b/%s\t(rejected hunks)\n",
4571 patch
->new_name
, patch
->new_name
);
4572 for (cnt
= 1, frag
= patch
->fragments
;
4574 cnt
++, frag
= frag
->next
) {
4575 if (!frag
->rejected
) {
4576 if (state
->apply_verbosity
> verbosity_silent
)
4577 fprintf_ln(stderr
, _("Hunk #%d applied cleanly."), cnt
);
4580 if (state
->apply_verbosity
> verbosity_silent
)
4581 fprintf_ln(stderr
, _("Rejected hunk #%d."), cnt
);
4582 fprintf(rej
, "%.*s", frag
->size
, frag
->patch
);
4583 if (frag
->patch
[frag
->size
-1] != '\n')
4592 * -1 if an error happened
4593 * 0 if the patch applied cleanly
4594 * 1 if the patch did not apply cleanly
4596 static int write_out_results(struct apply_state
*state
, struct patch
*list
)
4601 struct string_list cpath
= STRING_LIST_INIT_DUP
;
4603 for (phase
= 0; phase
< 2; phase
++) {
4609 if (write_out_one_result(state
, l
, phase
)) {
4610 string_list_clear(&cpath
, 0);
4614 if (write_out_one_reject(state
, l
))
4616 if (l
->conflicted_threeway
) {
4617 string_list_append(&cpath
, l
->new_name
);
4627 struct string_list_item
*item
;
4629 string_list_sort(&cpath
);
4630 if (state
->apply_verbosity
> verbosity_silent
) {
4631 for_each_string_list_item(item
, &cpath
)
4632 fprintf(stderr
, "U %s\n", item
->string
);
4634 string_list_clear(&cpath
, 0);
4643 * Try to apply a patch.
4646 * -128 if a bad error happened (like patch unreadable)
4647 * -1 if patch did not apply and user cannot deal with it
4648 * 0 if the patch applied
4649 * 1 if the patch did not apply but user might fix it
4651 static int apply_patch(struct apply_state
*state
,
4653 const char *filename
,
4657 struct strbuf buf
= STRBUF_INIT
; /* owns the patch text */
4658 struct patch
*list
= NULL
, **listp
= &list
;
4659 int skipped_patch
= 0;
4662 state
->patch_input_file
= filename
;
4663 if (read_patch_file(&buf
, fd
) < 0)
4666 while (offset
< buf
.len
) {
4667 struct patch
*patch
;
4670 patch
= xcalloc(1, sizeof(*patch
));
4671 patch
->inaccurate_eof
= !!(options
& APPLY_OPT_INACCURATE_EOF
);
4672 patch
->recount
= !!(options
& APPLY_OPT_RECOUNT
);
4673 nr
= parse_chunk(state
, buf
.buf
+ offset
, buf
.len
- offset
, patch
);
4682 if (state
->apply_in_reverse
)
4683 reverse_patches(patch
);
4684 if (use_patch(state
, patch
)) {
4685 patch_stats(state
, patch
);
4687 listp
= &patch
->next
;
4690 if (state
->apply_verbosity
> verbosity_normal
)
4691 say_patch_name(stderr
, _("Skipped patch '%s'."), patch
);
4698 if (!list
&& !skipped_patch
) {
4699 error(_("unrecognized input"));
4704 if (state
->whitespace_error
&& (state
->ws_error_action
== die_on_ws_error
))
4707 state
->update_index
= state
->check_index
&& state
->apply
;
4708 if (state
->update_index
&& state
->newfd
< 0) {
4709 if (state
->index_file
)
4710 state
->newfd
= hold_lock_file_for_update(&state
->lock_file
,
4714 state
->newfd
= hold_locked_index(&state
->lock_file
, LOCK_DIE_ON_ERROR
);
4717 if (state
->check_index
&& read_apply_cache(state
) < 0) {
4718 error(_("unable to read index file"));
4723 if (state
->check
|| state
->apply
) {
4724 int r
= check_patch_list(state
, list
);
4729 if (r
< 0 && !state
->apply_with_reject
) {
4736 int write_res
= write_out_results(state
, list
);
4737 if (write_res
< 0) {
4741 if (write_res
> 0) {
4742 /* with --3way, we still need to write the index out */
4743 res
= state
->apply_with_reject
? -1 : 1;
4748 if (state
->fake_ancestor
&&
4749 build_fake_ancestor(state
, list
)) {
4754 if (state
->diffstat
&& state
->apply_verbosity
> verbosity_silent
)
4755 stat_patch_list(state
, list
);
4757 if (state
->numstat
&& state
->apply_verbosity
> verbosity_silent
)
4758 numstat_patch_list(state
, list
);
4760 if (state
->summary
&& state
->apply_verbosity
> verbosity_silent
)
4761 summary_patch_list(list
);
4764 free_patch_list(list
);
4765 strbuf_release(&buf
);
4766 string_list_clear(&state
->fn_table
, 0);
4770 static int apply_option_parse_exclude(const struct option
*opt
,
4771 const char *arg
, int unset
)
4773 struct apply_state
*state
= opt
->value
;
4774 add_name_limit(state
, arg
, 1);
4778 static int apply_option_parse_include(const struct option
*opt
,
4779 const char *arg
, int unset
)
4781 struct apply_state
*state
= opt
->value
;
4782 add_name_limit(state
, arg
, 0);
4783 state
->has_include
= 1;
4787 static int apply_option_parse_p(const struct option
*opt
,
4791 struct apply_state
*state
= opt
->value
;
4792 state
->p_value
= atoi(arg
);
4793 state
->p_value_known
= 1;
4797 static int apply_option_parse_space_change(const struct option
*opt
,
4798 const char *arg
, int unset
)
4800 struct apply_state
*state
= opt
->value
;
4802 state
->ws_ignore_action
= ignore_ws_none
;
4804 state
->ws_ignore_action
= ignore_ws_change
;
4808 static int apply_option_parse_whitespace(const struct option
*opt
,
4809 const char *arg
, int unset
)
4811 struct apply_state
*state
= opt
->value
;
4812 state
->whitespace_option
= arg
;
4813 if (parse_whitespace_option(state
, arg
))
4818 static int apply_option_parse_directory(const struct option
*opt
,
4819 const char *arg
, int unset
)
4821 struct apply_state
*state
= opt
->value
;
4822 strbuf_reset(&state
->root
);
4823 strbuf_addstr(&state
->root
, arg
);
4824 strbuf_complete(&state
->root
, '/');
4828 int apply_all_patches(struct apply_state
*state
,
4838 for (i
= 0; i
< argc
; i
++) {
4839 const char *arg
= argv
[i
];
4840 char *to_free
= NULL
;
4843 if (!strcmp(arg
, "-")) {
4844 res
= apply_patch(state
, 0, "<stdin>", options
);
4851 arg
= to_free
= prefix_filename(state
->prefix
, arg
);
4853 fd
= open(arg
, O_RDONLY
);
4855 error(_("can't open patch '%s': %s"), arg
, strerror(errno
));
4861 set_default_whitespace_mode(state
);
4862 res
= apply_patch(state
, fd
, arg
, options
);
4869 set_default_whitespace_mode(state
);
4871 res
= apply_patch(state
, 0, "<stdin>", options
);
4877 if (state
->whitespace_error
) {
4878 if (state
->squelch_whitespace_errors
&&
4879 state
->squelch_whitespace_errors
< state
->whitespace_error
) {
4881 state
->whitespace_error
- state
->squelch_whitespace_errors
;
4882 warning(Q_("squelched %d whitespace error",
4883 "squelched %d whitespace errors",
4887 if (state
->ws_error_action
== die_on_ws_error
) {
4888 error(Q_("%d line adds whitespace errors.",
4889 "%d lines add whitespace errors.",
4890 state
->whitespace_error
),
4891 state
->whitespace_error
);
4895 if (state
->applied_after_fixing_ws
&& state
->apply
)
4896 warning(Q_("%d line applied after"
4897 " fixing whitespace errors.",
4898 "%d lines applied after"
4899 " fixing whitespace errors.",
4900 state
->applied_after_fixing_ws
),
4901 state
->applied_after_fixing_ws
);
4902 else if (state
->whitespace_error
)
4903 warning(Q_("%d line adds whitespace errors.",
4904 "%d lines add whitespace errors.",
4905 state
->whitespace_error
),
4906 state
->whitespace_error
);
4909 if (state
->update_index
) {
4910 res
= write_locked_index(&the_index
, &state
->lock_file
, COMMIT_LOCK
);
4912 error(_("Unable to write new index file"));
4922 if (state
->newfd
>= 0) {
4923 rollback_lock_file(&state
->lock_file
);
4927 if (state
->apply_verbosity
<= verbosity_silent
) {
4928 set_error_routine(state
->saved_error_routine
);
4929 set_warn_routine(state
->saved_warn_routine
);
4934 return (res
== -1 ? 1 : 128);
4937 int apply_parse_options(int argc
, const char **argv
,
4938 struct apply_state
*state
,
4939 int *force_apply
, int *options
,
4940 const char * const *apply_usage
)
4942 struct option builtin_apply_options
[] = {
4943 { OPTION_CALLBACK
, 0, "exclude", state
, N_("path"),
4944 N_("don't apply changes matching the given path"),
4945 0, apply_option_parse_exclude
},
4946 { OPTION_CALLBACK
, 0, "include", state
, N_("path"),
4947 N_("apply changes matching the given path"),
4948 0, apply_option_parse_include
},
4949 { OPTION_CALLBACK
, 'p', NULL
, state
, N_("num"),
4950 N_("remove <num> leading slashes from traditional diff paths"),
4951 0, apply_option_parse_p
},
4952 OPT_BOOL(0, "no-add", &state
->no_add
,
4953 N_("ignore additions made by the patch")),
4954 OPT_BOOL(0, "stat", &state
->diffstat
,
4955 N_("instead of applying the patch, output diffstat for the input")),
4956 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
4957 OPT_NOOP_NOARG(0, "binary"),
4958 OPT_BOOL(0, "numstat", &state
->numstat
,
4959 N_("show number of added and deleted lines in decimal notation")),
4960 OPT_BOOL(0, "summary", &state
->summary
,
4961 N_("instead of applying the patch, output a summary for the input")),
4962 OPT_BOOL(0, "check", &state
->check
,
4963 N_("instead of applying the patch, see if the patch is applicable")),
4964 OPT_BOOL(0, "index", &state
->check_index
,
4965 N_("make sure the patch is applicable to the current index")),
4966 OPT_BOOL(0, "cached", &state
->cached
,
4967 N_("apply a patch without touching the working tree")),
4968 OPT_BOOL(0, "unsafe-paths", &state
->unsafe_paths
,
4969 N_("accept a patch that touches outside the working area")),
4970 OPT_BOOL(0, "apply", force_apply
,
4971 N_("also apply the patch (use with --stat/--summary/--check)")),
4972 OPT_BOOL('3', "3way", &state
->threeway
,
4973 N_( "attempt three-way merge if a patch does not apply")),
4974 OPT_FILENAME(0, "build-fake-ancestor", &state
->fake_ancestor
,
4975 N_("build a temporary index based on embedded index information")),
4976 /* Think twice before adding "--nul" synonym to this */
4977 OPT_SET_INT('z', NULL
, &state
->line_termination
,
4978 N_("paths are separated with NUL character"), '\0'),
4979 OPT_INTEGER('C', NULL
, &state
->p_context
,
4980 N_("ensure at least <n> lines of context match")),
4981 { OPTION_CALLBACK
, 0, "whitespace", state
, N_("action"),
4982 N_("detect new or modified lines that have whitespace errors"),
4983 0, apply_option_parse_whitespace
},
4984 { OPTION_CALLBACK
, 0, "ignore-space-change", state
, NULL
,
4985 N_("ignore changes in whitespace when finding context"),
4986 PARSE_OPT_NOARG
, apply_option_parse_space_change
},
4987 { OPTION_CALLBACK
, 0, "ignore-whitespace", state
, NULL
,
4988 N_("ignore changes in whitespace when finding context"),
4989 PARSE_OPT_NOARG
, apply_option_parse_space_change
},
4990 OPT_BOOL('R', "reverse", &state
->apply_in_reverse
,
4991 N_("apply the patch in reverse")),
4992 OPT_BOOL(0, "unidiff-zero", &state
->unidiff_zero
,
4993 N_("don't expect at least one line of context")),
4994 OPT_BOOL(0, "reject", &state
->apply_with_reject
,
4995 N_("leave the rejected hunks in corresponding *.rej files")),
4996 OPT_BOOL(0, "allow-overlap", &state
->allow_overlap
,
4997 N_("allow overlapping hunks")),
4998 OPT__VERBOSE(&state
->apply_verbosity
, N_("be verbose")),
4999 OPT_BIT(0, "inaccurate-eof", options
,
5000 N_("tolerate incorrectly detected missing new-line at the end of file"),
5001 APPLY_OPT_INACCURATE_EOF
),
5002 OPT_BIT(0, "recount", options
,
5003 N_("do not trust the line counts in the hunk headers"),
5005 { OPTION_CALLBACK
, 0, "directory", state
, N_("root"),
5006 N_("prepend <root> to all filenames"),
5007 0, apply_option_parse_directory
},
5011 return parse_options(argc
, argv
, state
->prefix
, builtin_apply_options
, apply_usage
, 0);