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