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