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