4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
12 #include "object-store.h"
17 #include "xdiff-interface.h"
20 #include "parse-options.h"
32 static void git_apply_config(void)
34 git_config_get_string("apply.whitespace", &apply_default_whitespace
);
35 git_config_get_string("apply.ignorewhitespace", &apply_default_ignorewhitespace
);
36 git_config(git_xmerge_config
, NULL
);
39 static int parse_whitespace_option(struct apply_state
*state
, const char *option
)
42 state
->ws_error_action
= warn_on_ws_error
;
45 if (!strcmp(option
, "warn")) {
46 state
->ws_error_action
= warn_on_ws_error
;
49 if (!strcmp(option
, "nowarn")) {
50 state
->ws_error_action
= nowarn_ws_error
;
53 if (!strcmp(option
, "error")) {
54 state
->ws_error_action
= die_on_ws_error
;
57 if (!strcmp(option
, "error-all")) {
58 state
->ws_error_action
= die_on_ws_error
;
59 state
->squelch_whitespace_errors
= 0;
62 if (!strcmp(option
, "strip") || !strcmp(option
, "fix")) {
63 state
->ws_error_action
= correct_ws_error
;
67 * Please update $__git_whitespacelist in git-completion.bash
68 * when you add new options.
70 return error(_("unrecognized whitespace option '%s'"), option
);
73 static int parse_ignorewhitespace_option(struct apply_state
*state
,
76 if (!option
|| !strcmp(option
, "no") ||
77 !strcmp(option
, "false") || !strcmp(option
, "never") ||
78 !strcmp(option
, "none")) {
79 state
->ws_ignore_action
= ignore_ws_none
;
82 if (!strcmp(option
, "change")) {
83 state
->ws_ignore_action
= ignore_ws_change
;
86 return error(_("unrecognized whitespace ignore option '%s'"), option
);
89 int init_apply_state(struct apply_state
*state
,
90 struct repository
*repo
,
93 memset(state
, 0, sizeof(*state
));
94 state
->prefix
= prefix
;
97 state
->line_termination
= '\n';
99 state
->p_context
= UINT_MAX
;
100 state
->squelch_whitespace_errors
= 5;
101 state
->ws_error_action
= warn_on_ws_error
;
102 state
->ws_ignore_action
= ignore_ws_none
;
104 string_list_init_nodup(&state
->fn_table
);
105 string_list_init_nodup(&state
->limit_by_name
);
106 strset_init(&state
->removed_symlinks
);
107 strset_init(&state
->kept_symlinks
);
108 strbuf_init(&state
->root
, 0);
111 if (apply_default_whitespace
&& parse_whitespace_option(state
, apply_default_whitespace
))
113 if (apply_default_ignorewhitespace
&& parse_ignorewhitespace_option(state
, apply_default_ignorewhitespace
))
118 void clear_apply_state(struct apply_state
*state
)
120 string_list_clear(&state
->limit_by_name
, 0);
121 strset_clear(&state
->removed_symlinks
);
122 strset_clear(&state
->kept_symlinks
);
123 strbuf_release(&state
->root
);
125 /* &state->fn_table is cleared at the end of apply_patch() */
128 static void mute_routine(const char *msg UNUSED
, va_list params UNUSED
)
133 int check_apply_state(struct apply_state
*state
, int force_apply
)
135 int is_not_gitdir
= !startup_info
->have_repository
;
137 if (state
->apply_with_reject
&& state
->threeway
)
138 return error(_("options '%s' and '%s' cannot be used together"), "--reject", "--3way");
139 if (state
->threeway
) {
141 return error(_("'%s' outside a repository"), "--3way");
142 state
->check_index
= 1;
144 if (state
->apply_with_reject
) {
146 if (state
->apply_verbosity
== verbosity_normal
)
147 state
->apply_verbosity
= verbosity_verbose
;
149 if (!force_apply
&& (state
->diffstat
|| state
->numstat
|| state
->summary
|| state
->check
|| state
->fake_ancestor
))
151 if (state
->check_index
&& is_not_gitdir
)
152 return error(_("'%s' outside a repository"), "--index");
155 return error(_("'%s' outside a repository"), "--cached");
156 state
->check_index
= 1;
158 if (state
->ita_only
&& (state
->check_index
|| is_not_gitdir
))
160 if (state
->check_index
)
161 state
->unsafe_paths
= 0;
163 if (state
->apply_verbosity
<= verbosity_silent
) {
164 state
->saved_error_routine
= get_error_routine();
165 state
->saved_warn_routine
= get_warn_routine();
166 set_error_routine(mute_routine
);
167 set_warn_routine(mute_routine
);
173 static void set_default_whitespace_mode(struct apply_state
*state
)
175 if (!state
->whitespace_option
&& !apply_default_whitespace
)
176 state
->ws_error_action
= (state
->apply
? warn_on_ws_error
: nowarn_ws_error
);
180 * This represents one "hunk" from a patch, starting with
181 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
182 * patch text is pointed at by patch, and its byte length
183 * is stored in size. leading and trailing are the number
187 unsigned long leading
, trailing
;
188 unsigned long oldpos
, oldlines
;
189 unsigned long newpos
, newlines
;
191 * 'patch' is usually borrowed from buf in apply_patch(),
192 * but some codepaths store an allocated buffer.
195 unsigned free_patch
:1,
199 struct fragment
*next
;
203 * When dealing with a binary patch, we reuse "leading" field
204 * to store the type of the binary hunk, either deflated "delta"
205 * or deflated "literal".
207 #define binary_patch_method leading
208 #define BINARY_DELTA_DEFLATED 1
209 #define BINARY_LITERAL_DEFLATED 2
211 static void free_fragment_list(struct fragment
*list
)
214 struct fragment
*next
= list
->next
;
215 if (list
->free_patch
)
216 free((char *)list
->patch
);
222 void release_patch(struct patch
*patch
)
224 free_fragment_list(patch
->fragments
);
225 free(patch
->def_name
);
226 free(patch
->old_name
);
227 free(patch
->new_name
);
231 static void free_patch(struct patch
*patch
)
233 release_patch(patch
);
237 static void free_patch_list(struct patch
*list
)
240 struct patch
*next
= list
->next
;
247 * A line in a file, len-bytes long (includes the terminating LF,
248 * except for an incomplete line at the end if the file ends with
249 * one), and its contents hashes to 'hash'.
255 #define LINE_COMMON 1
256 #define LINE_PATCHED 2
260 * This represents a "file", which is an array of "lines".
267 struct line
*line_allocated
;
271 static uint32_t hash_line(const char *cp
, size_t len
)
275 for (i
= 0, h
= 0; i
< len
; i
++) {
276 if (!isspace(cp
[i
])) {
277 h
= h
* 3 + (cp
[i
] & 0xff);
284 * Compare lines s1 of length n1 and s2 of length n2, ignoring
285 * whitespace difference. Returns 1 if they match, 0 otherwise
287 static int fuzzy_matchlines(const char *s1
, size_t n1
,
288 const char *s2
, size_t n2
)
290 const char *end1
= s1
+ n1
;
291 const char *end2
= s2
+ n2
;
293 /* ignore line endings */
294 while (s1
< end1
&& (end1
[-1] == '\r' || end1
[-1] == '\n'))
296 while (s2
< end2
&& (end2
[-1] == '\r' || end2
[-1] == '\n'))
299 while (s1
< end1
&& s2
< end2
) {
302 * Skip whitespace. We check on both buffers
303 * because we don't want "a b" to match "ab".
307 while (s1
< end1
&& isspace(*s1
))
309 while (s2
< end2
&& isspace(*s2
))
311 } else if (*s1
++ != *s2
++)
315 /* If we reached the end on one side only, lines don't match. */
316 return s1
== end1
&& s2
== end2
;
319 static void add_line_info(struct image
*img
, const char *bol
, size_t len
, unsigned flag
)
321 ALLOC_GROW(img
->line_allocated
, img
->nr
+ 1, img
->alloc
);
322 img
->line_allocated
[img
->nr
].len
= len
;
323 img
->line_allocated
[img
->nr
].hash
= hash_line(bol
, len
);
324 img
->line_allocated
[img
->nr
].flag
= flag
;
329 * "buf" has the file contents to be patched (read from various sources).
330 * attach it to "image" and add line-based index to it.
331 * "image" now owns the "buf".
333 static void prepare_image(struct image
*image
, char *buf
, size_t len
,
334 int prepare_linetable
)
338 memset(image
, 0, sizeof(*image
));
342 if (!prepare_linetable
)
345 ep
= image
->buf
+ image
->len
;
349 for (next
= cp
; next
< ep
&& *next
!= '\n'; next
++)
353 add_line_info(image
, cp
, next
- cp
, 0);
356 image
->line
= image
->line_allocated
;
359 static void clear_image(struct image
*image
)
362 free(image
->line_allocated
);
363 memset(image
, 0, sizeof(*image
));
366 /* fmt must contain _one_ %s and no other substitution */
367 static void say_patch_name(FILE *output
, const char *fmt
, struct patch
*patch
)
369 struct strbuf sb
= STRBUF_INIT
;
371 if (patch
->old_name
&& patch
->new_name
&&
372 strcmp(patch
->old_name
, patch
->new_name
)) {
373 quote_c_style(patch
->old_name
, &sb
, NULL
, 0);
374 strbuf_addstr(&sb
, " => ");
375 quote_c_style(patch
->new_name
, &sb
, NULL
, 0);
377 const char *n
= patch
->new_name
;
380 quote_c_style(n
, &sb
, NULL
, 0);
382 fprintf(output
, fmt
, sb
.buf
);
390 * apply.c isn't equipped to handle arbitrarily large patches, because
391 * it intermingles `unsigned long` with `int` for the type used to store
394 * Only process patches that are just shy of 1 GiB large in order to
395 * avoid any truncation or overflow issues.
397 #define MAX_APPLY_SIZE (1024UL * 1024 * 1023)
399 static int read_patch_file(struct strbuf
*sb
, int fd
)
401 if (strbuf_read(sb
, fd
, 0) < 0)
402 return error_errno(_("failed to read patch"));
403 else if (sb
->len
>= MAX_APPLY_SIZE
)
404 return error(_("patch too large"));
406 * Make sure that we have some slop in the buffer
407 * so that we can do speculative "memcmp" etc, and
408 * see to it that it is NUL-filled.
410 strbuf_grow(sb
, SLOP
);
411 memset(sb
->buf
+ sb
->len
, 0, SLOP
);
415 static unsigned long linelen(const char *buffer
, unsigned long size
)
417 unsigned long len
= 0;
420 if (*buffer
++ == '\n')
426 static int is_dev_null(const char *str
)
428 return skip_prefix(str
, "/dev/null", &str
) && isspace(*str
);
434 static int name_terminate(int c
, int terminate
)
436 if (c
== ' ' && !(terminate
& TERM_SPACE
))
438 if (c
== '\t' && !(terminate
& TERM_TAB
))
444 /* remove double slashes to make --index work with such filenames */
445 static char *squash_slash(char *name
)
453 if ((name
[j
++] = name
[i
++]) == '/')
454 while (name
[i
] == '/')
461 static char *find_name_gnu(struct strbuf
*root
,
465 struct strbuf name
= STRBUF_INIT
;
469 * Proposed "new-style" GNU patch/diff format; see
470 * https://lore.kernel.org/git/7vll0wvb2a.fsf@assigned-by-dhcp.cox.net/
472 if (unquote_c_style(&name
, line
, NULL
)) {
473 strbuf_release(&name
);
477 for (cp
= name
.buf
; p_value
; p_value
--) {
478 cp
= strchr(cp
, '/');
480 strbuf_release(&name
);
486 strbuf_remove(&name
, 0, cp
- name
.buf
);
488 strbuf_insert(&name
, 0, root
->buf
, root
->len
);
489 return squash_slash(strbuf_detach(&name
, NULL
));
492 static size_t sane_tz_len(const char *line
, size_t len
)
496 if (len
< strlen(" +0500") || line
[len
-strlen(" +0500")] != ' ')
498 tz
= line
+ len
- strlen(" +0500");
500 if (tz
[1] != '+' && tz
[1] != '-')
503 for (p
= tz
+ 2; p
!= line
+ len
; p
++)
507 return line
+ len
- tz
;
510 static size_t tz_with_colon_len(const char *line
, size_t len
)
514 if (len
< strlen(" +08:00") || line
[len
- strlen(":00")] != ':')
516 tz
= line
+ len
- strlen(" +08:00");
518 if (tz
[0] != ' ' || (tz
[1] != '+' && tz
[1] != '-'))
521 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
522 !isdigit(*p
++) || !isdigit(*p
++))
525 return line
+ len
- tz
;
528 static size_t date_len(const char *line
, size_t len
)
530 const char *date
, *p
;
532 if (len
< strlen("72-02-05") || line
[len
-strlen("-05")] != '-')
534 p
= date
= line
+ len
- strlen("72-02-05");
536 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
537 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
538 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a date. */
541 if (date
- line
>= strlen("19") &&
542 isdigit(date
[-1]) && isdigit(date
[-2])) /* 4-digit year */
543 date
-= strlen("19");
545 return line
+ len
- date
;
548 static size_t short_time_len(const char *line
, size_t len
)
550 const char *time
, *p
;
552 if (len
< strlen(" 07:01:32") || line
[len
-strlen(":32")] != ':')
554 p
= time
= line
+ len
- strlen(" 07:01:32");
556 /* Permit 1-digit hours? */
558 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
559 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
560 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a time. */
563 return line
+ len
- time
;
566 static size_t fractional_time_len(const char *line
, size_t len
)
571 /* Expected format: 19:41:17.620000023 */
572 if (!len
|| !isdigit(line
[len
- 1]))
576 /* Fractional seconds. */
577 while (p
> line
&& isdigit(*p
))
582 /* Hours, minutes, and whole seconds. */
583 n
= short_time_len(line
, p
- line
);
587 return line
+ len
- p
+ n
;
590 static size_t trailing_spaces_len(const char *line
, size_t len
)
594 /* Expected format: ' ' x (1 or more) */
595 if (!len
|| line
[len
- 1] != ' ')
602 return line
+ len
- (p
+ 1);
609 static size_t diff_timestamp_len(const char *line
, size_t len
)
611 const char *end
= line
+ len
;
615 * Posix: 2010-07-05 19:41:17
616 * GNU: 2010-07-05 19:41:17.620000023 -0500
619 if (!isdigit(end
[-1]))
622 n
= sane_tz_len(line
, end
- line
);
624 n
= tz_with_colon_len(line
, end
- line
);
627 n
= short_time_len(line
, end
- line
);
629 n
= fractional_time_len(line
, end
- line
);
632 n
= date_len(line
, end
- line
);
633 if (!n
) /* No date. Too bad. */
637 if (end
== line
) /* No space before date. */
639 if (end
[-1] == '\t') { /* Success! */
641 return line
+ len
- end
;
643 if (end
[-1] != ' ') /* No space before date. */
646 /* Whitespace damage. */
647 end
-= trailing_spaces_len(line
, end
- line
);
648 return line
+ len
- end
;
651 static char *find_name_common(struct strbuf
*root
,
659 const char *start
= NULL
;
663 while (line
!= end
) {
666 if (!end
&& isspace(c
)) {
669 if (name_terminate(c
, terminate
))
673 if (c
== '/' && !--p_value
)
677 return squash_slash(xstrdup_or_null(def
));
680 return squash_slash(xstrdup_or_null(def
));
683 * Generally we prefer the shorter name, especially
684 * if the other one is just a variation of that with
685 * something else tacked on to the end (ie "file.orig"
689 int deflen
= strlen(def
);
690 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
691 return squash_slash(xstrdup(def
));
695 char *ret
= xstrfmt("%s%.*s", root
->buf
, len
, start
);
696 return squash_slash(ret
);
699 return squash_slash(xmemdupz(start
, len
));
702 static char *find_name(struct strbuf
*root
,
709 char *name
= find_name_gnu(root
, line
, p_value
);
714 return find_name_common(root
, line
, def
, p_value
, NULL
, terminate
);
717 static char *find_name_traditional(struct strbuf
*root
,
726 char *name
= find_name_gnu(root
, line
, p_value
);
731 len
= strchrnul(line
, '\n') - line
;
732 date_len
= diff_timestamp_len(line
, len
);
734 return find_name_common(root
, line
, def
, p_value
, NULL
, TERM_TAB
);
737 return find_name_common(root
, line
, def
, p_value
, line
+ len
, 0);
741 * Given the string after "--- " or "+++ ", guess the appropriate
742 * p_value for the given patch.
744 static int guess_p_value(struct apply_state
*state
, const char *nameline
)
749 if (is_dev_null(nameline
))
751 name
= find_name_traditional(&state
->root
, nameline
, NULL
, 0);
754 cp
= strchr(name
, '/');
757 else if (state
->prefix
) {
759 * Does it begin with "a/$our-prefix" and such? Then this is
760 * very likely to apply to our directory.
762 if (starts_with(name
, state
->prefix
))
763 val
= count_slashes(state
->prefix
);
766 if (starts_with(cp
, state
->prefix
))
767 val
= count_slashes(state
->prefix
) + 1;
775 * Does the ---/+++ line have the POSIX timestamp after the last HT?
776 * GNU diff puts epoch there to signal a creation/deletion event. Is
777 * this such a timestamp?
779 static int has_epoch_timestamp(const char *nameline
)
782 * We are only interested in epoch timestamp; any non-zero
783 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
784 * For the same reason, the date must be either 1969-12-31 or
785 * 1970-01-01, and the seconds part must be "00".
787 const char stamp_regexp
[] =
788 "^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?"
790 "([-+][0-2][0-9]:?[0-5][0-9])\n";
791 const char *timestamp
= NULL
, *cp
, *colon
;
792 static regex_t
*stamp
;
794 int zoneoffset
, epoch_hour
, hour
, minute
;
797 for (cp
= nameline
; *cp
!= '\n'; cp
++) {
805 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
806 * (west of GMT) or 1970-01-01 (east of GMT)
808 if (skip_prefix(timestamp
, "1969-12-31 ", ×tamp
))
810 else if (skip_prefix(timestamp
, "1970-01-01 ", ×tamp
))
816 stamp
= xmalloc(sizeof(*stamp
));
817 if (regcomp(stamp
, stamp_regexp
, REG_EXTENDED
)) {
818 warning(_("Cannot prepare timestamp regexp %s"),
824 status
= regexec(stamp
, timestamp
, ARRAY_SIZE(m
), m
, 0);
826 if (status
!= REG_NOMATCH
)
827 warning(_("regexec returned %d for input: %s"),
832 hour
= strtol(timestamp
, NULL
, 10);
833 minute
= strtol(timestamp
+ m
[1].rm_so
, NULL
, 10);
835 zoneoffset
= strtol(timestamp
+ m
[3].rm_so
+ 1, (char **) &colon
, 10);
837 zoneoffset
= zoneoffset
* 60 + strtol(colon
+ 1, NULL
, 10);
839 zoneoffset
= (zoneoffset
/ 100) * 60 + (zoneoffset
% 100);
840 if (timestamp
[m
[3].rm_so
] == '-')
841 zoneoffset
= -zoneoffset
;
843 return hour
* 60 + minute
- zoneoffset
== epoch_hour
* 60;
847 * Get the name etc info from the ---/+++ lines of a traditional patch header
849 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
850 * files, we can happily check the index for a match, but for creating a
851 * new file we should try to match whatever "patch" does. I have no idea.
853 static int parse_traditional_patch(struct apply_state
*state
,
860 first
+= 4; /* skip "--- " */
861 second
+= 4; /* skip "+++ " */
862 if (!state
->p_value_known
) {
864 p
= guess_p_value(state
, first
);
865 q
= guess_p_value(state
, second
);
867 if (0 <= p
&& p
== q
) {
869 state
->p_value_known
= 1;
872 if (is_dev_null(first
)) {
874 patch
->is_delete
= 0;
875 name
= find_name_traditional(&state
->root
, second
, NULL
, state
->p_value
);
876 patch
->new_name
= name
;
877 } else if (is_dev_null(second
)) {
879 patch
->is_delete
= 1;
880 name
= find_name_traditional(&state
->root
, first
, NULL
, state
->p_value
);
881 patch
->old_name
= name
;
884 first_name
= find_name_traditional(&state
->root
, first
, NULL
, state
->p_value
);
885 name
= find_name_traditional(&state
->root
, second
, first_name
, state
->p_value
);
887 if (has_epoch_timestamp(first
)) {
889 patch
->is_delete
= 0;
890 patch
->new_name
= name
;
891 } else if (has_epoch_timestamp(second
)) {
893 patch
->is_delete
= 1;
894 patch
->old_name
= name
;
896 patch
->old_name
= name
;
897 patch
->new_name
= xstrdup_or_null(name
);
901 return error(_("unable to find filename in patch at line %d"), state
->linenr
);
906 static int gitdiff_hdrend(struct gitdiff_data
*state UNUSED
,
907 const char *line UNUSED
,
908 struct patch
*patch UNUSED
)
914 * We're anal about diff header consistency, to make
915 * sure that we don't end up having strange ambiguous
916 * patches floating around.
918 * As a result, gitdiff_{old|new}name() will check
919 * their names against any previous information, just
922 #define DIFF_OLD_NAME 0
923 #define DIFF_NEW_NAME 1
925 static int gitdiff_verify_name(struct gitdiff_data
*state
,
931 if (!*name
&& !isnull
) {
932 *name
= find_name(state
->root
, line
, NULL
, state
->p_value
, TERM_TAB
);
939 return error(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
940 *name
, state
->linenr
);
941 another
= find_name(state
->root
, line
, NULL
, state
->p_value
, TERM_TAB
);
942 if (!another
|| strcmp(another
, *name
)) {
944 return error((side
== DIFF_NEW_NAME
) ?
945 _("git apply: bad git-diff - inconsistent new filename on line %d") :
946 _("git apply: bad git-diff - inconsistent old filename on line %d"), state
->linenr
);
950 if (!is_dev_null(line
))
951 return error(_("git apply: bad git-diff - expected /dev/null on line %d"), state
->linenr
);
957 static int gitdiff_oldname(struct gitdiff_data
*state
,
961 return gitdiff_verify_name(state
, line
,
962 patch
->is_new
, &patch
->old_name
,
966 static int gitdiff_newname(struct gitdiff_data
*state
,
970 return gitdiff_verify_name(state
, line
,
971 patch
->is_delete
, &patch
->new_name
,
975 static int parse_mode_line(const char *line
, int linenr
, unsigned int *mode
)
978 *mode
= strtoul(line
, &end
, 8);
979 if (end
== line
|| !isspace(*end
))
980 return error(_("invalid mode on line %d: %s"), linenr
, line
);
984 static int gitdiff_oldmode(struct gitdiff_data
*state
,
988 return parse_mode_line(line
, state
->linenr
, &patch
->old_mode
);
991 static int gitdiff_newmode(struct gitdiff_data
*state
,
995 return parse_mode_line(line
, state
->linenr
, &patch
->new_mode
);
998 static int gitdiff_delete(struct gitdiff_data
*state
,
1000 struct patch
*patch
)
1002 patch
->is_delete
= 1;
1003 free(patch
->old_name
);
1004 patch
->old_name
= xstrdup_or_null(patch
->def_name
);
1005 return gitdiff_oldmode(state
, line
, patch
);
1008 static int gitdiff_newfile(struct gitdiff_data
*state
,
1010 struct patch
*patch
)
1013 free(patch
->new_name
);
1014 patch
->new_name
= xstrdup_or_null(patch
->def_name
);
1015 return gitdiff_newmode(state
, line
, patch
);
1018 static int gitdiff_copysrc(struct gitdiff_data
*state
,
1020 struct patch
*patch
)
1023 free(patch
->old_name
);
1024 patch
->old_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1028 static int gitdiff_copydst(struct gitdiff_data
*state
,
1030 struct patch
*patch
)
1033 free(patch
->new_name
);
1034 patch
->new_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1038 static int gitdiff_renamesrc(struct gitdiff_data
*state
,
1040 struct patch
*patch
)
1042 patch
->is_rename
= 1;
1043 free(patch
->old_name
);
1044 patch
->old_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1048 static int gitdiff_renamedst(struct gitdiff_data
*state
,
1050 struct patch
*patch
)
1052 patch
->is_rename
= 1;
1053 free(patch
->new_name
);
1054 patch
->new_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1058 static int gitdiff_similarity(struct gitdiff_data
*state UNUSED
,
1060 struct patch
*patch
)
1062 unsigned long val
= strtoul(line
, NULL
, 10);
1068 static int gitdiff_dissimilarity(struct gitdiff_data
*state UNUSED
,
1070 struct patch
*patch
)
1072 unsigned long val
= strtoul(line
, NULL
, 10);
1078 static int gitdiff_index(struct gitdiff_data
*state
,
1080 struct patch
*patch
)
1083 * index line is N hexadecimal, "..", N hexadecimal,
1084 * and optional space with octal mode.
1086 const char *ptr
, *eol
;
1088 const unsigned hexsz
= the_hash_algo
->hexsz
;
1090 ptr
= strchr(line
, '.');
1091 if (!ptr
|| ptr
[1] != '.' || hexsz
< ptr
- line
)
1094 memcpy(patch
->old_oid_prefix
, line
, len
);
1095 patch
->old_oid_prefix
[len
] = 0;
1098 ptr
= strchr(line
, ' ');
1099 eol
= strchrnul(line
, '\n');
1101 if (!ptr
|| eol
< ptr
)
1107 memcpy(patch
->new_oid_prefix
, line
, len
);
1108 patch
->new_oid_prefix
[len
] = 0;
1110 return gitdiff_oldmode(state
, ptr
+ 1, patch
);
1115 * This is normal for a diff that doesn't change anything: we'll fall through
1116 * into the next diff. Tell the parser to break out.
1118 static int gitdiff_unrecognized(struct gitdiff_data
*state UNUSED
,
1119 const char *line UNUSED
,
1120 struct patch
*patch UNUSED
)
1126 * Skip p_value leading components from "line"; as we do not accept
1127 * absolute paths, return NULL in that case.
1129 static const char *skip_tree_prefix(int p_value
,
1137 return (llen
&& line
[0] == '/') ? NULL
: line
;
1140 for (i
= 0; i
< llen
; i
++) {
1142 if (ch
== '/' && --nslash
<= 0)
1143 return (i
== 0) ? NULL
: &line
[i
+ 1];
1149 * This is to extract the same name that appears on "diff --git"
1150 * line. We do not find and return anything if it is a rename
1151 * patch, and it is OK because we will find the name elsewhere.
1152 * We need to reliably find name only when it is mode-change only,
1153 * creation or deletion of an empty file. In any of these cases,
1154 * both sides are the same name under a/ and b/ respectively.
1156 static char *git_header_name(int p_value
,
1161 const char *second
= NULL
;
1162 size_t len
, line_len
;
1164 line
+= strlen("diff --git ");
1165 llen
-= strlen("diff --git ");
1169 struct strbuf first
= STRBUF_INIT
;
1170 struct strbuf sp
= STRBUF_INIT
;
1172 if (unquote_c_style(&first
, line
, &second
))
1173 goto free_and_fail1
;
1175 /* strip the a/b prefix including trailing slash */
1176 cp
= skip_tree_prefix(p_value
, first
.buf
, first
.len
);
1178 goto free_and_fail1
;
1179 strbuf_remove(&first
, 0, cp
- first
.buf
);
1182 * second points at one past closing dq of name.
1183 * find the second name.
1185 while ((second
< line
+ llen
) && isspace(*second
))
1188 if (line
+ llen
<= second
)
1189 goto free_and_fail1
;
1190 if (*second
== '"') {
1191 if (unquote_c_style(&sp
, second
, NULL
))
1192 goto free_and_fail1
;
1193 cp
= skip_tree_prefix(p_value
, sp
.buf
, sp
.len
);
1195 goto free_and_fail1
;
1196 /* They must match, otherwise ignore */
1197 if (strcmp(cp
, first
.buf
))
1198 goto free_and_fail1
;
1199 strbuf_release(&sp
);
1200 return strbuf_detach(&first
, NULL
);
1203 /* unquoted second */
1204 cp
= skip_tree_prefix(p_value
, second
, line
+ llen
- second
);
1206 goto free_and_fail1
;
1207 if (line
+ llen
- cp
!= first
.len
||
1208 memcmp(first
.buf
, cp
, first
.len
))
1209 goto free_and_fail1
;
1210 return strbuf_detach(&first
, NULL
);
1213 strbuf_release(&first
);
1214 strbuf_release(&sp
);
1218 /* unquoted first name */
1219 name
= skip_tree_prefix(p_value
, line
, llen
);
1224 * since the first name is unquoted, a dq if exists must be
1225 * the beginning of the second name.
1227 for (second
= name
; second
< line
+ llen
; second
++) {
1228 if (*second
== '"') {
1229 struct strbuf sp
= STRBUF_INIT
;
1232 if (unquote_c_style(&sp
, second
, NULL
))
1233 goto free_and_fail2
;
1235 np
= skip_tree_prefix(p_value
, sp
.buf
, sp
.len
);
1237 goto free_and_fail2
;
1239 len
= sp
.buf
+ sp
.len
- np
;
1240 if (len
< second
- name
&&
1241 !strncmp(np
, name
, len
) &&
1242 isspace(name
[len
])) {
1244 strbuf_remove(&sp
, 0, np
- sp
.buf
);
1245 return strbuf_detach(&sp
, NULL
);
1249 strbuf_release(&sp
);
1255 * Accept a name only if it shows up twice, exactly the same
1258 second
= strchr(name
, '\n');
1261 line_len
= second
- name
;
1262 for (len
= 0 ; ; len
++) {
1263 switch (name
[len
]) {
1268 case '\t': case ' ':
1270 * Is this the separator between the preimage
1271 * and the postimage pathname? Again, we are
1272 * only interested in the case where there is
1273 * no rename, as this is only to set def_name
1274 * and a rename patch has the names elsewhere
1275 * in an unambiguous form.
1278 return NULL
; /* no postimage name */
1279 second
= skip_tree_prefix(p_value
, name
+ len
+ 1,
1280 line_len
- (len
+ 1));
1284 * Does len bytes starting at "name" and "second"
1285 * (that are separated by one HT or SP we just
1286 * found) exactly match?
1288 if (second
[len
] == '\n' && !strncmp(name
, second
, len
))
1289 return xmemdupz(name
, len
);
1294 static int check_header_line(int linenr
, struct patch
*patch
)
1296 int extensions
= (patch
->is_delete
== 1) + (patch
->is_new
== 1) +
1297 (patch
->is_rename
== 1) + (patch
->is_copy
== 1);
1299 return error(_("inconsistent header lines %d and %d"),
1300 patch
->extension_linenr
, linenr
);
1301 if (extensions
&& !patch
->extension_linenr
)
1302 patch
->extension_linenr
= linenr
;
1306 int parse_git_diff_header(struct strbuf
*root
,
1312 struct patch
*patch
)
1314 unsigned long offset
;
1315 struct gitdiff_data parse_hdr_state
;
1317 /* A git diff has explicit new/delete information, so we don't guess */
1319 patch
->is_delete
= 0;
1322 * Some things may not have the old name in the
1323 * rest of the headers anywhere (pure mode changes,
1324 * or removing or adding empty files), so we get
1325 * the default name from the header.
1327 patch
->def_name
= git_header_name(p_value
, line
, len
);
1328 if (patch
->def_name
&& root
->len
) {
1329 char *s
= xstrfmt("%s%s", root
->buf
, patch
->def_name
);
1330 free(patch
->def_name
);
1331 patch
->def_name
= s
;
1337 parse_hdr_state
.root
= root
;
1338 parse_hdr_state
.linenr
= *linenr
;
1339 parse_hdr_state
.p_value
= p_value
;
1341 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, (*linenr
)++) {
1342 static const struct opentry
{
1344 int (*fn
)(struct gitdiff_data
*, const char *, struct patch
*);
1346 { "@@ -", gitdiff_hdrend
},
1347 { "--- ", gitdiff_oldname
},
1348 { "+++ ", gitdiff_newname
},
1349 { "old mode ", gitdiff_oldmode
},
1350 { "new mode ", gitdiff_newmode
},
1351 { "deleted file mode ", gitdiff_delete
},
1352 { "new file mode ", gitdiff_newfile
},
1353 { "copy from ", gitdiff_copysrc
},
1354 { "copy to ", gitdiff_copydst
},
1355 { "rename old ", gitdiff_renamesrc
},
1356 { "rename new ", gitdiff_renamedst
},
1357 { "rename from ", gitdiff_renamesrc
},
1358 { "rename to ", gitdiff_renamedst
},
1359 { "similarity index ", gitdiff_similarity
},
1360 { "dissimilarity index ", gitdiff_dissimilarity
},
1361 { "index ", gitdiff_index
},
1362 { "", gitdiff_unrecognized
},
1366 len
= linelen(line
, size
);
1367 if (!len
|| line
[len
-1] != '\n')
1369 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
1370 const struct opentry
*p
= optable
+ i
;
1371 int oplen
= strlen(p
->str
);
1373 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
1375 res
= p
->fn(&parse_hdr_state
, line
+ oplen
, patch
);
1378 if (check_header_line(*linenr
, patch
))
1387 if (!patch
->old_name
&& !patch
->new_name
) {
1388 if (!patch
->def_name
) {
1389 error(Q_("git diff header lacks filename information when removing "
1390 "%d leading pathname component (line %d)",
1391 "git diff header lacks filename information when removing "
1392 "%d leading pathname components (line %d)",
1393 parse_hdr_state
.p_value
),
1394 parse_hdr_state
.p_value
, *linenr
);
1397 patch
->old_name
= xstrdup(patch
->def_name
);
1398 patch
->new_name
= xstrdup(patch
->def_name
);
1400 if ((!patch
->new_name
&& !patch
->is_delete
) ||
1401 (!patch
->old_name
&& !patch
->is_new
)) {
1402 error(_("git diff header lacks filename information "
1403 "(line %d)"), *linenr
);
1406 patch
->is_toplevel_relative
= 1;
1410 static int parse_num(const char *line
, unsigned long *p
)
1414 if (!isdigit(*line
))
1416 *p
= strtoul(line
, &ptr
, 10);
1420 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
1421 unsigned long *p1
, unsigned long *p2
)
1425 if (offset
< 0 || offset
>= len
)
1430 digits
= parse_num(line
, p1
);
1440 digits
= parse_num(line
+1, p2
);
1449 ex
= strlen(expect
);
1452 if (memcmp(line
, expect
, ex
))
1458 static void recount_diff(const char *line
, int size
, struct fragment
*fragment
)
1460 int oldlines
= 0, newlines
= 0, ret
= 0;
1463 warning("recount: ignore empty hunk");
1468 int len
= linelen(line
, size
);
1476 case ' ': case '\n':
1488 ret
= size
< 3 || !starts_with(line
, "@@ ");
1491 ret
= size
< 5 || !starts_with(line
, "diff ");
1498 warning(_("recount: unexpected line: %.*s"),
1499 (int)linelen(line
, size
), line
);
1504 fragment
->oldlines
= oldlines
;
1505 fragment
->newlines
= newlines
;
1509 * Parse a unified diff fragment header of the
1510 * form "@@ -a,b +c,d @@"
1512 static int parse_fragment_header(const char *line
, int len
, struct fragment
*fragment
)
1516 if (!len
|| line
[len
-1] != '\n')
1519 /* Figure out the number of lines in a fragment */
1520 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
1521 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
1527 * Find file diff header
1530 * -1 if no header was found
1531 * -128 in case of error
1532 * the size of the header in bytes (called "offset") otherwise
1534 static int find_header(struct apply_state
*state
,
1538 struct patch
*patch
)
1540 unsigned long offset
, len
;
1542 patch
->is_toplevel_relative
= 0;
1543 patch
->is_rename
= patch
->is_copy
= 0;
1544 patch
->is_new
= patch
->is_delete
= -1;
1545 patch
->old_mode
= patch
->new_mode
= 0;
1546 patch
->old_name
= patch
->new_name
= NULL
;
1547 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1548 unsigned long nextlen
;
1550 len
= linelen(line
, size
);
1554 /* Testing this early allows us to take a few shortcuts.. */
1559 * Make sure we don't find any unconnected patch fragments.
1560 * That's a sign that we didn't find a header, and that a
1561 * patch has become corrupted/broken up.
1563 if (!memcmp("@@ -", line
, 4)) {
1564 struct fragment dummy
;
1565 if (parse_fragment_header(line
, len
, &dummy
) < 0)
1567 error(_("patch fragment without header at line %d: %.*s"),
1568 state
->linenr
, (int)len
-1, line
);
1576 * Git patch? It might not have a real patch, just a rename
1577 * or mode change, so we handle that specially
1579 if (!memcmp("diff --git ", line
, 11)) {
1580 int git_hdr_len
= parse_git_diff_header(&state
->root
, &state
->linenr
,
1581 state
->p_value
, line
, len
,
1583 if (git_hdr_len
< 0)
1585 if (git_hdr_len
<= len
)
1587 *hdrsize
= git_hdr_len
;
1591 /* --- followed by +++ ? */
1592 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
1596 * We only accept unified patches, so we want it to
1597 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1598 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1600 nextlen
= linelen(line
+ len
, size
- len
);
1601 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
1604 /* Ok, we'll consider it a patch */
1605 if (parse_traditional_patch(state
, line
, line
+len
, patch
))
1607 *hdrsize
= len
+ nextlen
;
1614 static void record_ws_error(struct apply_state
*state
,
1625 state
->whitespace_error
++;
1626 if (state
->squelch_whitespace_errors
&&
1627 state
->squelch_whitespace_errors
< state
->whitespace_error
)
1630 err
= whitespace_error_string(result
);
1631 if (state
->apply_verbosity
> verbosity_silent
)
1632 fprintf(stderr
, "%s:%d: %s.\n%.*s\n",
1633 state
->patch_input_file
, linenr
, err
, len
, line
);
1637 static void check_whitespace(struct apply_state
*state
,
1642 unsigned result
= ws_check(line
+ 1, len
- 1, ws_rule
);
1644 record_ws_error(state
, result
, line
+ 1, len
- 2, state
->linenr
);
1648 * Check if the patch has context lines with CRLF or
1649 * the patch wants to remove lines with CRLF.
1651 static void check_old_for_crlf(struct patch
*patch
, const char *line
, int len
)
1653 if (len
>= 2 && line
[len
-1] == '\n' && line
[len
-2] == '\r') {
1654 patch
->ws_rule
|= WS_CR_AT_EOL
;
1655 patch
->crlf_in_old
= 1;
1661 * Parse a unified diff. Note that this really needs to parse each
1662 * fragment separately, since the only way to know the difference
1663 * between a "---" that is part of a patch, and a "---" that starts
1664 * the next patch is to look at the line counts..
1666 static int parse_fragment(struct apply_state
*state
,
1669 struct patch
*patch
,
1670 struct fragment
*fragment
)
1673 int len
= linelen(line
, size
), offset
;
1674 unsigned long oldlines
, newlines
;
1675 unsigned long leading
, trailing
;
1677 offset
= parse_fragment_header(line
, len
, fragment
);
1680 if (offset
> 0 && patch
->recount
)
1681 recount_diff(line
+ offset
, size
- offset
, fragment
);
1682 oldlines
= fragment
->oldlines
;
1683 newlines
= fragment
->newlines
;
1687 /* Parse the thing.. */
1691 added
= deleted
= 0;
1694 offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1695 if (!oldlines
&& !newlines
)
1697 len
= linelen(line
, size
);
1698 if (!len
|| line
[len
-1] != '\n')
1703 case '\n': /* newer GNU diff, an empty context line */
1707 if (!deleted
&& !added
)
1710 check_old_for_crlf(patch
, line
, len
);
1711 if (!state
->apply_in_reverse
&&
1712 state
->ws_error_action
== correct_ws_error
)
1713 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1716 if (!state
->apply_in_reverse
)
1717 check_old_for_crlf(patch
, line
, len
);
1718 if (state
->apply_in_reverse
&&
1719 state
->ws_error_action
!= nowarn_ws_error
)
1720 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1726 if (state
->apply_in_reverse
)
1727 check_old_for_crlf(patch
, line
, len
);
1728 if (!state
->apply_in_reverse
&&
1729 state
->ws_error_action
!= nowarn_ws_error
)
1730 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1737 * We allow "\ No newline at end of file". Depending
1738 * on locale settings when the patch was produced we
1739 * don't know what this line looks like. The only
1740 * thing we do know is that it begins with "\ ".
1741 * Checking for 12 is just for sanity check -- any
1742 * l10n of "\ No newline..." is at least that long.
1745 if (len
< 12 || memcmp(line
, "\\ ", 2))
1750 if (oldlines
|| newlines
)
1752 if (!patch
->recount
&& !deleted
&& !added
)
1755 fragment
->leading
= leading
;
1756 fragment
->trailing
= trailing
;
1759 * If a fragment ends with an incomplete line, we failed to include
1760 * it in the above loop because we hit oldlines == newlines == 0
1763 if (12 < size
&& !memcmp(line
, "\\ ", 2))
1764 offset
+= linelen(line
, size
);
1766 patch
->lines_added
+= added
;
1767 patch
->lines_deleted
+= deleted
;
1769 if (0 < patch
->is_new
&& oldlines
)
1770 return error(_("new file depends on old contents"));
1771 if (0 < patch
->is_delete
&& newlines
)
1772 return error(_("deleted file still has contents"));
1777 * We have seen "diff --git a/... b/..." header (or a traditional patch
1778 * header). Read hunks that belong to this patch into fragments and hang
1779 * them to the given patch structure.
1781 * The (fragment->patch, fragment->size) pair points into the memory given
1782 * by the caller, not a copy, when we return.
1785 * -1 in case of error,
1786 * the number of bytes in the patch otherwise.
1788 static int parse_single_patch(struct apply_state
*state
,
1791 struct patch
*patch
)
1793 unsigned long offset
= 0;
1794 unsigned long oldlines
= 0, newlines
= 0, context
= 0;
1795 struct fragment
**fragp
= &patch
->fragments
;
1797 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
1798 struct fragment
*fragment
;
1801 CALLOC_ARRAY(fragment
, 1);
1802 fragment
->linenr
= state
->linenr
;
1803 len
= parse_fragment(state
, line
, size
, patch
, fragment
);
1806 return error(_("corrupt patch at line %d"), state
->linenr
);
1808 fragment
->patch
= line
;
1809 fragment
->size
= len
;
1810 oldlines
+= fragment
->oldlines
;
1811 newlines
+= fragment
->newlines
;
1812 context
+= fragment
->leading
+ fragment
->trailing
;
1815 fragp
= &fragment
->next
;
1823 * If something was removed (i.e. we have old-lines) it cannot
1824 * be creation, and if something was added it cannot be
1825 * deletion. However, the reverse is not true; --unified=0
1826 * patches that only add are not necessarily creation even
1827 * though they do not have any old lines, and ones that only
1828 * delete are not necessarily deletion.
1830 * Unfortunately, a real creation/deletion patch do _not_ have
1831 * any context line by definition, so we cannot safely tell it
1832 * apart with --unified=0 insanity. At least if the patch has
1833 * more than one hunk it is not creation or deletion.
1835 if (patch
->is_new
< 0 &&
1836 (oldlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1838 if (patch
->is_delete
< 0 &&
1839 (newlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1840 patch
->is_delete
= 0;
1842 if (0 < patch
->is_new
&& oldlines
)
1843 return error(_("new file %s depends on old contents"), patch
->new_name
);
1844 if (0 < patch
->is_delete
&& newlines
)
1845 return error(_("deleted file %s still has contents"), patch
->old_name
);
1846 if (!patch
->is_delete
&& !newlines
&& context
&& state
->apply_verbosity
> verbosity_silent
)
1849 "file %s becomes empty but is not deleted"),
1855 static inline int metadata_changes(struct patch
*patch
)
1857 return patch
->is_rename
> 0 ||
1858 patch
->is_copy
> 0 ||
1859 patch
->is_new
> 0 ||
1861 (patch
->old_mode
&& patch
->new_mode
&&
1862 patch
->old_mode
!= patch
->new_mode
);
1865 static char *inflate_it(const void *data
, unsigned long size
,
1866 unsigned long inflated_size
)
1872 memset(&stream
, 0, sizeof(stream
));
1874 stream
.next_in
= (unsigned char *)data
;
1875 stream
.avail_in
= size
;
1876 stream
.next_out
= out
= xmalloc(inflated_size
);
1877 stream
.avail_out
= inflated_size
;
1878 git_inflate_init(&stream
);
1879 st
= git_inflate(&stream
, Z_FINISH
);
1880 git_inflate_end(&stream
);
1881 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1889 * Read a binary hunk and return a new fragment; fragment->patch
1890 * points at an allocated memory that the caller must free, so
1891 * it is marked as "->free_patch = 1".
1893 static struct fragment
*parse_binary_hunk(struct apply_state
*state
,
1895 unsigned long *sz_p
,
1900 * Expect a line that begins with binary patch method ("literal"
1901 * or "delta"), followed by the length of data before deflating.
1902 * a sequence of 'length-byte' followed by base-85 encoded data
1903 * should follow, terminated by a newline.
1905 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1906 * and we would limit the patch line to 66 characters,
1907 * so one line can fit up to 13 groups that would decode
1908 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1909 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1912 unsigned long size
= *sz_p
;
1913 char *buffer
= *buf_p
;
1915 unsigned long origlen
;
1918 struct fragment
*frag
;
1920 llen
= linelen(buffer
, size
);
1925 if (starts_with(buffer
, "delta ")) {
1926 patch_method
= BINARY_DELTA_DEFLATED
;
1927 origlen
= strtoul(buffer
+ 6, NULL
, 10);
1929 else if (starts_with(buffer
, "literal ")) {
1930 patch_method
= BINARY_LITERAL_DEFLATED
;
1931 origlen
= strtoul(buffer
+ 8, NULL
, 10);
1940 int byte_length
, max_byte_length
, newsize
;
1941 llen
= linelen(buffer
, size
);
1945 /* consume the blank line */
1951 * Minimum line is "A00000\n" which is 7-byte long,
1952 * and the line length must be multiple of 5 plus 2.
1954 if ((llen
< 7) || (llen
-2) % 5)
1956 max_byte_length
= (llen
- 2) / 5 * 4;
1957 byte_length
= *buffer
;
1958 if ('A' <= byte_length
&& byte_length
<= 'Z')
1959 byte_length
= byte_length
- 'A' + 1;
1960 else if ('a' <= byte_length
&& byte_length
<= 'z')
1961 byte_length
= byte_length
- 'a' + 27;
1964 /* if the input length was not multiple of 4, we would
1965 * have filler at the end but the filler should never
1968 if (max_byte_length
< byte_length
||
1969 byte_length
<= max_byte_length
- 4)
1971 newsize
= hunk_size
+ byte_length
;
1972 data
= xrealloc(data
, newsize
);
1973 if (decode_85(data
+ hunk_size
, buffer
+ 1, byte_length
))
1975 hunk_size
= newsize
;
1980 CALLOC_ARRAY(frag
, 1);
1981 frag
->patch
= inflate_it(data
, hunk_size
, origlen
);
1982 frag
->free_patch
= 1;
1986 frag
->size
= origlen
;
1990 frag
->binary_patch_method
= patch_method
;
1996 error(_("corrupt binary patch at line %d: %.*s"),
1997 state
->linenr
-1, llen
-1, buffer
);
2003 * -1 in case of error,
2004 * the length of the parsed binary patch otherwise
2006 static int parse_binary(struct apply_state
*state
,
2009 struct patch
*patch
)
2012 * We have read "GIT binary patch\n"; what follows is a line
2013 * that says the patch method (currently, either "literal" or
2014 * "delta") and the length of data before deflating; a
2015 * sequence of 'length-byte' followed by base-85 encoded data
2018 * When a binary patch is reversible, there is another binary
2019 * hunk in the same format, starting with patch method (either
2020 * "literal" or "delta") with the length of data, and a sequence
2021 * of length-byte + base-85 encoded data, terminated with another
2022 * empty line. This data, when applied to the postimage, produces
2025 struct fragment
*forward
;
2026 struct fragment
*reverse
;
2030 forward
= parse_binary_hunk(state
, &buffer
, &size
, &status
, &used
);
2031 if (!forward
&& !status
)
2032 /* there has to be one hunk (forward hunk) */
2033 return error(_("unrecognized binary patch at line %d"), state
->linenr
-1);
2035 /* otherwise we already gave an error message */
2038 reverse
= parse_binary_hunk(state
, &buffer
, &size
, &status
, &used_1
);
2043 * Not having reverse hunk is not an error, but having
2044 * a corrupt reverse hunk is.
2046 free((void*) forward
->patch
);
2050 forward
->next
= reverse
;
2051 patch
->fragments
= forward
;
2052 patch
->is_binary
= 1;
2056 static void prefix_one(struct apply_state
*state
, char **name
)
2058 char *old_name
= *name
;
2061 *name
= prefix_filename(state
->prefix
, *name
);
2065 static void prefix_patch(struct apply_state
*state
, struct patch
*p
)
2067 if (!state
->prefix
|| p
->is_toplevel_relative
)
2069 prefix_one(state
, &p
->new_name
);
2070 prefix_one(state
, &p
->old_name
);
2077 static void add_name_limit(struct apply_state
*state
,
2081 struct string_list_item
*it
;
2083 it
= string_list_append(&state
->limit_by_name
, name
);
2084 it
->util
= exclude
? NULL
: (void *) 1;
2087 static int use_patch(struct apply_state
*state
, struct patch
*p
)
2089 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
2092 /* Paths outside are not touched regardless of "--include" */
2093 if (state
->prefix
&& *state
->prefix
) {
2095 if (!skip_prefix(pathname
, state
->prefix
, &rest
) || !*rest
)
2099 /* See if it matches any of exclude/include rule */
2100 for (i
= 0; i
< state
->limit_by_name
.nr
; i
++) {
2101 struct string_list_item
*it
= &state
->limit_by_name
.items
[i
];
2102 if (!wildmatch(it
->string
, pathname
, 0))
2103 return (it
->util
!= NULL
);
2107 * If we had any include, a path that does not match any rule is
2108 * not used. Otherwise, we saw bunch of exclude rules (or none)
2109 * and such a path is used.
2111 return !state
->has_include
;
2115 * Read the patch text in "buffer" that extends for "size" bytes; stop
2116 * reading after seeing a single patch (i.e. changes to a single file).
2117 * Create fragments (i.e. patch hunks) and hang them to the given patch.
2120 * -1 if no header was found or parse_binary() failed,
2121 * -128 on another error,
2122 * the number of bytes consumed otherwise,
2123 * so that the caller can call us again for the next patch.
2125 static int parse_chunk(struct apply_state
*state
, char *buffer
, unsigned long size
, struct patch
*patch
)
2127 int hdrsize
, patchsize
;
2128 int offset
= find_header(state
, buffer
, size
, &hdrsize
, patch
);
2133 prefix_patch(state
, patch
);
2135 if (!use_patch(state
, patch
))
2137 else if (patch
->new_name
)
2138 patch
->ws_rule
= whitespace_rule(state
->repo
->index
,
2141 patch
->ws_rule
= whitespace_rule(state
->repo
->index
,
2144 patchsize
= parse_single_patch(state
,
2145 buffer
+ offset
+ hdrsize
,
2146 size
- offset
- hdrsize
,
2153 static const char git_binary
[] = "GIT binary patch\n";
2154 int hd
= hdrsize
+ offset
;
2155 unsigned long llen
= linelen(buffer
+ hd
, size
- hd
);
2157 if (llen
== sizeof(git_binary
) - 1 &&
2158 !memcmp(git_binary
, buffer
+ hd
, llen
)) {
2161 used
= parse_binary(state
, buffer
+ hd
+ llen
,
2162 size
- hd
- llen
, patch
);
2166 patchsize
= used
+ llen
;
2170 else if (!memcmp(" differ\n", buffer
+ hd
+ llen
- 8, 8)) {
2171 static const char *binhdr
[] = {
2177 for (i
= 0; binhdr
[i
]; i
++) {
2178 int len
= strlen(binhdr
[i
]);
2179 if (len
< size
- hd
&&
2180 !memcmp(binhdr
[i
], buffer
+ hd
, len
)) {
2182 patch
->is_binary
= 1;
2189 /* Empty patch cannot be applied if it is a text patch
2190 * without metadata change. A binary patch appears
2193 if ((state
->apply
|| state
->check
) &&
2194 (!patch
->is_binary
&& !metadata_changes(patch
))) {
2195 error(_("patch with only garbage at line %d"), state
->linenr
);
2200 return offset
+ hdrsize
+ patchsize
;
2203 static void reverse_patches(struct patch
*p
)
2205 for (; p
; p
= p
->next
) {
2206 struct fragment
*frag
= p
->fragments
;
2208 SWAP(p
->new_name
, p
->old_name
);
2209 SWAP(p
->new_mode
, p
->old_mode
);
2210 SWAP(p
->is_new
, p
->is_delete
);
2211 SWAP(p
->lines_added
, p
->lines_deleted
);
2212 SWAP(p
->old_oid_prefix
, p
->new_oid_prefix
);
2214 for (; frag
; frag
= frag
->next
) {
2215 SWAP(frag
->newpos
, frag
->oldpos
);
2216 SWAP(frag
->newlines
, frag
->oldlines
);
2221 static const char pluses
[] =
2222 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2223 static const char minuses
[]=
2224 "----------------------------------------------------------------------";
2226 static void show_stats(struct apply_state
*state
, struct patch
*patch
)
2228 struct strbuf qname
= STRBUF_INIT
;
2229 char *cp
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
2232 quote_c_style(cp
, &qname
, NULL
, 0);
2235 * "scale" the filename
2237 max
= state
->max_len
;
2241 if (qname
.len
> max
) {
2242 cp
= strchr(qname
.buf
+ qname
.len
+ 3 - max
, '/');
2244 cp
= qname
.buf
+ qname
.len
+ 3 - max
;
2245 strbuf_splice(&qname
, 0, cp
- qname
.buf
, "...", 3);
2248 if (patch
->is_binary
) {
2249 printf(" %-*s | Bin\n", max
, qname
.buf
);
2250 strbuf_release(&qname
);
2254 printf(" %-*s |", max
, qname
.buf
);
2255 strbuf_release(&qname
);
2258 * scale the add/delete
2260 max
= max
+ state
->max_change
> 70 ? 70 - max
: state
->max_change
;
2261 add
= patch
->lines_added
;
2262 del
= patch
->lines_deleted
;
2264 if (state
->max_change
> 0) {
2265 int total
= ((add
+ del
) * max
+ state
->max_change
/ 2) / state
->max_change
;
2266 add
= (add
* max
+ state
->max_change
/ 2) / state
->max_change
;
2269 printf("%5d %.*s%.*s\n", patch
->lines_added
+ patch
->lines_deleted
,
2270 add
, pluses
, del
, minuses
);
2273 static int read_old_data(struct stat
*st
, struct patch
*patch
,
2274 const char *path
, struct strbuf
*buf
)
2276 int conv_flags
= patch
->crlf_in_old
?
2277 CONV_EOL_KEEP_CRLF
: CONV_EOL_RENORMALIZE
;
2278 switch (st
->st_mode
& S_IFMT
) {
2280 if (strbuf_readlink(buf
, path
, st
->st_size
) < 0)
2281 return error(_("unable to read symlink %s"), path
);
2284 if (strbuf_read_file(buf
, path
, st
->st_size
) != st
->st_size
)
2285 return error(_("unable to open or read %s"), path
);
2287 * "git apply" without "--index/--cached" should never look
2288 * at the index; the target file may not have been added to
2289 * the index yet, and we may not even be in any Git repository.
2290 * Pass NULL to convert_to_git() to stress this; the function
2291 * should never look at the index when explicit crlf option
2294 convert_to_git(NULL
, path
, buf
->buf
, buf
->len
, buf
, conv_flags
);
2302 * Update the preimage, and the common lines in postimage,
2303 * from buffer buf of length len. If postlen is 0 the postimage
2304 * is updated in place, otherwise it's updated on a new buffer
2308 static void update_pre_post_images(struct image
*preimage
,
2309 struct image
*postimage
,
2311 size_t len
, size_t postlen
)
2313 int i
, ctx
, reduced
;
2314 char *new_buf
, *old_buf
, *fixed
;
2315 struct image fixed_preimage
;
2318 * Update the preimage with whitespace fixes. Note that we
2319 * are not losing preimage->buf -- apply_one_fragment() will
2322 prepare_image(&fixed_preimage
, buf
, len
, 1);
2324 ? fixed_preimage
.nr
== preimage
->nr
2325 : fixed_preimage
.nr
<= preimage
->nr
);
2326 for (i
= 0; i
< fixed_preimage
.nr
; i
++)
2327 fixed_preimage
.line
[i
].flag
= preimage
->line
[i
].flag
;
2328 free(preimage
->line_allocated
);
2329 *preimage
= fixed_preimage
;
2332 * Adjust the common context lines in postimage. This can be
2333 * done in-place when we are shrinking it with whitespace
2334 * fixing, but needs a new buffer when ignoring whitespace or
2335 * expanding leading tabs to spaces.
2337 * We trust the caller to tell us if the update can be done
2338 * in place (postlen==0) or not.
2340 old_buf
= postimage
->buf
;
2342 new_buf
= postimage
->buf
= xmalloc(postlen
);
2345 fixed
= preimage
->buf
;
2347 for (i
= reduced
= ctx
= 0; i
< postimage
->nr
; i
++) {
2348 size_t l_len
= postimage
->line
[i
].len
;
2349 if (!(postimage
->line
[i
].flag
& LINE_COMMON
)) {
2350 /* an added line -- no counterparts in preimage */
2351 memmove(new_buf
, old_buf
, l_len
);
2357 /* a common context -- skip it in the original postimage */
2360 /* and find the corresponding one in the fixed preimage */
2361 while (ctx
< preimage
->nr
&&
2362 !(preimage
->line
[ctx
].flag
& LINE_COMMON
)) {
2363 fixed
+= preimage
->line
[ctx
].len
;
2368 * preimage is expected to run out, if the caller
2369 * fixed addition of trailing blank lines.
2371 if (preimage
->nr
<= ctx
) {
2376 /* and copy it in, while fixing the line length */
2377 l_len
= preimage
->line
[ctx
].len
;
2378 memcpy(new_buf
, fixed
, l_len
);
2381 postimage
->line
[i
].len
= l_len
;
2386 ? postlen
< new_buf
- postimage
->buf
2387 : postimage
->len
< new_buf
- postimage
->buf
)
2388 BUG("caller miscounted postlen: asked %d, orig = %d, used = %d",
2389 (int)postlen
, (int) postimage
->len
, (int)(new_buf
- postimage
->buf
));
2391 /* Fix the length of the whole thing */
2392 postimage
->len
= new_buf
- postimage
->buf
;
2393 postimage
->nr
-= reduced
;
2396 static int line_by_line_fuzzy_match(struct image
*img
,
2397 struct image
*preimage
,
2398 struct image
*postimage
,
2399 unsigned long current
,
2406 size_t postlen
= postimage
->len
;
2411 struct strbuf fixed
;
2415 for (i
= 0; i
< preimage_limit
; i
++) {
2416 size_t prelen
= preimage
->line
[i
].len
;
2417 size_t imglen
= img
->line
[current_lno
+i
].len
;
2419 if (!fuzzy_matchlines(img
->buf
+ current
+ imgoff
, imglen
,
2420 preimage
->buf
+ preoff
, prelen
))
2422 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2423 postlen
+= imglen
- prelen
;
2429 * Ok, the preimage matches with whitespace fuzz.
2431 * imgoff now holds the true length of the target that
2432 * matches the preimage before the end of the file.
2434 * Count the number of characters in the preimage that fall
2435 * beyond the end of the file and make sure that all of them
2436 * are whitespace characters. (This can only happen if
2437 * we are removing blank lines at the end of the file.)
2439 buf
= preimage_eof
= preimage
->buf
+ preoff
;
2440 for ( ; i
< preimage
->nr
; i
++)
2441 preoff
+= preimage
->line
[i
].len
;
2442 preimage_end
= preimage
->buf
+ preoff
;
2443 for ( ; buf
< preimage_end
; buf
++)
2448 * Update the preimage and the common postimage context
2449 * lines to use the same whitespace as the target.
2450 * If whitespace is missing in the target (i.e.
2451 * if the preimage extends beyond the end of the file),
2452 * use the whitespace from the preimage.
2454 extra_chars
= preimage_end
- preimage_eof
;
2455 strbuf_init(&fixed
, imgoff
+ extra_chars
);
2456 strbuf_add(&fixed
, img
->buf
+ current
, imgoff
);
2457 strbuf_add(&fixed
, preimage_eof
, extra_chars
);
2458 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2459 update_pre_post_images(preimage
, postimage
,
2460 fixed_buf
, fixed_len
, postlen
);
2464 static int match_fragment(struct apply_state
*state
,
2466 struct image
*preimage
,
2467 struct image
*postimage
,
2468 unsigned long current
,
2471 int match_beginning
, int match_end
)
2474 char *fixed_buf
, *buf
, *orig
, *target
;
2475 struct strbuf fixed
;
2476 size_t fixed_len
, postlen
;
2479 if (preimage
->nr
+ current_lno
<= img
->nr
) {
2481 * The hunk falls within the boundaries of img.
2483 preimage_limit
= preimage
->nr
;
2484 if (match_end
&& (preimage
->nr
+ current_lno
!= img
->nr
))
2486 } else if (state
->ws_error_action
== correct_ws_error
&&
2487 (ws_rule
& WS_BLANK_AT_EOF
)) {
2489 * This hunk extends beyond the end of img, and we are
2490 * removing blank lines at the end of the file. This
2491 * many lines from the beginning of the preimage must
2492 * match with img, and the remainder of the preimage
2495 preimage_limit
= img
->nr
- current_lno
;
2498 * The hunk extends beyond the end of the img and
2499 * we are not removing blanks at the end, so we
2500 * should reject the hunk at this position.
2505 if (match_beginning
&& current_lno
)
2508 /* Quick hash check */
2509 for (i
= 0; i
< preimage_limit
; i
++)
2510 if ((img
->line
[current_lno
+ i
].flag
& LINE_PATCHED
) ||
2511 (preimage
->line
[i
].hash
!= img
->line
[current_lno
+ i
].hash
))
2514 if (preimage_limit
== preimage
->nr
) {
2516 * Do we have an exact match? If we were told to match
2517 * at the end, size must be exactly at current+fragsize,
2518 * otherwise current+fragsize must be still within the preimage,
2519 * and either case, the old piece should match the preimage
2523 ? (current
+ preimage
->len
== img
->len
)
2524 : (current
+ preimage
->len
<= img
->len
)) &&
2525 !memcmp(img
->buf
+ current
, preimage
->buf
, preimage
->len
))
2529 * The preimage extends beyond the end of img, so
2530 * there cannot be an exact match.
2532 * There must be one non-blank context line that match
2533 * a line before the end of img.
2537 buf
= preimage
->buf
;
2539 for (i
= 0; i
< preimage_limit
; i
++)
2540 buf_end
+= preimage
->line
[i
].len
;
2542 for ( ; buf
< buf_end
; buf
++)
2550 * No exact match. If we are ignoring whitespace, run a line-by-line
2551 * fuzzy matching. We collect all the line length information because
2552 * we need it to adjust whitespace if we match.
2554 if (state
->ws_ignore_action
== ignore_ws_change
)
2555 return line_by_line_fuzzy_match(img
, preimage
, postimage
,
2556 current
, current_lno
, preimage_limit
);
2558 if (state
->ws_error_action
!= correct_ws_error
)
2562 * The hunk does not apply byte-by-byte, but the hash says
2563 * it might with whitespace fuzz. We weren't asked to
2564 * ignore whitespace, we were asked to correct whitespace
2565 * errors, so let's try matching after whitespace correction.
2567 * While checking the preimage against the target, whitespace
2568 * errors in both fixed, we count how large the corresponding
2569 * postimage needs to be. The postimage prepared by
2570 * apply_one_fragment() has whitespace errors fixed on added
2571 * lines already, but the common lines were propagated as-is,
2572 * which may become longer when their whitespace errors are
2576 /* First count added lines in postimage */
2578 for (i
= 0; i
< postimage
->nr
; i
++) {
2579 if (!(postimage
->line
[i
].flag
& LINE_COMMON
))
2580 postlen
+= postimage
->line
[i
].len
;
2584 * The preimage may extend beyond the end of the file,
2585 * but in this loop we will only handle the part of the
2586 * preimage that falls within the file.
2588 strbuf_init(&fixed
, preimage
->len
+ 1);
2589 orig
= preimage
->buf
;
2590 target
= img
->buf
+ current
;
2591 for (i
= 0; i
< preimage_limit
; i
++) {
2592 size_t oldlen
= preimage
->line
[i
].len
;
2593 size_t tgtlen
= img
->line
[current_lno
+ i
].len
;
2594 size_t fixstart
= fixed
.len
;
2595 struct strbuf tgtfix
;
2598 /* Try fixing the line in the preimage */
2599 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2601 /* Try fixing the line in the target */
2602 strbuf_init(&tgtfix
, tgtlen
);
2603 ws_fix_copy(&tgtfix
, target
, tgtlen
, ws_rule
, NULL
);
2606 * If they match, either the preimage was based on
2607 * a version before our tree fixed whitespace breakage,
2608 * or we are lacking a whitespace-fix patch the tree
2609 * the preimage was based on already had (i.e. target
2610 * has whitespace breakage, the preimage doesn't).
2611 * In either case, we are fixing the whitespace breakages
2612 * so we might as well take the fix together with their
2615 match
= (tgtfix
.len
== fixed
.len
- fixstart
&&
2616 !memcmp(tgtfix
.buf
, fixed
.buf
+ fixstart
,
2617 fixed
.len
- fixstart
));
2619 /* Add the length if this is common with the postimage */
2620 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2621 postlen
+= tgtfix
.len
;
2623 strbuf_release(&tgtfix
);
2633 * Now handle the lines in the preimage that falls beyond the
2634 * end of the file (if any). They will only match if they are
2635 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2638 for ( ; i
< preimage
->nr
; i
++) {
2639 size_t fixstart
= fixed
.len
; /* start of the fixed preimage */
2640 size_t oldlen
= preimage
->line
[i
].len
;
2643 /* Try fixing the line in the preimage */
2644 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2646 for (j
= fixstart
; j
< fixed
.len
; j
++)
2647 if (!isspace(fixed
.buf
[j
]))
2654 * Yes, the preimage is based on an older version that still
2655 * has whitespace breakages unfixed, and fixing them makes the
2656 * hunk match. Update the context lines in the postimage.
2658 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2659 if (postlen
< postimage
->len
)
2661 update_pre_post_images(preimage
, postimage
,
2662 fixed_buf
, fixed_len
, postlen
);
2666 strbuf_release(&fixed
);
2670 static int find_pos(struct apply_state
*state
,
2672 struct image
*preimage
,
2673 struct image
*postimage
,
2676 int match_beginning
, int match_end
)
2679 unsigned long backwards
, forwards
, current
;
2680 int backwards_lno
, forwards_lno
, current_lno
;
2683 * When running with --allow-overlap, it is possible that a hunk is
2684 * seen that pretends to start at the beginning (but no longer does),
2685 * and that *still* needs to match the end. So trust `match_end` more
2686 * than `match_beginning`.
2688 if (state
->allow_overlap
&& match_beginning
&& match_end
&&
2689 img
->nr
- preimage
->nr
!= 0)
2690 match_beginning
= 0;
2693 * If match_beginning or match_end is specified, there is no
2694 * point starting from a wrong line that will never match and
2695 * wander around and wait for a match at the specified end.
2697 if (match_beginning
)
2700 line
= img
->nr
- preimage
->nr
;
2703 * Because the comparison is unsigned, the following test
2704 * will also take care of a negative line number that can
2705 * result when match_end and preimage is larger than the target.
2707 if ((size_t) line
> img
->nr
)
2711 for (i
= 0; i
< line
; i
++)
2712 current
+= img
->line
[i
].len
;
2715 * There's probably some smart way to do this, but I'll leave
2716 * that to the smart and beautiful people. I'm simple and stupid.
2718 backwards
= current
;
2719 backwards_lno
= line
;
2721 forwards_lno
= line
;
2724 for (i
= 0; ; i
++) {
2725 if (match_fragment(state
, img
, preimage
, postimage
,
2726 current
, current_lno
, ws_rule
,
2727 match_beginning
, match_end
))
2731 if (backwards_lno
== 0 && forwards_lno
== img
->nr
)
2735 if (backwards_lno
== 0) {
2740 backwards
-= img
->line
[backwards_lno
].len
;
2741 current
= backwards
;
2742 current_lno
= backwards_lno
;
2744 if (forwards_lno
== img
->nr
) {
2748 forwards
+= img
->line
[forwards_lno
].len
;
2751 current_lno
= forwards_lno
;
2758 static void remove_first_line(struct image
*img
)
2760 img
->buf
+= img
->line
[0].len
;
2761 img
->len
-= img
->line
[0].len
;
2766 static void remove_last_line(struct image
*img
)
2768 img
->len
-= img
->line
[--img
->nr
].len
;
2772 * The change from "preimage" and "postimage" has been found to
2773 * apply at applied_pos (counts in line numbers) in "img".
2774 * Update "img" to remove "preimage" and replace it with "postimage".
2776 static void update_image(struct apply_state
*state
,
2779 struct image
*preimage
,
2780 struct image
*postimage
)
2783 * remove the copy of preimage at offset in img
2784 * and replace it with postimage
2787 size_t remove_count
, insert_count
, applied_at
= 0;
2792 * If we are removing blank lines at the end of img,
2793 * the preimage may extend beyond the end.
2794 * If that is the case, we must be careful only to
2795 * remove the part of the preimage that falls within
2796 * the boundaries of img. Initialize preimage_limit
2797 * to the number of lines in the preimage that falls
2798 * within the boundaries.
2800 preimage_limit
= preimage
->nr
;
2801 if (preimage_limit
> img
->nr
- applied_pos
)
2802 preimage_limit
= img
->nr
- applied_pos
;
2804 for (i
= 0; i
< applied_pos
; i
++)
2805 applied_at
+= img
->line
[i
].len
;
2808 for (i
= 0; i
< preimage_limit
; i
++)
2809 remove_count
+= img
->line
[applied_pos
+ i
].len
;
2810 insert_count
= postimage
->len
;
2812 /* Adjust the contents */
2813 result
= xmalloc(st_add3(st_sub(img
->len
, remove_count
), insert_count
, 1));
2814 memcpy(result
, img
->buf
, applied_at
);
2815 memcpy(result
+ applied_at
, postimage
->buf
, postimage
->len
);
2816 memcpy(result
+ applied_at
+ postimage
->len
,
2817 img
->buf
+ (applied_at
+ remove_count
),
2818 img
->len
- (applied_at
+ remove_count
));
2821 img
->len
+= insert_count
- remove_count
;
2822 result
[img
->len
] = '\0';
2824 /* Adjust the line table */
2825 nr
= img
->nr
+ postimage
->nr
- preimage_limit
;
2826 if (preimage_limit
< postimage
->nr
) {
2828 * NOTE: this knows that we never call remove_first_line()
2829 * on anything other than pre/post image.
2831 REALLOC_ARRAY(img
->line
, nr
);
2832 img
->line_allocated
= img
->line
;
2834 if (preimage_limit
!= postimage
->nr
)
2835 MOVE_ARRAY(img
->line
+ applied_pos
+ postimage
->nr
,
2836 img
->line
+ applied_pos
+ preimage_limit
,
2837 img
->nr
- (applied_pos
+ preimage_limit
));
2838 COPY_ARRAY(img
->line
+ applied_pos
, postimage
->line
, postimage
->nr
);
2839 if (!state
->allow_overlap
)
2840 for (i
= 0; i
< postimage
->nr
; i
++)
2841 img
->line
[applied_pos
+ i
].flag
|= LINE_PATCHED
;
2846 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2847 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2848 * replace the part of "img" with "postimage" text.
2850 static int apply_one_fragment(struct apply_state
*state
,
2851 struct image
*img
, struct fragment
*frag
,
2852 int inaccurate_eof
, unsigned ws_rule
,
2855 int match_beginning
, match_end
;
2856 const char *patch
= frag
->patch
;
2857 int size
= frag
->size
;
2858 char *old
, *oldlines
;
2859 struct strbuf newlines
;
2860 int new_blank_lines_at_end
= 0;
2861 int found_new_blank_lines_at_end
= 0;
2862 int hunk_linenr
= frag
->linenr
;
2863 unsigned long leading
, trailing
;
2864 int pos
, applied_pos
;
2865 struct image preimage
;
2866 struct image postimage
;
2868 memset(&preimage
, 0, sizeof(preimage
));
2869 memset(&postimage
, 0, sizeof(postimage
));
2870 oldlines
= xmalloc(size
);
2871 strbuf_init(&newlines
, size
);
2876 int len
= linelen(patch
, size
);
2878 int added_blank_line
= 0;
2879 int is_blank_context
= 0;
2886 * "plen" is how much of the line we should use for
2887 * the actual patch data. Normally we just remove the
2888 * first character on the line, but if the line is
2889 * followed by "\ No newline", then we also remove the
2890 * last one (which is the newline, of course).
2893 if (len
< size
&& patch
[len
] == '\\')
2896 if (state
->apply_in_reverse
) {
2899 else if (first
== '+')
2905 /* Newer GNU diff, empty context line */
2907 /* ... followed by '\No newline'; nothing */
2910 strbuf_addch(&newlines
, '\n');
2911 add_line_info(&preimage
, "\n", 1, LINE_COMMON
);
2912 add_line_info(&postimage
, "\n", 1, LINE_COMMON
);
2913 is_blank_context
= 1;
2916 if (plen
&& (ws_rule
& WS_BLANK_AT_EOF
) &&
2917 ws_blank_line(patch
+ 1, plen
))
2918 is_blank_context
= 1;
2921 memcpy(old
, patch
+ 1, plen
);
2922 add_line_info(&preimage
, old
, plen
,
2923 (first
== ' ' ? LINE_COMMON
: 0));
2929 /* --no-add does not add new lines */
2930 if (first
== '+' && state
->no_add
)
2933 start
= newlines
.len
;
2935 !state
->whitespace_error
||
2936 state
->ws_error_action
!= correct_ws_error
) {
2937 strbuf_add(&newlines
, patch
+ 1, plen
);
2940 ws_fix_copy(&newlines
, patch
+ 1, plen
, ws_rule
, &state
->applied_after_fixing_ws
);
2942 add_line_info(&postimage
, newlines
.buf
+ start
, newlines
.len
- start
,
2943 (first
== '+' ? 0 : LINE_COMMON
));
2945 (ws_rule
& WS_BLANK_AT_EOF
) &&
2946 ws_blank_line(patch
+ 1, plen
))
2947 added_blank_line
= 1;
2949 case '@': case '\\':
2950 /* Ignore it, we already handled it */
2953 if (state
->apply_verbosity
> verbosity_normal
)
2954 error(_("invalid start of line: '%c'"), first
);
2958 if (added_blank_line
) {
2959 if (!new_blank_lines_at_end
)
2960 found_new_blank_lines_at_end
= hunk_linenr
;
2961 new_blank_lines_at_end
++;
2963 else if (is_blank_context
)
2966 new_blank_lines_at_end
= 0;
2971 if (inaccurate_eof
&&
2972 old
> oldlines
&& old
[-1] == '\n' &&
2973 newlines
.len
> 0 && newlines
.buf
[newlines
.len
- 1] == '\n') {
2975 strbuf_setlen(&newlines
, newlines
.len
- 1);
2976 preimage
.line_allocated
[preimage
.nr
- 1].len
--;
2977 postimage
.line_allocated
[postimage
.nr
- 1].len
--;
2980 leading
= frag
->leading
;
2981 trailing
= frag
->trailing
;
2984 * A hunk to change lines at the beginning would begin with
2986 * but we need to be careful. -U0 that inserts before the second
2987 * line also has this pattern.
2989 * And a hunk to add to an empty file would begin with
2992 * In other words, a hunk that is (frag->oldpos <= 1) with or
2993 * without leading context must match at the beginning.
2995 match_beginning
= (!frag
->oldpos
||
2996 (frag
->oldpos
== 1 && !state
->unidiff_zero
));
2999 * A hunk without trailing lines must match at the end.
3000 * However, we simply cannot tell if a hunk must match end
3001 * from the lack of trailing lines if the patch was generated
3002 * with unidiff without any context.
3004 match_end
= !state
->unidiff_zero
&& !trailing
;
3006 pos
= frag
->newpos
? (frag
->newpos
- 1) : 0;
3007 preimage
.buf
= oldlines
;
3008 preimage
.len
= old
- oldlines
;
3009 postimage
.buf
= newlines
.buf
;
3010 postimage
.len
= newlines
.len
;
3011 preimage
.line
= preimage
.line_allocated
;
3012 postimage
.line
= postimage
.line_allocated
;
3016 applied_pos
= find_pos(state
, img
, &preimage
, &postimage
, pos
,
3017 ws_rule
, match_beginning
, match_end
);
3019 if (applied_pos
>= 0)
3022 /* Am I at my context limits? */
3023 if ((leading
<= state
->p_context
) && (trailing
<= state
->p_context
))
3025 if (match_beginning
|| match_end
) {
3026 match_beginning
= match_end
= 0;
3031 * Reduce the number of context lines; reduce both
3032 * leading and trailing if they are equal otherwise
3033 * just reduce the larger context.
3035 if (leading
>= trailing
) {
3036 remove_first_line(&preimage
);
3037 remove_first_line(&postimage
);
3041 if (trailing
> leading
) {
3042 remove_last_line(&preimage
);
3043 remove_last_line(&postimage
);
3048 if (applied_pos
>= 0) {
3049 if (new_blank_lines_at_end
&&
3050 preimage
.nr
+ applied_pos
>= img
->nr
&&
3051 (ws_rule
& WS_BLANK_AT_EOF
) &&
3052 state
->ws_error_action
!= nowarn_ws_error
) {
3053 record_ws_error(state
, WS_BLANK_AT_EOF
, "+", 1,
3054 found_new_blank_lines_at_end
);
3055 if (state
->ws_error_action
== correct_ws_error
) {
3056 while (new_blank_lines_at_end
--)
3057 remove_last_line(&postimage
);
3060 * We would want to prevent write_out_results()
3061 * from taking place in apply_patch() that follows
3062 * the callchain led us here, which is:
3063 * apply_patch->check_patch_list->check_patch->
3064 * apply_data->apply_fragments->apply_one_fragment
3066 if (state
->ws_error_action
== die_on_ws_error
)
3070 if (state
->apply_verbosity
> verbosity_normal
&& applied_pos
!= pos
) {
3071 int offset
= applied_pos
- pos
;
3072 if (state
->apply_in_reverse
)
3073 offset
= 0 - offset
;
3075 Q_("Hunk #%d succeeded at %d (offset %d line).",
3076 "Hunk #%d succeeded at %d (offset %d lines).",
3078 nth_fragment
, applied_pos
+ 1, offset
);
3082 * Warn if it was necessary to reduce the number
3085 if ((leading
!= frag
->leading
||
3086 trailing
!= frag
->trailing
) && state
->apply_verbosity
> verbosity_silent
)
3087 fprintf_ln(stderr
, _("Context reduced to (%ld/%ld)"
3088 " to apply fragment at %d"),
3089 leading
, trailing
, applied_pos
+1);
3090 update_image(state
, img
, applied_pos
, &preimage
, &postimage
);
3092 if (state
->apply_verbosity
> verbosity_normal
)
3093 error(_("while searching for:\n%.*s"),
3094 (int)(old
- oldlines
), oldlines
);
3099 strbuf_release(&newlines
);
3100 free(preimage
.line_allocated
);
3101 free(postimage
.line_allocated
);
3103 return (applied_pos
< 0);
3106 static int apply_binary_fragment(struct apply_state
*state
,
3108 struct patch
*patch
)
3110 struct fragment
*fragment
= patch
->fragments
;
3115 return error(_("missing binary patch data for '%s'"),
3120 /* Binary patch is irreversible without the optional second hunk */
3121 if (state
->apply_in_reverse
) {
3122 if (!fragment
->next
)
3123 return error(_("cannot reverse-apply a binary patch "
3124 "without the reverse hunk to '%s'"),
3126 ? patch
->new_name
: patch
->old_name
);
3127 fragment
= fragment
->next
;
3129 switch (fragment
->binary_patch_method
) {
3130 case BINARY_DELTA_DEFLATED
:
3131 dst
= patch_delta(img
->buf
, img
->len
, fragment
->patch
,
3132 fragment
->size
, &len
);
3139 case BINARY_LITERAL_DEFLATED
:
3141 img
->len
= fragment
->size
;
3142 img
->buf
= xmemdupz(fragment
->patch
, img
->len
);
3149 * Replace "img" with the result of applying the binary patch.
3150 * The binary patch data itself in patch->fragment is still kept
3151 * but the preimage prepared by the caller in "img" is freed here
3152 * or in the helper function apply_binary_fragment() this calls.
3154 static int apply_binary(struct apply_state
*state
,
3156 struct patch
*patch
)
3158 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3159 struct object_id oid
;
3160 const unsigned hexsz
= the_hash_algo
->hexsz
;
3163 * For safety, we require patch index line to contain
3164 * full hex textual object ID for old and new, at least for now.
3166 if (strlen(patch
->old_oid_prefix
) != hexsz
||
3167 strlen(patch
->new_oid_prefix
) != hexsz
||
3168 get_oid_hex(patch
->old_oid_prefix
, &oid
) ||
3169 get_oid_hex(patch
->new_oid_prefix
, &oid
))
3170 return error(_("cannot apply binary patch to '%s' "
3171 "without full index line"), name
);
3173 if (patch
->old_name
) {
3175 * See if the old one matches what the patch
3178 hash_object_file(the_hash_algo
, img
->buf
, img
->len
, OBJ_BLOB
,
3180 if (strcmp(oid_to_hex(&oid
), patch
->old_oid_prefix
))
3181 return error(_("the patch applies to '%s' (%s), "
3182 "which does not match the "
3183 "current contents."),
3184 name
, oid_to_hex(&oid
));
3187 /* Otherwise, the old one must be empty. */
3189 return error(_("the patch applies to an empty "
3190 "'%s' but it is not empty"), name
);
3193 get_oid_hex(patch
->new_oid_prefix
, &oid
);
3194 if (is_null_oid(&oid
)) {
3196 return 0; /* deletion patch */
3199 if (has_object(the_repository
, &oid
, 0)) {
3200 /* We already have the postimage */
3201 enum object_type type
;
3205 result
= read_object_file(&oid
, &type
, &size
);
3207 return error(_("the necessary postimage %s for "
3208 "'%s' cannot be read"),
3209 patch
->new_oid_prefix
, name
);
3215 * We have verified buf matches the preimage;
3216 * apply the patch data to it, which is stored
3217 * in the patch->fragments->{patch,size}.
3219 if (apply_binary_fragment(state
, img
, patch
))
3220 return error(_("binary patch does not apply to '%s'"),
3223 /* verify that the result matches */
3224 hash_object_file(the_hash_algo
, img
->buf
, img
->len
, OBJ_BLOB
,
3226 if (strcmp(oid_to_hex(&oid
), patch
->new_oid_prefix
))
3227 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3228 name
, patch
->new_oid_prefix
, oid_to_hex(&oid
));
3234 static int apply_fragments(struct apply_state
*state
, struct image
*img
, struct patch
*patch
)
3236 struct fragment
*frag
= patch
->fragments
;
3237 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3238 unsigned ws_rule
= patch
->ws_rule
;
3239 unsigned inaccurate_eof
= patch
->inaccurate_eof
;
3242 if (patch
->is_binary
)
3243 return apply_binary(state
, img
, patch
);
3247 if (apply_one_fragment(state
, img
, frag
, inaccurate_eof
, ws_rule
, nth
)) {
3248 error(_("patch failed: %s:%ld"), name
, frag
->oldpos
);
3249 if (!state
->apply_with_reject
)
3258 static int read_blob_object(struct strbuf
*buf
, const struct object_id
*oid
, unsigned mode
)
3260 if (S_ISGITLINK(mode
)) {
3261 strbuf_grow(buf
, 100);
3262 strbuf_addf(buf
, "Subproject commit %s\n", oid_to_hex(oid
));
3264 enum object_type type
;
3268 result
= read_object_file(oid
, &type
, &sz
);
3271 /* XXX read_sha1_file NUL-terminates */
3272 strbuf_attach(buf
, result
, sz
, sz
+ 1);
3277 static int read_file_or_gitlink(const struct cache_entry
*ce
, struct strbuf
*buf
)
3281 return read_blob_object(buf
, &ce
->oid
, ce
->ce_mode
);
3284 static struct patch
*in_fn_table(struct apply_state
*state
, const char *name
)
3286 struct string_list_item
*item
;
3291 item
= string_list_lookup(&state
->fn_table
, name
);
3293 return (struct patch
*)item
->util
;
3299 * item->util in the filename table records the status of the path.
3300 * Usually it points at a patch (whose result records the contents
3301 * of it after applying it), but it could be PATH_WAS_DELETED for a
3302 * path that a previously applied patch has already removed, or
3303 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3305 * The latter is needed to deal with a case where two paths A and B
3306 * are swapped by first renaming A to B and then renaming B to A;
3307 * moving A to B should not be prevented due to presence of B as we
3308 * will remove it in a later patch.
3310 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3311 #define PATH_WAS_DELETED ((struct patch *) -1)
3313 static int to_be_deleted(struct patch
*patch
)
3315 return patch
== PATH_TO_BE_DELETED
;
3318 static int was_deleted(struct patch
*patch
)
3320 return patch
== PATH_WAS_DELETED
;
3323 static void add_to_fn_table(struct apply_state
*state
, struct patch
*patch
)
3325 struct string_list_item
*item
;
3328 * Always add new_name unless patch is a deletion
3329 * This should cover the cases for normal diffs,
3330 * file creations and copies
3332 if (patch
->new_name
) {
3333 item
= string_list_insert(&state
->fn_table
, patch
->new_name
);
3338 * store a failure on rename/deletion cases because
3339 * later chunks shouldn't patch old names
3341 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3342 item
= string_list_insert(&state
->fn_table
, patch
->old_name
);
3343 item
->util
= PATH_WAS_DELETED
;
3347 static void prepare_fn_table(struct apply_state
*state
, struct patch
*patch
)
3350 * store information about incoming file deletion
3353 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3354 struct string_list_item
*item
;
3355 item
= string_list_insert(&state
->fn_table
, patch
->old_name
);
3356 item
->util
= PATH_TO_BE_DELETED
;
3358 patch
= patch
->next
;
3362 static int checkout_target(struct index_state
*istate
,
3363 struct cache_entry
*ce
, struct stat
*st
)
3365 struct checkout costate
= CHECKOUT_INIT
;
3367 costate
.refresh_cache
= 1;
3368 costate
.istate
= istate
;
3369 if (checkout_entry(ce
, &costate
, NULL
, NULL
) ||
3370 lstat(ce
->name
, st
))
3371 return error(_("cannot checkout %s"), ce
->name
);
3375 static struct patch
*previous_patch(struct apply_state
*state
,
3376 struct patch
*patch
,
3379 struct patch
*previous
;
3382 if (patch
->is_copy
|| patch
->is_rename
)
3383 return NULL
; /* "git" patches do not depend on the order */
3385 previous
= in_fn_table(state
, patch
->old_name
);
3389 if (to_be_deleted(previous
))
3390 return NULL
; /* the deletion hasn't happened yet */
3392 if (was_deleted(previous
))
3398 static int verify_index_match(struct apply_state
*state
,
3399 const struct cache_entry
*ce
,
3402 if (S_ISGITLINK(ce
->ce_mode
)) {
3403 if (!S_ISDIR(st
->st_mode
))
3407 return ie_match_stat(state
->repo
->index
, ce
, st
,
3408 CE_MATCH_IGNORE_VALID
| CE_MATCH_IGNORE_SKIP_WORKTREE
);
3411 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3413 static int load_patch_target(struct apply_state
*state
,
3415 const struct cache_entry
*ce
,
3417 struct patch
*patch
,
3419 unsigned expected_mode
)
3421 if (state
->cached
|| state
->check_index
) {
3422 if (read_file_or_gitlink(ce
, buf
))
3423 return error(_("failed to read %s"), name
);
3425 if (S_ISGITLINK(expected_mode
)) {
3427 return read_file_or_gitlink(ce
, buf
);
3429 return SUBMODULE_PATCH_WITHOUT_INDEX
;
3430 } else if (has_symlink_leading_path(name
, strlen(name
))) {
3431 return error(_("reading from '%s' beyond a symbolic link"), name
);
3433 if (read_old_data(st
, patch
, name
, buf
))
3434 return error(_("failed to read %s"), name
);
3441 * We are about to apply "patch"; populate the "image" with the
3442 * current version we have, from the working tree or from the index,
3443 * depending on the situation e.g. --cached/--index. If we are
3444 * applying a non-git patch that incrementally updates the tree,
3445 * we read from the result of a previous diff.
3447 static int load_preimage(struct apply_state
*state
,
3448 struct image
*image
,
3449 struct patch
*patch
, struct stat
*st
,
3450 const struct cache_entry
*ce
)
3452 struct strbuf buf
= STRBUF_INIT
;
3455 struct patch
*previous
;
3458 previous
= previous_patch(state
, patch
, &status
);
3460 return error(_("path %s has been renamed/deleted"),
3463 /* We have a patched copy in memory; use that. */
3464 strbuf_add(&buf
, previous
->result
, previous
->resultsize
);
3466 status
= load_patch_target(state
, &buf
, ce
, st
, patch
,
3467 patch
->old_name
, patch
->old_mode
);
3470 else if (status
== SUBMODULE_PATCH_WITHOUT_INDEX
) {
3472 * There is no way to apply subproject
3473 * patch without looking at the index.
3474 * NEEDSWORK: shouldn't this be flagged
3477 free_fragment_list(patch
->fragments
);
3478 patch
->fragments
= NULL
;
3479 } else if (status
) {
3480 return error(_("failed to read %s"), patch
->old_name
);
3484 img
= strbuf_detach(&buf
, &len
);
3485 prepare_image(image
, img
, len
, !patch
->is_binary
);
3489 static int resolve_to(struct image
*image
, const struct object_id
*result_id
)
3492 enum object_type type
;
3496 image
->buf
= read_object_file(result_id
, &type
, &size
);
3497 if (!image
->buf
|| type
!= OBJ_BLOB
)
3498 die("unable to read blob object %s", oid_to_hex(result_id
));
3504 static int three_way_merge(struct apply_state
*state
,
3505 struct image
*image
,
3507 const struct object_id
*base
,
3508 const struct object_id
*ours
,
3509 const struct object_id
*theirs
)
3511 mmfile_t base_file
, our_file
, their_file
;
3512 mmbuffer_t result
= { NULL
};
3513 enum ll_merge_result status
;
3515 /* resolve trivial cases first */
3516 if (oideq(base
, ours
))
3517 return resolve_to(image
, theirs
);
3518 else if (oideq(base
, theirs
) || oideq(ours
, theirs
))
3519 return resolve_to(image
, ours
);
3521 read_mmblob(&base_file
, base
);
3522 read_mmblob(&our_file
, ours
);
3523 read_mmblob(&their_file
, theirs
);
3524 status
= ll_merge(&result
, path
,
3527 &their_file
, "theirs",
3530 if (status
== LL_MERGE_BINARY_CONFLICT
)
3531 warning("Cannot merge binary files: %s (%s vs. %s)",
3532 path
, "ours", "theirs");
3533 free(base_file
.ptr
);
3535 free(their_file
.ptr
);
3536 if (status
< 0 || !result
.ptr
) {
3541 image
->buf
= result
.ptr
;
3542 image
->len
= result
.size
;
3548 * When directly falling back to add/add three-way merge, we read from
3549 * the current contents of the new_name. In no cases other than that
3550 * this function will be called.
3552 static int load_current(struct apply_state
*state
,
3553 struct image
*image
,
3554 struct patch
*patch
)
3556 struct strbuf buf
= STRBUF_INIT
;
3561 struct cache_entry
*ce
;
3562 char *name
= patch
->new_name
;
3563 unsigned mode
= patch
->new_mode
;
3566 BUG("patch to %s is not a creation", patch
->old_name
);
3568 pos
= index_name_pos(state
->repo
->index
, name
, strlen(name
));
3570 return error(_("%s: does not exist in index"), name
);
3571 ce
= state
->repo
->index
->cache
[pos
];
3572 if (lstat(name
, &st
)) {
3573 if (errno
!= ENOENT
)
3574 return error_errno("%s", name
);
3575 if (checkout_target(state
->repo
->index
, ce
, &st
))
3578 if (verify_index_match(state
, ce
, &st
))
3579 return error(_("%s: does not match index"), name
);
3581 status
= load_patch_target(state
, &buf
, ce
, &st
, patch
, name
, mode
);
3586 img
= strbuf_detach(&buf
, &len
);
3587 prepare_image(image
, img
, len
, !patch
->is_binary
);
3591 static int try_threeway(struct apply_state
*state
,
3592 struct image
*image
,
3593 struct patch
*patch
,
3595 const struct cache_entry
*ce
)
3597 struct object_id pre_oid
, post_oid
, our_oid
;
3598 struct strbuf buf
= STRBUF_INIT
;
3602 struct image tmp_image
;
3604 /* No point falling back to 3-way merge in these cases */
3605 if (patch
->is_delete
||
3606 S_ISGITLINK(patch
->old_mode
) || S_ISGITLINK(patch
->new_mode
) ||
3607 (patch
->is_new
&& !patch
->direct_to_threeway
) ||
3608 (patch
->is_rename
&& !patch
->lines_added
&& !patch
->lines_deleted
))
3611 /* Preimage the patch was prepared for */
3613 write_object_file("", 0, OBJ_BLOB
, &pre_oid
);
3614 else if (get_oid(patch
->old_oid_prefix
, &pre_oid
) ||
3615 read_blob_object(&buf
, &pre_oid
, patch
->old_mode
))
3616 return error(_("repository lacks the necessary blob to perform 3-way merge."));
3618 if (state
->apply_verbosity
> verbosity_silent
&& patch
->direct_to_threeway
)
3619 fprintf(stderr
, _("Performing three-way merge...\n"));
3621 img
= strbuf_detach(&buf
, &len
);
3622 prepare_image(&tmp_image
, img
, len
, 1);
3623 /* Apply the patch to get the post image */
3624 if (apply_fragments(state
, &tmp_image
, patch
) < 0) {
3625 clear_image(&tmp_image
);
3628 /* post_oid is theirs */
3629 write_object_file(tmp_image
.buf
, tmp_image
.len
, OBJ_BLOB
, &post_oid
);
3630 clear_image(&tmp_image
);
3632 /* our_oid is ours */
3633 if (patch
->is_new
) {
3634 if (load_current(state
, &tmp_image
, patch
))
3635 return error(_("cannot read the current contents of '%s'"),
3638 if (load_preimage(state
, &tmp_image
, patch
, st
, ce
))
3639 return error(_("cannot read the current contents of '%s'"),
3642 write_object_file(tmp_image
.buf
, tmp_image
.len
, OBJ_BLOB
, &our_oid
);
3643 clear_image(&tmp_image
);
3645 /* in-core three-way merge between post and our using pre as base */
3646 status
= three_way_merge(state
, image
, patch
->new_name
,
3647 &pre_oid
, &our_oid
, &post_oid
);
3649 if (state
->apply_verbosity
> verbosity_silent
)
3651 _("Failed to perform three-way merge...\n"));
3656 patch
->conflicted_threeway
= 1;
3658 oidclr(&patch
->threeway_stage
[0]);
3660 oidcpy(&patch
->threeway_stage
[0], &pre_oid
);
3661 oidcpy(&patch
->threeway_stage
[1], &our_oid
);
3662 oidcpy(&patch
->threeway_stage
[2], &post_oid
);
3663 if (state
->apply_verbosity
> verbosity_silent
)
3665 _("Applied patch to '%s' with conflicts.\n"),
3668 if (state
->apply_verbosity
> verbosity_silent
)
3670 _("Applied patch to '%s' cleanly.\n"),
3676 static int apply_data(struct apply_state
*state
, struct patch
*patch
,
3677 struct stat
*st
, const struct cache_entry
*ce
)
3681 if (load_preimage(state
, &image
, patch
, st
, ce
) < 0)
3684 if (!state
->threeway
|| try_threeway(state
, &image
, patch
, st
, ce
) < 0) {
3685 if (state
->apply_verbosity
> verbosity_silent
&&
3686 state
->threeway
&& !patch
->direct_to_threeway
)
3687 fprintf(stderr
, _("Falling back to direct application...\n"));
3689 /* Note: with --reject, apply_fragments() returns 0 */
3690 if (patch
->direct_to_threeway
|| apply_fragments(state
, &image
, patch
) < 0)
3693 patch
->result
= image
.buf
;
3694 patch
->resultsize
= image
.len
;
3695 add_to_fn_table(state
, patch
);
3696 free(image
.line_allocated
);
3698 if (0 < patch
->is_delete
&& patch
->resultsize
)
3699 return error(_("removal patch leaves file contents"));
3705 * If "patch" that we are looking at modifies or deletes what we have,
3706 * we would want it not to lose any local modification we have, either
3707 * in the working tree or in the index.
3709 * This also decides if a non-git patch is a creation patch or a
3710 * modification to an existing empty file. We do not check the state
3711 * of the current tree for a creation patch in this function; the caller
3712 * check_patch() separately makes sure (and errors out otherwise) that
3713 * the path the patch creates does not exist in the current tree.
3715 static int check_preimage(struct apply_state
*state
,
3716 struct patch
*patch
,
3717 struct cache_entry
**ce
,
3720 const char *old_name
= patch
->old_name
;
3721 struct patch
*previous
= NULL
;
3722 int stat_ret
= 0, status
;
3723 unsigned st_mode
= 0;
3728 assert(patch
->is_new
<= 0);
3729 previous
= previous_patch(state
, patch
, &status
);
3732 return error(_("path %s has been renamed/deleted"), old_name
);
3734 st_mode
= previous
->new_mode
;
3735 } else if (!state
->cached
) {
3736 stat_ret
= lstat(old_name
, st
);
3737 if (stat_ret
&& errno
!= ENOENT
)
3738 return error_errno("%s", old_name
);
3741 if (state
->check_index
&& !previous
) {
3742 int pos
= index_name_pos(state
->repo
->index
, old_name
,
3745 if (patch
->is_new
< 0)
3747 return error(_("%s: does not exist in index"), old_name
);
3749 *ce
= state
->repo
->index
->cache
[pos
];
3751 if (checkout_target(state
->repo
->index
, *ce
, st
))
3754 if (!state
->cached
&& verify_index_match(state
, *ce
, st
))
3755 return error(_("%s: does not match index"), old_name
);
3757 st_mode
= (*ce
)->ce_mode
;
3758 } else if (stat_ret
< 0) {
3759 if (patch
->is_new
< 0)
3761 return error_errno("%s", old_name
);
3764 if (!state
->cached
&& !previous
)
3765 st_mode
= ce_mode_from_stat(*ce
, st
->st_mode
);
3767 if (patch
->is_new
< 0)
3769 if (!patch
->old_mode
)
3770 patch
->old_mode
= st_mode
;
3771 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
3772 return error(_("%s: wrong type"), old_name
);
3773 if (st_mode
!= patch
->old_mode
)
3774 warning(_("%s has type %o, expected %o"),
3775 old_name
, st_mode
, patch
->old_mode
);
3776 if (!patch
->new_mode
&& !patch
->is_delete
)
3777 patch
->new_mode
= st_mode
;
3782 patch
->is_delete
= 0;
3783 FREE_AND_NULL(patch
->old_name
);
3788 #define EXISTS_IN_INDEX 1
3789 #define EXISTS_IN_WORKTREE 2
3790 #define EXISTS_IN_INDEX_AS_ITA 3
3792 static int check_to_create(struct apply_state
*state
,
3793 const char *new_name
,
3798 if (state
->check_index
&& (!ok_if_exists
|| !state
->cached
)) {
3801 pos
= index_name_pos(state
->repo
->index
, new_name
, strlen(new_name
));
3803 struct cache_entry
*ce
= state
->repo
->index
->cache
[pos
];
3805 /* allow ITA, as they do not yet exist in the index */
3806 if (!ok_if_exists
&& !(ce
->ce_flags
& CE_INTENT_TO_ADD
))
3807 return EXISTS_IN_INDEX
;
3809 /* ITA entries can never match working tree files */
3810 if (!state
->cached
&& (ce
->ce_flags
& CE_INTENT_TO_ADD
))
3811 return EXISTS_IN_INDEX_AS_ITA
;
3818 if (!lstat(new_name
, &nst
)) {
3819 if (S_ISDIR(nst
.st_mode
) || ok_if_exists
)
3822 * A leading component of new_name might be a symlink
3823 * that is going to be removed with this patch, but
3824 * still pointing at somewhere that has the path.
3825 * In such a case, path "new_name" does not exist as
3826 * far as git is concerned.
3828 if (has_symlink_leading_path(new_name
, strlen(new_name
)))
3831 return EXISTS_IN_WORKTREE
;
3832 } else if (!is_missing_file_error(errno
)) {
3833 return error_errno("%s", new_name
);
3838 static void prepare_symlink_changes(struct apply_state
*state
, struct patch
*patch
)
3840 for ( ; patch
; patch
= patch
->next
) {
3841 if ((patch
->old_name
&& S_ISLNK(patch
->old_mode
)) &&
3842 (patch
->is_rename
|| patch
->is_delete
))
3843 /* the symlink at patch->old_name is removed */
3844 strset_add(&state
->removed_symlinks
, patch
->old_name
);
3846 if (patch
->new_name
&& S_ISLNK(patch
->new_mode
))
3847 /* the symlink at patch->new_name is created or remains */
3848 strset_add(&state
->kept_symlinks
, patch
->new_name
);
3852 static int path_is_beyond_symlink_1(struct apply_state
*state
, struct strbuf
*name
)
3855 while (--name
->len
&& name
->buf
[name
->len
] != '/')
3856 ; /* scan backwards */
3859 name
->buf
[name
->len
] = '\0';
3860 if (strset_contains(&state
->kept_symlinks
, name
->buf
))
3862 if (strset_contains(&state
->removed_symlinks
, name
->buf
))
3864 * This cannot be "return 0", because we may
3865 * see a new one created at a higher level.
3869 /* otherwise, check the preimage */
3870 if (state
->check_index
) {
3871 struct cache_entry
*ce
;
3873 ce
= index_file_exists(state
->repo
->index
, name
->buf
,
3874 name
->len
, ignore_case
);
3875 if (ce
&& S_ISLNK(ce
->ce_mode
))
3879 if (!lstat(name
->buf
, &st
) && S_ISLNK(st
.st_mode
))
3886 static int path_is_beyond_symlink(struct apply_state
*state
, const char *name_
)
3889 struct strbuf name
= STRBUF_INIT
;
3891 assert(*name_
!= '\0');
3892 strbuf_addstr(&name
, name_
);
3893 ret
= path_is_beyond_symlink_1(state
, &name
);
3894 strbuf_release(&name
);
3899 static int check_unsafe_path(struct patch
*patch
)
3901 const char *old_name
= NULL
;
3902 const char *new_name
= NULL
;
3903 if (patch
->is_delete
)
3904 old_name
= patch
->old_name
;
3905 else if (!patch
->is_new
&& !patch
->is_copy
)
3906 old_name
= patch
->old_name
;
3907 if (!patch
->is_delete
)
3908 new_name
= patch
->new_name
;
3910 if (old_name
&& !verify_path(old_name
, patch
->old_mode
))
3911 return error(_("invalid path '%s'"), old_name
);
3912 if (new_name
&& !verify_path(new_name
, patch
->new_mode
))
3913 return error(_("invalid path '%s'"), new_name
);
3918 * Check and apply the patch in-core; leave the result in patch->result
3919 * for the caller to write it out to the final destination.
3921 static int check_patch(struct apply_state
*state
, struct patch
*patch
)
3924 const char *old_name
= patch
->old_name
;
3925 const char *new_name
= patch
->new_name
;
3926 const char *name
= old_name
? old_name
: new_name
;
3927 struct cache_entry
*ce
= NULL
;
3928 struct patch
*tpatch
;
3932 patch
->rejected
= 1; /* we will drop this after we succeed */
3934 status
= check_preimage(state
, patch
, &ce
, &st
);
3937 old_name
= patch
->old_name
;
3940 * A type-change diff is always split into a patch to delete
3941 * old, immediately followed by a patch to create new (see
3942 * diff.c::run_diff()); in such a case it is Ok that the entry
3943 * to be deleted by the previous patch is still in the working
3944 * tree and in the index.
3946 * A patch to swap-rename between A and B would first rename A
3947 * to B and then rename B to A. While applying the first one,
3948 * the presence of B should not stop A from getting renamed to
3949 * B; ask to_be_deleted() about the later rename. Removal of
3950 * B and rename from A to B is handled the same way by asking
3953 if ((tpatch
= in_fn_table(state
, new_name
)) &&
3954 (was_deleted(tpatch
) || to_be_deleted(tpatch
)))
3960 ((0 < patch
->is_new
) || patch
->is_rename
|| patch
->is_copy
)) {
3961 int err
= check_to_create(state
, new_name
, ok_if_exists
);
3963 if (err
&& state
->threeway
) {
3964 patch
->direct_to_threeway
= 1;
3965 } else switch (err
) {
3968 case EXISTS_IN_INDEX
:
3969 return error(_("%s: already exists in index"), new_name
);
3970 case EXISTS_IN_INDEX_AS_ITA
:
3971 return error(_("%s: does not match index"), new_name
);
3972 case EXISTS_IN_WORKTREE
:
3973 return error(_("%s: already exists in working directory"),
3979 if (!patch
->new_mode
) {
3980 if (0 < patch
->is_new
)
3981 patch
->new_mode
= S_IFREG
| 0644;
3983 patch
->new_mode
= patch
->old_mode
;
3987 if (new_name
&& old_name
) {
3988 int same
= !strcmp(old_name
, new_name
);
3989 if (!patch
->new_mode
)
3990 patch
->new_mode
= patch
->old_mode
;
3991 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
) {
3993 return error(_("new mode (%o) of %s does not "
3994 "match old mode (%o)"),
3995 patch
->new_mode
, new_name
,
3998 return error(_("new mode (%o) of %s does not "
3999 "match old mode (%o) of %s"),
4000 patch
->new_mode
, new_name
,
4001 patch
->old_mode
, old_name
);
4005 if (!state
->unsafe_paths
&& check_unsafe_path(patch
))
4009 * An attempt to read from or delete a path that is beyond a
4010 * symbolic link will be prevented by load_patch_target() that
4011 * is called at the beginning of apply_data() so we do not
4012 * have to worry about a patch marked with "is_delete" bit
4013 * here. We however need to make sure that the patch result
4014 * is not deposited to a path that is beyond a symbolic link
4017 if (!patch
->is_delete
&& path_is_beyond_symlink(state
, patch
->new_name
))
4018 return error(_("affected file '%s' is beyond a symbolic link"),
4021 if (apply_data(state
, patch
, &st
, ce
) < 0)
4022 return error(_("%s: patch does not apply"), name
);
4023 patch
->rejected
= 0;
4027 static int check_patch_list(struct apply_state
*state
, struct patch
*patch
)
4031 prepare_symlink_changes(state
, patch
);
4032 prepare_fn_table(state
, patch
);
4035 if (state
->apply_verbosity
> verbosity_normal
)
4036 say_patch_name(stderr
,
4037 _("Checking patch %s..."), patch
);
4038 res
= check_patch(state
, patch
);
4042 patch
= patch
->next
;
4047 static int read_apply_cache(struct apply_state
*state
)
4049 if (state
->index_file
)
4050 return read_index_from(state
->repo
->index
, state
->index_file
,
4053 return repo_read_index(state
->repo
);
4056 /* This function tries to read the object name from the current index */
4057 static int get_current_oid(struct apply_state
*state
, const char *path
,
4058 struct object_id
*oid
)
4062 if (read_apply_cache(state
) < 0)
4064 pos
= index_name_pos(state
->repo
->index
, path
, strlen(path
));
4067 oidcpy(oid
, &state
->repo
->index
->cache
[pos
]->oid
);
4071 static int preimage_oid_in_gitlink_patch(struct patch
*p
, struct object_id
*oid
)
4074 * A usable gitlink patch has only one fragment (hunk) that looks like:
4076 * -Subproject commit <old sha1>
4077 * +Subproject commit <new sha1>
4080 * -Subproject commit <old sha1>
4081 * for a removal patch.
4083 struct fragment
*hunk
= p
->fragments
;
4084 static const char heading
[] = "-Subproject commit ";
4087 if (/* does the patch have only one hunk? */
4088 hunk
&& !hunk
->next
&&
4089 /* is its preimage one line? */
4090 hunk
->oldpos
== 1 && hunk
->oldlines
== 1 &&
4091 /* does preimage begin with the heading? */
4092 (preimage
= memchr(hunk
->patch
, '\n', hunk
->size
)) != NULL
&&
4093 starts_with(++preimage
, heading
) &&
4094 /* does it record full SHA-1? */
4095 !get_oid_hex(preimage
+ sizeof(heading
) - 1, oid
) &&
4096 preimage
[sizeof(heading
) + the_hash_algo
->hexsz
- 1] == '\n' &&
4097 /* does the abbreviated name on the index line agree with it? */
4098 starts_with(preimage
+ sizeof(heading
) - 1, p
->old_oid_prefix
))
4099 return 0; /* it all looks fine */
4101 /* we may have full object name on the index line */
4102 return get_oid_hex(p
->old_oid_prefix
, oid
);
4105 /* Build an index that contains just the files needed for a 3way merge */
4106 static int build_fake_ancestor(struct apply_state
*state
, struct patch
*list
)
4108 struct patch
*patch
;
4109 struct index_state result
= { NULL
};
4110 struct lock_file lock
= LOCK_INIT
;
4113 /* Once we start supporting the reverse patch, it may be
4114 * worth showing the new sha1 prefix, but until then...
4116 for (patch
= list
; patch
; patch
= patch
->next
) {
4117 struct object_id oid
;
4118 struct cache_entry
*ce
;
4121 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
4122 if (0 < patch
->is_new
)
4125 if (S_ISGITLINK(patch
->old_mode
)) {
4126 if (!preimage_oid_in_gitlink_patch(patch
, &oid
))
4127 ; /* ok, the textual part looks sane */
4129 return error(_("sha1 information is lacking or "
4130 "useless for submodule %s"), name
);
4131 } else if (!get_oid_blob(patch
->old_oid_prefix
, &oid
)) {
4133 } else if (!patch
->lines_added
&& !patch
->lines_deleted
) {
4134 /* mode-only change: update the current */
4135 if (get_current_oid(state
, patch
->old_name
, &oid
))
4136 return error(_("mode change for %s, which is not "
4137 "in current HEAD"), name
);
4139 return error(_("sha1 information is lacking or useless "
4142 ce
= make_cache_entry(&result
, patch
->old_mode
, &oid
, name
, 0, 0);
4144 return error(_("make_cache_entry failed for path '%s'"),
4146 if (add_index_entry(&result
, ce
, ADD_CACHE_OK_TO_ADD
)) {
4147 discard_cache_entry(ce
);
4148 return error(_("could not add %s to temporary index"),
4153 hold_lock_file_for_update(&lock
, state
->fake_ancestor
, LOCK_DIE_ON_ERROR
);
4154 res
= write_locked_index(&result
, &lock
, COMMIT_LOCK
);
4155 discard_index(&result
);
4158 return error(_("could not write temporary index to %s"),
4159 state
->fake_ancestor
);
4164 static void stat_patch_list(struct apply_state
*state
, struct patch
*patch
)
4166 int files
, adds
, dels
;
4168 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
4170 adds
+= patch
->lines_added
;
4171 dels
+= patch
->lines_deleted
;
4172 show_stats(state
, patch
);
4175 print_stat_summary(stdout
, files
, adds
, dels
);
4178 static void numstat_patch_list(struct apply_state
*state
,
4179 struct patch
*patch
)
4181 for ( ; patch
; patch
= patch
->next
) {
4183 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
4184 if (patch
->is_binary
)
4187 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
4188 write_name_quoted(name
, stdout
, state
->line_termination
);
4192 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
4195 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
4197 printf(" %s %s\n", newdelete
, name
);
4200 static void show_mode_change(struct patch
*p
, int show_name
)
4202 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
4204 printf(" mode change %06o => %06o %s\n",
4205 p
->old_mode
, p
->new_mode
, p
->new_name
);
4207 printf(" mode change %06o => %06o\n",
4208 p
->old_mode
, p
->new_mode
);
4212 static void show_rename_copy(struct patch
*p
)
4214 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
4215 const char *old_name
, *new_name
;
4217 /* Find common prefix */
4218 old_name
= p
->old_name
;
4219 new_name
= p
->new_name
;
4221 const char *slash_old
, *slash_new
;
4222 slash_old
= strchr(old_name
, '/');
4223 slash_new
= strchr(new_name
, '/');
4226 slash_old
- old_name
!= slash_new
- new_name
||
4227 memcmp(old_name
, new_name
, slash_new
- new_name
))
4229 old_name
= slash_old
+ 1;
4230 new_name
= slash_new
+ 1;
4232 /* p->old_name through old_name is the common prefix, and old_name and
4233 * new_name through the end of names are renames
4235 if (old_name
!= p
->old_name
)
4236 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
4237 (int)(old_name
- p
->old_name
), p
->old_name
,
4238 old_name
, new_name
, p
->score
);
4240 printf(" %s %s => %s (%d%%)\n", renamecopy
,
4241 p
->old_name
, p
->new_name
, p
->score
);
4242 show_mode_change(p
, 0);
4245 static void summary_patch_list(struct patch
*patch
)
4249 for (p
= patch
; p
; p
= p
->next
) {
4251 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
4252 else if (p
->is_delete
)
4253 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
4255 if (p
->is_rename
|| p
->is_copy
)
4256 show_rename_copy(p
);
4259 printf(" rewrite %s (%d%%)\n",
4260 p
->new_name
, p
->score
);
4261 show_mode_change(p
, 0);
4264 show_mode_change(p
, 1);
4270 static void patch_stats(struct apply_state
*state
, struct patch
*patch
)
4272 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
4274 if (lines
> state
->max_change
)
4275 state
->max_change
= lines
;
4276 if (patch
->old_name
) {
4277 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
4279 len
= strlen(patch
->old_name
);
4280 if (len
> state
->max_len
)
4281 state
->max_len
= len
;
4283 if (patch
->new_name
) {
4284 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
4286 len
= strlen(patch
->new_name
);
4287 if (len
> state
->max_len
)
4288 state
->max_len
= len
;
4292 static int remove_file(struct apply_state
*state
, struct patch
*patch
, int rmdir_empty
)
4294 if (state
->update_index
&& !state
->ita_only
) {
4295 if (remove_file_from_index(state
->repo
->index
, patch
->old_name
) < 0)
4296 return error(_("unable to remove %s from index"), patch
->old_name
);
4298 if (!state
->cached
) {
4299 if (!remove_or_warn(patch
->old_mode
, patch
->old_name
) && rmdir_empty
) {
4300 remove_path(patch
->old_name
);
4306 static int add_index_file(struct apply_state
*state
,
4313 struct cache_entry
*ce
;
4314 int namelen
= strlen(path
);
4316 ce
= make_empty_cache_entry(state
->repo
->index
, namelen
);
4317 memcpy(ce
->name
, path
, namelen
);
4318 ce
->ce_mode
= create_ce_mode(mode
);
4319 ce
->ce_flags
= create_ce_flags(0);
4320 ce
->ce_namelen
= namelen
;
4321 if (state
->ita_only
) {
4322 ce
->ce_flags
|= CE_INTENT_TO_ADD
;
4323 set_object_name_for_intent_to_add_entry(ce
);
4324 } else if (S_ISGITLINK(mode
)) {
4327 if (!skip_prefix(buf
, "Subproject commit ", &s
) ||
4328 get_oid_hex(s
, &ce
->oid
)) {
4329 discard_cache_entry(ce
);
4330 return error(_("corrupt patch for submodule %s"), path
);
4333 if (!state
->cached
) {
4334 if (lstat(path
, &st
) < 0) {
4335 discard_cache_entry(ce
);
4336 return error_errno(_("unable to stat newly "
4337 "created file '%s'"),
4340 fill_stat_cache_info(state
->repo
->index
, ce
, &st
);
4342 if (write_object_file(buf
, size
, OBJ_BLOB
, &ce
->oid
) < 0) {
4343 discard_cache_entry(ce
);
4344 return error(_("unable to create backing store "
4345 "for newly created file %s"), path
);
4348 if (add_index_entry(state
->repo
->index
, ce
, ADD_CACHE_OK_TO_ADD
) < 0) {
4349 discard_cache_entry(ce
);
4350 return error(_("unable to add cache entry for %s"), path
);
4358 * -1 if an unrecoverable error happened
4359 * 0 if everything went well
4360 * 1 if a recoverable error happened
4362 static int try_create_file(struct apply_state
*state
, const char *path
,
4363 unsigned int mode
, const char *buf
,
4367 struct strbuf nbuf
= STRBUF_INIT
;
4369 if (S_ISGITLINK(mode
)) {
4371 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
))
4373 return !!mkdir(path
, 0777);
4376 if (has_symlinks
&& S_ISLNK(mode
))
4377 /* Although buf:size is counted string, it also is NUL
4380 return !!symlink(buf
, path
);
4382 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
4386 if (convert_to_working_tree(state
->repo
->index
, path
, buf
, size
, &nbuf
, NULL
)) {
4391 res
= write_in_full(fd
, buf
, size
) < 0;
4393 error_errno(_("failed to write to '%s'"), path
);
4394 strbuf_release(&nbuf
);
4396 if (close(fd
) < 0 && !res
)
4397 return error_errno(_("closing file '%s'"), path
);
4399 return res
? -1 : 0;
4403 * We optimistically assume that the directories exist,
4404 * which is true 99% of the time anyway. If they don't,
4405 * we create them and try again.
4411 static int create_one_file(struct apply_state
*state
,
4423 * We already try to detect whether files are beyond a symlink in our
4424 * up-front checks. But in the case where symlinks are created by any
4425 * of the intermediate hunks it can happen that our up-front checks
4426 * didn't yet see the symlink, but at the point of arriving here there
4427 * in fact is one. We thus repeat the check for symlinks here.
4429 * Note that this does not make the up-front check obsolete as the
4430 * failure mode is different:
4432 * - The up-front checks cause us to abort before we have written
4433 * anything into the working directory. So when we exit this way the
4434 * working directory remains clean.
4436 * - The checks here happen in the middle of the action where we have
4437 * already started to apply the patch. The end result will be a dirty
4438 * working directory.
4440 * Ideally, we should update the up-front checks to catch what would
4441 * happen when we apply the patch before we damage the working tree.
4442 * We have all the information necessary to do so. But for now, as a
4443 * part of embargoed security work, having this check would serve as a
4444 * reasonable first step.
4446 if (path_is_beyond_symlink(state
, path
))
4447 return error(_("affected file '%s' is beyond a symbolic link"), path
);
4449 res
= try_create_file(state
, path
, mode
, buf
, size
);
4455 if (errno
== ENOENT
) {
4456 if (safe_create_leading_directories_no_share(path
))
4458 res
= try_create_file(state
, path
, mode
, buf
, size
);
4465 if (errno
== EEXIST
|| errno
== EACCES
) {
4466 /* We may be trying to create a file where a directory
4470 if (!lstat(path
, &st
) && (!S_ISDIR(st
.st_mode
) || !rmdir(path
)))
4474 if (errno
== EEXIST
) {
4475 unsigned int nr
= getpid();
4478 char newpath
[PATH_MAX
];
4479 mksnpath(newpath
, sizeof(newpath
), "%s~%u", path
, nr
);
4480 res
= try_create_file(state
, newpath
, mode
, buf
, size
);
4484 if (!rename(newpath
, path
))
4486 unlink_or_warn(newpath
);
4489 if (errno
!= EEXIST
)
4494 return error_errno(_("unable to write file '%s' mode %o"),
4498 static int add_conflicted_stages_file(struct apply_state
*state
,
4499 struct patch
*patch
)
4503 struct cache_entry
*ce
;
4505 if (!state
->update_index
)
4507 namelen
= strlen(patch
->new_name
);
4508 mode
= patch
->new_mode
? patch
->new_mode
: (S_IFREG
| 0644);
4510 remove_file_from_index(state
->repo
->index
, patch
->new_name
);
4511 for (stage
= 1; stage
< 4; stage
++) {
4512 if (is_null_oid(&patch
->threeway_stage
[stage
- 1]))
4514 ce
= make_empty_cache_entry(state
->repo
->index
, namelen
);
4515 memcpy(ce
->name
, patch
->new_name
, namelen
);
4516 ce
->ce_mode
= create_ce_mode(mode
);
4517 ce
->ce_flags
= create_ce_flags(stage
);
4518 ce
->ce_namelen
= namelen
;
4519 oidcpy(&ce
->oid
, &patch
->threeway_stage
[stage
- 1]);
4520 if (add_index_entry(state
->repo
->index
, ce
, ADD_CACHE_OK_TO_ADD
) < 0) {
4521 discard_cache_entry(ce
);
4522 return error(_("unable to add cache entry for %s"),
4530 static int create_file(struct apply_state
*state
, struct patch
*patch
)
4532 char *path
= patch
->new_name
;
4533 unsigned mode
= patch
->new_mode
;
4534 unsigned long size
= patch
->resultsize
;
4535 char *buf
= patch
->result
;
4538 mode
= S_IFREG
| 0644;
4539 if (create_one_file(state
, path
, mode
, buf
, size
))
4542 if (patch
->conflicted_threeway
)
4543 return add_conflicted_stages_file(state
, patch
);
4544 else if (state
->update_index
)
4545 return add_index_file(state
, path
, mode
, buf
, size
);
4549 /* phase zero is to remove, phase one is to create */
4550 static int write_out_one_result(struct apply_state
*state
,
4551 struct patch
*patch
,
4554 if (patch
->is_delete
> 0) {
4556 return remove_file(state
, patch
, 1);
4559 if (patch
->is_new
> 0 || patch
->is_copy
) {
4561 return create_file(state
, patch
);
4565 * Rename or modification boils down to the same
4566 * thing: remove the old, write the new
4569 return remove_file(state
, patch
, patch
->is_rename
);
4571 return create_file(state
, patch
);
4575 static int write_out_one_reject(struct apply_state
*state
, struct patch
*patch
)
4578 char namebuf
[PATH_MAX
];
4579 struct fragment
*frag
;
4581 struct strbuf sb
= STRBUF_INIT
;
4583 for (cnt
= 0, frag
= patch
->fragments
; frag
; frag
= frag
->next
) {
4584 if (!frag
->rejected
)
4590 if (state
->apply_verbosity
> verbosity_normal
)
4591 say_patch_name(stderr
,
4592 _("Applied patch %s cleanly."), patch
);
4596 /* This should not happen, because a removal patch that leaves
4597 * contents are marked "rejected" at the patch level.
4599 if (!patch
->new_name
)
4600 die(_("internal error"));
4602 /* Say this even without --verbose */
4603 strbuf_addf(&sb
, Q_("Applying patch %%s with %d reject...",
4604 "Applying patch %%s with %d rejects...",
4607 if (state
->apply_verbosity
> verbosity_silent
)
4608 say_patch_name(stderr
, sb
.buf
, patch
);
4609 strbuf_release(&sb
);
4611 cnt
= strlen(patch
->new_name
);
4612 if (ARRAY_SIZE(namebuf
) <= cnt
+ 5) {
4613 cnt
= ARRAY_SIZE(namebuf
) - 5;
4614 warning(_("truncating .rej filename to %.*s.rej"),
4615 cnt
- 1, patch
->new_name
);
4617 memcpy(namebuf
, patch
->new_name
, cnt
);
4618 memcpy(namebuf
+ cnt
, ".rej", 5);
4620 fd
= open(namebuf
, O_CREAT
| O_EXCL
| O_WRONLY
, 0666);
4622 if (errno
!= EEXIST
)
4623 return error_errno(_("cannot open %s"), namebuf
);
4624 if (unlink(namebuf
))
4625 return error_errno(_("cannot unlink '%s'"), namebuf
);
4626 fd
= open(namebuf
, O_CREAT
| O_EXCL
| O_WRONLY
, 0666);
4628 return error_errno(_("cannot open %s"), namebuf
);
4630 rej
= fdopen(fd
, "w");
4632 return error_errno(_("cannot open %s"), namebuf
);
4634 /* Normal git tools never deal with .rej, so do not pretend
4635 * this is a git patch by saying --git or giving extended
4636 * headers. While at it, maybe please "kompare" that wants
4637 * the trailing TAB and some garbage at the end of line ;-).
4639 fprintf(rej
, "diff a/%s b/%s\t(rejected hunks)\n",
4640 patch
->new_name
, patch
->new_name
);
4641 for (cnt
= 1, frag
= patch
->fragments
;
4643 cnt
++, frag
= frag
->next
) {
4644 if (!frag
->rejected
) {
4645 if (state
->apply_verbosity
> verbosity_silent
)
4646 fprintf_ln(stderr
, _("Hunk #%d applied cleanly."), cnt
);
4649 if (state
->apply_verbosity
> verbosity_silent
)
4650 fprintf_ln(stderr
, _("Rejected hunk #%d."), cnt
);
4651 fprintf(rej
, "%.*s", frag
->size
, frag
->patch
);
4652 if (frag
->patch
[frag
->size
-1] != '\n')
4661 * -1 if an error happened
4662 * 0 if the patch applied cleanly
4663 * 1 if the patch did not apply cleanly
4665 static int write_out_results(struct apply_state
*state
, struct patch
*list
)
4670 struct string_list cpath
= STRING_LIST_INIT_DUP
;
4672 for (phase
= 0; phase
< 2; phase
++) {
4678 if (write_out_one_result(state
, l
, phase
)) {
4679 string_list_clear(&cpath
, 0);
4683 if (write_out_one_reject(state
, l
))
4685 if (l
->conflicted_threeway
) {
4686 string_list_append(&cpath
, l
->new_name
);
4696 struct string_list_item
*item
;
4698 string_list_sort(&cpath
);
4699 if (state
->apply_verbosity
> verbosity_silent
) {
4700 for_each_string_list_item(item
, &cpath
)
4701 fprintf(stderr
, "U %s\n", item
->string
);
4703 string_list_clear(&cpath
, 0);
4706 * rerere relies on the partially merged result being in the working
4707 * tree with conflict markers, but that isn't written with --cached.
4710 repo_rerere(state
->repo
, 0);
4717 * Try to apply a patch.
4720 * -128 if a bad error happened (like patch unreadable)
4721 * -1 if patch did not apply and user cannot deal with it
4722 * 0 if the patch applied
4723 * 1 if the patch did not apply but user might fix it
4725 static int apply_patch(struct apply_state
*state
,
4727 const char *filename
,
4731 struct strbuf buf
= STRBUF_INIT
; /* owns the patch text */
4732 struct patch
*list
= NULL
, **listp
= &list
;
4733 int skipped_patch
= 0;
4735 int flush_attributes
= 0;
4737 state
->patch_input_file
= filename
;
4738 if (read_patch_file(&buf
, fd
) < 0)
4741 while (offset
< buf
.len
) {
4742 struct patch
*patch
;
4745 CALLOC_ARRAY(patch
, 1);
4746 patch
->inaccurate_eof
= !!(options
& APPLY_OPT_INACCURATE_EOF
);
4747 patch
->recount
= !!(options
& APPLY_OPT_RECOUNT
);
4748 nr
= parse_chunk(state
, buf
.buf
+ offset
, buf
.len
- offset
, patch
);
4757 if (state
->apply_in_reverse
)
4758 reverse_patches(patch
);
4759 if (use_patch(state
, patch
)) {
4760 patch_stats(state
, patch
);
4761 if (!list
|| !state
->apply_in_reverse
) {
4763 listp
= &patch
->next
;
4769 if ((patch
->new_name
&&
4770 ends_with_path_components(patch
->new_name
,
4771 GITATTRIBUTES_FILE
)) ||
4773 ends_with_path_components(patch
->old_name
,
4774 GITATTRIBUTES_FILE
)))
4775 flush_attributes
= 1;
4778 if (state
->apply_verbosity
> verbosity_normal
)
4779 say_patch_name(stderr
, _("Skipped patch '%s'."), patch
);
4786 if (!list
&& !skipped_patch
) {
4787 if (!state
->allow_empty
) {
4788 error(_("No valid patches in input (allow with \"--allow-empty\")"));
4794 if (state
->whitespace_error
&& (state
->ws_error_action
== die_on_ws_error
))
4797 state
->update_index
= (state
->check_index
|| state
->ita_only
) && state
->apply
;
4798 if (state
->update_index
&& !is_lock_file_locked(&state
->lock_file
)) {
4799 if (state
->index_file
)
4800 hold_lock_file_for_update(&state
->lock_file
,
4804 repo_hold_locked_index(state
->repo
, &state
->lock_file
,
4808 if (state
->check_index
&& read_apply_cache(state
) < 0) {
4809 error(_("unable to read index file"));
4814 if (state
->check
|| state
->apply
) {
4815 int r
= check_patch_list(state
, list
);
4820 if (r
< 0 && !state
->apply_with_reject
) {
4827 int write_res
= write_out_results(state
, list
);
4828 if (write_res
< 0) {
4832 if (write_res
> 0) {
4833 /* with --3way, we still need to write the index out */
4834 res
= state
->apply_with_reject
? -1 : 1;
4839 if (state
->fake_ancestor
&&
4840 build_fake_ancestor(state
, list
)) {
4845 if (state
->diffstat
&& state
->apply_verbosity
> verbosity_silent
)
4846 stat_patch_list(state
, list
);
4848 if (state
->numstat
&& state
->apply_verbosity
> verbosity_silent
)
4849 numstat_patch_list(state
, list
);
4851 if (state
->summary
&& state
->apply_verbosity
> verbosity_silent
)
4852 summary_patch_list(list
);
4854 if (flush_attributes
)
4855 reset_parsed_attributes();
4857 free_patch_list(list
);
4858 strbuf_release(&buf
);
4859 string_list_clear(&state
->fn_table
, 0);
4863 static int apply_option_parse_exclude(const struct option
*opt
,
4864 const char *arg
, int unset
)
4866 struct apply_state
*state
= opt
->value
;
4868 BUG_ON_OPT_NEG(unset
);
4870 add_name_limit(state
, arg
, 1);
4874 static int apply_option_parse_include(const struct option
*opt
,
4875 const char *arg
, int unset
)
4877 struct apply_state
*state
= opt
->value
;
4879 BUG_ON_OPT_NEG(unset
);
4881 add_name_limit(state
, arg
, 0);
4882 state
->has_include
= 1;
4886 static int apply_option_parse_p(const struct option
*opt
,
4890 struct apply_state
*state
= opt
->value
;
4892 BUG_ON_OPT_NEG(unset
);
4894 state
->p_value
= atoi(arg
);
4895 state
->p_value_known
= 1;
4899 static int apply_option_parse_space_change(const struct option
*opt
,
4900 const char *arg
, int unset
)
4902 struct apply_state
*state
= opt
->value
;
4904 BUG_ON_OPT_ARG(arg
);
4907 state
->ws_ignore_action
= ignore_ws_none
;
4909 state
->ws_ignore_action
= ignore_ws_change
;
4913 static int apply_option_parse_whitespace(const struct option
*opt
,
4914 const char *arg
, int unset
)
4916 struct apply_state
*state
= opt
->value
;
4918 BUG_ON_OPT_NEG(unset
);
4920 state
->whitespace_option
= arg
;
4921 if (parse_whitespace_option(state
, arg
))
4926 static int apply_option_parse_directory(const struct option
*opt
,
4927 const char *arg
, int unset
)
4929 struct apply_state
*state
= opt
->value
;
4931 BUG_ON_OPT_NEG(unset
);
4933 strbuf_reset(&state
->root
);
4934 strbuf_addstr(&state
->root
, arg
);
4935 strbuf_complete(&state
->root
, '/');
4939 int apply_all_patches(struct apply_state
*state
,
4949 for (i
= 0; i
< argc
; i
++) {
4950 const char *arg
= argv
[i
];
4951 char *to_free
= NULL
;
4954 if (!strcmp(arg
, "-")) {
4955 res
= apply_patch(state
, 0, "<stdin>", options
);
4962 arg
= to_free
= prefix_filename(state
->prefix
, arg
);
4964 fd
= open(arg
, O_RDONLY
);
4966 error(_("can't open patch '%s': %s"), arg
, strerror(errno
));
4972 set_default_whitespace_mode(state
);
4973 res
= apply_patch(state
, fd
, arg
, options
);
4980 set_default_whitespace_mode(state
);
4982 res
= apply_patch(state
, 0, "<stdin>", options
);
4988 if (state
->whitespace_error
) {
4989 if (state
->squelch_whitespace_errors
&&
4990 state
->squelch_whitespace_errors
< state
->whitespace_error
) {
4992 state
->whitespace_error
- state
->squelch_whitespace_errors
;
4993 warning(Q_("squelched %d whitespace error",
4994 "squelched %d whitespace errors",
4998 if (state
->ws_error_action
== die_on_ws_error
) {
4999 error(Q_("%d line adds whitespace errors.",
5000 "%d lines add whitespace errors.",
5001 state
->whitespace_error
),
5002 state
->whitespace_error
);
5006 if (state
->applied_after_fixing_ws
&& state
->apply
)
5007 warning(Q_("%d line applied after"
5008 " fixing whitespace errors.",
5009 "%d lines applied after"
5010 " fixing whitespace errors.",
5011 state
->applied_after_fixing_ws
),
5012 state
->applied_after_fixing_ws
);
5013 else if (state
->whitespace_error
)
5014 warning(Q_("%d line adds whitespace errors.",
5015 "%d lines add whitespace errors.",
5016 state
->whitespace_error
),
5017 state
->whitespace_error
);
5020 if (state
->update_index
) {
5021 res
= write_locked_index(state
->repo
->index
, &state
->lock_file
, COMMIT_LOCK
);
5023 error(_("Unable to write new index file"));
5032 rollback_lock_file(&state
->lock_file
);
5034 if (state
->apply_verbosity
<= verbosity_silent
) {
5035 set_error_routine(state
->saved_error_routine
);
5036 set_warn_routine(state
->saved_warn_routine
);
5041 return (res
== -1 ? 1 : 128);
5044 int apply_parse_options(int argc
, const char **argv
,
5045 struct apply_state
*state
,
5046 int *force_apply
, int *options
,
5047 const char * const *apply_usage
)
5049 struct option builtin_apply_options
[] = {
5050 OPT_CALLBACK_F(0, "exclude", state
, N_("path"),
5051 N_("don't apply changes matching the given path"),
5052 PARSE_OPT_NONEG
, apply_option_parse_exclude
),
5053 OPT_CALLBACK_F(0, "include", state
, N_("path"),
5054 N_("apply changes matching the given path"),
5055 PARSE_OPT_NONEG
, apply_option_parse_include
),
5056 OPT_CALLBACK('p', NULL
, state
, N_("num"),
5057 N_("remove <num> leading slashes from traditional diff paths"),
5058 apply_option_parse_p
),
5059 OPT_BOOL(0, "no-add", &state
->no_add
,
5060 N_("ignore additions made by the patch")),
5061 OPT_BOOL(0, "stat", &state
->diffstat
,
5062 N_("instead of applying the patch, output diffstat for the input")),
5063 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
5064 OPT_NOOP_NOARG(0, "binary"),
5065 OPT_BOOL(0, "numstat", &state
->numstat
,
5066 N_("show number of added and deleted lines in decimal notation")),
5067 OPT_BOOL(0, "summary", &state
->summary
,
5068 N_("instead of applying the patch, output a summary for the input")),
5069 OPT_BOOL(0, "check", &state
->check
,
5070 N_("instead of applying the patch, see if the patch is applicable")),
5071 OPT_BOOL(0, "index", &state
->check_index
,
5072 N_("make sure the patch is applicable to the current index")),
5073 OPT_BOOL('N', "intent-to-add", &state
->ita_only
,
5074 N_("mark new files with `git add --intent-to-add`")),
5075 OPT_BOOL(0, "cached", &state
->cached
,
5076 N_("apply a patch without touching the working tree")),
5077 OPT_BOOL_F(0, "unsafe-paths", &state
->unsafe_paths
,
5078 N_("accept a patch that touches outside the working area"),
5079 PARSE_OPT_NOCOMPLETE
),
5080 OPT_BOOL(0, "apply", force_apply
,
5081 N_("also apply the patch (use with --stat/--summary/--check)")),
5082 OPT_BOOL('3', "3way", &state
->threeway
,
5083 N_( "attempt three-way merge, fall back on normal patch if that fails")),
5084 OPT_FILENAME(0, "build-fake-ancestor", &state
->fake_ancestor
,
5085 N_("build a temporary index based on embedded index information")),
5086 /* Think twice before adding "--nul" synonym to this */
5087 OPT_SET_INT('z', NULL
, &state
->line_termination
,
5088 N_("paths are separated with NUL character"), '\0'),
5089 OPT_INTEGER('C', NULL
, &state
->p_context
,
5090 N_("ensure at least <n> lines of context match")),
5091 OPT_CALLBACK(0, "whitespace", state
, N_("action"),
5092 N_("detect new or modified lines that have whitespace errors"),
5093 apply_option_parse_whitespace
),
5094 OPT_CALLBACK_F(0, "ignore-space-change", state
, NULL
,
5095 N_("ignore changes in whitespace when finding context"),
5096 PARSE_OPT_NOARG
, apply_option_parse_space_change
),
5097 OPT_CALLBACK_F(0, "ignore-whitespace", state
, NULL
,
5098 N_("ignore changes in whitespace when finding context"),
5099 PARSE_OPT_NOARG
, apply_option_parse_space_change
),
5100 OPT_BOOL('R', "reverse", &state
->apply_in_reverse
,
5101 N_("apply the patch in reverse")),
5102 OPT_BOOL(0, "unidiff-zero", &state
->unidiff_zero
,
5103 N_("don't expect at least one line of context")),
5104 OPT_BOOL(0, "reject", &state
->apply_with_reject
,
5105 N_("leave the rejected hunks in corresponding *.rej files")),
5106 OPT_BOOL(0, "allow-overlap", &state
->allow_overlap
,
5107 N_("allow overlapping hunks")),
5108 OPT__VERBOSITY(&state
->apply_verbosity
),
5109 OPT_BIT(0, "inaccurate-eof", options
,
5110 N_("tolerate incorrectly detected missing new-line at the end of file"),
5111 APPLY_OPT_INACCURATE_EOF
),
5112 OPT_BIT(0, "recount", options
,
5113 N_("do not trust the line counts in the hunk headers"),
5115 OPT_CALLBACK(0, "directory", state
, N_("root"),
5116 N_("prepend <root> to all filenames"),
5117 apply_option_parse_directory
),
5118 OPT_BOOL(0, "allow-empty", &state
->allow_empty
,
5119 N_("don't return error for empty patches")),
5123 return parse_options(argc
, argv
, state
->prefix
, builtin_apply_options
, apply_usage
, 0);