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