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