4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
13 // --check turns on checking that the working tree matches the
14 // files that are being modified, but doesn't apply the patch
15 // --stat does just a diffstat, and doesn't actually apply
16 // --index-info shows the old and new index info for paths if available.
18 static int check_index
= 0;
19 static int write_index
= 0;
20 static int diffstat
= 0;
21 static int summary
= 0;
24 static int show_index_info
= 0;
25 static int line_termination
= '\n';
26 static const char apply_usage
[] =
27 "git-apply [--stat] [--summary] [--check] [--index] [--apply] [--index-info] [-z] <patch>...";
30 * For "diff-stat" like behaviour, we keep track of the biggest change
31 * we've seen, and the longest filename. That allows us to do simple
34 static int max_change
, max_len
;
37 * Various "current state", notably line numbers and what
38 * file (and how) we're patching right now.. The "is_xxxx"
39 * things are flags, where -1 means "don't know yet".
41 static int linenr
= 1;
44 unsigned long oldpos
, oldlines
;
45 unsigned long newpos
, newlines
;
48 struct fragment
*next
;
52 char *new_name
, *old_name
, *def_name
;
53 unsigned int old_mode
, new_mode
;
54 int is_rename
, is_copy
, is_new
, is_delete
;
55 int lines_added
, lines_deleted
;
57 struct fragment
*fragments
;
59 unsigned long resultsize
;
60 char old_sha1_prefix
[41];
61 char new_sha1_prefix
[41];
65 #define CHUNKSIZE (8192)
68 static void *read_patch_file(int fd
, unsigned long *sizep
)
70 unsigned long size
= 0, alloc
= CHUNKSIZE
;
71 void *buffer
= xmalloc(alloc
);
74 int nr
= alloc
- size
;
77 buffer
= xrealloc(buffer
, alloc
);
80 nr
= read(fd
, buffer
+ size
, nr
);
86 die("git-apply: read returned %s", strerror(errno
));
93 * Make sure that we have some slop in the buffer
94 * so that we can do speculative "memcmp" etc, and
95 * see to it that it is NUL-filled.
97 if (alloc
< size
+ SLOP
)
98 buffer
= xrealloc(buffer
, size
+ SLOP
);
99 memset(buffer
+ size
, 0, SLOP
);
103 static unsigned long linelen(const char *buffer
, unsigned long size
)
105 unsigned long len
= 0;
108 if (*buffer
++ == '\n')
114 static int is_dev_null(const char *str
)
116 return !memcmp("/dev/null", str
, 9) && isspace(str
[9]);
122 static int name_terminate(const char *name
, int namelen
, int c
, int terminate
)
124 if (c
== ' ' && !(terminate
& TERM_SPACE
))
126 if (c
== '\t' && !(terminate
& TERM_TAB
))
132 static char * find_name(const char *line
, char *def
, int p_value
, int terminate
)
135 const char *start
= line
;
139 /* Proposed "new-style" GNU patch/diff format; see
140 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
142 name
= unquote_c_style(line
, NULL
);
146 cp
= strchr(name
, '/');
153 /* name can later be freed, so we need
154 * to memmove, not just return cp
156 memmove(name
, cp
, strlen(cp
) + 1);
173 if (name_terminate(start
, line
-start
, c
, terminate
))
177 if (c
== '/' && !--p_value
)
187 * Generally we prefer the shorter name, especially
188 * if the other one is just a variation of that with
189 * something else tacked on to the end (ie "file.orig"
193 int deflen
= strlen(def
);
194 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
198 name
= xmalloc(len
+ 1);
199 memcpy(name
, start
, len
);
206 * Get the name etc info from the --/+++ lines of a traditional patch header
208 * NOTE! This hardcodes "-p1" behaviour in filename detection.
210 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
211 * files, we can happily check the index for a match, but for creating a
212 * new file we should try to match whatever "patch" does. I have no idea.
214 static void parse_traditional_patch(const char *first
, const char *second
, struct patch
*patch
)
219 first
+= 4; // skip "--- "
220 second
+= 4; // skip "+++ "
221 if (is_dev_null(first
)) {
223 patch
->is_delete
= 0;
224 name
= find_name(second
, NULL
, p_value
, TERM_SPACE
| TERM_TAB
);
225 patch
->new_name
= name
;
226 } else if (is_dev_null(second
)) {
228 patch
->is_delete
= 1;
229 name
= find_name(first
, NULL
, p_value
, TERM_SPACE
| TERM_TAB
);
230 patch
->old_name
= name
;
232 name
= find_name(first
, NULL
, p_value
, TERM_SPACE
| TERM_TAB
);
233 name
= find_name(second
, name
, p_value
, TERM_SPACE
| TERM_TAB
);
234 patch
->old_name
= patch
->new_name
= name
;
237 die("unable to find filename in patch at line %d", linenr
);
240 static int gitdiff_hdrend(const char *line
, struct patch
*patch
)
246 * We're anal about diff header consistency, to make
247 * sure that we don't end up having strange ambiguous
248 * patches floating around.
250 * As a result, gitdiff_{old|new}name() will check
251 * their names against any previous information, just
254 static char *gitdiff_verify_name(const char *line
, int isnull
, char *orig_name
, const char *oldnew
)
256 if (!orig_name
&& !isnull
)
257 return find_name(line
, NULL
, 1, 0);
266 die("git-apply: bad git-diff - expected /dev/null, got %s on line %d", name
, linenr
);
267 another
= find_name(line
, NULL
, 1, 0);
268 if (!another
|| memcmp(another
, name
, len
))
269 die("git-apply: bad git-diff - inconsistent %s filename on line %d", oldnew
, linenr
);
274 /* expect "/dev/null" */
275 if (memcmp("/dev/null", line
, 9) || line
[9] != '\n')
276 die("git-apply: bad git-diff - expected /dev/null on line %d", linenr
);
281 static int gitdiff_oldname(const char *line
, struct patch
*patch
)
283 patch
->old_name
= gitdiff_verify_name(line
, patch
->is_new
, patch
->old_name
, "old");
287 static int gitdiff_newname(const char *line
, struct patch
*patch
)
289 patch
->new_name
= gitdiff_verify_name(line
, patch
->is_delete
, patch
->new_name
, "new");
293 static int gitdiff_oldmode(const char *line
, struct patch
*patch
)
295 patch
->old_mode
= strtoul(line
, NULL
, 8);
299 static int gitdiff_newmode(const char *line
, struct patch
*patch
)
301 patch
->new_mode
= strtoul(line
, NULL
, 8);
305 static int gitdiff_delete(const char *line
, struct patch
*patch
)
307 patch
->is_delete
= 1;
308 patch
->old_name
= patch
->def_name
;
309 return gitdiff_oldmode(line
, patch
);
312 static int gitdiff_newfile(const char *line
, struct patch
*patch
)
315 patch
->new_name
= patch
->def_name
;
316 return gitdiff_newmode(line
, patch
);
319 static int gitdiff_copysrc(const char *line
, struct patch
*patch
)
322 patch
->old_name
= find_name(line
, NULL
, 0, 0);
326 static int gitdiff_copydst(const char *line
, struct patch
*patch
)
329 patch
->new_name
= find_name(line
, NULL
, 0, 0);
333 static int gitdiff_renamesrc(const char *line
, struct patch
*patch
)
335 patch
->is_rename
= 1;
336 patch
->old_name
= find_name(line
, NULL
, 0, 0);
340 static int gitdiff_renamedst(const char *line
, struct patch
*patch
)
342 patch
->is_rename
= 1;
343 patch
->new_name
= find_name(line
, NULL
, 0, 0);
347 static int gitdiff_similarity(const char *line
, struct patch
*patch
)
349 if ((patch
->score
= strtoul(line
, NULL
, 10)) == ULONG_MAX
)
354 static int gitdiff_dissimilarity(const char *line
, struct patch
*patch
)
356 if ((patch
->score
= strtoul(line
, NULL
, 10)) == ULONG_MAX
)
361 static int gitdiff_index(const char *line
, struct patch
*patch
)
363 /* index line is N hexadecimal, "..", N hexadecimal,
364 * and optional space with octal mode.
366 const char *ptr
, *eol
;
369 ptr
= strchr(line
, '.');
370 if (!ptr
|| ptr
[1] != '.' || 40 <= ptr
- line
)
373 memcpy(patch
->old_sha1_prefix
, line
, len
);
374 patch
->old_sha1_prefix
[len
] = 0;
377 ptr
= strchr(line
, ' ');
378 eol
= strchr(line
, '\n');
380 if (!ptr
|| eol
< ptr
)
386 memcpy(patch
->new_sha1_prefix
, line
, len
);
387 patch
->new_sha1_prefix
[len
] = 0;
389 patch
->new_mode
= patch
->old_mode
= strtoul(ptr
+1, NULL
, 8);
394 * This is normal for a diff that doesn't change anything: we'll fall through
395 * into the next diff. Tell the parser to break out.
397 static int gitdiff_unrecognized(const char *line
, struct patch
*patch
)
402 static const char *stop_at_slash(const char *line
, int llen
)
406 for (i
= 0; i
< llen
; i
++) {
414 /* This is to extract the same name that appears on "diff --git"
415 * line. We do not find and return anything if it is a rename
416 * patch, and it is OK because we will find the name elsewhere.
417 * We need to reliably find name only when it is mode-change only,
418 * creation or deletion of an empty file. In any of these cases,
419 * both sides are the same name under a/ and b/ respectively.
421 static char *git_header_name(char *line
, int llen
)
425 const char *second
= NULL
;
427 line
+= strlen("diff --git ");
428 llen
-= strlen("diff --git ");
432 char *first
= unquote_c_style(line
, &second
);
436 /* advance to the first slash */
437 cp
= stop_at_slash(first
, strlen(first
));
438 if (!cp
|| cp
== first
) {
439 /* we do not accept absolute paths */
445 memmove(first
, cp
+1, len
+1); /* including NUL */
447 /* second points at one past closing dq of name.
448 * find the second name.
450 while ((second
< line
+ llen
) && isspace(*second
))
453 if (line
+ llen
<= second
)
454 goto free_first_and_fail
;
455 if (*second
== '"') {
456 char *sp
= unquote_c_style(second
, NULL
);
458 goto free_first_and_fail
;
459 cp
= stop_at_slash(sp
, strlen(sp
));
460 if (!cp
|| cp
== sp
) {
463 goto free_first_and_fail
;
465 /* They must match, otherwise ignore */
466 if (strcmp(cp
+1, first
))
467 goto free_both_and_fail
;
472 /* unquoted second */
473 cp
= stop_at_slash(second
, line
+ llen
- second
);
474 if (!cp
|| cp
== second
)
475 goto free_first_and_fail
;
477 if (line
+ llen
- cp
!= len
+ 1 ||
478 memcmp(first
, cp
, len
))
479 goto free_first_and_fail
;
483 /* unquoted first name */
484 name
= stop_at_slash(line
, llen
);
485 if (!name
|| name
== line
)
490 /* since the first name is unquoted, a dq if exists must be
491 * the beginning of the second name.
493 for (second
= name
; second
< line
+ llen
; second
++) {
494 if (*second
== '"') {
495 const char *cp
= second
;
497 char *sp
= unquote_c_style(second
, NULL
);
501 np
= stop_at_slash(sp
, strlen(sp
));
502 if (!np
|| np
== sp
) {
503 free_second_and_fail
:
509 if (len
< cp
- name
&&
510 !strncmp(np
, name
, len
) &&
511 isspace(name
[len
])) {
513 memmove(sp
, np
, len
+ 1);
516 goto free_second_and_fail
;
521 * Accept a name only if it shows up twice, exactly the same
524 for (len
= 0 ; ; len
++) {
541 if (second
[len
] == '\n' && !memcmp(name
, second
, len
)) {
542 char *ret
= xmalloc(len
+ 1);
543 memcpy(ret
, name
, len
);
552 /* Verify that we recognize the lines following a git header */
553 static int parse_git_header(char *line
, int len
, unsigned int size
, struct patch
*patch
)
555 unsigned long offset
;
557 /* A git diff has explicit new/delete information, so we don't guess */
559 patch
->is_delete
= 0;
562 * Some things may not have the old name in the
563 * rest of the headers anywhere (pure mode changes,
564 * or removing or adding empty files), so we get
565 * the default name from the header.
567 patch
->def_name
= git_header_name(line
, len
);
572 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
573 static const struct opentry
{
575 int (*fn
)(const char *, struct patch
*);
577 { "@@ -", gitdiff_hdrend
},
578 { "--- ", gitdiff_oldname
},
579 { "+++ ", gitdiff_newname
},
580 { "old mode ", gitdiff_oldmode
},
581 { "new mode ", gitdiff_newmode
},
582 { "deleted file mode ", gitdiff_delete
},
583 { "new file mode ", gitdiff_newfile
},
584 { "copy from ", gitdiff_copysrc
},
585 { "copy to ", gitdiff_copydst
},
586 { "rename old ", gitdiff_renamesrc
},
587 { "rename new ", gitdiff_renamedst
},
588 { "rename from ", gitdiff_renamesrc
},
589 { "rename to ", gitdiff_renamedst
},
590 { "similarity index ", gitdiff_similarity
},
591 { "dissimilarity index ", gitdiff_dissimilarity
},
592 { "index ", gitdiff_index
},
593 { "", gitdiff_unrecognized
},
597 len
= linelen(line
, size
);
598 if (!len
|| line
[len
-1] != '\n')
600 for (i
= 0; i
< sizeof(optable
) / sizeof(optable
[0]); i
++) {
601 const struct opentry
*p
= optable
+ i
;
602 int oplen
= strlen(p
->str
);
603 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
605 if (p
->fn(line
+ oplen
, patch
) < 0)
614 static int parse_num(const char *line
, unsigned long *p
)
620 *p
= strtoul(line
, &ptr
, 10);
624 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
625 unsigned long *p1
, unsigned long *p2
)
629 if (offset
< 0 || offset
>= len
)
634 digits
= parse_num(line
, p1
);
644 digits
= parse_num(line
+1, p2
);
656 if (memcmp(line
, expect
, ex
))
663 * Parse a unified diff fragment header of the
664 * form "@@ -a,b +c,d @@"
666 static int parse_fragment_header(char *line
, int len
, struct fragment
*fragment
)
670 if (!len
|| line
[len
-1] != '\n')
673 /* Figure out the number of lines in a fragment */
674 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
675 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
680 static int find_header(char *line
, unsigned long size
, int *hdrsize
, struct patch
*patch
)
682 unsigned long offset
, len
;
684 patch
->is_rename
= patch
->is_copy
= 0;
685 patch
->is_new
= patch
->is_delete
= -1;
686 patch
->old_mode
= patch
->new_mode
= 0;
687 patch
->old_name
= patch
->new_name
= NULL
;
688 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
689 unsigned long nextlen
;
691 len
= linelen(line
, size
);
695 /* Testing this early allows us to take a few shortcuts.. */
700 * Make sure we don't find any unconnected patch fragmants.
701 * That's a sign that we didn't find a header, and that a
702 * patch has become corrupted/broken up.
704 if (!memcmp("@@ -", line
, 4)) {
705 struct fragment dummy
;
706 if (parse_fragment_header(line
, len
, &dummy
) < 0)
708 error("patch fragment without header at line %d: %.*s", linenr
, (int)len
-1, line
);
715 * Git patch? It might not have a real patch, just a rename
716 * or mode change, so we handle that specially
718 if (!memcmp("diff --git ", line
, 11)) {
719 int git_hdr_len
= parse_git_header(line
, len
, size
, patch
);
720 if (git_hdr_len
<= len
)
722 if (!patch
->old_name
&& !patch
->new_name
) {
723 if (!patch
->def_name
)
724 die("git diff header lacks filename information (line %d)", linenr
);
725 patch
->old_name
= patch
->new_name
= patch
->def_name
;
727 *hdrsize
= git_hdr_len
;
731 /** --- followed by +++ ? */
732 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
736 * We only accept unified patches, so we want it to
737 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
740 nextlen
= linelen(line
+ len
, size
- len
);
741 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
744 /* Ok, we'll consider it a patch */
745 parse_traditional_patch(line
, line
+len
, patch
);
746 *hdrsize
= len
+ nextlen
;
754 * Parse a unified diff. Note that this really needs
755 * to parse each fragment separately, since the only
756 * way to know the difference between a "---" that is
757 * part of a patch, and a "---" that starts the next
758 * patch is to look at the line counts..
760 static int parse_fragment(char *line
, unsigned long size
, struct patch
*patch
, struct fragment
*fragment
)
763 int len
= linelen(line
, size
), offset
;
764 unsigned long oldlines
, newlines
;
766 offset
= parse_fragment_header(line
, len
, fragment
);
769 oldlines
= fragment
->oldlines
;
770 newlines
= fragment
->newlines
;
772 if (patch
->is_new
< 0) {
773 patch
->is_new
= !oldlines
;
775 patch
->old_name
= NULL
;
777 if (patch
->is_delete
< 0) {
778 patch
->is_delete
= !newlines
;
780 patch
->new_name
= NULL
;
783 if (patch
->is_new
!= !oldlines
)
784 return error("new file depends on old contents");
785 if (patch
->is_delete
!= !newlines
) {
787 return error("deleted file still has contents");
788 fprintf(stderr
, "** warning: file %s becomes empty but is not deleted\n", patch
->new_name
);
791 /* Parse the thing.. */
796 for (offset
= len
; size
> 0; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
797 if (!oldlines
&& !newlines
)
799 len
= linelen(line
, size
);
800 if (!len
|| line
[len
-1] != '\n')
818 /* We allow "\ No newline at end of file". Depending
819 * on locale settings when the patch was produced we
820 * don't know what this line looks like. The only
821 * thing we do know is that it begins with "\ ".
822 * Checking for 12 is just for sanity check -- any
823 * l10n of "\ No newline..." is at least that long.
826 if (len
< 12 || memcmp(line
, "\\ ", 2))
831 /* If a fragment ends with an incomplete line, we failed to include
832 * it in the above loop because we hit oldlines == newlines == 0
835 if (12 < size
&& !memcmp(line
, "\\ ", 2))
836 offset
+= linelen(line
, size
);
838 patch
->lines_added
+= added
;
839 patch
->lines_deleted
+= deleted
;
843 static int parse_single_patch(char *line
, unsigned long size
, struct patch
*patch
)
845 unsigned long offset
= 0;
846 struct fragment
**fragp
= &patch
->fragments
;
848 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
849 struct fragment
*fragment
;
852 fragment
= xmalloc(sizeof(*fragment
));
853 memset(fragment
, 0, sizeof(*fragment
));
854 len
= parse_fragment(line
, size
, patch
, fragment
);
856 die("corrupt patch at line %d", linenr
);
858 fragment
->patch
= line
;
859 fragment
->size
= len
;
862 fragp
= &fragment
->next
;
871 static inline int metadata_changes(struct patch
*patch
)
873 return patch
->is_rename
> 0 ||
874 patch
->is_copy
> 0 ||
877 (patch
->old_mode
&& patch
->new_mode
&&
878 patch
->old_mode
!= patch
->new_mode
);
881 static int parse_chunk(char *buffer
, unsigned long size
, struct patch
*patch
)
883 int hdrsize
, patchsize
;
884 int offset
= find_header(buffer
, size
, &hdrsize
, patch
);
889 patchsize
= parse_single_patch(buffer
+ offset
+ hdrsize
, size
- offset
- hdrsize
, patch
);
891 if (!patchsize
&& !metadata_changes(patch
))
892 die("patch with only garbage at line %d", linenr
);
894 return offset
+ hdrsize
+ patchsize
;
897 static const char pluses
[] = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
898 static const char minuses
[]= "----------------------------------------------------------------------";
900 static void show_stats(struct patch
*patch
)
902 const char *prefix
= "";
903 char *name
= patch
->new_name
;
905 int len
, max
, add
, del
, total
;
908 name
= patch
->old_name
;
910 if (0 < (len
= quote_c_style(name
, NULL
, NULL
, 0))) {
911 qname
= xmalloc(len
+ 1);
912 quote_c_style(name
, qname
, NULL
, 0);
917 * "scale" the filename
928 slash
= strchr(name
, '/');
935 * scale the add/delete
941 add
= patch
->lines_added
;
942 del
= patch
->lines_deleted
;
945 if (max_change
> 0) {
946 total
= (total
* max
+ max_change
/ 2) / max_change
;
947 add
= (add
* max
+ max_change
/ 2) / max_change
;
950 printf(" %s%-*s |%5d %.*s%.*s\n", prefix
,
951 len
, name
, patch
->lines_added
+ patch
->lines_deleted
,
952 add
, pluses
, del
, minuses
);
957 static int read_old_data(struct stat
*st
, const char *path
, void *buf
, unsigned long size
)
962 switch (st
->st_mode
& S_IFMT
) {
964 return readlink(path
, buf
, size
);
966 fd
= open(path
, O_RDONLY
);
968 return error("unable to open %s", path
);
971 int ret
= read(fd
, buf
+ got
, size
- got
);
989 static int find_offset(const char *buf
, unsigned long size
, const char *fragment
, unsigned long fragsize
, int line
)
992 unsigned long start
, backwards
, forwards
;
999 unsigned long offset
= 0;
1001 while (offset
+ fragsize
<= size
) {
1002 if (buf
[offset
++] == '\n') {
1010 /* Exact line number? */
1011 if (!memcmp(buf
+ start
, fragment
, fragsize
))
1015 * There's probably some smart way to do this, but I'll leave
1016 * that to the smart and beautiful people. I'm simple and stupid.
1020 for (i
= 0; ; i
++) {
1027 if (forwards
+ fragsize
> size
)
1033 } while (backwards
&& buf
[backwards
-1] != '\n');
1036 while (forwards
+ fragsize
<= size
) {
1037 if (buf
[forwards
++] == '\n')
1043 if (try + fragsize
> size
)
1045 if (memcmp(buf
+ try, fragment
, fragsize
))
1054 * We should start searching forward and backward.
1059 struct buffer_desc
{
1062 unsigned long alloc
;
1065 static int apply_one_fragment(struct buffer_desc
*desc
, struct fragment
*frag
)
1067 char *buf
= desc
->buffer
;
1068 const char *patch
= frag
->patch
;
1069 int offset
, size
= frag
->size
;
1070 char *old
= xmalloc(size
);
1071 char *new = xmalloc(size
);
1072 int oldsize
= 0, newsize
= 0;
1075 int len
= linelen(patch
, size
);
1082 * "plen" is how much of the line we should use for
1083 * the actual patch data. Normally we just remove the
1084 * first character on the line, but if the line is
1085 * followed by "\ No newline", then we also remove the
1086 * last one (which is the newline, of course).
1089 if (len
< size
&& patch
[len
] == '\\')
1094 memcpy(old
+ oldsize
, patch
+ 1, plen
);
1098 /* Fall-through for ' ' */
1100 memcpy(new + newsize
, patch
+ 1, plen
);
1103 case '@': case '\\':
1104 /* Ignore it, we already handled it */
1113 offset
= find_offset(buf
, desc
->size
, old
, oldsize
, frag
->newpos
);
1115 int diff
= newsize
- oldsize
;
1116 unsigned long size
= desc
->size
+ diff
;
1117 unsigned long alloc
= desc
->alloc
;
1120 alloc
= size
+ 8192;
1121 desc
->alloc
= alloc
;
1122 buf
= xrealloc(buf
, alloc
);
1126 memmove(buf
+ offset
+ newsize
, buf
+ offset
+ oldsize
, size
- offset
- newsize
);
1127 memcpy(buf
+ offset
, new, newsize
);
1136 static int apply_fragments(struct buffer_desc
*desc
, struct patch
*patch
)
1138 struct fragment
*frag
= patch
->fragments
;
1141 if (apply_one_fragment(desc
, frag
) < 0)
1142 return error("patch failed: %s:%ld", patch
->old_name
, frag
->oldpos
);
1148 static int apply_data(struct patch
*patch
, struct stat
*st
)
1151 unsigned long size
, alloc
;
1152 struct buffer_desc desc
;
1157 if (patch
->old_name
) {
1159 alloc
= size
+ 8192;
1160 buf
= xmalloc(alloc
);
1161 if (read_old_data(st
, patch
->old_name
, buf
, alloc
) != size
)
1162 return error("read of %s failed", patch
->old_name
);
1168 if (apply_fragments(&desc
, patch
) < 0)
1170 patch
->result
= desc
.buffer
;
1171 patch
->resultsize
= desc
.size
;
1173 if (patch
->is_delete
&& patch
->resultsize
)
1174 return error("removal patch leaves file contents");
1179 static int check_patch(struct patch
*patch
)
1182 const char *old_name
= patch
->old_name
;
1183 const char *new_name
= patch
->new_name
;
1187 int stat_ret
= lstat(old_name
, &st
);
1190 int pos
= cache_name_pos(old_name
, strlen(old_name
));
1192 return error("%s: does not exist in index",
1195 struct checkout costate
;
1196 if (errno
!= ENOENT
)
1197 return error("%s: %s", old_name
,
1200 costate
.base_dir
= "";
1201 costate
.base_dir_len
= 0;
1204 costate
.not_new
= 0;
1205 costate
.refresh_cache
= 1;
1206 if (checkout_entry(active_cache
[pos
],
1208 lstat(old_name
, &st
))
1212 changed
= ce_match_stat(active_cache
[pos
], &st
);
1214 return error("%s: does not match index",
1217 else if (stat_ret
< 0)
1218 return error("%s: %s", old_name
, strerror(errno
));
1220 if (patch
->is_new
< 0)
1222 st
.st_mode
= ntohl(create_ce_mode(st
.st_mode
));
1223 if (!patch
->old_mode
)
1224 patch
->old_mode
= st
.st_mode
;
1225 if ((st
.st_mode
^ patch
->old_mode
) & S_IFMT
)
1226 return error("%s: wrong type", old_name
);
1227 if (st
.st_mode
!= patch
->old_mode
)
1228 fprintf(stderr
, "warning: %s has type %o, expected %o\n",
1229 old_name
, st
.st_mode
, patch
->old_mode
);
1232 if (new_name
&& (patch
->is_new
| patch
->is_rename
| patch
->is_copy
)) {
1233 if (check_index
&& cache_name_pos(new_name
, strlen(new_name
)) >= 0)
1234 return error("%s: already exists in index", new_name
);
1235 if (!lstat(new_name
, &st
))
1236 return error("%s: already exists in working directory", new_name
);
1237 if (errno
!= ENOENT
)
1238 return error("%s: %s", new_name
, strerror(errno
));
1239 if (!patch
->new_mode
) {
1241 patch
->new_mode
= S_IFREG
| 0644;
1243 patch
->new_mode
= patch
->old_mode
;
1247 if (new_name
&& old_name
) {
1248 int same
= !strcmp(old_name
, new_name
);
1249 if (!patch
->new_mode
)
1250 patch
->new_mode
= patch
->old_mode
;
1251 if ((patch
->old_mode
^ patch
->new_mode
) & S_IFMT
)
1252 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
1253 patch
->new_mode
, new_name
, patch
->old_mode
,
1254 same
? "" : " of ", same
? "" : old_name
);
1257 if (apply_data(patch
, &st
) < 0)
1258 return error("%s: patch does not apply", old_name
);
1262 static int check_patch_list(struct patch
*patch
)
1266 for (;patch
; patch
= patch
->next
)
1267 error
|= check_patch(patch
);
1271 static inline int is_null_sha1(const unsigned char *sha1
)
1273 return !memcmp(sha1
, null_sha1
, 20);
1276 static void show_index_list(struct patch
*list
)
1278 struct patch
*patch
;
1280 /* Once we start supporting the reverse patch, it may be
1281 * worth showing the new sha1 prefix, but until then...
1283 for (patch
= list
; patch
; patch
= patch
->next
) {
1284 const unsigned char *sha1_ptr
;
1285 unsigned char sha1
[20];
1288 name
= patch
->old_name
? patch
->old_name
: patch
->new_name
;
1290 sha1_ptr
= null_sha1
;
1291 else if (get_sha1(patch
->old_sha1_prefix
, sha1
))
1292 die("sha1 information is lacking or useless (%s).",
1297 printf("%06o %s ",patch
->old_mode
, sha1_to_hex(sha1_ptr
));
1298 if (line_termination
&& quote_c_style(name
, NULL
, NULL
, 0))
1299 quote_c_style(name
, NULL
, stdout
, 0);
1301 fputs(name
, stdout
);
1302 putchar(line_termination
);
1306 static void stat_patch_list(struct patch
*patch
)
1308 int files
, adds
, dels
;
1310 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
1312 adds
+= patch
->lines_added
;
1313 dels
+= patch
->lines_deleted
;
1317 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files
, adds
, dels
);
1320 static void show_file_mode_name(const char *newdelete
, unsigned int mode
, const char *name
)
1323 printf(" %s mode %06o %s\n", newdelete
, mode
, name
);
1325 printf(" %s %s\n", newdelete
, name
);
1328 static void show_mode_change(struct patch
*p
, int show_name
)
1330 if (p
->old_mode
&& p
->new_mode
&& p
->old_mode
!= p
->new_mode
) {
1332 printf(" mode change %06o => %06o %s\n",
1333 p
->old_mode
, p
->new_mode
, p
->new_name
);
1335 printf(" mode change %06o => %06o\n",
1336 p
->old_mode
, p
->new_mode
);
1340 static void show_rename_copy(struct patch
*p
)
1342 const char *renamecopy
= p
->is_rename
? "rename" : "copy";
1343 const char *old
, *new;
1345 /* Find common prefix */
1349 const char *slash_old
, *slash_new
;
1350 slash_old
= strchr(old
, '/');
1351 slash_new
= strchr(new, '/');
1354 slash_old
- old
!= slash_new
- new ||
1355 memcmp(old
, new, slash_new
- new))
1357 old
= slash_old
+ 1;
1358 new = slash_new
+ 1;
1360 /* p->old_name thru old is the common prefix, and old and new
1361 * through the end of names are renames
1363 if (old
!= p
->old_name
)
1364 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy
,
1365 (int)(old
- p
->old_name
), p
->old_name
,
1366 old
, new, p
->score
);
1368 printf(" %s %s => %s (%d%%)\n", renamecopy
,
1369 p
->old_name
, p
->new_name
, p
->score
);
1370 show_mode_change(p
, 0);
1373 static void summary_patch_list(struct patch
*patch
)
1377 for (p
= patch
; p
; p
= p
->next
) {
1379 show_file_mode_name("create", p
->new_mode
, p
->new_name
);
1380 else if (p
->is_delete
)
1381 show_file_mode_name("delete", p
->old_mode
, p
->old_name
);
1383 if (p
->is_rename
|| p
->is_copy
)
1384 show_rename_copy(p
);
1387 printf(" rewrite %s (%d%%)\n",
1388 p
->new_name
, p
->score
);
1389 show_mode_change(p
, 0);
1392 show_mode_change(p
, 1);
1398 static void patch_stats(struct patch
*patch
)
1400 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
1402 if (lines
> max_change
)
1404 if (patch
->old_name
) {
1405 int len
= quote_c_style(patch
->old_name
, NULL
, NULL
, 0);
1407 len
= strlen(patch
->old_name
);
1411 if (patch
->new_name
) {
1412 int len
= quote_c_style(patch
->new_name
, NULL
, NULL
, 0);
1414 len
= strlen(patch
->new_name
);
1420 static void remove_file(struct patch
*patch
)
1423 if (remove_file_from_cache(patch
->old_name
) < 0)
1424 die("unable to remove %s from index", patch
->old_name
);
1426 unlink(patch
->old_name
);
1429 static void add_index_file(const char *path
, unsigned mode
, void *buf
, unsigned long size
)
1432 struct cache_entry
*ce
;
1433 int namelen
= strlen(path
);
1434 unsigned ce_size
= cache_entry_size(namelen
);
1439 ce
= xmalloc(ce_size
);
1440 memset(ce
, 0, ce_size
);
1441 memcpy(ce
->name
, path
, namelen
);
1442 ce
->ce_mode
= create_ce_mode(mode
);
1443 ce
->ce_flags
= htons(namelen
);
1444 if (lstat(path
, &st
) < 0)
1445 die("unable to stat newly created file %s", path
);
1446 fill_stat_cache_info(ce
, &st
);
1447 if (write_sha1_file(buf
, size
, "blob", ce
->sha1
) < 0)
1448 die("unable to create backing store for newly created file %s", path
);
1449 if (add_cache_entry(ce
, ADD_CACHE_OK_TO_ADD
) < 0)
1450 die("unable to add cache entry for %s", path
);
1453 static void create_subdirectories(const char *path
)
1455 int len
= strlen(path
);
1456 char *buf
= xmalloc(len
+ 1);
1457 const char *slash
= path
;
1459 while ((slash
= strchr(slash
+1, '/')) != NULL
) {
1461 memcpy(buf
, path
, len
);
1463 if (mkdir(buf
, 0777) < 0) {
1464 if (errno
!= EEXIST
)
1471 static int try_create_file(const char *path
, unsigned int mode
, const char *buf
, unsigned long size
)
1476 return symlink(buf
, path
);
1477 fd
= open(path
, O_CREAT
| O_EXCL
| O_WRONLY
| O_TRUNC
, (mode
& 0100) ? 0777 : 0666);
1481 int written
= write(fd
, buf
, size
);
1483 if (errno
== EINTR
|| errno
== EAGAIN
)
1485 die("writing file %s: %s", path
, strerror(errno
));
1488 die("out of space writing file %s", path
);
1493 die("closing file %s: %s", path
, strerror(errno
));
1498 * We optimistically assume that the directories exist,
1499 * which is true 99% of the time anyway. If they don't,
1500 * we create them and try again.
1502 static void create_one_file(const char *path
, unsigned mode
, const char *buf
, unsigned long size
)
1504 if (!try_create_file(path
, mode
, buf
, size
))
1507 if (errno
== ENOENT
) {
1508 create_subdirectories(path
);
1509 if (!try_create_file(path
, mode
, buf
, size
))
1513 if (errno
== EEXIST
) {
1514 unsigned int nr
= getpid();
1517 const char *newpath
;
1518 newpath
= mkpath("%s~%u", path
, nr
);
1519 if (!try_create_file(newpath
, mode
, buf
, size
)) {
1520 if (!rename(newpath
, path
))
1525 if (errno
!= EEXIST
)
1529 die("unable to write file %s mode %o", path
, mode
);
1532 static void create_file(struct patch
*patch
)
1534 const char *path
= patch
->new_name
;
1535 unsigned mode
= patch
->new_mode
;
1536 unsigned long size
= patch
->resultsize
;
1537 char *buf
= patch
->result
;
1540 mode
= S_IFREG
| 0644;
1541 create_one_file(path
, mode
, buf
, size
);
1542 add_index_file(path
, mode
, buf
, size
);
1545 static void write_out_one_result(struct patch
*patch
)
1547 if (patch
->is_delete
> 0) {
1551 if (patch
->is_new
> 0 || patch
->is_copy
) {
1556 * Rename or modification boils down to the same
1557 * thing: remove the old, write the new
1563 static void write_out_results(struct patch
*list
, int skipped_patch
)
1565 if (!list
&& !skipped_patch
)
1569 write_out_one_result(list
);
1574 static struct cache_file cache_file
;
1576 static struct excludes
{
1577 struct excludes
*next
;
1581 static int use_patch(struct patch
*p
)
1583 const char *pathname
= p
->new_name
? p
->new_name
: p
->old_name
;
1584 struct excludes
*x
= excludes
;
1586 if (fnmatch(x
->path
, pathname
, 0) == 0)
1593 static int apply_patch(int fd
)
1596 unsigned long offset
, size
;
1597 char *buffer
= read_patch_file(fd
, &size
);
1598 struct patch
*list
= NULL
, **listp
= &list
;
1599 int skipped_patch
= 0;
1605 struct patch
*patch
;
1608 patch
= xmalloc(sizeof(*patch
));
1609 memset(patch
, 0, sizeof(*patch
));
1610 nr
= parse_chunk(buffer
+ offset
, size
, patch
);
1613 if (use_patch(patch
)) {
1616 listp
= &patch
->next
;
1618 /* perhaps free it a bit better? */
1627 write_index
= check_index
&& apply
;
1629 newfd
= hold_index_file_for_update(&cache_file
, get_index_file());
1631 if (read_cache() < 0)
1632 die("unable to read index file");
1635 if ((check
|| apply
) && check_patch_list(list
) < 0)
1639 write_out_results(list
, skipped_patch
);
1642 if (write_cache(newfd
, active_cache
, active_nr
) ||
1643 commit_index_file(&cache_file
))
1644 die("Unable to write new cachefile");
1647 if (show_index_info
)
1648 show_index_list(list
);
1651 stat_patch_list(list
);
1654 summary_patch_list(list
);
1660 int main(int argc
, char **argv
)
1665 for (i
= 1; i
< argc
; i
++) {
1666 const char *arg
= argv
[i
];
1669 if (!strcmp(arg
, "-")) {
1674 if (!strncmp(arg
, "--exclude=", 10)) {
1675 struct excludes
*x
= xmalloc(sizeof(*x
));
1681 if (!strcmp(arg
, "--stat")) {
1686 if (!strcmp(arg
, "--summary")) {
1691 if (!strcmp(arg
, "--check")) {
1696 if (!strcmp(arg
, "--index")) {
1700 if (!strcmp(arg
, "--apply")) {
1704 if (!strcmp(arg
, "--index-info")) {
1706 show_index_info
= 1;
1709 if (!strcmp(arg
, "-z")) {
1710 line_termination
= 0;
1713 fd
= open(arg
, O_RDONLY
);