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