4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
10 #include "cache-tree.h"
15 #include "string-list.h"
17 #include "parse-options.h"
20 * --check turns on checking that the working tree matches the
21 * files that are being modified, but doesn't apply the patch
22 * --stat does just a diffstat, and doesn't actually apply
23 * --numstat does numeric diffstat, and doesn't actually apply
24 * --index-info shows the old and new index info for paths if available.
25 * --index updates the cache as well.
26 * --cached updates only the cache without ever touching the working tree.
28 static const char *prefix
;
29 static int prefix_length
= -1;
30 static int newfd
= -1;
32 static int unidiff_zero
;
33 static int p_value
= 1;
34 static int p_value_known
;
35 static int check_index
;
36 static int update_index
;
43 static int apply_in_reverse
;
44 static int apply_with_reject
;
45 static int apply_verbosely
;
47 static const char *fake_ancestor
;
48 static int line_termination
= '\n';
49 static unsigned int p_context
= UINT_MAX
;
50 static const char * const apply_usage
[] = {
51 "git apply [options] [<patch>...]",
55 static enum ws_error_action
{
60 } ws_error_action
= warn_on_ws_error
;
61 static int whitespace_error
;
62 static int squelch_whitespace_errors
= 5;
63 static int applied_after_fixing_ws
;
65 static enum ws_ignore
{
68 } ws_ignore_action
= ignore_ws_none
;
71 static const char *patch_input_file
;
72 static const char *root
;
74 static int read_stdin
= 1;
77 static void parse_whitespace_option(const char *option
)
80 ws_error_action
= warn_on_ws_error
;
83 if (!strcmp(option
, "warn")) {
84 ws_error_action
= warn_on_ws_error
;
87 if (!strcmp(option
, "nowarn")) {
88 ws_error_action
= nowarn_ws_error
;
91 if (!strcmp(option
, "error")) {
92 ws_error_action
= die_on_ws_error
;
95 if (!strcmp(option
, "error-all")) {
96 ws_error_action
= die_on_ws_error
;
97 squelch_whitespace_errors
= 0;
100 if (!strcmp(option
, "strip") || !strcmp(option
, "fix")) {
101 ws_error_action
= correct_ws_error
;
104 die("unrecognized whitespace option '%s'", option
);
107 static void parse_ignorewhitespace_option(const char *option
)
109 if (!option
|| !strcmp(option
, "no") ||
110 !strcmp(option
, "false") || !strcmp(option
, "never") ||
111 !strcmp(option
, "none")) {
112 ws_ignore_action
= ignore_ws_none
;
115 if (!strcmp(option
, "change")) {
116 ws_ignore_action
= ignore_ws_change
;
119 die("unrecognized whitespace ignore option '%s'", option
);
122 static void set_default_whitespace_mode(const char *whitespace_option
)
124 if (!whitespace_option
&& !apply_default_whitespace
)
125 ws_error_action
= (apply
? warn_on_ws_error
: nowarn_ws_error
);
129 * For "diff-stat" like behaviour, we keep track of the biggest change
130 * we've seen, and the longest filename. That allows us to do simple
133 static int max_change
, max_len
;
136 * Various "current state", notably line numbers and what
137 * file (and how) we're patching right now.. The "is_xxxx"
138 * things are flags, where -1 means "don't know yet".
140 static int linenr
= 1;
143 * This represents one "hunk" from a patch, starting with
144 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
145 * patch text is pointed at by patch, and its byte length
146 * is stored in size. leading and trailing are the number
150 unsigned long leading
, trailing
;
151 unsigned long oldpos
, oldlines
;
152 unsigned long newpos
, newlines
;
157 struct fragment
*next
;
161 * When dealing with a binary patch, we reuse "leading" field
162 * to store the type of the binary hunk, either deflated "delta"
163 * or deflated "literal".
165 #define binary_patch_method leading
166 #define BINARY_DELTA_DEFLATED 1
167 #define BINARY_LITERAL_DEFLATED 2
170 * This represents a "patch" to a file, both metainfo changes
171 * such as creation/deletion, filemode and content changes represented
172 * as a series of fragments.
175 char *new_name
, *old_name
, *def_name
;
176 unsigned int old_mode
, new_mode
;
177 int is_new
, is_delete
; /* -1 = unknown, 0 = false, 1 = true */
180 unsigned long deflate_origlen
;
181 int lines_added
, lines_deleted
;
183 unsigned int is_toplevel_relative
:1;
184 unsigned int inaccurate_eof
:1;
185 unsigned int is_binary
:1;
186 unsigned int is_copy
:1;
187 unsigned int is_rename
:1;
188 unsigned int recount
:1;
189 struct fragment
*fragments
;
192 char old_sha1_prefix
[41];
193 char new_sha1_prefix
[41];
198 * A line in a file, len-bytes long (includes the terminating LF,
199 * except for an incomplete line at the end if the file ends with
200 * one), and its contents hashes to 'hash'.
206 #define LINE_COMMON 1
210 * This represents a "file", which is an array of "lines".
217 struct line
*line_allocated
;
222 * Records filenames that have been touched, in order to handle
223 * the case where more than one patches touch the same file.
226 static struct string_list fn_table
;
228 static uint32_t hash_line(const char *cp
, size_t len
)
232 for (i
= 0, h
= 0; i
< len
; i
++) {
233 if (!isspace(cp
[i
])) {
234 h
= h
* 3 + (cp
[i
] & 0xff);
241 * Compare lines s1 of length n1 and s2 of length n2, ignoring
242 * whitespace difference. Returns 1 if they match, 0 otherwise
244 static int fuzzy_matchlines(const char *s1
, size_t n1
,
245 const char *s2
, size_t n2
)
247 const char *last1
= s1
+ n1
- 1;
248 const char *last2
= s2
+ n2
- 1;
251 if (n1
< 0 || n2
< 0)
254 /* ignore line endings */
255 while ((*last1
== '\r') || (*last1
== '\n'))
257 while ((*last2
== '\r') || (*last2
== '\n'))
260 /* skip leading whitespace */
261 while (isspace(*s1
) && (s1
<= last1
))
263 while (isspace(*s2
) && (s2
<= last2
))
265 /* early return if both lines are empty */
266 if ((s1
> last1
) && (s2
> last2
))
269 result
= *s1
++ - *s2
++;
271 * Skip whitespace inside. We check for whitespace on
272 * both buffers because we don't want "a b" to match
275 if (isspace(*s1
) && isspace(*s2
)) {
276 while (isspace(*s1
) && s1
<= last1
)
278 while (isspace(*s2
) && s2
<= last2
)
282 * If we reached the end on one side only,
286 ((s2
> last2
) && (s1
<= last1
)) ||
287 ((s1
> last1
) && (s2
<= last2
)))
289 if ((s1
> last1
) && (s2
> last2
))
296 static void add_line_info(struct image
*img
, const char *bol
, size_t len
, unsigned flag
)
298 ALLOC_GROW(img
->line_allocated
, img
->nr
+ 1, img
->alloc
);
299 img
->line_allocated
[img
->nr
].len
= len
;
300 img
->line_allocated
[img
->nr
].hash
= hash_line(bol
, len
);
301 img
->line_allocated
[img
->nr
].flag
= flag
;
305 static void prepare_image(struct image
*image
, char *buf
, size_t len
,
306 int prepare_linetable
)
310 memset(image
, 0, sizeof(*image
));
314 if (!prepare_linetable
)
317 ep
= image
->buf
+ image
->len
;
321 for (next
= cp
; next
< ep
&& *next
!= '\n'; next
++)
325 add_line_info(image
, cp
, next
- cp
, 0);
328 image
->line
= image
->line_allocated
;
331 static void clear_image(struct image
*image
)
338 static void say_patch_name(FILE *output
, const char *pre
,
339 struct patch
*patch
, const char *post
)
342 if (patch
->old_name
&& patch
->new_name
&&
343 strcmp(patch
->old_name
, patch
->new_name
)) {
344 quote_c_style(patch
->old_name
, NULL
, output
, 0);
345 fputs(" => ", output
);
346 quote_c_style(patch
->new_name
, NULL
, output
, 0);
348 const char *n
= patch
->new_name
;
351 quote_c_style(n
, NULL
, output
, 0);
356 #define CHUNKSIZE (8192)
359 static void read_patch_file(struct strbuf
*sb
, int fd
)
361 if (strbuf_read(sb
, fd
, 0) < 0)
362 die_errno("git apply: failed to read");
365 * Make sure that we have some slop in the buffer
366 * so that we can do speculative "memcmp" etc, and
367 * see to it that it is NUL-filled.
369 strbuf_grow(sb
, SLOP
);
370 memset(sb
->buf
+ sb
->len
, 0, SLOP
);
373 static unsigned long linelen(const char *buffer
, unsigned long size
)
375 unsigned long len
= 0;
378 if (*buffer
++ == '\n')
384 static int is_dev_null(const char *str
)
386 return !memcmp("/dev/null", str
, 9) && isspace(str
[9]);
392 static int name_terminate(const char *name
, int namelen
, int c
, int terminate
)
394 if (c
== ' ' && !(terminate
& TERM_SPACE
))
396 if (c
== '\t' && !(terminate
& TERM_TAB
))
402 /* remove double slashes to make --index work with such filenames */
403 static char *squash_slash(char *name
)
411 if ((name
[j
++] = name
[i
++]) == '/')
412 while (name
[i
] == '/')
419 static char *find_name_gnu(const char *line
, char *def
, int p_value
)
421 struct strbuf name
= STRBUF_INIT
;
425 * Proposed "new-style" GNU patch/diff format; see
426 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
428 if (unquote_c_style(&name
, line
, NULL
)) {
429 strbuf_release(&name
);
433 for (cp
= name
.buf
; p_value
; p_value
--) {
434 cp
= strchr(cp
, '/');
436 strbuf_release(&name
);
442 /* name can later be freed, so we need
443 * to memmove, not just return cp
445 strbuf_remove(&name
, 0, cp
- name
.buf
);
448 strbuf_insert(&name
, 0, root
, root_len
);
449 return squash_slash(strbuf_detach(&name
, NULL
));
452 static size_t tz_len(const char *line
, size_t len
)
456 if (len
< strlen(" +0500") || line
[len
-strlen(" +0500")] != ' ')
458 tz
= line
+ len
- strlen(" +0500");
460 if (tz
[1] != '+' && tz
[1] != '-')
463 for (p
= tz
+ 2; p
!= line
+ len
; p
++)
467 return line
+ len
- tz
;
470 static size_t date_len(const char *line
, size_t len
)
472 const char *date
, *p
;
474 if (len
< strlen("72-02-05") || line
[len
-strlen("-05")] != '-')
476 p
= date
= line
+ len
- strlen("72-02-05");
478 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
479 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
480 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a date. */
483 if (date
- line
>= strlen("19") &&
484 isdigit(date
[-1]) && isdigit(date
[-2])) /* 4-digit year */
485 date
-= strlen("19");
487 return line
+ len
- date
;
490 static size_t short_time_len(const char *line
, size_t len
)
492 const char *time
, *p
;
494 if (len
< strlen(" 07:01:32") || line
[len
-strlen(":32")] != ':')
496 p
= time
= line
+ len
- strlen(" 07:01:32");
498 /* Permit 1-digit hours? */
500 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
501 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
502 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a time. */
505 return line
+ len
- time
;
508 static size_t fractional_time_len(const char *line
, size_t len
)
513 /* Expected format: 19:41:17.620000023 */
514 if (!len
|| !isdigit(line
[len
- 1]))
518 /* Fractional seconds. */
519 while (p
> line
&& isdigit(*p
))
524 /* Hours, minutes, and whole seconds. */
525 n
= short_time_len(line
, p
- line
);
529 return line
+ len
- p
+ n
;
532 static size_t trailing_spaces_len(const char *line
, size_t len
)
536 /* Expected format: ' ' x (1 or more) */
537 if (!len
|| line
[len
- 1] != ' ')
544 return line
+ len
- (p
+ 1);
551 static size_t diff_timestamp_len(const char *line
, size_t len
)
553 const char *end
= line
+ len
;
557 * Posix: 2010-07-05 19:41:17
558 * GNU: 2010-07-05 19:41:17.620000023 -0500
561 if (!isdigit(end
[-1]))
564 n
= tz_len(line
, end
- line
);
567 n
= short_time_len(line
, end
- line
);
569 n
= fractional_time_len(line
, end
- line
);
572 n
= date_len(line
, end
- line
);
573 if (!n
) /* No date. Too bad. */
577 if (end
== line
) /* No space before date. */
579 if (end
[-1] == '\t') { /* Success! */
581 return line
+ len
- end
;
583 if (end
[-1] != ' ') /* No space before date. */
586 /* Whitespace damage. */
587 end
-= trailing_spaces_len(line
, end
- line
);
588 return line
+ len
- end
;
591 static char *find_name_common(const char *line
, char *def
, int p_value
,
592 const char *end
, int terminate
)
595 const char *start
= NULL
;
599 while (line
!= end
) {
602 if (!end
&& isspace(c
)) {
605 if (name_terminate(start
, line
-start
, c
, terminate
))
609 if (c
== '/' && !--p_value
)
613 return squash_slash(def
);
616 return squash_slash(def
);
619 * Generally we prefer the shorter name, especially
620 * if the other one is just a variation of that with
621 * something else tacked on to the end (ie "file.orig"
625 int deflen
= strlen(def
);
626 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
627 return squash_slash(def
);
632 char *ret
= xmalloc(root_len
+ len
+ 1);
634 memcpy(ret
+ root_len
, start
, len
);
635 ret
[root_len
+ len
] = '\0';
636 return squash_slash(ret
);
639 return squash_slash(xmemdupz(start
, len
));
642 static char *find_name(const char *line
, char *def
, int p_value
, int terminate
)
645 char *name
= find_name_gnu(line
, def
, p_value
);
650 return find_name_common(line
, def
, p_value
, NULL
, terminate
);
653 static char *find_name_traditional(const char *line
, char *def
, int p_value
)
655 size_t len
= strlen(line
);
659 char *name
= find_name_gnu(line
, def
, p_value
);
664 len
= strchrnul(line
, '\n') - line
;
665 date_len
= diff_timestamp_len(line
, len
);
667 return find_name_common(line
, def
, p_value
, NULL
, TERM_TAB
);
670 return find_name_common(line
, def
, p_value
, line
+ len
, 0);
673 static int count_slashes(const char *cp
)
685 * Given the string after "--- " or "+++ ", guess the appropriate
686 * p_value for the given patch.
688 static int guess_p_value(const char *nameline
)
693 if (is_dev_null(nameline
))
695 name
= find_name_traditional(nameline
, NULL
, 0);
698 cp
= strchr(name
, '/');
703 * Does it begin with "a/$our-prefix" and such? Then this is
704 * very likely to apply to our directory.
706 if (!strncmp(name
, prefix
, prefix_length
))
707 val
= count_slashes(prefix
);
710 if (!strncmp(cp
, prefix
, prefix_length
))
711 val
= count_slashes(prefix
) + 1;
719 * Does the ---/+++ line has the POSIX timestamp after the last HT?
720 * GNU diff puts epoch there to signal a creation/deletion event. Is
721 * this such a timestamp?
723 static int has_epoch_timestamp(const char *nameline
)
726 * We are only interested in epoch timestamp; any non-zero
727 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
728 * For the same reason, the date must be either 1969-12-31 or
729 * 1970-01-01, and the seconds part must be "00".
731 const char stamp_regexp
[] =
732 "^(1969-12-31|1970-01-01)"
734 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
736 "([-+][0-2][0-9]:?[0-5][0-9])\n";
737 const char *timestamp
= NULL
, *cp
, *colon
;
738 static regex_t
*stamp
;
744 for (cp
= nameline
; *cp
!= '\n'; cp
++) {
751 stamp
= xmalloc(sizeof(*stamp
));
752 if (regcomp(stamp
, stamp_regexp
, REG_EXTENDED
)) {
753 warning("Cannot prepare timestamp regexp %s",
759 status
= regexec(stamp
, timestamp
, ARRAY_SIZE(m
), m
, 0);
761 if (status
!= REG_NOMATCH
)
762 warning("regexec returned %d for input: %s",
767 zoneoffset
= strtol(timestamp
+ m
[3].rm_so
+ 1, (char **) &colon
, 10);
769 zoneoffset
= zoneoffset
* 60 + strtol(colon
+ 1, NULL
, 10);
771 zoneoffset
= (zoneoffset
/ 100) * 60 + (zoneoffset
% 100);
772 if (timestamp
[m
[3].rm_so
] == '-')
773 zoneoffset
= -zoneoffset
;
776 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
777 * (west of GMT) or 1970-01-01 (east of GMT)
779 if ((zoneoffset
< 0 && memcmp(timestamp
, "1969-12-31", 10)) ||
780 (0 <= zoneoffset
&& memcmp(timestamp
, "1970-01-01", 10)))
783 hourminute
= (strtol(timestamp
+ 11, NULL
, 10) * 60 +
784 strtol(timestamp
+ 14, NULL
, 10) -
787 return ((zoneoffset
< 0 && hourminute
== 1440) ||
788 (0 <= zoneoffset
&& !hourminute
));
792 * Get the name etc info from the ---/+++ lines of a traditional patch header
794 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
795 * files, we can happily check the index for a match, but for creating a
796 * new file we should try to match whatever "patch" does. I have no idea.
798 static void parse_traditional_patch(const char *first
, const char *second
, struct patch
*patch
)
802 first
+= 4; /* skip "--- " */
803 second
+= 4; /* skip "+++ " */
804 if (!p_value_known
) {
806 p
= guess_p_value(first
);
807 q
= guess_p_value(second
);
809 if (0 <= p
&& p
== q
) {
814 if (is_dev_null(first
)) {
816 patch
->is_delete
= 0;
817 name
= find_name_traditional(second
, NULL
, p_value
);
818 patch
->new_name
= name
;
819 } else if (is_dev_null(second
)) {
821 patch
->is_delete
= 1;
822 name
= find_name_traditional(first
, NULL
, p_value
);
823 patch
->old_name
= name
;
825 name
= find_name_traditional(first
, NULL
, p_value
);
826 name
= find_name_traditional(second
, name
, p_value
);
827 if (has_epoch_timestamp(first
)) {
829 patch
->is_delete
= 0;
830 patch
->new_name
= name
;
831 } else if (has_epoch_timestamp(second
)) {
833 patch
->is_delete
= 1;
834 patch
->old_name
= name
;
836 patch
->old_name
= patch
->new_name
= name
;
840 die("unable to find filename in patch at line %d", linenr
);
843 static int gitdiff_hdrend(const char *line
, struct patch
*patch
)
849 * We're anal about diff header consistency, to make
850 * sure that we don't end up having strange ambiguous
851 * patches floating around.
853 * As a result, gitdiff_{old|new}name() will check
854 * their names against any previous information, just
857 static char *gitdiff_verify_name(const char *line
, int isnull
, char *orig_name
, const char *oldnew
)
859 if (!orig_name
&& !isnull
)
860 return find_name(line
, NULL
, p_value
, TERM_TAB
);
869 die("git apply: bad git-diff - expected /dev/null, got %s on line %d", name
, linenr
);
870 another
= find_name(line
, NULL
, p_value
, TERM_TAB
);
871 if (!another
|| memcmp(another
, name
, len
+ 1))
872 die("git apply: bad git-diff - inconsistent %s filename on line %d", oldnew
, linenr
);
877 /* expect "/dev/null" */
878 if (memcmp("/dev/null", line
, 9) || line
[9] != '\n')
879 die("git apply: bad git-diff - expected /dev/null on line %d", linenr
);
884 static int gitdiff_oldname(const char *line
, struct patch
*patch
)
886 patch
->old_name
= gitdiff_verify_name(line
, patch
->is_new
, patch
->old_name
, "old");
890 static int gitdiff_newname(const char *line
, struct patch
*patch
)
892 patch
->new_name
= gitdiff_verify_name(line
, patch
->is_delete
, patch
->new_name
, "new");
896 static int gitdiff_oldmode(const char *line
, struct patch
*patch
)
898 patch
->old_mode
= strtoul(line
, NULL
, 8);
902 static int gitdiff_newmode(const char *line
, struct patch
*patch
)
904 patch
->new_mode
= strtoul(line
, NULL
, 8);
908 static int gitdiff_delete(const char *line
, struct patch
*patch
)
910 patch
->is_delete
= 1;
911 patch
->old_name
= patch
->def_name
;
912 return gitdiff_oldmode(line
, patch
);
915 static int gitdiff_newfile(const char *line
, struct patch
*patch
)
918 patch
->new_name
= patch
->def_name
;
919 return gitdiff_newmode(line
, patch
);
922 static int gitdiff_copysrc(const char *line
, struct patch
*patch
)
925 patch
->old_name
= find_name(line
, NULL
, 0, 0);
929 static int gitdiff_copydst(const char *line
, struct patch
*patch
)
932 patch
->new_name
= find_name(line
, NULL
, 0, 0);
936 static int gitdiff_renamesrc(const char *line
, struct patch
*patch
)
938 patch
->is_rename
= 1;
939 patch
->old_name
= find_name(line
, NULL
, 0, 0);
943 static int gitdiff_renamedst(const char *line
, struct patch
*patch
)
945 patch
->is_rename
= 1;
946 patch
->new_name
= find_name(line
, NULL
, 0, 0);
950 static int gitdiff_similarity(const char *line
, struct patch
*patch
)
952 if ((patch
->score
= strtoul(line
, NULL
, 10)) == ULONG_MAX
)
957 static int gitdiff_dissimilarity(const char *line
, struct patch
*patch
)
959 if ((patch
->score
= strtoul(line
, NULL
, 10)) == ULONG_MAX
)
964 static int gitdiff_index(const char *line
, struct patch
*patch
)
967 * index line is N hexadecimal, "..", N hexadecimal,
968 * and optional space with octal mode.
970 const char *ptr
, *eol
;
973 ptr
= strchr(line
, '.');
974 if (!ptr
|| ptr
[1] != '.' || 40 < ptr
- line
)
977 memcpy(patch
->old_sha1_prefix
, line
, len
);
978 patch
->old_sha1_prefix
[len
] = 0;
981 ptr
= strchr(line
, ' ');
982 eol
= strchr(line
, '\n');
984 if (!ptr
|| eol
< ptr
)
990 memcpy(patch
->new_sha1_prefix
, line
, len
);
991 patch
->new_sha1_prefix
[len
] = 0;
993 patch
->old_mode
= strtoul(ptr
+1, NULL
, 8);
998 * This is normal for a diff that doesn't change anything: we'll fall through
999 * into the next diff. Tell the parser to break out.
1001 static int gitdiff_unrecognized(const char *line
, struct patch
*patch
)
1006 static const char *stop_at_slash(const char *line
, int llen
)
1008 int nslash
= p_value
;
1011 for (i
= 0; i
< llen
; i
++) {
1013 if (ch
== '/' && --nslash
<= 0)
1020 * This is to extract the same name that appears on "diff --git"
1021 * line. We do not find and return anything if it is a rename
1022 * patch, and it is OK because we will find the name elsewhere.
1023 * We need to reliably find name only when it is mode-change only,
1024 * creation or deletion of an empty file. In any of these cases,
1025 * both sides are the same name under a/ and b/ respectively.
1027 static char *git_header_name(char *line
, int llen
)
1030 const char *second
= NULL
;
1033 line
+= strlen("diff --git ");
1034 llen
-= strlen("diff --git ");
1038 struct strbuf first
= STRBUF_INIT
;
1039 struct strbuf sp
= STRBUF_INIT
;
1041 if (unquote_c_style(&first
, line
, &second
))
1042 goto free_and_fail1
;
1044 /* advance to the first slash */
1045 cp
= stop_at_slash(first
.buf
, first
.len
);
1046 /* we do not accept absolute paths */
1047 if (!cp
|| cp
== first
.buf
)
1048 goto free_and_fail1
;
1049 strbuf_remove(&first
, 0, cp
+ 1 - first
.buf
);
1052 * second points at one past closing dq of name.
1053 * find the second name.
1055 while ((second
< line
+ llen
) && isspace(*second
))
1058 if (line
+ llen
<= second
)
1059 goto free_and_fail1
;
1060 if (*second
== '"') {
1061 if (unquote_c_style(&sp
, second
, NULL
))
1062 goto free_and_fail1
;
1063 cp
= stop_at_slash(sp
.buf
, sp
.len
);
1064 if (!cp
|| cp
== sp
.buf
)
1065 goto free_and_fail1
;
1066 /* They must match, otherwise ignore */
1067 if (strcmp(cp
+ 1, first
.buf
))
1068 goto free_and_fail1
;
1069 strbuf_release(&sp
);
1070 return strbuf_detach(&first
, NULL
);
1073 /* unquoted second */
1074 cp
= stop_at_slash(second
, line
+ llen
- second
);
1075 if (!cp
|| cp
== second
)
1076 goto free_and_fail1
;
1078 if (line
+ llen
- cp
!= first
.len
+ 1 ||
1079 memcmp(first
.buf
, cp
, first
.len
))
1080 goto free_and_fail1
;
1081 return strbuf_detach(&first
, NULL
);
1084 strbuf_release(&first
);
1085 strbuf_release(&sp
);
1089 /* unquoted first name */
1090 name
= stop_at_slash(line
, llen
);
1091 if (!name
|| name
== line
)
1096 * since the first name is unquoted, a dq if exists must be
1097 * the beginning of the second name.
1099 for (second
= name
; second
< line
+ llen
; second
++) {
1100 if (*second
== '"') {
1101 struct strbuf sp
= STRBUF_INIT
;
1104 if (unquote_c_style(&sp
, second
, NULL
))
1105 goto free_and_fail2
;
1107 np
= stop_at_slash(sp
.buf
, sp
.len
);
1108 if (!np
|| np
== sp
.buf
)
1109 goto free_and_fail2
;
1112 len
= sp
.buf
+ sp
.len
- np
;
1113 if (len
< second
- name
&&
1114 !strncmp(np
, name
, len
) &&
1115 isspace(name
[len
])) {
1117 strbuf_remove(&sp
, 0, np
- sp
.buf
);
1118 return strbuf_detach(&sp
, NULL
);
1122 strbuf_release(&sp
);
1128 * Accept a name only if it shows up twice, exactly the same
1131 for (len
= 0 ; ; len
++) {
1132 switch (name
[len
]) {
1137 case '\t': case ' ':
1146 if (second
[len
] == '\n' && !memcmp(name
, second
, len
)) {
1147 return xmemdupz(name
, len
);
1153 /* Verify that we recognize the lines following a git header */
1154 static int parse_git_header(char *line
, int len
, unsigned int size
, struct patch
*patch
)
1156 unsigned long offset
;
1158 /* A git diff has explicit new/delete information, so we don't guess */
1160 patch
->is_delete
= 0;
1163 * Some things may not have the old name in the
1164 * rest of the headers anywhere (pure mode changes,
1165 * or removing or adding empty files), so we get
1166 * the default name from the header.
1168 patch
->def_name
= git_header_name(line
, len
);
1169 if (patch
->def_name
&& root
) {
1170 char *s
= xmalloc(root_len
+ strlen(patch
->def_name
) + 1);
1172 strcpy(s
+ root_len
, patch
->def_name
);
1173 free(patch
->def_name
);
1174 patch
->def_name
= s
;
1180 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1181 static const struct opentry
{
1183 int (*fn
)(const char *, struct patch
*);
1185 { "@@ -", gitdiff_hdrend
},
1186 { "--- ", gitdiff_oldname
},
1187 { "+++ ", gitdiff_newname
},
1188 { "old mode ", gitdiff_oldmode
},
1189 { "new mode ", gitdiff_newmode
},
1190 { "deleted file mode ", gitdiff_delete
},
1191 { "new file mode ", gitdiff_newfile
},
1192 { "copy from ", gitdiff_copysrc
},
1193 { "copy to ", gitdiff_copydst
},
1194 { "rename old ", gitdiff_renamesrc
},
1195 { "rename new ", gitdiff_renamedst
},
1196 { "rename from ", gitdiff_renamesrc
},
1197 { "rename to ", gitdiff_renamedst
},
1198 { "similarity index ", gitdiff_similarity
},
1199 { "dissimilarity index ", gitdiff_dissimilarity
},
1200 { "index ", gitdiff_index
},
1201 { "", gitdiff_unrecognized
},
1205 len
= linelen(line
, size
);
1206 if (!len
|| line
[len
-1] != '\n')
1208 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
1209 const struct opentry
*p
= optable
+ i
;
1210 int oplen
= strlen(p
->str
);
1211 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
1213 if (p
->fn(line
+ oplen
, patch
) < 0)
1222 static int parse_num(const char *line
, unsigned long *p
)
1226 if (!isdigit(*line
))
1228 *p
= strtoul(line
, &ptr
, 10);
1232 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
1233 unsigned long *p1
, unsigned long *p2
)
1237 if (offset
< 0 || offset
>= len
)
1242 digits
= parse_num(line
, p1
);
1252 digits
= parse_num(line
+1, p2
);
1261 ex
= strlen(expect
);
1264 if (memcmp(line
, expect
, ex
))
1270 static void recount_diff(char *line
, int size
, struct fragment
*fragment
)
1272 int oldlines
= 0, newlines
= 0, ret
= 0;
1275 warning("recount: ignore empty hunk");
1280 int len
= linelen(line
, size
);
1288 case ' ': case '\n':
1300 ret
= size
< 3 || prefixcmp(line
, "@@ ");
1303 ret
= size
< 5 || prefixcmp(line
, "diff ");
1310 warning("recount: unexpected line: %.*s",
1311 (int)linelen(line
, size
), line
);
1316 fragment
->oldlines
= oldlines
;
1317 fragment
->newlines
= newlines
;
1321 * Parse a unified diff fragment header of the
1322 * form "@@ -a,b +c,d @@"
1324 static int parse_fragment_header(char *line
, int len
, struct fragment
*fragment
)
1328 if (!len
|| line
[len
-1] != '\n')
1331 /* Figure out the number of lines in a fragment */
1332 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
1333 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
1338 static int find_header(char *line
, unsigned long size
, int *hdrsize
, struct patch
*patch
)
1340 unsigned long offset
, len
;
1342 patch
->is_toplevel_relative
= 0;
1343 patch
->is_rename
= patch
->is_copy
= 0;
1344 patch
->is_new
= patch
->is_delete
= -1;
1345 patch
->old_mode
= patch
->new_mode
= 0;
1346 patch
->old_name
= patch
->new_name
= NULL
;
1347 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1348 unsigned long nextlen
;
1350 len
= linelen(line
, size
);
1354 /* Testing this early allows us to take a few shortcuts.. */
1359 * Make sure we don't find any unconnected patch fragments.
1360 * That's a sign that we didn't find a header, and that a
1361 * patch has become corrupted/broken up.
1363 if (!memcmp("@@ -", line
, 4)) {
1364 struct fragment dummy
;
1365 if (parse_fragment_header(line
, len
, &dummy
) < 0)
1367 die("patch fragment without header at line %d: %.*s",
1368 linenr
, (int)len
-1, line
);
1375 * Git patch? It might not have a real patch, just a rename
1376 * or mode change, so we handle that specially
1378 if (!memcmp("diff --git ", line
, 11)) {
1379 int git_hdr_len
= parse_git_header(line
, len
, size
, patch
);
1380 if (git_hdr_len
<= len
)
1382 if (!patch
->old_name
&& !patch
->new_name
) {
1383 if (!patch
->def_name
)
1384 die("git diff header lacks filename information when removing "
1385 "%d leading pathname components (line %d)" , p_value
, linenr
);
1386 patch
->old_name
= patch
->new_name
= patch
->def_name
;
1388 patch
->is_toplevel_relative
= 1;
1389 *hdrsize
= git_hdr_len
;
1393 /* --- followed by +++ ? */
1394 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
1398 * We only accept unified patches, so we want it to
1399 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1400 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1402 nextlen
= linelen(line
+ len
, size
- len
);
1403 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
1406 /* Ok, we'll consider it a patch */
1407 parse_traditional_patch(line
, line
+len
, patch
);
1408 *hdrsize
= len
+ nextlen
;
1415 static void record_ws_error(unsigned result
, const char *line
, int len
, int linenr
)
1423 if (squelch_whitespace_errors
&&
1424 squelch_whitespace_errors
< whitespace_error
)
1427 err
= whitespace_error_string(result
);
1428 fprintf(stderr
, "%s:%d: %s.\n%.*s\n",
1429 patch_input_file
, linenr
, err
, len
, line
);
1433 static void check_whitespace(const char *line
, int len
, unsigned ws_rule
)
1435 unsigned result
= ws_check(line
+ 1, len
- 1, ws_rule
);
1437 record_ws_error(result
, line
+ 1, len
- 2, linenr
);
1441 * Parse a unified diff. Note that this really needs to parse each
1442 * fragment separately, since the only way to know the difference
1443 * between a "---" that is part of a patch, and a "---" that starts
1444 * the next patch is to look at the line counts..
1446 static int parse_fragment(char *line
, unsigned long size
,
1447 struct patch
*patch
, struct fragment
*fragment
)
1450 int len
= linelen(line
, size
), offset
;
1451 unsigned long oldlines
, newlines
;
1452 unsigned long leading
, trailing
;
1454 offset
= parse_fragment_header(line
, len
, fragment
);
1457 if (offset
> 0 && patch
->recount
)
1458 recount_diff(line
+ offset
, size
- offset
, fragment
);
1459 oldlines
= fragment
->oldlines
;
1460 newlines
= fragment
->newlines
;
1464 /* Parse the thing.. */
1468 added
= deleted
= 0;
1471 offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1472 if (!oldlines
&& !newlines
)
1474 len
= linelen(line
, size
);
1475 if (!len
|| line
[len
-1] != '\n')
1480 case '\n': /* newer GNU diff, an empty context line */
1484 if (!deleted
&& !added
)
1489 if (apply_in_reverse
&&
1490 ws_error_action
!= nowarn_ws_error
)
1491 check_whitespace(line
, len
, patch
->ws_rule
);
1497 if (!apply_in_reverse
&&
1498 ws_error_action
!= nowarn_ws_error
)
1499 check_whitespace(line
, len
, patch
->ws_rule
);
1506 * We allow "\ No newline at end of file". Depending
1507 * on locale settings when the patch was produced we
1508 * don't know what this line looks like. The only
1509 * thing we do know is that it begins with "\ ".
1510 * Checking for 12 is just for sanity check -- any
1511 * l10n of "\ No newline..." is at least that long.
1514 if (len
< 12 || memcmp(line
, "\\ ", 2))
1519 if (oldlines
|| newlines
)
1521 fragment
->leading
= leading
;
1522 fragment
->trailing
= trailing
;
1525 * If a fragment ends with an incomplete line, we failed to include
1526 * it in the above loop because we hit oldlines == newlines == 0
1529 if (12 < size
&& !memcmp(line
, "\\ ", 2))
1530 offset
+= linelen(line
, size
);
1532 patch
->lines_added
+= added
;
1533 patch
->lines_deleted
+= deleted
;
1535 if (0 < patch
->is_new
&& oldlines
)
1536 return error("new file depends on old contents");
1537 if (0 < patch
->is_delete
&& newlines
)
1538 return error("deleted file still has contents");
1542 static int parse_single_patch(char *line
, unsigned long size
, struct patch
*patch
)
1544 unsigned long offset
= 0;
1545 unsigned long oldlines
= 0, newlines
= 0, context
= 0;
1546 struct fragment
**fragp
= &patch
->fragments
;
1548 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
1549 struct fragment
*fragment
;
1552 fragment
= xcalloc(1, sizeof(*fragment
));
1553 fragment
->linenr
= linenr
;
1554 len
= parse_fragment(line
, size
, patch
, fragment
);
1556 die("corrupt patch at line %d", linenr
);
1557 fragment
->patch
= line
;
1558 fragment
->size
= len
;
1559 oldlines
+= fragment
->oldlines
;
1560 newlines
+= fragment
->newlines
;
1561 context
+= fragment
->leading
+ fragment
->trailing
;
1564 fragp
= &fragment
->next
;
1572 * If something was removed (i.e. we have old-lines) it cannot
1573 * be creation, and if something was added it cannot be
1574 * deletion. However, the reverse is not true; --unified=0
1575 * patches that only add are not necessarily creation even
1576 * though they do not have any old lines, and ones that only
1577 * delete are not necessarily deletion.
1579 * Unfortunately, a real creation/deletion patch do _not_ have
1580 * any context line by definition, so we cannot safely tell it
1581 * apart with --unified=0 insanity. At least if the patch has
1582 * more than one hunk it is not creation or deletion.
1584 if (patch
->is_new
< 0 &&
1585 (oldlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1587 if (patch
->is_delete
< 0 &&
1588 (newlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1589 patch
->is_delete
= 0;
1591 if (0 < patch
->is_new
&& oldlines
)
1592 die("new file %s depends on old contents", patch
->new_name
);
1593 if (0 < patch
->is_delete
&& newlines
)
1594 die("deleted file %s still has contents", patch
->old_name
);
1595 if (!patch
->is_delete
&& !newlines
&& context
)
1596 fprintf(stderr
, "** warning: file %s becomes empty but "
1597 "is not deleted\n", patch
->new_name
);
1602 static inline int metadata_changes(struct patch
*patch
)
1604 return patch
->is_rename
> 0 ||
1605 patch
->is_copy
> 0 ||
1606 patch
->is_new
> 0 ||
1608 (patch
->old_mode
&& patch
->new_mode
&&
1609 patch
->old_mode
!= patch
->new_mode
);
1612 static char *inflate_it(const void *data
, unsigned long size
,
1613 unsigned long inflated_size
)
1619 memset(&stream
, 0, sizeof(stream
));
1621 stream
.next_in
= (unsigned char *)data
;
1622 stream
.avail_in
= size
;
1623 stream
.next_out
= out
= xmalloc(inflated_size
);
1624 stream
.avail_out
= inflated_size
;
1625 git_inflate_init(&stream
);
1626 st
= git_inflate(&stream
, Z_FINISH
);
1627 git_inflate_end(&stream
);
1628 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1635 static struct fragment
*parse_binary_hunk(char **buf_p
,
1636 unsigned long *sz_p
,
1641 * Expect a line that begins with binary patch method ("literal"
1642 * or "delta"), followed by the length of data before deflating.
1643 * a sequence of 'length-byte' followed by base-85 encoded data
1644 * should follow, terminated by a newline.
1646 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1647 * and we would limit the patch line to 66 characters,
1648 * so one line can fit up to 13 groups that would decode
1649 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1650 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1653 unsigned long size
= *sz_p
;
1654 char *buffer
= *buf_p
;
1656 unsigned long origlen
;
1659 struct fragment
*frag
;
1661 llen
= linelen(buffer
, size
);
1666 if (!prefixcmp(buffer
, "delta ")) {
1667 patch_method
= BINARY_DELTA_DEFLATED
;
1668 origlen
= strtoul(buffer
+ 6, NULL
, 10);
1670 else if (!prefixcmp(buffer
, "literal ")) {
1671 patch_method
= BINARY_LITERAL_DEFLATED
;
1672 origlen
= strtoul(buffer
+ 8, NULL
, 10);
1680 int byte_length
, max_byte_length
, newsize
;
1681 llen
= linelen(buffer
, size
);
1685 /* consume the blank line */
1691 * Minimum line is "A00000\n" which is 7-byte long,
1692 * and the line length must be multiple of 5 plus 2.
1694 if ((llen
< 7) || (llen
-2) % 5)
1696 max_byte_length
= (llen
- 2) / 5 * 4;
1697 byte_length
= *buffer
;
1698 if ('A' <= byte_length
&& byte_length
<= 'Z')
1699 byte_length
= byte_length
- 'A' + 1;
1700 else if ('a' <= byte_length
&& byte_length
<= 'z')
1701 byte_length
= byte_length
- 'a' + 27;
1704 /* if the input length was not multiple of 4, we would
1705 * have filler at the end but the filler should never
1708 if (max_byte_length
< byte_length
||
1709 byte_length
<= max_byte_length
- 4)
1711 newsize
= hunk_size
+ byte_length
;
1712 data
= xrealloc(data
, newsize
);
1713 if (decode_85(data
+ hunk_size
, buffer
+ 1, byte_length
))
1715 hunk_size
= newsize
;
1720 frag
= xcalloc(1, sizeof(*frag
));
1721 frag
->patch
= inflate_it(data
, hunk_size
, origlen
);
1725 frag
->size
= origlen
;
1729 frag
->binary_patch_method
= patch_method
;
1735 error("corrupt binary patch at line %d: %.*s",
1736 linenr
-1, llen
-1, buffer
);
1740 static int parse_binary(char *buffer
, unsigned long size
, struct patch
*patch
)
1743 * We have read "GIT binary patch\n"; what follows is a line
1744 * that says the patch method (currently, either "literal" or
1745 * "delta") and the length of data before deflating; a
1746 * sequence of 'length-byte' followed by base-85 encoded data
1749 * When a binary patch is reversible, there is another binary
1750 * hunk in the same format, starting with patch method (either
1751 * "literal" or "delta") with the length of data, and a sequence
1752 * of length-byte + base-85 encoded data, terminated with another
1753 * empty line. This data, when applied to the postimage, produces
1756 struct fragment
*forward
;
1757 struct fragment
*reverse
;
1761 forward
= parse_binary_hunk(&buffer
, &size
, &status
, &used
);
1762 if (!forward
&& !status
)
1763 /* there has to be one hunk (forward hunk) */
1764 return error("unrecognized binary patch at line %d", linenr
-1);
1766 /* otherwise we already gave an error message */
1769 reverse
= parse_binary_hunk(&buffer
, &size
, &status
, &used_1
);
1774 * Not having reverse hunk is not an error, but having
1775 * a corrupt reverse hunk is.
1777 free((void*) forward
->patch
);
1781 forward
->next
= reverse
;
1782 patch
->fragments
= forward
;
1783 patch
->is_binary
= 1;
1787 static int parse_chunk(char *buffer
, unsigned long size
, struct patch
*patch
)
1789 int hdrsize
, patchsize
;
1790 int offset
= find_header(buffer
, size
, &hdrsize
, patch
);
1795 patch
->ws_rule
= whitespace_rule(patch
->new_name
1799 patchsize
= parse_single_patch(buffer
+ offset
+ hdrsize
,
1800 size
- offset
- hdrsize
, patch
);
1803 static const char *binhdr
[] = {
1808 static const char git_binary
[] = "GIT binary patch\n";
1810 int hd
= hdrsize
+ offset
;
1811 unsigned long llen
= linelen(buffer
+ hd
, size
- hd
);
1813 if (llen
== sizeof(git_binary
) - 1 &&
1814 !memcmp(git_binary
, buffer
+ hd
, llen
)) {
1817 used
= parse_binary(buffer
+ hd
+ llen
,
1818 size
- hd
- llen
, patch
);
1820 patchsize
= used
+ llen
;
1824 else if (!memcmp(" differ\n", buffer
+ hd
+ llen
- 8, 8)) {
1825 for (i
= 0; binhdr
[i
]; i
++) {
1826 int len
= strlen(binhdr
[i
]);
1827 if (len
< size
- hd
&&
1828 !memcmp(binhdr
[i
], buffer
+ hd
, len
)) {
1830 patch
->is_binary
= 1;
1837 /* Empty patch cannot be applied if it is a text patch
1838 * without metadata change. A binary patch appears
1841 if ((apply
|| check
) &&
1842 (!patch
->is_binary
&& !metadata_changes(patch
)))
1843 die("patch with only garbage at line %d", linenr
);
1846 return offset
+ hdrsize
+ patchsize
;
1849 #define swap(a,b) myswap((a),(b),sizeof(a))
1851 #define myswap(a, b, size) do { \
1852 unsigned char mytmp[size]; \
1853 memcpy(mytmp, &a, size); \
1854 memcpy(&a, &b, size); \
1855 memcpy(&b, mytmp, size); \
1858 static void reverse_patches(struct patch
*p
)
1860 for (; p
; p
= p
->next
) {
1861 struct fragment
*frag
= p
->fragments
;
1863 swap(p
->new_name
, p
->old_name
);
1864 swap(p
->new_mode
, p
->old_mode
);
1865 swap(p
->is_new
, p
->is_delete
);
1866 swap(p
->lines_added
, p
->lines_deleted
);
1867 swap(p
->old_sha1_prefix
, p
->new_sha1_prefix
);
1869 for (; frag
; frag
= frag
->next
) {
1870 swap(frag
->newpos
, frag
->oldpos
);
1871 swap(frag
->newlines
, frag
->oldlines
);
1876 static const char pluses
[] =
1877 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1878 static const char minuses
[]=
1879 "----------------------------------------------------------------------";
1881 static void show_stats(struct patch
*patch
)
1883 struct strbuf qname
= STRBUF_INIT
;
1884 char *cp
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
1887 quote_c_style(cp
, &qname
, NULL
, 0);
1890 * "scale" the filename
1896 if (qname
.len
> max
) {
1897 cp
= strchr(qname
.buf
+ qname
.len
+ 3 - max
, '/');
1899 cp
= qname
.buf
+ qname
.len
+ 3 - max
;
1900 strbuf_splice(&qname
, 0, cp
- qname
.buf
, "...", 3);
1903 if (patch
->is_binary
) {
1904 printf(" %-*s | Bin\n", max
, qname
.buf
);
1905 strbuf_release(&qname
);
1909 printf(" %-*s |", max
, qname
.buf
);
1910 strbuf_release(&qname
);
1913 * scale the add/delete
1915 max
= max
+ max_change
> 70 ? 70 - max
: max_change
;
1916 add
= patch
->lines_added
;
1917 del
= patch
->lines_deleted
;
1919 if (max_change
> 0) {
1920 int total
= ((add
+ del
) * max
+ max_change
/ 2) / max_change
;
1921 add
= (add
* max
+ max_change
/ 2) / max_change
;
1924 printf("%5d %.*s%.*s\n", patch
->lines_added
+ patch
->lines_deleted
,
1925 add
, pluses
, del
, minuses
);
1928 static int read_old_data(struct stat
*st
, const char *path
, struct strbuf
*buf
)
1930 switch (st
->st_mode
& S_IFMT
) {
1932 if (strbuf_readlink(buf
, path
, st
->st_size
) < 0)
1933 return error("unable to read symlink %s", path
);
1936 if (strbuf_read_file(buf
, path
, st
->st_size
) != st
->st_size
)
1937 return error("unable to open or read %s", path
);
1938 convert_to_git(path
, buf
->buf
, buf
->len
, buf
, 0);
1946 * Update the preimage, and the common lines in postimage,
1947 * from buffer buf of length len. If postlen is 0 the postimage
1948 * is updated in place, otherwise it's updated on a new buffer
1952 static void update_pre_post_images(struct image
*preimage
,
1953 struct image
*postimage
,
1955 size_t len
, size_t postlen
)
1958 char *new, *old
, *fixed
;
1959 struct image fixed_preimage
;
1962 * Update the preimage with whitespace fixes. Note that we
1963 * are not losing preimage->buf -- apply_one_fragment() will
1966 prepare_image(&fixed_preimage
, buf
, len
, 1);
1967 assert(fixed_preimage
.nr
== preimage
->nr
);
1968 for (i
= 0; i
< preimage
->nr
; i
++)
1969 fixed_preimage
.line
[i
].flag
= preimage
->line
[i
].flag
;
1970 free(preimage
->line_allocated
);
1971 *preimage
= fixed_preimage
;
1974 * Adjust the common context lines in postimage. This can be
1975 * done in-place when we are just doing whitespace fixing,
1976 * which does not make the string grow, but needs a new buffer
1977 * when ignoring whitespace causes the update, since in this case
1978 * we could have e.g. tabs converted to multiple spaces.
1979 * We trust the caller to tell us if the update can be done
1980 * in place (postlen==0) or not.
1982 old
= postimage
->buf
;
1984 new = postimage
->buf
= xmalloc(postlen
);
1987 fixed
= preimage
->buf
;
1988 for (i
= ctx
= 0; i
< postimage
->nr
; i
++) {
1989 size_t len
= postimage
->line
[i
].len
;
1990 if (!(postimage
->line
[i
].flag
& LINE_COMMON
)) {
1991 /* an added line -- no counterparts in preimage */
1992 memmove(new, old
, len
);
1998 /* a common context -- skip it in the original postimage */
2001 /* and find the corresponding one in the fixed preimage */
2002 while (ctx
< preimage
->nr
&&
2003 !(preimage
->line
[ctx
].flag
& LINE_COMMON
)) {
2004 fixed
+= preimage
->line
[ctx
].len
;
2007 if (preimage
->nr
<= ctx
)
2010 /* and copy it in, while fixing the line length */
2011 len
= preimage
->line
[ctx
].len
;
2012 memcpy(new, fixed
, len
);
2015 postimage
->line
[i
].len
= len
;
2019 /* Fix the length of the whole thing */
2020 postimage
->len
= new - postimage
->buf
;
2023 static int match_fragment(struct image
*img
,
2024 struct image
*preimage
,
2025 struct image
*postimage
,
2029 int match_beginning
, int match_end
)
2032 char *fixed_buf
, *buf
, *orig
, *target
;
2033 struct strbuf fixed
;
2037 if (preimage
->nr
+ try_lno
<= img
->nr
) {
2039 * The hunk falls within the boundaries of img.
2041 preimage_limit
= preimage
->nr
;
2042 if (match_end
&& (preimage
->nr
+ try_lno
!= img
->nr
))
2044 } else if (ws_error_action
== correct_ws_error
&&
2045 (ws_rule
& WS_BLANK_AT_EOF
)) {
2047 * This hunk extends beyond the end of img, and we are
2048 * removing blank lines at the end of the file. This
2049 * many lines from the beginning of the preimage must
2050 * match with img, and the remainder of the preimage
2053 preimage_limit
= img
->nr
- try_lno
;
2056 * The hunk extends beyond the end of the img and
2057 * we are not removing blanks at the end, so we
2058 * should reject the hunk at this position.
2063 if (match_beginning
&& try_lno
)
2066 /* Quick hash check */
2067 for (i
= 0; i
< preimage_limit
; i
++)
2068 if (preimage
->line
[i
].hash
!= img
->line
[try_lno
+ i
].hash
)
2071 if (preimage_limit
== preimage
->nr
) {
2073 * Do we have an exact match? If we were told to match
2074 * at the end, size must be exactly at try+fragsize,
2075 * otherwise try+fragsize must be still within the preimage,
2076 * and either case, the old piece should match the preimage
2080 ? (try + preimage
->len
== img
->len
)
2081 : (try + preimage
->len
<= img
->len
)) &&
2082 !memcmp(img
->buf
+ try, preimage
->buf
, preimage
->len
))
2086 * The preimage extends beyond the end of img, so
2087 * there cannot be an exact match.
2089 * There must be one non-blank context line that match
2090 * a line before the end of img.
2094 buf
= preimage
->buf
;
2096 for (i
= 0; i
< preimage_limit
; i
++)
2097 buf_end
+= preimage
->line
[i
].len
;
2099 for ( ; buf
< buf_end
; buf
++)
2107 * No exact match. If we are ignoring whitespace, run a line-by-line
2108 * fuzzy matching. We collect all the line length information because
2109 * we need it to adjust whitespace if we match.
2111 if (ws_ignore_action
== ignore_ws_change
) {
2114 size_t postlen
= postimage
->len
;
2118 for (i
= 0; i
< preimage_limit
; i
++) {
2119 size_t prelen
= preimage
->line
[i
].len
;
2120 size_t imglen
= img
->line
[try_lno
+i
].len
;
2122 if (!fuzzy_matchlines(img
->buf
+ try + imgoff
, imglen
,
2123 preimage
->buf
+ preoff
, prelen
))
2125 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2126 postlen
+= imglen
- prelen
;
2132 * Ok, the preimage matches with whitespace fuzz.
2134 * imgoff now holds the true length of the target that
2135 * matches the preimage before the end of the file.
2137 * Count the number of characters in the preimage that fall
2138 * beyond the end of the file and make sure that all of them
2139 * are whitespace characters. (This can only happen if
2140 * we are removing blank lines at the end of the file.)
2142 buf
= preimage_eof
= preimage
->buf
+ preoff
;
2143 for ( ; i
< preimage
->nr
; i
++)
2144 preoff
+= preimage
->line
[i
].len
;
2145 preimage_end
= preimage
->buf
+ preoff
;
2146 for ( ; buf
< preimage_end
; buf
++)
2151 * Update the preimage and the common postimage context
2152 * lines to use the same whitespace as the target.
2153 * If whitespace is missing in the target (i.e.
2154 * if the preimage extends beyond the end of the file),
2155 * use the whitespace from the preimage.
2157 extra_chars
= preimage_end
- preimage_eof
;
2158 strbuf_init(&fixed
, imgoff
+ extra_chars
);
2159 strbuf_add(&fixed
, img
->buf
+ try, imgoff
);
2160 strbuf_add(&fixed
, preimage_eof
, extra_chars
);
2161 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2162 update_pre_post_images(preimage
, postimage
,
2163 fixed_buf
, fixed_len
, postlen
);
2167 if (ws_error_action
!= correct_ws_error
)
2171 * The hunk does not apply byte-by-byte, but the hash says
2172 * it might with whitespace fuzz. We haven't been asked to
2173 * ignore whitespace, we were asked to correct whitespace
2174 * errors, so let's try matching after whitespace correction.
2176 * The preimage may extend beyond the end of the file,
2177 * but in this loop we will only handle the part of the
2178 * preimage that falls within the file.
2180 strbuf_init(&fixed
, preimage
->len
+ 1);
2181 orig
= preimage
->buf
;
2182 target
= img
->buf
+ try;
2183 for (i
= 0; i
< preimage_limit
; i
++) {
2184 size_t oldlen
= preimage
->line
[i
].len
;
2185 size_t tgtlen
= img
->line
[try_lno
+ i
].len
;
2186 size_t fixstart
= fixed
.len
;
2187 struct strbuf tgtfix
;
2190 /* Try fixing the line in the preimage */
2191 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2193 /* Try fixing the line in the target */
2194 strbuf_init(&tgtfix
, tgtlen
);
2195 ws_fix_copy(&tgtfix
, target
, tgtlen
, ws_rule
, NULL
);
2198 * If they match, either the preimage was based on
2199 * a version before our tree fixed whitespace breakage,
2200 * or we are lacking a whitespace-fix patch the tree
2201 * the preimage was based on already had (i.e. target
2202 * has whitespace breakage, the preimage doesn't).
2203 * In either case, we are fixing the whitespace breakages
2204 * so we might as well take the fix together with their
2207 match
= (tgtfix
.len
== fixed
.len
- fixstart
&&
2208 !memcmp(tgtfix
.buf
, fixed
.buf
+ fixstart
,
2209 fixed
.len
- fixstart
));
2211 strbuf_release(&tgtfix
);
2221 * Now handle the lines in the preimage that falls beyond the
2222 * end of the file (if any). They will only match if they are
2223 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2226 for ( ; i
< preimage
->nr
; i
++) {
2227 size_t fixstart
= fixed
.len
; /* start of the fixed preimage */
2228 size_t oldlen
= preimage
->line
[i
].len
;
2231 /* Try fixing the line in the preimage */
2232 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2234 for (j
= fixstart
; j
< fixed
.len
; j
++)
2235 if (!isspace(fixed
.buf
[j
]))
2242 * Yes, the preimage is based on an older version that still
2243 * has whitespace breakages unfixed, and fixing them makes the
2244 * hunk match. Update the context lines in the postimage.
2246 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2247 update_pre_post_images(preimage
, postimage
,
2248 fixed_buf
, fixed_len
, 0);
2252 strbuf_release(&fixed
);
2256 static int find_pos(struct image
*img
,
2257 struct image
*preimage
,
2258 struct image
*postimage
,
2261 int match_beginning
, int match_end
)
2264 unsigned long backwards
, forwards
, try;
2265 int backwards_lno
, forwards_lno
, try_lno
;
2268 * If match_beginning or match_end is specified, there is no
2269 * point starting from a wrong line that will never match and
2270 * wander around and wait for a match at the specified end.
2272 if (match_beginning
)
2275 line
= img
->nr
- preimage
->nr
;
2278 * Because the comparison is unsigned, the following test
2279 * will also take care of a negative line number that can
2280 * result when match_end and preimage is larger than the target.
2282 if ((size_t) line
> img
->nr
)
2286 for (i
= 0; i
< line
; i
++)
2287 try += img
->line
[i
].len
;
2290 * There's probably some smart way to do this, but I'll leave
2291 * that to the smart and beautiful people. I'm simple and stupid.
2294 backwards_lno
= line
;
2296 forwards_lno
= line
;
2299 for (i
= 0; ; i
++) {
2300 if (match_fragment(img
, preimage
, postimage
,
2301 try, try_lno
, ws_rule
,
2302 match_beginning
, match_end
))
2306 if (backwards_lno
== 0 && forwards_lno
== img
->nr
)
2310 if (backwards_lno
== 0) {
2315 backwards
-= img
->line
[backwards_lno
].len
;
2317 try_lno
= backwards_lno
;
2319 if (forwards_lno
== img
->nr
) {
2323 forwards
+= img
->line
[forwards_lno
].len
;
2326 try_lno
= forwards_lno
;
2333 static void remove_first_line(struct image
*img
)
2335 img
->buf
+= img
->line
[0].len
;
2336 img
->len
-= img
->line
[0].len
;
2341 static void remove_last_line(struct image
*img
)
2343 img
->len
-= img
->line
[--img
->nr
].len
;
2346 static void update_image(struct image
*img
,
2348 struct image
*preimage
,
2349 struct image
*postimage
)
2352 * remove the copy of preimage at offset in img
2353 * and replace it with postimage
2356 size_t remove_count
, insert_count
, applied_at
= 0;
2361 * If we are removing blank lines at the end of img,
2362 * the preimage may extend beyond the end.
2363 * If that is the case, we must be careful only to
2364 * remove the part of the preimage that falls within
2365 * the boundaries of img. Initialize preimage_limit
2366 * to the number of lines in the preimage that falls
2367 * within the boundaries.
2369 preimage_limit
= preimage
->nr
;
2370 if (preimage_limit
> img
->nr
- applied_pos
)
2371 preimage_limit
= img
->nr
- applied_pos
;
2373 for (i
= 0; i
< applied_pos
; i
++)
2374 applied_at
+= img
->line
[i
].len
;
2377 for (i
= 0; i
< preimage_limit
; i
++)
2378 remove_count
+= img
->line
[applied_pos
+ i
].len
;
2379 insert_count
= postimage
->len
;
2381 /* Adjust the contents */
2382 result
= xmalloc(img
->len
+ insert_count
- remove_count
+ 1);
2383 memcpy(result
, img
->buf
, applied_at
);
2384 memcpy(result
+ applied_at
, postimage
->buf
, postimage
->len
);
2385 memcpy(result
+ applied_at
+ postimage
->len
,
2386 img
->buf
+ (applied_at
+ remove_count
),
2387 img
->len
- (applied_at
+ remove_count
));
2390 img
->len
+= insert_count
- remove_count
;
2391 result
[img
->len
] = '\0';
2393 /* Adjust the line table */
2394 nr
= img
->nr
+ postimage
->nr
- preimage_limit
;
2395 if (preimage_limit
< postimage
->nr
) {
2397 * NOTE: this knows that we never call remove_first_line()
2398 * on anything other than pre/post image.
2400 img
->line
= xrealloc(img
->line
, nr
* sizeof(*img
->line
));
2401 img
->line_allocated
= img
->line
;
2403 if (preimage_limit
!= postimage
->nr
)
2404 memmove(img
->line
+ applied_pos
+ postimage
->nr
,
2405 img
->line
+ applied_pos
+ preimage_limit
,
2406 (img
->nr
- (applied_pos
+ preimage_limit
)) *
2407 sizeof(*img
->line
));
2408 memcpy(img
->line
+ applied_pos
,
2410 postimage
->nr
* sizeof(*img
->line
));
2414 static int apply_one_fragment(struct image
*img
, struct fragment
*frag
,
2415 int inaccurate_eof
, unsigned ws_rule
)
2417 int match_beginning
, match_end
;
2418 const char *patch
= frag
->patch
;
2419 int size
= frag
->size
;
2420 char *old
, *oldlines
;
2421 struct strbuf newlines
;
2422 int new_blank_lines_at_end
= 0;
2423 unsigned long leading
, trailing
;
2424 int pos
, applied_pos
;
2425 struct image preimage
;
2426 struct image postimage
;
2428 memset(&preimage
, 0, sizeof(preimage
));
2429 memset(&postimage
, 0, sizeof(postimage
));
2430 oldlines
= xmalloc(size
);
2431 strbuf_init(&newlines
, size
);
2436 int len
= linelen(patch
, size
);
2438 int added_blank_line
= 0;
2439 int is_blank_context
= 0;
2446 * "plen" is how much of the line we should use for
2447 * the actual patch data. Normally we just remove the
2448 * first character on the line, but if the line is
2449 * followed by "\ No newline", then we also remove the
2450 * last one (which is the newline, of course).
2453 if (len
< size
&& patch
[len
] == '\\')
2456 if (apply_in_reverse
) {
2459 else if (first
== '+')
2465 /* Newer GNU diff, empty context line */
2467 /* ... followed by '\No newline'; nothing */
2470 strbuf_addch(&newlines
, '\n');
2471 add_line_info(&preimage
, "\n", 1, LINE_COMMON
);
2472 add_line_info(&postimage
, "\n", 1, LINE_COMMON
);
2473 is_blank_context
= 1;
2476 if (plen
&& (ws_rule
& WS_BLANK_AT_EOF
) &&
2477 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2478 is_blank_context
= 1;
2480 memcpy(old
, patch
+ 1, plen
);
2481 add_line_info(&preimage
, old
, plen
,
2482 (first
== ' ' ? LINE_COMMON
: 0));
2486 /* Fall-through for ' ' */
2488 /* --no-add does not add new lines */
2489 if (first
== '+' && no_add
)
2492 start
= newlines
.len
;
2494 !whitespace_error
||
2495 ws_error_action
!= correct_ws_error
) {
2496 strbuf_add(&newlines
, patch
+ 1, plen
);
2499 ws_fix_copy(&newlines
, patch
+ 1, plen
, ws_rule
, &applied_after_fixing_ws
);
2501 add_line_info(&postimage
, newlines
.buf
+ start
, newlines
.len
- start
,
2502 (first
== '+' ? 0 : LINE_COMMON
));
2504 (ws_rule
& WS_BLANK_AT_EOF
) &&
2505 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2506 added_blank_line
= 1;
2508 case '@': case '\\':
2509 /* Ignore it, we already handled it */
2512 if (apply_verbosely
)
2513 error("invalid start of line: '%c'", first
);
2516 if (added_blank_line
)
2517 new_blank_lines_at_end
++;
2518 else if (is_blank_context
)
2521 new_blank_lines_at_end
= 0;
2525 if (inaccurate_eof
&&
2526 old
> oldlines
&& old
[-1] == '\n' &&
2527 newlines
.len
> 0 && newlines
.buf
[newlines
.len
- 1] == '\n') {
2529 strbuf_setlen(&newlines
, newlines
.len
- 1);
2532 leading
= frag
->leading
;
2533 trailing
= frag
->trailing
;
2536 * A hunk to change lines at the beginning would begin with
2538 * but we need to be careful. -U0 that inserts before the second
2539 * line also has this pattern.
2541 * And a hunk to add to an empty file would begin with
2544 * In other words, a hunk that is (frag->oldpos <= 1) with or
2545 * without leading context must match at the beginning.
2547 match_beginning
= (!frag
->oldpos
||
2548 (frag
->oldpos
== 1 && !unidiff_zero
));
2551 * A hunk without trailing lines must match at the end.
2552 * However, we simply cannot tell if a hunk must match end
2553 * from the lack of trailing lines if the patch was generated
2554 * with unidiff without any context.
2556 match_end
= !unidiff_zero
&& !trailing
;
2558 pos
= frag
->newpos
? (frag
->newpos
- 1) : 0;
2559 preimage
.buf
= oldlines
;
2560 preimage
.len
= old
- oldlines
;
2561 postimage
.buf
= newlines
.buf
;
2562 postimage
.len
= newlines
.len
;
2563 preimage
.line
= preimage
.line_allocated
;
2564 postimage
.line
= postimage
.line_allocated
;
2568 applied_pos
= find_pos(img
, &preimage
, &postimage
, pos
,
2569 ws_rule
, match_beginning
, match_end
);
2571 if (applied_pos
>= 0)
2574 /* Am I at my context limits? */
2575 if ((leading
<= p_context
) && (trailing
<= p_context
))
2577 if (match_beginning
|| match_end
) {
2578 match_beginning
= match_end
= 0;
2583 * Reduce the number of context lines; reduce both
2584 * leading and trailing if they are equal otherwise
2585 * just reduce the larger context.
2587 if (leading
>= trailing
) {
2588 remove_first_line(&preimage
);
2589 remove_first_line(&postimage
);
2593 if (trailing
> leading
) {
2594 remove_last_line(&preimage
);
2595 remove_last_line(&postimage
);
2600 if (applied_pos
>= 0) {
2601 if (new_blank_lines_at_end
&&
2602 preimage
.nr
+ applied_pos
>= img
->nr
&&
2603 (ws_rule
& WS_BLANK_AT_EOF
) &&
2604 ws_error_action
!= nowarn_ws_error
) {
2605 record_ws_error(WS_BLANK_AT_EOF
, "+", 1, frag
->linenr
);
2606 if (ws_error_action
== correct_ws_error
) {
2607 while (new_blank_lines_at_end
--)
2608 remove_last_line(&postimage
);
2611 * We would want to prevent write_out_results()
2612 * from taking place in apply_patch() that follows
2613 * the callchain led us here, which is:
2614 * apply_patch->check_patch_list->check_patch->
2615 * apply_data->apply_fragments->apply_one_fragment
2617 if (ws_error_action
== die_on_ws_error
)
2622 * Warn if it was necessary to reduce the number
2625 if ((leading
!= frag
->leading
) ||
2626 (trailing
!= frag
->trailing
))
2627 fprintf(stderr
, "Context reduced to (%ld/%ld)"
2628 " to apply fragment at %d\n",
2629 leading
, trailing
, applied_pos
+1);
2630 update_image(img
, applied_pos
, &preimage
, &postimage
);
2632 if (apply_verbosely
)
2633 error("while searching for:\n%.*s",
2634 (int)(old
- oldlines
), oldlines
);
2638 strbuf_release(&newlines
);
2639 free(preimage
.line_allocated
);
2640 free(postimage
.line_allocated
);
2642 return (applied_pos
< 0);
2645 static int apply_binary_fragment(struct image
*img
, struct patch
*patch
)
2647 struct fragment
*fragment
= patch
->fragments
;
2651 /* Binary patch is irreversible without the optional second hunk */
2652 if (apply_in_reverse
) {
2653 if (!fragment
->next
)
2654 return error("cannot reverse-apply a binary patch "
2655 "without the reverse hunk to '%s'",
2657 ? patch
->new_name
: patch
->old_name
);
2658 fragment
= fragment
->next
;
2660 switch (fragment
->binary_patch_method
) {
2661 case BINARY_DELTA_DEFLATED
:
2662 dst
= patch_delta(img
->buf
, img
->len
, fragment
->patch
,
2663 fragment
->size
, &len
);
2670 case BINARY_LITERAL_DEFLATED
:
2672 img
->len
= fragment
->size
;
2673 img
->buf
= xmalloc(img
->len
+1);
2674 memcpy(img
->buf
, fragment
->patch
, img
->len
);
2675 img
->buf
[img
->len
] = '\0';
2681 static int apply_binary(struct image
*img
, struct patch
*patch
)
2683 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
2684 unsigned char sha1
[20];
2687 * For safety, we require patch index line to contain
2688 * full 40-byte textual SHA1 for old and new, at least for now.
2690 if (strlen(patch
->old_sha1_prefix
) != 40 ||
2691 strlen(patch
->new_sha1_prefix
) != 40 ||
2692 get_sha1_hex(patch
->old_sha1_prefix
, sha1
) ||
2693 get_sha1_hex(patch
->new_sha1_prefix
, sha1
))
2694 return error("cannot apply binary patch to '%s' "
2695 "without full index line", name
);
2697 if (patch
->old_name
) {
2699 * See if the old one matches what the patch
2702 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
2703 if (strcmp(sha1_to_hex(sha1
), patch
->old_sha1_prefix
))
2704 return error("the patch applies to '%s' (%s), "
2705 "which does not match the "
2706 "current contents.",
2707 name
, sha1_to_hex(sha1
));
2710 /* Otherwise, the old one must be empty. */
2712 return error("the patch applies to an empty "
2713 "'%s' but it is not empty", name
);
2716 get_sha1_hex(patch
->new_sha1_prefix
, sha1
);
2717 if (is_null_sha1(sha1
)) {
2719 return 0; /* deletion patch */
2722 if (has_sha1_file(sha1
)) {
2723 /* We already have the postimage */
2724 enum object_type type
;
2728 result
= read_sha1_file(sha1
, &type
, &size
);
2730 return error("the necessary postimage %s for "
2731 "'%s' cannot be read",
2732 patch
->new_sha1_prefix
, name
);
2738 * We have verified buf matches the preimage;
2739 * apply the patch data to it, which is stored
2740 * in the patch->fragments->{patch,size}.
2742 if (apply_binary_fragment(img
, patch
))
2743 return error("binary patch does not apply to '%s'",
2746 /* verify that the result matches */
2747 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
2748 if (strcmp(sha1_to_hex(sha1
), patch
->new_sha1_prefix
))
2749 return error("binary patch to '%s' creates incorrect result (expecting %s, got %s)",
2750 name
, patch
->new_sha1_prefix
, sha1_to_hex(sha1
));
2756 static int apply_fragments(struct image
*img
, struct patch
*patch
)
2758 struct fragment
*frag
= patch
->fragments
;
2759 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
2760 unsigned ws_rule
= patch
->ws_rule
;
2761 unsigned inaccurate_eof
= patch
->inaccurate_eof
;
2763 if (patch
->is_binary
)
2764 return apply_binary(img
, patch
);
2767 if (apply_one_fragment(img
, frag
, inaccurate_eof
, ws_rule
)) {
2768 error("patch failed: %s:%ld", name
, frag
->oldpos
);
2769 if (!apply_with_reject
)
2778 static int read_file_or_gitlink(struct cache_entry
*ce
, struct strbuf
*buf
)
2783 if (S_ISGITLINK(ce
->ce_mode
)) {
2784 strbuf_grow(buf
, 100);
2785 strbuf_addf(buf
, "Subproject commit %s\n", sha1_to_hex(ce
->sha1
));
2787 enum object_type type
;
2791 result
= read_sha1_file(ce
->sha1
, &type
, &sz
);
2794 /* XXX read_sha1_file NUL-terminates */
2795 strbuf_attach(buf
, result
, sz
, sz
+ 1);
2800 static struct patch
*in_fn_table(const char *name
)
2802 struct string_list_item
*item
;
2807 item
= string_list_lookup(&fn_table
, name
);
2809 return (struct patch
*)item
->util
;
2815 * item->util in the filename table records the status of the path.
2816 * Usually it points at a patch (whose result records the contents
2817 * of it after applying it), but it could be PATH_WAS_DELETED for a
2818 * path that a previously applied patch has already removed.
2820 #define PATH_TO_BE_DELETED ((struct patch *) -2)
2821 #define PATH_WAS_DELETED ((struct patch *) -1)
2823 static int to_be_deleted(struct patch
*patch
)
2825 return patch
== PATH_TO_BE_DELETED
;
2828 static int was_deleted(struct patch
*patch
)
2830 return patch
== PATH_WAS_DELETED
;
2833 static void add_to_fn_table(struct patch
*patch
)
2835 struct string_list_item
*item
;
2838 * Always add new_name unless patch is a deletion
2839 * This should cover the cases for normal diffs,
2840 * file creations and copies
2842 if (patch
->new_name
!= NULL
) {
2843 item
= string_list_insert(&fn_table
, patch
->new_name
);
2848 * store a failure on rename/deletion cases because
2849 * later chunks shouldn't patch old names
2851 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
2852 item
= string_list_insert(&fn_table
, patch
->old_name
);
2853 item
->util
= PATH_WAS_DELETED
;
2857 static void prepare_fn_table(struct patch
*patch
)
2860 * store information about incoming file deletion
2863 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
2864 struct string_list_item
*item
;
2865 item
= string_list_insert(&fn_table
, patch
->old_name
);
2866 item
->util
= PATH_TO_BE_DELETED
;
2868 patch
= patch
->next
;
2872 static int apply_data(struct patch
*patch
, struct stat
*st
, struct cache_entry
*ce
)
2874 struct strbuf buf
= STRBUF_INIT
;
2878 struct patch
*tpatch
;
2880 if (!(patch
->is_copy
|| patch
->is_rename
) &&
2881 (tpatch
= in_fn_table(patch
->old_name
)) != NULL
&& !to_be_deleted(tpatch
)) {
2882 if (was_deleted(tpatch
)) {
2883 return error("patch %s has been renamed/deleted",
2886 /* We have a patched copy in memory use that */
2887 strbuf_add(&buf
, tpatch
->result
, tpatch
->resultsize
);
2888 } else if (cached
) {
2889 if (read_file_or_gitlink(ce
, &buf
))
2890 return error("read of %s failed", patch
->old_name
);
2891 } else if (patch
->old_name
) {
2892 if (S_ISGITLINK(patch
->old_mode
)) {
2894 read_file_or_gitlink(ce
, &buf
);
2897 * There is no way to apply subproject
2898 * patch without looking at the index.
2900 patch
->fragments
= NULL
;
2903 if (read_old_data(st
, patch
->old_name
, &buf
))
2904 return error("read of %s failed", patch
->old_name
);
2908 img
= strbuf_detach(&buf
, &len
);
2909 prepare_image(&image
, img
, len
, !patch
->is_binary
);
2911 if (apply_fragments(&image
, patch
) < 0)
2912 return -1; /* note with --reject this succeeds. */
2913 patch
->result
= image
.buf
;
2914 patch
->resultsize
= image
.len
;
2915 add_to_fn_table(patch
);
2916 free(image
.line_allocated
);
2918 if (0 < patch
->is_delete
&& patch
->resultsize
)
2919 return error("removal patch leaves file contents");
2924 static int check_to_create_blob(const char *new_name
, int ok_if_exists
)
2927 if (!lstat(new_name
, &nst
)) {
2928 if (S_ISDIR(nst
.st_mode
) || ok_if_exists
)
2931 * A leading component of new_name might be a symlink
2932 * that is going to be removed with this patch, but
2933 * still pointing at somewhere that has the path.
2934 * In such a case, path "new_name" does not exist as
2935 * far as git is concerned.
2937 if (has_symlink_leading_path(new_name
, strlen(new_name
)))
2940 return error("%s: already exists in working directory", new_name
);
2942 else if ((errno
!= ENOENT
) && (errno
!= ENOTDIR
))
2943 return error("%s: %s", new_name
, strerror(errno
));
2947 static int verify_index_match(struct cache_entry
*ce
, struct stat
*st
)
2949 if (S_ISGITLINK(ce
->ce_mode
)) {
2950 if (!S_ISDIR(st
->st_mode
))
2954 return ce_match_stat(ce
, st
, CE_MATCH_IGNORE_VALID
|CE_MATCH_IGNORE_SKIP_WORKTREE
);
2957 static int check_preimage(struct patch
*patch
, struct cache_entry
**ce
, struct stat
*st
)
2959 const char *old_name
= patch
->old_name
;
2960 struct patch
*tpatch
= NULL
;
2962 unsigned st_mode
= 0;
2965 * Make sure that we do not have local modifications from the
2966 * index when we are looking at the index. Also make sure
2967 * we have the preimage file to be patched in the work tree,
2968 * unless --cached, which tells git to apply only in the index.
2973 assert(patch
->is_new
<= 0);
2975 if (!(patch
->is_copy
|| patch
->is_rename
) &&
2976 (tpatch
= in_fn_table(old_name
)) != NULL
&& !to_be_deleted(tpatch
)) {
2977 if (was_deleted(tpatch
))
2978 return error("%s: has been deleted/renamed", old_name
);
2979 st_mode
= tpatch
->new_mode
;
2980 } else if (!cached
) {
2981 stat_ret
= lstat(old_name
, st
);
2982 if (stat_ret
&& errno
!= ENOENT
)
2983 return error("%s: %s", old_name
, strerror(errno
));
2986 if (to_be_deleted(tpatch
))
2989 if (check_index
&& !tpatch
) {
2990 int pos
= cache_name_pos(old_name
, strlen(old_name
));
2992 if (patch
->is_new
< 0)
2994 return error("%s: does not exist in index", old_name
);
2996 *ce
= active_cache
[pos
];
2998 struct checkout costate
;
3000 memset(&costate
, 0, sizeof(costate
));
3001 costate
.base_dir
= "";
3002 costate
.refresh_cache
= 1;
3003 if (checkout_entry(*ce
, &costate
, NULL
) ||
3004 lstat(old_name
, st
))
3007 if (!cached
&& verify_index_match(*ce
, st
))
3008 return error("%s: does not match index", old_name
);
3010 st_mode
= (*ce
)->ce_mode
;
3011 } else if (stat_ret
< 0) {
3012 if (patch
->is_new
< 0)
3014 return error("%s: %s", old_name
, strerror(errno
));
3017 if (!cached
&& !tpatch
)
3018 st_mode
= ce_mode_from_stat(*ce
, st
->st_mode
);
3020 if (patch
->is_new
< 0)
3022 if (!patch
->old_mode
)
3023 patch
->old_mode
= st_mode
;
3024 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
3025 return error("%s: wrong type", old_name
);
3026 if (st_mode
!= patch
->old_mode
)
3027 warning("%s has type %o, expected %o",
3028 old_name
, st_mode
, patch
->old_mode
);
3029 if (!patch
->new_mode
&& !patch
->is_delete
)
3030 patch
->new_mode
= st_mode
;
3035 patch
->is_delete
= 0;
3036 patch
->old_name
= NULL
;
3040 static int check_patch(struct patch
*patch
)
3043 const char *old_name
= patch
->old_name
;
3044 const char *new_name
= patch
->new_name
;
3045 const char *name
= old_name
? old_name
: new_name
;
3046 struct cache_entry
*ce
= NULL
;
3047 struct patch
*tpatch
;
3051 patch
->rejected
= 1; /* we will drop this after we succeed */
3053 status
= check_preimage(patch
, &ce
, &st
);
3056 old_name
= patch
->old_name
;
3058 if ((tpatch
= in_fn_table(new_name
)) &&
3059 (was_deleted(tpatch
) || to_be_deleted(tpatch
)))
3061 * A type-change diff is always split into a patch to
3062 * delete old, immediately followed by a patch to
3063 * create new (see diff.c::run_diff()); in such a case
3064 * it is Ok that the entry to be deleted by the
3065 * previous patch is still in the working tree and in
3073 ((0 < patch
->is_new
) | (0 < patch
->is_rename
) | patch
->is_copy
)) {
3075 cache_name_pos(new_name
, strlen(new_name
)) >= 0 &&
3077 return error("%s: already exists in index", new_name
);
3079 int err
= check_to_create_blob(new_name
, ok_if_exists
);
3083 if (!patch
->new_mode
) {
3084 if (0 < patch
->is_new
)
3085 patch
->new_mode
= S_IFREG
| 0644;
3087 patch
->new_mode
= patch
->old_mode
;
3091 if (new_name
&& old_name
) {
3092 int same
= !strcmp(old_name
, new_name
);
3093 if (!patch
->new_mode
)
3094 patch
->new_mode
= patch
->old_mode
;
3095 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
)
3096 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
3097 patch
->new_mode
, new_name
, patch
->old_mode
,
3098 same
? "" : " of ", same
? "" : old_name
);
3101 if (apply_data(patch
, &st
, ce
) < 0)
3102 return error("%s: patch does not apply", name
);
3103 patch
->rejected
= 0;
3107 static int check_patch_list(struct patch
*patch
)
3111 prepare_fn_table(patch
);
3113 if (apply_verbosely
)
3114 say_patch_name(stderr
,
3115 "Checking patch ", patch
, "...\n");
3116 err
|= check_patch(patch
);
3117 patch
= patch
->next
;
3122 /* This function tries to read the sha1 from the current index */
3123 static int get_current_sha1(const char *path
, unsigned char *sha1
)
3127 if (read_cache() < 0)
3129 pos
= cache_name_pos(path
, strlen(path
));
3132 hashcpy(sha1
, active_cache
[pos
]->sha1
);
3136 /* Build an index that contains the just the files needed for a 3way merge */
3137 static void build_fake_ancestor(struct patch
*list
, const char *filename
)
3139 struct patch
*patch
;
3140 struct index_state result
= { NULL
};
3143 /* Once we start supporting the reverse patch, it may be
3144 * worth showing the new sha1 prefix, but until then...
3146 for (patch
= list
; patch
; patch
= patch
->next
) {
3147 const unsigned char *sha1_ptr
;
3148 unsigned char sha1
[20];
3149 struct cache_entry
*ce
;
3152 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3153 if (0 < patch
->is_new
)
3155 else if (get_sha1(patch
->old_sha1_prefix
, sha1
))
3156 /* git diff has no index line for mode/type changes */
3157 if (!patch
->lines_added
&& !patch
->lines_deleted
) {
3158 if (get_current_sha1(patch
->old_name
, sha1
))
3159 die("mode change for %s, which is not "
3160 "in current HEAD", name
);
3163 die("sha1 information is lacking or useless "
3168 ce
= make_cache_entry(patch
->old_mode
, sha1_ptr
, name
, 0, 0);
3170 die("make_cache_entry failed for path '%s'", name
);
3171 if (add_index_entry(&result
, ce
, ADD_CACHE_OK_TO_ADD
))
3172 die ("Could not add %s to temporary index", name
);
3175 fd
= open(filename
, O_WRONLY
| O_CREAT
, 0666);
3176 if (fd
< 0 || write_index(&result
, fd
) || close(fd
))
3177 die ("Could not write temporary index to %s", filename
);
3179 discard_index(&result
);
3182 static void stat_patch_list(struct patch
*patch
)
3184 int files
, adds
, dels
;
3186 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
3188 adds
+= patch
->lines_added
;
3189 dels
+= patch
->lines_deleted
;
3193 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files
, adds
, dels
);
3196 static void numstat_patch_list(struct patch
*patch
)
3198 for ( ; patch
; patch
= patch
->next
) {
3200 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
3201 if (patch
->is_binary
)
3204 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
3205 write_name_quoted(name
, stdout
, line_termination
);
3209 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
3212 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
3214 printf(" %s %s\n", newdelete
, name
);
3217 static void show_mode_change(struct patch
*p
, int show_name
)
3219 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
3221 printf(" mode change %06o => %06o %s\n",
3222 p
->old_mode
, p
->new_mode
, p
->new_name
);
3224 printf(" mode change %06o => %06o\n",
3225 p
->old_mode
, p
->new_mode
);
3229 static void show_rename_copy(struct patch
*p
)
3231 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
3232 const char *old
, *new;
3234 /* Find common prefix */
3238 const char *slash_old
, *slash_new
;
3239 slash_old
= strchr(old
, '/');
3240 slash_new
= strchr(new, '/');
3243 slash_old
- old
!= slash_new
- new ||
3244 memcmp(old
, new, slash_new
- new))
3246 old
= slash_old
+ 1;
3247 new = slash_new
+ 1;
3249 /* p->old_name thru old is the common prefix, and old and new
3250 * through the end of names are renames
3252 if (old
!= p
->old_name
)
3253 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
3254 (int)(old
- p
->old_name
), p
->old_name
,
3255 old
, new, p
->score
);
3257 printf(" %s %s => %s (%d%%)\n", renamecopy
,
3258 p
->old_name
, p
->new_name
, p
->score
);
3259 show_mode_change(p
, 0);
3262 static void summary_patch_list(struct patch
*patch
)
3266 for (p
= patch
; p
; p
= p
->next
) {
3268 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
3269 else if (p
->is_delete
)
3270 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
3272 if (p
->is_rename
|| p
->is_copy
)
3273 show_rename_copy(p
);
3276 printf(" rewrite %s (%d%%)\n",
3277 p
->new_name
, p
->score
);
3278 show_mode_change(p
, 0);
3281 show_mode_change(p
, 1);
3287 static void patch_stats(struct patch
*patch
)
3289 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
3291 if (lines
> max_change
)
3293 if (patch
->old_name
) {
3294 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
3296 len
= strlen(patch
->old_name
);
3300 if (patch
->new_name
) {
3301 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
3303 len
= strlen(patch
->new_name
);
3309 static void remove_file(struct patch
*patch
, int rmdir_empty
)
3312 if (remove_file_from_cache(patch
->old_name
) < 0)
3313 die("unable to remove %s from index", patch
->old_name
);
3316 if (!remove_or_warn(patch
->old_mode
, patch
->old_name
) && rmdir_empty
) {
3317 remove_path(patch
->old_name
);
3322 static void add_index_file(const char *path
, unsigned mode
, void *buf
, unsigned long size
)
3325 struct cache_entry
*ce
;
3326 int namelen
= strlen(path
);
3327 unsigned ce_size
= cache_entry_size(namelen
);
3332 ce
= xcalloc(1, ce_size
);
3333 memcpy(ce
->name
, path
, namelen
);
3334 ce
->ce_mode
= create_ce_mode(mode
);
3335 ce
->ce_flags
= namelen
;
3336 if (S_ISGITLINK(mode
)) {
3337 const char *s
= buf
;
3339 if (get_sha1_hex(s
+ strlen("Subproject commit "), ce
->sha1
))
3340 die("corrupt patch for subproject %s", path
);
3343 if (lstat(path
, &st
) < 0)
3344 die_errno("unable to stat newly created file '%s'",
3346 fill_stat_cache_info(ce
, &st
);
3348 if (write_sha1_file(buf
, size
, blob_type
, ce
->sha1
) < 0)
3349 die("unable to create backing store for newly created file %s", path
);
3351 if (add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
) < 0)
3352 die("unable to add cache entry for %s", path
);
3355 static int try_create_file(const char *path
, unsigned int mode
, const char *buf
, unsigned long size
)
3358 struct strbuf nbuf
= STRBUF_INIT
;
3360 if (S_ISGITLINK(mode
)) {
3362 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
))
3364 return mkdir(path
, 0777);
3367 if (has_symlinks
&& S_ISLNK(mode
))
3368 /* Although buf:size is counted string, it also is NUL
3371 return symlink(buf
, path
);
3373 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
3377 if (convert_to_working_tree(path
, buf
, size
, &nbuf
)) {
3381 write_or_die(fd
, buf
, size
);
3382 strbuf_release(&nbuf
);
3385 die_errno("closing file '%s'", path
);
3390 * We optimistically assume that the directories exist,
3391 * which is true 99% of the time anyway. If they don't,
3392 * we create them and try again.
3394 static void create_one_file(char *path
, unsigned mode
, const char *buf
, unsigned long size
)
3398 if (!try_create_file(path
, mode
, buf
, size
))
3401 if (errno
== ENOENT
) {
3402 if (safe_create_leading_directories(path
))
3404 if (!try_create_file(path
, mode
, buf
, size
))
3408 if (errno
== EEXIST
|| errno
== EACCES
) {
3409 /* We may be trying to create a file where a directory
3413 if (!lstat(path
, &st
) && (!S_ISDIR(st
.st_mode
) || !rmdir(path
)))
3417 if (errno
== EEXIST
) {
3418 unsigned int nr
= getpid();
3421 char newpath
[PATH_MAX
];
3422 mksnpath(newpath
, sizeof(newpath
), "%s~%u", path
, nr
);
3423 if (!try_create_file(newpath
, mode
, buf
, size
)) {
3424 if (!rename(newpath
, path
))
3426 unlink_or_warn(newpath
);
3429 if (errno
!= EEXIST
)
3434 die_errno("unable to write file '%s' mode %o", path
, mode
);
3437 static void create_file(struct patch
*patch
)
3439 char *path
= patch
->new_name
;
3440 unsigned mode
= patch
->new_mode
;
3441 unsigned long size
= patch
->resultsize
;
3442 char *buf
= patch
->result
;
3445 mode
= S_IFREG
| 0644;
3446 create_one_file(path
, mode
, buf
, size
);
3447 add_index_file(path
, mode
, buf
, size
);
3450 /* phase zero is to remove, phase one is to create */
3451 static void write_out_one_result(struct patch
*patch
, int phase
)
3453 if (patch
->is_delete
> 0) {
3455 remove_file(patch
, 1);
3458 if (patch
->is_new
> 0 || patch
->is_copy
) {
3464 * Rename or modification boils down to the same
3465 * thing: remove the old, write the new
3468 remove_file(patch
, patch
->is_rename
);
3473 static int write_out_one_reject(struct patch
*patch
)
3476 char namebuf
[PATH_MAX
];
3477 struct fragment
*frag
;
3480 for (cnt
= 0, frag
= patch
->fragments
; frag
; frag
= frag
->next
) {
3481 if (!frag
->rejected
)
3487 if (apply_verbosely
)
3488 say_patch_name(stderr
,
3489 "Applied patch ", patch
, " cleanly.\n");
3493 /* This should not happen, because a removal patch that leaves
3494 * contents are marked "rejected" at the patch level.
3496 if (!patch
->new_name
)
3497 die("internal error");
3499 /* Say this even without --verbose */
3500 say_patch_name(stderr
, "Applying patch ", patch
, " with");
3501 fprintf(stderr
, " %d rejects...\n", cnt
);
3503 cnt
= strlen(patch
->new_name
);
3504 if (ARRAY_SIZE(namebuf
) <= cnt
+ 5) {
3505 cnt
= ARRAY_SIZE(namebuf
) - 5;
3506 warning("truncating .rej filename to %.*s.rej",
3507 cnt
- 1, patch
->new_name
);
3509 memcpy(namebuf
, patch
->new_name
, cnt
);
3510 memcpy(namebuf
+ cnt
, ".rej", 5);
3512 rej
= fopen(namebuf
, "w");
3514 return error("cannot open %s: %s", namebuf
, strerror(errno
));
3516 /* Normal git tools never deal with .rej, so do not pretend
3517 * this is a git patch by saying --git nor give extended
3518 * headers. While at it, maybe please "kompare" that wants
3519 * the trailing TAB and some garbage at the end of line ;-).
3521 fprintf(rej
, "diff a/%s b/%s\t(rejected hunks)\n",
3522 patch
->new_name
, patch
->new_name
);
3523 for (cnt
= 1, frag
= patch
->fragments
;
3525 cnt
++, frag
= frag
->next
) {
3526 if (!frag
->rejected
) {
3527 fprintf(stderr
, "Hunk #%d applied cleanly.\n", cnt
);
3530 fprintf(stderr
, "Rejected hunk #%d.\n", cnt
);
3531 fprintf(rej
, "%.*s", frag
->size
, frag
->patch
);
3532 if (frag
->patch
[frag
->size
-1] != '\n')
3539 static int write_out_results(struct patch
*list
, int skipped_patch
)
3545 if (!list
&& !skipped_patch
)
3546 return error("No changes");
3548 for (phase
= 0; phase
< 2; phase
++) {
3554 write_out_one_result(l
, phase
);
3555 if (phase
== 1 && write_out_one_reject(l
))
3564 static struct lock_file lock_file
;
3566 static struct string_list limit_by_name
;
3567 static int has_include
;
3568 static void add_name_limit(const char *name
, int exclude
)
3570 struct string_list_item
*it
;
3572 it
= string_list_append(&limit_by_name
, name
);
3573 it
->util
= exclude
? NULL
: (void *) 1;
3576 static int use_patch(struct patch
*p
)
3578 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
3581 /* Paths outside are not touched regardless of "--include" */
3582 if (0 < prefix_length
) {
3583 int pathlen
= strlen(pathname
);
3584 if (pathlen
<= prefix_length
||
3585 memcmp(prefix
, pathname
, prefix_length
))
3589 /* See if it matches any of exclude/include rule */
3590 for (i
= 0; i
< limit_by_name
.nr
; i
++) {
3591 struct string_list_item
*it
= &limit_by_name
.items
[i
];
3592 if (!fnmatch(it
->string
, pathname
, 0))
3593 return (it
->util
!= NULL
);
3597 * If we had any include, a path that does not match any rule is
3598 * not used. Otherwise, we saw bunch of exclude rules (or none)
3599 * and such a path is used.
3601 return !has_include
;
3605 static void prefix_one(char **name
)
3607 char *old_name
= *name
;
3610 *name
= xstrdup(prefix_filename(prefix
, prefix_length
, *name
));
3614 static void prefix_patches(struct patch
*p
)
3616 if (!prefix
|| p
->is_toplevel_relative
)
3618 for ( ; p
; p
= p
->next
) {
3619 if (p
->new_name
== p
->old_name
) {
3620 char *prefixed
= p
->new_name
;
3621 prefix_one(&prefixed
);
3622 p
->new_name
= p
->old_name
= prefixed
;
3625 prefix_one(&p
->new_name
);
3626 prefix_one(&p
->old_name
);
3631 #define INACCURATE_EOF (1<<0)
3632 #define RECOUNT (1<<1)
3634 static int apply_patch(int fd
, const char *filename
, int options
)
3637 struct strbuf buf
= STRBUF_INIT
;
3638 struct patch
*list
= NULL
, **listp
= &list
;
3639 int skipped_patch
= 0;
3641 /* FIXME - memory leak when using multiple patch files as inputs */
3642 memset(&fn_table
, 0, sizeof(struct string_list
));
3643 patch_input_file
= filename
;
3644 read_patch_file(&buf
, fd
);
3646 while (offset
< buf
.len
) {
3647 struct patch
*patch
;
3650 patch
= xcalloc(1, sizeof(*patch
));
3651 patch
->inaccurate_eof
= !!(options
& INACCURATE_EOF
);
3652 patch
->recount
= !!(options
& RECOUNT
);
3653 nr
= parse_chunk(buf
.buf
+ offset
, buf
.len
- offset
, patch
);
3656 if (apply_in_reverse
)
3657 reverse_patches(patch
);
3659 prefix_patches(patch
);
3660 if (use_patch(patch
)) {
3663 listp
= &patch
->next
;
3666 /* perhaps free it a bit better? */
3673 if (whitespace_error
&& (ws_error_action
== die_on_ws_error
))
3676 update_index
= check_index
&& apply
;
3677 if (update_index
&& newfd
< 0)
3678 newfd
= hold_locked_index(&lock_file
, 1);
3681 if (read_cache() < 0)
3682 die("unable to read index file");
3685 if ((check
|| apply
) &&
3686 check_patch_list(list
) < 0 &&
3690 if (apply
&& write_out_results(list
, skipped_patch
))
3694 build_fake_ancestor(list
, fake_ancestor
);
3697 stat_patch_list(list
);
3700 numstat_patch_list(list
);
3703 summary_patch_list(list
);
3705 strbuf_release(&buf
);
3709 static int git_apply_config(const char *var
, const char *value
, void *cb
)
3711 if (!strcmp(var
, "apply.whitespace"))
3712 return git_config_string(&apply_default_whitespace
, var
, value
);
3713 else if (!strcmp(var
, "apply.ignorewhitespace"))
3714 return git_config_string(&apply_default_ignorewhitespace
, var
, value
);
3715 return git_default_config(var
, value
, cb
);
3718 static int option_parse_exclude(const struct option
*opt
,
3719 const char *arg
, int unset
)
3721 add_name_limit(arg
, 1);
3725 static int option_parse_include(const struct option
*opt
,
3726 const char *arg
, int unset
)
3728 add_name_limit(arg
, 0);
3733 static int option_parse_p(const struct option
*opt
,
3734 const char *arg
, int unset
)
3736 p_value
= atoi(arg
);
3741 static int option_parse_z(const struct option
*opt
,
3742 const char *arg
, int unset
)
3745 line_termination
= '\n';
3747 line_termination
= 0;
3751 static int option_parse_space_change(const struct option
*opt
,
3752 const char *arg
, int unset
)
3755 ws_ignore_action
= ignore_ws_none
;
3757 ws_ignore_action
= ignore_ws_change
;
3761 static int option_parse_whitespace(const struct option
*opt
,
3762 const char *arg
, int unset
)
3764 const char **whitespace_option
= opt
->value
;
3766 *whitespace_option
= arg
;
3767 parse_whitespace_option(arg
);
3771 static int option_parse_directory(const struct option
*opt
,
3772 const char *arg
, int unset
)
3774 root_len
= strlen(arg
);
3775 if (root_len
&& arg
[root_len
- 1] != '/') {
3777 root
= new_root
= xmalloc(root_len
+ 2);
3778 strcpy(new_root
, arg
);
3779 strcpy(new_root
+ root_len
++, "/");
3785 int cmd_apply(int argc
, const char **argv
, const char *prefix_
)
3789 int is_not_gitdir
= !startup_info
->have_repository
;
3791 int force_apply
= 0;
3793 const char *whitespace_option
= NULL
;
3795 struct option builtin_apply_options
[] = {
3796 { OPTION_CALLBACK
, 0, "exclude", NULL
, "path",
3797 "don't apply changes matching the given path",
3798 0, option_parse_exclude
},
3799 { OPTION_CALLBACK
, 0, "include", NULL
, "path",
3800 "apply changes matching the given path",
3801 0, option_parse_include
},
3802 { OPTION_CALLBACK
, 'p', NULL
, NULL
, "num",
3803 "remove <num> leading slashes from traditional diff paths",
3804 0, option_parse_p
},
3805 OPT_BOOLEAN(0, "no-add", &no_add
,
3806 "ignore additions made by the patch"),
3807 OPT_BOOLEAN(0, "stat", &diffstat
,
3808 "instead of applying the patch, output diffstat for the input"),
3809 { OPTION_BOOLEAN
, 0, "allow-binary-replacement", &binary
,
3810 NULL
, "old option, now no-op",
3811 PARSE_OPT_HIDDEN
| PARSE_OPT_NOARG
},
3812 { OPTION_BOOLEAN
, 0, "binary", &binary
,
3813 NULL
, "old option, now no-op",
3814 PARSE_OPT_HIDDEN
| PARSE_OPT_NOARG
},
3815 OPT_BOOLEAN(0, "numstat", &numstat
,
3816 "shows number of added and deleted lines in decimal notation"),
3817 OPT_BOOLEAN(0, "summary", &summary
,
3818 "instead of applying the patch, output a summary for the input"),
3819 OPT_BOOLEAN(0, "check", &check
,
3820 "instead of applying the patch, see if the patch is applicable"),
3821 OPT_BOOLEAN(0, "index", &check_index
,
3822 "make sure the patch is applicable to the current index"),
3823 OPT_BOOLEAN(0, "cached", &cached
,
3824 "apply a patch without touching the working tree"),
3825 OPT_BOOLEAN(0, "apply", &force_apply
,
3826 "also apply the patch (use with --stat/--summary/--check)"),
3827 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor
,
3828 "build a temporary index based on embedded index information"),
3829 { OPTION_CALLBACK
, 'z', NULL
, NULL
, NULL
,
3830 "paths are separated with NUL character",
3831 PARSE_OPT_NOARG
, option_parse_z
},
3832 OPT_INTEGER('C', NULL
, &p_context
,
3833 "ensure at least <n> lines of context match"),
3834 { OPTION_CALLBACK
, 0, "whitespace", &whitespace_option
, "action",
3835 "detect new or modified lines that have whitespace errors",
3836 0, option_parse_whitespace
},
3837 { OPTION_CALLBACK
, 0, "ignore-space-change", NULL
, NULL
,
3838 "ignore changes in whitespace when finding context",
3839 PARSE_OPT_NOARG
, option_parse_space_change
},
3840 { OPTION_CALLBACK
, 0, "ignore-whitespace", NULL
, NULL
,
3841 "ignore changes in whitespace when finding context",
3842 PARSE_OPT_NOARG
, option_parse_space_change
},
3843 OPT_BOOLEAN('R', "reverse", &apply_in_reverse
,
3844 "apply the patch in reverse"),
3845 OPT_BOOLEAN(0, "unidiff-zero", &unidiff_zero
,
3846 "don't expect at least one line of context"),
3847 OPT_BOOLEAN(0, "reject", &apply_with_reject
,
3848 "leave the rejected hunks in corresponding *.rej files"),
3849 OPT__VERBOSE(&apply_verbosely
),
3850 OPT_BIT(0, "inaccurate-eof", &options
,
3851 "tolerate incorrectly detected missing new-line at the end of file",
3853 OPT_BIT(0, "recount", &options
,
3854 "do not trust the line counts in the hunk headers",
3856 { OPTION_CALLBACK
, 0, "directory", NULL
, "root",
3857 "prepend <root> to all filenames",
3858 0, option_parse_directory
},
3863 prefix_length
= prefix
? strlen(prefix
) : 0;
3864 git_config(git_apply_config
, NULL
);
3865 if (apply_default_whitespace
)
3866 parse_whitespace_option(apply_default_whitespace
);
3867 if (apply_default_ignorewhitespace
)
3868 parse_ignorewhitespace_option(apply_default_ignorewhitespace
);
3870 argc
= parse_options(argc
, argv
, prefix
, builtin_apply_options
,
3873 if (apply_with_reject
)
3874 apply
= apply_verbosely
= 1;
3875 if (!force_apply
&& (diffstat
|| numstat
|| summary
|| check
|| fake_ancestor
))
3877 if (check_index
&& is_not_gitdir
)
3878 die("--index outside a repository");
3881 die("--cached outside a repository");
3884 for (i
= 0; i
< argc
; i
++) {
3885 const char *arg
= argv
[i
];
3888 if (!strcmp(arg
, "-")) {
3889 errs
|= apply_patch(0, "<stdin>", options
);
3892 } else if (0 < prefix_length
)
3893 arg
= prefix_filename(prefix
, prefix_length
, arg
);
3895 fd
= open(arg
, O_RDONLY
);
3897 die_errno("can't open patch '%s'", arg
);
3899 set_default_whitespace_mode(whitespace_option
);
3900 errs
|= apply_patch(fd
, arg
, options
);
3903 set_default_whitespace_mode(whitespace_option
);
3905 errs
|= apply_patch(0, "<stdin>", options
);
3906 if (whitespace_error
) {
3907 if (squelch_whitespace_errors
&&
3908 squelch_whitespace_errors
< whitespace_error
) {
3910 whitespace_error
- squelch_whitespace_errors
;
3911 warning("squelched %d "
3912 "whitespace error%s",
3914 squelched
== 1 ? "" : "s");
3916 if (ws_error_action
== die_on_ws_error
)
3917 die("%d line%s add%s whitespace errors.",
3919 whitespace_error
== 1 ? "" : "s",
3920 whitespace_error
== 1 ? "s" : "");
3921 if (applied_after_fixing_ws
&& apply
)
3922 warning("%d line%s applied after"
3923 " fixing whitespace errors.",
3924 applied_after_fixing_ws
,
3925 applied_after_fixing_ws
== 1 ? "" : "s");
3926 else if (whitespace_error
)
3927 warning("%d line%s add%s whitespace errors.",
3929 whitespace_error
== 1 ? "" : "s",
3930 whitespace_error
== 1 ? "s" : "");
3934 if (write_cache(newfd
, active_cache
, active_nr
) ||
3935 commit_locked_index(&lock_file
))
3936 die("Unable to write new index file");