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