4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
13 // --check turns on checking that the working tree matches the
14 // files that are being modified, but doesn't apply the patch
15 // --stat does just a diffstat, and doesn't actually apply
16 // --show-files shows the directory changes
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 const char apply_usage[] =
26 "git-apply [--stat] [--summary] [--check] [--index] [--apply] [--show-files] <patch>...";
29 * For "diff-stat" like behaviour, we keep track of the biggest change
30 * we've seen, and the longest filename. That allows us to do simple
33 static int max_change, max_len;
36 * Various "current state", notably line numbers and what
37 * file (and how) we're patching right now.. The "is_xxxx"
38 * things are flags, where -1 means "don't know yet".
40 static int linenr = 1;
43 unsigned long oldpos, oldlines;
44 unsigned long newpos, newlines;
47 struct fragment *next;
51 char *new_name, *old_name, *def_name;
52 unsigned int old_mode, new_mode;
53 int is_rename, is_copy, is_new, is_delete;
54 int lines_added, lines_deleted;
56 struct fragment *fragments;
58 unsigned long resultsize;
62 #define CHUNKSIZE (8192)
65 static void *read_patch_file(int fd, unsigned long *sizep)
67 unsigned long size = 0, alloc = CHUNKSIZE;
68 void *buffer = xmalloc(alloc);
71 int nr = alloc - size;
74 buffer = xrealloc(buffer, alloc);
77 nr = read(fd, buffer + size, nr);
83 die("git-apply: read returned %s", strerror(errno));
90 * Make sure that we have some slop in the buffer
91 * so that we can do speculative "memcmp" etc, and
92 * see to it that it is NUL-filled.
94 if (alloc < size + SLOP)
95 buffer = xrealloc(buffer, size + SLOP);
96 memset(buffer + size, 0, SLOP);
100 static unsigned long linelen(const char *buffer, unsigned long size)
102 unsigned long len = 0;
105 if (*buffer++ == '\n')
111 static int is_dev_null(const char *str)
113 return !memcmp("/dev/null", str, 9) && isspace(str[9]);
119 static int name_terminate(const char *name, int namelen, int c, int terminate)
121 if (c == ' ' && !(terminate & TERM_SPACE))
123 if (c == '\t' && !(terminate & TERM_TAB))
129 static char * find_name(const char *line, char *def, int p_value, int terminate)
132 const char *start = line;
141 if (name_terminate(start, line-start, c, terminate))
145 if (c == '/' && !--p_value)
155 * Generally we prefer the shorter name, especially
156 * if the other one is just a variation of that with
157 * something else tacked on to the end (ie "file.orig"
161 int deflen = strlen(def);
162 if (deflen < len && !strncmp(start, def, deflen))
166 name = xmalloc(len + 1);
167 memcpy(name, start, len);
174 * Get the name etc info from the --/+++ lines of a traditional patch header
176 * NOTE! This hardcodes "-p1" behaviour in filename detection.
178 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
179 * files, we can happily check the index for a match, but for creating a
180 * new file we should try to match whatever "patch" does. I have no idea.
182 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
187 first += 4; // skip "--- "
188 second += 4; // skip "+++ "
189 if (is_dev_null(first)) {
191 patch->is_delete = 0;
192 name = find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB);
193 patch->new_name = name;
194 } else if (is_dev_null(second)) {
196 patch->is_delete = 1;
197 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
198 patch->old_name = name;
200 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
201 name = find_name(second, name, p_value, TERM_SPACE | TERM_TAB);
202 patch->old_name = patch->new_name = name;
205 die("unable to find filename in patch at line %d", linenr);
208 static int gitdiff_hdrend(const char *line, struct patch *patch)
214 * We're anal about diff header consistency, to make
215 * sure that we don't end up having strange ambiguous
216 * patches floating around.
218 * As a result, gitdiff_{old|new}name() will check
219 * their names against any previous information, just
222 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
227 if (!orig_name && !isnull)
228 return find_name(line, NULL, 1, 0);
236 die("git-apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
249 if (memcmp(line, name, len) || line[len] != '\n')
253 die("git-apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
257 static int gitdiff_oldname(const char *line, struct patch *patch)
259 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
263 static int gitdiff_newname(const char *line, struct patch *patch)
265 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
269 static int gitdiff_oldmode(const char *line, struct patch *patch)
271 patch->old_mode = strtoul(line, NULL, 8);
275 static int gitdiff_newmode(const char *line, struct patch *patch)
277 patch->new_mode = strtoul(line, NULL, 8);
281 static int gitdiff_delete(const char *line, struct patch *patch)
283 patch->is_delete = 1;
284 patch->old_name = patch->def_name;
285 return gitdiff_oldmode(line, patch);
288 static int gitdiff_newfile(const char *line, struct patch *patch)
291 patch->new_name = patch->def_name;
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)
325 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
330 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
332 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
338 * This is normal for a diff that doesn't change anything: we'll fall through
339 * into the next diff. Tell the parser to break out.
341 static int gitdiff_unrecognized(const char *line, struct patch *patch)
346 static char *git_header_name(char *line)
364 * We don't accept absolute paths (/dev/null) as possibly valid
370 * Accept a name only if it shows up twice, exactly the same
373 for (len = 0 ; ; len++) {
390 if (second[len] == '\n' && !memcmp(name, second, len)) {
391 char *ret = xmalloc(len + 1);
392 memcpy(ret, name, len);
401 /* Verify that we recognize the lines following a git header */
402 static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
404 unsigned long offset;
406 /* A git diff has explicit new/delete information, so we don't guess */
408 patch->is_delete = 0;
411 * Some things may not have the old name in the
412 * rest of the headers anywhere (pure mode changes,
413 * or removing or adding empty files), so we get
414 * the default name from the header.
416 patch->def_name = git_header_name(line + strlen("diff --git "));
421 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
422 static const struct opentry {
424 int (*fn)(const char *, struct patch *);
426 { "@@ -", gitdiff_hdrend },
427 { "--- ", gitdiff_oldname },
428 { "+++ ", gitdiff_newname },
429 { "old mode ", gitdiff_oldmode },
430 { "new mode ", gitdiff_newmode },
431 { "deleted file mode ", gitdiff_delete },
432 { "new file mode ", gitdiff_newfile },
433 { "copy from ", gitdiff_copysrc },
434 { "copy to ", gitdiff_copydst },
435 { "rename old ", gitdiff_renamesrc },
436 { "rename new ", gitdiff_renamedst },
437 { "rename from ", gitdiff_renamesrc },
438 { "rename to ", gitdiff_renamedst },
439 { "similarity index ", gitdiff_similarity },
440 { "dissimilarity index ", gitdiff_dissimilarity },
441 { "", gitdiff_unrecognized },
445 len = linelen(line, size);
446 if (!len || line[len-1] != '\n')
448 for (i = 0; i < sizeof(optable) / sizeof(optable[0]); i++) {
449 const struct opentry *p = optable + i;
450 int oplen = strlen(p->str);
451 if (len < oplen || memcmp(p->str, line, oplen))
453 if (p->fn(line + oplen, patch) < 0)
462 static int parse_num(const char *line, unsigned long *p)
468 *p = strtoul(line, &ptr, 10);
472 static int parse_range(const char *line, int len, int offset, const char *expect,
473 unsigned long *p1, unsigned long *p2)
477 if (offset < 0 || offset >= len)
482 digits = parse_num(line, p1);
492 digits = parse_num(line+1, p2);
504 if (memcmp(line, expect, ex))
511 * Parse a unified diff fragment header of the
512 * form "@@ -a,b +c,d @@"
514 static int parse_fragment_header(char *line, int len, struct fragment *fragment)
518 if (!len || line[len-1] != '\n')
521 /* Figure out the number of lines in a fragment */
522 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
523 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
528 static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
530 unsigned long offset, len;
532 patch->is_rename = patch->is_copy = 0;
533 patch->is_new = patch->is_delete = -1;
534 patch->old_mode = patch->new_mode = 0;
535 patch->old_name = patch->new_name = NULL;
536 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
537 unsigned long nextlen;
539 len = linelen(line, size);
543 /* Testing this early allows us to take a few shortcuts.. */
548 * Make sure we don't find any unconnected patch fragmants.
549 * That's a sign that we didn't find a header, and that a
550 * patch has become corrupted/broken up.
552 if (!memcmp("@@ -", line, 4)) {
553 struct fragment dummy;
554 if (parse_fragment_header(line, len, &dummy) < 0)
556 error("patch fragment without header at line %d: %.*s", linenr, (int)len-1, line);
563 * Git patch? It might not have a real patch, just a rename
564 * or mode change, so we handle that specially
566 if (!memcmp("diff --git ", line, 11)) {
567 int git_hdr_len = parse_git_header(line, len, size, patch);
568 if (git_hdr_len <= len)
570 if (!patch->old_name && !patch->new_name) {
571 if (!patch->def_name)
572 die("git diff header lacks filename information (line %d)", linenr);
573 patch->old_name = patch->new_name = patch->def_name;
575 *hdrsize = git_hdr_len;
579 /** --- followed by +++ ? */
580 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
584 * We only accept unified patches, so we want it to
585 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
588 nextlen = linelen(line + len, size - len);
589 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
592 /* Ok, we'll consider it a patch */
593 parse_traditional_patch(line, line+len, patch);
594 *hdrsize = len + nextlen;
602 * Parse a unified diff. Note that this really needs
603 * to parse each fragment separately, since the only
604 * way to know the difference between a "---" that is
605 * part of a patch, and a "---" that starts the next
606 * patch is to look at the line counts..
608 static int parse_fragment(char *line, unsigned long size, struct patch *patch, struct fragment *fragment)
611 int len = linelen(line, size), offset;
612 unsigned long oldlines, newlines;
614 offset = parse_fragment_header(line, len, fragment);
617 oldlines = fragment->oldlines;
618 newlines = fragment->newlines;
620 if (patch->is_new < 0) {
621 patch->is_new = !oldlines;
623 patch->old_name = NULL;
625 if (patch->is_delete < 0) {
626 patch->is_delete = !newlines;
628 patch->new_name = NULL;
631 if (patch->is_new != !oldlines)
632 return error("new file depends on old contents");
633 if (patch->is_delete != !newlines) {
635 return error("deleted file still has contents");
636 fprintf(stderr, "** warning: file %s becomes empty but is not deleted\n", patch->new_name);
639 /* Parse the thing.. */
644 for (offset = len; size > 0; offset += len, size -= len, line += len, linenr++) {
645 if (!oldlines && !newlines)
647 len = linelen(line, size);
648 if (!len || line[len-1] != '\n')
666 /* We allow "\ No newline at end of file". Depending
667 * on locale settings when the patch was produced we
668 * don't know what this line looks like. The only
669 * thing we do know is that it begins with "\ ".
670 * Checking for 12 is just for sanity check -- any
671 * l10n of "\ No newline..." is at least that long.
674 if (len < 12 || memcmp(line, "\\ ", 2))
679 /* If a fragment ends with an incomplete line, we failed to include
680 * it in the above loop because we hit oldlines == newlines == 0
683 if (12 < size && !memcmp(line, "\\ ", 2))
684 offset += linelen(line, size);
686 patch->lines_added += added;
687 patch->lines_deleted += deleted;
691 static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
693 unsigned long offset = 0;
694 struct fragment **fragp = &patch->fragments;
696 while (size > 4 && !memcmp(line, "@@ -", 4)) {
697 struct fragment *fragment;
700 fragment = xmalloc(sizeof(*fragment));
701 memset(fragment, 0, sizeof(*fragment));
702 len = parse_fragment(line, size, patch, fragment);
704 die("corrupt patch at line %d", linenr);
706 fragment->patch = line;
707 fragment->size = len;
710 fragp = &fragment->next;
719 static inline int metadata_changes(struct patch *patch)
721 return patch->is_rename > 0 ||
722 patch->is_copy > 0 ||
725 (patch->old_mode && patch->new_mode &&
726 patch->old_mode != patch->new_mode);
729 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
731 int hdrsize, patchsize;
732 int offset = find_header(buffer, size, &hdrsize, patch);
737 patchsize = parse_single_patch(buffer + offset + hdrsize, size - offset - hdrsize, patch);
739 if (!patchsize && !metadata_changes(patch))
740 die("patch with only garbage at line %d", linenr);
742 return offset + hdrsize + patchsize;
745 static const char pluses[] = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
746 static const char minuses[]= "----------------------------------------------------------------------";
748 static void show_stats(struct patch *patch)
750 const char *prefix = "";
751 char *name = patch->new_name;
752 int len, max, add, del, total;
755 name = patch->old_name;
758 * "scale" the filename
769 slash = strchr(name, '/');
776 * scale the add/delete
782 add = patch->lines_added;
783 del = patch->lines_deleted;
786 if (max_change > 0) {
787 total = (total * max + max_change / 2) / max_change;
788 add = (add * max + max_change / 2) / max_change;
791 printf(" %s%-*s |%5d %.*s%.*s\n", prefix,
792 len, name, patch->lines_added + patch->lines_deleted,
793 add, pluses, del, minuses);
796 static int read_old_data(struct stat *st, const char *path, void *buf, unsigned long size)
801 switch (st->st_mode & S_IFMT) {
803 return readlink(path, buf, size);
805 fd = open(path, O_RDONLY);
807 return error("unable to open %s", path);
810 int ret = read(fd, buf + got, size - got);
828 static int find_offset(const char *buf, unsigned long size, const char *fragment, unsigned long fragsize, int line)
831 unsigned long start, backwards, forwards;
838 unsigned long offset = 0;
840 while (offset + fragsize <= size) {
841 if (buf[offset++] == '\n') {
849 /* Exact line number? */
850 if (!memcmp(buf + start, fragment, fragsize))
854 * There's probably some smart way to do this, but I'll leave
855 * that to the smart and beautiful people. I'm simple and stupid.
866 if (forwards + fragsize > size)
872 } while (backwards && buf[backwards-1] != '\n');
875 while (forwards + fragsize <= size) {
876 if (buf[forwards++] == '\n')
882 if (try + fragsize > size)
884 if (memcmp(buf + try, fragment, fragsize))
893 * We should start searching forward and backward.
904 static int apply_one_fragment(struct buffer_desc *desc, struct fragment *frag)
906 char *buf = desc->buffer;
907 const char *patch = frag->patch;
908 int offset, size = frag->size;
909 char *old = xmalloc(size);
910 char *new = xmalloc(size);
911 int oldsize = 0, newsize = 0;
914 int len = linelen(patch, size);
921 * "plen" is how much of the line we should use for
922 * the actual patch data. Normally we just remove the
923 * first character on the line, but if the line is
924 * followed by "\ No newline", then we also remove the
925 * last one (which is the newline, of course).
928 if (len < size && patch[len] == '\\')
933 memcpy(old + oldsize, patch + 1, plen);
937 /* Fall-through for ' ' */
939 memcpy(new + newsize, patch + 1, plen);
943 /* Ignore it, we already handled it */
952 offset = find_offset(buf, desc->size, old, oldsize, frag->newpos);
954 int diff = newsize - oldsize;
955 unsigned long size = desc->size + diff;
956 unsigned long alloc = desc->alloc;
961 buf = xrealloc(buf, alloc);
965 memmove(buf + offset + newsize, buf + offset + oldsize, size - offset - newsize);
966 memcpy(buf + offset, new, newsize);
975 static int apply_fragments(struct buffer_desc *desc, struct patch *patch)
977 struct fragment *frag = patch->fragments;
980 if (apply_one_fragment(desc, frag) < 0)
981 return error("patch failed: %s:%ld", patch->old_name, frag->oldpos);
987 static int apply_data(struct patch *patch, struct stat *st)
990 unsigned long size, alloc;
991 struct buffer_desc desc;
996 if (patch->old_name) {
999 buf = xmalloc(alloc);
1000 if (read_old_data(st, patch->old_name, buf, alloc) != size)
1001 return error("read of %s failed", patch->old_name);
1007 if (apply_fragments(&desc, patch) < 0)
1009 patch->result = desc.buffer;
1010 patch->resultsize = desc.size;
1012 if (patch->is_delete && patch->resultsize)
1013 return error("removal patch leaves file contents");
1018 static int check_patch(struct patch *patch)
1021 const char *old_name = patch->old_name;
1022 const char *new_name = patch->new_name;
1026 int stat_ret = lstat(old_name, &st);
1029 int pos = cache_name_pos(old_name, strlen(old_name));
1031 return error("%s: does not exist in index",
1034 struct checkout costate;
1035 if (errno != ENOENT)
1036 return error("%s: %s", old_name,
1039 costate.base_dir = "";
1040 costate.base_dir_len = 0;
1043 costate.not_new = 0;
1044 costate.refresh_cache = 1;
1045 if (checkout_entry(active_cache[pos],
1047 lstat(old_name, &st))
1051 changed = ce_match_stat(active_cache[pos], &st);
1053 return error("%s: does not match index",
1056 else if (stat_ret < 0)
1057 return error("%s: %s", old_name, strerror(errno));
1059 if (patch->is_new < 0)
1061 st.st_mode = ntohl(create_ce_mode(st.st_mode));
1062 if (!patch->old_mode)
1063 patch->old_mode = st.st_mode;
1064 if ((st.st_mode ^ patch->old_mode) & S_IFMT)
1065 return error("%s: wrong type", old_name);
1066 if (st.st_mode != patch->old_mode)
1067 fprintf(stderr, "warning: %s has type %o, expected %o\n",
1068 old_name, st.st_mode, patch->old_mode);
1071 if (new_name && (patch->is_new | patch->is_rename | patch->is_copy)) {
1072 if (check_index && cache_name_pos(new_name, strlen(new_name)) >= 0)
1073 return error("%s: already exists in index", new_name);
1074 if (!lstat(new_name, &st))
1075 return error("%s: already exists in working directory", new_name);
1076 if (errno != ENOENT)
1077 return error("%s: %s", new_name, strerror(errno));
1078 if (!patch->new_mode) {
1080 patch->new_mode = S_IFREG | 0644;
1082 patch->new_mode = patch->old_mode;
1086 if (new_name && old_name) {
1087 int same = !strcmp(old_name, new_name);
1088 if (!patch->new_mode)
1089 patch->new_mode = patch->old_mode;
1090 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
1091 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
1092 patch->new_mode, new_name, patch->old_mode,
1093 same ? "" : " of ", same ? "" : old_name);
1096 if (apply_data(patch, &st) < 0)
1097 return error("%s: patch does not apply", old_name);
1101 static int check_patch_list(struct patch *patch)
1105 for (;patch ; patch = patch->next)
1106 error |= check_patch(patch);
1110 static void show_file(int c, unsigned int mode, const char *name)
1112 printf("%c %o %s\n", c, mode, name);
1115 static void show_file_list(struct patch *patch)
1117 for (;patch ; patch = patch->next) {
1118 if (patch->is_rename) {
1119 show_file('-', patch->old_mode, patch->old_name);
1120 show_file('+', patch->new_mode, patch->new_name);
1123 if (patch->is_copy || patch->is_new) {
1124 show_file('+', patch->new_mode, patch->new_name);
1127 if (patch->is_delete) {
1128 show_file('-', patch->old_mode, patch->old_name);
1131 if (patch->old_mode && patch->new_mode && patch->old_mode != patch->new_mode) {
1132 printf("M %o:%o %s\n", patch->old_mode, patch->new_mode, patch->old_name);
1135 printf("M %o %s\n", patch->old_mode, patch->old_name);
1139 static void stat_patch_list(struct patch *patch)
1141 int files, adds, dels;
1143 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
1145 adds += patch->lines_added;
1146 dels += patch->lines_deleted;
1150 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
1153 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
1156 printf(" %s mode %06o %s\n", newdelete, mode, name);
1158 printf(" %s %s\n", newdelete, name);
1161 static void show_mode_change(struct patch *p, int show_name)
1163 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
1165 printf(" mode change %06o => %06o %s\n",
1166 p->old_mode, p->new_mode, p->new_name);
1168 printf(" mode change %06o => %06o\n",
1169 p->old_mode, p->new_mode);
1173 static void show_rename_copy(struct patch *p)
1175 const char *renamecopy = p->is_rename ? "rename" : "copy";
1176 const char *old, *new;
1178 /* Find common prefix */
1182 const char *slash_old, *slash_new;
1183 slash_old = strchr(old, '/');
1184 slash_new = strchr(new, '/');
1187 slash_old - old != slash_new - new ||
1188 memcmp(old, new, slash_new - new))
1190 old = slash_old + 1;
1191 new = slash_new + 1;
1193 /* p->old_name thru old is the common prefix, and old and new
1194 * through the end of names are renames
1196 if (old != p->old_name)
1197 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
1198 (int)(old - p->old_name), p->old_name,
1199 old, new, p->score);
1201 printf(" %s %s => %s (%d%%)\n", renamecopy,
1202 p->old_name, p->new_name, p->score);
1203 show_mode_change(p, 0);
1206 static void summary_patch_list(struct patch *patch)
1210 for (p = patch; p; p = p->next) {
1212 show_file_mode_name("create", p->new_mode, p->new_name);
1213 else if (p->is_delete)
1214 show_file_mode_name("delete", p->old_mode, p->old_name);
1216 if (p->is_rename || p->is_copy)
1217 show_rename_copy(p);
1220 printf(" rewrite %s (%d%%)\n",
1221 p->new_name, p->score);
1222 show_mode_change(p, 0);
1225 show_mode_change(p, 1);
1231 static void patch_stats(struct patch *patch)
1233 int lines = patch->lines_added + patch->lines_deleted;
1235 if (lines > max_change)
1237 if (patch->old_name) {
1238 int len = strlen(patch->old_name);
1242 if (patch->new_name) {
1243 int len = strlen(patch->new_name);
1249 static void remove_file(struct patch *patch)
1252 if (remove_file_from_cache(patch->old_name) < 0)
1253 die("unable to remove %s from index", patch->old_name);
1255 unlink(patch->old_name);
1258 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
1261 struct cache_entry *ce;
1262 int namelen = strlen(path);
1263 unsigned ce_size = cache_entry_size(namelen);
1268 ce = xmalloc(ce_size);
1269 memset(ce, 0, ce_size);
1270 memcpy(ce->name, path, namelen);
1271 ce->ce_mode = create_ce_mode(mode);
1272 ce->ce_flags = htons(namelen);
1273 if (lstat(path, &st) < 0)
1274 die("unable to stat newly created file %s", path);
1275 fill_stat_cache_info(ce, &st);
1276 if (write_sha1_file(buf, size, "blob", ce->sha1) < 0)
1277 die("unable to create backing store for newly created file %s", path);
1278 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
1279 die("unable to add cache entry for %s", path);
1282 static void create_subdirectories(const char *path)
1284 int len = strlen(path);
1285 char *buf = xmalloc(len + 1);
1286 const char *slash = path;
1288 while ((slash = strchr(slash+1, '/')) != NULL) {
1290 memcpy(buf, path, len);
1292 if (mkdir(buf, 0777) < 0) {
1293 if (errno != EEXIST)
1300 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
1305 return symlink(buf, path);
1306 fd = open(path, O_CREAT | O_EXCL | O_WRONLY | O_TRUNC, (mode & 0100) ? 0777 : 0666);
1310 int written = write(fd, buf, size);
1312 if (errno == EINTR || errno == EAGAIN)
1314 die("writing file %s: %s", path, strerror(errno));
1317 die("out of space writing file %s", path);
1322 die("closing file %s: %s", path, strerror(errno));
1327 * We optimistically assume that the directories exist,
1328 * which is true 99% of the time anyway. If they don't,
1329 * we create them and try again.
1331 static void create_one_file(const char *path, unsigned mode, const char *buf, unsigned long size)
1333 if (!try_create_file(path, mode, buf, size))
1336 if (errno == ENOENT) {
1337 create_subdirectories(path);
1338 if (!try_create_file(path, mode, buf, size))
1342 if (errno == EEXIST) {
1343 unsigned int nr = getpid();
1346 const char *newpath;
1347 newpath = mkpath("%s~%u", path, nr);
1348 if (!try_create_file(newpath, mode, buf, size)) {
1349 if (!rename(newpath, path))
1354 if (errno != EEXIST)
1358 die("unable to write file %s mode %o", path, mode);
1361 static void create_file(struct patch *patch)
1363 const char *path = patch->new_name;
1364 unsigned mode = patch->new_mode;
1365 unsigned long size = patch->resultsize;
1366 char *buf = patch->result;
1369 mode = S_IFREG | 0644;
1370 create_one_file(path, mode, buf, size);
1371 add_index_file(path, mode, buf, size);
1374 static void write_out_one_result(struct patch *patch)
1376 if (patch->is_delete > 0) {
1380 if (patch->is_new > 0 || patch->is_copy) {
1385 * Rename or modification boils down to the same
1386 * thing: remove the old, write the new
1392 static void write_out_results(struct patch *list, int skipped_patch)
1394 if (!list && !skipped_patch)
1398 write_out_one_result(list);
1403 static struct cache_file cache_file;
1405 static struct excludes {
1406 struct excludes *next;
1410 static int use_patch(struct patch *p)
1412 const char *pathname = p->new_name ? p->new_name : p->old_name;
1413 struct excludes *x = excludes;
1415 if (fnmatch(x->path, pathname, 0) == 0)
1422 static int apply_patch(int fd)
1425 unsigned long offset, size;
1426 char *buffer = read_patch_file(fd, &size);
1427 struct patch *list = NULL, **listp = &list;
1428 int skipped_patch = 0;
1434 struct patch *patch;
1437 patch = xmalloc(sizeof(*patch));
1438 memset(patch, 0, sizeof(*patch));
1439 nr = parse_chunk(buffer + offset, size, patch);
1442 if (use_patch(patch)) {
1445 listp = &patch->next;
1447 /* perhaps free it a bit better? */
1456 write_index = check_index && apply;
1458 newfd = hold_index_file_for_update(&cache_file, get_index_file());
1460 if (read_cache() < 0)
1461 die("unable to read index file");
1464 if ((check || apply) && check_patch_list(list) < 0)
1468 write_out_results(list, skipped_patch);
1471 if (write_cache(newfd, active_cache, active_nr) ||
1472 commit_index_file(&cache_file))
1473 die("Unable to write new cachefile");
1477 show_file_list(list);
1480 stat_patch_list(list);
1483 summary_patch_list(list);
1489 int main(int argc, char **argv)
1494 for (i = 1; i < argc; i++) {
1495 const char *arg = argv[i];
1498 if (!strcmp(arg, "-")) {
1503 if (!strncmp(arg, "--exclude=", 10)) {
1504 struct excludes *x = xmalloc(sizeof(*x));
1510 if (!strcmp(arg, "--stat")) {
1515 if (!strcmp(arg, "--summary")) {
1520 if (!strcmp(arg, "--check")) {
1525 if (!strcmp(arg, "--index")) {
1529 if (!strcmp(arg, "--apply")) {
1533 if (!strcmp(arg, "--show-files")) {
1537 fd = open(arg, O_RDONLY);