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]);
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;
144 if (name_terminate(start, line-start, c, terminate))
148 if (c == '/' && !--p_value)
158 * Generally we prefer the shorter name, especially
159 * if the other one is just a variation of that with
160 * something else tacked on to the end (ie "file.orig"
164 int deflen = strlen(def);
165 if (deflen < len && !strncmp(start, def, deflen))
169 name = xmalloc(len + 1);
170 memcpy(name, start, len);
177 * Get the name etc info from the --/+++ lines of a traditional patch header
179 * NOTE! This hardcodes "-p1" behaviour in filename detection.
181 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
182 * files, we can happily check the index for a match, but for creating a
183 * new file we should try to match whatever "patch" does. I have no idea.
185 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
190 first += 4; // skip "--- "
191 second += 4; // skip "+++ "
192 if (is_dev_null(first)) {
194 patch->is_delete = 0;
195 name = find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB);
196 patch->new_name = name;
197 } else if (is_dev_null(second)) {
199 patch->is_delete = 1;
200 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
201 patch->old_name = name;
203 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
204 name = find_name(second, name, p_value, TERM_SPACE | TERM_TAB);
205 patch->old_name = patch->new_name = name;
208 die("unable to find filename in patch at line %d", linenr);
211 static int gitdiff_hdrend(const char *line, struct patch *patch)
217 * We're anal about diff header consistency, to make
218 * sure that we don't end up having strange ambiguous
219 * patches floating around.
221 * As a result, gitdiff_{old|new}name() will check
222 * their names against any previous information, just
225 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
230 if (!orig_name && !isnull)
231 return find_name(line, NULL, 1, 0);
239 die("git-apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
252 if (memcmp(line, name, len) || line[len] != '\n')
256 die("git-apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
260 static int gitdiff_oldname(const char *line, struct patch *patch)
262 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
266 static int gitdiff_newname(const char *line, struct patch *patch)
268 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
272 static int gitdiff_oldmode(const char *line, struct patch *patch)
274 patch->old_mode = strtoul(line, NULL, 8);
278 static int gitdiff_newmode(const char *line, struct patch *patch)
280 patch->new_mode = strtoul(line, NULL, 8);
284 static int gitdiff_delete(const char *line, struct patch *patch)
286 patch->is_delete = 1;
287 patch->old_name = patch->def_name;
288 return gitdiff_oldmode(line, patch);
291 static int gitdiff_newfile(const char *line, struct patch *patch)
294 patch->new_name = patch->def_name;
295 return gitdiff_newmode(line, patch);
298 static int gitdiff_copysrc(const char *line, struct patch *patch)
301 patch->old_name = find_name(line, NULL, 0, 0);
305 static int gitdiff_copydst(const char *line, struct patch *patch)
308 patch->new_name = find_name(line, NULL, 0, 0);
312 static int gitdiff_renamesrc(const char *line, struct patch *patch)
314 patch->is_rename = 1;
315 patch->old_name = find_name(line, NULL, 0, 0);
319 static int gitdiff_renamedst(const char *line, struct patch *patch)
321 patch->is_rename = 1;
322 patch->new_name = find_name(line, NULL, 0, 0);
326 static int gitdiff_similarity(const char *line, struct patch *patch)
331 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
337 * This is normal for a diff that doesn't change anything: we'll fall through
338 * into the next diff. Tell the parser to break out.
340 static int gitdiff_unrecognized(const char *line, struct patch *patch)
345 static char *git_header_name(char *line)
363 * We don't accept absolute paths (/dev/null) as possibly valid
369 * Accept a name only if it shows up twice, exactly the same
372 for (len = 0 ; ; len++) {
389 if (second[len] == '\n' && !memcmp(name, second, len)) {
390 char *ret = xmalloc(len + 1);
391 memcpy(ret, name, len);
400 /* Verify that we recognize the lines following a git header */
401 static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
403 unsigned long offset;
405 /* A git diff has explicit new/delete information, so we don't guess */
407 patch->is_delete = 0;
410 * Some things may not have the old name in the
411 * rest of the headers anywhere (pure mode changes,
412 * or removing or adding empty files), so we get
413 * the default name from the header.
415 patch->def_name = git_header_name(line + strlen("diff --git "));
420 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
421 static const struct opentry {
423 int (*fn)(const char *, struct patch *);
425 { "@@ -", gitdiff_hdrend },
426 { "--- ", gitdiff_oldname },
427 { "+++ ", gitdiff_newname },
428 { "old mode ", gitdiff_oldmode },
429 { "new mode ", gitdiff_newmode },
430 { "deleted file mode ", gitdiff_delete },
431 { "new file mode ", gitdiff_newfile },
432 { "copy from ", gitdiff_copysrc },
433 { "copy to ", gitdiff_copydst },
434 { "rename from ", gitdiff_renamesrc },
435 { "rename to ", gitdiff_renamedst },
436 { "similarity index ", gitdiff_similarity },
437 { "dissimilarity index ", gitdiff_dissimilarity },
438 { "", gitdiff_unrecognized },
442 len = linelen(line, size);
443 if (!len || line[len-1] != '\n')
445 for (i = 0; i < sizeof(optable) / sizeof(optable[0]); i++) {
446 const struct opentry *p = optable + i;
447 int oplen = strlen(p->str);
448 if (len < oplen || memcmp(p->str, line, oplen))
450 if (p->fn(line + oplen, patch) < 0)
459 static int parse_num(const char *line, unsigned long *p)
465 *p = strtoul(line, &ptr, 10);
469 static int parse_range(const char *line, int len, int offset, const char *expect,
470 unsigned long *p1, unsigned long *p2)
474 if (offset < 0 || offset >= len)
479 digits = parse_num(line, p1);
489 digits = parse_num(line+1, p2);
501 if (memcmp(line, expect, ex))
508 * Parse a unified diff fragment header of the
509 * form "@@ -a,b +c,d @@"
511 static int parse_fragment_header(char *line, int len, struct fragment *fragment)
515 if (!len || line[len-1] != '\n')
518 /* Figure out the number of lines in a fragment */
519 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
520 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
525 static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
527 unsigned long offset, len;
529 patch->is_rename = patch->is_copy = 0;
530 patch->is_new = patch->is_delete = -1;
531 patch->old_mode = patch->new_mode = 0;
532 patch->old_name = patch->new_name = NULL;
533 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
534 unsigned long nextlen;
536 len = linelen(line, size);
540 /* Testing this early allows us to take a few shortcuts.. */
545 * Make sure we don't find any unconnected patch fragmants.
546 * That's a sign that we didn't find a header, and that a
547 * patch has become corrupted/broken up.
549 if (!memcmp("@@ -", line, 4)) {
550 struct fragment dummy;
551 if (parse_fragment_header(line, len, &dummy) < 0)
553 error("patch fragment without header at line %d: %.*s", linenr, len-1, line);
560 * Git patch? It might not have a real patch, just a rename
561 * or mode change, so we handle that specially
563 if (!memcmp("diff --git ", line, 11)) {
564 int git_hdr_len = parse_git_header(line, len, size, patch);
567 if (!patch->old_name && !patch->new_name)
568 die("git diff header lacks filename information");
569 *hdrsize = git_hdr_len;
573 /** --- followed by +++ ? */
574 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
578 * We only accept unified patches, so we want it to
579 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
582 nextlen = linelen(line + len, size - len);
583 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
586 /* Ok, we'll consider it a patch */
587 parse_traditional_patch(line, line+len, patch);
588 *hdrsize = len + nextlen;
596 * Parse a unified diff. Note that this really needs
597 * to parse each fragment separately, since the only
598 * way to know the difference between a "---" that is
599 * part of a patch, and a "---" that starts the next
600 * patch is to look at the line counts..
602 static int parse_fragment(char *line, unsigned long size, struct patch *patch, struct fragment *fragment)
605 int len = linelen(line, size), offset;
606 unsigned long pos[4], oldlines, newlines;
608 offset = parse_fragment_header(line, len, fragment);
611 oldlines = fragment->oldlines;
612 newlines = fragment->newlines;
614 if (patch->is_new < 0 && (pos[0] || oldlines))
616 if (patch->is_delete < 0 && (pos[1] || newlines))
617 patch->is_delete = 0;
619 /* Parse the thing.. */
624 for (offset = len; size > 0; offset += len, size -= len, line += len, linenr++) {
625 if (!oldlines && !newlines)
627 len = linelen(line, size);
628 if (!len || line[len-1] != '\n')
645 /* We allow "\ No newline at end of file" */
650 patch->lines_added += added;
651 patch->lines_deleted += deleted;
655 static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
657 unsigned long offset = 0;
658 struct fragment **fragp = &patch->fragments;
660 while (size > 4 && !memcmp(line, "@@ -", 4)) {
661 struct fragment *fragment;
664 fragment = xmalloc(sizeof(*fragment));
665 memset(fragment, 0, sizeof(*fragment));
666 len = parse_fragment(line, size, patch, fragment);
668 die("corrupt patch at line %d", linenr);
670 fragment->patch = line;
671 fragment->size = len;
674 fragp = &fragment->next;
683 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
685 int hdrsize, patchsize;
686 int offset = find_header(buffer, size, &hdrsize, patch);
691 patchsize = parse_single_patch(buffer + offset + hdrsize, size - offset - hdrsize, patch);
693 return offset + hdrsize + patchsize;
696 const char pluses[] = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
697 const char minuses[]= "----------------------------------------------------------------------";
699 static void show_stats(struct patch *patch)
701 char *name = patch->old_name;
702 int len, max, add, del, total;
705 name = patch->new_name;
708 * "scale" the filename
719 * scale the add/delete
725 add = patch->lines_added;
726 del = patch->lines_deleted;
729 total = (total * max + max_change / 2) / max_change;
730 add = (add * max + max_change / 2) / max_change;
732 printf(" %-*s |%5d %.*s%.*s\n",
733 len, name, patch->lines_added + patch->lines_deleted,
734 add, pluses, del, minuses);
737 static int check_patch(struct patch *patch)
740 const char *old_name = patch->old_name;
741 const char *new_name = patch->new_name;
744 int pos = cache_name_pos(old_name, strlen(old_name));
748 return error("%s: does not exist in index", old_name);
749 if (patch->is_new < 0)
751 if (lstat(old_name, &st) < 0)
752 return error("%s: %s\n", strerror(errno));
753 changed = ce_match_stat(active_cache[pos], &st);
755 return error("%s: does not match index", old_name);
756 if (!patch->old_mode)
757 patch->old_mode = st.st_mode;
760 if (new_name && (patch->is_new | patch->is_rename | patch->is_copy)) {
761 if (cache_name_pos(new_name, strlen(new_name)) >= 0)
762 return error("%s: already exists in index", new_name);
763 if (!lstat(new_name, &st))
764 return error("%s: already exists in working directory", new_name);
766 return error("%s: %s", new_name, strerror(errno));
771 static int check_patch_list(struct patch *patch)
775 for (;patch ; patch = patch->next)
776 error |= check_patch(patch);
780 static void show_file(int c, unsigned int mode, const char *name)
782 printf("%c %o %s\n", c, mode, name);
785 static void show_file_list(struct patch *patch)
787 for (;patch ; patch = patch->next) {
788 if (patch->is_rename) {
789 show_file('-', patch->old_mode, patch->old_name);
790 show_file('+', patch->new_mode, patch->new_name);
793 if (patch->is_copy || patch->is_new) {
794 show_file('+', patch->new_mode, patch->new_name);
797 if (patch->is_delete) {
798 show_file('-', patch->old_mode, patch->old_name);
801 if (patch->old_mode && patch->new_mode && patch->old_mode != patch->new_mode) {
802 printf("M %o:%o %s\n", patch->old_mode, patch->new_mode, patch->old_name);
805 printf("M %o %s\n", patch->old_mode, patch->old_name);
809 static void stat_patch_list(struct patch *patch)
811 int files, adds, dels;
813 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
815 adds += patch->lines_added;
816 dels += patch->lines_deleted;
820 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
823 static void patch_stats(struct patch *patch)
825 int lines = patch->lines_added + patch->lines_deleted;
827 if (lines > max_change)
829 if (patch->old_name) {
830 int len = strlen(patch->old_name);
834 if (patch->new_name) {
835 int len = strlen(patch->new_name);
841 static int apply_patch(int fd)
843 unsigned long offset, size;
844 char *buffer = read_patch_file(fd, &size);
845 struct patch *list = NULL, **listp = &list;
854 patch = xmalloc(sizeof(*patch));
855 memset(patch, 0, sizeof(*patch));
856 nr = parse_chunk(buffer + offset, size, patch);
861 listp = &patch->next;
866 if ((check || apply) && check_patch_list(list) < 0)
870 show_file_list(list);
873 stat_patch_list(list);
879 int main(int argc, char **argv)
884 if (read_cache() < 0)
885 die("unable to read index file");
887 for (i = 1; i < argc; i++) {
888 const char *arg = argv[i];
891 if (!strcmp(arg, "-")) {
896 if (!strcmp(arg, "--no-merge")) {
900 if (!strcmp(arg, "--stat")) {
905 if (!strcmp(arg, "--check")) {
910 if (!strcmp(arg, "--show-files")) {
914 fd = open(arg, O_RDONLY);