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 const char apply_usage[] = "git-apply <patch>";
25 * For "diff-stat" like behaviour, we keep track of the biggest change
26 * we've seen, and the longest filename. That allows us to do simple
29 static int max_change, max_len;
32 * Various "current state", notably line numbers and what
33 * file (and how) we're patching right now.. The "is_xxxx"
34 * things are flags, where -1 means "don't know yet".
36 static int linenr = 1;
37 static char *def_name = NULL;
40 unsigned long oldpos, oldlines;
41 unsigned long newpos, newlines;
44 struct fragment *next;
48 char *new_name, *old_name;
49 unsigned int old_mode, new_mode;
50 int is_rename, is_copy, is_new, is_delete;
51 int lines_added, lines_deleted;
52 struct fragment *fragments;
56 #define CHUNKSIZE (8192)
59 static void *read_patch_file(int fd, unsigned long *sizep)
61 unsigned long size = 0, alloc = CHUNKSIZE;
62 void *buffer = xmalloc(alloc);
65 int nr = alloc - size;
68 buffer = xrealloc(buffer, alloc);
71 nr = read(fd, buffer + size, nr);
77 die("git-apply: read returned %s", strerror(errno));
84 * Make sure that we have some slop in the buffer
85 * so that we can do speculative "memcmp" etc, and
86 * see to it that it is NUL-filled.
88 if (alloc < size + SLOP)
89 buffer = xrealloc(buffer, size + SLOP);
90 memset(buffer + size, 0, SLOP);
94 static unsigned long linelen(char *buffer, unsigned long size)
96 unsigned long len = 0;
99 if (*buffer++ == '\n')
105 static int is_dev_null(const char *str)
107 return !memcmp("/dev/null", str, 9) && isspace(str[9]);
114 static int name_terminate(const char *name, int namelen, int c, int terminate)
116 if (c == ' ' && !(terminate & TERM_SPACE))
118 if (c == '\t' && !(terminate & TERM_TAB))
122 * Do we want an existing name? Return false and
123 * continue if it's not there.
125 if (terminate & TERM_EXIST)
126 return cache_name_pos(name, namelen) >= 0;
131 static char * find_name(const char *line, char *def, int p_value, int terminate)
134 const char *start = line;
143 if (name_terminate(start, line-start, c, terminate))
147 if (c == '/' && !--p_value)
157 * Generally we prefer the shorter name, especially
158 * if the other one is just a variation of that with
159 * something else tacked on to the end (ie "file.orig"
163 int deflen = strlen(def);
164 if (deflen < len && !strncmp(start, def, deflen))
168 name = xmalloc(len + 1);
169 memcpy(name, start, len);
176 * Get the name etc info from the --/+++ lines of a traditional patch header
178 * NOTE! This hardcodes "-p1" behaviour in filename detection.
180 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
181 * files, we can happily check the index for a match, but for creating a
182 * new file we should try to match whatever "patch" does. I have no idea.
184 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
189 first += 4; // skip "--- "
190 second += 4; // skip "+++ "
191 if (is_dev_null(first)) {
193 patch->is_delete = 0;
194 name = find_name(second, def_name, p_value, TERM_SPACE | TERM_TAB);
195 patch->new_name = name;
196 } else if (is_dev_null(second)) {
198 patch->is_delete = 1;
199 name = find_name(first, def_name, p_value, TERM_EXIST | TERM_SPACE | TERM_TAB);
200 patch->old_name = name;
202 name = find_name(first, def_name, p_value, TERM_EXIST | TERM_SPACE | TERM_TAB);
203 name = find_name(second, name, p_value, TERM_EXIST | TERM_SPACE | TERM_TAB);
204 patch->old_name = patch->new_name = name;
207 die("unable to find filename in patch at line %d", linenr);
210 static int gitdiff_hdrend(const char *line, struct patch *patch)
216 * We're anal about diff header consistency, to make
217 * sure that we don't end up having strange ambiguous
218 * patches floating around.
220 * As a result, gitdiff_{old|new}name() will check
221 * their names against any previous information, just
224 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
229 if (!orig_name && !isnull)
230 return find_name(line, NULL, 1, 0);
238 die("git-apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
251 if (memcmp(line, name, len) || line[len] != '\n')
255 die("git-apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
259 static int gitdiff_oldname(const char *line, struct patch *patch)
261 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
265 static int gitdiff_newname(const char *line, struct patch *patch)
267 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
271 static int gitdiff_oldmode(const char *line, struct patch *patch)
273 patch->old_mode = strtoul(line, NULL, 8);
277 static int gitdiff_newmode(const char *line, struct patch *patch)
279 patch->new_mode = strtoul(line, NULL, 8);
283 static int gitdiff_delete(const char *line, struct patch *patch)
285 patch->is_delete = 1;
286 return gitdiff_oldmode(line, patch);
289 static int gitdiff_newfile(const char *line, struct patch *patch)
292 return gitdiff_newmode(line, patch);
295 static int gitdiff_copysrc(const char *line, struct patch *patch)
298 patch->old_name = find_name(line, NULL, 0, 0);
302 static int gitdiff_copydst(const char *line, struct patch *patch)
305 patch->new_name = find_name(line, NULL, 0, 0);
309 static int gitdiff_renamesrc(const char *line, struct patch *patch)
311 patch->is_rename = 1;
312 patch->old_name = find_name(line, NULL, 0, 0);
316 static int gitdiff_renamedst(const char *line, struct patch *patch)
318 patch->is_rename = 1;
319 patch->new_name = find_name(line, NULL, 0, 0);
323 static int gitdiff_similarity(const char *line, struct patch *patch)
329 * This is normal for a diff that doesn't change anything: we'll fall through
330 * into the next diff. Tell the parser to break out.
332 static int gitdiff_unrecognized(const char *line, struct patch *patch)
337 /* Verify that we recognize the lines following a git header */
338 static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
340 unsigned long offset;
342 /* A git diff has explicit new/delete information, so we don't guess */
344 patch->is_delete = 0;
349 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
350 static const struct opentry {
352 int (*fn)(const char *, struct patch *);
354 { "@@ -", gitdiff_hdrend },
355 { "--- ", gitdiff_oldname },
356 { "+++ ", gitdiff_newname },
357 { "old mode ", gitdiff_oldmode },
358 { "new mode ", gitdiff_newmode },
359 { "deleted file mode ", gitdiff_delete },
360 { "new file mode ", gitdiff_newfile },
361 { "copy from ", gitdiff_copysrc },
362 { "copy to ", gitdiff_copydst },
363 { "rename from ", gitdiff_renamesrc },
364 { "rename to ", gitdiff_renamedst },
365 { "similarity index ", gitdiff_similarity },
366 { "", gitdiff_unrecognized },
370 len = linelen(line, size);
371 if (!len || line[len-1] != '\n')
373 for (i = 0; i < sizeof(optable) / sizeof(optable[0]); i++) {
374 const struct opentry *p = optable + i;
375 int oplen = strlen(p->str);
376 if (len < oplen || memcmp(p->str, line, oplen))
378 if (p->fn(line + oplen, patch) < 0)
387 static int parse_num(const char *line, int len, int offset, const char *expect, unsigned long *p)
392 if (offset < 0 || offset >= len)
399 *p = strtoul(line, &ptr, 10);
410 if (memcmp(line, expect, ex))
417 * Parse a unified diff fragment header of the
418 * form "@@ -a,b +c,d @@"
420 static int parse_fragment_header(char *line, int len, struct fragment *fragment)
424 if (!len || line[len-1] != '\n')
427 /* Figure out the number of lines in a fragment */
428 offset = parse_num(line, len, 4, ",", &fragment->oldpos);
429 offset = parse_num(line, len, offset, " +", &fragment->oldlines);
430 offset = parse_num(line, len, offset, ",", &fragment->newpos);
431 offset = parse_num(line, len, offset, " @@", &fragment->newlines);
436 static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
438 unsigned long offset, len;
440 patch->is_rename = patch->is_copy = 0;
441 patch->is_new = patch->is_delete = -1;
442 patch->old_mode = patch->new_mode = 0;
443 patch->old_name = patch->new_name = NULL;
444 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
445 unsigned long nextlen;
447 len = linelen(line, size);
451 /* Testing this early allows us to take a few shortcuts.. */
456 * Make sure we don't find any unconnected patch fragmants.
457 * That's a sign that we didn't find a header, and that a
458 * patch has become corrupted/broken up.
460 if (!memcmp("@@ -", line, 4)) {
461 struct fragment dummy;
462 if (parse_fragment_header(line, len, &dummy) < 0)
464 error("patch fragment without header at line %d: %.*s", linenr, len-1, line);
471 * Git patch? It might not have a real patch, just a rename
472 * or mode change, so we handle that specially
474 if (!memcmp("diff --git ", line, 11)) {
475 int git_hdr_len = parse_git_header(line, len, size, patch);
479 *hdrsize = git_hdr_len;
483 /** --- followed by +++ ? */
484 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
488 * We only accept unified patches, so we want it to
489 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
492 nextlen = linelen(line + len, size - len);
493 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
496 /* Ok, we'll consider it a patch */
497 parse_traditional_patch(line, line+len, patch);
498 *hdrsize = len + nextlen;
506 * Parse a unified diff. Note that this really needs
507 * to parse each fragment separately, since the only
508 * way to know the difference between a "---" that is
509 * part of a patch, and a "---" that starts the next
510 * patch is to look at the line counts..
512 static int parse_fragment(char *line, unsigned long size, struct patch *patch, struct fragment *fragment)
515 int len = linelen(line, size), offset;
516 unsigned long pos[4], oldlines, newlines;
518 offset = parse_fragment_header(line, len, fragment);
521 oldlines = fragment->oldlines;
522 newlines = fragment->newlines;
524 if (patch->is_new < 0 && (pos[0] || oldlines))
526 if (patch->is_delete < 0 && (pos[1] || newlines))
527 patch->is_delete = 0;
529 /* Parse the thing.. */
534 for (offset = len; size > 0; offset += len, size -= len, line += len, linenr++) {
535 if (!oldlines && !newlines)
537 len = linelen(line, size);
538 if (!len || line[len-1] != '\n')
557 patch->lines_added += added;
558 patch->lines_deleted += deleted;
562 static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
564 unsigned long offset = 0;
565 struct fragment **fragp = &patch->fragments;
567 while (size > 4 && !memcmp(line, "@@ -", 4)) {
568 struct fragment *fragment;
571 fragment = xmalloc(sizeof(*fragment));
572 memset(fragment, 0, sizeof(*fragment));
573 len = parse_fragment(line, size, patch, fragment);
575 die("corrupt patch at line %d", linenr);
577 fragment->patch = line;
578 fragment->size = len;
581 fragp = &fragment->next;
590 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
592 int hdrsize, patchsize;
593 int offset = find_header(buffer, size, &hdrsize, patch);
598 patchsize = parse_single_patch(buffer + offset + hdrsize, size - offset - hdrsize, patch);
600 return offset + hdrsize + patchsize;
603 const char pluses[] = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
604 const char minuses[]= "----------------------------------------------------------------------";
606 static void show_stats(struct patch *patch)
608 char *name = patch->old_name;
609 int len, max, add, del;
612 name = patch->new_name;
615 * "scale" the filename
626 * scale the add/delete
632 add = (patch->lines_added * max + max_change/2) / max_change;
633 del = (patch->lines_deleted * max + max_change/2) / max_change;
634 printf(" %-*s |%5d %.*s%.*s\n",
635 len, name, patch->lines_added + patch->lines_deleted,
636 add, pluses, del, minuses);
639 static void apply_patch_list(struct patch *patch)
641 int files, adds, dels;
643 files = adds = dels = 0;
645 die("no patch found");
647 const char *old_name = patch->old_name;
648 const char *new_name = patch->new_name;
651 if (cache_name_pos(old_name, strlen(old_name)) < 0)
652 die("file %s does not exist", old_name);
653 if (patch->is_new < 0)
656 if (new_name && (patch->is_new | patch->is_rename | patch->is_copy)) {
657 if (cache_name_pos(new_name, strlen(new_name)) >= 0)
658 die("file %s already exists", new_name);
662 adds += patch->lines_added;
663 dels += patch->lines_deleted;
665 } while ((patch = patch->next) != NULL);
666 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
669 static void patch_stats(struct patch *patch)
671 int lines = patch->lines_added + patch->lines_deleted;
673 if (lines > max_change)
675 if (patch->old_name) {
676 int len = strlen(patch->old_name);
680 if (patch->new_name) {
681 int len = strlen(patch->new_name);
687 static int apply_patch(int fd)
689 unsigned long offset, size;
690 char *buffer = read_patch_file(fd, &size);
691 struct patch *list = NULL, **listp = &list;
700 patch = xmalloc(sizeof(*patch));
701 memset(patch, 0, sizeof(*patch));
702 nr = parse_chunk(buffer + offset, size, patch);
707 listp = &patch->next;
712 apply_patch_list(list);
718 int main(int argc, char **argv)
723 if (read_cache() < 0)
724 die("unable to read index file");
726 for (i = 1; i < argc; i++) {
727 const char *arg = argv[i];
730 if (!strcmp(arg, "-")) {
735 if (!strcmp(arg, "--no-merge")) {
739 fd = open(arg, O_RDONLY);