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