Teach git-status about spaces in file names also on MacOSX
[git/trast.git] / apply.c
blobf8862722fdba204d6e15e4d012f8891bcc36475c
1 /*
2 * apply.c
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
10 * patch apply.
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.
15 #include <ctype.h>
16 #include <fnmatch.h>
17 #include "cache.h"
19 // We default to the merge behaviour, since that's what most people would
20 // expect.
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;
32 static int check = 0;
33 static int apply = 1;
34 static int show_files = 0;
35 static const char apply_usage[] =
36 "git-apply [--no-merge] [--stat] [--summary] [--check] [--index] [--apply] [--show-files] <patch>...";
39 * For "diff-stat" like behaviour, we keep track of the biggest change
40 * we've seen, and the longest filename. That allows us to do simple
41 * scaling.
43 static int max_change, max_len;
46 * Various "current state", notably line numbers and what
47 * file (and how) we're patching right now.. The "is_xxxx"
48 * things are flags, where -1 means "don't know yet".
50 static int linenr = 1;
52 struct fragment {
53 unsigned long oldpos, oldlines;
54 unsigned long newpos, newlines;
55 const char *patch;
56 int size;
57 struct fragment *next;
60 struct patch {
61 char *new_name, *old_name, *def_name;
62 unsigned int old_mode, new_mode;
63 int is_rename, is_copy, is_new, is_delete;
64 int lines_added, lines_deleted;
65 int score;
66 struct fragment *fragments;
67 char *result;
68 unsigned long resultsize;
69 struct patch *next;
72 #define CHUNKSIZE (8192)
73 #define SLOP (16)
75 static void *read_patch_file(int fd, unsigned long *sizep)
77 unsigned long size = 0, alloc = CHUNKSIZE;
78 void *buffer = xmalloc(alloc);
80 for (;;) {
81 int nr = alloc - size;
82 if (nr < 1024) {
83 alloc += CHUNKSIZE;
84 buffer = xrealloc(buffer, alloc);
85 nr = alloc - size;
87 nr = read(fd, buffer + size, nr);
88 if (!nr)
89 break;
90 if (nr < 0) {
91 if (errno == EAGAIN)
92 continue;
93 die("git-apply: read returned %s", strerror(errno));
95 size += nr;
97 *sizep = size;
100 * Make sure that we have some slop in the buffer
101 * so that we can do speculative "memcmp" etc, and
102 * see to it that it is NUL-filled.
104 if (alloc < size + SLOP)
105 buffer = xrealloc(buffer, size + SLOP);
106 memset(buffer + size, 0, SLOP);
107 return buffer;
110 static unsigned long linelen(const char *buffer, unsigned long size)
112 unsigned long len = 0;
113 while (size--) {
114 len++;
115 if (*buffer++ == '\n')
116 break;
118 return len;
121 static int is_dev_null(const char *str)
123 return !memcmp("/dev/null", str, 9) && isspace(str[9]);
126 #define TERM_SPACE 1
127 #define TERM_TAB 2
129 static int name_terminate(const char *name, int namelen, int c, int terminate)
131 if (c == ' ' && !(terminate & TERM_SPACE))
132 return 0;
133 if (c == '\t' && !(terminate & TERM_TAB))
134 return 0;
136 return 1;
139 static char * find_name(const char *line, char *def, int p_value, int terminate)
141 int len;
142 const char *start = line;
143 char *name;
145 for (;;) {
146 char c = *line;
148 if (isspace(c)) {
149 if (c == '\n')
150 break;
151 if (name_terminate(start, line-start, c, terminate))
152 break;
154 line++;
155 if (c == '/' && !--p_value)
156 start = line;
158 if (!start)
159 return def;
160 len = line - start;
161 if (!len)
162 return def;
165 * Generally we prefer the shorter name, especially
166 * if the other one is just a variation of that with
167 * something else tacked on to the end (ie "file.orig"
168 * or "file~").
170 if (def) {
171 int deflen = strlen(def);
172 if (deflen < len && !strncmp(start, def, deflen))
173 return def;
176 name = xmalloc(len + 1);
177 memcpy(name, start, len);
178 name[len] = 0;
179 free(def);
180 return name;
184 * Get the name etc info from the --/+++ lines of a traditional patch header
186 * NOTE! This hardcodes "-p1" behaviour in filename detection.
188 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
189 * files, we can happily check the index for a match, but for creating a
190 * new file we should try to match whatever "patch" does. I have no idea.
192 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
194 int p_value = 1;
195 char *name;
197 first += 4; // skip "--- "
198 second += 4; // skip "+++ "
199 if (is_dev_null(first)) {
200 patch->is_new = 1;
201 patch->is_delete = 0;
202 name = find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB);
203 patch->new_name = name;
204 } else if (is_dev_null(second)) {
205 patch->is_new = 0;
206 patch->is_delete = 1;
207 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
208 patch->old_name = name;
209 } else {
210 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
211 name = find_name(second, name, p_value, TERM_SPACE | TERM_TAB);
212 patch->old_name = patch->new_name = name;
214 if (!name)
215 die("unable to find filename in patch at line %d", linenr);
218 static int gitdiff_hdrend(const char *line, struct patch *patch)
220 return -1;
224 * We're anal about diff header consistency, to make
225 * sure that we don't end up having strange ambiguous
226 * patches floating around.
228 * As a result, gitdiff_{old|new}name() will check
229 * their names against any previous information, just
230 * to make sure..
232 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
234 int len;
235 const char *name;
237 if (!orig_name && !isnull)
238 return find_name(line, NULL, 1, 0);
240 name = "/dev/null";
241 len = 9;
242 if (orig_name) {
243 name = orig_name;
244 len = strlen(name);
245 if (isnull)
246 die("git-apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
249 if (*name == '/')
250 goto absolute_path;
252 for (;;) {
253 char c = *line++;
254 if (c == '\n')
255 break;
256 if (c != '/')
257 continue;
258 absolute_path:
259 if (memcmp(line, name, len) || line[len] != '\n')
260 break;
261 return orig_name;
263 die("git-apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
264 return NULL;
267 static int gitdiff_oldname(const char *line, struct patch *patch)
269 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
270 return 0;
273 static int gitdiff_newname(const char *line, struct patch *patch)
275 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
276 return 0;
279 static int gitdiff_oldmode(const char *line, struct patch *patch)
281 patch->old_mode = strtoul(line, NULL, 8);
282 return 0;
285 static int gitdiff_newmode(const char *line, struct patch *patch)
287 patch->new_mode = strtoul(line, NULL, 8);
288 return 0;
291 static int gitdiff_delete(const char *line, struct patch *patch)
293 patch->is_delete = 1;
294 patch->old_name = patch->def_name;
295 return gitdiff_oldmode(line, patch);
298 static int gitdiff_newfile(const char *line, struct patch *patch)
300 patch->is_new = 1;
301 patch->new_name = patch->def_name;
302 return gitdiff_newmode(line, patch);
305 static int gitdiff_copysrc(const char *line, struct patch *patch)
307 patch->is_copy = 1;
308 patch->old_name = find_name(line, NULL, 0, 0);
309 return 0;
312 static int gitdiff_copydst(const char *line, struct patch *patch)
314 patch->is_copy = 1;
315 patch->new_name = find_name(line, NULL, 0, 0);
316 return 0;
319 static int gitdiff_renamesrc(const char *line, struct patch *patch)
321 patch->is_rename = 1;
322 patch->old_name = find_name(line, NULL, 0, 0);
323 return 0;
326 static int gitdiff_renamedst(const char *line, struct patch *patch)
328 patch->is_rename = 1;
329 patch->new_name = find_name(line, NULL, 0, 0);
330 return 0;
333 static int gitdiff_similarity(const char *line, struct patch *patch)
335 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
336 patch->score = 0;
337 return 0;
340 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
342 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
343 patch->score = 0;
344 return 0;
348 * This is normal for a diff that doesn't change anything: we'll fall through
349 * into the next diff. Tell the parser to break out.
351 static int gitdiff_unrecognized(const char *line, struct patch *patch)
353 return -1;
356 static char *git_header_name(char *line)
358 int len;
359 char *name, *second;
362 * Find the first '/'
364 name = line;
365 for (;;) {
366 char c = *name++;
367 if (c == '\n')
368 return NULL;
369 if (c == '/')
370 break;
374 * We don't accept absolute paths (/dev/null) as possibly valid
376 if (name == line+1)
377 return NULL;
380 * Accept a name only if it shows up twice, exactly the same
381 * form.
383 for (len = 0 ; ; len++) {
384 char c = name[len];
386 switch (c) {
387 default:
388 continue;
389 case '\n':
390 return NULL;
391 case '\t': case ' ':
392 second = name+len;
393 for (;;) {
394 char c = *second++;
395 if (c == '\n')
396 return NULL;
397 if (c == '/')
398 break;
400 if (second[len] == '\n' && !memcmp(name, second, len)) {
401 char *ret = xmalloc(len + 1);
402 memcpy(ret, name, len);
403 ret[len] = 0;
404 return ret;
408 return NULL;
411 /* Verify that we recognize the lines following a git header */
412 static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
414 unsigned long offset;
416 /* A git diff has explicit new/delete information, so we don't guess */
417 patch->is_new = 0;
418 patch->is_delete = 0;
421 * Some things may not have the old name in the
422 * rest of the headers anywhere (pure mode changes,
423 * or removing or adding empty files), so we get
424 * the default name from the header.
426 patch->def_name = git_header_name(line + strlen("diff --git "));
428 line += len;
429 size -= len;
430 linenr++;
431 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
432 static const struct opentry {
433 const char *str;
434 int (*fn)(const char *, struct patch *);
435 } optable[] = {
436 { "@@ -", gitdiff_hdrend },
437 { "--- ", gitdiff_oldname },
438 { "+++ ", gitdiff_newname },
439 { "old mode ", gitdiff_oldmode },
440 { "new mode ", gitdiff_newmode },
441 { "deleted file mode ", gitdiff_delete },
442 { "new file mode ", gitdiff_newfile },
443 { "copy from ", gitdiff_copysrc },
444 { "copy to ", gitdiff_copydst },
445 { "rename old ", gitdiff_renamesrc },
446 { "rename new ", gitdiff_renamedst },
447 { "rename from ", gitdiff_renamesrc },
448 { "rename to ", gitdiff_renamedst },
449 { "similarity index ", gitdiff_similarity },
450 { "dissimilarity index ", gitdiff_dissimilarity },
451 { "", gitdiff_unrecognized },
453 int i;
455 len = linelen(line, size);
456 if (!len || line[len-1] != '\n')
457 break;
458 for (i = 0; i < sizeof(optable) / sizeof(optable[0]); i++) {
459 const struct opentry *p = optable + i;
460 int oplen = strlen(p->str);
461 if (len < oplen || memcmp(p->str, line, oplen))
462 continue;
463 if (p->fn(line + oplen, patch) < 0)
464 return offset;
465 break;
469 return offset;
472 static int parse_num(const char *line, unsigned long *p)
474 char *ptr;
476 if (!isdigit(*line))
477 return 0;
478 *p = strtoul(line, &ptr, 10);
479 return ptr - line;
482 static int parse_range(const char *line, int len, int offset, const char *expect,
483 unsigned long *p1, unsigned long *p2)
485 int digits, ex;
487 if (offset < 0 || offset >= len)
488 return -1;
489 line += offset;
490 len -= offset;
492 digits = parse_num(line, p1);
493 if (!digits)
494 return -1;
496 offset += digits;
497 line += digits;
498 len -= digits;
500 *p2 = *p1;
501 if (*line == ',') {
502 digits = parse_num(line+1, p2);
503 if (!digits)
504 return -1;
506 offset += digits+1;
507 line += digits+1;
508 len -= digits+1;
511 ex = strlen(expect);
512 if (ex > len)
513 return -1;
514 if (memcmp(line, expect, ex))
515 return -1;
517 return offset + ex;
521 * Parse a unified diff fragment header of the
522 * form "@@ -a,b +c,d @@"
524 static int parse_fragment_header(char *line, int len, struct fragment *fragment)
526 int offset;
528 if (!len || line[len-1] != '\n')
529 return -1;
531 /* Figure out the number of lines in a fragment */
532 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
533 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
535 return offset;
538 static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
540 unsigned long offset, len;
542 patch->is_rename = patch->is_copy = 0;
543 patch->is_new = patch->is_delete = -1;
544 patch->old_mode = patch->new_mode = 0;
545 patch->old_name = patch->new_name = NULL;
546 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
547 unsigned long nextlen;
549 len = linelen(line, size);
550 if (!len)
551 break;
553 /* Testing this early allows us to take a few shortcuts.. */
554 if (len < 6)
555 continue;
558 * Make sure we don't find any unconnected patch fragmants.
559 * That's a sign that we didn't find a header, and that a
560 * patch has become corrupted/broken up.
562 if (!memcmp("@@ -", line, 4)) {
563 struct fragment dummy;
564 if (parse_fragment_header(line, len, &dummy) < 0)
565 continue;
566 error("patch fragment without header at line %d: %.*s", linenr, (int)len-1, line);
569 if (size < len + 6)
570 break;
573 * Git patch? It might not have a real patch, just a rename
574 * or mode change, so we handle that specially
576 if (!memcmp("diff --git ", line, 11)) {
577 int git_hdr_len = parse_git_header(line, len, size, patch);
578 if (git_hdr_len <= len)
579 continue;
580 if (!patch->old_name && !patch->new_name) {
581 if (!patch->def_name)
582 die("git diff header lacks filename information (line %d)", linenr);
583 patch->old_name = patch->new_name = patch->def_name;
585 *hdrsize = git_hdr_len;
586 return offset;
589 /** --- followed by +++ ? */
590 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
591 continue;
594 * We only accept unified patches, so we want it to
595 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
596 * minimum
598 nextlen = linelen(line + len, size - len);
599 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
600 continue;
602 /* Ok, we'll consider it a patch */
603 parse_traditional_patch(line, line+len, patch);
604 *hdrsize = len + nextlen;
605 linenr += 2;
606 return offset;
608 return -1;
612 * Parse a unified diff. Note that this really needs
613 * to parse each fragment separately, since the only
614 * way to know the difference between a "---" that is
615 * part of a patch, and a "---" that starts the next
616 * patch is to look at the line counts..
618 static int parse_fragment(char *line, unsigned long size, struct patch *patch, struct fragment *fragment)
620 int added, deleted;
621 int len = linelen(line, size), offset;
622 unsigned long oldlines, newlines;
624 offset = parse_fragment_header(line, len, fragment);
625 if (offset < 0)
626 return -1;
627 oldlines = fragment->oldlines;
628 newlines = fragment->newlines;
630 if (patch->is_new < 0) {
631 patch->is_new = !oldlines;
632 if (!oldlines)
633 patch->old_name = NULL;
635 if (patch->is_delete < 0) {
636 patch->is_delete = !newlines;
637 if (!newlines)
638 patch->new_name = NULL;
641 if (patch->is_new != !oldlines)
642 return error("new file depends on old contents");
643 if (patch->is_delete != !newlines) {
644 if (newlines)
645 return error("deleted file still has contents");
646 fprintf(stderr, "** warning: file %s becomes empty but is not deleted\n", patch->new_name);
649 /* Parse the thing.. */
650 line += len;
651 size -= len;
652 linenr++;
653 added = deleted = 0;
654 for (offset = len; size > 0; offset += len, size -= len, line += len, linenr++) {
655 if (!oldlines && !newlines)
656 break;
657 len = linelen(line, size);
658 if (!len || line[len-1] != '\n')
659 return -1;
660 switch (*line) {
661 default:
662 return -1;
663 case ' ':
664 oldlines--;
665 newlines--;
666 break;
667 case '-':
668 deleted++;
669 oldlines--;
670 break;
671 case '+':
672 added++;
673 newlines--;
674 break;
676 /* We allow "\ No newline at end of file". Depending
677 * on locale settings when the patch was produced we
678 * don't know what this line looks like. The only
679 * thing we do know is that it begins with "\ ". */
680 case '\\':
681 if (len < 12 || memcmp(line, "\\ ", 2))
682 return -1;
683 break;
686 /* If a fragment ends with an incomplete line, we failed to include
687 * it in the above loop because we hit oldlines == newlines == 0
688 * before seeing it.
690 if (12 < size && !memcmp(line, "\\ ", 2))
691 offset += linelen(line, size);
693 patch->lines_added += added;
694 patch->lines_deleted += deleted;
695 return offset;
698 static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
700 unsigned long offset = 0;
701 struct fragment **fragp = &patch->fragments;
703 while (size > 4 && !memcmp(line, "@@ -", 4)) {
704 struct fragment *fragment;
705 int len;
707 fragment = xmalloc(sizeof(*fragment));
708 memset(fragment, 0, sizeof(*fragment));
709 len = parse_fragment(line, size, patch, fragment);
710 if (len <= 0)
711 die("corrupt patch at line %d", linenr);
713 fragment->patch = line;
714 fragment->size = len;
716 *fragp = fragment;
717 fragp = &fragment->next;
719 offset += len;
720 line += len;
721 size -= len;
723 return offset;
726 static inline int metadata_changes(struct patch *patch)
728 return patch->is_rename > 0 ||
729 patch->is_copy > 0 ||
730 patch->is_new > 0 ||
731 patch->is_delete ||
732 (patch->old_mode && patch->new_mode &&
733 patch->old_mode != patch->new_mode);
736 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
738 int hdrsize, patchsize;
739 int offset = find_header(buffer, size, &hdrsize, patch);
741 if (offset < 0)
742 return offset;
744 patchsize = parse_single_patch(buffer + offset + hdrsize, size - offset - hdrsize, patch);
746 if (!patchsize && !metadata_changes(patch))
747 die("patch with only garbage at line %d", linenr);
749 return offset + hdrsize + patchsize;
752 static const char pluses[] = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
753 static const char minuses[]= "----------------------------------------------------------------------";
755 static void show_stats(struct patch *patch)
757 const char *prefix = "";
758 char *name = patch->new_name;
759 int len, max, add, del, total;
761 if (!name)
762 name = patch->old_name;
765 * "scale" the filename
767 len = strlen(name);
768 max = max_len;
769 if (max > 50)
770 max = 50;
771 if (len > max) {
772 char *slash;
773 prefix = "...";
774 max -= 3;
775 name += len - max;
776 slash = strchr(name, '/');
777 if (slash)
778 name = slash;
780 len = max;
783 * scale the add/delete
785 max = max_change;
786 if (max + len > 70)
787 max = 70 - len;
789 add = patch->lines_added;
790 del = patch->lines_deleted;
791 total = add + del;
793 if (max_change > 0) {
794 total = (total * max + max_change / 2) / max_change;
795 add = (add * max + max_change / 2) / max_change;
796 del = total - add;
798 printf(" %s%-*s |%5d %.*s%.*s\n", prefix,
799 len, name, patch->lines_added + patch->lines_deleted,
800 add, pluses, del, minuses);
803 static int read_old_data(struct stat *st, const char *path, void *buf, unsigned long size)
805 int fd;
806 unsigned long got;
808 switch (st->st_mode & S_IFMT) {
809 case S_IFLNK:
810 return readlink(path, buf, size);
811 case S_IFREG:
812 fd = open(path, O_RDONLY);
813 if (fd < 0)
814 return error("unable to open %s", path);
815 got = 0;
816 for (;;) {
817 int ret = read(fd, buf + got, size - got);
818 if (ret < 0) {
819 if (errno == EAGAIN)
820 continue;
821 break;
823 if (!ret)
824 break;
825 got += ret;
827 close(fd);
828 return got;
830 default:
831 return -1;
835 static int find_offset(const char *buf, unsigned long size, const char *fragment, unsigned long fragsize, int line)
837 int i;
838 unsigned long start, backwards, forwards;
840 if (fragsize > size)
841 return -1;
843 start = 0;
844 if (line > 1) {
845 unsigned long offset = 0;
846 i = line-1;
847 while (offset + fragsize <= size) {
848 if (buf[offset++] == '\n') {
849 start = offset;
850 if (!--i)
851 break;
856 /* Exact line number? */
857 if (!memcmp(buf + start, fragment, fragsize))
858 return start;
861 * There's probably some smart way to do this, but I'll leave
862 * that to the smart and beautiful people. I'm simple and stupid.
864 backwards = start;
865 forwards = start;
866 for (i = 0; ; i++) {
867 unsigned long try;
868 int n;
870 /* "backward" */
871 if (i & 1) {
872 if (!backwards) {
873 if (forwards + fragsize > size)
874 break;
875 continue;
877 do {
878 --backwards;
879 } while (backwards && buf[backwards-1] != '\n');
880 try = backwards;
881 } else {
882 while (forwards + fragsize <= size) {
883 if (buf[forwards++] == '\n')
884 break;
886 try = forwards;
889 if (try + fragsize > size)
890 continue;
891 if (memcmp(buf + try, fragment, fragsize))
892 continue;
893 n = (i >> 1)+1;
894 if (i & 1)
895 n = -n;
896 return try;
900 * We should start searching forward and backward.
902 return -1;
905 struct buffer_desc {
906 char *buffer;
907 unsigned long size;
908 unsigned long alloc;
911 static int apply_one_fragment(struct buffer_desc *desc, struct fragment *frag)
913 char *buf = desc->buffer;
914 const char *patch = frag->patch;
915 int offset, size = frag->size;
916 char *old = xmalloc(size);
917 char *new = xmalloc(size);
918 int oldsize = 0, newsize = 0;
920 while (size > 0) {
921 int len = linelen(patch, size);
922 int plen;
924 if (!len)
925 break;
928 * "plen" is how much of the line we should use for
929 * the actual patch data. Normally we just remove the
930 * first character on the line, but if the line is
931 * followed by "\ No newline", then we also remove the
932 * last one (which is the newline, of course).
934 plen = len-1;
935 if (len < size && patch[len] == '\\')
936 plen--;
937 switch (*patch) {
938 case ' ':
939 case '-':
940 memcpy(old + oldsize, patch + 1, plen);
941 oldsize += plen;
942 if (*patch == '-')
943 break;
944 /* Fall-through for ' ' */
945 case '+':
946 memcpy(new + newsize, patch + 1, plen);
947 newsize += plen;
948 break;
949 case '@': case '\\':
950 /* Ignore it, we already handled it */
951 break;
952 default:
953 return -1;
955 patch += len;
956 size -= len;
959 offset = find_offset(buf, desc->size, old, oldsize, frag->newpos);
960 if (offset >= 0) {
961 int diff = newsize - oldsize;
962 unsigned long size = desc->size + diff;
963 unsigned long alloc = desc->alloc;
965 if (size > alloc) {
966 alloc = size + 8192;
967 desc->alloc = alloc;
968 buf = xrealloc(buf, alloc);
969 desc->buffer = buf;
971 desc->size = size;
972 memmove(buf + offset + newsize, buf + offset + oldsize, size - offset - newsize);
973 memcpy(buf + offset, new, newsize);
974 offset = 0;
977 free(old);
978 free(new);
979 return offset;
982 static int apply_fragments(struct buffer_desc *desc, struct patch *patch)
984 struct fragment *frag = patch->fragments;
986 while (frag) {
987 if (apply_one_fragment(desc, frag) < 0)
988 return error("patch failed: %s:%ld", patch->old_name, frag->oldpos);
989 frag = frag->next;
991 return 0;
994 static int apply_data(struct patch *patch, struct stat *st)
996 char *buf;
997 unsigned long size, alloc;
998 struct buffer_desc desc;
1000 size = 0;
1001 alloc = 0;
1002 buf = NULL;
1003 if (patch->old_name) {
1004 size = st->st_size;
1005 alloc = size + 8192;
1006 buf = xmalloc(alloc);
1007 if (read_old_data(st, patch->old_name, buf, alloc) != size)
1008 return error("read of %s failed", patch->old_name);
1011 desc.size = size;
1012 desc.alloc = alloc;
1013 desc.buffer = buf;
1014 if (apply_fragments(&desc, patch) < 0)
1015 return -1;
1016 patch->result = desc.buffer;
1017 patch->resultsize = desc.size;
1019 if (patch->is_delete && patch->resultsize)
1020 return error("removal patch leaves file contents");
1022 return 0;
1025 static int check_patch(struct patch *patch)
1027 struct stat st;
1028 const char *old_name = patch->old_name;
1029 const char *new_name = patch->new_name;
1031 if (old_name) {
1032 int changed;
1034 if (lstat(old_name, &st) < 0)
1035 return error("%s: %s", old_name, strerror(errno));
1036 if (check_index) {
1037 int pos = cache_name_pos(old_name, strlen(old_name));
1038 if (pos < 0)
1039 return error("%s: does not exist in index", old_name);
1040 changed = ce_match_stat(active_cache[pos], &st);
1041 if (changed)
1042 return error("%s: does not match index", old_name);
1044 if (patch->is_new < 0)
1045 patch->is_new = 0;
1046 st.st_mode = ntohl(create_ce_mode(st.st_mode));
1047 if (!patch->old_mode)
1048 patch->old_mode = st.st_mode;
1049 if ((st.st_mode ^ patch->old_mode) & S_IFMT)
1050 return error("%s: wrong type", old_name);
1051 if (st.st_mode != patch->old_mode)
1052 fprintf(stderr, "warning: %s has type %o, expected %o\n",
1053 old_name, st.st_mode, patch->old_mode);
1056 if (new_name && (patch->is_new | patch->is_rename | patch->is_copy)) {
1057 if (check_index && cache_name_pos(new_name, strlen(new_name)) >= 0)
1058 return error("%s: already exists in index", new_name);
1059 if (!lstat(new_name, &st))
1060 return error("%s: already exists in working directory", new_name);
1061 if (errno != ENOENT)
1062 return error("%s: %s", new_name, strerror(errno));
1063 if (!patch->new_mode) {
1064 if (patch->is_new)
1065 patch->new_mode = S_IFREG | 0644;
1066 else
1067 patch->new_mode = patch->old_mode;
1071 if (new_name && old_name) {
1072 int same = !strcmp(old_name, new_name);
1073 if (!patch->new_mode)
1074 patch->new_mode = patch->old_mode;
1075 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
1076 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
1077 patch->new_mode, new_name, patch->old_mode,
1078 same ? "" : " of ", same ? "" : old_name);
1081 if (apply_data(patch, &st) < 0)
1082 return error("%s: patch does not apply", old_name);
1083 return 0;
1086 static int check_patch_list(struct patch *patch)
1088 int error = 0;
1090 for (;patch ; patch = patch->next)
1091 error |= check_patch(patch);
1092 return error;
1095 static void show_file(int c, unsigned int mode, const char *name)
1097 printf("%c %o %s\n", c, mode, name);
1100 static void show_file_list(struct patch *patch)
1102 for (;patch ; patch = patch->next) {
1103 if (patch->is_rename) {
1104 show_file('-', patch->old_mode, patch->old_name);
1105 show_file('+', patch->new_mode, patch->new_name);
1106 continue;
1108 if (patch->is_copy || patch->is_new) {
1109 show_file('+', patch->new_mode, patch->new_name);
1110 continue;
1112 if (patch->is_delete) {
1113 show_file('-', patch->old_mode, patch->old_name);
1114 continue;
1116 if (patch->old_mode && patch->new_mode && patch->old_mode != patch->new_mode) {
1117 printf("M %o:%o %s\n", patch->old_mode, patch->new_mode, patch->old_name);
1118 continue;
1120 printf("M %o %s\n", patch->old_mode, patch->old_name);
1124 static void stat_patch_list(struct patch *patch)
1126 int files, adds, dels;
1128 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
1129 files++;
1130 adds += patch->lines_added;
1131 dels += patch->lines_deleted;
1132 show_stats(patch);
1135 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
1138 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
1140 if (mode)
1141 printf(" %s mode %06o %s\n", newdelete, mode, name);
1142 else
1143 printf(" %s %s\n", newdelete, name);
1146 static void show_mode_change(struct patch *p, int show_name)
1148 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
1149 if (show_name)
1150 printf(" mode change %06o => %06o %s\n",
1151 p->old_mode, p->new_mode, p->new_name);
1152 else
1153 printf(" mode change %06o => %06o\n",
1154 p->old_mode, p->new_mode);
1158 static void show_rename_copy(struct patch *p)
1160 const char *renamecopy = p->is_rename ? "rename" : "copy";
1161 const char *old, *new;
1163 /* Find common prefix */
1164 old = p->old_name;
1165 new = p->new_name;
1166 while (1) {
1167 const char *slash_old, *slash_new;
1168 slash_old = strchr(old, '/');
1169 slash_new = strchr(new, '/');
1170 if (!slash_old ||
1171 !slash_new ||
1172 slash_old - old != slash_new - new ||
1173 memcmp(old, new, slash_new - new))
1174 break;
1175 old = slash_old + 1;
1176 new = slash_new + 1;
1178 /* p->old_name thru old is the common prefix, and old and new
1179 * through the end of names are renames
1181 if (old != p->old_name)
1182 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
1183 (int)(old - p->old_name), p->old_name,
1184 old, new, p->score);
1185 else
1186 printf(" %s %s => %s (%d%%)\n", renamecopy,
1187 p->old_name, p->new_name, p->score);
1188 show_mode_change(p, 0);
1191 static void summary_patch_list(struct patch *patch)
1193 struct patch *p;
1195 for (p = patch; p; p = p->next) {
1196 if (p->is_new)
1197 show_file_mode_name("create", p->new_mode, p->new_name);
1198 else if (p->is_delete)
1199 show_file_mode_name("delete", p->old_mode, p->old_name);
1200 else {
1201 if (p->is_rename || p->is_copy)
1202 show_rename_copy(p);
1203 else {
1204 if (p->score) {
1205 printf(" rewrite %s (%d%%)\n",
1206 p->new_name, p->score);
1207 show_mode_change(p, 0);
1209 else
1210 show_mode_change(p, 1);
1216 static void patch_stats(struct patch *patch)
1218 int lines = patch->lines_added + patch->lines_deleted;
1220 if (lines > max_change)
1221 max_change = lines;
1222 if (patch->old_name) {
1223 int len = strlen(patch->old_name);
1224 if (len > max_len)
1225 max_len = len;
1227 if (patch->new_name) {
1228 int len = strlen(patch->new_name);
1229 if (len > max_len)
1230 max_len = len;
1234 static void remove_file(struct patch *patch)
1236 if (write_index) {
1237 if (remove_file_from_cache(patch->old_name) < 0)
1238 die("unable to remove %s from index", patch->old_name);
1240 unlink(patch->old_name);
1243 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
1245 struct stat st;
1246 struct cache_entry *ce;
1247 int namelen = strlen(path);
1248 unsigned ce_size = cache_entry_size(namelen);
1250 if (!write_index)
1251 return;
1253 ce = xmalloc(ce_size);
1254 memset(ce, 0, ce_size);
1255 memcpy(ce->name, path, namelen);
1256 ce->ce_mode = create_ce_mode(mode);
1257 ce->ce_flags = htons(namelen);
1258 if (lstat(path, &st) < 0)
1259 die("unable to stat newly created file %s", path);
1260 fill_stat_cache_info(ce, &st);
1261 if (write_sha1_file(buf, size, "blob", ce->sha1) < 0)
1262 die("unable to create backing store for newly created file %s", path);
1263 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
1264 die("unable to add cache entry for %s", path);
1267 static void create_subdirectories(const char *path)
1269 int len = strlen(path);
1270 char *buf = xmalloc(len + 1);
1271 const char *slash = path;
1273 while ((slash = strchr(slash+1, '/')) != NULL) {
1274 len = slash - path;
1275 memcpy(buf, path, len);
1276 buf[len] = 0;
1277 if (mkdir(buf, 0777) < 0) {
1278 if (errno != EEXIST)
1279 break;
1282 free(buf);
1285 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
1287 int fd;
1289 if (S_ISLNK(mode))
1290 return symlink(buf, path);
1291 fd = open(path, O_CREAT | O_EXCL | O_WRONLY | O_TRUNC, (mode & 0100) ? 0777 : 0666);
1292 if (fd < 0)
1293 return -1;
1294 while (size) {
1295 int written = write(fd, buf, size);
1296 if (written < 0) {
1297 if (errno == EINTR || errno == EAGAIN)
1298 continue;
1299 die("writing file %s: %s", path, strerror(errno));
1301 if (!written)
1302 die("out of space writing file %s", path);
1303 buf += written;
1304 size -= written;
1306 if (close(fd) < 0)
1307 die("closing file %s: %s", path, strerror(errno));
1308 return 0;
1312 * We optimistically assume that the directories exist,
1313 * which is true 99% of the time anyway. If they don't,
1314 * we create them and try again.
1316 static void create_one_file(const char *path, unsigned mode, const char *buf, unsigned long size)
1318 if (!try_create_file(path, mode, buf, size))
1319 return;
1321 if (errno == ENOENT) {
1322 create_subdirectories(path);
1323 if (!try_create_file(path, mode, buf, size))
1324 return;
1327 if (errno == EEXIST) {
1328 unsigned int nr = getpid();
1330 for (;;) {
1331 const char *newpath;
1332 newpath = mkpath("%s~%u", path, nr);
1333 if (!try_create_file(newpath, mode, buf, size)) {
1334 if (!rename(newpath, path))
1335 return;
1336 unlink(newpath);
1337 break;
1339 if (errno != EEXIST)
1340 break;
1343 die("unable to write file %s mode %o", path, mode);
1346 static void create_file(struct patch *patch)
1348 const char *path = patch->new_name;
1349 unsigned mode = patch->new_mode;
1350 unsigned long size = patch->resultsize;
1351 char *buf = patch->result;
1353 if (!mode)
1354 mode = S_IFREG | 0644;
1355 create_one_file(path, mode, buf, size);
1356 add_index_file(path, mode, buf, size);
1359 static void write_out_one_result(struct patch *patch)
1361 if (patch->is_delete > 0) {
1362 remove_file(patch);
1363 return;
1365 if (patch->is_new > 0 || patch->is_copy) {
1366 create_file(patch);
1367 return;
1370 * Rename or modification boils down to the same
1371 * thing: remove the old, write the new
1373 remove_file(patch);
1374 create_file(patch);
1377 static void write_out_results(struct patch *list, int skipped_patch)
1379 if (!list && !skipped_patch)
1380 die("No changes");
1382 while (list) {
1383 write_out_one_result(list);
1384 list = list->next;
1388 static struct cache_file cache_file;
1390 static struct excludes {
1391 struct excludes *next;
1392 const char *path;
1393 } *excludes;
1395 static int use_patch(struct patch *p)
1397 const char *pathname = p->new_name ? p->new_name : p->old_name;
1398 struct excludes *x = excludes;
1399 while (x) {
1400 if (fnmatch(x->path, pathname, 0) == 0)
1401 return 0;
1402 x = x->next;
1404 return 1;
1407 static int apply_patch(int fd)
1409 int newfd;
1410 unsigned long offset, size;
1411 char *buffer = read_patch_file(fd, &size);
1412 struct patch *list = NULL, **listp = &list;
1413 int skipped_patch = 0;
1415 if (!buffer)
1416 return -1;
1417 offset = 0;
1418 while (size > 0) {
1419 struct patch *patch;
1420 int nr;
1422 patch = xmalloc(sizeof(*patch));
1423 memset(patch, 0, sizeof(*patch));
1424 nr = parse_chunk(buffer + offset, size, patch);
1425 if (nr < 0)
1426 break;
1427 if (use_patch(patch)) {
1428 patch_stats(patch);
1429 *listp = patch;
1430 listp = &patch->next;
1431 } else {
1432 /* perhaps free it a bit better? */
1433 free(patch);
1434 skipped_patch++;
1436 offset += nr;
1437 size -= nr;
1440 newfd = -1;
1441 write_index = check_index && apply;
1442 if (write_index)
1443 newfd = hold_index_file_for_update(&cache_file, get_index_file());
1444 if (check_index) {
1445 if (read_cache() < 0)
1446 die("unable to read index file");
1449 if ((check || apply) && check_patch_list(list) < 0)
1450 exit(1);
1452 if (apply)
1453 write_out_results(list, skipped_patch);
1455 if (write_index) {
1456 if (write_cache(newfd, active_cache, active_nr) ||
1457 commit_index_file(&cache_file))
1458 die("Unable to write new cachefile");
1461 if (show_files)
1462 show_file_list(list);
1464 if (diffstat)
1465 stat_patch_list(list);
1467 if (summary)
1468 summary_patch_list(list);
1470 free(buffer);
1471 return 0;
1474 int main(int argc, char **argv)
1476 int i;
1477 int read_stdin = 1;
1479 for (i = 1; i < argc; i++) {
1480 const char *arg = argv[i];
1481 int fd;
1483 if (!strcmp(arg, "-")) {
1484 apply_patch(0);
1485 read_stdin = 0;
1486 continue;
1488 if (!strncmp(arg, "--exclude=", 10)) {
1489 struct excludes *x = xmalloc(sizeof(*x));
1490 x->path = arg + 10;
1491 x->next = excludes;
1492 excludes = x;
1493 continue;
1495 /* NEEDSWORK: this does not do anything at this moment. */
1496 if (!strcmp(arg, "--no-merge")) {
1497 merge_patch = 0;
1498 continue;
1500 if (!strcmp(arg, "--stat")) {
1501 apply = 0;
1502 diffstat = 1;
1503 continue;
1505 if (!strcmp(arg, "--summary")) {
1506 apply = 0;
1507 summary = 1;
1508 continue;
1510 if (!strcmp(arg, "--check")) {
1511 apply = 0;
1512 check = 1;
1513 continue;
1515 if (!strcmp(arg, "--index")) {
1516 check_index = 1;
1517 continue;
1519 if (!strcmp(arg, "--apply")) {
1520 apply = 1;
1521 continue;
1523 if (!strcmp(arg, "--show-files")) {
1524 show_files = 1;
1525 continue;
1527 fd = open(arg, O_RDONLY);
1528 if (fd < 0)
1529 usage(apply_usage);
1530 read_stdin = 0;
1531 apply_patch(fd);
1532 close(fd);
1534 if (read_stdin)
1535 apply_patch(0);
1536 return 0;