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