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
;
46 static int allow_overlap
;
48 static const char *fake_ancestor
;
49 static int line_termination
= '\n';
50 static unsigned int p_context
= UINT_MAX
;
51 static const char * const apply_usage
[] = {
52 "git apply [options] [<patch>...]",
56 static enum ws_error_action
{
61 } ws_error_action
= warn_on_ws_error
;
62 static int whitespace_error
;
63 static int squelch_whitespace_errors
= 5;
64 static int applied_after_fixing_ws
;
66 static enum ws_ignore
{
69 } ws_ignore_action
= ignore_ws_none
;
72 static const char *patch_input_file
;
73 static const char *root
;
75 static int read_stdin
= 1;
78 static void parse_whitespace_option(const char *option
)
81 ws_error_action
= warn_on_ws_error
;
84 if (!strcmp(option
, "warn")) {
85 ws_error_action
= warn_on_ws_error
;
88 if (!strcmp(option
, "nowarn")) {
89 ws_error_action
= nowarn_ws_error
;
92 if (!strcmp(option
, "error")) {
93 ws_error_action
= die_on_ws_error
;
96 if (!strcmp(option
, "error-all")) {
97 ws_error_action
= die_on_ws_error
;
98 squelch_whitespace_errors
= 0;
101 if (!strcmp(option
, "strip") || !strcmp(option
, "fix")) {
102 ws_error_action
= correct_ws_error
;
105 die("unrecognized whitespace option '%s'", option
);
108 static void parse_ignorewhitespace_option(const char *option
)
110 if (!option
|| !strcmp(option
, "no") ||
111 !strcmp(option
, "false") || !strcmp(option
, "never") ||
112 !strcmp(option
, "none")) {
113 ws_ignore_action
= ignore_ws_none
;
116 if (!strcmp(option
, "change")) {
117 ws_ignore_action
= ignore_ws_change
;
120 die("unrecognized whitespace ignore option '%s'", option
);
123 static void set_default_whitespace_mode(const char *whitespace_option
)
125 if (!whitespace_option
&& !apply_default_whitespace
)
126 ws_error_action
= (apply
? warn_on_ws_error
: nowarn_ws_error
);
130 * For "diff-stat" like behaviour, we keep track of the biggest change
131 * we've seen, and the longest filename. That allows us to do simple
134 static int max_change
, max_len
;
137 * Various "current state", notably line numbers and what
138 * file (and how) we're patching right now.. The "is_xxxx"
139 * things are flags, where -1 means "don't know yet".
141 static int linenr
= 1;
144 * This represents one "hunk" from a patch, starting with
145 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
146 * patch text is pointed at by patch, and its byte length
147 * is stored in size. leading and trailing are the number
151 unsigned long leading
, trailing
;
152 unsigned long oldpos
, oldlines
;
153 unsigned long newpos
, newlines
;
158 struct fragment
*next
;
162 * When dealing with a binary patch, we reuse "leading" field
163 * to store the type of the binary hunk, either deflated "delta"
164 * or deflated "literal".
166 #define binary_patch_method leading
167 #define BINARY_DELTA_DEFLATED 1
168 #define BINARY_LITERAL_DEFLATED 2
171 * This represents a "patch" to a file, both metainfo changes
172 * such as creation/deletion, filemode and content changes represented
173 * as a series of fragments.
176 char *new_name
, *old_name
, *def_name
;
177 unsigned int old_mode
, new_mode
;
178 int is_new
, is_delete
; /* -1 = unknown, 0 = false, 1 = true */
181 unsigned long deflate_origlen
;
182 int lines_added
, lines_deleted
;
184 unsigned int is_toplevel_relative
:1;
185 unsigned int inaccurate_eof
:1;
186 unsigned int is_binary
:1;
187 unsigned int is_copy
:1;
188 unsigned int is_rename
:1;
189 unsigned int recount
:1;
190 struct fragment
*fragments
;
193 char old_sha1_prefix
[41];
194 char new_sha1_prefix
[41];
199 * A line in a file, len-bytes long (includes the terminating LF,
200 * except for an incomplete line at the end if the file ends with
201 * one), and its contents hashes to 'hash'.
207 #define LINE_COMMON 1
208 #define LINE_PATCHED 2
212 * This represents a "file", which is an array of "lines".
219 struct line
*line_allocated
;
224 * Records filenames that have been touched, in order to handle
225 * the case where more than one patches touch the same file.
228 static struct string_list fn_table
;
230 static uint32_t hash_line(const char *cp
, size_t len
)
234 for (i
= 0, h
= 0; i
< len
; i
++) {
235 if (!isspace(cp
[i
])) {
236 h
= h
* 3 + (cp
[i
] & 0xff);
243 * Compare lines s1 of length n1 and s2 of length n2, ignoring
244 * whitespace difference. Returns 1 if they match, 0 otherwise
246 static int fuzzy_matchlines(const char *s1
, size_t n1
,
247 const char *s2
, size_t n2
)
249 const char *last1
= s1
+ n1
- 1;
250 const char *last2
= s2
+ n2
- 1;
253 /* ignore line endings */
254 while ((*last1
== '\r') || (*last1
== '\n'))
256 while ((*last2
== '\r') || (*last2
== '\n'))
259 /* skip leading whitespace */
260 while (isspace(*s1
) && (s1
<= last1
))
262 while (isspace(*s2
) && (s2
<= last2
))
264 /* early return if both lines are empty */
265 if ((s1
> last1
) && (s2
> last2
))
268 result
= *s1
++ - *s2
++;
270 * Skip whitespace inside. We check for whitespace on
271 * both buffers because we don't want "a b" to match
274 if (isspace(*s1
) && isspace(*s2
)) {
275 while (isspace(*s1
) && s1
<= last1
)
277 while (isspace(*s2
) && s2
<= last2
)
281 * If we reached the end on one side only,
285 ((s2
> last2
) && (s1
<= last1
)) ||
286 ((s1
> last1
) && (s2
<= last2
)))
288 if ((s1
> last1
) && (s2
> last2
))
295 static void add_line_info(struct image
*img
, const char *bol
, size_t len
, unsigned flag
)
297 ALLOC_GROW(img
->line_allocated
, img
->nr
+ 1, img
->alloc
);
298 img
->line_allocated
[img
->nr
].len
= len
;
299 img
->line_allocated
[img
->nr
].hash
= hash_line(bol
, len
);
300 img
->line_allocated
[img
->nr
].flag
= flag
;
304 static void prepare_image(struct image
*image
, char *buf
, size_t len
,
305 int prepare_linetable
)
309 memset(image
, 0, sizeof(*image
));
313 if (!prepare_linetable
)
316 ep
= image
->buf
+ image
->len
;
320 for (next
= cp
; next
< ep
&& *next
!= '\n'; next
++)
324 add_line_info(image
, cp
, next
- cp
, 0);
327 image
->line
= image
->line_allocated
;
330 static void clear_image(struct image
*image
)
337 static void say_patch_name(FILE *output
, const char *pre
,
338 struct patch
*patch
, const char *post
)
341 if (patch
->old_name
&& patch
->new_name
&&
342 strcmp(patch
->old_name
, patch
->new_name
)) {
343 quote_c_style(patch
->old_name
, NULL
, output
, 0);
344 fputs(" => ", output
);
345 quote_c_style(patch
->new_name
, NULL
, output
, 0);
347 const char *n
= patch
->new_name
;
350 quote_c_style(n
, NULL
, output
, 0);
355 #define CHUNKSIZE (8192)
358 static void read_patch_file(struct strbuf
*sb
, int fd
)
360 if (strbuf_read(sb
, fd
, 0) < 0)
361 die_errno("git apply: failed to read");
364 * Make sure that we have some slop in the buffer
365 * so that we can do speculative "memcmp" etc, and
366 * see to it that it is NUL-filled.
368 strbuf_grow(sb
, SLOP
);
369 memset(sb
->buf
+ sb
->len
, 0, SLOP
);
372 static unsigned long linelen(const char *buffer
, unsigned long size
)
374 unsigned long len
= 0;
377 if (*buffer
++ == '\n')
383 static int is_dev_null(const char *str
)
385 return !memcmp("/dev/null", str
, 9) && isspace(str
[9]);
391 static int name_terminate(const char *name
, int namelen
, int c
, int terminate
)
393 if (c
== ' ' && !(terminate
& TERM_SPACE
))
395 if (c
== '\t' && !(terminate
& TERM_TAB
))
401 /* remove double slashes to make --index work with such filenames */
402 static char *squash_slash(char *name
)
410 if ((name
[j
++] = name
[i
++]) == '/')
411 while (name
[i
] == '/')
418 static char *find_name_gnu(const char *line
, char *def
, int p_value
)
420 struct strbuf name
= STRBUF_INIT
;
424 * Proposed "new-style" GNU patch/diff format; see
425 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
427 if (unquote_c_style(&name
, line
, NULL
)) {
428 strbuf_release(&name
);
432 for (cp
= name
.buf
; p_value
; p_value
--) {
433 cp
= strchr(cp
, '/');
435 strbuf_release(&name
);
441 /* name can later be freed, so we need
442 * to memmove, not just return cp
444 strbuf_remove(&name
, 0, cp
- name
.buf
);
447 strbuf_insert(&name
, 0, root
, root_len
);
448 return squash_slash(strbuf_detach(&name
, NULL
));
451 static size_t sane_tz_len(const char *line
, size_t len
)
455 if (len
< strlen(" +0500") || line
[len
-strlen(" +0500")] != ' ')
457 tz
= line
+ len
- strlen(" +0500");
459 if (tz
[1] != '+' && tz
[1] != '-')
462 for (p
= tz
+ 2; p
!= line
+ len
; p
++)
466 return line
+ len
- tz
;
469 static size_t tz_with_colon_len(const char *line
, size_t len
)
473 if (len
< strlen(" +08:00") || line
[len
- strlen(":00")] != ':')
475 tz
= line
+ len
- strlen(" +08:00");
477 if (tz
[0] != ' ' || (tz
[1] != '+' && tz
[1] != '-'))
480 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
481 !isdigit(*p
++) || !isdigit(*p
++))
484 return line
+ len
- tz
;
487 static size_t date_len(const char *line
, size_t len
)
489 const char *date
, *p
;
491 if (len
< strlen("72-02-05") || line
[len
-strlen("-05")] != '-')
493 p
= date
= line
+ len
- strlen("72-02-05");
495 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
496 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
497 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a date. */
500 if (date
- line
>= strlen("19") &&
501 isdigit(date
[-1]) && isdigit(date
[-2])) /* 4-digit year */
502 date
-= strlen("19");
504 return line
+ len
- date
;
507 static size_t short_time_len(const char *line
, size_t len
)
509 const char *time
, *p
;
511 if (len
< strlen(" 07:01:32") || line
[len
-strlen(":32")] != ':')
513 p
= time
= line
+ len
- strlen(" 07:01:32");
515 /* Permit 1-digit hours? */
517 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
518 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
519 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a time. */
522 return line
+ len
- time
;
525 static size_t fractional_time_len(const char *line
, size_t len
)
530 /* Expected format: 19:41:17.620000023 */
531 if (!len
|| !isdigit(line
[len
- 1]))
535 /* Fractional seconds. */
536 while (p
> line
&& isdigit(*p
))
541 /* Hours, minutes, and whole seconds. */
542 n
= short_time_len(line
, p
- line
);
546 return line
+ len
- p
+ n
;
549 static size_t trailing_spaces_len(const char *line
, size_t len
)
553 /* Expected format: ' ' x (1 or more) */
554 if (!len
|| line
[len
- 1] != ' ')
561 return line
+ len
- (p
+ 1);
568 static size_t diff_timestamp_len(const char *line
, size_t len
)
570 const char *end
= line
+ len
;
574 * Posix: 2010-07-05 19:41:17
575 * GNU: 2010-07-05 19:41:17.620000023 -0500
578 if (!isdigit(end
[-1]))
581 n
= sane_tz_len(line
, end
- line
);
583 n
= tz_with_colon_len(line
, end
- line
);
586 n
= short_time_len(line
, end
- line
);
588 n
= fractional_time_len(line
, end
- line
);
591 n
= date_len(line
, end
- line
);
592 if (!n
) /* No date. Too bad. */
596 if (end
== line
) /* No space before date. */
598 if (end
[-1] == '\t') { /* Success! */
600 return line
+ len
- end
;
602 if (end
[-1] != ' ') /* No space before date. */
605 /* Whitespace damage. */
606 end
-= trailing_spaces_len(line
, end
- line
);
607 return line
+ len
- end
;
610 static char *find_name_common(const char *line
, char *def
, int p_value
,
611 const char *end
, int terminate
)
614 const char *start
= NULL
;
618 while (line
!= end
) {
621 if (!end
&& isspace(c
)) {
624 if (name_terminate(start
, line
-start
, c
, terminate
))
628 if (c
== '/' && !--p_value
)
632 return squash_slash(def
);
635 return squash_slash(def
);
638 * Generally we prefer the shorter name, especially
639 * if the other one is just a variation of that with
640 * something else tacked on to the end (ie "file.orig"
644 int deflen
= strlen(def
);
645 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
646 return squash_slash(def
);
651 char *ret
= xmalloc(root_len
+ len
+ 1);
653 memcpy(ret
+ root_len
, start
, len
);
654 ret
[root_len
+ len
] = '\0';
655 return squash_slash(ret
);
658 return squash_slash(xmemdupz(start
, len
));
661 static char *find_name(const char *line
, char *def
, int p_value
, int terminate
)
664 char *name
= find_name_gnu(line
, def
, p_value
);
669 return find_name_common(line
, def
, p_value
, NULL
, terminate
);
672 static char *find_name_traditional(const char *line
, char *def
, int p_value
)
674 size_t len
= strlen(line
);
678 char *name
= find_name_gnu(line
, def
, p_value
);
683 len
= strchrnul(line
, '\n') - line
;
684 date_len
= diff_timestamp_len(line
, len
);
686 return find_name_common(line
, def
, p_value
, NULL
, TERM_TAB
);
689 return find_name_common(line
, def
, p_value
, line
+ len
, 0);
692 static int count_slashes(const char *cp
)
704 * Given the string after "--- " or "+++ ", guess the appropriate
705 * p_value for the given patch.
707 static int guess_p_value(const char *nameline
)
712 if (is_dev_null(nameline
))
714 name
= find_name_traditional(nameline
, NULL
, 0);
717 cp
= strchr(name
, '/');
722 * Does it begin with "a/$our-prefix" and such? Then this is
723 * very likely to apply to our directory.
725 if (!strncmp(name
, prefix
, prefix_length
))
726 val
= count_slashes(prefix
);
729 if (!strncmp(cp
, prefix
, prefix_length
))
730 val
= count_slashes(prefix
) + 1;
738 * Does the ---/+++ line has the POSIX timestamp after the last HT?
739 * GNU diff puts epoch there to signal a creation/deletion event. Is
740 * this such a timestamp?
742 static int has_epoch_timestamp(const char *nameline
)
745 * We are only interested in epoch timestamp; any non-zero
746 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
747 * For the same reason, the date must be either 1969-12-31 or
748 * 1970-01-01, and the seconds part must be "00".
750 const char stamp_regexp
[] =
751 "^(1969-12-31|1970-01-01)"
753 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
755 "([-+][0-2][0-9]:?[0-5][0-9])\n";
756 const char *timestamp
= NULL
, *cp
, *colon
;
757 static regex_t
*stamp
;
763 for (cp
= nameline
; *cp
!= '\n'; cp
++) {
770 stamp
= xmalloc(sizeof(*stamp
));
771 if (regcomp(stamp
, stamp_regexp
, REG_EXTENDED
)) {
772 warning("Cannot prepare timestamp regexp %s",
778 status
= regexec(stamp
, timestamp
, ARRAY_SIZE(m
), m
, 0);
780 if (status
!= REG_NOMATCH
)
781 warning("regexec returned %d for input: %s",
786 zoneoffset
= strtol(timestamp
+ m
[3].rm_so
+ 1, (char **) &colon
, 10);
788 zoneoffset
= zoneoffset
* 60 + strtol(colon
+ 1, NULL
, 10);
790 zoneoffset
= (zoneoffset
/ 100) * 60 + (zoneoffset
% 100);
791 if (timestamp
[m
[3].rm_so
] == '-')
792 zoneoffset
= -zoneoffset
;
795 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
796 * (west of GMT) or 1970-01-01 (east of GMT)
798 if ((zoneoffset
< 0 && memcmp(timestamp
, "1969-12-31", 10)) ||
799 (0 <= zoneoffset
&& memcmp(timestamp
, "1970-01-01", 10)))
802 hourminute
= (strtol(timestamp
+ 11, NULL
, 10) * 60 +
803 strtol(timestamp
+ 14, NULL
, 10) -
806 return ((zoneoffset
< 0 && hourminute
== 1440) ||
807 (0 <= zoneoffset
&& !hourminute
));
811 * Get the name etc info from the ---/+++ lines of a traditional patch header
813 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
814 * files, we can happily check the index for a match, but for creating a
815 * new file we should try to match whatever "patch" does. I have no idea.
817 static void parse_traditional_patch(const char *first
, const char *second
, struct patch
*patch
)
821 first
+= 4; /* skip "--- " */
822 second
+= 4; /* skip "+++ " */
823 if (!p_value_known
) {
825 p
= guess_p_value(first
);
826 q
= guess_p_value(second
);
828 if (0 <= p
&& p
== q
) {
833 if (is_dev_null(first
)) {
835 patch
->is_delete
= 0;
836 name
= find_name_traditional(second
, NULL
, p_value
);
837 patch
->new_name
= name
;
838 } else if (is_dev_null(second
)) {
840 patch
->is_delete
= 1;
841 name
= find_name_traditional(first
, NULL
, p_value
);
842 patch
->old_name
= name
;
844 name
= find_name_traditional(first
, NULL
, p_value
);
845 name
= find_name_traditional(second
, name
, p_value
);
846 if (has_epoch_timestamp(first
)) {
848 patch
->is_delete
= 0;
849 patch
->new_name
= name
;
850 } else if (has_epoch_timestamp(second
)) {
852 patch
->is_delete
= 1;
853 patch
->old_name
= name
;
855 patch
->old_name
= patch
->new_name
= name
;
859 die("unable to find filename in patch at line %d", linenr
);
862 static int gitdiff_hdrend(const char *line
, struct patch
*patch
)
868 * We're anal about diff header consistency, to make
869 * sure that we don't end up having strange ambiguous
870 * patches floating around.
872 * As a result, gitdiff_{old|new}name() will check
873 * their names against any previous information, just
876 static char *gitdiff_verify_name(const char *line
, int isnull
, char *orig_name
, const char *oldnew
)
878 if (!orig_name
&& !isnull
)
879 return find_name(line
, NULL
, p_value
, TERM_TAB
);
888 die("git apply: bad git-diff - expected /dev/null, got %s on line %d", name
, linenr
);
889 another
= find_name(line
, NULL
, p_value
, TERM_TAB
);
890 if (!another
|| memcmp(another
, name
, len
+ 1))
891 die("git apply: bad git-diff - inconsistent %s filename on line %d", oldnew
, linenr
);
896 /* expect "/dev/null" */
897 if (memcmp("/dev/null", line
, 9) || line
[9] != '\n')
898 die("git apply: bad git-diff - expected /dev/null on line %d", linenr
);
903 static int gitdiff_oldname(const char *line
, struct patch
*patch
)
905 patch
->old_name
= gitdiff_verify_name(line
, patch
->is_new
, patch
->old_name
, "old");
909 static int gitdiff_newname(const char *line
, struct patch
*patch
)
911 patch
->new_name
= gitdiff_verify_name(line
, patch
->is_delete
, patch
->new_name
, "new");
915 static int gitdiff_oldmode(const char *line
, struct patch
*patch
)
917 patch
->old_mode
= strtoul(line
, NULL
, 8);
921 static int gitdiff_newmode(const char *line
, struct patch
*patch
)
923 patch
->new_mode
= strtoul(line
, NULL
, 8);
927 static int gitdiff_delete(const char *line
, struct patch
*patch
)
929 patch
->is_delete
= 1;
930 patch
->old_name
= patch
->def_name
;
931 return gitdiff_oldmode(line
, patch
);
934 static int gitdiff_newfile(const char *line
, struct patch
*patch
)
937 patch
->new_name
= patch
->def_name
;
938 return gitdiff_newmode(line
, patch
);
941 static int gitdiff_copysrc(const char *line
, struct patch
*patch
)
944 patch
->old_name
= find_name(line
, NULL
, p_value
? p_value
- 1 : 0, 0);
948 static int gitdiff_copydst(const char *line
, struct patch
*patch
)
951 patch
->new_name
= find_name(line
, NULL
, p_value
? p_value
- 1 : 0, 0);
955 static int gitdiff_renamesrc(const char *line
, struct patch
*patch
)
957 patch
->is_rename
= 1;
958 patch
->old_name
= find_name(line
, NULL
, p_value
? p_value
- 1 : 0, 0);
962 static int gitdiff_renamedst(const char *line
, struct patch
*patch
)
964 patch
->is_rename
= 1;
965 patch
->new_name
= find_name(line
, NULL
, p_value
? p_value
- 1 : 0, 0);
969 static int gitdiff_similarity(const char *line
, struct patch
*patch
)
971 if ((patch
->score
= strtoul(line
, NULL
, 10)) == ULONG_MAX
)
976 static int gitdiff_dissimilarity(const char *line
, struct patch
*patch
)
978 if ((patch
->score
= strtoul(line
, NULL
, 10)) == ULONG_MAX
)
983 static int gitdiff_index(const char *line
, struct patch
*patch
)
986 * index line is N hexadecimal, "..", N hexadecimal,
987 * and optional space with octal mode.
989 const char *ptr
, *eol
;
992 ptr
= strchr(line
, '.');
993 if (!ptr
|| ptr
[1] != '.' || 40 < ptr
- line
)
996 memcpy(patch
->old_sha1_prefix
, line
, len
);
997 patch
->old_sha1_prefix
[len
] = 0;
1000 ptr
= strchr(line
, ' ');
1001 eol
= strchr(line
, '\n');
1003 if (!ptr
|| eol
< ptr
)
1009 memcpy(patch
->new_sha1_prefix
, line
, len
);
1010 patch
->new_sha1_prefix
[len
] = 0;
1012 patch
->old_mode
= strtoul(ptr
+1, NULL
, 8);
1017 * This is normal for a diff that doesn't change anything: we'll fall through
1018 * into the next diff. Tell the parser to break out.
1020 static int gitdiff_unrecognized(const char *line
, struct patch
*patch
)
1026 * Skip p_value leading components from "line"; as we do not accept
1027 * absolute paths, return NULL in that case.
1029 static const char *skip_tree_prefix(const char *line
, int llen
)
1035 return (llen
&& line
[0] == '/') ? NULL
: line
;
1038 for (i
= 0; i
< llen
; i
++) {
1040 if (ch
== '/' && --nslash
<= 0)
1041 return (i
== 0) ? NULL
: &line
[i
+ 1];
1047 * This is to extract the same name that appears on "diff --git"
1048 * line. We do not find and return anything if it is a rename
1049 * patch, and it is OK because we will find the name elsewhere.
1050 * We need to reliably find name only when it is mode-change only,
1051 * creation or deletion of an empty file. In any of these cases,
1052 * both sides are the same name under a/ and b/ respectively.
1054 static char *git_header_name(char *line
, int llen
)
1057 const char *second
= NULL
;
1058 size_t len
, line_len
;
1060 line
+= strlen("diff --git ");
1061 llen
-= strlen("diff --git ");
1065 struct strbuf first
= STRBUF_INIT
;
1066 struct strbuf sp
= STRBUF_INIT
;
1068 if (unquote_c_style(&first
, line
, &second
))
1069 goto free_and_fail1
;
1071 /* strip the a/b prefix including trailing slash */
1072 cp
= skip_tree_prefix(first
.buf
, first
.len
);
1074 goto free_and_fail1
;
1075 strbuf_remove(&first
, 0, cp
- first
.buf
);
1078 * second points at one past closing dq of name.
1079 * find the second name.
1081 while ((second
< line
+ llen
) && isspace(*second
))
1084 if (line
+ llen
<= second
)
1085 goto free_and_fail1
;
1086 if (*second
== '"') {
1087 if (unquote_c_style(&sp
, second
, NULL
))
1088 goto free_and_fail1
;
1089 cp
= skip_tree_prefix(sp
.buf
, sp
.len
);
1091 goto free_and_fail1
;
1092 /* They must match, otherwise ignore */
1093 if (strcmp(cp
, first
.buf
))
1094 goto free_and_fail1
;
1095 strbuf_release(&sp
);
1096 return strbuf_detach(&first
, NULL
);
1099 /* unquoted second */
1100 cp
= skip_tree_prefix(second
, line
+ llen
- second
);
1102 goto free_and_fail1
;
1103 if (line
+ llen
- cp
!= first
.len
||
1104 memcmp(first
.buf
, cp
, first
.len
))
1105 goto free_and_fail1
;
1106 return strbuf_detach(&first
, NULL
);
1109 strbuf_release(&first
);
1110 strbuf_release(&sp
);
1114 /* unquoted first name */
1115 name
= skip_tree_prefix(line
, llen
);
1120 * since the first name is unquoted, a dq if exists must be
1121 * the beginning of the second name.
1123 for (second
= name
; second
< line
+ llen
; second
++) {
1124 if (*second
== '"') {
1125 struct strbuf sp
= STRBUF_INIT
;
1128 if (unquote_c_style(&sp
, second
, NULL
))
1129 goto free_and_fail2
;
1131 np
= skip_tree_prefix(sp
.buf
, sp
.len
);
1133 goto free_and_fail2
;
1135 len
= sp
.buf
+ sp
.len
- np
;
1136 if (len
< second
- name
&&
1137 !strncmp(np
, name
, len
) &&
1138 isspace(name
[len
])) {
1140 strbuf_remove(&sp
, 0, np
- sp
.buf
);
1141 return strbuf_detach(&sp
, NULL
);
1145 strbuf_release(&sp
);
1151 * Accept a name only if it shows up twice, exactly the same
1154 second
= strchr(name
, '\n');
1157 line_len
= second
- name
;
1158 for (len
= 0 ; ; len
++) {
1159 switch (name
[len
]) {
1164 case '\t': case ' ':
1166 * Is this the separator between the preimage
1167 * and the postimage pathname? Again, we are
1168 * only interested in the case where there is
1169 * no rename, as this is only to set def_name
1170 * and a rename patch has the names elsewhere
1171 * in an unambiguous form.
1174 return NULL
; /* no postimage name */
1175 second
= skip_tree_prefix(name
+ len
+ 1,
1176 line_len
- (len
+ 1));
1180 * Does len bytes starting at "name" and "second"
1181 * (that are separated by one HT or SP we just
1182 * found) exactly match?
1184 if (second
[len
] == '\n' && !strncmp(name
, second
, len
))
1185 return xmemdupz(name
, len
);
1190 /* Verify that we recognize the lines following a git header */
1191 static int parse_git_header(char *line
, int len
, unsigned int size
, struct patch
*patch
)
1193 unsigned long offset
;
1195 /* A git diff has explicit new/delete information, so we don't guess */
1197 patch
->is_delete
= 0;
1200 * Some things may not have the old name in the
1201 * rest of the headers anywhere (pure mode changes,
1202 * or removing or adding empty files), so we get
1203 * the default name from the header.
1205 patch
->def_name
= git_header_name(line
, len
);
1206 if (patch
->def_name
&& root
) {
1207 char *s
= xmalloc(root_len
+ strlen(patch
->def_name
) + 1);
1209 strcpy(s
+ root_len
, patch
->def_name
);
1210 free(patch
->def_name
);
1211 patch
->def_name
= s
;
1217 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1218 static const struct opentry
{
1220 int (*fn
)(const char *, struct patch
*);
1222 { "@@ -", gitdiff_hdrend
},
1223 { "--- ", gitdiff_oldname
},
1224 { "+++ ", gitdiff_newname
},
1225 { "old mode ", gitdiff_oldmode
},
1226 { "new mode ", gitdiff_newmode
},
1227 { "deleted file mode ", gitdiff_delete
},
1228 { "new file mode ", gitdiff_newfile
},
1229 { "copy from ", gitdiff_copysrc
},
1230 { "copy to ", gitdiff_copydst
},
1231 { "rename old ", gitdiff_renamesrc
},
1232 { "rename new ", gitdiff_renamedst
},
1233 { "rename from ", gitdiff_renamesrc
},
1234 { "rename to ", gitdiff_renamedst
},
1235 { "similarity index ", gitdiff_similarity
},
1236 { "dissimilarity index ", gitdiff_dissimilarity
},
1237 { "index ", gitdiff_index
},
1238 { "", gitdiff_unrecognized
},
1242 len
= linelen(line
, size
);
1243 if (!len
|| line
[len
-1] != '\n')
1245 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
1246 const struct opentry
*p
= optable
+ i
;
1247 int oplen
= strlen(p
->str
);
1248 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
1250 if (p
->fn(line
+ oplen
, patch
) < 0)
1259 static int parse_num(const char *line
, unsigned long *p
)
1263 if (!isdigit(*line
))
1265 *p
= strtoul(line
, &ptr
, 10);
1269 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
1270 unsigned long *p1
, unsigned long *p2
)
1274 if (offset
< 0 || offset
>= len
)
1279 digits
= parse_num(line
, p1
);
1289 digits
= parse_num(line
+1, p2
);
1298 ex
= strlen(expect
);
1301 if (memcmp(line
, expect
, ex
))
1307 static void recount_diff(char *line
, int size
, struct fragment
*fragment
)
1309 int oldlines
= 0, newlines
= 0, ret
= 0;
1312 warning("recount: ignore empty hunk");
1317 int len
= linelen(line
, size
);
1325 case ' ': case '\n':
1337 ret
= size
< 3 || prefixcmp(line
, "@@ ");
1340 ret
= size
< 5 || prefixcmp(line
, "diff ");
1347 warning("recount: unexpected line: %.*s",
1348 (int)linelen(line
, size
), line
);
1353 fragment
->oldlines
= oldlines
;
1354 fragment
->newlines
= newlines
;
1358 * Parse a unified diff fragment header of the
1359 * form "@@ -a,b +c,d @@"
1361 static int parse_fragment_header(char *line
, int len
, struct fragment
*fragment
)
1365 if (!len
|| line
[len
-1] != '\n')
1368 /* Figure out the number of lines in a fragment */
1369 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
1370 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
1375 static int find_header(char *line
, unsigned long size
, int *hdrsize
, struct patch
*patch
)
1377 unsigned long offset
, len
;
1379 patch
->is_toplevel_relative
= 0;
1380 patch
->is_rename
= patch
->is_copy
= 0;
1381 patch
->is_new
= patch
->is_delete
= -1;
1382 patch
->old_mode
= patch
->new_mode
= 0;
1383 patch
->old_name
= patch
->new_name
= NULL
;
1384 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1385 unsigned long nextlen
;
1387 len
= linelen(line
, size
);
1391 /* Testing this early allows us to take a few shortcuts.. */
1396 * Make sure we don't find any unconnected patch fragments.
1397 * That's a sign that we didn't find a header, and that a
1398 * patch has become corrupted/broken up.
1400 if (!memcmp("@@ -", line
, 4)) {
1401 struct fragment dummy
;
1402 if (parse_fragment_header(line
, len
, &dummy
) < 0)
1404 die("patch fragment without header at line %d: %.*s",
1405 linenr
, (int)len
-1, line
);
1412 * Git patch? It might not have a real patch, just a rename
1413 * or mode change, so we handle that specially
1415 if (!memcmp("diff --git ", line
, 11)) {
1416 int git_hdr_len
= parse_git_header(line
, len
, size
, patch
);
1417 if (git_hdr_len
<= len
)
1419 if (!patch
->old_name
&& !patch
->new_name
) {
1420 if (!patch
->def_name
)
1421 die("git diff header lacks filename information when removing "
1422 "%d leading pathname components (line %d)" , p_value
, linenr
);
1423 patch
->old_name
= patch
->new_name
= patch
->def_name
;
1425 if (!patch
->is_delete
&& !patch
->new_name
)
1426 die("git diff header lacks filename information "
1427 "(line %d)", linenr
);
1428 patch
->is_toplevel_relative
= 1;
1429 *hdrsize
= git_hdr_len
;
1433 /* --- followed by +++ ? */
1434 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
1438 * We only accept unified patches, so we want it to
1439 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1440 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1442 nextlen
= linelen(line
+ len
, size
- len
);
1443 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
1446 /* Ok, we'll consider it a patch */
1447 parse_traditional_patch(line
, line
+len
, patch
);
1448 *hdrsize
= len
+ nextlen
;
1455 static void record_ws_error(unsigned result
, const char *line
, int len
, int linenr
)
1463 if (squelch_whitespace_errors
&&
1464 squelch_whitespace_errors
< whitespace_error
)
1467 err
= whitespace_error_string(result
);
1468 fprintf(stderr
, "%s:%d: %s.\n%.*s\n",
1469 patch_input_file
, linenr
, err
, len
, line
);
1473 static void check_whitespace(const char *line
, int len
, unsigned ws_rule
)
1475 unsigned result
= ws_check(line
+ 1, len
- 1, ws_rule
);
1477 record_ws_error(result
, line
+ 1, len
- 2, linenr
);
1481 * Parse a unified diff. Note that this really needs to parse each
1482 * fragment separately, since the only way to know the difference
1483 * between a "---" that is part of a patch, and a "---" that starts
1484 * the next patch is to look at the line counts..
1486 static int parse_fragment(char *line
, unsigned long size
,
1487 struct patch
*patch
, struct fragment
*fragment
)
1490 int len
= linelen(line
, size
), offset
;
1491 unsigned long oldlines
, newlines
;
1492 unsigned long leading
, trailing
;
1494 offset
= parse_fragment_header(line
, len
, fragment
);
1497 if (offset
> 0 && patch
->recount
)
1498 recount_diff(line
+ offset
, size
- offset
, fragment
);
1499 oldlines
= fragment
->oldlines
;
1500 newlines
= fragment
->newlines
;
1504 /* Parse the thing.. */
1508 added
= deleted
= 0;
1511 offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1512 if (!oldlines
&& !newlines
)
1514 len
= linelen(line
, size
);
1515 if (!len
|| line
[len
-1] != '\n')
1520 case '\n': /* newer GNU diff, an empty context line */
1524 if (!deleted
&& !added
)
1529 if (apply_in_reverse
&&
1530 ws_error_action
!= nowarn_ws_error
)
1531 check_whitespace(line
, len
, patch
->ws_rule
);
1537 if (!apply_in_reverse
&&
1538 ws_error_action
!= nowarn_ws_error
)
1539 check_whitespace(line
, len
, patch
->ws_rule
);
1546 * We allow "\ No newline at end of file". Depending
1547 * on locale settings when the patch was produced we
1548 * don't know what this line looks like. The only
1549 * thing we do know is that it begins with "\ ".
1550 * Checking for 12 is just for sanity check -- any
1551 * l10n of "\ No newline..." is at least that long.
1554 if (len
< 12 || memcmp(line
, "\\ ", 2))
1559 if (oldlines
|| newlines
)
1561 fragment
->leading
= leading
;
1562 fragment
->trailing
= trailing
;
1565 * If a fragment ends with an incomplete line, we failed to include
1566 * it in the above loop because we hit oldlines == newlines == 0
1569 if (12 < size
&& !memcmp(line
, "\\ ", 2))
1570 offset
+= linelen(line
, size
);
1572 patch
->lines_added
+= added
;
1573 patch
->lines_deleted
+= deleted
;
1575 if (0 < patch
->is_new
&& oldlines
)
1576 return error("new file depends on old contents");
1577 if (0 < patch
->is_delete
&& newlines
)
1578 return error("deleted file still has contents");
1582 static int parse_single_patch(char *line
, unsigned long size
, struct patch
*patch
)
1584 unsigned long offset
= 0;
1585 unsigned long oldlines
= 0, newlines
= 0, context
= 0;
1586 struct fragment
**fragp
= &patch
->fragments
;
1588 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
1589 struct fragment
*fragment
;
1592 fragment
= xcalloc(1, sizeof(*fragment
));
1593 fragment
->linenr
= linenr
;
1594 len
= parse_fragment(line
, size
, patch
, fragment
);
1596 die("corrupt patch at line %d", linenr
);
1597 fragment
->patch
= line
;
1598 fragment
->size
= len
;
1599 oldlines
+= fragment
->oldlines
;
1600 newlines
+= fragment
->newlines
;
1601 context
+= fragment
->leading
+ fragment
->trailing
;
1604 fragp
= &fragment
->next
;
1612 * If something was removed (i.e. we have old-lines) it cannot
1613 * be creation, and if something was added it cannot be
1614 * deletion. However, the reverse is not true; --unified=0
1615 * patches that only add are not necessarily creation even
1616 * though they do not have any old lines, and ones that only
1617 * delete are not necessarily deletion.
1619 * Unfortunately, a real creation/deletion patch do _not_ have
1620 * any context line by definition, so we cannot safely tell it
1621 * apart with --unified=0 insanity. At least if the patch has
1622 * more than one hunk it is not creation or deletion.
1624 if (patch
->is_new
< 0 &&
1625 (oldlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1627 if (patch
->is_delete
< 0 &&
1628 (newlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1629 patch
->is_delete
= 0;
1631 if (0 < patch
->is_new
&& oldlines
)
1632 die("new file %s depends on old contents", patch
->new_name
);
1633 if (0 < patch
->is_delete
&& newlines
)
1634 die("deleted file %s still has contents", patch
->old_name
);
1635 if (!patch
->is_delete
&& !newlines
&& context
)
1636 fprintf(stderr
, "** warning: file %s becomes empty but "
1637 "is not deleted\n", patch
->new_name
);
1642 static inline int metadata_changes(struct patch
*patch
)
1644 return patch
->is_rename
> 0 ||
1645 patch
->is_copy
> 0 ||
1646 patch
->is_new
> 0 ||
1648 (patch
->old_mode
&& patch
->new_mode
&&
1649 patch
->old_mode
!= patch
->new_mode
);
1652 static char *inflate_it(const void *data
, unsigned long size
,
1653 unsigned long inflated_size
)
1659 memset(&stream
, 0, sizeof(stream
));
1661 stream
.next_in
= (unsigned char *)data
;
1662 stream
.avail_in
= size
;
1663 stream
.next_out
= out
= xmalloc(inflated_size
);
1664 stream
.avail_out
= inflated_size
;
1665 git_inflate_init(&stream
);
1666 st
= git_inflate(&stream
, Z_FINISH
);
1667 git_inflate_end(&stream
);
1668 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1675 static struct fragment
*parse_binary_hunk(char **buf_p
,
1676 unsigned long *sz_p
,
1681 * Expect a line that begins with binary patch method ("literal"
1682 * or "delta"), followed by the length of data before deflating.
1683 * a sequence of 'length-byte' followed by base-85 encoded data
1684 * should follow, terminated by a newline.
1686 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1687 * and we would limit the patch line to 66 characters,
1688 * so one line can fit up to 13 groups that would decode
1689 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1690 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1693 unsigned long size
= *sz_p
;
1694 char *buffer
= *buf_p
;
1696 unsigned long origlen
;
1699 struct fragment
*frag
;
1701 llen
= linelen(buffer
, size
);
1706 if (!prefixcmp(buffer
, "delta ")) {
1707 patch_method
= BINARY_DELTA_DEFLATED
;
1708 origlen
= strtoul(buffer
+ 6, NULL
, 10);
1710 else if (!prefixcmp(buffer
, "literal ")) {
1711 patch_method
= BINARY_LITERAL_DEFLATED
;
1712 origlen
= strtoul(buffer
+ 8, NULL
, 10);
1720 int byte_length
, max_byte_length
, newsize
;
1721 llen
= linelen(buffer
, size
);
1725 /* consume the blank line */
1731 * Minimum line is "A00000\n" which is 7-byte long,
1732 * and the line length must be multiple of 5 plus 2.
1734 if ((llen
< 7) || (llen
-2) % 5)
1736 max_byte_length
= (llen
- 2) / 5 * 4;
1737 byte_length
= *buffer
;
1738 if ('A' <= byte_length
&& byte_length
<= 'Z')
1739 byte_length
= byte_length
- 'A' + 1;
1740 else if ('a' <= byte_length
&& byte_length
<= 'z')
1741 byte_length
= byte_length
- 'a' + 27;
1744 /* if the input length was not multiple of 4, we would
1745 * have filler at the end but the filler should never
1748 if (max_byte_length
< byte_length
||
1749 byte_length
<= max_byte_length
- 4)
1751 newsize
= hunk_size
+ byte_length
;
1752 data
= xrealloc(data
, newsize
);
1753 if (decode_85(data
+ hunk_size
, buffer
+ 1, byte_length
))
1755 hunk_size
= newsize
;
1760 frag
= xcalloc(1, sizeof(*frag
));
1761 frag
->patch
= inflate_it(data
, hunk_size
, origlen
);
1765 frag
->size
= origlen
;
1769 frag
->binary_patch_method
= patch_method
;
1775 error("corrupt binary patch at line %d: %.*s",
1776 linenr
-1, llen
-1, buffer
);
1780 static int parse_binary(char *buffer
, unsigned long size
, struct patch
*patch
)
1783 * We have read "GIT binary patch\n"; what follows is a line
1784 * that says the patch method (currently, either "literal" or
1785 * "delta") and the length of data before deflating; a
1786 * sequence of 'length-byte' followed by base-85 encoded data
1789 * When a binary patch is reversible, there is another binary
1790 * hunk in the same format, starting with patch method (either
1791 * "literal" or "delta") with the length of data, and a sequence
1792 * of length-byte + base-85 encoded data, terminated with another
1793 * empty line. This data, when applied to the postimage, produces
1796 struct fragment
*forward
;
1797 struct fragment
*reverse
;
1801 forward
= parse_binary_hunk(&buffer
, &size
, &status
, &used
);
1802 if (!forward
&& !status
)
1803 /* there has to be one hunk (forward hunk) */
1804 return error("unrecognized binary patch at line %d", linenr
-1);
1806 /* otherwise we already gave an error message */
1809 reverse
= parse_binary_hunk(&buffer
, &size
, &status
, &used_1
);
1814 * Not having reverse hunk is not an error, but having
1815 * a corrupt reverse hunk is.
1817 free((void*) forward
->patch
);
1821 forward
->next
= reverse
;
1822 patch
->fragments
= forward
;
1823 patch
->is_binary
= 1;
1827 static int parse_chunk(char *buffer
, unsigned long size
, struct patch
*patch
)
1829 int hdrsize
, patchsize
;
1830 int offset
= find_header(buffer
, size
, &hdrsize
, patch
);
1835 patch
->ws_rule
= whitespace_rule(patch
->new_name
1839 patchsize
= parse_single_patch(buffer
+ offset
+ hdrsize
,
1840 size
- offset
- hdrsize
, patch
);
1843 static const char *binhdr
[] = {
1848 static const char git_binary
[] = "GIT binary patch\n";
1850 int hd
= hdrsize
+ offset
;
1851 unsigned long llen
= linelen(buffer
+ hd
, size
- hd
);
1853 if (llen
== sizeof(git_binary
) - 1 &&
1854 !memcmp(git_binary
, buffer
+ hd
, llen
)) {
1857 used
= parse_binary(buffer
+ hd
+ llen
,
1858 size
- hd
- llen
, patch
);
1860 patchsize
= used
+ llen
;
1864 else if (!memcmp(" differ\n", buffer
+ hd
+ llen
- 8, 8)) {
1865 for (i
= 0; binhdr
[i
]; i
++) {
1866 int len
= strlen(binhdr
[i
]);
1867 if (len
< size
- hd
&&
1868 !memcmp(binhdr
[i
], buffer
+ hd
, len
)) {
1870 patch
->is_binary
= 1;
1877 /* Empty patch cannot be applied if it is a text patch
1878 * without metadata change. A binary patch appears
1881 if ((apply
|| check
) &&
1882 (!patch
->is_binary
&& !metadata_changes(patch
)))
1883 die("patch with only garbage at line %d", linenr
);
1886 return offset
+ hdrsize
+ patchsize
;
1889 #define swap(a,b) myswap((a),(b),sizeof(a))
1891 #define myswap(a, b, size) do { \
1892 unsigned char mytmp[size]; \
1893 memcpy(mytmp, &a, size); \
1894 memcpy(&a, &b, size); \
1895 memcpy(&b, mytmp, size); \
1898 static void reverse_patches(struct patch
*p
)
1900 for (; p
; p
= p
->next
) {
1901 struct fragment
*frag
= p
->fragments
;
1903 swap(p
->new_name
, p
->old_name
);
1904 swap(p
->new_mode
, p
->old_mode
);
1905 swap(p
->is_new
, p
->is_delete
);
1906 swap(p
->lines_added
, p
->lines_deleted
);
1907 swap(p
->old_sha1_prefix
, p
->new_sha1_prefix
);
1909 for (; frag
; frag
= frag
->next
) {
1910 swap(frag
->newpos
, frag
->oldpos
);
1911 swap(frag
->newlines
, frag
->oldlines
);
1916 static const char pluses
[] =
1917 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1918 static const char minuses
[]=
1919 "----------------------------------------------------------------------";
1921 static void show_stats(struct patch
*patch
)
1923 struct strbuf qname
= STRBUF_INIT
;
1924 char *cp
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
1927 quote_c_style(cp
, &qname
, NULL
, 0);
1930 * "scale" the filename
1936 if (qname
.len
> max
) {
1937 cp
= strchr(qname
.buf
+ qname
.len
+ 3 - max
, '/');
1939 cp
= qname
.buf
+ qname
.len
+ 3 - max
;
1940 strbuf_splice(&qname
, 0, cp
- qname
.buf
, "...", 3);
1943 if (patch
->is_binary
) {
1944 printf(" %-*s | Bin\n", max
, qname
.buf
);
1945 strbuf_release(&qname
);
1949 printf(" %-*s |", max
, qname
.buf
);
1950 strbuf_release(&qname
);
1953 * scale the add/delete
1955 max
= max
+ max_change
> 70 ? 70 - max
: max_change
;
1956 add
= patch
->lines_added
;
1957 del
= patch
->lines_deleted
;
1959 if (max_change
> 0) {
1960 int total
= ((add
+ del
) * max
+ max_change
/ 2) / max_change
;
1961 add
= (add
* max
+ max_change
/ 2) / max_change
;
1964 printf("%5d %.*s%.*s\n", patch
->lines_added
+ patch
->lines_deleted
,
1965 add
, pluses
, del
, minuses
);
1968 static int read_old_data(struct stat
*st
, const char *path
, struct strbuf
*buf
)
1970 switch (st
->st_mode
& S_IFMT
) {
1972 if (strbuf_readlink(buf
, path
, st
->st_size
) < 0)
1973 return error("unable to read symlink %s", path
);
1976 if (strbuf_read_file(buf
, path
, st
->st_size
) != st
->st_size
)
1977 return error("unable to open or read %s", path
);
1978 convert_to_git(path
, buf
->buf
, buf
->len
, buf
, 0);
1986 * Update the preimage, and the common lines in postimage,
1987 * from buffer buf of length len. If postlen is 0 the postimage
1988 * is updated in place, otherwise it's updated on a new buffer
1992 static void update_pre_post_images(struct image
*preimage
,
1993 struct image
*postimage
,
1995 size_t len
, size_t postlen
)
1998 char *new, *old
, *fixed
;
1999 struct image fixed_preimage
;
2002 * Update the preimage with whitespace fixes. Note that we
2003 * are not losing preimage->buf -- apply_one_fragment() will
2006 prepare_image(&fixed_preimage
, buf
, len
, 1);
2007 assert(fixed_preimage
.nr
== preimage
->nr
);
2008 for (i
= 0; i
< preimage
->nr
; i
++)
2009 fixed_preimage
.line
[i
].flag
= preimage
->line
[i
].flag
;
2010 free(preimage
->line_allocated
);
2011 *preimage
= fixed_preimage
;
2014 * Adjust the common context lines in postimage. This can be
2015 * done in-place when we are just doing whitespace fixing,
2016 * which does not make the string grow, but needs a new buffer
2017 * when ignoring whitespace causes the update, since in this case
2018 * we could have e.g. tabs converted to multiple spaces.
2019 * We trust the caller to tell us if the update can be done
2020 * in place (postlen==0) or not.
2022 old
= postimage
->buf
;
2024 new = postimage
->buf
= xmalloc(postlen
);
2027 fixed
= preimage
->buf
;
2028 for (i
= ctx
= 0; i
< postimage
->nr
; i
++) {
2029 size_t len
= postimage
->line
[i
].len
;
2030 if (!(postimage
->line
[i
].flag
& LINE_COMMON
)) {
2031 /* an added line -- no counterparts in preimage */
2032 memmove(new, old
, len
);
2038 /* a common context -- skip it in the original postimage */
2041 /* and find the corresponding one in the fixed preimage */
2042 while (ctx
< preimage
->nr
&&
2043 !(preimage
->line
[ctx
].flag
& LINE_COMMON
)) {
2044 fixed
+= preimage
->line
[ctx
].len
;
2047 if (preimage
->nr
<= ctx
)
2050 /* and copy it in, while fixing the line length */
2051 len
= preimage
->line
[ctx
].len
;
2052 memcpy(new, fixed
, len
);
2055 postimage
->line
[i
].len
= len
;
2059 /* Fix the length of the whole thing */
2060 postimage
->len
= new - postimage
->buf
;
2063 static int match_fragment(struct image
*img
,
2064 struct image
*preimage
,
2065 struct image
*postimage
,
2069 int match_beginning
, int match_end
)
2072 char *fixed_buf
, *buf
, *orig
, *target
;
2073 struct strbuf fixed
;
2077 if (preimage
->nr
+ try_lno
<= img
->nr
) {
2079 * The hunk falls within the boundaries of img.
2081 preimage_limit
= preimage
->nr
;
2082 if (match_end
&& (preimage
->nr
+ try_lno
!= img
->nr
))
2084 } else if (ws_error_action
== correct_ws_error
&&
2085 (ws_rule
& WS_BLANK_AT_EOF
)) {
2087 * This hunk extends beyond the end of img, and we are
2088 * removing blank lines at the end of the file. This
2089 * many lines from the beginning of the preimage must
2090 * match with img, and the remainder of the preimage
2093 preimage_limit
= img
->nr
- try_lno
;
2096 * The hunk extends beyond the end of the img and
2097 * we are not removing blanks at the end, so we
2098 * should reject the hunk at this position.
2103 if (match_beginning
&& try_lno
)
2106 /* Quick hash check */
2107 for (i
= 0; i
< preimage_limit
; i
++)
2108 if ((img
->line
[try_lno
+ i
].flag
& LINE_PATCHED
) ||
2109 (preimage
->line
[i
].hash
!= img
->line
[try_lno
+ i
].hash
))
2112 if (preimage_limit
== preimage
->nr
) {
2114 * Do we have an exact match? If we were told to match
2115 * at the end, size must be exactly at try+fragsize,
2116 * otherwise try+fragsize must be still within the preimage,
2117 * and either case, the old piece should match the preimage
2121 ? (try + preimage
->len
== img
->len
)
2122 : (try + preimage
->len
<= img
->len
)) &&
2123 !memcmp(img
->buf
+ try, preimage
->buf
, preimage
->len
))
2127 * The preimage extends beyond the end of img, so
2128 * there cannot be an exact match.
2130 * There must be one non-blank context line that match
2131 * a line before the end of img.
2135 buf
= preimage
->buf
;
2137 for (i
= 0; i
< preimage_limit
; i
++)
2138 buf_end
+= preimage
->line
[i
].len
;
2140 for ( ; buf
< buf_end
; buf
++)
2148 * No exact match. If we are ignoring whitespace, run a line-by-line
2149 * fuzzy matching. We collect all the line length information because
2150 * we need it to adjust whitespace if we match.
2152 if (ws_ignore_action
== ignore_ws_change
) {
2155 size_t postlen
= postimage
->len
;
2159 for (i
= 0; i
< preimage_limit
; i
++) {
2160 size_t prelen
= preimage
->line
[i
].len
;
2161 size_t imglen
= img
->line
[try_lno
+i
].len
;
2163 if (!fuzzy_matchlines(img
->buf
+ try + imgoff
, imglen
,
2164 preimage
->buf
+ preoff
, prelen
))
2166 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2167 postlen
+= imglen
- prelen
;
2173 * Ok, the preimage matches with whitespace fuzz.
2175 * imgoff now holds the true length of the target that
2176 * matches the preimage before the end of the file.
2178 * Count the number of characters in the preimage that fall
2179 * beyond the end of the file and make sure that all of them
2180 * are whitespace characters. (This can only happen if
2181 * we are removing blank lines at the end of the file.)
2183 buf
= preimage_eof
= preimage
->buf
+ preoff
;
2184 for ( ; i
< preimage
->nr
; i
++)
2185 preoff
+= preimage
->line
[i
].len
;
2186 preimage_end
= preimage
->buf
+ preoff
;
2187 for ( ; buf
< preimage_end
; buf
++)
2192 * Update the preimage and the common postimage context
2193 * lines to use the same whitespace as the target.
2194 * If whitespace is missing in the target (i.e.
2195 * if the preimage extends beyond the end of the file),
2196 * use the whitespace from the preimage.
2198 extra_chars
= preimage_end
- preimage_eof
;
2199 strbuf_init(&fixed
, imgoff
+ extra_chars
);
2200 strbuf_add(&fixed
, img
->buf
+ try, imgoff
);
2201 strbuf_add(&fixed
, preimage_eof
, extra_chars
);
2202 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2203 update_pre_post_images(preimage
, postimage
,
2204 fixed_buf
, fixed_len
, postlen
);
2208 if (ws_error_action
!= correct_ws_error
)
2212 * The hunk does not apply byte-by-byte, but the hash says
2213 * it might with whitespace fuzz. We haven't been asked to
2214 * ignore whitespace, we were asked to correct whitespace
2215 * errors, so let's try matching after whitespace correction.
2217 * The preimage may extend beyond the end of the file,
2218 * but in this loop we will only handle the part of the
2219 * preimage that falls within the file.
2221 strbuf_init(&fixed
, preimage
->len
+ 1);
2222 orig
= preimage
->buf
;
2223 target
= img
->buf
+ try;
2224 for (i
= 0; i
< preimage_limit
; i
++) {
2225 size_t oldlen
= preimage
->line
[i
].len
;
2226 size_t tgtlen
= img
->line
[try_lno
+ i
].len
;
2227 size_t fixstart
= fixed
.len
;
2228 struct strbuf tgtfix
;
2231 /* Try fixing the line in the preimage */
2232 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2234 /* Try fixing the line in the target */
2235 strbuf_init(&tgtfix
, tgtlen
);
2236 ws_fix_copy(&tgtfix
, target
, tgtlen
, ws_rule
, NULL
);
2239 * If they match, either the preimage was based on
2240 * a version before our tree fixed whitespace breakage,
2241 * or we are lacking a whitespace-fix patch the tree
2242 * the preimage was based on already had (i.e. target
2243 * has whitespace breakage, the preimage doesn't).
2244 * In either case, we are fixing the whitespace breakages
2245 * so we might as well take the fix together with their
2248 match
= (tgtfix
.len
== fixed
.len
- fixstart
&&
2249 !memcmp(tgtfix
.buf
, fixed
.buf
+ fixstart
,
2250 fixed
.len
- fixstart
));
2252 strbuf_release(&tgtfix
);
2262 * Now handle the lines in the preimage that falls beyond the
2263 * end of the file (if any). They will only match if they are
2264 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2267 for ( ; i
< preimage
->nr
; i
++) {
2268 size_t fixstart
= fixed
.len
; /* start of the fixed preimage */
2269 size_t oldlen
= preimage
->line
[i
].len
;
2272 /* Try fixing the line in the preimage */
2273 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2275 for (j
= fixstart
; j
< fixed
.len
; j
++)
2276 if (!isspace(fixed
.buf
[j
]))
2283 * Yes, the preimage is based on an older version that still
2284 * has whitespace breakages unfixed, and fixing them makes the
2285 * hunk match. Update the context lines in the postimage.
2287 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2288 update_pre_post_images(preimage
, postimage
,
2289 fixed_buf
, fixed_len
, 0);
2293 strbuf_release(&fixed
);
2297 static int find_pos(struct image
*img
,
2298 struct image
*preimage
,
2299 struct image
*postimage
,
2302 int match_beginning
, int match_end
)
2305 unsigned long backwards
, forwards
, try;
2306 int backwards_lno
, forwards_lno
, try_lno
;
2309 * If match_beginning or match_end is specified, there is no
2310 * point starting from a wrong line that will never match and
2311 * wander around and wait for a match at the specified end.
2313 if (match_beginning
)
2316 line
= img
->nr
- preimage
->nr
;
2319 * Because the comparison is unsigned, the following test
2320 * will also take care of a negative line number that can
2321 * result when match_end and preimage is larger than the target.
2323 if ((size_t) line
> img
->nr
)
2327 for (i
= 0; i
< line
; i
++)
2328 try += img
->line
[i
].len
;
2331 * There's probably some smart way to do this, but I'll leave
2332 * that to the smart and beautiful people. I'm simple and stupid.
2335 backwards_lno
= line
;
2337 forwards_lno
= line
;
2340 for (i
= 0; ; i
++) {
2341 if (match_fragment(img
, preimage
, postimage
,
2342 try, try_lno
, ws_rule
,
2343 match_beginning
, match_end
))
2347 if (backwards_lno
== 0 && forwards_lno
== img
->nr
)
2351 if (backwards_lno
== 0) {
2356 backwards
-= img
->line
[backwards_lno
].len
;
2358 try_lno
= backwards_lno
;
2360 if (forwards_lno
== img
->nr
) {
2364 forwards
+= img
->line
[forwards_lno
].len
;
2367 try_lno
= forwards_lno
;
2374 static void remove_first_line(struct image
*img
)
2376 img
->buf
+= img
->line
[0].len
;
2377 img
->len
-= img
->line
[0].len
;
2382 static void remove_last_line(struct image
*img
)
2384 img
->len
-= img
->line
[--img
->nr
].len
;
2387 static void update_image(struct image
*img
,
2389 struct image
*preimage
,
2390 struct image
*postimage
)
2393 * remove the copy of preimage at offset in img
2394 * and replace it with postimage
2397 size_t remove_count
, insert_count
, applied_at
= 0;
2402 * If we are removing blank lines at the end of img,
2403 * the preimage may extend beyond the end.
2404 * If that is the case, we must be careful only to
2405 * remove the part of the preimage that falls within
2406 * the boundaries of img. Initialize preimage_limit
2407 * to the number of lines in the preimage that falls
2408 * within the boundaries.
2410 preimage_limit
= preimage
->nr
;
2411 if (preimage_limit
> img
->nr
- applied_pos
)
2412 preimage_limit
= img
->nr
- applied_pos
;
2414 for (i
= 0; i
< applied_pos
; i
++)
2415 applied_at
+= img
->line
[i
].len
;
2418 for (i
= 0; i
< preimage_limit
; i
++)
2419 remove_count
+= img
->line
[applied_pos
+ i
].len
;
2420 insert_count
= postimage
->len
;
2422 /* Adjust the contents */
2423 result
= xmalloc(img
->len
+ insert_count
- remove_count
+ 1);
2424 memcpy(result
, img
->buf
, applied_at
);
2425 memcpy(result
+ applied_at
, postimage
->buf
, postimage
->len
);
2426 memcpy(result
+ applied_at
+ postimage
->len
,
2427 img
->buf
+ (applied_at
+ remove_count
),
2428 img
->len
- (applied_at
+ remove_count
));
2431 img
->len
+= insert_count
- remove_count
;
2432 result
[img
->len
] = '\0';
2434 /* Adjust the line table */
2435 nr
= img
->nr
+ postimage
->nr
- preimage_limit
;
2436 if (preimage_limit
< postimage
->nr
) {
2438 * NOTE: this knows that we never call remove_first_line()
2439 * on anything other than pre/post image.
2441 img
->line
= xrealloc(img
->line
, nr
* sizeof(*img
->line
));
2442 img
->line_allocated
= img
->line
;
2444 if (preimage_limit
!= postimage
->nr
)
2445 memmove(img
->line
+ applied_pos
+ postimage
->nr
,
2446 img
->line
+ applied_pos
+ preimage_limit
,
2447 (img
->nr
- (applied_pos
+ preimage_limit
)) *
2448 sizeof(*img
->line
));
2449 memcpy(img
->line
+ applied_pos
,
2451 postimage
->nr
* sizeof(*img
->line
));
2453 for (i
= 0; i
< postimage
->nr
; i
++)
2454 img
->line
[applied_pos
+ i
].flag
|= LINE_PATCHED
;
2458 static int apply_one_fragment(struct image
*img
, struct fragment
*frag
,
2459 int inaccurate_eof
, unsigned ws_rule
,
2462 int match_beginning
, match_end
;
2463 const char *patch
= frag
->patch
;
2464 int size
= frag
->size
;
2465 char *old
, *oldlines
;
2466 struct strbuf newlines
;
2467 int new_blank_lines_at_end
= 0;
2468 int found_new_blank_lines_at_end
= 0;
2469 int hunk_linenr
= frag
->linenr
;
2470 unsigned long leading
, trailing
;
2471 int pos
, applied_pos
;
2472 struct image preimage
;
2473 struct image postimage
;
2475 memset(&preimage
, 0, sizeof(preimage
));
2476 memset(&postimage
, 0, sizeof(postimage
));
2477 oldlines
= xmalloc(size
);
2478 strbuf_init(&newlines
, size
);
2483 int len
= linelen(patch
, size
);
2485 int added_blank_line
= 0;
2486 int is_blank_context
= 0;
2493 * "plen" is how much of the line we should use for
2494 * the actual patch data. Normally we just remove the
2495 * first character on the line, but if the line is
2496 * followed by "\ No newline", then we also remove the
2497 * last one (which is the newline, of course).
2500 if (len
< size
&& patch
[len
] == '\\')
2503 if (apply_in_reverse
) {
2506 else if (first
== '+')
2512 /* Newer GNU diff, empty context line */
2514 /* ... followed by '\No newline'; nothing */
2517 strbuf_addch(&newlines
, '\n');
2518 add_line_info(&preimage
, "\n", 1, LINE_COMMON
);
2519 add_line_info(&postimage
, "\n", 1, LINE_COMMON
);
2520 is_blank_context
= 1;
2523 if (plen
&& (ws_rule
& WS_BLANK_AT_EOF
) &&
2524 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2525 is_blank_context
= 1;
2527 memcpy(old
, patch
+ 1, plen
);
2528 add_line_info(&preimage
, old
, plen
,
2529 (first
== ' ' ? LINE_COMMON
: 0));
2533 /* Fall-through for ' ' */
2535 /* --no-add does not add new lines */
2536 if (first
== '+' && no_add
)
2539 start
= newlines
.len
;
2541 !whitespace_error
||
2542 ws_error_action
!= correct_ws_error
) {
2543 strbuf_add(&newlines
, patch
+ 1, plen
);
2546 ws_fix_copy(&newlines
, patch
+ 1, plen
, ws_rule
, &applied_after_fixing_ws
);
2548 add_line_info(&postimage
, newlines
.buf
+ start
, newlines
.len
- start
,
2549 (first
== '+' ? 0 : LINE_COMMON
));
2551 (ws_rule
& WS_BLANK_AT_EOF
) &&
2552 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2553 added_blank_line
= 1;
2555 case '@': case '\\':
2556 /* Ignore it, we already handled it */
2559 if (apply_verbosely
)
2560 error("invalid start of line: '%c'", first
);
2563 if (added_blank_line
) {
2564 if (!new_blank_lines_at_end
)
2565 found_new_blank_lines_at_end
= hunk_linenr
;
2566 new_blank_lines_at_end
++;
2568 else if (is_blank_context
)
2571 new_blank_lines_at_end
= 0;
2576 if (inaccurate_eof
&&
2577 old
> oldlines
&& old
[-1] == '\n' &&
2578 newlines
.len
> 0 && newlines
.buf
[newlines
.len
- 1] == '\n') {
2580 strbuf_setlen(&newlines
, newlines
.len
- 1);
2583 leading
= frag
->leading
;
2584 trailing
= frag
->trailing
;
2587 * A hunk to change lines at the beginning would begin with
2589 * but we need to be careful. -U0 that inserts before the second
2590 * line also has this pattern.
2592 * And a hunk to add to an empty file would begin with
2595 * In other words, a hunk that is (frag->oldpos <= 1) with or
2596 * without leading context must match at the beginning.
2598 match_beginning
= (!frag
->oldpos
||
2599 (frag
->oldpos
== 1 && !unidiff_zero
));
2602 * A hunk without trailing lines must match at the end.
2603 * However, we simply cannot tell if a hunk must match end
2604 * from the lack of trailing lines if the patch was generated
2605 * with unidiff without any context.
2607 match_end
= !unidiff_zero
&& !trailing
;
2609 pos
= frag
->newpos
? (frag
->newpos
- 1) : 0;
2610 preimage
.buf
= oldlines
;
2611 preimage
.len
= old
- oldlines
;
2612 postimage
.buf
= newlines
.buf
;
2613 postimage
.len
= newlines
.len
;
2614 preimage
.line
= preimage
.line_allocated
;
2615 postimage
.line
= postimage
.line_allocated
;
2619 applied_pos
= find_pos(img
, &preimage
, &postimage
, pos
,
2620 ws_rule
, match_beginning
, match_end
);
2622 if (applied_pos
>= 0)
2625 /* Am I at my context limits? */
2626 if ((leading
<= p_context
) && (trailing
<= p_context
))
2628 if (match_beginning
|| match_end
) {
2629 match_beginning
= match_end
= 0;
2634 * Reduce the number of context lines; reduce both
2635 * leading and trailing if they are equal otherwise
2636 * just reduce the larger context.
2638 if (leading
>= trailing
) {
2639 remove_first_line(&preimage
);
2640 remove_first_line(&postimage
);
2644 if (trailing
> leading
) {
2645 remove_last_line(&preimage
);
2646 remove_last_line(&postimage
);
2651 if (applied_pos
>= 0) {
2652 if (new_blank_lines_at_end
&&
2653 preimage
.nr
+ applied_pos
>= img
->nr
&&
2654 (ws_rule
& WS_BLANK_AT_EOF
) &&
2655 ws_error_action
!= nowarn_ws_error
) {
2656 record_ws_error(WS_BLANK_AT_EOF
, "+", 1,
2657 found_new_blank_lines_at_end
);
2658 if (ws_error_action
== correct_ws_error
) {
2659 while (new_blank_lines_at_end
--)
2660 remove_last_line(&postimage
);
2663 * We would want to prevent write_out_results()
2664 * from taking place in apply_patch() that follows
2665 * the callchain led us here, which is:
2666 * apply_patch->check_patch_list->check_patch->
2667 * apply_data->apply_fragments->apply_one_fragment
2669 if (ws_error_action
== die_on_ws_error
)
2673 if (apply_verbosely
&& applied_pos
!= pos
) {
2674 int offset
= applied_pos
- pos
;
2675 if (apply_in_reverse
)
2676 offset
= 0 - offset
;
2678 "Hunk #%d succeeded at %d (offset %d lines).\n",
2679 nth_fragment
, applied_pos
+ 1, offset
);
2683 * Warn if it was necessary to reduce the number
2686 if ((leading
!= frag
->leading
) ||
2687 (trailing
!= frag
->trailing
))
2688 fprintf(stderr
, "Context reduced to (%ld/%ld)"
2689 " to apply fragment at %d\n",
2690 leading
, trailing
, applied_pos
+1);
2691 update_image(img
, applied_pos
, &preimage
, &postimage
);
2693 if (apply_verbosely
)
2694 error("while searching for:\n%.*s",
2695 (int)(old
- oldlines
), oldlines
);
2699 strbuf_release(&newlines
);
2700 free(preimage
.line_allocated
);
2701 free(postimage
.line_allocated
);
2703 return (applied_pos
< 0);
2706 static int apply_binary_fragment(struct image
*img
, struct patch
*patch
)
2708 struct fragment
*fragment
= patch
->fragments
;
2713 return error("missing binary patch data for '%s'",
2718 /* Binary patch is irreversible without the optional second hunk */
2719 if (apply_in_reverse
) {
2720 if (!fragment
->next
)
2721 return error("cannot reverse-apply a binary patch "
2722 "without the reverse hunk to '%s'",
2724 ? patch
->new_name
: patch
->old_name
);
2725 fragment
= fragment
->next
;
2727 switch (fragment
->binary_patch_method
) {
2728 case BINARY_DELTA_DEFLATED
:
2729 dst
= patch_delta(img
->buf
, img
->len
, fragment
->patch
,
2730 fragment
->size
, &len
);
2737 case BINARY_LITERAL_DEFLATED
:
2739 img
->len
= fragment
->size
;
2740 img
->buf
= xmalloc(img
->len
+1);
2741 memcpy(img
->buf
, fragment
->patch
, img
->len
);
2742 img
->buf
[img
->len
] = '\0';
2748 static int apply_binary(struct image
*img
, struct patch
*patch
)
2750 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
2751 unsigned char sha1
[20];
2754 * For safety, we require patch index line to contain
2755 * full 40-byte textual SHA1 for old and new, at least for now.
2757 if (strlen(patch
->old_sha1_prefix
) != 40 ||
2758 strlen(patch
->new_sha1_prefix
) != 40 ||
2759 get_sha1_hex(patch
->old_sha1_prefix
, sha1
) ||
2760 get_sha1_hex(patch
->new_sha1_prefix
, sha1
))
2761 return error("cannot apply binary patch to '%s' "
2762 "without full index line", name
);
2764 if (patch
->old_name
) {
2766 * See if the old one matches what the patch
2769 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
2770 if (strcmp(sha1_to_hex(sha1
), patch
->old_sha1_prefix
))
2771 return error("the patch applies to '%s' (%s), "
2772 "which does not match the "
2773 "current contents.",
2774 name
, sha1_to_hex(sha1
));
2777 /* Otherwise, the old one must be empty. */
2779 return error("the patch applies to an empty "
2780 "'%s' but it is not empty", name
);
2783 get_sha1_hex(patch
->new_sha1_prefix
, sha1
);
2784 if (is_null_sha1(sha1
)) {
2786 return 0; /* deletion patch */
2789 if (has_sha1_file(sha1
)) {
2790 /* We already have the postimage */
2791 enum object_type type
;
2795 result
= read_sha1_file(sha1
, &type
, &size
);
2797 return error("the necessary postimage %s for "
2798 "'%s' cannot be read",
2799 patch
->new_sha1_prefix
, name
);
2805 * We have verified buf matches the preimage;
2806 * apply the patch data to it, which is stored
2807 * in the patch->fragments->{patch,size}.
2809 if (apply_binary_fragment(img
, patch
))
2810 return error("binary patch does not apply to '%s'",
2813 /* verify that the result matches */
2814 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
2815 if (strcmp(sha1_to_hex(sha1
), patch
->new_sha1_prefix
))
2816 return error("binary patch to '%s' creates incorrect result (expecting %s, got %s)",
2817 name
, patch
->new_sha1_prefix
, sha1_to_hex(sha1
));
2823 static int apply_fragments(struct image
*img
, struct patch
*patch
)
2825 struct fragment
*frag
= patch
->fragments
;
2826 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
2827 unsigned ws_rule
= patch
->ws_rule
;
2828 unsigned inaccurate_eof
= patch
->inaccurate_eof
;
2831 if (patch
->is_binary
)
2832 return apply_binary(img
, patch
);
2836 if (apply_one_fragment(img
, frag
, inaccurate_eof
, ws_rule
, nth
)) {
2837 error("patch failed: %s:%ld", name
, frag
->oldpos
);
2838 if (!apply_with_reject
)
2847 static int read_file_or_gitlink(struct cache_entry
*ce
, struct strbuf
*buf
)
2852 if (S_ISGITLINK(ce
->ce_mode
)) {
2853 strbuf_grow(buf
, 100);
2854 strbuf_addf(buf
, "Subproject commit %s\n", sha1_to_hex(ce
->sha1
));
2856 enum object_type type
;
2860 result
= read_sha1_file(ce
->sha1
, &type
, &sz
);
2863 /* XXX read_sha1_file NUL-terminates */
2864 strbuf_attach(buf
, result
, sz
, sz
+ 1);
2869 static struct patch
*in_fn_table(const char *name
)
2871 struct string_list_item
*item
;
2876 item
= string_list_lookup(&fn_table
, name
);
2878 return (struct patch
*)item
->util
;
2884 * item->util in the filename table records the status of the path.
2885 * Usually it points at a patch (whose result records the contents
2886 * of it after applying it), but it could be PATH_WAS_DELETED for a
2887 * path that a previously applied patch has already removed.
2889 #define PATH_TO_BE_DELETED ((struct patch *) -2)
2890 #define PATH_WAS_DELETED ((struct patch *) -1)
2892 static int to_be_deleted(struct patch
*patch
)
2894 return patch
== PATH_TO_BE_DELETED
;
2897 static int was_deleted(struct patch
*patch
)
2899 return patch
== PATH_WAS_DELETED
;
2902 static void add_to_fn_table(struct patch
*patch
)
2904 struct string_list_item
*item
;
2907 * Always add new_name unless patch is a deletion
2908 * This should cover the cases for normal diffs,
2909 * file creations and copies
2911 if (patch
->new_name
!= NULL
) {
2912 item
= string_list_insert(&fn_table
, patch
->new_name
);
2917 * store a failure on rename/deletion cases because
2918 * later chunks shouldn't patch old names
2920 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
2921 item
= string_list_insert(&fn_table
, patch
->old_name
);
2922 item
->util
= PATH_WAS_DELETED
;
2926 static void prepare_fn_table(struct patch
*patch
)
2929 * store information about incoming file deletion
2932 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
2933 struct string_list_item
*item
;
2934 item
= string_list_insert(&fn_table
, patch
->old_name
);
2935 item
->util
= PATH_TO_BE_DELETED
;
2937 patch
= patch
->next
;
2941 static int apply_data(struct patch
*patch
, struct stat
*st
, struct cache_entry
*ce
)
2943 struct strbuf buf
= STRBUF_INIT
;
2947 struct patch
*tpatch
;
2949 if (!(patch
->is_copy
|| patch
->is_rename
) &&
2950 (tpatch
= in_fn_table(patch
->old_name
)) != NULL
&& !to_be_deleted(tpatch
)) {
2951 if (was_deleted(tpatch
)) {
2952 return error("patch %s has been renamed/deleted",
2955 /* We have a patched copy in memory use that */
2956 strbuf_add(&buf
, tpatch
->result
, tpatch
->resultsize
);
2957 } else if (cached
) {
2958 if (read_file_or_gitlink(ce
, &buf
))
2959 return error("read of %s failed", patch
->old_name
);
2960 } else if (patch
->old_name
) {
2961 if (S_ISGITLINK(patch
->old_mode
)) {
2963 read_file_or_gitlink(ce
, &buf
);
2966 * There is no way to apply subproject
2967 * patch without looking at the index.
2969 patch
->fragments
= NULL
;
2972 if (read_old_data(st
, patch
->old_name
, &buf
))
2973 return error("read of %s failed", patch
->old_name
);
2977 img
= strbuf_detach(&buf
, &len
);
2978 prepare_image(&image
, img
, len
, !patch
->is_binary
);
2980 if (apply_fragments(&image
, patch
) < 0)
2981 return -1; /* note with --reject this succeeds. */
2982 patch
->result
= image
.buf
;
2983 patch
->resultsize
= image
.len
;
2984 add_to_fn_table(patch
);
2985 free(image
.line_allocated
);
2987 if (0 < patch
->is_delete
&& patch
->resultsize
)
2988 return error("removal patch leaves file contents");
2993 static int check_to_create_blob(const char *new_name
, int ok_if_exists
)
2996 if (!lstat(new_name
, &nst
)) {
2997 if (S_ISDIR(nst
.st_mode
) || ok_if_exists
)
3000 * A leading component of new_name might be a symlink
3001 * that is going to be removed with this patch, but
3002 * still pointing at somewhere that has the path.
3003 * In such a case, path "new_name" does not exist as
3004 * far as git is concerned.
3006 if (has_symlink_leading_path(new_name
, strlen(new_name
)))
3009 return error("%s: already exists in working directory", new_name
);
3011 else if ((errno
!= ENOENT
) && (errno
!= ENOTDIR
))
3012 return error("%s: %s", new_name
, strerror(errno
));
3016 static int verify_index_match(struct cache_entry
*ce
, struct stat
*st
)
3018 if (S_ISGITLINK(ce
->ce_mode
)) {
3019 if (!S_ISDIR(st
->st_mode
))
3023 return ce_match_stat(ce
, st
, CE_MATCH_IGNORE_VALID
|CE_MATCH_IGNORE_SKIP_WORKTREE
);
3026 static int check_preimage(struct patch
*patch
, struct cache_entry
**ce
, struct stat
*st
)
3028 const char *old_name
= patch
->old_name
;
3029 struct patch
*tpatch
= NULL
;
3031 unsigned st_mode
= 0;
3034 * Make sure that we do not have local modifications from the
3035 * index when we are looking at the index. Also make sure
3036 * we have the preimage file to be patched in the work tree,
3037 * unless --cached, which tells git to apply only in the index.
3042 assert(patch
->is_new
<= 0);
3044 if (!(patch
->is_copy
|| patch
->is_rename
) &&
3045 (tpatch
= in_fn_table(old_name
)) != NULL
&& !to_be_deleted(tpatch
)) {
3046 if (was_deleted(tpatch
))
3047 return error("%s: has been deleted/renamed", old_name
);
3048 st_mode
= tpatch
->new_mode
;
3049 } else if (!cached
) {
3050 stat_ret
= lstat(old_name
, st
);
3051 if (stat_ret
&& errno
!= ENOENT
)
3052 return error("%s: %s", old_name
, strerror(errno
));
3055 if (to_be_deleted(tpatch
))
3058 if (check_index
&& !tpatch
) {
3059 int pos
= cache_name_pos(old_name
, strlen(old_name
));
3061 if (patch
->is_new
< 0)
3063 return error("%s: does not exist in index", old_name
);
3065 *ce
= active_cache
[pos
];
3067 struct checkout costate
;
3069 memset(&costate
, 0, sizeof(costate
));
3070 costate
.base_dir
= "";
3071 costate
.refresh_cache
= 1;
3072 if (checkout_entry(*ce
, &costate
, NULL
) ||
3073 lstat(old_name
, st
))
3076 if (!cached
&& verify_index_match(*ce
, st
))
3077 return error("%s: does not match index", old_name
);
3079 st_mode
= (*ce
)->ce_mode
;
3080 } else if (stat_ret
< 0) {
3081 if (patch
->is_new
< 0)
3083 return error("%s: %s", old_name
, strerror(errno
));
3086 if (!cached
&& !tpatch
)
3087 st_mode
= ce_mode_from_stat(*ce
, st
->st_mode
);
3089 if (patch
->is_new
< 0)
3091 if (!patch
->old_mode
)
3092 patch
->old_mode
= st_mode
;
3093 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
3094 return error("%s: wrong type", old_name
);
3095 if (st_mode
!= patch
->old_mode
)
3096 warning("%s has type %o, expected %o",
3097 old_name
, st_mode
, patch
->old_mode
);
3098 if (!patch
->new_mode
&& !patch
->is_delete
)
3099 patch
->new_mode
= st_mode
;
3104 patch
->is_delete
= 0;
3105 patch
->old_name
= NULL
;
3109 static int check_patch(struct patch
*patch
)
3112 const char *old_name
= patch
->old_name
;
3113 const char *new_name
= patch
->new_name
;
3114 const char *name
= old_name
? old_name
: new_name
;
3115 struct cache_entry
*ce
= NULL
;
3116 struct patch
*tpatch
;
3120 patch
->rejected
= 1; /* we will drop this after we succeed */
3122 status
= check_preimage(patch
, &ce
, &st
);
3125 old_name
= patch
->old_name
;
3127 if ((tpatch
= in_fn_table(new_name
)) &&
3128 (was_deleted(tpatch
) || to_be_deleted(tpatch
)))
3130 * A type-change diff is always split into a patch to
3131 * delete old, immediately followed by a patch to
3132 * create new (see diff.c::run_diff()); in such a case
3133 * it is Ok that the entry to be deleted by the
3134 * previous patch is still in the working tree and in
3142 ((0 < patch
->is_new
) | (0 < patch
->is_rename
) | patch
->is_copy
)) {
3144 cache_name_pos(new_name
, strlen(new_name
)) >= 0 &&
3146 return error("%s: already exists in index", new_name
);
3148 int err
= check_to_create_blob(new_name
, ok_if_exists
);
3152 if (!patch
->new_mode
) {
3153 if (0 < patch
->is_new
)
3154 patch
->new_mode
= S_IFREG
| 0644;
3156 patch
->new_mode
= patch
->old_mode
;
3160 if (new_name
&& old_name
) {
3161 int same
= !strcmp(old_name
, new_name
);
3162 if (!patch
->new_mode
)
3163 patch
->new_mode
= patch
->old_mode
;
3164 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
)
3165 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
3166 patch
->new_mode
, new_name
, patch
->old_mode
,
3167 same
? "" : " of ", same
? "" : old_name
);
3170 if (apply_data(patch
, &st
, ce
) < 0)
3171 return error("%s: patch does not apply", name
);
3172 patch
->rejected
= 0;
3176 static int check_patch_list(struct patch
*patch
)
3180 prepare_fn_table(patch
);
3182 if (apply_verbosely
)
3183 say_patch_name(stderr
,
3184 "Checking patch ", patch
, "...\n");
3185 err
|= check_patch(patch
);
3186 patch
= patch
->next
;
3191 /* This function tries to read the sha1 from the current index */
3192 static int get_current_sha1(const char *path
, unsigned char *sha1
)
3196 if (read_cache() < 0)
3198 pos
= cache_name_pos(path
, strlen(path
));
3201 hashcpy(sha1
, active_cache
[pos
]->sha1
);
3205 /* Build an index that contains the just the files needed for a 3way merge */
3206 static void build_fake_ancestor(struct patch
*list
, const char *filename
)
3208 struct patch
*patch
;
3209 struct index_state result
= { NULL
};
3212 /* Once we start supporting the reverse patch, it may be
3213 * worth showing the new sha1 prefix, but until then...
3215 for (patch
= list
; patch
; patch
= patch
->next
) {
3216 const unsigned char *sha1_ptr
;
3217 unsigned char sha1
[20];
3218 struct cache_entry
*ce
;
3221 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3222 if (0 < patch
->is_new
)
3224 else if (get_sha1(patch
->old_sha1_prefix
, sha1
))
3225 /* git diff has no index line for mode/type changes */
3226 if (!patch
->lines_added
&& !patch
->lines_deleted
) {
3227 if (get_current_sha1(patch
->old_name
, sha1
))
3228 die("mode change for %s, which is not "
3229 "in current HEAD", name
);
3232 die("sha1 information is lacking or useless "
3237 ce
= make_cache_entry(patch
->old_mode
, sha1_ptr
, name
, 0, 0);
3239 die("make_cache_entry failed for path '%s'", name
);
3240 if (add_index_entry(&result
, ce
, ADD_CACHE_OK_TO_ADD
))
3241 die ("Could not add %s to temporary index", name
);
3244 fd
= open(filename
, O_WRONLY
| O_CREAT
, 0666);
3245 if (fd
< 0 || write_index(&result
, fd
) || close(fd
))
3246 die ("Could not write temporary index to %s", filename
);
3248 discard_index(&result
);
3251 static void stat_patch_list(struct patch
*patch
)
3253 int files
, adds
, dels
;
3255 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
3257 adds
+= patch
->lines_added
;
3258 dels
+= patch
->lines_deleted
;
3262 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files
, adds
, dels
);
3265 static void numstat_patch_list(struct patch
*patch
)
3267 for ( ; patch
; patch
= patch
->next
) {
3269 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
3270 if (patch
->is_binary
)
3273 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
3274 write_name_quoted(name
, stdout
, line_termination
);
3278 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
3281 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
3283 printf(" %s %s\n", newdelete
, name
);
3286 static void show_mode_change(struct patch
*p
, int show_name
)
3288 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
3290 printf(" mode change %06o => %06o %s\n",
3291 p
->old_mode
, p
->new_mode
, p
->new_name
);
3293 printf(" mode change %06o => %06o\n",
3294 p
->old_mode
, p
->new_mode
);
3298 static void show_rename_copy(struct patch
*p
)
3300 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
3301 const char *old
, *new;
3303 /* Find common prefix */
3307 const char *slash_old
, *slash_new
;
3308 slash_old
= strchr(old
, '/');
3309 slash_new
= strchr(new, '/');
3312 slash_old
- old
!= slash_new
- new ||
3313 memcmp(old
, new, slash_new
- new))
3315 old
= slash_old
+ 1;
3316 new = slash_new
+ 1;
3318 /* p->old_name thru old is the common prefix, and old and new
3319 * through the end of names are renames
3321 if (old
!= p
->old_name
)
3322 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
3323 (int)(old
- p
->old_name
), p
->old_name
,
3324 old
, new, p
->score
);
3326 printf(" %s %s => %s (%d%%)\n", renamecopy
,
3327 p
->old_name
, p
->new_name
, p
->score
);
3328 show_mode_change(p
, 0);
3331 static void summary_patch_list(struct patch
*patch
)
3335 for (p
= patch
; p
; p
= p
->next
) {
3337 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
3338 else if (p
->is_delete
)
3339 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
3341 if (p
->is_rename
|| p
->is_copy
)
3342 show_rename_copy(p
);
3345 printf(" rewrite %s (%d%%)\n",
3346 p
->new_name
, p
->score
);
3347 show_mode_change(p
, 0);
3350 show_mode_change(p
, 1);
3356 static void patch_stats(struct patch
*patch
)
3358 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
3360 if (lines
> max_change
)
3362 if (patch
->old_name
) {
3363 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
3365 len
= strlen(patch
->old_name
);
3369 if (patch
->new_name
) {
3370 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
3372 len
= strlen(patch
->new_name
);
3378 static void remove_file(struct patch
*patch
, int rmdir_empty
)
3381 if (remove_file_from_cache(patch
->old_name
) < 0)
3382 die("unable to remove %s from index", patch
->old_name
);
3385 if (!remove_or_warn(patch
->old_mode
, patch
->old_name
) && rmdir_empty
) {
3386 remove_path(patch
->old_name
);
3391 static void add_index_file(const char *path
, unsigned mode
, void *buf
, unsigned long size
)
3394 struct cache_entry
*ce
;
3395 int namelen
= strlen(path
);
3396 unsigned ce_size
= cache_entry_size(namelen
);
3401 ce
= xcalloc(1, ce_size
);
3402 memcpy(ce
->name
, path
, namelen
);
3403 ce
->ce_mode
= create_ce_mode(mode
);
3404 ce
->ce_flags
= namelen
;
3405 if (S_ISGITLINK(mode
)) {
3406 const char *s
= buf
;
3408 if (get_sha1_hex(s
+ strlen("Subproject commit "), ce
->sha1
))
3409 die("corrupt patch for subproject %s", path
);
3412 if (lstat(path
, &st
) < 0)
3413 die_errno("unable to stat newly created file '%s'",
3415 fill_stat_cache_info(ce
, &st
);
3417 if (write_sha1_file(buf
, size
, blob_type
, ce
->sha1
) < 0)
3418 die("unable to create backing store for newly created file %s", path
);
3420 if (add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
) < 0)
3421 die("unable to add cache entry for %s", path
);
3424 static int try_create_file(const char *path
, unsigned int mode
, const char *buf
, unsigned long size
)
3427 struct strbuf nbuf
= STRBUF_INIT
;
3429 if (S_ISGITLINK(mode
)) {
3431 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
))
3433 return mkdir(path
, 0777);
3436 if (has_symlinks
&& S_ISLNK(mode
))
3437 /* Although buf:size is counted string, it also is NUL
3440 return symlink(buf
, path
);
3442 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
3446 if (convert_to_working_tree(path
, buf
, size
, &nbuf
)) {
3450 write_or_die(fd
, buf
, size
);
3451 strbuf_release(&nbuf
);
3454 die_errno("closing file '%s'", path
);
3459 * We optimistically assume that the directories exist,
3460 * which is true 99% of the time anyway. If they don't,
3461 * we create them and try again.
3463 static void create_one_file(char *path
, unsigned mode
, const char *buf
, unsigned long size
)
3467 if (!try_create_file(path
, mode
, buf
, size
))
3470 if (errno
== ENOENT
) {
3471 if (safe_create_leading_directories(path
))
3473 if (!try_create_file(path
, mode
, buf
, size
))
3477 if (errno
== EEXIST
|| errno
== EACCES
) {
3478 /* We may be trying to create a file where a directory
3482 if (!lstat(path
, &st
) && (!S_ISDIR(st
.st_mode
) || !rmdir(path
)))
3486 if (errno
== EEXIST
) {
3487 unsigned int nr
= getpid();
3490 char newpath
[PATH_MAX
];
3491 mksnpath(newpath
, sizeof(newpath
), "%s~%u", path
, nr
);
3492 if (!try_create_file(newpath
, mode
, buf
, size
)) {
3493 if (!rename(newpath
, path
))
3495 unlink_or_warn(newpath
);
3498 if (errno
!= EEXIST
)
3503 die_errno("unable to write file '%s' mode %o", path
, mode
);
3506 static void create_file(struct patch
*patch
)
3508 char *path
= patch
->new_name
;
3509 unsigned mode
= patch
->new_mode
;
3510 unsigned long size
= patch
->resultsize
;
3511 char *buf
= patch
->result
;
3514 mode
= S_IFREG
| 0644;
3515 create_one_file(path
, mode
, buf
, size
);
3516 add_index_file(path
, mode
, buf
, size
);
3519 /* phase zero is to remove, phase one is to create */
3520 static void write_out_one_result(struct patch
*patch
, int phase
)
3522 if (patch
->is_delete
> 0) {
3524 remove_file(patch
, 1);
3527 if (patch
->is_new
> 0 || patch
->is_copy
) {
3533 * Rename or modification boils down to the same
3534 * thing: remove the old, write the new
3537 remove_file(patch
, patch
->is_rename
);
3542 static int write_out_one_reject(struct patch
*patch
)
3545 char namebuf
[PATH_MAX
];
3546 struct fragment
*frag
;
3549 for (cnt
= 0, frag
= patch
->fragments
; frag
; frag
= frag
->next
) {
3550 if (!frag
->rejected
)
3556 if (apply_verbosely
)
3557 say_patch_name(stderr
,
3558 "Applied patch ", patch
, " cleanly.\n");
3562 /* This should not happen, because a removal patch that leaves
3563 * contents are marked "rejected" at the patch level.
3565 if (!patch
->new_name
)
3566 die("internal error");
3568 /* Say this even without --verbose */
3569 say_patch_name(stderr
, "Applying patch ", patch
, " with");
3570 fprintf(stderr
, " %d rejects...\n", cnt
);
3572 cnt
= strlen(patch
->new_name
);
3573 if (ARRAY_SIZE(namebuf
) <= cnt
+ 5) {
3574 cnt
= ARRAY_SIZE(namebuf
) - 5;
3575 warning("truncating .rej filename to %.*s.rej",
3576 cnt
- 1, patch
->new_name
);
3578 memcpy(namebuf
, patch
->new_name
, cnt
);
3579 memcpy(namebuf
+ cnt
, ".rej", 5);
3581 rej
= fopen(namebuf
, "w");
3583 return error("cannot open %s: %s", namebuf
, strerror(errno
));
3585 /* Normal git tools never deal with .rej, so do not pretend
3586 * this is a git patch by saying --git nor give extended
3587 * headers. While at it, maybe please "kompare" that wants
3588 * the trailing TAB and some garbage at the end of line ;-).
3590 fprintf(rej
, "diff a/%s b/%s\t(rejected hunks)\n",
3591 patch
->new_name
, patch
->new_name
);
3592 for (cnt
= 1, frag
= patch
->fragments
;
3594 cnt
++, frag
= frag
->next
) {
3595 if (!frag
->rejected
) {
3596 fprintf(stderr
, "Hunk #%d applied cleanly.\n", cnt
);
3599 fprintf(stderr
, "Rejected hunk #%d.\n", cnt
);
3600 fprintf(rej
, "%.*s", frag
->size
, frag
->patch
);
3601 if (frag
->patch
[frag
->size
-1] != '\n')
3608 static int write_out_results(struct patch
*list
)
3614 for (phase
= 0; phase
< 2; phase
++) {
3620 write_out_one_result(l
, phase
);
3621 if (phase
== 1 && write_out_one_reject(l
))
3630 static struct lock_file lock_file
;
3632 static struct string_list limit_by_name
;
3633 static int has_include
;
3634 static void add_name_limit(const char *name
, int exclude
)
3636 struct string_list_item
*it
;
3638 it
= string_list_append(&limit_by_name
, name
);
3639 it
->util
= exclude
? NULL
: (void *) 1;
3642 static int use_patch(struct patch
*p
)
3644 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
3647 /* Paths outside are not touched regardless of "--include" */
3648 if (0 < prefix_length
) {
3649 int pathlen
= strlen(pathname
);
3650 if (pathlen
<= prefix_length
||
3651 memcmp(prefix
, pathname
, prefix_length
))
3655 /* See if it matches any of exclude/include rule */
3656 for (i
= 0; i
< limit_by_name
.nr
; i
++) {
3657 struct string_list_item
*it
= &limit_by_name
.items
[i
];
3658 if (!fnmatch(it
->string
, pathname
, 0))
3659 return (it
->util
!= NULL
);
3663 * If we had any include, a path that does not match any rule is
3664 * not used. Otherwise, we saw bunch of exclude rules (or none)
3665 * and such a path is used.
3667 return !has_include
;
3671 static void prefix_one(char **name
)
3673 char *old_name
= *name
;
3676 *name
= xstrdup(prefix_filename(prefix
, prefix_length
, *name
));
3680 static void prefix_patches(struct patch
*p
)
3682 if (!prefix
|| p
->is_toplevel_relative
)
3684 for ( ; p
; p
= p
->next
) {
3685 if (p
->new_name
== p
->old_name
) {
3686 char *prefixed
= p
->new_name
;
3687 prefix_one(&prefixed
);
3688 p
->new_name
= p
->old_name
= prefixed
;
3691 prefix_one(&p
->new_name
);
3692 prefix_one(&p
->old_name
);
3697 #define INACCURATE_EOF (1<<0)
3698 #define RECOUNT (1<<1)
3700 static int apply_patch(int fd
, const char *filename
, int options
)
3703 struct strbuf buf
= STRBUF_INIT
;
3704 struct patch
*list
= NULL
, **listp
= &list
;
3705 int skipped_patch
= 0;
3707 /* FIXME - memory leak when using multiple patch files as inputs */
3708 memset(&fn_table
, 0, sizeof(struct string_list
));
3709 patch_input_file
= filename
;
3710 read_patch_file(&buf
, fd
);
3712 while (offset
< buf
.len
) {
3713 struct patch
*patch
;
3716 patch
= xcalloc(1, sizeof(*patch
));
3717 patch
->inaccurate_eof
= !!(options
& INACCURATE_EOF
);
3718 patch
->recount
= !!(options
& RECOUNT
);
3719 nr
= parse_chunk(buf
.buf
+ offset
, buf
.len
- offset
, patch
);
3722 if (apply_in_reverse
)
3723 reverse_patches(patch
);
3725 prefix_patches(patch
);
3726 if (use_patch(patch
)) {
3729 listp
= &patch
->next
;
3732 /* perhaps free it a bit better? */
3739 if (!list
&& !skipped_patch
)
3740 die("unrecognized input");
3742 if (whitespace_error
&& (ws_error_action
== die_on_ws_error
))
3745 update_index
= check_index
&& apply
;
3746 if (update_index
&& newfd
< 0)
3747 newfd
= hold_locked_index(&lock_file
, 1);
3750 if (read_cache() < 0)
3751 die("unable to read index file");
3754 if ((check
|| apply
) &&
3755 check_patch_list(list
) < 0 &&
3759 if (apply
&& write_out_results(list
))
3763 build_fake_ancestor(list
, fake_ancestor
);
3766 stat_patch_list(list
);
3769 numstat_patch_list(list
);
3772 summary_patch_list(list
);
3774 strbuf_release(&buf
);
3778 static int git_apply_config(const char *var
, const char *value
, void *cb
)
3780 if (!strcmp(var
, "apply.whitespace"))
3781 return git_config_string(&apply_default_whitespace
, var
, value
);
3782 else if (!strcmp(var
, "apply.ignorewhitespace"))
3783 return git_config_string(&apply_default_ignorewhitespace
, var
, value
);
3784 return git_default_config(var
, value
, cb
);
3787 static int option_parse_exclude(const struct option
*opt
,
3788 const char *arg
, int unset
)
3790 add_name_limit(arg
, 1);
3794 static int option_parse_include(const struct option
*opt
,
3795 const char *arg
, int unset
)
3797 add_name_limit(arg
, 0);
3802 static int option_parse_p(const struct option
*opt
,
3803 const char *arg
, int unset
)
3805 p_value
= atoi(arg
);
3810 static int option_parse_z(const struct option
*opt
,
3811 const char *arg
, int unset
)
3814 line_termination
= '\n';
3816 line_termination
= 0;
3820 static int option_parse_space_change(const struct option
*opt
,
3821 const char *arg
, int unset
)
3824 ws_ignore_action
= ignore_ws_none
;
3826 ws_ignore_action
= ignore_ws_change
;
3830 static int option_parse_whitespace(const struct option
*opt
,
3831 const char *arg
, int unset
)
3833 const char **whitespace_option
= opt
->value
;
3835 *whitespace_option
= arg
;
3836 parse_whitespace_option(arg
);
3840 static int option_parse_directory(const struct option
*opt
,
3841 const char *arg
, int unset
)
3843 root_len
= strlen(arg
);
3844 if (root_len
&& arg
[root_len
- 1] != '/') {
3846 root
= new_root
= xmalloc(root_len
+ 2);
3847 strcpy(new_root
, arg
);
3848 strcpy(new_root
+ root_len
++, "/");
3854 int cmd_apply(int argc
, const char **argv
, const char *prefix_
)
3858 int is_not_gitdir
= !startup_info
->have_repository
;
3859 int force_apply
= 0;
3861 const char *whitespace_option
= NULL
;
3863 struct option builtin_apply_options
[] = {
3864 { OPTION_CALLBACK
, 0, "exclude", NULL
, "path",
3865 "don't apply changes matching the given path",
3866 0, option_parse_exclude
},
3867 { OPTION_CALLBACK
, 0, "include", NULL
, "path",
3868 "apply changes matching the given path",
3869 0, option_parse_include
},
3870 { OPTION_CALLBACK
, 'p', NULL
, NULL
, "num",
3871 "remove <num> leading slashes from traditional diff paths",
3872 0, option_parse_p
},
3873 OPT_BOOLEAN(0, "no-add", &no_add
,
3874 "ignore additions made by the patch"),
3875 OPT_BOOLEAN(0, "stat", &diffstat
,
3876 "instead of applying the patch, output diffstat for the input"),
3877 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
3878 OPT_NOOP_NOARG(0, "binary"),
3879 OPT_BOOLEAN(0, "numstat", &numstat
,
3880 "shows number of added and deleted lines in decimal notation"),
3881 OPT_BOOLEAN(0, "summary", &summary
,
3882 "instead of applying the patch, output a summary for the input"),
3883 OPT_BOOLEAN(0, "check", &check
,
3884 "instead of applying the patch, see if the patch is applicable"),
3885 OPT_BOOLEAN(0, "index", &check_index
,
3886 "make sure the patch is applicable to the current index"),
3887 OPT_BOOLEAN(0, "cached", &cached
,
3888 "apply a patch without touching the working tree"),
3889 OPT_BOOLEAN(0, "apply", &force_apply
,
3890 "also apply the patch (use with --stat/--summary/--check)"),
3891 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor
,
3892 "build a temporary index based on embedded index information"),
3893 { OPTION_CALLBACK
, 'z', NULL
, NULL
, NULL
,
3894 "paths are separated with NUL character",
3895 PARSE_OPT_NOARG
, option_parse_z
},
3896 OPT_INTEGER('C', NULL
, &p_context
,
3897 "ensure at least <n> lines of context match"),
3898 { OPTION_CALLBACK
, 0, "whitespace", &whitespace_option
, "action",
3899 "detect new or modified lines that have whitespace errors",
3900 0, option_parse_whitespace
},
3901 { OPTION_CALLBACK
, 0, "ignore-space-change", NULL
, NULL
,
3902 "ignore changes in whitespace when finding context",
3903 PARSE_OPT_NOARG
, option_parse_space_change
},
3904 { OPTION_CALLBACK
, 0, "ignore-whitespace", NULL
, NULL
,
3905 "ignore changes in whitespace when finding context",
3906 PARSE_OPT_NOARG
, option_parse_space_change
},
3907 OPT_BOOLEAN('R', "reverse", &apply_in_reverse
,
3908 "apply the patch in reverse"),
3909 OPT_BOOLEAN(0, "unidiff-zero", &unidiff_zero
,
3910 "don't expect at least one line of context"),
3911 OPT_BOOLEAN(0, "reject", &apply_with_reject
,
3912 "leave the rejected hunks in corresponding *.rej files"),
3913 OPT_BOOLEAN(0, "allow-overlap", &allow_overlap
,
3914 "allow overlapping hunks"),
3915 OPT__VERBOSE(&apply_verbosely
, "be verbose"),
3916 OPT_BIT(0, "inaccurate-eof", &options
,
3917 "tolerate incorrectly detected missing new-line at the end of file",
3919 OPT_BIT(0, "recount", &options
,
3920 "do not trust the line counts in the hunk headers",
3922 { OPTION_CALLBACK
, 0, "directory", NULL
, "root",
3923 "prepend <root> to all filenames",
3924 0, option_parse_directory
},
3929 prefix_length
= prefix
? strlen(prefix
) : 0;
3930 git_config(git_apply_config
, NULL
);
3931 if (apply_default_whitespace
)
3932 parse_whitespace_option(apply_default_whitespace
);
3933 if (apply_default_ignorewhitespace
)
3934 parse_ignorewhitespace_option(apply_default_ignorewhitespace
);
3936 argc
= parse_options(argc
, argv
, prefix
, builtin_apply_options
,
3939 if (apply_with_reject
)
3940 apply
= apply_verbosely
= 1;
3941 if (!force_apply
&& (diffstat
|| numstat
|| summary
|| check
|| fake_ancestor
))
3943 if (check_index
&& is_not_gitdir
)
3944 die("--index outside a repository");
3947 die("--cached outside a repository");
3950 for (i
= 0; i
< argc
; i
++) {
3951 const char *arg
= argv
[i
];
3954 if (!strcmp(arg
, "-")) {
3955 errs
|= apply_patch(0, "<stdin>", options
);
3958 } else if (0 < prefix_length
)
3959 arg
= prefix_filename(prefix
, prefix_length
, arg
);
3961 fd
= open(arg
, O_RDONLY
);
3963 die_errno("can't open patch '%s'", arg
);
3965 set_default_whitespace_mode(whitespace_option
);
3966 errs
|= apply_patch(fd
, arg
, options
);
3969 set_default_whitespace_mode(whitespace_option
);
3971 errs
|= apply_patch(0, "<stdin>", options
);
3972 if (whitespace_error
) {
3973 if (squelch_whitespace_errors
&&
3974 squelch_whitespace_errors
< whitespace_error
) {
3976 whitespace_error
- squelch_whitespace_errors
;
3977 warning("squelched %d "
3978 "whitespace error%s",
3980 squelched
== 1 ? "" : "s");
3982 if (ws_error_action
== die_on_ws_error
)
3983 die("%d line%s add%s whitespace errors.",
3985 whitespace_error
== 1 ? "" : "s",
3986 whitespace_error
== 1 ? "s" : "");
3987 if (applied_after_fixing_ws
&& apply
)
3988 warning("%d line%s applied after"
3989 " fixing whitespace errors.",
3990 applied_after_fixing_ws
,
3991 applied_after_fixing_ws
== 1 ? "" : "s");
3992 else if (whitespace_error
)
3993 warning("%d line%s add%s whitespace errors.",
3995 whitespace_error
== 1 ? "" : "s",
3996 whitespace_error
== 1 ? "s" : "");
4000 if (write_cache(newfd
, active_cache
, active_nr
) ||
4001 commit_locked_index(&lock_file
))
4002 die("Unable to write new index file");