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