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
;
54 unsigned int p_context
;
57 static int newfd
= -1;
59 static int state_p_value
= 1;
60 static int p_value_known
;
62 static const char * const apply_usage
[] = {
63 N_("git apply [<options>] [<patch>...]"),
67 static enum ws_error_action
{
72 } ws_error_action
= warn_on_ws_error
;
73 static int whitespace_error
;
74 static int squelch_whitespace_errors
= 5;
75 static int applied_after_fixing_ws
;
77 static enum ws_ignore
{
80 } ws_ignore_action
= ignore_ws_none
;
83 static struct strbuf root
= STRBUF_INIT
;
85 static void parse_whitespace_option(const char *option
)
88 ws_error_action
= warn_on_ws_error
;
91 if (!strcmp(option
, "warn")) {
92 ws_error_action
= warn_on_ws_error
;
95 if (!strcmp(option
, "nowarn")) {
96 ws_error_action
= nowarn_ws_error
;
99 if (!strcmp(option
, "error")) {
100 ws_error_action
= die_on_ws_error
;
103 if (!strcmp(option
, "error-all")) {
104 ws_error_action
= die_on_ws_error
;
105 squelch_whitespace_errors
= 0;
108 if (!strcmp(option
, "strip") || !strcmp(option
, "fix")) {
109 ws_error_action
= correct_ws_error
;
112 die(_("unrecognized whitespace option '%s'"), option
);
115 static void parse_ignorewhitespace_option(const char *option
)
117 if (!option
|| !strcmp(option
, "no") ||
118 !strcmp(option
, "false") || !strcmp(option
, "never") ||
119 !strcmp(option
, "none")) {
120 ws_ignore_action
= ignore_ws_none
;
123 if (!strcmp(option
, "change")) {
124 ws_ignore_action
= ignore_ws_change
;
127 die(_("unrecognized whitespace ignore option '%s'"), option
);
130 static void set_default_whitespace_mode(struct apply_state
*state
,
131 const char *whitespace_option
)
133 if (!whitespace_option
&& !apply_default_whitespace
)
134 ws_error_action
= (state
->apply
? warn_on_ws_error
: nowarn_ws_error
);
138 * For "diff-stat" like behaviour, we keep track of the biggest change
139 * we've seen, and the longest filename. That allows us to do simple
142 static int max_change
, max_len
;
145 * Various "current state", notably line numbers and what
146 * file (and how) we're patching right now.. The "is_xxxx"
147 * things are flags, where -1 means "don't know yet".
149 static int state_linenr
= 1;
152 * This represents one "hunk" from a patch, starting with
153 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
154 * patch text is pointed at by patch, and its byte length
155 * is stored in size. leading and trailing are the number
159 unsigned long leading
, trailing
;
160 unsigned long oldpos
, oldlines
;
161 unsigned long newpos
, newlines
;
163 * 'patch' is usually borrowed from buf in apply_patch(),
164 * but some codepaths store an allocated buffer.
167 unsigned free_patch
:1,
171 struct fragment
*next
;
175 * When dealing with a binary patch, we reuse "leading" field
176 * to store the type of the binary hunk, either deflated "delta"
177 * or deflated "literal".
179 #define binary_patch_method leading
180 #define BINARY_DELTA_DEFLATED 1
181 #define BINARY_LITERAL_DEFLATED 2
184 * This represents a "patch" to a file, both metainfo changes
185 * such as creation/deletion, filemode and content changes represented
186 * as a series of fragments.
189 char *new_name
, *old_name
, *def_name
;
190 unsigned int old_mode
, new_mode
;
191 int is_new
, is_delete
; /* -1 = unknown, 0 = false, 1 = true */
194 int lines_added
, lines_deleted
;
196 unsigned int is_toplevel_relative
:1;
197 unsigned int inaccurate_eof
:1;
198 unsigned int is_binary
:1;
199 unsigned int is_copy
:1;
200 unsigned int is_rename
:1;
201 unsigned int recount
:1;
202 unsigned int conflicted_threeway
:1;
203 unsigned int direct_to_threeway
:1;
204 struct fragment
*fragments
;
207 char old_sha1_prefix
[41];
208 char new_sha1_prefix
[41];
211 /* three-way fallback result */
212 struct object_id threeway_stage
[3];
215 static void free_fragment_list(struct fragment
*list
)
218 struct fragment
*next
= list
->next
;
219 if (list
->free_patch
)
220 free((char *)list
->patch
);
226 static void free_patch(struct patch
*patch
)
228 free_fragment_list(patch
->fragments
);
229 free(patch
->def_name
);
230 free(patch
->old_name
);
231 free(patch
->new_name
);
236 static void free_patch_list(struct patch
*list
)
239 struct patch
*next
= list
->next
;
246 * A line in a file, len-bytes long (includes the terminating LF,
247 * except for an incomplete line at the end if the file ends with
248 * one), and its contents hashes to 'hash'.
254 #define LINE_COMMON 1
255 #define LINE_PATCHED 2
259 * This represents a "file", which is an array of "lines".
266 struct line
*line_allocated
;
271 * Records filenames that have been touched, in order to handle
272 * the case where more than one patches touch the same file.
275 static struct string_list fn_table
;
277 static uint32_t hash_line(const char *cp
, size_t len
)
281 for (i
= 0, h
= 0; i
< len
; i
++) {
282 if (!isspace(cp
[i
])) {
283 h
= h
* 3 + (cp
[i
] & 0xff);
290 * Compare lines s1 of length n1 and s2 of length n2, ignoring
291 * whitespace difference. Returns 1 if they match, 0 otherwise
293 static int fuzzy_matchlines(const char *s1
, size_t n1
,
294 const char *s2
, size_t n2
)
296 const char *last1
= s1
+ n1
- 1;
297 const char *last2
= s2
+ n2
- 1;
300 /* ignore line endings */
301 while ((*last1
== '\r') || (*last1
== '\n'))
303 while ((*last2
== '\r') || (*last2
== '\n'))
306 /* skip leading whitespaces, if both begin with whitespace */
307 if (s1
<= last1
&& s2
<= last2
&& isspace(*s1
) && isspace(*s2
)) {
308 while (isspace(*s1
) && (s1
<= last1
))
310 while (isspace(*s2
) && (s2
<= last2
))
313 /* early return if both lines are empty */
314 if ((s1
> last1
) && (s2
> last2
))
317 result
= *s1
++ - *s2
++;
319 * Skip whitespace inside. We check for whitespace on
320 * both buffers because we don't want "a b" to match
323 if (isspace(*s1
) && isspace(*s2
)) {
324 while (isspace(*s1
) && s1
<= last1
)
326 while (isspace(*s2
) && s2
<= last2
)
330 * If we reached the end on one side only,
334 ((s2
> last2
) && (s1
<= last1
)) ||
335 ((s1
> last1
) && (s2
<= last2
)))
337 if ((s1
> last1
) && (s2
> last2
))
344 static void add_line_info(struct image
*img
, const char *bol
, size_t len
, unsigned flag
)
346 ALLOC_GROW(img
->line_allocated
, img
->nr
+ 1, img
->alloc
);
347 img
->line_allocated
[img
->nr
].len
= len
;
348 img
->line_allocated
[img
->nr
].hash
= hash_line(bol
, len
);
349 img
->line_allocated
[img
->nr
].flag
= flag
;
354 * "buf" has the file contents to be patched (read from various sources).
355 * attach it to "image" and add line-based index to it.
356 * "image" now owns the "buf".
358 static void prepare_image(struct image
*image
, char *buf
, size_t len
,
359 int prepare_linetable
)
363 memset(image
, 0, sizeof(*image
));
367 if (!prepare_linetable
)
370 ep
= image
->buf
+ image
->len
;
374 for (next
= cp
; next
< ep
&& *next
!= '\n'; next
++)
378 add_line_info(image
, cp
, next
- cp
, 0);
381 image
->line
= image
->line_allocated
;
384 static void clear_image(struct image
*image
)
387 free(image
->line_allocated
);
388 memset(image
, 0, sizeof(*image
));
391 /* fmt must contain _one_ %s and no other substitution */
392 static void say_patch_name(FILE *output
, const char *fmt
, struct patch
*patch
)
394 struct strbuf sb
= STRBUF_INIT
;
396 if (patch
->old_name
&& patch
->new_name
&&
397 strcmp(patch
->old_name
, patch
->new_name
)) {
398 quote_c_style(patch
->old_name
, &sb
, NULL
, 0);
399 strbuf_addstr(&sb
, " => ");
400 quote_c_style(patch
->new_name
, &sb
, NULL
, 0);
402 const char *n
= patch
->new_name
;
405 quote_c_style(n
, &sb
, NULL
, 0);
407 fprintf(output
, fmt
, sb
.buf
);
414 static void read_patch_file(struct strbuf
*sb
, int fd
)
416 if (strbuf_read(sb
, fd
, 0) < 0)
417 die_errno("git apply: failed to read");
420 * Make sure that we have some slop in the buffer
421 * so that we can do speculative "memcmp" etc, and
422 * see to it that it is NUL-filled.
424 strbuf_grow(sb
, SLOP
);
425 memset(sb
->buf
+ sb
->len
, 0, SLOP
);
428 static unsigned long linelen(const char *buffer
, unsigned long size
)
430 unsigned long len
= 0;
433 if (*buffer
++ == '\n')
439 static int is_dev_null(const char *str
)
441 return skip_prefix(str
, "/dev/null", &str
) && isspace(*str
);
447 static int name_terminate(const char *name
, int namelen
, int c
, int terminate
)
449 if (c
== ' ' && !(terminate
& TERM_SPACE
))
451 if (c
== '\t' && !(terminate
& TERM_TAB
))
457 /* remove double slashes to make --index work with such filenames */
458 static char *squash_slash(char *name
)
466 if ((name
[j
++] = name
[i
++]) == '/')
467 while (name
[i
] == '/')
474 static char *find_name_gnu(const char *line
, const char *def
, int p_value
)
476 struct strbuf name
= STRBUF_INIT
;
480 * Proposed "new-style" GNU patch/diff format; see
481 * http://marc.info/?l=git&m=112927316408690&w=2
483 if (unquote_c_style(&name
, line
, NULL
)) {
484 strbuf_release(&name
);
488 for (cp
= name
.buf
; p_value
; p_value
--) {
489 cp
= strchr(cp
, '/');
491 strbuf_release(&name
);
497 strbuf_remove(&name
, 0, cp
- name
.buf
);
499 strbuf_insert(&name
, 0, root
.buf
, root
.len
);
500 return squash_slash(strbuf_detach(&name
, NULL
));
503 static size_t sane_tz_len(const char *line
, size_t len
)
507 if (len
< strlen(" +0500") || line
[len
-strlen(" +0500")] != ' ')
509 tz
= line
+ len
- strlen(" +0500");
511 if (tz
[1] != '+' && tz
[1] != '-')
514 for (p
= tz
+ 2; p
!= line
+ len
; p
++)
518 return line
+ len
- tz
;
521 static size_t tz_with_colon_len(const char *line
, size_t len
)
525 if (len
< strlen(" +08:00") || line
[len
- strlen(":00")] != ':')
527 tz
= line
+ len
- strlen(" +08:00");
529 if (tz
[0] != ' ' || (tz
[1] != '+' && tz
[1] != '-'))
532 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
533 !isdigit(*p
++) || !isdigit(*p
++))
536 return line
+ len
- tz
;
539 static size_t date_len(const char *line
, size_t len
)
541 const char *date
, *p
;
543 if (len
< strlen("72-02-05") || line
[len
-strlen("-05")] != '-')
545 p
= date
= line
+ len
- strlen("72-02-05");
547 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
548 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
549 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a date. */
552 if (date
- line
>= strlen("19") &&
553 isdigit(date
[-1]) && isdigit(date
[-2])) /* 4-digit year */
554 date
-= strlen("19");
556 return line
+ len
- date
;
559 static size_t short_time_len(const char *line
, size_t len
)
561 const char *time
, *p
;
563 if (len
< strlen(" 07:01:32") || line
[len
-strlen(":32")] != ':')
565 p
= time
= line
+ len
- strlen(" 07:01:32");
567 /* Permit 1-digit hours? */
569 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
570 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
571 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a time. */
574 return line
+ len
- time
;
577 static size_t fractional_time_len(const char *line
, size_t len
)
582 /* Expected format: 19:41:17.620000023 */
583 if (!len
|| !isdigit(line
[len
- 1]))
587 /* Fractional seconds. */
588 while (p
> line
&& isdigit(*p
))
593 /* Hours, minutes, and whole seconds. */
594 n
= short_time_len(line
, p
- line
);
598 return line
+ len
- p
+ n
;
601 static size_t trailing_spaces_len(const char *line
, size_t len
)
605 /* Expected format: ' ' x (1 or more) */
606 if (!len
|| line
[len
- 1] != ' ')
613 return line
+ len
- (p
+ 1);
620 static size_t diff_timestamp_len(const char *line
, size_t len
)
622 const char *end
= line
+ len
;
626 * Posix: 2010-07-05 19:41:17
627 * GNU: 2010-07-05 19:41:17.620000023 -0500
630 if (!isdigit(end
[-1]))
633 n
= sane_tz_len(line
, end
- line
);
635 n
= tz_with_colon_len(line
, end
- line
);
638 n
= short_time_len(line
, end
- line
);
640 n
= fractional_time_len(line
, end
- line
);
643 n
= date_len(line
, end
- line
);
644 if (!n
) /* No date. Too bad. */
648 if (end
== line
) /* No space before date. */
650 if (end
[-1] == '\t') { /* Success! */
652 return line
+ len
- end
;
654 if (end
[-1] != ' ') /* No space before date. */
657 /* Whitespace damage. */
658 end
-= trailing_spaces_len(line
, end
- line
);
659 return line
+ len
- end
;
662 static char *find_name_common(const char *line
, const char *def
,
663 int p_value
, const char *end
, int terminate
)
666 const char *start
= NULL
;
670 while (line
!= end
) {
673 if (!end
&& isspace(c
)) {
676 if (name_terminate(start
, line
-start
, c
, terminate
))
680 if (c
== '/' && !--p_value
)
684 return squash_slash(xstrdup_or_null(def
));
687 return squash_slash(xstrdup_or_null(def
));
690 * Generally we prefer the shorter name, especially
691 * if the other one is just a variation of that with
692 * something else tacked on to the end (ie "file.orig"
696 int deflen
= strlen(def
);
697 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
698 return squash_slash(xstrdup(def
));
702 char *ret
= xstrfmt("%s%.*s", root
.buf
, len
, start
);
703 return squash_slash(ret
);
706 return squash_slash(xmemdupz(start
, len
));
709 static char *find_name(const char *line
, char *def
, int p_value
, int terminate
)
712 char *name
= find_name_gnu(line
, def
, p_value
);
717 return find_name_common(line
, def
, p_value
, NULL
, terminate
);
720 static char *find_name_traditional(const char *line
, char *def
, int p_value
)
726 char *name
= find_name_gnu(line
, def
, p_value
);
731 len
= strchrnul(line
, '\n') - line
;
732 date_len
= diff_timestamp_len(line
, len
);
734 return find_name_common(line
, def
, p_value
, NULL
, TERM_TAB
);
737 return find_name_common(line
, def
, p_value
, line
+ len
, 0);
740 static int count_slashes(const char *cp
)
752 * Given the string after "--- " or "+++ ", guess the appropriate
753 * p_value for the given patch.
755 static int guess_p_value(struct apply_state
*state
, const char *nameline
)
760 if (is_dev_null(nameline
))
762 name
= find_name_traditional(nameline
, NULL
, 0);
765 cp
= strchr(name
, '/');
768 else if (state
->prefix
) {
770 * Does it begin with "a/$our-prefix" and such? Then this is
771 * very likely to apply to our directory.
773 if (!strncmp(name
, state
->prefix
, state
->prefix_length
))
774 val
= count_slashes(state
->prefix
);
777 if (!strncmp(cp
, state
->prefix
, state
->prefix_length
))
778 val
= count_slashes(state
->prefix
) + 1;
786 * Does the ---/+++ line have the POSIX timestamp after the last HT?
787 * GNU diff puts epoch there to signal a creation/deletion event. Is
788 * this such a timestamp?
790 static int has_epoch_timestamp(const char *nameline
)
793 * We are only interested in epoch timestamp; any non-zero
794 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
795 * For the same reason, the date must be either 1969-12-31 or
796 * 1970-01-01, and the seconds part must be "00".
798 const char stamp_regexp
[] =
799 "^(1969-12-31|1970-01-01)"
801 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
803 "([-+][0-2][0-9]:?[0-5][0-9])\n";
804 const char *timestamp
= NULL
, *cp
, *colon
;
805 static regex_t
*stamp
;
811 for (cp
= nameline
; *cp
!= '\n'; cp
++) {
818 stamp
= xmalloc(sizeof(*stamp
));
819 if (regcomp(stamp
, stamp_regexp
, REG_EXTENDED
)) {
820 warning(_("Cannot prepare timestamp regexp %s"),
826 status
= regexec(stamp
, timestamp
, ARRAY_SIZE(m
), m
, 0);
828 if (status
!= REG_NOMATCH
)
829 warning(_("regexec returned %d for input: %s"),
834 zoneoffset
= strtol(timestamp
+ m
[3].rm_so
+ 1, (char **) &colon
, 10);
836 zoneoffset
= zoneoffset
* 60 + strtol(colon
+ 1, NULL
, 10);
838 zoneoffset
= (zoneoffset
/ 100) * 60 + (zoneoffset
% 100);
839 if (timestamp
[m
[3].rm_so
] == '-')
840 zoneoffset
= -zoneoffset
;
843 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
844 * (west of GMT) or 1970-01-01 (east of GMT)
846 if ((zoneoffset
< 0 && memcmp(timestamp
, "1969-12-31", 10)) ||
847 (0 <= zoneoffset
&& memcmp(timestamp
, "1970-01-01", 10)))
850 hourminute
= (strtol(timestamp
+ 11, NULL
, 10) * 60 +
851 strtol(timestamp
+ 14, NULL
, 10) -
854 return ((zoneoffset
< 0 && hourminute
== 1440) ||
855 (0 <= zoneoffset
&& !hourminute
));
859 * Get the name etc info from the ---/+++ lines of a traditional patch header
861 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
862 * files, we can happily check the index for a match, but for creating a
863 * new file we should try to match whatever "patch" does. I have no idea.
865 static void parse_traditional_patch(struct apply_state
*state
,
872 first
+= 4; /* skip "--- " */
873 second
+= 4; /* skip "+++ " */
874 if (!p_value_known
) {
876 p
= guess_p_value(state
, first
);
877 q
= guess_p_value(state
, second
);
879 if (0 <= p
&& p
== q
) {
884 if (is_dev_null(first
)) {
886 patch
->is_delete
= 0;
887 name
= find_name_traditional(second
, NULL
, state_p_value
);
888 patch
->new_name
= name
;
889 } else if (is_dev_null(second
)) {
891 patch
->is_delete
= 1;
892 name
= find_name_traditional(first
, NULL
, state_p_value
);
893 patch
->old_name
= name
;
896 first_name
= find_name_traditional(first
, NULL
, state_p_value
);
897 name
= find_name_traditional(second
, first_name
, state_p_value
);
899 if (has_epoch_timestamp(first
)) {
901 patch
->is_delete
= 0;
902 patch
->new_name
= name
;
903 } else if (has_epoch_timestamp(second
)) {
905 patch
->is_delete
= 1;
906 patch
->old_name
= name
;
908 patch
->old_name
= name
;
909 patch
->new_name
= xstrdup_or_null(name
);
913 die(_("unable to find filename in patch at line %d"), state_linenr
);
916 static int gitdiff_hdrend(const char *line
, struct patch
*patch
)
922 * We're anal about diff header consistency, to make
923 * sure that we don't end up having strange ambiguous
924 * patches floating around.
926 * As a result, gitdiff_{old|new}name() will check
927 * their names against any previous information, just
930 #define DIFF_OLD_NAME 0
931 #define DIFF_NEW_NAME 1
933 static void gitdiff_verify_name(const char *line
, int isnull
, char **name
, int side
)
935 if (!*name
&& !isnull
) {
936 *name
= find_name(line
, NULL
, state_p_value
, TERM_TAB
);
941 int len
= strlen(*name
);
944 die(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
945 *name
, state_linenr
);
946 another
= find_name(line
, NULL
, state_p_value
, TERM_TAB
);
947 if (!another
|| memcmp(another
, *name
, len
+ 1))
948 die((side
== DIFF_NEW_NAME
) ?
949 _("git apply: bad git-diff - inconsistent new filename on line %d") :
950 _("git apply: bad git-diff - inconsistent old filename on line %d"), state_linenr
);
953 /* expect "/dev/null" */
954 if (memcmp("/dev/null", line
, 9) || line
[9] != '\n')
955 die(_("git apply: bad git-diff - expected /dev/null on line %d"), state_linenr
);
959 static int gitdiff_oldname(const char *line
, struct patch
*patch
)
961 gitdiff_verify_name(line
, patch
->is_new
, &patch
->old_name
,
966 static int gitdiff_newname(const char *line
, struct patch
*patch
)
968 gitdiff_verify_name(line
, patch
->is_delete
, &patch
->new_name
,
973 static int gitdiff_oldmode(const char *line
, struct patch
*patch
)
975 patch
->old_mode
= strtoul(line
, NULL
, 8);
979 static int gitdiff_newmode(const char *line
, struct patch
*patch
)
981 patch
->new_mode
= strtoul(line
, NULL
, 8);
985 static int gitdiff_delete(const char *line
, struct patch
*patch
)
987 patch
->is_delete
= 1;
988 free(patch
->old_name
);
989 patch
->old_name
= xstrdup_or_null(patch
->def_name
);
990 return gitdiff_oldmode(line
, patch
);
993 static int gitdiff_newfile(const char *line
, struct patch
*patch
)
996 free(patch
->new_name
);
997 patch
->new_name
= xstrdup_or_null(patch
->def_name
);
998 return gitdiff_newmode(line
, patch
);
1001 static int gitdiff_copysrc(const char *line
, struct patch
*patch
)
1004 free(patch
->old_name
);
1005 patch
->old_name
= find_name(line
, NULL
, state_p_value
? state_p_value
- 1 : 0, 0);
1009 static int gitdiff_copydst(const char *line
, struct patch
*patch
)
1012 free(patch
->new_name
);
1013 patch
->new_name
= find_name(line
, NULL
, state_p_value
? state_p_value
- 1 : 0, 0);
1017 static int gitdiff_renamesrc(const char *line
, struct patch
*patch
)
1019 patch
->is_rename
= 1;
1020 free(patch
->old_name
);
1021 patch
->old_name
= find_name(line
, NULL
, state_p_value
? state_p_value
- 1 : 0, 0);
1025 static int gitdiff_renamedst(const char *line
, struct patch
*patch
)
1027 patch
->is_rename
= 1;
1028 free(patch
->new_name
);
1029 patch
->new_name
= find_name(line
, NULL
, state_p_value
? state_p_value
- 1 : 0, 0);
1033 static int gitdiff_similarity(const char *line
, struct patch
*patch
)
1035 unsigned long val
= strtoul(line
, NULL
, 10);
1041 static int gitdiff_dissimilarity(const char *line
, struct patch
*patch
)
1043 unsigned long val
= strtoul(line
, NULL
, 10);
1049 static int gitdiff_index(const char *line
, struct patch
*patch
)
1052 * index line is N hexadecimal, "..", N hexadecimal,
1053 * and optional space with octal mode.
1055 const char *ptr
, *eol
;
1058 ptr
= strchr(line
, '.');
1059 if (!ptr
|| ptr
[1] != '.' || 40 < ptr
- line
)
1062 memcpy(patch
->old_sha1_prefix
, line
, len
);
1063 patch
->old_sha1_prefix
[len
] = 0;
1066 ptr
= strchr(line
, ' ');
1067 eol
= strchrnul(line
, '\n');
1069 if (!ptr
|| eol
< ptr
)
1075 memcpy(patch
->new_sha1_prefix
, line
, len
);
1076 patch
->new_sha1_prefix
[len
] = 0;
1078 patch
->old_mode
= strtoul(ptr
+1, NULL
, 8);
1083 * This is normal for a diff that doesn't change anything: we'll fall through
1084 * into the next diff. Tell the parser to break out.
1086 static int gitdiff_unrecognized(const char *line
, struct patch
*patch
)
1092 * Skip p_value leading components from "line"; as we do not accept
1093 * absolute paths, return NULL in that case.
1095 static const char *skip_tree_prefix(const char *line
, int llen
)
1101 return (llen
&& line
[0] == '/') ? NULL
: line
;
1103 nslash
= state_p_value
;
1104 for (i
= 0; i
< llen
; i
++) {
1106 if (ch
== '/' && --nslash
<= 0)
1107 return (i
== 0) ? NULL
: &line
[i
+ 1];
1113 * This is to extract the same name that appears on "diff --git"
1114 * line. We do not find and return anything if it is a rename
1115 * patch, and it is OK because we will find the name elsewhere.
1116 * We need to reliably find name only when it is mode-change only,
1117 * creation or deletion of an empty file. In any of these cases,
1118 * both sides are the same name under a/ and b/ respectively.
1120 static char *git_header_name(const char *line
, int llen
)
1123 const char *second
= NULL
;
1124 size_t len
, line_len
;
1126 line
+= strlen("diff --git ");
1127 llen
-= strlen("diff --git ");
1131 struct strbuf first
= STRBUF_INIT
;
1132 struct strbuf sp
= STRBUF_INIT
;
1134 if (unquote_c_style(&first
, line
, &second
))
1135 goto free_and_fail1
;
1137 /* strip the a/b prefix including trailing slash */
1138 cp
= skip_tree_prefix(first
.buf
, first
.len
);
1140 goto free_and_fail1
;
1141 strbuf_remove(&first
, 0, cp
- first
.buf
);
1144 * second points at one past closing dq of name.
1145 * find the second name.
1147 while ((second
< line
+ llen
) && isspace(*second
))
1150 if (line
+ llen
<= second
)
1151 goto free_and_fail1
;
1152 if (*second
== '"') {
1153 if (unquote_c_style(&sp
, second
, NULL
))
1154 goto free_and_fail1
;
1155 cp
= skip_tree_prefix(sp
.buf
, sp
.len
);
1157 goto free_and_fail1
;
1158 /* They must match, otherwise ignore */
1159 if (strcmp(cp
, first
.buf
))
1160 goto free_and_fail1
;
1161 strbuf_release(&sp
);
1162 return strbuf_detach(&first
, NULL
);
1165 /* unquoted second */
1166 cp
= skip_tree_prefix(second
, line
+ llen
- second
);
1168 goto free_and_fail1
;
1169 if (line
+ llen
- cp
!= first
.len
||
1170 memcmp(first
.buf
, cp
, first
.len
))
1171 goto free_and_fail1
;
1172 return strbuf_detach(&first
, NULL
);
1175 strbuf_release(&first
);
1176 strbuf_release(&sp
);
1180 /* unquoted first name */
1181 name
= skip_tree_prefix(line
, llen
);
1186 * since the first name is unquoted, a dq if exists must be
1187 * the beginning of the second name.
1189 for (second
= name
; second
< line
+ llen
; second
++) {
1190 if (*second
== '"') {
1191 struct strbuf sp
= STRBUF_INIT
;
1194 if (unquote_c_style(&sp
, second
, NULL
))
1195 goto free_and_fail2
;
1197 np
= skip_tree_prefix(sp
.buf
, sp
.len
);
1199 goto free_and_fail2
;
1201 len
= sp
.buf
+ sp
.len
- np
;
1202 if (len
< second
- name
&&
1203 !strncmp(np
, name
, len
) &&
1204 isspace(name
[len
])) {
1206 strbuf_remove(&sp
, 0, np
- sp
.buf
);
1207 return strbuf_detach(&sp
, NULL
);
1211 strbuf_release(&sp
);
1217 * Accept a name only if it shows up twice, exactly the same
1220 second
= strchr(name
, '\n');
1223 line_len
= second
- name
;
1224 for (len
= 0 ; ; len
++) {
1225 switch (name
[len
]) {
1230 case '\t': case ' ':
1232 * Is this the separator between the preimage
1233 * and the postimage pathname? Again, we are
1234 * only interested in the case where there is
1235 * no rename, as this is only to set def_name
1236 * and a rename patch has the names elsewhere
1237 * in an unambiguous form.
1240 return NULL
; /* no postimage name */
1241 second
= skip_tree_prefix(name
+ len
+ 1,
1242 line_len
- (len
+ 1));
1246 * Does len bytes starting at "name" and "second"
1247 * (that are separated by one HT or SP we just
1248 * found) exactly match?
1250 if (second
[len
] == '\n' && !strncmp(name
, second
, len
))
1251 return xmemdupz(name
, len
);
1256 /* Verify that we recognize the lines following a git header */
1257 static int parse_git_header(const char *line
, int len
, unsigned int size
, struct patch
*patch
)
1259 unsigned long offset
;
1261 /* A git diff has explicit new/delete information, so we don't guess */
1263 patch
->is_delete
= 0;
1266 * Some things may not have the old name in the
1267 * rest of the headers anywhere (pure mode changes,
1268 * or removing or adding empty files), so we get
1269 * the default name from the header.
1271 patch
->def_name
= git_header_name(line
, len
);
1272 if (patch
->def_name
&& root
.len
) {
1273 char *s
= xstrfmt("%s%s", root
.buf
, patch
->def_name
);
1274 free(patch
->def_name
);
1275 patch
->def_name
= s
;
1281 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, state_linenr
++) {
1282 static const struct opentry
{
1284 int (*fn
)(const char *, struct patch
*);
1286 { "@@ -", gitdiff_hdrend
},
1287 { "--- ", gitdiff_oldname
},
1288 { "+++ ", gitdiff_newname
},
1289 { "old mode ", gitdiff_oldmode
},
1290 { "new mode ", gitdiff_newmode
},
1291 { "deleted file mode ", gitdiff_delete
},
1292 { "new file mode ", gitdiff_newfile
},
1293 { "copy from ", gitdiff_copysrc
},
1294 { "copy to ", gitdiff_copydst
},
1295 { "rename old ", gitdiff_renamesrc
},
1296 { "rename new ", gitdiff_renamedst
},
1297 { "rename from ", gitdiff_renamesrc
},
1298 { "rename to ", gitdiff_renamedst
},
1299 { "similarity index ", gitdiff_similarity
},
1300 { "dissimilarity index ", gitdiff_dissimilarity
},
1301 { "index ", gitdiff_index
},
1302 { "", gitdiff_unrecognized
},
1306 len
= linelen(line
, size
);
1307 if (!len
|| line
[len
-1] != '\n')
1309 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
1310 const struct opentry
*p
= optable
+ i
;
1311 int oplen
= strlen(p
->str
);
1312 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
1314 if (p
->fn(line
+ oplen
, patch
) < 0)
1323 static int parse_num(const char *line
, unsigned long *p
)
1327 if (!isdigit(*line
))
1329 *p
= strtoul(line
, &ptr
, 10);
1333 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
1334 unsigned long *p1
, unsigned long *p2
)
1338 if (offset
< 0 || offset
>= len
)
1343 digits
= parse_num(line
, p1
);
1353 digits
= parse_num(line
+1, p2
);
1362 ex
= strlen(expect
);
1365 if (memcmp(line
, expect
, ex
))
1371 static void recount_diff(const char *line
, int size
, struct fragment
*fragment
)
1373 int oldlines
= 0, newlines
= 0, ret
= 0;
1376 warning("recount: ignore empty hunk");
1381 int len
= linelen(line
, size
);
1389 case ' ': case '\n':
1401 ret
= size
< 3 || !starts_with(line
, "@@ ");
1404 ret
= size
< 5 || !starts_with(line
, "diff ");
1411 warning(_("recount: unexpected line: %.*s"),
1412 (int)linelen(line
, size
), line
);
1417 fragment
->oldlines
= oldlines
;
1418 fragment
->newlines
= newlines
;
1422 * Parse a unified diff fragment header of the
1423 * form "@@ -a,b +c,d @@"
1425 static int parse_fragment_header(const char *line
, int len
, struct fragment
*fragment
)
1429 if (!len
|| line
[len
-1] != '\n')
1432 /* Figure out the number of lines in a fragment */
1433 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
1434 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
1439 static int find_header(struct apply_state
*state
,
1443 struct patch
*patch
)
1445 unsigned long offset
, len
;
1447 patch
->is_toplevel_relative
= 0;
1448 patch
->is_rename
= patch
->is_copy
= 0;
1449 patch
->is_new
= patch
->is_delete
= -1;
1450 patch
->old_mode
= patch
->new_mode
= 0;
1451 patch
->old_name
= patch
->new_name
= NULL
;
1452 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, state_linenr
++) {
1453 unsigned long nextlen
;
1455 len
= linelen(line
, size
);
1459 /* Testing this early allows us to take a few shortcuts.. */
1464 * Make sure we don't find any unconnected patch fragments.
1465 * That's a sign that we didn't find a header, and that a
1466 * patch has become corrupted/broken up.
1468 if (!memcmp("@@ -", line
, 4)) {
1469 struct fragment dummy
;
1470 if (parse_fragment_header(line
, len
, &dummy
) < 0)
1472 die(_("patch fragment without header at line %d: %.*s"),
1473 state_linenr
, (int)len
-1, line
);
1480 * Git patch? It might not have a real patch, just a rename
1481 * or mode change, so we handle that specially
1483 if (!memcmp("diff --git ", line
, 11)) {
1484 int git_hdr_len
= parse_git_header(line
, len
, size
, patch
);
1485 if (git_hdr_len
<= len
)
1487 if (!patch
->old_name
&& !patch
->new_name
) {
1488 if (!patch
->def_name
)
1489 die(Q_("git diff header lacks filename information when removing "
1490 "%d leading pathname component (line %d)",
1491 "git diff header lacks filename information when removing "
1492 "%d leading pathname components (line %d)",
1494 state_p_value
, state_linenr
);
1495 patch
->old_name
= xstrdup(patch
->def_name
);
1496 patch
->new_name
= xstrdup(patch
->def_name
);
1498 if (!patch
->is_delete
&& !patch
->new_name
)
1499 die("git diff header lacks filename information "
1500 "(line %d)", state_linenr
);
1501 patch
->is_toplevel_relative
= 1;
1502 *hdrsize
= git_hdr_len
;
1506 /* --- followed by +++ ? */
1507 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
1511 * We only accept unified patches, so we want it to
1512 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1513 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1515 nextlen
= linelen(line
+ len
, size
- len
);
1516 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
1519 /* Ok, we'll consider it a patch */
1520 parse_traditional_patch(state
, line
, line
+len
, patch
);
1521 *hdrsize
= len
+ nextlen
;
1528 static void record_ws_error(struct apply_state
*state
,
1540 if (squelch_whitespace_errors
&&
1541 squelch_whitespace_errors
< whitespace_error
)
1544 err
= whitespace_error_string(result
);
1545 fprintf(stderr
, "%s:%d: %s.\n%.*s\n",
1546 state
->patch_input_file
, linenr
, err
, len
, line
);
1550 static void check_whitespace(struct apply_state
*state
,
1555 unsigned result
= ws_check(line
+ 1, len
- 1, ws_rule
);
1557 record_ws_error(state
, result
, line
+ 1, len
- 2, state_linenr
);
1561 * Parse a unified diff. Note that this really needs to parse each
1562 * fragment separately, since the only way to know the difference
1563 * between a "---" that is part of a patch, and a "---" that starts
1564 * the next patch is to look at the line counts..
1566 static int parse_fragment(struct apply_state
*state
,
1569 struct patch
*patch
,
1570 struct fragment
*fragment
)
1573 int len
= linelen(line
, size
), offset
;
1574 unsigned long oldlines
, newlines
;
1575 unsigned long leading
, trailing
;
1577 offset
= parse_fragment_header(line
, len
, fragment
);
1580 if (offset
> 0 && patch
->recount
)
1581 recount_diff(line
+ offset
, size
- offset
, fragment
);
1582 oldlines
= fragment
->oldlines
;
1583 newlines
= fragment
->newlines
;
1587 /* Parse the thing.. */
1591 added
= deleted
= 0;
1594 offset
+= len
, size
-= len
, line
+= len
, state_linenr
++) {
1595 if (!oldlines
&& !newlines
)
1597 len
= linelen(line
, size
);
1598 if (!len
|| line
[len
-1] != '\n')
1603 case '\n': /* newer GNU diff, an empty context line */
1607 if (!deleted
&& !added
)
1610 if (!state
->apply_in_reverse
&&
1611 ws_error_action
== correct_ws_error
)
1612 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1615 if (state
->apply_in_reverse
&&
1616 ws_error_action
!= nowarn_ws_error
)
1617 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1623 if (!state
->apply_in_reverse
&&
1624 ws_error_action
!= nowarn_ws_error
)
1625 check_whitespace(state
, line
, len
, patch
->ws_rule
);
1632 * We allow "\ No newline at end of file". Depending
1633 * on locale settings when the patch was produced we
1634 * don't know what this line looks like. The only
1635 * thing we do know is that it begins with "\ ".
1636 * Checking for 12 is just for sanity check -- any
1637 * l10n of "\ No newline..." is at least that long.
1640 if (len
< 12 || memcmp(line
, "\\ ", 2))
1645 if (oldlines
|| newlines
)
1647 if (!deleted
&& !added
)
1650 fragment
->leading
= leading
;
1651 fragment
->trailing
= trailing
;
1654 * If a fragment ends with an incomplete line, we failed to include
1655 * it in the above loop because we hit oldlines == newlines == 0
1658 if (12 < size
&& !memcmp(line
, "\\ ", 2))
1659 offset
+= linelen(line
, size
);
1661 patch
->lines_added
+= added
;
1662 patch
->lines_deleted
+= deleted
;
1664 if (0 < patch
->is_new
&& oldlines
)
1665 return error(_("new file depends on old contents"));
1666 if (0 < patch
->is_delete
&& newlines
)
1667 return error(_("deleted file still has contents"));
1672 * We have seen "diff --git a/... b/..." header (or a traditional patch
1673 * header). Read hunks that belong to this patch into fragments and hang
1674 * them to the given patch structure.
1676 * The (fragment->patch, fragment->size) pair points into the memory given
1677 * by the caller, not a copy, when we return.
1679 static int parse_single_patch(struct apply_state
*state
,
1682 struct patch
*patch
)
1684 unsigned long offset
= 0;
1685 unsigned long oldlines
= 0, newlines
= 0, context
= 0;
1686 struct fragment
**fragp
= &patch
->fragments
;
1688 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
1689 struct fragment
*fragment
;
1692 fragment
= xcalloc(1, sizeof(*fragment
));
1693 fragment
->linenr
= state_linenr
;
1694 len
= parse_fragment(state
, line
, size
, patch
, fragment
);
1696 die(_("corrupt patch at line %d"), state_linenr
);
1697 fragment
->patch
= line
;
1698 fragment
->size
= len
;
1699 oldlines
+= fragment
->oldlines
;
1700 newlines
+= fragment
->newlines
;
1701 context
+= fragment
->leading
+ fragment
->trailing
;
1704 fragp
= &fragment
->next
;
1712 * If something was removed (i.e. we have old-lines) it cannot
1713 * be creation, and if something was added it cannot be
1714 * deletion. However, the reverse is not true; --unified=0
1715 * patches that only add are not necessarily creation even
1716 * though they do not have any old lines, and ones that only
1717 * delete are not necessarily deletion.
1719 * Unfortunately, a real creation/deletion patch do _not_ have
1720 * any context line by definition, so we cannot safely tell it
1721 * apart with --unified=0 insanity. At least if the patch has
1722 * more than one hunk it is not creation or deletion.
1724 if (patch
->is_new
< 0 &&
1725 (oldlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1727 if (patch
->is_delete
< 0 &&
1728 (newlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1729 patch
->is_delete
= 0;
1731 if (0 < patch
->is_new
&& oldlines
)
1732 die(_("new file %s depends on old contents"), patch
->new_name
);
1733 if (0 < patch
->is_delete
&& newlines
)
1734 die(_("deleted file %s still has contents"), patch
->old_name
);
1735 if (!patch
->is_delete
&& !newlines
&& context
)
1738 "file %s becomes empty but is not deleted"),
1744 static inline int metadata_changes(struct patch
*patch
)
1746 return patch
->is_rename
> 0 ||
1747 patch
->is_copy
> 0 ||
1748 patch
->is_new
> 0 ||
1750 (patch
->old_mode
&& patch
->new_mode
&&
1751 patch
->old_mode
!= patch
->new_mode
);
1754 static char *inflate_it(const void *data
, unsigned long size
,
1755 unsigned long inflated_size
)
1761 memset(&stream
, 0, sizeof(stream
));
1763 stream
.next_in
= (unsigned char *)data
;
1764 stream
.avail_in
= size
;
1765 stream
.next_out
= out
= xmalloc(inflated_size
);
1766 stream
.avail_out
= inflated_size
;
1767 git_inflate_init(&stream
);
1768 st
= git_inflate(&stream
, Z_FINISH
);
1769 git_inflate_end(&stream
);
1770 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1778 * Read a binary hunk and return a new fragment; fragment->patch
1779 * points at an allocated memory that the caller must free, so
1780 * it is marked as "->free_patch = 1".
1782 static struct fragment
*parse_binary_hunk(char **buf_p
,
1783 unsigned long *sz_p
,
1788 * Expect a line that begins with binary patch method ("literal"
1789 * or "delta"), followed by the length of data before deflating.
1790 * a sequence of 'length-byte' followed by base-85 encoded data
1791 * should follow, terminated by a newline.
1793 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1794 * and we would limit the patch line to 66 characters,
1795 * so one line can fit up to 13 groups that would decode
1796 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1797 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1800 unsigned long size
= *sz_p
;
1801 char *buffer
= *buf_p
;
1803 unsigned long origlen
;
1806 struct fragment
*frag
;
1808 llen
= linelen(buffer
, size
);
1813 if (starts_with(buffer
, "delta ")) {
1814 patch_method
= BINARY_DELTA_DEFLATED
;
1815 origlen
= strtoul(buffer
+ 6, NULL
, 10);
1817 else if (starts_with(buffer
, "literal ")) {
1818 patch_method
= BINARY_LITERAL_DEFLATED
;
1819 origlen
= strtoul(buffer
+ 8, NULL
, 10);
1827 int byte_length
, max_byte_length
, newsize
;
1828 llen
= linelen(buffer
, size
);
1832 /* consume the blank line */
1838 * Minimum line is "A00000\n" which is 7-byte long,
1839 * and the line length must be multiple of 5 plus 2.
1841 if ((llen
< 7) || (llen
-2) % 5)
1843 max_byte_length
= (llen
- 2) / 5 * 4;
1844 byte_length
= *buffer
;
1845 if ('A' <= byte_length
&& byte_length
<= 'Z')
1846 byte_length
= byte_length
- 'A' + 1;
1847 else if ('a' <= byte_length
&& byte_length
<= 'z')
1848 byte_length
= byte_length
- 'a' + 27;
1851 /* if the input length was not multiple of 4, we would
1852 * have filler at the end but the filler should never
1855 if (max_byte_length
< byte_length
||
1856 byte_length
<= max_byte_length
- 4)
1858 newsize
= hunk_size
+ byte_length
;
1859 data
= xrealloc(data
, newsize
);
1860 if (decode_85(data
+ hunk_size
, buffer
+ 1, byte_length
))
1862 hunk_size
= newsize
;
1867 frag
= xcalloc(1, sizeof(*frag
));
1868 frag
->patch
= inflate_it(data
, hunk_size
, origlen
);
1869 frag
->free_patch
= 1;
1873 frag
->size
= origlen
;
1877 frag
->binary_patch_method
= patch_method
;
1883 error(_("corrupt binary patch at line %d: %.*s"),
1884 state_linenr
-1, llen
-1, buffer
);
1890 * -1 in case of error,
1891 * the length of the parsed binary patch otherwise
1893 static int parse_binary(char *buffer
, unsigned long size
, struct patch
*patch
)
1896 * We have read "GIT binary patch\n"; what follows is a line
1897 * that says the patch method (currently, either "literal" or
1898 * "delta") and the length of data before deflating; a
1899 * sequence of 'length-byte' followed by base-85 encoded data
1902 * When a binary patch is reversible, there is another binary
1903 * hunk in the same format, starting with patch method (either
1904 * "literal" or "delta") with the length of data, and a sequence
1905 * of length-byte + base-85 encoded data, terminated with another
1906 * empty line. This data, when applied to the postimage, produces
1909 struct fragment
*forward
;
1910 struct fragment
*reverse
;
1914 forward
= parse_binary_hunk(&buffer
, &size
, &status
, &used
);
1915 if (!forward
&& !status
)
1916 /* there has to be one hunk (forward hunk) */
1917 return error(_("unrecognized binary patch at line %d"), state_linenr
-1);
1919 /* otherwise we already gave an error message */
1922 reverse
= parse_binary_hunk(&buffer
, &size
, &status
, &used_1
);
1927 * Not having reverse hunk is not an error, but having
1928 * a corrupt reverse hunk is.
1930 free((void*) forward
->patch
);
1934 forward
->next
= reverse
;
1935 patch
->fragments
= forward
;
1936 patch
->is_binary
= 1;
1940 static void prefix_one(struct apply_state
*state
, char **name
)
1942 char *old_name
= *name
;
1945 *name
= xstrdup(prefix_filename(state
->prefix
, state
->prefix_length
, *name
));
1949 static void prefix_patch(struct apply_state
*state
, struct patch
*p
)
1951 if (!state
->prefix
|| p
->is_toplevel_relative
)
1953 prefix_one(state
, &p
->new_name
);
1954 prefix_one(state
, &p
->old_name
);
1961 static struct string_list limit_by_name
;
1962 static int has_include
;
1963 static void add_name_limit(const char *name
, int exclude
)
1965 struct string_list_item
*it
;
1967 it
= string_list_append(&limit_by_name
, name
);
1968 it
->util
= exclude
? NULL
: (void *) 1;
1971 static int use_patch(struct apply_state
*state
, struct patch
*p
)
1973 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
1976 /* Paths outside are not touched regardless of "--include" */
1977 if (0 < state
->prefix_length
) {
1978 int pathlen
= strlen(pathname
);
1979 if (pathlen
<= state
->prefix_length
||
1980 memcmp(state
->prefix
, pathname
, state
->prefix_length
))
1984 /* See if it matches any of exclude/include rule */
1985 for (i
= 0; i
< limit_by_name
.nr
; i
++) {
1986 struct string_list_item
*it
= &limit_by_name
.items
[i
];
1987 if (!wildmatch(it
->string
, pathname
, 0, NULL
))
1988 return (it
->util
!= NULL
);
1992 * If we had any include, a path that does not match any rule is
1993 * not used. Otherwise, we saw bunch of exclude rules (or none)
1994 * and such a path is used.
1996 return !has_include
;
2001 * Read the patch text in "buffer" that extends for "size" bytes; stop
2002 * reading after seeing a single patch (i.e. changes to a single file).
2003 * Create fragments (i.e. patch hunks) and hang them to the given patch.
2004 * Return the number of bytes consumed, so that the caller can call us
2005 * again for the next patch.
2007 static int parse_chunk(struct apply_state
*state
, char *buffer
, unsigned long size
, struct patch
*patch
)
2009 int hdrsize
, patchsize
;
2010 int offset
= find_header(state
, buffer
, size
, &hdrsize
, patch
);
2015 prefix_patch(state
, patch
);
2017 if (!use_patch(state
, patch
))
2020 patch
->ws_rule
= whitespace_rule(patch
->new_name
2024 patchsize
= parse_single_patch(state
,
2025 buffer
+ offset
+ hdrsize
,
2026 size
- offset
- hdrsize
,
2030 static const char git_binary
[] = "GIT binary patch\n";
2031 int hd
= hdrsize
+ offset
;
2032 unsigned long llen
= linelen(buffer
+ hd
, size
- hd
);
2034 if (llen
== sizeof(git_binary
) - 1 &&
2035 !memcmp(git_binary
, buffer
+ hd
, llen
)) {
2038 used
= parse_binary(buffer
+ hd
+ llen
,
2039 size
- hd
- llen
, patch
);
2043 patchsize
= used
+ llen
;
2047 else if (!memcmp(" differ\n", buffer
+ hd
+ llen
- 8, 8)) {
2048 static const char *binhdr
[] = {
2054 for (i
= 0; binhdr
[i
]; i
++) {
2055 int len
= strlen(binhdr
[i
]);
2056 if (len
< size
- hd
&&
2057 !memcmp(binhdr
[i
], buffer
+ hd
, len
)) {
2059 patch
->is_binary
= 1;
2066 /* Empty patch cannot be applied if it is a text patch
2067 * without metadata change. A binary patch appears
2070 if ((state
->apply
|| state
->check
) &&
2071 (!patch
->is_binary
&& !metadata_changes(patch
)))
2072 die(_("patch with only garbage at line %d"), state_linenr
);
2075 return offset
+ hdrsize
+ patchsize
;
2078 #define swap(a,b) myswap((a),(b),sizeof(a))
2080 #define myswap(a, b, size) do { \
2081 unsigned char mytmp[size]; \
2082 memcpy(mytmp, &a, size); \
2083 memcpy(&a, &b, size); \
2084 memcpy(&b, mytmp, size); \
2087 static void reverse_patches(struct patch
*p
)
2089 for (; p
; p
= p
->next
) {
2090 struct fragment
*frag
= p
->fragments
;
2092 swap(p
->new_name
, p
->old_name
);
2093 swap(p
->new_mode
, p
->old_mode
);
2094 swap(p
->is_new
, p
->is_delete
);
2095 swap(p
->lines_added
, p
->lines_deleted
);
2096 swap(p
->old_sha1_prefix
, p
->new_sha1_prefix
);
2098 for (; frag
; frag
= frag
->next
) {
2099 swap(frag
->newpos
, frag
->oldpos
);
2100 swap(frag
->newlines
, frag
->oldlines
);
2105 static const char pluses
[] =
2106 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2107 static const char minuses
[]=
2108 "----------------------------------------------------------------------";
2110 static void show_stats(struct patch
*patch
)
2112 struct strbuf qname
= STRBUF_INIT
;
2113 char *cp
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
2116 quote_c_style(cp
, &qname
, NULL
, 0);
2119 * "scale" the filename
2125 if (qname
.len
> max
) {
2126 cp
= strchr(qname
.buf
+ qname
.len
+ 3 - max
, '/');
2128 cp
= qname
.buf
+ qname
.len
+ 3 - max
;
2129 strbuf_splice(&qname
, 0, cp
- qname
.buf
, "...", 3);
2132 if (patch
->is_binary
) {
2133 printf(" %-*s | Bin\n", max
, qname
.buf
);
2134 strbuf_release(&qname
);
2138 printf(" %-*s |", max
, qname
.buf
);
2139 strbuf_release(&qname
);
2142 * scale the add/delete
2144 max
= max
+ max_change
> 70 ? 70 - max
: max_change
;
2145 add
= patch
->lines_added
;
2146 del
= patch
->lines_deleted
;
2148 if (max_change
> 0) {
2149 int total
= ((add
+ del
) * max
+ max_change
/ 2) / max_change
;
2150 add
= (add
* max
+ max_change
/ 2) / max_change
;
2153 printf("%5d %.*s%.*s\n", patch
->lines_added
+ patch
->lines_deleted
,
2154 add
, pluses
, del
, minuses
);
2157 static int read_old_data(struct stat
*st
, const char *path
, struct strbuf
*buf
)
2159 switch (st
->st_mode
& S_IFMT
) {
2161 if (strbuf_readlink(buf
, path
, st
->st_size
) < 0)
2162 return error(_("unable to read symlink %s"), path
);
2165 if (strbuf_read_file(buf
, path
, st
->st_size
) != st
->st_size
)
2166 return error(_("unable to open or read %s"), path
);
2167 convert_to_git(path
, buf
->buf
, buf
->len
, buf
, 0);
2175 * Update the preimage, and the common lines in postimage,
2176 * from buffer buf of length len. If postlen is 0 the postimage
2177 * is updated in place, otherwise it's updated on a new buffer
2181 static void update_pre_post_images(struct image
*preimage
,
2182 struct image
*postimage
,
2184 size_t len
, size_t postlen
)
2186 int i
, ctx
, reduced
;
2187 char *new, *old
, *fixed
;
2188 struct image fixed_preimage
;
2191 * Update the preimage with whitespace fixes. Note that we
2192 * are not losing preimage->buf -- apply_one_fragment() will
2195 prepare_image(&fixed_preimage
, buf
, len
, 1);
2197 ? fixed_preimage
.nr
== preimage
->nr
2198 : fixed_preimage
.nr
<= preimage
->nr
);
2199 for (i
= 0; i
< fixed_preimage
.nr
; i
++)
2200 fixed_preimage
.line
[i
].flag
= preimage
->line
[i
].flag
;
2201 free(preimage
->line_allocated
);
2202 *preimage
= fixed_preimage
;
2205 * Adjust the common context lines in postimage. This can be
2206 * done in-place when we are shrinking it with whitespace
2207 * fixing, but needs a new buffer when ignoring whitespace or
2208 * expanding leading tabs to spaces.
2210 * We trust the caller to tell us if the update can be done
2211 * in place (postlen==0) or not.
2213 old
= postimage
->buf
;
2215 new = postimage
->buf
= xmalloc(postlen
);
2218 fixed
= preimage
->buf
;
2220 for (i
= reduced
= ctx
= 0; i
< postimage
->nr
; i
++) {
2221 size_t l_len
= postimage
->line
[i
].len
;
2222 if (!(postimage
->line
[i
].flag
& LINE_COMMON
)) {
2223 /* an added line -- no counterparts in preimage */
2224 memmove(new, old
, l_len
);
2230 /* a common context -- skip it in the original postimage */
2233 /* and find the corresponding one in the fixed preimage */
2234 while (ctx
< preimage
->nr
&&
2235 !(preimage
->line
[ctx
].flag
& LINE_COMMON
)) {
2236 fixed
+= preimage
->line
[ctx
].len
;
2241 * preimage is expected to run out, if the caller
2242 * fixed addition of trailing blank lines.
2244 if (preimage
->nr
<= ctx
) {
2249 /* and copy it in, while fixing the line length */
2250 l_len
= preimage
->line
[ctx
].len
;
2251 memcpy(new, fixed
, l_len
);
2254 postimage
->line
[i
].len
= l_len
;
2259 ? postlen
< new - postimage
->buf
2260 : postimage
->len
< new - postimage
->buf
)
2261 die("BUG: caller miscounted postlen: asked %d, orig = %d, used = %d",
2262 (int)postlen
, (int) postimage
->len
, (int)(new - postimage
->buf
));
2264 /* Fix the length of the whole thing */
2265 postimage
->len
= new - postimage
->buf
;
2266 postimage
->nr
-= reduced
;
2269 static int line_by_line_fuzzy_match(struct image
*img
,
2270 struct image
*preimage
,
2271 struct image
*postimage
,
2279 size_t postlen
= postimage
->len
;
2284 struct strbuf fixed
;
2288 for (i
= 0; i
< preimage_limit
; i
++) {
2289 size_t prelen
= preimage
->line
[i
].len
;
2290 size_t imglen
= img
->line
[try_lno
+i
].len
;
2292 if (!fuzzy_matchlines(img
->buf
+ try + imgoff
, imglen
,
2293 preimage
->buf
+ preoff
, prelen
))
2295 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2296 postlen
+= imglen
- prelen
;
2302 * Ok, the preimage matches with whitespace fuzz.
2304 * imgoff now holds the true length of the target that
2305 * matches the preimage before the end of the file.
2307 * Count the number of characters in the preimage that fall
2308 * beyond the end of the file and make sure that all of them
2309 * are whitespace characters. (This can only happen if
2310 * we are removing blank lines at the end of the file.)
2312 buf
= preimage_eof
= preimage
->buf
+ preoff
;
2313 for ( ; i
< preimage
->nr
; i
++)
2314 preoff
+= preimage
->line
[i
].len
;
2315 preimage_end
= preimage
->buf
+ preoff
;
2316 for ( ; buf
< preimage_end
; buf
++)
2321 * Update the preimage and the common postimage context
2322 * lines to use the same whitespace as the target.
2323 * If whitespace is missing in the target (i.e.
2324 * if the preimage extends beyond the end of the file),
2325 * use the whitespace from the preimage.
2327 extra_chars
= preimage_end
- preimage_eof
;
2328 strbuf_init(&fixed
, imgoff
+ extra_chars
);
2329 strbuf_add(&fixed
, img
->buf
+ try, imgoff
);
2330 strbuf_add(&fixed
, preimage_eof
, extra_chars
);
2331 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2332 update_pre_post_images(preimage
, postimage
,
2333 fixed_buf
, fixed_len
, postlen
);
2337 static int match_fragment(struct image
*img
,
2338 struct image
*preimage
,
2339 struct image
*postimage
,
2343 int match_beginning
, int match_end
)
2346 char *fixed_buf
, *buf
, *orig
, *target
;
2347 struct strbuf fixed
;
2348 size_t fixed_len
, postlen
;
2351 if (preimage
->nr
+ try_lno
<= img
->nr
) {
2353 * The hunk falls within the boundaries of img.
2355 preimage_limit
= preimage
->nr
;
2356 if (match_end
&& (preimage
->nr
+ try_lno
!= img
->nr
))
2358 } else if (ws_error_action
== correct_ws_error
&&
2359 (ws_rule
& WS_BLANK_AT_EOF
)) {
2361 * This hunk extends beyond the end of img, and we are
2362 * removing blank lines at the end of the file. This
2363 * many lines from the beginning of the preimage must
2364 * match with img, and the remainder of the preimage
2367 preimage_limit
= img
->nr
- try_lno
;
2370 * The hunk extends beyond the end of the img and
2371 * we are not removing blanks at the end, so we
2372 * should reject the hunk at this position.
2377 if (match_beginning
&& try_lno
)
2380 /* Quick hash check */
2381 for (i
= 0; i
< preimage_limit
; i
++)
2382 if ((img
->line
[try_lno
+ i
].flag
& LINE_PATCHED
) ||
2383 (preimage
->line
[i
].hash
!= img
->line
[try_lno
+ i
].hash
))
2386 if (preimage_limit
== preimage
->nr
) {
2388 * Do we have an exact match? If we were told to match
2389 * at the end, size must be exactly at try+fragsize,
2390 * otherwise try+fragsize must be still within the preimage,
2391 * and either case, the old piece should match the preimage
2395 ? (try + preimage
->len
== img
->len
)
2396 : (try + preimage
->len
<= img
->len
)) &&
2397 !memcmp(img
->buf
+ try, preimage
->buf
, preimage
->len
))
2401 * The preimage extends beyond the end of img, so
2402 * there cannot be an exact match.
2404 * There must be one non-blank context line that match
2405 * a line before the end of img.
2409 buf
= preimage
->buf
;
2411 for (i
= 0; i
< preimage_limit
; i
++)
2412 buf_end
+= preimage
->line
[i
].len
;
2414 for ( ; buf
< buf_end
; buf
++)
2422 * No exact match. If we are ignoring whitespace, run a line-by-line
2423 * fuzzy matching. We collect all the line length information because
2424 * we need it to adjust whitespace if we match.
2426 if (ws_ignore_action
== ignore_ws_change
)
2427 return line_by_line_fuzzy_match(img
, preimage
, postimage
,
2428 try, try_lno
, preimage_limit
);
2430 if (ws_error_action
!= correct_ws_error
)
2434 * The hunk does not apply byte-by-byte, but the hash says
2435 * it might with whitespace fuzz. We weren't asked to
2436 * ignore whitespace, we were asked to correct whitespace
2437 * errors, so let's try matching after whitespace correction.
2439 * While checking the preimage against the target, whitespace
2440 * errors in both fixed, we count how large the corresponding
2441 * postimage needs to be. The postimage prepared by
2442 * apply_one_fragment() has whitespace errors fixed on added
2443 * lines already, but the common lines were propagated as-is,
2444 * which may become longer when their whitespace errors are
2448 /* First count added lines in postimage */
2450 for (i
= 0; i
< postimage
->nr
; i
++) {
2451 if (!(postimage
->line
[i
].flag
& LINE_COMMON
))
2452 postlen
+= postimage
->line
[i
].len
;
2456 * The preimage may extend beyond the end of the file,
2457 * but in this loop we will only handle the part of the
2458 * preimage that falls within the file.
2460 strbuf_init(&fixed
, preimage
->len
+ 1);
2461 orig
= preimage
->buf
;
2462 target
= img
->buf
+ try;
2463 for (i
= 0; i
< preimage_limit
; i
++) {
2464 size_t oldlen
= preimage
->line
[i
].len
;
2465 size_t tgtlen
= img
->line
[try_lno
+ i
].len
;
2466 size_t fixstart
= fixed
.len
;
2467 struct strbuf tgtfix
;
2470 /* Try fixing the line in the preimage */
2471 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2473 /* Try fixing the line in the target */
2474 strbuf_init(&tgtfix
, tgtlen
);
2475 ws_fix_copy(&tgtfix
, target
, tgtlen
, ws_rule
, NULL
);
2478 * If they match, either the preimage was based on
2479 * a version before our tree fixed whitespace breakage,
2480 * or we are lacking a whitespace-fix patch the tree
2481 * the preimage was based on already had (i.e. target
2482 * has whitespace breakage, the preimage doesn't).
2483 * In either case, we are fixing the whitespace breakages
2484 * so we might as well take the fix together with their
2487 match
= (tgtfix
.len
== fixed
.len
- fixstart
&&
2488 !memcmp(tgtfix
.buf
, fixed
.buf
+ fixstart
,
2489 fixed
.len
- fixstart
));
2491 /* Add the length if this is common with the postimage */
2492 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2493 postlen
+= tgtfix
.len
;
2495 strbuf_release(&tgtfix
);
2505 * Now handle the lines in the preimage that falls beyond the
2506 * end of the file (if any). They will only match if they are
2507 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2510 for ( ; i
< preimage
->nr
; i
++) {
2511 size_t fixstart
= fixed
.len
; /* start of the fixed preimage */
2512 size_t oldlen
= preimage
->line
[i
].len
;
2515 /* Try fixing the line in the preimage */
2516 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2518 for (j
= fixstart
; j
< fixed
.len
; j
++)
2519 if (!isspace(fixed
.buf
[j
]))
2526 * Yes, the preimage is based on an older version that still
2527 * has whitespace breakages unfixed, and fixing them makes the
2528 * hunk match. Update the context lines in the postimage.
2530 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2531 if (postlen
< postimage
->len
)
2533 update_pre_post_images(preimage
, postimage
,
2534 fixed_buf
, fixed_len
, postlen
);
2538 strbuf_release(&fixed
);
2542 static int find_pos(struct image
*img
,
2543 struct image
*preimage
,
2544 struct image
*postimage
,
2547 int match_beginning
, int match_end
)
2550 unsigned long backwards
, forwards
, try;
2551 int backwards_lno
, forwards_lno
, try_lno
;
2554 * If match_beginning or match_end is specified, there is no
2555 * point starting from a wrong line that will never match and
2556 * wander around and wait for a match at the specified end.
2558 if (match_beginning
)
2561 line
= img
->nr
- preimage
->nr
;
2564 * Because the comparison is unsigned, the following test
2565 * will also take care of a negative line number that can
2566 * result when match_end and preimage is larger than the target.
2568 if ((size_t) line
> img
->nr
)
2572 for (i
= 0; i
< line
; i
++)
2573 try += img
->line
[i
].len
;
2576 * There's probably some smart way to do this, but I'll leave
2577 * that to the smart and beautiful people. I'm simple and stupid.
2580 backwards_lno
= line
;
2582 forwards_lno
= line
;
2585 for (i
= 0; ; i
++) {
2586 if (match_fragment(img
, preimage
, postimage
,
2587 try, try_lno
, ws_rule
,
2588 match_beginning
, match_end
))
2592 if (backwards_lno
== 0 && forwards_lno
== img
->nr
)
2596 if (backwards_lno
== 0) {
2601 backwards
-= img
->line
[backwards_lno
].len
;
2603 try_lno
= backwards_lno
;
2605 if (forwards_lno
== img
->nr
) {
2609 forwards
+= img
->line
[forwards_lno
].len
;
2612 try_lno
= forwards_lno
;
2619 static void remove_first_line(struct image
*img
)
2621 img
->buf
+= img
->line
[0].len
;
2622 img
->len
-= img
->line
[0].len
;
2627 static void remove_last_line(struct image
*img
)
2629 img
->len
-= img
->line
[--img
->nr
].len
;
2633 * The change from "preimage" and "postimage" has been found to
2634 * apply at applied_pos (counts in line numbers) in "img".
2635 * Update "img" to remove "preimage" and replace it with "postimage".
2637 static void update_image(struct apply_state
*state
,
2640 struct image
*preimage
,
2641 struct image
*postimage
)
2644 * remove the copy of preimage at offset in img
2645 * and replace it with postimage
2648 size_t remove_count
, insert_count
, applied_at
= 0;
2653 * If we are removing blank lines at the end of img,
2654 * the preimage may extend beyond the end.
2655 * If that is the case, we must be careful only to
2656 * remove the part of the preimage that falls within
2657 * the boundaries of img. Initialize preimage_limit
2658 * to the number of lines in the preimage that falls
2659 * within the boundaries.
2661 preimage_limit
= preimage
->nr
;
2662 if (preimage_limit
> img
->nr
- applied_pos
)
2663 preimage_limit
= img
->nr
- applied_pos
;
2665 for (i
= 0; i
< applied_pos
; i
++)
2666 applied_at
+= img
->line
[i
].len
;
2669 for (i
= 0; i
< preimage_limit
; i
++)
2670 remove_count
+= img
->line
[applied_pos
+ i
].len
;
2671 insert_count
= postimage
->len
;
2673 /* Adjust the contents */
2674 result
= xmalloc(st_add3(st_sub(img
->len
, remove_count
), insert_count
, 1));
2675 memcpy(result
, img
->buf
, applied_at
);
2676 memcpy(result
+ applied_at
, postimage
->buf
, postimage
->len
);
2677 memcpy(result
+ applied_at
+ postimage
->len
,
2678 img
->buf
+ (applied_at
+ remove_count
),
2679 img
->len
- (applied_at
+ remove_count
));
2682 img
->len
+= insert_count
- remove_count
;
2683 result
[img
->len
] = '\0';
2685 /* Adjust the line table */
2686 nr
= img
->nr
+ postimage
->nr
- preimage_limit
;
2687 if (preimage_limit
< postimage
->nr
) {
2689 * NOTE: this knows that we never call remove_first_line()
2690 * on anything other than pre/post image.
2692 REALLOC_ARRAY(img
->line
, nr
);
2693 img
->line_allocated
= img
->line
;
2695 if (preimage_limit
!= postimage
->nr
)
2696 memmove(img
->line
+ applied_pos
+ postimage
->nr
,
2697 img
->line
+ applied_pos
+ preimage_limit
,
2698 (img
->nr
- (applied_pos
+ preimage_limit
)) *
2699 sizeof(*img
->line
));
2700 memcpy(img
->line
+ applied_pos
,
2702 postimage
->nr
* sizeof(*img
->line
));
2703 if (!state
->allow_overlap
)
2704 for (i
= 0; i
< postimage
->nr
; i
++)
2705 img
->line
[applied_pos
+ i
].flag
|= LINE_PATCHED
;
2710 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2711 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2712 * replace the part of "img" with "postimage" text.
2714 static int apply_one_fragment(struct apply_state
*state
,
2715 struct image
*img
, struct fragment
*frag
,
2716 int inaccurate_eof
, unsigned ws_rule
,
2719 int match_beginning
, match_end
;
2720 const char *patch
= frag
->patch
;
2721 int size
= frag
->size
;
2722 char *old
, *oldlines
;
2723 struct strbuf newlines
;
2724 int new_blank_lines_at_end
= 0;
2725 int found_new_blank_lines_at_end
= 0;
2726 int hunk_linenr
= frag
->linenr
;
2727 unsigned long leading
, trailing
;
2728 int pos
, applied_pos
;
2729 struct image preimage
;
2730 struct image postimage
;
2732 memset(&preimage
, 0, sizeof(preimage
));
2733 memset(&postimage
, 0, sizeof(postimage
));
2734 oldlines
= xmalloc(size
);
2735 strbuf_init(&newlines
, size
);
2740 int len
= linelen(patch
, size
);
2742 int added_blank_line
= 0;
2743 int is_blank_context
= 0;
2750 * "plen" is how much of the line we should use for
2751 * the actual patch data. Normally we just remove the
2752 * first character on the line, but if the line is
2753 * followed by "\ No newline", then we also remove the
2754 * last one (which is the newline, of course).
2757 if (len
< size
&& patch
[len
] == '\\')
2760 if (state
->apply_in_reverse
) {
2763 else if (first
== '+')
2769 /* Newer GNU diff, empty context line */
2771 /* ... followed by '\No newline'; nothing */
2774 strbuf_addch(&newlines
, '\n');
2775 add_line_info(&preimage
, "\n", 1, LINE_COMMON
);
2776 add_line_info(&postimage
, "\n", 1, LINE_COMMON
);
2777 is_blank_context
= 1;
2780 if (plen
&& (ws_rule
& WS_BLANK_AT_EOF
) &&
2781 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2782 is_blank_context
= 1;
2784 memcpy(old
, patch
+ 1, plen
);
2785 add_line_info(&preimage
, old
, plen
,
2786 (first
== ' ' ? LINE_COMMON
: 0));
2790 /* Fall-through for ' ' */
2792 /* --no-add does not add new lines */
2793 if (first
== '+' && state
->no_add
)
2796 start
= newlines
.len
;
2798 !whitespace_error
||
2799 ws_error_action
!= correct_ws_error
) {
2800 strbuf_add(&newlines
, patch
+ 1, plen
);
2803 ws_fix_copy(&newlines
, patch
+ 1, plen
, ws_rule
, &applied_after_fixing_ws
);
2805 add_line_info(&postimage
, newlines
.buf
+ start
, newlines
.len
- start
,
2806 (first
== '+' ? 0 : LINE_COMMON
));
2808 (ws_rule
& WS_BLANK_AT_EOF
) &&
2809 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2810 added_blank_line
= 1;
2812 case '@': case '\\':
2813 /* Ignore it, we already handled it */
2816 if (state
->apply_verbosely
)
2817 error(_("invalid start of line: '%c'"), first
);
2821 if (added_blank_line
) {
2822 if (!new_blank_lines_at_end
)
2823 found_new_blank_lines_at_end
= hunk_linenr
;
2824 new_blank_lines_at_end
++;
2826 else if (is_blank_context
)
2829 new_blank_lines_at_end
= 0;
2834 if (inaccurate_eof
&&
2835 old
> oldlines
&& old
[-1] == '\n' &&
2836 newlines
.len
> 0 && newlines
.buf
[newlines
.len
- 1] == '\n') {
2838 strbuf_setlen(&newlines
, newlines
.len
- 1);
2841 leading
= frag
->leading
;
2842 trailing
= frag
->trailing
;
2845 * A hunk to change lines at the beginning would begin with
2847 * but we need to be careful. -U0 that inserts before the second
2848 * line also has this pattern.
2850 * And a hunk to add to an empty file would begin with
2853 * In other words, a hunk that is (frag->oldpos <= 1) with or
2854 * without leading context must match at the beginning.
2856 match_beginning
= (!frag
->oldpos
||
2857 (frag
->oldpos
== 1 && !state
->unidiff_zero
));
2860 * A hunk without trailing lines must match at the end.
2861 * However, we simply cannot tell if a hunk must match end
2862 * from the lack of trailing lines if the patch was generated
2863 * with unidiff without any context.
2865 match_end
= !state
->unidiff_zero
&& !trailing
;
2867 pos
= frag
->newpos
? (frag
->newpos
- 1) : 0;
2868 preimage
.buf
= oldlines
;
2869 preimage
.len
= old
- oldlines
;
2870 postimage
.buf
= newlines
.buf
;
2871 postimage
.len
= newlines
.len
;
2872 preimage
.line
= preimage
.line_allocated
;
2873 postimage
.line
= postimage
.line_allocated
;
2877 applied_pos
= find_pos(img
, &preimage
, &postimage
, pos
,
2878 ws_rule
, match_beginning
, match_end
);
2880 if (applied_pos
>= 0)
2883 /* Am I at my context limits? */
2884 if ((leading
<= state
->p_context
) && (trailing
<= state
->p_context
))
2886 if (match_beginning
|| match_end
) {
2887 match_beginning
= match_end
= 0;
2892 * Reduce the number of context lines; reduce both
2893 * leading and trailing if they are equal otherwise
2894 * just reduce the larger context.
2896 if (leading
>= trailing
) {
2897 remove_first_line(&preimage
);
2898 remove_first_line(&postimage
);
2902 if (trailing
> leading
) {
2903 remove_last_line(&preimage
);
2904 remove_last_line(&postimage
);
2909 if (applied_pos
>= 0) {
2910 if (new_blank_lines_at_end
&&
2911 preimage
.nr
+ applied_pos
>= img
->nr
&&
2912 (ws_rule
& WS_BLANK_AT_EOF
) &&
2913 ws_error_action
!= nowarn_ws_error
) {
2914 record_ws_error(state
, WS_BLANK_AT_EOF
, "+", 1,
2915 found_new_blank_lines_at_end
);
2916 if (ws_error_action
== correct_ws_error
) {
2917 while (new_blank_lines_at_end
--)
2918 remove_last_line(&postimage
);
2921 * We would want to prevent write_out_results()
2922 * from taking place in apply_patch() that follows
2923 * the callchain led us here, which is:
2924 * apply_patch->check_patch_list->check_patch->
2925 * apply_data->apply_fragments->apply_one_fragment
2927 if (ws_error_action
== die_on_ws_error
)
2931 if (state
->apply_verbosely
&& applied_pos
!= pos
) {
2932 int offset
= applied_pos
- pos
;
2933 if (state
->apply_in_reverse
)
2934 offset
= 0 - offset
;
2936 Q_("Hunk #%d succeeded at %d (offset %d line).",
2937 "Hunk #%d succeeded at %d (offset %d lines).",
2939 nth_fragment
, applied_pos
+ 1, offset
);
2943 * Warn if it was necessary to reduce the number
2946 if ((leading
!= frag
->leading
) ||
2947 (trailing
!= frag
->trailing
))
2948 fprintf_ln(stderr
, _("Context reduced to (%ld/%ld)"
2949 " to apply fragment at %d"),
2950 leading
, trailing
, applied_pos
+1);
2951 update_image(state
, img
, applied_pos
, &preimage
, &postimage
);
2953 if (state
->apply_verbosely
)
2954 error(_("while searching for:\n%.*s"),
2955 (int)(old
- oldlines
), oldlines
);
2960 strbuf_release(&newlines
);
2961 free(preimage
.line_allocated
);
2962 free(postimage
.line_allocated
);
2964 return (applied_pos
< 0);
2967 static int apply_binary_fragment(struct apply_state
*state
,
2969 struct patch
*patch
)
2971 struct fragment
*fragment
= patch
->fragments
;
2976 return error(_("missing binary patch data for '%s'"),
2981 /* Binary patch is irreversible without the optional second hunk */
2982 if (state
->apply_in_reverse
) {
2983 if (!fragment
->next
)
2984 return error("cannot reverse-apply a binary patch "
2985 "without the reverse hunk to '%s'",
2987 ? patch
->new_name
: patch
->old_name
);
2988 fragment
= fragment
->next
;
2990 switch (fragment
->binary_patch_method
) {
2991 case BINARY_DELTA_DEFLATED
:
2992 dst
= patch_delta(img
->buf
, img
->len
, fragment
->patch
,
2993 fragment
->size
, &len
);
3000 case BINARY_LITERAL_DEFLATED
:
3002 img
->len
= fragment
->size
;
3003 img
->buf
= xmemdupz(fragment
->patch
, img
->len
);
3010 * Replace "img" with the result of applying the binary patch.
3011 * The binary patch data itself in patch->fragment is still kept
3012 * but the preimage prepared by the caller in "img" is freed here
3013 * or in the helper function apply_binary_fragment() this calls.
3015 static int apply_binary(struct apply_state
*state
,
3017 struct patch
*patch
)
3019 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3020 unsigned char sha1
[20];
3023 * For safety, we require patch index line to contain
3024 * full 40-byte textual SHA1 for old and new, at least for now.
3026 if (strlen(patch
->old_sha1_prefix
) != 40 ||
3027 strlen(patch
->new_sha1_prefix
) != 40 ||
3028 get_sha1_hex(patch
->old_sha1_prefix
, sha1
) ||
3029 get_sha1_hex(patch
->new_sha1_prefix
, sha1
))
3030 return error("cannot apply binary patch to '%s' "
3031 "without full index line", name
);
3033 if (patch
->old_name
) {
3035 * See if the old one matches what the patch
3038 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
3039 if (strcmp(sha1_to_hex(sha1
), patch
->old_sha1_prefix
))
3040 return error("the patch applies to '%s' (%s), "
3041 "which does not match the "
3042 "current contents.",
3043 name
, sha1_to_hex(sha1
));
3046 /* Otherwise, the old one must be empty. */
3048 return error("the patch applies to an empty "
3049 "'%s' but it is not empty", name
);
3052 get_sha1_hex(patch
->new_sha1_prefix
, sha1
);
3053 if (is_null_sha1(sha1
)) {
3055 return 0; /* deletion patch */
3058 if (has_sha1_file(sha1
)) {
3059 /* We already have the postimage */
3060 enum object_type type
;
3064 result
= read_sha1_file(sha1
, &type
, &size
);
3066 return error("the necessary postimage %s for "
3067 "'%s' cannot be read",
3068 patch
->new_sha1_prefix
, name
);
3074 * We have verified buf matches the preimage;
3075 * apply the patch data to it, which is stored
3076 * in the patch->fragments->{patch,size}.
3078 if (apply_binary_fragment(state
, img
, patch
))
3079 return error(_("binary patch does not apply to '%s'"),
3082 /* verify that the result matches */
3083 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
3084 if (strcmp(sha1_to_hex(sha1
), patch
->new_sha1_prefix
))
3085 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3086 name
, patch
->new_sha1_prefix
, sha1_to_hex(sha1
));
3092 static int apply_fragments(struct apply_state
*state
, struct image
*img
, struct patch
*patch
)
3094 struct fragment
*frag
= patch
->fragments
;
3095 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3096 unsigned ws_rule
= patch
->ws_rule
;
3097 unsigned inaccurate_eof
= patch
->inaccurate_eof
;
3100 if (patch
->is_binary
)
3101 return apply_binary(state
, img
, patch
);
3105 if (apply_one_fragment(state
, img
, frag
, inaccurate_eof
, ws_rule
, nth
)) {
3106 error(_("patch failed: %s:%ld"), name
, frag
->oldpos
);
3107 if (!state
->apply_with_reject
)
3116 static int read_blob_object(struct strbuf
*buf
, const unsigned char *sha1
, unsigned mode
)
3118 if (S_ISGITLINK(mode
)) {
3119 strbuf_grow(buf
, 100);
3120 strbuf_addf(buf
, "Subproject commit %s\n", sha1_to_hex(sha1
));
3122 enum object_type type
;
3126 result
= read_sha1_file(sha1
, &type
, &sz
);
3129 /* XXX read_sha1_file NUL-terminates */
3130 strbuf_attach(buf
, result
, sz
, sz
+ 1);
3135 static int read_file_or_gitlink(const struct cache_entry
*ce
, struct strbuf
*buf
)
3139 return read_blob_object(buf
, ce
->sha1
, ce
->ce_mode
);
3142 static struct patch
*in_fn_table(const char *name
)
3144 struct string_list_item
*item
;
3149 item
= string_list_lookup(&fn_table
, name
);
3151 return (struct patch
*)item
->util
;
3157 * item->util in the filename table records the status of the path.
3158 * Usually it points at a patch (whose result records the contents
3159 * of it after applying it), but it could be PATH_WAS_DELETED for a
3160 * path that a previously applied patch has already removed, or
3161 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3163 * The latter is needed to deal with a case where two paths A and B
3164 * are swapped by first renaming A to B and then renaming B to A;
3165 * moving A to B should not be prevented due to presence of B as we
3166 * will remove it in a later patch.
3168 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3169 #define PATH_WAS_DELETED ((struct patch *) -1)
3171 static int to_be_deleted(struct patch
*patch
)
3173 return patch
== PATH_TO_BE_DELETED
;
3176 static int was_deleted(struct patch
*patch
)
3178 return patch
== PATH_WAS_DELETED
;
3181 static void add_to_fn_table(struct patch
*patch
)
3183 struct string_list_item
*item
;
3186 * Always add new_name unless patch is a deletion
3187 * This should cover the cases for normal diffs,
3188 * file creations and copies
3190 if (patch
->new_name
!= NULL
) {
3191 item
= string_list_insert(&fn_table
, patch
->new_name
);
3196 * store a failure on rename/deletion cases because
3197 * later chunks shouldn't patch old names
3199 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3200 item
= string_list_insert(&fn_table
, patch
->old_name
);
3201 item
->util
= PATH_WAS_DELETED
;
3205 static void prepare_fn_table(struct patch
*patch
)
3208 * store information about incoming file deletion
3211 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3212 struct string_list_item
*item
;
3213 item
= string_list_insert(&fn_table
, patch
->old_name
);
3214 item
->util
= PATH_TO_BE_DELETED
;
3216 patch
= patch
->next
;
3220 static int checkout_target(struct index_state
*istate
,
3221 struct cache_entry
*ce
, struct stat
*st
)
3223 struct checkout costate
;
3225 memset(&costate
, 0, sizeof(costate
));
3226 costate
.base_dir
= "";
3227 costate
.refresh_cache
= 1;
3228 costate
.istate
= istate
;
3229 if (checkout_entry(ce
, &costate
, NULL
) || lstat(ce
->name
, st
))
3230 return error(_("cannot checkout %s"), ce
->name
);
3234 static struct patch
*previous_patch(struct patch
*patch
, int *gone
)
3236 struct patch
*previous
;
3239 if (patch
->is_copy
|| patch
->is_rename
)
3240 return NULL
; /* "git" patches do not depend on the order */
3242 previous
= in_fn_table(patch
->old_name
);
3246 if (to_be_deleted(previous
))
3247 return NULL
; /* the deletion hasn't happened yet */
3249 if (was_deleted(previous
))
3255 static int verify_index_match(const struct cache_entry
*ce
, struct stat
*st
)
3257 if (S_ISGITLINK(ce
->ce_mode
)) {
3258 if (!S_ISDIR(st
->st_mode
))
3262 return ce_match_stat(ce
, st
, CE_MATCH_IGNORE_VALID
|CE_MATCH_IGNORE_SKIP_WORKTREE
);
3265 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3267 static int load_patch_target(struct apply_state
*state
,
3269 const struct cache_entry
*ce
,
3272 unsigned expected_mode
)
3274 if (state
->cached
|| state
->check_index
) {
3275 if (read_file_or_gitlink(ce
, buf
))
3276 return error(_("read of %s failed"), name
);
3278 if (S_ISGITLINK(expected_mode
)) {
3280 return read_file_or_gitlink(ce
, buf
);
3282 return SUBMODULE_PATCH_WITHOUT_INDEX
;
3283 } else if (has_symlink_leading_path(name
, strlen(name
))) {
3284 return error(_("reading from '%s' beyond a symbolic link"), name
);
3286 if (read_old_data(st
, name
, buf
))
3287 return error(_("read of %s failed"), name
);
3294 * We are about to apply "patch"; populate the "image" with the
3295 * current version we have, from the working tree or from the index,
3296 * depending on the situation e.g. --cached/--index. If we are
3297 * applying a non-git patch that incrementally updates the tree,
3298 * we read from the result of a previous diff.
3300 static int load_preimage(struct apply_state
*state
,
3301 struct image
*image
,
3302 struct patch
*patch
, struct stat
*st
,
3303 const struct cache_entry
*ce
)
3305 struct strbuf buf
= STRBUF_INIT
;
3308 struct patch
*previous
;
3311 previous
= previous_patch(patch
, &status
);
3313 return error(_("path %s has been renamed/deleted"),
3316 /* We have a patched copy in memory; use that. */
3317 strbuf_add(&buf
, previous
->result
, previous
->resultsize
);
3319 status
= load_patch_target(state
, &buf
, ce
, st
,
3320 patch
->old_name
, patch
->old_mode
);
3323 else if (status
== SUBMODULE_PATCH_WITHOUT_INDEX
) {
3325 * There is no way to apply subproject
3326 * patch without looking at the index.
3327 * NEEDSWORK: shouldn't this be flagged
3330 free_fragment_list(patch
->fragments
);
3331 patch
->fragments
= NULL
;
3332 } else if (status
) {
3333 return error(_("read of %s failed"), patch
->old_name
);
3337 img
= strbuf_detach(&buf
, &len
);
3338 prepare_image(image
, img
, len
, !patch
->is_binary
);
3342 static int three_way_merge(struct image
*image
,
3344 const unsigned char *base
,
3345 const unsigned char *ours
,
3346 const unsigned char *theirs
)
3348 mmfile_t base_file
, our_file
, their_file
;
3349 mmbuffer_t result
= { NULL
};
3352 read_mmblob(&base_file
, base
);
3353 read_mmblob(&our_file
, ours
);
3354 read_mmblob(&their_file
, theirs
);
3355 status
= ll_merge(&result
, path
,
3358 &their_file
, "theirs", NULL
);
3359 free(base_file
.ptr
);
3361 free(their_file
.ptr
);
3362 if (status
< 0 || !result
.ptr
) {
3367 image
->buf
= result
.ptr
;
3368 image
->len
= result
.size
;
3374 * When directly falling back to add/add three-way merge, we read from
3375 * the current contents of the new_name. In no cases other than that
3376 * this function will be called.
3378 static int load_current(struct apply_state
*state
,
3379 struct image
*image
,
3380 struct patch
*patch
)
3382 struct strbuf buf
= STRBUF_INIT
;
3387 struct cache_entry
*ce
;
3388 char *name
= patch
->new_name
;
3389 unsigned mode
= patch
->new_mode
;
3392 die("BUG: patch to %s is not a creation", patch
->old_name
);
3394 pos
= cache_name_pos(name
, strlen(name
));
3396 return error(_("%s: does not exist in index"), name
);
3397 ce
= active_cache
[pos
];
3398 if (lstat(name
, &st
)) {
3399 if (errno
!= ENOENT
)
3400 return error(_("%s: %s"), name
, strerror(errno
));
3401 if (checkout_target(&the_index
, ce
, &st
))
3404 if (verify_index_match(ce
, &st
))
3405 return error(_("%s: does not match index"), name
);
3407 status
= load_patch_target(state
, &buf
, ce
, &st
, name
, mode
);
3412 img
= strbuf_detach(&buf
, &len
);
3413 prepare_image(image
, img
, len
, !patch
->is_binary
);
3417 static int try_threeway(struct apply_state
*state
,
3418 struct image
*image
,
3419 struct patch
*patch
,
3421 const struct cache_entry
*ce
)
3423 unsigned char pre_sha1
[20], post_sha1
[20], our_sha1
[20];
3424 struct strbuf buf
= STRBUF_INIT
;
3428 struct image tmp_image
;
3430 /* No point falling back to 3-way merge in these cases */
3431 if (patch
->is_delete
||
3432 S_ISGITLINK(patch
->old_mode
) || S_ISGITLINK(patch
->new_mode
))
3435 /* Preimage the patch was prepared for */
3437 write_sha1_file("", 0, blob_type
, pre_sha1
);
3438 else if (get_sha1(patch
->old_sha1_prefix
, pre_sha1
) ||
3439 read_blob_object(&buf
, pre_sha1
, patch
->old_mode
))
3440 return error("repository lacks the necessary blob to fall back on 3-way merge.");
3442 fprintf(stderr
, "Falling back to three-way merge...\n");
3444 img
= strbuf_detach(&buf
, &len
);
3445 prepare_image(&tmp_image
, img
, len
, 1);
3446 /* Apply the patch to get the post image */
3447 if (apply_fragments(state
, &tmp_image
, patch
) < 0) {
3448 clear_image(&tmp_image
);
3451 /* post_sha1[] is theirs */
3452 write_sha1_file(tmp_image
.buf
, tmp_image
.len
, blob_type
, post_sha1
);
3453 clear_image(&tmp_image
);
3455 /* our_sha1[] is ours */
3456 if (patch
->is_new
) {
3457 if (load_current(state
, &tmp_image
, patch
))
3458 return error("cannot read the current contents of '%s'",
3461 if (load_preimage(state
, &tmp_image
, patch
, st
, ce
))
3462 return error("cannot read the current contents of '%s'",
3465 write_sha1_file(tmp_image
.buf
, tmp_image
.len
, blob_type
, our_sha1
);
3466 clear_image(&tmp_image
);
3468 /* in-core three-way merge between post and our using pre as base */
3469 status
= three_way_merge(image
, patch
->new_name
,
3470 pre_sha1
, our_sha1
, post_sha1
);
3472 fprintf(stderr
, "Failed to fall back on three-way merge...\n");
3477 patch
->conflicted_threeway
= 1;
3479 oidclr(&patch
->threeway_stage
[0]);
3481 hashcpy(patch
->threeway_stage
[0].hash
, pre_sha1
);
3482 hashcpy(patch
->threeway_stage
[1].hash
, our_sha1
);
3483 hashcpy(patch
->threeway_stage
[2].hash
, post_sha1
);
3484 fprintf(stderr
, "Applied patch to '%s' with conflicts.\n", patch
->new_name
);
3486 fprintf(stderr
, "Applied patch to '%s' cleanly.\n", patch
->new_name
);
3491 static int apply_data(struct apply_state
*state
, struct patch
*patch
,
3492 struct stat
*st
, const struct cache_entry
*ce
)
3496 if (load_preimage(state
, &image
, patch
, st
, ce
) < 0)
3499 if (patch
->direct_to_threeway
||
3500 apply_fragments(state
, &image
, patch
) < 0) {
3501 /* Note: with --reject, apply_fragments() returns 0 */
3502 if (!state
->threeway
|| try_threeway(state
, &image
, patch
, st
, ce
) < 0)
3505 patch
->result
= image
.buf
;
3506 patch
->resultsize
= image
.len
;
3507 add_to_fn_table(patch
);
3508 free(image
.line_allocated
);
3510 if (0 < patch
->is_delete
&& patch
->resultsize
)
3511 return error(_("removal patch leaves file contents"));
3517 * If "patch" that we are looking at modifies or deletes what we have,
3518 * we would want it not to lose any local modification we have, either
3519 * in the working tree or in the index.
3521 * This also decides if a non-git patch is a creation patch or a
3522 * modification to an existing empty file. We do not check the state
3523 * of the current tree for a creation patch in this function; the caller
3524 * check_patch() separately makes sure (and errors out otherwise) that
3525 * the path the patch creates does not exist in the current tree.
3527 static int check_preimage(struct apply_state
*state
,
3528 struct patch
*patch
,
3529 struct cache_entry
**ce
,
3532 const char *old_name
= patch
->old_name
;
3533 struct patch
*previous
= NULL
;
3534 int stat_ret
= 0, status
;
3535 unsigned st_mode
= 0;
3540 assert(patch
->is_new
<= 0);
3541 previous
= previous_patch(patch
, &status
);
3544 return error(_("path %s has been renamed/deleted"), old_name
);
3546 st_mode
= previous
->new_mode
;
3547 } else if (!state
->cached
) {
3548 stat_ret
= lstat(old_name
, st
);
3549 if (stat_ret
&& errno
!= ENOENT
)
3550 return error(_("%s: %s"), old_name
, strerror(errno
));
3553 if (state
->check_index
&& !previous
) {
3554 int pos
= cache_name_pos(old_name
, strlen(old_name
));
3556 if (patch
->is_new
< 0)
3558 return error(_("%s: does not exist in index"), old_name
);
3560 *ce
= active_cache
[pos
];
3562 if (checkout_target(&the_index
, *ce
, st
))
3565 if (!state
->cached
&& verify_index_match(*ce
, st
))
3566 return error(_("%s: does not match index"), old_name
);
3568 st_mode
= (*ce
)->ce_mode
;
3569 } else if (stat_ret
< 0) {
3570 if (patch
->is_new
< 0)
3572 return error(_("%s: %s"), old_name
, strerror(errno
));
3575 if (!state
->cached
&& !previous
)
3576 st_mode
= ce_mode_from_stat(*ce
, st
->st_mode
);
3578 if (patch
->is_new
< 0)
3580 if (!patch
->old_mode
)
3581 patch
->old_mode
= st_mode
;
3582 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
3583 return error(_("%s: wrong type"), old_name
);
3584 if (st_mode
!= patch
->old_mode
)
3585 warning(_("%s has type %o, expected %o"),
3586 old_name
, st_mode
, patch
->old_mode
);
3587 if (!patch
->new_mode
&& !patch
->is_delete
)
3588 patch
->new_mode
= st_mode
;
3593 patch
->is_delete
= 0;
3594 free(patch
->old_name
);
3595 patch
->old_name
= NULL
;
3600 #define EXISTS_IN_INDEX 1
3601 #define EXISTS_IN_WORKTREE 2
3603 static int check_to_create(struct apply_state
*state
,
3604 const char *new_name
,
3609 if (state
->check_index
&&
3610 cache_name_pos(new_name
, strlen(new_name
)) >= 0 &&
3612 return EXISTS_IN_INDEX
;
3616 if (!lstat(new_name
, &nst
)) {
3617 if (S_ISDIR(nst
.st_mode
) || ok_if_exists
)
3620 * A leading component of new_name might be a symlink
3621 * that is going to be removed with this patch, but
3622 * still pointing at somewhere that has the path.
3623 * In such a case, path "new_name" does not exist as
3624 * far as git is concerned.
3626 if (has_symlink_leading_path(new_name
, strlen(new_name
)))
3629 return EXISTS_IN_WORKTREE
;
3630 } else if ((errno
!= ENOENT
) && (errno
!= ENOTDIR
)) {
3631 return error("%s: %s", new_name
, strerror(errno
));
3637 * We need to keep track of how symlinks in the preimage are
3638 * manipulated by the patches. A patch to add a/b/c where a/b
3639 * is a symlink should not be allowed to affect the directory
3640 * the symlink points at, but if the same patch removes a/b,
3641 * it is perfectly fine, as the patch removes a/b to make room
3642 * to create a directory a/b so that a/b/c can be created.
3644 static struct string_list symlink_changes
;
3645 #define SYMLINK_GOES_AWAY 01
3646 #define SYMLINK_IN_RESULT 02
3648 static uintptr_t register_symlink_changes(const char *path
, uintptr_t what
)
3650 struct string_list_item
*ent
;
3652 ent
= string_list_lookup(&symlink_changes
, path
);
3654 ent
= string_list_insert(&symlink_changes
, path
);
3655 ent
->util
= (void *)0;
3657 ent
->util
= (void *)(what
| ((uintptr_t)ent
->util
));
3658 return (uintptr_t)ent
->util
;
3661 static uintptr_t check_symlink_changes(const char *path
)
3663 struct string_list_item
*ent
;
3665 ent
= string_list_lookup(&symlink_changes
, path
);
3668 return (uintptr_t)ent
->util
;
3671 static void prepare_symlink_changes(struct patch
*patch
)
3673 for ( ; patch
; patch
= patch
->next
) {
3674 if ((patch
->old_name
&& S_ISLNK(patch
->old_mode
)) &&
3675 (patch
->is_rename
|| patch
->is_delete
))
3676 /* the symlink at patch->old_name is removed */
3677 register_symlink_changes(patch
->old_name
, SYMLINK_GOES_AWAY
);
3679 if (patch
->new_name
&& S_ISLNK(patch
->new_mode
))
3680 /* the symlink at patch->new_name is created or remains */
3681 register_symlink_changes(patch
->new_name
, SYMLINK_IN_RESULT
);
3685 static int path_is_beyond_symlink_1(struct apply_state
*state
, struct strbuf
*name
)
3688 unsigned int change
;
3690 while (--name
->len
&& name
->buf
[name
->len
] != '/')
3691 ; /* scan backwards */
3694 name
->buf
[name
->len
] = '\0';
3695 change
= check_symlink_changes(name
->buf
);
3696 if (change
& SYMLINK_IN_RESULT
)
3698 if (change
& SYMLINK_GOES_AWAY
)
3700 * This cannot be "return 0", because we may
3701 * see a new one created at a higher level.
3705 /* otherwise, check the preimage */
3706 if (state
->check_index
) {
3707 struct cache_entry
*ce
;
3709 ce
= cache_file_exists(name
->buf
, name
->len
, ignore_case
);
3710 if (ce
&& S_ISLNK(ce
->ce_mode
))
3714 if (!lstat(name
->buf
, &st
) && S_ISLNK(st
.st_mode
))
3721 static int path_is_beyond_symlink(struct apply_state
*state
, const char *name_
)
3724 struct strbuf name
= STRBUF_INIT
;
3726 assert(*name_
!= '\0');
3727 strbuf_addstr(&name
, name_
);
3728 ret
= path_is_beyond_symlink_1(state
, &name
);
3729 strbuf_release(&name
);
3734 static void die_on_unsafe_path(struct patch
*patch
)
3736 const char *old_name
= NULL
;
3737 const char *new_name
= NULL
;
3738 if (patch
->is_delete
)
3739 old_name
= patch
->old_name
;
3740 else if (!patch
->is_new
&& !patch
->is_copy
)
3741 old_name
= patch
->old_name
;
3742 if (!patch
->is_delete
)
3743 new_name
= patch
->new_name
;
3745 if (old_name
&& !verify_path(old_name
))
3746 die(_("invalid path '%s'"), old_name
);
3747 if (new_name
&& !verify_path(new_name
))
3748 die(_("invalid path '%s'"), new_name
);
3752 * Check and apply the patch in-core; leave the result in patch->result
3753 * for the caller to write it out to the final destination.
3755 static int check_patch(struct apply_state
*state
, struct patch
*patch
)
3758 const char *old_name
= patch
->old_name
;
3759 const char *new_name
= patch
->new_name
;
3760 const char *name
= old_name
? old_name
: new_name
;
3761 struct cache_entry
*ce
= NULL
;
3762 struct patch
*tpatch
;
3766 patch
->rejected
= 1; /* we will drop this after we succeed */
3768 status
= check_preimage(state
, patch
, &ce
, &st
);
3771 old_name
= patch
->old_name
;
3774 * A type-change diff is always split into a patch to delete
3775 * old, immediately followed by a patch to create new (see
3776 * diff.c::run_diff()); in such a case it is Ok that the entry
3777 * to be deleted by the previous patch is still in the working
3778 * tree and in the index.
3780 * A patch to swap-rename between A and B would first rename A
3781 * to B and then rename B to A. While applying the first one,
3782 * the presence of B should not stop A from getting renamed to
3783 * B; ask to_be_deleted() about the later rename. Removal of
3784 * B and rename from A to B is handled the same way by asking
3787 if ((tpatch
= in_fn_table(new_name
)) &&
3788 (was_deleted(tpatch
) || to_be_deleted(tpatch
)))
3794 ((0 < patch
->is_new
) || patch
->is_rename
|| patch
->is_copy
)) {
3795 int err
= check_to_create(state
, new_name
, ok_if_exists
);
3797 if (err
&& state
->threeway
) {
3798 patch
->direct_to_threeway
= 1;
3799 } else switch (err
) {
3802 case EXISTS_IN_INDEX
:
3803 return error(_("%s: already exists in index"), new_name
);
3805 case EXISTS_IN_WORKTREE
:
3806 return error(_("%s: already exists in working directory"),
3812 if (!patch
->new_mode
) {
3813 if (0 < patch
->is_new
)
3814 patch
->new_mode
= S_IFREG
| 0644;
3816 patch
->new_mode
= patch
->old_mode
;
3820 if (new_name
&& old_name
) {
3821 int same
= !strcmp(old_name
, new_name
);
3822 if (!patch
->new_mode
)
3823 patch
->new_mode
= patch
->old_mode
;
3824 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
) {
3826 return error(_("new mode (%o) of %s does not "
3827 "match old mode (%o)"),
3828 patch
->new_mode
, new_name
,
3831 return error(_("new mode (%o) of %s does not "
3832 "match old mode (%o) of %s"),
3833 patch
->new_mode
, new_name
,
3834 patch
->old_mode
, old_name
);
3838 if (!state
->unsafe_paths
)
3839 die_on_unsafe_path(patch
);
3842 * An attempt to read from or delete a path that is beyond a
3843 * symbolic link will be prevented by load_patch_target() that
3844 * is called at the beginning of apply_data() so we do not
3845 * have to worry about a patch marked with "is_delete" bit
3846 * here. We however need to make sure that the patch result
3847 * is not deposited to a path that is beyond a symbolic link
3850 if (!patch
->is_delete
&& path_is_beyond_symlink(state
, patch
->new_name
))
3851 return error(_("affected file '%s' is beyond a symbolic link"),
3854 if (apply_data(state
, patch
, &st
, ce
) < 0)
3855 return error(_("%s: patch does not apply"), name
);
3856 patch
->rejected
= 0;
3860 static int check_patch_list(struct apply_state
*state
, struct patch
*patch
)
3864 prepare_symlink_changes(patch
);
3865 prepare_fn_table(patch
);
3867 if (state
->apply_verbosely
)
3868 say_patch_name(stderr
,
3869 _("Checking patch %s..."), patch
);
3870 err
|= check_patch(state
, patch
);
3871 patch
= patch
->next
;
3876 /* This function tries to read the sha1 from the current index */
3877 static int get_current_sha1(const char *path
, unsigned char *sha1
)
3881 if (read_cache() < 0)
3883 pos
= cache_name_pos(path
, strlen(path
));
3886 hashcpy(sha1
, active_cache
[pos
]->sha1
);
3890 static int preimage_sha1_in_gitlink_patch(struct patch
*p
, unsigned char sha1
[20])
3893 * A usable gitlink patch has only one fragment (hunk) that looks like:
3895 * -Subproject commit <old sha1>
3896 * +Subproject commit <new sha1>
3899 * -Subproject commit <old sha1>
3900 * for a removal patch.
3902 struct fragment
*hunk
= p
->fragments
;
3903 static const char heading
[] = "-Subproject commit ";
3906 if (/* does the patch have only one hunk? */
3907 hunk
&& !hunk
->next
&&
3908 /* is its preimage one line? */
3909 hunk
->oldpos
== 1 && hunk
->oldlines
== 1 &&
3910 /* does preimage begin with the heading? */
3911 (preimage
= memchr(hunk
->patch
, '\n', hunk
->size
)) != NULL
&&
3912 starts_with(++preimage
, heading
) &&
3913 /* does it record full SHA-1? */
3914 !get_sha1_hex(preimage
+ sizeof(heading
) - 1, sha1
) &&
3915 preimage
[sizeof(heading
) + 40 - 1] == '\n' &&
3916 /* does the abbreviated name on the index line agree with it? */
3917 starts_with(preimage
+ sizeof(heading
) - 1, p
->old_sha1_prefix
))
3918 return 0; /* it all looks fine */
3920 /* we may have full object name on the index line */
3921 return get_sha1_hex(p
->old_sha1_prefix
, sha1
);
3924 /* Build an index that contains the just the files needed for a 3way merge */
3925 static void build_fake_ancestor(struct patch
*list
, const char *filename
)
3927 struct patch
*patch
;
3928 struct index_state result
= { NULL
};
3929 static struct lock_file lock
;
3931 /* Once we start supporting the reverse patch, it may be
3932 * worth showing the new sha1 prefix, but until then...
3934 for (patch
= list
; patch
; patch
= patch
->next
) {
3935 unsigned char sha1
[20];
3936 struct cache_entry
*ce
;
3939 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3940 if (0 < patch
->is_new
)
3943 if (S_ISGITLINK(patch
->old_mode
)) {
3944 if (!preimage_sha1_in_gitlink_patch(patch
, sha1
))
3945 ; /* ok, the textual part looks sane */
3947 die("sha1 information is lacking or useless for submodule %s",
3949 } else if (!get_sha1_blob(patch
->old_sha1_prefix
, sha1
)) {
3951 } else if (!patch
->lines_added
&& !patch
->lines_deleted
) {
3952 /* mode-only change: update the current */
3953 if (get_current_sha1(patch
->old_name
, sha1
))
3954 die("mode change for %s, which is not "
3955 "in current HEAD", name
);
3957 die("sha1 information is lacking or useless "
3960 ce
= make_cache_entry(patch
->old_mode
, sha1
, name
, 0, 0);
3962 die(_("make_cache_entry failed for path '%s'"), name
);
3963 if (add_index_entry(&result
, ce
, ADD_CACHE_OK_TO_ADD
))
3964 die ("Could not add %s to temporary index", name
);
3967 hold_lock_file_for_update(&lock
, filename
, LOCK_DIE_ON_ERROR
);
3968 if (write_locked_index(&result
, &lock
, COMMIT_LOCK
))
3969 die ("Could not write temporary index to %s", filename
);
3971 discard_index(&result
);
3974 static void stat_patch_list(struct patch
*patch
)
3976 int files
, adds
, dels
;
3978 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
3980 adds
+= patch
->lines_added
;
3981 dels
+= patch
->lines_deleted
;
3985 print_stat_summary(stdout
, files
, adds
, dels
);
3988 static void numstat_patch_list(struct apply_state
*state
,
3989 struct patch
*patch
)
3991 for ( ; patch
; patch
= patch
->next
) {
3993 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
3994 if (patch
->is_binary
)
3997 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
3998 write_name_quoted(name
, stdout
, state
->line_termination
);
4002 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
4005 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
4007 printf(" %s %s\n", newdelete
, name
);
4010 static void show_mode_change(struct patch
*p
, int show_name
)
4012 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
4014 printf(" mode change %06o => %06o %s\n",
4015 p
->old_mode
, p
->new_mode
, p
->new_name
);
4017 printf(" mode change %06o => %06o\n",
4018 p
->old_mode
, p
->new_mode
);
4022 static void show_rename_copy(struct patch
*p
)
4024 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
4025 const char *old
, *new;
4027 /* Find common prefix */
4031 const char *slash_old
, *slash_new
;
4032 slash_old
= strchr(old
, '/');
4033 slash_new
= strchr(new, '/');
4036 slash_old
- old
!= slash_new
- new ||
4037 memcmp(old
, new, slash_new
- new))
4039 old
= slash_old
+ 1;
4040 new = slash_new
+ 1;
4042 /* p->old_name thru old is the common prefix, and old and new
4043 * through the end of names are renames
4045 if (old
!= p
->old_name
)
4046 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
4047 (int)(old
- p
->old_name
), p
->old_name
,
4048 old
, new, p
->score
);
4050 printf(" %s %s => %s (%d%%)\n", renamecopy
,
4051 p
->old_name
, p
->new_name
, p
->score
);
4052 show_mode_change(p
, 0);
4055 static void summary_patch_list(struct patch
*patch
)
4059 for (p
= patch
; p
; p
= p
->next
) {
4061 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
4062 else if (p
->is_delete
)
4063 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
4065 if (p
->is_rename
|| p
->is_copy
)
4066 show_rename_copy(p
);
4069 printf(" rewrite %s (%d%%)\n",
4070 p
->new_name
, p
->score
);
4071 show_mode_change(p
, 0);
4074 show_mode_change(p
, 1);
4080 static void patch_stats(struct patch
*patch
)
4082 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
4084 if (lines
> max_change
)
4086 if (patch
->old_name
) {
4087 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
4089 len
= strlen(patch
->old_name
);
4093 if (patch
->new_name
) {
4094 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
4096 len
= strlen(patch
->new_name
);
4102 static void remove_file(struct apply_state
*state
, struct patch
*patch
, int rmdir_empty
)
4104 if (state
->update_index
) {
4105 if (remove_file_from_cache(patch
->old_name
) < 0)
4106 die(_("unable to remove %s from index"), patch
->old_name
);
4108 if (!state
->cached
) {
4109 if (!remove_or_warn(patch
->old_mode
, patch
->old_name
) && rmdir_empty
) {
4110 remove_path(patch
->old_name
);
4115 static void add_index_file(struct apply_state
*state
,
4122 struct cache_entry
*ce
;
4123 int namelen
= strlen(path
);
4124 unsigned ce_size
= cache_entry_size(namelen
);
4126 if (!state
->update_index
)
4129 ce
= xcalloc(1, ce_size
);
4130 memcpy(ce
->name
, path
, namelen
);
4131 ce
->ce_mode
= create_ce_mode(mode
);
4132 ce
->ce_flags
= create_ce_flags(0);
4133 ce
->ce_namelen
= namelen
;
4134 if (S_ISGITLINK(mode
)) {
4137 if (!skip_prefix(buf
, "Subproject commit ", &s
) ||
4138 get_sha1_hex(s
, ce
->sha1
))
4139 die(_("corrupt patch for submodule %s"), path
);
4141 if (!state
->cached
) {
4142 if (lstat(path
, &st
) < 0)
4143 die_errno(_("unable to stat newly created file '%s'"),
4145 fill_stat_cache_info(ce
, &st
);
4147 if (write_sha1_file(buf
, size
, blob_type
, ce
->sha1
) < 0)
4148 die(_("unable to create backing store for newly created file %s"), path
);
4150 if (add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
) < 0)
4151 die(_("unable to add cache entry for %s"), path
);
4154 static int try_create_file(const char *path
, unsigned int mode
, const char *buf
, unsigned long size
)
4157 struct strbuf nbuf
= STRBUF_INIT
;
4159 if (S_ISGITLINK(mode
)) {
4161 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
))
4163 return mkdir(path
, 0777);
4166 if (has_symlinks
&& S_ISLNK(mode
))
4167 /* Although buf:size is counted string, it also is NUL
4170 return symlink(buf
, path
);
4172 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
4176 if (convert_to_working_tree(path
, buf
, size
, &nbuf
)) {
4180 write_or_die(fd
, buf
, size
);
4181 strbuf_release(&nbuf
);
4184 die_errno(_("closing file '%s'"), path
);
4189 * We optimistically assume that the directories exist,
4190 * which is true 99% of the time anyway. If they don't,
4191 * we create them and try again.
4193 static void create_one_file(struct apply_state
*state
,
4201 if (!try_create_file(path
, mode
, buf
, size
))
4204 if (errno
== ENOENT
) {
4205 if (safe_create_leading_directories(path
))
4207 if (!try_create_file(path
, mode
, buf
, size
))
4211 if (errno
== EEXIST
|| errno
== EACCES
) {
4212 /* We may be trying to create a file where a directory
4216 if (!lstat(path
, &st
) && (!S_ISDIR(st
.st_mode
) || !rmdir(path
)))
4220 if (errno
== EEXIST
) {
4221 unsigned int nr
= getpid();
4224 char newpath
[PATH_MAX
];
4225 mksnpath(newpath
, sizeof(newpath
), "%s~%u", path
, nr
);
4226 if (!try_create_file(newpath
, mode
, buf
, size
)) {
4227 if (!rename(newpath
, path
))
4229 unlink_or_warn(newpath
);
4232 if (errno
!= EEXIST
)
4237 die_errno(_("unable to write file '%s' mode %o"), path
, mode
);
4240 static void add_conflicted_stages_file(struct apply_state
*state
,
4241 struct patch
*patch
)
4244 unsigned ce_size
, mode
;
4245 struct cache_entry
*ce
;
4247 if (!state
->update_index
)
4249 namelen
= strlen(patch
->new_name
);
4250 ce_size
= cache_entry_size(namelen
);
4251 mode
= patch
->new_mode
? patch
->new_mode
: (S_IFREG
| 0644);
4253 remove_file_from_cache(patch
->new_name
);
4254 for (stage
= 1; stage
< 4; stage
++) {
4255 if (is_null_oid(&patch
->threeway_stage
[stage
- 1]))
4257 ce
= xcalloc(1, ce_size
);
4258 memcpy(ce
->name
, patch
->new_name
, namelen
);
4259 ce
->ce_mode
= create_ce_mode(mode
);
4260 ce
->ce_flags
= create_ce_flags(stage
);
4261 ce
->ce_namelen
= namelen
;
4262 hashcpy(ce
->sha1
, patch
->threeway_stage
[stage
- 1].hash
);
4263 if (add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
) < 0)
4264 die(_("unable to add cache entry for %s"), patch
->new_name
);
4268 static void create_file(struct apply_state
*state
, struct patch
*patch
)
4270 char *path
= patch
->new_name
;
4271 unsigned mode
= patch
->new_mode
;
4272 unsigned long size
= patch
->resultsize
;
4273 char *buf
= patch
->result
;
4276 mode
= S_IFREG
| 0644;
4277 create_one_file(state
, path
, mode
, buf
, size
);
4279 if (patch
->conflicted_threeway
)
4280 add_conflicted_stages_file(state
, patch
);
4282 add_index_file(state
, path
, mode
, buf
, size
);
4285 /* phase zero is to remove, phase one is to create */
4286 static void write_out_one_result(struct apply_state
*state
,
4287 struct patch
*patch
,
4290 if (patch
->is_delete
> 0) {
4292 remove_file(state
, patch
, 1);
4295 if (patch
->is_new
> 0 || patch
->is_copy
) {
4297 create_file(state
, patch
);
4301 * Rename or modification boils down to the same
4302 * thing: remove the old, write the new
4305 remove_file(state
, patch
, patch
->is_rename
);
4307 create_file(state
, patch
);
4310 static int write_out_one_reject(struct apply_state
*state
, struct patch
*patch
)
4313 char namebuf
[PATH_MAX
];
4314 struct fragment
*frag
;
4316 struct strbuf sb
= STRBUF_INIT
;
4318 for (cnt
= 0, frag
= patch
->fragments
; frag
; frag
= frag
->next
) {
4319 if (!frag
->rejected
)
4325 if (state
->apply_verbosely
)
4326 say_patch_name(stderr
,
4327 _("Applied patch %s cleanly."), patch
);
4331 /* This should not happen, because a removal patch that leaves
4332 * contents are marked "rejected" at the patch level.
4334 if (!patch
->new_name
)
4335 die(_("internal error"));
4337 /* Say this even without --verbose */
4338 strbuf_addf(&sb
, Q_("Applying patch %%s with %d reject...",
4339 "Applying patch %%s with %d rejects...",
4342 say_patch_name(stderr
, sb
.buf
, patch
);
4343 strbuf_release(&sb
);
4345 cnt
= strlen(patch
->new_name
);
4346 if (ARRAY_SIZE(namebuf
) <= cnt
+ 5) {
4347 cnt
= ARRAY_SIZE(namebuf
) - 5;
4348 warning(_("truncating .rej filename to %.*s.rej"),
4349 cnt
- 1, patch
->new_name
);
4351 memcpy(namebuf
, patch
->new_name
, cnt
);
4352 memcpy(namebuf
+ cnt
, ".rej", 5);
4354 rej
= fopen(namebuf
, "w");
4356 return error(_("cannot open %s: %s"), namebuf
, strerror(errno
));
4358 /* Normal git tools never deal with .rej, so do not pretend
4359 * this is a git patch by saying --git or giving extended
4360 * headers. While at it, maybe please "kompare" that wants
4361 * the trailing TAB and some garbage at the end of line ;-).
4363 fprintf(rej
, "diff a/%s b/%s\t(rejected hunks)\n",
4364 patch
->new_name
, patch
->new_name
);
4365 for (cnt
= 1, frag
= patch
->fragments
;
4367 cnt
++, frag
= frag
->next
) {
4368 if (!frag
->rejected
) {
4369 fprintf_ln(stderr
, _("Hunk #%d applied cleanly."), cnt
);
4372 fprintf_ln(stderr
, _("Rejected hunk #%d."), cnt
);
4373 fprintf(rej
, "%.*s", frag
->size
, frag
->patch
);
4374 if (frag
->patch
[frag
->size
-1] != '\n')
4381 static int write_out_results(struct apply_state
*state
, struct patch
*list
)
4386 struct string_list cpath
= STRING_LIST_INIT_DUP
;
4388 for (phase
= 0; phase
< 2; phase
++) {
4394 write_out_one_result(state
, l
, phase
);
4396 if (write_out_one_reject(state
, l
))
4398 if (l
->conflicted_threeway
) {
4399 string_list_append(&cpath
, l
->new_name
);
4409 struct string_list_item
*item
;
4411 string_list_sort(&cpath
);
4412 for_each_string_list_item(item
, &cpath
)
4413 fprintf(stderr
, "U %s\n", item
->string
);
4414 string_list_clear(&cpath
, 0);
4422 static struct lock_file lock_file
;
4424 #define INACCURATE_EOF (1<<0)
4425 #define RECOUNT (1<<1)
4427 static int apply_patch(struct apply_state
*state
,
4429 const char *filename
,
4433 struct strbuf buf
= STRBUF_INIT
; /* owns the patch text */
4434 struct patch
*list
= NULL
, **listp
= &list
;
4435 int skipped_patch
= 0;
4437 state
->patch_input_file
= filename
;
4438 read_patch_file(&buf
, fd
);
4440 while (offset
< buf
.len
) {
4441 struct patch
*patch
;
4444 patch
= xcalloc(1, sizeof(*patch
));
4445 patch
->inaccurate_eof
= !!(options
& INACCURATE_EOF
);
4446 patch
->recount
= !!(options
& RECOUNT
);
4447 nr
= parse_chunk(state
, buf
.buf
+ offset
, buf
.len
- offset
, patch
);
4452 if (state
->apply_in_reverse
)
4453 reverse_patches(patch
);
4454 if (use_patch(state
, patch
)) {
4457 listp
= &patch
->next
;
4460 if (state
->apply_verbosely
)
4461 say_patch_name(stderr
, _("Skipped patch '%s'."), patch
);
4468 if (!list
&& !skipped_patch
)
4469 die(_("unrecognized input"));
4471 if (whitespace_error
&& (ws_error_action
== die_on_ws_error
))
4474 state
->update_index
= state
->check_index
&& state
->apply
;
4475 if (state
->update_index
&& newfd
< 0)
4476 newfd
= hold_locked_index(&lock_file
, 1);
4478 if (state
->check_index
) {
4479 if (read_cache() < 0)
4480 die(_("unable to read index file"));
4483 if ((state
->check
|| state
->apply
) &&
4484 check_patch_list(state
, list
) < 0 &&
4485 !state
->apply_with_reject
)
4488 if (state
->apply
&& write_out_results(state
, list
)) {
4489 if (state
->apply_with_reject
)
4491 /* with --3way, we still need to write the index out */
4495 if (state
->fake_ancestor
)
4496 build_fake_ancestor(list
, state
->fake_ancestor
);
4498 if (state
->diffstat
)
4499 stat_patch_list(list
);
4502 numstat_patch_list(state
, list
);
4505 summary_patch_list(list
);
4507 free_patch_list(list
);
4508 strbuf_release(&buf
);
4509 string_list_clear(&fn_table
, 0);
4513 static void git_apply_config(void)
4515 git_config_get_string_const("apply.whitespace", &apply_default_whitespace
);
4516 git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace
);
4517 git_config(git_default_config
, NULL
);
4520 static int option_parse_exclude(const struct option
*opt
,
4521 const char *arg
, int unset
)
4523 add_name_limit(arg
, 1);
4527 static int option_parse_include(const struct option
*opt
,
4528 const char *arg
, int unset
)
4530 add_name_limit(arg
, 0);
4535 static int option_parse_p(const struct option
*opt
,
4536 const char *arg
, int unset
)
4538 state_p_value
= atoi(arg
);
4543 static int option_parse_space_change(const struct option
*opt
,
4544 const char *arg
, int unset
)
4547 ws_ignore_action
= ignore_ws_none
;
4549 ws_ignore_action
= ignore_ws_change
;
4553 static int option_parse_whitespace(const struct option
*opt
,
4554 const char *arg
, int unset
)
4556 const char **whitespace_option
= opt
->value
;
4558 *whitespace_option
= arg
;
4559 parse_whitespace_option(arg
);
4563 static int option_parse_directory(const struct option
*opt
,
4564 const char *arg
, int unset
)
4566 strbuf_reset(&root
);
4567 strbuf_addstr(&root
, arg
);
4568 strbuf_complete(&root
, '/');
4572 static void init_apply_state(struct apply_state
*state
, const char *prefix
)
4574 memset(state
, 0, sizeof(*state
));
4575 state
->prefix
= prefix
;
4576 state
->prefix_length
= state
->prefix
? strlen(state
->prefix
) : 0;
4578 state
->line_termination
= '\n';
4579 state
->p_context
= UINT_MAX
;
4582 if (apply_default_whitespace
)
4583 parse_whitespace_option(apply_default_whitespace
);
4584 if (apply_default_ignorewhitespace
)
4585 parse_ignorewhitespace_option(apply_default_ignorewhitespace
);
4588 static void clear_apply_state(struct apply_state
*state
)
4593 int cmd_apply(int argc
, const char **argv
, const char *prefix
)
4597 int is_not_gitdir
= !startup_info
->have_repository
;
4598 int force_apply
= 0;
4601 struct apply_state state
;
4603 const char *whitespace_option
= NULL
;
4605 struct option builtin_apply_options
[] = {
4606 { OPTION_CALLBACK
, 0, "exclude", NULL
, N_("path"),
4607 N_("don't apply changes matching the given path"),
4608 0, option_parse_exclude
},
4609 { OPTION_CALLBACK
, 0, "include", NULL
, N_("path"),
4610 N_("apply changes matching the given path"),
4611 0, option_parse_include
},
4612 { OPTION_CALLBACK
, 'p', NULL
, NULL
, N_("num"),
4613 N_("remove <num> leading slashes from traditional diff paths"),
4614 0, option_parse_p
},
4615 OPT_BOOL(0, "no-add", &state
.no_add
,
4616 N_("ignore additions made by the patch")),
4617 OPT_BOOL(0, "stat", &state
.diffstat
,
4618 N_("instead of applying the patch, output diffstat for the input")),
4619 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
4620 OPT_NOOP_NOARG(0, "binary"),
4621 OPT_BOOL(0, "numstat", &state
.numstat
,
4622 N_("show number of added and deleted lines in decimal notation")),
4623 OPT_BOOL(0, "summary", &state
.summary
,
4624 N_("instead of applying the patch, output a summary for the input")),
4625 OPT_BOOL(0, "check", &state
.check
,
4626 N_("instead of applying the patch, see if the patch is applicable")),
4627 OPT_BOOL(0, "index", &state
.check_index
,
4628 N_("make sure the patch is applicable to the current index")),
4629 OPT_BOOL(0, "cached", &state
.cached
,
4630 N_("apply a patch without touching the working tree")),
4631 OPT_BOOL(0, "unsafe-paths", &state
.unsafe_paths
,
4632 N_("accept a patch that touches outside the working area")),
4633 OPT_BOOL(0, "apply", &force_apply
,
4634 N_("also apply the patch (use with --stat/--summary/--check)")),
4635 OPT_BOOL('3', "3way", &state
.threeway
,
4636 N_( "attempt three-way merge if a patch does not apply")),
4637 OPT_FILENAME(0, "build-fake-ancestor", &state
.fake_ancestor
,
4638 N_("build a temporary index based on embedded index information")),
4639 /* Think twice before adding "--nul" synonym to this */
4640 OPT_SET_INT('z', NULL
, &state
.line_termination
,
4641 N_("paths are separated with NUL character"), '\0'),
4642 OPT_INTEGER('C', NULL
, &state
.p_context
,
4643 N_("ensure at least <n> lines of context match")),
4644 { OPTION_CALLBACK
, 0, "whitespace", &whitespace_option
, N_("action"),
4645 N_("detect new or modified lines that have whitespace errors"),
4646 0, option_parse_whitespace
},
4647 { OPTION_CALLBACK
, 0, "ignore-space-change", NULL
, NULL
,
4648 N_("ignore changes in whitespace when finding context"),
4649 PARSE_OPT_NOARG
, option_parse_space_change
},
4650 { OPTION_CALLBACK
, 0, "ignore-whitespace", NULL
, NULL
,
4651 N_("ignore changes in whitespace when finding context"),
4652 PARSE_OPT_NOARG
, option_parse_space_change
},
4653 OPT_BOOL('R', "reverse", &state
.apply_in_reverse
,
4654 N_("apply the patch in reverse")),
4655 OPT_BOOL(0, "unidiff-zero", &state
.unidiff_zero
,
4656 N_("don't expect at least one line of context")),
4657 OPT_BOOL(0, "reject", &state
.apply_with_reject
,
4658 N_("leave the rejected hunks in corresponding *.rej files")),
4659 OPT_BOOL(0, "allow-overlap", &state
.allow_overlap
,
4660 N_("allow overlapping hunks")),
4661 OPT__VERBOSE(&state
.apply_verbosely
, N_("be verbose")),
4662 OPT_BIT(0, "inaccurate-eof", &options
,
4663 N_("tolerate incorrectly detected missing new-line at the end of file"),
4665 OPT_BIT(0, "recount", &options
,
4666 N_("do not trust the line counts in the hunk headers"),
4668 { OPTION_CALLBACK
, 0, "directory", NULL
, N_("root"),
4669 N_("prepend <root> to all filenames"),
4670 0, option_parse_directory
},
4674 init_apply_state(&state
, prefix
);
4676 argc
= parse_options(argc
, argv
, state
.prefix
, builtin_apply_options
,
4679 if (state
.apply_with_reject
&& state
.threeway
)
4680 die("--reject and --3way cannot be used together.");
4681 if (state
.cached
&& state
.threeway
)
4682 die("--cached and --3way cannot be used together.");
4683 if (state
.threeway
) {
4685 die(_("--3way outside a repository"));
4686 state
.check_index
= 1;
4688 if (state
.apply_with_reject
)
4689 state
.apply
= state
.apply_verbosely
= 1;
4690 if (!force_apply
&& (state
.diffstat
|| state
.numstat
|| state
.summary
|| state
.check
|| state
.fake_ancestor
))
4692 if (state
.check_index
&& is_not_gitdir
)
4693 die(_("--index outside a repository"));
4696 die(_("--cached outside a repository"));
4697 state
.check_index
= 1;
4699 if (state
.check_index
)
4700 state
.unsafe_paths
= 0;
4702 for (i
= 0; i
< argc
; i
++) {
4703 const char *arg
= argv
[i
];
4706 if (!strcmp(arg
, "-")) {
4707 errs
|= apply_patch(&state
, 0, "<stdin>", options
);
4710 } else if (0 < state
.prefix_length
)
4711 arg
= prefix_filename(state
.prefix
,
4712 state
.prefix_length
,
4715 fd
= open(arg
, O_RDONLY
);
4717 die_errno(_("can't open patch '%s'"), arg
);
4719 set_default_whitespace_mode(&state
, whitespace_option
);
4720 errs
|= apply_patch(&state
, fd
, arg
, options
);
4723 set_default_whitespace_mode(&state
, whitespace_option
);
4725 errs
|= apply_patch(&state
, 0, "<stdin>", options
);
4726 if (whitespace_error
) {
4727 if (squelch_whitespace_errors
&&
4728 squelch_whitespace_errors
< whitespace_error
) {
4730 whitespace_error
- squelch_whitespace_errors
;
4731 warning(Q_("squelched %d whitespace error",
4732 "squelched %d whitespace errors",
4736 if (ws_error_action
== die_on_ws_error
)
4737 die(Q_("%d line adds whitespace errors.",
4738 "%d lines add whitespace errors.",
4741 if (applied_after_fixing_ws
&& state
.apply
)
4742 warning("%d line%s applied after"
4743 " fixing whitespace errors.",
4744 applied_after_fixing_ws
,
4745 applied_after_fixing_ws
== 1 ? "" : "s");
4746 else if (whitespace_error
)
4747 warning(Q_("%d line adds whitespace errors.",
4748 "%d lines add whitespace errors.",
4753 if (state
.update_index
) {
4754 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
4755 die(_("Unable to write new index file"));
4758 clear_apply_state(&state
);