[PATCH] Documentation: describe git extended diff headers.
[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;
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 },
a4acb0eb 440 { "similarity index ", gitdiff_similarity },
70aadac0 441 { "dissimilarity index ", gitdiff_dissimilarity },
9a4a100e 442 { "", gitdiff_unrecognized },
a4acb0eb
LT
443 };
444 int i;
c1bb9350 445
c1bb9350 446 len = linelen(line, size);
a4acb0eb 447 if (!len || line[len-1] != '\n')
c1bb9350 448 break;
a4acb0eb
LT
449 for (i = 0; i < sizeof(optable) / sizeof(optable[0]); i++) {
450 const struct opentry *p = optable + i;
451 int oplen = strlen(p->str);
452 if (len < oplen || memcmp(p->str, line, oplen))
453 continue;
19c58fb8 454 if (p->fn(line + oplen, patch) < 0)
a4acb0eb 455 return offset;
9a4a100e 456 break;
a4acb0eb 457 }
c1bb9350
LT
458 }
459
a4acb0eb 460 return offset;
c1bb9350
LT
461}
462
fab2c257 463static int parse_num(const char *line, unsigned long *p)
46979f56
LT
464{
465 char *ptr;
fab2c257
LT
466
467 if (!isdigit(*line))
468 return 0;
469 *p = strtoul(line, &ptr, 10);
470 return ptr - line;
471}
472
473static int parse_range(const char *line, int len, int offset, const char *expect,
474 unsigned long *p1, unsigned long *p2)
475{
46979f56
LT
476 int digits, ex;
477
478 if (offset < 0 || offset >= len)
479 return -1;
480 line += offset;
481 len -= offset;
482
fab2c257
LT
483 digits = parse_num(line, p1);
484 if (!digits)
46979f56 485 return -1;
46979f56
LT
486
487 offset += digits;
488 line += digits;
489 len -= digits;
490
fab2c257
LT
491 *p2 = *p1;
492 if (*line == ',') {
493 digits = parse_num(line+1, p2);
494 if (!digits)
495 return -1;
496
497 offset += digits+1;
498 line += digits+1;
499 len -= digits+1;
500 }
501
46979f56
LT
502 ex = strlen(expect);
503 if (ex > len)
504 return -1;
505 if (memcmp(line, expect, ex))
506 return -1;
507
508 return offset + ex;
509}
510
511/*
512 * Parse a unified diff fragment header of the
513 * form "@@ -a,b +c,d @@"
514 */
19c58fb8 515static int parse_fragment_header(char *line, int len, struct fragment *fragment)
46979f56
LT
516{
517 int offset;
518
519 if (!len || line[len-1] != '\n')
520 return -1;
521
522 /* Figure out the number of lines in a fragment */
fab2c257
LT
523 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
524 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
46979f56
LT
525
526 return offset;
527}
528
19c58fb8 529static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
c1bb9350
LT
530{
531 unsigned long offset, len;
532
19c58fb8
LT
533 patch->is_rename = patch->is_copy = 0;
534 patch->is_new = patch->is_delete = -1;
535 patch->old_mode = patch->new_mode = 0;
536 patch->old_name = patch->new_name = NULL;
46979f56 537 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
c1bb9350
LT
538 unsigned long nextlen;
539
540 len = linelen(line, size);
541 if (!len)
542 break;
543
544 /* Testing this early allows us to take a few shortcuts.. */
545 if (len < 6)
546 continue;
46979f56
LT
547
548 /*
549 * Make sure we don't find any unconnected patch fragmants.
550 * That's a sign that we didn't find a header, and that a
551 * patch has become corrupted/broken up.
552 */
553 if (!memcmp("@@ -", line, 4)) {
19c58fb8
LT
554 struct fragment dummy;
555 if (parse_fragment_header(line, len, &dummy) < 0)
46979f56
LT
556 continue;
557 error("patch fragment without header at line %d: %.*s", linenr, len-1, line);
558 }
559
c1bb9350
LT
560 if (size < len + 6)
561 break;
562
563 /*
564 * Git patch? It might not have a real patch, just a rename
565 * or mode change, so we handle that specially
566 */
567 if (!memcmp("diff --git ", line, 11)) {
19c58fb8 568 int git_hdr_len = parse_git_header(line, len, size, patch);
c1bb9350
LT
569 if (git_hdr_len < 0)
570 continue;
5041aa70 571 if (!patch->old_name && !patch->new_name)
33f4d087 572 die("git diff header lacks filename information (line %d)", linenr);
a4acb0eb 573 *hdrsize = git_hdr_len;
c1bb9350
LT
574 return offset;
575 }
576
577 /** --- followed by +++ ? */
578 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
579 continue;
580
581 /*
582 * We only accept unified patches, so we want it to
583 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
584 * minimum
585 */
586 nextlen = linelen(line + len, size - len);
587 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
588 continue;
589
590 /* Ok, we'll consider it a patch */
19c58fb8 591 parse_traditional_patch(line, line+len, patch);
c1bb9350 592 *hdrsize = len + nextlen;
46979f56 593 linenr += 2;
c1bb9350
LT
594 return offset;
595 }
596 return -1;
597}
598
c1bb9350
LT
599/*
600 * Parse a unified diff. Note that this really needs
601 * to parse each fragment separately, since the only
602 * way to know the difference between a "---" that is
603 * part of a patch, and a "---" that starts the next
604 * patch is to look at the line counts..
605 */
19c58fb8 606static int parse_fragment(char *line, unsigned long size, struct patch *patch, struct fragment *fragment)
c1bb9350 607{
3f40315a 608 int added, deleted;
c1bb9350 609 int len = linelen(line, size), offset;
30996652 610 unsigned long oldlines, newlines;
c1bb9350 611
19c58fb8 612 offset = parse_fragment_header(line, len, fragment);
c1bb9350
LT
613 if (offset < 0)
614 return -1;
19c58fb8
LT
615 oldlines = fragment->oldlines;
616 newlines = fragment->newlines;
c1bb9350 617
30996652
LT
618 if (patch->is_new < 0) {
619 patch->is_new = !oldlines;
620 if (!oldlines)
621 patch->old_name = NULL;
622 }
623 if (patch->is_delete < 0) {
624 patch->is_delete = !newlines;
625 if (!newlines)
626 patch->new_name = NULL;
627 }
628
629 if (patch->is_new != !oldlines)
630 return error("new file depends on old contents");
631 if (patch->is_delete != !newlines)
632 return error("deleted file still has contents");
a4acb0eb 633
c1bb9350
LT
634 /* Parse the thing.. */
635 line += len;
636 size -= len;
46979f56 637 linenr++;
3f40315a 638 added = deleted = 0;
46979f56 639 for (offset = len; size > 0; offset += len, size -= len, line += len, linenr++) {
c1bb9350
LT
640 if (!oldlines && !newlines)
641 break;
642 len = linelen(line, size);
643 if (!len || line[len-1] != '\n')
644 return -1;
645 switch (*line) {
646 default:
647 return -1;
648 case ' ':
649 oldlines--;
650 newlines--;
651 break;
652 case '-':
3f40315a 653 deleted++;
c1bb9350
LT
654 oldlines--;
655 break;
656 case '+':
3f40315a 657 added++;
c1bb9350
LT
658 newlines--;
659 break;
fab2c257
LT
660 /* We allow "\ No newline at end of file" */
661 case '\\':
3cca928d
LT
662 if (len < 12 || memcmp(line, "\\ No newline", 12))
663 return -1;
fab2c257 664 break;
c1bb9350
LT
665 }
666 }
3f40315a
LT
667 patch->lines_added += added;
668 patch->lines_deleted += deleted;
c1bb9350
LT
669 return offset;
670}
671
19c58fb8 672static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
c1bb9350
LT
673{
674 unsigned long offset = 0;
19c58fb8 675 struct fragment **fragp = &patch->fragments;
c1bb9350
LT
676
677 while (size > 4 && !memcmp(line, "@@ -", 4)) {
19c58fb8
LT
678 struct fragment *fragment;
679 int len;
680
681 fragment = xmalloc(sizeof(*fragment));
682 memset(fragment, 0, sizeof(*fragment));
683 len = parse_fragment(line, size, patch, fragment);
c1bb9350 684 if (len <= 0)
46979f56 685 die("corrupt patch at line %d", linenr);
c1bb9350 686
19c58fb8
LT
687 fragment->patch = line;
688 fragment->size = len;
689
690 *fragp = fragment;
691 fragp = &fragment->next;
c1bb9350
LT
692
693 offset += len;
694 line += len;
695 size -= len;
696 }
697 return offset;
698}
699
19c58fb8 700static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
c1bb9350
LT
701{
702 int hdrsize, patchsize;
19c58fb8 703 int offset = find_header(buffer, size, &hdrsize, patch);
c1bb9350
LT
704
705 if (offset < 0)
706 return offset;
c1bb9350 707
19c58fb8 708 patchsize = parse_single_patch(buffer + offset + hdrsize, size - offset - hdrsize, patch);
c1bb9350
LT
709
710 return offset + hdrsize + patchsize;
711}
712
3f40315a
LT
713const char pluses[] = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
714const char minuses[]= "----------------------------------------------------------------------";
715
716static void show_stats(struct patch *patch)
717{
718 char *name = patch->old_name;
95bedc9e 719 int len, max, add, del, total;
3f40315a 720
5041aa70 721 if (!name)
3f40315a
LT
722 name = patch->new_name;
723
724 /*
725 * "scale" the filename
726 */
727 len = strlen(name);
728 max = max_len;
729 if (max > 50)
730 max = 50;
731 if (len > max)
732 name += len - max;
733 len = max;
734
735 /*
736 * scale the add/delete
737 */
738 max = max_change;
739 if (max + len > 70)
740 max = 70 - len;
95bedc9e
LT
741
742 add = patch->lines_added;
743 del = patch->lines_deleted;
744 total = add + del;
745
746 total = (total * max + max_change / 2) / max_change;
747 add = (add * max + max_change / 2) / max_change;
748 del = total - add;
3f40315a
LT
749 printf(" %-*s |%5d %.*s%.*s\n",
750 len, name, patch->lines_added + patch->lines_deleted,
751 add, pluses, del, minuses);
752}
753
3cca928d
LT
754static int read_old_data(struct stat *st, const char *path, void *buf, unsigned long size)
755{
756 int fd;
757 unsigned long got;
758
759 switch (st->st_mode & S_IFMT) {
760 case S_IFLNK:
761 return readlink(path, buf, size);
762 case S_IFREG:
763 fd = open(path, O_RDONLY);
764 if (fd < 0)
765 return error("unable to open %s", path);
766 got = 0;
767 for (;;) {
768 int ret = read(fd, buf + got, size - got);
769 if (ret < 0) {
770 if (errno == EAGAIN)
771 continue;
772 break;
773 }
774 if (!ret)
775 break;
776 got += ret;
777 }
778 close(fd);
779 return got;
780
781 default:
782 return -1;
783 }
784}
785
786static int find_offset(const char *buf, unsigned long size, const char *fragment, unsigned long fragsize, int line)
787{
6e7c92a9
LT
788 int i;
789 unsigned long start, backwards, forwards;
3cca928d
LT
790
791 if (fragsize > size)
792 return -1;
793
794 start = 0;
795 if (line > 1) {
3cca928d 796 unsigned long offset = 0;
6e7c92a9
LT
797 i = line-1;
798 while (offset + fragsize <= size) {
3cca928d
LT
799 if (buf[offset++] == '\n') {
800 start = offset;
6e7c92a9 801 if (!--i)
3cca928d
LT
802 break;
803 }
804 }
805 }
806
807 /* Exact line number? */
808 if (!memcmp(buf + start, fragment, fragsize))
809 return start;
810
6e7c92a9
LT
811 /*
812 * There's probably some smart way to do this, but I'll leave
813 * that to the smart and beautiful people. I'm simple and stupid.
814 */
815 backwards = start;
816 forwards = start;
817 for (i = 0; ; i++) {
818 unsigned long try;
819 int n;
820
821 /* "backward" */
822 if (i & 1) {
823 if (!backwards) {
824 if (forwards + fragsize > size)
825 break;
826 continue;
827 }
828 do {
829 --backwards;
830 } while (backwards && buf[backwards-1] != '\n');
831 try = backwards;
832 } else {
833 while (forwards + fragsize <= size) {
834 if (buf[forwards++] == '\n')
835 break;
836 }
837 try = forwards;
838 }
839
840 if (try + fragsize > size)
841 continue;
842 if (memcmp(buf + try, fragment, fragsize))
843 continue;
844 n = (i >> 1)+1;
845 if (i & 1)
846 n = -n;
847 fprintf(stderr, "Fragment applied at offset %d\n", n);
848 return try;
849 }
850
3cca928d
LT
851 /*
852 * We should start searching forward and backward.
853 */
854 return -1;
855}
856
6e7c92a9
LT
857struct buffer_desc {
858 char *buffer;
859 unsigned long size;
860 unsigned long alloc;
861};
862
863static int apply_one_fragment(struct buffer_desc *desc, struct fragment *frag)
3cca928d 864{
6e7c92a9 865 char *buf = desc->buffer;
3cca928d
LT
866 const char *patch = frag->patch;
867 int offset, size = frag->size;
868 char *old = xmalloc(size);
869 char *new = xmalloc(size);
870 int oldsize = 0, newsize = 0;
871
872 while (size > 0) {
873 int len = linelen(patch, size);
874 int plen;
875
876 if (!len)
877 break;
878
879 /*
880 * "plen" is how much of the line we should use for
881 * the actual patch data. Normally we just remove the
882 * first character on the line, but if the line is
883 * followed by "\ No newline", then we also remove the
884 * last one (which is the newline, of course).
885 */
886 plen = len-1;
887 if (len > size && patch[len] == '\\')
888 plen--;
889 switch (*patch) {
890 case ' ':
891 case '-':
892 memcpy(old + oldsize, patch + 1, plen);
893 oldsize += plen;
894 if (*patch == '-')
895 break;
896 /* Fall-through for ' ' */
897 case '+':
898 memcpy(new + newsize, patch + 1, plen);
899 newsize += plen;
900 break;
901 case '@': case '\\':
902 /* Ignore it, we already handled it */
903 break;
904 default:
905 return -1;
906 }
907 patch += len;
908 size -= len;
909 }
910
6e7c92a9 911 offset = find_offset(buf, desc->size, old, oldsize, frag->newpos);
3cca928d 912 if (offset >= 0) {
6e7c92a9
LT
913 int diff = newsize - oldsize;
914 unsigned long size = desc->size + diff;
915 unsigned long alloc = desc->alloc;
916
917 if (size > alloc) {
918 alloc = size + 8192;
919 desc->alloc = alloc;
920 buf = xrealloc(buf, alloc);
921 desc->buffer = buf;
922 }
923 desc->size = size;
924 memmove(buf + offset + newsize, buf + offset + oldsize, size - offset - newsize);
925 memcpy(buf + offset, new, newsize);
3cca928d
LT
926 offset = 0;
927 }
928
929 free(old);
930 free(new);
931 return offset;
932}
933
6e7c92a9 934static int apply_fragments(struct buffer_desc *desc, struct patch *patch)
3cca928d
LT
935{
936 struct fragment *frag = patch->fragments;
937
938 while (frag) {
6e7c92a9 939 if (apply_one_fragment(desc, frag) < 0)
3cca928d
LT
940 return error("patch failed: %s:%d", patch->old_name, frag->oldpos);
941 frag = frag->next;
942 }
30996652 943 return 0;
3cca928d
LT
944}
945
946static int apply_data(struct patch *patch, struct stat *st)
947{
6e7c92a9
LT
948 char *buf;
949 unsigned long size, alloc;
950 struct buffer_desc desc;
3cca928d 951
30996652
LT
952 size = 0;
953 alloc = 0;
954 buf = NULL;
955 if (patch->old_name) {
956 size = st->st_size;
957 alloc = size + 8192;
958 buf = xmalloc(alloc);
959 if (read_old_data(st, patch->old_name, buf, alloc) != size)
960 return error("read of %s failed", patch->old_name);
961 }
6e7c92a9
LT
962
963 desc.size = size;
964 desc.alloc = alloc;
965 desc.buffer = buf;
966 if (apply_fragments(&desc, patch) < 0)
3cca928d 967 return -1;
6e7c92a9
LT
968 patch->result = desc.buffer;
969 patch->resultsize = desc.size;
5aa7d94c
LT
970
971 if (patch->is_delete && patch->resultsize)
972 return error("removal patch leaves file contents");
973
3cca928d
LT
974 return 0;
975}
976
a577284a 977static int check_patch(struct patch *patch)
fab2c257 978{
a577284a 979 struct stat st;
fab2c257
LT
980 const char *old_name = patch->old_name;
981 const char *new_name = patch->new_name;
982
983 if (old_name) {
a577284a
LT
984 int changed;
985
a577284a
LT
986 if (lstat(old_name, &st) < 0)
987 return error("%s: %s\n", strerror(errno));
3cca928d
LT
988 if (check_index) {
989 int pos = cache_name_pos(old_name, strlen(old_name));
990 if (pos < 0)
991 return error("%s: does not exist in index", old_name);
992 changed = ce_match_stat(active_cache[pos], &st);
993 if (changed)
994 return error("%s: does not match index", old_name);
995 }
996 if (patch->is_new < 0)
997 patch->is_new = 0;
a577284a
LT
998 if (!patch->old_mode)
999 patch->old_mode = st.st_mode;
3cca928d
LT
1000 if ((st.st_mode ^ patch->old_mode) & S_IFMT)
1001 return error("%s: wrong type", old_name);
1002 if (st.st_mode != patch->old_mode)
1003 fprintf(stderr, "warning: %s has type %o, expected %o\n",
1004 old_name, st.st_mode, patch->old_mode);
fab2c257 1005 }
a577284a 1006
fab2c257 1007 if (new_name && (patch->is_new | patch->is_rename | patch->is_copy)) {
3cca928d 1008 if (check_index && cache_name_pos(new_name, strlen(new_name)) >= 0)
a577284a
LT
1009 return error("%s: already exists in index", new_name);
1010 if (!lstat(new_name, &st))
1011 return error("%s: already exists in working directory", new_name);
1012 if (errno != ENOENT)
1013 return error("%s: %s", new_name, strerror(errno));
5aa7d94c
LT
1014 if (!patch->new_mode)
1015 patch->new_mode = S_IFREG | 0644;
fab2c257 1016 }
3cca928d
LT
1017
1018 if (new_name && old_name) {
1019 int same = !strcmp(old_name, new_name);
1020 if (!patch->new_mode)
1021 patch->new_mode = patch->old_mode;
1022 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
1023 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
1024 patch->new_mode, new_name, patch->old_mode,
1025 same ? "" : " of ", same ? "" : old_name);
1026 }
1027
1028 if (apply_data(patch, &st) < 0)
1029 return error("%s: patch does not apply", old_name);
a577284a 1030 return 0;
fab2c257
LT
1031}
1032
a577284a 1033static int check_patch_list(struct patch *patch)
19c58fb8 1034{
a577284a
LT
1035 int error = 0;
1036
1037 for (;patch ; patch = patch->next)
1038 error |= check_patch(patch);
1039 return error;
1040}
1041
1042static void show_file(int c, unsigned int mode, const char *name)
1043{
1044 printf("%c %o %s\n", c, mode, name);
1045}
3f40315a 1046
a577284a
LT
1047static void show_file_list(struct patch *patch)
1048{
1049 for (;patch ; patch = patch->next) {
1050 if (patch->is_rename) {
1051 show_file('-', patch->old_mode, patch->old_name);
1052 show_file('+', patch->new_mode, patch->new_name);
1053 continue;
1054 }
1055 if (patch->is_copy || patch->is_new) {
1056 show_file('+', patch->new_mode, patch->new_name);
1057 continue;
1058 }
1059 if (patch->is_delete) {
1060 show_file('-', patch->old_mode, patch->old_name);
1061 continue;
1062 }
1063 if (patch->old_mode && patch->new_mode && patch->old_mode != patch->new_mode) {
1064 printf("M %o:%o %s\n", patch->old_mode, patch->new_mode, patch->old_name);
1065 continue;
19c58fb8 1066 }
a577284a
LT
1067 printf("M %o %s\n", patch->old_mode, patch->old_name);
1068 }
1069}
fab2c257 1070
a577284a
LT
1071static void stat_patch_list(struct patch *patch)
1072{
1073 int files, adds, dels;
1074
1075 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
1076 files++;
1077 adds += patch->lines_added;
1078 dels += patch->lines_deleted;
1079 show_stats(patch);
1080 }
1081
1082 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
3f40315a
LT
1083}
1084
1085static void patch_stats(struct patch *patch)
1086{
1087 int lines = patch->lines_added + patch->lines_deleted;
1088
1089 if (lines > max_change)
1090 max_change = lines;
1091 if (patch->old_name) {
1092 int len = strlen(patch->old_name);
1093 if (len > max_len)
1094 max_len = len;
1095 }
1096 if (patch->new_name) {
1097 int len = strlen(patch->new_name);
1098 if (len > max_len)
1099 max_len = len;
1100 }
19c58fb8
LT
1101}
1102
5aa7d94c
LT
1103static void remove_file(struct patch *patch)
1104{
1105 if (write_index) {
1106 if (remove_file_from_cache(patch->old_name) < 0)
1107 die("unable to remove %s from index", patch->old_name);
1108 }
1109 unlink(patch->old_name);
1110}
1111
1112static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
1113{
1114 struct stat st;
1115 struct cache_entry *ce;
1116 int namelen = strlen(path);
1117 unsigned ce_size = cache_entry_size(namelen);
1118
1119 if (!write_index)
1120 return;
1121
1122 ce = xmalloc(ce_size);
1123 memset(ce, 0, ce_size);
1124 memcpy(ce->name, path, namelen);
1125 ce->ce_mode = create_ce_mode(mode);
1126 ce->ce_flags = htons(namelen);
1127 if (lstat(path, &st) < 0)
1128 die("unable to stat newly created file %s", path);
1129 fill_stat_cache_info(ce, &st);
1130 if (write_sha1_file(buf, size, "blob", ce->sha1) < 0)
1131 die("unable to create backing store for newly created file %s", path);
1132 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
1133 die("unable to add cache entry for %s", path);
1134}
1135
1136static void create_file(struct patch *patch)
1137{
1138 const char *path = patch->new_name;
1139 unsigned mode = patch->new_mode;
1140 unsigned long size = patch->resultsize;
1141 char *buf = patch->result;
1142
1143 if (!mode)
1144 mode = S_IFREG | 0644;
1145 if (S_ISREG(mode)) {
1146 int fd;
1147 mode = (mode & 0100) ? 0777 : 0666;
1148 fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, mode);
1149 if (fd < 0)
1150 die("unable to create file %s (%s)", path, strerror(errno));
1151 if (write(fd, buf, size) != size)
1152 die("unable to write file %s", path);
1153 close(fd);
1154 add_index_file(path, mode, buf, size);
1155 return;
1156 }
1157 if (S_ISLNK(mode)) {
1158 if (size && buf[size-1] == '\n')
1159 size--;
1160 buf[size] = 0;
1161 if (symlink(buf, path) < 0)
1162 die("unable to write symlink %s", path);
1163 add_index_file(path, mode, buf, size);
1164 return;
1165 }
1166 die("unable to write file mode %o", mode);
1167}
1168
1169static void write_out_one_result(struct patch *patch)
1170{
1171 if (patch->is_delete > 0) {
1172 remove_file(patch);
1173 return;
1174 }
1175 if (patch->is_new > 0 || patch->is_copy) {
1176 create_file(patch);
1177 return;
1178 }
1179 /*
1180 * Rename or modification boils down to the same
1181 * thing: remove the old, write the new
1182 */
1183 remove_file(patch);
1184 create_file(patch);
1185}
1186
1187static void write_out_results(struct patch *list)
1188{
1189 while (list) {
1190 write_out_one_result(list);
1191 list = list->next;
1192 }
1193}
1194
1195static struct cache_file cache_file;
1196
c1bb9350
LT
1197static int apply_patch(int fd)
1198{
5aa7d94c 1199 int newfd;
c1bb9350
LT
1200 unsigned long offset, size;
1201 char *buffer = read_patch_file(fd, &size);
19c58fb8 1202 struct patch *list = NULL, **listp = &list;
c1bb9350
LT
1203
1204 if (!buffer)
1205 return -1;
1206 offset = 0;
1207 while (size > 0) {
19c58fb8
LT
1208 struct patch *patch;
1209 int nr;
1210
1211 patch = xmalloc(sizeof(*patch));
1212 memset(patch, 0, sizeof(*patch));
1213 nr = parse_chunk(buffer + offset, size, patch);
c1bb9350
LT
1214 if (nr < 0)
1215 break;
3f40315a 1216 patch_stats(patch);
19c58fb8
LT
1217 *listp = patch;
1218 listp = &patch->next;
c1bb9350
LT
1219 offset += nr;
1220 size -= nr;
1221 }
19c58fb8 1222
5aa7d94c
LT
1223 newfd = -1;
1224 write_index = check_index && apply;
1225 if (write_index)
1226 newfd = hold_index_file_for_update(&cache_file, get_index_file());
1227 if (check_index) {
1228 if (read_cache() < 0)
1229 die("unable to read index file");
1230 }
1231
a577284a
LT
1232 if ((check || apply) && check_patch_list(list) < 0)
1233 exit(1);
1234
5aa7d94c
LT
1235 if (apply)
1236 write_out_results(list);
1237
1238 if (write_index) {
1239 if (write_cache(newfd, active_cache, active_nr) ||
1240 commit_index_file(&cache_file))
1241 die("Unable to write new cachefile");
1242 }
1243
a577284a
LT
1244 if (show_files)
1245 show_file_list(list);
1246
1247 if (diffstat)
1248 stat_patch_list(list);
19c58fb8 1249
c1bb9350
LT
1250 free(buffer);
1251 return 0;
1252}
1253
1254int main(int argc, char **argv)
1255{
1256 int i;
4dfdbe10 1257 int read_stdin = 1;
c1bb9350 1258
c1bb9350
LT
1259 for (i = 1; i < argc; i++) {
1260 const char *arg = argv[i];
1261 int fd;
1262
1263 if (!strcmp(arg, "-")) {
1264 apply_patch(0);
4dfdbe10 1265 read_stdin = 0;
c1bb9350
LT
1266 continue;
1267 }
1268 if (!strcmp(arg, "--no-merge")) {
1269 merge_patch = 0;
1270 continue;
1271 }
fab2c257 1272 if (!strcmp(arg, "--stat")) {
a577284a 1273 apply = 0;
fab2c257
LT
1274 diffstat = 1;
1275 continue;
1276 }
a577284a
LT
1277 if (!strcmp(arg, "--check")) {
1278 apply = 0;
1279 check = 1;
1280 continue;
1281 }
3cca928d
LT
1282 if (!strcmp(arg, "--index")) {
1283 check_index = 1;
1284 continue;
1285 }
a577284a
LT
1286 if (!strcmp(arg, "--show-files")) {
1287 show_files = 1;
1288 continue;
1289 }
c1bb9350
LT
1290 fd = open(arg, O_RDONLY);
1291 if (fd < 0)
1292 usage(apply_usage);
4dfdbe10 1293 read_stdin = 0;
c1bb9350
LT
1294 apply_patch(fd);
1295 close(fd);
1296 }
4dfdbe10
LT
1297 if (read_stdin)
1298 apply_patch(0);
c1bb9350
LT
1299 return 0;
1300}