4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
12 #include "object-store.h"
17 #include "xdiff-interface.h"
20 #include "parse-options.h"
32 static void git_apply_config(void)
34 git_config_get_string("apply.whitespace", &apply_default_whitespace
);
35 git_config_get_string("apply.ignorewhitespace", &apply_default_ignorewhitespace
);
36 git_config(git_xmerge_config
, NULL
);
39 static int parse_whitespace_option(struct apply_state
*state
, const char *option
)
42 state
->ws_error_action
= warn_on_ws_error
;
45 if (!strcmp(option
, "warn")) {
46 state
->ws_error_action
= warn_on_ws_error
;
49 if (!strcmp(option
, "nowarn")) {
50 state
->ws_error_action
= nowarn_ws_error
;
53 if (!strcmp(option
, "error")) {
54 state
->ws_error_action
= die_on_ws_error
;
57 if (!strcmp(option
, "error-all")) {
58 state
->ws_error_action
= die_on_ws_error
;
59 state
->squelch_whitespace_errors
= 0;
62 if (!strcmp(option
, "strip") || !strcmp(option
, "fix")) {
63 state
->ws_error_action
= correct_ws_error
;
67 * Please update $__git_whitespacelist in git-completion.bash
68 * when you add new options.
70 return error(_("unrecognized whitespace option '%s'"), option
);
73 static int parse_ignorewhitespace_option(struct apply_state
*state
,
76 if (!option
|| !strcmp(option
, "no") ||
77 !strcmp(option
, "false") || !strcmp(option
, "never") ||
78 !strcmp(option
, "none")) {
79 state
->ws_ignore_action
= ignore_ws_none
;
82 if (!strcmp(option
, "change")) {
83 state
->ws_ignore_action
= ignore_ws_change
;
86 return error(_("unrecognized whitespace ignore option '%s'"), option
);
89 int init_apply_state(struct apply_state
*state
,
90 struct repository
*repo
,
93 memset(state
, 0, sizeof(*state
));
94 state
->prefix
= prefix
;
97 state
->line_termination
= '\n';
99 state
->p_context
= UINT_MAX
;
100 state
->squelch_whitespace_errors
= 5;
101 state
->ws_error_action
= warn_on_ws_error
;
102 state
->ws_ignore_action
= ignore_ws_none
;
104 string_list_init_nodup(&state
->fn_table
);
105 string_list_init_nodup(&state
->limit_by_name
);
106 strset_init(&state
->removed_symlinks
);
107 strset_init(&state
->kept_symlinks
);
108 strbuf_init(&state
->root
, 0);
111 if (apply_default_whitespace
&& parse_whitespace_option(state
, apply_default_whitespace
))
113 if (apply_default_ignorewhitespace
&& parse_ignorewhitespace_option(state
, apply_default_ignorewhitespace
))
118 void clear_apply_state(struct apply_state
*state
)
120 string_list_clear(&state
->limit_by_name
, 0);
121 strset_clear(&state
->removed_symlinks
);
122 strset_clear(&state
->kept_symlinks
);
123 strbuf_release(&state
->root
);
125 /* &state->fn_table is cleared at the end of apply_patch() */
128 static void mute_routine(const char *msg
, va_list params
)
133 int check_apply_state(struct apply_state
*state
, int force_apply
)
135 int is_not_gitdir
= !startup_info
->have_repository
;
137 if (state
->apply_with_reject
&& state
->threeway
)
138 return error(_("options '%s' and '%s' cannot be used together"), "--reject", "--3way");
139 if (state
->threeway
) {
141 return error(_("'%s' outside a repository"), "--3way");
142 state
->check_index
= 1;
144 if (state
->apply_with_reject
) {
146 if (state
->apply_verbosity
== verbosity_normal
)
147 state
->apply_verbosity
= verbosity_verbose
;
149 if (!force_apply
&& (state
->diffstat
|| state
->numstat
|| state
->summary
|| state
->check
|| state
->fake_ancestor
))
151 if (state
->check_index
&& is_not_gitdir
)
152 return error(_("'%s' outside a repository"), "--index");
155 return error(_("'%s' outside a repository"), "--cached");
156 state
->check_index
= 1;
158 if (state
->ita_only
&& (state
->check_index
|| is_not_gitdir
))
160 if (state
->check_index
)
161 state
->unsafe_paths
= 0;
163 if (state
->apply_verbosity
<= verbosity_silent
) {
164 state
->saved_error_routine
= get_error_routine();
165 state
->saved_warn_routine
= get_warn_routine();
166 set_error_routine(mute_routine
);
167 set_warn_routine(mute_routine
);
173 static void set_default_whitespace_mode(struct apply_state
*state
)
175 if (!state
->whitespace_option
&& !apply_default_whitespace
)
176 state
->ws_error_action
= (state
->apply
? warn_on_ws_error
: nowarn_ws_error
);
180 * This represents one "hunk" from a patch, starting with
181 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
182 * patch text is pointed at by patch, and its byte length
183 * is stored in size. leading and trailing are the number
187 unsigned long leading
, trailing
;
188 unsigned long oldpos
, oldlines
;
189 unsigned long newpos
, newlines
;
191 * 'patch' is usually borrowed from buf in apply_patch(),
192 * but some codepaths store an allocated buffer.
195 unsigned free_patch
:1,
199 struct fragment
*next
;
203 * When dealing with a binary patch, we reuse "leading" field
204 * to store the type of the binary hunk, either deflated "delta"
205 * or deflated "literal".
207 #define binary_patch_method leading
208 #define BINARY_DELTA_DEFLATED 1
209 #define BINARY_LITERAL_DEFLATED 2
211 static void free_fragment_list(struct fragment
*list
)
214 struct fragment
*next
= list
->next
;
215 if (list
->free_patch
)
216 free((char *)list
->patch
);
222 void release_patch(struct patch
*patch
)
224 free_fragment_list(patch
->fragments
);
225 free(patch
->def_name
);
226 free(patch
->old_name
);
227 free(patch
->new_name
);
231 static void free_patch(struct patch
*patch
)
233 release_patch(patch
);
237 static void free_patch_list(struct patch
*list
)
240 struct patch
*next
= list
->next
;
247 * A line in a file, len-bytes long (includes the terminating LF,
248 * except for an incomplete line at the end if the file ends with
249 * one), and its contents hashes to 'hash'.
255 #define LINE_COMMON 1
256 #define LINE_PATCHED 2
260 * This represents a "file", which is an array of "lines".
267 struct line
*line_allocated
;
271 static uint32_t hash_line(const char *cp
, size_t len
)
275 for (i
= 0, h
= 0; i
< len
; i
++) {
276 if (!isspace(cp
[i
])) {
277 h
= h
* 3 + (cp
[i
] & 0xff);
284 * Compare lines s1 of length n1 and s2 of length n2, ignoring
285 * whitespace difference. Returns 1 if they match, 0 otherwise
287 static int fuzzy_matchlines(const char *s1
, size_t n1
,
288 const char *s2
, size_t n2
)
290 const char *end1
= s1
+ n1
;
291 const char *end2
= s2
+ n2
;
293 /* ignore line endings */
294 while (s1
< end1
&& (end1
[-1] == '\r' || end1
[-1] == '\n'))
296 while (s2
< end2
&& (end2
[-1] == '\r' || end2
[-1] == '\n'))
299 while (s1
< end1
&& s2
< end2
) {
302 * Skip whitespace. We check on both buffers
303 * because we don't want "a b" to match "ab".
307 while (s1
< end1
&& isspace(*s1
))
309 while (s2
< end2
&& isspace(*s2
))
311 } else if (*s1
++ != *s2
++)
315 /* If we reached the end on one side only, lines don't match. */
316 return s1
== end1
&& s2
== end2
;
319 static void add_line_info(struct image
*img
, const char *bol
, size_t len
, unsigned flag
)
321 ALLOC_GROW(img
->line_allocated
, img
->nr
+ 1, img
->alloc
);
322 img
->line_allocated
[img
->nr
].len
= len
;
323 img
->line_allocated
[img
->nr
].hash
= hash_line(bol
, len
);
324 img
->line_allocated
[img
->nr
].flag
= flag
;
329 * "buf" has the file contents to be patched (read from various sources).
330 * attach it to "image" and add line-based index to it.
331 * "image" now owns the "buf".
333 static void prepare_image(struct image
*image
, char *buf
, size_t len
,
334 int prepare_linetable
)
338 memset(image
, 0, sizeof(*image
));
342 if (!prepare_linetable
)
345 ep
= image
->buf
+ image
->len
;
349 for (next
= cp
; next
< ep
&& *next
!= '\n'; next
++)
353 add_line_info(image
, cp
, next
- cp
, 0);
356 image
->line
= image
->line_allocated
;
359 static void clear_image(struct image
*image
)
362 free(image
->line_allocated
);
363 memset(image
, 0, sizeof(*image
));
366 /* fmt must contain _one_ %s and no other substitution */
367 static void say_patch_name(FILE *output
, const char *fmt
, struct patch
*patch
)
369 struct strbuf sb
= STRBUF_INIT
;
371 if (patch
->old_name
&& patch
->new_name
&&
372 strcmp(patch
->old_name
, patch
->new_name
)) {
373 quote_c_style(patch
->old_name
, &sb
, NULL
, 0);
374 strbuf_addstr(&sb
, " => ");
375 quote_c_style(patch
->new_name
, &sb
, NULL
, 0);
377 const char *n
= patch
->new_name
;
380 quote_c_style(n
, &sb
, NULL
, 0);
382 fprintf(output
, fmt
, sb
.buf
);
389 static int read_patch_file(struct strbuf
*sb
, int fd
)
391 if (strbuf_read(sb
, fd
, 0) < 0)
392 return error_errno("git apply: failed to read");
395 * Make sure that we have some slop in the buffer
396 * so that we can do speculative "memcmp" etc, and
397 * see to it that it is NUL-filled.
399 strbuf_grow(sb
, SLOP
);
400 memset(sb
->buf
+ sb
->len
, 0, SLOP
);
404 static unsigned long linelen(const char *buffer
, unsigned long size
)
406 unsigned long len
= 0;
409 if (*buffer
++ == '\n')
415 static int is_dev_null(const char *str
)
417 return skip_prefix(str
, "/dev/null", &str
) && isspace(*str
);
423 static int name_terminate(int c
, int terminate
)
425 if (c
== ' ' && !(terminate
& TERM_SPACE
))
427 if (c
== '\t' && !(terminate
& TERM_TAB
))
433 /* remove double slashes to make --index work with such filenames */
434 static char *squash_slash(char *name
)
442 if ((name
[j
++] = name
[i
++]) == '/')
443 while (name
[i
] == '/')
450 static char *find_name_gnu(struct strbuf
*root
,
454 struct strbuf name
= STRBUF_INIT
;
458 * Proposed "new-style" GNU patch/diff format; see
459 * https://lore.kernel.org/git/7vll0wvb2a.fsf@assigned-by-dhcp.cox.net/
461 if (unquote_c_style(&name
, line
, NULL
)) {
462 strbuf_release(&name
);
466 for (cp
= name
.buf
; p_value
; p_value
--) {
467 cp
= strchr(cp
, '/');
469 strbuf_release(&name
);
475 strbuf_remove(&name
, 0, cp
- name
.buf
);
477 strbuf_insert(&name
, 0, root
->buf
, root
->len
);
478 return squash_slash(strbuf_detach(&name
, NULL
));
481 static size_t sane_tz_len(const char *line
, size_t len
)
485 if (len
< strlen(" +0500") || line
[len
-strlen(" +0500")] != ' ')
487 tz
= line
+ len
- strlen(" +0500");
489 if (tz
[1] != '+' && tz
[1] != '-')
492 for (p
= tz
+ 2; p
!= line
+ len
; p
++)
496 return line
+ len
- tz
;
499 static size_t tz_with_colon_len(const char *line
, size_t len
)
503 if (len
< strlen(" +08:00") || line
[len
- strlen(":00")] != ':')
505 tz
= line
+ len
- strlen(" +08:00");
507 if (tz
[0] != ' ' || (tz
[1] != '+' && tz
[1] != '-'))
510 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
511 !isdigit(*p
++) || !isdigit(*p
++))
514 return line
+ len
- tz
;
517 static size_t date_len(const char *line
, size_t len
)
519 const char *date
, *p
;
521 if (len
< strlen("72-02-05") || line
[len
-strlen("-05")] != '-')
523 p
= date
= line
+ len
- strlen("72-02-05");
525 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
526 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
527 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a date. */
530 if (date
- line
>= strlen("19") &&
531 isdigit(date
[-1]) && isdigit(date
[-2])) /* 4-digit year */
532 date
-= strlen("19");
534 return line
+ len
- date
;
537 static size_t short_time_len(const char *line
, size_t len
)
539 const char *time
, *p
;
541 if (len
< strlen(" 07:01:32") || line
[len
-strlen(":32")] != ':')
543 p
= time
= line
+ len
- strlen(" 07:01:32");
545 /* Permit 1-digit hours? */
547 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
548 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
549 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a time. */
552 return line
+ len
- time
;
555 static size_t fractional_time_len(const char *line
, size_t len
)
560 /* Expected format: 19:41:17.620000023 */
561 if (!len
|| !isdigit(line
[len
- 1]))
565 /* Fractional seconds. */
566 while (p
> line
&& isdigit(*p
))
571 /* Hours, minutes, and whole seconds. */
572 n
= short_time_len(line
, p
- line
);
576 return line
+ len
- p
+ n
;
579 static size_t trailing_spaces_len(const char *line
, size_t len
)
583 /* Expected format: ' ' x (1 or more) */
584 if (!len
|| line
[len
- 1] != ' ')
591 return line
+ len
- (p
+ 1);
598 static size_t diff_timestamp_len(const char *line
, size_t len
)
600 const char *end
= line
+ len
;
604 * Posix: 2010-07-05 19:41:17
605 * GNU: 2010-07-05 19:41:17.620000023 -0500
608 if (!isdigit(end
[-1]))
611 n
= sane_tz_len(line
, end
- line
);
613 n
= tz_with_colon_len(line
, end
- line
);
616 n
= short_time_len(line
, end
- line
);
618 n
= fractional_time_len(line
, end
- line
);
621 n
= date_len(line
, end
- line
);
622 if (!n
) /* No date. Too bad. */
626 if (end
== line
) /* No space before date. */
628 if (end
[-1] == '\t') { /* Success! */
630 return line
+ len
- end
;
632 if (end
[-1] != ' ') /* No space before date. */
635 /* Whitespace damage. */
636 end
-= trailing_spaces_len(line
, end
- line
);
637 return line
+ len
- end
;
640 static char *find_name_common(struct strbuf
*root
,
648 const char *start
= NULL
;
652 while (line
!= end
) {
655 if (!end
&& isspace(c
)) {
658 if (name_terminate(c
, terminate
))
662 if (c
== '/' && !--p_value
)
666 return squash_slash(xstrdup_or_null(def
));
669 return squash_slash(xstrdup_or_null(def
));
672 * Generally we prefer the shorter name, especially
673 * if the other one is just a variation of that with
674 * something else tacked on to the end (ie "file.orig"
678 int deflen
= strlen(def
);
679 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
680 return squash_slash(xstrdup(def
));
684 char *ret
= xstrfmt("%s%.*s", root
->buf
, len
, start
);
685 return squash_slash(ret
);
688 return squash_slash(xmemdupz(start
, len
));
691 static char *find_name(struct strbuf
*root
,
698 char *name
= find_name_gnu(root
, line
, p_value
);
703 return find_name_common(root
, line
, def
, p_value
, NULL
, terminate
);
706 static char *find_name_traditional(struct strbuf
*root
,
715 char *name
= find_name_gnu(root
, line
, p_value
);
720 len
= strchrnul(line
, '\n') - line
;
721 date_len
= diff_timestamp_len(line
, len
);
723 return find_name_common(root
, line
, def
, p_value
, NULL
, TERM_TAB
);
726 return find_name_common(root
, line
, def
, p_value
, line
+ len
, 0);
730 * Given the string after "--- " or "+++ ", guess the appropriate
731 * p_value for the given patch.
733 static int guess_p_value(struct apply_state
*state
, const char *nameline
)
738 if (is_dev_null(nameline
))
740 name
= find_name_traditional(&state
->root
, nameline
, NULL
, 0);
743 cp
= strchr(name
, '/');
746 else if (state
->prefix
) {
748 * Does it begin with "a/$our-prefix" and such? Then this is
749 * very likely to apply to our directory.
751 if (starts_with(name
, state
->prefix
))
752 val
= count_slashes(state
->prefix
);
755 if (starts_with(cp
, state
->prefix
))
756 val
= count_slashes(state
->prefix
) + 1;
764 * Does the ---/+++ line have the POSIX timestamp after the last HT?
765 * GNU diff puts epoch there to signal a creation/deletion event. Is
766 * this such a timestamp?
768 static int has_epoch_timestamp(const char *nameline
)
771 * We are only interested in epoch timestamp; any non-zero
772 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
773 * For the same reason, the date must be either 1969-12-31 or
774 * 1970-01-01, and the seconds part must be "00".
776 const char stamp_regexp
[] =
777 "^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?"
779 "([-+][0-2][0-9]:?[0-5][0-9])\n";
780 const char *timestamp
= NULL
, *cp
, *colon
;
781 static regex_t
*stamp
;
783 int zoneoffset
, epoch_hour
, hour
, minute
;
786 for (cp
= nameline
; *cp
!= '\n'; cp
++) {
794 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
795 * (west of GMT) or 1970-01-01 (east of GMT)
797 if (skip_prefix(timestamp
, "1969-12-31 ", ×tamp
))
799 else if (skip_prefix(timestamp
, "1970-01-01 ", ×tamp
))
805 stamp
= xmalloc(sizeof(*stamp
));
806 if (regcomp(stamp
, stamp_regexp
, REG_EXTENDED
)) {
807 warning(_("Cannot prepare timestamp regexp %s"),
813 status
= regexec(stamp
, timestamp
, ARRAY_SIZE(m
), m
, 0);
815 if (status
!= REG_NOMATCH
)
816 warning(_("regexec returned %d for input: %s"),
821 hour
= strtol(timestamp
, NULL
, 10);
822 minute
= strtol(timestamp
+ m
[1].rm_so
, NULL
, 10);
824 zoneoffset
= strtol(timestamp
+ m
[3].rm_so
+ 1, (char **) &colon
, 10);
826 zoneoffset
= zoneoffset
* 60 + strtol(colon
+ 1, NULL
, 10);
828 zoneoffset
= (zoneoffset
/ 100) * 60 + (zoneoffset
% 100);
829 if (timestamp
[m
[3].rm_so
] == '-')
830 zoneoffset
= -zoneoffset
;
832 return hour
* 60 + minute
- zoneoffset
== epoch_hour
* 60;
836 * Get the name etc info from the ---/+++ lines of a traditional patch header
838 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
839 * files, we can happily check the index for a match, but for creating a
840 * new file we should try to match whatever "patch" does. I have no idea.
842 static int parse_traditional_patch(struct apply_state
*state
,
849 first
+= 4; /* skip "--- " */
850 second
+= 4; /* skip "+++ " */
851 if (!state
->p_value_known
) {
853 p
= guess_p_value(state
, first
);
854 q
= guess_p_value(state
, second
);
856 if (0 <= p
&& p
== q
) {
858 state
->p_value_known
= 1;
861 if (is_dev_null(first
)) {
863 patch
->is_delete
= 0;
864 name
= find_name_traditional(&state
->root
, second
, NULL
, state
->p_value
);
865 patch
->new_name
= name
;
866 } else if (is_dev_null(second
)) {
868 patch
->is_delete
= 1;
869 name
= find_name_traditional(&state
->root
, first
, NULL
, state
->p_value
);
870 patch
->old_name
= name
;
873 first_name
= find_name_traditional(&state
->root
, first
, NULL
, state
->p_value
);
874 name
= find_name_traditional(&state
->root
, second
, first_name
, state
->p_value
);
876 if (has_epoch_timestamp(first
)) {
878 patch
->is_delete
= 0;
879 patch
->new_name
= name
;
880 } else if (has_epoch_timestamp(second
)) {
882 patch
->is_delete
= 1;
883 patch
->old_name
= name
;
885 patch
->old_name
= name
;
886 patch
->new_name
= xstrdup_or_null(name
);
890 return error(_("unable to find filename in patch at line %d"), state
->linenr
);
895 static int gitdiff_hdrend(struct gitdiff_data
*state
,
903 * We're anal about diff header consistency, to make
904 * sure that we don't end up having strange ambiguous
905 * patches floating around.
907 * As a result, gitdiff_{old|new}name() will check
908 * their names against any previous information, just
911 #define DIFF_OLD_NAME 0
912 #define DIFF_NEW_NAME 1
914 static int gitdiff_verify_name(struct gitdiff_data
*state
,
920 if (!*name
&& !isnull
) {
921 *name
= find_name(state
->root
, line
, NULL
, state
->p_value
, TERM_TAB
);
928 return error(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
929 *name
, state
->linenr
);
930 another
= find_name(state
->root
, line
, NULL
, state
->p_value
, TERM_TAB
);
931 if (!another
|| strcmp(another
, *name
)) {
933 return error((side
== DIFF_NEW_NAME
) ?
934 _("git apply: bad git-diff - inconsistent new filename on line %d") :
935 _("git apply: bad git-diff - inconsistent old filename on line %d"), state
->linenr
);
939 if (!is_dev_null(line
))
940 return error(_("git apply: bad git-diff - expected /dev/null on line %d"), state
->linenr
);
946 static int gitdiff_oldname(struct gitdiff_data
*state
,
950 return gitdiff_verify_name(state
, line
,
951 patch
->is_new
, &patch
->old_name
,
955 static int gitdiff_newname(struct gitdiff_data
*state
,
959 return gitdiff_verify_name(state
, line
,
960 patch
->is_delete
, &patch
->new_name
,
964 static int parse_mode_line(const char *line
, int linenr
, unsigned int *mode
)
967 *mode
= strtoul(line
, &end
, 8);
968 if (end
== line
|| !isspace(*end
))
969 return error(_("invalid mode on line %d: %s"), linenr
, line
);
973 static int gitdiff_oldmode(struct gitdiff_data
*state
,
977 return parse_mode_line(line
, state
->linenr
, &patch
->old_mode
);
980 static int gitdiff_newmode(struct gitdiff_data
*state
,
984 return parse_mode_line(line
, state
->linenr
, &patch
->new_mode
);
987 static int gitdiff_delete(struct gitdiff_data
*state
,
991 patch
->is_delete
= 1;
992 free(patch
->old_name
);
993 patch
->old_name
= xstrdup_or_null(patch
->def_name
);
994 return gitdiff_oldmode(state
, line
, patch
);
997 static int gitdiff_newfile(struct gitdiff_data
*state
,
1002 free(patch
->new_name
);
1003 patch
->new_name
= xstrdup_or_null(patch
->def_name
);
1004 return gitdiff_newmode(state
, line
, patch
);
1007 static int gitdiff_copysrc(struct gitdiff_data
*state
,
1009 struct patch
*patch
)
1012 free(patch
->old_name
);
1013 patch
->old_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1017 static int gitdiff_copydst(struct gitdiff_data
*state
,
1019 struct patch
*patch
)
1022 free(patch
->new_name
);
1023 patch
->new_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1027 static int gitdiff_renamesrc(struct gitdiff_data
*state
,
1029 struct patch
*patch
)
1031 patch
->is_rename
= 1;
1032 free(patch
->old_name
);
1033 patch
->old_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1037 static int gitdiff_renamedst(struct gitdiff_data
*state
,
1039 struct patch
*patch
)
1041 patch
->is_rename
= 1;
1042 free(patch
->new_name
);
1043 patch
->new_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1047 static int gitdiff_similarity(struct gitdiff_data
*state
,
1049 struct patch
*patch
)
1051 unsigned long val
= strtoul(line
, NULL
, 10);
1057 static int gitdiff_dissimilarity(struct gitdiff_data
*state
,
1059 struct patch
*patch
)
1061 unsigned long val
= strtoul(line
, NULL
, 10);
1067 static int gitdiff_index(struct gitdiff_data
*state
,
1069 struct patch
*patch
)
1072 * index line is N hexadecimal, "..", N hexadecimal,
1073 * and optional space with octal mode.
1075 const char *ptr
, *eol
;
1077 const unsigned hexsz
= the_hash_algo
->hexsz
;
1079 ptr
= strchr(line
, '.');
1080 if (!ptr
|| ptr
[1] != '.' || hexsz
< ptr
- line
)
1083 memcpy(patch
->old_oid_prefix
, line
, len
);
1084 patch
->old_oid_prefix
[len
] = 0;
1087 ptr
= strchr(line
, ' ');
1088 eol
= strchrnul(line
, '\n');
1090 if (!ptr
|| eol
< ptr
)
1096 memcpy(patch
->new_oid_prefix
, line
, len
);
1097 patch
->new_oid_prefix
[len
] = 0;
1099 return gitdiff_oldmode(state
, ptr
+ 1, patch
);
1104 * This is normal for a diff that doesn't change anything: we'll fall through
1105 * into the next diff. Tell the parser to break out.
1107 static int gitdiff_unrecognized(struct gitdiff_data
*state
,
1109 struct patch
*patch
)
1115 * Skip p_value leading components from "line"; as we do not accept
1116 * absolute paths, return NULL in that case.
1118 static const char *skip_tree_prefix(int p_value
,
1126 return (llen
&& line
[0] == '/') ? NULL
: line
;
1129 for (i
= 0; i
< llen
; i
++) {
1131 if (ch
== '/' && --nslash
<= 0)
1132 return (i
== 0) ? NULL
: &line
[i
+ 1];
1138 * This is to extract the same name that appears on "diff --git"
1139 * line. We do not find and return anything if it is a rename
1140 * patch, and it is OK because we will find the name elsewhere.
1141 * We need to reliably find name only when it is mode-change only,
1142 * creation or deletion of an empty file. In any of these cases,
1143 * both sides are the same name under a/ and b/ respectively.
1145 static char *git_header_name(int p_value
,
1150 const char *second
= NULL
;
1151 size_t len
, line_len
;
1153 line
+= strlen("diff --git ");
1154 llen
-= strlen("diff --git ");
1158 struct strbuf first
= STRBUF_INIT
;
1159 struct strbuf sp
= STRBUF_INIT
;
1161 if (unquote_c_style(&first
, line
, &second
))
1162 goto free_and_fail1
;
1164 /* strip the a/b prefix including trailing slash */
1165 cp
= skip_tree_prefix(p_value
, first
.buf
, first
.len
);
1167 goto free_and_fail1
;
1168 strbuf_remove(&first
, 0, cp
- first
.buf
);
1171 * second points at one past closing dq of name.
1172 * find the second name.
1174 while ((second
< line
+ llen
) && isspace(*second
))
1177 if (line
+ llen
<= second
)
1178 goto free_and_fail1
;
1179 if (*second
== '"') {
1180 if (unquote_c_style(&sp
, second
, NULL
))
1181 goto free_and_fail1
;
1182 cp
= skip_tree_prefix(p_value
, sp
.buf
, sp
.len
);
1184 goto free_and_fail1
;
1185 /* They must match, otherwise ignore */
1186 if (strcmp(cp
, first
.buf
))
1187 goto free_and_fail1
;
1188 strbuf_release(&sp
);
1189 return strbuf_detach(&first
, NULL
);
1192 /* unquoted second */
1193 cp
= skip_tree_prefix(p_value
, second
, line
+ llen
- second
);
1195 goto free_and_fail1
;
1196 if (line
+ llen
- cp
!= first
.len
||
1197 memcmp(first
.buf
, cp
, first
.len
))
1198 goto free_and_fail1
;
1199 return strbuf_detach(&first
, NULL
);
1202 strbuf_release(&first
);
1203 strbuf_release(&sp
);
1207 /* unquoted first name */
1208 name
= skip_tree_prefix(p_value
, line
, llen
);
1213 * since the first name is unquoted, a dq if exists must be
1214 * the beginning of the second name.
1216 for (second
= name
; second
< line
+ llen
; second
++) {
1217 if (*second
== '"') {
1218 struct strbuf sp
= STRBUF_INIT
;
1221 if (unquote_c_style(&sp
, second
, NULL
))
1222 goto free_and_fail2
;
1224 np
= skip_tree_prefix(p_value
, sp
.buf
, sp
.len
);
1226 goto free_and_fail2
;
1228 len
= sp
.buf
+ sp
.len
- np
;
1229 if (len
< second
- name
&&
1230 !strncmp(np
, name
, len
) &&
1231 isspace(name
[len
])) {
1233 strbuf_remove(&sp
, 0, np
- sp
.buf
);
1234 return strbuf_detach(&sp
, NULL
);
1238 strbuf_release(&sp
);
1244 * Accept a name only if it shows up twice, exactly the same
1247 second
= strchr(name
, '\n');
1250 line_len
= second
- name
;
1251 for (len
= 0 ; ; len
++) {
1252 switch (name
[len
]) {
1257 case '\t': case ' ':
1259 * Is this the separator between the preimage
1260 * and the postimage pathname? Again, we are
1261 * only interested in the case where there is
1262 * no rename, as this is only to set def_name
1263 * and a rename patch has the names elsewhere
1264 * in an unambiguous form.
1267 return NULL
; /* no postimage name */
1268 second
= skip_tree_prefix(p_value
, name
+ len
+ 1,
1269 line_len
- (len
+ 1));
1273 * Does len bytes starting at "name" and "second"
1274 * (that are separated by one HT or SP we just
1275 * found) exactly match?
1277 if (second
[len
] == '\n' && !strncmp(name
, second
, len
))
1278 return xmemdupz(name
, len
);
1283 static int check_header_line(int linenr
, struct patch
*patch
)
1285 int extensions
= (patch
->is_delete
== 1) + (patch
->is_new
== 1) +
1286 (patch
->is_rename
== 1) + (patch
->is_copy
== 1);
1288 return error(_("inconsistent header lines %d and %d"),
1289 patch
->extension_linenr
, linenr
);
1290 if (extensions
&& !patch
->extension_linenr
)
1291 patch
->extension_linenr
= linenr
;
1295 int parse_git_diff_header(struct strbuf
*root
,
1301 struct patch
*patch
)
1303 unsigned long offset
;
1304 struct gitdiff_data parse_hdr_state
;
1306 /* A git diff has explicit new/delete information, so we don't guess */
1308 patch
->is_delete
= 0;
1311 * Some things may not have the old name in the
1312 * rest of the headers anywhere (pure mode changes,
1313 * or removing or adding empty files), so we get
1314 * the default name from the header.
1316 patch
->def_name
= git_header_name(p_value
, line
, len
);
1317 if (patch
->def_name
&& root
->len
) {
1318 char *s
= xstrfmt("%s%s", root
->buf
, patch
->def_name
);
1319 free(patch
->def_name
);
1320 patch
->def_name
= s
;
1326 parse_hdr_state
.root
= root
;
1327 parse_hdr_state
.linenr
= *linenr
;
1328 parse_hdr_state
.p_value
= p_value
;
1330 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, (*linenr
)++) {
1331 static const struct opentry
{
1333 int (*fn
)(struct gitdiff_data
*, const char *, struct patch
*);
1335 { "@@ -", gitdiff_hdrend
},
1336 { "--- ", gitdiff_oldname
},
1337 { "+++ ", gitdiff_newname
},
1338 { "old mode ", gitdiff_oldmode
},
1339 { "new mode ", gitdiff_newmode
},
1340 { "deleted file mode ", gitdiff_delete
},
1341 { "new file mode ", gitdiff_newfile
},
1342 { "copy from ", gitdiff_copysrc
},
1343 { "copy to ", gitdiff_copydst
},
1344 { "rename old ", gitdiff_renamesrc
},
1345 { "rename new ", gitdiff_renamedst
},
1346 { "rename from ", gitdiff_renamesrc
},
1347 { "rename to ", gitdiff_renamedst
},
1348 { "similarity index ", gitdiff_similarity
},
1349 { "dissimilarity index ", gitdiff_dissimilarity
},
1350 { "index ", gitdiff_index
},
1351 { "", gitdiff_unrecognized
},
1355 len
= linelen(line
, size
);
1356 if (!len
|| line
[len
-1] != '\n')
1358 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
1359 const struct opentry
*p
= optable
+ i
;
1360 int oplen
= strlen(p
->str
);
1362 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
1364 res
= p
->fn(&parse_hdr_state
, line
+ oplen
, patch
);
1367 if (check_header_line(*linenr
, patch
))
1376 if (!patch
->old_name
&& !patch
->new_name
) {
1377 if (!patch
->def_name
) {
1378 error(Q_("git diff header lacks filename information when removing "
1379 "%d leading pathname component (line %d)",
1380 "git diff header lacks filename information when removing "
1381 "%d leading pathname components (line %d)",
1382 parse_hdr_state
.p_value
),
1383 parse_hdr_state
.p_value
, *linenr
);
1386 patch
->old_name
= xstrdup(patch
->def_name
);
1387 patch
->new_name
= xstrdup(patch
->def_name
);
1389 if ((!patch
->new_name
&& !patch
->is_delete
) ||
1390 (!patch
->old_name
&& !patch
->is_new
)) {
1391 error(_("git diff header lacks filename information "
1392 "(line %d)"), *linenr
);
1395 patch
->is_toplevel_relative
= 1;
1399 static int parse_num(const char *line
, unsigned long *p
)
1403 if (!isdigit(*line
))
1405 *p
= strtoul(line
, &ptr
, 10);
1409 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
1410 unsigned long *p1
, unsigned long *p2
)
1414 if (offset
< 0 || offset
>= len
)
1419 digits
= parse_num(line
, p1
);
1429 digits
= parse_num(line
+1, p2
);
1438 ex
= strlen(expect
);
1441 if (memcmp(line
, expect
, ex
))
1447 static void recount_diff(const char *line
, int size
, struct fragment
*fragment
)
1449 int oldlines
= 0, newlines
= 0, ret
= 0;
1452 warning("recount: ignore empty hunk");
1457 int len
= linelen(line
, size
);
1465 case ' ': case '\n':
1477 ret
= size
< 3 || !starts_with(line
, "@@ ");
1480 ret
= size
< 5 || !starts_with(line
, "diff ");
1487 warning(_("recount: unexpected line: %.*s"),
1488 (int)linelen(line
, size
), line
);
1493 fragment
->oldlines
= oldlines
;
1494 fragment
->newlines
= newlines
;
1498 * Parse a unified diff fragment header of the
1499 * form "@@ -a,b +c,d @@"
1501 static int parse_fragment_header(const char *line
, int len
, struct fragment
*fragment
)
1505 if (!len
|| line
[len
-1] != '\n')
1508 /* Figure out the number of lines in a fragment */
1509 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
1510 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
1516 * Find file diff header
1519 * -1 if no header was found
1520 * -128 in case of error
1521 * the size of the header in bytes (called "offset") otherwise
1523 static int find_header(struct apply_state
*state
,
1527 struct patch
*patch
)
1529 unsigned long offset
, len
;
1531 patch
->is_toplevel_relative
= 0;
1532 patch
->is_rename
= patch
->is_copy
= 0;
1533 patch
->is_new
= patch
->is_delete
= -1;
1534 patch
->old_mode
= patch
->new_mode
= 0;
1535 patch
->old_name
= patch
->new_name
= NULL
;
1536 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1537 unsigned long nextlen
;
1539 len
= linelen(line
, size
);
1543 /* Testing this early allows us to take a few shortcuts.. */
1548 * Make sure we don't find any unconnected patch fragments.
1549 * That's a sign that we didn't find a header, and that a
1550 * patch has become corrupted/broken up.
1552 if (!memcmp("@@ -", line
, 4)) {
1553 struct fragment dummy
;
1554 if (parse_fragment_header(line
, len
, &dummy
) < 0)
1556 error(_("patch fragment without header at line %d: %.*s"),
1557 state
->linenr
, (int)len
-1, line
);
1565 * Git patch? It might not have a real patch, just a rename
1566 * or mode change, so we handle that specially
1568 if (!memcmp("diff --git ", line
, 11)) {
1569 int git_hdr_len
= parse_git_diff_header(&state
->root
, &state
->linenr
,
1570 state
->p_value
, line
, len
,
1572 if (git_hdr_len
< 0)
1574 if (git_hdr_len
<= len
)
1576 *hdrsize
= git_hdr_len
;
1580 /* --- followed by +++ ? */
1581 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
1585 * We only accept unified patches, so we want it to
1586 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1587 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1589 nextlen
= linelen(line
+ len
, size
- len
);
1590 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
1593 /* Ok, we'll consider it a patch */
1594 if (parse_traditional_patch(state
, line
, line
+len
, patch
))
1596 *hdrsize
= len
+ nextlen
;
1603 static void record_ws_error(struct apply_state
*state
,
1614 state
->whitespace_error
++;
1615 if (state
->squelch_whitespace_errors
&&
1616 state
->squelch_whitespace_errors
< state
->whitespace_error
)
1619 err
= whitespace_error_string(result
);
1620 if (state
->apply_verbosity
> verbosity_silent
)
1621 fprintf(stderr
, "%s:%d: %s.\n%.*s\n",
1622 state
->patch_input_file
, linenr
, err
, len
, line
);
1626 static void check_whitespace(struct apply_state
*state
,
1631 unsigned result
= ws_check(line
+ 1, len
- 1, ws_rule
);
1633 record_ws_error(state
, result
, line
+ 1, len
- 2, state
->linenr
);
1637 * Check if the patch has context lines with CRLF or
1638 * the patch wants to remove lines with CRLF.
1640 static void check_old_for_crlf(struct patch
*patch
, const char *line
, int len
)
1642 if (len
>= 2 && line
[len
-1] == '\n' && line
[len
-2] == '\r') {
1643 patch
->ws_rule
|= WS_CR_AT_EOL
;
1644 patch
->crlf_in_old
= 1;
1650 * Parse a unified diff. Note that this really needs to parse each
1651 * fragment separately, since the only way to know the difference
1652 * between a "---" that is part of a patch, and a "---" that starts
1653 * the next patch is to look at the line counts..
1655 static int parse_fragment(struct apply_state
*state
,
1658 struct patch
*patch
,
1659 struct fragment
*fragment
)
1662 int len
= linelen(line
, size
), offset
;
1663 unsigned long oldlines
, newlines
;
1664 unsigned long leading
, trailing
;
1666 offset
= parse_fragment_header(line
, len
, fragment
);
1669 if (offset
> 0 && patch
->recount
)
1670 recount_diff(line
+ offset
, size
- offset
, fragment
);
1671 oldlines
= fragment
->oldlines
;
1672 newlines
= fragment
->newlines
;
1676 /* Parse the thing.. */
1680 added
= deleted
= 0;
1683 offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1684 if (!oldlines
&& !newlines
)
1686 len
= linelen(line
, size
);
1687 if (!len
|| line
[len
-1] != '\n')
1692 case '\n': /* newer GNU diff, an empty context line */
1696 if (!deleted
&& !added
)
1699 check_old_for_crlf(patch
, line
, len
);
1700 if (!state
->apply_in_reverse
&&
1701 state
->ws_error_action
== correct_ws_error
)
1702 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1705 if (!state
->apply_in_reverse
)
1706 check_old_for_crlf(patch
, line
, len
);
1707 if (state
->apply_in_reverse
&&
1708 state
->ws_error_action
!= nowarn_ws_error
)
1709 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1715 if (state
->apply_in_reverse
)
1716 check_old_for_crlf(patch
, line
, len
);
1717 if (!state
->apply_in_reverse
&&
1718 state
->ws_error_action
!= nowarn_ws_error
)
1719 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1726 * We allow "\ No newline at end of file". Depending
1727 * on locale settings when the patch was produced we
1728 * don't know what this line looks like. The only
1729 * thing we do know is that it begins with "\ ".
1730 * Checking for 12 is just for sanity check -- any
1731 * l10n of "\ No newline..." is at least that long.
1734 if (len
< 12 || memcmp(line
, "\\ ", 2))
1739 if (oldlines
|| newlines
)
1741 if (!patch
->recount
&& !deleted
&& !added
)
1744 fragment
->leading
= leading
;
1745 fragment
->trailing
= trailing
;
1748 * If a fragment ends with an incomplete line, we failed to include
1749 * it in the above loop because we hit oldlines == newlines == 0
1752 if (12 < size
&& !memcmp(line
, "\\ ", 2))
1753 offset
+= linelen(line
, size
);
1755 patch
->lines_added
+= added
;
1756 patch
->lines_deleted
+= deleted
;
1758 if (0 < patch
->is_new
&& oldlines
)
1759 return error(_("new file depends on old contents"));
1760 if (0 < patch
->is_delete
&& newlines
)
1761 return error(_("deleted file still has contents"));
1766 * We have seen "diff --git a/... b/..." header (or a traditional patch
1767 * header). Read hunks that belong to this patch into fragments and hang
1768 * them to the given patch structure.
1770 * The (fragment->patch, fragment->size) pair points into the memory given
1771 * by the caller, not a copy, when we return.
1774 * -1 in case of error,
1775 * the number of bytes in the patch otherwise.
1777 static int parse_single_patch(struct apply_state
*state
,
1780 struct patch
*patch
)
1782 unsigned long offset
= 0;
1783 unsigned long oldlines
= 0, newlines
= 0, context
= 0;
1784 struct fragment
**fragp
= &patch
->fragments
;
1786 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
1787 struct fragment
*fragment
;
1790 CALLOC_ARRAY(fragment
, 1);
1791 fragment
->linenr
= state
->linenr
;
1792 len
= parse_fragment(state
, line
, size
, patch
, fragment
);
1795 return error(_("corrupt patch at line %d"), state
->linenr
);
1797 fragment
->patch
= line
;
1798 fragment
->size
= len
;
1799 oldlines
+= fragment
->oldlines
;
1800 newlines
+= fragment
->newlines
;
1801 context
+= fragment
->leading
+ fragment
->trailing
;
1804 fragp
= &fragment
->next
;
1812 * If something was removed (i.e. we have old-lines) it cannot
1813 * be creation, and if something was added it cannot be
1814 * deletion. However, the reverse is not true; --unified=0
1815 * patches that only add are not necessarily creation even
1816 * though they do not have any old lines, and ones that only
1817 * delete are not necessarily deletion.
1819 * Unfortunately, a real creation/deletion patch do _not_ have
1820 * any context line by definition, so we cannot safely tell it
1821 * apart with --unified=0 insanity. At least if the patch has
1822 * more than one hunk it is not creation or deletion.
1824 if (patch
->is_new
< 0 &&
1825 (oldlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1827 if (patch
->is_delete
< 0 &&
1828 (newlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1829 patch
->is_delete
= 0;
1831 if (0 < patch
->is_new
&& oldlines
)
1832 return error(_("new file %s depends on old contents"), patch
->new_name
);
1833 if (0 < patch
->is_delete
&& newlines
)
1834 return error(_("deleted file %s still has contents"), patch
->old_name
);
1835 if (!patch
->is_delete
&& !newlines
&& context
&& state
->apply_verbosity
> verbosity_silent
)
1838 "file %s becomes empty but is not deleted"),
1844 static inline int metadata_changes(struct patch
*patch
)
1846 return patch
->is_rename
> 0 ||
1847 patch
->is_copy
> 0 ||
1848 patch
->is_new
> 0 ||
1850 (patch
->old_mode
&& patch
->new_mode
&&
1851 patch
->old_mode
!= patch
->new_mode
);
1854 static char *inflate_it(const void *data
, unsigned long size
,
1855 unsigned long inflated_size
)
1861 memset(&stream
, 0, sizeof(stream
));
1863 stream
.next_in
= (unsigned char *)data
;
1864 stream
.avail_in
= size
;
1865 stream
.next_out
= out
= xmalloc(inflated_size
);
1866 stream
.avail_out
= inflated_size
;
1867 git_inflate_init(&stream
);
1868 st
= git_inflate(&stream
, Z_FINISH
);
1869 git_inflate_end(&stream
);
1870 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1878 * Read a binary hunk and return a new fragment; fragment->patch
1879 * points at an allocated memory that the caller must free, so
1880 * it is marked as "->free_patch = 1".
1882 static struct fragment
*parse_binary_hunk(struct apply_state
*state
,
1884 unsigned long *sz_p
,
1889 * Expect a line that begins with binary patch method ("literal"
1890 * or "delta"), followed by the length of data before deflating.
1891 * a sequence of 'length-byte' followed by base-85 encoded data
1892 * should follow, terminated by a newline.
1894 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1895 * and we would limit the patch line to 66 characters,
1896 * so one line can fit up to 13 groups that would decode
1897 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1898 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1901 unsigned long size
= *sz_p
;
1902 char *buffer
= *buf_p
;
1904 unsigned long origlen
;
1907 struct fragment
*frag
;
1909 llen
= linelen(buffer
, size
);
1914 if (starts_with(buffer
, "delta ")) {
1915 patch_method
= BINARY_DELTA_DEFLATED
;
1916 origlen
= strtoul(buffer
+ 6, NULL
, 10);
1918 else if (starts_with(buffer
, "literal ")) {
1919 patch_method
= BINARY_LITERAL_DEFLATED
;
1920 origlen
= strtoul(buffer
+ 8, NULL
, 10);
1929 int byte_length
, max_byte_length
, newsize
;
1930 llen
= linelen(buffer
, size
);
1934 /* consume the blank line */
1940 * Minimum line is "A00000\n" which is 7-byte long,
1941 * and the line length must be multiple of 5 plus 2.
1943 if ((llen
< 7) || (llen
-2) % 5)
1945 max_byte_length
= (llen
- 2) / 5 * 4;
1946 byte_length
= *buffer
;
1947 if ('A' <= byte_length
&& byte_length
<= 'Z')
1948 byte_length
= byte_length
- 'A' + 1;
1949 else if ('a' <= byte_length
&& byte_length
<= 'z')
1950 byte_length
= byte_length
- 'a' + 27;
1953 /* if the input length was not multiple of 4, we would
1954 * have filler at the end but the filler should never
1957 if (max_byte_length
< byte_length
||
1958 byte_length
<= max_byte_length
- 4)
1960 newsize
= hunk_size
+ byte_length
;
1961 data
= xrealloc(data
, newsize
);
1962 if (decode_85(data
+ hunk_size
, buffer
+ 1, byte_length
))
1964 hunk_size
= newsize
;
1969 CALLOC_ARRAY(frag
, 1);
1970 frag
->patch
= inflate_it(data
, hunk_size
, origlen
);
1971 frag
->free_patch
= 1;
1975 frag
->size
= origlen
;
1979 frag
->binary_patch_method
= patch_method
;
1985 error(_("corrupt binary patch at line %d: %.*s"),
1986 state
->linenr
-1, llen
-1, buffer
);
1992 * -1 in case of error,
1993 * the length of the parsed binary patch otherwise
1995 static int parse_binary(struct apply_state
*state
,
1998 struct patch
*patch
)
2001 * We have read "GIT binary patch\n"; what follows is a line
2002 * that says the patch method (currently, either "literal" or
2003 * "delta") and the length of data before deflating; a
2004 * sequence of 'length-byte' followed by base-85 encoded data
2007 * When a binary patch is reversible, there is another binary
2008 * hunk in the same format, starting with patch method (either
2009 * "literal" or "delta") with the length of data, and a sequence
2010 * of length-byte + base-85 encoded data, terminated with another
2011 * empty line. This data, when applied to the postimage, produces
2014 struct fragment
*forward
;
2015 struct fragment
*reverse
;
2019 forward
= parse_binary_hunk(state
, &buffer
, &size
, &status
, &used
);
2020 if (!forward
&& !status
)
2021 /* there has to be one hunk (forward hunk) */
2022 return error(_("unrecognized binary patch at line %d"), state
->linenr
-1);
2024 /* otherwise we already gave an error message */
2027 reverse
= parse_binary_hunk(state
, &buffer
, &size
, &status
, &used_1
);
2032 * Not having reverse hunk is not an error, but having
2033 * a corrupt reverse hunk is.
2035 free((void*) forward
->patch
);
2039 forward
->next
= reverse
;
2040 patch
->fragments
= forward
;
2041 patch
->is_binary
= 1;
2045 static void prefix_one(struct apply_state
*state
, char **name
)
2047 char *old_name
= *name
;
2050 *name
= prefix_filename(state
->prefix
, *name
);
2054 static void prefix_patch(struct apply_state
*state
, struct patch
*p
)
2056 if (!state
->prefix
|| p
->is_toplevel_relative
)
2058 prefix_one(state
, &p
->new_name
);
2059 prefix_one(state
, &p
->old_name
);
2066 static void add_name_limit(struct apply_state
*state
,
2070 struct string_list_item
*it
;
2072 it
= string_list_append(&state
->limit_by_name
, name
);
2073 it
->util
= exclude
? NULL
: (void *) 1;
2076 static int use_patch(struct apply_state
*state
, struct patch
*p
)
2078 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
2081 /* Paths outside are not touched regardless of "--include" */
2082 if (state
->prefix
&& *state
->prefix
) {
2084 if (!skip_prefix(pathname
, state
->prefix
, &rest
) || !*rest
)
2088 /* See if it matches any of exclude/include rule */
2089 for (i
= 0; i
< state
->limit_by_name
.nr
; i
++) {
2090 struct string_list_item
*it
= &state
->limit_by_name
.items
[i
];
2091 if (!wildmatch(it
->string
, pathname
, 0))
2092 return (it
->util
!= NULL
);
2096 * If we had any include, a path that does not match any rule is
2097 * not used. Otherwise, we saw bunch of exclude rules (or none)
2098 * and such a path is used.
2100 return !state
->has_include
;
2104 * Read the patch text in "buffer" that extends for "size" bytes; stop
2105 * reading after seeing a single patch (i.e. changes to a single file).
2106 * Create fragments (i.e. patch hunks) and hang them to the given patch.
2109 * -1 if no header was found or parse_binary() failed,
2110 * -128 on another error,
2111 * the number of bytes consumed otherwise,
2112 * so that the caller can call us again for the next patch.
2114 static int parse_chunk(struct apply_state
*state
, char *buffer
, unsigned long size
, struct patch
*patch
)
2116 int hdrsize
, patchsize
;
2117 int offset
= find_header(state
, buffer
, size
, &hdrsize
, patch
);
2122 prefix_patch(state
, patch
);
2124 if (!use_patch(state
, patch
))
2126 else if (patch
->new_name
)
2127 patch
->ws_rule
= whitespace_rule(state
->repo
->index
,
2130 patch
->ws_rule
= whitespace_rule(state
->repo
->index
,
2133 patchsize
= parse_single_patch(state
,
2134 buffer
+ offset
+ hdrsize
,
2135 size
- offset
- hdrsize
,
2142 static const char git_binary
[] = "GIT binary patch\n";
2143 int hd
= hdrsize
+ offset
;
2144 unsigned long llen
= linelen(buffer
+ hd
, size
- hd
);
2146 if (llen
== sizeof(git_binary
) - 1 &&
2147 !memcmp(git_binary
, buffer
+ hd
, llen
)) {
2150 used
= parse_binary(state
, buffer
+ hd
+ llen
,
2151 size
- hd
- llen
, patch
);
2155 patchsize
= used
+ llen
;
2159 else if (!memcmp(" differ\n", buffer
+ hd
+ llen
- 8, 8)) {
2160 static const char *binhdr
[] = {
2166 for (i
= 0; binhdr
[i
]; i
++) {
2167 int len
= strlen(binhdr
[i
]);
2168 if (len
< size
- hd
&&
2169 !memcmp(binhdr
[i
], buffer
+ hd
, len
)) {
2171 patch
->is_binary
= 1;
2178 /* Empty patch cannot be applied if it is a text patch
2179 * without metadata change. A binary patch appears
2182 if ((state
->apply
|| state
->check
) &&
2183 (!patch
->is_binary
&& !metadata_changes(patch
))) {
2184 error(_("patch with only garbage at line %d"), state
->linenr
);
2189 return offset
+ hdrsize
+ patchsize
;
2192 static void reverse_patches(struct patch
*p
)
2194 for (; p
; p
= p
->next
) {
2195 struct fragment
*frag
= p
->fragments
;
2197 SWAP(p
->new_name
, p
->old_name
);
2198 SWAP(p
->new_mode
, p
->old_mode
);
2199 SWAP(p
->is_new
, p
->is_delete
);
2200 SWAP(p
->lines_added
, p
->lines_deleted
);
2201 SWAP(p
->old_oid_prefix
, p
->new_oid_prefix
);
2203 for (; frag
; frag
= frag
->next
) {
2204 SWAP(frag
->newpos
, frag
->oldpos
);
2205 SWAP(frag
->newlines
, frag
->oldlines
);
2210 static const char pluses
[] =
2211 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2212 static const char minuses
[]=
2213 "----------------------------------------------------------------------";
2215 static void show_stats(struct apply_state
*state
, struct patch
*patch
)
2217 struct strbuf qname
= STRBUF_INIT
;
2218 char *cp
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
2221 quote_c_style(cp
, &qname
, NULL
, 0);
2224 * "scale" the filename
2226 max
= state
->max_len
;
2230 if (qname
.len
> max
) {
2231 cp
= strchr(qname
.buf
+ qname
.len
+ 3 - max
, '/');
2233 cp
= qname
.buf
+ qname
.len
+ 3 - max
;
2234 strbuf_splice(&qname
, 0, cp
- qname
.buf
, "...", 3);
2237 if (patch
->is_binary
) {
2238 printf(" %-*s | Bin\n", max
, qname
.buf
);
2239 strbuf_release(&qname
);
2243 printf(" %-*s |", max
, qname
.buf
);
2244 strbuf_release(&qname
);
2247 * scale the add/delete
2249 max
= max
+ state
->max_change
> 70 ? 70 - max
: state
->max_change
;
2250 add
= patch
->lines_added
;
2251 del
= patch
->lines_deleted
;
2253 if (state
->max_change
> 0) {
2254 int total
= ((add
+ del
) * max
+ state
->max_change
/ 2) / state
->max_change
;
2255 add
= (add
* max
+ state
->max_change
/ 2) / state
->max_change
;
2258 printf("%5d %.*s%.*s\n", patch
->lines_added
+ patch
->lines_deleted
,
2259 add
, pluses
, del
, minuses
);
2262 static int read_old_data(struct stat
*st
, struct patch
*patch
,
2263 const char *path
, struct strbuf
*buf
)
2265 int conv_flags
= patch
->crlf_in_old
?
2266 CONV_EOL_KEEP_CRLF
: CONV_EOL_RENORMALIZE
;
2267 switch (st
->st_mode
& S_IFMT
) {
2269 if (strbuf_readlink(buf
, path
, st
->st_size
) < 0)
2270 return error(_("unable to read symlink %s"), path
);
2273 if (strbuf_read_file(buf
, path
, st
->st_size
) != st
->st_size
)
2274 return error(_("unable to open or read %s"), path
);
2276 * "git apply" without "--index/--cached" should never look
2277 * at the index; the target file may not have been added to
2278 * the index yet, and we may not even be in any Git repository.
2279 * Pass NULL to convert_to_git() to stress this; the function
2280 * should never look at the index when explicit crlf option
2283 convert_to_git(NULL
, path
, buf
->buf
, buf
->len
, buf
, conv_flags
);
2291 * Update the preimage, and the common lines in postimage,
2292 * from buffer buf of length len. If postlen is 0 the postimage
2293 * is updated in place, otherwise it's updated on a new buffer
2297 static void update_pre_post_images(struct image
*preimage
,
2298 struct image
*postimage
,
2300 size_t len
, size_t postlen
)
2302 int i
, ctx
, reduced
;
2303 char *new_buf
, *old_buf
, *fixed
;
2304 struct image fixed_preimage
;
2307 * Update the preimage with whitespace fixes. Note that we
2308 * are not losing preimage->buf -- apply_one_fragment() will
2311 prepare_image(&fixed_preimage
, buf
, len
, 1);
2313 ? fixed_preimage
.nr
== preimage
->nr
2314 : fixed_preimage
.nr
<= preimage
->nr
);
2315 for (i
= 0; i
< fixed_preimage
.nr
; i
++)
2316 fixed_preimage
.line
[i
].flag
= preimage
->line
[i
].flag
;
2317 free(preimage
->line_allocated
);
2318 *preimage
= fixed_preimage
;
2321 * Adjust the common context lines in postimage. This can be
2322 * done in-place when we are shrinking it with whitespace
2323 * fixing, but needs a new buffer when ignoring whitespace or
2324 * expanding leading tabs to spaces.
2326 * We trust the caller to tell us if the update can be done
2327 * in place (postlen==0) or not.
2329 old_buf
= postimage
->buf
;
2331 new_buf
= postimage
->buf
= xmalloc(postlen
);
2334 fixed
= preimage
->buf
;
2336 for (i
= reduced
= ctx
= 0; i
< postimage
->nr
; i
++) {
2337 size_t l_len
= postimage
->line
[i
].len
;
2338 if (!(postimage
->line
[i
].flag
& LINE_COMMON
)) {
2339 /* an added line -- no counterparts in preimage */
2340 memmove(new_buf
, old_buf
, l_len
);
2346 /* a common context -- skip it in the original postimage */
2349 /* and find the corresponding one in the fixed preimage */
2350 while (ctx
< preimage
->nr
&&
2351 !(preimage
->line
[ctx
].flag
& LINE_COMMON
)) {
2352 fixed
+= preimage
->line
[ctx
].len
;
2357 * preimage is expected to run out, if the caller
2358 * fixed addition of trailing blank lines.
2360 if (preimage
->nr
<= ctx
) {
2365 /* and copy it in, while fixing the line length */
2366 l_len
= preimage
->line
[ctx
].len
;
2367 memcpy(new_buf
, fixed
, l_len
);
2370 postimage
->line
[i
].len
= l_len
;
2375 ? postlen
< new_buf
- postimage
->buf
2376 : postimage
->len
< new_buf
- postimage
->buf
)
2377 BUG("caller miscounted postlen: asked %d, orig = %d, used = %d",
2378 (int)postlen
, (int) postimage
->len
, (int)(new_buf
- postimage
->buf
));
2380 /* Fix the length of the whole thing */
2381 postimage
->len
= new_buf
- postimage
->buf
;
2382 postimage
->nr
-= reduced
;
2385 static int line_by_line_fuzzy_match(struct image
*img
,
2386 struct image
*preimage
,
2387 struct image
*postimage
,
2388 unsigned long current
,
2395 size_t postlen
= postimage
->len
;
2400 struct strbuf fixed
;
2404 for (i
= 0; i
< preimage_limit
; i
++) {
2405 size_t prelen
= preimage
->line
[i
].len
;
2406 size_t imglen
= img
->line
[current_lno
+i
].len
;
2408 if (!fuzzy_matchlines(img
->buf
+ current
+ imgoff
, imglen
,
2409 preimage
->buf
+ preoff
, prelen
))
2411 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2412 postlen
+= imglen
- prelen
;
2418 * Ok, the preimage matches with whitespace fuzz.
2420 * imgoff now holds the true length of the target that
2421 * matches the preimage before the end of the file.
2423 * Count the number of characters in the preimage that fall
2424 * beyond the end of the file and make sure that all of them
2425 * are whitespace characters. (This can only happen if
2426 * we are removing blank lines at the end of the file.)
2428 buf
= preimage_eof
= preimage
->buf
+ preoff
;
2429 for ( ; i
< preimage
->nr
; i
++)
2430 preoff
+= preimage
->line
[i
].len
;
2431 preimage_end
= preimage
->buf
+ preoff
;
2432 for ( ; buf
< preimage_end
; buf
++)
2437 * Update the preimage and the common postimage context
2438 * lines to use the same whitespace as the target.
2439 * If whitespace is missing in the target (i.e.
2440 * if the preimage extends beyond the end of the file),
2441 * use the whitespace from the preimage.
2443 extra_chars
= preimage_end
- preimage_eof
;
2444 strbuf_init(&fixed
, imgoff
+ extra_chars
);
2445 strbuf_add(&fixed
, img
->buf
+ current
, imgoff
);
2446 strbuf_add(&fixed
, preimage_eof
, extra_chars
);
2447 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2448 update_pre_post_images(preimage
, postimage
,
2449 fixed_buf
, fixed_len
, postlen
);
2453 static int match_fragment(struct apply_state
*state
,
2455 struct image
*preimage
,
2456 struct image
*postimage
,
2457 unsigned long current
,
2460 int match_beginning
, int match_end
)
2463 char *fixed_buf
, *buf
, *orig
, *target
;
2464 struct strbuf fixed
;
2465 size_t fixed_len
, postlen
;
2468 if (preimage
->nr
+ current_lno
<= img
->nr
) {
2470 * The hunk falls within the boundaries of img.
2472 preimage_limit
= preimage
->nr
;
2473 if (match_end
&& (preimage
->nr
+ current_lno
!= img
->nr
))
2475 } else if (state
->ws_error_action
== correct_ws_error
&&
2476 (ws_rule
& WS_BLANK_AT_EOF
)) {
2478 * This hunk extends beyond the end of img, and we are
2479 * removing blank lines at the end of the file. This
2480 * many lines from the beginning of the preimage must
2481 * match with img, and the remainder of the preimage
2484 preimage_limit
= img
->nr
- current_lno
;
2487 * The hunk extends beyond the end of the img and
2488 * we are not removing blanks at the end, so we
2489 * should reject the hunk at this position.
2494 if (match_beginning
&& current_lno
)
2497 /* Quick hash check */
2498 for (i
= 0; i
< preimage_limit
; i
++)
2499 if ((img
->line
[current_lno
+ i
].flag
& LINE_PATCHED
) ||
2500 (preimage
->line
[i
].hash
!= img
->line
[current_lno
+ i
].hash
))
2503 if (preimage_limit
== preimage
->nr
) {
2505 * Do we have an exact match? If we were told to match
2506 * at the end, size must be exactly at current+fragsize,
2507 * otherwise current+fragsize must be still within the preimage,
2508 * and either case, the old piece should match the preimage
2512 ? (current
+ preimage
->len
== img
->len
)
2513 : (current
+ preimage
->len
<= img
->len
)) &&
2514 !memcmp(img
->buf
+ current
, preimage
->buf
, preimage
->len
))
2518 * The preimage extends beyond the end of img, so
2519 * there cannot be an exact match.
2521 * There must be one non-blank context line that match
2522 * a line before the end of img.
2526 buf
= preimage
->buf
;
2528 for (i
= 0; i
< preimage_limit
; i
++)
2529 buf_end
+= preimage
->line
[i
].len
;
2531 for ( ; buf
< buf_end
; buf
++)
2539 * No exact match. If we are ignoring whitespace, run a line-by-line
2540 * fuzzy matching. We collect all the line length information because
2541 * we need it to adjust whitespace if we match.
2543 if (state
->ws_ignore_action
== ignore_ws_change
)
2544 return line_by_line_fuzzy_match(img
, preimage
, postimage
,
2545 current
, current_lno
, preimage_limit
);
2547 if (state
->ws_error_action
!= correct_ws_error
)
2551 * The hunk does not apply byte-by-byte, but the hash says
2552 * it might with whitespace fuzz. We weren't asked to
2553 * ignore whitespace, we were asked to correct whitespace
2554 * errors, so let's try matching after whitespace correction.
2556 * While checking the preimage against the target, whitespace
2557 * errors in both fixed, we count how large the corresponding
2558 * postimage needs to be. The postimage prepared by
2559 * apply_one_fragment() has whitespace errors fixed on added
2560 * lines already, but the common lines were propagated as-is,
2561 * which may become longer when their whitespace errors are
2565 /* First count added lines in postimage */
2567 for (i
= 0; i
< postimage
->nr
; i
++) {
2568 if (!(postimage
->line
[i
].flag
& LINE_COMMON
))
2569 postlen
+= postimage
->line
[i
].len
;
2573 * The preimage may extend beyond the end of the file,
2574 * but in this loop we will only handle the part of the
2575 * preimage that falls within the file.
2577 strbuf_init(&fixed
, preimage
->len
+ 1);
2578 orig
= preimage
->buf
;
2579 target
= img
->buf
+ current
;
2580 for (i
= 0; i
< preimage_limit
; i
++) {
2581 size_t oldlen
= preimage
->line
[i
].len
;
2582 size_t tgtlen
= img
->line
[current_lno
+ i
].len
;
2583 size_t fixstart
= fixed
.len
;
2584 struct strbuf tgtfix
;
2587 /* Try fixing the line in the preimage */
2588 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2590 /* Try fixing the line in the target */
2591 strbuf_init(&tgtfix
, tgtlen
);
2592 ws_fix_copy(&tgtfix
, target
, tgtlen
, ws_rule
, NULL
);
2595 * If they match, either the preimage was based on
2596 * a version before our tree fixed whitespace breakage,
2597 * or we are lacking a whitespace-fix patch the tree
2598 * the preimage was based on already had (i.e. target
2599 * has whitespace breakage, the preimage doesn't).
2600 * In either case, we are fixing the whitespace breakages
2601 * so we might as well take the fix together with their
2604 match
= (tgtfix
.len
== fixed
.len
- fixstart
&&
2605 !memcmp(tgtfix
.buf
, fixed
.buf
+ fixstart
,
2606 fixed
.len
- fixstart
));
2608 /* Add the length if this is common with the postimage */
2609 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2610 postlen
+= tgtfix
.len
;
2612 strbuf_release(&tgtfix
);
2622 * Now handle the lines in the preimage that falls beyond the
2623 * end of the file (if any). They will only match if they are
2624 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2627 for ( ; i
< preimage
->nr
; i
++) {
2628 size_t fixstart
= fixed
.len
; /* start of the fixed preimage */
2629 size_t oldlen
= preimage
->line
[i
].len
;
2632 /* Try fixing the line in the preimage */
2633 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2635 for (j
= fixstart
; j
< fixed
.len
; j
++)
2636 if (!isspace(fixed
.buf
[j
]))
2643 * Yes, the preimage is based on an older version that still
2644 * has whitespace breakages unfixed, and fixing them makes the
2645 * hunk match. Update the context lines in the postimage.
2647 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2648 if (postlen
< postimage
->len
)
2650 update_pre_post_images(preimage
, postimage
,
2651 fixed_buf
, fixed_len
, postlen
);
2655 strbuf_release(&fixed
);
2659 static int find_pos(struct apply_state
*state
,
2661 struct image
*preimage
,
2662 struct image
*postimage
,
2665 int match_beginning
, int match_end
)
2668 unsigned long backwards
, forwards
, current
;
2669 int backwards_lno
, forwards_lno
, current_lno
;
2672 * When running with --allow-overlap, it is possible that a hunk is
2673 * seen that pretends to start at the beginning (but no longer does),
2674 * and that *still* needs to match the end. So trust `match_end` more
2675 * than `match_beginning`.
2677 if (state
->allow_overlap
&& match_beginning
&& match_end
&&
2678 img
->nr
- preimage
->nr
!= 0)
2679 match_beginning
= 0;
2682 * If match_beginning or match_end is specified, there is no
2683 * point starting from a wrong line that will never match and
2684 * wander around and wait for a match at the specified end.
2686 if (match_beginning
)
2689 line
= img
->nr
- preimage
->nr
;
2692 * Because the comparison is unsigned, the following test
2693 * will also take care of a negative line number that can
2694 * result when match_end and preimage is larger than the target.
2696 if ((size_t) line
> img
->nr
)
2700 for (i
= 0; i
< line
; i
++)
2701 current
+= img
->line
[i
].len
;
2704 * There's probably some smart way to do this, but I'll leave
2705 * that to the smart and beautiful people. I'm simple and stupid.
2707 backwards
= current
;
2708 backwards_lno
= line
;
2710 forwards_lno
= line
;
2713 for (i
= 0; ; i
++) {
2714 if (match_fragment(state
, img
, preimage
, postimage
,
2715 current
, current_lno
, ws_rule
,
2716 match_beginning
, match_end
))
2720 if (backwards_lno
== 0 && forwards_lno
== img
->nr
)
2724 if (backwards_lno
== 0) {
2729 backwards
-= img
->line
[backwards_lno
].len
;
2730 current
= backwards
;
2731 current_lno
= backwards_lno
;
2733 if (forwards_lno
== img
->nr
) {
2737 forwards
+= img
->line
[forwards_lno
].len
;
2740 current_lno
= forwards_lno
;
2747 static void remove_first_line(struct image
*img
)
2749 img
->buf
+= img
->line
[0].len
;
2750 img
->len
-= img
->line
[0].len
;
2755 static void remove_last_line(struct image
*img
)
2757 img
->len
-= img
->line
[--img
->nr
].len
;
2761 * The change from "preimage" and "postimage" has been found to
2762 * apply at applied_pos (counts in line numbers) in "img".
2763 * Update "img" to remove "preimage" and replace it with "postimage".
2765 static void update_image(struct apply_state
*state
,
2768 struct image
*preimage
,
2769 struct image
*postimage
)
2772 * remove the copy of preimage at offset in img
2773 * and replace it with postimage
2776 size_t remove_count
, insert_count
, applied_at
= 0;
2781 * If we are removing blank lines at the end of img,
2782 * the preimage may extend beyond the end.
2783 * If that is the case, we must be careful only to
2784 * remove the part of the preimage that falls within
2785 * the boundaries of img. Initialize preimage_limit
2786 * to the number of lines in the preimage that falls
2787 * within the boundaries.
2789 preimage_limit
= preimage
->nr
;
2790 if (preimage_limit
> img
->nr
- applied_pos
)
2791 preimage_limit
= img
->nr
- applied_pos
;
2793 for (i
= 0; i
< applied_pos
; i
++)
2794 applied_at
+= img
->line
[i
].len
;
2797 for (i
= 0; i
< preimage_limit
; i
++)
2798 remove_count
+= img
->line
[applied_pos
+ i
].len
;
2799 insert_count
= postimage
->len
;
2801 /* Adjust the contents */
2802 result
= xmalloc(st_add3(st_sub(img
->len
, remove_count
), insert_count
, 1));
2803 memcpy(result
, img
->buf
, applied_at
);
2804 memcpy(result
+ applied_at
, postimage
->buf
, postimage
->len
);
2805 memcpy(result
+ applied_at
+ postimage
->len
,
2806 img
->buf
+ (applied_at
+ remove_count
),
2807 img
->len
- (applied_at
+ remove_count
));
2810 img
->len
+= insert_count
- remove_count
;
2811 result
[img
->len
] = '\0';
2813 /* Adjust the line table */
2814 nr
= img
->nr
+ postimage
->nr
- preimage_limit
;
2815 if (preimage_limit
< postimage
->nr
) {
2817 * NOTE: this knows that we never call remove_first_line()
2818 * on anything other than pre/post image.
2820 REALLOC_ARRAY(img
->line
, nr
);
2821 img
->line_allocated
= img
->line
;
2823 if (preimage_limit
!= postimage
->nr
)
2824 MOVE_ARRAY(img
->line
+ applied_pos
+ postimage
->nr
,
2825 img
->line
+ applied_pos
+ preimage_limit
,
2826 img
->nr
- (applied_pos
+ preimage_limit
));
2827 COPY_ARRAY(img
->line
+ applied_pos
, postimage
->line
, postimage
->nr
);
2828 if (!state
->allow_overlap
)
2829 for (i
= 0; i
< postimage
->nr
; i
++)
2830 img
->line
[applied_pos
+ i
].flag
|= LINE_PATCHED
;
2835 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2836 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2837 * replace the part of "img" with "postimage" text.
2839 static int apply_one_fragment(struct apply_state
*state
,
2840 struct image
*img
, struct fragment
*frag
,
2841 int inaccurate_eof
, unsigned ws_rule
,
2844 int match_beginning
, match_end
;
2845 const char *patch
= frag
->patch
;
2846 int size
= frag
->size
;
2847 char *old
, *oldlines
;
2848 struct strbuf newlines
;
2849 int new_blank_lines_at_end
= 0;
2850 int found_new_blank_lines_at_end
= 0;
2851 int hunk_linenr
= frag
->linenr
;
2852 unsigned long leading
, trailing
;
2853 int pos
, applied_pos
;
2854 struct image preimage
;
2855 struct image postimage
;
2857 memset(&preimage
, 0, sizeof(preimage
));
2858 memset(&postimage
, 0, sizeof(postimage
));
2859 oldlines
= xmalloc(size
);
2860 strbuf_init(&newlines
, size
);
2865 int len
= linelen(patch
, size
);
2867 int added_blank_line
= 0;
2868 int is_blank_context
= 0;
2875 * "plen" is how much of the line we should use for
2876 * the actual patch data. Normally we just remove the
2877 * first character on the line, but if the line is
2878 * followed by "\ No newline", then we also remove the
2879 * last one (which is the newline, of course).
2882 if (len
< size
&& patch
[len
] == '\\')
2885 if (state
->apply_in_reverse
) {
2888 else if (first
== '+')
2894 /* Newer GNU diff, empty context line */
2896 /* ... followed by '\No newline'; nothing */
2899 strbuf_addch(&newlines
, '\n');
2900 add_line_info(&preimage
, "\n", 1, LINE_COMMON
);
2901 add_line_info(&postimage
, "\n", 1, LINE_COMMON
);
2902 is_blank_context
= 1;
2905 if (plen
&& (ws_rule
& WS_BLANK_AT_EOF
) &&
2906 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2907 is_blank_context
= 1;
2910 memcpy(old
, patch
+ 1, plen
);
2911 add_line_info(&preimage
, old
, plen
,
2912 (first
== ' ' ? LINE_COMMON
: 0));
2918 /* --no-add does not add new lines */
2919 if (first
== '+' && state
->no_add
)
2922 start
= newlines
.len
;
2924 !state
->whitespace_error
||
2925 state
->ws_error_action
!= correct_ws_error
) {
2926 strbuf_add(&newlines
, patch
+ 1, plen
);
2929 ws_fix_copy(&newlines
, patch
+ 1, plen
, ws_rule
, &state
->applied_after_fixing_ws
);
2931 add_line_info(&postimage
, newlines
.buf
+ start
, newlines
.len
- start
,
2932 (first
== '+' ? 0 : LINE_COMMON
));
2934 (ws_rule
& WS_BLANK_AT_EOF
) &&
2935 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2936 added_blank_line
= 1;
2938 case '@': case '\\':
2939 /* Ignore it, we already handled it */
2942 if (state
->apply_verbosity
> verbosity_normal
)
2943 error(_("invalid start of line: '%c'"), first
);
2947 if (added_blank_line
) {
2948 if (!new_blank_lines_at_end
)
2949 found_new_blank_lines_at_end
= hunk_linenr
;
2950 new_blank_lines_at_end
++;
2952 else if (is_blank_context
)
2955 new_blank_lines_at_end
= 0;
2960 if (inaccurate_eof
&&
2961 old
> oldlines
&& old
[-1] == '\n' &&
2962 newlines
.len
> 0 && newlines
.buf
[newlines
.len
- 1] == '\n') {
2964 strbuf_setlen(&newlines
, newlines
.len
- 1);
2965 preimage
.line_allocated
[preimage
.nr
- 1].len
--;
2966 postimage
.line_allocated
[postimage
.nr
- 1].len
--;
2969 leading
= frag
->leading
;
2970 trailing
= frag
->trailing
;
2973 * A hunk to change lines at the beginning would begin with
2975 * but we need to be careful. -U0 that inserts before the second
2976 * line also has this pattern.
2978 * And a hunk to add to an empty file would begin with
2981 * In other words, a hunk that is (frag->oldpos <= 1) with or
2982 * without leading context must match at the beginning.
2984 match_beginning
= (!frag
->oldpos
||
2985 (frag
->oldpos
== 1 && !state
->unidiff_zero
));
2988 * A hunk without trailing lines must match at the end.
2989 * However, we simply cannot tell if a hunk must match end
2990 * from the lack of trailing lines if the patch was generated
2991 * with unidiff without any context.
2993 match_end
= !state
->unidiff_zero
&& !trailing
;
2995 pos
= frag
->newpos
? (frag
->newpos
- 1) : 0;
2996 preimage
.buf
= oldlines
;
2997 preimage
.len
= old
- oldlines
;
2998 postimage
.buf
= newlines
.buf
;
2999 postimage
.len
= newlines
.len
;
3000 preimage
.line
= preimage
.line_allocated
;
3001 postimage
.line
= postimage
.line_allocated
;
3005 applied_pos
= find_pos(state
, img
, &preimage
, &postimage
, pos
,
3006 ws_rule
, match_beginning
, match_end
);
3008 if (applied_pos
>= 0)
3011 /* Am I at my context limits? */
3012 if ((leading
<= state
->p_context
) && (trailing
<= state
->p_context
))
3014 if (match_beginning
|| match_end
) {
3015 match_beginning
= match_end
= 0;
3020 * Reduce the number of context lines; reduce both
3021 * leading and trailing if they are equal otherwise
3022 * just reduce the larger context.
3024 if (leading
>= trailing
) {
3025 remove_first_line(&preimage
);
3026 remove_first_line(&postimage
);
3030 if (trailing
> leading
) {
3031 remove_last_line(&preimage
);
3032 remove_last_line(&postimage
);
3037 if (applied_pos
>= 0) {
3038 if (new_blank_lines_at_end
&&
3039 preimage
.nr
+ applied_pos
>= img
->nr
&&
3040 (ws_rule
& WS_BLANK_AT_EOF
) &&
3041 state
->ws_error_action
!= nowarn_ws_error
) {
3042 record_ws_error(state
, WS_BLANK_AT_EOF
, "+", 1,
3043 found_new_blank_lines_at_end
);
3044 if (state
->ws_error_action
== correct_ws_error
) {
3045 while (new_blank_lines_at_end
--)
3046 remove_last_line(&postimage
);
3049 * We would want to prevent write_out_results()
3050 * from taking place in apply_patch() that follows
3051 * the callchain led us here, which is:
3052 * apply_patch->check_patch_list->check_patch->
3053 * apply_data->apply_fragments->apply_one_fragment
3055 if (state
->ws_error_action
== die_on_ws_error
)
3059 if (state
->apply_verbosity
> verbosity_normal
&& applied_pos
!= pos
) {
3060 int offset
= applied_pos
- pos
;
3061 if (state
->apply_in_reverse
)
3062 offset
= 0 - offset
;
3064 Q_("Hunk #%d succeeded at %d (offset %d line).",
3065 "Hunk #%d succeeded at %d (offset %d lines).",
3067 nth_fragment
, applied_pos
+ 1, offset
);
3071 * Warn if it was necessary to reduce the number
3074 if ((leading
!= frag
->leading
||
3075 trailing
!= frag
->trailing
) && state
->apply_verbosity
> verbosity_silent
)
3076 fprintf_ln(stderr
, _("Context reduced to (%ld/%ld)"
3077 " to apply fragment at %d"),
3078 leading
, trailing
, applied_pos
+1);
3079 update_image(state
, img
, applied_pos
, &preimage
, &postimage
);
3081 if (state
->apply_verbosity
> verbosity_normal
)
3082 error(_("while searching for:\n%.*s"),
3083 (int)(old
- oldlines
), oldlines
);
3088 strbuf_release(&newlines
);
3089 free(preimage
.line_allocated
);
3090 free(postimage
.line_allocated
);
3092 return (applied_pos
< 0);
3095 static int apply_binary_fragment(struct apply_state
*state
,
3097 struct patch
*patch
)
3099 struct fragment
*fragment
= patch
->fragments
;
3104 return error(_("missing binary patch data for '%s'"),
3109 /* Binary patch is irreversible without the optional second hunk */
3110 if (state
->apply_in_reverse
) {
3111 if (!fragment
->next
)
3112 return error(_("cannot reverse-apply a binary patch "
3113 "without the reverse hunk to '%s'"),
3115 ? patch
->new_name
: patch
->old_name
);
3116 fragment
= fragment
->next
;
3118 switch (fragment
->binary_patch_method
) {
3119 case BINARY_DELTA_DEFLATED
:
3120 dst
= patch_delta(img
->buf
, img
->len
, fragment
->patch
,
3121 fragment
->size
, &len
);
3128 case BINARY_LITERAL_DEFLATED
:
3130 img
->len
= fragment
->size
;
3131 img
->buf
= xmemdupz(fragment
->patch
, img
->len
);
3138 * Replace "img" with the result of applying the binary patch.
3139 * The binary patch data itself in patch->fragment is still kept
3140 * but the preimage prepared by the caller in "img" is freed here
3141 * or in the helper function apply_binary_fragment() this calls.
3143 static int apply_binary(struct apply_state
*state
,
3145 struct patch
*patch
)
3147 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3148 struct object_id oid
;
3149 const unsigned hexsz
= the_hash_algo
->hexsz
;
3152 * For safety, we require patch index line to contain
3153 * full hex textual object ID for old and new, at least for now.
3155 if (strlen(patch
->old_oid_prefix
) != hexsz
||
3156 strlen(patch
->new_oid_prefix
) != hexsz
||
3157 get_oid_hex(patch
->old_oid_prefix
, &oid
) ||
3158 get_oid_hex(patch
->new_oid_prefix
, &oid
))
3159 return error(_("cannot apply binary patch to '%s' "
3160 "without full index line"), name
);
3162 if (patch
->old_name
) {
3164 * See if the old one matches what the patch
3167 hash_object_file(the_hash_algo
, img
->buf
, img
->len
, OBJ_BLOB
,
3169 if (strcmp(oid_to_hex(&oid
), patch
->old_oid_prefix
))
3170 return error(_("the patch applies to '%s' (%s), "
3171 "which does not match the "
3172 "current contents."),
3173 name
, oid_to_hex(&oid
));
3176 /* Otherwise, the old one must be empty. */
3178 return error(_("the patch applies to an empty "
3179 "'%s' but it is not empty"), name
);
3182 get_oid_hex(patch
->new_oid_prefix
, &oid
);
3183 if (is_null_oid(&oid
)) {
3185 return 0; /* deletion patch */
3188 if (has_object(the_repository
, &oid
, 0)) {
3189 /* We already have the postimage */
3190 enum object_type type
;
3194 result
= read_object_file(&oid
, &type
, &size
);
3196 return error(_("the necessary postimage %s for "
3197 "'%s' cannot be read"),
3198 patch
->new_oid_prefix
, name
);
3204 * We have verified buf matches the preimage;
3205 * apply the patch data to it, which is stored
3206 * in the patch->fragments->{patch,size}.
3208 if (apply_binary_fragment(state
, img
, patch
))
3209 return error(_("binary patch does not apply to '%s'"),
3212 /* verify that the result matches */
3213 hash_object_file(the_hash_algo
, img
->buf
, img
->len
, OBJ_BLOB
,
3215 if (strcmp(oid_to_hex(&oid
), patch
->new_oid_prefix
))
3216 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3217 name
, patch
->new_oid_prefix
, oid_to_hex(&oid
));
3223 static int apply_fragments(struct apply_state
*state
, struct image
*img
, struct patch
*patch
)
3225 struct fragment
*frag
= patch
->fragments
;
3226 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3227 unsigned ws_rule
= patch
->ws_rule
;
3228 unsigned inaccurate_eof
= patch
->inaccurate_eof
;
3231 if (patch
->is_binary
)
3232 return apply_binary(state
, img
, patch
);
3236 if (apply_one_fragment(state
, img
, frag
, inaccurate_eof
, ws_rule
, nth
)) {
3237 error(_("patch failed: %s:%ld"), name
, frag
->oldpos
);
3238 if (!state
->apply_with_reject
)
3247 static int read_blob_object(struct strbuf
*buf
, const struct object_id
*oid
, unsigned mode
)
3249 if (S_ISGITLINK(mode
)) {
3250 strbuf_grow(buf
, 100);
3251 strbuf_addf(buf
, "Subproject commit %s\n", oid_to_hex(oid
));
3253 enum object_type type
;
3257 result
= read_object_file(oid
, &type
, &sz
);
3260 /* XXX read_sha1_file NUL-terminates */
3261 strbuf_attach(buf
, result
, sz
, sz
+ 1);
3266 static int read_file_or_gitlink(const struct cache_entry
*ce
, struct strbuf
*buf
)
3270 return read_blob_object(buf
, &ce
->oid
, ce
->ce_mode
);
3273 static struct patch
*in_fn_table(struct apply_state
*state
, const char *name
)
3275 struct string_list_item
*item
;
3280 item
= string_list_lookup(&state
->fn_table
, name
);
3282 return (struct patch
*)item
->util
;
3288 * item->util in the filename table records the status of the path.
3289 * Usually it points at a patch (whose result records the contents
3290 * of it after applying it), but it could be PATH_WAS_DELETED for a
3291 * path that a previously applied patch has already removed, or
3292 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3294 * The latter is needed to deal with a case where two paths A and B
3295 * are swapped by first renaming A to B and then renaming B to A;
3296 * moving A to B should not be prevented due to presence of B as we
3297 * will remove it in a later patch.
3299 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3300 #define PATH_WAS_DELETED ((struct patch *) -1)
3302 static int to_be_deleted(struct patch
*patch
)
3304 return patch
== PATH_TO_BE_DELETED
;
3307 static int was_deleted(struct patch
*patch
)
3309 return patch
== PATH_WAS_DELETED
;
3312 static void add_to_fn_table(struct apply_state
*state
, struct patch
*patch
)
3314 struct string_list_item
*item
;
3317 * Always add new_name unless patch is a deletion
3318 * This should cover the cases for normal diffs,
3319 * file creations and copies
3321 if (patch
->new_name
) {
3322 item
= string_list_insert(&state
->fn_table
, patch
->new_name
);
3327 * store a failure on rename/deletion cases because
3328 * later chunks shouldn't patch old names
3330 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3331 item
= string_list_insert(&state
->fn_table
, patch
->old_name
);
3332 item
->util
= PATH_WAS_DELETED
;
3336 static void prepare_fn_table(struct apply_state
*state
, struct patch
*patch
)
3339 * store information about incoming file deletion
3342 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3343 struct string_list_item
*item
;
3344 item
= string_list_insert(&state
->fn_table
, patch
->old_name
);
3345 item
->util
= PATH_TO_BE_DELETED
;
3347 patch
= patch
->next
;
3351 static int checkout_target(struct index_state
*istate
,
3352 struct cache_entry
*ce
, struct stat
*st
)
3354 struct checkout costate
= CHECKOUT_INIT
;
3356 costate
.refresh_cache
= 1;
3357 costate
.istate
= istate
;
3358 if (checkout_entry(ce
, &costate
, NULL
, NULL
) ||
3359 lstat(ce
->name
, st
))
3360 return error(_("cannot checkout %s"), ce
->name
);
3364 static struct patch
*previous_patch(struct apply_state
*state
,
3365 struct patch
*patch
,
3368 struct patch
*previous
;
3371 if (patch
->is_copy
|| patch
->is_rename
)
3372 return NULL
; /* "git" patches do not depend on the order */
3374 previous
= in_fn_table(state
, patch
->old_name
);
3378 if (to_be_deleted(previous
))
3379 return NULL
; /* the deletion hasn't happened yet */
3381 if (was_deleted(previous
))
3387 static int verify_index_match(struct apply_state
*state
,
3388 const struct cache_entry
*ce
,
3391 if (S_ISGITLINK(ce
->ce_mode
)) {
3392 if (!S_ISDIR(st
->st_mode
))
3396 return ie_match_stat(state
->repo
->index
, ce
, st
,
3397 CE_MATCH_IGNORE_VALID
| CE_MATCH_IGNORE_SKIP_WORKTREE
);
3400 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3402 static int load_patch_target(struct apply_state
*state
,
3404 const struct cache_entry
*ce
,
3406 struct patch
*patch
,
3408 unsigned expected_mode
)
3410 if (state
->cached
|| state
->check_index
) {
3411 if (read_file_or_gitlink(ce
, buf
))
3412 return error(_("failed to read %s"), name
);
3414 if (S_ISGITLINK(expected_mode
)) {
3416 return read_file_or_gitlink(ce
, buf
);
3418 return SUBMODULE_PATCH_WITHOUT_INDEX
;
3419 } else if (has_symlink_leading_path(name
, strlen(name
))) {
3420 return error(_("reading from '%s' beyond a symbolic link"), name
);
3422 if (read_old_data(st
, patch
, name
, buf
))
3423 return error(_("failed to read %s"), name
);
3430 * We are about to apply "patch"; populate the "image" with the
3431 * current version we have, from the working tree or from the index,
3432 * depending on the situation e.g. --cached/--index. If we are
3433 * applying a non-git patch that incrementally updates the tree,
3434 * we read from the result of a previous diff.
3436 static int load_preimage(struct apply_state
*state
,
3437 struct image
*image
,
3438 struct patch
*patch
, struct stat
*st
,
3439 const struct cache_entry
*ce
)
3441 struct strbuf buf
= STRBUF_INIT
;
3444 struct patch
*previous
;
3447 previous
= previous_patch(state
, patch
, &status
);
3449 return error(_("path %s has been renamed/deleted"),
3452 /* We have a patched copy in memory; use that. */
3453 strbuf_add(&buf
, previous
->result
, previous
->resultsize
);
3455 status
= load_patch_target(state
, &buf
, ce
, st
, patch
,
3456 patch
->old_name
, patch
->old_mode
);
3459 else if (status
== SUBMODULE_PATCH_WITHOUT_INDEX
) {
3461 * There is no way to apply subproject
3462 * patch without looking at the index.
3463 * NEEDSWORK: shouldn't this be flagged
3466 free_fragment_list(patch
->fragments
);
3467 patch
->fragments
= NULL
;
3468 } else if (status
) {
3469 return error(_("failed to read %s"), patch
->old_name
);
3473 img
= strbuf_detach(&buf
, &len
);
3474 prepare_image(image
, img
, len
, !patch
->is_binary
);
3478 static int resolve_to(struct image
*image
, const struct object_id
*result_id
)
3481 enum object_type type
;
3485 image
->buf
= read_object_file(result_id
, &type
, &size
);
3486 if (!image
->buf
|| type
!= OBJ_BLOB
)
3487 die("unable to read blob object %s", oid_to_hex(result_id
));
3493 static int three_way_merge(struct apply_state
*state
,
3494 struct image
*image
,
3496 const struct object_id
*base
,
3497 const struct object_id
*ours
,
3498 const struct object_id
*theirs
)
3500 mmfile_t base_file
, our_file
, their_file
;
3501 mmbuffer_t result
= { NULL
};
3502 enum ll_merge_result status
;
3504 /* resolve trivial cases first */
3505 if (oideq(base
, ours
))
3506 return resolve_to(image
, theirs
);
3507 else if (oideq(base
, theirs
) || oideq(ours
, theirs
))
3508 return resolve_to(image
, ours
);
3510 read_mmblob(&base_file
, base
);
3511 read_mmblob(&our_file
, ours
);
3512 read_mmblob(&their_file
, theirs
);
3513 status
= ll_merge(&result
, path
,
3516 &their_file
, "theirs",
3519 if (status
== LL_MERGE_BINARY_CONFLICT
)
3520 warning("Cannot merge binary files: %s (%s vs. %s)",
3521 path
, "ours", "theirs");
3522 free(base_file
.ptr
);
3524 free(their_file
.ptr
);
3525 if (status
< 0 || !result
.ptr
) {
3530 image
->buf
= result
.ptr
;
3531 image
->len
= result
.size
;
3537 * When directly falling back to add/add three-way merge, we read from
3538 * the current contents of the new_name. In no cases other than that
3539 * this function will be called.
3541 static int load_current(struct apply_state
*state
,
3542 struct image
*image
,
3543 struct patch
*patch
)
3545 struct strbuf buf
= STRBUF_INIT
;
3550 struct cache_entry
*ce
;
3551 char *name
= patch
->new_name
;
3552 unsigned mode
= patch
->new_mode
;
3555 BUG("patch to %s is not a creation", patch
->old_name
);
3557 pos
= index_name_pos(state
->repo
->index
, name
, strlen(name
));
3559 return error(_("%s: does not exist in index"), name
);
3560 ce
= state
->repo
->index
->cache
[pos
];
3561 if (lstat(name
, &st
)) {
3562 if (errno
!= ENOENT
)
3563 return error_errno("%s", name
);
3564 if (checkout_target(state
->repo
->index
, ce
, &st
))
3567 if (verify_index_match(state
, ce
, &st
))
3568 return error(_("%s: does not match index"), name
);
3570 status
= load_patch_target(state
, &buf
, ce
, &st
, patch
, name
, mode
);
3575 img
= strbuf_detach(&buf
, &len
);
3576 prepare_image(image
, img
, len
, !patch
->is_binary
);
3580 static int try_threeway(struct apply_state
*state
,
3581 struct image
*image
,
3582 struct patch
*patch
,
3584 const struct cache_entry
*ce
)
3586 struct object_id pre_oid
, post_oid
, our_oid
;
3587 struct strbuf buf
= STRBUF_INIT
;
3591 struct image tmp_image
;
3593 /* No point falling back to 3-way merge in these cases */
3594 if (patch
->is_delete
||
3595 S_ISGITLINK(patch
->old_mode
) || S_ISGITLINK(patch
->new_mode
) ||
3596 (patch
->is_new
&& !patch
->direct_to_threeway
) ||
3597 (patch
->is_rename
&& !patch
->lines_added
&& !patch
->lines_deleted
))
3600 /* Preimage the patch was prepared for */
3602 write_object_file("", 0, OBJ_BLOB
, &pre_oid
);
3603 else if (get_oid(patch
->old_oid_prefix
, &pre_oid
) ||
3604 read_blob_object(&buf
, &pre_oid
, patch
->old_mode
))
3605 return error(_("repository lacks the necessary blob to perform 3-way merge."));
3607 if (state
->apply_verbosity
> verbosity_silent
&& patch
->direct_to_threeway
)
3608 fprintf(stderr
, _("Performing three-way merge...\n"));
3610 img
= strbuf_detach(&buf
, &len
);
3611 prepare_image(&tmp_image
, img
, len
, 1);
3612 /* Apply the patch to get the post image */
3613 if (apply_fragments(state
, &tmp_image
, patch
) < 0) {
3614 clear_image(&tmp_image
);
3617 /* post_oid is theirs */
3618 write_object_file(tmp_image
.buf
, tmp_image
.len
, OBJ_BLOB
, &post_oid
);
3619 clear_image(&tmp_image
);
3621 /* our_oid is ours */
3622 if (patch
->is_new
) {
3623 if (load_current(state
, &tmp_image
, patch
))
3624 return error(_("cannot read the current contents of '%s'"),
3627 if (load_preimage(state
, &tmp_image
, patch
, st
, ce
))
3628 return error(_("cannot read the current contents of '%s'"),
3631 write_object_file(tmp_image
.buf
, tmp_image
.len
, OBJ_BLOB
, &our_oid
);
3632 clear_image(&tmp_image
);
3634 /* in-core three-way merge between post and our using pre as base */
3635 status
= three_way_merge(state
, image
, patch
->new_name
,
3636 &pre_oid
, &our_oid
, &post_oid
);
3638 if (state
->apply_verbosity
> verbosity_silent
)
3640 _("Failed to perform three-way merge...\n"));
3645 patch
->conflicted_threeway
= 1;
3647 oidclr(&patch
->threeway_stage
[0]);
3649 oidcpy(&patch
->threeway_stage
[0], &pre_oid
);
3650 oidcpy(&patch
->threeway_stage
[1], &our_oid
);
3651 oidcpy(&patch
->threeway_stage
[2], &post_oid
);
3652 if (state
->apply_verbosity
> verbosity_silent
)
3654 _("Applied patch to '%s' with conflicts.\n"),
3657 if (state
->apply_verbosity
> verbosity_silent
)
3659 _("Applied patch to '%s' cleanly.\n"),
3665 static int apply_data(struct apply_state
*state
, struct patch
*patch
,
3666 struct stat
*st
, const struct cache_entry
*ce
)
3670 if (load_preimage(state
, &image
, patch
, st
, ce
) < 0)
3673 if (!state
->threeway
|| try_threeway(state
, &image
, patch
, st
, ce
) < 0) {
3674 if (state
->apply_verbosity
> verbosity_silent
&&
3675 state
->threeway
&& !patch
->direct_to_threeway
)
3676 fprintf(stderr
, _("Falling back to direct application...\n"));
3678 /* Note: with --reject, apply_fragments() returns 0 */
3679 if (patch
->direct_to_threeway
|| apply_fragments(state
, &image
, patch
) < 0)
3682 patch
->result
= image
.buf
;
3683 patch
->resultsize
= image
.len
;
3684 add_to_fn_table(state
, patch
);
3685 free(image
.line_allocated
);
3687 if (0 < patch
->is_delete
&& patch
->resultsize
)
3688 return error(_("removal patch leaves file contents"));
3694 * If "patch" that we are looking at modifies or deletes what we have,
3695 * we would want it not to lose any local modification we have, either
3696 * in the working tree or in the index.
3698 * This also decides if a non-git patch is a creation patch or a
3699 * modification to an existing empty file. We do not check the state
3700 * of the current tree for a creation patch in this function; the caller
3701 * check_patch() separately makes sure (and errors out otherwise) that
3702 * the path the patch creates does not exist in the current tree.
3704 static int check_preimage(struct apply_state
*state
,
3705 struct patch
*patch
,
3706 struct cache_entry
**ce
,
3709 const char *old_name
= patch
->old_name
;
3710 struct patch
*previous
= NULL
;
3711 int stat_ret
= 0, status
;
3712 unsigned st_mode
= 0;
3717 assert(patch
->is_new
<= 0);
3718 previous
= previous_patch(state
, patch
, &status
);
3721 return error(_("path %s has been renamed/deleted"), old_name
);
3723 st_mode
= previous
->new_mode
;
3724 } else if (!state
->cached
) {
3725 stat_ret
= lstat(old_name
, st
);
3726 if (stat_ret
&& errno
!= ENOENT
)
3727 return error_errno("%s", old_name
);
3730 if (state
->check_index
&& !previous
) {
3731 int pos
= index_name_pos(state
->repo
->index
, old_name
,
3734 if (patch
->is_new
< 0)
3736 return error(_("%s: does not exist in index"), old_name
);
3738 *ce
= state
->repo
->index
->cache
[pos
];
3740 if (checkout_target(state
->repo
->index
, *ce
, st
))
3743 if (!state
->cached
&& verify_index_match(state
, *ce
, st
))
3744 return error(_("%s: does not match index"), old_name
);
3746 st_mode
= (*ce
)->ce_mode
;
3747 } else if (stat_ret
< 0) {
3748 if (patch
->is_new
< 0)
3750 return error_errno("%s", old_name
);
3753 if (!state
->cached
&& !previous
)
3754 st_mode
= ce_mode_from_stat(*ce
, st
->st_mode
);
3756 if (patch
->is_new
< 0)
3758 if (!patch
->old_mode
)
3759 patch
->old_mode
= st_mode
;
3760 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
3761 return error(_("%s: wrong type"), old_name
);
3762 if (st_mode
!= patch
->old_mode
)
3763 warning(_("%s has type %o, expected %o"),
3764 old_name
, st_mode
, patch
->old_mode
);
3765 if (!patch
->new_mode
&& !patch
->is_delete
)
3766 patch
->new_mode
= st_mode
;
3771 patch
->is_delete
= 0;
3772 FREE_AND_NULL(patch
->old_name
);
3777 #define EXISTS_IN_INDEX 1
3778 #define EXISTS_IN_WORKTREE 2
3779 #define EXISTS_IN_INDEX_AS_ITA 3
3781 static int check_to_create(struct apply_state
*state
,
3782 const char *new_name
,
3787 if (state
->check_index
&& (!ok_if_exists
|| !state
->cached
)) {
3790 pos
= index_name_pos(state
->repo
->index
, new_name
, strlen(new_name
));
3792 struct cache_entry
*ce
= state
->repo
->index
->cache
[pos
];
3794 /* allow ITA, as they do not yet exist in the index */
3795 if (!ok_if_exists
&& !(ce
->ce_flags
& CE_INTENT_TO_ADD
))
3796 return EXISTS_IN_INDEX
;
3798 /* ITA entries can never match working tree files */
3799 if (!state
->cached
&& (ce
->ce_flags
& CE_INTENT_TO_ADD
))
3800 return EXISTS_IN_INDEX_AS_ITA
;
3807 if (!lstat(new_name
, &nst
)) {
3808 if (S_ISDIR(nst
.st_mode
) || ok_if_exists
)
3811 * A leading component of new_name might be a symlink
3812 * that is going to be removed with this patch, but
3813 * still pointing at somewhere that has the path.
3814 * In such a case, path "new_name" does not exist as
3815 * far as git is concerned.
3817 if (has_symlink_leading_path(new_name
, strlen(new_name
)))
3820 return EXISTS_IN_WORKTREE
;
3821 } else if (!is_missing_file_error(errno
)) {
3822 return error_errno("%s", new_name
);
3827 static void prepare_symlink_changes(struct apply_state
*state
, struct patch
*patch
)
3829 for ( ; patch
; patch
= patch
->next
) {
3830 if ((patch
->old_name
&& S_ISLNK(patch
->old_mode
)) &&
3831 (patch
->is_rename
|| patch
->is_delete
))
3832 /* the symlink at patch->old_name is removed */
3833 strset_add(&state
->removed_symlinks
, patch
->old_name
);
3835 if (patch
->new_name
&& S_ISLNK(patch
->new_mode
))
3836 /* the symlink at patch->new_name is created or remains */
3837 strset_add(&state
->kept_symlinks
, patch
->new_name
);
3841 static int path_is_beyond_symlink_1(struct apply_state
*state
, struct strbuf
*name
)
3844 while (--name
->len
&& name
->buf
[name
->len
] != '/')
3845 ; /* scan backwards */
3848 name
->buf
[name
->len
] = '\0';
3849 if (strset_contains(&state
->kept_symlinks
, name
->buf
))
3851 if (strset_contains(&state
->removed_symlinks
, name
->buf
))
3853 * This cannot be "return 0", because we may
3854 * see a new one created at a higher level.
3858 /* otherwise, check the preimage */
3859 if (state
->check_index
) {
3860 struct cache_entry
*ce
;
3862 ce
= index_file_exists(state
->repo
->index
, name
->buf
,
3863 name
->len
, ignore_case
);
3864 if (ce
&& S_ISLNK(ce
->ce_mode
))
3868 if (!lstat(name
->buf
, &st
) && S_ISLNK(st
.st_mode
))
3875 static int path_is_beyond_symlink(struct apply_state
*state
, const char *name_
)
3878 struct strbuf name
= STRBUF_INIT
;
3880 assert(*name_
!= '\0');
3881 strbuf_addstr(&name
, name_
);
3882 ret
= path_is_beyond_symlink_1(state
, &name
);
3883 strbuf_release(&name
);
3888 static int check_unsafe_path(struct patch
*patch
)
3890 const char *old_name
= NULL
;
3891 const char *new_name
= NULL
;
3892 if (patch
->is_delete
)
3893 old_name
= patch
->old_name
;
3894 else if (!patch
->is_new
&& !patch
->is_copy
)
3895 old_name
= patch
->old_name
;
3896 if (!patch
->is_delete
)
3897 new_name
= patch
->new_name
;
3899 if (old_name
&& !verify_path(old_name
, patch
->old_mode
))
3900 return error(_("invalid path '%s'"), old_name
);
3901 if (new_name
&& !verify_path(new_name
, patch
->new_mode
))
3902 return error(_("invalid path '%s'"), new_name
);
3907 * Check and apply the patch in-core; leave the result in patch->result
3908 * for the caller to write it out to the final destination.
3910 static int check_patch(struct apply_state
*state
, struct patch
*patch
)
3913 const char *old_name
= patch
->old_name
;
3914 const char *new_name
= patch
->new_name
;
3915 const char *name
= old_name
? old_name
: new_name
;
3916 struct cache_entry
*ce
= NULL
;
3917 struct patch
*tpatch
;
3921 patch
->rejected
= 1; /* we will drop this after we succeed */
3923 status
= check_preimage(state
, patch
, &ce
, &st
);
3926 old_name
= patch
->old_name
;
3929 * A type-change diff is always split into a patch to delete
3930 * old, immediately followed by a patch to create new (see
3931 * diff.c::run_diff()); in such a case it is Ok that the entry
3932 * to be deleted by the previous patch is still in the working
3933 * tree and in the index.
3935 * A patch to swap-rename between A and B would first rename A
3936 * to B and then rename B to A. While applying the first one,
3937 * the presence of B should not stop A from getting renamed to
3938 * B; ask to_be_deleted() about the later rename. Removal of
3939 * B and rename from A to B is handled the same way by asking
3942 if ((tpatch
= in_fn_table(state
, new_name
)) &&
3943 (was_deleted(tpatch
) || to_be_deleted(tpatch
)))
3949 ((0 < patch
->is_new
) || patch
->is_rename
|| patch
->is_copy
)) {
3950 int err
= check_to_create(state
, new_name
, ok_if_exists
);
3952 if (err
&& state
->threeway
) {
3953 patch
->direct_to_threeway
= 1;
3954 } else switch (err
) {
3957 case EXISTS_IN_INDEX
:
3958 return error(_("%s: already exists in index"), new_name
);
3959 case EXISTS_IN_INDEX_AS_ITA
:
3960 return error(_("%s: does not match index"), new_name
);
3961 case EXISTS_IN_WORKTREE
:
3962 return error(_("%s: already exists in working directory"),
3968 if (!patch
->new_mode
) {
3969 if (0 < patch
->is_new
)
3970 patch
->new_mode
= S_IFREG
| 0644;
3972 patch
->new_mode
= patch
->old_mode
;
3976 if (new_name
&& old_name
) {
3977 int same
= !strcmp(old_name
, new_name
);
3978 if (!patch
->new_mode
)
3979 patch
->new_mode
= patch
->old_mode
;
3980 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
) {
3982 return error(_("new mode (%o) of %s does not "
3983 "match old mode (%o)"),
3984 patch
->new_mode
, new_name
,
3987 return error(_("new mode (%o) of %s does not "
3988 "match old mode (%o) of %s"),
3989 patch
->new_mode
, new_name
,
3990 patch
->old_mode
, old_name
);
3994 if (!state
->unsafe_paths
&& check_unsafe_path(patch
))
3998 * An attempt to read from or delete a path that is beyond a
3999 * symbolic link will be prevented by load_patch_target() that
4000 * is called at the beginning of apply_data() so we do not
4001 * have to worry about a patch marked with "is_delete" bit
4002 * here. We however need to make sure that the patch result
4003 * is not deposited to a path that is beyond a symbolic link
4006 if (!patch
->is_delete
&& path_is_beyond_symlink(state
, patch
->new_name
))
4007 return error(_("affected file '%s' is beyond a symbolic link"),
4010 if (apply_data(state
, patch
, &st
, ce
) < 0)
4011 return error(_("%s: patch does not apply"), name
);
4012 patch
->rejected
= 0;
4016 static int check_patch_list(struct apply_state
*state
, struct patch
*patch
)
4020 prepare_symlink_changes(state
, patch
);
4021 prepare_fn_table(state
, patch
);
4024 if (state
->apply_verbosity
> verbosity_normal
)
4025 say_patch_name(stderr
,
4026 _("Checking patch %s..."), patch
);
4027 res
= check_patch(state
, patch
);
4031 patch
= patch
->next
;
4036 static int read_apply_cache(struct apply_state
*state
)
4038 if (state
->index_file
)
4039 return read_index_from(state
->repo
->index
, state
->index_file
,
4042 return repo_read_index(state
->repo
);
4045 /* This function tries to read the object name from the current index */
4046 static int get_current_oid(struct apply_state
*state
, const char *path
,
4047 struct object_id
*oid
)
4051 if (read_apply_cache(state
) < 0)
4053 pos
= index_name_pos(state
->repo
->index
, path
, strlen(path
));
4056 oidcpy(oid
, &state
->repo
->index
->cache
[pos
]->oid
);
4060 static int preimage_oid_in_gitlink_patch(struct patch
*p
, struct object_id
*oid
)
4063 * A usable gitlink patch has only one fragment (hunk) that looks like:
4065 * -Subproject commit <old sha1>
4066 * +Subproject commit <new sha1>
4069 * -Subproject commit <old sha1>
4070 * for a removal patch.
4072 struct fragment
*hunk
= p
->fragments
;
4073 static const char heading
[] = "-Subproject commit ";
4076 if (/* does the patch have only one hunk? */
4077 hunk
&& !hunk
->next
&&
4078 /* is its preimage one line? */
4079 hunk
->oldpos
== 1 && hunk
->oldlines
== 1 &&
4080 /* does preimage begin with the heading? */
4081 (preimage
= memchr(hunk
->patch
, '\n', hunk
->size
)) != NULL
&&
4082 starts_with(++preimage
, heading
) &&
4083 /* does it record full SHA-1? */
4084 !get_oid_hex(preimage
+ sizeof(heading
) - 1, oid
) &&
4085 preimage
[sizeof(heading
) + the_hash_algo
->hexsz
- 1] == '\n' &&
4086 /* does the abbreviated name on the index line agree with it? */
4087 starts_with(preimage
+ sizeof(heading
) - 1, p
->old_oid_prefix
))
4088 return 0; /* it all looks fine */
4090 /* we may have full object name on the index line */
4091 return get_oid_hex(p
->old_oid_prefix
, oid
);
4094 /* Build an index that contains just the files needed for a 3way merge */
4095 static int build_fake_ancestor(struct apply_state
*state
, struct patch
*list
)
4097 struct patch
*patch
;
4098 struct index_state result
= { NULL
};
4099 struct lock_file lock
= LOCK_INIT
;
4102 /* Once we start supporting the reverse patch, it may be
4103 * worth showing the new sha1 prefix, but until then...
4105 for (patch
= list
; patch
; patch
= patch
->next
) {
4106 struct object_id oid
;
4107 struct cache_entry
*ce
;
4110 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
4111 if (0 < patch
->is_new
)
4114 if (S_ISGITLINK(patch
->old_mode
)) {
4115 if (!preimage_oid_in_gitlink_patch(patch
, &oid
))
4116 ; /* ok, the textual part looks sane */
4118 return error(_("sha1 information is lacking or "
4119 "useless for submodule %s"), name
);
4120 } else if (!get_oid_blob(patch
->old_oid_prefix
, &oid
)) {
4122 } else if (!patch
->lines_added
&& !patch
->lines_deleted
) {
4123 /* mode-only change: update the current */
4124 if (get_current_oid(state
, patch
->old_name
, &oid
))
4125 return error(_("mode change for %s, which is not "
4126 "in current HEAD"), name
);
4128 return error(_("sha1 information is lacking or useless "
4131 ce
= make_cache_entry(&result
, patch
->old_mode
, &oid
, name
, 0, 0);
4133 return error(_("make_cache_entry failed for path '%s'"),
4135 if (add_index_entry(&result
, ce
, ADD_CACHE_OK_TO_ADD
)) {
4136 discard_cache_entry(ce
);
4137 return error(_("could not add %s to temporary index"),
4142 hold_lock_file_for_update(&lock
, state
->fake_ancestor
, LOCK_DIE_ON_ERROR
);
4143 res
= write_locked_index(&result
, &lock
, COMMIT_LOCK
);
4144 discard_index(&result
);
4147 return error(_("could not write temporary index to %s"),
4148 state
->fake_ancestor
);
4153 static void stat_patch_list(struct apply_state
*state
, struct patch
*patch
)
4155 int files
, adds
, dels
;
4157 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
4159 adds
+= patch
->lines_added
;
4160 dels
+= patch
->lines_deleted
;
4161 show_stats(state
, patch
);
4164 print_stat_summary(stdout
, files
, adds
, dels
);
4167 static void numstat_patch_list(struct apply_state
*state
,
4168 struct patch
*patch
)
4170 for ( ; patch
; patch
= patch
->next
) {
4172 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
4173 if (patch
->is_binary
)
4176 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
4177 write_name_quoted(name
, stdout
, state
->line_termination
);
4181 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
4184 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
4186 printf(" %s %s\n", newdelete
, name
);
4189 static void show_mode_change(struct patch
*p
, int show_name
)
4191 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
4193 printf(" mode change %06o => %06o %s\n",
4194 p
->old_mode
, p
->new_mode
, p
->new_name
);
4196 printf(" mode change %06o => %06o\n",
4197 p
->old_mode
, p
->new_mode
);
4201 static void show_rename_copy(struct patch
*p
)
4203 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
4204 const char *old_name
, *new_name
;
4206 /* Find common prefix */
4207 old_name
= p
->old_name
;
4208 new_name
= p
->new_name
;
4210 const char *slash_old
, *slash_new
;
4211 slash_old
= strchr(old_name
, '/');
4212 slash_new
= strchr(new_name
, '/');
4215 slash_old
- old_name
!= slash_new
- new_name
||
4216 memcmp(old_name
, new_name
, slash_new
- new_name
))
4218 old_name
= slash_old
+ 1;
4219 new_name
= slash_new
+ 1;
4221 /* p->old_name through old_name is the common prefix, and old_name and
4222 * new_name through the end of names are renames
4224 if (old_name
!= p
->old_name
)
4225 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
4226 (int)(old_name
- p
->old_name
), p
->old_name
,
4227 old_name
, new_name
, p
->score
);
4229 printf(" %s %s => %s (%d%%)\n", renamecopy
,
4230 p
->old_name
, p
->new_name
, p
->score
);
4231 show_mode_change(p
, 0);
4234 static void summary_patch_list(struct patch
*patch
)
4238 for (p
= patch
; p
; p
= p
->next
) {
4240 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
4241 else if (p
->is_delete
)
4242 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
4244 if (p
->is_rename
|| p
->is_copy
)
4245 show_rename_copy(p
);
4248 printf(" rewrite %s (%d%%)\n",
4249 p
->new_name
, p
->score
);
4250 show_mode_change(p
, 0);
4253 show_mode_change(p
, 1);
4259 static void patch_stats(struct apply_state
*state
, struct patch
*patch
)
4261 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
4263 if (lines
> state
->max_change
)
4264 state
->max_change
= lines
;
4265 if (patch
->old_name
) {
4266 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
4268 len
= strlen(patch
->old_name
);
4269 if (len
> state
->max_len
)
4270 state
->max_len
= len
;
4272 if (patch
->new_name
) {
4273 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
4275 len
= strlen(patch
->new_name
);
4276 if (len
> state
->max_len
)
4277 state
->max_len
= len
;
4281 static int remove_file(struct apply_state
*state
, struct patch
*patch
, int rmdir_empty
)
4283 if (state
->update_index
&& !state
->ita_only
) {
4284 if (remove_file_from_index(state
->repo
->index
, patch
->old_name
) < 0)
4285 return error(_("unable to remove %s from index"), patch
->old_name
);
4287 if (!state
->cached
) {
4288 if (!remove_or_warn(patch
->old_mode
, patch
->old_name
) && rmdir_empty
) {
4289 remove_path(patch
->old_name
);
4295 static int add_index_file(struct apply_state
*state
,
4302 struct cache_entry
*ce
;
4303 int namelen
= strlen(path
);
4305 ce
= make_empty_cache_entry(state
->repo
->index
, namelen
);
4306 memcpy(ce
->name
, path
, namelen
);
4307 ce
->ce_mode
= create_ce_mode(mode
);
4308 ce
->ce_flags
= create_ce_flags(0);
4309 ce
->ce_namelen
= namelen
;
4310 if (state
->ita_only
) {
4311 ce
->ce_flags
|= CE_INTENT_TO_ADD
;
4312 set_object_name_for_intent_to_add_entry(ce
);
4313 } else if (S_ISGITLINK(mode
)) {
4316 if (!skip_prefix(buf
, "Subproject commit ", &s
) ||
4317 get_oid_hex(s
, &ce
->oid
)) {
4318 discard_cache_entry(ce
);
4319 return error(_("corrupt patch for submodule %s"), path
);
4322 if (!state
->cached
) {
4323 if (lstat(path
, &st
) < 0) {
4324 discard_cache_entry(ce
);
4325 return error_errno(_("unable to stat newly "
4326 "created file '%s'"),
4329 fill_stat_cache_info(state
->repo
->index
, ce
, &st
);
4331 if (write_object_file(buf
, size
, OBJ_BLOB
, &ce
->oid
) < 0) {
4332 discard_cache_entry(ce
);
4333 return error(_("unable to create backing store "
4334 "for newly created file %s"), path
);
4337 if (add_index_entry(state
->repo
->index
, ce
, ADD_CACHE_OK_TO_ADD
) < 0) {
4338 discard_cache_entry(ce
);
4339 return error(_("unable to add cache entry for %s"), path
);
4347 * -1 if an unrecoverable error happened
4348 * 0 if everything went well
4349 * 1 if a recoverable error happened
4351 static int try_create_file(struct apply_state
*state
, const char *path
,
4352 unsigned int mode
, const char *buf
,
4356 struct strbuf nbuf
= STRBUF_INIT
;
4358 if (S_ISGITLINK(mode
)) {
4360 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
))
4362 return !!mkdir(path
, 0777);
4365 if (has_symlinks
&& S_ISLNK(mode
))
4366 /* Although buf:size is counted string, it also is NUL
4369 return !!symlink(buf
, path
);
4371 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
4375 if (convert_to_working_tree(state
->repo
->index
, path
, buf
, size
, &nbuf
, NULL
)) {
4380 res
= write_in_full(fd
, buf
, size
) < 0;
4382 error_errno(_("failed to write to '%s'"), path
);
4383 strbuf_release(&nbuf
);
4385 if (close(fd
) < 0 && !res
)
4386 return error_errno(_("closing file '%s'"), path
);
4388 return res
? -1 : 0;
4392 * We optimistically assume that the directories exist,
4393 * which is true 99% of the time anyway. If they don't,
4394 * we create them and try again.
4400 static int create_one_file(struct apply_state
*state
,
4411 res
= try_create_file(state
, path
, mode
, buf
, size
);
4417 if (errno
== ENOENT
) {
4418 if (safe_create_leading_directories_no_share(path
))
4420 res
= try_create_file(state
, path
, mode
, buf
, size
);
4427 if (errno
== EEXIST
|| errno
== EACCES
) {
4428 /* We may be trying to create a file where a directory
4432 if (!lstat(path
, &st
) && (!S_ISDIR(st
.st_mode
) || !rmdir(path
)))
4436 if (errno
== EEXIST
) {
4437 unsigned int nr
= getpid();
4440 char newpath
[PATH_MAX
];
4441 mksnpath(newpath
, sizeof(newpath
), "%s~%u", path
, nr
);
4442 res
= try_create_file(state
, newpath
, mode
, buf
, size
);
4446 if (!rename(newpath
, path
))
4448 unlink_or_warn(newpath
);
4451 if (errno
!= EEXIST
)
4456 return error_errno(_("unable to write file '%s' mode %o"),
4460 static int add_conflicted_stages_file(struct apply_state
*state
,
4461 struct patch
*patch
)
4465 struct cache_entry
*ce
;
4467 if (!state
->update_index
)
4469 namelen
= strlen(patch
->new_name
);
4470 mode
= patch
->new_mode
? patch
->new_mode
: (S_IFREG
| 0644);
4472 remove_file_from_index(state
->repo
->index
, patch
->new_name
);
4473 for (stage
= 1; stage
< 4; stage
++) {
4474 if (is_null_oid(&patch
->threeway_stage
[stage
- 1]))
4476 ce
= make_empty_cache_entry(state
->repo
->index
, namelen
);
4477 memcpy(ce
->name
, patch
->new_name
, namelen
);
4478 ce
->ce_mode
= create_ce_mode(mode
);
4479 ce
->ce_flags
= create_ce_flags(stage
);
4480 ce
->ce_namelen
= namelen
;
4481 oidcpy(&ce
->oid
, &patch
->threeway_stage
[stage
- 1]);
4482 if (add_index_entry(state
->repo
->index
, ce
, ADD_CACHE_OK_TO_ADD
) < 0) {
4483 discard_cache_entry(ce
);
4484 return error(_("unable to add cache entry for %s"),
4492 static int create_file(struct apply_state
*state
, struct patch
*patch
)
4494 char *path
= patch
->new_name
;
4495 unsigned mode
= patch
->new_mode
;
4496 unsigned long size
= patch
->resultsize
;
4497 char *buf
= patch
->result
;
4500 mode
= S_IFREG
| 0644;
4501 if (create_one_file(state
, path
, mode
, buf
, size
))
4504 if (patch
->conflicted_threeway
)
4505 return add_conflicted_stages_file(state
, patch
);
4506 else if (state
->update_index
)
4507 return add_index_file(state
, path
, mode
, buf
, size
);
4511 /* phase zero is to remove, phase one is to create */
4512 static int write_out_one_result(struct apply_state
*state
,
4513 struct patch
*patch
,
4516 if (patch
->is_delete
> 0) {
4518 return remove_file(state
, patch
, 1);
4521 if (patch
->is_new
> 0 || patch
->is_copy
) {
4523 return create_file(state
, patch
);
4527 * Rename or modification boils down to the same
4528 * thing: remove the old, write the new
4531 return remove_file(state
, patch
, patch
->is_rename
);
4533 return create_file(state
, patch
);
4537 static int write_out_one_reject(struct apply_state
*state
, struct patch
*patch
)
4540 char namebuf
[PATH_MAX
];
4541 struct fragment
*frag
;
4543 struct strbuf sb
= STRBUF_INIT
;
4545 for (cnt
= 0, frag
= patch
->fragments
; frag
; frag
= frag
->next
) {
4546 if (!frag
->rejected
)
4552 if (state
->apply_verbosity
> verbosity_normal
)
4553 say_patch_name(stderr
,
4554 _("Applied patch %s cleanly."), patch
);
4558 /* This should not happen, because a removal patch that leaves
4559 * contents are marked "rejected" at the patch level.
4561 if (!patch
->new_name
)
4562 die(_("internal error"));
4564 /* Say this even without --verbose */
4565 strbuf_addf(&sb
, Q_("Applying patch %%s with %d reject...",
4566 "Applying patch %%s with %d rejects...",
4569 if (state
->apply_verbosity
> verbosity_silent
)
4570 say_patch_name(stderr
, sb
.buf
, patch
);
4571 strbuf_release(&sb
);
4573 cnt
= strlen(patch
->new_name
);
4574 if (ARRAY_SIZE(namebuf
) <= cnt
+ 5) {
4575 cnt
= ARRAY_SIZE(namebuf
) - 5;
4576 warning(_("truncating .rej filename to %.*s.rej"),
4577 cnt
- 1, patch
->new_name
);
4579 memcpy(namebuf
, patch
->new_name
, cnt
);
4580 memcpy(namebuf
+ cnt
, ".rej", 5);
4582 rej
= fopen(namebuf
, "w");
4584 return error_errno(_("cannot open %s"), namebuf
);
4586 /* Normal git tools never deal with .rej, so do not pretend
4587 * this is a git patch by saying --git or giving extended
4588 * headers. While at it, maybe please "kompare" that wants
4589 * the trailing TAB and some garbage at the end of line ;-).
4591 fprintf(rej
, "diff a/%s b/%s\t(rejected hunks)\n",
4592 patch
->new_name
, patch
->new_name
);
4593 for (cnt
= 1, frag
= patch
->fragments
;
4595 cnt
++, frag
= frag
->next
) {
4596 if (!frag
->rejected
) {
4597 if (state
->apply_verbosity
> verbosity_silent
)
4598 fprintf_ln(stderr
, _("Hunk #%d applied cleanly."), cnt
);
4601 if (state
->apply_verbosity
> verbosity_silent
)
4602 fprintf_ln(stderr
, _("Rejected hunk #%d."), cnt
);
4603 fprintf(rej
, "%.*s", frag
->size
, frag
->patch
);
4604 if (frag
->patch
[frag
->size
-1] != '\n')
4613 * -1 if an error happened
4614 * 0 if the patch applied cleanly
4615 * 1 if the patch did not apply cleanly
4617 static int write_out_results(struct apply_state
*state
, struct patch
*list
)
4622 struct string_list cpath
= STRING_LIST_INIT_DUP
;
4624 for (phase
= 0; phase
< 2; phase
++) {
4630 if (write_out_one_result(state
, l
, phase
)) {
4631 string_list_clear(&cpath
, 0);
4635 if (write_out_one_reject(state
, l
))
4637 if (l
->conflicted_threeway
) {
4638 string_list_append(&cpath
, l
->new_name
);
4648 struct string_list_item
*item
;
4650 string_list_sort(&cpath
);
4651 if (state
->apply_verbosity
> verbosity_silent
) {
4652 for_each_string_list_item(item
, &cpath
)
4653 fprintf(stderr
, "U %s\n", item
->string
);
4655 string_list_clear(&cpath
, 0);
4658 * rerere relies on the partially merged result being in the working
4659 * tree with conflict markers, but that isn't written with --cached.
4662 repo_rerere(state
->repo
, 0);
4669 * Try to apply a patch.
4672 * -128 if a bad error happened (like patch unreadable)
4673 * -1 if patch did not apply and user cannot deal with it
4674 * 0 if the patch applied
4675 * 1 if the patch did not apply but user might fix it
4677 static int apply_patch(struct apply_state
*state
,
4679 const char *filename
,
4683 struct strbuf buf
= STRBUF_INIT
; /* owns the patch text */
4684 struct patch
*list
= NULL
, **listp
= &list
;
4685 int skipped_patch
= 0;
4687 int flush_attributes
= 0;
4689 state
->patch_input_file
= filename
;
4690 if (read_patch_file(&buf
, fd
) < 0)
4693 while (offset
< buf
.len
) {
4694 struct patch
*patch
;
4697 CALLOC_ARRAY(patch
, 1);
4698 patch
->inaccurate_eof
= !!(options
& APPLY_OPT_INACCURATE_EOF
);
4699 patch
->recount
= !!(options
& APPLY_OPT_RECOUNT
);
4700 nr
= parse_chunk(state
, buf
.buf
+ offset
, buf
.len
- offset
, patch
);
4709 if (state
->apply_in_reverse
)
4710 reverse_patches(patch
);
4711 if (use_patch(state
, patch
)) {
4712 patch_stats(state
, patch
);
4713 if (!list
|| !state
->apply_in_reverse
) {
4715 listp
= &patch
->next
;
4721 if ((patch
->new_name
&&
4722 ends_with_path_components(patch
->new_name
,
4723 GITATTRIBUTES_FILE
)) ||
4725 ends_with_path_components(patch
->old_name
,
4726 GITATTRIBUTES_FILE
)))
4727 flush_attributes
= 1;
4730 if (state
->apply_verbosity
> verbosity_normal
)
4731 say_patch_name(stderr
, _("Skipped patch '%s'."), patch
);
4738 if (!list
&& !skipped_patch
) {
4739 if (!state
->allow_empty
) {
4740 error(_("No valid patches in input (allow with \"--allow-empty\")"));
4746 if (state
->whitespace_error
&& (state
->ws_error_action
== die_on_ws_error
))
4749 state
->update_index
= (state
->check_index
|| state
->ita_only
) && state
->apply
;
4750 if (state
->update_index
&& !is_lock_file_locked(&state
->lock_file
)) {
4751 if (state
->index_file
)
4752 hold_lock_file_for_update(&state
->lock_file
,
4756 repo_hold_locked_index(state
->repo
, &state
->lock_file
,
4760 if (state
->check_index
&& read_apply_cache(state
) < 0) {
4761 error(_("unable to read index file"));
4766 if (state
->check
|| state
->apply
) {
4767 int r
= check_patch_list(state
, list
);
4772 if (r
< 0 && !state
->apply_with_reject
) {
4779 int write_res
= write_out_results(state
, list
);
4780 if (write_res
< 0) {
4784 if (write_res
> 0) {
4785 /* with --3way, we still need to write the index out */
4786 res
= state
->apply_with_reject
? -1 : 1;
4791 if (state
->fake_ancestor
&&
4792 build_fake_ancestor(state
, list
)) {
4797 if (state
->diffstat
&& state
->apply_verbosity
> verbosity_silent
)
4798 stat_patch_list(state
, list
);
4800 if (state
->numstat
&& state
->apply_verbosity
> verbosity_silent
)
4801 numstat_patch_list(state
, list
);
4803 if (state
->summary
&& state
->apply_verbosity
> verbosity_silent
)
4804 summary_patch_list(list
);
4806 if (flush_attributes
)
4807 reset_parsed_attributes();
4809 free_patch_list(list
);
4810 strbuf_release(&buf
);
4811 string_list_clear(&state
->fn_table
, 0);
4815 static int apply_option_parse_exclude(const struct option
*opt
,
4816 const char *arg
, int unset
)
4818 struct apply_state
*state
= opt
->value
;
4820 BUG_ON_OPT_NEG(unset
);
4822 add_name_limit(state
, arg
, 1);
4826 static int apply_option_parse_include(const struct option
*opt
,
4827 const char *arg
, int unset
)
4829 struct apply_state
*state
= opt
->value
;
4831 BUG_ON_OPT_NEG(unset
);
4833 add_name_limit(state
, arg
, 0);
4834 state
->has_include
= 1;
4838 static int apply_option_parse_p(const struct option
*opt
,
4842 struct apply_state
*state
= opt
->value
;
4844 BUG_ON_OPT_NEG(unset
);
4846 state
->p_value
= atoi(arg
);
4847 state
->p_value_known
= 1;
4851 static int apply_option_parse_space_change(const struct option
*opt
,
4852 const char *arg
, int unset
)
4854 struct apply_state
*state
= opt
->value
;
4856 BUG_ON_OPT_ARG(arg
);
4859 state
->ws_ignore_action
= ignore_ws_none
;
4861 state
->ws_ignore_action
= ignore_ws_change
;
4865 static int apply_option_parse_whitespace(const struct option
*opt
,
4866 const char *arg
, int unset
)
4868 struct apply_state
*state
= opt
->value
;
4870 BUG_ON_OPT_NEG(unset
);
4872 state
->whitespace_option
= arg
;
4873 if (parse_whitespace_option(state
, arg
))
4878 static int apply_option_parse_directory(const struct option
*opt
,
4879 const char *arg
, int unset
)
4881 struct apply_state
*state
= opt
->value
;
4883 BUG_ON_OPT_NEG(unset
);
4885 strbuf_reset(&state
->root
);
4886 strbuf_addstr(&state
->root
, arg
);
4887 strbuf_complete(&state
->root
, '/');
4891 int apply_all_patches(struct apply_state
*state
,
4901 for (i
= 0; i
< argc
; i
++) {
4902 const char *arg
= argv
[i
];
4903 char *to_free
= NULL
;
4906 if (!strcmp(arg
, "-")) {
4907 res
= apply_patch(state
, 0, "<stdin>", options
);
4914 arg
= to_free
= prefix_filename(state
->prefix
, arg
);
4916 fd
= open(arg
, O_RDONLY
);
4918 error(_("can't open patch '%s': %s"), arg
, strerror(errno
));
4924 set_default_whitespace_mode(state
);
4925 res
= apply_patch(state
, fd
, arg
, options
);
4932 set_default_whitespace_mode(state
);
4934 res
= apply_patch(state
, 0, "<stdin>", options
);
4940 if (state
->whitespace_error
) {
4941 if (state
->squelch_whitespace_errors
&&
4942 state
->squelch_whitespace_errors
< state
->whitespace_error
) {
4944 state
->whitespace_error
- state
->squelch_whitespace_errors
;
4945 warning(Q_("squelched %d whitespace error",
4946 "squelched %d whitespace errors",
4950 if (state
->ws_error_action
== die_on_ws_error
) {
4951 error(Q_("%d line adds whitespace errors.",
4952 "%d lines add whitespace errors.",
4953 state
->whitespace_error
),
4954 state
->whitespace_error
);
4958 if (state
->applied_after_fixing_ws
&& state
->apply
)
4959 warning(Q_("%d line applied after"
4960 " fixing whitespace errors.",
4961 "%d lines applied after"
4962 " fixing whitespace errors.",
4963 state
->applied_after_fixing_ws
),
4964 state
->applied_after_fixing_ws
);
4965 else if (state
->whitespace_error
)
4966 warning(Q_("%d line adds whitespace errors.",
4967 "%d lines add whitespace errors.",
4968 state
->whitespace_error
),
4969 state
->whitespace_error
);
4972 if (state
->update_index
) {
4973 res
= write_locked_index(state
->repo
->index
, &state
->lock_file
, COMMIT_LOCK
);
4975 error(_("Unable to write new index file"));
4984 rollback_lock_file(&state
->lock_file
);
4986 if (state
->apply_verbosity
<= verbosity_silent
) {
4987 set_error_routine(state
->saved_error_routine
);
4988 set_warn_routine(state
->saved_warn_routine
);
4993 return (res
== -1 ? 1 : 128);
4996 int apply_parse_options(int argc
, const char **argv
,
4997 struct apply_state
*state
,
4998 int *force_apply
, int *options
,
4999 const char * const *apply_usage
)
5001 struct option builtin_apply_options
[] = {
5002 OPT_CALLBACK_F(0, "exclude", state
, N_("path"),
5003 N_("don't apply changes matching the given path"),
5004 PARSE_OPT_NONEG
, apply_option_parse_exclude
),
5005 OPT_CALLBACK_F(0, "include", state
, N_("path"),
5006 N_("apply changes matching the given path"),
5007 PARSE_OPT_NONEG
, apply_option_parse_include
),
5008 OPT_CALLBACK('p', NULL
, state
, N_("num"),
5009 N_("remove <num> leading slashes from traditional diff paths"),
5010 apply_option_parse_p
),
5011 OPT_BOOL(0, "no-add", &state
->no_add
,
5012 N_("ignore additions made by the patch")),
5013 OPT_BOOL(0, "stat", &state
->diffstat
,
5014 N_("instead of applying the patch, output diffstat for the input")),
5015 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
5016 OPT_NOOP_NOARG(0, "binary"),
5017 OPT_BOOL(0, "numstat", &state
->numstat
,
5018 N_("show number of added and deleted lines in decimal notation")),
5019 OPT_BOOL(0, "summary", &state
->summary
,
5020 N_("instead of applying the patch, output a summary for the input")),
5021 OPT_BOOL(0, "check", &state
->check
,
5022 N_("instead of applying the patch, see if the patch is applicable")),
5023 OPT_BOOL(0, "index", &state
->check_index
,
5024 N_("make sure the patch is applicable to the current index")),
5025 OPT_BOOL('N', "intent-to-add", &state
->ita_only
,
5026 N_("mark new files with `git add --intent-to-add`")),
5027 OPT_BOOL(0, "cached", &state
->cached
,
5028 N_("apply a patch without touching the working tree")),
5029 OPT_BOOL_F(0, "unsafe-paths", &state
->unsafe_paths
,
5030 N_("accept a patch that touches outside the working area"),
5031 PARSE_OPT_NOCOMPLETE
),
5032 OPT_BOOL(0, "apply", force_apply
,
5033 N_("also apply the patch (use with --stat/--summary/--check)")),
5034 OPT_BOOL('3', "3way", &state
->threeway
,
5035 N_( "attempt three-way merge, fall back on normal patch if that fails")),
5036 OPT_FILENAME(0, "build-fake-ancestor", &state
->fake_ancestor
,
5037 N_("build a temporary index based on embedded index information")),
5038 /* Think twice before adding "--nul" synonym to this */
5039 OPT_SET_INT('z', NULL
, &state
->line_termination
,
5040 N_("paths are separated with NUL character"), '\0'),
5041 OPT_INTEGER('C', NULL
, &state
->p_context
,
5042 N_("ensure at least <n> lines of context match")),
5043 OPT_CALLBACK(0, "whitespace", state
, N_("action"),
5044 N_("detect new or modified lines that have whitespace errors"),
5045 apply_option_parse_whitespace
),
5046 OPT_CALLBACK_F(0, "ignore-space-change", state
, NULL
,
5047 N_("ignore changes in whitespace when finding context"),
5048 PARSE_OPT_NOARG
, apply_option_parse_space_change
),
5049 OPT_CALLBACK_F(0, "ignore-whitespace", state
, NULL
,
5050 N_("ignore changes in whitespace when finding context"),
5051 PARSE_OPT_NOARG
, apply_option_parse_space_change
),
5052 OPT_BOOL('R', "reverse", &state
->apply_in_reverse
,
5053 N_("apply the patch in reverse")),
5054 OPT_BOOL(0, "unidiff-zero", &state
->unidiff_zero
,
5055 N_("don't expect at least one line of context")),
5056 OPT_BOOL(0, "reject", &state
->apply_with_reject
,
5057 N_("leave the rejected hunks in corresponding *.rej files")),
5058 OPT_BOOL(0, "allow-overlap", &state
->allow_overlap
,
5059 N_("allow overlapping hunks")),
5060 OPT__VERBOSITY(&state
->apply_verbosity
),
5061 OPT_BIT(0, "inaccurate-eof", options
,
5062 N_("tolerate incorrectly detected missing new-line at the end of file"),
5063 APPLY_OPT_INACCURATE_EOF
),
5064 OPT_BIT(0, "recount", options
,
5065 N_("do not trust the line counts in the hunk headers"),
5067 OPT_CALLBACK(0, "directory", state
, N_("root"),
5068 N_("prepend <root> to all filenames"),
5069 apply_option_parse_directory
),
5070 OPT_BOOL(0, "allow-empty", &state
->allow_empty
,
5071 N_("don't return error for empty patches")),
5075 return parse_options(argc
, argv
, state
->prefix
, builtin_apply_options
, apply_usage
, 0);