4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
13 #include "object-store.h"
19 #include "xdiff-interface.h"
22 #include "parse-options.h"
34 static void git_apply_config(void)
36 git_config_get_string("apply.whitespace", &apply_default_whitespace
);
37 git_config_get_string("apply.ignorewhitespace", &apply_default_ignorewhitespace
);
38 git_config(git_xmerge_config
, NULL
);
41 static int parse_whitespace_option(struct apply_state
*state
, const char *option
)
44 state
->ws_error_action
= warn_on_ws_error
;
47 if (!strcmp(option
, "warn")) {
48 state
->ws_error_action
= warn_on_ws_error
;
51 if (!strcmp(option
, "nowarn")) {
52 state
->ws_error_action
= nowarn_ws_error
;
55 if (!strcmp(option
, "error")) {
56 state
->ws_error_action
= die_on_ws_error
;
59 if (!strcmp(option
, "error-all")) {
60 state
->ws_error_action
= die_on_ws_error
;
61 state
->squelch_whitespace_errors
= 0;
64 if (!strcmp(option
, "strip") || !strcmp(option
, "fix")) {
65 state
->ws_error_action
= correct_ws_error
;
69 * Please update $__git_whitespacelist in git-completion.bash
70 * when you add new options.
72 return error(_("unrecognized whitespace option '%s'"), option
);
75 static int parse_ignorewhitespace_option(struct apply_state
*state
,
78 if (!option
|| !strcmp(option
, "no") ||
79 !strcmp(option
, "false") || !strcmp(option
, "never") ||
80 !strcmp(option
, "none")) {
81 state
->ws_ignore_action
= ignore_ws_none
;
84 if (!strcmp(option
, "change")) {
85 state
->ws_ignore_action
= ignore_ws_change
;
88 return error(_("unrecognized whitespace ignore option '%s'"), option
);
91 int init_apply_state(struct apply_state
*state
,
92 struct repository
*repo
,
95 memset(state
, 0, sizeof(*state
));
96 state
->prefix
= prefix
;
99 state
->line_termination
= '\n';
101 state
->p_context
= UINT_MAX
;
102 state
->squelch_whitespace_errors
= 5;
103 state
->ws_error_action
= warn_on_ws_error
;
104 state
->ws_ignore_action
= ignore_ws_none
;
106 string_list_init_nodup(&state
->fn_table
);
107 string_list_init_nodup(&state
->limit_by_name
);
108 strset_init(&state
->removed_symlinks
);
109 strset_init(&state
->kept_symlinks
);
110 strbuf_init(&state
->root
, 0);
113 if (apply_default_whitespace
&& parse_whitespace_option(state
, apply_default_whitespace
))
115 if (apply_default_ignorewhitespace
&& parse_ignorewhitespace_option(state
, apply_default_ignorewhitespace
))
120 void clear_apply_state(struct apply_state
*state
)
122 string_list_clear(&state
->limit_by_name
, 0);
123 strset_clear(&state
->removed_symlinks
);
124 strset_clear(&state
->kept_symlinks
);
125 strbuf_release(&state
->root
);
127 /* &state->fn_table is cleared at the end of apply_patch() */
130 static void mute_routine(const char *msg UNUSED
, va_list params UNUSED
)
135 int check_apply_state(struct apply_state
*state
, int force_apply
)
137 int is_not_gitdir
= !startup_info
->have_repository
;
139 if (state
->apply_with_reject
&& state
->threeway
)
140 return error(_("options '%s' and '%s' cannot be used together"), "--reject", "--3way");
141 if (state
->threeway
) {
143 return error(_("'%s' outside a repository"), "--3way");
144 state
->check_index
= 1;
146 if (state
->apply_with_reject
) {
148 if (state
->apply_verbosity
== verbosity_normal
)
149 state
->apply_verbosity
= verbosity_verbose
;
151 if (!force_apply
&& (state
->diffstat
|| state
->numstat
|| state
->summary
|| state
->check
|| state
->fake_ancestor
))
153 if (state
->check_index
&& is_not_gitdir
)
154 return error(_("'%s' outside a repository"), "--index");
157 return error(_("'%s' outside a repository"), "--cached");
158 state
->check_index
= 1;
160 if (state
->ita_only
&& (state
->check_index
|| is_not_gitdir
))
162 if (state
->check_index
)
163 state
->unsafe_paths
= 0;
165 if (state
->apply_verbosity
<= verbosity_silent
) {
166 state
->saved_error_routine
= get_error_routine();
167 state
->saved_warn_routine
= get_warn_routine();
168 set_error_routine(mute_routine
);
169 set_warn_routine(mute_routine
);
175 static void set_default_whitespace_mode(struct apply_state
*state
)
177 if (!state
->whitespace_option
&& !apply_default_whitespace
)
178 state
->ws_error_action
= (state
->apply
? warn_on_ws_error
: nowarn_ws_error
);
182 * This represents one "hunk" from a patch, starting with
183 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
184 * patch text is pointed at by patch, and its byte length
185 * is stored in size. leading and trailing are the number
189 unsigned long leading
, trailing
;
190 unsigned long oldpos
, oldlines
;
191 unsigned long newpos
, newlines
;
193 * 'patch' is usually borrowed from buf in apply_patch(),
194 * but some codepaths store an allocated buffer.
197 unsigned free_patch
:1,
201 struct fragment
*next
;
205 * When dealing with a binary patch, we reuse "leading" field
206 * to store the type of the binary hunk, either deflated "delta"
207 * or deflated "literal".
209 #define binary_patch_method leading
210 #define BINARY_DELTA_DEFLATED 1
211 #define BINARY_LITERAL_DEFLATED 2
213 static void free_fragment_list(struct fragment
*list
)
216 struct fragment
*next
= list
->next
;
217 if (list
->free_patch
)
218 free((char *)list
->patch
);
224 void release_patch(struct patch
*patch
)
226 free_fragment_list(patch
->fragments
);
227 free(patch
->def_name
);
228 free(patch
->old_name
);
229 free(patch
->new_name
);
233 static void free_patch(struct patch
*patch
)
235 release_patch(patch
);
239 static void free_patch_list(struct patch
*list
)
242 struct patch
*next
= list
->next
;
249 * A line in a file, len-bytes long (includes the terminating LF,
250 * except for an incomplete line at the end if the file ends with
251 * one), and its contents hashes to 'hash'.
257 #define LINE_COMMON 1
258 #define LINE_PATCHED 2
262 * This represents a "file", which is an array of "lines".
269 struct line
*line_allocated
;
273 static uint32_t hash_line(const char *cp
, size_t len
)
277 for (i
= 0, h
= 0; i
< len
; i
++) {
278 if (!isspace(cp
[i
])) {
279 h
= h
* 3 + (cp
[i
] & 0xff);
286 * Compare lines s1 of length n1 and s2 of length n2, ignoring
287 * whitespace difference. Returns 1 if they match, 0 otherwise
289 static int fuzzy_matchlines(const char *s1
, size_t n1
,
290 const char *s2
, size_t n2
)
292 const char *end1
= s1
+ n1
;
293 const char *end2
= s2
+ n2
;
295 /* ignore line endings */
296 while (s1
< end1
&& (end1
[-1] == '\r' || end1
[-1] == '\n'))
298 while (s2
< end2
&& (end2
[-1] == '\r' || end2
[-1] == '\n'))
301 while (s1
< end1
&& s2
< end2
) {
304 * Skip whitespace. We check on both buffers
305 * because we don't want "a b" to match "ab".
309 while (s1
< end1
&& isspace(*s1
))
311 while (s2
< end2
&& isspace(*s2
))
313 } else if (*s1
++ != *s2
++)
317 /* If we reached the end on one side only, lines don't match. */
318 return s1
== end1
&& s2
== end2
;
321 static void add_line_info(struct image
*img
, const char *bol
, size_t len
, unsigned flag
)
323 ALLOC_GROW(img
->line_allocated
, img
->nr
+ 1, img
->alloc
);
324 img
->line_allocated
[img
->nr
].len
= len
;
325 img
->line_allocated
[img
->nr
].hash
= hash_line(bol
, len
);
326 img
->line_allocated
[img
->nr
].flag
= flag
;
331 * "buf" has the file contents to be patched (read from various sources).
332 * attach it to "image" and add line-based index to it.
333 * "image" now owns the "buf".
335 static void prepare_image(struct image
*image
, char *buf
, size_t len
,
336 int prepare_linetable
)
340 memset(image
, 0, sizeof(*image
));
344 if (!prepare_linetable
)
347 ep
= image
->buf
+ image
->len
;
351 for (next
= cp
; next
< ep
&& *next
!= '\n'; next
++)
355 add_line_info(image
, cp
, next
- cp
, 0);
358 image
->line
= image
->line_allocated
;
361 static void clear_image(struct image
*image
)
364 free(image
->line_allocated
);
365 memset(image
, 0, sizeof(*image
));
368 /* fmt must contain _one_ %s and no other substitution */
369 static void say_patch_name(FILE *output
, const char *fmt
, struct patch
*patch
)
371 struct strbuf sb
= STRBUF_INIT
;
373 if (patch
->old_name
&& patch
->new_name
&&
374 strcmp(patch
->old_name
, patch
->new_name
)) {
375 quote_c_style(patch
->old_name
, &sb
, NULL
, 0);
376 strbuf_addstr(&sb
, " => ");
377 quote_c_style(patch
->new_name
, &sb
, NULL
, 0);
379 const char *n
= patch
->new_name
;
382 quote_c_style(n
, &sb
, NULL
, 0);
384 fprintf(output
, fmt
, sb
.buf
);
392 * apply.c isn't equipped to handle arbitrarily large patches, because
393 * it intermingles `unsigned long` with `int` for the type used to store
396 * Only process patches that are just shy of 1 GiB large in order to
397 * avoid any truncation or overflow issues.
399 #define MAX_APPLY_SIZE (1024UL * 1024 * 1023)
401 static int read_patch_file(struct strbuf
*sb
, int fd
)
403 if (strbuf_read(sb
, fd
, 0) < 0 || sb
->len
>= MAX_APPLY_SIZE
)
404 return error_errno("git apply: failed to read");
407 * Make sure that we have some slop in the buffer
408 * so that we can do speculative "memcmp" etc, and
409 * see to it that it is NUL-filled.
411 strbuf_grow(sb
, SLOP
);
412 memset(sb
->buf
+ sb
->len
, 0, SLOP
);
416 static unsigned long linelen(const char *buffer
, unsigned long size
)
418 unsigned long len
= 0;
421 if (*buffer
++ == '\n')
427 static int is_dev_null(const char *str
)
429 return skip_prefix(str
, "/dev/null", &str
) && isspace(*str
);
435 static int name_terminate(int c
, int terminate
)
437 if (c
== ' ' && !(terminate
& TERM_SPACE
))
439 if (c
== '\t' && !(terminate
& TERM_TAB
))
445 /* remove double slashes to make --index work with such filenames */
446 static char *squash_slash(char *name
)
454 if ((name
[j
++] = name
[i
++]) == '/')
455 while (name
[i
] == '/')
462 static char *find_name_gnu(struct strbuf
*root
,
466 struct strbuf name
= STRBUF_INIT
;
470 * Proposed "new-style" GNU patch/diff format; see
471 * https://lore.kernel.org/git/7vll0wvb2a.fsf@assigned-by-dhcp.cox.net/
473 if (unquote_c_style(&name
, line
, NULL
)) {
474 strbuf_release(&name
);
478 for (cp
= name
.buf
; p_value
; p_value
--) {
479 cp
= strchr(cp
, '/');
481 strbuf_release(&name
);
487 strbuf_remove(&name
, 0, cp
- name
.buf
);
489 strbuf_insert(&name
, 0, root
->buf
, root
->len
);
490 return squash_slash(strbuf_detach(&name
, NULL
));
493 static size_t sane_tz_len(const char *line
, size_t len
)
497 if (len
< strlen(" +0500") || line
[len
-strlen(" +0500")] != ' ')
499 tz
= line
+ len
- strlen(" +0500");
501 if (tz
[1] != '+' && tz
[1] != '-')
504 for (p
= tz
+ 2; p
!= line
+ len
; p
++)
508 return line
+ len
- tz
;
511 static size_t tz_with_colon_len(const char *line
, size_t len
)
515 if (len
< strlen(" +08:00") || line
[len
- strlen(":00")] != ':')
517 tz
= line
+ len
- strlen(" +08:00");
519 if (tz
[0] != ' ' || (tz
[1] != '+' && tz
[1] != '-'))
522 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
523 !isdigit(*p
++) || !isdigit(*p
++))
526 return line
+ len
- tz
;
529 static size_t date_len(const char *line
, size_t len
)
531 const char *date
, *p
;
533 if (len
< strlen("72-02-05") || line
[len
-strlen("-05")] != '-')
535 p
= date
= line
+ len
- strlen("72-02-05");
537 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
538 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
539 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a date. */
542 if (date
- line
>= strlen("19") &&
543 isdigit(date
[-1]) && isdigit(date
[-2])) /* 4-digit year */
544 date
-= strlen("19");
546 return line
+ len
- date
;
549 static size_t short_time_len(const char *line
, size_t len
)
551 const char *time
, *p
;
553 if (len
< strlen(" 07:01:32") || line
[len
-strlen(":32")] != ':')
555 p
= time
= line
+ len
- strlen(" 07:01:32");
557 /* Permit 1-digit hours? */
559 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
560 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
561 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a time. */
564 return line
+ len
- time
;
567 static size_t fractional_time_len(const char *line
, size_t len
)
572 /* Expected format: 19:41:17.620000023 */
573 if (!len
|| !isdigit(line
[len
- 1]))
577 /* Fractional seconds. */
578 while (p
> line
&& isdigit(*p
))
583 /* Hours, minutes, and whole seconds. */
584 n
= short_time_len(line
, p
- line
);
588 return line
+ len
- p
+ n
;
591 static size_t trailing_spaces_len(const char *line
, size_t len
)
595 /* Expected format: ' ' x (1 or more) */
596 if (!len
|| line
[len
- 1] != ' ')
603 return line
+ len
- (p
+ 1);
610 static size_t diff_timestamp_len(const char *line
, size_t len
)
612 const char *end
= line
+ len
;
616 * Posix: 2010-07-05 19:41:17
617 * GNU: 2010-07-05 19:41:17.620000023 -0500
620 if (!isdigit(end
[-1]))
623 n
= sane_tz_len(line
, end
- line
);
625 n
= tz_with_colon_len(line
, end
- line
);
628 n
= short_time_len(line
, end
- line
);
630 n
= fractional_time_len(line
, end
- line
);
633 n
= date_len(line
, end
- line
);
634 if (!n
) /* No date. Too bad. */
638 if (end
== line
) /* No space before date. */
640 if (end
[-1] == '\t') { /* Success! */
642 return line
+ len
- end
;
644 if (end
[-1] != ' ') /* No space before date. */
647 /* Whitespace damage. */
648 end
-= trailing_spaces_len(line
, end
- line
);
649 return line
+ len
- end
;
652 static char *find_name_common(struct strbuf
*root
,
660 const char *start
= NULL
;
664 while (line
!= end
) {
667 if (!end
&& isspace(c
)) {
670 if (name_terminate(c
, terminate
))
674 if (c
== '/' && !--p_value
)
678 return squash_slash(xstrdup_or_null(def
));
681 return squash_slash(xstrdup_or_null(def
));
684 * Generally we prefer the shorter name, especially
685 * if the other one is just a variation of that with
686 * something else tacked on to the end (ie "file.orig"
690 int deflen
= strlen(def
);
691 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
692 return squash_slash(xstrdup(def
));
696 char *ret
= xstrfmt("%s%.*s", root
->buf
, len
, start
);
697 return squash_slash(ret
);
700 return squash_slash(xmemdupz(start
, len
));
703 static char *find_name(struct strbuf
*root
,
710 char *name
= find_name_gnu(root
, line
, p_value
);
715 return find_name_common(root
, line
, def
, p_value
, NULL
, terminate
);
718 static char *find_name_traditional(struct strbuf
*root
,
727 char *name
= find_name_gnu(root
, line
, p_value
);
732 len
= strchrnul(line
, '\n') - line
;
733 date_len
= diff_timestamp_len(line
, len
);
735 return find_name_common(root
, line
, def
, p_value
, NULL
, TERM_TAB
);
738 return find_name_common(root
, line
, def
, p_value
, line
+ len
, 0);
742 * Given the string after "--- " or "+++ ", guess the appropriate
743 * p_value for the given patch.
745 static int guess_p_value(struct apply_state
*state
, const char *nameline
)
750 if (is_dev_null(nameline
))
752 name
= find_name_traditional(&state
->root
, nameline
, NULL
, 0);
755 cp
= strchr(name
, '/');
758 else if (state
->prefix
) {
760 * Does it begin with "a/$our-prefix" and such? Then this is
761 * very likely to apply to our directory.
763 if (starts_with(name
, state
->prefix
))
764 val
= count_slashes(state
->prefix
);
767 if (starts_with(cp
, state
->prefix
))
768 val
= count_slashes(state
->prefix
) + 1;
776 * Does the ---/+++ line have the POSIX timestamp after the last HT?
777 * GNU diff puts epoch there to signal a creation/deletion event. Is
778 * this such a timestamp?
780 static int has_epoch_timestamp(const char *nameline
)
783 * We are only interested in epoch timestamp; any non-zero
784 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
785 * For the same reason, the date must be either 1969-12-31 or
786 * 1970-01-01, and the seconds part must be "00".
788 const char stamp_regexp
[] =
789 "^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?"
791 "([-+][0-2][0-9]:?[0-5][0-9])\n";
792 const char *timestamp
= NULL
, *cp
, *colon
;
793 static regex_t
*stamp
;
795 int zoneoffset
, epoch_hour
, hour
, minute
;
798 for (cp
= nameline
; *cp
!= '\n'; cp
++) {
806 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
807 * (west of GMT) or 1970-01-01 (east of GMT)
809 if (skip_prefix(timestamp
, "1969-12-31 ", ×tamp
))
811 else if (skip_prefix(timestamp
, "1970-01-01 ", ×tamp
))
817 stamp
= xmalloc(sizeof(*stamp
));
818 if (regcomp(stamp
, stamp_regexp
, REG_EXTENDED
)) {
819 warning(_("Cannot prepare timestamp regexp %s"),
825 status
= regexec(stamp
, timestamp
, ARRAY_SIZE(m
), m
, 0);
827 if (status
!= REG_NOMATCH
)
828 warning(_("regexec returned %d for input: %s"),
833 hour
= strtol(timestamp
, NULL
, 10);
834 minute
= strtol(timestamp
+ m
[1].rm_so
, NULL
, 10);
836 zoneoffset
= strtol(timestamp
+ m
[3].rm_so
+ 1, (char **) &colon
, 10);
838 zoneoffset
= zoneoffset
* 60 + strtol(colon
+ 1, NULL
, 10);
840 zoneoffset
= (zoneoffset
/ 100) * 60 + (zoneoffset
% 100);
841 if (timestamp
[m
[3].rm_so
] == '-')
842 zoneoffset
= -zoneoffset
;
844 return hour
* 60 + minute
- zoneoffset
== epoch_hour
* 60;
848 * Get the name etc info from the ---/+++ lines of a traditional patch header
850 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
851 * files, we can happily check the index for a match, but for creating a
852 * new file we should try to match whatever "patch" does. I have no idea.
854 static int parse_traditional_patch(struct apply_state
*state
,
861 first
+= 4; /* skip "--- " */
862 second
+= 4; /* skip "+++ " */
863 if (!state
->p_value_known
) {
865 p
= guess_p_value(state
, first
);
866 q
= guess_p_value(state
, second
);
868 if (0 <= p
&& p
== q
) {
870 state
->p_value_known
= 1;
873 if (is_dev_null(first
)) {
875 patch
->is_delete
= 0;
876 name
= find_name_traditional(&state
->root
, second
, NULL
, state
->p_value
);
877 patch
->new_name
= name
;
878 } else if (is_dev_null(second
)) {
880 patch
->is_delete
= 1;
881 name
= find_name_traditional(&state
->root
, first
, NULL
, state
->p_value
);
882 patch
->old_name
= name
;
885 first_name
= find_name_traditional(&state
->root
, first
, NULL
, state
->p_value
);
886 name
= find_name_traditional(&state
->root
, second
, first_name
, state
->p_value
);
888 if (has_epoch_timestamp(first
)) {
890 patch
->is_delete
= 0;
891 patch
->new_name
= name
;
892 } else if (has_epoch_timestamp(second
)) {
894 patch
->is_delete
= 1;
895 patch
->old_name
= name
;
897 patch
->old_name
= name
;
898 patch
->new_name
= xstrdup_or_null(name
);
902 return error(_("unable to find filename in patch at line %d"), state
->linenr
);
907 static int gitdiff_hdrend(struct gitdiff_data
*state UNUSED
,
908 const char *line UNUSED
,
909 struct patch
*patch UNUSED
)
915 * We're anal about diff header consistency, to make
916 * sure that we don't end up having strange ambiguous
917 * patches floating around.
919 * As a result, gitdiff_{old|new}name() will check
920 * their names against any previous information, just
923 #define DIFF_OLD_NAME 0
924 #define DIFF_NEW_NAME 1
926 static int gitdiff_verify_name(struct gitdiff_data
*state
,
932 if (!*name
&& !isnull
) {
933 *name
= find_name(state
->root
, line
, NULL
, state
->p_value
, TERM_TAB
);
940 return error(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
941 *name
, state
->linenr
);
942 another
= find_name(state
->root
, line
, NULL
, state
->p_value
, TERM_TAB
);
943 if (!another
|| strcmp(another
, *name
)) {
945 return error((side
== DIFF_NEW_NAME
) ?
946 _("git apply: bad git-diff - inconsistent new filename on line %d") :
947 _("git apply: bad git-diff - inconsistent old filename on line %d"), state
->linenr
);
951 if (!is_dev_null(line
))
952 return error(_("git apply: bad git-diff - expected /dev/null on line %d"), state
->linenr
);
958 static int gitdiff_oldname(struct gitdiff_data
*state
,
962 return gitdiff_verify_name(state
, line
,
963 patch
->is_new
, &patch
->old_name
,
967 static int gitdiff_newname(struct gitdiff_data
*state
,
971 return gitdiff_verify_name(state
, line
,
972 patch
->is_delete
, &patch
->new_name
,
976 static int parse_mode_line(const char *line
, int linenr
, unsigned int *mode
)
979 *mode
= strtoul(line
, &end
, 8);
980 if (end
== line
|| !isspace(*end
))
981 return error(_("invalid mode on line %d: %s"), linenr
, line
);
985 static int gitdiff_oldmode(struct gitdiff_data
*state
,
989 return parse_mode_line(line
, state
->linenr
, &patch
->old_mode
);
992 static int gitdiff_newmode(struct gitdiff_data
*state
,
996 return parse_mode_line(line
, state
->linenr
, &patch
->new_mode
);
999 static int gitdiff_delete(struct gitdiff_data
*state
,
1001 struct patch
*patch
)
1003 patch
->is_delete
= 1;
1004 free(patch
->old_name
);
1005 patch
->old_name
= xstrdup_or_null(patch
->def_name
);
1006 return gitdiff_oldmode(state
, line
, patch
);
1009 static int gitdiff_newfile(struct gitdiff_data
*state
,
1011 struct patch
*patch
)
1014 free(patch
->new_name
);
1015 patch
->new_name
= xstrdup_or_null(patch
->def_name
);
1016 return gitdiff_newmode(state
, line
, patch
);
1019 static int gitdiff_copysrc(struct gitdiff_data
*state
,
1021 struct patch
*patch
)
1024 free(patch
->old_name
);
1025 patch
->old_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1029 static int gitdiff_copydst(struct gitdiff_data
*state
,
1031 struct patch
*patch
)
1034 free(patch
->new_name
);
1035 patch
->new_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1039 static int gitdiff_renamesrc(struct gitdiff_data
*state
,
1041 struct patch
*patch
)
1043 patch
->is_rename
= 1;
1044 free(patch
->old_name
);
1045 patch
->old_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1049 static int gitdiff_renamedst(struct gitdiff_data
*state
,
1051 struct patch
*patch
)
1053 patch
->is_rename
= 1;
1054 free(patch
->new_name
);
1055 patch
->new_name
= find_name(state
->root
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1059 static int gitdiff_similarity(struct gitdiff_data
*state UNUSED
,
1061 struct patch
*patch
)
1063 unsigned long val
= strtoul(line
, NULL
, 10);
1069 static int gitdiff_dissimilarity(struct gitdiff_data
*state UNUSED
,
1071 struct patch
*patch
)
1073 unsigned long val
= strtoul(line
, NULL
, 10);
1079 static int gitdiff_index(struct gitdiff_data
*state
,
1081 struct patch
*patch
)
1084 * index line is N hexadecimal, "..", N hexadecimal,
1085 * and optional space with octal mode.
1087 const char *ptr
, *eol
;
1089 const unsigned hexsz
= the_hash_algo
->hexsz
;
1091 ptr
= strchr(line
, '.');
1092 if (!ptr
|| ptr
[1] != '.' || hexsz
< ptr
- line
)
1095 memcpy(patch
->old_oid_prefix
, line
, len
);
1096 patch
->old_oid_prefix
[len
] = 0;
1099 ptr
= strchr(line
, ' ');
1100 eol
= strchrnul(line
, '\n');
1102 if (!ptr
|| eol
< ptr
)
1108 memcpy(patch
->new_oid_prefix
, line
, len
);
1109 patch
->new_oid_prefix
[len
] = 0;
1111 return gitdiff_oldmode(state
, ptr
+ 1, patch
);
1116 * This is normal for a diff that doesn't change anything: we'll fall through
1117 * into the next diff. Tell the parser to break out.
1119 static int gitdiff_unrecognized(struct gitdiff_data
*state UNUSED
,
1120 const char *line UNUSED
,
1121 struct patch
*patch UNUSED
)
1127 * Skip p_value leading components from "line"; as we do not accept
1128 * absolute paths, return NULL in that case.
1130 static const char *skip_tree_prefix(int p_value
,
1138 return (llen
&& line
[0] == '/') ? NULL
: line
;
1141 for (i
= 0; i
< llen
; i
++) {
1143 if (ch
== '/' && --nslash
<= 0)
1144 return (i
== 0) ? NULL
: &line
[i
+ 1];
1150 * This is to extract the same name that appears on "diff --git"
1151 * line. We do not find and return anything if it is a rename
1152 * patch, and it is OK because we will find the name elsewhere.
1153 * We need to reliably find name only when it is mode-change only,
1154 * creation or deletion of an empty file. In any of these cases,
1155 * both sides are the same name under a/ and b/ respectively.
1157 static char *git_header_name(int p_value
,
1162 const char *second
= NULL
;
1163 size_t len
, line_len
;
1165 line
+= strlen("diff --git ");
1166 llen
-= strlen("diff --git ");
1170 struct strbuf first
= STRBUF_INIT
;
1171 struct strbuf sp
= STRBUF_INIT
;
1173 if (unquote_c_style(&first
, line
, &second
))
1174 goto free_and_fail1
;
1176 /* strip the a/b prefix including trailing slash */
1177 cp
= skip_tree_prefix(p_value
, first
.buf
, first
.len
);
1179 goto free_and_fail1
;
1180 strbuf_remove(&first
, 0, cp
- first
.buf
);
1183 * second points at one past closing dq of name.
1184 * find the second name.
1186 while ((second
< line
+ llen
) && isspace(*second
))
1189 if (line
+ llen
<= second
)
1190 goto free_and_fail1
;
1191 if (*second
== '"') {
1192 if (unquote_c_style(&sp
, second
, NULL
))
1193 goto free_and_fail1
;
1194 cp
= skip_tree_prefix(p_value
, sp
.buf
, sp
.len
);
1196 goto free_and_fail1
;
1197 /* They must match, otherwise ignore */
1198 if (strcmp(cp
, first
.buf
))
1199 goto free_and_fail1
;
1200 strbuf_release(&sp
);
1201 return strbuf_detach(&first
, NULL
);
1204 /* unquoted second */
1205 cp
= skip_tree_prefix(p_value
, second
, line
+ llen
- second
);
1207 goto free_and_fail1
;
1208 if (line
+ llen
- cp
!= first
.len
||
1209 memcmp(first
.buf
, cp
, first
.len
))
1210 goto free_and_fail1
;
1211 return strbuf_detach(&first
, NULL
);
1214 strbuf_release(&first
);
1215 strbuf_release(&sp
);
1219 /* unquoted first name */
1220 name
= skip_tree_prefix(p_value
, line
, llen
);
1225 * since the first name is unquoted, a dq if exists must be
1226 * the beginning of the second name.
1228 for (second
= name
; second
< line
+ llen
; second
++) {
1229 if (*second
== '"') {
1230 struct strbuf sp
= STRBUF_INIT
;
1233 if (unquote_c_style(&sp
, second
, NULL
))
1234 goto free_and_fail2
;
1236 np
= skip_tree_prefix(p_value
, sp
.buf
, sp
.len
);
1238 goto free_and_fail2
;
1240 len
= sp
.buf
+ sp
.len
- np
;
1241 if (len
< second
- name
&&
1242 !strncmp(np
, name
, len
) &&
1243 isspace(name
[len
])) {
1245 strbuf_remove(&sp
, 0, np
- sp
.buf
);
1246 return strbuf_detach(&sp
, NULL
);
1250 strbuf_release(&sp
);
1256 * Accept a name only if it shows up twice, exactly the same
1259 second
= strchr(name
, '\n');
1262 line_len
= second
- name
;
1263 for (len
= 0 ; ; len
++) {
1264 switch (name
[len
]) {
1269 case '\t': case ' ':
1271 * Is this the separator between the preimage
1272 * and the postimage pathname? Again, we are
1273 * only interested in the case where there is
1274 * no rename, as this is only to set def_name
1275 * and a rename patch has the names elsewhere
1276 * in an unambiguous form.
1279 return NULL
; /* no postimage name */
1280 second
= skip_tree_prefix(p_value
, name
+ len
+ 1,
1281 line_len
- (len
+ 1));
1285 * Does len bytes starting at "name" and "second"
1286 * (that are separated by one HT or SP we just
1287 * found) exactly match?
1289 if (second
[len
] == '\n' && !strncmp(name
, second
, len
))
1290 return xmemdupz(name
, len
);
1295 static int check_header_line(int linenr
, struct patch
*patch
)
1297 int extensions
= (patch
->is_delete
== 1) + (patch
->is_new
== 1) +
1298 (patch
->is_rename
== 1) + (patch
->is_copy
== 1);
1300 return error(_("inconsistent header lines %d and %d"),
1301 patch
->extension_linenr
, linenr
);
1302 if (extensions
&& !patch
->extension_linenr
)
1303 patch
->extension_linenr
= linenr
;
1307 int parse_git_diff_header(struct strbuf
*root
,
1313 struct patch
*patch
)
1315 unsigned long offset
;
1316 struct gitdiff_data parse_hdr_state
;
1318 /* A git diff has explicit new/delete information, so we don't guess */
1320 patch
->is_delete
= 0;
1323 * Some things may not have the old name in the
1324 * rest of the headers anywhere (pure mode changes,
1325 * or removing or adding empty files), so we get
1326 * the default name from the header.
1328 patch
->def_name
= git_header_name(p_value
, line
, len
);
1329 if (patch
->def_name
&& root
->len
) {
1330 char *s
= xstrfmt("%s%s", root
->buf
, patch
->def_name
);
1331 free(patch
->def_name
);
1332 patch
->def_name
= s
;
1338 parse_hdr_state
.root
= root
;
1339 parse_hdr_state
.linenr
= *linenr
;
1340 parse_hdr_state
.p_value
= p_value
;
1342 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, (*linenr
)++) {
1343 static const struct opentry
{
1345 int (*fn
)(struct gitdiff_data
*, const char *, struct patch
*);
1347 { "@@ -", gitdiff_hdrend
},
1348 { "--- ", gitdiff_oldname
},
1349 { "+++ ", gitdiff_newname
},
1350 { "old mode ", gitdiff_oldmode
},
1351 { "new mode ", gitdiff_newmode
},
1352 { "deleted file mode ", gitdiff_delete
},
1353 { "new file mode ", gitdiff_newfile
},
1354 { "copy from ", gitdiff_copysrc
},
1355 { "copy to ", gitdiff_copydst
},
1356 { "rename old ", gitdiff_renamesrc
},
1357 { "rename new ", gitdiff_renamedst
},
1358 { "rename from ", gitdiff_renamesrc
},
1359 { "rename to ", gitdiff_renamedst
},
1360 { "similarity index ", gitdiff_similarity
},
1361 { "dissimilarity index ", gitdiff_dissimilarity
},
1362 { "index ", gitdiff_index
},
1363 { "", gitdiff_unrecognized
},
1367 len
= linelen(line
, size
);
1368 if (!len
|| line
[len
-1] != '\n')
1370 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
1371 const struct opentry
*p
= optable
+ i
;
1372 int oplen
= strlen(p
->str
);
1374 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
1376 res
= p
->fn(&parse_hdr_state
, line
+ oplen
, patch
);
1379 if (check_header_line(*linenr
, patch
))
1388 if (!patch
->old_name
&& !patch
->new_name
) {
1389 if (!patch
->def_name
) {
1390 error(Q_("git diff header lacks filename information when removing "
1391 "%d leading pathname component (line %d)",
1392 "git diff header lacks filename information when removing "
1393 "%d leading pathname components (line %d)",
1394 parse_hdr_state
.p_value
),
1395 parse_hdr_state
.p_value
, *linenr
);
1398 patch
->old_name
= xstrdup(patch
->def_name
);
1399 patch
->new_name
= xstrdup(patch
->def_name
);
1401 if ((!patch
->new_name
&& !patch
->is_delete
) ||
1402 (!patch
->old_name
&& !patch
->is_new
)) {
1403 error(_("git diff header lacks filename information "
1404 "(line %d)"), *linenr
);
1407 patch
->is_toplevel_relative
= 1;
1411 static int parse_num(const char *line
, unsigned long *p
)
1415 if (!isdigit(*line
))
1417 *p
= strtoul(line
, &ptr
, 10);
1421 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
1422 unsigned long *p1
, unsigned long *p2
)
1426 if (offset
< 0 || offset
>= len
)
1431 digits
= parse_num(line
, p1
);
1441 digits
= parse_num(line
+1, p2
);
1450 ex
= strlen(expect
);
1453 if (memcmp(line
, expect
, ex
))
1459 static void recount_diff(const char *line
, int size
, struct fragment
*fragment
)
1461 int oldlines
= 0, newlines
= 0, ret
= 0;
1464 warning("recount: ignore empty hunk");
1469 int len
= linelen(line
, size
);
1477 case ' ': case '\n':
1489 ret
= size
< 3 || !starts_with(line
, "@@ ");
1492 ret
= size
< 5 || !starts_with(line
, "diff ");
1499 warning(_("recount: unexpected line: %.*s"),
1500 (int)linelen(line
, size
), line
);
1505 fragment
->oldlines
= oldlines
;
1506 fragment
->newlines
= newlines
;
1510 * Parse a unified diff fragment header of the
1511 * form "@@ -a,b +c,d @@"
1513 static int parse_fragment_header(const char *line
, int len
, struct fragment
*fragment
)
1517 if (!len
|| line
[len
-1] != '\n')
1520 /* Figure out the number of lines in a fragment */
1521 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
1522 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
1528 * Find file diff header
1531 * -1 if no header was found
1532 * -128 in case of error
1533 * the size of the header in bytes (called "offset") otherwise
1535 static int find_header(struct apply_state
*state
,
1539 struct patch
*patch
)
1541 unsigned long offset
, len
;
1543 patch
->is_toplevel_relative
= 0;
1544 patch
->is_rename
= patch
->is_copy
= 0;
1545 patch
->is_new
= patch
->is_delete
= -1;
1546 patch
->old_mode
= patch
->new_mode
= 0;
1547 patch
->old_name
= patch
->new_name
= NULL
;
1548 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1549 unsigned long nextlen
;
1551 len
= linelen(line
, size
);
1555 /* Testing this early allows us to take a few shortcuts.. */
1560 * Make sure we don't find any unconnected patch fragments.
1561 * That's a sign that we didn't find a header, and that a
1562 * patch has become corrupted/broken up.
1564 if (!memcmp("@@ -", line
, 4)) {
1565 struct fragment dummy
;
1566 if (parse_fragment_header(line
, len
, &dummy
) < 0)
1568 error(_("patch fragment without header at line %d: %.*s"),
1569 state
->linenr
, (int)len
-1, line
);
1577 * Git patch? It might not have a real patch, just a rename
1578 * or mode change, so we handle that specially
1580 if (!memcmp("diff --git ", line
, 11)) {
1581 int git_hdr_len
= parse_git_diff_header(&state
->root
, &state
->linenr
,
1582 state
->p_value
, line
, len
,
1584 if (git_hdr_len
< 0)
1586 if (git_hdr_len
<= len
)
1588 *hdrsize
= git_hdr_len
;
1592 /* --- followed by +++ ? */
1593 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
1597 * We only accept unified patches, so we want it to
1598 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1599 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1601 nextlen
= linelen(line
+ len
, size
- len
);
1602 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
1605 /* Ok, we'll consider it a patch */
1606 if (parse_traditional_patch(state
, line
, line
+len
, patch
))
1608 *hdrsize
= len
+ nextlen
;
1615 static void record_ws_error(struct apply_state
*state
,
1626 state
->whitespace_error
++;
1627 if (state
->squelch_whitespace_errors
&&
1628 state
->squelch_whitespace_errors
< state
->whitespace_error
)
1631 err
= whitespace_error_string(result
);
1632 if (state
->apply_verbosity
> verbosity_silent
)
1633 fprintf(stderr
, "%s:%d: %s.\n%.*s\n",
1634 state
->patch_input_file
, linenr
, err
, len
, line
);
1638 static void check_whitespace(struct apply_state
*state
,
1643 unsigned result
= ws_check(line
+ 1, len
- 1, ws_rule
);
1645 record_ws_error(state
, result
, line
+ 1, len
- 2, state
->linenr
);
1649 * Check if the patch has context lines with CRLF or
1650 * the patch wants to remove lines with CRLF.
1652 static void check_old_for_crlf(struct patch
*patch
, const char *line
, int len
)
1654 if (len
>= 2 && line
[len
-1] == '\n' && line
[len
-2] == '\r') {
1655 patch
->ws_rule
|= WS_CR_AT_EOL
;
1656 patch
->crlf_in_old
= 1;
1662 * Parse a unified diff. Note that this really needs to parse each
1663 * fragment separately, since the only way to know the difference
1664 * between a "---" that is part of a patch, and a "---" that starts
1665 * the next patch is to look at the line counts..
1667 static int parse_fragment(struct apply_state
*state
,
1670 struct patch
*patch
,
1671 struct fragment
*fragment
)
1674 int len
= linelen(line
, size
), offset
;
1675 unsigned long oldlines
, newlines
;
1676 unsigned long leading
, trailing
;
1678 offset
= parse_fragment_header(line
, len
, fragment
);
1681 if (offset
> 0 && patch
->recount
)
1682 recount_diff(line
+ offset
, size
- offset
, fragment
);
1683 oldlines
= fragment
->oldlines
;
1684 newlines
= fragment
->newlines
;
1688 /* Parse the thing.. */
1692 added
= deleted
= 0;
1695 offset
+= len
, size
-= len
, line
+= len
, state
->linenr
++) {
1696 if (!oldlines
&& !newlines
)
1698 len
= linelen(line
, size
);
1699 if (!len
|| line
[len
-1] != '\n')
1704 case '\n': /* newer GNU diff, an empty context line */
1708 if (!deleted
&& !added
)
1711 check_old_for_crlf(patch
, line
, len
);
1712 if (!state
->apply_in_reverse
&&
1713 state
->ws_error_action
== correct_ws_error
)
1714 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1717 if (!state
->apply_in_reverse
)
1718 check_old_for_crlf(patch
, line
, len
);
1719 if (state
->apply_in_reverse
&&
1720 state
->ws_error_action
!= nowarn_ws_error
)
1721 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1727 if (state
->apply_in_reverse
)
1728 check_old_for_crlf(patch
, line
, len
);
1729 if (!state
->apply_in_reverse
&&
1730 state
->ws_error_action
!= nowarn_ws_error
)
1731 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1738 * We allow "\ No newline at end of file". Depending
1739 * on locale settings when the patch was produced we
1740 * don't know what this line looks like. The only
1741 * thing we do know is that it begins with "\ ".
1742 * Checking for 12 is just for sanity check -- any
1743 * l10n of "\ No newline..." is at least that long.
1746 if (len
< 12 || memcmp(line
, "\\ ", 2))
1751 if (oldlines
|| newlines
)
1753 if (!patch
->recount
&& !deleted
&& !added
)
1756 fragment
->leading
= leading
;
1757 fragment
->trailing
= trailing
;
1760 * If a fragment ends with an incomplete line, we failed to include
1761 * it in the above loop because we hit oldlines == newlines == 0
1764 if (12 < size
&& !memcmp(line
, "\\ ", 2))
1765 offset
+= linelen(line
, size
);
1767 patch
->lines_added
+= added
;
1768 patch
->lines_deleted
+= deleted
;
1770 if (0 < patch
->is_new
&& oldlines
)
1771 return error(_("new file depends on old contents"));
1772 if (0 < patch
->is_delete
&& newlines
)
1773 return error(_("deleted file still has contents"));
1778 * We have seen "diff --git a/... b/..." header (or a traditional patch
1779 * header). Read hunks that belong to this patch into fragments and hang
1780 * them to the given patch structure.
1782 * The (fragment->patch, fragment->size) pair points into the memory given
1783 * by the caller, not a copy, when we return.
1786 * -1 in case of error,
1787 * the number of bytes in the patch otherwise.
1789 static int parse_single_patch(struct apply_state
*state
,
1792 struct patch
*patch
)
1794 unsigned long offset
= 0;
1795 unsigned long oldlines
= 0, newlines
= 0, context
= 0;
1796 struct fragment
**fragp
= &patch
->fragments
;
1798 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
1799 struct fragment
*fragment
;
1802 CALLOC_ARRAY(fragment
, 1);
1803 fragment
->linenr
= state
->linenr
;
1804 len
= parse_fragment(state
, line
, size
, patch
, fragment
);
1807 return error(_("corrupt patch at line %d"), state
->linenr
);
1809 fragment
->patch
= line
;
1810 fragment
->size
= len
;
1811 oldlines
+= fragment
->oldlines
;
1812 newlines
+= fragment
->newlines
;
1813 context
+= fragment
->leading
+ fragment
->trailing
;
1816 fragp
= &fragment
->next
;
1824 * If something was removed (i.e. we have old-lines) it cannot
1825 * be creation, and if something was added it cannot be
1826 * deletion. However, the reverse is not true; --unified=0
1827 * patches that only add are not necessarily creation even
1828 * though they do not have any old lines, and ones that only
1829 * delete are not necessarily deletion.
1831 * Unfortunately, a real creation/deletion patch do _not_ have
1832 * any context line by definition, so we cannot safely tell it
1833 * apart with --unified=0 insanity. At least if the patch has
1834 * more than one hunk it is not creation or deletion.
1836 if (patch
->is_new
< 0 &&
1837 (oldlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1839 if (patch
->is_delete
< 0 &&
1840 (newlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1841 patch
->is_delete
= 0;
1843 if (0 < patch
->is_new
&& oldlines
)
1844 return error(_("new file %s depends on old contents"), patch
->new_name
);
1845 if (0 < patch
->is_delete
&& newlines
)
1846 return error(_("deleted file %s still has contents"), patch
->old_name
);
1847 if (!patch
->is_delete
&& !newlines
&& context
&& state
->apply_verbosity
> verbosity_silent
)
1850 "file %s becomes empty but is not deleted"),
1856 static inline int metadata_changes(struct patch
*patch
)
1858 return patch
->is_rename
> 0 ||
1859 patch
->is_copy
> 0 ||
1860 patch
->is_new
> 0 ||
1862 (patch
->old_mode
&& patch
->new_mode
&&
1863 patch
->old_mode
!= patch
->new_mode
);
1866 static char *inflate_it(const void *data
, unsigned long size
,
1867 unsigned long inflated_size
)
1873 memset(&stream
, 0, sizeof(stream
));
1875 stream
.next_in
= (unsigned char *)data
;
1876 stream
.avail_in
= size
;
1877 stream
.next_out
= out
= xmalloc(inflated_size
);
1878 stream
.avail_out
= inflated_size
;
1879 git_inflate_init(&stream
);
1880 st
= git_inflate(&stream
, Z_FINISH
);
1881 git_inflate_end(&stream
);
1882 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1890 * Read a binary hunk and return a new fragment; fragment->patch
1891 * points at an allocated memory that the caller must free, so
1892 * it is marked as "->free_patch = 1".
1894 static struct fragment
*parse_binary_hunk(struct apply_state
*state
,
1896 unsigned long *sz_p
,
1901 * Expect a line that begins with binary patch method ("literal"
1902 * or "delta"), followed by the length of data before deflating.
1903 * a sequence of 'length-byte' followed by base-85 encoded data
1904 * should follow, terminated by a newline.
1906 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1907 * and we would limit the patch line to 66 characters,
1908 * so one line can fit up to 13 groups that would decode
1909 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1910 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1913 unsigned long size
= *sz_p
;
1914 char *buffer
= *buf_p
;
1916 unsigned long origlen
;
1919 struct fragment
*frag
;
1921 llen
= linelen(buffer
, size
);
1926 if (starts_with(buffer
, "delta ")) {
1927 patch_method
= BINARY_DELTA_DEFLATED
;
1928 origlen
= strtoul(buffer
+ 6, NULL
, 10);
1930 else if (starts_with(buffer
, "literal ")) {
1931 patch_method
= BINARY_LITERAL_DEFLATED
;
1932 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 CALLOC_ARRAY(frag
, 1);
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 * When running with --allow-overlap, it is possible that a hunk is
2685 * seen that pretends to start at the beginning (but no longer does),
2686 * and that *still* needs to match the end. So trust `match_end` more
2687 * than `match_beginning`.
2689 if (state
->allow_overlap
&& match_beginning
&& match_end
&&
2690 img
->nr
- preimage
->nr
!= 0)
2691 match_beginning
= 0;
2694 * If match_beginning or match_end is specified, there is no
2695 * point starting from a wrong line that will never match and
2696 * wander around and wait for a match at the specified end.
2698 if (match_beginning
)
2701 line
= img
->nr
- preimage
->nr
;
2704 * Because the comparison is unsigned, the following test
2705 * will also take care of a negative line number that can
2706 * result when match_end and preimage is larger than the target.
2708 if ((size_t) line
> img
->nr
)
2712 for (i
= 0; i
< line
; i
++)
2713 current
+= img
->line
[i
].len
;
2716 * There's probably some smart way to do this, but I'll leave
2717 * that to the smart and beautiful people. I'm simple and stupid.
2719 backwards
= current
;
2720 backwards_lno
= line
;
2722 forwards_lno
= line
;
2725 for (i
= 0; ; i
++) {
2726 if (match_fragment(state
, img
, preimage
, postimage
,
2727 current
, current_lno
, ws_rule
,
2728 match_beginning
, match_end
))
2732 if (backwards_lno
== 0 && forwards_lno
== img
->nr
)
2736 if (backwards_lno
== 0) {
2741 backwards
-= img
->line
[backwards_lno
].len
;
2742 current
= backwards
;
2743 current_lno
= backwards_lno
;
2745 if (forwards_lno
== img
->nr
) {
2749 forwards
+= img
->line
[forwards_lno
].len
;
2752 current_lno
= forwards_lno
;
2759 static void remove_first_line(struct image
*img
)
2761 img
->buf
+= img
->line
[0].len
;
2762 img
->len
-= img
->line
[0].len
;
2767 static void remove_last_line(struct image
*img
)
2769 img
->len
-= img
->line
[--img
->nr
].len
;
2773 * The change from "preimage" and "postimage" has been found to
2774 * apply at applied_pos (counts in line numbers) in "img".
2775 * Update "img" to remove "preimage" and replace it with "postimage".
2777 static void update_image(struct apply_state
*state
,
2780 struct image
*preimage
,
2781 struct image
*postimage
)
2784 * remove the copy of preimage at offset in img
2785 * and replace it with postimage
2788 size_t remove_count
, insert_count
, applied_at
= 0;
2793 * If we are removing blank lines at the end of img,
2794 * the preimage may extend beyond the end.
2795 * If that is the case, we must be careful only to
2796 * remove the part of the preimage that falls within
2797 * the boundaries of img. Initialize preimage_limit
2798 * to the number of lines in the preimage that falls
2799 * within the boundaries.
2801 preimage_limit
= preimage
->nr
;
2802 if (preimage_limit
> img
->nr
- applied_pos
)
2803 preimage_limit
= img
->nr
- applied_pos
;
2805 for (i
= 0; i
< applied_pos
; i
++)
2806 applied_at
+= img
->line
[i
].len
;
2809 for (i
= 0; i
< preimage_limit
; i
++)
2810 remove_count
+= img
->line
[applied_pos
+ i
].len
;
2811 insert_count
= postimage
->len
;
2813 /* Adjust the contents */
2814 result
= xmalloc(st_add3(st_sub(img
->len
, remove_count
), insert_count
, 1));
2815 memcpy(result
, img
->buf
, applied_at
);
2816 memcpy(result
+ applied_at
, postimage
->buf
, postimage
->len
);
2817 memcpy(result
+ applied_at
+ postimage
->len
,
2818 img
->buf
+ (applied_at
+ remove_count
),
2819 img
->len
- (applied_at
+ remove_count
));
2822 img
->len
+= insert_count
- remove_count
;
2823 result
[img
->len
] = '\0';
2825 /* Adjust the line table */
2826 nr
= img
->nr
+ postimage
->nr
- preimage_limit
;
2827 if (preimage_limit
< postimage
->nr
) {
2829 * NOTE: this knows that we never call remove_first_line()
2830 * on anything other than pre/post image.
2832 REALLOC_ARRAY(img
->line
, nr
);
2833 img
->line_allocated
= img
->line
;
2835 if (preimage_limit
!= postimage
->nr
)
2836 MOVE_ARRAY(img
->line
+ applied_pos
+ postimage
->nr
,
2837 img
->line
+ applied_pos
+ preimage_limit
,
2838 img
->nr
- (applied_pos
+ preimage_limit
));
2839 COPY_ARRAY(img
->line
+ applied_pos
, postimage
->line
, postimage
->nr
);
2840 if (!state
->allow_overlap
)
2841 for (i
= 0; i
< postimage
->nr
; i
++)
2842 img
->line
[applied_pos
+ i
].flag
|= LINE_PATCHED
;
2847 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2848 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2849 * replace the part of "img" with "postimage" text.
2851 static int apply_one_fragment(struct apply_state
*state
,
2852 struct image
*img
, struct fragment
*frag
,
2853 int inaccurate_eof
, unsigned ws_rule
,
2856 int match_beginning
, match_end
;
2857 const char *patch
= frag
->patch
;
2858 int size
= frag
->size
;
2859 char *old
, *oldlines
;
2860 struct strbuf newlines
;
2861 int new_blank_lines_at_end
= 0;
2862 int found_new_blank_lines_at_end
= 0;
2863 int hunk_linenr
= frag
->linenr
;
2864 unsigned long leading
, trailing
;
2865 int pos
, applied_pos
;
2866 struct image preimage
;
2867 struct image postimage
;
2869 memset(&preimage
, 0, sizeof(preimage
));
2870 memset(&postimage
, 0, sizeof(postimage
));
2871 oldlines
= xmalloc(size
);
2872 strbuf_init(&newlines
, size
);
2877 int len
= linelen(patch
, size
);
2879 int added_blank_line
= 0;
2880 int is_blank_context
= 0;
2887 * "plen" is how much of the line we should use for
2888 * the actual patch data. Normally we just remove the
2889 * first character on the line, but if the line is
2890 * followed by "\ No newline", then we also remove the
2891 * last one (which is the newline, of course).
2894 if (len
< size
&& patch
[len
] == '\\')
2897 if (state
->apply_in_reverse
) {
2900 else if (first
== '+')
2906 /* Newer GNU diff, empty context line */
2908 /* ... followed by '\No newline'; nothing */
2911 strbuf_addch(&newlines
, '\n');
2912 add_line_info(&preimage
, "\n", 1, LINE_COMMON
);
2913 add_line_info(&postimage
, "\n", 1, LINE_COMMON
);
2914 is_blank_context
= 1;
2917 if (plen
&& (ws_rule
& WS_BLANK_AT_EOF
) &&
2918 ws_blank_line(patch
+ 1, plen
))
2919 is_blank_context
= 1;
2922 memcpy(old
, patch
+ 1, plen
);
2923 add_line_info(&preimage
, old
, plen
,
2924 (first
== ' ' ? LINE_COMMON
: 0));
2930 /* --no-add does not add new lines */
2931 if (first
== '+' && state
->no_add
)
2934 start
= newlines
.len
;
2936 !state
->whitespace_error
||
2937 state
->ws_error_action
!= correct_ws_error
) {
2938 strbuf_add(&newlines
, patch
+ 1, plen
);
2941 ws_fix_copy(&newlines
, patch
+ 1, plen
, ws_rule
, &state
->applied_after_fixing_ws
);
2943 add_line_info(&postimage
, newlines
.buf
+ start
, newlines
.len
- start
,
2944 (first
== '+' ? 0 : LINE_COMMON
));
2946 (ws_rule
& WS_BLANK_AT_EOF
) &&
2947 ws_blank_line(patch
+ 1, plen
))
2948 added_blank_line
= 1;
2950 case '@': case '\\':
2951 /* Ignore it, we already handled it */
2954 if (state
->apply_verbosity
> verbosity_normal
)
2955 error(_("invalid start of line: '%c'"), first
);
2959 if (added_blank_line
) {
2960 if (!new_blank_lines_at_end
)
2961 found_new_blank_lines_at_end
= hunk_linenr
;
2962 new_blank_lines_at_end
++;
2964 else if (is_blank_context
)
2967 new_blank_lines_at_end
= 0;
2972 if (inaccurate_eof
&&
2973 old
> oldlines
&& old
[-1] == '\n' &&
2974 newlines
.len
> 0 && newlines
.buf
[newlines
.len
- 1] == '\n') {
2976 strbuf_setlen(&newlines
, newlines
.len
- 1);
2977 preimage
.line_allocated
[preimage
.nr
- 1].len
--;
2978 postimage
.line_allocated
[postimage
.nr
- 1].len
--;
2981 leading
= frag
->leading
;
2982 trailing
= frag
->trailing
;
2985 * A hunk to change lines at the beginning would begin with
2987 * but we need to be careful. -U0 that inserts before the second
2988 * line also has this pattern.
2990 * And a hunk to add to an empty file would begin with
2993 * In other words, a hunk that is (frag->oldpos <= 1) with or
2994 * without leading context must match at the beginning.
2996 match_beginning
= (!frag
->oldpos
||
2997 (frag
->oldpos
== 1 && !state
->unidiff_zero
));
3000 * A hunk without trailing lines must match at the end.
3001 * However, we simply cannot tell if a hunk must match end
3002 * from the lack of trailing lines if the patch was generated
3003 * with unidiff without any context.
3005 match_end
= !state
->unidiff_zero
&& !trailing
;
3007 pos
= frag
->newpos
? (frag
->newpos
- 1) : 0;
3008 preimage
.buf
= oldlines
;
3009 preimage
.len
= old
- oldlines
;
3010 postimage
.buf
= newlines
.buf
;
3011 postimage
.len
= newlines
.len
;
3012 preimage
.line
= preimage
.line_allocated
;
3013 postimage
.line
= postimage
.line_allocated
;
3017 applied_pos
= find_pos(state
, img
, &preimage
, &postimage
, pos
,
3018 ws_rule
, match_beginning
, match_end
);
3020 if (applied_pos
>= 0)
3023 /* Am I at my context limits? */
3024 if ((leading
<= state
->p_context
) && (trailing
<= state
->p_context
))
3026 if (match_beginning
|| match_end
) {
3027 match_beginning
= match_end
= 0;
3032 * Reduce the number of context lines; reduce both
3033 * leading and trailing if they are equal otherwise
3034 * just reduce the larger context.
3036 if (leading
>= trailing
) {
3037 remove_first_line(&preimage
);
3038 remove_first_line(&postimage
);
3042 if (trailing
> leading
) {
3043 remove_last_line(&preimage
);
3044 remove_last_line(&postimage
);
3049 if (applied_pos
>= 0) {
3050 if (new_blank_lines_at_end
&&
3051 preimage
.nr
+ applied_pos
>= img
->nr
&&
3052 (ws_rule
& WS_BLANK_AT_EOF
) &&
3053 state
->ws_error_action
!= nowarn_ws_error
) {
3054 record_ws_error(state
, WS_BLANK_AT_EOF
, "+", 1,
3055 found_new_blank_lines_at_end
);
3056 if (state
->ws_error_action
== correct_ws_error
) {
3057 while (new_blank_lines_at_end
--)
3058 remove_last_line(&postimage
);
3061 * We would want to prevent write_out_results()
3062 * from taking place in apply_patch() that follows
3063 * the callchain led us here, which is:
3064 * apply_patch->check_patch_list->check_patch->
3065 * apply_data->apply_fragments->apply_one_fragment
3067 if (state
->ws_error_action
== die_on_ws_error
)
3071 if (state
->apply_verbosity
> verbosity_normal
&& applied_pos
!= pos
) {
3072 int offset
= applied_pos
- pos
;
3073 if (state
->apply_in_reverse
)
3074 offset
= 0 - offset
;
3076 Q_("Hunk #%d succeeded at %d (offset %d line).",
3077 "Hunk #%d succeeded at %d (offset %d lines).",
3079 nth_fragment
, applied_pos
+ 1, offset
);
3083 * Warn if it was necessary to reduce the number
3086 if ((leading
!= frag
->leading
||
3087 trailing
!= frag
->trailing
) && state
->apply_verbosity
> verbosity_silent
)
3088 fprintf_ln(stderr
, _("Context reduced to (%ld/%ld)"
3089 " to apply fragment at %d"),
3090 leading
, trailing
, applied_pos
+1);
3091 update_image(state
, img
, applied_pos
, &preimage
, &postimage
);
3093 if (state
->apply_verbosity
> verbosity_normal
)
3094 error(_("while searching for:\n%.*s"),
3095 (int)(old
- oldlines
), oldlines
);
3100 strbuf_release(&newlines
);
3101 free(preimage
.line_allocated
);
3102 free(postimage
.line_allocated
);
3104 return (applied_pos
< 0);
3107 static int apply_binary_fragment(struct apply_state
*state
,
3109 struct patch
*patch
)
3111 struct fragment
*fragment
= patch
->fragments
;
3116 return error(_("missing binary patch data for '%s'"),
3121 /* Binary patch is irreversible without the optional second hunk */
3122 if (state
->apply_in_reverse
) {
3123 if (!fragment
->next
)
3124 return error(_("cannot reverse-apply a binary patch "
3125 "without the reverse hunk to '%s'"),
3127 ? patch
->new_name
: patch
->old_name
);
3128 fragment
= fragment
->next
;
3130 switch (fragment
->binary_patch_method
) {
3131 case BINARY_DELTA_DEFLATED
:
3132 dst
= patch_delta(img
->buf
, img
->len
, fragment
->patch
,
3133 fragment
->size
, &len
);
3140 case BINARY_LITERAL_DEFLATED
:
3142 img
->len
= fragment
->size
;
3143 img
->buf
= xmemdupz(fragment
->patch
, img
->len
);
3150 * Replace "img" with the result of applying the binary patch.
3151 * The binary patch data itself in patch->fragment is still kept
3152 * but the preimage prepared by the caller in "img" is freed here
3153 * or in the helper function apply_binary_fragment() this calls.
3155 static int apply_binary(struct apply_state
*state
,
3157 struct patch
*patch
)
3159 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3160 struct object_id oid
;
3161 const unsigned hexsz
= the_hash_algo
->hexsz
;
3164 * For safety, we require patch index line to contain
3165 * full hex textual object ID for old and new, at least for now.
3167 if (strlen(patch
->old_oid_prefix
) != hexsz
||
3168 strlen(patch
->new_oid_prefix
) != hexsz
||
3169 get_oid_hex(patch
->old_oid_prefix
, &oid
) ||
3170 get_oid_hex(patch
->new_oid_prefix
, &oid
))
3171 return error(_("cannot apply binary patch to '%s' "
3172 "without full index line"), name
);
3174 if (patch
->old_name
) {
3176 * See if the old one matches what the patch
3179 hash_object_file(the_hash_algo
, img
->buf
, img
->len
, OBJ_BLOB
,
3181 if (strcmp(oid_to_hex(&oid
), patch
->old_oid_prefix
))
3182 return error(_("the patch applies to '%s' (%s), "
3183 "which does not match the "
3184 "current contents."),
3185 name
, oid_to_hex(&oid
));
3188 /* Otherwise, the old one must be empty. */
3190 return error(_("the patch applies to an empty "
3191 "'%s' but it is not empty"), name
);
3194 get_oid_hex(patch
->new_oid_prefix
, &oid
);
3195 if (is_null_oid(&oid
)) {
3197 return 0; /* deletion patch */
3200 if (has_object(the_repository
, &oid
, 0)) {
3201 /* We already have the postimage */
3202 enum object_type type
;
3206 result
= read_object_file(&oid
, &type
, &size
);
3208 return error(_("the necessary postimage %s for "
3209 "'%s' cannot be read"),
3210 patch
->new_oid_prefix
, name
);
3216 * We have verified buf matches the preimage;
3217 * apply the patch data to it, which is stored
3218 * in the patch->fragments->{patch,size}.
3220 if (apply_binary_fragment(state
, img
, patch
))
3221 return error(_("binary patch does not apply to '%s'"),
3224 /* verify that the result matches */
3225 hash_object_file(the_hash_algo
, img
->buf
, img
->len
, OBJ_BLOB
,
3227 if (strcmp(oid_to_hex(&oid
), patch
->new_oid_prefix
))
3228 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3229 name
, patch
->new_oid_prefix
, oid_to_hex(&oid
));
3235 static int apply_fragments(struct apply_state
*state
, struct image
*img
, struct patch
*patch
)
3237 struct fragment
*frag
= patch
->fragments
;
3238 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3239 unsigned ws_rule
= patch
->ws_rule
;
3240 unsigned inaccurate_eof
= patch
->inaccurate_eof
;
3243 if (patch
->is_binary
)
3244 return apply_binary(state
, img
, patch
);
3248 if (apply_one_fragment(state
, img
, frag
, inaccurate_eof
, ws_rule
, nth
)) {
3249 error(_("patch failed: %s:%ld"), name
, frag
->oldpos
);
3250 if (!state
->apply_with_reject
)
3259 static int read_blob_object(struct strbuf
*buf
, const struct object_id
*oid
, unsigned mode
)
3261 if (S_ISGITLINK(mode
)) {
3262 strbuf_grow(buf
, 100);
3263 strbuf_addf(buf
, "Subproject commit %s\n", oid_to_hex(oid
));
3265 enum object_type type
;
3269 result
= read_object_file(oid
, &type
, &sz
);
3272 /* XXX read_sha1_file NUL-terminates */
3273 strbuf_attach(buf
, result
, sz
, sz
+ 1);
3278 static int read_file_or_gitlink(const struct cache_entry
*ce
, struct strbuf
*buf
)
3282 return read_blob_object(buf
, &ce
->oid
, ce
->ce_mode
);
3285 static struct patch
*in_fn_table(struct apply_state
*state
, const char *name
)
3287 struct string_list_item
*item
;
3292 item
= string_list_lookup(&state
->fn_table
, name
);
3294 return (struct patch
*)item
->util
;
3300 * item->util in the filename table records the status of the path.
3301 * Usually it points at a patch (whose result records the contents
3302 * of it after applying it), but it could be PATH_WAS_DELETED for a
3303 * path that a previously applied patch has already removed, or
3304 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3306 * The latter is needed to deal with a case where two paths A and B
3307 * are swapped by first renaming A to B and then renaming B to A;
3308 * moving A to B should not be prevented due to presence of B as we
3309 * will remove it in a later patch.
3311 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3312 #define PATH_WAS_DELETED ((struct patch *) -1)
3314 static int to_be_deleted(struct patch
*patch
)
3316 return patch
== PATH_TO_BE_DELETED
;
3319 static int was_deleted(struct patch
*patch
)
3321 return patch
== PATH_WAS_DELETED
;
3324 static void add_to_fn_table(struct apply_state
*state
, struct patch
*patch
)
3326 struct string_list_item
*item
;
3329 * Always add new_name unless patch is a deletion
3330 * This should cover the cases for normal diffs,
3331 * file creations and copies
3333 if (patch
->new_name
) {
3334 item
= string_list_insert(&state
->fn_table
, patch
->new_name
);
3339 * store a failure on rename/deletion cases because
3340 * later chunks shouldn't patch old names
3342 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3343 item
= string_list_insert(&state
->fn_table
, patch
->old_name
);
3344 item
->util
= PATH_WAS_DELETED
;
3348 static void prepare_fn_table(struct apply_state
*state
, struct patch
*patch
)
3351 * store information about incoming file deletion
3354 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3355 struct string_list_item
*item
;
3356 item
= string_list_insert(&state
->fn_table
, patch
->old_name
);
3357 item
->util
= PATH_TO_BE_DELETED
;
3359 patch
= patch
->next
;
3363 static int checkout_target(struct index_state
*istate
,
3364 struct cache_entry
*ce
, struct stat
*st
)
3366 struct checkout costate
= CHECKOUT_INIT
;
3368 costate
.refresh_cache
= 1;
3369 costate
.istate
= istate
;
3370 if (checkout_entry(ce
, &costate
, NULL
, NULL
) ||
3371 lstat(ce
->name
, st
))
3372 return error(_("cannot checkout %s"), ce
->name
);
3376 static struct patch
*previous_patch(struct apply_state
*state
,
3377 struct patch
*patch
,
3380 struct patch
*previous
;
3383 if (patch
->is_copy
|| patch
->is_rename
)
3384 return NULL
; /* "git" patches do not depend on the order */
3386 previous
= in_fn_table(state
, patch
->old_name
);
3390 if (to_be_deleted(previous
))
3391 return NULL
; /* the deletion hasn't happened yet */
3393 if (was_deleted(previous
))
3399 static int verify_index_match(struct apply_state
*state
,
3400 const struct cache_entry
*ce
,
3403 if (S_ISGITLINK(ce
->ce_mode
)) {
3404 if (!S_ISDIR(st
->st_mode
))
3408 return ie_match_stat(state
->repo
->index
, ce
, st
,
3409 CE_MATCH_IGNORE_VALID
| CE_MATCH_IGNORE_SKIP_WORKTREE
);
3412 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3414 static int load_patch_target(struct apply_state
*state
,
3416 const struct cache_entry
*ce
,
3418 struct patch
*patch
,
3420 unsigned expected_mode
)
3422 if (state
->cached
|| state
->check_index
) {
3423 if (read_file_or_gitlink(ce
, buf
))
3424 return error(_("failed to read %s"), name
);
3426 if (S_ISGITLINK(expected_mode
)) {
3428 return read_file_or_gitlink(ce
, buf
);
3430 return SUBMODULE_PATCH_WITHOUT_INDEX
;
3431 } else if (has_symlink_leading_path(name
, strlen(name
))) {
3432 return error(_("reading from '%s' beyond a symbolic link"), name
);
3434 if (read_old_data(st
, patch
, name
, buf
))
3435 return error(_("failed to read %s"), name
);
3442 * We are about to apply "patch"; populate the "image" with the
3443 * current version we have, from the working tree or from the index,
3444 * depending on the situation e.g. --cached/--index. If we are
3445 * applying a non-git patch that incrementally updates the tree,
3446 * we read from the result of a previous diff.
3448 static int load_preimage(struct apply_state
*state
,
3449 struct image
*image
,
3450 struct patch
*patch
, struct stat
*st
,
3451 const struct cache_entry
*ce
)
3453 struct strbuf buf
= STRBUF_INIT
;
3456 struct patch
*previous
;
3459 previous
= previous_patch(state
, patch
, &status
);
3461 return error(_("path %s has been renamed/deleted"),
3464 /* We have a patched copy in memory; use that. */
3465 strbuf_add(&buf
, previous
->result
, previous
->resultsize
);
3467 status
= load_patch_target(state
, &buf
, ce
, st
, patch
,
3468 patch
->old_name
, patch
->old_mode
);
3471 else if (status
== SUBMODULE_PATCH_WITHOUT_INDEX
) {
3473 * There is no way to apply subproject
3474 * patch without looking at the index.
3475 * NEEDSWORK: shouldn't this be flagged
3478 free_fragment_list(patch
->fragments
);
3479 patch
->fragments
= NULL
;
3480 } else if (status
) {
3481 return error(_("failed to read %s"), patch
->old_name
);
3485 img
= strbuf_detach(&buf
, &len
);
3486 prepare_image(image
, img
, len
, !patch
->is_binary
);
3490 static int resolve_to(struct image
*image
, const struct object_id
*result_id
)
3493 enum object_type type
;
3497 image
->buf
= read_object_file(result_id
, &type
, &size
);
3498 if (!image
->buf
|| type
!= OBJ_BLOB
)
3499 die("unable to read blob object %s", oid_to_hex(result_id
));
3505 static int three_way_merge(struct apply_state
*state
,
3506 struct image
*image
,
3508 const struct object_id
*base
,
3509 const struct object_id
*ours
,
3510 const struct object_id
*theirs
)
3512 mmfile_t base_file
, our_file
, their_file
;
3513 mmbuffer_t result
= { NULL
};
3514 enum ll_merge_result status
;
3516 /* resolve trivial cases first */
3517 if (oideq(base
, ours
))
3518 return resolve_to(image
, theirs
);
3519 else if (oideq(base
, theirs
) || oideq(ours
, theirs
))
3520 return resolve_to(image
, ours
);
3522 read_mmblob(&base_file
, base
);
3523 read_mmblob(&our_file
, ours
);
3524 read_mmblob(&their_file
, theirs
);
3525 status
= ll_merge(&result
, path
,
3528 &their_file
, "theirs",
3531 if (status
== LL_MERGE_BINARY_CONFLICT
)
3532 warning("Cannot merge binary files: %s (%s vs. %s)",
3533 path
, "ours", "theirs");
3534 free(base_file
.ptr
);
3536 free(their_file
.ptr
);
3537 if (status
< 0 || !result
.ptr
) {
3542 image
->buf
= result
.ptr
;
3543 image
->len
= result
.size
;
3549 * When directly falling back to add/add three-way merge, we read from
3550 * the current contents of the new_name. In no cases other than that
3551 * this function will be called.
3553 static int load_current(struct apply_state
*state
,
3554 struct image
*image
,
3555 struct patch
*patch
)
3557 struct strbuf buf
= STRBUF_INIT
;
3562 struct cache_entry
*ce
;
3563 char *name
= patch
->new_name
;
3564 unsigned mode
= patch
->new_mode
;
3567 BUG("patch to %s is not a creation", patch
->old_name
);
3569 pos
= index_name_pos(state
->repo
->index
, name
, strlen(name
));
3571 return error(_("%s: does not exist in index"), name
);
3572 ce
= state
->repo
->index
->cache
[pos
];
3573 if (lstat(name
, &st
)) {
3574 if (errno
!= ENOENT
)
3575 return error_errno("%s", name
);
3576 if (checkout_target(state
->repo
->index
, ce
, &st
))
3579 if (verify_index_match(state
, ce
, &st
))
3580 return error(_("%s: does not match index"), name
);
3582 status
= load_patch_target(state
, &buf
, ce
, &st
, patch
, name
, mode
);
3587 img
= strbuf_detach(&buf
, &len
);
3588 prepare_image(image
, img
, len
, !patch
->is_binary
);
3592 static int try_threeway(struct apply_state
*state
,
3593 struct image
*image
,
3594 struct patch
*patch
,
3596 const struct cache_entry
*ce
)
3598 struct object_id pre_oid
, post_oid
, our_oid
;
3599 struct strbuf buf
= STRBUF_INIT
;
3603 struct image tmp_image
;
3605 /* No point falling back to 3-way merge in these cases */
3606 if (patch
->is_delete
||
3607 S_ISGITLINK(patch
->old_mode
) || S_ISGITLINK(patch
->new_mode
) ||
3608 (patch
->is_new
&& !patch
->direct_to_threeway
) ||
3609 (patch
->is_rename
&& !patch
->lines_added
&& !patch
->lines_deleted
))
3612 /* Preimage the patch was prepared for */
3614 write_object_file("", 0, OBJ_BLOB
, &pre_oid
);
3615 else if (get_oid(patch
->old_oid_prefix
, &pre_oid
) ||
3616 read_blob_object(&buf
, &pre_oid
, patch
->old_mode
))
3617 return error(_("repository lacks the necessary blob to perform 3-way merge."));
3619 if (state
->apply_verbosity
> verbosity_silent
&& patch
->direct_to_threeway
)
3620 fprintf(stderr
, _("Performing three-way merge...\n"));
3622 img
= strbuf_detach(&buf
, &len
);
3623 prepare_image(&tmp_image
, img
, len
, 1);
3624 /* Apply the patch to get the post image */
3625 if (apply_fragments(state
, &tmp_image
, patch
) < 0) {
3626 clear_image(&tmp_image
);
3629 /* post_oid is theirs */
3630 write_object_file(tmp_image
.buf
, tmp_image
.len
, OBJ_BLOB
, &post_oid
);
3631 clear_image(&tmp_image
);
3633 /* our_oid is ours */
3634 if (patch
->is_new
) {
3635 if (load_current(state
, &tmp_image
, patch
))
3636 return error(_("cannot read the current contents of '%s'"),
3639 if (load_preimage(state
, &tmp_image
, patch
, st
, ce
))
3640 return error(_("cannot read the current contents of '%s'"),
3643 write_object_file(tmp_image
.buf
, tmp_image
.len
, OBJ_BLOB
, &our_oid
);
3644 clear_image(&tmp_image
);
3646 /* in-core three-way merge between post and our using pre as base */
3647 status
= three_way_merge(state
, image
, patch
->new_name
,
3648 &pre_oid
, &our_oid
, &post_oid
);
3650 if (state
->apply_verbosity
> verbosity_silent
)
3652 _("Failed to perform three-way merge...\n"));
3657 patch
->conflicted_threeway
= 1;
3659 oidclr(&patch
->threeway_stage
[0]);
3661 oidcpy(&patch
->threeway_stage
[0], &pre_oid
);
3662 oidcpy(&patch
->threeway_stage
[1], &our_oid
);
3663 oidcpy(&patch
->threeway_stage
[2], &post_oid
);
3664 if (state
->apply_verbosity
> verbosity_silent
)
3666 _("Applied patch to '%s' with conflicts.\n"),
3669 if (state
->apply_verbosity
> verbosity_silent
)
3671 _("Applied patch to '%s' cleanly.\n"),
3677 static int apply_data(struct apply_state
*state
, struct patch
*patch
,
3678 struct stat
*st
, const struct cache_entry
*ce
)
3682 if (load_preimage(state
, &image
, patch
, st
, ce
) < 0)
3685 if (!state
->threeway
|| try_threeway(state
, &image
, patch
, st
, ce
) < 0) {
3686 if (state
->apply_verbosity
> verbosity_silent
&&
3687 state
->threeway
&& !patch
->direct_to_threeway
)
3688 fprintf(stderr
, _("Falling back to direct application...\n"));
3690 /* Note: with --reject, apply_fragments() returns 0 */
3691 if (patch
->direct_to_threeway
|| apply_fragments(state
, &image
, patch
) < 0)
3694 patch
->result
= image
.buf
;
3695 patch
->resultsize
= image
.len
;
3696 add_to_fn_table(state
, patch
);
3697 free(image
.line_allocated
);
3699 if (0 < patch
->is_delete
&& patch
->resultsize
)
3700 return error(_("removal patch leaves file contents"));
3706 * If "patch" that we are looking at modifies or deletes what we have,
3707 * we would want it not to lose any local modification we have, either
3708 * in the working tree or in the index.
3710 * This also decides if a non-git patch is a creation patch or a
3711 * modification to an existing empty file. We do not check the state
3712 * of the current tree for a creation patch in this function; the caller
3713 * check_patch() separately makes sure (and errors out otherwise) that
3714 * the path the patch creates does not exist in the current tree.
3716 static int check_preimage(struct apply_state
*state
,
3717 struct patch
*patch
,
3718 struct cache_entry
**ce
,
3721 const char *old_name
= patch
->old_name
;
3722 struct patch
*previous
= NULL
;
3723 int stat_ret
= 0, status
;
3724 unsigned st_mode
= 0;
3729 assert(patch
->is_new
<= 0);
3730 previous
= previous_patch(state
, patch
, &status
);
3733 return error(_("path %s has been renamed/deleted"), old_name
);
3735 st_mode
= previous
->new_mode
;
3736 } else if (!state
->cached
) {
3737 stat_ret
= lstat(old_name
, st
);
3738 if (stat_ret
&& errno
!= ENOENT
)
3739 return error_errno("%s", old_name
);
3742 if (state
->check_index
&& !previous
) {
3743 int pos
= index_name_pos(state
->repo
->index
, old_name
,
3746 if (patch
->is_new
< 0)
3748 return error(_("%s: does not exist in index"), old_name
);
3750 *ce
= state
->repo
->index
->cache
[pos
];
3752 if (checkout_target(state
->repo
->index
, *ce
, st
))
3755 if (!state
->cached
&& verify_index_match(state
, *ce
, st
))
3756 return error(_("%s: does not match index"), old_name
);
3758 st_mode
= (*ce
)->ce_mode
;
3759 } else if (stat_ret
< 0) {
3760 if (patch
->is_new
< 0)
3762 return error_errno("%s", old_name
);
3765 if (!state
->cached
&& !previous
)
3766 st_mode
= ce_mode_from_stat(*ce
, st
->st_mode
);
3768 if (patch
->is_new
< 0)
3770 if (!patch
->old_mode
)
3771 patch
->old_mode
= st_mode
;
3772 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
3773 return error(_("%s: wrong type"), old_name
);
3774 if (st_mode
!= patch
->old_mode
)
3775 warning(_("%s has type %o, expected %o"),
3776 old_name
, st_mode
, patch
->old_mode
);
3777 if (!patch
->new_mode
&& !patch
->is_delete
)
3778 patch
->new_mode
= st_mode
;
3783 patch
->is_delete
= 0;
3784 FREE_AND_NULL(patch
->old_name
);
3789 #define EXISTS_IN_INDEX 1
3790 #define EXISTS_IN_WORKTREE 2
3791 #define EXISTS_IN_INDEX_AS_ITA 3
3793 static int check_to_create(struct apply_state
*state
,
3794 const char *new_name
,
3799 if (state
->check_index
&& (!ok_if_exists
|| !state
->cached
)) {
3802 pos
= index_name_pos(state
->repo
->index
, new_name
, strlen(new_name
));
3804 struct cache_entry
*ce
= state
->repo
->index
->cache
[pos
];
3806 /* allow ITA, as they do not yet exist in the index */
3807 if (!ok_if_exists
&& !(ce
->ce_flags
& CE_INTENT_TO_ADD
))
3808 return EXISTS_IN_INDEX
;
3810 /* ITA entries can never match working tree files */
3811 if (!state
->cached
&& (ce
->ce_flags
& CE_INTENT_TO_ADD
))
3812 return EXISTS_IN_INDEX_AS_ITA
;
3819 if (!lstat(new_name
, &nst
)) {
3820 if (S_ISDIR(nst
.st_mode
) || ok_if_exists
)
3823 * A leading component of new_name might be a symlink
3824 * that is going to be removed with this patch, but
3825 * still pointing at somewhere that has the path.
3826 * In such a case, path "new_name" does not exist as
3827 * far as git is concerned.
3829 if (has_symlink_leading_path(new_name
, strlen(new_name
)))
3832 return EXISTS_IN_WORKTREE
;
3833 } else if (!is_missing_file_error(errno
)) {
3834 return error_errno("%s", new_name
);
3839 static void prepare_symlink_changes(struct apply_state
*state
, struct patch
*patch
)
3841 for ( ; patch
; patch
= patch
->next
) {
3842 if ((patch
->old_name
&& S_ISLNK(patch
->old_mode
)) &&
3843 (patch
->is_rename
|| patch
->is_delete
))
3844 /* the symlink at patch->old_name is removed */
3845 strset_add(&state
->removed_symlinks
, patch
->old_name
);
3847 if (patch
->new_name
&& S_ISLNK(patch
->new_mode
))
3848 /* the symlink at patch->new_name is created or remains */
3849 strset_add(&state
->kept_symlinks
, patch
->new_name
);
3853 static int path_is_beyond_symlink_1(struct apply_state
*state
, struct strbuf
*name
)
3856 while (--name
->len
&& name
->buf
[name
->len
] != '/')
3857 ; /* scan backwards */
3860 name
->buf
[name
->len
] = '\0';
3861 if (strset_contains(&state
->kept_symlinks
, name
->buf
))
3863 if (strset_contains(&state
->removed_symlinks
, name
->buf
))
3865 * This cannot be "return 0", because we may
3866 * see a new one created at a higher level.
3870 /* otherwise, check the preimage */
3871 if (state
->check_index
) {
3872 struct cache_entry
*ce
;
3874 ce
= index_file_exists(state
->repo
->index
, name
->buf
,
3875 name
->len
, ignore_case
);
3876 if (ce
&& S_ISLNK(ce
->ce_mode
))
3880 if (!lstat(name
->buf
, &st
) && S_ISLNK(st
.st_mode
))
3887 static int path_is_beyond_symlink(struct apply_state
*state
, const char *name_
)
3890 struct strbuf name
= STRBUF_INIT
;
3892 assert(*name_
!= '\0');
3893 strbuf_addstr(&name
, name_
);
3894 ret
= path_is_beyond_symlink_1(state
, &name
);
3895 strbuf_release(&name
);
3900 static int check_unsafe_path(struct patch
*patch
)
3902 const char *old_name
= NULL
;
3903 const char *new_name
= NULL
;
3904 if (patch
->is_delete
)
3905 old_name
= patch
->old_name
;
3906 else if (!patch
->is_new
&& !patch
->is_copy
)
3907 old_name
= patch
->old_name
;
3908 if (!patch
->is_delete
)
3909 new_name
= patch
->new_name
;
3911 if (old_name
&& !verify_path(old_name
, patch
->old_mode
))
3912 return error(_("invalid path '%s'"), old_name
);
3913 if (new_name
&& !verify_path(new_name
, patch
->new_mode
))
3914 return error(_("invalid path '%s'"), new_name
);
3919 * Check and apply the patch in-core; leave the result in patch->result
3920 * for the caller to write it out to the final destination.
3922 static int check_patch(struct apply_state
*state
, struct patch
*patch
)
3925 const char *old_name
= patch
->old_name
;
3926 const char *new_name
= patch
->new_name
;
3927 const char *name
= old_name
? old_name
: new_name
;
3928 struct cache_entry
*ce
= NULL
;
3929 struct patch
*tpatch
;
3933 patch
->rejected
= 1; /* we will drop this after we succeed */
3935 status
= check_preimage(state
, patch
, &ce
, &st
);
3938 old_name
= patch
->old_name
;
3941 * A type-change diff is always split into a patch to delete
3942 * old, immediately followed by a patch to create new (see
3943 * diff.c::run_diff()); in such a case it is Ok that the entry
3944 * to be deleted by the previous patch is still in the working
3945 * tree and in the index.
3947 * A patch to swap-rename between A and B would first rename A
3948 * to B and then rename B to A. While applying the first one,
3949 * the presence of B should not stop A from getting renamed to
3950 * B; ask to_be_deleted() about the later rename. Removal of
3951 * B and rename from A to B is handled the same way by asking
3954 if ((tpatch
= in_fn_table(state
, new_name
)) &&
3955 (was_deleted(tpatch
) || to_be_deleted(tpatch
)))
3961 ((0 < patch
->is_new
) || patch
->is_rename
|| patch
->is_copy
)) {
3962 int err
= check_to_create(state
, new_name
, ok_if_exists
);
3964 if (err
&& state
->threeway
) {
3965 patch
->direct_to_threeway
= 1;
3966 } else switch (err
) {
3969 case EXISTS_IN_INDEX
:
3970 return error(_("%s: already exists in index"), new_name
);
3971 case EXISTS_IN_INDEX_AS_ITA
:
3972 return error(_("%s: does not match index"), new_name
);
3973 case EXISTS_IN_WORKTREE
:
3974 return error(_("%s: already exists in working directory"),
3980 if (!patch
->new_mode
) {
3981 if (0 < patch
->is_new
)
3982 patch
->new_mode
= S_IFREG
| 0644;
3984 patch
->new_mode
= patch
->old_mode
;
3988 if (new_name
&& old_name
) {
3989 int same
= !strcmp(old_name
, new_name
);
3990 if (!patch
->new_mode
)
3991 patch
->new_mode
= patch
->old_mode
;
3992 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
) {
3994 return error(_("new mode (%o) of %s does not "
3995 "match old mode (%o)"),
3996 patch
->new_mode
, new_name
,
3999 return error(_("new mode (%o) of %s does not "
4000 "match old mode (%o) of %s"),
4001 patch
->new_mode
, new_name
,
4002 patch
->old_mode
, old_name
);
4006 if (!state
->unsafe_paths
&& check_unsafe_path(patch
))
4010 * An attempt to read from or delete a path that is beyond a
4011 * symbolic link will be prevented by load_patch_target() that
4012 * is called at the beginning of apply_data() so we do not
4013 * have to worry about a patch marked with "is_delete" bit
4014 * here. We however need to make sure that the patch result
4015 * is not deposited to a path that is beyond a symbolic link
4018 if (!patch
->is_delete
&& path_is_beyond_symlink(state
, patch
->new_name
))
4019 return error(_("affected file '%s' is beyond a symbolic link"),
4022 if (apply_data(state
, patch
, &st
, ce
) < 0)
4023 return error(_("%s: patch does not apply"), name
);
4024 patch
->rejected
= 0;
4028 static int check_patch_list(struct apply_state
*state
, struct patch
*patch
)
4032 prepare_symlink_changes(state
, patch
);
4033 prepare_fn_table(state
, patch
);
4036 if (state
->apply_verbosity
> verbosity_normal
)
4037 say_patch_name(stderr
,
4038 _("Checking patch %s..."), patch
);
4039 res
= check_patch(state
, patch
);
4043 patch
= patch
->next
;
4048 static int read_apply_cache(struct apply_state
*state
)
4050 if (state
->index_file
)
4051 return read_index_from(state
->repo
->index
, state
->index_file
,
4054 return repo_read_index(state
->repo
);
4057 /* This function tries to read the object name from the current index */
4058 static int get_current_oid(struct apply_state
*state
, const char *path
,
4059 struct object_id
*oid
)
4063 if (read_apply_cache(state
) < 0)
4065 pos
= index_name_pos(state
->repo
->index
, path
, strlen(path
));
4068 oidcpy(oid
, &state
->repo
->index
->cache
[pos
]->oid
);
4072 static int preimage_oid_in_gitlink_patch(struct patch
*p
, struct object_id
*oid
)
4075 * A usable gitlink patch has only one fragment (hunk) that looks like:
4077 * -Subproject commit <old sha1>
4078 * +Subproject commit <new sha1>
4081 * -Subproject commit <old sha1>
4082 * for a removal patch.
4084 struct fragment
*hunk
= p
->fragments
;
4085 static const char heading
[] = "-Subproject commit ";
4088 if (/* does the patch have only one hunk? */
4089 hunk
&& !hunk
->next
&&
4090 /* is its preimage one line? */
4091 hunk
->oldpos
== 1 && hunk
->oldlines
== 1 &&
4092 /* does preimage begin with the heading? */
4093 (preimage
= memchr(hunk
->patch
, '\n', hunk
->size
)) != NULL
&&
4094 starts_with(++preimage
, heading
) &&
4095 /* does it record full SHA-1? */
4096 !get_oid_hex(preimage
+ sizeof(heading
) - 1, oid
) &&
4097 preimage
[sizeof(heading
) + the_hash_algo
->hexsz
- 1] == '\n' &&
4098 /* does the abbreviated name on the index line agree with it? */
4099 starts_with(preimage
+ sizeof(heading
) - 1, p
->old_oid_prefix
))
4100 return 0; /* it all looks fine */
4102 /* we may have full object name on the index line */
4103 return get_oid_hex(p
->old_oid_prefix
, oid
);
4106 /* Build an index that contains just the files needed for a 3way merge */
4107 static int build_fake_ancestor(struct apply_state
*state
, struct patch
*list
)
4109 struct patch
*patch
;
4110 struct index_state result
= INDEX_STATE_INIT(state
->repo
);
4111 struct lock_file lock
= LOCK_INIT
;
4114 /* Once we start supporting the reverse patch, it may be
4115 * worth showing the new sha1 prefix, but until then...
4117 for (patch
= list
; patch
; patch
= patch
->next
) {
4118 struct object_id oid
;
4119 struct cache_entry
*ce
;
4122 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
4123 if (0 < patch
->is_new
)
4126 if (S_ISGITLINK(patch
->old_mode
)) {
4127 if (!preimage_oid_in_gitlink_patch(patch
, &oid
))
4128 ; /* ok, the textual part looks sane */
4130 return error(_("sha1 information is lacking or "
4131 "useless for submodule %s"), name
);
4132 } else if (!get_oid_blob(patch
->old_oid_prefix
, &oid
)) {
4134 } else if (!patch
->lines_added
&& !patch
->lines_deleted
) {
4135 /* mode-only change: update the current */
4136 if (get_current_oid(state
, patch
->old_name
, &oid
))
4137 return error(_("mode change for %s, which is not "
4138 "in current HEAD"), name
);
4140 return error(_("sha1 information is lacking or useless "
4143 ce
= make_cache_entry(&result
, patch
->old_mode
, &oid
, name
, 0, 0);
4145 return error(_("make_cache_entry failed for path '%s'"),
4147 if (add_index_entry(&result
, ce
, ADD_CACHE_OK_TO_ADD
)) {
4148 discard_cache_entry(ce
);
4149 return error(_("could not add %s to temporary index"),
4154 hold_lock_file_for_update(&lock
, state
->fake_ancestor
, LOCK_DIE_ON_ERROR
);
4155 res
= write_locked_index(&result
, &lock
, COMMIT_LOCK
);
4156 discard_index(&result
);
4159 return error(_("could not write temporary index to %s"),
4160 state
->fake_ancestor
);
4165 static void stat_patch_list(struct apply_state
*state
, struct patch
*patch
)
4167 int files
, adds
, dels
;
4169 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
4171 adds
+= patch
->lines_added
;
4172 dels
+= patch
->lines_deleted
;
4173 show_stats(state
, patch
);
4176 print_stat_summary(stdout
, files
, adds
, dels
);
4179 static void numstat_patch_list(struct apply_state
*state
,
4180 struct patch
*patch
)
4182 for ( ; patch
; patch
= patch
->next
) {
4184 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
4185 if (patch
->is_binary
)
4188 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
4189 write_name_quoted(name
, stdout
, state
->line_termination
);
4193 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
4196 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
4198 printf(" %s %s\n", newdelete
, name
);
4201 static void show_mode_change(struct patch
*p
, int show_name
)
4203 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
4205 printf(" mode change %06o => %06o %s\n",
4206 p
->old_mode
, p
->new_mode
, p
->new_name
);
4208 printf(" mode change %06o => %06o\n",
4209 p
->old_mode
, p
->new_mode
);
4213 static void show_rename_copy(struct patch
*p
)
4215 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
4216 const char *old_name
, *new_name
;
4218 /* Find common prefix */
4219 old_name
= p
->old_name
;
4220 new_name
= p
->new_name
;
4222 const char *slash_old
, *slash_new
;
4223 slash_old
= strchr(old_name
, '/');
4224 slash_new
= strchr(new_name
, '/');
4227 slash_old
- old_name
!= slash_new
- new_name
||
4228 memcmp(old_name
, new_name
, slash_new
- new_name
))
4230 old_name
= slash_old
+ 1;
4231 new_name
= slash_new
+ 1;
4233 /* p->old_name through old_name is the common prefix, and old_name and
4234 * new_name through the end of names are renames
4236 if (old_name
!= p
->old_name
)
4237 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
4238 (int)(old_name
- p
->old_name
), p
->old_name
,
4239 old_name
, new_name
, p
->score
);
4241 printf(" %s %s => %s (%d%%)\n", renamecopy
,
4242 p
->old_name
, p
->new_name
, p
->score
);
4243 show_mode_change(p
, 0);
4246 static void summary_patch_list(struct patch
*patch
)
4250 for (p
= patch
; p
; p
= p
->next
) {
4252 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
4253 else if (p
->is_delete
)
4254 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
4256 if (p
->is_rename
|| p
->is_copy
)
4257 show_rename_copy(p
);
4260 printf(" rewrite %s (%d%%)\n",
4261 p
->new_name
, p
->score
);
4262 show_mode_change(p
, 0);
4265 show_mode_change(p
, 1);
4271 static void patch_stats(struct apply_state
*state
, struct patch
*patch
)
4273 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
4275 if (lines
> state
->max_change
)
4276 state
->max_change
= lines
;
4277 if (patch
->old_name
) {
4278 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
4280 len
= strlen(patch
->old_name
);
4281 if (len
> state
->max_len
)
4282 state
->max_len
= len
;
4284 if (patch
->new_name
) {
4285 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
4287 len
= strlen(patch
->new_name
);
4288 if (len
> state
->max_len
)
4289 state
->max_len
= len
;
4293 static int remove_file(struct apply_state
*state
, struct patch
*patch
, int rmdir_empty
)
4295 if (state
->update_index
&& !state
->ita_only
) {
4296 if (remove_file_from_index(state
->repo
->index
, patch
->old_name
) < 0)
4297 return error(_("unable to remove %s from index"), patch
->old_name
);
4299 if (!state
->cached
) {
4300 if (!remove_or_warn(patch
->old_mode
, patch
->old_name
) && rmdir_empty
) {
4301 remove_path(patch
->old_name
);
4307 static int add_index_file(struct apply_state
*state
,
4314 struct cache_entry
*ce
;
4315 int namelen
= strlen(path
);
4317 ce
= make_empty_cache_entry(state
->repo
->index
, namelen
);
4318 memcpy(ce
->name
, path
, namelen
);
4319 ce
->ce_mode
= create_ce_mode(mode
);
4320 ce
->ce_flags
= create_ce_flags(0);
4321 ce
->ce_namelen
= namelen
;
4322 if (state
->ita_only
) {
4323 ce
->ce_flags
|= CE_INTENT_TO_ADD
;
4324 set_object_name_for_intent_to_add_entry(ce
);
4325 } else if (S_ISGITLINK(mode
)) {
4328 if (!skip_prefix(buf
, "Subproject commit ", &s
) ||
4329 get_oid_hex(s
, &ce
->oid
)) {
4330 discard_cache_entry(ce
);
4331 return error(_("corrupt patch for submodule %s"), path
);
4334 if (!state
->cached
) {
4335 if (lstat(path
, &st
) < 0) {
4336 discard_cache_entry(ce
);
4337 return error_errno(_("unable to stat newly "
4338 "created file '%s'"),
4341 fill_stat_cache_info(state
->repo
->index
, ce
, &st
);
4343 if (write_object_file(buf
, size
, OBJ_BLOB
, &ce
->oid
) < 0) {
4344 discard_cache_entry(ce
);
4345 return error(_("unable to create backing store "
4346 "for newly created file %s"), path
);
4349 if (add_index_entry(state
->repo
->index
, ce
, ADD_CACHE_OK_TO_ADD
) < 0) {
4350 discard_cache_entry(ce
);
4351 return error(_("unable to add cache entry for %s"), path
);
4359 * -1 if an unrecoverable error happened
4360 * 0 if everything went well
4361 * 1 if a recoverable error happened
4363 static int try_create_file(struct apply_state
*state
, const char *path
,
4364 unsigned int mode
, const char *buf
,
4368 struct strbuf nbuf
= STRBUF_INIT
;
4370 if (S_ISGITLINK(mode
)) {
4372 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
))
4374 return !!mkdir(path
, 0777);
4377 if (has_symlinks
&& S_ISLNK(mode
))
4378 /* Although buf:size is counted string, it also is NUL
4381 return !!symlink(buf
, path
);
4383 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
4387 if (convert_to_working_tree(state
->repo
->index
, path
, buf
, size
, &nbuf
, NULL
)) {
4392 res
= write_in_full(fd
, buf
, size
) < 0;
4394 error_errno(_("failed to write to '%s'"), path
);
4395 strbuf_release(&nbuf
);
4397 if (close(fd
) < 0 && !res
)
4398 return error_errno(_("closing file '%s'"), path
);
4400 return res
? -1 : 0;
4404 * We optimistically assume that the directories exist,
4405 * which is true 99% of the time anyway. If they don't,
4406 * we create them and try again.
4412 static int create_one_file(struct apply_state
*state
,
4424 * We already try to detect whether files are beyond a symlink in our
4425 * up-front checks. But in the case where symlinks are created by any
4426 * of the intermediate hunks it can happen that our up-front checks
4427 * didn't yet see the symlink, but at the point of arriving here there
4428 * in fact is one. We thus repeat the check for symlinks here.
4430 * Note that this does not make the up-front check obsolete as the
4431 * failure mode is different:
4433 * - The up-front checks cause us to abort before we have written
4434 * anything into the working directory. So when we exit this way the
4435 * working directory remains clean.
4437 * - The checks here happen in the middle of the action where we have
4438 * already started to apply the patch. The end result will be a dirty
4439 * working directory.
4441 * Ideally, we should update the up-front checks to catch what would
4442 * happen when we apply the patch before we damage the working tree.
4443 * We have all the information necessary to do so. But for now, as a
4444 * part of embargoed security work, having this check would serve as a
4445 * reasonable first step.
4447 if (path_is_beyond_symlink(state
, path
))
4448 return error(_("affected file '%s' is beyond a symbolic link"), path
);
4450 res
= try_create_file(state
, path
, mode
, buf
, size
);
4456 if (errno
== ENOENT
) {
4457 if (safe_create_leading_directories_no_share(path
))
4459 res
= try_create_file(state
, path
, mode
, buf
, size
);
4466 if (errno
== EEXIST
|| errno
== EACCES
) {
4467 /* We may be trying to create a file where a directory
4471 if (!lstat(path
, &st
) && (!S_ISDIR(st
.st_mode
) || !rmdir(path
)))
4475 if (errno
== EEXIST
) {
4476 unsigned int nr
= getpid();
4479 char newpath
[PATH_MAX
];
4480 mksnpath(newpath
, sizeof(newpath
), "%s~%u", path
, nr
);
4481 res
= try_create_file(state
, newpath
, mode
, buf
, size
);
4485 if (!rename(newpath
, path
))
4487 unlink_or_warn(newpath
);
4490 if (errno
!= EEXIST
)
4495 return error_errno(_("unable to write file '%s' mode %o"),
4499 static int add_conflicted_stages_file(struct apply_state
*state
,
4500 struct patch
*patch
)
4504 struct cache_entry
*ce
;
4506 if (!state
->update_index
)
4508 namelen
= strlen(patch
->new_name
);
4509 mode
= patch
->new_mode
? patch
->new_mode
: (S_IFREG
| 0644);
4511 remove_file_from_index(state
->repo
->index
, patch
->new_name
);
4512 for (stage
= 1; stage
< 4; stage
++) {
4513 if (is_null_oid(&patch
->threeway_stage
[stage
- 1]))
4515 ce
= make_empty_cache_entry(state
->repo
->index
, namelen
);
4516 memcpy(ce
->name
, patch
->new_name
, namelen
);
4517 ce
->ce_mode
= create_ce_mode(mode
);
4518 ce
->ce_flags
= create_ce_flags(stage
);
4519 ce
->ce_namelen
= namelen
;
4520 oidcpy(&ce
->oid
, &patch
->threeway_stage
[stage
- 1]);
4521 if (add_index_entry(state
->repo
->index
, ce
, ADD_CACHE_OK_TO_ADD
) < 0) {
4522 discard_cache_entry(ce
);
4523 return error(_("unable to add cache entry for %s"),
4531 static int create_file(struct apply_state
*state
, struct patch
*patch
)
4533 char *path
= patch
->new_name
;
4534 unsigned mode
= patch
->new_mode
;
4535 unsigned long size
= patch
->resultsize
;
4536 char *buf
= patch
->result
;
4539 mode
= S_IFREG
| 0644;
4540 if (create_one_file(state
, path
, mode
, buf
, size
))
4543 if (patch
->conflicted_threeway
)
4544 return add_conflicted_stages_file(state
, patch
);
4545 else if (state
->update_index
)
4546 return add_index_file(state
, path
, mode
, buf
, size
);
4550 /* phase zero is to remove, phase one is to create */
4551 static int write_out_one_result(struct apply_state
*state
,
4552 struct patch
*patch
,
4555 if (patch
->is_delete
> 0) {
4557 return remove_file(state
, patch
, 1);
4560 if (patch
->is_new
> 0 || patch
->is_copy
) {
4562 return create_file(state
, patch
);
4566 * Rename or modification boils down to the same
4567 * thing: remove the old, write the new
4570 return remove_file(state
, patch
, patch
->is_rename
);
4572 return create_file(state
, patch
);
4576 static int write_out_one_reject(struct apply_state
*state
, struct patch
*patch
)
4579 char namebuf
[PATH_MAX
];
4580 struct fragment
*frag
;
4582 struct strbuf sb
= STRBUF_INIT
;
4584 for (cnt
= 0, frag
= patch
->fragments
; frag
; frag
= frag
->next
) {
4585 if (!frag
->rejected
)
4591 if (state
->apply_verbosity
> verbosity_normal
)
4592 say_patch_name(stderr
,
4593 _("Applied patch %s cleanly."), patch
);
4597 /* This should not happen, because a removal patch that leaves
4598 * contents are marked "rejected" at the patch level.
4600 if (!patch
->new_name
)
4601 die(_("internal error"));
4603 /* Say this even without --verbose */
4604 strbuf_addf(&sb
, Q_("Applying patch %%s with %d reject...",
4605 "Applying patch %%s with %d rejects...",
4608 if (state
->apply_verbosity
> verbosity_silent
)
4609 say_patch_name(stderr
, sb
.buf
, patch
);
4610 strbuf_release(&sb
);
4612 cnt
= strlen(patch
->new_name
);
4613 if (ARRAY_SIZE(namebuf
) <= cnt
+ 5) {
4614 cnt
= ARRAY_SIZE(namebuf
) - 5;
4615 warning(_("truncating .rej filename to %.*s.rej"),
4616 cnt
- 1, patch
->new_name
);
4618 memcpy(namebuf
, patch
->new_name
, cnt
);
4619 memcpy(namebuf
+ cnt
, ".rej", 5);
4621 rej
= fopen(namebuf
, "w");
4623 return error_errno(_("cannot open %s"), namebuf
);
4625 /* Normal git tools never deal with .rej, so do not pretend
4626 * this is a git patch by saying --git or giving extended
4627 * headers. While at it, maybe please "kompare" that wants
4628 * the trailing TAB and some garbage at the end of line ;-).
4630 fprintf(rej
, "diff a/%s b/%s\t(rejected hunks)\n",
4631 patch
->new_name
, patch
->new_name
);
4632 for (cnt
= 1, frag
= patch
->fragments
;
4634 cnt
++, frag
= frag
->next
) {
4635 if (!frag
->rejected
) {
4636 if (state
->apply_verbosity
> verbosity_silent
)
4637 fprintf_ln(stderr
, _("Hunk #%d applied cleanly."), cnt
);
4640 if (state
->apply_verbosity
> verbosity_silent
)
4641 fprintf_ln(stderr
, _("Rejected hunk #%d."), cnt
);
4642 fprintf(rej
, "%.*s", frag
->size
, frag
->patch
);
4643 if (frag
->patch
[frag
->size
-1] != '\n')
4652 * -1 if an error happened
4653 * 0 if the patch applied cleanly
4654 * 1 if the patch did not apply cleanly
4656 static int write_out_results(struct apply_state
*state
, struct patch
*list
)
4661 struct string_list cpath
= STRING_LIST_INIT_DUP
;
4663 for (phase
= 0; phase
< 2; phase
++) {
4669 if (write_out_one_result(state
, l
, phase
)) {
4670 string_list_clear(&cpath
, 0);
4674 if (write_out_one_reject(state
, l
))
4676 if (l
->conflicted_threeway
) {
4677 string_list_append(&cpath
, l
->new_name
);
4687 struct string_list_item
*item
;
4689 string_list_sort(&cpath
);
4690 if (state
->apply_verbosity
> verbosity_silent
) {
4691 for_each_string_list_item(item
, &cpath
)
4692 fprintf(stderr
, "U %s\n", item
->string
);
4694 string_list_clear(&cpath
, 0);
4697 * rerere relies on the partially merged result being in the working
4698 * tree with conflict markers, but that isn't written with --cached.
4701 repo_rerere(state
->repo
, 0);
4708 * Try to apply a patch.
4711 * -128 if a bad error happened (like patch unreadable)
4712 * -1 if patch did not apply and user cannot deal with it
4713 * 0 if the patch applied
4714 * 1 if the patch did not apply but user might fix it
4716 static int apply_patch(struct apply_state
*state
,
4718 const char *filename
,
4722 struct strbuf buf
= STRBUF_INIT
; /* owns the patch text */
4723 struct patch
*list
= NULL
, **listp
= &list
;
4724 int skipped_patch
= 0;
4726 int flush_attributes
= 0;
4728 state
->patch_input_file
= filename
;
4729 if (read_patch_file(&buf
, fd
) < 0)
4732 while (offset
< buf
.len
) {
4733 struct patch
*patch
;
4736 CALLOC_ARRAY(patch
, 1);
4737 patch
->inaccurate_eof
= !!(options
& APPLY_OPT_INACCURATE_EOF
);
4738 patch
->recount
= !!(options
& APPLY_OPT_RECOUNT
);
4739 nr
= parse_chunk(state
, buf
.buf
+ offset
, buf
.len
- offset
, patch
);
4748 if (state
->apply_in_reverse
)
4749 reverse_patches(patch
);
4750 if (use_patch(state
, patch
)) {
4751 patch_stats(state
, patch
);
4752 if (!list
|| !state
->apply_in_reverse
) {
4754 listp
= &patch
->next
;
4760 if ((patch
->new_name
&&
4761 ends_with_path_components(patch
->new_name
,
4762 GITATTRIBUTES_FILE
)) ||
4764 ends_with_path_components(patch
->old_name
,
4765 GITATTRIBUTES_FILE
)))
4766 flush_attributes
= 1;
4769 if (state
->apply_verbosity
> verbosity_normal
)
4770 say_patch_name(stderr
, _("Skipped patch '%s'."), patch
);
4777 if (!list
&& !skipped_patch
) {
4778 if (!state
->allow_empty
) {
4779 error(_("No valid patches in input (allow with \"--allow-empty\")"));
4785 if (state
->whitespace_error
&& (state
->ws_error_action
== die_on_ws_error
))
4788 state
->update_index
= (state
->check_index
|| state
->ita_only
) && state
->apply
;
4789 if (state
->update_index
&& !is_lock_file_locked(&state
->lock_file
)) {
4790 if (state
->index_file
)
4791 hold_lock_file_for_update(&state
->lock_file
,
4795 repo_hold_locked_index(state
->repo
, &state
->lock_file
,
4799 if (state
->check_index
&& read_apply_cache(state
) < 0) {
4800 error(_("unable to read index file"));
4805 if (state
->check
|| state
->apply
) {
4806 int r
= check_patch_list(state
, list
);
4811 if (r
< 0 && !state
->apply_with_reject
) {
4818 int write_res
= write_out_results(state
, list
);
4819 if (write_res
< 0) {
4823 if (write_res
> 0) {
4824 /* with --3way, we still need to write the index out */
4825 res
= state
->apply_with_reject
? -1 : 1;
4830 if (state
->fake_ancestor
&&
4831 build_fake_ancestor(state
, list
)) {
4836 if (state
->diffstat
&& state
->apply_verbosity
> verbosity_silent
)
4837 stat_patch_list(state
, list
);
4839 if (state
->numstat
&& state
->apply_verbosity
> verbosity_silent
)
4840 numstat_patch_list(state
, list
);
4842 if (state
->summary
&& state
->apply_verbosity
> verbosity_silent
)
4843 summary_patch_list(list
);
4845 if (flush_attributes
)
4846 reset_parsed_attributes();
4848 free_patch_list(list
);
4849 strbuf_release(&buf
);
4850 string_list_clear(&state
->fn_table
, 0);
4854 static int apply_option_parse_exclude(const struct option
*opt
,
4855 const char *arg
, int unset
)
4857 struct apply_state
*state
= opt
->value
;
4859 BUG_ON_OPT_NEG(unset
);
4861 add_name_limit(state
, arg
, 1);
4865 static int apply_option_parse_include(const struct option
*opt
,
4866 const char *arg
, int unset
)
4868 struct apply_state
*state
= opt
->value
;
4870 BUG_ON_OPT_NEG(unset
);
4872 add_name_limit(state
, arg
, 0);
4873 state
->has_include
= 1;
4877 static int apply_option_parse_p(const struct option
*opt
,
4881 struct apply_state
*state
= opt
->value
;
4883 BUG_ON_OPT_NEG(unset
);
4885 state
->p_value
= atoi(arg
);
4886 state
->p_value_known
= 1;
4890 static int apply_option_parse_space_change(const struct option
*opt
,
4891 const char *arg
, int unset
)
4893 struct apply_state
*state
= opt
->value
;
4895 BUG_ON_OPT_ARG(arg
);
4898 state
->ws_ignore_action
= ignore_ws_none
;
4900 state
->ws_ignore_action
= ignore_ws_change
;
4904 static int apply_option_parse_whitespace(const struct option
*opt
,
4905 const char *arg
, int unset
)
4907 struct apply_state
*state
= opt
->value
;
4909 BUG_ON_OPT_NEG(unset
);
4911 state
->whitespace_option
= arg
;
4912 if (parse_whitespace_option(state
, arg
))
4917 static int apply_option_parse_directory(const struct option
*opt
,
4918 const char *arg
, int unset
)
4920 struct apply_state
*state
= opt
->value
;
4922 BUG_ON_OPT_NEG(unset
);
4924 strbuf_reset(&state
->root
);
4925 strbuf_addstr(&state
->root
, arg
);
4926 strbuf_complete(&state
->root
, '/');
4930 int apply_all_patches(struct apply_state
*state
,
4940 for (i
= 0; i
< argc
; i
++) {
4941 const char *arg
= argv
[i
];
4942 char *to_free
= NULL
;
4945 if (!strcmp(arg
, "-")) {
4946 res
= apply_patch(state
, 0, "<stdin>", options
);
4953 arg
= to_free
= prefix_filename(state
->prefix
, arg
);
4955 fd
= open(arg
, O_RDONLY
);
4957 error(_("can't open patch '%s': %s"), arg
, strerror(errno
));
4963 set_default_whitespace_mode(state
);
4964 res
= apply_patch(state
, fd
, arg
, options
);
4971 set_default_whitespace_mode(state
);
4973 res
= apply_patch(state
, 0, "<stdin>", options
);
4979 if (state
->whitespace_error
) {
4980 if (state
->squelch_whitespace_errors
&&
4981 state
->squelch_whitespace_errors
< state
->whitespace_error
) {
4983 state
->whitespace_error
- state
->squelch_whitespace_errors
;
4984 warning(Q_("squelched %d whitespace error",
4985 "squelched %d whitespace errors",
4989 if (state
->ws_error_action
== die_on_ws_error
) {
4990 error(Q_("%d line adds whitespace errors.",
4991 "%d lines add whitespace errors.",
4992 state
->whitespace_error
),
4993 state
->whitespace_error
);
4997 if (state
->applied_after_fixing_ws
&& state
->apply
)
4998 warning(Q_("%d line applied after"
4999 " fixing whitespace errors.",
5000 "%d lines applied after"
5001 " fixing whitespace errors.",
5002 state
->applied_after_fixing_ws
),
5003 state
->applied_after_fixing_ws
);
5004 else if (state
->whitespace_error
)
5005 warning(Q_("%d line adds whitespace errors.",
5006 "%d lines add whitespace errors.",
5007 state
->whitespace_error
),
5008 state
->whitespace_error
);
5011 if (state
->update_index
) {
5012 res
= write_locked_index(state
->repo
->index
, &state
->lock_file
, COMMIT_LOCK
);
5014 error(_("Unable to write new index file"));
5023 rollback_lock_file(&state
->lock_file
);
5025 if (state
->apply_verbosity
<= verbosity_silent
) {
5026 set_error_routine(state
->saved_error_routine
);
5027 set_warn_routine(state
->saved_warn_routine
);
5032 return (res
== -1 ? 1 : 128);
5035 int apply_parse_options(int argc
, const char **argv
,
5036 struct apply_state
*state
,
5037 int *force_apply
, int *options
,
5038 const char * const *apply_usage
)
5040 struct option builtin_apply_options
[] = {
5041 OPT_CALLBACK_F(0, "exclude", state
, N_("path"),
5042 N_("don't apply changes matching the given path"),
5043 PARSE_OPT_NONEG
, apply_option_parse_exclude
),
5044 OPT_CALLBACK_F(0, "include", state
, N_("path"),
5045 N_("apply changes matching the given path"),
5046 PARSE_OPT_NONEG
, apply_option_parse_include
),
5047 OPT_CALLBACK('p', NULL
, state
, N_("num"),
5048 N_("remove <num> leading slashes from traditional diff paths"),
5049 apply_option_parse_p
),
5050 OPT_BOOL(0, "no-add", &state
->no_add
,
5051 N_("ignore additions made by the patch")),
5052 OPT_BOOL(0, "stat", &state
->diffstat
,
5053 N_("instead of applying the patch, output diffstat for the input")),
5054 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
5055 OPT_NOOP_NOARG(0, "binary"),
5056 OPT_BOOL(0, "numstat", &state
->numstat
,
5057 N_("show number of added and deleted lines in decimal notation")),
5058 OPT_BOOL(0, "summary", &state
->summary
,
5059 N_("instead of applying the patch, output a summary for the input")),
5060 OPT_BOOL(0, "check", &state
->check
,
5061 N_("instead of applying the patch, see if the patch is applicable")),
5062 OPT_BOOL(0, "index", &state
->check_index
,
5063 N_("make sure the patch is applicable to the current index")),
5064 OPT_BOOL('N', "intent-to-add", &state
->ita_only
,
5065 N_("mark new files with `git add --intent-to-add`")),
5066 OPT_BOOL(0, "cached", &state
->cached
,
5067 N_("apply a patch without touching the working tree")),
5068 OPT_BOOL_F(0, "unsafe-paths", &state
->unsafe_paths
,
5069 N_("accept a patch that touches outside the working area"),
5070 PARSE_OPT_NOCOMPLETE
),
5071 OPT_BOOL(0, "apply", force_apply
,
5072 N_("also apply the patch (use with --stat/--summary/--check)")),
5073 OPT_BOOL('3', "3way", &state
->threeway
,
5074 N_( "attempt three-way merge, fall back on normal patch if that fails")),
5075 OPT_FILENAME(0, "build-fake-ancestor", &state
->fake_ancestor
,
5076 N_("build a temporary index based on embedded index information")),
5077 /* Think twice before adding "--nul" synonym to this */
5078 OPT_SET_INT('z', NULL
, &state
->line_termination
,
5079 N_("paths are separated with NUL character"), '\0'),
5080 OPT_INTEGER('C', NULL
, &state
->p_context
,
5081 N_("ensure at least <n> lines of context match")),
5082 OPT_CALLBACK(0, "whitespace", state
, N_("action"),
5083 N_("detect new or modified lines that have whitespace errors"),
5084 apply_option_parse_whitespace
),
5085 OPT_CALLBACK_F(0, "ignore-space-change", state
, NULL
,
5086 N_("ignore changes in whitespace when finding context"),
5087 PARSE_OPT_NOARG
, apply_option_parse_space_change
),
5088 OPT_CALLBACK_F(0, "ignore-whitespace", state
, NULL
,
5089 N_("ignore changes in whitespace when finding context"),
5090 PARSE_OPT_NOARG
, apply_option_parse_space_change
),
5091 OPT_BOOL('R', "reverse", &state
->apply_in_reverse
,
5092 N_("apply the patch in reverse")),
5093 OPT_BOOL(0, "unidiff-zero", &state
->unidiff_zero
,
5094 N_("don't expect at least one line of context")),
5095 OPT_BOOL(0, "reject", &state
->apply_with_reject
,
5096 N_("leave the rejected hunks in corresponding *.rej files")),
5097 OPT_BOOL(0, "allow-overlap", &state
->allow_overlap
,
5098 N_("allow overlapping hunks")),
5099 OPT__VERBOSITY(&state
->apply_verbosity
),
5100 OPT_BIT(0, "inaccurate-eof", options
,
5101 N_("tolerate incorrectly detected missing new-line at the end of file"),
5102 APPLY_OPT_INACCURATE_EOF
),
5103 OPT_BIT(0, "recount", options
,
5104 N_("do not trust the line counts in the hunk headers"),
5106 OPT_CALLBACK(0, "directory", state
, N_("root"),
5107 N_("prepend <root> to all filenames"),
5108 apply_option_parse_directory
),
5109 OPT_BOOL(0, "allow-empty", &state
->allow_empty
,
5110 N_("don't return error for empty patches")),
5114 return parse_options(argc
, argv
, state
->prefix
, builtin_apply_options
, apply_usage
, 0);