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
;
155 * 'patch' is usually borrowed from buf in apply_patch(),
156 * but some codepaths store an allocated buffer.
159 unsigned free_patch
:1,
163 struct fragment
*next
;
167 * When dealing with a binary patch, we reuse "leading" field
168 * to store the type of the binary hunk, either deflated "delta"
169 * or deflated "literal".
171 #define binary_patch_method leading
172 #define BINARY_DELTA_DEFLATED 1
173 #define BINARY_LITERAL_DEFLATED 2
176 * This represents a "patch" to a file, both metainfo changes
177 * such as creation/deletion, filemode and content changes represented
178 * as a series of fragments.
181 char *new_name
, *old_name
, *def_name
;
182 unsigned int old_mode
, new_mode
;
183 int is_new
, is_delete
; /* -1 = unknown, 0 = false, 1 = true */
186 unsigned long deflate_origlen
;
187 int lines_added
, lines_deleted
;
189 unsigned int is_toplevel_relative
:1;
190 unsigned int inaccurate_eof
:1;
191 unsigned int is_binary
:1;
192 unsigned int is_copy
:1;
193 unsigned int is_rename
:1;
194 unsigned int recount
:1;
195 struct fragment
*fragments
;
198 char old_sha1_prefix
[41];
199 char new_sha1_prefix
[41];
203 static void free_fragment_list(struct fragment
*list
)
206 struct fragment
*next
= list
->next
;
207 if (list
->free_patch
)
208 free((char *)list
->patch
);
214 static void free_patch(struct patch
*patch
)
216 free_fragment_list(patch
->fragments
);
217 free(patch
->def_name
);
218 free(patch
->old_name
);
219 free(patch
->new_name
);
224 static void free_patch_list(struct patch
*list
)
227 struct patch
*next
= list
->next
;
234 * A line in a file, len-bytes long (includes the terminating LF,
235 * except for an incomplete line at the end if the file ends with
236 * one), and its contents hashes to 'hash'.
242 #define LINE_COMMON 1
243 #define LINE_PATCHED 2
247 * This represents a "file", which is an array of "lines".
254 struct line
*line_allocated
;
259 * Records filenames that have been touched, in order to handle
260 * the case where more than one patches touch the same file.
263 static struct string_list fn_table
;
265 static uint32_t hash_line(const char *cp
, size_t len
)
269 for (i
= 0, h
= 0; i
< len
; i
++) {
270 if (!isspace(cp
[i
])) {
271 h
= h
* 3 + (cp
[i
] & 0xff);
278 * Compare lines s1 of length n1 and s2 of length n2, ignoring
279 * whitespace difference. Returns 1 if they match, 0 otherwise
281 static int fuzzy_matchlines(const char *s1
, size_t n1
,
282 const char *s2
, size_t n2
)
284 const char *last1
= s1
+ n1
- 1;
285 const char *last2
= s2
+ n2
- 1;
288 /* ignore line endings */
289 while ((*last1
== '\r') || (*last1
== '\n'))
291 while ((*last2
== '\r') || (*last2
== '\n'))
294 /* skip leading whitespace */
295 while (isspace(*s1
) && (s1
<= last1
))
297 while (isspace(*s2
) && (s2
<= last2
))
299 /* early return if both lines are empty */
300 if ((s1
> last1
) && (s2
> last2
))
303 result
= *s1
++ - *s2
++;
305 * Skip whitespace inside. We check for whitespace on
306 * both buffers because we don't want "a b" to match
309 if (isspace(*s1
) && isspace(*s2
)) {
310 while (isspace(*s1
) && s1
<= last1
)
312 while (isspace(*s2
) && s2
<= last2
)
316 * If we reached the end on one side only,
320 ((s2
> last2
) && (s1
<= last1
)) ||
321 ((s1
> last1
) && (s2
<= last2
)))
323 if ((s1
> last1
) && (s2
> last2
))
330 static void add_line_info(struct image
*img
, const char *bol
, size_t len
, unsigned flag
)
332 ALLOC_GROW(img
->line_allocated
, img
->nr
+ 1, img
->alloc
);
333 img
->line_allocated
[img
->nr
].len
= len
;
334 img
->line_allocated
[img
->nr
].hash
= hash_line(bol
, len
);
335 img
->line_allocated
[img
->nr
].flag
= flag
;
340 * "buf" has the file contents to be patched (read from various sources).
341 * attach it to "image" and add line-based index to it.
342 * "image" now owns the "buf".
344 static void prepare_image(struct image
*image
, char *buf
, size_t len
,
345 int prepare_linetable
)
349 memset(image
, 0, sizeof(*image
));
353 if (!prepare_linetable
)
356 ep
= image
->buf
+ image
->len
;
360 for (next
= cp
; next
< ep
&& *next
!= '\n'; next
++)
364 add_line_info(image
, cp
, next
- cp
, 0);
367 image
->line
= image
->line_allocated
;
370 static void clear_image(struct image
*image
)
377 static void say_patch_name(FILE *output
, const char *pre
,
378 struct patch
*patch
, const char *post
)
381 if (patch
->old_name
&& patch
->new_name
&&
382 strcmp(patch
->old_name
, patch
->new_name
)) {
383 quote_c_style(patch
->old_name
, NULL
, output
, 0);
384 fputs(" => ", output
);
385 quote_c_style(patch
->new_name
, NULL
, output
, 0);
387 const char *n
= patch
->new_name
;
390 quote_c_style(n
, NULL
, output
, 0);
397 static void read_patch_file(struct strbuf
*sb
, int fd
)
399 if (strbuf_read(sb
, fd
, 0) < 0)
400 die_errno("git apply: failed to read");
403 * Make sure that we have some slop in the buffer
404 * so that we can do speculative "memcmp" etc, and
405 * see to it that it is NUL-filled.
407 strbuf_grow(sb
, SLOP
);
408 memset(sb
->buf
+ sb
->len
, 0, SLOP
);
411 static unsigned long linelen(const char *buffer
, unsigned long size
)
413 unsigned long len
= 0;
416 if (*buffer
++ == '\n')
422 static int is_dev_null(const char *str
)
424 return !memcmp("/dev/null", str
, 9) && isspace(str
[9]);
430 static int name_terminate(const char *name
, int namelen
, int c
, int terminate
)
432 if (c
== ' ' && !(terminate
& TERM_SPACE
))
434 if (c
== '\t' && !(terminate
& TERM_TAB
))
440 /* remove double slashes to make --index work with such filenames */
441 static char *squash_slash(char *name
)
449 if ((name
[j
++] = name
[i
++]) == '/')
450 while (name
[i
] == '/')
457 static char *find_name_gnu(const char *line
, const char *def
, int p_value
)
459 struct strbuf name
= STRBUF_INIT
;
463 * Proposed "new-style" GNU patch/diff format; see
464 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
466 if (unquote_c_style(&name
, line
, NULL
)) {
467 strbuf_release(&name
);
471 for (cp
= name
.buf
; p_value
; p_value
--) {
472 cp
= strchr(cp
, '/');
474 strbuf_release(&name
);
480 strbuf_remove(&name
, 0, cp
- name
.buf
);
482 strbuf_insert(&name
, 0, root
, root_len
);
483 return squash_slash(strbuf_detach(&name
, NULL
));
486 static size_t sane_tz_len(const char *line
, size_t len
)
490 if (len
< strlen(" +0500") || line
[len
-strlen(" +0500")] != ' ')
492 tz
= line
+ len
- strlen(" +0500");
494 if (tz
[1] != '+' && tz
[1] != '-')
497 for (p
= tz
+ 2; p
!= line
+ len
; p
++)
501 return line
+ len
- tz
;
504 static size_t tz_with_colon_len(const char *line
, size_t len
)
508 if (len
< strlen(" +08:00") || line
[len
- strlen(":00")] != ':')
510 tz
= line
+ len
- strlen(" +08:00");
512 if (tz
[0] != ' ' || (tz
[1] != '+' && tz
[1] != '-'))
515 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
516 !isdigit(*p
++) || !isdigit(*p
++))
519 return line
+ len
- tz
;
522 static size_t date_len(const char *line
, size_t len
)
524 const char *date
, *p
;
526 if (len
< strlen("72-02-05") || line
[len
-strlen("-05")] != '-')
528 p
= date
= line
+ len
- strlen("72-02-05");
530 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
531 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
532 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a date. */
535 if (date
- line
>= strlen("19") &&
536 isdigit(date
[-1]) && isdigit(date
[-2])) /* 4-digit year */
537 date
-= strlen("19");
539 return line
+ len
- date
;
542 static size_t short_time_len(const char *line
, size_t len
)
544 const char *time
, *p
;
546 if (len
< strlen(" 07:01:32") || line
[len
-strlen(":32")] != ':')
548 p
= time
= line
+ len
- strlen(" 07:01:32");
550 /* Permit 1-digit hours? */
552 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
553 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
554 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a time. */
557 return line
+ len
- time
;
560 static size_t fractional_time_len(const char *line
, size_t len
)
565 /* Expected format: 19:41:17.620000023 */
566 if (!len
|| !isdigit(line
[len
- 1]))
570 /* Fractional seconds. */
571 while (p
> line
&& isdigit(*p
))
576 /* Hours, minutes, and whole seconds. */
577 n
= short_time_len(line
, p
- line
);
581 return line
+ len
- p
+ n
;
584 static size_t trailing_spaces_len(const char *line
, size_t len
)
588 /* Expected format: ' ' x (1 or more) */
589 if (!len
|| line
[len
- 1] != ' ')
596 return line
+ len
- (p
+ 1);
603 static size_t diff_timestamp_len(const char *line
, size_t len
)
605 const char *end
= line
+ len
;
609 * Posix: 2010-07-05 19:41:17
610 * GNU: 2010-07-05 19:41:17.620000023 -0500
613 if (!isdigit(end
[-1]))
616 n
= sane_tz_len(line
, end
- line
);
618 n
= tz_with_colon_len(line
, end
- line
);
621 n
= short_time_len(line
, end
- line
);
623 n
= fractional_time_len(line
, end
- line
);
626 n
= date_len(line
, end
- line
);
627 if (!n
) /* No date. Too bad. */
631 if (end
== line
) /* No space before date. */
633 if (end
[-1] == '\t') { /* Success! */
635 return line
+ len
- end
;
637 if (end
[-1] != ' ') /* No space before date. */
640 /* Whitespace damage. */
641 end
-= trailing_spaces_len(line
, end
- line
);
642 return line
+ len
- end
;
645 static char *null_strdup(const char *s
)
647 return s
? xstrdup(s
) : NULL
;
650 static char *find_name_common(const char *line
, const char *def
,
651 int p_value
, const char *end
, int terminate
)
654 const char *start
= NULL
;
658 while (line
!= end
) {
661 if (!end
&& isspace(c
)) {
664 if (name_terminate(start
, line
-start
, c
, terminate
))
668 if (c
== '/' && !--p_value
)
672 return squash_slash(null_strdup(def
));
675 return squash_slash(null_strdup(def
));
678 * Generally we prefer the shorter name, especially
679 * if the other one is just a variation of that with
680 * something else tacked on to the end (ie "file.orig"
684 int deflen
= strlen(def
);
685 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
686 return squash_slash(xstrdup(def
));
690 char *ret
= xmalloc(root_len
+ len
+ 1);
692 memcpy(ret
+ root_len
, start
, len
);
693 ret
[root_len
+ len
] = '\0';
694 return squash_slash(ret
);
697 return squash_slash(xmemdupz(start
, len
));
700 static char *find_name(const char *line
, char *def
, int p_value
, int terminate
)
703 char *name
= find_name_gnu(line
, def
, p_value
);
708 return find_name_common(line
, def
, p_value
, NULL
, terminate
);
711 static char *find_name_traditional(const char *line
, char *def
, int p_value
)
713 size_t len
= strlen(line
);
717 char *name
= find_name_gnu(line
, def
, p_value
);
722 len
= strchrnul(line
, '\n') - line
;
723 date_len
= diff_timestamp_len(line
, len
);
725 return find_name_common(line
, def
, p_value
, NULL
, TERM_TAB
);
728 return find_name_common(line
, def
, p_value
, line
+ len
, 0);
731 static int count_slashes(const char *cp
)
743 * Given the string after "--- " or "+++ ", guess the appropriate
744 * p_value for the given patch.
746 static int guess_p_value(const char *nameline
)
751 if (is_dev_null(nameline
))
753 name
= find_name_traditional(nameline
, NULL
, 0);
756 cp
= strchr(name
, '/');
761 * Does it begin with "a/$our-prefix" and such? Then this is
762 * very likely to apply to our directory.
764 if (!strncmp(name
, prefix
, prefix_length
))
765 val
= count_slashes(prefix
);
768 if (!strncmp(cp
, prefix
, prefix_length
))
769 val
= count_slashes(prefix
) + 1;
777 * Does the ---/+++ line has the POSIX timestamp after the last HT?
778 * GNU diff puts epoch there to signal a creation/deletion event. Is
779 * this such a timestamp?
781 static int has_epoch_timestamp(const char *nameline
)
784 * We are only interested in epoch timestamp; any non-zero
785 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
786 * For the same reason, the date must be either 1969-12-31 or
787 * 1970-01-01, and the seconds part must be "00".
789 const char stamp_regexp
[] =
790 "^(1969-12-31|1970-01-01)"
792 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
794 "([-+][0-2][0-9]:?[0-5][0-9])\n";
795 const char *timestamp
= NULL
, *cp
, *colon
;
796 static regex_t
*stamp
;
802 for (cp
= nameline
; *cp
!= '\n'; cp
++) {
809 stamp
= xmalloc(sizeof(*stamp
));
810 if (regcomp(stamp
, stamp_regexp
, REG_EXTENDED
)) {
811 warning("Cannot prepare timestamp regexp %s",
817 status
= regexec(stamp
, timestamp
, ARRAY_SIZE(m
), m
, 0);
819 if (status
!= REG_NOMATCH
)
820 warning("regexec returned %d for input: %s",
825 zoneoffset
= strtol(timestamp
+ m
[3].rm_so
+ 1, (char **) &colon
, 10);
827 zoneoffset
= zoneoffset
* 60 + strtol(colon
+ 1, NULL
, 10);
829 zoneoffset
= (zoneoffset
/ 100) * 60 + (zoneoffset
% 100);
830 if (timestamp
[m
[3].rm_so
] == '-')
831 zoneoffset
= -zoneoffset
;
834 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
835 * (west of GMT) or 1970-01-01 (east of GMT)
837 if ((zoneoffset
< 0 && memcmp(timestamp
, "1969-12-31", 10)) ||
838 (0 <= zoneoffset
&& memcmp(timestamp
, "1970-01-01", 10)))
841 hourminute
= (strtol(timestamp
+ 11, NULL
, 10) * 60 +
842 strtol(timestamp
+ 14, NULL
, 10) -
845 return ((zoneoffset
< 0 && hourminute
== 1440) ||
846 (0 <= zoneoffset
&& !hourminute
));
850 * Get the name etc info from the ---/+++ lines of a traditional patch header
852 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
853 * files, we can happily check the index for a match, but for creating a
854 * new file we should try to match whatever "patch" does. I have no idea.
856 static void parse_traditional_patch(const char *first
, const char *second
, struct patch
*patch
)
860 first
+= 4; /* skip "--- " */
861 second
+= 4; /* skip "+++ " */
862 if (!p_value_known
) {
864 p
= guess_p_value(first
);
865 q
= guess_p_value(second
);
867 if (0 <= p
&& p
== q
) {
872 if (is_dev_null(first
)) {
874 patch
->is_delete
= 0;
875 name
= find_name_traditional(second
, NULL
, p_value
);
876 patch
->new_name
= name
;
877 } else if (is_dev_null(second
)) {
879 patch
->is_delete
= 1;
880 name
= find_name_traditional(first
, NULL
, p_value
);
881 patch
->old_name
= name
;
884 first_name
= find_name_traditional(first
, NULL
, p_value
);
885 name
= find_name_traditional(second
, first_name
, p_value
);
887 if (has_epoch_timestamp(first
)) {
889 patch
->is_delete
= 0;
890 patch
->new_name
= name
;
891 } else if (has_epoch_timestamp(second
)) {
893 patch
->is_delete
= 1;
894 patch
->old_name
= name
;
896 patch
->old_name
= name
;
897 patch
->new_name
= xstrdup(name
);
901 die("unable to find filename in patch at line %d", linenr
);
904 static int gitdiff_hdrend(const char *line
, struct patch
*patch
)
910 * We're anal about diff header consistency, to make
911 * sure that we don't end up having strange ambiguous
912 * patches floating around.
914 * As a result, gitdiff_{old|new}name() will check
915 * their names against any previous information, just
918 static char *gitdiff_verify_name(const char *line
, int isnull
, char *orig_name
, const char *oldnew
)
920 if (!orig_name
&& !isnull
)
921 return find_name(line
, NULL
, p_value
, TERM_TAB
);
930 die("git apply: bad git-diff - expected /dev/null, got %s on line %d", name
, linenr
);
931 another
= find_name(line
, NULL
, p_value
, TERM_TAB
);
932 if (!another
|| memcmp(another
, name
, len
+ 1))
933 die("git apply: bad git-diff - inconsistent %s filename on line %d", oldnew
, linenr
);
938 /* expect "/dev/null" */
939 if (memcmp("/dev/null", line
, 9) || line
[9] != '\n')
940 die("git apply: bad git-diff - expected /dev/null on line %d", linenr
);
945 static int gitdiff_oldname(const char *line
, struct patch
*patch
)
947 char *orig
= patch
->old_name
;
948 patch
->old_name
= gitdiff_verify_name(line
, patch
->is_new
, patch
->old_name
, "old");
949 if (orig
!= patch
->old_name
)
954 static int gitdiff_newname(const char *line
, struct patch
*patch
)
956 char *orig
= patch
->new_name
;
957 patch
->new_name
= gitdiff_verify_name(line
, patch
->is_delete
, patch
->new_name
, "new");
958 if (orig
!= patch
->new_name
)
963 static int gitdiff_oldmode(const char *line
, struct patch
*patch
)
965 patch
->old_mode
= strtoul(line
, NULL
, 8);
969 static int gitdiff_newmode(const char *line
, struct patch
*patch
)
971 patch
->new_mode
= strtoul(line
, NULL
, 8);
975 static int gitdiff_delete(const char *line
, struct patch
*patch
)
977 patch
->is_delete
= 1;
978 free(patch
->old_name
);
979 patch
->old_name
= null_strdup(patch
->def_name
);
980 return gitdiff_oldmode(line
, patch
);
983 static int gitdiff_newfile(const char *line
, struct patch
*patch
)
986 free(patch
->new_name
);
987 patch
->new_name
= null_strdup(patch
->def_name
);
988 return gitdiff_newmode(line
, patch
);
991 static int gitdiff_copysrc(const char *line
, struct patch
*patch
)
994 free(patch
->old_name
);
995 patch
->old_name
= find_name(line
, NULL
, p_value
? p_value
- 1 : 0, 0);
999 static int gitdiff_copydst(const char *line
, struct patch
*patch
)
1002 free(patch
->new_name
);
1003 patch
->new_name
= find_name(line
, NULL
, p_value
? p_value
- 1 : 0, 0);
1007 static int gitdiff_renamesrc(const char *line
, struct patch
*patch
)
1009 patch
->is_rename
= 1;
1010 free(patch
->old_name
);
1011 patch
->old_name
= find_name(line
, NULL
, p_value
? p_value
- 1 : 0, 0);
1015 static int gitdiff_renamedst(const char *line
, struct patch
*patch
)
1017 patch
->is_rename
= 1;
1018 free(patch
->new_name
);
1019 patch
->new_name
= find_name(line
, NULL
, p_value
? p_value
- 1 : 0, 0);
1023 static int gitdiff_similarity(const char *line
, struct patch
*patch
)
1025 if ((patch
->score
= strtoul(line
, NULL
, 10)) == ULONG_MAX
)
1030 static int gitdiff_dissimilarity(const char *line
, struct patch
*patch
)
1032 if ((patch
->score
= strtoul(line
, NULL
, 10)) == ULONG_MAX
)
1037 static int gitdiff_index(const char *line
, struct patch
*patch
)
1040 * index line is N hexadecimal, "..", N hexadecimal,
1041 * and optional space with octal mode.
1043 const char *ptr
, *eol
;
1046 ptr
= strchr(line
, '.');
1047 if (!ptr
|| ptr
[1] != '.' || 40 < ptr
- line
)
1050 memcpy(patch
->old_sha1_prefix
, line
, len
);
1051 patch
->old_sha1_prefix
[len
] = 0;
1054 ptr
= strchr(line
, ' ');
1055 eol
= strchr(line
, '\n');
1057 if (!ptr
|| eol
< ptr
)
1063 memcpy(patch
->new_sha1_prefix
, line
, len
);
1064 patch
->new_sha1_prefix
[len
] = 0;
1066 patch
->old_mode
= strtoul(ptr
+1, NULL
, 8);
1071 * This is normal for a diff that doesn't change anything: we'll fall through
1072 * into the next diff. Tell the parser to break out.
1074 static int gitdiff_unrecognized(const char *line
, struct patch
*patch
)
1079 static const char *stop_at_slash(const char *line
, int llen
)
1081 int nslash
= p_value
;
1084 for (i
= 0; i
< llen
; i
++) {
1086 if (ch
== '/' && --nslash
<= 0)
1093 * This is to extract the same name that appears on "diff --git"
1094 * line. We do not find and return anything if it is a rename
1095 * patch, and it is OK because we will find the name elsewhere.
1096 * We need to reliably find name only when it is mode-change only,
1097 * creation or deletion of an empty file. In any of these cases,
1098 * both sides are the same name under a/ and b/ respectively.
1100 static char *git_header_name(const char *line
, int llen
)
1103 const char *second
= NULL
;
1104 size_t len
, line_len
;
1106 line
+= strlen("diff --git ");
1107 llen
-= strlen("diff --git ");
1111 struct strbuf first
= STRBUF_INIT
;
1112 struct strbuf sp
= STRBUF_INIT
;
1114 if (unquote_c_style(&first
, line
, &second
))
1115 goto free_and_fail1
;
1117 /* advance to the first slash */
1118 cp
= stop_at_slash(first
.buf
, first
.len
);
1119 /* we do not accept absolute paths */
1120 if (!cp
|| cp
== first
.buf
)
1121 goto free_and_fail1
;
1122 strbuf_remove(&first
, 0, cp
+ 1 - first
.buf
);
1125 * second points at one past closing dq of name.
1126 * find the second name.
1128 while ((second
< line
+ llen
) && isspace(*second
))
1131 if (line
+ llen
<= second
)
1132 goto free_and_fail1
;
1133 if (*second
== '"') {
1134 if (unquote_c_style(&sp
, second
, NULL
))
1135 goto free_and_fail1
;
1136 cp
= stop_at_slash(sp
.buf
, sp
.len
);
1137 if (!cp
|| cp
== sp
.buf
)
1138 goto free_and_fail1
;
1139 /* They must match, otherwise ignore */
1140 if (strcmp(cp
+ 1, first
.buf
))
1141 goto free_and_fail1
;
1142 strbuf_release(&sp
);
1143 return strbuf_detach(&first
, NULL
);
1146 /* unquoted second */
1147 cp
= stop_at_slash(second
, line
+ llen
- second
);
1148 if (!cp
|| cp
== second
)
1149 goto free_and_fail1
;
1151 if (line
+ llen
- cp
!= first
.len
+ 1 ||
1152 memcmp(first
.buf
, cp
, first
.len
))
1153 goto free_and_fail1
;
1154 return strbuf_detach(&first
, NULL
);
1157 strbuf_release(&first
);
1158 strbuf_release(&sp
);
1162 /* unquoted first name */
1163 name
= stop_at_slash(line
, llen
);
1164 if (!name
|| name
== line
)
1169 * since the first name is unquoted, a dq if exists must be
1170 * the beginning of the second name.
1172 for (second
= name
; second
< line
+ llen
; second
++) {
1173 if (*second
== '"') {
1174 struct strbuf sp
= STRBUF_INIT
;
1177 if (unquote_c_style(&sp
, second
, NULL
))
1178 goto free_and_fail2
;
1180 np
= stop_at_slash(sp
.buf
, sp
.len
);
1181 if (!np
|| np
== sp
.buf
)
1182 goto free_and_fail2
;
1185 len
= sp
.buf
+ sp
.len
- np
;
1186 if (len
< second
- name
&&
1187 !strncmp(np
, name
, len
) &&
1188 isspace(name
[len
])) {
1190 strbuf_remove(&sp
, 0, np
- sp
.buf
);
1191 return strbuf_detach(&sp
, NULL
);
1195 strbuf_release(&sp
);
1201 * Accept a name only if it shows up twice, exactly the same
1204 second
= strchr(name
, '\n');
1207 line_len
= second
- name
;
1208 for (len
= 0 ; ; len
++) {
1209 switch (name
[len
]) {
1214 case '\t': case ' ':
1215 second
= stop_at_slash(name
+ len
, line_len
- len
);
1219 if (second
[len
] == '\n' && !strncmp(name
, second
, len
)) {
1220 return xmemdupz(name
, len
);
1226 /* Verify that we recognize the lines following a git header */
1227 static int parse_git_header(const char *line
, int len
, unsigned int size
, struct patch
*patch
)
1229 unsigned long offset
;
1231 /* A git diff has explicit new/delete information, so we don't guess */
1233 patch
->is_delete
= 0;
1236 * Some things may not have the old name in the
1237 * rest of the headers anywhere (pure mode changes,
1238 * or removing or adding empty files), so we get
1239 * the default name from the header.
1241 patch
->def_name
= git_header_name(line
, len
);
1242 if (patch
->def_name
&& root
) {
1243 char *s
= xmalloc(root_len
+ strlen(patch
->def_name
) + 1);
1245 strcpy(s
+ root_len
, patch
->def_name
);
1246 free(patch
->def_name
);
1247 patch
->def_name
= s
;
1253 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1254 static const struct opentry
{
1256 int (*fn
)(const char *, struct patch
*);
1258 { "@@ -", gitdiff_hdrend
},
1259 { "--- ", gitdiff_oldname
},
1260 { "+++ ", gitdiff_newname
},
1261 { "old mode ", gitdiff_oldmode
},
1262 { "new mode ", gitdiff_newmode
},
1263 { "deleted file mode ", gitdiff_delete
},
1264 { "new file mode ", gitdiff_newfile
},
1265 { "copy from ", gitdiff_copysrc
},
1266 { "copy to ", gitdiff_copydst
},
1267 { "rename old ", gitdiff_renamesrc
},
1268 { "rename new ", gitdiff_renamedst
},
1269 { "rename from ", gitdiff_renamesrc
},
1270 { "rename to ", gitdiff_renamedst
},
1271 { "similarity index ", gitdiff_similarity
},
1272 { "dissimilarity index ", gitdiff_dissimilarity
},
1273 { "index ", gitdiff_index
},
1274 { "", gitdiff_unrecognized
},
1278 len
= linelen(line
, size
);
1279 if (!len
|| line
[len
-1] != '\n')
1281 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
1282 const struct opentry
*p
= optable
+ i
;
1283 int oplen
= strlen(p
->str
);
1284 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
1286 if (p
->fn(line
+ oplen
, patch
) < 0)
1295 static int parse_num(const char *line
, unsigned long *p
)
1299 if (!isdigit(*line
))
1301 *p
= strtoul(line
, &ptr
, 10);
1305 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
1306 unsigned long *p1
, unsigned long *p2
)
1310 if (offset
< 0 || offset
>= len
)
1315 digits
= parse_num(line
, p1
);
1325 digits
= parse_num(line
+1, p2
);
1334 ex
= strlen(expect
);
1337 if (memcmp(line
, expect
, ex
))
1343 static void recount_diff(const char *line
, int size
, struct fragment
*fragment
)
1345 int oldlines
= 0, newlines
= 0, ret
= 0;
1348 warning("recount: ignore empty hunk");
1353 int len
= linelen(line
, size
);
1361 case ' ': case '\n':
1373 ret
= size
< 3 || prefixcmp(line
, "@@ ");
1376 ret
= size
< 5 || prefixcmp(line
, "diff ");
1383 warning("recount: unexpected line: %.*s",
1384 (int)linelen(line
, size
), line
);
1389 fragment
->oldlines
= oldlines
;
1390 fragment
->newlines
= newlines
;
1394 * Parse a unified diff fragment header of the
1395 * form "@@ -a,b +c,d @@"
1397 static int parse_fragment_header(const char *line
, int len
, struct fragment
*fragment
)
1401 if (!len
|| line
[len
-1] != '\n')
1404 /* Figure out the number of lines in a fragment */
1405 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
1406 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
1411 static int find_header(const char *line
, unsigned long size
, int *hdrsize
, struct patch
*patch
)
1413 unsigned long offset
, len
;
1415 patch
->is_toplevel_relative
= 0;
1416 patch
->is_rename
= patch
->is_copy
= 0;
1417 patch
->is_new
= patch
->is_delete
= -1;
1418 patch
->old_mode
= patch
->new_mode
= 0;
1419 patch
->old_name
= patch
->new_name
= NULL
;
1420 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1421 unsigned long nextlen
;
1423 len
= linelen(line
, size
);
1427 /* Testing this early allows us to take a few shortcuts.. */
1432 * Make sure we don't find any unconnected patch fragments.
1433 * That's a sign that we didn't find a header, and that a
1434 * patch has become corrupted/broken up.
1436 if (!memcmp("@@ -", line
, 4)) {
1437 struct fragment dummy
;
1438 if (parse_fragment_header(line
, len
, &dummy
) < 0)
1440 die("patch fragment without header at line %d: %.*s",
1441 linenr
, (int)len
-1, line
);
1448 * Git patch? It might not have a real patch, just a rename
1449 * or mode change, so we handle that specially
1451 if (!memcmp("diff --git ", line
, 11)) {
1452 int git_hdr_len
= parse_git_header(line
, len
, size
, patch
);
1453 if (git_hdr_len
<= len
)
1455 if (!patch
->old_name
&& !patch
->new_name
) {
1456 if (!patch
->def_name
)
1457 die("git diff header lacks filename information when removing "
1458 "%d leading pathname components (line %d)" , p_value
, linenr
);
1459 patch
->old_name
= xstrdup(patch
->def_name
);
1460 patch
->new_name
= xstrdup(patch
->def_name
);
1462 if (!patch
->is_delete
&& !patch
->new_name
)
1463 die("git diff header lacks filename information "
1464 "(line %d)", linenr
);
1465 patch
->is_toplevel_relative
= 1;
1466 *hdrsize
= git_hdr_len
;
1470 /* --- followed by +++ ? */
1471 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
1475 * We only accept unified patches, so we want it to
1476 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1477 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1479 nextlen
= linelen(line
+ len
, size
- len
);
1480 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
1483 /* Ok, we'll consider it a patch */
1484 parse_traditional_patch(line
, line
+len
, patch
);
1485 *hdrsize
= len
+ nextlen
;
1492 static void record_ws_error(unsigned result
, const char *line
, int len
, int linenr
)
1500 if (squelch_whitespace_errors
&&
1501 squelch_whitespace_errors
< whitespace_error
)
1504 err
= whitespace_error_string(result
);
1505 fprintf(stderr
, "%s:%d: %s.\n%.*s\n",
1506 patch_input_file
, linenr
, err
, len
, line
);
1510 static void check_whitespace(const char *line
, int len
, unsigned ws_rule
)
1512 unsigned result
= ws_check(line
+ 1, len
- 1, ws_rule
);
1514 record_ws_error(result
, line
+ 1, len
- 2, linenr
);
1518 * Parse a unified diff. Note that this really needs to parse each
1519 * fragment separately, since the only way to know the difference
1520 * between a "---" that is part of a patch, and a "---" that starts
1521 * the next patch is to look at the line counts..
1523 static int parse_fragment(const char *line
, unsigned long size
,
1524 struct patch
*patch
, struct fragment
*fragment
)
1527 int len
= linelen(line
, size
), offset
;
1528 unsigned long oldlines
, newlines
;
1529 unsigned long leading
, trailing
;
1531 offset
= parse_fragment_header(line
, len
, fragment
);
1534 if (offset
> 0 && patch
->recount
)
1535 recount_diff(line
+ offset
, size
- offset
, fragment
);
1536 oldlines
= fragment
->oldlines
;
1537 newlines
= fragment
->newlines
;
1541 /* Parse the thing.. */
1545 added
= deleted
= 0;
1548 offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1549 if (!oldlines
&& !newlines
)
1551 len
= linelen(line
, size
);
1552 if (!len
|| line
[len
-1] != '\n')
1557 case '\n': /* newer GNU diff, an empty context line */
1561 if (!deleted
&& !added
)
1566 if (apply_in_reverse
&&
1567 ws_error_action
!= nowarn_ws_error
)
1568 check_whitespace(line
, len
, patch
->ws_rule
);
1574 if (!apply_in_reverse
&&
1575 ws_error_action
!= nowarn_ws_error
)
1576 check_whitespace(line
, len
, patch
->ws_rule
);
1583 * We allow "\ No newline at end of file". Depending
1584 * on locale settings when the patch was produced we
1585 * don't know what this line looks like. The only
1586 * thing we do know is that it begins with "\ ".
1587 * Checking for 12 is just for sanity check -- any
1588 * l10n of "\ No newline..." is at least that long.
1591 if (len
< 12 || memcmp(line
, "\\ ", 2))
1596 if (oldlines
|| newlines
)
1598 fragment
->leading
= leading
;
1599 fragment
->trailing
= trailing
;
1602 * If a fragment ends with an incomplete line, we failed to include
1603 * it in the above loop because we hit oldlines == newlines == 0
1606 if (12 < size
&& !memcmp(line
, "\\ ", 2))
1607 offset
+= linelen(line
, size
);
1609 patch
->lines_added
+= added
;
1610 patch
->lines_deleted
+= deleted
;
1612 if (0 < patch
->is_new
&& oldlines
)
1613 return error("new file depends on old contents");
1614 if (0 < patch
->is_delete
&& newlines
)
1615 return error("deleted file still has contents");
1620 * We have seen "diff --git a/... b/..." header (or a traditional patch
1621 * header). Read hunks that belong to this patch into fragments and hang
1622 * them to the given patch structure.
1624 * The (fragment->patch, fragment->size) pair points into the memory given
1625 * by the caller, not a copy, when we return.
1627 static int parse_single_patch(const char *line
, unsigned long size
, struct patch
*patch
)
1629 unsigned long offset
= 0;
1630 unsigned long oldlines
= 0, newlines
= 0, context
= 0;
1631 struct fragment
**fragp
= &patch
->fragments
;
1633 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
1634 struct fragment
*fragment
;
1637 fragment
= xcalloc(1, sizeof(*fragment
));
1638 fragment
->linenr
= linenr
;
1639 len
= parse_fragment(line
, size
, patch
, fragment
);
1641 die("corrupt patch at line %d", linenr
);
1642 fragment
->patch
= line
;
1643 fragment
->size
= len
;
1644 oldlines
+= fragment
->oldlines
;
1645 newlines
+= fragment
->newlines
;
1646 context
+= fragment
->leading
+ fragment
->trailing
;
1649 fragp
= &fragment
->next
;
1657 * If something was removed (i.e. we have old-lines) it cannot
1658 * be creation, and if something was added it cannot be
1659 * deletion. However, the reverse is not true; --unified=0
1660 * patches that only add are not necessarily creation even
1661 * though they do not have any old lines, and ones that only
1662 * delete are not necessarily deletion.
1664 * Unfortunately, a real creation/deletion patch do _not_ have
1665 * any context line by definition, so we cannot safely tell it
1666 * apart with --unified=0 insanity. At least if the patch has
1667 * more than one hunk it is not creation or deletion.
1669 if (patch
->is_new
< 0 &&
1670 (oldlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1672 if (patch
->is_delete
< 0 &&
1673 (newlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1674 patch
->is_delete
= 0;
1676 if (0 < patch
->is_new
&& oldlines
)
1677 die("new file %s depends on old contents", patch
->new_name
);
1678 if (0 < patch
->is_delete
&& newlines
)
1679 die("deleted file %s still has contents", patch
->old_name
);
1680 if (!patch
->is_delete
&& !newlines
&& context
)
1681 fprintf(stderr
, "** warning: file %s becomes empty but "
1682 "is not deleted\n", patch
->new_name
);
1687 static inline int metadata_changes(struct patch
*patch
)
1689 return patch
->is_rename
> 0 ||
1690 patch
->is_copy
> 0 ||
1691 patch
->is_new
> 0 ||
1693 (patch
->old_mode
&& patch
->new_mode
&&
1694 patch
->old_mode
!= patch
->new_mode
);
1697 static char *inflate_it(const void *data
, unsigned long size
,
1698 unsigned long inflated_size
)
1704 memset(&stream
, 0, sizeof(stream
));
1706 stream
.next_in
= (unsigned char *)data
;
1707 stream
.avail_in
= size
;
1708 stream
.next_out
= out
= xmalloc(inflated_size
);
1709 stream
.avail_out
= inflated_size
;
1710 git_inflate_init(&stream
);
1711 st
= git_inflate(&stream
, Z_FINISH
);
1712 git_inflate_end(&stream
);
1713 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1721 * Read a binary hunk and return a new fragment; fragment->patch
1722 * points at an allocated memory that the caller must free, so
1723 * it is marked as "->free_patch = 1".
1725 static struct fragment
*parse_binary_hunk(char **buf_p
,
1726 unsigned long *sz_p
,
1731 * Expect a line that begins with binary patch method ("literal"
1732 * or "delta"), followed by the length of data before deflating.
1733 * a sequence of 'length-byte' followed by base-85 encoded data
1734 * should follow, terminated by a newline.
1736 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1737 * and we would limit the patch line to 66 characters,
1738 * so one line can fit up to 13 groups that would decode
1739 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1740 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1743 unsigned long size
= *sz_p
;
1744 char *buffer
= *buf_p
;
1746 unsigned long origlen
;
1749 struct fragment
*frag
;
1751 llen
= linelen(buffer
, size
);
1756 if (!prefixcmp(buffer
, "delta ")) {
1757 patch_method
= BINARY_DELTA_DEFLATED
;
1758 origlen
= strtoul(buffer
+ 6, NULL
, 10);
1760 else if (!prefixcmp(buffer
, "literal ")) {
1761 patch_method
= BINARY_LITERAL_DEFLATED
;
1762 origlen
= strtoul(buffer
+ 8, NULL
, 10);
1770 int byte_length
, max_byte_length
, newsize
;
1771 llen
= linelen(buffer
, size
);
1775 /* consume the blank line */
1781 * Minimum line is "A00000\n" which is 7-byte long,
1782 * and the line length must be multiple of 5 plus 2.
1784 if ((llen
< 7) || (llen
-2) % 5)
1786 max_byte_length
= (llen
- 2) / 5 * 4;
1787 byte_length
= *buffer
;
1788 if ('A' <= byte_length
&& byte_length
<= 'Z')
1789 byte_length
= byte_length
- 'A' + 1;
1790 else if ('a' <= byte_length
&& byte_length
<= 'z')
1791 byte_length
= byte_length
- 'a' + 27;
1794 /* if the input length was not multiple of 4, we would
1795 * have filler at the end but the filler should never
1798 if (max_byte_length
< byte_length
||
1799 byte_length
<= max_byte_length
- 4)
1801 newsize
= hunk_size
+ byte_length
;
1802 data
= xrealloc(data
, newsize
);
1803 if (decode_85(data
+ hunk_size
, buffer
+ 1, byte_length
))
1805 hunk_size
= newsize
;
1810 frag
= xcalloc(1, sizeof(*frag
));
1811 frag
->patch
= inflate_it(data
, hunk_size
, origlen
);
1812 frag
->free_patch
= 1;
1816 frag
->size
= origlen
;
1820 frag
->binary_patch_method
= patch_method
;
1826 error("corrupt binary patch at line %d: %.*s",
1827 linenr
-1, llen
-1, buffer
);
1831 static int parse_binary(char *buffer
, unsigned long size
, struct patch
*patch
)
1834 * We have read "GIT binary patch\n"; what follows is a line
1835 * that says the patch method (currently, either "literal" or
1836 * "delta") and the length of data before deflating; a
1837 * sequence of 'length-byte' followed by base-85 encoded data
1840 * When a binary patch is reversible, there is another binary
1841 * hunk in the same format, starting with patch method (either
1842 * "literal" or "delta") with the length of data, and a sequence
1843 * of length-byte + base-85 encoded data, terminated with another
1844 * empty line. This data, when applied to the postimage, produces
1847 struct fragment
*forward
;
1848 struct fragment
*reverse
;
1852 forward
= parse_binary_hunk(&buffer
, &size
, &status
, &used
);
1853 if (!forward
&& !status
)
1854 /* there has to be one hunk (forward hunk) */
1855 return error("unrecognized binary patch at line %d", linenr
-1);
1857 /* otherwise we already gave an error message */
1860 reverse
= parse_binary_hunk(&buffer
, &size
, &status
, &used_1
);
1865 * Not having reverse hunk is not an error, but having
1866 * a corrupt reverse hunk is.
1868 free((void*) forward
->patch
);
1872 forward
->next
= reverse
;
1873 patch
->fragments
= forward
;
1874 patch
->is_binary
= 1;
1879 * Read the patch text in "buffer" taht extends for "size" bytes; stop
1880 * reading after seeing a single patch (i.e. changes to a single file).
1881 * Create fragments (i.e. patch hunks) and hang them to the given patch.
1882 * Return the number of bytes consumed, so that the caller can call us
1883 * again for the next patch.
1885 static int parse_chunk(char *buffer
, unsigned long size
, struct patch
*patch
)
1887 int hdrsize
, patchsize
;
1888 int offset
= find_header(buffer
, size
, &hdrsize
, patch
);
1893 patch
->ws_rule
= whitespace_rule(patch
->new_name
1897 patchsize
= parse_single_patch(buffer
+ offset
+ hdrsize
,
1898 size
- offset
- hdrsize
, patch
);
1901 static const char *binhdr
[] = {
1906 static const char git_binary
[] = "GIT binary patch\n";
1908 int hd
= hdrsize
+ offset
;
1909 unsigned long llen
= linelen(buffer
+ hd
, size
- hd
);
1911 if (llen
== sizeof(git_binary
) - 1 &&
1912 !memcmp(git_binary
, buffer
+ hd
, llen
)) {
1915 used
= parse_binary(buffer
+ hd
+ llen
,
1916 size
- hd
- llen
, patch
);
1918 patchsize
= used
+ llen
;
1922 else if (!memcmp(" differ\n", buffer
+ hd
+ llen
- 8, 8)) {
1923 for (i
= 0; binhdr
[i
]; i
++) {
1924 int len
= strlen(binhdr
[i
]);
1925 if (len
< size
- hd
&&
1926 !memcmp(binhdr
[i
], buffer
+ hd
, len
)) {
1928 patch
->is_binary
= 1;
1935 /* Empty patch cannot be applied if it is a text patch
1936 * without metadata change. A binary patch appears
1939 if ((apply
|| check
) &&
1940 (!patch
->is_binary
&& !metadata_changes(patch
)))
1941 die("patch with only garbage at line %d", linenr
);
1944 return offset
+ hdrsize
+ patchsize
;
1947 #define swap(a,b) myswap((a),(b),sizeof(a))
1949 #define myswap(a, b, size) do { \
1950 unsigned char mytmp[size]; \
1951 memcpy(mytmp, &a, size); \
1952 memcpy(&a, &b, size); \
1953 memcpy(&b, mytmp, size); \
1956 static void reverse_patches(struct patch
*p
)
1958 for (; p
; p
= p
->next
) {
1959 struct fragment
*frag
= p
->fragments
;
1961 swap(p
->new_name
, p
->old_name
);
1962 swap(p
->new_mode
, p
->old_mode
);
1963 swap(p
->is_new
, p
->is_delete
);
1964 swap(p
->lines_added
, p
->lines_deleted
);
1965 swap(p
->old_sha1_prefix
, p
->new_sha1_prefix
);
1967 for (; frag
; frag
= frag
->next
) {
1968 swap(frag
->newpos
, frag
->oldpos
);
1969 swap(frag
->newlines
, frag
->oldlines
);
1974 static const char pluses
[] =
1975 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1976 static const char minuses
[]=
1977 "----------------------------------------------------------------------";
1979 static void show_stats(struct patch
*patch
)
1981 struct strbuf qname
= STRBUF_INIT
;
1982 char *cp
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
1985 quote_c_style(cp
, &qname
, NULL
, 0);
1988 * "scale" the filename
1994 if (qname
.len
> max
) {
1995 cp
= strchr(qname
.buf
+ qname
.len
+ 3 - max
, '/');
1997 cp
= qname
.buf
+ qname
.len
+ 3 - max
;
1998 strbuf_splice(&qname
, 0, cp
- qname
.buf
, "...", 3);
2001 if (patch
->is_binary
) {
2002 printf(" %-*s | Bin\n", max
, qname
.buf
);
2003 strbuf_release(&qname
);
2007 printf(" %-*s |", max
, qname
.buf
);
2008 strbuf_release(&qname
);
2011 * scale the add/delete
2013 max
= max
+ max_change
> 70 ? 70 - max
: max_change
;
2014 add
= patch
->lines_added
;
2015 del
= patch
->lines_deleted
;
2017 if (max_change
> 0) {
2018 int total
= ((add
+ del
) * max
+ max_change
/ 2) / max_change
;
2019 add
= (add
* max
+ max_change
/ 2) / max_change
;
2022 printf("%5d %.*s%.*s\n", patch
->lines_added
+ patch
->lines_deleted
,
2023 add
, pluses
, del
, minuses
);
2026 static int read_old_data(struct stat
*st
, const char *path
, struct strbuf
*buf
)
2028 switch (st
->st_mode
& S_IFMT
) {
2030 if (strbuf_readlink(buf
, path
, st
->st_size
) < 0)
2031 return error("unable to read symlink %s", path
);
2034 if (strbuf_read_file(buf
, path
, st
->st_size
) != st
->st_size
)
2035 return error("unable to open or read %s", path
);
2036 convert_to_git(path
, buf
->buf
, buf
->len
, buf
, 0);
2044 * Update the preimage, and the common lines in postimage,
2045 * from buffer buf of length len. If postlen is 0 the postimage
2046 * is updated in place, otherwise it's updated on a new buffer
2050 static void update_pre_post_images(struct image
*preimage
,
2051 struct image
*postimage
,
2053 size_t len
, size_t postlen
)
2056 char *new, *old
, *fixed
;
2057 struct image fixed_preimage
;
2060 * Update the preimage with whitespace fixes. Note that we
2061 * are not losing preimage->buf -- apply_one_fragment() will
2064 prepare_image(&fixed_preimage
, buf
, len
, 1);
2065 assert(fixed_preimage
.nr
== preimage
->nr
);
2066 for (i
= 0; i
< preimage
->nr
; i
++)
2067 fixed_preimage
.line
[i
].flag
= preimage
->line
[i
].flag
;
2068 free(preimage
->line_allocated
);
2069 *preimage
= fixed_preimage
;
2072 * Adjust the common context lines in postimage. This can be
2073 * done in-place when we are just doing whitespace fixing,
2074 * which does not make the string grow, but needs a new buffer
2075 * when ignoring whitespace causes the update, since in this case
2076 * we could have e.g. tabs converted to multiple spaces.
2077 * We trust the caller to tell us if the update can be done
2078 * in place (postlen==0) or not.
2080 old
= postimage
->buf
;
2082 new = postimage
->buf
= xmalloc(postlen
);
2085 fixed
= preimage
->buf
;
2086 for (i
= ctx
= 0; i
< postimage
->nr
; i
++) {
2087 size_t len
= postimage
->line
[i
].len
;
2088 if (!(postimage
->line
[i
].flag
& LINE_COMMON
)) {
2089 /* an added line -- no counterparts in preimage */
2090 memmove(new, old
, len
);
2096 /* a common context -- skip it in the original postimage */
2099 /* and find the corresponding one in the fixed preimage */
2100 while (ctx
< preimage
->nr
&&
2101 !(preimage
->line
[ctx
].flag
& LINE_COMMON
)) {
2102 fixed
+= preimage
->line
[ctx
].len
;
2105 if (preimage
->nr
<= ctx
)
2108 /* and copy it in, while fixing the line length */
2109 len
= preimage
->line
[ctx
].len
;
2110 memcpy(new, fixed
, len
);
2113 postimage
->line
[i
].len
= len
;
2117 /* Fix the length of the whole thing */
2118 postimage
->len
= new - postimage
->buf
;
2121 static int match_fragment(struct image
*img
,
2122 struct image
*preimage
,
2123 struct image
*postimage
,
2127 int match_beginning
, int match_end
)
2130 char *fixed_buf
, *buf
, *orig
, *target
;
2131 struct strbuf fixed
;
2135 if (preimage
->nr
+ try_lno
<= img
->nr
) {
2137 * The hunk falls within the boundaries of img.
2139 preimage_limit
= preimage
->nr
;
2140 if (match_end
&& (preimage
->nr
+ try_lno
!= img
->nr
))
2142 } else if (ws_error_action
== correct_ws_error
&&
2143 (ws_rule
& WS_BLANK_AT_EOF
)) {
2145 * This hunk extends beyond the end of img, and we are
2146 * removing blank lines at the end of the file. This
2147 * many lines from the beginning of the preimage must
2148 * match with img, and the remainder of the preimage
2151 preimage_limit
= img
->nr
- try_lno
;
2154 * The hunk extends beyond the end of the img and
2155 * we are not removing blanks at the end, so we
2156 * should reject the hunk at this position.
2161 if (match_beginning
&& try_lno
)
2164 /* Quick hash check */
2165 for (i
= 0; i
< preimage_limit
; i
++)
2166 if ((img
->line
[try_lno
+ i
].flag
& LINE_PATCHED
) ||
2167 (preimage
->line
[i
].hash
!= img
->line
[try_lno
+ i
].hash
))
2170 if (preimage_limit
== preimage
->nr
) {
2172 * Do we have an exact match? If we were told to match
2173 * at the end, size must be exactly at try+fragsize,
2174 * otherwise try+fragsize must be still within the preimage,
2175 * and either case, the old piece should match the preimage
2179 ? (try + preimage
->len
== img
->len
)
2180 : (try + preimage
->len
<= img
->len
)) &&
2181 !memcmp(img
->buf
+ try, preimage
->buf
, preimage
->len
))
2185 * The preimage extends beyond the end of img, so
2186 * there cannot be an exact match.
2188 * There must be one non-blank context line that match
2189 * a line before the end of img.
2193 buf
= preimage
->buf
;
2195 for (i
= 0; i
< preimage_limit
; i
++)
2196 buf_end
+= preimage
->line
[i
].len
;
2198 for ( ; buf
< buf_end
; buf
++)
2206 * No exact match. If we are ignoring whitespace, run a line-by-line
2207 * fuzzy matching. We collect all the line length information because
2208 * we need it to adjust whitespace if we match.
2210 if (ws_ignore_action
== ignore_ws_change
) {
2213 size_t postlen
= postimage
->len
;
2217 for (i
= 0; i
< preimage_limit
; i
++) {
2218 size_t prelen
= preimage
->line
[i
].len
;
2219 size_t imglen
= img
->line
[try_lno
+i
].len
;
2221 if (!fuzzy_matchlines(img
->buf
+ try + imgoff
, imglen
,
2222 preimage
->buf
+ preoff
, prelen
))
2224 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2225 postlen
+= imglen
- prelen
;
2231 * Ok, the preimage matches with whitespace fuzz.
2233 * imgoff now holds the true length of the target that
2234 * matches the preimage before the end of the file.
2236 * Count the number of characters in the preimage that fall
2237 * beyond the end of the file and make sure that all of them
2238 * are whitespace characters. (This can only happen if
2239 * we are removing blank lines at the end of the file.)
2241 buf
= preimage_eof
= preimage
->buf
+ preoff
;
2242 for ( ; i
< preimage
->nr
; i
++)
2243 preoff
+= preimage
->line
[i
].len
;
2244 preimage_end
= preimage
->buf
+ preoff
;
2245 for ( ; buf
< preimage_end
; buf
++)
2250 * Update the preimage and the common postimage context
2251 * lines to use the same whitespace as the target.
2252 * If whitespace is missing in the target (i.e.
2253 * if the preimage extends beyond the end of the file),
2254 * use the whitespace from the preimage.
2256 extra_chars
= preimage_end
- preimage_eof
;
2257 strbuf_init(&fixed
, imgoff
+ extra_chars
);
2258 strbuf_add(&fixed
, img
->buf
+ try, imgoff
);
2259 strbuf_add(&fixed
, preimage_eof
, extra_chars
);
2260 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2261 update_pre_post_images(preimage
, postimage
,
2262 fixed_buf
, fixed_len
, postlen
);
2266 if (ws_error_action
!= correct_ws_error
)
2270 * The hunk does not apply byte-by-byte, but the hash says
2271 * it might with whitespace fuzz. We haven't been asked to
2272 * ignore whitespace, we were asked to correct whitespace
2273 * errors, so let's try matching after whitespace correction.
2275 * The preimage may extend beyond the end of the file,
2276 * but in this loop we will only handle the part of the
2277 * preimage that falls within the file.
2279 strbuf_init(&fixed
, preimage
->len
+ 1);
2280 orig
= preimage
->buf
;
2281 target
= img
->buf
+ try;
2282 for (i
= 0; i
< preimage_limit
; i
++) {
2283 size_t oldlen
= preimage
->line
[i
].len
;
2284 size_t tgtlen
= img
->line
[try_lno
+ i
].len
;
2285 size_t fixstart
= fixed
.len
;
2286 struct strbuf tgtfix
;
2289 /* Try fixing the line in the preimage */
2290 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2292 /* Try fixing the line in the target */
2293 strbuf_init(&tgtfix
, tgtlen
);
2294 ws_fix_copy(&tgtfix
, target
, tgtlen
, ws_rule
, NULL
);
2297 * If they match, either the preimage was based on
2298 * a version before our tree fixed whitespace breakage,
2299 * or we are lacking a whitespace-fix patch the tree
2300 * the preimage was based on already had (i.e. target
2301 * has whitespace breakage, the preimage doesn't).
2302 * In either case, we are fixing the whitespace breakages
2303 * so we might as well take the fix together with their
2306 match
= (tgtfix
.len
== fixed
.len
- fixstart
&&
2307 !memcmp(tgtfix
.buf
, fixed
.buf
+ fixstart
,
2308 fixed
.len
- fixstart
));
2310 strbuf_release(&tgtfix
);
2320 * Now handle the lines in the preimage that falls beyond the
2321 * end of the file (if any). They will only match if they are
2322 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2325 for ( ; i
< preimage
->nr
; i
++) {
2326 size_t fixstart
= fixed
.len
; /* start of the fixed preimage */
2327 size_t oldlen
= preimage
->line
[i
].len
;
2330 /* Try fixing the line in the preimage */
2331 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2333 for (j
= fixstart
; j
< fixed
.len
; j
++)
2334 if (!isspace(fixed
.buf
[j
]))
2341 * Yes, the preimage is based on an older version that still
2342 * has whitespace breakages unfixed, and fixing them makes the
2343 * hunk match. Update the context lines in the postimage.
2345 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2346 update_pre_post_images(preimage
, postimage
,
2347 fixed_buf
, fixed_len
, 0);
2351 strbuf_release(&fixed
);
2355 static int find_pos(struct image
*img
,
2356 struct image
*preimage
,
2357 struct image
*postimage
,
2360 int match_beginning
, int match_end
)
2363 unsigned long backwards
, forwards
, try;
2364 int backwards_lno
, forwards_lno
, try_lno
;
2367 * If match_beginning or match_end is specified, there is no
2368 * point starting from a wrong line that will never match and
2369 * wander around and wait for a match at the specified end.
2371 if (match_beginning
)
2374 line
= img
->nr
- preimage
->nr
;
2377 * Because the comparison is unsigned, the following test
2378 * will also take care of a negative line number that can
2379 * result when match_end and preimage is larger than the target.
2381 if ((size_t) line
> img
->nr
)
2385 for (i
= 0; i
< line
; i
++)
2386 try += img
->line
[i
].len
;
2389 * There's probably some smart way to do this, but I'll leave
2390 * that to the smart and beautiful people. I'm simple and stupid.
2393 backwards_lno
= line
;
2395 forwards_lno
= line
;
2398 for (i
= 0; ; i
++) {
2399 if (match_fragment(img
, preimage
, postimage
,
2400 try, try_lno
, ws_rule
,
2401 match_beginning
, match_end
))
2405 if (backwards_lno
== 0 && forwards_lno
== img
->nr
)
2409 if (backwards_lno
== 0) {
2414 backwards
-= img
->line
[backwards_lno
].len
;
2416 try_lno
= backwards_lno
;
2418 if (forwards_lno
== img
->nr
) {
2422 forwards
+= img
->line
[forwards_lno
].len
;
2425 try_lno
= forwards_lno
;
2432 static void remove_first_line(struct image
*img
)
2434 img
->buf
+= img
->line
[0].len
;
2435 img
->len
-= img
->line
[0].len
;
2440 static void remove_last_line(struct image
*img
)
2442 img
->len
-= img
->line
[--img
->nr
].len
;
2446 * The change from "preimage" and "postimage" has been found to
2447 * apply at applied_pos (counts in line numbers) in "img".
2448 * Update "img" to remove "preimage" and replace it with "postimage".
2450 static void update_image(struct image
*img
,
2452 struct image
*preimage
,
2453 struct image
*postimage
)
2456 * remove the copy of preimage at offset in img
2457 * and replace it with postimage
2460 size_t remove_count
, insert_count
, applied_at
= 0;
2465 * If we are removing blank lines at the end of img,
2466 * the preimage may extend beyond the end.
2467 * If that is the case, we must be careful only to
2468 * remove the part of the preimage that falls within
2469 * the boundaries of img. Initialize preimage_limit
2470 * to the number of lines in the preimage that falls
2471 * within the boundaries.
2473 preimage_limit
= preimage
->nr
;
2474 if (preimage_limit
> img
->nr
- applied_pos
)
2475 preimage_limit
= img
->nr
- applied_pos
;
2477 for (i
= 0; i
< applied_pos
; i
++)
2478 applied_at
+= img
->line
[i
].len
;
2481 for (i
= 0; i
< preimage_limit
; i
++)
2482 remove_count
+= img
->line
[applied_pos
+ i
].len
;
2483 insert_count
= postimage
->len
;
2485 /* Adjust the contents */
2486 result
= xmalloc(img
->len
+ insert_count
- remove_count
+ 1);
2487 memcpy(result
, img
->buf
, applied_at
);
2488 memcpy(result
+ applied_at
, postimage
->buf
, postimage
->len
);
2489 memcpy(result
+ applied_at
+ postimage
->len
,
2490 img
->buf
+ (applied_at
+ remove_count
),
2491 img
->len
- (applied_at
+ remove_count
));
2494 img
->len
+= insert_count
- remove_count
;
2495 result
[img
->len
] = '\0';
2497 /* Adjust the line table */
2498 nr
= img
->nr
+ postimage
->nr
- preimage_limit
;
2499 if (preimage_limit
< postimage
->nr
) {
2501 * NOTE: this knows that we never call remove_first_line()
2502 * on anything other than pre/post image.
2504 img
->line
= xrealloc(img
->line
, nr
* sizeof(*img
->line
));
2505 img
->line_allocated
= img
->line
;
2507 if (preimage_limit
!= postimage
->nr
)
2508 memmove(img
->line
+ applied_pos
+ postimage
->nr
,
2509 img
->line
+ applied_pos
+ preimage_limit
,
2510 (img
->nr
- (applied_pos
+ preimage_limit
)) *
2511 sizeof(*img
->line
));
2512 memcpy(img
->line
+ applied_pos
,
2514 postimage
->nr
* sizeof(*img
->line
));
2516 for (i
= 0; i
< postimage
->nr
; i
++)
2517 img
->line
[applied_pos
+ i
].flag
|= LINE_PATCHED
;
2522 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2523 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2524 * replace the part of "img" with "postimage" text.
2526 static int apply_one_fragment(struct image
*img
, struct fragment
*frag
,
2527 int inaccurate_eof
, unsigned ws_rule
,
2530 int match_beginning
, match_end
;
2531 const char *patch
= frag
->patch
;
2532 int size
= frag
->size
;
2533 char *old
, *oldlines
;
2534 struct strbuf newlines
;
2535 int new_blank_lines_at_end
= 0;
2536 int found_new_blank_lines_at_end
= 0;
2537 int hunk_linenr
= frag
->linenr
;
2538 unsigned long leading
, trailing
;
2539 int pos
, applied_pos
;
2540 struct image preimage
;
2541 struct image postimage
;
2543 memset(&preimage
, 0, sizeof(preimage
));
2544 memset(&postimage
, 0, sizeof(postimage
));
2545 oldlines
= xmalloc(size
);
2546 strbuf_init(&newlines
, size
);
2551 int len
= linelen(patch
, size
);
2553 int added_blank_line
= 0;
2554 int is_blank_context
= 0;
2561 * "plen" is how much of the line we should use for
2562 * the actual patch data. Normally we just remove the
2563 * first character on the line, but if the line is
2564 * followed by "\ No newline", then we also remove the
2565 * last one (which is the newline, of course).
2568 if (len
< size
&& patch
[len
] == '\\')
2571 if (apply_in_reverse
) {
2574 else if (first
== '+')
2580 /* Newer GNU diff, empty context line */
2582 /* ... followed by '\No newline'; nothing */
2585 strbuf_addch(&newlines
, '\n');
2586 add_line_info(&preimage
, "\n", 1, LINE_COMMON
);
2587 add_line_info(&postimage
, "\n", 1, LINE_COMMON
);
2588 is_blank_context
= 1;
2591 if (plen
&& (ws_rule
& WS_BLANK_AT_EOF
) &&
2592 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2593 is_blank_context
= 1;
2595 memcpy(old
, patch
+ 1, plen
);
2596 add_line_info(&preimage
, old
, plen
,
2597 (first
== ' ' ? LINE_COMMON
: 0));
2601 /* Fall-through for ' ' */
2603 /* --no-add does not add new lines */
2604 if (first
== '+' && no_add
)
2607 start
= newlines
.len
;
2609 !whitespace_error
||
2610 ws_error_action
!= correct_ws_error
) {
2611 strbuf_add(&newlines
, patch
+ 1, plen
);
2614 ws_fix_copy(&newlines
, patch
+ 1, plen
, ws_rule
, &applied_after_fixing_ws
);
2616 add_line_info(&postimage
, newlines
.buf
+ start
, newlines
.len
- start
,
2617 (first
== '+' ? 0 : LINE_COMMON
));
2619 (ws_rule
& WS_BLANK_AT_EOF
) &&
2620 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2621 added_blank_line
= 1;
2623 case '@': case '\\':
2624 /* Ignore it, we already handled it */
2627 if (apply_verbosely
)
2628 error("invalid start of line: '%c'", first
);
2631 if (added_blank_line
) {
2632 if (!new_blank_lines_at_end
)
2633 found_new_blank_lines_at_end
= hunk_linenr
;
2634 new_blank_lines_at_end
++;
2636 else if (is_blank_context
)
2639 new_blank_lines_at_end
= 0;
2644 if (inaccurate_eof
&&
2645 old
> oldlines
&& old
[-1] == '\n' &&
2646 newlines
.len
> 0 && newlines
.buf
[newlines
.len
- 1] == '\n') {
2648 strbuf_setlen(&newlines
, newlines
.len
- 1);
2651 leading
= frag
->leading
;
2652 trailing
= frag
->trailing
;
2655 * A hunk to change lines at the beginning would begin with
2657 * but we need to be careful. -U0 that inserts before the second
2658 * line also has this pattern.
2660 * And a hunk to add to an empty file would begin with
2663 * In other words, a hunk that is (frag->oldpos <= 1) with or
2664 * without leading context must match at the beginning.
2666 match_beginning
= (!frag
->oldpos
||
2667 (frag
->oldpos
== 1 && !unidiff_zero
));
2670 * A hunk without trailing lines must match at the end.
2671 * However, we simply cannot tell if a hunk must match end
2672 * from the lack of trailing lines if the patch was generated
2673 * with unidiff without any context.
2675 match_end
= !unidiff_zero
&& !trailing
;
2677 pos
= frag
->newpos
? (frag
->newpos
- 1) : 0;
2678 preimage
.buf
= oldlines
;
2679 preimage
.len
= old
- oldlines
;
2680 postimage
.buf
= newlines
.buf
;
2681 postimage
.len
= newlines
.len
;
2682 preimage
.line
= preimage
.line_allocated
;
2683 postimage
.line
= postimage
.line_allocated
;
2687 applied_pos
= find_pos(img
, &preimage
, &postimage
, pos
,
2688 ws_rule
, match_beginning
, match_end
);
2690 if (applied_pos
>= 0)
2693 /* Am I at my context limits? */
2694 if ((leading
<= p_context
) && (trailing
<= p_context
))
2696 if (match_beginning
|| match_end
) {
2697 match_beginning
= match_end
= 0;
2702 * Reduce the number of context lines; reduce both
2703 * leading and trailing if they are equal otherwise
2704 * just reduce the larger context.
2706 if (leading
>= trailing
) {
2707 remove_first_line(&preimage
);
2708 remove_first_line(&postimage
);
2712 if (trailing
> leading
) {
2713 remove_last_line(&preimage
);
2714 remove_last_line(&postimage
);
2719 if (applied_pos
>= 0) {
2720 if (new_blank_lines_at_end
&&
2721 preimage
.nr
+ applied_pos
>= img
->nr
&&
2722 (ws_rule
& WS_BLANK_AT_EOF
) &&
2723 ws_error_action
!= nowarn_ws_error
) {
2724 record_ws_error(WS_BLANK_AT_EOF
, "+", 1,
2725 found_new_blank_lines_at_end
);
2726 if (ws_error_action
== correct_ws_error
) {
2727 while (new_blank_lines_at_end
--)
2728 remove_last_line(&postimage
);
2731 * We would want to prevent write_out_results()
2732 * from taking place in apply_patch() that follows
2733 * the callchain led us here, which is:
2734 * apply_patch->check_patch_list->check_patch->
2735 * apply_data->apply_fragments->apply_one_fragment
2737 if (ws_error_action
== die_on_ws_error
)
2741 if (apply_verbosely
&& applied_pos
!= pos
) {
2742 int offset
= applied_pos
- pos
;
2743 if (apply_in_reverse
)
2744 offset
= 0 - offset
;
2746 "Hunk #%d succeeded at %d (offset %d lines).\n",
2747 nth_fragment
, applied_pos
+ 1, offset
);
2751 * Warn if it was necessary to reduce the number
2754 if ((leading
!= frag
->leading
) ||
2755 (trailing
!= frag
->trailing
))
2756 fprintf(stderr
, "Context reduced to (%ld/%ld)"
2757 " to apply fragment at %d\n",
2758 leading
, trailing
, applied_pos
+1);
2759 update_image(img
, applied_pos
, &preimage
, &postimage
);
2761 if (apply_verbosely
)
2762 error("while searching for:\n%.*s",
2763 (int)(old
- oldlines
), oldlines
);
2767 strbuf_release(&newlines
);
2768 free(preimage
.line_allocated
);
2769 free(postimage
.line_allocated
);
2771 return (applied_pos
< 0);
2774 static int apply_binary_fragment(struct image
*img
, struct patch
*patch
)
2776 struct fragment
*fragment
= patch
->fragments
;
2781 return error("missing binary patch data for '%s'",
2786 /* Binary patch is irreversible without the optional second hunk */
2787 if (apply_in_reverse
) {
2788 if (!fragment
->next
)
2789 return error("cannot reverse-apply a binary patch "
2790 "without the reverse hunk to '%s'",
2792 ? patch
->new_name
: patch
->old_name
);
2793 fragment
= fragment
->next
;
2795 switch (fragment
->binary_patch_method
) {
2796 case BINARY_DELTA_DEFLATED
:
2797 dst
= patch_delta(img
->buf
, img
->len
, fragment
->patch
,
2798 fragment
->size
, &len
);
2805 case BINARY_LITERAL_DEFLATED
:
2807 img
->len
= fragment
->size
;
2808 img
->buf
= xmalloc(img
->len
+1);
2809 memcpy(img
->buf
, fragment
->patch
, img
->len
);
2810 img
->buf
[img
->len
] = '\0';
2817 * Replace "img" with the result of applying the binary patch.
2818 * The binary patch data itself in patch->fragment is still kept
2819 * but the preimage prepared by the caller in "img" is freed here
2820 * or in the helper function apply_binary_fragment() this calls.
2822 static int apply_binary(struct image
*img
, struct patch
*patch
)
2824 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
2825 unsigned char sha1
[20];
2828 * For safety, we require patch index line to contain
2829 * full 40-byte textual SHA1 for old and new, at least for now.
2831 if (strlen(patch
->old_sha1_prefix
) != 40 ||
2832 strlen(patch
->new_sha1_prefix
) != 40 ||
2833 get_sha1_hex(patch
->old_sha1_prefix
, sha1
) ||
2834 get_sha1_hex(patch
->new_sha1_prefix
, sha1
))
2835 return error("cannot apply binary patch to '%s' "
2836 "without full index line", name
);
2838 if (patch
->old_name
) {
2840 * See if the old one matches what the patch
2843 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
2844 if (strcmp(sha1_to_hex(sha1
), patch
->old_sha1_prefix
))
2845 return error("the patch applies to '%s' (%s), "
2846 "which does not match the "
2847 "current contents.",
2848 name
, sha1_to_hex(sha1
));
2851 /* Otherwise, the old one must be empty. */
2853 return error("the patch applies to an empty "
2854 "'%s' but it is not empty", name
);
2857 get_sha1_hex(patch
->new_sha1_prefix
, sha1
);
2858 if (is_null_sha1(sha1
)) {
2860 return 0; /* deletion patch */
2863 if (has_sha1_file(sha1
)) {
2864 /* We already have the postimage */
2865 enum object_type type
;
2869 result
= read_sha1_file(sha1
, &type
, &size
);
2871 return error("the necessary postimage %s for "
2872 "'%s' cannot be read",
2873 patch
->new_sha1_prefix
, name
);
2879 * We have verified buf matches the preimage;
2880 * apply the patch data to it, which is stored
2881 * in the patch->fragments->{patch,size}.
2883 if (apply_binary_fragment(img
, patch
))
2884 return error("binary patch does not apply to '%s'",
2887 /* verify that the result matches */
2888 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
2889 if (strcmp(sha1_to_hex(sha1
), patch
->new_sha1_prefix
))
2890 return error("binary patch to '%s' creates incorrect result (expecting %s, got %s)",
2891 name
, patch
->new_sha1_prefix
, sha1_to_hex(sha1
));
2897 static int apply_fragments(struct image
*img
, struct patch
*patch
)
2899 struct fragment
*frag
= patch
->fragments
;
2900 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
2901 unsigned ws_rule
= patch
->ws_rule
;
2902 unsigned inaccurate_eof
= patch
->inaccurate_eof
;
2905 if (patch
->is_binary
)
2906 return apply_binary(img
, patch
);
2910 if (apply_one_fragment(img
, frag
, inaccurate_eof
, ws_rule
, nth
)) {
2911 error("patch failed: %s:%ld", name
, frag
->oldpos
);
2912 if (!apply_with_reject
)
2921 static int read_file_or_gitlink(struct cache_entry
*ce
, struct strbuf
*buf
)
2926 if (S_ISGITLINK(ce
->ce_mode
)) {
2927 strbuf_grow(buf
, 100);
2928 strbuf_addf(buf
, "Subproject commit %s\n", sha1_to_hex(ce
->sha1
));
2930 enum object_type type
;
2934 result
= read_sha1_file(ce
->sha1
, &type
, &sz
);
2937 /* XXX read_sha1_file NUL-terminates */
2938 strbuf_attach(buf
, result
, sz
, sz
+ 1);
2943 static struct patch
*in_fn_table(const char *name
)
2945 struct string_list_item
*item
;
2950 item
= string_list_lookup(&fn_table
, name
);
2952 return (struct patch
*)item
->util
;
2958 * item->util in the filename table records the status of the path.
2959 * Usually it points at a patch (whose result records the contents
2960 * of it after applying it), but it could be PATH_WAS_DELETED for a
2961 * path that a previously applied patch has already removed.
2963 #define PATH_TO_BE_DELETED ((struct patch *) -2)
2964 #define PATH_WAS_DELETED ((struct patch *) -1)
2966 static int to_be_deleted(struct patch
*patch
)
2968 return patch
== PATH_TO_BE_DELETED
;
2971 static int was_deleted(struct patch
*patch
)
2973 return patch
== PATH_WAS_DELETED
;
2976 static void add_to_fn_table(struct patch
*patch
)
2978 struct string_list_item
*item
;
2981 * Always add new_name unless patch is a deletion
2982 * This should cover the cases for normal diffs,
2983 * file creations and copies
2985 if (patch
->new_name
!= NULL
) {
2986 item
= string_list_insert(&fn_table
, patch
->new_name
);
2991 * store a failure on rename/deletion cases because
2992 * later chunks shouldn't patch old names
2994 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
2995 item
= string_list_insert(&fn_table
, patch
->old_name
);
2996 item
->util
= PATH_WAS_DELETED
;
3000 static void prepare_fn_table(struct patch
*patch
)
3003 * store information about incoming file deletion
3006 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3007 struct string_list_item
*item
;
3008 item
= string_list_insert(&fn_table
, patch
->old_name
);
3009 item
->util
= PATH_TO_BE_DELETED
;
3011 patch
= patch
->next
;
3015 static int apply_data(struct patch
*patch
, struct stat
*st
, struct cache_entry
*ce
)
3017 struct strbuf buf
= STRBUF_INIT
;
3021 struct patch
*tpatch
;
3023 if (!(patch
->is_copy
|| patch
->is_rename
) &&
3024 (tpatch
= in_fn_table(patch
->old_name
)) != NULL
&& !to_be_deleted(tpatch
)) {
3025 if (was_deleted(tpatch
)) {
3026 return error("patch %s has been renamed/deleted",
3029 /* We have a patched copy in memory; use that. */
3030 strbuf_add(&buf
, tpatch
->result
, tpatch
->resultsize
);
3031 } else if (cached
) {
3032 if (read_file_or_gitlink(ce
, &buf
))
3033 return error("read of %s failed", patch
->old_name
);
3034 } else if (patch
->old_name
) {
3035 if (S_ISGITLINK(patch
->old_mode
)) {
3037 read_file_or_gitlink(ce
, &buf
);
3040 * There is no way to apply subproject
3041 * patch without looking at the index.
3042 * NEEDSWORK: shouldn't this be flagged
3045 free_fragment_list(patch
->fragments
);
3046 patch
->fragments
= NULL
;
3049 if (read_old_data(st
, patch
->old_name
, &buf
))
3050 return error("read of %s failed", patch
->old_name
);
3054 img
= strbuf_detach(&buf
, &len
);
3055 prepare_image(&image
, img
, len
, !patch
->is_binary
);
3057 if (apply_fragments(&image
, patch
) < 0)
3058 return -1; /* note with --reject this succeeds. */
3059 patch
->result
= image
.buf
;
3060 patch
->resultsize
= image
.len
;
3061 add_to_fn_table(patch
);
3062 free(image
.line_allocated
);
3064 if (0 < patch
->is_delete
&& patch
->resultsize
)
3065 return error("removal patch leaves file contents");
3070 static int check_to_create_blob(const char *new_name
, int ok_if_exists
)
3073 if (!lstat(new_name
, &nst
)) {
3074 if (S_ISDIR(nst
.st_mode
) || ok_if_exists
)
3077 * A leading component of new_name might be a symlink
3078 * that is going to be removed with this patch, but
3079 * still pointing at somewhere that has the path.
3080 * In such a case, path "new_name" does not exist as
3081 * far as git is concerned.
3083 if (has_symlink_leading_path(new_name
, strlen(new_name
)))
3086 return error("%s: already exists in working directory", new_name
);
3088 else if ((errno
!= ENOENT
) && (errno
!= ENOTDIR
))
3089 return error("%s: %s", new_name
, strerror(errno
));
3093 static int verify_index_match(struct cache_entry
*ce
, struct stat
*st
)
3095 if (S_ISGITLINK(ce
->ce_mode
)) {
3096 if (!S_ISDIR(st
->st_mode
))
3100 return ce_match_stat(ce
, st
, CE_MATCH_IGNORE_VALID
|CE_MATCH_IGNORE_SKIP_WORKTREE
);
3103 static int check_preimage(struct patch
*patch
, struct cache_entry
**ce
, struct stat
*st
)
3105 const char *old_name
= patch
->old_name
;
3106 struct patch
*tpatch
= NULL
;
3108 unsigned st_mode
= 0;
3111 * Make sure that we do not have local modifications from the
3112 * index when we are looking at the index. Also make sure
3113 * we have the preimage file to be patched in the work tree,
3114 * unless --cached, which tells git to apply only in the index.
3119 assert(patch
->is_new
<= 0);
3121 if (!(patch
->is_copy
|| patch
->is_rename
) &&
3122 (tpatch
= in_fn_table(old_name
)) != NULL
&& !to_be_deleted(tpatch
)) {
3123 if (was_deleted(tpatch
))
3124 return error("%s: has been deleted/renamed", old_name
);
3125 st_mode
= tpatch
->new_mode
;
3126 } else if (!cached
) {
3127 stat_ret
= lstat(old_name
, st
);
3128 if (stat_ret
&& errno
!= ENOENT
)
3129 return error("%s: %s", old_name
, strerror(errno
));
3132 if (to_be_deleted(tpatch
))
3135 if (check_index
&& !tpatch
) {
3136 int pos
= cache_name_pos(old_name
, strlen(old_name
));
3138 if (patch
->is_new
< 0)
3140 return error("%s: does not exist in index", old_name
);
3142 *ce
= active_cache
[pos
];
3144 struct checkout costate
;
3146 memset(&costate
, 0, sizeof(costate
));
3147 costate
.base_dir
= "";
3148 costate
.refresh_cache
= 1;
3149 if (checkout_entry(*ce
, &costate
, NULL
) ||
3150 lstat(old_name
, st
))
3153 if (!cached
&& verify_index_match(*ce
, st
))
3154 return error("%s: does not match index", old_name
);
3156 st_mode
= (*ce
)->ce_mode
;
3157 } else if (stat_ret
< 0) {
3158 if (patch
->is_new
< 0)
3160 return error("%s: %s", old_name
, strerror(errno
));
3163 if (!cached
&& !tpatch
)
3164 st_mode
= ce_mode_from_stat(*ce
, st
->st_mode
);
3166 if (patch
->is_new
< 0)
3168 if (!patch
->old_mode
)
3169 patch
->old_mode
= st_mode
;
3170 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
3171 return error("%s: wrong type", old_name
);
3172 if (st_mode
!= patch
->old_mode
)
3173 warning("%s has type %o, expected %o",
3174 old_name
, st_mode
, patch
->old_mode
);
3175 if (!patch
->new_mode
&& !patch
->is_delete
)
3176 patch
->new_mode
= st_mode
;
3181 patch
->is_delete
= 0;
3182 free(patch
->old_name
);
3183 patch
->old_name
= NULL
;
3188 * Check and apply the patch in-core; leave the result in patch->result
3189 * for the caller to write it out to the final destination.
3191 static int check_patch(struct patch
*patch
)
3194 const char *old_name
= patch
->old_name
;
3195 const char *new_name
= patch
->new_name
;
3196 const char *name
= old_name
? old_name
: new_name
;
3197 struct cache_entry
*ce
= NULL
;
3198 struct patch
*tpatch
;
3202 patch
->rejected
= 1; /* we will drop this after we succeed */
3204 status
= check_preimage(patch
, &ce
, &st
);
3207 old_name
= patch
->old_name
;
3209 if ((tpatch
= in_fn_table(new_name
)) &&
3210 (was_deleted(tpatch
) || to_be_deleted(tpatch
)))
3212 * A type-change diff is always split into a patch to
3213 * delete old, immediately followed by a patch to
3214 * create new (see diff.c::run_diff()); in such a case
3215 * it is Ok that the entry to be deleted by the
3216 * previous patch is still in the working tree and in
3224 ((0 < patch
->is_new
) | (0 < patch
->is_rename
) | patch
->is_copy
)) {
3226 cache_name_pos(new_name
, strlen(new_name
)) >= 0 &&
3228 return error("%s: already exists in index", new_name
);
3230 int err
= check_to_create_blob(new_name
, ok_if_exists
);
3234 if (!patch
->new_mode
) {
3235 if (0 < patch
->is_new
)
3236 patch
->new_mode
= S_IFREG
| 0644;
3238 patch
->new_mode
= patch
->old_mode
;
3242 if (new_name
&& old_name
) {
3243 int same
= !strcmp(old_name
, new_name
);
3244 if (!patch
->new_mode
)
3245 patch
->new_mode
= patch
->old_mode
;
3246 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
)
3247 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
3248 patch
->new_mode
, new_name
, patch
->old_mode
,
3249 same
? "" : " of ", same
? "" : old_name
);
3252 if (apply_data(patch
, &st
, ce
) < 0)
3253 return error("%s: patch does not apply", name
);
3254 patch
->rejected
= 0;
3258 static int check_patch_list(struct patch
*patch
)
3262 prepare_fn_table(patch
);
3264 if (apply_verbosely
)
3265 say_patch_name(stderr
,
3266 "Checking patch ", patch
, "...\n");
3267 err
|= check_patch(patch
);
3268 patch
= patch
->next
;
3273 /* This function tries to read the sha1 from the current index */
3274 static int get_current_sha1(const char *path
, unsigned char *sha1
)
3278 if (read_cache() < 0)
3280 pos
= cache_name_pos(path
, strlen(path
));
3283 hashcpy(sha1
, active_cache
[pos
]->sha1
);
3287 /* Build an index that contains the just the files needed for a 3way merge */
3288 static void build_fake_ancestor(struct patch
*list
, const char *filename
)
3290 struct patch
*patch
;
3291 struct index_state result
= { NULL
};
3294 /* Once we start supporting the reverse patch, it may be
3295 * worth showing the new sha1 prefix, but until then...
3297 for (patch
= list
; patch
; patch
= patch
->next
) {
3298 const unsigned char *sha1_ptr
;
3299 unsigned char sha1
[20];
3300 struct cache_entry
*ce
;
3303 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3304 if (0 < patch
->is_new
)
3306 else if (get_sha1(patch
->old_sha1_prefix
, sha1
))
3307 /* git diff has no index line for mode/type changes */
3308 if (!patch
->lines_added
&& !patch
->lines_deleted
) {
3309 if (get_current_sha1(patch
->old_name
, sha1
))
3310 die("mode change for %s, which is not "
3311 "in current HEAD", name
);
3314 die("sha1 information is lacking or useless "
3319 ce
= make_cache_entry(patch
->old_mode
, sha1_ptr
, name
, 0, 0);
3321 die("make_cache_entry failed for path '%s'", name
);
3322 if (add_index_entry(&result
, ce
, ADD_CACHE_OK_TO_ADD
))
3323 die ("Could not add %s to temporary index", name
);
3326 fd
= open(filename
, O_WRONLY
| O_CREAT
, 0666);
3327 if (fd
< 0 || write_index(&result
, fd
) || close(fd
))
3328 die ("Could not write temporary index to %s", filename
);
3330 discard_index(&result
);
3333 static void stat_patch_list(struct patch
*patch
)
3335 int files
, adds
, dels
;
3337 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
3339 adds
+= patch
->lines_added
;
3340 dels
+= patch
->lines_deleted
;
3344 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files
, adds
, dels
);
3347 static void numstat_patch_list(struct patch
*patch
)
3349 for ( ; patch
; patch
= patch
->next
) {
3351 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
3352 if (patch
->is_binary
)
3355 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
3356 write_name_quoted(name
, stdout
, line_termination
);
3360 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
3363 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
3365 printf(" %s %s\n", newdelete
, name
);
3368 static void show_mode_change(struct patch
*p
, int show_name
)
3370 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
3372 printf(" mode change %06o => %06o %s\n",
3373 p
->old_mode
, p
->new_mode
, p
->new_name
);
3375 printf(" mode change %06o => %06o\n",
3376 p
->old_mode
, p
->new_mode
);
3380 static void show_rename_copy(struct patch
*p
)
3382 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
3383 const char *old
, *new;
3385 /* Find common prefix */
3389 const char *slash_old
, *slash_new
;
3390 slash_old
= strchr(old
, '/');
3391 slash_new
= strchr(new, '/');
3394 slash_old
- old
!= slash_new
- new ||
3395 memcmp(old
, new, slash_new
- new))
3397 old
= slash_old
+ 1;
3398 new = slash_new
+ 1;
3400 /* p->old_name thru old is the common prefix, and old and new
3401 * through the end of names are renames
3403 if (old
!= p
->old_name
)
3404 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
3405 (int)(old
- p
->old_name
), p
->old_name
,
3406 old
, new, p
->score
);
3408 printf(" %s %s => %s (%d%%)\n", renamecopy
,
3409 p
->old_name
, p
->new_name
, p
->score
);
3410 show_mode_change(p
, 0);
3413 static void summary_patch_list(struct patch
*patch
)
3417 for (p
= patch
; p
; p
= p
->next
) {
3419 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
3420 else if (p
->is_delete
)
3421 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
3423 if (p
->is_rename
|| p
->is_copy
)
3424 show_rename_copy(p
);
3427 printf(" rewrite %s (%d%%)\n",
3428 p
->new_name
, p
->score
);
3429 show_mode_change(p
, 0);
3432 show_mode_change(p
, 1);
3438 static void patch_stats(struct patch
*patch
)
3440 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
3442 if (lines
> max_change
)
3444 if (patch
->old_name
) {
3445 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
3447 len
= strlen(patch
->old_name
);
3451 if (patch
->new_name
) {
3452 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
3454 len
= strlen(patch
->new_name
);
3460 static void remove_file(struct patch
*patch
, int rmdir_empty
)
3463 if (remove_file_from_cache(patch
->old_name
) < 0)
3464 die("unable to remove %s from index", patch
->old_name
);
3467 if (!remove_or_warn(patch
->old_mode
, patch
->old_name
) && rmdir_empty
) {
3468 remove_path(patch
->old_name
);
3473 static void add_index_file(const char *path
, unsigned mode
, void *buf
, unsigned long size
)
3476 struct cache_entry
*ce
;
3477 int namelen
= strlen(path
);
3478 unsigned ce_size
= cache_entry_size(namelen
);
3483 ce
= xcalloc(1, ce_size
);
3484 memcpy(ce
->name
, path
, namelen
);
3485 ce
->ce_mode
= create_ce_mode(mode
);
3486 ce
->ce_flags
= namelen
;
3487 if (S_ISGITLINK(mode
)) {
3488 const char *s
= buf
;
3490 if (get_sha1_hex(s
+ strlen("Subproject commit "), ce
->sha1
))
3491 die("corrupt patch for subproject %s", path
);
3494 if (lstat(path
, &st
) < 0)
3495 die_errno("unable to stat newly created file '%s'",
3497 fill_stat_cache_info(ce
, &st
);
3499 if (write_sha1_file(buf
, size
, blob_type
, ce
->sha1
) < 0)
3500 die("unable to create backing store for newly created file %s", path
);
3502 if (add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
) < 0)
3503 die("unable to add cache entry for %s", path
);
3506 static int try_create_file(const char *path
, unsigned int mode
, const char *buf
, unsigned long size
)
3509 struct strbuf nbuf
= STRBUF_INIT
;
3511 if (S_ISGITLINK(mode
)) {
3513 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
))
3515 return mkdir(path
, 0777);
3518 if (has_symlinks
&& S_ISLNK(mode
))
3519 /* Although buf:size is counted string, it also is NUL
3522 return symlink(buf
, path
);
3524 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
3528 if (convert_to_working_tree(path
, buf
, size
, &nbuf
)) {
3532 write_or_die(fd
, buf
, size
);
3533 strbuf_release(&nbuf
);
3536 die_errno("closing file '%s'", path
);
3541 * We optimistically assume that the directories exist,
3542 * which is true 99% of the time anyway. If they don't,
3543 * we create them and try again.
3545 static void create_one_file(char *path
, unsigned mode
, const char *buf
, unsigned long size
)
3549 if (!try_create_file(path
, mode
, buf
, size
))
3552 if (errno
== ENOENT
) {
3553 if (safe_create_leading_directories(path
))
3555 if (!try_create_file(path
, mode
, buf
, size
))
3559 if (errno
== EEXIST
|| errno
== EACCES
) {
3560 /* We may be trying to create a file where a directory
3564 if (!lstat(path
, &st
) && (!S_ISDIR(st
.st_mode
) || !rmdir(path
)))
3568 if (errno
== EEXIST
) {
3569 unsigned int nr
= getpid();
3572 char newpath
[PATH_MAX
];
3573 mksnpath(newpath
, sizeof(newpath
), "%s~%u", path
, nr
);
3574 if (!try_create_file(newpath
, mode
, buf
, size
)) {
3575 if (!rename(newpath
, path
))
3577 unlink_or_warn(newpath
);
3580 if (errno
!= EEXIST
)
3585 die_errno("unable to write file '%s' mode %o", path
, mode
);
3588 static void create_file(struct patch
*patch
)
3590 char *path
= patch
->new_name
;
3591 unsigned mode
= patch
->new_mode
;
3592 unsigned long size
= patch
->resultsize
;
3593 char *buf
= patch
->result
;
3596 mode
= S_IFREG
| 0644;
3597 create_one_file(path
, mode
, buf
, size
);
3598 add_index_file(path
, mode
, buf
, size
);
3601 /* phase zero is to remove, phase one is to create */
3602 static void write_out_one_result(struct patch
*patch
, int phase
)
3604 if (patch
->is_delete
> 0) {
3606 remove_file(patch
, 1);
3609 if (patch
->is_new
> 0 || patch
->is_copy
) {
3615 * Rename or modification boils down to the same
3616 * thing: remove the old, write the new
3619 remove_file(patch
, patch
->is_rename
);
3624 static int write_out_one_reject(struct patch
*patch
)
3627 char namebuf
[PATH_MAX
];
3628 struct fragment
*frag
;
3631 for (cnt
= 0, frag
= patch
->fragments
; frag
; frag
= frag
->next
) {
3632 if (!frag
->rejected
)
3638 if (apply_verbosely
)
3639 say_patch_name(stderr
,
3640 "Applied patch ", patch
, " cleanly.\n");
3644 /* This should not happen, because a removal patch that leaves
3645 * contents are marked "rejected" at the patch level.
3647 if (!patch
->new_name
)
3648 die("internal error");
3650 /* Say this even without --verbose */
3651 say_patch_name(stderr
, "Applying patch ", patch
, " with");
3652 fprintf(stderr
, " %d rejects...\n", cnt
);
3654 cnt
= strlen(patch
->new_name
);
3655 if (ARRAY_SIZE(namebuf
) <= cnt
+ 5) {
3656 cnt
= ARRAY_SIZE(namebuf
) - 5;
3657 warning("truncating .rej filename to %.*s.rej",
3658 cnt
- 1, patch
->new_name
);
3660 memcpy(namebuf
, patch
->new_name
, cnt
);
3661 memcpy(namebuf
+ cnt
, ".rej", 5);
3663 rej
= fopen(namebuf
, "w");
3665 return error("cannot open %s: %s", namebuf
, strerror(errno
));
3667 /* Normal git tools never deal with .rej, so do not pretend
3668 * this is a git patch by saying --git nor give extended
3669 * headers. While at it, maybe please "kompare" that wants
3670 * the trailing TAB and some garbage at the end of line ;-).
3672 fprintf(rej
, "diff a/%s b/%s\t(rejected hunks)\n",
3673 patch
->new_name
, patch
->new_name
);
3674 for (cnt
= 1, frag
= patch
->fragments
;
3676 cnt
++, frag
= frag
->next
) {
3677 if (!frag
->rejected
) {
3678 fprintf(stderr
, "Hunk #%d applied cleanly.\n", cnt
);
3681 fprintf(stderr
, "Rejected hunk #%d.\n", cnt
);
3682 fprintf(rej
, "%.*s", frag
->size
, frag
->patch
);
3683 if (frag
->patch
[frag
->size
-1] != '\n')
3690 static int write_out_results(struct patch
*list
)
3696 for (phase
= 0; phase
< 2; phase
++) {
3702 write_out_one_result(l
, phase
);
3703 if (phase
== 1 && write_out_one_reject(l
))
3712 static struct lock_file lock_file
;
3714 static struct string_list limit_by_name
;
3715 static int has_include
;
3716 static void add_name_limit(const char *name
, int exclude
)
3718 struct string_list_item
*it
;
3720 it
= string_list_append(&limit_by_name
, name
);
3721 it
->util
= exclude
? NULL
: (void *) 1;
3724 static int use_patch(struct patch
*p
)
3726 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
3729 /* Paths outside are not touched regardless of "--include" */
3730 if (0 < prefix_length
) {
3731 int pathlen
= strlen(pathname
);
3732 if (pathlen
<= prefix_length
||
3733 memcmp(prefix
, pathname
, prefix_length
))
3737 /* See if it matches any of exclude/include rule */
3738 for (i
= 0; i
< limit_by_name
.nr
; i
++) {
3739 struct string_list_item
*it
= &limit_by_name
.items
[i
];
3740 if (!fnmatch(it
->string
, pathname
, 0))
3741 return (it
->util
!= NULL
);
3745 * If we had any include, a path that does not match any rule is
3746 * not used. Otherwise, we saw bunch of exclude rules (or none)
3747 * and such a path is used.
3749 return !has_include
;
3753 static void prefix_one(char **name
)
3755 char *old_name
= *name
;
3758 *name
= xstrdup(prefix_filename(prefix
, prefix_length
, *name
));
3762 static void prefix_patches(struct patch
*p
)
3764 if (!prefix
|| p
->is_toplevel_relative
)
3766 for ( ; p
; p
= p
->next
) {
3767 prefix_one(&p
->new_name
);
3768 prefix_one(&p
->old_name
);
3772 #define INACCURATE_EOF (1<<0)
3773 #define RECOUNT (1<<1)
3775 static int apply_patch(int fd
, const char *filename
, int options
)
3778 struct strbuf buf
= STRBUF_INIT
; /* owns the patch text */
3779 struct patch
*list
= NULL
, **listp
= &list
;
3780 int skipped_patch
= 0;
3782 patch_input_file
= filename
;
3783 read_patch_file(&buf
, fd
);
3785 while (offset
< buf
.len
) {
3786 struct patch
*patch
;
3789 patch
= xcalloc(1, sizeof(*patch
));
3790 patch
->inaccurate_eof
= !!(options
& INACCURATE_EOF
);
3791 patch
->recount
= !!(options
& RECOUNT
);
3792 nr
= parse_chunk(buf
.buf
+ offset
, buf
.len
- offset
, patch
);
3795 if (apply_in_reverse
)
3796 reverse_patches(patch
);
3798 prefix_patches(patch
);
3799 if (use_patch(patch
)) {
3802 listp
= &patch
->next
;
3811 if (!list
&& !skipped_patch
)
3812 die("unrecognized input");
3814 if (whitespace_error
&& (ws_error_action
== die_on_ws_error
))
3817 update_index
= check_index
&& apply
;
3818 if (update_index
&& newfd
< 0)
3819 newfd
= hold_locked_index(&lock_file
, 1);
3822 if (read_cache() < 0)
3823 die("unable to read index file");
3826 if ((check
|| apply
) &&
3827 check_patch_list(list
) < 0 &&
3831 if (apply
&& write_out_results(list
))
3835 build_fake_ancestor(list
, fake_ancestor
);
3838 stat_patch_list(list
);
3841 numstat_patch_list(list
);
3844 summary_patch_list(list
);
3846 free_patch_list(list
);
3847 strbuf_release(&buf
);
3848 string_list_clear(&fn_table
, 0);
3852 static int git_apply_config(const char *var
, const char *value
, void *cb
)
3854 if (!strcmp(var
, "apply.whitespace"))
3855 return git_config_string(&apply_default_whitespace
, var
, value
);
3856 else if (!strcmp(var
, "apply.ignorewhitespace"))
3857 return git_config_string(&apply_default_ignorewhitespace
, var
, value
);
3858 return git_default_config(var
, value
, cb
);
3861 static int option_parse_exclude(const struct option
*opt
,
3862 const char *arg
, int unset
)
3864 add_name_limit(arg
, 1);
3868 static int option_parse_include(const struct option
*opt
,
3869 const char *arg
, int unset
)
3871 add_name_limit(arg
, 0);
3876 static int option_parse_p(const struct option
*opt
,
3877 const char *arg
, int unset
)
3879 p_value
= atoi(arg
);
3884 static int option_parse_z(const struct option
*opt
,
3885 const char *arg
, int unset
)
3888 line_termination
= '\n';
3890 line_termination
= 0;
3894 static int option_parse_space_change(const struct option
*opt
,
3895 const char *arg
, int unset
)
3898 ws_ignore_action
= ignore_ws_none
;
3900 ws_ignore_action
= ignore_ws_change
;
3904 static int option_parse_whitespace(const struct option
*opt
,
3905 const char *arg
, int unset
)
3907 const char **whitespace_option
= opt
->value
;
3909 *whitespace_option
= arg
;
3910 parse_whitespace_option(arg
);
3914 static int option_parse_directory(const struct option
*opt
,
3915 const char *arg
, int unset
)
3917 root_len
= strlen(arg
);
3918 if (root_len
&& arg
[root_len
- 1] != '/') {
3920 root
= new_root
= xmalloc(root_len
+ 2);
3921 strcpy(new_root
, arg
);
3922 strcpy(new_root
+ root_len
++, "/");
3928 int cmd_apply(int argc
, const char **argv
, const char *prefix_
)
3932 int is_not_gitdir
= !startup_info
->have_repository
;
3933 int force_apply
= 0;
3935 const char *whitespace_option
= NULL
;
3937 struct option builtin_apply_options
[] = {
3938 { OPTION_CALLBACK
, 0, "exclude", NULL
, "path",
3939 "don't apply changes matching the given path",
3940 0, option_parse_exclude
},
3941 { OPTION_CALLBACK
, 0, "include", NULL
, "path",
3942 "apply changes matching the given path",
3943 0, option_parse_include
},
3944 { OPTION_CALLBACK
, 'p', NULL
, NULL
, "num",
3945 "remove <num> leading slashes from traditional diff paths",
3946 0, option_parse_p
},
3947 OPT_BOOLEAN(0, "no-add", &no_add
,
3948 "ignore additions made by the patch"),
3949 OPT_BOOLEAN(0, "stat", &diffstat
,
3950 "instead of applying the patch, output diffstat for the input"),
3951 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
3952 OPT_NOOP_NOARG(0, "binary"),
3953 OPT_BOOLEAN(0, "numstat", &numstat
,
3954 "shows number of added and deleted lines in decimal notation"),
3955 OPT_BOOLEAN(0, "summary", &summary
,
3956 "instead of applying the patch, output a summary for the input"),
3957 OPT_BOOLEAN(0, "check", &check
,
3958 "instead of applying the patch, see if the patch is applicable"),
3959 OPT_BOOLEAN(0, "index", &check_index
,
3960 "make sure the patch is applicable to the current index"),
3961 OPT_BOOLEAN(0, "cached", &cached
,
3962 "apply a patch without touching the working tree"),
3963 OPT_BOOLEAN(0, "apply", &force_apply
,
3964 "also apply the patch (use with --stat/--summary/--check)"),
3965 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor
,
3966 "build a temporary index based on embedded index information"),
3967 { OPTION_CALLBACK
, 'z', NULL
, NULL
, NULL
,
3968 "paths are separated with NUL character",
3969 PARSE_OPT_NOARG
, option_parse_z
},
3970 OPT_INTEGER('C', NULL
, &p_context
,
3971 "ensure at least <n> lines of context match"),
3972 { OPTION_CALLBACK
, 0, "whitespace", &whitespace_option
, "action",
3973 "detect new or modified lines that have whitespace errors",
3974 0, option_parse_whitespace
},
3975 { OPTION_CALLBACK
, 0, "ignore-space-change", NULL
, NULL
,
3976 "ignore changes in whitespace when finding context",
3977 PARSE_OPT_NOARG
, option_parse_space_change
},
3978 { OPTION_CALLBACK
, 0, "ignore-whitespace", NULL
, NULL
,
3979 "ignore changes in whitespace when finding context",
3980 PARSE_OPT_NOARG
, option_parse_space_change
},
3981 OPT_BOOLEAN('R', "reverse", &apply_in_reverse
,
3982 "apply the patch in reverse"),
3983 OPT_BOOLEAN(0, "unidiff-zero", &unidiff_zero
,
3984 "don't expect at least one line of context"),
3985 OPT_BOOLEAN(0, "reject", &apply_with_reject
,
3986 "leave the rejected hunks in corresponding *.rej files"),
3987 OPT_BOOLEAN(0, "allow-overlap", &allow_overlap
,
3988 "allow overlapping hunks"),
3989 OPT__VERBOSE(&apply_verbosely
, "be verbose"),
3990 OPT_BIT(0, "inaccurate-eof", &options
,
3991 "tolerate incorrectly detected missing new-line at the end of file",
3993 OPT_BIT(0, "recount", &options
,
3994 "do not trust the line counts in the hunk headers",
3996 { OPTION_CALLBACK
, 0, "directory", NULL
, "root",
3997 "prepend <root> to all filenames",
3998 0, option_parse_directory
},
4003 prefix_length
= prefix
? strlen(prefix
) : 0;
4004 git_config(git_apply_config
, NULL
);
4005 if (apply_default_whitespace
)
4006 parse_whitespace_option(apply_default_whitespace
);
4007 if (apply_default_ignorewhitespace
)
4008 parse_ignorewhitespace_option(apply_default_ignorewhitespace
);
4010 argc
= parse_options(argc
, argv
, prefix
, builtin_apply_options
,
4013 if (apply_with_reject
)
4014 apply
= apply_verbosely
= 1;
4015 if (!force_apply
&& (diffstat
|| numstat
|| summary
|| check
|| fake_ancestor
))
4017 if (check_index
&& is_not_gitdir
)
4018 die("--index outside a repository");
4021 die("--cached outside a repository");
4024 for (i
= 0; i
< argc
; i
++) {
4025 const char *arg
= argv
[i
];
4028 if (!strcmp(arg
, "-")) {
4029 errs
|= apply_patch(0, "<stdin>", options
);
4032 } else if (0 < prefix_length
)
4033 arg
= prefix_filename(prefix
, prefix_length
, arg
);
4035 fd
= open(arg
, O_RDONLY
);
4037 die_errno("can't open patch '%s'", arg
);
4039 set_default_whitespace_mode(whitespace_option
);
4040 errs
|= apply_patch(fd
, arg
, options
);
4043 set_default_whitespace_mode(whitespace_option
);
4045 errs
|= apply_patch(0, "<stdin>", options
);
4046 if (whitespace_error
) {
4047 if (squelch_whitespace_errors
&&
4048 squelch_whitespace_errors
< whitespace_error
) {
4050 whitespace_error
- squelch_whitespace_errors
;
4051 warning("squelched %d "
4052 "whitespace error%s",
4054 squelched
== 1 ? "" : "s");
4056 if (ws_error_action
== die_on_ws_error
)
4057 die("%d line%s add%s whitespace errors.",
4059 whitespace_error
== 1 ? "" : "s",
4060 whitespace_error
== 1 ? "s" : "");
4061 if (applied_after_fixing_ws
&& apply
)
4062 warning("%d line%s applied after"
4063 " fixing whitespace errors.",
4064 applied_after_fixing_ws
,
4065 applied_after_fixing_ws
== 1 ? "" : "s");
4066 else if (whitespace_error
)
4067 warning("%d line%s add%s whitespace errors.",
4069 whitespace_error
== 1 ? "" : "s",
4070 whitespace_error
== 1 ? "s" : "");
4074 if (write_cache(newfd
, active_cache
, active_nr
) ||
4075 commit_locked_index(&lock_file
))
4076 die("Unable to write new index file");