]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/apply.c
Merge branch 'lt/default-abbrev' into maint
[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"
c455c87c 15#include "string-list.h"
175a4948 16#include "dir.h"
f26c4940 17#include "parse-options.h"
c1bb9350 18
a9486b02
PR
19/*
20 * --check turns on checking that the working tree matches the
21 * files that are being modified, but doesn't apply the patch
22 * --stat does just a diffstat, and doesn't actually apply
23 * --numstat does numeric diffstat, and doesn't actually apply
24 * --index-info shows the old and new index info for paths if available.
25 * --index updates the cache as well.
26 * --cached updates only the cache without ever touching the working tree.
27 */
edf2e370
JH
28static const char *prefix;
29static int prefix_length = -1;
dbd0f7d3 30static int newfd = -1;
edf2e370 31
4be60962 32static int unidiff_zero;
e36f8b60 33static int p_value = 1;
3e8a5db9 34static int p_value_known;
96f1e58f 35static int check_index;
7da3bf37 36static int update_index;
96f1e58f
DR
37static int cached;
38static int diffstat;
39static int numstat;
40static int summary;
41static int check;
a577284a 42static int apply = 1;
96f1e58f 43static int apply_in_reverse;
57dc397c 44static int apply_with_reject;
a2bf404e 45static int apply_verbosely;
96f1e58f 46static int no_add;
7a988699 47static const char *fake_ancestor;
22943f1a 48static int line_termination = '\n';
f26c4940
MV
49static unsigned int p_context = UINT_MAX;
50static const char * const apply_usage[] = {
51 "git apply [options] [<patch>...]",
52 NULL
53};
c1bb9350 54
81bf96bb
JH
55static enum ws_error_action {
56 nowarn_ws_error,
57 warn_on_ws_error,
58 die_on_ws_error,
4b05548f 59 correct_ws_error
81bf96bb 60} ws_error_action = warn_on_ws_error;
96f1e58f 61static int whitespace_error;
fc96b7c9 62static int squelch_whitespace_errors = 5;
c94bf41c 63static int applied_after_fixing_ws;
86c91f91
GB
64
65static enum ws_ignore {
66 ignore_ws_none,
4b05548f 67 ignore_ws_change
86c91f91
GB
68} ws_ignore_action = ignore_ws_none;
69
70
96f1e58f 71static const char *patch_input_file;
c4730f35
JS
72static const char *root;
73static int root_len;
f26c4940
MV
74static int read_stdin = 1;
75static int options;
19bfcd5a 76
2ae1c53b
JH
77static void parse_whitespace_option(const char *option)
78{
79 if (!option) {
81bf96bb 80 ws_error_action = warn_on_ws_error;
2ae1c53b
JH
81 return;
82 }
83 if (!strcmp(option, "warn")) {
81bf96bb 84 ws_error_action = warn_on_ws_error;
2ae1c53b
JH
85 return;
86 }
621603b7 87 if (!strcmp(option, "nowarn")) {
81bf96bb 88 ws_error_action = nowarn_ws_error;
621603b7
JH
89 return;
90 }
2ae1c53b 91 if (!strcmp(option, "error")) {
81bf96bb 92 ws_error_action = die_on_ws_error;
2ae1c53b
JH
93 return;
94 }
95 if (!strcmp(option, "error-all")) {
81bf96bb 96 ws_error_action = die_on_ws_error;
2ae1c53b
JH
97 squelch_whitespace_errors = 0;
98 return;
99 }
81bf96bb
JH
100 if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
101 ws_error_action = correct_ws_error;
2ae1c53b
JH
102 return;
103 }
104 die("unrecognized whitespace option '%s'", option);
105}
106
86c91f91
GB
107static void parse_ignorewhitespace_option(const char *option)
108{
109 if (!option || !strcmp(option, "no") ||
110 !strcmp(option, "false") || !strcmp(option, "never") ||
111 !strcmp(option, "none")) {
112 ws_ignore_action = ignore_ws_none;
113 return;
114 }
115 if (!strcmp(option, "change")) {
116 ws_ignore_action = ignore_ws_change;
117 return;
118 }
119 die("unrecognized whitespace ignore option '%s'", option);
120}
121
f21d6726
JH
122static void set_default_whitespace_mode(const char *whitespace_option)
123{
81bf96bb
JH
124 if (!whitespace_option && !apply_default_whitespace)
125 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error);
f21d6726
JH
126}
127
3f40315a
LT
128/*
129 * For "diff-stat" like behaviour, we keep track of the biggest change
130 * we've seen, and the longest filename. That allows us to do simple
131 * scaling.
132 */
133static int max_change, max_len;
134
a4acb0eb
LT
135/*
136 * Various "current state", notably line numbers and what
137 * file (and how) we're patching right now.. The "is_xxxx"
138 * things are flags, where -1 means "don't know yet".
139 */
46979f56 140static int linenr = 1;
19c58fb8 141
3cd4f5e8
JH
142/*
143 * This represents one "hunk" from a patch, starting with
144 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
145 * patch text is pointed at by patch, and its byte length
146 * is stored in size. leading and trailing are the number
147 * of context lines.
148 */
19c58fb8 149struct fragment {
47495887 150 unsigned long leading, trailing;
19c58fb8
LT
151 unsigned long oldpos, oldlines;
152 unsigned long newpos, newlines;
153 const char *patch;
154 int size;
57dc397c 155 int rejected;
77b15bbd 156 int linenr;
19c58fb8
LT
157 struct fragment *next;
158};
159
3cd4f5e8
JH
160/*
161 * When dealing with a binary patch, we reuse "leading" field
162 * to store the type of the binary hunk, either deflated "delta"
163 * or deflated "literal".
164 */
165#define binary_patch_method leading
166#define BINARY_DELTA_DEFLATED 1
167#define BINARY_LITERAL_DEFLATED 2
168
81bf96bb
JH
169/*
170 * This represents a "patch" to a file, both metainfo changes
171 * such as creation/deletion, filemode and content changes represented
172 * as a series of fragments.
173 */
19c58fb8 174struct patch {
5041aa70 175 char *new_name, *old_name, *def_name;
19c58fb8 176 unsigned int old_mode, new_mode;
3dad11bf 177 int is_new, is_delete; /* -1 = unknown, 0 = false, 1 = true */
57dc397c 178 int rejected;
cf1b7869 179 unsigned ws_rule;
0660626c 180 unsigned long deflate_origlen;
3f40315a 181 int lines_added, lines_deleted;
96c912a4 182 int score;
9987d7c5 183 unsigned int is_toplevel_relative:1;
3dad11bf
RS
184 unsigned int inaccurate_eof:1;
185 unsigned int is_binary:1;
186 unsigned int is_copy:1;
187 unsigned int is_rename:1;
c14b9d1e 188 unsigned int recount:1;
19c58fb8 189 struct fragment *fragments;
5aa7d94c 190 char *result;
c32f749f 191 size_t resultsize;
2cf67f1e
JH
192 char old_sha1_prefix[41];
193 char new_sha1_prefix[41];
19c58fb8
LT
194 struct patch *next;
195};
46979f56 196
b94f2eda
JH
197/*
198 * A line in a file, len-bytes long (includes the terminating LF,
199 * except for an incomplete line at the end if the file ends with
200 * one), and its contents hashes to 'hash'.
201 */
202struct line {
203 size_t len;
204 unsigned hash : 24;
205 unsigned flag : 8;
c330fdd4 206#define LINE_COMMON 1
9d158601 207#define LINE_PATCHED 2
b94f2eda
JH
208};
209
210/*
211 * This represents a "file", which is an array of "lines".
212 */
213struct image {
214 char *buf;
215 size_t len;
216 size_t nr;
c330fdd4 217 size_t alloc;
b94f2eda
JH
218 struct line *line_allocated;
219 struct line *line;
220};
221
7a07841c
DZ
222/*
223 * Records filenames that have been touched, in order to handle
224 * the case where more than one patches touch the same file.
225 */
226
c455c87c 227static struct string_list fn_table;
7a07841c 228
b94f2eda
JH
229static uint32_t hash_line(const char *cp, size_t len)
230{
231 size_t i;
232 uint32_t h;
233 for (i = 0, h = 0; i < len; i++) {
234 if (!isspace(cp[i])) {
235 h = h * 3 + (cp[i] & 0xff);
236 }
237 }
238 return h;
239}
240
86c91f91
GB
241/*
242 * Compare lines s1 of length n1 and s2 of length n2, ignoring
243 * whitespace difference. Returns 1 if they match, 0 otherwise
244 */
245static int fuzzy_matchlines(const char *s1, size_t n1,
246 const char *s2, size_t n2)
247{
248 const char *last1 = s1 + n1 - 1;
249 const char *last2 = s2 + n2 - 1;
250 int result = 0;
251
252 if (n1 < 0 || n2 < 0)
253 return 0;
254
255 /* ignore line endings */
256 while ((*last1 == '\r') || (*last1 == '\n'))
257 last1--;
258 while ((*last2 == '\r') || (*last2 == '\n'))
259 last2--;
260
261 /* skip leading whitespace */
262 while (isspace(*s1) && (s1 <= last1))
263 s1++;
264 while (isspace(*s2) && (s2 <= last2))
265 s2++;
266 /* early return if both lines are empty */
267 if ((s1 > last1) && (s2 > last2))
268 return 1;
269 while (!result) {
270 result = *s1++ - *s2++;
271 /*
272 * Skip whitespace inside. We check for whitespace on
273 * both buffers because we don't want "a b" to match
274 * "ab"
275 */
276 if (isspace(*s1) && isspace(*s2)) {
277 while (isspace(*s1) && s1 <= last1)
278 s1++;
279 while (isspace(*s2) && s2 <= last2)
280 s2++;
281 }
282 /*
283 * If we reached the end on one side only,
284 * lines don't match
285 */
286 if (
287 ((s2 > last2) && (s1 <= last1)) ||
288 ((s1 > last1) && (s2 <= last2)))
289 return 0;
290 if ((s1 > last1) && (s2 > last2))
291 break;
292 }
293
294 return !result;
295}
296
c330fdd4
JH
297static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
298{
299 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
300 img->line_allocated[img->nr].len = len;
301 img->line_allocated[img->nr].hash = hash_line(bol, len);
302 img->line_allocated[img->nr].flag = flag;
303 img->nr++;
304}
305
b94f2eda
JH
306static void prepare_image(struct image *image, char *buf, size_t len,
307 int prepare_linetable)
308{
309 const char *cp, *ep;
b94f2eda 310
c330fdd4 311 memset(image, 0, sizeof(*image));
b94f2eda
JH
312 image->buf = buf;
313 image->len = len;
314
c330fdd4 315 if (!prepare_linetable)
b94f2eda 316 return;
b94f2eda
JH
317
318 ep = image->buf + image->len;
b94f2eda 319 cp = image->buf;
b94f2eda
JH
320 while (cp < ep) {
321 const char *next;
322 for (next = cp; next < ep && *next != '\n'; next++)
323 ;
324 if (next < ep)
325 next++;
c330fdd4 326 add_line_info(image, cp, next - cp, 0);
b94f2eda 327 cp = next;
b94f2eda 328 }
c330fdd4 329 image->line = image->line_allocated;
b94f2eda
JH
330}
331
332static void clear_image(struct image *image)
333{
334 free(image->buf);
335 image->buf = NULL;
336 image->len = 0;
337}
338
81bf96bb
JH
339static void say_patch_name(FILE *output, const char *pre,
340 struct patch *patch, const char *post)
a2bf404e
JH
341{
342 fputs(pre, output);
343 if (patch->old_name && patch->new_name &&
344 strcmp(patch->old_name, patch->new_name)) {
663af342 345 quote_c_style(patch->old_name, NULL, output, 0);
a2bf404e 346 fputs(" => ", output);
663af342
PH
347 quote_c_style(patch->new_name, NULL, output, 0);
348 } else {
a2bf404e
JH
349 const char *n = patch->new_name;
350 if (!n)
351 n = patch->old_name;
663af342 352 quote_c_style(n, NULL, output, 0);
a2bf404e
JH
353 }
354 fputs(post, output);
355}
356
c1bb9350 357#define CHUNKSIZE (8192)
a4acb0eb 358#define SLOP (16)
c1bb9350 359
9a76adeb 360static void read_patch_file(struct strbuf *sb, int fd)
c1bb9350 361{
9a76adeb 362 if (strbuf_read(sb, fd, 0) < 0)
d824cbba 363 die_errno("git apply: failed to read");
a4acb0eb
LT
364
365 /*
366 * Make sure that we have some slop in the buffer
367 * so that we can do speculative "memcmp" etc, and
368 * see to it that it is NUL-filled.
369 */
9a76adeb
PH
370 strbuf_grow(sb, SLOP);
371 memset(sb->buf + sb->len, 0, SLOP);
c1bb9350
LT
372}
373
3cca928d 374static unsigned long linelen(const char *buffer, unsigned long size)
c1bb9350
LT
375{
376 unsigned long len = 0;
377 while (size--) {
378 len++;
379 if (*buffer++ == '\n')
380 break;
381 }
382 return len;
383}
384
a4acb0eb
LT
385static int is_dev_null(const char *str)
386{
387 return !memcmp("/dev/null", str, 9) && isspace(str[9]);
388}
389
381ca9a3
LT
390#define TERM_SPACE 1
391#define TERM_TAB 2
9a4a100e
LT
392
393static int name_terminate(const char *name, int namelen, int c, int terminate)
394{
395 if (c == ' ' && !(terminate & TERM_SPACE))
396 return 0;
397 if (c == '\t' && !(terminate & TERM_TAB))
398 return 0;
399
9a4a100e
LT
400 return 1;
401}
402
33eb4dd9
MM
403/* remove double slashes to make --index work with such filenames */
404static char *squash_slash(char *name)
405{
406 int i = 0, j = 0;
407
15862087
AG
408 if (!name)
409 return NULL;
410
33eb4dd9
MM
411 while (name[i]) {
412 if ((name[j++] = name[i++]) == '/')
413 while (name[i] == '/')
414 i++;
415 }
416 name[j] = '\0';
417 return name;
418}
419
bb7306b5 420static char *find_name_gnu(const char *line, char *def, int p_value)
c1bb9350 421{
bb7306b5
JN
422 struct strbuf name = STRBUF_INIT;
423 char *cp;
15862087 424
bb7306b5
JN
425 /*
426 * Proposed "new-style" GNU patch/diff format; see
427 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
428 */
429 if (unquote_c_style(&name, line, NULL)) {
430 strbuf_release(&name);
431 return NULL;
432 }
7fb1011e 433
bb7306b5
JN
434 for (cp = name.buf; p_value; p_value--) {
435 cp = strchr(cp, '/');
436 if (!cp) {
437 strbuf_release(&name);
438 return NULL;
22943f1a 439 }
bb7306b5
JN
440 cp++;
441 }
442
443 /* name can later be freed, so we need
444 * to memmove, not just return cp
445 */
446 strbuf_remove(&name, 0, cp - name.buf);
447 free(def);
448 if (root)
449 strbuf_insert(&name, 0, root, root_len);
450 return squash_slash(strbuf_detach(&name, NULL));
451}
452
2d502e1f 453static size_t sane_tz_len(const char *line, size_t len)
c1bb9350 454{
5a12c886 455 const char *tz, *p;
15862087 456
5a12c886
JN
457 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
458 return 0;
459 tz = line + len - strlen(" +0500");
460
461 if (tz[1] != '+' && tz[1] != '-')
462 return 0;
463
464 for (p = tz + 2; p != line + len; p++)
465 if (!isdigit(*p))
466 return 0;
467
468 return line + len - tz;
469}
470
2d502e1f
JN
471static size_t tz_with_colon_len(const char *line, size_t len)
472{
473 const char *tz, *p;
474
475 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
476 return 0;
477 tz = line + len - strlen(" +08:00");
478
479 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
480 return 0;
481 p = tz + 2;
482 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
483 !isdigit(*p++) || !isdigit(*p++))
484 return 0;
485
486 return line + len - tz;
487}
488
5a12c886
JN
489static size_t date_len(const char *line, size_t len)
490{
491 const char *date, *p;
492
493 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
494 return 0;
495 p = date = line + len - strlen("72-02-05");
496
497 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
498 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
499 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */
500 return 0;
501
502 if (date - line >= strlen("19") &&
503 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */
504 date -= strlen("19");
505
506 return line + len - date;
507}
508
509static size_t short_time_len(const char *line, size_t len)
510{
511 const char *time, *p;
512
513 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
514 return 0;
515 p = time = line + len - strlen(" 07:01:32");
516
517 /* Permit 1-digit hours? */
518 if (*p++ != ' ' ||
519 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
520 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
521 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */
522 return 0;
523
524 return line + len - time;
525}
526
527static size_t fractional_time_len(const char *line, size_t len)
528{
529 const char *p;
530 size_t n;
531
532 /* Expected format: 19:41:17.620000023 */
533 if (!len || !isdigit(line[len - 1]))
534 return 0;
535 p = line + len - 1;
536
537 /* Fractional seconds. */
538 while (p > line && isdigit(*p))
539 p--;
540 if (*p != '.')
541 return 0;
542
543 /* Hours, minutes, and whole seconds. */
544 n = short_time_len(line, p - line);
545 if (!n)
546 return 0;
547
548 return line + len - p + n;
549}
550
551static size_t trailing_spaces_len(const char *line, size_t len)
552{
553 const char *p;
554
555 /* Expected format: ' ' x (1 or more) */
556 if (!len || line[len - 1] != ' ')
557 return 0;
558
559 p = line + len;
560 while (p != line) {
561 p--;
562 if (*p != ' ')
563 return line + len - (p + 1);
22943f1a
JH
564 }
565
5a12c886
JN
566 /* All spaces! */
567 return len;
568}
569
570static size_t diff_timestamp_len(const char *line, size_t len)
571{
572 const char *end = line + len;
573 size_t n;
574
575 /*
576 * Posix: 2010-07-05 19:41:17
577 * GNU: 2010-07-05 19:41:17.620000023 -0500
578 */
579
580 if (!isdigit(end[-1]))
581 return 0;
582
2d502e1f
JN
583 n = sane_tz_len(line, end - line);
584 if (!n)
585 n = tz_with_colon_len(line, end - line);
5a12c886
JN
586 end -= n;
587
588 n = short_time_len(line, end - line);
589 if (!n)
590 n = fractional_time_len(line, end - line);
591 end -= n;
592
593 n = date_len(line, end - line);
594 if (!n) /* No date. Too bad. */
595 return 0;
596 end -= n;
597
598 if (end == line) /* No space before date. */
599 return 0;
600 if (end[-1] == '\t') { /* Success! */
601 end--;
602 return line + len - end;
603 }
604 if (end[-1] != ' ') /* No space before date. */
605 return 0;
606
607 /* Whitespace damage. */
608 end -= trailing_spaces_len(line, end - line);
609 return line + len - end;
610}
611
612static char *find_name_common(const char *line, char *def, int p_value,
613 const char *end, int terminate)
614{
615 int len;
616 const char *start = NULL;
617
bb7306b5
JN
618 if (p_value == 0)
619 start = line;
5a12c886 620 while (line != end) {
a4acb0eb 621 char c = *line;
9a4a100e 622
5a12c886 623 if (!end && isspace(c)) {
9a4a100e
LT
624 if (c == '\n')
625 break;
626 if (name_terminate(start, line-start, c, terminate))
627 break;
628 }
a4acb0eb
LT
629 line++;
630 if (c == '/' && !--p_value)
631 start = line;
632 }
633 if (!start)
33eb4dd9 634 return squash_slash(def);
a4acb0eb
LT
635 len = line - start;
636 if (!len)
33eb4dd9 637 return squash_slash(def);
a4acb0eb
LT
638
639 /*
640 * Generally we prefer the shorter name, especially
641 * if the other one is just a variation of that with
642 * something else tacked on to the end (ie "file.orig"
643 * or "file~").
644 */
645 if (def) {
646 int deflen = strlen(def);
647 if (deflen < len && !strncmp(start, def, deflen))
33eb4dd9 648 return squash_slash(def);
ca032835 649 free(def);
c1bb9350 650 }
a4acb0eb 651
c4730f35
JS
652 if (root) {
653 char *ret = xmalloc(root_len + len + 1);
654 strcpy(ret, root);
655 memcpy(ret + root_len, start, len);
656 ret[root_len + len] = '\0';
33eb4dd9 657 return squash_slash(ret);
c4730f35
JS
658 }
659
33eb4dd9 660 return squash_slash(xmemdupz(start, len));
a4acb0eb
LT
661}
662
5a12c886
JN
663static char *find_name(const char *line, char *def, int p_value, int terminate)
664{
665 if (*line == '"') {
666 char *name = find_name_gnu(line, def, p_value);
667 if (name)
668 return name;
669 }
670
671 return find_name_common(line, def, p_value, NULL, terminate);
672}
673
674static char *find_name_traditional(const char *line, char *def, int p_value)
675{
676 size_t len = strlen(line);
677 size_t date_len;
678
679 if (*line == '"') {
680 char *name = find_name_gnu(line, def, p_value);
681 if (name)
682 return name;
683 }
684
685 len = strchrnul(line, '\n') - line;
686 date_len = diff_timestamp_len(line, len);
687 if (!date_len)
688 return find_name_common(line, def, p_value, NULL, TERM_TAB);
689 len -= date_len;
690
691 return find_name_common(line, def, p_value, line + len, 0);
692}
693
3e8a5db9
JH
694static int count_slashes(const char *cp)
695{
696 int cnt = 0;
697 char ch;
698
699 while ((ch = *cp++))
700 if (ch == '/')
701 cnt++;
702 return cnt;
703}
704
705/*
706 * Given the string after "--- " or "+++ ", guess the appropriate
707 * p_value for the given patch.
708 */
709static int guess_p_value(const char *nameline)
710{
711 char *name, *cp;
712 int val = -1;
713
714 if (is_dev_null(nameline))
715 return -1;
5a12c886 716 name = find_name_traditional(nameline, NULL, 0);
3e8a5db9
JH
717 if (!name)
718 return -1;
719 cp = strchr(name, '/');
720 if (!cp)
721 val = 0;
722 else if (prefix) {
723 /*
724 * Does it begin with "a/$our-prefix" and such? Then this is
725 * very likely to apply to our directory.
726 */
727 if (!strncmp(name, prefix, prefix_length))
728 val = count_slashes(prefix);
729 else {
730 cp++;
731 if (!strncmp(cp, prefix, prefix_length))
732 val = count_slashes(prefix) + 1;
733 }
734 }
735 free(name);
736 return val;
737}
738
c4593faf
JH
739/*
740 * Does the ---/+++ line has the POSIX timestamp after the last HT?
741 * GNU diff puts epoch there to signal a creation/deletion event. Is
742 * this such a timestamp?
743 */
744static int has_epoch_timestamp(const char *nameline)
745{
746 /*
747 * We are only interested in epoch timestamp; any non-zero
748 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
749 * For the same reason, the date must be either 1969-12-31 or
750 * 1970-01-01, and the seconds part must be "00".
751 */
752 const char stamp_regexp[] =
753 "^(1969-12-31|1970-01-01)"
754 " "
755 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
756 " "
a1980c4e
AK
757 "([-+][0-2][0-9]:?[0-5][0-9])\n";
758 const char *timestamp = NULL, *cp, *colon;
c4593faf
JH
759 static regex_t *stamp;
760 regmatch_t m[10];
761 int zoneoffset;
762 int hourminute;
763 int status;
764
765 for (cp = nameline; *cp != '\n'; cp++) {
766 if (*cp == '\t')
767 timestamp = cp + 1;
768 }
769 if (!timestamp)
770 return 0;
771 if (!stamp) {
772 stamp = xmalloc(sizeof(*stamp));
773 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
774 warning("Cannot prepare timestamp regexp %s",
775 stamp_regexp);
776 return 0;
777 }
778 }
779
780 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
781 if (status) {
782 if (status != REG_NOMATCH)
783 warning("regexec returned %d for input: %s",
784 status, timestamp);
785 return 0;
786 }
787
a1980c4e
AK
788 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
789 if (*colon == ':')
790 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
791 else
792 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
c4593faf
JH
793 if (timestamp[m[3].rm_so] == '-')
794 zoneoffset = -zoneoffset;
795
796 /*
797 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
798 * (west of GMT) or 1970-01-01 (east of GMT)
799 */
800 if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) ||
801 (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10)))
802 return 0;
803
804 hourminute = (strtol(timestamp + 11, NULL, 10) * 60 +
805 strtol(timestamp + 14, NULL, 10) -
806 zoneoffset);
807
808 return ((zoneoffset < 0 && hourminute == 1440) ||
809 (0 <= zoneoffset && !hourminute));
810}
811
a4acb0eb 812/*
88f6dbaf 813 * Get the name etc info from the ---/+++ lines of a traditional patch header
a4acb0eb 814 *
9a4a100e
LT
815 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
816 * files, we can happily check the index for a match, but for creating a
817 * new file we should try to match whatever "patch" does. I have no idea.
a4acb0eb 818 */
19c58fb8 819static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
a4acb0eb 820{
a4acb0eb
LT
821 char *name;
822
a9486b02
PR
823 first += 4; /* skip "--- " */
824 second += 4; /* skip "+++ " */
3e8a5db9
JH
825 if (!p_value_known) {
826 int p, q;
827 p = guess_p_value(first);
828 q = guess_p_value(second);
829 if (p < 0) p = q;
830 if (0 <= p && p == q) {
831 p_value = p;
832 p_value_known = 1;
833 }
834 }
a4acb0eb 835 if (is_dev_null(first)) {
19c58fb8
LT
836 patch->is_new = 1;
837 patch->is_delete = 0;
5a12c886 838 name = find_name_traditional(second, NULL, p_value);
19c58fb8 839 patch->new_name = name;
a4acb0eb 840 } else if (is_dev_null(second)) {
19c58fb8
LT
841 patch->is_new = 0;
842 patch->is_delete = 1;
5a12c886 843 name = find_name_traditional(first, NULL, p_value);
19c58fb8 844 patch->old_name = name;
a4acb0eb 845 } else {
5a12c886
JN
846 name = find_name_traditional(first, NULL, p_value);
847 name = find_name_traditional(second, name, p_value);
c4593faf
JH
848 if (has_epoch_timestamp(first)) {
849 patch->is_new = 1;
850 patch->is_delete = 0;
851 patch->new_name = name;
852 } else if (has_epoch_timestamp(second)) {
853 patch->is_new = 0;
854 patch->is_delete = 1;
855 patch->old_name = name;
856 } else {
857 patch->old_name = patch->new_name = name;
858 }
a4acb0eb
LT
859 }
860 if (!name)
861 die("unable to find filename in patch at line %d", linenr);
a4acb0eb
LT
862}
863
19c58fb8 864static int gitdiff_hdrend(const char *line, struct patch *patch)
a4acb0eb
LT
865{
866 return -1;
867}
868
1e3f6b6e
LT
869/*
870 * We're anal about diff header consistency, to make
871 * sure that we don't end up having strange ambiguous
872 * patches floating around.
873 *
874 * As a result, gitdiff_{old|new}name() will check
875 * their names against any previous information, just
876 * to make sure..
877 */
878static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
879{
1e3f6b6e 880 if (!orig_name && !isnull)
79ee194e 881 return find_name(line, NULL, p_value, TERM_TAB);
1e3f6b6e 882
1e3f6b6e 883 if (orig_name) {
22943f1a
JH
884 int len;
885 const char *name;
886 char *another;
1e3f6b6e
LT
887 name = orig_name;
888 len = strlen(name);
889 if (isnull)
7e44c935 890 die("git apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
79ee194e 891 another = find_name(line, NULL, p_value, TERM_TAB);
da915939 892 if (!another || memcmp(another, name, len + 1))
7e44c935 893 die("git apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
22943f1a 894 free(another);
1e3f6b6e
LT
895 return orig_name;
896 }
22943f1a
JH
897 else {
898 /* expect "/dev/null" */
899 if (memcmp("/dev/null", line, 9) || line[9] != '\n')
7e44c935 900 die("git apply: bad git-diff - expected /dev/null on line %d", linenr);
22943f1a
JH
901 return NULL;
902 }
1e3f6b6e
LT
903}
904
19c58fb8 905static int gitdiff_oldname(const char *line, struct patch *patch)
a4acb0eb 906{
19c58fb8 907 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
a4acb0eb
LT
908 return 0;
909}
910
19c58fb8 911static int gitdiff_newname(const char *line, struct patch *patch)
a4acb0eb 912{
19c58fb8 913 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
a4acb0eb
LT
914 return 0;
915}
916
19c58fb8 917static int gitdiff_oldmode(const char *line, struct patch *patch)
a4acb0eb 918{
19c58fb8 919 patch->old_mode = strtoul(line, NULL, 8);
a4acb0eb
LT
920 return 0;
921}
922
19c58fb8 923static int gitdiff_newmode(const char *line, struct patch *patch)
a4acb0eb 924{
19c58fb8 925 patch->new_mode = strtoul(line, NULL, 8);
a4acb0eb
LT
926 return 0;
927}
928
19c58fb8 929static int gitdiff_delete(const char *line, struct patch *patch)
a4acb0eb 930{
19c58fb8 931 patch->is_delete = 1;
5041aa70 932 patch->old_name = patch->def_name;
19c58fb8 933 return gitdiff_oldmode(line, patch);
a4acb0eb
LT
934}
935
19c58fb8 936static int gitdiff_newfile(const char *line, struct patch *patch)
a4acb0eb 937{
19c58fb8 938 patch->is_new = 1;
5041aa70 939 patch->new_name = patch->def_name;
19c58fb8 940 return gitdiff_newmode(line, patch);
a4acb0eb
LT
941}
942
19c58fb8 943static int gitdiff_copysrc(const char *line, struct patch *patch)
a4acb0eb 944{
19c58fb8 945 patch->is_copy = 1;
cefd43b7 946 patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
a4acb0eb
LT
947 return 0;
948}
949
19c58fb8 950static int gitdiff_copydst(const char *line, struct patch *patch)
a4acb0eb 951{
19c58fb8 952 patch->is_copy = 1;
cefd43b7 953 patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
a4acb0eb
LT
954 return 0;
955}
956
19c58fb8 957static int gitdiff_renamesrc(const char *line, struct patch *patch)
a4acb0eb 958{
19c58fb8 959 patch->is_rename = 1;
cefd43b7 960 patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
a4acb0eb
LT
961 return 0;
962}
963
19c58fb8 964static int gitdiff_renamedst(const char *line, struct patch *patch)
a4acb0eb 965{
19c58fb8 966 patch->is_rename = 1;
cefd43b7 967 patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
a4acb0eb
LT
968 return 0;
969}
970
19c58fb8 971static int gitdiff_similarity(const char *line, struct patch *patch)
a4acb0eb 972{
96c912a4
JH
973 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
974 patch->score = 0;
a4acb0eb 975 return 0;
c1bb9350
LT
976}
977
70aadac0
JH
978static int gitdiff_dissimilarity(const char *line, struct patch *patch)
979{
96c912a4
JH
980 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
981 patch->score = 0;
70aadac0
JH
982 return 0;
983}
984
2cf67f1e
JH
985static int gitdiff_index(const char *line, struct patch *patch)
986{
81bf96bb
JH
987 /*
988 * index line is N hexadecimal, "..", N hexadecimal,
2cf67f1e
JH
989 * and optional space with octal mode.
990 */
991 const char *ptr, *eol;
992 int len;
993
994 ptr = strchr(line, '.');
9add69b1 995 if (!ptr || ptr[1] != '.' || 40 < ptr - line)
2cf67f1e
JH
996 return 0;
997 len = ptr - line;
998 memcpy(patch->old_sha1_prefix, line, len);
999 patch->old_sha1_prefix[len] = 0;
1000
1001 line = ptr + 2;
1002 ptr = strchr(line, ' ');
1003 eol = strchr(line, '\n');
1004
1005 if (!ptr || eol < ptr)
1006 ptr = eol;
1007 len = ptr - line;
1008
9add69b1 1009 if (40 < len)
2cf67f1e
JH
1010 return 0;
1011 memcpy(patch->new_sha1_prefix, line, len);
1012 patch->new_sha1_prefix[len] = 0;
1013 if (*ptr == ' ')
1f7903a3 1014 patch->old_mode = strtoul(ptr+1, NULL, 8);
2cf67f1e
JH
1015 return 0;
1016}
1017
9a4a100e
LT
1018/*
1019 * This is normal for a diff that doesn't change anything: we'll fall through
1020 * into the next diff. Tell the parser to break out.
1021 */
19c58fb8 1022static int gitdiff_unrecognized(const char *line, struct patch *patch)
9a4a100e
LT
1023{
1024 return -1;
1025}
1026
22943f1a
JH
1027static const char *stop_at_slash(const char *line, int llen)
1028{
ec7fc0b1 1029 int nslash = p_value;
22943f1a
JH
1030 int i;
1031
1032 for (i = 0; i < llen; i++) {
1033 int ch = line[i];
ec7fc0b1
JH
1034 if (ch == '/' && --nslash <= 0)
1035 return &line[i];
22943f1a
JH
1036 }
1037 return NULL;
1038}
1039
81bf96bb
JH
1040/*
1041 * This is to extract the same name that appears on "diff --git"
22943f1a
JH
1042 * line. We do not find and return anything if it is a rename
1043 * patch, and it is OK because we will find the name elsewhere.
1044 * We need to reliably find name only when it is mode-change only,
1045 * creation or deletion of an empty file. In any of these cases,
1046 * both sides are the same name under a/ and b/ respectively.
1047 */
1048static char *git_header_name(char *line, int llen)
5041aa70 1049{
22943f1a
JH
1050 const char *name;
1051 const char *second = NULL;
cefd43b7 1052 size_t len, line_len;
5041aa70 1053
22943f1a
JH
1054 line += strlen("diff --git ");
1055 llen -= strlen("diff --git ");
1056
1057 if (*line == '"') {
1058 const char *cp;
f285a2d7
BC
1059 struct strbuf first = STRBUF_INIT;
1060 struct strbuf sp = STRBUF_INIT;
7fb1011e
PH
1061
1062 if (unquote_c_style(&first, line, &second))
1063 goto free_and_fail1;
22943f1a
JH
1064
1065 /* advance to the first slash */
7fb1011e
PH
1066 cp = stop_at_slash(first.buf, first.len);
1067 /* we do not accept absolute paths */
1068 if (!cp || cp == first.buf)
1069 goto free_and_fail1;
1070 strbuf_remove(&first, 0, cp + 1 - first.buf);
22943f1a 1071
81bf96bb
JH
1072 /*
1073 * second points at one past closing dq of name.
22943f1a
JH
1074 * find the second name.
1075 */
1076 while ((second < line + llen) && isspace(*second))
1077 second++;
1078
1079 if (line + llen <= second)
7fb1011e 1080 goto free_and_fail1;
22943f1a 1081 if (*second == '"') {
7fb1011e
PH
1082 if (unquote_c_style(&sp, second, NULL))
1083 goto free_and_fail1;
1084 cp = stop_at_slash(sp.buf, sp.len);
1085 if (!cp || cp == sp.buf)
1086 goto free_and_fail1;
22943f1a 1087 /* They must match, otherwise ignore */
7fb1011e
PH
1088 if (strcmp(cp + 1, first.buf))
1089 goto free_and_fail1;
1090 strbuf_release(&sp);
b315c5c0 1091 return strbuf_detach(&first, NULL);
22943f1a
JH
1092 }
1093
1094 /* unquoted second */
1095 cp = stop_at_slash(second, line + llen - second);
1096 if (!cp || cp == second)
7fb1011e 1097 goto free_and_fail1;
22943f1a 1098 cp++;
7fb1011e
PH
1099 if (line + llen - cp != first.len + 1 ||
1100 memcmp(first.buf, cp, first.len))
1101 goto free_and_fail1;
b315c5c0 1102 return strbuf_detach(&first, NULL);
7fb1011e
PH
1103
1104 free_and_fail1:
1105 strbuf_release(&first);
1106 strbuf_release(&sp);
1107 return NULL;
5041aa70
LT
1108 }
1109
22943f1a
JH
1110 /* unquoted first name */
1111 name = stop_at_slash(line, llen);
1112 if (!name || name == line)
5041aa70 1113 return NULL;
22943f1a
JH
1114 name++;
1115
81bf96bb
JH
1116 /*
1117 * since the first name is unquoted, a dq if exists must be
22943f1a
JH
1118 * the beginning of the second name.
1119 */
1120 for (second = name; second < line + llen; second++) {
1121 if (*second == '"') {
f285a2d7 1122 struct strbuf sp = STRBUF_INIT;
22943f1a 1123 const char *np;
7fb1011e 1124
7fb1011e
PH
1125 if (unquote_c_style(&sp, second, NULL))
1126 goto free_and_fail2;
1127
1128 np = stop_at_slash(sp.buf, sp.len);
1129 if (!np || np == sp.buf)
1130 goto free_and_fail2;
22943f1a 1131 np++;
7fb1011e
PH
1132
1133 len = sp.buf + sp.len - np;
1134 if (len < second - name &&
22943f1a
JH
1135 !strncmp(np, name, len) &&
1136 isspace(name[len])) {
1137 /* Good */
7fb1011e 1138 strbuf_remove(&sp, 0, np - sp.buf);
b315c5c0 1139 return strbuf_detach(&sp, NULL);
22943f1a 1140 }
7fb1011e
PH
1141
1142 free_and_fail2:
1143 strbuf_release(&sp);
1144 return NULL;
22943f1a
JH
1145 }
1146 }
1147
5041aa70
LT
1148 /*
1149 * Accept a name only if it shows up twice, exactly the same
1150 * form.
1151 */
cefd43b7
FC
1152 second = strchr(name, '\n');
1153 if (!second)
1154 return NULL;
1155 line_len = second - name;
5041aa70 1156 for (len = 0 ; ; len++) {
dd305c84 1157 switch (name[len]) {
5041aa70
LT
1158 default:
1159 continue;
1160 case '\n':
e70a165d 1161 return NULL;
5041aa70 1162 case '\t': case ' ':
cefd43b7
FC
1163 second = stop_at_slash(name + len, line_len - len);
1164 if (!second)
1165 return NULL;
1166 second++;
1167 if (second[len] == '\n' && !strncmp(name, second, len)) {
182af834 1168 return xmemdupz(name, len);
5041aa70
LT
1169 }
1170 }
1171 }
5041aa70
LT
1172}
1173
c1bb9350 1174/* Verify that we recognize the lines following a git header */
19c58fb8 1175static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
c1bb9350 1176{
a4acb0eb
LT
1177 unsigned long offset;
1178
1179 /* A git diff has explicit new/delete information, so we don't guess */
19c58fb8
LT
1180 patch->is_new = 0;
1181 patch->is_delete = 0;
a4acb0eb 1182
5041aa70
LT
1183 /*
1184 * Some things may not have the old name in the
1185 * rest of the headers anywhere (pure mode changes,
1186 * or removing or adding empty files), so we get
1187 * the default name from the header.
1188 */
22943f1a 1189 patch->def_name = git_header_name(line, len);
969c8775
JK
1190 if (patch->def_name && root) {
1191 char *s = xmalloc(root_len + strlen(patch->def_name) + 1);
1192 strcpy(s, root);
1193 strcpy(s + root_len, patch->def_name);
1194 free(patch->def_name);
1195 patch->def_name = s;
1196 }
5041aa70 1197
a4acb0eb
LT
1198 line += len;
1199 size -= len;
1200 linenr++;
1201 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
1202 static const struct opentry {
1203 const char *str;
19c58fb8 1204 int (*fn)(const char *, struct patch *);
a4acb0eb
LT
1205 } optable[] = {
1206 { "@@ -", gitdiff_hdrend },
1207 { "--- ", gitdiff_oldname },
1208 { "+++ ", gitdiff_newname },
1209 { "old mode ", gitdiff_oldmode },
1210 { "new mode ", gitdiff_newmode },
1211 { "deleted file mode ", gitdiff_delete },
1212 { "new file mode ", gitdiff_newfile },
1213 { "copy from ", gitdiff_copysrc },
1214 { "copy to ", gitdiff_copydst },
33f4d087
LT
1215 { "rename old ", gitdiff_renamesrc },
1216 { "rename new ", gitdiff_renamedst },
dc938417
LT
1217 { "rename from ", gitdiff_renamesrc },
1218 { "rename to ", gitdiff_renamedst },
a4acb0eb 1219 { "similarity index ", gitdiff_similarity },
70aadac0 1220 { "dissimilarity index ", gitdiff_dissimilarity },
2cf67f1e 1221 { "index ", gitdiff_index },
9a4a100e 1222 { "", gitdiff_unrecognized },
a4acb0eb
LT
1223 };
1224 int i;
c1bb9350 1225
c1bb9350 1226 len = linelen(line, size);
a4acb0eb 1227 if (!len || line[len-1] != '\n')
c1bb9350 1228 break;
b4f2a6ac 1229 for (i = 0; i < ARRAY_SIZE(optable); i++) {
a4acb0eb
LT
1230 const struct opentry *p = optable + i;
1231 int oplen = strlen(p->str);
1232 if (len < oplen || memcmp(p->str, line, oplen))
1233 continue;
19c58fb8 1234 if (p->fn(line + oplen, patch) < 0)
a4acb0eb 1235 return offset;
9a4a100e 1236 break;
a4acb0eb 1237 }
c1bb9350
LT
1238 }
1239
a4acb0eb 1240 return offset;
c1bb9350
LT
1241}
1242
fab2c257 1243static int parse_num(const char *line, unsigned long *p)
46979f56
LT
1244{
1245 char *ptr;
fab2c257
LT
1246
1247 if (!isdigit(*line))
1248 return 0;
1249 *p = strtoul(line, &ptr, 10);
1250 return ptr - line;
1251}
1252
1253static int parse_range(const char *line, int len, int offset, const char *expect,
81bf96bb 1254 unsigned long *p1, unsigned long *p2)
fab2c257 1255{
46979f56
LT
1256 int digits, ex;
1257
1258 if (offset < 0 || offset >= len)
1259 return -1;
1260 line += offset;
1261 len -= offset;
1262
fab2c257
LT
1263 digits = parse_num(line, p1);
1264 if (!digits)
46979f56 1265 return -1;
46979f56
LT
1266
1267 offset += digits;
1268 line += digits;
1269 len -= digits;
1270
c1504628 1271 *p2 = 1;
fab2c257
LT
1272 if (*line == ',') {
1273 digits = parse_num(line+1, p2);
1274 if (!digits)
1275 return -1;
1276
1277 offset += digits+1;
1278 line += digits+1;
1279 len -= digits+1;
1280 }
1281
46979f56
LT
1282 ex = strlen(expect);
1283 if (ex > len)
1284 return -1;
1285 if (memcmp(line, expect, ex))
1286 return -1;
1287
1288 return offset + ex;
1289}
1290
c14b9d1e
JS
1291static void recount_diff(char *line, int size, struct fragment *fragment)
1292{
1293 int oldlines = 0, newlines = 0, ret = 0;
1294
1295 if (size < 1) {
1296 warning("recount: ignore empty hunk");
1297 return;
1298 }
1299
1300 for (;;) {
1301 int len = linelen(line, size);
1302 size -= len;
1303 line += len;
1304
1305 if (size < 1)
1306 break;
1307
1308 switch (*line) {
1309 case ' ': case '\n':
1310 newlines++;
1311 /* fall through */
1312 case '-':
1313 oldlines++;
1314 continue;
1315 case '+':
1316 newlines++;
1317 continue;
1318 case '\\':
6cf91492 1319 continue;
c14b9d1e
JS
1320 case '@':
1321 ret = size < 3 || prefixcmp(line, "@@ ");
1322 break;
1323 case 'd':
1324 ret = size < 5 || prefixcmp(line, "diff ");
1325 break;
1326 default:
1327 ret = -1;
1328 break;
1329 }
1330 if (ret) {
1331 warning("recount: unexpected line: %.*s",
1332 (int)linelen(line, size), line);
1333 return;
1334 }
1335 break;
1336 }
1337 fragment->oldlines = oldlines;
1338 fragment->newlines = newlines;
1339}
1340
46979f56
LT
1341/*
1342 * Parse a unified diff fragment header of the
1343 * form "@@ -a,b +c,d @@"
1344 */
19c58fb8 1345static int parse_fragment_header(char *line, int len, struct fragment *fragment)
46979f56
LT
1346{
1347 int offset;
1348
1349 if (!len || line[len-1] != '\n')
1350 return -1;
1351
1352 /* Figure out the number of lines in a fragment */
fab2c257
LT
1353 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1354 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
46979f56
LT
1355
1356 return offset;
1357}
1358
19c58fb8 1359static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
c1bb9350
LT
1360{
1361 unsigned long offset, len;
1362
9987d7c5 1363 patch->is_toplevel_relative = 0;
19c58fb8
LT
1364 patch->is_rename = patch->is_copy = 0;
1365 patch->is_new = patch->is_delete = -1;
1366 patch->old_mode = patch->new_mode = 0;
1367 patch->old_name = patch->new_name = NULL;
46979f56 1368 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
c1bb9350
LT
1369 unsigned long nextlen;
1370
1371 len = linelen(line, size);
1372 if (!len)
1373 break;
1374
1375 /* Testing this early allows us to take a few shortcuts.. */
1376 if (len < 6)
1377 continue;
46979f56
LT
1378
1379 /*
82e5a82f 1380 * Make sure we don't find any unconnected patch fragments.
46979f56
LT
1381 * That's a sign that we didn't find a header, and that a
1382 * patch has become corrupted/broken up.
1383 */
1384 if (!memcmp("@@ -", line, 4)) {
19c58fb8
LT
1385 struct fragment dummy;
1386 if (parse_fragment_header(line, len, &dummy) < 0)
46979f56 1387 continue;
65341411
JH
1388 die("patch fragment without header at line %d: %.*s",
1389 linenr, (int)len-1, line);
46979f56
LT
1390 }
1391
c1bb9350
LT
1392 if (size < len + 6)
1393 break;
1394
1395 /*
1396 * Git patch? It might not have a real patch, just a rename
1397 * or mode change, so we handle that specially
1398 */
1399 if (!memcmp("diff --git ", line, 11)) {
19c58fb8 1400 int git_hdr_len = parse_git_header(line, len, size, patch);
206de27e 1401 if (git_hdr_len <= len)
c1bb9350 1402 continue;
b7e8039a
LT
1403 if (!patch->old_name && !patch->new_name) {
1404 if (!patch->def_name)
15862087
AG
1405 die("git diff header lacks filename information when removing "
1406 "%d leading pathname components (line %d)" , p_value, linenr);
b7e8039a
LT
1407 patch->old_name = patch->new_name = patch->def_name;
1408 }
9987d7c5 1409 patch->is_toplevel_relative = 1;
a4acb0eb 1410 *hdrsize = git_hdr_len;
c1bb9350
LT
1411 return offset;
1412 }
1413
81bf96bb 1414 /* --- followed by +++ ? */
c1bb9350
LT
1415 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1416 continue;
1417
1418 /*
1419 * We only accept unified patches, so we want it to
1420 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
81bf96bb 1421 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
c1bb9350
LT
1422 */
1423 nextlen = linelen(line + len, size - len);
1424 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1425 continue;
1426
1427 /* Ok, we'll consider it a patch */
19c58fb8 1428 parse_traditional_patch(line, line+len, patch);
c1bb9350 1429 *hdrsize = len + nextlen;
46979f56 1430 linenr += 2;
c1bb9350
LT
1431 return offset;
1432 }
1433 return -1;
1434}
1435
92a1747e 1436static void record_ws_error(unsigned result, const char *line, int len, int linenr)
d0c25035 1437{
c1795bb0 1438 char *err;
92a1747e 1439
c1795bb0
WC
1440 if (!result)
1441 return;
d0c25035 1442
d0c25035
JH
1443 whitespace_error++;
1444 if (squelch_whitespace_errors &&
1445 squelch_whitespace_errors < whitespace_error)
92a1747e
JH
1446 return;
1447
1448 err = whitespace_error_string(result);
1449 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1450 patch_input_file, linenr, err, len, line);
1451 free(err);
1452}
1453
1454static void check_whitespace(const char *line, int len, unsigned ws_rule)
1455{
1456 unsigned result = ws_check(line + 1, len - 1, ws_rule);
1457
1458 record_ws_error(result, line + 1, len - 2, linenr);
d0c25035
JH
1459}
1460
c1bb9350 1461/*
4be60962
JH
1462 * Parse a unified diff. Note that this really needs to parse each
1463 * fragment separately, since the only way to know the difference
1464 * between a "---" that is part of a patch, and a "---" that starts
1465 * the next patch is to look at the line counts..
c1bb9350 1466 */
81bf96bb
JH
1467static int parse_fragment(char *line, unsigned long size,
1468 struct patch *patch, struct fragment *fragment)
c1bb9350 1469{
3f40315a 1470 int added, deleted;
c1bb9350 1471 int len = linelen(line, size), offset;
30996652 1472 unsigned long oldlines, newlines;
47495887 1473 unsigned long leading, trailing;
c1bb9350 1474
19c58fb8 1475 offset = parse_fragment_header(line, len, fragment);
c1bb9350
LT
1476 if (offset < 0)
1477 return -1;
c14b9d1e
JS
1478 if (offset > 0 && patch->recount)
1479 recount_diff(line + offset, size - offset, fragment);
19c58fb8
LT
1480 oldlines = fragment->oldlines;
1481 newlines = fragment->newlines;
47495887
EB
1482 leading = 0;
1483 trailing = 0;
c1bb9350
LT
1484
1485 /* Parse the thing.. */
1486 line += len;
1487 size -= len;
46979f56 1488 linenr++;
3f40315a 1489 added = deleted = 0;
4be60962
JH
1490 for (offset = len;
1491 0 < size;
1492 offset += len, size -= len, line += len, linenr++) {
c1bb9350
LT
1493 if (!oldlines && !newlines)
1494 break;
1495 len = linelen(line, size);
1496 if (!len || line[len-1] != '\n')
1497 return -1;
1498 switch (*line) {
1499 default:
1500 return -1;
b507b465 1501 case '\n': /* newer GNU diff, an empty context line */
c1bb9350
LT
1502 case ' ':
1503 oldlines--;
1504 newlines--;
47495887
EB
1505 if (!deleted && !added)
1506 leading++;
1507 trailing++;
c1bb9350
LT
1508 break;
1509 case '-':
5fda48d6 1510 if (apply_in_reverse &&
81bf96bb 1511 ws_error_action != nowarn_ws_error)
cf1b7869 1512 check_whitespace(line, len, patch->ws_rule);
3f40315a 1513 deleted++;
c1bb9350 1514 oldlines--;
47495887 1515 trailing = 0;
c1bb9350
LT
1516 break;
1517 case '+':
5fda48d6 1518 if (!apply_in_reverse &&
81bf96bb 1519 ws_error_action != nowarn_ws_error)
cf1b7869 1520 check_whitespace(line, len, patch->ws_rule);
3f40315a 1521 added++;
c1bb9350 1522 newlines--;
47495887 1523 trailing = 0;
c1bb9350 1524 break;
433ef8a2 1525
81bf96bb
JH
1526 /*
1527 * We allow "\ No newline at end of file". Depending
433ef8a2
FK
1528 * on locale settings when the patch was produced we
1529 * don't know what this line looks like. The only
56d33b11
JH
1530 * thing we do know is that it begins with "\ ".
1531 * Checking for 12 is just for sanity check -- any
1532 * l10n of "\ No newline..." is at least that long.
1533 */
fab2c257 1534 case '\\':
433ef8a2 1535 if (len < 12 || memcmp(line, "\\ ", 2))
3cca928d 1536 return -1;
fab2c257 1537 break;
c1bb9350
LT
1538 }
1539 }
c1504628
LT
1540 if (oldlines || newlines)
1541 return -1;
47495887
EB
1542 fragment->leading = leading;
1543 fragment->trailing = trailing;
1544
81bf96bb
JH
1545 /*
1546 * If a fragment ends with an incomplete line, we failed to include
8b64647d
JH
1547 * it in the above loop because we hit oldlines == newlines == 0
1548 * before seeing it.
1549 */
433ef8a2 1550 if (12 < size && !memcmp(line, "\\ ", 2))
8b64647d
JH
1551 offset += linelen(line, size);
1552
3f40315a
LT
1553 patch->lines_added += added;
1554 patch->lines_deleted += deleted;
4be60962
JH
1555
1556 if (0 < patch->is_new && oldlines)
1557 return error("new file depends on old contents");
1558 if (0 < patch->is_delete && newlines)
1559 return error("deleted file still has contents");
c1bb9350
LT
1560 return offset;
1561}
1562
19c58fb8 1563static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
c1bb9350
LT
1564{
1565 unsigned long offset = 0;
4be60962 1566 unsigned long oldlines = 0, newlines = 0, context = 0;
19c58fb8 1567 struct fragment **fragp = &patch->fragments;
c1bb9350
LT
1568
1569 while (size > 4 && !memcmp(line, "@@ -", 4)) {
19c58fb8
LT
1570 struct fragment *fragment;
1571 int len;
1572
90321c10 1573 fragment = xcalloc(1, sizeof(*fragment));
77b15bbd 1574 fragment->linenr = linenr;
19c58fb8 1575 len = parse_fragment(line, size, patch, fragment);
c1bb9350 1576 if (len <= 0)
46979f56 1577 die("corrupt patch at line %d", linenr);
19c58fb8
LT
1578 fragment->patch = line;
1579 fragment->size = len;
4be60962
JH
1580 oldlines += fragment->oldlines;
1581 newlines += fragment->newlines;
1582 context += fragment->leading + fragment->trailing;
19c58fb8
LT
1583
1584 *fragp = fragment;
1585 fragp = &fragment->next;
c1bb9350
LT
1586
1587 offset += len;
1588 line += len;
1589 size -= len;
1590 }
4be60962
JH
1591
1592 /*
1593 * If something was removed (i.e. we have old-lines) it cannot
1594 * be creation, and if something was added it cannot be
1595 * deletion. However, the reverse is not true; --unified=0
1596 * patches that only add are not necessarily creation even
1597 * though they do not have any old lines, and ones that only
1598 * delete are not necessarily deletion.
1599 *
1600 * Unfortunately, a real creation/deletion patch do _not_ have
1601 * any context line by definition, so we cannot safely tell it
1602 * apart with --unified=0 insanity. At least if the patch has
1603 * more than one hunk it is not creation or deletion.
1604 */
1605 if (patch->is_new < 0 &&
1606 (oldlines || (patch->fragments && patch->fragments->next)))
1607 patch->is_new = 0;
1608 if (patch->is_delete < 0 &&
1609 (newlines || (patch->fragments && patch->fragments->next)))
1610 patch->is_delete = 0;
4be60962
JH
1611
1612 if (0 < patch->is_new && oldlines)
1613 die("new file %s depends on old contents", patch->new_name);
1614 if (0 < patch->is_delete && newlines)
1615 die("deleted file %s still has contents", patch->old_name);
1616 if (!patch->is_delete && !newlines && context)
1617 fprintf(stderr, "** warning: file %s becomes empty but "
1618 "is not deleted\n", patch->new_name);
1619
c1bb9350
LT
1620 return offset;
1621}
1622
1fea629f
LT
1623static inline int metadata_changes(struct patch *patch)
1624{
1625 return patch->is_rename > 0 ||
1626 patch->is_copy > 0 ||
1627 patch->is_new > 0 ||
1628 patch->is_delete ||
1629 (patch->old_mode && patch->new_mode &&
1630 patch->old_mode != patch->new_mode);
1631}
1632
3cd4f5e8
JH
1633static char *inflate_it(const void *data, unsigned long size,
1634 unsigned long inflated_size)
051308f6 1635{
3cd4f5e8
JH
1636 z_stream stream;
1637 void *out;
1638 int st;
1639
1640 memset(&stream, 0, sizeof(stream));
1641
1642 stream.next_in = (unsigned char *)data;
1643 stream.avail_in = size;
1644 stream.next_out = out = xmalloc(inflated_size);
1645 stream.avail_out = inflated_size;
39c68542
LT
1646 git_inflate_init(&stream);
1647 st = git_inflate(&stream, Z_FINISH);
1648 git_inflate_end(&stream);
3cd4f5e8
JH
1649 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1650 free(out);
1651 return NULL;
1652 }
1653 return out;
1654}
1655
1656static struct fragment *parse_binary_hunk(char **buf_p,
1657 unsigned long *sz_p,
1658 int *status_p,
1659 int *used_p)
1660{
81bf96bb
JH
1661 /*
1662 * Expect a line that begins with binary patch method ("literal"
3cd4f5e8
JH
1663 * or "delta"), followed by the length of data before deflating.
1664 * a sequence of 'length-byte' followed by base-85 encoded data
1665 * should follow, terminated by a newline.
051308f6
JH
1666 *
1667 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1668 * and we would limit the patch line to 66 characters,
1669 * so one line can fit up to 13 groups that would decode
1670 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1671 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
051308f6
JH
1672 */
1673 int llen, used;
3cd4f5e8
JH
1674 unsigned long size = *sz_p;
1675 char *buffer = *buf_p;
1676 int patch_method;
1677 unsigned long origlen;
0660626c 1678 char *data = NULL;
3cd4f5e8
JH
1679 int hunk_size = 0;
1680 struct fragment *frag;
051308f6 1681
0660626c
JH
1682 llen = linelen(buffer, size);
1683 used = llen;
3cd4f5e8
JH
1684
1685 *status_p = 0;
0660626c 1686
cc44c765 1687 if (!prefixcmp(buffer, "delta ")) {
3cd4f5e8
JH
1688 patch_method = BINARY_DELTA_DEFLATED;
1689 origlen = strtoul(buffer + 6, NULL, 10);
0660626c 1690 }
cc44c765 1691 else if (!prefixcmp(buffer, "literal ")) {
3cd4f5e8
JH
1692 patch_method = BINARY_LITERAL_DEFLATED;
1693 origlen = strtoul(buffer + 8, NULL, 10);
0660626c
JH
1694 }
1695 else
3cd4f5e8
JH
1696 return NULL;
1697
1698 linenr++;
0660626c 1699 buffer += llen;
051308f6
JH
1700 while (1) {
1701 int byte_length, max_byte_length, newsize;
1702 llen = linelen(buffer, size);
1703 used += llen;
1704 linenr++;
03eb8f8a
JH
1705 if (llen == 1) {
1706 /* consume the blank line */
1707 buffer++;
1708 size--;
051308f6 1709 break;
03eb8f8a 1710 }
81bf96bb
JH
1711 /*
1712 * Minimum line is "A00000\n" which is 7-byte long,
051308f6
JH
1713 * and the line length must be multiple of 5 plus 2.
1714 */
1715 if ((llen < 7) || (llen-2) % 5)
1716 goto corrupt;
1717 max_byte_length = (llen - 2) / 5 * 4;
1718 byte_length = *buffer;
1719 if ('A' <= byte_length && byte_length <= 'Z')
1720 byte_length = byte_length - 'A' + 1;
1721 else if ('a' <= byte_length && byte_length <= 'z')
1722 byte_length = byte_length - 'a' + 27;
1723 else
1724 goto corrupt;
1725 /* if the input length was not multiple of 4, we would
1726 * have filler at the end but the filler should never
1727 * exceed 3 bytes
1728 */
1729 if (max_byte_length < byte_length ||
1730 byte_length <= max_byte_length - 4)
1731 goto corrupt;
3cd4f5e8 1732 newsize = hunk_size + byte_length;
0660626c 1733 data = xrealloc(data, newsize);
3cd4f5e8 1734 if (decode_85(data + hunk_size, buffer + 1, byte_length))
051308f6 1735 goto corrupt;
3cd4f5e8 1736 hunk_size = newsize;
051308f6
JH
1737 buffer += llen;
1738 size -= llen;
1739 }
3cd4f5e8
JH
1740
1741 frag = xcalloc(1, sizeof(*frag));
1742 frag->patch = inflate_it(data, hunk_size, origlen);
1743 if (!frag->patch)
1744 goto corrupt;
1745 free(data);
1746 frag->size = origlen;
1747 *buf_p = buffer;
1748 *sz_p = size;
1749 *used_p = used;
1750 frag->binary_patch_method = patch_method;
1751 return frag;
1752
051308f6 1753 corrupt:
4cac42b1 1754 free(data);
3cd4f5e8
JH
1755 *status_p = -1;
1756 error("corrupt binary patch at line %d: %.*s",
1757 linenr-1, llen-1, buffer);
1758 return NULL;
1759}
1760
1761static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1762{
81bf96bb
JH
1763 /*
1764 * We have read "GIT binary patch\n"; what follows is a line
3cd4f5e8
JH
1765 * that says the patch method (currently, either "literal" or
1766 * "delta") and the length of data before deflating; a
1767 * sequence of 'length-byte' followed by base-85 encoded data
1768 * follows.
1769 *
1770 * When a binary patch is reversible, there is another binary
1771 * hunk in the same format, starting with patch method (either
1772 * "literal" or "delta") with the length of data, and a sequence
1773 * of length-byte + base-85 encoded data, terminated with another
1774 * empty line. This data, when applied to the postimage, produces
1775 * the preimage.
1776 */
1777 struct fragment *forward;
1778 struct fragment *reverse;
1779 int status;
1780 int used, used_1;
1781
1782 forward = parse_binary_hunk(&buffer, &size, &status, &used);
1783 if (!forward && !status)
1784 /* there has to be one hunk (forward hunk) */
1785 return error("unrecognized binary patch at line %d", linenr-1);
1786 if (status)
1787 /* otherwise we already gave an error message */
1788 return status;
1789
1790 reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1791 if (reverse)
1792 used += used_1;
1793 else if (status) {
81bf96bb
JH
1794 /*
1795 * Not having reverse hunk is not an error, but having
3cd4f5e8
JH
1796 * a corrupt reverse hunk is.
1797 */
1798 free((void*) forward->patch);
1799 free(forward);
1800 return status;
1801 }
1802 forward->next = reverse;
1803 patch->fragments = forward;
1804 patch->is_binary = 1;
1805 return used;
051308f6
JH
1806}
1807
19c58fb8 1808static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
c1bb9350
LT
1809{
1810 int hdrsize, patchsize;
19c58fb8 1811 int offset = find_header(buffer, size, &hdrsize, patch);
c1bb9350
LT
1812
1813 if (offset < 0)
1814 return offset;
c1bb9350 1815
cf1b7869
JH
1816 patch->ws_rule = whitespace_rule(patch->new_name
1817 ? patch->new_name
1818 : patch->old_name);
1819
81bf96bb
JH
1820 patchsize = parse_single_patch(buffer + offset + hdrsize,
1821 size - offset - hdrsize, patch);
c1bb9350 1822
92927ed0 1823 if (!patchsize) {
3200d1ae
JH
1824 static const char *binhdr[] = {
1825 "Binary files ",
1826 "Files ",
1827 NULL,
1828 };
051308f6 1829 static const char git_binary[] = "GIT binary patch\n";
3200d1ae
JH
1830 int i;
1831 int hd = hdrsize + offset;
1832 unsigned long llen = linelen(buffer + hd, size - hd);
1833
051308f6
JH
1834 if (llen == sizeof(git_binary) - 1 &&
1835 !memcmp(git_binary, buffer + hd, llen)) {
1836 int used;
1837 linenr++;
1838 used = parse_binary(buffer + hd + llen,
1839 size - hd - llen, patch);
1840 if (used)
1841 patchsize = used + llen;
1842 else
1843 patchsize = 0;
1844 }
1845 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
3200d1ae
JH
1846 for (i = 0; binhdr[i]; i++) {
1847 int len = strlen(binhdr[i]);
1848 if (len < size - hd &&
1849 !memcmp(binhdr[i], buffer + hd, len)) {
051308f6 1850 linenr++;
3200d1ae 1851 patch->is_binary = 1;
051308f6 1852 patchsize = llen;
3200d1ae
JH
1853 break;
1854 }
1855 }
051308f6 1856 }
ff36de08 1857
2b6eef94
JH
1858 /* Empty patch cannot be applied if it is a text patch
1859 * without metadata change. A binary patch appears
1860 * empty to us here.
92927ed0
JH
1861 */
1862 if ((apply || check) &&
2b6eef94 1863 (!patch->is_binary && !metadata_changes(patch)))
ff36de08
JH
1864 die("patch with only garbage at line %d", linenr);
1865 }
1fea629f 1866
c1bb9350
LT
1867 return offset + hdrsize + patchsize;
1868}
1869
e5a94313
JS
1870#define swap(a,b) myswap((a),(b),sizeof(a))
1871
1872#define myswap(a, b, size) do { \
1873 unsigned char mytmp[size]; \
1874 memcpy(mytmp, &a, size); \
1875 memcpy(&a, &b, size); \
1876 memcpy(&b, mytmp, size); \
1877} while (0)
1878
1879static void reverse_patches(struct patch *p)
1880{
1881 for (; p; p = p->next) {
1882 struct fragment *frag = p->fragments;
1883
1884 swap(p->new_name, p->old_name);
1885 swap(p->new_mode, p->old_mode);
1886 swap(p->is_new, p->is_delete);
1887 swap(p->lines_added, p->lines_deleted);
1888 swap(p->old_sha1_prefix, p->new_sha1_prefix);
1889
1890 for (; frag; frag = frag->next) {
1891 swap(frag->newpos, frag->oldpos);
1892 swap(frag->newlines, frag->oldlines);
1893 }
e5a94313
JS
1894 }
1895}
1896
81bf96bb
JH
1897static const char pluses[] =
1898"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1899static const char minuses[]=
1900"----------------------------------------------------------------------";
3f40315a
LT
1901
1902static void show_stats(struct patch *patch)
1903{
f285a2d7 1904 struct strbuf qname = STRBUF_INIT;
663af342
PH
1905 char *cp = patch->new_name ? patch->new_name : patch->old_name;
1906 int max, add, del;
3f40315a 1907
663af342 1908 quote_c_style(cp, &qname, NULL, 0);
22943f1a 1909
3f40315a
LT
1910 /*
1911 * "scale" the filename
1912 */
3f40315a
LT
1913 max = max_len;
1914 if (max > 50)
1915 max = 50;
663af342
PH
1916
1917 if (qname.len > max) {
1918 cp = strchr(qname.buf + qname.len + 3 - max, '/');
1919 if (!cp)
1920 cp = qname.buf + qname.len + 3 - max;
1921 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
1922 }
1923
1924 if (patch->is_binary) {
1925 printf(" %-*s | Bin\n", max, qname.buf);
1926 strbuf_release(&qname);
1927 return;
62917097 1928 }
663af342
PH
1929
1930 printf(" %-*s |", max, qname.buf);
1931 strbuf_release(&qname);
3f40315a
LT
1932
1933 /*
1934 * scale the add/delete
1935 */
663af342 1936 max = max + max_change > 70 ? 70 - max : max_change;
95bedc9e
LT
1937 add = patch->lines_added;
1938 del = patch->lines_deleted;
95bedc9e 1939
69f956e1 1940 if (max_change > 0) {
663af342 1941 int total = ((add + del) * max + max_change / 2) / max_change;
69f956e1
SV
1942 add = (add * max + max_change / 2) / max_change;
1943 del = total - add;
1944 }
663af342
PH
1945 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
1946 add, pluses, del, minuses);
3f40315a
LT
1947}
1948
c7f9cb14 1949static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
3cca928d 1950{
3cca928d
LT
1951 switch (st->st_mode & S_IFMT) {
1952 case S_IFLNK:
b11b7e13
LT
1953 if (strbuf_readlink(buf, path, st->st_size) < 0)
1954 return error("unable to read symlink %s", path);
c7f9cb14 1955 return 0;
3cca928d 1956 case S_IFREG:
387e7e19
PH
1957 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
1958 return error("unable to open or read %s", path);
21e5ad50 1959 convert_to_git(path, buf->buf, buf->len, buf, 0);
c7f9cb14 1960 return 0;
3cca928d
LT
1961 default:
1962 return -1;
1963 }
1964}
1965
86c91f91
GB
1966/*
1967 * Update the preimage, and the common lines in postimage,
1968 * from buffer buf of length len. If postlen is 0 the postimage
1969 * is updated in place, otherwise it's updated on a new buffer
1970 * of length postlen
1971 */
1972
c1beba5b
JH
1973static void update_pre_post_images(struct image *preimage,
1974 struct image *postimage,
1975 char *buf,
86c91f91 1976 size_t len, size_t postlen)
3cca928d 1977{
c1beba5b
JH
1978 int i, ctx;
1979 char *new, *old, *fixed;
1980 struct image fixed_preimage;
3cca928d 1981
c1beba5b
JH
1982 /*
1983 * Update the preimage with whitespace fixes. Note that we
1984 * are not losing preimage->buf -- apply_one_fragment() will
1985 * free "oldlines".
1986 */
1987 prepare_image(&fixed_preimage, buf, len, 1);
1988 assert(fixed_preimage.nr == preimage->nr);
1989 for (i = 0; i < preimage->nr; i++)
1990 fixed_preimage.line[i].flag = preimage->line[i].flag;
1991 free(preimage->line_allocated);
1992 *preimage = fixed_preimage;
3cca928d 1993
c1beba5b 1994 /*
86c91f91
GB
1995 * Adjust the common context lines in postimage. This can be
1996 * done in-place when we are just doing whitespace fixing,
1997 * which does not make the string grow, but needs a new buffer
1998 * when ignoring whitespace causes the update, since in this case
1999 * we could have e.g. tabs converted to multiple spaces.
2000 * We trust the caller to tell us if the update can be done
2001 * in place (postlen==0) or not.
c1beba5b 2002 */
86c91f91
GB
2003 old = postimage->buf;
2004 if (postlen)
2005 new = postimage->buf = xmalloc(postlen);
2006 else
2007 new = old;
c1beba5b
JH
2008 fixed = preimage->buf;
2009 for (i = ctx = 0; i < postimage->nr; i++) {
2010 size_t len = postimage->line[i].len;
2011 if (!(postimage->line[i].flag & LINE_COMMON)) {
2012 /* an added line -- no counterparts in preimage */
2013 memmove(new, old, len);
2014 old += len;
2015 new += len;
2016 continue;
3cca928d 2017 }
c1beba5b
JH
2018
2019 /* a common context -- skip it in the original postimage */
2020 old += len;
2021
2022 /* and find the corresponding one in the fixed preimage */
2023 while (ctx < preimage->nr &&
2024 !(preimage->line[ctx].flag & LINE_COMMON)) {
2025 fixed += preimage->line[ctx].len;
2026 ctx++;
2027 }
2028 if (preimage->nr <= ctx)
2029 die("oops");
2030
2031 /* and copy it in, while fixing the line length */
2032 len = preimage->line[ctx].len;
2033 memcpy(new, fixed, len);
2034 new += len;
2035 fixed += len;
2036 postimage->line[i].len = len;
2037 ctx++;
2038 }
2039
2040 /* Fix the length of the whole thing */
2041 postimage->len = new - postimage->buf;
2042}
2043
b94f2eda
JH
2044static int match_fragment(struct image *img,
2045 struct image *preimage,
2046 struct image *postimage,
c89fb6b1 2047 unsigned long try,
b94f2eda 2048 int try_lno,
c607aaa2 2049 unsigned ws_rule,
dc41976a 2050 int match_beginning, int match_end)
c89fb6b1 2051{
b94f2eda 2052 int i;
c1beba5b 2053 char *fixed_buf, *buf, *orig, *target;
d511bd33
CW
2054 struct strbuf fixed;
2055 size_t fixed_len;
51667147 2056 int preimage_limit;
b94f2eda 2057
51667147
BG
2058 if (preimage->nr + try_lno <= img->nr) {
2059 /*
2060 * The hunk falls within the boundaries of img.
2061 */
2062 preimage_limit = preimage->nr;
2063 if (match_end && (preimage->nr + try_lno != img->nr))
2064 return 0;
2065 } else if (ws_error_action == correct_ws_error &&
0c3ef984 2066 (ws_rule & WS_BLANK_AT_EOF)) {
51667147 2067 /*
0c3ef984
BG
2068 * This hunk extends beyond the end of img, and we are
2069 * removing blank lines at the end of the file. This
2070 * many lines from the beginning of the preimage must
2071 * match with img, and the remainder of the preimage
2072 * must be blank.
51667147
BG
2073 */
2074 preimage_limit = img->nr - try_lno;
2075 } else {
2076 /*
2077 * The hunk extends beyond the end of the img and
2078 * we are not removing blanks at the end, so we
2079 * should reject the hunk at this position.
2080 */
b94f2eda 2081 return 0;
51667147 2082 }
b94f2eda
JH
2083
2084 if (match_beginning && try_lno)
c89fb6b1 2085 return 0;
dc41976a 2086
b94f2eda 2087 /* Quick hash check */
51667147 2088 for (i = 0; i < preimage_limit; i++)
9d158601
JH
2089 if ((img->line[try_lno + i].flag & LINE_PATCHED) ||
2090 (preimage->line[i].hash != img->line[try_lno + i].hash))
b94f2eda
JH
2091 return 0;
2092
51667147
BG
2093 if (preimage_limit == preimage->nr) {
2094 /*
2095 * Do we have an exact match? If we were told to match
2096 * at the end, size must be exactly at try+fragsize,
2097 * otherwise try+fragsize must be still within the preimage,
2098 * and either case, the old piece should match the preimage
2099 * exactly.
2100 */
2101 if ((match_end
2102 ? (try + preimage->len == img->len)
2103 : (try + preimage->len <= img->len)) &&
2104 !memcmp(img->buf + try, preimage->buf, preimage->len))
2105 return 1;
2106 } else {
2107 /*
2108 * The preimage extends beyond the end of img, so
2109 * there cannot be an exact match.
2110 *
2111 * There must be one non-blank context line that match
2112 * a line before the end of img.
2113 */
2114 char *buf_end;
2115
2116 buf = preimage->buf;
2117 buf_end = buf;
2118 for (i = 0; i < preimage_limit; i++)
2119 buf_end += preimage->line[i].len;
2120
2121 for ( ; buf < buf_end; buf++)
2122 if (!isspace(*buf))
2123 break;
2124 if (buf == buf_end)
2125 return 0;
2126 }
dc41976a 2127
86c91f91
GB
2128 /*
2129 * No exact match. If we are ignoring whitespace, run a line-by-line
2130 * fuzzy matching. We collect all the line length information because
2131 * we need it to adjust whitespace if we match.
2132 */
2133 if (ws_ignore_action == ignore_ws_change) {
2134 size_t imgoff = 0;
2135 size_t preoff = 0;
2136 size_t postlen = postimage->len;
51667147
BG
2137 size_t extra_chars;
2138 char *preimage_eof;
2139 char *preimage_end;
2140 for (i = 0; i < preimage_limit; i++) {
86c91f91 2141 size_t prelen = preimage->line[i].len;
0b1fac32 2142 size_t imglen = img->line[try_lno+i].len;
86c91f91 2143
0b1fac32
JH
2144 if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,
2145 preimage->buf + preoff, prelen))
86c91f91
GB
2146 return 0;
2147 if (preimage->line[i].flag & LINE_COMMON)
0b1fac32
JH
2148 postlen += imglen - prelen;
2149 imgoff += imglen;
86c91f91
GB
2150 preoff += prelen;
2151 }
2152
2153 /*
9b25949a
BG
2154 * Ok, the preimage matches with whitespace fuzz.
2155 *
2156 * imgoff now holds the true length of the target that
51667147
BG
2157 * matches the preimage before the end of the file.
2158 *
2159 * Count the number of characters in the preimage that fall
2160 * beyond the end of the file and make sure that all of them
2161 * are whitespace characters. (This can only happen if
2162 * we are removing blank lines at the end of the file.)
86c91f91 2163 */
51667147
BG
2164 buf = preimage_eof = preimage->buf + preoff;
2165 for ( ; i < preimage->nr; i++)
2166 preoff += preimage->line[i].len;
2167 preimage_end = preimage->buf + preoff;
2168 for ( ; buf < preimage_end; buf++)
2169 if (!isspace(*buf))
2170 return 0;
2171
2172 /*
2173 * Update the preimage and the common postimage context
2174 * lines to use the same whitespace as the target.
2175 * If whitespace is missing in the target (i.e.
2176 * if the preimage extends beyond the end of the file),
2177 * use the whitespace from the preimage.
2178 */
2179 extra_chars = preimage_end - preimage_eof;
d511bd33
CW
2180 strbuf_init(&fixed, imgoff + extra_chars);
2181 strbuf_add(&fixed, img->buf + try, imgoff);
2182 strbuf_add(&fixed, preimage_eof, extra_chars);
2183 fixed_buf = strbuf_detach(&fixed, &fixed_len);
86c91f91 2184 update_pre_post_images(preimage, postimage,
d511bd33 2185 fixed_buf, fixed_len, postlen);
86c91f91
GB
2186 return 1;
2187 }
2188
c1beba5b
JH
2189 if (ws_error_action != correct_ws_error)
2190 return 0;
2191
dc41976a 2192 /*
c1beba5b 2193 * The hunk does not apply byte-by-byte, but the hash says
86c91f91
GB
2194 * it might with whitespace fuzz. We haven't been asked to
2195 * ignore whitespace, we were asked to correct whitespace
2196 * errors, so let's try matching after whitespace correction.
51667147
BG
2197 *
2198 * The preimage may extend beyond the end of the file,
2199 * but in this loop we will only handle the part of the
2200 * preimage that falls within the file.
dc41976a 2201 */
d511bd33 2202 strbuf_init(&fixed, preimage->len + 1);
c1beba5b
JH
2203 orig = preimage->buf;
2204 target = img->buf + try;
51667147 2205 for (i = 0; i < preimage_limit; i++) {
c1beba5b
JH
2206 size_t oldlen = preimage->line[i].len;
2207 size_t tgtlen = img->line[try_lno + i].len;
d511bd33
CW
2208 size_t fixstart = fixed.len;
2209 struct strbuf tgtfix;
c1beba5b
JH
2210 int match;
2211
2212 /* Try fixing the line in the preimage */
d511bd33 2213 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
c1beba5b
JH
2214
2215 /* Try fixing the line in the target */
d511bd33
CW
2216 strbuf_init(&tgtfix, tgtlen);
2217 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
c1beba5b
JH
2218
2219 /*
2220 * If they match, either the preimage was based on
2221 * a version before our tree fixed whitespace breakage,
2222 * or we are lacking a whitespace-fix patch the tree
2223 * the preimage was based on already had (i.e. target
2224 * has whitespace breakage, the preimage doesn't).
2225 * In either case, we are fixing the whitespace breakages
2226 * so we might as well take the fix together with their
2227 * real change.
2228 */
d511bd33
CW
2229 match = (tgtfix.len == fixed.len - fixstart &&
2230 !memcmp(tgtfix.buf, fixed.buf + fixstart,
2231 fixed.len - fixstart));
c1beba5b 2232
d511bd33 2233 strbuf_release(&tgtfix);
c1beba5b
JH
2234 if (!match)
2235 goto unmatch_exit;
2236
2237 orig += oldlen;
c1beba5b 2238 target += tgtlen;
3cca928d
LT
2239 }
2240
51667147
BG
2241
2242 /*
2243 * Now handle the lines in the preimage that falls beyond the
2244 * end of the file (if any). They will only match if they are
2245 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2246 * false).
2247 */
2248 for ( ; i < preimage->nr; i++) {
d511bd33 2249 size_t fixstart = fixed.len; /* start of the fixed preimage */
51667147
BG
2250 size_t oldlen = preimage->line[i].len;
2251 int j;
2252
2253 /* Try fixing the line in the preimage */
d511bd33 2254 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
51667147 2255
d511bd33
CW
2256 for (j = fixstart; j < fixed.len; j++)
2257 if (!isspace(fixed.buf[j]))
51667147
BG
2258 goto unmatch_exit;
2259
2260 orig += oldlen;
51667147
BG
2261 }
2262
c1beba5b
JH
2263 /*
2264 * Yes, the preimage is based on an older version that still
2265 * has whitespace breakages unfixed, and fixing them makes the
2266 * hunk match. Update the context lines in the postimage.
2267 */
d511bd33 2268 fixed_buf = strbuf_detach(&fixed, &fixed_len);
c1beba5b 2269 update_pre_post_images(preimage, postimage,
d511bd33 2270 fixed_buf, fixed_len, 0);
c1beba5b
JH
2271 return 1;
2272
2273 unmatch_exit:
d511bd33 2274 strbuf_release(&fixed);
dc41976a 2275 return 0;
c89fb6b1
JH
2276}
2277
b94f2eda
JH
2278static int find_pos(struct image *img,
2279 struct image *preimage,
2280 struct image *postimage,
2281 int line,
c607aaa2 2282 unsigned ws_rule,
b94f2eda 2283 int match_beginning, int match_end)
3cca928d 2284{
b94f2eda
JH
2285 int i;
2286 unsigned long backwards, forwards, try;
2287 int backwards_lno, forwards_lno, try_lno;
3cca928d 2288
ecf4c2ec 2289 /*
24ff4d56 2290 * If match_beginning or match_end is specified, there is no
ecf4c2ec
JH
2291 * point starting from a wrong line that will never match and
2292 * wander around and wait for a match at the specified end.
2293 */
2294 if (match_beginning)
2295 line = 0;
2296 else if (match_end)
2297 line = img->nr - preimage->nr;
2298
24ff4d56
BG
2299 /*
2300 * Because the comparison is unsigned, the following test
2301 * will also take care of a negative line number that can
2302 * result when match_end and preimage is larger than the target.
2303 */
2304 if ((size_t) line > img->nr)
52f3c81a
JH
2305 line = img->nr;
2306
b94f2eda
JH
2307 try = 0;
2308 for (i = 0; i < line; i++)
2309 try += img->line[i].len;
3cca928d 2310
6e7c92a9
LT
2311 /*
2312 * There's probably some smart way to do this, but I'll leave
2313 * that to the smart and beautiful people. I'm simple and stupid.
2314 */
b94f2eda
JH
2315 backwards = try;
2316 backwards_lno = line;
2317 forwards = try;
2318 forwards_lno = line;
2319 try_lno = line;
fcb77bc5 2320
6e7c92a9 2321 for (i = 0; ; i++) {
b94f2eda 2322 if (match_fragment(img, preimage, postimage,
c607aaa2 2323 try, try_lno, ws_rule,
b94f2eda
JH
2324 match_beginning, match_end))
2325 return try_lno;
fcb77bc5
JH
2326
2327 again:
b94f2eda 2328 if (backwards_lno == 0 && forwards_lno == img->nr)
fcb77bc5 2329 break;
6e7c92a9 2330
6e7c92a9 2331 if (i & 1) {
b94f2eda 2332 if (backwards_lno == 0) {
fcb77bc5
JH
2333 i++;
2334 goto again;
6e7c92a9 2335 }
b94f2eda
JH
2336 backwards_lno--;
2337 backwards -= img->line[backwards_lno].len;
6e7c92a9 2338 try = backwards;
b94f2eda 2339 try_lno = backwards_lno;
6e7c92a9 2340 } else {
b94f2eda 2341 if (forwards_lno == img->nr) {
fcb77bc5
JH
2342 i++;
2343 goto again;
6e7c92a9 2344 }
b94f2eda
JH
2345 forwards += img->line[forwards_lno].len;
2346 forwards_lno++;
6e7c92a9 2347 try = forwards;
b94f2eda 2348 try_lno = forwards_lno;
6e7c92a9
LT
2349 }
2350
6e7c92a9 2351 }
3cca928d
LT
2352 return -1;
2353}
2354
b94f2eda 2355static void remove_first_line(struct image *img)
47495887 2356{
b94f2eda
JH
2357 img->buf += img->line[0].len;
2358 img->len -= img->line[0].len;
2359 img->line++;
2360 img->nr--;
47495887
EB
2361}
2362
b94f2eda 2363static void remove_last_line(struct image *img)
47495887 2364{
b94f2eda 2365 img->len -= img->line[--img->nr].len;
47495887
EB
2366}
2367
b94f2eda
JH
2368static void update_image(struct image *img,
2369 int applied_pos,
2370 struct image *preimage,
2371 struct image *postimage)
b5767dd6 2372{
81bf96bb 2373 /*
b94f2eda
JH
2374 * remove the copy of preimage at offset in img
2375 * and replace it with postimage
81bf96bb 2376 */
b94f2eda
JH
2377 int i, nr;
2378 size_t remove_count, insert_count, applied_at = 0;
2379 char *result;
51667147
BG
2380 int preimage_limit;
2381
2382 /*
2383 * If we are removing blank lines at the end of img,
2384 * the preimage may extend beyond the end.
2385 * If that is the case, we must be careful only to
2386 * remove the part of the preimage that falls within
2387 * the boundaries of img. Initialize preimage_limit
2388 * to the number of lines in the preimage that falls
2389 * within the boundaries.
2390 */
2391 preimage_limit = preimage->nr;
2392 if (preimage_limit > img->nr - applied_pos)
2393 preimage_limit = img->nr - applied_pos;
d5a41641 2394
b94f2eda
JH
2395 for (i = 0; i < applied_pos; i++)
2396 applied_at += img->line[i].len;
2397
2398 remove_count = 0;
51667147 2399 for (i = 0; i < preimage_limit; i++)
b94f2eda
JH
2400 remove_count += img->line[applied_pos + i].len;
2401 insert_count = postimage->len;
2402
2403 /* Adjust the contents */
2404 result = xmalloc(img->len + insert_count - remove_count + 1);
2405 memcpy(result, img->buf, applied_at);
2406 memcpy(result + applied_at, postimage->buf, postimage->len);
2407 memcpy(result + applied_at + postimage->len,
2408 img->buf + (applied_at + remove_count),
2409 img->len - (applied_at + remove_count));
2410 free(img->buf);
2411 img->buf = result;
2412 img->len += insert_count - remove_count;
2413 result[img->len] = '\0';
2414
2415 /* Adjust the line table */
51667147
BG
2416 nr = img->nr + postimage->nr - preimage_limit;
2417 if (preimage_limit < postimage->nr) {
81bf96bb 2418 /*
b94f2eda
JH
2419 * NOTE: this knows that we never call remove_first_line()
2420 * on anything other than pre/post image.
d0c25035 2421 */
b94f2eda
JH
2422 img->line = xrealloc(img->line, nr * sizeof(*img->line));
2423 img->line_allocated = img->line;
d0c25035 2424 }
51667147 2425 if (preimage_limit != postimage->nr)
b94f2eda 2426 memmove(img->line + applied_pos + postimage->nr,
51667147
BG
2427 img->line + applied_pos + preimage_limit,
2428 (img->nr - (applied_pos + preimage_limit)) *
b94f2eda
JH
2429 sizeof(*img->line));
2430 memcpy(img->line + applied_pos,
2431 postimage->line,
2432 postimage->nr * sizeof(*img->line));
9d158601
JH
2433 for (i = 0; i < postimage->nr; i++)
2434 img->line[applied_pos + i].flag |= LINE_PATCHED;
2435
b94f2eda 2436 img->nr = nr;
b5767dd6
JH
2437}
2438
b94f2eda 2439static int apply_one_fragment(struct image *img, struct fragment *frag,
334f8cb2
JH
2440 int inaccurate_eof, unsigned ws_rule,
2441 int nth_fragment)
3cca928d 2442{
65aadb92 2443 int match_beginning, match_end;
3cca928d 2444 const char *patch = frag->patch;
b94f2eda 2445 int size = frag->size;
d511bd33
CW
2446 char *old, *oldlines;
2447 struct strbuf newlines;
077e1af5 2448 int new_blank_lines_at_end = 0;
47495887 2449 unsigned long leading, trailing;
b94f2eda
JH
2450 int pos, applied_pos;
2451 struct image preimage;
2452 struct image postimage;
3cca928d 2453
c330fdd4
JH
2454 memset(&preimage, 0, sizeof(preimage));
2455 memset(&postimage, 0, sizeof(postimage));
61e08cca 2456 oldlines = xmalloc(size);
d511bd33 2457 strbuf_init(&newlines, size);
c330fdd4 2458
61e08cca 2459 old = oldlines;
3cca928d 2460 while (size > 0) {
e5a94313 2461 char first;
3cca928d 2462 int len = linelen(patch, size);
d511bd33 2463 int plen;
077e1af5 2464 int added_blank_line = 0;
efa57443 2465 int is_blank_context = 0;
d511bd33 2466 size_t start;
3cca928d
LT
2467
2468 if (!len)
2469 break;
2470
2471 /*
2472 * "plen" is how much of the line we should use for
2473 * the actual patch data. Normally we just remove the
2474 * first character on the line, but if the line is
2475 * followed by "\ No newline", then we also remove the
2476 * last one (which is the newline, of course).
2477 */
61e08cca 2478 plen = len - 1;
8b64647d 2479 if (len < size && patch[len] == '\\')
3cca928d 2480 plen--;
e5a94313 2481 first = *patch;
f686d030 2482 if (apply_in_reverse) {
e5a94313
JS
2483 if (first == '-')
2484 first = '+';
2485 else if (first == '+')
2486 first = '-';
2487 }
efe7f358 2488
e5a94313 2489 switch (first) {
b507b465
LT
2490 case '\n':
2491 /* Newer GNU diff, empty context line */
2492 if (plen < 0)
2493 /* ... followed by '\No newline'; nothing */
2494 break;
61e08cca 2495 *old++ = '\n';
d511bd33 2496 strbuf_addch(&newlines, '\n');
c330fdd4
JH
2497 add_line_info(&preimage, "\n", 1, LINE_COMMON);
2498 add_line_info(&postimage, "\n", 1, LINE_COMMON);
efa57443 2499 is_blank_context = 1;
b507b465 2500 break;
3cca928d 2501 case ' ':
94ea026b
JH
2502 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2503 ws_blank_line(patch + 1, plen, ws_rule))
efa57443 2504 is_blank_context = 1;
3cca928d 2505 case '-':
61e08cca
JH
2506 memcpy(old, patch + 1, plen);
2507 add_line_info(&preimage, old, plen,
c330fdd4 2508 (first == ' ' ? LINE_COMMON : 0));
61e08cca 2509 old += plen;
e5a94313 2510 if (first == '-')
3cca928d
LT
2511 break;
2512 /* Fall-through for ' ' */
2513 case '+':
8441a9a8
JH
2514 /* --no-add does not add new lines */
2515 if (first == '+' && no_add)
2516 break;
2517
d511bd33 2518 start = newlines.len;
8441a9a8
JH
2519 if (first != '+' ||
2520 !whitespace_error ||
2521 ws_error_action != correct_ws_error) {
d511bd33 2522 strbuf_add(&newlines, patch + 1, plen);
8441a9a8
JH
2523 }
2524 else {
d511bd33 2525 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &applied_after_fixing_ws);
077e1af5 2526 }
d511bd33 2527 add_line_info(&postimage, newlines.buf + start, newlines.len - start,
8441a9a8 2528 (first == '+' ? 0 : LINE_COMMON));
8441a9a8 2529 if (first == '+' &&
94ea026b
JH
2530 (ws_rule & WS_BLANK_AT_EOF) &&
2531 ws_blank_line(patch + 1, plen, ws_rule))
8441a9a8 2532 added_blank_line = 1;
3cca928d
LT
2533 break;
2534 case '@': case '\\':
2535 /* Ignore it, we already handled it */
2536 break;
2537 default:
aeabfa07
JS
2538 if (apply_verbosely)
2539 error("invalid start of line: '%c'", first);
3cca928d
LT
2540 return -1;
2541 }
077e1af5
JH
2542 if (added_blank_line)
2543 new_blank_lines_at_end++;
efa57443
JH
2544 else if (is_blank_context)
2545 ;
077e1af5
JH
2546 else
2547 new_blank_lines_at_end = 0;
3cca928d
LT
2548 patch += len;
2549 size -= len;
2550 }
81bf96bb 2551 if (inaccurate_eof &&
61e08cca 2552 old > oldlines && old[-1] == '\n' &&
d511bd33 2553 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
61e08cca 2554 old--;
d511bd33 2555 strbuf_setlen(&newlines, newlines.len - 1);
5b5d4d9e 2556 }
47495887 2557
47495887
EB
2558 leading = frag->leading;
2559 trailing = frag->trailing;
1bf1a859
LT
2560
2561 /*
ee5a317e
JH
2562 * A hunk to change lines at the beginning would begin with
2563 * @@ -1,L +N,M @@
ed0f47a8
JH
2564 * but we need to be careful. -U0 that inserts before the second
2565 * line also has this pattern.
4be60962 2566 *
ee5a317e
JH
2567 * And a hunk to add to an empty file would begin with
2568 * @@ -0,0 +N,M @@
2569 *
2570 * In other words, a hunk that is (frag->oldpos <= 1) with or
2571 * without leading context must match at the beginning.
1bf1a859 2572 */
ed0f47a8
JH
2573 match_beginning = (!frag->oldpos ||
2574 (frag->oldpos == 1 && !unidiff_zero));
ee5a317e
JH
2575
2576 /*
2577 * A hunk without trailing lines must match at the end.
2578 * However, we simply cannot tell if a hunk must match end
2579 * from the lack of trailing lines if the patch was generated
2580 * with unidiff without any context.
2581 */
2582 match_end = !unidiff_zero && !trailing;
1bf1a859 2583
b94f2eda 2584 pos = frag->newpos ? (frag->newpos - 1) : 0;
61e08cca
JH
2585 preimage.buf = oldlines;
2586 preimage.len = old - oldlines;
d511bd33
CW
2587 postimage.buf = newlines.buf;
2588 postimage.len = newlines.len;
c330fdd4
JH
2589 preimage.line = preimage.line_allocated;
2590 postimage.line = postimage.line_allocated;
2591
47495887 2592 for (;;) {
efe7f358 2593
c607aaa2
JH
2594 applied_pos = find_pos(img, &preimage, &postimage, pos,
2595 ws_rule, match_beginning, match_end);
b94f2eda
JH
2596
2597 if (applied_pos >= 0)
47495887 2598 break;
47495887
EB
2599
2600 /* Am I at my context limits? */
2601 if ((leading <= p_context) && (trailing <= p_context))
2602 break;
65aadb92
JH
2603 if (match_beginning || match_end) {
2604 match_beginning = match_end = 0;
1bf1a859
LT
2605 continue;
2606 }
b94f2eda 2607
81bf96bb
JH
2608 /*
2609 * Reduce the number of context lines; reduce both
2610 * leading and trailing if they are equal otherwise
2611 * just reduce the larger context.
47495887
EB
2612 */
2613 if (leading >= trailing) {
b94f2eda
JH
2614 remove_first_line(&preimage);
2615 remove_first_line(&postimage);
47495887
EB
2616 pos--;
2617 leading--;
2618 }
2619 if (trailing > leading) {
b94f2eda
JH
2620 remove_last_line(&preimage);
2621 remove_last_line(&postimage);
47495887 2622 trailing--;
6e7c92a9 2623 }
3cca928d
LT
2624 }
2625
b94f2eda 2626 if (applied_pos >= 0) {
77b15bbd 2627 if (new_blank_lines_at_end &&
51667147 2628 preimage.nr + applied_pos >= img->nr &&
77b15bbd
JH
2629 (ws_rule & WS_BLANK_AT_EOF) &&
2630 ws_error_action != nowarn_ws_error) {
2631 record_ws_error(WS_BLANK_AT_EOF, "+", 1, frag->linenr);
2632 if (ws_error_action == correct_ws_error) {
2633 while (new_blank_lines_at_end--)
2634 remove_last_line(&postimage);
2635 }
b94f2eda 2636 /*
77b15bbd
JH
2637 * We would want to prevent write_out_results()
2638 * from taking place in apply_patch() that follows
2639 * the callchain led us here, which is:
2640 * apply_patch->check_patch_list->check_patch->
2641 * apply_data->apply_fragments->apply_one_fragment
b94f2eda 2642 */
77b15bbd
JH
2643 if (ws_error_action == die_on_ws_error)
2644 apply = 0;
b94f2eda 2645 }
aeabfa07 2646
334f8cb2
JH
2647 if (apply_verbosely && applied_pos != pos) {
2648 int offset = applied_pos - pos;
2649 if (apply_in_reverse)
2650 offset = 0 - offset;
2651 fprintf(stderr,
2652 "Hunk #%d succeeded at %d (offset %d lines).\n",
2653 nth_fragment, applied_pos + 1, offset);
2654 }
2655
b94f2eda
JH
2656 /*
2657 * Warn if it was necessary to reduce the number
2658 * of context lines.
2659 */
2660 if ((leading != frag->leading) ||
2661 (trailing != frag->trailing))
2662 fprintf(stderr, "Context reduced to (%ld/%ld)"
2663 " to apply fragment at %d\n",
2664 leading, trailing, applied_pos+1);
2665 update_image(img, applied_pos, &preimage, &postimage);
2666 } else {
2667 if (apply_verbosely)
61e08cca
JH
2668 error("while searching for:\n%.*s",
2669 (int)(old - oldlines), oldlines);
b94f2eda 2670 }
aeabfa07 2671
61e08cca 2672 free(oldlines);
d511bd33 2673 strbuf_release(&newlines);
b94f2eda
JH
2674 free(preimage.line_allocated);
2675 free(postimage.line_allocated);
2676
2677 return (applied_pos < 0);
3cca928d
LT
2678}
2679
b94f2eda 2680static int apply_binary_fragment(struct image *img, struct patch *patch)
0660626c 2681{
0660626c 2682 struct fragment *fragment = patch->fragments;
c7f9cb14
PH
2683 unsigned long len;
2684 void *dst;
0660626c 2685
24305cd7
JK
2686 if (!fragment)
2687 return error("missing binary patch data for '%s'",
2688 patch->new_name ?
2689 patch->new_name :
2690 patch->old_name);
2691
3cd4f5e8
JH
2692 /* Binary patch is irreversible without the optional second hunk */
2693 if (apply_in_reverse) {
2694 if (!fragment->next)
2695 return error("cannot reverse-apply a binary patch "
2696 "without the reverse hunk to '%s'",
2697 patch->new_name
2698 ? patch->new_name : patch->old_name);
03eb8f8a 2699 fragment = fragment->next;
3cd4f5e8 2700 }
3cd4f5e8 2701 switch (fragment->binary_patch_method) {
0660626c 2702 case BINARY_DELTA_DEFLATED:
b94f2eda 2703 dst = patch_delta(img->buf, img->len, fragment->patch,
c7f9cb14
PH
2704 fragment->size, &len);
2705 if (!dst)
2706 return -1;
b94f2eda
JH
2707 clear_image(img);
2708 img->buf = dst;
2709 img->len = len;
c7f9cb14 2710 return 0;
0660626c 2711 case BINARY_LITERAL_DEFLATED:
b94f2eda
JH
2712 clear_image(img);
2713 img->len = fragment->size;
2714 img->buf = xmalloc(img->len+1);
2715 memcpy(img->buf, fragment->patch, img->len);
2716 img->buf[img->len] = '\0';
c7f9cb14 2717 return 0;
0660626c 2718 }
c7f9cb14 2719 return -1;
0660626c
JH
2720}
2721
b94f2eda 2722static int apply_binary(struct image *img, struct patch *patch)
3cca928d 2723{
011f4274 2724 const char *name = patch->old_name ? patch->old_name : patch->new_name;
051308f6 2725 unsigned char sha1[20];
011f4274 2726
81bf96bb
JH
2727 /*
2728 * For safety, we require patch index line to contain
051308f6
JH
2729 * full 40-byte textual SHA1 for old and new, at least for now.
2730 */
2731 if (strlen(patch->old_sha1_prefix) != 40 ||
2732 strlen(patch->new_sha1_prefix) != 40 ||
2733 get_sha1_hex(patch->old_sha1_prefix, sha1) ||
2734 get_sha1_hex(patch->new_sha1_prefix, sha1))
2735 return error("cannot apply binary patch to '%s' "
2736 "without full index line", name);
011f4274 2737
051308f6 2738 if (patch->old_name) {
81bf96bb
JH
2739 /*
2740 * See if the old one matches what the patch
051308f6 2741 * applies to.
011f4274 2742 */
b94f2eda 2743 hash_sha1_file(img->buf, img->len, blob_type, sha1);
051308f6
JH
2744 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
2745 return error("the patch applies to '%s' (%s), "
2746 "which does not match the "
2747 "current contents.",
2748 name, sha1_to_hex(sha1));
2749 }
2750 else {
2751 /* Otherwise, the old one must be empty. */
b94f2eda 2752 if (img->len)
051308f6
JH
2753 return error("the patch applies to an empty "
2754 "'%s' but it is not empty", name);
2755 }
011f4274 2756
0660626c 2757 get_sha1_hex(patch->new_sha1_prefix, sha1);
0bef57ee 2758 if (is_null_sha1(sha1)) {
b94f2eda 2759 clear_image(img);
051308f6 2760 return 0; /* deletion patch */
0660626c 2761 }
011f4274 2762
051308f6 2763 if (has_sha1_file(sha1)) {
0660626c 2764 /* We already have the postimage */
21666f1a 2765 enum object_type type;
051308f6 2766 unsigned long size;
c7f9cb14 2767 char *result;
051308f6 2768
c7f9cb14
PH
2769 result = read_sha1_file(sha1, &type, &size);
2770 if (!result)
051308f6
JH
2771 return error("the necessary postimage %s for "
2772 "'%s' cannot be read",
2773 patch->new_sha1_prefix, name);
b94f2eda
JH
2774 clear_image(img);
2775 img->buf = result;
2776 img->len = size;
c7f9cb14 2777 } else {
81bf96bb
JH
2778 /*
2779 * We have verified buf matches the preimage;
0660626c
JH
2780 * apply the patch data to it, which is stored
2781 * in the patch->fragments->{patch,size}.
011f4274 2782 */
b94f2eda 2783 if (apply_binary_fragment(img, patch))
051308f6
JH
2784 return error("binary patch does not apply to '%s'",
2785 name);
011f4274 2786
051308f6 2787 /* verify that the result matches */
b94f2eda 2788 hash_sha1_file(img->buf, img->len, blob_type, sha1);
051308f6 2789 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
c7f9cb14
PH
2790 return error("binary patch to '%s' creates incorrect result (expecting %s, got %s)",
2791 name, patch->new_sha1_prefix, sha1_to_hex(sha1));
011f4274 2792 }
3cca928d 2793
051308f6
JH
2794 return 0;
2795}
2796
b94f2eda 2797static int apply_fragments(struct image *img, struct patch *patch)
051308f6
JH
2798{
2799 struct fragment *frag = patch->fragments;
2800 const char *name = patch->old_name ? patch->old_name : patch->new_name;
cf1b7869
JH
2801 unsigned ws_rule = patch->ws_rule;
2802 unsigned inaccurate_eof = patch->inaccurate_eof;
334f8cb2 2803 int nth = 0;
051308f6
JH
2804
2805 if (patch->is_binary)
b94f2eda 2806 return apply_binary(img, patch);
051308f6 2807
3cca928d 2808 while (frag) {
334f8cb2
JH
2809 nth++;
2810 if (apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {
57dc397c
JH
2811 error("patch failed: %s:%ld", name, frag->oldpos);
2812 if (!apply_with_reject)
2813 return -1;
2814 frag->rejected = 1;
2815 }
3cca928d
LT
2816 frag = frag->next;
2817 }
30996652 2818 return 0;
3cca928d
LT
2819}
2820
c7f9cb14 2821static int read_file_or_gitlink(struct cache_entry *ce, struct strbuf *buf)
e06c5a6c
SV
2822{
2823 if (!ce)
2824 return 0;
2825
7a51ed66 2826 if (S_ISGITLINK(ce->ce_mode)) {
c7f9cb14
PH
2827 strbuf_grow(buf, 100);
2828 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(ce->sha1));
e06c5a6c
SV
2829 } else {
2830 enum object_type type;
c7f9cb14
PH
2831 unsigned long sz;
2832 char *result;
2833
2834 result = read_sha1_file(ce->sha1, &type, &sz);
2835 if (!result)
e06c5a6c 2836 return -1;
c7f9cb14
PH
2837 /* XXX read_sha1_file NUL-terminates */
2838 strbuf_attach(buf, result, sz, sz + 1);
e06c5a6c
SV
2839 }
2840 return 0;
2841}
2842
7a07841c
DZ
2843static struct patch *in_fn_table(const char *name)
2844{
c455c87c 2845 struct string_list_item *item;
7a07841c
DZ
2846
2847 if (name == NULL)
2848 return NULL;
2849
e8c8b713 2850 item = string_list_lookup(&fn_table, name);
7a07841c
DZ
2851 if (item != NULL)
2852 return (struct patch *)item->util;
2853
2854 return NULL;
2855}
2856
7fac0eef
MK
2857/*
2858 * item->util in the filename table records the status of the path.
2859 * Usually it points at a patch (whose result records the contents
2860 * of it after applying it), but it could be PATH_WAS_DELETED for a
2861 * path that a previously applied patch has already removed.
2862 */
2863 #define PATH_TO_BE_DELETED ((struct patch *) -2)
2864#define PATH_WAS_DELETED ((struct patch *) -1)
2865
2866static int to_be_deleted(struct patch *patch)
2867{
2868 return patch == PATH_TO_BE_DELETED;
2869}
2870
2871static int was_deleted(struct patch *patch)
2872{
2873 return patch == PATH_WAS_DELETED;
2874}
2875
7a07841c
DZ
2876static void add_to_fn_table(struct patch *patch)
2877{
c455c87c 2878 struct string_list_item *item;
7a07841c
DZ
2879
2880 /*
2881 * Always add new_name unless patch is a deletion
2882 * This should cover the cases for normal diffs,
2883 * file creations and copies
2884 */
2885 if (patch->new_name != NULL) {
78a395d3 2886 item = string_list_insert(&fn_table, patch->new_name);
7a07841c
DZ
2887 item->util = patch;
2888 }
2889
2890 /*
2891 * store a failure on rename/deletion cases because
2892 * later chunks shouldn't patch old names
2893 */
2894 if ((patch->new_name == NULL) || (patch->is_rename)) {
78a395d3 2895 item = string_list_insert(&fn_table, patch->old_name);
7fac0eef
MK
2896 item->util = PATH_WAS_DELETED;
2897 }
2898}
2899
2900static void prepare_fn_table(struct patch *patch)
2901{
2902 /*
2903 * store information about incoming file deletion
2904 */
2905 while (patch) {
2906 if ((patch->new_name == NULL) || (patch->is_rename)) {
2907 struct string_list_item *item;
78a395d3 2908 item = string_list_insert(&fn_table, patch->old_name);
7fac0eef
MK
2909 item->util = PATH_TO_BE_DELETED;
2910 }
2911 patch = patch->next;
7a07841c
DZ
2912 }
2913}
2914
04e4888e 2915static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce)
3cca928d 2916{
f285a2d7 2917 struct strbuf buf = STRBUF_INIT;
b94f2eda
JH
2918 struct image image;
2919 size_t len;
2920 char *img;
7a07841c 2921 struct patch *tpatch;
3cca928d 2922
a9a3e82e 2923 if (!(patch->is_copy || patch->is_rename) &&
7fac0eef
MK
2924 (tpatch = in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {
2925 if (was_deleted(tpatch)) {
7a07841c
DZ
2926 return error("patch %s has been renamed/deleted",
2927 patch->old_name);
2928 }
2929 /* We have a patched copy in memory use that */
2930 strbuf_add(&buf, tpatch->result, tpatch->resultsize);
2931 } else if (cached) {
c7f9cb14 2932 if (read_file_or_gitlink(ce, &buf))
e06c5a6c 2933 return error("read of %s failed", patch->old_name);
e06c5a6c
SV
2934 } else if (patch->old_name) {
2935 if (S_ISGITLINK(patch->old_mode)) {
c7f9cb14
PH
2936 if (ce) {
2937 read_file_or_gitlink(ce, &buf);
2938 } else {
e06c5a6c
SV
2939 /*
2940 * There is no way to apply subproject
2941 * patch without looking at the index.
2942 */
2943 patch->fragments = NULL;
e06c5a6c 2944 }
c7f9cb14
PH
2945 } else {
2946 if (read_old_data(st, patch->old_name, &buf))
2947 return error("read of %s failed", patch->old_name);
04e4888e
JH
2948 }
2949 }
6e7c92a9 2950
b94f2eda
JH
2951 img = strbuf_detach(&buf, &len);
2952 prepare_image(&image, img, len, !patch->is_binary);
2953
2954 if (apply_fragments(&image, patch) < 0)
57dc397c 2955 return -1; /* note with --reject this succeeds. */
b94f2eda
JH
2956 patch->result = image.buf;
2957 patch->resultsize = image.len;
7a07841c 2958 add_to_fn_table(patch);
b94f2eda 2959 free(image.line_allocated);
5aa7d94c 2960
4be60962 2961 if (0 < patch->is_delete && patch->resultsize)
5aa7d94c
LT
2962 return error("removal patch leaves file contents");
2963
3cca928d
LT
2964 return 0;
2965}
2966
64cab591
JH
2967static int check_to_create_blob(const char *new_name, int ok_if_exists)
2968{
2969 struct stat nst;
2970 if (!lstat(new_name, &nst)) {
2971 if (S_ISDIR(nst.st_mode) || ok_if_exists)
2972 return 0;
2973 /*
2974 * A leading component of new_name might be a symlink
2975 * that is going to be removed with this patch, but
2976 * still pointing at somewhere that has the path.
2977 * In such a case, path "new_name" does not exist as
2978 * far as git is concerned.
2979 */
57199892 2980 if (has_symlink_leading_path(new_name, strlen(new_name)))
64cab591
JH
2981 return 0;
2982
2983 return error("%s: already exists in working directory", new_name);
2984 }
2985 else if ((errno != ENOENT) && (errno != ENOTDIR))
2986 return error("%s: %s", new_name, strerror(errno));
2987 return 0;
2988}
2989
e06c5a6c
SV
2990static int verify_index_match(struct cache_entry *ce, struct stat *st)
2991{
7a51ed66 2992 if (S_ISGITLINK(ce->ce_mode)) {
e06c5a6c
SV
2993 if (!S_ISDIR(st->st_mode))
2994 return -1;
2995 return 0;
2996 }
56cac48c 2997 return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
e06c5a6c
SV
2998}
2999
5c47f4c6 3000static int check_preimage(struct patch *patch, struct cache_entry **ce, struct stat *st)
fab2c257
LT
3001{
3002 const char *old_name = patch->old_name;
a9a3e82e 3003 struct patch *tpatch = NULL;
5c47f4c6
JH
3004 int stat_ret = 0;
3005 unsigned st_mode = 0;
e06c5a6c
SV
3006
3007 /*
3008 * Make sure that we do not have local modifications from the
3009 * index when we are looking at the index. Also make sure
3010 * we have the preimage file to be patched in the work tree,
3011 * unless --cached, which tells git to apply only in the index.
3012 */
5c47f4c6
JH
3013 if (!old_name)
3014 return 0;
04e4888e 3015
5c47f4c6 3016 assert(patch->is_new <= 0);
a9a3e82e
JH
3017
3018 if (!(patch->is_copy || patch->is_rename) &&
7fac0eef
MK
3019 (tpatch = in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {
3020 if (was_deleted(tpatch))
7a07841c 3021 return error("%s: has been deleted/renamed", old_name);
7a07841c
DZ
3022 st_mode = tpatch->new_mode;
3023 } else if (!cached) {
5c47f4c6
JH
3024 stat_ret = lstat(old_name, st);
3025 if (stat_ret && errno != ENOENT)
3026 return error("%s: %s", old_name, strerror(errno));
3027 }
a9a3e82e 3028
7fac0eef
MK
3029 if (to_be_deleted(tpatch))
3030 tpatch = NULL;
3031
7a07841c 3032 if (check_index && !tpatch) {
5c47f4c6
JH
3033 int pos = cache_name_pos(old_name, strlen(old_name));
3034 if (pos < 0) {
3035 if (patch->is_new < 0)
3036 goto is_new;
3037 return error("%s: does not exist in index", old_name);
3038 }
3039 *ce = active_cache[pos];
3040 if (stat_ret < 0) {
3041 struct checkout costate;
3042 /* checkout */
54fd955c 3043 memset(&costate, 0, sizeof(costate));
5c47f4c6 3044 costate.base_dir = "";
5c47f4c6
JH
3045 costate.refresh_cache = 1;
3046 if (checkout_entry(*ce, &costate, NULL) ||
3047 lstat(old_name, st))
3048 return -1;
3049 }
3050 if (!cached && verify_index_match(*ce, st))
3051 return error("%s: does not match index", old_name);
3052 if (cached)
3053 st_mode = (*ce)->ce_mode;
3054 } else if (stat_ret < 0) {
3cca928d 3055 if (patch->is_new < 0)
5c47f4c6
JH
3056 goto is_new;
3057 return error("%s: %s", old_name, strerror(errno));
fab2c257 3058 }
a577284a 3059
e1e43898 3060 if (!cached && !tpatch)
5c47f4c6
JH
3061 st_mode = ce_mode_from_stat(*ce, st->st_mode);
3062
3063 if (patch->is_new < 0)
3064 patch->is_new = 0;
3065 if (!patch->old_mode)
3066 patch->old_mode = st_mode;
3067 if ((st_mode ^ patch->old_mode) & S_IFMT)
3068 return error("%s: wrong type", old_name);
3069 if (st_mode != patch->old_mode)
eca2a8f0 3070 warning("%s has type %o, expected %o",
5c47f4c6 3071 old_name, st_mode, patch->old_mode);
a15080e5 3072 if (!patch->new_mode && !patch->is_delete)
1f7903a3 3073 patch->new_mode = st_mode;
5c47f4c6
JH
3074 return 0;
3075
3076 is_new:
3077 patch->is_new = 1;
3078 patch->is_delete = 0;
3079 patch->old_name = NULL;
3080 return 0;
3081}
3082
7a07841c 3083static int check_patch(struct patch *patch)
5c47f4c6
JH
3084{
3085 struct stat st;
3086 const char *old_name = patch->old_name;
3087 const char *new_name = patch->new_name;
3088 const char *name = old_name ? old_name : new_name;
3089 struct cache_entry *ce = NULL;
7fac0eef 3090 struct patch *tpatch;
5c47f4c6
JH
3091 int ok_if_exists;
3092 int status;
3093
3094 patch->rejected = 1; /* we will drop this after we succeed */
3095
3096 status = check_preimage(patch, &ce, &st);
3097 if (status)
3098 return status;
3099 old_name = patch->old_name;
3100
7fac0eef
MK
3101 if ((tpatch = in_fn_table(new_name)) &&
3102 (was_deleted(tpatch) || to_be_deleted(tpatch)))
81bf96bb
JH
3103 /*
3104 * A type-change diff is always split into a patch to
7f95aef2
JH
3105 * delete old, immediately followed by a patch to
3106 * create new (see diff.c::run_diff()); in such a case
3107 * it is Ok that the entry to be deleted by the
3108 * previous patch is still in the working tree and in
3109 * the index.
3110 */
3111 ok_if_exists = 1;
3112 else
3113 ok_if_exists = 0;
3114
4be60962
JH
3115 if (new_name &&
3116 ((0 < patch->is_new) | (0 < patch->is_rename) | patch->is_copy)) {
7f95aef2
JH
3117 if (check_index &&
3118 cache_name_pos(new_name, strlen(new_name)) >= 0 &&
3119 !ok_if_exists)
a577284a 3120 return error("%s: already exists in index", new_name);
d91d4c2c 3121 if (!cached) {
64cab591
JH
3122 int err = check_to_create_blob(new_name, ok_if_exists);
3123 if (err)
3124 return err;
d91d4c2c 3125 }
35cc4bcd 3126 if (!patch->new_mode) {
4be60962 3127 if (0 < patch->is_new)
35cc4bcd
JS
3128 patch->new_mode = S_IFREG | 0644;
3129 else
3130 patch->new_mode = patch->old_mode;
3131 }
fab2c257 3132 }
3cca928d
LT
3133
3134 if (new_name && old_name) {
3135 int same = !strcmp(old_name, new_name);
3136 if (!patch->new_mode)
3137 patch->new_mode = patch->old_mode;
3138 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
3139 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
3140 patch->new_mode, new_name, patch->old_mode,
3141 same ? "" : " of ", same ? "" : old_name);
04e4888e 3142 }
3cca928d 3143
04e4888e 3144 if (apply_data(patch, &st, ce) < 0)
011f4274 3145 return error("%s: patch does not apply", name);
57dc397c 3146 patch->rejected = 0;
a577284a 3147 return 0;
fab2c257
LT
3148}
3149
a577284a 3150static int check_patch_list(struct patch *patch)
19c58fb8 3151{
60b7f38e 3152 int err = 0;
a577284a 3153
7fac0eef 3154 prepare_fn_table(patch);
7a07841c 3155 while (patch) {
a2bf404e
JH
3156 if (apply_verbosely)
3157 say_patch_name(stderr,
3158 "Checking patch ", patch, "...\n");
7a07841c
DZ
3159 err |= check_patch(patch);
3160 patch = patch->next;
7f95aef2 3161 }
60b7f38e 3162 return err;
a577284a
LT
3163}
3164
ece7b749
JS
3165/* This function tries to read the sha1 from the current index */
3166static int get_current_sha1(const char *path, unsigned char *sha1)
3167{
3168 int pos;
3169
3170 if (read_cache() < 0)
3171 return -1;
3172 pos = cache_name_pos(path, strlen(path));
3173 if (pos < 0)
3174 return -1;
3175 hashcpy(sha1, active_cache[pos]->sha1);
3176 return 0;
3177}
3178
7a988699
JS
3179/* Build an index that contains the just the files needed for a 3way merge */
3180static void build_fake_ancestor(struct patch *list, const char *filename)
2cf67f1e
JH
3181{
3182 struct patch *patch;
2af202be 3183 struct index_state result = { NULL };
7a988699 3184 int fd;
2cf67f1e
JH
3185
3186 /* Once we start supporting the reverse patch, it may be
3187 * worth showing the new sha1 prefix, but until then...
3188 */
3189 for (patch = list; patch; patch = patch->next) {
3190 const unsigned char *sha1_ptr;
3191 unsigned char sha1[20];
7a988699 3192 struct cache_entry *ce;
2cf67f1e
JH
3193 const char *name;
3194
3195 name = patch->old_name ? patch->old_name : patch->new_name;
4be60962 3196 if (0 < patch->is_new)
7a988699 3197 continue;
2cf67f1e 3198 else if (get_sha1(patch->old_sha1_prefix, sha1))
ece7b749
JS
3199 /* git diff has no index line for mode/type changes */
3200 if (!patch->lines_added && !patch->lines_deleted) {
18cdf802 3201 if (get_current_sha1(patch->old_name, sha1))
ece7b749
JS
3202 die("mode change for %s, which is not "
3203 "in current HEAD", name);
3204 sha1_ptr = sha1;
3205 } else
3206 die("sha1 information is lacking or useless "
3207 "(%s).", name);
2cf67f1e
JH
3208 else
3209 sha1_ptr = sha1;
22943f1a 3210
7a988699 3211 ce = make_cache_entry(patch->old_mode, sha1_ptr, name, 0, 0);
048f2762
DP
3212 if (!ce)
3213 die("make_cache_entry failed for path '%s'", name);
7a988699
JS
3214 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))
3215 die ("Could not add %s to temporary index", name);
2cf67f1e 3216 }
7a988699
JS
3217
3218 fd = open(filename, O_WRONLY | O_CREAT, 0666);
3219 if (fd < 0 || write_index(&result, fd) || close(fd))
3220 die ("Could not write temporary index to %s", filename);
3221
3222 discard_index(&result);
2cf67f1e
JH
3223}
3224
a577284a
LT
3225static void stat_patch_list(struct patch *patch)
3226{
3227 int files, adds, dels;
3228
3229 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
3230 files++;
3231 adds += patch->lines_added;
3232 dels += patch->lines_deleted;
3233 show_stats(patch);
3234 }
3235
3236 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
3f40315a
LT
3237}
3238
7d8b7c21
JH
3239static void numstat_patch_list(struct patch *patch)
3240{
3241 for ( ; patch; patch = patch->next) {
3242 const char *name;
49e3343c 3243 name = patch->new_name ? patch->new_name : patch->old_name;
ef58d958
JH
3244 if (patch->is_binary)
3245 printf("-\t-\t");
3246 else
663af342
PH
3247 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
3248 write_name_quoted(name, stdout, line_termination);
7d8b7c21
JH
3249 }
3250}
3251
96c912a4
JH
3252static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
3253{
3254 if (mode)
3255 printf(" %s mode %06o %s\n", newdelete, mode, name);
3256 else
3257 printf(" %s %s\n", newdelete, name);
3258}
3259
3260static void show_mode_change(struct patch *p, int show_name)
3261{
3262 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
3263 if (show_name)
3264 printf(" mode change %06o => %06o %s\n",
3265 p->old_mode, p->new_mode, p->new_name);
3266 else
3267 printf(" mode change %06o => %06o\n",
3268 p->old_mode, p->new_mode);
3269 }
3270}
3271
3272static void show_rename_copy(struct patch *p)
3273{
3274 const char *renamecopy = p->is_rename ? "rename" : "copy";
3275 const char *old, *new;
3276
3277 /* Find common prefix */
3278 old = p->old_name;
3279 new = p->new_name;
3280 while (1) {
3281 const char *slash_old, *slash_new;
3282 slash_old = strchr(old, '/');
3283 slash_new = strchr(new, '/');
3284 if (!slash_old ||
3285 !slash_new ||
3286 slash_old - old != slash_new - new ||
3287 memcmp(old, new, slash_new - new))
3288 break;
3289 old = slash_old + 1;
3290 new = slash_new + 1;
3291 }
3292 /* p->old_name thru old is the common prefix, and old and new
3293 * through the end of names are renames
3294 */
3295 if (old != p->old_name)
3296 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
e30e814d 3297 (int)(old - p->old_name), p->old_name,
96c912a4
JH
3298 old, new, p->score);
3299 else
3300 printf(" %s %s => %s (%d%%)\n", renamecopy,
3301 p->old_name, p->new_name, p->score);
3302 show_mode_change(p, 0);
3303}
3304
3305static void summary_patch_list(struct patch *patch)
3306{
3307 struct patch *p;
3308
3309 for (p = patch; p; p = p->next) {
3310 if (p->is_new)
3311 show_file_mode_name("create", p->new_mode, p->new_name);
3312 else if (p->is_delete)
3313 show_file_mode_name("delete", p->old_mode, p->old_name);
3314 else {
3315 if (p->is_rename || p->is_copy)
3316 show_rename_copy(p);
3317 else {
3318 if (p->score) {
3319 printf(" rewrite %s (%d%%)\n",
3320 p->new_name, p->score);
3321 show_mode_change(p, 0);
3322 }
3323 else
3324 show_mode_change(p, 1);
3325 }
3326 }
3327 }
3328}
3329
3f40315a
LT
3330static void patch_stats(struct patch *patch)
3331{
3332 int lines = patch->lines_added + patch->lines_deleted;
3333
3334 if (lines > max_change)
3335 max_change = lines;
3336 if (patch->old_name) {
22943f1a
JH
3337 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
3338 if (!len)
3339 len = strlen(patch->old_name);
3f40315a
LT
3340 if (len > max_len)
3341 max_len = len;
3342 }
3343 if (patch->new_name) {
22943f1a
JH
3344 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
3345 if (!len)
3346 len = strlen(patch->new_name);
3f40315a
LT
3347 if (len > max_len)
3348 max_len = len;
3349 }
19c58fb8
LT
3350}
3351
aea19457 3352static void remove_file(struct patch *patch, int rmdir_empty)
5aa7d94c 3353{
7da3bf37 3354 if (update_index) {
5aa7d94c
LT
3355 if (remove_file_from_cache(patch->old_name) < 0)
3356 die("unable to remove %s from index", patch->old_name);
3357 }
d234b21c 3358 if (!cached) {
80d706af 3359 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
175a4948 3360 remove_path(patch->old_name);
d234b21c
AJ
3361 }
3362 }
5aa7d94c
LT
3363}
3364
3365static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
3366{
3367 struct stat st;
3368 struct cache_entry *ce;
3369 int namelen = strlen(path);
3370 unsigned ce_size = cache_entry_size(namelen);
3371
7da3bf37 3372 if (!update_index)
5aa7d94c
LT
3373 return;
3374
90321c10 3375 ce = xcalloc(1, ce_size);
5aa7d94c
LT
3376 memcpy(ce->name, path, namelen);
3377 ce->ce_mode = create_ce_mode(mode);
7a51ed66 3378 ce->ce_flags = namelen;
e06c5a6c
SV
3379 if (S_ISGITLINK(mode)) {
3380 const char *s = buf;
3381
3382 if (get_sha1_hex(s + strlen("Subproject commit "), ce->sha1))
3383 die("corrupt patch for subproject %s", path);
3384 } else {
3385 if (!cached) {
3386 if (lstat(path, &st) < 0)
0721c314
TR
3387 die_errno("unable to stat newly created file '%s'",
3388 path);
e06c5a6c
SV
3389 fill_stat_cache_info(ce, &st);
3390 }
3391 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
3392 die("unable to create backing store for newly created file %s", path);
04e4888e 3393 }
5aa7d94c
LT
3394 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
3395 die("unable to add cache entry for %s", path);
3396}
3397
1b668341
LT
3398static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
3399{
ac78e548 3400 int fd;
f285a2d7 3401 struct strbuf nbuf = STRBUF_INIT;
1b668341 3402
e06c5a6c
SV
3403 if (S_ISGITLINK(mode)) {
3404 struct stat st;
3405 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
3406 return 0;
3407 return mkdir(path, 0777);
3408 }
3409
78a8d641 3410 if (has_symlinks && S_ISLNK(mode))
2c71810b
JH
3411 /* Although buf:size is counted string, it also is NUL
3412 * terminated.
3413 */
1b668341 3414 return symlink(buf, path);
cc96fd09
JH
3415
3416 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
3417 if (fd < 0)
3418 return -1;
3419
5ecd293d
PH
3420 if (convert_to_working_tree(path, buf, size, &nbuf)) {
3421 size = nbuf.len;
3422 buf = nbuf.buf;
1b668341 3423 }
c7f9cb14
PH
3424 write_or_die(fd, buf, size);
3425 strbuf_release(&nbuf);
ac78e548 3426
1b668341 3427 if (close(fd) < 0)
d824cbba 3428 die_errno("closing file '%s'", path);
1b668341
LT
3429 return 0;
3430}
3431
5c8af185
LT
3432/*
3433 * We optimistically assume that the directories exist,
3434 * which is true 99% of the time anyway. If they don't,
3435 * we create them and try again.
3436 */
8361e1d4 3437static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
5c8af185 3438{
04e4888e
JH
3439 if (cached)
3440 return;
1b668341
LT
3441 if (!try_create_file(path, mode, buf, size))
3442 return;
5c8af185 3443
1b668341 3444 if (errno == ENOENT) {
8361e1d4
JR
3445 if (safe_create_leading_directories(path))
3446 return;
1b668341
LT
3447 if (!try_create_file(path, mode, buf, size))
3448 return;
5c8af185 3449 }
5c8af185 3450
56ac168f 3451 if (errno == EEXIST || errno == EACCES) {
c28c571c
JH
3452 /* We may be trying to create a file where a directory
3453 * used to be.
3454 */
3455 struct stat st;
0afa7644 3456 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
c28c571c
JH
3457 errno = EEXIST;
3458 }
3459
1b668341
LT
3460 if (errno == EEXIST) {
3461 unsigned int nr = getpid();
5c8af185 3462
1b668341 3463 for (;;) {
9fa03c17
AR
3464 char newpath[PATH_MAX];
3465 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
1b668341
LT
3466 if (!try_create_file(newpath, mode, buf, size)) {
3467 if (!rename(newpath, path))
3468 return;
691f1a28 3469 unlink_or_warn(newpath);
1b668341
LT
3470 break;
3471 }
3472 if (errno != EEXIST)
3473 break;
d9e08be9
AR
3474 ++nr;
3475 }
5c8af185 3476 }
0721c314 3477 die_errno("unable to write file '%s' mode %o", path, mode);
5c8af185
LT
3478}
3479
5aa7d94c
LT
3480static void create_file(struct patch *patch)
3481{
8361e1d4 3482 char *path = patch->new_name;
5aa7d94c
LT
3483 unsigned mode = patch->new_mode;
3484 unsigned long size = patch->resultsize;
3485 char *buf = patch->result;
3486
3487 if (!mode)
3488 mode = S_IFREG | 0644;
03ac6e64 3489 create_one_file(path, mode, buf, size);
1b668341 3490 add_index_file(path, mode, buf, size);
5aa7d94c
LT
3491}
3492
eed46644
JH
3493/* phase zero is to remove, phase one is to create */
3494static void write_out_one_result(struct patch *patch, int phase)
5aa7d94c
LT
3495{
3496 if (patch->is_delete > 0) {
eed46644 3497 if (phase == 0)
aea19457 3498 remove_file(patch, 1);
5aa7d94c
LT
3499 return;
3500 }
3501 if (patch->is_new > 0 || patch->is_copy) {
eed46644
JH
3502 if (phase == 1)
3503 create_file(patch);
5aa7d94c
LT
3504 return;
3505 }
3506 /*
3507 * Rename or modification boils down to the same
3508 * thing: remove the old, write the new
3509 */
eed46644 3510 if (phase == 0)
93969438 3511 remove_file(patch, patch->is_rename);
eed46644 3512 if (phase == 1)
57dc397c 3513 create_file(patch);
5aa7d94c
LT
3514}
3515
57dc397c
JH
3516static int write_out_one_reject(struct patch *patch)
3517{
82e2765f
JH
3518 FILE *rej;
3519 char namebuf[PATH_MAX];
57dc397c 3520 struct fragment *frag;
82e2765f 3521 int cnt = 0;
57dc397c 3522
82e2765f 3523 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
57dc397c
JH
3524 if (!frag->rejected)
3525 continue;
82e2765f
JH
3526 cnt++;
3527 }
3528
a2bf404e
JH
3529 if (!cnt) {
3530 if (apply_verbosely)
3531 say_patch_name(stderr,
3532 "Applied patch ", patch, " cleanly.\n");
82e2765f 3533 return 0;
a2bf404e 3534 }
82e2765f
JH
3535
3536 /* This should not happen, because a removal patch that leaves
3537 * contents are marked "rejected" at the patch level.
3538 */
3539 if (!patch->new_name)
3540 die("internal error");
3541
a2bf404e
JH
3542 /* Say this even without --verbose */
3543 say_patch_name(stderr, "Applying patch ", patch, " with");
3544 fprintf(stderr, " %d rejects...\n", cnt);
3545
82e2765f
JH
3546 cnt = strlen(patch->new_name);
3547 if (ARRAY_SIZE(namebuf) <= cnt + 5) {
3548 cnt = ARRAY_SIZE(namebuf) - 5;
eca2a8f0 3549 warning("truncating .rej filename to %.*s.rej",
82e2765f
JH
3550 cnt - 1, patch->new_name);
3551 }
3552 memcpy(namebuf, patch->new_name, cnt);
3553 memcpy(namebuf + cnt, ".rej", 5);
3554
3555 rej = fopen(namebuf, "w");
3556 if (!rej)
3557 return error("cannot open %s: %s", namebuf, strerror(errno));
3558
3559 /* Normal git tools never deal with .rej, so do not pretend
3560 * this is a git patch by saying --git nor give extended
3561 * headers. While at it, maybe please "kompare" that wants
3562 * the trailing TAB and some garbage at the end of line ;-).
3563 */
3564 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
3565 patch->new_name, patch->new_name);
0e9ee323 3566 for (cnt = 1, frag = patch->fragments;
82e2765f
JH
3567 frag;
3568 cnt++, frag = frag->next) {
3569 if (!frag->rejected) {
3570 fprintf(stderr, "Hunk #%d applied cleanly.\n", cnt);
3571 continue;
57dc397c 3572 }
82e2765f
JH
3573 fprintf(stderr, "Rejected hunk #%d.\n", cnt);
3574 fprintf(rej, "%.*s", frag->size, frag->patch);
57dc397c 3575 if (frag->patch[frag->size-1] != '\n')
82e2765f 3576 fputc('\n', rej);
57dc397c 3577 }
82e2765f
JH
3578 fclose(rej);
3579 return -1;
5aa7d94c
LT
3580}
3581
57dc397c 3582static int write_out_results(struct patch *list, int skipped_patch)
5aa7d94c 3583{
eed46644 3584 int phase;
57dc397c
JH
3585 int errs = 0;
3586 struct patch *l;
eed46644 3587
d854f783 3588 if (!list && !skipped_patch)
57dc397c 3589 return error("No changes");
f7b79707 3590
eed46644 3591 for (phase = 0; phase < 2; phase++) {
57dc397c 3592 l = list;
eed46644 3593 while (l) {
57dc397c
JH
3594 if (l->rejected)
3595 errs = 1;
82e2765f 3596 else {
57dc397c 3597 write_out_one_result(l, phase);
82e2765f 3598 if (phase == 1 && write_out_one_reject(l))
57dc397c
JH
3599 errs = 1;
3600 }
eed46644
JH
3601 l = l->next;
3602 }
5aa7d94c 3603 }
57dc397c 3604 return errs;
5aa7d94c
LT
3605}
3606
021b6e45 3607static struct lock_file lock_file;
5aa7d94c 3608
6ecb1ee2
JH
3609static struct string_list limit_by_name;
3610static int has_include;
3611static void add_name_limit(const char *name, int exclude)
3612{
3613 struct string_list_item *it;
3614
1d2f80fa 3615 it = string_list_append(&limit_by_name, name);
6ecb1ee2
JH
3616 it->util = exclude ? NULL : (void *) 1;
3617}
d854f783
JH
3618
3619static int use_patch(struct patch *p)
3620{
c7c81b3a 3621 const char *pathname = p->new_name ? p->new_name : p->old_name;
6ecb1ee2
JH
3622 int i;
3623
3624 /* Paths outside are not touched regardless of "--include" */
edf2e370
JH
3625 if (0 < prefix_length) {
3626 int pathlen = strlen(pathname);
3627 if (pathlen <= prefix_length ||
3628 memcmp(prefix, pathname, prefix_length))
3629 return 0;
3630 }
6ecb1ee2
JH
3631
3632 /* See if it matches any of exclude/include rule */
3633 for (i = 0; i < limit_by_name.nr; i++) {
3634 struct string_list_item *it = &limit_by_name.items[i];
3635 if (!fnmatch(it->string, pathname, 0))
3636 return (it->util != NULL);
3637 }
3638
3639 /*
3640 * If we had any include, a path that does not match any rule is
3641 * not used. Otherwise, we saw bunch of exclude rules (or none)
3642 * and such a path is used.
3643 */
3644 return !has_include;
d854f783
JH
3645}
3646
6ecb1ee2 3647
eac70c4f 3648static void prefix_one(char **name)
56185f49 3649{
eac70c4f
JS
3650 char *old_name = *name;
3651 if (!old_name)
3652 return;
3653 *name = xstrdup(prefix_filename(prefix, prefix_length, *name));
3654 free(old_name);
56185f49
JH
3655}
3656
3657static void prefix_patches(struct patch *p)
3658{
9987d7c5 3659 if (!prefix || p->is_toplevel_relative)
56185f49
JH
3660 return;
3661 for ( ; p; p = p->next) {
6c912f5b
JH
3662 if (p->new_name == p->old_name) {
3663 char *prefixed = p->new_name;
3664 prefix_one(&prefixed);
3665 p->new_name = p->old_name = prefixed;
3666 }
3667 else {
eac70c4f 3668 prefix_one(&p->new_name);
6c912f5b
JH
3669 prefix_one(&p->old_name);
3670 }
56185f49
JH
3671 }
3672}
3673
c14b9d1e
JS
3674#define INACCURATE_EOF (1<<0)
3675#define RECOUNT (1<<1)
3676
3677static int apply_patch(int fd, const char *filename, int options)
c1bb9350 3678{
9a76adeb 3679 size_t offset;
f285a2d7 3680 struct strbuf buf = STRBUF_INIT;
19c58fb8 3681 struct patch *list = NULL, **listp = &list;
d854f783 3682 int skipped_patch = 0;
c1bb9350 3683
7a07841c 3684 /* FIXME - memory leak when using multiple patch files as inputs */
c455c87c 3685 memset(&fn_table, 0, sizeof(struct string_list));
b5767dd6 3686 patch_input_file = filename;
9a76adeb 3687 read_patch_file(&buf, fd);
c1bb9350 3688 offset = 0;
9a76adeb 3689 while (offset < buf.len) {
19c58fb8
LT
3690 struct patch *patch;
3691 int nr;
3692
90321c10 3693 patch = xcalloc(1, sizeof(*patch));
c14b9d1e
JS
3694 patch->inaccurate_eof = !!(options & INACCURATE_EOF);
3695 patch->recount = !!(options & RECOUNT);
f94bf440 3696 nr = parse_chunk(buf.buf + offset, buf.len - offset, patch);
c1bb9350
LT
3697 if (nr < 0)
3698 break;
f686d030 3699 if (apply_in_reverse)
e5a94313 3700 reverse_patches(patch);
56185f49
JH
3701 if (prefix)
3702 prefix_patches(patch);
d854f783
JH
3703 if (use_patch(patch)) {
3704 patch_stats(patch);
3705 *listp = patch;
3706 listp = &patch->next;
56185f49
JH
3707 }
3708 else {
d854f783
JH
3709 /* perhaps free it a bit better? */
3710 free(patch);
3711 skipped_patch++;
3712 }
c1bb9350 3713 offset += nr;
c1bb9350 3714 }
19c58fb8 3715
81bf96bb 3716 if (whitespace_error && (ws_error_action == die_on_ws_error))
b5767dd6
JH
3717 apply = 0;
3718
7da3bf37
JH
3719 update_index = check_index && apply;
3720 if (update_index && newfd < 0)
30ca07a2
JH
3721 newfd = hold_locked_index(&lock_file, 1);
3722
5aa7d94c
LT
3723 if (check_index) {
3724 if (read_cache() < 0)
3725 die("unable to read index file");
3726 }
3727
57dc397c
JH
3728 if ((check || apply) &&
3729 check_patch_list(list) < 0 &&
3730 !apply_with_reject)
a577284a
LT
3731 exit(1);
3732
57dc397c
JH
3733 if (apply && write_out_results(list, skipped_patch))
3734 exit(1);
5aa7d94c 3735
7a988699
JS
3736 if (fake_ancestor)
3737 build_fake_ancestor(list, fake_ancestor);
2cf67f1e 3738
a577284a
LT
3739 if (diffstat)
3740 stat_patch_list(list);
19c58fb8 3741
7d8b7c21
JH
3742 if (numstat)
3743 numstat_patch_list(list);
3744
96c912a4
JH
3745 if (summary)
3746 summary_patch_list(list);
3747
9a76adeb 3748 strbuf_release(&buf);
c1bb9350
LT
3749 return 0;
3750}
3751
ef90d6d4 3752static int git_apply_config(const char *var, const char *value, void *cb)
2ae1c53b 3753{
8e4c6aa1
SB
3754 if (!strcmp(var, "apply.whitespace"))
3755 return git_config_string(&apply_default_whitespace, var, value);
86c91f91
GB
3756 else if (!strcmp(var, "apply.ignorewhitespace"))
3757 return git_config_string(&apply_default_ignorewhitespace, var, value);
ef90d6d4 3758 return git_default_config(var, value, cb);
2ae1c53b
JH
3759}
3760
f26c4940
MV
3761static int option_parse_exclude(const struct option *opt,
3762 const char *arg, int unset)
3763{
3764 add_name_limit(arg, 1);
3765 return 0;
3766}
3767
3768static int option_parse_include(const struct option *opt,
3769 const char *arg, int unset)
3770{
3771 add_name_limit(arg, 0);
3772 has_include = 1;
3773 return 0;
3774}
3775
3776static int option_parse_p(const struct option *opt,
3777 const char *arg, int unset)
3778{
3779 p_value = atoi(arg);
3780 p_value_known = 1;
3781 return 0;
3782}
3783
3784static int option_parse_z(const struct option *opt,
3785 const char *arg, int unset)
3786{
3787 if (unset)
3788 line_termination = '\n';
3789 else
3790 line_termination = 0;
3791 return 0;
3792}
3793
86c91f91
GB
3794static int option_parse_space_change(const struct option *opt,
3795 const char *arg, int unset)
3796{
3797 if (unset)
3798 ws_ignore_action = ignore_ws_none;
3799 else
3800 ws_ignore_action = ignore_ws_change;
3801 return 0;
3802}
3803
f26c4940
MV
3804static int option_parse_whitespace(const struct option *opt,
3805 const char *arg, int unset)
3806{
3807 const char **whitespace_option = opt->value;
3808
3809 *whitespace_option = arg;
3810 parse_whitespace_option(arg);
3811 return 0;
3812}
3813
3814static int option_parse_directory(const struct option *opt,
3815 const char *arg, int unset)
3816{
3817 root_len = strlen(arg);
3818 if (root_len && arg[root_len - 1] != '/') {
3819 char *new_root;
3820 root = new_root = xmalloc(root_len + 2);
3821 strcpy(new_root, arg);
3822 strcpy(new_root + root_len++, "/");
3823 } else
3824 root = arg;
3825 return 0;
3826}
2ae1c53b 3827
d1ea8962 3828int cmd_apply(int argc, const char **argv, const char *prefix_)
c1bb9350
LT
3829{
3830 int i;
57dc397c 3831 int errs = 0;
d1ea8962 3832 int is_not_gitdir = !startup_info->have_repository;
f26c4940
MV
3833 int binary;
3834 int force_apply = 0;
3eaa38da 3835
2ae1c53b 3836 const char *whitespace_option = NULL;
c1bb9350 3837
f26c4940 3838 struct option builtin_apply_options[] = {
f26c4940 3839 { OPTION_CALLBACK, 0, "exclude", NULL, "path",
40bac151 3840 "don't apply changes matching the given path",
f26c4940
MV
3841 0, option_parse_exclude },
3842 { OPTION_CALLBACK, 0, "include", NULL, "path",
3843 "apply changes matching the given path",
3844 0, option_parse_include },
3845 { OPTION_CALLBACK, 'p', NULL, NULL, "num",
3846 "remove <num> leading slashes from traditional diff paths",
3847 0, option_parse_p },
3848 OPT_BOOLEAN(0, "no-add", &no_add,
3849 "ignore additions made by the patch"),
3850 OPT_BOOLEAN(0, "stat", &diffstat,
3851 "instead of applying the patch, output diffstat for the input"),
092927c1 3852 { OPTION_BOOLEAN, 0, "allow-binary-replacement", &binary,
34aec9f5
SB
3853 NULL, "old option, now no-op",
3854 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },
092927c1 3855 { OPTION_BOOLEAN, 0, "binary", &binary,
34aec9f5
SB
3856 NULL, "old option, now no-op",
3857 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },
f26c4940
MV
3858 OPT_BOOLEAN(0, "numstat", &numstat,
3859 "shows number of added and deleted lines in decimal notation"),
3860 OPT_BOOLEAN(0, "summary", &summary,
3861 "instead of applying the patch, output a summary for the input"),
3862 OPT_BOOLEAN(0, "check", &check,
3863 "instead of applying the patch, see if the patch is applicable"),
3864 OPT_BOOLEAN(0, "index", &check_index,
3865 "make sure the patch is applicable to the current index"),
3866 OPT_BOOLEAN(0, "cached", &cached,
3867 "apply a patch without touching the working tree"),
3868 OPT_BOOLEAN(0, "apply", &force_apply,
3869 "also apply the patch (use with --stat/--summary/--check)"),
df217ed6 3870 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor,
f26c4940
MV
3871 "build a temporary index based on embedded index information"),
3872 { OPTION_CALLBACK, 'z', NULL, NULL, NULL,
3873 "paths are separated with NUL character",
3874 PARSE_OPT_NOARG, option_parse_z },
3875 OPT_INTEGER('C', NULL, &p_context,
3876 "ensure at least <n> lines of context match"),
3877 { OPTION_CALLBACK, 0, "whitespace", &whitespace_option, "action",
3878 "detect new or modified lines that have whitespace errors",
3879 0, option_parse_whitespace },
86c91f91
GB
3880 { OPTION_CALLBACK, 0, "ignore-space-change", NULL, NULL,
3881 "ignore changes in whitespace when finding context",
3882 PARSE_OPT_NOARG, option_parse_space_change },
3883 { OPTION_CALLBACK, 0, "ignore-whitespace", NULL, NULL,
3884 "ignore changes in whitespace when finding context",
3885 PARSE_OPT_NOARG, option_parse_space_change },
f26c4940
MV
3886 OPT_BOOLEAN('R', "reverse", &apply_in_reverse,
3887 "apply the patch in reverse"),
3888 OPT_BOOLEAN(0, "unidiff-zero", &unidiff_zero,
3889 "don't expect at least one line of context"),
3890 OPT_BOOLEAN(0, "reject", &apply_with_reject,
3891 "leave the rejected hunks in corresponding *.rej files"),
fd03881a 3892 OPT__VERBOSE(&apply_verbosely, "be verbose"),
f26c4940
MV
3893 OPT_BIT(0, "inaccurate-eof", &options,
3894 "tolerate incorrectly detected missing new-line at the end of file",
3895 INACCURATE_EOF),
3896 OPT_BIT(0, "recount", &options,
3897 "do not trust the line counts in the hunk headers",
3898 RECOUNT),
3899 { OPTION_CALLBACK, 0, "directory", NULL, "root",
3900 "prepend <root> to all filenames",
3901 0, option_parse_directory },
3902 OPT_END()
3903 };
3904
d1ea8962 3905 prefix = prefix_;
dc7b2436 3906 prefix_length = prefix ? strlen(prefix) : 0;
ef90d6d4 3907 git_config(git_apply_config, NULL);
700ea479
JH
3908 if (apply_default_whitespace)
3909 parse_whitespace_option(apply_default_whitespace);
86c91f91
GB
3910 if (apply_default_ignorewhitespace)
3911 parse_ignorewhitespace_option(apply_default_ignorewhitespace);
67160271 3912
37782920 3913 argc = parse_options(argc, argv, prefix, builtin_apply_options,
f26c4940 3914 apply_usage, 0);
4c8d4c14 3915
f26c4940
MV
3916 if (apply_with_reject)
3917 apply = apply_verbosely = 1;
3918 if (!force_apply && (diffstat || numstat || summary || check || fake_ancestor))
3919 apply = 0;
3920 if (check_index && is_not_gitdir)
3921 die("--index outside a repository");
3922 if (cached) {
3923 if (is_not_gitdir)
3924 die("--cached outside a repository");
3925 check_index = 1;
3926 }
3927 for (i = 0; i < argc; i++) {
c1bb9350
LT
3928 const char *arg = argv[i];
3929 int fd;
3930
3931 if (!strcmp(arg, "-")) {
c14b9d1e 3932 errs |= apply_patch(0, "<stdin>", options);
4dfdbe10 3933 read_stdin = 0;
c1bb9350 3934 continue;
64912a67 3935 } else if (0 < prefix_length)
edf2e370
JH
3936 arg = prefix_filename(prefix, prefix_length, arg);
3937
c1bb9350
LT
3938 fd = open(arg, O_RDONLY);
3939 if (fd < 0)
d824cbba 3940 die_errno("can't open patch '%s'", arg);
4dfdbe10 3941 read_stdin = 0;
f21d6726 3942 set_default_whitespace_mode(whitespace_option);
c14b9d1e 3943 errs |= apply_patch(fd, arg, options);
c1bb9350
LT
3944 close(fd);
3945 }
f21d6726 3946 set_default_whitespace_mode(whitespace_option);
4dfdbe10 3947 if (read_stdin)
c14b9d1e 3948 errs |= apply_patch(0, "<stdin>", options);
fc96b7c9
JH
3949 if (whitespace_error) {
3950 if (squelch_whitespace_errors &&
3951 squelch_whitespace_errors < whitespace_error) {
3952 int squelched =
3953 whitespace_error - squelch_whitespace_errors;
eca2a8f0
MV
3954 warning("squelched %d "
3955 "whitespace error%s",
fc96b7c9
JH
3956 squelched,
3957 squelched == 1 ? "" : "s");
3958 }
81bf96bb 3959 if (ws_error_action == die_on_ws_error)
c94bf41c 3960 die("%d line%s add%s whitespace errors.",
fc96b7c9
JH
3961 whitespace_error,
3962 whitespace_error == 1 ? "" : "s",
3963 whitespace_error == 1 ? "s" : "");
d8c37945 3964 if (applied_after_fixing_ws && apply)
eca2a8f0
MV
3965 warning("%d line%s applied after"
3966 " fixing whitespace errors.",
c94bf41c
JH
3967 applied_after_fixing_ws,
3968 applied_after_fixing_ws == 1 ? "" : "s");
fc96b7c9 3969 else if (whitespace_error)
eca2a8f0 3970 warning("%d line%s add%s whitespace errors.",
fc96b7c9
JH
3971 whitespace_error,
3972 whitespace_error == 1 ? "" : "s",
3973 whitespace_error == 1 ? "s" : "");
3974 }
dbd0f7d3 3975
7da3bf37 3976 if (update_index) {
dbd0f7d3 3977 if (write_cache(newfd, active_cache, active_nr) ||
4ed7cd3a 3978 commit_locked_index(&lock_file))
021b6e45 3979 die("Unable to write new index file");
dbd0f7d3
EW
3980 }
3981
57dc397c 3982 return !!errs;
c1bb9350 3983}