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"
18 #include "parse-options.h"
21 * --check turns on checking that the working tree matches the
22 * files that are being modified, but doesn't apply the patch
23 * --stat does just a diffstat, and doesn't actually apply
24 * --numstat does numeric diffstat, and doesn't actually apply
25 * --index-info shows the old and new index info for paths if available.
26 * --index updates the cache as well.
27 * --cached updates only the cache without ever touching the working tree.
29 static const char *prefix
;
30 static int prefix_length
= -1;
31 static int newfd
= -1;
33 static int unidiff_zero
;
34 static int p_value
= 1;
35 static int p_value_known
;
36 static int check_index
;
37 static int update_index
;
44 static int apply_in_reverse
;
45 static int apply_with_reject
;
46 static int apply_verbosely
;
47 static int allow_overlap
;
49 static const char *fake_ancestor
;
50 static int line_termination
= '\n';
51 static unsigned int p_context
= UINT_MAX
;
52 static const char * const apply_usage
[] = {
53 "git apply [options] [<patch>...]",
57 static enum ws_error_action
{
62 } ws_error_action
= warn_on_ws_error
;
63 static int whitespace_error
;
64 static int squelch_whitespace_errors
= 5;
65 static int applied_after_fixing_ws
;
67 static enum ws_ignore
{
70 } ws_ignore_action
= ignore_ws_none
;
73 static const char *patch_input_file
;
74 static const char *root
;
76 static int read_stdin
= 1;
79 static void parse_whitespace_option(const char *option
)
82 ws_error_action
= warn_on_ws_error
;
85 if (!strcmp(option
, "warn")) {
86 ws_error_action
= warn_on_ws_error
;
89 if (!strcmp(option
, "nowarn")) {
90 ws_error_action
= nowarn_ws_error
;
93 if (!strcmp(option
, "error")) {
94 ws_error_action
= die_on_ws_error
;
97 if (!strcmp(option
, "error-all")) {
98 ws_error_action
= die_on_ws_error
;
99 squelch_whitespace_errors
= 0;
102 if (!strcmp(option
, "strip") || !strcmp(option
, "fix")) {
103 ws_error_action
= correct_ws_error
;
106 die(_("unrecognized whitespace option '%s'"), option
);
109 static void parse_ignorewhitespace_option(const char *option
)
111 if (!option
|| !strcmp(option
, "no") ||
112 !strcmp(option
, "false") || !strcmp(option
, "never") ||
113 !strcmp(option
, "none")) {
114 ws_ignore_action
= ignore_ws_none
;
117 if (!strcmp(option
, "change")) {
118 ws_ignore_action
= ignore_ws_change
;
121 die(_("unrecognized whitespace ignore option '%s'"), option
);
124 static void set_default_whitespace_mode(const char *whitespace_option
)
126 if (!whitespace_option
&& !apply_default_whitespace
)
127 ws_error_action
= (apply
? warn_on_ws_error
: nowarn_ws_error
);
131 * For "diff-stat" like behaviour, we keep track of the biggest change
132 * we've seen, and the longest filename. That allows us to do simple
135 static int max_change
, max_len
;
138 * Various "current state", notably line numbers and what
139 * file (and how) we're patching right now.. The "is_xxxx"
140 * things are flags, where -1 means "don't know yet".
142 static int linenr
= 1;
145 * This represents one "hunk" from a patch, starting with
146 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
147 * patch text is pointed at by patch, and its byte length
148 * is stored in size. leading and trailing are the number
152 unsigned long leading
, trailing
;
153 unsigned long oldpos
, oldlines
;
154 unsigned long newpos
, newlines
;
156 * 'patch' is usually borrowed from buf in apply_patch(),
157 * but some codepaths store an allocated buffer.
160 unsigned free_patch
:1,
164 struct fragment
*next
;
168 * When dealing with a binary patch, we reuse "leading" field
169 * to store the type of the binary hunk, either deflated "delta"
170 * or deflated "literal".
172 #define binary_patch_method leading
173 #define BINARY_DELTA_DEFLATED 1
174 #define BINARY_LITERAL_DEFLATED 2
177 * This represents a "patch" to a file, both metainfo changes
178 * such as creation/deletion, filemode and content changes represented
179 * as a series of fragments.
182 char *new_name
, *old_name
, *def_name
;
183 unsigned int old_mode
, new_mode
;
184 int is_new
, is_delete
; /* -1 = unknown, 0 = false, 1 = true */
187 unsigned long deflate_origlen
;
188 int lines_added
, lines_deleted
;
190 unsigned int is_toplevel_relative
:1;
191 unsigned int inaccurate_eof
:1;
192 unsigned int is_binary
:1;
193 unsigned int is_copy
:1;
194 unsigned int is_rename
:1;
195 unsigned int recount
:1;
196 struct fragment
*fragments
;
199 char old_sha1_prefix
[41];
200 char new_sha1_prefix
[41];
204 static void free_fragment_list(struct fragment
*list
)
207 struct fragment
*next
= list
->next
;
208 if (list
->free_patch
)
209 free((char *)list
->patch
);
215 static void free_patch(struct patch
*patch
)
217 free_fragment_list(patch
->fragments
);
218 free(patch
->def_name
);
219 free(patch
->old_name
);
220 free(patch
->new_name
);
225 static void free_patch_list(struct patch
*list
)
228 struct patch
*next
= list
->next
;
235 * A line in a file, len-bytes long (includes the terminating LF,
236 * except for an incomplete line at the end if the file ends with
237 * one), and its contents hashes to 'hash'.
243 #define LINE_COMMON 1
244 #define LINE_PATCHED 2
248 * This represents a "file", which is an array of "lines".
255 struct line
*line_allocated
;
260 * Records filenames that have been touched, in order to handle
261 * the case where more than one patches touch the same file.
264 static struct string_list fn_table
;
266 static uint32_t hash_line(const char *cp
, size_t len
)
270 for (i
= 0, h
= 0; i
< len
; i
++) {
271 if (!isspace(cp
[i
])) {
272 h
= h
* 3 + (cp
[i
] & 0xff);
279 * Compare lines s1 of length n1 and s2 of length n2, ignoring
280 * whitespace difference. Returns 1 if they match, 0 otherwise
282 static int fuzzy_matchlines(const char *s1
, size_t n1
,
283 const char *s2
, size_t n2
)
285 const char *last1
= s1
+ n1
- 1;
286 const char *last2
= s2
+ n2
- 1;
289 /* ignore line endings */
290 while ((*last1
== '\r') || (*last1
== '\n'))
292 while ((*last2
== '\r') || (*last2
== '\n'))
295 /* skip leading whitespace */
296 while (isspace(*s1
) && (s1
<= last1
))
298 while (isspace(*s2
) && (s2
<= last2
))
300 /* early return if both lines are empty */
301 if ((s1
> last1
) && (s2
> last2
))
304 result
= *s1
++ - *s2
++;
306 * Skip whitespace inside. We check for whitespace on
307 * both buffers because we don't want "a b" to match
310 if (isspace(*s1
) && isspace(*s2
)) {
311 while (isspace(*s1
) && s1
<= last1
)
313 while (isspace(*s2
) && s2
<= last2
)
317 * If we reached the end on one side only,
321 ((s2
> last2
) && (s1
<= last1
)) ||
322 ((s1
> last1
) && (s2
<= last2
)))
324 if ((s1
> last1
) && (s2
> last2
))
331 static void add_line_info(struct image
*img
, const char *bol
, size_t len
, unsigned flag
)
333 ALLOC_GROW(img
->line_allocated
, img
->nr
+ 1, img
->alloc
);
334 img
->line_allocated
[img
->nr
].len
= len
;
335 img
->line_allocated
[img
->nr
].hash
= hash_line(bol
, len
);
336 img
->line_allocated
[img
->nr
].flag
= flag
;
341 * "buf" has the file contents to be patched (read from various sources).
342 * attach it to "image" and add line-based index to it.
343 * "image" now owns the "buf".
345 static void prepare_image(struct image
*image
, char *buf
, size_t len
,
346 int prepare_linetable
)
350 memset(image
, 0, sizeof(*image
));
354 if (!prepare_linetable
)
357 ep
= image
->buf
+ image
->len
;
361 for (next
= cp
; next
< ep
&& *next
!= '\n'; next
++)
365 add_line_info(image
, cp
, next
- cp
, 0);
368 image
->line
= image
->line_allocated
;
371 static void clear_image(struct image
*image
)
374 free(image
->line_allocated
);
375 memset(image
, 0, sizeof(*image
));
378 /* fmt must contain _one_ %s and no other substitution */
379 static void say_patch_name(FILE *output
, const char *fmt
, struct patch
*patch
)
381 struct strbuf sb
= STRBUF_INIT
;
383 if (patch
->old_name
&& patch
->new_name
&&
384 strcmp(patch
->old_name
, patch
->new_name
)) {
385 quote_c_style(patch
->old_name
, &sb
, NULL
, 0);
386 strbuf_addstr(&sb
, " => ");
387 quote_c_style(patch
->new_name
, &sb
, NULL
, 0);
389 const char *n
= patch
->new_name
;
392 quote_c_style(n
, &sb
, NULL
, 0);
394 fprintf(output
, fmt
, sb
.buf
);
401 static void read_patch_file(struct strbuf
*sb
, int fd
)
403 if (strbuf_read(sb
, fd
, 0) < 0)
404 die_errno("git apply: failed to read");
407 * Make sure that we have some slop in the buffer
408 * so that we can do speculative "memcmp" etc, and
409 * see to it that it is NUL-filled.
411 strbuf_grow(sb
, SLOP
);
412 memset(sb
->buf
+ sb
->len
, 0, SLOP
);
415 static unsigned long linelen(const char *buffer
, unsigned long size
)
417 unsigned long len
= 0;
420 if (*buffer
++ == '\n')
426 static int is_dev_null(const char *str
)
428 return !memcmp("/dev/null", str
, 9) && isspace(str
[9]);
434 static int name_terminate(const char *name
, int namelen
, int c
, int terminate
)
436 if (c
== ' ' && !(terminate
& TERM_SPACE
))
438 if (c
== '\t' && !(terminate
& TERM_TAB
))
444 /* remove double slashes to make --index work with such filenames */
445 static char *squash_slash(char *name
)
453 if ((name
[j
++] = name
[i
++]) == '/')
454 while (name
[i
] == '/')
461 static char *find_name_gnu(const char *line
, const char *def
, int p_value
)
463 struct strbuf name
= STRBUF_INIT
;
467 * Proposed "new-style" GNU patch/diff format; see
468 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
470 if (unquote_c_style(&name
, line
, NULL
)) {
471 strbuf_release(&name
);
475 for (cp
= name
.buf
; p_value
; p_value
--) {
476 cp
= strchr(cp
, '/');
478 strbuf_release(&name
);
484 strbuf_remove(&name
, 0, cp
- name
.buf
);
486 strbuf_insert(&name
, 0, root
, root_len
);
487 return squash_slash(strbuf_detach(&name
, NULL
));
490 static size_t sane_tz_len(const char *line
, size_t len
)
494 if (len
< strlen(" +0500") || line
[len
-strlen(" +0500")] != ' ')
496 tz
= line
+ len
- strlen(" +0500");
498 if (tz
[1] != '+' && tz
[1] != '-')
501 for (p
= tz
+ 2; p
!= line
+ len
; p
++)
505 return line
+ len
- tz
;
508 static size_t tz_with_colon_len(const char *line
, size_t len
)
512 if (len
< strlen(" +08:00") || line
[len
- strlen(":00")] != ':')
514 tz
= line
+ len
- strlen(" +08:00");
516 if (tz
[0] != ' ' || (tz
[1] != '+' && tz
[1] != '-'))
519 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
520 !isdigit(*p
++) || !isdigit(*p
++))
523 return line
+ len
- tz
;
526 static size_t date_len(const char *line
, size_t len
)
528 const char *date
, *p
;
530 if (len
< strlen("72-02-05") || line
[len
-strlen("-05")] != '-')
532 p
= date
= line
+ len
- strlen("72-02-05");
534 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
535 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
536 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a date. */
539 if (date
- line
>= strlen("19") &&
540 isdigit(date
[-1]) && isdigit(date
[-2])) /* 4-digit year */
541 date
-= strlen("19");
543 return line
+ len
- date
;
546 static size_t short_time_len(const char *line
, size_t len
)
548 const char *time
, *p
;
550 if (len
< strlen(" 07:01:32") || line
[len
-strlen(":32")] != ':')
552 p
= time
= line
+ len
- strlen(" 07:01:32");
554 /* Permit 1-digit hours? */
556 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
557 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
558 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a time. */
561 return line
+ len
- time
;
564 static size_t fractional_time_len(const char *line
, size_t len
)
569 /* Expected format: 19:41:17.620000023 */
570 if (!len
|| !isdigit(line
[len
- 1]))
574 /* Fractional seconds. */
575 while (p
> line
&& isdigit(*p
))
580 /* Hours, minutes, and whole seconds. */
581 n
= short_time_len(line
, p
- line
);
585 return line
+ len
- p
+ n
;
588 static size_t trailing_spaces_len(const char *line
, size_t len
)
592 /* Expected format: ' ' x (1 or more) */
593 if (!len
|| line
[len
- 1] != ' ')
600 return line
+ len
- (p
+ 1);
607 static size_t diff_timestamp_len(const char *line
, size_t len
)
609 const char *end
= line
+ len
;
613 * Posix: 2010-07-05 19:41:17
614 * GNU: 2010-07-05 19:41:17.620000023 -0500
617 if (!isdigit(end
[-1]))
620 n
= sane_tz_len(line
, end
- line
);
622 n
= tz_with_colon_len(line
, end
- line
);
625 n
= short_time_len(line
, end
- line
);
627 n
= fractional_time_len(line
, end
- line
);
630 n
= date_len(line
, end
- line
);
631 if (!n
) /* No date. Too bad. */
635 if (end
== line
) /* No space before date. */
637 if (end
[-1] == '\t') { /* Success! */
639 return line
+ len
- end
;
641 if (end
[-1] != ' ') /* No space before date. */
644 /* Whitespace damage. */
645 end
-= trailing_spaces_len(line
, end
- line
);
646 return line
+ len
- end
;
649 static char *null_strdup(const char *s
)
651 return s
? xstrdup(s
) : NULL
;
654 static char *find_name_common(const char *line
, const char *def
,
655 int p_value
, const char *end
, int terminate
)
658 const char *start
= NULL
;
662 while (line
!= end
) {
665 if (!end
&& isspace(c
)) {
668 if (name_terminate(start
, line
-start
, c
, terminate
))
672 if (c
== '/' && !--p_value
)
676 return squash_slash(null_strdup(def
));
679 return squash_slash(null_strdup(def
));
682 * Generally we prefer the shorter name, especially
683 * if the other one is just a variation of that with
684 * something else tacked on to the end (ie "file.orig"
688 int deflen
= strlen(def
);
689 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
690 return squash_slash(xstrdup(def
));
694 char *ret
= xmalloc(root_len
+ len
+ 1);
696 memcpy(ret
+ root_len
, start
, len
);
697 ret
[root_len
+ len
] = '\0';
698 return squash_slash(ret
);
701 return squash_slash(xmemdupz(start
, len
));
704 static char *find_name(const char *line
, char *def
, int p_value
, int terminate
)
707 char *name
= find_name_gnu(line
, def
, p_value
);
712 return find_name_common(line
, def
, p_value
, NULL
, terminate
);
715 static char *find_name_traditional(const char *line
, char *def
, int p_value
)
717 size_t len
= strlen(line
);
721 char *name
= find_name_gnu(line
, def
, p_value
);
726 len
= strchrnul(line
, '\n') - line
;
727 date_len
= diff_timestamp_len(line
, len
);
729 return find_name_common(line
, def
, p_value
, NULL
, TERM_TAB
);
732 return find_name_common(line
, def
, p_value
, line
+ len
, 0);
735 static int count_slashes(const char *cp
)
747 * Given the string after "--- " or "+++ ", guess the appropriate
748 * p_value for the given patch.
750 static int guess_p_value(const char *nameline
)
755 if (is_dev_null(nameline
))
757 name
= find_name_traditional(nameline
, NULL
, 0);
760 cp
= strchr(name
, '/');
765 * Does it begin with "a/$our-prefix" and such? Then this is
766 * very likely to apply to our directory.
768 if (!strncmp(name
, prefix
, prefix_length
))
769 val
= count_slashes(prefix
);
772 if (!strncmp(cp
, prefix
, prefix_length
))
773 val
= count_slashes(prefix
) + 1;
781 * Does the ---/+++ line has the POSIX timestamp after the last HT?
782 * GNU diff puts epoch there to signal a creation/deletion event. Is
783 * this such a timestamp?
785 static int has_epoch_timestamp(const char *nameline
)
788 * We are only interested in epoch timestamp; any non-zero
789 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
790 * For the same reason, the date must be either 1969-12-31 or
791 * 1970-01-01, and the seconds part must be "00".
793 const char stamp_regexp
[] =
794 "^(1969-12-31|1970-01-01)"
796 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
798 "([-+][0-2][0-9]:?[0-5][0-9])\n";
799 const char *timestamp
= NULL
, *cp
, *colon
;
800 static regex_t
*stamp
;
806 for (cp
= nameline
; *cp
!= '\n'; cp
++) {
813 stamp
= xmalloc(sizeof(*stamp
));
814 if (regcomp(stamp
, stamp_regexp
, REG_EXTENDED
)) {
815 warning(_("Cannot prepare timestamp regexp %s"),
821 status
= regexec(stamp
, timestamp
, ARRAY_SIZE(m
), m
, 0);
823 if (status
!= REG_NOMATCH
)
824 warning(_("regexec returned %d for input: %s"),
829 zoneoffset
= strtol(timestamp
+ m
[3].rm_so
+ 1, (char **) &colon
, 10);
831 zoneoffset
= zoneoffset
* 60 + strtol(colon
+ 1, NULL
, 10);
833 zoneoffset
= (zoneoffset
/ 100) * 60 + (zoneoffset
% 100);
834 if (timestamp
[m
[3].rm_so
] == '-')
835 zoneoffset
= -zoneoffset
;
838 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
839 * (west of GMT) or 1970-01-01 (east of GMT)
841 if ((zoneoffset
< 0 && memcmp(timestamp
, "1969-12-31", 10)) ||
842 (0 <= zoneoffset
&& memcmp(timestamp
, "1970-01-01", 10)))
845 hourminute
= (strtol(timestamp
+ 11, NULL
, 10) * 60 +
846 strtol(timestamp
+ 14, NULL
, 10) -
849 return ((zoneoffset
< 0 && hourminute
== 1440) ||
850 (0 <= zoneoffset
&& !hourminute
));
854 * Get the name etc info from the ---/+++ lines of a traditional patch header
856 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
857 * files, we can happily check the index for a match, but for creating a
858 * new file we should try to match whatever "patch" does. I have no idea.
860 static void parse_traditional_patch(const char *first
, const char *second
, struct patch
*patch
)
864 first
+= 4; /* skip "--- " */
865 second
+= 4; /* skip "+++ " */
866 if (!p_value_known
) {
868 p
= guess_p_value(first
);
869 q
= guess_p_value(second
);
871 if (0 <= p
&& p
== q
) {
876 if (is_dev_null(first
)) {
878 patch
->is_delete
= 0;
879 name
= find_name_traditional(second
, NULL
, p_value
);
880 patch
->new_name
= name
;
881 } else if (is_dev_null(second
)) {
883 patch
->is_delete
= 1;
884 name
= find_name_traditional(first
, NULL
, p_value
);
885 patch
->old_name
= name
;
888 first_name
= find_name_traditional(first
, NULL
, p_value
);
889 name
= find_name_traditional(second
, first_name
, p_value
);
891 if (has_epoch_timestamp(first
)) {
893 patch
->is_delete
= 0;
894 patch
->new_name
= name
;
895 } else if (has_epoch_timestamp(second
)) {
897 patch
->is_delete
= 1;
898 patch
->old_name
= name
;
900 patch
->old_name
= name
;
901 patch
->new_name
= xstrdup(name
);
905 die(_("unable to find filename in patch at line %d"), linenr
);
908 static int gitdiff_hdrend(const char *line
, struct patch
*patch
)
914 * We're anal about diff header consistency, to make
915 * sure that we don't end up having strange ambiguous
916 * patches floating around.
918 * As a result, gitdiff_{old|new}name() will check
919 * their names against any previous information, just
922 static char *gitdiff_verify_name(const char *line
, int isnull
, char *orig_name
, const char *oldnew
)
924 if (!orig_name
&& !isnull
)
925 return find_name(line
, NULL
, p_value
, TERM_TAB
);
934 die(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"), name
, linenr
);
935 another
= find_name(line
, NULL
, p_value
, TERM_TAB
);
936 if (!another
|| memcmp(another
, name
, len
+ 1))
937 die(_("git apply: bad git-diff - inconsistent %s filename on line %d"), oldnew
, linenr
);
942 /* expect "/dev/null" */
943 if (memcmp("/dev/null", line
, 9) || line
[9] != '\n')
944 die(_("git apply: bad git-diff - expected /dev/null on line %d"), linenr
);
949 static int gitdiff_oldname(const char *line
, struct patch
*patch
)
951 char *orig
= patch
->old_name
;
952 patch
->old_name
= gitdiff_verify_name(line
, patch
->is_new
, patch
->old_name
, "old");
953 if (orig
!= patch
->old_name
)
958 static int gitdiff_newname(const char *line
, struct patch
*patch
)
960 char *orig
= patch
->new_name
;
961 patch
->new_name
= gitdiff_verify_name(line
, patch
->is_delete
, patch
->new_name
, "new");
962 if (orig
!= patch
->new_name
)
967 static int gitdiff_oldmode(const char *line
, struct patch
*patch
)
969 patch
->old_mode
= strtoul(line
, NULL
, 8);
973 static int gitdiff_newmode(const char *line
, struct patch
*patch
)
975 patch
->new_mode
= strtoul(line
, NULL
, 8);
979 static int gitdiff_delete(const char *line
, struct patch
*patch
)
981 patch
->is_delete
= 1;
982 free(patch
->old_name
);
983 patch
->old_name
= null_strdup(patch
->def_name
);
984 return gitdiff_oldmode(line
, patch
);
987 static int gitdiff_newfile(const char *line
, struct patch
*patch
)
990 free(patch
->new_name
);
991 patch
->new_name
= null_strdup(patch
->def_name
);
992 return gitdiff_newmode(line
, patch
);
995 static int gitdiff_copysrc(const char *line
, struct patch
*patch
)
998 free(patch
->old_name
);
999 patch
->old_name
= find_name(line
, NULL
, p_value
? p_value
- 1 : 0, 0);
1003 static int gitdiff_copydst(const char *line
, struct patch
*patch
)
1006 free(patch
->new_name
);
1007 patch
->new_name
= find_name(line
, NULL
, p_value
? p_value
- 1 : 0, 0);
1011 static int gitdiff_renamesrc(const char *line
, struct patch
*patch
)
1013 patch
->is_rename
= 1;
1014 free(patch
->old_name
);
1015 patch
->old_name
= find_name(line
, NULL
, p_value
? p_value
- 1 : 0, 0);
1019 static int gitdiff_renamedst(const char *line
, struct patch
*patch
)
1021 patch
->is_rename
= 1;
1022 free(patch
->new_name
);
1023 patch
->new_name
= find_name(line
, NULL
, p_value
? p_value
- 1 : 0, 0);
1027 static int gitdiff_similarity(const char *line
, struct patch
*patch
)
1029 if ((patch
->score
= strtoul(line
, NULL
, 10)) == ULONG_MAX
)
1034 static int gitdiff_dissimilarity(const char *line
, struct patch
*patch
)
1036 if ((patch
->score
= strtoul(line
, NULL
, 10)) == ULONG_MAX
)
1041 static int gitdiff_index(const char *line
, struct patch
*patch
)
1044 * index line is N hexadecimal, "..", N hexadecimal,
1045 * and optional space with octal mode.
1047 const char *ptr
, *eol
;
1050 ptr
= strchr(line
, '.');
1051 if (!ptr
|| ptr
[1] != '.' || 40 < ptr
- line
)
1054 memcpy(patch
->old_sha1_prefix
, line
, len
);
1055 patch
->old_sha1_prefix
[len
] = 0;
1058 ptr
= strchr(line
, ' ');
1059 eol
= strchr(line
, '\n');
1061 if (!ptr
|| eol
< ptr
)
1067 memcpy(patch
->new_sha1_prefix
, line
, len
);
1068 patch
->new_sha1_prefix
[len
] = 0;
1070 patch
->old_mode
= strtoul(ptr
+1, NULL
, 8);
1075 * This is normal for a diff that doesn't change anything: we'll fall through
1076 * into the next diff. Tell the parser to break out.
1078 static int gitdiff_unrecognized(const char *line
, struct patch
*patch
)
1083 static const char *stop_at_slash(const char *line
, int llen
)
1085 int nslash
= p_value
;
1088 for (i
= 0; i
< llen
; i
++) {
1090 if (ch
== '/' && --nslash
<= 0)
1097 * This is to extract the same name that appears on "diff --git"
1098 * line. We do not find and return anything if it is a rename
1099 * patch, and it is OK because we will find the name elsewhere.
1100 * We need to reliably find name only when it is mode-change only,
1101 * creation or deletion of an empty file. In any of these cases,
1102 * both sides are the same name under a/ and b/ respectively.
1104 static char *git_header_name(const char *line
, int llen
)
1107 const char *second
= NULL
;
1108 size_t len
, line_len
;
1110 line
+= strlen("diff --git ");
1111 llen
-= strlen("diff --git ");
1115 struct strbuf first
= STRBUF_INIT
;
1116 struct strbuf sp
= STRBUF_INIT
;
1118 if (unquote_c_style(&first
, line
, &second
))
1119 goto free_and_fail1
;
1121 /* advance to the first slash */
1122 cp
= stop_at_slash(first
.buf
, first
.len
);
1123 /* we do not accept absolute paths */
1124 if (!cp
|| cp
== first
.buf
)
1125 goto free_and_fail1
;
1126 strbuf_remove(&first
, 0, cp
+ 1 - first
.buf
);
1129 * second points at one past closing dq of name.
1130 * find the second name.
1132 while ((second
< line
+ llen
) && isspace(*second
))
1135 if (line
+ llen
<= second
)
1136 goto free_and_fail1
;
1137 if (*second
== '"') {
1138 if (unquote_c_style(&sp
, second
, NULL
))
1139 goto free_and_fail1
;
1140 cp
= stop_at_slash(sp
.buf
, sp
.len
);
1141 if (!cp
|| cp
== sp
.buf
)
1142 goto free_and_fail1
;
1143 /* They must match, otherwise ignore */
1144 if (strcmp(cp
+ 1, first
.buf
))
1145 goto free_and_fail1
;
1146 strbuf_release(&sp
);
1147 return strbuf_detach(&first
, NULL
);
1150 /* unquoted second */
1151 cp
= stop_at_slash(second
, line
+ llen
- second
);
1152 if (!cp
|| cp
== second
)
1153 goto free_and_fail1
;
1155 if (line
+ llen
- cp
!= first
.len
+ 1 ||
1156 memcmp(first
.buf
, cp
, first
.len
))
1157 goto free_and_fail1
;
1158 return strbuf_detach(&first
, NULL
);
1161 strbuf_release(&first
);
1162 strbuf_release(&sp
);
1166 /* unquoted first name */
1167 name
= stop_at_slash(line
, llen
);
1168 if (!name
|| name
== line
)
1173 * since the first name is unquoted, a dq if exists must be
1174 * the beginning of the second name.
1176 for (second
= name
; second
< line
+ llen
; second
++) {
1177 if (*second
== '"') {
1178 struct strbuf sp
= STRBUF_INIT
;
1181 if (unquote_c_style(&sp
, second
, NULL
))
1182 goto free_and_fail2
;
1184 np
= stop_at_slash(sp
.buf
, sp
.len
);
1185 if (!np
|| np
== sp
.buf
)
1186 goto free_and_fail2
;
1189 len
= sp
.buf
+ sp
.len
- np
;
1190 if (len
< second
- name
&&
1191 !strncmp(np
, name
, len
) &&
1192 isspace(name
[len
])) {
1194 strbuf_remove(&sp
, 0, np
- sp
.buf
);
1195 return strbuf_detach(&sp
, NULL
);
1199 strbuf_release(&sp
);
1205 * Accept a name only if it shows up twice, exactly the same
1208 second
= strchr(name
, '\n');
1211 line_len
= second
- name
;
1212 for (len
= 0 ; ; len
++) {
1213 switch (name
[len
]) {
1218 case '\t': case ' ':
1219 second
= stop_at_slash(name
+ len
, line_len
- len
);
1223 if (second
[len
] == '\n' && !strncmp(name
, second
, len
)) {
1224 return xmemdupz(name
, len
);
1230 /* Verify that we recognize the lines following a git header */
1231 static int parse_git_header(const char *line
, int len
, unsigned int size
, struct patch
*patch
)
1233 unsigned long offset
;
1235 /* A git diff has explicit new/delete information, so we don't guess */
1237 patch
->is_delete
= 0;
1240 * Some things may not have the old name in the
1241 * rest of the headers anywhere (pure mode changes,
1242 * or removing or adding empty files), so we get
1243 * the default name from the header.
1245 patch
->def_name
= git_header_name(line
, len
);
1246 if (patch
->def_name
&& root
) {
1247 char *s
= xmalloc(root_len
+ strlen(patch
->def_name
) + 1);
1249 strcpy(s
+ root_len
, patch
->def_name
);
1250 free(patch
->def_name
);
1251 patch
->def_name
= s
;
1257 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1258 static const struct opentry
{
1260 int (*fn
)(const char *, struct patch
*);
1262 { "@@ -", gitdiff_hdrend
},
1263 { "--- ", gitdiff_oldname
},
1264 { "+++ ", gitdiff_newname
},
1265 { "old mode ", gitdiff_oldmode
},
1266 { "new mode ", gitdiff_newmode
},
1267 { "deleted file mode ", gitdiff_delete
},
1268 { "new file mode ", gitdiff_newfile
},
1269 { "copy from ", gitdiff_copysrc
},
1270 { "copy to ", gitdiff_copydst
},
1271 { "rename old ", gitdiff_renamesrc
},
1272 { "rename new ", gitdiff_renamedst
},
1273 { "rename from ", gitdiff_renamesrc
},
1274 { "rename to ", gitdiff_renamedst
},
1275 { "similarity index ", gitdiff_similarity
},
1276 { "dissimilarity index ", gitdiff_dissimilarity
},
1277 { "index ", gitdiff_index
},
1278 { "", gitdiff_unrecognized
},
1282 len
= linelen(line
, size
);
1283 if (!len
|| line
[len
-1] != '\n')
1285 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
1286 const struct opentry
*p
= optable
+ i
;
1287 int oplen
= strlen(p
->str
);
1288 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
1290 if (p
->fn(line
+ oplen
, patch
) < 0)
1299 static int parse_num(const char *line
, unsigned long *p
)
1303 if (!isdigit(*line
))
1305 *p
= strtoul(line
, &ptr
, 10);
1309 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
1310 unsigned long *p1
, unsigned long *p2
)
1314 if (offset
< 0 || offset
>= len
)
1319 digits
= parse_num(line
, p1
);
1329 digits
= parse_num(line
+1, p2
);
1338 ex
= strlen(expect
);
1341 if (memcmp(line
, expect
, ex
))
1347 static void recount_diff(const char *line
, int size
, struct fragment
*fragment
)
1349 int oldlines
= 0, newlines
= 0, ret
= 0;
1352 warning("recount: ignore empty hunk");
1357 int len
= linelen(line
, size
);
1365 case ' ': case '\n':
1377 ret
= size
< 3 || prefixcmp(line
, "@@ ");
1380 ret
= size
< 5 || prefixcmp(line
, "diff ");
1387 warning(_("recount: unexpected line: %.*s"),
1388 (int)linelen(line
, size
), line
);
1393 fragment
->oldlines
= oldlines
;
1394 fragment
->newlines
= newlines
;
1398 * Parse a unified diff fragment header of the
1399 * form "@@ -a,b +c,d @@"
1401 static int parse_fragment_header(const char *line
, int len
, struct fragment
*fragment
)
1405 if (!len
|| line
[len
-1] != '\n')
1408 /* Figure out the number of lines in a fragment */
1409 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
1410 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
1415 static int find_header(const char *line
, unsigned long size
, int *hdrsize
, struct patch
*patch
)
1417 unsigned long offset
, len
;
1419 patch
->is_toplevel_relative
= 0;
1420 patch
->is_rename
= patch
->is_copy
= 0;
1421 patch
->is_new
= patch
->is_delete
= -1;
1422 patch
->old_mode
= patch
->new_mode
= 0;
1423 patch
->old_name
= patch
->new_name
= NULL
;
1424 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1425 unsigned long nextlen
;
1427 len
= linelen(line
, size
);
1431 /* Testing this early allows us to take a few shortcuts.. */
1436 * Make sure we don't find any unconnected patch fragments.
1437 * That's a sign that we didn't find a header, and that a
1438 * patch has become corrupted/broken up.
1440 if (!memcmp("@@ -", line
, 4)) {
1441 struct fragment dummy
;
1442 if (parse_fragment_header(line
, len
, &dummy
) < 0)
1444 die(_("patch fragment without header at line %d: %.*s"),
1445 linenr
, (int)len
-1, line
);
1452 * Git patch? It might not have a real patch, just a rename
1453 * or mode change, so we handle that specially
1455 if (!memcmp("diff --git ", line
, 11)) {
1456 int git_hdr_len
= parse_git_header(line
, len
, size
, patch
);
1457 if (git_hdr_len
<= len
)
1459 if (!patch
->old_name
&& !patch
->new_name
) {
1460 if (!patch
->def_name
)
1461 die(Q_("git diff header lacks filename information when removing "
1462 "%d leading pathname component (line %d)",
1463 "git diff header lacks filename information when removing "
1464 "%d leading pathname components (line %d)",
1467 patch
->old_name
= xstrdup(patch
->def_name
);
1468 patch
->new_name
= xstrdup(patch
->def_name
);
1470 if (!patch
->is_delete
&& !patch
->new_name
)
1471 die("git diff header lacks filename information "
1472 "(line %d)", linenr
);
1473 patch
->is_toplevel_relative
= 1;
1474 *hdrsize
= git_hdr_len
;
1478 /* --- followed by +++ ? */
1479 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
1483 * We only accept unified patches, so we want it to
1484 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1485 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1487 nextlen
= linelen(line
+ len
, size
- len
);
1488 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
1491 /* Ok, we'll consider it a patch */
1492 parse_traditional_patch(line
, line
+len
, patch
);
1493 *hdrsize
= len
+ nextlen
;
1500 static void record_ws_error(unsigned result
, const char *line
, int len
, int linenr
)
1508 if (squelch_whitespace_errors
&&
1509 squelch_whitespace_errors
< whitespace_error
)
1512 err
= whitespace_error_string(result
);
1513 fprintf(stderr
, "%s:%d: %s.\n%.*s\n",
1514 patch_input_file
, linenr
, err
, len
, line
);
1518 static void check_whitespace(const char *line
, int len
, unsigned ws_rule
)
1520 unsigned result
= ws_check(line
+ 1, len
- 1, ws_rule
);
1522 record_ws_error(result
, line
+ 1, len
- 2, linenr
);
1526 * Parse a unified diff. Note that this really needs to parse each
1527 * fragment separately, since the only way to know the difference
1528 * between a "---" that is part of a patch, and a "---" that starts
1529 * the next patch is to look at the line counts..
1531 static int parse_fragment(const char *line
, unsigned long size
,
1532 struct patch
*patch
, struct fragment
*fragment
)
1535 int len
= linelen(line
, size
), offset
;
1536 unsigned long oldlines
, newlines
;
1537 unsigned long leading
, trailing
;
1539 offset
= parse_fragment_header(line
, len
, fragment
);
1542 if (offset
> 0 && patch
->recount
)
1543 recount_diff(line
+ offset
, size
- offset
, fragment
);
1544 oldlines
= fragment
->oldlines
;
1545 newlines
= fragment
->newlines
;
1549 /* Parse the thing.. */
1553 added
= deleted
= 0;
1556 offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1557 if (!oldlines
&& !newlines
)
1559 len
= linelen(line
, size
);
1560 if (!len
|| line
[len
-1] != '\n')
1565 case '\n': /* newer GNU diff, an empty context line */
1569 if (!deleted
&& !added
)
1574 if (apply_in_reverse
&&
1575 ws_error_action
!= nowarn_ws_error
)
1576 check_whitespace(line
, len
, patch
->ws_rule
);
1582 if (!apply_in_reverse
&&
1583 ws_error_action
!= nowarn_ws_error
)
1584 check_whitespace(line
, len
, patch
->ws_rule
);
1591 * We allow "\ No newline at end of file". Depending
1592 * on locale settings when the patch was produced we
1593 * don't know what this line looks like. The only
1594 * thing we do know is that it begins with "\ ".
1595 * Checking for 12 is just for sanity check -- any
1596 * l10n of "\ No newline..." is at least that long.
1599 if (len
< 12 || memcmp(line
, "\\ ", 2))
1604 if (oldlines
|| newlines
)
1606 fragment
->leading
= leading
;
1607 fragment
->trailing
= trailing
;
1610 * If a fragment ends with an incomplete line, we failed to include
1611 * it in the above loop because we hit oldlines == newlines == 0
1614 if (12 < size
&& !memcmp(line
, "\\ ", 2))
1615 offset
+= linelen(line
, size
);
1617 patch
->lines_added
+= added
;
1618 patch
->lines_deleted
+= deleted
;
1620 if (0 < patch
->is_new
&& oldlines
)
1621 return error(_("new file depends on old contents"));
1622 if (0 < patch
->is_delete
&& newlines
)
1623 return error(_("deleted file still has contents"));
1628 * We have seen "diff --git a/... b/..." header (or a traditional patch
1629 * header). Read hunks that belong to this patch into fragments and hang
1630 * them to the given patch structure.
1632 * The (fragment->patch, fragment->size) pair points into the memory given
1633 * by the caller, not a copy, when we return.
1635 static int parse_single_patch(const char *line
, unsigned long size
, struct patch
*patch
)
1637 unsigned long offset
= 0;
1638 unsigned long oldlines
= 0, newlines
= 0, context
= 0;
1639 struct fragment
**fragp
= &patch
->fragments
;
1641 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
1642 struct fragment
*fragment
;
1645 fragment
= xcalloc(1, sizeof(*fragment
));
1646 fragment
->linenr
= linenr
;
1647 len
= parse_fragment(line
, size
, patch
, fragment
);
1649 die(_("corrupt patch at line %d"), linenr
);
1650 fragment
->patch
= line
;
1651 fragment
->size
= len
;
1652 oldlines
+= fragment
->oldlines
;
1653 newlines
+= fragment
->newlines
;
1654 context
+= fragment
->leading
+ fragment
->trailing
;
1657 fragp
= &fragment
->next
;
1665 * If something was removed (i.e. we have old-lines) it cannot
1666 * be creation, and if something was added it cannot be
1667 * deletion. However, the reverse is not true; --unified=0
1668 * patches that only add are not necessarily creation even
1669 * though they do not have any old lines, and ones that only
1670 * delete are not necessarily deletion.
1672 * Unfortunately, a real creation/deletion patch do _not_ have
1673 * any context line by definition, so we cannot safely tell it
1674 * apart with --unified=0 insanity. At least if the patch has
1675 * more than one hunk it is not creation or deletion.
1677 if (patch
->is_new
< 0 &&
1678 (oldlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1680 if (patch
->is_delete
< 0 &&
1681 (newlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1682 patch
->is_delete
= 0;
1684 if (0 < patch
->is_new
&& oldlines
)
1685 die(_("new file %s depends on old contents"), patch
->new_name
);
1686 if (0 < patch
->is_delete
&& newlines
)
1687 die(_("deleted file %s still has contents"), patch
->old_name
);
1688 if (!patch
->is_delete
&& !newlines
&& context
)
1691 "file %s becomes empty but is not deleted"),
1697 static inline int metadata_changes(struct patch
*patch
)
1699 return patch
->is_rename
> 0 ||
1700 patch
->is_copy
> 0 ||
1701 patch
->is_new
> 0 ||
1703 (patch
->old_mode
&& patch
->new_mode
&&
1704 patch
->old_mode
!= patch
->new_mode
);
1707 static char *inflate_it(const void *data
, unsigned long size
,
1708 unsigned long inflated_size
)
1714 memset(&stream
, 0, sizeof(stream
));
1716 stream
.next_in
= (unsigned char *)data
;
1717 stream
.avail_in
= size
;
1718 stream
.next_out
= out
= xmalloc(inflated_size
);
1719 stream
.avail_out
= inflated_size
;
1720 git_inflate_init(&stream
);
1721 st
= git_inflate(&stream
, Z_FINISH
);
1722 git_inflate_end(&stream
);
1723 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1731 * Read a binary hunk and return a new fragment; fragment->patch
1732 * points at an allocated memory that the caller must free, so
1733 * it is marked as "->free_patch = 1".
1735 static struct fragment
*parse_binary_hunk(char **buf_p
,
1736 unsigned long *sz_p
,
1741 * Expect a line that begins with binary patch method ("literal"
1742 * or "delta"), followed by the length of data before deflating.
1743 * a sequence of 'length-byte' followed by base-85 encoded data
1744 * should follow, terminated by a newline.
1746 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1747 * and we would limit the patch line to 66 characters,
1748 * so one line can fit up to 13 groups that would decode
1749 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1750 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1753 unsigned long size
= *sz_p
;
1754 char *buffer
= *buf_p
;
1756 unsigned long origlen
;
1759 struct fragment
*frag
;
1761 llen
= linelen(buffer
, size
);
1766 if (!prefixcmp(buffer
, "delta ")) {
1767 patch_method
= BINARY_DELTA_DEFLATED
;
1768 origlen
= strtoul(buffer
+ 6, NULL
, 10);
1770 else if (!prefixcmp(buffer
, "literal ")) {
1771 patch_method
= BINARY_LITERAL_DEFLATED
;
1772 origlen
= strtoul(buffer
+ 8, NULL
, 10);
1780 int byte_length
, max_byte_length
, newsize
;
1781 llen
= linelen(buffer
, size
);
1785 /* consume the blank line */
1791 * Minimum line is "A00000\n" which is 7-byte long,
1792 * and the line length must be multiple of 5 plus 2.
1794 if ((llen
< 7) || (llen
-2) % 5)
1796 max_byte_length
= (llen
- 2) / 5 * 4;
1797 byte_length
= *buffer
;
1798 if ('A' <= byte_length
&& byte_length
<= 'Z')
1799 byte_length
= byte_length
- 'A' + 1;
1800 else if ('a' <= byte_length
&& byte_length
<= 'z')
1801 byte_length
= byte_length
- 'a' + 27;
1804 /* if the input length was not multiple of 4, we would
1805 * have filler at the end but the filler should never
1808 if (max_byte_length
< byte_length
||
1809 byte_length
<= max_byte_length
- 4)
1811 newsize
= hunk_size
+ byte_length
;
1812 data
= xrealloc(data
, newsize
);
1813 if (decode_85(data
+ hunk_size
, buffer
+ 1, byte_length
))
1815 hunk_size
= newsize
;
1820 frag
= xcalloc(1, sizeof(*frag
));
1821 frag
->patch
= inflate_it(data
, hunk_size
, origlen
);
1822 frag
->free_patch
= 1;
1826 frag
->size
= origlen
;
1830 frag
->binary_patch_method
= patch_method
;
1836 error(_("corrupt binary patch at line %d: %.*s"),
1837 linenr
-1, llen
-1, buffer
);
1841 static int parse_binary(char *buffer
, unsigned long size
, struct patch
*patch
)
1844 * We have read "GIT binary patch\n"; what follows is a line
1845 * that says the patch method (currently, either "literal" or
1846 * "delta") and the length of data before deflating; a
1847 * sequence of 'length-byte' followed by base-85 encoded data
1850 * When a binary patch is reversible, there is another binary
1851 * hunk in the same format, starting with patch method (either
1852 * "literal" or "delta") with the length of data, and a sequence
1853 * of length-byte + base-85 encoded data, terminated with another
1854 * empty line. This data, when applied to the postimage, produces
1857 struct fragment
*forward
;
1858 struct fragment
*reverse
;
1862 forward
= parse_binary_hunk(&buffer
, &size
, &status
, &used
);
1863 if (!forward
&& !status
)
1864 /* there has to be one hunk (forward hunk) */
1865 return error(_("unrecognized binary patch at line %d"), linenr
-1);
1867 /* otherwise we already gave an error message */
1870 reverse
= parse_binary_hunk(&buffer
, &size
, &status
, &used_1
);
1875 * Not having reverse hunk is not an error, but having
1876 * a corrupt reverse hunk is.
1878 free((void*) forward
->patch
);
1882 forward
->next
= reverse
;
1883 patch
->fragments
= forward
;
1884 patch
->is_binary
= 1;
1889 * Read the patch text in "buffer" taht extends for "size" bytes; stop
1890 * reading after seeing a single patch (i.e. changes to a single file).
1891 * Create fragments (i.e. patch hunks) and hang them to the given patch.
1892 * Return the number of bytes consumed, so that the caller can call us
1893 * again for the next patch.
1895 static int parse_chunk(char *buffer
, unsigned long size
, struct patch
*patch
)
1897 int hdrsize
, patchsize
;
1898 int offset
= find_header(buffer
, size
, &hdrsize
, patch
);
1903 patch
->ws_rule
= whitespace_rule(patch
->new_name
1907 patchsize
= parse_single_patch(buffer
+ offset
+ hdrsize
,
1908 size
- offset
- hdrsize
, patch
);
1911 static const char *binhdr
[] = {
1916 static const char git_binary
[] = "GIT binary patch\n";
1918 int hd
= hdrsize
+ offset
;
1919 unsigned long llen
= linelen(buffer
+ hd
, size
- hd
);
1921 if (llen
== sizeof(git_binary
) - 1 &&
1922 !memcmp(git_binary
, buffer
+ hd
, llen
)) {
1925 used
= parse_binary(buffer
+ hd
+ llen
,
1926 size
- hd
- llen
, patch
);
1928 patchsize
= used
+ llen
;
1932 else if (!memcmp(" differ\n", buffer
+ hd
+ llen
- 8, 8)) {
1933 for (i
= 0; binhdr
[i
]; i
++) {
1934 int len
= strlen(binhdr
[i
]);
1935 if (len
< size
- hd
&&
1936 !memcmp(binhdr
[i
], buffer
+ hd
, len
)) {
1938 patch
->is_binary
= 1;
1945 /* Empty patch cannot be applied if it is a text patch
1946 * without metadata change. A binary patch appears
1949 if ((apply
|| check
) &&
1950 (!patch
->is_binary
&& !metadata_changes(patch
)))
1951 die(_("patch with only garbage at line %d"), linenr
);
1954 return offset
+ hdrsize
+ patchsize
;
1957 #define swap(a,b) myswap((a),(b),sizeof(a))
1959 #define myswap(a, b, size) do { \
1960 unsigned char mytmp[size]; \
1961 memcpy(mytmp, &a, size); \
1962 memcpy(&a, &b, size); \
1963 memcpy(&b, mytmp, size); \
1966 static void reverse_patches(struct patch
*p
)
1968 for (; p
; p
= p
->next
) {
1969 struct fragment
*frag
= p
->fragments
;
1971 swap(p
->new_name
, p
->old_name
);
1972 swap(p
->new_mode
, p
->old_mode
);
1973 swap(p
->is_new
, p
->is_delete
);
1974 swap(p
->lines_added
, p
->lines_deleted
);
1975 swap(p
->old_sha1_prefix
, p
->new_sha1_prefix
);
1977 for (; frag
; frag
= frag
->next
) {
1978 swap(frag
->newpos
, frag
->oldpos
);
1979 swap(frag
->newlines
, frag
->oldlines
);
1984 static const char pluses
[] =
1985 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1986 static const char minuses
[]=
1987 "----------------------------------------------------------------------";
1989 static void show_stats(struct patch
*patch
)
1991 struct strbuf qname
= STRBUF_INIT
;
1992 char *cp
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
1995 quote_c_style(cp
, &qname
, NULL
, 0);
1998 * "scale" the filename
2004 if (qname
.len
> max
) {
2005 cp
= strchr(qname
.buf
+ qname
.len
+ 3 - max
, '/');
2007 cp
= qname
.buf
+ qname
.len
+ 3 - max
;
2008 strbuf_splice(&qname
, 0, cp
- qname
.buf
, "...", 3);
2011 if (patch
->is_binary
) {
2012 printf(" %-*s | Bin\n", max
, qname
.buf
);
2013 strbuf_release(&qname
);
2017 printf(" %-*s |", max
, qname
.buf
);
2018 strbuf_release(&qname
);
2021 * scale the add/delete
2023 max
= max
+ max_change
> 70 ? 70 - max
: max_change
;
2024 add
= patch
->lines_added
;
2025 del
= patch
->lines_deleted
;
2027 if (max_change
> 0) {
2028 int total
= ((add
+ del
) * max
+ max_change
/ 2) / max_change
;
2029 add
= (add
* max
+ max_change
/ 2) / max_change
;
2032 printf("%5d %.*s%.*s\n", patch
->lines_added
+ patch
->lines_deleted
,
2033 add
, pluses
, del
, minuses
);
2036 static int read_old_data(struct stat
*st
, const char *path
, struct strbuf
*buf
)
2038 switch (st
->st_mode
& S_IFMT
) {
2040 if (strbuf_readlink(buf
, path
, st
->st_size
) < 0)
2041 return error(_("unable to read symlink %s"), path
);
2044 if (strbuf_read_file(buf
, path
, st
->st_size
) != st
->st_size
)
2045 return error(_("unable to open or read %s"), path
);
2046 convert_to_git(path
, buf
->buf
, buf
->len
, buf
, 0);
2054 * Update the preimage, and the common lines in postimage,
2055 * from buffer buf of length len. If postlen is 0 the postimage
2056 * is updated in place, otherwise it's updated on a new buffer
2060 static void update_pre_post_images(struct image
*preimage
,
2061 struct image
*postimage
,
2063 size_t len
, size_t postlen
)
2066 char *new, *old
, *fixed
;
2067 struct image fixed_preimage
;
2070 * Update the preimage with whitespace fixes. Note that we
2071 * are not losing preimage->buf -- apply_one_fragment() will
2074 prepare_image(&fixed_preimage
, buf
, len
, 1);
2075 assert(fixed_preimage
.nr
== preimage
->nr
);
2076 for (i
= 0; i
< preimage
->nr
; i
++)
2077 fixed_preimage
.line
[i
].flag
= preimage
->line
[i
].flag
;
2078 free(preimage
->line_allocated
);
2079 *preimage
= fixed_preimage
;
2082 * Adjust the common context lines in postimage. This can be
2083 * done in-place when we are just doing whitespace fixing,
2084 * which does not make the string grow, but needs a new buffer
2085 * when ignoring whitespace causes the update, since in this case
2086 * we could have e.g. tabs converted to multiple spaces.
2087 * We trust the caller to tell us if the update can be done
2088 * in place (postlen==0) or not.
2090 old
= postimage
->buf
;
2092 new = postimage
->buf
= xmalloc(postlen
);
2095 fixed
= preimage
->buf
;
2096 for (i
= ctx
= 0; i
< postimage
->nr
; i
++) {
2097 size_t len
= postimage
->line
[i
].len
;
2098 if (!(postimage
->line
[i
].flag
& LINE_COMMON
)) {
2099 /* an added line -- no counterparts in preimage */
2100 memmove(new, old
, len
);
2106 /* a common context -- skip it in the original postimage */
2109 /* and find the corresponding one in the fixed preimage */
2110 while (ctx
< preimage
->nr
&&
2111 !(preimage
->line
[ctx
].flag
& LINE_COMMON
)) {
2112 fixed
+= preimage
->line
[ctx
].len
;
2115 if (preimage
->nr
<= ctx
)
2118 /* and copy it in, while fixing the line length */
2119 len
= preimage
->line
[ctx
].len
;
2120 memcpy(new, fixed
, len
);
2123 postimage
->line
[i
].len
= len
;
2127 /* Fix the length of the whole thing */
2128 postimage
->len
= new - postimage
->buf
;
2131 static int match_fragment(struct image
*img
,
2132 struct image
*preimage
,
2133 struct image
*postimage
,
2137 int match_beginning
, int match_end
)
2140 char *fixed_buf
, *buf
, *orig
, *target
;
2141 struct strbuf fixed
;
2145 if (preimage
->nr
+ try_lno
<= img
->nr
) {
2147 * The hunk falls within the boundaries of img.
2149 preimage_limit
= preimage
->nr
;
2150 if (match_end
&& (preimage
->nr
+ try_lno
!= img
->nr
))
2152 } else if (ws_error_action
== correct_ws_error
&&
2153 (ws_rule
& WS_BLANK_AT_EOF
)) {
2155 * This hunk extends beyond the end of img, and we are
2156 * removing blank lines at the end of the file. This
2157 * many lines from the beginning of the preimage must
2158 * match with img, and the remainder of the preimage
2161 preimage_limit
= img
->nr
- try_lno
;
2164 * The hunk extends beyond the end of the img and
2165 * we are not removing blanks at the end, so we
2166 * should reject the hunk at this position.
2171 if (match_beginning
&& try_lno
)
2174 /* Quick hash check */
2175 for (i
= 0; i
< preimage_limit
; i
++)
2176 if ((img
->line
[try_lno
+ i
].flag
& LINE_PATCHED
) ||
2177 (preimage
->line
[i
].hash
!= img
->line
[try_lno
+ i
].hash
))
2180 if (preimage_limit
== preimage
->nr
) {
2182 * Do we have an exact match? If we were told to match
2183 * at the end, size must be exactly at try+fragsize,
2184 * otherwise try+fragsize must be still within the preimage,
2185 * and either case, the old piece should match the preimage
2189 ? (try + preimage
->len
== img
->len
)
2190 : (try + preimage
->len
<= img
->len
)) &&
2191 !memcmp(img
->buf
+ try, preimage
->buf
, preimage
->len
))
2195 * The preimage extends beyond the end of img, so
2196 * there cannot be an exact match.
2198 * There must be one non-blank context line that match
2199 * a line before the end of img.
2203 buf
= preimage
->buf
;
2205 for (i
= 0; i
< preimage_limit
; i
++)
2206 buf_end
+= preimage
->line
[i
].len
;
2208 for ( ; buf
< buf_end
; buf
++)
2216 * No exact match. If we are ignoring whitespace, run a line-by-line
2217 * fuzzy matching. We collect all the line length information because
2218 * we need it to adjust whitespace if we match.
2220 if (ws_ignore_action
== ignore_ws_change
) {
2223 size_t postlen
= postimage
->len
;
2227 for (i
= 0; i
< preimage_limit
; i
++) {
2228 size_t prelen
= preimage
->line
[i
].len
;
2229 size_t imglen
= img
->line
[try_lno
+i
].len
;
2231 if (!fuzzy_matchlines(img
->buf
+ try + imgoff
, imglen
,
2232 preimage
->buf
+ preoff
, prelen
))
2234 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2235 postlen
+= imglen
- prelen
;
2241 * Ok, the preimage matches with whitespace fuzz.
2243 * imgoff now holds the true length of the target that
2244 * matches the preimage before the end of the file.
2246 * Count the number of characters in the preimage that fall
2247 * beyond the end of the file and make sure that all of them
2248 * are whitespace characters. (This can only happen if
2249 * we are removing blank lines at the end of the file.)
2251 buf
= preimage_eof
= preimage
->buf
+ preoff
;
2252 for ( ; i
< preimage
->nr
; i
++)
2253 preoff
+= preimage
->line
[i
].len
;
2254 preimage_end
= preimage
->buf
+ preoff
;
2255 for ( ; buf
< preimage_end
; buf
++)
2260 * Update the preimage and the common postimage context
2261 * lines to use the same whitespace as the target.
2262 * If whitespace is missing in the target (i.e.
2263 * if the preimage extends beyond the end of the file),
2264 * use the whitespace from the preimage.
2266 extra_chars
= preimage_end
- preimage_eof
;
2267 strbuf_init(&fixed
, imgoff
+ extra_chars
);
2268 strbuf_add(&fixed
, img
->buf
+ try, imgoff
);
2269 strbuf_add(&fixed
, preimage_eof
, extra_chars
);
2270 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2271 update_pre_post_images(preimage
, postimage
,
2272 fixed_buf
, fixed_len
, postlen
);
2276 if (ws_error_action
!= correct_ws_error
)
2280 * The hunk does not apply byte-by-byte, but the hash says
2281 * it might with whitespace fuzz. We haven't been asked to
2282 * ignore whitespace, we were asked to correct whitespace
2283 * errors, so let's try matching after whitespace correction.
2285 * The preimage may extend beyond the end of the file,
2286 * but in this loop we will only handle the part of the
2287 * preimage that falls within the file.
2289 strbuf_init(&fixed
, preimage
->len
+ 1);
2290 orig
= preimage
->buf
;
2291 target
= img
->buf
+ try;
2292 for (i
= 0; i
< preimage_limit
; i
++) {
2293 size_t oldlen
= preimage
->line
[i
].len
;
2294 size_t tgtlen
= img
->line
[try_lno
+ i
].len
;
2295 size_t fixstart
= fixed
.len
;
2296 struct strbuf tgtfix
;
2299 /* Try fixing the line in the preimage */
2300 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2302 /* Try fixing the line in the target */
2303 strbuf_init(&tgtfix
, tgtlen
);
2304 ws_fix_copy(&tgtfix
, target
, tgtlen
, ws_rule
, NULL
);
2307 * If they match, either the preimage was based on
2308 * a version before our tree fixed whitespace breakage,
2309 * or we are lacking a whitespace-fix patch the tree
2310 * the preimage was based on already had (i.e. target
2311 * has whitespace breakage, the preimage doesn't).
2312 * In either case, we are fixing the whitespace breakages
2313 * so we might as well take the fix together with their
2316 match
= (tgtfix
.len
== fixed
.len
- fixstart
&&
2317 !memcmp(tgtfix
.buf
, fixed
.buf
+ fixstart
,
2318 fixed
.len
- fixstart
));
2320 strbuf_release(&tgtfix
);
2330 * Now handle the lines in the preimage that falls beyond the
2331 * end of the file (if any). They will only match if they are
2332 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2335 for ( ; i
< preimage
->nr
; i
++) {
2336 size_t fixstart
= fixed
.len
; /* start of the fixed preimage */
2337 size_t oldlen
= preimage
->line
[i
].len
;
2340 /* Try fixing the line in the preimage */
2341 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2343 for (j
= fixstart
; j
< fixed
.len
; j
++)
2344 if (!isspace(fixed
.buf
[j
]))
2351 * Yes, the preimage is based on an older version that still
2352 * has whitespace breakages unfixed, and fixing them makes the
2353 * hunk match. Update the context lines in the postimage.
2355 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2356 update_pre_post_images(preimage
, postimage
,
2357 fixed_buf
, fixed_len
, 0);
2361 strbuf_release(&fixed
);
2365 static int find_pos(struct image
*img
,
2366 struct image
*preimage
,
2367 struct image
*postimage
,
2370 int match_beginning
, int match_end
)
2373 unsigned long backwards
, forwards
, try;
2374 int backwards_lno
, forwards_lno
, try_lno
;
2377 * If match_beginning or match_end is specified, there is no
2378 * point starting from a wrong line that will never match and
2379 * wander around and wait for a match at the specified end.
2381 if (match_beginning
)
2384 line
= img
->nr
- preimage
->nr
;
2387 * Because the comparison is unsigned, the following test
2388 * will also take care of a negative line number that can
2389 * result when match_end and preimage is larger than the target.
2391 if ((size_t) line
> img
->nr
)
2395 for (i
= 0; i
< line
; i
++)
2396 try += img
->line
[i
].len
;
2399 * There's probably some smart way to do this, but I'll leave
2400 * that to the smart and beautiful people. I'm simple and stupid.
2403 backwards_lno
= line
;
2405 forwards_lno
= line
;
2408 for (i
= 0; ; i
++) {
2409 if (match_fragment(img
, preimage
, postimage
,
2410 try, try_lno
, ws_rule
,
2411 match_beginning
, match_end
))
2415 if (backwards_lno
== 0 && forwards_lno
== img
->nr
)
2419 if (backwards_lno
== 0) {
2424 backwards
-= img
->line
[backwards_lno
].len
;
2426 try_lno
= backwards_lno
;
2428 if (forwards_lno
== img
->nr
) {
2432 forwards
+= img
->line
[forwards_lno
].len
;
2435 try_lno
= forwards_lno
;
2442 static void remove_first_line(struct image
*img
)
2444 img
->buf
+= img
->line
[0].len
;
2445 img
->len
-= img
->line
[0].len
;
2450 static void remove_last_line(struct image
*img
)
2452 img
->len
-= img
->line
[--img
->nr
].len
;
2456 * The change from "preimage" and "postimage" has been found to
2457 * apply at applied_pos (counts in line numbers) in "img".
2458 * Update "img" to remove "preimage" and replace it with "postimage".
2460 static void update_image(struct image
*img
,
2462 struct image
*preimage
,
2463 struct image
*postimage
)
2466 * remove the copy of preimage at offset in img
2467 * and replace it with postimage
2470 size_t remove_count
, insert_count
, applied_at
= 0;
2475 * If we are removing blank lines at the end of img,
2476 * the preimage may extend beyond the end.
2477 * If that is the case, we must be careful only to
2478 * remove the part of the preimage that falls within
2479 * the boundaries of img. Initialize preimage_limit
2480 * to the number of lines in the preimage that falls
2481 * within the boundaries.
2483 preimage_limit
= preimage
->nr
;
2484 if (preimage_limit
> img
->nr
- applied_pos
)
2485 preimage_limit
= img
->nr
- applied_pos
;
2487 for (i
= 0; i
< applied_pos
; i
++)
2488 applied_at
+= img
->line
[i
].len
;
2491 for (i
= 0; i
< preimage_limit
; i
++)
2492 remove_count
+= img
->line
[applied_pos
+ i
].len
;
2493 insert_count
= postimage
->len
;
2495 /* Adjust the contents */
2496 result
= xmalloc(img
->len
+ insert_count
- remove_count
+ 1);
2497 memcpy(result
, img
->buf
, applied_at
);
2498 memcpy(result
+ applied_at
, postimage
->buf
, postimage
->len
);
2499 memcpy(result
+ applied_at
+ postimage
->len
,
2500 img
->buf
+ (applied_at
+ remove_count
),
2501 img
->len
- (applied_at
+ remove_count
));
2504 img
->len
+= insert_count
- remove_count
;
2505 result
[img
->len
] = '\0';
2507 /* Adjust the line table */
2508 nr
= img
->nr
+ postimage
->nr
- preimage_limit
;
2509 if (preimage_limit
< postimage
->nr
) {
2511 * NOTE: this knows that we never call remove_first_line()
2512 * on anything other than pre/post image.
2514 img
->line
= xrealloc(img
->line
, nr
* sizeof(*img
->line
));
2515 img
->line_allocated
= img
->line
;
2517 if (preimage_limit
!= postimage
->nr
)
2518 memmove(img
->line
+ applied_pos
+ postimage
->nr
,
2519 img
->line
+ applied_pos
+ preimage_limit
,
2520 (img
->nr
- (applied_pos
+ preimage_limit
)) *
2521 sizeof(*img
->line
));
2522 memcpy(img
->line
+ applied_pos
,
2524 postimage
->nr
* sizeof(*img
->line
));
2526 for (i
= 0; i
< postimage
->nr
; i
++)
2527 img
->line
[applied_pos
+ i
].flag
|= LINE_PATCHED
;
2532 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2533 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2534 * replace the part of "img" with "postimage" text.
2536 static int apply_one_fragment(struct image
*img
, struct fragment
*frag
,
2537 int inaccurate_eof
, unsigned ws_rule
,
2540 int match_beginning
, match_end
;
2541 const char *patch
= frag
->patch
;
2542 int size
= frag
->size
;
2543 char *old
, *oldlines
;
2544 struct strbuf newlines
;
2545 int new_blank_lines_at_end
= 0;
2546 int found_new_blank_lines_at_end
= 0;
2547 int hunk_linenr
= frag
->linenr
;
2548 unsigned long leading
, trailing
;
2549 int pos
, applied_pos
;
2550 struct image preimage
;
2551 struct image postimage
;
2553 memset(&preimage
, 0, sizeof(preimage
));
2554 memset(&postimage
, 0, sizeof(postimage
));
2555 oldlines
= xmalloc(size
);
2556 strbuf_init(&newlines
, size
);
2561 int len
= linelen(patch
, size
);
2563 int added_blank_line
= 0;
2564 int is_blank_context
= 0;
2571 * "plen" is how much of the line we should use for
2572 * the actual patch data. Normally we just remove the
2573 * first character on the line, but if the line is
2574 * followed by "\ No newline", then we also remove the
2575 * last one (which is the newline, of course).
2578 if (len
< size
&& patch
[len
] == '\\')
2581 if (apply_in_reverse
) {
2584 else if (first
== '+')
2590 /* Newer GNU diff, empty context line */
2592 /* ... followed by '\No newline'; nothing */
2595 strbuf_addch(&newlines
, '\n');
2596 add_line_info(&preimage
, "\n", 1, LINE_COMMON
);
2597 add_line_info(&postimage
, "\n", 1, LINE_COMMON
);
2598 is_blank_context
= 1;
2601 if (plen
&& (ws_rule
& WS_BLANK_AT_EOF
) &&
2602 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2603 is_blank_context
= 1;
2605 memcpy(old
, patch
+ 1, plen
);
2606 add_line_info(&preimage
, old
, plen
,
2607 (first
== ' ' ? LINE_COMMON
: 0));
2611 /* Fall-through for ' ' */
2613 /* --no-add does not add new lines */
2614 if (first
== '+' && no_add
)
2617 start
= newlines
.len
;
2619 !whitespace_error
||
2620 ws_error_action
!= correct_ws_error
) {
2621 strbuf_add(&newlines
, patch
+ 1, plen
);
2624 ws_fix_copy(&newlines
, patch
+ 1, plen
, ws_rule
, &applied_after_fixing_ws
);
2626 add_line_info(&postimage
, newlines
.buf
+ start
, newlines
.len
- start
,
2627 (first
== '+' ? 0 : LINE_COMMON
));
2629 (ws_rule
& WS_BLANK_AT_EOF
) &&
2630 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2631 added_blank_line
= 1;
2633 case '@': case '\\':
2634 /* Ignore it, we already handled it */
2637 if (apply_verbosely
)
2638 error(_("invalid start of line: '%c'"), first
);
2641 if (added_blank_line
) {
2642 if (!new_blank_lines_at_end
)
2643 found_new_blank_lines_at_end
= hunk_linenr
;
2644 new_blank_lines_at_end
++;
2646 else if (is_blank_context
)
2649 new_blank_lines_at_end
= 0;
2654 if (inaccurate_eof
&&
2655 old
> oldlines
&& old
[-1] == '\n' &&
2656 newlines
.len
> 0 && newlines
.buf
[newlines
.len
- 1] == '\n') {
2658 strbuf_setlen(&newlines
, newlines
.len
- 1);
2661 leading
= frag
->leading
;
2662 trailing
= frag
->trailing
;
2665 * A hunk to change lines at the beginning would begin with
2667 * but we need to be careful. -U0 that inserts before the second
2668 * line also has this pattern.
2670 * And a hunk to add to an empty file would begin with
2673 * In other words, a hunk that is (frag->oldpos <= 1) with or
2674 * without leading context must match at the beginning.
2676 match_beginning
= (!frag
->oldpos
||
2677 (frag
->oldpos
== 1 && !unidiff_zero
));
2680 * A hunk without trailing lines must match at the end.
2681 * However, we simply cannot tell if a hunk must match end
2682 * from the lack of trailing lines if the patch was generated
2683 * with unidiff without any context.
2685 match_end
= !unidiff_zero
&& !trailing
;
2687 pos
= frag
->newpos
? (frag
->newpos
- 1) : 0;
2688 preimage
.buf
= oldlines
;
2689 preimage
.len
= old
- oldlines
;
2690 postimage
.buf
= newlines
.buf
;
2691 postimage
.len
= newlines
.len
;
2692 preimage
.line
= preimage
.line_allocated
;
2693 postimage
.line
= postimage
.line_allocated
;
2697 applied_pos
= find_pos(img
, &preimage
, &postimage
, pos
,
2698 ws_rule
, match_beginning
, match_end
);
2700 if (applied_pos
>= 0)
2703 /* Am I at my context limits? */
2704 if ((leading
<= p_context
) && (trailing
<= p_context
))
2706 if (match_beginning
|| match_end
) {
2707 match_beginning
= match_end
= 0;
2712 * Reduce the number of context lines; reduce both
2713 * leading and trailing if they are equal otherwise
2714 * just reduce the larger context.
2716 if (leading
>= trailing
) {
2717 remove_first_line(&preimage
);
2718 remove_first_line(&postimage
);
2722 if (trailing
> leading
) {
2723 remove_last_line(&preimage
);
2724 remove_last_line(&postimage
);
2729 if (applied_pos
>= 0) {
2730 if (new_blank_lines_at_end
&&
2731 preimage
.nr
+ applied_pos
>= img
->nr
&&
2732 (ws_rule
& WS_BLANK_AT_EOF
) &&
2733 ws_error_action
!= nowarn_ws_error
) {
2734 record_ws_error(WS_BLANK_AT_EOF
, "+", 1,
2735 found_new_blank_lines_at_end
);
2736 if (ws_error_action
== correct_ws_error
) {
2737 while (new_blank_lines_at_end
--)
2738 remove_last_line(&postimage
);
2741 * We would want to prevent write_out_results()
2742 * from taking place in apply_patch() that follows
2743 * the callchain led us here, which is:
2744 * apply_patch->check_patch_list->check_patch->
2745 * apply_data->apply_fragments->apply_one_fragment
2747 if (ws_error_action
== die_on_ws_error
)
2751 if (apply_verbosely
&& applied_pos
!= pos
) {
2752 int offset
= applied_pos
- pos
;
2753 if (apply_in_reverse
)
2754 offset
= 0 - offset
;
2756 Q_("Hunk #%d succeeded at %d (offset %d line).",
2757 "Hunk #%d succeeded at %d (offset %d lines).",
2759 nth_fragment
, applied_pos
+ 1, offset
);
2763 * Warn if it was necessary to reduce the number
2766 if ((leading
!= frag
->leading
) ||
2767 (trailing
!= frag
->trailing
))
2768 fprintf_ln(stderr
, _("Context reduced to (%ld/%ld)"
2769 " to apply fragment at %d"),
2770 leading
, trailing
, applied_pos
+1);
2771 update_image(img
, applied_pos
, &preimage
, &postimage
);
2773 if (apply_verbosely
)
2774 error(_("while searching for:\n%.*s"),
2775 (int)(old
- oldlines
), oldlines
);
2779 strbuf_release(&newlines
);
2780 free(preimage
.line_allocated
);
2781 free(postimage
.line_allocated
);
2783 return (applied_pos
< 0);
2786 static int apply_binary_fragment(struct image
*img
, struct patch
*patch
)
2788 struct fragment
*fragment
= patch
->fragments
;
2793 return error(_("missing binary patch data for '%s'"),
2798 /* Binary patch is irreversible without the optional second hunk */
2799 if (apply_in_reverse
) {
2800 if (!fragment
->next
)
2801 return error("cannot reverse-apply a binary patch "
2802 "without the reverse hunk to '%s'",
2804 ? patch
->new_name
: patch
->old_name
);
2805 fragment
= fragment
->next
;
2807 switch (fragment
->binary_patch_method
) {
2808 case BINARY_DELTA_DEFLATED
:
2809 dst
= patch_delta(img
->buf
, img
->len
, fragment
->patch
,
2810 fragment
->size
, &len
);
2817 case BINARY_LITERAL_DEFLATED
:
2819 img
->len
= fragment
->size
;
2820 img
->buf
= xmalloc(img
->len
+1);
2821 memcpy(img
->buf
, fragment
->patch
, img
->len
);
2822 img
->buf
[img
->len
] = '\0';
2829 * Replace "img" with the result of applying the binary patch.
2830 * The binary patch data itself in patch->fragment is still kept
2831 * but the preimage prepared by the caller in "img" is freed here
2832 * or in the helper function apply_binary_fragment() this calls.
2834 static int apply_binary(struct image
*img
, struct patch
*patch
)
2836 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
2837 unsigned char sha1
[20];
2840 * For safety, we require patch index line to contain
2841 * full 40-byte textual SHA1 for old and new, at least for now.
2843 if (strlen(patch
->old_sha1_prefix
) != 40 ||
2844 strlen(patch
->new_sha1_prefix
) != 40 ||
2845 get_sha1_hex(patch
->old_sha1_prefix
, sha1
) ||
2846 get_sha1_hex(patch
->new_sha1_prefix
, sha1
))
2847 return error("cannot apply binary patch to '%s' "
2848 "without full index line", name
);
2850 if (patch
->old_name
) {
2852 * See if the old one matches what the patch
2855 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
2856 if (strcmp(sha1_to_hex(sha1
), patch
->old_sha1_prefix
))
2857 return error("the patch applies to '%s' (%s), "
2858 "which does not match the "
2859 "current contents.",
2860 name
, sha1_to_hex(sha1
));
2863 /* Otherwise, the old one must be empty. */
2865 return error("the patch applies to an empty "
2866 "'%s' but it is not empty", name
);
2869 get_sha1_hex(patch
->new_sha1_prefix
, sha1
);
2870 if (is_null_sha1(sha1
)) {
2872 return 0; /* deletion patch */
2875 if (has_sha1_file(sha1
)) {
2876 /* We already have the postimage */
2877 enum object_type type
;
2881 result
= read_sha1_file(sha1
, &type
, &size
);
2883 return error("the necessary postimage %s for "
2884 "'%s' cannot be read",
2885 patch
->new_sha1_prefix
, name
);
2891 * We have verified buf matches the preimage;
2892 * apply the patch data to it, which is stored
2893 * in the patch->fragments->{patch,size}.
2895 if (apply_binary_fragment(img
, patch
))
2896 return error(_("binary patch does not apply to '%s'"),
2899 /* verify that the result matches */
2900 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
2901 if (strcmp(sha1_to_hex(sha1
), patch
->new_sha1_prefix
))
2902 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
2903 name
, patch
->new_sha1_prefix
, sha1_to_hex(sha1
));
2909 static int apply_fragments(struct image
*img
, struct patch
*patch
)
2911 struct fragment
*frag
= patch
->fragments
;
2912 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
2913 unsigned ws_rule
= patch
->ws_rule
;
2914 unsigned inaccurate_eof
= patch
->inaccurate_eof
;
2917 if (patch
->is_binary
)
2918 return apply_binary(img
, patch
);
2922 if (apply_one_fragment(img
, frag
, inaccurate_eof
, ws_rule
, nth
)) {
2923 error(_("patch failed: %s:%ld"), name
, frag
->oldpos
);
2924 if (!apply_with_reject
)
2933 static int read_blob_object(struct strbuf
*buf
, const unsigned char *sha1
, unsigned mode
)
2935 if (S_ISGITLINK(mode
)) {
2936 strbuf_grow(buf
, 100);
2937 strbuf_addf(buf
, "Subproject commit %s\n", sha1_to_hex(sha1
));
2939 enum object_type type
;
2943 result
= read_sha1_file(sha1
, &type
, &sz
);
2946 /* XXX read_sha1_file NUL-terminates */
2947 strbuf_attach(buf
, result
, sz
, sz
+ 1);
2952 static int read_file_or_gitlink(struct cache_entry
*ce
, struct strbuf
*buf
)
2956 return read_blob_object(buf
, ce
->sha1
, ce
->ce_mode
);
2959 static struct patch
*in_fn_table(const char *name
)
2961 struct string_list_item
*item
;
2966 item
= string_list_lookup(&fn_table
, name
);
2968 return (struct patch
*)item
->util
;
2974 * item->util in the filename table records the status of the path.
2975 * Usually it points at a patch (whose result records the contents
2976 * of it after applying it), but it could be PATH_WAS_DELETED for a
2977 * path that a previously applied patch has already removed, or
2978 * PATH_TO_BE_DELETED for a path that a later patch would remove.
2980 * The latter is needed to deal with a case where two paths A and B
2981 * are swapped by first renaming A to B and then renaming B to A;
2982 * moving A to B should not be prevented due to presense of B as we
2983 * will remove it in a later patch.
2985 #define PATH_TO_BE_DELETED ((struct patch *) -2)
2986 #define PATH_WAS_DELETED ((struct patch *) -1)
2988 static int to_be_deleted(struct patch
*patch
)
2990 return patch
== PATH_TO_BE_DELETED
;
2993 static int was_deleted(struct patch
*patch
)
2995 return patch
== PATH_WAS_DELETED
;
2998 static void add_to_fn_table(struct patch
*patch
)
3000 struct string_list_item
*item
;
3003 * Always add new_name unless patch is a deletion
3004 * This should cover the cases for normal diffs,
3005 * file creations and copies
3007 if (patch
->new_name
!= NULL
) {
3008 item
= string_list_insert(&fn_table
, patch
->new_name
);
3013 * store a failure on rename/deletion cases because
3014 * later chunks shouldn't patch old names
3016 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3017 item
= string_list_insert(&fn_table
, patch
->old_name
);
3018 item
->util
= PATH_WAS_DELETED
;
3022 static void prepare_fn_table(struct patch
*patch
)
3025 * store information about incoming file deletion
3028 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3029 struct string_list_item
*item
;
3030 item
= string_list_insert(&fn_table
, patch
->old_name
);
3031 item
->util
= PATH_TO_BE_DELETED
;
3033 patch
= patch
->next
;
3037 static int checkout_target(struct cache_entry
*ce
, struct stat
*st
)
3039 struct checkout costate
;
3041 memset(&costate
, 0, sizeof(costate
));
3042 costate
.base_dir
= "";
3043 costate
.refresh_cache
= 1;
3044 if (checkout_entry(ce
, &costate
, NULL
) || lstat(ce
->name
, st
))
3045 return error(_("cannot checkout %s"), ce
->name
);
3049 static struct patch
*previous_patch(struct patch
*patch
, int *gone
)
3051 struct patch
*previous
;
3054 if (patch
->is_copy
|| patch
->is_rename
)
3055 return NULL
; /* "git" patches do not depend on the order */
3057 previous
= in_fn_table(patch
->old_name
);
3061 if (to_be_deleted(previous
))
3062 return NULL
; /* the deletion hasn't happened yet */
3064 if (was_deleted(previous
))
3070 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3072 static int load_patch_target(struct strbuf
*buf
,
3073 struct cache_entry
*ce
,
3076 unsigned expected_mode
)
3079 if (read_file_or_gitlink(ce
, buf
))
3080 return error(_("read of %s failed"), name
);
3082 if (S_ISGITLINK(expected_mode
)) {
3084 return read_file_or_gitlink(ce
, buf
);
3086 return SUBMODULE_PATCH_WITHOUT_INDEX
;
3088 if (read_old_data(st
, name
, buf
))
3089 return error(_("read of %s failed"), name
);
3096 * We are about to apply "patch"; populate the "image" with the
3097 * current version we have, from the working tree or from the index,
3098 * depending on the situation e.g. --cached/--index. If we are
3099 * applying a non-git patch that incrementally updates the tree,
3100 * we read from the result of a previous diff.
3102 static int load_preimage(struct image
*image
,
3103 struct patch
*patch
, struct stat
*st
, struct cache_entry
*ce
)
3105 struct strbuf buf
= STRBUF_INIT
;
3108 struct patch
*previous
;
3111 previous
= previous_patch(patch
, &status
);
3113 return error(_("path %s has been renamed/deleted"),
3116 /* We have a patched copy in memory; use that. */
3117 strbuf_add(&buf
, previous
->result
, previous
->resultsize
);
3119 status
= load_patch_target(&buf
, ce
, st
,
3120 patch
->old_name
, patch
->old_mode
);
3123 else if (status
== SUBMODULE_PATCH_WITHOUT_INDEX
) {
3125 * There is no way to apply subproject
3126 * patch without looking at the index.
3127 * NEEDSWORK: shouldn't this be flagged
3130 free_fragment_list(patch
->fragments
);
3131 patch
->fragments
= NULL
;
3132 } else if (status
) {
3133 return error(_("read of %s failed"), patch
->old_name
);
3137 img
= strbuf_detach(&buf
, &len
);
3138 prepare_image(image
, img
, len
, !patch
->is_binary
);
3142 static int apply_data(struct patch
*patch
, struct stat
*st
, struct cache_entry
*ce
)
3146 if (load_preimage(&image
, patch
, st
, ce
) < 0)
3149 if (apply_fragments(&image
, patch
) < 0)
3150 return -1; /* note with --reject this succeeds. */
3151 patch
->result
= image
.buf
;
3152 patch
->resultsize
= image
.len
;
3153 add_to_fn_table(patch
);
3154 free(image
.line_allocated
);
3156 if (0 < patch
->is_delete
&& patch
->resultsize
)
3157 return error(_("removal patch leaves file contents"));
3162 static int verify_index_match(struct cache_entry
*ce
, struct stat
*st
)
3164 if (S_ISGITLINK(ce
->ce_mode
)) {
3165 if (!S_ISDIR(st
->st_mode
))
3169 return ce_match_stat(ce
, st
, CE_MATCH_IGNORE_VALID
|CE_MATCH_IGNORE_SKIP_WORKTREE
);
3173 * If "patch" that we are looking at modifies or deletes what we have,
3174 * we would want it not to lose any local modification we have, either
3175 * in the working tree or in the index.
3177 * This also decides if a non-git patch is a creation patch or a
3178 * modification to an existing empty file. We do not check the state
3179 * of the current tree for a creation patch in this function; the caller
3180 * check_patch() separately makes sure (and errors out otherwise) that
3181 * the path the patch creates does not exist in the current tree.
3183 static int check_preimage(struct patch
*patch
, struct cache_entry
**ce
, struct stat
*st
)
3185 const char *old_name
= patch
->old_name
;
3186 struct patch
*previous
= NULL
;
3187 int stat_ret
= 0, status
;
3188 unsigned st_mode
= 0;
3193 assert(patch
->is_new
<= 0);
3194 previous
= previous_patch(patch
, &status
);
3197 return error(_("path %s has been renamed/deleted"), old_name
);
3199 st_mode
= previous
->new_mode
;
3200 } else if (!cached
) {
3201 stat_ret
= lstat(old_name
, st
);
3202 if (stat_ret
&& errno
!= ENOENT
)
3203 return error(_("%s: %s"), old_name
, strerror(errno
));
3206 if (check_index
&& !previous
) {
3207 int pos
= cache_name_pos(old_name
, strlen(old_name
));
3209 if (patch
->is_new
< 0)
3211 return error(_("%s: does not exist in index"), old_name
);
3213 *ce
= active_cache
[pos
];
3215 if (checkout_target(*ce
, st
))
3218 if (!cached
&& verify_index_match(*ce
, st
))
3219 return error(_("%s: does not match index"), old_name
);
3221 st_mode
= (*ce
)->ce_mode
;
3222 } else if (stat_ret
< 0) {
3223 if (patch
->is_new
< 0)
3225 return error(_("%s: %s"), old_name
, strerror(errno
));
3228 if (!cached
&& !previous
)
3229 st_mode
= ce_mode_from_stat(*ce
, st
->st_mode
);
3231 if (patch
->is_new
< 0)
3233 if (!patch
->old_mode
)
3234 patch
->old_mode
= st_mode
;
3235 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
3236 return error(_("%s: wrong type"), old_name
);
3237 if (st_mode
!= patch
->old_mode
)
3238 warning(_("%s has type %o, expected %o"),
3239 old_name
, st_mode
, patch
->old_mode
);
3240 if (!patch
->new_mode
&& !patch
->is_delete
)
3241 patch
->new_mode
= st_mode
;
3246 patch
->is_delete
= 0;
3247 free(patch
->old_name
);
3248 patch
->old_name
= NULL
;
3252 static int check_to_create_blob(const char *new_name
, int ok_if_exists
)
3255 if (!lstat(new_name
, &nst
)) {
3256 if (S_ISDIR(nst
.st_mode
) || ok_if_exists
)
3259 * A leading component of new_name might be a symlink
3260 * that is going to be removed with this patch, but
3261 * still pointing at somewhere that has the path.
3262 * In such a case, path "new_name" does not exist as
3263 * far as git is concerned.
3265 if (has_symlink_leading_path(new_name
, strlen(new_name
)))
3268 return error(_("%s: already exists in working directory"), new_name
);
3270 else if ((errno
!= ENOENT
) && (errno
!= ENOTDIR
))
3271 return error("%s: %s", new_name
, strerror(errno
));
3276 * Check and apply the patch in-core; leave the result in patch->result
3277 * for the caller to write it out to the final destination.
3279 static int check_patch(struct patch
*patch
)
3282 const char *old_name
= patch
->old_name
;
3283 const char *new_name
= patch
->new_name
;
3284 const char *name
= old_name
? old_name
: new_name
;
3285 struct cache_entry
*ce
= NULL
;
3286 struct patch
*tpatch
;
3290 patch
->rejected
= 1; /* we will drop this after we succeed */
3292 status
= check_preimage(patch
, &ce
, &st
);
3295 old_name
= patch
->old_name
;
3298 * A type-change diff is always split into a patch to delete
3299 * old, immediately followed by a patch to create new (see
3300 * diff.c::run_diff()); in such a case it is Ok that the entry
3301 * to be deleted by the previous patch is still in the working
3302 * tree and in the index.
3304 * A patch to swap-rename between A and B would first rename A
3305 * to B and then rename B to A. While applying the first one,
3306 * the presense of B should not stop A from getting renamed to
3307 * B; ask to_be_deleted() about the later rename. Removal of
3308 * B and rename from A to B is handled the same way by asking
3311 if ((tpatch
= in_fn_table(new_name
)) &&
3312 (was_deleted(tpatch
) || to_be_deleted(tpatch
)))
3318 ((0 < patch
->is_new
) | (0 < patch
->is_rename
) | patch
->is_copy
)) {
3320 cache_name_pos(new_name
, strlen(new_name
)) >= 0 &&
3322 return error(_("%s: already exists in index"), new_name
);
3324 int err
= check_to_create_blob(new_name
, ok_if_exists
);
3328 if (!patch
->new_mode
) {
3329 if (0 < patch
->is_new
)
3330 patch
->new_mode
= S_IFREG
| 0644;
3332 patch
->new_mode
= patch
->old_mode
;
3336 if (new_name
&& old_name
) {
3337 int same
= !strcmp(old_name
, new_name
);
3338 if (!patch
->new_mode
)
3339 patch
->new_mode
= patch
->old_mode
;
3340 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
)
3341 return error(_("new mode (%o) of %s does not match old mode (%o)%s%s"),
3342 patch
->new_mode
, new_name
, patch
->old_mode
,
3343 same
? "" : " of ", same
? "" : old_name
);
3346 if (apply_data(patch
, &st
, ce
) < 0)
3347 return error(_("%s: patch does not apply"), name
);
3348 patch
->rejected
= 0;
3352 static int check_patch_list(struct patch
*patch
)
3356 prepare_fn_table(patch
);
3358 if (apply_verbosely
)
3359 say_patch_name(stderr
,
3360 _("Checking patch %s..."), patch
);
3361 err
|= check_patch(patch
);
3362 patch
= patch
->next
;
3367 /* This function tries to read the sha1 from the current index */
3368 static int get_current_sha1(const char *path
, unsigned char *sha1
)
3372 if (read_cache() < 0)
3374 pos
= cache_name_pos(path
, strlen(path
));
3377 hashcpy(sha1
, active_cache
[pos
]->sha1
);
3381 /* Build an index that contains the just the files needed for a 3way merge */
3382 static void build_fake_ancestor(struct patch
*list
, const char *filename
)
3384 struct patch
*patch
;
3385 struct index_state result
= { NULL
};
3388 /* Once we start supporting the reverse patch, it may be
3389 * worth showing the new sha1 prefix, but until then...
3391 for (patch
= list
; patch
; patch
= patch
->next
) {
3392 const unsigned char *sha1_ptr
;
3393 unsigned char sha1
[20];
3394 struct cache_entry
*ce
;
3397 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3398 if (0 < patch
->is_new
)
3400 else if (get_sha1(patch
->old_sha1_prefix
, sha1
))
3401 /* git diff has no index line for mode/type changes */
3402 if (!patch
->lines_added
&& !patch
->lines_deleted
) {
3403 if (get_current_sha1(patch
->old_name
, sha1
))
3404 die("mode change for %s, which is not "
3405 "in current HEAD", name
);
3408 die("sha1 information is lacking or useless "
3413 ce
= make_cache_entry(patch
->old_mode
, sha1_ptr
, name
, 0, 0);
3415 die(_("make_cache_entry failed for path '%s'"), name
);
3416 if (add_index_entry(&result
, ce
, ADD_CACHE_OK_TO_ADD
))
3417 die ("Could not add %s to temporary index", name
);
3420 fd
= open(filename
, O_WRONLY
| O_CREAT
, 0666);
3421 if (fd
< 0 || write_index(&result
, fd
) || close(fd
))
3422 die ("Could not write temporary index to %s", filename
);
3424 discard_index(&result
);
3427 static void stat_patch_list(struct patch
*patch
)
3429 int files
, adds
, dels
;
3431 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
3433 adds
+= patch
->lines_added
;
3434 dels
+= patch
->lines_deleted
;
3438 print_stat_summary(stdout
, files
, adds
, dels
);
3441 static void numstat_patch_list(struct patch
*patch
)
3443 for ( ; patch
; patch
= patch
->next
) {
3445 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
3446 if (patch
->is_binary
)
3449 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
3450 write_name_quoted(name
, stdout
, line_termination
);
3454 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
3457 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
3459 printf(" %s %s\n", newdelete
, name
);
3462 static void show_mode_change(struct patch
*p
, int show_name
)
3464 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
3466 printf(" mode change %06o => %06o %s\n",
3467 p
->old_mode
, p
->new_mode
, p
->new_name
);
3469 printf(" mode change %06o => %06o\n",
3470 p
->old_mode
, p
->new_mode
);
3474 static void show_rename_copy(struct patch
*p
)
3476 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
3477 const char *old
, *new;
3479 /* Find common prefix */
3483 const char *slash_old
, *slash_new
;
3484 slash_old
= strchr(old
, '/');
3485 slash_new
= strchr(new, '/');
3488 slash_old
- old
!= slash_new
- new ||
3489 memcmp(old
, new, slash_new
- new))
3491 old
= slash_old
+ 1;
3492 new = slash_new
+ 1;
3494 /* p->old_name thru old is the common prefix, and old and new
3495 * through the end of names are renames
3497 if (old
!= p
->old_name
)
3498 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
3499 (int)(old
- p
->old_name
), p
->old_name
,
3500 old
, new, p
->score
);
3502 printf(" %s %s => %s (%d%%)\n", renamecopy
,
3503 p
->old_name
, p
->new_name
, p
->score
);
3504 show_mode_change(p
, 0);
3507 static void summary_patch_list(struct patch
*patch
)
3511 for (p
= patch
; p
; p
= p
->next
) {
3513 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
3514 else if (p
->is_delete
)
3515 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
3517 if (p
->is_rename
|| p
->is_copy
)
3518 show_rename_copy(p
);
3521 printf(" rewrite %s (%d%%)\n",
3522 p
->new_name
, p
->score
);
3523 show_mode_change(p
, 0);
3526 show_mode_change(p
, 1);
3532 static void patch_stats(struct patch
*patch
)
3534 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
3536 if (lines
> max_change
)
3538 if (patch
->old_name
) {
3539 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
3541 len
= strlen(patch
->old_name
);
3545 if (patch
->new_name
) {
3546 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
3548 len
= strlen(patch
->new_name
);
3554 static void remove_file(struct patch
*patch
, int rmdir_empty
)
3557 if (remove_file_from_cache(patch
->old_name
) < 0)
3558 die(_("unable to remove %s from index"), patch
->old_name
);
3561 if (!remove_or_warn(patch
->old_mode
, patch
->old_name
) && rmdir_empty
) {
3562 remove_path(patch
->old_name
);
3567 static void add_index_file(const char *path
, unsigned mode
, void *buf
, unsigned long size
)
3570 struct cache_entry
*ce
;
3571 int namelen
= strlen(path
);
3572 unsigned ce_size
= cache_entry_size(namelen
);
3577 ce
= xcalloc(1, ce_size
);
3578 memcpy(ce
->name
, path
, namelen
);
3579 ce
->ce_mode
= create_ce_mode(mode
);
3580 ce
->ce_flags
= namelen
;
3581 if (S_ISGITLINK(mode
)) {
3582 const char *s
= buf
;
3584 if (get_sha1_hex(s
+ strlen("Subproject commit "), ce
->sha1
))
3585 die(_("corrupt patch for subproject %s"), path
);
3588 if (lstat(path
, &st
) < 0)
3589 die_errno(_("unable to stat newly created file '%s'"),
3591 fill_stat_cache_info(ce
, &st
);
3593 if (write_sha1_file(buf
, size
, blob_type
, ce
->sha1
) < 0)
3594 die(_("unable to create backing store for newly created file %s"), path
);
3596 if (add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
) < 0)
3597 die(_("unable to add cache entry for %s"), path
);
3600 static int try_create_file(const char *path
, unsigned int mode
, const char *buf
, unsigned long size
)
3603 struct strbuf nbuf
= STRBUF_INIT
;
3605 if (S_ISGITLINK(mode
)) {
3607 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
))
3609 return mkdir(path
, 0777);
3612 if (has_symlinks
&& S_ISLNK(mode
))
3613 /* Although buf:size is counted string, it also is NUL
3616 return symlink(buf
, path
);
3618 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
3622 if (convert_to_working_tree(path
, buf
, size
, &nbuf
)) {
3626 write_or_die(fd
, buf
, size
);
3627 strbuf_release(&nbuf
);
3630 die_errno(_("closing file '%s'"), path
);
3635 * We optimistically assume that the directories exist,
3636 * which is true 99% of the time anyway. If they don't,
3637 * we create them and try again.
3639 static void create_one_file(char *path
, unsigned mode
, const char *buf
, unsigned long size
)
3643 if (!try_create_file(path
, mode
, buf
, size
))
3646 if (errno
== ENOENT
) {
3647 if (safe_create_leading_directories(path
))
3649 if (!try_create_file(path
, mode
, buf
, size
))
3653 if (errno
== EEXIST
|| errno
== EACCES
) {
3654 /* We may be trying to create a file where a directory
3658 if (!lstat(path
, &st
) && (!S_ISDIR(st
.st_mode
) || !rmdir(path
)))
3662 if (errno
== EEXIST
) {
3663 unsigned int nr
= getpid();
3666 char newpath
[PATH_MAX
];
3667 mksnpath(newpath
, sizeof(newpath
), "%s~%u", path
, nr
);
3668 if (!try_create_file(newpath
, mode
, buf
, size
)) {
3669 if (!rename(newpath
, path
))
3671 unlink_or_warn(newpath
);
3674 if (errno
!= EEXIST
)
3679 die_errno(_("unable to write file '%s' mode %o"), path
, mode
);
3682 static void create_file(struct patch
*patch
)
3684 char *path
= patch
->new_name
;
3685 unsigned mode
= patch
->new_mode
;
3686 unsigned long size
= patch
->resultsize
;
3687 char *buf
= patch
->result
;
3690 mode
= S_IFREG
| 0644;
3691 create_one_file(path
, mode
, buf
, size
);
3692 add_index_file(path
, mode
, buf
, size
);
3695 /* phase zero is to remove, phase one is to create */
3696 static void write_out_one_result(struct patch
*patch
, int phase
)
3698 if (patch
->is_delete
> 0) {
3700 remove_file(patch
, 1);
3703 if (patch
->is_new
> 0 || patch
->is_copy
) {
3709 * Rename or modification boils down to the same
3710 * thing: remove the old, write the new
3713 remove_file(patch
, patch
->is_rename
);
3718 static int write_out_one_reject(struct patch
*patch
)
3721 char namebuf
[PATH_MAX
];
3722 struct fragment
*frag
;
3724 struct strbuf sb
= STRBUF_INIT
;
3726 for (cnt
= 0, frag
= patch
->fragments
; frag
; frag
= frag
->next
) {
3727 if (!frag
->rejected
)
3733 if (apply_verbosely
)
3734 say_patch_name(stderr
,
3735 _("Applied patch %s cleanly."), patch
);
3739 /* This should not happen, because a removal patch that leaves
3740 * contents are marked "rejected" at the patch level.
3742 if (!patch
->new_name
)
3743 die(_("internal error"));
3745 /* Say this even without --verbose */
3746 strbuf_addf(&sb
, Q_("Applying patch %%s with %d reject...",
3747 "Applying patch %%s with %d rejects...",
3750 say_patch_name(stderr
, sb
.buf
, patch
);
3751 strbuf_release(&sb
);
3753 cnt
= strlen(patch
->new_name
);
3754 if (ARRAY_SIZE(namebuf
) <= cnt
+ 5) {
3755 cnt
= ARRAY_SIZE(namebuf
) - 5;
3756 warning(_("truncating .rej filename to %.*s.rej"),
3757 cnt
- 1, patch
->new_name
);
3759 memcpy(namebuf
, patch
->new_name
, cnt
);
3760 memcpy(namebuf
+ cnt
, ".rej", 5);
3762 rej
= fopen(namebuf
, "w");
3764 return error(_("cannot open %s: %s"), namebuf
, strerror(errno
));
3766 /* Normal git tools never deal with .rej, so do not pretend
3767 * this is a git patch by saying --git nor give extended
3768 * headers. While at it, maybe please "kompare" that wants
3769 * the trailing TAB and some garbage at the end of line ;-).
3771 fprintf(rej
, "diff a/%s b/%s\t(rejected hunks)\n",
3772 patch
->new_name
, patch
->new_name
);
3773 for (cnt
= 1, frag
= patch
->fragments
;
3775 cnt
++, frag
= frag
->next
) {
3776 if (!frag
->rejected
) {
3777 fprintf_ln(stderr
, _("Hunk #%d applied cleanly."), cnt
);
3780 fprintf_ln(stderr
, _("Rejected hunk #%d."), cnt
);
3781 fprintf(rej
, "%.*s", frag
->size
, frag
->patch
);
3782 if (frag
->patch
[frag
->size
-1] != '\n')
3789 static int write_out_results(struct patch
*list
)
3795 for (phase
= 0; phase
< 2; phase
++) {
3801 write_out_one_result(l
, phase
);
3802 if (phase
== 1 && write_out_one_reject(l
))
3811 static struct lock_file lock_file
;
3813 static struct string_list limit_by_name
;
3814 static int has_include
;
3815 static void add_name_limit(const char *name
, int exclude
)
3817 struct string_list_item
*it
;
3819 it
= string_list_append(&limit_by_name
, name
);
3820 it
->util
= exclude
? NULL
: (void *) 1;
3823 static int use_patch(struct patch
*p
)
3825 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
3828 /* Paths outside are not touched regardless of "--include" */
3829 if (0 < prefix_length
) {
3830 int pathlen
= strlen(pathname
);
3831 if (pathlen
<= prefix_length
||
3832 memcmp(prefix
, pathname
, prefix_length
))
3836 /* See if it matches any of exclude/include rule */
3837 for (i
= 0; i
< limit_by_name
.nr
; i
++) {
3838 struct string_list_item
*it
= &limit_by_name
.items
[i
];
3839 if (!fnmatch(it
->string
, pathname
, 0))
3840 return (it
->util
!= NULL
);
3844 * If we had any include, a path that does not match any rule is
3845 * not used. Otherwise, we saw bunch of exclude rules (or none)
3846 * and such a path is used.
3848 return !has_include
;
3852 static void prefix_one(char **name
)
3854 char *old_name
= *name
;
3857 *name
= xstrdup(prefix_filename(prefix
, prefix_length
, *name
));
3861 static void prefix_patches(struct patch
*p
)
3863 if (!prefix
|| p
->is_toplevel_relative
)
3865 for ( ; p
; p
= p
->next
) {
3866 prefix_one(&p
->new_name
);
3867 prefix_one(&p
->old_name
);
3871 #define INACCURATE_EOF (1<<0)
3872 #define RECOUNT (1<<1)
3874 static int apply_patch(int fd
, const char *filename
, int options
)
3877 struct strbuf buf
= STRBUF_INIT
; /* owns the patch text */
3878 struct patch
*list
= NULL
, **listp
= &list
;
3879 int skipped_patch
= 0;
3881 patch_input_file
= filename
;
3882 read_patch_file(&buf
, fd
);
3884 while (offset
< buf
.len
) {
3885 struct patch
*patch
;
3888 patch
= xcalloc(1, sizeof(*patch
));
3889 patch
->inaccurate_eof
= !!(options
& INACCURATE_EOF
);
3890 patch
->recount
= !!(options
& RECOUNT
);
3891 nr
= parse_chunk(buf
.buf
+ offset
, buf
.len
- offset
, patch
);
3894 if (apply_in_reverse
)
3895 reverse_patches(patch
);
3897 prefix_patches(patch
);
3898 if (use_patch(patch
)) {
3901 listp
= &patch
->next
;
3910 if (!list
&& !skipped_patch
)
3911 die(_("unrecognized input"));
3913 if (whitespace_error
&& (ws_error_action
== die_on_ws_error
))
3916 update_index
= check_index
&& apply
;
3917 if (update_index
&& newfd
< 0)
3918 newfd
= hold_locked_index(&lock_file
, 1);
3921 if (read_cache() < 0)
3922 die(_("unable to read index file"));
3925 if ((check
|| apply
) &&
3926 check_patch_list(list
) < 0 &&
3930 if (apply
&& write_out_results(list
))
3934 build_fake_ancestor(list
, fake_ancestor
);
3937 stat_patch_list(list
);
3940 numstat_patch_list(list
);
3943 summary_patch_list(list
);
3945 free_patch_list(list
);
3946 strbuf_release(&buf
);
3947 string_list_clear(&fn_table
, 0);
3951 static int git_apply_config(const char *var
, const char *value
, void *cb
)
3953 if (!strcmp(var
, "apply.whitespace"))
3954 return git_config_string(&apply_default_whitespace
, var
, value
);
3955 else if (!strcmp(var
, "apply.ignorewhitespace"))
3956 return git_config_string(&apply_default_ignorewhitespace
, var
, value
);
3957 return git_default_config(var
, value
, cb
);
3960 static int option_parse_exclude(const struct option
*opt
,
3961 const char *arg
, int unset
)
3963 add_name_limit(arg
, 1);
3967 static int option_parse_include(const struct option
*opt
,
3968 const char *arg
, int unset
)
3970 add_name_limit(arg
, 0);
3975 static int option_parse_p(const struct option
*opt
,
3976 const char *arg
, int unset
)
3978 p_value
= atoi(arg
);
3983 static int option_parse_z(const struct option
*opt
,
3984 const char *arg
, int unset
)
3987 line_termination
= '\n';
3989 line_termination
= 0;
3993 static int option_parse_space_change(const struct option
*opt
,
3994 const char *arg
, int unset
)
3997 ws_ignore_action
= ignore_ws_none
;
3999 ws_ignore_action
= ignore_ws_change
;
4003 static int option_parse_whitespace(const struct option
*opt
,
4004 const char *arg
, int unset
)
4006 const char **whitespace_option
= opt
->value
;
4008 *whitespace_option
= arg
;
4009 parse_whitespace_option(arg
);
4013 static int option_parse_directory(const struct option
*opt
,
4014 const char *arg
, int unset
)
4016 root_len
= strlen(arg
);
4017 if (root_len
&& arg
[root_len
- 1] != '/') {
4019 root
= new_root
= xmalloc(root_len
+ 2);
4020 strcpy(new_root
, arg
);
4021 strcpy(new_root
+ root_len
++, "/");
4027 int cmd_apply(int argc
, const char **argv
, const char *prefix_
)
4031 int is_not_gitdir
= !startup_info
->have_repository
;
4032 int force_apply
= 0;
4034 const char *whitespace_option
= NULL
;
4036 struct option builtin_apply_options
[] = {
4037 { OPTION_CALLBACK
, 0, "exclude", NULL
, "path",
4038 "don't apply changes matching the given path",
4039 0, option_parse_exclude
},
4040 { OPTION_CALLBACK
, 0, "include", NULL
, "path",
4041 "apply changes matching the given path",
4042 0, option_parse_include
},
4043 { OPTION_CALLBACK
, 'p', NULL
, NULL
, "num",
4044 "remove <num> leading slashes from traditional diff paths",
4045 0, option_parse_p
},
4046 OPT_BOOLEAN(0, "no-add", &no_add
,
4047 "ignore additions made by the patch"),
4048 OPT_BOOLEAN(0, "stat", &diffstat
,
4049 "instead of applying the patch, output diffstat for the input"),
4050 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
4051 OPT_NOOP_NOARG(0, "binary"),
4052 OPT_BOOLEAN(0, "numstat", &numstat
,
4053 "shows number of added and deleted lines in decimal notation"),
4054 OPT_BOOLEAN(0, "summary", &summary
,
4055 "instead of applying the patch, output a summary for the input"),
4056 OPT_BOOLEAN(0, "check", &check
,
4057 "instead of applying the patch, see if the patch is applicable"),
4058 OPT_BOOLEAN(0, "index", &check_index
,
4059 "make sure the patch is applicable to the current index"),
4060 OPT_BOOLEAN(0, "cached", &cached
,
4061 "apply a patch without touching the working tree"),
4062 OPT_BOOLEAN(0, "apply", &force_apply
,
4063 "also apply the patch (use with --stat/--summary/--check)"),
4064 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor
,
4065 "build a temporary index based on embedded index information"),
4066 { OPTION_CALLBACK
, 'z', NULL
, NULL
, NULL
,
4067 "paths are separated with NUL character",
4068 PARSE_OPT_NOARG
, option_parse_z
},
4069 OPT_INTEGER('C', NULL
, &p_context
,
4070 "ensure at least <n> lines of context match"),
4071 { OPTION_CALLBACK
, 0, "whitespace", &whitespace_option
, "action",
4072 "detect new or modified lines that have whitespace errors",
4073 0, option_parse_whitespace
},
4074 { OPTION_CALLBACK
, 0, "ignore-space-change", NULL
, NULL
,
4075 "ignore changes in whitespace when finding context",
4076 PARSE_OPT_NOARG
, option_parse_space_change
},
4077 { OPTION_CALLBACK
, 0, "ignore-whitespace", NULL
, NULL
,
4078 "ignore changes in whitespace when finding context",
4079 PARSE_OPT_NOARG
, option_parse_space_change
},
4080 OPT_BOOLEAN('R', "reverse", &apply_in_reverse
,
4081 "apply the patch in reverse"),
4082 OPT_BOOLEAN(0, "unidiff-zero", &unidiff_zero
,
4083 "don't expect at least one line of context"),
4084 OPT_BOOLEAN(0, "reject", &apply_with_reject
,
4085 "leave the rejected hunks in corresponding *.rej files"),
4086 OPT_BOOLEAN(0, "allow-overlap", &allow_overlap
,
4087 "allow overlapping hunks"),
4088 OPT__VERBOSE(&apply_verbosely
, "be verbose"),
4089 OPT_BIT(0, "inaccurate-eof", &options
,
4090 "tolerate incorrectly detected missing new-line at the end of file",
4092 OPT_BIT(0, "recount", &options
,
4093 "do not trust the line counts in the hunk headers",
4095 { OPTION_CALLBACK
, 0, "directory", NULL
, "root",
4096 "prepend <root> to all filenames",
4097 0, option_parse_directory
},
4102 prefix_length
= prefix
? strlen(prefix
) : 0;
4103 git_config(git_apply_config
, NULL
);
4104 if (apply_default_whitespace
)
4105 parse_whitespace_option(apply_default_whitespace
);
4106 if (apply_default_ignorewhitespace
)
4107 parse_ignorewhitespace_option(apply_default_ignorewhitespace
);
4109 argc
= parse_options(argc
, argv
, prefix
, builtin_apply_options
,
4112 if (apply_with_reject
)
4113 apply
= apply_verbosely
= 1;
4114 if (!force_apply
&& (diffstat
|| numstat
|| summary
|| check
|| fake_ancestor
))
4116 if (check_index
&& is_not_gitdir
)
4117 die(_("--index outside a repository"));
4120 die(_("--cached outside a repository"));
4123 for (i
= 0; i
< argc
; i
++) {
4124 const char *arg
= argv
[i
];
4127 if (!strcmp(arg
, "-")) {
4128 errs
|= apply_patch(0, "<stdin>", options
);
4131 } else if (0 < prefix_length
)
4132 arg
= prefix_filename(prefix
, prefix_length
, arg
);
4134 fd
= open(arg
, O_RDONLY
);
4136 die_errno(_("can't open patch '%s'"), arg
);
4138 set_default_whitespace_mode(whitespace_option
);
4139 errs
|= apply_patch(fd
, arg
, options
);
4142 set_default_whitespace_mode(whitespace_option
);
4144 errs
|= apply_patch(0, "<stdin>", options
);
4145 if (whitespace_error
) {
4146 if (squelch_whitespace_errors
&&
4147 squelch_whitespace_errors
< whitespace_error
) {
4149 whitespace_error
- squelch_whitespace_errors
;
4150 warning(Q_("squelched %d whitespace error",
4151 "squelched %d whitespace errors",
4155 if (ws_error_action
== die_on_ws_error
)
4156 die(Q_("%d line adds whitespace errors.",
4157 "%d lines add whitespace errors.",
4160 if (applied_after_fixing_ws
&& apply
)
4161 warning("%d line%s applied after"
4162 " fixing whitespace errors.",
4163 applied_after_fixing_ws
,
4164 applied_after_fixing_ws
== 1 ? "" : "s");
4165 else if (whitespace_error
)
4166 warning(Q_("%d line adds whitespace errors.",
4167 "%d lines add whitespace errors.",
4173 if (write_cache(newfd
, active_cache
, active_nr
) ||
4174 commit_locked_index(&lock_file
))
4175 die(_("Unable to write new index file"));