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 control what gets looked at and modified */
29 int apply
; /* this is not a dry-run */
30 int cached
; /* apply to the index only */
31 int check
; /* preimage must match working tree, don't actually apply */
32 int check_index
; /* preimage must match the indexed version */
33 int update_index
; /* check_index && apply */
35 /* These control cosmetic aspect of the output */
36 int diffstat
; /* just show a diffstat, and don't actually apply */
37 int numstat
; /* just show a numeric diffstat, and don't actually apply */
38 int summary
; /* just report creation, deletion, etc, and don't actually apply */
40 /* These boolean parameters control how the apply is done */
43 int apply_with_reject
;
50 /* Other non boolean parameters */
51 const char *fake_ancestor
;
52 const char *patch_input_file
;
57 unsigned int p_context
;
59 /* Exclude and include path parameters */
60 struct string_list limit_by_name
;
63 /* These control whitespace errors */
67 static int newfd
= -1;
69 static const char * const apply_usage
[] = {
70 N_("git apply [<options>] [<patch>...]"),
74 static enum ws_error_action
{
79 } ws_error_action
= warn_on_ws_error
;
80 static int squelch_whitespace_errors
= 5;
81 static int applied_after_fixing_ws
;
83 static enum ws_ignore
{
86 } ws_ignore_action
= ignore_ws_none
;
89 static void parse_whitespace_option(const char *option
)
92 ws_error_action
= warn_on_ws_error
;
95 if (!strcmp(option
, "warn")) {
96 ws_error_action
= warn_on_ws_error
;
99 if (!strcmp(option
, "nowarn")) {
100 ws_error_action
= nowarn_ws_error
;
103 if (!strcmp(option
, "error")) {
104 ws_error_action
= die_on_ws_error
;
107 if (!strcmp(option
, "error-all")) {
108 ws_error_action
= die_on_ws_error
;
109 squelch_whitespace_errors
= 0;
112 if (!strcmp(option
, "strip") || !strcmp(option
, "fix")) {
113 ws_error_action
= correct_ws_error
;
116 die(_("unrecognized whitespace option '%s'"), option
);
119 static void parse_ignorewhitespace_option(const char *option
)
121 if (!option
|| !strcmp(option
, "no") ||
122 !strcmp(option
, "false") || !strcmp(option
, "never") ||
123 !strcmp(option
, "none")) {
124 ws_ignore_action
= ignore_ws_none
;
127 if (!strcmp(option
, "change")) {
128 ws_ignore_action
= ignore_ws_change
;
131 die(_("unrecognized whitespace ignore option '%s'"), option
);
134 static void set_default_whitespace_mode(struct apply_state
*state
,
135 const char *whitespace_option
)
137 if (!whitespace_option
&& !apply_default_whitespace
)
138 ws_error_action
= (state
->apply
? warn_on_ws_error
: nowarn_ws_error
);
142 * For "diff-stat" like behaviour, we keep track of the biggest change
143 * we've seen, and the longest filename. That allows us to do simple
146 static int max_change
, max_len
;
149 * Various "current state", notably line numbers and what
150 * file (and how) we're patching right now.. The "is_xxxx"
151 * things are flags, where -1 means "don't know yet".
153 static int state_linenr
= 1;
156 * This represents one "hunk" from a patch, starting with
157 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
158 * patch text is pointed at by patch, and its byte length
159 * is stored in size. leading and trailing are the number
163 unsigned long leading
, trailing
;
164 unsigned long oldpos
, oldlines
;
165 unsigned long newpos
, newlines
;
167 * 'patch' is usually borrowed from buf in apply_patch(),
168 * but some codepaths store an allocated buffer.
171 unsigned free_patch
:1,
175 struct fragment
*next
;
179 * When dealing with a binary patch, we reuse "leading" field
180 * to store the type of the binary hunk, either deflated "delta"
181 * or deflated "literal".
183 #define binary_patch_method leading
184 #define BINARY_DELTA_DEFLATED 1
185 #define BINARY_LITERAL_DEFLATED 2
188 * This represents a "patch" to a file, both metainfo changes
189 * such as creation/deletion, filemode and content changes represented
190 * as a series of fragments.
193 char *new_name
, *old_name
, *def_name
;
194 unsigned int old_mode
, new_mode
;
195 int is_new
, is_delete
; /* -1 = unknown, 0 = false, 1 = true */
198 int lines_added
, lines_deleted
;
200 unsigned int is_toplevel_relative
:1;
201 unsigned int inaccurate_eof
:1;
202 unsigned int is_binary
:1;
203 unsigned int is_copy
:1;
204 unsigned int is_rename
:1;
205 unsigned int recount
:1;
206 unsigned int conflicted_threeway
:1;
207 unsigned int direct_to_threeway
:1;
208 struct fragment
*fragments
;
211 char old_sha1_prefix
[41];
212 char new_sha1_prefix
[41];
215 /* three-way fallback result */
216 struct object_id threeway_stage
[3];
219 static void free_fragment_list(struct fragment
*list
)
222 struct fragment
*next
= list
->next
;
223 if (list
->free_patch
)
224 free((char *)list
->patch
);
230 static void free_patch(struct patch
*patch
)
232 free_fragment_list(patch
->fragments
);
233 free(patch
->def_name
);
234 free(patch
->old_name
);
235 free(patch
->new_name
);
240 static void free_patch_list(struct patch
*list
)
243 struct patch
*next
= list
->next
;
250 * A line in a file, len-bytes long (includes the terminating LF,
251 * except for an incomplete line at the end if the file ends with
252 * one), and its contents hashes to 'hash'.
258 #define LINE_COMMON 1
259 #define LINE_PATCHED 2
263 * This represents a "file", which is an array of "lines".
270 struct line
*line_allocated
;
275 * Records filenames that have been touched, in order to handle
276 * the case where more than one patches touch the same file.
279 static struct string_list fn_table
;
281 static uint32_t hash_line(const char *cp
, size_t len
)
285 for (i
= 0, h
= 0; i
< len
; i
++) {
286 if (!isspace(cp
[i
])) {
287 h
= h
* 3 + (cp
[i
] & 0xff);
294 * Compare lines s1 of length n1 and s2 of length n2, ignoring
295 * whitespace difference. Returns 1 if they match, 0 otherwise
297 static int fuzzy_matchlines(const char *s1
, size_t n1
,
298 const char *s2
, size_t n2
)
300 const char *last1
= s1
+ n1
- 1;
301 const char *last2
= s2
+ n2
- 1;
304 /* ignore line endings */
305 while ((*last1
== '\r') || (*last1
== '\n'))
307 while ((*last2
== '\r') || (*last2
== '\n'))
310 /* skip leading whitespaces, if both begin with whitespace */
311 if (s1
<= last1
&& s2
<= last2
&& isspace(*s1
) && isspace(*s2
)) {
312 while (isspace(*s1
) && (s1
<= last1
))
314 while (isspace(*s2
) && (s2
<= last2
))
317 /* early return if both lines are empty */
318 if ((s1
> last1
) && (s2
> last2
))
321 result
= *s1
++ - *s2
++;
323 * Skip whitespace inside. We check for whitespace on
324 * both buffers because we don't want "a b" to match
327 if (isspace(*s1
) && isspace(*s2
)) {
328 while (isspace(*s1
) && s1
<= last1
)
330 while (isspace(*s2
) && s2
<= last2
)
334 * If we reached the end on one side only,
338 ((s2
> last2
) && (s1
<= last1
)) ||
339 ((s1
> last1
) && (s2
<= last2
)))
341 if ((s1
> last1
) && (s2
> last2
))
348 static void add_line_info(struct image
*img
, const char *bol
, size_t len
, unsigned flag
)
350 ALLOC_GROW(img
->line_allocated
, img
->nr
+ 1, img
->alloc
);
351 img
->line_allocated
[img
->nr
].len
= len
;
352 img
->line_allocated
[img
->nr
].hash
= hash_line(bol
, len
);
353 img
->line_allocated
[img
->nr
].flag
= flag
;
358 * "buf" has the file contents to be patched (read from various sources).
359 * attach it to "image" and add line-based index to it.
360 * "image" now owns the "buf".
362 static void prepare_image(struct image
*image
, char *buf
, size_t len
,
363 int prepare_linetable
)
367 memset(image
, 0, sizeof(*image
));
371 if (!prepare_linetable
)
374 ep
= image
->buf
+ image
->len
;
378 for (next
= cp
; next
< ep
&& *next
!= '\n'; next
++)
382 add_line_info(image
, cp
, next
- cp
, 0);
385 image
->line
= image
->line_allocated
;
388 static void clear_image(struct image
*image
)
391 free(image
->line_allocated
);
392 memset(image
, 0, sizeof(*image
));
395 /* fmt must contain _one_ %s and no other substitution */
396 static void say_patch_name(FILE *output
, const char *fmt
, struct patch
*patch
)
398 struct strbuf sb
= STRBUF_INIT
;
400 if (patch
->old_name
&& patch
->new_name
&&
401 strcmp(patch
->old_name
, patch
->new_name
)) {
402 quote_c_style(patch
->old_name
, &sb
, NULL
, 0);
403 strbuf_addstr(&sb
, " => ");
404 quote_c_style(patch
->new_name
, &sb
, NULL
, 0);
406 const char *n
= patch
->new_name
;
409 quote_c_style(n
, &sb
, NULL
, 0);
411 fprintf(output
, fmt
, sb
.buf
);
418 static void read_patch_file(struct strbuf
*sb
, int fd
)
420 if (strbuf_read(sb
, fd
, 0) < 0)
421 die_errno("git apply: failed to read");
424 * Make sure that we have some slop in the buffer
425 * so that we can do speculative "memcmp" etc, and
426 * see to it that it is NUL-filled.
428 strbuf_grow(sb
, SLOP
);
429 memset(sb
->buf
+ sb
->len
, 0, SLOP
);
432 static unsigned long linelen(const char *buffer
, unsigned long size
)
434 unsigned long len
= 0;
437 if (*buffer
++ == '\n')
443 static int is_dev_null(const char *str
)
445 return skip_prefix(str
, "/dev/null", &str
) && isspace(*str
);
451 static int name_terminate(const char *name
, int namelen
, int c
, int terminate
)
453 if (c
== ' ' && !(terminate
& TERM_SPACE
))
455 if (c
== '\t' && !(terminate
& TERM_TAB
))
461 /* remove double slashes to make --index work with such filenames */
462 static char *squash_slash(char *name
)
470 if ((name
[j
++] = name
[i
++]) == '/')
471 while (name
[i
] == '/')
478 static char *find_name_gnu(struct apply_state
*state
,
483 struct strbuf name
= STRBUF_INIT
;
487 * Proposed "new-style" GNU patch/diff format; see
488 * http://marc.info/?l=git&m=112927316408690&w=2
490 if (unquote_c_style(&name
, line
, NULL
)) {
491 strbuf_release(&name
);
495 for (cp
= name
.buf
; p_value
; p_value
--) {
496 cp
= strchr(cp
, '/');
498 strbuf_release(&name
);
504 strbuf_remove(&name
, 0, cp
- name
.buf
);
506 strbuf_insert(&name
, 0, state
->root
.buf
, state
->root
.len
);
507 return squash_slash(strbuf_detach(&name
, NULL
));
510 static size_t sane_tz_len(const char *line
, size_t len
)
514 if (len
< strlen(" +0500") || line
[len
-strlen(" +0500")] != ' ')
516 tz
= line
+ len
- strlen(" +0500");
518 if (tz
[1] != '+' && tz
[1] != '-')
521 for (p
= tz
+ 2; p
!= line
+ len
; p
++)
525 return line
+ len
- tz
;
528 static size_t tz_with_colon_len(const char *line
, size_t len
)
532 if (len
< strlen(" +08:00") || line
[len
- strlen(":00")] != ':')
534 tz
= line
+ len
- strlen(" +08:00");
536 if (tz
[0] != ' ' || (tz
[1] != '+' && tz
[1] != '-'))
539 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
540 !isdigit(*p
++) || !isdigit(*p
++))
543 return line
+ len
- tz
;
546 static size_t date_len(const char *line
, size_t len
)
548 const char *date
, *p
;
550 if (len
< strlen("72-02-05") || line
[len
-strlen("-05")] != '-')
552 p
= date
= line
+ len
- strlen("72-02-05");
554 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
555 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
556 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a date. */
559 if (date
- line
>= strlen("19") &&
560 isdigit(date
[-1]) && isdigit(date
[-2])) /* 4-digit year */
561 date
-= strlen("19");
563 return line
+ len
- date
;
566 static size_t short_time_len(const char *line
, size_t len
)
568 const char *time
, *p
;
570 if (len
< strlen(" 07:01:32") || line
[len
-strlen(":32")] != ':')
572 p
= time
= line
+ len
- strlen(" 07:01:32");
574 /* Permit 1-digit hours? */
576 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
577 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
578 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a time. */
581 return line
+ len
- time
;
584 static size_t fractional_time_len(const char *line
, size_t len
)
589 /* Expected format: 19:41:17.620000023 */
590 if (!len
|| !isdigit(line
[len
- 1]))
594 /* Fractional seconds. */
595 while (p
> line
&& isdigit(*p
))
600 /* Hours, minutes, and whole seconds. */
601 n
= short_time_len(line
, p
- line
);
605 return line
+ len
- p
+ n
;
608 static size_t trailing_spaces_len(const char *line
, size_t len
)
612 /* Expected format: ' ' x (1 or more) */
613 if (!len
|| line
[len
- 1] != ' ')
620 return line
+ len
- (p
+ 1);
627 static size_t diff_timestamp_len(const char *line
, size_t len
)
629 const char *end
= line
+ len
;
633 * Posix: 2010-07-05 19:41:17
634 * GNU: 2010-07-05 19:41:17.620000023 -0500
637 if (!isdigit(end
[-1]))
640 n
= sane_tz_len(line
, end
- line
);
642 n
= tz_with_colon_len(line
, end
- line
);
645 n
= short_time_len(line
, end
- line
);
647 n
= fractional_time_len(line
, end
- line
);
650 n
= date_len(line
, end
- line
);
651 if (!n
) /* No date. Too bad. */
655 if (end
== line
) /* No space before date. */
657 if (end
[-1] == '\t') { /* Success! */
659 return line
+ len
- end
;
661 if (end
[-1] != ' ') /* No space before date. */
664 /* Whitespace damage. */
665 end
-= trailing_spaces_len(line
, end
- line
);
666 return line
+ len
- end
;
669 static char *find_name_common(struct apply_state
*state
,
677 const char *start
= NULL
;
681 while (line
!= end
) {
684 if (!end
&& isspace(c
)) {
687 if (name_terminate(start
, line
-start
, c
, terminate
))
691 if (c
== '/' && !--p_value
)
695 return squash_slash(xstrdup_or_null(def
));
698 return squash_slash(xstrdup_or_null(def
));
701 * Generally we prefer the shorter name, especially
702 * if the other one is just a variation of that with
703 * something else tacked on to the end (ie "file.orig"
707 int deflen
= strlen(def
);
708 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
709 return squash_slash(xstrdup(def
));
712 if (state
->root
.len
) {
713 char *ret
= xstrfmt("%s%.*s", state
->root
.buf
, len
, start
);
714 return squash_slash(ret
);
717 return squash_slash(xmemdupz(start
, len
));
720 static char *find_name(struct apply_state
*state
,
727 char *name
= find_name_gnu(state
, line
, def
, p_value
);
732 return find_name_common(state
, line
, def
, p_value
, NULL
, terminate
);
735 static char *find_name_traditional(struct apply_state
*state
,
744 char *name
= find_name_gnu(state
, line
, def
, p_value
);
749 len
= strchrnul(line
, '\n') - line
;
750 date_len
= diff_timestamp_len(line
, len
);
752 return find_name_common(state
, line
, def
, p_value
, NULL
, TERM_TAB
);
755 return find_name_common(state
, line
, def
, p_value
, line
+ len
, 0);
758 static int count_slashes(const char *cp
)
770 * Given the string after "--- " or "+++ ", guess the appropriate
771 * p_value for the given patch.
773 static int guess_p_value(struct apply_state
*state
, const char *nameline
)
778 if (is_dev_null(nameline
))
780 name
= find_name_traditional(state
, nameline
, NULL
, 0);
783 cp
= strchr(name
, '/');
786 else if (state
->prefix
) {
788 * Does it begin with "a/$our-prefix" and such? Then this is
789 * very likely to apply to our directory.
791 if (!strncmp(name
, state
->prefix
, state
->prefix_length
))
792 val
= count_slashes(state
->prefix
);
795 if (!strncmp(cp
, state
->prefix
, state
->prefix_length
))
796 val
= count_slashes(state
->prefix
) + 1;
804 * Does the ---/+++ line have the POSIX timestamp after the last HT?
805 * GNU diff puts epoch there to signal a creation/deletion event. Is
806 * this such a timestamp?
808 static int has_epoch_timestamp(const char *nameline
)
811 * We are only interested in epoch timestamp; any non-zero
812 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
813 * For the same reason, the date must be either 1969-12-31 or
814 * 1970-01-01, and the seconds part must be "00".
816 const char stamp_regexp
[] =
817 "^(1969-12-31|1970-01-01)"
819 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
821 "([-+][0-2][0-9]:?[0-5][0-9])\n";
822 const char *timestamp
= NULL
, *cp
, *colon
;
823 static regex_t
*stamp
;
829 for (cp
= nameline
; *cp
!= '\n'; cp
++) {
836 stamp
= xmalloc(sizeof(*stamp
));
837 if (regcomp(stamp
, stamp_regexp
, REG_EXTENDED
)) {
838 warning(_("Cannot prepare timestamp regexp %s"),
844 status
= regexec(stamp
, timestamp
, ARRAY_SIZE(m
), m
, 0);
846 if (status
!= REG_NOMATCH
)
847 warning(_("regexec returned %d for input: %s"),
852 zoneoffset
= strtol(timestamp
+ m
[3].rm_so
+ 1, (char **) &colon
, 10);
854 zoneoffset
= zoneoffset
* 60 + strtol(colon
+ 1, NULL
, 10);
856 zoneoffset
= (zoneoffset
/ 100) * 60 + (zoneoffset
% 100);
857 if (timestamp
[m
[3].rm_so
] == '-')
858 zoneoffset
= -zoneoffset
;
861 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
862 * (west of GMT) or 1970-01-01 (east of GMT)
864 if ((zoneoffset
< 0 && memcmp(timestamp
, "1969-12-31", 10)) ||
865 (0 <= zoneoffset
&& memcmp(timestamp
, "1970-01-01", 10)))
868 hourminute
= (strtol(timestamp
+ 11, NULL
, 10) * 60 +
869 strtol(timestamp
+ 14, NULL
, 10) -
872 return ((zoneoffset
< 0 && hourminute
== 1440) ||
873 (0 <= zoneoffset
&& !hourminute
));
877 * Get the name etc info from the ---/+++ lines of a traditional patch header
879 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
880 * files, we can happily check the index for a match, but for creating a
881 * new file we should try to match whatever "patch" does. I have no idea.
883 static void parse_traditional_patch(struct apply_state
*state
,
890 first
+= 4; /* skip "--- " */
891 second
+= 4; /* skip "+++ " */
892 if (!state
->p_value_known
) {
894 p
= guess_p_value(state
, first
);
895 q
= guess_p_value(state
, second
);
897 if (0 <= p
&& p
== q
) {
899 state
->p_value_known
= 1;
902 if (is_dev_null(first
)) {
904 patch
->is_delete
= 0;
905 name
= find_name_traditional(state
, second
, NULL
, state
->p_value
);
906 patch
->new_name
= name
;
907 } else if (is_dev_null(second
)) {
909 patch
->is_delete
= 1;
910 name
= find_name_traditional(state
, first
, NULL
, state
->p_value
);
911 patch
->old_name
= name
;
914 first_name
= find_name_traditional(state
, first
, NULL
, state
->p_value
);
915 name
= find_name_traditional(state
, second
, first_name
, state
->p_value
);
917 if (has_epoch_timestamp(first
)) {
919 patch
->is_delete
= 0;
920 patch
->new_name
= name
;
921 } else if (has_epoch_timestamp(second
)) {
923 patch
->is_delete
= 1;
924 patch
->old_name
= name
;
926 patch
->old_name
= name
;
927 patch
->new_name
= xstrdup_or_null(name
);
931 die(_("unable to find filename in patch at line %d"), state_linenr
);
934 static int gitdiff_hdrend(struct apply_state
*state
,
942 * We're anal about diff header consistency, to make
943 * sure that we don't end up having strange ambiguous
944 * patches floating around.
946 * As a result, gitdiff_{old|new}name() will check
947 * their names against any previous information, just
950 #define DIFF_OLD_NAME 0
951 #define DIFF_NEW_NAME 1
953 static void gitdiff_verify_name(struct apply_state
*state
,
959 if (!*name
&& !isnull
) {
960 *name
= find_name(state
, line
, NULL
, state
->p_value
, TERM_TAB
);
965 int len
= strlen(*name
);
968 die(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
969 *name
, state_linenr
);
970 another
= find_name(state
, line
, NULL
, state
->p_value
, TERM_TAB
);
971 if (!another
|| memcmp(another
, *name
, len
+ 1))
972 die((side
== DIFF_NEW_NAME
) ?
973 _("git apply: bad git-diff - inconsistent new filename on line %d") :
974 _("git apply: bad git-diff - inconsistent old filename on line %d"), state_linenr
);
977 /* expect "/dev/null" */
978 if (memcmp("/dev/null", line
, 9) || line
[9] != '\n')
979 die(_("git apply: bad git-diff - expected /dev/null on line %d"), state_linenr
);
983 static int gitdiff_oldname(struct apply_state
*state
,
987 gitdiff_verify_name(state
, line
,
988 patch
->is_new
, &patch
->old_name
,
993 static int gitdiff_newname(struct apply_state
*state
,
997 gitdiff_verify_name(state
, line
,
998 patch
->is_delete
, &patch
->new_name
,
1003 static int gitdiff_oldmode(struct apply_state
*state
,
1005 struct patch
*patch
)
1007 patch
->old_mode
= strtoul(line
, NULL
, 8);
1011 static int gitdiff_newmode(struct apply_state
*state
,
1013 struct patch
*patch
)
1015 patch
->new_mode
= strtoul(line
, NULL
, 8);
1019 static int gitdiff_delete(struct apply_state
*state
,
1021 struct patch
*patch
)
1023 patch
->is_delete
= 1;
1024 free(patch
->old_name
);
1025 patch
->old_name
= xstrdup_or_null(patch
->def_name
);
1026 return gitdiff_oldmode(state
, line
, patch
);
1029 static int gitdiff_newfile(struct apply_state
*state
,
1031 struct patch
*patch
)
1034 free(patch
->new_name
);
1035 patch
->new_name
= xstrdup_or_null(patch
->def_name
);
1036 return gitdiff_newmode(state
, line
, patch
);
1039 static int gitdiff_copysrc(struct apply_state
*state
,
1041 struct patch
*patch
)
1044 free(patch
->old_name
);
1045 patch
->old_name
= find_name(state
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1049 static int gitdiff_copydst(struct apply_state
*state
,
1051 struct patch
*patch
)
1054 free(patch
->new_name
);
1055 patch
->new_name
= find_name(state
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1059 static int gitdiff_renamesrc(struct apply_state
*state
,
1061 struct patch
*patch
)
1063 patch
->is_rename
= 1;
1064 free(patch
->old_name
);
1065 patch
->old_name
= find_name(state
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1069 static int gitdiff_renamedst(struct apply_state
*state
,
1071 struct patch
*patch
)
1073 patch
->is_rename
= 1;
1074 free(patch
->new_name
);
1075 patch
->new_name
= find_name(state
, line
, NULL
, state
->p_value
? state
->p_value
- 1 : 0, 0);
1079 static int gitdiff_similarity(struct apply_state
*state
,
1081 struct patch
*patch
)
1083 unsigned long val
= strtoul(line
, NULL
, 10);
1089 static int gitdiff_dissimilarity(struct apply_state
*state
,
1091 struct patch
*patch
)
1093 unsigned long val
= strtoul(line
, NULL
, 10);
1099 static int gitdiff_index(struct apply_state
*state
,
1101 struct patch
*patch
)
1104 * index line is N hexadecimal, "..", N hexadecimal,
1105 * and optional space with octal mode.
1107 const char *ptr
, *eol
;
1110 ptr
= strchr(line
, '.');
1111 if (!ptr
|| ptr
[1] != '.' || 40 < ptr
- line
)
1114 memcpy(patch
->old_sha1_prefix
, line
, len
);
1115 patch
->old_sha1_prefix
[len
] = 0;
1118 ptr
= strchr(line
, ' ');
1119 eol
= strchrnul(line
, '\n');
1121 if (!ptr
|| eol
< ptr
)
1127 memcpy(patch
->new_sha1_prefix
, line
, len
);
1128 patch
->new_sha1_prefix
[len
] = 0;
1130 patch
->old_mode
= strtoul(ptr
+1, NULL
, 8);
1135 * This is normal for a diff that doesn't change anything: we'll fall through
1136 * into the next diff. Tell the parser to break out.
1138 static int gitdiff_unrecognized(struct apply_state
*state
,
1140 struct patch
*patch
)
1146 * Skip p_value leading components from "line"; as we do not accept
1147 * absolute paths, return NULL in that case.
1149 static const char *skip_tree_prefix(struct apply_state
*state
,
1156 if (!state
->p_value
)
1157 return (llen
&& line
[0] == '/') ? NULL
: line
;
1159 nslash
= state
->p_value
;
1160 for (i
= 0; i
< llen
; i
++) {
1162 if (ch
== '/' && --nslash
<= 0)
1163 return (i
== 0) ? NULL
: &line
[i
+ 1];
1169 * This is to extract the same name that appears on "diff --git"
1170 * line. We do not find and return anything if it is a rename
1171 * patch, and it is OK because we will find the name elsewhere.
1172 * We need to reliably find name only when it is mode-change only,
1173 * creation or deletion of an empty file. In any of these cases,
1174 * both sides are the same name under a/ and b/ respectively.
1176 static char *git_header_name(struct apply_state
*state
,
1181 const char *second
= NULL
;
1182 size_t len
, line_len
;
1184 line
+= strlen("diff --git ");
1185 llen
-= strlen("diff --git ");
1189 struct strbuf first
= STRBUF_INIT
;
1190 struct strbuf sp
= STRBUF_INIT
;
1192 if (unquote_c_style(&first
, line
, &second
))
1193 goto free_and_fail1
;
1195 /* strip the a/b prefix including trailing slash */
1196 cp
= skip_tree_prefix(state
, first
.buf
, first
.len
);
1198 goto free_and_fail1
;
1199 strbuf_remove(&first
, 0, cp
- first
.buf
);
1202 * second points at one past closing dq of name.
1203 * find the second name.
1205 while ((second
< line
+ llen
) && isspace(*second
))
1208 if (line
+ llen
<= second
)
1209 goto free_and_fail1
;
1210 if (*second
== '"') {
1211 if (unquote_c_style(&sp
, second
, NULL
))
1212 goto free_and_fail1
;
1213 cp
= skip_tree_prefix(state
, sp
.buf
, sp
.len
);
1215 goto free_and_fail1
;
1216 /* They must match, otherwise ignore */
1217 if (strcmp(cp
, first
.buf
))
1218 goto free_and_fail1
;
1219 strbuf_release(&sp
);
1220 return strbuf_detach(&first
, NULL
);
1223 /* unquoted second */
1224 cp
= skip_tree_prefix(state
, second
, line
+ llen
- second
);
1226 goto free_and_fail1
;
1227 if (line
+ llen
- cp
!= first
.len
||
1228 memcmp(first
.buf
, cp
, first
.len
))
1229 goto free_and_fail1
;
1230 return strbuf_detach(&first
, NULL
);
1233 strbuf_release(&first
);
1234 strbuf_release(&sp
);
1238 /* unquoted first name */
1239 name
= skip_tree_prefix(state
, line
, llen
);
1244 * since the first name is unquoted, a dq if exists must be
1245 * the beginning of the second name.
1247 for (second
= name
; second
< line
+ llen
; second
++) {
1248 if (*second
== '"') {
1249 struct strbuf sp
= STRBUF_INIT
;
1252 if (unquote_c_style(&sp
, second
, NULL
))
1253 goto free_and_fail2
;
1255 np
= skip_tree_prefix(state
, sp
.buf
, sp
.len
);
1257 goto free_and_fail2
;
1259 len
= sp
.buf
+ sp
.len
- np
;
1260 if (len
< second
- name
&&
1261 !strncmp(np
, name
, len
) &&
1262 isspace(name
[len
])) {
1264 strbuf_remove(&sp
, 0, np
- sp
.buf
);
1265 return strbuf_detach(&sp
, NULL
);
1269 strbuf_release(&sp
);
1275 * Accept a name only if it shows up twice, exactly the same
1278 second
= strchr(name
, '\n');
1281 line_len
= second
- name
;
1282 for (len
= 0 ; ; len
++) {
1283 switch (name
[len
]) {
1288 case '\t': case ' ':
1290 * Is this the separator between the preimage
1291 * and the postimage pathname? Again, we are
1292 * only interested in the case where there is
1293 * no rename, as this is only to set def_name
1294 * and a rename patch has the names elsewhere
1295 * in an unambiguous form.
1298 return NULL
; /* no postimage name */
1299 second
= skip_tree_prefix(state
, name
+ len
+ 1,
1300 line_len
- (len
+ 1));
1304 * Does len bytes starting at "name" and "second"
1305 * (that are separated by one HT or SP we just
1306 * found) exactly match?
1308 if (second
[len
] == '\n' && !strncmp(name
, second
, len
))
1309 return xmemdupz(name
, len
);
1314 /* Verify that we recognize the lines following a git header */
1315 static int parse_git_header(struct apply_state
*state
,
1319 struct patch
*patch
)
1321 unsigned long offset
;
1323 /* A git diff has explicit new/delete information, so we don't guess */
1325 patch
->is_delete
= 0;
1328 * Some things may not have the old name in the
1329 * rest of the headers anywhere (pure mode changes,
1330 * or removing or adding empty files), so we get
1331 * the default name from the header.
1333 patch
->def_name
= git_header_name(state
, line
, len
);
1334 if (patch
->def_name
&& state
->root
.len
) {
1335 char *s
= xstrfmt("%s%s", state
->root
.buf
, patch
->def_name
);
1336 free(patch
->def_name
);
1337 patch
->def_name
= s
;
1343 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, state_linenr
++) {
1344 static const struct opentry
{
1346 int (*fn
)(struct apply_state
*, const char *, struct patch
*);
1348 { "@@ -", gitdiff_hdrend
},
1349 { "--- ", gitdiff_oldname
},
1350 { "+++ ", gitdiff_newname
},
1351 { "old mode ", gitdiff_oldmode
},
1352 { "new mode ", gitdiff_newmode
},
1353 { "deleted file mode ", gitdiff_delete
},
1354 { "new file mode ", gitdiff_newfile
},
1355 { "copy from ", gitdiff_copysrc
},
1356 { "copy to ", gitdiff_copydst
},
1357 { "rename old ", gitdiff_renamesrc
},
1358 { "rename new ", gitdiff_renamedst
},
1359 { "rename from ", gitdiff_renamesrc
},
1360 { "rename to ", gitdiff_renamedst
},
1361 { "similarity index ", gitdiff_similarity
},
1362 { "dissimilarity index ", gitdiff_dissimilarity
},
1363 { "index ", gitdiff_index
},
1364 { "", gitdiff_unrecognized
},
1368 len
= linelen(line
, size
);
1369 if (!len
|| line
[len
-1] != '\n')
1371 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
1372 const struct opentry
*p
= optable
+ i
;
1373 int oplen
= strlen(p
->str
);
1374 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
1376 if (p
->fn(state
, line
+ oplen
, patch
) < 0)
1385 static int parse_num(const char *line
, unsigned long *p
)
1389 if (!isdigit(*line
))
1391 *p
= strtoul(line
, &ptr
, 10);
1395 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
1396 unsigned long *p1
, unsigned long *p2
)
1400 if (offset
< 0 || offset
>= len
)
1405 digits
= parse_num(line
, p1
);
1415 digits
= parse_num(line
+1, p2
);
1424 ex
= strlen(expect
);
1427 if (memcmp(line
, expect
, ex
))
1433 static void recount_diff(const char *line
, int size
, struct fragment
*fragment
)
1435 int oldlines
= 0, newlines
= 0, ret
= 0;
1438 warning("recount: ignore empty hunk");
1443 int len
= linelen(line
, size
);
1451 case ' ': case '\n':
1463 ret
= size
< 3 || !starts_with(line
, "@@ ");
1466 ret
= size
< 5 || !starts_with(line
, "diff ");
1473 warning(_("recount: unexpected line: %.*s"),
1474 (int)linelen(line
, size
), line
);
1479 fragment
->oldlines
= oldlines
;
1480 fragment
->newlines
= newlines
;
1484 * Parse a unified diff fragment header of the
1485 * form "@@ -a,b +c,d @@"
1487 static int parse_fragment_header(const char *line
, int len
, struct fragment
*fragment
)
1491 if (!len
|| line
[len
-1] != '\n')
1494 /* Figure out the number of lines in a fragment */
1495 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
1496 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
1501 static int find_header(struct apply_state
*state
,
1505 struct patch
*patch
)
1507 unsigned long offset
, len
;
1509 patch
->is_toplevel_relative
= 0;
1510 patch
->is_rename
= patch
->is_copy
= 0;
1511 patch
->is_new
= patch
->is_delete
= -1;
1512 patch
->old_mode
= patch
->new_mode
= 0;
1513 patch
->old_name
= patch
->new_name
= NULL
;
1514 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, state_linenr
++) {
1515 unsigned long nextlen
;
1517 len
= linelen(line
, size
);
1521 /* Testing this early allows us to take a few shortcuts.. */
1526 * Make sure we don't find any unconnected patch fragments.
1527 * That's a sign that we didn't find a header, and that a
1528 * patch has become corrupted/broken up.
1530 if (!memcmp("@@ -", line
, 4)) {
1531 struct fragment dummy
;
1532 if (parse_fragment_header(line
, len
, &dummy
) < 0)
1534 die(_("patch fragment without header at line %d: %.*s"),
1535 state_linenr
, (int)len
-1, line
);
1542 * Git patch? It might not have a real patch, just a rename
1543 * or mode change, so we handle that specially
1545 if (!memcmp("diff --git ", line
, 11)) {
1546 int git_hdr_len
= parse_git_header(state
, line
, len
, size
, patch
);
1547 if (git_hdr_len
<= len
)
1549 if (!patch
->old_name
&& !patch
->new_name
) {
1550 if (!patch
->def_name
)
1551 die(Q_("git diff header lacks filename information when removing "
1552 "%d leading pathname component (line %d)",
1553 "git diff header lacks filename information when removing "
1554 "%d leading pathname components (line %d)",
1556 state
->p_value
, state_linenr
);
1557 patch
->old_name
= xstrdup(patch
->def_name
);
1558 patch
->new_name
= xstrdup(patch
->def_name
);
1560 if (!patch
->is_delete
&& !patch
->new_name
)
1561 die("git diff header lacks filename information "
1562 "(line %d)", state_linenr
);
1563 patch
->is_toplevel_relative
= 1;
1564 *hdrsize
= git_hdr_len
;
1568 /* --- followed by +++ ? */
1569 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
1573 * We only accept unified patches, so we want it to
1574 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1575 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1577 nextlen
= linelen(line
+ len
, size
- len
);
1578 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
1581 /* Ok, we'll consider it a patch */
1582 parse_traditional_patch(state
, line
, line
+len
, patch
);
1583 *hdrsize
= len
+ nextlen
;
1590 static void record_ws_error(struct apply_state
*state
,
1601 state
->whitespace_error
++;
1602 if (squelch_whitespace_errors
&&
1603 squelch_whitespace_errors
< state
->whitespace_error
)
1606 err
= whitespace_error_string(result
);
1607 fprintf(stderr
, "%s:%d: %s.\n%.*s\n",
1608 state
->patch_input_file
, linenr
, err
, len
, line
);
1612 static void check_whitespace(struct apply_state
*state
,
1617 unsigned result
= ws_check(line
+ 1, len
- 1, ws_rule
);
1619 record_ws_error(state
, result
, line
+ 1, len
- 2, state_linenr
);
1623 * Parse a unified diff. Note that this really needs to parse each
1624 * fragment separately, since the only way to know the difference
1625 * between a "---" that is part of a patch, and a "---" that starts
1626 * the next patch is to look at the line counts..
1628 static int parse_fragment(struct apply_state
*state
,
1631 struct patch
*patch
,
1632 struct fragment
*fragment
)
1635 int len
= linelen(line
, size
), offset
;
1636 unsigned long oldlines
, newlines
;
1637 unsigned long leading
, trailing
;
1639 offset
= parse_fragment_header(line
, len
, fragment
);
1642 if (offset
> 0 && patch
->recount
)
1643 recount_diff(line
+ offset
, size
- offset
, fragment
);
1644 oldlines
= fragment
->oldlines
;
1645 newlines
= fragment
->newlines
;
1649 /* Parse the thing.. */
1653 added
= deleted
= 0;
1656 offset
+= len
, size
-= len
, line
+= len
, state_linenr
++) {
1657 if (!oldlines
&& !newlines
)
1659 len
= linelen(line
, size
);
1660 if (!len
|| line
[len
-1] != '\n')
1665 case '\n': /* newer GNU diff, an empty context line */
1669 if (!deleted
&& !added
)
1672 if (!state
->apply_in_reverse
&&
1673 ws_error_action
== correct_ws_error
)
1674 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1677 if (state
->apply_in_reverse
&&
1678 ws_error_action
!= nowarn_ws_error
)
1679 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1685 if (!state
->apply_in_reverse
&&
1686 ws_error_action
!= nowarn_ws_error
)
1687 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1694 * We allow "\ No newline at end of file". Depending
1695 * on locale settings when the patch was produced we
1696 * don't know what this line looks like. The only
1697 * thing we do know is that it begins with "\ ".
1698 * Checking for 12 is just for sanity check -- any
1699 * l10n of "\ No newline..." is at least that long.
1702 if (len
< 12 || memcmp(line
, "\\ ", 2))
1707 if (oldlines
|| newlines
)
1709 if (!deleted
&& !added
)
1712 fragment
->leading
= leading
;
1713 fragment
->trailing
= trailing
;
1716 * If a fragment ends with an incomplete line, we failed to include
1717 * it in the above loop because we hit oldlines == newlines == 0
1720 if (12 < size
&& !memcmp(line
, "\\ ", 2))
1721 offset
+= linelen(line
, size
);
1723 patch
->lines_added
+= added
;
1724 patch
->lines_deleted
+= deleted
;
1726 if (0 < patch
->is_new
&& oldlines
)
1727 return error(_("new file depends on old contents"));
1728 if (0 < patch
->is_delete
&& newlines
)
1729 return error(_("deleted file still has contents"));
1734 * We have seen "diff --git a/... b/..." header (or a traditional patch
1735 * header). Read hunks that belong to this patch into fragments and hang
1736 * them to the given patch structure.
1738 * The (fragment->patch, fragment->size) pair points into the memory given
1739 * by the caller, not a copy, when we return.
1741 static int parse_single_patch(struct apply_state
*state
,
1744 struct patch
*patch
)
1746 unsigned long offset
= 0;
1747 unsigned long oldlines
= 0, newlines
= 0, context
= 0;
1748 struct fragment
**fragp
= &patch
->fragments
;
1750 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
1751 struct fragment
*fragment
;
1754 fragment
= xcalloc(1, sizeof(*fragment
));
1755 fragment
->linenr
= state_linenr
;
1756 len
= parse_fragment(state
, line
, size
, patch
, fragment
);
1758 die(_("corrupt patch at line %d"), state_linenr
);
1759 fragment
->patch
= line
;
1760 fragment
->size
= len
;
1761 oldlines
+= fragment
->oldlines
;
1762 newlines
+= fragment
->newlines
;
1763 context
+= fragment
->leading
+ fragment
->trailing
;
1766 fragp
= &fragment
->next
;
1774 * If something was removed (i.e. we have old-lines) it cannot
1775 * be creation, and if something was added it cannot be
1776 * deletion. However, the reverse is not true; --unified=0
1777 * patches that only add are not necessarily creation even
1778 * though they do not have any old lines, and ones that only
1779 * delete are not necessarily deletion.
1781 * Unfortunately, a real creation/deletion patch do _not_ have
1782 * any context line by definition, so we cannot safely tell it
1783 * apart with --unified=0 insanity. At least if the patch has
1784 * more than one hunk it is not creation or deletion.
1786 if (patch
->is_new
< 0 &&
1787 (oldlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1789 if (patch
->is_delete
< 0 &&
1790 (newlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1791 patch
->is_delete
= 0;
1793 if (0 < patch
->is_new
&& oldlines
)
1794 die(_("new file %s depends on old contents"), patch
->new_name
);
1795 if (0 < patch
->is_delete
&& newlines
)
1796 die(_("deleted file %s still has contents"), patch
->old_name
);
1797 if (!patch
->is_delete
&& !newlines
&& context
)
1800 "file %s becomes empty but is not deleted"),
1806 static inline int metadata_changes(struct patch
*patch
)
1808 return patch
->is_rename
> 0 ||
1809 patch
->is_copy
> 0 ||
1810 patch
->is_new
> 0 ||
1812 (patch
->old_mode
&& patch
->new_mode
&&
1813 patch
->old_mode
!= patch
->new_mode
);
1816 static char *inflate_it(const void *data
, unsigned long size
,
1817 unsigned long inflated_size
)
1823 memset(&stream
, 0, sizeof(stream
));
1825 stream
.next_in
= (unsigned char *)data
;
1826 stream
.avail_in
= size
;
1827 stream
.next_out
= out
= xmalloc(inflated_size
);
1828 stream
.avail_out
= inflated_size
;
1829 git_inflate_init(&stream
);
1830 st
= git_inflate(&stream
, Z_FINISH
);
1831 git_inflate_end(&stream
);
1832 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1840 * Read a binary hunk and return a new fragment; fragment->patch
1841 * points at an allocated memory that the caller must free, so
1842 * it is marked as "->free_patch = 1".
1844 static struct fragment
*parse_binary_hunk(char **buf_p
,
1845 unsigned long *sz_p
,
1850 * Expect a line that begins with binary patch method ("literal"
1851 * or "delta"), followed by the length of data before deflating.
1852 * a sequence of 'length-byte' followed by base-85 encoded data
1853 * should follow, terminated by a newline.
1855 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1856 * and we would limit the patch line to 66 characters,
1857 * so one line can fit up to 13 groups that would decode
1858 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1859 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1862 unsigned long size
= *sz_p
;
1863 char *buffer
= *buf_p
;
1865 unsigned long origlen
;
1868 struct fragment
*frag
;
1870 llen
= linelen(buffer
, size
);
1875 if (starts_with(buffer
, "delta ")) {
1876 patch_method
= BINARY_DELTA_DEFLATED
;
1877 origlen
= strtoul(buffer
+ 6, NULL
, 10);
1879 else if (starts_with(buffer
, "literal ")) {
1880 patch_method
= BINARY_LITERAL_DEFLATED
;
1881 origlen
= strtoul(buffer
+ 8, NULL
, 10);
1889 int byte_length
, max_byte_length
, newsize
;
1890 llen
= linelen(buffer
, size
);
1894 /* consume the blank line */
1900 * Minimum line is "A00000\n" which is 7-byte long,
1901 * and the line length must be multiple of 5 plus 2.
1903 if ((llen
< 7) || (llen
-2) % 5)
1905 max_byte_length
= (llen
- 2) / 5 * 4;
1906 byte_length
= *buffer
;
1907 if ('A' <= byte_length
&& byte_length
<= 'Z')
1908 byte_length
= byte_length
- 'A' + 1;
1909 else if ('a' <= byte_length
&& byte_length
<= 'z')
1910 byte_length
= byte_length
- 'a' + 27;
1913 /* if the input length was not multiple of 4, we would
1914 * have filler at the end but the filler should never
1917 if (max_byte_length
< byte_length
||
1918 byte_length
<= max_byte_length
- 4)
1920 newsize
= hunk_size
+ byte_length
;
1921 data
= xrealloc(data
, newsize
);
1922 if (decode_85(data
+ hunk_size
, buffer
+ 1, byte_length
))
1924 hunk_size
= newsize
;
1929 frag
= xcalloc(1, sizeof(*frag
));
1930 frag
->patch
= inflate_it(data
, hunk_size
, origlen
);
1931 frag
->free_patch
= 1;
1935 frag
->size
= origlen
;
1939 frag
->binary_patch_method
= patch_method
;
1945 error(_("corrupt binary patch at line %d: %.*s"),
1946 state_linenr
-1, llen
-1, buffer
);
1952 * -1 in case of error,
1953 * the length of the parsed binary patch otherwise
1955 static int parse_binary(char *buffer
, unsigned long size
, struct patch
*patch
)
1958 * We have read "GIT binary patch\n"; what follows is a line
1959 * that says the patch method (currently, either "literal" or
1960 * "delta") and the length of data before deflating; a
1961 * sequence of 'length-byte' followed by base-85 encoded data
1964 * When a binary patch is reversible, there is another binary
1965 * hunk in the same format, starting with patch method (either
1966 * "literal" or "delta") with the length of data, and a sequence
1967 * of length-byte + base-85 encoded data, terminated with another
1968 * empty line. This data, when applied to the postimage, produces
1971 struct fragment
*forward
;
1972 struct fragment
*reverse
;
1976 forward
= parse_binary_hunk(&buffer
, &size
, &status
, &used
);
1977 if (!forward
&& !status
)
1978 /* there has to be one hunk (forward hunk) */
1979 return error(_("unrecognized binary patch at line %d"), state_linenr
-1);
1981 /* otherwise we already gave an error message */
1984 reverse
= parse_binary_hunk(&buffer
, &size
, &status
, &used_1
);
1989 * Not having reverse hunk is not an error, but having
1990 * a corrupt reverse hunk is.
1992 free((void*) forward
->patch
);
1996 forward
->next
= reverse
;
1997 patch
->fragments
= forward
;
1998 patch
->is_binary
= 1;
2002 static void prefix_one(struct apply_state
*state
, char **name
)
2004 char *old_name
= *name
;
2007 *name
= xstrdup(prefix_filename(state
->prefix
, state
->prefix_length
, *name
));
2011 static void prefix_patch(struct apply_state
*state
, struct patch
*p
)
2013 if (!state
->prefix
|| p
->is_toplevel_relative
)
2015 prefix_one(state
, &p
->new_name
);
2016 prefix_one(state
, &p
->old_name
);
2023 static void add_name_limit(struct apply_state
*state
,
2027 struct string_list_item
*it
;
2029 it
= string_list_append(&state
->limit_by_name
, name
);
2030 it
->util
= exclude
? NULL
: (void *) 1;
2033 static int use_patch(struct apply_state
*state
, struct patch
*p
)
2035 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
2038 /* Paths outside are not touched regardless of "--include" */
2039 if (0 < state
->prefix_length
) {
2040 int pathlen
= strlen(pathname
);
2041 if (pathlen
<= state
->prefix_length
||
2042 memcmp(state
->prefix
, pathname
, state
->prefix_length
))
2046 /* See if it matches any of exclude/include rule */
2047 for (i
= 0; i
< state
->limit_by_name
.nr
; i
++) {
2048 struct string_list_item
*it
= &state
->limit_by_name
.items
[i
];
2049 if (!wildmatch(it
->string
, pathname
, 0, NULL
))
2050 return (it
->util
!= NULL
);
2054 * If we had any include, a path that does not match any rule is
2055 * not used. Otherwise, we saw bunch of exclude rules (or none)
2056 * and such a path is used.
2058 return !state
->has_include
;
2063 * Read the patch text in "buffer" that extends for "size" bytes; stop
2064 * reading after seeing a single patch (i.e. changes to a single file).
2065 * Create fragments (i.e. patch hunks) and hang them to the given patch.
2066 * Return the number of bytes consumed, so that the caller can call us
2067 * again for the next patch.
2069 static int parse_chunk(struct apply_state
*state
, char *buffer
, unsigned long size
, struct patch
*patch
)
2071 int hdrsize
, patchsize
;
2072 int offset
= find_header(state
, buffer
, size
, &hdrsize
, patch
);
2077 prefix_patch(state
, patch
);
2079 if (!use_patch(state
, patch
))
2082 patch
->ws_rule
= whitespace_rule(patch
->new_name
2086 patchsize
= parse_single_patch(state
,
2087 buffer
+ offset
+ hdrsize
,
2088 size
- offset
- hdrsize
,
2092 static const char git_binary
[] = "GIT binary patch\n";
2093 int hd
= hdrsize
+ offset
;
2094 unsigned long llen
= linelen(buffer
+ hd
, size
- hd
);
2096 if (llen
== sizeof(git_binary
) - 1 &&
2097 !memcmp(git_binary
, buffer
+ hd
, llen
)) {
2100 used
= parse_binary(buffer
+ hd
+ llen
,
2101 size
- hd
- llen
, patch
);
2105 patchsize
= used
+ llen
;
2109 else if (!memcmp(" differ\n", buffer
+ hd
+ llen
- 8, 8)) {
2110 static const char *binhdr
[] = {
2116 for (i
= 0; binhdr
[i
]; i
++) {
2117 int len
= strlen(binhdr
[i
]);
2118 if (len
< size
- hd
&&
2119 !memcmp(binhdr
[i
], buffer
+ hd
, len
)) {
2121 patch
->is_binary
= 1;
2128 /* Empty patch cannot be applied if it is a text patch
2129 * without metadata change. A binary patch appears
2132 if ((state
->apply
|| state
->check
) &&
2133 (!patch
->is_binary
&& !metadata_changes(patch
)))
2134 die(_("patch with only garbage at line %d"), state_linenr
);
2137 return offset
+ hdrsize
+ patchsize
;
2140 #define swap(a,b) myswap((a),(b),sizeof(a))
2142 #define myswap(a, b, size) do { \
2143 unsigned char mytmp[size]; \
2144 memcpy(mytmp, &a, size); \
2145 memcpy(&a, &b, size); \
2146 memcpy(&b, mytmp, size); \
2149 static void reverse_patches(struct patch
*p
)
2151 for (; p
; p
= p
->next
) {
2152 struct fragment
*frag
= p
->fragments
;
2154 swap(p
->new_name
, p
->old_name
);
2155 swap(p
->new_mode
, p
->old_mode
);
2156 swap(p
->is_new
, p
->is_delete
);
2157 swap(p
->lines_added
, p
->lines_deleted
);
2158 swap(p
->old_sha1_prefix
, p
->new_sha1_prefix
);
2160 for (; frag
; frag
= frag
->next
) {
2161 swap(frag
->newpos
, frag
->oldpos
);
2162 swap(frag
->newlines
, frag
->oldlines
);
2167 static const char pluses
[] =
2168 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2169 static const char minuses
[]=
2170 "----------------------------------------------------------------------";
2172 static void show_stats(struct patch
*patch
)
2174 struct strbuf qname
= STRBUF_INIT
;
2175 char *cp
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
2178 quote_c_style(cp
, &qname
, NULL
, 0);
2181 * "scale" the filename
2187 if (qname
.len
> max
) {
2188 cp
= strchr(qname
.buf
+ qname
.len
+ 3 - max
, '/');
2190 cp
= qname
.buf
+ qname
.len
+ 3 - max
;
2191 strbuf_splice(&qname
, 0, cp
- qname
.buf
, "...", 3);
2194 if (patch
->is_binary
) {
2195 printf(" %-*s | Bin\n", max
, qname
.buf
);
2196 strbuf_release(&qname
);
2200 printf(" %-*s |", max
, qname
.buf
);
2201 strbuf_release(&qname
);
2204 * scale the add/delete
2206 max
= max
+ max_change
> 70 ? 70 - max
: max_change
;
2207 add
= patch
->lines_added
;
2208 del
= patch
->lines_deleted
;
2210 if (max_change
> 0) {
2211 int total
= ((add
+ del
) * max
+ max_change
/ 2) / max_change
;
2212 add
= (add
* max
+ max_change
/ 2) / max_change
;
2215 printf("%5d %.*s%.*s\n", patch
->lines_added
+ patch
->lines_deleted
,
2216 add
, pluses
, del
, minuses
);
2219 static int read_old_data(struct stat
*st
, const char *path
, struct strbuf
*buf
)
2221 switch (st
->st_mode
& S_IFMT
) {
2223 if (strbuf_readlink(buf
, path
, st
->st_size
) < 0)
2224 return error(_("unable to read symlink %s"), path
);
2227 if (strbuf_read_file(buf
, path
, st
->st_size
) != st
->st_size
)
2228 return error(_("unable to open or read %s"), path
);
2229 convert_to_git(path
, buf
->buf
, buf
->len
, buf
, 0);
2237 * Update the preimage, and the common lines in postimage,
2238 * from buffer buf of length len. If postlen is 0 the postimage
2239 * is updated in place, otherwise it's updated on a new buffer
2243 static void update_pre_post_images(struct image
*preimage
,
2244 struct image
*postimage
,
2246 size_t len
, size_t postlen
)
2248 int i
, ctx
, reduced
;
2249 char *new, *old
, *fixed
;
2250 struct image fixed_preimage
;
2253 * Update the preimage with whitespace fixes. Note that we
2254 * are not losing preimage->buf -- apply_one_fragment() will
2257 prepare_image(&fixed_preimage
, buf
, len
, 1);
2259 ? fixed_preimage
.nr
== preimage
->nr
2260 : fixed_preimage
.nr
<= preimage
->nr
);
2261 for (i
= 0; i
< fixed_preimage
.nr
; i
++)
2262 fixed_preimage
.line
[i
].flag
= preimage
->line
[i
].flag
;
2263 free(preimage
->line_allocated
);
2264 *preimage
= fixed_preimage
;
2267 * Adjust the common context lines in postimage. This can be
2268 * done in-place when we are shrinking it with whitespace
2269 * fixing, but needs a new buffer when ignoring whitespace or
2270 * expanding leading tabs to spaces.
2272 * We trust the caller to tell us if the update can be done
2273 * in place (postlen==0) or not.
2275 old
= postimage
->buf
;
2277 new = postimage
->buf
= xmalloc(postlen
);
2280 fixed
= preimage
->buf
;
2282 for (i
= reduced
= ctx
= 0; i
< postimage
->nr
; i
++) {
2283 size_t l_len
= postimage
->line
[i
].len
;
2284 if (!(postimage
->line
[i
].flag
& LINE_COMMON
)) {
2285 /* an added line -- no counterparts in preimage */
2286 memmove(new, old
, l_len
);
2292 /* a common context -- skip it in the original postimage */
2295 /* and find the corresponding one in the fixed preimage */
2296 while (ctx
< preimage
->nr
&&
2297 !(preimage
->line
[ctx
].flag
& LINE_COMMON
)) {
2298 fixed
+= preimage
->line
[ctx
].len
;
2303 * preimage is expected to run out, if the caller
2304 * fixed addition of trailing blank lines.
2306 if (preimage
->nr
<= ctx
) {
2311 /* and copy it in, while fixing the line length */
2312 l_len
= preimage
->line
[ctx
].len
;
2313 memcpy(new, fixed
, l_len
);
2316 postimage
->line
[i
].len
= l_len
;
2321 ? postlen
< new - postimage
->buf
2322 : postimage
->len
< new - postimage
->buf
)
2323 die("BUG: caller miscounted postlen: asked %d, orig = %d, used = %d",
2324 (int)postlen
, (int) postimage
->len
, (int)(new - postimage
->buf
));
2326 /* Fix the length of the whole thing */
2327 postimage
->len
= new - postimage
->buf
;
2328 postimage
->nr
-= reduced
;
2331 static int line_by_line_fuzzy_match(struct image
*img
,
2332 struct image
*preimage
,
2333 struct image
*postimage
,
2341 size_t postlen
= postimage
->len
;
2346 struct strbuf fixed
;
2350 for (i
= 0; i
< preimage_limit
; i
++) {
2351 size_t prelen
= preimage
->line
[i
].len
;
2352 size_t imglen
= img
->line
[try_lno
+i
].len
;
2354 if (!fuzzy_matchlines(img
->buf
+ try + imgoff
, imglen
,
2355 preimage
->buf
+ preoff
, prelen
))
2357 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2358 postlen
+= imglen
- prelen
;
2364 * Ok, the preimage matches with whitespace fuzz.
2366 * imgoff now holds the true length of the target that
2367 * matches the preimage before the end of the file.
2369 * Count the number of characters in the preimage that fall
2370 * beyond the end of the file and make sure that all of them
2371 * are whitespace characters. (This can only happen if
2372 * we are removing blank lines at the end of the file.)
2374 buf
= preimage_eof
= preimage
->buf
+ preoff
;
2375 for ( ; i
< preimage
->nr
; i
++)
2376 preoff
+= preimage
->line
[i
].len
;
2377 preimage_end
= preimage
->buf
+ preoff
;
2378 for ( ; buf
< preimage_end
; buf
++)
2383 * Update the preimage and the common postimage context
2384 * lines to use the same whitespace as the target.
2385 * If whitespace is missing in the target (i.e.
2386 * if the preimage extends beyond the end of the file),
2387 * use the whitespace from the preimage.
2389 extra_chars
= preimage_end
- preimage_eof
;
2390 strbuf_init(&fixed
, imgoff
+ extra_chars
);
2391 strbuf_add(&fixed
, img
->buf
+ try, imgoff
);
2392 strbuf_add(&fixed
, preimage_eof
, extra_chars
);
2393 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2394 update_pre_post_images(preimage
, postimage
,
2395 fixed_buf
, fixed_len
, postlen
);
2399 static int match_fragment(struct image
*img
,
2400 struct image
*preimage
,
2401 struct image
*postimage
,
2405 int match_beginning
, int match_end
)
2408 char *fixed_buf
, *buf
, *orig
, *target
;
2409 struct strbuf fixed
;
2410 size_t fixed_len
, postlen
;
2413 if (preimage
->nr
+ try_lno
<= img
->nr
) {
2415 * The hunk falls within the boundaries of img.
2417 preimage_limit
= preimage
->nr
;
2418 if (match_end
&& (preimage
->nr
+ try_lno
!= img
->nr
))
2420 } else if (ws_error_action
== correct_ws_error
&&
2421 (ws_rule
& WS_BLANK_AT_EOF
)) {
2423 * This hunk extends beyond the end of img, and we are
2424 * removing blank lines at the end of the file. This
2425 * many lines from the beginning of the preimage must
2426 * match with img, and the remainder of the preimage
2429 preimage_limit
= img
->nr
- try_lno
;
2432 * The hunk extends beyond the end of the img and
2433 * we are not removing blanks at the end, so we
2434 * should reject the hunk at this position.
2439 if (match_beginning
&& try_lno
)
2442 /* Quick hash check */
2443 for (i
= 0; i
< preimage_limit
; i
++)
2444 if ((img
->line
[try_lno
+ i
].flag
& LINE_PATCHED
) ||
2445 (preimage
->line
[i
].hash
!= img
->line
[try_lno
+ i
].hash
))
2448 if (preimage_limit
== preimage
->nr
) {
2450 * Do we have an exact match? If we were told to match
2451 * at the end, size must be exactly at try+fragsize,
2452 * otherwise try+fragsize must be still within the preimage,
2453 * and either case, the old piece should match the preimage
2457 ? (try + preimage
->len
== img
->len
)
2458 : (try + preimage
->len
<= img
->len
)) &&
2459 !memcmp(img
->buf
+ try, preimage
->buf
, preimage
->len
))
2463 * The preimage extends beyond the end of img, so
2464 * there cannot be an exact match.
2466 * There must be one non-blank context line that match
2467 * a line before the end of img.
2471 buf
= preimage
->buf
;
2473 for (i
= 0; i
< preimage_limit
; i
++)
2474 buf_end
+= preimage
->line
[i
].len
;
2476 for ( ; buf
< buf_end
; buf
++)
2484 * No exact match. If we are ignoring whitespace, run a line-by-line
2485 * fuzzy matching. We collect all the line length information because
2486 * we need it to adjust whitespace if we match.
2488 if (ws_ignore_action
== ignore_ws_change
)
2489 return line_by_line_fuzzy_match(img
, preimage
, postimage
,
2490 try, try_lno
, preimage_limit
);
2492 if (ws_error_action
!= correct_ws_error
)
2496 * The hunk does not apply byte-by-byte, but the hash says
2497 * it might with whitespace fuzz. We weren't asked to
2498 * ignore whitespace, we were asked to correct whitespace
2499 * errors, so let's try matching after whitespace correction.
2501 * While checking the preimage against the target, whitespace
2502 * errors in both fixed, we count how large the corresponding
2503 * postimage needs to be. The postimage prepared by
2504 * apply_one_fragment() has whitespace errors fixed on added
2505 * lines already, but the common lines were propagated as-is,
2506 * which may become longer when their whitespace errors are
2510 /* First count added lines in postimage */
2512 for (i
= 0; i
< postimage
->nr
; i
++) {
2513 if (!(postimage
->line
[i
].flag
& LINE_COMMON
))
2514 postlen
+= postimage
->line
[i
].len
;
2518 * The preimage may extend beyond the end of the file,
2519 * but in this loop we will only handle the part of the
2520 * preimage that falls within the file.
2522 strbuf_init(&fixed
, preimage
->len
+ 1);
2523 orig
= preimage
->buf
;
2524 target
= img
->buf
+ try;
2525 for (i
= 0; i
< preimage_limit
; i
++) {
2526 size_t oldlen
= preimage
->line
[i
].len
;
2527 size_t tgtlen
= img
->line
[try_lno
+ i
].len
;
2528 size_t fixstart
= fixed
.len
;
2529 struct strbuf tgtfix
;
2532 /* Try fixing the line in the preimage */
2533 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2535 /* Try fixing the line in the target */
2536 strbuf_init(&tgtfix
, tgtlen
);
2537 ws_fix_copy(&tgtfix
, target
, tgtlen
, ws_rule
, NULL
);
2540 * If they match, either the preimage was based on
2541 * a version before our tree fixed whitespace breakage,
2542 * or we are lacking a whitespace-fix patch the tree
2543 * the preimage was based on already had (i.e. target
2544 * has whitespace breakage, the preimage doesn't).
2545 * In either case, we are fixing the whitespace breakages
2546 * so we might as well take the fix together with their
2549 match
= (tgtfix
.len
== fixed
.len
- fixstart
&&
2550 !memcmp(tgtfix
.buf
, fixed
.buf
+ fixstart
,
2551 fixed
.len
- fixstart
));
2553 /* Add the length if this is common with the postimage */
2554 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2555 postlen
+= tgtfix
.len
;
2557 strbuf_release(&tgtfix
);
2567 * Now handle the lines in the preimage that falls beyond the
2568 * end of the file (if any). They will only match if they are
2569 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2572 for ( ; i
< preimage
->nr
; i
++) {
2573 size_t fixstart
= fixed
.len
; /* start of the fixed preimage */
2574 size_t oldlen
= preimage
->line
[i
].len
;
2577 /* Try fixing the line in the preimage */
2578 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2580 for (j
= fixstart
; j
< fixed
.len
; j
++)
2581 if (!isspace(fixed
.buf
[j
]))
2588 * Yes, the preimage is based on an older version that still
2589 * has whitespace breakages unfixed, and fixing them makes the
2590 * hunk match. Update the context lines in the postimage.
2592 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2593 if (postlen
< postimage
->len
)
2595 update_pre_post_images(preimage
, postimage
,
2596 fixed_buf
, fixed_len
, postlen
);
2600 strbuf_release(&fixed
);
2604 static int find_pos(struct image
*img
,
2605 struct image
*preimage
,
2606 struct image
*postimage
,
2609 int match_beginning
, int match_end
)
2612 unsigned long backwards
, forwards
, try;
2613 int backwards_lno
, forwards_lno
, try_lno
;
2616 * If match_beginning or match_end is specified, there is no
2617 * point starting from a wrong line that will never match and
2618 * wander around and wait for a match at the specified end.
2620 if (match_beginning
)
2623 line
= img
->nr
- preimage
->nr
;
2626 * Because the comparison is unsigned, the following test
2627 * will also take care of a negative line number that can
2628 * result when match_end and preimage is larger than the target.
2630 if ((size_t) line
> img
->nr
)
2634 for (i
= 0; i
< line
; i
++)
2635 try += img
->line
[i
].len
;
2638 * There's probably some smart way to do this, but I'll leave
2639 * that to the smart and beautiful people. I'm simple and stupid.
2642 backwards_lno
= line
;
2644 forwards_lno
= line
;
2647 for (i
= 0; ; i
++) {
2648 if (match_fragment(img
, preimage
, postimage
,
2649 try, try_lno
, ws_rule
,
2650 match_beginning
, match_end
))
2654 if (backwards_lno
== 0 && forwards_lno
== img
->nr
)
2658 if (backwards_lno
== 0) {
2663 backwards
-= img
->line
[backwards_lno
].len
;
2665 try_lno
= backwards_lno
;
2667 if (forwards_lno
== img
->nr
) {
2671 forwards
+= img
->line
[forwards_lno
].len
;
2674 try_lno
= forwards_lno
;
2681 static void remove_first_line(struct image
*img
)
2683 img
->buf
+= img
->line
[0].len
;
2684 img
->len
-= img
->line
[0].len
;
2689 static void remove_last_line(struct image
*img
)
2691 img
->len
-= img
->line
[--img
->nr
].len
;
2695 * The change from "preimage" and "postimage" has been found to
2696 * apply at applied_pos (counts in line numbers) in "img".
2697 * Update "img" to remove "preimage" and replace it with "postimage".
2699 static void update_image(struct apply_state
*state
,
2702 struct image
*preimage
,
2703 struct image
*postimage
)
2706 * remove the copy of preimage at offset in img
2707 * and replace it with postimage
2710 size_t remove_count
, insert_count
, applied_at
= 0;
2715 * If we are removing blank lines at the end of img,
2716 * the preimage may extend beyond the end.
2717 * If that is the case, we must be careful only to
2718 * remove the part of the preimage that falls within
2719 * the boundaries of img. Initialize preimage_limit
2720 * to the number of lines in the preimage that falls
2721 * within the boundaries.
2723 preimage_limit
= preimage
->nr
;
2724 if (preimage_limit
> img
->nr
- applied_pos
)
2725 preimage_limit
= img
->nr
- applied_pos
;
2727 for (i
= 0; i
< applied_pos
; i
++)
2728 applied_at
+= img
->line
[i
].len
;
2731 for (i
= 0; i
< preimage_limit
; i
++)
2732 remove_count
+= img
->line
[applied_pos
+ i
].len
;
2733 insert_count
= postimage
->len
;
2735 /* Adjust the contents */
2736 result
= xmalloc(st_add3(st_sub(img
->len
, remove_count
), insert_count
, 1));
2737 memcpy(result
, img
->buf
, applied_at
);
2738 memcpy(result
+ applied_at
, postimage
->buf
, postimage
->len
);
2739 memcpy(result
+ applied_at
+ postimage
->len
,
2740 img
->buf
+ (applied_at
+ remove_count
),
2741 img
->len
- (applied_at
+ remove_count
));
2744 img
->len
+= insert_count
- remove_count
;
2745 result
[img
->len
] = '\0';
2747 /* Adjust the line table */
2748 nr
= img
->nr
+ postimage
->nr
- preimage_limit
;
2749 if (preimage_limit
< postimage
->nr
) {
2751 * NOTE: this knows that we never call remove_first_line()
2752 * on anything other than pre/post image.
2754 REALLOC_ARRAY(img
->line
, nr
);
2755 img
->line_allocated
= img
->line
;
2757 if (preimage_limit
!= postimage
->nr
)
2758 memmove(img
->line
+ applied_pos
+ postimage
->nr
,
2759 img
->line
+ applied_pos
+ preimage_limit
,
2760 (img
->nr
- (applied_pos
+ preimage_limit
)) *
2761 sizeof(*img
->line
));
2762 memcpy(img
->line
+ applied_pos
,
2764 postimage
->nr
* sizeof(*img
->line
));
2765 if (!state
->allow_overlap
)
2766 for (i
= 0; i
< postimage
->nr
; i
++)
2767 img
->line
[applied_pos
+ i
].flag
|= LINE_PATCHED
;
2772 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2773 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2774 * replace the part of "img" with "postimage" text.
2776 static int apply_one_fragment(struct apply_state
*state
,
2777 struct image
*img
, struct fragment
*frag
,
2778 int inaccurate_eof
, unsigned ws_rule
,
2781 int match_beginning
, match_end
;
2782 const char *patch
= frag
->patch
;
2783 int size
= frag
->size
;
2784 char *old
, *oldlines
;
2785 struct strbuf newlines
;
2786 int new_blank_lines_at_end
= 0;
2787 int found_new_blank_lines_at_end
= 0;
2788 int hunk_linenr
= frag
->linenr
;
2789 unsigned long leading
, trailing
;
2790 int pos
, applied_pos
;
2791 struct image preimage
;
2792 struct image postimage
;
2794 memset(&preimage
, 0, sizeof(preimage
));
2795 memset(&postimage
, 0, sizeof(postimage
));
2796 oldlines
= xmalloc(size
);
2797 strbuf_init(&newlines
, size
);
2802 int len
= linelen(patch
, size
);
2804 int added_blank_line
= 0;
2805 int is_blank_context
= 0;
2812 * "plen" is how much of the line we should use for
2813 * the actual patch data. Normally we just remove the
2814 * first character on the line, but if the line is
2815 * followed by "\ No newline", then we also remove the
2816 * last one (which is the newline, of course).
2819 if (len
< size
&& patch
[len
] == '\\')
2822 if (state
->apply_in_reverse
) {
2825 else if (first
== '+')
2831 /* Newer GNU diff, empty context line */
2833 /* ... followed by '\No newline'; nothing */
2836 strbuf_addch(&newlines
, '\n');
2837 add_line_info(&preimage
, "\n", 1, LINE_COMMON
);
2838 add_line_info(&postimage
, "\n", 1, LINE_COMMON
);
2839 is_blank_context
= 1;
2842 if (plen
&& (ws_rule
& WS_BLANK_AT_EOF
) &&
2843 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2844 is_blank_context
= 1;
2846 memcpy(old
, patch
+ 1, plen
);
2847 add_line_info(&preimage
, old
, plen
,
2848 (first
== ' ' ? LINE_COMMON
: 0));
2852 /* Fall-through for ' ' */
2854 /* --no-add does not add new lines */
2855 if (first
== '+' && state
->no_add
)
2858 start
= newlines
.len
;
2860 !state
->whitespace_error
||
2861 ws_error_action
!= correct_ws_error
) {
2862 strbuf_add(&newlines
, patch
+ 1, plen
);
2865 ws_fix_copy(&newlines
, patch
+ 1, plen
, ws_rule
, &applied_after_fixing_ws
);
2867 add_line_info(&postimage
, newlines
.buf
+ start
, newlines
.len
- start
,
2868 (first
== '+' ? 0 : LINE_COMMON
));
2870 (ws_rule
& WS_BLANK_AT_EOF
) &&
2871 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2872 added_blank_line
= 1;
2874 case '@': case '\\':
2875 /* Ignore it, we already handled it */
2878 if (state
->apply_verbosely
)
2879 error(_("invalid start of line: '%c'"), first
);
2883 if (added_blank_line
) {
2884 if (!new_blank_lines_at_end
)
2885 found_new_blank_lines_at_end
= hunk_linenr
;
2886 new_blank_lines_at_end
++;
2888 else if (is_blank_context
)
2891 new_blank_lines_at_end
= 0;
2896 if (inaccurate_eof
&&
2897 old
> oldlines
&& old
[-1] == '\n' &&
2898 newlines
.len
> 0 && newlines
.buf
[newlines
.len
- 1] == '\n') {
2900 strbuf_setlen(&newlines
, newlines
.len
- 1);
2903 leading
= frag
->leading
;
2904 trailing
= frag
->trailing
;
2907 * A hunk to change lines at the beginning would begin with
2909 * but we need to be careful. -U0 that inserts before the second
2910 * line also has this pattern.
2912 * And a hunk to add to an empty file would begin with
2915 * In other words, a hunk that is (frag->oldpos <= 1) with or
2916 * without leading context must match at the beginning.
2918 match_beginning
= (!frag
->oldpos
||
2919 (frag
->oldpos
== 1 && !state
->unidiff_zero
));
2922 * A hunk without trailing lines must match at the end.
2923 * However, we simply cannot tell if a hunk must match end
2924 * from the lack of trailing lines if the patch was generated
2925 * with unidiff without any context.
2927 match_end
= !state
->unidiff_zero
&& !trailing
;
2929 pos
= frag
->newpos
? (frag
->newpos
- 1) : 0;
2930 preimage
.buf
= oldlines
;
2931 preimage
.len
= old
- oldlines
;
2932 postimage
.buf
= newlines
.buf
;
2933 postimage
.len
= newlines
.len
;
2934 preimage
.line
= preimage
.line_allocated
;
2935 postimage
.line
= postimage
.line_allocated
;
2939 applied_pos
= find_pos(img
, &preimage
, &postimage
, pos
,
2940 ws_rule
, match_beginning
, match_end
);
2942 if (applied_pos
>= 0)
2945 /* Am I at my context limits? */
2946 if ((leading
<= state
->p_context
) && (trailing
<= state
->p_context
))
2948 if (match_beginning
|| match_end
) {
2949 match_beginning
= match_end
= 0;
2954 * Reduce the number of context lines; reduce both
2955 * leading and trailing if they are equal otherwise
2956 * just reduce the larger context.
2958 if (leading
>= trailing
) {
2959 remove_first_line(&preimage
);
2960 remove_first_line(&postimage
);
2964 if (trailing
> leading
) {
2965 remove_last_line(&preimage
);
2966 remove_last_line(&postimage
);
2971 if (applied_pos
>= 0) {
2972 if (new_blank_lines_at_end
&&
2973 preimage
.nr
+ applied_pos
>= img
->nr
&&
2974 (ws_rule
& WS_BLANK_AT_EOF
) &&
2975 ws_error_action
!= nowarn_ws_error
) {
2976 record_ws_error(state
, WS_BLANK_AT_EOF
, "+", 1,
2977 found_new_blank_lines_at_end
);
2978 if (ws_error_action
== correct_ws_error
) {
2979 while (new_blank_lines_at_end
--)
2980 remove_last_line(&postimage
);
2983 * We would want to prevent write_out_results()
2984 * from taking place in apply_patch() that follows
2985 * the callchain led us here, which is:
2986 * apply_patch->check_patch_list->check_patch->
2987 * apply_data->apply_fragments->apply_one_fragment
2989 if (ws_error_action
== die_on_ws_error
)
2993 if (state
->apply_verbosely
&& applied_pos
!= pos
) {
2994 int offset
= applied_pos
- pos
;
2995 if (state
->apply_in_reverse
)
2996 offset
= 0 - offset
;
2998 Q_("Hunk #%d succeeded at %d (offset %d line).",
2999 "Hunk #%d succeeded at %d (offset %d lines).",
3001 nth_fragment
, applied_pos
+ 1, offset
);
3005 * Warn if it was necessary to reduce the number
3008 if ((leading
!= frag
->leading
) ||
3009 (trailing
!= frag
->trailing
))
3010 fprintf_ln(stderr
, _("Context reduced to (%ld/%ld)"
3011 " to apply fragment at %d"),
3012 leading
, trailing
, applied_pos
+1);
3013 update_image(state
, img
, applied_pos
, &preimage
, &postimage
);
3015 if (state
->apply_verbosely
)
3016 error(_("while searching for:\n%.*s"),
3017 (int)(old
- oldlines
), oldlines
);
3022 strbuf_release(&newlines
);
3023 free(preimage
.line_allocated
);
3024 free(postimage
.line_allocated
);
3026 return (applied_pos
< 0);
3029 static int apply_binary_fragment(struct apply_state
*state
,
3031 struct patch
*patch
)
3033 struct fragment
*fragment
= patch
->fragments
;
3038 return error(_("missing binary patch data for '%s'"),
3043 /* Binary patch is irreversible without the optional second hunk */
3044 if (state
->apply_in_reverse
) {
3045 if (!fragment
->next
)
3046 return error("cannot reverse-apply a binary patch "
3047 "without the reverse hunk to '%s'",
3049 ? patch
->new_name
: patch
->old_name
);
3050 fragment
= fragment
->next
;
3052 switch (fragment
->binary_patch_method
) {
3053 case BINARY_DELTA_DEFLATED
:
3054 dst
= patch_delta(img
->buf
, img
->len
, fragment
->patch
,
3055 fragment
->size
, &len
);
3062 case BINARY_LITERAL_DEFLATED
:
3064 img
->len
= fragment
->size
;
3065 img
->buf
= xmemdupz(fragment
->patch
, img
->len
);
3072 * Replace "img" with the result of applying the binary patch.
3073 * The binary patch data itself in patch->fragment is still kept
3074 * but the preimage prepared by the caller in "img" is freed here
3075 * or in the helper function apply_binary_fragment() this calls.
3077 static int apply_binary(struct apply_state
*state
,
3079 struct patch
*patch
)
3081 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3082 unsigned char sha1
[20];
3085 * For safety, we require patch index line to contain
3086 * full 40-byte textual SHA1 for old and new, at least for now.
3088 if (strlen(patch
->old_sha1_prefix
) != 40 ||
3089 strlen(patch
->new_sha1_prefix
) != 40 ||
3090 get_sha1_hex(patch
->old_sha1_prefix
, sha1
) ||
3091 get_sha1_hex(patch
->new_sha1_prefix
, sha1
))
3092 return error("cannot apply binary patch to '%s' "
3093 "without full index line", name
);
3095 if (patch
->old_name
) {
3097 * See if the old one matches what the patch
3100 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
3101 if (strcmp(sha1_to_hex(sha1
), patch
->old_sha1_prefix
))
3102 return error("the patch applies to '%s' (%s), "
3103 "which does not match the "
3104 "current contents.",
3105 name
, sha1_to_hex(sha1
));
3108 /* Otherwise, the old one must be empty. */
3110 return error("the patch applies to an empty "
3111 "'%s' but it is not empty", name
);
3114 get_sha1_hex(patch
->new_sha1_prefix
, sha1
);
3115 if (is_null_sha1(sha1
)) {
3117 return 0; /* deletion patch */
3120 if (has_sha1_file(sha1
)) {
3121 /* We already have the postimage */
3122 enum object_type type
;
3126 result
= read_sha1_file(sha1
, &type
, &size
);
3128 return error("the necessary postimage %s for "
3129 "'%s' cannot be read",
3130 patch
->new_sha1_prefix
, name
);
3136 * We have verified buf matches the preimage;
3137 * apply the patch data to it, which is stored
3138 * in the patch->fragments->{patch,size}.
3140 if (apply_binary_fragment(state
, img
, patch
))
3141 return error(_("binary patch does not apply to '%s'"),
3144 /* verify that the result matches */
3145 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
3146 if (strcmp(sha1_to_hex(sha1
), patch
->new_sha1_prefix
))
3147 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3148 name
, patch
->new_sha1_prefix
, sha1_to_hex(sha1
));
3154 static int apply_fragments(struct apply_state
*state
, struct image
*img
, struct patch
*patch
)
3156 struct fragment
*frag
= patch
->fragments
;
3157 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3158 unsigned ws_rule
= patch
->ws_rule
;
3159 unsigned inaccurate_eof
= patch
->inaccurate_eof
;
3162 if (patch
->is_binary
)
3163 return apply_binary(state
, img
, patch
);
3167 if (apply_one_fragment(state
, img
, frag
, inaccurate_eof
, ws_rule
, nth
)) {
3168 error(_("patch failed: %s:%ld"), name
, frag
->oldpos
);
3169 if (!state
->apply_with_reject
)
3178 static int read_blob_object(struct strbuf
*buf
, const unsigned char *sha1
, unsigned mode
)
3180 if (S_ISGITLINK(mode
)) {
3181 strbuf_grow(buf
, 100);
3182 strbuf_addf(buf
, "Subproject commit %s\n", sha1_to_hex(sha1
));
3184 enum object_type type
;
3188 result
= read_sha1_file(sha1
, &type
, &sz
);
3191 /* XXX read_sha1_file NUL-terminates */
3192 strbuf_attach(buf
, result
, sz
, sz
+ 1);
3197 static int read_file_or_gitlink(const struct cache_entry
*ce
, struct strbuf
*buf
)
3201 return read_blob_object(buf
, ce
->sha1
, ce
->ce_mode
);
3204 static struct patch
*in_fn_table(const char *name
)
3206 struct string_list_item
*item
;
3211 item
= string_list_lookup(&fn_table
, name
);
3213 return (struct patch
*)item
->util
;
3219 * item->util in the filename table records the status of the path.
3220 * Usually it points at a patch (whose result records the contents
3221 * of it after applying it), but it could be PATH_WAS_DELETED for a
3222 * path that a previously applied patch has already removed, or
3223 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3225 * The latter is needed to deal with a case where two paths A and B
3226 * are swapped by first renaming A to B and then renaming B to A;
3227 * moving A to B should not be prevented due to presence of B as we
3228 * will remove it in a later patch.
3230 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3231 #define PATH_WAS_DELETED ((struct patch *) -1)
3233 static int to_be_deleted(struct patch
*patch
)
3235 return patch
== PATH_TO_BE_DELETED
;
3238 static int was_deleted(struct patch
*patch
)
3240 return patch
== PATH_WAS_DELETED
;
3243 static void add_to_fn_table(struct patch
*patch
)
3245 struct string_list_item
*item
;
3248 * Always add new_name unless patch is a deletion
3249 * This should cover the cases for normal diffs,
3250 * file creations and copies
3252 if (patch
->new_name
!= NULL
) {
3253 item
= string_list_insert(&fn_table
, patch
->new_name
);
3258 * store a failure on rename/deletion cases because
3259 * later chunks shouldn't patch old names
3261 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3262 item
= string_list_insert(&fn_table
, patch
->old_name
);
3263 item
->util
= PATH_WAS_DELETED
;
3267 static void prepare_fn_table(struct patch
*patch
)
3270 * store information about incoming file deletion
3273 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3274 struct string_list_item
*item
;
3275 item
= string_list_insert(&fn_table
, patch
->old_name
);
3276 item
->util
= PATH_TO_BE_DELETED
;
3278 patch
= patch
->next
;
3282 static int checkout_target(struct index_state
*istate
,
3283 struct cache_entry
*ce
, struct stat
*st
)
3285 struct checkout costate
;
3287 memset(&costate
, 0, sizeof(costate
));
3288 costate
.base_dir
= "";
3289 costate
.refresh_cache
= 1;
3290 costate
.istate
= istate
;
3291 if (checkout_entry(ce
, &costate
, NULL
) || lstat(ce
->name
, st
))
3292 return error(_("cannot checkout %s"), ce
->name
);
3296 static struct patch
*previous_patch(struct patch
*patch
, int *gone
)
3298 struct patch
*previous
;
3301 if (patch
->is_copy
|| patch
->is_rename
)
3302 return NULL
; /* "git" patches do not depend on the order */
3304 previous
= in_fn_table(patch
->old_name
);
3308 if (to_be_deleted(previous
))
3309 return NULL
; /* the deletion hasn't happened yet */
3311 if (was_deleted(previous
))
3317 static int verify_index_match(const struct cache_entry
*ce
, struct stat
*st
)
3319 if (S_ISGITLINK(ce
->ce_mode
)) {
3320 if (!S_ISDIR(st
->st_mode
))
3324 return ce_match_stat(ce
, st
, CE_MATCH_IGNORE_VALID
|CE_MATCH_IGNORE_SKIP_WORKTREE
);
3327 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3329 static int load_patch_target(struct apply_state
*state
,
3331 const struct cache_entry
*ce
,
3334 unsigned expected_mode
)
3336 if (state
->cached
|| state
->check_index
) {
3337 if (read_file_or_gitlink(ce
, buf
))
3338 return error(_("read of %s failed"), name
);
3340 if (S_ISGITLINK(expected_mode
)) {
3342 return read_file_or_gitlink(ce
, buf
);
3344 return SUBMODULE_PATCH_WITHOUT_INDEX
;
3345 } else if (has_symlink_leading_path(name
, strlen(name
))) {
3346 return error(_("reading from '%s' beyond a symbolic link"), name
);
3348 if (read_old_data(st
, name
, buf
))
3349 return error(_("read of %s failed"), name
);
3356 * We are about to apply "patch"; populate the "image" with the
3357 * current version we have, from the working tree or from the index,
3358 * depending on the situation e.g. --cached/--index. If we are
3359 * applying a non-git patch that incrementally updates the tree,
3360 * we read from the result of a previous diff.
3362 static int load_preimage(struct apply_state
*state
,
3363 struct image
*image
,
3364 struct patch
*patch
, struct stat
*st
,
3365 const struct cache_entry
*ce
)
3367 struct strbuf buf
= STRBUF_INIT
;
3370 struct patch
*previous
;
3373 previous
= previous_patch(patch
, &status
);
3375 return error(_("path %s has been renamed/deleted"),
3378 /* We have a patched copy in memory; use that. */
3379 strbuf_add(&buf
, previous
->result
, previous
->resultsize
);
3381 status
= load_patch_target(state
, &buf
, ce
, st
,
3382 patch
->old_name
, patch
->old_mode
);
3385 else if (status
== SUBMODULE_PATCH_WITHOUT_INDEX
) {
3387 * There is no way to apply subproject
3388 * patch without looking at the index.
3389 * NEEDSWORK: shouldn't this be flagged
3392 free_fragment_list(patch
->fragments
);
3393 patch
->fragments
= NULL
;
3394 } else if (status
) {
3395 return error(_("read of %s failed"), patch
->old_name
);
3399 img
= strbuf_detach(&buf
, &len
);
3400 prepare_image(image
, img
, len
, !patch
->is_binary
);
3404 static int three_way_merge(struct image
*image
,
3406 const unsigned char *base
,
3407 const unsigned char *ours
,
3408 const unsigned char *theirs
)
3410 mmfile_t base_file
, our_file
, their_file
;
3411 mmbuffer_t result
= { NULL
};
3414 read_mmblob(&base_file
, base
);
3415 read_mmblob(&our_file
, ours
);
3416 read_mmblob(&their_file
, theirs
);
3417 status
= ll_merge(&result
, path
,
3420 &their_file
, "theirs", NULL
);
3421 free(base_file
.ptr
);
3423 free(their_file
.ptr
);
3424 if (status
< 0 || !result
.ptr
) {
3429 image
->buf
= result
.ptr
;
3430 image
->len
= result
.size
;
3436 * When directly falling back to add/add three-way merge, we read from
3437 * the current contents of the new_name. In no cases other than that
3438 * this function will be called.
3440 static int load_current(struct apply_state
*state
,
3441 struct image
*image
,
3442 struct patch
*patch
)
3444 struct strbuf buf
= STRBUF_INIT
;
3449 struct cache_entry
*ce
;
3450 char *name
= patch
->new_name
;
3451 unsigned mode
= patch
->new_mode
;
3454 die("BUG: patch to %s is not a creation", patch
->old_name
);
3456 pos
= cache_name_pos(name
, strlen(name
));
3458 return error(_("%s: does not exist in index"), name
);
3459 ce
= active_cache
[pos
];
3460 if (lstat(name
, &st
)) {
3461 if (errno
!= ENOENT
)
3462 return error(_("%s: %s"), name
, strerror(errno
));
3463 if (checkout_target(&the_index
, ce
, &st
))
3466 if (verify_index_match(ce
, &st
))
3467 return error(_("%s: does not match index"), name
);
3469 status
= load_patch_target(state
, &buf
, ce
, &st
, name
, mode
);
3474 img
= strbuf_detach(&buf
, &len
);
3475 prepare_image(image
, img
, len
, !patch
->is_binary
);
3479 static int try_threeway(struct apply_state
*state
,
3480 struct image
*image
,
3481 struct patch
*patch
,
3483 const struct cache_entry
*ce
)
3485 unsigned char pre_sha1
[20], post_sha1
[20], our_sha1
[20];
3486 struct strbuf buf
= STRBUF_INIT
;
3490 struct image tmp_image
;
3492 /* No point falling back to 3-way merge in these cases */
3493 if (patch
->is_delete
||
3494 S_ISGITLINK(patch
->old_mode
) || S_ISGITLINK(patch
->new_mode
))
3497 /* Preimage the patch was prepared for */
3499 write_sha1_file("", 0, blob_type
, pre_sha1
);
3500 else if (get_sha1(patch
->old_sha1_prefix
, pre_sha1
) ||
3501 read_blob_object(&buf
, pre_sha1
, patch
->old_mode
))
3502 return error("repository lacks the necessary blob to fall back on 3-way merge.");
3504 fprintf(stderr
, "Falling back to three-way merge...\n");
3506 img
= strbuf_detach(&buf
, &len
);
3507 prepare_image(&tmp_image
, img
, len
, 1);
3508 /* Apply the patch to get the post image */
3509 if (apply_fragments(state
, &tmp_image
, patch
) < 0) {
3510 clear_image(&tmp_image
);
3513 /* post_sha1[] is theirs */
3514 write_sha1_file(tmp_image
.buf
, tmp_image
.len
, blob_type
, post_sha1
);
3515 clear_image(&tmp_image
);
3517 /* our_sha1[] is ours */
3518 if (patch
->is_new
) {
3519 if (load_current(state
, &tmp_image
, patch
))
3520 return error("cannot read the current contents of '%s'",
3523 if (load_preimage(state
, &tmp_image
, patch
, st
, ce
))
3524 return error("cannot read the current contents of '%s'",
3527 write_sha1_file(tmp_image
.buf
, tmp_image
.len
, blob_type
, our_sha1
);
3528 clear_image(&tmp_image
);
3530 /* in-core three-way merge between post and our using pre as base */
3531 status
= three_way_merge(image
, patch
->new_name
,
3532 pre_sha1
, our_sha1
, post_sha1
);
3534 fprintf(stderr
, "Failed to fall back on three-way merge...\n");
3539 patch
->conflicted_threeway
= 1;
3541 oidclr(&patch
->threeway_stage
[0]);
3543 hashcpy(patch
->threeway_stage
[0].hash
, pre_sha1
);
3544 hashcpy(patch
->threeway_stage
[1].hash
, our_sha1
);
3545 hashcpy(patch
->threeway_stage
[2].hash
, post_sha1
);
3546 fprintf(stderr
, "Applied patch to '%s' with conflicts.\n", patch
->new_name
);
3548 fprintf(stderr
, "Applied patch to '%s' cleanly.\n", patch
->new_name
);
3553 static int apply_data(struct apply_state
*state
, struct patch
*patch
,
3554 struct stat
*st
, const struct cache_entry
*ce
)
3558 if (load_preimage(state
, &image
, patch
, st
, ce
) < 0)
3561 if (patch
->direct_to_threeway
||
3562 apply_fragments(state
, &image
, patch
) < 0) {
3563 /* Note: with --reject, apply_fragments() returns 0 */
3564 if (!state
->threeway
|| try_threeway(state
, &image
, patch
, st
, ce
) < 0)
3567 patch
->result
= image
.buf
;
3568 patch
->resultsize
= image
.len
;
3569 add_to_fn_table(patch
);
3570 free(image
.line_allocated
);
3572 if (0 < patch
->is_delete
&& patch
->resultsize
)
3573 return error(_("removal patch leaves file contents"));
3579 * If "patch" that we are looking at modifies or deletes what we have,
3580 * we would want it not to lose any local modification we have, either
3581 * in the working tree or in the index.
3583 * This also decides if a non-git patch is a creation patch or a
3584 * modification to an existing empty file. We do not check the state
3585 * of the current tree for a creation patch in this function; the caller
3586 * check_patch() separately makes sure (and errors out otherwise) that
3587 * the path the patch creates does not exist in the current tree.
3589 static int check_preimage(struct apply_state
*state
,
3590 struct patch
*patch
,
3591 struct cache_entry
**ce
,
3594 const char *old_name
= patch
->old_name
;
3595 struct patch
*previous
= NULL
;
3596 int stat_ret
= 0, status
;
3597 unsigned st_mode
= 0;
3602 assert(patch
->is_new
<= 0);
3603 previous
= previous_patch(patch
, &status
);
3606 return error(_("path %s has been renamed/deleted"), old_name
);
3608 st_mode
= previous
->new_mode
;
3609 } else if (!state
->cached
) {
3610 stat_ret
= lstat(old_name
, st
);
3611 if (stat_ret
&& errno
!= ENOENT
)
3612 return error(_("%s: %s"), old_name
, strerror(errno
));
3615 if (state
->check_index
&& !previous
) {
3616 int pos
= cache_name_pos(old_name
, strlen(old_name
));
3618 if (patch
->is_new
< 0)
3620 return error(_("%s: does not exist in index"), old_name
);
3622 *ce
= active_cache
[pos
];
3624 if (checkout_target(&the_index
, *ce
, st
))
3627 if (!state
->cached
&& verify_index_match(*ce
, st
))
3628 return error(_("%s: does not match index"), old_name
);
3630 st_mode
= (*ce
)->ce_mode
;
3631 } else if (stat_ret
< 0) {
3632 if (patch
->is_new
< 0)
3634 return error(_("%s: %s"), old_name
, strerror(errno
));
3637 if (!state
->cached
&& !previous
)
3638 st_mode
= ce_mode_from_stat(*ce
, st
->st_mode
);
3640 if (patch
->is_new
< 0)
3642 if (!patch
->old_mode
)
3643 patch
->old_mode
= st_mode
;
3644 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
3645 return error(_("%s: wrong type"), old_name
);
3646 if (st_mode
!= patch
->old_mode
)
3647 warning(_("%s has type %o, expected %o"),
3648 old_name
, st_mode
, patch
->old_mode
);
3649 if (!patch
->new_mode
&& !patch
->is_delete
)
3650 patch
->new_mode
= st_mode
;
3655 patch
->is_delete
= 0;
3656 free(patch
->old_name
);
3657 patch
->old_name
= NULL
;
3662 #define EXISTS_IN_INDEX 1
3663 #define EXISTS_IN_WORKTREE 2
3665 static int check_to_create(struct apply_state
*state
,
3666 const char *new_name
,
3671 if (state
->check_index
&&
3672 cache_name_pos(new_name
, strlen(new_name
)) >= 0 &&
3674 return EXISTS_IN_INDEX
;
3678 if (!lstat(new_name
, &nst
)) {
3679 if (S_ISDIR(nst
.st_mode
) || ok_if_exists
)
3682 * A leading component of new_name might be a symlink
3683 * that is going to be removed with this patch, but
3684 * still pointing at somewhere that has the path.
3685 * In such a case, path "new_name" does not exist as
3686 * far as git is concerned.
3688 if (has_symlink_leading_path(new_name
, strlen(new_name
)))
3691 return EXISTS_IN_WORKTREE
;
3692 } else if ((errno
!= ENOENT
) && (errno
!= ENOTDIR
)) {
3693 return error("%s: %s", new_name
, strerror(errno
));
3699 * We need to keep track of how symlinks in the preimage are
3700 * manipulated by the patches. A patch to add a/b/c where a/b
3701 * is a symlink should not be allowed to affect the directory
3702 * the symlink points at, but if the same patch removes a/b,
3703 * it is perfectly fine, as the patch removes a/b to make room
3704 * to create a directory a/b so that a/b/c can be created.
3706 static struct string_list symlink_changes
;
3707 #define SYMLINK_GOES_AWAY 01
3708 #define SYMLINK_IN_RESULT 02
3710 static uintptr_t register_symlink_changes(const char *path
, uintptr_t what
)
3712 struct string_list_item
*ent
;
3714 ent
= string_list_lookup(&symlink_changes
, path
);
3716 ent
= string_list_insert(&symlink_changes
, path
);
3717 ent
->util
= (void *)0;
3719 ent
->util
= (void *)(what
| ((uintptr_t)ent
->util
));
3720 return (uintptr_t)ent
->util
;
3723 static uintptr_t check_symlink_changes(const char *path
)
3725 struct string_list_item
*ent
;
3727 ent
= string_list_lookup(&symlink_changes
, path
);
3730 return (uintptr_t)ent
->util
;
3733 static void prepare_symlink_changes(struct patch
*patch
)
3735 for ( ; patch
; patch
= patch
->next
) {
3736 if ((patch
->old_name
&& S_ISLNK(patch
->old_mode
)) &&
3737 (patch
->is_rename
|| patch
->is_delete
))
3738 /* the symlink at patch->old_name is removed */
3739 register_symlink_changes(patch
->old_name
, SYMLINK_GOES_AWAY
);
3741 if (patch
->new_name
&& S_ISLNK(patch
->new_mode
))
3742 /* the symlink at patch->new_name is created or remains */
3743 register_symlink_changes(patch
->new_name
, SYMLINK_IN_RESULT
);
3747 static int path_is_beyond_symlink_1(struct apply_state
*state
, struct strbuf
*name
)
3750 unsigned int change
;
3752 while (--name
->len
&& name
->buf
[name
->len
] != '/')
3753 ; /* scan backwards */
3756 name
->buf
[name
->len
] = '\0';
3757 change
= check_symlink_changes(name
->buf
);
3758 if (change
& SYMLINK_IN_RESULT
)
3760 if (change
& SYMLINK_GOES_AWAY
)
3762 * This cannot be "return 0", because we may
3763 * see a new one created at a higher level.
3767 /* otherwise, check the preimage */
3768 if (state
->check_index
) {
3769 struct cache_entry
*ce
;
3771 ce
= cache_file_exists(name
->buf
, name
->len
, ignore_case
);
3772 if (ce
&& S_ISLNK(ce
->ce_mode
))
3776 if (!lstat(name
->buf
, &st
) && S_ISLNK(st
.st_mode
))
3783 static int path_is_beyond_symlink(struct apply_state
*state
, const char *name_
)
3786 struct strbuf name
= STRBUF_INIT
;
3788 assert(*name_
!= '\0');
3789 strbuf_addstr(&name
, name_
);
3790 ret
= path_is_beyond_symlink_1(state
, &name
);
3791 strbuf_release(&name
);
3796 static void die_on_unsafe_path(struct patch
*patch
)
3798 const char *old_name
= NULL
;
3799 const char *new_name
= NULL
;
3800 if (patch
->is_delete
)
3801 old_name
= patch
->old_name
;
3802 else if (!patch
->is_new
&& !patch
->is_copy
)
3803 old_name
= patch
->old_name
;
3804 if (!patch
->is_delete
)
3805 new_name
= patch
->new_name
;
3807 if (old_name
&& !verify_path(old_name
))
3808 die(_("invalid path '%s'"), old_name
);
3809 if (new_name
&& !verify_path(new_name
))
3810 die(_("invalid path '%s'"), new_name
);
3814 * Check and apply the patch in-core; leave the result in patch->result
3815 * for the caller to write it out to the final destination.
3817 static int check_patch(struct apply_state
*state
, struct patch
*patch
)
3820 const char *old_name
= patch
->old_name
;
3821 const char *new_name
= patch
->new_name
;
3822 const char *name
= old_name
? old_name
: new_name
;
3823 struct cache_entry
*ce
= NULL
;
3824 struct patch
*tpatch
;
3828 patch
->rejected
= 1; /* we will drop this after we succeed */
3830 status
= check_preimage(state
, patch
, &ce
, &st
);
3833 old_name
= patch
->old_name
;
3836 * A type-change diff is always split into a patch to delete
3837 * old, immediately followed by a patch to create new (see
3838 * diff.c::run_diff()); in such a case it is Ok that the entry
3839 * to be deleted by the previous patch is still in the working
3840 * tree and in the index.
3842 * A patch to swap-rename between A and B would first rename A
3843 * to B and then rename B to A. While applying the first one,
3844 * the presence of B should not stop A from getting renamed to
3845 * B; ask to_be_deleted() about the later rename. Removal of
3846 * B and rename from A to B is handled the same way by asking
3849 if ((tpatch
= in_fn_table(new_name
)) &&
3850 (was_deleted(tpatch
) || to_be_deleted(tpatch
)))
3856 ((0 < patch
->is_new
) || patch
->is_rename
|| patch
->is_copy
)) {
3857 int err
= check_to_create(state
, new_name
, ok_if_exists
);
3859 if (err
&& state
->threeway
) {
3860 patch
->direct_to_threeway
= 1;
3861 } else switch (err
) {
3864 case EXISTS_IN_INDEX
:
3865 return error(_("%s: already exists in index"), new_name
);
3867 case EXISTS_IN_WORKTREE
:
3868 return error(_("%s: already exists in working directory"),
3874 if (!patch
->new_mode
) {
3875 if (0 < patch
->is_new
)
3876 patch
->new_mode
= S_IFREG
| 0644;
3878 patch
->new_mode
= patch
->old_mode
;
3882 if (new_name
&& old_name
) {
3883 int same
= !strcmp(old_name
, new_name
);
3884 if (!patch
->new_mode
)
3885 patch
->new_mode
= patch
->old_mode
;
3886 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
) {
3888 return error(_("new mode (%o) of %s does not "
3889 "match old mode (%o)"),
3890 patch
->new_mode
, new_name
,
3893 return error(_("new mode (%o) of %s does not "
3894 "match old mode (%o) of %s"),
3895 patch
->new_mode
, new_name
,
3896 patch
->old_mode
, old_name
);
3900 if (!state
->unsafe_paths
)
3901 die_on_unsafe_path(patch
);
3904 * An attempt to read from or delete a path that is beyond a
3905 * symbolic link will be prevented by load_patch_target() that
3906 * is called at the beginning of apply_data() so we do not
3907 * have to worry about a patch marked with "is_delete" bit
3908 * here. We however need to make sure that the patch result
3909 * is not deposited to a path that is beyond a symbolic link
3912 if (!patch
->is_delete
&& path_is_beyond_symlink(state
, patch
->new_name
))
3913 return error(_("affected file '%s' is beyond a symbolic link"),
3916 if (apply_data(state
, patch
, &st
, ce
) < 0)
3917 return error(_("%s: patch does not apply"), name
);
3918 patch
->rejected
= 0;
3922 static int check_patch_list(struct apply_state
*state
, struct patch
*patch
)
3926 prepare_symlink_changes(patch
);
3927 prepare_fn_table(patch
);
3929 if (state
->apply_verbosely
)
3930 say_patch_name(stderr
,
3931 _("Checking patch %s..."), patch
);
3932 err
|= check_patch(state
, patch
);
3933 patch
= patch
->next
;
3938 /* This function tries to read the sha1 from the current index */
3939 static int get_current_sha1(const char *path
, unsigned char *sha1
)
3943 if (read_cache() < 0)
3945 pos
= cache_name_pos(path
, strlen(path
));
3948 hashcpy(sha1
, active_cache
[pos
]->sha1
);
3952 static int preimage_sha1_in_gitlink_patch(struct patch
*p
, unsigned char sha1
[20])
3955 * A usable gitlink patch has only one fragment (hunk) that looks like:
3957 * -Subproject commit <old sha1>
3958 * +Subproject commit <new sha1>
3961 * -Subproject commit <old sha1>
3962 * for a removal patch.
3964 struct fragment
*hunk
= p
->fragments
;
3965 static const char heading
[] = "-Subproject commit ";
3968 if (/* does the patch have only one hunk? */
3969 hunk
&& !hunk
->next
&&
3970 /* is its preimage one line? */
3971 hunk
->oldpos
== 1 && hunk
->oldlines
== 1 &&
3972 /* does preimage begin with the heading? */
3973 (preimage
= memchr(hunk
->patch
, '\n', hunk
->size
)) != NULL
&&
3974 starts_with(++preimage
, heading
) &&
3975 /* does it record full SHA-1? */
3976 !get_sha1_hex(preimage
+ sizeof(heading
) - 1, sha1
) &&
3977 preimage
[sizeof(heading
) + 40 - 1] == '\n' &&
3978 /* does the abbreviated name on the index line agree with it? */
3979 starts_with(preimage
+ sizeof(heading
) - 1, p
->old_sha1_prefix
))
3980 return 0; /* it all looks fine */
3982 /* we may have full object name on the index line */
3983 return get_sha1_hex(p
->old_sha1_prefix
, sha1
);
3986 /* Build an index that contains the just the files needed for a 3way merge */
3987 static void build_fake_ancestor(struct patch
*list
, const char *filename
)
3989 struct patch
*patch
;
3990 struct index_state result
= { NULL
};
3991 static struct lock_file lock
;
3993 /* Once we start supporting the reverse patch, it may be
3994 * worth showing the new sha1 prefix, but until then...
3996 for (patch
= list
; patch
; patch
= patch
->next
) {
3997 unsigned char sha1
[20];
3998 struct cache_entry
*ce
;
4001 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
4002 if (0 < patch
->is_new
)
4005 if (S_ISGITLINK(patch
->old_mode
)) {
4006 if (!preimage_sha1_in_gitlink_patch(patch
, sha1
))
4007 ; /* ok, the textual part looks sane */
4009 die("sha1 information is lacking or useless for submodule %s",
4011 } else if (!get_sha1_blob(patch
->old_sha1_prefix
, sha1
)) {
4013 } else if (!patch
->lines_added
&& !patch
->lines_deleted
) {
4014 /* mode-only change: update the current */
4015 if (get_current_sha1(patch
->old_name
, sha1
))
4016 die("mode change for %s, which is not "
4017 "in current HEAD", name
);
4019 die("sha1 information is lacking or useless "
4022 ce
= make_cache_entry(patch
->old_mode
, sha1
, name
, 0, 0);
4024 die(_("make_cache_entry failed for path '%s'"), name
);
4025 if (add_index_entry(&result
, ce
, ADD_CACHE_OK_TO_ADD
))
4026 die ("Could not add %s to temporary index", name
);
4029 hold_lock_file_for_update(&lock
, filename
, LOCK_DIE_ON_ERROR
);
4030 if (write_locked_index(&result
, &lock
, COMMIT_LOCK
))
4031 die ("Could not write temporary index to %s", filename
);
4033 discard_index(&result
);
4036 static void stat_patch_list(struct patch
*patch
)
4038 int files
, adds
, dels
;
4040 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
4042 adds
+= patch
->lines_added
;
4043 dels
+= patch
->lines_deleted
;
4047 print_stat_summary(stdout
, files
, adds
, dels
);
4050 static void numstat_patch_list(struct apply_state
*state
,
4051 struct patch
*patch
)
4053 for ( ; patch
; patch
= patch
->next
) {
4055 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
4056 if (patch
->is_binary
)
4059 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
4060 write_name_quoted(name
, stdout
, state
->line_termination
);
4064 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
4067 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
4069 printf(" %s %s\n", newdelete
, name
);
4072 static void show_mode_change(struct patch
*p
, int show_name
)
4074 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
4076 printf(" mode change %06o => %06o %s\n",
4077 p
->old_mode
, p
->new_mode
, p
->new_name
);
4079 printf(" mode change %06o => %06o\n",
4080 p
->old_mode
, p
->new_mode
);
4084 static void show_rename_copy(struct patch
*p
)
4086 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
4087 const char *old
, *new;
4089 /* Find common prefix */
4093 const char *slash_old
, *slash_new
;
4094 slash_old
= strchr(old
, '/');
4095 slash_new
= strchr(new, '/');
4098 slash_old
- old
!= slash_new
- new ||
4099 memcmp(old
, new, slash_new
- new))
4101 old
= slash_old
+ 1;
4102 new = slash_new
+ 1;
4104 /* p->old_name thru old is the common prefix, and old and new
4105 * through the end of names are renames
4107 if (old
!= p
->old_name
)
4108 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
4109 (int)(old
- p
->old_name
), p
->old_name
,
4110 old
, new, p
->score
);
4112 printf(" %s %s => %s (%d%%)\n", renamecopy
,
4113 p
->old_name
, p
->new_name
, p
->score
);
4114 show_mode_change(p
, 0);
4117 static void summary_patch_list(struct patch
*patch
)
4121 for (p
= patch
; p
; p
= p
->next
) {
4123 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
4124 else if (p
->is_delete
)
4125 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
4127 if (p
->is_rename
|| p
->is_copy
)
4128 show_rename_copy(p
);
4131 printf(" rewrite %s (%d%%)\n",
4132 p
->new_name
, p
->score
);
4133 show_mode_change(p
, 0);
4136 show_mode_change(p
, 1);
4142 static void patch_stats(struct patch
*patch
)
4144 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
4146 if (lines
> max_change
)
4148 if (patch
->old_name
) {
4149 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
4151 len
= strlen(patch
->old_name
);
4155 if (patch
->new_name
) {
4156 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
4158 len
= strlen(patch
->new_name
);
4164 static void remove_file(struct apply_state
*state
, struct patch
*patch
, int rmdir_empty
)
4166 if (state
->update_index
) {
4167 if (remove_file_from_cache(patch
->old_name
) < 0)
4168 die(_("unable to remove %s from index"), patch
->old_name
);
4170 if (!state
->cached
) {
4171 if (!remove_or_warn(patch
->old_mode
, patch
->old_name
) && rmdir_empty
) {
4172 remove_path(patch
->old_name
);
4177 static void add_index_file(struct apply_state
*state
,
4184 struct cache_entry
*ce
;
4185 int namelen
= strlen(path
);
4186 unsigned ce_size
= cache_entry_size(namelen
);
4188 if (!state
->update_index
)
4191 ce
= xcalloc(1, ce_size
);
4192 memcpy(ce
->name
, path
, namelen
);
4193 ce
->ce_mode
= create_ce_mode(mode
);
4194 ce
->ce_flags
= create_ce_flags(0);
4195 ce
->ce_namelen
= namelen
;
4196 if (S_ISGITLINK(mode
)) {
4199 if (!skip_prefix(buf
, "Subproject commit ", &s
) ||
4200 get_sha1_hex(s
, ce
->sha1
))
4201 die(_("corrupt patch for submodule %s"), path
);
4203 if (!state
->cached
) {
4204 if (lstat(path
, &st
) < 0)
4205 die_errno(_("unable to stat newly created file '%s'"),
4207 fill_stat_cache_info(ce
, &st
);
4209 if (write_sha1_file(buf
, size
, blob_type
, ce
->sha1
) < 0)
4210 die(_("unable to create backing store for newly created file %s"), path
);
4212 if (add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
) < 0)
4213 die(_("unable to add cache entry for %s"), path
);
4216 static int try_create_file(const char *path
, unsigned int mode
, const char *buf
, unsigned long size
)
4219 struct strbuf nbuf
= STRBUF_INIT
;
4221 if (S_ISGITLINK(mode
)) {
4223 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
))
4225 return mkdir(path
, 0777);
4228 if (has_symlinks
&& S_ISLNK(mode
))
4229 /* Although buf:size is counted string, it also is NUL
4232 return symlink(buf
, path
);
4234 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
4238 if (convert_to_working_tree(path
, buf
, size
, &nbuf
)) {
4242 write_or_die(fd
, buf
, size
);
4243 strbuf_release(&nbuf
);
4246 die_errno(_("closing file '%s'"), path
);
4251 * We optimistically assume that the directories exist,
4252 * which is true 99% of the time anyway. If they don't,
4253 * we create them and try again.
4255 static void create_one_file(struct apply_state
*state
,
4263 if (!try_create_file(path
, mode
, buf
, size
))
4266 if (errno
== ENOENT
) {
4267 if (safe_create_leading_directories(path
))
4269 if (!try_create_file(path
, mode
, buf
, size
))
4273 if (errno
== EEXIST
|| errno
== EACCES
) {
4274 /* We may be trying to create a file where a directory
4278 if (!lstat(path
, &st
) && (!S_ISDIR(st
.st_mode
) || !rmdir(path
)))
4282 if (errno
== EEXIST
) {
4283 unsigned int nr
= getpid();
4286 char newpath
[PATH_MAX
];
4287 mksnpath(newpath
, sizeof(newpath
), "%s~%u", path
, nr
);
4288 if (!try_create_file(newpath
, mode
, buf
, size
)) {
4289 if (!rename(newpath
, path
))
4291 unlink_or_warn(newpath
);
4294 if (errno
!= EEXIST
)
4299 die_errno(_("unable to write file '%s' mode %o"), path
, mode
);
4302 static void add_conflicted_stages_file(struct apply_state
*state
,
4303 struct patch
*patch
)
4306 unsigned ce_size
, mode
;
4307 struct cache_entry
*ce
;
4309 if (!state
->update_index
)
4311 namelen
= strlen(patch
->new_name
);
4312 ce_size
= cache_entry_size(namelen
);
4313 mode
= patch
->new_mode
? patch
->new_mode
: (S_IFREG
| 0644);
4315 remove_file_from_cache(patch
->new_name
);
4316 for (stage
= 1; stage
< 4; stage
++) {
4317 if (is_null_oid(&patch
->threeway_stage
[stage
- 1]))
4319 ce
= xcalloc(1, ce_size
);
4320 memcpy(ce
->name
, patch
->new_name
, namelen
);
4321 ce
->ce_mode
= create_ce_mode(mode
);
4322 ce
->ce_flags
= create_ce_flags(stage
);
4323 ce
->ce_namelen
= namelen
;
4324 hashcpy(ce
->sha1
, patch
->threeway_stage
[stage
- 1].hash
);
4325 if (add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
) < 0)
4326 die(_("unable to add cache entry for %s"), patch
->new_name
);
4330 static void create_file(struct apply_state
*state
, struct patch
*patch
)
4332 char *path
= patch
->new_name
;
4333 unsigned mode
= patch
->new_mode
;
4334 unsigned long size
= patch
->resultsize
;
4335 char *buf
= patch
->result
;
4338 mode
= S_IFREG
| 0644;
4339 create_one_file(state
, path
, mode
, buf
, size
);
4341 if (patch
->conflicted_threeway
)
4342 add_conflicted_stages_file(state
, patch
);
4344 add_index_file(state
, path
, mode
, buf
, size
);
4347 /* phase zero is to remove, phase one is to create */
4348 static void write_out_one_result(struct apply_state
*state
,
4349 struct patch
*patch
,
4352 if (patch
->is_delete
> 0) {
4354 remove_file(state
, patch
, 1);
4357 if (patch
->is_new
> 0 || patch
->is_copy
) {
4359 create_file(state
, patch
);
4363 * Rename or modification boils down to the same
4364 * thing: remove the old, write the new
4367 remove_file(state
, patch
, patch
->is_rename
);
4369 create_file(state
, patch
);
4372 static int write_out_one_reject(struct apply_state
*state
, struct patch
*patch
)
4375 char namebuf
[PATH_MAX
];
4376 struct fragment
*frag
;
4378 struct strbuf sb
= STRBUF_INIT
;
4380 for (cnt
= 0, frag
= patch
->fragments
; frag
; frag
= frag
->next
) {
4381 if (!frag
->rejected
)
4387 if (state
->apply_verbosely
)
4388 say_patch_name(stderr
,
4389 _("Applied patch %s cleanly."), patch
);
4393 /* This should not happen, because a removal patch that leaves
4394 * contents are marked "rejected" at the patch level.
4396 if (!patch
->new_name
)
4397 die(_("internal error"));
4399 /* Say this even without --verbose */
4400 strbuf_addf(&sb
, Q_("Applying patch %%s with %d reject...",
4401 "Applying patch %%s with %d rejects...",
4404 say_patch_name(stderr
, sb
.buf
, patch
);
4405 strbuf_release(&sb
);
4407 cnt
= strlen(patch
->new_name
);
4408 if (ARRAY_SIZE(namebuf
) <= cnt
+ 5) {
4409 cnt
= ARRAY_SIZE(namebuf
) - 5;
4410 warning(_("truncating .rej filename to %.*s.rej"),
4411 cnt
- 1, patch
->new_name
);
4413 memcpy(namebuf
, patch
->new_name
, cnt
);
4414 memcpy(namebuf
+ cnt
, ".rej", 5);
4416 rej
= fopen(namebuf
, "w");
4418 return error(_("cannot open %s: %s"), namebuf
, strerror(errno
));
4420 /* Normal git tools never deal with .rej, so do not pretend
4421 * this is a git patch by saying --git or giving extended
4422 * headers. While at it, maybe please "kompare" that wants
4423 * the trailing TAB and some garbage at the end of line ;-).
4425 fprintf(rej
, "diff a/%s b/%s\t(rejected hunks)\n",
4426 patch
->new_name
, patch
->new_name
);
4427 for (cnt
= 1, frag
= patch
->fragments
;
4429 cnt
++, frag
= frag
->next
) {
4430 if (!frag
->rejected
) {
4431 fprintf_ln(stderr
, _("Hunk #%d applied cleanly."), cnt
);
4434 fprintf_ln(stderr
, _("Rejected hunk #%d."), cnt
);
4435 fprintf(rej
, "%.*s", frag
->size
, frag
->patch
);
4436 if (frag
->patch
[frag
->size
-1] != '\n')
4443 static int write_out_results(struct apply_state
*state
, struct patch
*list
)
4448 struct string_list cpath
= STRING_LIST_INIT_DUP
;
4450 for (phase
= 0; phase
< 2; phase
++) {
4456 write_out_one_result(state
, l
, phase
);
4458 if (write_out_one_reject(state
, l
))
4460 if (l
->conflicted_threeway
) {
4461 string_list_append(&cpath
, l
->new_name
);
4471 struct string_list_item
*item
;
4473 string_list_sort(&cpath
);
4474 for_each_string_list_item(item
, &cpath
)
4475 fprintf(stderr
, "U %s\n", item
->string
);
4476 string_list_clear(&cpath
, 0);
4484 static struct lock_file lock_file
;
4486 #define INACCURATE_EOF (1<<0)
4487 #define RECOUNT (1<<1)
4489 static int apply_patch(struct apply_state
*state
,
4491 const char *filename
,
4495 struct strbuf buf
= STRBUF_INIT
; /* owns the patch text */
4496 struct patch
*list
= NULL
, **listp
= &list
;
4497 int skipped_patch
= 0;
4499 state
->patch_input_file
= filename
;
4500 read_patch_file(&buf
, fd
);
4502 while (offset
< buf
.len
) {
4503 struct patch
*patch
;
4506 patch
= xcalloc(1, sizeof(*patch
));
4507 patch
->inaccurate_eof
= !!(options
& INACCURATE_EOF
);
4508 patch
->recount
= !!(options
& RECOUNT
);
4509 nr
= parse_chunk(state
, buf
.buf
+ offset
, buf
.len
- offset
, patch
);
4514 if (state
->apply_in_reverse
)
4515 reverse_patches(patch
);
4516 if (use_patch(state
, patch
)) {
4519 listp
= &patch
->next
;
4522 if (state
->apply_verbosely
)
4523 say_patch_name(stderr
, _("Skipped patch '%s'."), patch
);
4530 if (!list
&& !skipped_patch
)
4531 die(_("unrecognized input"));
4533 if (state
->whitespace_error
&& (ws_error_action
== die_on_ws_error
))
4536 state
->update_index
= state
->check_index
&& state
->apply
;
4537 if (state
->update_index
&& newfd
< 0)
4538 newfd
= hold_locked_index(&lock_file
, 1);
4540 if (state
->check_index
) {
4541 if (read_cache() < 0)
4542 die(_("unable to read index file"));
4545 if ((state
->check
|| state
->apply
) &&
4546 check_patch_list(state
, list
) < 0 &&
4547 !state
->apply_with_reject
)
4550 if (state
->apply
&& write_out_results(state
, list
)) {
4551 if (state
->apply_with_reject
)
4553 /* with --3way, we still need to write the index out */
4557 if (state
->fake_ancestor
)
4558 build_fake_ancestor(list
, state
->fake_ancestor
);
4560 if (state
->diffstat
)
4561 stat_patch_list(list
);
4564 numstat_patch_list(state
, list
);
4567 summary_patch_list(list
);
4569 free_patch_list(list
);
4570 strbuf_release(&buf
);
4571 string_list_clear(&fn_table
, 0);
4575 static void git_apply_config(void)
4577 git_config_get_string_const("apply.whitespace", &apply_default_whitespace
);
4578 git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace
);
4579 git_config(git_default_config
, NULL
);
4582 static int option_parse_exclude(const struct option
*opt
,
4583 const char *arg
, int unset
)
4585 struct apply_state
*state
= opt
->value
;
4586 add_name_limit(state
, arg
, 1);
4590 static int option_parse_include(const struct option
*opt
,
4591 const char *arg
, int unset
)
4593 struct apply_state
*state
= opt
->value
;
4594 add_name_limit(state
, arg
, 0);
4595 state
->has_include
= 1;
4599 static int option_parse_p(const struct option
*opt
,
4603 struct apply_state
*state
= opt
->value
;
4604 state
->p_value
= atoi(arg
);
4605 state
->p_value_known
= 1;
4609 static int option_parse_space_change(const struct option
*opt
,
4610 const char *arg
, int unset
)
4613 ws_ignore_action
= ignore_ws_none
;
4615 ws_ignore_action
= ignore_ws_change
;
4619 static int option_parse_whitespace(const struct option
*opt
,
4620 const char *arg
, int unset
)
4622 const char **whitespace_option
= opt
->value
;
4624 *whitespace_option
= arg
;
4625 parse_whitespace_option(arg
);
4629 static int option_parse_directory(const struct option
*opt
,
4630 const char *arg
, int unset
)
4632 struct apply_state
*state
= opt
->value
;
4633 strbuf_reset(&state
->root
);
4634 strbuf_addstr(&state
->root
, arg
);
4635 strbuf_complete(&state
->root
, '/');
4639 static void init_apply_state(struct apply_state
*state
, const char *prefix
)
4641 memset(state
, 0, sizeof(*state
));
4642 state
->prefix
= prefix
;
4643 state
->prefix_length
= state
->prefix
? strlen(state
->prefix
) : 0;
4645 state
->line_termination
= '\n';
4647 state
->p_context
= UINT_MAX
;
4648 strbuf_init(&state
->root
, 0);
4651 if (apply_default_whitespace
)
4652 parse_whitespace_option(apply_default_whitespace
);
4653 if (apply_default_ignorewhitespace
)
4654 parse_ignorewhitespace_option(apply_default_ignorewhitespace
);
4657 static void clear_apply_state(struct apply_state
*state
)
4659 string_list_clear(&state
->limit_by_name
, 0);
4660 strbuf_release(&state
->root
);
4663 int cmd_apply(int argc
, const char **argv
, const char *prefix
)
4667 int is_not_gitdir
= !startup_info
->have_repository
;
4668 int force_apply
= 0;
4671 struct apply_state state
;
4673 const char *whitespace_option
= NULL
;
4675 struct option builtin_apply_options
[] = {
4676 { OPTION_CALLBACK
, 0, "exclude", &state
, N_("path"),
4677 N_("don't apply changes matching the given path"),
4678 0, option_parse_exclude
},
4679 { OPTION_CALLBACK
, 0, "include", &state
, N_("path"),
4680 N_("apply changes matching the given path"),
4681 0, option_parse_include
},
4682 { OPTION_CALLBACK
, 'p', NULL
, &state
, N_("num"),
4683 N_("remove <num> leading slashes from traditional diff paths"),
4684 0, option_parse_p
},
4685 OPT_BOOL(0, "no-add", &state
.no_add
,
4686 N_("ignore additions made by the patch")),
4687 OPT_BOOL(0, "stat", &state
.diffstat
,
4688 N_("instead of applying the patch, output diffstat for the input")),
4689 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
4690 OPT_NOOP_NOARG(0, "binary"),
4691 OPT_BOOL(0, "numstat", &state
.numstat
,
4692 N_("show number of added and deleted lines in decimal notation")),
4693 OPT_BOOL(0, "summary", &state
.summary
,
4694 N_("instead of applying the patch, output a summary for the input")),
4695 OPT_BOOL(0, "check", &state
.check
,
4696 N_("instead of applying the patch, see if the patch is applicable")),
4697 OPT_BOOL(0, "index", &state
.check_index
,
4698 N_("make sure the patch is applicable to the current index")),
4699 OPT_BOOL(0, "cached", &state
.cached
,
4700 N_("apply a patch without touching the working tree")),
4701 OPT_BOOL(0, "unsafe-paths", &state
.unsafe_paths
,
4702 N_("accept a patch that touches outside the working area")),
4703 OPT_BOOL(0, "apply", &force_apply
,
4704 N_("also apply the patch (use with --stat/--summary/--check)")),
4705 OPT_BOOL('3', "3way", &state
.threeway
,
4706 N_( "attempt three-way merge if a patch does not apply")),
4707 OPT_FILENAME(0, "build-fake-ancestor", &state
.fake_ancestor
,
4708 N_("build a temporary index based on embedded index information")),
4709 /* Think twice before adding "--nul" synonym to this */
4710 OPT_SET_INT('z', NULL
, &state
.line_termination
,
4711 N_("paths are separated with NUL character"), '\0'),
4712 OPT_INTEGER('C', NULL
, &state
.p_context
,
4713 N_("ensure at least <n> lines of context match")),
4714 { OPTION_CALLBACK
, 0, "whitespace", &whitespace_option
, N_("action"),
4715 N_("detect new or modified lines that have whitespace errors"),
4716 0, option_parse_whitespace
},
4717 { OPTION_CALLBACK
, 0, "ignore-space-change", NULL
, NULL
,
4718 N_("ignore changes in whitespace when finding context"),
4719 PARSE_OPT_NOARG
, option_parse_space_change
},
4720 { OPTION_CALLBACK
, 0, "ignore-whitespace", NULL
, NULL
,
4721 N_("ignore changes in whitespace when finding context"),
4722 PARSE_OPT_NOARG
, option_parse_space_change
},
4723 OPT_BOOL('R', "reverse", &state
.apply_in_reverse
,
4724 N_("apply the patch in reverse")),
4725 OPT_BOOL(0, "unidiff-zero", &state
.unidiff_zero
,
4726 N_("don't expect at least one line of context")),
4727 OPT_BOOL(0, "reject", &state
.apply_with_reject
,
4728 N_("leave the rejected hunks in corresponding *.rej files")),
4729 OPT_BOOL(0, "allow-overlap", &state
.allow_overlap
,
4730 N_("allow overlapping hunks")),
4731 OPT__VERBOSE(&state
.apply_verbosely
, N_("be verbose")),
4732 OPT_BIT(0, "inaccurate-eof", &options
,
4733 N_("tolerate incorrectly detected missing new-line at the end of file"),
4735 OPT_BIT(0, "recount", &options
,
4736 N_("do not trust the line counts in the hunk headers"),
4738 { OPTION_CALLBACK
, 0, "directory", &state
, N_("root"),
4739 N_("prepend <root> to all filenames"),
4740 0, option_parse_directory
},
4744 init_apply_state(&state
, prefix
);
4746 argc
= parse_options(argc
, argv
, state
.prefix
, builtin_apply_options
,
4749 if (state
.apply_with_reject
&& state
.threeway
)
4750 die("--reject and --3way cannot be used together.");
4751 if (state
.cached
&& state
.threeway
)
4752 die("--cached and --3way cannot be used together.");
4753 if (state
.threeway
) {
4755 die(_("--3way outside a repository"));
4756 state
.check_index
= 1;
4758 if (state
.apply_with_reject
)
4759 state
.apply
= state
.apply_verbosely
= 1;
4760 if (!force_apply
&& (state
.diffstat
|| state
.numstat
|| state
.summary
|| state
.check
|| state
.fake_ancestor
))
4762 if (state
.check_index
&& is_not_gitdir
)
4763 die(_("--index outside a repository"));
4766 die(_("--cached outside a repository"));
4767 state
.check_index
= 1;
4769 if (state
.check_index
)
4770 state
.unsafe_paths
= 0;
4772 for (i
= 0; i
< argc
; i
++) {
4773 const char *arg
= argv
[i
];
4776 if (!strcmp(arg
, "-")) {
4777 errs
|= apply_patch(&state
, 0, "<stdin>", options
);
4780 } else if (0 < state
.prefix_length
)
4781 arg
= prefix_filename(state
.prefix
,
4782 state
.prefix_length
,
4785 fd
= open(arg
, O_RDONLY
);
4787 die_errno(_("can't open patch '%s'"), arg
);
4789 set_default_whitespace_mode(&state
, whitespace_option
);
4790 errs
|= apply_patch(&state
, fd
, arg
, options
);
4793 set_default_whitespace_mode(&state
, whitespace_option
);
4795 errs
|= apply_patch(&state
, 0, "<stdin>", options
);
4796 if (state
.whitespace_error
) {
4797 if (squelch_whitespace_errors
&&
4798 squelch_whitespace_errors
< state
.whitespace_error
) {
4800 state
.whitespace_error
- squelch_whitespace_errors
;
4801 warning(Q_("squelched %d whitespace error",
4802 "squelched %d whitespace errors",
4806 if (ws_error_action
== die_on_ws_error
)
4807 die(Q_("%d line adds whitespace errors.",
4808 "%d lines add whitespace errors.",
4809 state
.whitespace_error
),
4810 state
.whitespace_error
);
4811 if (applied_after_fixing_ws
&& state
.apply
)
4812 warning("%d line%s applied after"
4813 " fixing whitespace errors.",
4814 applied_after_fixing_ws
,
4815 applied_after_fixing_ws
== 1 ? "" : "s");
4816 else if (state
.whitespace_error
)
4817 warning(Q_("%d line adds whitespace errors.",
4818 "%d lines add whitespace errors.",
4819 state
.whitespace_error
),
4820 state
.whitespace_error
);
4823 if (state
.update_index
) {
4824 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
4825 die(_("Unable to write new index file"));
4828 clear_apply_state(&state
);