4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
16 #include "xdiff-interface.h"
19 #include "parse-options.h"
24 static void git_apply_config(void)
26 git_config_get_string_const("apply.whitespace", &apply_default_whitespace
);
27 git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace
);
28 git_config(git_default_config
, NULL
);
31 static int parse_whitespace_option(struct apply_state
*state
, const char *option
)
34 state
->ws_error_action
= warn_on_ws_error
;
37 if (!strcmp(option
, "warn")) {
38 state
->ws_error_action
= warn_on_ws_error
;
41 if (!strcmp(option
, "nowarn")) {
42 state
->ws_error_action
= nowarn_ws_error
;
45 if (!strcmp(option
, "error")) {
46 state
->ws_error_action
= die_on_ws_error
;
49 if (!strcmp(option
, "error-all")) {
50 state
->ws_error_action
= die_on_ws_error
;
51 state
->squelch_whitespace_errors
= 0;
54 if (!strcmp(option
, "strip") || !strcmp(option
, "fix")) {
55 state
->ws_error_action
= correct_ws_error
;
58 return error(_("unrecognized whitespace option '%s'"), option
);
61 static int parse_ignorewhitespace_option(struct apply_state
*state
,
64 if (!option
|| !strcmp(option
, "no") ||
65 !strcmp(option
, "false") || !strcmp(option
, "never") ||
66 !strcmp(option
, "none")) {
67 state
->ws_ignore_action
= ignore_ws_none
;
70 if (!strcmp(option
, "change")) {
71 state
->ws_ignore_action
= ignore_ws_change
;
74 return error(_("unrecognized whitespace ignore option '%s'"), option
);
77 int init_apply_state(struct apply_state
*state
,
80 memset(state
, 0, sizeof(*state
));
81 state
->prefix
= prefix
;
83 state
->line_termination
= '\n';
85 state
->p_context
= UINT_MAX
;
86 state
->squelch_whitespace_errors
= 5;
87 state
->ws_error_action
= warn_on_ws_error
;
88 state
->ws_ignore_action
= ignore_ws_none
;
90 string_list_init(&state
->fn_table
, 0);
91 string_list_init(&state
->limit_by_name
, 0);
92 string_list_init(&state
->symlink_changes
, 0);
93 strbuf_init(&state
->root
, 0);
96 if (apply_default_whitespace
&& parse_whitespace_option(state
, apply_default_whitespace
))
98 if (apply_default_ignorewhitespace
&& parse_ignorewhitespace_option(state
, apply_default_ignorewhitespace
))
103 void clear_apply_state(struct apply_state
*state
)
105 string_list_clear(&state
->limit_by_name
, 0);
106 string_list_clear(&state
->symlink_changes
, 0);
107 strbuf_release(&state
->root
);
109 /* &state->fn_table is cleared at the end of apply_patch() */
112 static void mute_routine(const char *msg
, va_list params
)
117 int check_apply_state(struct apply_state
*state
, int force_apply
)
119 int is_not_gitdir
= !startup_info
->have_repository
;
121 if (state
->apply_with_reject
&& state
->threeway
)
122 return error(_("--reject and --3way cannot be used together."));
123 if (state
->cached
&& state
->threeway
)
124 return error(_("--cached and --3way cannot be used together."));
125 if (state
->threeway
) {
127 return error(_("--3way outside a repository"));
128 state
->check_index
= 1;
130 if (state
->apply_with_reject
) {
132 if (state
->apply_verbosity
== verbosity_normal
)
133 state
->apply_verbosity
= verbosity_verbose
;
135 if (!force_apply
&& (state
->diffstat
|| state
->numstat
|| state
->summary
|| state
->check
|| state
->fake_ancestor
))
137 if (state
->check_index
&& is_not_gitdir
)
138 return error(_("--index outside a repository"));
141 return error(_("--cached outside a repository"));
142 state
->check_index
= 1;
144 if (state
->check_index
)
145 state
->unsafe_paths
= 0;
147 if (state
->apply_verbosity
<= verbosity_silent
) {
148 state
->saved_error_routine
= get_error_routine();
149 state
->saved_warn_routine
= get_warn_routine();
150 set_error_routine(mute_routine
);
151 set_warn_routine(mute_routine
);
157 static void set_default_whitespace_mode(struct apply_state
*state
)
159 if (!state
->whitespace_option
&& !apply_default_whitespace
)
160 state
->ws_error_action
= (state
->apply
? warn_on_ws_error
: nowarn_ws_error
);
164 * This represents one "hunk" from a patch, starting with
165 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
166 * patch text is pointed at by patch, and its byte length
167 * is stored in size. leading and trailing are the number
171 unsigned long leading
, trailing
;
172 unsigned long oldpos
, oldlines
;
173 unsigned long newpos
, newlines
;
175 * 'patch' is usually borrowed from buf in apply_patch(),
176 * but some codepaths store an allocated buffer.
179 unsigned free_patch
:1,
183 struct fragment
*next
;
187 * When dealing with a binary patch, we reuse "leading" field
188 * to store the type of the binary hunk, either deflated "delta"
189 * or deflated "literal".
191 #define binary_patch_method leading
192 #define BINARY_DELTA_DEFLATED 1
193 #define BINARY_LITERAL_DEFLATED 2
196 * This represents a "patch" to a file, both metainfo changes
197 * such as creation/deletion, filemode and content changes represented
198 * as a series of fragments.
201 char *new_name
, *old_name
, *def_name
;
202 unsigned int old_mode
, new_mode
;
203 int is_new
, is_delete
; /* -1 = unknown, 0 = false, 1 = true */
206 int lines_added
, lines_deleted
;
208 int extension_linenr
; /* first line specifying delete/new/rename/copy */
209 unsigned int is_toplevel_relative
:1;
210 unsigned int inaccurate_eof
:1;
211 unsigned int is_binary
:1;
212 unsigned int is_copy
:1;
213 unsigned int is_rename
:1;
214 unsigned int recount
:1;
215 unsigned int conflicted_threeway
:1;
216 unsigned int direct_to_threeway
:1;
217 unsigned int crlf_in_old
:1;
218 struct fragment
*fragments
;
221 char old_sha1_prefix
[41];
222 char new_sha1_prefix
[41];
225 /* three-way fallback result */
226 struct object_id threeway_stage
[3];
229 static void free_fragment_list(struct fragment
*list
)
232 struct fragment
*next
= list
->next
;
233 if (list
->free_patch
)
234 free((char *)list
->patch
);
240 static void free_patch(struct patch
*patch
)
242 free_fragment_list(patch
->fragments
);
243 free(patch
->def_name
);
244 free(patch
->old_name
);
245 free(patch
->new_name
);
250 static void free_patch_list(struct patch
*list
)
253 struct patch
*next
= list
->next
;
260 * A line in a file, len-bytes long (includes the terminating LF,
261 * except for an incomplete line at the end if the file ends with
262 * one), and its contents hashes to 'hash'.
268 #define LINE_COMMON 1
269 #define LINE_PATCHED 2
273 * This represents a "file", which is an array of "lines".
280 struct line
*line_allocated
;
284 static uint32_t hash_line(const char *cp
, size_t len
)
288 for (i
= 0, h
= 0; i
< len
; i
++) {
289 if (!isspace(cp
[i
])) {
290 h
= h
* 3 + (cp
[i
] & 0xff);
297 * Compare lines s1 of length n1 and s2 of length n2, ignoring
298 * whitespace difference. Returns 1 if they match, 0 otherwise
300 static int fuzzy_matchlines(const char *s1
, size_t n1
,
301 const char *s2
, size_t n2
)
303 const char *last1
= s1
+ n1
- 1;
304 const char *last2
= s2
+ n2
- 1;
307 /* ignore line endings */
308 while ((*last1
== '\r') || (*last1
== '\n'))
310 while ((*last2
== '\r') || (*last2
== '\n'))
313 /* skip leading whitespaces, if both begin with whitespace */
314 if (s1
<= last1
&& s2
<= last2
&& isspace(*s1
) && isspace(*s2
)) {
315 while (isspace(*s1
) && (s1
<= last1
))
317 while (isspace(*s2
) && (s2
<= last2
))
320 /* early return if both lines are empty */
321 if ((s1
> last1
) && (s2
> last2
))
324 result
= *s1
++ - *s2
++;
326 * Skip whitespace inside. We check for whitespace on
327 * both buffers because we don't want "a b" to match
330 if (isspace(*s1
) && isspace(*s2
)) {
331 while (isspace(*s1
) && s1
<= last1
)
333 while (isspace(*s2
) && s2
<= last2
)
337 * If we reached the end on one side only,
341 ((s2
> last2
) && (s1
<= last1
)) ||
342 ((s1
> last1
) && (s2
<= last2
)))
344 if ((s1
> last1
) && (s2
> last2
))
351 static void add_line_info(struct image
*img
, const char *bol
, size_t len
, unsigned flag
)
353 ALLOC_GROW(img
->line_allocated
, img
->nr
+ 1, img
->alloc
);
354 img
->line_allocated
[img
->nr
].len
= len
;
355 img
->line_allocated
[img
->nr
].hash
= hash_line(bol
, len
);
356 img
->line_allocated
[img
->nr
].flag
= flag
;
361 * "buf" has the file contents to be patched (read from various sources).
362 * attach it to "image" and add line-based index to it.
363 * "image" now owns the "buf".
365 static void prepare_image(struct image
*image
, char *buf
, size_t len
,
366 int prepare_linetable
)
370 memset(image
, 0, sizeof(*image
));
374 if (!prepare_linetable
)
377 ep
= image
->buf
+ image
->len
;
381 for (next
= cp
; next
< ep
&& *next
!= '\n'; next
++)
385 add_line_info(image
, cp
, next
- cp
, 0);
388 image
->line
= image
->line_allocated
;
391 static void clear_image(struct image
*image
)
394 free(image
->line_allocated
);
395 memset(image
, 0, sizeof(*image
));
398 /* fmt must contain _one_ %s and no other substitution */
399 static void say_patch_name(FILE *output
, const char *fmt
, struct patch
*patch
)
401 struct strbuf sb
= STRBUF_INIT
;
403 if (patch
->old_name
&& patch
->new_name
&&
404 strcmp(patch
->old_name
, patch
->new_name
)) {
405 quote_c_style(patch
->old_name
, &sb
, NULL
, 0);
406 strbuf_addstr(&sb
, " => ");
407 quote_c_style(patch
->new_name
, &sb
, NULL
, 0);
409 const char *n
= patch
->new_name
;
412 quote_c_style(n
, &sb
, NULL
, 0);
414 fprintf(output
, fmt
, sb
.buf
);
421 static int read_patch_file(struct strbuf
*sb
, int fd
)
423 if (strbuf_read(sb
, fd
, 0) < 0)
424 return error_errno("git apply: failed to read");
427 * Make sure that we have some slop in the buffer
428 * so that we can do speculative "memcmp" etc, and
429 * see to it that it is NUL-filled.
431 strbuf_grow(sb
, SLOP
);
432 memset(sb
->buf
+ sb
->len
, 0, SLOP
);
436 static unsigned long linelen(const char *buffer
, unsigned long size
)
438 unsigned long len
= 0;
441 if (*buffer
++ == '\n')
447 static int is_dev_null(const char *str
)
449 return skip_prefix(str
, "/dev/null", &str
) && isspace(*str
);
455 static int name_terminate(int c
, int terminate
)
457 if (c
== ' ' && !(terminate
& TERM_SPACE
))
459 if (c
== '\t' && !(terminate
& TERM_TAB
))
465 /* remove double slashes to make --index work with such filenames */
466 static char *squash_slash(char *name
)
474 if ((name
[j
++] = name
[i
++]) == '/')
475 while (name
[i
] == '/')
482 static char *find_name_gnu(struct apply_state
*state
,
487 struct strbuf name
= STRBUF_INIT
;
491 * Proposed "new-style" GNU patch/diff format; see
492 * http://marc.info/?l=git&m=112927316408690&w=2
494 if (unquote_c_style(&name
, line
, NULL
)) {
495 strbuf_release(&name
);
499 for (cp
= name
.buf
; p_value
; p_value
--) {
500 cp
= strchr(cp
, '/');
502 strbuf_release(&name
);
508 strbuf_remove(&name
, 0, cp
- name
.buf
);
510 strbuf_insert(&name
, 0, state
->root
.buf
, state
->root
.len
);
511 return squash_slash(strbuf_detach(&name
, NULL
));
514 static size_t sane_tz_len(const char *line
, size_t len
)
518 if (len
< strlen(" +0500") || line
[len
-strlen(" +0500")] != ' ')
520 tz
= line
+ len
- strlen(" +0500");
522 if (tz
[1] != '+' && tz
[1] != '-')
525 for (p
= tz
+ 2; p
!= line
+ len
; p
++)
529 return line
+ len
- tz
;
532 static size_t tz_with_colon_len(const char *line
, size_t len
)
536 if (len
< strlen(" +08:00") || line
[len
- strlen(":00")] != ':')
538 tz
= line
+ len
- strlen(" +08:00");
540 if (tz
[0] != ' ' || (tz
[1] != '+' && tz
[1] != '-'))
543 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
544 !isdigit(*p
++) || !isdigit(*p
++))
547 return line
+ len
- tz
;
550 static size_t date_len(const char *line
, size_t len
)
552 const char *date
, *p
;
554 if (len
< strlen("72-02-05") || line
[len
-strlen("-05")] != '-')
556 p
= date
= line
+ len
- strlen("72-02-05");
558 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
559 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
560 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a date. */
563 if (date
- line
>= strlen("19") &&
564 isdigit(date
[-1]) && isdigit(date
[-2])) /* 4-digit year */
565 date
-= strlen("19");
567 return line
+ len
- date
;
570 static size_t short_time_len(const char *line
, size_t len
)
572 const char *time
, *p
;
574 if (len
< strlen(" 07:01:32") || line
[len
-strlen(":32")] != ':')
576 p
= time
= line
+ len
- strlen(" 07:01:32");
578 /* Permit 1-digit hours? */
580 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
581 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
582 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a time. */
585 return line
+ len
- time
;
588 static size_t fractional_time_len(const char *line
, size_t len
)
593 /* Expected format: 19:41:17.620000023 */
594 if (!len
|| !isdigit(line
[len
- 1]))
598 /* Fractional seconds. */
599 while (p
> line
&& isdigit(*p
))
604 /* Hours, minutes, and whole seconds. */
605 n
= short_time_len(line
, p
- line
);
609 return line
+ len
- p
+ n
;
612 static size_t trailing_spaces_len(const char *line
, size_t len
)
616 /* Expected format: ' ' x (1 or more) */
617 if (!len
|| line
[len
- 1] != ' ')
624 return line
+ len
- (p
+ 1);
631 static size_t diff_timestamp_len(const char *line
, size_t len
)
633 const char *end
= line
+ len
;
637 * Posix: 2010-07-05 19:41:17
638 * GNU: 2010-07-05 19:41:17.620000023 -0500
641 if (!isdigit(end
[-1]))
644 n
= sane_tz_len(line
, end
- line
);
646 n
= tz_with_colon_len(line
, end
- line
);
649 n
= short_time_len(line
, end
- line
);
651 n
= fractional_time_len(line
, end
- line
);
654 n
= date_len(line
, end
- line
);
655 if (!n
) /* No date. Too bad. */
659 if (end
== line
) /* No space before date. */
661 if (end
[-1] == '\t') { /* Success! */
663 return line
+ len
- end
;
665 if (end
[-1] != ' ') /* No space before date. */
668 /* Whitespace damage. */
669 end
-= trailing_spaces_len(line
, end
- line
);
670 return line
+ len
- end
;
673 static char *find_name_common(struct apply_state
*state
,
681 const char *start
= NULL
;
685 while (line
!= end
) {
688 if (!end
&& isspace(c
)) {
691 if (name_terminate(c
, terminate
))
695 if (c
== '/' && !--p_value
)
699 return squash_slash(xstrdup_or_null(def
));
702 return squash_slash(xstrdup_or_null(def
));
705 * Generally we prefer the shorter name, especially
706 * if the other one is just a variation of that with
707 * something else tacked on to the end (ie "file.orig"
711 int deflen
= strlen(def
);
712 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
713 return squash_slash(xstrdup(def
));
716 if (state
->root
.len
) {
717 char *ret
= xstrfmt("%s%.*s", state
->root
.buf
, len
, start
);
718 return squash_slash(ret
);
721 return squash_slash(xmemdupz(start
, len
));
724 static char *find_name(struct apply_state
*state
,
731 char *name
= find_name_gnu(state
, line
, def
, p_value
);
736 return find_name_common(state
, line
, def
, p_value
, NULL
, terminate
);
739 static char *find_name_traditional(struct apply_state
*state
,
748 char *name
= find_name_gnu(state
, line
, def
, p_value
);
753 len
= strchrnul(line
, '\n') - line
;
754 date_len
= diff_timestamp_len(line
, len
);
756 return find_name_common(state
, line
, def
, p_value
, NULL
, TERM_TAB
);
759 return find_name_common(state
, line
, def
, p_value
, line
+ len
, 0);
763 * Given the string after "--- " or "+++ ", guess the appropriate
764 * p_value for the given patch.
766 static int guess_p_value(struct apply_state
*state
, const char *nameline
)
771 if (is_dev_null(nameline
))
773 name
= find_name_traditional(state
, nameline
, NULL
, 0);
776 cp
= strchr(name
, '/');
779 else if (state
->prefix
) {
781 * Does it begin with "a/$our-prefix" and such? Then this is
782 * very likely to apply to our directory.
784 if (starts_with(name
, state
->prefix
))
785 val
= count_slashes(state
->prefix
);
788 if (starts_with(cp
, state
->prefix
))
789 val
= count_slashes(state
->prefix
) + 1;
797 * Does the ---/+++ line have the POSIX timestamp after the last HT?
798 * GNU diff puts epoch there to signal a creation/deletion event. Is
799 * this such a timestamp?
801 static int has_epoch_timestamp(const char *nameline
)
804 * We are only interested in epoch timestamp; any non-zero
805 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
806 * For the same reason, the date must be either 1969-12-31 or
807 * 1970-01-01, and the seconds part must be "00".
809 const char stamp_regexp
[] =
810 "^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?"
812 "([-+][0-2][0-9]:?[0-5][0-9])\n";
813 const char *timestamp
= NULL
, *cp
, *colon
;
814 static regex_t
*stamp
;
816 int zoneoffset
, epoch_hour
, hour
, minute
;
819 for (cp
= nameline
; *cp
!= '\n'; cp
++) {
827 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
828 * (west of GMT) or 1970-01-01 (east of GMT)
830 if (skip_prefix(timestamp
, "1969-12-31 ", ×tamp
))
832 else if (skip_prefix(timestamp
, "1970-01-01 ", ×tamp
))
838 stamp
= xmalloc(sizeof(*stamp
));
839 if (regcomp(stamp
, stamp_regexp
, REG_EXTENDED
)) {
840 warning(_("Cannot prepare timestamp regexp %s"),
846 status
= regexec(stamp
, timestamp
, ARRAY_SIZE(m
), m
, 0);
848 if (status
!= REG_NOMATCH
)
849 warning(_("regexec returned %d for input: %s"),
854 hour
= strtol(timestamp
, NULL
, 10);
855 minute
= strtol(timestamp
+ m
[1].rm_so
, NULL
, 10);
857 zoneoffset
= strtol(timestamp
+ m
[3].rm_so
+ 1, (char **) &colon
, 10);
859 zoneoffset
= zoneoffset
* 60 + strtol(colon
+ 1, NULL
, 10);
861 zoneoffset
= (zoneoffset
/ 100) * 60 + (zoneoffset
% 100);
862 if (timestamp
[m
[3].rm_so
] == '-')
863 zoneoffset
= -zoneoffset
;
865 return hour
* 60 + minute
- zoneoffset
== epoch_hour
* 60;
869 * Get the name etc info from the ---/+++ lines of a traditional patch header
871 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
872 * files, we can happily check the index for a match, but for creating a
873 * new file we should try to match whatever "patch" does. I have no idea.
875 static int parse_traditional_patch(struct apply_state
*state
,
882 first
+= 4; /* skip "--- " */
883 second
+= 4; /* skip "+++ " */
884 if (!state
->p_value_known
) {
886 p
= guess_p_value(state
, first
);
887 q
= guess_p_value(state
, second
);
889 if (0 <= p
&& p
== q
) {
891 state
->p_value_known
= 1;
894 if (is_dev_null(first
)) {
896 patch
->is_delete
= 0;
897 name
= find_name_traditional(state
, second
, NULL
, state
->p_value
);
898 patch
->new_name
= name
;
899 } else if (is_dev_null(second
)) {
901 patch
->is_delete
= 1;
902 name
= find_name_traditional(state
, first
, NULL
, state
->p_value
);
903 patch
->old_name
= name
;
906 first_name
= find_name_traditional(state
, first
, NULL
, state
->p_value
);
907 name
= find_name_traditional(state
, second
, first_name
, state
->p_value
);
909 if (has_epoch_timestamp(first
)) {
911 patch
->is_delete
= 0;
912 patch
->new_name
= name
;
913 } else if (has_epoch_timestamp(second
)) {
915 patch
->is_delete
= 1;
916 patch
->old_name
= name
;
918 patch
->old_name
= name
;
919 patch
->new_name
= xstrdup_or_null(name
);
923 return error(_("unable to find filename in patch at line %d"), state
->linenr
);
928 static int gitdiff_hdrend(struct apply_state
*state
,
936 * We're anal about diff header consistency, to make
937 * sure that we don't end up having strange ambiguous
938 * patches floating around.
940 * As a result, gitdiff_{old|new}name() will check
941 * their names against any previous information, just
944 #define DIFF_OLD_NAME 0
945 #define DIFF_NEW_NAME 1
947 static int gitdiff_verify_name(struct apply_state
*state
,
953 if (!*name
&& !isnull
) {
954 *name
= find_name(state
, line
, NULL
, state
->p_value
, TERM_TAB
);
961 return error(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
962 *name
, state
->linenr
);
963 another
= find_name(state
, line
, NULL
, state
->p_value
, TERM_TAB
);
964 if (!another
|| strcmp(another
, *name
)) {
966 return error((side
== DIFF_NEW_NAME
) ?
967 _("git apply: bad git-diff - inconsistent new filename on line %d") :
968 _("git apply: bad git-diff - inconsistent old filename on line %d"), state
->linenr
);
972 if (!starts_with(line
, "/dev/null\n"))
973 return error(_("git apply: bad git-diff - expected /dev/null on line %d"), state
->linenr
);
979 static int gitdiff_oldname(struct apply_state
*state
,
983 return gitdiff_verify_name(state
, line
,
984 patch
->is_new
, &patch
->old_name
,
988 static int gitdiff_newname(struct apply_state
*state
,
992 return gitdiff_verify_name(state
, line
,
993 patch
->is_delete
, &patch
->new_name
,
997 static int parse_mode_line(const char *line
, int linenr
, unsigned int *mode
)
1000 *mode
= strtoul(line
, &end
, 8);
1001 if (end
== line
|| !isspace(*end
))
1002 return error(_("invalid mode on line %d: %s"), linenr
, line
);
1006 static int gitdiff_oldmode(struct apply_state
*state
,
1008 struct patch
*patch
)
1010 return parse_mode_line(line
, state
->linenr
, &patch
->old_mode
);
1013 static int gitdiff_newmode(struct apply_state
*state
,
1015 struct patch
*patch
)
1017 return parse_mode_line(line
, state
->linenr
, &patch
->new_mode
);
1020 static int gitdiff_delete(struct apply_state
*state
,
1022 struct patch
*patch
)
1024 patch
->is_delete
= 1;
1025 free(patch
->old_name
);
1026 patch
->old_name
= xstrdup_or_null(patch
->def_name
);
1027 return gitdiff_oldmode(state
, line
, patch
);
1030 static int gitdiff_newfile(struct apply_state
*state
,
1032 struct patch
*patch
)
1035 free(patch
->new_name
);
1036 patch
->new_name
= xstrdup_or_null(patch
->def_name
);
1037 return gitdiff_newmode(state
, line
, patch
);
1040 static int gitdiff_copysrc(struct apply_state
*state
,
1042 struct patch
*patch
)
1045 free(patch
->old_name
);
1046 patch
->old_name
= find_name(state
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1050 static int gitdiff_copydst(struct apply_state
*state
,
1052 struct patch
*patch
)
1055 free(patch
->new_name
);
1056 patch
->new_name
= find_name(state
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1060 static int gitdiff_renamesrc(struct apply_state
*state
,
1062 struct patch
*patch
)
1064 patch
->is_rename
= 1;
1065 free(patch
->old_name
);
1066 patch
->old_name
= find_name(state
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1070 static int gitdiff_renamedst(struct apply_state
*state
,
1072 struct patch
*patch
)
1074 patch
->is_rename
= 1;
1075 free(patch
->new_name
);
1076 patch
->new_name
= find_name(state
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1080 static int gitdiff_similarity(struct apply_state
*state
,
1082 struct patch
*patch
)
1084 unsigned long val
= strtoul(line
, NULL
, 10);
1090 static int gitdiff_dissimilarity(struct apply_state
*state
,
1092 struct patch
*patch
)
1094 unsigned long val
= strtoul(line
, NULL
, 10);
1100 static int gitdiff_index(struct apply_state
*state
,
1102 struct patch
*patch
)
1105 * index line is N hexadecimal, "..", N hexadecimal,
1106 * and optional space with octal mode.
1108 const char *ptr
, *eol
;
1111 ptr
= strchr(line
, '.');
1112 if (!ptr
|| ptr
[1] != '.' || 40 < ptr
- line
)
1115 memcpy(patch
->old_sha1_prefix
, line
, len
);
1116 patch
->old_sha1_prefix
[len
] = 0;
1119 ptr
= strchr(line
, ' ');
1120 eol
= strchrnul(line
, '\n');
1122 if (!ptr
|| eol
< ptr
)
1128 memcpy(patch
->new_sha1_prefix
, line
, len
);
1129 patch
->new_sha1_prefix
[len
] = 0;
1131 return gitdiff_oldmode(state
, ptr
+ 1, patch
);
1136 * This is normal for a diff that doesn't change anything: we'll fall through
1137 * into the next diff. Tell the parser to break out.
1139 static int gitdiff_unrecognized(struct apply_state
*state
,
1141 struct patch
*patch
)
1147 * Skip p_value leading components from "line"; as we do not accept
1148 * absolute paths, return NULL in that case.
1150 static const char *skip_tree_prefix(struct apply_state
*state
,
1157 if (!state
->p_value
)
1158 return (llen
&& line
[0] == '/') ? NULL
: line
;
1160 nslash
= state
->p_value
;
1161 for (i
= 0; i
< llen
; i
++) {
1163 if (ch
== '/' && --nslash
<= 0)
1164 return (i
== 0) ? NULL
: &line
[i
+ 1];
1170 * This is to extract the same name that appears on "diff --git"
1171 * line. We do not find and return anything if it is a rename
1172 * patch, and it is OK because we will find the name elsewhere.
1173 * We need to reliably find name only when it is mode-change only,
1174 * creation or deletion of an empty file. In any of these cases,
1175 * both sides are the same name under a/ and b/ respectively.
1177 static char *git_header_name(struct apply_state
*state
,
1182 const char *second
= NULL
;
1183 size_t len
, line_len
;
1185 line
+= strlen("diff --git ");
1186 llen
-= strlen("diff --git ");
1190 struct strbuf first
= STRBUF_INIT
;
1191 struct strbuf sp
= STRBUF_INIT
;
1193 if (unquote_c_style(&first
, line
, &second
))
1194 goto free_and_fail1
;
1196 /* strip the a/b prefix including trailing slash */
1197 cp
= skip_tree_prefix(state
, first
.buf
, first
.len
);
1199 goto free_and_fail1
;
1200 strbuf_remove(&first
, 0, cp
- first
.buf
);
1203 * second points at one past closing dq of name.
1204 * find the second name.
1206 while ((second
< line
+ llen
) && isspace(*second
))
1209 if (line
+ llen
<= second
)
1210 goto free_and_fail1
;
1211 if (*second
== '"') {
1212 if (unquote_c_style(&sp
, second
, NULL
))
1213 goto free_and_fail1
;
1214 cp
= skip_tree_prefix(state
, sp
.buf
, sp
.len
);
1216 goto free_and_fail1
;
1217 /* They must match, otherwise ignore */
1218 if (strcmp(cp
, first
.buf
))
1219 goto free_and_fail1
;
1220 strbuf_release(&sp
);
1221 return strbuf_detach(&first
, NULL
);
1224 /* unquoted second */
1225 cp
= skip_tree_prefix(state
, second
, line
+ llen
- second
);
1227 goto free_and_fail1
;
1228 if (line
+ llen
- cp
!= first
.len
||
1229 memcmp(first
.buf
, cp
, first
.len
))
1230 goto free_and_fail1
;
1231 return strbuf_detach(&first
, NULL
);
1234 strbuf_release(&first
);
1235 strbuf_release(&sp
);
1239 /* unquoted first name */
1240 name
= skip_tree_prefix(state
, line
, llen
);
1245 * since the first name is unquoted, a dq if exists must be
1246 * the beginning of the second name.
1248 for (second
= name
; second
< line
+ llen
; second
++) {
1249 if (*second
== '"') {
1250 struct strbuf sp
= STRBUF_INIT
;
1253 if (unquote_c_style(&sp
, second
, NULL
))
1254 goto free_and_fail2
;
1256 np
= skip_tree_prefix(state
, sp
.buf
, sp
.len
);
1258 goto free_and_fail2
;
1260 len
= sp
.buf
+ sp
.len
- np
;
1261 if (len
< second
- name
&&
1262 !strncmp(np
, name
, len
) &&
1263 isspace(name
[len
])) {
1265 strbuf_remove(&sp
, 0, np
- sp
.buf
);
1266 return strbuf_detach(&sp
, NULL
);
1270 strbuf_release(&sp
);
1276 * Accept a name only if it shows up twice, exactly the same
1279 second
= strchr(name
, '\n');
1282 line_len
= second
- name
;
1283 for (len
= 0 ; ; len
++) {
1284 switch (name
[len
]) {
1289 case '\t': case ' ':
1291 * Is this the separator between the preimage
1292 * and the postimage pathname? Again, we are
1293 * only interested in the case where there is
1294 * no rename, as this is only to set def_name
1295 * and a rename patch has the names elsewhere
1296 * in an unambiguous form.
1299 return NULL
; /* no postimage name */
1300 second
= skip_tree_prefix(state
, name
+ len
+ 1,
1301 line_len
- (len
+ 1));
1305 * Does len bytes starting at "name" and "second"
1306 * (that are separated by one HT or SP we just
1307 * found) exactly match?
1309 if (second
[len
] == '\n' && !strncmp(name
, second
, len
))
1310 return xmemdupz(name
, len
);
1315 static int check_header_line(struct apply_state
*state
, struct patch
*patch
)
1317 int extensions
= (patch
->is_delete
== 1) + (patch
->is_new
== 1) +
1318 (patch
->is_rename
== 1) + (patch
->is_copy
== 1);
1320 return error(_("inconsistent header lines %d and %d"),
1321 patch
->extension_linenr
, state
->linenr
);
1322 if (extensions
&& !patch
->extension_linenr
)
1323 patch
->extension_linenr
= state
->linenr
;
1327 /* Verify that we recognize the lines following a git header */
1328 static int parse_git_header(struct apply_state
*state
,
1332 struct patch
*patch
)
1334 unsigned long offset
;
1336 /* A git diff has explicit new/delete information, so we don't guess */
1338 patch
->is_delete
= 0;
1341 * Some things may not have the old name in the
1342 * rest of the headers anywhere (pure mode changes,
1343 * or removing or adding empty files), so we get
1344 * the default name from the header.
1346 patch
->def_name
= git_header_name(state
, line
, len
);
1347 if (patch
->def_name
&& state
->root
.len
) {
1348 char *s
= xstrfmt("%s%s", state
->root
.buf
, patch
->def_name
);
1349 free(patch
->def_name
);
1350 patch
->def_name
= s
;
1356 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1357 static const struct opentry
{
1359 int (*fn
)(struct apply_state
*, const char *, struct patch
*);
1361 { "@@ -", gitdiff_hdrend
},
1362 { "--- ", gitdiff_oldname
},
1363 { "+++ ", gitdiff_newname
},
1364 { "old mode ", gitdiff_oldmode
},
1365 { "new mode ", gitdiff_newmode
},
1366 { "deleted file mode ", gitdiff_delete
},
1367 { "new file mode ", gitdiff_newfile
},
1368 { "copy from ", gitdiff_copysrc
},
1369 { "copy to ", gitdiff_copydst
},
1370 { "rename old ", gitdiff_renamesrc
},
1371 { "rename new ", gitdiff_renamedst
},
1372 { "rename from ", gitdiff_renamesrc
},
1373 { "rename to ", gitdiff_renamedst
},
1374 { "similarity index ", gitdiff_similarity
},
1375 { "dissimilarity index ", gitdiff_dissimilarity
},
1376 { "index ", gitdiff_index
},
1377 { "", gitdiff_unrecognized
},
1381 len
= linelen(line
, size
);
1382 if (!len
|| line
[len
-1] != '\n')
1384 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
1385 const struct opentry
*p
= optable
+ i
;
1386 int oplen
= strlen(p
->str
);
1388 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
1390 res
= p
->fn(state
, line
+ oplen
, patch
);
1393 if (check_header_line(state
, patch
))
1404 static int parse_num(const char *line
, unsigned long *p
)
1408 if (!isdigit(*line
))
1410 *p
= strtoul(line
, &ptr
, 10);
1414 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
1415 unsigned long *p1
, unsigned long *p2
)
1419 if (offset
< 0 || offset
>= len
)
1424 digits
= parse_num(line
, p1
);
1434 digits
= parse_num(line
+1, p2
);
1443 ex
= strlen(expect
);
1446 if (memcmp(line
, expect
, ex
))
1452 static void recount_diff(const char *line
, int size
, struct fragment
*fragment
)
1454 int oldlines
= 0, newlines
= 0, ret
= 0;
1457 warning("recount: ignore empty hunk");
1462 int len
= linelen(line
, size
);
1470 case ' ': case '\n':
1482 ret
= size
< 3 || !starts_with(line
, "@@ ");
1485 ret
= size
< 5 || !starts_with(line
, "diff ");
1492 warning(_("recount: unexpected line: %.*s"),
1493 (int)linelen(line
, size
), line
);
1498 fragment
->oldlines
= oldlines
;
1499 fragment
->newlines
= newlines
;
1503 * Parse a unified diff fragment header of the
1504 * form "@@ -a,b +c,d @@"
1506 static int parse_fragment_header(const char *line
, int len
, struct fragment
*fragment
)
1510 if (!len
|| line
[len
-1] != '\n')
1513 /* Figure out the number of lines in a fragment */
1514 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
1515 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
1521 * Find file diff header
1524 * -1 if no header was found
1525 * -128 in case of error
1526 * the size of the header in bytes (called "offset") otherwise
1528 static int find_header(struct apply_state
*state
,
1532 struct patch
*patch
)
1534 unsigned long offset
, len
;
1536 patch
->is_toplevel_relative
= 0;
1537 patch
->is_rename
= patch
->is_copy
= 0;
1538 patch
->is_new
= patch
->is_delete
= -1;
1539 patch
->old_mode
= patch
->new_mode
= 0;
1540 patch
->old_name
= patch
->new_name
= NULL
;
1541 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1542 unsigned long nextlen
;
1544 len
= linelen(line
, size
);
1548 /* Testing this early allows us to take a few shortcuts.. */
1553 * Make sure we don't find any unconnected patch fragments.
1554 * That's a sign that we didn't find a header, and that a
1555 * patch has become corrupted/broken up.
1557 if (!memcmp("@@ -", line
, 4)) {
1558 struct fragment dummy
;
1559 if (parse_fragment_header(line
, len
, &dummy
) < 0)
1561 error(_("patch fragment without header at line %d: %.*s"),
1562 state
->linenr
, (int)len
-1, line
);
1570 * Git patch? It might not have a real patch, just a rename
1571 * or mode change, so we handle that specially
1573 if (!memcmp("diff --git ", line
, 11)) {
1574 int git_hdr_len
= parse_git_header(state
, line
, len
, size
, patch
);
1575 if (git_hdr_len
< 0)
1577 if (git_hdr_len
<= len
)
1579 if (!patch
->old_name
&& !patch
->new_name
) {
1580 if (!patch
->def_name
) {
1581 error(Q_("git diff header lacks filename information when removing "
1582 "%d leading pathname component (line %d)",
1583 "git diff header lacks filename information when removing "
1584 "%d leading pathname components (line %d)",
1586 state
->p_value
, state
->linenr
);
1589 patch
->old_name
= xstrdup(patch
->def_name
);
1590 patch
->new_name
= xstrdup(patch
->def_name
);
1592 if ((!patch
->new_name
&& !patch
->is_delete
) ||
1593 (!patch
->old_name
&& !patch
->is_new
)) {
1594 error(_("git diff header lacks filename information "
1595 "(line %d)"), state
->linenr
);
1598 patch
->is_toplevel_relative
= 1;
1599 *hdrsize
= git_hdr_len
;
1603 /* --- followed by +++ ? */
1604 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
1608 * We only accept unified patches, so we want it to
1609 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1610 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1612 nextlen
= linelen(line
+ len
, size
- len
);
1613 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
1616 /* Ok, we'll consider it a patch */
1617 if (parse_traditional_patch(state
, line
, line
+len
, patch
))
1619 *hdrsize
= len
+ nextlen
;
1626 static void record_ws_error(struct apply_state
*state
,
1637 state
->whitespace_error
++;
1638 if (state
->squelch_whitespace_errors
&&
1639 state
->squelch_whitespace_errors
< state
->whitespace_error
)
1642 err
= whitespace_error_string(result
);
1643 if (state
->apply_verbosity
> verbosity_silent
)
1644 fprintf(stderr
, "%s:%d: %s.\n%.*s\n",
1645 state
->patch_input_file
, linenr
, err
, len
, line
);
1649 static void check_whitespace(struct apply_state
*state
,
1654 unsigned result
= ws_check(line
+ 1, len
- 1, ws_rule
);
1656 record_ws_error(state
, result
, line
+ 1, len
- 2, state
->linenr
);
1660 * Check if the patch has context lines with CRLF or
1661 * the patch wants to remove lines with CRLF.
1663 static void check_old_for_crlf(struct patch
*patch
, const char *line
, int len
)
1665 if (len
>= 2 && line
[len
-1] == '\n' && line
[len
-2] == '\r') {
1666 patch
->ws_rule
|= WS_CR_AT_EOL
;
1667 patch
->crlf_in_old
= 1;
1673 * Parse a unified diff. Note that this really needs to parse each
1674 * fragment separately, since the only way to know the difference
1675 * between a "---" that is part of a patch, and a "---" that starts
1676 * the next patch is to look at the line counts..
1678 static int parse_fragment(struct apply_state
*state
,
1681 struct patch
*patch
,
1682 struct fragment
*fragment
)
1685 int len
= linelen(line
, size
), offset
;
1686 unsigned long oldlines
, newlines
;
1687 unsigned long leading
, trailing
;
1689 offset
= parse_fragment_header(line
, len
, fragment
);
1692 if (offset
> 0 && patch
->recount
)
1693 recount_diff(line
+ offset
, size
- offset
, fragment
);
1694 oldlines
= fragment
->oldlines
;
1695 newlines
= fragment
->newlines
;
1699 /* Parse the thing.. */
1703 added
= deleted
= 0;
1706 offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1707 if (!oldlines
&& !newlines
)
1709 len
= linelen(line
, size
);
1710 if (!len
|| line
[len
-1] != '\n')
1715 case '\n': /* newer GNU diff, an empty context line */
1719 if (!deleted
&& !added
)
1722 check_old_for_crlf(patch
, line
, len
);
1723 if (!state
->apply_in_reverse
&&
1724 state
->ws_error_action
== correct_ws_error
)
1725 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1728 if (!state
->apply_in_reverse
)
1729 check_old_for_crlf(patch
, line
, len
);
1730 if (state
->apply_in_reverse
&&
1731 state
->ws_error_action
!= nowarn_ws_error
)
1732 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1738 if (state
->apply_in_reverse
)
1739 check_old_for_crlf(patch
, line
, len
);
1740 if (!state
->apply_in_reverse
&&
1741 state
->ws_error_action
!= nowarn_ws_error
)
1742 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1749 * We allow "\ No newline at end of file". Depending
1750 * on locale settings when the patch was produced we
1751 * don't know what this line looks like. The only
1752 * thing we do know is that it begins with "\ ".
1753 * Checking for 12 is just for sanity check -- any
1754 * l10n of "\ No newline..." is at least that long.
1757 if (len
< 12 || memcmp(line
, "\\ ", 2))
1762 if (oldlines
|| newlines
)
1764 if (!deleted
&& !added
)
1767 fragment
->leading
= leading
;
1768 fragment
->trailing
= trailing
;
1771 * If a fragment ends with an incomplete line, we failed to include
1772 * it in the above loop because we hit oldlines == newlines == 0
1775 if (12 < size
&& !memcmp(line
, "\\ ", 2))
1776 offset
+= linelen(line
, size
);
1778 patch
->lines_added
+= added
;
1779 patch
->lines_deleted
+= deleted
;
1781 if (0 < patch
->is_new
&& oldlines
)
1782 return error(_("new file depends on old contents"));
1783 if (0 < patch
->is_delete
&& newlines
)
1784 return error(_("deleted file still has contents"));
1789 * We have seen "diff --git a/... b/..." header (or a traditional patch
1790 * header). Read hunks that belong to this patch into fragments and hang
1791 * them to the given patch structure.
1793 * The (fragment->patch, fragment->size) pair points into the memory given
1794 * by the caller, not a copy, when we return.
1797 * -1 in case of error,
1798 * the number of bytes in the patch otherwise.
1800 static int parse_single_patch(struct apply_state
*state
,
1803 struct patch
*patch
)
1805 unsigned long offset
= 0;
1806 unsigned long oldlines
= 0, newlines
= 0, context
= 0;
1807 struct fragment
**fragp
= &patch
->fragments
;
1809 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
1810 struct fragment
*fragment
;
1813 fragment
= xcalloc(1, sizeof(*fragment
));
1814 fragment
->linenr
= state
->linenr
;
1815 len
= parse_fragment(state
, line
, size
, patch
, fragment
);
1818 return error(_("corrupt patch at line %d"), state
->linenr
);
1820 fragment
->patch
= line
;
1821 fragment
->size
= len
;
1822 oldlines
+= fragment
->oldlines
;
1823 newlines
+= fragment
->newlines
;
1824 context
+= fragment
->leading
+ fragment
->trailing
;
1827 fragp
= &fragment
->next
;
1835 * If something was removed (i.e. we have old-lines) it cannot
1836 * be creation, and if something was added it cannot be
1837 * deletion. However, the reverse is not true; --unified=0
1838 * patches that only add are not necessarily creation even
1839 * though they do not have any old lines, and ones that only
1840 * delete are not necessarily deletion.
1842 * Unfortunately, a real creation/deletion patch do _not_ have
1843 * any context line by definition, so we cannot safely tell it
1844 * apart with --unified=0 insanity. At least if the patch has
1845 * more than one hunk it is not creation or deletion.
1847 if (patch
->is_new
< 0 &&
1848 (oldlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1850 if (patch
->is_delete
< 0 &&
1851 (newlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1852 patch
->is_delete
= 0;
1854 if (0 < patch
->is_new
&& oldlines
)
1855 return error(_("new file %s depends on old contents"), patch
->new_name
);
1856 if (0 < patch
->is_delete
&& newlines
)
1857 return error(_("deleted file %s still has contents"), patch
->old_name
);
1858 if (!patch
->is_delete
&& !newlines
&& context
&& state
->apply_verbosity
> verbosity_silent
)
1861 "file %s becomes empty but is not deleted"),
1867 static inline int metadata_changes(struct patch
*patch
)
1869 return patch
->is_rename
> 0 ||
1870 patch
->is_copy
> 0 ||
1871 patch
->is_new
> 0 ||
1873 (patch
->old_mode
&& patch
->new_mode
&&
1874 patch
->old_mode
!= patch
->new_mode
);
1877 static char *inflate_it(const void *data
, unsigned long size
,
1878 unsigned long inflated_size
)
1884 memset(&stream
, 0, sizeof(stream
));
1886 stream
.next_in
= (unsigned char *)data
;
1887 stream
.avail_in
= size
;
1888 stream
.next_out
= out
= xmalloc(inflated_size
);
1889 stream
.avail_out
= inflated_size
;
1890 git_inflate_init(&stream
);
1891 st
= git_inflate(&stream
, Z_FINISH
);
1892 git_inflate_end(&stream
);
1893 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1901 * Read a binary hunk and return a new fragment; fragment->patch
1902 * points at an allocated memory that the caller must free, so
1903 * it is marked as "->free_patch = 1".
1905 static struct fragment
*parse_binary_hunk(struct apply_state
*state
,
1907 unsigned long *sz_p
,
1912 * Expect a line that begins with binary patch method ("literal"
1913 * or "delta"), followed by the length of data before deflating.
1914 * a sequence of 'length-byte' followed by base-85 encoded data
1915 * should follow, terminated by a newline.
1917 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1918 * and we would limit the patch line to 66 characters,
1919 * so one line can fit up to 13 groups that would decode
1920 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1921 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1924 unsigned long size
= *sz_p
;
1925 char *buffer
= *buf_p
;
1927 unsigned long origlen
;
1930 struct fragment
*frag
;
1932 llen
= linelen(buffer
, size
);
1937 if (starts_with(buffer
, "delta ")) {
1938 patch_method
= BINARY_DELTA_DEFLATED
;
1939 origlen
= strtoul(buffer
+ 6, NULL
, 10);
1941 else if (starts_with(buffer
, "literal ")) {
1942 patch_method
= BINARY_LITERAL_DEFLATED
;
1943 origlen
= strtoul(buffer
+ 8, NULL
, 10);
1951 int byte_length
, max_byte_length
, newsize
;
1952 llen
= linelen(buffer
, size
);
1956 /* consume the blank line */
1962 * Minimum line is "A00000\n" which is 7-byte long,
1963 * and the line length must be multiple of 5 plus 2.
1965 if ((llen
< 7) || (llen
-2) % 5)
1967 max_byte_length
= (llen
- 2) / 5 * 4;
1968 byte_length
= *buffer
;
1969 if ('A' <= byte_length
&& byte_length
<= 'Z')
1970 byte_length
= byte_length
- 'A' + 1;
1971 else if ('a' <= byte_length
&& byte_length
<= 'z')
1972 byte_length
= byte_length
- 'a' + 27;
1975 /* if the input length was not multiple of 4, we would
1976 * have filler at the end but the filler should never
1979 if (max_byte_length
< byte_length
||
1980 byte_length
<= max_byte_length
- 4)
1982 newsize
= hunk_size
+ byte_length
;
1983 data
= xrealloc(data
, newsize
);
1984 if (decode_85(data
+ hunk_size
, buffer
+ 1, byte_length
))
1986 hunk_size
= newsize
;
1991 frag
= xcalloc(1, sizeof(*frag
));
1992 frag
->patch
= inflate_it(data
, hunk_size
, origlen
);
1993 frag
->free_patch
= 1;
1997 frag
->size
= origlen
;
2001 frag
->binary_patch_method
= patch_method
;
2007 error(_("corrupt binary patch at line %d: %.*s"),
2008 state
->linenr
-1, llen
-1, buffer
);
2014 * -1 in case of error,
2015 * the length of the parsed binary patch otherwise
2017 static int parse_binary(struct apply_state
*state
,
2020 struct patch
*patch
)
2023 * We have read "GIT binary patch\n"; what follows is a line
2024 * that says the patch method (currently, either "literal" or
2025 * "delta") and the length of data before deflating; a
2026 * sequence of 'length-byte' followed by base-85 encoded data
2029 * When a binary patch is reversible, there is another binary
2030 * hunk in the same format, starting with patch method (either
2031 * "literal" or "delta") with the length of data, and a sequence
2032 * of length-byte + base-85 encoded data, terminated with another
2033 * empty line. This data, when applied to the postimage, produces
2036 struct fragment
*forward
;
2037 struct fragment
*reverse
;
2041 forward
= parse_binary_hunk(state
, &buffer
, &size
, &status
, &used
);
2042 if (!forward
&& !status
)
2043 /* there has to be one hunk (forward hunk) */
2044 return error(_("unrecognized binary patch at line %d"), state
->linenr
-1);
2046 /* otherwise we already gave an error message */
2049 reverse
= parse_binary_hunk(state
, &buffer
, &size
, &status
, &used_1
);
2054 * Not having reverse hunk is not an error, but having
2055 * a corrupt reverse hunk is.
2057 free((void*) forward
->patch
);
2061 forward
->next
= reverse
;
2062 patch
->fragments
= forward
;
2063 patch
->is_binary
= 1;
2067 static void prefix_one(struct apply_state
*state
, char **name
)
2069 char *old_name
= *name
;
2072 *name
= prefix_filename(state
->prefix
, *name
);
2076 static void prefix_patch(struct apply_state
*state
, struct patch
*p
)
2078 if (!state
->prefix
|| p
->is_toplevel_relative
)
2080 prefix_one(state
, &p
->new_name
);
2081 prefix_one(state
, &p
->old_name
);
2088 static void add_name_limit(struct apply_state
*state
,
2092 struct string_list_item
*it
;
2094 it
= string_list_append(&state
->limit_by_name
, name
);
2095 it
->util
= exclude
? NULL
: (void *) 1;
2098 static int use_patch(struct apply_state
*state
, struct patch
*p
)
2100 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
2103 /* Paths outside are not touched regardless of "--include" */
2104 if (state
->prefix
&& *state
->prefix
) {
2106 if (!skip_prefix(pathname
, state
->prefix
, &rest
) || !*rest
)
2110 /* See if it matches any of exclude/include rule */
2111 for (i
= 0; i
< state
->limit_by_name
.nr
; i
++) {
2112 struct string_list_item
*it
= &state
->limit_by_name
.items
[i
];
2113 if (!wildmatch(it
->string
, pathname
, 0))
2114 return (it
->util
!= NULL
);
2118 * If we had any include, a path that does not match any rule is
2119 * not used. Otherwise, we saw bunch of exclude rules (or none)
2120 * and such a path is used.
2122 return !state
->has_include
;
2126 * Read the patch text in "buffer" that extends for "size" bytes; stop
2127 * reading after seeing a single patch (i.e. changes to a single file).
2128 * Create fragments (i.e. patch hunks) and hang them to the given patch.
2131 * -1 if no header was found or parse_binary() failed,
2132 * -128 on another error,
2133 * the number of bytes consumed otherwise,
2134 * so that the caller can call us again for the next patch.
2136 static int parse_chunk(struct apply_state
*state
, char *buffer
, unsigned long size
, struct patch
*patch
)
2138 int hdrsize
, patchsize
;
2139 int offset
= find_header(state
, buffer
, size
, &hdrsize
, patch
);
2144 prefix_patch(state
, patch
);
2146 if (!use_patch(state
, patch
))
2149 patch
->ws_rule
= whitespace_rule(patch
->new_name
2153 patchsize
= parse_single_patch(state
,
2154 buffer
+ offset
+ hdrsize
,
2155 size
- offset
- hdrsize
,
2162 static const char git_binary
[] = "GIT binary patch\n";
2163 int hd
= hdrsize
+ offset
;
2164 unsigned long llen
= linelen(buffer
+ hd
, size
- hd
);
2166 if (llen
== sizeof(git_binary
) - 1 &&
2167 !memcmp(git_binary
, buffer
+ hd
, llen
)) {
2170 used
= parse_binary(state
, buffer
+ hd
+ llen
,
2171 size
- hd
- llen
, patch
);
2175 patchsize
= used
+ llen
;
2179 else if (!memcmp(" differ\n", buffer
+ hd
+ llen
- 8, 8)) {
2180 static const char *binhdr
[] = {
2186 for (i
= 0; binhdr
[i
]; i
++) {
2187 int len
= strlen(binhdr
[i
]);
2188 if (len
< size
- hd
&&
2189 !memcmp(binhdr
[i
], buffer
+ hd
, len
)) {
2191 patch
->is_binary
= 1;
2198 /* Empty patch cannot be applied if it is a text patch
2199 * without metadata change. A binary patch appears
2202 if ((state
->apply
|| state
->check
) &&
2203 (!patch
->is_binary
&& !metadata_changes(patch
))) {
2204 error(_("patch with only garbage at line %d"), state
->linenr
);
2209 return offset
+ hdrsize
+ patchsize
;
2212 static void reverse_patches(struct patch
*p
)
2214 for (; p
; p
= p
->next
) {
2215 struct fragment
*frag
= p
->fragments
;
2217 SWAP(p
->new_name
, p
->old_name
);
2218 SWAP(p
->new_mode
, p
->old_mode
);
2219 SWAP(p
->is_new
, p
->is_delete
);
2220 SWAP(p
->lines_added
, p
->lines_deleted
);
2221 SWAP(p
->old_sha1_prefix
, p
->new_sha1_prefix
);
2223 for (; frag
; frag
= frag
->next
) {
2224 SWAP(frag
->newpos
, frag
->oldpos
);
2225 SWAP(frag
->newlines
, frag
->oldlines
);
2230 static const char pluses
[] =
2231 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2232 static const char minuses
[]=
2233 "----------------------------------------------------------------------";
2235 static void show_stats(struct apply_state
*state
, struct patch
*patch
)
2237 struct strbuf qname
= STRBUF_INIT
;
2238 char *cp
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
2241 quote_c_style(cp
, &qname
, NULL
, 0);
2244 * "scale" the filename
2246 max
= state
->max_len
;
2250 if (qname
.len
> max
) {
2251 cp
= strchr(qname
.buf
+ qname
.len
+ 3 - max
, '/');
2253 cp
= qname
.buf
+ qname
.len
+ 3 - max
;
2254 strbuf_splice(&qname
, 0, cp
- qname
.buf
, "...", 3);
2257 if (patch
->is_binary
) {
2258 printf(" %-*s | Bin\n", max
, qname
.buf
);
2259 strbuf_release(&qname
);
2263 printf(" %-*s |", max
, qname
.buf
);
2264 strbuf_release(&qname
);
2267 * scale the add/delete
2269 max
= max
+ state
->max_change
> 70 ? 70 - max
: state
->max_change
;
2270 add
= patch
->lines_added
;
2271 del
= patch
->lines_deleted
;
2273 if (state
->max_change
> 0) {
2274 int total
= ((add
+ del
) * max
+ state
->max_change
/ 2) / state
->max_change
;
2275 add
= (add
* max
+ state
->max_change
/ 2) / state
->max_change
;
2278 printf("%5d %.*s%.*s\n", patch
->lines_added
+ patch
->lines_deleted
,
2279 add
, pluses
, del
, minuses
);
2282 static int read_old_data(struct stat
*st
, struct patch
*patch
,
2283 const char *path
, struct strbuf
*buf
)
2285 enum safe_crlf safe_crlf
= patch
->crlf_in_old
?
2286 SAFE_CRLF_KEEP_CRLF
: SAFE_CRLF_RENORMALIZE
;
2287 switch (st
->st_mode
& S_IFMT
) {
2289 if (strbuf_readlink(buf
, path
, st
->st_size
) < 0)
2290 return error(_("unable to read symlink %s"), path
);
2293 if (strbuf_read_file(buf
, path
, st
->st_size
) != st
->st_size
)
2294 return error(_("unable to open or read %s"), path
);
2296 * "git apply" without "--index/--cached" should never look
2297 * at the index; the target file may not have been added to
2298 * the index yet, and we may not even be in any Git repository.
2299 * Pass NULL to convert_to_git() to stress this; the function
2300 * should never look at the index when explicit crlf option
2303 convert_to_git(NULL
, path
, buf
->buf
, buf
->len
, buf
, safe_crlf
);
2311 * Update the preimage, and the common lines in postimage,
2312 * from buffer buf of length len. If postlen is 0 the postimage
2313 * is updated in place, otherwise it's updated on a new buffer
2317 static void update_pre_post_images(struct image
*preimage
,
2318 struct image
*postimage
,
2320 size_t len
, size_t postlen
)
2322 int i
, ctx
, reduced
;
2323 char *new, *old
, *fixed
;
2324 struct image fixed_preimage
;
2327 * Update the preimage with whitespace fixes. Note that we
2328 * are not losing preimage->buf -- apply_one_fragment() will
2331 prepare_image(&fixed_preimage
, buf
, len
, 1);
2333 ? fixed_preimage
.nr
== preimage
->nr
2334 : fixed_preimage
.nr
<= preimage
->nr
);
2335 for (i
= 0; i
< fixed_preimage
.nr
; i
++)
2336 fixed_preimage
.line
[i
].flag
= preimage
->line
[i
].flag
;
2337 free(preimage
->line_allocated
);
2338 *preimage
= fixed_preimage
;
2341 * Adjust the common context lines in postimage. This can be
2342 * done in-place when we are shrinking it with whitespace
2343 * fixing, but needs a new buffer when ignoring whitespace or
2344 * expanding leading tabs to spaces.
2346 * We trust the caller to tell us if the update can be done
2347 * in place (postlen==0) or not.
2349 old
= postimage
->buf
;
2351 new = postimage
->buf
= xmalloc(postlen
);
2354 fixed
= preimage
->buf
;
2356 for (i
= reduced
= ctx
= 0; i
< postimage
->nr
; i
++) {
2357 size_t l_len
= postimage
->line
[i
].len
;
2358 if (!(postimage
->line
[i
].flag
& LINE_COMMON
)) {
2359 /* an added line -- no counterparts in preimage */
2360 memmove(new, old
, l_len
);
2366 /* a common context -- skip it in the original postimage */
2369 /* and find the corresponding one in the fixed preimage */
2370 while (ctx
< preimage
->nr
&&
2371 !(preimage
->line
[ctx
].flag
& LINE_COMMON
)) {
2372 fixed
+= preimage
->line
[ctx
].len
;
2377 * preimage is expected to run out, if the caller
2378 * fixed addition of trailing blank lines.
2380 if (preimage
->nr
<= ctx
) {
2385 /* and copy it in, while fixing the line length */
2386 l_len
= preimage
->line
[ctx
].len
;
2387 memcpy(new, fixed
, l_len
);
2390 postimage
->line
[i
].len
= l_len
;
2395 ? postlen
< new - postimage
->buf
2396 : postimage
->len
< new - postimage
->buf
)
2397 die("BUG: caller miscounted postlen: asked %d, orig = %d, used = %d",
2398 (int)postlen
, (int) postimage
->len
, (int)(new - postimage
->buf
));
2400 /* Fix the length of the whole thing */
2401 postimage
->len
= new - postimage
->buf
;
2402 postimage
->nr
-= reduced
;
2405 static int line_by_line_fuzzy_match(struct image
*img
,
2406 struct image
*preimage
,
2407 struct image
*postimage
,
2415 size_t postlen
= postimage
->len
;
2420 struct strbuf fixed
;
2424 for (i
= 0; i
< preimage_limit
; i
++) {
2425 size_t prelen
= preimage
->line
[i
].len
;
2426 size_t imglen
= img
->line
[try_lno
+i
].len
;
2428 if (!fuzzy_matchlines(img
->buf
+ try + imgoff
, imglen
,
2429 preimage
->buf
+ preoff
, prelen
))
2431 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2432 postlen
+= imglen
- prelen
;
2438 * Ok, the preimage matches with whitespace fuzz.
2440 * imgoff now holds the true length of the target that
2441 * matches the preimage before the end of the file.
2443 * Count the number of characters in the preimage that fall
2444 * beyond the end of the file and make sure that all of them
2445 * are whitespace characters. (This can only happen if
2446 * we are removing blank lines at the end of the file.)
2448 buf
= preimage_eof
= preimage
->buf
+ preoff
;
2449 for ( ; i
< preimage
->nr
; i
++)
2450 preoff
+= preimage
->line
[i
].len
;
2451 preimage_end
= preimage
->buf
+ preoff
;
2452 for ( ; buf
< preimage_end
; buf
++)
2457 * Update the preimage and the common postimage context
2458 * lines to use the same whitespace as the target.
2459 * If whitespace is missing in the target (i.e.
2460 * if the preimage extends beyond the end of the file),
2461 * use the whitespace from the preimage.
2463 extra_chars
= preimage_end
- preimage_eof
;
2464 strbuf_init(&fixed
, imgoff
+ extra_chars
);
2465 strbuf_add(&fixed
, img
->buf
+ try, imgoff
);
2466 strbuf_add(&fixed
, preimage_eof
, extra_chars
);
2467 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2468 update_pre_post_images(preimage
, postimage
,
2469 fixed_buf
, fixed_len
, postlen
);
2473 static int match_fragment(struct apply_state
*state
,
2475 struct image
*preimage
,
2476 struct image
*postimage
,
2480 int match_beginning
, int match_end
)
2483 char *fixed_buf
, *buf
, *orig
, *target
;
2484 struct strbuf fixed
;
2485 size_t fixed_len
, postlen
;
2488 if (preimage
->nr
+ try_lno
<= img
->nr
) {
2490 * The hunk falls within the boundaries of img.
2492 preimage_limit
= preimage
->nr
;
2493 if (match_end
&& (preimage
->nr
+ try_lno
!= img
->nr
))
2495 } else if (state
->ws_error_action
== correct_ws_error
&&
2496 (ws_rule
& WS_BLANK_AT_EOF
)) {
2498 * This hunk extends beyond the end of img, and we are
2499 * removing blank lines at the end of the file. This
2500 * many lines from the beginning of the preimage must
2501 * match with img, and the remainder of the preimage
2504 preimage_limit
= img
->nr
- try_lno
;
2507 * The hunk extends beyond the end of the img and
2508 * we are not removing blanks at the end, so we
2509 * should reject the hunk at this position.
2514 if (match_beginning
&& try_lno
)
2517 /* Quick hash check */
2518 for (i
= 0; i
< preimage_limit
; i
++)
2519 if ((img
->line
[try_lno
+ i
].flag
& LINE_PATCHED
) ||
2520 (preimage
->line
[i
].hash
!= img
->line
[try_lno
+ i
].hash
))
2523 if (preimage_limit
== preimage
->nr
) {
2525 * Do we have an exact match? If we were told to match
2526 * at the end, size must be exactly at try+fragsize,
2527 * otherwise try+fragsize must be still within the preimage,
2528 * and either case, the old piece should match the preimage
2532 ? (try + preimage
->len
== img
->len
)
2533 : (try + preimage
->len
<= img
->len
)) &&
2534 !memcmp(img
->buf
+ try, preimage
->buf
, preimage
->len
))
2538 * The preimage extends beyond the end of img, so
2539 * there cannot be an exact match.
2541 * There must be one non-blank context line that match
2542 * a line before the end of img.
2546 buf
= preimage
->buf
;
2548 for (i
= 0; i
< preimage_limit
; i
++)
2549 buf_end
+= preimage
->line
[i
].len
;
2551 for ( ; buf
< buf_end
; buf
++)
2559 * No exact match. If we are ignoring whitespace, run a line-by-line
2560 * fuzzy matching. We collect all the line length information because
2561 * we need it to adjust whitespace if we match.
2563 if (state
->ws_ignore_action
== ignore_ws_change
)
2564 return line_by_line_fuzzy_match(img
, preimage
, postimage
,
2565 try, try_lno
, preimage_limit
);
2567 if (state
->ws_error_action
!= correct_ws_error
)
2571 * The hunk does not apply byte-by-byte, but the hash says
2572 * it might with whitespace fuzz. We weren't asked to
2573 * ignore whitespace, we were asked to correct whitespace
2574 * errors, so let's try matching after whitespace correction.
2576 * While checking the preimage against the target, whitespace
2577 * errors in both fixed, we count how large the corresponding
2578 * postimage needs to be. The postimage prepared by
2579 * apply_one_fragment() has whitespace errors fixed on added
2580 * lines already, but the common lines were propagated as-is,
2581 * which may become longer when their whitespace errors are
2585 /* First count added lines in postimage */
2587 for (i
= 0; i
< postimage
->nr
; i
++) {
2588 if (!(postimage
->line
[i
].flag
& LINE_COMMON
))
2589 postlen
+= postimage
->line
[i
].len
;
2593 * The preimage may extend beyond the end of the file,
2594 * but in this loop we will only handle the part of the
2595 * preimage that falls within the file.
2597 strbuf_init(&fixed
, preimage
->len
+ 1);
2598 orig
= preimage
->buf
;
2599 target
= img
->buf
+ try;
2600 for (i
= 0; i
< preimage_limit
; i
++) {
2601 size_t oldlen
= preimage
->line
[i
].len
;
2602 size_t tgtlen
= img
->line
[try_lno
+ i
].len
;
2603 size_t fixstart
= fixed
.len
;
2604 struct strbuf tgtfix
;
2607 /* Try fixing the line in the preimage */
2608 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2610 /* Try fixing the line in the target */
2611 strbuf_init(&tgtfix
, tgtlen
);
2612 ws_fix_copy(&tgtfix
, target
, tgtlen
, ws_rule
, NULL
);
2615 * If they match, either the preimage was based on
2616 * a version before our tree fixed whitespace breakage,
2617 * or we are lacking a whitespace-fix patch the tree
2618 * the preimage was based on already had (i.e. target
2619 * has whitespace breakage, the preimage doesn't).
2620 * In either case, we are fixing the whitespace breakages
2621 * so we might as well take the fix together with their
2624 match
= (tgtfix
.len
== fixed
.len
- fixstart
&&
2625 !memcmp(tgtfix
.buf
, fixed
.buf
+ fixstart
,
2626 fixed
.len
- fixstart
));
2628 /* Add the length if this is common with the postimage */
2629 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2630 postlen
+= tgtfix
.len
;
2632 strbuf_release(&tgtfix
);
2642 * Now handle the lines in the preimage that falls beyond the
2643 * end of the file (if any). They will only match if they are
2644 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2647 for ( ; i
< preimage
->nr
; i
++) {
2648 size_t fixstart
= fixed
.len
; /* start of the fixed preimage */
2649 size_t oldlen
= preimage
->line
[i
].len
;
2652 /* Try fixing the line in the preimage */
2653 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2655 for (j
= fixstart
; j
< fixed
.len
; j
++)
2656 if (!isspace(fixed
.buf
[j
]))
2663 * Yes, the preimage is based on an older version that still
2664 * has whitespace breakages unfixed, and fixing them makes the
2665 * hunk match. Update the context lines in the postimage.
2667 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2668 if (postlen
< postimage
->len
)
2670 update_pre_post_images(preimage
, postimage
,
2671 fixed_buf
, fixed_len
, postlen
);
2675 strbuf_release(&fixed
);
2679 static int find_pos(struct apply_state
*state
,
2681 struct image
*preimage
,
2682 struct image
*postimage
,
2685 int match_beginning
, int match_end
)
2688 unsigned long backwards
, forwards
, try;
2689 int backwards_lno
, forwards_lno
, try_lno
;
2692 * If match_beginning or match_end is specified, there is no
2693 * point starting from a wrong line that will never match and
2694 * wander around and wait for a match at the specified end.
2696 if (match_beginning
)
2699 line
= img
->nr
- preimage
->nr
;
2702 * Because the comparison is unsigned, the following test
2703 * will also take care of a negative line number that can
2704 * result when match_end and preimage is larger than the target.
2706 if ((size_t) line
> img
->nr
)
2710 for (i
= 0; i
< line
; i
++)
2711 try += img
->line
[i
].len
;
2714 * There's probably some smart way to do this, but I'll leave
2715 * that to the smart and beautiful people. I'm simple and stupid.
2718 backwards_lno
= line
;
2720 forwards_lno
= line
;
2723 for (i
= 0; ; i
++) {
2724 if (match_fragment(state
, img
, preimage
, postimage
,
2725 try, try_lno
, ws_rule
,
2726 match_beginning
, match_end
))
2730 if (backwards_lno
== 0 && forwards_lno
== img
->nr
)
2734 if (backwards_lno
== 0) {
2739 backwards
-= img
->line
[backwards_lno
].len
;
2741 try_lno
= backwards_lno
;
2743 if (forwards_lno
== img
->nr
) {
2747 forwards
+= img
->line
[forwards_lno
].len
;
2750 try_lno
= forwards_lno
;
2757 static void remove_first_line(struct image
*img
)
2759 img
->buf
+= img
->line
[0].len
;
2760 img
->len
-= img
->line
[0].len
;
2765 static void remove_last_line(struct image
*img
)
2767 img
->len
-= img
->line
[--img
->nr
].len
;
2771 * The change from "preimage" and "postimage" has been found to
2772 * apply at applied_pos (counts in line numbers) in "img".
2773 * Update "img" to remove "preimage" and replace it with "postimage".
2775 static void update_image(struct apply_state
*state
,
2778 struct image
*preimage
,
2779 struct image
*postimage
)
2782 * remove the copy of preimage at offset in img
2783 * and replace it with postimage
2786 size_t remove_count
, insert_count
, applied_at
= 0;
2791 * If we are removing blank lines at the end of img,
2792 * the preimage may extend beyond the end.
2793 * If that is the case, we must be careful only to
2794 * remove the part of the preimage that falls within
2795 * the boundaries of img. Initialize preimage_limit
2796 * to the number of lines in the preimage that falls
2797 * within the boundaries.
2799 preimage_limit
= preimage
->nr
;
2800 if (preimage_limit
> img
->nr
- applied_pos
)
2801 preimage_limit
= img
->nr
- applied_pos
;
2803 for (i
= 0; i
< applied_pos
; i
++)
2804 applied_at
+= img
->line
[i
].len
;
2807 for (i
= 0; i
< preimage_limit
; i
++)
2808 remove_count
+= img
->line
[applied_pos
+ i
].len
;
2809 insert_count
= postimage
->len
;
2811 /* Adjust the contents */
2812 result
= xmalloc(st_add3(st_sub(img
->len
, remove_count
), insert_count
, 1));
2813 memcpy(result
, img
->buf
, applied_at
);
2814 memcpy(result
+ applied_at
, postimage
->buf
, postimage
->len
);
2815 memcpy(result
+ applied_at
+ postimage
->len
,
2816 img
->buf
+ (applied_at
+ remove_count
),
2817 img
->len
- (applied_at
+ remove_count
));
2820 img
->len
+= insert_count
- remove_count
;
2821 result
[img
->len
] = '\0';
2823 /* Adjust the line table */
2824 nr
= img
->nr
+ postimage
->nr
- preimage_limit
;
2825 if (preimage_limit
< postimage
->nr
) {
2827 * NOTE: this knows that we never call remove_first_line()
2828 * on anything other than pre/post image.
2830 REALLOC_ARRAY(img
->line
, nr
);
2831 img
->line_allocated
= img
->line
;
2833 if (preimage_limit
!= postimage
->nr
)
2834 MOVE_ARRAY(img
->line
+ applied_pos
+ postimage
->nr
,
2835 img
->line
+ applied_pos
+ preimage_limit
,
2836 img
->nr
- (applied_pos
+ preimage_limit
));
2837 COPY_ARRAY(img
->line
+ applied_pos
, postimage
->line
, postimage
->nr
);
2838 if (!state
->allow_overlap
)
2839 for (i
= 0; i
< postimage
->nr
; i
++)
2840 img
->line
[applied_pos
+ i
].flag
|= LINE_PATCHED
;
2845 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2846 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2847 * replace the part of "img" with "postimage" text.
2849 static int apply_one_fragment(struct apply_state
*state
,
2850 struct image
*img
, struct fragment
*frag
,
2851 int inaccurate_eof
, unsigned ws_rule
,
2854 int match_beginning
, match_end
;
2855 const char *patch
= frag
->patch
;
2856 int size
= frag
->size
;
2857 char *old
, *oldlines
;
2858 struct strbuf newlines
;
2859 int new_blank_lines_at_end
= 0;
2860 int found_new_blank_lines_at_end
= 0;
2861 int hunk_linenr
= frag
->linenr
;
2862 unsigned long leading
, trailing
;
2863 int pos
, applied_pos
;
2864 struct image preimage
;
2865 struct image postimage
;
2867 memset(&preimage
, 0, sizeof(preimage
));
2868 memset(&postimage
, 0, sizeof(postimage
));
2869 oldlines
= xmalloc(size
);
2870 strbuf_init(&newlines
, size
);
2875 int len
= linelen(patch
, size
);
2877 int added_blank_line
= 0;
2878 int is_blank_context
= 0;
2885 * "plen" is how much of the line we should use for
2886 * the actual patch data. Normally we just remove the
2887 * first character on the line, but if the line is
2888 * followed by "\ No newline", then we also remove the
2889 * last one (which is the newline, of course).
2892 if (len
< size
&& patch
[len
] == '\\')
2895 if (state
->apply_in_reverse
) {
2898 else if (first
== '+')
2904 /* Newer GNU diff, empty context line */
2906 /* ... followed by '\No newline'; nothing */
2909 strbuf_addch(&newlines
, '\n');
2910 add_line_info(&preimage
, "\n", 1, LINE_COMMON
);
2911 add_line_info(&postimage
, "\n", 1, LINE_COMMON
);
2912 is_blank_context
= 1;
2915 if (plen
&& (ws_rule
& WS_BLANK_AT_EOF
) &&
2916 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2917 is_blank_context
= 1;
2920 memcpy(old
, patch
+ 1, plen
);
2921 add_line_info(&preimage
, old
, plen
,
2922 (first
== ' ' ? LINE_COMMON
: 0));
2928 /* --no-add does not add new lines */
2929 if (first
== '+' && state
->no_add
)
2932 start
= newlines
.len
;
2934 !state
->whitespace_error
||
2935 state
->ws_error_action
!= correct_ws_error
) {
2936 strbuf_add(&newlines
, patch
+ 1, plen
);
2939 ws_fix_copy(&newlines
, patch
+ 1, plen
, ws_rule
, &state
->applied_after_fixing_ws
);
2941 add_line_info(&postimage
, newlines
.buf
+ start
, newlines
.len
- start
,
2942 (first
== '+' ? 0 : LINE_COMMON
));
2944 (ws_rule
& WS_BLANK_AT_EOF
) &&
2945 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2946 added_blank_line
= 1;
2948 case '@': case '\\':
2949 /* Ignore it, we already handled it */
2952 if (state
->apply_verbosity
> verbosity_normal
)
2953 error(_("invalid start of line: '%c'"), first
);
2957 if (added_blank_line
) {
2958 if (!new_blank_lines_at_end
)
2959 found_new_blank_lines_at_end
= hunk_linenr
;
2960 new_blank_lines_at_end
++;
2962 else if (is_blank_context
)
2965 new_blank_lines_at_end
= 0;
2970 if (inaccurate_eof
&&
2971 old
> oldlines
&& old
[-1] == '\n' &&
2972 newlines
.len
> 0 && newlines
.buf
[newlines
.len
- 1] == '\n') {
2974 strbuf_setlen(&newlines
, newlines
.len
- 1);
2977 leading
= frag
->leading
;
2978 trailing
= frag
->trailing
;
2981 * A hunk to change lines at the beginning would begin with
2983 * but we need to be careful. -U0 that inserts before the second
2984 * line also has this pattern.
2986 * And a hunk to add to an empty file would begin with
2989 * In other words, a hunk that is (frag->oldpos <= 1) with or
2990 * without leading context must match at the beginning.
2992 match_beginning
= (!frag
->oldpos
||
2993 (frag
->oldpos
== 1 && !state
->unidiff_zero
));
2996 * A hunk without trailing lines must match at the end.
2997 * However, we simply cannot tell if a hunk must match end
2998 * from the lack of trailing lines if the patch was generated
2999 * with unidiff without any context.
3001 match_end
= !state
->unidiff_zero
&& !trailing
;
3003 pos
= frag
->newpos
? (frag
->newpos
- 1) : 0;
3004 preimage
.buf
= oldlines
;
3005 preimage
.len
= old
- oldlines
;
3006 postimage
.buf
= newlines
.buf
;
3007 postimage
.len
= newlines
.len
;
3008 preimage
.line
= preimage
.line_allocated
;
3009 postimage
.line
= postimage
.line_allocated
;
3013 applied_pos
= find_pos(state
, img
, &preimage
, &postimage
, pos
,
3014 ws_rule
, match_beginning
, match_end
);
3016 if (applied_pos
>= 0)
3019 /* Am I at my context limits? */
3020 if ((leading
<= state
->p_context
) && (trailing
<= state
->p_context
))
3022 if (match_beginning
|| match_end
) {
3023 match_beginning
= match_end
= 0;
3028 * Reduce the number of context lines; reduce both
3029 * leading and trailing if they are equal otherwise
3030 * just reduce the larger context.
3032 if (leading
>= trailing
) {
3033 remove_first_line(&preimage
);
3034 remove_first_line(&postimage
);
3038 if (trailing
> leading
) {
3039 remove_last_line(&preimage
);
3040 remove_last_line(&postimage
);
3045 if (applied_pos
>= 0) {
3046 if (new_blank_lines_at_end
&&
3047 preimage
.nr
+ applied_pos
>= img
->nr
&&
3048 (ws_rule
& WS_BLANK_AT_EOF
) &&
3049 state
->ws_error_action
!= nowarn_ws_error
) {
3050 record_ws_error(state
, WS_BLANK_AT_EOF
, "+", 1,
3051 found_new_blank_lines_at_end
);
3052 if (state
->ws_error_action
== correct_ws_error
) {
3053 while (new_blank_lines_at_end
--)
3054 remove_last_line(&postimage
);
3057 * We would want to prevent write_out_results()
3058 * from taking place in apply_patch() that follows
3059 * the callchain led us here, which is:
3060 * apply_patch->check_patch_list->check_patch->
3061 * apply_data->apply_fragments->apply_one_fragment
3063 if (state
->ws_error_action
== die_on_ws_error
)
3067 if (state
->apply_verbosity
> verbosity_normal
&& applied_pos
!= pos
) {
3068 int offset
= applied_pos
- pos
;
3069 if (state
->apply_in_reverse
)
3070 offset
= 0 - offset
;
3072 Q_("Hunk #%d succeeded at %d (offset %d line).",
3073 "Hunk #%d succeeded at %d (offset %d lines).",
3075 nth_fragment
, applied_pos
+ 1, offset
);
3079 * Warn if it was necessary to reduce the number
3082 if ((leading
!= frag
->leading
||
3083 trailing
!= frag
->trailing
) && state
->apply_verbosity
> verbosity_silent
)
3084 fprintf_ln(stderr
, _("Context reduced to (%ld/%ld)"
3085 " to apply fragment at %d"),
3086 leading
, trailing
, applied_pos
+1);
3087 update_image(state
, img
, applied_pos
, &preimage
, &postimage
);
3089 if (state
->apply_verbosity
> verbosity_normal
)
3090 error(_("while searching for:\n%.*s"),
3091 (int)(old
- oldlines
), oldlines
);
3096 strbuf_release(&newlines
);
3097 free(preimage
.line_allocated
);
3098 free(postimage
.line_allocated
);
3100 return (applied_pos
< 0);
3103 static int apply_binary_fragment(struct apply_state
*state
,
3105 struct patch
*patch
)
3107 struct fragment
*fragment
= patch
->fragments
;
3112 return error(_("missing binary patch data for '%s'"),
3117 /* Binary patch is irreversible without the optional second hunk */
3118 if (state
->apply_in_reverse
) {
3119 if (!fragment
->next
)
3120 return error(_("cannot reverse-apply a binary patch "
3121 "without the reverse hunk to '%s'"),
3123 ? patch
->new_name
: patch
->old_name
);
3124 fragment
= fragment
->next
;
3126 switch (fragment
->binary_patch_method
) {
3127 case BINARY_DELTA_DEFLATED
:
3128 dst
= patch_delta(img
->buf
, img
->len
, fragment
->patch
,
3129 fragment
->size
, &len
);
3136 case BINARY_LITERAL_DEFLATED
:
3138 img
->len
= fragment
->size
;
3139 img
->buf
= xmemdupz(fragment
->patch
, img
->len
);
3146 * Replace "img" with the result of applying the binary patch.
3147 * The binary patch data itself in patch->fragment is still kept
3148 * but the preimage prepared by the caller in "img" is freed here
3149 * or in the helper function apply_binary_fragment() this calls.
3151 static int apply_binary(struct apply_state
*state
,
3153 struct patch
*patch
)
3155 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3156 struct object_id oid
;
3159 * For safety, we require patch index line to contain
3160 * full 40-byte textual SHA1 for old and new, at least for now.
3162 if (strlen(patch
->old_sha1_prefix
) != 40 ||
3163 strlen(patch
->new_sha1_prefix
) != 40 ||
3164 get_oid_hex(patch
->old_sha1_prefix
, &oid
) ||
3165 get_oid_hex(patch
->new_sha1_prefix
, &oid
))
3166 return error(_("cannot apply binary patch to '%s' "
3167 "without full index line"), name
);
3169 if (patch
->old_name
) {
3171 * See if the old one matches what the patch
3174 hash_sha1_file(img
->buf
, img
->len
, blob_type
, oid
.hash
);
3175 if (strcmp(oid_to_hex(&oid
), patch
->old_sha1_prefix
))
3176 return error(_("the patch applies to '%s' (%s), "
3177 "which does not match the "
3178 "current contents."),
3179 name
, oid_to_hex(&oid
));
3182 /* Otherwise, the old one must be empty. */
3184 return error(_("the patch applies to an empty "
3185 "'%s' but it is not empty"), name
);
3188 get_oid_hex(patch
->new_sha1_prefix
, &oid
);
3189 if (is_null_oid(&oid
)) {
3191 return 0; /* deletion patch */
3194 if (has_sha1_file(oid
.hash
)) {
3195 /* We already have the postimage */
3196 enum object_type type
;
3200 result
= read_sha1_file(oid
.hash
, &type
, &size
);
3202 return error(_("the necessary postimage %s for "
3203 "'%s' cannot be read"),
3204 patch
->new_sha1_prefix
, name
);
3210 * We have verified buf matches the preimage;
3211 * apply the patch data to it, which is stored
3212 * in the patch->fragments->{patch,size}.
3214 if (apply_binary_fragment(state
, img
, patch
))
3215 return error(_("binary patch does not apply to '%s'"),
3218 /* verify that the result matches */
3219 hash_sha1_file(img
->buf
, img
->len
, blob_type
, oid
.hash
);
3220 if (strcmp(oid_to_hex(&oid
), patch
->new_sha1_prefix
))
3221 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3222 name
, patch
->new_sha1_prefix
, oid_to_hex(&oid
));
3228 static int apply_fragments(struct apply_state
*state
, struct image
*img
, struct patch
*patch
)
3230 struct fragment
*frag
= patch
->fragments
;
3231 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3232 unsigned ws_rule
= patch
->ws_rule
;
3233 unsigned inaccurate_eof
= patch
->inaccurate_eof
;
3236 if (patch
->is_binary
)
3237 return apply_binary(state
, img
, patch
);
3241 if (apply_one_fragment(state
, img
, frag
, inaccurate_eof
, ws_rule
, nth
)) {
3242 error(_("patch failed: %s:%ld"), name
, frag
->oldpos
);
3243 if (!state
->apply_with_reject
)
3252 static int read_blob_object(struct strbuf
*buf
, const struct object_id
*oid
, unsigned mode
)
3254 if (S_ISGITLINK(mode
)) {
3255 strbuf_grow(buf
, 100);
3256 strbuf_addf(buf
, "Subproject commit %s\n", oid_to_hex(oid
));
3258 enum object_type type
;
3262 result
= read_sha1_file(oid
->hash
, &type
, &sz
);
3265 /* XXX read_sha1_file NUL-terminates */
3266 strbuf_attach(buf
, result
, sz
, sz
+ 1);
3271 static int read_file_or_gitlink(const struct cache_entry
*ce
, struct strbuf
*buf
)
3275 return read_blob_object(buf
, &ce
->oid
, ce
->ce_mode
);
3278 static struct patch
*in_fn_table(struct apply_state
*state
, const char *name
)
3280 struct string_list_item
*item
;
3285 item
= string_list_lookup(&state
->fn_table
, name
);
3287 return (struct patch
*)item
->util
;
3293 * item->util in the filename table records the status of the path.
3294 * Usually it points at a patch (whose result records the contents
3295 * of it after applying it), but it could be PATH_WAS_DELETED for a
3296 * path that a previously applied patch has already removed, or
3297 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3299 * The latter is needed to deal with a case where two paths A and B
3300 * are swapped by first renaming A to B and then renaming B to A;
3301 * moving A to B should not be prevented due to presence of B as we
3302 * will remove it in a later patch.
3304 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3305 #define PATH_WAS_DELETED ((struct patch *) -1)
3307 static int to_be_deleted(struct patch
*patch
)
3309 return patch
== PATH_TO_BE_DELETED
;
3312 static int was_deleted(struct patch
*patch
)
3314 return patch
== PATH_WAS_DELETED
;
3317 static void add_to_fn_table(struct apply_state
*state
, struct patch
*patch
)
3319 struct string_list_item
*item
;
3322 * Always add new_name unless patch is a deletion
3323 * This should cover the cases for normal diffs,
3324 * file creations and copies
3326 if (patch
->new_name
!= NULL
) {
3327 item
= string_list_insert(&state
->fn_table
, patch
->new_name
);
3332 * store a failure on rename/deletion cases because
3333 * later chunks shouldn't patch old names
3335 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3336 item
= string_list_insert(&state
->fn_table
, patch
->old_name
);
3337 item
->util
= PATH_WAS_DELETED
;
3341 static void prepare_fn_table(struct apply_state
*state
, struct patch
*patch
)
3344 * store information about incoming file deletion
3347 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3348 struct string_list_item
*item
;
3349 item
= string_list_insert(&state
->fn_table
, patch
->old_name
);
3350 item
->util
= PATH_TO_BE_DELETED
;
3352 patch
= patch
->next
;
3356 static int checkout_target(struct index_state
*istate
,
3357 struct cache_entry
*ce
, struct stat
*st
)
3359 struct checkout costate
= CHECKOUT_INIT
;
3361 costate
.refresh_cache
= 1;
3362 costate
.istate
= istate
;
3363 if (checkout_entry(ce
, &costate
, NULL
) || lstat(ce
->name
, st
))
3364 return error(_("cannot checkout %s"), ce
->name
);
3368 static struct patch
*previous_patch(struct apply_state
*state
,
3369 struct patch
*patch
,
3372 struct patch
*previous
;
3375 if (patch
->is_copy
|| patch
->is_rename
)
3376 return NULL
; /* "git" patches do not depend on the order */
3378 previous
= in_fn_table(state
, patch
->old_name
);
3382 if (to_be_deleted(previous
))
3383 return NULL
; /* the deletion hasn't happened yet */
3385 if (was_deleted(previous
))
3391 static int verify_index_match(const struct cache_entry
*ce
, struct stat
*st
)
3393 if (S_ISGITLINK(ce
->ce_mode
)) {
3394 if (!S_ISDIR(st
->st_mode
))
3398 return ce_match_stat(ce
, st
, CE_MATCH_IGNORE_VALID
|CE_MATCH_IGNORE_SKIP_WORKTREE
);
3401 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3403 static int load_patch_target(struct apply_state
*state
,
3405 const struct cache_entry
*ce
,
3407 struct patch
*patch
,
3409 unsigned expected_mode
)
3411 if (state
->cached
|| state
->check_index
) {
3412 if (read_file_or_gitlink(ce
, buf
))
3413 return error(_("failed to read %s"), name
);
3415 if (S_ISGITLINK(expected_mode
)) {
3417 return read_file_or_gitlink(ce
, buf
);
3419 return SUBMODULE_PATCH_WITHOUT_INDEX
;
3420 } else if (has_symlink_leading_path(name
, strlen(name
))) {
3421 return error(_("reading from '%s' beyond a symbolic link"), name
);
3423 if (read_old_data(st
, patch
, name
, buf
))
3424 return error(_("failed to read %s"), name
);
3431 * We are about to apply "patch"; populate the "image" with the
3432 * current version we have, from the working tree or from the index,
3433 * depending on the situation e.g. --cached/--index. If we are
3434 * applying a non-git patch that incrementally updates the tree,
3435 * we read from the result of a previous diff.
3437 static int load_preimage(struct apply_state
*state
,
3438 struct image
*image
,
3439 struct patch
*patch
, struct stat
*st
,
3440 const struct cache_entry
*ce
)
3442 struct strbuf buf
= STRBUF_INIT
;
3445 struct patch
*previous
;
3448 previous
= previous_patch(state
, patch
, &status
);
3450 return error(_("path %s has been renamed/deleted"),
3453 /* We have a patched copy in memory; use that. */
3454 strbuf_add(&buf
, previous
->result
, previous
->resultsize
);
3456 status
= load_patch_target(state
, &buf
, ce
, st
, patch
,
3457 patch
->old_name
, patch
->old_mode
);
3460 else if (status
== SUBMODULE_PATCH_WITHOUT_INDEX
) {
3462 * There is no way to apply subproject
3463 * patch without looking at the index.
3464 * NEEDSWORK: shouldn't this be flagged
3467 free_fragment_list(patch
->fragments
);
3468 patch
->fragments
= NULL
;
3469 } else if (status
) {
3470 return error(_("failed to read %s"), patch
->old_name
);
3474 img
= strbuf_detach(&buf
, &len
);
3475 prepare_image(image
, img
, len
, !patch
->is_binary
);
3479 static int three_way_merge(struct image
*image
,
3481 const struct object_id
*base
,
3482 const struct object_id
*ours
,
3483 const struct object_id
*theirs
)
3485 mmfile_t base_file
, our_file
, their_file
;
3486 mmbuffer_t result
= { NULL
};
3489 read_mmblob(&base_file
, base
);
3490 read_mmblob(&our_file
, ours
);
3491 read_mmblob(&their_file
, theirs
);
3492 status
= ll_merge(&result
, path
,
3495 &their_file
, "theirs", NULL
);
3496 free(base_file
.ptr
);
3498 free(their_file
.ptr
);
3499 if (status
< 0 || !result
.ptr
) {
3504 image
->buf
= result
.ptr
;
3505 image
->len
= result
.size
;
3511 * When directly falling back to add/add three-way merge, we read from
3512 * the current contents of the new_name. In no cases other than that
3513 * this function will be called.
3515 static int load_current(struct apply_state
*state
,
3516 struct image
*image
,
3517 struct patch
*patch
)
3519 struct strbuf buf
= STRBUF_INIT
;
3524 struct cache_entry
*ce
;
3525 char *name
= patch
->new_name
;
3526 unsigned mode
= patch
->new_mode
;
3529 die("BUG: patch to %s is not a creation", patch
->old_name
);
3531 pos
= cache_name_pos(name
, strlen(name
));
3533 return error(_("%s: does not exist in index"), name
);
3534 ce
= active_cache
[pos
];
3535 if (lstat(name
, &st
)) {
3536 if (errno
!= ENOENT
)
3537 return error_errno("%s", name
);
3538 if (checkout_target(&the_index
, ce
, &st
))
3541 if (verify_index_match(ce
, &st
))
3542 return error(_("%s: does not match index"), name
);
3544 status
= load_patch_target(state
, &buf
, ce
, &st
, patch
, name
, mode
);
3549 img
= strbuf_detach(&buf
, &len
);
3550 prepare_image(image
, img
, len
, !patch
->is_binary
);
3554 static int try_threeway(struct apply_state
*state
,
3555 struct image
*image
,
3556 struct patch
*patch
,
3558 const struct cache_entry
*ce
)
3560 struct object_id pre_oid
, post_oid
, our_oid
;
3561 struct strbuf buf
= STRBUF_INIT
;
3565 struct image tmp_image
;
3567 /* No point falling back to 3-way merge in these cases */
3568 if (patch
->is_delete
||
3569 S_ISGITLINK(patch
->old_mode
) || S_ISGITLINK(patch
->new_mode
))
3572 /* Preimage the patch was prepared for */
3574 write_sha1_file("", 0, blob_type
, pre_oid
.hash
);
3575 else if (get_oid(patch
->old_sha1_prefix
, &pre_oid
) ||
3576 read_blob_object(&buf
, &pre_oid
, patch
->old_mode
))
3577 return error(_("repository lacks the necessary blob to fall back on 3-way merge."));
3579 if (state
->apply_verbosity
> verbosity_silent
)
3580 fprintf(stderr
, _("Falling back to three-way merge...\n"));
3582 img
= strbuf_detach(&buf
, &len
);
3583 prepare_image(&tmp_image
, img
, len
, 1);
3584 /* Apply the patch to get the post image */
3585 if (apply_fragments(state
, &tmp_image
, patch
) < 0) {
3586 clear_image(&tmp_image
);
3589 /* post_oid is theirs */
3590 write_sha1_file(tmp_image
.buf
, tmp_image
.len
, blob_type
, post_oid
.hash
);
3591 clear_image(&tmp_image
);
3593 /* our_oid is ours */
3594 if (patch
->is_new
) {
3595 if (load_current(state
, &tmp_image
, patch
))
3596 return error(_("cannot read the current contents of '%s'"),
3599 if (load_preimage(state
, &tmp_image
, patch
, st
, ce
))
3600 return error(_("cannot read the current contents of '%s'"),
3603 write_sha1_file(tmp_image
.buf
, tmp_image
.len
, blob_type
, our_oid
.hash
);
3604 clear_image(&tmp_image
);
3606 /* in-core three-way merge between post and our using pre as base */
3607 status
= three_way_merge(image
, patch
->new_name
,
3608 &pre_oid
, &our_oid
, &post_oid
);
3610 if (state
->apply_verbosity
> verbosity_silent
)
3612 _("Failed to fall back on three-way merge...\n"));
3617 patch
->conflicted_threeway
= 1;
3619 oidclr(&patch
->threeway_stage
[0]);
3621 oidcpy(&patch
->threeway_stage
[0], &pre_oid
);
3622 oidcpy(&patch
->threeway_stage
[1], &our_oid
);
3623 oidcpy(&patch
->threeway_stage
[2], &post_oid
);
3624 if (state
->apply_verbosity
> verbosity_silent
)
3626 _("Applied patch to '%s' with conflicts.\n"),
3629 if (state
->apply_verbosity
> verbosity_silent
)
3631 _("Applied patch to '%s' cleanly.\n"),
3637 static int apply_data(struct apply_state
*state
, struct patch
*patch
,
3638 struct stat
*st
, const struct cache_entry
*ce
)
3642 if (load_preimage(state
, &image
, patch
, st
, ce
) < 0)
3645 if (patch
->direct_to_threeway
||
3646 apply_fragments(state
, &image
, patch
) < 0) {
3647 /* Note: with --reject, apply_fragments() returns 0 */
3648 if (!state
->threeway
|| try_threeway(state
, &image
, patch
, st
, ce
) < 0)
3651 patch
->result
= image
.buf
;
3652 patch
->resultsize
= image
.len
;
3653 add_to_fn_table(state
, patch
);
3654 free(image
.line_allocated
);
3656 if (0 < patch
->is_delete
&& patch
->resultsize
)
3657 return error(_("removal patch leaves file contents"));
3663 * If "patch" that we are looking at modifies or deletes what we have,
3664 * we would want it not to lose any local modification we have, either
3665 * in the working tree or in the index.
3667 * This also decides if a non-git patch is a creation patch or a
3668 * modification to an existing empty file. We do not check the state
3669 * of the current tree for a creation patch in this function; the caller
3670 * check_patch() separately makes sure (and errors out otherwise) that
3671 * the path the patch creates does not exist in the current tree.
3673 static int check_preimage(struct apply_state
*state
,
3674 struct patch
*patch
,
3675 struct cache_entry
**ce
,
3678 const char *old_name
= patch
->old_name
;
3679 struct patch
*previous
= NULL
;
3680 int stat_ret
= 0, status
;
3681 unsigned st_mode
= 0;
3686 assert(patch
->is_new
<= 0);
3687 previous
= previous_patch(state
, patch
, &status
);
3690 return error(_("path %s has been renamed/deleted"), old_name
);
3692 st_mode
= previous
->new_mode
;
3693 } else if (!state
->cached
) {
3694 stat_ret
= lstat(old_name
, st
);
3695 if (stat_ret
&& errno
!= ENOENT
)
3696 return error_errno("%s", old_name
);
3699 if (state
->check_index
&& !previous
) {
3700 int pos
= cache_name_pos(old_name
, strlen(old_name
));
3702 if (patch
->is_new
< 0)
3704 return error(_("%s: does not exist in index"), old_name
);
3706 *ce
= active_cache
[pos
];
3708 if (checkout_target(&the_index
, *ce
, st
))
3711 if (!state
->cached
&& verify_index_match(*ce
, st
))
3712 return error(_("%s: does not match index"), old_name
);
3714 st_mode
= (*ce
)->ce_mode
;
3715 } else if (stat_ret
< 0) {
3716 if (patch
->is_new
< 0)
3718 return error_errno("%s", old_name
);
3721 if (!state
->cached
&& !previous
)
3722 st_mode
= ce_mode_from_stat(*ce
, st
->st_mode
);
3724 if (patch
->is_new
< 0)
3726 if (!patch
->old_mode
)
3727 patch
->old_mode
= st_mode
;
3728 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
3729 return error(_("%s: wrong type"), old_name
);
3730 if (st_mode
!= patch
->old_mode
)
3731 warning(_("%s has type %o, expected %o"),
3732 old_name
, st_mode
, patch
->old_mode
);
3733 if (!patch
->new_mode
&& !patch
->is_delete
)
3734 patch
->new_mode
= st_mode
;
3739 patch
->is_delete
= 0;
3740 FREE_AND_NULL(patch
->old_name
);
3745 #define EXISTS_IN_INDEX 1
3746 #define EXISTS_IN_WORKTREE 2
3748 static int check_to_create(struct apply_state
*state
,
3749 const char *new_name
,
3754 if (state
->check_index
&&
3755 cache_name_pos(new_name
, strlen(new_name
)) >= 0 &&
3757 return EXISTS_IN_INDEX
;
3761 if (!lstat(new_name
, &nst
)) {
3762 if (S_ISDIR(nst
.st_mode
) || ok_if_exists
)
3765 * A leading component of new_name might be a symlink
3766 * that is going to be removed with this patch, but
3767 * still pointing at somewhere that has the path.
3768 * In such a case, path "new_name" does not exist as
3769 * far as git is concerned.
3771 if (has_symlink_leading_path(new_name
, strlen(new_name
)))
3774 return EXISTS_IN_WORKTREE
;
3775 } else if (!is_missing_file_error(errno
)) {
3776 return error_errno("%s", new_name
);
3781 static uintptr_t register_symlink_changes(struct apply_state
*state
,
3785 struct string_list_item
*ent
;
3787 ent
= string_list_lookup(&state
->symlink_changes
, path
);
3789 ent
= string_list_insert(&state
->symlink_changes
, path
);
3790 ent
->util
= (void *)0;
3792 ent
->util
= (void *)(what
| ((uintptr_t)ent
->util
));
3793 return (uintptr_t)ent
->util
;
3796 static uintptr_t check_symlink_changes(struct apply_state
*state
, const char *path
)
3798 struct string_list_item
*ent
;
3800 ent
= string_list_lookup(&state
->symlink_changes
, path
);
3803 return (uintptr_t)ent
->util
;
3806 static void prepare_symlink_changes(struct apply_state
*state
, struct patch
*patch
)
3808 for ( ; patch
; patch
= patch
->next
) {
3809 if ((patch
->old_name
&& S_ISLNK(patch
->old_mode
)) &&
3810 (patch
->is_rename
|| patch
->is_delete
))
3811 /* the symlink at patch->old_name is removed */
3812 register_symlink_changes(state
, patch
->old_name
, APPLY_SYMLINK_GOES_AWAY
);
3814 if (patch
->new_name
&& S_ISLNK(patch
->new_mode
))
3815 /* the symlink at patch->new_name is created or remains */
3816 register_symlink_changes(state
, patch
->new_name
, APPLY_SYMLINK_IN_RESULT
);
3820 static int path_is_beyond_symlink_1(struct apply_state
*state
, struct strbuf
*name
)
3823 unsigned int change
;
3825 while (--name
->len
&& name
->buf
[name
->len
] != '/')
3826 ; /* scan backwards */
3829 name
->buf
[name
->len
] = '\0';
3830 change
= check_symlink_changes(state
, name
->buf
);
3831 if (change
& APPLY_SYMLINK_IN_RESULT
)
3833 if (change
& APPLY_SYMLINK_GOES_AWAY
)
3835 * This cannot be "return 0", because we may
3836 * see a new one created at a higher level.
3840 /* otherwise, check the preimage */
3841 if (state
->check_index
) {
3842 struct cache_entry
*ce
;
3844 ce
= cache_file_exists(name
->buf
, name
->len
, ignore_case
);
3845 if (ce
&& S_ISLNK(ce
->ce_mode
))
3849 if (!lstat(name
->buf
, &st
) && S_ISLNK(st
.st_mode
))
3856 static int path_is_beyond_symlink(struct apply_state
*state
, const char *name_
)
3859 struct strbuf name
= STRBUF_INIT
;
3861 assert(*name_
!= '\0');
3862 strbuf_addstr(&name
, name_
);
3863 ret
= path_is_beyond_symlink_1(state
, &name
);
3864 strbuf_release(&name
);
3869 static int check_unsafe_path(struct patch
*patch
)
3871 const char *old_name
= NULL
;
3872 const char *new_name
= NULL
;
3873 if (patch
->is_delete
)
3874 old_name
= patch
->old_name
;
3875 else if (!patch
->is_new
&& !patch
->is_copy
)
3876 old_name
= patch
->old_name
;
3877 if (!patch
->is_delete
)
3878 new_name
= patch
->new_name
;
3880 if (old_name
&& !verify_path(old_name
))
3881 return error(_("invalid path '%s'"), old_name
);
3882 if (new_name
&& !verify_path(new_name
))
3883 return error(_("invalid path '%s'"), new_name
);
3888 * Check and apply the patch in-core; leave the result in patch->result
3889 * for the caller to write it out to the final destination.
3891 static int check_patch(struct apply_state
*state
, struct patch
*patch
)
3894 const char *old_name
= patch
->old_name
;
3895 const char *new_name
= patch
->new_name
;
3896 const char *name
= old_name
? old_name
: new_name
;
3897 struct cache_entry
*ce
= NULL
;
3898 struct patch
*tpatch
;
3902 patch
->rejected
= 1; /* we will drop this after we succeed */
3904 status
= check_preimage(state
, patch
, &ce
, &st
);
3907 old_name
= patch
->old_name
;
3910 * A type-change diff is always split into a patch to delete
3911 * old, immediately followed by a patch to create new (see
3912 * diff.c::run_diff()); in such a case it is Ok that the entry
3913 * to be deleted by the previous patch is still in the working
3914 * tree and in the index.
3916 * A patch to swap-rename between A and B would first rename A
3917 * to B and then rename B to A. While applying the first one,
3918 * the presence of B should not stop A from getting renamed to
3919 * B; ask to_be_deleted() about the later rename. Removal of
3920 * B and rename from A to B is handled the same way by asking
3923 if ((tpatch
= in_fn_table(state
, new_name
)) &&
3924 (was_deleted(tpatch
) || to_be_deleted(tpatch
)))
3930 ((0 < patch
->is_new
) || patch
->is_rename
|| patch
->is_copy
)) {
3931 int err
= check_to_create(state
, new_name
, ok_if_exists
);
3933 if (err
&& state
->threeway
) {
3934 patch
->direct_to_threeway
= 1;
3935 } else switch (err
) {
3938 case EXISTS_IN_INDEX
:
3939 return error(_("%s: already exists in index"), new_name
);
3941 case EXISTS_IN_WORKTREE
:
3942 return error(_("%s: already exists in working directory"),
3948 if (!patch
->new_mode
) {
3949 if (0 < patch
->is_new
)
3950 patch
->new_mode
= S_IFREG
| 0644;
3952 patch
->new_mode
= patch
->old_mode
;
3956 if (new_name
&& old_name
) {
3957 int same
= !strcmp(old_name
, new_name
);
3958 if (!patch
->new_mode
)
3959 patch
->new_mode
= patch
->old_mode
;
3960 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
) {
3962 return error(_("new mode (%o) of %s does not "
3963 "match old mode (%o)"),
3964 patch
->new_mode
, new_name
,
3967 return error(_("new mode (%o) of %s does not "
3968 "match old mode (%o) of %s"),
3969 patch
->new_mode
, new_name
,
3970 patch
->old_mode
, old_name
);
3974 if (!state
->unsafe_paths
&& check_unsafe_path(patch
))
3978 * An attempt to read from or delete a path that is beyond a
3979 * symbolic link will be prevented by load_patch_target() that
3980 * is called at the beginning of apply_data() so we do not
3981 * have to worry about a patch marked with "is_delete" bit
3982 * here. We however need to make sure that the patch result
3983 * is not deposited to a path that is beyond a symbolic link
3986 if (!patch
->is_delete
&& path_is_beyond_symlink(state
, patch
->new_name
))
3987 return error(_("affected file '%s' is beyond a symbolic link"),
3990 if (apply_data(state
, patch
, &st
, ce
) < 0)
3991 return error(_("%s: patch does not apply"), name
);
3992 patch
->rejected
= 0;
3996 static int check_patch_list(struct apply_state
*state
, struct patch
*patch
)
4000 prepare_symlink_changes(state
, patch
);
4001 prepare_fn_table(state
, patch
);
4004 if (state
->apply_verbosity
> verbosity_normal
)
4005 say_patch_name(stderr
,
4006 _("Checking patch %s..."), patch
);
4007 res
= check_patch(state
, patch
);
4011 patch
= patch
->next
;
4016 static int read_apply_cache(struct apply_state
*state
)
4018 if (state
->index_file
)
4019 return read_cache_from(state
->index_file
);
4021 return read_cache();
4024 /* This function tries to read the object name from the current index */
4025 static int get_current_oid(struct apply_state
*state
, const char *path
,
4026 struct object_id
*oid
)
4030 if (read_apply_cache(state
) < 0)
4032 pos
= cache_name_pos(path
, strlen(path
));
4035 oidcpy(oid
, &active_cache
[pos
]->oid
);
4039 static int preimage_oid_in_gitlink_patch(struct patch
*p
, struct object_id
*oid
)
4042 * A usable gitlink patch has only one fragment (hunk) that looks like:
4044 * -Subproject commit <old sha1>
4045 * +Subproject commit <new sha1>
4048 * -Subproject commit <old sha1>
4049 * for a removal patch.
4051 struct fragment
*hunk
= p
->fragments
;
4052 static const char heading
[] = "-Subproject commit ";
4055 if (/* does the patch have only one hunk? */
4056 hunk
&& !hunk
->next
&&
4057 /* is its preimage one line? */
4058 hunk
->oldpos
== 1 && hunk
->oldlines
== 1 &&
4059 /* does preimage begin with the heading? */
4060 (preimage
= memchr(hunk
->patch
, '\n', hunk
->size
)) != NULL
&&
4061 starts_with(++preimage
, heading
) &&
4062 /* does it record full SHA-1? */
4063 !get_oid_hex(preimage
+ sizeof(heading
) - 1, oid
) &&
4064 preimage
[sizeof(heading
) + GIT_SHA1_HEXSZ
- 1] == '\n' &&
4065 /* does the abbreviated name on the index line agree with it? */
4066 starts_with(preimage
+ sizeof(heading
) - 1, p
->old_sha1_prefix
))
4067 return 0; /* it all looks fine */
4069 /* we may have full object name on the index line */
4070 return get_oid_hex(p
->old_sha1_prefix
, oid
);
4073 /* Build an index that contains the just the files needed for a 3way merge */
4074 static int build_fake_ancestor(struct apply_state
*state
, struct patch
*list
)
4076 struct patch
*patch
;
4077 struct index_state result
= { NULL
};
4078 static struct lock_file lock
;
4081 /* Once we start supporting the reverse patch, it may be
4082 * worth showing the new sha1 prefix, but until then...
4084 for (patch
= list
; patch
; patch
= patch
->next
) {
4085 struct object_id oid
;
4086 struct cache_entry
*ce
;
4089 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
4090 if (0 < patch
->is_new
)
4093 if (S_ISGITLINK(patch
->old_mode
)) {
4094 if (!preimage_oid_in_gitlink_patch(patch
, &oid
))
4095 ; /* ok, the textual part looks sane */
4097 return error(_("sha1 information is lacking or "
4098 "useless for submodule %s"), name
);
4099 } else if (!get_oid_blob(patch
->old_sha1_prefix
, &oid
)) {
4101 } else if (!patch
->lines_added
&& !patch
->lines_deleted
) {
4102 /* mode-only change: update the current */
4103 if (get_current_oid(state
, patch
->old_name
, &oid
))
4104 return error(_("mode change for %s, which is not "
4105 "in current HEAD"), name
);
4107 return error(_("sha1 information is lacking or useless "
4110 ce
= make_cache_entry(patch
->old_mode
, oid
.hash
, name
, 0, 0);
4112 return error(_("make_cache_entry failed for path '%s'"),
4114 if (add_index_entry(&result
, ce
, ADD_CACHE_OK_TO_ADD
)) {
4116 return error(_("could not add %s to temporary index"),
4121 hold_lock_file_for_update(&lock
, state
->fake_ancestor
, LOCK_DIE_ON_ERROR
);
4122 res
= write_locked_index(&result
, &lock
, COMMIT_LOCK
);
4123 discard_index(&result
);
4126 return error(_("could not write temporary index to %s"),
4127 state
->fake_ancestor
);
4132 static void stat_patch_list(struct apply_state
*state
, struct patch
*patch
)
4134 int files
, adds
, dels
;
4136 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
4138 adds
+= patch
->lines_added
;
4139 dels
+= patch
->lines_deleted
;
4140 show_stats(state
, patch
);
4143 print_stat_summary(stdout
, files
, adds
, dels
);
4146 static void numstat_patch_list(struct apply_state
*state
,
4147 struct patch
*patch
)
4149 for ( ; patch
; patch
= patch
->next
) {
4151 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
4152 if (patch
->is_binary
)
4155 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
4156 write_name_quoted(name
, stdout
, state
->line_termination
);
4160 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
4163 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
4165 printf(" %s %s\n", newdelete
, name
);
4168 static void show_mode_change(struct patch
*p
, int show_name
)
4170 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
4172 printf(" mode change %06o => %06o %s\n",
4173 p
->old_mode
, p
->new_mode
, p
->new_name
);
4175 printf(" mode change %06o => %06o\n",
4176 p
->old_mode
, p
->new_mode
);
4180 static void show_rename_copy(struct patch
*p
)
4182 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
4183 const char *old
, *new;
4185 /* Find common prefix */
4189 const char *slash_old
, *slash_new
;
4190 slash_old
= strchr(old
, '/');
4191 slash_new
= strchr(new, '/');
4194 slash_old
- old
!= slash_new
- new ||
4195 memcmp(old
, new, slash_new
- new))
4197 old
= slash_old
+ 1;
4198 new = slash_new
+ 1;
4200 /* p->old_name thru old is the common prefix, and old and new
4201 * through the end of names are renames
4203 if (old
!= p
->old_name
)
4204 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
4205 (int)(old
- p
->old_name
), p
->old_name
,
4206 old
, new, p
->score
);
4208 printf(" %s %s => %s (%d%%)\n", renamecopy
,
4209 p
->old_name
, p
->new_name
, p
->score
);
4210 show_mode_change(p
, 0);
4213 static void summary_patch_list(struct patch
*patch
)
4217 for (p
= patch
; p
; p
= p
->next
) {
4219 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
4220 else if (p
->is_delete
)
4221 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
4223 if (p
->is_rename
|| p
->is_copy
)
4224 show_rename_copy(p
);
4227 printf(" rewrite %s (%d%%)\n",
4228 p
->new_name
, p
->score
);
4229 show_mode_change(p
, 0);
4232 show_mode_change(p
, 1);
4238 static void patch_stats(struct apply_state
*state
, struct patch
*patch
)
4240 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
4242 if (lines
> state
->max_change
)
4243 state
->max_change
= lines
;
4244 if (patch
->old_name
) {
4245 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
4247 len
= strlen(patch
->old_name
);
4248 if (len
> state
->max_len
)
4249 state
->max_len
= len
;
4251 if (patch
->new_name
) {
4252 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
4254 len
= strlen(patch
->new_name
);
4255 if (len
> state
->max_len
)
4256 state
->max_len
= len
;
4260 static int remove_file(struct apply_state
*state
, struct patch
*patch
, int rmdir_empty
)
4262 if (state
->update_index
) {
4263 if (remove_file_from_cache(patch
->old_name
) < 0)
4264 return error(_("unable to remove %s from index"), patch
->old_name
);
4266 if (!state
->cached
) {
4267 if (!remove_or_warn(patch
->old_mode
, patch
->old_name
) && rmdir_empty
) {
4268 remove_path(patch
->old_name
);
4274 static int add_index_file(struct apply_state
*state
,
4281 struct cache_entry
*ce
;
4282 int namelen
= strlen(path
);
4283 unsigned ce_size
= cache_entry_size(namelen
);
4285 if (!state
->update_index
)
4288 ce
= xcalloc(1, ce_size
);
4289 memcpy(ce
->name
, path
, namelen
);
4290 ce
->ce_mode
= create_ce_mode(mode
);
4291 ce
->ce_flags
= create_ce_flags(0);
4292 ce
->ce_namelen
= namelen
;
4293 if (S_ISGITLINK(mode
)) {
4296 if (!skip_prefix(buf
, "Subproject commit ", &s
) ||
4297 get_oid_hex(s
, &ce
->oid
)) {
4299 return error(_("corrupt patch for submodule %s"), path
);
4302 if (!state
->cached
) {
4303 if (lstat(path
, &st
) < 0) {
4305 return error_errno(_("unable to stat newly "
4306 "created file '%s'"),
4309 fill_stat_cache_info(ce
, &st
);
4311 if (write_sha1_file(buf
, size
, blob_type
, ce
->oid
.hash
) < 0) {
4313 return error(_("unable to create backing store "
4314 "for newly created file %s"), path
);
4317 if (add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
) < 0) {
4319 return error(_("unable to add cache entry for %s"), path
);
4327 * -1 if an unrecoverable error happened
4328 * 0 if everything went well
4329 * 1 if a recoverable error happened
4331 static int try_create_file(const char *path
, unsigned int mode
, const char *buf
, unsigned long size
)
4334 struct strbuf nbuf
= STRBUF_INIT
;
4336 if (S_ISGITLINK(mode
)) {
4338 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
))
4340 return !!mkdir(path
, 0777);
4343 if (has_symlinks
&& S_ISLNK(mode
))
4344 /* Although buf:size is counted string, it also is NUL
4347 return !!symlink(buf
, path
);
4349 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
4353 if (convert_to_working_tree(path
, buf
, size
, &nbuf
)) {
4358 res
= write_in_full(fd
, buf
, size
) < 0;
4360 error_errno(_("failed to write to '%s'"), path
);
4361 strbuf_release(&nbuf
);
4363 if (close(fd
) < 0 && !res
)
4364 return error_errno(_("closing file '%s'"), path
);
4366 return res
? -1 : 0;
4370 * We optimistically assume that the directories exist,
4371 * which is true 99% of the time anyway. If they don't,
4372 * we create them and try again.
4378 static int create_one_file(struct apply_state
*state
,
4389 res
= try_create_file(path
, mode
, buf
, size
);
4395 if (errno
== ENOENT
) {
4396 if (safe_create_leading_directories(path
))
4398 res
= try_create_file(path
, mode
, buf
, size
);
4405 if (errno
== EEXIST
|| errno
== EACCES
) {
4406 /* We may be trying to create a file where a directory
4410 if (!lstat(path
, &st
) && (!S_ISDIR(st
.st_mode
) || !rmdir(path
)))
4414 if (errno
== EEXIST
) {
4415 unsigned int nr
= getpid();
4418 char newpath
[PATH_MAX
];
4419 mksnpath(newpath
, sizeof(newpath
), "%s~%u", path
, nr
);
4420 res
= try_create_file(newpath
, mode
, buf
, size
);
4424 if (!rename(newpath
, path
))
4426 unlink_or_warn(newpath
);
4429 if (errno
!= EEXIST
)
4434 return error_errno(_("unable to write file '%s' mode %o"),
4438 static int add_conflicted_stages_file(struct apply_state
*state
,
4439 struct patch
*patch
)
4442 unsigned ce_size
, mode
;
4443 struct cache_entry
*ce
;
4445 if (!state
->update_index
)
4447 namelen
= strlen(patch
->new_name
);
4448 ce_size
= cache_entry_size(namelen
);
4449 mode
= patch
->new_mode
? patch
->new_mode
: (S_IFREG
| 0644);
4451 remove_file_from_cache(patch
->new_name
);
4452 for (stage
= 1; stage
< 4; stage
++) {
4453 if (is_null_oid(&patch
->threeway_stage
[stage
- 1]))
4455 ce
= xcalloc(1, ce_size
);
4456 memcpy(ce
->name
, patch
->new_name
, namelen
);
4457 ce
->ce_mode
= create_ce_mode(mode
);
4458 ce
->ce_flags
= create_ce_flags(stage
);
4459 ce
->ce_namelen
= namelen
;
4460 oidcpy(&ce
->oid
, &patch
->threeway_stage
[stage
- 1]);
4461 if (add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
) < 0) {
4463 return error(_("unable to add cache entry for %s"),
4471 static int create_file(struct apply_state
*state
, struct patch
*patch
)
4473 char *path
= patch
->new_name
;
4474 unsigned mode
= patch
->new_mode
;
4475 unsigned long size
= patch
->resultsize
;
4476 char *buf
= patch
->result
;
4479 mode
= S_IFREG
| 0644;
4480 if (create_one_file(state
, path
, mode
, buf
, size
))
4483 if (patch
->conflicted_threeway
)
4484 return add_conflicted_stages_file(state
, patch
);
4486 return add_index_file(state
, path
, mode
, buf
, size
);
4489 /* phase zero is to remove, phase one is to create */
4490 static int write_out_one_result(struct apply_state
*state
,
4491 struct patch
*patch
,
4494 if (patch
->is_delete
> 0) {
4496 return remove_file(state
, patch
, 1);
4499 if (patch
->is_new
> 0 || patch
->is_copy
) {
4501 return create_file(state
, patch
);
4505 * Rename or modification boils down to the same
4506 * thing: remove the old, write the new
4509 return remove_file(state
, patch
, patch
->is_rename
);
4511 return create_file(state
, patch
);
4515 static int write_out_one_reject(struct apply_state
*state
, struct patch
*patch
)
4518 char namebuf
[PATH_MAX
];
4519 struct fragment
*frag
;
4521 struct strbuf sb
= STRBUF_INIT
;
4523 for (cnt
= 0, frag
= patch
->fragments
; frag
; frag
= frag
->next
) {
4524 if (!frag
->rejected
)
4530 if (state
->apply_verbosity
> verbosity_normal
)
4531 say_patch_name(stderr
,
4532 _("Applied patch %s cleanly."), patch
);
4536 /* This should not happen, because a removal patch that leaves
4537 * contents are marked "rejected" at the patch level.
4539 if (!patch
->new_name
)
4540 die(_("internal error"));
4542 /* Say this even without --verbose */
4543 strbuf_addf(&sb
, Q_("Applying patch %%s with %d reject...",
4544 "Applying patch %%s with %d rejects...",
4547 if (state
->apply_verbosity
> verbosity_silent
)
4548 say_patch_name(stderr
, sb
.buf
, patch
);
4549 strbuf_release(&sb
);
4551 cnt
= strlen(patch
->new_name
);
4552 if (ARRAY_SIZE(namebuf
) <= cnt
+ 5) {
4553 cnt
= ARRAY_SIZE(namebuf
) - 5;
4554 warning(_("truncating .rej filename to %.*s.rej"),
4555 cnt
- 1, patch
->new_name
);
4557 memcpy(namebuf
, patch
->new_name
, cnt
);
4558 memcpy(namebuf
+ cnt
, ".rej", 5);
4560 rej
= fopen(namebuf
, "w");
4562 return error_errno(_("cannot open %s"), namebuf
);
4564 /* Normal git tools never deal with .rej, so do not pretend
4565 * this is a git patch by saying --git or giving extended
4566 * headers. While at it, maybe please "kompare" that wants
4567 * the trailing TAB and some garbage at the end of line ;-).
4569 fprintf(rej
, "diff a/%s b/%s\t(rejected hunks)\n",
4570 patch
->new_name
, patch
->new_name
);
4571 for (cnt
= 1, frag
= patch
->fragments
;
4573 cnt
++, frag
= frag
->next
) {
4574 if (!frag
->rejected
) {
4575 if (state
->apply_verbosity
> verbosity_silent
)
4576 fprintf_ln(stderr
, _("Hunk #%d applied cleanly."), cnt
);
4579 if (state
->apply_verbosity
> verbosity_silent
)
4580 fprintf_ln(stderr
, _("Rejected hunk #%d."), cnt
);
4581 fprintf(rej
, "%.*s", frag
->size
, frag
->patch
);
4582 if (frag
->patch
[frag
->size
-1] != '\n')
4591 * -1 if an error happened
4592 * 0 if the patch applied cleanly
4593 * 1 if the patch did not apply cleanly
4595 static int write_out_results(struct apply_state
*state
, struct patch
*list
)
4600 struct string_list cpath
= STRING_LIST_INIT_DUP
;
4602 for (phase
= 0; phase
< 2; phase
++) {
4608 if (write_out_one_result(state
, l
, phase
)) {
4609 string_list_clear(&cpath
, 0);
4613 if (write_out_one_reject(state
, l
))
4615 if (l
->conflicted_threeway
) {
4616 string_list_append(&cpath
, l
->new_name
);
4626 struct string_list_item
*item
;
4628 string_list_sort(&cpath
);
4629 if (state
->apply_verbosity
> verbosity_silent
) {
4630 for_each_string_list_item(item
, &cpath
)
4631 fprintf(stderr
, "U %s\n", item
->string
);
4633 string_list_clear(&cpath
, 0);
4642 * Try to apply a patch.
4645 * -128 if a bad error happened (like patch unreadable)
4646 * -1 if patch did not apply and user cannot deal with it
4647 * 0 if the patch applied
4648 * 1 if the patch did not apply but user might fix it
4650 static int apply_patch(struct apply_state
*state
,
4652 const char *filename
,
4656 struct strbuf buf
= STRBUF_INIT
; /* owns the patch text */
4657 struct patch
*list
= NULL
, **listp
= &list
;
4658 int skipped_patch
= 0;
4661 state
->patch_input_file
= filename
;
4662 if (read_patch_file(&buf
, fd
) < 0)
4665 while (offset
< buf
.len
) {
4666 struct patch
*patch
;
4669 patch
= xcalloc(1, sizeof(*patch
));
4670 patch
->inaccurate_eof
= !!(options
& APPLY_OPT_INACCURATE_EOF
);
4671 patch
->recount
= !!(options
& APPLY_OPT_RECOUNT
);
4672 nr
= parse_chunk(state
, buf
.buf
+ offset
, buf
.len
- offset
, patch
);
4681 if (state
->apply_in_reverse
)
4682 reverse_patches(patch
);
4683 if (use_patch(state
, patch
)) {
4684 patch_stats(state
, patch
);
4686 listp
= &patch
->next
;
4689 if (state
->apply_verbosity
> verbosity_normal
)
4690 say_patch_name(stderr
, _("Skipped patch '%s'."), patch
);
4697 if (!list
&& !skipped_patch
) {
4698 error(_("unrecognized input"));
4703 if (state
->whitespace_error
&& (state
->ws_error_action
== die_on_ws_error
))
4706 state
->update_index
= state
->check_index
&& state
->apply
;
4707 if (state
->update_index
&& !is_lock_file_locked(&state
->lock_file
)) {
4708 if (state
->index_file
)
4709 hold_lock_file_for_update(&state
->lock_file
,
4713 hold_locked_index(&state
->lock_file
, LOCK_DIE_ON_ERROR
);
4716 if (state
->check_index
&& read_apply_cache(state
) < 0) {
4717 error(_("unable to read index file"));
4722 if (state
->check
|| state
->apply
) {
4723 int r
= check_patch_list(state
, list
);
4728 if (r
< 0 && !state
->apply_with_reject
) {
4735 int write_res
= write_out_results(state
, list
);
4736 if (write_res
< 0) {
4740 if (write_res
> 0) {
4741 /* with --3way, we still need to write the index out */
4742 res
= state
->apply_with_reject
? -1 : 1;
4747 if (state
->fake_ancestor
&&
4748 build_fake_ancestor(state
, list
)) {
4753 if (state
->diffstat
&& state
->apply_verbosity
> verbosity_silent
)
4754 stat_patch_list(state
, list
);
4756 if (state
->numstat
&& state
->apply_verbosity
> verbosity_silent
)
4757 numstat_patch_list(state
, list
);
4759 if (state
->summary
&& state
->apply_verbosity
> verbosity_silent
)
4760 summary_patch_list(list
);
4763 free_patch_list(list
);
4764 strbuf_release(&buf
);
4765 string_list_clear(&state
->fn_table
, 0);
4769 static int apply_option_parse_exclude(const struct option
*opt
,
4770 const char *arg
, int unset
)
4772 struct apply_state
*state
= opt
->value
;
4773 add_name_limit(state
, arg
, 1);
4777 static int apply_option_parse_include(const struct option
*opt
,
4778 const char *arg
, int unset
)
4780 struct apply_state
*state
= opt
->value
;
4781 add_name_limit(state
, arg
, 0);
4782 state
->has_include
= 1;
4786 static int apply_option_parse_p(const struct option
*opt
,
4790 struct apply_state
*state
= opt
->value
;
4791 state
->p_value
= atoi(arg
);
4792 state
->p_value_known
= 1;
4796 static int apply_option_parse_space_change(const struct option
*opt
,
4797 const char *arg
, int unset
)
4799 struct apply_state
*state
= opt
->value
;
4801 state
->ws_ignore_action
= ignore_ws_none
;
4803 state
->ws_ignore_action
= ignore_ws_change
;
4807 static int apply_option_parse_whitespace(const struct option
*opt
,
4808 const char *arg
, int unset
)
4810 struct apply_state
*state
= opt
->value
;
4811 state
->whitespace_option
= arg
;
4812 if (parse_whitespace_option(state
, arg
))
4817 static int apply_option_parse_directory(const struct option
*opt
,
4818 const char *arg
, int unset
)
4820 struct apply_state
*state
= opt
->value
;
4821 strbuf_reset(&state
->root
);
4822 strbuf_addstr(&state
->root
, arg
);
4823 strbuf_complete(&state
->root
, '/');
4827 int apply_all_patches(struct apply_state
*state
,
4837 for (i
= 0; i
< argc
; i
++) {
4838 const char *arg
= argv
[i
];
4839 char *to_free
= NULL
;
4842 if (!strcmp(arg
, "-")) {
4843 res
= apply_patch(state
, 0, "<stdin>", options
);
4850 arg
= to_free
= prefix_filename(state
->prefix
, arg
);
4852 fd
= open(arg
, O_RDONLY
);
4854 error(_("can't open patch '%s': %s"), arg
, strerror(errno
));
4860 set_default_whitespace_mode(state
);
4861 res
= apply_patch(state
, fd
, arg
, options
);
4868 set_default_whitespace_mode(state
);
4870 res
= apply_patch(state
, 0, "<stdin>", options
);
4876 if (state
->whitespace_error
) {
4877 if (state
->squelch_whitespace_errors
&&
4878 state
->squelch_whitespace_errors
< state
->whitespace_error
) {
4880 state
->whitespace_error
- state
->squelch_whitespace_errors
;
4881 warning(Q_("squelched %d whitespace error",
4882 "squelched %d whitespace errors",
4886 if (state
->ws_error_action
== die_on_ws_error
) {
4887 error(Q_("%d line adds whitespace errors.",
4888 "%d lines add whitespace errors.",
4889 state
->whitespace_error
),
4890 state
->whitespace_error
);
4894 if (state
->applied_after_fixing_ws
&& state
->apply
)
4895 warning(Q_("%d line applied after"
4896 " fixing whitespace errors.",
4897 "%d lines applied after"
4898 " fixing whitespace errors.",
4899 state
->applied_after_fixing_ws
),
4900 state
->applied_after_fixing_ws
);
4901 else if (state
->whitespace_error
)
4902 warning(Q_("%d line adds whitespace errors.",
4903 "%d lines add whitespace errors.",
4904 state
->whitespace_error
),
4905 state
->whitespace_error
);
4908 if (state
->update_index
) {
4909 res
= write_locked_index(&the_index
, &state
->lock_file
, COMMIT_LOCK
);
4911 error(_("Unable to write new index file"));
4920 rollback_lock_file(&state
->lock_file
);
4922 if (state
->apply_verbosity
<= verbosity_silent
) {
4923 set_error_routine(state
->saved_error_routine
);
4924 set_warn_routine(state
->saved_warn_routine
);
4929 return (res
== -1 ? 1 : 128);
4932 int apply_parse_options(int argc
, const char **argv
,
4933 struct apply_state
*state
,
4934 int *force_apply
, int *options
,
4935 const char * const *apply_usage
)
4937 struct option builtin_apply_options
[] = {
4938 { OPTION_CALLBACK
, 0, "exclude", state
, N_("path"),
4939 N_("don't apply changes matching the given path"),
4940 0, apply_option_parse_exclude
},
4941 { OPTION_CALLBACK
, 0, "include", state
, N_("path"),
4942 N_("apply changes matching the given path"),
4943 0, apply_option_parse_include
},
4944 { OPTION_CALLBACK
, 'p', NULL
, state
, N_("num"),
4945 N_("remove <num> leading slashes from traditional diff paths"),
4946 0, apply_option_parse_p
},
4947 OPT_BOOL(0, "no-add", &state
->no_add
,
4948 N_("ignore additions made by the patch")),
4949 OPT_BOOL(0, "stat", &state
->diffstat
,
4950 N_("instead of applying the patch, output diffstat for the input")),
4951 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
4952 OPT_NOOP_NOARG(0, "binary"),
4953 OPT_BOOL(0, "numstat", &state
->numstat
,
4954 N_("show number of added and deleted lines in decimal notation")),
4955 OPT_BOOL(0, "summary", &state
->summary
,
4956 N_("instead of applying the patch, output a summary for the input")),
4957 OPT_BOOL(0, "check", &state
->check
,
4958 N_("instead of applying the patch, see if the patch is applicable")),
4959 OPT_BOOL(0, "index", &state
->check_index
,
4960 N_("make sure the patch is applicable to the current index")),
4961 OPT_BOOL(0, "cached", &state
->cached
,
4962 N_("apply a patch without touching the working tree")),
4963 OPT_BOOL(0, "unsafe-paths", &state
->unsafe_paths
,
4964 N_("accept a patch that touches outside the working area")),
4965 OPT_BOOL(0, "apply", force_apply
,
4966 N_("also apply the patch (use with --stat/--summary/--check)")),
4967 OPT_BOOL('3', "3way", &state
->threeway
,
4968 N_( "attempt three-way merge if a patch does not apply")),
4969 OPT_FILENAME(0, "build-fake-ancestor", &state
->fake_ancestor
,
4970 N_("build a temporary index based on embedded index information")),
4971 /* Think twice before adding "--nul" synonym to this */
4972 OPT_SET_INT('z', NULL
, &state
->line_termination
,
4973 N_("paths are separated with NUL character"), '\0'),
4974 OPT_INTEGER('C', NULL
, &state
->p_context
,
4975 N_("ensure at least <n> lines of context match")),
4976 { OPTION_CALLBACK
, 0, "whitespace", state
, N_("action"),
4977 N_("detect new or modified lines that have whitespace errors"),
4978 0, apply_option_parse_whitespace
},
4979 { OPTION_CALLBACK
, 0, "ignore-space-change", state
, NULL
,
4980 N_("ignore changes in whitespace when finding context"),
4981 PARSE_OPT_NOARG
, apply_option_parse_space_change
},
4982 { OPTION_CALLBACK
, 0, "ignore-whitespace", state
, NULL
,
4983 N_("ignore changes in whitespace when finding context"),
4984 PARSE_OPT_NOARG
, apply_option_parse_space_change
},
4985 OPT_BOOL('R', "reverse", &state
->apply_in_reverse
,
4986 N_("apply the patch in reverse")),
4987 OPT_BOOL(0, "unidiff-zero", &state
->unidiff_zero
,
4988 N_("don't expect at least one line of context")),
4989 OPT_BOOL(0, "reject", &state
->apply_with_reject
,
4990 N_("leave the rejected hunks in corresponding *.rej files")),
4991 OPT_BOOL(0, "allow-overlap", &state
->allow_overlap
,
4992 N_("allow overlapping hunks")),
4993 OPT__VERBOSE(&state
->apply_verbosity
, N_("be verbose")),
4994 OPT_BIT(0, "inaccurate-eof", options
,
4995 N_("tolerate incorrectly detected missing new-line at the end of file"),
4996 APPLY_OPT_INACCURATE_EOF
),
4997 OPT_BIT(0, "recount", options
,
4998 N_("do not trust the line counts in the hunk headers"),
5000 { OPTION_CALLBACK
, 0, "directory", state
, N_("root"),
5001 N_("prepend <root> to all filenames"),
5002 0, apply_option_parse_directory
},
5006 return parse_options(argc
, argv
, state
->prefix
, builtin_apply_options
, apply_usage
, 0);