Sparse fixes for http-fetch
[git/debian.git] / apply.c
blobf4d00f2835c444aecf1b6c7ca3f97739c1958803
1 /*
2 * apply.c
4 * Copyright (C) Linus Torvalds, 2005
6 * This applies patches on top of some (arbitrary) version of the SCM.
8 */
9 #include <fnmatch.h>
10 #include "cache.h"
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;
22 static int check = 0;
23 static int apply = 1;
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
32 * scaling.
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;
43 struct fragment {
44 unsigned long oldpos, oldlines;
45 unsigned long newpos, newlines;
46 const char *patch;
47 int size;
48 struct fragment *next;
51 struct patch {
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;
56 int score;
57 struct fragment *fragments;
58 char *result;
59 unsigned long resultsize;
60 char old_sha1_prefix[41];
61 char new_sha1_prefix[41];
62 struct patch *next;
65 #define CHUNKSIZE (8192)
66 #define SLOP (16)
68 static void *read_patch_file(int fd, unsigned long *sizep)
70 unsigned long size = 0, alloc = CHUNKSIZE;
71 void *buffer = xmalloc(alloc);
73 for (;;) {
74 int nr = alloc - size;
75 if (nr < 1024) {
76 alloc += CHUNKSIZE;
77 buffer = xrealloc(buffer, alloc);
78 nr = alloc - size;
80 nr = read(fd, buffer + size, nr);
81 if (!nr)
82 break;
83 if (nr < 0) {
84 if (errno == EAGAIN)
85 continue;
86 die("git-apply: read returned %s", strerror(errno));
88 size += nr;
90 *sizep = size;
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);
100 return buffer;
103 static unsigned long linelen(const char *buffer, unsigned long size)
105 unsigned long len = 0;
106 while (size--) {
107 len++;
108 if (*buffer++ == '\n')
109 break;
111 return len;
114 static int is_dev_null(const char *str)
116 return !memcmp("/dev/null", str, 9) && isspace(str[9]);
119 #define TERM_SPACE 1
120 #define TERM_TAB 2
122 static int name_terminate(const char *name, int namelen, int c, int terminate)
124 if (c == ' ' && !(terminate & TERM_SPACE))
125 return 0;
126 if (c == '\t' && !(terminate & TERM_TAB))
127 return 0;
129 return 1;
132 static char * find_name(const char *line, char *def, int p_value, int terminate)
134 int len;
135 const char *start = line;
136 char *name;
138 for (;;) {
139 char c = *line;
141 if (isspace(c)) {
142 if (c == '\n')
143 break;
144 if (name_terminate(start, line-start, c, terminate))
145 break;
147 line++;
148 if (c == '/' && !--p_value)
149 start = line;
151 if (!start)
152 return def;
153 len = line - start;
154 if (!len)
155 return def;
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"
161 * or "file~").
163 if (def) {
164 int deflen = strlen(def);
165 if (deflen < len && !strncmp(start, def, deflen))
166 return def;
169 name = xmalloc(len + 1);
170 memcpy(name, start, len);
171 name[len] = 0;
172 free(def);
173 return name;
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)
187 int p_value = 1;
188 char *name;
190 first += 4; // skip "--- "
191 second += 4; // skip "+++ "
192 if (is_dev_null(first)) {
193 patch->is_new = 1;
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)) {
198 patch->is_new = 0;
199 patch->is_delete = 1;
200 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
201 patch->old_name = name;
202 } else {
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;
207 if (!name)
208 die("unable to find filename in patch at line %d", linenr);
211 static int gitdiff_hdrend(const char *line, struct patch *patch)
213 return -1;
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
223 * to make sure..
225 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
227 int len;
228 const char *name;
230 if (!orig_name && !isnull)
231 return find_name(line, NULL, 1, 0);
233 name = "/dev/null";
234 len = 9;
235 if (orig_name) {
236 name = orig_name;
237 len = strlen(name);
238 if (isnull)
239 die("git-apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
242 if (*name == '/')
243 goto absolute_path;
245 for (;;) {
246 char c = *line++;
247 if (c == '\n')
248 break;
249 if (c != '/')
250 continue;
251 absolute_path:
252 if (memcmp(line, name, len) || line[len] != '\n')
253 break;
254 return orig_name;
256 die("git-apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
257 return NULL;
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");
263 return 0;
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");
269 return 0;
272 static int gitdiff_oldmode(const char *line, struct patch *patch)
274 patch->old_mode = strtoul(line, NULL, 8);
275 return 0;
278 static int gitdiff_newmode(const char *line, struct patch *patch)
280 patch->new_mode = strtoul(line, NULL, 8);
281 return 0;
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)
293 patch->is_new = 1;
294 patch->new_name = patch->def_name;
295 return gitdiff_newmode(line, patch);
298 static int gitdiff_copysrc(const char *line, struct patch *patch)
300 patch->is_copy = 1;
301 patch->old_name = find_name(line, NULL, 0, 0);
302 return 0;
305 static int gitdiff_copydst(const char *line, struct patch *patch)
307 patch->is_copy = 1;
308 patch->new_name = find_name(line, NULL, 0, 0);
309 return 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);
316 return 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);
323 return 0;
326 static int gitdiff_similarity(const char *line, struct patch *patch)
328 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
329 patch->score = 0;
330 return 0;
333 static int gitdiff_dissimilarity(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_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;
346 int len;
348 ptr = strchr(line, '.');
349 if (!ptr || ptr[1] != '.' || 40 <= ptr - line)
350 return 0;
351 len = ptr - line;
352 memcpy(patch->old_sha1_prefix, line, len);
353 patch->old_sha1_prefix[len] = 0;
355 line = ptr + 2;
356 ptr = strchr(line, ' ');
357 eol = strchr(line, '\n');
359 if (!ptr || eol < ptr)
360 ptr = eol;
361 len = ptr - line;
363 if (40 <= len)
364 return 0;
365 memcpy(patch->new_sha1_prefix, line, len);
366 patch->new_sha1_prefix[len] = 0;
367 if (*ptr == ' ')
368 patch->new_mode = patch->old_mode = strtoul(ptr+1, NULL, 8);
369 return 0;
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)
378 return -1;
381 static char *git_header_name(char *line)
383 int len;
384 char *name, *second;
387 * Find the first '/'
389 name = line;
390 for (;;) {
391 char c = *name++;
392 if (c == '\n')
393 return NULL;
394 if (c == '/')
395 break;
399 * We don't accept absolute paths (/dev/null) as possibly valid
401 if (name == line+1)
402 return NULL;
405 * Accept a name only if it shows up twice, exactly the same
406 * form.
408 for (len = 0 ; ; len++) {
409 char c = name[len];
411 switch (c) {
412 default:
413 continue;
414 case '\n':
415 return NULL;
416 case '\t': case ' ':
417 second = name+len;
418 for (;;) {
419 char c = *second++;
420 if (c == '\n')
421 return NULL;
422 if (c == '/')
423 break;
425 if (second[len] == '\n' && !memcmp(name, second, len)) {
426 char *ret = xmalloc(len + 1);
427 memcpy(ret, name, len);
428 ret[len] = 0;
429 return ret;
433 return NULL;
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 */
442 patch->is_new = 0;
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 "));
453 line += len;
454 size -= len;
455 linenr++;
456 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
457 static const struct opentry {
458 const char *str;
459 int (*fn)(const char *, struct patch *);
460 } optable[] = {
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 },
479 int i;
481 len = linelen(line, size);
482 if (!len || line[len-1] != '\n')
483 break;
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))
488 continue;
489 if (p->fn(line + oplen, patch) < 0)
490 return offset;
491 break;
495 return offset;
498 static int parse_num(const char *line, unsigned long *p)
500 char *ptr;
502 if (!isdigit(*line))
503 return 0;
504 *p = strtoul(line, &ptr, 10);
505 return ptr - line;
508 static int parse_range(const char *line, int len, int offset, const char *expect,
509 unsigned long *p1, unsigned long *p2)
511 int digits, ex;
513 if (offset < 0 || offset >= len)
514 return -1;
515 line += offset;
516 len -= offset;
518 digits = parse_num(line, p1);
519 if (!digits)
520 return -1;
522 offset += digits;
523 line += digits;
524 len -= digits;
526 *p2 = *p1;
527 if (*line == ',') {
528 digits = parse_num(line+1, p2);
529 if (!digits)
530 return -1;
532 offset += digits+1;
533 line += digits+1;
534 len -= digits+1;
537 ex = strlen(expect);
538 if (ex > len)
539 return -1;
540 if (memcmp(line, expect, ex))
541 return -1;
543 return offset + 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)
552 int offset;
554 if (!len || line[len-1] != '\n')
555 return -1;
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);
561 return offset;
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);
576 if (!len)
577 break;
579 /* Testing this early allows us to take a few shortcuts.. */
580 if (len < 6)
581 continue;
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)
591 continue;
592 error("patch fragment without header at line %d: %.*s", linenr, (int)len-1, line);
595 if (size < len + 6)
596 break;
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)
605 continue;
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;
612 return offset;
615 /** --- followed by +++ ? */
616 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
617 continue;
620 * We only accept unified patches, so we want it to
621 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
622 * minimum
624 nextlen = linelen(line + len, size - len);
625 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
626 continue;
628 /* Ok, we'll consider it a patch */
629 parse_traditional_patch(line, line+len, patch);
630 *hdrsize = len + nextlen;
631 linenr += 2;
632 return offset;
634 return -1;
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)
646 int added, deleted;
647 int len = linelen(line, size), offset;
648 unsigned long oldlines, newlines;
650 offset = parse_fragment_header(line, len, fragment);
651 if (offset < 0)
652 return -1;
653 oldlines = fragment->oldlines;
654 newlines = fragment->newlines;
656 if (patch->is_new < 0) {
657 patch->is_new = !oldlines;
658 if (!oldlines)
659 patch->old_name = NULL;
661 if (patch->is_delete < 0) {
662 patch->is_delete = !newlines;
663 if (!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) {
670 if (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.. */
676 line += len;
677 size -= len;
678 linenr++;
679 added = deleted = 0;
680 for (offset = len; size > 0; offset += len, size -= len, line += len, linenr++) {
681 if (!oldlines && !newlines)
682 break;
683 len = linelen(line, size);
684 if (!len || line[len-1] != '\n')
685 return -1;
686 switch (*line) {
687 default:
688 return -1;
689 case ' ':
690 oldlines--;
691 newlines--;
692 break;
693 case '-':
694 deleted++;
695 oldlines--;
696 break;
697 case '+':
698 added++;
699 newlines--;
700 break;
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.
709 case '\\':
710 if (len < 12 || memcmp(line, "\\ ", 2))
711 return -1;
712 break;
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
717 * before seeing it.
719 if (12 < size && !memcmp(line, "\\ ", 2))
720 offset += linelen(line, size);
722 patch->lines_added += added;
723 patch->lines_deleted += deleted;
724 return offset;
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;
734 int len;
736 fragment = xmalloc(sizeof(*fragment));
737 memset(fragment, 0, sizeof(*fragment));
738 len = parse_fragment(line, size, patch, fragment);
739 if (len <= 0)
740 die("corrupt patch at line %d", linenr);
742 fragment->patch = line;
743 fragment->size = len;
745 *fragp = fragment;
746 fragp = &fragment->next;
748 offset += len;
749 line += len;
750 size -= len;
752 return offset;
755 static inline int metadata_changes(struct patch *patch)
757 return patch->is_rename > 0 ||
758 patch->is_copy > 0 ||
759 patch->is_new > 0 ||
760 patch->is_delete ||
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);
770 if (offset < 0)
771 return offset;
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;
790 if (!name)
791 name = patch->old_name;
794 * "scale" the filename
796 len = strlen(name);
797 max = max_len;
798 if (max > 50)
799 max = 50;
800 if (len > max) {
801 char *slash;
802 prefix = "...";
803 max -= 3;
804 name += len - max;
805 slash = strchr(name, '/');
806 if (slash)
807 name = slash;
809 len = max;
812 * scale the add/delete
814 max = max_change;
815 if (max + len > 70)
816 max = 70 - len;
818 add = patch->lines_added;
819 del = patch->lines_deleted;
820 total = add + del;
822 if (max_change > 0) {
823 total = (total * max + max_change / 2) / max_change;
824 add = (add * max + max_change / 2) / max_change;
825 del = total - add;
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)
834 int fd;
835 unsigned long got;
837 switch (st->st_mode & S_IFMT) {
838 case S_IFLNK:
839 return readlink(path, buf, size);
840 case S_IFREG:
841 fd = open(path, O_RDONLY);
842 if (fd < 0)
843 return error("unable to open %s", path);
844 got = 0;
845 for (;;) {
846 int ret = read(fd, buf + got, size - got);
847 if (ret < 0) {
848 if (errno == EAGAIN)
849 continue;
850 break;
852 if (!ret)
853 break;
854 got += ret;
856 close(fd);
857 return got;
859 default:
860 return -1;
864 static int find_offset(const char *buf, unsigned long size, const char *fragment, unsigned long fragsize, int line)
866 int i;
867 unsigned long start, backwards, forwards;
869 if (fragsize > size)
870 return -1;
872 start = 0;
873 if (line > 1) {
874 unsigned long offset = 0;
875 i = line-1;
876 while (offset + fragsize <= size) {
877 if (buf[offset++] == '\n') {
878 start = offset;
879 if (!--i)
880 break;
885 /* Exact line number? */
886 if (!memcmp(buf + start, fragment, fragsize))
887 return start;
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.
893 backwards = start;
894 forwards = start;
895 for (i = 0; ; i++) {
896 unsigned long try;
897 int n;
899 /* "backward" */
900 if (i & 1) {
901 if (!backwards) {
902 if (forwards + fragsize > size)
903 break;
904 continue;
906 do {
907 --backwards;
908 } while (backwards && buf[backwards-1] != '\n');
909 try = backwards;
910 } else {
911 while (forwards + fragsize <= size) {
912 if (buf[forwards++] == '\n')
913 break;
915 try = forwards;
918 if (try + fragsize > size)
919 continue;
920 if (memcmp(buf + try, fragment, fragsize))
921 continue;
922 n = (i >> 1)+1;
923 if (i & 1)
924 n = -n;
925 return try;
929 * We should start searching forward and backward.
931 return -1;
934 struct buffer_desc {
935 char *buffer;
936 unsigned long size;
937 unsigned long alloc;
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;
949 while (size > 0) {
950 int len = linelen(patch, size);
951 int plen;
953 if (!len)
954 break;
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).
963 plen = len-1;
964 if (len < size && patch[len] == '\\')
965 plen--;
966 switch (*patch) {
967 case ' ':
968 case '-':
969 memcpy(old + oldsize, patch + 1, plen);
970 oldsize += plen;
971 if (*patch == '-')
972 break;
973 /* Fall-through for ' ' */
974 case '+':
975 memcpy(new + newsize, patch + 1, plen);
976 newsize += plen;
977 break;
978 case '@': case '\\':
979 /* Ignore it, we already handled it */
980 break;
981 default:
982 return -1;
984 patch += len;
985 size -= len;
988 offset = find_offset(buf, desc->size, old, oldsize, frag->newpos);
989 if (offset >= 0) {
990 int diff = newsize - oldsize;
991 unsigned long size = desc->size + diff;
992 unsigned long alloc = desc->alloc;
994 if (size > alloc) {
995 alloc = size + 8192;
996 desc->alloc = alloc;
997 buf = xrealloc(buf, alloc);
998 desc->buffer = buf;
1000 desc->size = size;
1001 memmove(buf + offset + newsize, buf + offset + oldsize, size - offset - newsize);
1002 memcpy(buf + offset, new, newsize);
1003 offset = 0;
1006 free(old);
1007 free(new);
1008 return offset;
1011 static int apply_fragments(struct buffer_desc *desc, struct patch *patch)
1013 struct fragment *frag = patch->fragments;
1015 while (frag) {
1016 if (apply_one_fragment(desc, frag) < 0)
1017 return error("patch failed: %s:%ld", patch->old_name, frag->oldpos);
1018 frag = frag->next;
1020 return 0;
1023 static int apply_data(struct patch *patch, struct stat *st)
1025 char *buf;
1026 unsigned long size, alloc;
1027 struct buffer_desc desc;
1029 size = 0;
1030 alloc = 0;
1031 buf = NULL;
1032 if (patch->old_name) {
1033 size = st->st_size;
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);
1040 desc.size = size;
1041 desc.alloc = alloc;
1042 desc.buffer = buf;
1043 if (apply_fragments(&desc, patch) < 0)
1044 return -1;
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");
1051 return 0;
1054 static int check_patch(struct patch *patch)
1056 struct stat st;
1057 const char *old_name = patch->old_name;
1058 const char *new_name = patch->new_name;
1060 if (old_name) {
1061 int changed;
1062 int stat_ret = lstat(old_name, &st);
1064 if (check_index) {
1065 int pos = cache_name_pos(old_name, strlen(old_name));
1066 if (pos < 0)
1067 return error("%s: does not exist in index",
1068 old_name);
1069 if (stat_ret < 0) {
1070 struct checkout costate;
1071 if (errno != ENOENT)
1072 return error("%s: %s", old_name,
1073 strerror(errno));
1074 /* checkout */
1075 costate.base_dir = "";
1076 costate.base_dir_len = 0;
1077 costate.force = 0;
1078 costate.quiet = 0;
1079 costate.not_new = 0;
1080 costate.refresh_cache = 1;
1081 if (checkout_entry(active_cache[pos],
1082 &costate) ||
1083 lstat(old_name, &st))
1084 return -1;
1087 changed = ce_match_stat(active_cache[pos], &st);
1088 if (changed)
1089 return error("%s: does not match index",
1090 old_name);
1092 else if (stat_ret < 0)
1093 return error("%s: %s", old_name, strerror(errno));
1095 if (patch->is_new < 0)
1096 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) {
1115 if (patch->is_new)
1116 patch->new_mode = S_IFREG | 0644;
1117 else
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);
1134 return 0;
1137 static int check_patch_list(struct patch *patch)
1139 int error = 0;
1141 for (;patch ; patch = patch->next)
1142 error |= check_patch(patch);
1143 return error;
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);
1157 continue;
1159 if (patch->is_copy || patch->is_new) {
1160 show_file('+', patch->new_mode, patch->new_name);
1161 continue;
1163 if (patch->is_delete) {
1164 show_file('-', patch->old_mode, patch->old_name);
1165 continue;
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);
1169 continue;
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];
1190 const char *name;
1192 name = patch->old_name ? patch->old_name : patch->new_name;
1193 if (patch->is_new)
1194 sha1_ptr = null_sha1;
1195 else if (get_sha1(patch->old_sha1_prefix, sha1))
1196 die("sha1 information is lacking or useless (%s).",
1197 name);
1198 else
1199 sha1_ptr = sha1;
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) {
1210 files++;
1211 adds += patch->lines_added;
1212 dels += patch->lines_deleted;
1213 show_stats(patch);
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)
1221 if (mode)
1222 printf(" %s mode %06o %s\n", newdelete, mode, name);
1223 else
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) {
1230 if (show_name)
1231 printf(" mode change %06o => %06o %s\n",
1232 p->old_mode, p->new_mode, p->new_name);
1233 else
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 */
1245 old = p->old_name;
1246 new = p->new_name;
1247 while (1) {
1248 const char *slash_old, *slash_new;
1249 slash_old = strchr(old, '/');
1250 slash_new = strchr(new, '/');
1251 if (!slash_old ||
1252 !slash_new ||
1253 slash_old - old != slash_new - new ||
1254 memcmp(old, new, slash_new - new))
1255 break;
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);
1266 else
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)
1274 struct patch *p;
1276 for (p = patch; p; p = p->next) {
1277 if (p->is_new)
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);
1281 else {
1282 if (p->is_rename || p->is_copy)
1283 show_rename_copy(p);
1284 else {
1285 if (p->score) {
1286 printf(" rewrite %s (%d%%)\n",
1287 p->new_name, p->score);
1288 show_mode_change(p, 0);
1290 else
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)
1302 max_change = lines;
1303 if (patch->old_name) {
1304 int len = strlen(patch->old_name);
1305 if (len > max_len)
1306 max_len = len;
1308 if (patch->new_name) {
1309 int len = strlen(patch->new_name);
1310 if (len > max_len)
1311 max_len = len;
1315 static void remove_file(struct patch *patch)
1317 if (write_index) {
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)
1326 struct stat st;
1327 struct cache_entry *ce;
1328 int namelen = strlen(path);
1329 unsigned ce_size = cache_entry_size(namelen);
1331 if (!write_index)
1332 return;
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) {
1355 len = slash - path;
1356 memcpy(buf, path, len);
1357 buf[len] = 0;
1358 if (mkdir(buf, 0777) < 0) {
1359 if (errno != EEXIST)
1360 break;
1363 free(buf);
1366 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
1368 int fd;
1370 if (S_ISLNK(mode))
1371 return symlink(buf, path);
1372 fd = open(path, O_CREAT | O_EXCL | O_WRONLY | O_TRUNC, (mode & 0100) ? 0777 : 0666);
1373 if (fd < 0)
1374 return -1;
1375 while (size) {
1376 int written = write(fd, buf, size);
1377 if (written < 0) {
1378 if (errno == EINTR || errno == EAGAIN)
1379 continue;
1380 die("writing file %s: %s", path, strerror(errno));
1382 if (!written)
1383 die("out of space writing file %s", path);
1384 buf += written;
1385 size -= written;
1387 if (close(fd) < 0)
1388 die("closing file %s: %s", path, strerror(errno));
1389 return 0;
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))
1400 return;
1402 if (errno == ENOENT) {
1403 create_subdirectories(path);
1404 if (!try_create_file(path, mode, buf, size))
1405 return;
1408 if (errno == EEXIST) {
1409 unsigned int nr = getpid();
1411 for (;;) {
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))
1416 return;
1417 unlink(newpath);
1418 break;
1420 if (errno != EEXIST)
1421 break;
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;
1434 if (!mode)
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) {
1443 remove_file(patch);
1444 return;
1446 if (patch->is_new > 0 || patch->is_copy) {
1447 create_file(patch);
1448 return;
1451 * Rename or modification boils down to the same
1452 * thing: remove the old, write the new
1454 remove_file(patch);
1455 create_file(patch);
1458 static void write_out_results(struct patch *list, int skipped_patch)
1460 if (!list && !skipped_patch)
1461 die("No changes");
1463 while (list) {
1464 write_out_one_result(list);
1465 list = list->next;
1469 static struct cache_file cache_file;
1471 static struct excludes {
1472 struct excludes *next;
1473 const char *path;
1474 } *excludes;
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;
1480 while (x) {
1481 if (fnmatch(x->path, pathname, 0) == 0)
1482 return 0;
1483 x = x->next;
1485 return 1;
1488 static int apply_patch(int fd)
1490 int newfd;
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;
1496 if (!buffer)
1497 return -1;
1498 offset = 0;
1499 while (size > 0) {
1500 struct patch *patch;
1501 int nr;
1503 patch = xmalloc(sizeof(*patch));
1504 memset(patch, 0, sizeof(*patch));
1505 nr = parse_chunk(buffer + offset, size, patch);
1506 if (nr < 0)
1507 break;
1508 if (use_patch(patch)) {
1509 patch_stats(patch);
1510 *listp = patch;
1511 listp = &patch->next;
1512 } else {
1513 /* perhaps free it a bit better? */
1514 free(patch);
1515 skipped_patch++;
1517 offset += nr;
1518 size -= nr;
1521 newfd = -1;
1522 write_index = check_index && apply;
1523 if (write_index)
1524 newfd = hold_index_file_for_update(&cache_file, get_index_file());
1525 if (check_index) {
1526 if (read_cache() < 0)
1527 die("unable to read index file");
1530 if ((check || apply) && check_patch_list(list) < 0)
1531 exit(1);
1533 if (apply)
1534 write_out_results(list, skipped_patch);
1536 if (write_index) {
1537 if (write_cache(newfd, active_cache, active_nr) ||
1538 commit_index_file(&cache_file))
1539 die("Unable to write new cachefile");
1542 if (show_files)
1543 show_file_list(list);
1545 if (show_index_info)
1546 show_index_list(list);
1548 if (diffstat)
1549 stat_patch_list(list);
1551 if (summary)
1552 summary_patch_list(list);
1554 free(buffer);
1555 return 0;
1558 int main(int argc, char **argv)
1560 int i;
1561 int read_stdin = 1;
1563 for (i = 1; i < argc; i++) {
1564 const char *arg = argv[i];
1565 int fd;
1567 if (!strcmp(arg, "-")) {
1568 apply_patch(0);
1569 read_stdin = 0;
1570 continue;
1572 if (!strncmp(arg, "--exclude=", 10)) {
1573 struct excludes *x = xmalloc(sizeof(*x));
1574 x->path = arg + 10;
1575 x->next = excludes;
1576 excludes = x;
1577 continue;
1579 if (!strcmp(arg, "--stat")) {
1580 apply = 0;
1581 diffstat = 1;
1582 continue;
1584 if (!strcmp(arg, "--summary")) {
1585 apply = 0;
1586 summary = 1;
1587 continue;
1589 if (!strcmp(arg, "--check")) {
1590 apply = 0;
1591 check = 1;
1592 continue;
1594 if (!strcmp(arg, "--index")) {
1595 check_index = 1;
1596 continue;
1598 if (!strcmp(arg, "--apply")) {
1599 apply = 1;
1600 continue;
1602 if (!strcmp(arg, "--show-files")) {
1603 show_files = 1;
1604 continue;
1606 if (!strcmp(arg, "--show-index-info")) {
1607 apply = 0;
1608 show_index_info = 1;
1609 continue;
1611 fd = open(arg, O_RDONLY);
1612 if (fd < 0)
1613 usage(apply_usage);
1614 read_stdin = 0;
1615 apply_patch(fd);
1616 close(fd);
1618 if (read_stdin)
1619 apply_patch(0);
1620 return 0;