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