t1400: make test debuggable.
[git/git.git] / builtin-apply.c
CommitLineData
c1bb9350
LT
1/*
2 * apply.c
3 *
4 * Copyright (C) Linus Torvalds, 2005
5 *
6 * This applies patches on top of some (arbitrary) version of the SCM.
7 *
c1bb9350 8 */
d854f783 9#include <fnmatch.h>
c1bb9350 10#include "cache.h"
03ac6e64 11#include "cache-tree.h"
22943f1a 12#include "quote.h"
8e440259 13#include "blob.h"
051308f6 14#include "delta.h"
ac6245e3 15#include "builtin.h"
c1bb9350 16
a9486b02
PR
17/*
18 * --check turns on checking that the working tree matches the
19 * files that are being modified, but doesn't apply the patch
20 * --stat does just a diffstat, and doesn't actually apply
21 * --numstat does numeric diffstat, and doesn't actually apply
22 * --index-info shows the old and new index info for paths if available.
23 * --index updates the cache as well.
24 * --cached updates only the cache without ever touching the working tree.
25 */
edf2e370
JH
26static const char *prefix;
27static int prefix_length = -1;
dbd0f7d3 28static int newfd = -1;
edf2e370 29
e36f8b60 30static int p_value = 1;
96f1e58f
DR
31static int check_index;
32static int write_index;
33static int cached;
34static int diffstat;
35static int numstat;
36static int summary;
37static int check;
a577284a 38static int apply = 1;
96f1e58f 39static int apply_in_reverse;
57dc397c 40static int apply_with_reject;
a2bf404e 41static int apply_verbosely;
96f1e58f
DR
42static int no_add;
43static int show_index_info;
22943f1a 44static int line_termination = '\n';
47495887 45static unsigned long p_context = -1;
12dd6e8c 46static const char apply_usage[] =
a2bf404e 47"git-apply [--stat] [--numstat] [--summary] [--check] [--index] [--cached] [--apply] [--no-add] [--index-info] [--allow-binary-replacement] [--reverse] [--reject] [--verbose] [-z] [-pNUM] [-CNUM] [--whitespace=<nowarn|warn|error|error-all|strip>] <patch>...";
c1bb9350 48
19bfcd5a 49static enum whitespace_eol {
2ae1c53b 50 nowarn_whitespace,
19bfcd5a 51 warn_on_whitespace,
b5767dd6 52 error_on_whitespace,
2ae1c53b 53 strip_whitespace,
621603b7 54} new_whitespace = warn_on_whitespace;
96f1e58f 55static int whitespace_error;
fc96b7c9 56static int squelch_whitespace_errors = 5;
96f1e58f
DR
57static int applied_after_stripping;
58static const char *patch_input_file;
19bfcd5a 59
2ae1c53b
JH
60static void parse_whitespace_option(const char *option)
61{
62 if (!option) {
621603b7 63 new_whitespace = warn_on_whitespace;
2ae1c53b
JH
64 return;
65 }
66 if (!strcmp(option, "warn")) {
67 new_whitespace = warn_on_whitespace;
68 return;
69 }
621603b7
JH
70 if (!strcmp(option, "nowarn")) {
71 new_whitespace = nowarn_whitespace;
72 return;
73 }
2ae1c53b
JH
74 if (!strcmp(option, "error")) {
75 new_whitespace = error_on_whitespace;
76 return;
77 }
78 if (!strcmp(option, "error-all")) {
79 new_whitespace = error_on_whitespace;
80 squelch_whitespace_errors = 0;
81 return;
82 }
83 if (!strcmp(option, "strip")) {
84 new_whitespace = strip_whitespace;
85 return;
86 }
87 die("unrecognized whitespace option '%s'", option);
88}
89
f21d6726
JH
90static void set_default_whitespace_mode(const char *whitespace_option)
91{
92 if (!whitespace_option && !apply_default_whitespace) {
93 new_whitespace = (apply
94 ? warn_on_whitespace
95 : nowarn_whitespace);
96 }
97}
98
3f40315a
LT
99/*
100 * For "diff-stat" like behaviour, we keep track of the biggest change
101 * we've seen, and the longest filename. That allows us to do simple
102 * scaling.
103 */
104static int max_change, max_len;
105
a4acb0eb
LT
106/*
107 * Various "current state", notably line numbers and what
108 * file (and how) we're patching right now.. The "is_xxxx"
109 * things are flags, where -1 means "don't know yet".
110 */
46979f56 111static int linenr = 1;
19c58fb8 112
3cd4f5e8
JH
113/*
114 * This represents one "hunk" from a patch, starting with
115 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
116 * patch text is pointed at by patch, and its byte length
117 * is stored in size. leading and trailing are the number
118 * of context lines.
119 */
19c58fb8 120struct fragment {
47495887 121 unsigned long leading, trailing;
19c58fb8
LT
122 unsigned long oldpos, oldlines;
123 unsigned long newpos, newlines;
124 const char *patch;
125 int size;
57dc397c 126 int rejected;
19c58fb8
LT
127 struct fragment *next;
128};
129
3cd4f5e8
JH
130/*
131 * When dealing with a binary patch, we reuse "leading" field
132 * to store the type of the binary hunk, either deflated "delta"
133 * or deflated "literal".
134 */
135#define binary_patch_method leading
136#define BINARY_DELTA_DEFLATED 1
137#define BINARY_LITERAL_DEFLATED 2
138
19c58fb8 139struct patch {
5041aa70 140 char *new_name, *old_name, *def_name;
19c58fb8 141 unsigned int old_mode, new_mode;
f686d030 142 int is_rename, is_copy, is_new, is_delete, is_binary;
57dc397c 143 int rejected;
0660626c 144 unsigned long deflate_origlen;
3f40315a 145 int lines_added, lines_deleted;
96c912a4 146 int score;
3eaa38da 147 int inaccurate_eof:1;
19c58fb8 148 struct fragment *fragments;
5aa7d94c 149 char *result;
3cca928d 150 unsigned long resultsize;
2cf67f1e
JH
151 char old_sha1_prefix[41];
152 char new_sha1_prefix[41];
19c58fb8
LT
153 struct patch *next;
154};
46979f56 155
a2bf404e
JH
156static void say_patch_name(FILE *output, const char *pre, struct patch *patch, const char *post)
157{
158 fputs(pre, output);
159 if (patch->old_name && patch->new_name &&
160 strcmp(patch->old_name, patch->new_name)) {
161 write_name_quoted(NULL, 0, patch->old_name, 1, output);
162 fputs(" => ", output);
163 write_name_quoted(NULL, 0, patch->new_name, 1, output);
164 }
165 else {
166 const char *n = patch->new_name;
167 if (!n)
168 n = patch->old_name;
169 write_name_quoted(NULL, 0, n, 1, output);
170 }
171 fputs(post, output);
172}
173
c1bb9350 174#define CHUNKSIZE (8192)
a4acb0eb 175#define SLOP (16)
c1bb9350
LT
176
177static void *read_patch_file(int fd, unsigned long *sizep)
178{
179 unsigned long size = 0, alloc = CHUNKSIZE;
180 void *buffer = xmalloc(alloc);
181
182 for (;;) {
183 int nr = alloc - size;
184 if (nr < 1024) {
185 alloc += CHUNKSIZE;
186 buffer = xrealloc(buffer, alloc);
187 nr = alloc - size;
188 }
1d7f171c 189 nr = xread(fd, (char *) buffer + size, nr);
c1bb9350
LT
190 if (!nr)
191 break;
1c15afb9 192 if (nr < 0)
c1bb9350 193 die("git-apply: read returned %s", strerror(errno));
c1bb9350
LT
194 size += nr;
195 }
196 *sizep = size;
a4acb0eb
LT
197
198 /*
199 * Make sure that we have some slop in the buffer
200 * so that we can do speculative "memcmp" etc, and
201 * see to it that it is NUL-filled.
202 */
203 if (alloc < size + SLOP)
204 buffer = xrealloc(buffer, size + SLOP);
1d7f171c 205 memset((char *) buffer + size, 0, SLOP);
c1bb9350
LT
206 return buffer;
207}
208
3cca928d 209static unsigned long linelen(const char *buffer, unsigned long size)
c1bb9350
LT
210{
211 unsigned long len = 0;
212 while (size--) {
213 len++;
214 if (*buffer++ == '\n')
215 break;
216 }
217 return len;
218}
219
a4acb0eb
LT
220static int is_dev_null(const char *str)
221{
222 return !memcmp("/dev/null", str, 9) && isspace(str[9]);
223}
224
381ca9a3
LT
225#define TERM_SPACE 1
226#define TERM_TAB 2
9a4a100e
LT
227
228static int name_terminate(const char *name, int namelen, int c, int terminate)
229{
230 if (c == ' ' && !(terminate & TERM_SPACE))
231 return 0;
232 if (c == '\t' && !(terminate & TERM_TAB))
233 return 0;
234
9a4a100e
LT
235 return 1;
236}
237
238static char * find_name(const char *line, char *def, int p_value, int terminate)
c1bb9350 239{
a4acb0eb
LT
240 int len;
241 const char *start = line;
242 char *name;
243
22943f1a
JH
244 if (*line == '"') {
245 /* Proposed "new-style" GNU patch/diff format; see
246 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
247 */
248 name = unquote_c_style(line, NULL);
249 if (name) {
250 char *cp = name;
251 while (p_value) {
252 cp = strchr(name, '/');
253 if (!cp)
254 break;
255 cp++;
256 p_value--;
257 }
258 if (cp) {
259 /* name can later be freed, so we need
260 * to memmove, not just return cp
261 */
262 memmove(name, cp, strlen(cp) + 1);
263 free(def);
264 return name;
265 }
266 else {
267 free(name);
268 name = NULL;
269 }
270 }
271 }
272
c1bb9350 273 for (;;) {
a4acb0eb 274 char c = *line;
9a4a100e
LT
275
276 if (isspace(c)) {
277 if (c == '\n')
278 break;
279 if (name_terminate(start, line-start, c, terminate))
280 break;
281 }
a4acb0eb
LT
282 line++;
283 if (c == '/' && !--p_value)
284 start = line;
285 }
286 if (!start)
287 return def;
288 len = line - start;
289 if (!len)
290 return def;
291
292 /*
293 * Generally we prefer the shorter name, especially
294 * if the other one is just a variation of that with
295 * something else tacked on to the end (ie "file.orig"
296 * or "file~").
297 */
298 if (def) {
299 int deflen = strlen(def);
300 if (deflen < len && !strncmp(start, def, deflen))
301 return def;
c1bb9350 302 }
a4acb0eb
LT
303
304 name = xmalloc(len + 1);
305 memcpy(name, start, len);
306 name[len] = 0;
307 free(def);
308 return name;
309}
310
311/*
312 * Get the name etc info from the --/+++ lines of a traditional patch header
313 *
314 * NOTE! This hardcodes "-p1" behaviour in filename detection.
9a4a100e
LT
315 *
316 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
317 * files, we can happily check the index for a match, but for creating a
318 * new file we should try to match whatever "patch" does. I have no idea.
a4acb0eb 319 */
19c58fb8 320static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
a4acb0eb 321{
a4acb0eb
LT
322 char *name;
323
a9486b02
PR
324 first += 4; /* skip "--- " */
325 second += 4; /* skip "+++ " */
a4acb0eb 326 if (is_dev_null(first)) {
19c58fb8
LT
327 patch->is_new = 1;
328 patch->is_delete = 0;
5041aa70 329 name = find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB);
19c58fb8 330 patch->new_name = name;
a4acb0eb 331 } else if (is_dev_null(second)) {
19c58fb8
LT
332 patch->is_new = 0;
333 patch->is_delete = 1;
381ca9a3 334 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
19c58fb8 335 patch->old_name = name;
a4acb0eb 336 } else {
381ca9a3
LT
337 name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
338 name = find_name(second, name, p_value, TERM_SPACE | TERM_TAB);
19c58fb8 339 patch->old_name = patch->new_name = name;
a4acb0eb
LT
340 }
341 if (!name)
342 die("unable to find filename in patch at line %d", linenr);
a4acb0eb
LT
343}
344
19c58fb8 345static int gitdiff_hdrend(const char *line, struct patch *patch)
a4acb0eb
LT
346{
347 return -1;
348}
349
1e3f6b6e
LT
350/*
351 * We're anal about diff header consistency, to make
352 * sure that we don't end up having strange ambiguous
353 * patches floating around.
354 *
355 * As a result, gitdiff_{old|new}name() will check
356 * their names against any previous information, just
357 * to make sure..
358 */
359static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
360{
1e3f6b6e
LT
361 if (!orig_name && !isnull)
362 return find_name(line, NULL, 1, 0);
363
1e3f6b6e 364 if (orig_name) {
22943f1a
JH
365 int len;
366 const char *name;
367 char *another;
1e3f6b6e
LT
368 name = orig_name;
369 len = strlen(name);
370 if (isnull)
371 die("git-apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
22943f1a
JH
372 another = find_name(line, NULL, 1, 0);
373 if (!another || memcmp(another, name, len))
374 die("git-apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
375 free(another);
1e3f6b6e
LT
376 return orig_name;
377 }
22943f1a
JH
378 else {
379 /* expect "/dev/null" */
380 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
381 die("git-apply: bad git-diff - expected /dev/null on line %d", linenr);
382 return NULL;
383 }
1e3f6b6e
LT
384}
385
19c58fb8 386static int gitdiff_oldname(const char *line, struct patch *patch)
a4acb0eb 387{
19c58fb8 388 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
a4acb0eb
LT
389 return 0;
390}
391
19c58fb8 392static int gitdiff_newname(const char *line, struct patch *patch)
a4acb0eb 393{
19c58fb8 394 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
a4acb0eb
LT
395 return 0;
396}
397
19c58fb8 398static int gitdiff_oldmode(const char *line, struct patch *patch)
a4acb0eb 399{
19c58fb8 400 patch->old_mode = strtoul(line, NULL, 8);
a4acb0eb
LT
401 return 0;
402}
403
19c58fb8 404static int gitdiff_newmode(const char *line, struct patch *patch)
a4acb0eb 405{
19c58fb8 406 patch->new_mode = strtoul(line, NULL, 8);
a4acb0eb
LT
407 return 0;
408}
409
19c58fb8 410static int gitdiff_delete(const char *line, struct patch *patch)
a4acb0eb 411{
19c58fb8 412 patch->is_delete = 1;
5041aa70 413 patch->old_name = patch->def_name;
19c58fb8 414 return gitdiff_oldmode(line, patch);
a4acb0eb
LT
415}
416
19c58fb8 417static int gitdiff_newfile(const char *line, struct patch *patch)
a4acb0eb 418{
19c58fb8 419 patch->is_new = 1;
5041aa70 420 patch->new_name = patch->def_name;
19c58fb8 421 return gitdiff_newmode(line, patch);
a4acb0eb
LT
422}
423
19c58fb8 424static int gitdiff_copysrc(const char *line, struct patch *patch)
a4acb0eb 425{
19c58fb8
LT
426 patch->is_copy = 1;
427 patch->old_name = find_name(line, NULL, 0, 0);
a4acb0eb
LT
428 return 0;
429}
430
19c58fb8 431static int gitdiff_copydst(const char *line, struct patch *patch)
a4acb0eb 432{
19c58fb8
LT
433 patch->is_copy = 1;
434 patch->new_name = find_name(line, NULL, 0, 0);
a4acb0eb
LT
435 return 0;
436}
437
19c58fb8 438static int gitdiff_renamesrc(const char *line, struct patch *patch)
a4acb0eb 439{
19c58fb8
LT
440 patch->is_rename = 1;
441 patch->old_name = find_name(line, NULL, 0, 0);
a4acb0eb
LT
442 return 0;
443}
444
19c58fb8 445static int gitdiff_renamedst(const char *line, struct patch *patch)
a4acb0eb 446{
19c58fb8
LT
447 patch->is_rename = 1;
448 patch->new_name = find_name(line, NULL, 0, 0);
a4acb0eb
LT
449 return 0;
450}
451
19c58fb8 452static int gitdiff_similarity(const char *line, struct patch *patch)
a4acb0eb 453{
96c912a4
JH
454 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
455 patch->score = 0;
a4acb0eb 456 return 0;
c1bb9350
LT
457}
458
70aadac0
JH
459static int gitdiff_dissimilarity(const char *line, struct patch *patch)
460{
96c912a4
JH
461 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
462 patch->score = 0;
70aadac0
JH
463 return 0;
464}
465
2cf67f1e
JH
466static int gitdiff_index(const char *line, struct patch *patch)
467{
468 /* index line is N hexadecimal, "..", N hexadecimal,
469 * and optional space with octal mode.
470 */
471 const char *ptr, *eol;
472 int len;
473
474 ptr = strchr(line, '.');
9add69b1 475 if (!ptr || ptr[1] != '.' || 40 < ptr - line)
2cf67f1e
JH
476 return 0;
477 len = ptr - line;
478 memcpy(patch->old_sha1_prefix, line, len);
479 patch->old_sha1_prefix[len] = 0;
480
481 line = ptr + 2;
482 ptr = strchr(line, ' ');
483 eol = strchr(line, '\n');
484
485 if (!ptr || eol < ptr)
486 ptr = eol;
487 len = ptr - line;
488
9add69b1 489 if (40 < len)
2cf67f1e
JH
490 return 0;
491 memcpy(patch->new_sha1_prefix, line, len);
492 patch->new_sha1_prefix[len] = 0;
493 if (*ptr == ' ')
494 patch->new_mode = patch->old_mode = strtoul(ptr+1, NULL, 8);
495 return 0;
496}
497
9a4a100e
LT
498/*
499 * This is normal for a diff that doesn't change anything: we'll fall through
500 * into the next diff. Tell the parser to break out.
501 */
19c58fb8 502static int gitdiff_unrecognized(const char *line, struct patch *patch)
9a4a100e
LT
503{
504 return -1;
505}
506
22943f1a
JH
507static const char *stop_at_slash(const char *line, int llen)
508{
509 int i;
510
511 for (i = 0; i < llen; i++) {
512 int ch = line[i];
513 if (ch == '/')
514 return line + i;
515 }
516 return NULL;
517}
518
519/* This is to extract the same name that appears on "diff --git"
520 * line. We do not find and return anything if it is a rename
521 * patch, and it is OK because we will find the name elsewhere.
522 * We need to reliably find name only when it is mode-change only,
523 * creation or deletion of an empty file. In any of these cases,
524 * both sides are the same name under a/ and b/ respectively.
525 */
526static char *git_header_name(char *line, int llen)
5041aa70
LT
527{
528 int len;
22943f1a
JH
529 const char *name;
530 const char *second = NULL;
5041aa70 531
22943f1a
JH
532 line += strlen("diff --git ");
533 llen -= strlen("diff --git ");
534
535 if (*line == '"') {
536 const char *cp;
537 char *first = unquote_c_style(line, &second);
538 if (!first)
5041aa70 539 return NULL;
22943f1a
JH
540
541 /* advance to the first slash */
542 cp = stop_at_slash(first, strlen(first));
543 if (!cp || cp == first) {
544 /* we do not accept absolute paths */
545 free_first_and_fail:
546 free(first);
547 return NULL;
548 }
549 len = strlen(cp+1);
550 memmove(first, cp+1, len+1); /* including NUL */
551
552 /* second points at one past closing dq of name.
553 * find the second name.
554 */
555 while ((second < line + llen) && isspace(*second))
556 second++;
557
558 if (line + llen <= second)
559 goto free_first_and_fail;
560 if (*second == '"') {
561 char *sp = unquote_c_style(second, NULL);
562 if (!sp)
563 goto free_first_and_fail;
564 cp = stop_at_slash(sp, strlen(sp));
565 if (!cp || cp == sp) {
566 free_both_and_fail:
567 free(sp);
568 goto free_first_and_fail;
569 }
570 /* They must match, otherwise ignore */
571 if (strcmp(cp+1, first))
572 goto free_both_and_fail;
573 free(sp);
574 return first;
575 }
576
577 /* unquoted second */
578 cp = stop_at_slash(second, line + llen - second);
579 if (!cp || cp == second)
580 goto free_first_and_fail;
581 cp++;
582 if (line + llen - cp != len + 1 ||
583 memcmp(first, cp, len))
584 goto free_first_and_fail;
585 return first;
5041aa70
LT
586 }
587
22943f1a
JH
588 /* unquoted first name */
589 name = stop_at_slash(line, llen);
590 if (!name || name == line)
5041aa70
LT
591 return NULL;
592
22943f1a
JH
593 name++;
594
595 /* since the first name is unquoted, a dq if exists must be
596 * the beginning of the second name.
597 */
598 for (second = name; second < line + llen; second++) {
599 if (*second == '"') {
600 const char *cp = second;
601 const char *np;
602 char *sp = unquote_c_style(second, NULL);
603
604 if (!sp)
605 return NULL;
606 np = stop_at_slash(sp, strlen(sp));
607 if (!np || np == sp) {
608 free_second_and_fail:
609 free(sp);
610 return NULL;
611 }
612 np++;
613 len = strlen(np);
614 if (len < cp - name &&
615 !strncmp(np, name, len) &&
616 isspace(name[len])) {
617 /* Good */
618 memmove(sp, np, len + 1);
619 return sp;
620 }
621 goto free_second_and_fail;
622 }
623 }
624
5041aa70
LT
625 /*
626 * Accept a name only if it shows up twice, exactly the same
627 * form.
628 */
629 for (len = 0 ; ; len++) {
dd305c84 630 switch (name[len]) {
5041aa70
LT
631 default:
632 continue;
633 case '\n':
e70a165d 634 return NULL;
5041aa70
LT
635 case '\t': case ' ':
636 second = name+len;
637 for (;;) {
638 char c = *second++;
639 if (c == '\n')
640 return NULL;
641 if (c == '/')
642 break;
643 }
0e87e048 644 if (second[len] == '\n' && !memcmp(name, second, len)) {
5041aa70
LT
645 char *ret = xmalloc(len + 1);
646 memcpy(ret, name, len);
647 ret[len] = 0;
648 return ret;
649 }
650 }
651 }
652 return NULL;
653}
654
c1bb9350 655/* Verify that we recognize the lines following a git header */
19c58fb8 656static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
c1bb9350 657{
a4acb0eb
LT
658 unsigned long offset;
659
660 /* A git diff has explicit new/delete information, so we don't guess */
19c58fb8
LT
661 patch->is_new = 0;
662 patch->is_delete = 0;
a4acb0eb 663
5041aa70
LT
664 /*
665 * Some things may not have the old name in the
666 * rest of the headers anywhere (pure mode changes,
667 * or removing or adding empty files), so we get
668 * the default name from the header.
669 */
22943f1a 670 patch->def_name = git_header_name(line, len);
5041aa70 671
a4acb0eb
LT
672 line += len;
673 size -= len;
674 linenr++;
675 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
676 static const struct opentry {
677 const char *str;
19c58fb8 678 int (*fn)(const char *, struct patch *);
a4acb0eb
LT
679 } optable[] = {
680 { "@@ -", gitdiff_hdrend },
681 { "--- ", gitdiff_oldname },
682 { "+++ ", gitdiff_newname },
683 { "old mode ", gitdiff_oldmode },
684 { "new mode ", gitdiff_newmode },
685 { "deleted file mode ", gitdiff_delete },
686 { "new file mode ", gitdiff_newfile },
687 { "copy from ", gitdiff_copysrc },
688 { "copy to ", gitdiff_copydst },
33f4d087
LT
689 { "rename old ", gitdiff_renamesrc },
690 { "rename new ", gitdiff_renamedst },
dc938417
LT
691 { "rename from ", gitdiff_renamesrc },
692 { "rename to ", gitdiff_renamedst },
a4acb0eb 693 { "similarity index ", gitdiff_similarity },
70aadac0 694 { "dissimilarity index ", gitdiff_dissimilarity },
2cf67f1e 695 { "index ", gitdiff_index },
9a4a100e 696 { "", gitdiff_unrecognized },
a4acb0eb
LT
697 };
698 int i;
c1bb9350 699
c1bb9350 700 len = linelen(line, size);
a4acb0eb 701 if (!len || line[len-1] != '\n')
c1bb9350 702 break;
b4f2a6ac 703 for (i = 0; i < ARRAY_SIZE(optable); i++) {
a4acb0eb
LT
704 const struct opentry *p = optable + i;
705 int oplen = strlen(p->str);
706 if (len < oplen || memcmp(p->str, line, oplen))
707 continue;
19c58fb8 708 if (p->fn(line + oplen, patch) < 0)
a4acb0eb 709 return offset;
9a4a100e 710 break;
a4acb0eb 711 }
c1bb9350
LT
712 }
713
a4acb0eb 714 return offset;
c1bb9350
LT
715}
716
fab2c257 717static int parse_num(const char *line, unsigned long *p)
46979f56
LT
718{
719 char *ptr;
fab2c257
LT
720
721 if (!isdigit(*line))
722 return 0;
723 *p = strtoul(line, &ptr, 10);
724 return ptr - line;
725}
726
727static int parse_range(const char *line, int len, int offset, const char *expect,
728 unsigned long *p1, unsigned long *p2)
729{
46979f56
LT
730 int digits, ex;
731
732 if (offset < 0 || offset >= len)
733 return -1;
734 line += offset;
735 len -= offset;
736
fab2c257
LT
737 digits = parse_num(line, p1);
738 if (!digits)
46979f56 739 return -1;
46979f56
LT
740
741 offset += digits;
742 line += digits;
743 len -= digits;
744
c1504628 745 *p2 = 1;
fab2c257
LT
746 if (*line == ',') {
747 digits = parse_num(line+1, p2);
748 if (!digits)
749 return -1;
750
751 offset += digits+1;
752 line += digits+1;
753 len -= digits+1;
754 }
755
46979f56
LT
756 ex = strlen(expect);
757 if (ex > len)
758 return -1;
759 if (memcmp(line, expect, ex))
760 return -1;
761
762 return offset + ex;
763}
764
765/*
766 * Parse a unified diff fragment header of the
767 * form "@@ -a,b +c,d @@"
768 */
19c58fb8 769static int parse_fragment_header(char *line, int len, struct fragment *fragment)
46979f56
LT
770{
771 int offset;
772
773 if (!len || line[len-1] != '\n')
774 return -1;
775
776 /* Figure out the number of lines in a fragment */
fab2c257
LT
777 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
778 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
46979f56
LT
779
780 return offset;
781}
782
19c58fb8 783static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
c1bb9350
LT
784{
785 unsigned long offset, len;
786
19c58fb8
LT
787 patch->is_rename = patch->is_copy = 0;
788 patch->is_new = patch->is_delete = -1;
789 patch->old_mode = patch->new_mode = 0;
790 patch->old_name = patch->new_name = NULL;
46979f56 791 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
c1bb9350
LT
792 unsigned long nextlen;
793
794 len = linelen(line, size);
795 if (!len)
796 break;
797
798 /* Testing this early allows us to take a few shortcuts.. */
799 if (len < 6)
800 continue;
46979f56
LT
801
802 /*
82e5a82f 803 * Make sure we don't find any unconnected patch fragments.
46979f56
LT
804 * That's a sign that we didn't find a header, and that a
805 * patch has become corrupted/broken up.
806 */
807 if (!memcmp("@@ -", line, 4)) {
19c58fb8
LT
808 struct fragment dummy;
809 if (parse_fragment_header(line, len, &dummy) < 0)
46979f56 810 continue;
4ec99bf0 811 error("patch fragment without header at line %d: %.*s", linenr, (int)len-1, line);
46979f56
LT
812 }
813
c1bb9350
LT
814 if (size < len + 6)
815 break;
816
817 /*
818 * Git patch? It might not have a real patch, just a rename
819 * or mode change, so we handle that specially
820 */
821 if (!memcmp("diff --git ", line, 11)) {
19c58fb8 822 int git_hdr_len = parse_git_header(line, len, size, patch);
206de27e 823 if (git_hdr_len <= len)
c1bb9350 824 continue;
b7e8039a
LT
825 if (!patch->old_name && !patch->new_name) {
826 if (!patch->def_name)
827 die("git diff header lacks filename information (line %d)", linenr);
828 patch->old_name = patch->new_name = patch->def_name;
829 }
a4acb0eb 830 *hdrsize = git_hdr_len;
c1bb9350
LT
831 return offset;
832 }
833
834 /** --- followed by +++ ? */
835 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
836 continue;
837
838 /*
839 * We only accept unified patches, so we want it to
840 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
841 * minimum
842 */
843 nextlen = linelen(line + len, size - len);
844 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
845 continue;
846
847 /* Ok, we'll consider it a patch */
19c58fb8 848 parse_traditional_patch(line, line+len, patch);
c1bb9350 849 *hdrsize = len + nextlen;
46979f56 850 linenr += 2;
c1bb9350
LT
851 return offset;
852 }
853 return -1;
854}
855
c1bb9350
LT
856/*
857 * Parse a unified diff. Note that this really needs
858 * to parse each fragment separately, since the only
859 * way to know the difference between a "---" that is
860 * part of a patch, and a "---" that starts the next
861 * patch is to look at the line counts..
862 */
19c58fb8 863static int parse_fragment(char *line, unsigned long size, struct patch *patch, struct fragment *fragment)
c1bb9350 864{
3f40315a 865 int added, deleted;
c1bb9350 866 int len = linelen(line, size), offset;
30996652 867 unsigned long oldlines, newlines;
47495887 868 unsigned long leading, trailing;
c1bb9350 869
19c58fb8 870 offset = parse_fragment_header(line, len, fragment);
c1bb9350
LT
871 if (offset < 0)
872 return -1;
19c58fb8
LT
873 oldlines = fragment->oldlines;
874 newlines = fragment->newlines;
47495887
EB
875 leading = 0;
876 trailing = 0;
c1bb9350 877
30996652
LT
878 if (patch->is_new < 0) {
879 patch->is_new = !oldlines;
880 if (!oldlines)
881 patch->old_name = NULL;
882 }
883 if (patch->is_delete < 0) {
884 patch->is_delete = !newlines;
885 if (!newlines)
886 patch->new_name = NULL;
887 }
888
3103cf9e 889 if (patch->is_new && oldlines)
30996652 890 return error("new file depends on old contents");
af3f929f
LT
891 if (patch->is_delete != !newlines) {
892 if (newlines)
893 return error("deleted file still has contents");
894 fprintf(stderr, "** warning: file %s becomes empty but is not deleted\n", patch->new_name);
895 }
a4acb0eb 896
c1bb9350
LT
897 /* Parse the thing.. */
898 line += len;
899 size -= len;
46979f56 900 linenr++;
3f40315a 901 added = deleted = 0;
46979f56 902 for (offset = len; size > 0; offset += len, size -= len, line += len, linenr++) {
c1bb9350
LT
903 if (!oldlines && !newlines)
904 break;
905 len = linelen(line, size);
906 if (!len || line[len-1] != '\n')
907 return -1;
908 switch (*line) {
909 default:
910 return -1;
911 case ' ':
912 oldlines--;
913 newlines--;
47495887
EB
914 if (!deleted && !added)
915 leading++;
916 trailing++;
c1bb9350
LT
917 break;
918 case '-':
3f40315a 919 deleted++;
c1bb9350 920 oldlines--;
47495887 921 trailing = 0;
c1bb9350
LT
922 break;
923 case '+':
19bfcd5a
LT
924 /*
925 * We know len is at least two, since we have a '+' and
b5767dd6
JH
926 * we checked that the last character was a '\n' above.
927 * That is, an addition of an empty line would check
928 * the '+' here. Sneaky...
19bfcd5a 929 */
2ae1c53b 930 if ((new_whitespace != nowarn_whitespace) &&
b5767dd6 931 isspace(line[len-2])) {
fc96b7c9
JH
932 whitespace_error++;
933 if (squelch_whitespace_errors &&
934 squelch_whitespace_errors <
935 whitespace_error)
936 ;
937 else {
938 fprintf(stderr, "Adds trailing whitespace.\n%s:%d:%.*s\n",
939 patch_input_file,
940 linenr, len-2, line+1);
941 }
19bfcd5a 942 }
3f40315a 943 added++;
c1bb9350 944 newlines--;
47495887 945 trailing = 0;
c1bb9350 946 break;
433ef8a2
FK
947
948 /* We allow "\ No newline at end of file". Depending
949 * on locale settings when the patch was produced we
950 * don't know what this line looks like. The only
56d33b11
JH
951 * thing we do know is that it begins with "\ ".
952 * Checking for 12 is just for sanity check -- any
953 * l10n of "\ No newline..." is at least that long.
954 */
fab2c257 955 case '\\':
433ef8a2 956 if (len < 12 || memcmp(line, "\\ ", 2))
3cca928d 957 return -1;
fab2c257 958 break;
c1bb9350
LT
959 }
960 }
c1504628
LT
961 if (oldlines || newlines)
962 return -1;
47495887
EB
963 fragment->leading = leading;
964 fragment->trailing = trailing;
965
8b64647d
JH
966 /* If a fragment ends with an incomplete line, we failed to include
967 * it in the above loop because we hit oldlines == newlines == 0
968 * before seeing it.
969 */
433ef8a2 970 if (12 < size && !memcmp(line, "\\ ", 2))
8b64647d
JH
971 offset += linelen(line, size);
972
3f40315a
LT
973 patch->lines_added += added;
974 patch->lines_deleted += deleted;
c1bb9350
LT
975 return offset;
976}
977
19c58fb8 978static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
c1bb9350
LT
979{
980 unsigned long offset = 0;
19c58fb8 981 struct fragment **fragp = &patch->fragments;
c1bb9350
LT
982
983 while (size > 4 && !memcmp(line, "@@ -", 4)) {
19c58fb8
LT
984 struct fragment *fragment;
985 int len;
986
90321c10 987 fragment = xcalloc(1, sizeof(*fragment));
19c58fb8 988 len = parse_fragment(line, size, patch, fragment);
c1bb9350 989 if (len <= 0)
46979f56 990 die("corrupt patch at line %d", linenr);
c1bb9350 991
19c58fb8
LT
992 fragment->patch = line;
993 fragment->size = len;
994
995 *fragp = fragment;
996 fragp = &fragment->next;
c1bb9350
LT
997
998 offset += len;
999 line += len;
1000 size -= len;
1001 }
1002 return offset;
1003}
1004
1fea629f
LT
1005static inline int metadata_changes(struct patch *patch)
1006{
1007 return patch->is_rename > 0 ||
1008 patch->is_copy > 0 ||
1009 patch->is_new > 0 ||
1010 patch->is_delete ||
1011 (patch->old_mode && patch->new_mode &&
1012 patch->old_mode != patch->new_mode);
1013}
1014
3cd4f5e8
JH
1015static char *inflate_it(const void *data, unsigned long size,
1016 unsigned long inflated_size)
051308f6 1017{
3cd4f5e8
JH
1018 z_stream stream;
1019 void *out;
1020 int st;
1021
1022 memset(&stream, 0, sizeof(stream));
1023
1024 stream.next_in = (unsigned char *)data;
1025 stream.avail_in = size;
1026 stream.next_out = out = xmalloc(inflated_size);
1027 stream.avail_out = inflated_size;
1028 inflateInit(&stream);
1029 st = inflate(&stream, Z_FINISH);
1030 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1031 free(out);
1032 return NULL;
1033 }
1034 return out;
1035}
1036
1037static struct fragment *parse_binary_hunk(char **buf_p,
1038 unsigned long *sz_p,
1039 int *status_p,
1040 int *used_p)
1041{
1042 /* Expect a line that begins with binary patch method ("literal"
1043 * or "delta"), followed by the length of data before deflating.
1044 * a sequence of 'length-byte' followed by base-85 encoded data
1045 * should follow, terminated by a newline.
051308f6
JH
1046 *
1047 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1048 * and we would limit the patch line to 66 characters,
1049 * so one line can fit up to 13 groups that would decode
1050 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1051 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
051308f6
JH
1052 */
1053 int llen, used;
3cd4f5e8
JH
1054 unsigned long size = *sz_p;
1055 char *buffer = *buf_p;
1056 int patch_method;
1057 unsigned long origlen;
0660626c 1058 char *data = NULL;
3cd4f5e8
JH
1059 int hunk_size = 0;
1060 struct fragment *frag;
051308f6 1061
0660626c
JH
1062 llen = linelen(buffer, size);
1063 used = llen;
3cd4f5e8
JH
1064
1065 *status_p = 0;
0660626c
JH
1066
1067 if (!strncmp(buffer, "delta ", 6)) {
3cd4f5e8
JH
1068 patch_method = BINARY_DELTA_DEFLATED;
1069 origlen = strtoul(buffer + 6, NULL, 10);
0660626c
JH
1070 }
1071 else if (!strncmp(buffer, "literal ", 8)) {
3cd4f5e8
JH
1072 patch_method = BINARY_LITERAL_DEFLATED;
1073 origlen = strtoul(buffer + 8, NULL, 10);
0660626c
JH
1074 }
1075 else
3cd4f5e8
JH
1076 return NULL;
1077
1078 linenr++;
0660626c 1079 buffer += llen;
051308f6
JH
1080 while (1) {
1081 int byte_length, max_byte_length, newsize;
1082 llen = linelen(buffer, size);
1083 used += llen;
1084 linenr++;
03eb8f8a
JH
1085 if (llen == 1) {
1086 /* consume the blank line */
1087 buffer++;
1088 size--;
051308f6 1089 break;
03eb8f8a 1090 }
051308f6
JH
1091 /* Minimum line is "A00000\n" which is 7-byte long,
1092 * and the line length must be multiple of 5 plus 2.
1093 */
1094 if ((llen < 7) || (llen-2) % 5)
1095 goto corrupt;
1096 max_byte_length = (llen - 2) / 5 * 4;
1097 byte_length = *buffer;
1098 if ('A' <= byte_length && byte_length <= 'Z')
1099 byte_length = byte_length - 'A' + 1;
1100 else if ('a' <= byte_length && byte_length <= 'z')
1101 byte_length = byte_length - 'a' + 27;
1102 else
1103 goto corrupt;
1104 /* if the input length was not multiple of 4, we would
1105 * have filler at the end but the filler should never
1106 * exceed 3 bytes
1107 */
1108 if (max_byte_length < byte_length ||
1109 byte_length <= max_byte_length - 4)
1110 goto corrupt;
3cd4f5e8 1111 newsize = hunk_size + byte_length;
0660626c 1112 data = xrealloc(data, newsize);
3cd4f5e8 1113 if (decode_85(data + hunk_size, buffer + 1, byte_length))
051308f6 1114 goto corrupt;
3cd4f5e8 1115 hunk_size = newsize;
051308f6
JH
1116 buffer += llen;
1117 size -= llen;
1118 }
3cd4f5e8
JH
1119
1120 frag = xcalloc(1, sizeof(*frag));
1121 frag->patch = inflate_it(data, hunk_size, origlen);
1122 if (!frag->patch)
1123 goto corrupt;
1124 free(data);
1125 frag->size = origlen;
1126 *buf_p = buffer;
1127 *sz_p = size;
1128 *used_p = used;
1129 frag->binary_patch_method = patch_method;
1130 return frag;
1131
051308f6 1132 corrupt:
4cac42b1 1133 free(data);
3cd4f5e8
JH
1134 *status_p = -1;
1135 error("corrupt binary patch at line %d: %.*s",
1136 linenr-1, llen-1, buffer);
1137 return NULL;
1138}
1139
1140static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1141{
1142 /* We have read "GIT binary patch\n"; what follows is a line
1143 * that says the patch method (currently, either "literal" or
1144 * "delta") and the length of data before deflating; a
1145 * sequence of 'length-byte' followed by base-85 encoded data
1146 * follows.
1147 *
1148 * When a binary patch is reversible, there is another binary
1149 * hunk in the same format, starting with patch method (either
1150 * "literal" or "delta") with the length of data, and a sequence
1151 * of length-byte + base-85 encoded data, terminated with another
1152 * empty line. This data, when applied to the postimage, produces
1153 * the preimage.
1154 */
1155 struct fragment *forward;
1156 struct fragment *reverse;
1157 int status;
1158 int used, used_1;
1159
1160 forward = parse_binary_hunk(&buffer, &size, &status, &used);
1161 if (!forward && !status)
1162 /* there has to be one hunk (forward hunk) */
1163 return error("unrecognized binary patch at line %d", linenr-1);
1164 if (status)
1165 /* otherwise we already gave an error message */
1166 return status;
1167
1168 reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1169 if (reverse)
1170 used += used_1;
1171 else if (status) {
1172 /* not having reverse hunk is not an error, but having
1173 * a corrupt reverse hunk is.
1174 */
1175 free((void*) forward->patch);
1176 free(forward);
1177 return status;
1178 }
1179 forward->next = reverse;
1180 patch->fragments = forward;
1181 patch->is_binary = 1;
1182 return used;
051308f6
JH
1183}
1184
19c58fb8 1185static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
c1bb9350
LT
1186{
1187 int hdrsize, patchsize;
19c58fb8 1188 int offset = find_header(buffer, size, &hdrsize, patch);
c1bb9350
LT
1189
1190 if (offset < 0)
1191 return offset;
c1bb9350 1192
19c58fb8 1193 patchsize = parse_single_patch(buffer + offset + hdrsize, size - offset - hdrsize, patch);
c1bb9350 1194
92927ed0 1195 if (!patchsize) {
3200d1ae
JH
1196 static const char *binhdr[] = {
1197 "Binary files ",
1198 "Files ",
1199 NULL,
1200 };
051308f6 1201 static const char git_binary[] = "GIT binary patch\n";
3200d1ae
JH
1202 int i;
1203 int hd = hdrsize + offset;
1204 unsigned long llen = linelen(buffer + hd, size - hd);
1205
051308f6
JH
1206 if (llen == sizeof(git_binary) - 1 &&
1207 !memcmp(git_binary, buffer + hd, llen)) {
1208 int used;
1209 linenr++;
1210 used = parse_binary(buffer + hd + llen,
1211 size - hd - llen, patch);
1212 if (used)
1213 patchsize = used + llen;
1214 else
1215 patchsize = 0;
1216 }
1217 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
3200d1ae
JH
1218 for (i = 0; binhdr[i]; i++) {
1219 int len = strlen(binhdr[i]);
1220 if (len < size - hd &&
1221 !memcmp(binhdr[i], buffer + hd, len)) {
051308f6 1222 linenr++;
3200d1ae 1223 patch->is_binary = 1;
051308f6 1224 patchsize = llen;
3200d1ae
JH
1225 break;
1226 }
1227 }
051308f6 1228 }
ff36de08 1229
2b6eef94
JH
1230 /* Empty patch cannot be applied if it is a text patch
1231 * without metadata change. A binary patch appears
1232 * empty to us here.
92927ed0
JH
1233 */
1234 if ((apply || check) &&
2b6eef94 1235 (!patch->is_binary && !metadata_changes(patch)))
ff36de08
JH
1236 die("patch with only garbage at line %d", linenr);
1237 }
1fea629f 1238
c1bb9350
LT
1239 return offset + hdrsize + patchsize;
1240}
1241
e5a94313
JS
1242#define swap(a,b) myswap((a),(b),sizeof(a))
1243
1244#define myswap(a, b, size) do { \
1245 unsigned char mytmp[size]; \
1246 memcpy(mytmp, &a, size); \
1247 memcpy(&a, &b, size); \
1248 memcpy(&b, mytmp, size); \
1249} while (0)
1250
1251static void reverse_patches(struct patch *p)
1252{
1253 for (; p; p = p->next) {
1254 struct fragment *frag = p->fragments;
1255
1256 swap(p->new_name, p->old_name);
1257 swap(p->new_mode, p->old_mode);
1258 swap(p->is_new, p->is_delete);
1259 swap(p->lines_added, p->lines_deleted);
1260 swap(p->old_sha1_prefix, p->new_sha1_prefix);
1261
1262 for (; frag; frag = frag->next) {
1263 swap(frag->newpos, frag->oldpos);
1264 swap(frag->newlines, frag->oldlines);
1265 }
e5a94313
JS
1266 }
1267}
1268
6da4016a
LT
1269static const char pluses[] = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1270static const char minuses[]= "----------------------------------------------------------------------";
3f40315a
LT
1271
1272static void show_stats(struct patch *patch)
1273{
62917097 1274 const char *prefix = "";
03b4538b 1275 char *name = patch->new_name;
22943f1a 1276 char *qname = NULL;
95bedc9e 1277 int len, max, add, del, total;
3f40315a 1278
5041aa70 1279 if (!name)
03b4538b 1280 name = patch->old_name;
3f40315a 1281
22943f1a
JH
1282 if (0 < (len = quote_c_style(name, NULL, NULL, 0))) {
1283 qname = xmalloc(len + 1);
1284 quote_c_style(name, qname, NULL, 0);
1285 name = qname;
1286 }
1287
3f40315a
LT
1288 /*
1289 * "scale" the filename
1290 */
1291 len = strlen(name);
1292 max = max_len;
1293 if (max > 50)
1294 max = 50;
62917097
LT
1295 if (len > max) {
1296 char *slash;
1297 prefix = "...";
1298 max -= 3;
3f40315a 1299 name += len - max;
62917097
LT
1300 slash = strchr(name, '/');
1301 if (slash)
1302 name = slash;
1303 }
3f40315a
LT
1304 len = max;
1305
1306 /*
1307 * scale the add/delete
1308 */
1309 max = max_change;
1310 if (max + len > 70)
1311 max = 70 - len;
95bedc9e
LT
1312
1313 add = patch->lines_added;
1314 del = patch->lines_deleted;
1315 total = add + del;
1316
69f956e1
SV
1317 if (max_change > 0) {
1318 total = (total * max + max_change / 2) / max_change;
1319 add = (add * max + max_change / 2) / max_change;
1320 del = total - add;
1321 }
ff36de08
JH
1322 if (patch->is_binary)
1323 printf(" %s%-*s | Bin\n", prefix, len, name);
1324 else
1325 printf(" %s%-*s |%5d %.*s%.*s\n", prefix,
1326 len, name, patch->lines_added + patch->lines_deleted,
1327 add, pluses, del, minuses);
4cac42b1 1328 free(qname);
3f40315a
LT
1329}
1330
3cca928d
LT
1331static int read_old_data(struct stat *st, const char *path, void *buf, unsigned long size)
1332{
1333 int fd;
1334 unsigned long got;
1335
1336 switch (st->st_mode & S_IFMT) {
1337 case S_IFLNK:
1338 return readlink(path, buf, size);
1339 case S_IFREG:
1340 fd = open(path, O_RDONLY);
1341 if (fd < 0)
1342 return error("unable to open %s", path);
1343 got = 0;
1344 for (;;) {
1d7f171c 1345 int ret = xread(fd, (char *) buf + got, size - got);
1c15afb9 1346 if (ret <= 0)
3cca928d
LT
1347 break;
1348 got += ret;
1349 }
1350 close(fd);
1351 return got;
1352
1353 default:
1354 return -1;
1355 }
1356}
1357
47495887 1358static int find_offset(const char *buf, unsigned long size, const char *fragment, unsigned long fragsize, int line, int *lines)
3cca928d 1359{
6e7c92a9
LT
1360 int i;
1361 unsigned long start, backwards, forwards;
3cca928d
LT
1362
1363 if (fragsize > size)
1364 return -1;
1365
1366 start = 0;
1367 if (line > 1) {
3cca928d 1368 unsigned long offset = 0;
6e7c92a9
LT
1369 i = line-1;
1370 while (offset + fragsize <= size) {
3cca928d
LT
1371 if (buf[offset++] == '\n') {
1372 start = offset;
6e7c92a9 1373 if (!--i)
3cca928d
LT
1374 break;
1375 }
1376 }
1377 }
1378
1379 /* Exact line number? */
1380 if (!memcmp(buf + start, fragment, fragsize))
1381 return start;
1382
6e7c92a9
LT
1383 /*
1384 * There's probably some smart way to do this, but I'll leave
1385 * that to the smart and beautiful people. I'm simple and stupid.
1386 */
1387 backwards = start;
1388 forwards = start;
1389 for (i = 0; ; i++) {
1390 unsigned long try;
1391 int n;
1392
1393 /* "backward" */
1394 if (i & 1) {
1395 if (!backwards) {
1396 if (forwards + fragsize > size)
1397 break;
1398 continue;
1399 }
1400 do {
1401 --backwards;
1402 } while (backwards && buf[backwards-1] != '\n');
1403 try = backwards;
1404 } else {
1405 while (forwards + fragsize <= size) {
1406 if (buf[forwards++] == '\n')
1407 break;
1408 }
1409 try = forwards;
1410 }
1411
1412 if (try + fragsize > size)
1413 continue;
1414 if (memcmp(buf + try, fragment, fragsize))
1415 continue;
1416 n = (i >> 1)+1;
1417 if (i & 1)
1418 n = -n;
47495887 1419 *lines = n;
6e7c92a9
LT
1420 return try;
1421 }
1422
3cca928d
LT
1423 /*
1424 * We should start searching forward and backward.
1425 */
1426 return -1;
1427}
1428
47495887
EB
1429static void remove_first_line(const char **rbuf, int *rsize)
1430{
1431 const char *buf = *rbuf;
1432 int size = *rsize;
1433 unsigned long offset;
1434 offset = 0;
1435 while (offset <= size) {
1436 if (buf[offset++] == '\n')
1437 break;
1438 }
1439 *rsize = size - offset;
1440 *rbuf = buf + offset;
1441}
1442
1443static void remove_last_line(const char **rbuf, int *rsize)
1444{
1445 const char *buf = *rbuf;
1446 int size = *rsize;
1447 unsigned long offset;
1448 offset = size - 1;
1449 while (offset > 0) {
1450 if (buf[--offset] == '\n')
1451 break;
1452 }
1453 *rsize = offset + 1;
1454}
1455
6e7c92a9
LT
1456struct buffer_desc {
1457 char *buffer;
1458 unsigned long size;
1459 unsigned long alloc;
1460};
1461
b5767dd6
JH
1462static int apply_line(char *output, const char *patch, int plen)
1463{
1464 /* plen is number of bytes to be copied from patch,
1465 * starting at patch+1 (patch[0] is '+'). Typically
1466 * patch[plen] is '\n'.
1467 */
1468 int add_nl_to_tail = 0;
2ae1c53b 1469 if ((new_whitespace == strip_whitespace) &&
b5767dd6
JH
1470 1 < plen && isspace(patch[plen-1])) {
1471 if (patch[plen] == '\n')
1472 add_nl_to_tail = 1;
1473 plen--;
1474 while (0 < plen && isspace(patch[plen]))
1475 plen--;
fc96b7c9 1476 applied_after_stripping++;
b5767dd6
JH
1477 }
1478 memcpy(output, patch + 1, plen);
1479 if (add_nl_to_tail)
1480 output[plen++] = '\n';
1481 return plen;
1482}
1483
f686d030 1484static int apply_one_fragment(struct buffer_desc *desc, struct fragment *frag, int inaccurate_eof)
3cca928d 1485{
65aadb92 1486 int match_beginning, match_end;
6e7c92a9 1487 char *buf = desc->buffer;
3cca928d
LT
1488 const char *patch = frag->patch;
1489 int offset, size = frag->size;
1490 char *old = xmalloc(size);
1491 char *new = xmalloc(size);
47495887 1492 const char *oldlines, *newlines;
3cca928d 1493 int oldsize = 0, newsize = 0;
47495887
EB
1494 unsigned long leading, trailing;
1495 int pos, lines;
3cca928d
LT
1496
1497 while (size > 0) {
e5a94313 1498 char first;
3cca928d
LT
1499 int len = linelen(patch, size);
1500 int plen;
1501
1502 if (!len)
1503 break;
1504
1505 /*
1506 * "plen" is how much of the line we should use for
1507 * the actual patch data. Normally we just remove the
1508 * first character on the line, but if the line is
1509 * followed by "\ No newline", then we also remove the
1510 * last one (which is the newline, of course).
1511 */
1512 plen = len-1;
8b64647d 1513 if (len < size && patch[len] == '\\')
3cca928d 1514 plen--;
e5a94313 1515 first = *patch;
f686d030 1516 if (apply_in_reverse) {
e5a94313
JS
1517 if (first == '-')
1518 first = '+';
1519 else if (first == '+')
1520 first = '-';
1521 }
1522 switch (first) {
3cca928d
LT
1523 case ' ':
1524 case '-':
1525 memcpy(old + oldsize, patch + 1, plen);
1526 oldsize += plen;
e5a94313 1527 if (first == '-')
3cca928d
LT
1528 break;
1529 /* Fall-through for ' ' */
1530 case '+':
e5a94313 1531 if (first != '+' || !no_add)
b5767dd6
JH
1532 newsize += apply_line(new + newsize, patch,
1533 plen);
3cca928d
LT
1534 break;
1535 case '@': case '\\':
1536 /* Ignore it, we already handled it */
1537 break;
1538 default:
1539 return -1;
1540 }
1541 patch += len;
1542 size -= len;
1543 }
1544
3eaa38da 1545 if (inaccurate_eof && oldsize > 0 && old[oldsize - 1] == '\n' &&
5b5d4d9e
JS
1546 newsize > 0 && new[newsize - 1] == '\n') {
1547 oldsize--;
1548 newsize--;
1549 }
47495887
EB
1550
1551 oldlines = old;
1552 newlines = new;
1553 leading = frag->leading;
1554 trailing = frag->trailing;
1bf1a859
LT
1555
1556 /*
65aadb92
JH
1557 * If we don't have any leading/trailing data in the patch,
1558 * we want it to match at the beginning/end of the file.
1bf1a859 1559 */
65aadb92 1560 match_beginning = !leading && (frag->oldpos == 1);
1bf1a859
LT
1561 match_end = !trailing;
1562
47495887
EB
1563 lines = 0;
1564 pos = frag->newpos;
1565 for (;;) {
57dc397c
JH
1566 offset = find_offset(buf, desc->size,
1567 oldlines, oldsize, pos, &lines);
1bf1a859
LT
1568 if (match_end && offset + oldsize != desc->size)
1569 offset = -1;
65aadb92
JH
1570 if (match_beginning && offset)
1571 offset = -1;
47495887
EB
1572 if (offset >= 0) {
1573 int diff = newsize - oldsize;
1574 unsigned long size = desc->size + diff;
1575 unsigned long alloc = desc->alloc;
1576
1577 /* Warn if it was necessary to reduce the number
1578 * of context lines.
1579 */
57dc397c
JH
1580 if ((leading != frag->leading) ||
1581 (trailing != frag->trailing))
1582 fprintf(stderr, "Context reduced to (%ld/%ld)"
1583 " to apply fragment at %d\n",
47495887
EB
1584 leading, trailing, pos + lines);
1585
1586 if (size > alloc) {
1587 alloc = size + 8192;
1588 desc->alloc = alloc;
1589 buf = xrealloc(buf, alloc);
1590 desc->buffer = buf;
1591 }
1592 desc->size = size;
57dc397c
JH
1593 memmove(buf + offset + newsize,
1594 buf + offset + oldsize,
1595 size - offset - newsize);
47495887
EB
1596 memcpy(buf + offset, newlines, newsize);
1597 offset = 0;
1598
1599 break;
1600 }
1601
1602 /* Am I at my context limits? */
1603 if ((leading <= p_context) && (trailing <= p_context))
1604 break;
65aadb92
JH
1605 if (match_beginning || match_end) {
1606 match_beginning = match_end = 0;
1bf1a859
LT
1607 continue;
1608 }
47495887
EB
1609 /* Reduce the number of context lines
1610 * Reduce both leading and trailing if they are equal
1611 * otherwise just reduce the larger context.
1612 */
1613 if (leading >= trailing) {
1614 remove_first_line(&oldlines, &oldsize);
1615 remove_first_line(&newlines, &newsize);
1616 pos--;
1617 leading--;
1618 }
1619 if (trailing > leading) {
1620 remove_last_line(&oldlines, &oldsize);
1621 remove_last_line(&newlines, &newsize);
1622 trailing--;
6e7c92a9 1623 }
3cca928d
LT
1624 }
1625
1626 free(old);
1627 free(new);
1628 return offset;
1629}
1630
0660626c
JH
1631static int apply_binary_fragment(struct buffer_desc *desc, struct patch *patch)
1632{
1633 unsigned long dst_size;
1634 struct fragment *fragment = patch->fragments;
1635 void *data;
1636 void *result;
1637
3cd4f5e8
JH
1638 /* Binary patch is irreversible without the optional second hunk */
1639 if (apply_in_reverse) {
1640 if (!fragment->next)
1641 return error("cannot reverse-apply a binary patch "
1642 "without the reverse hunk to '%s'",
1643 patch->new_name
1644 ? patch->new_name : patch->old_name);
03eb8f8a 1645 fragment = fragment->next;
3cd4f5e8
JH
1646 }
1647 data = (void*) fragment->patch;
1648 switch (fragment->binary_patch_method) {
0660626c
JH
1649 case BINARY_DELTA_DEFLATED:
1650 result = patch_delta(desc->buffer, desc->size,
1651 data,
3cd4f5e8 1652 fragment->size,
0660626c
JH
1653 &dst_size);
1654 free(desc->buffer);
1655 desc->buffer = result;
0660626c
JH
1656 break;
1657 case BINARY_LITERAL_DEFLATED:
1658 free(desc->buffer);
1659 desc->buffer = data;
3cd4f5e8 1660 dst_size = fragment->size;
0660626c
JH
1661 break;
1662 }
1663 if (!desc->buffer)
1664 return -1;
1665 desc->size = desc->alloc = dst_size;
1666 return 0;
1667}
1668
051308f6 1669static int apply_binary(struct buffer_desc *desc, struct patch *patch)
3cca928d 1670{
011f4274 1671 const char *name = patch->old_name ? patch->old_name : patch->new_name;
051308f6
JH
1672 unsigned char sha1[20];
1673 unsigned char hdr[50];
1674 int hdrlen;
011f4274 1675
051308f6
JH
1676 /* For safety, we require patch index line to contain
1677 * full 40-byte textual SHA1 for old and new, at least for now.
1678 */
1679 if (strlen(patch->old_sha1_prefix) != 40 ||
1680 strlen(patch->new_sha1_prefix) != 40 ||
1681 get_sha1_hex(patch->old_sha1_prefix, sha1) ||
1682 get_sha1_hex(patch->new_sha1_prefix, sha1))
1683 return error("cannot apply binary patch to '%s' "
1684 "without full index line", name);
011f4274 1685
051308f6
JH
1686 if (patch->old_name) {
1687 /* See if the old one matches what the patch
1688 * applies to.
011f4274 1689 */
051308f6
JH
1690 write_sha1_file_prepare(desc->buffer, desc->size,
1691 blob_type, sha1, hdr, &hdrlen);
1692 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
1693 return error("the patch applies to '%s' (%s), "
1694 "which does not match the "
1695 "current contents.",
1696 name, sha1_to_hex(sha1));
1697 }
1698 else {
1699 /* Otherwise, the old one must be empty. */
1700 if (desc->size)
1701 return error("the patch applies to an empty "
1702 "'%s' but it is not empty", name);
1703 }
011f4274 1704
0660626c 1705 get_sha1_hex(patch->new_sha1_prefix, sha1);
0bef57ee 1706 if (is_null_sha1(sha1)) {
051308f6
JH
1707 free(desc->buffer);
1708 desc->alloc = desc->size = 0;
0660626c 1709 desc->buffer = NULL;
051308f6 1710 return 0; /* deletion patch */
0660626c 1711 }
011f4274 1712
051308f6 1713 if (has_sha1_file(sha1)) {
0660626c 1714 /* We already have the postimage */
051308f6
JH
1715 char type[10];
1716 unsigned long size;
1717
0660626c 1718 free(desc->buffer);
051308f6
JH
1719 desc->buffer = read_sha1_file(sha1, type, &size);
1720 if (!desc->buffer)
1721 return error("the necessary postimage %s for "
1722 "'%s' cannot be read",
1723 patch->new_sha1_prefix, name);
1724 desc->alloc = desc->size = size;
1725 }
1726 else {
0660626c
JH
1727 /* We have verified desc matches the preimage;
1728 * apply the patch data to it, which is stored
1729 * in the patch->fragments->{patch,size}.
011f4274 1730 */
0660626c 1731 if (apply_binary_fragment(desc, patch))
051308f6
JH
1732 return error("binary patch does not apply to '%s'",
1733 name);
011f4274 1734
051308f6
JH
1735 /* verify that the result matches */
1736 write_sha1_file_prepare(desc->buffer, desc->size, blob_type,
1737 sha1, hdr, &hdrlen);
1738 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
03eb8f8a 1739 return error("binary patch to '%s' creates incorrect result (expecting %s, got %s)", name, patch->new_sha1_prefix, sha1_to_hex(sha1));
011f4274 1740 }
3cca928d 1741
051308f6
JH
1742 return 0;
1743}
1744
1745static int apply_fragments(struct buffer_desc *desc, struct patch *patch)
1746{
1747 struct fragment *frag = patch->fragments;
1748 const char *name = patch->old_name ? patch->old_name : patch->new_name;
1749
1750 if (patch->is_binary)
1751 return apply_binary(desc, patch);
1752
3cca928d 1753 while (frag) {
57dc397c
JH
1754 if (apply_one_fragment(desc, frag, patch->inaccurate_eof)) {
1755 error("patch failed: %s:%ld", name, frag->oldpos);
1756 if (!apply_with_reject)
1757 return -1;
1758 frag->rejected = 1;
1759 }
3cca928d
LT
1760 frag = frag->next;
1761 }
30996652 1762 return 0;
3cca928d
LT
1763}
1764
04e4888e 1765static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce)
3cca928d 1766{
6e7c92a9
LT
1767 char *buf;
1768 unsigned long size, alloc;
1769 struct buffer_desc desc;
3cca928d 1770
30996652
LT
1771 size = 0;
1772 alloc = 0;
1773 buf = NULL;
04e4888e
JH
1774 if (cached) {
1775 if (ce) {
1776 char type[20];
1777 buf = read_sha1_file(ce->sha1, type, &size);
1778 if (!buf)
1779 return error("read of %s failed",
1780 patch->old_name);
1781 alloc = size;
1782 }
1783 }
1784 else if (patch->old_name) {
30996652
LT
1785 size = st->st_size;
1786 alloc = size + 8192;
1787 buf = xmalloc(alloc);
1788 if (read_old_data(st, patch->old_name, buf, alloc) != size)
1789 return error("read of %s failed", patch->old_name);
1790 }
6e7c92a9
LT
1791
1792 desc.size = size;
1793 desc.alloc = alloc;
1794 desc.buffer = buf;
57dc397c 1795
6e7c92a9 1796 if (apply_fragments(&desc, patch) < 0)
57dc397c 1797 return -1; /* note with --reject this succeeds. */
2c71810b
JH
1798
1799 /* NUL terminate the result */
242abf10 1800 if (desc.alloc <= desc.size)
2c71810b 1801 desc.buffer = xrealloc(desc.buffer, desc.size + 1);
2c71810b
JH
1802 desc.buffer[desc.size] = 0;
1803
6e7c92a9
LT
1804 patch->result = desc.buffer;
1805 patch->resultsize = desc.size;
5aa7d94c
LT
1806
1807 if (patch->is_delete && patch->resultsize)
1808 return error("removal patch leaves file contents");
1809
3cca928d
LT
1810 return 0;
1811}
1812
7f95aef2 1813static int check_patch(struct patch *patch, struct patch *prev_patch)
fab2c257 1814{
a577284a 1815 struct stat st;
fab2c257
LT
1816 const char *old_name = patch->old_name;
1817 const char *new_name = patch->new_name;
011f4274 1818 const char *name = old_name ? old_name : new_name;
04e4888e 1819 struct cache_entry *ce = NULL;
7f95aef2 1820 int ok_if_exists;
fab2c257 1821
57dc397c 1822 patch->rejected = 1; /* we will drop this after we succeed */
fab2c257 1823 if (old_name) {
04e4888e
JH
1824 int changed = 0;
1825 int stat_ret = 0;
1826 unsigned st_mode = 0;
a577284a 1827
04e4888e
JH
1828 if (!cached)
1829 stat_ret = lstat(old_name, &st);
3cca928d
LT
1830 if (check_index) {
1831 int pos = cache_name_pos(old_name, strlen(old_name));
1832 if (pos < 0)
56d33b11
JH
1833 return error("%s: does not exist in index",
1834 old_name);
04e4888e 1835 ce = active_cache[pos];
56d33b11
JH
1836 if (stat_ret < 0) {
1837 struct checkout costate;
1838 if (errno != ENOENT)
1839 return error("%s: %s", old_name,
1840 strerror(errno));
1841 /* checkout */
1842 costate.base_dir = "";
1843 costate.base_dir_len = 0;
1844 costate.force = 0;
1845 costate.quiet = 0;
1846 costate.not_new = 0;
1847 costate.refresh_cache = 1;
04e4888e 1848 if (checkout_entry(ce,
de84f99c
SP
1849 &costate,
1850 NULL) ||
56d33b11
JH
1851 lstat(old_name, &st))
1852 return -1;
1853 }
04e4888e
JH
1854 if (!cached)
1855 changed = ce_match_stat(ce, &st, 1);
3cca928d 1856 if (changed)
56d33b11
JH
1857 return error("%s: does not match index",
1858 old_name);
04e4888e
JH
1859 if (cached)
1860 st_mode = ntohl(ce->ce_mode);
3cca928d 1861 }
56d33b11
JH
1862 else if (stat_ret < 0)
1863 return error("%s: %s", old_name, strerror(errno));
1864
04e4888e
JH
1865 if (!cached)
1866 st_mode = ntohl(create_ce_mode(st.st_mode));
1867
3cca928d
LT
1868 if (patch->is_new < 0)
1869 patch->is_new = 0;
a577284a 1870 if (!patch->old_mode)
04e4888e
JH
1871 patch->old_mode = st_mode;
1872 if ((st_mode ^ patch->old_mode) & S_IFMT)
3cca928d 1873 return error("%s: wrong type", old_name);
04e4888e 1874 if (st_mode != patch->old_mode)
3cca928d 1875 fprintf(stderr, "warning: %s has type %o, expected %o\n",
04e4888e 1876 old_name, st_mode, patch->old_mode);
fab2c257 1877 }
a577284a 1878
7f95aef2
JH
1879 if (new_name && prev_patch && prev_patch->is_delete &&
1880 !strcmp(prev_patch->old_name, new_name))
1881 /* A type-change diff is always split into a patch to
1882 * delete old, immediately followed by a patch to
1883 * create new (see diff.c::run_diff()); in such a case
1884 * it is Ok that the entry to be deleted by the
1885 * previous patch is still in the working tree and in
1886 * the index.
1887 */
1888 ok_if_exists = 1;
1889 else
1890 ok_if_exists = 0;
1891
fab2c257 1892 if (new_name && (patch->is_new | patch->is_rename | patch->is_copy)) {
7f95aef2
JH
1893 if (check_index &&
1894 cache_name_pos(new_name, strlen(new_name)) >= 0 &&
1895 !ok_if_exists)
a577284a 1896 return error("%s: already exists in index", new_name);
d91d4c2c 1897 if (!cached) {
c28c571c
JH
1898 struct stat nst;
1899 if (!lstat(new_name, &nst)) {
7f95aef2 1900 if (S_ISDIR(nst.st_mode) || ok_if_exists)
c28c571c
JH
1901 ; /* ok */
1902 else
1903 return error("%s: already exists in working directory", new_name);
1904 }
1905 else if ((errno != ENOENT) && (errno != ENOTDIR))
d91d4c2c
JH
1906 return error("%s: %s", new_name, strerror(errno));
1907 }
35cc4bcd
JS
1908 if (!patch->new_mode) {
1909 if (patch->is_new)
1910 patch->new_mode = S_IFREG | 0644;
1911 else
1912 patch->new_mode = patch->old_mode;
1913 }
fab2c257 1914 }
3cca928d
LT
1915
1916 if (new_name && old_name) {
1917 int same = !strcmp(old_name, new_name);
1918 if (!patch->new_mode)
1919 patch->new_mode = patch->old_mode;
1920 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
1921 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
1922 patch->new_mode, new_name, patch->old_mode,
1923 same ? "" : " of ", same ? "" : old_name);
04e4888e 1924 }
3cca928d 1925
04e4888e 1926 if (apply_data(patch, &st, ce) < 0)
011f4274 1927 return error("%s: patch does not apply", name);
57dc397c 1928 patch->rejected = 0;
a577284a 1929 return 0;
fab2c257
LT
1930}
1931
a577284a 1932static int check_patch_list(struct patch *patch)
19c58fb8 1933{
7f95aef2 1934 struct patch *prev_patch = NULL;
60b7f38e 1935 int err = 0;
a577284a 1936
7f95aef2 1937 for (prev_patch = NULL; patch ; patch = patch->next) {
a2bf404e
JH
1938 if (apply_verbosely)
1939 say_patch_name(stderr,
1940 "Checking patch ", patch, "...\n");
60b7f38e 1941 err |= check_patch(patch, prev_patch);
7f95aef2
JH
1942 prev_patch = patch;
1943 }
60b7f38e 1944 return err;
a577284a
LT
1945}
1946
2cf67f1e
JH
1947static void show_index_list(struct patch *list)
1948{
1949 struct patch *patch;
1950
1951 /* Once we start supporting the reverse patch, it may be
1952 * worth showing the new sha1 prefix, but until then...
1953 */
1954 for (patch = list; patch; patch = patch->next) {
1955 const unsigned char *sha1_ptr;
1956 unsigned char sha1[20];
1957 const char *name;
1958
1959 name = patch->old_name ? patch->old_name : patch->new_name;
1960 if (patch->is_new)
1961 sha1_ptr = null_sha1;
1962 else if (get_sha1(patch->old_sha1_prefix, sha1))
1963 die("sha1 information is lacking or useless (%s).",
1964 name);
1965 else
1966 sha1_ptr = sha1;
22943f1a
JH
1967
1968 printf("%06o %s ",patch->old_mode, sha1_to_hex(sha1_ptr));
1969 if (line_termination && quote_c_style(name, NULL, NULL, 0))
1970 quote_c_style(name, NULL, stdout, 0);
1971 else
1972 fputs(name, stdout);
1973 putchar(line_termination);
2cf67f1e
JH
1974 }
1975}
1976
a577284a
LT
1977static void stat_patch_list(struct patch *patch)
1978{
1979 int files, adds, dels;
1980
1981 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
1982 files++;
1983 adds += patch->lines_added;
1984 dels += patch->lines_deleted;
1985 show_stats(patch);
1986 }
1987
1988 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
3f40315a
LT
1989}
1990
7d8b7c21
JH
1991static void numstat_patch_list(struct patch *patch)
1992{
1993 for ( ; patch; patch = patch->next) {
1994 const char *name;
49e3343c 1995 name = patch->new_name ? patch->new_name : patch->old_name;
7d8b7c21
JH
1996 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
1997 if (line_termination && quote_c_style(name, NULL, NULL, 0))
1998 quote_c_style(name, NULL, stdout, 0);
1999 else
2000 fputs(name, stdout);
2001 putchar('\n');
2002 }
2003}
2004
96c912a4
JH
2005static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
2006{
2007 if (mode)
2008 printf(" %s mode %06o %s\n", newdelete, mode, name);
2009 else
2010 printf(" %s %s\n", newdelete, name);
2011}
2012
2013static void show_mode_change(struct patch *p, int show_name)
2014{
2015 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
2016 if (show_name)
2017 printf(" mode change %06o => %06o %s\n",
2018 p->old_mode, p->new_mode, p->new_name);
2019 else
2020 printf(" mode change %06o => %06o\n",
2021 p->old_mode, p->new_mode);
2022 }
2023}
2024
2025static void show_rename_copy(struct patch *p)
2026{
2027 const char *renamecopy = p->is_rename ? "rename" : "copy";
2028 const char *old, *new;
2029
2030 /* Find common prefix */
2031 old = p->old_name;
2032 new = p->new_name;
2033 while (1) {
2034 const char *slash_old, *slash_new;
2035 slash_old = strchr(old, '/');
2036 slash_new = strchr(new, '/');
2037 if (!slash_old ||
2038 !slash_new ||
2039 slash_old - old != slash_new - new ||
2040 memcmp(old, new, slash_new - new))
2041 break;
2042 old = slash_old + 1;
2043 new = slash_new + 1;
2044 }
2045 /* p->old_name thru old is the common prefix, and old and new
2046 * through the end of names are renames
2047 */
2048 if (old != p->old_name)
2049 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
e30e814d 2050 (int)(old - p->old_name), p->old_name,
96c912a4
JH
2051 old, new, p->score);
2052 else
2053 printf(" %s %s => %s (%d%%)\n", renamecopy,
2054 p->old_name, p->new_name, p->score);
2055 show_mode_change(p, 0);
2056}
2057
2058static void summary_patch_list(struct patch *patch)
2059{
2060 struct patch *p;
2061
2062 for (p = patch; p; p = p->next) {
2063 if (p->is_new)
2064 show_file_mode_name("create", p->new_mode, p->new_name);
2065 else if (p->is_delete)
2066 show_file_mode_name("delete", p->old_mode, p->old_name);
2067 else {
2068 if (p->is_rename || p->is_copy)
2069 show_rename_copy(p);
2070 else {
2071 if (p->score) {
2072 printf(" rewrite %s (%d%%)\n",
2073 p->new_name, p->score);
2074 show_mode_change(p, 0);
2075 }
2076 else
2077 show_mode_change(p, 1);
2078 }
2079 }
2080 }
2081}
2082
3f40315a
LT
2083static void patch_stats(struct patch *patch)
2084{
2085 int lines = patch->lines_added + patch->lines_deleted;
2086
2087 if (lines > max_change)
2088 max_change = lines;
2089 if (patch->old_name) {
22943f1a
JH
2090 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
2091 if (!len)
2092 len = strlen(patch->old_name);
3f40315a
LT
2093 if (len > max_len)
2094 max_len = len;
2095 }
2096 if (patch->new_name) {
22943f1a
JH
2097 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
2098 if (!len)
2099 len = strlen(patch->new_name);
3f40315a
LT
2100 if (len > max_len)
2101 max_len = len;
2102 }
19c58fb8
LT
2103}
2104
5aa7d94c
LT
2105static void remove_file(struct patch *patch)
2106{
2107 if (write_index) {
2108 if (remove_file_from_cache(patch->old_name) < 0)
2109 die("unable to remove %s from index", patch->old_name);
03ac6e64 2110 cache_tree_invalidate_path(active_cache_tree, patch->old_name);
5aa7d94c 2111 }
04e4888e
JH
2112 if (!cached)
2113 unlink(patch->old_name);
5aa7d94c
LT
2114}
2115
2116static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
2117{
2118 struct stat st;
2119 struct cache_entry *ce;
2120 int namelen = strlen(path);
2121 unsigned ce_size = cache_entry_size(namelen);
2122
2123 if (!write_index)
2124 return;
2125
90321c10 2126 ce = xcalloc(1, ce_size);
5aa7d94c
LT
2127 memcpy(ce->name, path, namelen);
2128 ce->ce_mode = create_ce_mode(mode);
2129 ce->ce_flags = htons(namelen);
04e4888e
JH
2130 if (!cached) {
2131 if (lstat(path, &st) < 0)
2132 die("unable to stat newly created file %s", path);
2133 fill_stat_cache_info(ce, &st);
2134 }
8e440259 2135 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
5aa7d94c
LT
2136 die("unable to create backing store for newly created file %s", path);
2137 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
2138 die("unable to add cache entry for %s", path);
2139}
2140
1b668341
LT
2141static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
2142{
2143 int fd;
2144
2145 if (S_ISLNK(mode))
2c71810b
JH
2146 /* Although buf:size is counted string, it also is NUL
2147 * terminated.
2148 */
1b668341 2149 return symlink(buf, path);
781411ed 2150 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
1b668341
LT
2151 if (fd < 0)
2152 return -1;
2153 while (size) {
1c15afb9
JH
2154 int written = xwrite(fd, buf, size);
2155 if (written < 0)
1b668341 2156 die("writing file %s: %s", path, strerror(errno));
1b668341
LT
2157 if (!written)
2158 die("out of space writing file %s", path);
2159 buf += written;
2160 size -= written;
2161 }
2162 if (close(fd) < 0)
2163 die("closing file %s: %s", path, strerror(errno));
2164 return 0;
2165}
2166
5c8af185
LT
2167/*
2168 * We optimistically assume that the directories exist,
2169 * which is true 99% of the time anyway. If they don't,
2170 * we create them and try again.
2171 */
8361e1d4 2172static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
5c8af185 2173{
04e4888e
JH
2174 if (cached)
2175 return;
1b668341
LT
2176 if (!try_create_file(path, mode, buf, size))
2177 return;
5c8af185 2178
1b668341 2179 if (errno == ENOENT) {
8361e1d4
JR
2180 if (safe_create_leading_directories(path))
2181 return;
1b668341
LT
2182 if (!try_create_file(path, mode, buf, size))
2183 return;
5c8af185 2184 }
5c8af185 2185
56ac168f 2186 if (errno == EEXIST || errno == EACCES) {
c28c571c
JH
2187 /* We may be trying to create a file where a directory
2188 * used to be.
2189 */
2190 struct stat st;
2191 errno = 0;
2192 if (!lstat(path, &st) && S_ISDIR(st.st_mode) && !rmdir(path))
2193 errno = EEXIST;
2194 }
2195
1b668341
LT
2196 if (errno == EEXIST) {
2197 unsigned int nr = getpid();
5c8af185 2198
1b668341
LT
2199 for (;;) {
2200 const char *newpath;
2201 newpath = mkpath("%s~%u", path, nr);
2202 if (!try_create_file(newpath, mode, buf, size)) {
2203 if (!rename(newpath, path))
2204 return;
2205 unlink(newpath);
2206 break;
2207 }
2208 if (errno != EEXIST)
2209 break;
d9e08be9
AR
2210 ++nr;
2211 }
5c8af185 2212 }
1b668341 2213 die("unable to write file %s mode %o", path, mode);
5c8af185
LT
2214}
2215
5aa7d94c
LT
2216static void create_file(struct patch *patch)
2217{
8361e1d4 2218 char *path = patch->new_name;
5aa7d94c
LT
2219 unsigned mode = patch->new_mode;
2220 unsigned long size = patch->resultsize;
2221 char *buf = patch->result;
2222
2223 if (!mode)
2224 mode = S_IFREG | 0644;
03ac6e64 2225 create_one_file(path, mode, buf, size);
1b668341 2226 add_index_file(path, mode, buf, size);
03ac6e64 2227 cache_tree_invalidate_path(active_cache_tree, path);
5aa7d94c
LT
2228}
2229
eed46644
JH
2230/* phase zero is to remove, phase one is to create */
2231static void write_out_one_result(struct patch *patch, int phase)
5aa7d94c
LT
2232{
2233 if (patch->is_delete > 0) {
eed46644
JH
2234 if (phase == 0)
2235 remove_file(patch);
5aa7d94c
LT
2236 return;
2237 }
2238 if (patch->is_new > 0 || patch->is_copy) {
eed46644
JH
2239 if (phase == 1)
2240 create_file(patch);
5aa7d94c
LT
2241 return;
2242 }
2243 /*
2244 * Rename or modification boils down to the same
2245 * thing: remove the old, write the new
2246 */
eed46644
JH
2247 if (phase == 0)
2248 remove_file(patch);
2249 if (phase == 1)
57dc397c 2250 create_file(patch);
5aa7d94c
LT
2251}
2252
57dc397c
JH
2253static int write_out_one_reject(struct patch *patch)
2254{
82e2765f
JH
2255 FILE *rej;
2256 char namebuf[PATH_MAX];
57dc397c 2257 struct fragment *frag;
82e2765f 2258 int cnt = 0;
57dc397c 2259
82e2765f 2260 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
57dc397c
JH
2261 if (!frag->rejected)
2262 continue;
82e2765f
JH
2263 cnt++;
2264 }
2265
a2bf404e
JH
2266 if (!cnt) {
2267 if (apply_verbosely)
2268 say_patch_name(stderr,
2269 "Applied patch ", patch, " cleanly.\n");
82e2765f 2270 return 0;
a2bf404e 2271 }
82e2765f
JH
2272
2273 /* This should not happen, because a removal patch that leaves
2274 * contents are marked "rejected" at the patch level.
2275 */
2276 if (!patch->new_name)
2277 die("internal error");
2278
a2bf404e
JH
2279 /* Say this even without --verbose */
2280 say_patch_name(stderr, "Applying patch ", patch, " with");
2281 fprintf(stderr, " %d rejects...\n", cnt);
2282
82e2765f
JH
2283 cnt = strlen(patch->new_name);
2284 if (ARRAY_SIZE(namebuf) <= cnt + 5) {
2285 cnt = ARRAY_SIZE(namebuf) - 5;
2286 fprintf(stderr,
2287 "warning: truncating .rej filename to %.*s.rej",
2288 cnt - 1, patch->new_name);
2289 }
2290 memcpy(namebuf, patch->new_name, cnt);
2291 memcpy(namebuf + cnt, ".rej", 5);
2292
2293 rej = fopen(namebuf, "w");
2294 if (!rej)
2295 return error("cannot open %s: %s", namebuf, strerror(errno));
2296
2297 /* Normal git tools never deal with .rej, so do not pretend
2298 * this is a git patch by saying --git nor give extended
2299 * headers. While at it, maybe please "kompare" that wants
2300 * the trailing TAB and some garbage at the end of line ;-).
2301 */
2302 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
2303 patch->new_name, patch->new_name);
0e9ee323 2304 for (cnt = 1, frag = patch->fragments;
82e2765f
JH
2305 frag;
2306 cnt++, frag = frag->next) {
2307 if (!frag->rejected) {
2308 fprintf(stderr, "Hunk #%d applied cleanly.\n", cnt);
2309 continue;
57dc397c 2310 }
82e2765f
JH
2311 fprintf(stderr, "Rejected hunk #%d.\n", cnt);
2312 fprintf(rej, "%.*s", frag->size, frag->patch);
57dc397c 2313 if (frag->patch[frag->size-1] != '\n')
82e2765f 2314 fputc('\n', rej);
57dc397c 2315 }
82e2765f
JH
2316 fclose(rej);
2317 return -1;
5aa7d94c
LT
2318}
2319
57dc397c 2320static int write_out_results(struct patch *list, int skipped_patch)
5aa7d94c 2321{
eed46644 2322 int phase;
57dc397c
JH
2323 int errs = 0;
2324 struct patch *l;
eed46644 2325
d854f783 2326 if (!list && !skipped_patch)
57dc397c 2327 return error("No changes");
f7b79707 2328
eed46644 2329 for (phase = 0; phase < 2; phase++) {
57dc397c 2330 l = list;
eed46644 2331 while (l) {
57dc397c
JH
2332 if (l->rejected)
2333 errs = 1;
82e2765f 2334 else {
57dc397c 2335 write_out_one_result(l, phase);
82e2765f 2336 if (phase == 1 && write_out_one_reject(l))
57dc397c
JH
2337 errs = 1;
2338 }
eed46644
JH
2339 l = l->next;
2340 }
5aa7d94c 2341 }
57dc397c 2342 return errs;
5aa7d94c
LT
2343}
2344
021b6e45 2345static struct lock_file lock_file;
5aa7d94c 2346
d854f783
JH
2347static struct excludes {
2348 struct excludes *next;
2349 const char *path;
2350} *excludes;
2351
2352static int use_patch(struct patch *p)
2353{
c7c81b3a 2354 const char *pathname = p->new_name ? p->new_name : p->old_name;
d854f783
JH
2355 struct excludes *x = excludes;
2356 while (x) {
2357 if (fnmatch(x->path, pathname, 0) == 0)
2358 return 0;
2359 x = x->next;
2360 }
edf2e370
JH
2361 if (0 < prefix_length) {
2362 int pathlen = strlen(pathname);
2363 if (pathlen <= prefix_length ||
2364 memcmp(prefix, pathname, prefix_length))
2365 return 0;
2366 }
d854f783
JH
2367 return 1;
2368}
2369
f686d030 2370static int apply_patch(int fd, const char *filename, int inaccurate_eof)
c1bb9350
LT
2371{
2372 unsigned long offset, size;
2373 char *buffer = read_patch_file(fd, &size);
19c58fb8 2374 struct patch *list = NULL, **listp = &list;
d854f783 2375 int skipped_patch = 0;
c1bb9350 2376
b5767dd6 2377 patch_input_file = filename;
c1bb9350
LT
2378 if (!buffer)
2379 return -1;
2380 offset = 0;
2381 while (size > 0) {
19c58fb8
LT
2382 struct patch *patch;
2383 int nr;
2384
90321c10 2385 patch = xcalloc(1, sizeof(*patch));
3eaa38da 2386 patch->inaccurate_eof = inaccurate_eof;
19c58fb8 2387 nr = parse_chunk(buffer + offset, size, patch);
c1bb9350
LT
2388 if (nr < 0)
2389 break;
f686d030 2390 if (apply_in_reverse)
e5a94313 2391 reverse_patches(patch);
d854f783
JH
2392 if (use_patch(patch)) {
2393 patch_stats(patch);
2394 *listp = patch;
2395 listp = &patch->next;
2396 } else {
2397 /* perhaps free it a bit better? */
2398 free(patch);
2399 skipped_patch++;
2400 }
c1bb9350
LT
2401 offset += nr;
2402 size -= nr;
2403 }
19c58fb8 2404
b5767dd6
JH
2405 if (whitespace_error && (new_whitespace == error_on_whitespace))
2406 apply = 0;
2407
5aa7d94c 2408 write_index = check_index && apply;
40aaae88 2409 if (write_index && newfd < 0)
021b6e45 2410 newfd = hold_lock_file_for_update(&lock_file,
40aaae88 2411 get_index_file(), 1);
5aa7d94c
LT
2412 if (check_index) {
2413 if (read_cache() < 0)
2414 die("unable to read index file");
2415 }
2416
57dc397c
JH
2417 if ((check || apply) &&
2418 check_patch_list(list) < 0 &&
2419 !apply_with_reject)
a577284a
LT
2420 exit(1);
2421
57dc397c
JH
2422 if (apply && write_out_results(list, skipped_patch))
2423 exit(1);
5aa7d94c 2424
2cf67f1e
JH
2425 if (show_index_info)
2426 show_index_list(list);
2427
a577284a
LT
2428 if (diffstat)
2429 stat_patch_list(list);
19c58fb8 2430
7d8b7c21
JH
2431 if (numstat)
2432 numstat_patch_list(list);
2433
96c912a4
JH
2434 if (summary)
2435 summary_patch_list(list);
2436
c1bb9350
LT
2437 free(buffer);
2438 return 0;
2439}
2440
2ae1c53b
JH
2441static int git_apply_config(const char *var, const char *value)
2442{
2443 if (!strcmp(var, "apply.whitespace")) {
9befac47 2444 apply_default_whitespace = xstrdup(value);
2ae1c53b
JH
2445 return 0;
2446 }
2447 return git_default_config(var, value);
2448}
2449
2450
a633fca0 2451int cmd_apply(int argc, const char **argv, const char *prefix)
c1bb9350
LT
2452{
2453 int i;
4dfdbe10 2454 int read_stdin = 1;
3eaa38da 2455 int inaccurate_eof = 0;
57dc397c 2456 int errs = 0;
3eaa38da 2457
2ae1c53b 2458 const char *whitespace_option = NULL;
c1bb9350 2459
c1bb9350
LT
2460 for (i = 1; i < argc; i++) {
2461 const char *arg = argv[i];
47495887 2462 char *end;
c1bb9350
LT
2463 int fd;
2464
2465 if (!strcmp(arg, "-")) {
57dc397c 2466 errs |= apply_patch(0, "<stdin>", inaccurate_eof);
4dfdbe10 2467 read_stdin = 0;
c1bb9350
LT
2468 continue;
2469 }
d854f783
JH
2470 if (!strncmp(arg, "--exclude=", 10)) {
2471 struct excludes *x = xmalloc(sizeof(*x));
2472 x->path = arg + 10;
2473 x->next = excludes;
2474 excludes = x;
2475 continue;
2476 }
e36f8b60
DB
2477 if (!strncmp(arg, "-p", 2)) {
2478 p_value = atoi(arg + 2);
2479 continue;
2480 }
cb93c193
JH
2481 if (!strcmp(arg, "--no-add")) {
2482 no_add = 1;
2483 continue;
2484 }
fab2c257 2485 if (!strcmp(arg, "--stat")) {
a577284a 2486 apply = 0;
fab2c257
LT
2487 diffstat = 1;
2488 continue;
2489 }
0660626c
JH
2490 if (!strcmp(arg, "--allow-binary-replacement") ||
2491 !strcmp(arg, "--binary")) {
2b6eef94 2492 continue; /* now no-op */
011f4274 2493 }
7d8b7c21
JH
2494 if (!strcmp(arg, "--numstat")) {
2495 apply = 0;
2496 numstat = 1;
2497 continue;
2498 }
96c912a4
JH
2499 if (!strcmp(arg, "--summary")) {
2500 apply = 0;
2501 summary = 1;
2502 continue;
2503 }
a577284a
LT
2504 if (!strcmp(arg, "--check")) {
2505 apply = 0;
2506 check = 1;
2507 continue;
2508 }
3cca928d
LT
2509 if (!strcmp(arg, "--index")) {
2510 check_index = 1;
2511 continue;
2512 }
04e4888e
JH
2513 if (!strcmp(arg, "--cached")) {
2514 check_index = 1;
2515 cached = 1;
2516 continue;
2517 }
aefa4a5b
LT
2518 if (!strcmp(arg, "--apply")) {
2519 apply = 1;
2520 continue;
2521 }
22943f1a 2522 if (!strcmp(arg, "--index-info")) {
2cf67f1e
JH
2523 apply = 0;
2524 show_index_info = 1;
2525 continue;
2526 }
22943f1a
JH
2527 if (!strcmp(arg, "-z")) {
2528 line_termination = 0;
2529 continue;
2530 }
47495887
EB
2531 if (!strncmp(arg, "-C", 2)) {
2532 p_context = strtoul(arg + 2, &end, 0);
2533 if (*end != '\0')
2534 die("unrecognized context count '%s'", arg + 2);
2535 continue;
2536 }
19bfcd5a 2537 if (!strncmp(arg, "--whitespace=", 13)) {
2ae1c53b
JH
2538 whitespace_option = arg + 13;
2539 parse_whitespace_option(arg + 13);
2540 continue;
19bfcd5a 2541 }
e5a94313 2542 if (!strcmp(arg, "-R") || !strcmp(arg, "--reverse")) {
f686d030 2543 apply_in_reverse = 1;
e5a94313
JS
2544 continue;
2545 }
57dc397c 2546 if (!strcmp(arg, "--reject")) {
8938045a 2547 apply = apply_with_reject = apply_verbosely = 1;
57dc397c
JH
2548 continue;
2549 }
a2bf404e
JH
2550 if (!strcmp(arg, "--verbose")) {
2551 apply_verbosely = 1;
2552 continue;
2553 }
3eaa38da
JS
2554 if (!strcmp(arg, "--inaccurate-eof")) {
2555 inaccurate_eof = 1;
2556 continue;
2557 }
edf2e370
JH
2558
2559 if (check_index && prefix_length < 0) {
2560 prefix = setup_git_directory();
2561 prefix_length = prefix ? strlen(prefix) : 0;
2ae1c53b
JH
2562 git_config(git_apply_config);
2563 if (!whitespace_option && apply_default_whitespace)
2564 parse_whitespace_option(apply_default_whitespace);
edf2e370
JH
2565 }
2566 if (0 < prefix_length)
2567 arg = prefix_filename(prefix, prefix_length, arg);
2568
c1bb9350
LT
2569 fd = open(arg, O_RDONLY);
2570 if (fd < 0)
2571 usage(apply_usage);
4dfdbe10 2572 read_stdin = 0;
f21d6726 2573 set_default_whitespace_mode(whitespace_option);
57dc397c 2574 errs |= apply_patch(fd, arg, inaccurate_eof);
c1bb9350
LT
2575 close(fd);
2576 }
f21d6726 2577 set_default_whitespace_mode(whitespace_option);
4dfdbe10 2578 if (read_stdin)
57dc397c 2579 errs |= apply_patch(0, "<stdin>", inaccurate_eof);
fc96b7c9
JH
2580 if (whitespace_error) {
2581 if (squelch_whitespace_errors &&
2582 squelch_whitespace_errors < whitespace_error) {
2583 int squelched =
2584 whitespace_error - squelch_whitespace_errors;
57dc397c
JH
2585 fprintf(stderr, "warning: squelched %d "
2586 "whitespace error%s\n",
fc96b7c9
JH
2587 squelched,
2588 squelched == 1 ? "" : "s");
2589 }
2590 if (new_whitespace == error_on_whitespace)
2591 die("%d line%s add%s trailing whitespaces.",
2592 whitespace_error,
2593 whitespace_error == 1 ? "" : "s",
2594 whitespace_error == 1 ? "s" : "");
2595 if (applied_after_stripping)
2596 fprintf(stderr, "warning: %d line%s applied after"
2597 " stripping trailing whitespaces.\n",
2598 applied_after_stripping,
2599 applied_after_stripping == 1 ? "" : "s");
2600 else if (whitespace_error)
2601 fprintf(stderr, "warning: %d line%s add%s trailing"
2602 " whitespaces.\n",
2603 whitespace_error,
2604 whitespace_error == 1 ? "" : "s",
2605 whitespace_error == 1 ? "s" : "");
2606 }
dbd0f7d3
EW
2607
2608 if (write_index) {
2609 if (write_cache(newfd, active_cache, active_nr) ||
6244b249 2610 close(newfd) || commit_lock_file(&lock_file))
021b6e45 2611 die("Unable to write new index file");
dbd0f7d3
EW
2612 }
2613
57dc397c 2614 return !!errs;
c1bb9350 2615}