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