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