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.
20 // We default to the merge behaviour, since that's what most people would
23 // --check turns on checking that the working tree matches the
24 // files that are being modified, but doesn't apply the patch
25 // --stat does just a diffstat, and doesn't actually apply
26 // --show-files shows the directory changes
28 static int merge_patch = 1;
29 static int check_index = 0;
30 static int write_index = 0;
31 static int diffstat = 0;
32 static int summary = 0;
35 static int show_files = 0;
36 static const char apply_usage[] =
37 "git-apply [--no-merge] [--stat] [--summary] [--check] [--index] [--apply] [--show-files] <patch>...";
40 * For "diff-stat" like behaviour, we keep track of the biggest change
41 * we've seen, and the longest filename. That allows us to do simple
44 static int max_change, max_len;
47 * Various "current state", notably line numbers and what
48 * file (and how) we're patching right now.. The "is_xxxx"
49 * things are flags, where -1 means "don't know yet".
51 static int linenr = 1;
54 unsigned long oldpos, oldlines;
55 unsigned long newpos, newlines;
58 struct fragment *next;
62 char *new_name, *old_name, *def_name;
63 unsigned int old_mode, new_mode;
64 int is_rename, is_copy, is_new, is_delete;
65 int lines_added, lines_deleted;
67 struct fragment *fragments;
69 unsigned long resultsize;
73 #define CHUNKSIZE (8192)
76 static void *read_patch_file(int fd, unsigned long *sizep)
78 unsigned long size = 0, alloc = CHUNKSIZE;
79 void *buffer = xmalloc(alloc);
82 int nr = alloc - size;
85 buffer = xrealloc(buffer, alloc);
88 nr = read(fd, buffer + size, nr);
94 die("git-apply: read returned %s", strerror(errno));
101 * Make sure that we have some slop in the buffer
102 * so that we can do speculative "memcmp" etc, and
103 * see to it that it is NUL-filled.
105 if (alloc < size + SLOP)
106 buffer = xrealloc(buffer, size + SLOP);
107 memset(buffer + size, 0, SLOP);
111 static unsigned long linelen(const char *buffer, unsigned long size)
113 unsigned long len = 0;
116 if (*buffer++ == '\n')
122 static int is_dev_null(const char *str)
124 return !memcmp("/dev/null", str, 9) && isspace(str[9]);
130 static int name_terminate(const char *name, int namelen, int c, int terminate)
132 if (c == ' ' && !(terminate & TERM_SPACE))
134 if (c == '\t' && !(terminate & TERM_TAB))
140 static char * find_name(const char *line, char *def, int p_value, int terminate)
143 const char *start = line;
147 /* Proposed "new-style" GNU patch/diff format; see
148 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
150 name = unquote_c_style(line, NULL);
154 cp = strchr(name, '/');
161 /* name can later be freed, so we need
162 * to memmove, not just return cp
164 memmove(name, cp, strlen(cp) + 1);
181 if (name_terminate(start, line-start, c, terminate))
185 if (c == '/' && !--p_value)
195 * Generally we prefer the shorter name, especially
196 * if the other one is just a variation of that with
197 * something else tacked on to the end (ie "file.orig"
201 int deflen = strlen(def);
202 if (deflen < len && !strncmp(start, def, deflen))
206 name = xmalloc(len + 1);
207 memcpy(name, start, len);
214 * Get the name etc info from the --/+++ lines of a traditional patch header
216 * NOTE! This hardcodes "-p1" behaviour in filename detection.
218 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
219 * files, we can happily check the index for a match, but for creating a
220 * new file we should try to match whatever "patch" does. I have no idea.
222 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
227 first += 4; // skip "--- "
228 second += 4; // skip "+++ "
229 if (is_dev_null(first)) {
231 patch->is_delete = 0;
232 name = find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB);
233 patch->new_name = name;
234 } else if (is_dev_null(second)) {
236 patch->is_delete = 1;
237 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
238 patch->old_name = name;
240 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
241 name = find_name(second, name, p_value, TERM_SPACE | TERM_TAB);
242 patch->old_name = patch->new_name = name;
245 die("unable to find filename in patch at line %d", linenr);
248 static int gitdiff_hdrend(const char *line, struct patch *patch)
254 * We're anal about diff header consistency, to make
255 * sure that we don't end up having strange ambiguous
256 * patches floating around.
258 * As a result, gitdiff_{old|new}name() will check
259 * their names against any previous information, just
262 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
264 if (!orig_name && !isnull)
265 return find_name(line, NULL, 1, 0);
274 die("git-apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
275 another = find_name(line, NULL, 1, 0);
276 if (!another || memcmp(another, name, len))
277 die("git-apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
282 /* expect "/dev/null" */
283 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
284 die("git-apply: bad git-diff - expected /dev/null on line %d", linenr);
289 static int gitdiff_oldname(const char *line, struct patch *patch)
291 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
295 static int gitdiff_newname(const char *line, struct patch *patch)
297 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
301 static int gitdiff_oldmode(const char *line, struct patch *patch)
303 patch->old_mode = strtoul(line, NULL, 8);
307 static int gitdiff_newmode(const char *line, struct patch *patch)
309 patch->new_mode = strtoul(line, NULL, 8);
313 static int gitdiff_delete(const char *line, struct patch *patch)
315 patch->is_delete = 1;
316 patch->old_name = patch->def_name;
317 return gitdiff_oldmode(line, patch);
320 static int gitdiff_newfile(const char *line, struct patch *patch)
323 patch->new_name = patch->def_name;
324 return gitdiff_newmode(line, patch);
327 static int gitdiff_copysrc(const char *line, struct patch *patch)
330 patch->old_name = find_name(line, NULL, 0, 0);
334 static int gitdiff_copydst(const char *line, struct patch *patch)
337 patch->new_name = find_name(line, NULL, 0, 0);
341 static int gitdiff_renamesrc(const char *line, struct patch *patch)
343 patch->is_rename = 1;
344 patch->old_name = find_name(line, NULL, 0, 0);
348 static int gitdiff_renamedst(const char *line, struct patch *patch)
350 patch->is_rename = 1;
351 patch->new_name = find_name(line, NULL, 0, 0);
355 static int gitdiff_similarity(const char *line, struct patch *patch)
357 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
362 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
364 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
370 * This is normal for a diff that doesn't change anything: we'll fall through
371 * into the next diff. Tell the parser to break out.
373 static int gitdiff_unrecognized(const char *line, struct patch *patch)
378 static const char *stop_at_slash(const char *line, int llen)
382 for (i = 0; i < llen; i++) {
390 /* This is to extract the same name that appears on "diff --git"
391 * line. We do not find and return anything if it is a rename
392 * patch, and it is OK because we will find the name elsewhere.
393 * We need to reliably find name only when it is mode-change only,
394 * creation or deletion of an empty file. In any of these cases,
395 * both sides are the same name under a/ and b/ respectively.
397 static char *git_header_name(char *line, int llen)
401 const char *second = NULL;
403 line += strlen("diff --git ");
404 llen -= strlen("diff --git ");
408 char *first = unquote_c_style(line, &second);
412 /* advance to the first slash */
413 cp = stop_at_slash(first, strlen(first));
414 if (!cp || cp == first) {
415 /* we do not accept absolute paths */
421 memmove(first, cp+1, len+1); /* including NUL */
423 /* second points at one past closing dq of name.
424 * find the second name.
426 while ((second < line + llen) && isspace(*second))
429 if (line + llen <= second)
430 goto free_first_and_fail;
431 if (*second == '"') {
432 char *sp = unquote_c_style(second, NULL);
434 goto free_first_and_fail;
435 cp = stop_at_slash(sp, strlen(sp));
436 if (!cp || cp == sp) {
439 goto free_first_and_fail;
441 /* They must match, otherwise ignore */
442 if (strcmp(cp+1, first))
443 goto free_both_and_fail;
448 /* unquoted second */
449 cp = stop_at_slash(second, line + llen - second);
450 if (!cp || cp == second)
451 goto free_first_and_fail;
453 if (line + llen - cp != len + 1 ||
454 memcmp(first, cp, len))
455 goto free_first_and_fail;
459 /* unquoted first name */
460 name = stop_at_slash(line, llen);
461 if (!name || name == line)
466 /* since the first name is unquoted, a dq if exists must be
467 * the beginning of the second name.
469 for (second = name; second < line + llen; second++) {
470 if (*second == '"') {
471 const char *cp = second;
473 char *sp = unquote_c_style(second, NULL);
477 np = stop_at_slash(sp, strlen(sp));
478 if (!np || np == sp) {
479 free_second_and_fail:
485 if (len < cp - name &&
486 !strncmp(np, name, len) &&
487 isspace(name[len])) {
489 memmove(sp, np, len + 1);
492 goto free_second_and_fail;
497 * Accept a name only if it shows up twice, exactly the same
500 for (len = 0 ; ; len++) {
517 if (second[len] == '\n' && !memcmp(name, second, len)) {
518 char *ret = xmalloc(len + 1);
519 memcpy(ret, name, len);
528 /* Verify that we recognize the lines following a git header */
529 static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
531 unsigned long offset;
533 /* A git diff has explicit new/delete information, so we don't guess */
535 patch->is_delete = 0;
538 * Some things may not have the old name in the
539 * rest of the headers anywhere (pure mode changes,
540 * or removing or adding empty files), so we get
541 * the default name from the header.
543 patch->def_name = git_header_name(line, len);
548 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
549 static const struct opentry {
551 int (*fn)(const char *, struct patch *);
553 { "@@ -", gitdiff_hdrend },
554 { "--- ", gitdiff_oldname },
555 { "+++ ", gitdiff_newname },
556 { "old mode ", gitdiff_oldmode },
557 { "new mode ", gitdiff_newmode },
558 { "deleted file mode ", gitdiff_delete },
559 { "new file mode ", gitdiff_newfile },
560 { "copy from ", gitdiff_copysrc },
561 { "copy to ", gitdiff_copydst },
562 { "rename old ", gitdiff_renamesrc },
563 { "rename new ", gitdiff_renamedst },
564 { "rename from ", gitdiff_renamesrc },
565 { "rename to ", gitdiff_renamedst },
566 { "similarity index ", gitdiff_similarity },
567 { "dissimilarity index ", gitdiff_dissimilarity },
568 { "", gitdiff_unrecognized },
572 len = linelen(line, size);
573 if (!len || line[len-1] != '\n')
575 for (i = 0; i < sizeof(optable) / sizeof(optable[0]); i++) {
576 const struct opentry *p = optable + i;
577 int oplen = strlen(p->str);
578 if (len < oplen || memcmp(p->str, line, oplen))
580 if (p->fn(line + oplen, patch) < 0)
589 static int parse_num(const char *line, unsigned long *p)
595 *p = strtoul(line, &ptr, 10);
599 static int parse_range(const char *line, int len, int offset, const char *expect,
600 unsigned long *p1, unsigned long *p2)
604 if (offset < 0 || offset >= len)
609 digits = parse_num(line, p1);
619 digits = parse_num(line+1, p2);
631 if (memcmp(line, expect, ex))
638 * Parse a unified diff fragment header of the
639 * form "@@ -a,b +c,d @@"
641 static int parse_fragment_header(char *line, int len, struct fragment *fragment)
645 if (!len || line[len-1] != '\n')
648 /* Figure out the number of lines in a fragment */
649 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
650 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
655 static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
657 unsigned long offset, len;
659 patch->is_rename = patch->is_copy = 0;
660 patch->is_new = patch->is_delete = -1;
661 patch->old_mode = patch->new_mode = 0;
662 patch->old_name = patch->new_name = NULL;
663 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
664 unsigned long nextlen;
666 len = linelen(line, size);
670 /* Testing this early allows us to take a few shortcuts.. */
675 * Make sure we don't find any unconnected patch fragmants.
676 * That's a sign that we didn't find a header, and that a
677 * patch has become corrupted/broken up.
679 if (!memcmp("@@ -", line, 4)) {
680 struct fragment dummy;
681 if (parse_fragment_header(line, len, &dummy) < 0)
683 error("patch fragment without header at line %d: %.*s", linenr, (int)len-1, line);
690 * Git patch? It might not have a real patch, just a rename
691 * or mode change, so we handle that specially
693 if (!memcmp("diff --git ", line, 11)) {
694 int git_hdr_len = parse_git_header(line, len, size, patch);
695 if (git_hdr_len <= len)
697 if (!patch->old_name && !patch->new_name) {
698 if (!patch->def_name)
699 die("git diff header lacks filename information (line %d)", linenr);
700 patch->old_name = patch->new_name = patch->def_name;
702 *hdrsize = git_hdr_len;
706 /** --- followed by +++ ? */
707 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
711 * We only accept unified patches, so we want it to
712 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
715 nextlen = linelen(line + len, size - len);
716 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
719 /* Ok, we'll consider it a patch */
720 parse_traditional_patch(line, line+len, patch);
721 *hdrsize = len + nextlen;
729 * Parse a unified diff. Note that this really needs
730 * to parse each fragment separately, since the only
731 * way to know the difference between a "---" that is
732 * part of a patch, and a "---" that starts the next
733 * patch is to look at the line counts..
735 static int parse_fragment(char *line, unsigned long size, struct patch *patch, struct fragment *fragment)
738 int len = linelen(line, size), offset;
739 unsigned long oldlines, newlines;
741 offset = parse_fragment_header(line, len, fragment);
744 oldlines = fragment->oldlines;
745 newlines = fragment->newlines;
747 if (patch->is_new < 0) {
748 patch->is_new = !oldlines;
750 patch->old_name = NULL;
752 if (patch->is_delete < 0) {
753 patch->is_delete = !newlines;
755 patch->new_name = NULL;
758 if (patch->is_new != !oldlines)
759 return error("new file depends on old contents");
760 if (patch->is_delete != !newlines) {
762 return error("deleted file still has contents");
763 fprintf(stderr, "** warning: file %s becomes empty but is not deleted\n", patch->new_name);
766 /* Parse the thing.. */
771 for (offset = len; size > 0; offset += len, size -= len, line += len, linenr++) {
772 if (!oldlines && !newlines)
774 len = linelen(line, size);
775 if (!len || line[len-1] != '\n')
793 /* We allow "\ No newline at end of file". Depending
794 * on locale settings when the patch was produced we
795 * don't know what this line looks like. The only
796 * thing we do know is that it begins with "\ ". */
798 if (len < 12 || memcmp(line, "\\ ", 2))
803 /* If a fragment ends with an incomplete line, we failed to include
804 * it in the above loop because we hit oldlines == newlines == 0
807 if (12 < size && !memcmp(line, "\\ ", 2))
808 offset += linelen(line, size);
810 patch->lines_added += added;
811 patch->lines_deleted += deleted;
815 static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
817 unsigned long offset = 0;
818 struct fragment **fragp = &patch->fragments;
820 while (size > 4 && !memcmp(line, "@@ -", 4)) {
821 struct fragment *fragment;
824 fragment = xmalloc(sizeof(*fragment));
825 memset(fragment, 0, sizeof(*fragment));
826 len = parse_fragment(line, size, patch, fragment);
828 die("corrupt patch at line %d", linenr);
830 fragment->patch = line;
831 fragment->size = len;
834 fragp = &fragment->next;
843 static inline int metadata_changes(struct patch *patch)
845 return patch->is_rename > 0 ||
846 patch->is_copy > 0 ||
849 (patch->old_mode && patch->new_mode &&
850 patch->old_mode != patch->new_mode);
853 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
855 int hdrsize, patchsize;
856 int offset = find_header(buffer, size, &hdrsize, patch);
861 patchsize = parse_single_patch(buffer + offset + hdrsize, size - offset - hdrsize, patch);
863 if (!patchsize && !metadata_changes(patch))
864 die("patch with only garbage at line %d", linenr);
866 return offset + hdrsize + patchsize;
869 static const char pluses[] = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
870 static const char minuses[]= "----------------------------------------------------------------------";
872 static void show_stats(struct patch *patch)
874 const char *prefix = "";
875 char *name = patch->new_name;
877 int len, max, add, del, total;
880 name = patch->old_name;
882 if (0 < (len = quote_c_style(name, NULL, NULL, 0))) {
883 qname = xmalloc(len + 1);
884 quote_c_style(name, qname, NULL, 0);
889 * "scale" the filename
900 slash = strchr(name, '/');
907 * scale the add/delete
913 add = patch->lines_added;
914 del = patch->lines_deleted;
917 if (max_change > 0) {
918 total = (total * max + max_change / 2) / max_change;
919 add = (add * max + max_change / 2) / max_change;
922 printf(" %s%-*s |%5d %.*s%.*s\n", prefix,
923 len, name, patch->lines_added + patch->lines_deleted,
924 add, pluses, del, minuses);
929 static int read_old_data(struct stat *st, const char *path, void *buf, unsigned long size)
934 switch (st->st_mode & S_IFMT) {
936 return readlink(path, buf, size);
938 fd = open(path, O_RDONLY);
940 return error("unable to open %s", path);
943 int ret = read(fd, buf + got, size - got);
961 static int find_offset(const char *buf, unsigned long size, const char *fragment, unsigned long fragsize, int line)
964 unsigned long start, backwards, forwards;
971 unsigned long offset = 0;
973 while (offset + fragsize <= size) {
974 if (buf[offset++] == '\n') {
982 /* Exact line number? */
983 if (!memcmp(buf + start, fragment, fragsize))
987 * There's probably some smart way to do this, but I'll leave
988 * that to the smart and beautiful people. I'm simple and stupid.
999 if (forwards + fragsize > size)
1005 } while (backwards && buf[backwards-1] != '\n');
1008 while (forwards + fragsize <= size) {
1009 if (buf[forwards++] == '\n')
1015 if (try + fragsize > size)
1017 if (memcmp(buf + try, fragment, fragsize))
1026 * We should start searching forward and backward.
1031 struct buffer_desc {
1034 unsigned long alloc;
1037 static int apply_one_fragment(struct buffer_desc *desc, struct fragment *frag)
1039 char *buf = desc->buffer;
1040 const char *patch = frag->patch;
1041 int offset, size = frag->size;
1042 char *old = xmalloc(size);
1043 char *new = xmalloc(size);
1044 int oldsize = 0, newsize = 0;
1047 int len = linelen(patch, size);
1054 * "plen" is how much of the line we should use for
1055 * the actual patch data. Normally we just remove the
1056 * first character on the line, but if the line is
1057 * followed by "\ No newline", then we also remove the
1058 * last one (which is the newline, of course).
1061 if (len < size && patch[len] == '\\')
1066 memcpy(old + oldsize, patch + 1, plen);
1070 /* Fall-through for ' ' */
1072 memcpy(new + newsize, patch + 1, plen);
1075 case '@': case '\\':
1076 /* Ignore it, we already handled it */
1085 offset = find_offset(buf, desc->size, old, oldsize, frag->newpos);
1087 int diff = newsize - oldsize;
1088 unsigned long size = desc->size + diff;
1089 unsigned long alloc = desc->alloc;
1092 alloc = size + 8192;
1093 desc->alloc = alloc;
1094 buf = xrealloc(buf, alloc);
1098 memmove(buf + offset + newsize, buf + offset + oldsize, size - offset - newsize);
1099 memcpy(buf + offset, new, newsize);
1108 static int apply_fragments(struct buffer_desc *desc, struct patch *patch)
1110 struct fragment *frag = patch->fragments;
1113 if (apply_one_fragment(desc, frag) < 0)
1114 return error("patch failed: %s:%ld", patch->old_name, frag->oldpos);
1120 static int apply_data(struct patch *patch, struct stat *st)
1123 unsigned long size, alloc;
1124 struct buffer_desc desc;
1129 if (patch->old_name) {
1131 alloc = size + 8192;
1132 buf = xmalloc(alloc);
1133 if (read_old_data(st, patch->old_name, buf, alloc) != size)
1134 return error("read of %s failed", patch->old_name);
1140 if (apply_fragments(&desc, patch) < 0)
1142 patch->result = desc.buffer;
1143 patch->resultsize = desc.size;
1145 if (patch->is_delete && patch->resultsize)
1146 return error("removal patch leaves file contents");
1151 static int check_patch(struct patch *patch)
1154 const char *old_name = patch->old_name;
1155 const char *new_name = patch->new_name;
1160 if (lstat(old_name, &st) < 0)
1161 return error("%s: %s", old_name, strerror(errno));
1163 int pos = cache_name_pos(old_name, strlen(old_name));
1165 return error("%s: does not exist in index", old_name);
1166 changed = ce_match_stat(active_cache[pos], &st);
1168 return error("%s: does not match index", old_name);
1170 if (patch->is_new < 0)
1172 st.st_mode = ntohl(create_ce_mode(st.st_mode));
1173 if (!patch->old_mode)
1174 patch->old_mode = st.st_mode;
1175 if ((st.st_mode ^ patch->old_mode) & S_IFMT)
1176 return error("%s: wrong type", old_name);
1177 if (st.st_mode != patch->old_mode)
1178 fprintf(stderr, "warning: %s has type %o, expected %o\n",
1179 old_name, st.st_mode, patch->old_mode);
1182 if (new_name && (patch->is_new | patch->is_rename | patch->is_copy)) {
1183 if (check_index && cache_name_pos(new_name, strlen(new_name)) >= 0)
1184 return error("%s: already exists in index", new_name);
1185 if (!lstat(new_name, &st))
1186 return error("%s: already exists in working directory", new_name);
1187 if (errno != ENOENT)
1188 return error("%s: %s", new_name, strerror(errno));
1189 if (!patch->new_mode) {
1191 patch->new_mode = S_IFREG | 0644;
1193 patch->new_mode = patch->old_mode;
1197 if (new_name && old_name) {
1198 int same = !strcmp(old_name, new_name);
1199 if (!patch->new_mode)
1200 patch->new_mode = patch->old_mode;
1201 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
1202 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
1203 patch->new_mode, new_name, patch->old_mode,
1204 same ? "" : " of ", same ? "" : old_name);
1207 if (apply_data(patch, &st) < 0)
1208 return error("%s: patch does not apply", old_name);
1212 static int check_patch_list(struct patch *patch)
1216 for (;patch ; patch = patch->next)
1217 error |= check_patch(patch);
1221 static void show_file(int c, unsigned int mode, const char *name)
1223 printf("%c %o %s\n", c, mode, name);
1226 static void show_file_list(struct patch *patch)
1228 for (;patch ; patch = patch->next) {
1229 if (patch->is_rename) {
1230 show_file('-', patch->old_mode, patch->old_name);
1231 show_file('+', patch->new_mode, patch->new_name);
1234 if (patch->is_copy || patch->is_new) {
1235 show_file('+', patch->new_mode, patch->new_name);
1238 if (patch->is_delete) {
1239 show_file('-', patch->old_mode, patch->old_name);
1242 if (patch->old_mode && patch->new_mode && patch->old_mode != patch->new_mode) {
1243 printf("M %o:%o %s\n", patch->old_mode, patch->new_mode, patch->old_name);
1246 printf("M %o %s\n", patch->old_mode, patch->old_name);
1250 static void stat_patch_list(struct patch *patch)
1252 int files, adds, dels;
1254 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
1256 adds += patch->lines_added;
1257 dels += patch->lines_deleted;
1261 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
1264 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
1267 printf(" %s mode %06o %s\n", newdelete, mode, name);
1269 printf(" %s %s\n", newdelete, name);
1272 static void show_mode_change(struct patch *p, int show_name)
1274 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
1276 printf(" mode change %06o => %06o %s\n",
1277 p->old_mode, p->new_mode, p->new_name);
1279 printf(" mode change %06o => %06o\n",
1280 p->old_mode, p->new_mode);
1284 static void show_rename_copy(struct patch *p)
1286 const char *renamecopy = p->is_rename ? "rename" : "copy";
1287 const char *old, *new;
1289 /* Find common prefix */
1293 const char *slash_old, *slash_new;
1294 slash_old = strchr(old, '/');
1295 slash_new = strchr(new, '/');
1298 slash_old - old != slash_new - new ||
1299 memcmp(old, new, slash_new - new))
1301 old = slash_old + 1;
1302 new = slash_new + 1;
1304 /* p->old_name thru old is the common prefix, and old and new
1305 * through the end of names are renames
1307 if (old != p->old_name)
1308 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
1309 (int)(old - p->old_name), p->old_name,
1310 old, new, p->score);
1312 printf(" %s %s => %s (%d%%)\n", renamecopy,
1313 p->old_name, p->new_name, p->score);
1314 show_mode_change(p, 0);
1317 static void summary_patch_list(struct patch *patch)
1321 for (p = patch; p; p = p->next) {
1323 show_file_mode_name("create", p->new_mode, p->new_name);
1324 else if (p->is_delete)
1325 show_file_mode_name("delete", p->old_mode, p->old_name);
1327 if (p->is_rename || p->is_copy)
1328 show_rename_copy(p);
1331 printf(" rewrite %s (%d%%)\n",
1332 p->new_name, p->score);
1333 show_mode_change(p, 0);
1336 show_mode_change(p, 1);
1342 static void patch_stats(struct patch *patch)
1344 int lines = patch->lines_added + patch->lines_deleted;
1346 if (lines > max_change)
1348 if (patch->old_name) {
1349 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
1351 len = strlen(patch->old_name);
1355 if (patch->new_name) {
1356 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
1358 len = strlen(patch->new_name);
1364 static void remove_file(struct patch *patch)
1367 if (remove_file_from_cache(patch->old_name) < 0)
1368 die("unable to remove %s from index", patch->old_name);
1370 unlink(patch->old_name);
1373 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
1376 struct cache_entry *ce;
1377 int namelen = strlen(path);
1378 unsigned ce_size = cache_entry_size(namelen);
1383 ce = xmalloc(ce_size);
1384 memset(ce, 0, ce_size);
1385 memcpy(ce->name, path, namelen);
1386 ce->ce_mode = create_ce_mode(mode);
1387 ce->ce_flags = htons(namelen);
1388 if (lstat(path, &st) < 0)
1389 die("unable to stat newly created file %s", path);
1390 fill_stat_cache_info(ce, &st);
1391 if (write_sha1_file(buf, size, "blob", ce->sha1) < 0)
1392 die("unable to create backing store for newly created file %s", path);
1393 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
1394 die("unable to add cache entry for %s", path);
1397 static void create_subdirectories(const char *path)
1399 int len = strlen(path);
1400 char *buf = xmalloc(len + 1);
1401 const char *slash = path;
1403 while ((slash = strchr(slash+1, '/')) != NULL) {
1405 memcpy(buf, path, len);
1407 if (mkdir(buf, 0777) < 0) {
1408 if (errno != EEXIST)
1415 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
1420 return symlink(buf, path);
1421 fd = open(path, O_CREAT | O_EXCL | O_WRONLY | O_TRUNC, (mode & 0100) ? 0777 : 0666);
1425 int written = write(fd, buf, size);
1427 if (errno == EINTR || errno == EAGAIN)
1429 die("writing file %s: %s", path, strerror(errno));
1432 die("out of space writing file %s", path);
1437 die("closing file %s: %s", path, strerror(errno));
1442 * We optimistically assume that the directories exist,
1443 * which is true 99% of the time anyway. If they don't,
1444 * we create them and try again.
1446 static void create_one_file(const char *path, unsigned mode, const char *buf, unsigned long size)
1448 if (!try_create_file(path, mode, buf, size))
1451 if (errno == ENOENT) {
1452 create_subdirectories(path);
1453 if (!try_create_file(path, mode, buf, size))
1457 if (errno == EEXIST) {
1458 unsigned int nr = getpid();
1461 const char *newpath;
1462 newpath = mkpath("%s~%u", path, nr);
1463 if (!try_create_file(newpath, mode, buf, size)) {
1464 if (!rename(newpath, path))
1469 if (errno != EEXIST)
1473 die("unable to write file %s mode %o", path, mode);
1476 static void create_file(struct patch *patch)
1478 const char *path = patch->new_name;
1479 unsigned mode = patch->new_mode;
1480 unsigned long size = patch->resultsize;
1481 char *buf = patch->result;
1484 mode = S_IFREG | 0644;
1485 create_one_file(path, mode, buf, size);
1486 add_index_file(path, mode, buf, size);
1489 static void write_out_one_result(struct patch *patch)
1491 if (patch->is_delete > 0) {
1495 if (patch->is_new > 0 || patch->is_copy) {
1500 * Rename or modification boils down to the same
1501 * thing: remove the old, write the new
1507 static void write_out_results(struct patch *list, int skipped_patch)
1509 if (!list && !skipped_patch)
1513 write_out_one_result(list);
1518 static struct cache_file cache_file;
1520 static struct excludes {
1521 struct excludes *next;
1525 static int use_patch(struct patch *p)
1527 const char *pathname = p->new_name ? p->new_name : p->old_name;
1528 struct excludes *x = excludes;
1530 if (fnmatch(x->path, pathname, 0) == 0)
1537 static int apply_patch(int fd)
1540 unsigned long offset, size;
1541 char *buffer = read_patch_file(fd, &size);
1542 struct patch *list = NULL, **listp = &list;
1543 int skipped_patch = 0;
1549 struct patch *patch;
1552 patch = xmalloc(sizeof(*patch));
1553 memset(patch, 0, sizeof(*patch));
1554 nr = parse_chunk(buffer + offset, size, patch);
1557 if (use_patch(patch)) {
1560 listp = &patch->next;
1562 /* perhaps free it a bit better? */
1571 write_index = check_index && apply;
1573 newfd = hold_index_file_for_update(&cache_file, get_index_file());
1575 if (read_cache() < 0)
1576 die("unable to read index file");
1579 if ((check || apply) && check_patch_list(list) < 0)
1583 write_out_results(list, skipped_patch);
1586 if (write_cache(newfd, active_cache, active_nr) ||
1587 commit_index_file(&cache_file))
1588 die("Unable to write new cachefile");
1592 show_file_list(list);
1595 stat_patch_list(list);
1598 summary_patch_list(list);
1604 int main(int argc, char **argv)
1609 for (i = 1; i < argc; i++) {
1610 const char *arg = argv[i];
1613 if (!strcmp(arg, "-")) {
1618 if (!strncmp(arg, "--exclude=", 10)) {
1619 struct excludes *x = xmalloc(sizeof(*x));
1625 /* NEEDSWORK: this does not do anything at this moment. */
1626 if (!strcmp(arg, "--no-merge")) {
1630 if (!strcmp(arg, "--stat")) {
1635 if (!strcmp(arg, "--summary")) {
1640 if (!strcmp(arg, "--check")) {
1645 if (!strcmp(arg, "--index")) {
1649 if (!strcmp(arg, "--apply")) {
1653 if (!strcmp(arg, "--show-files")) {
1657 fd = open(arg, O_RDONLY);