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