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
22 // --check turns on checking that the working tree matches the
23 // files that are being modified, but doesn't apply the patch
24 // --stat does just a diffstat, and doesn't actually apply
25 // --show-files shows the directory changes
27 static int merge_patch = 1;
28 static int check_index = 0;
29 static int write_index = 0;
30 static int diffstat = 0;
31 static int summary = 0;
34 static int show_files = 0;
35 static const char apply_usage[] = "git-apply [--stat] [--summary] [--check] [--show-files] <patch>";
38 * For "diff-stat" like behaviour, we keep track of the biggest change
39 * we've seen, and the longest filename. That allows us to do simple
42 static int max_change, max_len;
45 * Various "current state", notably line numbers and what
46 * file (and how) we're patching right now.. The "is_xxxx"
47 * things are flags, where -1 means "don't know yet".
49 static int linenr = 1;
52 unsigned long oldpos, oldlines;
53 unsigned long newpos, newlines;
56 struct fragment *next;
60 char *new_name, *old_name, *def_name;
61 unsigned int old_mode, new_mode;
62 int is_rename, is_copy, is_new, is_delete;
63 int lines_added, lines_deleted;
65 struct fragment *fragments;
67 unsigned long resultsize;
71 #define CHUNKSIZE (8192)
74 static void *read_patch_file(int fd, unsigned long *sizep)
76 unsigned long size = 0, alloc = CHUNKSIZE;
77 void *buffer = xmalloc(alloc);
80 int nr = alloc - size;
83 buffer = xrealloc(buffer, alloc);
86 nr = read(fd, buffer + size, nr);
92 die("git-apply: read returned %s", strerror(errno));
99 * Make sure that we have some slop in the buffer
100 * so that we can do speculative "memcmp" etc, and
101 * see to it that it is NUL-filled.
103 if (alloc < size + SLOP)
104 buffer = xrealloc(buffer, size + SLOP);
105 memset(buffer + size, 0, SLOP);
109 static unsigned long linelen(const char *buffer, unsigned long size)
111 unsigned long len = 0;
114 if (*buffer++ == '\n')
120 static int is_dev_null(const char *str)
122 return !memcmp("/dev/null", str, 9) && isspace(str[9]);
128 static int name_terminate(const char *name, int namelen, int c, int terminate)
130 if (c == ' ' && !(terminate & TERM_SPACE))
132 if (c == '\t' && !(terminate & TERM_TAB))
138 static char * find_name(const char *line, char *def, int p_value, int terminate)
141 const char *start = line;
150 if (name_terminate(start, line-start, c, terminate))
154 if (c == '/' && !--p_value)
164 * Generally we prefer the shorter name, especially
165 * if the other one is just a variation of that with
166 * something else tacked on to the end (ie "file.orig"
170 int deflen = strlen(def);
171 if (deflen < len && !strncmp(start, def, deflen))
175 name = xmalloc(len + 1);
176 memcpy(name, start, len);
183 * Get the name etc info from the --/+++ lines of a traditional patch header
185 * NOTE! This hardcodes "-p1" behaviour in filename detection.
187 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
188 * files, we can happily check the index for a match, but for creating a
189 * new file we should try to match whatever "patch" does. I have no idea.
191 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
196 first += 4; // skip "--- "
197 second += 4; // skip "+++ "
198 if (is_dev_null(first)) {
200 patch->is_delete = 0;
201 name = find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB);
202 patch->new_name = name;
203 } else if (is_dev_null(second)) {
205 patch->is_delete = 1;
206 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
207 patch->old_name = name;
209 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
210 name = find_name(second, name, p_value, TERM_SPACE | TERM_TAB);
211 patch->old_name = patch->new_name = name;
214 die("unable to find filename in patch at line %d", linenr);
217 static int gitdiff_hdrend(const char *line, struct patch *patch)
223 * We're anal about diff header consistency, to make
224 * sure that we don't end up having strange ambiguous
225 * patches floating around.
227 * As a result, gitdiff_{old|new}name() will check
228 * their names against any previous information, just
231 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
236 if (!orig_name && !isnull)
237 return find_name(line, NULL, 1, 0);
245 die("git-apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
258 if (memcmp(line, name, len) || line[len] != '\n')
262 die("git-apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
266 static int gitdiff_oldname(const char *line, struct patch *patch)
268 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
272 static int gitdiff_newname(const char *line, struct patch *patch)
274 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
278 static int gitdiff_oldmode(const char *line, struct patch *patch)
280 patch->old_mode = strtoul(line, NULL, 8);
284 static int gitdiff_newmode(const char *line, struct patch *patch)
286 patch->new_mode = strtoul(line, NULL, 8);
290 static int gitdiff_delete(const char *line, struct patch *patch)
292 patch->is_delete = 1;
293 patch->old_name = patch->def_name;
294 return gitdiff_oldmode(line, patch);
297 static int gitdiff_newfile(const char *line, struct patch *patch)
300 patch->new_name = patch->def_name;
301 return gitdiff_newmode(line, patch);
304 static int gitdiff_copysrc(const char *line, struct patch *patch)
307 patch->old_name = find_name(line, NULL, 0, 0);
311 static int gitdiff_copydst(const char *line, struct patch *patch)
314 patch->new_name = find_name(line, NULL, 0, 0);
318 static int gitdiff_renamesrc(const char *line, struct patch *patch)
320 patch->is_rename = 1;
321 patch->old_name = find_name(line, NULL, 0, 0);
325 static int gitdiff_renamedst(const char *line, struct patch *patch)
327 patch->is_rename = 1;
328 patch->new_name = find_name(line, NULL, 0, 0);
332 static int gitdiff_similarity(const char *line, struct patch *patch)
334 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
339 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
341 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
347 * This is normal for a diff that doesn't change anything: we'll fall through
348 * into the next diff. Tell the parser to break out.
350 static int gitdiff_unrecognized(const char *line, struct patch *patch)
355 static char *git_header_name(char *line)
373 * We don't accept absolute paths (/dev/null) as possibly valid
379 * Accept a name only if it shows up twice, exactly the same
382 for (len = 0 ; ; len++) {
399 if (second[len] == '\n' && !memcmp(name, second, len)) {
400 char *ret = xmalloc(len + 1);
401 memcpy(ret, name, len);
410 /* Verify that we recognize the lines following a git header */
411 static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
413 unsigned long offset;
415 /* A git diff has explicit new/delete information, so we don't guess */
417 patch->is_delete = 0;
420 * Some things may not have the old name in the
421 * rest of the headers anywhere (pure mode changes,
422 * or removing or adding empty files), so we get
423 * the default name from the header.
425 patch->def_name = git_header_name(line + strlen("diff --git "));
430 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
431 static const struct opentry {
433 int (*fn)(const char *, struct patch *);
435 { "@@ -", gitdiff_hdrend },
436 { "--- ", gitdiff_oldname },
437 { "+++ ", gitdiff_newname },
438 { "old mode ", gitdiff_oldmode },
439 { "new mode ", gitdiff_newmode },
440 { "deleted file mode ", gitdiff_delete },
441 { "new file mode ", gitdiff_newfile },
442 { "copy from ", gitdiff_copysrc },
443 { "copy to ", gitdiff_copydst },
444 { "rename old ", gitdiff_renamesrc },
445 { "rename new ", gitdiff_renamedst },
446 { "rename from ", gitdiff_renamesrc },
447 { "rename to ", gitdiff_renamedst },
448 { "similarity index ", gitdiff_similarity },
449 { "dissimilarity index ", gitdiff_dissimilarity },
450 { "", gitdiff_unrecognized },
454 len = linelen(line, size);
455 if (!len || line[len-1] != '\n')
457 for (i = 0; i < sizeof(optable) / sizeof(optable[0]); i++) {
458 const struct opentry *p = optable + i;
459 int oplen = strlen(p->str);
460 if (len < oplen || memcmp(p->str, line, oplen))
462 if (p->fn(line + oplen, patch) < 0)
471 static int parse_num(const char *line, unsigned long *p)
477 *p = strtoul(line, &ptr, 10);
481 static int parse_range(const char *line, int len, int offset, const char *expect,
482 unsigned long *p1, unsigned long *p2)
486 if (offset < 0 || offset >= len)
491 digits = parse_num(line, p1);
501 digits = parse_num(line+1, p2);
513 if (memcmp(line, expect, ex))
520 * Parse a unified diff fragment header of the
521 * form "@@ -a,b +c,d @@"
523 static int parse_fragment_header(char *line, int len, struct fragment *fragment)
527 if (!len || line[len-1] != '\n')
530 /* Figure out the number of lines in a fragment */
531 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
532 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
537 static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
539 unsigned long offset, len;
541 patch->is_rename = patch->is_copy = 0;
542 patch->is_new = patch->is_delete = -1;
543 patch->old_mode = patch->new_mode = 0;
544 patch->old_name = patch->new_name = NULL;
545 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
546 unsigned long nextlen;
548 len = linelen(line, size);
552 /* Testing this early allows us to take a few shortcuts.. */
557 * Make sure we don't find any unconnected patch fragmants.
558 * That's a sign that we didn't find a header, and that a
559 * patch has become corrupted/broken up.
561 if (!memcmp("@@ -", line, 4)) {
562 struct fragment dummy;
563 if (parse_fragment_header(line, len, &dummy) < 0)
565 error("patch fragment without header at line %d: %.*s", linenr, len-1, line);
572 * Git patch? It might not have a real patch, just a rename
573 * or mode change, so we handle that specially
575 if (!memcmp("diff --git ", line, 11)) {
576 int git_hdr_len = parse_git_header(line, len, size, patch);
577 if (git_hdr_len <= len)
579 if (!patch->old_name && !patch->new_name) {
580 if (!patch->def_name)
581 die("git diff header lacks filename information (line %d)", linenr);
582 patch->old_name = patch->new_name = patch->def_name;
584 *hdrsize = git_hdr_len;
588 /** --- followed by +++ ? */
589 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
593 * We only accept unified patches, so we want it to
594 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
597 nextlen = linelen(line + len, size - len);
598 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
601 /* Ok, we'll consider it a patch */
602 parse_traditional_patch(line, line+len, patch);
603 *hdrsize = len + nextlen;
611 * Parse a unified diff. Note that this really needs
612 * to parse each fragment separately, since the only
613 * way to know the difference between a "---" that is
614 * part of a patch, and a "---" that starts the next
615 * patch is to look at the line counts..
617 static int parse_fragment(char *line, unsigned long size, struct patch *patch, struct fragment *fragment)
620 int len = linelen(line, size), offset;
621 unsigned long oldlines, newlines;
623 offset = parse_fragment_header(line, len, fragment);
626 oldlines = fragment->oldlines;
627 newlines = fragment->newlines;
629 if (patch->is_new < 0) {
630 patch->is_new = !oldlines;
632 patch->old_name = NULL;
634 if (patch->is_delete < 0) {
635 patch->is_delete = !newlines;
637 patch->new_name = NULL;
640 if (patch->is_new != !oldlines)
641 return error("new file depends on old contents");
642 if (patch->is_delete != !newlines) {
644 return error("deleted file still has contents");
645 fprintf(stderr, "** warning: file %s becomes empty but is not deleted\n", patch->new_name);
648 /* Parse the thing.. */
653 for (offset = len; size > 0; offset += len, size -= len, line += len, linenr++) {
654 if (!oldlines && !newlines)
656 len = linelen(line, size);
657 if (!len || line[len-1] != '\n')
674 /* We allow "\ No newline at end of file" */
676 if (len < 12 || memcmp(line, "\\ No newline", 12))
681 patch->lines_added += added;
682 patch->lines_deleted += deleted;
686 static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
688 unsigned long offset = 0;
689 struct fragment **fragp = &patch->fragments;
691 while (size > 4 && !memcmp(line, "@@ -", 4)) {
692 struct fragment *fragment;
695 fragment = xmalloc(sizeof(*fragment));
696 memset(fragment, 0, sizeof(*fragment));
697 len = parse_fragment(line, size, patch, fragment);
699 die("corrupt patch at line %d", linenr);
701 fragment->patch = line;
702 fragment->size = len;
705 fragp = &fragment->next;
714 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
716 int hdrsize, patchsize;
717 int offset = find_header(buffer, size, &hdrsize, patch);
722 patchsize = parse_single_patch(buffer + offset + hdrsize, size - offset - hdrsize, patch);
724 return offset + hdrsize + patchsize;
727 const char pluses[] = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
728 const char minuses[]= "----------------------------------------------------------------------";
730 static void show_stats(struct patch *patch)
732 char *name = patch->new_name;
733 int len, max, add, del, total;
736 name = patch->old_name;
739 * "scale" the filename
750 * scale the add/delete
756 add = patch->lines_added;
757 del = patch->lines_deleted;
760 if (max_change > 0) {
761 total = (total * max + max_change / 2) / max_change;
762 add = (add * max + max_change / 2) / max_change;
765 printf(" %-*s |%5d %.*s%.*s\n",
766 len, name, patch->lines_added + patch->lines_deleted,
767 add, pluses, del, minuses);
770 static int read_old_data(struct stat *st, const char *path, void *buf, unsigned long size)
775 switch (st->st_mode & S_IFMT) {
777 return readlink(path, buf, size);
779 fd = open(path, O_RDONLY);
781 return error("unable to open %s", path);
784 int ret = read(fd, buf + got, size - got);
802 static int find_offset(const char *buf, unsigned long size, const char *fragment, unsigned long fragsize, int line)
805 unsigned long start, backwards, forwards;
812 unsigned long offset = 0;
814 while (offset + fragsize <= size) {
815 if (buf[offset++] == '\n') {
823 /* Exact line number? */
824 if (!memcmp(buf + start, fragment, fragsize))
828 * There's probably some smart way to do this, but I'll leave
829 * that to the smart and beautiful people. I'm simple and stupid.
840 if (forwards + fragsize > size)
846 } while (backwards && buf[backwards-1] != '\n');
849 while (forwards + fragsize <= size) {
850 if (buf[forwards++] == '\n')
856 if (try + fragsize > size)
858 if (memcmp(buf + try, fragment, fragsize))
863 fprintf(stderr, "Fragment applied at offset %d\n", n);
868 * We should start searching forward and backward.
879 static int apply_one_fragment(struct buffer_desc *desc, struct fragment *frag)
881 char *buf = desc->buffer;
882 const char *patch = frag->patch;
883 int offset, size = frag->size;
884 char *old = xmalloc(size);
885 char *new = xmalloc(size);
886 int oldsize = 0, newsize = 0;
889 int len = linelen(patch, size);
896 * "plen" is how much of the line we should use for
897 * the actual patch data. Normally we just remove the
898 * first character on the line, but if the line is
899 * followed by "\ No newline", then we also remove the
900 * last one (which is the newline, of course).
903 if (len > size && patch[len] == '\\')
908 memcpy(old + oldsize, patch + 1, plen);
912 /* Fall-through for ' ' */
914 memcpy(new + newsize, patch + 1, plen);
918 /* Ignore it, we already handled it */
927 offset = find_offset(buf, desc->size, old, oldsize, frag->newpos);
929 int diff = newsize - oldsize;
930 unsigned long size = desc->size + diff;
931 unsigned long alloc = desc->alloc;
936 buf = xrealloc(buf, alloc);
940 memmove(buf + offset + newsize, buf + offset + oldsize, size - offset - newsize);
941 memcpy(buf + offset, new, newsize);
950 static int apply_fragments(struct buffer_desc *desc, struct patch *patch)
952 struct fragment *frag = patch->fragments;
955 if (apply_one_fragment(desc, frag) < 0)
956 return error("patch failed: %s:%d", patch->old_name, frag->oldpos);
962 static int apply_data(struct patch *patch, struct stat *st)
965 unsigned long size, alloc;
966 struct buffer_desc desc;
971 if (patch->old_name) {
974 buf = xmalloc(alloc);
975 if (read_old_data(st, patch->old_name, buf, alloc) != size)
976 return error("read of %s failed", patch->old_name);
982 if (apply_fragments(&desc, patch) < 0)
984 patch->result = desc.buffer;
985 patch->resultsize = desc.size;
987 if (patch->is_delete && patch->resultsize)
988 return error("removal patch leaves file contents");
993 static int check_patch(struct patch *patch)
996 const char *old_name = patch->old_name;
997 const char *new_name = patch->new_name;
1002 if (lstat(old_name, &st) < 0)
1003 return error("%s: %s", old_name, strerror(errno));
1005 int pos = cache_name_pos(old_name, strlen(old_name));
1007 return error("%s: does not exist in index", old_name);
1008 changed = ce_match_stat(active_cache[pos], &st);
1010 return error("%s: does not match index", old_name);
1012 if (patch->is_new < 0)
1014 st.st_mode = ntohl(create_ce_mode(st.st_mode));
1015 if (!patch->old_mode)
1016 patch->old_mode = st.st_mode;
1017 if ((st.st_mode ^ patch->old_mode) & S_IFMT)
1018 return error("%s: wrong type", old_name);
1019 if (st.st_mode != patch->old_mode)
1020 fprintf(stderr, "warning: %s has type %o, expected %o\n",
1021 old_name, st.st_mode, patch->old_mode);
1024 if (new_name && (patch->is_new | patch->is_rename | patch->is_copy)) {
1025 if (check_index && cache_name_pos(new_name, strlen(new_name)) >= 0)
1026 return error("%s: already exists in index", new_name);
1027 if (!lstat(new_name, &st))
1028 return error("%s: already exists in working directory", new_name);
1029 if (errno != ENOENT)
1030 return error("%s: %s", new_name, strerror(errno));
1031 if (!patch->new_mode)
1032 patch->new_mode = S_IFREG | 0644;
1035 if (new_name && old_name) {
1036 int same = !strcmp(old_name, new_name);
1037 if (!patch->new_mode)
1038 patch->new_mode = patch->old_mode;
1039 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
1040 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
1041 patch->new_mode, new_name, patch->old_mode,
1042 same ? "" : " of ", same ? "" : old_name);
1045 if (apply_data(patch, &st) < 0)
1046 return error("%s: patch does not apply", old_name);
1050 static int check_patch_list(struct patch *patch)
1054 for (;patch ; patch = patch->next)
1055 error |= check_patch(patch);
1059 static void show_file(int c, unsigned int mode, const char *name)
1061 printf("%c %o %s\n", c, mode, name);
1064 static void show_file_list(struct patch *patch)
1066 for (;patch ; patch = patch->next) {
1067 if (patch->is_rename) {
1068 show_file('-', patch->old_mode, patch->old_name);
1069 show_file('+', patch->new_mode, patch->new_name);
1072 if (patch->is_copy || patch->is_new) {
1073 show_file('+', patch->new_mode, patch->new_name);
1076 if (patch->is_delete) {
1077 show_file('-', patch->old_mode, patch->old_name);
1080 if (patch->old_mode && patch->new_mode && patch->old_mode != patch->new_mode) {
1081 printf("M %o:%o %s\n", patch->old_mode, patch->new_mode, patch->old_name);
1084 printf("M %o %s\n", patch->old_mode, patch->old_name);
1088 static void stat_patch_list(struct patch *patch)
1090 int files, adds, dels;
1092 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
1094 adds += patch->lines_added;
1095 dels += patch->lines_deleted;
1099 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
1102 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
1105 printf(" %s mode %06o %s\n", newdelete, mode, name);
1107 printf(" %s %s\n", newdelete, name);
1110 static void show_mode_change(struct patch *p, int show_name)
1112 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
1114 printf(" mode change %06o => %06o %s\n",
1115 p->old_mode, p->new_mode, p->new_name);
1117 printf(" mode change %06o => %06o\n",
1118 p->old_mode, p->new_mode);
1122 static void show_rename_copy(struct patch *p)
1124 const char *renamecopy = p->is_rename ? "rename" : "copy";
1125 const char *old, *new;
1127 /* Find common prefix */
1131 const char *slash_old, *slash_new;
1132 slash_old = strchr(old, '/');
1133 slash_new = strchr(new, '/');
1136 slash_old - old != slash_new - new ||
1137 memcmp(old, new, slash_new - new))
1139 old = slash_old + 1;
1140 new = slash_new + 1;
1142 /* p->old_name thru old is the common prefix, and old and new
1143 * through the end of names are renames
1145 if (old != p->old_name)
1146 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
1147 old - p->old_name, p->old_name,
1148 old, new, p->score);
1150 printf(" %s %s => %s (%d%%)\n", renamecopy,
1151 p->old_name, p->new_name, p->score);
1152 show_mode_change(p, 0);
1155 static void summary_patch_list(struct patch *patch)
1159 for (p = patch; p; p = p->next) {
1161 show_file_mode_name("create", p->new_mode, p->new_name);
1162 else if (p->is_delete)
1163 show_file_mode_name("delete", p->old_mode, p->old_name);
1165 if (p->is_rename || p->is_copy)
1166 show_rename_copy(p);
1169 printf(" rewrite %s (%d%%)\n",
1170 p->new_name, p->score);
1171 show_mode_change(p, 0);
1174 show_mode_change(p, 1);
1180 static void patch_stats(struct patch *patch)
1182 int lines = patch->lines_added + patch->lines_deleted;
1184 if (lines > max_change)
1186 if (patch->old_name) {
1187 int len = strlen(patch->old_name);
1191 if (patch->new_name) {
1192 int len = strlen(patch->new_name);
1198 static void remove_file(struct patch *patch)
1201 if (remove_file_from_cache(patch->old_name) < 0)
1202 die("unable to remove %s from index", patch->old_name);
1204 unlink(patch->old_name);
1207 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
1210 struct cache_entry *ce;
1211 int namelen = strlen(path);
1212 unsigned ce_size = cache_entry_size(namelen);
1217 ce = xmalloc(ce_size);
1218 memset(ce, 0, ce_size);
1219 memcpy(ce->name, path, namelen);
1220 ce->ce_mode = create_ce_mode(mode);
1221 ce->ce_flags = htons(namelen);
1222 if (lstat(path, &st) < 0)
1223 die("unable to stat newly created file %s", path);
1224 fill_stat_cache_info(ce, &st);
1225 if (write_sha1_file(buf, size, "blob", ce->sha1) < 0)
1226 die("unable to create backing store for newly created file %s", path);
1227 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
1228 die("unable to add cache entry for %s", path);
1231 static void create_subdirectories(const char *path)
1233 int len = strlen(path);
1234 char *buf = xmalloc(len + 1);
1235 const char *slash = path;
1237 while ((slash = strchr(slash+1, '/')) != NULL) {
1239 memcpy(buf, path, len);
1241 if (mkdir(buf, 0755) < 0) {
1242 if (errno != EEXIST)
1250 * We optimistically assume that the directories exist,
1251 * which is true 99% of the time anyway. If they don't,
1252 * we create them and try again.
1254 static int create_regular_file(const char *path, unsigned int mode)
1256 int ret = open(path, O_WRONLY | O_CREAT | O_TRUNC, mode);
1258 if (ret < 0 && errno == ENOENT) {
1259 create_subdirectories(path);
1260 ret = open(path, O_WRONLY | O_CREAT | O_TRUNC, mode);
1265 static int create_symlink(const char *buf, const char *path)
1267 int ret = symlink(buf, path);
1269 if (ret < 0 && errno == ENOENT) {
1270 create_subdirectories(path);
1271 ret = symlink(buf, path);
1276 static void create_file(struct patch *patch)
1278 const char *path = patch->new_name;
1279 unsigned mode = patch->new_mode;
1280 unsigned long size = patch->resultsize;
1281 char *buf = patch->result;
1284 mode = S_IFREG | 0644;
1285 if (S_ISREG(mode)) {
1287 mode = (mode & 0100) ? 0777 : 0666;
1288 fd = create_regular_file(path, mode);
1290 die("unable to create file %s (%s)", path, strerror(errno));
1291 if (write(fd, buf, size) != size)
1292 die("unable to write file %s", path);
1294 add_index_file(path, mode, buf, size);
1297 if (S_ISLNK(mode)) {
1298 if (size && buf[size-1] == '\n')
1301 if (create_symlink(buf, path) < 0)
1302 die("unable to write symlink %s", path);
1303 add_index_file(path, mode, buf, size);
1306 die("unable to write file mode %o", mode);
1309 static void write_out_one_result(struct patch *patch)
1311 if (patch->is_delete > 0) {
1315 if (patch->is_new > 0 || patch->is_copy) {
1320 * Rename or modification boils down to the same
1321 * thing: remove the old, write the new
1327 static void write_out_results(struct patch *list)
1333 write_out_one_result(list);
1338 static struct cache_file cache_file;
1340 static int apply_patch(int fd)
1343 unsigned long offset, size;
1344 char *buffer = read_patch_file(fd, &size);
1345 struct patch *list = NULL, **listp = &list;
1351 struct patch *patch;
1354 patch = xmalloc(sizeof(*patch));
1355 memset(patch, 0, sizeof(*patch));
1356 nr = parse_chunk(buffer + offset, size, patch);
1361 listp = &patch->next;
1367 write_index = check_index && apply;
1369 newfd = hold_index_file_for_update(&cache_file, get_index_file());
1371 if (read_cache() < 0)
1372 die("unable to read index file");
1375 if ((check || apply) && check_patch_list(list) < 0)
1379 write_out_results(list);
1382 if (write_cache(newfd, active_cache, active_nr) ||
1383 commit_index_file(&cache_file))
1384 die("Unable to write new cachefile");
1388 show_file_list(list);
1391 stat_patch_list(list);
1394 summary_patch_list(list);
1400 int main(int argc, char **argv)
1405 for (i = 1; i < argc; i++) {
1406 const char *arg = argv[i];
1409 if (!strcmp(arg, "-")) {
1414 if (!strcmp(arg, "--no-merge")) {
1418 if (!strcmp(arg, "--stat")) {
1423 if (!strcmp(arg, "--summary")) {
1428 if (!strcmp(arg, "--check")) {
1433 if (!strcmp(arg, "--index")) {
1437 if (!strcmp(arg, "--show-files")) {
1441 fd = open(arg, O_RDONLY);