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
;
50 static const char *fake_ancestor
;
51 static int line_termination
= '\n';
52 static unsigned int p_context
= UINT_MAX
;
53 static const char * const apply_usage
[] = {
54 "git apply [options] [<patch>...]",
58 static enum ws_error_action
{
63 } ws_error_action
= warn_on_ws_error
;
64 static int whitespace_error
;
65 static int squelch_whitespace_errors
= 5;
66 static int applied_after_fixing_ws
;
68 static enum ws_ignore
{
71 } ws_ignore_action
= ignore_ws_none
;
74 static const char *patch_input_file
;
75 static const char *root
;
77 static int read_stdin
= 1;
80 static void parse_whitespace_option(const char *option
)
83 ws_error_action
= warn_on_ws_error
;
86 if (!strcmp(option
, "warn")) {
87 ws_error_action
= warn_on_ws_error
;
90 if (!strcmp(option
, "nowarn")) {
91 ws_error_action
= nowarn_ws_error
;
94 if (!strcmp(option
, "error")) {
95 ws_error_action
= die_on_ws_error
;
98 if (!strcmp(option
, "error-all")) {
99 ws_error_action
= die_on_ws_error
;
100 squelch_whitespace_errors
= 0;
103 if (!strcmp(option
, "strip") || !strcmp(option
, "fix")) {
104 ws_error_action
= correct_ws_error
;
107 die(_("unrecognized whitespace option '%s'"), option
);
110 static void parse_ignorewhitespace_option(const char *option
)
112 if (!option
|| !strcmp(option
, "no") ||
113 !strcmp(option
, "false") || !strcmp(option
, "never") ||
114 !strcmp(option
, "none")) {
115 ws_ignore_action
= ignore_ws_none
;
118 if (!strcmp(option
, "change")) {
119 ws_ignore_action
= ignore_ws_change
;
122 die(_("unrecognized whitespace ignore option '%s'"), option
);
125 static void set_default_whitespace_mode(const char *whitespace_option
)
127 if (!whitespace_option
&& !apply_default_whitespace
)
128 ws_error_action
= (apply
? warn_on_ws_error
: nowarn_ws_error
);
132 * For "diff-stat" like behaviour, we keep track of the biggest change
133 * we've seen, and the longest filename. That allows us to do simple
136 static int max_change
, max_len
;
139 * Various "current state", notably line numbers and what
140 * file (and how) we're patching right now.. The "is_xxxx"
141 * things are flags, where -1 means "don't know yet".
143 static int linenr
= 1;
146 * This represents one "hunk" from a patch, starting with
147 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
148 * patch text is pointed at by patch, and its byte length
149 * is stored in size. leading and trailing are the number
153 unsigned long leading
, trailing
;
154 unsigned long oldpos
, oldlines
;
155 unsigned long newpos
, newlines
;
157 * 'patch' is usually borrowed from buf in apply_patch(),
158 * but some codepaths store an allocated buffer.
161 unsigned free_patch
:1,
165 struct fragment
*next
;
169 * When dealing with a binary patch, we reuse "leading" field
170 * to store the type of the binary hunk, either deflated "delta"
171 * or deflated "literal".
173 #define binary_patch_method leading
174 #define BINARY_DELTA_DEFLATED 1
175 #define BINARY_LITERAL_DEFLATED 2
178 * This represents a "patch" to a file, both metainfo changes
179 * such as creation/deletion, filemode and content changes represented
180 * as a series of fragments.
183 char *new_name
, *old_name
, *def_name
;
184 unsigned int old_mode
, new_mode
;
185 int is_new
, is_delete
; /* -1 = unknown, 0 = false, 1 = true */
188 unsigned long deflate_origlen
;
189 int lines_added
, lines_deleted
;
191 unsigned int is_toplevel_relative
:1;
192 unsigned int inaccurate_eof
:1;
193 unsigned int is_binary
:1;
194 unsigned int is_copy
:1;
195 unsigned int is_rename
:1;
196 unsigned int recount
:1;
197 struct fragment
*fragments
;
200 char old_sha1_prefix
[41];
201 char new_sha1_prefix
[41];
205 static void free_fragment_list(struct fragment
*list
)
208 struct fragment
*next
= list
->next
;
209 if (list
->free_patch
)
210 free((char *)list
->patch
);
216 static void free_patch(struct patch
*patch
)
218 free_fragment_list(patch
->fragments
);
219 free(patch
->def_name
);
220 free(patch
->old_name
);
221 free(patch
->new_name
);
226 static void free_patch_list(struct patch
*list
)
229 struct patch
*next
= list
->next
;
236 * A line in a file, len-bytes long (includes the terminating LF,
237 * except for an incomplete line at the end if the file ends with
238 * one), and its contents hashes to 'hash'.
244 #define LINE_COMMON 1
245 #define LINE_PATCHED 2
249 * This represents a "file", which is an array of "lines".
256 struct line
*line_allocated
;
261 * Records filenames that have been touched, in order to handle
262 * the case where more than one patches touch the same file.
265 static struct string_list fn_table
;
267 static uint32_t hash_line(const char *cp
, size_t len
)
271 for (i
= 0, h
= 0; i
< len
; i
++) {
272 if (!isspace(cp
[i
])) {
273 h
= h
* 3 + (cp
[i
] & 0xff);
280 * Compare lines s1 of length n1 and s2 of length n2, ignoring
281 * whitespace difference. Returns 1 if they match, 0 otherwise
283 static int fuzzy_matchlines(const char *s1
, size_t n1
,
284 const char *s2
, size_t n2
)
286 const char *last1
= s1
+ n1
- 1;
287 const char *last2
= s2
+ n2
- 1;
290 /* ignore line endings */
291 while ((*last1
== '\r') || (*last1
== '\n'))
293 while ((*last2
== '\r') || (*last2
== '\n'))
296 /* skip leading whitespace */
297 while (isspace(*s1
) && (s1
<= last1
))
299 while (isspace(*s2
) && (s2
<= last2
))
301 /* early return if both lines are empty */
302 if ((s1
> last1
) && (s2
> last2
))
305 result
= *s1
++ - *s2
++;
307 * Skip whitespace inside. We check for whitespace on
308 * both buffers because we don't want "a b" to match
311 if (isspace(*s1
) && isspace(*s2
)) {
312 while (isspace(*s1
) && s1
<= last1
)
314 while (isspace(*s2
) && s2
<= last2
)
318 * If we reached the end on one side only,
322 ((s2
> last2
) && (s1
<= last1
)) ||
323 ((s1
> last1
) && (s2
<= last2
)))
325 if ((s1
> last1
) && (s2
> last2
))
332 static void add_line_info(struct image
*img
, const char *bol
, size_t len
, unsigned flag
)
334 ALLOC_GROW(img
->line_allocated
, img
->nr
+ 1, img
->alloc
);
335 img
->line_allocated
[img
->nr
].len
= len
;
336 img
->line_allocated
[img
->nr
].hash
= hash_line(bol
, len
);
337 img
->line_allocated
[img
->nr
].flag
= flag
;
342 * "buf" has the file contents to be patched (read from various sources).
343 * attach it to "image" and add line-based index to it.
344 * "image" now owns the "buf".
346 static void prepare_image(struct image
*image
, char *buf
, size_t len
,
347 int prepare_linetable
)
351 memset(image
, 0, sizeof(*image
));
355 if (!prepare_linetable
)
358 ep
= image
->buf
+ image
->len
;
362 for (next
= cp
; next
< ep
&& *next
!= '\n'; next
++)
366 add_line_info(image
, cp
, next
- cp
, 0);
369 image
->line
= image
->line_allocated
;
372 static void clear_image(struct image
*image
)
375 free(image
->line_allocated
);
376 memset(image
, 0, sizeof(*image
));
379 /* fmt must contain _one_ %s and no other substitution */
380 static void say_patch_name(FILE *output
, const char *fmt
, struct patch
*patch
)
382 struct strbuf sb
= STRBUF_INIT
;
384 if (patch
->old_name
&& patch
->new_name
&&
385 strcmp(patch
->old_name
, patch
->new_name
)) {
386 quote_c_style(patch
->old_name
, &sb
, NULL
, 0);
387 strbuf_addstr(&sb
, " => ");
388 quote_c_style(patch
->new_name
, &sb
, NULL
, 0);
390 const char *n
= patch
->new_name
;
393 quote_c_style(n
, &sb
, NULL
, 0);
395 fprintf(output
, fmt
, sb
.buf
);
402 static void read_patch_file(struct strbuf
*sb
, int fd
)
404 if (strbuf_read(sb
, fd
, 0) < 0)
405 die_errno("git apply: failed to read");
408 * Make sure that we have some slop in the buffer
409 * so that we can do speculative "memcmp" etc, and
410 * see to it that it is NUL-filled.
412 strbuf_grow(sb
, SLOP
);
413 memset(sb
->buf
+ sb
->len
, 0, SLOP
);
416 static unsigned long linelen(const char *buffer
, unsigned long size
)
418 unsigned long len
= 0;
421 if (*buffer
++ == '\n')
427 static int is_dev_null(const char *str
)
429 return !memcmp("/dev/null", str
, 9) && isspace(str
[9]);
435 static int name_terminate(const char *name
, int namelen
, int c
, int terminate
)
437 if (c
== ' ' && !(terminate
& TERM_SPACE
))
439 if (c
== '\t' && !(terminate
& TERM_TAB
))
445 /* remove double slashes to make --index work with such filenames */
446 static char *squash_slash(char *name
)
454 if ((name
[j
++] = name
[i
++]) == '/')
455 while (name
[i
] == '/')
462 static char *find_name_gnu(const char *line
, const char *def
, int p_value
)
464 struct strbuf name
= STRBUF_INIT
;
468 * Proposed "new-style" GNU patch/diff format; see
469 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
471 if (unquote_c_style(&name
, line
, NULL
)) {
472 strbuf_release(&name
);
476 for (cp
= name
.buf
; p_value
; p_value
--) {
477 cp
= strchr(cp
, '/');
479 strbuf_release(&name
);
485 strbuf_remove(&name
, 0, cp
- name
.buf
);
487 strbuf_insert(&name
, 0, root
, root_len
);
488 return squash_slash(strbuf_detach(&name
, NULL
));
491 static size_t sane_tz_len(const char *line
, size_t len
)
495 if (len
< strlen(" +0500") || line
[len
-strlen(" +0500")] != ' ')
497 tz
= line
+ len
- strlen(" +0500");
499 if (tz
[1] != '+' && tz
[1] != '-')
502 for (p
= tz
+ 2; p
!= line
+ len
; p
++)
506 return line
+ len
- tz
;
509 static size_t tz_with_colon_len(const char *line
, size_t len
)
513 if (len
< strlen(" +08:00") || line
[len
- strlen(":00")] != ':')
515 tz
= line
+ len
- strlen(" +08:00");
517 if (tz
[0] != ' ' || (tz
[1] != '+' && tz
[1] != '-'))
520 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
521 !isdigit(*p
++) || !isdigit(*p
++))
524 return line
+ len
- tz
;
527 static size_t date_len(const char *line
, size_t len
)
529 const char *date
, *p
;
531 if (len
< strlen("72-02-05") || line
[len
-strlen("-05")] != '-')
533 p
= date
= line
+ len
- strlen("72-02-05");
535 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
536 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
537 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a date. */
540 if (date
- line
>= strlen("19") &&
541 isdigit(date
[-1]) && isdigit(date
[-2])) /* 4-digit year */
542 date
-= strlen("19");
544 return line
+ len
- date
;
547 static size_t short_time_len(const char *line
, size_t len
)
549 const char *time
, *p
;
551 if (len
< strlen(" 07:01:32") || line
[len
-strlen(":32")] != ':')
553 p
= time
= line
+ len
- strlen(" 07:01:32");
555 /* Permit 1-digit hours? */
557 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
558 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
559 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a time. */
562 return line
+ len
- time
;
565 static size_t fractional_time_len(const char *line
, size_t len
)
570 /* Expected format: 19:41:17.620000023 */
571 if (!len
|| !isdigit(line
[len
- 1]))
575 /* Fractional seconds. */
576 while (p
> line
&& isdigit(*p
))
581 /* Hours, minutes, and whole seconds. */
582 n
= short_time_len(line
, p
- line
);
586 return line
+ len
- p
+ n
;
589 static size_t trailing_spaces_len(const char *line
, size_t len
)
593 /* Expected format: ' ' x (1 or more) */
594 if (!len
|| line
[len
- 1] != ' ')
601 return line
+ len
- (p
+ 1);
608 static size_t diff_timestamp_len(const char *line
, size_t len
)
610 const char *end
= line
+ len
;
614 * Posix: 2010-07-05 19:41:17
615 * GNU: 2010-07-05 19:41:17.620000023 -0500
618 if (!isdigit(end
[-1]))
621 n
= sane_tz_len(line
, end
- line
);
623 n
= tz_with_colon_len(line
, end
- line
);
626 n
= short_time_len(line
, end
- line
);
628 n
= fractional_time_len(line
, end
- line
);
631 n
= date_len(line
, end
- line
);
632 if (!n
) /* No date. Too bad. */
636 if (end
== line
) /* No space before date. */
638 if (end
[-1] == '\t') { /* Success! */
640 return line
+ len
- end
;
642 if (end
[-1] != ' ') /* No space before date. */
645 /* Whitespace damage. */
646 end
-= trailing_spaces_len(line
, end
- line
);
647 return line
+ len
- end
;
650 static char *null_strdup(const char *s
)
652 return s
? xstrdup(s
) : NULL
;
655 static char *find_name_common(const char *line
, const char *def
,
656 int p_value
, const char *end
, int terminate
)
659 const char *start
= NULL
;
663 while (line
!= end
) {
666 if (!end
&& isspace(c
)) {
669 if (name_terminate(start
, line
-start
, c
, terminate
))
673 if (c
== '/' && !--p_value
)
677 return squash_slash(null_strdup(def
));
680 return squash_slash(null_strdup(def
));
683 * Generally we prefer the shorter name, especially
684 * if the other one is just a variation of that with
685 * something else tacked on to the end (ie "file.orig"
689 int deflen
= strlen(def
);
690 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
691 return squash_slash(xstrdup(def
));
695 char *ret
= xmalloc(root_len
+ len
+ 1);
697 memcpy(ret
+ root_len
, start
, len
);
698 ret
[root_len
+ len
] = '\0';
699 return squash_slash(ret
);
702 return squash_slash(xmemdupz(start
, len
));
705 static char *find_name(const char *line
, char *def
, int p_value
, int terminate
)
708 char *name
= find_name_gnu(line
, def
, p_value
);
713 return find_name_common(line
, def
, p_value
, NULL
, terminate
);
716 static char *find_name_traditional(const char *line
, char *def
, int p_value
)
718 size_t len
= strlen(line
);
722 char *name
= find_name_gnu(line
, def
, p_value
);
727 len
= strchrnul(line
, '\n') - line
;
728 date_len
= diff_timestamp_len(line
, len
);
730 return find_name_common(line
, def
, p_value
, NULL
, TERM_TAB
);
733 return find_name_common(line
, def
, p_value
, line
+ len
, 0);
736 static int count_slashes(const char *cp
)
748 * Given the string after "--- " or "+++ ", guess the appropriate
749 * p_value for the given patch.
751 static int guess_p_value(const char *nameline
)
756 if (is_dev_null(nameline
))
758 name
= find_name_traditional(nameline
, NULL
, 0);
761 cp
= strchr(name
, '/');
766 * Does it begin with "a/$our-prefix" and such? Then this is
767 * very likely to apply to our directory.
769 if (!strncmp(name
, prefix
, prefix_length
))
770 val
= count_slashes(prefix
);
773 if (!strncmp(cp
, prefix
, prefix_length
))
774 val
= count_slashes(prefix
) + 1;
782 * Does the ---/+++ line has the POSIX timestamp after the last HT?
783 * GNU diff puts epoch there to signal a creation/deletion event. Is
784 * this such a timestamp?
786 static int has_epoch_timestamp(const char *nameline
)
789 * We are only interested in epoch timestamp; any non-zero
790 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
791 * For the same reason, the date must be either 1969-12-31 or
792 * 1970-01-01, and the seconds part must be "00".
794 const char stamp_regexp
[] =
795 "^(1969-12-31|1970-01-01)"
797 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
799 "([-+][0-2][0-9]:?[0-5][0-9])\n";
800 const char *timestamp
= NULL
, *cp
, *colon
;
801 static regex_t
*stamp
;
807 for (cp
= nameline
; *cp
!= '\n'; cp
++) {
814 stamp
= xmalloc(sizeof(*stamp
));
815 if (regcomp(stamp
, stamp_regexp
, REG_EXTENDED
)) {
816 warning(_("Cannot prepare timestamp regexp %s"),
822 status
= regexec(stamp
, timestamp
, ARRAY_SIZE(m
), m
, 0);
824 if (status
!= REG_NOMATCH
)
825 warning(_("regexec returned %d for input: %s"),
830 zoneoffset
= strtol(timestamp
+ m
[3].rm_so
+ 1, (char **) &colon
, 10);
832 zoneoffset
= zoneoffset
* 60 + strtol(colon
+ 1, NULL
, 10);
834 zoneoffset
= (zoneoffset
/ 100) * 60 + (zoneoffset
% 100);
835 if (timestamp
[m
[3].rm_so
] == '-')
836 zoneoffset
= -zoneoffset
;
839 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
840 * (west of GMT) or 1970-01-01 (east of GMT)
842 if ((zoneoffset
< 0 && memcmp(timestamp
, "1969-12-31", 10)) ||
843 (0 <= zoneoffset
&& memcmp(timestamp
, "1970-01-01", 10)))
846 hourminute
= (strtol(timestamp
+ 11, NULL
, 10) * 60 +
847 strtol(timestamp
+ 14, NULL
, 10) -
850 return ((zoneoffset
< 0 && hourminute
== 1440) ||
851 (0 <= zoneoffset
&& !hourminute
));
855 * Get the name etc info from the ---/+++ lines of a traditional patch header
857 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
858 * files, we can happily check the index for a match, but for creating a
859 * new file we should try to match whatever "patch" does. I have no idea.
861 static void parse_traditional_patch(const char *first
, const char *second
, struct patch
*patch
)
865 first
+= 4; /* skip "--- " */
866 second
+= 4; /* skip "+++ " */
867 if (!p_value_known
) {
869 p
= guess_p_value(first
);
870 q
= guess_p_value(second
);
872 if (0 <= p
&& p
== q
) {
877 if (is_dev_null(first
)) {
879 patch
->is_delete
= 0;
880 name
= find_name_traditional(second
, NULL
, p_value
);
881 patch
->new_name
= name
;
882 } else if (is_dev_null(second
)) {
884 patch
->is_delete
= 1;
885 name
= find_name_traditional(first
, NULL
, p_value
);
886 patch
->old_name
= name
;
889 first_name
= find_name_traditional(first
, NULL
, p_value
);
890 name
= find_name_traditional(second
, first_name
, p_value
);
892 if (has_epoch_timestamp(first
)) {
894 patch
->is_delete
= 0;
895 patch
->new_name
= name
;
896 } else if (has_epoch_timestamp(second
)) {
898 patch
->is_delete
= 1;
899 patch
->old_name
= name
;
901 patch
->old_name
= name
;
902 patch
->new_name
= xstrdup(name
);
906 die(_("unable to find filename in patch at line %d"), linenr
);
909 static int gitdiff_hdrend(const char *line
, struct patch
*patch
)
915 * We're anal about diff header consistency, to make
916 * sure that we don't end up having strange ambiguous
917 * patches floating around.
919 * As a result, gitdiff_{old|new}name() will check
920 * their names against any previous information, just
923 static char *gitdiff_verify_name(const char *line
, int isnull
, char *orig_name
, const char *oldnew
)
925 if (!orig_name
&& !isnull
)
926 return find_name(line
, NULL
, p_value
, TERM_TAB
);
935 die(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"), name
, linenr
);
936 another
= find_name(line
, NULL
, p_value
, TERM_TAB
);
937 if (!another
|| memcmp(another
, name
, len
+ 1))
938 die(_("git apply: bad git-diff - inconsistent %s filename on line %d"), oldnew
, linenr
);
943 /* expect "/dev/null" */
944 if (memcmp("/dev/null", line
, 9) || line
[9] != '\n')
945 die(_("git apply: bad git-diff - expected /dev/null on line %d"), linenr
);
950 static int gitdiff_oldname(const char *line
, struct patch
*patch
)
952 char *orig
= patch
->old_name
;
953 patch
->old_name
= gitdiff_verify_name(line
, patch
->is_new
, patch
->old_name
, "old");
954 if (orig
!= patch
->old_name
)
959 static int gitdiff_newname(const char *line
, struct patch
*patch
)
961 char *orig
= patch
->new_name
;
962 patch
->new_name
= gitdiff_verify_name(line
, patch
->is_delete
, patch
->new_name
, "new");
963 if (orig
!= patch
->new_name
)
968 static int gitdiff_oldmode(const char *line
, struct patch
*patch
)
970 patch
->old_mode
= strtoul(line
, NULL
, 8);
974 static int gitdiff_newmode(const char *line
, struct patch
*patch
)
976 patch
->new_mode
= strtoul(line
, NULL
, 8);
980 static int gitdiff_delete(const char *line
, struct patch
*patch
)
982 patch
->is_delete
= 1;
983 free(patch
->old_name
);
984 patch
->old_name
= null_strdup(patch
->def_name
);
985 return gitdiff_oldmode(line
, patch
);
988 static int gitdiff_newfile(const char *line
, struct patch
*patch
)
991 free(patch
->new_name
);
992 patch
->new_name
= null_strdup(patch
->def_name
);
993 return gitdiff_newmode(line
, patch
);
996 static int gitdiff_copysrc(const char *line
, struct patch
*patch
)
999 free(patch
->old_name
);
1000 patch
->old_name
= find_name(line
, NULL
, p_value
? p_value
- 1 : 0, 0);
1004 static int gitdiff_copydst(const char *line
, struct patch
*patch
)
1007 free(patch
->new_name
);
1008 patch
->new_name
= find_name(line
, NULL
, p_value
? p_value
- 1 : 0, 0);
1012 static int gitdiff_renamesrc(const char *line
, struct patch
*patch
)
1014 patch
->is_rename
= 1;
1015 free(patch
->old_name
);
1016 patch
->old_name
= find_name(line
, NULL
, p_value
? p_value
- 1 : 0, 0);
1020 static int gitdiff_renamedst(const char *line
, struct patch
*patch
)
1022 patch
->is_rename
= 1;
1023 free(patch
->new_name
);
1024 patch
->new_name
= find_name(line
, NULL
, p_value
? p_value
- 1 : 0, 0);
1028 static int gitdiff_similarity(const char *line
, struct patch
*patch
)
1030 if ((patch
->score
= strtoul(line
, NULL
, 10)) == ULONG_MAX
)
1035 static int gitdiff_dissimilarity(const char *line
, struct patch
*patch
)
1037 if ((patch
->score
= strtoul(line
, NULL
, 10)) == ULONG_MAX
)
1042 static int gitdiff_index(const char *line
, struct patch
*patch
)
1045 * index line is N hexadecimal, "..", N hexadecimal,
1046 * and optional space with octal mode.
1048 const char *ptr
, *eol
;
1051 ptr
= strchr(line
, '.');
1052 if (!ptr
|| ptr
[1] != '.' || 40 < ptr
- line
)
1055 memcpy(patch
->old_sha1_prefix
, line
, len
);
1056 patch
->old_sha1_prefix
[len
] = 0;
1059 ptr
= strchr(line
, ' ');
1060 eol
= strchr(line
, '\n');
1062 if (!ptr
|| eol
< ptr
)
1068 memcpy(patch
->new_sha1_prefix
, line
, len
);
1069 patch
->new_sha1_prefix
[len
] = 0;
1071 patch
->old_mode
= strtoul(ptr
+1, NULL
, 8);
1076 * This is normal for a diff that doesn't change anything: we'll fall through
1077 * into the next diff. Tell the parser to break out.
1079 static int gitdiff_unrecognized(const char *line
, struct patch
*patch
)
1084 static const char *stop_at_slash(const char *line
, int llen
)
1086 int nslash
= p_value
;
1089 for (i
= 0; i
< llen
; i
++) {
1091 if (ch
== '/' && --nslash
<= 0)
1098 * This is to extract the same name that appears on "diff --git"
1099 * line. We do not find and return anything if it is a rename
1100 * patch, and it is OK because we will find the name elsewhere.
1101 * We need to reliably find name only when it is mode-change only,
1102 * creation or deletion of an empty file. In any of these cases,
1103 * both sides are the same name under a/ and b/ respectively.
1105 static char *git_header_name(const char *line
, int llen
)
1108 const char *second
= NULL
;
1109 size_t len
, line_len
;
1111 line
+= strlen("diff --git ");
1112 llen
-= strlen("diff --git ");
1116 struct strbuf first
= STRBUF_INIT
;
1117 struct strbuf sp
= STRBUF_INIT
;
1119 if (unquote_c_style(&first
, line
, &second
))
1120 goto free_and_fail1
;
1122 /* advance to the first slash */
1123 cp
= stop_at_slash(first
.buf
, first
.len
);
1124 /* we do not accept absolute paths */
1125 if (!cp
|| cp
== first
.buf
)
1126 goto free_and_fail1
;
1127 strbuf_remove(&first
, 0, cp
+ 1 - first
.buf
);
1130 * second points at one past closing dq of name.
1131 * find the second name.
1133 while ((second
< line
+ llen
) && isspace(*second
))
1136 if (line
+ llen
<= second
)
1137 goto free_and_fail1
;
1138 if (*second
== '"') {
1139 if (unquote_c_style(&sp
, second
, NULL
))
1140 goto free_and_fail1
;
1141 cp
= stop_at_slash(sp
.buf
, sp
.len
);
1142 if (!cp
|| cp
== sp
.buf
)
1143 goto free_and_fail1
;
1144 /* They must match, otherwise ignore */
1145 if (strcmp(cp
+ 1, first
.buf
))
1146 goto free_and_fail1
;
1147 strbuf_release(&sp
);
1148 return strbuf_detach(&first
, NULL
);
1151 /* unquoted second */
1152 cp
= stop_at_slash(second
, line
+ llen
- second
);
1153 if (!cp
|| cp
== second
)
1154 goto free_and_fail1
;
1156 if (line
+ llen
- cp
!= first
.len
+ 1 ||
1157 memcmp(first
.buf
, cp
, first
.len
))
1158 goto free_and_fail1
;
1159 return strbuf_detach(&first
, NULL
);
1162 strbuf_release(&first
);
1163 strbuf_release(&sp
);
1167 /* unquoted first name */
1168 name
= stop_at_slash(line
, llen
);
1169 if (!name
|| name
== line
)
1174 * since the first name is unquoted, a dq if exists must be
1175 * the beginning of the second name.
1177 for (second
= name
; second
< line
+ llen
; second
++) {
1178 if (*second
== '"') {
1179 struct strbuf sp
= STRBUF_INIT
;
1182 if (unquote_c_style(&sp
, second
, NULL
))
1183 goto free_and_fail2
;
1185 np
= stop_at_slash(sp
.buf
, sp
.len
);
1186 if (!np
|| np
== sp
.buf
)
1187 goto free_and_fail2
;
1190 len
= sp
.buf
+ sp
.len
- np
;
1191 if (len
< second
- name
&&
1192 !strncmp(np
, name
, len
) &&
1193 isspace(name
[len
])) {
1195 strbuf_remove(&sp
, 0, np
- sp
.buf
);
1196 return strbuf_detach(&sp
, NULL
);
1200 strbuf_release(&sp
);
1206 * Accept a name only if it shows up twice, exactly the same
1209 second
= strchr(name
, '\n');
1212 line_len
= second
- name
;
1213 for (len
= 0 ; ; len
++) {
1214 switch (name
[len
]) {
1219 case '\t': case ' ':
1220 second
= stop_at_slash(name
+ len
, line_len
- len
);
1224 if (second
[len
] == '\n' && !strncmp(name
, second
, len
)) {
1225 return xmemdupz(name
, len
);
1231 /* Verify that we recognize the lines following a git header */
1232 static int parse_git_header(const char *line
, int len
, unsigned int size
, struct patch
*patch
)
1234 unsigned long offset
;
1236 /* A git diff has explicit new/delete information, so we don't guess */
1238 patch
->is_delete
= 0;
1241 * Some things may not have the old name in the
1242 * rest of the headers anywhere (pure mode changes,
1243 * or removing or adding empty files), so we get
1244 * the default name from the header.
1246 patch
->def_name
= git_header_name(line
, len
);
1247 if (patch
->def_name
&& root
) {
1248 char *s
= xmalloc(root_len
+ strlen(patch
->def_name
) + 1);
1250 strcpy(s
+ root_len
, patch
->def_name
);
1251 free(patch
->def_name
);
1252 patch
->def_name
= s
;
1258 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1259 static const struct opentry
{
1261 int (*fn
)(const char *, struct patch
*);
1263 { "@@ -", gitdiff_hdrend
},
1264 { "--- ", gitdiff_oldname
},
1265 { "+++ ", gitdiff_newname
},
1266 { "old mode ", gitdiff_oldmode
},
1267 { "new mode ", gitdiff_newmode
},
1268 { "deleted file mode ", gitdiff_delete
},
1269 { "new file mode ", gitdiff_newfile
},
1270 { "copy from ", gitdiff_copysrc
},
1271 { "copy to ", gitdiff_copydst
},
1272 { "rename old ", gitdiff_renamesrc
},
1273 { "rename new ", gitdiff_renamedst
},
1274 { "rename from ", gitdiff_renamesrc
},
1275 { "rename to ", gitdiff_renamedst
},
1276 { "similarity index ", gitdiff_similarity
},
1277 { "dissimilarity index ", gitdiff_dissimilarity
},
1278 { "index ", gitdiff_index
},
1279 { "", gitdiff_unrecognized
},
1283 len
= linelen(line
, size
);
1284 if (!len
|| line
[len
-1] != '\n')
1286 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
1287 const struct opentry
*p
= optable
+ i
;
1288 int oplen
= strlen(p
->str
);
1289 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
1291 if (p
->fn(line
+ oplen
, patch
) < 0)
1300 static int parse_num(const char *line
, unsigned long *p
)
1304 if (!isdigit(*line
))
1306 *p
= strtoul(line
, &ptr
, 10);
1310 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
1311 unsigned long *p1
, unsigned long *p2
)
1315 if (offset
< 0 || offset
>= len
)
1320 digits
= parse_num(line
, p1
);
1330 digits
= parse_num(line
+1, p2
);
1339 ex
= strlen(expect
);
1342 if (memcmp(line
, expect
, ex
))
1348 static void recount_diff(const char *line
, int size
, struct fragment
*fragment
)
1350 int oldlines
= 0, newlines
= 0, ret
= 0;
1353 warning("recount: ignore empty hunk");
1358 int len
= linelen(line
, size
);
1366 case ' ': case '\n':
1378 ret
= size
< 3 || prefixcmp(line
, "@@ ");
1381 ret
= size
< 5 || prefixcmp(line
, "diff ");
1388 warning(_("recount: unexpected line: %.*s"),
1389 (int)linelen(line
, size
), line
);
1394 fragment
->oldlines
= oldlines
;
1395 fragment
->newlines
= newlines
;
1399 * Parse a unified diff fragment header of the
1400 * form "@@ -a,b +c,d @@"
1402 static int parse_fragment_header(const char *line
, int len
, struct fragment
*fragment
)
1406 if (!len
|| line
[len
-1] != '\n')
1409 /* Figure out the number of lines in a fragment */
1410 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
1411 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
1416 static int find_header(const char *line
, unsigned long size
, int *hdrsize
, struct patch
*patch
)
1418 unsigned long offset
, len
;
1420 patch
->is_toplevel_relative
= 0;
1421 patch
->is_rename
= patch
->is_copy
= 0;
1422 patch
->is_new
= patch
->is_delete
= -1;
1423 patch
->old_mode
= patch
->new_mode
= 0;
1424 patch
->old_name
= patch
->new_name
= NULL
;
1425 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1426 unsigned long nextlen
;
1428 len
= linelen(line
, size
);
1432 /* Testing this early allows us to take a few shortcuts.. */
1437 * Make sure we don't find any unconnected patch fragments.
1438 * That's a sign that we didn't find a header, and that a
1439 * patch has become corrupted/broken up.
1441 if (!memcmp("@@ -", line
, 4)) {
1442 struct fragment dummy
;
1443 if (parse_fragment_header(line
, len
, &dummy
) < 0)
1445 die(_("patch fragment without header at line %d: %.*s"),
1446 linenr
, (int)len
-1, line
);
1453 * Git patch? It might not have a real patch, just a rename
1454 * or mode change, so we handle that specially
1456 if (!memcmp("diff --git ", line
, 11)) {
1457 int git_hdr_len
= parse_git_header(line
, len
, size
, patch
);
1458 if (git_hdr_len
<= len
)
1460 if (!patch
->old_name
&& !patch
->new_name
) {
1461 if (!patch
->def_name
)
1462 die(Q_("git diff header lacks filename information when removing "
1463 "%d leading pathname component (line %d)",
1464 "git diff header lacks filename information when removing "
1465 "%d leading pathname components (line %d)",
1468 patch
->old_name
= xstrdup(patch
->def_name
);
1469 patch
->new_name
= xstrdup(patch
->def_name
);
1471 if (!patch
->is_delete
&& !patch
->new_name
)
1472 die("git diff header lacks filename information "
1473 "(line %d)", linenr
);
1474 patch
->is_toplevel_relative
= 1;
1475 *hdrsize
= git_hdr_len
;
1479 /* --- followed by +++ ? */
1480 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
1484 * We only accept unified patches, so we want it to
1485 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1486 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1488 nextlen
= linelen(line
+ len
, size
- len
);
1489 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
1492 /* Ok, we'll consider it a patch */
1493 parse_traditional_patch(line
, line
+len
, patch
);
1494 *hdrsize
= len
+ nextlen
;
1501 static void record_ws_error(unsigned result
, const char *line
, int len
, int linenr
)
1509 if (squelch_whitespace_errors
&&
1510 squelch_whitespace_errors
< whitespace_error
)
1513 err
= whitespace_error_string(result
);
1514 fprintf(stderr
, "%s:%d: %s.\n%.*s\n",
1515 patch_input_file
, linenr
, err
, len
, line
);
1519 static void check_whitespace(const char *line
, int len
, unsigned ws_rule
)
1521 unsigned result
= ws_check(line
+ 1, len
- 1, ws_rule
);
1523 record_ws_error(result
, line
+ 1, len
- 2, linenr
);
1527 * Parse a unified diff. Note that this really needs to parse each
1528 * fragment separately, since the only way to know the difference
1529 * between a "---" that is part of a patch, and a "---" that starts
1530 * the next patch is to look at the line counts..
1532 static int parse_fragment(const char *line
, unsigned long size
,
1533 struct patch
*patch
, struct fragment
*fragment
)
1536 int len
= linelen(line
, size
), offset
;
1537 unsigned long oldlines
, newlines
;
1538 unsigned long leading
, trailing
;
1540 offset
= parse_fragment_header(line
, len
, fragment
);
1543 if (offset
> 0 && patch
->recount
)
1544 recount_diff(line
+ offset
, size
- offset
, fragment
);
1545 oldlines
= fragment
->oldlines
;
1546 newlines
= fragment
->newlines
;
1550 /* Parse the thing.. */
1554 added
= deleted
= 0;
1557 offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1558 if (!oldlines
&& !newlines
)
1560 len
= linelen(line
, size
);
1561 if (!len
|| line
[len
-1] != '\n')
1566 case '\n': /* newer GNU diff, an empty context line */
1570 if (!deleted
&& !added
)
1575 if (apply_in_reverse
&&
1576 ws_error_action
!= nowarn_ws_error
)
1577 check_whitespace(line
, len
, patch
->ws_rule
);
1583 if (!apply_in_reverse
&&
1584 ws_error_action
!= nowarn_ws_error
)
1585 check_whitespace(line
, len
, patch
->ws_rule
);
1592 * We allow "\ No newline at end of file". Depending
1593 * on locale settings when the patch was produced we
1594 * don't know what this line looks like. The only
1595 * thing we do know is that it begins with "\ ".
1596 * Checking for 12 is just for sanity check -- any
1597 * l10n of "\ No newline..." is at least that long.
1600 if (len
< 12 || memcmp(line
, "\\ ", 2))
1605 if (oldlines
|| newlines
)
1607 fragment
->leading
= leading
;
1608 fragment
->trailing
= trailing
;
1611 * If a fragment ends with an incomplete line, we failed to include
1612 * it in the above loop because we hit oldlines == newlines == 0
1615 if (12 < size
&& !memcmp(line
, "\\ ", 2))
1616 offset
+= linelen(line
, size
);
1618 patch
->lines_added
+= added
;
1619 patch
->lines_deleted
+= deleted
;
1621 if (0 < patch
->is_new
&& oldlines
)
1622 return error(_("new file depends on old contents"));
1623 if (0 < patch
->is_delete
&& newlines
)
1624 return error(_("deleted file still has contents"));
1629 * We have seen "diff --git a/... b/..." header (or a traditional patch
1630 * header). Read hunks that belong to this patch into fragments and hang
1631 * them to the given patch structure.
1633 * The (fragment->patch, fragment->size) pair points into the memory given
1634 * by the caller, not a copy, when we return.
1636 static int parse_single_patch(const char *line
, unsigned long size
, struct patch
*patch
)
1638 unsigned long offset
= 0;
1639 unsigned long oldlines
= 0, newlines
= 0, context
= 0;
1640 struct fragment
**fragp
= &patch
->fragments
;
1642 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
1643 struct fragment
*fragment
;
1646 fragment
= xcalloc(1, sizeof(*fragment
));
1647 fragment
->linenr
= linenr
;
1648 len
= parse_fragment(line
, size
, patch
, fragment
);
1650 die(_("corrupt patch at line %d"), linenr
);
1651 fragment
->patch
= line
;
1652 fragment
->size
= len
;
1653 oldlines
+= fragment
->oldlines
;
1654 newlines
+= fragment
->newlines
;
1655 context
+= fragment
->leading
+ fragment
->trailing
;
1658 fragp
= &fragment
->next
;
1666 * If something was removed (i.e. we have old-lines) it cannot
1667 * be creation, and if something was added it cannot be
1668 * deletion. However, the reverse is not true; --unified=0
1669 * patches that only add are not necessarily creation even
1670 * though they do not have any old lines, and ones that only
1671 * delete are not necessarily deletion.
1673 * Unfortunately, a real creation/deletion patch do _not_ have
1674 * any context line by definition, so we cannot safely tell it
1675 * apart with --unified=0 insanity. At least if the patch has
1676 * more than one hunk it is not creation or deletion.
1678 if (patch
->is_new
< 0 &&
1679 (oldlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1681 if (patch
->is_delete
< 0 &&
1682 (newlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1683 patch
->is_delete
= 0;
1685 if (0 < patch
->is_new
&& oldlines
)
1686 die(_("new file %s depends on old contents"), patch
->new_name
);
1687 if (0 < patch
->is_delete
&& newlines
)
1688 die(_("deleted file %s still has contents"), patch
->old_name
);
1689 if (!patch
->is_delete
&& !newlines
&& context
)
1692 "file %s becomes empty but is not deleted"),
1698 static inline int metadata_changes(struct patch
*patch
)
1700 return patch
->is_rename
> 0 ||
1701 patch
->is_copy
> 0 ||
1702 patch
->is_new
> 0 ||
1704 (patch
->old_mode
&& patch
->new_mode
&&
1705 patch
->old_mode
!= patch
->new_mode
);
1708 static char *inflate_it(const void *data
, unsigned long size
,
1709 unsigned long inflated_size
)
1715 memset(&stream
, 0, sizeof(stream
));
1717 stream
.next_in
= (unsigned char *)data
;
1718 stream
.avail_in
= size
;
1719 stream
.next_out
= out
= xmalloc(inflated_size
);
1720 stream
.avail_out
= inflated_size
;
1721 git_inflate_init(&stream
);
1722 st
= git_inflate(&stream
, Z_FINISH
);
1723 git_inflate_end(&stream
);
1724 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1732 * Read a binary hunk and return a new fragment; fragment->patch
1733 * points at an allocated memory that the caller must free, so
1734 * it is marked as "->free_patch = 1".
1736 static struct fragment
*parse_binary_hunk(char **buf_p
,
1737 unsigned long *sz_p
,
1742 * Expect a line that begins with binary patch method ("literal"
1743 * or "delta"), followed by the length of data before deflating.
1744 * a sequence of 'length-byte' followed by base-85 encoded data
1745 * should follow, terminated by a newline.
1747 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1748 * and we would limit the patch line to 66 characters,
1749 * so one line can fit up to 13 groups that would decode
1750 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1751 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1754 unsigned long size
= *sz_p
;
1755 char *buffer
= *buf_p
;
1757 unsigned long origlen
;
1760 struct fragment
*frag
;
1762 llen
= linelen(buffer
, size
);
1767 if (!prefixcmp(buffer
, "delta ")) {
1768 patch_method
= BINARY_DELTA_DEFLATED
;
1769 origlen
= strtoul(buffer
+ 6, NULL
, 10);
1771 else if (!prefixcmp(buffer
, "literal ")) {
1772 patch_method
= BINARY_LITERAL_DEFLATED
;
1773 origlen
= strtoul(buffer
+ 8, NULL
, 10);
1781 int byte_length
, max_byte_length
, newsize
;
1782 llen
= linelen(buffer
, size
);
1786 /* consume the blank line */
1792 * Minimum line is "A00000\n" which is 7-byte long,
1793 * and the line length must be multiple of 5 plus 2.
1795 if ((llen
< 7) || (llen
-2) % 5)
1797 max_byte_length
= (llen
- 2) / 5 * 4;
1798 byte_length
= *buffer
;
1799 if ('A' <= byte_length
&& byte_length
<= 'Z')
1800 byte_length
= byte_length
- 'A' + 1;
1801 else if ('a' <= byte_length
&& byte_length
<= 'z')
1802 byte_length
= byte_length
- 'a' + 27;
1805 /* if the input length was not multiple of 4, we would
1806 * have filler at the end but the filler should never
1809 if (max_byte_length
< byte_length
||
1810 byte_length
<= max_byte_length
- 4)
1812 newsize
= hunk_size
+ byte_length
;
1813 data
= xrealloc(data
, newsize
);
1814 if (decode_85(data
+ hunk_size
, buffer
+ 1, byte_length
))
1816 hunk_size
= newsize
;
1821 frag
= xcalloc(1, sizeof(*frag
));
1822 frag
->patch
= inflate_it(data
, hunk_size
, origlen
);
1823 frag
->free_patch
= 1;
1827 frag
->size
= origlen
;
1831 frag
->binary_patch_method
= patch_method
;
1837 error(_("corrupt binary patch at line %d: %.*s"),
1838 linenr
-1, llen
-1, buffer
);
1842 static int parse_binary(char *buffer
, unsigned long size
, struct patch
*patch
)
1845 * We have read "GIT binary patch\n"; what follows is a line
1846 * that says the patch method (currently, either "literal" or
1847 * "delta") and the length of data before deflating; a
1848 * sequence of 'length-byte' followed by base-85 encoded data
1851 * When a binary patch is reversible, there is another binary
1852 * hunk in the same format, starting with patch method (either
1853 * "literal" or "delta") with the length of data, and a sequence
1854 * of length-byte + base-85 encoded data, terminated with another
1855 * empty line. This data, when applied to the postimage, produces
1858 struct fragment
*forward
;
1859 struct fragment
*reverse
;
1863 forward
= parse_binary_hunk(&buffer
, &size
, &status
, &used
);
1864 if (!forward
&& !status
)
1865 /* there has to be one hunk (forward hunk) */
1866 return error(_("unrecognized binary patch at line %d"), linenr
-1);
1868 /* otherwise we already gave an error message */
1871 reverse
= parse_binary_hunk(&buffer
, &size
, &status
, &used_1
);
1876 * Not having reverse hunk is not an error, but having
1877 * a corrupt reverse hunk is.
1879 free((void*) forward
->patch
);
1883 forward
->next
= reverse
;
1884 patch
->fragments
= forward
;
1885 patch
->is_binary
= 1;
1890 * Read the patch text in "buffer" taht extends for "size" bytes; stop
1891 * reading after seeing a single patch (i.e. changes to a single file).
1892 * Create fragments (i.e. patch hunks) and hang them to the given patch.
1893 * Return the number of bytes consumed, so that the caller can call us
1894 * again for the next patch.
1896 static int parse_chunk(char *buffer
, unsigned long size
, struct patch
*patch
)
1898 int hdrsize
, patchsize
;
1899 int offset
= find_header(buffer
, size
, &hdrsize
, patch
);
1904 patch
->ws_rule
= whitespace_rule(patch
->new_name
1908 patchsize
= parse_single_patch(buffer
+ offset
+ hdrsize
,
1909 size
- offset
- hdrsize
, patch
);
1912 static const char *binhdr
[] = {
1917 static const char git_binary
[] = "GIT binary patch\n";
1919 int hd
= hdrsize
+ offset
;
1920 unsigned long llen
= linelen(buffer
+ hd
, size
- hd
);
1922 if (llen
== sizeof(git_binary
) - 1 &&
1923 !memcmp(git_binary
, buffer
+ hd
, llen
)) {
1926 used
= parse_binary(buffer
+ hd
+ llen
,
1927 size
- hd
- llen
, patch
);
1929 patchsize
= used
+ llen
;
1933 else if (!memcmp(" differ\n", buffer
+ hd
+ llen
- 8, 8)) {
1934 for (i
= 0; binhdr
[i
]; i
++) {
1935 int len
= strlen(binhdr
[i
]);
1936 if (len
< size
- hd
&&
1937 !memcmp(binhdr
[i
], buffer
+ hd
, len
)) {
1939 patch
->is_binary
= 1;
1946 /* Empty patch cannot be applied if it is a text patch
1947 * without metadata change. A binary patch appears
1950 if ((apply
|| check
) &&
1951 (!patch
->is_binary
&& !metadata_changes(patch
)))
1952 die(_("patch with only garbage at line %d"), linenr
);
1955 return offset
+ hdrsize
+ patchsize
;
1958 #define swap(a,b) myswap((a),(b),sizeof(a))
1960 #define myswap(a, b, size) do { \
1961 unsigned char mytmp[size]; \
1962 memcpy(mytmp, &a, size); \
1963 memcpy(&a, &b, size); \
1964 memcpy(&b, mytmp, size); \
1967 static void reverse_patches(struct patch
*p
)
1969 for (; p
; p
= p
->next
) {
1970 struct fragment
*frag
= p
->fragments
;
1972 swap(p
->new_name
, p
->old_name
);
1973 swap(p
->new_mode
, p
->old_mode
);
1974 swap(p
->is_new
, p
->is_delete
);
1975 swap(p
->lines_added
, p
->lines_deleted
);
1976 swap(p
->old_sha1_prefix
, p
->new_sha1_prefix
);
1978 for (; frag
; frag
= frag
->next
) {
1979 swap(frag
->newpos
, frag
->oldpos
);
1980 swap(frag
->newlines
, frag
->oldlines
);
1985 static const char pluses
[] =
1986 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1987 static const char minuses
[]=
1988 "----------------------------------------------------------------------";
1990 static void show_stats(struct patch
*patch
)
1992 struct strbuf qname
= STRBUF_INIT
;
1993 char *cp
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
1996 quote_c_style(cp
, &qname
, NULL
, 0);
1999 * "scale" the filename
2005 if (qname
.len
> max
) {
2006 cp
= strchr(qname
.buf
+ qname
.len
+ 3 - max
, '/');
2008 cp
= qname
.buf
+ qname
.len
+ 3 - max
;
2009 strbuf_splice(&qname
, 0, cp
- qname
.buf
, "...", 3);
2012 if (patch
->is_binary
) {
2013 printf(" %-*s | Bin\n", max
, qname
.buf
);
2014 strbuf_release(&qname
);
2018 printf(" %-*s |", max
, qname
.buf
);
2019 strbuf_release(&qname
);
2022 * scale the add/delete
2024 max
= max
+ max_change
> 70 ? 70 - max
: max_change
;
2025 add
= patch
->lines_added
;
2026 del
= patch
->lines_deleted
;
2028 if (max_change
> 0) {
2029 int total
= ((add
+ del
) * max
+ max_change
/ 2) / max_change
;
2030 add
= (add
* max
+ max_change
/ 2) / max_change
;
2033 printf("%5d %.*s%.*s\n", patch
->lines_added
+ patch
->lines_deleted
,
2034 add
, pluses
, del
, minuses
);
2037 static int read_old_data(struct stat
*st
, const char *path
, struct strbuf
*buf
)
2039 switch (st
->st_mode
& S_IFMT
) {
2041 if (strbuf_readlink(buf
, path
, st
->st_size
) < 0)
2042 return error(_("unable to read symlink %s"), path
);
2045 if (strbuf_read_file(buf
, path
, st
->st_size
) != st
->st_size
)
2046 return error(_("unable to open or read %s"), path
);
2047 convert_to_git(path
, buf
->buf
, buf
->len
, buf
, 0);
2055 * Update the preimage, and the common lines in postimage,
2056 * from buffer buf of length len. If postlen is 0 the postimage
2057 * is updated in place, otherwise it's updated on a new buffer
2061 static void update_pre_post_images(struct image
*preimage
,
2062 struct image
*postimage
,
2064 size_t len
, size_t postlen
)
2067 char *new, *old
, *fixed
;
2068 struct image fixed_preimage
;
2071 * Update the preimage with whitespace fixes. Note that we
2072 * are not losing preimage->buf -- apply_one_fragment() will
2075 prepare_image(&fixed_preimage
, buf
, len
, 1);
2076 assert(fixed_preimage
.nr
== preimage
->nr
);
2077 for (i
= 0; i
< preimage
->nr
; i
++)
2078 fixed_preimage
.line
[i
].flag
= preimage
->line
[i
].flag
;
2079 free(preimage
->line_allocated
);
2080 *preimage
= fixed_preimage
;
2083 * Adjust the common context lines in postimage. This can be
2084 * done in-place when we are just doing whitespace fixing,
2085 * which does not make the string grow, but needs a new buffer
2086 * when ignoring whitespace causes the update, since in this case
2087 * we could have e.g. tabs converted to multiple spaces.
2088 * We trust the caller to tell us if the update can be done
2089 * in place (postlen==0) or not.
2091 old
= postimage
->buf
;
2093 new = postimage
->buf
= xmalloc(postlen
);
2096 fixed
= preimage
->buf
;
2097 for (i
= ctx
= 0; i
< postimage
->nr
; i
++) {
2098 size_t len
= postimage
->line
[i
].len
;
2099 if (!(postimage
->line
[i
].flag
& LINE_COMMON
)) {
2100 /* an added line -- no counterparts in preimage */
2101 memmove(new, old
, len
);
2107 /* a common context -- skip it in the original postimage */
2110 /* and find the corresponding one in the fixed preimage */
2111 while (ctx
< preimage
->nr
&&
2112 !(preimage
->line
[ctx
].flag
& LINE_COMMON
)) {
2113 fixed
+= preimage
->line
[ctx
].len
;
2116 if (preimage
->nr
<= ctx
)
2119 /* and copy it in, while fixing the line length */
2120 len
= preimage
->line
[ctx
].len
;
2121 memcpy(new, fixed
, len
);
2124 postimage
->line
[i
].len
= len
;
2128 /* Fix the length of the whole thing */
2129 postimage
->len
= new - postimage
->buf
;
2132 static int match_fragment(struct image
*img
,
2133 struct image
*preimage
,
2134 struct image
*postimage
,
2138 int match_beginning
, int match_end
)
2141 char *fixed_buf
, *buf
, *orig
, *target
;
2142 struct strbuf fixed
;
2146 if (preimage
->nr
+ try_lno
<= img
->nr
) {
2148 * The hunk falls within the boundaries of img.
2150 preimage_limit
= preimage
->nr
;
2151 if (match_end
&& (preimage
->nr
+ try_lno
!= img
->nr
))
2153 } else if (ws_error_action
== correct_ws_error
&&
2154 (ws_rule
& WS_BLANK_AT_EOF
)) {
2156 * This hunk extends beyond the end of img, and we are
2157 * removing blank lines at the end of the file. This
2158 * many lines from the beginning of the preimage must
2159 * match with img, and the remainder of the preimage
2162 preimage_limit
= img
->nr
- try_lno
;
2165 * The hunk extends beyond the end of the img and
2166 * we are not removing blanks at the end, so we
2167 * should reject the hunk at this position.
2172 if (match_beginning
&& try_lno
)
2175 /* Quick hash check */
2176 for (i
= 0; i
< preimage_limit
; i
++)
2177 if ((img
->line
[try_lno
+ i
].flag
& LINE_PATCHED
) ||
2178 (preimage
->line
[i
].hash
!= img
->line
[try_lno
+ i
].hash
))
2181 if (preimage_limit
== preimage
->nr
) {
2183 * Do we have an exact match? If we were told to match
2184 * at the end, size must be exactly at try+fragsize,
2185 * otherwise try+fragsize must be still within the preimage,
2186 * and either case, the old piece should match the preimage
2190 ? (try + preimage
->len
== img
->len
)
2191 : (try + preimage
->len
<= img
->len
)) &&
2192 !memcmp(img
->buf
+ try, preimage
->buf
, preimage
->len
))
2196 * The preimage extends beyond the end of img, so
2197 * there cannot be an exact match.
2199 * There must be one non-blank context line that match
2200 * a line before the end of img.
2204 buf
= preimage
->buf
;
2206 for (i
= 0; i
< preimage_limit
; i
++)
2207 buf_end
+= preimage
->line
[i
].len
;
2209 for ( ; buf
< buf_end
; buf
++)
2217 * No exact match. If we are ignoring whitespace, run a line-by-line
2218 * fuzzy matching. We collect all the line length information because
2219 * we need it to adjust whitespace if we match.
2221 if (ws_ignore_action
== ignore_ws_change
) {
2224 size_t postlen
= postimage
->len
;
2228 for (i
= 0; i
< preimage_limit
; i
++) {
2229 size_t prelen
= preimage
->line
[i
].len
;
2230 size_t imglen
= img
->line
[try_lno
+i
].len
;
2232 if (!fuzzy_matchlines(img
->buf
+ try + imgoff
, imglen
,
2233 preimage
->buf
+ preoff
, prelen
))
2235 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2236 postlen
+= imglen
- prelen
;
2242 * Ok, the preimage matches with whitespace fuzz.
2244 * imgoff now holds the true length of the target that
2245 * matches the preimage before the end of the file.
2247 * Count the number of characters in the preimage that fall
2248 * beyond the end of the file and make sure that all of them
2249 * are whitespace characters. (This can only happen if
2250 * we are removing blank lines at the end of the file.)
2252 buf
= preimage_eof
= preimage
->buf
+ preoff
;
2253 for ( ; i
< preimage
->nr
; i
++)
2254 preoff
+= preimage
->line
[i
].len
;
2255 preimage_end
= preimage
->buf
+ preoff
;
2256 for ( ; buf
< preimage_end
; buf
++)
2261 * Update the preimage and the common postimage context
2262 * lines to use the same whitespace as the target.
2263 * If whitespace is missing in the target (i.e.
2264 * if the preimage extends beyond the end of the file),
2265 * use the whitespace from the preimage.
2267 extra_chars
= preimage_end
- preimage_eof
;
2268 strbuf_init(&fixed
, imgoff
+ extra_chars
);
2269 strbuf_add(&fixed
, img
->buf
+ try, imgoff
);
2270 strbuf_add(&fixed
, preimage_eof
, extra_chars
);
2271 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2272 update_pre_post_images(preimage
, postimage
,
2273 fixed_buf
, fixed_len
, postlen
);
2277 if (ws_error_action
!= correct_ws_error
)
2281 * The hunk does not apply byte-by-byte, but the hash says
2282 * it might with whitespace fuzz. We haven't been asked to
2283 * ignore whitespace, we were asked to correct whitespace
2284 * errors, so let's try matching after whitespace correction.
2286 * The preimage may extend beyond the end of the file,
2287 * but in this loop we will only handle the part of the
2288 * preimage that falls within the file.
2290 strbuf_init(&fixed
, preimage
->len
+ 1);
2291 orig
= preimage
->buf
;
2292 target
= img
->buf
+ try;
2293 for (i
= 0; i
< preimage_limit
; i
++) {
2294 size_t oldlen
= preimage
->line
[i
].len
;
2295 size_t tgtlen
= img
->line
[try_lno
+ i
].len
;
2296 size_t fixstart
= fixed
.len
;
2297 struct strbuf tgtfix
;
2300 /* Try fixing the line in the preimage */
2301 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2303 /* Try fixing the line in the target */
2304 strbuf_init(&tgtfix
, tgtlen
);
2305 ws_fix_copy(&tgtfix
, target
, tgtlen
, ws_rule
, NULL
);
2308 * If they match, either the preimage was based on
2309 * a version before our tree fixed whitespace breakage,
2310 * or we are lacking a whitespace-fix patch the tree
2311 * the preimage was based on already had (i.e. target
2312 * has whitespace breakage, the preimage doesn't).
2313 * In either case, we are fixing the whitespace breakages
2314 * so we might as well take the fix together with their
2317 match
= (tgtfix
.len
== fixed
.len
- fixstart
&&
2318 !memcmp(tgtfix
.buf
, fixed
.buf
+ fixstart
,
2319 fixed
.len
- fixstart
));
2321 strbuf_release(&tgtfix
);
2331 * Now handle the lines in the preimage that falls beyond the
2332 * end of the file (if any). They will only match if they are
2333 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2336 for ( ; i
< preimage
->nr
; i
++) {
2337 size_t fixstart
= fixed
.len
; /* start of the fixed preimage */
2338 size_t oldlen
= preimage
->line
[i
].len
;
2341 /* Try fixing the line in the preimage */
2342 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2344 for (j
= fixstart
; j
< fixed
.len
; j
++)
2345 if (!isspace(fixed
.buf
[j
]))
2352 * Yes, the preimage is based on an older version that still
2353 * has whitespace breakages unfixed, and fixing them makes the
2354 * hunk match. Update the context lines in the postimage.
2356 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2357 update_pre_post_images(preimage
, postimage
,
2358 fixed_buf
, fixed_len
, 0);
2362 strbuf_release(&fixed
);
2366 static int find_pos(struct image
*img
,
2367 struct image
*preimage
,
2368 struct image
*postimage
,
2371 int match_beginning
, int match_end
)
2374 unsigned long backwards
, forwards
, try;
2375 int backwards_lno
, forwards_lno
, try_lno
;
2378 * If match_beginning or match_end is specified, there is no
2379 * point starting from a wrong line that will never match and
2380 * wander around and wait for a match at the specified end.
2382 if (match_beginning
)
2385 line
= img
->nr
- preimage
->nr
;
2388 * Because the comparison is unsigned, the following test
2389 * will also take care of a negative line number that can
2390 * result when match_end and preimage is larger than the target.
2392 if ((size_t) line
> img
->nr
)
2396 for (i
= 0; i
< line
; i
++)
2397 try += img
->line
[i
].len
;
2400 * There's probably some smart way to do this, but I'll leave
2401 * that to the smart and beautiful people. I'm simple and stupid.
2404 backwards_lno
= line
;
2406 forwards_lno
= line
;
2409 for (i
= 0; ; i
++) {
2410 if (match_fragment(img
, preimage
, postimage
,
2411 try, try_lno
, ws_rule
,
2412 match_beginning
, match_end
))
2416 if (backwards_lno
== 0 && forwards_lno
== img
->nr
)
2420 if (backwards_lno
== 0) {
2425 backwards
-= img
->line
[backwards_lno
].len
;
2427 try_lno
= backwards_lno
;
2429 if (forwards_lno
== img
->nr
) {
2433 forwards
+= img
->line
[forwards_lno
].len
;
2436 try_lno
= forwards_lno
;
2443 static void remove_first_line(struct image
*img
)
2445 img
->buf
+= img
->line
[0].len
;
2446 img
->len
-= img
->line
[0].len
;
2451 static void remove_last_line(struct image
*img
)
2453 img
->len
-= img
->line
[--img
->nr
].len
;
2457 * The change from "preimage" and "postimage" has been found to
2458 * apply at applied_pos (counts in line numbers) in "img".
2459 * Update "img" to remove "preimage" and replace it with "postimage".
2461 static void update_image(struct image
*img
,
2463 struct image
*preimage
,
2464 struct image
*postimage
)
2467 * remove the copy of preimage at offset in img
2468 * and replace it with postimage
2471 size_t remove_count
, insert_count
, applied_at
= 0;
2476 * If we are removing blank lines at the end of img,
2477 * the preimage may extend beyond the end.
2478 * If that is the case, we must be careful only to
2479 * remove the part of the preimage that falls within
2480 * the boundaries of img. Initialize preimage_limit
2481 * to the number of lines in the preimage that falls
2482 * within the boundaries.
2484 preimage_limit
= preimage
->nr
;
2485 if (preimage_limit
> img
->nr
- applied_pos
)
2486 preimage_limit
= img
->nr
- applied_pos
;
2488 for (i
= 0; i
< applied_pos
; i
++)
2489 applied_at
+= img
->line
[i
].len
;
2492 for (i
= 0; i
< preimage_limit
; i
++)
2493 remove_count
+= img
->line
[applied_pos
+ i
].len
;
2494 insert_count
= postimage
->len
;
2496 /* Adjust the contents */
2497 result
= xmalloc(img
->len
+ insert_count
- remove_count
+ 1);
2498 memcpy(result
, img
->buf
, applied_at
);
2499 memcpy(result
+ applied_at
, postimage
->buf
, postimage
->len
);
2500 memcpy(result
+ applied_at
+ postimage
->len
,
2501 img
->buf
+ (applied_at
+ remove_count
),
2502 img
->len
- (applied_at
+ remove_count
));
2505 img
->len
+= insert_count
- remove_count
;
2506 result
[img
->len
] = '\0';
2508 /* Adjust the line table */
2509 nr
= img
->nr
+ postimage
->nr
- preimage_limit
;
2510 if (preimage_limit
< postimage
->nr
) {
2512 * NOTE: this knows that we never call remove_first_line()
2513 * on anything other than pre/post image.
2515 img
->line
= xrealloc(img
->line
, nr
* sizeof(*img
->line
));
2516 img
->line_allocated
= img
->line
;
2518 if (preimage_limit
!= postimage
->nr
)
2519 memmove(img
->line
+ applied_pos
+ postimage
->nr
,
2520 img
->line
+ applied_pos
+ preimage_limit
,
2521 (img
->nr
- (applied_pos
+ preimage_limit
)) *
2522 sizeof(*img
->line
));
2523 memcpy(img
->line
+ applied_pos
,
2525 postimage
->nr
* sizeof(*img
->line
));
2527 for (i
= 0; i
< postimage
->nr
; i
++)
2528 img
->line
[applied_pos
+ i
].flag
|= LINE_PATCHED
;
2533 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2534 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2535 * replace the part of "img" with "postimage" text.
2537 static int apply_one_fragment(struct image
*img
, struct fragment
*frag
,
2538 int inaccurate_eof
, unsigned ws_rule
,
2541 int match_beginning
, match_end
;
2542 const char *patch
= frag
->patch
;
2543 int size
= frag
->size
;
2544 char *old
, *oldlines
;
2545 struct strbuf newlines
;
2546 int new_blank_lines_at_end
= 0;
2547 int found_new_blank_lines_at_end
= 0;
2548 int hunk_linenr
= frag
->linenr
;
2549 unsigned long leading
, trailing
;
2550 int pos
, applied_pos
;
2551 struct image preimage
;
2552 struct image postimage
;
2554 memset(&preimage
, 0, sizeof(preimage
));
2555 memset(&postimage
, 0, sizeof(postimage
));
2556 oldlines
= xmalloc(size
);
2557 strbuf_init(&newlines
, size
);
2562 int len
= linelen(patch
, size
);
2564 int added_blank_line
= 0;
2565 int is_blank_context
= 0;
2572 * "plen" is how much of the line we should use for
2573 * the actual patch data. Normally we just remove the
2574 * first character on the line, but if the line is
2575 * followed by "\ No newline", then we also remove the
2576 * last one (which is the newline, of course).
2579 if (len
< size
&& patch
[len
] == '\\')
2582 if (apply_in_reverse
) {
2585 else if (first
== '+')
2591 /* Newer GNU diff, empty context line */
2593 /* ... followed by '\No newline'; nothing */
2596 strbuf_addch(&newlines
, '\n');
2597 add_line_info(&preimage
, "\n", 1, LINE_COMMON
);
2598 add_line_info(&postimage
, "\n", 1, LINE_COMMON
);
2599 is_blank_context
= 1;
2602 if (plen
&& (ws_rule
& WS_BLANK_AT_EOF
) &&
2603 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2604 is_blank_context
= 1;
2606 memcpy(old
, patch
+ 1, plen
);
2607 add_line_info(&preimage
, old
, plen
,
2608 (first
== ' ' ? LINE_COMMON
: 0));
2612 /* Fall-through for ' ' */
2614 /* --no-add does not add new lines */
2615 if (first
== '+' && no_add
)
2618 start
= newlines
.len
;
2620 !whitespace_error
||
2621 ws_error_action
!= correct_ws_error
) {
2622 strbuf_add(&newlines
, patch
+ 1, plen
);
2625 ws_fix_copy(&newlines
, patch
+ 1, plen
, ws_rule
, &applied_after_fixing_ws
);
2627 add_line_info(&postimage
, newlines
.buf
+ start
, newlines
.len
- start
,
2628 (first
== '+' ? 0 : LINE_COMMON
));
2630 (ws_rule
& WS_BLANK_AT_EOF
) &&
2631 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2632 added_blank_line
= 1;
2634 case '@': case '\\':
2635 /* Ignore it, we already handled it */
2638 if (apply_verbosely
)
2639 error(_("invalid start of line: '%c'"), first
);
2642 if (added_blank_line
) {
2643 if (!new_blank_lines_at_end
)
2644 found_new_blank_lines_at_end
= hunk_linenr
;
2645 new_blank_lines_at_end
++;
2647 else if (is_blank_context
)
2650 new_blank_lines_at_end
= 0;
2655 if (inaccurate_eof
&&
2656 old
> oldlines
&& old
[-1] == '\n' &&
2657 newlines
.len
> 0 && newlines
.buf
[newlines
.len
- 1] == '\n') {
2659 strbuf_setlen(&newlines
, newlines
.len
- 1);
2662 leading
= frag
->leading
;
2663 trailing
= frag
->trailing
;
2666 * A hunk to change lines at the beginning would begin with
2668 * but we need to be careful. -U0 that inserts before the second
2669 * line also has this pattern.
2671 * And a hunk to add to an empty file would begin with
2674 * In other words, a hunk that is (frag->oldpos <= 1) with or
2675 * without leading context must match at the beginning.
2677 match_beginning
= (!frag
->oldpos
||
2678 (frag
->oldpos
== 1 && !unidiff_zero
));
2681 * A hunk without trailing lines must match at the end.
2682 * However, we simply cannot tell if a hunk must match end
2683 * from the lack of trailing lines if the patch was generated
2684 * with unidiff without any context.
2686 match_end
= !unidiff_zero
&& !trailing
;
2688 pos
= frag
->newpos
? (frag
->newpos
- 1) : 0;
2689 preimage
.buf
= oldlines
;
2690 preimage
.len
= old
- oldlines
;
2691 postimage
.buf
= newlines
.buf
;
2692 postimage
.len
= newlines
.len
;
2693 preimage
.line
= preimage
.line_allocated
;
2694 postimage
.line
= postimage
.line_allocated
;
2698 applied_pos
= find_pos(img
, &preimage
, &postimage
, pos
,
2699 ws_rule
, match_beginning
, match_end
);
2701 if (applied_pos
>= 0)
2704 /* Am I at my context limits? */
2705 if ((leading
<= p_context
) && (trailing
<= p_context
))
2707 if (match_beginning
|| match_end
) {
2708 match_beginning
= match_end
= 0;
2713 * Reduce the number of context lines; reduce both
2714 * leading and trailing if they are equal otherwise
2715 * just reduce the larger context.
2717 if (leading
>= trailing
) {
2718 remove_first_line(&preimage
);
2719 remove_first_line(&postimage
);
2723 if (trailing
> leading
) {
2724 remove_last_line(&preimage
);
2725 remove_last_line(&postimage
);
2730 if (applied_pos
>= 0) {
2731 if (new_blank_lines_at_end
&&
2732 preimage
.nr
+ applied_pos
>= img
->nr
&&
2733 (ws_rule
& WS_BLANK_AT_EOF
) &&
2734 ws_error_action
!= nowarn_ws_error
) {
2735 record_ws_error(WS_BLANK_AT_EOF
, "+", 1,
2736 found_new_blank_lines_at_end
);
2737 if (ws_error_action
== correct_ws_error
) {
2738 while (new_blank_lines_at_end
--)
2739 remove_last_line(&postimage
);
2742 * We would want to prevent write_out_results()
2743 * from taking place in apply_patch() that follows
2744 * the callchain led us here, which is:
2745 * apply_patch->check_patch_list->check_patch->
2746 * apply_data->apply_fragments->apply_one_fragment
2748 if (ws_error_action
== die_on_ws_error
)
2752 if (apply_verbosely
&& applied_pos
!= pos
) {
2753 int offset
= applied_pos
- pos
;
2754 if (apply_in_reverse
)
2755 offset
= 0 - offset
;
2757 Q_("Hunk #%d succeeded at %d (offset %d line).",
2758 "Hunk #%d succeeded at %d (offset %d lines).",
2760 nth_fragment
, applied_pos
+ 1, offset
);
2764 * Warn if it was necessary to reduce the number
2767 if ((leading
!= frag
->leading
) ||
2768 (trailing
!= frag
->trailing
))
2769 fprintf_ln(stderr
, _("Context reduced to (%ld/%ld)"
2770 " to apply fragment at %d"),
2771 leading
, trailing
, applied_pos
+1);
2772 update_image(img
, applied_pos
, &preimage
, &postimage
);
2774 if (apply_verbosely
)
2775 error(_("while searching for:\n%.*s"),
2776 (int)(old
- oldlines
), oldlines
);
2780 strbuf_release(&newlines
);
2781 free(preimage
.line_allocated
);
2782 free(postimage
.line_allocated
);
2784 return (applied_pos
< 0);
2787 static int apply_binary_fragment(struct image
*img
, struct patch
*patch
)
2789 struct fragment
*fragment
= patch
->fragments
;
2794 return error(_("missing binary patch data for '%s'"),
2799 /* Binary patch is irreversible without the optional second hunk */
2800 if (apply_in_reverse
) {
2801 if (!fragment
->next
)
2802 return error("cannot reverse-apply a binary patch "
2803 "without the reverse hunk to '%s'",
2805 ? patch
->new_name
: patch
->old_name
);
2806 fragment
= fragment
->next
;
2808 switch (fragment
->binary_patch_method
) {
2809 case BINARY_DELTA_DEFLATED
:
2810 dst
= patch_delta(img
->buf
, img
->len
, fragment
->patch
,
2811 fragment
->size
, &len
);
2818 case BINARY_LITERAL_DEFLATED
:
2820 img
->len
= fragment
->size
;
2821 img
->buf
= xmalloc(img
->len
+1);
2822 memcpy(img
->buf
, fragment
->patch
, img
->len
);
2823 img
->buf
[img
->len
] = '\0';
2830 * Replace "img" with the result of applying the binary patch.
2831 * The binary patch data itself in patch->fragment is still kept
2832 * but the preimage prepared by the caller in "img" is freed here
2833 * or in the helper function apply_binary_fragment() this calls.
2835 static int apply_binary(struct image
*img
, struct patch
*patch
)
2837 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
2838 unsigned char sha1
[20];
2841 * For safety, we require patch index line to contain
2842 * full 40-byte textual SHA1 for old and new, at least for now.
2844 if (strlen(patch
->old_sha1_prefix
) != 40 ||
2845 strlen(patch
->new_sha1_prefix
) != 40 ||
2846 get_sha1_hex(patch
->old_sha1_prefix
, sha1
) ||
2847 get_sha1_hex(patch
->new_sha1_prefix
, sha1
))
2848 return error("cannot apply binary patch to '%s' "
2849 "without full index line", name
);
2851 if (patch
->old_name
) {
2853 * See if the old one matches what the patch
2856 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
2857 if (strcmp(sha1_to_hex(sha1
), patch
->old_sha1_prefix
))
2858 return error("the patch applies to '%s' (%s), "
2859 "which does not match the "
2860 "current contents.",
2861 name
, sha1_to_hex(sha1
));
2864 /* Otherwise, the old one must be empty. */
2866 return error("the patch applies to an empty "
2867 "'%s' but it is not empty", name
);
2870 get_sha1_hex(patch
->new_sha1_prefix
, sha1
);
2871 if (is_null_sha1(sha1
)) {
2873 return 0; /* deletion patch */
2876 if (has_sha1_file(sha1
)) {
2877 /* We already have the postimage */
2878 enum object_type type
;
2882 result
= read_sha1_file(sha1
, &type
, &size
);
2884 return error("the necessary postimage %s for "
2885 "'%s' cannot be read",
2886 patch
->new_sha1_prefix
, name
);
2892 * We have verified buf matches the preimage;
2893 * apply the patch data to it, which is stored
2894 * in the patch->fragments->{patch,size}.
2896 if (apply_binary_fragment(img
, patch
))
2897 return error(_("binary patch does not apply to '%s'"),
2900 /* verify that the result matches */
2901 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
2902 if (strcmp(sha1_to_hex(sha1
), patch
->new_sha1_prefix
))
2903 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
2904 name
, patch
->new_sha1_prefix
, sha1_to_hex(sha1
));
2910 static int apply_fragments(struct image
*img
, struct patch
*patch
)
2912 struct fragment
*frag
= patch
->fragments
;
2913 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
2914 unsigned ws_rule
= patch
->ws_rule
;
2915 unsigned inaccurate_eof
= patch
->inaccurate_eof
;
2918 if (patch
->is_binary
)
2919 return apply_binary(img
, patch
);
2923 if (apply_one_fragment(img
, frag
, inaccurate_eof
, ws_rule
, nth
)) {
2924 error(_("patch failed: %s:%ld"), name
, frag
->oldpos
);
2925 if (!apply_with_reject
)
2934 static int read_blob_object(struct strbuf
*buf
, const unsigned char *sha1
, unsigned mode
)
2936 if (S_ISGITLINK(mode
)) {
2937 strbuf_grow(buf
, 100);
2938 strbuf_addf(buf
, "Subproject commit %s\n", sha1_to_hex(sha1
));
2940 enum object_type type
;
2944 result
= read_sha1_file(sha1
, &type
, &sz
);
2947 /* XXX read_sha1_file NUL-terminates */
2948 strbuf_attach(buf
, result
, sz
, sz
+ 1);
2953 static int read_file_or_gitlink(struct cache_entry
*ce
, struct strbuf
*buf
)
2957 return read_blob_object(buf
, ce
->sha1
, ce
->ce_mode
);
2960 static struct patch
*in_fn_table(const char *name
)
2962 struct string_list_item
*item
;
2967 item
= string_list_lookup(&fn_table
, name
);
2969 return (struct patch
*)item
->util
;
2975 * item->util in the filename table records the status of the path.
2976 * Usually it points at a patch (whose result records the contents
2977 * of it after applying it), but it could be PATH_WAS_DELETED for a
2978 * path that a previously applied patch has already removed, or
2979 * PATH_TO_BE_DELETED for a path that a later patch would remove.
2981 * The latter is needed to deal with a case where two paths A and B
2982 * are swapped by first renaming A to B and then renaming B to A;
2983 * moving A to B should not be prevented due to presense of B as we
2984 * will remove it in a later patch.
2986 #define PATH_TO_BE_DELETED ((struct patch *) -2)
2987 #define PATH_WAS_DELETED ((struct patch *) -1)
2989 static int to_be_deleted(struct patch
*patch
)
2991 return patch
== PATH_TO_BE_DELETED
;
2994 static int was_deleted(struct patch
*patch
)
2996 return patch
== PATH_WAS_DELETED
;
2999 static void add_to_fn_table(struct patch
*patch
)
3001 struct string_list_item
*item
;
3004 * Always add new_name unless patch is a deletion
3005 * This should cover the cases for normal diffs,
3006 * file creations and copies
3008 if (patch
->new_name
!= NULL
) {
3009 item
= string_list_insert(&fn_table
, patch
->new_name
);
3014 * store a failure on rename/deletion cases because
3015 * later chunks shouldn't patch old names
3017 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3018 item
= string_list_insert(&fn_table
, patch
->old_name
);
3019 item
->util
= PATH_WAS_DELETED
;
3023 static void prepare_fn_table(struct patch
*patch
)
3026 * store information about incoming file deletion
3029 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3030 struct string_list_item
*item
;
3031 item
= string_list_insert(&fn_table
, patch
->old_name
);
3032 item
->util
= PATH_TO_BE_DELETED
;
3034 patch
= patch
->next
;
3038 static int checkout_target(struct cache_entry
*ce
, struct stat
*st
)
3040 struct checkout costate
;
3042 memset(&costate
, 0, sizeof(costate
));
3043 costate
.base_dir
= "";
3044 costate
.refresh_cache
= 1;
3045 if (checkout_entry(ce
, &costate
, NULL
) || lstat(ce
->name
, st
))
3046 return error(_("cannot checkout %s"), ce
->name
);
3050 static struct patch
*previous_patch(struct patch
*patch
, int *gone
)
3052 struct patch
*previous
;
3055 if (patch
->is_copy
|| patch
->is_rename
)
3056 return NULL
; /* "git" patches do not depend on the order */
3058 previous
= in_fn_table(patch
->old_name
);
3062 if (to_be_deleted(previous
))
3063 return NULL
; /* the deletion hasn't happened yet */
3065 if (was_deleted(previous
))
3071 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3073 static int load_patch_target(struct strbuf
*buf
,
3074 struct cache_entry
*ce
,
3077 unsigned expected_mode
)
3080 if (read_file_or_gitlink(ce
, buf
))
3081 return error(_("read of %s failed"), name
);
3083 if (S_ISGITLINK(expected_mode
)) {
3085 return read_file_or_gitlink(ce
, buf
);
3087 return SUBMODULE_PATCH_WITHOUT_INDEX
;
3089 if (read_old_data(st
, name
, buf
))
3090 return error(_("read of %s failed"), name
);
3097 * We are about to apply "patch"; populate the "image" with the
3098 * current version we have, from the working tree or from the index,
3099 * depending on the situation e.g. --cached/--index. If we are
3100 * applying a non-git patch that incrementally updates the tree,
3101 * we read from the result of a previous diff.
3103 static int load_preimage(struct image
*image
,
3104 struct patch
*patch
, struct stat
*st
, struct cache_entry
*ce
)
3106 struct strbuf buf
= STRBUF_INIT
;
3109 struct patch
*previous
;
3112 previous
= previous_patch(patch
, &status
);
3114 return error(_("path %s has been renamed/deleted"),
3117 /* We have a patched copy in memory; use that. */
3118 strbuf_add(&buf
, previous
->result
, previous
->resultsize
);
3120 status
= load_patch_target(&buf
, ce
, st
,
3121 patch
->old_name
, patch
->old_mode
);
3124 else if (status
== SUBMODULE_PATCH_WITHOUT_INDEX
) {
3126 * There is no way to apply subproject
3127 * patch without looking at the index.
3128 * NEEDSWORK: shouldn't this be flagged
3131 free_fragment_list(patch
->fragments
);
3132 patch
->fragments
= NULL
;
3133 } else if (status
) {
3134 return error(_("read of %s failed"), patch
->old_name
);
3138 img
= strbuf_detach(&buf
, &len
);
3139 prepare_image(image
, img
, len
, !patch
->is_binary
);
3143 static int try_threeway(struct image
*image
, struct patch
*patch
,
3144 struct stat
*st
, struct cache_entry
*ce
)
3146 return -1; /* for now */
3149 static int apply_data(struct patch
*patch
, struct stat
*st
, struct cache_entry
*ce
)
3153 if (load_preimage(&image
, patch
, st
, ce
) < 0)
3156 if (apply_fragments(&image
, patch
) < 0) {
3157 /* Note: with --reject, apply_fragments() returns 0 */
3158 if (!threeway
|| try_threeway(&image
, patch
, st
, ce
) < 0)
3161 patch
->result
= image
.buf
;
3162 patch
->resultsize
= image
.len
;
3163 add_to_fn_table(patch
);
3164 free(image
.line_allocated
);
3166 if (0 < patch
->is_delete
&& patch
->resultsize
)
3167 return error(_("removal patch leaves file contents"));
3172 static int verify_index_match(struct cache_entry
*ce
, struct stat
*st
)
3174 if (S_ISGITLINK(ce
->ce_mode
)) {
3175 if (!S_ISDIR(st
->st_mode
))
3179 return ce_match_stat(ce
, st
, CE_MATCH_IGNORE_VALID
|CE_MATCH_IGNORE_SKIP_WORKTREE
);
3183 * If "patch" that we are looking at modifies or deletes what we have,
3184 * we would want it not to lose any local modification we have, either
3185 * in the working tree or in the index.
3187 * This also decides if a non-git patch is a creation patch or a
3188 * modification to an existing empty file. We do not check the state
3189 * of the current tree for a creation patch in this function; the caller
3190 * check_patch() separately makes sure (and errors out otherwise) that
3191 * the path the patch creates does not exist in the current tree.
3193 static int check_preimage(struct patch
*patch
, struct cache_entry
**ce
, struct stat
*st
)
3195 const char *old_name
= patch
->old_name
;
3196 struct patch
*previous
= NULL
;
3197 int stat_ret
= 0, status
;
3198 unsigned st_mode
= 0;
3203 assert(patch
->is_new
<= 0);
3204 previous
= previous_patch(patch
, &status
);
3207 return error(_("path %s has been renamed/deleted"), old_name
);
3209 st_mode
= previous
->new_mode
;
3210 } else if (!cached
) {
3211 stat_ret
= lstat(old_name
, st
);
3212 if (stat_ret
&& errno
!= ENOENT
)
3213 return error(_("%s: %s"), old_name
, strerror(errno
));
3216 if (check_index
&& !previous
) {
3217 int pos
= cache_name_pos(old_name
, strlen(old_name
));
3219 if (patch
->is_new
< 0)
3221 return error(_("%s: does not exist in index"), old_name
);
3223 *ce
= active_cache
[pos
];
3225 if (checkout_target(*ce
, st
))
3228 if (!cached
&& verify_index_match(*ce
, st
))
3229 return error(_("%s: does not match index"), old_name
);
3231 st_mode
= (*ce
)->ce_mode
;
3232 } else if (stat_ret
< 0) {
3233 if (patch
->is_new
< 0)
3235 return error(_("%s: %s"), old_name
, strerror(errno
));
3238 if (!cached
&& !previous
)
3239 st_mode
= ce_mode_from_stat(*ce
, st
->st_mode
);
3241 if (patch
->is_new
< 0)
3243 if (!patch
->old_mode
)
3244 patch
->old_mode
= st_mode
;
3245 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
3246 return error(_("%s: wrong type"), old_name
);
3247 if (st_mode
!= patch
->old_mode
)
3248 warning(_("%s has type %o, expected %o"),
3249 old_name
, st_mode
, patch
->old_mode
);
3250 if (!patch
->new_mode
&& !patch
->is_delete
)
3251 patch
->new_mode
= st_mode
;
3256 patch
->is_delete
= 0;
3257 free(patch
->old_name
);
3258 patch
->old_name
= NULL
;
3263 #define EXISTS_IN_INDEX 1
3264 #define EXISTS_IN_WORKTREE 2
3266 static int check_to_create(const char *new_name
, int ok_if_exists
)
3271 cache_name_pos(new_name
, strlen(new_name
)) >= 0 &&
3273 return EXISTS_IN_INDEX
;
3277 if (!lstat(new_name
, &nst
)) {
3278 if (S_ISDIR(nst
.st_mode
) || ok_if_exists
)
3281 * A leading component of new_name might be a symlink
3282 * that is going to be removed with this patch, but
3283 * still pointing at somewhere that has the path.
3284 * In such a case, path "new_name" does not exist as
3285 * far as git is concerned.
3287 if (has_symlink_leading_path(new_name
, strlen(new_name
)))
3290 return EXISTS_IN_WORKTREE
;
3291 } else if ((errno
!= ENOENT
) && (errno
!= ENOTDIR
)) {
3292 return error("%s: %s", new_name
, strerror(errno
));
3298 * Check and apply the patch in-core; leave the result in patch->result
3299 * for the caller to write it out to the final destination.
3301 static int check_patch(struct patch
*patch
)
3304 const char *old_name
= patch
->old_name
;
3305 const char *new_name
= patch
->new_name
;
3306 const char *name
= old_name
? old_name
: new_name
;
3307 struct cache_entry
*ce
= NULL
;
3308 struct patch
*tpatch
;
3312 patch
->rejected
= 1; /* we will drop this after we succeed */
3314 status
= check_preimage(patch
, &ce
, &st
);
3317 old_name
= patch
->old_name
;
3320 * A type-change diff is always split into a patch to delete
3321 * old, immediately followed by a patch to create new (see
3322 * diff.c::run_diff()); in such a case it is Ok that the entry
3323 * to be deleted by the previous patch is still in the working
3324 * tree and in the index.
3326 * A patch to swap-rename between A and B would first rename A
3327 * to B and then rename B to A. While applying the first one,
3328 * the presense of B should not stop A from getting renamed to
3329 * B; ask to_be_deleted() about the later rename. Removal of
3330 * B and rename from A to B is handled the same way by asking
3333 if ((tpatch
= in_fn_table(new_name
)) &&
3334 (was_deleted(tpatch
) || to_be_deleted(tpatch
)))
3340 ((0 < patch
->is_new
) | (0 < patch
->is_rename
) | patch
->is_copy
)) {
3341 int err
= check_to_create(new_name
, ok_if_exists
);
3346 case EXISTS_IN_INDEX
:
3347 return error(_("%s: already exists in index"), new_name
);
3349 case EXISTS_IN_WORKTREE
:
3350 return error(_("%s: already exists in working directory"),
3356 if (!patch
->new_mode
) {
3357 if (0 < patch
->is_new
)
3358 patch
->new_mode
= S_IFREG
| 0644;
3360 patch
->new_mode
= patch
->old_mode
;
3364 if (new_name
&& old_name
) {
3365 int same
= !strcmp(old_name
, new_name
);
3366 if (!patch
->new_mode
)
3367 patch
->new_mode
= patch
->old_mode
;
3368 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
)
3369 return error(_("new mode (%o) of %s does not match old mode (%o)%s%s"),
3370 patch
->new_mode
, new_name
, patch
->old_mode
,
3371 same
? "" : " of ", same
? "" : old_name
);
3374 if (apply_data(patch
, &st
, ce
) < 0)
3375 return error(_("%s: patch does not apply"), name
);
3376 patch
->rejected
= 0;
3380 static int check_patch_list(struct patch
*patch
)
3384 prepare_fn_table(patch
);
3386 if (apply_verbosely
)
3387 say_patch_name(stderr
,
3388 _("Checking patch %s..."), patch
);
3389 err
|= check_patch(patch
);
3390 patch
= patch
->next
;
3395 /* This function tries to read the sha1 from the current index */
3396 static int get_current_sha1(const char *path
, unsigned char *sha1
)
3400 if (read_cache() < 0)
3402 pos
= cache_name_pos(path
, strlen(path
));
3405 hashcpy(sha1
, active_cache
[pos
]->sha1
);
3409 /* Build an index that contains the just the files needed for a 3way merge */
3410 static void build_fake_ancestor(struct patch
*list
, const char *filename
)
3412 struct patch
*patch
;
3413 struct index_state result
= { NULL
};
3416 /* Once we start supporting the reverse patch, it may be
3417 * worth showing the new sha1 prefix, but until then...
3419 for (patch
= list
; patch
; patch
= patch
->next
) {
3420 const unsigned char *sha1_ptr
;
3421 unsigned char sha1
[20];
3422 struct cache_entry
*ce
;
3425 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3426 if (0 < patch
->is_new
)
3428 else if (get_sha1(patch
->old_sha1_prefix
, sha1
))
3429 /* git diff has no index line for mode/type changes */
3430 if (!patch
->lines_added
&& !patch
->lines_deleted
) {
3431 if (get_current_sha1(patch
->old_name
, sha1
))
3432 die("mode change for %s, which is not "
3433 "in current HEAD", name
);
3436 die("sha1 information is lacking or useless "
3441 ce
= make_cache_entry(patch
->old_mode
, sha1_ptr
, name
, 0, 0);
3443 die(_("make_cache_entry failed for path '%s'"), name
);
3444 if (add_index_entry(&result
, ce
, ADD_CACHE_OK_TO_ADD
))
3445 die ("Could not add %s to temporary index", name
);
3448 fd
= open(filename
, O_WRONLY
| O_CREAT
, 0666);
3449 if (fd
< 0 || write_index(&result
, fd
) || close(fd
))
3450 die ("Could not write temporary index to %s", filename
);
3452 discard_index(&result
);
3455 static void stat_patch_list(struct patch
*patch
)
3457 int files
, adds
, dels
;
3459 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
3461 adds
+= patch
->lines_added
;
3462 dels
+= patch
->lines_deleted
;
3466 print_stat_summary(stdout
, files
, adds
, dels
);
3469 static void numstat_patch_list(struct patch
*patch
)
3471 for ( ; patch
; patch
= patch
->next
) {
3473 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
3474 if (patch
->is_binary
)
3477 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
3478 write_name_quoted(name
, stdout
, line_termination
);
3482 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
3485 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
3487 printf(" %s %s\n", newdelete
, name
);
3490 static void show_mode_change(struct patch
*p
, int show_name
)
3492 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
3494 printf(" mode change %06o => %06o %s\n",
3495 p
->old_mode
, p
->new_mode
, p
->new_name
);
3497 printf(" mode change %06o => %06o\n",
3498 p
->old_mode
, p
->new_mode
);
3502 static void show_rename_copy(struct patch
*p
)
3504 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
3505 const char *old
, *new;
3507 /* Find common prefix */
3511 const char *slash_old
, *slash_new
;
3512 slash_old
= strchr(old
, '/');
3513 slash_new
= strchr(new, '/');
3516 slash_old
- old
!= slash_new
- new ||
3517 memcmp(old
, new, slash_new
- new))
3519 old
= slash_old
+ 1;
3520 new = slash_new
+ 1;
3522 /* p->old_name thru old is the common prefix, and old and new
3523 * through the end of names are renames
3525 if (old
!= p
->old_name
)
3526 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
3527 (int)(old
- p
->old_name
), p
->old_name
,
3528 old
, new, p
->score
);
3530 printf(" %s %s => %s (%d%%)\n", renamecopy
,
3531 p
->old_name
, p
->new_name
, p
->score
);
3532 show_mode_change(p
, 0);
3535 static void summary_patch_list(struct patch
*patch
)
3539 for (p
= patch
; p
; p
= p
->next
) {
3541 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
3542 else if (p
->is_delete
)
3543 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
3545 if (p
->is_rename
|| p
->is_copy
)
3546 show_rename_copy(p
);
3549 printf(" rewrite %s (%d%%)\n",
3550 p
->new_name
, p
->score
);
3551 show_mode_change(p
, 0);
3554 show_mode_change(p
, 1);
3560 static void patch_stats(struct patch
*patch
)
3562 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
3564 if (lines
> max_change
)
3566 if (patch
->old_name
) {
3567 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
3569 len
= strlen(patch
->old_name
);
3573 if (patch
->new_name
) {
3574 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
3576 len
= strlen(patch
->new_name
);
3582 static void remove_file(struct patch
*patch
, int rmdir_empty
)
3585 if (remove_file_from_cache(patch
->old_name
) < 0)
3586 die(_("unable to remove %s from index"), patch
->old_name
);
3589 if (!remove_or_warn(patch
->old_mode
, patch
->old_name
) && rmdir_empty
) {
3590 remove_path(patch
->old_name
);
3595 static void add_index_file(const char *path
, unsigned mode
, void *buf
, unsigned long size
)
3598 struct cache_entry
*ce
;
3599 int namelen
= strlen(path
);
3600 unsigned ce_size
= cache_entry_size(namelen
);
3605 ce
= xcalloc(1, ce_size
);
3606 memcpy(ce
->name
, path
, namelen
);
3607 ce
->ce_mode
= create_ce_mode(mode
);
3608 ce
->ce_flags
= namelen
;
3609 if (S_ISGITLINK(mode
)) {
3610 const char *s
= buf
;
3612 if (get_sha1_hex(s
+ strlen("Subproject commit "), ce
->sha1
))
3613 die(_("corrupt patch for subproject %s"), path
);
3616 if (lstat(path
, &st
) < 0)
3617 die_errno(_("unable to stat newly created file '%s'"),
3619 fill_stat_cache_info(ce
, &st
);
3621 if (write_sha1_file(buf
, size
, blob_type
, ce
->sha1
) < 0)
3622 die(_("unable to create backing store for newly created file %s"), path
);
3624 if (add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
) < 0)
3625 die(_("unable to add cache entry for %s"), path
);
3628 static int try_create_file(const char *path
, unsigned int mode
, const char *buf
, unsigned long size
)
3631 struct strbuf nbuf
= STRBUF_INIT
;
3633 if (S_ISGITLINK(mode
)) {
3635 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
))
3637 return mkdir(path
, 0777);
3640 if (has_symlinks
&& S_ISLNK(mode
))
3641 /* Although buf:size is counted string, it also is NUL
3644 return symlink(buf
, path
);
3646 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
3650 if (convert_to_working_tree(path
, buf
, size
, &nbuf
)) {
3654 write_or_die(fd
, buf
, size
);
3655 strbuf_release(&nbuf
);
3658 die_errno(_("closing file '%s'"), path
);
3663 * We optimistically assume that the directories exist,
3664 * which is true 99% of the time anyway. If they don't,
3665 * we create them and try again.
3667 static void create_one_file(char *path
, unsigned mode
, const char *buf
, unsigned long size
)
3671 if (!try_create_file(path
, mode
, buf
, size
))
3674 if (errno
== ENOENT
) {
3675 if (safe_create_leading_directories(path
))
3677 if (!try_create_file(path
, mode
, buf
, size
))
3681 if (errno
== EEXIST
|| errno
== EACCES
) {
3682 /* We may be trying to create a file where a directory
3686 if (!lstat(path
, &st
) && (!S_ISDIR(st
.st_mode
) || !rmdir(path
)))
3690 if (errno
== EEXIST
) {
3691 unsigned int nr
= getpid();
3694 char newpath
[PATH_MAX
];
3695 mksnpath(newpath
, sizeof(newpath
), "%s~%u", path
, nr
);
3696 if (!try_create_file(newpath
, mode
, buf
, size
)) {
3697 if (!rename(newpath
, path
))
3699 unlink_or_warn(newpath
);
3702 if (errno
!= EEXIST
)
3707 die_errno(_("unable to write file '%s' mode %o"), path
, mode
);
3710 static void create_file(struct patch
*patch
)
3712 char *path
= patch
->new_name
;
3713 unsigned mode
= patch
->new_mode
;
3714 unsigned long size
= patch
->resultsize
;
3715 char *buf
= patch
->result
;
3718 mode
= S_IFREG
| 0644;
3719 create_one_file(path
, mode
, buf
, size
);
3720 add_index_file(path
, mode
, buf
, size
);
3723 /* phase zero is to remove, phase one is to create */
3724 static void write_out_one_result(struct patch
*patch
, int phase
)
3726 if (patch
->is_delete
> 0) {
3728 remove_file(patch
, 1);
3731 if (patch
->is_new
> 0 || patch
->is_copy
) {
3737 * Rename or modification boils down to the same
3738 * thing: remove the old, write the new
3741 remove_file(patch
, patch
->is_rename
);
3746 static int write_out_one_reject(struct patch
*patch
)
3749 char namebuf
[PATH_MAX
];
3750 struct fragment
*frag
;
3752 struct strbuf sb
= STRBUF_INIT
;
3754 for (cnt
= 0, frag
= patch
->fragments
; frag
; frag
= frag
->next
) {
3755 if (!frag
->rejected
)
3761 if (apply_verbosely
)
3762 say_patch_name(stderr
,
3763 _("Applied patch %s cleanly."), patch
);
3767 /* This should not happen, because a removal patch that leaves
3768 * contents are marked "rejected" at the patch level.
3770 if (!patch
->new_name
)
3771 die(_("internal error"));
3773 /* Say this even without --verbose */
3774 strbuf_addf(&sb
, Q_("Applying patch %%s with %d reject...",
3775 "Applying patch %%s with %d rejects...",
3778 say_patch_name(stderr
, sb
.buf
, patch
);
3779 strbuf_release(&sb
);
3781 cnt
= strlen(patch
->new_name
);
3782 if (ARRAY_SIZE(namebuf
) <= cnt
+ 5) {
3783 cnt
= ARRAY_SIZE(namebuf
) - 5;
3784 warning(_("truncating .rej filename to %.*s.rej"),
3785 cnt
- 1, patch
->new_name
);
3787 memcpy(namebuf
, patch
->new_name
, cnt
);
3788 memcpy(namebuf
+ cnt
, ".rej", 5);
3790 rej
= fopen(namebuf
, "w");
3792 return error(_("cannot open %s: %s"), namebuf
, strerror(errno
));
3794 /* Normal git tools never deal with .rej, so do not pretend
3795 * this is a git patch by saying --git nor give extended
3796 * headers. While at it, maybe please "kompare" that wants
3797 * the trailing TAB and some garbage at the end of line ;-).
3799 fprintf(rej
, "diff a/%s b/%s\t(rejected hunks)\n",
3800 patch
->new_name
, patch
->new_name
);
3801 for (cnt
= 1, frag
= patch
->fragments
;
3803 cnt
++, frag
= frag
->next
) {
3804 if (!frag
->rejected
) {
3805 fprintf_ln(stderr
, _("Hunk #%d applied cleanly."), cnt
);
3808 fprintf_ln(stderr
, _("Rejected hunk #%d."), cnt
);
3809 fprintf(rej
, "%.*s", frag
->size
, frag
->patch
);
3810 if (frag
->patch
[frag
->size
-1] != '\n')
3817 static int write_out_results(struct patch
*list
)
3823 for (phase
= 0; phase
< 2; phase
++) {
3829 write_out_one_result(l
, phase
);
3830 if (phase
== 1 && write_out_one_reject(l
))
3839 static struct lock_file lock_file
;
3841 static struct string_list limit_by_name
;
3842 static int has_include
;
3843 static void add_name_limit(const char *name
, int exclude
)
3845 struct string_list_item
*it
;
3847 it
= string_list_append(&limit_by_name
, name
);
3848 it
->util
= exclude
? NULL
: (void *) 1;
3851 static int use_patch(struct patch
*p
)
3853 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
3856 /* Paths outside are not touched regardless of "--include" */
3857 if (0 < prefix_length
) {
3858 int pathlen
= strlen(pathname
);
3859 if (pathlen
<= prefix_length
||
3860 memcmp(prefix
, pathname
, prefix_length
))
3864 /* See if it matches any of exclude/include rule */
3865 for (i
= 0; i
< limit_by_name
.nr
; i
++) {
3866 struct string_list_item
*it
= &limit_by_name
.items
[i
];
3867 if (!fnmatch(it
->string
, pathname
, 0))
3868 return (it
->util
!= NULL
);
3872 * If we had any include, a path that does not match any rule is
3873 * not used. Otherwise, we saw bunch of exclude rules (or none)
3874 * and such a path is used.
3876 return !has_include
;
3880 static void prefix_one(char **name
)
3882 char *old_name
= *name
;
3885 *name
= xstrdup(prefix_filename(prefix
, prefix_length
, *name
));
3889 static void prefix_patches(struct patch
*p
)
3891 if (!prefix
|| p
->is_toplevel_relative
)
3893 for ( ; p
; p
= p
->next
) {
3894 prefix_one(&p
->new_name
);
3895 prefix_one(&p
->old_name
);
3899 #define INACCURATE_EOF (1<<0)
3900 #define RECOUNT (1<<1)
3902 static int apply_patch(int fd
, const char *filename
, int options
)
3905 struct strbuf buf
= STRBUF_INIT
; /* owns the patch text */
3906 struct patch
*list
= NULL
, **listp
= &list
;
3907 int skipped_patch
= 0;
3909 patch_input_file
= filename
;
3910 read_patch_file(&buf
, fd
);
3912 while (offset
< buf
.len
) {
3913 struct patch
*patch
;
3916 patch
= xcalloc(1, sizeof(*patch
));
3917 patch
->inaccurate_eof
= !!(options
& INACCURATE_EOF
);
3918 patch
->recount
= !!(options
& RECOUNT
);
3919 nr
= parse_chunk(buf
.buf
+ offset
, buf
.len
- offset
, patch
);
3922 if (apply_in_reverse
)
3923 reverse_patches(patch
);
3925 prefix_patches(patch
);
3926 if (use_patch(patch
)) {
3929 listp
= &patch
->next
;
3938 if (!list
&& !skipped_patch
)
3939 die(_("unrecognized input"));
3941 if (whitespace_error
&& (ws_error_action
== die_on_ws_error
))
3944 update_index
= check_index
&& apply
;
3945 if (update_index
&& newfd
< 0)
3946 newfd
= hold_locked_index(&lock_file
, 1);
3949 if (read_cache() < 0)
3950 die(_("unable to read index file"));
3953 if ((check
|| apply
) &&
3954 check_patch_list(list
) < 0 &&
3958 if (apply
&& write_out_results(list
))
3962 build_fake_ancestor(list
, fake_ancestor
);
3965 stat_patch_list(list
);
3968 numstat_patch_list(list
);
3971 summary_patch_list(list
);
3973 free_patch_list(list
);
3974 strbuf_release(&buf
);
3975 string_list_clear(&fn_table
, 0);
3979 static int git_apply_config(const char *var
, const char *value
, void *cb
)
3981 if (!strcmp(var
, "apply.whitespace"))
3982 return git_config_string(&apply_default_whitespace
, var
, value
);
3983 else if (!strcmp(var
, "apply.ignorewhitespace"))
3984 return git_config_string(&apply_default_ignorewhitespace
, var
, value
);
3985 return git_default_config(var
, value
, cb
);
3988 static int option_parse_exclude(const struct option
*opt
,
3989 const char *arg
, int unset
)
3991 add_name_limit(arg
, 1);
3995 static int option_parse_include(const struct option
*opt
,
3996 const char *arg
, int unset
)
3998 add_name_limit(arg
, 0);
4003 static int option_parse_p(const struct option
*opt
,
4004 const char *arg
, int unset
)
4006 p_value
= atoi(arg
);
4011 static int option_parse_z(const struct option
*opt
,
4012 const char *arg
, int unset
)
4015 line_termination
= '\n';
4017 line_termination
= 0;
4021 static int option_parse_space_change(const struct option
*opt
,
4022 const char *arg
, int unset
)
4025 ws_ignore_action
= ignore_ws_none
;
4027 ws_ignore_action
= ignore_ws_change
;
4031 static int option_parse_whitespace(const struct option
*opt
,
4032 const char *arg
, int unset
)
4034 const char **whitespace_option
= opt
->value
;
4036 *whitespace_option
= arg
;
4037 parse_whitespace_option(arg
);
4041 static int option_parse_directory(const struct option
*opt
,
4042 const char *arg
, int unset
)
4044 root_len
= strlen(arg
);
4045 if (root_len
&& arg
[root_len
- 1] != '/') {
4047 root
= new_root
= xmalloc(root_len
+ 2);
4048 strcpy(new_root
, arg
);
4049 strcpy(new_root
+ root_len
++, "/");
4055 int cmd_apply(int argc
, const char **argv
, const char *prefix_
)
4059 int is_not_gitdir
= !startup_info
->have_repository
;
4060 int force_apply
= 0;
4062 const char *whitespace_option
= NULL
;
4064 struct option builtin_apply_options
[] = {
4065 { OPTION_CALLBACK
, 0, "exclude", NULL
, "path",
4066 "don't apply changes matching the given path",
4067 0, option_parse_exclude
},
4068 { OPTION_CALLBACK
, 0, "include", NULL
, "path",
4069 "apply changes matching the given path",
4070 0, option_parse_include
},
4071 { OPTION_CALLBACK
, 'p', NULL
, NULL
, "num",
4072 "remove <num> leading slashes from traditional diff paths",
4073 0, option_parse_p
},
4074 OPT_BOOLEAN(0, "no-add", &no_add
,
4075 "ignore additions made by the patch"),
4076 OPT_BOOLEAN(0, "stat", &diffstat
,
4077 "instead of applying the patch, output diffstat for the input"),
4078 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
4079 OPT_NOOP_NOARG(0, "binary"),
4080 OPT_BOOLEAN(0, "numstat", &numstat
,
4081 "shows number of added and deleted lines in decimal notation"),
4082 OPT_BOOLEAN(0, "summary", &summary
,
4083 "instead of applying the patch, output a summary for the input"),
4084 OPT_BOOLEAN(0, "check", &check
,
4085 "instead of applying the patch, see if the patch is applicable"),
4086 OPT_BOOLEAN(0, "index", &check_index
,
4087 "make sure the patch is applicable to the current index"),
4088 OPT_BOOLEAN(0, "cached", &cached
,
4089 "apply a patch without touching the working tree"),
4090 OPT_BOOLEAN(0, "apply", &force_apply
,
4091 "also apply the patch (use with --stat/--summary/--check)"),
4092 OPT_BOOL('3', "3way", &threeway
,
4093 "attempt three-way merge if a patch does not apply"),
4094 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor
,
4095 "build a temporary index based on embedded index information"),
4096 { OPTION_CALLBACK
, 'z', NULL
, NULL
, NULL
,
4097 "paths are separated with NUL character",
4098 PARSE_OPT_NOARG
, option_parse_z
},
4099 OPT_INTEGER('C', NULL
, &p_context
,
4100 "ensure at least <n> lines of context match"),
4101 { OPTION_CALLBACK
, 0, "whitespace", &whitespace_option
, "action",
4102 "detect new or modified lines that have whitespace errors",
4103 0, option_parse_whitespace
},
4104 { OPTION_CALLBACK
, 0, "ignore-space-change", NULL
, NULL
,
4105 "ignore changes in whitespace when finding context",
4106 PARSE_OPT_NOARG
, option_parse_space_change
},
4107 { OPTION_CALLBACK
, 0, "ignore-whitespace", NULL
, NULL
,
4108 "ignore changes in whitespace when finding context",
4109 PARSE_OPT_NOARG
, option_parse_space_change
},
4110 OPT_BOOLEAN('R', "reverse", &apply_in_reverse
,
4111 "apply the patch in reverse"),
4112 OPT_BOOLEAN(0, "unidiff-zero", &unidiff_zero
,
4113 "don't expect at least one line of context"),
4114 OPT_BOOLEAN(0, "reject", &apply_with_reject
,
4115 "leave the rejected hunks in corresponding *.rej files"),
4116 OPT_BOOLEAN(0, "allow-overlap", &allow_overlap
,
4117 "allow overlapping hunks"),
4118 OPT__VERBOSE(&apply_verbosely
, "be verbose"),
4119 OPT_BIT(0, "inaccurate-eof", &options
,
4120 "tolerate incorrectly detected missing new-line at the end of file",
4122 OPT_BIT(0, "recount", &options
,
4123 "do not trust the line counts in the hunk headers",
4125 { OPTION_CALLBACK
, 0, "directory", NULL
, "root",
4126 "prepend <root> to all filenames",
4127 0, option_parse_directory
},
4132 prefix_length
= prefix
? strlen(prefix
) : 0;
4133 git_config(git_apply_config
, NULL
);
4134 if (apply_default_whitespace
)
4135 parse_whitespace_option(apply_default_whitespace
);
4136 if (apply_default_ignorewhitespace
)
4137 parse_ignorewhitespace_option(apply_default_ignorewhitespace
);
4139 argc
= parse_options(argc
, argv
, prefix
, builtin_apply_options
,
4142 if (apply_with_reject
&& threeway
)
4143 die("--reject and --3way cannot be used together.");
4144 if (cached
&& threeway
)
4145 die("--cached and --3way cannot be used together.");
4148 die(_("--3way outside a repository"));
4151 if (apply_with_reject
)
4152 apply
= apply_verbosely
= 1;
4153 if (!force_apply
&& (diffstat
|| numstat
|| summary
|| check
|| fake_ancestor
))
4155 if (check_index
&& is_not_gitdir
)
4156 die(_("--index outside a repository"));
4159 die(_("--cached outside a repository"));
4162 for (i
= 0; i
< argc
; i
++) {
4163 const char *arg
= argv
[i
];
4166 if (!strcmp(arg
, "-")) {
4167 errs
|= apply_patch(0, "<stdin>", options
);
4170 } else if (0 < prefix_length
)
4171 arg
= prefix_filename(prefix
, prefix_length
, arg
);
4173 fd
= open(arg
, O_RDONLY
);
4175 die_errno(_("can't open patch '%s'"), arg
);
4177 set_default_whitespace_mode(whitespace_option
);
4178 errs
|= apply_patch(fd
, arg
, options
);
4181 set_default_whitespace_mode(whitespace_option
);
4183 errs
|= apply_patch(0, "<stdin>", options
);
4184 if (whitespace_error
) {
4185 if (squelch_whitespace_errors
&&
4186 squelch_whitespace_errors
< whitespace_error
) {
4188 whitespace_error
- squelch_whitespace_errors
;
4189 warning(Q_("squelched %d whitespace error",
4190 "squelched %d whitespace errors",
4194 if (ws_error_action
== die_on_ws_error
)
4195 die(Q_("%d line adds whitespace errors.",
4196 "%d lines add whitespace errors.",
4199 if (applied_after_fixing_ws
&& apply
)
4200 warning("%d line%s applied after"
4201 " fixing whitespace errors.",
4202 applied_after_fixing_ws
,
4203 applied_after_fixing_ws
== 1 ? "" : "s");
4204 else if (whitespace_error
)
4205 warning(Q_("%d line adds whitespace errors.",
4206 "%d lines add whitespace errors.",
4212 if (write_cache(newfd
, active_cache
, active_nr
) ||
4213 commit_locked_index(&lock_file
))
4214 die(_("Unable to write new index file"));