4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
12 #include "object-store.h"
17 #include "xdiff-interface.h"
20 #include "parse-options.h"
25 static void git_apply_config(void)
27 git_config_get_string_const("apply.whitespace", &apply_default_whitespace
);
28 git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace
);
29 git_config(git_default_config
, NULL
);
32 static int parse_whitespace_option(struct apply_state
*state
, const char *option
)
35 state
->ws_error_action
= warn_on_ws_error
;
38 if (!strcmp(option
, "warn")) {
39 state
->ws_error_action
= warn_on_ws_error
;
42 if (!strcmp(option
, "nowarn")) {
43 state
->ws_error_action
= nowarn_ws_error
;
46 if (!strcmp(option
, "error")) {
47 state
->ws_error_action
= die_on_ws_error
;
50 if (!strcmp(option
, "error-all")) {
51 state
->ws_error_action
= die_on_ws_error
;
52 state
->squelch_whitespace_errors
= 0;
55 if (!strcmp(option
, "strip") || !strcmp(option
, "fix")) {
56 state
->ws_error_action
= correct_ws_error
;
60 * Please update $__git_whitespacelist in git-completion.bash
61 * when you add new options.
63 return error(_("unrecognized whitespace option '%s'"), option
);
66 static int parse_ignorewhitespace_option(struct apply_state
*state
,
69 if (!option
|| !strcmp(option
, "no") ||
70 !strcmp(option
, "false") || !strcmp(option
, "never") ||
71 !strcmp(option
, "none")) {
72 state
->ws_ignore_action
= ignore_ws_none
;
75 if (!strcmp(option
, "change")) {
76 state
->ws_ignore_action
= ignore_ws_change
;
79 return error(_("unrecognized whitespace ignore option '%s'"), option
);
82 int init_apply_state(struct apply_state
*state
,
83 struct repository
*repo
,
86 memset(state
, 0, sizeof(*state
));
87 state
->prefix
= prefix
;
90 state
->line_termination
= '\n';
92 state
->p_context
= UINT_MAX
;
93 state
->squelch_whitespace_errors
= 5;
94 state
->ws_error_action
= warn_on_ws_error
;
95 state
->ws_ignore_action
= ignore_ws_none
;
97 string_list_init(&state
->fn_table
, 0);
98 string_list_init(&state
->limit_by_name
, 0);
99 string_list_init(&state
->symlink_changes
, 0);
100 strbuf_init(&state
->root
, 0);
103 if (apply_default_whitespace
&& parse_whitespace_option(state
, apply_default_whitespace
))
105 if (apply_default_ignorewhitespace
&& parse_ignorewhitespace_option(state
, apply_default_ignorewhitespace
))
110 void clear_apply_state(struct apply_state
*state
)
112 string_list_clear(&state
->limit_by_name
, 0);
113 string_list_clear(&state
->symlink_changes
, 0);
114 strbuf_release(&state
->root
);
116 /* &state->fn_table is cleared at the end of apply_patch() */
119 static void mute_routine(const char *msg
, va_list params
)
124 int check_apply_state(struct apply_state
*state
, int force_apply
)
126 int is_not_gitdir
= !startup_info
->have_repository
;
128 if (state
->apply_with_reject
&& state
->threeway
)
129 return error(_("--reject and --3way cannot be used together."));
130 if (state
->cached
&& state
->threeway
)
131 return error(_("--cached and --3way cannot be used together."));
132 if (state
->threeway
) {
134 return error(_("--3way outside a repository"));
135 state
->check_index
= 1;
137 if (state
->apply_with_reject
) {
139 if (state
->apply_verbosity
== verbosity_normal
)
140 state
->apply_verbosity
= verbosity_verbose
;
142 if (!force_apply
&& (state
->diffstat
|| state
->numstat
|| state
->summary
|| state
->check
|| state
->fake_ancestor
))
144 if (state
->check_index
&& is_not_gitdir
)
145 return error(_("--index outside a repository"));
148 return error(_("--cached outside a repository"));
149 state
->check_index
= 1;
151 if (state
->ita_only
&& (state
->check_index
|| is_not_gitdir
))
153 if (state
->check_index
)
154 state
->unsafe_paths
= 0;
156 if (state
->apply_verbosity
<= verbosity_silent
) {
157 state
->saved_error_routine
= get_error_routine();
158 state
->saved_warn_routine
= get_warn_routine();
159 set_error_routine(mute_routine
);
160 set_warn_routine(mute_routine
);
166 static void set_default_whitespace_mode(struct apply_state
*state
)
168 if (!state
->whitespace_option
&& !apply_default_whitespace
)
169 state
->ws_error_action
= (state
->apply
? warn_on_ws_error
: nowarn_ws_error
);
173 * This represents one "hunk" from a patch, starting with
174 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
175 * patch text is pointed at by patch, and its byte length
176 * is stored in size. leading and trailing are the number
180 unsigned long leading
, trailing
;
181 unsigned long oldpos
, oldlines
;
182 unsigned long newpos
, newlines
;
184 * 'patch' is usually borrowed from buf in apply_patch(),
185 * but some codepaths store an allocated buffer.
188 unsigned free_patch
:1,
192 struct fragment
*next
;
196 * When dealing with a binary patch, we reuse "leading" field
197 * to store the type of the binary hunk, either deflated "delta"
198 * or deflated "literal".
200 #define binary_patch_method leading
201 #define BINARY_DELTA_DEFLATED 1
202 #define BINARY_LITERAL_DEFLATED 2
205 * This represents a "patch" to a file, both metainfo changes
206 * such as creation/deletion, filemode and content changes represented
207 * as a series of fragments.
210 char *new_name
, *old_name
, *def_name
;
211 unsigned int old_mode
, new_mode
;
212 int is_new
, is_delete
; /* -1 = unknown, 0 = false, 1 = true */
215 int lines_added
, lines_deleted
;
217 int extension_linenr
; /* first line specifying delete/new/rename/copy */
218 unsigned int is_toplevel_relative
:1;
219 unsigned int inaccurate_eof
:1;
220 unsigned int is_binary
:1;
221 unsigned int is_copy
:1;
222 unsigned int is_rename
:1;
223 unsigned int recount
:1;
224 unsigned int conflicted_threeway
:1;
225 unsigned int direct_to_threeway
:1;
226 unsigned int crlf_in_old
:1;
227 struct fragment
*fragments
;
230 char old_oid_prefix
[GIT_MAX_HEXSZ
+ 1];
231 char new_oid_prefix
[GIT_MAX_HEXSZ
+ 1];
234 /* three-way fallback result */
235 struct object_id threeway_stage
[3];
238 static void free_fragment_list(struct fragment
*list
)
241 struct fragment
*next
= list
->next
;
242 if (list
->free_patch
)
243 free((char *)list
->patch
);
249 static void free_patch(struct patch
*patch
)
251 free_fragment_list(patch
->fragments
);
252 free(patch
->def_name
);
253 free(patch
->old_name
);
254 free(patch
->new_name
);
259 static void free_patch_list(struct patch
*list
)
262 struct patch
*next
= list
->next
;
269 * A line in a file, len-bytes long (includes the terminating LF,
270 * except for an incomplete line at the end if the file ends with
271 * one), and its contents hashes to 'hash'.
277 #define LINE_COMMON 1
278 #define LINE_PATCHED 2
282 * This represents a "file", which is an array of "lines".
289 struct line
*line_allocated
;
293 static uint32_t hash_line(const char *cp
, size_t len
)
297 for (i
= 0, h
= 0; i
< len
; i
++) {
298 if (!isspace(cp
[i
])) {
299 h
= h
* 3 + (cp
[i
] & 0xff);
306 * Compare lines s1 of length n1 and s2 of length n2, ignoring
307 * whitespace difference. Returns 1 if they match, 0 otherwise
309 static int fuzzy_matchlines(const char *s1
, size_t n1
,
310 const char *s2
, size_t n2
)
312 const char *end1
= s1
+ n1
;
313 const char *end2
= s2
+ n2
;
315 /* ignore line endings */
316 while (s1
< end1
&& (end1
[-1] == '\r' || end1
[-1] == '\n'))
318 while (s2
< end2
&& (end2
[-1] == '\r' || end2
[-1] == '\n'))
321 while (s1
< end1
&& s2
< end2
) {
324 * Skip whitespace. We check on both buffers
325 * because we don't want "a b" to match "ab".
329 while (s1
< end1
&& isspace(*s1
))
331 while (s2
< end2
&& isspace(*s2
))
333 } else if (*s1
++ != *s2
++)
337 /* If we reached the end on one side only, lines don't match. */
338 return s1
== end1
&& s2
== end2
;
341 static void add_line_info(struct image
*img
, const char *bol
, size_t len
, unsigned flag
)
343 ALLOC_GROW(img
->line_allocated
, img
->nr
+ 1, img
->alloc
);
344 img
->line_allocated
[img
->nr
].len
= len
;
345 img
->line_allocated
[img
->nr
].hash
= hash_line(bol
, len
);
346 img
->line_allocated
[img
->nr
].flag
= flag
;
351 * "buf" has the file contents to be patched (read from various sources).
352 * attach it to "image" and add line-based index to it.
353 * "image" now owns the "buf".
355 static void prepare_image(struct image
*image
, char *buf
, size_t len
,
356 int prepare_linetable
)
360 memset(image
, 0, sizeof(*image
));
364 if (!prepare_linetable
)
367 ep
= image
->buf
+ image
->len
;
371 for (next
= cp
; next
< ep
&& *next
!= '\n'; next
++)
375 add_line_info(image
, cp
, next
- cp
, 0);
378 image
->line
= image
->line_allocated
;
381 static void clear_image(struct image
*image
)
384 free(image
->line_allocated
);
385 memset(image
, 0, sizeof(*image
));
388 /* fmt must contain _one_ %s and no other substitution */
389 static void say_patch_name(FILE *output
, const char *fmt
, struct patch
*patch
)
391 struct strbuf sb
= STRBUF_INIT
;
393 if (patch
->old_name
&& patch
->new_name
&&
394 strcmp(patch
->old_name
, patch
->new_name
)) {
395 quote_c_style(patch
->old_name
, &sb
, NULL
, 0);
396 strbuf_addstr(&sb
, " => ");
397 quote_c_style(patch
->new_name
, &sb
, NULL
, 0);
399 const char *n
= patch
->new_name
;
402 quote_c_style(n
, &sb
, NULL
, 0);
404 fprintf(output
, fmt
, sb
.buf
);
411 static int read_patch_file(struct strbuf
*sb
, int fd
)
413 if (strbuf_read(sb
, fd
, 0) < 0)
414 return error_errno("git apply: failed to read");
417 * Make sure that we have some slop in the buffer
418 * so that we can do speculative "memcmp" etc, and
419 * see to it that it is NUL-filled.
421 strbuf_grow(sb
, SLOP
);
422 memset(sb
->buf
+ sb
->len
, 0, SLOP
);
426 static unsigned long linelen(const char *buffer
, unsigned long size
)
428 unsigned long len
= 0;
431 if (*buffer
++ == '\n')
437 static int is_dev_null(const char *str
)
439 return skip_prefix(str
, "/dev/null", &str
) && isspace(*str
);
445 static int name_terminate(int c
, int terminate
)
447 if (c
== ' ' && !(terminate
& TERM_SPACE
))
449 if (c
== '\t' && !(terminate
& TERM_TAB
))
455 /* remove double slashes to make --index work with such filenames */
456 static char *squash_slash(char *name
)
464 if ((name
[j
++] = name
[i
++]) == '/')
465 while (name
[i
] == '/')
472 static char *find_name_gnu(struct apply_state
*state
,
476 struct strbuf name
= STRBUF_INIT
;
480 * Proposed "new-style" GNU patch/diff format; see
481 * http://marc.info/?l=git&m=112927316408690&w=2
483 if (unquote_c_style(&name
, line
, NULL
)) {
484 strbuf_release(&name
);
488 for (cp
= name
.buf
; p_value
; p_value
--) {
489 cp
= strchr(cp
, '/');
491 strbuf_release(&name
);
497 strbuf_remove(&name
, 0, cp
- name
.buf
);
499 strbuf_insert(&name
, 0, state
->root
.buf
, state
->root
.len
);
500 return squash_slash(strbuf_detach(&name
, NULL
));
503 static size_t sane_tz_len(const char *line
, size_t len
)
507 if (len
< strlen(" +0500") || line
[len
-strlen(" +0500")] != ' ')
509 tz
= line
+ len
- strlen(" +0500");
511 if (tz
[1] != '+' && tz
[1] != '-')
514 for (p
= tz
+ 2; p
!= line
+ len
; p
++)
518 return line
+ len
- tz
;
521 static size_t tz_with_colon_len(const char *line
, size_t len
)
525 if (len
< strlen(" +08:00") || line
[len
- strlen(":00")] != ':')
527 tz
= line
+ len
- strlen(" +08:00");
529 if (tz
[0] != ' ' || (tz
[1] != '+' && tz
[1] != '-'))
532 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
533 !isdigit(*p
++) || !isdigit(*p
++))
536 return line
+ len
- tz
;
539 static size_t date_len(const char *line
, size_t len
)
541 const char *date
, *p
;
543 if (len
< strlen("72-02-05") || line
[len
-strlen("-05")] != '-')
545 p
= date
= line
+ len
- strlen("72-02-05");
547 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
548 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
549 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a date. */
552 if (date
- line
>= strlen("19") &&
553 isdigit(date
[-1]) && isdigit(date
[-2])) /* 4-digit year */
554 date
-= strlen("19");
556 return line
+ len
- date
;
559 static size_t short_time_len(const char *line
, size_t len
)
561 const char *time
, *p
;
563 if (len
< strlen(" 07:01:32") || line
[len
-strlen(":32")] != ':')
565 p
= time
= line
+ len
- strlen(" 07:01:32");
567 /* Permit 1-digit hours? */
569 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
570 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
571 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a time. */
574 return line
+ len
- time
;
577 static size_t fractional_time_len(const char *line
, size_t len
)
582 /* Expected format: 19:41:17.620000023 */
583 if (!len
|| !isdigit(line
[len
- 1]))
587 /* Fractional seconds. */
588 while (p
> line
&& isdigit(*p
))
593 /* Hours, minutes, and whole seconds. */
594 n
= short_time_len(line
, p
- line
);
598 return line
+ len
- p
+ n
;
601 static size_t trailing_spaces_len(const char *line
, size_t len
)
605 /* Expected format: ' ' x (1 or more) */
606 if (!len
|| line
[len
- 1] != ' ')
613 return line
+ len
- (p
+ 1);
620 static size_t diff_timestamp_len(const char *line
, size_t len
)
622 const char *end
= line
+ len
;
626 * Posix: 2010-07-05 19:41:17
627 * GNU: 2010-07-05 19:41:17.620000023 -0500
630 if (!isdigit(end
[-1]))
633 n
= sane_tz_len(line
, end
- line
);
635 n
= tz_with_colon_len(line
, end
- line
);
638 n
= short_time_len(line
, end
- line
);
640 n
= fractional_time_len(line
, end
- line
);
643 n
= date_len(line
, end
- line
);
644 if (!n
) /* No date. Too bad. */
648 if (end
== line
) /* No space before date. */
650 if (end
[-1] == '\t') { /* Success! */
652 return line
+ len
- end
;
654 if (end
[-1] != ' ') /* No space before date. */
657 /* Whitespace damage. */
658 end
-= trailing_spaces_len(line
, end
- line
);
659 return line
+ len
- end
;
662 static char *find_name_common(struct apply_state
*state
,
670 const char *start
= NULL
;
674 while (line
!= end
) {
677 if (!end
&& isspace(c
)) {
680 if (name_terminate(c
, terminate
))
684 if (c
== '/' && !--p_value
)
688 return squash_slash(xstrdup_or_null(def
));
691 return squash_slash(xstrdup_or_null(def
));
694 * Generally we prefer the shorter name, especially
695 * if the other one is just a variation of that with
696 * something else tacked on to the end (ie "file.orig"
700 int deflen
= strlen(def
);
701 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
702 return squash_slash(xstrdup(def
));
705 if (state
->root
.len
) {
706 char *ret
= xstrfmt("%s%.*s", state
->root
.buf
, len
, start
);
707 return squash_slash(ret
);
710 return squash_slash(xmemdupz(start
, len
));
713 static char *find_name(struct apply_state
*state
,
720 char *name
= find_name_gnu(state
, line
, p_value
);
725 return find_name_common(state
, line
, def
, p_value
, NULL
, terminate
);
728 static char *find_name_traditional(struct apply_state
*state
,
737 char *name
= find_name_gnu(state
, line
, p_value
);
742 len
= strchrnul(line
, '\n') - line
;
743 date_len
= diff_timestamp_len(line
, len
);
745 return find_name_common(state
, line
, def
, p_value
, NULL
, TERM_TAB
);
748 return find_name_common(state
, line
, def
, p_value
, line
+ len
, 0);
752 * Given the string after "--- " or "+++ ", guess the appropriate
753 * p_value for the given patch.
755 static int guess_p_value(struct apply_state
*state
, const char *nameline
)
760 if (is_dev_null(nameline
))
762 name
= find_name_traditional(state
, nameline
, NULL
, 0);
765 cp
= strchr(name
, '/');
768 else if (state
->prefix
) {
770 * Does it begin with "a/$our-prefix" and such? Then this is
771 * very likely to apply to our directory.
773 if (starts_with(name
, state
->prefix
))
774 val
= count_slashes(state
->prefix
);
777 if (starts_with(cp
, state
->prefix
))
778 val
= count_slashes(state
->prefix
) + 1;
786 * Does the ---/+++ line have the POSIX timestamp after the last HT?
787 * GNU diff puts epoch there to signal a creation/deletion event. Is
788 * this such a timestamp?
790 static int has_epoch_timestamp(const char *nameline
)
793 * We are only interested in epoch timestamp; any non-zero
794 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
795 * For the same reason, the date must be either 1969-12-31 or
796 * 1970-01-01, and the seconds part must be "00".
798 const char stamp_regexp
[] =
799 "^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?"
801 "([-+][0-2][0-9]:?[0-5][0-9])\n";
802 const char *timestamp
= NULL
, *cp
, *colon
;
803 static regex_t
*stamp
;
805 int zoneoffset
, epoch_hour
, hour
, minute
;
808 for (cp
= nameline
; *cp
!= '\n'; cp
++) {
816 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
817 * (west of GMT) or 1970-01-01 (east of GMT)
819 if (skip_prefix(timestamp
, "1969-12-31 ", ×tamp
))
821 else if (skip_prefix(timestamp
, "1970-01-01 ", ×tamp
))
827 stamp
= xmalloc(sizeof(*stamp
));
828 if (regcomp(stamp
, stamp_regexp
, REG_EXTENDED
)) {
829 warning(_("Cannot prepare timestamp regexp %s"),
835 status
= regexec(stamp
, timestamp
, ARRAY_SIZE(m
), m
, 0);
837 if (status
!= REG_NOMATCH
)
838 warning(_("regexec returned %d for input: %s"),
843 hour
= strtol(timestamp
, NULL
, 10);
844 minute
= strtol(timestamp
+ m
[1].rm_so
, NULL
, 10);
846 zoneoffset
= strtol(timestamp
+ m
[3].rm_so
+ 1, (char **) &colon
, 10);
848 zoneoffset
= zoneoffset
* 60 + strtol(colon
+ 1, NULL
, 10);
850 zoneoffset
= (zoneoffset
/ 100) * 60 + (zoneoffset
% 100);
851 if (timestamp
[m
[3].rm_so
] == '-')
852 zoneoffset
= -zoneoffset
;
854 return hour
* 60 + minute
- zoneoffset
== epoch_hour
* 60;
858 * Get the name etc info from the ---/+++ lines of a traditional patch header
860 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
861 * files, we can happily check the index for a match, but for creating a
862 * new file we should try to match whatever "patch" does. I have no idea.
864 static int parse_traditional_patch(struct apply_state
*state
,
871 first
+= 4; /* skip "--- " */
872 second
+= 4; /* skip "+++ " */
873 if (!state
->p_value_known
) {
875 p
= guess_p_value(state
, first
);
876 q
= guess_p_value(state
, second
);
878 if (0 <= p
&& p
== q
) {
880 state
->p_value_known
= 1;
883 if (is_dev_null(first
)) {
885 patch
->is_delete
= 0;
886 name
= find_name_traditional(state
, second
, NULL
, state
->p_value
);
887 patch
->new_name
= name
;
888 } else if (is_dev_null(second
)) {
890 patch
->is_delete
= 1;
891 name
= find_name_traditional(state
, first
, NULL
, state
->p_value
);
892 patch
->old_name
= name
;
895 first_name
= find_name_traditional(state
, first
, NULL
, state
->p_value
);
896 name
= find_name_traditional(state
, second
, first_name
, state
->p_value
);
898 if (has_epoch_timestamp(first
)) {
900 patch
->is_delete
= 0;
901 patch
->new_name
= name
;
902 } else if (has_epoch_timestamp(second
)) {
904 patch
->is_delete
= 1;
905 patch
->old_name
= name
;
907 patch
->old_name
= name
;
908 patch
->new_name
= xstrdup_or_null(name
);
912 return error(_("unable to find filename in patch at line %d"), state
->linenr
);
917 static int gitdiff_hdrend(struct apply_state
*state
,
925 * We're anal about diff header consistency, to make
926 * sure that we don't end up having strange ambiguous
927 * patches floating around.
929 * As a result, gitdiff_{old|new}name() will check
930 * their names against any previous information, just
933 #define DIFF_OLD_NAME 0
934 #define DIFF_NEW_NAME 1
936 static int gitdiff_verify_name(struct apply_state
*state
,
942 if (!*name
&& !isnull
) {
943 *name
= find_name(state
, line
, NULL
, state
->p_value
, TERM_TAB
);
950 return error(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
951 *name
, state
->linenr
);
952 another
= find_name(state
, line
, NULL
, state
->p_value
, TERM_TAB
);
953 if (!another
|| strcmp(another
, *name
)) {
955 return error((side
== DIFF_NEW_NAME
) ?
956 _("git apply: bad git-diff - inconsistent new filename on line %d") :
957 _("git apply: bad git-diff - inconsistent old filename on line %d"), state
->linenr
);
961 if (!is_dev_null(line
))
962 return error(_("git apply: bad git-diff - expected /dev/null on line %d"), state
->linenr
);
968 static int gitdiff_oldname(struct apply_state
*state
,
972 return gitdiff_verify_name(state
, line
,
973 patch
->is_new
, &patch
->old_name
,
977 static int gitdiff_newname(struct apply_state
*state
,
981 return gitdiff_verify_name(state
, line
,
982 patch
->is_delete
, &patch
->new_name
,
986 static int parse_mode_line(const char *line
, int linenr
, unsigned int *mode
)
989 *mode
= strtoul(line
, &end
, 8);
990 if (end
== line
|| !isspace(*end
))
991 return error(_("invalid mode on line %d: %s"), linenr
, line
);
995 static int gitdiff_oldmode(struct apply_state
*state
,
999 return parse_mode_line(line
, state
->linenr
, &patch
->old_mode
);
1002 static int gitdiff_newmode(struct apply_state
*state
,
1004 struct patch
*patch
)
1006 return parse_mode_line(line
, state
->linenr
, &patch
->new_mode
);
1009 static int gitdiff_delete(struct apply_state
*state
,
1011 struct patch
*patch
)
1013 patch
->is_delete
= 1;
1014 free(patch
->old_name
);
1015 patch
->old_name
= xstrdup_or_null(patch
->def_name
);
1016 return gitdiff_oldmode(state
, line
, patch
);
1019 static int gitdiff_newfile(struct apply_state
*state
,
1021 struct patch
*patch
)
1024 free(patch
->new_name
);
1025 patch
->new_name
= xstrdup_or_null(patch
->def_name
);
1026 return gitdiff_newmode(state
, line
, patch
);
1029 static int gitdiff_copysrc(struct apply_state
*state
,
1031 struct patch
*patch
)
1034 free(patch
->old_name
);
1035 patch
->old_name
= find_name(state
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1039 static int gitdiff_copydst(struct apply_state
*state
,
1041 struct patch
*patch
)
1044 free(patch
->new_name
);
1045 patch
->new_name
= find_name(state
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1049 static int gitdiff_renamesrc(struct apply_state
*state
,
1051 struct patch
*patch
)
1053 patch
->is_rename
= 1;
1054 free(patch
->old_name
);
1055 patch
->old_name
= find_name(state
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1059 static int gitdiff_renamedst(struct apply_state
*state
,
1061 struct patch
*patch
)
1063 patch
->is_rename
= 1;
1064 free(patch
->new_name
);
1065 patch
->new_name
= find_name(state
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1069 static int gitdiff_similarity(struct apply_state
*state
,
1071 struct patch
*patch
)
1073 unsigned long val
= strtoul(line
, NULL
, 10);
1079 static int gitdiff_dissimilarity(struct apply_state
*state
,
1081 struct patch
*patch
)
1083 unsigned long val
= strtoul(line
, NULL
, 10);
1089 static int gitdiff_index(struct apply_state
*state
,
1091 struct patch
*patch
)
1094 * index line is N hexadecimal, "..", N hexadecimal,
1095 * and optional space with octal mode.
1097 const char *ptr
, *eol
;
1099 const unsigned hexsz
= the_hash_algo
->hexsz
;
1101 ptr
= strchr(line
, '.');
1102 if (!ptr
|| ptr
[1] != '.' || hexsz
< ptr
- line
)
1105 memcpy(patch
->old_oid_prefix
, line
, len
);
1106 patch
->old_oid_prefix
[len
] = 0;
1109 ptr
= strchr(line
, ' ');
1110 eol
= strchrnul(line
, '\n');
1112 if (!ptr
|| eol
< ptr
)
1118 memcpy(patch
->new_oid_prefix
, line
, len
);
1119 patch
->new_oid_prefix
[len
] = 0;
1121 return gitdiff_oldmode(state
, ptr
+ 1, patch
);
1126 * This is normal for a diff that doesn't change anything: we'll fall through
1127 * into the next diff. Tell the parser to break out.
1129 static int gitdiff_unrecognized(struct apply_state
*state
,
1131 struct patch
*patch
)
1137 * Skip p_value leading components from "line"; as we do not accept
1138 * absolute paths, return NULL in that case.
1140 static const char *skip_tree_prefix(struct apply_state
*state
,
1147 if (!state
->p_value
)
1148 return (llen
&& line
[0] == '/') ? NULL
: line
;
1150 nslash
= state
->p_value
;
1151 for (i
= 0; i
< llen
; i
++) {
1153 if (ch
== '/' && --nslash
<= 0)
1154 return (i
== 0) ? NULL
: &line
[i
+ 1];
1160 * This is to extract the same name that appears on "diff --git"
1161 * line. We do not find and return anything if it is a rename
1162 * patch, and it is OK because we will find the name elsewhere.
1163 * We need to reliably find name only when it is mode-change only,
1164 * creation or deletion of an empty file. In any of these cases,
1165 * both sides are the same name under a/ and b/ respectively.
1167 static char *git_header_name(struct apply_state
*state
,
1172 const char *second
= NULL
;
1173 size_t len
, line_len
;
1175 line
+= strlen("diff --git ");
1176 llen
-= strlen("diff --git ");
1180 struct strbuf first
= STRBUF_INIT
;
1181 struct strbuf sp
= STRBUF_INIT
;
1183 if (unquote_c_style(&first
, line
, &second
))
1184 goto free_and_fail1
;
1186 /* strip the a/b prefix including trailing slash */
1187 cp
= skip_tree_prefix(state
, first
.buf
, first
.len
);
1189 goto free_and_fail1
;
1190 strbuf_remove(&first
, 0, cp
- first
.buf
);
1193 * second points at one past closing dq of name.
1194 * find the second name.
1196 while ((second
< line
+ llen
) && isspace(*second
))
1199 if (line
+ llen
<= second
)
1200 goto free_and_fail1
;
1201 if (*second
== '"') {
1202 if (unquote_c_style(&sp
, second
, NULL
))
1203 goto free_and_fail1
;
1204 cp
= skip_tree_prefix(state
, sp
.buf
, sp
.len
);
1206 goto free_and_fail1
;
1207 /* They must match, otherwise ignore */
1208 if (strcmp(cp
, first
.buf
))
1209 goto free_and_fail1
;
1210 strbuf_release(&sp
);
1211 return strbuf_detach(&first
, NULL
);
1214 /* unquoted second */
1215 cp
= skip_tree_prefix(state
, second
, line
+ llen
- second
);
1217 goto free_and_fail1
;
1218 if (line
+ llen
- cp
!= first
.len
||
1219 memcmp(first
.buf
, cp
, first
.len
))
1220 goto free_and_fail1
;
1221 return strbuf_detach(&first
, NULL
);
1224 strbuf_release(&first
);
1225 strbuf_release(&sp
);
1229 /* unquoted first name */
1230 name
= skip_tree_prefix(state
, line
, llen
);
1235 * since the first name is unquoted, a dq if exists must be
1236 * the beginning of the second name.
1238 for (second
= name
; second
< line
+ llen
; second
++) {
1239 if (*second
== '"') {
1240 struct strbuf sp
= STRBUF_INIT
;
1243 if (unquote_c_style(&sp
, second
, NULL
))
1244 goto free_and_fail2
;
1246 np
= skip_tree_prefix(state
, sp
.buf
, sp
.len
);
1248 goto free_and_fail2
;
1250 len
= sp
.buf
+ sp
.len
- np
;
1251 if (len
< second
- name
&&
1252 !strncmp(np
, name
, len
) &&
1253 isspace(name
[len
])) {
1255 strbuf_remove(&sp
, 0, np
- sp
.buf
);
1256 return strbuf_detach(&sp
, NULL
);
1260 strbuf_release(&sp
);
1266 * Accept a name only if it shows up twice, exactly the same
1269 second
= strchr(name
, '\n');
1272 line_len
= second
- name
;
1273 for (len
= 0 ; ; len
++) {
1274 switch (name
[len
]) {
1279 case '\t': case ' ':
1281 * Is this the separator between the preimage
1282 * and the postimage pathname? Again, we are
1283 * only interested in the case where there is
1284 * no rename, as this is only to set def_name
1285 * and a rename patch has the names elsewhere
1286 * in an unambiguous form.
1289 return NULL
; /* no postimage name */
1290 second
= skip_tree_prefix(state
, name
+ len
+ 1,
1291 line_len
- (len
+ 1));
1295 * Does len bytes starting at "name" and "second"
1296 * (that are separated by one HT or SP we just
1297 * found) exactly match?
1299 if (second
[len
] == '\n' && !strncmp(name
, second
, len
))
1300 return xmemdupz(name
, len
);
1305 static int check_header_line(struct apply_state
*state
, struct patch
*patch
)
1307 int extensions
= (patch
->is_delete
== 1) + (patch
->is_new
== 1) +
1308 (patch
->is_rename
== 1) + (patch
->is_copy
== 1);
1310 return error(_("inconsistent header lines %d and %d"),
1311 patch
->extension_linenr
, state
->linenr
);
1312 if (extensions
&& !patch
->extension_linenr
)
1313 patch
->extension_linenr
= state
->linenr
;
1317 /* Verify that we recognize the lines following a git header */
1318 static int parse_git_header(struct apply_state
*state
,
1322 struct patch
*patch
)
1324 unsigned long offset
;
1326 /* A git diff has explicit new/delete information, so we don't guess */
1328 patch
->is_delete
= 0;
1331 * Some things may not have the old name in the
1332 * rest of the headers anywhere (pure mode changes,
1333 * or removing or adding empty files), so we get
1334 * the default name from the header.
1336 patch
->def_name
= git_header_name(state
, line
, len
);
1337 if (patch
->def_name
&& state
->root
.len
) {
1338 char *s
= xstrfmt("%s%s", state
->root
.buf
, patch
->def_name
);
1339 free(patch
->def_name
);
1340 patch
->def_name
= s
;
1346 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1347 static const struct opentry
{
1349 int (*fn
)(struct apply_state
*, const char *, struct patch
*);
1351 { "@@ -", gitdiff_hdrend
},
1352 { "--- ", gitdiff_oldname
},
1353 { "+++ ", gitdiff_newname
},
1354 { "old mode ", gitdiff_oldmode
},
1355 { "new mode ", gitdiff_newmode
},
1356 { "deleted file mode ", gitdiff_delete
},
1357 { "new file mode ", gitdiff_newfile
},
1358 { "copy from ", gitdiff_copysrc
},
1359 { "copy to ", gitdiff_copydst
},
1360 { "rename old ", gitdiff_renamesrc
},
1361 { "rename new ", gitdiff_renamedst
},
1362 { "rename from ", gitdiff_renamesrc
},
1363 { "rename to ", gitdiff_renamedst
},
1364 { "similarity index ", gitdiff_similarity
},
1365 { "dissimilarity index ", gitdiff_dissimilarity
},
1366 { "index ", gitdiff_index
},
1367 { "", gitdiff_unrecognized
},
1371 len
= linelen(line
, size
);
1372 if (!len
|| line
[len
-1] != '\n')
1374 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
1375 const struct opentry
*p
= optable
+ i
;
1376 int oplen
= strlen(p
->str
);
1378 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
1380 res
= p
->fn(state
, line
+ oplen
, patch
);
1383 if (check_header_line(state
, patch
))
1394 static int parse_num(const char *line
, unsigned long *p
)
1398 if (!isdigit(*line
))
1400 *p
= strtoul(line
, &ptr
, 10);
1404 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
1405 unsigned long *p1
, unsigned long *p2
)
1409 if (offset
< 0 || offset
>= len
)
1414 digits
= parse_num(line
, p1
);
1424 digits
= parse_num(line
+1, p2
);
1433 ex
= strlen(expect
);
1436 if (memcmp(line
, expect
, ex
))
1442 static void recount_diff(const char *line
, int size
, struct fragment
*fragment
)
1444 int oldlines
= 0, newlines
= 0, ret
= 0;
1447 warning("recount: ignore empty hunk");
1452 int len
= linelen(line
, size
);
1460 case ' ': case '\n':
1472 ret
= size
< 3 || !starts_with(line
, "@@ ");
1475 ret
= size
< 5 || !starts_with(line
, "diff ");
1482 warning(_("recount: unexpected line: %.*s"),
1483 (int)linelen(line
, size
), line
);
1488 fragment
->oldlines
= oldlines
;
1489 fragment
->newlines
= newlines
;
1493 * Parse a unified diff fragment header of the
1494 * form "@@ -a,b +c,d @@"
1496 static int parse_fragment_header(const char *line
, int len
, struct fragment
*fragment
)
1500 if (!len
|| line
[len
-1] != '\n')
1503 /* Figure out the number of lines in a fragment */
1504 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
1505 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
1511 * Find file diff header
1514 * -1 if no header was found
1515 * -128 in case of error
1516 * the size of the header in bytes (called "offset") otherwise
1518 static int find_header(struct apply_state
*state
,
1522 struct patch
*patch
)
1524 unsigned long offset
, len
;
1526 patch
->is_toplevel_relative
= 0;
1527 patch
->is_rename
= patch
->is_copy
= 0;
1528 patch
->is_new
= patch
->is_delete
= -1;
1529 patch
->old_mode
= patch
->new_mode
= 0;
1530 patch
->old_name
= patch
->new_name
= NULL
;
1531 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1532 unsigned long nextlen
;
1534 len
= linelen(line
, size
);
1538 /* Testing this early allows us to take a few shortcuts.. */
1543 * Make sure we don't find any unconnected patch fragments.
1544 * That's a sign that we didn't find a header, and that a
1545 * patch has become corrupted/broken up.
1547 if (!memcmp("@@ -", line
, 4)) {
1548 struct fragment dummy
;
1549 if (parse_fragment_header(line
, len
, &dummy
) < 0)
1551 error(_("patch fragment without header at line %d: %.*s"),
1552 state
->linenr
, (int)len
-1, line
);
1560 * Git patch? It might not have a real patch, just a rename
1561 * or mode change, so we handle that specially
1563 if (!memcmp("diff --git ", line
, 11)) {
1564 int git_hdr_len
= parse_git_header(state
, line
, len
, size
, patch
);
1565 if (git_hdr_len
< 0)
1567 if (git_hdr_len
<= len
)
1569 if (!patch
->old_name
&& !patch
->new_name
) {
1570 if (!patch
->def_name
) {
1571 error(Q_("git diff header lacks filename information when removing "
1572 "%d leading pathname component (line %d)",
1573 "git diff header lacks filename information when removing "
1574 "%d leading pathname components (line %d)",
1576 state
->p_value
, state
->linenr
);
1579 patch
->old_name
= xstrdup(patch
->def_name
);
1580 patch
->new_name
= xstrdup(patch
->def_name
);
1582 if ((!patch
->new_name
&& !patch
->is_delete
) ||
1583 (!patch
->old_name
&& !patch
->is_new
)) {
1584 error(_("git diff header lacks filename information "
1585 "(line %d)"), state
->linenr
);
1588 patch
->is_toplevel_relative
= 1;
1589 *hdrsize
= git_hdr_len
;
1593 /* --- followed by +++ ? */
1594 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
1598 * We only accept unified patches, so we want it to
1599 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1600 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1602 nextlen
= linelen(line
+ len
, size
- len
);
1603 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
1606 /* Ok, we'll consider it a patch */
1607 if (parse_traditional_patch(state
, line
, line
+len
, patch
))
1609 *hdrsize
= len
+ nextlen
;
1616 static void record_ws_error(struct apply_state
*state
,
1627 state
->whitespace_error
++;
1628 if (state
->squelch_whitespace_errors
&&
1629 state
->squelch_whitespace_errors
< state
->whitespace_error
)
1632 err
= whitespace_error_string(result
);
1633 if (state
->apply_verbosity
> verbosity_silent
)
1634 fprintf(stderr
, "%s:%d: %s.\n%.*s\n",
1635 state
->patch_input_file
, linenr
, err
, len
, line
);
1639 static void check_whitespace(struct apply_state
*state
,
1644 unsigned result
= ws_check(line
+ 1, len
- 1, ws_rule
);
1646 record_ws_error(state
, result
, line
+ 1, len
- 2, state
->linenr
);
1650 * Check if the patch has context lines with CRLF or
1651 * the patch wants to remove lines with CRLF.
1653 static void check_old_for_crlf(struct patch
*patch
, const char *line
, int len
)
1655 if (len
>= 2 && line
[len
-1] == '\n' && line
[len
-2] == '\r') {
1656 patch
->ws_rule
|= WS_CR_AT_EOL
;
1657 patch
->crlf_in_old
= 1;
1663 * Parse a unified diff. Note that this really needs to parse each
1664 * fragment separately, since the only way to know the difference
1665 * between a "---" that is part of a patch, and a "---" that starts
1666 * the next patch is to look at the line counts..
1668 static int parse_fragment(struct apply_state
*state
,
1671 struct patch
*patch
,
1672 struct fragment
*fragment
)
1675 int len
= linelen(line
, size
), offset
;
1676 unsigned long oldlines
, newlines
;
1677 unsigned long leading
, trailing
;
1679 offset
= parse_fragment_header(line
, len
, fragment
);
1682 if (offset
> 0 && patch
->recount
)
1683 recount_diff(line
+ offset
, size
- offset
, fragment
);
1684 oldlines
= fragment
->oldlines
;
1685 newlines
= fragment
->newlines
;
1689 /* Parse the thing.. */
1693 added
= deleted
= 0;
1696 offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1697 if (!oldlines
&& !newlines
)
1699 len
= linelen(line
, size
);
1700 if (!len
|| line
[len
-1] != '\n')
1705 case '\n': /* newer GNU diff, an empty context line */
1709 if (!deleted
&& !added
)
1712 check_old_for_crlf(patch
, line
, len
);
1713 if (!state
->apply_in_reverse
&&
1714 state
->ws_error_action
== correct_ws_error
)
1715 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1718 if (!state
->apply_in_reverse
)
1719 check_old_for_crlf(patch
, line
, len
);
1720 if (state
->apply_in_reverse
&&
1721 state
->ws_error_action
!= nowarn_ws_error
)
1722 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
);
1739 * We allow "\ No newline at end of file". Depending
1740 * on locale settings when the patch was produced we
1741 * don't know what this line looks like. The only
1742 * thing we do know is that it begins with "\ ".
1743 * Checking for 12 is just for sanity check -- any
1744 * l10n of "\ No newline..." is at least that long.
1747 if (len
< 12 || memcmp(line
, "\\ ", 2))
1752 if (oldlines
|| newlines
)
1754 if (!patch
->recount
&& !deleted
&& !added
)
1757 fragment
->leading
= leading
;
1758 fragment
->trailing
= trailing
;
1761 * If a fragment ends with an incomplete line, we failed to include
1762 * it in the above loop because we hit oldlines == newlines == 0
1765 if (12 < size
&& !memcmp(line
, "\\ ", 2))
1766 offset
+= linelen(line
, size
);
1768 patch
->lines_added
+= added
;
1769 patch
->lines_deleted
+= deleted
;
1771 if (0 < patch
->is_new
&& oldlines
)
1772 return error(_("new file depends on old contents"));
1773 if (0 < patch
->is_delete
&& newlines
)
1774 return error(_("deleted file still has contents"));
1779 * We have seen "diff --git a/... b/..." header (or a traditional patch
1780 * header). Read hunks that belong to this patch into fragments and hang
1781 * them to the given patch structure.
1783 * The (fragment->patch, fragment->size) pair points into the memory given
1784 * by the caller, not a copy, when we return.
1787 * -1 in case of error,
1788 * the number of bytes in the patch otherwise.
1790 static int parse_single_patch(struct apply_state
*state
,
1793 struct patch
*patch
)
1795 unsigned long offset
= 0;
1796 unsigned long oldlines
= 0, newlines
= 0, context
= 0;
1797 struct fragment
**fragp
= &patch
->fragments
;
1799 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
1800 struct fragment
*fragment
;
1803 fragment
= xcalloc(1, sizeof(*fragment
));
1804 fragment
->linenr
= state
->linenr
;
1805 len
= parse_fragment(state
, line
, size
, patch
, fragment
);
1808 return error(_("corrupt patch at line %d"), state
->linenr
);
1810 fragment
->patch
= line
;
1811 fragment
->size
= len
;
1812 oldlines
+= fragment
->oldlines
;
1813 newlines
+= fragment
->newlines
;
1814 context
+= fragment
->leading
+ fragment
->trailing
;
1817 fragp
= &fragment
->next
;
1825 * If something was removed (i.e. we have old-lines) it cannot
1826 * be creation, and if something was added it cannot be
1827 * deletion. However, the reverse is not true; --unified=0
1828 * patches that only add are not necessarily creation even
1829 * though they do not have any old lines, and ones that only
1830 * delete are not necessarily deletion.
1832 * Unfortunately, a real creation/deletion patch do _not_ have
1833 * any context line by definition, so we cannot safely tell it
1834 * apart with --unified=0 insanity. At least if the patch has
1835 * more than one hunk it is not creation or deletion.
1837 if (patch
->is_new
< 0 &&
1838 (oldlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1840 if (patch
->is_delete
< 0 &&
1841 (newlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1842 patch
->is_delete
= 0;
1844 if (0 < patch
->is_new
&& oldlines
)
1845 return error(_("new file %s depends on old contents"), patch
->new_name
);
1846 if (0 < patch
->is_delete
&& newlines
)
1847 return error(_("deleted file %s still has contents"), patch
->old_name
);
1848 if (!patch
->is_delete
&& !newlines
&& context
&& state
->apply_verbosity
> verbosity_silent
)
1851 "file %s becomes empty but is not deleted"),
1857 static inline int metadata_changes(struct patch
*patch
)
1859 return patch
->is_rename
> 0 ||
1860 patch
->is_copy
> 0 ||
1861 patch
->is_new
> 0 ||
1863 (patch
->old_mode
&& patch
->new_mode
&&
1864 patch
->old_mode
!= patch
->new_mode
);
1867 static char *inflate_it(const void *data
, unsigned long size
,
1868 unsigned long inflated_size
)
1874 memset(&stream
, 0, sizeof(stream
));
1876 stream
.next_in
= (unsigned char *)data
;
1877 stream
.avail_in
= size
;
1878 stream
.next_out
= out
= xmalloc(inflated_size
);
1879 stream
.avail_out
= inflated_size
;
1880 git_inflate_init(&stream
);
1881 st
= git_inflate(&stream
, Z_FINISH
);
1882 git_inflate_end(&stream
);
1883 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1891 * Read a binary hunk and return a new fragment; fragment->patch
1892 * points at an allocated memory that the caller must free, so
1893 * it is marked as "->free_patch = 1".
1895 static struct fragment
*parse_binary_hunk(struct apply_state
*state
,
1897 unsigned long *sz_p
,
1902 * Expect a line that begins with binary patch method ("literal"
1903 * or "delta"), followed by the length of data before deflating.
1904 * a sequence of 'length-byte' followed by base-85 encoded data
1905 * should follow, terminated by a newline.
1907 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1908 * and we would limit the patch line to 66 characters,
1909 * so one line can fit up to 13 groups that would decode
1910 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1911 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1914 unsigned long size
= *sz_p
;
1915 char *buffer
= *buf_p
;
1917 unsigned long origlen
;
1920 struct fragment
*frag
;
1922 llen
= linelen(buffer
, size
);
1927 if (starts_with(buffer
, "delta ")) {
1928 patch_method
= BINARY_DELTA_DEFLATED
;
1929 origlen
= strtoul(buffer
+ 6, NULL
, 10);
1931 else if (starts_with(buffer
, "literal ")) {
1932 patch_method
= BINARY_LITERAL_DEFLATED
;
1933 origlen
= strtoul(buffer
+ 8, NULL
, 10);
1941 int byte_length
, max_byte_length
, newsize
;
1942 llen
= linelen(buffer
, size
);
1946 /* consume the blank line */
1952 * Minimum line is "A00000\n" which is 7-byte long,
1953 * and the line length must be multiple of 5 plus 2.
1955 if ((llen
< 7) || (llen
-2) % 5)
1957 max_byte_length
= (llen
- 2) / 5 * 4;
1958 byte_length
= *buffer
;
1959 if ('A' <= byte_length
&& byte_length
<= 'Z')
1960 byte_length
= byte_length
- 'A' + 1;
1961 else if ('a' <= byte_length
&& byte_length
<= 'z')
1962 byte_length
= byte_length
- 'a' + 27;
1965 /* if the input length was not multiple of 4, we would
1966 * have filler at the end but the filler should never
1969 if (max_byte_length
< byte_length
||
1970 byte_length
<= max_byte_length
- 4)
1972 newsize
= hunk_size
+ byte_length
;
1973 data
= xrealloc(data
, newsize
);
1974 if (decode_85(data
+ hunk_size
, buffer
+ 1, byte_length
))
1976 hunk_size
= newsize
;
1981 frag
= xcalloc(1, sizeof(*frag
));
1982 frag
->patch
= inflate_it(data
, hunk_size
, origlen
);
1983 frag
->free_patch
= 1;
1987 frag
->size
= origlen
;
1991 frag
->binary_patch_method
= patch_method
;
1997 error(_("corrupt binary patch at line %d: %.*s"),
1998 state
->linenr
-1, llen
-1, buffer
);
2004 * -1 in case of error,
2005 * the length of the parsed binary patch otherwise
2007 static int parse_binary(struct apply_state
*state
,
2010 struct patch
*patch
)
2013 * We have read "GIT binary patch\n"; what follows is a line
2014 * that says the patch method (currently, either "literal" or
2015 * "delta") and the length of data before deflating; a
2016 * sequence of 'length-byte' followed by base-85 encoded data
2019 * When a binary patch is reversible, there is another binary
2020 * hunk in the same format, starting with patch method (either
2021 * "literal" or "delta") with the length of data, and a sequence
2022 * of length-byte + base-85 encoded data, terminated with another
2023 * empty line. This data, when applied to the postimage, produces
2026 struct fragment
*forward
;
2027 struct fragment
*reverse
;
2031 forward
= parse_binary_hunk(state
, &buffer
, &size
, &status
, &used
);
2032 if (!forward
&& !status
)
2033 /* there has to be one hunk (forward hunk) */
2034 return error(_("unrecognized binary patch at line %d"), state
->linenr
-1);
2036 /* otherwise we already gave an error message */
2039 reverse
= parse_binary_hunk(state
, &buffer
, &size
, &status
, &used_1
);
2044 * Not having reverse hunk is not an error, but having
2045 * a corrupt reverse hunk is.
2047 free((void*) forward
->patch
);
2051 forward
->next
= reverse
;
2052 patch
->fragments
= forward
;
2053 patch
->is_binary
= 1;
2057 static void prefix_one(struct apply_state
*state
, char **name
)
2059 char *old_name
= *name
;
2062 *name
= prefix_filename(state
->prefix
, *name
);
2066 static void prefix_patch(struct apply_state
*state
, struct patch
*p
)
2068 if (!state
->prefix
|| p
->is_toplevel_relative
)
2070 prefix_one(state
, &p
->new_name
);
2071 prefix_one(state
, &p
->old_name
);
2078 static void add_name_limit(struct apply_state
*state
,
2082 struct string_list_item
*it
;
2084 it
= string_list_append(&state
->limit_by_name
, name
);
2085 it
->util
= exclude
? NULL
: (void *) 1;
2088 static int use_patch(struct apply_state
*state
, struct patch
*p
)
2090 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
2093 /* Paths outside are not touched regardless of "--include" */
2094 if (state
->prefix
&& *state
->prefix
) {
2096 if (!skip_prefix(pathname
, state
->prefix
, &rest
) || !*rest
)
2100 /* See if it matches any of exclude/include rule */
2101 for (i
= 0; i
< state
->limit_by_name
.nr
; i
++) {
2102 struct string_list_item
*it
= &state
->limit_by_name
.items
[i
];
2103 if (!wildmatch(it
->string
, pathname
, 0))
2104 return (it
->util
!= NULL
);
2108 * If we had any include, a path that does not match any rule is
2109 * not used. Otherwise, we saw bunch of exclude rules (or none)
2110 * and such a path is used.
2112 return !state
->has_include
;
2116 * Read the patch text in "buffer" that extends for "size" bytes; stop
2117 * reading after seeing a single patch (i.e. changes to a single file).
2118 * Create fragments (i.e. patch hunks) and hang them to the given patch.
2121 * -1 if no header was found or parse_binary() failed,
2122 * -128 on another error,
2123 * the number of bytes consumed otherwise,
2124 * so that the caller can call us again for the next patch.
2126 static int parse_chunk(struct apply_state
*state
, char *buffer
, unsigned long size
, struct patch
*patch
)
2128 int hdrsize
, patchsize
;
2129 int offset
= find_header(state
, buffer
, size
, &hdrsize
, patch
);
2134 prefix_patch(state
, patch
);
2136 if (!use_patch(state
, patch
))
2138 else if (patch
->new_name
)
2139 patch
->ws_rule
= whitespace_rule(state
->repo
->index
,
2142 patch
->ws_rule
= whitespace_rule(state
->repo
->index
,
2145 patchsize
= parse_single_patch(state
,
2146 buffer
+ offset
+ hdrsize
,
2147 size
- offset
- hdrsize
,
2154 static const char git_binary
[] = "GIT binary patch\n";
2155 int hd
= hdrsize
+ offset
;
2156 unsigned long llen
= linelen(buffer
+ hd
, size
- hd
);
2158 if (llen
== sizeof(git_binary
) - 1 &&
2159 !memcmp(git_binary
, buffer
+ hd
, llen
)) {
2162 used
= parse_binary(state
, buffer
+ hd
+ llen
,
2163 size
- hd
- llen
, patch
);
2167 patchsize
= used
+ llen
;
2171 else if (!memcmp(" differ\n", buffer
+ hd
+ llen
- 8, 8)) {
2172 static const char *binhdr
[] = {
2178 for (i
= 0; binhdr
[i
]; i
++) {
2179 int len
= strlen(binhdr
[i
]);
2180 if (len
< size
- hd
&&
2181 !memcmp(binhdr
[i
], buffer
+ hd
, len
)) {
2183 patch
->is_binary
= 1;
2190 /* Empty patch cannot be applied if it is a text patch
2191 * without metadata change. A binary patch appears
2194 if ((state
->apply
|| state
->check
) &&
2195 (!patch
->is_binary
&& !metadata_changes(patch
))) {
2196 error(_("patch with only garbage at line %d"), state
->linenr
);
2201 return offset
+ hdrsize
+ patchsize
;
2204 static void reverse_patches(struct patch
*p
)
2206 for (; p
; p
= p
->next
) {
2207 struct fragment
*frag
= p
->fragments
;
2209 SWAP(p
->new_name
, p
->old_name
);
2210 SWAP(p
->new_mode
, p
->old_mode
);
2211 SWAP(p
->is_new
, p
->is_delete
);
2212 SWAP(p
->lines_added
, p
->lines_deleted
);
2213 SWAP(p
->old_oid_prefix
, p
->new_oid_prefix
);
2215 for (; frag
; frag
= frag
->next
) {
2216 SWAP(frag
->newpos
, frag
->oldpos
);
2217 SWAP(frag
->newlines
, frag
->oldlines
);
2222 static const char pluses
[] =
2223 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2224 static const char minuses
[]=
2225 "----------------------------------------------------------------------";
2227 static void show_stats(struct apply_state
*state
, struct patch
*patch
)
2229 struct strbuf qname
= STRBUF_INIT
;
2230 char *cp
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
2233 quote_c_style(cp
, &qname
, NULL
, 0);
2236 * "scale" the filename
2238 max
= state
->max_len
;
2242 if (qname
.len
> max
) {
2243 cp
= strchr(qname
.buf
+ qname
.len
+ 3 - max
, '/');
2245 cp
= qname
.buf
+ qname
.len
+ 3 - max
;
2246 strbuf_splice(&qname
, 0, cp
- qname
.buf
, "...", 3);
2249 if (patch
->is_binary
) {
2250 printf(" %-*s | Bin\n", max
, qname
.buf
);
2251 strbuf_release(&qname
);
2255 printf(" %-*s |", max
, qname
.buf
);
2256 strbuf_release(&qname
);
2259 * scale the add/delete
2261 max
= max
+ state
->max_change
> 70 ? 70 - max
: state
->max_change
;
2262 add
= patch
->lines_added
;
2263 del
= patch
->lines_deleted
;
2265 if (state
->max_change
> 0) {
2266 int total
= ((add
+ del
) * max
+ state
->max_change
/ 2) / state
->max_change
;
2267 add
= (add
* max
+ state
->max_change
/ 2) / state
->max_change
;
2270 printf("%5d %.*s%.*s\n", patch
->lines_added
+ patch
->lines_deleted
,
2271 add
, pluses
, del
, minuses
);
2274 static int read_old_data(struct stat
*st
, struct patch
*patch
,
2275 const char *path
, struct strbuf
*buf
)
2277 int conv_flags
= patch
->crlf_in_old
?
2278 CONV_EOL_KEEP_CRLF
: CONV_EOL_RENORMALIZE
;
2279 switch (st
->st_mode
& S_IFMT
) {
2281 if (strbuf_readlink(buf
, path
, st
->st_size
) < 0)
2282 return error(_("unable to read symlink %s"), path
);
2285 if (strbuf_read_file(buf
, path
, st
->st_size
) != st
->st_size
)
2286 return error(_("unable to open or read %s"), path
);
2288 * "git apply" without "--index/--cached" should never look
2289 * at the index; the target file may not have been added to
2290 * the index yet, and we may not even be in any Git repository.
2291 * Pass NULL to convert_to_git() to stress this; the function
2292 * should never look at the index when explicit crlf option
2295 convert_to_git(NULL
, path
, buf
->buf
, buf
->len
, buf
, conv_flags
);
2303 * Update the preimage, and the common lines in postimage,
2304 * from buffer buf of length len. If postlen is 0 the postimage
2305 * is updated in place, otherwise it's updated on a new buffer
2309 static void update_pre_post_images(struct image
*preimage
,
2310 struct image
*postimage
,
2312 size_t len
, size_t postlen
)
2314 int i
, ctx
, reduced
;
2315 char *new_buf
, *old_buf
, *fixed
;
2316 struct image fixed_preimage
;
2319 * Update the preimage with whitespace fixes. Note that we
2320 * are not losing preimage->buf -- apply_one_fragment() will
2323 prepare_image(&fixed_preimage
, buf
, len
, 1);
2325 ? fixed_preimage
.nr
== preimage
->nr
2326 : fixed_preimage
.nr
<= preimage
->nr
);
2327 for (i
= 0; i
< fixed_preimage
.nr
; i
++)
2328 fixed_preimage
.line
[i
].flag
= preimage
->line
[i
].flag
;
2329 free(preimage
->line_allocated
);
2330 *preimage
= fixed_preimage
;
2333 * Adjust the common context lines in postimage. This can be
2334 * done in-place when we are shrinking it with whitespace
2335 * fixing, but needs a new buffer when ignoring whitespace or
2336 * expanding leading tabs to spaces.
2338 * We trust the caller to tell us if the update can be done
2339 * in place (postlen==0) or not.
2341 old_buf
= postimage
->buf
;
2343 new_buf
= postimage
->buf
= xmalloc(postlen
);
2346 fixed
= preimage
->buf
;
2348 for (i
= reduced
= ctx
= 0; i
< postimage
->nr
; i
++) {
2349 size_t l_len
= postimage
->line
[i
].len
;
2350 if (!(postimage
->line
[i
].flag
& LINE_COMMON
)) {
2351 /* an added line -- no counterparts in preimage */
2352 memmove(new_buf
, old_buf
, l_len
);
2358 /* a common context -- skip it in the original postimage */
2361 /* and find the corresponding one in the fixed preimage */
2362 while (ctx
< preimage
->nr
&&
2363 !(preimage
->line
[ctx
].flag
& LINE_COMMON
)) {
2364 fixed
+= preimage
->line
[ctx
].len
;
2369 * preimage is expected to run out, if the caller
2370 * fixed addition of trailing blank lines.
2372 if (preimage
->nr
<= ctx
) {
2377 /* and copy it in, while fixing the line length */
2378 l_len
= preimage
->line
[ctx
].len
;
2379 memcpy(new_buf
, fixed
, l_len
);
2382 postimage
->line
[i
].len
= l_len
;
2387 ? postlen
< new_buf
- postimage
->buf
2388 : postimage
->len
< new_buf
- postimage
->buf
)
2389 BUG("caller miscounted postlen: asked %d, orig = %d, used = %d",
2390 (int)postlen
, (int) postimage
->len
, (int)(new_buf
- postimage
->buf
));
2392 /* Fix the length of the whole thing */
2393 postimage
->len
= new_buf
- postimage
->buf
;
2394 postimage
->nr
-= reduced
;
2397 static int line_by_line_fuzzy_match(struct image
*img
,
2398 struct image
*preimage
,
2399 struct image
*postimage
,
2400 unsigned long current
,
2407 size_t postlen
= postimage
->len
;
2412 struct strbuf fixed
;
2416 for (i
= 0; i
< preimage_limit
; i
++) {
2417 size_t prelen
= preimage
->line
[i
].len
;
2418 size_t imglen
= img
->line
[current_lno
+i
].len
;
2420 if (!fuzzy_matchlines(img
->buf
+ current
+ imgoff
, imglen
,
2421 preimage
->buf
+ preoff
, prelen
))
2423 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2424 postlen
+= imglen
- prelen
;
2430 * Ok, the preimage matches with whitespace fuzz.
2432 * imgoff now holds the true length of the target that
2433 * matches the preimage before the end of the file.
2435 * Count the number of characters in the preimage that fall
2436 * beyond the end of the file and make sure that all of them
2437 * are whitespace characters. (This can only happen if
2438 * we are removing blank lines at the end of the file.)
2440 buf
= preimage_eof
= preimage
->buf
+ preoff
;
2441 for ( ; i
< preimage
->nr
; i
++)
2442 preoff
+= preimage
->line
[i
].len
;
2443 preimage_end
= preimage
->buf
+ preoff
;
2444 for ( ; buf
< preimage_end
; buf
++)
2449 * Update the preimage and the common postimage context
2450 * lines to use the same whitespace as the target.
2451 * If whitespace is missing in the target (i.e.
2452 * if the preimage extends beyond the end of the file),
2453 * use the whitespace from the preimage.
2455 extra_chars
= preimage_end
- preimage_eof
;
2456 strbuf_init(&fixed
, imgoff
+ extra_chars
);
2457 strbuf_add(&fixed
, img
->buf
+ current
, imgoff
);
2458 strbuf_add(&fixed
, preimage_eof
, extra_chars
);
2459 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2460 update_pre_post_images(preimage
, postimage
,
2461 fixed_buf
, fixed_len
, postlen
);
2465 static int match_fragment(struct apply_state
*state
,
2467 struct image
*preimage
,
2468 struct image
*postimage
,
2469 unsigned long current
,
2472 int match_beginning
, int match_end
)
2475 char *fixed_buf
, *buf
, *orig
, *target
;
2476 struct strbuf fixed
;
2477 size_t fixed_len
, postlen
;
2480 if (preimage
->nr
+ current_lno
<= img
->nr
) {
2482 * The hunk falls within the boundaries of img.
2484 preimage_limit
= preimage
->nr
;
2485 if (match_end
&& (preimage
->nr
+ current_lno
!= img
->nr
))
2487 } else if (state
->ws_error_action
== correct_ws_error
&&
2488 (ws_rule
& WS_BLANK_AT_EOF
)) {
2490 * This hunk extends beyond the end of img, and we are
2491 * removing blank lines at the end of the file. This
2492 * many lines from the beginning of the preimage must
2493 * match with img, and the remainder of the preimage
2496 preimage_limit
= img
->nr
- current_lno
;
2499 * The hunk extends beyond the end of the img and
2500 * we are not removing blanks at the end, so we
2501 * should reject the hunk at this position.
2506 if (match_beginning
&& current_lno
)
2509 /* Quick hash check */
2510 for (i
= 0; i
< preimage_limit
; i
++)
2511 if ((img
->line
[current_lno
+ i
].flag
& LINE_PATCHED
) ||
2512 (preimage
->line
[i
].hash
!= img
->line
[current_lno
+ i
].hash
))
2515 if (preimage_limit
== preimage
->nr
) {
2517 * Do we have an exact match? If we were told to match
2518 * at the end, size must be exactly at current+fragsize,
2519 * otherwise current+fragsize must be still within the preimage,
2520 * and either case, the old piece should match the preimage
2524 ? (current
+ preimage
->len
== img
->len
)
2525 : (current
+ preimage
->len
<= img
->len
)) &&
2526 !memcmp(img
->buf
+ current
, preimage
->buf
, preimage
->len
))
2530 * The preimage extends beyond the end of img, so
2531 * there cannot be an exact match.
2533 * There must be one non-blank context line that match
2534 * a line before the end of img.
2538 buf
= preimage
->buf
;
2540 for (i
= 0; i
< preimage_limit
; i
++)
2541 buf_end
+= preimage
->line
[i
].len
;
2543 for ( ; buf
< buf_end
; buf
++)
2551 * No exact match. If we are ignoring whitespace, run a line-by-line
2552 * fuzzy matching. We collect all the line length information because
2553 * we need it to adjust whitespace if we match.
2555 if (state
->ws_ignore_action
== ignore_ws_change
)
2556 return line_by_line_fuzzy_match(img
, preimage
, postimage
,
2557 current
, current_lno
, preimage_limit
);
2559 if (state
->ws_error_action
!= correct_ws_error
)
2563 * The hunk does not apply byte-by-byte, but the hash says
2564 * it might with whitespace fuzz. We weren't asked to
2565 * ignore whitespace, we were asked to correct whitespace
2566 * errors, so let's try matching after whitespace correction.
2568 * While checking the preimage against the target, whitespace
2569 * errors in both fixed, we count how large the corresponding
2570 * postimage needs to be. The postimage prepared by
2571 * apply_one_fragment() has whitespace errors fixed on added
2572 * lines already, but the common lines were propagated as-is,
2573 * which may become longer when their whitespace errors are
2577 /* First count added lines in postimage */
2579 for (i
= 0; i
< postimage
->nr
; i
++) {
2580 if (!(postimage
->line
[i
].flag
& LINE_COMMON
))
2581 postlen
+= postimage
->line
[i
].len
;
2585 * The preimage may extend beyond the end of the file,
2586 * but in this loop we will only handle the part of the
2587 * preimage that falls within the file.
2589 strbuf_init(&fixed
, preimage
->len
+ 1);
2590 orig
= preimage
->buf
;
2591 target
= img
->buf
+ current
;
2592 for (i
= 0; i
< preimage_limit
; i
++) {
2593 size_t oldlen
= preimage
->line
[i
].len
;
2594 size_t tgtlen
= img
->line
[current_lno
+ i
].len
;
2595 size_t fixstart
= fixed
.len
;
2596 struct strbuf tgtfix
;
2599 /* Try fixing the line in the preimage */
2600 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2602 /* Try fixing the line in the target */
2603 strbuf_init(&tgtfix
, tgtlen
);
2604 ws_fix_copy(&tgtfix
, target
, tgtlen
, ws_rule
, NULL
);
2607 * If they match, either the preimage was based on
2608 * a version before our tree fixed whitespace breakage,
2609 * or we are lacking a whitespace-fix patch the tree
2610 * the preimage was based on already had (i.e. target
2611 * has whitespace breakage, the preimage doesn't).
2612 * In either case, we are fixing the whitespace breakages
2613 * so we might as well take the fix together with their
2616 match
= (tgtfix
.len
== fixed
.len
- fixstart
&&
2617 !memcmp(tgtfix
.buf
, fixed
.buf
+ fixstart
,
2618 fixed
.len
- fixstart
));
2620 /* Add the length if this is common with the postimage */
2621 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2622 postlen
+= tgtfix
.len
;
2624 strbuf_release(&tgtfix
);
2634 * Now handle the lines in the preimage that falls beyond the
2635 * end of the file (if any). They will only match if they are
2636 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2639 for ( ; i
< preimage
->nr
; i
++) {
2640 size_t fixstart
= fixed
.len
; /* start of the fixed preimage */
2641 size_t oldlen
= preimage
->line
[i
].len
;
2644 /* Try fixing the line in the preimage */
2645 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2647 for (j
= fixstart
; j
< fixed
.len
; j
++)
2648 if (!isspace(fixed
.buf
[j
]))
2655 * Yes, the preimage is based on an older version that still
2656 * has whitespace breakages unfixed, and fixing them makes the
2657 * hunk match. Update the context lines in the postimage.
2659 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2660 if (postlen
< postimage
->len
)
2662 update_pre_post_images(preimage
, postimage
,
2663 fixed_buf
, fixed_len
, postlen
);
2667 strbuf_release(&fixed
);
2671 static int find_pos(struct apply_state
*state
,
2673 struct image
*preimage
,
2674 struct image
*postimage
,
2677 int match_beginning
, int match_end
)
2680 unsigned long backwards
, forwards
, current
;
2681 int backwards_lno
, forwards_lno
, current_lno
;
2684 * If match_beginning or match_end is specified, there is no
2685 * point starting from a wrong line that will never match and
2686 * wander around and wait for a match at the specified end.
2688 if (match_beginning
)
2691 line
= img
->nr
- preimage
->nr
;
2694 * Because the comparison is unsigned, the following test
2695 * will also take care of a negative line number that can
2696 * result when match_end and preimage is larger than the target.
2698 if ((size_t) line
> img
->nr
)
2702 for (i
= 0; i
< line
; i
++)
2703 current
+= img
->line
[i
].len
;
2706 * There's probably some smart way to do this, but I'll leave
2707 * that to the smart and beautiful people. I'm simple and stupid.
2709 backwards
= current
;
2710 backwards_lno
= line
;
2712 forwards_lno
= line
;
2715 for (i
= 0; ; i
++) {
2716 if (match_fragment(state
, img
, preimage
, postimage
,
2717 current
, current_lno
, ws_rule
,
2718 match_beginning
, match_end
))
2722 if (backwards_lno
== 0 && forwards_lno
== img
->nr
)
2726 if (backwards_lno
== 0) {
2731 backwards
-= img
->line
[backwards_lno
].len
;
2732 current
= backwards
;
2733 current_lno
= backwards_lno
;
2735 if (forwards_lno
== img
->nr
) {
2739 forwards
+= img
->line
[forwards_lno
].len
;
2742 current_lno
= forwards_lno
;
2749 static void remove_first_line(struct image
*img
)
2751 img
->buf
+= img
->line
[0].len
;
2752 img
->len
-= img
->line
[0].len
;
2757 static void remove_last_line(struct image
*img
)
2759 img
->len
-= img
->line
[--img
->nr
].len
;
2763 * The change from "preimage" and "postimage" has been found to
2764 * apply at applied_pos (counts in line numbers) in "img".
2765 * Update "img" to remove "preimage" and replace it with "postimage".
2767 static void update_image(struct apply_state
*state
,
2770 struct image
*preimage
,
2771 struct image
*postimage
)
2774 * remove the copy of preimage at offset in img
2775 * and replace it with postimage
2778 size_t remove_count
, insert_count
, applied_at
= 0;
2783 * If we are removing blank lines at the end of img,
2784 * the preimage may extend beyond the end.
2785 * If that is the case, we must be careful only to
2786 * remove the part of the preimage that falls within
2787 * the boundaries of img. Initialize preimage_limit
2788 * to the number of lines in the preimage that falls
2789 * within the boundaries.
2791 preimage_limit
= preimage
->nr
;
2792 if (preimage_limit
> img
->nr
- applied_pos
)
2793 preimage_limit
= img
->nr
- applied_pos
;
2795 for (i
= 0; i
< applied_pos
; i
++)
2796 applied_at
+= img
->line
[i
].len
;
2799 for (i
= 0; i
< preimage_limit
; i
++)
2800 remove_count
+= img
->line
[applied_pos
+ i
].len
;
2801 insert_count
= postimage
->len
;
2803 /* Adjust the contents */
2804 result
= xmalloc(st_add3(st_sub(img
->len
, remove_count
), insert_count
, 1));
2805 memcpy(result
, img
->buf
, applied_at
);
2806 memcpy(result
+ applied_at
, postimage
->buf
, postimage
->len
);
2807 memcpy(result
+ applied_at
+ postimage
->len
,
2808 img
->buf
+ (applied_at
+ remove_count
),
2809 img
->len
- (applied_at
+ remove_count
));
2812 img
->len
+= insert_count
- remove_count
;
2813 result
[img
->len
] = '\0';
2815 /* Adjust the line table */
2816 nr
= img
->nr
+ postimage
->nr
- preimage_limit
;
2817 if (preimage_limit
< postimage
->nr
) {
2819 * NOTE: this knows that we never call remove_first_line()
2820 * on anything other than pre/post image.
2822 REALLOC_ARRAY(img
->line
, nr
);
2823 img
->line_allocated
= img
->line
;
2825 if (preimage_limit
!= postimage
->nr
)
2826 MOVE_ARRAY(img
->line
+ applied_pos
+ postimage
->nr
,
2827 img
->line
+ applied_pos
+ preimage_limit
,
2828 img
->nr
- (applied_pos
+ preimage_limit
));
2829 COPY_ARRAY(img
->line
+ applied_pos
, postimage
->line
, postimage
->nr
);
2830 if (!state
->allow_overlap
)
2831 for (i
= 0; i
< postimage
->nr
; i
++)
2832 img
->line
[applied_pos
+ i
].flag
|= LINE_PATCHED
;
2837 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2838 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2839 * replace the part of "img" with "postimage" text.
2841 static int apply_one_fragment(struct apply_state
*state
,
2842 struct image
*img
, struct fragment
*frag
,
2843 int inaccurate_eof
, unsigned ws_rule
,
2846 int match_beginning
, match_end
;
2847 const char *patch
= frag
->patch
;
2848 int size
= frag
->size
;
2849 char *old
, *oldlines
;
2850 struct strbuf newlines
;
2851 int new_blank_lines_at_end
= 0;
2852 int found_new_blank_lines_at_end
= 0;
2853 int hunk_linenr
= frag
->linenr
;
2854 unsigned long leading
, trailing
;
2855 int pos
, applied_pos
;
2856 struct image preimage
;
2857 struct image postimage
;
2859 memset(&preimage
, 0, sizeof(preimage
));
2860 memset(&postimage
, 0, sizeof(postimage
));
2861 oldlines
= xmalloc(size
);
2862 strbuf_init(&newlines
, size
);
2867 int len
= linelen(patch
, size
);
2869 int added_blank_line
= 0;
2870 int is_blank_context
= 0;
2877 * "plen" is how much of the line we should use for
2878 * the actual patch data. Normally we just remove the
2879 * first character on the line, but if the line is
2880 * followed by "\ No newline", then we also remove the
2881 * last one (which is the newline, of course).
2884 if (len
< size
&& patch
[len
] == '\\')
2887 if (state
->apply_in_reverse
) {
2890 else if (first
== '+')
2896 /* Newer GNU diff, empty context line */
2898 /* ... followed by '\No newline'; nothing */
2901 strbuf_addch(&newlines
, '\n');
2902 add_line_info(&preimage
, "\n", 1, LINE_COMMON
);
2903 add_line_info(&postimage
, "\n", 1, LINE_COMMON
);
2904 is_blank_context
= 1;
2907 if (plen
&& (ws_rule
& WS_BLANK_AT_EOF
) &&
2908 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2909 is_blank_context
= 1;
2912 memcpy(old
, patch
+ 1, plen
);
2913 add_line_info(&preimage
, old
, plen
,
2914 (first
== ' ' ? LINE_COMMON
: 0));
2920 /* --no-add does not add new lines */
2921 if (first
== '+' && state
->no_add
)
2924 start
= newlines
.len
;
2926 !state
->whitespace_error
||
2927 state
->ws_error_action
!= correct_ws_error
) {
2928 strbuf_add(&newlines
, patch
+ 1, plen
);
2931 ws_fix_copy(&newlines
, patch
+ 1, plen
, ws_rule
, &state
->applied_after_fixing_ws
);
2933 add_line_info(&postimage
, newlines
.buf
+ start
, newlines
.len
- start
,
2934 (first
== '+' ? 0 : LINE_COMMON
));
2936 (ws_rule
& WS_BLANK_AT_EOF
) &&
2937 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2938 added_blank_line
= 1;
2940 case '@': case '\\':
2941 /* Ignore it, we already handled it */
2944 if (state
->apply_verbosity
> verbosity_normal
)
2945 error(_("invalid start of line: '%c'"), first
);
2949 if (added_blank_line
) {
2950 if (!new_blank_lines_at_end
)
2951 found_new_blank_lines_at_end
= hunk_linenr
;
2952 new_blank_lines_at_end
++;
2954 else if (is_blank_context
)
2957 new_blank_lines_at_end
= 0;
2962 if (inaccurate_eof
&&
2963 old
> oldlines
&& old
[-1] == '\n' &&
2964 newlines
.len
> 0 && newlines
.buf
[newlines
.len
- 1] == '\n') {
2966 strbuf_setlen(&newlines
, newlines
.len
- 1);
2967 preimage
.line_allocated
[preimage
.nr
- 1].len
--;
2968 postimage
.line_allocated
[postimage
.nr
- 1].len
--;
2971 leading
= frag
->leading
;
2972 trailing
= frag
->trailing
;
2975 * A hunk to change lines at the beginning would begin with
2977 * but we need to be careful. -U0 that inserts before the second
2978 * line also has this pattern.
2980 * And a hunk to add to an empty file would begin with
2983 * In other words, a hunk that is (frag->oldpos <= 1) with or
2984 * without leading context must match at the beginning.
2986 match_beginning
= (!frag
->oldpos
||
2987 (frag
->oldpos
== 1 && !state
->unidiff_zero
));
2990 * A hunk without trailing lines must match at the end.
2991 * However, we simply cannot tell if a hunk must match end
2992 * from the lack of trailing lines if the patch was generated
2993 * with unidiff without any context.
2995 match_end
= !state
->unidiff_zero
&& !trailing
;
2997 pos
= frag
->newpos
? (frag
->newpos
- 1) : 0;
2998 preimage
.buf
= oldlines
;
2999 preimage
.len
= old
- oldlines
;
3000 postimage
.buf
= newlines
.buf
;
3001 postimage
.len
= newlines
.len
;
3002 preimage
.line
= preimage
.line_allocated
;
3003 postimage
.line
= postimage
.line_allocated
;
3007 applied_pos
= find_pos(state
, img
, &preimage
, &postimage
, pos
,
3008 ws_rule
, match_beginning
, match_end
);
3010 if (applied_pos
>= 0)
3013 /* Am I at my context limits? */
3014 if ((leading
<= state
->p_context
) && (trailing
<= state
->p_context
))
3016 if (match_beginning
|| match_end
) {
3017 match_beginning
= match_end
= 0;
3022 * Reduce the number of context lines; reduce both
3023 * leading and trailing if they are equal otherwise
3024 * just reduce the larger context.
3026 if (leading
>= trailing
) {
3027 remove_first_line(&preimage
);
3028 remove_first_line(&postimage
);
3032 if (trailing
> leading
) {
3033 remove_last_line(&preimage
);
3034 remove_last_line(&postimage
);
3039 if (applied_pos
>= 0) {
3040 if (new_blank_lines_at_end
&&
3041 preimage
.nr
+ applied_pos
>= img
->nr
&&
3042 (ws_rule
& WS_BLANK_AT_EOF
) &&
3043 state
->ws_error_action
!= nowarn_ws_error
) {
3044 record_ws_error(state
, WS_BLANK_AT_EOF
, "+", 1,
3045 found_new_blank_lines_at_end
);
3046 if (state
->ws_error_action
== correct_ws_error
) {
3047 while (new_blank_lines_at_end
--)
3048 remove_last_line(&postimage
);
3051 * We would want to prevent write_out_results()
3052 * from taking place in apply_patch() that follows
3053 * the callchain led us here, which is:
3054 * apply_patch->check_patch_list->check_patch->
3055 * apply_data->apply_fragments->apply_one_fragment
3057 if (state
->ws_error_action
== die_on_ws_error
)
3061 if (state
->apply_verbosity
> verbosity_normal
&& applied_pos
!= pos
) {
3062 int offset
= applied_pos
- pos
;
3063 if (state
->apply_in_reverse
)
3064 offset
= 0 - offset
;
3066 Q_("Hunk #%d succeeded at %d (offset %d line).",
3067 "Hunk #%d succeeded at %d (offset %d lines).",
3069 nth_fragment
, applied_pos
+ 1, offset
);
3073 * Warn if it was necessary to reduce the number
3076 if ((leading
!= frag
->leading
||
3077 trailing
!= frag
->trailing
) && state
->apply_verbosity
> verbosity_silent
)
3078 fprintf_ln(stderr
, _("Context reduced to (%ld/%ld)"
3079 " to apply fragment at %d"),
3080 leading
, trailing
, applied_pos
+1);
3081 update_image(state
, img
, applied_pos
, &preimage
, &postimage
);
3083 if (state
->apply_verbosity
> verbosity_normal
)
3084 error(_("while searching for:\n%.*s"),
3085 (int)(old
- oldlines
), oldlines
);
3090 strbuf_release(&newlines
);
3091 free(preimage
.line_allocated
);
3092 free(postimage
.line_allocated
);
3094 return (applied_pos
< 0);
3097 static int apply_binary_fragment(struct apply_state
*state
,
3099 struct patch
*patch
)
3101 struct fragment
*fragment
= patch
->fragments
;
3106 return error(_("missing binary patch data for '%s'"),
3111 /* Binary patch is irreversible without the optional second hunk */
3112 if (state
->apply_in_reverse
) {
3113 if (!fragment
->next
)
3114 return error(_("cannot reverse-apply a binary patch "
3115 "without the reverse hunk to '%s'"),
3117 ? patch
->new_name
: patch
->old_name
);
3118 fragment
= fragment
->next
;
3120 switch (fragment
->binary_patch_method
) {
3121 case BINARY_DELTA_DEFLATED
:
3122 dst
= patch_delta(img
->buf
, img
->len
, fragment
->patch
,
3123 fragment
->size
, &len
);
3130 case BINARY_LITERAL_DEFLATED
:
3132 img
->len
= fragment
->size
;
3133 img
->buf
= xmemdupz(fragment
->patch
, img
->len
);
3140 * Replace "img" with the result of applying the binary patch.
3141 * The binary patch data itself in patch->fragment is still kept
3142 * but the preimage prepared by the caller in "img" is freed here
3143 * or in the helper function apply_binary_fragment() this calls.
3145 static int apply_binary(struct apply_state
*state
,
3147 struct patch
*patch
)
3149 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3150 struct object_id oid
;
3151 const unsigned hexsz
= the_hash_algo
->hexsz
;
3154 * For safety, we require patch index line to contain
3155 * full hex textual object ID for old and new, at least for now.
3157 if (strlen(patch
->old_oid_prefix
) != hexsz
||
3158 strlen(patch
->new_oid_prefix
) != hexsz
||
3159 get_oid_hex(patch
->old_oid_prefix
, &oid
) ||
3160 get_oid_hex(patch
->new_oid_prefix
, &oid
))
3161 return error(_("cannot apply binary patch to '%s' "
3162 "without full index line"), name
);
3164 if (patch
->old_name
) {
3166 * See if the old one matches what the patch
3169 hash_object_file(img
->buf
, img
->len
, blob_type
, &oid
);
3170 if (strcmp(oid_to_hex(&oid
), patch
->old_oid_prefix
))
3171 return error(_("the patch applies to '%s' (%s), "
3172 "which does not match the "
3173 "current contents."),
3174 name
, oid_to_hex(&oid
));
3177 /* Otherwise, the old one must be empty. */
3179 return error(_("the patch applies to an empty "
3180 "'%s' but it is not empty"), name
);
3183 get_oid_hex(patch
->new_oid_prefix
, &oid
);
3184 if (is_null_oid(&oid
)) {
3186 return 0; /* deletion patch */
3189 if (has_object_file(&oid
)) {
3190 /* We already have the postimage */
3191 enum object_type type
;
3195 result
= read_object_file(&oid
, &type
, &size
);
3197 return error(_("the necessary postimage %s for "
3198 "'%s' cannot be read"),
3199 patch
->new_oid_prefix
, name
);
3205 * We have verified buf matches the preimage;
3206 * apply the patch data to it, which is stored
3207 * in the patch->fragments->{patch,size}.
3209 if (apply_binary_fragment(state
, img
, patch
))
3210 return error(_("binary patch does not apply to '%s'"),
3213 /* verify that the result matches */
3214 hash_object_file(img
->buf
, img
->len
, blob_type
, &oid
);
3215 if (strcmp(oid_to_hex(&oid
), patch
->new_oid_prefix
))
3216 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3217 name
, patch
->new_oid_prefix
, oid_to_hex(&oid
));
3223 static int apply_fragments(struct apply_state
*state
, struct image
*img
, struct patch
*patch
)
3225 struct fragment
*frag
= patch
->fragments
;
3226 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3227 unsigned ws_rule
= patch
->ws_rule
;
3228 unsigned inaccurate_eof
= patch
->inaccurate_eof
;
3231 if (patch
->is_binary
)
3232 return apply_binary(state
, img
, patch
);
3236 if (apply_one_fragment(state
, img
, frag
, inaccurate_eof
, ws_rule
, nth
)) {
3237 error(_("patch failed: %s:%ld"), name
, frag
->oldpos
);
3238 if (!state
->apply_with_reject
)
3247 static int read_blob_object(struct strbuf
*buf
, const struct object_id
*oid
, unsigned mode
)
3249 if (S_ISGITLINK(mode
)) {
3250 strbuf_grow(buf
, 100);
3251 strbuf_addf(buf
, "Subproject commit %s\n", oid_to_hex(oid
));
3253 enum object_type type
;
3257 result
= read_object_file(oid
, &type
, &sz
);
3260 /* XXX read_sha1_file NUL-terminates */
3261 strbuf_attach(buf
, result
, sz
, sz
+ 1);
3266 static int read_file_or_gitlink(const struct cache_entry
*ce
, struct strbuf
*buf
)
3270 return read_blob_object(buf
, &ce
->oid
, ce
->ce_mode
);
3273 static struct patch
*in_fn_table(struct apply_state
*state
, const char *name
)
3275 struct string_list_item
*item
;
3280 item
= string_list_lookup(&state
->fn_table
, name
);
3282 return (struct patch
*)item
->util
;
3288 * item->util in the filename table records the status of the path.
3289 * Usually it points at a patch (whose result records the contents
3290 * of it after applying it), but it could be PATH_WAS_DELETED for a
3291 * path that a previously applied patch has already removed, or
3292 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3294 * The latter is needed to deal with a case where two paths A and B
3295 * are swapped by first renaming A to B and then renaming B to A;
3296 * moving A to B should not be prevented due to presence of B as we
3297 * will remove it in a later patch.
3299 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3300 #define PATH_WAS_DELETED ((struct patch *) -1)
3302 static int to_be_deleted(struct patch
*patch
)
3304 return patch
== PATH_TO_BE_DELETED
;
3307 static int was_deleted(struct patch
*patch
)
3309 return patch
== PATH_WAS_DELETED
;
3312 static void add_to_fn_table(struct apply_state
*state
, struct patch
*patch
)
3314 struct string_list_item
*item
;
3317 * Always add new_name unless patch is a deletion
3318 * This should cover the cases for normal diffs,
3319 * file creations and copies
3321 if (patch
->new_name
!= NULL
) {
3322 item
= string_list_insert(&state
->fn_table
, patch
->new_name
);
3327 * store a failure on rename/deletion cases because
3328 * later chunks shouldn't patch old names
3330 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3331 item
= string_list_insert(&state
->fn_table
, patch
->old_name
);
3332 item
->util
= PATH_WAS_DELETED
;
3336 static void prepare_fn_table(struct apply_state
*state
, struct patch
*patch
)
3339 * store information about incoming file deletion
3342 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3343 struct string_list_item
*item
;
3344 item
= string_list_insert(&state
->fn_table
, patch
->old_name
);
3345 item
->util
= PATH_TO_BE_DELETED
;
3347 patch
= patch
->next
;
3351 static int checkout_target(struct index_state
*istate
,
3352 struct cache_entry
*ce
, struct stat
*st
)
3354 struct checkout costate
= CHECKOUT_INIT
;
3356 costate
.refresh_cache
= 1;
3357 costate
.istate
= istate
;
3358 if (checkout_entry(ce
, &costate
, NULL
, NULL
) ||
3359 lstat(ce
->name
, st
))
3360 return error(_("cannot checkout %s"), ce
->name
);
3364 static struct patch
*previous_patch(struct apply_state
*state
,
3365 struct patch
*patch
,
3368 struct patch
*previous
;
3371 if (patch
->is_copy
|| patch
->is_rename
)
3372 return NULL
; /* "git" patches do not depend on the order */
3374 previous
= in_fn_table(state
, patch
->old_name
);
3378 if (to_be_deleted(previous
))
3379 return NULL
; /* the deletion hasn't happened yet */
3381 if (was_deleted(previous
))
3387 static int verify_index_match(struct apply_state
*state
,
3388 const struct cache_entry
*ce
,
3391 if (S_ISGITLINK(ce
->ce_mode
)) {
3392 if (!S_ISDIR(st
->st_mode
))
3396 return ie_match_stat(state
->repo
->index
, ce
, st
,
3397 CE_MATCH_IGNORE_VALID
| CE_MATCH_IGNORE_SKIP_WORKTREE
);
3400 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3402 static int load_patch_target(struct apply_state
*state
,
3404 const struct cache_entry
*ce
,
3406 struct patch
*patch
,
3408 unsigned expected_mode
)
3410 if (state
->cached
|| state
->check_index
) {
3411 if (read_file_or_gitlink(ce
, buf
))
3412 return error(_("failed to read %s"), name
);
3414 if (S_ISGITLINK(expected_mode
)) {
3416 return read_file_or_gitlink(ce
, buf
);
3418 return SUBMODULE_PATCH_WITHOUT_INDEX
;
3419 } else if (has_symlink_leading_path(name
, strlen(name
))) {
3420 return error(_("reading from '%s' beyond a symbolic link"), name
);
3422 if (read_old_data(st
, patch
, name
, buf
))
3423 return error(_("failed to read %s"), name
);
3430 * We are about to apply "patch"; populate the "image" with the
3431 * current version we have, from the working tree or from the index,
3432 * depending on the situation e.g. --cached/--index. If we are
3433 * applying a non-git patch that incrementally updates the tree,
3434 * we read from the result of a previous diff.
3436 static int load_preimage(struct apply_state
*state
,
3437 struct image
*image
,
3438 struct patch
*patch
, struct stat
*st
,
3439 const struct cache_entry
*ce
)
3441 struct strbuf buf
= STRBUF_INIT
;
3444 struct patch
*previous
;
3447 previous
= previous_patch(state
, patch
, &status
);
3449 return error(_("path %s has been renamed/deleted"),
3452 /* We have a patched copy in memory; use that. */
3453 strbuf_add(&buf
, previous
->result
, previous
->resultsize
);
3455 status
= load_patch_target(state
, &buf
, ce
, st
, patch
,
3456 patch
->old_name
, patch
->old_mode
);
3459 else if (status
== SUBMODULE_PATCH_WITHOUT_INDEX
) {
3461 * There is no way to apply subproject
3462 * patch without looking at the index.
3463 * NEEDSWORK: shouldn't this be flagged
3466 free_fragment_list(patch
->fragments
);
3467 patch
->fragments
= NULL
;
3468 } else if (status
) {
3469 return error(_("failed to read %s"), patch
->old_name
);
3473 img
= strbuf_detach(&buf
, &len
);
3474 prepare_image(image
, img
, len
, !patch
->is_binary
);
3478 static int three_way_merge(struct apply_state
*state
,
3479 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",
3498 free(base_file
.ptr
);
3500 free(their_file
.ptr
);
3501 if (status
< 0 || !result
.ptr
) {
3506 image
->buf
= result
.ptr
;
3507 image
->len
= result
.size
;
3513 * When directly falling back to add/add three-way merge, we read from
3514 * the current contents of the new_name. In no cases other than that
3515 * this function will be called.
3517 static int load_current(struct apply_state
*state
,
3518 struct image
*image
,
3519 struct patch
*patch
)
3521 struct strbuf buf
= STRBUF_INIT
;
3526 struct cache_entry
*ce
;
3527 char *name
= patch
->new_name
;
3528 unsigned mode
= patch
->new_mode
;
3531 BUG("patch to %s is not a creation", patch
->old_name
);
3533 pos
= index_name_pos(state
->repo
->index
, name
, strlen(name
));
3535 return error(_("%s: does not exist in index"), name
);
3536 ce
= state
->repo
->index
->cache
[pos
];
3537 if (lstat(name
, &st
)) {
3538 if (errno
!= ENOENT
)
3539 return error_errno("%s", name
);
3540 if (checkout_target(state
->repo
->index
, ce
, &st
))
3543 if (verify_index_match(state
, ce
, &st
))
3544 return error(_("%s: does not match index"), name
);
3546 status
= load_patch_target(state
, &buf
, ce
, &st
, patch
, name
, mode
);
3551 img
= strbuf_detach(&buf
, &len
);
3552 prepare_image(image
, img
, len
, !patch
->is_binary
);
3556 static int try_threeway(struct apply_state
*state
,
3557 struct image
*image
,
3558 struct patch
*patch
,
3560 const struct cache_entry
*ce
)
3562 struct object_id pre_oid
, post_oid
, our_oid
;
3563 struct strbuf buf
= STRBUF_INIT
;
3567 struct image tmp_image
;
3569 /* No point falling back to 3-way merge in these cases */
3570 if (patch
->is_delete
||
3571 S_ISGITLINK(patch
->old_mode
) || S_ISGITLINK(patch
->new_mode
))
3574 /* Preimage the patch was prepared for */
3576 write_object_file("", 0, blob_type
, &pre_oid
);
3577 else if (get_oid(patch
->old_oid_prefix
, &pre_oid
) ||
3578 read_blob_object(&buf
, &pre_oid
, patch
->old_mode
))
3579 return error(_("repository lacks the necessary blob to fall back on 3-way merge."));
3581 if (state
->apply_verbosity
> verbosity_silent
)
3582 fprintf(stderr
, _("Falling back to three-way merge...\n"));
3584 img
= strbuf_detach(&buf
, &len
);
3585 prepare_image(&tmp_image
, img
, len
, 1);
3586 /* Apply the patch to get the post image */
3587 if (apply_fragments(state
, &tmp_image
, patch
) < 0) {
3588 clear_image(&tmp_image
);
3591 /* post_oid is theirs */
3592 write_object_file(tmp_image
.buf
, tmp_image
.len
, blob_type
, &post_oid
);
3593 clear_image(&tmp_image
);
3595 /* our_oid is ours */
3596 if (patch
->is_new
) {
3597 if (load_current(state
, &tmp_image
, patch
))
3598 return error(_("cannot read the current contents of '%s'"),
3601 if (load_preimage(state
, &tmp_image
, patch
, st
, ce
))
3602 return error(_("cannot read the current contents of '%s'"),
3605 write_object_file(tmp_image
.buf
, tmp_image
.len
, blob_type
, &our_oid
);
3606 clear_image(&tmp_image
);
3608 /* in-core three-way merge between post and our using pre as base */
3609 status
= three_way_merge(state
, image
, patch
->new_name
,
3610 &pre_oid
, &our_oid
, &post_oid
);
3612 if (state
->apply_verbosity
> verbosity_silent
)
3614 _("Failed to fall back on three-way merge...\n"));
3619 patch
->conflicted_threeway
= 1;
3621 oidclr(&patch
->threeway_stage
[0]);
3623 oidcpy(&patch
->threeway_stage
[0], &pre_oid
);
3624 oidcpy(&patch
->threeway_stage
[1], &our_oid
);
3625 oidcpy(&patch
->threeway_stage
[2], &post_oid
);
3626 if (state
->apply_verbosity
> verbosity_silent
)
3628 _("Applied patch to '%s' with conflicts.\n"),
3631 if (state
->apply_verbosity
> verbosity_silent
)
3633 _("Applied patch to '%s' cleanly.\n"),
3639 static int apply_data(struct apply_state
*state
, struct patch
*patch
,
3640 struct stat
*st
, const struct cache_entry
*ce
)
3644 if (load_preimage(state
, &image
, patch
, st
, ce
) < 0)
3647 if (patch
->direct_to_threeway
||
3648 apply_fragments(state
, &image
, patch
) < 0) {
3649 /* Note: with --reject, apply_fragments() returns 0 */
3650 if (!state
->threeway
|| try_threeway(state
, &image
, patch
, st
, ce
) < 0)
3653 patch
->result
= image
.buf
;
3654 patch
->resultsize
= image
.len
;
3655 add_to_fn_table(state
, patch
);
3656 free(image
.line_allocated
);
3658 if (0 < patch
->is_delete
&& patch
->resultsize
)
3659 return error(_("removal patch leaves file contents"));
3665 * If "patch" that we are looking at modifies or deletes what we have,
3666 * we would want it not to lose any local modification we have, either
3667 * in the working tree or in the index.
3669 * This also decides if a non-git patch is a creation patch or a
3670 * modification to an existing empty file. We do not check the state
3671 * of the current tree for a creation patch in this function; the caller
3672 * check_patch() separately makes sure (and errors out otherwise) that
3673 * the path the patch creates does not exist in the current tree.
3675 static int check_preimage(struct apply_state
*state
,
3676 struct patch
*patch
,
3677 struct cache_entry
**ce
,
3680 const char *old_name
= patch
->old_name
;
3681 struct patch
*previous
= NULL
;
3682 int stat_ret
= 0, status
;
3683 unsigned st_mode
= 0;
3688 assert(patch
->is_new
<= 0);
3689 previous
= previous_patch(state
, patch
, &status
);
3692 return error(_("path %s has been renamed/deleted"), old_name
);
3694 st_mode
= previous
->new_mode
;
3695 } else if (!state
->cached
) {
3696 stat_ret
= lstat(old_name
, st
);
3697 if (stat_ret
&& errno
!= ENOENT
)
3698 return error_errno("%s", old_name
);
3701 if (state
->check_index
&& !previous
) {
3702 int pos
= index_name_pos(state
->repo
->index
, old_name
,
3705 if (patch
->is_new
< 0)
3707 return error(_("%s: does not exist in index"), old_name
);
3709 *ce
= state
->repo
->index
->cache
[pos
];
3711 if (checkout_target(state
->repo
->index
, *ce
, st
))
3714 if (!state
->cached
&& verify_index_match(state
, *ce
, st
))
3715 return error(_("%s: does not match index"), old_name
);
3717 st_mode
= (*ce
)->ce_mode
;
3718 } else if (stat_ret
< 0) {
3719 if (patch
->is_new
< 0)
3721 return error_errno("%s", old_name
);
3724 if (!state
->cached
&& !previous
)
3725 st_mode
= ce_mode_from_stat(*ce
, st
->st_mode
);
3727 if (patch
->is_new
< 0)
3729 if (!patch
->old_mode
)
3730 patch
->old_mode
= st_mode
;
3731 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
3732 return error(_("%s: wrong type"), old_name
);
3733 if (st_mode
!= patch
->old_mode
)
3734 warning(_("%s has type %o, expected %o"),
3735 old_name
, st_mode
, patch
->old_mode
);
3736 if (!patch
->new_mode
&& !patch
->is_delete
)
3737 patch
->new_mode
= st_mode
;
3742 patch
->is_delete
= 0;
3743 FREE_AND_NULL(patch
->old_name
);
3748 #define EXISTS_IN_INDEX 1
3749 #define EXISTS_IN_WORKTREE 2
3751 static int check_to_create(struct apply_state
*state
,
3752 const char *new_name
,
3757 if (state
->check_index
&&
3758 index_name_pos(state
->repo
->index
, new_name
, strlen(new_name
)) >= 0 &&
3760 return EXISTS_IN_INDEX
;
3764 if (!lstat(new_name
, &nst
)) {
3765 if (S_ISDIR(nst
.st_mode
) || ok_if_exists
)
3768 * A leading component of new_name might be a symlink
3769 * that is going to be removed with this patch, but
3770 * still pointing at somewhere that has the path.
3771 * In such a case, path "new_name" does not exist as
3772 * far as git is concerned.
3774 if (has_symlink_leading_path(new_name
, strlen(new_name
)))
3777 return EXISTS_IN_WORKTREE
;
3778 } else if (!is_missing_file_error(errno
)) {
3779 return error_errno("%s", new_name
);
3784 static uintptr_t register_symlink_changes(struct apply_state
*state
,
3788 struct string_list_item
*ent
;
3790 ent
= string_list_lookup(&state
->symlink_changes
, path
);
3792 ent
= string_list_insert(&state
->symlink_changes
, path
);
3793 ent
->util
= (void *)0;
3795 ent
->util
= (void *)(what
| ((uintptr_t)ent
->util
));
3796 return (uintptr_t)ent
->util
;
3799 static uintptr_t check_symlink_changes(struct apply_state
*state
, const char *path
)
3801 struct string_list_item
*ent
;
3803 ent
= string_list_lookup(&state
->symlink_changes
, path
);
3806 return (uintptr_t)ent
->util
;
3809 static void prepare_symlink_changes(struct apply_state
*state
, struct patch
*patch
)
3811 for ( ; patch
; patch
= patch
->next
) {
3812 if ((patch
->old_name
&& S_ISLNK(patch
->old_mode
)) &&
3813 (patch
->is_rename
|| patch
->is_delete
))
3814 /* the symlink at patch->old_name is removed */
3815 register_symlink_changes(state
, patch
->old_name
, APPLY_SYMLINK_GOES_AWAY
);
3817 if (patch
->new_name
&& S_ISLNK(patch
->new_mode
))
3818 /* the symlink at patch->new_name is created or remains */
3819 register_symlink_changes(state
, patch
->new_name
, APPLY_SYMLINK_IN_RESULT
);
3823 static int path_is_beyond_symlink_1(struct apply_state
*state
, struct strbuf
*name
)
3826 unsigned int change
;
3828 while (--name
->len
&& name
->buf
[name
->len
] != '/')
3829 ; /* scan backwards */
3832 name
->buf
[name
->len
] = '\0';
3833 change
= check_symlink_changes(state
, name
->buf
);
3834 if (change
& APPLY_SYMLINK_IN_RESULT
)
3836 if (change
& APPLY_SYMLINK_GOES_AWAY
)
3838 * This cannot be "return 0", because we may
3839 * see a new one created at a higher level.
3843 /* otherwise, check the preimage */
3844 if (state
->check_index
) {
3845 struct cache_entry
*ce
;
3847 ce
= index_file_exists(state
->repo
->index
, name
->buf
,
3848 name
->len
, ignore_case
);
3849 if (ce
&& S_ISLNK(ce
->ce_mode
))
3853 if (!lstat(name
->buf
, &st
) && S_ISLNK(st
.st_mode
))
3860 static int path_is_beyond_symlink(struct apply_state
*state
, const char *name_
)
3863 struct strbuf name
= STRBUF_INIT
;
3865 assert(*name_
!= '\0');
3866 strbuf_addstr(&name
, name_
);
3867 ret
= path_is_beyond_symlink_1(state
, &name
);
3868 strbuf_release(&name
);
3873 static int check_unsafe_path(struct patch
*patch
)
3875 const char *old_name
= NULL
;
3876 const char *new_name
= NULL
;
3877 if (patch
->is_delete
)
3878 old_name
= patch
->old_name
;
3879 else if (!patch
->is_new
&& !patch
->is_copy
)
3880 old_name
= patch
->old_name
;
3881 if (!patch
->is_delete
)
3882 new_name
= patch
->new_name
;
3884 if (old_name
&& !verify_path(old_name
, patch
->old_mode
))
3885 return error(_("invalid path '%s'"), old_name
);
3886 if (new_name
&& !verify_path(new_name
, patch
->new_mode
))
3887 return error(_("invalid path '%s'"), new_name
);
3892 * Check and apply the patch in-core; leave the result in patch->result
3893 * for the caller to write it out to the final destination.
3895 static int check_patch(struct apply_state
*state
, struct patch
*patch
)
3898 const char *old_name
= patch
->old_name
;
3899 const char *new_name
= patch
->new_name
;
3900 const char *name
= old_name
? old_name
: new_name
;
3901 struct cache_entry
*ce
= NULL
;
3902 struct patch
*tpatch
;
3906 patch
->rejected
= 1; /* we will drop this after we succeed */
3908 status
= check_preimage(state
, patch
, &ce
, &st
);
3911 old_name
= patch
->old_name
;
3914 * A type-change diff is always split into a patch to delete
3915 * old, immediately followed by a patch to create new (see
3916 * diff.c::run_diff()); in such a case it is Ok that the entry
3917 * to be deleted by the previous patch is still in the working
3918 * tree and in the index.
3920 * A patch to swap-rename between A and B would first rename A
3921 * to B and then rename B to A. While applying the first one,
3922 * the presence of B should not stop A from getting renamed to
3923 * B; ask to_be_deleted() about the later rename. Removal of
3924 * B and rename from A to B is handled the same way by asking
3927 if ((tpatch
= in_fn_table(state
, new_name
)) &&
3928 (was_deleted(tpatch
) || to_be_deleted(tpatch
)))
3934 ((0 < patch
->is_new
) || patch
->is_rename
|| patch
->is_copy
)) {
3935 int err
= check_to_create(state
, new_name
, ok_if_exists
);
3937 if (err
&& state
->threeway
) {
3938 patch
->direct_to_threeway
= 1;
3939 } else switch (err
) {
3942 case EXISTS_IN_INDEX
:
3943 return error(_("%s: already exists in index"), new_name
);
3945 case EXISTS_IN_WORKTREE
:
3946 return error(_("%s: already exists in working directory"),
3952 if (!patch
->new_mode
) {
3953 if (0 < patch
->is_new
)
3954 patch
->new_mode
= S_IFREG
| 0644;
3956 patch
->new_mode
= patch
->old_mode
;
3960 if (new_name
&& old_name
) {
3961 int same
= !strcmp(old_name
, new_name
);
3962 if (!patch
->new_mode
)
3963 patch
->new_mode
= patch
->old_mode
;
3964 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
) {
3966 return error(_("new mode (%o) of %s does not "
3967 "match old mode (%o)"),
3968 patch
->new_mode
, new_name
,
3971 return error(_("new mode (%o) of %s does not "
3972 "match old mode (%o) of %s"),
3973 patch
->new_mode
, new_name
,
3974 patch
->old_mode
, old_name
);
3978 if (!state
->unsafe_paths
&& check_unsafe_path(patch
))
3982 * An attempt to read from or delete a path that is beyond a
3983 * symbolic link will be prevented by load_patch_target() that
3984 * is called at the beginning of apply_data() so we do not
3985 * have to worry about a patch marked with "is_delete" bit
3986 * here. We however need to make sure that the patch result
3987 * is not deposited to a path that is beyond a symbolic link
3990 if (!patch
->is_delete
&& path_is_beyond_symlink(state
, patch
->new_name
))
3991 return error(_("affected file '%s' is beyond a symbolic link"),
3994 if (apply_data(state
, patch
, &st
, ce
) < 0)
3995 return error(_("%s: patch does not apply"), name
);
3996 patch
->rejected
= 0;
4000 static int check_patch_list(struct apply_state
*state
, struct patch
*patch
)
4004 prepare_symlink_changes(state
, patch
);
4005 prepare_fn_table(state
, patch
);
4008 if (state
->apply_verbosity
> verbosity_normal
)
4009 say_patch_name(stderr
,
4010 _("Checking patch %s..."), patch
);
4011 res
= check_patch(state
, patch
);
4015 patch
= patch
->next
;
4020 static int read_apply_cache(struct apply_state
*state
)
4022 if (state
->index_file
)
4023 return read_index_from(state
->repo
->index
, state
->index_file
,
4026 return repo_read_index(state
->repo
);
4029 /* This function tries to read the object name from the current index */
4030 static int get_current_oid(struct apply_state
*state
, const char *path
,
4031 struct object_id
*oid
)
4035 if (read_apply_cache(state
) < 0)
4037 pos
= index_name_pos(state
->repo
->index
, path
, strlen(path
));
4040 oidcpy(oid
, &state
->repo
->index
->cache
[pos
]->oid
);
4044 static int preimage_oid_in_gitlink_patch(struct patch
*p
, struct object_id
*oid
)
4047 * A usable gitlink patch has only one fragment (hunk) that looks like:
4049 * -Subproject commit <old sha1>
4050 * +Subproject commit <new sha1>
4053 * -Subproject commit <old sha1>
4054 * for a removal patch.
4056 struct fragment
*hunk
= p
->fragments
;
4057 static const char heading
[] = "-Subproject commit ";
4060 if (/* does the patch have only one hunk? */
4061 hunk
&& !hunk
->next
&&
4062 /* is its preimage one line? */
4063 hunk
->oldpos
== 1 && hunk
->oldlines
== 1 &&
4064 /* does preimage begin with the heading? */
4065 (preimage
= memchr(hunk
->patch
, '\n', hunk
->size
)) != NULL
&&
4066 starts_with(++preimage
, heading
) &&
4067 /* does it record full SHA-1? */
4068 !get_oid_hex(preimage
+ sizeof(heading
) - 1, oid
) &&
4069 preimage
[sizeof(heading
) + the_hash_algo
->hexsz
- 1] == '\n' &&
4070 /* does the abbreviated name on the index line agree with it? */
4071 starts_with(preimage
+ sizeof(heading
) - 1, p
->old_oid_prefix
))
4072 return 0; /* it all looks fine */
4074 /* we may have full object name on the index line */
4075 return get_oid_hex(p
->old_oid_prefix
, oid
);
4078 /* Build an index that contains just the files needed for a 3way merge */
4079 static int build_fake_ancestor(struct apply_state
*state
, struct patch
*list
)
4081 struct patch
*patch
;
4082 struct index_state result
= { NULL
};
4083 struct lock_file lock
= LOCK_INIT
;
4086 /* Once we start supporting the reverse patch, it may be
4087 * worth showing the new sha1 prefix, but until then...
4089 for (patch
= list
; patch
; patch
= patch
->next
) {
4090 struct object_id oid
;
4091 struct cache_entry
*ce
;
4094 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
4095 if (0 < patch
->is_new
)
4098 if (S_ISGITLINK(patch
->old_mode
)) {
4099 if (!preimage_oid_in_gitlink_patch(patch
, &oid
))
4100 ; /* ok, the textual part looks sane */
4102 return error(_("sha1 information is lacking or "
4103 "useless for submodule %s"), name
);
4104 } else if (!get_oid_blob(patch
->old_oid_prefix
, &oid
)) {
4106 } else if (!patch
->lines_added
&& !patch
->lines_deleted
) {
4107 /* mode-only change: update the current */
4108 if (get_current_oid(state
, patch
->old_name
, &oid
))
4109 return error(_("mode change for %s, which is not "
4110 "in current HEAD"), name
);
4112 return error(_("sha1 information is lacking or useless "
4115 ce
= make_cache_entry(&result
, patch
->old_mode
, &oid
, name
, 0, 0);
4117 return error(_("make_cache_entry failed for path '%s'"),
4119 if (add_index_entry(&result
, ce
, ADD_CACHE_OK_TO_ADD
)) {
4120 discard_cache_entry(ce
);
4121 return error(_("could not add %s to temporary index"),
4126 hold_lock_file_for_update(&lock
, state
->fake_ancestor
, LOCK_DIE_ON_ERROR
);
4127 res
= write_locked_index(&result
, &lock
, COMMIT_LOCK
);
4128 discard_index(&result
);
4131 return error(_("could not write temporary index to %s"),
4132 state
->fake_ancestor
);
4137 static void stat_patch_list(struct apply_state
*state
, struct patch
*patch
)
4139 int files
, adds
, dels
;
4141 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
4143 adds
+= patch
->lines_added
;
4144 dels
+= patch
->lines_deleted
;
4145 show_stats(state
, patch
);
4148 print_stat_summary(stdout
, files
, adds
, dels
);
4151 static void numstat_patch_list(struct apply_state
*state
,
4152 struct patch
*patch
)
4154 for ( ; patch
; patch
= patch
->next
) {
4156 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
4157 if (patch
->is_binary
)
4160 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
4161 write_name_quoted(name
, stdout
, state
->line_termination
);
4165 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
4168 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
4170 printf(" %s %s\n", newdelete
, name
);
4173 static void show_mode_change(struct patch
*p
, int show_name
)
4175 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
4177 printf(" mode change %06o => %06o %s\n",
4178 p
->old_mode
, p
->new_mode
, p
->new_name
);
4180 printf(" mode change %06o => %06o\n",
4181 p
->old_mode
, p
->new_mode
);
4185 static void show_rename_copy(struct patch
*p
)
4187 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
4188 const char *old_name
, *new_name
;
4190 /* Find common prefix */
4191 old_name
= p
->old_name
;
4192 new_name
= p
->new_name
;
4194 const char *slash_old
, *slash_new
;
4195 slash_old
= strchr(old_name
, '/');
4196 slash_new
= strchr(new_name
, '/');
4199 slash_old
- old_name
!= slash_new
- new_name
||
4200 memcmp(old_name
, new_name
, slash_new
- new_name
))
4202 old_name
= slash_old
+ 1;
4203 new_name
= slash_new
+ 1;
4205 /* p->old_name thru old_name is the common prefix, and old_name and new_name
4206 * through the end of names are renames
4208 if (old_name
!= p
->old_name
)
4209 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
4210 (int)(old_name
- p
->old_name
), p
->old_name
,
4211 old_name
, new_name
, p
->score
);
4213 printf(" %s %s => %s (%d%%)\n", renamecopy
,
4214 p
->old_name
, p
->new_name
, p
->score
);
4215 show_mode_change(p
, 0);
4218 static void summary_patch_list(struct patch
*patch
)
4222 for (p
= patch
; p
; p
= p
->next
) {
4224 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
4225 else if (p
->is_delete
)
4226 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
4228 if (p
->is_rename
|| p
->is_copy
)
4229 show_rename_copy(p
);
4232 printf(" rewrite %s (%d%%)\n",
4233 p
->new_name
, p
->score
);
4234 show_mode_change(p
, 0);
4237 show_mode_change(p
, 1);
4243 static void patch_stats(struct apply_state
*state
, struct patch
*patch
)
4245 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
4247 if (lines
> state
->max_change
)
4248 state
->max_change
= lines
;
4249 if (patch
->old_name
) {
4250 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
4252 len
= strlen(patch
->old_name
);
4253 if (len
> state
->max_len
)
4254 state
->max_len
= len
;
4256 if (patch
->new_name
) {
4257 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
4259 len
= strlen(patch
->new_name
);
4260 if (len
> state
->max_len
)
4261 state
->max_len
= len
;
4265 static int remove_file(struct apply_state
*state
, struct patch
*patch
, int rmdir_empty
)
4267 if (state
->update_index
&& !state
->ita_only
) {
4268 if (remove_file_from_index(state
->repo
->index
, patch
->old_name
) < 0)
4269 return error(_("unable to remove %s from index"), patch
->old_name
);
4271 if (!state
->cached
) {
4272 if (!remove_or_warn(patch
->old_mode
, patch
->old_name
) && rmdir_empty
) {
4273 remove_path(patch
->old_name
);
4279 static int add_index_file(struct apply_state
*state
,
4286 struct cache_entry
*ce
;
4287 int namelen
= strlen(path
);
4289 ce
= make_empty_cache_entry(state
->repo
->index
, namelen
);
4290 memcpy(ce
->name
, path
, namelen
);
4291 ce
->ce_mode
= create_ce_mode(mode
);
4292 ce
->ce_flags
= create_ce_flags(0);
4293 ce
->ce_namelen
= namelen
;
4294 if (state
->ita_only
) {
4295 ce
->ce_flags
|= CE_INTENT_TO_ADD
;
4296 set_object_name_for_intent_to_add_entry(ce
);
4297 } else if (S_ISGITLINK(mode
)) {
4300 if (!skip_prefix(buf
, "Subproject commit ", &s
) ||
4301 get_oid_hex(s
, &ce
->oid
)) {
4302 discard_cache_entry(ce
);
4303 return error(_("corrupt patch for submodule %s"), path
);
4306 if (!state
->cached
) {
4307 if (lstat(path
, &st
) < 0) {
4308 discard_cache_entry(ce
);
4309 return error_errno(_("unable to stat newly "
4310 "created file '%s'"),
4313 fill_stat_cache_info(ce
, &st
);
4315 if (write_object_file(buf
, size
, blob_type
, &ce
->oid
) < 0) {
4316 discard_cache_entry(ce
);
4317 return error(_("unable to create backing store "
4318 "for newly created file %s"), path
);
4321 if (add_index_entry(state
->repo
->index
, ce
, ADD_CACHE_OK_TO_ADD
) < 0) {
4322 discard_cache_entry(ce
);
4323 return error(_("unable to add cache entry for %s"), path
);
4331 * -1 if an unrecoverable error happened
4332 * 0 if everything went well
4333 * 1 if a recoverable error happened
4335 static int try_create_file(struct apply_state
*state
, const char *path
,
4336 unsigned int mode
, const char *buf
,
4340 struct strbuf nbuf
= STRBUF_INIT
;
4342 if (S_ISGITLINK(mode
)) {
4344 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
))
4346 return !!mkdir(path
, 0777);
4349 if (has_symlinks
&& S_ISLNK(mode
))
4350 /* Although buf:size is counted string, it also is NUL
4353 return !!symlink(buf
, path
);
4355 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
4359 if (convert_to_working_tree(state
->repo
->index
, path
, buf
, size
, &nbuf
)) {
4364 res
= write_in_full(fd
, buf
, size
) < 0;
4366 error_errno(_("failed to write to '%s'"), path
);
4367 strbuf_release(&nbuf
);
4369 if (close(fd
) < 0 && !res
)
4370 return error_errno(_("closing file '%s'"), path
);
4372 return res
? -1 : 0;
4376 * We optimistically assume that the directories exist,
4377 * which is true 99% of the time anyway. If they don't,
4378 * we create them and try again.
4384 static int create_one_file(struct apply_state
*state
,
4395 res
= try_create_file(state
, path
, mode
, buf
, size
);
4401 if (errno
== ENOENT
) {
4402 if (safe_create_leading_directories(path
))
4404 res
= try_create_file(state
, path
, mode
, buf
, size
);
4411 if (errno
== EEXIST
|| errno
== EACCES
) {
4412 /* We may be trying to create a file where a directory
4416 if (!lstat(path
, &st
) && (!S_ISDIR(st
.st_mode
) || !rmdir(path
)))
4420 if (errno
== EEXIST
) {
4421 unsigned int nr
= getpid();
4424 char newpath
[PATH_MAX
];
4425 mksnpath(newpath
, sizeof(newpath
), "%s~%u", path
, nr
);
4426 res
= try_create_file(state
, newpath
, mode
, buf
, size
);
4430 if (!rename(newpath
, path
))
4432 unlink_or_warn(newpath
);
4435 if (errno
!= EEXIST
)
4440 return error_errno(_("unable to write file '%s' mode %o"),
4444 static int add_conflicted_stages_file(struct apply_state
*state
,
4445 struct patch
*patch
)
4449 struct cache_entry
*ce
;
4451 if (!state
->update_index
)
4453 namelen
= strlen(patch
->new_name
);
4454 mode
= patch
->new_mode
? patch
->new_mode
: (S_IFREG
| 0644);
4456 remove_file_from_index(state
->repo
->index
, patch
->new_name
);
4457 for (stage
= 1; stage
< 4; stage
++) {
4458 if (is_null_oid(&patch
->threeway_stage
[stage
- 1]))
4460 ce
= make_empty_cache_entry(state
->repo
->index
, namelen
);
4461 memcpy(ce
->name
, patch
->new_name
, namelen
);
4462 ce
->ce_mode
= create_ce_mode(mode
);
4463 ce
->ce_flags
= create_ce_flags(stage
);
4464 ce
->ce_namelen
= namelen
;
4465 oidcpy(&ce
->oid
, &patch
->threeway_stage
[stage
- 1]);
4466 if (add_index_entry(state
->repo
->index
, ce
, ADD_CACHE_OK_TO_ADD
) < 0) {
4467 discard_cache_entry(ce
);
4468 return error(_("unable to add cache entry for %s"),
4476 static int create_file(struct apply_state
*state
, struct patch
*patch
)
4478 char *path
= patch
->new_name
;
4479 unsigned mode
= patch
->new_mode
;
4480 unsigned long size
= patch
->resultsize
;
4481 char *buf
= patch
->result
;
4484 mode
= S_IFREG
| 0644;
4485 if (create_one_file(state
, path
, mode
, buf
, size
))
4488 if (patch
->conflicted_threeway
)
4489 return add_conflicted_stages_file(state
, patch
);
4490 else if (state
->update_index
)
4491 return add_index_file(state
, path
, mode
, buf
, size
);
4495 /* phase zero is to remove, phase one is to create */
4496 static int write_out_one_result(struct apply_state
*state
,
4497 struct patch
*patch
,
4500 if (patch
->is_delete
> 0) {
4502 return remove_file(state
, patch
, 1);
4505 if (patch
->is_new
> 0 || patch
->is_copy
) {
4507 return create_file(state
, patch
);
4511 * Rename or modification boils down to the same
4512 * thing: remove the old, write the new
4515 return remove_file(state
, patch
, patch
->is_rename
);
4517 return create_file(state
, patch
);
4521 static int write_out_one_reject(struct apply_state
*state
, struct patch
*patch
)
4524 char namebuf
[PATH_MAX
];
4525 struct fragment
*frag
;
4527 struct strbuf sb
= STRBUF_INIT
;
4529 for (cnt
= 0, frag
= patch
->fragments
; frag
; frag
= frag
->next
) {
4530 if (!frag
->rejected
)
4536 if (state
->apply_verbosity
> verbosity_normal
)
4537 say_patch_name(stderr
,
4538 _("Applied patch %s cleanly."), patch
);
4542 /* This should not happen, because a removal patch that leaves
4543 * contents are marked "rejected" at the patch level.
4545 if (!patch
->new_name
)
4546 die(_("internal error"));
4548 /* Say this even without --verbose */
4549 strbuf_addf(&sb
, Q_("Applying patch %%s with %d reject...",
4550 "Applying patch %%s with %d rejects...",
4553 if (state
->apply_verbosity
> verbosity_silent
)
4554 say_patch_name(stderr
, sb
.buf
, patch
);
4555 strbuf_release(&sb
);
4557 cnt
= strlen(patch
->new_name
);
4558 if (ARRAY_SIZE(namebuf
) <= cnt
+ 5) {
4559 cnt
= ARRAY_SIZE(namebuf
) - 5;
4560 warning(_("truncating .rej filename to %.*s.rej"),
4561 cnt
- 1, patch
->new_name
);
4563 memcpy(namebuf
, patch
->new_name
, cnt
);
4564 memcpy(namebuf
+ cnt
, ".rej", 5);
4566 rej
= fopen(namebuf
, "w");
4568 return error_errno(_("cannot open %s"), namebuf
);
4570 /* Normal git tools never deal with .rej, so do not pretend
4571 * this is a git patch by saying --git or giving extended
4572 * headers. While at it, maybe please "kompare" that wants
4573 * the trailing TAB and some garbage at the end of line ;-).
4575 fprintf(rej
, "diff a/%s b/%s\t(rejected hunks)\n",
4576 patch
->new_name
, patch
->new_name
);
4577 for (cnt
= 1, frag
= patch
->fragments
;
4579 cnt
++, frag
= frag
->next
) {
4580 if (!frag
->rejected
) {
4581 if (state
->apply_verbosity
> verbosity_silent
)
4582 fprintf_ln(stderr
, _("Hunk #%d applied cleanly."), cnt
);
4585 if (state
->apply_verbosity
> verbosity_silent
)
4586 fprintf_ln(stderr
, _("Rejected hunk #%d."), cnt
);
4587 fprintf(rej
, "%.*s", frag
->size
, frag
->patch
);
4588 if (frag
->patch
[frag
->size
-1] != '\n')
4597 * -1 if an error happened
4598 * 0 if the patch applied cleanly
4599 * 1 if the patch did not apply cleanly
4601 static int write_out_results(struct apply_state
*state
, struct patch
*list
)
4606 struct string_list cpath
= STRING_LIST_INIT_DUP
;
4608 for (phase
= 0; phase
< 2; phase
++) {
4614 if (write_out_one_result(state
, l
, phase
)) {
4615 string_list_clear(&cpath
, 0);
4619 if (write_out_one_reject(state
, l
))
4621 if (l
->conflicted_threeway
) {
4622 string_list_append(&cpath
, l
->new_name
);
4632 struct string_list_item
*item
;
4634 string_list_sort(&cpath
);
4635 if (state
->apply_verbosity
> verbosity_silent
) {
4636 for_each_string_list_item(item
, &cpath
)
4637 fprintf(stderr
, "U %s\n", item
->string
);
4639 string_list_clear(&cpath
, 0);
4641 repo_rerere(state
->repo
, 0);
4648 * Try to apply a patch.
4651 * -128 if a bad error happened (like patch unreadable)
4652 * -1 if patch did not apply and user cannot deal with it
4653 * 0 if the patch applied
4654 * 1 if the patch did not apply but user might fix it
4656 static int apply_patch(struct apply_state
*state
,
4658 const char *filename
,
4662 struct strbuf buf
= STRBUF_INIT
; /* owns the patch text */
4663 struct patch
*list
= NULL
, **listp
= &list
;
4664 int skipped_patch
= 0;
4667 state
->patch_input_file
= filename
;
4668 if (read_patch_file(&buf
, fd
) < 0)
4671 while (offset
< buf
.len
) {
4672 struct patch
*patch
;
4675 patch
= xcalloc(1, sizeof(*patch
));
4676 patch
->inaccurate_eof
= !!(options
& APPLY_OPT_INACCURATE_EOF
);
4677 patch
->recount
= !!(options
& APPLY_OPT_RECOUNT
);
4678 nr
= parse_chunk(state
, buf
.buf
+ offset
, buf
.len
- offset
, patch
);
4687 if (state
->apply_in_reverse
)
4688 reverse_patches(patch
);
4689 if (use_patch(state
, patch
)) {
4690 patch_stats(state
, patch
);
4692 listp
= &patch
->next
;
4695 if (state
->apply_verbosity
> verbosity_normal
)
4696 say_patch_name(stderr
, _("Skipped patch '%s'."), patch
);
4703 if (!list
&& !skipped_patch
) {
4704 error(_("unrecognized input"));
4709 if (state
->whitespace_error
&& (state
->ws_error_action
== die_on_ws_error
))
4712 state
->update_index
= (state
->check_index
|| state
->ita_only
) && state
->apply
;
4713 if (state
->update_index
&& !is_lock_file_locked(&state
->lock_file
)) {
4714 if (state
->index_file
)
4715 hold_lock_file_for_update(&state
->lock_file
,
4719 repo_hold_locked_index(state
->repo
, &state
->lock_file
,
4723 if (state
->check_index
&& read_apply_cache(state
) < 0) {
4724 error(_("unable to read index file"));
4729 if (state
->check
|| state
->apply
) {
4730 int r
= check_patch_list(state
, list
);
4735 if (r
< 0 && !state
->apply_with_reject
) {
4742 int write_res
= write_out_results(state
, list
);
4743 if (write_res
< 0) {
4747 if (write_res
> 0) {
4748 /* with --3way, we still need to write the index out */
4749 res
= state
->apply_with_reject
? -1 : 1;
4754 if (state
->fake_ancestor
&&
4755 build_fake_ancestor(state
, list
)) {
4760 if (state
->diffstat
&& state
->apply_verbosity
> verbosity_silent
)
4761 stat_patch_list(state
, list
);
4763 if (state
->numstat
&& state
->apply_verbosity
> verbosity_silent
)
4764 numstat_patch_list(state
, list
);
4766 if (state
->summary
&& state
->apply_verbosity
> verbosity_silent
)
4767 summary_patch_list(list
);
4770 free_patch_list(list
);
4771 strbuf_release(&buf
);
4772 string_list_clear(&state
->fn_table
, 0);
4776 static int apply_option_parse_exclude(const struct option
*opt
,
4777 const char *arg
, int unset
)
4779 struct apply_state
*state
= opt
->value
;
4781 BUG_ON_OPT_NEG(unset
);
4783 add_name_limit(state
, arg
, 1);
4787 static int apply_option_parse_include(const struct option
*opt
,
4788 const char *arg
, int unset
)
4790 struct apply_state
*state
= opt
->value
;
4792 BUG_ON_OPT_NEG(unset
);
4794 add_name_limit(state
, arg
, 0);
4795 state
->has_include
= 1;
4799 static int apply_option_parse_p(const struct option
*opt
,
4803 struct apply_state
*state
= opt
->value
;
4805 BUG_ON_OPT_NEG(unset
);
4807 state
->p_value
= atoi(arg
);
4808 state
->p_value_known
= 1;
4812 static int apply_option_parse_space_change(const struct option
*opt
,
4813 const char *arg
, int unset
)
4815 struct apply_state
*state
= opt
->value
;
4817 BUG_ON_OPT_ARG(arg
);
4820 state
->ws_ignore_action
= ignore_ws_none
;
4822 state
->ws_ignore_action
= ignore_ws_change
;
4826 static int apply_option_parse_whitespace(const struct option
*opt
,
4827 const char *arg
, int unset
)
4829 struct apply_state
*state
= opt
->value
;
4831 BUG_ON_OPT_NEG(unset
);
4833 state
->whitespace_option
= arg
;
4834 if (parse_whitespace_option(state
, arg
))
4839 static int apply_option_parse_directory(const struct option
*opt
,
4840 const char *arg
, int unset
)
4842 struct apply_state
*state
= opt
->value
;
4844 BUG_ON_OPT_NEG(unset
);
4846 strbuf_reset(&state
->root
);
4847 strbuf_addstr(&state
->root
, arg
);
4848 strbuf_complete(&state
->root
, '/');
4852 int apply_all_patches(struct apply_state
*state
,
4862 for (i
= 0; i
< argc
; i
++) {
4863 const char *arg
= argv
[i
];
4864 char *to_free
= NULL
;
4867 if (!strcmp(arg
, "-")) {
4868 res
= apply_patch(state
, 0, "<stdin>", options
);
4875 arg
= to_free
= prefix_filename(state
->prefix
, arg
);
4877 fd
= open(arg
, O_RDONLY
);
4879 error(_("can't open patch '%s': %s"), arg
, strerror(errno
));
4885 set_default_whitespace_mode(state
);
4886 res
= apply_patch(state
, fd
, arg
, options
);
4893 set_default_whitespace_mode(state
);
4895 res
= apply_patch(state
, 0, "<stdin>", options
);
4901 if (state
->whitespace_error
) {
4902 if (state
->squelch_whitespace_errors
&&
4903 state
->squelch_whitespace_errors
< state
->whitespace_error
) {
4905 state
->whitespace_error
- state
->squelch_whitespace_errors
;
4906 warning(Q_("squelched %d whitespace error",
4907 "squelched %d whitespace errors",
4911 if (state
->ws_error_action
== die_on_ws_error
) {
4912 error(Q_("%d line adds whitespace errors.",
4913 "%d lines add whitespace errors.",
4914 state
->whitespace_error
),
4915 state
->whitespace_error
);
4919 if (state
->applied_after_fixing_ws
&& state
->apply
)
4920 warning(Q_("%d line applied after"
4921 " fixing whitespace errors.",
4922 "%d lines applied after"
4923 " fixing whitespace errors.",
4924 state
->applied_after_fixing_ws
),
4925 state
->applied_after_fixing_ws
);
4926 else if (state
->whitespace_error
)
4927 warning(Q_("%d line adds whitespace errors.",
4928 "%d lines add whitespace errors.",
4929 state
->whitespace_error
),
4930 state
->whitespace_error
);
4933 if (state
->update_index
) {
4934 res
= write_locked_index(state
->repo
->index
, &state
->lock_file
, COMMIT_LOCK
);
4936 error(_("Unable to write new index file"));
4945 rollback_lock_file(&state
->lock_file
);
4947 if (state
->apply_verbosity
<= verbosity_silent
) {
4948 set_error_routine(state
->saved_error_routine
);
4949 set_warn_routine(state
->saved_warn_routine
);
4954 return (res
== -1 ? 1 : 128);
4957 int apply_parse_options(int argc
, const char **argv
,
4958 struct apply_state
*state
,
4959 int *force_apply
, int *options
,
4960 const char * const *apply_usage
)
4962 struct option builtin_apply_options
[] = {
4963 { OPTION_CALLBACK
, 0, "exclude", state
, N_("path"),
4964 N_("don't apply changes matching the given path"),
4965 PARSE_OPT_NONEG
, apply_option_parse_exclude
},
4966 { OPTION_CALLBACK
, 0, "include", state
, N_("path"),
4967 N_("apply changes matching the given path"),
4968 PARSE_OPT_NONEG
, apply_option_parse_include
},
4969 { OPTION_CALLBACK
, 'p', NULL
, state
, N_("num"),
4970 N_("remove <num> leading slashes from traditional diff paths"),
4971 0, apply_option_parse_p
},
4972 OPT_BOOL(0, "no-add", &state
->no_add
,
4973 N_("ignore additions made by the patch")),
4974 OPT_BOOL(0, "stat", &state
->diffstat
,
4975 N_("instead of applying the patch, output diffstat for the input")),
4976 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
4977 OPT_NOOP_NOARG(0, "binary"),
4978 OPT_BOOL(0, "numstat", &state
->numstat
,
4979 N_("show number of added and deleted lines in decimal notation")),
4980 OPT_BOOL(0, "summary", &state
->summary
,
4981 N_("instead of applying the patch, output a summary for the input")),
4982 OPT_BOOL(0, "check", &state
->check
,
4983 N_("instead of applying the patch, see if the patch is applicable")),
4984 OPT_BOOL(0, "index", &state
->check_index
,
4985 N_("make sure the patch is applicable to the current index")),
4986 OPT_BOOL('N', "intent-to-add", &state
->ita_only
,
4987 N_("mark new files with `git add --intent-to-add`")),
4988 OPT_BOOL(0, "cached", &state
->cached
,
4989 N_("apply a patch without touching the working tree")),
4990 OPT_BOOL_F(0, "unsafe-paths", &state
->unsafe_paths
,
4991 N_("accept a patch that touches outside the working area"),
4992 PARSE_OPT_NOCOMPLETE
),
4993 OPT_BOOL(0, "apply", force_apply
,
4994 N_("also apply the patch (use with --stat/--summary/--check)")),
4995 OPT_BOOL('3', "3way", &state
->threeway
,
4996 N_( "attempt three-way merge if a patch does not apply")),
4997 OPT_FILENAME(0, "build-fake-ancestor", &state
->fake_ancestor
,
4998 N_("build a temporary index based on embedded index information")),
4999 /* Think twice before adding "--nul" synonym to this */
5000 OPT_SET_INT('z', NULL
, &state
->line_termination
,
5001 N_("paths are separated with NUL character"), '\0'),
5002 OPT_INTEGER('C', NULL
, &state
->p_context
,
5003 N_("ensure at least <n> lines of context match")),
5004 { OPTION_CALLBACK
, 0, "whitespace", state
, N_("action"),
5005 N_("detect new or modified lines that have whitespace errors"),
5006 0, apply_option_parse_whitespace
},
5007 { OPTION_CALLBACK
, 0, "ignore-space-change", state
, NULL
,
5008 N_("ignore changes in whitespace when finding context"),
5009 PARSE_OPT_NOARG
, apply_option_parse_space_change
},
5010 { OPTION_CALLBACK
, 0, "ignore-whitespace", state
, NULL
,
5011 N_("ignore changes in whitespace when finding context"),
5012 PARSE_OPT_NOARG
, apply_option_parse_space_change
},
5013 OPT_BOOL('R', "reverse", &state
->apply_in_reverse
,
5014 N_("apply the patch in reverse")),
5015 OPT_BOOL(0, "unidiff-zero", &state
->unidiff_zero
,
5016 N_("don't expect at least one line of context")),
5017 OPT_BOOL(0, "reject", &state
->apply_with_reject
,
5018 N_("leave the rejected hunks in corresponding *.rej files")),
5019 OPT_BOOL(0, "allow-overlap", &state
->allow_overlap
,
5020 N_("allow overlapping hunks")),
5021 OPT__VERBOSE(&state
->apply_verbosity
, N_("be verbose")),
5022 OPT_BIT(0, "inaccurate-eof", options
,
5023 N_("tolerate incorrectly detected missing new-line at the end of file"),
5024 APPLY_OPT_INACCURATE_EOF
),
5025 OPT_BIT(0, "recount", options
,
5026 N_("do not trust the line counts in the hunk headers"),
5028 { OPTION_CALLBACK
, 0, "directory", state
, N_("root"),
5029 N_("prepend <root> to all filenames"),
5030 0, apply_option_parse_directory
},
5034 return parse_options(argc
, argv
, state
->prefix
, builtin_apply_options
, apply_usage
, 0);