4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
12 // --check turns on checking that the working tree matches the
13 // files that are being modified, but doesn't apply the patch
14 // --stat does just a diffstat, and doesn't actually apply
15 // --show-files shows the directory changes
16 // --show-index-info shows the old and new index info for paths if available.
18 static int check_index = 0;
19 static int write_index = 0;
20 static int diffstat = 0;
21 static int summary = 0;
24 static int show_files = 0;
25 static int show_index_info = 0;
26 static const char apply_usage[] =
27 "git-apply [--stat] [--summary] [--check] [--index] [--apply] [--show-files] [--show-index-info] <patch>...";
30 * For "diff-stat" like behaviour, we keep track of the biggest change
31 * we've seen, and the longest filename. That allows us to do simple
34 static int max_change, max_len;
37 * Various "current state", notably line numbers and what
38 * file (and how) we're patching right now.. The "is_xxxx"
39 * things are flags, where -1 means "don't know yet".
41 static int linenr = 1;
44 unsigned long oldpos, oldlines;
45 unsigned long newpos, newlines;
48 struct fragment *next;
52 char *new_name, *old_name, *def_name;
53 unsigned int old_mode, new_mode;
54 int is_rename, is_copy, is_new, is_delete;
55 int lines_added, lines_deleted;
57 struct fragment *fragments;
59 unsigned long resultsize;
60 char old_sha1_prefix[41];
61 char new_sha1_prefix[41];
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(const 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)
328 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
333 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
335 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
340 static int gitdiff_index(const char *line, struct patch *patch)
342 /* index line is N hexadecimal, "..", N hexadecimal,
343 * and optional space with octal mode.
345 const char *ptr, *eol;
348 ptr = strchr(line, '.');
349 if (!ptr || ptr[1] != '.' || 40 <= ptr - line)
352 memcpy(patch->old_sha1_prefix, line, len);
353 patch->old_sha1_prefix[len] = 0;
356 ptr = strchr(line, ' ');
357 eol = strchr(line, '\n');
359 if (!ptr || eol < ptr)
365 memcpy(patch->new_sha1_prefix, line, len);
366 patch->new_sha1_prefix[len] = 0;
368 patch->new_mode = patch->old_mode = strtoul(ptr+1, NULL, 8);
373 * This is normal for a diff that doesn't change anything: we'll fall through
374 * into the next diff. Tell the parser to break out.
376 static int gitdiff_unrecognized(const char *line, struct patch *patch)
381 static char *git_header_name(char *line)
399 * We don't accept absolute paths (/dev/null) as possibly valid
405 * Accept a name only if it shows up twice, exactly the same
408 for (len = 0 ; ; len++) {
425 if (second[len] == '\n' && !memcmp(name, second, len)) {
426 char *ret = xmalloc(len + 1);
427 memcpy(ret, name, len);
436 /* Verify that we recognize the lines following a git header */
437 static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
439 unsigned long offset;
441 /* A git diff has explicit new/delete information, so we don't guess */
443 patch->is_delete = 0;
446 * Some things may not have the old name in the
447 * rest of the headers anywhere (pure mode changes,
448 * or removing or adding empty files), so we get
449 * the default name from the header.
451 patch->def_name = git_header_name(line + strlen("diff --git "));
456 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
457 static const struct opentry {
459 int (*fn)(const char *, struct patch *);
461 { "@@ -", gitdiff_hdrend },
462 { "--- ", gitdiff_oldname },
463 { "+++ ", gitdiff_newname },
464 { "old mode ", gitdiff_oldmode },
465 { "new mode ", gitdiff_newmode },
466 { "deleted file mode ", gitdiff_delete },
467 { "new file mode ", gitdiff_newfile },
468 { "copy from ", gitdiff_copysrc },
469 { "copy to ", gitdiff_copydst },
470 { "rename old ", gitdiff_renamesrc },
471 { "rename new ", gitdiff_renamedst },
472 { "rename from ", gitdiff_renamesrc },
473 { "rename to ", gitdiff_renamedst },
474 { "similarity index ", gitdiff_similarity },
475 { "dissimilarity index ", gitdiff_dissimilarity },
476 { "index ", gitdiff_index },
477 { "", gitdiff_unrecognized },
481 len = linelen(line, size);
482 if (!len || line[len-1] != '\n')
484 for (i = 0; i < sizeof(optable) / sizeof(optable[0]); i++) {
485 const struct opentry *p = optable + i;
486 int oplen = strlen(p->str);
487 if (len < oplen || memcmp(p->str, line, oplen))
489 if (p->fn(line + oplen, patch) < 0)
498 static int parse_num(const char *line, unsigned long *p)
504 *p = strtoul(line, &ptr, 10);
508 static int parse_range(const char *line, int len, int offset, const char *expect,
509 unsigned long *p1, unsigned long *p2)
513 if (offset < 0 || offset >= len)
518 digits = parse_num(line, p1);
528 digits = parse_num(line+1, p2);
540 if (memcmp(line, expect, ex))
547 * Parse a unified diff fragment header of the
548 * form "@@ -a,b +c,d @@"
550 static int parse_fragment_header(char *line, int len, struct fragment *fragment)
554 if (!len || line[len-1] != '\n')
557 /* Figure out the number of lines in a fragment */
558 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
559 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
564 static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
566 unsigned long offset, len;
568 patch->is_rename = patch->is_copy = 0;
569 patch->is_new = patch->is_delete = -1;
570 patch->old_mode = patch->new_mode = 0;
571 patch->old_name = patch->new_name = NULL;
572 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
573 unsigned long nextlen;
575 len = linelen(line, size);
579 /* Testing this early allows us to take a few shortcuts.. */
584 * Make sure we don't find any unconnected patch fragmants.
585 * That's a sign that we didn't find a header, and that a
586 * patch has become corrupted/broken up.
588 if (!memcmp("@@ -", line, 4)) {
589 struct fragment dummy;
590 if (parse_fragment_header(line, len, &dummy) < 0)
592 error("patch fragment without header at line %d: %.*s", linenr, (int)len-1, line);
599 * Git patch? It might not have a real patch, just a rename
600 * or mode change, so we handle that specially
602 if (!memcmp("diff --git ", line, 11)) {
603 int git_hdr_len = parse_git_header(line, len, size, patch);
604 if (git_hdr_len <= len)
606 if (!patch->old_name && !patch->new_name) {
607 if (!patch->def_name)
608 die("git diff header lacks filename information (line %d)", linenr);
609 patch->old_name = patch->new_name = patch->def_name;
611 *hdrsize = git_hdr_len;
615 /** --- followed by +++ ? */
616 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
620 * We only accept unified patches, so we want it to
621 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
624 nextlen = linelen(line + len, size - len);
625 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
628 /* Ok, we'll consider it a patch */
629 parse_traditional_patch(line, line+len, patch);
630 *hdrsize = len + nextlen;
638 * Parse a unified diff. Note that this really needs
639 * to parse each fragment separately, since the only
640 * way to know the difference between a "---" that is
641 * part of a patch, and a "---" that starts the next
642 * patch is to look at the line counts..
644 static int parse_fragment(char *line, unsigned long size, struct patch *patch, struct fragment *fragment)
647 int len = linelen(line, size), offset;
648 unsigned long oldlines, newlines;
650 offset = parse_fragment_header(line, len, fragment);
653 oldlines = fragment->oldlines;
654 newlines = fragment->newlines;
656 if (patch->is_new < 0) {
657 patch->is_new = !oldlines;
659 patch->old_name = NULL;
661 if (patch->is_delete < 0) {
662 patch->is_delete = !newlines;
664 patch->new_name = NULL;
667 if (patch->is_new != !oldlines)
668 return error("new file depends on old contents");
669 if (patch->is_delete != !newlines) {
671 return error("deleted file still has contents");
672 fprintf(stderr, "** warning: file %s becomes empty but is not deleted\n", patch->new_name);
675 /* Parse the thing.. */
680 for (offset = len; size > 0; offset += len, size -= len, line += len, linenr++) {
681 if (!oldlines && !newlines)
683 len = linelen(line, size);
684 if (!len || line[len-1] != '\n')
702 /* We allow "\ No newline at end of file". Depending
703 * on locale settings when the patch was produced we
704 * don't know what this line looks like. The only
705 * thing we do know is that it begins with "\ ".
706 * Checking for 12 is just for sanity check -- any
707 * l10n of "\ No newline..." is at least that long.
710 if (len < 12 || memcmp(line, "\\ ", 2))
715 /* If a fragment ends with an incomplete line, we failed to include
716 * it in the above loop because we hit oldlines == newlines == 0
719 if (12 < size && !memcmp(line, "\\ ", 2))
720 offset += linelen(line, size);
722 patch->lines_added += added;
723 patch->lines_deleted += deleted;
727 static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
729 unsigned long offset = 0;
730 struct fragment **fragp = &patch->fragments;
732 while (size > 4 && !memcmp(line, "@@ -", 4)) {
733 struct fragment *fragment;
736 fragment = xmalloc(sizeof(*fragment));
737 memset(fragment, 0, sizeof(*fragment));
738 len = parse_fragment(line, size, patch, fragment);
740 die("corrupt patch at line %d", linenr);
742 fragment->patch = line;
743 fragment->size = len;
746 fragp = &fragment->next;
755 static inline int metadata_changes(struct patch *patch)
757 return patch->is_rename > 0 ||
758 patch->is_copy > 0 ||
761 (patch->old_mode && patch->new_mode &&
762 patch->old_mode != patch->new_mode);
765 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
767 int hdrsize, patchsize;
768 int offset = find_header(buffer, size, &hdrsize, patch);
773 patchsize = parse_single_patch(buffer + offset + hdrsize, size - offset - hdrsize, patch);
775 if (!patchsize && !metadata_changes(patch))
776 die("patch with only garbage at line %d", linenr);
778 return offset + hdrsize + patchsize;
781 static const char pluses[] = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
782 static const char minuses[]= "----------------------------------------------------------------------";
784 static void show_stats(struct patch *patch)
786 const char *prefix = "";
787 char *name = patch->new_name;
788 int len, max, add, del, total;
791 name = patch->old_name;
794 * "scale" the filename
805 slash = strchr(name, '/');
812 * scale the add/delete
818 add = patch->lines_added;
819 del = patch->lines_deleted;
822 if (max_change > 0) {
823 total = (total * max + max_change / 2) / max_change;
824 add = (add * max + max_change / 2) / max_change;
827 printf(" %s%-*s |%5d %.*s%.*s\n", prefix,
828 len, name, patch->lines_added + patch->lines_deleted,
829 add, pluses, del, minuses);
832 static int read_old_data(struct stat *st, const char *path, void *buf, unsigned long size)
837 switch (st->st_mode & S_IFMT) {
839 return readlink(path, buf, size);
841 fd = open(path, O_RDONLY);
843 return error("unable to open %s", path);
846 int ret = read(fd, buf + got, size - got);
864 static int find_offset(const char *buf, unsigned long size, const char *fragment, unsigned long fragsize, int line)
867 unsigned long start, backwards, forwards;
874 unsigned long offset = 0;
876 while (offset + fragsize <= size) {
877 if (buf[offset++] == '\n') {
885 /* Exact line number? */
886 if (!memcmp(buf + start, fragment, fragsize))
890 * There's probably some smart way to do this, but I'll leave
891 * that to the smart and beautiful people. I'm simple and stupid.
902 if (forwards + fragsize > size)
908 } while (backwards && buf[backwards-1] != '\n');
911 while (forwards + fragsize <= size) {
912 if (buf[forwards++] == '\n')
918 if (try + fragsize > size)
920 if (memcmp(buf + try, fragment, fragsize))
929 * We should start searching forward and backward.
940 static int apply_one_fragment(struct buffer_desc *desc, struct fragment *frag)
942 char *buf = desc->buffer;
943 const char *patch = frag->patch;
944 int offset, size = frag->size;
945 char *old = xmalloc(size);
946 char *new = xmalloc(size);
947 int oldsize = 0, newsize = 0;
950 int len = linelen(patch, size);
957 * "plen" is how much of the line we should use for
958 * the actual patch data. Normally we just remove the
959 * first character on the line, but if the line is
960 * followed by "\ No newline", then we also remove the
961 * last one (which is the newline, of course).
964 if (len < size && patch[len] == '\\')
969 memcpy(old + oldsize, patch + 1, plen);
973 /* Fall-through for ' ' */
975 memcpy(new + newsize, patch + 1, plen);
979 /* Ignore it, we already handled it */
988 offset = find_offset(buf, desc->size, old, oldsize, frag->newpos);
990 int diff = newsize - oldsize;
991 unsigned long size = desc->size + diff;
992 unsigned long alloc = desc->alloc;
997 buf = xrealloc(buf, alloc);
1001 memmove(buf + offset + newsize, buf + offset + oldsize, size - offset - newsize);
1002 memcpy(buf + offset, new, newsize);
1011 static int apply_fragments(struct buffer_desc *desc, struct patch *patch)
1013 struct fragment *frag = patch->fragments;
1016 if (apply_one_fragment(desc, frag) < 0)
1017 return error("patch failed: %s:%ld", patch->old_name, frag->oldpos);
1023 static int apply_data(struct patch *patch, struct stat *st)
1026 unsigned long size, alloc;
1027 struct buffer_desc desc;
1032 if (patch->old_name) {
1034 alloc = size + 8192;
1035 buf = xmalloc(alloc);
1036 if (read_old_data(st, patch->old_name, buf, alloc) != size)
1037 return error("read of %s failed", patch->old_name);
1043 if (apply_fragments(&desc, patch) < 0)
1045 patch->result = desc.buffer;
1046 patch->resultsize = desc.size;
1048 if (patch->is_delete && patch->resultsize)
1049 return error("removal patch leaves file contents");
1054 static int check_patch(struct patch *patch)
1057 const char *old_name = patch->old_name;
1058 const char *new_name = patch->new_name;
1062 int stat_ret = lstat(old_name, &st);
1065 int pos = cache_name_pos(old_name, strlen(old_name));
1067 return error("%s: does not exist in index",
1070 struct checkout costate;
1071 if (errno != ENOENT)
1072 return error("%s: %s", old_name,
1075 costate.base_dir = "";
1076 costate.base_dir_len = 0;
1079 costate.not_new = 0;
1080 costate.refresh_cache = 1;
1081 if (checkout_entry(active_cache[pos],
1083 lstat(old_name, &st))
1087 changed = ce_match_stat(active_cache[pos], &st);
1089 return error("%s: does not match index",
1092 else if (stat_ret < 0)
1093 return error("%s: %s", old_name, strerror(errno));
1095 if (patch->is_new < 0)
1097 st.st_mode = ntohl(create_ce_mode(st.st_mode));
1098 if (!patch->old_mode)
1099 patch->old_mode = st.st_mode;
1100 if ((st.st_mode ^ patch->old_mode) & S_IFMT)
1101 return error("%s: wrong type", old_name);
1102 if (st.st_mode != patch->old_mode)
1103 fprintf(stderr, "warning: %s has type %o, expected %o\n",
1104 old_name, st.st_mode, patch->old_mode);
1107 if (new_name && (patch->is_new | patch->is_rename | patch->is_copy)) {
1108 if (check_index && cache_name_pos(new_name, strlen(new_name)) >= 0)
1109 return error("%s: already exists in index", new_name);
1110 if (!lstat(new_name, &st))
1111 return error("%s: already exists in working directory", new_name);
1112 if (errno != ENOENT)
1113 return error("%s: %s", new_name, strerror(errno));
1114 if (!patch->new_mode) {
1116 patch->new_mode = S_IFREG | 0644;
1118 patch->new_mode = patch->old_mode;
1122 if (new_name && old_name) {
1123 int same = !strcmp(old_name, new_name);
1124 if (!patch->new_mode)
1125 patch->new_mode = patch->old_mode;
1126 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
1127 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
1128 patch->new_mode, new_name, patch->old_mode,
1129 same ? "" : " of ", same ? "" : old_name);
1132 if (apply_data(patch, &st) < 0)
1133 return error("%s: patch does not apply", old_name);
1137 static int check_patch_list(struct patch *patch)
1141 for (;patch ; patch = patch->next)
1142 error |= check_patch(patch);
1146 static void show_file(int c, unsigned int mode, const char *name)
1148 printf("%c %o %s\n", c, mode, name);
1151 static void show_file_list(struct patch *patch)
1153 for (;patch ; patch = patch->next) {
1154 if (patch->is_rename) {
1155 show_file('-', patch->old_mode, patch->old_name);
1156 show_file('+', patch->new_mode, patch->new_name);
1159 if (patch->is_copy || patch->is_new) {
1160 show_file('+', patch->new_mode, patch->new_name);
1163 if (patch->is_delete) {
1164 show_file('-', patch->old_mode, patch->old_name);
1167 if (patch->old_mode && patch->new_mode && patch->old_mode != patch->new_mode) {
1168 printf("M %o:%o %s\n", patch->old_mode, patch->new_mode, patch->old_name);
1171 printf("M %o %s\n", patch->old_mode, patch->old_name);
1175 static inline int is_null_sha1(const unsigned char *sha1)
1177 return !memcmp(sha1, null_sha1, 20);
1180 static void show_index_list(struct patch *list)
1182 struct patch *patch;
1184 /* Once we start supporting the reverse patch, it may be
1185 * worth showing the new sha1 prefix, but until then...
1187 for (patch = list; patch; patch = patch->next) {
1188 const unsigned char *sha1_ptr;
1189 unsigned char sha1[20];
1192 name = patch->old_name ? patch->old_name : patch->new_name;
1194 sha1_ptr = null_sha1;
1195 else if (get_sha1(patch->old_sha1_prefix, sha1))
1196 die("sha1 information is lacking or useless (%s).",
1200 printf("%06o %s %s\n",patch->old_mode,
1201 sha1_to_hex(sha1_ptr), name);
1205 static void stat_patch_list(struct patch *patch)
1207 int files, adds, dels;
1209 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
1211 adds += patch->lines_added;
1212 dels += patch->lines_deleted;
1216 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
1219 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
1222 printf(" %s mode %06o %s\n", newdelete, mode, name);
1224 printf(" %s %s\n", newdelete, name);
1227 static void show_mode_change(struct patch *p, int show_name)
1229 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
1231 printf(" mode change %06o => %06o %s\n",
1232 p->old_mode, p->new_mode, p->new_name);
1234 printf(" mode change %06o => %06o\n",
1235 p->old_mode, p->new_mode);
1239 static void show_rename_copy(struct patch *p)
1241 const char *renamecopy = p->is_rename ? "rename" : "copy";
1242 const char *old, *new;
1244 /* Find common prefix */
1248 const char *slash_old, *slash_new;
1249 slash_old = strchr(old, '/');
1250 slash_new = strchr(new, '/');
1253 slash_old - old != slash_new - new ||
1254 memcmp(old, new, slash_new - new))
1256 old = slash_old + 1;
1257 new = slash_new + 1;
1259 /* p->old_name thru old is the common prefix, and old and new
1260 * through the end of names are renames
1262 if (old != p->old_name)
1263 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
1264 (int)(old - p->old_name), p->old_name,
1265 old, new, p->score);
1267 printf(" %s %s => %s (%d%%)\n", renamecopy,
1268 p->old_name, p->new_name, p->score);
1269 show_mode_change(p, 0);
1272 static void summary_patch_list(struct patch *patch)
1276 for (p = patch; p; p = p->next) {
1278 show_file_mode_name("create", p->new_mode, p->new_name);
1279 else if (p->is_delete)
1280 show_file_mode_name("delete", p->old_mode, p->old_name);
1282 if (p->is_rename || p->is_copy)
1283 show_rename_copy(p);
1286 printf(" rewrite %s (%d%%)\n",
1287 p->new_name, p->score);
1288 show_mode_change(p, 0);
1291 show_mode_change(p, 1);
1297 static void patch_stats(struct patch *patch)
1299 int lines = patch->lines_added + patch->lines_deleted;
1301 if (lines > max_change)
1303 if (patch->old_name) {
1304 int len = strlen(patch->old_name);
1308 if (patch->new_name) {
1309 int len = strlen(patch->new_name);
1315 static void remove_file(struct patch *patch)
1318 if (remove_file_from_cache(patch->old_name) < 0)
1319 die("unable to remove %s from index", patch->old_name);
1321 unlink(patch->old_name);
1324 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
1327 struct cache_entry *ce;
1328 int namelen = strlen(path);
1329 unsigned ce_size = cache_entry_size(namelen);
1334 ce = xmalloc(ce_size);
1335 memset(ce, 0, ce_size);
1336 memcpy(ce->name, path, namelen);
1337 ce->ce_mode = create_ce_mode(mode);
1338 ce->ce_flags = htons(namelen);
1339 if (lstat(path, &st) < 0)
1340 die("unable to stat newly created file %s", path);
1341 fill_stat_cache_info(ce, &st);
1342 if (write_sha1_file(buf, size, "blob", ce->sha1) < 0)
1343 die("unable to create backing store for newly created file %s", path);
1344 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
1345 die("unable to add cache entry for %s", path);
1348 static void create_subdirectories(const char *path)
1350 int len = strlen(path);
1351 char *buf = xmalloc(len + 1);
1352 const char *slash = path;
1354 while ((slash = strchr(slash+1, '/')) != NULL) {
1356 memcpy(buf, path, len);
1358 if (mkdir(buf, 0777) < 0) {
1359 if (errno != EEXIST)
1366 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
1371 return symlink(buf, path);
1372 fd = open(path, O_CREAT | O_EXCL | O_WRONLY | O_TRUNC, (mode & 0100) ? 0777 : 0666);
1376 int written = write(fd, buf, size);
1378 if (errno == EINTR || errno == EAGAIN)
1380 die("writing file %s: %s", path, strerror(errno));
1383 die("out of space writing file %s", path);
1388 die("closing file %s: %s", path, strerror(errno));
1393 * We optimistically assume that the directories exist,
1394 * which is true 99% of the time anyway. If they don't,
1395 * we create them and try again.
1397 static void create_one_file(const char *path, unsigned mode, const char *buf, unsigned long size)
1399 if (!try_create_file(path, mode, buf, size))
1402 if (errno == ENOENT) {
1403 create_subdirectories(path);
1404 if (!try_create_file(path, mode, buf, size))
1408 if (errno == EEXIST) {
1409 unsigned int nr = getpid();
1412 const char *newpath;
1413 newpath = mkpath("%s~%u", path, nr);
1414 if (!try_create_file(newpath, mode, buf, size)) {
1415 if (!rename(newpath, path))
1420 if (errno != EEXIST)
1424 die("unable to write file %s mode %o", path, mode);
1427 static void create_file(struct patch *patch)
1429 const char *path = patch->new_name;
1430 unsigned mode = patch->new_mode;
1431 unsigned long size = patch->resultsize;
1432 char *buf = patch->result;
1435 mode = S_IFREG | 0644;
1436 create_one_file(path, mode, buf, size);
1437 add_index_file(path, mode, buf, size);
1440 static void write_out_one_result(struct patch *patch)
1442 if (patch->is_delete > 0) {
1446 if (patch->is_new > 0 || patch->is_copy) {
1451 * Rename or modification boils down to the same
1452 * thing: remove the old, write the new
1458 static void write_out_results(struct patch *list, int skipped_patch)
1460 if (!list && !skipped_patch)
1464 write_out_one_result(list);
1469 static struct cache_file cache_file;
1471 static struct excludes {
1472 struct excludes *next;
1476 static int use_patch(struct patch *p)
1478 const char *pathname = p->new_name ? p->new_name : p->old_name;
1479 struct excludes *x = excludes;
1481 if (fnmatch(x->path, pathname, 0) == 0)
1488 static int apply_patch(int fd)
1491 unsigned long offset, size;
1492 char *buffer = read_patch_file(fd, &size);
1493 struct patch *list = NULL, **listp = &list;
1494 int skipped_patch = 0;
1500 struct patch *patch;
1503 patch = xmalloc(sizeof(*patch));
1504 memset(patch, 0, sizeof(*patch));
1505 nr = parse_chunk(buffer + offset, size, patch);
1508 if (use_patch(patch)) {
1511 listp = &patch->next;
1513 /* perhaps free it a bit better? */
1522 write_index = check_index && apply;
1524 newfd = hold_index_file_for_update(&cache_file, get_index_file());
1526 if (read_cache() < 0)
1527 die("unable to read index file");
1530 if ((check || apply) && check_patch_list(list) < 0)
1534 write_out_results(list, skipped_patch);
1537 if (write_cache(newfd, active_cache, active_nr) ||
1538 commit_index_file(&cache_file))
1539 die("Unable to write new cachefile");
1543 show_file_list(list);
1545 if (show_index_info)
1546 show_index_list(list);
1549 stat_patch_list(list);
1552 summary_patch_list(list);
1558 int main(int argc, char **argv)
1563 for (i = 1; i < argc; i++) {
1564 const char *arg = argv[i];
1567 if (!strcmp(arg, "-")) {
1572 if (!strncmp(arg, "--exclude=", 10)) {
1573 struct excludes *x = xmalloc(sizeof(*x));
1579 if (!strcmp(arg, "--stat")) {
1584 if (!strcmp(arg, "--summary")) {
1589 if (!strcmp(arg, "--check")) {
1594 if (!strcmp(arg, "--index")) {
1598 if (!strcmp(arg, "--apply")) {
1602 if (!strcmp(arg, "--show-files")) {
1606 if (!strcmp(arg, "--show-index-info")) {
1608 show_index_info = 1;
1611 fd = open(arg, O_RDONLY);