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