4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
8 * NOTE! It does all its work in the index file, and only cares about
9 * the files in the working directory if you tell it to "merge" the
12 * Even when merging it always takes the source from the index, and
13 * uses the working tree as a "branch" for a 3-way merge.
19 // We default to the merge behaviour, since that's what most people would
22 // --check turns on checking that the working tree matches the
23 // files that are being modified, but doesn't apply the patch
24 // --stat does just a diffstat, and doesn't actually apply
25 // --show-files shows the directory changes
27 static int merge_patch
= 1;
28 static int diffstat
= 0;
31 static int show_files
= 0;
32 static const char apply_usage
[] = "git-apply [--stat] [--check] [--show-files] <patch>";
35 * For "diff-stat" like behaviour, we keep track of the biggest change
36 * we've seen, and the longest filename. That allows us to do simple
39 static int max_change
, max_len
;
42 * Various "current state", notably line numbers and what
43 * file (and how) we're patching right now.. The "is_xxxx"
44 * things are flags, where -1 means "don't know yet".
46 static int linenr
= 1;
49 unsigned long oldpos
, oldlines
;
50 unsigned long newpos
, newlines
;
53 struct fragment
*next
;
57 char *new_name
, *old_name
, *def_name
;
58 unsigned int old_mode
, new_mode
;
59 int is_rename
, is_copy
, is_new
, is_delete
;
60 int lines_added
, lines_deleted
;
61 struct fragment
*fragments
;
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(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]);
123 static int name_terminate(const char *name
, int namelen
, int c
, int terminate
)
125 if (c
== ' ' && !(terminate
& TERM_SPACE
))
127 if (c
== '\t' && !(terminate
& TERM_TAB
))
131 * Do we want an existing name? Return false and
132 * continue if it's not there.
134 if (terminate
& TERM_EXIST
)
135 return cache_name_pos(name
, namelen
) >= 0;
140 static char * find_name(const char *line
, char *def
, int p_value
, int terminate
)
143 const char *start
= line
;
152 if (name_terminate(start
, line
-start
, c
, terminate
))
156 if (c
== '/' && !--p_value
)
166 * Generally we prefer the shorter name, especially
167 * if the other one is just a variation of that with
168 * something else tacked on to the end (ie "file.orig"
172 int deflen
= strlen(def
);
173 if (deflen
< len
&& !strncmp(start
, def
, deflen
))
177 name
= xmalloc(len
+ 1);
178 memcpy(name
, start
, len
);
185 * Get the name etc info from the --/+++ lines of a traditional patch header
187 * NOTE! This hardcodes "-p1" behaviour in filename detection.
189 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
190 * files, we can happily check the index for a match, but for creating a
191 * new file we should try to match whatever "patch" does. I have no idea.
193 static void parse_traditional_patch(const char *first
, const char *second
, struct patch
*patch
)
198 first
+= 4; // skip "--- "
199 second
+= 4; // skip "+++ "
200 if (is_dev_null(first
)) {
202 patch
->is_delete
= 0;
203 name
= find_name(second
, NULL
, p_value
, TERM_SPACE
| TERM_TAB
);
204 patch
->new_name
= name
;
205 } else if (is_dev_null(second
)) {
207 patch
->is_delete
= 1;
208 name
= find_name(first
, NULL
, p_value
, TERM_EXIST
| TERM_SPACE
| TERM_TAB
);
209 patch
->old_name
= name
;
211 name
= find_name(first
, NULL
, p_value
, TERM_EXIST
| TERM_SPACE
| TERM_TAB
);
212 name
= find_name(second
, name
, p_value
, TERM_EXIST
| TERM_SPACE
| TERM_TAB
);
213 patch
->old_name
= patch
->new_name
= name
;
216 die("unable to find filename in patch at line %d", linenr
);
219 static int gitdiff_hdrend(const char *line
, struct patch
*patch
)
225 * We're anal about diff header consistency, to make
226 * sure that we don't end up having strange ambiguous
227 * patches floating around.
229 * As a result, gitdiff_{old|new}name() will check
230 * their names against any previous information, just
233 static char *gitdiff_verify_name(const char *line
, int isnull
, char *orig_name
, const char *oldnew
)
238 if (!orig_name
&& !isnull
)
239 return find_name(line
, NULL
, 1, 0);
247 die("git-apply: bad git-diff - expected /dev/null, got %s on line %d", name
, linenr
);
260 if (memcmp(line
, name
, len
) || line
[len
] != '\n')
264 die("git-apply: bad git-diff - inconsistent %s filename on line %d", oldnew
, linenr
);
268 static int gitdiff_oldname(const char *line
, struct patch
*patch
)
270 patch
->old_name
= gitdiff_verify_name(line
, patch
->is_new
, patch
->old_name
, "old");
274 static int gitdiff_newname(const char *line
, struct patch
*patch
)
276 patch
->new_name
= gitdiff_verify_name(line
, patch
->is_delete
, patch
->new_name
, "new");
280 static int gitdiff_oldmode(const char *line
, struct patch
*patch
)
282 patch
->old_mode
= strtoul(line
, NULL
, 8);
286 static int gitdiff_newmode(const char *line
, struct patch
*patch
)
288 patch
->new_mode
= strtoul(line
, NULL
, 8);
292 static int gitdiff_delete(const char *line
, struct patch
*patch
)
294 patch
->is_delete
= 1;
295 patch
->old_name
= patch
->def_name
;
296 return gitdiff_oldmode(line
, patch
);
299 static int gitdiff_newfile(const char *line
, struct patch
*patch
)
302 patch
->new_name
= patch
->def_name
;
303 return gitdiff_newmode(line
, patch
);
306 static int gitdiff_copysrc(const char *line
, struct patch
*patch
)
309 patch
->old_name
= find_name(line
, NULL
, 0, 0);
313 static int gitdiff_copydst(const char *line
, struct patch
*patch
)
316 patch
->new_name
= find_name(line
, NULL
, 0, 0);
320 static int gitdiff_renamesrc(const char *line
, struct patch
*patch
)
322 patch
->is_rename
= 1;
323 patch
->old_name
= find_name(line
, NULL
, 0, 0);
327 static int gitdiff_renamedst(const char *line
, struct patch
*patch
)
329 patch
->is_rename
= 1;
330 patch
->new_name
= find_name(line
, NULL
, 0, 0);
334 static int gitdiff_similarity(const char *line
, struct patch
*patch
)
340 * This is normal for a diff that doesn't change anything: we'll fall through
341 * into the next diff. Tell the parser to break out.
343 static int gitdiff_unrecognized(const char *line
, struct patch
*patch
)
348 static char *git_header_name(char *line
)
366 * We don't accept absolute paths (/dev/null) as possibly valid
372 * Accept a name only if it shows up twice, exactly the same
375 for (len
= 0 ; ; len
++) {
392 if (second
[len
] == '\n' && !memcmp(name
, second
, len
)) {
393 char *ret
= xmalloc(len
+ 1);
394 memcpy(ret
, name
, len
);
403 /* Verify that we recognize the lines following a git header */
404 static int parse_git_header(char *line
, int len
, unsigned int size
, struct patch
*patch
)
406 unsigned long offset
;
408 /* A git diff has explicit new/delete information, so we don't guess */
410 patch
->is_delete
= 0;
413 * Some things may not have the old name in the
414 * rest of the headers anywhere (pure mode changes,
415 * or removing or adding empty files), so we get
416 * the default name from the header.
418 patch
->def_name
= git_header_name(line
+ strlen("diff --git "));
423 for (offset
= len
; size
> 0 ; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
424 static const struct opentry
{
426 int (*fn
)(const char *, struct patch
*);
428 { "@@ -", gitdiff_hdrend
},
429 { "--- ", gitdiff_oldname
},
430 { "+++ ", gitdiff_newname
},
431 { "old mode ", gitdiff_oldmode
},
432 { "new mode ", gitdiff_newmode
},
433 { "deleted file mode ", gitdiff_delete
},
434 { "new file mode ", gitdiff_newfile
},
435 { "copy from ", gitdiff_copysrc
},
436 { "copy to ", gitdiff_copydst
},
437 { "rename from ", gitdiff_renamesrc
},
438 { "rename to ", gitdiff_renamedst
},
439 { "similarity index ", gitdiff_similarity
},
440 { "", gitdiff_unrecognized
},
444 len
= linelen(line
, size
);
445 if (!len
|| line
[len
-1] != '\n')
447 for (i
= 0; i
< sizeof(optable
) / sizeof(optable
[0]); i
++) {
448 const struct opentry
*p
= optable
+ i
;
449 int oplen
= strlen(p
->str
);
450 if (len
< oplen
|| memcmp(p
->str
, line
, oplen
))
452 if (p
->fn(line
+ oplen
, patch
) < 0)
461 static int parse_num(const char *line
, unsigned long *p
)
467 *p
= strtoul(line
, &ptr
, 10);
471 static int parse_range(const char *line
, int len
, int offset
, const char *expect
,
472 unsigned long *p1
, unsigned long *p2
)
476 if (offset
< 0 || offset
>= len
)
481 digits
= parse_num(line
, p1
);
491 digits
= parse_num(line
+1, p2
);
503 if (memcmp(line
, expect
, ex
))
510 * Parse a unified diff fragment header of the
511 * form "@@ -a,b +c,d @@"
513 static int parse_fragment_header(char *line
, int len
, struct fragment
*fragment
)
517 if (!len
|| line
[len
-1] != '\n')
520 /* Figure out the number of lines in a fragment */
521 offset
= parse_range(line
, len
, 4, " +", &fragment
->oldpos
, &fragment
->oldlines
);
522 offset
= parse_range(line
, len
, offset
, " @@", &fragment
->newpos
, &fragment
->newlines
);
527 static int find_header(char *line
, unsigned long size
, int *hdrsize
, struct patch
*patch
)
529 unsigned long offset
, len
;
531 patch
->is_rename
= patch
->is_copy
= 0;
532 patch
->is_new
= patch
->is_delete
= -1;
533 patch
->old_mode
= patch
->new_mode
= 0;
534 patch
->old_name
= patch
->new_name
= NULL
;
535 for (offset
= 0; size
> 0; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
536 unsigned long nextlen
;
538 len
= linelen(line
, size
);
542 /* Testing this early allows us to take a few shortcuts.. */
547 * Make sure we don't find any unconnected patch fragmants.
548 * That's a sign that we didn't find a header, and that a
549 * patch has become corrupted/broken up.
551 if (!memcmp("@@ -", line
, 4)) {
552 struct fragment dummy
;
553 if (parse_fragment_header(line
, len
, &dummy
) < 0)
555 error("patch fragment without header at line %d: %.*s", linenr
, len
-1, line
);
562 * Git patch? It might not have a real patch, just a rename
563 * or mode change, so we handle that specially
565 if (!memcmp("diff --git ", line
, 11)) {
566 int git_hdr_len
= parse_git_header(line
, len
, size
, patch
);
569 if (!patch
->old_name
&& !patch
->new_name
)
570 die("git diff header lacks filename information");
571 *hdrsize
= git_hdr_len
;
575 /** --- followed by +++ ? */
576 if (memcmp("--- ", line
, 4) || memcmp("+++ ", line
+ len
, 4))
580 * We only accept unified patches, so we want it to
581 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
584 nextlen
= linelen(line
+ len
, size
- len
);
585 if (size
< nextlen
+ 14 || memcmp("@@ -", line
+ len
+ nextlen
, 4))
588 /* Ok, we'll consider it a patch */
589 parse_traditional_patch(line
, line
+len
, patch
);
590 *hdrsize
= len
+ nextlen
;
598 * Parse a unified diff. Note that this really needs
599 * to parse each fragment separately, since the only
600 * way to know the difference between a "---" that is
601 * part of a patch, and a "---" that starts the next
602 * patch is to look at the line counts..
604 static int parse_fragment(char *line
, unsigned long size
, struct patch
*patch
, struct fragment
*fragment
)
607 int len
= linelen(line
, size
), offset
;
608 unsigned long pos
[4], oldlines
, newlines
;
610 offset
= parse_fragment_header(line
, len
, fragment
);
613 oldlines
= fragment
->oldlines
;
614 newlines
= fragment
->newlines
;
616 if (patch
->is_new
< 0 && (pos
[0] || oldlines
))
618 if (patch
->is_delete
< 0 && (pos
[1] || newlines
))
619 patch
->is_delete
= 0;
621 /* Parse the thing.. */
626 for (offset
= len
; size
> 0; offset
+= len
, size
-= len
, line
+= len
, linenr
++) {
627 if (!oldlines
&& !newlines
)
629 len
= linelen(line
, size
);
630 if (!len
|| line
[len
-1] != '\n')
647 /* We allow "\ No newline at end of file" */
652 patch
->lines_added
+= added
;
653 patch
->lines_deleted
+= deleted
;
657 static int parse_single_patch(char *line
, unsigned long size
, struct patch
*patch
)
659 unsigned long offset
= 0;
660 struct fragment
**fragp
= &patch
->fragments
;
662 while (size
> 4 && !memcmp(line
, "@@ -", 4)) {
663 struct fragment
*fragment
;
666 fragment
= xmalloc(sizeof(*fragment
));
667 memset(fragment
, 0, sizeof(*fragment
));
668 len
= parse_fragment(line
, size
, patch
, fragment
);
670 die("corrupt patch at line %d", linenr
);
672 fragment
->patch
= line
;
673 fragment
->size
= len
;
676 fragp
= &fragment
->next
;
685 static int parse_chunk(char *buffer
, unsigned long size
, struct patch
*patch
)
687 int hdrsize
, patchsize
;
688 int offset
= find_header(buffer
, size
, &hdrsize
, patch
);
693 patchsize
= parse_single_patch(buffer
+ offset
+ hdrsize
, size
- offset
- hdrsize
, patch
);
695 return offset
+ hdrsize
+ patchsize
;
698 const char pluses
[] = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
699 const char minuses
[]= "----------------------------------------------------------------------";
701 static void show_stats(struct patch
*patch
)
703 char *name
= patch
->old_name
;
704 int len
, max
, add
, del
;
707 name
= patch
->new_name
;
710 * "scale" the filename
721 * scale the add/delete
727 add
= (patch
->lines_added
* max
+ max_change
/2) / max_change
;
728 del
= (patch
->lines_deleted
* max
+ max_change
/2) / max_change
;
729 printf(" %-*s |%5d %.*s%.*s\n",
730 len
, name
, patch
->lines_added
+ patch
->lines_deleted
,
731 add
, pluses
, del
, minuses
);
734 static int check_patch(struct patch
*patch
)
737 const char *old_name
= patch
->old_name
;
738 const char *new_name
= patch
->new_name
;
741 int pos
= cache_name_pos(old_name
, strlen(old_name
));
745 return error("%s: does not exist in index", old_name
);
746 if (patch
->is_new
< 0)
748 if (lstat(old_name
, &st
) < 0)
749 return error("%s: %s\n", strerror(errno
));
750 changed
= ce_match_stat(active_cache
[pos
], &st
);
752 return error("%s: does not match index", old_name
);
753 if (!patch
->old_mode
)
754 patch
->old_mode
= st
.st_mode
;
757 if (new_name
&& (patch
->is_new
| patch
->is_rename
| patch
->is_copy
)) {
758 if (cache_name_pos(new_name
, strlen(new_name
)) >= 0)
759 return error("%s: already exists in index", new_name
);
760 if (!lstat(new_name
, &st
))
761 return error("%s: already exists in working directory", new_name
);
763 return error("%s: %s", new_name
, strerror(errno
));
768 static int check_patch_list(struct patch
*patch
)
772 for (;patch
; patch
= patch
->next
)
773 error
|= check_patch(patch
);
777 static void show_file(int c
, unsigned int mode
, const char *name
)
779 printf("%c %o %s\n", c
, mode
, name
);
782 static void show_file_list(struct patch
*patch
)
784 for (;patch
; patch
= patch
->next
) {
785 if (patch
->is_rename
) {
786 show_file('-', patch
->old_mode
, patch
->old_name
);
787 show_file('+', patch
->new_mode
, patch
->new_name
);
790 if (patch
->is_copy
|| patch
->is_new
) {
791 show_file('+', patch
->new_mode
, patch
->new_name
);
794 if (patch
->is_delete
) {
795 show_file('-', patch
->old_mode
, patch
->old_name
);
798 if (patch
->old_mode
&& patch
->new_mode
&& patch
->old_mode
!= patch
->new_mode
) {
799 printf("M %o:%o %s\n", patch
->old_mode
, patch
->new_mode
, patch
->old_name
);
802 printf("M %o %s\n", patch
->old_mode
, patch
->old_name
);
806 static void stat_patch_list(struct patch
*patch
)
808 int files
, adds
, dels
;
810 for (files
= adds
= dels
= 0 ; patch
; patch
= patch
->next
) {
812 adds
+= patch
->lines_added
;
813 dels
+= patch
->lines_deleted
;
817 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files
, adds
, dels
);
820 static void patch_stats(struct patch
*patch
)
822 int lines
= patch
->lines_added
+ patch
->lines_deleted
;
824 if (lines
> max_change
)
826 if (patch
->old_name
) {
827 int len
= strlen(patch
->old_name
);
831 if (patch
->new_name
) {
832 int len
= strlen(patch
->new_name
);
838 static int apply_patch(int fd
)
840 unsigned long offset
, size
;
841 char *buffer
= read_patch_file(fd
, &size
);
842 struct patch
*list
= NULL
, **listp
= &list
;
851 patch
= xmalloc(sizeof(*patch
));
852 memset(patch
, 0, sizeof(*patch
));
853 nr
= parse_chunk(buffer
+ offset
, size
, patch
);
858 listp
= &patch
->next
;
863 if ((check
|| apply
) && check_patch_list(list
) < 0)
867 show_file_list(list
);
870 stat_patch_list(list
);
876 int main(int argc
, char **argv
)
881 if (read_cache() < 0)
882 die("unable to read index file");
884 for (i
= 1; i
< argc
; i
++) {
885 const char *arg
= argv
[i
];
888 if (!strcmp(arg
, "-")) {
893 if (!strcmp(arg
, "--no-merge")) {
897 if (!strcmp(arg
, "--stat")) {
902 if (!strcmp(arg
, "--check")) {
907 if (!strcmp(arg
, "--show-files")) {
911 fd
= open(arg
, O_RDONLY
);