4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
10 #include "cache-tree.h"
15 #include "string-list.h"
18 #include "parse-options.h"
21 * --check turns on checking that the working tree matches the
22 * files that are being modified, but doesn't apply the patch
23 * --stat does just a diffstat, and doesn't actually apply
24 * --numstat does numeric diffstat, and doesn't actually apply
25 * --index-info shows the old and new index info for paths if available.
26 * --index updates the cache as well.
27 * --cached updates only the cache without ever touching the working tree.
29 static const char *prefix
;
30 static int prefix_length
= -1;
31 static int newfd
= -1;
33 static int unidiff_zero
;
34 static int p_value
= 1;
35 static int p_value_known
;
36 static int check_index
;
37 static int update_index
;
44 static int apply_in_reverse
;
45 static int apply_with_reject
;
46 static int apply_verbosely
;
47 static int allow_overlap
;
49 static const char *fake_ancestor
;
50 static int line_termination
= '\n';
51 static unsigned int p_context
= UINT_MAX
;
52 static const char * const apply_usage
[] = {
53 N_("git apply [options] [<patch>...]"),
57 static enum ws_error_action
{
62 } ws_error_action
= warn_on_ws_error
;
63 static int whitespace_error
;
64 static int squelch_whitespace_errors
= 5;
65 static int applied_after_fixing_ws
;
67 static enum ws_ignore
{
70 } ws_ignore_action
= ignore_ws_none
;
73 static const char *patch_input_file
;
74 static const char *root
;
76 static int read_stdin
= 1;
79 static void parse_whitespace_option(const char *option
)
82 ws_error_action
= warn_on_ws_error
;
85 if (!strcmp(option
, "warn")) {
86 ws_error_action
= warn_on_ws_error
;
89 if (!strcmp(option
, "nowarn")) {
90 ws_error_action
= nowarn_ws_error
;
93 if (!strcmp(option
, "error")) {
94 ws_error_action
= die_on_ws_error
;
97 if (!strcmp(option
, "error-all")) {
98 ws_error_action
= die_on_ws_error
;
99 squelch_whitespace_errors
= 0;
102 if (!strcmp(option
, "strip") || !strcmp(option
, "fix")) {
103 ws_error_action
= correct_ws_error
;
106 die(_("unrecognized whitespace option '%s'"), option
);
109 static void parse_ignorewhitespace_option(const char *option
)
111 if (!option
|| !strcmp(option
, "no") ||
112 !strcmp(option
, "false") || !strcmp(option
, "never") ||
113 !strcmp(option
, "none")) {
114 ws_ignore_action
= ignore_ws_none
;
117 if (!strcmp(option
, "change")) {
118 ws_ignore_action
= ignore_ws_change
;
121 die(_("unrecognized whitespace ignore option '%s'"), option
);
124 static void set_default_whitespace_mode(const char *whitespace_option
)
126 if (!whitespace_option
&& !apply_default_whitespace
)
127 ws_error_action
= (apply
? warn_on_ws_error
: nowarn_ws_error
);
131 * For "diff-stat" like behaviour, we keep track of the biggest change
132 * we've seen, and the longest filename. That allows us to do simple
135 static int max_change
, max_len
;
138 * Various "current state", notably line numbers and what
139 * file (and how) we're patching right now.. The "is_xxxx"
140 * things are flags, where -1 means "don't know yet".
142 static int linenr
= 1;
145 * This represents one "hunk" from a patch, starting with
146 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
147 * patch text is pointed at by patch, and its byte length
148 * is stored in size. leading and trailing are the number
152 unsigned long leading
, trailing
;
153 unsigned long oldpos
, oldlines
;
154 unsigned long newpos
, newlines
;
156 * 'patch' is usually borrowed from buf in apply_patch(),
157 * but some codepaths store an allocated buffer.
160 unsigned free_patch
:1,
164 struct fragment
*next
;
168 * When dealing with a binary patch, we reuse "leading" field
169 * to store the type of the binary hunk, either deflated "delta"
170 * or deflated "literal".
172 #define binary_patch_method leading
173 #define BINARY_DELTA_DEFLATED 1
174 #define BINARY_LITERAL_DEFLATED 2
177 * This represents a "patch" to a file, both metainfo changes
178 * such as creation/deletion, filemode and content changes represented
179 * as a series of fragments.
182 char *new_name
, *old_name
, *def_name
;
183 unsigned int old_mode
, new_mode
;
184 int is_new
, is_delete
; /* -1 = unknown, 0 = false, 1 = true */
187 unsigned long deflate_origlen
;
188 int lines_added
, lines_deleted
;
190 unsigned int is_toplevel_relative
:1;
191 unsigned int inaccurate_eof
:1;
192 unsigned int is_binary
:1;
193 unsigned int is_copy
:1;
194 unsigned int is_rename
:1;
195 unsigned int recount
:1;
196 struct fragment
*fragments
;
199 char old_sha1_prefix
[41];
200 char new_sha1_prefix
[41];
204 static void free_fragment_list(struct fragment
*list
)
207 struct fragment
*next
= list
->next
;
208 if (list
->free_patch
)
209 free((char *)list
->patch
);
215 static void free_patch(struct patch
*patch
)
217 free_fragment_list(patch
->fragments
);
218 free(patch
->def_name
);
219 free(patch
->old_name
);
220 free(patch
->new_name
);
225 static void free_patch_list(struct patch
*list
)
228 struct patch
*next
= list
->next
;
235 * A line in a file, len-bytes long (includes the terminating LF,
236 * except for an incomplete line at the end if the file ends with
237 * one), and its contents hashes to 'hash'.
243 #define LINE_COMMON 1
244 #define LINE_PATCHED 2
248 * This represents a "file", which is an array of "lines".
255 struct line
*line_allocated
;
260 * Records filenames that have been touched, in order to handle
261 * the case where more than one patches touch the same file.
264 static struct string_list fn_table
;
266 static uint32_t hash_line(const char *cp
, size_t len
)
270 for (i
= 0, h
= 0; i
< len
; i
++) {
271 if (!isspace(cp
[i
])) {
272 h
= h
* 3 + (cp
[i
] & 0xff);
279 * Compare lines s1 of length n1 and s2 of length n2, ignoring
280 * whitespace difference. Returns 1 if they match, 0 otherwise
282 static int fuzzy_matchlines(const char *s1
, size_t n1
,
283 const char *s2
, size_t n2
)
285 const char *last1
= s1
+ n1
- 1;
286 const char *last2
= s2
+ n2
- 1;
289 /* ignore line endings */
290 while ((*last1
== '\r') || (*last1
== '\n'))
292 while ((*last2
== '\r') || (*last2
== '\n'))
295 /* skip leading whitespace */
296 while (isspace(*s1
) && (s1
<= last1
))
298 while (isspace(*s2
) && (s2
<= last2
))
300 /* early return if both lines are empty */
301 if ((s1
> last1
) && (s2
> last2
))
304 result
= *s1
++ - *s2
++;
306 * Skip whitespace inside. We check for whitespace on
307 * both buffers because we don't want "a b" to match
310 if (isspace(*s1
) && isspace(*s2
)) {
311 while (isspace(*s1
) && s1
<= last1
)
313 while (isspace(*s2
) && s2
<= last2
)
317 * If we reached the end on one side only,
321 ((s2
> last2
) && (s1
<= last1
)) ||
322 ((s1
> last1
) && (s2
<= last2
)))
324 if ((s1
> last1
) && (s2
> last2
))
331 static void add_line_info(struct image
*img
, const char *bol
, size_t len
, unsigned flag
)
333 ALLOC_GROW(img
->line_allocated
, img
->nr
+ 1, img
->alloc
);
334 img
->line_allocated
[img
->nr
].len
= len
;
335 img
->line_allocated
[img
->nr
].hash
= hash_line(bol
, len
);
336 img
->line_allocated
[img
->nr
].flag
= flag
;
341 * "buf" has the file contents to be patched (read from various sources).
342 * attach it to "image" and add line-based index to it.
343 * "image" now owns the "buf".
345 static void prepare_image(struct image
*image
, char *buf
, size_t len
,
346 int prepare_linetable
)
350 memset(image
, 0, sizeof(*image
));
354 if (!prepare_linetable
)
357 ep
= image
->buf
+ image
->len
;
361 for (next
= cp
; next
< ep
&& *next
!= '\n'; next
++)
365 add_line_info(image
, cp
, next
- cp
, 0);
368 image
->line
= image
->line_allocated
;
371 static void clear_image(struct image
*image
)
378 /* fmt must contain _one_ %s and no other substitution */
379 static void say_patch_name(FILE *output
, const char *fmt
, struct patch
*patch
)
381 struct strbuf sb
= STRBUF_INIT
;
383 if (patch
->old_name
&& patch
->new_name
&&
384 strcmp(patch
->old_name
, patch
->new_name
)) {
385 quote_c_style(patch
->old_name
, &sb
, NULL
, 0);
386 strbuf_addstr(&sb
, " => ");
387 quote_c_style(patch
->new_name
, &sb
, NULL
, 0);
389 const char *n
= patch
->new_name
;
392 quote_c_style(n
, &sb
, NULL
, 0);
394 fprintf(output
, fmt
, sb
.buf
);
401 static void read_patch_file(struct strbuf
*sb
, int fd
)
403 if (strbuf_read(sb
, fd
, 0) < 0)
404 die_errno("git apply: failed to read");
407 * Make sure that we have some slop in the buffer
408 * so that we can do speculative "memcmp" etc, and
409 * see to it that it is NUL-filled.
411 strbuf_grow(sb
, SLOP
);
412 memset(sb
->buf
+ sb
->len
, 0, SLOP
);
415 static unsigned long linelen(const char *buffer
, unsigned long size
)
417 unsigned long len
= 0;
420 if (*buffer
++ == '\n')
426 static int is_dev_null(const char *str
)
428 return !memcmp("/dev/null", str
, 9) && isspace(str
[9]);
434 static int name_terminate(const char *name
, int namelen
, int c
, int terminate
)
436 if (c
== ' ' && !(terminate
& TERM_SPACE
))
438 if (c
== '\t' && !(terminate
& TERM_TAB
))
444 /* remove double slashes to make --index work with such filenames */
445 static char *squash_slash(char *name
)
453 if ((name
[j
++] = name
[i
++]) == '/')
454 while (name
[i
] == '/')
461 static char *find_name_gnu(const char *line
, const char *def
, int p_value
)
463 struct strbuf name
= STRBUF_INIT
;
467 * Proposed "new-style" GNU patch/diff format; see
468 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
470 if (unquote_c_style(&name
, line
, NULL
)) {
471 strbuf_release(&name
);
475 for (cp
= name
.buf
; p_value
; p_value
--) {
476 cp
= strchr(cp
, '/');
478 strbuf_release(&name
);
484 strbuf_remove(&name
, 0, cp
- name
.buf
);
486 strbuf_insert(&name
, 0, root
, root_len
);
487 return squash_slash(strbuf_detach(&name
, NULL
));
490 static size_t sane_tz_len(const char *line
, size_t len
)
494 if (len
< strlen(" +0500") || line
[len
-strlen(" +0500")] != ' ')
496 tz
= line
+ len
- strlen(" +0500");
498 if (tz
[1] != '+' && tz
[1] != '-')
501 for (p
= tz
+ 2; p
!= line
+ len
; p
++)
505 return line
+ len
- tz
;
508 static size_t tz_with_colon_len(const char *line
, size_t len
)
512 if (len
< strlen(" +08:00") || line
[len
- strlen(":00")] != ':')
514 tz
= line
+ len
- strlen(" +08:00");
516 if (tz
[0] != ' ' || (tz
[1] != '+' && tz
[1] != '-'))
519 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
520 !isdigit(*p
++) || !isdigit(*p
++))
523 return line
+ len
- tz
;
526 static size_t date_len(const char *line
, size_t len
)
528 const char *date
, *p
;
530 if (len
< strlen("72-02-05") || line
[len
-strlen("-05")] != '-')
532 p
= date
= line
+ len
- strlen("72-02-05");
534 if (!isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
535 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != '-' ||
536 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a date. */
539 if (date
- line
>= strlen("19") &&
540 isdigit(date
[-1]) && isdigit(date
[-2])) /* 4-digit year */
541 date
-= strlen("19");
543 return line
+ len
- date
;
546 static size_t short_time_len(const char *line
, size_t len
)
548 const char *time
, *p
;
550 if (len
< strlen(" 07:01:32") || line
[len
-strlen(":32")] != ':')
552 p
= time
= line
+ len
- strlen(" 07:01:32");
554 /* Permit 1-digit hours? */
556 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
557 !isdigit(*p
++) || !isdigit(*p
++) || *p
++ != ':' ||
558 !isdigit(*p
++) || !isdigit(*p
++)) /* Not a time. */
561 return line
+ len
- time
;
564 static size_t fractional_time_len(const char *line
, size_t len
)
569 /* Expected format: 19:41:17.620000023 */
570 if (!len
|| !isdigit(line
[len
- 1]))
574 /* Fractional seconds. */
575 while (p
> line
&& isdigit(*p
))
580 /* Hours, minutes, and whole seconds. */
581 n
= short_time_len(line
, p
- line
);
585 return line
+ len
- p
+ n
;
588 static size_t trailing_spaces_len(const char *line
, size_t len
)
592 /* Expected format: ' ' x (1 or more) */
593 if (!len
|| line
[len
- 1] != ' ')
600 return line
+ len
- (p
+ 1);
607 static size_t diff_timestamp_len(const char *line
, size_t len
)
609 const char *end
= line
+ len
;
613 * Posix: 2010-07-05 19:41:17
614 * GNU: 2010-07-05 19:41:17.620000023 -0500
617 if (!isdigit(end
[-1]))
620 n
= sane_tz_len(line
, end
- line
);
622 n
= tz_with_colon_len(line
, end
- line
);
625 n
= short_time_len(line
, end
- line
);
627 n
= fractional_time_len(line
, end
- line
);
630 n
= date_len(line
, end
- line
);
631 if (!n
) /* No date. Too bad. */
635 if (end
== line
) /* No space before date. */
637 if (end
[-1] == '\t') { /* Success! */
639 return line
+ len
- end
;
641 if (end
[-1] != ' ') /* No space before date. */
644 /* Whitespace damage. */
645 end
-= trailing_spaces_len(line
, end
- line
);
646 return line
+ len
- end
;
649 static char *null_strdup(const char *s
)
651 return s
? xstrdup(s
) : NULL
;
654 static char *find_name_common(const char *line
, const char *def
,
655 int p_value
, const char *end
, int terminate
)
658 const char *start
= NULL
;
662 while (line
!= end
) {
665 if (!end
&& isspace(c
)) {
668 if (name_terminate(start
, line
-start
, c
, terminate
))
672 if (c
== '/' && !--p_value
)
676 return squash_slash(null_strdup(def
));
679 return squash_slash(null_strdup(def
));
682 * Generally we prefer the shorter name, especially
683 * if the other one is just a variation of that with
684 * something else tacked on to the end (ie "file.orig"
688 int deflen
= strlen(def
);
689 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
690 return squash_slash(xstrdup(def
));
694 char *ret
= xmalloc(root_len
+ len
+ 1);
696 memcpy(ret
+ root_len
, start
, len
);
697 ret
[root_len
+ len
] = '\0';
698 return squash_slash(ret
);
701 return squash_slash(xmemdupz(start
, len
));
704 static char *find_name(const char *line
, char *def
, int p_value
, int terminate
)
707 char *name
= find_name_gnu(line
, def
, p_value
);
712 return find_name_common(line
, def
, p_value
, NULL
, terminate
);
715 static char *find_name_traditional(const char *line
, char *def
, int p_value
)
717 size_t len
= strlen(line
);
721 char *name
= find_name_gnu(line
, def
, p_value
);
726 len
= strchrnul(line
, '\n') - line
;
727 date_len
= diff_timestamp_len(line
, len
);
729 return find_name_common(line
, def
, p_value
, NULL
, TERM_TAB
);
732 return find_name_common(line
, def
, p_value
, line
+ len
, 0);
735 static int count_slashes(const char *cp
)
747 * Given the string after "--- " or "+++ ", guess the appropriate
748 * p_value for the given patch.
750 static int guess_p_value(const char *nameline
)
755 if (is_dev_null(nameline
))
757 name
= find_name_traditional(nameline
, NULL
, 0);
760 cp
= strchr(name
, '/');
765 * Does it begin with "a/$our-prefix" and such? Then this is
766 * very likely to apply to our directory.
768 if (!strncmp(name
, prefix
, prefix_length
))
769 val
= count_slashes(prefix
);
772 if (!strncmp(cp
, prefix
, prefix_length
))
773 val
= count_slashes(prefix
) + 1;
781 * Does the ---/+++ line has the POSIX timestamp after the last HT?
782 * GNU diff puts epoch there to signal a creation/deletion event. Is
783 * this such a timestamp?
785 static int has_epoch_timestamp(const char *nameline
)
788 * We are only interested in epoch timestamp; any non-zero
789 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
790 * For the same reason, the date must be either 1969-12-31 or
791 * 1970-01-01, and the seconds part must be "00".
793 const char stamp_regexp
[] =
794 "^(1969-12-31|1970-01-01)"
796 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
798 "([-+][0-2][0-9]:?[0-5][0-9])\n";
799 const char *timestamp
= NULL
, *cp
, *colon
;
800 static regex_t
*stamp
;
806 for (cp
= nameline
; *cp
!= '\n'; cp
++) {
813 stamp
= xmalloc(sizeof(*stamp
));
814 if (regcomp(stamp
, stamp_regexp
, REG_EXTENDED
)) {
815 warning(_("Cannot prepare timestamp regexp %s"),
821 status
= regexec(stamp
, timestamp
, ARRAY_SIZE(m
), m
, 0);
823 if (status
!= REG_NOMATCH
)
824 warning(_("regexec returned %d for input: %s"),
829 zoneoffset
= strtol(timestamp
+ m
[3].rm_so
+ 1, (char **) &colon
, 10);
831 zoneoffset
= zoneoffset
* 60 + strtol(colon
+ 1, NULL
, 10);
833 zoneoffset
= (zoneoffset
/ 100) * 60 + (zoneoffset
% 100);
834 if (timestamp
[m
[3].rm_so
] == '-')
835 zoneoffset
= -zoneoffset
;
838 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
839 * (west of GMT) or 1970-01-01 (east of GMT)
841 if ((zoneoffset
< 0 && memcmp(timestamp
, "1969-12-31", 10)) ||
842 (0 <= zoneoffset
&& memcmp(timestamp
, "1970-01-01", 10)))
845 hourminute
= (strtol(timestamp
+ 11, NULL
, 10) * 60 +
846 strtol(timestamp
+ 14, NULL
, 10) -
849 return ((zoneoffset
< 0 && hourminute
== 1440) ||
850 (0 <= zoneoffset
&& !hourminute
));
854 * Get the name etc info from the ---/+++ lines of a traditional patch header
856 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
857 * files, we can happily check the index for a match, but for creating a
858 * new file we should try to match whatever "patch" does. I have no idea.
860 static void parse_traditional_patch(const char *first
, const char *second
, struct patch
*patch
)
864 first
+= 4; /* skip "--- " */
865 second
+= 4; /* skip "+++ " */
866 if (!p_value_known
) {
868 p
= guess_p_value(first
);
869 q
= guess_p_value(second
);
871 if (0 <= p
&& p
== q
) {
876 if (is_dev_null(first
)) {
878 patch
->is_delete
= 0;
879 name
= find_name_traditional(second
, NULL
, p_value
);
880 patch
->new_name
= name
;
881 } else if (is_dev_null(second
)) {
883 patch
->is_delete
= 1;
884 name
= find_name_traditional(first
, NULL
, p_value
);
885 patch
->old_name
= name
;
888 first_name
= find_name_traditional(first
, NULL
, p_value
);
889 name
= find_name_traditional(second
, first_name
, p_value
);
891 if (has_epoch_timestamp(first
)) {
893 patch
->is_delete
= 0;
894 patch
->new_name
= name
;
895 } else if (has_epoch_timestamp(second
)) {
897 patch
->is_delete
= 1;
898 patch
->old_name
= name
;
900 patch
->old_name
= name
;
901 patch
->new_name
= xstrdup(name
);
905 die(_("unable to find filename in patch at line %d"), linenr
);
908 static int gitdiff_hdrend(const char *line
, struct patch
*patch
)
914 * We're anal about diff header consistency, to make
915 * sure that we don't end up having strange ambiguous
916 * patches floating around.
918 * As a result, gitdiff_{old|new}name() will check
919 * their names against any previous information, just
922 #define DIFF_OLD_NAME 0
923 #define DIFF_NEW_NAME 1
925 static char *gitdiff_verify_name(const char *line
, int isnull
, char *orig_name
, int side
)
927 if (!orig_name
&& !isnull
)
928 return find_name(line
, NULL
, p_value
, TERM_TAB
);
937 die(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"), name
, linenr
);
938 another
= find_name(line
, NULL
, p_value
, TERM_TAB
);
939 if (!another
|| memcmp(another
, name
, len
+ 1))
940 die((side
== DIFF_NEW_NAME
) ?
941 _("git apply: bad git-diff - inconsistent new filename on line %d") :
942 _("git apply: bad git-diff - inconsistent old filename on line %d"), linenr
);
947 /* expect "/dev/null" */
948 if (memcmp("/dev/null", line
, 9) || line
[9] != '\n')
949 die(_("git apply: bad git-diff - expected /dev/null on line %d"), linenr
);
954 static int gitdiff_oldname(const char *line
, struct patch
*patch
)
956 char *orig
= patch
->old_name
;
957 patch
->old_name
= gitdiff_verify_name(line
, patch
->is_new
, patch
->old_name
,
959 if (orig
!= patch
->old_name
)
964 static int gitdiff_newname(const char *line
, struct patch
*patch
)
966 char *orig
= patch
->new_name
;
967 patch
->new_name
= gitdiff_verify_name(line
, patch
->is_delete
, patch
->new_name
,
969 if (orig
!= patch
->new_name
)
974 static int gitdiff_oldmode(const char *line
, struct patch
*patch
)
976 patch
->old_mode
= strtoul(line
, NULL
, 8);
980 static int gitdiff_newmode(const char *line
, struct patch
*patch
)
982 patch
->new_mode
= strtoul(line
, NULL
, 8);
986 static int gitdiff_delete(const char *line
, struct patch
*patch
)
988 patch
->is_delete
= 1;
989 free(patch
->old_name
);
990 patch
->old_name
= null_strdup(patch
->def_name
);
991 return gitdiff_oldmode(line
, patch
);
994 static int gitdiff_newfile(const char *line
, struct patch
*patch
)
997 free(patch
->new_name
);
998 patch
->new_name
= null_strdup(patch
->def_name
);
999 return gitdiff_newmode(line
, patch
);
1002 static int gitdiff_copysrc(const char *line
, struct patch
*patch
)
1005 free(patch
->old_name
);
1006 patch
->old_name
= find_name(line
, NULL
, p_value
? p_value
- 1 : 0, 0);
1010 static int gitdiff_copydst(const char *line
, struct patch
*patch
)
1013 free(patch
->new_name
);
1014 patch
->new_name
= find_name(line
, NULL
, p_value
? p_value
- 1 : 0, 0);
1018 static int gitdiff_renamesrc(const char *line
, struct patch
*patch
)
1020 patch
->is_rename
= 1;
1021 free(patch
->old_name
);
1022 patch
->old_name
= find_name(line
, NULL
, p_value
? p_value
- 1 : 0, 0);
1026 static int gitdiff_renamedst(const char *line
, struct patch
*patch
)
1028 patch
->is_rename
= 1;
1029 free(patch
->new_name
);
1030 patch
->new_name
= find_name(line
, NULL
, p_value
? p_value
- 1 : 0, 0);
1034 static int gitdiff_similarity(const char *line
, struct patch
*patch
)
1036 if ((patch
->score
= strtoul(line
, NULL
, 10)) == ULONG_MAX
)
1041 static int gitdiff_dissimilarity(const char *line
, struct patch
*patch
)
1043 if ((patch
->score
= strtoul(line
, NULL
, 10)) == ULONG_MAX
)
1048 static int gitdiff_index(const char *line
, struct patch
*patch
)
1051 * index line is N hexadecimal, "..", N hexadecimal,
1052 * and optional space with octal mode.
1054 const char *ptr
, *eol
;
1057 ptr
= strchr(line
, '.');
1058 if (!ptr
|| ptr
[1] != '.' || 40 < ptr
- line
)
1061 memcpy(patch
->old_sha1_prefix
, line
, len
);
1062 patch
->old_sha1_prefix
[len
] = 0;
1065 ptr
= strchr(line
, ' ');
1066 eol
= strchr(line
, '\n');
1068 if (!ptr
|| eol
< ptr
)
1074 memcpy(patch
->new_sha1_prefix
, line
, len
);
1075 patch
->new_sha1_prefix
[len
] = 0;
1077 patch
->old_mode
= strtoul(ptr
+1, NULL
, 8);
1082 * This is normal for a diff that doesn't change anything: we'll fall through
1083 * into the next diff. Tell the parser to break out.
1085 static int gitdiff_unrecognized(const char *line
, struct patch
*patch
)
1090 static const char *stop_at_slash(const char *line
, int llen
)
1092 int nslash
= p_value
;
1095 for (i
= 0; i
< llen
; i
++) {
1097 if (ch
== '/' && --nslash
<= 0)
1104 * This is to extract the same name that appears on "diff --git"
1105 * line. We do not find and return anything if it is a rename
1106 * patch, and it is OK because we will find the name elsewhere.
1107 * We need to reliably find name only when it is mode-change only,
1108 * creation or deletion of an empty file. In any of these cases,
1109 * both sides are the same name under a/ and b/ respectively.
1111 static char *git_header_name(const char *line
, int llen
)
1114 const char *second
= NULL
;
1115 size_t len
, line_len
;
1117 line
+= strlen("diff --git ");
1118 llen
-= strlen("diff --git ");
1122 struct strbuf first
= STRBUF_INIT
;
1123 struct strbuf sp
= STRBUF_INIT
;
1125 if (unquote_c_style(&first
, line
, &second
))
1126 goto free_and_fail1
;
1128 /* advance to the first slash */
1129 cp
= stop_at_slash(first
.buf
, first
.len
);
1130 /* we do not accept absolute paths */
1131 if (!cp
|| cp
== first
.buf
)
1132 goto free_and_fail1
;
1133 strbuf_remove(&first
, 0, cp
+ 1 - first
.buf
);
1136 * second points at one past closing dq of name.
1137 * find the second name.
1139 while ((second
< line
+ llen
) && isspace(*second
))
1142 if (line
+ llen
<= second
)
1143 goto free_and_fail1
;
1144 if (*second
== '"') {
1145 if (unquote_c_style(&sp
, second
, NULL
))
1146 goto free_and_fail1
;
1147 cp
= stop_at_slash(sp
.buf
, sp
.len
);
1148 if (!cp
|| cp
== sp
.buf
)
1149 goto free_and_fail1
;
1150 /* They must match, otherwise ignore */
1151 if (strcmp(cp
+ 1, first
.buf
))
1152 goto free_and_fail1
;
1153 strbuf_release(&sp
);
1154 return strbuf_detach(&first
, NULL
);
1157 /* unquoted second */
1158 cp
= stop_at_slash(second
, line
+ llen
- second
);
1159 if (!cp
|| cp
== second
)
1160 goto free_and_fail1
;
1162 if (line
+ llen
- cp
!= first
.len
+ 1 ||
1163 memcmp(first
.buf
, cp
, first
.len
))
1164 goto free_and_fail1
;
1165 return strbuf_detach(&first
, NULL
);
1168 strbuf_release(&first
);
1169 strbuf_release(&sp
);
1173 /* unquoted first name */
1174 name
= stop_at_slash(line
, llen
);
1175 if (!name
|| name
== line
)
1180 * since the first name is unquoted, a dq if exists must be
1181 * the beginning of the second name.
1183 for (second
= name
; second
< line
+ llen
; second
++) {
1184 if (*second
== '"') {
1185 struct strbuf sp
= STRBUF_INIT
;
1188 if (unquote_c_style(&sp
, second
, NULL
))
1189 goto free_and_fail2
;
1191 np
= stop_at_slash(sp
.buf
, sp
.len
);
1192 if (!np
|| np
== sp
.buf
)
1193 goto free_and_fail2
;
1196 len
= sp
.buf
+ sp
.len
- np
;
1197 if (len
< second
- name
&&
1198 !strncmp(np
, name
, len
) &&
1199 isspace(name
[len
])) {
1201 strbuf_remove(&sp
, 0, np
- sp
.buf
);
1202 return strbuf_detach(&sp
, NULL
);
1206 strbuf_release(&sp
);
1212 * Accept a name only if it shows up twice, exactly the same
1215 second
= strchr(name
, '\n');
1218 line_len
= second
- name
;
1219 for (len
= 0 ; ; len
++) {
1220 switch (name
[len
]) {
1225 case '\t': case ' ':
1226 second
= stop_at_slash(name
+ len
, line_len
- len
);
1230 if (second
[len
] == '\n' && !strncmp(name
, second
, len
)) {
1231 return xmemdupz(name
, len
);
1237 /* Verify that we recognize the lines following a git header */
1238 static int parse_git_header(const char *line
, int len
, unsigned int size
, struct patch
*patch
)
1240 unsigned long offset
;
1242 /* A git diff has explicit new/delete information, so we don't guess */
1244 patch
->is_delete
= 0;
1247 * Some things may not have the old name in the
1248 * rest of the headers anywhere (pure mode changes,
1249 * or removing or adding empty files), so we get
1250 * the default name from the header.
1252 patch
->def_name
= git_header_name(line
, len
);
1253 if (patch
->def_name
&& root
) {
1254 char *s
= xmalloc(root_len
+ strlen(patch
->def_name
) + 1);
1256 strcpy(s
+ root_len
, patch
->def_name
);
1257 free(patch
->def_name
);
1258 patch
->def_name
= s
;
1264 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1265 static const struct opentry
{
1267 int (*fn
)(const char *, struct patch
*);
1269 { "@@ -", gitdiff_hdrend
},
1270 { "--- ", gitdiff_oldname
},
1271 { "+++ ", gitdiff_newname
},
1272 { "old mode ", gitdiff_oldmode
},
1273 { "new mode ", gitdiff_newmode
},
1274 { "deleted file mode ", gitdiff_delete
},
1275 { "new file mode ", gitdiff_newfile
},
1276 { "copy from ", gitdiff_copysrc
},
1277 { "copy to ", gitdiff_copydst
},
1278 { "rename old ", gitdiff_renamesrc
},
1279 { "rename new ", gitdiff_renamedst
},
1280 { "rename from ", gitdiff_renamesrc
},
1281 { "rename to ", gitdiff_renamedst
},
1282 { "similarity index ", gitdiff_similarity
},
1283 { "dissimilarity index ", gitdiff_dissimilarity
},
1284 { "index ", gitdiff_index
},
1285 { "", gitdiff_unrecognized
},
1289 len
= linelen(line
, size
);
1290 if (!len
|| line
[len
-1] != '\n')
1292 for (i
= 0; i
< ARRAY_SIZE(optable
); i
++) {
1293 const struct opentry
*p
= optable
+ i
;
1294 int oplen
= strlen(p
->str
);
1295 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
1297 if (p
->fn(line
+ oplen
, patch
) < 0)
1306 static int parse_num(const char *line
, unsigned long *p
)
1310 if (!isdigit(*line
))
1312 *p
= strtoul(line
, &ptr
, 10);
1316 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
1317 unsigned long *p1
, unsigned long *p2
)
1321 if (offset
< 0 || offset
>= len
)
1326 digits
= parse_num(line
, p1
);
1336 digits
= parse_num(line
+1, p2
);
1345 ex
= strlen(expect
);
1348 if (memcmp(line
, expect
, ex
))
1354 static void recount_diff(const char *line
, int size
, struct fragment
*fragment
)
1356 int oldlines
= 0, newlines
= 0, ret
= 0;
1359 warning("recount: ignore empty hunk");
1364 int len
= linelen(line
, size
);
1372 case ' ': case '\n':
1384 ret
= size
< 3 || prefixcmp(line
, "@@ ");
1387 ret
= size
< 5 || prefixcmp(line
, "diff ");
1394 warning(_("recount: unexpected line: %.*s"),
1395 (int)linelen(line
, size
), line
);
1400 fragment
->oldlines
= oldlines
;
1401 fragment
->newlines
= newlines
;
1405 * Parse a unified diff fragment header of the
1406 * form "@@ -a,b +c,d @@"
1408 static int parse_fragment_header(const char *line
, int len
, struct fragment
*fragment
)
1412 if (!len
|| line
[len
-1] != '\n')
1415 /* Figure out the number of lines in a fragment */
1416 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
1417 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
1422 static int find_header(const char *line
, unsigned long size
, int *hdrsize
, struct patch
*patch
)
1424 unsigned long offset
, len
;
1426 patch
->is_toplevel_relative
= 0;
1427 patch
->is_rename
= patch
->is_copy
= 0;
1428 patch
->is_new
= patch
->is_delete
= -1;
1429 patch
->old_mode
= patch
->new_mode
= 0;
1430 patch
->old_name
= patch
->new_name
= NULL
;
1431 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1432 unsigned long nextlen
;
1434 len
= linelen(line
, size
);
1438 /* Testing this early allows us to take a few shortcuts.. */
1443 * Make sure we don't find any unconnected patch fragments.
1444 * That's a sign that we didn't find a header, and that a
1445 * patch has become corrupted/broken up.
1447 if (!memcmp("@@ -", line
, 4)) {
1448 struct fragment dummy
;
1449 if (parse_fragment_header(line
, len
, &dummy
) < 0)
1451 die(_("patch fragment without header at line %d: %.*s"),
1452 linenr
, (int)len
-1, line
);
1459 * Git patch? It might not have a real patch, just a rename
1460 * or mode change, so we handle that specially
1462 if (!memcmp("diff --git ", line
, 11)) {
1463 int git_hdr_len
= parse_git_header(line
, len
, size
, patch
);
1464 if (git_hdr_len
<= len
)
1466 if (!patch
->old_name
&& !patch
->new_name
) {
1467 if (!patch
->def_name
)
1468 die(Q_("git diff header lacks filename information when removing "
1469 "%d leading pathname component (line %d)",
1470 "git diff header lacks filename information when removing "
1471 "%d leading pathname components (line %d)",
1474 patch
->old_name
= xstrdup(patch
->def_name
);
1475 patch
->new_name
= xstrdup(patch
->def_name
);
1477 if (!patch
->is_delete
&& !patch
->new_name
)
1478 die("git diff header lacks filename information "
1479 "(line %d)", linenr
);
1480 patch
->is_toplevel_relative
= 1;
1481 *hdrsize
= git_hdr_len
;
1485 /* --- followed by +++ ? */
1486 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
1490 * We only accept unified patches, so we want it to
1491 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1492 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1494 nextlen
= linelen(line
+ len
, size
- len
);
1495 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
1498 /* Ok, we'll consider it a patch */
1499 parse_traditional_patch(line
, line
+len
, patch
);
1500 *hdrsize
= len
+ nextlen
;
1507 static void record_ws_error(unsigned result
, const char *line
, int len
, int linenr
)
1515 if (squelch_whitespace_errors
&&
1516 squelch_whitespace_errors
< whitespace_error
)
1519 err
= whitespace_error_string(result
);
1520 fprintf(stderr
, "%s:%d: %s.\n%.*s\n",
1521 patch_input_file
, linenr
, err
, len
, line
);
1525 static void check_whitespace(const char *line
, int len
, unsigned ws_rule
)
1527 unsigned result
= ws_check(line
+ 1, len
- 1, ws_rule
);
1529 record_ws_error(result
, line
+ 1, len
- 2, linenr
);
1533 * Parse a unified diff. Note that this really needs to parse each
1534 * fragment separately, since the only way to know the difference
1535 * between a "---" that is part of a patch, and a "---" that starts
1536 * the next patch is to look at the line counts..
1538 static int parse_fragment(const char *line
, unsigned long size
,
1539 struct patch
*patch
, struct fragment
*fragment
)
1542 int len
= linelen(line
, size
), offset
;
1543 unsigned long oldlines
, newlines
;
1544 unsigned long leading
, trailing
;
1546 offset
= parse_fragment_header(line
, len
, fragment
);
1549 if (offset
> 0 && patch
->recount
)
1550 recount_diff(line
+ offset
, size
- offset
, fragment
);
1551 oldlines
= fragment
->oldlines
;
1552 newlines
= fragment
->newlines
;
1556 /* Parse the thing.. */
1560 added
= deleted
= 0;
1563 offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
1564 if (!oldlines
&& !newlines
)
1566 len
= linelen(line
, size
);
1567 if (!len
|| line
[len
-1] != '\n')
1572 case '\n': /* newer GNU diff, an empty context line */
1576 if (!deleted
&& !added
)
1581 if (apply_in_reverse
&&
1582 ws_error_action
!= nowarn_ws_error
)
1583 check_whitespace(line
, len
, patch
->ws_rule
);
1589 if (!apply_in_reverse
&&
1590 ws_error_action
!= nowarn_ws_error
)
1591 check_whitespace(line
, len
, patch
->ws_rule
);
1598 * We allow "\ No newline at end of file". Depending
1599 * on locale settings when the patch was produced we
1600 * don't know what this line looks like. The only
1601 * thing we do know is that it begins with "\ ".
1602 * Checking for 12 is just for sanity check -- any
1603 * l10n of "\ No newline..." is at least that long.
1606 if (len
< 12 || memcmp(line
, "\\ ", 2))
1611 if (oldlines
|| newlines
)
1613 fragment
->leading
= leading
;
1614 fragment
->trailing
= trailing
;
1617 * If a fragment ends with an incomplete line, we failed to include
1618 * it in the above loop because we hit oldlines == newlines == 0
1621 if (12 < size
&& !memcmp(line
, "\\ ", 2))
1622 offset
+= linelen(line
, size
);
1624 patch
->lines_added
+= added
;
1625 patch
->lines_deleted
+= deleted
;
1627 if (0 < patch
->is_new
&& oldlines
)
1628 return error(_("new file depends on old contents"));
1629 if (0 < patch
->is_delete
&& newlines
)
1630 return error(_("deleted file still has contents"));
1635 * We have seen "diff --git a/... b/..." header (or a traditional patch
1636 * header). Read hunks that belong to this patch into fragments and hang
1637 * them to the given patch structure.
1639 * The (fragment->patch, fragment->size) pair points into the memory given
1640 * by the caller, not a copy, when we return.
1642 static int parse_single_patch(const char *line
, unsigned long size
, struct patch
*patch
)
1644 unsigned long offset
= 0;
1645 unsigned long oldlines
= 0, newlines
= 0, context
= 0;
1646 struct fragment
**fragp
= &patch
->fragments
;
1648 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
1649 struct fragment
*fragment
;
1652 fragment
= xcalloc(1, sizeof(*fragment
));
1653 fragment
->linenr
= linenr
;
1654 len
= parse_fragment(line
, size
, patch
, fragment
);
1656 die(_("corrupt patch at line %d"), linenr
);
1657 fragment
->patch
= line
;
1658 fragment
->size
= len
;
1659 oldlines
+= fragment
->oldlines
;
1660 newlines
+= fragment
->newlines
;
1661 context
+= fragment
->leading
+ fragment
->trailing
;
1664 fragp
= &fragment
->next
;
1672 * If something was removed (i.e. we have old-lines) it cannot
1673 * be creation, and if something was added it cannot be
1674 * deletion. However, the reverse is not true; --unified=0
1675 * patches that only add are not necessarily creation even
1676 * though they do not have any old lines, and ones that only
1677 * delete are not necessarily deletion.
1679 * Unfortunately, a real creation/deletion patch do _not_ have
1680 * any context line by definition, so we cannot safely tell it
1681 * apart with --unified=0 insanity. At least if the patch has
1682 * more than one hunk it is not creation or deletion.
1684 if (patch
->is_new
< 0 &&
1685 (oldlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1687 if (patch
->is_delete
< 0 &&
1688 (newlines
|| (patch
->fragments
&& patch
->fragments
->next
)))
1689 patch
->is_delete
= 0;
1691 if (0 < patch
->is_new
&& oldlines
)
1692 die(_("new file %s depends on old contents"), patch
->new_name
);
1693 if (0 < patch
->is_delete
&& newlines
)
1694 die(_("deleted file %s still has contents"), patch
->old_name
);
1695 if (!patch
->is_delete
&& !newlines
&& context
)
1698 "file %s becomes empty but is not deleted"),
1704 static inline int metadata_changes(struct patch
*patch
)
1706 return patch
->is_rename
> 0 ||
1707 patch
->is_copy
> 0 ||
1708 patch
->is_new
> 0 ||
1710 (patch
->old_mode
&& patch
->new_mode
&&
1711 patch
->old_mode
!= patch
->new_mode
);
1714 static char *inflate_it(const void *data
, unsigned long size
,
1715 unsigned long inflated_size
)
1721 memset(&stream
, 0, sizeof(stream
));
1723 stream
.next_in
= (unsigned char *)data
;
1724 stream
.avail_in
= size
;
1725 stream
.next_out
= out
= xmalloc(inflated_size
);
1726 stream
.avail_out
= inflated_size
;
1727 git_inflate_init(&stream
);
1728 st
= git_inflate(&stream
, Z_FINISH
);
1729 git_inflate_end(&stream
);
1730 if ((st
!= Z_STREAM_END
) || stream
.total_out
!= inflated_size
) {
1738 * Read a binary hunk and return a new fragment; fragment->patch
1739 * points at an allocated memory that the caller must free, so
1740 * it is marked as "->free_patch = 1".
1742 static struct fragment
*parse_binary_hunk(char **buf_p
,
1743 unsigned long *sz_p
,
1748 * Expect a line that begins with binary patch method ("literal"
1749 * or "delta"), followed by the length of data before deflating.
1750 * a sequence of 'length-byte' followed by base-85 encoded data
1751 * should follow, terminated by a newline.
1753 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1754 * and we would limit the patch line to 66 characters,
1755 * so one line can fit up to 13 groups that would decode
1756 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1757 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1760 unsigned long size
= *sz_p
;
1761 char *buffer
= *buf_p
;
1763 unsigned long origlen
;
1766 struct fragment
*frag
;
1768 llen
= linelen(buffer
, size
);
1773 if (!prefixcmp(buffer
, "delta ")) {
1774 patch_method
= BINARY_DELTA_DEFLATED
;
1775 origlen
= strtoul(buffer
+ 6, NULL
, 10);
1777 else if (!prefixcmp(buffer
, "literal ")) {
1778 patch_method
= BINARY_LITERAL_DEFLATED
;
1779 origlen
= strtoul(buffer
+ 8, NULL
, 10);
1787 int byte_length
, max_byte_length
, newsize
;
1788 llen
= linelen(buffer
, size
);
1792 /* consume the blank line */
1798 * Minimum line is "A00000\n" which is 7-byte long,
1799 * and the line length must be multiple of 5 plus 2.
1801 if ((llen
< 7) || (llen
-2) % 5)
1803 max_byte_length
= (llen
- 2) / 5 * 4;
1804 byte_length
= *buffer
;
1805 if ('A' <= byte_length
&& byte_length
<= 'Z')
1806 byte_length
= byte_length
- 'A' + 1;
1807 else if ('a' <= byte_length
&& byte_length
<= 'z')
1808 byte_length
= byte_length
- 'a' + 27;
1811 /* if the input length was not multiple of 4, we would
1812 * have filler at the end but the filler should never
1815 if (max_byte_length
< byte_length
||
1816 byte_length
<= max_byte_length
- 4)
1818 newsize
= hunk_size
+ byte_length
;
1819 data
= xrealloc(data
, newsize
);
1820 if (decode_85(data
+ hunk_size
, buffer
+ 1, byte_length
))
1822 hunk_size
= newsize
;
1827 frag
= xcalloc(1, sizeof(*frag
));
1828 frag
->patch
= inflate_it(data
, hunk_size
, origlen
);
1829 frag
->free_patch
= 1;
1833 frag
->size
= origlen
;
1837 frag
->binary_patch_method
= patch_method
;
1843 error(_("corrupt binary patch at line %d: %.*s"),
1844 linenr
-1, llen
-1, buffer
);
1848 static int parse_binary(char *buffer
, unsigned long size
, struct patch
*patch
)
1851 * We have read "GIT binary patch\n"; what follows is a line
1852 * that says the patch method (currently, either "literal" or
1853 * "delta") and the length of data before deflating; a
1854 * sequence of 'length-byte' followed by base-85 encoded data
1857 * When a binary patch is reversible, there is another binary
1858 * hunk in the same format, starting with patch method (either
1859 * "literal" or "delta") with the length of data, and a sequence
1860 * of length-byte + base-85 encoded data, terminated with another
1861 * empty line. This data, when applied to the postimage, produces
1864 struct fragment
*forward
;
1865 struct fragment
*reverse
;
1869 forward
= parse_binary_hunk(&buffer
, &size
, &status
, &used
);
1870 if (!forward
&& !status
)
1871 /* there has to be one hunk (forward hunk) */
1872 return error(_("unrecognized binary patch at line %d"), linenr
-1);
1874 /* otherwise we already gave an error message */
1877 reverse
= parse_binary_hunk(&buffer
, &size
, &status
, &used_1
);
1882 * Not having reverse hunk is not an error, but having
1883 * a corrupt reverse hunk is.
1885 free((void*) forward
->patch
);
1889 forward
->next
= reverse
;
1890 patch
->fragments
= forward
;
1891 patch
->is_binary
= 1;
1896 * Read the patch text in "buffer" taht extends for "size" bytes; stop
1897 * reading after seeing a single patch (i.e. changes to a single file).
1898 * Create fragments (i.e. patch hunks) and hang them to the given patch.
1899 * Return the number of bytes consumed, so that the caller can call us
1900 * again for the next patch.
1902 static int parse_chunk(char *buffer
, unsigned long size
, struct patch
*patch
)
1904 int hdrsize
, patchsize
;
1905 int offset
= find_header(buffer
, size
, &hdrsize
, patch
);
1910 patch
->ws_rule
= whitespace_rule(patch
->new_name
1914 patchsize
= parse_single_patch(buffer
+ offset
+ hdrsize
,
1915 size
- offset
- hdrsize
, patch
);
1918 static const char *binhdr
[] = {
1923 static const char git_binary
[] = "GIT binary patch\n";
1925 int hd
= hdrsize
+ offset
;
1926 unsigned long llen
= linelen(buffer
+ hd
, size
- hd
);
1928 if (llen
== sizeof(git_binary
) - 1 &&
1929 !memcmp(git_binary
, buffer
+ hd
, llen
)) {
1932 used
= parse_binary(buffer
+ hd
+ llen
,
1933 size
- hd
- llen
, patch
);
1935 patchsize
= used
+ llen
;
1939 else if (!memcmp(" differ\n", buffer
+ hd
+ llen
- 8, 8)) {
1940 for (i
= 0; binhdr
[i
]; i
++) {
1941 int len
= strlen(binhdr
[i
]);
1942 if (len
< size
- hd
&&
1943 !memcmp(binhdr
[i
], buffer
+ hd
, len
)) {
1945 patch
->is_binary
= 1;
1952 /* Empty patch cannot be applied if it is a text patch
1953 * without metadata change. A binary patch appears
1956 if ((apply
|| check
) &&
1957 (!patch
->is_binary
&& !metadata_changes(patch
)))
1958 die(_("patch with only garbage at line %d"), linenr
);
1961 return offset
+ hdrsize
+ patchsize
;
1964 #define swap(a,b) myswap((a),(b),sizeof(a))
1966 #define myswap(a, b, size) do { \
1967 unsigned char mytmp[size]; \
1968 memcpy(mytmp, &a, size); \
1969 memcpy(&a, &b, size); \
1970 memcpy(&b, mytmp, size); \
1973 static void reverse_patches(struct patch
*p
)
1975 for (; p
; p
= p
->next
) {
1976 struct fragment
*frag
= p
->fragments
;
1978 swap(p
->new_name
, p
->old_name
);
1979 swap(p
->new_mode
, p
->old_mode
);
1980 swap(p
->is_new
, p
->is_delete
);
1981 swap(p
->lines_added
, p
->lines_deleted
);
1982 swap(p
->old_sha1_prefix
, p
->new_sha1_prefix
);
1984 for (; frag
; frag
= frag
->next
) {
1985 swap(frag
->newpos
, frag
->oldpos
);
1986 swap(frag
->newlines
, frag
->oldlines
);
1991 static const char pluses
[] =
1992 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1993 static const char minuses
[]=
1994 "----------------------------------------------------------------------";
1996 static void show_stats(struct patch
*patch
)
1998 struct strbuf qname
= STRBUF_INIT
;
1999 char *cp
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
2002 quote_c_style(cp
, &qname
, NULL
, 0);
2005 * "scale" the filename
2011 if (qname
.len
> max
) {
2012 cp
= strchr(qname
.buf
+ qname
.len
+ 3 - max
, '/');
2014 cp
= qname
.buf
+ qname
.len
+ 3 - max
;
2015 strbuf_splice(&qname
, 0, cp
- qname
.buf
, "...", 3);
2018 if (patch
->is_binary
) {
2019 printf(" %-*s | Bin\n", max
, qname
.buf
);
2020 strbuf_release(&qname
);
2024 printf(" %-*s |", max
, qname
.buf
);
2025 strbuf_release(&qname
);
2028 * scale the add/delete
2030 max
= max
+ max_change
> 70 ? 70 - max
: max_change
;
2031 add
= patch
->lines_added
;
2032 del
= patch
->lines_deleted
;
2034 if (max_change
> 0) {
2035 int total
= ((add
+ del
) * max
+ max_change
/ 2) / max_change
;
2036 add
= (add
* max
+ max_change
/ 2) / max_change
;
2039 printf("%5d %.*s%.*s\n", patch
->lines_added
+ patch
->lines_deleted
,
2040 add
, pluses
, del
, minuses
);
2043 static int read_old_data(struct stat
*st
, const char *path
, struct strbuf
*buf
)
2045 switch (st
->st_mode
& S_IFMT
) {
2047 if (strbuf_readlink(buf
, path
, st
->st_size
) < 0)
2048 return error(_("unable to read symlink %s"), path
);
2051 if (strbuf_read_file(buf
, path
, st
->st_size
) != st
->st_size
)
2052 return error(_("unable to open or read %s"), path
);
2053 convert_to_git(path
, buf
->buf
, buf
->len
, buf
, 0);
2061 * Update the preimage, and the common lines in postimage,
2062 * from buffer buf of length len. If postlen is 0 the postimage
2063 * is updated in place, otherwise it's updated on a new buffer
2067 static void update_pre_post_images(struct image
*preimage
,
2068 struct image
*postimage
,
2070 size_t len
, size_t postlen
)
2073 char *new, *old
, *fixed
;
2074 struct image fixed_preimage
;
2077 * Update the preimage with whitespace fixes. Note that we
2078 * are not losing preimage->buf -- apply_one_fragment() will
2081 prepare_image(&fixed_preimage
, buf
, len
, 1);
2082 assert(fixed_preimage
.nr
== preimage
->nr
);
2083 for (i
= 0; i
< preimage
->nr
; i
++)
2084 fixed_preimage
.line
[i
].flag
= preimage
->line
[i
].flag
;
2085 free(preimage
->line_allocated
);
2086 *preimage
= fixed_preimage
;
2089 * Adjust the common context lines in postimage. This can be
2090 * done in-place when we are just doing whitespace fixing,
2091 * which does not make the string grow, but needs a new buffer
2092 * when ignoring whitespace causes the update, since in this case
2093 * we could have e.g. tabs converted to multiple spaces.
2094 * We trust the caller to tell us if the update can be done
2095 * in place (postlen==0) or not.
2097 old
= postimage
->buf
;
2099 new = postimage
->buf
= xmalloc(postlen
);
2102 fixed
= preimage
->buf
;
2103 for (i
= ctx
= 0; i
< postimage
->nr
; i
++) {
2104 size_t len
= postimage
->line
[i
].len
;
2105 if (!(postimage
->line
[i
].flag
& LINE_COMMON
)) {
2106 /* an added line -- no counterparts in preimage */
2107 memmove(new, old
, len
);
2113 /* a common context -- skip it in the original postimage */
2116 /* and find the corresponding one in the fixed preimage */
2117 while (ctx
< preimage
->nr
&&
2118 !(preimage
->line
[ctx
].flag
& LINE_COMMON
)) {
2119 fixed
+= preimage
->line
[ctx
].len
;
2122 if (preimage
->nr
<= ctx
)
2125 /* and copy it in, while fixing the line length */
2126 len
= preimage
->line
[ctx
].len
;
2127 memcpy(new, fixed
, len
);
2130 postimage
->line
[i
].len
= len
;
2134 /* Fix the length of the whole thing */
2135 postimage
->len
= new - postimage
->buf
;
2138 static int match_fragment(struct image
*img
,
2139 struct image
*preimage
,
2140 struct image
*postimage
,
2144 int match_beginning
, int match_end
)
2147 char *fixed_buf
, *buf
, *orig
, *target
;
2148 struct strbuf fixed
;
2152 if (preimage
->nr
+ try_lno
<= img
->nr
) {
2154 * The hunk falls within the boundaries of img.
2156 preimage_limit
= preimage
->nr
;
2157 if (match_end
&& (preimage
->nr
+ try_lno
!= img
->nr
))
2159 } else if (ws_error_action
== correct_ws_error
&&
2160 (ws_rule
& WS_BLANK_AT_EOF
)) {
2162 * This hunk extends beyond the end of img, and we are
2163 * removing blank lines at the end of the file. This
2164 * many lines from the beginning of the preimage must
2165 * match with img, and the remainder of the preimage
2168 preimage_limit
= img
->nr
- try_lno
;
2171 * The hunk extends beyond the end of the img and
2172 * we are not removing blanks at the end, so we
2173 * should reject the hunk at this position.
2178 if (match_beginning
&& try_lno
)
2181 /* Quick hash check */
2182 for (i
= 0; i
< preimage_limit
; i
++)
2183 if ((img
->line
[try_lno
+ i
].flag
& LINE_PATCHED
) ||
2184 (preimage
->line
[i
].hash
!= img
->line
[try_lno
+ i
].hash
))
2187 if (preimage_limit
== preimage
->nr
) {
2189 * Do we have an exact match? If we were told to match
2190 * at the end, size must be exactly at try+fragsize,
2191 * otherwise try+fragsize must be still within the preimage,
2192 * and either case, the old piece should match the preimage
2196 ? (try + preimage
->len
== img
->len
)
2197 : (try + preimage
->len
<= img
->len
)) &&
2198 !memcmp(img
->buf
+ try, preimage
->buf
, preimage
->len
))
2202 * The preimage extends beyond the end of img, so
2203 * there cannot be an exact match.
2205 * There must be one non-blank context line that match
2206 * a line before the end of img.
2210 buf
= preimage
->buf
;
2212 for (i
= 0; i
< preimage_limit
; i
++)
2213 buf_end
+= preimage
->line
[i
].len
;
2215 for ( ; buf
< buf_end
; buf
++)
2223 * No exact match. If we are ignoring whitespace, run a line-by-line
2224 * fuzzy matching. We collect all the line length information because
2225 * we need it to adjust whitespace if we match.
2227 if (ws_ignore_action
== ignore_ws_change
) {
2230 size_t postlen
= postimage
->len
;
2234 for (i
= 0; i
< preimage_limit
; i
++) {
2235 size_t prelen
= preimage
->line
[i
].len
;
2236 size_t imglen
= img
->line
[try_lno
+i
].len
;
2238 if (!fuzzy_matchlines(img
->buf
+ try + imgoff
, imglen
,
2239 preimage
->buf
+ preoff
, prelen
))
2241 if (preimage
->line
[i
].flag
& LINE_COMMON
)
2242 postlen
+= imglen
- prelen
;
2248 * Ok, the preimage matches with whitespace fuzz.
2250 * imgoff now holds the true length of the target that
2251 * matches the preimage before the end of the file.
2253 * Count the number of characters in the preimage that fall
2254 * beyond the end of the file and make sure that all of them
2255 * are whitespace characters. (This can only happen if
2256 * we are removing blank lines at the end of the file.)
2258 buf
= preimage_eof
= preimage
->buf
+ preoff
;
2259 for ( ; i
< preimage
->nr
; i
++)
2260 preoff
+= preimage
->line
[i
].len
;
2261 preimage_end
= preimage
->buf
+ preoff
;
2262 for ( ; buf
< preimage_end
; buf
++)
2267 * Update the preimage and the common postimage context
2268 * lines to use the same whitespace as the target.
2269 * If whitespace is missing in the target (i.e.
2270 * if the preimage extends beyond the end of the file),
2271 * use the whitespace from the preimage.
2273 extra_chars
= preimage_end
- preimage_eof
;
2274 strbuf_init(&fixed
, imgoff
+ extra_chars
);
2275 strbuf_add(&fixed
, img
->buf
+ try, imgoff
);
2276 strbuf_add(&fixed
, preimage_eof
, extra_chars
);
2277 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2278 update_pre_post_images(preimage
, postimage
,
2279 fixed_buf
, fixed_len
, postlen
);
2283 if (ws_error_action
!= correct_ws_error
)
2287 * The hunk does not apply byte-by-byte, but the hash says
2288 * it might with whitespace fuzz. We haven't been asked to
2289 * ignore whitespace, we were asked to correct whitespace
2290 * errors, so let's try matching after whitespace correction.
2292 * The preimage may extend beyond the end of the file,
2293 * but in this loop we will only handle the part of the
2294 * preimage that falls within the file.
2296 strbuf_init(&fixed
, preimage
->len
+ 1);
2297 orig
= preimage
->buf
;
2298 target
= img
->buf
+ try;
2299 for (i
= 0; i
< preimage_limit
; i
++) {
2300 size_t oldlen
= preimage
->line
[i
].len
;
2301 size_t tgtlen
= img
->line
[try_lno
+ i
].len
;
2302 size_t fixstart
= fixed
.len
;
2303 struct strbuf tgtfix
;
2306 /* Try fixing the line in the preimage */
2307 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2309 /* Try fixing the line in the target */
2310 strbuf_init(&tgtfix
, tgtlen
);
2311 ws_fix_copy(&tgtfix
, target
, tgtlen
, ws_rule
, NULL
);
2314 * If they match, either the preimage was based on
2315 * a version before our tree fixed whitespace breakage,
2316 * or we are lacking a whitespace-fix patch the tree
2317 * the preimage was based on already had (i.e. target
2318 * has whitespace breakage, the preimage doesn't).
2319 * In either case, we are fixing the whitespace breakages
2320 * so we might as well take the fix together with their
2323 match
= (tgtfix
.len
== fixed
.len
- fixstart
&&
2324 !memcmp(tgtfix
.buf
, fixed
.buf
+ fixstart
,
2325 fixed
.len
- fixstart
));
2327 strbuf_release(&tgtfix
);
2337 * Now handle the lines in the preimage that falls beyond the
2338 * end of the file (if any). They will only match if they are
2339 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2342 for ( ; i
< preimage
->nr
; i
++) {
2343 size_t fixstart
= fixed
.len
; /* start of the fixed preimage */
2344 size_t oldlen
= preimage
->line
[i
].len
;
2347 /* Try fixing the line in the preimage */
2348 ws_fix_copy(&fixed
, orig
, oldlen
, ws_rule
, NULL
);
2350 for (j
= fixstart
; j
< fixed
.len
; j
++)
2351 if (!isspace(fixed
.buf
[j
]))
2358 * Yes, the preimage is based on an older version that still
2359 * has whitespace breakages unfixed, and fixing them makes the
2360 * hunk match. Update the context lines in the postimage.
2362 fixed_buf
= strbuf_detach(&fixed
, &fixed_len
);
2363 update_pre_post_images(preimage
, postimage
,
2364 fixed_buf
, fixed_len
, 0);
2368 strbuf_release(&fixed
);
2372 static int find_pos(struct image
*img
,
2373 struct image
*preimage
,
2374 struct image
*postimage
,
2377 int match_beginning
, int match_end
)
2380 unsigned long backwards
, forwards
, try;
2381 int backwards_lno
, forwards_lno
, try_lno
;
2384 * If match_beginning or match_end is specified, there is no
2385 * point starting from a wrong line that will never match and
2386 * wander around and wait for a match at the specified end.
2388 if (match_beginning
)
2391 line
= img
->nr
- preimage
->nr
;
2394 * Because the comparison is unsigned, the following test
2395 * will also take care of a negative line number that can
2396 * result when match_end and preimage is larger than the target.
2398 if ((size_t) line
> img
->nr
)
2402 for (i
= 0; i
< line
; i
++)
2403 try += img
->line
[i
].len
;
2406 * There's probably some smart way to do this, but I'll leave
2407 * that to the smart and beautiful people. I'm simple and stupid.
2410 backwards_lno
= line
;
2412 forwards_lno
= line
;
2415 for (i
= 0; ; i
++) {
2416 if (match_fragment(img
, preimage
, postimage
,
2417 try, try_lno
, ws_rule
,
2418 match_beginning
, match_end
))
2422 if (backwards_lno
== 0 && forwards_lno
== img
->nr
)
2426 if (backwards_lno
== 0) {
2431 backwards
-= img
->line
[backwards_lno
].len
;
2433 try_lno
= backwards_lno
;
2435 if (forwards_lno
== img
->nr
) {
2439 forwards
+= img
->line
[forwards_lno
].len
;
2442 try_lno
= forwards_lno
;
2449 static void remove_first_line(struct image
*img
)
2451 img
->buf
+= img
->line
[0].len
;
2452 img
->len
-= img
->line
[0].len
;
2457 static void remove_last_line(struct image
*img
)
2459 img
->len
-= img
->line
[--img
->nr
].len
;
2463 * The change from "preimage" and "postimage" has been found to
2464 * apply at applied_pos (counts in line numbers) in "img".
2465 * Update "img" to remove "preimage" and replace it with "postimage".
2467 static void update_image(struct image
*img
,
2469 struct image
*preimage
,
2470 struct image
*postimage
)
2473 * remove the copy of preimage at offset in img
2474 * and replace it with postimage
2477 size_t remove_count
, insert_count
, applied_at
= 0;
2482 * If we are removing blank lines at the end of img,
2483 * the preimage may extend beyond the end.
2484 * If that is the case, we must be careful only to
2485 * remove the part of the preimage that falls within
2486 * the boundaries of img. Initialize preimage_limit
2487 * to the number of lines in the preimage that falls
2488 * within the boundaries.
2490 preimage_limit
= preimage
->nr
;
2491 if (preimage_limit
> img
->nr
- applied_pos
)
2492 preimage_limit
= img
->nr
- applied_pos
;
2494 for (i
= 0; i
< applied_pos
; i
++)
2495 applied_at
+= img
->line
[i
].len
;
2498 for (i
= 0; i
< preimage_limit
; i
++)
2499 remove_count
+= img
->line
[applied_pos
+ i
].len
;
2500 insert_count
= postimage
->len
;
2502 /* Adjust the contents */
2503 result
= xmalloc(img
->len
+ insert_count
- remove_count
+ 1);
2504 memcpy(result
, img
->buf
, applied_at
);
2505 memcpy(result
+ applied_at
, postimage
->buf
, postimage
->len
);
2506 memcpy(result
+ applied_at
+ postimage
->len
,
2507 img
->buf
+ (applied_at
+ remove_count
),
2508 img
->len
- (applied_at
+ remove_count
));
2511 img
->len
+= insert_count
- remove_count
;
2512 result
[img
->len
] = '\0';
2514 /* Adjust the line table */
2515 nr
= img
->nr
+ postimage
->nr
- preimage_limit
;
2516 if (preimage_limit
< postimage
->nr
) {
2518 * NOTE: this knows that we never call remove_first_line()
2519 * on anything other than pre/post image.
2521 img
->line
= xrealloc(img
->line
, nr
* sizeof(*img
->line
));
2522 img
->line_allocated
= img
->line
;
2524 if (preimage_limit
!= postimage
->nr
)
2525 memmove(img
->line
+ applied_pos
+ postimage
->nr
,
2526 img
->line
+ applied_pos
+ preimage_limit
,
2527 (img
->nr
- (applied_pos
+ preimage_limit
)) *
2528 sizeof(*img
->line
));
2529 memcpy(img
->line
+ applied_pos
,
2531 postimage
->nr
* sizeof(*img
->line
));
2533 for (i
= 0; i
< postimage
->nr
; i
++)
2534 img
->line
[applied_pos
+ i
].flag
|= LINE_PATCHED
;
2539 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2540 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2541 * replace the part of "img" with "postimage" text.
2543 static int apply_one_fragment(struct image
*img
, struct fragment
*frag
,
2544 int inaccurate_eof
, unsigned ws_rule
,
2547 int match_beginning
, match_end
;
2548 const char *patch
= frag
->patch
;
2549 int size
= frag
->size
;
2550 char *old
, *oldlines
;
2551 struct strbuf newlines
;
2552 int new_blank_lines_at_end
= 0;
2553 int found_new_blank_lines_at_end
= 0;
2554 int hunk_linenr
= frag
->linenr
;
2555 unsigned long leading
, trailing
;
2556 int pos
, applied_pos
;
2557 struct image preimage
;
2558 struct image postimage
;
2560 memset(&preimage
, 0, sizeof(preimage
));
2561 memset(&postimage
, 0, sizeof(postimage
));
2562 oldlines
= xmalloc(size
);
2563 strbuf_init(&newlines
, size
);
2568 int len
= linelen(patch
, size
);
2570 int added_blank_line
= 0;
2571 int is_blank_context
= 0;
2578 * "plen" is how much of the line we should use for
2579 * the actual patch data. Normally we just remove the
2580 * first character on the line, but if the line is
2581 * followed by "\ No newline", then we also remove the
2582 * last one (which is the newline, of course).
2585 if (len
< size
&& patch
[len
] == '\\')
2588 if (apply_in_reverse
) {
2591 else if (first
== '+')
2597 /* Newer GNU diff, empty context line */
2599 /* ... followed by '\No newline'; nothing */
2602 strbuf_addch(&newlines
, '\n');
2603 add_line_info(&preimage
, "\n", 1, LINE_COMMON
);
2604 add_line_info(&postimage
, "\n", 1, LINE_COMMON
);
2605 is_blank_context
= 1;
2608 if (plen
&& (ws_rule
& WS_BLANK_AT_EOF
) &&
2609 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2610 is_blank_context
= 1;
2612 memcpy(old
, patch
+ 1, plen
);
2613 add_line_info(&preimage
, old
, plen
,
2614 (first
== ' ' ? LINE_COMMON
: 0));
2618 /* Fall-through for ' ' */
2620 /* --no-add does not add new lines */
2621 if (first
== '+' && no_add
)
2624 start
= newlines
.len
;
2626 !whitespace_error
||
2627 ws_error_action
!= correct_ws_error
) {
2628 strbuf_add(&newlines
, patch
+ 1, plen
);
2631 ws_fix_copy(&newlines
, patch
+ 1, plen
, ws_rule
, &applied_after_fixing_ws
);
2633 add_line_info(&postimage
, newlines
.buf
+ start
, newlines
.len
- start
,
2634 (first
== '+' ? 0 : LINE_COMMON
));
2636 (ws_rule
& WS_BLANK_AT_EOF
) &&
2637 ws_blank_line(patch
+ 1, plen
, ws_rule
))
2638 added_blank_line
= 1;
2640 case '@': case '\\':
2641 /* Ignore it, we already handled it */
2644 if (apply_verbosely
)
2645 error(_("invalid start of line: '%c'"), first
);
2648 if (added_blank_line
) {
2649 if (!new_blank_lines_at_end
)
2650 found_new_blank_lines_at_end
= hunk_linenr
;
2651 new_blank_lines_at_end
++;
2653 else if (is_blank_context
)
2656 new_blank_lines_at_end
= 0;
2661 if (inaccurate_eof
&&
2662 old
> oldlines
&& old
[-1] == '\n' &&
2663 newlines
.len
> 0 && newlines
.buf
[newlines
.len
- 1] == '\n') {
2665 strbuf_setlen(&newlines
, newlines
.len
- 1);
2668 leading
= frag
->leading
;
2669 trailing
= frag
->trailing
;
2672 * A hunk to change lines at the beginning would begin with
2674 * but we need to be careful. -U0 that inserts before the second
2675 * line also has this pattern.
2677 * And a hunk to add to an empty file would begin with
2680 * In other words, a hunk that is (frag->oldpos <= 1) with or
2681 * without leading context must match at the beginning.
2683 match_beginning
= (!frag
->oldpos
||
2684 (frag
->oldpos
== 1 && !unidiff_zero
));
2687 * A hunk without trailing lines must match at the end.
2688 * However, we simply cannot tell if a hunk must match end
2689 * from the lack of trailing lines if the patch was generated
2690 * with unidiff without any context.
2692 match_end
= !unidiff_zero
&& !trailing
;
2694 pos
= frag
->newpos
? (frag
->newpos
- 1) : 0;
2695 preimage
.buf
= oldlines
;
2696 preimage
.len
= old
- oldlines
;
2697 postimage
.buf
= newlines
.buf
;
2698 postimage
.len
= newlines
.len
;
2699 preimage
.line
= preimage
.line_allocated
;
2700 postimage
.line
= postimage
.line_allocated
;
2704 applied_pos
= find_pos(img
, &preimage
, &postimage
, pos
,
2705 ws_rule
, match_beginning
, match_end
);
2707 if (applied_pos
>= 0)
2710 /* Am I at my context limits? */
2711 if ((leading
<= p_context
) && (trailing
<= p_context
))
2713 if (match_beginning
|| match_end
) {
2714 match_beginning
= match_end
= 0;
2719 * Reduce the number of context lines; reduce both
2720 * leading and trailing if they are equal otherwise
2721 * just reduce the larger context.
2723 if (leading
>= trailing
) {
2724 remove_first_line(&preimage
);
2725 remove_first_line(&postimage
);
2729 if (trailing
> leading
) {
2730 remove_last_line(&preimage
);
2731 remove_last_line(&postimage
);
2736 if (applied_pos
>= 0) {
2737 if (new_blank_lines_at_end
&&
2738 preimage
.nr
+ applied_pos
>= img
->nr
&&
2739 (ws_rule
& WS_BLANK_AT_EOF
) &&
2740 ws_error_action
!= nowarn_ws_error
) {
2741 record_ws_error(WS_BLANK_AT_EOF
, "+", 1,
2742 found_new_blank_lines_at_end
);
2743 if (ws_error_action
== correct_ws_error
) {
2744 while (new_blank_lines_at_end
--)
2745 remove_last_line(&postimage
);
2748 * We would want to prevent write_out_results()
2749 * from taking place in apply_patch() that follows
2750 * the callchain led us here, which is:
2751 * apply_patch->check_patch_list->check_patch->
2752 * apply_data->apply_fragments->apply_one_fragment
2754 if (ws_error_action
== die_on_ws_error
)
2758 if (apply_verbosely
&& applied_pos
!= pos
) {
2759 int offset
= applied_pos
- pos
;
2760 if (apply_in_reverse
)
2761 offset
= 0 - offset
;
2763 Q_("Hunk #%d succeeded at %d (offset %d line).",
2764 "Hunk #%d succeeded at %d (offset %d lines).",
2766 nth_fragment
, applied_pos
+ 1, offset
);
2770 * Warn if it was necessary to reduce the number
2773 if ((leading
!= frag
->leading
) ||
2774 (trailing
!= frag
->trailing
))
2775 fprintf_ln(stderr
, _("Context reduced to (%ld/%ld)"
2776 " to apply fragment at %d"),
2777 leading
, trailing
, applied_pos
+1);
2778 update_image(img
, applied_pos
, &preimage
, &postimage
);
2780 if (apply_verbosely
)
2781 error(_("while searching for:\n%.*s"),
2782 (int)(old
- oldlines
), oldlines
);
2786 strbuf_release(&newlines
);
2787 free(preimage
.line_allocated
);
2788 free(postimage
.line_allocated
);
2790 return (applied_pos
< 0);
2793 static int apply_binary_fragment(struct image
*img
, struct patch
*patch
)
2795 struct fragment
*fragment
= patch
->fragments
;
2800 return error(_("missing binary patch data for '%s'"),
2805 /* Binary patch is irreversible without the optional second hunk */
2806 if (apply_in_reverse
) {
2807 if (!fragment
->next
)
2808 return error("cannot reverse-apply a binary patch "
2809 "without the reverse hunk to '%s'",
2811 ? patch
->new_name
: patch
->old_name
);
2812 fragment
= fragment
->next
;
2814 switch (fragment
->binary_patch_method
) {
2815 case BINARY_DELTA_DEFLATED
:
2816 dst
= patch_delta(img
->buf
, img
->len
, fragment
->patch
,
2817 fragment
->size
, &len
);
2824 case BINARY_LITERAL_DEFLATED
:
2826 img
->len
= fragment
->size
;
2827 img
->buf
= xmalloc(img
->len
+1);
2828 memcpy(img
->buf
, fragment
->patch
, img
->len
);
2829 img
->buf
[img
->len
] = '\0';
2836 * Replace "img" with the result of applying the binary patch.
2837 * The binary patch data itself in patch->fragment is still kept
2838 * but the preimage prepared by the caller in "img" is freed here
2839 * or in the helper function apply_binary_fragment() this calls.
2841 static int apply_binary(struct image
*img
, struct patch
*patch
)
2843 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
2844 unsigned char sha1
[20];
2847 * For safety, we require patch index line to contain
2848 * full 40-byte textual SHA1 for old and new, at least for now.
2850 if (strlen(patch
->old_sha1_prefix
) != 40 ||
2851 strlen(patch
->new_sha1_prefix
) != 40 ||
2852 get_sha1_hex(patch
->old_sha1_prefix
, sha1
) ||
2853 get_sha1_hex(patch
->new_sha1_prefix
, sha1
))
2854 return error("cannot apply binary patch to '%s' "
2855 "without full index line", name
);
2857 if (patch
->old_name
) {
2859 * See if the old one matches what the patch
2862 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
2863 if (strcmp(sha1_to_hex(sha1
), patch
->old_sha1_prefix
))
2864 return error("the patch applies to '%s' (%s), "
2865 "which does not match the "
2866 "current contents.",
2867 name
, sha1_to_hex(sha1
));
2870 /* Otherwise, the old one must be empty. */
2872 return error("the patch applies to an empty "
2873 "'%s' but it is not empty", name
);
2876 get_sha1_hex(patch
->new_sha1_prefix
, sha1
);
2877 if (is_null_sha1(sha1
)) {
2879 return 0; /* deletion patch */
2882 if (has_sha1_file(sha1
)) {
2883 /* We already have the postimage */
2884 enum object_type type
;
2888 result
= read_sha1_file(sha1
, &type
, &size
);
2890 return error("the necessary postimage %s for "
2891 "'%s' cannot be read",
2892 patch
->new_sha1_prefix
, name
);
2898 * We have verified buf matches the preimage;
2899 * apply the patch data to it, which is stored
2900 * in the patch->fragments->{patch,size}.
2902 if (apply_binary_fragment(img
, patch
))
2903 return error(_("binary patch does not apply to '%s'"),
2906 /* verify that the result matches */
2907 hash_sha1_file(img
->buf
, img
->len
, blob_type
, sha1
);
2908 if (strcmp(sha1_to_hex(sha1
), patch
->new_sha1_prefix
))
2909 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
2910 name
, patch
->new_sha1_prefix
, sha1_to_hex(sha1
));
2916 static int apply_fragments(struct image
*img
, struct patch
*patch
)
2918 struct fragment
*frag
= patch
->fragments
;
2919 const char *name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
2920 unsigned ws_rule
= patch
->ws_rule
;
2921 unsigned inaccurate_eof
= patch
->inaccurate_eof
;
2924 if (patch
->is_binary
)
2925 return apply_binary(img
, patch
);
2929 if (apply_one_fragment(img
, frag
, inaccurate_eof
, ws_rule
, nth
)) {
2930 error(_("patch failed: %s:%ld"), name
, frag
->oldpos
);
2931 if (!apply_with_reject
)
2940 static int read_file_or_gitlink(struct cache_entry
*ce
, struct strbuf
*buf
)
2945 if (S_ISGITLINK(ce
->ce_mode
)) {
2946 strbuf_grow(buf
, 100);
2947 strbuf_addf(buf
, "Subproject commit %s\n", sha1_to_hex(ce
->sha1
));
2949 enum object_type type
;
2953 result
= read_sha1_file(ce
->sha1
, &type
, &sz
);
2956 /* XXX read_sha1_file NUL-terminates */
2957 strbuf_attach(buf
, result
, sz
, sz
+ 1);
2962 static struct patch
*in_fn_table(const char *name
)
2964 struct string_list_item
*item
;
2969 item
= string_list_lookup(&fn_table
, name
);
2971 return (struct patch
*)item
->util
;
2977 * item->util in the filename table records the status of the path.
2978 * Usually it points at a patch (whose result records the contents
2979 * of it after applying it), but it could be PATH_WAS_DELETED for a
2980 * path that a previously applied patch has already removed.
2982 #define PATH_TO_BE_DELETED ((struct patch *) -2)
2983 #define PATH_WAS_DELETED ((struct patch *) -1)
2985 static int to_be_deleted(struct patch
*patch
)
2987 return patch
== PATH_TO_BE_DELETED
;
2990 static int was_deleted(struct patch
*patch
)
2992 return patch
== PATH_WAS_DELETED
;
2995 static void add_to_fn_table(struct patch
*patch
)
2997 struct string_list_item
*item
;
3000 * Always add new_name unless patch is a deletion
3001 * This should cover the cases for normal diffs,
3002 * file creations and copies
3004 if (patch
->new_name
!= NULL
) {
3005 item
= string_list_insert(&fn_table
, patch
->new_name
);
3010 * store a failure on rename/deletion cases because
3011 * later chunks shouldn't patch old names
3013 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3014 item
= string_list_insert(&fn_table
, patch
->old_name
);
3015 item
->util
= PATH_WAS_DELETED
;
3019 static void prepare_fn_table(struct patch
*patch
)
3022 * store information about incoming file deletion
3025 if ((patch
->new_name
== NULL
) || (patch
->is_rename
)) {
3026 struct string_list_item
*item
;
3027 item
= string_list_insert(&fn_table
, patch
->old_name
);
3028 item
->util
= PATH_TO_BE_DELETED
;
3030 patch
= patch
->next
;
3034 static int apply_data(struct patch
*patch
, struct stat
*st
, struct cache_entry
*ce
)
3036 struct strbuf buf
= STRBUF_INIT
;
3040 struct patch
*tpatch
;
3042 if (!(patch
->is_copy
|| patch
->is_rename
) &&
3043 (tpatch
= in_fn_table(patch
->old_name
)) != NULL
&& !to_be_deleted(tpatch
)) {
3044 if (was_deleted(tpatch
)) {
3045 return error(_("patch %s has been renamed/deleted"),
3048 /* We have a patched copy in memory; use that. */
3049 strbuf_add(&buf
, tpatch
->result
, tpatch
->resultsize
);
3050 } else if (cached
) {
3051 if (read_file_or_gitlink(ce
, &buf
))
3052 return error(_("read of %s failed"), patch
->old_name
);
3053 } else if (patch
->old_name
) {
3054 if (S_ISGITLINK(patch
->old_mode
)) {
3056 read_file_or_gitlink(ce
, &buf
);
3059 * There is no way to apply subproject
3060 * patch without looking at the index.
3061 * NEEDSWORK: shouldn't this be flagged
3064 free_fragment_list(patch
->fragments
);
3065 patch
->fragments
= NULL
;
3068 if (read_old_data(st
, patch
->old_name
, &buf
))
3069 return error(_("read of %s failed"), patch
->old_name
);
3073 img
= strbuf_detach(&buf
, &len
);
3074 prepare_image(&image
, img
, len
, !patch
->is_binary
);
3076 if (apply_fragments(&image
, patch
) < 0)
3077 return -1; /* note with --reject this succeeds. */
3078 patch
->result
= image
.buf
;
3079 patch
->resultsize
= image
.len
;
3080 add_to_fn_table(patch
);
3081 free(image
.line_allocated
);
3083 if (0 < patch
->is_delete
&& patch
->resultsize
)
3084 return error(_("removal patch leaves file contents"));
3089 static int check_to_create_blob(const char *new_name
, int ok_if_exists
)
3092 if (!lstat(new_name
, &nst
)) {
3093 if (S_ISDIR(nst
.st_mode
) || ok_if_exists
)
3096 * A leading component of new_name might be a symlink
3097 * that is going to be removed with this patch, but
3098 * still pointing at somewhere that has the path.
3099 * In such a case, path "new_name" does not exist as
3100 * far as git is concerned.
3102 if (has_symlink_leading_path(new_name
, strlen(new_name
)))
3105 return error(_("%s: already exists in working directory"), new_name
);
3107 else if ((errno
!= ENOENT
) && (errno
!= ENOTDIR
))
3108 return error("%s: %s", new_name
, strerror(errno
));
3112 static int verify_index_match(struct cache_entry
*ce
, struct stat
*st
)
3114 if (S_ISGITLINK(ce
->ce_mode
)) {
3115 if (!S_ISDIR(st
->st_mode
))
3119 return ce_match_stat(ce
, st
, CE_MATCH_IGNORE_VALID
|CE_MATCH_IGNORE_SKIP_WORKTREE
);
3122 static int check_preimage(struct patch
*patch
, struct cache_entry
**ce
, struct stat
*st
)
3124 const char *old_name
= patch
->old_name
;
3125 struct patch
*tpatch
= NULL
;
3127 unsigned st_mode
= 0;
3130 * Make sure that we do not have local modifications from the
3131 * index when we are looking at the index. Also make sure
3132 * we have the preimage file to be patched in the work tree,
3133 * unless --cached, which tells git to apply only in the index.
3138 assert(patch
->is_new
<= 0);
3140 if (!(patch
->is_copy
|| patch
->is_rename
) &&
3141 (tpatch
= in_fn_table(old_name
)) != NULL
&& !to_be_deleted(tpatch
)) {
3142 if (was_deleted(tpatch
))
3143 return error(_("%s: has been deleted/renamed"), old_name
);
3144 st_mode
= tpatch
->new_mode
;
3145 } else if (!cached
) {
3146 stat_ret
= lstat(old_name
, st
);
3147 if (stat_ret
&& errno
!= ENOENT
)
3148 return error(_("%s: %s"), old_name
, strerror(errno
));
3151 if (to_be_deleted(tpatch
))
3154 if (check_index
&& !tpatch
) {
3155 int pos
= cache_name_pos(old_name
, strlen(old_name
));
3157 if (patch
->is_new
< 0)
3159 return error(_("%s: does not exist in index"), old_name
);
3161 *ce
= active_cache
[pos
];
3163 struct checkout costate
;
3165 memset(&costate
, 0, sizeof(costate
));
3166 costate
.base_dir
= "";
3167 costate
.refresh_cache
= 1;
3168 if (checkout_entry(*ce
, &costate
, NULL
) ||
3169 lstat(old_name
, st
))
3172 if (!cached
&& verify_index_match(*ce
, st
))
3173 return error(_("%s: does not match index"), old_name
);
3175 st_mode
= (*ce
)->ce_mode
;
3176 } else if (stat_ret
< 0) {
3177 if (patch
->is_new
< 0)
3179 return error(_("%s: %s"), old_name
, strerror(errno
));
3182 if (!cached
&& !tpatch
)
3183 st_mode
= ce_mode_from_stat(*ce
, st
->st_mode
);
3185 if (patch
->is_new
< 0)
3187 if (!patch
->old_mode
)
3188 patch
->old_mode
= st_mode
;
3189 if ((st_mode
^ patch
->old_mode
) & S_IFMT
)
3190 return error(_("%s: wrong type"), old_name
);
3191 if (st_mode
!= patch
->old_mode
)
3192 warning(_("%s has type %o, expected %o"),
3193 old_name
, st_mode
, patch
->old_mode
);
3194 if (!patch
->new_mode
&& !patch
->is_delete
)
3195 patch
->new_mode
= st_mode
;
3200 patch
->is_delete
= 0;
3201 free(patch
->old_name
);
3202 patch
->old_name
= NULL
;
3207 * Check and apply the patch in-core; leave the result in patch->result
3208 * for the caller to write it out to the final destination.
3210 static int check_patch(struct patch
*patch
)
3213 const char *old_name
= patch
->old_name
;
3214 const char *new_name
= patch
->new_name
;
3215 const char *name
= old_name
? old_name
: new_name
;
3216 struct cache_entry
*ce
= NULL
;
3217 struct patch
*tpatch
;
3221 patch
->rejected
= 1; /* we will drop this after we succeed */
3223 status
= check_preimage(patch
, &ce
, &st
);
3226 old_name
= patch
->old_name
;
3228 if ((tpatch
= in_fn_table(new_name
)) &&
3229 (was_deleted(tpatch
) || to_be_deleted(tpatch
)))
3231 * A type-change diff is always split into a patch to
3232 * delete old, immediately followed by a patch to
3233 * create new (see diff.c::run_diff()); in such a case
3234 * it is Ok that the entry to be deleted by the
3235 * previous patch is still in the working tree and in
3243 ((0 < patch
->is_new
) | (0 < patch
->is_rename
) | patch
->is_copy
)) {
3245 cache_name_pos(new_name
, strlen(new_name
)) >= 0 &&
3247 return error(_("%s: already exists in index"), new_name
);
3249 int err
= check_to_create_blob(new_name
, ok_if_exists
);
3253 if (!patch
->new_mode
) {
3254 if (0 < patch
->is_new
)
3255 patch
->new_mode
= S_IFREG
| 0644;
3257 patch
->new_mode
= patch
->old_mode
;
3261 if (new_name
&& old_name
) {
3262 int same
= !strcmp(old_name
, new_name
);
3263 if (!patch
->new_mode
)
3264 patch
->new_mode
= patch
->old_mode
;
3265 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
) {
3267 return error(_("new mode (%o) of %s does not "
3268 "match old mode (%o)"),
3269 patch
->new_mode
, new_name
,
3272 return error(_("new mode (%o) of %s does not "
3273 "match old mode (%o) of %s"),
3274 patch
->new_mode
, new_name
,
3275 patch
->old_mode
, old_name
);
3279 if (apply_data(patch
, &st
, ce
) < 0)
3280 return error(_("%s: patch does not apply"), name
);
3281 patch
->rejected
= 0;
3285 static int check_patch_list(struct patch
*patch
)
3289 prepare_fn_table(patch
);
3291 if (apply_verbosely
)
3292 say_patch_name(stderr
,
3293 _("Checking patch %s..."), patch
);
3294 err
|= check_patch(patch
);
3295 patch
= patch
->next
;
3300 /* This function tries to read the sha1 from the current index */
3301 static int get_current_sha1(const char *path
, unsigned char *sha1
)
3305 if (read_cache() < 0)
3307 pos
= cache_name_pos(path
, strlen(path
));
3310 hashcpy(sha1
, active_cache
[pos
]->sha1
);
3314 /* Build an index that contains the just the files needed for a 3way merge */
3315 static void build_fake_ancestor(struct patch
*list
, const char *filename
)
3317 struct patch
*patch
;
3318 struct index_state result
= { NULL
};
3321 /* Once we start supporting the reverse patch, it may be
3322 * worth showing the new sha1 prefix, but until then...
3324 for (patch
= list
; patch
; patch
= patch
->next
) {
3325 const unsigned char *sha1_ptr
;
3326 unsigned char sha1
[20];
3327 struct cache_entry
*ce
;
3330 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
3331 if (0 < patch
->is_new
)
3333 else if (get_sha1(patch
->old_sha1_prefix
, sha1
))
3334 /* git diff has no index line for mode/type changes */
3335 if (!patch
->lines_added
&& !patch
->lines_deleted
) {
3336 if (get_current_sha1(patch
->old_name
, sha1
))
3337 die("mode change for %s, which is not "
3338 "in current HEAD", name
);
3341 die("sha1 information is lacking or useless "
3346 ce
= make_cache_entry(patch
->old_mode
, sha1_ptr
, name
, 0, 0);
3348 die(_("make_cache_entry failed for path '%s'"), name
);
3349 if (add_index_entry(&result
, ce
, ADD_CACHE_OK_TO_ADD
))
3350 die ("Could not add %s to temporary index", name
);
3353 fd
= open(filename
, O_WRONLY
| O_CREAT
, 0666);
3354 if (fd
< 0 || write_index(&result
, fd
) || close(fd
))
3355 die ("Could not write temporary index to %s", filename
);
3357 discard_index(&result
);
3360 static void stat_patch_list(struct patch
*patch
)
3362 int files
, adds
, dels
;
3364 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
3366 adds
+= patch
->lines_added
;
3367 dels
+= patch
->lines_deleted
;
3371 print_stat_summary(stdout
, files
, adds
, dels
);
3374 static void numstat_patch_list(struct patch
*patch
)
3376 for ( ; patch
; patch
= patch
->next
) {
3378 name
= patch
->new_name
? patch
->new_name
: patch
->old_name
;
3379 if (patch
->is_binary
)
3382 printf("%d\t%d\t", patch
->lines_added
, patch
->lines_deleted
);
3383 write_name_quoted(name
, stdout
, line_termination
);
3387 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
3390 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
3392 printf(" %s %s\n", newdelete
, name
);
3395 static void show_mode_change(struct patch
*p
, int show_name
)
3397 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
3399 printf(" mode change %06o => %06o %s\n",
3400 p
->old_mode
, p
->new_mode
, p
->new_name
);
3402 printf(" mode change %06o => %06o\n",
3403 p
->old_mode
, p
->new_mode
);
3407 static void show_rename_copy(struct patch
*p
)
3409 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
3410 const char *old
, *new;
3412 /* Find common prefix */
3416 const char *slash_old
, *slash_new
;
3417 slash_old
= strchr(old
, '/');
3418 slash_new
= strchr(new, '/');
3421 slash_old
- old
!= slash_new
- new ||
3422 memcmp(old
, new, slash_new
- new))
3424 old
= slash_old
+ 1;
3425 new = slash_new
+ 1;
3427 /* p->old_name thru old is the common prefix, and old and new
3428 * through the end of names are renames
3430 if (old
!= p
->old_name
)
3431 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
3432 (int)(old
- p
->old_name
), p
->old_name
,
3433 old
, new, p
->score
);
3435 printf(" %s %s => %s (%d%%)\n", renamecopy
,
3436 p
->old_name
, p
->new_name
, p
->score
);
3437 show_mode_change(p
, 0);
3440 static void summary_patch_list(struct patch
*patch
)
3444 for (p
= patch
; p
; p
= p
->next
) {
3446 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
3447 else if (p
->is_delete
)
3448 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
3450 if (p
->is_rename
|| p
->is_copy
)
3451 show_rename_copy(p
);
3454 printf(" rewrite %s (%d%%)\n",
3455 p
->new_name
, p
->score
);
3456 show_mode_change(p
, 0);
3459 show_mode_change(p
, 1);
3465 static void patch_stats(struct patch
*patch
)
3467 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
3469 if (lines
> max_change
)
3471 if (patch
->old_name
) {
3472 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
3474 len
= strlen(patch
->old_name
);
3478 if (patch
->new_name
) {
3479 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
3481 len
= strlen(patch
->new_name
);
3487 static void remove_file(struct patch
*patch
, int rmdir_empty
)
3490 if (remove_file_from_cache(patch
->old_name
) < 0)
3491 die(_("unable to remove %s from index"), patch
->old_name
);
3494 if (!remove_or_warn(patch
->old_mode
, patch
->old_name
) && rmdir_empty
) {
3495 remove_path(patch
->old_name
);
3500 static void add_index_file(const char *path
, unsigned mode
, void *buf
, unsigned long size
)
3503 struct cache_entry
*ce
;
3504 int namelen
= strlen(path
);
3505 unsigned ce_size
= cache_entry_size(namelen
);
3510 ce
= xcalloc(1, ce_size
);
3511 memcpy(ce
->name
, path
, namelen
);
3512 ce
->ce_mode
= create_ce_mode(mode
);
3513 ce
->ce_flags
= namelen
;
3514 if (S_ISGITLINK(mode
)) {
3515 const char *s
= buf
;
3517 if (get_sha1_hex(s
+ strlen("Subproject commit "), ce
->sha1
))
3518 die(_("corrupt patch for subproject %s"), path
);
3521 if (lstat(path
, &st
) < 0)
3522 die_errno(_("unable to stat newly created file '%s'"),
3524 fill_stat_cache_info(ce
, &st
);
3526 if (write_sha1_file(buf
, size
, blob_type
, ce
->sha1
) < 0)
3527 die(_("unable to create backing store for newly created file %s"), path
);
3529 if (add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
) < 0)
3530 die(_("unable to add cache entry for %s"), path
);
3533 static int try_create_file(const char *path
, unsigned int mode
, const char *buf
, unsigned long size
)
3536 struct strbuf nbuf
= STRBUF_INIT
;
3538 if (S_ISGITLINK(mode
)) {
3540 if (!lstat(path
, &st
) && S_ISDIR(st
.st_mode
))
3542 return mkdir(path
, 0777);
3545 if (has_symlinks
&& S_ISLNK(mode
))
3546 /* Although buf:size is counted string, it also is NUL
3549 return symlink(buf
, path
);
3551 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
, (mode
& 0100) ? 0777 : 0666);
3555 if (convert_to_working_tree(path
, buf
, size
, &nbuf
)) {
3559 write_or_die(fd
, buf
, size
);
3560 strbuf_release(&nbuf
);
3563 die_errno(_("closing file '%s'"), path
);
3568 * We optimistically assume that the directories exist,
3569 * which is true 99% of the time anyway. If they don't,
3570 * we create them and try again.
3572 static void create_one_file(char *path
, unsigned mode
, const char *buf
, unsigned long size
)
3576 if (!try_create_file(path
, mode
, buf
, size
))
3579 if (errno
== ENOENT
) {
3580 if (safe_create_leading_directories(path
))
3582 if (!try_create_file(path
, mode
, buf
, size
))
3586 if (errno
== EEXIST
|| errno
== EACCES
) {
3587 /* We may be trying to create a file where a directory
3591 if (!lstat(path
, &st
) && (!S_ISDIR(st
.st_mode
) || !rmdir(path
)))
3595 if (errno
== EEXIST
) {
3596 unsigned int nr
= getpid();
3599 char newpath
[PATH_MAX
];
3600 mksnpath(newpath
, sizeof(newpath
), "%s~%u", path
, nr
);
3601 if (!try_create_file(newpath
, mode
, buf
, size
)) {
3602 if (!rename(newpath
, path
))
3604 unlink_or_warn(newpath
);
3607 if (errno
!= EEXIST
)
3612 die_errno(_("unable to write file '%s' mode %o"), path
, mode
);
3615 static void create_file(struct patch
*patch
)
3617 char *path
= patch
->new_name
;
3618 unsigned mode
= patch
->new_mode
;
3619 unsigned long size
= patch
->resultsize
;
3620 char *buf
= patch
->result
;
3623 mode
= S_IFREG
| 0644;
3624 create_one_file(path
, mode
, buf
, size
);
3625 add_index_file(path
, mode
, buf
, size
);
3628 /* phase zero is to remove, phase one is to create */
3629 static void write_out_one_result(struct patch
*patch
, int phase
)
3631 if (patch
->is_delete
> 0) {
3633 remove_file(patch
, 1);
3636 if (patch
->is_new
> 0 || patch
->is_copy
) {
3642 * Rename or modification boils down to the same
3643 * thing: remove the old, write the new
3646 remove_file(patch
, patch
->is_rename
);
3651 static int write_out_one_reject(struct patch
*patch
)
3654 char namebuf
[PATH_MAX
];
3655 struct fragment
*frag
;
3657 struct strbuf sb
= STRBUF_INIT
;
3659 for (cnt
= 0, frag
= patch
->fragments
; frag
; frag
= frag
->next
) {
3660 if (!frag
->rejected
)
3666 if (apply_verbosely
)
3667 say_patch_name(stderr
,
3668 _("Applied patch %s cleanly."), patch
);
3672 /* This should not happen, because a removal patch that leaves
3673 * contents are marked "rejected" at the patch level.
3675 if (!patch
->new_name
)
3676 die(_("internal error"));
3678 /* Say this even without --verbose */
3679 strbuf_addf(&sb
, Q_("Applying patch %%s with %d reject...",
3680 "Applying patch %%s with %d rejects...",
3683 say_patch_name(stderr
, sb
.buf
, patch
);
3684 strbuf_release(&sb
);
3686 cnt
= strlen(patch
->new_name
);
3687 if (ARRAY_SIZE(namebuf
) <= cnt
+ 5) {
3688 cnt
= ARRAY_SIZE(namebuf
) - 5;
3689 warning(_("truncating .rej filename to %.*s.rej"),
3690 cnt
- 1, patch
->new_name
);
3692 memcpy(namebuf
, patch
->new_name
, cnt
);
3693 memcpy(namebuf
+ cnt
, ".rej", 5);
3695 rej
= fopen(namebuf
, "w");
3697 return error(_("cannot open %s: %s"), namebuf
, strerror(errno
));
3699 /* Normal git tools never deal with .rej, so do not pretend
3700 * this is a git patch by saying --git nor give extended
3701 * headers. While at it, maybe please "kompare" that wants
3702 * the trailing TAB and some garbage at the end of line ;-).
3704 fprintf(rej
, "diff a/%s b/%s\t(rejected hunks)\n",
3705 patch
->new_name
, patch
->new_name
);
3706 for (cnt
= 1, frag
= patch
->fragments
;
3708 cnt
++, frag
= frag
->next
) {
3709 if (!frag
->rejected
) {
3710 fprintf_ln(stderr
, _("Hunk #%d applied cleanly."), cnt
);
3713 fprintf_ln(stderr
, _("Rejected hunk #%d."), cnt
);
3714 fprintf(rej
, "%.*s", frag
->size
, frag
->patch
);
3715 if (frag
->patch
[frag
->size
-1] != '\n')
3722 static int write_out_results(struct patch
*list
)
3728 for (phase
= 0; phase
< 2; phase
++) {
3734 write_out_one_result(l
, phase
);
3735 if (phase
== 1 && write_out_one_reject(l
))
3744 static struct lock_file lock_file
;
3746 static struct string_list limit_by_name
;
3747 static int has_include
;
3748 static void add_name_limit(const char *name
, int exclude
)
3750 struct string_list_item
*it
;
3752 it
= string_list_append(&limit_by_name
, name
);
3753 it
->util
= exclude
? NULL
: (void *) 1;
3756 static int use_patch(struct patch
*p
)
3758 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
3761 /* Paths outside are not touched regardless of "--include" */
3762 if (0 < prefix_length
) {
3763 int pathlen
= strlen(pathname
);
3764 if (pathlen
<= prefix_length
||
3765 memcmp(prefix
, pathname
, prefix_length
))
3769 /* See if it matches any of exclude/include rule */
3770 for (i
= 0; i
< limit_by_name
.nr
; i
++) {
3771 struct string_list_item
*it
= &limit_by_name
.items
[i
];
3772 if (!fnmatch(it
->string
, pathname
, 0))
3773 return (it
->util
!= NULL
);
3777 * If we had any include, a path that does not match any rule is
3778 * not used. Otherwise, we saw bunch of exclude rules (or none)
3779 * and such a path is used.
3781 return !has_include
;
3785 static void prefix_one(char **name
)
3787 char *old_name
= *name
;
3790 *name
= xstrdup(prefix_filename(prefix
, prefix_length
, *name
));
3794 static void prefix_patches(struct patch
*p
)
3796 if (!prefix
|| p
->is_toplevel_relative
)
3798 for ( ; p
; p
= p
->next
) {
3799 prefix_one(&p
->new_name
);
3800 prefix_one(&p
->old_name
);
3804 #define INACCURATE_EOF (1<<0)
3805 #define RECOUNT (1<<1)
3807 static int apply_patch(int fd
, const char *filename
, int options
)
3810 struct strbuf buf
= STRBUF_INIT
; /* owns the patch text */
3811 struct patch
*list
= NULL
, **listp
= &list
;
3812 int skipped_patch
= 0;
3814 patch_input_file
= filename
;
3815 read_patch_file(&buf
, fd
);
3817 while (offset
< buf
.len
) {
3818 struct patch
*patch
;
3821 patch
= xcalloc(1, sizeof(*patch
));
3822 patch
->inaccurate_eof
= !!(options
& INACCURATE_EOF
);
3823 patch
->recount
= !!(options
& RECOUNT
);
3824 nr
= parse_chunk(buf
.buf
+ offset
, buf
.len
- offset
, patch
);
3827 if (apply_in_reverse
)
3828 reverse_patches(patch
);
3830 prefix_patches(patch
);
3831 if (use_patch(patch
)) {
3834 listp
= &patch
->next
;
3843 if (!list
&& !skipped_patch
)
3844 die(_("unrecognized input"));
3846 if (whitespace_error
&& (ws_error_action
== die_on_ws_error
))
3849 update_index
= check_index
&& apply
;
3850 if (update_index
&& newfd
< 0)
3851 newfd
= hold_locked_index(&lock_file
, 1);
3854 if (read_cache() < 0)
3855 die(_("unable to read index file"));
3858 if ((check
|| apply
) &&
3859 check_patch_list(list
) < 0 &&
3863 if (apply
&& write_out_results(list
))
3867 build_fake_ancestor(list
, fake_ancestor
);
3870 stat_patch_list(list
);
3873 numstat_patch_list(list
);
3876 summary_patch_list(list
);
3878 free_patch_list(list
);
3879 strbuf_release(&buf
);
3880 string_list_clear(&fn_table
, 0);
3884 static int git_apply_config(const char *var
, const char *value
, void *cb
)
3886 if (!strcmp(var
, "apply.whitespace"))
3887 return git_config_string(&apply_default_whitespace
, var
, value
);
3888 else if (!strcmp(var
, "apply.ignorewhitespace"))
3889 return git_config_string(&apply_default_ignorewhitespace
, var
, value
);
3890 return git_default_config(var
, value
, cb
);
3893 static int option_parse_exclude(const struct option
*opt
,
3894 const char *arg
, int unset
)
3896 add_name_limit(arg
, 1);
3900 static int option_parse_include(const struct option
*opt
,
3901 const char *arg
, int unset
)
3903 add_name_limit(arg
, 0);
3908 static int option_parse_p(const struct option
*opt
,
3909 const char *arg
, int unset
)
3911 p_value
= atoi(arg
);
3916 static int option_parse_z(const struct option
*opt
,
3917 const char *arg
, int unset
)
3920 line_termination
= '\n';
3922 line_termination
= 0;
3926 static int option_parse_space_change(const struct option
*opt
,
3927 const char *arg
, int unset
)
3930 ws_ignore_action
= ignore_ws_none
;
3932 ws_ignore_action
= ignore_ws_change
;
3936 static int option_parse_whitespace(const struct option
*opt
,
3937 const char *arg
, int unset
)
3939 const char **whitespace_option
= opt
->value
;
3941 *whitespace_option
= arg
;
3942 parse_whitespace_option(arg
);
3946 static int option_parse_directory(const struct option
*opt
,
3947 const char *arg
, int unset
)
3949 root_len
= strlen(arg
);
3950 if (root_len
&& arg
[root_len
- 1] != '/') {
3952 root
= new_root
= xmalloc(root_len
+ 2);
3953 strcpy(new_root
, arg
);
3954 strcpy(new_root
+ root_len
++, "/");
3960 int cmd_apply(int argc
, const char **argv
, const char *prefix_
)
3964 int is_not_gitdir
= !startup_info
->have_repository
;
3965 int force_apply
= 0;
3967 const char *whitespace_option
= NULL
;
3969 struct option builtin_apply_options
[] = {
3970 { OPTION_CALLBACK
, 0, "exclude", NULL
, N_("path"),
3971 N_("don't apply changes matching the given path"),
3972 0, option_parse_exclude
},
3973 { OPTION_CALLBACK
, 0, "include", NULL
, N_("path"),
3974 N_("apply changes matching the given path"),
3975 0, option_parse_include
},
3976 { OPTION_CALLBACK
, 'p', NULL
, NULL
, N_("num"),
3977 N_("remove <num> leading slashes from traditional diff paths"),
3978 0, option_parse_p
},
3979 OPT_BOOLEAN(0, "no-add", &no_add
,
3980 N_("ignore additions made by the patch")),
3981 OPT_BOOLEAN(0, "stat", &diffstat
,
3982 N_("instead of applying the patch, output diffstat for the input")),
3983 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
3984 OPT_NOOP_NOARG(0, "binary"),
3985 OPT_BOOLEAN(0, "numstat", &numstat
,
3986 N_("shows number of added and deleted lines in decimal notation")),
3987 OPT_BOOLEAN(0, "summary", &summary
,
3988 N_("instead of applying the patch, output a summary for the input")),
3989 OPT_BOOLEAN(0, "check", &check
,
3990 N_("instead of applying the patch, see if the patch is applicable")),
3991 OPT_BOOLEAN(0, "index", &check_index
,
3992 N_("make sure the patch is applicable to the current index")),
3993 OPT_BOOLEAN(0, "cached", &cached
,
3994 N_("apply a patch without touching the working tree")),
3995 OPT_BOOLEAN(0, "apply", &force_apply
,
3996 N_("also apply the patch (use with --stat/--summary/--check)")),
3997 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor
,
3998 N_("build a temporary index based on embedded index information")),
3999 { OPTION_CALLBACK
, 'z', NULL
, NULL
, NULL
,
4000 N_("paths are separated with NUL character"),
4001 PARSE_OPT_NOARG
, option_parse_z
},
4002 OPT_INTEGER('C', NULL
, &p_context
,
4003 N_("ensure at least <n> lines of context match")),
4004 { OPTION_CALLBACK
, 0, "whitespace", &whitespace_option
, N_("action"),
4005 N_("detect new or modified lines that have whitespace errors"),
4006 0, option_parse_whitespace
},
4007 { OPTION_CALLBACK
, 0, "ignore-space-change", NULL
, NULL
,
4008 N_("ignore changes in whitespace when finding context"),
4009 PARSE_OPT_NOARG
, option_parse_space_change
},
4010 { OPTION_CALLBACK
, 0, "ignore-whitespace", NULL
, NULL
,
4011 N_("ignore changes in whitespace when finding context"),
4012 PARSE_OPT_NOARG
, option_parse_space_change
},
4013 OPT_BOOLEAN('R', "reverse", &apply_in_reverse
,
4014 N_("apply the patch in reverse")),
4015 OPT_BOOLEAN(0, "unidiff-zero", &unidiff_zero
,
4016 N_("don't expect at least one line of context")),
4017 OPT_BOOLEAN(0, "reject", &apply_with_reject
,
4018 N_("leave the rejected hunks in corresponding *.rej files")),
4019 OPT_BOOLEAN(0, "allow-overlap", &allow_overlap
,
4020 N_("allow overlapping hunks")),
4021 OPT__VERBOSE(&apply_verbosely
, N_("be verbose")),
4022 OPT_BIT(0, "inaccurate-eof", &options
,
4023 N_("tolerate incorrectly detected missing new-line at the end of file"),
4025 OPT_BIT(0, "recount", &options
,
4026 N_("do not trust the line counts in the hunk headers"),
4028 { OPTION_CALLBACK
, 0, "directory", NULL
, N_("root"),
4029 N_("prepend <root> to all filenames"),
4030 0, option_parse_directory
},
4035 prefix_length
= prefix
? strlen(prefix
) : 0;
4036 git_config(git_apply_config
, NULL
);
4037 if (apply_default_whitespace
)
4038 parse_whitespace_option(apply_default_whitespace
);
4039 if (apply_default_ignorewhitespace
)
4040 parse_ignorewhitespace_option(apply_default_ignorewhitespace
);
4042 argc
= parse_options(argc
, argv
, prefix
, builtin_apply_options
,
4045 if (apply_with_reject
)
4046 apply
= apply_verbosely
= 1;
4047 if (!force_apply
&& (diffstat
|| numstat
|| summary
|| check
|| fake_ancestor
))
4049 if (check_index
&& is_not_gitdir
)
4050 die(_("--index outside a repository"));
4053 die(_("--cached outside a repository"));
4056 for (i
= 0; i
< argc
; i
++) {
4057 const char *arg
= argv
[i
];
4060 if (!strcmp(arg
, "-")) {
4061 errs
|= apply_patch(0, "<stdin>", options
);
4064 } else if (0 < prefix_length
)
4065 arg
= prefix_filename(prefix
, prefix_length
, arg
);
4067 fd
= open(arg
, O_RDONLY
);
4069 die_errno(_("can't open patch '%s'"), arg
);
4071 set_default_whitespace_mode(whitespace_option
);
4072 errs
|= apply_patch(fd
, arg
, options
);
4075 set_default_whitespace_mode(whitespace_option
);
4077 errs
|= apply_patch(0, "<stdin>", options
);
4078 if (whitespace_error
) {
4079 if (squelch_whitespace_errors
&&
4080 squelch_whitespace_errors
< whitespace_error
) {
4082 whitespace_error
- squelch_whitespace_errors
;
4083 warning(Q_("squelched %d whitespace error",
4084 "squelched %d whitespace errors",
4088 if (ws_error_action
== die_on_ws_error
)
4089 die(Q_("%d line adds whitespace errors.",
4090 "%d lines add whitespace errors.",
4093 if (applied_after_fixing_ws
&& apply
)
4094 warning("%d line%s applied after"
4095 " fixing whitespace errors.",
4096 applied_after_fixing_ws
,
4097 applied_after_fixing_ws
== 1 ? "" : "s");
4098 else if (whitespace_error
)
4099 warning(Q_("%d line adds whitespace errors.",
4100 "%d lines add whitespace errors.",
4106 if (write_cache(newfd
, active_cache
, active_nr
) ||
4107 commit_locked_index(&lock_file
))
4108 die(_("Unable to write new index file"));