Use sha1_file.c's mkdir-like routine in apply.c.
[git] / apply.c
1 /*
2  * apply.c
3  *
4  * Copyright (C) Linus Torvalds, 2005
5  *
6  * This applies patches on top of some (arbitrary) version of the SCM.
7  *
8  */
9 #include <fnmatch.h>
10 #include "cache.h"
11 #include "quote.h"
12
13 //  --check turns on checking that the working tree matches the
14 //    files that are being modified, but doesn't apply the patch
15 //  --stat does just a diffstat, and doesn't actually apply
16 //  --numstat does numeric diffstat, and doesn't actually apply
17 //  --index-info shows the old and new index info for paths if available.
18 //
19 static const char *prefix;
20 static int prefix_length = -1;
21
22 static int p_value = 1;
23 static int allow_binary_replacement = 0;
24 static int check_index = 0;
25 static int write_index = 0;
26 static int diffstat = 0;
27 static int numstat = 0;
28 static int summary = 0;
29 static int check = 0;
30 static int apply = 1;
31 static int no_add = 0;
32 static int show_index_info = 0;
33 static int line_termination = '\n';
34 static const char apply_usage[] =
35 "git-apply [--stat] [--numstat] [--summary] [--check] [--index] [--apply] [--no-add] [--index-info] [--allow-binary-replacement] [-z] [-pNUM] <patch>...";
36
37 /*
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
40  * scaling.
41  */
42 static int max_change, max_len;
43
44 /*
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".
48  */
49 static int linenr = 1;
50
51 struct fragment {
52         unsigned long oldpos, oldlines;
53         unsigned long newpos, newlines;
54         const char *patch;
55         int size;
56         struct fragment *next;
57 };
58
59 struct patch {
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, is_binary;
63         int lines_added, lines_deleted;
64         int score;
65         struct fragment *fragments;
66         char *result;
67         unsigned long resultsize;
68         char old_sha1_prefix[41];
69         char new_sha1_prefix[41];
70         struct patch *next;
71 };
72
73 #define CHUNKSIZE (8192)
74 #define SLOP (16)
75
76 static void *read_patch_file(int fd, unsigned long *sizep)
77 {
78         unsigned long size = 0, alloc = CHUNKSIZE;
79         void *buffer = xmalloc(alloc);
80
81         for (;;) {
82                 int nr = alloc - size;
83                 if (nr < 1024) {
84                         alloc += CHUNKSIZE;
85                         buffer = xrealloc(buffer, alloc);
86                         nr = alloc - size;
87                 }
88                 nr = xread(fd, buffer + size, nr);
89                 if (!nr)
90                         break;
91                 if (nr < 0)
92                         die("git-apply: read returned %s", strerror(errno));
93                 size += nr;
94         }
95         *sizep = size;
96
97         /*
98          * Make sure that we have some slop in the buffer
99          * so that we can do speculative "memcmp" etc, and
100          * see to it that it is NUL-filled.
101          */
102         if (alloc < size + SLOP)
103                 buffer = xrealloc(buffer, size + SLOP);
104         memset(buffer + size, 0, SLOP);
105         return buffer;
106 }
107
108 static unsigned long linelen(const char *buffer, unsigned long size)
109 {
110         unsigned long len = 0;
111         while (size--) {
112                 len++;
113                 if (*buffer++ == '\n')
114                         break;
115         }
116         return len;
117 }
118
119 static int is_dev_null(const char *str)
120 {
121         return !memcmp("/dev/null", str, 9) && isspace(str[9]);
122 }
123
124 #define TERM_SPACE      1
125 #define TERM_TAB        2
126
127 static int name_terminate(const char *name, int namelen, int c, int terminate)
128 {
129         if (c == ' ' && !(terminate & TERM_SPACE))
130                 return 0;
131         if (c == '\t' && !(terminate & TERM_TAB))
132                 return 0;
133
134         return 1;
135 }
136
137 static char * find_name(const char *line, char *def, int p_value, int terminate)
138 {
139         int len;
140         const char *start = line;
141         char *name;
142
143         if (*line == '"') {
144                 /* Proposed "new-style" GNU patch/diff format; see
145                  * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
146                  */
147                 name = unquote_c_style(line, NULL);
148                 if (name) {
149                         char *cp = name;
150                         while (p_value) {
151                                 cp = strchr(name, '/');
152                                 if (!cp)
153                                         break;
154                                 cp++;
155                                 p_value--;
156                         }
157                         if (cp) {
158                                 /* name can later be freed, so we need
159                                  * to memmove, not just return cp
160                                  */
161                                 memmove(name, cp, strlen(cp) + 1);
162                                 free(def);
163                                 return name;
164                         }
165                         else {
166                                 free(name);
167                                 name = NULL;
168                         }
169                 }
170         }
171
172         for (;;) {
173                 char c = *line;
174
175                 if (isspace(c)) {
176                         if (c == '\n')
177                                 break;
178                         if (name_terminate(start, line-start, c, terminate))
179                                 break;
180                 }
181                 line++;
182                 if (c == '/' && !--p_value)
183                         start = line;
184         }
185         if (!start)
186                 return def;
187         len = line - start;
188         if (!len)
189                 return def;
190
191         /*
192          * Generally we prefer the shorter name, especially
193          * if the other one is just a variation of that with
194          * something else tacked on to the end (ie "file.orig"
195          * or "file~").
196          */
197         if (def) {
198                 int deflen = strlen(def);
199                 if (deflen < len && !strncmp(start, def, deflen))
200                         return def;
201         }
202
203         name = xmalloc(len + 1);
204         memcpy(name, start, len);
205         name[len] = 0;
206         free(def);
207         return name;
208 }
209
210 /*
211  * Get the name etc info from the --/+++ lines of a traditional patch header
212  *
213  * NOTE! This hardcodes "-p1" behaviour in filename detection.
214  *
215  * FIXME! The end-of-filename heuristics are kind of screwy. For existing
216  * files, we can happily check the index for a match, but for creating a
217  * new file we should try to match whatever "patch" does. I have no idea.
218  */
219 static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
220 {
221         char *name;
222
223         first += 4;     // skip "--- "
224         second += 4;    // skip "+++ "
225         if (is_dev_null(first)) {
226                 patch->is_new = 1;
227                 patch->is_delete = 0;
228                 name = find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB);
229                 patch->new_name = name;
230         } else if (is_dev_null(second)) {
231                 patch->is_new = 0;
232                 patch->is_delete = 1;
233                 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
234                 patch->old_name = name;
235         } else {
236                 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
237                 name = find_name(second, name, p_value, TERM_SPACE | TERM_TAB);
238                 patch->old_name = patch->new_name = name;
239         }
240         if (!name)
241                 die("unable to find filename in patch at line %d", linenr);
242 }
243
244 static int gitdiff_hdrend(const char *line, struct patch *patch)
245 {
246         return -1;
247 }
248
249 /*
250  * We're anal about diff header consistency, to make
251  * sure that we don't end up having strange ambiguous
252  * patches floating around.
253  *
254  * As a result, gitdiff_{old|new}name() will check
255  * their names against any previous information, just
256  * to make sure..
257  */
258 static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
259 {
260         if (!orig_name && !isnull)
261                 return find_name(line, NULL, 1, 0);
262
263         if (orig_name) {
264                 int len;
265                 const char *name;
266                 char *another;
267                 name = orig_name;
268                 len = strlen(name);
269                 if (isnull)
270                         die("git-apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
271                 another = find_name(line, NULL, 1, 0);
272                 if (!another || memcmp(another, name, len))
273                         die("git-apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
274                 free(another);
275                 return orig_name;
276         }
277         else {
278                 /* expect "/dev/null" */
279                 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
280                         die("git-apply: bad git-diff - expected /dev/null on line %d", linenr);
281                 return NULL;
282         }
283 }
284
285 static int gitdiff_oldname(const char *line, struct patch *patch)
286 {
287         patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
288         return 0;
289 }
290
291 static int gitdiff_newname(const char *line, struct patch *patch)
292 {
293         patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
294         return 0;
295 }
296
297 static int gitdiff_oldmode(const char *line, struct patch *patch)
298 {
299         patch->old_mode = strtoul(line, NULL, 8);
300         return 0;
301 }
302
303 static int gitdiff_newmode(const char *line, struct patch *patch)
304 {
305         patch->new_mode = strtoul(line, NULL, 8);
306         return 0;
307 }
308
309 static int gitdiff_delete(const char *line, struct patch *patch)
310 {
311         patch->is_delete = 1;
312         patch->old_name = patch->def_name;
313         return gitdiff_oldmode(line, patch);
314 }
315
316 static int gitdiff_newfile(const char *line, struct patch *patch)
317 {
318         patch->is_new = 1;
319         patch->new_name = patch->def_name;
320         return gitdiff_newmode(line, patch);
321 }
322
323 static int gitdiff_copysrc(const char *line, struct patch *patch)
324 {
325         patch->is_copy = 1;
326         patch->old_name = find_name(line, NULL, 0, 0);
327         return 0;
328 }
329
330 static int gitdiff_copydst(const char *line, struct patch *patch)
331 {
332         patch->is_copy = 1;
333         patch->new_name = find_name(line, NULL, 0, 0);
334         return 0;
335 }
336
337 static int gitdiff_renamesrc(const char *line, struct patch *patch)
338 {
339         patch->is_rename = 1;
340         patch->old_name = find_name(line, NULL, 0, 0);
341         return 0;
342 }
343
344 static int gitdiff_renamedst(const char *line, struct patch *patch)
345 {
346         patch->is_rename = 1;
347         patch->new_name = find_name(line, NULL, 0, 0);
348         return 0;
349 }
350
351 static int gitdiff_similarity(const char *line, struct patch *patch)
352 {
353         if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
354                 patch->score = 0;
355         return 0;
356 }
357
358 static int gitdiff_dissimilarity(const char *line, struct patch *patch)
359 {
360         if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
361                 patch->score = 0;
362         return 0;
363 }
364
365 static int gitdiff_index(const char *line, struct patch *patch)
366 {
367         /* index line is N hexadecimal, "..", N hexadecimal,
368          * and optional space with octal mode.
369          */
370         const char *ptr, *eol;
371         int len;
372
373         ptr = strchr(line, '.');
374         if (!ptr || ptr[1] != '.' || 40 < ptr - line)
375                 return 0;
376         len = ptr - line;
377         memcpy(patch->old_sha1_prefix, line, len);
378         patch->old_sha1_prefix[len] = 0;
379
380         line = ptr + 2;
381         ptr = strchr(line, ' ');
382         eol = strchr(line, '\n');
383
384         if (!ptr || eol < ptr)
385                 ptr = eol;
386         len = ptr - line;
387
388         if (40 < len)
389                 return 0;
390         memcpy(patch->new_sha1_prefix, line, len);
391         patch->new_sha1_prefix[len] = 0;
392         if (*ptr == ' ')
393                 patch->new_mode = patch->old_mode = strtoul(ptr+1, NULL, 8);
394         return 0;
395 }
396
397 /*
398  * This is normal for a diff that doesn't change anything: we'll fall through
399  * into the next diff. Tell the parser to break out.
400  */
401 static int gitdiff_unrecognized(const char *line, struct patch *patch)
402 {
403         return -1;
404 }
405
406 static const char *stop_at_slash(const char *line, int llen)
407 {
408         int i;
409
410         for (i = 0; i < llen; i++) {
411                 int ch = line[i];
412                 if (ch == '/')
413                         return line + i;
414         }
415         return NULL;
416 }
417
418 /* This is to extract the same name that appears on "diff --git"
419  * line.  We do not find and return anything if it is a rename
420  * patch, and it is OK because we will find the name elsewhere.
421  * We need to reliably find name only when it is mode-change only,
422  * creation or deletion of an empty file.  In any of these cases,
423  * both sides are the same name under a/ and b/ respectively.
424  */
425 static char *git_header_name(char *line, int llen)
426 {
427         int len;
428         const char *name;
429         const char *second = NULL;
430
431         line += strlen("diff --git ");
432         llen -= strlen("diff --git ");
433
434         if (*line == '"') {
435                 const char *cp;
436                 char *first = unquote_c_style(line, &second);
437                 if (!first)
438                         return NULL;
439
440                 /* advance to the first slash */
441                 cp = stop_at_slash(first, strlen(first));
442                 if (!cp || cp == first) {
443                         /* we do not accept absolute paths */
444                 free_first_and_fail:
445                         free(first);
446                         return NULL;
447                 }
448                 len = strlen(cp+1);
449                 memmove(first, cp+1, len+1); /* including NUL */
450
451                 /* second points at one past closing dq of name.
452                  * find the second name.
453                  */
454                 while ((second < line + llen) && isspace(*second))
455                         second++;
456
457                 if (line + llen <= second)
458                         goto free_first_and_fail;
459                 if (*second == '"') {
460                         char *sp = unquote_c_style(second, NULL);
461                         if (!sp)
462                                 goto free_first_and_fail;
463                         cp = stop_at_slash(sp, strlen(sp));
464                         if (!cp || cp == sp) {
465                         free_both_and_fail:
466                                 free(sp);
467                                 goto free_first_and_fail;
468                         }
469                         /* They must match, otherwise ignore */
470                         if (strcmp(cp+1, first))
471                                 goto free_both_and_fail;
472                         free(sp);
473                         return first;
474                 }
475
476                 /* unquoted second */
477                 cp = stop_at_slash(second, line + llen - second);
478                 if (!cp || cp == second)
479                         goto free_first_and_fail;
480                 cp++;
481                 if (line + llen - cp != len + 1 ||
482                     memcmp(first, cp, len))
483                         goto free_first_and_fail;
484                 return first;
485         }
486
487         /* unquoted first name */
488         name = stop_at_slash(line, llen);
489         if (!name || name == line)
490                 return NULL;
491
492         name++;
493
494         /* since the first name is unquoted, a dq if exists must be
495          * the beginning of the second name.
496          */
497         for (second = name; second < line + llen; second++) {
498                 if (*second == '"') {
499                         const char *cp = second;
500                         const char *np;
501                         char *sp = unquote_c_style(second, NULL);
502
503                         if (!sp)
504                                 return NULL;
505                         np = stop_at_slash(sp, strlen(sp));
506                         if (!np || np == sp) {
507                         free_second_and_fail:
508                                 free(sp);
509                                 return NULL;
510                         }
511                         np++;
512                         len = strlen(np);
513                         if (len < cp - name &&
514                             !strncmp(np, name, len) &&
515                             isspace(name[len])) {
516                                 /* Good */
517                                 memmove(sp, np, len + 1);
518                                 return sp;
519                         }
520                         goto free_second_and_fail;
521                 }
522         }
523
524         /*
525          * Accept a name only if it shows up twice, exactly the same
526          * form.
527          */
528         for (len = 0 ; ; len++) {
529                 char c = name[len];
530
531                 switch (c) {
532                 default:
533                         continue;
534                 case '\n':
535                         return NULL;
536                 case '\t': case ' ':
537                         second = name+len;
538                         for (;;) {
539                                 char c = *second++;
540                                 if (c == '\n')
541                                         return NULL;
542                                 if (c == '/')
543                                         break;
544                         }
545                         if (second[len] == '\n' && !memcmp(name, second, len)) {
546                                 char *ret = xmalloc(len + 1);
547                                 memcpy(ret, name, len);
548                                 ret[len] = 0;
549                                 return ret;
550                         }
551                 }
552         }
553         return NULL;
554 }
555
556 /* Verify that we recognize the lines following a git header */
557 static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
558 {
559         unsigned long offset;
560
561         /* A git diff has explicit new/delete information, so we don't guess */
562         patch->is_new = 0;
563         patch->is_delete = 0;
564
565         /*
566          * Some things may not have the old name in the
567          * rest of the headers anywhere (pure mode changes,
568          * or removing or adding empty files), so we get
569          * the default name from the header.
570          */
571         patch->def_name = git_header_name(line, len);
572
573         line += len;
574         size -= len;
575         linenr++;
576         for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
577                 static const struct opentry {
578                         const char *str;
579                         int (*fn)(const char *, struct patch *);
580                 } optable[] = {
581                         { "@@ -", gitdiff_hdrend },
582                         { "--- ", gitdiff_oldname },
583                         { "+++ ", gitdiff_newname },
584                         { "old mode ", gitdiff_oldmode },
585                         { "new mode ", gitdiff_newmode },
586                         { "deleted file mode ", gitdiff_delete },
587                         { "new file mode ", gitdiff_newfile },
588                         { "copy from ", gitdiff_copysrc },
589                         { "copy to ", gitdiff_copydst },
590                         { "rename old ", gitdiff_renamesrc },
591                         { "rename new ", gitdiff_renamedst },
592                         { "rename from ", gitdiff_renamesrc },
593                         { "rename to ", gitdiff_renamedst },
594                         { "similarity index ", gitdiff_similarity },
595                         { "dissimilarity index ", gitdiff_dissimilarity },
596                         { "index ", gitdiff_index },
597                         { "", gitdiff_unrecognized },
598                 };
599                 int i;
600
601                 len = linelen(line, size);
602                 if (!len || line[len-1] != '\n')
603                         break;
604                 for (i = 0; i < sizeof(optable) / sizeof(optable[0]); i++) {
605                         const struct opentry *p = optable + i;
606                         int oplen = strlen(p->str);
607                         if (len < oplen || memcmp(p->str, line, oplen))
608                                 continue;
609                         if (p->fn(line + oplen, patch) < 0)
610                                 return offset;
611                         break;
612                 }
613         }
614
615         return offset;
616 }
617
618 static int parse_num(const char *line, unsigned long *p)
619 {
620         char *ptr;
621
622         if (!isdigit(*line))
623                 return 0;
624         *p = strtoul(line, &ptr, 10);
625         return ptr - line;
626 }
627
628 static int parse_range(const char *line, int len, int offset, const char *expect,
629                         unsigned long *p1, unsigned long *p2)
630 {
631         int digits, ex;
632
633         if (offset < 0 || offset >= len)
634                 return -1;
635         line += offset;
636         len -= offset;
637
638         digits = parse_num(line, p1);
639         if (!digits)
640                 return -1;
641
642         offset += digits;
643         line += digits;
644         len -= digits;
645
646         *p2 = *p1;
647         if (*line == ',') {
648                 digits = parse_num(line+1, p2);
649                 if (!digits)
650                         return -1;
651
652                 offset += digits+1;
653                 line += digits+1;
654                 len -= digits+1;
655         }
656
657         ex = strlen(expect);
658         if (ex > len)
659                 return -1;
660         if (memcmp(line, expect, ex))
661                 return -1;
662
663         return offset + ex;
664 }
665
666 /*
667  * Parse a unified diff fragment header of the
668  * form "@@ -a,b +c,d @@"
669  */
670 static int parse_fragment_header(char *line, int len, struct fragment *fragment)
671 {
672         int offset;
673
674         if (!len || line[len-1] != '\n')
675                 return -1;
676
677         /* Figure out the number of lines in a fragment */
678         offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
679         offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
680
681         return offset;
682 }
683
684 static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
685 {
686         unsigned long offset, len;
687
688         patch->is_rename = patch->is_copy = 0;
689         patch->is_new = patch->is_delete = -1;
690         patch->old_mode = patch->new_mode = 0;
691         patch->old_name = patch->new_name = NULL;
692         for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
693                 unsigned long nextlen;
694
695                 len = linelen(line, size);
696                 if (!len)
697                         break;
698
699                 /* Testing this early allows us to take a few shortcuts.. */
700                 if (len < 6)
701                         continue;
702
703                 /*
704                  * Make sure we don't find any unconnected patch fragmants.
705                  * That's a sign that we didn't find a header, and that a
706                  * patch has become corrupted/broken up.
707                  */
708                 if (!memcmp("@@ -", line, 4)) {
709                         struct fragment dummy;
710                         if (parse_fragment_header(line, len, &dummy) < 0)
711                                 continue;
712                         error("patch fragment without header at line %d: %.*s", linenr, (int)len-1, line);
713                 }
714
715                 if (size < len + 6)
716                         break;
717
718                 /*
719                  * Git patch? It might not have a real patch, just a rename
720                  * or mode change, so we handle that specially
721                  */
722                 if (!memcmp("diff --git ", line, 11)) {
723                         int git_hdr_len = parse_git_header(line, len, size, patch);
724                         if (git_hdr_len <= len)
725                                 continue;
726                         if (!patch->old_name && !patch->new_name) {
727                                 if (!patch->def_name)
728                                         die("git diff header lacks filename information (line %d)", linenr);
729                                 patch->old_name = patch->new_name = patch->def_name;
730                         }
731                         *hdrsize = git_hdr_len;
732                         return offset;
733                 }
734
735                 /** --- followed by +++ ? */
736                 if (memcmp("--- ", line,  4) || memcmp("+++ ", line + len, 4))
737                         continue;
738
739                 /*
740                  * We only accept unified patches, so we want it to
741                  * at least have "@@ -a,b +c,d @@\n", which is 14 chars
742                  * minimum
743                  */
744                 nextlen = linelen(line + len, size - len);
745                 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
746                         continue;
747
748                 /* Ok, we'll consider it a patch */
749                 parse_traditional_patch(line, line+len, patch);
750                 *hdrsize = len + nextlen;
751                 linenr += 2;
752                 return offset;
753         }
754         return -1;
755 }
756
757 /*
758  * Parse a unified diff. Note that this really needs
759  * to parse each fragment separately, since the only
760  * way to know the difference between a "---" that is
761  * part of a patch, and a "---" that starts the next
762  * patch is to look at the line counts..
763  */
764 static int parse_fragment(char *line, unsigned long size, struct patch *patch, struct fragment *fragment)
765 {
766         int added, deleted;
767         int len = linelen(line, size), offset;
768         unsigned long oldlines, newlines;
769
770         offset = parse_fragment_header(line, len, fragment);
771         if (offset < 0)
772                 return -1;
773         oldlines = fragment->oldlines;
774         newlines = fragment->newlines;
775
776         if (patch->is_new < 0) {
777                 patch->is_new =  !oldlines;
778                 if (!oldlines)
779                         patch->old_name = NULL;
780         }
781         if (patch->is_delete < 0) {
782                 patch->is_delete = !newlines;
783                 if (!newlines)
784                         patch->new_name = NULL;
785         }
786
787         if (patch->is_new != !oldlines)
788                 return error("new file depends on old contents");
789         if (patch->is_delete != !newlines) {
790                 if (newlines)
791                         return error("deleted file still has contents");
792                 fprintf(stderr, "** warning: file %s becomes empty but is not deleted\n", patch->new_name);
793         }
794
795         /* Parse the thing.. */
796         line += len;
797         size -= len;
798         linenr++;
799         added = deleted = 0;
800         for (offset = len; size > 0; offset += len, size -= len, line += len, linenr++) {
801                 if (!oldlines && !newlines)
802                         break;
803                 len = linelen(line, size);
804                 if (!len || line[len-1] != '\n')
805                         return -1;
806                 switch (*line) {
807                 default:
808                         return -1;
809                 case ' ':
810                         oldlines--;
811                         newlines--;
812                         break;
813                 case '-':
814                         deleted++;
815                         oldlines--;
816                         break;
817                 case '+':
818                         added++;
819                         newlines--;
820                         break;
821
822                 /* We allow "\ No newline at end of file". Depending
823                  * on locale settings when the patch was produced we
824                  * don't know what this line looks like. The only
825                  * thing we do know is that it begins with "\ ".
826                  * Checking for 12 is just for sanity check -- any
827                  * l10n of "\ No newline..." is at least that long.
828                  */
829                 case '\\':
830                         if (len < 12 || memcmp(line, "\\ ", 2))
831                                 return -1;
832                         break;
833                 }
834         }
835         /* If a fragment ends with an incomplete line, we failed to include
836          * it in the above loop because we hit oldlines == newlines == 0
837          * before seeing it.
838          */
839         if (12 < size && !memcmp(line, "\\ ", 2))
840                 offset += linelen(line, size);
841
842         patch->lines_added += added;
843         patch->lines_deleted += deleted;
844         return offset;
845 }
846
847 static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
848 {
849         unsigned long offset = 0;
850         struct fragment **fragp = &patch->fragments;
851
852         while (size > 4 && !memcmp(line, "@@ -", 4)) {
853                 struct fragment *fragment;
854                 int len;
855
856                 fragment = xmalloc(sizeof(*fragment));
857                 memset(fragment, 0, sizeof(*fragment));
858                 len = parse_fragment(line, size, patch, fragment);
859                 if (len <= 0)
860                         die("corrupt patch at line %d", linenr);
861
862                 fragment->patch = line;
863                 fragment->size = len;
864
865                 *fragp = fragment;
866                 fragp = &fragment->next;
867
868                 offset += len;
869                 line += len;
870                 size -= len;
871         }
872         return offset;
873 }
874
875 static inline int metadata_changes(struct patch *patch)
876 {
877         return  patch->is_rename > 0 ||
878                 patch->is_copy > 0 ||
879                 patch->is_new > 0 ||
880                 patch->is_delete ||
881                 (patch->old_mode && patch->new_mode &&
882                  patch->old_mode != patch->new_mode);
883 }
884
885 static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
886 {
887         int hdrsize, patchsize;
888         int offset = find_header(buffer, size, &hdrsize, patch);
889
890         if (offset < 0)
891                 return offset;
892
893         patchsize = parse_single_patch(buffer + offset + hdrsize, size - offset - hdrsize, patch);
894
895         if (!patchsize) {
896                 static const char *binhdr[] = {
897                         "Binary files ",
898                         "Files ",
899                         NULL,
900                 };
901                 int i;
902                 int hd = hdrsize + offset;
903                 unsigned long llen = linelen(buffer + hd, size - hd);
904
905                 if (!memcmp(" differ\n", buffer + hd + llen - 8, 8))
906                         for (i = 0; binhdr[i]; i++) {
907                                 int len = strlen(binhdr[i]);
908                                 if (len < size - hd &&
909                                     !memcmp(binhdr[i], buffer + hd, len)) {
910                                         patch->is_binary = 1;
911                                         break;
912                                 }
913                         }
914
915                 /* Empty patch cannot be applied if:
916                  * - it is a binary patch and we do not do binary_replace, or
917                  * - text patch without metadata change
918                  */
919                 if ((apply || check) &&
920                     (patch->is_binary
921                      ? !allow_binary_replacement
922                      : !metadata_changes(patch)))
923                         die("patch with only garbage at line %d", linenr);
924         }
925
926         return offset + hdrsize + patchsize;
927 }
928
929 static const char pluses[] = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
930 static const char minuses[]= "----------------------------------------------------------------------";
931
932 static void show_stats(struct patch *patch)
933 {
934         const char *prefix = "";
935         char *name = patch->new_name;
936         char *qname = NULL;
937         int len, max, add, del, total;
938
939         if (!name)
940                 name = patch->old_name;
941
942         if (0 < (len = quote_c_style(name, NULL, NULL, 0))) {
943                 qname = xmalloc(len + 1);
944                 quote_c_style(name, qname, NULL, 0);
945                 name = qname;
946         }
947
948         /*
949          * "scale" the filename
950          */
951         len = strlen(name);
952         max = max_len;
953         if (max > 50)
954                 max = 50;
955         if (len > max) {
956                 char *slash;
957                 prefix = "...";
958                 max -= 3;
959                 name += len - max;
960                 slash = strchr(name, '/');
961                 if (slash)
962                         name = slash;
963         }
964         len = max;
965
966         /*
967          * scale the add/delete
968          */
969         max = max_change;
970         if (max + len > 70)
971                 max = 70 - len;
972
973         add = patch->lines_added;
974         del = patch->lines_deleted;
975         total = add + del;
976
977         if (max_change > 0) {
978                 total = (total * max + max_change / 2) / max_change;
979                 add = (add * max + max_change / 2) / max_change;
980                 del = total - add;
981         }
982         if (patch->is_binary)
983                 printf(" %s%-*s |  Bin\n", prefix, len, name);
984         else
985                 printf(" %s%-*s |%5d %.*s%.*s\n", prefix,
986                        len, name, patch->lines_added + patch->lines_deleted,
987                        add, pluses, del, minuses);
988         if (qname)
989                 free(qname);
990 }
991
992 static int read_old_data(struct stat *st, const char *path, void *buf, unsigned long size)
993 {
994         int fd;
995         unsigned long got;
996
997         switch (st->st_mode & S_IFMT) {
998         case S_IFLNK:
999                 return readlink(path, buf, size);
1000         case S_IFREG:
1001                 fd = open(path, O_RDONLY);
1002                 if (fd < 0)
1003                         return error("unable to open %s", path);
1004                 got = 0;
1005                 for (;;) {
1006                         int ret = xread(fd, buf + got, size - got);
1007                         if (ret <= 0)
1008                                 break;
1009                         got += ret;
1010                 }
1011                 close(fd);
1012                 return got;
1013
1014         default:
1015                 return -1;
1016         }
1017 }
1018
1019 static int find_offset(const char *buf, unsigned long size, const char *fragment, unsigned long fragsize, int line)
1020 {
1021         int i;
1022         unsigned long start, backwards, forwards;
1023
1024         if (fragsize > size)
1025                 return -1;
1026
1027         start = 0;
1028         if (line > 1) {
1029                 unsigned long offset = 0;
1030                 i = line-1;
1031                 while (offset + fragsize <= size) {
1032                         if (buf[offset++] == '\n') {
1033                                 start = offset;
1034                                 if (!--i)
1035                                         break;
1036                         }
1037                 }
1038         }
1039
1040         /* Exact line number? */
1041         if (!memcmp(buf + start, fragment, fragsize))
1042                 return start;
1043
1044         /*
1045          * There's probably some smart way to do this, but I'll leave
1046          * that to the smart and beautiful people. I'm simple and stupid.
1047          */
1048         backwards = start;
1049         forwards = start;
1050         for (i = 0; ; i++) {
1051                 unsigned long try;
1052                 int n;
1053
1054                 /* "backward" */
1055                 if (i & 1) {
1056                         if (!backwards) {
1057                                 if (forwards + fragsize > size)
1058                                         break;
1059                                 continue;
1060                         }
1061                         do {
1062                                 --backwards;
1063                         } while (backwards && buf[backwards-1] != '\n');
1064                         try = backwards;
1065                 } else {
1066                         while (forwards + fragsize <= size) {
1067                                 if (buf[forwards++] == '\n')
1068                                         break;
1069                         }
1070                         try = forwards;
1071                 }
1072
1073                 if (try + fragsize > size)
1074                         continue;
1075                 if (memcmp(buf + try, fragment, fragsize))
1076                         continue;
1077                 n = (i >> 1)+1;
1078                 if (i & 1)
1079                         n = -n;
1080                 return try;
1081         }
1082
1083         /*
1084          * We should start searching forward and backward.
1085          */
1086         return -1;
1087 }
1088
1089 struct buffer_desc {
1090         char *buffer;
1091         unsigned long size;
1092         unsigned long alloc;
1093 };
1094
1095 static int apply_one_fragment(struct buffer_desc *desc, struct fragment *frag)
1096 {
1097         char *buf = desc->buffer;
1098         const char *patch = frag->patch;
1099         int offset, size = frag->size;
1100         char *old = xmalloc(size);
1101         char *new = xmalloc(size);
1102         int oldsize = 0, newsize = 0;
1103
1104         while (size > 0) {
1105                 int len = linelen(patch, size);
1106                 int plen;
1107
1108                 if (!len)
1109                         break;
1110
1111                 /*
1112                  * "plen" is how much of the line we should use for
1113                  * the actual patch data. Normally we just remove the
1114                  * first character on the line, but if the line is
1115                  * followed by "\ No newline", then we also remove the
1116                  * last one (which is the newline, of course).
1117                  */
1118                 plen = len-1;
1119                 if (len < size && patch[len] == '\\')
1120                         plen--;
1121                 switch (*patch) {
1122                 case ' ':
1123                 case '-':
1124                         memcpy(old + oldsize, patch + 1, plen);
1125                         oldsize += plen;
1126                         if (*patch == '-')
1127                                 break;
1128                 /* Fall-through for ' ' */
1129                 case '+':
1130                         if (*patch != '+' || !no_add) {
1131                                 memcpy(new + newsize, patch + 1, plen);
1132                                 newsize += plen;
1133                         }
1134                         break;
1135                 case '@': case '\\':
1136                         /* Ignore it, we already handled it */
1137                         break;
1138                 default:
1139                         return -1;
1140                 }
1141                 patch += len;
1142                 size -= len;
1143         }
1144
1145         offset = find_offset(buf, desc->size, old, oldsize, frag->newpos);
1146         if (offset >= 0) {
1147                 int diff = newsize - oldsize;
1148                 unsigned long size = desc->size + diff;
1149                 unsigned long alloc = desc->alloc;
1150
1151                 if (size > alloc) {
1152                         alloc = size + 8192;
1153                         desc->alloc = alloc;
1154                         buf = xrealloc(buf, alloc);
1155                         desc->buffer = buf;
1156                 }
1157                 desc->size = size;
1158                 memmove(buf + offset + newsize, buf + offset + oldsize, size - offset - newsize);
1159                 memcpy(buf + offset, new, newsize);
1160                 offset = 0;
1161         }
1162
1163         free(old);
1164         free(new);
1165         return offset;
1166 }
1167
1168 static int apply_fragments(struct buffer_desc *desc, struct patch *patch)
1169 {
1170         struct fragment *frag = patch->fragments;
1171         const char *name = patch->old_name ? patch->old_name : patch->new_name;
1172
1173         if (patch->is_binary) {
1174                 unsigned char sha1[20];
1175
1176                 if (!allow_binary_replacement)
1177                         return error("cannot apply binary patch to '%s' "
1178                                      "without --allow-binary-replacement",
1179                                      name);
1180
1181                 /* For safety, we require patch index line to contain
1182                  * full 40-byte textual SHA1 for old and new, at least for now.
1183                  */
1184                 if (strlen(patch->old_sha1_prefix) != 40 ||
1185                     strlen(patch->new_sha1_prefix) != 40 ||
1186                     get_sha1_hex(patch->old_sha1_prefix, sha1) ||
1187                     get_sha1_hex(patch->new_sha1_prefix, sha1))
1188                         return error("cannot apply binary patch to '%s' "
1189                                      "without full index line", name);
1190
1191                 if (patch->old_name) {
1192                         unsigned char hdr[50];
1193                         int hdrlen;
1194
1195                         /* See if the old one matches what the patch
1196                          * applies to.
1197                          */
1198                         write_sha1_file_prepare(desc->buffer, desc->size,
1199                                                 "blob", sha1, hdr, &hdrlen);
1200                         if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
1201                                 return error("the patch applies to '%s' (%s), "
1202                                              "which does not match the "
1203                                              "current contents.",
1204                                              name, sha1_to_hex(sha1));
1205                 }
1206                 else {
1207                         /* Otherwise, the old one must be empty. */
1208                         if (desc->size)
1209                                 return error("the patch applies to an empty "
1210                                              "'%s' but it is not empty", name);
1211                 }
1212
1213                 /* For now, we do not record post-image data in the patch,
1214                  * and require the object already present in the recipient's
1215                  * object database.
1216                  */
1217                 if (desc->buffer) {
1218                         free(desc->buffer);
1219                         desc->alloc = desc->size = 0;
1220                 }
1221                 get_sha1_hex(patch->new_sha1_prefix, sha1);
1222
1223                 if (memcmp(sha1, null_sha1, 20)) {
1224                         char type[10];
1225                         unsigned long size;
1226
1227                         desc->buffer = read_sha1_file(sha1, type, &size);
1228                         if (!desc->buffer)
1229                                 return error("the necessary postimage %s for "
1230                                              "'%s' does not exist",
1231                                              patch->new_sha1_prefix, name);
1232                         desc->alloc = desc->size = size;
1233                 }
1234
1235                 return 0;
1236         }
1237
1238         while (frag) {
1239                 if (apply_one_fragment(desc, frag) < 0)
1240                         return error("patch failed: %s:%ld",
1241                                      name, frag->oldpos);
1242                 frag = frag->next;
1243         }
1244         return 0;
1245 }
1246
1247 static int apply_data(struct patch *patch, struct stat *st)
1248 {
1249         char *buf;
1250         unsigned long size, alloc;
1251         struct buffer_desc desc;
1252
1253         size = 0;
1254         alloc = 0;
1255         buf = NULL;
1256         if (patch->old_name) {
1257                 size = st->st_size;
1258                 alloc = size + 8192;
1259                 buf = xmalloc(alloc);
1260                 if (read_old_data(st, patch->old_name, buf, alloc) != size)
1261                         return error("read of %s failed", patch->old_name);
1262         }
1263
1264         desc.size = size;
1265         desc.alloc = alloc;
1266         desc.buffer = buf;
1267         if (apply_fragments(&desc, patch) < 0)
1268                 return -1;
1269         patch->result = desc.buffer;
1270         patch->resultsize = desc.size;
1271
1272         if (patch->is_delete && patch->resultsize)
1273                 return error("removal patch leaves file contents");
1274
1275         return 0;
1276 }
1277
1278 static int check_patch(struct patch *patch)
1279 {
1280         struct stat st;
1281         const char *old_name = patch->old_name;
1282         const char *new_name = patch->new_name;
1283         const char *name = old_name ? old_name : new_name;
1284
1285         if (old_name) {
1286                 int changed;
1287                 int stat_ret = lstat(old_name, &st);
1288
1289                 if (check_index) {
1290                         int pos = cache_name_pos(old_name, strlen(old_name));
1291                         if (pos < 0)
1292                                 return error("%s: does not exist in index",
1293                                              old_name);
1294                         if (stat_ret < 0) {
1295                                 struct checkout costate;
1296                                 if (errno != ENOENT)
1297                                         return error("%s: %s", old_name,
1298                                                      strerror(errno));
1299                                 /* checkout */
1300                                 costate.base_dir = "";
1301                                 costate.base_dir_len = 0;
1302                                 costate.force = 0;
1303                                 costate.quiet = 0;
1304                                 costate.not_new = 0;
1305                                 costate.refresh_cache = 1;
1306                                 if (checkout_entry(active_cache[pos],
1307                                                    &costate) ||
1308                                     lstat(old_name, &st))
1309                                         return -1;
1310                         }
1311
1312                         changed = ce_match_stat(active_cache[pos], &st);
1313                         if (changed)
1314                                 return error("%s: does not match index",
1315                                              old_name);
1316                 }
1317                 else if (stat_ret < 0)
1318                         return error("%s: %s", old_name, strerror(errno));
1319
1320                 if (patch->is_new < 0)
1321                         patch->is_new = 0;
1322                 st.st_mode = ntohl(create_ce_mode(st.st_mode));
1323                 if (!patch->old_mode)
1324                         patch->old_mode = st.st_mode;
1325                 if ((st.st_mode ^ patch->old_mode) & S_IFMT)
1326                         return error("%s: wrong type", old_name);
1327                 if (st.st_mode != patch->old_mode)
1328                         fprintf(stderr, "warning: %s has type %o, expected %o\n",
1329                                 old_name, st.st_mode, patch->old_mode);
1330         }
1331
1332         if (new_name && (patch->is_new | patch->is_rename | patch->is_copy)) {
1333                 if (check_index && cache_name_pos(new_name, strlen(new_name)) >= 0)
1334                         return error("%s: already exists in index", new_name);
1335                 if (!lstat(new_name, &st))
1336                         return error("%s: already exists in working directory", new_name);
1337                 if (errno != ENOENT)
1338                         return error("%s: %s", new_name, strerror(errno));
1339                 if (!patch->new_mode) {
1340                         if (patch->is_new)
1341                                 patch->new_mode = S_IFREG | 0644;
1342                         else
1343                                 patch->new_mode = patch->old_mode;
1344                 }
1345         }
1346
1347         if (new_name && old_name) {
1348                 int same = !strcmp(old_name, new_name);
1349                 if (!patch->new_mode)
1350                         patch->new_mode = patch->old_mode;
1351                 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
1352                         return error("new mode (%o) of %s does not match old mode (%o)%s%s",
1353                                 patch->new_mode, new_name, patch->old_mode,
1354                                 same ? "" : " of ", same ? "" : old_name);
1355         }       
1356
1357         if (apply_data(patch, &st) < 0)
1358                 return error("%s: patch does not apply", name);
1359         return 0;
1360 }
1361
1362 static int check_patch_list(struct patch *patch)
1363 {
1364         int error = 0;
1365
1366         for (;patch ; patch = patch->next)
1367                 error |= check_patch(patch);
1368         return error;
1369 }
1370
1371 static inline int is_null_sha1(const unsigned char *sha1)
1372 {
1373         return !memcmp(sha1, null_sha1, 20);
1374 }
1375
1376 static void show_index_list(struct patch *list)
1377 {
1378         struct patch *patch;
1379
1380         /* Once we start supporting the reverse patch, it may be
1381          * worth showing the new sha1 prefix, but until then...
1382          */
1383         for (patch = list; patch; patch = patch->next) {
1384                 const unsigned char *sha1_ptr;
1385                 unsigned char sha1[20];
1386                 const char *name;
1387
1388                 name = patch->old_name ? patch->old_name : patch->new_name;
1389                 if (patch->is_new)
1390                         sha1_ptr = null_sha1;
1391                 else if (get_sha1(patch->old_sha1_prefix, sha1))
1392                         die("sha1 information is lacking or useless (%s).",
1393                             name);
1394                 else
1395                         sha1_ptr = sha1;
1396
1397                 printf("%06o %s ",patch->old_mode, sha1_to_hex(sha1_ptr));
1398                 if (line_termination && quote_c_style(name, NULL, NULL, 0))
1399                         quote_c_style(name, NULL, stdout, 0);
1400                 else
1401                         fputs(name, stdout);
1402                 putchar(line_termination);
1403         }
1404 }
1405
1406 static void stat_patch_list(struct patch *patch)
1407 {
1408         int files, adds, dels;
1409
1410         for (files = adds = dels = 0 ; patch ; patch = patch->next) {
1411                 files++;
1412                 adds += patch->lines_added;
1413                 dels += patch->lines_deleted;
1414                 show_stats(patch);
1415         }
1416
1417         printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
1418 }
1419
1420 static void numstat_patch_list(struct patch *patch)
1421 {
1422         for ( ; patch; patch = patch->next) {
1423                 const char *name;
1424                 name = patch->old_name ? patch->old_name : patch->new_name;
1425                 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
1426                 if (line_termination && quote_c_style(name, NULL, NULL, 0))
1427                         quote_c_style(name, NULL, stdout, 0);
1428                 else
1429                         fputs(name, stdout);
1430                 putchar('\n');
1431         }
1432 }
1433
1434 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
1435 {
1436         if (mode)
1437                 printf(" %s mode %06o %s\n", newdelete, mode, name);
1438         else
1439                 printf(" %s %s\n", newdelete, name);
1440 }
1441
1442 static void show_mode_change(struct patch *p, int show_name)
1443 {
1444         if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
1445                 if (show_name)
1446                         printf(" mode change %06o => %06o %s\n",
1447                                p->old_mode, p->new_mode, p->new_name);
1448                 else
1449                         printf(" mode change %06o => %06o\n",
1450                                p->old_mode, p->new_mode);
1451         }
1452 }
1453
1454 static void show_rename_copy(struct patch *p)
1455 {
1456         const char *renamecopy = p->is_rename ? "rename" : "copy";
1457         const char *old, *new;
1458
1459         /* Find common prefix */
1460         old = p->old_name;
1461         new = p->new_name;
1462         while (1) {
1463                 const char *slash_old, *slash_new;
1464                 slash_old = strchr(old, '/');
1465                 slash_new = strchr(new, '/');
1466                 if (!slash_old ||
1467                     !slash_new ||
1468                     slash_old - old != slash_new - new ||
1469                     memcmp(old, new, slash_new - new))
1470                         break;
1471                 old = slash_old + 1;
1472                 new = slash_new + 1;
1473         }
1474         /* p->old_name thru old is the common prefix, and old and new
1475          * through the end of names are renames
1476          */
1477         if (old != p->old_name)
1478                 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
1479                        (int)(old - p->old_name), p->old_name,
1480                        old, new, p->score);
1481         else
1482                 printf(" %s %s => %s (%d%%)\n", renamecopy,
1483                        p->old_name, p->new_name, p->score);
1484         show_mode_change(p, 0);
1485 }
1486
1487 static void summary_patch_list(struct patch *patch)
1488 {
1489         struct patch *p;
1490
1491         for (p = patch; p; p = p->next) {
1492                 if (p->is_new)
1493                         show_file_mode_name("create", p->new_mode, p->new_name);
1494                 else if (p->is_delete)
1495                         show_file_mode_name("delete", p->old_mode, p->old_name);
1496                 else {
1497                         if (p->is_rename || p->is_copy)
1498                                 show_rename_copy(p);
1499                         else {
1500                                 if (p->score) {
1501                                         printf(" rewrite %s (%d%%)\n",
1502                                                p->new_name, p->score);
1503                                         show_mode_change(p, 0);
1504                                 }
1505                                 else
1506                                         show_mode_change(p, 1);
1507                         }
1508                 }
1509         }
1510 }
1511
1512 static void patch_stats(struct patch *patch)
1513 {
1514         int lines = patch->lines_added + patch->lines_deleted;
1515
1516         if (lines > max_change)
1517                 max_change = lines;
1518         if (patch->old_name) {
1519                 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
1520                 if (!len)
1521                         len = strlen(patch->old_name);
1522                 if (len > max_len)
1523                         max_len = len;
1524         }
1525         if (patch->new_name) {
1526                 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
1527                 if (!len)
1528                         len = strlen(patch->new_name);
1529                 if (len > max_len)
1530                         max_len = len;
1531         }
1532 }
1533
1534 static void remove_file(struct patch *patch)
1535 {
1536         if (write_index) {
1537                 if (remove_file_from_cache(patch->old_name) < 0)
1538                         die("unable to remove %s from index", patch->old_name);
1539         }
1540         unlink(patch->old_name);
1541 }
1542
1543 static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
1544 {
1545         struct stat st;
1546         struct cache_entry *ce;
1547         int namelen = strlen(path);
1548         unsigned ce_size = cache_entry_size(namelen);
1549
1550         if (!write_index)
1551                 return;
1552
1553         ce = xmalloc(ce_size);
1554         memset(ce, 0, ce_size);
1555         memcpy(ce->name, path, namelen);
1556         ce->ce_mode = create_ce_mode(mode);
1557         ce->ce_flags = htons(namelen);
1558         if (lstat(path, &st) < 0)
1559                 die("unable to stat newly created file %s", path);
1560         fill_stat_cache_info(ce, &st);
1561         if (write_sha1_file(buf, size, "blob", ce->sha1) < 0)
1562                 die("unable to create backing store for newly created file %s", path);
1563         if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
1564                 die("unable to add cache entry for %s", path);
1565 }
1566
1567 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
1568 {
1569         int fd;
1570
1571         if (S_ISLNK(mode))
1572                 return symlink(buf, path);
1573         fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
1574         if (fd < 0)
1575                 return -1;
1576         while (size) {
1577                 int written = xwrite(fd, buf, size);
1578                 if (written < 0)
1579                         die("writing file %s: %s", path, strerror(errno));
1580                 if (!written)
1581                         die("out of space writing file %s", path);
1582                 buf += written;
1583                 size -= written;
1584         }
1585         if (close(fd) < 0)
1586                 die("closing file %s: %s", path, strerror(errno));
1587         return 0;
1588 }
1589
1590 /*
1591  * We optimistically assume that the directories exist,
1592  * which is true 99% of the time anyway. If they don't,
1593  * we create them and try again.
1594  */
1595 static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
1596 {
1597         if (!try_create_file(path, mode, buf, size))
1598                 return;
1599
1600         if (errno == ENOENT) {
1601                 if (safe_create_leading_directories(path))
1602                         return;
1603                 if (!try_create_file(path, mode, buf, size))
1604                         return;
1605         }
1606
1607         if (errno == EEXIST) {
1608                 unsigned int nr = getpid();
1609
1610                 for (;;) {
1611                         const char *newpath;
1612                         newpath = mkpath("%s~%u", path, nr);
1613                         if (!try_create_file(newpath, mode, buf, size)) {
1614                                 if (!rename(newpath, path))
1615                                         return;
1616                                 unlink(newpath);
1617                                 break;
1618                         }
1619                         if (errno != EEXIST)
1620                                 break;
1621                         ++nr;
1622                 }
1623         }
1624         die("unable to write file %s mode %o", path, mode);
1625 }
1626
1627 static void create_file(struct patch *patch)
1628 {
1629         char *path = patch->new_name;
1630         unsigned mode = patch->new_mode;
1631         unsigned long size = patch->resultsize;
1632         char *buf = patch->result;
1633
1634         if (!mode)
1635                 mode = S_IFREG | 0644;
1636         create_one_file(path, mode, buf, size); 
1637         add_index_file(path, mode, buf, size);
1638 }
1639
1640 static void write_out_one_result(struct patch *patch)
1641 {
1642         if (patch->is_delete > 0) {
1643                 remove_file(patch);
1644                 return;
1645         }
1646         if (patch->is_new > 0 || patch->is_copy) {
1647                 create_file(patch);
1648                 return;
1649         }
1650         /*
1651          * Rename or modification boils down to the same
1652          * thing: remove the old, write the new
1653          */
1654         remove_file(patch);
1655         create_file(patch);
1656 }
1657
1658 static void write_out_results(struct patch *list, int skipped_patch)
1659 {
1660         if (!list && !skipped_patch)
1661                 die("No changes");
1662
1663         while (list) {
1664                 write_out_one_result(list);
1665                 list = list->next;
1666         }
1667 }
1668
1669 static struct cache_file cache_file;
1670
1671 static struct excludes {
1672         struct excludes *next;
1673         const char *path;
1674 } *excludes;
1675
1676 static int use_patch(struct patch *p)
1677 {
1678         const char *pathname = p->new_name ? p->new_name : p->old_name;
1679         struct excludes *x = excludes;
1680         while (x) {
1681                 if (fnmatch(x->path, pathname, 0) == 0)
1682                         return 0;
1683                 x = x->next;
1684         }
1685         if (0 < prefix_length) {
1686                 int pathlen = strlen(pathname);
1687                 if (pathlen <= prefix_length ||
1688                     memcmp(prefix, pathname, prefix_length))
1689                         return 0;
1690         }
1691         return 1;
1692 }
1693
1694 static int apply_patch(int fd)
1695 {
1696         int newfd;
1697         unsigned long offset, size;
1698         char *buffer = read_patch_file(fd, &size);
1699         struct patch *list = NULL, **listp = &list;
1700         int skipped_patch = 0;
1701
1702         if (!buffer)
1703                 return -1;
1704         offset = 0;
1705         while (size > 0) {
1706                 struct patch *patch;
1707                 int nr;
1708
1709                 patch = xmalloc(sizeof(*patch));
1710                 memset(patch, 0, sizeof(*patch));
1711                 nr = parse_chunk(buffer + offset, size, patch);
1712                 if (nr < 0)
1713                         break;
1714                 if (use_patch(patch)) {
1715                         patch_stats(patch);
1716                         *listp = patch;
1717                         listp = &patch->next;
1718                 } else {
1719                         /* perhaps free it a bit better? */
1720                         free(patch);
1721                         skipped_patch++;
1722                 }
1723                 offset += nr;
1724                 size -= nr;
1725         }
1726
1727         newfd = -1;
1728         write_index = check_index && apply;
1729         if (write_index)
1730                 newfd = hold_index_file_for_update(&cache_file, get_index_file());
1731         if (check_index) {
1732                 if (read_cache() < 0)
1733                         die("unable to read index file");
1734         }
1735
1736         if ((check || apply) && check_patch_list(list) < 0)
1737                 exit(1);
1738
1739         if (apply)
1740                 write_out_results(list, skipped_patch);
1741
1742         if (write_index) {
1743                 if (write_cache(newfd, active_cache, active_nr) ||
1744                     commit_index_file(&cache_file))
1745                         die("Unable to write new cachefile");
1746         }
1747
1748         if (show_index_info)
1749                 show_index_list(list);
1750
1751         if (diffstat)
1752                 stat_patch_list(list);
1753
1754         if (numstat)
1755                 numstat_patch_list(list);
1756
1757         if (summary)
1758                 summary_patch_list(list);
1759
1760         free(buffer);
1761         return 0;
1762 }
1763
1764 int main(int argc, char **argv)
1765 {
1766         int i;
1767         int read_stdin = 1;
1768
1769         for (i = 1; i < argc; i++) {
1770                 const char *arg = argv[i];
1771                 int fd;
1772
1773                 if (!strcmp(arg, "-")) {
1774                         apply_patch(0);
1775                         read_stdin = 0;
1776                         continue;
1777                 }
1778                 if (!strncmp(arg, "--exclude=", 10)) {
1779                         struct excludes *x = xmalloc(sizeof(*x));
1780                         x->path = arg + 10;
1781                         x->next = excludes;
1782                         excludes = x;
1783                         continue;
1784                 }
1785                 if (!strncmp(arg, "-p", 2)) {
1786                         p_value = atoi(arg + 2);
1787                         continue;
1788                 }
1789                 if (!strcmp(arg, "--no-add")) {
1790                         no_add = 1;
1791                         continue;
1792                 }
1793                 if (!strcmp(arg, "--stat")) {
1794                         apply = 0;
1795                         diffstat = 1;
1796                         continue;
1797                 }
1798                 if (!strcmp(arg, "--allow-binary-replacement")) {
1799                         allow_binary_replacement = 1;
1800                         continue;
1801                 }
1802                 if (!strcmp(arg, "--numstat")) {
1803                         apply = 0;
1804                         numstat = 1;
1805                         continue;
1806                 }
1807                 if (!strcmp(arg, "--summary")) {
1808                         apply = 0;
1809                         summary = 1;
1810                         continue;
1811                 }
1812                 if (!strcmp(arg, "--check")) {
1813                         apply = 0;
1814                         check = 1;
1815                         continue;
1816                 }
1817                 if (!strcmp(arg, "--index")) {
1818                         check_index = 1;
1819                         continue;
1820                 }
1821                 if (!strcmp(arg, "--apply")) {
1822                         apply = 1;
1823                         continue;
1824                 }
1825                 if (!strcmp(arg, "--index-info")) {
1826                         apply = 0;
1827                         show_index_info = 1;
1828                         continue;
1829                 }
1830                 if (!strcmp(arg, "-z")) {
1831                         line_termination = 0;
1832                         continue;
1833                 }
1834
1835                 if (check_index && prefix_length < 0) {
1836                         prefix = setup_git_directory();
1837                         prefix_length = prefix ? strlen(prefix) : 0;
1838                         git_config(git_default_config);
1839                 }
1840                 if (0 < prefix_length)
1841                         arg = prefix_filename(prefix, prefix_length, arg);
1842
1843                 fd = open(arg, O_RDONLY);
1844                 if (fd < 0)
1845                         usage(apply_usage);
1846                 read_stdin = 0;
1847                 apply_patch(fd);
1848                 close(fd);
1849         }
1850         if (read_stdin)
1851                 apply_patch(0);
1852         return 0;
1853 }