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