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