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)
339 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
345 * This is normal for a diff that doesn't change anything: we'll fall through
346 * into the next diff. Tell the parser to break out.
348 static int gitdiff_unrecognized(const char *line, struct patch *patch)
353 static char *git_header_name(char *line)
371 * We don't accept absolute paths (/dev/null) as possibly valid
377 * Accept a name only if it shows up twice, exactly the same
380 for (len = 0 ; ; len++) {
397 if (second[len] == '\n' && !memcmp(name, second, len)) {
398 char *ret = xmalloc(len + 1);
399 memcpy(ret, name, len);
408 /* Verify that we recognize the lines following a git header */
409 static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
411 unsigned long offset;
413 /* A git diff has explicit new/delete information, so we don't guess */
415 patch->is_delete = 0;
418 * Some things may not have the old name in the
419 * rest of the headers anywhere (pure mode changes,
420 * or removing or adding empty files), so we get
421 * the default name from the header.
423 patch->def_name = git_header_name(line + strlen("diff --git "));
428 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
429 static const struct opentry {
431 int (*fn)(const char *, struct patch *);
433 { "@@ -", gitdiff_hdrend },
434 { "--- ", gitdiff_oldname },
435 { "+++ ", gitdiff_newname },
436 { "old mode ", gitdiff_oldmode },
437 { "new mode ", gitdiff_newmode },
438 { "deleted file mode ", gitdiff_delete },
439 { "new file mode ", gitdiff_newfile },
440 { "copy from ", gitdiff_copysrc },
441 { "copy to ", gitdiff_copydst },
442 { "rename from ", gitdiff_renamesrc },
443 { "rename to ", gitdiff_renamedst },
444 { "similarity index ", gitdiff_similarity },
445 { "dissimilarity index ", gitdiff_dissimilarity },
446 { "", gitdiff_unrecognized },
450 len = linelen(line, size);
451 if (!len || line[len-1] != '\n')
453 for (i = 0; i < sizeof(optable) / sizeof(optable[0]); i++) {
454 const struct opentry *p = optable + i;
455 int oplen = strlen(p->str);
456 if (len < oplen || memcmp(p->str, line, oplen))
458 if (p->fn(line + oplen, patch) < 0)
467 static int parse_num(const char *line, unsigned long *p)
473 *p = strtoul(line, &ptr, 10);
477 static int parse_range(const char *line, int len, int offset, const char *expect,
478 unsigned long *p1, unsigned long *p2)
482 if (offset < 0 || offset >= len)
487 digits = parse_num(line, p1);
497 digits = parse_num(line+1, p2);
509 if (memcmp(line, expect, ex))
516 * Parse a unified diff fragment header of the
517 * form "@@ -a,b +c,d @@"
519 static int parse_fragment_header(char *line, int len, struct fragment *fragment)
523 if (!len || line[len-1] != '\n')
526 /* Figure out the number of lines in a fragment */
527 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
528 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
533 static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
535 unsigned long offset, len;
537 patch->is_rename = patch->is_copy = 0;
538 patch->is_new = patch->is_delete = -1;
539 patch->old_mode = patch->new_mode = 0;
540 patch->old_name = patch->new_name = NULL;
541 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
542 unsigned long nextlen;
544 len = linelen(line, size);
548 /* Testing this early allows us to take a few shortcuts.. */
553 * Make sure we don't find any unconnected patch fragmants.
554 * That's a sign that we didn't find a header, and that a
555 * patch has become corrupted/broken up.
557 if (!memcmp("@@ -", line, 4)) {
558 struct fragment dummy;
559 if (parse_fragment_header(line, len, &dummy) < 0)
561 error("patch fragment without header at line %d: %.*s", linenr, len-1, line);
568 * Git patch? It might not have a real patch, just a rename
569 * or mode change, so we handle that specially
571 if (!memcmp("diff --git ", line, 11)) {
572 int git_hdr_len = parse_git_header(line, len, size, patch);
575 if (!patch->old_name && !patch->new_name)
576 die("git diff header lacks filename information");
577 *hdrsize = git_hdr_len;
581 /** --- followed by +++ ? */
582 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
586 * We only accept unified patches, so we want it to
587 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
590 nextlen = linelen(line + len, size - len);
591 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
594 /* Ok, we'll consider it a patch */
595 parse_traditional_patch(line, line+len, patch);
596 *hdrsize = len + nextlen;
604 * Parse a unified diff. Note that this really needs
605 * to parse each fragment separately, since the only
606 * way to know the difference between a "---" that is
607 * part of a patch, and a "---" that starts the next
608 * patch is to look at the line counts..
610 static int parse_fragment(char *line, unsigned long size, struct patch *patch, struct fragment *fragment)
613 int len = linelen(line, size), offset;
614 unsigned long pos[4], oldlines, newlines;
616 offset = parse_fragment_header(line, len, fragment);
619 oldlines = fragment->oldlines;
620 newlines = fragment->newlines;
622 if (patch->is_new < 0 && (pos[0] || oldlines))
624 if (patch->is_delete < 0 && (pos[1] || newlines))
625 patch->is_delete = 0;
627 /* Parse the thing.. */
632 for (offset = len; size > 0; offset += len, size -= len, line += len, linenr++) {
633 if (!oldlines && !newlines)
635 len = linelen(line, size);
636 if (!len || line[len-1] != '\n')
653 /* We allow "\ No newline at end of file" */
658 patch->lines_added += added;
659 patch->lines_deleted += deleted;
663 static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
665 unsigned long offset = 0;
666 struct fragment **fragp = &patch->fragments;
668 while (size > 4 && !memcmp(line, "@@ -", 4)) {
669 struct fragment *fragment;
672 fragment = xmalloc(sizeof(*fragment));
673 memset(fragment, 0, sizeof(*fragment));
674 len = parse_fragment(line, size, patch, fragment);
676 die("corrupt patch at line %d", linenr);
678 fragment->patch = line;
679 fragment->size = len;
682 fragp = &fragment->next;
691 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
693 int hdrsize, patchsize;
694 int offset = find_header(buffer, size, &hdrsize, patch);
699 patchsize = parse_single_patch(buffer + offset + hdrsize, size - offset - hdrsize, patch);
701 return offset + hdrsize + patchsize;
704 const char pluses[] = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
705 const char minuses[]= "----------------------------------------------------------------------";
707 static void show_stats(struct patch *patch)
709 char *name = patch->old_name;
710 int len, max, add, del;
713 name = patch->new_name;
716 * "scale" the filename
727 * scale the add/delete
733 add = (patch->lines_added * max + max_change/2) / max_change;
734 del = (patch->lines_deleted * max + max_change/2) / max_change;
735 printf(" %-*s |%5d %.*s%.*s\n",
736 len, name, patch->lines_added + patch->lines_deleted,
737 add, pluses, del, minuses);
740 static int check_patch(struct patch *patch)
743 const char *old_name = patch->old_name;
744 const char *new_name = patch->new_name;
747 int pos = cache_name_pos(old_name, strlen(old_name));
751 return error("%s: does not exist in index", old_name);
752 if (patch->is_new < 0)
754 if (lstat(old_name, &st) < 0)
755 return error("%s: %s\n", strerror(errno));
756 changed = ce_match_stat(active_cache[pos], &st);
758 return error("%s: does not match index", old_name);
759 if (!patch->old_mode)
760 patch->old_mode = st.st_mode;
763 if (new_name && (patch->is_new | patch->is_rename | patch->is_copy)) {
764 if (cache_name_pos(new_name, strlen(new_name)) >= 0)
765 return error("%s: already exists in index", new_name);
766 if (!lstat(new_name, &st))
767 return error("%s: already exists in working directory", new_name);
769 return error("%s: %s", new_name, strerror(errno));
774 static int check_patch_list(struct patch *patch)
778 for (;patch ; patch = patch->next)
779 error |= check_patch(patch);
783 static void show_file(int c, unsigned int mode, const char *name)
785 printf("%c %o %s\n", c, mode, name);
788 static void show_file_list(struct patch *patch)
790 for (;patch ; patch = patch->next) {
791 if (patch->is_rename) {
792 show_file('-', patch->old_mode, patch->old_name);
793 show_file('+', patch->new_mode, patch->new_name);
796 if (patch->is_copy || patch->is_new) {
797 show_file('+', patch->new_mode, patch->new_name);
800 if (patch->is_delete) {
801 show_file('-', patch->old_mode, patch->old_name);
804 if (patch->old_mode && patch->new_mode && patch->old_mode != patch->new_mode) {
805 printf("M %o:%o %s\n", patch->old_mode, patch->new_mode, patch->old_name);
808 printf("M %o %s\n", patch->old_mode, patch->old_name);
812 static void stat_patch_list(struct patch *patch)
814 int files, adds, dels;
816 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
818 adds += patch->lines_added;
819 dels += patch->lines_deleted;
823 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
826 static void patch_stats(struct patch *patch)
828 int lines = patch->lines_added + patch->lines_deleted;
830 if (lines > max_change)
832 if (patch->old_name) {
833 int len = strlen(patch->old_name);
837 if (patch->new_name) {
838 int len = strlen(patch->new_name);
844 static int apply_patch(int fd)
846 unsigned long offset, size;
847 char *buffer = read_patch_file(fd, &size);
848 struct patch *list = NULL, **listp = &list;
857 patch = xmalloc(sizeof(*patch));
858 memset(patch, 0, sizeof(*patch));
859 nr = parse_chunk(buffer + offset, size, patch);
864 listp = &patch->next;
869 if ((check || apply) && check_patch_list(list) < 0)
873 show_file_list(list);
876 stat_patch_list(list);
882 int main(int argc, char **argv)
887 if (read_cache() < 0)
888 die("unable to read index file");
890 for (i = 1; i < argc; i++) {
891 const char *arg = argv[i];
894 if (!strcmp(arg, "-")) {
899 if (!strcmp(arg, "--no-merge")) {
903 if (!strcmp(arg, "--stat")) {
908 if (!strcmp(arg, "--check")) {
913 if (!strcmp(arg, "--show-files")) {
917 fd = open(arg, O_RDONLY);