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