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