4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
11 #include "cache-tree.h"
16 #include "string-list.h"
19 #include "parse-options.h"
20 #include "xdiff-interface.h"
28 /* These boolean parameters control how the apply is done */
33 * --check turns on checking that the working tree matches the
34 * files that are being modified, but doesn't apply the patch
35 * --stat does just a diffstat, and doesn't actually apply
36 * --numstat does numeric diffstat, and doesn't actually apply
37 * --index-info shows the old and new index info for paths if available.
38 * --index updates the cache as well.
39 * --cached updates only the cache without ever touching the working tree.
41 static int newfd
= -1;
43 static int state_p_value
= 1;
44 static int p_value_known
;
45 static int check_index
;
46 static int update_index
;
53 static int apply_in_reverse
;
54 static int apply_with_reject
;
55 static int apply_verbosely
;
56 static int allow_overlap
;
59 static int unsafe_paths
;
60 static const char *fake_ancestor
;
61 static int line_termination
= '\n';
62 static unsigned int p_context
= UINT_MAX
;
63 static const char * const apply_usage
[] = {
64 N_("git apply [<options>] [<patch>...]"),
68 static enum ws_error_action
{
73 } ws_error_action
= warn_on_ws_error
;
74 static int whitespace_error
;
75 static int squelch_whitespace_errors
= 5;
76 static int applied_after_fixing_ws
;
78 static enum ws_ignore
{
81 } ws_ignore_action
= ignore_ws_none
;
84 static const char *patch_input_file
;
85 static struct strbuf root
= STRBUF_INIT
;
87 static void parse_whitespace_option(const char *option
)
90 ws_error_action
= warn_on_ws_error
;
93 if (!strcmp(option
, "warn")) {
94 ws_error_action
= warn_on_ws_error
;
97 if (!strcmp(option
, "nowarn")) {
98 ws_error_action
= nowarn_ws_error
;
101 if (!strcmp(option
, "error")) {
102 ws_error_action
= die_on_ws_error
;
105 if (!strcmp(option
, "error-all")) {
106 ws_error_action
= die_on_ws_error
;
107 squelch_whitespace_errors
= 0;
110 if (!strcmp(option
, "strip") || !strcmp(option
, "fix")) {
111 ws_error_action
= correct_ws_error
;
114 die(_("unrecognized whitespace option '%s'"), option
);
117 static void parse_ignorewhitespace_option(const char *option
)
119 if (!option
|| !strcmp(option
, "no") ||
120 !strcmp(option
, "false") || !strcmp(option
, "never") ||
121 !strcmp(option
, "none")) {
122 ws_ignore_action
= ignore_ws_none
;
125 if (!strcmp(option
, "change")) {
126 ws_ignore_action
= ignore_ws_change
;
129 die(_("unrecognized whitespace ignore option '%s'"), option
);
132 static void set_default_whitespace_mode(const char *whitespace_option
)
134 if (!whitespace_option
&& !apply_default_whitespace
)
135 ws_error_action
= (apply
? warn_on_ws_error
: nowarn_ws_error
);
139 * For "diff-stat" like behaviour, we keep track of the biggest change
140 * we've seen, and the longest filename. That allows us to do simple
143 static int max_change
, max_len
;
146 * Various "current state", notably line numbers and what
147 * file (and how) we're patching right now.. The "is_xxxx"
148 * things are flags, where -1 means "don't know yet".
150 static int state_linenr
= 1;
153 * This represents one "hunk" from a patch, starting with
154 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
155 * patch text is pointed at by patch, and its byte length
156 * is stored in size. leading and trailing are the number
160 unsigned long leading
, trailing
;
161 unsigned long oldpos
, oldlines
;
162 unsigned long newpos
, newlines
;
164 * 'patch' is usually borrowed from buf in apply_patch(),
165 * but some codepaths store an allocated buffer.
168 unsigned free_patch
:1,
172 struct fragment
*next
;
176 * When dealing with a binary patch, we reuse "leading" field
177 * to store the type of the binary hunk, either deflated "delta"
178 * or deflated "literal".
180 #define binary_patch_method leading
181 #define BINARY_DELTA_DEFLATED 1
182 #define BINARY_LITERAL_DEFLATED 2
185 * This represents a "patch" to a file, both metainfo changes
186 * such as creation/deletion, filemode and content changes represented
187 * as a series of fragments.
190 char *new_name
, *old_name
, *def_name
;
191 unsigned int old_mode
, new_mode
;
192 int is_new
, is_delete
; /* -1 = unknown, 0 = false, 1 = true */
195 int lines_added
, lines_deleted
;
197 unsigned int is_toplevel_relative
:1;
198 unsigned int inaccurate_eof
:1;
199 unsigned int is_binary
:1;
200 unsigned int is_copy
:1;
201 unsigned int is_rename
:1;
202 unsigned int recount
:1;
203 unsigned int conflicted_threeway
:1;
204 unsigned int direct_to_threeway
:1;
205 struct fragment
*fragments
;
208 char old_sha1_prefix
[41];
209 char new_sha1_prefix
[41];
212 /* three-way fallback result */
213 struct object_id threeway_stage
[3];
216 static void free_fragment_list(struct fragment
*list
)
219 struct fragment
*next
= list
->next
;
220 if (list
->free_patch
)
221 free((char *)list
->patch
);
227 static void free_patch(struct patch
*patch
)
229 free_fragment_list(patch
->fragments
);
230 free(patch
->def_name
);
231 free(patch
->old_name
);
232 free(patch
->new_name
);
237 static void free_patch_list(struct patch
*list
)
240 struct patch
*next
= list
->next
;
247 * A line in a file, len-bytes long (includes the terminating LF,
248 * except for an incomplete line at the end if the file ends with
249 * one), and its contents hashes to 'hash'.
255 #define LINE_COMMON 1
256 #define LINE_PATCHED 2
260 * This represents a "file", which is an array of "lines".
267 struct line
*line_allocated
;
272 * Records filenames that have been touched, in order to handle
273 * the case where more than one patches touch the same file.
276 static struct string_list fn_table
;
278 static uint32_t hash_line(const char *cp
, size_t len
)
282 for (i
= 0, h
= 0; i
< len
; i
++) {
283 if (!isspace(cp
[i
])) {
284 h
= h
* 3 + (cp
[i
] & 0xff);
291 * Compare lines s1 of length n1 and s2 of length n2, ignoring
292 * whitespace difference. Returns 1 if they match, 0 otherwise
294 static int fuzzy_matchlines(const char *s1
, size_t n1
,
295 const char *s2
, size_t n2
)
297 const char *last1
= s1
+ n1
- 1;
298 const char *last2
= s2
+ n2
- 1;
301 /* ignore line endings */
302 while ((*last1
== '\r') || (*last1
== '\n'))
304 while ((*last2
== '\r') || (*last2
== '\n'))
307 /* skip leading whitespaces, if both begin with whitespace */
308 if (s1
<= last1
&& s2
<= last2
&& isspace(*s1
) && isspace(*s2
)) {
309 while (isspace(*s1
) && (s1
<= last1
))
311 while (isspace(*s2
) && (s2
<= last2
))
314 /* early return if both lines are empty */
315 if ((s1
> last1
) && (s2
> last2
))
318 result
= *s1
++ - *s2
++;
320 * Skip whitespace inside. We check for whitespace on
321 * both buffers because we don't want "a b" to match
324 if (isspace(*s1
) && isspace(*s2
)) {
325 while (isspace(*s1
) && s1
<= last1
)
327 while (isspace(*s2
) && s2
<= last2
)
331 * If we reached the end on one side only,
335 ((s2
> last2
) && (s1
<= last1
)) ||
336 ((s1
> last1
) && (s2
<= last2
)))
338 if ((s1
> last1
) && (s2
> last2
))
345 static void add_line_info(struct image
*img
, const char *bol
, size_t len
, unsigned flag
)
347 ALLOC_GROW(img
->line_allocated
, img
->nr
+ 1, img
->alloc
);
348 img
->line_allocated
[img
->nr
].len
= len
;
349 img
->line_allocated
[img
->nr
].hash
= hash_line(bol
, len
);
350 img
->line_allocated
[img
->nr
].flag
= flag
;
355 * "buf" has the file contents to be patched (read from various sources).
356 * attach it to "image" and add line-based index to it.
357 * "image" now owns the "buf".
359 static void prepare_image(struct image
*image
, char *buf
, size_t len
,
360 int prepare_linetable
)
364 memset(image
, 0, sizeof(*image
));
368 if (!prepare_linetable
)
371 ep
= image
->buf
+ image
->len
;
375 for (next
= cp
; next
< ep
&& *next
!= '\n'; next
++)
379 add_line_info(image
, cp
, next
- cp
, 0);
382 image
->line
= image
->line_allocated
;
385 static void clear_image(struct image
*image
)
388 free(image
->line_allocated
);
389 memset(image
, 0, sizeof(*image
));
392 /* fmt must contain _one_ %s and no other substitution */
393 static void say_patch_name(FILE *output
, const char *fmt
, struct patch
*patch
)
395 struct strbuf sb
= STRBUF_INIT
;
397 if (patch
->old_name
&& patch
->new_name
&&
398 strcmp(patch
->old_name
, patch
->new_name
)) {
399 quote_c_style(patch
->old_name
, &sb
, NULL
, 0);
400 strbuf_addstr(&sb
, " => ");
401 quote_c_style(patch
->new_name
, &sb
, NULL
, 0);
403 const char *n
= patch
->new_name
;
406 quote_c_style(n
, &sb
, NULL
, 0);
408 fprintf(output
, fmt
, sb
.buf
);
415 static void read_patch_file(struct strbuf
*sb
, int fd
)
417 if (strbuf_read(sb
, fd
, 0) < 0)
418 die_errno("git apply: failed to read");
421 * Make sure that we have some slop in the buffer
422 * so that we can do speculative "memcmp" etc, and
423 * see to it that it is NUL-filled.
425 strbuf_grow(sb
, SLOP
);
426 memset(sb
->buf
+ sb
->len
, 0, SLOP
);
429 static unsigned long linelen(const char *buffer
, unsigned long size
)
431 unsigned long len
= 0;
434 if (*buffer
++ == '\n')
440 static int is_dev_null(const char *str
)
442 return skip_prefix(str
, "/dev/null", &str
) && isspace(*str
);
448 static int name_terminate(const char *name
, int namelen
, int c
, int terminate
)
450 if (c
== ' ' && !(terminate
& TERM_SPACE
))
452 if (c
== '\t' && !(terminate
& TERM_TAB
))
458 /* remove double slashes to make --index work with such filenames */
459 static char *squash_slash(char *name
)
467 if ((name
[j
++] = name
[i
++]) == '/')
468 while (name
[i
] == '/')
475 static char *find_name_gnu(const char *line
, const char *def
, int p_value
)
477 struct strbuf name
= STRBUF_INIT
;
481 * Proposed "new-style" GNU patch/diff format; see
482 * http://marc.info/?l=git&m=112927316408690&w=2
484 if (unquote_c_style(&name
, line
, NULL
)) {
485 strbuf_release(&name
);
489 for (cp
= name
.buf
; p_value
; p_value
--) {
490 cp
= strchr(cp
, '/');
492 strbuf_release(&name
);
498 strbuf_remove(&name
, 0, cp
- name
.buf
);
500 strbuf_insert(&name
, 0, root
.buf
, root
.len
);
501 return squash_slash(strbuf_detach(&name
, NULL
));
504 static size_t sane_tz_len(const char *line
, size_t len
)
508 if (len
< strlen(" +0500") || line
[len
-strlen(" +0500")] != ' ')
510 tz
= line
+ len
- strlen(" +0500");
512 if (tz
[1] != '+' && tz
[1] != '-')
515 for (p
= tz
+ 2; p
!= line
+ len
; p
++)
519 return line
+ len
- tz
;
522 static size_t tz_with_colon_len(const char *line
, size_t len
)
526 if (len
< strlen(" +08:00") || line
[len
- strlen(":00")] != ':')
528 tz
= line
+ len
- strlen(" +08:00");
530 if (tz
[0] != ' ' || (tz
[1] != '+' && tz
[1] != '-'))
533 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
534 !isdigit(*p
++) || !isdigit(*p
++))
537 return line
+ len
- tz
;
540 static size_t date_len(const char *line
, size_t len
)
542 const char *date
, *p
;
544 if (len
< strlen("72-02-05") || line
[len
-strlen("-05")] != '-')
546 p
= date
= line
+ len
- strlen("72-02-05");
548 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
549 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
550 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a date. */
553 if (date
- line
>= strlen("19") &&
554 isdigit(date
[-1]) && isdigit(date
[-2])) /* 4-digit year */
555 date
-= strlen("19");
557 return line
+ len
- date
;
560 static size_t short_time_len(const char *line
, size_t len
)
562 const char *time
, *p
;
564 if (len
< strlen(" 07:01:32") || line
[len
-strlen(":32")] != ':')
566 p
= time
= line
+ len
- strlen(" 07:01:32");
568 /* Permit 1-digit hours? */
570 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
571 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
572 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a time. */
575 return line
+ len
- time
;
578 static size_t fractional_time_len(const char *line
, size_t len
)
583 /* Expected format: 19:41:17.620000023 */
584 if (!len
|| !isdigit(line
[len
- 1]))
588 /* Fractional seconds. */
589 while (p
> line
&& isdigit(*p
))
594 /* Hours, minutes, and whole seconds. */
595 n
= short_time_len(line
, p
- line
);
599 return line
+ len
- p
+ n
;
602 static size_t trailing_spaces_len(const char *line
, size_t len
)
606 /* Expected format: ' ' x (1 or more) */
607 if (!len
|| line
[len
- 1] != ' ')
614 return line
+ len
- (p
+ 1);
621 static size_t diff_timestamp_len(const char *line
, size_t len
)
623 const char *end
= line
+ len
;
627 * Posix: 2010-07-05 19:41:17
628 * GNU: 2010-07-05 19:41:17.620000023 -0500
631 if (!isdigit(end
[-1]))
634 n
= sane_tz_len(line
, end
- line
);
636 n
= tz_with_colon_len(line
, end
- line
);
639 n
= short_time_len(line
, end
- line
);
641 n
= fractional_time_len(line
, end
- line
);
644 n
= date_len(line
, end
- line
);
645 if (!n
) /* No date. Too bad. */
649 if (end
== line
) /* No space before date. */
651 if (end
[-1] == '\t') { /* Success! */
653 return line
+ len
- end
;
655 if (end
[-1] != ' ') /* No space before date. */
658 /* Whitespace damage. */
659 end
-= trailing_spaces_len(line
, end
- line
);
660 return line
+ len
- end
;
663 static char *find_name_common(const char *line
, const char *def
,
664 int p_value
, const char *end
, int terminate
)
667 const char *start
= NULL
;
671 while (line
!= end
) {
674 if (!end
&& isspace(c
)) {
677 if (name_terminate(start
, line
-start
, c
, terminate
))
681 if (c
== '/' && !--p_value
)
685 return squash_slash(xstrdup_or_null(def
));
688 return squash_slash(xstrdup_or_null(def
));
691 * Generally we prefer the shorter name, especially
692 * if the other one is just a variation of that with
693 * something else tacked on to the end (ie "file.orig"
697 int deflen
= strlen(def
);
698 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
699 return squash_slash(xstrdup(def
));
703 char *ret
= xstrfmt("%s%.*s", root
.buf
, len
, start
);
704 return squash_slash(ret
);
707 return squash_slash(xmemdupz(start
, len
));
710 static char *find_name(const char *line
, char *def
, int p_value
, int terminate
)
713 char *name
= find_name_gnu(line
, def
, p_value
);
718 return find_name_common(line
, def
, p_value
, NULL
, terminate
);
721 static char *find_name_traditional(const char *line
, char *def
, int p_value
)
727 char *name
= find_name_gnu(line
, def
, p_value
);
732 len
= strchrnul(line
, '\n') - line
;
733 date_len
= diff_timestamp_len(line
, len
);
735 return find_name_common(line
, def
, p_value
, NULL
, TERM_TAB
);
738 return find_name_common(line
, def
, p_value
, line
+ len
, 0);
741 static int count_slashes(const char *cp
)
753 * Given the string after "--- " or "+++ ", guess the appropriate
754 * p_value for the given patch.
756 static int guess_p_value(struct apply_state
*state
, const char *nameline
)
761 if (is_dev_null(nameline
))
763 name
= find_name_traditional(nameline
, NULL
, 0);
766 cp
= strchr(name
, '/');
769 else if (state
->prefix
) {
771 * Does it begin with "a/$our-prefix" and such? Then this is
772 * very likely to apply to our directory.
774 if (!strncmp(name
, state
->prefix
, state
->prefix_length
))
775 val
= count_slashes(state
->prefix
);
778 if (!strncmp(cp
, state
->prefix
, state
->prefix_length
))
779 val
= count_slashes(state
->prefix
) + 1;
787 * Does the ---/+++ line have the POSIX timestamp after the last HT?
788 * GNU diff puts epoch there to signal a creation/deletion event. Is
789 * this such a timestamp?
791 static int has_epoch_timestamp(const char *nameline
)
794 * We are only interested in epoch timestamp; any non-zero
795 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
796 * For the same reason, the date must be either 1969-12-31 or
797 * 1970-01-01, and the seconds part must be "00".
799 const char stamp_regexp
[] =
800 "^(1969-12-31|1970-01-01)"
802 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
804 "([-+][0-2][0-9]:?[0-5][0-9])\n";
805 const char *timestamp
= NULL
, *cp
, *colon
;
806 static regex_t
*stamp
;
812 for (cp
= nameline
; *cp
!= '\n'; cp
++) {
819 stamp
= xmalloc(sizeof(*stamp
));
820 if (regcomp(stamp
, stamp_regexp
, REG_EXTENDED
)) {
821 warning(_("Cannot prepare timestamp regexp %s"),
827 status
= regexec(stamp
, timestamp
, ARRAY_SIZE(m
), m
, 0);
829 if (status
!= REG_NOMATCH
)
830 warning(_("regexec returned %d for input: %s"),
835 zoneoffset
= strtol(timestamp
+ m
[3].rm_so
+ 1, (char **) &colon
, 10);
837 zoneoffset
= zoneoffset
* 60 + strtol(colon
+ 1, NULL
, 10);
839 zoneoffset
= (zoneoffset
/ 100) * 60 + (zoneoffset
% 100);
840 if (timestamp
[m
[3].rm_so
] == '-')
841 zoneoffset
= -zoneoffset
;
844 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
845 * (west of GMT) or 1970-01-01 (east of GMT)
847 if ((zoneoffset
< 0 && memcmp(timestamp
, "1969-12-31", 10)) ||
848 (0 <= zoneoffset
&& memcmp(timestamp
, "1970-01-01", 10)))
851 hourminute
= (strtol(timestamp
+ 11, NULL
, 10) * 60 +
852 strtol(timestamp
+ 14, NULL
, 10) -
855 return ((zoneoffset
< 0 && hourminute
== 1440) ||
856 (0 <= zoneoffset
&& !hourminute
));
860 * Get the name etc info from the ---/+++ lines of a traditional patch header
862 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
863 * files, we can happily check the index for a match, but for creating a
864 * new file we should try to match whatever "patch" does. I have no idea.
866 static void parse_traditional_patch(struct apply_state
*state
,
873 first
+= 4; /* skip "--- " */
874 second
+= 4; /* skip "+++ " */
875 if (!p_value_known
) {
877 p
= guess_p_value(state
, first
);
878 q
= guess_p_value(state
, second
);
880 if (0 <= p
&& p
== q
) {
885 if (is_dev_null(first
)) {
887 patch
->is_delete
= 0;
888 name
= find_name_traditional(second
, NULL
, state_p_value
);
889 patch
->new_name
= name
;
890 } else if (is_dev_null(second
)) {
892 patch
->is_delete
= 1;
893 name
= find_name_traditional(first
, NULL
, state_p_value
);
894 patch
->old_name
= name
;
897 first_name
= find_name_traditional(first
, NULL
, state_p_value
);
898 name
= find_name_traditional(second
, first_name
, state_p_value
);
900 if (has_epoch_timestamp(first
)) {
902 patch
->is_delete
= 0;
903 patch
->new_name
= name
;
904 } else if (has_epoch_timestamp(second
)) {
906 patch
->is_delete
= 1;
907 patch
->old_name
= name
;
909 patch
->old_name
= name
;
910 patch
->new_name
= xstrdup_or_null(name
);
914 die(_("unable to find filename in patch at line %d"), state_linenr
);
917 static int gitdiff_hdrend(const char *line
, struct patch
*patch
)
923 * We're anal about diff header consistency, to make
924 * sure that we don't end up having strange ambiguous
925 * patches floating around.
927 * As a result, gitdiff_{old|new}name() will check
928 * their names against any previous information, just
931 #define DIFF_OLD_NAME 0
932 #define DIFF_NEW_NAME 1
934 static void gitdiff_verify_name(const char *line
, int isnull
, char **name
, int side
)
936 if (!*name
&& !isnull
) {
937 *name
= find_name(line
, NULL
, state_p_value
, TERM_TAB
);
942 int len
= strlen(*name
);
945 die(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
946 *name
, state_linenr
);
947 another
= find_name(line
, NULL
, state_p_value
, TERM_TAB
);
948 if (!another
|| memcmp(another
, *name
, len
+ 1))
949 die((side
== DIFF_NEW_NAME
) ?
950 _("git apply: bad git-diff - inconsistent new filename on line %d") :
951 _("git apply: bad git-diff - inconsistent old filename on line %d"), state_linenr
);
954 /* expect "/dev/null" */
955 if (memcmp("/dev/null", line
, 9) || line
[9] != '\n')
956 die(_("git apply: bad git-diff - expected /dev/null on line %d"), state_linenr
);
960 static int gitdiff_oldname(const char *line
, struct patch
*patch
)
962 gitdiff_verify_name(line
, patch
->is_new
, &patch
->old_name
,
967 static int gitdiff_newname(const char *line
, struct patch
*patch
)
969 gitdiff_verify_name(line
, patch
->is_delete
, &patch
->new_name
,
974 static int gitdiff_oldmode(const char *line
, struct patch
*patch
)
976 patch
->old_mode
= strtoul(line
, NULL
, 8);
980 static int gitdiff_newmode(const char *line
, struct patch
*patch
)
982 patch
->new_mode
= strtoul(line
, NULL
, 8);
986 static int gitdiff_delete(const char *line
, struct patch
*patch
)
988 patch
->is_delete
= 1;
989 free(patch
->old_name
);
990 patch
->old_name
= xstrdup_or_null(patch
->def_name
);
991 return gitdiff_oldmode(line
, patch
);
994 static int gitdiff_newfile(const char *line
, struct patch
*patch
)
997 free(patch
->new_name
);
998 patch
->new_name
= xstrdup_or_null(patch
->def_name
);
999 return gitdiff_newmode(line
, patch
);
1002 static int gitdiff_copysrc(const char *line
, struct patch
*patch
)
1005 free(patch
->old_name
);
1006 patch
->old_name
= find_name(line
, NULL
, state_p_value
? state_p_value
- 1 : 0, 0);
1010 static int gitdiff_copydst(const char *line
, struct patch
*patch
)
1013 free(patch
->new_name
);
1014 patch
->new_name
= find_name(line
, NULL
, state_p_value
? state_p_value
- 1 : 0, 0);
1018 static int gitdiff_renamesrc(const char *line
, struct patch
*patch
)
1020 patch
->is_rename
= 1;
1021 free(patch
->old_name
);
1022 patch
->old_name
= find_name(line
, NULL
, state_p_value
? state_p_value
- 1 : 0, 0);
1026 static int gitdiff_renamedst(const char *line
, struct patch
*patch
)
1028 patch
->is_rename
= 1;
1029 free(patch
->new_name
);
1030 patch
->new_name
= find_name(line
, NULL
, state_p_value
? state_p_value
- 1 : 0, 0);
1034 static int gitdiff_similarity(const char *line
, struct patch
*patch
)
1036 unsigned long val
= strtoul(line
, NULL
, 10);
1042 static int gitdiff_dissimilarity(const char *line
, struct patch
*patch
)
1044 unsigned long val
= strtoul(line
, NULL
, 10);
1050 static int gitdiff_index(const char *line
, struct patch
*patch
)
1053 * index line is N hexadecimal, "..", N hexadecimal,
1054 * and optional space with octal mode.
1056 const char *ptr
, *eol
;
1059 ptr
= strchr(line
, '.');
1060 if (!ptr
|| ptr
[1] != '.' || 40 < ptr
- line
)
1063 memcpy(patch
->old_sha1_prefix
, line
, len
);
1064 patch
->old_sha1_prefix
[len
] = 0;
1067 ptr
= strchr(line
, ' ');
1068 eol
= strchrnul(line
, '\n');
1070 if (!ptr
|| eol
< ptr
)
1076 memcpy(patch
->new_sha1_prefix
, line
, len
);
1077 patch
->new_sha1_prefix
[len
] = 0;
1079 patch
->old_mode
= strtoul(ptr
+1, NULL
, 8);
1084 * This is normal for a diff that doesn't change anything: we'll fall through
1085 * into the next diff. Tell the parser to break out.
1087 static int gitdiff_unrecognized(const char *line
, struct patch
*patch
)
1093 * Skip p_value leading components from "line"; as we do not accept
1094 * absolute paths, return NULL in that case.
1096 static const char *skip_tree_prefix(const char *line
, int llen
)
1102 return (llen
&& line
[0] == '/') ? NULL
: line
;
1104 nslash
= state_p_value
;
1105 for (i
= 0; i
< llen
; i
++) {
1107 if (ch
== '/' && --nslash
<= 0)
1108 return (i
== 0) ? NULL
: &line
[i
+ 1];
1114 * This is to extract the same name that appears on "diff --git"
1115 * line. We do not find and return anything if it is a rename
1116 * patch, and it is OK because we will find the name elsewhere.
1117 * We need to reliably find name only when it is mode-change only,
1118 * creation or deletion of an empty file. In any of these cases,
1119 * both sides are the same name under a/ and b/ respectively.
1121 static char *git_header_name(const char *line
, int llen
)
1124 const char *second
= NULL
;
1125 size_t len
, line_len
;
1127 line
+= strlen("diff --git ");
1128 llen
-= strlen("diff --git ");
1132 struct strbuf first
= STRBUF_INIT
;
1133 struct strbuf sp
= STRBUF_INIT
;
1135 if (unquote_c_style(&first
, line
, &second
))
1136 goto free_and_fail1
;
1138 /* strip the a/b prefix including trailing slash */
1139 cp
= skip_tree_prefix(first
.buf
, first
.len
);
1141 goto free_and_fail1
;
1142 strbuf_remove(&first
, 0, cp
- first
.buf
);
1145 * second points at one past closing dq of name.
1146 * find the second name.
1148 while ((second
< line
+ llen
) && isspace(*second
))
1151 if (line
+ llen
<= second
)
1152 goto free_and_fail1
;
1153 if (*second
== '"') {
1154 if (unquote_c_style(&sp
, second
, NULL
))
1155 goto free_and_fail1
;
1156 cp
= skip_tree_prefix(sp
.buf
, sp
.len
);
1158 goto free_and_fail1
;
1159 /* They must match, otherwise ignore */
1160 if (strcmp(cp
, first
.buf
))
1161 goto free_and_fail1
;
1162 strbuf_release(&sp
);
1163 return strbuf_detach(&first
, NULL
);
1166 /* unquoted second */
1167 cp
= skip_tree_prefix(second
, line
+ llen
- second
);
1169 goto free_and_fail1
;
1170 if (line
+ llen
- cp
!= first
.len
||
1171 memcmp(first
.buf
, cp
, first
.len
))
1172 goto free_and_fail1
;
1173 return strbuf_detach(&first
, NULL
);
1176 strbuf_release(&first
);
1177 strbuf_release(&sp
);
1181 /* unquoted first name */
1182 name
= skip_tree_prefix(line
, llen
);
1187 * since the first name is unquoted, a dq if exists must be
1188 * the beginning of the second name.
1190 for (second
= name
; second
< line
+ llen
; second
++) {
1191 if (*second
== '"') {
1192 struct strbuf sp
= STRBUF_INIT
;
1195 if (unquote_c_style(&sp
, second
, NULL
))
1196 goto free_and_fail2
;
1198 np
= skip_tree_prefix(sp
.buf
, sp
.len
);
1200 goto free_and_fail2
;
1202 len
= sp
.buf
+ sp
.len
- np
;
1203 if (len
< second
- name
&&
1204 !strncmp(np
, name
, len
) &&
1205 isspace(name
[len
])) {
1207 strbuf_remove(&sp
, 0, np
- sp
.buf
);
1208 return strbuf_detach(&sp
, NULL
);
1212 strbuf_release(&sp
);
1218 * Accept a name only if it shows up twice, exactly the same
1221 second
= strchr(name
, '\n');
1224 line_len
= second
- name
;
1225 for (len
= 0 ; ; len
++) {
1226 switch (name
[len
]) {
1231 case '\t': case ' ':
1233 * Is this the separator between the preimage
1234 * and the postimage pathname? Again, we are
1235 * only interested in the case where there is
1236 * no rename, as this is only to set def_name
1237 * and a rename patch has the names elsewhere
1238 * in an unambiguous form.
1241 return NULL
; /* no postimage name */
1242 second
= skip_tree_prefix(name
+ len
+ 1,
1243 line_len
- (len
+ 1));
1247 * Does len bytes starting at "name" and "second"
1248 * (that are separated by one HT or SP we just
1249 * found) exactly match?
1251 if (second
[len
] == '\n' && !strncmp(name
, second
, len
))
1252 return xmemdupz(name
, len
);
1257 /* Verify that we recognize the lines following a git header */
1258 static int parse_git_header(const char *line
, int len
, unsigned int size
, struct patch
*patch
)
1260 unsigned long offset
;
1262 /* A git diff has explicit new/delete information, so we don't guess */
1264 patch
->is_delete
= 0;
1267 * Some things may not have the old name in the
1268 * rest of the headers anywhere (pure mode changes,
1269 * or removing or adding empty files), so we get
1270 * the default name from the header.
1272 patch
->def_name
= git_header_name(line
, len
);
1273 if (patch
->def_name
&& root
.len
) {
1274 char *s
= xstrfmt("%s%s", root
.buf
, patch
->def_name
);
1275 free(patch
->def_name
);
1276 patch
->def_name
= s
;
1282 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, state_linenr
++) {
1283 static const struct opentry
{
1285 int (*fn
)(const char *, struct patch
*);
1287 { "@@ -", gitdiff_hdrend
},
1288 { "--- ", gitdiff_oldname
},
1289 { "+++ ", gitdiff_newname
},
1290 { "old mode ", gitdiff_oldmode
},
1291 { "new mode ", gitdiff_newmode
},
1292 { "deleted file mode ", gitdiff_delete
},
1293 { "new file mode ", gitdiff_newfile
},
1294 { "copy from ", gitdiff_copysrc
},
1295 { "copy to ", gitdiff_copydst
},
1296 { "rename old ", gitdiff_renamesrc
},
1297 { "rename new ", gitdiff_renamedst
},
1298 { "rename from ", gitdiff_renamesrc
},
1299 { "rename to ", gitdiff_renamedst
},
1300 { "similarity index ", gitdiff_similarity
},
1301 { "dissimilarity index ", gitdiff_dissimilarity
},
1302 { "index ", gitdiff_index
},
1303 { "", gitdiff_unrecognized
},
1307 len
= linelen(line
, size
);
1308 if (!len
|| line
[len
-1] != '\n')
1310 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
1311 const struct opentry
*p
= optable
+ i
;
1312 int oplen
= strlen(p
->str
);
1313 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
1315 if (p
->fn(line
+ oplen
, patch
) < 0)
1324 static int parse_num(const char *line
, unsigned long *p
)
1328 if (!isdigit(*line
))
1330 *p
= strtoul(line
, &ptr
, 10);
1334 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
1335 unsigned long *p1
, unsigned long *p2
)
1339 if (offset
< 0 || offset
>= len
)
1344 digits
= parse_num(line
, p1
);
1354 digits
= parse_num(line
+1, p2
);
1363 ex
= strlen(expect
);
1366 if (memcmp(line
, expect
, ex
))
1372 static void recount_diff(const char *line
, int size
, struct fragment
*fragment
)
1374 int oldlines
= 0, newlines
= 0, ret
= 0;
1377 warning("recount: ignore empty hunk");
1382 int len
= linelen(line
, size
);
1390 case ' ': case '\n':
1402 ret
= size
< 3 || !starts_with(line
, "@@ ");
1405 ret
= size
< 5 || !starts_with(line
, "diff ");
1412 warning(_("recount: unexpected line: %.*s"),
1413 (int)linelen(line
, size
), line
);
1418 fragment
->oldlines
= oldlines
;
1419 fragment
->newlines
= newlines
;
1423 * Parse a unified diff fragment header of the
1424 * form "@@ -a,b +c,d @@"
1426 static int parse_fragment_header(const char *line
, int len
, struct fragment
*fragment
)
1430 if (!len
|| line
[len
-1] != '\n')
1433 /* Figure out the number of lines in a fragment */
1434 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
1435 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
1440 static int find_header(struct apply_state
*state
,
1444 struct patch
*patch
)
1446 unsigned long offset
, len
;
1448 patch
->is_toplevel_relative
= 0;
1449 patch
->is_rename
= patch
->is_copy
= 0;
1450 patch
->is_new
= patch
->is_delete
= -1;
1451 patch
->old_mode
= patch
->new_mode
= 0;
1452 patch
->old_name
= patch
->new_name
= NULL
;
1453 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, state_linenr
++) {
1454 unsigned long nextlen
;
1456 len
= linelen(line
, size
);
1460 /* Testing this early allows us to take a few shortcuts.. */
1465 * Make sure we don't find any unconnected patch fragments.
1466 * That's a sign that we didn't find a header, and that a
1467 * patch has become corrupted/broken up.
1469 if (!memcmp("@@ -", line
, 4)) {
1470 struct fragment dummy
;
1471 if (parse_fragment_header(line
, len
, &dummy
) < 0)
1473 die(_("patch fragment without header at line %d: %.*s"),
1474 state_linenr
, (int)len
-1, line
);
1481 * Git patch? It might not have a real patch, just a rename
1482 * or mode change, so we handle that specially
1484 if (!memcmp("diff --git ", line
, 11)) {
1485 int git_hdr_len
= parse_git_header(line
, len
, size
, patch
);
1486 if (git_hdr_len
<= len
)
1488 if (!patch
->old_name
&& !patch
->new_name
) {
1489 if (!patch
->def_name
)
1490 die(Q_("git diff header lacks filename information when removing "
1491 "%d leading pathname component (line %d)",
1492 "git diff header lacks filename information when removing "
1493 "%d leading pathname components (line %d)",
1495 state_p_value
, state_linenr
);
1496 patch
->old_name
= xstrdup(patch
->def_name
);
1497 patch
->new_name
= xstrdup(patch
->def_name
);
1499 if (!patch
->is_delete
&& !patch
->new_name
)
1500 die("git diff header lacks filename information "
1501 "(line %d)", state_linenr
);
1502 patch
->is_toplevel_relative
= 1;
1503 *hdrsize
= git_hdr_len
;
1507 /* --- followed by +++ ? */
1508 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
1512 * We only accept unified patches, so we want it to
1513 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1514 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1516 nextlen
= linelen(line
+ len
, size
- len
);
1517 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
1520 /* Ok, we'll consider it a patch */
1521 parse_traditional_patch(state
, line
, line
+len
, patch
);
1522 *hdrsize
= len
+ nextlen
;
1529 static void record_ws_error(unsigned result
, const char *line
, int len
, int linenr
)
1537 if (squelch_whitespace_errors
&&
1538 squelch_whitespace_errors
< whitespace_error
)
1541 err
= whitespace_error_string(result
);
1542 fprintf(stderr
, "%s:%d: %s.\n%.*s\n",
1543 patch_input_file
, linenr
, err
, len
, line
);
1547 static void check_whitespace(const char *line
, int len
, unsigned ws_rule
)
1549 unsigned result
= ws_check(line
+ 1, len
- 1, ws_rule
);
1551 record_ws_error(result
, line
+ 1, len
- 2, state_linenr
);
1555 * Parse a unified diff. Note that this really needs to parse each
1556 * fragment separately, since the only way to know the difference
1557 * between a "---" that is part of a patch, and a "---" that starts
1558 * the next patch is to look at the line counts..
1560 static int parse_fragment(const char *line
, unsigned long size
,
1561 struct patch
*patch
, struct fragment
*fragment
)
1564 int len
= linelen(line
, size
), offset
;
1565 unsigned long oldlines
, newlines
;
1566 unsigned long leading
, trailing
;
1568 offset
= parse_fragment_header(line
, len
, fragment
);
1571 if (offset
> 0 && patch
->recount
)
1572 recount_diff(line
+ offset
, size
- offset
, fragment
);
1573 oldlines
= fragment
->oldlines
;
1574 newlines
= fragment
->newlines
;
1578 /* Parse the thing.. */
1582 added
= deleted
= 0;
1585 offset
+= len
, size
-= len
, line
+= len
, state_linenr
++) {
1586 if (!oldlines
&& !newlines
)
1588 len
= linelen(line
, size
);
1589 if (!len
|| line
[len
-1] != '\n')
1594 case '\n': /* newer GNU diff, an empty context line */
1598 if (!deleted
&& !added
)
1601 if (!apply_in_reverse
&&
1602 ws_error_action
== correct_ws_error
)
1603 check_whitespace(line
, len
, patch
->ws_rule
);
1606 if (apply_in_reverse
&&
1607 ws_error_action
!= nowarn_ws_error
)
1608 check_whitespace(line
, len
, patch
->ws_rule
);
1614 if (!apply_in_reverse
&&
1615 ws_error_action
!= nowarn_ws_error
)
1616 check_whitespace(line
, len
, patch
->ws_rule
);
1623 * We allow "\ No newline at end of file". Depending
1624 * on locale settings when the patch was produced we
1625 * don't know what this line looks like. The only
1626 * thing we do know is that it begins with "\ ".
1627 * Checking for 12 is just for sanity check -- any
1628 * l10n of "\ No newline..." is at least that long.
1631 if (len
< 12 || memcmp(line
, "\\ ", 2))
1636 if (oldlines
|| newlines
)
1638 if (!deleted
&& !added
)
1641 fragment
->leading
= leading
;
1642 fragment
->trailing
= trailing
;
1645 * If a fragment ends with an incomplete line, we failed to include
1646 * it in the above loop because we hit oldlines == newlines == 0
1649 if (12 < size
&& !memcmp(line
, "\\ ", 2))
1650 offset
+= linelen(line
, size
);
1652 patch
->lines_added
+= added
;
1653 patch
->lines_deleted
+= deleted
;
1655 if (0 < patch
->is_new
&& oldlines
)
1656 return error(_("new file depends on old contents"));
1657 if (0 < patch
->is_delete
&& newlines
)
1658 return error(_("deleted file still has contents"));
1663 * We have seen "diff --git a/... b/..." header (or a traditional patch
1664 * header). Read hunks that belong to this patch into fragments and hang
1665 * them to the given patch structure.
1667 * The (fragment->patch, fragment->size) pair points into the memory given
1668 * by the caller, not a copy, when we return.
1670 static int parse_single_patch(const char *line
, unsigned long size
, struct patch
*patch
)
1672 unsigned long offset
= 0;
1673 unsigned long oldlines
= 0, newlines
= 0, context
= 0;
1674 struct fragment
**fragp
= &patch
->fragments
;
1676 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
1677 struct fragment
*fragment
;
1680 fragment
= xcalloc(1, sizeof(*fragment
));
1681 fragment
->linenr
= state_linenr
;
1682 len
= parse_fragment(line
, size
, patch
, fragment
);
1684 die(_("corrupt patch at line %d"), state_linenr
);
1685 fragment
->patch
= line
;
1686 fragment
->size
= len
;
1687 oldlines
+= fragment
->oldlines
;
1688 newlines
+= fragment
->newlines
;
1689 context
+= fragment
->leading
+ fragment
->trailing
;
1692 fragp
= &fragment
->next
;
1700 * If something was removed (i.e. we have old-lines) it cannot
1701 * be creation, and if something was added it cannot be
1702 * deletion. However, the reverse is not true; --unified=0
1703 * patches that only add are not necessarily creation even
1704 * though they do not have any old lines, and ones that only
1705 * delete are not necessarily deletion.
1707 * Unfortunately, a real creation/deletion patch do _not_ have
1708 * any context line by definition, so we cannot safely tell it
1709 * apart with --unified=0 insanity. At least if the patch has
1710 * more than one hunk it is not creation or deletion.
1712 if (patch
->is_new
< 0 &&
1713 (oldlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1715 if (patch
->is_delete
< 0 &&
1716 (newlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1717 patch
->is_delete
= 0;
1719 if (0 < patch
->is_new
&& oldlines
)
1720 die(_("new file %s depends on old contents"), patch
->new_name
);
1721 if (0 < patch
->is_delete
&& newlines
)
1722 die(_("deleted file %s still has contents"), patch
->old_name
);
1723 if (!patch
->is_delete
&& !newlines
&& context
)
1726 "file %s becomes empty but is not deleted"),
1732 static inline int metadata_changes(struct patch
*patch
)
1734 return patch
->is_rename
> 0 ||
1735 patch
->is_copy
> 0 ||
1736 patch
->is_new
> 0 ||
1738 (patch
->old_mode
&& patch
->new_mode
&&
1739 patch
->old_mode
!= patch
->new_mode
);
1742 static char *inflate_it(const void *data
, unsigned long size
,
1743 unsigned long inflated_size
)
1749 memset(&stream
, 0, sizeof(stream
));
1751 stream
.next_in
= (unsigned char *)data
;
1752 stream
.avail_in
= size
;
1753 stream
.next_out
= out
= xmalloc(inflated_size
);
1754 stream
.avail_out
= inflated_size
;
1755 git_inflate_init(&stream
);
1756 st
= git_inflate(&stream
, Z_FINISH
);
1757 git_inflate_end(&stream
);
1758 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1766 * Read a binary hunk and return a new fragment; fragment->patch
1767 * points at an allocated memory that the caller must free, so
1768 * it is marked as "->free_patch = 1".
1770 static struct fragment
*parse_binary_hunk(char **buf_p
,
1771 unsigned long *sz_p
,
1776 * Expect a line that begins with binary patch method ("literal"
1777 * or "delta"), followed by the length of data before deflating.
1778 * a sequence of 'length-byte' followed by base-85 encoded data
1779 * should follow, terminated by a newline.
1781 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1782 * and we would limit the patch line to 66 characters,
1783 * so one line can fit up to 13 groups that would decode
1784 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1785 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1788 unsigned long size
= *sz_p
;
1789 char *buffer
= *buf_p
;
1791 unsigned long origlen
;
1794 struct fragment
*frag
;
1796 llen
= linelen(buffer
, size
);
1801 if (starts_with(buffer
, "delta ")) {
1802 patch_method
= BINARY_DELTA_DEFLATED
;
1803 origlen
= strtoul(buffer
+ 6, NULL
, 10);
1805 else if (starts_with(buffer
, "literal ")) {
1806 patch_method
= BINARY_LITERAL_DEFLATED
;
1807 origlen
= strtoul(buffer
+ 8, NULL
, 10);
1815 int byte_length
, max_byte_length
, newsize
;
1816 llen
= linelen(buffer
, size
);
1820 /* consume the blank line */
1826 * Minimum line is "A00000\n" which is 7-byte long,
1827 * and the line length must be multiple of 5 plus 2.
1829 if ((llen
< 7) || (llen
-2) % 5)
1831 max_byte_length
= (llen
- 2) / 5 * 4;
1832 byte_length
= *buffer
;
1833 if ('A' <= byte_length
&& byte_length
<= 'Z')
1834 byte_length
= byte_length
- 'A' + 1;
1835 else if ('a' <= byte_length
&& byte_length
<= 'z')
1836 byte_length
= byte_length
- 'a' + 27;
1839 /* if the input length was not multiple of 4, we would
1840 * have filler at the end but the filler should never
1843 if (max_byte_length
< byte_length
||
1844 byte_length
<= max_byte_length
- 4)
1846 newsize
= hunk_size
+ byte_length
;
1847 data
= xrealloc(data
, newsize
);
1848 if (decode_85(data
+ hunk_size
, buffer
+ 1, byte_length
))
1850 hunk_size
= newsize
;
1855 frag
= xcalloc(1, sizeof(*frag
));
1856 frag
->patch
= inflate_it(data
, hunk_size
, origlen
);
1857 frag
->free_patch
= 1;
1861 frag
->size
= origlen
;
1865 frag
->binary_patch_method
= patch_method
;
1871 error(_("corrupt binary patch at line %d: %.*s"),
1872 state_linenr
-1, llen
-1, buffer
);
1878 * -1 in case of error,
1879 * the length of the parsed binary patch otherwise
1881 static int parse_binary(char *buffer
, unsigned long size
, struct patch
*patch
)
1884 * We have read "GIT binary patch\n"; what follows is a line
1885 * that says the patch method (currently, either "literal" or
1886 * "delta") and the length of data before deflating; a
1887 * sequence of 'length-byte' followed by base-85 encoded data
1890 * When a binary patch is reversible, there is another binary
1891 * hunk in the same format, starting with patch method (either
1892 * "literal" or "delta") with the length of data, and a sequence
1893 * of length-byte + base-85 encoded data, terminated with another
1894 * empty line. This data, when applied to the postimage, produces
1897 struct fragment
*forward
;
1898 struct fragment
*reverse
;
1902 forward
= parse_binary_hunk(&buffer
, &size
, &status
, &used
);
1903 if (!forward
&& !status
)
1904 /* there has to be one hunk (forward hunk) */
1905 return error(_("unrecognized binary patch at line %d"), state_linenr
-1);
1907 /* otherwise we already gave an error message */
1910 reverse
= parse_binary_hunk(&buffer
, &size
, &status
, &used_1
);
1915 * Not having reverse hunk is not an error, but having
1916 * a corrupt reverse hunk is.
1918 free((void*) forward
->patch
);
1922 forward
->next
= reverse
;
1923 patch
->fragments
= forward
;
1924 patch
->is_binary
= 1;
1928 static void prefix_one(struct apply_state
*state
, char **name
)
1930 char *old_name
= *name
;
1933 *name
= xstrdup(prefix_filename(state
->prefix
, state
->prefix_length
, *name
));
1937 static void prefix_patch(struct apply_state
*state
, struct patch
*p
)
1939 if (!state
->prefix
|| p
->is_toplevel_relative
)
1941 prefix_one(state
, &p
->new_name
);
1942 prefix_one(state
, &p
->old_name
);
1949 static struct string_list limit_by_name
;
1950 static int has_include
;
1951 static void add_name_limit(const char *name
, int exclude
)
1953 struct string_list_item
*it
;
1955 it
= string_list_append(&limit_by_name
, name
);
1956 it
->util
= exclude
? NULL
: (void *) 1;
1959 static int use_patch(struct apply_state
*state
, struct patch
*p
)
1961 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
1964 /* Paths outside are not touched regardless of "--include" */
1965 if (0 < state
->prefix_length
) {
1966 int pathlen
= strlen(pathname
);
1967 if (pathlen
<= state
->prefix_length
||
1968 memcmp(state
->prefix
, pathname
, state
->prefix_length
))
1972 /* See if it matches any of exclude/include rule */
1973 for (i
= 0; i
< limit_by_name
.nr
; i
++) {
1974 struct string_list_item
*it
= &limit_by_name
.items
[i
];
1975 if (!wildmatch(it
->string
, pathname
, 0, NULL
))
1976 return (it
->util
!= NULL
);
1980 * If we had any include, a path that does not match any rule is
1981 * not used. Otherwise, we saw bunch of exclude rules (or none)
1982 * and such a path is used.
1984 return !has_include
;
1989 * Read the patch text in "buffer" that extends for "size" bytes; stop
1990 * reading after seeing a single patch (i.e. changes to a single file).
1991 * Create fragments (i.e. patch hunks) and hang them to the given patch.
1992 * Return the number of bytes consumed, so that the caller can call us
1993 * again for the next patch.
1995 static int parse_chunk(struct apply_state
*state
, char *buffer
, unsigned long size
, struct patch
*patch
)
1997 int hdrsize
, patchsize
;
1998 int offset
= find_header(state
, buffer
, size
, &hdrsize
, patch
);
2003 prefix_patch(state
, patch
);
2005 if (!use_patch(state
, patch
))
2008 patch
->ws_rule
= whitespace_rule(patch
->new_name
2012 patchsize
= parse_single_patch(buffer
+ offset
+ hdrsize
,
2013 size
- offset
- hdrsize
, patch
);
2016 static const char git_binary
[] = "GIT binary patch\n";
2017 int hd
= hdrsize
+ offset
;
2018 unsigned long llen
= linelen(buffer
+ hd
, size
- hd
);
2020 if (llen
== sizeof(git_binary
) - 1 &&
2021 !memcmp(git_binary
, buffer
+ hd
, llen
)) {
2024 used
= parse_binary(buffer
+ hd
+ llen
,
2025 size
- hd
- llen
, patch
);
2029 patchsize
= used
+ llen
;
2033 else if (!memcmp(" differ\n", buffer
+ hd
+ llen
- 8, 8)) {
2034 static const char *binhdr
[] = {
2040 for (i
= 0; binhdr
[i
]; i
++) {
2041 int len
= strlen(binhdr
[i
]);
2042 if (len
< size
- hd
&&
2043 !memcmp(binhdr
[i
], buffer
+ hd
, len
)) {
2045 patch
->is_binary
= 1;
2052 /* Empty patch cannot be applied if it is a text patch
2053 * without metadata change. A binary patch appears
2056 if ((apply
|| check
) &&
2057 (!patch
->is_binary
&& !metadata_changes(patch
)))
2058 die(_("patch with only garbage at line %d"), state_linenr
);
2061 return offset
+ hdrsize
+ patchsize
;
2064 #define swap(a,b) myswap((a),(b),sizeof(a))
2066 #define myswap(a, b, size) do { \
2067 unsigned char mytmp[size]; \
2068 memcpy(mytmp, &a, size); \
2069 memcpy(&a, &b, size); \
2070 memcpy(&b, mytmp, size); \
2073 static void reverse_patches(struct patch
*p
)
2075 for (; p
; p
= p
->next
) {
2076 struct fragment
*frag
= p
->fragments
;
2078 swap(p
->new_name
, p
->old_name
);
2079 swap(p
->new_mode
, p
->old_mode
);
2080 swap(p
->is_new
, p
->is_delete
);
2081 swap(p
->lines_added
, p
->lines_deleted
);
2082 swap(p
->old_sha1_prefix
, p
->new_sha1_prefix
);
2084 for (; frag
; frag
= frag
->next
) {
2085 swap(frag
->newpos
, frag
->oldpos
);
2086 swap(frag
->newlines
, frag
->oldlines
);
2091 static const char pluses
[] =
2092 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2093 static const char minuses
[]=
2094 "----------------------------------------------------------------------";
2096 static void show_stats(struct patch
*patch
)
2098 struct strbuf qname
= STRBUF_INIT
;
2099 char *cp
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
2102 quote_c_style(cp
, &qname
, NULL
, 0);
2105 * "scale" the filename
2111 if (qname
.len
> max
) {
2112 cp
= strchr(qname
.buf
+ qname
.len
+ 3 - max
, '/');
2114 cp
= qname
.buf
+ qname
.len
+ 3 - max
;
2115 strbuf_splice(&qname
, 0, cp
- qname
.buf
, "...", 3);
2118 if (patch
->is_binary
) {
2119 printf(" %-*s | Bin\n", max
, qname
.buf
);
2120 strbuf_release(&qname
);
2124 printf(" %-*s |", max
, qname
.buf
);
2125 strbuf_release(&qname
);
2128 * scale the add/delete
2130 max
= max
+ max_change
> 70 ? 70 - max
: max_change
;
2131 add
= patch
->lines_added
;
2132 del
= patch
->lines_deleted
;
2134 if (max_change
> 0) {
2135 int total
= ((add
+ del
) * max
+ max_change
/ 2) / max_change
;
2136 add
= (add
* max
+ max_change
/ 2) / max_change
;
2139 printf("%5d %.*s%.*s\n", patch
->lines_added
+ patch
->lines_deleted
,
2140 add
, pluses
, del
, minuses
);
2143 static int read_old_data(struct stat
*st
, const char *path
, struct strbuf
*buf
)
2145 switch (st
->st_mode
& S_IFMT
) {
2147 if (strbuf_readlink(buf
, path
, st
->st_size
) < 0)
2148 return error(_("unable to read symlink %s"), path
);
2151 if (strbuf_read_file(buf
, path
, st
->st_size
) != st
->st_size
)
2152 return error(_("unable to open or read %s"), path
);
2153 convert_to_git(path
, buf
->buf
, buf
->len
, buf
, 0);
2161 * Update the preimage, and the common lines in postimage,
2162 * from buffer buf of length len. If postlen is 0 the postimage
2163 * is updated in place, otherwise it's updated on a new buffer
2167 static void update_pre_post_images(struct image
*preimage
,
2168 struct image
*postimage
,
2170 size_t len
, size_t postlen
)
2172 int i
, ctx
, reduced
;
2173 char *new, *old
, *fixed
;
2174 struct image fixed_preimage
;
2177 * Update the preimage with whitespace fixes. Note that we
2178 * are not losing preimage->buf -- apply_one_fragment() will
2181 prepare_image(&fixed_preimage
, buf
, len
, 1);
2183 ? fixed_preimage
.nr
== preimage
->nr
2184 : fixed_preimage
.nr
<= preimage
->nr
);
2185 for (i
= 0; i
< fixed_preimage
.nr
; i
++)
2186 fixed_preimage
.line
[i
].flag
= preimage
->line
[i
].flag
;
2187 free(preimage
->line_allocated
);
2188 *preimage
= fixed_preimage
;
2191 * Adjust the common context lines in postimage. This can be
2192 * done in-place when we are shrinking it with whitespace
2193 * fixing, but needs a new buffer when ignoring whitespace or
2194 * expanding leading tabs to spaces.
2196 * We trust the caller to tell us if the update can be done
2197 * in place (postlen==0) or not.
2199 old
= postimage
->buf
;
2201 new = postimage
->buf
= xmalloc(postlen
);
2204 fixed
= preimage
->buf
;
2206 for (i
= reduced
= ctx
= 0; i
< postimage
->nr
; i
++) {
2207 size_t l_len
= postimage
->line
[i
].len
;
2208 if (!(postimage
->line
[i
].flag
& LINE_COMMON
)) {
2209 /* an added line -- no counterparts in preimage */
2210 memmove(new, old
, l_len
);
2216 /* a common context -- skip it in the original postimage */
2219 /* and find the corresponding one in the fixed preimage */
2220 while (ctx
< preimage
->nr
&&
2221 !(preimage
->line
[ctx
].flag
& LINE_COMMON
)) {
2222 fixed
+= preimage
->line
[ctx
].len
;
2227 * preimage is expected to run out, if the caller
2228 * fixed addition of trailing blank lines.
2230 if (preimage
->nr
<= ctx
) {
2235 /* and copy it in, while fixing the line length */
2236 l_len
= preimage
->line
[ctx
].len
;
2237 memcpy(new, fixed
, l_len
);
2240 postimage
->line
[i
].len
= l_len
;
2245 ? postlen
< new - postimage
->buf
2246 : postimage
->len
< new - postimage
->buf
)
2247 die("BUG: caller miscounted postlen: asked %d, orig = %d, used = %d",
2248 (int)postlen
, (int) postimage
->len
, (int)(new - postimage
->buf
));
2250 /* Fix the length of the whole thing */
2251 postimage
->len
= new - postimage
->buf
;
2252 postimage
->nr
-= reduced
;
2255 static int line_by_line_fuzzy_match(struct image
*img
,
2256 struct image
*preimage
,
2257 struct image
*postimage
,
2265 size_t postlen
= postimage
->len
;
2270 struct strbuf fixed
;
2274 for (i
= 0; i
< preimage_limit
; i
++) {
2275 size_t prelen
= preimage
->line
[i
].len
;
2276 size_t imglen
= img
->line
[try_lno
+i
].len
;
2278 if (!fuzzy_matchlines(img
->buf
+ try + imgoff
, imglen
,
2279 preimage
->buf
+ preoff
, prelen
))
2281 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2282 postlen
+= imglen
- prelen
;
2288 * Ok, the preimage matches with whitespace fuzz.
2290 * imgoff now holds the true length of the target that
2291 * matches the preimage before the end of the file.
2293 * Count the number of characters in the preimage that fall
2294 * beyond the end of the file and make sure that all of them
2295 * are whitespace characters. (This can only happen if
2296 * we are removing blank lines at the end of the file.)
2298 buf
= preimage_eof
= preimage
->buf
+ preoff
;
2299 for ( ; i
< preimage
->nr
; i
++)
2300 preoff
+= preimage
->line
[i
].len
;
2301 preimage_end
= preimage
->buf
+ preoff
;
2302 for ( ; buf
< preimage_end
; buf
++)
2307 * Update the preimage and the common postimage context
2308 * lines to use the same whitespace as the target.
2309 * If whitespace is missing in the target (i.e.
2310 * if the preimage extends beyond the end of the file),
2311 * use the whitespace from the preimage.
2313 extra_chars
= preimage_end
- preimage_eof
;
2314 strbuf_init(&fixed
, imgoff
+ extra_chars
);
2315 strbuf_add(&fixed
, img
->buf
+ try, imgoff
);
2316 strbuf_add(&fixed
, preimage_eof
, extra_chars
);
2317 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2318 update_pre_post_images(preimage
, postimage
,
2319 fixed_buf
, fixed_len
, postlen
);
2323 static int match_fragment(struct image
*img
,
2324 struct image
*preimage
,
2325 struct image
*postimage
,
2329 int match_beginning
, int match_end
)
2332 char *fixed_buf
, *buf
, *orig
, *target
;
2333 struct strbuf fixed
;
2334 size_t fixed_len
, postlen
;
2337 if (preimage
->nr
+ try_lno
<= img
->nr
) {
2339 * The hunk falls within the boundaries of img.
2341 preimage_limit
= preimage
->nr
;
2342 if (match_end
&& (preimage
->nr
+ try_lno
!= img
->nr
))
2344 } else if (ws_error_action
== correct_ws_error
&&
2345 (ws_rule
& WS_BLANK_AT_EOF
)) {
2347 * This hunk extends beyond the end of img, and we are
2348 * removing blank lines at the end of the file. This
2349 * many lines from the beginning of the preimage must
2350 * match with img, and the remainder of the preimage
2353 preimage_limit
= img
->nr
- try_lno
;
2356 * The hunk extends beyond the end of the img and
2357 * we are not removing blanks at the end, so we
2358 * should reject the hunk at this position.
2363 if (match_beginning
&& try_lno
)
2366 /* Quick hash check */
2367 for (i
= 0; i
< preimage_limit
; i
++)
2368 if ((img
->line
[try_lno
+ i
].flag
& LINE_PATCHED
) ||
2369 (preimage
->line
[i
].hash
!= img
->line
[try_lno
+ i
].hash
))
2372 if (preimage_limit
== preimage
->nr
) {
2374 * Do we have an exact match? If we were told to match
2375 * at the end, size must be exactly at try+fragsize,
2376 * otherwise try+fragsize must be still within the preimage,
2377 * and either case, the old piece should match the preimage
2381 ? (try + preimage
->len
== img
->len
)
2382 : (try + preimage
->len
<= img
->len
)) &&
2383 !memcmp(img
->buf
+ try, preimage
->buf
, preimage
->len
))
2387 * The preimage extends beyond the end of img, so
2388 * there cannot be an exact match.
2390 * There must be one non-blank context line that match
2391 * a line before the end of img.
2395 buf
= preimage
->buf
;
2397 for (i
= 0; i
< preimage_limit
; i
++)
2398 buf_end
+= preimage
->line
[i
].len
;
2400 for ( ; buf
< buf_end
; buf
++)
2408 * No exact match. If we are ignoring whitespace, run a line-by-line
2409 * fuzzy matching. We collect all the line length information because
2410 * we need it to adjust whitespace if we match.
2412 if (ws_ignore_action
== ignore_ws_change
)
2413 return line_by_line_fuzzy_match(img
, preimage
, postimage
,
2414 try, try_lno
, preimage_limit
);
2416 if (ws_error_action
!= correct_ws_error
)
2420 * The hunk does not apply byte-by-byte, but the hash says
2421 * it might with whitespace fuzz. We weren't asked to
2422 * ignore whitespace, we were asked to correct whitespace
2423 * errors, so let's try matching after whitespace correction.
2425 * While checking the preimage against the target, whitespace
2426 * errors in both fixed, we count how large the corresponding
2427 * postimage needs to be. The postimage prepared by
2428 * apply_one_fragment() has whitespace errors fixed on added
2429 * lines already, but the common lines were propagated as-is,
2430 * which may become longer when their whitespace errors are
2434 /* First count added lines in postimage */
2436 for (i
= 0; i
< postimage
->nr
; i
++) {
2437 if (!(postimage
->line
[i
].flag
& LINE_COMMON
))
2438 postlen
+= postimage
->line
[i
].len
;
2442 * The preimage may extend beyond the end of the file,
2443 * but in this loop we will only handle the part of the
2444 * preimage that falls within the file.
2446 strbuf_init(&fixed
, preimage
->len
+ 1);
2447 orig
= preimage
->buf
;
2448 target
= img
->buf
+ try;
2449 for (i
= 0; i
< preimage_limit
; i
++) {
2450 size_t oldlen
= preimage
->line
[i
].len
;
2451 size_t tgtlen
= img
->line
[try_lno
+ i
].len
;
2452 size_t fixstart
= fixed
.len
;
2453 struct strbuf tgtfix
;
2456 /* Try fixing the line in the preimage */
2457 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2459 /* Try fixing the line in the target */
2460 strbuf_init(&tgtfix
, tgtlen
);
2461 ws_fix_copy(&tgtfix
, target
, tgtlen
, ws_rule
, NULL
);
2464 * If they match, either the preimage was based on
2465 * a version before our tree fixed whitespace breakage,
2466 * or we are lacking a whitespace-fix patch the tree
2467 * the preimage was based on already had (i.e. target
2468 * has whitespace breakage, the preimage doesn't).
2469 * In either case, we are fixing the whitespace breakages
2470 * so we might as well take the fix together with their
2473 match
= (tgtfix
.len
== fixed
.len
- fixstart
&&
2474 !memcmp(tgtfix
.buf
, fixed
.buf
+ fixstart
,
2475 fixed
.len
- fixstart
));
2477 /* Add the length if this is common with the postimage */
2478 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2479 postlen
+= tgtfix
.len
;
2481 strbuf_release(&tgtfix
);
2491 * Now handle the lines in the preimage that falls beyond the
2492 * end of the file (if any). They will only match if they are
2493 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2496 for ( ; i
< preimage
->nr
; i
++) {
2497 size_t fixstart
= fixed
.len
; /* start of the fixed preimage */
2498 size_t oldlen
= preimage
->line
[i
].len
;
2501 /* Try fixing the line in the preimage */
2502 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2504 for (j
= fixstart
; j
< fixed
.len
; j
++)
2505 if (!isspace(fixed
.buf
[j
]))
2512 * Yes, the preimage is based on an older version that still
2513 * has whitespace breakages unfixed, and fixing them makes the
2514 * hunk match. Update the context lines in the postimage.
2516 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2517 if (postlen
< postimage
->len
)
2519 update_pre_post_images(preimage
, postimage
,
2520 fixed_buf
, fixed_len
, postlen
);
2524 strbuf_release(&fixed
);
2528 static int find_pos(struct image
*img
,
2529 struct image
*preimage
,
2530 struct image
*postimage
,
2533 int match_beginning
, int match_end
)
2536 unsigned long backwards
, forwards
, try;
2537 int backwards_lno
, forwards_lno
, try_lno
;
2540 * If match_beginning or match_end is specified, there is no
2541 * point starting from a wrong line that will never match and
2542 * wander around and wait for a match at the specified end.
2544 if (match_beginning
)
2547 line
= img
->nr
- preimage
->nr
;
2550 * Because the comparison is unsigned, the following test
2551 * will also take care of a negative line number that can
2552 * result when match_end and preimage is larger than the target.
2554 if ((size_t) line
> img
->nr
)
2558 for (i
= 0; i
< line
; i
++)
2559 try += img
->line
[i
].len
;
2562 * There's probably some smart way to do this, but I'll leave
2563 * that to the smart and beautiful people. I'm simple and stupid.
2566 backwards_lno
= line
;
2568 forwards_lno
= line
;
2571 for (i
= 0; ; i
++) {
2572 if (match_fragment(img
, preimage
, postimage
,
2573 try, try_lno
, ws_rule
,
2574 match_beginning
, match_end
))
2578 if (backwards_lno
== 0 && forwards_lno
== img
->nr
)
2582 if (backwards_lno
== 0) {
2587 backwards
-= img
->line
[backwards_lno
].len
;
2589 try_lno
= backwards_lno
;
2591 if (forwards_lno
== img
->nr
) {
2595 forwards
+= img
->line
[forwards_lno
].len
;
2598 try_lno
= forwards_lno
;
2605 static void remove_first_line(struct image
*img
)
2607 img
->buf
+= img
->line
[0].len
;
2608 img
->len
-= img
->line
[0].len
;
2613 static void remove_last_line(struct image
*img
)
2615 img
->len
-= img
->line
[--img
->nr
].len
;
2619 * The change from "preimage" and "postimage" has been found to
2620 * apply at applied_pos (counts in line numbers) in "img".
2621 * Update "img" to remove "preimage" and replace it with "postimage".
2623 static void update_image(struct image
*img
,
2625 struct image
*preimage
,
2626 struct image
*postimage
)
2629 * remove the copy of preimage at offset in img
2630 * and replace it with postimage
2633 size_t remove_count
, insert_count
, applied_at
= 0;
2638 * If we are removing blank lines at the end of img,
2639 * the preimage may extend beyond the end.
2640 * If that is the case, we must be careful only to
2641 * remove the part of the preimage that falls within
2642 * the boundaries of img. Initialize preimage_limit
2643 * to the number of lines in the preimage that falls
2644 * within the boundaries.
2646 preimage_limit
= preimage
->nr
;
2647 if (preimage_limit
> img
->nr
- applied_pos
)
2648 preimage_limit
= img
->nr
- applied_pos
;
2650 for (i
= 0; i
< applied_pos
; i
++)
2651 applied_at
+= img
->line
[i
].len
;
2654 for (i
= 0; i
< preimage_limit
; i
++)
2655 remove_count
+= img
->line
[applied_pos
+ i
].len
;
2656 insert_count
= postimage
->len
;
2658 /* Adjust the contents */
2659 result
= xmalloc(st_add3(st_sub(img
->len
, remove_count
), insert_count
, 1));
2660 memcpy(result
, img
->buf
, applied_at
);
2661 memcpy(result
+ applied_at
, postimage
->buf
, postimage
->len
);
2662 memcpy(result
+ applied_at
+ postimage
->len
,
2663 img
->buf
+ (applied_at
+ remove_count
),
2664 img
->len
- (applied_at
+ remove_count
));
2667 img
->len
+= insert_count
- remove_count
;
2668 result
[img
->len
] = '\0';
2670 /* Adjust the line table */
2671 nr
= img
->nr
+ postimage
->nr
- preimage_limit
;
2672 if (preimage_limit
< postimage
->nr
) {
2674 * NOTE: this knows that we never call remove_first_line()
2675 * on anything other than pre/post image.
2677 REALLOC_ARRAY(img
->line
, nr
);
2678 img
->line_allocated
= img
->line
;
2680 if (preimage_limit
!= postimage
->nr
)
2681 memmove(img
->line
+ applied_pos
+ postimage
->nr
,
2682 img
->line
+ applied_pos
+ preimage_limit
,
2683 (img
->nr
- (applied_pos
+ preimage_limit
)) *
2684 sizeof(*img
->line
));
2685 memcpy(img
->line
+ applied_pos
,
2687 postimage
->nr
* sizeof(*img
->line
));
2689 for (i
= 0; i
< postimage
->nr
; i
++)
2690 img
->line
[applied_pos
+ i
].flag
|= LINE_PATCHED
;
2695 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2696 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2697 * replace the part of "img" with "postimage" text.
2699 static int apply_one_fragment(struct apply_state
*state
,
2700 struct image
*img
, struct fragment
*frag
,
2701 int inaccurate_eof
, unsigned ws_rule
,
2704 int match_beginning
, match_end
;
2705 const char *patch
= frag
->patch
;
2706 int size
= frag
->size
;
2707 char *old
, *oldlines
;
2708 struct strbuf newlines
;
2709 int new_blank_lines_at_end
= 0;
2710 int found_new_blank_lines_at_end
= 0;
2711 int hunk_linenr
= frag
->linenr
;
2712 unsigned long leading
, trailing
;
2713 int pos
, applied_pos
;
2714 struct image preimage
;
2715 struct image postimage
;
2717 memset(&preimage
, 0, sizeof(preimage
));
2718 memset(&postimage
, 0, sizeof(postimage
));
2719 oldlines
= xmalloc(size
);
2720 strbuf_init(&newlines
, size
);
2725 int len
= linelen(patch
, size
);
2727 int added_blank_line
= 0;
2728 int is_blank_context
= 0;
2735 * "plen" is how much of the line we should use for
2736 * the actual patch data. Normally we just remove the
2737 * first character on the line, but if the line is
2738 * followed by "\ No newline", then we also remove the
2739 * last one (which is the newline, of course).
2742 if (len
< size
&& patch
[len
] == '\\')
2745 if (apply_in_reverse
) {
2748 else if (first
== '+')
2754 /* Newer GNU diff, empty context line */
2756 /* ... followed by '\No newline'; nothing */
2759 strbuf_addch(&newlines
, '\n');
2760 add_line_info(&preimage
, "\n", 1, LINE_COMMON
);
2761 add_line_info(&postimage
, "\n", 1, LINE_COMMON
);
2762 is_blank_context
= 1;
2765 if (plen
&& (ws_rule
& WS_BLANK_AT_EOF
) &&
2766 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2767 is_blank_context
= 1;
2769 memcpy(old
, patch
+ 1, plen
);
2770 add_line_info(&preimage
, old
, plen
,
2771 (first
== ' ' ? LINE_COMMON
: 0));
2775 /* Fall-through for ' ' */
2777 /* --no-add does not add new lines */
2778 if (first
== '+' && no_add
)
2781 start
= newlines
.len
;
2783 !whitespace_error
||
2784 ws_error_action
!= correct_ws_error
) {
2785 strbuf_add(&newlines
, patch
+ 1, plen
);
2788 ws_fix_copy(&newlines
, patch
+ 1, plen
, ws_rule
, &applied_after_fixing_ws
);
2790 add_line_info(&postimage
, newlines
.buf
+ start
, newlines
.len
- start
,
2791 (first
== '+' ? 0 : LINE_COMMON
));
2793 (ws_rule
& WS_BLANK_AT_EOF
) &&
2794 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2795 added_blank_line
= 1;
2797 case '@': case '\\':
2798 /* Ignore it, we already handled it */
2801 if (apply_verbosely
)
2802 error(_("invalid start of line: '%c'"), first
);
2806 if (added_blank_line
) {
2807 if (!new_blank_lines_at_end
)
2808 found_new_blank_lines_at_end
= hunk_linenr
;
2809 new_blank_lines_at_end
++;
2811 else if (is_blank_context
)
2814 new_blank_lines_at_end
= 0;
2819 if (inaccurate_eof
&&
2820 old
> oldlines
&& old
[-1] == '\n' &&
2821 newlines
.len
> 0 && newlines
.buf
[newlines
.len
- 1] == '\n') {
2823 strbuf_setlen(&newlines
, newlines
.len
- 1);
2826 leading
= frag
->leading
;
2827 trailing
= frag
->trailing
;
2830 * A hunk to change lines at the beginning would begin with
2832 * but we need to be careful. -U0 that inserts before the second
2833 * line also has this pattern.
2835 * And a hunk to add to an empty file would begin with
2838 * In other words, a hunk that is (frag->oldpos <= 1) with or
2839 * without leading context must match at the beginning.
2841 match_beginning
= (!frag
->oldpos
||
2842 (frag
->oldpos
== 1 && !state
->unidiff_zero
));
2845 * A hunk without trailing lines must match at the end.
2846 * However, we simply cannot tell if a hunk must match end
2847 * from the lack of trailing lines if the patch was generated
2848 * with unidiff without any context.
2850 match_end
= !state
->unidiff_zero
&& !trailing
;
2852 pos
= frag
->newpos
? (frag
->newpos
- 1) : 0;
2853 preimage
.buf
= oldlines
;
2854 preimage
.len
= old
- oldlines
;
2855 postimage
.buf
= newlines
.buf
;
2856 postimage
.len
= newlines
.len
;
2857 preimage
.line
= preimage
.line_allocated
;
2858 postimage
.line
= postimage
.line_allocated
;
2862 applied_pos
= find_pos(img
, &preimage
, &postimage
, pos
,
2863 ws_rule
, match_beginning
, match_end
);
2865 if (applied_pos
>= 0)
2868 /* Am I at my context limits? */
2869 if ((leading
<= p_context
) && (trailing
<= p_context
))
2871 if (match_beginning
|| match_end
) {
2872 match_beginning
= match_end
= 0;
2877 * Reduce the number of context lines; reduce both
2878 * leading and trailing if they are equal otherwise
2879 * just reduce the larger context.
2881 if (leading
>= trailing
) {
2882 remove_first_line(&preimage
);
2883 remove_first_line(&postimage
);
2887 if (trailing
> leading
) {
2888 remove_last_line(&preimage
);
2889 remove_last_line(&postimage
);
2894 if (applied_pos
>= 0) {
2895 if (new_blank_lines_at_end
&&
2896 preimage
.nr
+ applied_pos
>= img
->nr
&&
2897 (ws_rule
& WS_BLANK_AT_EOF
) &&
2898 ws_error_action
!= nowarn_ws_error
) {
2899 record_ws_error(WS_BLANK_AT_EOF
, "+", 1,
2900 found_new_blank_lines_at_end
);
2901 if (ws_error_action
== correct_ws_error
) {
2902 while (new_blank_lines_at_end
--)
2903 remove_last_line(&postimage
);
2906 * We would want to prevent write_out_results()
2907 * from taking place in apply_patch() that follows
2908 * the callchain led us here, which is:
2909 * apply_patch->check_patch_list->check_patch->
2910 * apply_data->apply_fragments->apply_one_fragment
2912 if (ws_error_action
== die_on_ws_error
)
2916 if (apply_verbosely
&& applied_pos
!= pos
) {
2917 int offset
= applied_pos
- pos
;
2918 if (apply_in_reverse
)
2919 offset
= 0 - offset
;
2921 Q_("Hunk #%d succeeded at %d (offset %d line).",
2922 "Hunk #%d succeeded at %d (offset %d lines).",
2924 nth_fragment
, applied_pos
+ 1, offset
);
2928 * Warn if it was necessary to reduce the number
2931 if ((leading
!= frag
->leading
) ||
2932 (trailing
!= frag
->trailing
))
2933 fprintf_ln(stderr
, _("Context reduced to (%ld/%ld)"
2934 " to apply fragment at %d"),
2935 leading
, trailing
, applied_pos
+1);
2936 update_image(img
, applied_pos
, &preimage
, &postimage
);
2938 if (apply_verbosely
)
2939 error(_("while searching for:\n%.*s"),
2940 (int)(old
- oldlines
), oldlines
);
2945 strbuf_release(&newlines
);
2946 free(preimage
.line_allocated
);
2947 free(postimage
.line_allocated
);
2949 return (applied_pos
< 0);
2952 static int apply_binary_fragment(struct image
*img
, struct patch
*patch
)
2954 struct fragment
*fragment
= patch
->fragments
;
2959 return error(_("missing binary patch data for '%s'"),
2964 /* Binary patch is irreversible without the optional second hunk */
2965 if (apply_in_reverse
) {
2966 if (!fragment
->next
)
2967 return error("cannot reverse-apply a binary patch "
2968 "without the reverse hunk to '%s'",
2970 ? patch
->new_name
: patch
->old_name
);
2971 fragment
= fragment
->next
;
2973 switch (fragment
->binary_patch_method
) {
2974 case BINARY_DELTA_DEFLATED
:
2975 dst
= patch_delta(img
->buf
, img
->len
, fragment
->patch
,
2976 fragment
->size
, &len
);
2983 case BINARY_LITERAL_DEFLATED
:
2985 img
->len
= fragment
->size
;
2986 img
->buf
= xmemdupz(fragment
->patch
, img
->len
);
2993 * Replace "img" with the result of applying the binary patch.
2994 * The binary patch data itself in patch->fragment is still kept
2995 * but the preimage prepared by the caller in "img" is freed here
2996 * or in the helper function apply_binary_fragment() this calls.
2998 static int apply_binary(struct image
*img
, struct patch
*patch
)
3000 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3001 unsigned char sha1
[20];
3004 * For safety, we require patch index line to contain
3005 * full 40-byte textual SHA1 for old and new, at least for now.
3007 if (strlen(patch
->old_sha1_prefix
) != 40 ||
3008 strlen(patch
->new_sha1_prefix
) != 40 ||
3009 get_sha1_hex(patch
->old_sha1_prefix
, sha1
) ||
3010 get_sha1_hex(patch
->new_sha1_prefix
, sha1
))
3011 return error("cannot apply binary patch to '%s' "
3012 "without full index line", name
);
3014 if (patch
->old_name
) {
3016 * See if the old one matches what the patch
3019 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
3020 if (strcmp(sha1_to_hex(sha1
), patch
->old_sha1_prefix
))
3021 return error("the patch applies to '%s' (%s), "
3022 "which does not match the "
3023 "current contents.",
3024 name
, sha1_to_hex(sha1
));
3027 /* Otherwise, the old one must be empty. */
3029 return error("the patch applies to an empty "
3030 "'%s' but it is not empty", name
);
3033 get_sha1_hex(patch
->new_sha1_prefix
, sha1
);
3034 if (is_null_sha1(sha1
)) {
3036 return 0; /* deletion patch */
3039 if (has_sha1_file(sha1
)) {
3040 /* We already have the postimage */
3041 enum object_type type
;
3045 result
= read_sha1_file(sha1
, &type
, &size
);
3047 return error("the necessary postimage %s for "
3048 "'%s' cannot be read",
3049 patch
->new_sha1_prefix
, name
);
3055 * We have verified buf matches the preimage;
3056 * apply the patch data to it, which is stored
3057 * in the patch->fragments->{patch,size}.
3059 if (apply_binary_fragment(img
, patch
))
3060 return error(_("binary patch does not apply to '%s'"),
3063 /* verify that the result matches */
3064 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
3065 if (strcmp(sha1_to_hex(sha1
), patch
->new_sha1_prefix
))
3066 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3067 name
, patch
->new_sha1_prefix
, sha1_to_hex(sha1
));
3073 static int apply_fragments(struct apply_state
*state
, struct image
*img
, struct patch
*patch
)
3075 struct fragment
*frag
= patch
->fragments
;
3076 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3077 unsigned ws_rule
= patch
->ws_rule
;
3078 unsigned inaccurate_eof
= patch
->inaccurate_eof
;
3081 if (patch
->is_binary
)
3082 return apply_binary(img
, patch
);
3086 if (apply_one_fragment(state
, img
, frag
, inaccurate_eof
, ws_rule
, nth
)) {
3087 error(_("patch failed: %s:%ld"), name
, frag
->oldpos
);
3088 if (!apply_with_reject
)
3097 static int read_blob_object(struct strbuf
*buf
, const unsigned char *sha1
, unsigned mode
)
3099 if (S_ISGITLINK(mode
)) {
3100 strbuf_grow(buf
, 100);
3101 strbuf_addf(buf
, "Subproject commit %s\n", sha1_to_hex(sha1
));
3103 enum object_type type
;
3107 result
= read_sha1_file(sha1
, &type
, &sz
);
3110 /* XXX read_sha1_file NUL-terminates */
3111 strbuf_attach(buf
, result
, sz
, sz
+ 1);
3116 static int read_file_or_gitlink(const struct cache_entry
*ce
, struct strbuf
*buf
)
3120 return read_blob_object(buf
, ce
->sha1
, ce
->ce_mode
);
3123 static struct patch
*in_fn_table(const char *name
)
3125 struct string_list_item
*item
;
3130 item
= string_list_lookup(&fn_table
, name
);
3132 return (struct patch
*)item
->util
;
3138 * item->util in the filename table records the status of the path.
3139 * Usually it points at a patch (whose result records the contents
3140 * of it after applying it), but it could be PATH_WAS_DELETED for a
3141 * path that a previously applied patch has already removed, or
3142 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3144 * The latter is needed to deal with a case where two paths A and B
3145 * are swapped by first renaming A to B and then renaming B to A;
3146 * moving A to B should not be prevented due to presence of B as we
3147 * will remove it in a later patch.
3149 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3150 #define PATH_WAS_DELETED ((struct patch *) -1)
3152 static int to_be_deleted(struct patch
*patch
)
3154 return patch
== PATH_TO_BE_DELETED
;
3157 static int was_deleted(struct patch
*patch
)
3159 return patch
== PATH_WAS_DELETED
;
3162 static void add_to_fn_table(struct patch
*patch
)
3164 struct string_list_item
*item
;
3167 * Always add new_name unless patch is a deletion
3168 * This should cover the cases for normal diffs,
3169 * file creations and copies
3171 if (patch
->new_name
!= NULL
) {
3172 item
= string_list_insert(&fn_table
, patch
->new_name
);
3177 * store a failure on rename/deletion cases because
3178 * later chunks shouldn't patch old names
3180 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3181 item
= string_list_insert(&fn_table
, patch
->old_name
);
3182 item
->util
= PATH_WAS_DELETED
;
3186 static void prepare_fn_table(struct patch
*patch
)
3189 * store information about incoming file deletion
3192 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3193 struct string_list_item
*item
;
3194 item
= string_list_insert(&fn_table
, patch
->old_name
);
3195 item
->util
= PATH_TO_BE_DELETED
;
3197 patch
= patch
->next
;
3201 static int checkout_target(struct index_state
*istate
,
3202 struct cache_entry
*ce
, struct stat
*st
)
3204 struct checkout costate
;
3206 memset(&costate
, 0, sizeof(costate
));
3207 costate
.base_dir
= "";
3208 costate
.refresh_cache
= 1;
3209 costate
.istate
= istate
;
3210 if (checkout_entry(ce
, &costate
, NULL
) || lstat(ce
->name
, st
))
3211 return error(_("cannot checkout %s"), ce
->name
);
3215 static struct patch
*previous_patch(struct patch
*patch
, int *gone
)
3217 struct patch
*previous
;
3220 if (patch
->is_copy
|| patch
->is_rename
)
3221 return NULL
; /* "git" patches do not depend on the order */
3223 previous
= in_fn_table(patch
->old_name
);
3227 if (to_be_deleted(previous
))
3228 return NULL
; /* the deletion hasn't happened yet */
3230 if (was_deleted(previous
))
3236 static int verify_index_match(const struct cache_entry
*ce
, struct stat
*st
)
3238 if (S_ISGITLINK(ce
->ce_mode
)) {
3239 if (!S_ISDIR(st
->st_mode
))
3243 return ce_match_stat(ce
, st
, CE_MATCH_IGNORE_VALID
|CE_MATCH_IGNORE_SKIP_WORKTREE
);
3246 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3248 static int load_patch_target(struct strbuf
*buf
,
3249 const struct cache_entry
*ce
,
3252 unsigned expected_mode
)
3254 if (cached
|| check_index
) {
3255 if (read_file_or_gitlink(ce
, buf
))
3256 return error(_("read of %s failed"), name
);
3258 if (S_ISGITLINK(expected_mode
)) {
3260 return read_file_or_gitlink(ce
, buf
);
3262 return SUBMODULE_PATCH_WITHOUT_INDEX
;
3263 } else if (has_symlink_leading_path(name
, strlen(name
))) {
3264 return error(_("reading from '%s' beyond a symbolic link"), name
);
3266 if (read_old_data(st
, name
, buf
))
3267 return error(_("read of %s failed"), name
);
3274 * We are about to apply "patch"; populate the "image" with the
3275 * current version we have, from the working tree or from the index,
3276 * depending on the situation e.g. --cached/--index. If we are
3277 * applying a non-git patch that incrementally updates the tree,
3278 * we read from the result of a previous diff.
3280 static int load_preimage(struct image
*image
,
3281 struct patch
*patch
, struct stat
*st
,
3282 const struct cache_entry
*ce
)
3284 struct strbuf buf
= STRBUF_INIT
;
3287 struct patch
*previous
;
3290 previous
= previous_patch(patch
, &status
);
3292 return error(_("path %s has been renamed/deleted"),
3295 /* We have a patched copy in memory; use that. */
3296 strbuf_add(&buf
, previous
->result
, previous
->resultsize
);
3298 status
= load_patch_target(&buf
, ce
, st
,
3299 patch
->old_name
, patch
->old_mode
);
3302 else if (status
== SUBMODULE_PATCH_WITHOUT_INDEX
) {
3304 * There is no way to apply subproject
3305 * patch without looking at the index.
3306 * NEEDSWORK: shouldn't this be flagged
3309 free_fragment_list(patch
->fragments
);
3310 patch
->fragments
= NULL
;
3311 } else if (status
) {
3312 return error(_("read of %s failed"), patch
->old_name
);
3316 img
= strbuf_detach(&buf
, &len
);
3317 prepare_image(image
, img
, len
, !patch
->is_binary
);
3321 static int three_way_merge(struct image
*image
,
3323 const unsigned char *base
,
3324 const unsigned char *ours
,
3325 const unsigned char *theirs
)
3327 mmfile_t base_file
, our_file
, their_file
;
3328 mmbuffer_t result
= { NULL
};
3331 read_mmblob(&base_file
, base
);
3332 read_mmblob(&our_file
, ours
);
3333 read_mmblob(&their_file
, theirs
);
3334 status
= ll_merge(&result
, path
,
3337 &their_file
, "theirs", NULL
);
3338 free(base_file
.ptr
);
3340 free(their_file
.ptr
);
3341 if (status
< 0 || !result
.ptr
) {
3346 image
->buf
= result
.ptr
;
3347 image
->len
= result
.size
;
3353 * When directly falling back to add/add three-way merge, we read from
3354 * the current contents of the new_name. In no cases other than that
3355 * this function will be called.
3357 static int load_current(struct image
*image
, struct patch
*patch
)
3359 struct strbuf buf
= STRBUF_INIT
;
3364 struct cache_entry
*ce
;
3365 char *name
= patch
->new_name
;
3366 unsigned mode
= patch
->new_mode
;
3369 die("BUG: patch to %s is not a creation", patch
->old_name
);
3371 pos
= cache_name_pos(name
, strlen(name
));
3373 return error(_("%s: does not exist in index"), name
);
3374 ce
= active_cache
[pos
];
3375 if (lstat(name
, &st
)) {
3376 if (errno
!= ENOENT
)
3377 return error(_("%s: %s"), name
, strerror(errno
));
3378 if (checkout_target(&the_index
, ce
, &st
))
3381 if (verify_index_match(ce
, &st
))
3382 return error(_("%s: does not match index"), name
);
3384 status
= load_patch_target(&buf
, ce
, &st
, name
, mode
);
3389 img
= strbuf_detach(&buf
, &len
);
3390 prepare_image(image
, img
, len
, !patch
->is_binary
);
3394 static int try_threeway(struct apply_state
*state
,
3395 struct image
*image
,
3396 struct patch
*patch
,
3398 const struct cache_entry
*ce
)
3400 unsigned char pre_sha1
[20], post_sha1
[20], our_sha1
[20];
3401 struct strbuf buf
= STRBUF_INIT
;
3405 struct image tmp_image
;
3407 /* No point falling back to 3-way merge in these cases */
3408 if (patch
->is_delete
||
3409 S_ISGITLINK(patch
->old_mode
) || S_ISGITLINK(patch
->new_mode
))
3412 /* Preimage the patch was prepared for */
3414 write_sha1_file("", 0, blob_type
, pre_sha1
);
3415 else if (get_sha1(patch
->old_sha1_prefix
, pre_sha1
) ||
3416 read_blob_object(&buf
, pre_sha1
, patch
->old_mode
))
3417 return error("repository lacks the necessary blob to fall back on 3-way merge.");
3419 fprintf(stderr
, "Falling back to three-way merge...\n");
3421 img
= strbuf_detach(&buf
, &len
);
3422 prepare_image(&tmp_image
, img
, len
, 1);
3423 /* Apply the patch to get the post image */
3424 if (apply_fragments(state
, &tmp_image
, patch
) < 0) {
3425 clear_image(&tmp_image
);
3428 /* post_sha1[] is theirs */
3429 write_sha1_file(tmp_image
.buf
, tmp_image
.len
, blob_type
, post_sha1
);
3430 clear_image(&tmp_image
);
3432 /* our_sha1[] is ours */
3433 if (patch
->is_new
) {
3434 if (load_current(&tmp_image
, patch
))
3435 return error("cannot read the current contents of '%s'",
3438 if (load_preimage(&tmp_image
, patch
, st
, ce
))
3439 return error("cannot read the current contents of '%s'",
3442 write_sha1_file(tmp_image
.buf
, tmp_image
.len
, blob_type
, our_sha1
);
3443 clear_image(&tmp_image
);
3445 /* in-core three-way merge between post and our using pre as base */
3446 status
= three_way_merge(image
, patch
->new_name
,
3447 pre_sha1
, our_sha1
, post_sha1
);
3449 fprintf(stderr
, "Failed to fall back on three-way merge...\n");
3454 patch
->conflicted_threeway
= 1;
3456 oidclr(&patch
->threeway_stage
[0]);
3458 hashcpy(patch
->threeway_stage
[0].hash
, pre_sha1
);
3459 hashcpy(patch
->threeway_stage
[1].hash
, our_sha1
);
3460 hashcpy(patch
->threeway_stage
[2].hash
, post_sha1
);
3461 fprintf(stderr
, "Applied patch to '%s' with conflicts.\n", patch
->new_name
);
3463 fprintf(stderr
, "Applied patch to '%s' cleanly.\n", patch
->new_name
);
3468 static int apply_data(struct apply_state
*state
, struct patch
*patch
,
3469 struct stat
*st
, const struct cache_entry
*ce
)
3473 if (load_preimage(&image
, patch
, st
, ce
) < 0)
3476 if (patch
->direct_to_threeway
||
3477 apply_fragments(state
, &image
, patch
) < 0) {
3478 /* Note: with --reject, apply_fragments() returns 0 */
3479 if (!threeway
|| try_threeway(state
, &image
, patch
, st
, ce
) < 0)
3482 patch
->result
= image
.buf
;
3483 patch
->resultsize
= image
.len
;
3484 add_to_fn_table(patch
);
3485 free(image
.line_allocated
);
3487 if (0 < patch
->is_delete
&& patch
->resultsize
)
3488 return error(_("removal patch leaves file contents"));
3494 * If "patch" that we are looking at modifies or deletes what we have,
3495 * we would want it not to lose any local modification we have, either
3496 * in the working tree or in the index.
3498 * This also decides if a non-git patch is a creation patch or a
3499 * modification to an existing empty file. We do not check the state
3500 * of the current tree for a creation patch in this function; the caller
3501 * check_patch() separately makes sure (and errors out otherwise) that
3502 * the path the patch creates does not exist in the current tree.
3504 static int check_preimage(struct patch
*patch
, struct cache_entry
**ce
, struct stat
*st
)
3506 const char *old_name
= patch
->old_name
;
3507 struct patch
*previous
= NULL
;
3508 int stat_ret
= 0, status
;
3509 unsigned st_mode
= 0;
3514 assert(patch
->is_new
<= 0);
3515 previous
= previous_patch(patch
, &status
);
3518 return error(_("path %s has been renamed/deleted"), old_name
);
3520 st_mode
= previous
->new_mode
;
3521 } else if (!cached
) {
3522 stat_ret
= lstat(old_name
, st
);
3523 if (stat_ret
&& errno
!= ENOENT
)
3524 return error(_("%s: %s"), old_name
, strerror(errno
));
3527 if (check_index
&& !previous
) {
3528 int pos
= cache_name_pos(old_name
, strlen(old_name
));
3530 if (patch
->is_new
< 0)
3532 return error(_("%s: does not exist in index"), old_name
);
3534 *ce
= active_cache
[pos
];
3536 if (checkout_target(&the_index
, *ce
, st
))
3539 if (!cached
&& verify_index_match(*ce
, st
))
3540 return error(_("%s: does not match index"), old_name
);
3542 st_mode
= (*ce
)->ce_mode
;
3543 } else if (stat_ret
< 0) {
3544 if (patch
->is_new
< 0)
3546 return error(_("%s: %s"), old_name
, strerror(errno
));
3549 if (!cached
&& !previous
)
3550 st_mode
= ce_mode_from_stat(*ce
, st
->st_mode
);
3552 if (patch
->is_new
< 0)
3554 if (!patch
->old_mode
)
3555 patch
->old_mode
= st_mode
;
3556 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
3557 return error(_("%s: wrong type"), old_name
);
3558 if (st_mode
!= patch
->old_mode
)
3559 warning(_("%s has type %o, expected %o"),
3560 old_name
, st_mode
, patch
->old_mode
);
3561 if (!patch
->new_mode
&& !patch
->is_delete
)
3562 patch
->new_mode
= st_mode
;
3567 patch
->is_delete
= 0;
3568 free(patch
->old_name
);
3569 patch
->old_name
= NULL
;
3574 #define EXISTS_IN_INDEX 1
3575 #define EXISTS_IN_WORKTREE 2
3577 static int check_to_create(const char *new_name
, int ok_if_exists
)
3582 cache_name_pos(new_name
, strlen(new_name
)) >= 0 &&
3584 return EXISTS_IN_INDEX
;
3588 if (!lstat(new_name
, &nst
)) {
3589 if (S_ISDIR(nst
.st_mode
) || ok_if_exists
)
3592 * A leading component of new_name might be a symlink
3593 * that is going to be removed with this patch, but
3594 * still pointing at somewhere that has the path.
3595 * In such a case, path "new_name" does not exist as
3596 * far as git is concerned.
3598 if (has_symlink_leading_path(new_name
, strlen(new_name
)))
3601 return EXISTS_IN_WORKTREE
;
3602 } else if ((errno
!= ENOENT
) && (errno
!= ENOTDIR
)) {
3603 return error("%s: %s", new_name
, strerror(errno
));
3609 * We need to keep track of how symlinks in the preimage are
3610 * manipulated by the patches. A patch to add a/b/c where a/b
3611 * is a symlink should not be allowed to affect the directory
3612 * the symlink points at, but if the same patch removes a/b,
3613 * it is perfectly fine, as the patch removes a/b to make room
3614 * to create a directory a/b so that a/b/c can be created.
3616 static struct string_list symlink_changes
;
3617 #define SYMLINK_GOES_AWAY 01
3618 #define SYMLINK_IN_RESULT 02
3620 static uintptr_t register_symlink_changes(const char *path
, uintptr_t what
)
3622 struct string_list_item
*ent
;
3624 ent
= string_list_lookup(&symlink_changes
, path
);
3626 ent
= string_list_insert(&symlink_changes
, path
);
3627 ent
->util
= (void *)0;
3629 ent
->util
= (void *)(what
| ((uintptr_t)ent
->util
));
3630 return (uintptr_t)ent
->util
;
3633 static uintptr_t check_symlink_changes(const char *path
)
3635 struct string_list_item
*ent
;
3637 ent
= string_list_lookup(&symlink_changes
, path
);
3640 return (uintptr_t)ent
->util
;
3643 static void prepare_symlink_changes(struct patch
*patch
)
3645 for ( ; patch
; patch
= patch
->next
) {
3646 if ((patch
->old_name
&& S_ISLNK(patch
->old_mode
)) &&
3647 (patch
->is_rename
|| patch
->is_delete
))
3648 /* the symlink at patch->old_name is removed */
3649 register_symlink_changes(patch
->old_name
, SYMLINK_GOES_AWAY
);
3651 if (patch
->new_name
&& S_ISLNK(patch
->new_mode
))
3652 /* the symlink at patch->new_name is created or remains */
3653 register_symlink_changes(patch
->new_name
, SYMLINK_IN_RESULT
);
3657 static int path_is_beyond_symlink_1(struct strbuf
*name
)
3660 unsigned int change
;
3662 while (--name
->len
&& name
->buf
[name
->len
] != '/')
3663 ; /* scan backwards */
3666 name
->buf
[name
->len
] = '\0';
3667 change
= check_symlink_changes(name
->buf
);
3668 if (change
& SYMLINK_IN_RESULT
)
3670 if (change
& SYMLINK_GOES_AWAY
)
3672 * This cannot be "return 0", because we may
3673 * see a new one created at a higher level.
3677 /* otherwise, check the preimage */
3679 struct cache_entry
*ce
;
3681 ce
= cache_file_exists(name
->buf
, name
->len
, ignore_case
);
3682 if (ce
&& S_ISLNK(ce
->ce_mode
))
3686 if (!lstat(name
->buf
, &st
) && S_ISLNK(st
.st_mode
))
3693 static int path_is_beyond_symlink(const char *name_
)
3696 struct strbuf name
= STRBUF_INIT
;
3698 assert(*name_
!= '\0');
3699 strbuf_addstr(&name
, name_
);
3700 ret
= path_is_beyond_symlink_1(&name
);
3701 strbuf_release(&name
);
3706 static void die_on_unsafe_path(struct patch
*patch
)
3708 const char *old_name
= NULL
;
3709 const char *new_name
= NULL
;
3710 if (patch
->is_delete
)
3711 old_name
= patch
->old_name
;
3712 else if (!patch
->is_new
&& !patch
->is_copy
)
3713 old_name
= patch
->old_name
;
3714 if (!patch
->is_delete
)
3715 new_name
= patch
->new_name
;
3717 if (old_name
&& !verify_path(old_name
))
3718 die(_("invalid path '%s'"), old_name
);
3719 if (new_name
&& !verify_path(new_name
))
3720 die(_("invalid path '%s'"), new_name
);
3724 * Check and apply the patch in-core; leave the result in patch->result
3725 * for the caller to write it out to the final destination.
3727 static int check_patch(struct apply_state
*state
, struct patch
*patch
)
3730 const char *old_name
= patch
->old_name
;
3731 const char *new_name
= patch
->new_name
;
3732 const char *name
= old_name
? old_name
: new_name
;
3733 struct cache_entry
*ce
= NULL
;
3734 struct patch
*tpatch
;
3738 patch
->rejected
= 1; /* we will drop this after we succeed */
3740 status
= check_preimage(patch
, &ce
, &st
);
3743 old_name
= patch
->old_name
;
3746 * A type-change diff is always split into a patch to delete
3747 * old, immediately followed by a patch to create new (see
3748 * diff.c::run_diff()); in such a case it is Ok that the entry
3749 * to be deleted by the previous patch is still in the working
3750 * tree and in the index.
3752 * A patch to swap-rename between A and B would first rename A
3753 * to B and then rename B to A. While applying the first one,
3754 * the presence of B should not stop A from getting renamed to
3755 * B; ask to_be_deleted() about the later rename. Removal of
3756 * B and rename from A to B is handled the same way by asking
3759 if ((tpatch
= in_fn_table(new_name
)) &&
3760 (was_deleted(tpatch
) || to_be_deleted(tpatch
)))
3766 ((0 < patch
->is_new
) || patch
->is_rename
|| patch
->is_copy
)) {
3767 int err
= check_to_create(new_name
, ok_if_exists
);
3769 if (err
&& threeway
) {
3770 patch
->direct_to_threeway
= 1;
3771 } else switch (err
) {
3774 case EXISTS_IN_INDEX
:
3775 return error(_("%s: already exists in index"), new_name
);
3777 case EXISTS_IN_WORKTREE
:
3778 return error(_("%s: already exists in working directory"),
3784 if (!patch
->new_mode
) {
3785 if (0 < patch
->is_new
)
3786 patch
->new_mode
= S_IFREG
| 0644;
3788 patch
->new_mode
= patch
->old_mode
;
3792 if (new_name
&& old_name
) {
3793 int same
= !strcmp(old_name
, new_name
);
3794 if (!patch
->new_mode
)
3795 patch
->new_mode
= patch
->old_mode
;
3796 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
) {
3798 return error(_("new mode (%o) of %s does not "
3799 "match old mode (%o)"),
3800 patch
->new_mode
, new_name
,
3803 return error(_("new mode (%o) of %s does not "
3804 "match old mode (%o) of %s"),
3805 patch
->new_mode
, new_name
,
3806 patch
->old_mode
, old_name
);
3811 die_on_unsafe_path(patch
);
3814 * An attempt to read from or delete a path that is beyond a
3815 * symbolic link will be prevented by load_patch_target() that
3816 * is called at the beginning of apply_data() so we do not
3817 * have to worry about a patch marked with "is_delete" bit
3818 * here. We however need to make sure that the patch result
3819 * is not deposited to a path that is beyond a symbolic link
3822 if (!patch
->is_delete
&& path_is_beyond_symlink(patch
->new_name
))
3823 return error(_("affected file '%s' is beyond a symbolic link"),
3826 if (apply_data(state
, patch
, &st
, ce
) < 0)
3827 return error(_("%s: patch does not apply"), name
);
3828 patch
->rejected
= 0;
3832 static int check_patch_list(struct apply_state
*state
, struct patch
*patch
)
3836 prepare_symlink_changes(patch
);
3837 prepare_fn_table(patch
);
3839 if (apply_verbosely
)
3840 say_patch_name(stderr
,
3841 _("Checking patch %s..."), patch
);
3842 err
|= check_patch(state
, patch
);
3843 patch
= patch
->next
;
3848 /* This function tries to read the sha1 from the current index */
3849 static int get_current_sha1(const char *path
, unsigned char *sha1
)
3853 if (read_cache() < 0)
3855 pos
= cache_name_pos(path
, strlen(path
));
3858 hashcpy(sha1
, active_cache
[pos
]->sha1
);
3862 static int preimage_sha1_in_gitlink_patch(struct patch
*p
, unsigned char sha1
[20])
3865 * A usable gitlink patch has only one fragment (hunk) that looks like:
3867 * -Subproject commit <old sha1>
3868 * +Subproject commit <new sha1>
3871 * -Subproject commit <old sha1>
3872 * for a removal patch.
3874 struct fragment
*hunk
= p
->fragments
;
3875 static const char heading
[] = "-Subproject commit ";
3878 if (/* does the patch have only one hunk? */
3879 hunk
&& !hunk
->next
&&
3880 /* is its preimage one line? */
3881 hunk
->oldpos
== 1 && hunk
->oldlines
== 1 &&
3882 /* does preimage begin with the heading? */
3883 (preimage
= memchr(hunk
->patch
, '\n', hunk
->size
)) != NULL
&&
3884 starts_with(++preimage
, heading
) &&
3885 /* does it record full SHA-1? */
3886 !get_sha1_hex(preimage
+ sizeof(heading
) - 1, sha1
) &&
3887 preimage
[sizeof(heading
) + 40 - 1] == '\n' &&
3888 /* does the abbreviated name on the index line agree with it? */
3889 starts_with(preimage
+ sizeof(heading
) - 1, p
->old_sha1_prefix
))
3890 return 0; /* it all looks fine */
3892 /* we may have full object name on the index line */
3893 return get_sha1_hex(p
->old_sha1_prefix
, sha1
);
3896 /* Build an index that contains the just the files needed for a 3way merge */
3897 static void build_fake_ancestor(struct patch
*list
, const char *filename
)
3899 struct patch
*patch
;
3900 struct index_state result
= { NULL
};
3901 static struct lock_file lock
;
3903 /* Once we start supporting the reverse patch, it may be
3904 * worth showing the new sha1 prefix, but until then...
3906 for (patch
= list
; patch
; patch
= patch
->next
) {
3907 unsigned char sha1
[20];
3908 struct cache_entry
*ce
;
3911 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3912 if (0 < patch
->is_new
)
3915 if (S_ISGITLINK(patch
->old_mode
)) {
3916 if (!preimage_sha1_in_gitlink_patch(patch
, sha1
))
3917 ; /* ok, the textual part looks sane */
3919 die("sha1 information is lacking or useless for submodule %s",
3921 } else if (!get_sha1_blob(patch
->old_sha1_prefix
, sha1
)) {
3923 } else if (!patch
->lines_added
&& !patch
->lines_deleted
) {
3924 /* mode-only change: update the current */
3925 if (get_current_sha1(patch
->old_name
, sha1
))
3926 die("mode change for %s, which is not "
3927 "in current HEAD", name
);
3929 die("sha1 information is lacking or useless "
3932 ce
= make_cache_entry(patch
->old_mode
, sha1
, name
, 0, 0);
3934 die(_("make_cache_entry failed for path '%s'"), name
);
3935 if (add_index_entry(&result
, ce
, ADD_CACHE_OK_TO_ADD
))
3936 die ("Could not add %s to temporary index", name
);
3939 hold_lock_file_for_update(&lock
, filename
, LOCK_DIE_ON_ERROR
);
3940 if (write_locked_index(&result
, &lock
, COMMIT_LOCK
))
3941 die ("Could not write temporary index to %s", filename
);
3943 discard_index(&result
);
3946 static void stat_patch_list(struct patch
*patch
)
3948 int files
, adds
, dels
;
3950 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
3952 adds
+= patch
->lines_added
;
3953 dels
+= patch
->lines_deleted
;
3957 print_stat_summary(stdout
, files
, adds
, dels
);
3960 static void numstat_patch_list(struct patch
*patch
)
3962 for ( ; patch
; patch
= patch
->next
) {
3964 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
3965 if (patch
->is_binary
)
3968 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
3969 write_name_quoted(name
, stdout
, line_termination
);
3973 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
3976 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
3978 printf(" %s %s\n", newdelete
, name
);
3981 static void show_mode_change(struct patch
*p
, int show_name
)
3983 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
3985 printf(" mode change %06o => %06o %s\n",
3986 p
->old_mode
, p
->new_mode
, p
->new_name
);
3988 printf(" mode change %06o => %06o\n",
3989 p
->old_mode
, p
->new_mode
);
3993 static void show_rename_copy(struct patch
*p
)
3995 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
3996 const char *old
, *new;
3998 /* Find common prefix */
4002 const char *slash_old
, *slash_new
;
4003 slash_old
= strchr(old
, '/');
4004 slash_new
= strchr(new, '/');
4007 slash_old
- old
!= slash_new
- new ||
4008 memcmp(old
, new, slash_new
- new))
4010 old
= slash_old
+ 1;
4011 new = slash_new
+ 1;
4013 /* p->old_name thru old is the common prefix, and old and new
4014 * through the end of names are renames
4016 if (old
!= p
->old_name
)
4017 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
4018 (int)(old
- p
->old_name
), p
->old_name
,
4019 old
, new, p
->score
);
4021 printf(" %s %s => %s (%d%%)\n", renamecopy
,
4022 p
->old_name
, p
->new_name
, p
->score
);
4023 show_mode_change(p
, 0);
4026 static void summary_patch_list(struct patch
*patch
)
4030 for (p
= patch
; p
; p
= p
->next
) {
4032 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
4033 else if (p
->is_delete
)
4034 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
4036 if (p
->is_rename
|| p
->is_copy
)
4037 show_rename_copy(p
);
4040 printf(" rewrite %s (%d%%)\n",
4041 p
->new_name
, p
->score
);
4042 show_mode_change(p
, 0);
4045 show_mode_change(p
, 1);
4051 static void patch_stats(struct patch
*patch
)
4053 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
4055 if (lines
> max_change
)
4057 if (patch
->old_name
) {
4058 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
4060 len
= strlen(patch
->old_name
);
4064 if (patch
->new_name
) {
4065 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
4067 len
= strlen(patch
->new_name
);
4073 static void remove_file(struct patch
*patch
, int rmdir_empty
)
4076 if (remove_file_from_cache(patch
->old_name
) < 0)
4077 die(_("unable to remove %s from index"), patch
->old_name
);
4080 if (!remove_or_warn(patch
->old_mode
, patch
->old_name
) && rmdir_empty
) {
4081 remove_path(patch
->old_name
);
4086 static void add_index_file(const char *path
, unsigned mode
, void *buf
, unsigned long size
)
4089 struct cache_entry
*ce
;
4090 int namelen
= strlen(path
);
4091 unsigned ce_size
= cache_entry_size(namelen
);
4096 ce
= xcalloc(1, ce_size
);
4097 memcpy(ce
->name
, path
, namelen
);
4098 ce
->ce_mode
= create_ce_mode(mode
);
4099 ce
->ce_flags
= create_ce_flags(0);
4100 ce
->ce_namelen
= namelen
;
4101 if (S_ISGITLINK(mode
)) {
4104 if (!skip_prefix(buf
, "Subproject commit ", &s
) ||
4105 get_sha1_hex(s
, ce
->sha1
))
4106 die(_("corrupt patch for submodule %s"), path
);
4109 if (lstat(path
, &st
) < 0)
4110 die_errno(_("unable to stat newly created file '%s'"),
4112 fill_stat_cache_info(ce
, &st
);
4114 if (write_sha1_file(buf
, size
, blob_type
, ce
->sha1
) < 0)
4115 die(_("unable to create backing store for newly created file %s"), path
);
4117 if (add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
) < 0)
4118 die(_("unable to add cache entry for %s"), path
);
4121 static int try_create_file(const char *path
, unsigned int mode
, const char *buf
, unsigned long size
)
4124 struct strbuf nbuf
= STRBUF_INIT
;
4126 if (S_ISGITLINK(mode
)) {
4128 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
))
4130 return mkdir(path
, 0777);
4133 if (has_symlinks
&& S_ISLNK(mode
))
4134 /* Although buf:size is counted string, it also is NUL
4137 return symlink(buf
, path
);
4139 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
4143 if (convert_to_working_tree(path
, buf
, size
, &nbuf
)) {
4147 write_or_die(fd
, buf
, size
);
4148 strbuf_release(&nbuf
);
4151 die_errno(_("closing file '%s'"), path
);
4156 * We optimistically assume that the directories exist,
4157 * which is true 99% of the time anyway. If they don't,
4158 * we create them and try again.
4160 static void create_one_file(char *path
, unsigned mode
, const char *buf
, unsigned long size
)
4164 if (!try_create_file(path
, mode
, buf
, size
))
4167 if (errno
== ENOENT
) {
4168 if (safe_create_leading_directories(path
))
4170 if (!try_create_file(path
, mode
, buf
, size
))
4174 if (errno
== EEXIST
|| errno
== EACCES
) {
4175 /* We may be trying to create a file where a directory
4179 if (!lstat(path
, &st
) && (!S_ISDIR(st
.st_mode
) || !rmdir(path
)))
4183 if (errno
== EEXIST
) {
4184 unsigned int nr
= getpid();
4187 char newpath
[PATH_MAX
];
4188 mksnpath(newpath
, sizeof(newpath
), "%s~%u", path
, nr
);
4189 if (!try_create_file(newpath
, mode
, buf
, size
)) {
4190 if (!rename(newpath
, path
))
4192 unlink_or_warn(newpath
);
4195 if (errno
!= EEXIST
)
4200 die_errno(_("unable to write file '%s' mode %o"), path
, mode
);
4203 static void add_conflicted_stages_file(struct patch
*patch
)
4206 unsigned ce_size
, mode
;
4207 struct cache_entry
*ce
;
4211 namelen
= strlen(patch
->new_name
);
4212 ce_size
= cache_entry_size(namelen
);
4213 mode
= patch
->new_mode
? patch
->new_mode
: (S_IFREG
| 0644);
4215 remove_file_from_cache(patch
->new_name
);
4216 for (stage
= 1; stage
< 4; stage
++) {
4217 if (is_null_oid(&patch
->threeway_stage
[stage
- 1]))
4219 ce
= xcalloc(1, ce_size
);
4220 memcpy(ce
->name
, patch
->new_name
, namelen
);
4221 ce
->ce_mode
= create_ce_mode(mode
);
4222 ce
->ce_flags
= create_ce_flags(stage
);
4223 ce
->ce_namelen
= namelen
;
4224 hashcpy(ce
->sha1
, patch
->threeway_stage
[stage
- 1].hash
);
4225 if (add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
) < 0)
4226 die(_("unable to add cache entry for %s"), patch
->new_name
);
4230 static void create_file(struct patch
*patch
)
4232 char *path
= patch
->new_name
;
4233 unsigned mode
= patch
->new_mode
;
4234 unsigned long size
= patch
->resultsize
;
4235 char *buf
= patch
->result
;
4238 mode
= S_IFREG
| 0644;
4239 create_one_file(path
, mode
, buf
, size
);
4241 if (patch
->conflicted_threeway
)
4242 add_conflicted_stages_file(patch
);
4244 add_index_file(path
, mode
, buf
, size
);
4247 /* phase zero is to remove, phase one is to create */
4248 static void write_out_one_result(struct patch
*patch
, int phase
)
4250 if (patch
->is_delete
> 0) {
4252 remove_file(patch
, 1);
4255 if (patch
->is_new
> 0 || patch
->is_copy
) {
4261 * Rename or modification boils down to the same
4262 * thing: remove the old, write the new
4265 remove_file(patch
, patch
->is_rename
);
4270 static int write_out_one_reject(struct patch
*patch
)
4273 char namebuf
[PATH_MAX
];
4274 struct fragment
*frag
;
4276 struct strbuf sb
= STRBUF_INIT
;
4278 for (cnt
= 0, frag
= patch
->fragments
; frag
; frag
= frag
->next
) {
4279 if (!frag
->rejected
)
4285 if (apply_verbosely
)
4286 say_patch_name(stderr
,
4287 _("Applied patch %s cleanly."), patch
);
4291 /* This should not happen, because a removal patch that leaves
4292 * contents are marked "rejected" at the patch level.
4294 if (!patch
->new_name
)
4295 die(_("internal error"));
4297 /* Say this even without --verbose */
4298 strbuf_addf(&sb
, Q_("Applying patch %%s with %d reject...",
4299 "Applying patch %%s with %d rejects...",
4302 say_patch_name(stderr
, sb
.buf
, patch
);
4303 strbuf_release(&sb
);
4305 cnt
= strlen(patch
->new_name
);
4306 if (ARRAY_SIZE(namebuf
) <= cnt
+ 5) {
4307 cnt
= ARRAY_SIZE(namebuf
) - 5;
4308 warning(_("truncating .rej filename to %.*s.rej"),
4309 cnt
- 1, patch
->new_name
);
4311 memcpy(namebuf
, patch
->new_name
, cnt
);
4312 memcpy(namebuf
+ cnt
, ".rej", 5);
4314 rej
= fopen(namebuf
, "w");
4316 return error(_("cannot open %s: %s"), namebuf
, strerror(errno
));
4318 /* Normal git tools never deal with .rej, so do not pretend
4319 * this is a git patch by saying --git or giving extended
4320 * headers. While at it, maybe please "kompare" that wants
4321 * the trailing TAB and some garbage at the end of line ;-).
4323 fprintf(rej
, "diff a/%s b/%s\t(rejected hunks)\n",
4324 patch
->new_name
, patch
->new_name
);
4325 for (cnt
= 1, frag
= patch
->fragments
;
4327 cnt
++, frag
= frag
->next
) {
4328 if (!frag
->rejected
) {
4329 fprintf_ln(stderr
, _("Hunk #%d applied cleanly."), cnt
);
4332 fprintf_ln(stderr
, _("Rejected hunk #%d."), cnt
);
4333 fprintf(rej
, "%.*s", frag
->size
, frag
->patch
);
4334 if (frag
->patch
[frag
->size
-1] != '\n')
4341 static int write_out_results(struct patch
*list
)
4346 struct string_list cpath
= STRING_LIST_INIT_DUP
;
4348 for (phase
= 0; phase
< 2; phase
++) {
4354 write_out_one_result(l
, phase
);
4356 if (write_out_one_reject(l
))
4358 if (l
->conflicted_threeway
) {
4359 string_list_append(&cpath
, l
->new_name
);
4369 struct string_list_item
*item
;
4371 string_list_sort(&cpath
);
4372 for_each_string_list_item(item
, &cpath
)
4373 fprintf(stderr
, "U %s\n", item
->string
);
4374 string_list_clear(&cpath
, 0);
4382 static struct lock_file lock_file
;
4384 #define INACCURATE_EOF (1<<0)
4385 #define RECOUNT (1<<1)
4387 static int apply_patch(struct apply_state
*state
,
4389 const char *filename
,
4393 struct strbuf buf
= STRBUF_INIT
; /* owns the patch text */
4394 struct patch
*list
= NULL
, **listp
= &list
;
4395 int skipped_patch
= 0;
4397 patch_input_file
= filename
;
4398 read_patch_file(&buf
, fd
);
4400 while (offset
< buf
.len
) {
4401 struct patch
*patch
;
4404 patch
= xcalloc(1, sizeof(*patch
));
4405 patch
->inaccurate_eof
= !!(options
& INACCURATE_EOF
);
4406 patch
->recount
= !!(options
& RECOUNT
);
4407 nr
= parse_chunk(state
, buf
.buf
+ offset
, buf
.len
- offset
, patch
);
4412 if (apply_in_reverse
)
4413 reverse_patches(patch
);
4414 if (use_patch(state
, patch
)) {
4417 listp
= &patch
->next
;
4420 if (apply_verbosely
)
4421 say_patch_name(stderr
, _("Skipped patch '%s'."), patch
);
4428 if (!list
&& !skipped_patch
)
4429 die(_("unrecognized input"));
4431 if (whitespace_error
&& (ws_error_action
== die_on_ws_error
))
4434 update_index
= check_index
&& apply
;
4435 if (update_index
&& newfd
< 0)
4436 newfd
= hold_locked_index(&lock_file
, 1);
4439 if (read_cache() < 0)
4440 die(_("unable to read index file"));
4443 if ((check
|| apply
) &&
4444 check_patch_list(state
, list
) < 0 &&
4448 if (apply
&& write_out_results(list
)) {
4449 if (apply_with_reject
)
4451 /* with --3way, we still need to write the index out */
4456 build_fake_ancestor(list
, fake_ancestor
);
4459 stat_patch_list(list
);
4462 numstat_patch_list(list
);
4465 summary_patch_list(list
);
4467 free_patch_list(list
);
4468 strbuf_release(&buf
);
4469 string_list_clear(&fn_table
, 0);
4473 static void git_apply_config(void)
4475 git_config_get_string_const("apply.whitespace", &apply_default_whitespace
);
4476 git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace
);
4477 git_config(git_default_config
, NULL
);
4480 static int option_parse_exclude(const struct option
*opt
,
4481 const char *arg
, int unset
)
4483 add_name_limit(arg
, 1);
4487 static int option_parse_include(const struct option
*opt
,
4488 const char *arg
, int unset
)
4490 add_name_limit(arg
, 0);
4495 static int option_parse_p(const struct option
*opt
,
4496 const char *arg
, int unset
)
4498 state_p_value
= atoi(arg
);
4503 static int option_parse_space_change(const struct option
*opt
,
4504 const char *arg
, int unset
)
4507 ws_ignore_action
= ignore_ws_none
;
4509 ws_ignore_action
= ignore_ws_change
;
4513 static int option_parse_whitespace(const struct option
*opt
,
4514 const char *arg
, int unset
)
4516 const char **whitespace_option
= opt
->value
;
4518 *whitespace_option
= arg
;
4519 parse_whitespace_option(arg
);
4523 static int option_parse_directory(const struct option
*opt
,
4524 const char *arg
, int unset
)
4526 strbuf_reset(&root
);
4527 strbuf_addstr(&root
, arg
);
4528 strbuf_complete(&root
, '/');
4532 static void init_apply_state(struct apply_state
*state
, const char *prefix
)
4534 memset(state
, 0, sizeof(*state
));
4535 state
->prefix
= prefix
;
4536 state
->prefix_length
= state
->prefix
? strlen(state
->prefix
) : 0;
4539 if (apply_default_whitespace
)
4540 parse_whitespace_option(apply_default_whitespace
);
4541 if (apply_default_ignorewhitespace
)
4542 parse_ignorewhitespace_option(apply_default_ignorewhitespace
);
4545 static void clear_apply_state(struct apply_state
*state
)
4550 int cmd_apply(int argc
, const char **argv
, const char *prefix
)
4554 int is_not_gitdir
= !startup_info
->have_repository
;
4555 int force_apply
= 0;
4558 struct apply_state state
;
4560 const char *whitespace_option
= NULL
;
4562 struct option builtin_apply_options
[] = {
4563 { OPTION_CALLBACK
, 0, "exclude", NULL
, N_("path"),
4564 N_("don't apply changes matching the given path"),
4565 0, option_parse_exclude
},
4566 { OPTION_CALLBACK
, 0, "include", NULL
, N_("path"),
4567 N_("apply changes matching the given path"),
4568 0, option_parse_include
},
4569 { OPTION_CALLBACK
, 'p', NULL
, NULL
, N_("num"),
4570 N_("remove <num> leading slashes from traditional diff paths"),
4571 0, option_parse_p
},
4572 OPT_BOOL(0, "no-add", &no_add
,
4573 N_("ignore additions made by the patch")),
4574 OPT_BOOL(0, "stat", &diffstat
,
4575 N_("instead of applying the patch, output diffstat for the input")),
4576 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
4577 OPT_NOOP_NOARG(0, "binary"),
4578 OPT_BOOL(0, "numstat", &numstat
,
4579 N_("show number of added and deleted lines in decimal notation")),
4580 OPT_BOOL(0, "summary", &summary
,
4581 N_("instead of applying the patch, output a summary for the input")),
4582 OPT_BOOL(0, "check", &check
,
4583 N_("instead of applying the patch, see if the patch is applicable")),
4584 OPT_BOOL(0, "index", &check_index
,
4585 N_("make sure the patch is applicable to the current index")),
4586 OPT_BOOL(0, "cached", &cached
,
4587 N_("apply a patch without touching the working tree")),
4588 OPT_BOOL(0, "unsafe-paths", &unsafe_paths
,
4589 N_("accept a patch that touches outside the working area")),
4590 OPT_BOOL(0, "apply", &force_apply
,
4591 N_("also apply the patch (use with --stat/--summary/--check)")),
4592 OPT_BOOL('3', "3way", &threeway
,
4593 N_( "attempt three-way merge if a patch does not apply")),
4594 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor
,
4595 N_("build a temporary index based on embedded index information")),
4596 /* Think twice before adding "--nul" synonym to this */
4597 OPT_SET_INT('z', NULL
, &line_termination
,
4598 N_("paths are separated with NUL character"), '\0'),
4599 OPT_INTEGER('C', NULL
, &p_context
,
4600 N_("ensure at least <n> lines of context match")),
4601 { OPTION_CALLBACK
, 0, "whitespace", &whitespace_option
, N_("action"),
4602 N_("detect new or modified lines that have whitespace errors"),
4603 0, option_parse_whitespace
},
4604 { OPTION_CALLBACK
, 0, "ignore-space-change", NULL
, NULL
,
4605 N_("ignore changes in whitespace when finding context"),
4606 PARSE_OPT_NOARG
, option_parse_space_change
},
4607 { OPTION_CALLBACK
, 0, "ignore-whitespace", NULL
, NULL
,
4608 N_("ignore changes in whitespace when finding context"),
4609 PARSE_OPT_NOARG
, option_parse_space_change
},
4610 OPT_BOOL('R', "reverse", &apply_in_reverse
,
4611 N_("apply the patch in reverse")),
4612 OPT_BOOL(0, "unidiff-zero", &state
.unidiff_zero
,
4613 N_("don't expect at least one line of context")),
4614 OPT_BOOL(0, "reject", &apply_with_reject
,
4615 N_("leave the rejected hunks in corresponding *.rej files")),
4616 OPT_BOOL(0, "allow-overlap", &allow_overlap
,
4617 N_("allow overlapping hunks")),
4618 OPT__VERBOSE(&apply_verbosely
, N_("be verbose")),
4619 OPT_BIT(0, "inaccurate-eof", &options
,
4620 N_("tolerate incorrectly detected missing new-line at the end of file"),
4622 OPT_BIT(0, "recount", &options
,
4623 N_("do not trust the line counts in the hunk headers"),
4625 { OPTION_CALLBACK
, 0, "directory", NULL
, N_("root"),
4626 N_("prepend <root> to all filenames"),
4627 0, option_parse_directory
},
4631 init_apply_state(&state
, prefix
);
4633 argc
= parse_options(argc
, argv
, state
.prefix
, builtin_apply_options
,
4636 if (apply_with_reject
&& threeway
)
4637 die("--reject and --3way cannot be used together.");
4638 if (cached
&& threeway
)
4639 die("--cached and --3way cannot be used together.");
4642 die(_("--3way outside a repository"));
4645 if (apply_with_reject
)
4646 apply
= apply_verbosely
= 1;
4647 if (!force_apply
&& (diffstat
|| numstat
|| summary
|| check
|| fake_ancestor
))
4649 if (check_index
&& is_not_gitdir
)
4650 die(_("--index outside a repository"));
4653 die(_("--cached outside a repository"));
4659 for (i
= 0; i
< argc
; i
++) {
4660 const char *arg
= argv
[i
];
4663 if (!strcmp(arg
, "-")) {
4664 errs
|= apply_patch(&state
, 0, "<stdin>", options
);
4667 } else if (0 < state
.prefix_length
)
4668 arg
= prefix_filename(state
.prefix
,
4669 state
.prefix_length
,
4672 fd
= open(arg
, O_RDONLY
);
4674 die_errno(_("can't open patch '%s'"), arg
);
4676 set_default_whitespace_mode(whitespace_option
);
4677 errs
|= apply_patch(&state
, fd
, arg
, options
);
4680 set_default_whitespace_mode(whitespace_option
);
4682 errs
|= apply_patch(&state
, 0, "<stdin>", options
);
4683 if (whitespace_error
) {
4684 if (squelch_whitespace_errors
&&
4685 squelch_whitespace_errors
< whitespace_error
) {
4687 whitespace_error
- squelch_whitespace_errors
;
4688 warning(Q_("squelched %d whitespace error",
4689 "squelched %d whitespace errors",
4693 if (ws_error_action
== die_on_ws_error
)
4694 die(Q_("%d line adds whitespace errors.",
4695 "%d lines add whitespace errors.",
4698 if (applied_after_fixing_ws
&& apply
)
4699 warning("%d line%s applied after"
4700 " fixing whitespace errors.",
4701 applied_after_fixing_ws
,
4702 applied_after_fixing_ws
== 1 ? "" : "s");
4703 else if (whitespace_error
)
4704 warning(Q_("%d line adds whitespace errors.",
4705 "%d lines add whitespace errors.",
4711 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
4712 die(_("Unable to write new index file"));
4715 clear_apply_state(&state
);