Make "git fetch" able to fetch a named tag
[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 *
8 * NOTE! It does all its work in the index file, and only cares about
9 * the files in the working directory if you tell it to "merge" the
10 * patch apply.
11 *
12 * Even when merging it always takes the source from the index, and
13 * uses the working tree as a "branch" for a 3-way merge.
14 */
15#include <ctype.h>
16
17#include "cache.h"
18
19// We default to the merge behaviour, since that's what most people would
a577284a
LT
20// expect.
21//
22// --check turns on checking that the working tree matches the
23// files that are being modified, but doesn't apply the patch
24// --stat does just a diffstat, and doesn't actually apply
25// --show-files shows the directory changes
26//
c1bb9350 27static int merge_patch = 1;
3cca928d 28static int check_index = 0;
5aa7d94c 29static int write_index = 0;
fab2c257 30static int diffstat = 0;
96c912a4 31static int summary = 0;
a577284a
LT
32static int check = 0;
33static int apply = 1;
34static int show_files = 0;
96c912a4 35static const char apply_usage[] = "git-apply [--stat] [--summary] [--check] [--show-files] <patch>";
c1bb9350 36
3f40315a
LT
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 */
42static int max_change, max_len;
43
a4acb0eb
LT
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 */
46979f56 49static int linenr = 1;
19c58fb8
LT
50
51struct fragment {
52 unsigned long oldpos, oldlines;
53 unsigned long newpos, newlines;
54 const char *patch;
55 int size;
56 struct fragment *next;
57};
58
59struct patch {
5041aa70 60 char *new_name, *old_name, *def_name;
19c58fb8
LT
61 unsigned int old_mode, new_mode;
62 int is_rename, is_copy, is_new, is_delete;
3f40315a 63 int lines_added, lines_deleted;
96c912a4 64 int score;
19c58fb8 65 struct fragment *fragments;
5aa7d94c 66 char *result;
3cca928d 67 unsigned long resultsize;
19c58fb8
LT
68 struct patch *next;
69};
46979f56 70
c1bb9350 71#define CHUNKSIZE (8192)
a4acb0eb 72#define SLOP (16)
c1bb9350
LT
73
74static void *read_patch_file(int fd, unsigned long *sizep)
75{
76 unsigned long size = 0, alloc = CHUNKSIZE;
77 void *buffer = xmalloc(alloc);
78
79 for (;;) {
80 int nr = alloc - size;
81 if (nr < 1024) {
82 alloc += CHUNKSIZE;
83 buffer = xrealloc(buffer, alloc);
84 nr = alloc - size;
85 }
86 nr = read(fd, buffer + size, nr);
87 if (!nr)
88 break;
89 if (nr < 0) {
90 if (errno == EAGAIN)
91 continue;
92 die("git-apply: read returned %s", strerror(errno));
93 }
94 size += nr;
95 }
96 *sizep = size;
a4acb0eb
LT
97
98 /*
99 * Make sure that we have some slop in the buffer
100 * so that we can do speculative "memcmp" etc, and
101 * see to it that it is NUL-filled.
102 */
103 if (alloc < size + SLOP)
104 buffer = xrealloc(buffer, size + SLOP);
105 memset(buffer + size, 0, SLOP);
c1bb9350
LT
106 return buffer;
107}
108
3cca928d 109static unsigned long linelen(const char *buffer, unsigned long size)
c1bb9350
LT
110{
111 unsigned long len = 0;
112 while (size--) {
113 len++;
114 if (*buffer++ == '\n')
115 break;
116 }
117 return len;
118}
119
a4acb0eb
LT
120static int is_dev_null(const char *str)
121{
122 return !memcmp("/dev/null", str, 9) && isspace(str[9]);
123}
124
381ca9a3
LT
125#define TERM_SPACE 1
126#define TERM_TAB 2
9a4a100e
LT
127
128static int name_terminate(const char *name, int namelen, int c, int terminate)
129{
130 if (c == ' ' && !(terminate & TERM_SPACE))
131 return 0;
132 if (c == '\t' && !(terminate & TERM_TAB))
133 return 0;
134
9a4a100e
LT
135 return 1;
136}
137
138static char * find_name(const char *line, char *def, int p_value, int terminate)
c1bb9350 139{
a4acb0eb
LT
140 int len;
141 const char *start = line;
142 char *name;
143
c1bb9350 144 for (;;) {
a4acb0eb 145 char c = *line;
9a4a100e
LT
146
147 if (isspace(c)) {
148 if (c == '\n')
149 break;
150 if (name_terminate(start, line-start, c, terminate))
151 break;
152 }
a4acb0eb
LT
153 line++;
154 if (c == '/' && !--p_value)
155 start = line;
156 }
157 if (!start)
158 return def;
159 len = line - start;
160 if (!len)
161 return def;
162
163 /*
164 * Generally we prefer the shorter name, especially
165 * if the other one is just a variation of that with
166 * something else tacked on to the end (ie "file.orig"
167 * or "file~").
168 */
169 if (def) {
170 int deflen = strlen(def);
171 if (deflen < len && !strncmp(start, def, deflen))
172 return def;
c1bb9350 173 }
a4acb0eb
LT
174
175 name = xmalloc(len + 1);
176 memcpy(name, start, len);
177 name[len] = 0;
178 free(def);
179 return name;
180}
181
182/*
183 * Get the name etc info from the --/+++ lines of a traditional patch header
184 *
185 * NOTE! This hardcodes "-p1" behaviour in filename detection.
9a4a100e
LT
186 *
187 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
188 * files, we can happily check the index for a match, but for creating a
189 * new file we should try to match whatever "patch" does. I have no idea.
a4acb0eb 190 */
19c58fb8 191static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
a4acb0eb
LT
192{
193 int p_value = 1;
194 char *name;
195
196 first += 4; // skip "--- "
197 second += 4; // skip "+++ "
198 if (is_dev_null(first)) {
19c58fb8
LT
199 patch->is_new = 1;
200 patch->is_delete = 0;
5041aa70 201 name = find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB);
19c58fb8 202 patch->new_name = name;
a4acb0eb 203 } else if (is_dev_null(second)) {
19c58fb8
LT
204 patch->is_new = 0;
205 patch->is_delete = 1;
381ca9a3 206 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
19c58fb8 207 patch->old_name = name;
a4acb0eb 208 } else {
381ca9a3
LT
209 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
210 name = find_name(second, name, p_value, TERM_SPACE | TERM_TAB);
19c58fb8 211 patch->old_name = patch->new_name = name;
a4acb0eb
LT
212 }
213 if (!name)
214 die("unable to find filename in patch at line %d", linenr);
a4acb0eb
LT
215}
216
19c58fb8 217static int gitdiff_hdrend(const char *line, struct patch *patch)
a4acb0eb
LT
218{
219 return -1;
220}
221
1e3f6b6e
LT
222/*
223 * We're anal about diff header consistency, to make
224 * sure that we don't end up having strange ambiguous
225 * patches floating around.
226 *
227 * As a result, gitdiff_{old|new}name() will check
228 * their names against any previous information, just
229 * to make sure..
230 */
231static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
232{
233 int len;
234 const char *name;
235
236 if (!orig_name && !isnull)
237 return find_name(line, NULL, 1, 0);
238
239 name = "/dev/null";
240 len = 9;
241 if (orig_name) {
242 name = orig_name;
243 len = strlen(name);
244 if (isnull)
245 die("git-apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
246 }
247
248 if (*name == '/')
249 goto absolute_path;
250
251 for (;;) {
252 char c = *line++;
253 if (c == '\n')
254 break;
255 if (c != '/')
256 continue;
257absolute_path:
258 if (memcmp(line, name, len) || line[len] != '\n')
259 break;
260 return orig_name;
261 }
262 die("git-apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
263 return NULL;
264}
265
19c58fb8 266static int gitdiff_oldname(const char *line, struct patch *patch)
a4acb0eb 267{
19c58fb8 268 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
a4acb0eb
LT
269 return 0;
270}
271
19c58fb8 272static int gitdiff_newname(const char *line, struct patch *patch)
a4acb0eb 273{
19c58fb8 274 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
a4acb0eb
LT
275 return 0;
276}
277
19c58fb8 278static int gitdiff_oldmode(const char *line, struct patch *patch)
a4acb0eb 279{
19c58fb8 280 patch->old_mode = strtoul(line, NULL, 8);
a4acb0eb
LT
281 return 0;
282}
283
19c58fb8 284static int gitdiff_newmode(const char *line, struct patch *patch)
a4acb0eb 285{
19c58fb8 286 patch->new_mode = strtoul(line, NULL, 8);
a4acb0eb
LT
287 return 0;
288}
289
19c58fb8 290static int gitdiff_delete(const char *line, struct patch *patch)
a4acb0eb 291{
19c58fb8 292 patch->is_delete = 1;
5041aa70 293 patch->old_name = patch->def_name;
19c58fb8 294 return gitdiff_oldmode(line, patch);
a4acb0eb
LT
295}
296
19c58fb8 297static int gitdiff_newfile(const char *line, struct patch *patch)
a4acb0eb 298{
19c58fb8 299 patch->is_new = 1;
5041aa70 300 patch->new_name = patch->def_name;
19c58fb8 301 return gitdiff_newmode(line, patch);
a4acb0eb
LT
302}
303
19c58fb8 304static int gitdiff_copysrc(const char *line, struct patch *patch)
a4acb0eb 305{
19c58fb8
LT
306 patch->is_copy = 1;
307 patch->old_name = find_name(line, NULL, 0, 0);
a4acb0eb
LT
308 return 0;
309}
310
19c58fb8 311static int gitdiff_copydst(const char *line, struct patch *patch)
a4acb0eb 312{
19c58fb8
LT
313 patch->is_copy = 1;
314 patch->new_name = find_name(line, NULL, 0, 0);
a4acb0eb
LT
315 return 0;
316}
317
19c58fb8 318static int gitdiff_renamesrc(const char *line, struct patch *patch)
a4acb0eb 319{
19c58fb8
LT
320 patch->is_rename = 1;
321 patch->old_name = find_name(line, NULL, 0, 0);
a4acb0eb
LT
322 return 0;
323}
324
19c58fb8 325static int gitdiff_renamedst(const char *line, struct patch *patch)
a4acb0eb 326{
19c58fb8
LT
327 patch->is_rename = 1;
328 patch->new_name = find_name(line, NULL, 0, 0);
a4acb0eb
LT
329 return 0;
330}
331
19c58fb8 332static int gitdiff_similarity(const char *line, struct patch *patch)
a4acb0eb 333{
96c912a4
JH
334 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
335 patch->score = 0;
a4acb0eb 336 return 0;
c1bb9350
LT
337}
338
70aadac0
JH
339static int gitdiff_dissimilarity(const char *line, struct patch *patch)
340{
96c912a4
JH
341 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
342 patch->score = 0;
70aadac0
JH
343 return 0;
344}
345
9a4a100e
LT
346/*
347 * This is normal for a diff that doesn't change anything: we'll fall through
348 * into the next diff. Tell the parser to break out.
349 */
19c58fb8 350static int gitdiff_unrecognized(const char *line, struct patch *patch)
9a4a100e
LT
351{
352 return -1;
353}
354
5041aa70
LT
355static char *git_header_name(char *line)
356{
357 int len;
358 char *name, *second;
359
360 /*
361 * Find the first '/'
362 */
363 name = line;
364 for (;;) {
365 char c = *name++;
366 if (c == '\n')
367 return NULL;
368 if (c == '/')
369 break;
370 }
371
372 /*
373 * We don't accept absolute paths (/dev/null) as possibly valid
374 */
375 if (name == line+1)
376 return NULL;
377
378 /*
379 * Accept a name only if it shows up twice, exactly the same
380 * form.
381 */
382 for (len = 0 ; ; len++) {
383 char c = name[len];
384
385 switch (c) {
386 default:
387 continue;
388 case '\n':
389 break;
390 case '\t': case ' ':
391 second = name+len;
392 for (;;) {
393 char c = *second++;
394 if (c == '\n')
395 return NULL;
396 if (c == '/')
397 break;
398 }
0e87e048 399 if (second[len] == '\n' && !memcmp(name, second, len)) {
5041aa70
LT
400 char *ret = xmalloc(len + 1);
401 memcpy(ret, name, len);
402 ret[len] = 0;
403 return ret;
404 }
405 }
406 }
407 return NULL;
408}
409
c1bb9350 410/* Verify that we recognize the lines following a git header */
19c58fb8 411static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
c1bb9350 412{
a4acb0eb
LT
413 unsigned long offset;
414
415 /* A git diff has explicit new/delete information, so we don't guess */
19c58fb8
LT
416 patch->is_new = 0;
417 patch->is_delete = 0;
a4acb0eb 418
5041aa70
LT
419 /*
420 * Some things may not have the old name in the
421 * rest of the headers anywhere (pure mode changes,
422 * or removing or adding empty files), so we get
423 * the default name from the header.
424 */
425 patch->def_name = git_header_name(line + strlen("diff --git "));
426
a4acb0eb
LT
427 line += len;
428 size -= len;
429 linenr++;
430 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
431 static const struct opentry {
432 const char *str;
19c58fb8 433 int (*fn)(const char *, struct patch *);
a4acb0eb
LT
434 } optable[] = {
435 { "@@ -", gitdiff_hdrend },
436 { "--- ", gitdiff_oldname },
437 { "+++ ", gitdiff_newname },
438 { "old mode ", gitdiff_oldmode },
439 { "new mode ", gitdiff_newmode },
440 { "deleted file mode ", gitdiff_delete },
441 { "new file mode ", gitdiff_newfile },
442 { "copy from ", gitdiff_copysrc },
443 { "copy to ", gitdiff_copydst },
33f4d087
LT
444 { "rename old ", gitdiff_renamesrc },
445 { "rename new ", gitdiff_renamedst },
dc938417
LT
446 { "rename from ", gitdiff_renamesrc },
447 { "rename to ", gitdiff_renamedst },
a4acb0eb 448 { "similarity index ", gitdiff_similarity },
70aadac0 449 { "dissimilarity index ", gitdiff_dissimilarity },
9a4a100e 450 { "", gitdiff_unrecognized },
a4acb0eb
LT
451 };
452 int i;
c1bb9350 453
c1bb9350 454 len = linelen(line, size);
a4acb0eb 455 if (!len || line[len-1] != '\n')
c1bb9350 456 break;
a4acb0eb
LT
457 for (i = 0; i < sizeof(optable) / sizeof(optable[0]); i++) {
458 const struct opentry *p = optable + i;
459 int oplen = strlen(p->str);
460 if (len < oplen || memcmp(p->str, line, oplen))
461 continue;
19c58fb8 462 if (p->fn(line + oplen, patch) < 0)
a4acb0eb 463 return offset;
9a4a100e 464 break;
a4acb0eb 465 }
c1bb9350
LT
466 }
467
a4acb0eb 468 return offset;
c1bb9350
LT
469}
470
fab2c257 471static int parse_num(const char *line, unsigned long *p)
46979f56
LT
472{
473 char *ptr;
fab2c257
LT
474
475 if (!isdigit(*line))
476 return 0;
477 *p = strtoul(line, &ptr, 10);
478 return ptr - line;
479}
480
481static int parse_range(const char *line, int len, int offset, const char *expect,
482 unsigned long *p1, unsigned long *p2)
483{
46979f56
LT
484 int digits, ex;
485
486 if (offset < 0 || offset >= len)
487 return -1;
488 line += offset;
489 len -= offset;
490
fab2c257
LT
491 digits = parse_num(line, p1);
492 if (!digits)
46979f56 493 return -1;
46979f56
LT
494
495 offset += digits;
496 line += digits;
497 len -= digits;
498
fab2c257
LT
499 *p2 = *p1;
500 if (*line == ',') {
501 digits = parse_num(line+1, p2);
502 if (!digits)
503 return -1;
504
505 offset += digits+1;
506 line += digits+1;
507 len -= digits+1;
508 }
509
46979f56
LT
510 ex = strlen(expect);
511 if (ex > len)
512 return -1;
513 if (memcmp(line, expect, ex))
514 return -1;
515
516 return offset + ex;
517}
518
519/*
520 * Parse a unified diff fragment header of the
521 * form "@@ -a,b +c,d @@"
522 */
19c58fb8 523static int parse_fragment_header(char *line, int len, struct fragment *fragment)
46979f56
LT
524{
525 int offset;
526
527 if (!len || line[len-1] != '\n')
528 return -1;
529
530 /* Figure out the number of lines in a fragment */
fab2c257
LT
531 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
532 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
46979f56
LT
533
534 return offset;
535}
536
19c58fb8 537static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
c1bb9350
LT
538{
539 unsigned long offset, len;
540
19c58fb8
LT
541 patch->is_rename = patch->is_copy = 0;
542 patch->is_new = patch->is_delete = -1;
543 patch->old_mode = patch->new_mode = 0;
544 patch->old_name = patch->new_name = NULL;
46979f56 545 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
c1bb9350
LT
546 unsigned long nextlen;
547
548 len = linelen(line, size);
549 if (!len)
550 break;
551
552 /* Testing this early allows us to take a few shortcuts.. */
553 if (len < 6)
554 continue;
46979f56
LT
555
556 /*
557 * Make sure we don't find any unconnected patch fragmants.
558 * That's a sign that we didn't find a header, and that a
559 * patch has become corrupted/broken up.
560 */
561 if (!memcmp("@@ -", line, 4)) {
19c58fb8
LT
562 struct fragment dummy;
563 if (parse_fragment_header(line, len, &dummy) < 0)
46979f56
LT
564 continue;
565 error("patch fragment without header at line %d: %.*s", linenr, len-1, line);
566 }
567
c1bb9350
LT
568 if (size < len + 6)
569 break;
570
571 /*
572 * Git patch? It might not have a real patch, just a rename
573 * or mode change, so we handle that specially
574 */
575 if (!memcmp("diff --git ", line, 11)) {
19c58fb8 576 int git_hdr_len = parse_git_header(line, len, size, patch);
206de27e 577 if (git_hdr_len <= len)
c1bb9350 578 continue;
b7e8039a
LT
579 if (!patch->old_name && !patch->new_name) {
580 if (!patch->def_name)
581 die("git diff header lacks filename information (line %d)", linenr);
582 patch->old_name = patch->new_name = patch->def_name;
583 }
a4acb0eb 584 *hdrsize = git_hdr_len;
c1bb9350
LT
585 return offset;
586 }
587
588 /** --- followed by +++ ? */
589 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
590 continue;
591
592 /*
593 * We only accept unified patches, so we want it to
594 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
595 * minimum
596 */
597 nextlen = linelen(line + len, size - len);
598 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
599 continue;
600
601 /* Ok, we'll consider it a patch */
19c58fb8 602 parse_traditional_patch(line, line+len, patch);
c1bb9350 603 *hdrsize = len + nextlen;
46979f56 604 linenr += 2;
c1bb9350
LT
605 return offset;
606 }
607 return -1;
608}
609
c1bb9350
LT
610/*
611 * Parse a unified diff. Note that this really needs
612 * to parse each fragment separately, since the only
613 * way to know the difference between a "---" that is
614 * part of a patch, and a "---" that starts the next
615 * patch is to look at the line counts..
616 */
19c58fb8 617static int parse_fragment(char *line, unsigned long size, struct patch *patch, struct fragment *fragment)
c1bb9350 618{
3f40315a 619 int added, deleted;
c1bb9350 620 int len = linelen(line, size), offset;
30996652 621 unsigned long oldlines, newlines;
c1bb9350 622
19c58fb8 623 offset = parse_fragment_header(line, len, fragment);
c1bb9350
LT
624 if (offset < 0)
625 return -1;
19c58fb8
LT
626 oldlines = fragment->oldlines;
627 newlines = fragment->newlines;
c1bb9350 628
30996652
LT
629 if (patch->is_new < 0) {
630 patch->is_new = !oldlines;
631 if (!oldlines)
632 patch->old_name = NULL;
633 }
634 if (patch->is_delete < 0) {
635 patch->is_delete = !newlines;
636 if (!newlines)
637 patch->new_name = NULL;
638 }
639
640 if (patch->is_new != !oldlines)
641 return error("new file depends on old contents");
af3f929f
LT
642 if (patch->is_delete != !newlines) {
643 if (newlines)
644 return error("deleted file still has contents");
645 fprintf(stderr, "** warning: file %s becomes empty but is not deleted\n", patch->new_name);
646 }
a4acb0eb 647
c1bb9350
LT
648 /* Parse the thing.. */
649 line += len;
650 size -= len;
46979f56 651 linenr++;
3f40315a 652 added = deleted = 0;
46979f56 653 for (offset = len; size > 0; offset += len, size -= len, line += len, linenr++) {
c1bb9350
LT
654 if (!oldlines && !newlines)
655 break;
656 len = linelen(line, size);
657 if (!len || line[len-1] != '\n')
658 return -1;
659 switch (*line) {
660 default:
661 return -1;
662 case ' ':
663 oldlines--;
664 newlines--;
665 break;
666 case '-':
3f40315a 667 deleted++;
c1bb9350
LT
668 oldlines--;
669 break;
670 case '+':
3f40315a 671 added++;
c1bb9350
LT
672 newlines--;
673 break;
fab2c257
LT
674 /* We allow "\ No newline at end of file" */
675 case '\\':
3cca928d
LT
676 if (len < 12 || memcmp(line, "\\ No newline", 12))
677 return -1;
fab2c257 678 break;
c1bb9350
LT
679 }
680 }
3f40315a
LT
681 patch->lines_added += added;
682 patch->lines_deleted += deleted;
c1bb9350
LT
683 return offset;
684}
685
19c58fb8 686static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
c1bb9350
LT
687{
688 unsigned long offset = 0;
19c58fb8 689 struct fragment **fragp = &patch->fragments;
c1bb9350
LT
690
691 while (size > 4 && !memcmp(line, "@@ -", 4)) {
19c58fb8
LT
692 struct fragment *fragment;
693 int len;
694
695 fragment = xmalloc(sizeof(*fragment));
696 memset(fragment, 0, sizeof(*fragment));
697 len = parse_fragment(line, size, patch, fragment);
c1bb9350 698 if (len <= 0)
46979f56 699 die("corrupt patch at line %d", linenr);
c1bb9350 700
19c58fb8
LT
701 fragment->patch = line;
702 fragment->size = len;
703
704 *fragp = fragment;
705 fragp = &fragment->next;
c1bb9350
LT
706
707 offset += len;
708 line += len;
709 size -= len;
710 }
711 return offset;
712}
713
19c58fb8 714static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
c1bb9350
LT
715{
716 int hdrsize, patchsize;
19c58fb8 717 int offset = find_header(buffer, size, &hdrsize, patch);
c1bb9350
LT
718
719 if (offset < 0)
720 return offset;
c1bb9350 721
19c58fb8 722 patchsize = parse_single_patch(buffer + offset + hdrsize, size - offset - hdrsize, patch);
c1bb9350
LT
723
724 return offset + hdrsize + patchsize;
725}
726
3f40315a
LT
727const char pluses[] = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
728const char minuses[]= "----------------------------------------------------------------------";
729
730static void show_stats(struct patch *patch)
731{
03b4538b 732 char *name = patch->new_name;
95bedc9e 733 int len, max, add, del, total;
3f40315a 734
5041aa70 735 if (!name)
03b4538b 736 name = patch->old_name;
3f40315a
LT
737
738 /*
739 * "scale" the filename
740 */
741 len = strlen(name);
742 max = max_len;
743 if (max > 50)
744 max = 50;
745 if (len > max)
746 name += len - max;
747 len = max;
748
749 /*
750 * scale the add/delete
751 */
752 max = max_change;
753 if (max + len > 70)
754 max = 70 - len;
95bedc9e
LT
755
756 add = patch->lines_added;
757 del = patch->lines_deleted;
758 total = add + del;
759
69f956e1
SV
760 if (max_change > 0) {
761 total = (total * max + max_change / 2) / max_change;
762 add = (add * max + max_change / 2) / max_change;
763 del = total - add;
764 }
3f40315a
LT
765 printf(" %-*s |%5d %.*s%.*s\n",
766 len, name, patch->lines_added + patch->lines_deleted,
767 add, pluses, del, minuses);
768}
769
3cca928d
LT
770static int read_old_data(struct stat *st, const char *path, void *buf, unsigned long size)
771{
772 int fd;
773 unsigned long got;
774
775 switch (st->st_mode & S_IFMT) {
776 case S_IFLNK:
777 return readlink(path, buf, size);
778 case S_IFREG:
779 fd = open(path, O_RDONLY);
780 if (fd < 0)
781 return error("unable to open %s", path);
782 got = 0;
783 for (;;) {
784 int ret = read(fd, buf + got, size - got);
785 if (ret < 0) {
786 if (errno == EAGAIN)
787 continue;
788 break;
789 }
790 if (!ret)
791 break;
792 got += ret;
793 }
794 close(fd);
795 return got;
796
797 default:
798 return -1;
799 }
800}
801
802static int find_offset(const char *buf, unsigned long size, const char *fragment, unsigned long fragsize, int line)
803{
6e7c92a9
LT
804 int i;
805 unsigned long start, backwards, forwards;
3cca928d
LT
806
807 if (fragsize > size)
808 return -1;
809
810 start = 0;
811 if (line > 1) {
3cca928d 812 unsigned long offset = 0;
6e7c92a9
LT
813 i = line-1;
814 while (offset + fragsize <= size) {
3cca928d
LT
815 if (buf[offset++] == '\n') {
816 start = offset;
6e7c92a9 817 if (!--i)
3cca928d
LT
818 break;
819 }
820 }
821 }
822
823 /* Exact line number? */
824 if (!memcmp(buf + start, fragment, fragsize))
825 return start;
826
6e7c92a9
LT
827 /*
828 * There's probably some smart way to do this, but I'll leave
829 * that to the smart and beautiful people. I'm simple and stupid.
830 */
831 backwards = start;
832 forwards = start;
833 for (i = 0; ; i++) {
834 unsigned long try;
835 int n;
836
837 /* "backward" */
838 if (i & 1) {
839 if (!backwards) {
840 if (forwards + fragsize > size)
841 break;
842 continue;
843 }
844 do {
845 --backwards;
846 } while (backwards && buf[backwards-1] != '\n');
847 try = backwards;
848 } else {
849 while (forwards + fragsize <= size) {
850 if (buf[forwards++] == '\n')
851 break;
852 }
853 try = forwards;
854 }
855
856 if (try + fragsize > size)
857 continue;
858 if (memcmp(buf + try, fragment, fragsize))
859 continue;
860 n = (i >> 1)+1;
861 if (i & 1)
862 n = -n;
863 fprintf(stderr, "Fragment applied at offset %d\n", n);
864 return try;
865 }
866
3cca928d
LT
867 /*
868 * We should start searching forward and backward.
869 */
870 return -1;
871}
872
6e7c92a9
LT
873struct buffer_desc {
874 char *buffer;
875 unsigned long size;
876 unsigned long alloc;
877};
878
879static int apply_one_fragment(struct buffer_desc *desc, struct fragment *frag)
3cca928d 880{
6e7c92a9 881 char *buf = desc->buffer;
3cca928d
LT
882 const char *patch = frag->patch;
883 int offset, size = frag->size;
884 char *old = xmalloc(size);
885 char *new = xmalloc(size);
886 int oldsize = 0, newsize = 0;
887
888 while (size > 0) {
889 int len = linelen(patch, size);
890 int plen;
891
892 if (!len)
893 break;
894
895 /*
896 * "plen" is how much of the line we should use for
897 * the actual patch data. Normally we just remove the
898 * first character on the line, but if the line is
899 * followed by "\ No newline", then we also remove the
900 * last one (which is the newline, of course).
901 */
902 plen = len-1;
903 if (len > size && patch[len] == '\\')
904 plen--;
905 switch (*patch) {
906 case ' ':
907 case '-':
908 memcpy(old + oldsize, patch + 1, plen);
909 oldsize += plen;
910 if (*patch == '-')
911 break;
912 /* Fall-through for ' ' */
913 case '+':
914 memcpy(new + newsize, patch + 1, plen);
915 newsize += plen;
916 break;
917 case '@': case '\\':
918 /* Ignore it, we already handled it */
919 break;
920 default:
921 return -1;
922 }
923 patch += len;
924 size -= len;
925 }
926
6e7c92a9 927 offset = find_offset(buf, desc->size, old, oldsize, frag->newpos);
3cca928d 928 if (offset >= 0) {
6e7c92a9
LT
929 int diff = newsize - oldsize;
930 unsigned long size = desc->size + diff;
931 unsigned long alloc = desc->alloc;
932
933 if (size > alloc) {
934 alloc = size + 8192;
935 desc->alloc = alloc;
936 buf = xrealloc(buf, alloc);
937 desc->buffer = buf;
938 }
939 desc->size = size;
940 memmove(buf + offset + newsize, buf + offset + oldsize, size - offset - newsize);
941 memcpy(buf + offset, new, newsize);
3cca928d
LT
942 offset = 0;
943 }
944
945 free(old);
946 free(new);
947 return offset;
948}
949
6e7c92a9 950static int apply_fragments(struct buffer_desc *desc, struct patch *patch)
3cca928d
LT
951{
952 struct fragment *frag = patch->fragments;
953
954 while (frag) {
6e7c92a9 955 if (apply_one_fragment(desc, frag) < 0)
3cca928d
LT
956 return error("patch failed: %s:%d", patch->old_name, frag->oldpos);
957 frag = frag->next;
958 }
30996652 959 return 0;
3cca928d
LT
960}
961
962static int apply_data(struct patch *patch, struct stat *st)
963{
6e7c92a9
LT
964 char *buf;
965 unsigned long size, alloc;
966 struct buffer_desc desc;
3cca928d 967
30996652
LT
968 size = 0;
969 alloc = 0;
970 buf = NULL;
971 if (patch->old_name) {
972 size = st->st_size;
973 alloc = size + 8192;
974 buf = xmalloc(alloc);
975 if (read_old_data(st, patch->old_name, buf, alloc) != size)
976 return error("read of %s failed", patch->old_name);
977 }
6e7c92a9
LT
978
979 desc.size = size;
980 desc.alloc = alloc;
981 desc.buffer = buf;
982 if (apply_fragments(&desc, patch) < 0)
3cca928d 983 return -1;
6e7c92a9
LT
984 patch->result = desc.buffer;
985 patch->resultsize = desc.size;
5aa7d94c
LT
986
987 if (patch->is_delete && patch->resultsize)
988 return error("removal patch leaves file contents");
989
3cca928d
LT
990 return 0;
991}
992
a577284a 993static int check_patch(struct patch *patch)
fab2c257 994{
a577284a 995 struct stat st;
fab2c257
LT
996 const char *old_name = patch->old_name;
997 const char *new_name = patch->new_name;
998
999 if (old_name) {
a577284a
LT
1000 int changed;
1001
a577284a 1002 if (lstat(old_name, &st) < 0)
84fb9a4d 1003 return error("%s: %s", old_name, strerror(errno));
3cca928d
LT
1004 if (check_index) {
1005 int pos = cache_name_pos(old_name, strlen(old_name));
1006 if (pos < 0)
1007 return error("%s: does not exist in index", old_name);
1008 changed = ce_match_stat(active_cache[pos], &st);
1009 if (changed)
1010 return error("%s: does not match index", old_name);
1011 }
1012 if (patch->is_new < 0)
1013 patch->is_new = 0;
de4971b5 1014 st.st_mode = ntohl(create_ce_mode(st.st_mode));
a577284a
LT
1015 if (!patch->old_mode)
1016 patch->old_mode = st.st_mode;
3cca928d
LT
1017 if ((st.st_mode ^ patch->old_mode) & S_IFMT)
1018 return error("%s: wrong type", old_name);
1019 if (st.st_mode != patch->old_mode)
1020 fprintf(stderr, "warning: %s has type %o, expected %o\n",
1021 old_name, st.st_mode, patch->old_mode);
fab2c257 1022 }
a577284a 1023
fab2c257 1024 if (new_name && (patch->is_new | patch->is_rename | patch->is_copy)) {
3cca928d 1025 if (check_index && cache_name_pos(new_name, strlen(new_name)) >= 0)
a577284a
LT
1026 return error("%s: already exists in index", new_name);
1027 if (!lstat(new_name, &st))
1028 return error("%s: already exists in working directory", new_name);
1029 if (errno != ENOENT)
1030 return error("%s: %s", new_name, strerror(errno));
5aa7d94c
LT
1031 if (!patch->new_mode)
1032 patch->new_mode = S_IFREG | 0644;
fab2c257 1033 }
3cca928d
LT
1034
1035 if (new_name && old_name) {
1036 int same = !strcmp(old_name, new_name);
1037 if (!patch->new_mode)
1038 patch->new_mode = patch->old_mode;
1039 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
1040 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
1041 patch->new_mode, new_name, patch->old_mode,
1042 same ? "" : " of ", same ? "" : old_name);
1043 }
1044
1045 if (apply_data(patch, &st) < 0)
1046 return error("%s: patch does not apply", old_name);
a577284a 1047 return 0;
fab2c257
LT
1048}
1049
a577284a 1050static int check_patch_list(struct patch *patch)
19c58fb8 1051{
a577284a
LT
1052 int error = 0;
1053
1054 for (;patch ; patch = patch->next)
1055 error |= check_patch(patch);
1056 return error;
1057}
1058
1059static void show_file(int c, unsigned int mode, const char *name)
1060{
1061 printf("%c %o %s\n", c, mode, name);
1062}
3f40315a 1063
a577284a
LT
1064static void show_file_list(struct patch *patch)
1065{
1066 for (;patch ; patch = patch->next) {
1067 if (patch->is_rename) {
1068 show_file('-', patch->old_mode, patch->old_name);
1069 show_file('+', patch->new_mode, patch->new_name);
1070 continue;
1071 }
1072 if (patch->is_copy || patch->is_new) {
1073 show_file('+', patch->new_mode, patch->new_name);
1074 continue;
1075 }
1076 if (patch->is_delete) {
1077 show_file('-', patch->old_mode, patch->old_name);
1078 continue;
1079 }
1080 if (patch->old_mode && patch->new_mode && patch->old_mode != patch->new_mode) {
1081 printf("M %o:%o %s\n", patch->old_mode, patch->new_mode, patch->old_name);
1082 continue;
19c58fb8 1083 }
a577284a
LT
1084 printf("M %o %s\n", patch->old_mode, patch->old_name);
1085 }
1086}
fab2c257 1087
a577284a
LT
1088static void stat_patch_list(struct patch *patch)
1089{
1090 int files, adds, dels;
1091
1092 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
1093 files++;
1094 adds += patch->lines_added;
1095 dels += patch->lines_deleted;
1096 show_stats(patch);
1097 }
1098
1099 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
3f40315a
LT
1100}
1101
96c912a4
JH
1102static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
1103{
1104 if (mode)
1105 printf(" %s mode %06o %s\n", newdelete, mode, name);
1106 else
1107 printf(" %s %s\n", newdelete, name);
1108}
1109
1110static void show_mode_change(struct patch *p, int show_name)
1111{
1112 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
1113 if (show_name)
1114 printf(" mode change %06o => %06o %s\n",
1115 p->old_mode, p->new_mode, p->new_name);
1116 else
1117 printf(" mode change %06o => %06o\n",
1118 p->old_mode, p->new_mode);
1119 }
1120}
1121
1122static void show_rename_copy(struct patch *p)
1123{
1124 const char *renamecopy = p->is_rename ? "rename" : "copy";
1125 const char *old, *new;
1126
1127 /* Find common prefix */
1128 old = p->old_name;
1129 new = p->new_name;
1130 while (1) {
1131 const char *slash_old, *slash_new;
1132 slash_old = strchr(old, '/');
1133 slash_new = strchr(new, '/');
1134 if (!slash_old ||
1135 !slash_new ||
1136 slash_old - old != slash_new - new ||
1137 memcmp(old, new, slash_new - new))
1138 break;
1139 old = slash_old + 1;
1140 new = slash_new + 1;
1141 }
1142 /* p->old_name thru old is the common prefix, and old and new
1143 * through the end of names are renames
1144 */
1145 if (old != p->old_name)
1146 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
1147 old - p->old_name, p->old_name,
1148 old, new, p->score);
1149 else
1150 printf(" %s %s => %s (%d%%)\n", renamecopy,
1151 p->old_name, p->new_name, p->score);
1152 show_mode_change(p, 0);
1153}
1154
1155static void summary_patch_list(struct patch *patch)
1156{
1157 struct patch *p;
1158
1159 for (p = patch; p; p = p->next) {
1160 if (p->is_new)
1161 show_file_mode_name("create", p->new_mode, p->new_name);
1162 else if (p->is_delete)
1163 show_file_mode_name("delete", p->old_mode, p->old_name);
1164 else {
1165 if (p->is_rename || p->is_copy)
1166 show_rename_copy(p);
1167 else {
1168 if (p->score) {
1169 printf(" rewrite %s (%d%%)\n",
1170 p->new_name, p->score);
1171 show_mode_change(p, 0);
1172 }
1173 else
1174 show_mode_change(p, 1);
1175 }
1176 }
1177 }
1178}
1179
3f40315a
LT
1180static void patch_stats(struct patch *patch)
1181{
1182 int lines = patch->lines_added + patch->lines_deleted;
1183
1184 if (lines > max_change)
1185 max_change = lines;
1186 if (patch->old_name) {
1187 int len = strlen(patch->old_name);
1188 if (len > max_len)
1189 max_len = len;
1190 }
1191 if (patch->new_name) {
1192 int len = strlen(patch->new_name);
1193 if (len > max_len)
1194 max_len = len;
1195 }
19c58fb8
LT
1196}
1197
5aa7d94c
LT
1198static void remove_file(struct patch *patch)
1199{
1200 if (write_index) {
1201 if (remove_file_from_cache(patch->old_name) < 0)
1202 die("unable to remove %s from index", patch->old_name);
1203 }
1204 unlink(patch->old_name);
1205}
1206
1207static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
1208{
1209 struct stat st;
1210 struct cache_entry *ce;
1211 int namelen = strlen(path);
1212 unsigned ce_size = cache_entry_size(namelen);
1213
1214 if (!write_index)
1215 return;
1216
1217 ce = xmalloc(ce_size);
1218 memset(ce, 0, ce_size);
1219 memcpy(ce->name, path, namelen);
1220 ce->ce_mode = create_ce_mode(mode);
1221 ce->ce_flags = htons(namelen);
1222 if (lstat(path, &st) < 0)
1223 die("unable to stat newly created file %s", path);
1224 fill_stat_cache_info(ce, &st);
1225 if (write_sha1_file(buf, size, "blob", ce->sha1) < 0)
1226 die("unable to create backing store for newly created file %s", path);
1227 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
1228 die("unable to add cache entry for %s", path);
1229}
1230
5c8af185
LT
1231static void create_subdirectories(const char *path)
1232{
1233 int len = strlen(path);
1234 char *buf = xmalloc(len + 1);
1235 const char *slash = path;
1236
1237 while ((slash = strchr(slash+1, '/')) != NULL) {
1238 len = slash - path;
1239 memcpy(buf, path, len);
1240 buf[len] = 0;
1241 if (mkdir(buf, 0755) < 0) {
1242 if (errno != EEXIST)
1243 break;
1244 }
1245 }
1246 free(buf);
1247}
1248
1249/*
1250 * We optimistically assume that the directories exist,
1251 * which is true 99% of the time anyway. If they don't,
1252 * we create them and try again.
1253 */
1254static int create_regular_file(const char *path, unsigned int mode)
1255{
1256 int ret = open(path, O_WRONLY | O_CREAT | O_TRUNC, mode);
1257
1258 if (ret < 0 && errno == ENOENT) {
1259 create_subdirectories(path);
1260 ret = open(path, O_WRONLY | O_CREAT | O_TRUNC, mode);
1261 }
1262 return ret;
1263}
1264
1265static int create_symlink(const char *buf, const char *path)
1266{
1267 int ret = symlink(buf, path);
1268
1269 if (ret < 0 && errno == ENOENT) {
1270 create_subdirectories(path);
1271 ret = symlink(buf, path);
1272 }
1273 return ret;
1274}
1275
5aa7d94c
LT
1276static void create_file(struct patch *patch)
1277{
1278 const char *path = patch->new_name;
1279 unsigned mode = patch->new_mode;
1280 unsigned long size = patch->resultsize;
1281 char *buf = patch->result;
1282
1283 if (!mode)
1284 mode = S_IFREG | 0644;
1285 if (S_ISREG(mode)) {
1286 int fd;
1287 mode = (mode & 0100) ? 0777 : 0666;
5c8af185 1288 fd = create_regular_file(path, mode);
5aa7d94c
LT
1289 if (fd < 0)
1290 die("unable to create file %s (%s)", path, strerror(errno));
1291 if (write(fd, buf, size) != size)
1292 die("unable to write file %s", path);
1293 close(fd);
1294 add_index_file(path, mode, buf, size);
1295 return;
1296 }
1297 if (S_ISLNK(mode)) {
1298 if (size && buf[size-1] == '\n')
1299 size--;
1300 buf[size] = 0;
5c8af185 1301 if (create_symlink(buf, path) < 0)
5aa7d94c
LT
1302 die("unable to write symlink %s", path);
1303 add_index_file(path, mode, buf, size);
1304 return;
1305 }
1306 die("unable to write file mode %o", mode);
1307}
1308
1309static void write_out_one_result(struct patch *patch)
1310{
1311 if (patch->is_delete > 0) {
1312 remove_file(patch);
1313 return;
1314 }
1315 if (patch->is_new > 0 || patch->is_copy) {
1316 create_file(patch);
1317 return;
1318 }
1319 /*
1320 * Rename or modification boils down to the same
1321 * thing: remove the old, write the new
1322 */
1323 remove_file(patch);
1324 create_file(patch);
1325}
1326
1327static void write_out_results(struct patch *list)
1328{
f7b79707
LT
1329 if (!list)
1330 die("No changes");
1331
5aa7d94c
LT
1332 while (list) {
1333 write_out_one_result(list);
1334 list = list->next;
1335 }
1336}
1337
1338static struct cache_file cache_file;
1339
c1bb9350
LT
1340static int apply_patch(int fd)
1341{
5aa7d94c 1342 int newfd;
c1bb9350
LT
1343 unsigned long offset, size;
1344 char *buffer = read_patch_file(fd, &size);
19c58fb8 1345 struct patch *list = NULL, **listp = &list;
c1bb9350
LT
1346
1347 if (!buffer)
1348 return -1;
1349 offset = 0;
1350 while (size > 0) {
19c58fb8
LT
1351 struct patch *patch;
1352 int nr;
1353
1354 patch = xmalloc(sizeof(*patch));
1355 memset(patch, 0, sizeof(*patch));
1356 nr = parse_chunk(buffer + offset, size, patch);
c1bb9350
LT
1357 if (nr < 0)
1358 break;
3f40315a 1359 patch_stats(patch);
19c58fb8
LT
1360 *listp = patch;
1361 listp = &patch->next;
c1bb9350
LT
1362 offset += nr;
1363 size -= nr;
1364 }
19c58fb8 1365
5aa7d94c
LT
1366 newfd = -1;
1367 write_index = check_index && apply;
1368 if (write_index)
1369 newfd = hold_index_file_for_update(&cache_file, get_index_file());
1370 if (check_index) {
1371 if (read_cache() < 0)
1372 die("unable to read index file");
1373 }
1374
a577284a
LT
1375 if ((check || apply) && check_patch_list(list) < 0)
1376 exit(1);
1377
5aa7d94c
LT
1378 if (apply)
1379 write_out_results(list);
1380
1381 if (write_index) {
1382 if (write_cache(newfd, active_cache, active_nr) ||
1383 commit_index_file(&cache_file))
1384 die("Unable to write new cachefile");
1385 }
1386
a577284a
LT
1387 if (show_files)
1388 show_file_list(list);
1389
1390 if (diffstat)
1391 stat_patch_list(list);
19c58fb8 1392
96c912a4
JH
1393 if (summary)
1394 summary_patch_list(list);
1395
c1bb9350
LT
1396 free(buffer);
1397 return 0;
1398}
1399
1400int main(int argc, char **argv)
1401{
1402 int i;
4dfdbe10 1403 int read_stdin = 1;
c1bb9350 1404
c1bb9350
LT
1405 for (i = 1; i < argc; i++) {
1406 const char *arg = argv[i];
1407 int fd;
1408
1409 if (!strcmp(arg, "-")) {
1410 apply_patch(0);
4dfdbe10 1411 read_stdin = 0;
c1bb9350
LT
1412 continue;
1413 }
1414 if (!strcmp(arg, "--no-merge")) {
1415 merge_patch = 0;
1416 continue;
1417 }
fab2c257 1418 if (!strcmp(arg, "--stat")) {
a577284a 1419 apply = 0;
fab2c257
LT
1420 diffstat = 1;
1421 continue;
1422 }
96c912a4
JH
1423 if (!strcmp(arg, "--summary")) {
1424 apply = 0;
1425 summary = 1;
1426 continue;
1427 }
a577284a
LT
1428 if (!strcmp(arg, "--check")) {
1429 apply = 0;
1430 check = 1;
1431 continue;
1432 }
3cca928d
LT
1433 if (!strcmp(arg, "--index")) {
1434 check_index = 1;
1435 continue;
1436 }
a577284a
LT
1437 if (!strcmp(arg, "--show-files")) {
1438 show_files = 1;
1439 continue;
1440 }
c1bb9350
LT
1441 fd = open(arg, O_RDONLY);
1442 if (fd < 0)
1443 usage(apply_usage);
4dfdbe10 1444 read_stdin = 0;
c1bb9350
LT
1445 apply_patch(fd);
1446 close(fd);
1447 }
4dfdbe10
LT
1448 if (read_stdin)
1449 apply_patch(0);
c1bb9350
LT
1450 return 0;
1451}