4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
14 #include "object-store.h"
21 #include "xdiff-interface.h"
24 #include "parse-options.h"
36 static void git_apply_config(void)
38 git_config_get_string("apply.whitespace", &apply_default_whitespace
);
39 git_config_get_string("apply.ignorewhitespace", &apply_default_ignorewhitespace
);
40 git_config(git_xmerge_config
, NULL
);
43 static int parse_whitespace_option(struct apply_state
*state
, const char *option
)
46 state
->ws_error_action
= warn_on_ws_error
;
49 if (!strcmp(option
, "warn")) {
50 state
->ws_error_action
= warn_on_ws_error
;
53 if (!strcmp(option
, "nowarn")) {
54 state
->ws_error_action
= nowarn_ws_error
;
57 if (!strcmp(option
, "error")) {
58 state
->ws_error_action
= die_on_ws_error
;
61 if (!strcmp(option
, "error-all")) {
62 state
->ws_error_action
= die_on_ws_error
;
63 state
->squelch_whitespace_errors
= 0;
66 if (!strcmp(option
, "strip") || !strcmp(option
, "fix")) {
67 state
->ws_error_action
= correct_ws_error
;
71 * Please update $__git_whitespacelist in git-completion.bash
72 * when you add new options.
74 return error(_("unrecognized whitespace option '%s'"), option
);
77 static int parse_ignorewhitespace_option(struct apply_state
*state
,
80 if (!option
|| !strcmp(option
, "no") ||
81 !strcmp(option
, "false") || !strcmp(option
, "never") ||
82 !strcmp(option
, "none")) {
83 state
->ws_ignore_action
= ignore_ws_none
;
86 if (!strcmp(option
, "change")) {
87 state
->ws_ignore_action
= ignore_ws_change
;
90 return error(_("unrecognized whitespace ignore option '%s'"), option
);
93 int init_apply_state(struct apply_state
*state
,
94 struct repository
*repo
,
97 memset(state
, 0, sizeof(*state
));
98 state
->prefix
= prefix
;
101 state
->line_termination
= '\n';
103 state
->p_context
= UINT_MAX
;
104 state
->squelch_whitespace_errors
= 5;
105 state
->ws_error_action
= warn_on_ws_error
;
106 state
->ws_ignore_action
= ignore_ws_none
;
108 string_list_init_nodup(&state
->fn_table
);
109 string_list_init_nodup(&state
->limit_by_name
);
110 strset_init(&state
->removed_symlinks
);
111 strset_init(&state
->kept_symlinks
);
112 strbuf_init(&state
->root
, 0);
115 if (apply_default_whitespace
&& parse_whitespace_option(state
, apply_default_whitespace
))
117 if (apply_default_ignorewhitespace
&& parse_ignorewhitespace_option(state
, apply_default_ignorewhitespace
))
122 void clear_apply_state(struct apply_state
*state
)
124 string_list_clear(&state
->limit_by_name
, 0);
125 strset_clear(&state
->removed_symlinks
);
126 strset_clear(&state
->kept_symlinks
);
127 strbuf_release(&state
->root
);
129 /* &state->fn_table is cleared at the end of apply_patch() */
132 static void mute_routine(const char *msg UNUSED
, va_list params UNUSED
)
137 int check_apply_state(struct apply_state
*state
, int force_apply
)
139 int is_not_gitdir
= !startup_info
->have_repository
;
141 if (state
->apply_with_reject
&& state
->threeway
)
142 return error(_("options '%s' and '%s' cannot be used together"), "--reject", "--3way");
143 if (state
->threeway
) {
145 return error(_("'%s' outside a repository"), "--3way");
146 state
->check_index
= 1;
148 if (state
->apply_with_reject
) {
150 if (state
->apply_verbosity
== verbosity_normal
)
151 state
->apply_verbosity
= verbosity_verbose
;
153 if (!force_apply
&& (state
->diffstat
|| state
->numstat
|| state
->summary
|| state
->check
|| state
->fake_ancestor
))
155 if (state
->check_index
&& is_not_gitdir
)
156 return error(_("'%s' outside a repository"), "--index");
159 return error(_("'%s' outside a repository"), "--cached");
160 state
->check_index
= 1;
162 if (state
->ita_only
&& (state
->check_index
|| is_not_gitdir
))
164 if (state
->check_index
)
165 state
->unsafe_paths
= 0;
167 if (state
->apply_verbosity
<= verbosity_silent
) {
168 state
->saved_error_routine
= get_error_routine();
169 state
->saved_warn_routine
= get_warn_routine();
170 set_error_routine(mute_routine
);
171 set_warn_routine(mute_routine
);
177 static void set_default_whitespace_mode(struct apply_state
*state
)
179 if (!state
->whitespace_option
&& !apply_default_whitespace
)
180 state
->ws_error_action
= (state
->apply
? warn_on_ws_error
: nowarn_ws_error
);
184 * This represents one "hunk" from a patch, starting with
185 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
186 * patch text is pointed at by patch, and its byte length
187 * is stored in size. leading and trailing are the number
191 unsigned long leading
, trailing
;
192 unsigned long oldpos
, oldlines
;
193 unsigned long newpos
, newlines
;
195 * 'patch' is usually borrowed from buf in apply_patch(),
196 * but some codepaths store an allocated buffer.
199 unsigned free_patch
:1,
203 struct fragment
*next
;
207 * When dealing with a binary patch, we reuse "leading" field
208 * to store the type of the binary hunk, either deflated "delta"
209 * or deflated "literal".
211 #define binary_patch_method leading
212 #define BINARY_DELTA_DEFLATED 1
213 #define BINARY_LITERAL_DEFLATED 2
215 static void free_fragment_list(struct fragment
*list
)
218 struct fragment
*next
= list
->next
;
219 if (list
->free_patch
)
220 free((char *)list
->patch
);
226 void release_patch(struct patch
*patch
)
228 free_fragment_list(patch
->fragments
);
229 free(patch
->def_name
);
230 free(patch
->old_name
);
231 free(patch
->new_name
);
235 static void free_patch(struct patch
*patch
)
237 release_patch(patch
);
241 static void free_patch_list(struct patch
*list
)
244 struct patch
*next
= list
->next
;
251 * A line in a file, len-bytes long (includes the terminating LF,
252 * except for an incomplete line at the end if the file ends with
253 * one), and its contents hashes to 'hash'.
259 #define LINE_COMMON 1
260 #define LINE_PATCHED 2
264 * This represents a "file", which is an array of "lines".
271 struct line
*line_allocated
;
275 static uint32_t hash_line(const char *cp
, size_t len
)
279 for (i
= 0, h
= 0; i
< len
; i
++) {
280 if (!isspace(cp
[i
])) {
281 h
= h
* 3 + (cp
[i
] & 0xff);
288 * Compare lines s1 of length n1 and s2 of length n2, ignoring
289 * whitespace difference. Returns 1 if they match, 0 otherwise
291 static int fuzzy_matchlines(const char *s1
, size_t n1
,
292 const char *s2
, size_t n2
)
294 const char *end1
= s1
+ n1
;
295 const char *end2
= s2
+ n2
;
297 /* ignore line endings */
298 while (s1
< end1
&& (end1
[-1] == '\r' || end1
[-1] == '\n'))
300 while (s2
< end2
&& (end2
[-1] == '\r' || end2
[-1] == '\n'))
303 while (s1
< end1
&& s2
< end2
) {
306 * Skip whitespace. We check on both buffers
307 * because we don't want "a b" to match "ab".
311 while (s1
< end1
&& isspace(*s1
))
313 while (s2
< end2
&& isspace(*s2
))
315 } else if (*s1
++ != *s2
++)
319 /* If we reached the end on one side only, lines don't match. */
320 return s1
== end1
&& s2
== end2
;
323 static void add_line_info(struct image
*img
, const char *bol
, size_t len
, unsigned flag
)
325 ALLOC_GROW(img
->line_allocated
, img
->nr
+ 1, img
->alloc
);
326 img
->line_allocated
[img
->nr
].len
= len
;
327 img
->line_allocated
[img
->nr
].hash
= hash_line(bol
, len
);
328 img
->line_allocated
[img
->nr
].flag
= flag
;
333 * "buf" has the file contents to be patched (read from various sources).
334 * attach it to "image" and add line-based index to it.
335 * "image" now owns the "buf".
337 static void prepare_image(struct image
*image
, char *buf
, size_t len
,
338 int prepare_linetable
)
342 memset(image
, 0, sizeof(*image
));
346 if (!prepare_linetable
)
349 ep
= image
->buf
+ image
->len
;
353 for (next
= cp
; next
< ep
&& *next
!= '\n'; next
++)
357 add_line_info(image
, cp
, next
- cp
, 0);
360 image
->line
= image
->line_allocated
;
363 static void clear_image(struct image
*image
)
366 free(image
->line_allocated
);
367 memset(image
, 0, sizeof(*image
));
370 /* fmt must contain _one_ %s and no other substitution */
371 static void say_patch_name(FILE *output
, const char *fmt
, struct patch
*patch
)
373 struct strbuf sb
= STRBUF_INIT
;
375 if (patch
->old_name
&& patch
->new_name
&&
376 strcmp(patch
->old_name
, patch
->new_name
)) {
377 quote_c_style(patch
->old_name
, &sb
, NULL
, 0);
378 strbuf_addstr(&sb
, " => ");
379 quote_c_style(patch
->new_name
, &sb
, NULL
, 0);
381 const char *n
= patch
->new_name
;
384 quote_c_style(n
, &sb
, NULL
, 0);
386 fprintf(output
, fmt
, sb
.buf
);
394 * apply.c isn't equipped to handle arbitrarily large patches, because
395 * it intermingles `unsigned long` with `int` for the type used to store
398 * Only process patches that are just shy of 1 GiB large in order to
399 * avoid any truncation or overflow issues.
401 #define MAX_APPLY_SIZE (1024UL * 1024 * 1023)
403 static int read_patch_file(struct strbuf
*sb
, int fd
)
405 if (strbuf_read(sb
, fd
, 0) < 0 || sb
->len
>= MAX_APPLY_SIZE
)
406 return error_errno("git apply: failed to read");
409 * Make sure that we have some slop in the buffer
410 * so that we can do speculative "memcmp" etc, and
411 * see to it that it is NUL-filled.
413 strbuf_grow(sb
, SLOP
);
414 memset(sb
->buf
+ sb
->len
, 0, SLOP
);
418 static unsigned long linelen(const char *buffer
, unsigned long size
)
420 unsigned long len
= 0;
423 if (*buffer
++ == '\n')
429 static int is_dev_null(const char *str
)
431 return skip_prefix(str
, "/dev/null", &str
) && isspace(*str
);
437 static int name_terminate(int c
, int terminate
)
439 if (c
== ' ' && !(terminate
& TERM_SPACE
))
441 if (c
== '\t' && !(terminate
& TERM_TAB
))
447 /* remove double slashes to make --index work with such filenames */
448 static char *squash_slash(char *name
)
456 if ((name
[j
++] = name
[i
++]) == '/')
457 while (name
[i
] == '/')
464 static char *find_name_gnu(struct strbuf
*root
,
468 struct strbuf name
= STRBUF_INIT
;
472 * Proposed "new-style" GNU patch/diff format; see
473 * https://lore.kernel.org/git/7vll0wvb2a.fsf@assigned-by-dhcp.cox.net/
475 if (unquote_c_style(&name
, line
, NULL
)) {
476 strbuf_release(&name
);
480 for (cp
= name
.buf
; p_value
; p_value
--) {
481 cp
= strchr(cp
, '/');
483 strbuf_release(&name
);
489 strbuf_remove(&name
, 0, cp
- name
.buf
);
491 strbuf_insert(&name
, 0, root
->buf
, root
->len
);
492 return squash_slash(strbuf_detach(&name
, NULL
));
495 static size_t sane_tz_len(const char *line
, size_t len
)
499 if (len
< strlen(" +0500") || line
[len
-strlen(" +0500")] != ' ')
501 tz
= line
+ len
- strlen(" +0500");
503 if (tz
[1] != '+' && tz
[1] != '-')
506 for (p
= tz
+ 2; p
!= line
+ len
; p
++)
510 return line
+ len
- tz
;
513 static size_t tz_with_colon_len(const char *line
, size_t len
)
517 if (len
< strlen(" +08:00") || line
[len
- strlen(":00")] != ':')
519 tz
= line
+ len
- strlen(" +08:00");
521 if (tz
[0] != ' ' || (tz
[1] != '+' && tz
[1] != '-'))
524 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
525 !isdigit(*p
++) || !isdigit(*p
++))
528 return line
+ len
- tz
;
531 static size_t date_len(const char *line
, size_t len
)
533 const char *date
, *p
;
535 if (len
< strlen("72-02-05") || line
[len
-strlen("-05")] != '-')
537 p
= date
= line
+ len
- strlen("72-02-05");
539 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
540 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
541 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a date. */
544 if (date
- line
>= strlen("19") &&
545 isdigit(date
[-1]) && isdigit(date
[-2])) /* 4-digit year */
546 date
-= strlen("19");
548 return line
+ len
- date
;
551 static size_t short_time_len(const char *line
, size_t len
)
553 const char *time
, *p
;
555 if (len
< strlen(" 07:01:32") || line
[len
-strlen(":32")] != ':')
557 p
= time
= line
+ len
- strlen(" 07:01:32");
559 /* Permit 1-digit hours? */
561 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
562 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
563 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a time. */
566 return line
+ len
- time
;
569 static size_t fractional_time_len(const char *line
, size_t len
)
574 /* Expected format: 19:41:17.620000023 */
575 if (!len
|| !isdigit(line
[len
- 1]))
579 /* Fractional seconds. */
580 while (p
> line
&& isdigit(*p
))
585 /* Hours, minutes, and whole seconds. */
586 n
= short_time_len(line
, p
- line
);
590 return line
+ len
- p
+ n
;
593 static size_t trailing_spaces_len(const char *line
, size_t len
)
597 /* Expected format: ' ' x (1 or more) */
598 if (!len
|| line
[len
- 1] != ' ')
605 return line
+ len
- (p
+ 1);
612 static size_t diff_timestamp_len(const char *line
, size_t len
)
614 const char *end
= line
+ len
;
618 * Posix: 2010-07-05 19:41:17
619 * GNU: 2010-07-05 19:41:17.620000023 -0500
622 if (!isdigit(end
[-1]))
625 n
= sane_tz_len(line
, end
- line
);
627 n
= tz_with_colon_len(line
, end
- line
);
630 n
= short_time_len(line
, end
- line
);
632 n
= fractional_time_len(line
, end
- line
);
635 n
= date_len(line
, end
- line
);
636 if (!n
) /* No date. Too bad. */
640 if (end
== line
) /* No space before date. */
642 if (end
[-1] == '\t') { /* Success! */
644 return line
+ len
- end
;
646 if (end
[-1] != ' ') /* No space before date. */
649 /* Whitespace damage. */
650 end
-= trailing_spaces_len(line
, end
- line
);
651 return line
+ len
- end
;
654 static char *find_name_common(struct strbuf
*root
,
662 const char *start
= NULL
;
666 while (line
!= end
) {
669 if (!end
&& isspace(c
)) {
672 if (name_terminate(c
, terminate
))
676 if (c
== '/' && !--p_value
)
680 return squash_slash(xstrdup_or_null(def
));
683 return squash_slash(xstrdup_or_null(def
));
686 * Generally we prefer the shorter name, especially
687 * if the other one is just a variation of that with
688 * something else tacked on to the end (ie "file.orig"
692 int deflen
= strlen(def
);
693 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
694 return squash_slash(xstrdup(def
));
698 char *ret
= xstrfmt("%s%.*s", root
->buf
, len
, start
);
699 return squash_slash(ret
);
702 return squash_slash(xmemdupz(start
, len
));
705 static char *find_name(struct strbuf
*root
,
712 char *name
= find_name_gnu(root
, line
, p_value
);
717 return find_name_common(root
, line
, def
, p_value
, NULL
, terminate
);
720 static char *find_name_traditional(struct strbuf
*root
,
729 char *name
= find_name_gnu(root
, line
, p_value
);
734 len
= strchrnul(line
, '\n') - line
;
735 date_len
= diff_timestamp_len(line
, len
);
737 return find_name_common(root
, line
, def
, p_value
, NULL
, TERM_TAB
);
740 return find_name_common(root
, line
, def
, p_value
, line
+ len
, 0);
744 * Given the string after "--- " or "+++ ", guess the appropriate
745 * p_value for the given patch.
747 static int guess_p_value(struct apply_state
*state
, const char *nameline
)
752 if (is_dev_null(nameline
))
754 name
= find_name_traditional(&state
->root
, nameline
, NULL
, 0);
757 cp
= strchr(name
, '/');
760 else if (state
->prefix
) {
762 * Does it begin with "a/$our-prefix" and such? Then this is
763 * very likely to apply to our directory.
765 if (starts_with(name
, state
->prefix
))
766 val
= count_slashes(state
->prefix
);
769 if (starts_with(cp
, state
->prefix
))
770 val
= count_slashes(state
->prefix
) + 1;
778 * Does the ---/+++ line have the POSIX timestamp after the last HT?
779 * GNU diff puts epoch there to signal a creation/deletion event. Is
780 * this such a timestamp?
782 static int has_epoch_timestamp(const char *nameline
)
785 * We are only interested in epoch timestamp; any non-zero
786 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
787 * For the same reason, the date must be either 1969-12-31 or
788 * 1970-01-01, and the seconds part must be "00".
790 const char stamp_regexp
[] =
791 "^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?"
793 "([-+][0-2][0-9]:?[0-5][0-9])\n";
794 const char *timestamp
= NULL
, *cp
, *colon
;
795 static regex_t
*stamp
;
797 int zoneoffset
, epoch_hour
, hour
, minute
;
800 for (cp
= nameline
; *cp
!= '\n'; cp
++) {
808 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
809 * (west of GMT) or 1970-01-01 (east of GMT)
811 if (skip_prefix(timestamp
, "1969-12-31 ", ×tamp
))
813 else if (skip_prefix(timestamp
, "1970-01-01 ", ×tamp
))
819 stamp
= xmalloc(sizeof(*stamp
));
820 if (regcomp(stamp
, stamp_regexp
, REG_EXTENDED
)) {
821 warning(_("Cannot prepare timestamp regexp %s"),
827 status
= regexec(stamp
, timestamp
, ARRAY_SIZE(m
), m
, 0);
829 if (status
!= REG_NOMATCH
)
830 warning(_("regexec returned %d for input: %s"),
835 hour
= strtol(timestamp
, NULL
, 10);
836 minute
= strtol(timestamp
+ m
[1].rm_so
, NULL
, 10);
838 zoneoffset
= strtol(timestamp
+ m
[3].rm_so
+ 1, (char **) &colon
, 10);
840 zoneoffset
= zoneoffset
* 60 + strtol(colon
+ 1, NULL
, 10);
842 zoneoffset
= (zoneoffset
/ 100) * 60 + (zoneoffset
% 100);
843 if (timestamp
[m
[3].rm_so
] == '-')
844 zoneoffset
= -zoneoffset
;
846 return hour
* 60 + minute
- zoneoffset
== epoch_hour
* 60;
850 * Get the name etc info from the ---/+++ lines of a traditional patch header
852 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
853 * files, we can happily check the index for a match, but for creating a
854 * new file we should try to match whatever "patch" does. I have no idea.
856 static int parse_traditional_patch(struct apply_state
*state
,
863 first
+= 4; /* skip "--- " */
864 second
+= 4; /* skip "+++ " */
865 if (!state
->p_value_known
) {
867 p
= guess_p_value(state
, first
);
868 q
= guess_p_value(state
, second
);
870 if (0 <= p
&& p
== q
) {
872 state
->p_value_known
= 1;
875 if (is_dev_null(first
)) {
877 patch
->is_delete
= 0;
878 name
= find_name_traditional(&state
->root
, second
, NULL
, state
->p_value
);
879 patch
->new_name
= name
;
880 } else if (is_dev_null(second
)) {
882 patch
->is_delete
= 1;
883 name
= find_name_traditional(&state
->root
, first
, NULL
, state
->p_value
);
884 patch
->old_name
= name
;
887 first_name
= find_name_traditional(&state
->root
, first
, NULL
, state
->p_value
);
888 name
= find_name_traditional(&state
->root
, second
, first_name
, state
->p_value
);
890 if (has_epoch_timestamp(first
)) {
892 patch
->is_delete
= 0;
893 patch
->new_name
= name
;
894 } else if (has_epoch_timestamp(second
)) {
896 patch
->is_delete
= 1;
897 patch
->old_name
= name
;
899 patch
->old_name
= name
;
900 patch
->new_name
= xstrdup_or_null(name
);
904 return error(_("unable to find filename in patch at line %d"), state
->linenr
);
909 static int gitdiff_hdrend(struct gitdiff_data
*state UNUSED
,
910 const char *line UNUSED
,
911 struct patch
*patch UNUSED
)
917 * We're anal about diff header consistency, to make
918 * sure that we don't end up having strange ambiguous
919 * patches floating around.
921 * As a result, gitdiff_{old|new}name() will check
922 * their names against any previous information, just
925 #define DIFF_OLD_NAME 0
926 #define DIFF_NEW_NAME 1
928 static int gitdiff_verify_name(struct gitdiff_data
*state
,
934 if (!*name
&& !isnull
) {
935 *name
= find_name(state
->root
, line
, NULL
, state
->p_value
, TERM_TAB
);
942 return error(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
943 *name
, state
->linenr
);
944 another
= find_name(state
->root
, line
, NULL
, state
->p_value
, TERM_TAB
);
945 if (!another
|| strcmp(another
, *name
)) {
947 return error((side
== DIFF_NEW_NAME
) ?
948 _("git apply: bad git-diff - inconsistent new filename on line %d") :
949 _("git apply: bad git-diff - inconsistent old filename on line %d"), state
->linenr
);
953 if (!is_dev_null(line
))
954 return error(_("git apply: bad git-diff - expected /dev/null on line %d"), state
->linenr
);
960 static int gitdiff_oldname(struct gitdiff_data
*state
,
964 return gitdiff_verify_name(state
, line
,
965 patch
->is_new
, &patch
->old_name
,
969 static int gitdiff_newname(struct gitdiff_data
*state
,
973 return gitdiff_verify_name(state
, line
,
974 patch
->is_delete
, &patch
->new_name
,
978 static int parse_mode_line(const char *line
, int linenr
, unsigned int *mode
)
981 *mode
= strtoul(line
, &end
, 8);
982 if (end
== line
|| !isspace(*end
))
983 return error(_("invalid mode on line %d: %s"), linenr
, line
);
987 static int gitdiff_oldmode(struct gitdiff_data
*state
,
991 return parse_mode_line(line
, state
->linenr
, &patch
->old_mode
);
994 static int gitdiff_newmode(struct gitdiff_data
*state
,
998 return parse_mode_line(line
, state
->linenr
, &patch
->new_mode
);
1001 static int gitdiff_delete(struct gitdiff_data
*state
,
1003 struct patch
*patch
)
1005 patch
->is_delete
= 1;
1006 free(patch
->old_name
);
1007 patch
->old_name
= xstrdup_or_null(patch
->def_name
);
1008 return gitdiff_oldmode(state
, line
, patch
);
1011 static int gitdiff_newfile(struct gitdiff_data
*state
,
1013 struct patch
*patch
)
1016 free(patch
->new_name
);
1017 patch
->new_name
= xstrdup_or_null(patch
->def_name
);
1018 return gitdiff_newmode(state
, line
, patch
);
1021 static int gitdiff_copysrc(struct gitdiff_data
*state
,
1023 struct patch
*patch
)
1026 free(patch
->old_name
);
1027 patch
->old_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1031 static int gitdiff_copydst(struct gitdiff_data
*state
,
1033 struct patch
*patch
)
1036 free(patch
->new_name
);
1037 patch
->new_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1041 static int gitdiff_renamesrc(struct gitdiff_data
*state
,
1043 struct patch
*patch
)
1045 patch
->is_rename
= 1;
1046 free(patch
->old_name
);
1047 patch
->old_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1051 static int gitdiff_renamedst(struct gitdiff_data
*state
,
1053 struct patch
*patch
)
1055 patch
->is_rename
= 1;
1056 free(patch
->new_name
);
1057 patch
->new_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1061 static int gitdiff_similarity(struct gitdiff_data
*state UNUSED
,
1063 struct patch
*patch
)
1065 unsigned long val
= strtoul(line
, NULL
, 10);
1071 static int gitdiff_dissimilarity(struct gitdiff_data
*state UNUSED
,
1073 struct patch
*patch
)
1075 unsigned long val
= strtoul(line
, NULL
, 10);
1081 static int gitdiff_index(struct gitdiff_data
*state
,
1083 struct patch
*patch
)
1086 * index line is N hexadecimal, "..", N hexadecimal,
1087 * and optional space with octal mode.
1089 const char *ptr
, *eol
;
1091 const unsigned hexsz
= the_hash_algo
->hexsz
;
1093 ptr
= strchr(line
, '.');
1094 if (!ptr
|| ptr
[1] != '.' || hexsz
< ptr
- line
)
1097 memcpy(patch
->old_oid_prefix
, line
, len
);
1098 patch
->old_oid_prefix
[len
] = 0;
1101 ptr
= strchr(line
, ' ');
1102 eol
= strchrnul(line
, '\n');
1104 if (!ptr
|| eol
< ptr
)
1110 memcpy(patch
->new_oid_prefix
, line
, len
);
1111 patch
->new_oid_prefix
[len
] = 0;
1113 return gitdiff_oldmode(state
, ptr
+ 1, patch
);
1118 * This is normal for a diff that doesn't change anything: we'll fall through
1119 * into the next diff. Tell the parser to break out.
1121 static int gitdiff_unrecognized(struct gitdiff_data
*state UNUSED
,
1122 const char *line UNUSED
,
1123 struct patch
*patch UNUSED
)
1129 * Skip p_value leading components from "line"; as we do not accept
1130 * absolute paths, return NULL in that case.
1132 static const char *skip_tree_prefix(int p_value
,
1140 return (llen
&& line
[0] == '/') ? NULL
: line
;
1143 for (i
= 0; i
< llen
; i
++) {
1145 if (ch
== '/' && --nslash
<= 0)
1146 return (i
== 0) ? NULL
: &line
[i
+ 1];
1152 * This is to extract the same name that appears on "diff --git"
1153 * line. We do not find and return anything if it is a rename
1154 * patch, and it is OK because we will find the name elsewhere.
1155 * We need to reliably find name only when it is mode-change only,
1156 * creation or deletion of an empty file. In any of these cases,
1157 * both sides are the same name under a/ and b/ respectively.
1159 static char *git_header_name(int p_value
,
1164 const char *second
= NULL
;
1165 size_t len
, line_len
;
1167 line
+= strlen("diff --git ");
1168 llen
-= strlen("diff --git ");
1172 struct strbuf first
= STRBUF_INIT
;
1173 struct strbuf sp
= STRBUF_INIT
;
1175 if (unquote_c_style(&first
, line
, &second
))
1176 goto free_and_fail1
;
1178 /* strip the a/b prefix including trailing slash */
1179 cp
= skip_tree_prefix(p_value
, first
.buf
, first
.len
);
1181 goto free_and_fail1
;
1182 strbuf_remove(&first
, 0, cp
- first
.buf
);
1185 * second points at one past closing dq of name.
1186 * find the second name.
1188 while ((second
< line
+ llen
) && isspace(*second
))
1191 if (line
+ llen
<= second
)
1192 goto free_and_fail1
;
1193 if (*second
== '"') {
1194 if (unquote_c_style(&sp
, second
, NULL
))
1195 goto free_and_fail1
;
1196 cp
= skip_tree_prefix(p_value
, sp
.buf
, sp
.len
);
1198 goto free_and_fail1
;
1199 /* They must match, otherwise ignore */
1200 if (strcmp(cp
, first
.buf
))
1201 goto free_and_fail1
;
1202 strbuf_release(&sp
);
1203 return strbuf_detach(&first
, NULL
);
1206 /* unquoted second */
1207 cp
= skip_tree_prefix(p_value
, second
, line
+ llen
- second
);
1209 goto free_and_fail1
;
1210 if (line
+ llen
- cp
!= first
.len
||
1211 memcmp(first
.buf
, cp
, first
.len
))
1212 goto free_and_fail1
;
1213 return strbuf_detach(&first
, NULL
);
1216 strbuf_release(&first
);
1217 strbuf_release(&sp
);
1221 /* unquoted first name */
1222 name
= skip_tree_prefix(p_value
, line
, llen
);
1227 * since the first name is unquoted, a dq if exists must be
1228 * the beginning of the second name.
1230 for (second
= name
; second
< line
+ llen
; second
++) {
1231 if (*second
== '"') {
1232 struct strbuf sp
= STRBUF_INIT
;
1235 if (unquote_c_style(&sp
, second
, NULL
))
1236 goto free_and_fail2
;
1238 np
= skip_tree_prefix(p_value
, sp
.buf
, sp
.len
);
1240 goto free_and_fail2
;
1242 len
= sp
.buf
+ sp
.len
- np
;
1243 if (len
< second
- name
&&
1244 !strncmp(np
, name
, len
) &&
1245 isspace(name
[len
])) {
1247 strbuf_remove(&sp
, 0, np
- sp
.buf
);
1248 return strbuf_detach(&sp
, NULL
);
1252 strbuf_release(&sp
);
1258 * Accept a name only if it shows up twice, exactly the same
1261 second
= strchr(name
, '\n');
1264 line_len
= second
- name
;
1265 for (len
= 0 ; ; len
++) {
1266 switch (name
[len
]) {
1271 case '\t': case ' ':
1273 * Is this the separator between the preimage
1274 * and the postimage pathname? Again, we are
1275 * only interested in the case where there is
1276 * no rename, as this is only to set def_name
1277 * and a rename patch has the names elsewhere
1278 * in an unambiguous form.
1281 return NULL
; /* no postimage name */
1282 second
= skip_tree_prefix(p_value
, name
+ len
+ 1,
1283 line_len
- (len
+ 1));
1287 * Does len bytes starting at "name" and "second"
1288 * (that are separated by one HT or SP we just
1289 * found) exactly match?
1291 if (second
[len
] == '\n' && !strncmp(name
, second
, len
))
1292 return xmemdupz(name
, len
);
1297 static int check_header_line(int linenr
, struct patch
*patch
)
1299 int extensions
= (patch
->is_delete
== 1) + (patch
->is_new
== 1) +
1300 (patch
->is_rename
== 1) + (patch
->is_copy
== 1);
1302 return error(_("inconsistent header lines %d and %d"),
1303 patch
->extension_linenr
, linenr
);
1304 if (extensions
&& !patch
->extension_linenr
)
1305 patch
->extension_linenr
= linenr
;
1309 int parse_git_diff_header(struct strbuf
*root
,
1315 struct patch
*patch
)
1317 unsigned long offset
;
1318 struct gitdiff_data parse_hdr_state
;
1320 /* A git diff has explicit new/delete information, so we don't guess */
1322 patch
->is_delete
= 0;
1325 * Some things may not have the old name in the
1326 * rest of the headers anywhere (pure mode changes,
1327 * or removing or adding empty files), so we get
1328 * the default name from the header.
1330 patch
->def_name
= git_header_name(p_value
, line
, len
);
1331 if (patch
->def_name
&& root
->len
) {
1332 char *s
= xstrfmt("%s%s", root
->buf
, patch
->def_name
);
1333 free(patch
->def_name
);
1334 patch
->def_name
= s
;
1340 parse_hdr_state
.root
= root
;
1341 parse_hdr_state
.linenr
= *linenr
;
1342 parse_hdr_state
.p_value
= p_value
;
1344 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, (*linenr
)++) {
1345 static const struct opentry
{
1347 int (*fn
)(struct gitdiff_data
*, const char *, struct patch
*);
1349 { "@@ -", gitdiff_hdrend
},
1350 { "--- ", gitdiff_oldname
},
1351 { "+++ ", gitdiff_newname
},
1352 { "old mode ", gitdiff_oldmode
},
1353 { "new mode ", gitdiff_newmode
},
1354 { "deleted file mode ", gitdiff_delete
},
1355 { "new file mode ", gitdiff_newfile
},
1356 { "copy from ", gitdiff_copysrc
},
1357 { "copy to ", gitdiff_copydst
},
1358 { "rename old ", gitdiff_renamesrc
},
1359 { "rename new ", gitdiff_renamedst
},
1360 { "rename from ", gitdiff_renamesrc
},
1361 { "rename to ", gitdiff_renamedst
},
1362 { "similarity index ", gitdiff_similarity
},
1363 { "dissimilarity index ", gitdiff_dissimilarity
},
1364 { "index ", gitdiff_index
},
1365 { "", gitdiff_unrecognized
},
1369 len
= linelen(line
, size
);
1370 if (!len
|| line
[len
-1] != '\n')
1372 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
1373 const struct opentry
*p
= optable
+ i
;
1374 int oplen
= strlen(p
->str
);
1376 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
1378 res
= p
->fn(&parse_hdr_state
, line
+ oplen
, patch
);
1381 if (check_header_line(*linenr
, patch
))
1390 if (!patch
->old_name
&& !patch
->new_name
) {
1391 if (!patch
->def_name
) {
1392 error(Q_("git diff header lacks filename information when removing "
1393 "%d leading pathname component (line %d)",
1394 "git diff header lacks filename information when removing "
1395 "%d leading pathname components (line %d)",
1396 parse_hdr_state
.p_value
),
1397 parse_hdr_state
.p_value
, *linenr
);
1400 patch
->old_name
= xstrdup(patch
->def_name
);
1401 patch
->new_name
= xstrdup(patch
->def_name
);
1403 if ((!patch
->new_name
&& !patch
->is_delete
) ||
1404 (!patch
->old_name
&& !patch
->is_new
)) {
1405 error(_("git diff header lacks filename information "
1406 "(line %d)"), *linenr
);
1409 patch
->is_toplevel_relative
= 1;
1413 static int parse_num(const char *line
, unsigned long *p
)
1417 if (!isdigit(*line
))
1419 *p
= strtoul(line
, &ptr
, 10);
1423 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
1424 unsigned long *p1
, unsigned long *p2
)
1428 if (offset
< 0 || offset
>= len
)
1433 digits
= parse_num(line
, p1
);
1443 digits
= parse_num(line
+1, p2
);
1452 ex
= strlen(expect
);
1455 if (memcmp(line
, expect
, ex
))
1461 static void recount_diff(const char *line
, int size
, struct fragment
*fragment
)
1463 int oldlines
= 0, newlines
= 0, ret
= 0;
1466 warning("recount: ignore empty hunk");
1471 int len
= linelen(line
, size
);
1479 case ' ': case '\n':
1491 ret
= size
< 3 || !starts_with(line
, "@@ ");
1494 ret
= size
< 5 || !starts_with(line
, "diff ");
1501 warning(_("recount: unexpected line: %.*s"),
1502 (int)linelen(line
, size
), line
);
1507 fragment
->oldlines
= oldlines
;
1508 fragment
->newlines
= newlines
;
1512 * Parse a unified diff fragment header of the
1513 * form "@@ -a,b +c,d @@"
1515 static int parse_fragment_header(const char *line
, int len
, struct fragment
*fragment
)
1519 if (!len
|| line
[len
-1] != '\n')
1522 /* Figure out the number of lines in a fragment */
1523 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
1524 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
1530 * Find file diff header
1533 * -1 if no header was found
1534 * -128 in case of error
1535 * the size of the header in bytes (called "offset") otherwise
1537 static int find_header(struct apply_state
*state
,
1541 struct patch
*patch
)
1543 unsigned long offset
, len
;
1545 patch
->is_toplevel_relative
= 0;
1546 patch
->is_rename
= patch
->is_copy
= 0;
1547 patch
->is_new
= patch
->is_delete
= -1;
1548 patch
->old_mode
= patch
->new_mode
= 0;
1549 patch
->old_name
= patch
->new_name
= NULL
;
1550 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1551 unsigned long nextlen
;
1553 len
= linelen(line
, size
);
1557 /* Testing this early allows us to take a few shortcuts.. */
1562 * Make sure we don't find any unconnected patch fragments.
1563 * That's a sign that we didn't find a header, and that a
1564 * patch has become corrupted/broken up.
1566 if (!memcmp("@@ -", line
, 4)) {
1567 struct fragment dummy
;
1568 if (parse_fragment_header(line
, len
, &dummy
) < 0)
1570 error(_("patch fragment without header at line %d: %.*s"),
1571 state
->linenr
, (int)len
-1, line
);
1579 * Git patch? It might not have a real patch, just a rename
1580 * or mode change, so we handle that specially
1582 if (!memcmp("diff --git ", line
, 11)) {
1583 int git_hdr_len
= parse_git_diff_header(&state
->root
, &state
->linenr
,
1584 state
->p_value
, line
, len
,
1586 if (git_hdr_len
< 0)
1588 if (git_hdr_len
<= len
)
1590 *hdrsize
= git_hdr_len
;
1594 /* --- followed by +++ ? */
1595 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
1599 * We only accept unified patches, so we want it to
1600 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1601 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1603 nextlen
= linelen(line
+ len
, size
- len
);
1604 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
1607 /* Ok, we'll consider it a patch */
1608 if (parse_traditional_patch(state
, line
, line
+len
, patch
))
1610 *hdrsize
= len
+ nextlen
;
1617 static void record_ws_error(struct apply_state
*state
,
1628 state
->whitespace_error
++;
1629 if (state
->squelch_whitespace_errors
&&
1630 state
->squelch_whitespace_errors
< state
->whitespace_error
)
1633 err
= whitespace_error_string(result
);
1634 if (state
->apply_verbosity
> verbosity_silent
)
1635 fprintf(stderr
, "%s:%d: %s.\n%.*s\n",
1636 state
->patch_input_file
, linenr
, err
, len
, line
);
1640 static void check_whitespace(struct apply_state
*state
,
1645 unsigned result
= ws_check(line
+ 1, len
- 1, ws_rule
);
1647 record_ws_error(state
, result
, line
+ 1, len
- 2, state
->linenr
);
1651 * Check if the patch has context lines with CRLF or
1652 * the patch wants to remove lines with CRLF.
1654 static void check_old_for_crlf(struct patch
*patch
, const char *line
, int len
)
1656 if (len
>= 2 && line
[len
-1] == '\n' && line
[len
-2] == '\r') {
1657 patch
->ws_rule
|= WS_CR_AT_EOL
;
1658 patch
->crlf_in_old
= 1;
1664 * Parse a unified diff. Note that this really needs to parse each
1665 * fragment separately, since the only way to know the difference
1666 * between a "---" that is part of a patch, and a "---" that starts
1667 * the next patch is to look at the line counts..
1669 static int parse_fragment(struct apply_state
*state
,
1672 struct patch
*patch
,
1673 struct fragment
*fragment
)
1676 int len
= linelen(line
, size
), offset
;
1677 unsigned long oldlines
, newlines
;
1678 unsigned long leading
, trailing
;
1680 offset
= parse_fragment_header(line
, len
, fragment
);
1683 if (offset
> 0 && patch
->recount
)
1684 recount_diff(line
+ offset
, size
- offset
, fragment
);
1685 oldlines
= fragment
->oldlines
;
1686 newlines
= fragment
->newlines
;
1690 /* Parse the thing.. */
1694 added
= deleted
= 0;
1697 offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1698 if (!oldlines
&& !newlines
)
1700 len
= linelen(line
, size
);
1701 if (!len
|| line
[len
-1] != '\n')
1706 case '\n': /* newer GNU diff, an empty context line */
1710 if (!deleted
&& !added
)
1713 check_old_for_crlf(patch
, line
, len
);
1714 if (!state
->apply_in_reverse
&&
1715 state
->ws_error_action
== correct_ws_error
)
1716 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1719 if (!state
->apply_in_reverse
)
1720 check_old_for_crlf(patch
, line
, len
);
1721 if (state
->apply_in_reverse
&&
1722 state
->ws_error_action
!= nowarn_ws_error
)
1723 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1729 if (state
->apply_in_reverse
)
1730 check_old_for_crlf(patch
, line
, len
);
1731 if (!state
->apply_in_reverse
&&
1732 state
->ws_error_action
!= nowarn_ws_error
)
1733 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1740 * We allow "\ No newline at end of file". Depending
1741 * on locale settings when the patch was produced we
1742 * don't know what this line looks like. The only
1743 * thing we do know is that it begins with "\ ".
1744 * Checking for 12 is just for sanity check -- any
1745 * l10n of "\ No newline..." is at least that long.
1748 if (len
< 12 || memcmp(line
, "\\ ", 2))
1753 if (oldlines
|| newlines
)
1755 if (!patch
->recount
&& !deleted
&& !added
)
1758 fragment
->leading
= leading
;
1759 fragment
->trailing
= trailing
;
1762 * If a fragment ends with an incomplete line, we failed to include
1763 * it in the above loop because we hit oldlines == newlines == 0
1766 if (12 < size
&& !memcmp(line
, "\\ ", 2))
1767 offset
+= linelen(line
, size
);
1769 patch
->lines_added
+= added
;
1770 patch
->lines_deleted
+= deleted
;
1772 if (0 < patch
->is_new
&& oldlines
)
1773 return error(_("new file depends on old contents"));
1774 if (0 < patch
->is_delete
&& newlines
)
1775 return error(_("deleted file still has contents"));
1780 * We have seen "diff --git a/... b/..." header (or a traditional patch
1781 * header). Read hunks that belong to this patch into fragments and hang
1782 * them to the given patch structure.
1784 * The (fragment->patch, fragment->size) pair points into the memory given
1785 * by the caller, not a copy, when we return.
1788 * -1 in case of error,
1789 * the number of bytes in the patch otherwise.
1791 static int parse_single_patch(struct apply_state
*state
,
1794 struct patch
*patch
)
1796 unsigned long offset
= 0;
1797 unsigned long oldlines
= 0, newlines
= 0, context
= 0;
1798 struct fragment
**fragp
= &patch
->fragments
;
1800 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
1801 struct fragment
*fragment
;
1804 CALLOC_ARRAY(fragment
, 1);
1805 fragment
->linenr
= state
->linenr
;
1806 len
= parse_fragment(state
, line
, size
, patch
, fragment
);
1809 return error(_("corrupt patch at line %d"), state
->linenr
);
1811 fragment
->patch
= line
;
1812 fragment
->size
= len
;
1813 oldlines
+= fragment
->oldlines
;
1814 newlines
+= fragment
->newlines
;
1815 context
+= fragment
->leading
+ fragment
->trailing
;
1818 fragp
= &fragment
->next
;
1826 * If something was removed (i.e. we have old-lines) it cannot
1827 * be creation, and if something was added it cannot be
1828 * deletion. However, the reverse is not true; --unified=0
1829 * patches that only add are not necessarily creation even
1830 * though they do not have any old lines, and ones that only
1831 * delete are not necessarily deletion.
1833 * Unfortunately, a real creation/deletion patch do _not_ have
1834 * any context line by definition, so we cannot safely tell it
1835 * apart with --unified=0 insanity. At least if the patch has
1836 * more than one hunk it is not creation or deletion.
1838 if (patch
->is_new
< 0 &&
1839 (oldlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1841 if (patch
->is_delete
< 0 &&
1842 (newlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1843 patch
->is_delete
= 0;
1845 if (0 < patch
->is_new
&& oldlines
)
1846 return error(_("new file %s depends on old contents"), patch
->new_name
);
1847 if (0 < patch
->is_delete
&& newlines
)
1848 return error(_("deleted file %s still has contents"), patch
->old_name
);
1849 if (!patch
->is_delete
&& !newlines
&& context
&& state
->apply_verbosity
> verbosity_silent
)
1852 "file %s becomes empty but is not deleted"),
1858 static inline int metadata_changes(struct patch
*patch
)
1860 return patch
->is_rename
> 0 ||
1861 patch
->is_copy
> 0 ||
1862 patch
->is_new
> 0 ||
1864 (patch
->old_mode
&& patch
->new_mode
&&
1865 patch
->old_mode
!= patch
->new_mode
);
1868 static char *inflate_it(const void *data
, unsigned long size
,
1869 unsigned long inflated_size
)
1875 memset(&stream
, 0, sizeof(stream
));
1877 stream
.next_in
= (unsigned char *)data
;
1878 stream
.avail_in
= size
;
1879 stream
.next_out
= out
= xmalloc(inflated_size
);
1880 stream
.avail_out
= inflated_size
;
1881 git_inflate_init(&stream
);
1882 st
= git_inflate(&stream
, Z_FINISH
);
1883 git_inflate_end(&stream
);
1884 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1892 * Read a binary hunk and return a new fragment; fragment->patch
1893 * points at an allocated memory that the caller must free, so
1894 * it is marked as "->free_patch = 1".
1896 static struct fragment
*parse_binary_hunk(struct apply_state
*state
,
1898 unsigned long *sz_p
,
1903 * Expect a line that begins with binary patch method ("literal"
1904 * or "delta"), followed by the length of data before deflating.
1905 * a sequence of 'length-byte' followed by base-85 encoded data
1906 * should follow, terminated by a newline.
1908 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1909 * and we would limit the patch line to 66 characters,
1910 * so one line can fit up to 13 groups that would decode
1911 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1912 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1915 unsigned long size
= *sz_p
;
1916 char *buffer
= *buf_p
;
1918 unsigned long origlen
;
1921 struct fragment
*frag
;
1923 llen
= linelen(buffer
, size
);
1928 if (starts_with(buffer
, "delta ")) {
1929 patch_method
= BINARY_DELTA_DEFLATED
;
1930 origlen
= strtoul(buffer
+ 6, NULL
, 10);
1932 else if (starts_with(buffer
, "literal ")) {
1933 patch_method
= BINARY_LITERAL_DEFLATED
;
1934 origlen
= strtoul(buffer
+ 8, NULL
, 10);
1943 int byte_length
, max_byte_length
, newsize
;
1944 llen
= linelen(buffer
, size
);
1948 /* consume the blank line */
1954 * Minimum line is "A00000\n" which is 7-byte long,
1955 * and the line length must be multiple of 5 plus 2.
1957 if ((llen
< 7) || (llen
-2) % 5)
1959 max_byte_length
= (llen
- 2) / 5 * 4;
1960 byte_length
= *buffer
;
1961 if ('A' <= byte_length
&& byte_length
<= 'Z')
1962 byte_length
= byte_length
- 'A' + 1;
1963 else if ('a' <= byte_length
&& byte_length
<= 'z')
1964 byte_length
= byte_length
- 'a' + 27;
1967 /* if the input length was not multiple of 4, we would
1968 * have filler at the end but the filler should never
1971 if (max_byte_length
< byte_length
||
1972 byte_length
<= max_byte_length
- 4)
1974 newsize
= hunk_size
+ byte_length
;
1975 data
= xrealloc(data
, newsize
);
1976 if (decode_85(data
+ hunk_size
, buffer
+ 1, byte_length
))
1978 hunk_size
= newsize
;
1983 CALLOC_ARRAY(frag
, 1);
1984 frag
->patch
= inflate_it(data
, hunk_size
, origlen
);
1985 frag
->free_patch
= 1;
1989 frag
->size
= origlen
;
1993 frag
->binary_patch_method
= patch_method
;
1999 error(_("corrupt binary patch at line %d: %.*s"),
2000 state
->linenr
-1, llen
-1, buffer
);
2006 * -1 in case of error,
2007 * the length of the parsed binary patch otherwise
2009 static int parse_binary(struct apply_state
*state
,
2012 struct patch
*patch
)
2015 * We have read "GIT binary patch\n"; what follows is a line
2016 * that says the patch method (currently, either "literal" or
2017 * "delta") and the length of data before deflating; a
2018 * sequence of 'length-byte' followed by base-85 encoded data
2021 * When a binary patch is reversible, there is another binary
2022 * hunk in the same format, starting with patch method (either
2023 * "literal" or "delta") with the length of data, and a sequence
2024 * of length-byte + base-85 encoded data, terminated with another
2025 * empty line. This data, when applied to the postimage, produces
2028 struct fragment
*forward
;
2029 struct fragment
*reverse
;
2033 forward
= parse_binary_hunk(state
, &buffer
, &size
, &status
, &used
);
2034 if (!forward
&& !status
)
2035 /* there has to be one hunk (forward hunk) */
2036 return error(_("unrecognized binary patch at line %d"), state
->linenr
-1);
2038 /* otherwise we already gave an error message */
2041 reverse
= parse_binary_hunk(state
, &buffer
, &size
, &status
, &used_1
);
2046 * Not having reverse hunk is not an error, but having
2047 * a corrupt reverse hunk is.
2049 free((void*) forward
->patch
);
2053 forward
->next
= reverse
;
2054 patch
->fragments
= forward
;
2055 patch
->is_binary
= 1;
2059 static void prefix_one(struct apply_state
*state
, char **name
)
2061 char *old_name
= *name
;
2064 *name
= prefix_filename(state
->prefix
, *name
);
2068 static void prefix_patch(struct apply_state
*state
, struct patch
*p
)
2070 if (!state
->prefix
|| p
->is_toplevel_relative
)
2072 prefix_one(state
, &p
->new_name
);
2073 prefix_one(state
, &p
->old_name
);
2080 static void add_name_limit(struct apply_state
*state
,
2084 struct string_list_item
*it
;
2086 it
= string_list_append(&state
->limit_by_name
, name
);
2087 it
->util
= exclude
? NULL
: (void *) 1;
2090 static int use_patch(struct apply_state
*state
, struct patch
*p
)
2092 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
2095 /* Paths outside are not touched regardless of "--include" */
2096 if (state
->prefix
&& *state
->prefix
) {
2098 if (!skip_prefix(pathname
, state
->prefix
, &rest
) || !*rest
)
2102 /* See if it matches any of exclude/include rule */
2103 for (i
= 0; i
< state
->limit_by_name
.nr
; i
++) {
2104 struct string_list_item
*it
= &state
->limit_by_name
.items
[i
];
2105 if (!wildmatch(it
->string
, pathname
, 0))
2106 return (it
->util
!= NULL
);
2110 * If we had any include, a path that does not match any rule is
2111 * not used. Otherwise, we saw bunch of exclude rules (or none)
2112 * and such a path is used.
2114 return !state
->has_include
;
2118 * Read the patch text in "buffer" that extends for "size" bytes; stop
2119 * reading after seeing a single patch (i.e. changes to a single file).
2120 * Create fragments (i.e. patch hunks) and hang them to the given patch.
2123 * -1 if no header was found or parse_binary() failed,
2124 * -128 on another error,
2125 * the number of bytes consumed otherwise,
2126 * so that the caller can call us again for the next patch.
2128 static int parse_chunk(struct apply_state
*state
, char *buffer
, unsigned long size
, struct patch
*patch
)
2130 int hdrsize
, patchsize
;
2131 int offset
= find_header(state
, buffer
, size
, &hdrsize
, patch
);
2136 prefix_patch(state
, patch
);
2138 if (!use_patch(state
, patch
))
2140 else if (patch
->new_name
)
2141 patch
->ws_rule
= whitespace_rule(state
->repo
->index
,
2144 patch
->ws_rule
= whitespace_rule(state
->repo
->index
,
2147 patchsize
= parse_single_patch(state
,
2148 buffer
+ offset
+ hdrsize
,
2149 size
- offset
- hdrsize
,
2156 static const char git_binary
[] = "GIT binary patch\n";
2157 int hd
= hdrsize
+ offset
;
2158 unsigned long llen
= linelen(buffer
+ hd
, size
- hd
);
2160 if (llen
== sizeof(git_binary
) - 1 &&
2161 !memcmp(git_binary
, buffer
+ hd
, llen
)) {
2164 used
= parse_binary(state
, buffer
+ hd
+ llen
,
2165 size
- hd
- llen
, patch
);
2169 patchsize
= used
+ llen
;
2173 else if (!memcmp(" differ\n", buffer
+ hd
+ llen
- 8, 8)) {
2174 static const char *binhdr
[] = {
2180 for (i
= 0; binhdr
[i
]; i
++) {
2181 int len
= strlen(binhdr
[i
]);
2182 if (len
< size
- hd
&&
2183 !memcmp(binhdr
[i
], buffer
+ hd
, len
)) {
2185 patch
->is_binary
= 1;
2192 /* Empty patch cannot be applied if it is a text patch
2193 * without metadata change. A binary patch appears
2196 if ((state
->apply
|| state
->check
) &&
2197 (!patch
->is_binary
&& !metadata_changes(patch
))) {
2198 error(_("patch with only garbage at line %d"), state
->linenr
);
2203 return offset
+ hdrsize
+ patchsize
;
2206 static void reverse_patches(struct patch
*p
)
2208 for (; p
; p
= p
->next
) {
2209 struct fragment
*frag
= p
->fragments
;
2211 SWAP(p
->new_name
, p
->old_name
);
2212 SWAP(p
->new_mode
, p
->old_mode
);
2213 SWAP(p
->is_new
, p
->is_delete
);
2214 SWAP(p
->lines_added
, p
->lines_deleted
);
2215 SWAP(p
->old_oid_prefix
, p
->new_oid_prefix
);
2217 for (; frag
; frag
= frag
->next
) {
2218 SWAP(frag
->newpos
, frag
->oldpos
);
2219 SWAP(frag
->newlines
, frag
->oldlines
);
2224 static const char pluses
[] =
2225 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2226 static const char minuses
[]=
2227 "----------------------------------------------------------------------";
2229 static void show_stats(struct apply_state
*state
, struct patch
*patch
)
2231 struct strbuf qname
= STRBUF_INIT
;
2232 char *cp
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
2235 quote_c_style(cp
, &qname
, NULL
, 0);
2238 * "scale" the filename
2240 max
= state
->max_len
;
2244 if (qname
.len
> max
) {
2245 cp
= strchr(qname
.buf
+ qname
.len
+ 3 - max
, '/');
2247 cp
= qname
.buf
+ qname
.len
+ 3 - max
;
2248 strbuf_splice(&qname
, 0, cp
- qname
.buf
, "...", 3);
2251 if (patch
->is_binary
) {
2252 printf(" %-*s | Bin\n", max
, qname
.buf
);
2253 strbuf_release(&qname
);
2257 printf(" %-*s |", max
, qname
.buf
);
2258 strbuf_release(&qname
);
2261 * scale the add/delete
2263 max
= max
+ state
->max_change
> 70 ? 70 - max
: state
->max_change
;
2264 add
= patch
->lines_added
;
2265 del
= patch
->lines_deleted
;
2267 if (state
->max_change
> 0) {
2268 int total
= ((add
+ del
) * max
+ state
->max_change
/ 2) / state
->max_change
;
2269 add
= (add
* max
+ state
->max_change
/ 2) / state
->max_change
;
2272 printf("%5d %.*s%.*s\n", patch
->lines_added
+ patch
->lines_deleted
,
2273 add
, pluses
, del
, minuses
);
2276 static int read_old_data(struct stat
*st
, struct patch
*patch
,
2277 const char *path
, struct strbuf
*buf
)
2279 int conv_flags
= patch
->crlf_in_old
?
2280 CONV_EOL_KEEP_CRLF
: CONV_EOL_RENORMALIZE
;
2281 switch (st
->st_mode
& S_IFMT
) {
2283 if (strbuf_readlink(buf
, path
, st
->st_size
) < 0)
2284 return error(_("unable to read symlink %s"), path
);
2287 if (strbuf_read_file(buf
, path
, st
->st_size
) != st
->st_size
)
2288 return error(_("unable to open or read %s"), path
);
2290 * "git apply" without "--index/--cached" should never look
2291 * at the index; the target file may not have been added to
2292 * the index yet, and we may not even be in any Git repository.
2293 * Pass NULL to convert_to_git() to stress this; the function
2294 * should never look at the index when explicit crlf option
2297 convert_to_git(NULL
, path
, buf
->buf
, buf
->len
, buf
, conv_flags
);
2305 * Update the preimage, and the common lines in postimage,
2306 * from buffer buf of length len. If postlen is 0 the postimage
2307 * is updated in place, otherwise it's updated on a new buffer
2311 static void update_pre_post_images(struct image
*preimage
,
2312 struct image
*postimage
,
2314 size_t len
, size_t postlen
)
2316 int i
, ctx
, reduced
;
2317 char *new_buf
, *old_buf
, *fixed
;
2318 struct image fixed_preimage
;
2321 * Update the preimage with whitespace fixes. Note that we
2322 * are not losing preimage->buf -- apply_one_fragment() will
2325 prepare_image(&fixed_preimage
, buf
, len
, 1);
2327 ? fixed_preimage
.nr
== preimage
->nr
2328 : fixed_preimage
.nr
<= preimage
->nr
);
2329 for (i
= 0; i
< fixed_preimage
.nr
; i
++)
2330 fixed_preimage
.line
[i
].flag
= preimage
->line
[i
].flag
;
2331 free(preimage
->line_allocated
);
2332 *preimage
= fixed_preimage
;
2335 * Adjust the common context lines in postimage. This can be
2336 * done in-place when we are shrinking it with whitespace
2337 * fixing, but needs a new buffer when ignoring whitespace or
2338 * expanding leading tabs to spaces.
2340 * We trust the caller to tell us if the update can be done
2341 * in place (postlen==0) or not.
2343 old_buf
= postimage
->buf
;
2345 new_buf
= postimage
->buf
= xmalloc(postlen
);
2348 fixed
= preimage
->buf
;
2350 for (i
= reduced
= ctx
= 0; i
< postimage
->nr
; i
++) {
2351 size_t l_len
= postimage
->line
[i
].len
;
2352 if (!(postimage
->line
[i
].flag
& LINE_COMMON
)) {
2353 /* an added line -- no counterparts in preimage */
2354 memmove(new_buf
, old_buf
, l_len
);
2360 /* a common context -- skip it in the original postimage */
2363 /* and find the corresponding one in the fixed preimage */
2364 while (ctx
< preimage
->nr
&&
2365 !(preimage
->line
[ctx
].flag
& LINE_COMMON
)) {
2366 fixed
+= preimage
->line
[ctx
].len
;
2371 * preimage is expected to run out, if the caller
2372 * fixed addition of trailing blank lines.
2374 if (preimage
->nr
<= ctx
) {
2379 /* and copy it in, while fixing the line length */
2380 l_len
= preimage
->line
[ctx
].len
;
2381 memcpy(new_buf
, fixed
, l_len
);
2384 postimage
->line
[i
].len
= l_len
;
2389 ? postlen
< new_buf
- postimage
->buf
2390 : postimage
->len
< new_buf
- postimage
->buf
)
2391 BUG("caller miscounted postlen: asked %d, orig = %d, used = %d",
2392 (int)postlen
, (int) postimage
->len
, (int)(new_buf
- postimage
->buf
));
2394 /* Fix the length of the whole thing */
2395 postimage
->len
= new_buf
- postimage
->buf
;
2396 postimage
->nr
-= reduced
;
2399 static int line_by_line_fuzzy_match(struct image
*img
,
2400 struct image
*preimage
,
2401 struct image
*postimage
,
2402 unsigned long current
,
2409 size_t postlen
= postimage
->len
;
2414 struct strbuf fixed
;
2418 for (i
= 0; i
< preimage_limit
; i
++) {
2419 size_t prelen
= preimage
->line
[i
].len
;
2420 size_t imglen
= img
->line
[current_lno
+i
].len
;
2422 if (!fuzzy_matchlines(img
->buf
+ current
+ imgoff
, imglen
,
2423 preimage
->buf
+ preoff
, prelen
))
2425 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2426 postlen
+= imglen
- prelen
;
2432 * Ok, the preimage matches with whitespace fuzz.
2434 * imgoff now holds the true length of the target that
2435 * matches the preimage before the end of the file.
2437 * Count the number of characters in the preimage that fall
2438 * beyond the end of the file and make sure that all of them
2439 * are whitespace characters. (This can only happen if
2440 * we are removing blank lines at the end of the file.)
2442 buf
= preimage_eof
= preimage
->buf
+ preoff
;
2443 for ( ; i
< preimage
->nr
; i
++)
2444 preoff
+= preimage
->line
[i
].len
;
2445 preimage_end
= preimage
->buf
+ preoff
;
2446 for ( ; buf
< preimage_end
; buf
++)
2451 * Update the preimage and the common postimage context
2452 * lines to use the same whitespace as the target.
2453 * If whitespace is missing in the target (i.e.
2454 * if the preimage extends beyond the end of the file),
2455 * use the whitespace from the preimage.
2457 extra_chars
= preimage_end
- preimage_eof
;
2458 strbuf_init(&fixed
, imgoff
+ extra_chars
);
2459 strbuf_add(&fixed
, img
->buf
+ current
, imgoff
);
2460 strbuf_add(&fixed
, preimage_eof
, extra_chars
);
2461 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2462 update_pre_post_images(preimage
, postimage
,
2463 fixed_buf
, fixed_len
, postlen
);
2467 static int match_fragment(struct apply_state
*state
,
2469 struct image
*preimage
,
2470 struct image
*postimage
,
2471 unsigned long current
,
2474 int match_beginning
, int match_end
)
2477 char *fixed_buf
, *buf
, *orig
, *target
;
2478 struct strbuf fixed
;
2479 size_t fixed_len
, postlen
;
2482 if (preimage
->nr
+ current_lno
<= img
->nr
) {
2484 * The hunk falls within the boundaries of img.
2486 preimage_limit
= preimage
->nr
;
2487 if (match_end
&& (preimage
->nr
+ current_lno
!= img
->nr
))
2489 } else if (state
->ws_error_action
== correct_ws_error
&&
2490 (ws_rule
& WS_BLANK_AT_EOF
)) {
2492 * This hunk extends beyond the end of img, and we are
2493 * removing blank lines at the end of the file. This
2494 * many lines from the beginning of the preimage must
2495 * match with img, and the remainder of the preimage
2498 preimage_limit
= img
->nr
- current_lno
;
2501 * The hunk extends beyond the end of the img and
2502 * we are not removing blanks at the end, so we
2503 * should reject the hunk at this position.
2508 if (match_beginning
&& current_lno
)
2511 /* Quick hash check */
2512 for (i
= 0; i
< preimage_limit
; i
++)
2513 if ((img
->line
[current_lno
+ i
].flag
& LINE_PATCHED
) ||
2514 (preimage
->line
[i
].hash
!= img
->line
[current_lno
+ i
].hash
))
2517 if (preimage_limit
== preimage
->nr
) {
2519 * Do we have an exact match? If we were told to match
2520 * at the end, size must be exactly at current+fragsize,
2521 * otherwise current+fragsize must be still within the preimage,
2522 * and either case, the old piece should match the preimage
2526 ? (current
+ preimage
->len
== img
->len
)
2527 : (current
+ preimage
->len
<= img
->len
)) &&
2528 !memcmp(img
->buf
+ current
, preimage
->buf
, preimage
->len
))
2532 * The preimage extends beyond the end of img, so
2533 * there cannot be an exact match.
2535 * There must be one non-blank context line that match
2536 * a line before the end of img.
2540 buf
= preimage
->buf
;
2542 for (i
= 0; i
< preimage_limit
; i
++)
2543 buf_end
+= preimage
->line
[i
].len
;
2545 for ( ; buf
< buf_end
; buf
++)
2553 * No exact match. If we are ignoring whitespace, run a line-by-line
2554 * fuzzy matching. We collect all the line length information because
2555 * we need it to adjust whitespace if we match.
2557 if (state
->ws_ignore_action
== ignore_ws_change
)
2558 return line_by_line_fuzzy_match(img
, preimage
, postimage
,
2559 current
, current_lno
, preimage_limit
);
2561 if (state
->ws_error_action
!= correct_ws_error
)
2565 * The hunk does not apply byte-by-byte, but the hash says
2566 * it might with whitespace fuzz. We weren't asked to
2567 * ignore whitespace, we were asked to correct whitespace
2568 * errors, so let's try matching after whitespace correction.
2570 * While checking the preimage against the target, whitespace
2571 * errors in both fixed, we count how large the corresponding
2572 * postimage needs to be. The postimage prepared by
2573 * apply_one_fragment() has whitespace errors fixed on added
2574 * lines already, but the common lines were propagated as-is,
2575 * which may become longer when their whitespace errors are
2579 /* First count added lines in postimage */
2581 for (i
= 0; i
< postimage
->nr
; i
++) {
2582 if (!(postimage
->line
[i
].flag
& LINE_COMMON
))
2583 postlen
+= postimage
->line
[i
].len
;
2587 * The preimage may extend beyond the end of the file,
2588 * but in this loop we will only handle the part of the
2589 * preimage that falls within the file.
2591 strbuf_init(&fixed
, preimage
->len
+ 1);
2592 orig
= preimage
->buf
;
2593 target
= img
->buf
+ current
;
2594 for (i
= 0; i
< preimage_limit
; i
++) {
2595 size_t oldlen
= preimage
->line
[i
].len
;
2596 size_t tgtlen
= img
->line
[current_lno
+ i
].len
;
2597 size_t fixstart
= fixed
.len
;
2598 struct strbuf tgtfix
;
2601 /* Try fixing the line in the preimage */
2602 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2604 /* Try fixing the line in the target */
2605 strbuf_init(&tgtfix
, tgtlen
);
2606 ws_fix_copy(&tgtfix
, target
, tgtlen
, ws_rule
, NULL
);
2609 * If they match, either the preimage was based on
2610 * a version before our tree fixed whitespace breakage,
2611 * or we are lacking a whitespace-fix patch the tree
2612 * the preimage was based on already had (i.e. target
2613 * has whitespace breakage, the preimage doesn't).
2614 * In either case, we are fixing the whitespace breakages
2615 * so we might as well take the fix together with their
2618 match
= (tgtfix
.len
== fixed
.len
- fixstart
&&
2619 !memcmp(tgtfix
.buf
, fixed
.buf
+ fixstart
,
2620 fixed
.len
- fixstart
));
2622 /* Add the length if this is common with the postimage */
2623 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2624 postlen
+= tgtfix
.len
;
2626 strbuf_release(&tgtfix
);
2636 * Now handle the lines in the preimage that falls beyond the
2637 * end of the file (if any). They will only match if they are
2638 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2641 for ( ; i
< preimage
->nr
; i
++) {
2642 size_t fixstart
= fixed
.len
; /* start of the fixed preimage */
2643 size_t oldlen
= preimage
->line
[i
].len
;
2646 /* Try fixing the line in the preimage */
2647 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2649 for (j
= fixstart
; j
< fixed
.len
; j
++)
2650 if (!isspace(fixed
.buf
[j
]))
2657 * Yes, the preimage is based on an older version that still
2658 * has whitespace breakages unfixed, and fixing them makes the
2659 * hunk match. Update the context lines in the postimage.
2661 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2662 if (postlen
< postimage
->len
)
2664 update_pre_post_images(preimage
, postimage
,
2665 fixed_buf
, fixed_len
, postlen
);
2669 strbuf_release(&fixed
);
2673 static int find_pos(struct apply_state
*state
,
2675 struct image
*preimage
,
2676 struct image
*postimage
,
2679 int match_beginning
, int match_end
)
2682 unsigned long backwards
, forwards
, current
;
2683 int backwards_lno
, forwards_lno
, current_lno
;
2686 * When running with --allow-overlap, it is possible that a hunk is
2687 * seen that pretends to start at the beginning (but no longer does),
2688 * and that *still* needs to match the end. So trust `match_end` more
2689 * than `match_beginning`.
2691 if (state
->allow_overlap
&& match_beginning
&& match_end
&&
2692 img
->nr
- preimage
->nr
!= 0)
2693 match_beginning
= 0;
2696 * If match_beginning or match_end is specified, there is no
2697 * point starting from a wrong line that will never match and
2698 * wander around and wait for a match at the specified end.
2700 if (match_beginning
)
2703 line
= img
->nr
- preimage
->nr
;
2706 * Because the comparison is unsigned, the following test
2707 * will also take care of a negative line number that can
2708 * result when match_end and preimage is larger than the target.
2710 if ((size_t) line
> img
->nr
)
2714 for (i
= 0; i
< line
; i
++)
2715 current
+= img
->line
[i
].len
;
2718 * There's probably some smart way to do this, but I'll leave
2719 * that to the smart and beautiful people. I'm simple and stupid.
2721 backwards
= current
;
2722 backwards_lno
= line
;
2724 forwards_lno
= line
;
2727 for (i
= 0; ; i
++) {
2728 if (match_fragment(state
, img
, preimage
, postimage
,
2729 current
, current_lno
, ws_rule
,
2730 match_beginning
, match_end
))
2734 if (backwards_lno
== 0 && forwards_lno
== img
->nr
)
2738 if (backwards_lno
== 0) {
2743 backwards
-= img
->line
[backwards_lno
].len
;
2744 current
= backwards
;
2745 current_lno
= backwards_lno
;
2747 if (forwards_lno
== img
->nr
) {
2751 forwards
+= img
->line
[forwards_lno
].len
;
2754 current_lno
= forwards_lno
;
2761 static void remove_first_line(struct image
*img
)
2763 img
->buf
+= img
->line
[0].len
;
2764 img
->len
-= img
->line
[0].len
;
2769 static void remove_last_line(struct image
*img
)
2771 img
->len
-= img
->line
[--img
->nr
].len
;
2775 * The change from "preimage" and "postimage" has been found to
2776 * apply at applied_pos (counts in line numbers) in "img".
2777 * Update "img" to remove "preimage" and replace it with "postimage".
2779 static void update_image(struct apply_state
*state
,
2782 struct image
*preimage
,
2783 struct image
*postimage
)
2786 * remove the copy of preimage at offset in img
2787 * and replace it with postimage
2790 size_t remove_count
, insert_count
, applied_at
= 0;
2795 * If we are removing blank lines at the end of img,
2796 * the preimage may extend beyond the end.
2797 * If that is the case, we must be careful only to
2798 * remove the part of the preimage that falls within
2799 * the boundaries of img. Initialize preimage_limit
2800 * to the number of lines in the preimage that falls
2801 * within the boundaries.
2803 preimage_limit
= preimage
->nr
;
2804 if (preimage_limit
> img
->nr
- applied_pos
)
2805 preimage_limit
= img
->nr
- applied_pos
;
2807 for (i
= 0; i
< applied_pos
; i
++)
2808 applied_at
+= img
->line
[i
].len
;
2811 for (i
= 0; i
< preimage_limit
; i
++)
2812 remove_count
+= img
->line
[applied_pos
+ i
].len
;
2813 insert_count
= postimage
->len
;
2815 /* Adjust the contents */
2816 result
= xmalloc(st_add3(st_sub(img
->len
, remove_count
), insert_count
, 1));
2817 memcpy(result
, img
->buf
, applied_at
);
2818 memcpy(result
+ applied_at
, postimage
->buf
, postimage
->len
);
2819 memcpy(result
+ applied_at
+ postimage
->len
,
2820 img
->buf
+ (applied_at
+ remove_count
),
2821 img
->len
- (applied_at
+ remove_count
));
2824 img
->len
+= insert_count
- remove_count
;
2825 result
[img
->len
] = '\0';
2827 /* Adjust the line table */
2828 nr
= img
->nr
+ postimage
->nr
- preimage_limit
;
2829 if (preimage_limit
< postimage
->nr
) {
2831 * NOTE: this knows that we never call remove_first_line()
2832 * on anything other than pre/post image.
2834 REALLOC_ARRAY(img
->line
, nr
);
2835 img
->line_allocated
= img
->line
;
2837 if (preimage_limit
!= postimage
->nr
)
2838 MOVE_ARRAY(img
->line
+ applied_pos
+ postimage
->nr
,
2839 img
->line
+ applied_pos
+ preimage_limit
,
2840 img
->nr
- (applied_pos
+ preimage_limit
));
2841 COPY_ARRAY(img
->line
+ applied_pos
, postimage
->line
, postimage
->nr
);
2842 if (!state
->allow_overlap
)
2843 for (i
= 0; i
< postimage
->nr
; i
++)
2844 img
->line
[applied_pos
+ i
].flag
|= LINE_PATCHED
;
2849 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2850 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2851 * replace the part of "img" with "postimage" text.
2853 static int apply_one_fragment(struct apply_state
*state
,
2854 struct image
*img
, struct fragment
*frag
,
2855 int inaccurate_eof
, unsigned ws_rule
,
2858 int match_beginning
, match_end
;
2859 const char *patch
= frag
->patch
;
2860 int size
= frag
->size
;
2861 char *old
, *oldlines
;
2862 struct strbuf newlines
;
2863 int new_blank_lines_at_end
= 0;
2864 int found_new_blank_lines_at_end
= 0;
2865 int hunk_linenr
= frag
->linenr
;
2866 unsigned long leading
, trailing
;
2867 int pos
, applied_pos
;
2868 struct image preimage
;
2869 struct image postimage
;
2871 memset(&preimage
, 0, sizeof(preimage
));
2872 memset(&postimage
, 0, sizeof(postimage
));
2873 oldlines
= xmalloc(size
);
2874 strbuf_init(&newlines
, size
);
2879 int len
= linelen(patch
, size
);
2881 int added_blank_line
= 0;
2882 int is_blank_context
= 0;
2889 * "plen" is how much of the line we should use for
2890 * the actual patch data. Normally we just remove the
2891 * first character on the line, but if the line is
2892 * followed by "\ No newline", then we also remove the
2893 * last one (which is the newline, of course).
2896 if (len
< size
&& patch
[len
] == '\\')
2899 if (state
->apply_in_reverse
) {
2902 else if (first
== '+')
2908 /* Newer GNU diff, empty context line */
2910 /* ... followed by '\No newline'; nothing */
2913 strbuf_addch(&newlines
, '\n');
2914 add_line_info(&preimage
, "\n", 1, LINE_COMMON
);
2915 add_line_info(&postimage
, "\n", 1, LINE_COMMON
);
2916 is_blank_context
= 1;
2919 if (plen
&& (ws_rule
& WS_BLANK_AT_EOF
) &&
2920 ws_blank_line(patch
+ 1, plen
))
2921 is_blank_context
= 1;
2924 memcpy(old
, patch
+ 1, plen
);
2925 add_line_info(&preimage
, old
, plen
,
2926 (first
== ' ' ? LINE_COMMON
: 0));
2932 /* --no-add does not add new lines */
2933 if (first
== '+' && state
->no_add
)
2936 start
= newlines
.len
;
2938 !state
->whitespace_error
||
2939 state
->ws_error_action
!= correct_ws_error
) {
2940 strbuf_add(&newlines
, patch
+ 1, plen
);
2943 ws_fix_copy(&newlines
, patch
+ 1, plen
, ws_rule
, &state
->applied_after_fixing_ws
);
2945 add_line_info(&postimage
, newlines
.buf
+ start
, newlines
.len
- start
,
2946 (first
== '+' ? 0 : LINE_COMMON
));
2948 (ws_rule
& WS_BLANK_AT_EOF
) &&
2949 ws_blank_line(patch
+ 1, plen
))
2950 added_blank_line
= 1;
2952 case '@': case '\\':
2953 /* Ignore it, we already handled it */
2956 if (state
->apply_verbosity
> verbosity_normal
)
2957 error(_("invalid start of line: '%c'"), first
);
2961 if (added_blank_line
) {
2962 if (!new_blank_lines_at_end
)
2963 found_new_blank_lines_at_end
= hunk_linenr
;
2964 new_blank_lines_at_end
++;
2966 else if (is_blank_context
)
2969 new_blank_lines_at_end
= 0;
2974 if (inaccurate_eof
&&
2975 old
> oldlines
&& old
[-1] == '\n' &&
2976 newlines
.len
> 0 && newlines
.buf
[newlines
.len
- 1] == '\n') {
2978 strbuf_setlen(&newlines
, newlines
.len
- 1);
2979 preimage
.line_allocated
[preimage
.nr
- 1].len
--;
2980 postimage
.line_allocated
[postimage
.nr
- 1].len
--;
2983 leading
= frag
->leading
;
2984 trailing
= frag
->trailing
;
2987 * A hunk to change lines at the beginning would begin with
2989 * but we need to be careful. -U0 that inserts before the second
2990 * line also has this pattern.
2992 * And a hunk to add to an empty file would begin with
2995 * In other words, a hunk that is (frag->oldpos <= 1) with or
2996 * without leading context must match at the beginning.
2998 match_beginning
= (!frag
->oldpos
||
2999 (frag
->oldpos
== 1 && !state
->unidiff_zero
));
3002 * A hunk without trailing lines must match at the end.
3003 * However, we simply cannot tell if a hunk must match end
3004 * from the lack of trailing lines if the patch was generated
3005 * with unidiff without any context.
3007 match_end
= !state
->unidiff_zero
&& !trailing
;
3009 pos
= frag
->newpos
? (frag
->newpos
- 1) : 0;
3010 preimage
.buf
= oldlines
;
3011 preimage
.len
= old
- oldlines
;
3012 postimage
.buf
= newlines
.buf
;
3013 postimage
.len
= newlines
.len
;
3014 preimage
.line
= preimage
.line_allocated
;
3015 postimage
.line
= postimage
.line_allocated
;
3019 applied_pos
= find_pos(state
, img
, &preimage
, &postimage
, pos
,
3020 ws_rule
, match_beginning
, match_end
);
3022 if (applied_pos
>= 0)
3025 /* Am I at my context limits? */
3026 if ((leading
<= state
->p_context
) && (trailing
<= state
->p_context
))
3028 if (match_beginning
|| match_end
) {
3029 match_beginning
= match_end
= 0;
3034 * Reduce the number of context lines; reduce both
3035 * leading and trailing if they are equal otherwise
3036 * just reduce the larger context.
3038 if (leading
>= trailing
) {
3039 remove_first_line(&preimage
);
3040 remove_first_line(&postimage
);
3044 if (trailing
> leading
) {
3045 remove_last_line(&preimage
);
3046 remove_last_line(&postimage
);
3051 if (applied_pos
>= 0) {
3052 if (new_blank_lines_at_end
&&
3053 preimage
.nr
+ applied_pos
>= img
->nr
&&
3054 (ws_rule
& WS_BLANK_AT_EOF
) &&
3055 state
->ws_error_action
!= nowarn_ws_error
) {
3056 record_ws_error(state
, WS_BLANK_AT_EOF
, "+", 1,
3057 found_new_blank_lines_at_end
);
3058 if (state
->ws_error_action
== correct_ws_error
) {
3059 while (new_blank_lines_at_end
--)
3060 remove_last_line(&postimage
);
3063 * We would want to prevent write_out_results()
3064 * from taking place in apply_patch() that follows
3065 * the callchain led us here, which is:
3066 * apply_patch->check_patch_list->check_patch->
3067 * apply_data->apply_fragments->apply_one_fragment
3069 if (state
->ws_error_action
== die_on_ws_error
)
3073 if (state
->apply_verbosity
> verbosity_normal
&& applied_pos
!= pos
) {
3074 int offset
= applied_pos
- pos
;
3075 if (state
->apply_in_reverse
)
3076 offset
= 0 - offset
;
3078 Q_("Hunk #%d succeeded at %d (offset %d line).",
3079 "Hunk #%d succeeded at %d (offset %d lines).",
3081 nth_fragment
, applied_pos
+ 1, offset
);
3085 * Warn if it was necessary to reduce the number
3088 if ((leading
!= frag
->leading
||
3089 trailing
!= frag
->trailing
) && state
->apply_verbosity
> verbosity_silent
)
3090 fprintf_ln(stderr
, _("Context reduced to (%ld/%ld)"
3091 " to apply fragment at %d"),
3092 leading
, trailing
, applied_pos
+1);
3093 update_image(state
, img
, applied_pos
, &preimage
, &postimage
);
3095 if (state
->apply_verbosity
> verbosity_normal
)
3096 error(_("while searching for:\n%.*s"),
3097 (int)(old
- oldlines
), oldlines
);
3102 strbuf_release(&newlines
);
3103 free(preimage
.line_allocated
);
3104 free(postimage
.line_allocated
);
3106 return (applied_pos
< 0);
3109 static int apply_binary_fragment(struct apply_state
*state
,
3111 struct patch
*patch
)
3113 struct fragment
*fragment
= patch
->fragments
;
3118 return error(_("missing binary patch data for '%s'"),
3123 /* Binary patch is irreversible without the optional second hunk */
3124 if (state
->apply_in_reverse
) {
3125 if (!fragment
->next
)
3126 return error(_("cannot reverse-apply a binary patch "
3127 "without the reverse hunk to '%s'"),
3129 ? patch
->new_name
: patch
->old_name
);
3130 fragment
= fragment
->next
;
3132 switch (fragment
->binary_patch_method
) {
3133 case BINARY_DELTA_DEFLATED
:
3134 dst
= patch_delta(img
->buf
, img
->len
, fragment
->patch
,
3135 fragment
->size
, &len
);
3142 case BINARY_LITERAL_DEFLATED
:
3144 img
->len
= fragment
->size
;
3145 img
->buf
= xmemdupz(fragment
->patch
, img
->len
);
3152 * Replace "img" with the result of applying the binary patch.
3153 * The binary patch data itself in patch->fragment is still kept
3154 * but the preimage prepared by the caller in "img" is freed here
3155 * or in the helper function apply_binary_fragment() this calls.
3157 static int apply_binary(struct apply_state
*state
,
3159 struct patch
*patch
)
3161 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3162 struct object_id oid
;
3163 const unsigned hexsz
= the_hash_algo
->hexsz
;
3166 * For safety, we require patch index line to contain
3167 * full hex textual object ID for old and new, at least for now.
3169 if (strlen(patch
->old_oid_prefix
) != hexsz
||
3170 strlen(patch
->new_oid_prefix
) != hexsz
||
3171 get_oid_hex(patch
->old_oid_prefix
, &oid
) ||
3172 get_oid_hex(patch
->new_oid_prefix
, &oid
))
3173 return error(_("cannot apply binary patch to '%s' "
3174 "without full index line"), name
);
3176 if (patch
->old_name
) {
3178 * See if the old one matches what the patch
3181 hash_object_file(the_hash_algo
, img
->buf
, img
->len
, OBJ_BLOB
,
3183 if (strcmp(oid_to_hex(&oid
), patch
->old_oid_prefix
))
3184 return error(_("the patch applies to '%s' (%s), "
3185 "which does not match the "
3186 "current contents."),
3187 name
, oid_to_hex(&oid
));
3190 /* Otherwise, the old one must be empty. */
3192 return error(_("the patch applies to an empty "
3193 "'%s' but it is not empty"), name
);
3196 get_oid_hex(patch
->new_oid_prefix
, &oid
);
3197 if (is_null_oid(&oid
)) {
3199 return 0; /* deletion patch */
3202 if (has_object(the_repository
, &oid
, 0)) {
3203 /* We already have the postimage */
3204 enum object_type type
;
3208 result
= read_object_file(&oid
, &type
, &size
);
3210 return error(_("the necessary postimage %s for "
3211 "'%s' cannot be read"),
3212 patch
->new_oid_prefix
, name
);
3218 * We have verified buf matches the preimage;
3219 * apply the patch data to it, which is stored
3220 * in the patch->fragments->{patch,size}.
3222 if (apply_binary_fragment(state
, img
, patch
))
3223 return error(_("binary patch does not apply to '%s'"),
3226 /* verify that the result matches */
3227 hash_object_file(the_hash_algo
, img
->buf
, img
->len
, OBJ_BLOB
,
3229 if (strcmp(oid_to_hex(&oid
), patch
->new_oid_prefix
))
3230 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3231 name
, patch
->new_oid_prefix
, oid_to_hex(&oid
));
3237 static int apply_fragments(struct apply_state
*state
, struct image
*img
, struct patch
*patch
)
3239 struct fragment
*frag
= patch
->fragments
;
3240 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3241 unsigned ws_rule
= patch
->ws_rule
;
3242 unsigned inaccurate_eof
= patch
->inaccurate_eof
;
3245 if (patch
->is_binary
)
3246 return apply_binary(state
, img
, patch
);
3250 if (apply_one_fragment(state
, img
, frag
, inaccurate_eof
, ws_rule
, nth
)) {
3251 error(_("patch failed: %s:%ld"), name
, frag
->oldpos
);
3252 if (!state
->apply_with_reject
)
3261 static int read_blob_object(struct strbuf
*buf
, const struct object_id
*oid
, unsigned mode
)
3263 if (S_ISGITLINK(mode
)) {
3264 strbuf_grow(buf
, 100);
3265 strbuf_addf(buf
, "Subproject commit %s\n", oid_to_hex(oid
));
3267 enum object_type type
;
3271 result
= read_object_file(oid
, &type
, &sz
);
3274 /* XXX read_sha1_file NUL-terminates */
3275 strbuf_attach(buf
, result
, sz
, sz
+ 1);
3280 static int read_file_or_gitlink(const struct cache_entry
*ce
, struct strbuf
*buf
)
3284 return read_blob_object(buf
, &ce
->oid
, ce
->ce_mode
);
3287 static struct patch
*in_fn_table(struct apply_state
*state
, const char *name
)
3289 struct string_list_item
*item
;
3294 item
= string_list_lookup(&state
->fn_table
, name
);
3296 return (struct patch
*)item
->util
;
3302 * item->util in the filename table records the status of the path.
3303 * Usually it points at a patch (whose result records the contents
3304 * of it after applying it), but it could be PATH_WAS_DELETED for a
3305 * path that a previously applied patch has already removed, or
3306 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3308 * The latter is needed to deal with a case where two paths A and B
3309 * are swapped by first renaming A to B and then renaming B to A;
3310 * moving A to B should not be prevented due to presence of B as we
3311 * will remove it in a later patch.
3313 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3314 #define PATH_WAS_DELETED ((struct patch *) -1)
3316 static int to_be_deleted(struct patch
*patch
)
3318 return patch
== PATH_TO_BE_DELETED
;
3321 static int was_deleted(struct patch
*patch
)
3323 return patch
== PATH_WAS_DELETED
;
3326 static void add_to_fn_table(struct apply_state
*state
, struct patch
*patch
)
3328 struct string_list_item
*item
;
3331 * Always add new_name unless patch is a deletion
3332 * This should cover the cases for normal diffs,
3333 * file creations and copies
3335 if (patch
->new_name
) {
3336 item
= string_list_insert(&state
->fn_table
, patch
->new_name
);
3341 * store a failure on rename/deletion cases because
3342 * later chunks shouldn't patch old names
3344 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3345 item
= string_list_insert(&state
->fn_table
, patch
->old_name
);
3346 item
->util
= PATH_WAS_DELETED
;
3350 static void prepare_fn_table(struct apply_state
*state
, struct patch
*patch
)
3353 * store information about incoming file deletion
3356 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3357 struct string_list_item
*item
;
3358 item
= string_list_insert(&state
->fn_table
, patch
->old_name
);
3359 item
->util
= PATH_TO_BE_DELETED
;
3361 patch
= patch
->next
;
3365 static int checkout_target(struct index_state
*istate
,
3366 struct cache_entry
*ce
, struct stat
*st
)
3368 struct checkout costate
= CHECKOUT_INIT
;
3370 costate
.refresh_cache
= 1;
3371 costate
.istate
= istate
;
3372 if (checkout_entry(ce
, &costate
, NULL
, NULL
) ||
3373 lstat(ce
->name
, st
))
3374 return error(_("cannot checkout %s"), ce
->name
);
3378 static struct patch
*previous_patch(struct apply_state
*state
,
3379 struct patch
*patch
,
3382 struct patch
*previous
;
3385 if (patch
->is_copy
|| patch
->is_rename
)
3386 return NULL
; /* "git" patches do not depend on the order */
3388 previous
= in_fn_table(state
, patch
->old_name
);
3392 if (to_be_deleted(previous
))
3393 return NULL
; /* the deletion hasn't happened yet */
3395 if (was_deleted(previous
))
3401 static int verify_index_match(struct apply_state
*state
,
3402 const struct cache_entry
*ce
,
3405 if (S_ISGITLINK(ce
->ce_mode
)) {
3406 if (!S_ISDIR(st
->st_mode
))
3410 return ie_match_stat(state
->repo
->index
, ce
, st
,
3411 CE_MATCH_IGNORE_VALID
| CE_MATCH_IGNORE_SKIP_WORKTREE
);
3414 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3416 static int load_patch_target(struct apply_state
*state
,
3418 const struct cache_entry
*ce
,
3420 struct patch
*patch
,
3422 unsigned expected_mode
)
3424 if (state
->cached
|| state
->check_index
) {
3425 if (read_file_or_gitlink(ce
, buf
))
3426 return error(_("failed to read %s"), name
);
3428 if (S_ISGITLINK(expected_mode
)) {
3430 return read_file_or_gitlink(ce
, buf
);
3432 return SUBMODULE_PATCH_WITHOUT_INDEX
;
3433 } else if (has_symlink_leading_path(name
, strlen(name
))) {
3434 return error(_("reading from '%s' beyond a symbolic link"), name
);
3436 if (read_old_data(st
, patch
, name
, buf
))
3437 return error(_("failed to read %s"), name
);
3444 * We are about to apply "patch"; populate the "image" with the
3445 * current version we have, from the working tree or from the index,
3446 * depending on the situation e.g. --cached/--index. If we are
3447 * applying a non-git patch that incrementally updates the tree,
3448 * we read from the result of a previous diff.
3450 static int load_preimage(struct apply_state
*state
,
3451 struct image
*image
,
3452 struct patch
*patch
, struct stat
*st
,
3453 const struct cache_entry
*ce
)
3455 struct strbuf buf
= STRBUF_INIT
;
3458 struct patch
*previous
;
3461 previous
= previous_patch(state
, patch
, &status
);
3463 return error(_("path %s has been renamed/deleted"),
3466 /* We have a patched copy in memory; use that. */
3467 strbuf_add(&buf
, previous
->result
, previous
->resultsize
);
3469 status
= load_patch_target(state
, &buf
, ce
, st
, patch
,
3470 patch
->old_name
, patch
->old_mode
);
3473 else if (status
== SUBMODULE_PATCH_WITHOUT_INDEX
) {
3475 * There is no way to apply subproject
3476 * patch without looking at the index.
3477 * NEEDSWORK: shouldn't this be flagged
3480 free_fragment_list(patch
->fragments
);
3481 patch
->fragments
= NULL
;
3482 } else if (status
) {
3483 return error(_("failed to read %s"), patch
->old_name
);
3487 img
= strbuf_detach(&buf
, &len
);
3488 prepare_image(image
, img
, len
, !patch
->is_binary
);
3492 static int resolve_to(struct image
*image
, const struct object_id
*result_id
)
3495 enum object_type type
;
3499 image
->buf
= read_object_file(result_id
, &type
, &size
);
3500 if (!image
->buf
|| type
!= OBJ_BLOB
)
3501 die("unable to read blob object %s", oid_to_hex(result_id
));
3507 static int three_way_merge(struct apply_state
*state
,
3508 struct image
*image
,
3510 const struct object_id
*base
,
3511 const struct object_id
*ours
,
3512 const struct object_id
*theirs
)
3514 mmfile_t base_file
, our_file
, their_file
;
3515 mmbuffer_t result
= { NULL
};
3516 enum ll_merge_result status
;
3518 /* resolve trivial cases first */
3519 if (oideq(base
, ours
))
3520 return resolve_to(image
, theirs
);
3521 else if (oideq(base
, theirs
) || oideq(ours
, theirs
))
3522 return resolve_to(image
, ours
);
3524 read_mmblob(&base_file
, base
);
3525 read_mmblob(&our_file
, ours
);
3526 read_mmblob(&their_file
, theirs
);
3527 status
= ll_merge(&result
, path
,
3530 &their_file
, "theirs",
3533 if (status
== LL_MERGE_BINARY_CONFLICT
)
3534 warning("Cannot merge binary files: %s (%s vs. %s)",
3535 path
, "ours", "theirs");
3536 free(base_file
.ptr
);
3538 free(their_file
.ptr
);
3539 if (status
< 0 || !result
.ptr
) {
3544 image
->buf
= result
.ptr
;
3545 image
->len
= result
.size
;
3551 * When directly falling back to add/add three-way merge, we read from
3552 * the current contents of the new_name. In no cases other than that
3553 * this function will be called.
3555 static int load_current(struct apply_state
*state
,
3556 struct image
*image
,
3557 struct patch
*patch
)
3559 struct strbuf buf
= STRBUF_INIT
;
3564 struct cache_entry
*ce
;
3565 char *name
= patch
->new_name
;
3566 unsigned mode
= patch
->new_mode
;
3569 BUG("patch to %s is not a creation", patch
->old_name
);
3571 pos
= index_name_pos(state
->repo
->index
, name
, strlen(name
));
3573 return error(_("%s: does not exist in index"), name
);
3574 ce
= state
->repo
->index
->cache
[pos
];
3575 if (lstat(name
, &st
)) {
3576 if (errno
!= ENOENT
)
3577 return error_errno("%s", name
);
3578 if (checkout_target(state
->repo
->index
, ce
, &st
))
3581 if (verify_index_match(state
, ce
, &st
))
3582 return error(_("%s: does not match index"), name
);
3584 status
= load_patch_target(state
, &buf
, ce
, &st
, patch
, name
, mode
);
3589 img
= strbuf_detach(&buf
, &len
);
3590 prepare_image(image
, img
, len
, !patch
->is_binary
);
3594 static int try_threeway(struct apply_state
*state
,
3595 struct image
*image
,
3596 struct patch
*patch
,
3598 const struct cache_entry
*ce
)
3600 struct object_id pre_oid
, post_oid
, our_oid
;
3601 struct strbuf buf
= STRBUF_INIT
;
3605 struct image tmp_image
;
3607 /* No point falling back to 3-way merge in these cases */
3608 if (patch
->is_delete
||
3609 S_ISGITLINK(patch
->old_mode
) || S_ISGITLINK(patch
->new_mode
) ||
3610 (patch
->is_new
&& !patch
->direct_to_threeway
) ||
3611 (patch
->is_rename
&& !patch
->lines_added
&& !patch
->lines_deleted
))
3614 /* Preimage the patch was prepared for */
3616 write_object_file("", 0, OBJ_BLOB
, &pre_oid
);
3617 else if (get_oid(patch
->old_oid_prefix
, &pre_oid
) ||
3618 read_blob_object(&buf
, &pre_oid
, patch
->old_mode
))
3619 return error(_("repository lacks the necessary blob to perform 3-way merge."));
3621 if (state
->apply_verbosity
> verbosity_silent
&& patch
->direct_to_threeway
)
3622 fprintf(stderr
, _("Performing three-way merge...\n"));
3624 img
= strbuf_detach(&buf
, &len
);
3625 prepare_image(&tmp_image
, img
, len
, 1);
3626 /* Apply the patch to get the post image */
3627 if (apply_fragments(state
, &tmp_image
, patch
) < 0) {
3628 clear_image(&tmp_image
);
3631 /* post_oid is theirs */
3632 write_object_file(tmp_image
.buf
, tmp_image
.len
, OBJ_BLOB
, &post_oid
);
3633 clear_image(&tmp_image
);
3635 /* our_oid is ours */
3636 if (patch
->is_new
) {
3637 if (load_current(state
, &tmp_image
, patch
))
3638 return error(_("cannot read the current contents of '%s'"),
3641 if (load_preimage(state
, &tmp_image
, patch
, st
, ce
))
3642 return error(_("cannot read the current contents of '%s'"),
3645 write_object_file(tmp_image
.buf
, tmp_image
.len
, OBJ_BLOB
, &our_oid
);
3646 clear_image(&tmp_image
);
3648 /* in-core three-way merge between post and our using pre as base */
3649 status
= three_way_merge(state
, image
, patch
->new_name
,
3650 &pre_oid
, &our_oid
, &post_oid
);
3652 if (state
->apply_verbosity
> verbosity_silent
)
3654 _("Failed to perform three-way merge...\n"));
3659 patch
->conflicted_threeway
= 1;
3661 oidclr(&patch
->threeway_stage
[0]);
3663 oidcpy(&patch
->threeway_stage
[0], &pre_oid
);
3664 oidcpy(&patch
->threeway_stage
[1], &our_oid
);
3665 oidcpy(&patch
->threeway_stage
[2], &post_oid
);
3666 if (state
->apply_verbosity
> verbosity_silent
)
3668 _("Applied patch to '%s' with conflicts.\n"),
3671 if (state
->apply_verbosity
> verbosity_silent
)
3673 _("Applied patch to '%s' cleanly.\n"),
3679 static int apply_data(struct apply_state
*state
, struct patch
*patch
,
3680 struct stat
*st
, const struct cache_entry
*ce
)
3684 if (load_preimage(state
, &image
, patch
, st
, ce
) < 0)
3687 if (!state
->threeway
|| try_threeway(state
, &image
, patch
, st
, ce
) < 0) {
3688 if (state
->apply_verbosity
> verbosity_silent
&&
3689 state
->threeway
&& !patch
->direct_to_threeway
)
3690 fprintf(stderr
, _("Falling back to direct application...\n"));
3692 /* Note: with --reject, apply_fragments() returns 0 */
3693 if (patch
->direct_to_threeway
|| apply_fragments(state
, &image
, patch
) < 0)
3696 patch
->result
= image
.buf
;
3697 patch
->resultsize
= image
.len
;
3698 add_to_fn_table(state
, patch
);
3699 free(image
.line_allocated
);
3701 if (0 < patch
->is_delete
&& patch
->resultsize
)
3702 return error(_("removal patch leaves file contents"));
3708 * If "patch" that we are looking at modifies or deletes what we have,
3709 * we would want it not to lose any local modification we have, either
3710 * in the working tree or in the index.
3712 * This also decides if a non-git patch is a creation patch or a
3713 * modification to an existing empty file. We do not check the state
3714 * of the current tree for a creation patch in this function; the caller
3715 * check_patch() separately makes sure (and errors out otherwise) that
3716 * the path the patch creates does not exist in the current tree.
3718 static int check_preimage(struct apply_state
*state
,
3719 struct patch
*patch
,
3720 struct cache_entry
**ce
,
3723 const char *old_name
= patch
->old_name
;
3724 struct patch
*previous
= NULL
;
3725 int stat_ret
= 0, status
;
3726 unsigned st_mode
= 0;
3731 assert(patch
->is_new
<= 0);
3732 previous
= previous_patch(state
, patch
, &status
);
3735 return error(_("path %s has been renamed/deleted"), old_name
);
3737 st_mode
= previous
->new_mode
;
3738 } else if (!state
->cached
) {
3739 stat_ret
= lstat(old_name
, st
);
3740 if (stat_ret
&& errno
!= ENOENT
)
3741 return error_errno("%s", old_name
);
3744 if (state
->check_index
&& !previous
) {
3745 int pos
= index_name_pos(state
->repo
->index
, old_name
,
3748 if (patch
->is_new
< 0)
3750 return error(_("%s: does not exist in index"), old_name
);
3752 *ce
= state
->repo
->index
->cache
[pos
];
3754 if (checkout_target(state
->repo
->index
, *ce
, st
))
3757 if (!state
->cached
&& verify_index_match(state
, *ce
, st
))
3758 return error(_("%s: does not match index"), old_name
);
3760 st_mode
= (*ce
)->ce_mode
;
3761 } else if (stat_ret
< 0) {
3762 if (patch
->is_new
< 0)
3764 return error_errno("%s", old_name
);
3767 if (!state
->cached
&& !previous
)
3768 st_mode
= ce_mode_from_stat(*ce
, st
->st_mode
);
3770 if (patch
->is_new
< 0)
3772 if (!patch
->old_mode
)
3773 patch
->old_mode
= st_mode
;
3774 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
3775 return error(_("%s: wrong type"), old_name
);
3776 if (st_mode
!= patch
->old_mode
)
3777 warning(_("%s has type %o, expected %o"),
3778 old_name
, st_mode
, patch
->old_mode
);
3779 if (!patch
->new_mode
&& !patch
->is_delete
)
3780 patch
->new_mode
= st_mode
;
3785 patch
->is_delete
= 0;
3786 FREE_AND_NULL(patch
->old_name
);
3791 #define EXISTS_IN_INDEX 1
3792 #define EXISTS_IN_WORKTREE 2
3793 #define EXISTS_IN_INDEX_AS_ITA 3
3795 static int check_to_create(struct apply_state
*state
,
3796 const char *new_name
,
3801 if (state
->check_index
&& (!ok_if_exists
|| !state
->cached
)) {
3804 pos
= index_name_pos(state
->repo
->index
, new_name
, strlen(new_name
));
3806 struct cache_entry
*ce
= state
->repo
->index
->cache
[pos
];
3808 /* allow ITA, as they do not yet exist in the index */
3809 if (!ok_if_exists
&& !(ce
->ce_flags
& CE_INTENT_TO_ADD
))
3810 return EXISTS_IN_INDEX
;
3812 /* ITA entries can never match working tree files */
3813 if (!state
->cached
&& (ce
->ce_flags
& CE_INTENT_TO_ADD
))
3814 return EXISTS_IN_INDEX_AS_ITA
;
3821 if (!lstat(new_name
, &nst
)) {
3822 if (S_ISDIR(nst
.st_mode
) || ok_if_exists
)
3825 * A leading component of new_name might be a symlink
3826 * that is going to be removed with this patch, but
3827 * still pointing at somewhere that has the path.
3828 * In such a case, path "new_name" does not exist as
3829 * far as git is concerned.
3831 if (has_symlink_leading_path(new_name
, strlen(new_name
)))
3834 return EXISTS_IN_WORKTREE
;
3835 } else if (!is_missing_file_error(errno
)) {
3836 return error_errno("%s", new_name
);
3841 static void prepare_symlink_changes(struct apply_state
*state
, struct patch
*patch
)
3843 for ( ; patch
; patch
= patch
->next
) {
3844 if ((patch
->old_name
&& S_ISLNK(patch
->old_mode
)) &&
3845 (patch
->is_rename
|| patch
->is_delete
))
3846 /* the symlink at patch->old_name is removed */
3847 strset_add(&state
->removed_symlinks
, patch
->old_name
);
3849 if (patch
->new_name
&& S_ISLNK(patch
->new_mode
))
3850 /* the symlink at patch->new_name is created or remains */
3851 strset_add(&state
->kept_symlinks
, patch
->new_name
);
3855 static int path_is_beyond_symlink_1(struct apply_state
*state
, struct strbuf
*name
)
3858 while (--name
->len
&& name
->buf
[name
->len
] != '/')
3859 ; /* scan backwards */
3862 name
->buf
[name
->len
] = '\0';
3863 if (strset_contains(&state
->kept_symlinks
, name
->buf
))
3865 if (strset_contains(&state
->removed_symlinks
, name
->buf
))
3867 * This cannot be "return 0", because we may
3868 * see a new one created at a higher level.
3872 /* otherwise, check the preimage */
3873 if (state
->check_index
) {
3874 struct cache_entry
*ce
;
3876 ce
= index_file_exists(state
->repo
->index
, name
->buf
,
3877 name
->len
, ignore_case
);
3878 if (ce
&& S_ISLNK(ce
->ce_mode
))
3882 if (!lstat(name
->buf
, &st
) && S_ISLNK(st
.st_mode
))
3889 static int path_is_beyond_symlink(struct apply_state
*state
, const char *name_
)
3892 struct strbuf name
= STRBUF_INIT
;
3894 assert(*name_
!= '\0');
3895 strbuf_addstr(&name
, name_
);
3896 ret
= path_is_beyond_symlink_1(state
, &name
);
3897 strbuf_release(&name
);
3902 static int check_unsafe_path(struct patch
*patch
)
3904 const char *old_name
= NULL
;
3905 const char *new_name
= NULL
;
3906 if (patch
->is_delete
)
3907 old_name
= patch
->old_name
;
3908 else if (!patch
->is_new
&& !patch
->is_copy
)
3909 old_name
= patch
->old_name
;
3910 if (!patch
->is_delete
)
3911 new_name
= patch
->new_name
;
3913 if (old_name
&& !verify_path(old_name
, patch
->old_mode
))
3914 return error(_("invalid path '%s'"), old_name
);
3915 if (new_name
&& !verify_path(new_name
, patch
->new_mode
))
3916 return error(_("invalid path '%s'"), new_name
);
3921 * Check and apply the patch in-core; leave the result in patch->result
3922 * for the caller to write it out to the final destination.
3924 static int check_patch(struct apply_state
*state
, struct patch
*patch
)
3927 const char *old_name
= patch
->old_name
;
3928 const char *new_name
= patch
->new_name
;
3929 const char *name
= old_name
? old_name
: new_name
;
3930 struct cache_entry
*ce
= NULL
;
3931 struct patch
*tpatch
;
3935 patch
->rejected
= 1; /* we will drop this after we succeed */
3937 status
= check_preimage(state
, patch
, &ce
, &st
);
3940 old_name
= patch
->old_name
;
3943 * A type-change diff is always split into a patch to delete
3944 * old, immediately followed by a patch to create new (see
3945 * diff.c::run_diff()); in such a case it is Ok that the entry
3946 * to be deleted by the previous patch is still in the working
3947 * tree and in the index.
3949 * A patch to swap-rename between A and B would first rename A
3950 * to B and then rename B to A. While applying the first one,
3951 * the presence of B should not stop A from getting renamed to
3952 * B; ask to_be_deleted() about the later rename. Removal of
3953 * B and rename from A to B is handled the same way by asking
3956 if ((tpatch
= in_fn_table(state
, new_name
)) &&
3957 (was_deleted(tpatch
) || to_be_deleted(tpatch
)))
3963 ((0 < patch
->is_new
) || patch
->is_rename
|| patch
->is_copy
)) {
3964 int err
= check_to_create(state
, new_name
, ok_if_exists
);
3966 if (err
&& state
->threeway
) {
3967 patch
->direct_to_threeway
= 1;
3968 } else switch (err
) {
3971 case EXISTS_IN_INDEX
:
3972 return error(_("%s: already exists in index"), new_name
);
3973 case EXISTS_IN_INDEX_AS_ITA
:
3974 return error(_("%s: does not match index"), new_name
);
3975 case EXISTS_IN_WORKTREE
:
3976 return error(_("%s: already exists in working directory"),
3982 if (!patch
->new_mode
) {
3983 if (0 < patch
->is_new
)
3984 patch
->new_mode
= S_IFREG
| 0644;
3986 patch
->new_mode
= patch
->old_mode
;
3990 if (new_name
&& old_name
) {
3991 int same
= !strcmp(old_name
, new_name
);
3992 if (!patch
->new_mode
)
3993 patch
->new_mode
= patch
->old_mode
;
3994 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
) {
3996 return error(_("new mode (%o) of %s does not "
3997 "match old mode (%o)"),
3998 patch
->new_mode
, new_name
,
4001 return error(_("new mode (%o) of %s does not "
4002 "match old mode (%o) of %s"),
4003 patch
->new_mode
, new_name
,
4004 patch
->old_mode
, old_name
);
4008 if (!state
->unsafe_paths
&& check_unsafe_path(patch
))
4012 * An attempt to read from or delete a path that is beyond a
4013 * symbolic link will be prevented by load_patch_target() that
4014 * is called at the beginning of apply_data() so we do not
4015 * have to worry about a patch marked with "is_delete" bit
4016 * here. We however need to make sure that the patch result
4017 * is not deposited to a path that is beyond a symbolic link
4020 if (!patch
->is_delete
&& path_is_beyond_symlink(state
, patch
->new_name
))
4021 return error(_("affected file '%s' is beyond a symbolic link"),
4024 if (apply_data(state
, patch
, &st
, ce
) < 0)
4025 return error(_("%s: patch does not apply"), name
);
4026 patch
->rejected
= 0;
4030 static int check_patch_list(struct apply_state
*state
, struct patch
*patch
)
4034 prepare_symlink_changes(state
, patch
);
4035 prepare_fn_table(state
, patch
);
4038 if (state
->apply_verbosity
> verbosity_normal
)
4039 say_patch_name(stderr
,
4040 _("Checking patch %s..."), patch
);
4041 res
= check_patch(state
, patch
);
4045 patch
= patch
->next
;
4050 static int read_apply_cache(struct apply_state
*state
)
4052 if (state
->index_file
)
4053 return read_index_from(state
->repo
->index
, state
->index_file
,
4056 return repo_read_index(state
->repo
);
4059 /* This function tries to read the object name from the current index */
4060 static int get_current_oid(struct apply_state
*state
, const char *path
,
4061 struct object_id
*oid
)
4065 if (read_apply_cache(state
) < 0)
4067 pos
= index_name_pos(state
->repo
->index
, path
, strlen(path
));
4070 oidcpy(oid
, &state
->repo
->index
->cache
[pos
]->oid
);
4074 static int preimage_oid_in_gitlink_patch(struct patch
*p
, struct object_id
*oid
)
4077 * A usable gitlink patch has only one fragment (hunk) that looks like:
4079 * -Subproject commit <old sha1>
4080 * +Subproject commit <new sha1>
4083 * -Subproject commit <old sha1>
4084 * for a removal patch.
4086 struct fragment
*hunk
= p
->fragments
;
4087 static const char heading
[] = "-Subproject commit ";
4090 if (/* does the patch have only one hunk? */
4091 hunk
&& !hunk
->next
&&
4092 /* is its preimage one line? */
4093 hunk
->oldpos
== 1 && hunk
->oldlines
== 1 &&
4094 /* does preimage begin with the heading? */
4095 (preimage
= memchr(hunk
->patch
, '\n', hunk
->size
)) != NULL
&&
4096 starts_with(++preimage
, heading
) &&
4097 /* does it record full SHA-1? */
4098 !get_oid_hex(preimage
+ sizeof(heading
) - 1, oid
) &&
4099 preimage
[sizeof(heading
) + the_hash_algo
->hexsz
- 1] == '\n' &&
4100 /* does the abbreviated name on the index line agree with it? */
4101 starts_with(preimage
+ sizeof(heading
) - 1, p
->old_oid_prefix
))
4102 return 0; /* it all looks fine */
4104 /* we may have full object name on the index line */
4105 return get_oid_hex(p
->old_oid_prefix
, oid
);
4108 /* Build an index that contains just the files needed for a 3way merge */
4109 static int build_fake_ancestor(struct apply_state
*state
, struct patch
*list
)
4111 struct patch
*patch
;
4112 struct index_state result
= INDEX_STATE_INIT(state
->repo
);
4113 struct lock_file lock
= LOCK_INIT
;
4116 /* Once we start supporting the reverse patch, it may be
4117 * worth showing the new sha1 prefix, but until then...
4119 for (patch
= list
; patch
; patch
= patch
->next
) {
4120 struct object_id oid
;
4121 struct cache_entry
*ce
;
4124 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
4125 if (0 < patch
->is_new
)
4128 if (S_ISGITLINK(patch
->old_mode
)) {
4129 if (!preimage_oid_in_gitlink_patch(patch
, &oid
))
4130 ; /* ok, the textual part looks sane */
4132 return error(_("sha1 information is lacking or "
4133 "useless for submodule %s"), name
);
4134 } else if (!get_oid_blob(patch
->old_oid_prefix
, &oid
)) {
4136 } else if (!patch
->lines_added
&& !patch
->lines_deleted
) {
4137 /* mode-only change: update the current */
4138 if (get_current_oid(state
, patch
->old_name
, &oid
))
4139 return error(_("mode change for %s, which is not "
4140 "in current HEAD"), name
);
4142 return error(_("sha1 information is lacking or useless "
4145 ce
= make_cache_entry(&result
, patch
->old_mode
, &oid
, name
, 0, 0);
4147 return error(_("make_cache_entry failed for path '%s'"),
4149 if (add_index_entry(&result
, ce
, ADD_CACHE_OK_TO_ADD
)) {
4150 discard_cache_entry(ce
);
4151 return error(_("could not add %s to temporary index"),
4156 hold_lock_file_for_update(&lock
, state
->fake_ancestor
, LOCK_DIE_ON_ERROR
);
4157 res
= write_locked_index(&result
, &lock
, COMMIT_LOCK
);
4158 discard_index(&result
);
4161 return error(_("could not write temporary index to %s"),
4162 state
->fake_ancestor
);
4167 static void stat_patch_list(struct apply_state
*state
, struct patch
*patch
)
4169 int files
, adds
, dels
;
4171 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
4173 adds
+= patch
->lines_added
;
4174 dels
+= patch
->lines_deleted
;
4175 show_stats(state
, patch
);
4178 print_stat_summary(stdout
, files
, adds
, dels
);
4181 static void numstat_patch_list(struct apply_state
*state
,
4182 struct patch
*patch
)
4184 for ( ; patch
; patch
= patch
->next
) {
4186 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
4187 if (patch
->is_binary
)
4190 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
4191 write_name_quoted(name
, stdout
, state
->line_termination
);
4195 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
4198 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
4200 printf(" %s %s\n", newdelete
, name
);
4203 static void show_mode_change(struct patch
*p
, int show_name
)
4205 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
4207 printf(" mode change %06o => %06o %s\n",
4208 p
->old_mode
, p
->new_mode
, p
->new_name
);
4210 printf(" mode change %06o => %06o\n",
4211 p
->old_mode
, p
->new_mode
);
4215 static void show_rename_copy(struct patch
*p
)
4217 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
4218 const char *old_name
, *new_name
;
4220 /* Find common prefix */
4221 old_name
= p
->old_name
;
4222 new_name
= p
->new_name
;
4224 const char *slash_old
, *slash_new
;
4225 slash_old
= strchr(old_name
, '/');
4226 slash_new
= strchr(new_name
, '/');
4229 slash_old
- old_name
!= slash_new
- new_name
||
4230 memcmp(old_name
, new_name
, slash_new
- new_name
))
4232 old_name
= slash_old
+ 1;
4233 new_name
= slash_new
+ 1;
4235 /* p->old_name through old_name is the common prefix, and old_name and
4236 * new_name through the end of names are renames
4238 if (old_name
!= p
->old_name
)
4239 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
4240 (int)(old_name
- p
->old_name
), p
->old_name
,
4241 old_name
, new_name
, p
->score
);
4243 printf(" %s %s => %s (%d%%)\n", renamecopy
,
4244 p
->old_name
, p
->new_name
, p
->score
);
4245 show_mode_change(p
, 0);
4248 static void summary_patch_list(struct patch
*patch
)
4252 for (p
= patch
; p
; p
= p
->next
) {
4254 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
4255 else if (p
->is_delete
)
4256 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
4258 if (p
->is_rename
|| p
->is_copy
)
4259 show_rename_copy(p
);
4262 printf(" rewrite %s (%d%%)\n",
4263 p
->new_name
, p
->score
);
4264 show_mode_change(p
, 0);
4267 show_mode_change(p
, 1);
4273 static void patch_stats(struct apply_state
*state
, struct patch
*patch
)
4275 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
4277 if (lines
> state
->max_change
)
4278 state
->max_change
= lines
;
4279 if (patch
->old_name
) {
4280 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
4282 len
= strlen(patch
->old_name
);
4283 if (len
> state
->max_len
)
4284 state
->max_len
= len
;
4286 if (patch
->new_name
) {
4287 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
4289 len
= strlen(patch
->new_name
);
4290 if (len
> state
->max_len
)
4291 state
->max_len
= len
;
4295 static int remove_file(struct apply_state
*state
, struct patch
*patch
, int rmdir_empty
)
4297 if (state
->update_index
&& !state
->ita_only
) {
4298 if (remove_file_from_index(state
->repo
->index
, patch
->old_name
) < 0)
4299 return error(_("unable to remove %s from index"), patch
->old_name
);
4301 if (!state
->cached
) {
4302 if (!remove_or_warn(patch
->old_mode
, patch
->old_name
) && rmdir_empty
) {
4303 remove_path(patch
->old_name
);
4309 static int add_index_file(struct apply_state
*state
,
4316 struct cache_entry
*ce
;
4317 int namelen
= strlen(path
);
4319 ce
= make_empty_cache_entry(state
->repo
->index
, namelen
);
4320 memcpy(ce
->name
, path
, namelen
);
4321 ce
->ce_mode
= create_ce_mode(mode
);
4322 ce
->ce_flags
= create_ce_flags(0);
4323 ce
->ce_namelen
= namelen
;
4324 if (state
->ita_only
) {
4325 ce
->ce_flags
|= CE_INTENT_TO_ADD
;
4326 set_object_name_for_intent_to_add_entry(ce
);
4327 } else if (S_ISGITLINK(mode
)) {
4330 if (!skip_prefix(buf
, "Subproject commit ", &s
) ||
4331 get_oid_hex(s
, &ce
->oid
)) {
4332 discard_cache_entry(ce
);
4333 return error(_("corrupt patch for submodule %s"), path
);
4336 if (!state
->cached
) {
4337 if (lstat(path
, &st
) < 0) {
4338 discard_cache_entry(ce
);
4339 return error_errno(_("unable to stat newly "
4340 "created file '%s'"),
4343 fill_stat_cache_info(state
->repo
->index
, ce
, &st
);
4345 if (write_object_file(buf
, size
, OBJ_BLOB
, &ce
->oid
) < 0) {
4346 discard_cache_entry(ce
);
4347 return error(_("unable to create backing store "
4348 "for newly created file %s"), path
);
4351 if (add_index_entry(state
->repo
->index
, ce
, ADD_CACHE_OK_TO_ADD
) < 0) {
4352 discard_cache_entry(ce
);
4353 return error(_("unable to add cache entry for %s"), path
);
4361 * -1 if an unrecoverable error happened
4362 * 0 if everything went well
4363 * 1 if a recoverable error happened
4365 static int try_create_file(struct apply_state
*state
, const char *path
,
4366 unsigned int mode
, const char *buf
,
4370 struct strbuf nbuf
= STRBUF_INIT
;
4372 if (S_ISGITLINK(mode
)) {
4374 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
))
4376 return !!mkdir(path
, 0777);
4379 if (has_symlinks
&& S_ISLNK(mode
))
4380 /* Although buf:size is counted string, it also is NUL
4383 return !!symlink(buf
, path
);
4385 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
4389 if (convert_to_working_tree(state
->repo
->index
, path
, buf
, size
, &nbuf
, NULL
)) {
4394 res
= write_in_full(fd
, buf
, size
) < 0;
4396 error_errno(_("failed to write to '%s'"), path
);
4397 strbuf_release(&nbuf
);
4399 if (close(fd
) < 0 && !res
)
4400 return error_errno(_("closing file '%s'"), path
);
4402 return res
? -1 : 0;
4406 * We optimistically assume that the directories exist,
4407 * which is true 99% of the time anyway. If they don't,
4408 * we create them and try again.
4414 static int create_one_file(struct apply_state
*state
,
4426 * We already try to detect whether files are beyond a symlink in our
4427 * up-front checks. But in the case where symlinks are created by any
4428 * of the intermediate hunks it can happen that our up-front checks
4429 * didn't yet see the symlink, but at the point of arriving here there
4430 * in fact is one. We thus repeat the check for symlinks here.
4432 * Note that this does not make the up-front check obsolete as the
4433 * failure mode is different:
4435 * - The up-front checks cause us to abort before we have written
4436 * anything into the working directory. So when we exit this way the
4437 * working directory remains clean.
4439 * - The checks here happen in the middle of the action where we have
4440 * already started to apply the patch. The end result will be a dirty
4441 * working directory.
4443 * Ideally, we should update the up-front checks to catch what would
4444 * happen when we apply the patch before we damage the working tree.
4445 * We have all the information necessary to do so. But for now, as a
4446 * part of embargoed security work, having this check would serve as a
4447 * reasonable first step.
4449 if (path_is_beyond_symlink(state
, path
))
4450 return error(_("affected file '%s' is beyond a symbolic link"), path
);
4452 res
= try_create_file(state
, path
, mode
, buf
, size
);
4458 if (errno
== ENOENT
) {
4459 if (safe_create_leading_directories_no_share(path
))
4461 res
= try_create_file(state
, path
, mode
, buf
, size
);
4468 if (errno
== EEXIST
|| errno
== EACCES
) {
4469 /* We may be trying to create a file where a directory
4473 if (!lstat(path
, &st
) && (!S_ISDIR(st
.st_mode
) || !rmdir(path
)))
4477 if (errno
== EEXIST
) {
4478 unsigned int nr
= getpid();
4481 char newpath
[PATH_MAX
];
4482 mksnpath(newpath
, sizeof(newpath
), "%s~%u", path
, nr
);
4483 res
= try_create_file(state
, newpath
, mode
, buf
, size
);
4487 if (!rename(newpath
, path
))
4489 unlink_or_warn(newpath
);
4492 if (errno
!= EEXIST
)
4497 return error_errno(_("unable to write file '%s' mode %o"),
4501 static int add_conflicted_stages_file(struct apply_state
*state
,
4502 struct patch
*patch
)
4506 struct cache_entry
*ce
;
4508 if (!state
->update_index
)
4510 namelen
= strlen(patch
->new_name
);
4511 mode
= patch
->new_mode
? patch
->new_mode
: (S_IFREG
| 0644);
4513 remove_file_from_index(state
->repo
->index
, patch
->new_name
);
4514 for (stage
= 1; stage
< 4; stage
++) {
4515 if (is_null_oid(&patch
->threeway_stage
[stage
- 1]))
4517 ce
= make_empty_cache_entry(state
->repo
->index
, namelen
);
4518 memcpy(ce
->name
, patch
->new_name
, namelen
);
4519 ce
->ce_mode
= create_ce_mode(mode
);
4520 ce
->ce_flags
= create_ce_flags(stage
);
4521 ce
->ce_namelen
= namelen
;
4522 oidcpy(&ce
->oid
, &patch
->threeway_stage
[stage
- 1]);
4523 if (add_index_entry(state
->repo
->index
, ce
, ADD_CACHE_OK_TO_ADD
) < 0) {
4524 discard_cache_entry(ce
);
4525 return error(_("unable to add cache entry for %s"),
4533 static int create_file(struct apply_state
*state
, struct patch
*patch
)
4535 char *path
= patch
->new_name
;
4536 unsigned mode
= patch
->new_mode
;
4537 unsigned long size
= patch
->resultsize
;
4538 char *buf
= patch
->result
;
4541 mode
= S_IFREG
| 0644;
4542 if (create_one_file(state
, path
, mode
, buf
, size
))
4545 if (patch
->conflicted_threeway
)
4546 return add_conflicted_stages_file(state
, patch
);
4547 else if (state
->update_index
)
4548 return add_index_file(state
, path
, mode
, buf
, size
);
4552 /* phase zero is to remove, phase one is to create */
4553 static int write_out_one_result(struct apply_state
*state
,
4554 struct patch
*patch
,
4557 if (patch
->is_delete
> 0) {
4559 return remove_file(state
, patch
, 1);
4562 if (patch
->is_new
> 0 || patch
->is_copy
) {
4564 return create_file(state
, patch
);
4568 * Rename or modification boils down to the same
4569 * thing: remove the old, write the new
4572 return remove_file(state
, patch
, patch
->is_rename
);
4574 return create_file(state
, patch
);
4578 static int write_out_one_reject(struct apply_state
*state
, struct patch
*patch
)
4581 char namebuf
[PATH_MAX
];
4582 struct fragment
*frag
;
4584 struct strbuf sb
= STRBUF_INIT
;
4586 for (cnt
= 0, frag
= patch
->fragments
; frag
; frag
= frag
->next
) {
4587 if (!frag
->rejected
)
4593 if (state
->apply_verbosity
> verbosity_normal
)
4594 say_patch_name(stderr
,
4595 _("Applied patch %s cleanly."), patch
);
4599 /* This should not happen, because a removal patch that leaves
4600 * contents are marked "rejected" at the patch level.
4602 if (!patch
->new_name
)
4603 die(_("internal error"));
4605 /* Say this even without --verbose */
4606 strbuf_addf(&sb
, Q_("Applying patch %%s with %d reject...",
4607 "Applying patch %%s with %d rejects...",
4610 if (state
->apply_verbosity
> verbosity_silent
)
4611 say_patch_name(stderr
, sb
.buf
, patch
);
4612 strbuf_release(&sb
);
4614 cnt
= strlen(patch
->new_name
);
4615 if (ARRAY_SIZE(namebuf
) <= cnt
+ 5) {
4616 cnt
= ARRAY_SIZE(namebuf
) - 5;
4617 warning(_("truncating .rej filename to %.*s.rej"),
4618 cnt
- 1, patch
->new_name
);
4620 memcpy(namebuf
, patch
->new_name
, cnt
);
4621 memcpy(namebuf
+ cnt
, ".rej", 5);
4623 rej
= fopen(namebuf
, "w");
4625 return error_errno(_("cannot open %s"), namebuf
);
4627 /* Normal git tools never deal with .rej, so do not pretend
4628 * this is a git patch by saying --git or giving extended
4629 * headers. While at it, maybe please "kompare" that wants
4630 * the trailing TAB and some garbage at the end of line ;-).
4632 fprintf(rej
, "diff a/%s b/%s\t(rejected hunks)\n",
4633 patch
->new_name
, patch
->new_name
);
4634 for (cnt
= 1, frag
= patch
->fragments
;
4636 cnt
++, frag
= frag
->next
) {
4637 if (!frag
->rejected
) {
4638 if (state
->apply_verbosity
> verbosity_silent
)
4639 fprintf_ln(stderr
, _("Hunk #%d applied cleanly."), cnt
);
4642 if (state
->apply_verbosity
> verbosity_silent
)
4643 fprintf_ln(stderr
, _("Rejected hunk #%d."), cnt
);
4644 fprintf(rej
, "%.*s", frag
->size
, frag
->patch
);
4645 if (frag
->patch
[frag
->size
-1] != '\n')
4654 * -1 if an error happened
4655 * 0 if the patch applied cleanly
4656 * 1 if the patch did not apply cleanly
4658 static int write_out_results(struct apply_state
*state
, struct patch
*list
)
4663 struct string_list cpath
= STRING_LIST_INIT_DUP
;
4665 for (phase
= 0; phase
< 2; phase
++) {
4671 if (write_out_one_result(state
, l
, phase
)) {
4672 string_list_clear(&cpath
, 0);
4676 if (write_out_one_reject(state
, l
))
4678 if (l
->conflicted_threeway
) {
4679 string_list_append(&cpath
, l
->new_name
);
4689 struct string_list_item
*item
;
4691 string_list_sort(&cpath
);
4692 if (state
->apply_verbosity
> verbosity_silent
) {
4693 for_each_string_list_item(item
, &cpath
)
4694 fprintf(stderr
, "U %s\n", item
->string
);
4696 string_list_clear(&cpath
, 0);
4699 * rerere relies on the partially merged result being in the working
4700 * tree with conflict markers, but that isn't written with --cached.
4703 repo_rerere(state
->repo
, 0);
4710 * Try to apply a patch.
4713 * -128 if a bad error happened (like patch unreadable)
4714 * -1 if patch did not apply and user cannot deal with it
4715 * 0 if the patch applied
4716 * 1 if the patch did not apply but user might fix it
4718 static int apply_patch(struct apply_state
*state
,
4720 const char *filename
,
4724 struct strbuf buf
= STRBUF_INIT
; /* owns the patch text */
4725 struct patch
*list
= NULL
, **listp
= &list
;
4726 int skipped_patch
= 0;
4728 int flush_attributes
= 0;
4730 state
->patch_input_file
= filename
;
4731 if (read_patch_file(&buf
, fd
) < 0)
4734 while (offset
< buf
.len
) {
4735 struct patch
*patch
;
4738 CALLOC_ARRAY(patch
, 1);
4739 patch
->inaccurate_eof
= !!(options
& APPLY_OPT_INACCURATE_EOF
);
4740 patch
->recount
= !!(options
& APPLY_OPT_RECOUNT
);
4741 nr
= parse_chunk(state
, buf
.buf
+ offset
, buf
.len
- offset
, patch
);
4750 if (state
->apply_in_reverse
)
4751 reverse_patches(patch
);
4752 if (use_patch(state
, patch
)) {
4753 patch_stats(state
, patch
);
4754 if (!list
|| !state
->apply_in_reverse
) {
4756 listp
= &patch
->next
;
4762 if ((patch
->new_name
&&
4763 ends_with_path_components(patch
->new_name
,
4764 GITATTRIBUTES_FILE
)) ||
4766 ends_with_path_components(patch
->old_name
,
4767 GITATTRIBUTES_FILE
)))
4768 flush_attributes
= 1;
4771 if (state
->apply_verbosity
> verbosity_normal
)
4772 say_patch_name(stderr
, _("Skipped patch '%s'."), patch
);
4779 if (!list
&& !skipped_patch
) {
4780 if (!state
->allow_empty
) {
4781 error(_("No valid patches in input (allow with \"--allow-empty\")"));
4787 if (state
->whitespace_error
&& (state
->ws_error_action
== die_on_ws_error
))
4790 state
->update_index
= (state
->check_index
|| state
->ita_only
) && state
->apply
;
4791 if (state
->update_index
&& !is_lock_file_locked(&state
->lock_file
)) {
4792 if (state
->index_file
)
4793 hold_lock_file_for_update(&state
->lock_file
,
4797 repo_hold_locked_index(state
->repo
, &state
->lock_file
,
4801 if (state
->check_index
&& read_apply_cache(state
) < 0) {
4802 error(_("unable to read index file"));
4807 if (state
->check
|| state
->apply
) {
4808 int r
= check_patch_list(state
, list
);
4813 if (r
< 0 && !state
->apply_with_reject
) {
4820 int write_res
= write_out_results(state
, list
);
4821 if (write_res
< 0) {
4825 if (write_res
> 0) {
4826 /* with --3way, we still need to write the index out */
4827 res
= state
->apply_with_reject
? -1 : 1;
4832 if (state
->fake_ancestor
&&
4833 build_fake_ancestor(state
, list
)) {
4838 if (state
->diffstat
&& state
->apply_verbosity
> verbosity_silent
)
4839 stat_patch_list(state
, list
);
4841 if (state
->numstat
&& state
->apply_verbosity
> verbosity_silent
)
4842 numstat_patch_list(state
, list
);
4844 if (state
->summary
&& state
->apply_verbosity
> verbosity_silent
)
4845 summary_patch_list(list
);
4847 if (flush_attributes
)
4848 reset_parsed_attributes();
4850 free_patch_list(list
);
4851 strbuf_release(&buf
);
4852 string_list_clear(&state
->fn_table
, 0);
4856 static int apply_option_parse_exclude(const struct option
*opt
,
4857 const char *arg
, int unset
)
4859 struct apply_state
*state
= opt
->value
;
4861 BUG_ON_OPT_NEG(unset
);
4863 add_name_limit(state
, arg
, 1);
4867 static int apply_option_parse_include(const struct option
*opt
,
4868 const char *arg
, int unset
)
4870 struct apply_state
*state
= opt
->value
;
4872 BUG_ON_OPT_NEG(unset
);
4874 add_name_limit(state
, arg
, 0);
4875 state
->has_include
= 1;
4879 static int apply_option_parse_p(const struct option
*opt
,
4883 struct apply_state
*state
= opt
->value
;
4885 BUG_ON_OPT_NEG(unset
);
4887 state
->p_value
= atoi(arg
);
4888 state
->p_value_known
= 1;
4892 static int apply_option_parse_space_change(const struct option
*opt
,
4893 const char *arg
, int unset
)
4895 struct apply_state
*state
= opt
->value
;
4897 BUG_ON_OPT_ARG(arg
);
4900 state
->ws_ignore_action
= ignore_ws_none
;
4902 state
->ws_ignore_action
= ignore_ws_change
;
4906 static int apply_option_parse_whitespace(const struct option
*opt
,
4907 const char *arg
, int unset
)
4909 struct apply_state
*state
= opt
->value
;
4911 BUG_ON_OPT_NEG(unset
);
4913 state
->whitespace_option
= arg
;
4914 if (parse_whitespace_option(state
, arg
))
4919 static int apply_option_parse_directory(const struct option
*opt
,
4920 const char *arg
, int unset
)
4922 struct apply_state
*state
= opt
->value
;
4924 BUG_ON_OPT_NEG(unset
);
4926 strbuf_reset(&state
->root
);
4927 strbuf_addstr(&state
->root
, arg
);
4928 strbuf_complete(&state
->root
, '/');
4932 int apply_all_patches(struct apply_state
*state
,
4942 for (i
= 0; i
< argc
; i
++) {
4943 const char *arg
= argv
[i
];
4944 char *to_free
= NULL
;
4947 if (!strcmp(arg
, "-")) {
4948 res
= apply_patch(state
, 0, "<stdin>", options
);
4955 arg
= to_free
= prefix_filename(state
->prefix
, arg
);
4957 fd
= open(arg
, O_RDONLY
);
4959 error(_("can't open patch '%s': %s"), arg
, strerror(errno
));
4965 set_default_whitespace_mode(state
);
4966 res
= apply_patch(state
, fd
, arg
, options
);
4973 set_default_whitespace_mode(state
);
4975 res
= apply_patch(state
, 0, "<stdin>", options
);
4981 if (state
->whitespace_error
) {
4982 if (state
->squelch_whitespace_errors
&&
4983 state
->squelch_whitespace_errors
< state
->whitespace_error
) {
4985 state
->whitespace_error
- state
->squelch_whitespace_errors
;
4986 warning(Q_("squelched %d whitespace error",
4987 "squelched %d whitespace errors",
4991 if (state
->ws_error_action
== die_on_ws_error
) {
4992 error(Q_("%d line adds whitespace errors.",
4993 "%d lines add whitespace errors.",
4994 state
->whitespace_error
),
4995 state
->whitespace_error
);
4999 if (state
->applied_after_fixing_ws
&& state
->apply
)
5000 warning(Q_("%d line applied after"
5001 " fixing whitespace errors.",
5002 "%d lines applied after"
5003 " fixing whitespace errors.",
5004 state
->applied_after_fixing_ws
),
5005 state
->applied_after_fixing_ws
);
5006 else if (state
->whitespace_error
)
5007 warning(Q_("%d line adds whitespace errors.",
5008 "%d lines add whitespace errors.",
5009 state
->whitespace_error
),
5010 state
->whitespace_error
);
5013 if (state
->update_index
) {
5014 res
= write_locked_index(state
->repo
->index
, &state
->lock_file
, COMMIT_LOCK
);
5016 error(_("Unable to write new index file"));
5025 rollback_lock_file(&state
->lock_file
);
5027 if (state
->apply_verbosity
<= verbosity_silent
) {
5028 set_error_routine(state
->saved_error_routine
);
5029 set_warn_routine(state
->saved_warn_routine
);
5034 return (res
== -1 ? 1 : 128);
5037 int apply_parse_options(int argc
, const char **argv
,
5038 struct apply_state
*state
,
5039 int *force_apply
, int *options
,
5040 const char * const *apply_usage
)
5042 struct option builtin_apply_options
[] = {
5043 OPT_CALLBACK_F(0, "exclude", state
, N_("path"),
5044 N_("don't apply changes matching the given path"),
5045 PARSE_OPT_NONEG
, apply_option_parse_exclude
),
5046 OPT_CALLBACK_F(0, "include", state
, N_("path"),
5047 N_("apply changes matching the given path"),
5048 PARSE_OPT_NONEG
, apply_option_parse_include
),
5049 OPT_CALLBACK('p', NULL
, state
, N_("num"),
5050 N_("remove <num> leading slashes from traditional diff paths"),
5051 apply_option_parse_p
),
5052 OPT_BOOL(0, "no-add", &state
->no_add
,
5053 N_("ignore additions made by the patch")),
5054 OPT_BOOL(0, "stat", &state
->diffstat
,
5055 N_("instead of applying the patch, output diffstat for the input")),
5056 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
5057 OPT_NOOP_NOARG(0, "binary"),
5058 OPT_BOOL(0, "numstat", &state
->numstat
,
5059 N_("show number of added and deleted lines in decimal notation")),
5060 OPT_BOOL(0, "summary", &state
->summary
,
5061 N_("instead of applying the patch, output a summary for the input")),
5062 OPT_BOOL(0, "check", &state
->check
,
5063 N_("instead of applying the patch, see if the patch is applicable")),
5064 OPT_BOOL(0, "index", &state
->check_index
,
5065 N_("make sure the patch is applicable to the current index")),
5066 OPT_BOOL('N', "intent-to-add", &state
->ita_only
,
5067 N_("mark new files with `git add --intent-to-add`")),
5068 OPT_BOOL(0, "cached", &state
->cached
,
5069 N_("apply a patch without touching the working tree")),
5070 OPT_BOOL_F(0, "unsafe-paths", &state
->unsafe_paths
,
5071 N_("accept a patch that touches outside the working area"),
5072 PARSE_OPT_NOCOMPLETE
),
5073 OPT_BOOL(0, "apply", force_apply
,
5074 N_("also apply the patch (use with --stat/--summary/--check)")),
5075 OPT_BOOL('3', "3way", &state
->threeway
,
5076 N_( "attempt three-way merge, fall back on normal patch if that fails")),
5077 OPT_FILENAME(0, "build-fake-ancestor", &state
->fake_ancestor
,
5078 N_("build a temporary index based on embedded index information")),
5079 /* Think twice before adding "--nul" synonym to this */
5080 OPT_SET_INT('z', NULL
, &state
->line_termination
,
5081 N_("paths are separated with NUL character"), '\0'),
5082 OPT_INTEGER('C', NULL
, &state
->p_context
,
5083 N_("ensure at least <n> lines of context match")),
5084 OPT_CALLBACK(0, "whitespace", state
, N_("action"),
5085 N_("detect new or modified lines that have whitespace errors"),
5086 apply_option_parse_whitespace
),
5087 OPT_CALLBACK_F(0, "ignore-space-change", state
, NULL
,
5088 N_("ignore changes in whitespace when finding context"),
5089 PARSE_OPT_NOARG
, apply_option_parse_space_change
),
5090 OPT_CALLBACK_F(0, "ignore-whitespace", state
, NULL
,
5091 N_("ignore changes in whitespace when finding context"),
5092 PARSE_OPT_NOARG
, apply_option_parse_space_change
),
5093 OPT_BOOL('R', "reverse", &state
->apply_in_reverse
,
5094 N_("apply the patch in reverse")),
5095 OPT_BOOL(0, "unidiff-zero", &state
->unidiff_zero
,
5096 N_("don't expect at least one line of context")),
5097 OPT_BOOL(0, "reject", &state
->apply_with_reject
,
5098 N_("leave the rejected hunks in corresponding *.rej files")),
5099 OPT_BOOL(0, "allow-overlap", &state
->allow_overlap
,
5100 N_("allow overlapping hunks")),
5101 OPT__VERBOSITY(&state
->apply_verbosity
),
5102 OPT_BIT(0, "inaccurate-eof", options
,
5103 N_("tolerate incorrectly detected missing new-line at the end of file"),
5104 APPLY_OPT_INACCURATE_EOF
),
5105 OPT_BIT(0, "recount", options
,
5106 N_("do not trust the line counts in the hunk headers"),
5108 OPT_CALLBACK(0, "directory", state
, N_("root"),
5109 N_("prepend <root> to all filenames"),
5110 apply_option_parse_directory
),
5111 OPT_BOOL(0, "allow-empty", &state
->allow_empty
,
5112 N_("don't return error for empty patches")),
5116 return parse_options(argc
, argv
, state
->prefix
, builtin_apply_options
, apply_usage
, 0);