]> git.ipfire.org Git - thirdparty/git.git/blame - apply.c
mingw: use lowercase includes for some Windows headers
[thirdparty/git.git] / apply.c
CommitLineData
13b5af22
CC
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 *
8 */
9
bb493a5c 10#include "cache.h"
0b027f6c 11#include "abspath.h"
36bf1958 12#include "alloc.h"
9b5041f6 13#include "base85.h"
b2141fc1 14#include "config.h"
cbd53a21 15#include "object-store.h"
13b5af22
CC
16#include "blob.h"
17#include "delta.h"
18#include "diff.h"
19#include "dir.h"
32a8f510 20#include "environment.h"
f394e093 21#include "gettext.h"
41771fa4 22#include "hex.h"
13b5af22
CC
23#include "xdiff-interface.h"
24#include "ll-merge.h"
bb493a5c 25#include "lockfile.h"
dabab1d6 26#include "object-name.h"
87bed179 27#include "object-file.h"
13b5af22
CC
28#include "parse-options.h"
29#include "quote.h"
30#include "rerere.h"
bb493a5c 31#include "apply.h"
d052cc03 32#include "entry.h"
e38da487 33#include "setup.h"
cb2a5135 34#include "symlinks.h"
64122313 35#include "ws.h"
d5ebb50d 36#include "wrapper.h"
bb493a5c 37
80e18412
TG
38struct gitdiff_data {
39 struct strbuf *root;
40 int linenr;
41 int p_value;
42};
43
bb493a5c
CC
44static void git_apply_config(void)
45{
9a53219f
JK
46 git_config_get_string("apply.whitespace", &apply_default_whitespace);
47 git_config_get_string("apply.ignorewhitespace", &apply_default_ignorewhitespace);
091489d0 48 git_config(git_xmerge_config, NULL);
bb493a5c
CC
49}
50
9123d5dd 51static int parse_whitespace_option(struct apply_state *state, const char *option)
bb493a5c
CC
52{
53 if (!option) {
54 state->ws_error_action = warn_on_ws_error;
55 return 0;
56 }
57 if (!strcmp(option, "warn")) {
58 state->ws_error_action = warn_on_ws_error;
59 return 0;
60 }
61 if (!strcmp(option, "nowarn")) {
62 state->ws_error_action = nowarn_ws_error;
63 return 0;
64 }
65 if (!strcmp(option, "error")) {
66 state->ws_error_action = die_on_ws_error;
67 return 0;
68 }
69 if (!strcmp(option, "error-all")) {
70 state->ws_error_action = die_on_ws_error;
71 state->squelch_whitespace_errors = 0;
72 return 0;
73 }
74 if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
75 state->ws_error_action = correct_ws_error;
76 return 0;
77 }
5a59a230
NTND
78 /*
79 * Please update $__git_whitespacelist in git-completion.bash
80 * when you add new options.
81 */
bb493a5c
CC
82 return error(_("unrecognized whitespace option '%s'"), option);
83}
84
9123d5dd
CC
85static int parse_ignorewhitespace_option(struct apply_state *state,
86 const char *option)
bb493a5c
CC
87{
88 if (!option || !strcmp(option, "no") ||
89 !strcmp(option, "false") || !strcmp(option, "never") ||
90 !strcmp(option, "none")) {
91 state->ws_ignore_action = ignore_ws_none;
92 return 0;
93 }
94 if (!strcmp(option, "change")) {
95 state->ws_ignore_action = ignore_ws_change;
96 return 0;
97 }
98 return error(_("unrecognized whitespace ignore option '%s'"), option);
99}
100
2f5a6d12 101int init_apply_state(struct apply_state *state,
82ea77ec 102 struct repository *repo,
6d058c88 103 const char *prefix)
bb493a5c
CC
104{
105 memset(state, 0, sizeof(*state));
106 state->prefix = prefix;
82ea77ec 107 state->repo = repo;
bb493a5c
CC
108 state->apply = 1;
109 state->line_termination = '\n';
110 state->p_value = 1;
111 state->p_context = UINT_MAX;
112 state->squelch_whitespace_errors = 5;
113 state->ws_error_action = warn_on_ws_error;
114 state->ws_ignore_action = ignore_ws_none;
115 state->linenr = 1;
bc40dfb1
ÆAB
116 string_list_init_nodup(&state->fn_table);
117 string_list_init_nodup(&state->limit_by_name);
4e9a3252
RS
118 strset_init(&state->removed_symlinks);
119 strset_init(&state->kept_symlinks);
bb493a5c
CC
120 strbuf_init(&state->root, 0);
121
122 git_apply_config();
123 if (apply_default_whitespace && parse_whitespace_option(state, apply_default_whitespace))
2f5a6d12 124 return -1;
bb493a5c 125 if (apply_default_ignorewhitespace && parse_ignorewhitespace_option(state, apply_default_ignorewhitespace))
2f5a6d12
CC
126 return -1;
127 return 0;
bb493a5c
CC
128}
129
130void clear_apply_state(struct apply_state *state)
131{
132 string_list_clear(&state->limit_by_name, 0);
4e9a3252
RS
133 strset_clear(&state->removed_symlinks);
134 strset_clear(&state->kept_symlinks);
bb493a5c
CC
135 strbuf_release(&state->root);
136
137 /* &state->fn_table is cleared at the end of apply_patch() */
138}
b6446d54 139
75065357 140static void mute_routine(const char *msg UNUSED, va_list params UNUSED)
45b78d8b
CC
141{
142 /* do nothing */
143}
144
b6446d54
CC
145int check_apply_state(struct apply_state *state, int force_apply)
146{
147 int is_not_gitdir = !startup_info->have_repository;
148
149 if (state->apply_with_reject && state->threeway)
12909b6b 150 return error(_("options '%s' and '%s' cannot be used together"), "--reject", "--3way");
b6446d54
CC
151 if (state->threeway) {
152 if (is_not_gitdir)
59bb0009 153 return error(_("'%s' outside a repository"), "--3way");
b6446d54
CC
154 state->check_index = 1;
155 }
a46160d2
CC
156 if (state->apply_with_reject) {
157 state->apply = 1;
158 if (state->apply_verbosity == verbosity_normal)
159 state->apply_verbosity = verbosity_verbose;
160 }
b6446d54
CC
161 if (!force_apply && (state->diffstat || state->numstat || state->summary || state->check || state->fake_ancestor))
162 state->apply = 0;
163 if (state->check_index && is_not_gitdir)
59bb0009 164 return error(_("'%s' outside a repository"), "--index");
b6446d54
CC
165 if (state->cached) {
166 if (is_not_gitdir)
59bb0009 167 return error(_("'%s' outside a repository"), "--cached");
b6446d54
CC
168 state->check_index = 1;
169 }
cff5dc09
NTND
170 if (state->ita_only && (state->check_index || is_not_gitdir))
171 state->ita_only = 0;
b6446d54
CC
172 if (state->check_index)
173 state->unsafe_paths = 0;
b6446d54 174
45b78d8b
CC
175 if (state->apply_verbosity <= verbosity_silent) {
176 state->saved_error_routine = get_error_routine();
177 state->saved_warn_routine = get_warn_routine();
178 set_error_routine(mute_routine);
179 set_warn_routine(mute_routine);
180 }
181
b6446d54
CC
182 return 0;
183}
13b5af22
CC
184
185static void set_default_whitespace_mode(struct apply_state *state)
186{
187 if (!state->whitespace_option && !apply_default_whitespace)
188 state->ws_error_action = (state->apply ? warn_on_ws_error : nowarn_ws_error);
189}
190
191/*
192 * This represents one "hunk" from a patch, starting with
193 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The
194 * patch text is pointed at by patch, and its byte length
195 * is stored in size. leading and trailing are the number
196 * of context lines.
197 */
198struct fragment {
199 unsigned long leading, trailing;
200 unsigned long oldpos, oldlines;
201 unsigned long newpos, newlines;
202 /*
203 * 'patch' is usually borrowed from buf in apply_patch(),
204 * but some codepaths store an allocated buffer.
205 */
206 const char *patch;
207 unsigned free_patch:1,
208 rejected:1;
209 int size;
210 int linenr;
211 struct fragment *next;
212};
213
214/*
215 * When dealing with a binary patch, we reuse "leading" field
216 * to store the type of the binary hunk, either deflated "delta"
217 * or deflated "literal".
218 */
219#define binary_patch_method leading
220#define BINARY_DELTA_DEFLATED 1
221#define BINARY_LITERAL_DEFLATED 2
222
13b5af22
CC
223static void free_fragment_list(struct fragment *list)
224{
225 while (list) {
226 struct fragment *next = list->next;
227 if (list->free_patch)
228 free((char *)list->patch);
229 free(list);
230 list = next;
231 }
232}
233
4998e93f 234void release_patch(struct patch *patch)
13b5af22
CC
235{
236 free_fragment_list(patch->fragments);
237 free(patch->def_name);
238 free(patch->old_name);
239 free(patch->new_name);
240 free(patch->result);
4998e93f
ÆAB
241}
242
243static void free_patch(struct patch *patch)
244{
245 release_patch(patch);
13b5af22
CC
246 free(patch);
247}
248
249static void free_patch_list(struct patch *list)
250{
251 while (list) {
252 struct patch *next = list->next;
253 free_patch(list);
254 list = next;
255 }
256}
257
258/*
259 * A line in a file, len-bytes long (includes the terminating LF,
260 * except for an incomplete line at the end if the file ends with
261 * one), and its contents hashes to 'hash'.
262 */
263struct line {
264 size_t len;
265 unsigned hash : 24;
266 unsigned flag : 8;
267#define LINE_COMMON 1
268#define LINE_PATCHED 2
269};
270
271/*
272 * This represents a "file", which is an array of "lines".
273 */
274struct image {
275 char *buf;
276 size_t len;
277 size_t nr;
278 size_t alloc;
279 struct line *line_allocated;
280 struct line *line;
281};
282
283static uint32_t hash_line(const char *cp, size_t len)
284{
285 size_t i;
286 uint32_t h;
287 for (i = 0, h = 0; i < len; i++) {
288 if (!isspace(cp[i])) {
289 h = h * 3 + (cp[i] & 0xff);
290 }
291 }
292 return h;
293}
294
295/*
296 * Compare lines s1 of length n1 and s2 of length n2, ignoring
297 * whitespace difference. Returns 1 if they match, 0 otherwise
298 */
299static int fuzzy_matchlines(const char *s1, size_t n1,
300 const char *s2, size_t n2)
301{
6ce15ce5
RS
302 const char *end1 = s1 + n1;
303 const char *end2 = s2 + n2;
13b5af22
CC
304
305 /* ignore line endings */
6ce15ce5
RS
306 while (s1 < end1 && (end1[-1] == '\r' || end1[-1] == '\n'))
307 end1--;
308 while (s2 < end2 && (end2[-1] == '\r' || end2[-1] == '\n'))
309 end2--;
13b5af22 310
6ce15ce5
RS
311 while (s1 < end1 && s2 < end2) {
312 if (isspace(*s1)) {
313 /*
314 * Skip whitespace. We check on both buffers
315 * because we don't want "a b" to match "ab".
316 */
317 if (!isspace(*s2))
318 return 0;
319 while (s1 < end1 && isspace(*s1))
13b5af22 320 s1++;
6ce15ce5 321 while (s2 < end2 && isspace(*s2))
13b5af22 322 s2++;
6ce15ce5 323 } else if (*s1++ != *s2++)
13b5af22 324 return 0;
13b5af22
CC
325 }
326
6ce15ce5
RS
327 /* If we reached the end on one side only, lines don't match. */
328 return s1 == end1 && s2 == end2;
13b5af22
CC
329}
330
331static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
332{
333 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
334 img->line_allocated[img->nr].len = len;
335 img->line_allocated[img->nr].hash = hash_line(bol, len);
336 img->line_allocated[img->nr].flag = flag;
337 img->nr++;
338}
339
340/*
341 * "buf" has the file contents to be patched (read from various sources).
342 * attach it to "image" and add line-based index to it.
343 * "image" now owns the "buf".
344 */
345static void prepare_image(struct image *image, char *buf, size_t len,
346 int prepare_linetable)
347{
348 const char *cp, *ep;
349
350 memset(image, 0, sizeof(*image));
351 image->buf = buf;
352 image->len = len;
353
354 if (!prepare_linetable)
355 return;
356
357 ep = image->buf + image->len;
358 cp = image->buf;
359 while (cp < ep) {
360 const char *next;
361 for (next = cp; next < ep && *next != '\n'; next++)
362 ;
363 if (next < ep)
364 next++;
365 add_line_info(image, cp, next - cp, 0);
366 cp = next;
367 }
368 image->line = image->line_allocated;
369}
370
371static void clear_image(struct image *image)
372{
373 free(image->buf);
374 free(image->line_allocated);
375 memset(image, 0, sizeof(*image));
376}
377
378/* fmt must contain _one_ %s and no other substitution */
379static void say_patch_name(FILE *output, const char *fmt, struct patch *patch)
380{
381 struct strbuf sb = STRBUF_INIT;
382
383 if (patch->old_name && patch->new_name &&
384 strcmp(patch->old_name, patch->new_name)) {
385 quote_c_style(patch->old_name, &sb, NULL, 0);
386 strbuf_addstr(&sb, " => ");
387 quote_c_style(patch->new_name, &sb, NULL, 0);
388 } else {
389 const char *n = patch->new_name;
390 if (!n)
391 n = patch->old_name;
392 quote_c_style(n, &sb, NULL, 0);
393 }
394 fprintf(output, fmt, sb.buf);
395 fputc('\n', output);
396 strbuf_release(&sb);
397}
398
399#define SLOP (16)
400
f1c0e394
TB
401/*
402 * apply.c isn't equipped to handle arbitrarily large patches, because
403 * it intermingles `unsigned long` with `int` for the type used to store
404 * buffer lengths.
405 *
406 * Only process patches that are just shy of 1 GiB large in order to
407 * avoid any truncation or overflow issues.
408 */
409#define MAX_APPLY_SIZE (1024UL * 1024 * 1023)
410
13b5af22
CC
411static int read_patch_file(struct strbuf *sb, int fd)
412{
f1c0e394 413 if (strbuf_read(sb, fd, 0) < 0 || sb->len >= MAX_APPLY_SIZE)
13b5af22
CC
414 return error_errno("git apply: failed to read");
415
416 /*
417 * Make sure that we have some slop in the buffer
418 * so that we can do speculative "memcmp" etc, and
419 * see to it that it is NUL-filled.
420 */
421 strbuf_grow(sb, SLOP);
422 memset(sb->buf + sb->len, 0, SLOP);
423 return 0;
424}
425
426static unsigned long linelen(const char *buffer, unsigned long size)
427{
428 unsigned long len = 0;
429 while (size--) {
430 len++;
431 if (*buffer++ == '\n')
432 break;
433 }
434 return len;
435}
436
437static int is_dev_null(const char *str)
438{
439 return skip_prefix(str, "/dev/null", &str) && isspace(*str);
440}
441
442#define TERM_SPACE 1
443#define TERM_TAB 2
444
445static int name_terminate(int c, int terminate)
446{
447 if (c == ' ' && !(terminate & TERM_SPACE))
448 return 0;
449 if (c == '\t' && !(terminate & TERM_TAB))
450 return 0;
451
452 return 1;
453}
454
455/* remove double slashes to make --index work with such filenames */
456static char *squash_slash(char *name)
457{
458 int i = 0, j = 0;
459
460 if (!name)
461 return NULL;
462
463 while (name[i]) {
464 if ((name[j++] = name[i++]) == '/')
465 while (name[i] == '/')
466 i++;
467 }
468 name[j] = '\0';
469 return name;
470}
471
877a833b 472static char *find_name_gnu(struct strbuf *root,
13b5af22 473 const char *line,
13b5af22
CC
474 int p_value)
475{
476 struct strbuf name = STRBUF_INIT;
477 char *cp;
478
479 /*
480 * Proposed "new-style" GNU patch/diff format; see
3eae30e4 481 * https://lore.kernel.org/git/7vll0wvb2a.fsf@assigned-by-dhcp.cox.net/
13b5af22
CC
482 */
483 if (unquote_c_style(&name, line, NULL)) {
484 strbuf_release(&name);
485 return NULL;
486 }
487
488 for (cp = name.buf; p_value; p_value--) {
489 cp = strchr(cp, '/');
490 if (!cp) {
491 strbuf_release(&name);
492 return NULL;
493 }
494 cp++;
495 }
496
497 strbuf_remove(&name, 0, cp - name.buf);
877a833b
TG
498 if (root->len)
499 strbuf_insert(&name, 0, root->buf, root->len);
13b5af22
CC
500 return squash_slash(strbuf_detach(&name, NULL));
501}
502
503static size_t sane_tz_len(const char *line, size_t len)
504{
505 const char *tz, *p;
506
507 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
508 return 0;
509 tz = line + len - strlen(" +0500");
510
511 if (tz[1] != '+' && tz[1] != '-')
512 return 0;
513
514 for (p = tz + 2; p != line + len; p++)
515 if (!isdigit(*p))
516 return 0;
517
518 return line + len - tz;
519}
520
521static size_t tz_with_colon_len(const char *line, size_t len)
522{
523 const char *tz, *p;
524
525 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
526 return 0;
527 tz = line + len - strlen(" +08:00");
528
529 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
530 return 0;
531 p = tz + 2;
532 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
533 !isdigit(*p++) || !isdigit(*p++))
534 return 0;
535
536 return line + len - tz;
537}
538
539static size_t date_len(const char *line, size_t len)
540{
541 const char *date, *p;
542
543 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
544 return 0;
545 p = date = line + len - strlen("72-02-05");
546
547 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
548 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
549 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */
550 return 0;
551
552 if (date - line >= strlen("19") &&
553 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */
554 date -= strlen("19");
555
556 return line + len - date;
557}
558
559static size_t short_time_len(const char *line, size_t len)
560{
561 const char *time, *p;
562
563 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
564 return 0;
565 p = time = line + len - strlen(" 07:01:32");
566
567 /* Permit 1-digit hours? */
568 if (*p++ != ' ' ||
569 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
570 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
571 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */
572 return 0;
573
574 return line + len - time;
575}
576
577static size_t fractional_time_len(const char *line, size_t len)
578{
579 const char *p;
580 size_t n;
581
582 /* Expected format: 19:41:17.620000023 */
583 if (!len || !isdigit(line[len - 1]))
584 return 0;
585 p = line + len - 1;
586
587 /* Fractional seconds. */
588 while (p > line && isdigit(*p))
589 p--;
590 if (*p != '.')
591 return 0;
592
593 /* Hours, minutes, and whole seconds. */
594 n = short_time_len(line, p - line);
595 if (!n)
596 return 0;
597
598 return line + len - p + n;
599}
600
601static size_t trailing_spaces_len(const char *line, size_t len)
602{
603 const char *p;
604
605 /* Expected format: ' ' x (1 or more) */
606 if (!len || line[len - 1] != ' ')
607 return 0;
608
609 p = line + len;
610 while (p != line) {
611 p--;
612 if (*p != ' ')
613 return line + len - (p + 1);
614 }
615
616 /* All spaces! */
617 return len;
618}
619
620static size_t diff_timestamp_len(const char *line, size_t len)
621{
622 const char *end = line + len;
623 size_t n;
624
625 /*
626 * Posix: 2010-07-05 19:41:17
627 * GNU: 2010-07-05 19:41:17.620000023 -0500
628 */
629
630 if (!isdigit(end[-1]))
631 return 0;
632
633 n = sane_tz_len(line, end - line);
634 if (!n)
635 n = tz_with_colon_len(line, end - line);
636 end -= n;
637
638 n = short_time_len(line, end - line);
639 if (!n)
640 n = fractional_time_len(line, end - line);
641 end -= n;
642
643 n = date_len(line, end - line);
644 if (!n) /* No date. Too bad. */
645 return 0;
646 end -= n;
647
648 if (end == line) /* No space before date. */
649 return 0;
650 if (end[-1] == '\t') { /* Success! */
651 end--;
652 return line + len - end;
653 }
654 if (end[-1] != ' ') /* No space before date. */
655 return 0;
656
657 /* Whitespace damage. */
658 end -= trailing_spaces_len(line, end - line);
659 return line + len - end;
660}
661
877a833b 662static char *find_name_common(struct strbuf *root,
13b5af22
CC
663 const char *line,
664 const char *def,
665 int p_value,
666 const char *end,
667 int terminate)
668{
669 int len;
670 const char *start = NULL;
671
672 if (p_value == 0)
673 start = line;
674 while (line != end) {
675 char c = *line;
676
677 if (!end && isspace(c)) {
678 if (c == '\n')
679 break;
680 if (name_terminate(c, terminate))
681 break;
682 }
683 line++;
684 if (c == '/' && !--p_value)
685 start = line;
686 }
687 if (!start)
688 return squash_slash(xstrdup_or_null(def));
689 len = line - start;
690 if (!len)
691 return squash_slash(xstrdup_or_null(def));
692
693 /*
694 * Generally we prefer the shorter name, especially
695 * if the other one is just a variation of that with
696 * something else tacked on to the end (ie "file.orig"
697 * or "file~").
698 */
699 if (def) {
700 int deflen = strlen(def);
701 if (deflen < len && !strncmp(start, def, deflen))
702 return squash_slash(xstrdup(def));
703 }
704
877a833b
TG
705 if (root->len) {
706 char *ret = xstrfmt("%s%.*s", root->buf, len, start);
13b5af22
CC
707 return squash_slash(ret);
708 }
709
710 return squash_slash(xmemdupz(start, len));
711}
712
877a833b 713static char *find_name(struct strbuf *root,
13b5af22
CC
714 const char *line,
715 char *def,
716 int p_value,
717 int terminate)
718{
719 if (*line == '"') {
877a833b 720 char *name = find_name_gnu(root, line, p_value);
13b5af22
CC
721 if (name)
722 return name;
723 }
724
877a833b 725 return find_name_common(root, line, def, p_value, NULL, terminate);
13b5af22
CC
726}
727
877a833b 728static char *find_name_traditional(struct strbuf *root,
13b5af22
CC
729 const char *line,
730 char *def,
731 int p_value)
732{
733 size_t len;
734 size_t date_len;
735
736 if (*line == '"') {
877a833b 737 char *name = find_name_gnu(root, line, p_value);
13b5af22
CC
738 if (name)
739 return name;
740 }
741
742 len = strchrnul(line, '\n') - line;
743 date_len = diff_timestamp_len(line, len);
744 if (!date_len)
877a833b 745 return find_name_common(root, line, def, p_value, NULL, TERM_TAB);
13b5af22
CC
746 len -= date_len;
747
877a833b 748 return find_name_common(root, line, def, p_value, line + len, 0);
13b5af22
CC
749}
750
13b5af22
CC
751/*
752 * Given the string after "--- " or "+++ ", guess the appropriate
753 * p_value for the given patch.
754 */
755static int guess_p_value(struct apply_state *state, const char *nameline)
756{
757 char *name, *cp;
758 int val = -1;
759
760 if (is_dev_null(nameline))
761 return -1;
877a833b 762 name = find_name_traditional(&state->root, nameline, NULL, 0);
13b5af22
CC
763 if (!name)
764 return -1;
765 cp = strchr(name, '/');
766 if (!cp)
767 val = 0;
768 else if (state->prefix) {
769 /*
770 * Does it begin with "a/$our-prefix" and such? Then this is
771 * very likely to apply to our directory.
772 */
881529c8 773 if (starts_with(name, state->prefix))
13b5af22
CC
774 val = count_slashes(state->prefix);
775 else {
776 cp++;
881529c8 777 if (starts_with(cp, state->prefix))
13b5af22
CC
778 val = count_slashes(state->prefix) + 1;
779 }
780 }
781 free(name);
782 return val;
783}
784
785/*
786 * Does the ---/+++ line have the POSIX timestamp after the last HT?
787 * GNU diff puts epoch there to signal a creation/deletion event. Is
788 * this such a timestamp?
789 */
790static int has_epoch_timestamp(const char *nameline)
791{
792 /*
793 * We are only interested in epoch timestamp; any non-zero
794 * fraction cannot be one, hence "(\.0+)?" in the regexp below.
795 * For the same reason, the date must be either 1969-12-31 or
796 * 1970-01-01, and the seconds part must be "00".
797 */
798 const char stamp_regexp[] =
0db3dc75 799 "^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?"
13b5af22
CC
800 " "
801 "([-+][0-2][0-9]:?[0-5][0-9])\n";
802 const char *timestamp = NULL, *cp, *colon;
803 static regex_t *stamp;
804 regmatch_t m[10];
e4905019 805 int zoneoffset, epoch_hour, hour, minute;
13b5af22
CC
806 int status;
807
808 for (cp = nameline; *cp != '\n'; cp++) {
809 if (*cp == '\t')
810 timestamp = cp + 1;
811 }
812 if (!timestamp)
813 return 0;
e4905019
RS
814
815 /*
816 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
817 * (west of GMT) or 1970-01-01 (east of GMT)
818 */
0db3dc75 819 if (skip_prefix(timestamp, "1969-12-31 ", &timestamp))
e4905019 820 epoch_hour = 24;
0db3dc75 821 else if (skip_prefix(timestamp, "1970-01-01 ", &timestamp))
e4905019
RS
822 epoch_hour = 0;
823 else
824 return 0;
825
13b5af22
CC
826 if (!stamp) {
827 stamp = xmalloc(sizeof(*stamp));
828 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
829 warning(_("Cannot prepare timestamp regexp %s"),
830 stamp_regexp);
831 return 0;
832 }
833 }
834
835 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
836 if (status) {
837 if (status != REG_NOMATCH)
838 warning(_("regexec returned %d for input: %s"),
839 status, timestamp);
840 return 0;
841 }
842
0db3dc75
RS
843 hour = strtol(timestamp, NULL, 10);
844 minute = strtol(timestamp + m[1].rm_so, NULL, 10);
e4905019 845
13b5af22
CC
846 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
847 if (*colon == ':')
848 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
849 else
850 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
851 if (timestamp[m[3].rm_so] == '-')
852 zoneoffset = -zoneoffset;
853
e4905019 854 return hour * 60 + minute - zoneoffset == epoch_hour * 60;
13b5af22
CC
855}
856
857/*
858 * Get the name etc info from the ---/+++ lines of a traditional patch header
859 *
860 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
861 * files, we can happily check the index for a match, but for creating a
862 * new file we should try to match whatever "patch" does. I have no idea.
863 */
864static int parse_traditional_patch(struct apply_state *state,
865 const char *first,
866 const char *second,
867 struct patch *patch)
868{
869 char *name;
870
871 first += 4; /* skip "--- " */
872 second += 4; /* skip "+++ " */
873 if (!state->p_value_known) {
874 int p, q;
875 p = guess_p_value(state, first);
876 q = guess_p_value(state, second);
877 if (p < 0) p = q;
878 if (0 <= p && p == q) {
879 state->p_value = p;
880 state->p_value_known = 1;
881 }
882 }
883 if (is_dev_null(first)) {
884 patch->is_new = 1;
885 patch->is_delete = 0;
877a833b 886 name = find_name_traditional(&state->root, second, NULL, state->p_value);
13b5af22
CC
887 patch->new_name = name;
888 } else if (is_dev_null(second)) {
889 patch->is_new = 0;
890 patch->is_delete = 1;
877a833b 891 name = find_name_traditional(&state->root, first, NULL, state->p_value);
13b5af22
CC
892 patch->old_name = name;
893 } else {
894 char *first_name;
877a833b
TG
895 first_name = find_name_traditional(&state->root, first, NULL, state->p_value);
896 name = find_name_traditional(&state->root, second, first_name, state->p_value);
13b5af22
CC
897 free(first_name);
898 if (has_epoch_timestamp(first)) {
899 patch->is_new = 1;
900 patch->is_delete = 0;
901 patch->new_name = name;
902 } else if (has_epoch_timestamp(second)) {
903 patch->is_new = 0;
904 patch->is_delete = 1;
905 patch->old_name = name;
906 } else {
907 patch->old_name = name;
908 patch->new_name = xstrdup_or_null(name);
909 }
910 }
911 if (!name)
912 return error(_("unable to find filename in patch at line %d"), state->linenr);
913
914 return 0;
915}
916
0cff8699
JK
917static int gitdiff_hdrend(struct gitdiff_data *state UNUSED,
918 const char *line UNUSED,
919 struct patch *patch UNUSED)
13b5af22
CC
920{
921 return 1;
922}
923
924/*
925 * We're anal about diff header consistency, to make
926 * sure that we don't end up having strange ambiguous
927 * patches floating around.
928 *
929 * As a result, gitdiff_{old|new}name() will check
930 * their names against any previous information, just
931 * to make sure..
932 */
933#define DIFF_OLD_NAME 0
934#define DIFF_NEW_NAME 1
935
80e18412 936static int gitdiff_verify_name(struct gitdiff_data *state,
13b5af22
CC
937 const char *line,
938 int isnull,
939 char **name,
940 int side)
941{
942 if (!*name && !isnull) {
80e18412 943 *name = find_name(state->root, line, NULL, state->p_value, TERM_TAB);
13b5af22
CC
944 return 0;
945 }
946
947 if (*name) {
13b5af22
CC
948 char *another;
949 if (isnull)
950 return error(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
951 *name, state->linenr);
80e18412 952 another = find_name(state->root, line, NULL, state->p_value, TERM_TAB);
2d105451 953 if (!another || strcmp(another, *name)) {
13b5af22
CC
954 free(another);
955 return error((side == DIFF_NEW_NAME) ?
956 _("git apply: bad git-diff - inconsistent new filename on line %d") :
957 _("git apply: bad git-diff - inconsistent old filename on line %d"), state->linenr);
958 }
959 free(another);
960 } else {
e454ad4b 961 if (!is_dev_null(line))
13b5af22
CC
962 return error(_("git apply: bad git-diff - expected /dev/null on line %d"), state->linenr);
963 }
964
965 return 0;
966}
967
80e18412 968static int gitdiff_oldname(struct gitdiff_data *state,
13b5af22
CC
969 const char *line,
970 struct patch *patch)
971{
972 return gitdiff_verify_name(state, line,
973 patch->is_new, &patch->old_name,
974 DIFF_OLD_NAME);
975}
976
80e18412 977static int gitdiff_newname(struct gitdiff_data *state,
13b5af22
CC
978 const char *line,
979 struct patch *patch)
980{
981 return gitdiff_verify_name(state, line,
982 patch->is_delete, &patch->new_name,
983 DIFF_NEW_NAME);
984}
985
44e5471a
RS
986static int parse_mode_line(const char *line, int linenr, unsigned int *mode)
987{
988 char *end;
989 *mode = strtoul(line, &end, 8);
990 if (end == line || !isspace(*end))
991 return error(_("invalid mode on line %d: %s"), linenr, line);
992 return 0;
993}
994
80e18412 995static int gitdiff_oldmode(struct gitdiff_data *state,
13b5af22
CC
996 const char *line,
997 struct patch *patch)
998{
44e5471a 999 return parse_mode_line(line, state->linenr, &patch->old_mode);
13b5af22
CC
1000}
1001
80e18412 1002static int gitdiff_newmode(struct gitdiff_data *state,
13b5af22
CC
1003 const char *line,
1004 struct patch *patch)
1005{
44e5471a 1006 return parse_mode_line(line, state->linenr, &patch->new_mode);
13b5af22
CC
1007}
1008
80e18412 1009static int gitdiff_delete(struct gitdiff_data *state,
13b5af22
CC
1010 const char *line,
1011 struct patch *patch)
1012{
1013 patch->is_delete = 1;
1014 free(patch->old_name);
1015 patch->old_name = xstrdup_or_null(patch->def_name);
1016 return gitdiff_oldmode(state, line, patch);
1017}
1018
80e18412 1019static int gitdiff_newfile(struct gitdiff_data *state,
13b5af22
CC
1020 const char *line,
1021 struct patch *patch)
1022{
1023 patch->is_new = 1;
1024 free(patch->new_name);
1025 patch->new_name = xstrdup_or_null(patch->def_name);
1026 return gitdiff_newmode(state, line, patch);
1027}
1028
80e18412 1029static int gitdiff_copysrc(struct gitdiff_data *state,
13b5af22
CC
1030 const char *line,
1031 struct patch *patch)
1032{
1033 patch->is_copy = 1;
1034 free(patch->old_name);
80e18412 1035 patch->old_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
13b5af22
CC
1036 return 0;
1037}
1038
80e18412 1039static int gitdiff_copydst(struct gitdiff_data *state,
13b5af22
CC
1040 const char *line,
1041 struct patch *patch)
1042{
1043 patch->is_copy = 1;
1044 free(patch->new_name);
80e18412 1045 patch->new_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
13b5af22
CC
1046 return 0;
1047}
1048
80e18412 1049static int gitdiff_renamesrc(struct gitdiff_data *state,
13b5af22
CC
1050 const char *line,
1051 struct patch *patch)
1052{
1053 patch->is_rename = 1;
1054 free(patch->old_name);
80e18412 1055 patch->old_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
13b5af22
CC
1056 return 0;
1057}
1058
80e18412 1059static int gitdiff_renamedst(struct gitdiff_data *state,
13b5af22
CC
1060 const char *line,
1061 struct patch *patch)
1062{
1063 patch->is_rename = 1;
1064 free(patch->new_name);
80e18412 1065 patch->new_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
13b5af22
CC
1066 return 0;
1067}
1068
0cff8699 1069static int gitdiff_similarity(struct gitdiff_data *state UNUSED,
13b5af22
CC
1070 const char *line,
1071 struct patch *patch)
1072{
1073 unsigned long val = strtoul(line, NULL, 10);
1074 if (val <= 100)
1075 patch->score = val;
1076 return 0;
1077}
1078
0cff8699 1079static int gitdiff_dissimilarity(struct gitdiff_data *state UNUSED,
13b5af22
CC
1080 const char *line,
1081 struct patch *patch)
1082{
1083 unsigned long val = strtoul(line, NULL, 10);
1084 if (val <= 100)
1085 patch->score = val;
1086 return 0;
1087}
1088
80e18412 1089static int gitdiff_index(struct gitdiff_data *state,
13b5af22
CC
1090 const char *line,
1091 struct patch *patch)
1092{
1093 /*
1094 * index line is N hexadecimal, "..", N hexadecimal,
1095 * and optional space with octal mode.
1096 */
1097 const char *ptr, *eol;
1098 int len;
93eb00f7 1099 const unsigned hexsz = the_hash_algo->hexsz;
13b5af22
CC
1100
1101 ptr = strchr(line, '.');
93eb00f7 1102 if (!ptr || ptr[1] != '.' || hexsz < ptr - line)
13b5af22
CC
1103 return 0;
1104 len = ptr - line;
eccb5a5f 1105 memcpy(patch->old_oid_prefix, line, len);
1106 patch->old_oid_prefix[len] = 0;
13b5af22
CC
1107
1108 line = ptr + 2;
1109 ptr = strchr(line, ' ');
1110 eol = strchrnul(line, '\n');
1111
1112 if (!ptr || eol < ptr)
1113 ptr = eol;
1114 len = ptr - line;
1115
93eb00f7 1116 if (hexsz < len)
13b5af22 1117 return 0;
eccb5a5f 1118 memcpy(patch->new_oid_prefix, line, len);
1119 patch->new_oid_prefix[len] = 0;
13b5af22 1120 if (*ptr == ' ')
44e5471a 1121 return gitdiff_oldmode(state, ptr + 1, patch);
13b5af22
CC
1122 return 0;
1123}
1124
1125/*
1126 * This is normal for a diff that doesn't change anything: we'll fall through
1127 * into the next diff. Tell the parser to break out.
1128 */
0cff8699
JK
1129static int gitdiff_unrecognized(struct gitdiff_data *state UNUSED,
1130 const char *line UNUSED,
1131 struct patch *patch UNUSED)
13b5af22
CC
1132{
1133 return 1;
1134}
1135
1136/*
1137 * Skip p_value leading components from "line"; as we do not accept
1138 * absolute paths, return NULL in that case.
1139 */
d6c88c4f 1140static const char *skip_tree_prefix(int p_value,
13b5af22
CC
1141 const char *line,
1142 int llen)
1143{
1144 int nslash;
1145 int i;
1146
d6c88c4f 1147 if (!p_value)
13b5af22
CC
1148 return (llen && line[0] == '/') ? NULL : line;
1149
d6c88c4f 1150 nslash = p_value;
13b5af22
CC
1151 for (i = 0; i < llen; i++) {
1152 int ch = line[i];
1153 if (ch == '/' && --nslash <= 0)
1154 return (i == 0) ? NULL : &line[i + 1];
1155 }
1156 return NULL;
1157}
1158
1159/*
1160 * This is to extract the same name that appears on "diff --git"
1161 * line. We do not find and return anything if it is a rename
1162 * patch, and it is OK because we will find the name elsewhere.
1163 * We need to reliably find name only when it is mode-change only,
1164 * creation or deletion of an empty file. In any of these cases,
1165 * both sides are the same name under a/ and b/ respectively.
1166 */
85c3713d 1167static char *git_header_name(int p_value,
13b5af22
CC
1168 const char *line,
1169 int llen)
1170{
1171 const char *name;
1172 const char *second = NULL;
1173 size_t len, line_len;
1174
1175 line += strlen("diff --git ");
1176 llen -= strlen("diff --git ");
1177
1178 if (*line == '"') {
1179 const char *cp;
1180 struct strbuf first = STRBUF_INIT;
1181 struct strbuf sp = STRBUF_INIT;
1182
1183 if (unquote_c_style(&first, line, &second))
1184 goto free_and_fail1;
1185
1186 /* strip the a/b prefix including trailing slash */
85c3713d 1187 cp = skip_tree_prefix(p_value, first.buf, first.len);
13b5af22
CC
1188 if (!cp)
1189 goto free_and_fail1;
1190 strbuf_remove(&first, 0, cp - first.buf);
1191
1192 /*
1193 * second points at one past closing dq of name.
1194 * find the second name.
1195 */
1196 while ((second < line + llen) && isspace(*second))
1197 second++;
1198
1199 if (line + llen <= second)
1200 goto free_and_fail1;
1201 if (*second == '"') {
1202 if (unquote_c_style(&sp, second, NULL))
1203 goto free_and_fail1;
85c3713d 1204 cp = skip_tree_prefix(p_value, sp.buf, sp.len);
13b5af22
CC
1205 if (!cp)
1206 goto free_and_fail1;
1207 /* They must match, otherwise ignore */
1208 if (strcmp(cp, first.buf))
1209 goto free_and_fail1;
1210 strbuf_release(&sp);
1211 return strbuf_detach(&first, NULL);
1212 }
1213
1214 /* unquoted second */
85c3713d 1215 cp = skip_tree_prefix(p_value, second, line + llen - second);
13b5af22
CC
1216 if (!cp)
1217 goto free_and_fail1;
1218 if (line + llen - cp != first.len ||
1219 memcmp(first.buf, cp, first.len))
1220 goto free_and_fail1;
1221 return strbuf_detach(&first, NULL);
1222
1223 free_and_fail1:
1224 strbuf_release(&first);
1225 strbuf_release(&sp);
1226 return NULL;
1227 }
1228
1229 /* unquoted first name */
85c3713d 1230 name = skip_tree_prefix(p_value, line, llen);
13b5af22
CC
1231 if (!name)
1232 return NULL;
1233
1234 /*
1235 * since the first name is unquoted, a dq if exists must be
1236 * the beginning of the second name.
1237 */
1238 for (second = name; second < line + llen; second++) {
1239 if (*second == '"') {
1240 struct strbuf sp = STRBUF_INIT;
1241 const char *np;
1242
1243 if (unquote_c_style(&sp, second, NULL))
1244 goto free_and_fail2;
1245
85c3713d 1246 np = skip_tree_prefix(p_value, sp.buf, sp.len);
13b5af22
CC
1247 if (!np)
1248 goto free_and_fail2;
1249
1250 len = sp.buf + sp.len - np;
1251 if (len < second - name &&
1252 !strncmp(np, name, len) &&
1253 isspace(name[len])) {
1254 /* Good */
1255 strbuf_remove(&sp, 0, np - sp.buf);
1256 return strbuf_detach(&sp, NULL);
1257 }
1258
1259 free_and_fail2:
1260 strbuf_release(&sp);
1261 return NULL;
1262 }
1263 }
1264
1265 /*
1266 * Accept a name only if it shows up twice, exactly the same
1267 * form.
1268 */
1269 second = strchr(name, '\n');
1270 if (!second)
1271 return NULL;
1272 line_len = second - name;
1273 for (len = 0 ; ; len++) {
1274 switch (name[len]) {
1275 default:
1276 continue;
1277 case '\n':
1278 return NULL;
1279 case '\t': case ' ':
1280 /*
1281 * Is this the separator between the preimage
1282 * and the postimage pathname? Again, we are
1283 * only interested in the case where there is
1284 * no rename, as this is only to set def_name
1285 * and a rename patch has the names elsewhere
1286 * in an unambiguous form.
1287 */
1288 if (!name[len + 1])
1289 return NULL; /* no postimage name */
85c3713d 1290 second = skip_tree_prefix(p_value, name + len + 1,
13b5af22
CC
1291 line_len - (len + 1));
1292 if (!second)
1293 return NULL;
1294 /*
1295 * Does len bytes starting at "name" and "second"
1296 * (that are separated by one HT or SP we just
1297 * found) exactly match?
1298 */
1299 if (second[len] == '\n' && !strncmp(name, second, len))
1300 return xmemdupz(name, len);
1301 }
1302 }
1303}
1304
570fe991 1305static int check_header_line(int linenr, struct patch *patch)
d70e9c5c
RS
1306{
1307 int extensions = (patch->is_delete == 1) + (patch->is_new == 1) +
1308 (patch->is_rename == 1) + (patch->is_copy == 1);
1309 if (extensions > 1)
1310 return error(_("inconsistent header lines %d and %d"),
570fe991 1311 patch->extension_linenr, linenr);
d70e9c5c 1312 if (extensions && !patch->extension_linenr)
570fe991 1313 patch->extension_linenr = linenr;
d70e9c5c
RS
1314 return 0;
1315}
1316
ef283b36
TG
1317int parse_git_diff_header(struct strbuf *root,
1318 int *linenr,
1319 int p_value,
1320 const char *line,
1321 int len,
1322 unsigned int size,
1323 struct patch *patch)
13b5af22
CC
1324{
1325 unsigned long offset;
80e18412 1326 struct gitdiff_data parse_hdr_state;
13b5af22
CC
1327
1328 /* A git diff has explicit new/delete information, so we don't guess */
1329 patch->is_new = 0;
1330 patch->is_delete = 0;
1331
1332 /*
1333 * Some things may not have the old name in the
1334 * rest of the headers anywhere (pure mode changes,
1335 * or removing or adding empty files), so we get
1336 * the default name from the header.
1337 */
ef283b36
TG
1338 patch->def_name = git_header_name(p_value, line, len);
1339 if (patch->def_name && root->len) {
1340 char *s = xstrfmt("%s%s", root->buf, patch->def_name);
13b5af22
CC
1341 free(patch->def_name);
1342 patch->def_name = s;
1343 }
1344
1345 line += len;
1346 size -= len;
ef283b36
TG
1347 (*linenr)++;
1348 parse_hdr_state.root = root;
1349 parse_hdr_state.linenr = *linenr;
1350 parse_hdr_state.p_value = p_value;
80e18412 1351
ef283b36 1352 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, (*linenr)++) {
13b5af22
CC
1353 static const struct opentry {
1354 const char *str;
80e18412 1355 int (*fn)(struct gitdiff_data *, const char *, struct patch *);
13b5af22
CC
1356 } optable[] = {
1357 { "@@ -", gitdiff_hdrend },
1358 { "--- ", gitdiff_oldname },
1359 { "+++ ", gitdiff_newname },
1360 { "old mode ", gitdiff_oldmode },
1361 { "new mode ", gitdiff_newmode },
1362 { "deleted file mode ", gitdiff_delete },
1363 { "new file mode ", gitdiff_newfile },
1364 { "copy from ", gitdiff_copysrc },
1365 { "copy to ", gitdiff_copydst },
1366 { "rename old ", gitdiff_renamesrc },
1367 { "rename new ", gitdiff_renamedst },
1368 { "rename from ", gitdiff_renamesrc },
1369 { "rename to ", gitdiff_renamedst },
1370 { "similarity index ", gitdiff_similarity },
1371 { "dissimilarity index ", gitdiff_dissimilarity },
1372 { "index ", gitdiff_index },
1373 { "", gitdiff_unrecognized },
1374 };
1375 int i;
1376
1377 len = linelen(line, size);
1378 if (!len || line[len-1] != '\n')
1379 break;
1380 for (i = 0; i < ARRAY_SIZE(optable); i++) {
1381 const struct opentry *p = optable + i;
1382 int oplen = strlen(p->str);
1383 int res;
1384 if (len < oplen || memcmp(p->str, line, oplen))
1385 continue;
80e18412 1386 res = p->fn(&parse_hdr_state, line + oplen, patch);
13b5af22
CC
1387 if (res < 0)
1388 return -1;
ef283b36 1389 if (check_header_line(*linenr, patch))
d70e9c5c 1390 return -1;
13b5af22 1391 if (res > 0)
2b6a9b13 1392 goto done;
13b5af22
CC
1393 break;
1394 }
1395 }
1396
2b6a9b13
TG
1397done:
1398 if (!patch->old_name && !patch->new_name) {
1399 if (!patch->def_name) {
1400 error(Q_("git diff header lacks filename information when removing "
1401 "%d leading pathname component (line %d)",
1402 "git diff header lacks filename information when removing "
1403 "%d leading pathname components (line %d)",
1404 parse_hdr_state.p_value),
1405 parse_hdr_state.p_value, *linenr);
1406 return -128;
1407 }
1408 patch->old_name = xstrdup(patch->def_name);
1409 patch->new_name = xstrdup(patch->def_name);
1410 }
1411 if ((!patch->new_name && !patch->is_delete) ||
1412 (!patch->old_name && !patch->is_new)) {
1413 error(_("git diff header lacks filename information "
1414 "(line %d)"), *linenr);
1415 return -128;
1416 }
1417 patch->is_toplevel_relative = 1;
13b5af22
CC
1418 return offset;
1419}
1420
1421static int parse_num(const char *line, unsigned long *p)
1422{
1423 char *ptr;
1424
1425 if (!isdigit(*line))
1426 return 0;
1427 *p = strtoul(line, &ptr, 10);
1428 return ptr - line;
1429}
1430
1431static int parse_range(const char *line, int len, int offset, const char *expect,
1432 unsigned long *p1, unsigned long *p2)
1433{
1434 int digits, ex;
1435
1436 if (offset < 0 || offset >= len)
1437 return -1;
1438 line += offset;
1439 len -= offset;
1440
1441 digits = parse_num(line, p1);
1442 if (!digits)
1443 return -1;
1444
1445 offset += digits;
1446 line += digits;
1447 len -= digits;
1448
1449 *p2 = 1;
1450 if (*line == ',') {
1451 digits = parse_num(line+1, p2);
1452 if (!digits)
1453 return -1;
1454
1455 offset += digits+1;
1456 line += digits+1;
1457 len -= digits+1;
1458 }
1459
1460 ex = strlen(expect);
1461 if (ex > len)
1462 return -1;
1463 if (memcmp(line, expect, ex))
1464 return -1;
1465
1466 return offset + ex;
1467}
1468
1469static void recount_diff(const char *line, int size, struct fragment *fragment)
1470{
1471 int oldlines = 0, newlines = 0, ret = 0;
1472
1473 if (size < 1) {
1474 warning("recount: ignore empty hunk");
1475 return;
1476 }
1477
1478 for (;;) {
1479 int len = linelen(line, size);
1480 size -= len;
1481 line += len;
1482
1483 if (size < 1)
1484 break;
1485
1486 switch (*line) {
1487 case ' ': case '\n':
1488 newlines++;
1489 /* fall through */
1490 case '-':
1491 oldlines++;
1492 continue;
1493 case '+':
1494 newlines++;
1495 continue;
1496 case '\\':
1497 continue;
1498 case '@':
1499 ret = size < 3 || !starts_with(line, "@@ ");
1500 break;
1501 case 'd':
1502 ret = size < 5 || !starts_with(line, "diff ");
1503 break;
1504 default:
1505 ret = -1;
1506 break;
1507 }
1508 if (ret) {
1509 warning(_("recount: unexpected line: %.*s"),
1510 (int)linelen(line, size), line);
1511 return;
1512 }
1513 break;
1514 }
1515 fragment->oldlines = oldlines;
1516 fragment->newlines = newlines;
1517}
1518
1519/*
1520 * Parse a unified diff fragment header of the
1521 * form "@@ -a,b +c,d @@"
1522 */
1523static int parse_fragment_header(const char *line, int len, struct fragment *fragment)
1524{
1525 int offset;
1526
1527 if (!len || line[len-1] != '\n')
1528 return -1;
1529
1530 /* Figure out the number of lines in a fragment */
1531 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1532 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1533
1534 return offset;
1535}
1536
1537/*
1538 * Find file diff header
1539 *
1540 * Returns:
1541 * -1 if no header was found
1542 * -128 in case of error
1543 * the size of the header in bytes (called "offset") otherwise
1544 */
1545static int find_header(struct apply_state *state,
1546 const char *line,
1547 unsigned long size,
1548 int *hdrsize,
1549 struct patch *patch)
1550{
1551 unsigned long offset, len;
1552
1553 patch->is_toplevel_relative = 0;
1554 patch->is_rename = patch->is_copy = 0;
1555 patch->is_new = patch->is_delete = -1;
1556 patch->old_mode = patch->new_mode = 0;
1557 patch->old_name = patch->new_name = NULL;
1558 for (offset = 0; size > 0; offset += len, size -= len, line += len, state->linenr++) {
1559 unsigned long nextlen;
1560
1561 len = linelen(line, size);
1562 if (!len)
1563 break;
1564
1565 /* Testing this early allows us to take a few shortcuts.. */
1566 if (len < 6)
1567 continue;
1568
1569 /*
1570 * Make sure we don't find any unconnected patch fragments.
1571 * That's a sign that we didn't find a header, and that a
1572 * patch has become corrupted/broken up.
1573 */
1574 if (!memcmp("@@ -", line, 4)) {
1575 struct fragment dummy;
1576 if (parse_fragment_header(line, len, &dummy) < 0)
1577 continue;
1578 error(_("patch fragment without header at line %d: %.*s"),
1579 state->linenr, (int)len-1, line);
1580 return -128;
1581 }
1582
1583 if (size < len + 6)
1584 break;
1585
1586 /*
1587 * Git patch? It might not have a real patch, just a rename
1588 * or mode change, so we handle that specially
1589 */
1590 if (!memcmp("diff --git ", line, 11)) {
ef283b36
TG
1591 int git_hdr_len = parse_git_diff_header(&state->root, &state->linenr,
1592 state->p_value, line, len,
1593 size, patch);
13b5af22
CC
1594 if (git_hdr_len < 0)
1595 return -128;
1596 if (git_hdr_len <= len)
1597 continue;
13b5af22
CC
1598 *hdrsize = git_hdr_len;
1599 return offset;
1600 }
1601
1602 /* --- followed by +++ ? */
1603 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1604 continue;
1605
1606 /*
1607 * We only accept unified patches, so we want it to
1608 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1609 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1610 */
1611 nextlen = linelen(line + len, size - len);
1612 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1613 continue;
1614
1615 /* Ok, we'll consider it a patch */
1616 if (parse_traditional_patch(state, line, line+len, patch))
1617 return -128;
1618 *hdrsize = len + nextlen;
1619 state->linenr += 2;
1620 return offset;
1621 }
1622 return -1;
1623}
1624
1625static void record_ws_error(struct apply_state *state,
1626 unsigned result,
1627 const char *line,
1628 int len,
1629 int linenr)
1630{
1631 char *err;
1632
1633 if (!result)
1634 return;
1635
1636 state->whitespace_error++;
1637 if (state->squelch_whitespace_errors &&
1638 state->squelch_whitespace_errors < state->whitespace_error)
1639 return;
1640
1641 err = whitespace_error_string(result);
a46160d2
CC
1642 if (state->apply_verbosity > verbosity_silent)
1643 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1644 state->patch_input_file, linenr, err, len, line);
13b5af22
CC
1645 free(err);
1646}
1647
1648static void check_whitespace(struct apply_state *state,
1649 const char *line,
1650 int len,
1651 unsigned ws_rule)
1652{
1653 unsigned result = ws_check(line + 1, len - 1, ws_rule);
1654
1655 record_ws_error(state, result, line + 1, len - 2, state->linenr);
1656}
1657
c24f3aba
TB
1658/*
1659 * Check if the patch has context lines with CRLF or
1660 * the patch wants to remove lines with CRLF.
1661 */
1662static void check_old_for_crlf(struct patch *patch, const char *line, int len)
1663{
1664 if (len >= 2 && line[len-1] == '\n' && line[len-2] == '\r') {
1665 patch->ws_rule |= WS_CR_AT_EOL;
1666 patch->crlf_in_old = 1;
1667 }
1668}
1669
1670
13b5af22
CC
1671/*
1672 * Parse a unified diff. Note that this really needs to parse each
1673 * fragment separately, since the only way to know the difference
1674 * between a "---" that is part of a patch, and a "---" that starts
1675 * the next patch is to look at the line counts..
1676 */
1677static int parse_fragment(struct apply_state *state,
1678 const char *line,
1679 unsigned long size,
1680 struct patch *patch,
1681 struct fragment *fragment)
1682{
1683 int added, deleted;
1684 int len = linelen(line, size), offset;
1685 unsigned long oldlines, newlines;
1686 unsigned long leading, trailing;
1687
1688 offset = parse_fragment_header(line, len, fragment);
1689 if (offset < 0)
1690 return -1;
1691 if (offset > 0 && patch->recount)
1692 recount_diff(line + offset, size - offset, fragment);
1693 oldlines = fragment->oldlines;
1694 newlines = fragment->newlines;
1695 leading = 0;
1696 trailing = 0;
1697
1698 /* Parse the thing.. */
1699 line += len;
1700 size -= len;
1701 state->linenr++;
1702 added = deleted = 0;
1703 for (offset = len;
1704 0 < size;
1705 offset += len, size -= len, line += len, state->linenr++) {
1706 if (!oldlines && !newlines)
1707 break;
1708 len = linelen(line, size);
1709 if (!len || line[len-1] != '\n')
1710 return -1;
1711 switch (*line) {
1712 default:
1713 return -1;
1714 case '\n': /* newer GNU diff, an empty context line */
1715 case ' ':
1716 oldlines--;
1717 newlines--;
1718 if (!deleted && !added)
1719 leading++;
1720 trailing++;
c24f3aba 1721 check_old_for_crlf(patch, line, len);
13b5af22
CC
1722 if (!state->apply_in_reverse &&
1723 state->ws_error_action == correct_ws_error)
1724 check_whitespace(state, line, len, patch->ws_rule);
1725 break;
1726 case '-':
c24f3aba
TB
1727 if (!state->apply_in_reverse)
1728 check_old_for_crlf(patch, line, len);
13b5af22
CC
1729 if (state->apply_in_reverse &&
1730 state->ws_error_action != nowarn_ws_error)
1731 check_whitespace(state, line, len, patch->ws_rule);
1732 deleted++;
1733 oldlines--;
1734 trailing = 0;
1735 break;
1736 case '+':
c24f3aba
TB
1737 if (state->apply_in_reverse)
1738 check_old_for_crlf(patch, line, len);
13b5af22
CC
1739 if (!state->apply_in_reverse &&
1740 state->ws_error_action != nowarn_ws_error)
1741 check_whitespace(state, line, len, patch->ws_rule);
1742 added++;
1743 newlines--;
1744 trailing = 0;
1745 break;
1746
1747 /*
1748 * We allow "\ No newline at end of file". Depending
1749 * on locale settings when the patch was produced we
1750 * don't know what this line looks like. The only
1751 * thing we do know is that it begins with "\ ".
1752 * Checking for 12 is just for sanity check -- any
1753 * l10n of "\ No newline..." is at least that long.
1754 */
1755 case '\\':
1756 if (len < 12 || memcmp(line, "\\ ", 2))
1757 return -1;
1758 break;
1759 }
1760 }
1761 if (oldlines || newlines)
1762 return -1;
22cb3835 1763 if (!patch->recount && !deleted && !added)
13b5af22
CC
1764 return -1;
1765
1766 fragment->leading = leading;
1767 fragment->trailing = trailing;
1768
1769 /*
1770 * If a fragment ends with an incomplete line, we failed to include
1771 * it in the above loop because we hit oldlines == newlines == 0
1772 * before seeing it.
1773 */
1774 if (12 < size && !memcmp(line, "\\ ", 2))
1775 offset += linelen(line, size);
1776
1777 patch->lines_added += added;
1778 patch->lines_deleted += deleted;
1779
1780 if (0 < patch->is_new && oldlines)
1781 return error(_("new file depends on old contents"));
1782 if (0 < patch->is_delete && newlines)
1783 return error(_("deleted file still has contents"));
1784 return offset;
1785}
1786
1787/*
1788 * We have seen "diff --git a/... b/..." header (or a traditional patch
1789 * header). Read hunks that belong to this patch into fragments and hang
1790 * them to the given patch structure.
1791 *
1792 * The (fragment->patch, fragment->size) pair points into the memory given
1793 * by the caller, not a copy, when we return.
1794 *
1795 * Returns:
1796 * -1 in case of error,
1797 * the number of bytes in the patch otherwise.
1798 */
1799static int parse_single_patch(struct apply_state *state,
1800 const char *line,
1801 unsigned long size,
1802 struct patch *patch)
1803{
1804 unsigned long offset = 0;
1805 unsigned long oldlines = 0, newlines = 0, context = 0;
1806 struct fragment **fragp = &patch->fragments;
1807
1808 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1809 struct fragment *fragment;
1810 int len;
1811
ca56dadb 1812 CALLOC_ARRAY(fragment, 1);
13b5af22
CC
1813 fragment->linenr = state->linenr;
1814 len = parse_fragment(state, line, size, patch, fragment);
1815 if (len <= 0) {
1816 free(fragment);
1817 return error(_("corrupt patch at line %d"), state->linenr);
1818 }
1819 fragment->patch = line;
1820 fragment->size = len;
1821 oldlines += fragment->oldlines;
1822 newlines += fragment->newlines;
1823 context += fragment->leading + fragment->trailing;
1824
1825 *fragp = fragment;
1826 fragp = &fragment->next;
1827
1828 offset += len;
1829 line += len;
1830 size -= len;
1831 }
1832
1833 /*
1834 * If something was removed (i.e. we have old-lines) it cannot
1835 * be creation, and if something was added it cannot be
1836 * deletion. However, the reverse is not true; --unified=0
1837 * patches that only add are not necessarily creation even
1838 * though they do not have any old lines, and ones that only
1839 * delete are not necessarily deletion.
1840 *
1841 * Unfortunately, a real creation/deletion patch do _not_ have
1842 * any context line by definition, so we cannot safely tell it
1843 * apart with --unified=0 insanity. At least if the patch has
1844 * more than one hunk it is not creation or deletion.
1845 */
1846 if (patch->is_new < 0 &&
1847 (oldlines || (patch->fragments && patch->fragments->next)))
1848 patch->is_new = 0;
1849 if (patch->is_delete < 0 &&
1850 (newlines || (patch->fragments && patch->fragments->next)))
1851 patch->is_delete = 0;
1852
1853 if (0 < patch->is_new && oldlines)
1854 return error(_("new file %s depends on old contents"), patch->new_name);
1855 if (0 < patch->is_delete && newlines)
1856 return error(_("deleted file %s still has contents"), patch->old_name);
a46160d2 1857 if (!patch->is_delete && !newlines && context && state->apply_verbosity > verbosity_silent)
13b5af22
CC
1858 fprintf_ln(stderr,
1859 _("** warning: "
1860 "file %s becomes empty but is not deleted"),
1861 patch->new_name);
1862
1863 return offset;
1864}
1865
1866static inline int metadata_changes(struct patch *patch)
1867{
1868 return patch->is_rename > 0 ||
1869 patch->is_copy > 0 ||
1870 patch->is_new > 0 ||
1871 patch->is_delete ||
1872 (patch->old_mode && patch->new_mode &&
1873 patch->old_mode != patch->new_mode);
1874}
1875
1876static char *inflate_it(const void *data, unsigned long size,
1877 unsigned long inflated_size)
1878{
1879 git_zstream stream;
1880 void *out;
1881 int st;
1882
1883 memset(&stream, 0, sizeof(stream));
1884
1885 stream.next_in = (unsigned char *)data;
1886 stream.avail_in = size;
1887 stream.next_out = out = xmalloc(inflated_size);
1888 stream.avail_out = inflated_size;
1889 git_inflate_init(&stream);
1890 st = git_inflate(&stream, Z_FINISH);
1891 git_inflate_end(&stream);
1892 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1893 free(out);
1894 return NULL;
1895 }
1896 return out;
1897}
1898
1899/*
1900 * Read a binary hunk and return a new fragment; fragment->patch
1901 * points at an allocated memory that the caller must free, so
1902 * it is marked as "->free_patch = 1".
1903 */
1904static struct fragment *parse_binary_hunk(struct apply_state *state,
1905 char **buf_p,
1906 unsigned long *sz_p,
1907 int *status_p,
1908 int *used_p)
1909{
1910 /*
1911 * Expect a line that begins with binary patch method ("literal"
1912 * or "delta"), followed by the length of data before deflating.
1913 * a sequence of 'length-byte' followed by base-85 encoded data
1914 * should follow, terminated by a newline.
1915 *
1916 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1917 * and we would limit the patch line to 66 characters,
1918 * so one line can fit up to 13 groups that would decode
1919 * to 52 bytes max. The length byte 'A'-'Z' corresponds
1920 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1921 */
1922 int llen, used;
1923 unsigned long size = *sz_p;
1924 char *buffer = *buf_p;
1925 int patch_method;
1926 unsigned long origlen;
1927 char *data = NULL;
1928 int hunk_size = 0;
1929 struct fragment *frag;
1930
1931 llen = linelen(buffer, size);
1932 used = llen;
1933
1934 *status_p = 0;
1935
1936 if (starts_with(buffer, "delta ")) {
1937 patch_method = BINARY_DELTA_DEFLATED;
1938 origlen = strtoul(buffer + 6, NULL, 10);
1939 }
1940 else if (starts_with(buffer, "literal ")) {
1941 patch_method = BINARY_LITERAL_DEFLATED;
1942 origlen = strtoul(buffer + 8, NULL, 10);
1943 }
1944 else
1945 return NULL;
1946
1947 state->linenr++;
1948 buffer += llen;
46d723ce 1949 size -= llen;
13b5af22
CC
1950 while (1) {
1951 int byte_length, max_byte_length, newsize;
1952 llen = linelen(buffer, size);
1953 used += llen;
1954 state->linenr++;
1955 if (llen == 1) {
1956 /* consume the blank line */
1957 buffer++;
1958 size--;
1959 break;
1960 }
1961 /*
1962 * Minimum line is "A00000\n" which is 7-byte long,
1963 * and the line length must be multiple of 5 plus 2.
1964 */
1965 if ((llen < 7) || (llen-2) % 5)
1966 goto corrupt;
1967 max_byte_length = (llen - 2) / 5 * 4;
1968 byte_length = *buffer;
1969 if ('A' <= byte_length && byte_length <= 'Z')
1970 byte_length = byte_length - 'A' + 1;
1971 else if ('a' <= byte_length && byte_length <= 'z')
1972 byte_length = byte_length - 'a' + 27;
1973 else
1974 goto corrupt;
1975 /* if the input length was not multiple of 4, we would
1976 * have filler at the end but the filler should never
1977 * exceed 3 bytes
1978 */
1979 if (max_byte_length < byte_length ||
1980 byte_length <= max_byte_length - 4)
1981 goto corrupt;
1982 newsize = hunk_size + byte_length;
1983 data = xrealloc(data, newsize);
1984 if (decode_85(data + hunk_size, buffer + 1, byte_length))
1985 goto corrupt;
1986 hunk_size = newsize;
1987 buffer += llen;
1988 size -= llen;
1989 }
1990
ca56dadb 1991 CALLOC_ARRAY(frag, 1);
13b5af22
CC
1992 frag->patch = inflate_it(data, hunk_size, origlen);
1993 frag->free_patch = 1;
1994 if (!frag->patch)
1995 goto corrupt;
1996 free(data);
1997 frag->size = origlen;
1998 *buf_p = buffer;
1999 *sz_p = size;
2000 *used_p = used;
2001 frag->binary_patch_method = patch_method;
2002 return frag;
2003
2004 corrupt:
2005 free(data);
2006 *status_p = -1;
2007 error(_("corrupt binary patch at line %d: %.*s"),
2008 state->linenr-1, llen-1, buffer);
2009 return NULL;
2010}
2011
2012/*
2013 * Returns:
2014 * -1 in case of error,
2015 * the length of the parsed binary patch otherwise
2016 */
2017static int parse_binary(struct apply_state *state,
2018 char *buffer,
2019 unsigned long size,
2020 struct patch *patch)
2021{
2022 /*
2023 * We have read "GIT binary patch\n"; what follows is a line
2024 * that says the patch method (currently, either "literal" or
2025 * "delta") and the length of data before deflating; a
2026 * sequence of 'length-byte' followed by base-85 encoded data
2027 * follows.
2028 *
2029 * When a binary patch is reversible, there is another binary
2030 * hunk in the same format, starting with patch method (either
2031 * "literal" or "delta") with the length of data, and a sequence
2032 * of length-byte + base-85 encoded data, terminated with another
2033 * empty line. This data, when applied to the postimage, produces
2034 * the preimage.
2035 */
2036 struct fragment *forward;
2037 struct fragment *reverse;
2038 int status;
2039 int used, used_1;
2040
2041 forward = parse_binary_hunk(state, &buffer, &size, &status, &used);
2042 if (!forward && !status)
2043 /* there has to be one hunk (forward hunk) */
2044 return error(_("unrecognized binary patch at line %d"), state->linenr-1);
2045 if (status)
2046 /* otherwise we already gave an error message */
2047 return status;
2048
2049 reverse = parse_binary_hunk(state, &buffer, &size, &status, &used_1);
2050 if (reverse)
2051 used += used_1;
2052 else if (status) {
2053 /*
2054 * Not having reverse hunk is not an error, but having
2055 * a corrupt reverse hunk is.
2056 */
2057 free((void*) forward->patch);
2058 free(forward);
2059 return status;
2060 }
2061 forward->next = reverse;
2062 patch->fragments = forward;
2063 patch->is_binary = 1;
2064 return used;
2065}
2066
2067static void prefix_one(struct apply_state *state, char **name)
2068{
2069 char *old_name = *name;
2070 if (!old_name)
2071 return;
e4da43b1 2072 *name = prefix_filename(state->prefix, *name);
13b5af22
CC
2073 free(old_name);
2074}
2075
2076static void prefix_patch(struct apply_state *state, struct patch *p)
2077{
2078 if (!state->prefix || p->is_toplevel_relative)
2079 return;
2080 prefix_one(state, &p->new_name);
2081 prefix_one(state, &p->old_name);
2082}
2083
2084/*
2085 * include/exclude
2086 */
2087
2088static void add_name_limit(struct apply_state *state,
2089 const char *name,
2090 int exclude)
2091{
2092 struct string_list_item *it;
2093
2094 it = string_list_append(&state->limit_by_name, name);
2095 it->util = exclude ? NULL : (void *) 1;
2096}
2097
2098static int use_patch(struct apply_state *state, struct patch *p)
2099{
2100 const char *pathname = p->new_name ? p->new_name : p->old_name;
2101 int i;
2102
2103 /* Paths outside are not touched regardless of "--include" */
881529c8
RS
2104 if (state->prefix && *state->prefix) {
2105 const char *rest;
2106 if (!skip_prefix(pathname, state->prefix, &rest) || !*rest)
13b5af22
CC
2107 return 0;
2108 }
2109
2110 /* See if it matches any of exclude/include rule */
2111 for (i = 0; i < state->limit_by_name.nr; i++) {
2112 struct string_list_item *it = &state->limit_by_name.items[i];
55d34269 2113 if (!wildmatch(it->string, pathname, 0))
13b5af22
CC
2114 return (it->util != NULL);
2115 }
2116
2117 /*
2118 * If we had any include, a path that does not match any rule is
2119 * not used. Otherwise, we saw bunch of exclude rules (or none)
2120 * and such a path is used.
2121 */
2122 return !state->has_include;
2123}
2124
2125/*
2126 * Read the patch text in "buffer" that extends for "size" bytes; stop
2127 * reading after seeing a single patch (i.e. changes to a single file).
2128 * Create fragments (i.e. patch hunks) and hang them to the given patch.
2129 *
2130 * Returns:
2131 * -1 if no header was found or parse_binary() failed,
2132 * -128 on another error,
2133 * the number of bytes consumed otherwise,
2134 * so that the caller can call us again for the next patch.
2135 */
2136static int parse_chunk(struct apply_state *state, char *buffer, unsigned long size, struct patch *patch)
2137{
2138 int hdrsize, patchsize;
2139 int offset = find_header(state, buffer, size, &hdrsize, patch);
2140
2141 if (offset < 0)
2142 return offset;
2143
2144 prefix_patch(state, patch);
2145
2146 if (!use_patch(state, patch))
2147 patch->ws_rule = 0;
26d024ec
NTND
2148 else if (patch->new_name)
2149 patch->ws_rule = whitespace_rule(state->repo->index,
2150 patch->new_name);
13b5af22 2151 else
26d024ec
NTND
2152 patch->ws_rule = whitespace_rule(state->repo->index,
2153 patch->old_name);
13b5af22
CC
2154
2155 patchsize = parse_single_patch(state,
2156 buffer + offset + hdrsize,
2157 size - offset - hdrsize,
2158 patch);
2159
2160 if (patchsize < 0)
2161 return -128;
2162
2163 if (!patchsize) {
2164 static const char git_binary[] = "GIT binary patch\n";
2165 int hd = hdrsize + offset;
2166 unsigned long llen = linelen(buffer + hd, size - hd);
2167
2168 if (llen == sizeof(git_binary) - 1 &&
2169 !memcmp(git_binary, buffer + hd, llen)) {
2170 int used;
2171 state->linenr++;
2172 used = parse_binary(state, buffer + hd + llen,
2173 size - hd - llen, patch);
2174 if (used < 0)
2175 return -1;
2176 if (used)
2177 patchsize = used + llen;
2178 else
2179 patchsize = 0;
2180 }
2181 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
2182 static const char *binhdr[] = {
2183 "Binary files ",
2184 "Files ",
2185 NULL,
2186 };
2187 int i;
2188 for (i = 0; binhdr[i]; i++) {
2189 int len = strlen(binhdr[i]);
2190 if (len < size - hd &&
2191 !memcmp(binhdr[i], buffer + hd, len)) {
2192 state->linenr++;
2193 patch->is_binary = 1;
2194 patchsize = llen;
2195 break;
2196 }
2197 }
2198 }
2199
2200 /* Empty patch cannot be applied if it is a text patch
2201 * without metadata change. A binary patch appears
2202 * empty to us here.
2203 */
2204 if ((state->apply || state->check) &&
2205 (!patch->is_binary && !metadata_changes(patch))) {
2206 error(_("patch with only garbage at line %d"), state->linenr);
2207 return -128;
2208 }
2209 }
2210
2211 return offset + hdrsize + patchsize;
2212}
2213
13b5af22
CC
2214static void reverse_patches(struct patch *p)
2215{
2216 for (; p; p = p->next) {
2217 struct fragment *frag = p->fragments;
2218
db101991
RS
2219 SWAP(p->new_name, p->old_name);
2220 SWAP(p->new_mode, p->old_mode);
2221 SWAP(p->is_new, p->is_delete);
2222 SWAP(p->lines_added, p->lines_deleted);
eccb5a5f 2223 SWAP(p->old_oid_prefix, p->new_oid_prefix);
13b5af22
CC
2224
2225 for (; frag; frag = frag->next) {
db101991
RS
2226 SWAP(frag->newpos, frag->oldpos);
2227 SWAP(frag->newlines, frag->oldlines);
13b5af22
CC
2228 }
2229 }
2230}
2231
2232static const char pluses[] =
2233"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2234static const char minuses[]=
2235"----------------------------------------------------------------------";
2236
2237static void show_stats(struct apply_state *state, struct patch *patch)
2238{
2239 struct strbuf qname = STRBUF_INIT;
2240 char *cp = patch->new_name ? patch->new_name : patch->old_name;
2241 int max, add, del;
2242
2243 quote_c_style(cp, &qname, NULL, 0);
2244
2245 /*
2246 * "scale" the filename
2247 */
2248 max = state->max_len;
2249 if (max > 50)
2250 max = 50;
2251
2252 if (qname.len > max) {
2253 cp = strchr(qname.buf + qname.len + 3 - max, '/');
2254 if (!cp)
2255 cp = qname.buf + qname.len + 3 - max;
2256 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
2257 }
2258
2259 if (patch->is_binary) {
2260 printf(" %-*s | Bin\n", max, qname.buf);
2261 strbuf_release(&qname);
2262 return;
2263 }
2264
2265 printf(" %-*s |", max, qname.buf);
2266 strbuf_release(&qname);
2267
2268 /*
2269 * scale the add/delete
2270 */
2271 max = max + state->max_change > 70 ? 70 - max : state->max_change;
2272 add = patch->lines_added;
2273 del = patch->lines_deleted;
2274
2275 if (state->max_change > 0) {
2276 int total = ((add + del) * max + state->max_change / 2) / state->max_change;
2277 add = (add * max + state->max_change / 2) / state->max_change;
2278 del = total - add;
2279 }
2280 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
2281 add, pluses, del, minuses);
2282}
2283
c24f3aba
TB
2284static int read_old_data(struct stat *st, struct patch *patch,
2285 const char *path, struct strbuf *buf)
13b5af22 2286{
8462ff43
TB
2287 int conv_flags = patch->crlf_in_old ?
2288 CONV_EOL_KEEP_CRLF : CONV_EOL_RENORMALIZE;
13b5af22
CC
2289 switch (st->st_mode & S_IFMT) {
2290 case S_IFLNK:
2291 if (strbuf_readlink(buf, path, st->st_size) < 0)
2292 return error(_("unable to read symlink %s"), path);
2293 return 0;
2294 case S_IFREG:
2295 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
2296 return error(_("unable to open or read %s"), path);
c24f3aba
TB
2297 /*
2298 * "git apply" without "--index/--cached" should never look
2299 * at the index; the target file may not have been added to
2300 * the index yet, and we may not even be in any Git repository.
2301 * Pass NULL to convert_to_git() to stress this; the function
2302 * should never look at the index when explicit crlf option
2303 * is given.
2304 */
8462ff43 2305 convert_to_git(NULL, path, buf->buf, buf->len, buf, conv_flags);
13b5af22
CC
2306 return 0;
2307 default:
2308 return -1;
2309 }
2310}
2311
2312/*
2313 * Update the preimage, and the common lines in postimage,
2314 * from buffer buf of length len. If postlen is 0 the postimage
2315 * is updated in place, otherwise it's updated on a new buffer
2316 * of length postlen
2317 */
2318
2319static void update_pre_post_images(struct image *preimage,
2320 struct image *postimage,
2321 char *buf,
2322 size_t len, size_t postlen)
2323{
2324 int i, ctx, reduced;
f1ae97d3 2325 char *new_buf, *old_buf, *fixed;
13b5af22
CC
2326 struct image fixed_preimage;
2327
2328 /*
2329 * Update the preimage with whitespace fixes. Note that we
2330 * are not losing preimage->buf -- apply_one_fragment() will
2331 * free "oldlines".
2332 */
2333 prepare_image(&fixed_preimage, buf, len, 1);
2334 assert(postlen
2335 ? fixed_preimage.nr == preimage->nr
2336 : fixed_preimage.nr <= preimage->nr);
2337 for (i = 0; i < fixed_preimage.nr; i++)
2338 fixed_preimage.line[i].flag = preimage->line[i].flag;
2339 free(preimage->line_allocated);
2340 *preimage = fixed_preimage;
2341
2342 /*
2343 * Adjust the common context lines in postimage. This can be
2344 * done in-place when we are shrinking it with whitespace
2345 * fixing, but needs a new buffer when ignoring whitespace or
2346 * expanding leading tabs to spaces.
2347 *
2348 * We trust the caller to tell us if the update can be done
2349 * in place (postlen==0) or not.
2350 */
f1ae97d3 2351 old_buf = postimage->buf;
13b5af22 2352 if (postlen)
f1ae97d3 2353 new_buf = postimage->buf = xmalloc(postlen);
13b5af22 2354 else
f1ae97d3 2355 new_buf = old_buf;
13b5af22
CC
2356 fixed = preimage->buf;
2357
2358 for (i = reduced = ctx = 0; i < postimage->nr; i++) {
2359 size_t l_len = postimage->line[i].len;
2360 if (!(postimage->line[i].flag & LINE_COMMON)) {
2361 /* an added line -- no counterparts in preimage */
f1ae97d3
BW
2362 memmove(new_buf, old_buf, l_len);
2363 old_buf += l_len;
2364 new_buf += l_len;
13b5af22
CC
2365 continue;
2366 }
2367
2368 /* a common context -- skip it in the original postimage */
f1ae97d3 2369 old_buf += l_len;
13b5af22
CC
2370
2371 /* and find the corresponding one in the fixed preimage */
2372 while (ctx < preimage->nr &&
2373 !(preimage->line[ctx].flag & LINE_COMMON)) {
2374 fixed += preimage->line[ctx].len;
2375 ctx++;
2376 }
2377
2378 /*
2379 * preimage is expected to run out, if the caller
2380 * fixed addition of trailing blank lines.
2381 */
2382 if (preimage->nr <= ctx) {
2383 reduced++;
2384 continue;
2385 }
2386
2387 /* and copy it in, while fixing the line length */
2388 l_len = preimage->line[ctx].len;
f1ae97d3
BW
2389 memcpy(new_buf, fixed, l_len);
2390 new_buf += l_len;
13b5af22
CC
2391 fixed += l_len;
2392 postimage->line[i].len = l_len;
2393 ctx++;
2394 }
2395
2396 if (postlen
f1ae97d3
BW
2397 ? postlen < new_buf - postimage->buf
2398 : postimage->len < new_buf - postimage->buf)
033abf97 2399 BUG("caller miscounted postlen: asked %d, orig = %d, used = %d",
f1ae97d3 2400 (int)postlen, (int) postimage->len, (int)(new_buf - postimage->buf));
13b5af22
CC
2401
2402 /* Fix the length of the whole thing */
f1ae97d3 2403 postimage->len = new_buf - postimage->buf;
13b5af22
CC
2404 postimage->nr -= reduced;
2405}
2406
2407static int line_by_line_fuzzy_match(struct image *img,
2408 struct image *preimage,
2409 struct image *postimage,
6cbc7cfd
BW
2410 unsigned long current,
2411 int current_lno,
13b5af22
CC
2412 int preimage_limit)
2413{
2414 int i;
2415 size_t imgoff = 0;
2416 size_t preoff = 0;
2417 size_t postlen = postimage->len;
2418 size_t extra_chars;
2419 char *buf;
2420 char *preimage_eof;
2421 char *preimage_end;
2422 struct strbuf fixed;
2423 char *fixed_buf;
2424 size_t fixed_len;
2425
2426 for (i = 0; i < preimage_limit; i++) {
2427 size_t prelen = preimage->line[i].len;
6cbc7cfd 2428 size_t imglen = img->line[current_lno+i].len;
13b5af22 2429
6cbc7cfd 2430 if (!fuzzy_matchlines(img->buf + current + imgoff, imglen,
13b5af22
CC
2431 preimage->buf + preoff, prelen))
2432 return 0;
2433 if (preimage->line[i].flag & LINE_COMMON)
2434 postlen += imglen - prelen;
2435 imgoff += imglen;
2436 preoff += prelen;
2437 }
2438
2439 /*
2440 * Ok, the preimage matches with whitespace fuzz.
2441 *
2442 * imgoff now holds the true length of the target that
2443 * matches the preimage before the end of the file.
2444 *
2445 * Count the number of characters in the preimage that fall
2446 * beyond the end of the file and make sure that all of them
2447 * are whitespace characters. (This can only happen if
2448 * we are removing blank lines at the end of the file.)
2449 */
2450 buf = preimage_eof = preimage->buf + preoff;
2451 for ( ; i < preimage->nr; i++)
2452 preoff += preimage->line[i].len;
2453 preimage_end = preimage->buf + preoff;
2454 for ( ; buf < preimage_end; buf++)
2455 if (!isspace(*buf))
2456 return 0;
2457
2458 /*
2459 * Update the preimage and the common postimage context
2460 * lines to use the same whitespace as the target.
2461 * If whitespace is missing in the target (i.e.
2462 * if the preimage extends beyond the end of the file),
2463 * use the whitespace from the preimage.
2464 */
2465 extra_chars = preimage_end - preimage_eof;
2466 strbuf_init(&fixed, imgoff + extra_chars);
6cbc7cfd 2467 strbuf_add(&fixed, img->buf + current, imgoff);
13b5af22
CC
2468 strbuf_add(&fixed, preimage_eof, extra_chars);
2469 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2470 update_pre_post_images(preimage, postimage,
2471 fixed_buf, fixed_len, postlen);
2472 return 1;
2473}
2474
2475static int match_fragment(struct apply_state *state,
2476 struct image *img,
2477 struct image *preimage,
2478 struct image *postimage,
6cbc7cfd
BW
2479 unsigned long current,
2480 int current_lno,
13b5af22
CC
2481 unsigned ws_rule,
2482 int match_beginning, int match_end)
2483{
2484 int i;
2485 char *fixed_buf, *buf, *orig, *target;
2486 struct strbuf fixed;
2487 size_t fixed_len, postlen;
2488 int preimage_limit;
2489
6cbc7cfd 2490 if (preimage->nr + current_lno <= img->nr) {
13b5af22
CC
2491 /*
2492 * The hunk falls within the boundaries of img.
2493 */
2494 preimage_limit = preimage->nr;
6cbc7cfd 2495 if (match_end && (preimage->nr + current_lno != img->nr))
13b5af22
CC
2496 return 0;
2497 } else if (state->ws_error_action == correct_ws_error &&
2498 (ws_rule & WS_BLANK_AT_EOF)) {
2499 /*
2500 * This hunk extends beyond the end of img, and we are
2501 * removing blank lines at the end of the file. This
2502 * many lines from the beginning of the preimage must
2503 * match with img, and the remainder of the preimage
2504 * must be blank.
2505 */
6cbc7cfd 2506 preimage_limit = img->nr - current_lno;
13b5af22
CC
2507 } else {
2508 /*
2509 * The hunk extends beyond the end of the img and
2510 * we are not removing blanks at the end, so we
2511 * should reject the hunk at this position.
2512 */
2513 return 0;
2514 }
2515
6cbc7cfd 2516 if (match_beginning && current_lno)
13b5af22
CC
2517 return 0;
2518
2519 /* Quick hash check */
2520 for (i = 0; i < preimage_limit; i++)
6cbc7cfd
BW
2521 if ((img->line[current_lno + i].flag & LINE_PATCHED) ||
2522 (preimage->line[i].hash != img->line[current_lno + i].hash))
13b5af22
CC
2523 return 0;
2524
2525 if (preimage_limit == preimage->nr) {
2526 /*
2527 * Do we have an exact match? If we were told to match
6cbc7cfd
BW
2528 * at the end, size must be exactly at current+fragsize,
2529 * otherwise current+fragsize must be still within the preimage,
13b5af22
CC
2530 * and either case, the old piece should match the preimage
2531 * exactly.
2532 */
2533 if ((match_end
6cbc7cfd
BW
2534 ? (current + preimage->len == img->len)
2535 : (current + preimage->len <= img->len)) &&
2536 !memcmp(img->buf + current, preimage->buf, preimage->len))
13b5af22
CC
2537 return 1;
2538 } else {
2539 /*
2540 * The preimage extends beyond the end of img, so
2541 * there cannot be an exact match.
2542 *
2543 * There must be one non-blank context line that match
2544 * a line before the end of img.
2545 */
2546 char *buf_end;
2547
2548 buf = preimage->buf;
2549 buf_end = buf;
2550 for (i = 0; i < preimage_limit; i++)
2551 buf_end += preimage->line[i].len;
2552
2553 for ( ; buf < buf_end; buf++)
2554 if (!isspace(*buf))
2555 break;
2556 if (buf == buf_end)
2557 return 0;
2558 }
2559
2560 /*
2561 * No exact match. If we are ignoring whitespace, run a line-by-line
2562 * fuzzy matching. We collect all the line length information because
2563 * we need it to adjust whitespace if we match.
2564 */
2565 if (state->ws_ignore_action == ignore_ws_change)
2566 return line_by_line_fuzzy_match(img, preimage, postimage,
6cbc7cfd 2567 current, current_lno, preimage_limit);
13b5af22
CC
2568
2569 if (state->ws_error_action != correct_ws_error)
2570 return 0;
2571
2572 /*
2573 * The hunk does not apply byte-by-byte, but the hash says
2574 * it might with whitespace fuzz. We weren't asked to
2575 * ignore whitespace, we were asked to correct whitespace
2576 * errors, so let's try matching after whitespace correction.
2577 *
2578 * While checking the preimage against the target, whitespace
2579 * errors in both fixed, we count how large the corresponding
2580 * postimage needs to be. The postimage prepared by
2581 * apply_one_fragment() has whitespace errors fixed on added
2582 * lines already, but the common lines were propagated as-is,
2583 * which may become longer when their whitespace errors are
2584 * fixed.
2585 */
2586
2587 /* First count added lines in postimage */
2588 postlen = 0;
2589 for (i = 0; i < postimage->nr; i++) {
2590 if (!(postimage->line[i].flag & LINE_COMMON))
2591 postlen += postimage->line[i].len;
2592 }
2593
2594 /*
2595 * The preimage may extend beyond the end of the file,
2596 * but in this loop we will only handle the part of the
2597 * preimage that falls within the file.
2598 */
2599 strbuf_init(&fixed, preimage->len + 1);
2600 orig = preimage->buf;
6cbc7cfd 2601 target = img->buf + current;
13b5af22
CC
2602 for (i = 0; i < preimage_limit; i++) {
2603 size_t oldlen = preimage->line[i].len;
6cbc7cfd 2604 size_t tgtlen = img->line[current_lno + i].len;
13b5af22
CC
2605 size_t fixstart = fixed.len;
2606 struct strbuf tgtfix;
2607 int match;
2608
2609 /* Try fixing the line in the preimage */
2610 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2611
2612 /* Try fixing the line in the target */
2613 strbuf_init(&tgtfix, tgtlen);
2614 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2615
2616 /*
2617 * If they match, either the preimage was based on
2618 * a version before our tree fixed whitespace breakage,
2619 * or we are lacking a whitespace-fix patch the tree
2620 * the preimage was based on already had (i.e. target
2621 * has whitespace breakage, the preimage doesn't).
2622 * In either case, we are fixing the whitespace breakages
2623 * so we might as well take the fix together with their
2624 * real change.
2625 */
2626 match = (tgtfix.len == fixed.len - fixstart &&
2627 !memcmp(tgtfix.buf, fixed.buf + fixstart,
2628 fixed.len - fixstart));
2629
2630 /* Add the length if this is common with the postimage */
2631 if (preimage->line[i].flag & LINE_COMMON)
2632 postlen += tgtfix.len;
2633
2634 strbuf_release(&tgtfix);
2635 if (!match)
2636 goto unmatch_exit;
2637
2638 orig += oldlen;
2639 target += tgtlen;
2640 }
2641
2642
2643 /*
2644 * Now handle the lines in the preimage that falls beyond the
2645 * end of the file (if any). They will only match if they are
2646 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2647 * false).
2648 */
2649 for ( ; i < preimage->nr; i++) {
2650 size_t fixstart = fixed.len; /* start of the fixed preimage */
2651 size_t oldlen = preimage->line[i].len;
2652 int j;
2653
2654 /* Try fixing the line in the preimage */
2655 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2656
2657 for (j = fixstart; j < fixed.len; j++)
2658 if (!isspace(fixed.buf[j]))
2659 goto unmatch_exit;
2660
2661 orig += oldlen;
2662 }
2663
2664 /*
2665 * Yes, the preimage is based on an older version that still
2666 * has whitespace breakages unfixed, and fixing them makes the
2667 * hunk match. Update the context lines in the postimage.
2668 */
2669 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2670 if (postlen < postimage->len)
2671 postlen = 0;
2672 update_pre_post_images(preimage, postimage,
2673 fixed_buf, fixed_len, postlen);
2674 return 1;
2675
2676 unmatch_exit:
2677 strbuf_release(&fixed);
2678 return 0;
2679}
2680
2681static int find_pos(struct apply_state *state,
2682 struct image *img,
2683 struct image *preimage,
2684 struct image *postimage,
2685 int line,
2686 unsigned ws_rule,
2687 int match_beginning, int match_end)
2688{
2689 int i;
6cbc7cfd
BW
2690 unsigned long backwards, forwards, current;
2691 int backwards_lno, forwards_lno, current_lno;
13b5af22 2692
b4bbbbd5
JS
2693 /*
2694 * When running with --allow-overlap, it is possible that a hunk is
2695 * seen that pretends to start at the beginning (but no longer does),
2696 * and that *still* needs to match the end. So trust `match_end` more
2697 * than `match_beginning`.
2698 */
2699 if (state->allow_overlap && match_beginning && match_end &&
2700 img->nr - preimage->nr != 0)
2701 match_beginning = 0;
2702
13b5af22
CC
2703 /*
2704 * If match_beginning or match_end is specified, there is no
2705 * point starting from a wrong line that will never match and
2706 * wander around and wait for a match at the specified end.
2707 */
2708 if (match_beginning)
2709 line = 0;
2710 else if (match_end)
2711 line = img->nr - preimage->nr;
2712
2713 /*
2714 * Because the comparison is unsigned, the following test
2715 * will also take care of a negative line number that can
2716 * result when match_end and preimage is larger than the target.
2717 */
2718 if ((size_t) line > img->nr)
2719 line = img->nr;
2720
6cbc7cfd 2721 current = 0;
13b5af22 2722 for (i = 0; i < line; i++)
6cbc7cfd 2723 current += img->line[i].len;
13b5af22
CC
2724
2725 /*
2726 * There's probably some smart way to do this, but I'll leave
2727 * that to the smart and beautiful people. I'm simple and stupid.
2728 */
6cbc7cfd 2729 backwards = current;
13b5af22 2730 backwards_lno = line;
6cbc7cfd 2731 forwards = current;
13b5af22 2732 forwards_lno = line;
6cbc7cfd 2733 current_lno = line;
13b5af22
CC
2734
2735 for (i = 0; ; i++) {
2736 if (match_fragment(state, img, preimage, postimage,
6cbc7cfd 2737 current, current_lno, ws_rule,
13b5af22 2738 match_beginning, match_end))
6cbc7cfd 2739 return current_lno;
13b5af22
CC
2740
2741 again:
2742 if (backwards_lno == 0 && forwards_lno == img->nr)
2743 break;
2744
2745 if (i & 1) {
2746 if (backwards_lno == 0) {
2747 i++;
2748 goto again;
2749 }
2750 backwards_lno--;
2751 backwards -= img->line[backwards_lno].len;
6cbc7cfd
BW
2752 current = backwards;
2753 current_lno = backwards_lno;
13b5af22
CC
2754 } else {
2755 if (forwards_lno == img->nr) {
2756 i++;
2757 goto again;
2758 }
2759 forwards += img->line[forwards_lno].len;
2760 forwards_lno++;
6cbc7cfd
BW
2761 current = forwards;
2762 current_lno = forwards_lno;
13b5af22
CC
2763 }
2764
2765 }
2766 return -1;
2767}
2768
2769static void remove_first_line(struct image *img)
2770{
2771 img->buf += img->line[0].len;
2772 img->len -= img->line[0].len;
2773 img->line++;
2774 img->nr--;
2775}
2776
2777static void remove_last_line(struct image *img)
2778{
2779 img->len -= img->line[--img->nr].len;
2780}
2781
2782/*
2783 * The change from "preimage" and "postimage" has been found to
2784 * apply at applied_pos (counts in line numbers) in "img".
2785 * Update "img" to remove "preimage" and replace it with "postimage".
2786 */
2787static void update_image(struct apply_state *state,
2788 struct image *img,
2789 int applied_pos,
2790 struct image *preimage,
2791 struct image *postimage)
2792{
2793 /*
2794 * remove the copy of preimage at offset in img
2795 * and replace it with postimage
2796 */
2797 int i, nr;
2798 size_t remove_count, insert_count, applied_at = 0;
2799 char *result;
2800 int preimage_limit;
2801
2802 /*
2803 * If we are removing blank lines at the end of img,
2804 * the preimage may extend beyond the end.
2805 * If that is the case, we must be careful only to
2806 * remove the part of the preimage that falls within
2807 * the boundaries of img. Initialize preimage_limit
2808 * to the number of lines in the preimage that falls
2809 * within the boundaries.
2810 */
2811 preimage_limit = preimage->nr;
2812 if (preimage_limit > img->nr - applied_pos)
2813 preimage_limit = img->nr - applied_pos;
2814
2815 for (i = 0; i < applied_pos; i++)
2816 applied_at += img->line[i].len;
2817
2818 remove_count = 0;
2819 for (i = 0; i < preimage_limit; i++)
2820 remove_count += img->line[applied_pos + i].len;
2821 insert_count = postimage->len;
2822
2823 /* Adjust the contents */
2824 result = xmalloc(st_add3(st_sub(img->len, remove_count), insert_count, 1));
2825 memcpy(result, img->buf, applied_at);
2826 memcpy(result + applied_at, postimage->buf, postimage->len);
2827 memcpy(result + applied_at + postimage->len,
2828 img->buf + (applied_at + remove_count),
2829 img->len - (applied_at + remove_count));
2830 free(img->buf);
2831 img->buf = result;
2832 img->len += insert_count - remove_count;
2833 result[img->len] = '\0';
2834
2835 /* Adjust the line table */
2836 nr = img->nr + postimage->nr - preimage_limit;
2837 if (preimage_limit < postimage->nr) {
2838 /*
2839 * NOTE: this knows that we never call remove_first_line()
2840 * on anything other than pre/post image.
2841 */
2842 REALLOC_ARRAY(img->line, nr);
2843 img->line_allocated = img->line;
2844 }
2845 if (preimage_limit != postimage->nr)
17736641
RS
2846 MOVE_ARRAY(img->line + applied_pos + postimage->nr,
2847 img->line + applied_pos + preimage_limit,
2848 img->nr - (applied_pos + preimage_limit));
2849 COPY_ARRAY(img->line + applied_pos, postimage->line, postimage->nr);
13b5af22
CC
2850 if (!state->allow_overlap)
2851 for (i = 0; i < postimage->nr; i++)
2852 img->line[applied_pos + i].flag |= LINE_PATCHED;
2853 img->nr = nr;
2854}
2855
2856/*
2857 * Use the patch-hunk text in "frag" to prepare two images (preimage and
2858 * postimage) for the hunk. Find lines that match "preimage" in "img" and
2859 * replace the part of "img" with "postimage" text.
2860 */
2861static int apply_one_fragment(struct apply_state *state,
2862 struct image *img, struct fragment *frag,
2863 int inaccurate_eof, unsigned ws_rule,
2864 int nth_fragment)
2865{
2866 int match_beginning, match_end;
2867 const char *patch = frag->patch;
2868 int size = frag->size;
2869 char *old, *oldlines;
2870 struct strbuf newlines;
2871 int new_blank_lines_at_end = 0;
2872 int found_new_blank_lines_at_end = 0;
2873 int hunk_linenr = frag->linenr;
2874 unsigned long leading, trailing;
2875 int pos, applied_pos;
2876 struct image preimage;
2877 struct image postimage;
2878
2879 memset(&preimage, 0, sizeof(preimage));
2880 memset(&postimage, 0, sizeof(postimage));
2881 oldlines = xmalloc(size);
2882 strbuf_init(&newlines, size);
2883
2884 old = oldlines;
2885 while (size > 0) {
2886 char first;
2887 int len = linelen(patch, size);
2888 int plen;
2889 int added_blank_line = 0;
2890 int is_blank_context = 0;
2891 size_t start;
2892
2893 if (!len)
2894 break;
2895
2896 /*
2897 * "plen" is how much of the line we should use for
2898 * the actual patch data. Normally we just remove the
2899 * first character on the line, but if the line is
2900 * followed by "\ No newline", then we also remove the
2901 * last one (which is the newline, of course).
2902 */
2903 plen = len - 1;
2904 if (len < size && patch[len] == '\\')
2905 plen--;
2906 first = *patch;
2907 if (state->apply_in_reverse) {
2908 if (first == '-')
2909 first = '+';
2910 else if (first == '+')
2911 first = '-';
2912 }
2913
2914 switch (first) {
2915 case '\n':
2916 /* Newer GNU diff, empty context line */
2917 if (plen < 0)
2918 /* ... followed by '\No newline'; nothing */
2919 break;
2920 *old++ = '\n';
2921 strbuf_addch(&newlines, '\n');
2922 add_line_info(&preimage, "\n", 1, LINE_COMMON);
2923 add_line_info(&postimage, "\n", 1, LINE_COMMON);
2924 is_blank_context = 1;
2925 break;
2926 case ' ':
2927 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
c5224f0f 2928 ws_blank_line(patch + 1, plen))
13b5af22 2929 is_blank_context = 1;
1cf01a34 2930 /* fallthrough */
13b5af22
CC
2931 case '-':
2932 memcpy(old, patch + 1, plen);
2933 add_line_info(&preimage, old, plen,
2934 (first == ' ' ? LINE_COMMON : 0));
2935 old += plen;
2936 if (first == '-')
2937 break;
1cf01a34 2938 /* fallthrough */
13b5af22
CC
2939 case '+':
2940 /* --no-add does not add new lines */
2941 if (first == '+' && state->no_add)
2942 break;
2943
2944 start = newlines.len;
2945 if (first != '+' ||
2946 !state->whitespace_error ||
2947 state->ws_error_action != correct_ws_error) {
2948 strbuf_add(&newlines, patch + 1, plen);
2949 }
2950 else {
2951 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &state->applied_after_fixing_ws);
2952 }
2953 add_line_info(&postimage, newlines.buf + start, newlines.len - start,
2954 (first == '+' ? 0 : LINE_COMMON));
2955 if (first == '+' &&
2956 (ws_rule & WS_BLANK_AT_EOF) &&
c5224f0f 2957 ws_blank_line(patch + 1, plen))
13b5af22
CC
2958 added_blank_line = 1;
2959 break;
2960 case '@': case '\\':
2961 /* Ignore it, we already handled it */
2962 break;
2963 default:
a46160d2 2964 if (state->apply_verbosity > verbosity_normal)
13b5af22
CC
2965 error(_("invalid start of line: '%c'"), first);
2966 applied_pos = -1;
2967 goto out;
2968 }
2969 if (added_blank_line) {
2970 if (!new_blank_lines_at_end)
2971 found_new_blank_lines_at_end = hunk_linenr;
2972 new_blank_lines_at_end++;
2973 }
2974 else if (is_blank_context)
2975 ;
2976 else
2977 new_blank_lines_at_end = 0;
2978 patch += len;
2979 size -= len;
2980 hunk_linenr++;
2981 }
2982 if (inaccurate_eof &&
2983 old > oldlines && old[-1] == '\n' &&
2984 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
2985 old--;
2986 strbuf_setlen(&newlines, newlines.len - 1);
4855de12
RS
2987 preimage.line_allocated[preimage.nr - 1].len--;
2988 postimage.line_allocated[postimage.nr - 1].len--;
13b5af22
CC
2989 }
2990
2991 leading = frag->leading;
2992 trailing = frag->trailing;
2993
2994 /*
2995 * A hunk to change lines at the beginning would begin with
2996 * @@ -1,L +N,M @@
2997 * but we need to be careful. -U0 that inserts before the second
2998 * line also has this pattern.
2999 *
3000 * And a hunk to add to an empty file would begin with
3001 * @@ -0,0 +N,M @@
3002 *
3003 * In other words, a hunk that is (frag->oldpos <= 1) with or
3004 * without leading context must match at the beginning.
3005 */
3006 match_beginning = (!frag->oldpos ||
3007 (frag->oldpos == 1 && !state->unidiff_zero));
3008
3009 /*
3010 * A hunk without trailing lines must match at the end.
3011 * However, we simply cannot tell if a hunk must match end
3012 * from the lack of trailing lines if the patch was generated
3013 * with unidiff without any context.
3014 */
3015 match_end = !state->unidiff_zero && !trailing;
3016
3017 pos = frag->newpos ? (frag->newpos - 1) : 0;
3018 preimage.buf = oldlines;
3019 preimage.len = old - oldlines;
3020 postimage.buf = newlines.buf;
3021 postimage.len = newlines.len;
3022 preimage.line = preimage.line_allocated;
3023 postimage.line = postimage.line_allocated;
3024
3025 for (;;) {
3026
3027 applied_pos = find_pos(state, img, &preimage, &postimage, pos,
3028 ws_rule, match_beginning, match_end);
3029
3030 if (applied_pos >= 0)
3031 break;
3032
3033 /* Am I at my context limits? */
3034 if ((leading <= state->p_context) && (trailing <= state->p_context))
3035 break;
3036 if (match_beginning || match_end) {
3037 match_beginning = match_end = 0;
3038 continue;
3039 }
3040
3041 /*
3042 * Reduce the number of context lines; reduce both
3043 * leading and trailing if they are equal otherwise
3044 * just reduce the larger context.
3045 */
3046 if (leading >= trailing) {
3047 remove_first_line(&preimage);
3048 remove_first_line(&postimage);
3049 pos--;
3050 leading--;
3051 }
3052 if (trailing > leading) {
3053 remove_last_line(&preimage);
3054 remove_last_line(&postimage);
3055 trailing--;
3056 }
3057 }
3058
3059 if (applied_pos >= 0) {
3060 if (new_blank_lines_at_end &&
3061 preimage.nr + applied_pos >= img->nr &&
3062 (ws_rule & WS_BLANK_AT_EOF) &&
3063 state->ws_error_action != nowarn_ws_error) {
3064 record_ws_error(state, WS_BLANK_AT_EOF, "+", 1,
3065 found_new_blank_lines_at_end);
3066 if (state->ws_error_action == correct_ws_error) {
3067 while (new_blank_lines_at_end--)
3068 remove_last_line(&postimage);
3069 }
3070 /*
3071 * We would want to prevent write_out_results()
3072 * from taking place in apply_patch() that follows
3073 * the callchain led us here, which is:
3074 * apply_patch->check_patch_list->check_patch->
3075 * apply_data->apply_fragments->apply_one_fragment
3076 */
3077 if (state->ws_error_action == die_on_ws_error)
3078 state->apply = 0;
3079 }
3080
a46160d2 3081 if (state->apply_verbosity > verbosity_normal && applied_pos != pos) {
13b5af22
CC
3082 int offset = applied_pos - pos;
3083 if (state->apply_in_reverse)
3084 offset = 0 - offset;
3085 fprintf_ln(stderr,
3086 Q_("Hunk #%d succeeded at %d (offset %d line).",
3087 "Hunk #%d succeeded at %d (offset %d lines).",
3088 offset),
3089 nth_fragment, applied_pos + 1, offset);
3090 }
3091
3092 /*
3093 * Warn if it was necessary to reduce the number
3094 * of context lines.
3095 */
a46160d2
CC
3096 if ((leading != frag->leading ||
3097 trailing != frag->trailing) && state->apply_verbosity > verbosity_silent)
13b5af22
CC
3098 fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"
3099 " to apply fragment at %d"),
3100 leading, trailing, applied_pos+1);
3101 update_image(state, img, applied_pos, &preimage, &postimage);
3102 } else {
a46160d2 3103 if (state->apply_verbosity > verbosity_normal)
13b5af22
CC
3104 error(_("while searching for:\n%.*s"),
3105 (int)(old - oldlines), oldlines);
3106 }
3107
3108out:
3109 free(oldlines);
3110 strbuf_release(&newlines);
3111 free(preimage.line_allocated);
3112 free(postimage.line_allocated);
3113
3114 return (applied_pos < 0);
3115}
3116
3117static int apply_binary_fragment(struct apply_state *state,
3118 struct image *img,
3119 struct patch *patch)
3120{
3121 struct fragment *fragment = patch->fragments;
3122 unsigned long len;
3123 void *dst;
3124
3125 if (!fragment)
3126 return error(_("missing binary patch data for '%s'"),
3127 patch->new_name ?
3128 patch->new_name :
3129 patch->old_name);
3130
3131 /* Binary patch is irreversible without the optional second hunk */
3132 if (state->apply_in_reverse) {
3133 if (!fragment->next)
d1d42bf5
VA
3134 return error(_("cannot reverse-apply a binary patch "
3135 "without the reverse hunk to '%s'"),
13b5af22
CC
3136 patch->new_name
3137 ? patch->new_name : patch->old_name);
3138 fragment = fragment->next;
3139 }
3140 switch (fragment->binary_patch_method) {
3141 case BINARY_DELTA_DEFLATED:
3142 dst = patch_delta(img->buf, img->len, fragment->patch,
3143 fragment->size, &len);
3144 if (!dst)
3145 return -1;
3146 clear_image(img);
3147 img->buf = dst;
3148 img->len = len;
3149 return 0;
3150 case BINARY_LITERAL_DEFLATED:
3151 clear_image(img);
3152 img->len = fragment->size;
3153 img->buf = xmemdupz(fragment->patch, img->len);
3154 return 0;
3155 }
3156 return -1;
3157}
3158
3159/*
3160 * Replace "img" with the result of applying the binary patch.
3161 * The binary patch data itself in patch->fragment is still kept
3162 * but the preimage prepared by the caller in "img" is freed here
3163 * or in the helper function apply_binary_fragment() this calls.
3164 */
3165static int apply_binary(struct apply_state *state,
3166 struct image *img,
3167 struct patch *patch)
3168{
3169 const char *name = patch->old_name ? patch->old_name : patch->new_name;
4af9a7d3 3170 struct object_id oid;
93eb00f7 3171 const unsigned hexsz = the_hash_algo->hexsz;
13b5af22
CC
3172
3173 /*
3174 * For safety, we require patch index line to contain
93eb00f7 3175 * full hex textual object ID for old and new, at least for now.
13b5af22 3176 */
eccb5a5f 3177 if (strlen(patch->old_oid_prefix) != hexsz ||
3178 strlen(patch->new_oid_prefix) != hexsz ||
3179 get_oid_hex(patch->old_oid_prefix, &oid) ||
3180 get_oid_hex(patch->new_oid_prefix, &oid))
d1d42bf5
VA
3181 return error(_("cannot apply binary patch to '%s' "
3182 "without full index line"), name);
13b5af22
CC
3183
3184 if (patch->old_name) {
3185 /*
3186 * See if the old one matches what the patch
3187 * applies to.
3188 */
44439c1c 3189 hash_object_file(the_hash_algo, img->buf, img->len, OBJ_BLOB,
2dcde20e 3190 &oid);
eccb5a5f 3191 if (strcmp(oid_to_hex(&oid), patch->old_oid_prefix))
d1d42bf5
VA
3192 return error(_("the patch applies to '%s' (%s), "
3193 "which does not match the "
3194 "current contents."),
4af9a7d3 3195 name, oid_to_hex(&oid));
13b5af22
CC
3196 }
3197 else {
3198 /* Otherwise, the old one must be empty. */
3199 if (img->len)
d1d42bf5
VA
3200 return error(_("the patch applies to an empty "
3201 "'%s' but it is not empty"), name);
13b5af22
CC
3202 }
3203
eccb5a5f 3204 get_oid_hex(patch->new_oid_prefix, &oid);
4af9a7d3 3205 if (is_null_oid(&oid)) {
13b5af22
CC
3206 clear_image(img);
3207 return 0; /* deletion patch */
3208 }
3209
3318238d 3210 if (has_object(the_repository, &oid, 0)) {
13b5af22
CC
3211 /* We already have the postimage */
3212 enum object_type type;
3213 unsigned long size;
3214 char *result;
3215
bc726bd0
ÆAB
3216 result = repo_read_object_file(the_repository, &oid, &type,
3217 &size);
13b5af22 3218 if (!result)
d1d42bf5
VA
3219 return error(_("the necessary postimage %s for "
3220 "'%s' cannot be read"),
eccb5a5f 3221 patch->new_oid_prefix, name);
13b5af22
CC
3222 clear_image(img);
3223 img->buf = result;
3224 img->len = size;
3225 } else {
3226 /*
3227 * We have verified buf matches the preimage;
3228 * apply the patch data to it, which is stored
3229 * in the patch->fragments->{patch,size}.
3230 */
3231 if (apply_binary_fragment(state, img, patch))
3232 return error(_("binary patch does not apply to '%s'"),
3233 name);
3234
3235 /* verify that the result matches */
44439c1c 3236 hash_object_file(the_hash_algo, img->buf, img->len, OBJ_BLOB,
2dcde20e 3237 &oid);
eccb5a5f 3238 if (strcmp(oid_to_hex(&oid), patch->new_oid_prefix))
13b5af22 3239 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
eccb5a5f 3240 name, patch->new_oid_prefix, oid_to_hex(&oid));
13b5af22
CC
3241 }
3242
3243 return 0;
3244}
3245
3246static int apply_fragments(struct apply_state *state, struct image *img, struct patch *patch)
3247{
3248 struct fragment *frag = patch->fragments;
3249 const char *name = patch->old_name ? patch->old_name : patch->new_name;
3250 unsigned ws_rule = patch->ws_rule;
3251 unsigned inaccurate_eof = patch->inaccurate_eof;
3252 int nth = 0;
3253
3254 if (patch->is_binary)
3255 return apply_binary(state, img, patch);
3256
3257 while (frag) {
3258 nth++;
3259 if (apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {
3260 error(_("patch failed: %s:%ld"), name, frag->oldpos);
3261 if (!state->apply_with_reject)
3262 return -1;
3263 frag->rejected = 1;
3264 }
3265 frag = frag->next;
3266 }
3267 return 0;
3268}
3269
4af9a7d3 3270static int read_blob_object(struct strbuf *buf, const struct object_id *oid, unsigned mode)
13b5af22
CC
3271{
3272 if (S_ISGITLINK(mode)) {
3273 strbuf_grow(buf, 100);
4af9a7d3 3274 strbuf_addf(buf, "Subproject commit %s\n", oid_to_hex(oid));
13b5af22
CC
3275 } else {
3276 enum object_type type;
3277 unsigned long sz;
3278 char *result;
3279
bc726bd0
ÆAB
3280 result = repo_read_object_file(the_repository, oid, &type,
3281 &sz);
13b5af22
CC
3282 if (!result)
3283 return -1;
3284 /* XXX read_sha1_file NUL-terminates */
3285 strbuf_attach(buf, result, sz, sz + 1);
3286 }
3287 return 0;
3288}
3289
3290static int read_file_or_gitlink(const struct cache_entry *ce, struct strbuf *buf)
3291{
3292 if (!ce)
3293 return 0;
4af9a7d3 3294 return read_blob_object(buf, &ce->oid, ce->ce_mode);
13b5af22
CC
3295}
3296
3297static struct patch *in_fn_table(struct apply_state *state, const char *name)
3298{
3299 struct string_list_item *item;
3300
afe8a907 3301 if (!name)
13b5af22
CC
3302 return NULL;
3303
3304 item = string_list_lookup(&state->fn_table, name);
afe8a907 3305 if (item)
13b5af22
CC
3306 return (struct patch *)item->util;
3307
3308 return NULL;
3309}
3310
3311/*
3312 * item->util in the filename table records the status of the path.
3313 * Usually it points at a patch (whose result records the contents
3314 * of it after applying it), but it could be PATH_WAS_DELETED for a
3315 * path that a previously applied patch has already removed, or
3316 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3317 *
3318 * The latter is needed to deal with a case where two paths A and B
3319 * are swapped by first renaming A to B and then renaming B to A;
3320 * moving A to B should not be prevented due to presence of B as we
3321 * will remove it in a later patch.
3322 */
3323#define PATH_TO_BE_DELETED ((struct patch *) -2)
3324#define PATH_WAS_DELETED ((struct patch *) -1)
3325
3326static int to_be_deleted(struct patch *patch)
3327{
3328 return patch == PATH_TO_BE_DELETED;
3329}
3330
3331static int was_deleted(struct patch *patch)
3332{
3333 return patch == PATH_WAS_DELETED;
3334}
3335
3336static void add_to_fn_table(struct apply_state *state, struct patch *patch)
3337{
3338 struct string_list_item *item;
3339
3340 /*
3341 * Always add new_name unless patch is a deletion
3342 * This should cover the cases for normal diffs,
3343 * file creations and copies
3344 */
afe8a907 3345 if (patch->new_name) {
13b5af22
CC
3346 item = string_list_insert(&state->fn_table, patch->new_name);
3347 item->util = patch;
3348 }
3349
3350 /*
3351 * store a failure on rename/deletion cases because
3352 * later chunks shouldn't patch old names
3353 */
3354 if ((patch->new_name == NULL) || (patch->is_rename)) {
3355 item = string_list_insert(&state->fn_table, patch->old_name);
3356 item->util = PATH_WAS_DELETED;
3357 }
3358}
3359
3360static void prepare_fn_table(struct apply_state *state, struct patch *patch)
3361{
3362 /*
3363 * store information about incoming file deletion
3364 */
3365 while (patch) {
3366 if ((patch->new_name == NULL) || (patch->is_rename)) {
3367 struct string_list_item *item;
3368 item = string_list_insert(&state->fn_table, patch->old_name);
3369 item->util = PATH_TO_BE_DELETED;
3370 }
3371 patch = patch->next;
3372 }
3373}
3374
3375static int checkout_target(struct index_state *istate,
3376 struct cache_entry *ce, struct stat *st)
3377{
68e3d629 3378 struct checkout costate = CHECKOUT_INIT;
13b5af22 3379
13b5af22
CC
3380 costate.refresh_cache = 1;
3381 costate.istate = istate;
0f086e6d
NTND
3382 if (checkout_entry(ce, &costate, NULL, NULL) ||
3383 lstat(ce->name, st))
13b5af22
CC
3384 return error(_("cannot checkout %s"), ce->name);
3385 return 0;
3386}
3387
3388static struct patch *previous_patch(struct apply_state *state,
3389 struct patch *patch,
3390 int *gone)
3391{
3392 struct patch *previous;
3393
3394 *gone = 0;
3395 if (patch->is_copy || patch->is_rename)
3396 return NULL; /* "git" patches do not depend on the order */
3397
3398 previous = in_fn_table(state, patch->old_name);
3399 if (!previous)
3400 return NULL;
3401
3402 if (to_be_deleted(previous))
3403 return NULL; /* the deletion hasn't happened yet */
3404
3405 if (was_deleted(previous))
3406 *gone = 1;
3407
3408 return previous;
3409}
3410
332a82a5
NTND
3411static int verify_index_match(struct apply_state *state,
3412 const struct cache_entry *ce,
3413 struct stat *st)
13b5af22
CC
3414{
3415 if (S_ISGITLINK(ce->ce_mode)) {
3416 if (!S_ISDIR(st->st_mode))
3417 return -1;
3418 return 0;
3419 }
1b5c6c1e
NTND
3420 return ie_match_stat(state->repo->index, ce, st,
3421 CE_MATCH_IGNORE_VALID | CE_MATCH_IGNORE_SKIP_WORKTREE);
13b5af22
CC
3422}
3423
3424#define SUBMODULE_PATCH_WITHOUT_INDEX 1
3425
3426static int load_patch_target(struct apply_state *state,
3427 struct strbuf *buf,
3428 const struct cache_entry *ce,
3429 struct stat *st,
c24f3aba 3430 struct patch *patch,
13b5af22
CC
3431 const char *name,
3432 unsigned expected_mode)
3433{
3434 if (state->cached || state->check_index) {
3435 if (read_file_or_gitlink(ce, buf))
3436 return error(_("failed to read %s"), name);
3437 } else if (name) {
3438 if (S_ISGITLINK(expected_mode)) {
3439 if (ce)
3440 return read_file_or_gitlink(ce, buf);
3441 else
3442 return SUBMODULE_PATCH_WITHOUT_INDEX;
3443 } else if (has_symlink_leading_path(name, strlen(name))) {
3444 return error(_("reading from '%s' beyond a symbolic link"), name);
3445 } else {
c24f3aba 3446 if (read_old_data(st, patch, name, buf))
13b5af22
CC
3447 return error(_("failed to read %s"), name);
3448 }
3449 }
3450 return 0;
3451}
3452
3453/*
3454 * We are about to apply "patch"; populate the "image" with the
3455 * current version we have, from the working tree or from the index,
3456 * depending on the situation e.g. --cached/--index. If we are
3457 * applying a non-git patch that incrementally updates the tree,
3458 * we read from the result of a previous diff.
3459 */
3460static int load_preimage(struct apply_state *state,
3461 struct image *image,
3462 struct patch *patch, struct stat *st,
3463 const struct cache_entry *ce)
3464{
3465 struct strbuf buf = STRBUF_INIT;
3466 size_t len;
3467 char *img;
3468 struct patch *previous;
3469 int status;
3470
3471 previous = previous_patch(state, patch, &status);
3472 if (status)
3473 return error(_("path %s has been renamed/deleted"),
3474 patch->old_name);
3475 if (previous) {
3476 /* We have a patched copy in memory; use that. */
3477 strbuf_add(&buf, previous->result, previous->resultsize);
3478 } else {
c24f3aba 3479 status = load_patch_target(state, &buf, ce, st, patch,
13b5af22
CC
3480 patch->old_name, patch->old_mode);
3481 if (status < 0)
3482 return status;
3483 else if (status == SUBMODULE_PATCH_WITHOUT_INDEX) {
3484 /*
3485 * There is no way to apply subproject
3486 * patch without looking at the index.
3487 * NEEDSWORK: shouldn't this be flagged
3488 * as an error???
3489 */
3490 free_fragment_list(patch->fragments);
3491 patch->fragments = NULL;
3492 } else if (status) {
3493 return error(_("failed to read %s"), patch->old_name);
3494 }
3495 }
3496
3497 img = strbuf_detach(&buf, &len);
3498 prepare_image(image, img, len, !patch->is_binary);
3499 return 0;
3500}
3501
57f183b6
JH
3502static int resolve_to(struct image *image, const struct object_id *result_id)
3503{
3504 unsigned long size;
3505 enum object_type type;
3506
3507 clear_image(image);
3508
bc726bd0
ÆAB
3509 image->buf = repo_read_object_file(the_repository, result_id, &type,
3510 &size);
57f183b6
JH
3511 if (!image->buf || type != OBJ_BLOB)
3512 die("unable to read blob object %s", oid_to_hex(result_id));
3513 image->len = size;
3514
3515 return 0;
3516}
3517
32eaa468
NTND
3518static int three_way_merge(struct apply_state *state,
3519 struct image *image,
13b5af22 3520 char *path,
4af9a7d3
JH
3521 const struct object_id *base,
3522 const struct object_id *ours,
3523 const struct object_id *theirs)
13b5af22
CC
3524{
3525 mmfile_t base_file, our_file, their_file;
3526 mmbuffer_t result = { NULL };
35f69671 3527 enum ll_merge_result status;
13b5af22 3528
57f183b6
JH
3529 /* resolve trivial cases first */
3530 if (oideq(base, ours))
3531 return resolve_to(image, theirs);
3532 else if (oideq(base, theirs) || oideq(ours, theirs))
3533 return resolve_to(image, ours);
3534
13b5af22
CC
3535 read_mmblob(&base_file, base);
3536 read_mmblob(&our_file, ours);
3537 read_mmblob(&their_file, theirs);
3538 status = ll_merge(&result, path,
3539 &base_file, "base",
3540 &our_file, "ours",
32eaa468
NTND
3541 &their_file, "theirs",
3542 state->repo->index,
3543 NULL);
35f69671
EN
3544 if (status == LL_MERGE_BINARY_CONFLICT)
3545 warning("Cannot merge binary files: %s (%s vs. %s)",
3546 path, "ours", "theirs");
13b5af22
CC
3547 free(base_file.ptr);
3548 free(our_file.ptr);
3549 free(their_file.ptr);
3550 if (status < 0 || !result.ptr) {
3551 free(result.ptr);
3552 return -1;
3553 }
3554 clear_image(image);
3555 image->buf = result.ptr;
3556 image->len = result.size;
3557
3558 return status;
3559}
3560
3561/*
3562 * When directly falling back to add/add three-way merge, we read from
3563 * the current contents of the new_name. In no cases other than that
3564 * this function will be called.
3565 */
3566static int load_current(struct apply_state *state,
3567 struct image *image,
3568 struct patch *patch)
3569{
3570 struct strbuf buf = STRBUF_INIT;
3571 int status, pos;
3572 size_t len;
3573 char *img;
3574 struct stat st;
3575 struct cache_entry *ce;
3576 char *name = patch->new_name;
3577 unsigned mode = patch->new_mode;
3578
3579 if (!patch->is_new)
033abf97 3580 BUG("patch to %s is not a creation", patch->old_name);
13b5af22 3581
1b5c6c1e 3582 pos = index_name_pos(state->repo->index, name, strlen(name));
13b5af22
CC
3583 if (pos < 0)
3584 return error(_("%s: does not exist in index"), name);
1b5c6c1e 3585 ce = state->repo->index->cache[pos];
13b5af22
CC
3586 if (lstat(name, &st)) {
3587 if (errno != ENOENT)
90875eca 3588 return error_errno("%s", name);
1b5c6c1e 3589 if (checkout_target(state->repo->index, ce, &st))
13b5af22
CC
3590 return -1;
3591 }
332a82a5 3592 if (verify_index_match(state, ce, &st))
13b5af22
CC
3593 return error(_("%s: does not match index"), name);
3594
c24f3aba 3595 status = load_patch_target(state, &buf, ce, &st, patch, name, mode);
13b5af22
CC
3596 if (status < 0)
3597 return status;
3598 else if (status)
3599 return -1;
3600 img = strbuf_detach(&buf, &len);
3601 prepare_image(image, img, len, !patch->is_binary);
3602 return 0;
3603}
3604
3605static int try_threeway(struct apply_state *state,
3606 struct image *image,
3607 struct patch *patch,
3608 struct stat *st,
3609 const struct cache_entry *ce)
3610{
4af9a7d3 3611 struct object_id pre_oid, post_oid, our_oid;
13b5af22
CC
3612 struct strbuf buf = STRBUF_INIT;
3613 size_t len;
3614 int status;
3615 char *img;
3616 struct image tmp_image;
3617
3618 /* No point falling back to 3-way merge in these cases */
3619 if (patch->is_delete ||
34d60703
JZ
3620 S_ISGITLINK(patch->old_mode) || S_ISGITLINK(patch->new_mode) ||
3621 (patch->is_new && !patch->direct_to_threeway) ||
3622 (patch->is_rename && !patch->lines_added && !patch->lines_deleted))
13b5af22
CC
3623 return -1;
3624
3625 /* Preimage the patch was prepared for */
3626 if (patch->is_new)
c80d226a 3627 write_object_file("", 0, OBJ_BLOB, &pre_oid);
d850b7a5 3628 else if (repo_get_oid(the_repository, patch->old_oid_prefix, &pre_oid) ||
4af9a7d3 3629 read_blob_object(&buf, &pre_oid, patch->old_mode))
923cd87a 3630 return error(_("repository lacks the necessary blob to perform 3-way merge."));
13b5af22 3631
526705fd 3632 if (state->apply_verbosity > verbosity_silent && patch->direct_to_threeway)
923cd87a 3633 fprintf(stderr, _("Performing three-way merge...\n"));
13b5af22
CC
3634
3635 img = strbuf_detach(&buf, &len);
3636 prepare_image(&tmp_image, img, len, 1);
3637 /* Apply the patch to get the post image */
3638 if (apply_fragments(state, &tmp_image, patch) < 0) {
3639 clear_image(&tmp_image);
3640 return -1;
3641 }
4af9a7d3 3642 /* post_oid is theirs */
c80d226a 3643 write_object_file(tmp_image.buf, tmp_image.len, OBJ_BLOB, &post_oid);
13b5af22
CC
3644 clear_image(&tmp_image);
3645
4af9a7d3 3646 /* our_oid is ours */
13b5af22
CC
3647 if (patch->is_new) {
3648 if (load_current(state, &tmp_image, patch))
d1d42bf5 3649 return error(_("cannot read the current contents of '%s'"),
13b5af22
CC
3650 patch->new_name);
3651 } else {
3652 if (load_preimage(state, &tmp_image, patch, st, ce))
d1d42bf5 3653 return error(_("cannot read the current contents of '%s'"),
13b5af22
CC
3654 patch->old_name);
3655 }
c80d226a 3656 write_object_file(tmp_image.buf, tmp_image.len, OBJ_BLOB, &our_oid);
13b5af22
CC
3657 clear_image(&tmp_image);
3658
3659 /* in-core three-way merge between post and our using pre as base */
32eaa468 3660 status = three_way_merge(state, image, patch->new_name,
4af9a7d3 3661 &pre_oid, &our_oid, &post_oid);
13b5af22 3662 if (status < 0) {
a46160d2
CC
3663 if (state->apply_verbosity > verbosity_silent)
3664 fprintf(stderr,
923cd87a 3665 _("Failed to perform three-way merge...\n"));
13b5af22
CC
3666 return status;
3667 }
3668
3669 if (status) {
3670 patch->conflicted_threeway = 1;
3671 if (patch->is_new)
3672 oidclr(&patch->threeway_stage[0]);
3673 else
4af9a7d3
JH
3674 oidcpy(&patch->threeway_stage[0], &pre_oid);
3675 oidcpy(&patch->threeway_stage[1], &our_oid);
3676 oidcpy(&patch->threeway_stage[2], &post_oid);
a46160d2
CC
3677 if (state->apply_verbosity > verbosity_silent)
3678 fprintf(stderr,
5886637a 3679 _("Applied patch to '%s' with conflicts.\n"),
a46160d2 3680 patch->new_name);
13b5af22 3681 } else {
a46160d2
CC
3682 if (state->apply_verbosity > verbosity_silent)
3683 fprintf(stderr,
5886637a 3684 _("Applied patch to '%s' cleanly.\n"),
a46160d2 3685 patch->new_name);
13b5af22
CC
3686 }
3687 return 0;
3688}
3689
3690static int apply_data(struct apply_state *state, struct patch *patch,
3691 struct stat *st, const struct cache_entry *ce)
3692{
3693 struct image image;
3694
3695 if (load_preimage(state, &image, patch, st, ce) < 0)
3696 return -1;
3697
923cd87a 3698 if (!state->threeway || try_threeway(state, &image, patch, st, ce) < 0) {
526705fd
JZ
3699 if (state->apply_verbosity > verbosity_silent &&
3700 state->threeway && !patch->direct_to_threeway)
3701 fprintf(stderr, _("Falling back to direct application...\n"));
3702
13b5af22 3703 /* Note: with --reject, apply_fragments() returns 0 */
923cd87a 3704 if (patch->direct_to_threeway || apply_fragments(state, &image, patch) < 0)
13b5af22
CC
3705 return -1;
3706 }
3707 patch->result = image.buf;
3708 patch->resultsize = image.len;
3709 add_to_fn_table(state, patch);
3710 free(image.line_allocated);
3711
3712 if (0 < patch->is_delete && patch->resultsize)
3713 return error(_("removal patch leaves file contents"));
3714
3715 return 0;
3716}
3717
3718/*
3719 * If "patch" that we are looking at modifies or deletes what we have,
3720 * we would want it not to lose any local modification we have, either
3721 * in the working tree or in the index.
3722 *
3723 * This also decides if a non-git patch is a creation patch or a
3724 * modification to an existing empty file. We do not check the state
3725 * of the current tree for a creation patch in this function; the caller
3726 * check_patch() separately makes sure (and errors out otherwise) that
3727 * the path the patch creates does not exist in the current tree.
3728 */
3729static int check_preimage(struct apply_state *state,
3730 struct patch *patch,
3731 struct cache_entry **ce,
3732 struct stat *st)
3733{
3734 const char *old_name = patch->old_name;
3735 struct patch *previous = NULL;
3736 int stat_ret = 0, status;
3737 unsigned st_mode = 0;
3738
3739 if (!old_name)
3740 return 0;
3741
3742 assert(patch->is_new <= 0);
3743 previous = previous_patch(state, patch, &status);
3744
3745 if (status)
3746 return error(_("path %s has been renamed/deleted"), old_name);
3747 if (previous) {
3748 st_mode = previous->new_mode;
3749 } else if (!state->cached) {
3750 stat_ret = lstat(old_name, st);
3751 if (stat_ret && errno != ENOENT)
90875eca 3752 return error_errno("%s", old_name);
13b5af22
CC
3753 }
3754
3755 if (state->check_index && !previous) {
1b5c6c1e
NTND
3756 int pos = index_name_pos(state->repo->index, old_name,
3757 strlen(old_name));
13b5af22
CC
3758 if (pos < 0) {
3759 if (patch->is_new < 0)
3760 goto is_new;
3761 return error(_("%s: does not exist in index"), old_name);
3762 }
1b5c6c1e 3763 *ce = state->repo->index->cache[pos];
13b5af22 3764 if (stat_ret < 0) {
1b5c6c1e 3765 if (checkout_target(state->repo->index, *ce, st))
13b5af22
CC
3766 return -1;
3767 }
332a82a5 3768 if (!state->cached && verify_index_match(state, *ce, st))
13b5af22
CC
3769 return error(_("%s: does not match index"), old_name);
3770 if (state->cached)
3771 st_mode = (*ce)->ce_mode;
3772 } else if (stat_ret < 0) {
3773 if (patch->is_new < 0)
3774 goto is_new;
90875eca 3775 return error_errno("%s", old_name);
13b5af22
CC
3776 }
3777
3778 if (!state->cached && !previous)
3779 st_mode = ce_mode_from_stat(*ce, st->st_mode);
3780
3781 if (patch->is_new < 0)
3782 patch->is_new = 0;
3783 if (!patch->old_mode)
3784 patch->old_mode = st_mode;
3785 if ((st_mode ^ patch->old_mode) & S_IFMT)
3786 return error(_("%s: wrong type"), old_name);
3787 if (st_mode != patch->old_mode)
3788 warning(_("%s has type %o, expected %o"),
3789 old_name, st_mode, patch->old_mode);
3790 if (!patch->new_mode && !patch->is_delete)
3791 patch->new_mode = st_mode;
3792 return 0;
3793
3794 is_new:
3795 patch->is_new = 1;
3796 patch->is_delete = 0;
6a83d902 3797 FREE_AND_NULL(patch->old_name);
13b5af22
CC
3798 return 0;
3799}
3800
3801
3802#define EXISTS_IN_INDEX 1
3803#define EXISTS_IN_WORKTREE 2
e3cc41b4 3804#define EXISTS_IN_INDEX_AS_ITA 3
13b5af22
CC
3805
3806static int check_to_create(struct apply_state *state,
3807 const char *new_name,
3808 int ok_if_exists)
3809{
3810 struct stat nst;
3811
e3cc41b4
RP
3812 if (state->check_index && (!ok_if_exists || !state->cached)) {
3813 int pos;
3814
3815 pos = index_name_pos(state->repo->index, new_name, strlen(new_name));
3816 if (pos >= 0) {
3817 struct cache_entry *ce = state->repo->index->cache[pos];
3818
3819 /* allow ITA, as they do not yet exist in the index */
3820 if (!ok_if_exists && !(ce->ce_flags & CE_INTENT_TO_ADD))
3821 return EXISTS_IN_INDEX;
3822
3823 /* ITA entries can never match working tree files */
3824 if (!state->cached && (ce->ce_flags & CE_INTENT_TO_ADD))
3825 return EXISTS_IN_INDEX_AS_ITA;
3826 }
7cfde3fa
RP
3827 }
3828
13b5af22
CC
3829 if (state->cached)
3830 return 0;
3831
3832 if (!lstat(new_name, &nst)) {
3833 if (S_ISDIR(nst.st_mode) || ok_if_exists)
3834 return 0;
3835 /*
3836 * A leading component of new_name might be a symlink
3837 * that is going to be removed with this patch, but
3838 * still pointing at somewhere that has the path.
3839 * In such a case, path "new_name" does not exist as
3840 * far as git is concerned.
3841 */
3842 if (has_symlink_leading_path(new_name, strlen(new_name)))
3843 return 0;
3844
3845 return EXISTS_IN_WORKTREE;
c7054209 3846 } else if (!is_missing_file_error(errno)) {
90875eca 3847 return error_errno("%s", new_name);
13b5af22
CC
3848 }
3849 return 0;
3850}
3851
13b5af22
CC
3852static void prepare_symlink_changes(struct apply_state *state, struct patch *patch)
3853{
3854 for ( ; patch; patch = patch->next) {
3855 if ((patch->old_name && S_ISLNK(patch->old_mode)) &&
3856 (patch->is_rename || patch->is_delete))
3857 /* the symlink at patch->old_name is removed */
4e9a3252 3858 strset_add(&state->removed_symlinks, patch->old_name);
13b5af22
CC
3859
3860 if (patch->new_name && S_ISLNK(patch->new_mode))
3861 /* the symlink at patch->new_name is created or remains */
4e9a3252 3862 strset_add(&state->kept_symlinks, patch->new_name);
13b5af22
CC
3863 }
3864}
3865
3866static int path_is_beyond_symlink_1(struct apply_state *state, struct strbuf *name)
3867{
3868 do {
13b5af22
CC
3869 while (--name->len && name->buf[name->len] != '/')
3870 ; /* scan backwards */
3871 if (!name->len)
3872 break;
3873 name->buf[name->len] = '\0';
4e9a3252 3874 if (strset_contains(&state->kept_symlinks, name->buf))
13b5af22 3875 return 1;
4e9a3252 3876 if (strset_contains(&state->removed_symlinks, name->buf))
13b5af22
CC
3877 /*
3878 * This cannot be "return 0", because we may
3879 * see a new one created at a higher level.
3880 */
3881 continue;
3882
3883 /* otherwise, check the preimage */
3884 if (state->check_index) {
3885 struct cache_entry *ce;
3886
1b5c6c1e
NTND
3887 ce = index_file_exists(state->repo->index, name->buf,
3888 name->len, ignore_case);
13b5af22
CC
3889 if (ce && S_ISLNK(ce->ce_mode))
3890 return 1;
3891 } else {
3892 struct stat st;
3893 if (!lstat(name->buf, &st) && S_ISLNK(st.st_mode))
3894 return 1;
3895 }
3896 } while (1);
3897 return 0;
3898}
3899
3900static int path_is_beyond_symlink(struct apply_state *state, const char *name_)
3901{
3902 int ret;
3903 struct strbuf name = STRBUF_INIT;
3904
3905 assert(*name_ != '\0');
3906 strbuf_addstr(&name, name_);
3907 ret = path_is_beyond_symlink_1(state, &name);
3908 strbuf_release(&name);
3909
3910 return ret;
3911}
3912
3913static int check_unsafe_path(struct patch *patch)
3914{
3915 const char *old_name = NULL;
3916 const char *new_name = NULL;
3917 if (patch->is_delete)
3918 old_name = patch->old_name;
3919 else if (!patch->is_new && !patch->is_copy)
3920 old_name = patch->old_name;
3921 if (!patch->is_delete)
3922 new_name = patch->new_name;
3923
10ecfa76 3924 if (old_name && !verify_path(old_name, patch->old_mode))
13b5af22 3925 return error(_("invalid path '%s'"), old_name);
10ecfa76 3926 if (new_name && !verify_path(new_name, patch->new_mode))
13b5af22
CC
3927 return error(_("invalid path '%s'"), new_name);
3928 return 0;
3929}
3930
3931/*
3932 * Check and apply the patch in-core; leave the result in patch->result
3933 * for the caller to write it out to the final destination.
3934 */
3935static int check_patch(struct apply_state *state, struct patch *patch)
3936{
3937 struct stat st;
3938 const char *old_name = patch->old_name;
3939 const char *new_name = patch->new_name;
3940 const char *name = old_name ? old_name : new_name;
3941 struct cache_entry *ce = NULL;
3942 struct patch *tpatch;
3943 int ok_if_exists;
3944 int status;
3945
3946 patch->rejected = 1; /* we will drop this after we succeed */
3947
3948 status = check_preimage(state, patch, &ce, &st);
3949 if (status)
3950 return status;
3951 old_name = patch->old_name;
3952
3953 /*
3954 * A type-change diff is always split into a patch to delete
3955 * old, immediately followed by a patch to create new (see
3956 * diff.c::run_diff()); in such a case it is Ok that the entry
3957 * to be deleted by the previous patch is still in the working
3958 * tree and in the index.
3959 *
3960 * A patch to swap-rename between A and B would first rename A
3961 * to B and then rename B to A. While applying the first one,
3962 * the presence of B should not stop A from getting renamed to
3963 * B; ask to_be_deleted() about the later rename. Removal of
3964 * B and rename from A to B is handled the same way by asking
3965 * was_deleted().
3966 */
3967 if ((tpatch = in_fn_table(state, new_name)) &&
3968 (was_deleted(tpatch) || to_be_deleted(tpatch)))
3969 ok_if_exists = 1;
3970 else
3971 ok_if_exists = 0;
3972
3973 if (new_name &&
3974 ((0 < patch->is_new) || patch->is_rename || patch->is_copy)) {
3975 int err = check_to_create(state, new_name, ok_if_exists);
3976
3977 if (err && state->threeway) {
3978 patch->direct_to_threeway = 1;
3979 } else switch (err) {
3980 case 0:
3981 break; /* happy */
3982 case EXISTS_IN_INDEX:
3983 return error(_("%s: already exists in index"), new_name);
e3cc41b4
RP
3984 case EXISTS_IN_INDEX_AS_ITA:
3985 return error(_("%s: does not match index"), new_name);
13b5af22
CC
3986 case EXISTS_IN_WORKTREE:
3987 return error(_("%s: already exists in working directory"),
3988 new_name);
3989 default:
3990 return err;
3991 }
3992
3993 if (!patch->new_mode) {
3994 if (0 < patch->is_new)
3995 patch->new_mode = S_IFREG | 0644;
3996 else
3997 patch->new_mode = patch->old_mode;
3998 }
3999 }
4000
4001 if (new_name && old_name) {
4002 int same = !strcmp(old_name, new_name);
4003 if (!patch->new_mode)
4004 patch->new_mode = patch->old_mode;
4005 if ((patch->old_mode ^ patch->new_mode) & S_IFMT) {
4006 if (same)
4007 return error(_("new mode (%o) of %s does not "
4008 "match old mode (%o)"),
4009 patch->new_mode, new_name,
4010 patch->old_mode);
4011 else
4012 return error(_("new mode (%o) of %s does not "
4013 "match old mode (%o) of %s"),
4014 patch->new_mode, new_name,
4015 patch->old_mode, old_name);
4016 }
4017 }
4018
4019 if (!state->unsafe_paths && check_unsafe_path(patch))
4020 return -128;
4021
4022 /*
4023 * An attempt to read from or delete a path that is beyond a
4024 * symbolic link will be prevented by load_patch_target() that
4025 * is called at the beginning of apply_data() so we do not
4026 * have to worry about a patch marked with "is_delete" bit
4027 * here. We however need to make sure that the patch result
4028 * is not deposited to a path that is beyond a symbolic link
4029 * here.
4030 */
4031 if (!patch->is_delete && path_is_beyond_symlink(state, patch->new_name))
4032 return error(_("affected file '%s' is beyond a symbolic link"),
4033 patch->new_name);
4034
4035 if (apply_data(state, patch, &st, ce) < 0)
4036 return error(_("%s: patch does not apply"), name);
4037 patch->rejected = 0;
4038 return 0;
4039}
4040
4041static int check_patch_list(struct apply_state *state, struct patch *patch)
4042{
4043 int err = 0;
4044
4045 prepare_symlink_changes(state, patch);
4046 prepare_fn_table(state, patch);
4047 while (patch) {
4048 int res;
a46160d2 4049 if (state->apply_verbosity > verbosity_normal)
13b5af22
CC
4050 say_patch_name(stderr,
4051 _("Checking patch %s..."), patch);
4052 res = check_patch(state, patch);
4053 if (res == -128)
4054 return -128;
4055 err |= res;
4056 patch = patch->next;
4057 }
4058 return err;
4059}
4060
5b0b57fd
CC
4061static int read_apply_cache(struct apply_state *state)
4062{
4063 if (state->index_file)
1b5c6c1e
NTND
4064 return read_index_from(state->repo->index, state->index_file,
4065 get_git_dir());
5b0b57fd 4066 else
e1ff0a32 4067 return repo_read_index(state->repo);
5b0b57fd
CC
4068}
4069
4af9a7d3
JH
4070/* This function tries to read the object name from the current index */
4071static int get_current_oid(struct apply_state *state, const char *path,
4072 struct object_id *oid)
13b5af22
CC
4073{
4074 int pos;
4075
5b0b57fd 4076 if (read_apply_cache(state) < 0)
13b5af22 4077 return -1;
1b5c6c1e 4078 pos = index_name_pos(state->repo->index, path, strlen(path));
13b5af22
CC
4079 if (pos < 0)
4080 return -1;
1b5c6c1e 4081 oidcpy(oid, &state->repo->index->cache[pos]->oid);
13b5af22
CC
4082 return 0;
4083}
4084
4af9a7d3 4085static int preimage_oid_in_gitlink_patch(struct patch *p, struct object_id *oid)
13b5af22
CC
4086{
4087 /*
4088 * A usable gitlink patch has only one fragment (hunk) that looks like:
4089 * @@ -1 +1 @@
4090 * -Subproject commit <old sha1>
4091 * +Subproject commit <new sha1>
4092 * or
4093 * @@ -1 +0,0 @@
4094 * -Subproject commit <old sha1>
4095 * for a removal patch.
4096 */
4097 struct fragment *hunk = p->fragments;
4098 static const char heading[] = "-Subproject commit ";
4099 char *preimage;
4100
4101 if (/* does the patch have only one hunk? */
4102 hunk && !hunk->next &&
4103 /* is its preimage one line? */
4104 hunk->oldpos == 1 && hunk->oldlines == 1 &&
4105 /* does preimage begin with the heading? */
4106 (preimage = memchr(hunk->patch, '\n', hunk->size)) != NULL &&
4107 starts_with(++preimage, heading) &&
4108 /* does it record full SHA-1? */
4af9a7d3 4109 !get_oid_hex(preimage + sizeof(heading) - 1, oid) &&
93eb00f7 4110 preimage[sizeof(heading) + the_hash_algo->hexsz - 1] == '\n' &&
13b5af22 4111 /* does the abbreviated name on the index line agree with it? */
eccb5a5f 4112 starts_with(preimage + sizeof(heading) - 1, p->old_oid_prefix))
13b5af22
CC
4113 return 0; /* it all looks fine */
4114
4115 /* we may have full object name on the index line */
eccb5a5f 4116 return get_oid_hex(p->old_oid_prefix, oid);
13b5af22
CC
4117}
4118
59caacab 4119/* Build an index that contains just the files needed for a 3way merge */
b4290342 4120static int build_fake_ancestor(struct apply_state *state, struct patch *list)
13b5af22
CC
4121{
4122 struct patch *patch;
6269f8ea 4123 struct index_state result = INDEX_STATE_INIT(state->repo);
b2275868 4124 struct lock_file lock = LOCK_INIT;
13b5af22
CC
4125 int res;
4126
4127 /* Once we start supporting the reverse patch, it may be
4128 * worth showing the new sha1 prefix, but until then...
4129 */
4130 for (patch = list; patch; patch = patch->next) {
4af9a7d3 4131 struct object_id oid;
13b5af22
CC
4132 struct cache_entry *ce;
4133 const char *name;
4134
4135 name = patch->old_name ? patch->old_name : patch->new_name;
4136 if (0 < patch->is_new)
4137 continue;
4138
4139 if (S_ISGITLINK(patch->old_mode)) {
4af9a7d3 4140 if (!preimage_oid_in_gitlink_patch(patch, &oid))
13b5af22
CC
4141 ; /* ok, the textual part looks sane */
4142 else
d1d42bf5
VA
4143 return error(_("sha1 information is lacking or "
4144 "useless for submodule %s"), name);
d850b7a5 4145 } else if (!repo_get_oid_blob(the_repository, patch->old_oid_prefix, &oid)) {
13b5af22
CC
4146 ; /* ok */
4147 } else if (!patch->lines_added && !patch->lines_deleted) {
4148 /* mode-only change: update the current */
4af9a7d3 4149 if (get_current_oid(state, patch->old_name, &oid))
d1d42bf5
VA
4150 return error(_("mode change for %s, which is not "
4151 "in current HEAD"), name);
13b5af22 4152 } else
d1d42bf5
VA
4153 return error(_("sha1 information is lacking or useless "
4154 "(%s)."), name);
13b5af22 4155
a849735b 4156 ce = make_cache_entry(&result, patch->old_mode, &oid, name, 0, 0);
13b5af22
CC
4157 if (!ce)
4158 return error(_("make_cache_entry failed for path '%s'"),
4159 name);
4160 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) {
a849735b 4161 discard_cache_entry(ce);
d1d42bf5 4162 return error(_("could not add %s to temporary index"),
13b5af22
CC
4163 name);
4164 }
4165 }
4166
b4290342 4167 hold_lock_file_for_update(&lock, state->fake_ancestor, LOCK_DIE_ON_ERROR);
13b5af22
CC
4168 res = write_locked_index(&result, &lock, COMMIT_LOCK);
4169 discard_index(&result);
4170
e294e895
JH
4171 if (res)
4172 return error(_("could not write temporary index to %s"),
4173 state->fake_ancestor);
13b5af22 4174
e294e895
JH
4175 return 0;
4176}
13b5af22 4177
e294e895
JH
4178static void stat_patch_list(struct apply_state *state, struct patch *patch)
4179{
4180 int files, adds, dels;
13b5af22 4181
e294e895
JH
4182 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
4183 files++;
4184 adds += patch->lines_added;
4185 dels += patch->lines_deleted;
4186 show_stats(state, patch);
4187 }
13b5af22 4188
e294e895
JH
4189 print_stat_summary(stdout, files, adds, dels);
4190}
13b5af22 4191
e294e895
JH
4192static void numstat_patch_list(struct apply_state *state,
4193 struct patch *patch)
4194{
4195 for ( ; patch; patch = patch->next) {
4196 const char *name;
4197 name = patch->new_name ? patch->new_name : patch->old_name;
4198 if (patch->is_binary)
4199 printf("-\t-\t");
4200 else
4201 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
4202 write_name_quoted(name, stdout, state->line_termination);
4203 }
4204}
4205
4206static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
4207{
4208 if (mode)
4209 printf(" %s mode %06o %s\n", newdelete, mode, name);
4210 else
4211 printf(" %s %s\n", newdelete, name);
4212}
4213
4214static void show_mode_change(struct patch *p, int show_name)
4215{
4216 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
4217 if (show_name)
4218 printf(" mode change %06o => %06o %s\n",
4219 p->old_mode, p->new_mode, p->new_name);
4220 else
4221 printf(" mode change %06o => %06o\n",
4222 p->old_mode, p->new_mode);
4223 }
4224}
4225
4226static void show_rename_copy(struct patch *p)
4227{
4228 const char *renamecopy = p->is_rename ? "rename" : "copy";
f1ae97d3 4229 const char *old_name, *new_name;
e294e895
JH
4230
4231 /* Find common prefix */
f1ae97d3
BW
4232 old_name = p->old_name;
4233 new_name = p->new_name;
e294e895
JH
4234 while (1) {
4235 const char *slash_old, *slash_new;
f1ae97d3
BW
4236 slash_old = strchr(old_name, '/');
4237 slash_new = strchr(new_name, '/');
e294e895
JH
4238 if (!slash_old ||
4239 !slash_new ||
f1ae97d3
BW
4240 slash_old - old_name != slash_new - new_name ||
4241 memcmp(old_name, new_name, slash_new - new_name))
e294e895 4242 break;
f1ae97d3
BW
4243 old_name = slash_old + 1;
4244 new_name = slash_new + 1;
e294e895 4245 }
15beaaa3
EN
4246 /* p->old_name through old_name is the common prefix, and old_name and
4247 * new_name through the end of names are renames
e294e895 4248 */
f1ae97d3 4249 if (old_name != p->old_name)
e294e895 4250 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
f1ae97d3
BW
4251 (int)(old_name - p->old_name), p->old_name,
4252 old_name, new_name, p->score);
e294e895
JH
4253 else
4254 printf(" %s %s => %s (%d%%)\n", renamecopy,
4255 p->old_name, p->new_name, p->score);
4256 show_mode_change(p, 0);
4257}
4258
4259static void summary_patch_list(struct patch *patch)
4260{
4261 struct patch *p;
4262
4263 for (p = patch; p; p = p->next) {
4264 if (p->is_new)
4265 show_file_mode_name("create", p->new_mode, p->new_name);
4266 else if (p->is_delete)
4267 show_file_mode_name("delete", p->old_mode, p->old_name);
4268 else {
4269 if (p->is_rename || p->is_copy)
4270 show_rename_copy(p);
4271 else {
4272 if (p->score) {
4273 printf(" rewrite %s (%d%%)\n",
4274 p->new_name, p->score);
4275 show_mode_change(p, 0);
4276 }
4277 else
4278 show_mode_change(p, 1);
4279 }
4280 }
4281 }
4282}
4283
4284static void patch_stats(struct apply_state *state, struct patch *patch)
4285{
4286 int lines = patch->lines_added + patch->lines_deleted;
4287
4288 if (lines > state->max_change)
4289 state->max_change = lines;
4290 if (patch->old_name) {
4291 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
4292 if (!len)
4293 len = strlen(patch->old_name);
4294 if (len > state->max_len)
4295 state->max_len = len;
4296 }
4297 if (patch->new_name) {
4298 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
4299 if (!len)
4300 len = strlen(patch->new_name);
4301 if (len > state->max_len)
4302 state->max_len = len;
4303 }
4304}
4305
4306static int remove_file(struct apply_state *state, struct patch *patch, int rmdir_empty)
4307{
cff5dc09 4308 if (state->update_index && !state->ita_only) {
1b5c6c1e 4309 if (remove_file_from_index(state->repo->index, patch->old_name) < 0)
e294e895
JH
4310 return error(_("unable to remove %s from index"), patch->old_name);
4311 }
4312 if (!state->cached) {
4313 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
4314 remove_path(patch->old_name);
4315 }
4316 }
4317 return 0;
4318}
4319
4320static int add_index_file(struct apply_state *state,
4321 const char *path,
4322 unsigned mode,
4323 void *buf,
4324 unsigned long size)
4325{
4326 struct stat st;
4327 struct cache_entry *ce;
4328 int namelen = strlen(path);
e294e895 4329
1b5c6c1e 4330 ce = make_empty_cache_entry(state->repo->index, namelen);
e294e895
JH
4331 memcpy(ce->name, path, namelen);
4332 ce->ce_mode = create_ce_mode(mode);
4333 ce->ce_flags = create_ce_flags(0);
4334 ce->ce_namelen = namelen;
cff5dc09
NTND
4335 if (state->ita_only) {
4336 ce->ce_flags |= CE_INTENT_TO_ADD;
4337 set_object_name_for_intent_to_add_entry(ce);
4338 } else if (S_ISGITLINK(mode)) {
e294e895
JH
4339 const char *s;
4340
4341 if (!skip_prefix(buf, "Subproject commit ", &s) ||
4342 get_oid_hex(s, &ce->oid)) {
a849735b
JM
4343 discard_cache_entry(ce);
4344 return error(_("corrupt patch for submodule %s"), path);
13b5af22
CC
4345 }
4346 } else {
4347 if (!state->cached) {
4348 if (lstat(path, &st) < 0) {
a849735b 4349 discard_cache_entry(ce);
90875eca
CC
4350 return error_errno(_("unable to stat newly "
4351 "created file '%s'"),
4352 path);
13b5af22 4353 }
d4c0a3ac 4354 fill_stat_cache_info(state->repo->index, ce, &st);
13b5af22 4355 }
c80d226a 4356 if (write_object_file(buf, size, OBJ_BLOB, &ce->oid) < 0) {
a849735b 4357 discard_cache_entry(ce);
13b5af22
CC
4358 return error(_("unable to create backing store "
4359 "for newly created file %s"), path);
4360 }
4361 }
1b5c6c1e 4362 if (add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) < 0) {
a849735b 4363 discard_cache_entry(ce);
13b5af22
CC
4364 return error(_("unable to add cache entry for %s"), path);
4365 }
4366
4367 return 0;
4368}
4369
4370/*
4371 * Returns:
4372 * -1 if an unrecoverable error happened
4373 * 0 if everything went well
4374 * 1 if a recoverable error happened
4375 */
332a82a5
NTND
4376static int try_create_file(struct apply_state *state, const char *path,
4377 unsigned int mode, const char *buf,
4378 unsigned long size)
13b5af22
CC
4379{
4380 int fd, res;
4381 struct strbuf nbuf = STRBUF_INIT;
4382
4383 if (S_ISGITLINK(mode)) {
4384 struct stat st;
4385 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
4386 return 0;
4387 return !!mkdir(path, 0777);
4388 }
4389
4390 if (has_symlinks && S_ISLNK(mode))
4391 /* Although buf:size is counted string, it also is NUL
4392 * terminated.
4393 */
4394 return !!symlink(buf, path);
4395
4396 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
4397 if (fd < 0)
4398 return 1;
4399
ab90ecae 4400 if (convert_to_working_tree(state->repo->index, path, buf, size, &nbuf, NULL)) {
13b5af22
CC
4401 size = nbuf.len;
4402 buf = nbuf.buf;
4403 }
4404
4405 res = write_in_full(fd, buf, size) < 0;
4406 if (res)
4407 error_errno(_("failed to write to '%s'"), path);
4408 strbuf_release(&nbuf);
4409
4410 if (close(fd) < 0 && !res)
4411 return error_errno(_("closing file '%s'"), path);
4412
4413 return res ? -1 : 0;
4414}
4415
4416/*
4417 * We optimistically assume that the directories exist,
4418 * which is true 99% of the time anyway. If they don't,
4419 * we create them and try again.
4420 *
4421 * Returns:
4422 * -1 on error
4423 * 0 otherwise
4424 */
4425static int create_one_file(struct apply_state *state,
4426 char *path,
4427 unsigned mode,
4428 const char *buf,
4429 unsigned long size)
4430{
4431 int res;
4432
4433 if (state->cached)
4434 return 0;
4435
fade728d
PS
4436 /*
4437 * We already try to detect whether files are beyond a symlink in our
4438 * up-front checks. But in the case where symlinks are created by any
4439 * of the intermediate hunks it can happen that our up-front checks
4440 * didn't yet see the symlink, but at the point of arriving here there
4441 * in fact is one. We thus repeat the check for symlinks here.
4442 *
4443 * Note that this does not make the up-front check obsolete as the
4444 * failure mode is different:
4445 *
4446 * - The up-front checks cause us to abort before we have written
4447 * anything into the working directory. So when we exit this way the
4448 * working directory remains clean.
4449 *
4450 * - The checks here happen in the middle of the action where we have
4451 * already started to apply the patch. The end result will be a dirty
4452 * working directory.
4453 *
4454 * Ideally, we should update the up-front checks to catch what would
4455 * happen when we apply the patch before we damage the working tree.
4456 * We have all the information necessary to do so. But for now, as a
4457 * part of embargoed security work, having this check would serve as a
4458 * reasonable first step.
4459 */
4460 if (path_is_beyond_symlink(state, path))
4461 return error(_("affected file '%s' is beyond a symbolic link"), path);
4462
332a82a5 4463 res = try_create_file(state, path, mode, buf, size);
13b5af22
CC
4464 if (res < 0)
4465 return -1;
4466 if (!res)
4467 return 0;
4468
4469 if (errno == ENOENT) {
eb3c027e 4470 if (safe_create_leading_directories_no_share(path))
13b5af22 4471 return 0;
332a82a5 4472 res = try_create_file(state, path, mode, buf, size);
13b5af22
CC
4473 if (res < 0)
4474 return -1;
4475 if (!res)
4476 return 0;
4477 }
4478
4479 if (errno == EEXIST || errno == EACCES) {
4480 /* We may be trying to create a file where a directory
4481 * used to be.
4482 */
4483 struct stat st;
4484 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
4485 errno = EEXIST;
4486 }
4487
4488 if (errno == EEXIST) {
4489 unsigned int nr = getpid();
4490
4491 for (;;) {
4492 char newpath[PATH_MAX];
4493 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
332a82a5 4494 res = try_create_file(state, newpath, mode, buf, size);
13b5af22
CC
4495 if (res < 0)
4496 return -1;
4497 if (!res) {
4498 if (!rename(newpath, path))
4499 return 0;
4500 unlink_or_warn(newpath);
4501 break;
4502 }
4503 if (errno != EEXIST)
4504 break;
4505 ++nr;
4506 }
4507 }
4508 return error_errno(_("unable to write file '%s' mode %o"),
4509 path, mode);
4510}
4511
4512static int add_conflicted_stages_file(struct apply_state *state,
4513 struct patch *patch)
4514{
4515 int stage, namelen;
a849735b 4516 unsigned mode;
13b5af22
CC
4517 struct cache_entry *ce;
4518
4519 if (!state->update_index)
4520 return 0;
4521 namelen = strlen(patch->new_name);
13b5af22
CC
4522 mode = patch->new_mode ? patch->new_mode : (S_IFREG | 0644);
4523
1b5c6c1e 4524 remove_file_from_index(state->repo->index, patch->new_name);
13b5af22
CC
4525 for (stage = 1; stage < 4; stage++) {
4526 if (is_null_oid(&patch->threeway_stage[stage - 1]))
4527 continue;
1b5c6c1e 4528 ce = make_empty_cache_entry(state->repo->index, namelen);
13b5af22
CC
4529 memcpy(ce->name, patch->new_name, namelen);
4530 ce->ce_mode = create_ce_mode(mode);
4531 ce->ce_flags = create_ce_flags(stage);
4532 ce->ce_namelen = namelen;
4af9a7d3 4533 oidcpy(&ce->oid, &patch->threeway_stage[stage - 1]);
1b5c6c1e 4534 if (add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) < 0) {
a849735b 4535 discard_cache_entry(ce);
13b5af22
CC
4536 return error(_("unable to add cache entry for %s"),
4537 patch->new_name);
4538 }
4539 }
4540
4541 return 0;
4542}
4543
4544static int create_file(struct apply_state *state, struct patch *patch)
4545{
4546 char *path = patch->new_name;
4547 unsigned mode = patch->new_mode;
4548 unsigned long size = patch->resultsize;
4549 char *buf = patch->result;
4550
4551 if (!mode)
4552 mode = S_IFREG | 0644;
4553 if (create_one_file(state, path, mode, buf, size))
4554 return -1;
4555
4556 if (patch->conflicted_threeway)
4557 return add_conflicted_stages_file(state, patch);
cff5dc09 4558 else if (state->update_index)
13b5af22 4559 return add_index_file(state, path, mode, buf, size);
cff5dc09 4560 return 0;
13b5af22
CC
4561}
4562
4563/* phase zero is to remove, phase one is to create */
4564static int write_out_one_result(struct apply_state *state,
4565 struct patch *patch,
4566 int phase)
4567{
4568 if (patch->is_delete > 0) {
4569 if (phase == 0)
4570 return remove_file(state, patch, 1);
4571 return 0;
4572 }
4573 if (patch->is_new > 0 || patch->is_copy) {
4574 if (phase == 1)
4575 return create_file(state, patch);
4576 return 0;
4577 }
4578 /*
4579 * Rename or modification boils down to the same
4580 * thing: remove the old, write the new
4581 */
4582 if (phase == 0)
4583 return remove_file(state, patch, patch->is_rename);
4584 if (phase == 1)
4585 return create_file(state, patch);
4586 return 0;
4587}
4588
4589static int write_out_one_reject(struct apply_state *state, struct patch *patch)
4590{
4591 FILE *rej;
4592 char namebuf[PATH_MAX];
4593 struct fragment *frag;
9db05711 4594 int fd, cnt = 0;
13b5af22
CC
4595 struct strbuf sb = STRBUF_INIT;
4596
4597 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
4598 if (!frag->rejected)
4599 continue;
4600 cnt++;
4601 }
4602
4603 if (!cnt) {
a46160d2 4604 if (state->apply_verbosity > verbosity_normal)
13b5af22
CC
4605 say_patch_name(stderr,
4606 _("Applied patch %s cleanly."), patch);
4607 return 0;
4608 }
4609
4610 /* This should not happen, because a removal patch that leaves
4611 * contents are marked "rejected" at the patch level.
4612 */
4613 if (!patch->new_name)
4614 die(_("internal error"));
4615
4616 /* Say this even without --verbose */
4617 strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",
4618 "Applying patch %%s with %d rejects...",
4619 cnt),
4620 cnt);
a46160d2
CC
4621 if (state->apply_verbosity > verbosity_silent)
4622 say_patch_name(stderr, sb.buf, patch);
13b5af22
CC
4623 strbuf_release(&sb);
4624
4625 cnt = strlen(patch->new_name);
4626 if (ARRAY_SIZE(namebuf) <= cnt + 5) {
4627 cnt = ARRAY_SIZE(namebuf) - 5;
4628 warning(_("truncating .rej filename to %.*s.rej"),
4629 cnt - 1, patch->new_name);
4630 }
4631 memcpy(namebuf, patch->new_name, cnt);
4632 memcpy(namebuf + cnt, ".rej", 5);
4633
9db05711
JS
4634 fd = open(namebuf, O_CREAT | O_EXCL | O_WRONLY, 0666);
4635 if (fd < 0) {
4636 if (errno != EEXIST)
4637 return error_errno(_("cannot open %s"), namebuf);
4638 if (unlink(namebuf))
4639 return error_errno(_("cannot unlink '%s'"), namebuf);
4640 fd = open(namebuf, O_CREAT | O_EXCL | O_WRONLY, 0666);
4641 if (fd < 0)
4642 return error_errno(_("cannot open %s"), namebuf);
4643 }
4644 rej = fdopen(fd, "w");
13b5af22 4645 if (!rej)
90875eca 4646 return error_errno(_("cannot open %s"), namebuf);
13b5af22
CC
4647
4648 /* Normal git tools never deal with .rej, so do not pretend
4649 * this is a git patch by saying --git or giving extended
4650 * headers. While at it, maybe please "kompare" that wants
4651 * the trailing TAB and some garbage at the end of line ;-).
4652 */
4653 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
4654 patch->new_name, patch->new_name);
4655 for (cnt = 1, frag = patch->fragments;
4656 frag;
4657 cnt++, frag = frag->next) {
4658 if (!frag->rejected) {
a46160d2
CC
4659 if (state->apply_verbosity > verbosity_silent)
4660 fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);
13b5af22
CC
4661 continue;
4662 }
a46160d2
CC
4663 if (state->apply_verbosity > verbosity_silent)
4664 fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);
13b5af22
CC
4665 fprintf(rej, "%.*s", frag->size, frag->patch);
4666 if (frag->patch[frag->size-1] != '\n')
4667 fputc('\n', rej);
4668 }
4669 fclose(rej);
4670 return -1;
4671}
4672
4673/*
4674 * Returns:
4675 * -1 if an error happened
4676 * 0 if the patch applied cleanly
4677 * 1 if the patch did not apply cleanly
4678 */
4679static int write_out_results(struct apply_state *state, struct patch *list)
4680{
4681 int phase;
4682 int errs = 0;
4683 struct patch *l;
4684 struct string_list cpath = STRING_LIST_INIT_DUP;
4685
4686 for (phase = 0; phase < 2; phase++) {
4687 l = list;
4688 while (l) {
4689 if (l->rejected)
4690 errs = 1;
4691 else {
4692 if (write_out_one_result(state, l, phase)) {
4693 string_list_clear(&cpath, 0);
4694 return -1;
4695 }
4696 if (phase == 1) {
4697 if (write_out_one_reject(state, l))
4698 errs = 1;
4699 if (l->conflicted_threeway) {
4700 string_list_append(&cpath, l->new_name);
4701 errs = 1;
4702 }
4703 }
4704 }
4705 l = l->next;
4706 }
4707 }
4708
4709 if (cpath.nr) {
4710 struct string_list_item *item;
4711
4712 string_list_sort(&cpath);
a46160d2
CC
4713 if (state->apply_verbosity > verbosity_silent) {
4714 for_each_string_list_item(item, &cpath)
4715 fprintf(stderr, "U %s\n", item->string);
4716 }
13b5af22
CC
4717 string_list_clear(&cpath, 0);
4718
c0c2a37a
JZ
4719 /*
4720 * rerere relies on the partially merged result being in the working
4721 * tree with conflict markers, but that isn't written with --cached.
4722 */
4723 if (!state->cached)
4724 repo_rerere(state->repo, 0);
13b5af22
CC
4725 }
4726
4727 return errs;
4728}
4729
4730/*
4731 * Try to apply a patch.
4732 *
4733 * Returns:
4734 * -128 if a bad error happened (like patch unreadable)
4735 * -1 if patch did not apply and user cannot deal with it
4736 * 0 if the patch applied
4737 * 1 if the patch did not apply but user might fix it
4738 */
4739static int apply_patch(struct apply_state *state,
4740 int fd,
4741 const char *filename,
4742 int options)
4743{
4744 size_t offset;
4745 struct strbuf buf = STRBUF_INIT; /* owns the patch text */
4746 struct patch *list = NULL, **listp = &list;
4747 int skipped_patch = 0;
4748 int res = 0;
2c65d90f 4749 int flush_attributes = 0;
13b5af22
CC
4750
4751 state->patch_input_file = filename;
4752 if (read_patch_file(&buf, fd) < 0)
4753 return -128;
4754 offset = 0;
4755 while (offset < buf.len) {
4756 struct patch *patch;
4757 int nr;
4758
ca56dadb 4759 CALLOC_ARRAY(patch, 1);
13b5af22
CC
4760 patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF);
4761 patch->recount = !!(options & APPLY_OPT_RECOUNT);
4762 nr = parse_chunk(state, buf.buf + offset, buf.len - offset, patch);
4763 if (nr < 0) {
4764 free_patch(patch);
4765 if (nr == -128) {
4766 res = -128;
4767 goto end;
4768 }
4769 break;
4770 }
4771 if (state->apply_in_reverse)
4772 reverse_patches(patch);
4773 if (use_patch(state, patch)) {
4774 patch_stats(state, patch);
b0f266de
JT
4775 if (!list || !state->apply_in_reverse) {
4776 *listp = patch;
4777 listp = &patch->next;
4778 } else {
4779 patch->next = list;
4780 list = patch;
4781 }
2c65d90f 4782
4783 if ((patch->new_name &&
4784 ends_with_path_components(patch->new_name,
4785 GITATTRIBUTES_FILE)) ||
4786 (patch->old_name &&
4787 ends_with_path_components(patch->old_name,
4788 GITATTRIBUTES_FILE)))
4789 flush_attributes = 1;
13b5af22
CC
4790 }
4791 else {
a46160d2 4792 if (state->apply_verbosity > verbosity_normal)
13b5af22
CC
4793 say_patch_name(stderr, _("Skipped patch '%s'."), patch);
4794 free_patch(patch);
4795 skipped_patch++;
4796 }
4797 offset += nr;
4798 }
4799
4800 if (!list && !skipped_patch) {
324eb77e
JZ
4801 if (!state->allow_empty) {
4802 error(_("No valid patches in input (allow with \"--allow-empty\")"));
4803 res = -128;
4804 }
13b5af22
CC
4805 goto end;
4806 }
4807
4808 if (state->whitespace_error && (state->ws_error_action == die_on_ws_error))
4809 state->apply = 0;
4810
cff5dc09 4811 state->update_index = (state->check_index || state->ita_only) && state->apply;
d13cd4c9 4812 if (state->update_index && !is_lock_file_locked(&state->lock_file)) {
5b0b57fd 4813 if (state->index_file)
d13cd4c9
4814 hold_lock_file_for_update(&state->lock_file,
4815 state->index_file,
4816 LOCK_DIE_ON_ERROR);
5b0b57fd 4817 else
3a95f31d
NTND
4818 repo_hold_locked_index(state->repo, &state->lock_file,
4819 LOCK_DIE_ON_ERROR);
5b0b57fd 4820 }
13b5af22 4821
5b0b57fd 4822 if (state->check_index && read_apply_cache(state) < 0) {
13b5af22
CC
4823 error(_("unable to read index file"));
4824 res = -128;
4825 goto end;
4826 }
4827
4828 if (state->check || state->apply) {
4829 int r = check_patch_list(state, list);
4830 if (r == -128) {
4831 res = -128;
4832 goto end;
4833 }
4834 if (r < 0 && !state->apply_with_reject) {
4835 res = -1;
4836 goto end;
4837 }
4838 }
4839
4840 if (state->apply) {
4841 int write_res = write_out_results(state, list);
4842 if (write_res < 0) {
4843 res = -128;
4844 goto end;
4845 }
4846 if (write_res > 0) {
4847 /* with --3way, we still need to write the index out */
4848 res = state->apply_with_reject ? -1 : 1;
4849 goto end;
4850 }
4851 }
4852
4853 if (state->fake_ancestor &&
b4290342 4854 build_fake_ancestor(state, list)) {
13b5af22
CC
4855 res = -128;
4856 goto end;
4857 }
4858
487beee0 4859 if (state->diffstat && state->apply_verbosity > verbosity_silent)
13b5af22
CC
4860 stat_patch_list(state, list);
4861
487beee0 4862 if (state->numstat && state->apply_verbosity > verbosity_silent)
13b5af22
CC
4863 numstat_patch_list(state, list);
4864
487beee0 4865 if (state->summary && state->apply_verbosity > verbosity_silent)
13b5af22
CC
4866 summary_patch_list(list);
4867
2c65d90f 4868 if (flush_attributes)
4869 reset_parsed_attributes();
13b5af22
CC
4870end:
4871 free_patch_list(list);
4872 strbuf_release(&buf);
4873 string_list_clear(&state->fn_table, 0);
4874 return res;
4875}
4876
7e1bad24
CC
4877static int apply_option_parse_exclude(const struct option *opt,
4878 const char *arg, int unset)
13b5af22
CC
4879{
4880 struct apply_state *state = opt->value;
517fe807
JK
4881
4882 BUG_ON_OPT_NEG(unset);
4883
13b5af22
CC
4884 add_name_limit(state, arg, 1);
4885 return 0;
4886}
4887
7e1bad24
CC
4888static int apply_option_parse_include(const struct option *opt,
4889 const char *arg, int unset)
13b5af22
CC
4890{
4891 struct apply_state *state = opt->value;
517fe807
JK
4892
4893 BUG_ON_OPT_NEG(unset);
4894
13b5af22
CC
4895 add_name_limit(state, arg, 0);
4896 state->has_include = 1;
4897 return 0;
4898}
4899
7e1bad24
CC
4900static int apply_option_parse_p(const struct option *opt,
4901 const char *arg,
4902 int unset)
13b5af22
CC
4903{
4904 struct apply_state *state = opt->value;
517fe807
JK
4905
4906 BUG_ON_OPT_NEG(unset);
4907
13b5af22
CC
4908 state->p_value = atoi(arg);
4909 state->p_value_known = 1;
4910 return 0;
4911}
4912
7e1bad24
CC
4913static int apply_option_parse_space_change(const struct option *opt,
4914 const char *arg, int unset)
13b5af22
CC
4915{
4916 struct apply_state *state = opt->value;
517fe807
JK
4917
4918 BUG_ON_OPT_ARG(arg);
4919
13b5af22
CC
4920 if (unset)
4921 state->ws_ignore_action = ignore_ws_none;
4922 else
4923 state->ws_ignore_action = ignore_ws_change;
4924 return 0;
4925}
4926
7e1bad24
CC
4927static int apply_option_parse_whitespace(const struct option *opt,
4928 const char *arg, int unset)
13b5af22
CC
4929{
4930 struct apply_state *state = opt->value;
517fe807
JK
4931
4932 BUG_ON_OPT_NEG(unset);
4933
13b5af22
CC
4934 state->whitespace_option = arg;
4935 if (parse_whitespace_option(state, arg))
735ca208 4936 return -1;
13b5af22
CC
4937 return 0;
4938}
4939
7e1bad24
CC
4940static int apply_option_parse_directory(const struct option *opt,
4941 const char *arg, int unset)
13b5af22
CC
4942{
4943 struct apply_state *state = opt->value;
517fe807
JK
4944
4945 BUG_ON_OPT_NEG(unset);
4946
13b5af22
CC
4947 strbuf_reset(&state->root);
4948 strbuf_addstr(&state->root, arg);
4949 strbuf_complete(&state->root, '/');
4950 return 0;
4951}
4952
4953int apply_all_patches(struct apply_state *state,
4954 int argc,
4955 const char **argv,
4956 int options)
4957{
4958 int i;
4959 int res;
4960 int errs = 0;
4961 int read_stdin = 1;
4962
4963 for (i = 0; i < argc; i++) {
4964 const char *arg = argv[i];
e4da43b1 4965 char *to_free = NULL;
13b5af22
CC
4966 int fd;
4967
4968 if (!strcmp(arg, "-")) {
4969 res = apply_patch(state, 0, "<stdin>", options);
4970 if (res < 0)
4971 goto end;
4972 errs |= res;
4973 read_stdin = 0;
4974 continue;
e4da43b1
JK
4975 } else
4976 arg = to_free = prefix_filename(state->prefix, arg);
13b5af22
CC
4977
4978 fd = open(arg, O_RDONLY);
4979 if (fd < 0) {
4980 error(_("can't open patch '%s': %s"), arg, strerror(errno));
4981 res = -128;
e4da43b1 4982 free(to_free);
13b5af22
CC
4983 goto end;
4984 }
4985 read_stdin = 0;
4986 set_default_whitespace_mode(state);
4987 res = apply_patch(state, fd, arg, options);
4988 close(fd);
e4da43b1 4989 free(to_free);
13b5af22
CC
4990 if (res < 0)
4991 goto end;
4992 errs |= res;
4993 }
4994 set_default_whitespace_mode(state);
4995 if (read_stdin) {
4996 res = apply_patch(state, 0, "<stdin>", options);
4997 if (res < 0)
4998 goto end;
4999 errs |= res;
5000 }
5001
5002 if (state->whitespace_error) {
5003 if (state->squelch_whitespace_errors &&
5004 state->squelch_whitespace_errors < state->whitespace_error) {
5005 int squelched =
5006 state->whitespace_error - state->squelch_whitespace_errors;
5007 warning(Q_("squelched %d whitespace error",
5008 "squelched %d whitespace errors",
5009 squelched),
5010 squelched);
5011 }
5012 if (state->ws_error_action == die_on_ws_error) {
5013 error(Q_("%d line adds whitespace errors.",
5014 "%d lines add whitespace errors.",
5015 state->whitespace_error),
5016 state->whitespace_error);
5017 res = -128;
5018 goto end;
5019 }
5020 if (state->applied_after_fixing_ws && state->apply)
965d5c85
VA
5021 warning(Q_("%d line applied after"
5022 " fixing whitespace errors.",
5023 "%d lines applied after"
5024 " fixing whitespace errors.",
5025 state->applied_after_fixing_ws),
5026 state->applied_after_fixing_ws);
13b5af22
CC
5027 else if (state->whitespace_error)
5028 warning(Q_("%d line adds whitespace errors.",
5029 "%d lines add whitespace errors.",
5030 state->whitespace_error),
5031 state->whitespace_error);
5032 }
5033
5034 if (state->update_index) {
1b5c6c1e 5035 res = write_locked_index(state->repo->index, &state->lock_file, COMMIT_LOCK);
13b5af22
CC
5036 if (res) {
5037 error(_("Unable to write new index file"));
5038 res = -128;
5039 goto end;
5040 }
13b5af22
CC
5041 }
5042
45b78d8b 5043 res = !!errs;
13b5af22
CC
5044
5045end:
d13cd4c9 5046 rollback_lock_file(&state->lock_file);
13b5af22 5047
45b78d8b
CC
5048 if (state->apply_verbosity <= verbosity_silent) {
5049 set_error_routine(state->saved_error_routine);
5050 set_warn_routine(state->saved_warn_routine);
5051 }
5052
5053 if (res > -1)
5054 return res;
13b5af22
CC
5055 return (res == -1 ? 1 : 128);
5056}
7e1bad24
CC
5057
5058int apply_parse_options(int argc, const char **argv,
5059 struct apply_state *state,
5060 int *force_apply, int *options,
5061 const char * const *apply_usage)
5062{
5063 struct option builtin_apply_options[] = {
203c8533 5064 OPT_CALLBACK_F(0, "exclude", state, N_("path"),
7e1bad24 5065 N_("don't apply changes matching the given path"),
203c8533
DL
5066 PARSE_OPT_NONEG, apply_option_parse_exclude),
5067 OPT_CALLBACK_F(0, "include", state, N_("path"),
7e1bad24 5068 N_("apply changes matching the given path"),
203c8533
DL
5069 PARSE_OPT_NONEG, apply_option_parse_include),
5070 OPT_CALLBACK('p', NULL, state, N_("num"),
7e1bad24 5071 N_("remove <num> leading slashes from traditional diff paths"),
203c8533 5072 apply_option_parse_p),
7e1bad24
CC
5073 OPT_BOOL(0, "no-add", &state->no_add,
5074 N_("ignore additions made by the patch")),
5075 OPT_BOOL(0, "stat", &state->diffstat,
5076 N_("instead of applying the patch, output diffstat for the input")),
5077 OPT_NOOP_NOARG(0, "allow-binary-replacement"),
5078 OPT_NOOP_NOARG(0, "binary"),
5079 OPT_BOOL(0, "numstat", &state->numstat,
5080 N_("show number of added and deleted lines in decimal notation")),
5081 OPT_BOOL(0, "summary", &state->summary,
5082 N_("instead of applying the patch, output a summary for the input")),
5083 OPT_BOOL(0, "check", &state->check,
5084 N_("instead of applying the patch, see if the patch is applicable")),
5085 OPT_BOOL(0, "index", &state->check_index,
5086 N_("make sure the patch is applicable to the current index")),
cff5dc09
NTND
5087 OPT_BOOL('N', "intent-to-add", &state->ita_only,
5088 N_("mark new files with `git add --intent-to-add`")),
7e1bad24
CC
5089 OPT_BOOL(0, "cached", &state->cached,
5090 N_("apply a patch without touching the working tree")),
b8e9d662
NTND
5091 OPT_BOOL_F(0, "unsafe-paths", &state->unsafe_paths,
5092 N_("accept a patch that touches outside the working area"),
5093 PARSE_OPT_NOCOMPLETE),
7e1bad24
CC
5094 OPT_BOOL(0, "apply", force_apply,
5095 N_("also apply the patch (use with --stat/--summary/--check)")),
5096 OPT_BOOL('3', "3way", &state->threeway,
923cd87a 5097 N_( "attempt three-way merge, fall back on normal patch if that fails")),
7e1bad24
CC
5098 OPT_FILENAME(0, "build-fake-ancestor", &state->fake_ancestor,
5099 N_("build a temporary index based on embedded index information")),
5100 /* Think twice before adding "--nul" synonym to this */
5101 OPT_SET_INT('z', NULL, &state->line_termination,
5102 N_("paths are separated with NUL character"), '\0'),
5103 OPT_INTEGER('C', NULL, &state->p_context,
5104 N_("ensure at least <n> lines of context match")),
203c8533 5105 OPT_CALLBACK(0, "whitespace", state, N_("action"),
7e1bad24 5106 N_("detect new or modified lines that have whitespace errors"),
203c8533
DL
5107 apply_option_parse_whitespace),
5108 OPT_CALLBACK_F(0, "ignore-space-change", state, NULL,
7e1bad24 5109 N_("ignore changes in whitespace when finding context"),
203c8533
DL
5110 PARSE_OPT_NOARG, apply_option_parse_space_change),
5111 OPT_CALLBACK_F(0, "ignore-whitespace", state, NULL,
7e1bad24 5112 N_("ignore changes in whitespace when finding context"),
203c8533 5113 PARSE_OPT_NOARG, apply_option_parse_space_change),
7e1bad24
CC
5114 OPT_BOOL('R', "reverse", &state->apply_in_reverse,
5115 N_("apply the patch in reverse")),
5116 OPT_BOOL(0, "unidiff-zero", &state->unidiff_zero,
5117 N_("don't expect at least one line of context")),
5118 OPT_BOOL(0, "reject", &state->apply_with_reject,
5119 N_("leave the rejected hunks in corresponding *.rej files")),
5120 OPT_BOOL(0, "allow-overlap", &state->allow_overlap,
5121 N_("allow overlapping hunks")),
c21b8ae8 5122 OPT__VERBOSITY(&state->apply_verbosity),
7e1bad24
CC
5123 OPT_BIT(0, "inaccurate-eof", options,
5124 N_("tolerate incorrectly detected missing new-line at the end of file"),
5125 APPLY_OPT_INACCURATE_EOF),
5126 OPT_BIT(0, "recount", options,
5127 N_("do not trust the line counts in the hunk headers"),
5128 APPLY_OPT_RECOUNT),
203c8533 5129 OPT_CALLBACK(0, "directory", state, N_("root"),
7e1bad24 5130 N_("prepend <root> to all filenames"),
203c8533 5131 apply_option_parse_directory),
324eb77e
JZ
5132 OPT_BOOL(0, "allow-empty", &state->allow_empty,
5133 N_("don't return error for empty patches")),
7e1bad24
CC
5134 OPT_END()
5135 };
5136
5137 return parse_options(argc, argv, state->prefix, builtin_apply_options, apply_usage, 0);
5138}