Functions to quote and unquote pathnames in C-style.
[git/git.git] / apply.c
CommitLineData
c1bb9350
LT
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 *
c1bb9350 8 */
d854f783 9#include <fnmatch.h>
c1bb9350
LT
10#include "cache.h"
11
a577284a
LT
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
2cf67f1e 16// --show-index-info shows the old and new index info for paths if available.
a577284a 17//
3cca928d 18static int check_index = 0;
5aa7d94c 19static int write_index = 0;
fab2c257 20static int diffstat = 0;
96c912a4 21static int summary = 0;
a577284a
LT
22static int check = 0;
23static int apply = 1;
24static int show_files = 0;
2cf67f1e 25static int show_index_info = 0;
12dd6e8c 26static const char apply_usage[] =
2cf67f1e 27"git-apply [--stat] [--summary] [--check] [--index] [--apply] [--show-files] [--show-index-info] <patch>...";
c1bb9350 28
3f40315a
LT
29/*
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.
33 */
34static int max_change, max_len;
35
a4acb0eb
LT
36/*
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".
40 */
46979f56 41static int linenr = 1;
19c58fb8
LT
42
43struct fragment {
44 unsigned long oldpos, oldlines;
45 unsigned long newpos, newlines;
46 const char *patch;
47 int size;
48 struct fragment *next;
49};
50
51struct patch {
5041aa70 52 char *new_name, *old_name, *def_name;
19c58fb8
LT
53 unsigned int old_mode, new_mode;
54 int is_rename, is_copy, is_new, is_delete;
3f40315a 55 int lines_added, lines_deleted;
96c912a4 56 int score;
19c58fb8 57 struct fragment *fragments;
5aa7d94c 58 char *result;
3cca928d 59 unsigned long resultsize;
2cf67f1e
JH
60 char old_sha1_prefix[41];
61 char new_sha1_prefix[41];
19c58fb8
LT
62 struct patch *next;
63};
46979f56 64
c1bb9350 65#define CHUNKSIZE (8192)
a4acb0eb 66#define SLOP (16)
c1bb9350
LT
67
68static void *read_patch_file(int fd, unsigned long *sizep)
69{
70 unsigned long size = 0, alloc = CHUNKSIZE;
71 void *buffer = xmalloc(alloc);
72
73 for (;;) {
74 int nr = alloc - size;
75 if (nr < 1024) {
76 alloc += CHUNKSIZE;
77 buffer = xrealloc(buffer, alloc);
78 nr = alloc - size;
79 }
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));
87 }
88 size += nr;
89 }
90 *sizep = size;
a4acb0eb
LT
91
92 /*
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.
96 */
97 if (alloc < size + SLOP)
98 buffer = xrealloc(buffer, size + SLOP);
99 memset(buffer + size, 0, SLOP);
c1bb9350
LT
100 return buffer;
101}
102
3cca928d 103static unsigned long linelen(const char *buffer, unsigned long size)
c1bb9350
LT
104{
105 unsigned long len = 0;
106 while (size--) {
107 len++;
108 if (*buffer++ == '\n')
109 break;
110 }
111 return len;
112}
113
a4acb0eb
LT
114static int is_dev_null(const char *str)
115{
116 return !memcmp("/dev/null", str, 9) && isspace(str[9]);
117}
118
381ca9a3
LT
119#define TERM_SPACE 1
120#define TERM_TAB 2
9a4a100e
LT
121
122static int name_terminate(const char *name, int namelen, int c, int terminate)
123{
124 if (c == ' ' && !(terminate & TERM_SPACE))
125 return 0;
126 if (c == '\t' && !(terminate & TERM_TAB))
127 return 0;
128
9a4a100e
LT
129 return 1;
130}
131
132static char * find_name(const char *line, char *def, int p_value, int terminate)
c1bb9350 133{
a4acb0eb
LT
134 int len;
135 const char *start = line;
136 char *name;
137
c1bb9350 138 for (;;) {
a4acb0eb 139 char c = *line;
9a4a100e
LT
140
141 if (isspace(c)) {
142 if (c == '\n')
143 break;
144 if (name_terminate(start, line-start, c, terminate))
145 break;
146 }
a4acb0eb
LT
147 line++;
148 if (c == '/' && !--p_value)
149 start = line;
150 }
151 if (!start)
152 return def;
153 len = line - start;
154 if (!len)
155 return def;
156
157 /*
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~").
162 */
163 if (def) {
164 int deflen = strlen(def);
165 if (deflen < len && !strncmp(start, def, deflen))
166 return def;
c1bb9350 167 }
a4acb0eb
LT
168
169 name = xmalloc(len + 1);
170 memcpy(name, start, len);
171 name[len] = 0;
172 free(def);
173 return name;
174}
175
176/*
177 * Get the name etc info from the --/+++ lines of a traditional patch header
178 *
179 * NOTE! This hardcodes "-p1" behaviour in filename detection.
9a4a100e
LT
180 *
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.
a4acb0eb 184 */
19c58fb8 185static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
a4acb0eb
LT
186{
187 int p_value = 1;
188 char *name;
189
190 first += 4; // skip "--- "
191 second += 4; // skip "+++ "
192 if (is_dev_null(first)) {
19c58fb8
LT
193 patch->is_new = 1;
194 patch->is_delete = 0;
5041aa70 195 name = find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB);
19c58fb8 196 patch->new_name = name;
a4acb0eb 197 } else if (is_dev_null(second)) {
19c58fb8
LT
198 patch->is_new = 0;
199 patch->is_delete = 1;
381ca9a3 200 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
19c58fb8 201 patch->old_name = name;
a4acb0eb 202 } else {
381ca9a3
LT
203 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
204 name = find_name(second, name, p_value, TERM_SPACE | TERM_TAB);
19c58fb8 205 patch->old_name = patch->new_name = name;
a4acb0eb
LT
206 }
207 if (!name)
208 die("unable to find filename in patch at line %d", linenr);
a4acb0eb
LT
209}
210
19c58fb8 211static int gitdiff_hdrend(const char *line, struct patch *patch)
a4acb0eb
LT
212{
213 return -1;
214}
215
1e3f6b6e
LT
216/*
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.
220 *
221 * As a result, gitdiff_{old|new}name() will check
222 * their names against any previous information, just
223 * to make sure..
224 */
225static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
226{
227 int len;
228 const char *name;
229
230 if (!orig_name && !isnull)
231 return find_name(line, NULL, 1, 0);
232
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);
240 }
241
242 if (*name == '/')
243 goto absolute_path;
244
245 for (;;) {
246 char c = *line++;
247 if (c == '\n')
248 break;
249 if (c != '/')
250 continue;
251absolute_path:
252 if (memcmp(line, name, len) || line[len] != '\n')
253 break;
254 return orig_name;
255 }
256 die("git-apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
257 return NULL;
258}
259
19c58fb8 260static int gitdiff_oldname(const char *line, struct patch *patch)
a4acb0eb 261{
19c58fb8 262 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
a4acb0eb
LT
263 return 0;
264}
265
19c58fb8 266static int gitdiff_newname(const char *line, struct patch *patch)
a4acb0eb 267{
19c58fb8 268 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
a4acb0eb
LT
269 return 0;
270}
271
19c58fb8 272static int gitdiff_oldmode(const char *line, struct patch *patch)
a4acb0eb 273{
19c58fb8 274 patch->old_mode = strtoul(line, NULL, 8);
a4acb0eb
LT
275 return 0;
276}
277
19c58fb8 278static int gitdiff_newmode(const char *line, struct patch *patch)
a4acb0eb 279{
19c58fb8 280 patch->new_mode = strtoul(line, NULL, 8);
a4acb0eb
LT
281 return 0;
282}
283
19c58fb8 284static int gitdiff_delete(const char *line, struct patch *patch)
a4acb0eb 285{
19c58fb8 286 patch->is_delete = 1;
5041aa70 287 patch->old_name = patch->def_name;
19c58fb8 288 return gitdiff_oldmode(line, patch);
a4acb0eb
LT
289}
290
19c58fb8 291static int gitdiff_newfile(const char *line, struct patch *patch)
a4acb0eb 292{
19c58fb8 293 patch->is_new = 1;
5041aa70 294 patch->new_name = patch->def_name;
19c58fb8 295 return gitdiff_newmode(line, patch);
a4acb0eb
LT
296}
297
19c58fb8 298static int gitdiff_copysrc(const char *line, struct patch *patch)
a4acb0eb 299{
19c58fb8
LT
300 patch->is_copy = 1;
301 patch->old_name = find_name(line, NULL, 0, 0);
a4acb0eb
LT
302 return 0;
303}
304
19c58fb8 305static int gitdiff_copydst(const char *line, struct patch *patch)
a4acb0eb 306{
19c58fb8
LT
307 patch->is_copy = 1;
308 patch->new_name = find_name(line, NULL, 0, 0);
a4acb0eb
LT
309 return 0;
310}
311
19c58fb8 312static int gitdiff_renamesrc(const char *line, struct patch *patch)
a4acb0eb 313{
19c58fb8
LT
314 patch->is_rename = 1;
315 patch->old_name = find_name(line, NULL, 0, 0);
a4acb0eb
LT
316 return 0;
317}
318
19c58fb8 319static int gitdiff_renamedst(const char *line, struct patch *patch)
a4acb0eb 320{
19c58fb8
LT
321 patch->is_rename = 1;
322 patch->new_name = find_name(line, NULL, 0, 0);
a4acb0eb
LT
323 return 0;
324}
325
19c58fb8 326static int gitdiff_similarity(const char *line, struct patch *patch)
a4acb0eb 327{
96c912a4
JH
328 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
329 patch->score = 0;
a4acb0eb 330 return 0;
c1bb9350
LT
331}
332
70aadac0
JH
333static int gitdiff_dissimilarity(const char *line, struct patch *patch)
334{
96c912a4
JH
335 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
336 patch->score = 0;
70aadac0
JH
337 return 0;
338}
339
2cf67f1e
JH
340static int gitdiff_index(const char *line, struct patch *patch)
341{
342 /* index line is N hexadecimal, "..", N hexadecimal,
343 * and optional space with octal mode.
344 */
345 const char *ptr, *eol;
346 int len;
347
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;
354
355 line = ptr + 2;
356 ptr = strchr(line, ' ');
357 eol = strchr(line, '\n');
358
359 if (!ptr || eol < ptr)
360 ptr = eol;
361 len = ptr - line;
362
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;
370}
371
9a4a100e
LT
372/*
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.
375 */
19c58fb8 376static int gitdiff_unrecognized(const char *line, struct patch *patch)
9a4a100e
LT
377{
378 return -1;
379}
380
5041aa70
LT
381static char *git_header_name(char *line)
382{
383 int len;
384 char *name, *second;
385
386 /*
387 * Find the first '/'
388 */
389 name = line;
390 for (;;) {
391 char c = *name++;
392 if (c == '\n')
393 return NULL;
394 if (c == '/')
395 break;
396 }
397
398 /*
399 * We don't accept absolute paths (/dev/null) as possibly valid
400 */
401 if (name == line+1)
402 return NULL;
403
404 /*
405 * Accept a name only if it shows up twice, exactly the same
406 * form.
407 */
408 for (len = 0 ; ; len++) {
409 char c = name[len];
410
411 switch (c) {
412 default:
413 continue;
414 case '\n':
e70a165d 415 return NULL;
5041aa70
LT
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;
424 }
0e87e048 425 if (second[len] == '\n' && !memcmp(name, second, len)) {
5041aa70
LT
426 char *ret = xmalloc(len + 1);
427 memcpy(ret, name, len);
428 ret[len] = 0;
429 return ret;
430 }
431 }
432 }
433 return NULL;
434}
435
c1bb9350 436/* Verify that we recognize the lines following a git header */
19c58fb8 437static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
c1bb9350 438{
a4acb0eb
LT
439 unsigned long offset;
440
441 /* A git diff has explicit new/delete information, so we don't guess */
19c58fb8
LT
442 patch->is_new = 0;
443 patch->is_delete = 0;
a4acb0eb 444
5041aa70
LT
445 /*
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.
450 */
451 patch->def_name = git_header_name(line + strlen("diff --git "));
452
a4acb0eb
LT
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;
19c58fb8 459 int (*fn)(const char *, struct patch *);
a4acb0eb
LT
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 },
33f4d087
LT
470 { "rename old ", gitdiff_renamesrc },
471 { "rename new ", gitdiff_renamedst },
dc938417
LT
472 { "rename from ", gitdiff_renamesrc },
473 { "rename to ", gitdiff_renamedst },
a4acb0eb 474 { "similarity index ", gitdiff_similarity },
70aadac0 475 { "dissimilarity index ", gitdiff_dissimilarity },
2cf67f1e 476 { "index ", gitdiff_index },
9a4a100e 477 { "", gitdiff_unrecognized },
a4acb0eb
LT
478 };
479 int i;
c1bb9350 480
c1bb9350 481 len = linelen(line, size);
a4acb0eb 482 if (!len || line[len-1] != '\n')
c1bb9350 483 break;
a4acb0eb
LT
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;
19c58fb8 489 if (p->fn(line + oplen, patch) < 0)
a4acb0eb 490 return offset;
9a4a100e 491 break;
a4acb0eb 492 }
c1bb9350
LT
493 }
494
a4acb0eb 495 return offset;
c1bb9350
LT
496}
497
fab2c257 498static int parse_num(const char *line, unsigned long *p)
46979f56
LT
499{
500 char *ptr;
fab2c257
LT
501
502 if (!isdigit(*line))
503 return 0;
504 *p = strtoul(line, &ptr, 10);
505 return ptr - line;
506}
507
508static int parse_range(const char *line, int len, int offset, const char *expect,
509 unsigned long *p1, unsigned long *p2)
510{
46979f56
LT
511 int digits, ex;
512
513 if (offset < 0 || offset >= len)
514 return -1;
515 line += offset;
516 len -= offset;
517
fab2c257
LT
518 digits = parse_num(line, p1);
519 if (!digits)
46979f56 520 return -1;
46979f56
LT
521
522 offset += digits;
523 line += digits;
524 len -= digits;
525
fab2c257
LT
526 *p2 = *p1;
527 if (*line == ',') {
528 digits = parse_num(line+1, p2);
529 if (!digits)
530 return -1;
531
532 offset += digits+1;
533 line += digits+1;
534 len -= digits+1;
535 }
536
46979f56
LT
537 ex = strlen(expect);
538 if (ex > len)
539 return -1;
540 if (memcmp(line, expect, ex))
541 return -1;
542
543 return offset + ex;
544}
545
546/*
547 * Parse a unified diff fragment header of the
548 * form "@@ -a,b +c,d @@"
549 */
19c58fb8 550static int parse_fragment_header(char *line, int len, struct fragment *fragment)
46979f56
LT
551{
552 int offset;
553
554 if (!len || line[len-1] != '\n')
555 return -1;
556
557 /* Figure out the number of lines in a fragment */
fab2c257
LT
558 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
559 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
46979f56
LT
560
561 return offset;
562}
563
19c58fb8 564static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
c1bb9350
LT
565{
566 unsigned long offset, len;
567
19c58fb8
LT
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;
46979f56 572 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
c1bb9350
LT
573 unsigned long nextlen;
574
575 len = linelen(line, size);
576 if (!len)
577 break;
578
579 /* Testing this early allows us to take a few shortcuts.. */
580 if (len < 6)
581 continue;
46979f56
LT
582
583 /*
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.
587 */
588 if (!memcmp("@@ -", line, 4)) {
19c58fb8
LT
589 struct fragment dummy;
590 if (parse_fragment_header(line, len, &dummy) < 0)
46979f56 591 continue;
4ec99bf0 592 error("patch fragment without header at line %d: %.*s", linenr, (int)len-1, line);
46979f56
LT
593 }
594
c1bb9350
LT
595 if (size < len + 6)
596 break;
597
598 /*
599 * Git patch? It might not have a real patch, just a rename
600 * or mode change, so we handle that specially
601 */
602 if (!memcmp("diff --git ", line, 11)) {
19c58fb8 603 int git_hdr_len = parse_git_header(line, len, size, patch);
206de27e 604 if (git_hdr_len <= len)
c1bb9350 605 continue;
b7e8039a
LT
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;
610 }
a4acb0eb 611 *hdrsize = git_hdr_len;
c1bb9350
LT
612 return offset;
613 }
614
615 /** --- followed by +++ ? */
616 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
617 continue;
618
619 /*
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
623 */
624 nextlen = linelen(line + len, size - len);
625 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
626 continue;
627
628 /* Ok, we'll consider it a patch */
19c58fb8 629 parse_traditional_patch(line, line+len, patch);
c1bb9350 630 *hdrsize = len + nextlen;
46979f56 631 linenr += 2;
c1bb9350
LT
632 return offset;
633 }
634 return -1;
635}
636
c1bb9350
LT
637/*
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..
643 */
19c58fb8 644static int parse_fragment(char *line, unsigned long size, struct patch *patch, struct fragment *fragment)
c1bb9350 645{
3f40315a 646 int added, deleted;
c1bb9350 647 int len = linelen(line, size), offset;
30996652 648 unsigned long oldlines, newlines;
c1bb9350 649
19c58fb8 650 offset = parse_fragment_header(line, len, fragment);
c1bb9350
LT
651 if (offset < 0)
652 return -1;
19c58fb8
LT
653 oldlines = fragment->oldlines;
654 newlines = fragment->newlines;
c1bb9350 655
30996652
LT
656 if (patch->is_new < 0) {
657 patch->is_new = !oldlines;
658 if (!oldlines)
659 patch->old_name = NULL;
660 }
661 if (patch->is_delete < 0) {
662 patch->is_delete = !newlines;
663 if (!newlines)
664 patch->new_name = NULL;
665 }
666
667 if (patch->is_new != !oldlines)
668 return error("new file depends on old contents");
af3f929f
LT
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);
673 }
a4acb0eb 674
c1bb9350
LT
675 /* Parse the thing.. */
676 line += len;
677 size -= len;
46979f56 678 linenr++;
3f40315a 679 added = deleted = 0;
46979f56 680 for (offset = len; size > 0; offset += len, size -= len, line += len, linenr++) {
c1bb9350
LT
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 '-':
3f40315a 694 deleted++;
c1bb9350
LT
695 oldlines--;
696 break;
697 case '+':
3f40315a 698 added++;
c1bb9350
LT
699 newlines--;
700 break;
433ef8a2
FK
701
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
56d33b11
JH
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.
708 */
fab2c257 709 case '\\':
433ef8a2 710 if (len < 12 || memcmp(line, "\\ ", 2))
3cca928d 711 return -1;
fab2c257 712 break;
c1bb9350
LT
713 }
714 }
8b64647d
JH
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.
718 */
433ef8a2 719 if (12 < size && !memcmp(line, "\\ ", 2))
8b64647d
JH
720 offset += linelen(line, size);
721
3f40315a
LT
722 patch->lines_added += added;
723 patch->lines_deleted += deleted;
c1bb9350
LT
724 return offset;
725}
726
19c58fb8 727static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
c1bb9350
LT
728{
729 unsigned long offset = 0;
19c58fb8 730 struct fragment **fragp = &patch->fragments;
c1bb9350
LT
731
732 while (size > 4 && !memcmp(line, "@@ -", 4)) {
19c58fb8
LT
733 struct fragment *fragment;
734 int len;
735
736 fragment = xmalloc(sizeof(*fragment));
737 memset(fragment, 0, sizeof(*fragment));
738 len = parse_fragment(line, size, patch, fragment);
c1bb9350 739 if (len <= 0)
46979f56 740 die("corrupt patch at line %d", linenr);
c1bb9350 741
19c58fb8
LT
742 fragment->patch = line;
743 fragment->size = len;
744
745 *fragp = fragment;
746 fragp = &fragment->next;
c1bb9350
LT
747
748 offset += len;
749 line += len;
750 size -= len;
751 }
752 return offset;
753}
754
1fea629f
LT
755static inline int metadata_changes(struct patch *patch)
756{
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);
763}
764
19c58fb8 765static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
c1bb9350
LT
766{
767 int hdrsize, patchsize;
19c58fb8 768 int offset = find_header(buffer, size, &hdrsize, patch);
c1bb9350
LT
769
770 if (offset < 0)
771 return offset;
c1bb9350 772
19c58fb8 773 patchsize = parse_single_patch(buffer + offset + hdrsize, size - offset - hdrsize, patch);
c1bb9350 774
1fea629f
LT
775 if (!patchsize && !metadata_changes(patch))
776 die("patch with only garbage at line %d", linenr);
777
c1bb9350
LT
778 return offset + hdrsize + patchsize;
779}
780
6da4016a
LT
781static const char pluses[] = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
782static const char minuses[]= "----------------------------------------------------------------------";
3f40315a
LT
783
784static void show_stats(struct patch *patch)
785{
62917097 786 const char *prefix = "";
03b4538b 787 char *name = patch->new_name;
95bedc9e 788 int len, max, add, del, total;
3f40315a 789
5041aa70 790 if (!name)
03b4538b 791 name = patch->old_name;
3f40315a
LT
792
793 /*
794 * "scale" the filename
795 */
796 len = strlen(name);
797 max = max_len;
798 if (max > 50)
799 max = 50;
62917097
LT
800 if (len > max) {
801 char *slash;
802 prefix = "...";
803 max -= 3;
3f40315a 804 name += len - max;
62917097
LT
805 slash = strchr(name, '/');
806 if (slash)
807 name = slash;
808 }
3f40315a
LT
809 len = max;
810
811 /*
812 * scale the add/delete
813 */
814 max = max_change;
815 if (max + len > 70)
816 max = 70 - len;
95bedc9e
LT
817
818 add = patch->lines_added;
819 del = patch->lines_deleted;
820 total = add + del;
821
69f956e1
SV
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;
826 }
62917097 827 printf(" %s%-*s |%5d %.*s%.*s\n", prefix,
3f40315a
LT
828 len, name, patch->lines_added + patch->lines_deleted,
829 add, pluses, del, minuses);
830}
831
3cca928d
LT
832static int read_old_data(struct stat *st, const char *path, void *buf, unsigned long size)
833{
834 int fd;
835 unsigned long got;
836
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;
851 }
852 if (!ret)
853 break;
854 got += ret;
855 }
856 close(fd);
857 return got;
858
859 default:
860 return -1;
861 }
862}
863
864static int find_offset(const char *buf, unsigned long size, const char *fragment, unsigned long fragsize, int line)
865{
6e7c92a9
LT
866 int i;
867 unsigned long start, backwards, forwards;
3cca928d
LT
868
869 if (fragsize > size)
870 return -1;
871
872 start = 0;
873 if (line > 1) {
3cca928d 874 unsigned long offset = 0;
6e7c92a9
LT
875 i = line-1;
876 while (offset + fragsize <= size) {
3cca928d
LT
877 if (buf[offset++] == '\n') {
878 start = offset;
6e7c92a9 879 if (!--i)
3cca928d
LT
880 break;
881 }
882 }
883 }
884
885 /* Exact line number? */
886 if (!memcmp(buf + start, fragment, fragsize))
887 return start;
888
6e7c92a9
LT
889 /*
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.
892 */
893 backwards = start;
894 forwards = start;
895 for (i = 0; ; i++) {
896 unsigned long try;
897 int n;
898
899 /* "backward" */
900 if (i & 1) {
901 if (!backwards) {
902 if (forwards + fragsize > size)
903 break;
904 continue;
905 }
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;
914 }
915 try = forwards;
916 }
917
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;
6e7c92a9
LT
925 return try;
926 }
927
3cca928d
LT
928 /*
929 * We should start searching forward and backward.
930 */
931 return -1;
932}
933
6e7c92a9
LT
934struct buffer_desc {
935 char *buffer;
936 unsigned long size;
937 unsigned long alloc;
938};
939
940static int apply_one_fragment(struct buffer_desc *desc, struct fragment *frag)
3cca928d 941{
6e7c92a9 942 char *buf = desc->buffer;
3cca928d
LT
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;
948
949 while (size > 0) {
950 int len = linelen(patch, size);
951 int plen;
952
953 if (!len)
954 break;
955
956 /*
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).
962 */
963 plen = len-1;
8b64647d 964 if (len < size && patch[len] == '\\')
3cca928d
LT
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;
983 }
984 patch += len;
985 size -= len;
986 }
987
6e7c92a9 988 offset = find_offset(buf, desc->size, old, oldsize, frag->newpos);
3cca928d 989 if (offset >= 0) {
6e7c92a9
LT
990 int diff = newsize - oldsize;
991 unsigned long size = desc->size + diff;
992 unsigned long alloc = desc->alloc;
993
994 if (size > alloc) {
995 alloc = size + 8192;
996 desc->alloc = alloc;
997 buf = xrealloc(buf, alloc);
998 desc->buffer = buf;
999 }
1000 desc->size = size;
1001 memmove(buf + offset + newsize, buf + offset + oldsize, size - offset - newsize);
1002 memcpy(buf + offset, new, newsize);
3cca928d
LT
1003 offset = 0;
1004 }
1005
1006 free(old);
1007 free(new);
1008 return offset;
1009}
1010
6e7c92a9 1011static int apply_fragments(struct buffer_desc *desc, struct patch *patch)
3cca928d
LT
1012{
1013 struct fragment *frag = patch->fragments;
1014
1015 while (frag) {
6e7c92a9 1016 if (apply_one_fragment(desc, frag) < 0)
4ec99bf0 1017 return error("patch failed: %s:%ld", patch->old_name, frag->oldpos);
3cca928d
LT
1018 frag = frag->next;
1019 }
30996652 1020 return 0;
3cca928d
LT
1021}
1022
1023static int apply_data(struct patch *patch, struct stat *st)
1024{
6e7c92a9
LT
1025 char *buf;
1026 unsigned long size, alloc;
1027 struct buffer_desc desc;
3cca928d 1028
30996652
LT
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);
1038 }
6e7c92a9
LT
1039
1040 desc.size = size;
1041 desc.alloc = alloc;
1042 desc.buffer = buf;
1043 if (apply_fragments(&desc, patch) < 0)
3cca928d 1044 return -1;
6e7c92a9
LT
1045 patch->result = desc.buffer;
1046 patch->resultsize = desc.size;
5aa7d94c
LT
1047
1048 if (patch->is_delete && patch->resultsize)
1049 return error("removal patch leaves file contents");
1050
3cca928d
LT
1051 return 0;
1052}
1053
a577284a 1054static int check_patch(struct patch *patch)
fab2c257 1055{
a577284a 1056 struct stat st;
fab2c257
LT
1057 const char *old_name = patch->old_name;
1058 const char *new_name = patch->new_name;
1059
1060 if (old_name) {
a577284a 1061 int changed;
56d33b11 1062 int stat_ret = lstat(old_name, &st);
a577284a 1063
3cca928d
LT
1064 if (check_index) {
1065 int pos = cache_name_pos(old_name, strlen(old_name));
1066 if (pos < 0)
56d33b11
JH
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;
1085 }
1086
3cca928d
LT
1087 changed = ce_match_stat(active_cache[pos], &st);
1088 if (changed)
56d33b11
JH
1089 return error("%s: does not match index",
1090 old_name);
3cca928d 1091 }
56d33b11
JH
1092 else if (stat_ret < 0)
1093 return error("%s: %s", old_name, strerror(errno));
1094
3cca928d
LT
1095 if (patch->is_new < 0)
1096 patch->is_new = 0;
de4971b5 1097 st.st_mode = ntohl(create_ce_mode(st.st_mode));
a577284a
LT
1098 if (!patch->old_mode)
1099 patch->old_mode = st.st_mode;
3cca928d
LT
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);
fab2c257 1105 }
a577284a 1106
fab2c257 1107 if (new_name && (patch->is_new | patch->is_rename | patch->is_copy)) {
3cca928d 1108 if (check_index && cache_name_pos(new_name, strlen(new_name)) >= 0)
a577284a
LT
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));
35cc4bcd
JS
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;
1119 }
fab2c257 1120 }
3cca928d
LT
1121
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);
1130 }
1131
1132 if (apply_data(patch, &st) < 0)
1133 return error("%s: patch does not apply", old_name);
a577284a 1134 return 0;
fab2c257
LT
1135}
1136
a577284a 1137static int check_patch_list(struct patch *patch)
19c58fb8 1138{
a577284a
LT
1139 int error = 0;
1140
1141 for (;patch ; patch = patch->next)
1142 error |= check_patch(patch);
1143 return error;
1144}
1145
1146static void show_file(int c, unsigned int mode, const char *name)
1147{
1148 printf("%c %o %s\n", c, mode, name);
1149}
3f40315a 1150
a577284a
LT
1151static void show_file_list(struct patch *patch)
1152{
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;
1158 }
1159 if (patch->is_copy || patch->is_new) {
1160 show_file('+', patch->new_mode, patch->new_name);
1161 continue;
1162 }
1163 if (patch->is_delete) {
1164 show_file('-', patch->old_mode, patch->old_name);
1165 continue;
1166 }
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;
19c58fb8 1170 }
a577284a
LT
1171 printf("M %o %s\n", patch->old_mode, patch->old_name);
1172 }
1173}
fab2c257 1174
2cf67f1e
JH
1175static inline int is_null_sha1(const unsigned char *sha1)
1176{
1177 return !memcmp(sha1, null_sha1, 20);
1178}
1179
1180static void show_index_list(struct patch *list)
1181{
1182 struct patch *patch;
1183
1184 /* Once we start supporting the reverse patch, it may be
1185 * worth showing the new sha1 prefix, but until then...
1186 */
1187 for (patch = list; patch; patch = patch->next) {
1188 const unsigned char *sha1_ptr;
1189 unsigned char sha1[20];
1190 const char *name;
1191
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);
1202 }
1203}
1204
a577284a
LT
1205static void stat_patch_list(struct patch *patch)
1206{
1207 int files, adds, dels;
1208
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);
1214 }
1215
1216 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
3f40315a
LT
1217}
1218
96c912a4
JH
1219static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
1220{
1221 if (mode)
1222 printf(" %s mode %06o %s\n", newdelete, mode, name);
1223 else
1224 printf(" %s %s\n", newdelete, name);
1225}
1226
1227static void show_mode_change(struct patch *p, int show_name)
1228{
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);
1236 }
1237}
1238
1239static void show_rename_copy(struct patch *p)
1240{
1241 const char *renamecopy = p->is_rename ? "rename" : "copy";
1242 const char *old, *new;
1243
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;
1258 }
1259 /* p->old_name thru old is the common prefix, and old and new
1260 * through the end of names are renames
1261 */
1262 if (old != p->old_name)
1263 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
e30e814d 1264 (int)(old - p->old_name), p->old_name,
96c912a4
JH
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);
1270}
1271
1272static void summary_patch_list(struct patch *patch)
1273{
1274 struct patch *p;
1275
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);
1289 }
1290 else
1291 show_mode_change(p, 1);
1292 }
1293 }
1294 }
1295}
1296
3f40315a
LT
1297static void patch_stats(struct patch *patch)
1298{
1299 int lines = patch->lines_added + patch->lines_deleted;
1300
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;
1307 }
1308 if (patch->new_name) {
1309 int len = strlen(patch->new_name);
1310 if (len > max_len)
1311 max_len = len;
1312 }
19c58fb8
LT
1313}
1314
5aa7d94c
LT
1315static void remove_file(struct patch *patch)
1316{
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);
1320 }
1321 unlink(patch->old_name);
1322}
1323
1324static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
1325{
1326 struct stat st;
1327 struct cache_entry *ce;
1328 int namelen = strlen(path);
1329 unsigned ce_size = cache_entry_size(namelen);
1330
1331 if (!write_index)
1332 return;
1333
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);
1346}
1347
5c8af185
LT
1348static void create_subdirectories(const char *path)
1349{
1350 int len = strlen(path);
1351 char *buf = xmalloc(len + 1);
1352 const char *slash = path;
1353
1354 while ((slash = strchr(slash+1, '/')) != NULL) {
1355 len = slash - path;
1356 memcpy(buf, path, len);
1357 buf[len] = 0;
f312de01 1358 if (mkdir(buf, 0777) < 0) {
5c8af185
LT
1359 if (errno != EEXIST)
1360 break;
1361 }
1362 }
1363 free(buf);
1364}
1365
1b668341
LT
1366static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
1367{
1368 int fd;
1369
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));
1381 }
1382 if (!written)
1383 die("out of space writing file %s", path);
1384 buf += written;
1385 size -= written;
1386 }
1387 if (close(fd) < 0)
1388 die("closing file %s: %s", path, strerror(errno));
1389 return 0;
1390}
1391
5c8af185
LT
1392/*
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.
1396 */
1b668341 1397static void create_one_file(const char *path, unsigned mode, const char *buf, unsigned long size)
5c8af185 1398{
1b668341
LT
1399 if (!try_create_file(path, mode, buf, size))
1400 return;
5c8af185 1401
1b668341 1402 if (errno == ENOENT) {
5c8af185 1403 create_subdirectories(path);
1b668341
LT
1404 if (!try_create_file(path, mode, buf, size))
1405 return;
5c8af185 1406 }
5c8af185 1407
1b668341
LT
1408 if (errno == EEXIST) {
1409 unsigned int nr = getpid();
5c8af185 1410
1b668341
LT
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;
1419 }
1420 if (errno != EEXIST)
1421 break;
1422 }
5c8af185 1423 }
1b668341 1424 die("unable to write file %s mode %o", path, mode);
5c8af185
LT
1425}
1426
5aa7d94c
LT
1427static void create_file(struct patch *patch)
1428{
1429 const char *path = patch->new_name;
1430 unsigned mode = patch->new_mode;
1431 unsigned long size = patch->resultsize;
1432 char *buf = patch->result;
1433
1434 if (!mode)
1435 mode = S_IFREG | 0644;
1b668341
LT
1436 create_one_file(path, mode, buf, size);
1437 add_index_file(path, mode, buf, size);
5aa7d94c
LT
1438}
1439
1440static void write_out_one_result(struct patch *patch)
1441{
1442 if (patch->is_delete > 0) {
1443 remove_file(patch);
1444 return;
1445 }
1446 if (patch->is_new > 0 || patch->is_copy) {
1447 create_file(patch);
1448 return;
1449 }
1450 /*
1451 * Rename or modification boils down to the same
1452 * thing: remove the old, write the new
1453 */
1454 remove_file(patch);
1455 create_file(patch);
1456}
1457
d854f783 1458static void write_out_results(struct patch *list, int skipped_patch)
5aa7d94c 1459{
d854f783 1460 if (!list && !skipped_patch)
f7b79707
LT
1461 die("No changes");
1462
5aa7d94c
LT
1463 while (list) {
1464 write_out_one_result(list);
1465 list = list->next;
1466 }
1467}
1468
1469static struct cache_file cache_file;
1470
d854f783
JH
1471static struct excludes {
1472 struct excludes *next;
1473 const char *path;
1474} *excludes;
1475
1476static int use_patch(struct patch *p)
1477{
c7c81b3a 1478 const char *pathname = p->new_name ? p->new_name : p->old_name;
d854f783
JH
1479 struct excludes *x = excludes;
1480 while (x) {
1481 if (fnmatch(x->path, pathname, 0) == 0)
1482 return 0;
1483 x = x->next;
1484 }
1485 return 1;
1486}
1487
c1bb9350
LT
1488static int apply_patch(int fd)
1489{
5aa7d94c 1490 int newfd;
c1bb9350
LT
1491 unsigned long offset, size;
1492 char *buffer = read_patch_file(fd, &size);
19c58fb8 1493 struct patch *list = NULL, **listp = &list;
d854f783 1494 int skipped_patch = 0;
c1bb9350
LT
1495
1496 if (!buffer)
1497 return -1;
1498 offset = 0;
1499 while (size > 0) {
19c58fb8
LT
1500 struct patch *patch;
1501 int nr;
1502
1503 patch = xmalloc(sizeof(*patch));
1504 memset(patch, 0, sizeof(*patch));
1505 nr = parse_chunk(buffer + offset, size, patch);
c1bb9350
LT
1506 if (nr < 0)
1507 break;
d854f783
JH
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++;
1516 }
c1bb9350
LT
1517 offset += nr;
1518 size -= nr;
1519 }
19c58fb8 1520
5aa7d94c
LT
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");
1528 }
1529
a577284a
LT
1530 if ((check || apply) && check_patch_list(list) < 0)
1531 exit(1);
1532
5aa7d94c 1533 if (apply)
d854f783 1534 write_out_results(list, skipped_patch);
5aa7d94c
LT
1535
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");
1540 }
1541
a577284a
LT
1542 if (show_files)
1543 show_file_list(list);
1544
2cf67f1e
JH
1545 if (show_index_info)
1546 show_index_list(list);
1547
a577284a
LT
1548 if (diffstat)
1549 stat_patch_list(list);
19c58fb8 1550
96c912a4
JH
1551 if (summary)
1552 summary_patch_list(list);
1553
c1bb9350
LT
1554 free(buffer);
1555 return 0;
1556}
1557
1558int main(int argc, char **argv)
1559{
1560 int i;
4dfdbe10 1561 int read_stdin = 1;
c1bb9350 1562
c1bb9350
LT
1563 for (i = 1; i < argc; i++) {
1564 const char *arg = argv[i];
1565 int fd;
1566
1567 if (!strcmp(arg, "-")) {
1568 apply_patch(0);
4dfdbe10 1569 read_stdin = 0;
c1bb9350
LT
1570 continue;
1571 }
d854f783
JH
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;
1578 }
fab2c257 1579 if (!strcmp(arg, "--stat")) {
a577284a 1580 apply = 0;
fab2c257
LT
1581 diffstat = 1;
1582 continue;
1583 }
96c912a4
JH
1584 if (!strcmp(arg, "--summary")) {
1585 apply = 0;
1586 summary = 1;
1587 continue;
1588 }
a577284a
LT
1589 if (!strcmp(arg, "--check")) {
1590 apply = 0;
1591 check = 1;
1592 continue;
1593 }
3cca928d
LT
1594 if (!strcmp(arg, "--index")) {
1595 check_index = 1;
1596 continue;
1597 }
aefa4a5b
LT
1598 if (!strcmp(arg, "--apply")) {
1599 apply = 1;
1600 continue;
1601 }
a577284a
LT
1602 if (!strcmp(arg, "--show-files")) {
1603 show_files = 1;
1604 continue;
1605 }
2cf67f1e
JH
1606 if (!strcmp(arg, "--show-index-info")) {
1607 apply = 0;
1608 show_index_info = 1;
1609 continue;
1610 }
c1bb9350
LT
1611 fd = open(arg, O_RDONLY);
1612 if (fd < 0)
1613 usage(apply_usage);
4dfdbe10 1614 read_stdin = 0;
c1bb9350
LT
1615 apply_patch(fd);
1616 close(fd);
1617 }
4dfdbe10
LT
1618 if (read_stdin)
1619 apply_patch(0);
c1bb9350
LT
1620 return 0;
1621}