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
21 static int merge_patch = 1;
22 static int diffstat = 0;
24 static const char apply_usage[] = "git-apply <patch>";
27 * For "diff-stat" like behaviour, we keep track of the biggest change
28 * we've seen, and the longest filename. That allows us to do simple
31 static int max_change, max_len;
34 * Various "current state", notably line numbers and what
35 * file (and how) we're patching right now.. The "is_xxxx"
36 * things are flags, where -1 means "don't know yet".
38 static int linenr = 1;
39 static char *def_name = NULL;
42 unsigned long oldpos, oldlines;
43 unsigned long newpos, newlines;
46 struct fragment *next;
50 char *new_name, *old_name;
51 unsigned int old_mode, new_mode;
52 int is_rename, is_copy, is_new, is_delete;
53 int lines_added, lines_deleted;
54 struct fragment *fragments;
58 #define CHUNKSIZE (8192)
61 static void *read_patch_file(int fd, unsigned long *sizep)
63 unsigned long size = 0, alloc = CHUNKSIZE;
64 void *buffer = xmalloc(alloc);
67 int nr = alloc - size;
70 buffer = xrealloc(buffer, alloc);
73 nr = read(fd, buffer + size, nr);
79 die("git-apply: read returned %s", strerror(errno));
86 * Make sure that we have some slop in the buffer
87 * so that we can do speculative "memcmp" etc, and
88 * see to it that it is NUL-filled.
90 if (alloc < size + SLOP)
91 buffer = xrealloc(buffer, size + SLOP);
92 memset(buffer + size, 0, SLOP);
96 static unsigned long linelen(char *buffer, unsigned long size)
98 unsigned long len = 0;
101 if (*buffer++ == '\n')
107 static int is_dev_null(const char *str)
109 return !memcmp("/dev/null", str, 9) && isspace(str[9]);
116 static int name_terminate(const char *name, int namelen, int c, int terminate)
118 if (c == ' ' && !(terminate & TERM_SPACE))
120 if (c == '\t' && !(terminate & TERM_TAB))
124 * Do we want an existing name? Return false and
125 * continue if it's not there.
127 if (terminate & TERM_EXIST)
128 return cache_name_pos(name, namelen) >= 0;
133 static char * find_name(const char *line, char *def, int p_value, int terminate)
136 const char *start = line;
145 if (name_terminate(start, line-start, c, terminate))
149 if (c == '/' && !--p_value)
159 * Generally we prefer the shorter name, especially
160 * if the other one is just a variation of that with
161 * something else tacked on to the end (ie "file.orig"
165 int deflen = strlen(def);
166 if (deflen < len && !strncmp(start, def, deflen))
170 name = xmalloc(len + 1);
171 memcpy(name, start, len);
178 * Get the name etc info from the --/+++ lines of a traditional patch header
180 * NOTE! This hardcodes "-p1" behaviour in filename detection.
182 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
183 * files, we can happily check the index for a match, but for creating a
184 * new file we should try to match whatever "patch" does. I have no idea.
186 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
191 first += 4; // skip "--- "
192 second += 4; // skip "+++ "
193 if (is_dev_null(first)) {
195 patch->is_delete = 0;
196 name = find_name(second, def_name, p_value, TERM_SPACE | TERM_TAB);
197 patch->new_name = name;
198 } else if (is_dev_null(second)) {
200 patch->is_delete = 1;
201 name = find_name(first, def_name, p_value, TERM_EXIST | TERM_SPACE | TERM_TAB);
202 patch->old_name = name;
204 name = find_name(first, def_name, p_value, TERM_EXIST | TERM_SPACE | TERM_TAB);
205 name = find_name(second, name, p_value, TERM_EXIST | TERM_SPACE | TERM_TAB);
206 patch->old_name = patch->new_name = name;
209 die("unable to find filename in patch at line %d", linenr);
212 static int gitdiff_hdrend(const char *line, struct patch *patch)
218 * We're anal about diff header consistency, to make
219 * sure that we don't end up having strange ambiguous
220 * patches floating around.
222 * As a result, gitdiff_{old|new}name() will check
223 * their names against any previous information, just
226 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
231 if (!orig_name && !isnull)
232 return find_name(line, NULL, 1, 0);
240 die("git-apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
253 if (memcmp(line, name, len) || line[len] != '\n')
257 die("git-apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
261 static int gitdiff_oldname(const char *line, struct patch *patch)
263 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
267 static int gitdiff_newname(const char *line, struct patch *patch)
269 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
273 static int gitdiff_oldmode(const char *line, struct patch *patch)
275 patch->old_mode = strtoul(line, NULL, 8);
279 static int gitdiff_newmode(const char *line, struct patch *patch)
281 patch->new_mode = strtoul(line, NULL, 8);
285 static int gitdiff_delete(const char *line, struct patch *patch)
287 patch->is_delete = 1;
288 return gitdiff_oldmode(line, patch);
291 static int gitdiff_newfile(const char *line, struct patch *patch)
294 return gitdiff_newmode(line, patch);
297 static int gitdiff_copysrc(const char *line, struct patch *patch)
300 patch->old_name = find_name(line, NULL, 0, 0);
304 static int gitdiff_copydst(const char *line, struct patch *patch)
307 patch->new_name = find_name(line, NULL, 0, 0);
311 static int gitdiff_renamesrc(const char *line, struct patch *patch)
313 patch->is_rename = 1;
314 patch->old_name = find_name(line, NULL, 0, 0);
318 static int gitdiff_renamedst(const char *line, struct patch *patch)
320 patch->is_rename = 1;
321 patch->new_name = find_name(line, NULL, 0, 0);
325 static int gitdiff_similarity(const char *line, struct patch *patch)
331 * This is normal for a diff that doesn't change anything: we'll fall through
332 * into the next diff. Tell the parser to break out.
334 static int gitdiff_unrecognized(const char *line, struct patch *patch)
339 /* Verify that we recognize the lines following a git header */
340 static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
342 unsigned long offset;
344 /* A git diff has explicit new/delete information, so we don't guess */
346 patch->is_delete = 0;
351 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
352 static const struct opentry {
354 int (*fn)(const char *, struct patch *);
356 { "@@ -", gitdiff_hdrend },
357 { "--- ", gitdiff_oldname },
358 { "+++ ", gitdiff_newname },
359 { "old mode ", gitdiff_oldmode },
360 { "new mode ", gitdiff_newmode },
361 { "deleted file mode ", gitdiff_delete },
362 { "new file mode ", gitdiff_newfile },
363 { "copy from ", gitdiff_copysrc },
364 { "copy to ", gitdiff_copydst },
365 { "rename from ", gitdiff_renamesrc },
366 { "rename to ", gitdiff_renamedst },
367 { "similarity index ", gitdiff_similarity },
368 { "", gitdiff_unrecognized },
372 len = linelen(line, size);
373 if (!len || line[len-1] != '\n')
375 for (i = 0; i < sizeof(optable) / sizeof(optable[0]); i++) {
376 const struct opentry *p = optable + i;
377 int oplen = strlen(p->str);
378 if (len < oplen || memcmp(p->str, line, oplen))
380 if (p->fn(line + oplen, patch) < 0)
389 static int parse_num(const char *line, unsigned long *p)
395 *p = strtoul(line, &ptr, 10);
399 static int parse_range(const char *line, int len, int offset, const char *expect,
400 unsigned long *p1, unsigned long *p2)
404 if (offset < 0 || offset >= len)
409 digits = parse_num(line, p1);
419 digits = parse_num(line+1, p2);
431 if (memcmp(line, expect, ex))
438 * Parse a unified diff fragment header of the
439 * form "@@ -a,b +c,d @@"
441 static int parse_fragment_header(char *line, int len, struct fragment *fragment)
445 if (!len || line[len-1] != '\n')
448 /* Figure out the number of lines in a fragment */
449 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
450 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
455 static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
457 unsigned long offset, len;
459 patch->is_rename = patch->is_copy = 0;
460 patch->is_new = patch->is_delete = -1;
461 patch->old_mode = patch->new_mode = 0;
462 patch->old_name = patch->new_name = NULL;
463 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
464 unsigned long nextlen;
466 len = linelen(line, size);
470 /* Testing this early allows us to take a few shortcuts.. */
475 * Make sure we don't find any unconnected patch fragmants.
476 * That's a sign that we didn't find a header, and that a
477 * patch has become corrupted/broken up.
479 if (!memcmp("@@ -", line, 4)) {
480 struct fragment dummy;
481 if (parse_fragment_header(line, len, &dummy) < 0)
483 error("patch fragment without header at line %d: %.*s", linenr, len-1, line);
490 * Git patch? It might not have a real patch, just a rename
491 * or mode change, so we handle that specially
493 if (!memcmp("diff --git ", line, 11)) {
494 int git_hdr_len = parse_git_header(line, len, size, patch);
498 *hdrsize = git_hdr_len;
502 /** --- followed by +++ ? */
503 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
507 * We only accept unified patches, so we want it to
508 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
511 nextlen = linelen(line + len, size - len);
512 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
515 /* Ok, we'll consider it a patch */
516 parse_traditional_patch(line, line+len, patch);
517 *hdrsize = len + nextlen;
525 * Parse a unified diff. Note that this really needs
526 * to parse each fragment separately, since the only
527 * way to know the difference between a "---" that is
528 * part of a patch, and a "---" that starts the next
529 * patch is to look at the line counts..
531 static int parse_fragment(char *line, unsigned long size, struct patch *patch, struct fragment *fragment)
534 int len = linelen(line, size), offset;
535 unsigned long pos[4], oldlines, newlines;
537 offset = parse_fragment_header(line, len, fragment);
540 oldlines = fragment->oldlines;
541 newlines = fragment->newlines;
543 if (patch->is_new < 0 && (pos[0] || oldlines))
545 if (patch->is_delete < 0 && (pos[1] || newlines))
546 patch->is_delete = 0;
548 /* Parse the thing.. */
553 for (offset = len; size > 0; offset += len, size -= len, line += len, linenr++) {
554 if (!oldlines && !newlines)
556 len = linelen(line, size);
557 if (!len || line[len-1] != '\n')
574 /* We allow "\ No newline at end of file" */
579 patch->lines_added += added;
580 patch->lines_deleted += deleted;
584 static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
586 unsigned long offset = 0;
587 struct fragment **fragp = &patch->fragments;
589 while (size > 4 && !memcmp(line, "@@ -", 4)) {
590 struct fragment *fragment;
593 fragment = xmalloc(sizeof(*fragment));
594 memset(fragment, 0, sizeof(*fragment));
595 len = parse_fragment(line, size, patch, fragment);
597 die("corrupt patch at line %d", linenr);
599 fragment->patch = line;
600 fragment->size = len;
603 fragp = &fragment->next;
612 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
614 int hdrsize, patchsize;
615 int offset = find_header(buffer, size, &hdrsize, patch);
620 patchsize = parse_single_patch(buffer + offset + hdrsize, size - offset - hdrsize, patch);
622 return offset + hdrsize + patchsize;
625 const char pluses[] = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
626 const char minuses[]= "----------------------------------------------------------------------";
628 static void show_stats(struct patch *patch)
630 char *name = patch->old_name;
631 int len, max, add, del;
634 name = patch->new_name;
640 * "scale" the filename
651 * scale the add/delete
657 add = (patch->lines_added * max + max_change/2) / max_change;
658 del = (patch->lines_deleted * max + max_change/2) / max_change;
659 printf(" %-*s |%5d %.*s%.*s\n",
660 len, name, patch->lines_added + patch->lines_deleted,
661 add, pluses, del, minuses);
664 static void check_patch(struct patch *patch)
666 const char *old_name = patch->old_name;
667 const char *new_name = patch->new_name;
670 if (cache_name_pos(old_name, strlen(old_name)) < 0)
671 die("file %s does not exist", old_name);
672 if (patch->is_new < 0)
675 if (new_name && (patch->is_new | patch->is_rename | patch->is_copy)) {
676 if (cache_name_pos(new_name, strlen(new_name)) >= 0)
677 die("file %s already exists", new_name);
681 static void apply_patch_list(struct patch *patch)
683 int files, adds, dels;
685 files = adds = dels = 0;
687 die("no patch found");
694 adds += patch->lines_added;
695 dels += patch->lines_deleted;
698 } while ((patch = patch->next) != NULL);
701 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
704 static void patch_stats(struct patch *patch)
706 int lines = patch->lines_added + patch->lines_deleted;
708 if (lines > max_change)
710 if (patch->old_name) {
711 int len = strlen(patch->old_name);
715 if (patch->new_name) {
716 int len = strlen(patch->new_name);
722 static int apply_patch(int fd)
724 unsigned long offset, size;
725 char *buffer = read_patch_file(fd, &size);
726 struct patch *list = NULL, **listp = &list;
735 patch = xmalloc(sizeof(*patch));
736 memset(patch, 0, sizeof(*patch));
737 nr = parse_chunk(buffer + offset, size, patch);
742 listp = &patch->next;
747 apply_patch_list(list);
753 int main(int argc, char **argv)
758 if (read_cache() < 0)
759 die("unable to read index file");
761 for (i = 1; i < argc; i++) {
762 const char *arg = argv[i];
765 if (!strcmp(arg, "-")) {
770 if (!strcmp(arg, "--no-merge")) {
774 if (!strcmp(arg, "--stat")) {
779 fd = open(arg, O_RDONLY);