]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/apply.c
Merge branch 'jm/maint-apply-detects-corrupt-patch-header' into maint
[thirdparty/git.git] / builtin / apply.c
CommitLineData
c1bb9350
LT
1/*
2 * apply.c
3 *
4 * Copyright (C) Linus Torvalds, 2005
5 *
6 * This applies patches on top of some (arbitrary) version of the SCM.
7 *
c1bb9350 8 */
c1bb9350 9#include "cache.h"
03ac6e64 10#include "cache-tree.h"
22943f1a 11#include "quote.h"
8e440259 12#include "blob.h"
051308f6 13#include "delta.h"
ac6245e3 14#include "builtin.h"
c455c87c 15#include "string-list.h"
175a4948 16#include "dir.h"
f26c4940 17#include "parse-options.h"
c1bb9350 18
a9486b02
PR
19/*
20 * --check turns on checking that the working tree matches the
21 * files that are being modified, but doesn't apply the patch
22 * --stat does just a diffstat, and doesn't actually apply
23 * --numstat does numeric diffstat, and doesn't actually apply
24 * --index-info shows the old and new index info for paths if available.
25 * --index updates the cache as well.
26 * --cached updates only the cache without ever touching the working tree.
27 */
edf2e370
JH
28static const char *prefix;
29static int prefix_length = -1;
dbd0f7d3 30static int newfd = -1;
edf2e370 31
4be60962 32static int unidiff_zero;
e36f8b60 33static int p_value = 1;
3e8a5db9 34static int p_value_known;
96f1e58f 35static int check_index;
7da3bf37 36static int update_index;
96f1e58f
DR
37static int cached;
38static int diffstat;
39static int numstat;
40static int summary;
41static int check;
a577284a 42static int apply = 1;
96f1e58f 43static int apply_in_reverse;
57dc397c 44static int apply_with_reject;
a2bf404e 45static int apply_verbosely;
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 }
2c93286a
JM
1410 if (!patch->is_delete && !patch->new_name)
1411 die("git diff header lacks filename information "
1412 "(line %d)", linenr);
9987d7c5 1413 patch->is_toplevel_relative = 1;
a4acb0eb 1414 *hdrsize = git_hdr_len;
c1bb9350
LT
1415 return offset;
1416 }
1417
81bf96bb 1418 /* --- followed by +++ ? */
c1bb9350
LT
1419 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1420 continue;
1421
1422 /*
1423 * We only accept unified patches, so we want it to
1424 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
81bf96bb 1425 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
c1bb9350
LT
1426 */
1427 nextlen = linelen(line + len, size - len);
1428 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1429 continue;
1430
1431 /* Ok, we'll consider it a patch */
19c58fb8 1432 parse_traditional_patch(line, line+len, patch);
c1bb9350 1433 *hdrsize = len + nextlen;
46979f56 1434 linenr += 2;
c1bb9350
LT
1435 return offset;
1436 }
1437 return -1;
1438}
1439
92a1747e 1440static void record_ws_error(unsigned result, const char *line, int len, int linenr)
d0c25035 1441{
c1795bb0 1442 char *err;
92a1747e 1443
c1795bb0
WC
1444 if (!result)
1445 return;
d0c25035 1446
d0c25035
JH
1447 whitespace_error++;
1448 if (squelch_whitespace_errors &&
1449 squelch_whitespace_errors < whitespace_error)
92a1747e
JH
1450 return;
1451
1452 err = whitespace_error_string(result);
1453 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1454 patch_input_file, linenr, err, len, line);
1455 free(err);
1456}
1457
1458static void check_whitespace(const char *line, int len, unsigned ws_rule)
1459{
1460 unsigned result = ws_check(line + 1, len - 1, ws_rule);
1461
1462 record_ws_error(result, line + 1, len - 2, linenr);
d0c25035
JH
1463}
1464
c1bb9350 1465/*
4be60962
JH
1466 * Parse a unified diff. Note that this really needs to parse each
1467 * fragment separately, since the only way to know the difference
1468 * between a "---" that is part of a patch, and a "---" that starts
1469 * the next patch is to look at the line counts..
c1bb9350 1470 */
81bf96bb
JH
1471static int parse_fragment(char *line, unsigned long size,
1472 struct patch *patch, struct fragment *fragment)
c1bb9350 1473{
3f40315a 1474 int added, deleted;
c1bb9350 1475 int len = linelen(line, size), offset;
30996652 1476 unsigned long oldlines, newlines;
47495887 1477 unsigned long leading, trailing;
c1bb9350 1478
19c58fb8 1479 offset = parse_fragment_header(line, len, fragment);
c1bb9350
LT
1480 if (offset < 0)
1481 return -1;
c14b9d1e
JS
1482 if (offset > 0 && patch->recount)
1483 recount_diff(line + offset, size - offset, fragment);
19c58fb8
LT
1484 oldlines = fragment->oldlines;
1485 newlines = fragment->newlines;
47495887
EB
1486 leading = 0;
1487 trailing = 0;
c1bb9350
LT
1488
1489 /* Parse the thing.. */
1490 line += len;
1491 size -= len;
46979f56 1492 linenr++;
3f40315a 1493 added = deleted = 0;
4be60962
JH
1494 for (offset = len;
1495 0 < size;
1496 offset += len, size -= len, line += len, linenr++) {
c1bb9350
LT
1497 if (!oldlines && !newlines)
1498 break;
1499 len = linelen(line, size);
1500 if (!len || line[len-1] != '\n')
1501 return -1;
1502 switch (*line) {
1503 default:
1504 return -1;
b507b465 1505 case '\n': /* newer GNU diff, an empty context line */
c1bb9350
LT
1506 case ' ':
1507 oldlines--;
1508 newlines--;
47495887
EB
1509 if (!deleted && !added)
1510 leading++;
1511 trailing++;
c1bb9350
LT
1512 break;
1513 case '-':
5fda48d6 1514 if (apply_in_reverse &&
81bf96bb 1515 ws_error_action != nowarn_ws_error)
cf1b7869 1516 check_whitespace(line, len, patch->ws_rule);
3f40315a 1517 deleted++;
c1bb9350 1518 oldlines--;
47495887 1519 trailing = 0;
c1bb9350
LT
1520 break;
1521 case '+':
5fda48d6 1522 if (!apply_in_reverse &&
81bf96bb 1523 ws_error_action != nowarn_ws_error)
cf1b7869 1524 check_whitespace(line, len, patch->ws_rule);
3f40315a 1525 added++;
c1bb9350 1526 newlines--;
47495887 1527 trailing = 0;
c1bb9350 1528 break;
433ef8a2 1529
81bf96bb
JH
1530 /*
1531 * We allow "\ No newline at end of file". Depending
433ef8a2
FK
1532 * on locale settings when the patch was produced we
1533 * don't know what this line looks like. The only
56d33b11
JH
1534 * thing we do know is that it begins with "\ ".
1535 * Checking for 12 is just for sanity check -- any
1536 * l10n of "\ No newline..." is at least that long.
1537 */
fab2c257 1538 case '\\':
433ef8a2 1539 if (len < 12 || memcmp(line, "\\ ", 2))
3cca928d 1540 return -1;
fab2c257 1541 break;
c1bb9350
LT
1542 }
1543 }
c1504628
LT
1544 if (oldlines || newlines)
1545 return -1;
47495887
EB
1546 fragment->leading = leading;
1547 fragment->trailing = trailing;
1548
81bf96bb
JH
1549 /*
1550 * If a fragment ends with an incomplete line, we failed to include
8b64647d
JH
1551 * it in the above loop because we hit oldlines == newlines == 0
1552 * before seeing it.
1553 */
433ef8a2 1554 if (12 < size && !memcmp(line, "\\ ", 2))
8b64647d
JH
1555 offset += linelen(line, size);
1556
3f40315a
LT
1557 patch->lines_added += added;
1558 patch->lines_deleted += deleted;
4be60962
JH
1559
1560 if (0 < patch->is_new && oldlines)
1561 return error("new file depends on old contents");
1562 if (0 < patch->is_delete && newlines)
1563 return error("deleted file still has contents");
c1bb9350
LT
1564 return offset;
1565}
1566
19c58fb8 1567static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
c1bb9350
LT
1568{
1569 unsigned long offset = 0;
4be60962 1570 unsigned long oldlines = 0, newlines = 0, context = 0;
19c58fb8 1571 struct fragment **fragp = &patch->fragments;
c1bb9350
LT
1572
1573 while (size > 4 && !memcmp(line, "@@ -", 4)) {
19c58fb8
LT
1574 struct fragment *fragment;
1575 int len;
1576
90321c10 1577 fragment = xcalloc(1, sizeof(*fragment));
77b15bbd 1578 fragment->linenr = linenr;
19c58fb8 1579 len = parse_fragment(line, size, patch, fragment);
c1bb9350 1580 if (len <= 0)
46979f56 1581 die("corrupt patch at line %d", linenr);
19c58fb8
LT
1582 fragment->patch = line;
1583 fragment->size = len;
4be60962
JH
1584 oldlines += fragment->oldlines;
1585 newlines += fragment->newlines;
1586 context += fragment->leading + fragment->trailing;
19c58fb8
LT
1587
1588 *fragp = fragment;
1589 fragp = &fragment->next;
c1bb9350
LT
1590
1591 offset += len;
1592 line += len;
1593 size -= len;
1594 }
4be60962
JH
1595
1596 /*
1597 * If something was removed (i.e. we have old-lines) it cannot
1598 * be creation, and if something was added it cannot be
1599 * deletion. However, the reverse is not true; --unified=0
1600 * patches that only add are not necessarily creation even
1601 * though they do not have any old lines, and ones that only
1602 * delete are not necessarily deletion.
1603 *
1604 * Unfortunately, a real creation/deletion patch do _not_ have
1605 * any context line by definition, so we cannot safely tell it
1606 * apart with --unified=0 insanity. At least if the patch has
1607 * more than one hunk it is not creation or deletion.
1608 */
1609 if (patch->is_new < 0 &&
1610 (oldlines || (patch->fragments && patch->fragments->next)))
1611 patch->is_new = 0;
1612 if (patch->is_delete < 0 &&
1613 (newlines || (patch->fragments && patch->fragments->next)))
1614 patch->is_delete = 0;
4be60962
JH
1615
1616 if (0 < patch->is_new && oldlines)
1617 die("new file %s depends on old contents", patch->new_name);
1618 if (0 < patch->is_delete && newlines)
1619 die("deleted file %s still has contents", patch->old_name);
1620 if (!patch->is_delete && !newlines && context)
1621 fprintf(stderr, "** warning: file %s becomes empty but "
1622 "is not deleted\n", patch->new_name);
1623
c1bb9350
LT
1624 return offset;
1625}
1626
1fea629f
LT
1627static inline int metadata_changes(struct patch *patch)
1628{
1629 return patch->is_rename > 0 ||
1630 patch->is_copy > 0 ||
1631 patch->is_new > 0 ||
1632 patch->is_delete ||
1633 (patch->old_mode && patch->new_mode &&
1634 patch->old_mode != patch->new_mode);
1635}
1636
3cd4f5e8
JH
1637static char *inflate_it(const void *data, unsigned long size,
1638 unsigned long inflated_size)
051308f6 1639{
ef49a7a0 1640 git_zstream stream;
3cd4f5e8
JH
1641 void *out;
1642 int st;
1643
1644 memset(&stream, 0, sizeof(stream));
1645
1646 stream.next_in = (unsigned char *)data;
1647 stream.avail_in = size;
1648 stream.next_out = out = xmalloc(inflated_size);
1649 stream.avail_out = inflated_size;
39c68542
LT
1650 git_inflate_init(&stream);
1651 st = git_inflate(&stream, Z_FINISH);
1652 git_inflate_end(&stream);
3cd4f5e8
JH
1653 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1654 free(out);
1655 return NULL;
1656 }
1657 return out;
1658}
1659
1660static struct fragment *parse_binary_hunk(char **buf_p,
1661 unsigned long *sz_p,
1662 int *status_p,
1663 int *used_p)
1664{
81bf96bb
JH
1665 /*
1666 * Expect a line that begins with binary patch method ("literal"
3cd4f5e8
JH
1667 * or "delta"), followed by the length of data before deflating.
1668 * a sequence of 'length-byte' followed by base-85 encoded data
1669 * should follow, terminated by a newline.
051308f6
JH
1670 *
1671 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1672 * and we would limit the patch line to 66 characters,
1673 * so one line can fit up to 13 groups that would decode
1674 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1675 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
051308f6
JH
1676 */
1677 int llen, used;
3cd4f5e8
JH
1678 unsigned long size = *sz_p;
1679 char *buffer = *buf_p;
1680 int patch_method;
1681 unsigned long origlen;
0660626c 1682 char *data = NULL;
3cd4f5e8
JH
1683 int hunk_size = 0;
1684 struct fragment *frag;
051308f6 1685
0660626c
JH
1686 llen = linelen(buffer, size);
1687 used = llen;
3cd4f5e8
JH
1688
1689 *status_p = 0;
0660626c 1690
cc44c765 1691 if (!prefixcmp(buffer, "delta ")) {
3cd4f5e8
JH
1692 patch_method = BINARY_DELTA_DEFLATED;
1693 origlen = strtoul(buffer + 6, NULL, 10);
0660626c 1694 }
cc44c765 1695 else if (!prefixcmp(buffer, "literal ")) {
3cd4f5e8
JH
1696 patch_method = BINARY_LITERAL_DEFLATED;
1697 origlen = strtoul(buffer + 8, NULL, 10);
0660626c
JH
1698 }
1699 else
3cd4f5e8
JH
1700 return NULL;
1701
1702 linenr++;
0660626c 1703 buffer += llen;
051308f6
JH
1704 while (1) {
1705 int byte_length, max_byte_length, newsize;
1706 llen = linelen(buffer, size);
1707 used += llen;
1708 linenr++;
03eb8f8a
JH
1709 if (llen == 1) {
1710 /* consume the blank line */
1711 buffer++;
1712 size--;
051308f6 1713 break;
03eb8f8a 1714 }
81bf96bb
JH
1715 /*
1716 * Minimum line is "A00000\n" which is 7-byte long,
051308f6
JH
1717 * and the line length must be multiple of 5 plus 2.
1718 */
1719 if ((llen < 7) || (llen-2) % 5)
1720 goto corrupt;
1721 max_byte_length = (llen - 2) / 5 * 4;
1722 byte_length = *buffer;
1723 if ('A' <= byte_length && byte_length <= 'Z')
1724 byte_length = byte_length - 'A' + 1;
1725 else if ('a' <= byte_length && byte_length <= 'z')
1726 byte_length = byte_length - 'a' + 27;
1727 else
1728 goto corrupt;
1729 /* if the input length was not multiple of 4, we would
1730 * have filler at the end but the filler should never
1731 * exceed 3 bytes
1732 */
1733 if (max_byte_length < byte_length ||
1734 byte_length <= max_byte_length - 4)
1735 goto corrupt;
3cd4f5e8 1736 newsize = hunk_size + byte_length;
0660626c 1737 data = xrealloc(data, newsize);
3cd4f5e8 1738 if (decode_85(data + hunk_size, buffer + 1, byte_length))
051308f6 1739 goto corrupt;
3cd4f5e8 1740 hunk_size = newsize;
051308f6
JH
1741 buffer += llen;
1742 size -= llen;
1743 }
3cd4f5e8
JH
1744
1745 frag = xcalloc(1, sizeof(*frag));
1746 frag->patch = inflate_it(data, hunk_size, origlen);
1747 if (!frag->patch)
1748 goto corrupt;
1749 free(data);
1750 frag->size = origlen;
1751 *buf_p = buffer;
1752 *sz_p = size;
1753 *used_p = used;
1754 frag->binary_patch_method = patch_method;
1755 return frag;
1756
051308f6 1757 corrupt:
4cac42b1 1758 free(data);
3cd4f5e8
JH
1759 *status_p = -1;
1760 error("corrupt binary patch at line %d: %.*s",
1761 linenr-1, llen-1, buffer);
1762 return NULL;
1763}
1764
1765static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1766{
81bf96bb
JH
1767 /*
1768 * We have read "GIT binary patch\n"; what follows is a line
3cd4f5e8
JH
1769 * that says the patch method (currently, either "literal" or
1770 * "delta") and the length of data before deflating; a
1771 * sequence of 'length-byte' followed by base-85 encoded data
1772 * follows.
1773 *
1774 * When a binary patch is reversible, there is another binary
1775 * hunk in the same format, starting with patch method (either
1776 * "literal" or "delta") with the length of data, and a sequence
1777 * of length-byte + base-85 encoded data, terminated with another
1778 * empty line. This data, when applied to the postimage, produces
1779 * the preimage.
1780 */
1781 struct fragment *forward;
1782 struct fragment *reverse;
1783 int status;
1784 int used, used_1;
1785
1786 forward = parse_binary_hunk(&buffer, &size, &status, &used);
1787 if (!forward && !status)
1788 /* there has to be one hunk (forward hunk) */
1789 return error("unrecognized binary patch at line %d", linenr-1);
1790 if (status)
1791 /* otherwise we already gave an error message */
1792 return status;
1793
1794 reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1795 if (reverse)
1796 used += used_1;
1797 else if (status) {
81bf96bb
JH
1798 /*
1799 * Not having reverse hunk is not an error, but having
3cd4f5e8
JH
1800 * a corrupt reverse hunk is.
1801 */
1802 free((void*) forward->patch);
1803 free(forward);
1804 return status;
1805 }
1806 forward->next = reverse;
1807 patch->fragments = forward;
1808 patch->is_binary = 1;
1809 return used;
051308f6
JH
1810}
1811
19c58fb8 1812static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
c1bb9350
LT
1813{
1814 int hdrsize, patchsize;
19c58fb8 1815 int offset = find_header(buffer, size, &hdrsize, patch);
c1bb9350
LT
1816
1817 if (offset < 0)
1818 return offset;
c1bb9350 1819
cf1b7869
JH
1820 patch->ws_rule = whitespace_rule(patch->new_name
1821 ? patch->new_name
1822 : patch->old_name);
1823
81bf96bb
JH
1824 patchsize = parse_single_patch(buffer + offset + hdrsize,
1825 size - offset - hdrsize, patch);
c1bb9350 1826
92927ed0 1827 if (!patchsize) {
3200d1ae
JH
1828 static const char *binhdr[] = {
1829 "Binary files ",
1830 "Files ",
1831 NULL,
1832 };
051308f6 1833 static const char git_binary[] = "GIT binary patch\n";
3200d1ae
JH
1834 int i;
1835 int hd = hdrsize + offset;
1836 unsigned long llen = linelen(buffer + hd, size - hd);
1837
051308f6
JH
1838 if (llen == sizeof(git_binary) - 1 &&
1839 !memcmp(git_binary, buffer + hd, llen)) {
1840 int used;
1841 linenr++;
1842 used = parse_binary(buffer + hd + llen,
1843 size - hd - llen, patch);
1844 if (used)
1845 patchsize = used + llen;
1846 else
1847 patchsize = 0;
1848 }
1849 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
3200d1ae
JH
1850 for (i = 0; binhdr[i]; i++) {
1851 int len = strlen(binhdr[i]);
1852 if (len < size - hd &&
1853 !memcmp(binhdr[i], buffer + hd, len)) {
051308f6 1854 linenr++;
3200d1ae 1855 patch->is_binary = 1;
051308f6 1856 patchsize = llen;
3200d1ae
JH
1857 break;
1858 }
1859 }
051308f6 1860 }
ff36de08 1861
2b6eef94
JH
1862 /* Empty patch cannot be applied if it is a text patch
1863 * without metadata change. A binary patch appears
1864 * empty to us here.
92927ed0
JH
1865 */
1866 if ((apply || check) &&
2b6eef94 1867 (!patch->is_binary && !metadata_changes(patch)))
ff36de08
JH
1868 die("patch with only garbage at line %d", linenr);
1869 }
1fea629f 1870
c1bb9350
LT
1871 return offset + hdrsize + patchsize;
1872}
1873
e5a94313
JS
1874#define swap(a,b) myswap((a),(b),sizeof(a))
1875
1876#define myswap(a, b, size) do { \
1877 unsigned char mytmp[size]; \
1878 memcpy(mytmp, &a, size); \
1879 memcpy(&a, &b, size); \
1880 memcpy(&b, mytmp, size); \
1881} while (0)
1882
1883static void reverse_patches(struct patch *p)
1884{
1885 for (; p; p = p->next) {
1886 struct fragment *frag = p->fragments;
1887
1888 swap(p->new_name, p->old_name);
1889 swap(p->new_mode, p->old_mode);
1890 swap(p->is_new, p->is_delete);
1891 swap(p->lines_added, p->lines_deleted);
1892 swap(p->old_sha1_prefix, p->new_sha1_prefix);
1893
1894 for (; frag; frag = frag->next) {
1895 swap(frag->newpos, frag->oldpos);
1896 swap(frag->newlines, frag->oldlines);
1897 }
e5a94313
JS
1898 }
1899}
1900
81bf96bb
JH
1901static const char pluses[] =
1902"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1903static const char minuses[]=
1904"----------------------------------------------------------------------";
3f40315a
LT
1905
1906static void show_stats(struct patch *patch)
1907{
f285a2d7 1908 struct strbuf qname = STRBUF_INIT;
663af342
PH
1909 char *cp = patch->new_name ? patch->new_name : patch->old_name;
1910 int max, add, del;
3f40315a 1911
663af342 1912 quote_c_style(cp, &qname, NULL, 0);
22943f1a 1913
3f40315a
LT
1914 /*
1915 * "scale" the filename
1916 */
3f40315a
LT
1917 max = max_len;
1918 if (max > 50)
1919 max = 50;
663af342
PH
1920
1921 if (qname.len > max) {
1922 cp = strchr(qname.buf + qname.len + 3 - max, '/');
1923 if (!cp)
1924 cp = qname.buf + qname.len + 3 - max;
1925 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
1926 }
1927
1928 if (patch->is_binary) {
1929 printf(" %-*s | Bin\n", max, qname.buf);
1930 strbuf_release(&qname);
1931 return;
62917097 1932 }
663af342
PH
1933
1934 printf(" %-*s |", max, qname.buf);
1935 strbuf_release(&qname);
3f40315a
LT
1936
1937 /*
1938 * scale the add/delete
1939 */
663af342 1940 max = max + max_change > 70 ? 70 - max : max_change;
95bedc9e
LT
1941 add = patch->lines_added;
1942 del = patch->lines_deleted;
95bedc9e 1943
69f956e1 1944 if (max_change > 0) {
663af342 1945 int total = ((add + del) * max + max_change / 2) / max_change;
69f956e1
SV
1946 add = (add * max + max_change / 2) / max_change;
1947 del = total - add;
1948 }
663af342
PH
1949 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
1950 add, pluses, del, minuses);
3f40315a
LT
1951}
1952
c7f9cb14 1953static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
3cca928d 1954{
3cca928d
LT
1955 switch (st->st_mode & S_IFMT) {
1956 case S_IFLNK:
b11b7e13
LT
1957 if (strbuf_readlink(buf, path, st->st_size) < 0)
1958 return error("unable to read symlink %s", path);
c7f9cb14 1959 return 0;
3cca928d 1960 case S_IFREG:
387e7e19
PH
1961 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
1962 return error("unable to open or read %s", path);
21e5ad50 1963 convert_to_git(path, buf->buf, buf->len, buf, 0);
c7f9cb14 1964 return 0;
3cca928d
LT
1965 default:
1966 return -1;
1967 }
1968}
1969
86c91f91
GB
1970/*
1971 * Update the preimage, and the common lines in postimage,
1972 * from buffer buf of length len. If postlen is 0 the postimage
1973 * is updated in place, otherwise it's updated on a new buffer
1974 * of length postlen
1975 */
1976
c1beba5b
JH
1977static void update_pre_post_images(struct image *preimage,
1978 struct image *postimage,
1979 char *buf,
86c91f91 1980 size_t len, size_t postlen)
3cca928d 1981{
c1beba5b
JH
1982 int i, ctx;
1983 char *new, *old, *fixed;
1984 struct image fixed_preimage;
3cca928d 1985
c1beba5b
JH
1986 /*
1987 * Update the preimage with whitespace fixes. Note that we
1988 * are not losing preimage->buf -- apply_one_fragment() will
1989 * free "oldlines".
1990 */
1991 prepare_image(&fixed_preimage, buf, len, 1);
1992 assert(fixed_preimage.nr == preimage->nr);
1993 for (i = 0; i < preimage->nr; i++)
1994 fixed_preimage.line[i].flag = preimage->line[i].flag;
1995 free(preimage->line_allocated);
1996 *preimage = fixed_preimage;
3cca928d 1997
c1beba5b 1998 /*
86c91f91
GB
1999 * Adjust the common context lines in postimage. This can be
2000 * done in-place when we are just doing whitespace fixing,
2001 * which does not make the string grow, but needs a new buffer
2002 * when ignoring whitespace causes the update, since in this case
2003 * we could have e.g. tabs converted to multiple spaces.
2004 * We trust the caller to tell us if the update can be done
2005 * in place (postlen==0) or not.
c1beba5b 2006 */
86c91f91
GB
2007 old = postimage->buf;
2008 if (postlen)
2009 new = postimage->buf = xmalloc(postlen);
2010 else
2011 new = old;
c1beba5b
JH
2012 fixed = preimage->buf;
2013 for (i = ctx = 0; i < postimage->nr; i++) {
2014 size_t len = postimage->line[i].len;
2015 if (!(postimage->line[i].flag & LINE_COMMON)) {
2016 /* an added line -- no counterparts in preimage */
2017 memmove(new, old, len);
2018 old += len;
2019 new += len;
2020 continue;
3cca928d 2021 }
c1beba5b
JH
2022
2023 /* a common context -- skip it in the original postimage */
2024 old += len;
2025
2026 /* and find the corresponding one in the fixed preimage */
2027 while (ctx < preimage->nr &&
2028 !(preimage->line[ctx].flag & LINE_COMMON)) {
2029 fixed += preimage->line[ctx].len;
2030 ctx++;
2031 }
2032 if (preimage->nr <= ctx)
2033 die("oops");
2034
2035 /* and copy it in, while fixing the line length */
2036 len = preimage->line[ctx].len;
2037 memcpy(new, fixed, len);
2038 new += len;
2039 fixed += len;
2040 postimage->line[i].len = len;
2041 ctx++;
2042 }
2043
2044 /* Fix the length of the whole thing */
2045 postimage->len = new - postimage->buf;
2046}
2047
b94f2eda
JH
2048static int match_fragment(struct image *img,
2049 struct image *preimage,
2050 struct image *postimage,
c89fb6b1 2051 unsigned long try,
b94f2eda 2052 int try_lno,
c607aaa2 2053 unsigned ws_rule,
dc41976a 2054 int match_beginning, int match_end)
c89fb6b1 2055{
b94f2eda 2056 int i;
c1beba5b 2057 char *fixed_buf, *buf, *orig, *target;
d511bd33
CW
2058 struct strbuf fixed;
2059 size_t fixed_len;
51667147 2060 int preimage_limit;
b94f2eda 2061
51667147
BG
2062 if (preimage->nr + try_lno <= img->nr) {
2063 /*
2064 * The hunk falls within the boundaries of img.
2065 */
2066 preimage_limit = preimage->nr;
2067 if (match_end && (preimage->nr + try_lno != img->nr))
2068 return 0;
2069 } else if (ws_error_action == correct_ws_error &&
0c3ef984 2070 (ws_rule & WS_BLANK_AT_EOF)) {
51667147 2071 /*
0c3ef984
BG
2072 * This hunk extends beyond the end of img, and we are
2073 * removing blank lines at the end of the file. This
2074 * many lines from the beginning of the preimage must
2075 * match with img, and the remainder of the preimage
2076 * must be blank.
51667147
BG
2077 */
2078 preimage_limit = img->nr - try_lno;
2079 } else {
2080 /*
2081 * The hunk extends beyond the end of the img and
2082 * we are not removing blanks at the end, so we
2083 * should reject the hunk at this position.
2084 */
b94f2eda 2085 return 0;
51667147 2086 }
b94f2eda
JH
2087
2088 if (match_beginning && try_lno)
c89fb6b1 2089 return 0;
dc41976a 2090
b94f2eda 2091 /* Quick hash check */
51667147 2092 for (i = 0; i < preimage_limit; i++)
9d158601
JH
2093 if ((img->line[try_lno + i].flag & LINE_PATCHED) ||
2094 (preimage->line[i].hash != img->line[try_lno + i].hash))
b94f2eda
JH
2095 return 0;
2096
51667147
BG
2097 if (preimage_limit == preimage->nr) {
2098 /*
2099 * Do we have an exact match? If we were told to match
2100 * at the end, size must be exactly at try+fragsize,
2101 * otherwise try+fragsize must be still within the preimage,
2102 * and either case, the old piece should match the preimage
2103 * exactly.
2104 */
2105 if ((match_end
2106 ? (try + preimage->len == img->len)
2107 : (try + preimage->len <= img->len)) &&
2108 !memcmp(img->buf + try, preimage->buf, preimage->len))
2109 return 1;
2110 } else {
2111 /*
2112 * The preimage extends beyond the end of img, so
2113 * there cannot be an exact match.
2114 *
2115 * There must be one non-blank context line that match
2116 * a line before the end of img.
2117 */
2118 char *buf_end;
2119
2120 buf = preimage->buf;
2121 buf_end = buf;
2122 for (i = 0; i < preimage_limit; i++)
2123 buf_end += preimage->line[i].len;
2124
2125 for ( ; buf < buf_end; buf++)
2126 if (!isspace(*buf))
2127 break;
2128 if (buf == buf_end)
2129 return 0;
2130 }
dc41976a 2131
86c91f91
GB
2132 /*
2133 * No exact match. If we are ignoring whitespace, run a line-by-line
2134 * fuzzy matching. We collect all the line length information because
2135 * we need it to adjust whitespace if we match.
2136 */
2137 if (ws_ignore_action == ignore_ws_change) {
2138 size_t imgoff = 0;
2139 size_t preoff = 0;
2140 size_t postlen = postimage->len;
51667147
BG
2141 size_t extra_chars;
2142 char *preimage_eof;
2143 char *preimage_end;
2144 for (i = 0; i < preimage_limit; i++) {
86c91f91 2145 size_t prelen = preimage->line[i].len;
0b1fac32 2146 size_t imglen = img->line[try_lno+i].len;
86c91f91 2147
0b1fac32
JH
2148 if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,
2149 preimage->buf + preoff, prelen))
86c91f91
GB
2150 return 0;
2151 if (preimage->line[i].flag & LINE_COMMON)
0b1fac32
JH
2152 postlen += imglen - prelen;
2153 imgoff += imglen;
86c91f91
GB
2154 preoff += prelen;
2155 }
2156
2157 /*
9b25949a
BG
2158 * Ok, the preimage matches with whitespace fuzz.
2159 *
2160 * imgoff now holds the true length of the target that
51667147
BG
2161 * matches the preimage before the end of the file.
2162 *
2163 * Count the number of characters in the preimage that fall
2164 * beyond the end of the file and make sure that all of them
2165 * are whitespace characters. (This can only happen if
2166 * we are removing blank lines at the end of the file.)
86c91f91 2167 */
51667147
BG
2168 buf = preimage_eof = preimage->buf + preoff;
2169 for ( ; i < preimage->nr; i++)
2170 preoff += preimage->line[i].len;
2171 preimage_end = preimage->buf + preoff;
2172 for ( ; buf < preimage_end; buf++)
2173 if (!isspace(*buf))
2174 return 0;
2175
2176 /*
2177 * Update the preimage and the common postimage context
2178 * lines to use the same whitespace as the target.
2179 * If whitespace is missing in the target (i.e.
2180 * if the preimage extends beyond the end of the file),
2181 * use the whitespace from the preimage.
2182 */
2183 extra_chars = preimage_end - preimage_eof;
d511bd33
CW
2184 strbuf_init(&fixed, imgoff + extra_chars);
2185 strbuf_add(&fixed, img->buf + try, imgoff);
2186 strbuf_add(&fixed, preimage_eof, extra_chars);
2187 fixed_buf = strbuf_detach(&fixed, &fixed_len);
86c91f91 2188 update_pre_post_images(preimage, postimage,
d511bd33 2189 fixed_buf, fixed_len, postlen);
86c91f91
GB
2190 return 1;
2191 }
2192
c1beba5b
JH
2193 if (ws_error_action != correct_ws_error)
2194 return 0;
2195
dc41976a 2196 /*
c1beba5b 2197 * The hunk does not apply byte-by-byte, but the hash says
86c91f91
GB
2198 * it might with whitespace fuzz. We haven't been asked to
2199 * ignore whitespace, we were asked to correct whitespace
2200 * errors, so let's try matching after whitespace correction.
51667147
BG
2201 *
2202 * The preimage may extend beyond the end of the file,
2203 * but in this loop we will only handle the part of the
2204 * preimage that falls within the file.
dc41976a 2205 */
d511bd33 2206 strbuf_init(&fixed, preimage->len + 1);
c1beba5b
JH
2207 orig = preimage->buf;
2208 target = img->buf + try;
51667147 2209 for (i = 0; i < preimage_limit; i++) {
c1beba5b
JH
2210 size_t oldlen = preimage->line[i].len;
2211 size_t tgtlen = img->line[try_lno + i].len;
d511bd33
CW
2212 size_t fixstart = fixed.len;
2213 struct strbuf tgtfix;
c1beba5b
JH
2214 int match;
2215
2216 /* Try fixing the line in the preimage */
d511bd33 2217 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
c1beba5b
JH
2218
2219 /* Try fixing the line in the target */
d511bd33
CW
2220 strbuf_init(&tgtfix, tgtlen);
2221 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
c1beba5b
JH
2222
2223 /*
2224 * If they match, either the preimage was based on
2225 * a version before our tree fixed whitespace breakage,
2226 * or we are lacking a whitespace-fix patch the tree
2227 * the preimage was based on already had (i.e. target
2228 * has whitespace breakage, the preimage doesn't).
2229 * In either case, we are fixing the whitespace breakages
2230 * so we might as well take the fix together with their
2231 * real change.
2232 */
d511bd33
CW
2233 match = (tgtfix.len == fixed.len - fixstart &&
2234 !memcmp(tgtfix.buf, fixed.buf + fixstart,
2235 fixed.len - fixstart));
c1beba5b 2236
d511bd33 2237 strbuf_release(&tgtfix);
c1beba5b
JH
2238 if (!match)
2239 goto unmatch_exit;
2240
2241 orig += oldlen;
c1beba5b 2242 target += tgtlen;
3cca928d
LT
2243 }
2244
51667147
BG
2245
2246 /*
2247 * Now handle the lines in the preimage that falls beyond the
2248 * end of the file (if any). They will only match if they are
2249 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2250 * false).
2251 */
2252 for ( ; i < preimage->nr; i++) {
d511bd33 2253 size_t fixstart = fixed.len; /* start of the fixed preimage */
51667147
BG
2254 size_t oldlen = preimage->line[i].len;
2255 int j;
2256
2257 /* Try fixing the line in the preimage */
d511bd33 2258 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
51667147 2259
d511bd33
CW
2260 for (j = fixstart; j < fixed.len; j++)
2261 if (!isspace(fixed.buf[j]))
51667147
BG
2262 goto unmatch_exit;
2263
2264 orig += oldlen;
51667147
BG
2265 }
2266
c1beba5b
JH
2267 /*
2268 * Yes, the preimage is based on an older version that still
2269 * has whitespace breakages unfixed, and fixing them makes the
2270 * hunk match. Update the context lines in the postimage.
2271 */
d511bd33 2272 fixed_buf = strbuf_detach(&fixed, &fixed_len);
c1beba5b 2273 update_pre_post_images(preimage, postimage,
d511bd33 2274 fixed_buf, fixed_len, 0);
c1beba5b
JH
2275 return 1;
2276
2277 unmatch_exit:
d511bd33 2278 strbuf_release(&fixed);
dc41976a 2279 return 0;
c89fb6b1
JH
2280}
2281
b94f2eda
JH
2282static int find_pos(struct image *img,
2283 struct image *preimage,
2284 struct image *postimage,
2285 int line,
c607aaa2 2286 unsigned ws_rule,
b94f2eda 2287 int match_beginning, int match_end)
3cca928d 2288{
b94f2eda
JH
2289 int i;
2290 unsigned long backwards, forwards, try;
2291 int backwards_lno, forwards_lno, try_lno;
3cca928d 2292
ecf4c2ec 2293 /*
24ff4d56 2294 * If match_beginning or match_end is specified, there is no
ecf4c2ec
JH
2295 * point starting from a wrong line that will never match and
2296 * wander around and wait for a match at the specified end.
2297 */
2298 if (match_beginning)
2299 line = 0;
2300 else if (match_end)
2301 line = img->nr - preimage->nr;
2302
24ff4d56
BG
2303 /*
2304 * Because the comparison is unsigned, the following test
2305 * will also take care of a negative line number that can
2306 * result when match_end and preimage is larger than the target.
2307 */
2308 if ((size_t) line > img->nr)
52f3c81a
JH
2309 line = img->nr;
2310
b94f2eda
JH
2311 try = 0;
2312 for (i = 0; i < line; i++)
2313 try += img->line[i].len;
3cca928d 2314
6e7c92a9
LT
2315 /*
2316 * There's probably some smart way to do this, but I'll leave
2317 * that to the smart and beautiful people. I'm simple and stupid.
2318 */
b94f2eda
JH
2319 backwards = try;
2320 backwards_lno = line;
2321 forwards = try;
2322 forwards_lno = line;
2323 try_lno = line;
fcb77bc5 2324
6e7c92a9 2325 for (i = 0; ; i++) {
b94f2eda 2326 if (match_fragment(img, preimage, postimage,
c607aaa2 2327 try, try_lno, ws_rule,
b94f2eda
JH
2328 match_beginning, match_end))
2329 return try_lno;
fcb77bc5
JH
2330
2331 again:
b94f2eda 2332 if (backwards_lno == 0 && forwards_lno == img->nr)
fcb77bc5 2333 break;
6e7c92a9 2334
6e7c92a9 2335 if (i & 1) {
b94f2eda 2336 if (backwards_lno == 0) {
fcb77bc5
JH
2337 i++;
2338 goto again;
6e7c92a9 2339 }
b94f2eda
JH
2340 backwards_lno--;
2341 backwards -= img->line[backwards_lno].len;
6e7c92a9 2342 try = backwards;
b94f2eda 2343 try_lno = backwards_lno;
6e7c92a9 2344 } else {
b94f2eda 2345 if (forwards_lno == img->nr) {
fcb77bc5
JH
2346 i++;
2347 goto again;
6e7c92a9 2348 }
b94f2eda
JH
2349 forwards += img->line[forwards_lno].len;
2350 forwards_lno++;
6e7c92a9 2351 try = forwards;
b94f2eda 2352 try_lno = forwards_lno;
6e7c92a9
LT
2353 }
2354
6e7c92a9 2355 }
3cca928d
LT
2356 return -1;
2357}
2358
b94f2eda 2359static void remove_first_line(struct image *img)
47495887 2360{
b94f2eda
JH
2361 img->buf += img->line[0].len;
2362 img->len -= img->line[0].len;
2363 img->line++;
2364 img->nr--;
47495887
EB
2365}
2366
b94f2eda 2367static void remove_last_line(struct image *img)
47495887 2368{
b94f2eda 2369 img->len -= img->line[--img->nr].len;
47495887
EB
2370}
2371
b94f2eda
JH
2372static void update_image(struct image *img,
2373 int applied_pos,
2374 struct image *preimage,
2375 struct image *postimage)
b5767dd6 2376{
81bf96bb 2377 /*
b94f2eda
JH
2378 * remove the copy of preimage at offset in img
2379 * and replace it with postimage
81bf96bb 2380 */
b94f2eda
JH
2381 int i, nr;
2382 size_t remove_count, insert_count, applied_at = 0;
2383 char *result;
51667147
BG
2384 int preimage_limit;
2385
2386 /*
2387 * If we are removing blank lines at the end of img,
2388 * the preimage may extend beyond the end.
2389 * If that is the case, we must be careful only to
2390 * remove the part of the preimage that falls within
2391 * the boundaries of img. Initialize preimage_limit
2392 * to the number of lines in the preimage that falls
2393 * within the boundaries.
2394 */
2395 preimage_limit = preimage->nr;
2396 if (preimage_limit > img->nr - applied_pos)
2397 preimage_limit = img->nr - applied_pos;
d5a41641 2398
b94f2eda
JH
2399 for (i = 0; i < applied_pos; i++)
2400 applied_at += img->line[i].len;
2401
2402 remove_count = 0;
51667147 2403 for (i = 0; i < preimage_limit; i++)
b94f2eda
JH
2404 remove_count += img->line[applied_pos + i].len;
2405 insert_count = postimage->len;
2406
2407 /* Adjust the contents */
2408 result = xmalloc(img->len + insert_count - remove_count + 1);
2409 memcpy(result, img->buf, applied_at);
2410 memcpy(result + applied_at, postimage->buf, postimage->len);
2411 memcpy(result + applied_at + postimage->len,
2412 img->buf + (applied_at + remove_count),
2413 img->len - (applied_at + remove_count));
2414 free(img->buf);
2415 img->buf = result;
2416 img->len += insert_count - remove_count;
2417 result[img->len] = '\0';
2418
2419 /* Adjust the line table */
51667147
BG
2420 nr = img->nr + postimage->nr - preimage_limit;
2421 if (preimage_limit < postimage->nr) {
81bf96bb 2422 /*
b94f2eda
JH
2423 * NOTE: this knows that we never call remove_first_line()
2424 * on anything other than pre/post image.
d0c25035 2425 */
b94f2eda
JH
2426 img->line = xrealloc(img->line, nr * sizeof(*img->line));
2427 img->line_allocated = img->line;
d0c25035 2428 }
51667147 2429 if (preimage_limit != postimage->nr)
b94f2eda 2430 memmove(img->line + applied_pos + postimage->nr,
51667147
BG
2431 img->line + applied_pos + preimage_limit,
2432 (img->nr - (applied_pos + preimage_limit)) *
b94f2eda
JH
2433 sizeof(*img->line));
2434 memcpy(img->line + applied_pos,
2435 postimage->line,
2436 postimage->nr * sizeof(*img->line));
933e44d3
JH
2437 if (!allow_overlap)
2438 for (i = 0; i < postimage->nr; i++)
2439 img->line[applied_pos + i].flag |= LINE_PATCHED;
b94f2eda 2440 img->nr = nr;
b5767dd6
JH
2441}
2442
b94f2eda 2443static int apply_one_fragment(struct image *img, struct fragment *frag,
334f8cb2
JH
2444 int inaccurate_eof, unsigned ws_rule,
2445 int nth_fragment)
3cca928d 2446{
65aadb92 2447 int match_beginning, match_end;
3cca928d 2448 const char *patch = frag->patch;
b94f2eda 2449 int size = frag->size;
d511bd33
CW
2450 char *old, *oldlines;
2451 struct strbuf newlines;
077e1af5 2452 int new_blank_lines_at_end = 0;
47495887 2453 unsigned long leading, trailing;
b94f2eda
JH
2454 int pos, applied_pos;
2455 struct image preimage;
2456 struct image postimage;
3cca928d 2457
c330fdd4
JH
2458 memset(&preimage, 0, sizeof(preimage));
2459 memset(&postimage, 0, sizeof(postimage));
61e08cca 2460 oldlines = xmalloc(size);
d511bd33 2461 strbuf_init(&newlines, size);
c330fdd4 2462
61e08cca 2463 old = oldlines;
3cca928d 2464 while (size > 0) {
e5a94313 2465 char first;
3cca928d 2466 int len = linelen(patch, size);
d511bd33 2467 int plen;
077e1af5 2468 int added_blank_line = 0;
efa57443 2469 int is_blank_context = 0;
d511bd33 2470 size_t start;
3cca928d
LT
2471
2472 if (!len)
2473 break;
2474
2475 /*
2476 * "plen" is how much of the line we should use for
2477 * the actual patch data. Normally we just remove the
2478 * first character on the line, but if the line is
2479 * followed by "\ No newline", then we also remove the
2480 * last one (which is the newline, of course).
2481 */
61e08cca 2482 plen = len - 1;
8b64647d 2483 if (len < size && patch[len] == '\\')
3cca928d 2484 plen--;
e5a94313 2485 first = *patch;
f686d030 2486 if (apply_in_reverse) {
e5a94313
JS
2487 if (first == '-')
2488 first = '+';
2489 else if (first == '+')
2490 first = '-';
2491 }
efe7f358 2492
e5a94313 2493 switch (first) {
b507b465
LT
2494 case '\n':
2495 /* Newer GNU diff, empty context line */
2496 if (plen < 0)
2497 /* ... followed by '\No newline'; nothing */
2498 break;
61e08cca 2499 *old++ = '\n';
d511bd33 2500 strbuf_addch(&newlines, '\n');
c330fdd4
JH
2501 add_line_info(&preimage, "\n", 1, LINE_COMMON);
2502 add_line_info(&postimage, "\n", 1, LINE_COMMON);
efa57443 2503 is_blank_context = 1;
b507b465 2504 break;
3cca928d 2505 case ' ':
94ea026b
JH
2506 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2507 ws_blank_line(patch + 1, plen, ws_rule))
efa57443 2508 is_blank_context = 1;
3cca928d 2509 case '-':
61e08cca
JH
2510 memcpy(old, patch + 1, plen);
2511 add_line_info(&preimage, old, plen,
c330fdd4 2512 (first == ' ' ? LINE_COMMON : 0));
61e08cca 2513 old += plen;
e5a94313 2514 if (first == '-')
3cca928d
LT
2515 break;
2516 /* Fall-through for ' ' */
2517 case '+':
8441a9a8
JH
2518 /* --no-add does not add new lines */
2519 if (first == '+' && no_add)
2520 break;
2521
d511bd33 2522 start = newlines.len;
8441a9a8
JH
2523 if (first != '+' ||
2524 !whitespace_error ||
2525 ws_error_action != correct_ws_error) {
d511bd33 2526 strbuf_add(&newlines, patch + 1, plen);
8441a9a8
JH
2527 }
2528 else {
d511bd33 2529 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &applied_after_fixing_ws);
077e1af5 2530 }
d511bd33 2531 add_line_info(&postimage, newlines.buf + start, newlines.len - start,
8441a9a8 2532 (first == '+' ? 0 : LINE_COMMON));
8441a9a8 2533 if (first == '+' &&
94ea026b
JH
2534 (ws_rule & WS_BLANK_AT_EOF) &&
2535 ws_blank_line(patch + 1, plen, ws_rule))
8441a9a8 2536 added_blank_line = 1;
3cca928d
LT
2537 break;
2538 case '@': case '\\':
2539 /* Ignore it, we already handled it */
2540 break;
2541 default:
aeabfa07
JS
2542 if (apply_verbosely)
2543 error("invalid start of line: '%c'", first);
3cca928d
LT
2544 return -1;
2545 }
077e1af5
JH
2546 if (added_blank_line)
2547 new_blank_lines_at_end++;
efa57443
JH
2548 else if (is_blank_context)
2549 ;
077e1af5
JH
2550 else
2551 new_blank_lines_at_end = 0;
3cca928d
LT
2552 patch += len;
2553 size -= len;
2554 }
81bf96bb 2555 if (inaccurate_eof &&
61e08cca 2556 old > oldlines && old[-1] == '\n' &&
d511bd33 2557 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
61e08cca 2558 old--;
d511bd33 2559 strbuf_setlen(&newlines, newlines.len - 1);
5b5d4d9e 2560 }
47495887 2561
47495887
EB
2562 leading = frag->leading;
2563 trailing = frag->trailing;
1bf1a859
LT
2564
2565 /*
ee5a317e
JH
2566 * A hunk to change lines at the beginning would begin with
2567 * @@ -1,L +N,M @@
ed0f47a8
JH
2568 * but we need to be careful. -U0 that inserts before the second
2569 * line also has this pattern.
4be60962 2570 *
ee5a317e
JH
2571 * And a hunk to add to an empty file would begin with
2572 * @@ -0,0 +N,M @@
2573 *
2574 * In other words, a hunk that is (frag->oldpos <= 1) with or
2575 * without leading context must match at the beginning.
1bf1a859 2576 */
ed0f47a8
JH
2577 match_beginning = (!frag->oldpos ||
2578 (frag->oldpos == 1 && !unidiff_zero));
ee5a317e
JH
2579
2580 /*
2581 * A hunk without trailing lines must match at the end.
2582 * However, we simply cannot tell if a hunk must match end
2583 * from the lack of trailing lines if the patch was generated
2584 * with unidiff without any context.
2585 */
2586 match_end = !unidiff_zero && !trailing;
1bf1a859 2587
b94f2eda 2588 pos = frag->newpos ? (frag->newpos - 1) : 0;
61e08cca
JH
2589 preimage.buf = oldlines;
2590 preimage.len = old - oldlines;
d511bd33
CW
2591 postimage.buf = newlines.buf;
2592 postimage.len = newlines.len;
c330fdd4
JH
2593 preimage.line = preimage.line_allocated;
2594 postimage.line = postimage.line_allocated;
2595
47495887 2596 for (;;) {
efe7f358 2597
c607aaa2
JH
2598 applied_pos = find_pos(img, &preimage, &postimage, pos,
2599 ws_rule, match_beginning, match_end);
b94f2eda
JH
2600
2601 if (applied_pos >= 0)
47495887 2602 break;
47495887
EB
2603
2604 /* Am I at my context limits? */
2605 if ((leading <= p_context) && (trailing <= p_context))
2606 break;
65aadb92
JH
2607 if (match_beginning || match_end) {
2608 match_beginning = match_end = 0;
1bf1a859
LT
2609 continue;
2610 }
b94f2eda 2611
81bf96bb
JH
2612 /*
2613 * Reduce the number of context lines; reduce both
2614 * leading and trailing if they are equal otherwise
2615 * just reduce the larger context.
47495887
EB
2616 */
2617 if (leading >= trailing) {
b94f2eda
JH
2618 remove_first_line(&preimage);
2619 remove_first_line(&postimage);
47495887
EB
2620 pos--;
2621 leading--;
2622 }
2623 if (trailing > leading) {
b94f2eda
JH
2624 remove_last_line(&preimage);
2625 remove_last_line(&postimage);
47495887 2626 trailing--;
6e7c92a9 2627 }
3cca928d
LT
2628 }
2629
b94f2eda 2630 if (applied_pos >= 0) {
77b15bbd 2631 if (new_blank_lines_at_end &&
51667147 2632 preimage.nr + applied_pos >= img->nr &&
77b15bbd
JH
2633 (ws_rule & WS_BLANK_AT_EOF) &&
2634 ws_error_action != nowarn_ws_error) {
2635 record_ws_error(WS_BLANK_AT_EOF, "+", 1, frag->linenr);
2636 if (ws_error_action == correct_ws_error) {
2637 while (new_blank_lines_at_end--)
2638 remove_last_line(&postimage);
2639 }
b94f2eda 2640 /*
77b15bbd
JH
2641 * We would want to prevent write_out_results()
2642 * from taking place in apply_patch() that follows
2643 * the callchain led us here, which is:
2644 * apply_patch->check_patch_list->check_patch->
2645 * apply_data->apply_fragments->apply_one_fragment
b94f2eda 2646 */
77b15bbd
JH
2647 if (ws_error_action == die_on_ws_error)
2648 apply = 0;
b94f2eda 2649 }
aeabfa07 2650
334f8cb2
JH
2651 if (apply_verbosely && applied_pos != pos) {
2652 int offset = applied_pos - pos;
2653 if (apply_in_reverse)
2654 offset = 0 - offset;
2655 fprintf(stderr,
2656 "Hunk #%d succeeded at %d (offset %d lines).\n",
2657 nth_fragment, applied_pos + 1, offset);
2658 }
2659
b94f2eda
JH
2660 /*
2661 * Warn if it was necessary to reduce the number
2662 * of context lines.
2663 */
2664 if ((leading != frag->leading) ||
2665 (trailing != frag->trailing))
2666 fprintf(stderr, "Context reduced to (%ld/%ld)"
2667 " to apply fragment at %d\n",
2668 leading, trailing, applied_pos+1);
2669 update_image(img, applied_pos, &preimage, &postimage);
2670 } else {
2671 if (apply_verbosely)
61e08cca
JH
2672 error("while searching for:\n%.*s",
2673 (int)(old - oldlines), oldlines);
b94f2eda 2674 }
aeabfa07 2675
61e08cca 2676 free(oldlines);
d511bd33 2677 strbuf_release(&newlines);
b94f2eda
JH
2678 free(preimage.line_allocated);
2679 free(postimage.line_allocated);
2680
2681 return (applied_pos < 0);
3cca928d
LT
2682}
2683
b94f2eda 2684static int apply_binary_fragment(struct image *img, struct patch *patch)
0660626c 2685{
0660626c 2686 struct fragment *fragment = patch->fragments;
c7f9cb14
PH
2687 unsigned long len;
2688 void *dst;
0660626c 2689
24305cd7
JK
2690 if (!fragment)
2691 return error("missing binary patch data for '%s'",
2692 patch->new_name ?
2693 patch->new_name :
2694 patch->old_name);
2695
3cd4f5e8
JH
2696 /* Binary patch is irreversible without the optional second hunk */
2697 if (apply_in_reverse) {
2698 if (!fragment->next)
2699 return error("cannot reverse-apply a binary patch "
2700 "without the reverse hunk to '%s'",
2701 patch->new_name
2702 ? patch->new_name : patch->old_name);
03eb8f8a 2703 fragment = fragment->next;
3cd4f5e8 2704 }
3cd4f5e8 2705 switch (fragment->binary_patch_method) {
0660626c 2706 case BINARY_DELTA_DEFLATED:
b94f2eda 2707 dst = patch_delta(img->buf, img->len, fragment->patch,
c7f9cb14
PH
2708 fragment->size, &len);
2709 if (!dst)
2710 return -1;
b94f2eda
JH
2711 clear_image(img);
2712 img->buf = dst;
2713 img->len = len;
c7f9cb14 2714 return 0;
0660626c 2715 case BINARY_LITERAL_DEFLATED:
b94f2eda
JH
2716 clear_image(img);
2717 img->len = fragment->size;
2718 img->buf = xmalloc(img->len+1);
2719 memcpy(img->buf, fragment->patch, img->len);
2720 img->buf[img->len] = '\0';
c7f9cb14 2721 return 0;
0660626c 2722 }
c7f9cb14 2723 return -1;
0660626c
JH
2724}
2725
b94f2eda 2726static int apply_binary(struct image *img, struct patch *patch)
3cca928d 2727{
011f4274 2728 const char *name = patch->old_name ? patch->old_name : patch->new_name;
051308f6 2729 unsigned char sha1[20];
011f4274 2730
81bf96bb
JH
2731 /*
2732 * For safety, we require patch index line to contain
051308f6
JH
2733 * full 40-byte textual SHA1 for old and new, at least for now.
2734 */
2735 if (strlen(patch->old_sha1_prefix) != 40 ||
2736 strlen(patch->new_sha1_prefix) != 40 ||
2737 get_sha1_hex(patch->old_sha1_prefix, sha1) ||
2738 get_sha1_hex(patch->new_sha1_prefix, sha1))
2739 return error("cannot apply binary patch to '%s' "
2740 "without full index line", name);
011f4274 2741
051308f6 2742 if (patch->old_name) {
81bf96bb
JH
2743 /*
2744 * See if the old one matches what the patch
051308f6 2745 * applies to.
011f4274 2746 */
b94f2eda 2747 hash_sha1_file(img->buf, img->len, blob_type, sha1);
051308f6
JH
2748 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
2749 return error("the patch applies to '%s' (%s), "
2750 "which does not match the "
2751 "current contents.",
2752 name, sha1_to_hex(sha1));
2753 }
2754 else {
2755 /* Otherwise, the old one must be empty. */
b94f2eda 2756 if (img->len)
051308f6
JH
2757 return error("the patch applies to an empty "
2758 "'%s' but it is not empty", name);
2759 }
011f4274 2760
0660626c 2761 get_sha1_hex(patch->new_sha1_prefix, sha1);
0bef57ee 2762 if (is_null_sha1(sha1)) {
b94f2eda 2763 clear_image(img);
051308f6 2764 return 0; /* deletion patch */
0660626c 2765 }
011f4274 2766
051308f6 2767 if (has_sha1_file(sha1)) {
0660626c 2768 /* We already have the postimage */
21666f1a 2769 enum object_type type;
051308f6 2770 unsigned long size;
c7f9cb14 2771 char *result;
051308f6 2772
c7f9cb14
PH
2773 result = read_sha1_file(sha1, &type, &size);
2774 if (!result)
051308f6
JH
2775 return error("the necessary postimage %s for "
2776 "'%s' cannot be read",
2777 patch->new_sha1_prefix, name);
b94f2eda
JH
2778 clear_image(img);
2779 img->buf = result;
2780 img->len = size;
c7f9cb14 2781 } else {
81bf96bb
JH
2782 /*
2783 * We have verified buf matches the preimage;
0660626c
JH
2784 * apply the patch data to it, which is stored
2785 * in the patch->fragments->{patch,size}.
011f4274 2786 */
b94f2eda 2787 if (apply_binary_fragment(img, patch))
051308f6
JH
2788 return error("binary patch does not apply to '%s'",
2789 name);
011f4274 2790
051308f6 2791 /* verify that the result matches */
b94f2eda 2792 hash_sha1_file(img->buf, img->len, blob_type, sha1);
051308f6 2793 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
c7f9cb14
PH
2794 return error("binary patch to '%s' creates incorrect result (expecting %s, got %s)",
2795 name, patch->new_sha1_prefix, sha1_to_hex(sha1));
011f4274 2796 }
3cca928d 2797
051308f6
JH
2798 return 0;
2799}
2800
b94f2eda 2801static int apply_fragments(struct image *img, struct patch *patch)
051308f6
JH
2802{
2803 struct fragment *frag = patch->fragments;
2804 const char *name = patch->old_name ? patch->old_name : patch->new_name;
cf1b7869
JH
2805 unsigned ws_rule = patch->ws_rule;
2806 unsigned inaccurate_eof = patch->inaccurate_eof;
334f8cb2 2807 int nth = 0;
051308f6
JH
2808
2809 if (patch->is_binary)
b94f2eda 2810 return apply_binary(img, patch);
051308f6 2811
3cca928d 2812 while (frag) {
334f8cb2
JH
2813 nth++;
2814 if (apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {
57dc397c
JH
2815 error("patch failed: %s:%ld", name, frag->oldpos);
2816 if (!apply_with_reject)
2817 return -1;
2818 frag->rejected = 1;
2819 }
3cca928d
LT
2820 frag = frag->next;
2821 }
30996652 2822 return 0;
3cca928d
LT
2823}
2824
c7f9cb14 2825static int read_file_or_gitlink(struct cache_entry *ce, struct strbuf *buf)
e06c5a6c
SV
2826{
2827 if (!ce)
2828 return 0;
2829
7a51ed66 2830 if (S_ISGITLINK(ce->ce_mode)) {
c7f9cb14
PH
2831 strbuf_grow(buf, 100);
2832 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(ce->sha1));
e06c5a6c
SV
2833 } else {
2834 enum object_type type;
c7f9cb14
PH
2835 unsigned long sz;
2836 char *result;
2837
2838 result = read_sha1_file(ce->sha1, &type, &sz);
2839 if (!result)
e06c5a6c 2840 return -1;
c7f9cb14
PH
2841 /* XXX read_sha1_file NUL-terminates */
2842 strbuf_attach(buf, result, sz, sz + 1);
e06c5a6c
SV
2843 }
2844 return 0;
2845}
2846
7a07841c
DZ
2847static struct patch *in_fn_table(const char *name)
2848{
c455c87c 2849 struct string_list_item *item;
7a07841c
DZ
2850
2851 if (name == NULL)
2852 return NULL;
2853
e8c8b713 2854 item = string_list_lookup(&fn_table, name);
7a07841c
DZ
2855 if (item != NULL)
2856 return (struct patch *)item->util;
2857
2858 return NULL;
2859}
2860
7fac0eef
MK
2861/*
2862 * item->util in the filename table records the status of the path.
2863 * Usually it points at a patch (whose result records the contents
2864 * of it after applying it), but it could be PATH_WAS_DELETED for a
2865 * path that a previously applied patch has already removed.
2866 */
2867 #define PATH_TO_BE_DELETED ((struct patch *) -2)
2868#define PATH_WAS_DELETED ((struct patch *) -1)
2869
2870static int to_be_deleted(struct patch *patch)
2871{
2872 return patch == PATH_TO_BE_DELETED;
2873}
2874
2875static int was_deleted(struct patch *patch)
2876{
2877 return patch == PATH_WAS_DELETED;
2878}
2879
7a07841c
DZ
2880static void add_to_fn_table(struct patch *patch)
2881{
c455c87c 2882 struct string_list_item *item;
7a07841c
DZ
2883
2884 /*
2885 * Always add new_name unless patch is a deletion
2886 * This should cover the cases for normal diffs,
2887 * file creations and copies
2888 */
2889 if (patch->new_name != NULL) {
78a395d3 2890 item = string_list_insert(&fn_table, patch->new_name);
7a07841c
DZ
2891 item->util = patch;
2892 }
2893
2894 /*
2895 * store a failure on rename/deletion cases because
2896 * later chunks shouldn't patch old names
2897 */
2898 if ((patch->new_name == NULL) || (patch->is_rename)) {
78a395d3 2899 item = string_list_insert(&fn_table, patch->old_name);
7fac0eef
MK
2900 item->util = PATH_WAS_DELETED;
2901 }
2902}
2903
2904static void prepare_fn_table(struct patch *patch)
2905{
2906 /*
2907 * store information about incoming file deletion
2908 */
2909 while (patch) {
2910 if ((patch->new_name == NULL) || (patch->is_rename)) {
2911 struct string_list_item *item;
78a395d3 2912 item = string_list_insert(&fn_table, patch->old_name);
7fac0eef
MK
2913 item->util = PATH_TO_BE_DELETED;
2914 }
2915 patch = patch->next;
7a07841c
DZ
2916 }
2917}
2918
04e4888e 2919static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce)
3cca928d 2920{
f285a2d7 2921 struct strbuf buf = STRBUF_INIT;
b94f2eda
JH
2922 struct image image;
2923 size_t len;
2924 char *img;
7a07841c 2925 struct patch *tpatch;
3cca928d 2926
a9a3e82e 2927 if (!(patch->is_copy || patch->is_rename) &&
7fac0eef
MK
2928 (tpatch = in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {
2929 if (was_deleted(tpatch)) {
7a07841c
DZ
2930 return error("patch %s has been renamed/deleted",
2931 patch->old_name);
2932 }
2933 /* We have a patched copy in memory use that */
2934 strbuf_add(&buf, tpatch->result, tpatch->resultsize);
2935 } else if (cached) {
c7f9cb14 2936 if (read_file_or_gitlink(ce, &buf))
e06c5a6c 2937 return error("read of %s failed", patch->old_name);
e06c5a6c
SV
2938 } else if (patch->old_name) {
2939 if (S_ISGITLINK(patch->old_mode)) {
c7f9cb14
PH
2940 if (ce) {
2941 read_file_or_gitlink(ce, &buf);
2942 } else {
e06c5a6c
SV
2943 /*
2944 * There is no way to apply subproject
2945 * patch without looking at the index.
2946 */
2947 patch->fragments = NULL;
e06c5a6c 2948 }
c7f9cb14
PH
2949 } else {
2950 if (read_old_data(st, patch->old_name, &buf))
2951 return error("read of %s failed", patch->old_name);
04e4888e
JH
2952 }
2953 }
6e7c92a9 2954
b94f2eda
JH
2955 img = strbuf_detach(&buf, &len);
2956 prepare_image(&image, img, len, !patch->is_binary);
2957
2958 if (apply_fragments(&image, patch) < 0)
57dc397c 2959 return -1; /* note with --reject this succeeds. */
b94f2eda
JH
2960 patch->result = image.buf;
2961 patch->resultsize = image.len;
7a07841c 2962 add_to_fn_table(patch);
b94f2eda 2963 free(image.line_allocated);
5aa7d94c 2964
4be60962 2965 if (0 < patch->is_delete && patch->resultsize)
5aa7d94c
LT
2966 return error("removal patch leaves file contents");
2967
3cca928d
LT
2968 return 0;
2969}
2970
64cab591
JH
2971static int check_to_create_blob(const char *new_name, int ok_if_exists)
2972{
2973 struct stat nst;
2974 if (!lstat(new_name, &nst)) {
2975 if (S_ISDIR(nst.st_mode) || ok_if_exists)
2976 return 0;
2977 /*
2978 * A leading component of new_name might be a symlink
2979 * that is going to be removed with this patch, but
2980 * still pointing at somewhere that has the path.
2981 * In such a case, path "new_name" does not exist as
2982 * far as git is concerned.
2983 */
57199892 2984 if (has_symlink_leading_path(new_name, strlen(new_name)))
64cab591
JH
2985 return 0;
2986
2987 return error("%s: already exists in working directory", new_name);
2988 }
2989 else if ((errno != ENOENT) && (errno != ENOTDIR))
2990 return error("%s: %s", new_name, strerror(errno));
2991 return 0;
2992}
2993
e06c5a6c
SV
2994static int verify_index_match(struct cache_entry *ce, struct stat *st)
2995{
7a51ed66 2996 if (S_ISGITLINK(ce->ce_mode)) {
e06c5a6c
SV
2997 if (!S_ISDIR(st->st_mode))
2998 return -1;
2999 return 0;
3000 }
56cac48c 3001 return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
e06c5a6c
SV
3002}
3003
5c47f4c6 3004static int check_preimage(struct patch *patch, struct cache_entry **ce, struct stat *st)
fab2c257
LT
3005{
3006 const char *old_name = patch->old_name;
a9a3e82e 3007 struct patch *tpatch = NULL;
5c47f4c6
JH
3008 int stat_ret = 0;
3009 unsigned st_mode = 0;
e06c5a6c
SV
3010
3011 /*
3012 * Make sure that we do not have local modifications from the
3013 * index when we are looking at the index. Also make sure
3014 * we have the preimage file to be patched in the work tree,
3015 * unless --cached, which tells git to apply only in the index.
3016 */
5c47f4c6
JH
3017 if (!old_name)
3018 return 0;
04e4888e 3019
5c47f4c6 3020 assert(patch->is_new <= 0);
a9a3e82e
JH
3021
3022 if (!(patch->is_copy || patch->is_rename) &&
7fac0eef
MK
3023 (tpatch = in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {
3024 if (was_deleted(tpatch))
7a07841c 3025 return error("%s: has been deleted/renamed", old_name);
7a07841c
DZ
3026 st_mode = tpatch->new_mode;
3027 } else if (!cached) {
5c47f4c6
JH
3028 stat_ret = lstat(old_name, st);
3029 if (stat_ret && errno != ENOENT)
3030 return error("%s: %s", old_name, strerror(errno));
3031 }
a9a3e82e 3032
7fac0eef
MK
3033 if (to_be_deleted(tpatch))
3034 tpatch = NULL;
3035
7a07841c 3036 if (check_index && !tpatch) {
5c47f4c6
JH
3037 int pos = cache_name_pos(old_name, strlen(old_name));
3038 if (pos < 0) {
3039 if (patch->is_new < 0)
3040 goto is_new;
3041 return error("%s: does not exist in index", old_name);
3042 }
3043 *ce = active_cache[pos];
3044 if (stat_ret < 0) {
3045 struct checkout costate;
3046 /* checkout */
54fd955c 3047 memset(&costate, 0, sizeof(costate));
5c47f4c6 3048 costate.base_dir = "";
5c47f4c6
JH
3049 costate.refresh_cache = 1;
3050 if (checkout_entry(*ce, &costate, NULL) ||
3051 lstat(old_name, st))
3052 return -1;
3053 }
3054 if (!cached && verify_index_match(*ce, st))
3055 return error("%s: does not match index", old_name);
3056 if (cached)
3057 st_mode = (*ce)->ce_mode;
3058 } else if (stat_ret < 0) {
3cca928d 3059 if (patch->is_new < 0)
5c47f4c6
JH
3060 goto is_new;
3061 return error("%s: %s", old_name, strerror(errno));
fab2c257 3062 }
a577284a 3063
e1e43898 3064 if (!cached && !tpatch)
5c47f4c6
JH
3065 st_mode = ce_mode_from_stat(*ce, st->st_mode);
3066
3067 if (patch->is_new < 0)
3068 patch->is_new = 0;
3069 if (!patch->old_mode)
3070 patch->old_mode = st_mode;
3071 if ((st_mode ^ patch->old_mode) & S_IFMT)
3072 return error("%s: wrong type", old_name);
3073 if (st_mode != patch->old_mode)
eca2a8f0 3074 warning("%s has type %o, expected %o",
5c47f4c6 3075 old_name, st_mode, patch->old_mode);
a15080e5 3076 if (!patch->new_mode && !patch->is_delete)
1f7903a3 3077 patch->new_mode = st_mode;
5c47f4c6
JH
3078 return 0;
3079
3080 is_new:
3081 patch->is_new = 1;
3082 patch->is_delete = 0;
3083 patch->old_name = NULL;
3084 return 0;
3085}
3086
7a07841c 3087static int check_patch(struct patch *patch)
5c47f4c6
JH
3088{
3089 struct stat st;
3090 const char *old_name = patch->old_name;
3091 const char *new_name = patch->new_name;
3092 const char *name = old_name ? old_name : new_name;
3093 struct cache_entry *ce = NULL;
7fac0eef 3094 struct patch *tpatch;
5c47f4c6
JH
3095 int ok_if_exists;
3096 int status;
3097
3098 patch->rejected = 1; /* we will drop this after we succeed */
3099
3100 status = check_preimage(patch, &ce, &st);
3101 if (status)
3102 return status;
3103 old_name = patch->old_name;
3104
7fac0eef
MK
3105 if ((tpatch = in_fn_table(new_name)) &&
3106 (was_deleted(tpatch) || to_be_deleted(tpatch)))
81bf96bb
JH
3107 /*
3108 * A type-change diff is always split into a patch to
7f95aef2
JH
3109 * delete old, immediately followed by a patch to
3110 * create new (see diff.c::run_diff()); in such a case
3111 * it is Ok that the entry to be deleted by the
3112 * previous patch is still in the working tree and in
3113 * the index.
3114 */
3115 ok_if_exists = 1;
3116 else
3117 ok_if_exists = 0;
3118
4be60962
JH
3119 if (new_name &&
3120 ((0 < patch->is_new) | (0 < patch->is_rename) | patch->is_copy)) {
7f95aef2
JH
3121 if (check_index &&
3122 cache_name_pos(new_name, strlen(new_name)) >= 0 &&
3123 !ok_if_exists)
a577284a 3124 return error("%s: already exists in index", new_name);
d91d4c2c 3125 if (!cached) {
64cab591
JH
3126 int err = check_to_create_blob(new_name, ok_if_exists);
3127 if (err)
3128 return err;
d91d4c2c 3129 }
35cc4bcd 3130 if (!patch->new_mode) {
4be60962 3131 if (0 < patch->is_new)
35cc4bcd
JS
3132 patch->new_mode = S_IFREG | 0644;
3133 else
3134 patch->new_mode = patch->old_mode;
3135 }
fab2c257 3136 }
3cca928d
LT
3137
3138 if (new_name && old_name) {
3139 int same = !strcmp(old_name, new_name);
3140 if (!patch->new_mode)
3141 patch->new_mode = patch->old_mode;
3142 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
3143 return error("new mode (%o) of %s does not match old mode (%o)%s%s",
3144 patch->new_mode, new_name, patch->old_mode,
3145 same ? "" : " of ", same ? "" : old_name);
04e4888e 3146 }
3cca928d 3147
04e4888e 3148 if (apply_data(patch, &st, ce) < 0)
011f4274 3149 return error("%s: patch does not apply", name);
57dc397c 3150 patch->rejected = 0;
a577284a 3151 return 0;
fab2c257
LT
3152}
3153
a577284a 3154static int check_patch_list(struct patch *patch)
19c58fb8 3155{
60b7f38e 3156 int err = 0;
a577284a 3157
7fac0eef 3158 prepare_fn_table(patch);
7a07841c 3159 while (patch) {
a2bf404e
JH
3160 if (apply_verbosely)
3161 say_patch_name(stderr,
3162 "Checking patch ", patch, "...\n");
7a07841c
DZ
3163 err |= check_patch(patch);
3164 patch = patch->next;
7f95aef2 3165 }
60b7f38e 3166 return err;
a577284a
LT
3167}
3168
ece7b749
JS
3169/* This function tries to read the sha1 from the current index */
3170static int get_current_sha1(const char *path, unsigned char *sha1)
3171{
3172 int pos;
3173
3174 if (read_cache() < 0)
3175 return -1;
3176 pos = cache_name_pos(path, strlen(path));
3177 if (pos < 0)
3178 return -1;
3179 hashcpy(sha1, active_cache[pos]->sha1);
3180 return 0;
3181}
3182
7a988699
JS
3183/* Build an index that contains the just the files needed for a 3way merge */
3184static void build_fake_ancestor(struct patch *list, const char *filename)
2cf67f1e
JH
3185{
3186 struct patch *patch;
2af202be 3187 struct index_state result = { NULL };
7a988699 3188 int fd;
2cf67f1e
JH
3189
3190 /* Once we start supporting the reverse patch, it may be
3191 * worth showing the new sha1 prefix, but until then...
3192 */
3193 for (patch = list; patch; patch = patch->next) {
3194 const unsigned char *sha1_ptr;
3195 unsigned char sha1[20];
7a988699 3196 struct cache_entry *ce;
2cf67f1e
JH
3197 const char *name;
3198
3199 name = patch->old_name ? patch->old_name : patch->new_name;
4be60962 3200 if (0 < patch->is_new)
7a988699 3201 continue;
2cf67f1e 3202 else if (get_sha1(patch->old_sha1_prefix, sha1))
ece7b749
JS
3203 /* git diff has no index line for mode/type changes */
3204 if (!patch->lines_added && !patch->lines_deleted) {
18cdf802 3205 if (get_current_sha1(patch->old_name, sha1))
ece7b749
JS
3206 die("mode change for %s, which is not "
3207 "in current HEAD", name);
3208 sha1_ptr = sha1;
3209 } else
3210 die("sha1 information is lacking or useless "
3211 "(%s).", name);
2cf67f1e
JH
3212 else
3213 sha1_ptr = sha1;
22943f1a 3214
7a988699 3215 ce = make_cache_entry(patch->old_mode, sha1_ptr, name, 0, 0);
048f2762
DP
3216 if (!ce)
3217 die("make_cache_entry failed for path '%s'", name);
7a988699
JS
3218 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))
3219 die ("Could not add %s to temporary index", name);
2cf67f1e 3220 }
7a988699
JS
3221
3222 fd = open(filename, O_WRONLY | O_CREAT, 0666);
3223 if (fd < 0 || write_index(&result, fd) || close(fd))
3224 die ("Could not write temporary index to %s", filename);
3225
3226 discard_index(&result);
2cf67f1e
JH
3227}
3228
a577284a
LT
3229static void stat_patch_list(struct patch *patch)
3230{
3231 int files, adds, dels;
3232
3233 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
3234 files++;
3235 adds += patch->lines_added;
3236 dels += patch->lines_deleted;
3237 show_stats(patch);
3238 }
3239
3240 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
3f40315a
LT
3241}
3242
7d8b7c21
JH
3243static void numstat_patch_list(struct patch *patch)
3244{
3245 for ( ; patch; patch = patch->next) {
3246 const char *name;
49e3343c 3247 name = patch->new_name ? patch->new_name : patch->old_name;
ef58d958
JH
3248 if (patch->is_binary)
3249 printf("-\t-\t");
3250 else
663af342
PH
3251 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
3252 write_name_quoted(name, stdout, line_termination);
7d8b7c21
JH
3253 }
3254}
3255
96c912a4
JH
3256static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
3257{
3258 if (mode)
3259 printf(" %s mode %06o %s\n", newdelete, mode, name);
3260 else
3261 printf(" %s %s\n", newdelete, name);
3262}
3263
3264static void show_mode_change(struct patch *p, int show_name)
3265{
3266 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
3267 if (show_name)
3268 printf(" mode change %06o => %06o %s\n",
3269 p->old_mode, p->new_mode, p->new_name);
3270 else
3271 printf(" mode change %06o => %06o\n",
3272 p->old_mode, p->new_mode);
3273 }
3274}
3275
3276static void show_rename_copy(struct patch *p)
3277{
3278 const char *renamecopy = p->is_rename ? "rename" : "copy";
3279 const char *old, *new;
3280
3281 /* Find common prefix */
3282 old = p->old_name;
3283 new = p->new_name;
3284 while (1) {
3285 const char *slash_old, *slash_new;
3286 slash_old = strchr(old, '/');
3287 slash_new = strchr(new, '/');
3288 if (!slash_old ||
3289 !slash_new ||
3290 slash_old - old != slash_new - new ||
3291 memcmp(old, new, slash_new - new))
3292 break;
3293 old = slash_old + 1;
3294 new = slash_new + 1;
3295 }
3296 /* p->old_name thru old is the common prefix, and old and new
3297 * through the end of names are renames
3298 */
3299 if (old != p->old_name)
3300 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
e30e814d 3301 (int)(old - p->old_name), p->old_name,
96c912a4
JH
3302 old, new, p->score);
3303 else
3304 printf(" %s %s => %s (%d%%)\n", renamecopy,
3305 p->old_name, p->new_name, p->score);
3306 show_mode_change(p, 0);
3307}
3308
3309static void summary_patch_list(struct patch *patch)
3310{
3311 struct patch *p;
3312
3313 for (p = patch; p; p = p->next) {
3314 if (p->is_new)
3315 show_file_mode_name("create", p->new_mode, p->new_name);
3316 else if (p->is_delete)
3317 show_file_mode_name("delete", p->old_mode, p->old_name);
3318 else {
3319 if (p->is_rename || p->is_copy)
3320 show_rename_copy(p);
3321 else {
3322 if (p->score) {
3323 printf(" rewrite %s (%d%%)\n",
3324 p->new_name, p->score);
3325 show_mode_change(p, 0);
3326 }
3327 else
3328 show_mode_change(p, 1);
3329 }
3330 }
3331 }
3332}
3333
3f40315a
LT
3334static void patch_stats(struct patch *patch)
3335{
3336 int lines = patch->lines_added + patch->lines_deleted;
3337
3338 if (lines > max_change)
3339 max_change = lines;
3340 if (patch->old_name) {
22943f1a
JH
3341 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
3342 if (!len)
3343 len = strlen(patch->old_name);
3f40315a
LT
3344 if (len > max_len)
3345 max_len = len;
3346 }
3347 if (patch->new_name) {
22943f1a
JH
3348 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
3349 if (!len)
3350 len = strlen(patch->new_name);
3f40315a
LT
3351 if (len > max_len)
3352 max_len = len;
3353 }
19c58fb8
LT
3354}
3355
aea19457 3356static void remove_file(struct patch *patch, int rmdir_empty)
5aa7d94c 3357{
7da3bf37 3358 if (update_index) {
5aa7d94c
LT
3359 if (remove_file_from_cache(patch->old_name) < 0)
3360 die("unable to remove %s from index", patch->old_name);
3361 }
d234b21c 3362 if (!cached) {
80d706af 3363 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
175a4948 3364 remove_path(patch->old_name);
d234b21c
AJ
3365 }
3366 }
5aa7d94c
LT
3367}
3368
3369static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
3370{
3371 struct stat st;
3372 struct cache_entry *ce;
3373 int namelen = strlen(path);
3374 unsigned ce_size = cache_entry_size(namelen);
3375
7da3bf37 3376 if (!update_index)
5aa7d94c
LT
3377 return;
3378
90321c10 3379 ce = xcalloc(1, ce_size);
5aa7d94c
LT
3380 memcpy(ce->name, path, namelen);
3381 ce->ce_mode = create_ce_mode(mode);
7a51ed66 3382 ce->ce_flags = namelen;
e06c5a6c
SV
3383 if (S_ISGITLINK(mode)) {
3384 const char *s = buf;
3385
3386 if (get_sha1_hex(s + strlen("Subproject commit "), ce->sha1))
3387 die("corrupt patch for subproject %s", path);
3388 } else {
3389 if (!cached) {
3390 if (lstat(path, &st) < 0)
0721c314
TR
3391 die_errno("unable to stat newly created file '%s'",
3392 path);
e06c5a6c
SV
3393 fill_stat_cache_info(ce, &st);
3394 }
3395 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
3396 die("unable to create backing store for newly created file %s", path);
04e4888e 3397 }
5aa7d94c
LT
3398 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
3399 die("unable to add cache entry for %s", path);
3400}
3401
1b668341
LT
3402static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
3403{
ac78e548 3404 int fd;
f285a2d7 3405 struct strbuf nbuf = STRBUF_INIT;
1b668341 3406
e06c5a6c
SV
3407 if (S_ISGITLINK(mode)) {
3408 struct stat st;
3409 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
3410 return 0;
3411 return mkdir(path, 0777);
3412 }
3413
78a8d641 3414 if (has_symlinks && S_ISLNK(mode))
2c71810b
JH
3415 /* Although buf:size is counted string, it also is NUL
3416 * terminated.
3417 */
1b668341 3418 return symlink(buf, path);
cc96fd09
JH
3419
3420 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
3421 if (fd < 0)
3422 return -1;
3423
5ecd293d
PH
3424 if (convert_to_working_tree(path, buf, size, &nbuf)) {
3425 size = nbuf.len;
3426 buf = nbuf.buf;
1b668341 3427 }
c7f9cb14
PH
3428 write_or_die(fd, buf, size);
3429 strbuf_release(&nbuf);
ac78e548 3430
1b668341 3431 if (close(fd) < 0)
d824cbba 3432 die_errno("closing file '%s'", path);
1b668341
LT
3433 return 0;
3434}
3435
5c8af185
LT
3436/*
3437 * We optimistically assume that the directories exist,
3438 * which is true 99% of the time anyway. If they don't,
3439 * we create them and try again.
3440 */
8361e1d4 3441static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
5c8af185 3442{
04e4888e
JH
3443 if (cached)
3444 return;
1b668341
LT
3445 if (!try_create_file(path, mode, buf, size))
3446 return;
5c8af185 3447
1b668341 3448 if (errno == ENOENT) {
8361e1d4
JR
3449 if (safe_create_leading_directories(path))
3450 return;
1b668341
LT
3451 if (!try_create_file(path, mode, buf, size))
3452 return;
5c8af185 3453 }
5c8af185 3454
56ac168f 3455 if (errno == EEXIST || errno == EACCES) {
c28c571c
JH
3456 /* We may be trying to create a file where a directory
3457 * used to be.
3458 */
3459 struct stat st;
0afa7644 3460 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
c28c571c
JH
3461 errno = EEXIST;
3462 }
3463
1b668341
LT
3464 if (errno == EEXIST) {
3465 unsigned int nr = getpid();
5c8af185 3466
1b668341 3467 for (;;) {
9fa03c17
AR
3468 char newpath[PATH_MAX];
3469 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
1b668341
LT
3470 if (!try_create_file(newpath, mode, buf, size)) {
3471 if (!rename(newpath, path))
3472 return;
691f1a28 3473 unlink_or_warn(newpath);
1b668341
LT
3474 break;
3475 }
3476 if (errno != EEXIST)
3477 break;
d9e08be9
AR
3478 ++nr;
3479 }
5c8af185 3480 }
0721c314 3481 die_errno("unable to write file '%s' mode %o", path, mode);
5c8af185
LT
3482}
3483
5aa7d94c
LT
3484static void create_file(struct patch *patch)
3485{
8361e1d4 3486 char *path = patch->new_name;
5aa7d94c
LT
3487 unsigned mode = patch->new_mode;
3488 unsigned long size = patch->resultsize;
3489 char *buf = patch->result;
3490
3491 if (!mode)
3492 mode = S_IFREG | 0644;
03ac6e64 3493 create_one_file(path, mode, buf, size);
1b668341 3494 add_index_file(path, mode, buf, size);
5aa7d94c
LT
3495}
3496
eed46644
JH
3497/* phase zero is to remove, phase one is to create */
3498static void write_out_one_result(struct patch *patch, int phase)
5aa7d94c
LT
3499{
3500 if (patch->is_delete > 0) {
eed46644 3501 if (phase == 0)
aea19457 3502 remove_file(patch, 1);
5aa7d94c
LT
3503 return;
3504 }
3505 if (patch->is_new > 0 || patch->is_copy) {
eed46644
JH
3506 if (phase == 1)
3507 create_file(patch);
5aa7d94c
LT
3508 return;
3509 }
3510 /*
3511 * Rename or modification boils down to the same
3512 * thing: remove the old, write the new
3513 */
eed46644 3514 if (phase == 0)
93969438 3515 remove_file(patch, patch->is_rename);
eed46644 3516 if (phase == 1)
57dc397c 3517 create_file(patch);
5aa7d94c
LT
3518}
3519
57dc397c
JH
3520static int write_out_one_reject(struct patch *patch)
3521{
82e2765f
JH
3522 FILE *rej;
3523 char namebuf[PATH_MAX];
57dc397c 3524 struct fragment *frag;
82e2765f 3525 int cnt = 0;
57dc397c 3526
82e2765f 3527 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
57dc397c
JH
3528 if (!frag->rejected)
3529 continue;
82e2765f
JH
3530 cnt++;
3531 }
3532
a2bf404e
JH
3533 if (!cnt) {
3534 if (apply_verbosely)
3535 say_patch_name(stderr,
3536 "Applied patch ", patch, " cleanly.\n");
82e2765f 3537 return 0;
a2bf404e 3538 }
82e2765f
JH
3539
3540 /* This should not happen, because a removal patch that leaves
3541 * contents are marked "rejected" at the patch level.
3542 */
3543 if (!patch->new_name)
3544 die("internal error");
3545
a2bf404e
JH
3546 /* Say this even without --verbose */
3547 say_patch_name(stderr, "Applying patch ", patch, " with");
3548 fprintf(stderr, " %d rejects...\n", cnt);
3549
82e2765f
JH
3550 cnt = strlen(patch->new_name);
3551 if (ARRAY_SIZE(namebuf) <= cnt + 5) {
3552 cnt = ARRAY_SIZE(namebuf) - 5;
eca2a8f0 3553 warning("truncating .rej filename to %.*s.rej",
82e2765f
JH
3554 cnt - 1, patch->new_name);
3555 }
3556 memcpy(namebuf, patch->new_name, cnt);
3557 memcpy(namebuf + cnt, ".rej", 5);
3558
3559 rej = fopen(namebuf, "w");
3560 if (!rej)
3561 return error("cannot open %s: %s", namebuf, strerror(errno));
3562
3563 /* Normal git tools never deal with .rej, so do not pretend
3564 * this is a git patch by saying --git nor give extended
3565 * headers. While at it, maybe please "kompare" that wants
3566 * the trailing TAB and some garbage at the end of line ;-).
3567 */
3568 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
3569 patch->new_name, patch->new_name);
0e9ee323 3570 for (cnt = 1, frag = patch->fragments;
82e2765f
JH
3571 frag;
3572 cnt++, frag = frag->next) {
3573 if (!frag->rejected) {
3574 fprintf(stderr, "Hunk #%d applied cleanly.\n", cnt);
3575 continue;
57dc397c 3576 }
82e2765f
JH
3577 fprintf(stderr, "Rejected hunk #%d.\n", cnt);
3578 fprintf(rej, "%.*s", frag->size, frag->patch);
57dc397c 3579 if (frag->patch[frag->size-1] != '\n')
82e2765f 3580 fputc('\n', rej);
57dc397c 3581 }
82e2765f
JH
3582 fclose(rej);
3583 return -1;
5aa7d94c
LT
3584}
3585
57dc397c 3586static int write_out_results(struct patch *list, int skipped_patch)
5aa7d94c 3587{
eed46644 3588 int phase;
57dc397c
JH
3589 int errs = 0;
3590 struct patch *l;
eed46644 3591
d854f783 3592 if (!list && !skipped_patch)
57dc397c 3593 return error("No changes");
f7b79707 3594
eed46644 3595 for (phase = 0; phase < 2; phase++) {
57dc397c 3596 l = list;
eed46644 3597 while (l) {
57dc397c
JH
3598 if (l->rejected)
3599 errs = 1;
82e2765f 3600 else {
57dc397c 3601 write_out_one_result(l, phase);
82e2765f 3602 if (phase == 1 && write_out_one_reject(l))
57dc397c
JH
3603 errs = 1;
3604 }
eed46644
JH
3605 l = l->next;
3606 }
5aa7d94c 3607 }
57dc397c 3608 return errs;
5aa7d94c
LT
3609}
3610
021b6e45 3611static struct lock_file lock_file;
5aa7d94c 3612
6ecb1ee2
JH
3613static struct string_list limit_by_name;
3614static int has_include;
3615static void add_name_limit(const char *name, int exclude)
3616{
3617 struct string_list_item *it;
3618
1d2f80fa 3619 it = string_list_append(&limit_by_name, name);
6ecb1ee2
JH
3620 it->util = exclude ? NULL : (void *) 1;
3621}
d854f783
JH
3622
3623static int use_patch(struct patch *p)
3624{
c7c81b3a 3625 const char *pathname = p->new_name ? p->new_name : p->old_name;
6ecb1ee2
JH
3626 int i;
3627
3628 /* Paths outside are not touched regardless of "--include" */
edf2e370
JH
3629 if (0 < prefix_length) {
3630 int pathlen = strlen(pathname);
3631 if (pathlen <= prefix_length ||
3632 memcmp(prefix, pathname, prefix_length))
3633 return 0;
3634 }
6ecb1ee2
JH
3635
3636 /* See if it matches any of exclude/include rule */
3637 for (i = 0; i < limit_by_name.nr; i++) {
3638 struct string_list_item *it = &limit_by_name.items[i];
3639 if (!fnmatch(it->string, pathname, 0))
3640 return (it->util != NULL);
3641 }
3642
3643 /*
3644 * If we had any include, a path that does not match any rule is
3645 * not used. Otherwise, we saw bunch of exclude rules (or none)
3646 * and such a path is used.
3647 */
3648 return !has_include;
d854f783
JH
3649}
3650
6ecb1ee2 3651
eac70c4f 3652static void prefix_one(char **name)
56185f49 3653{
eac70c4f
JS
3654 char *old_name = *name;
3655 if (!old_name)
3656 return;
3657 *name = xstrdup(prefix_filename(prefix, prefix_length, *name));
3658 free(old_name);
56185f49
JH
3659}
3660
3661static void prefix_patches(struct patch *p)
3662{
9987d7c5 3663 if (!prefix || p->is_toplevel_relative)
56185f49
JH
3664 return;
3665 for ( ; p; p = p->next) {
6c912f5b
JH
3666 if (p->new_name == p->old_name) {
3667 char *prefixed = p->new_name;
3668 prefix_one(&prefixed);
3669 p->new_name = p->old_name = prefixed;
3670 }
3671 else {
eac70c4f 3672 prefix_one(&p->new_name);
6c912f5b
JH
3673 prefix_one(&p->old_name);
3674 }
56185f49
JH
3675 }
3676}
3677
c14b9d1e
JS
3678#define INACCURATE_EOF (1<<0)
3679#define RECOUNT (1<<1)
3680
3681static int apply_patch(int fd, const char *filename, int options)
c1bb9350 3682{
9a76adeb 3683 size_t offset;
f285a2d7 3684 struct strbuf buf = STRBUF_INIT;
19c58fb8 3685 struct patch *list = NULL, **listp = &list;
d854f783 3686 int skipped_patch = 0;
c1bb9350 3687
7a07841c 3688 /* FIXME - memory leak when using multiple patch files as inputs */
c455c87c 3689 memset(&fn_table, 0, sizeof(struct string_list));
b5767dd6 3690 patch_input_file = filename;
9a76adeb 3691 read_patch_file(&buf, fd);
c1bb9350 3692 offset = 0;
9a76adeb 3693 while (offset < buf.len) {
19c58fb8
LT
3694 struct patch *patch;
3695 int nr;
3696
90321c10 3697 patch = xcalloc(1, sizeof(*patch));
c14b9d1e
JS
3698 patch->inaccurate_eof = !!(options & INACCURATE_EOF);
3699 patch->recount = !!(options & RECOUNT);
f94bf440 3700 nr = parse_chunk(buf.buf + offset, buf.len - offset, patch);
c1bb9350
LT
3701 if (nr < 0)
3702 break;
f686d030 3703 if (apply_in_reverse)
e5a94313 3704 reverse_patches(patch);
56185f49
JH
3705 if (prefix)
3706 prefix_patches(patch);
d854f783
JH
3707 if (use_patch(patch)) {
3708 patch_stats(patch);
3709 *listp = patch;
3710 listp = &patch->next;
56185f49
JH
3711 }
3712 else {
d854f783
JH
3713 /* perhaps free it a bit better? */
3714 free(patch);
3715 skipped_patch++;
3716 }
c1bb9350 3717 offset += nr;
c1bb9350 3718 }
19c58fb8 3719
81bf96bb 3720 if (whitespace_error && (ws_error_action == die_on_ws_error))
b5767dd6
JH
3721 apply = 0;
3722
7da3bf37
JH
3723 update_index = check_index && apply;
3724 if (update_index && newfd < 0)
30ca07a2
JH
3725 newfd = hold_locked_index(&lock_file, 1);
3726
5aa7d94c
LT
3727 if (check_index) {
3728 if (read_cache() < 0)
3729 die("unable to read index file");
3730 }
3731
57dc397c
JH
3732 if ((check || apply) &&
3733 check_patch_list(list) < 0 &&
3734 !apply_with_reject)
a577284a
LT
3735 exit(1);
3736
57dc397c
JH
3737 if (apply && write_out_results(list, skipped_patch))
3738 exit(1);
5aa7d94c 3739
7a988699
JS
3740 if (fake_ancestor)
3741 build_fake_ancestor(list, fake_ancestor);
2cf67f1e 3742
a577284a
LT
3743 if (diffstat)
3744 stat_patch_list(list);
19c58fb8 3745
7d8b7c21
JH
3746 if (numstat)
3747 numstat_patch_list(list);
3748
96c912a4
JH
3749 if (summary)
3750 summary_patch_list(list);
3751
9a76adeb 3752 strbuf_release(&buf);
c1bb9350
LT
3753 return 0;
3754}
3755
ef90d6d4 3756static int git_apply_config(const char *var, const char *value, void *cb)
2ae1c53b 3757{
8e4c6aa1
SB
3758 if (!strcmp(var, "apply.whitespace"))
3759 return git_config_string(&apply_default_whitespace, var, value);
86c91f91
GB
3760 else if (!strcmp(var, "apply.ignorewhitespace"))
3761 return git_config_string(&apply_default_ignorewhitespace, var, value);
ef90d6d4 3762 return git_default_config(var, value, cb);
2ae1c53b
JH
3763}
3764
f26c4940
MV
3765static int option_parse_exclude(const struct option *opt,
3766 const char *arg, int unset)
3767{
3768 add_name_limit(arg, 1);
3769 return 0;
3770}
3771
3772static int option_parse_include(const struct option *opt,
3773 const char *arg, int unset)
3774{
3775 add_name_limit(arg, 0);
3776 has_include = 1;
3777 return 0;
3778}
3779
3780static int option_parse_p(const struct option *opt,
3781 const char *arg, int unset)
3782{
3783 p_value = atoi(arg);
3784 p_value_known = 1;
3785 return 0;
3786}
3787
3788static int option_parse_z(const struct option *opt,
3789 const char *arg, int unset)
3790{
3791 if (unset)
3792 line_termination = '\n';
3793 else
3794 line_termination = 0;
3795 return 0;
3796}
3797
86c91f91
GB
3798static int option_parse_space_change(const struct option *opt,
3799 const char *arg, int unset)
3800{
3801 if (unset)
3802 ws_ignore_action = ignore_ws_none;
3803 else
3804 ws_ignore_action = ignore_ws_change;
3805 return 0;
3806}
3807
f26c4940
MV
3808static int option_parse_whitespace(const struct option *opt,
3809 const char *arg, int unset)
3810{
3811 const char **whitespace_option = opt->value;
3812
3813 *whitespace_option = arg;
3814 parse_whitespace_option(arg);
3815 return 0;
3816}
3817
3818static int option_parse_directory(const struct option *opt,
3819 const char *arg, int unset)
3820{
3821 root_len = strlen(arg);
3822 if (root_len && arg[root_len - 1] != '/') {
3823 char *new_root;
3824 root = new_root = xmalloc(root_len + 2);
3825 strcpy(new_root, arg);
3826 strcpy(new_root + root_len++, "/");
3827 } else
3828 root = arg;
3829 return 0;
3830}
2ae1c53b 3831
d1ea8962 3832int cmd_apply(int argc, const char **argv, const char *prefix_)
c1bb9350
LT
3833{
3834 int i;
57dc397c 3835 int errs = 0;
d1ea8962 3836 int is_not_gitdir = !startup_info->have_repository;
f26c4940
MV
3837 int binary;
3838 int force_apply = 0;
3eaa38da 3839
2ae1c53b 3840 const char *whitespace_option = NULL;
c1bb9350 3841
f26c4940 3842 struct option builtin_apply_options[] = {
f26c4940 3843 { OPTION_CALLBACK, 0, "exclude", NULL, "path",
40bac151 3844 "don't apply changes matching the given path",
f26c4940
MV
3845 0, option_parse_exclude },
3846 { OPTION_CALLBACK, 0, "include", NULL, "path",
3847 "apply changes matching the given path",
3848 0, option_parse_include },
3849 { OPTION_CALLBACK, 'p', NULL, NULL, "num",
3850 "remove <num> leading slashes from traditional diff paths",
3851 0, option_parse_p },
3852 OPT_BOOLEAN(0, "no-add", &no_add,
3853 "ignore additions made by the patch"),
3854 OPT_BOOLEAN(0, "stat", &diffstat,
3855 "instead of applying the patch, output diffstat for the input"),
092927c1 3856 { OPTION_BOOLEAN, 0, "allow-binary-replacement", &binary,
34aec9f5
SB
3857 NULL, "old option, now no-op",
3858 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },
092927c1 3859 { OPTION_BOOLEAN, 0, "binary", &binary,
34aec9f5
SB
3860 NULL, "old option, now no-op",
3861 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },
f26c4940
MV
3862 OPT_BOOLEAN(0, "numstat", &numstat,
3863 "shows number of added and deleted lines in decimal notation"),
3864 OPT_BOOLEAN(0, "summary", &summary,
3865 "instead of applying the patch, output a summary for the input"),
3866 OPT_BOOLEAN(0, "check", &check,
3867 "instead of applying the patch, see if the patch is applicable"),
3868 OPT_BOOLEAN(0, "index", &check_index,
3869 "make sure the patch is applicable to the current index"),
3870 OPT_BOOLEAN(0, "cached", &cached,
3871 "apply a patch without touching the working tree"),
3872 OPT_BOOLEAN(0, "apply", &force_apply,
3873 "also apply the patch (use with --stat/--summary/--check)"),
df217ed6 3874 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor,
f26c4940
MV
3875 "build a temporary index based on embedded index information"),
3876 { OPTION_CALLBACK, 'z', NULL, NULL, NULL,
3877 "paths are separated with NUL character",
3878 PARSE_OPT_NOARG, option_parse_z },
3879 OPT_INTEGER('C', NULL, &p_context,
3880 "ensure at least <n> lines of context match"),
3881 { OPTION_CALLBACK, 0, "whitespace", &whitespace_option, "action",
3882 "detect new or modified lines that have whitespace errors",
3883 0, option_parse_whitespace },
86c91f91
GB
3884 { OPTION_CALLBACK, 0, "ignore-space-change", NULL, NULL,
3885 "ignore changes in whitespace when finding context",
3886 PARSE_OPT_NOARG, option_parse_space_change },
3887 { OPTION_CALLBACK, 0, "ignore-whitespace", NULL, NULL,
3888 "ignore changes in whitespace when finding context",
3889 PARSE_OPT_NOARG, option_parse_space_change },
f26c4940
MV
3890 OPT_BOOLEAN('R', "reverse", &apply_in_reverse,
3891 "apply the patch in reverse"),
3892 OPT_BOOLEAN(0, "unidiff-zero", &unidiff_zero,
3893 "don't expect at least one line of context"),
3894 OPT_BOOLEAN(0, "reject", &apply_with_reject,
3895 "leave the rejected hunks in corresponding *.rej files"),
933e44d3
JH
3896 OPT_BOOLEAN(0, "allow-overlap", &allow_overlap,
3897 "allow overlapping hunks"),
fd03881a 3898 OPT__VERBOSE(&apply_verbosely, "be verbose"),
f26c4940
MV
3899 OPT_BIT(0, "inaccurate-eof", &options,
3900 "tolerate incorrectly detected missing new-line at the end of file",
3901 INACCURATE_EOF),
3902 OPT_BIT(0, "recount", &options,
3903 "do not trust the line counts in the hunk headers",
3904 RECOUNT),
3905 { OPTION_CALLBACK, 0, "directory", NULL, "root",
3906 "prepend <root> to all filenames",
3907 0, option_parse_directory },
3908 OPT_END()
3909 };
3910
d1ea8962 3911 prefix = prefix_;
dc7b2436 3912 prefix_length = prefix ? strlen(prefix) : 0;
ef90d6d4 3913 git_config(git_apply_config, NULL);
700ea479
JH
3914 if (apply_default_whitespace)
3915 parse_whitespace_option(apply_default_whitespace);
86c91f91
GB
3916 if (apply_default_ignorewhitespace)
3917 parse_ignorewhitespace_option(apply_default_ignorewhitespace);
67160271 3918
37782920 3919 argc = parse_options(argc, argv, prefix, builtin_apply_options,
f26c4940 3920 apply_usage, 0);
4c8d4c14 3921
f26c4940
MV
3922 if (apply_with_reject)
3923 apply = apply_verbosely = 1;
3924 if (!force_apply && (diffstat || numstat || summary || check || fake_ancestor))
3925 apply = 0;
3926 if (check_index && is_not_gitdir)
3927 die("--index outside a repository");
3928 if (cached) {
3929 if (is_not_gitdir)
3930 die("--cached outside a repository");
3931 check_index = 1;
3932 }
3933 for (i = 0; i < argc; i++) {
c1bb9350
LT
3934 const char *arg = argv[i];
3935 int fd;
3936
3937 if (!strcmp(arg, "-")) {
c14b9d1e 3938 errs |= apply_patch(0, "<stdin>", options);
4dfdbe10 3939 read_stdin = 0;
c1bb9350 3940 continue;
64912a67 3941 } else if (0 < prefix_length)
edf2e370
JH
3942 arg = prefix_filename(prefix, prefix_length, arg);
3943
c1bb9350
LT
3944 fd = open(arg, O_RDONLY);
3945 if (fd < 0)
d824cbba 3946 die_errno("can't open patch '%s'", arg);
4dfdbe10 3947 read_stdin = 0;
f21d6726 3948 set_default_whitespace_mode(whitespace_option);
c14b9d1e 3949 errs |= apply_patch(fd, arg, options);
c1bb9350
LT
3950 close(fd);
3951 }
f21d6726 3952 set_default_whitespace_mode(whitespace_option);
4dfdbe10 3953 if (read_stdin)
c14b9d1e 3954 errs |= apply_patch(0, "<stdin>", options);
fc96b7c9
JH
3955 if (whitespace_error) {
3956 if (squelch_whitespace_errors &&
3957 squelch_whitespace_errors < whitespace_error) {
3958 int squelched =
3959 whitespace_error - squelch_whitespace_errors;
eca2a8f0
MV
3960 warning("squelched %d "
3961 "whitespace error%s",
fc96b7c9
JH
3962 squelched,
3963 squelched == 1 ? "" : "s");
3964 }
81bf96bb 3965 if (ws_error_action == die_on_ws_error)
c94bf41c 3966 die("%d line%s add%s whitespace errors.",
fc96b7c9
JH
3967 whitespace_error,
3968 whitespace_error == 1 ? "" : "s",
3969 whitespace_error == 1 ? "s" : "");
d8c37945 3970 if (applied_after_fixing_ws && apply)
eca2a8f0
MV
3971 warning("%d line%s applied after"
3972 " fixing whitespace errors.",
c94bf41c
JH
3973 applied_after_fixing_ws,
3974 applied_after_fixing_ws == 1 ? "" : "s");
fc96b7c9 3975 else if (whitespace_error)
eca2a8f0 3976 warning("%d line%s add%s whitespace errors.",
fc96b7c9
JH
3977 whitespace_error,
3978 whitespace_error == 1 ? "" : "s",
3979 whitespace_error == 1 ? "s" : "");
3980 }
dbd0f7d3 3981
7da3bf37 3982 if (update_index) {
dbd0f7d3 3983 if (write_cache(newfd, active_cache, active_nr) ||
4ed7cd3a 3984 commit_locked_index(&lock_file))
021b6e45 3985 die("Unable to write new index file");
dbd0f7d3
EW
3986 }
3987
57dc397c 3988 return !!errs;
c1bb9350 3989}