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