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 && !*patch->def_name)
1378 FREE_AND_NULL(patch->def_name);
1379
1380 if (patch->def_name && root->len) {
1381 char *s = xstrfmt("%s%s", root->buf, patch->def_name);
1382 free(patch->def_name);
1383 patch->def_name = s;
1384 }
1385
1386 line += len;
1387 size -= len;
1388 (*linenr)++;
1389 parse_hdr_state.root = root;
1390 parse_hdr_state.patch_input_file = patch_input_file;
1391 parse_hdr_state.linenr = *linenr;
1392 parse_hdr_state.p_value = p_value;
1393
1394 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, (*linenr)++) {
1395 static const struct opentry {
1396 const char *str;
1397 int (*fn)(struct gitdiff_data *, const char *, struct patch *);
1398 } optable[] = {
1399 { "@@ -", gitdiff_hdrend },
1400 { "--- ", gitdiff_oldname },
1401 { "+++ ", gitdiff_newname },
1402 { "old mode ", gitdiff_oldmode },
1403 { "new mode ", gitdiff_newmode },
1404 { "deleted file mode ", gitdiff_delete },
1405 { "new file mode ", gitdiff_newfile },
1406 { "copy from ", gitdiff_copysrc },
1407 { "copy to ", gitdiff_copydst },
1408 { "rename old ", gitdiff_renamesrc },
1409 { "rename new ", gitdiff_renamedst },
1410 { "rename from ", gitdiff_renamesrc },
1411 { "rename to ", gitdiff_renamedst },
1412 { "similarity index ", gitdiff_similarity },
1413 { "dissimilarity index ", gitdiff_dissimilarity },
1414 { "index ", gitdiff_index },
1415 { "", gitdiff_unrecognized },
1416 };
1417 int i;
1418
1419 len = linelen(line, size);
1420 if (!len || line[len-1] != '\n')
1421 break;
1422 for (i = 0; i < ARRAY_SIZE(optable); i++) {
1423 const struct opentry *p = optable + i;
1424 int oplen = strlen(p->str);
1425 int res;
1426 if (len < oplen || memcmp(p->str, line, oplen))
1427 continue;
1428 parse_hdr_state.linenr = *linenr;
1429 res = p->fn(&parse_hdr_state, line + oplen, patch);
1430 if (res < 0)
1431 return -1;
1432 if (check_header_line(*linenr, patch))
1433 return -1;
1434 if (res > 0)
1435 goto done;
1436 break;
1437 }
1438 }
1439
1440 done:
1441 if (!patch->old_name && !patch->new_name) {
1442 if (!patch->def_name) {
1443 if (patch_input_file)
1444 error(Q_("git diff header lacks filename information when removing "
1445 "%d leading pathname component at %s:%d",
1446 "git diff header lacks filename information when removing "
1447 "%d leading pathname components at %s:%d",
1448 parse_hdr_state.p_value),
1449 parse_hdr_state.p_value, patch_input_file, *linenr);
1450 else
1451 error(Q_("git diff header lacks filename information when removing "
1452 "%d leading pathname component (line %d)",
1453 "git diff header lacks filename information when removing "
1454 "%d leading pathname components (line %d)",
1455 parse_hdr_state.p_value),
1456 parse_hdr_state.p_value, *linenr);
1457 return -128;
1458 }
1459 patch->old_name = xstrdup(patch->def_name);
1460 patch->new_name = xstrdup(patch->def_name);
1461 }
1462 if ((!patch->new_name && !patch->is_delete) ||
1463 (!patch->old_name && !patch->is_new)) {
1464 if (patch_input_file)
1465 error(_("git diff header lacks filename information at %s:%d"),
1466 patch_input_file, *linenr);
1467 else
1468 error(_("git diff header lacks filename information (line %d)"),
1469 *linenr);
1470 return -128;
1471 }
1472 patch->is_toplevel_relative = 1;
1473 return offset;
1474 }
1475
1476 static int parse_num(const char *line, unsigned long *p)
1477 {
1478 char *ptr;
1479
1480 if (!isdigit(*line))
1481 return 0;
1482 errno = 0;
1483 *p = strtoul(line, &ptr, 10);
1484 if (errno)
1485 return 0;
1486 return ptr - line;
1487 }
1488
1489 static int parse_range(const char *line, int len, int offset, const char *expect,
1490 unsigned long *p1, unsigned long *p2)
1491 {
1492 int digits, ex;
1493
1494 if (offset < 0 || offset >= len)
1495 return -1;
1496 line += offset;
1497 len -= offset;
1498
1499 digits = parse_num(line, p1);
1500 if (!digits)
1501 return -1;
1502
1503 offset += digits;
1504 line += digits;
1505 len -= digits;
1506
1507 *p2 = 1;
1508 if (*line == ',') {
1509 digits = parse_num(line+1, p2);
1510 if (!digits)
1511 return -1;
1512
1513 offset += digits+1;
1514 line += digits+1;
1515 len -= digits+1;
1516 }
1517
1518 ex = strlen(expect);
1519 if (ex > len)
1520 return -1;
1521 if (memcmp(line, expect, ex))
1522 return -1;
1523
1524 return offset + ex;
1525 }
1526
1527 static void recount_diff(const char *line, int size, struct fragment *fragment)
1528 {
1529 int oldlines = 0, newlines = 0, ret = 0;
1530
1531 if (size < 1) {
1532 warning("recount: ignore empty hunk");
1533 return;
1534 }
1535
1536 for (;;) {
1537 int len = linelen(line, size);
1538 size -= len;
1539 line += len;
1540
1541 if (size < 1)
1542 break;
1543
1544 switch (*line) {
1545 case ' ': case '\n':
1546 newlines++;
1547 /* fall through */
1548 case '-':
1549 oldlines++;
1550 continue;
1551 case '+':
1552 newlines++;
1553 continue;
1554 case '\\':
1555 continue;
1556 case '@':
1557 ret = size < 3 || !starts_with(line, "@@ ");
1558 break;
1559 case 'd':
1560 ret = size < 5 || !starts_with(line, "diff ");
1561 break;
1562 default:
1563 ret = -1;
1564 break;
1565 }
1566 if (ret) {
1567 warning(_("recount: unexpected line: %.*s"),
1568 (int)linelen(line, size), line);
1569 return;
1570 }
1571 break;
1572 }
1573 fragment->oldlines = oldlines;
1574 fragment->newlines = newlines;
1575 }
1576
1577 /*
1578 * Parse a unified diff fragment header of the
1579 * form "@@ -a,b +c,d @@"
1580 */
1581 static int parse_fragment_header(const char *line, int len, struct fragment *fragment)
1582 {
1583 int offset;
1584
1585 if (!len || line[len-1] != '\n')
1586 return -1;
1587
1588 /* Figure out the number of lines in a fragment */
1589 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1590 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1591
1592 return offset;
1593 }
1594
1595 /*
1596 * Find file diff header
1597 *
1598 * Returns:
1599 * -1 if no header was found
1600 * -128 in case of error
1601 * the size of the header in bytes (called "offset") otherwise
1602 */
1603 static int find_header(struct apply_state *state,
1604 const char *line,
1605 unsigned long size,
1606 int *hdrsize,
1607 struct patch *patch)
1608 {
1609 unsigned long offset, len;
1610
1611 patch->is_toplevel_relative = 0;
1612 patch->is_rename = patch->is_copy = 0;
1613 patch->is_new = patch->is_delete = -1;
1614 patch->old_mode = patch->new_mode = 0;
1615 patch->old_name = patch->new_name = NULL;
1616 for (offset = 0; size > 0; offset += len, size -= len, line += len, state->linenr++) {
1617 unsigned long nextlen;
1618
1619 len = linelen(line, size);
1620 if (!len)
1621 break;
1622
1623 /* Testing this early allows us to take a few shortcuts.. */
1624 if (len < 6)
1625 continue;
1626
1627 /*
1628 * Make sure we don't find any unconnected patch fragments.
1629 * That's a sign that we didn't find a header, and that a
1630 * patch has become corrupted/broken up.
1631 */
1632 if (!memcmp("@@ -", line, 4)) {
1633 struct fragment dummy;
1634 if (parse_fragment_header(line, len, &dummy) < 0)
1635 continue;
1636 error(_("patch fragment without header at %s:%d: %.*s"),
1637 state->patch_input_file, state->linenr,
1638 (int)len-1, line);
1639 return -128;
1640 }
1641
1642 if (size < len + 6)
1643 break;
1644
1645 /*
1646 * Git patch? It might not have a real patch, just a rename
1647 * or mode change, so we handle that specially
1648 */
1649 if (!memcmp("diff --git ", line, 11)) {
1650 struct patch git_patch = { 0 };
1651 int git_linenr = state->linenr;
1652 int git_hdr_len;
1653
1654 git_patch.inaccurate_eof = patch->inaccurate_eof;
1655 git_patch.recount = patch->recount;
1656 git_hdr_len = parse_git_diff_header(&state->root,
1657 state->patch_input_file,
1658 &git_linenr,
1659 state->p_value, line, len,
1660 size, &git_patch);
1661 if (git_hdr_len < 0) {
1662 release_patch(&git_patch);
1663 return -128;
1664 }
1665 if (git_hdr_len <= len) {
1666 release_patch(&git_patch);
1667 continue;
1668 }
1669 *patch = git_patch;
1670 state->linenr = git_linenr;
1671 *hdrsize = git_hdr_len;
1672 return offset;
1673 }
1674
1675 /* --- followed by +++ ? */
1676 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))
1677 continue;
1678
1679 /*
1680 * We only accept unified patches, so we want it to
1681 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1682 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1683 */
1684 nextlen = linelen(line + len, size - len);
1685 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1686 continue;
1687
1688 /* Ok, we'll consider it a patch */
1689 if (parse_traditional_patch(state, line, line+len, patch))
1690 return -128;
1691 *hdrsize = len + nextlen;
1692 state->linenr += 2;
1693 return offset;
1694 }
1695 return -1;
1696 }
1697
1698 static void record_ws_error(struct apply_state *state,
1699 unsigned result,
1700 const char *line,
1701 int len,
1702 int linenr)
1703 {
1704 char *err;
1705
1706 if (!result)
1707 return;
1708
1709 state->whitespace_error++;
1710 if (state->squelch_whitespace_errors &&
1711 state->squelch_whitespace_errors < state->whitespace_error)
1712 return;
1713
1714 /*
1715 * line[len] for an incomplete line points at the "\n" at the end
1716 * of patch input line, so "%.*s" would drop the last letter on line;
1717 * compensate for it.
1718 */
1719 if (result & WS_INCOMPLETE_LINE)
1720 len++;
1721
1722 err = whitespace_error_string(result);
1723 if (state->apply_verbosity > verbosity_silent)
1724 fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1725 state->patch_input_file, linenr, err, len, line);
1726 free(err);
1727 }
1728
1729 static void check_whitespace(struct apply_state *state,
1730 const char *line,
1731 int len,
1732 unsigned ws_rule)
1733 {
1734 unsigned result = ws_check(line + 1, len - 1, ws_rule);
1735
1736 record_ws_error(state, result, line + 1, len - 2, state->linenr);
1737 }
1738
1739 /*
1740 * Check if the patch has context lines with CRLF or
1741 * the patch wants to remove lines with CRLF.
1742 */
1743 static void check_old_for_crlf(struct patch *patch, const char *line, int len)
1744 {
1745 if (len >= 2 && line[len-1] == '\n' && line[len-2] == '\r') {
1746 patch->ws_rule |= WS_CR_AT_EOL;
1747 patch->crlf_in_old = 1;
1748 }
1749 }
1750
1751
1752 /*
1753 * Just saw a single line in a fragment. If it is a part of this hunk
1754 * that is a context " ", an added "+", or a removed "-" line, it may
1755 * be followed by "\\ No newline..." to signal that the last "\n" on
1756 * this line needs to be dropped. Depending on locale settings when
1757 * the patch was produced we don't know what this line would exactly
1758 * say. The only thing we do know is that it begins with "\ ".
1759 * Checking for 12 is just for sanity check; "\ No newline..." would
1760 * be at least that long in any l10n.
1761 *
1762 * Return 0 if the line we saw is not followed by "\ No newline...",
1763 * or length of that line. The caller will use it to skip over the
1764 * "\ No newline..." line.
1765 */
1766 static int adjust_incomplete(const char *line, int len,
1767 unsigned long size)
1768 {
1769 int nextlen;
1770
1771 if (*line != '\n' && *line != ' ' && *line != '+' && *line != '-')
1772 return 0;
1773 if (size - len < 12 || memcmp(line + len, "\\ ", 2))
1774 return 0;
1775 nextlen = linelen(line + len, size - len);
1776 if (nextlen < 12)
1777 return 0;
1778 return nextlen;
1779 }
1780
1781 /*
1782 * Parse a unified diff. Note that this really needs to parse each
1783 * fragment separately, since the only way to know the difference
1784 * between a "---" that is part of a patch, and a "---" that starts
1785 * the next patch is to look at the line counts..
1786 */
1787 static int parse_fragment(struct apply_state *state,
1788 const char *line,
1789 unsigned long size,
1790 struct patch *patch,
1791 struct fragment *fragment)
1792 {
1793 int added, deleted;
1794 int len = linelen(line, size), offset;
1795 int skip_len = 0;
1796 unsigned long oldlines, newlines;
1797 unsigned long leading, trailing;
1798
1799 /* do not complain a symbolic link being an incomplete line */
1800 if (patch->ws_rule & WS_INCOMPLETE_LINE) {
1801 /*
1802 * We want to figure out if the postimage is a
1803 * symbolic link when applying the patch normally, or
1804 * if the preimage is a symbolic link when applying
1805 * the patch in reverse. A normal patch only has
1806 * old_mode without new_mode. If it changes the
1807 * filemode, new_mode has value, which is different
1808 * from old_mode.
1809 */
1810 unsigned mode = (state->apply_in_reverse
1811 ? patch->old_mode
1812 : patch->new_mode
1813 ? patch->new_mode
1814 : patch->old_mode);
1815 if (mode && S_ISLNK(mode))
1816 patch->ws_rule &= ~WS_INCOMPLETE_LINE;
1817 }
1818
1819 offset = parse_fragment_header(line, len, fragment);
1820 if (offset < 0)
1821 return -1;
1822 if (offset > 0 && patch->recount)
1823 recount_diff(line + offset, size - offset, fragment);
1824 oldlines = fragment->oldlines;
1825 newlines = fragment->newlines;
1826 leading = 0;
1827 trailing = 0;
1828
1829 /* Parse the thing.. */
1830 line += len;
1831 size -= len;
1832 state->linenr++;
1833 added = deleted = 0;
1834 for (offset = len;
1835 0 < size;
1836 offset += len, size -= len, line += len, state->linenr++) {
1837 if (!oldlines && !newlines)
1838 break;
1839 len = linelen(line, size);
1840 if (!len || line[len-1] != '\n')
1841 return -1;
1842
1843 /*
1844 * For an incomplete line, skip_len counts the bytes
1845 * on "\\ No newline..." marker line that comes next
1846 * to the current line.
1847 *
1848 * Reduce "len" to drop the newline at the end of
1849 * line[], but add one to "skip_len", which will be
1850 * added back to "len" for the next iteration, to
1851 * compensate.
1852 */
1853 skip_len = adjust_incomplete(line, len, size);
1854 if (skip_len) {
1855 len--;
1856 skip_len++;
1857 }
1858 switch (*line) {
1859 default:
1860 return -1;
1861 case '\n': /* newer GNU diff, an empty context line */
1862 case ' ':
1863 oldlines--;
1864 newlines--;
1865 if (!deleted && !added)
1866 leading++;
1867 trailing++;
1868 check_old_for_crlf(patch, line, len);
1869 if (!state->apply_in_reverse &&
1870 state->ws_error_action == correct_ws_error) {
1871 const char *test_line = line;
1872 int test_len = len;
1873 if (*line == '\n') {
1874 test_line = " \n";
1875 test_len = 2;
1876 }
1877 check_whitespace(state, test_line, test_len,
1878 patch->ws_rule);
1879 }
1880 break;
1881 case '-':
1882 if (!state->apply_in_reverse)
1883 check_old_for_crlf(patch, line, len);
1884 if (state->apply_in_reverse &&
1885 state->ws_error_action != nowarn_ws_error)
1886 check_whitespace(state, line, len, patch->ws_rule);
1887 deleted++;
1888 oldlines--;
1889 trailing = 0;
1890 break;
1891 case '+':
1892 if (state->apply_in_reverse)
1893 check_old_for_crlf(patch, line, len);
1894 if (!state->apply_in_reverse &&
1895 state->ws_error_action != nowarn_ws_error)
1896 check_whitespace(state, line, len, patch->ws_rule);
1897 added++;
1898 newlines--;
1899 trailing = 0;
1900 break;
1901 }
1902
1903 /* eat the "\\ No newline..." as well, if exists */
1904 if (skip_len) {
1905 len += skip_len;
1906 state->linenr++;
1907 }
1908 }
1909 if (oldlines || newlines)
1910 return -1;
1911 if (!patch->recount && !deleted && !added)
1912 return -1;
1913
1914 fragment->leading = leading;
1915 fragment->trailing = trailing;
1916
1917 patch->lines_added += added;
1918 patch->lines_deleted += deleted;
1919
1920 if (0 < patch->is_new && oldlines)
1921 return error(_("new file depends on old contents"));
1922 if (0 < patch->is_delete && newlines)
1923 return error(_("deleted file still has contents"));
1924 return offset;
1925 }
1926
1927 /*
1928 * We have seen "diff --git a/... b/..." header (or a traditional patch
1929 * header). Read hunks that belong to this patch into fragments and hang
1930 * them to the given patch structure.
1931 *
1932 * The (fragment->patch, fragment->size) pair points into the memory given
1933 * by the caller, not a copy, when we return.
1934 *
1935 * Returns:
1936 * -1 in case of error,
1937 * the number of bytes in the patch otherwise.
1938 */
1939 static int parse_single_patch(struct apply_state *state,
1940 const char *line,
1941 unsigned long size,
1942 struct patch *patch)
1943 {
1944 unsigned long offset = 0;
1945 unsigned long oldlines = 0, newlines = 0, context = 0;
1946 struct fragment **fragp = &patch->fragments;
1947
1948 while (size > 4 && !memcmp(line, "@@ -", 4)) {
1949 struct fragment *fragment;
1950 int len;
1951
1952 CALLOC_ARRAY(fragment, 1);
1953 fragment->linenr = state->linenr;
1954 len = parse_fragment(state, line, size, patch, fragment);
1955 if (len <= 0) {
1956 free(fragment);
1957 return error(_("corrupt patch at %s:%d"),
1958 state->patch_input_file, state->linenr);
1959 }
1960 fragment->patch = line;
1961 fragment->size = len;
1962 oldlines += fragment->oldlines;
1963 newlines += fragment->newlines;
1964 context += fragment->leading + fragment->trailing;
1965
1966 *fragp = fragment;
1967 fragp = &fragment->next;
1968
1969 offset += len;
1970 line += len;
1971 size -= len;
1972 }
1973
1974 /*
1975 * If something was removed (i.e. we have old-lines) it cannot
1976 * be creation, and if something was added it cannot be
1977 * deletion. However, the reverse is not true; --unified=0
1978 * patches that only add are not necessarily creation even
1979 * though they do not have any old lines, and ones that only
1980 * delete are not necessarily deletion.
1981 *
1982 * Unfortunately, a real creation/deletion patch do _not_ have
1983 * any context line by definition, so we cannot safely tell it
1984 * apart with --unified=0 insanity. At least if the patch has
1985 * more than one hunk it is not creation or deletion.
1986 */
1987 if (patch->is_new < 0 &&
1988 (oldlines || (patch->fragments && patch->fragments->next)))
1989 patch->is_new = 0;
1990 if (patch->is_delete < 0 &&
1991 (newlines || (patch->fragments && patch->fragments->next)))
1992 patch->is_delete = 0;
1993
1994 if (0 < patch->is_new && oldlines)
1995 return error(_("new file %s depends on old contents"), patch->new_name);
1996 if (0 < patch->is_delete && newlines)
1997 return error(_("deleted file %s still has contents"), patch->old_name);
1998 if (!patch->is_delete && !newlines && context && state->apply_verbosity > verbosity_silent)
1999 fprintf_ln(stderr,
2000 _("** warning: "
2001 "file %s becomes empty but is not deleted"),
2002 patch->new_name);
2003
2004 return offset;
2005 }
2006
2007 static inline int metadata_changes(struct patch *patch)
2008 {
2009 return patch->is_rename > 0 ||
2010 patch->is_copy > 0 ||
2011 patch->is_new > 0 ||
2012 patch->is_delete ||
2013 (patch->old_mode && patch->new_mode &&
2014 patch->old_mode != patch->new_mode);
2015 }
2016
2017 static char *inflate_it(const void *data, unsigned long size,
2018 unsigned long inflated_size)
2019 {
2020 git_zstream stream;
2021 void *out;
2022 int st;
2023
2024 memset(&stream, 0, sizeof(stream));
2025
2026 stream.next_in = (unsigned char *)data;
2027 stream.avail_in = size;
2028 stream.next_out = out = xmalloc(inflated_size);
2029 stream.avail_out = inflated_size;
2030 git_inflate_init(&stream);
2031 st = git_inflate(&stream, Z_FINISH);
2032 git_inflate_end(&stream);
2033 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
2034 free(out);
2035 return NULL;
2036 }
2037 return out;
2038 }
2039
2040 /*
2041 * Read a binary hunk and return a new fragment; fragment->patch
2042 * points at an allocated memory that the caller must free, so
2043 * it is marked as "->free_patch = 1".
2044 */
2045 static struct fragment *parse_binary_hunk(struct apply_state *state,
2046 char **buf_p,
2047 unsigned long *sz_p,
2048 int *status_p,
2049 int *used_p)
2050 {
2051 /*
2052 * Expect a line that begins with binary patch method ("literal"
2053 * or "delta"), followed by the length of data before deflating.
2054 * a sequence of 'length-byte' followed by base-85 encoded data
2055 * should follow, terminated by a newline.
2056 *
2057 * Each 5-byte sequence of base-85 encodes up to 4 bytes,
2058 * and we would limit the patch line to 66 characters,
2059 * so one line can fit up to 13 groups that would decode
2060 * to 52 bytes max. The length byte 'A'-'Z' corresponds
2061 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
2062 */
2063 int llen, used;
2064 unsigned long size = *sz_p;
2065 char *buffer = *buf_p;
2066 int patch_method;
2067 unsigned long origlen;
2068 char *data = NULL;
2069 int hunk_size = 0;
2070 struct fragment *frag;
2071
2072 llen = linelen(buffer, size);
2073 used = llen;
2074
2075 *status_p = 0;
2076
2077 if (starts_with(buffer, "delta ")) {
2078 patch_method = BINARY_DELTA_DEFLATED;
2079 origlen = strtoul(buffer + 6, NULL, 10);
2080 }
2081 else if (starts_with(buffer, "literal ")) {
2082 patch_method = BINARY_LITERAL_DEFLATED;
2083 origlen = strtoul(buffer + 8, NULL, 10);
2084 }
2085 else
2086 return NULL;
2087
2088 state->linenr++;
2089 buffer += llen;
2090 size -= llen;
2091 while (1) {
2092 int byte_length, max_byte_length, newsize;
2093 llen = linelen(buffer, size);
2094 used += llen;
2095 state->linenr++;
2096 if (llen == 1) {
2097 /* consume the blank line */
2098 buffer++;
2099 size--;
2100 break;
2101 }
2102 /*
2103 * Minimum line is "A00000\n" which is 7-byte long,
2104 * and the line length must be multiple of 5 plus 2.
2105 */
2106 if ((llen < 7) || (llen-2) % 5)
2107 goto corrupt;
2108 max_byte_length = (llen - 2) / 5 * 4;
2109 byte_length = *buffer;
2110 if ('A' <= byte_length && byte_length <= 'Z')
2111 byte_length = byte_length - 'A' + 1;
2112 else if ('a' <= byte_length && byte_length <= 'z')
2113 byte_length = byte_length - 'a' + 27;
2114 else
2115 goto corrupt;
2116 /* if the input length was not multiple of 4, we would
2117 * have filler at the end but the filler should never
2118 * exceed 3 bytes
2119 */
2120 if (max_byte_length < byte_length ||
2121 byte_length <= max_byte_length - 4)
2122 goto corrupt;
2123 newsize = hunk_size + byte_length;
2124 data = xrealloc(data, newsize);
2125 if (decode_85(data + hunk_size, buffer + 1, byte_length))
2126 goto corrupt;
2127 hunk_size = newsize;
2128 buffer += llen;
2129 size -= llen;
2130 }
2131
2132 CALLOC_ARRAY(frag, 1);
2133 frag->patch = inflate_it(data, hunk_size, origlen);
2134 frag->free_patch = 1;
2135 if (!frag->patch)
2136 goto corrupt;
2137 free(data);
2138 frag->size = origlen;
2139 *buf_p = buffer;
2140 *sz_p = size;
2141 *used_p = used;
2142 frag->binary_patch_method = patch_method;
2143 return frag;
2144
2145 corrupt:
2146 free(data);
2147 *status_p = -1;
2148 error(_("corrupt binary patch at %s:%d: %.*s"),
2149 state->patch_input_file, state->linenr-1, llen-1, buffer);
2150 return NULL;
2151 }
2152
2153 /*
2154 * Returns:
2155 * -1 in case of error,
2156 * the length of the parsed binary patch otherwise
2157 */
2158 static int parse_binary(struct apply_state *state,
2159 char *buffer,
2160 unsigned long size,
2161 struct patch *patch)
2162 {
2163 /*
2164 * We have read "GIT binary patch\n"; what follows is a line
2165 * that says the patch method (currently, either "literal" or
2166 * "delta") and the length of data before deflating; a
2167 * sequence of 'length-byte' followed by base-85 encoded data
2168 * follows.
2169 *
2170 * When a binary patch is reversible, there is another binary
2171 * hunk in the same format, starting with patch method (either
2172 * "literal" or "delta") with the length of data, and a sequence
2173 * of length-byte + base-85 encoded data, terminated with another
2174 * empty line. This data, when applied to the postimage, produces
2175 * the preimage.
2176 */
2177 struct fragment *forward;
2178 struct fragment *reverse;
2179 int status;
2180 int used, used_1;
2181
2182 forward = parse_binary_hunk(state, &buffer, &size, &status, &used);
2183 if (!forward && !status)
2184 /* there has to be one hunk (forward hunk) */
2185 return error(_("unrecognized binary patch at %s:%d"),
2186 state->patch_input_file, state->linenr-1);
2187 if (status)
2188 /* otherwise we already gave an error message */
2189 return status;
2190
2191 reverse = parse_binary_hunk(state, &buffer, &size, &status, &used_1);
2192 if (reverse)
2193 used += used_1;
2194 else if (status) {
2195 /*
2196 * Not having reverse hunk is not an error, but having
2197 * a corrupt reverse hunk is.
2198 */
2199 free((void*) forward->patch);
2200 free(forward);
2201 return status;
2202 }
2203 forward->next = reverse;
2204 patch->fragments = forward;
2205 patch->is_binary = 1;
2206 return used;
2207 }
2208
2209 static void prefix_one(struct apply_state *state, char **name)
2210 {
2211 char *old_name = *name;
2212 if (!old_name)
2213 return;
2214 *name = prefix_filename(state->prefix, *name);
2215 free(old_name);
2216 }
2217
2218 static void prefix_patch(struct apply_state *state, struct patch *p)
2219 {
2220 if (!state->prefix || p->is_toplevel_relative)
2221 return;
2222 prefix_one(state, &p->new_name);
2223 prefix_one(state, &p->old_name);
2224 }
2225
2226 /*
2227 * include/exclude
2228 */
2229
2230 static void add_name_limit(struct apply_state *state,
2231 const char *name,
2232 int exclude)
2233 {
2234 struct string_list_item *it;
2235
2236 it = string_list_append(&state->limit_by_name, name);
2237 it->util = exclude ? NULL : (void *) 1;
2238 }
2239
2240 static int use_patch(struct apply_state *state, struct patch *p)
2241 {
2242 const char *pathname = p->new_name ? p->new_name : p->old_name;
2243 int i;
2244
2245 /* Paths outside are not touched regardless of "--include" */
2246 if (state->prefix && *state->prefix) {
2247 const char *rest;
2248 if (!skip_prefix(pathname, state->prefix, &rest) || !*rest)
2249 return 0;
2250 }
2251
2252 /* See if it matches any of exclude/include rule */
2253 for (i = 0; i < state->limit_by_name.nr; i++) {
2254 struct string_list_item *it = &state->limit_by_name.items[i];
2255 if (!wildmatch(it->string, pathname, 0))
2256 return (it->util != NULL);
2257 }
2258
2259 /*
2260 * If we had any include, a path that does not match any rule is
2261 * not used. Otherwise, we saw bunch of exclude rules (or none)
2262 * and such a path is used.
2263 */
2264 return !state->has_include;
2265 }
2266
2267 /*
2268 * Read the patch text in "buffer" that extends for "size" bytes; stop
2269 * reading after seeing a single patch (i.e. changes to a single file).
2270 * Create fragments (i.e. patch hunks) and hang them to the given patch.
2271 *
2272 * Returns:
2273 * -1 if no header was found or parse_binary() failed,
2274 * -128 on another error,
2275 * the number of bytes consumed otherwise,
2276 * so that the caller can call us again for the next patch.
2277 */
2278 static int parse_chunk(struct apply_state *state, char *buffer, unsigned long size, struct patch *patch)
2279 {
2280 int hdrsize, patchsize;
2281 int offset = find_header(state, buffer, size, &hdrsize, patch);
2282
2283 if (offset < 0)
2284 return offset;
2285
2286 prefix_patch(state, patch);
2287
2288 if (!use_patch(state, patch))
2289 patch->ws_rule = 0;
2290 else if (patch->new_name)
2291 patch->ws_rule = whitespace_rule(state->repo->index,
2292 patch->new_name);
2293 else
2294 patch->ws_rule = whitespace_rule(state->repo->index,
2295 patch->old_name);
2296
2297 patchsize = parse_single_patch(state,
2298 buffer + offset + hdrsize,
2299 size - offset - hdrsize,
2300 patch);
2301
2302 if (patchsize < 0)
2303 return -128;
2304
2305 if (!patchsize) {
2306 static const char git_binary[] = "GIT binary patch\n";
2307 int hd = hdrsize + offset;
2308 unsigned long llen = linelen(buffer + hd, size - hd);
2309
2310 if (llen == sizeof(git_binary) - 1 &&
2311 !memcmp(git_binary, buffer + hd, llen)) {
2312 int used;
2313 state->linenr++;
2314 used = parse_binary(state, buffer + hd + llen,
2315 size - hd - llen, patch);
2316 if (used < 0)
2317 return -1;
2318 if (used)
2319 patchsize = used + llen;
2320 else
2321 patchsize = 0;
2322 }
2323 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
2324 static const char *binhdr[] = {
2325 "Binary files ",
2326 "Files ",
2327 NULL,
2328 };
2329 int i;
2330 for (i = 0; binhdr[i]; i++) {
2331 int len = strlen(binhdr[i]);
2332 if (len < size - hd &&
2333 !memcmp(binhdr[i], buffer + hd, len)) {
2334 state->linenr++;
2335 patch->is_binary = 1;
2336 patchsize = llen;
2337 break;
2338 }
2339 }
2340 }
2341
2342 /* Empty patch cannot be applied if it is a text patch
2343 * without metadata change. A binary patch appears
2344 * empty to us here.
2345 */
2346 if ((state->apply || state->check) &&
2347 (!patch->is_binary && !metadata_changes(patch))) {
2348 error(_("patch with only garbage at %s:%d"),
2349 state->patch_input_file, state->linenr);
2350 return -128;
2351 }
2352 }
2353
2354 return offset + hdrsize + patchsize;
2355 }
2356
2357 static void reverse_patches(struct patch *p)
2358 {
2359 for (; p; p = p->next) {
2360 struct fragment *frag = p->fragments;
2361
2362 SWAP(p->new_name, p->old_name);
2363 if (p->new_mode || p->is_delete)
2364 SWAP(p->new_mode, p->old_mode);
2365 SWAP(p->is_new, p->is_delete);
2366 SWAP(p->lines_added, p->lines_deleted);
2367 SWAP(p->old_oid_prefix, p->new_oid_prefix);
2368
2369 for (; frag; frag = frag->next) {
2370 SWAP(frag->newpos, frag->oldpos);
2371 SWAP(frag->newlines, frag->oldlines);
2372 }
2373 }
2374 }
2375
2376 static const char pluses[] =
2377 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
2378 static const char minuses[]=
2379 "----------------------------------------------------------------------";
2380
2381 static void show_stats(struct apply_state *state, struct patch *patch)
2382 {
2383 struct strbuf qname = STRBUF_INIT;
2384 char *cp = patch->new_name ? patch->new_name : patch->old_name;
2385 int max, add, del;
2386
2387 quote_c_style(cp, &qname, NULL, 0);
2388
2389 /*
2390 * "scale" the filename
2391 */
2392 max = state->max_len;
2393 if (max > 50)
2394 max = 50;
2395
2396 if (qname.len > max) {
2397 cp = strchr(qname.buf + qname.len + 3 - max, '/');
2398 if (!cp)
2399 cp = qname.buf + qname.len + 3 - max;
2400 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
2401 }
2402
2403 if (patch->is_binary) {
2404 printf(" %-*s | Bin\n", max, qname.buf);
2405 strbuf_release(&qname);
2406 return;
2407 }
2408
2409 printf(" %-*s |", max, qname.buf);
2410 strbuf_release(&qname);
2411
2412 /*
2413 * scale the add/delete
2414 */
2415 max = max + state->max_change > 70 ? 70 - max : state->max_change;
2416 add = patch->lines_added;
2417 del = patch->lines_deleted;
2418
2419 if (state->max_change > 0) {
2420 int total = ((add + del) * max + state->max_change / 2) / state->max_change;
2421 add = (add * max + state->max_change / 2) / state->max_change;
2422 del = total - add;
2423 }
2424 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
2425 add, pluses, del, minuses);
2426 }
2427
2428 static int read_old_data(struct stat *st, struct patch *patch,
2429 const char *path, struct strbuf *buf)
2430 {
2431 int conv_flags = patch->crlf_in_old ?
2432 CONV_EOL_KEEP_CRLF : CONV_EOL_RENORMALIZE;
2433 switch (st->st_mode & S_IFMT) {
2434 case S_IFLNK:
2435 if (strbuf_readlink(buf, path, st->st_size) < 0)
2436 return error(_("unable to read symlink %s"), path);
2437 return 0;
2438 case S_IFREG:
2439 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
2440 return error(_("unable to open or read %s"), path);
2441 /*
2442 * "git apply" without "--index/--cached" should never look
2443 * at the index; the target file may not have been added to
2444 * the index yet, and we may not even be in any Git repository.
2445 * Pass NULL to convert_to_git() to stress this; the function
2446 * should never look at the index when explicit crlf option
2447 * is given.
2448 */
2449 convert_to_git(NULL, path, buf->buf, buf->len, buf, conv_flags);
2450 return 0;
2451 default:
2452 return -1;
2453 }
2454 }
2455
2456 /*
2457 * Update the preimage, and the common lines in postimage,
2458 * from buffer buf of length len.
2459 */
2460 static void update_pre_post_images(struct image *preimage,
2461 struct image *postimage,
2462 char *buf, size_t len)
2463 {
2464 struct image fixed_preimage = IMAGE_INIT;
2465 size_t insert_pos = 0;
2466 int i, ctx, reduced;
2467 const char *fixed;
2468
2469 /*
2470 * Update the preimage with whitespace fixes. Note that we
2471 * are not losing preimage->buf -- apply_one_fragment() will
2472 * free "oldlines".
2473 */
2474 image_prepare(&fixed_preimage, buf, len, 1);
2475 for (i = 0; i < fixed_preimage.line_nr; i++)
2476 fixed_preimage.line[i].flag = preimage->line[i].flag;
2477 image_clear(preimage);
2478 *preimage = fixed_preimage;
2479 fixed = preimage->buf.buf;
2480
2481 /*
2482 * Adjust the common context lines in postimage.
2483 */
2484 for (i = reduced = ctx = 0; i < postimage->line_nr; i++) {
2485 size_t l_len = postimage->line[i].len;
2486
2487 if (!(postimage->line[i].flag & LINE_COMMON)) {
2488 /* an added line -- no counterparts in preimage */
2489 insert_pos += l_len;
2490 continue;
2491 }
2492
2493 /* and find the corresponding one in the fixed preimage */
2494 while (ctx < preimage->line_nr &&
2495 !(preimage->line[ctx].flag & LINE_COMMON)) {
2496 fixed += preimage->line[ctx].len;
2497 ctx++;
2498 }
2499
2500 /*
2501 * preimage is expected to run out, if the caller
2502 * fixed addition of trailing blank lines.
2503 */
2504 if (preimage->line_nr <= ctx) {
2505 reduced++;
2506 continue;
2507 }
2508
2509 /* and copy it in, while fixing the line length */
2510 l_len = preimage->line[ctx].len;
2511 strbuf_splice(&postimage->buf, insert_pos, postimage->line[i].len,
2512 fixed, l_len);
2513 insert_pos += l_len;
2514 fixed += l_len;
2515 postimage->line[i].len = l_len;
2516 ctx++;
2517 }
2518
2519 /* Fix the length of the whole thing */
2520 postimage->line_nr -= reduced;
2521 }
2522
2523 /*
2524 * Compare lines s1 of length n1 and s2 of length n2, ignoring
2525 * whitespace difference. Returns 1 if they match, 0 otherwise
2526 */
2527 static int fuzzy_matchlines(const char *s1, size_t n1,
2528 const char *s2, size_t n2)
2529 {
2530 const char *end1 = s1 + n1;
2531 const char *end2 = s2 + n2;
2532
2533 /* ignore line endings */
2534 while (s1 < end1 && (end1[-1] == '\r' || end1[-1] == '\n'))
2535 end1--;
2536 while (s2 < end2 && (end2[-1] == '\r' || end2[-1] == '\n'))
2537 end2--;
2538
2539 while (s1 < end1 && s2 < end2) {
2540 if (isspace(*s1)) {
2541 /*
2542 * Skip whitespace. We check on both buffers
2543 * because we don't want "a b" to match "ab".
2544 */
2545 if (!isspace(*s2))
2546 return 0;
2547 while (s1 < end1 && isspace(*s1))
2548 s1++;
2549 while (s2 < end2 && isspace(*s2))
2550 s2++;
2551 } else if (*s1++ != *s2++)
2552 return 0;
2553 }
2554
2555 /* If we reached the end on one side only, lines don't match. */
2556 return s1 == end1 && s2 == end2;
2557 }
2558
2559 static int line_by_line_fuzzy_match(struct image *img,
2560 struct image *preimage,
2561 struct image *postimage,
2562 unsigned long current,
2563 int current_lno,
2564 int preimage_limit)
2565 {
2566 int i;
2567 size_t imgoff = 0;
2568 size_t preoff = 0;
2569 size_t extra_chars;
2570 char *buf;
2571 char *preimage_eof;
2572 char *preimage_end;
2573 struct strbuf fixed;
2574 char *fixed_buf;
2575 size_t fixed_len;
2576
2577 for (i = 0; i < preimage_limit; i++) {
2578 size_t prelen = preimage->line[i].len;
2579 size_t imglen = img->line[current_lno+i].len;
2580
2581 if (!fuzzy_matchlines(img->buf.buf + current + imgoff, imglen,
2582 preimage->buf.buf + preoff, prelen))
2583 return 0;
2584 imgoff += imglen;
2585 preoff += prelen;
2586 }
2587
2588 /*
2589 * Ok, the preimage matches with whitespace fuzz.
2590 *
2591 * imgoff now holds the true length of the target that
2592 * matches the preimage before the end of the file.
2593 *
2594 * Count the number of characters in the preimage that fall
2595 * beyond the end of the file and make sure that all of them
2596 * are whitespace characters. (This can only happen if
2597 * we are removing blank lines at the end of the file.)
2598 */
2599 buf = preimage_eof = preimage->buf.buf + preoff;
2600 for ( ; i < preimage->line_nr; i++)
2601 preoff += preimage->line[i].len;
2602 preimage_end = preimage->buf.buf + preoff;
2603 for ( ; buf < preimage_end; buf++)
2604 if (!isspace(*buf))
2605 return 0;
2606
2607 /*
2608 * Update the preimage and the common postimage context
2609 * lines to use the same whitespace as the target.
2610 * If whitespace is missing in the target (i.e.
2611 * if the preimage extends beyond the end of the file),
2612 * use the whitespace from the preimage.
2613 */
2614 extra_chars = preimage_end - preimage_eof;
2615 strbuf_init(&fixed, imgoff + extra_chars);
2616 strbuf_add(&fixed, img->buf.buf + current, imgoff);
2617 strbuf_add(&fixed, preimage_eof, extra_chars);
2618 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2619 update_pre_post_images(preimage, postimage,
2620 fixed_buf, fixed_len);
2621 return 1;
2622 }
2623
2624 static int match_fragment(struct apply_state *state,
2625 struct image *img,
2626 struct image *preimage,
2627 struct image *postimage,
2628 unsigned long current,
2629 int current_lno,
2630 unsigned ws_rule,
2631 int match_beginning, int match_end)
2632 {
2633 int i;
2634 const char *orig, *target;
2635 struct strbuf fixed = STRBUF_INIT;
2636 char *fixed_buf;
2637 size_t fixed_len;
2638 int preimage_limit;
2639 int ret;
2640
2641 if (preimage->line_nr + current_lno <= img->line_nr) {
2642 /*
2643 * The hunk falls within the boundaries of img.
2644 */
2645 preimage_limit = preimage->line_nr;
2646 if (match_end && (preimage->line_nr + current_lno != img->line_nr)) {
2647 ret = 0;
2648 goto out;
2649 }
2650 } else if (state->ws_error_action == correct_ws_error &&
2651 (ws_rule & WS_BLANK_AT_EOF)) {
2652 /*
2653 * This hunk extends beyond the end of img, and we are
2654 * removing blank lines at the end of the file. This
2655 * many lines from the beginning of the preimage must
2656 * match with img, and the remainder of the preimage
2657 * must be blank.
2658 */
2659 preimage_limit = img->line_nr - current_lno;
2660 } else {
2661 /*
2662 * The hunk extends beyond the end of the img and
2663 * we are not removing blanks at the end, so we
2664 * should reject the hunk at this position.
2665 */
2666 ret = 0;
2667 goto out;
2668 }
2669
2670 if (match_beginning && current_lno) {
2671 ret = 0;
2672 goto out;
2673 }
2674
2675 /* Quick hash check */
2676 for (i = 0; i < preimage_limit; i++) {
2677 if ((img->line[current_lno + i].flag & LINE_PATCHED) ||
2678 (preimage->line[i].hash != img->line[current_lno + i].hash)) {
2679 ret = 0;
2680 goto out;
2681 }
2682 }
2683
2684 if (preimage_limit == preimage->line_nr) {
2685 /*
2686 * Do we have an exact match? If we were told to match
2687 * at the end, size must be exactly at current+fragsize,
2688 * otherwise current+fragsize must be still within the preimage,
2689 * and either case, the old piece should match the preimage
2690 * exactly.
2691 */
2692 if ((match_end
2693 ? (current + preimage->buf.len == img->buf.len)
2694 : (current + preimage->buf.len <= img->buf.len)) &&
2695 !memcmp(img->buf.buf + current, preimage->buf.buf, preimage->buf.len)) {
2696 ret = 1;
2697 goto out;
2698 }
2699 } else {
2700 /*
2701 * The preimage extends beyond the end of img, so
2702 * there cannot be an exact match.
2703 *
2704 * There must be one non-blank context line that match
2705 * a line before the end of img.
2706 */
2707 const char *buf, *buf_end;
2708
2709 buf = preimage->buf.buf;
2710 buf_end = buf;
2711 for (i = 0; i < preimage_limit; i++)
2712 buf_end += preimage->line[i].len;
2713
2714 for ( ; buf < buf_end; buf++)
2715 if (!isspace(*buf))
2716 break;
2717 if (buf == buf_end) {
2718 ret = 0;
2719 goto out;
2720 }
2721 }
2722
2723 /*
2724 * No exact match. If we are ignoring whitespace, run a line-by-line
2725 * fuzzy matching. We collect all the line length information because
2726 * we need it to adjust whitespace if we match.
2727 */
2728 if (state->ws_ignore_action == ignore_ws_change) {
2729 ret = line_by_line_fuzzy_match(img, preimage, postimage,
2730 current, current_lno, preimage_limit);
2731 goto out;
2732 }
2733
2734 if (state->ws_error_action != correct_ws_error) {
2735 ret = 0;
2736 goto out;
2737 }
2738
2739 /*
2740 * The hunk does not apply byte-by-byte, but the hash says
2741 * it might with whitespace fuzz. We weren't asked to
2742 * ignore whitespace, we were asked to correct whitespace
2743 * errors, so let's try matching after whitespace correction.
2744 *
2745 * While checking the preimage against the target, whitespace
2746 * errors in both fixed, we count how large the corresponding
2747 * postimage needs to be. The postimage prepared by
2748 * apply_one_fragment() has whitespace errors fixed on added
2749 * lines already, but the common lines were propagated as-is,
2750 * which may become longer when their whitespace errors are
2751 * fixed.
2752 */
2753
2754 /*
2755 * The preimage may extend beyond the end of the file,
2756 * but in this loop we will only handle the part of the
2757 * preimage that falls within the file.
2758 */
2759 strbuf_grow(&fixed, preimage->buf.len + 1);
2760 orig = preimage->buf.buf;
2761 target = img->buf.buf + current;
2762 for (i = 0; i < preimage_limit; i++) {
2763 size_t oldlen = preimage->line[i].len;
2764 size_t tgtlen = img->line[current_lno + i].len;
2765 size_t fixstart = fixed.len;
2766 struct strbuf tgtfix;
2767 int match;
2768
2769 /* Try fixing the line in the preimage */
2770 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2771
2772 /* Try fixing the line in the target */
2773 strbuf_init(&tgtfix, tgtlen);
2774 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2775
2776 /*
2777 * If they match, either the preimage was based on
2778 * a version before our tree fixed whitespace breakage,
2779 * or we are lacking a whitespace-fix patch the tree
2780 * the preimage was based on already had (i.e. target
2781 * has whitespace breakage, the preimage doesn't).
2782 * In either case, we are fixing the whitespace breakages
2783 * so we might as well take the fix together with their
2784 * real change.
2785 */
2786 match = (tgtfix.len == fixed.len - fixstart &&
2787 !memcmp(tgtfix.buf, fixed.buf + fixstart,
2788 fixed.len - fixstart));
2789
2790 strbuf_release(&tgtfix);
2791 if (!match) {
2792 ret = 0;
2793 goto out;
2794 }
2795
2796 orig += oldlen;
2797 target += tgtlen;
2798 }
2799
2800
2801 /*
2802 * Now handle the lines in the preimage that falls beyond the
2803 * end of the file (if any). They will only match if they are
2804 * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2805 * false).
2806 */
2807 for ( ; i < preimage->line_nr; i++) {
2808 size_t fixstart = fixed.len; /* start of the fixed preimage */
2809 size_t oldlen = preimage->line[i].len;
2810 int j;
2811
2812 /* Try fixing the line in the preimage */
2813 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2814
2815 for (j = fixstart; j < fixed.len; j++) {
2816 if (!isspace(fixed.buf[j])) {
2817 ret = 0;
2818 goto out;
2819 }
2820 }
2821
2822
2823 orig += oldlen;
2824 }
2825
2826 /*
2827 * Yes, the preimage is based on an older version that still
2828 * has whitespace breakages unfixed, and fixing them makes the
2829 * hunk match. Update the context lines in the postimage.
2830 */
2831 fixed_buf = strbuf_detach(&fixed, &fixed_len);
2832 update_pre_post_images(preimage, postimage,
2833 fixed_buf, fixed_len);
2834
2835 ret = 1;
2836
2837 out:
2838 strbuf_release(&fixed);
2839 return ret;
2840 }
2841
2842 static int find_pos(struct apply_state *state,
2843 struct image *img,
2844 struct image *preimage,
2845 struct image *postimage,
2846 int line,
2847 unsigned ws_rule,
2848 int match_beginning, int match_end)
2849 {
2850 int i;
2851 unsigned long backwards, forwards, current;
2852 int backwards_lno, forwards_lno, current_lno;
2853
2854 /*
2855 * When running with --allow-overlap, it is possible that a hunk is
2856 * seen that pretends to start at the beginning (but no longer does),
2857 * and that *still* needs to match the end. So trust `match_end` more
2858 * than `match_beginning`.
2859 */
2860 if (state->allow_overlap && match_beginning && match_end &&
2861 img->line_nr - preimage->line_nr != 0)
2862 match_beginning = 0;
2863
2864 /*
2865 * If match_beginning or match_end is specified, there is no
2866 * point starting from a wrong line that will never match and
2867 * wander around and wait for a match at the specified end.
2868 */
2869 if (match_beginning)
2870 line = 0;
2871 else if (match_end)
2872 line = img->line_nr - preimage->line_nr;
2873
2874 /*
2875 * Because the comparison is unsigned, the following test
2876 * will also take care of a negative line number that can
2877 * result when match_end and preimage is larger than the target.
2878 */
2879 if ((size_t) line > img->line_nr)
2880 line = img->line_nr;
2881
2882 current = 0;
2883 for (i = 0; i < line; i++)
2884 current += img->line[i].len;
2885
2886 /*
2887 * There's probably some smart way to do this, but I'll leave
2888 * that to the smart and beautiful people. I'm simple and stupid.
2889 */
2890 backwards = current;
2891 backwards_lno = line;
2892 forwards = current;
2893 forwards_lno = line;
2894 current_lno = line;
2895
2896 for (i = 0; ; i++) {
2897 if (match_fragment(state, img, preimage, postimage,
2898 current, current_lno, ws_rule,
2899 match_beginning, match_end))
2900 return current_lno;
2901
2902 again:
2903 if (backwards_lno == 0 && forwards_lno == img->line_nr)
2904 break;
2905
2906 if (i & 1) {
2907 if (backwards_lno == 0) {
2908 i++;
2909 goto again;
2910 }
2911 backwards_lno--;
2912 backwards -= img->line[backwards_lno].len;
2913 current = backwards;
2914 current_lno = backwards_lno;
2915 } else {
2916 if (forwards_lno == img->line_nr) {
2917 i++;
2918 goto again;
2919 }
2920 forwards += img->line[forwards_lno].len;
2921 forwards_lno++;
2922 current = forwards;
2923 current_lno = forwards_lno;
2924 }
2925
2926 }
2927 return -1;
2928 }
2929
2930 /*
2931 * The change from "preimage" and "postimage" has been found to
2932 * apply at applied_pos (counts in line numbers) in "img".
2933 * Update "img" to remove "preimage" and replace it with "postimage".
2934 */
2935 static void update_image(struct apply_state *state,
2936 struct image *img,
2937 int applied_pos,
2938 struct image *preimage,
2939 struct image *postimage)
2940 {
2941 /*
2942 * remove the copy of preimage at offset in img
2943 * and replace it with postimage
2944 */
2945 int i, nr;
2946 size_t remove_count, insert_count, applied_at = 0;
2947 size_t result_alloc;
2948 char *result;
2949 int preimage_limit;
2950
2951 /*
2952 * If we are removing blank lines at the end of img,
2953 * the preimage may extend beyond the end.
2954 * If that is the case, we must be careful only to
2955 * remove the part of the preimage that falls within
2956 * the boundaries of img. Initialize preimage_limit
2957 * to the number of lines in the preimage that falls
2958 * within the boundaries.
2959 */
2960 preimage_limit = preimage->line_nr;
2961 if (preimage_limit > img->line_nr - applied_pos)
2962 preimage_limit = img->line_nr - applied_pos;
2963
2964 for (i = 0; i < applied_pos; i++)
2965 applied_at += img->line[i].len;
2966
2967 remove_count = 0;
2968 for (i = 0; i < preimage_limit; i++)
2969 remove_count += img->line[applied_pos + i].len;
2970 insert_count = postimage->buf.len;
2971
2972 /* Adjust the contents */
2973 result_alloc = st_add3(st_sub(img->buf.len, remove_count), insert_count, 1);
2974 result = xmalloc(result_alloc);
2975 memcpy(result, img->buf.buf, applied_at);
2976 memcpy(result + applied_at, postimage->buf.buf, postimage->buf.len);
2977 memcpy(result + applied_at + postimage->buf.len,
2978 img->buf.buf + (applied_at + remove_count),
2979 img->buf.len - (applied_at + remove_count));
2980 strbuf_attach(&img->buf, result, postimage->buf.len + img->buf.len - remove_count,
2981 result_alloc);
2982
2983 /* Adjust the line table */
2984 nr = img->line_nr + postimage->line_nr - preimage_limit;
2985 if (preimage_limit < postimage->line_nr)
2986 /*
2987 * NOTE: this knows that we never call image_remove_first_line()
2988 * on anything other than pre/post image.
2989 */
2990 REALLOC_ARRAY(img->line, nr);
2991 if (preimage_limit != postimage->line_nr)
2992 MOVE_ARRAY(img->line + applied_pos + postimage->line_nr,
2993 img->line + applied_pos + preimage_limit,
2994 img->line_nr - (applied_pos + preimage_limit));
2995 COPY_ARRAY(img->line + applied_pos, postimage->line, postimage->line_nr);
2996 if (!state->allow_overlap)
2997 for (i = 0; i < postimage->line_nr; i++)
2998 img->line[applied_pos + i].flag |= LINE_PATCHED;
2999 img->line_nr = nr;
3000 }
3001
3002 /*
3003 * Use the patch-hunk text in "frag" to prepare two images (preimage and
3004 * postimage) for the hunk. Find lines that match "preimage" in "img" and
3005 * replace the part of "img" with "postimage" text.
3006 */
3007 static int apply_one_fragment(struct apply_state *state,
3008 struct image *img, struct fragment *frag,
3009 int inaccurate_eof, unsigned ws_rule,
3010 int nth_fragment)
3011 {
3012 int match_beginning, match_end;
3013 const char *patch = frag->patch;
3014 int size = frag->size;
3015 char *old, *oldlines;
3016 struct strbuf newlines;
3017 int new_blank_lines_at_end = 0;
3018 int found_new_blank_lines_at_end = 0;
3019 int hunk_linenr = frag->linenr;
3020 unsigned long leading, trailing;
3021 int pos, applied_pos;
3022 struct image preimage = IMAGE_INIT;
3023 struct image postimage = IMAGE_INIT;
3024
3025 oldlines = xmalloc(size);
3026 strbuf_init(&newlines, size);
3027
3028 old = oldlines;
3029 while (size > 0) {
3030 char first;
3031 int len = linelen(patch, size);
3032 int plen;
3033 int added_blank_line = 0;
3034 int is_blank_context = 0;
3035 size_t start;
3036
3037 if (!len)
3038 break;
3039
3040 /*
3041 * "plen" is how much of the line we should use for
3042 * the actual patch data. Normally we just remove the
3043 * first character on the line, but if the line is
3044 * followed by "\ No newline", then we also remove the
3045 * last one (which is the newline, of course).
3046 */
3047 plen = len - 1;
3048 if (len < size && patch[len] == '\\')
3049 plen--;
3050 first = *patch;
3051 if (state->apply_in_reverse) {
3052 if (first == '-')
3053 first = '+';
3054 else if (first == '+')
3055 first = '-';
3056 }
3057
3058 switch (first) {
3059 case '\n':
3060 /* Newer GNU diff, empty context line */
3061 if (plen < 0)
3062 /* ... followed by '\No newline'; nothing */
3063 break;
3064 *old++ = '\n';
3065 strbuf_addch(&newlines, '\n');
3066 image_add_line(&preimage, "\n", 1, LINE_COMMON);
3067 image_add_line(&postimage, "\n", 1, LINE_COMMON);
3068 is_blank_context = 1;
3069 break;
3070 case ' ':
3071 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
3072 ws_blank_line(patch + 1, plen))
3073 is_blank_context = 1;
3074 /* fallthrough */
3075 case '-':
3076 memcpy(old, patch + 1, plen);
3077 image_add_line(&preimage, old, plen,
3078 (first == ' ' ? LINE_COMMON : 0));
3079 old += plen;
3080 if (first == '-')
3081 break;
3082 /* fallthrough */
3083 case '+':
3084 /* --no-add does not add new lines */
3085 if (first == '+' && state->no_add)
3086 break;
3087
3088 start = newlines.len;
3089 if (first != '+' ||
3090 !state->whitespace_error ||
3091 state->ws_error_action != correct_ws_error) {
3092 strbuf_add(&newlines, patch + 1, plen);
3093 }
3094 else {
3095 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &state->applied_after_fixing_ws);
3096 }
3097 image_add_line(&postimage, newlines.buf + start, newlines.len - start,
3098 (first == '+' ? 0 : LINE_COMMON));
3099 if (first == '+' &&
3100 (ws_rule & WS_BLANK_AT_EOF) &&
3101 ws_blank_line(patch + 1, plen))
3102 added_blank_line = 1;
3103 break;
3104 case '@': case '\\':
3105 /* Ignore it, we already handled it */
3106 break;
3107 default:
3108 if (state->apply_verbosity > verbosity_normal)
3109 error(_("invalid start of line: '%c'"), first);
3110 applied_pos = -1;
3111 goto out;
3112 }
3113 if (added_blank_line) {
3114 if (!new_blank_lines_at_end)
3115 found_new_blank_lines_at_end = hunk_linenr;
3116 new_blank_lines_at_end++;
3117 }
3118 else if (is_blank_context)
3119 ;
3120 else
3121 new_blank_lines_at_end = 0;
3122 patch += len;
3123 size -= len;
3124 hunk_linenr++;
3125 }
3126 if (inaccurate_eof &&
3127 old > oldlines && old[-1] == '\n' &&
3128 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
3129 old--;
3130 strbuf_setlen(&newlines, newlines.len - 1);
3131 preimage.line[preimage.line_nr - 1].len--;
3132 postimage.line[postimage.line_nr - 1].len--;
3133 }
3134
3135 leading = frag->leading;
3136 trailing = frag->trailing;
3137
3138 /*
3139 * A hunk to change lines at the beginning would begin with
3140 * @@ -1,L +N,M @@
3141 * but we need to be careful. -U0 that inserts before the second
3142 * line also has this pattern.
3143 *
3144 * And a hunk to add to an empty file would begin with
3145 * @@ -0,0 +N,M @@
3146 *
3147 * In other words, a hunk that is (frag->oldpos <= 1) with or
3148 * without leading context must match at the beginning.
3149 */
3150 match_beginning = (!frag->oldpos ||
3151 (frag->oldpos == 1 && !state->unidiff_zero));
3152
3153 /*
3154 * A hunk without trailing lines must match at the end.
3155 * However, we simply cannot tell if a hunk must match end
3156 * from the lack of trailing lines if the patch was generated
3157 * with unidiff without any context.
3158 */
3159 match_end = !state->unidiff_zero && !trailing;
3160
3161 pos = frag->newpos ? (frag->newpos - 1) : 0;
3162 strbuf_add(&preimage.buf, oldlines, old - oldlines);
3163 strbuf_swap(&postimage.buf, &newlines);
3164
3165 for (;;) {
3166
3167 applied_pos = find_pos(state, img, &preimage, &postimage, pos,
3168 ws_rule, match_beginning, match_end);
3169
3170 if (applied_pos >= 0)
3171 break;
3172
3173 /* Am I at my context limits? */
3174 if ((leading <= state->p_context) && (trailing <= state->p_context))
3175 break;
3176 if (match_beginning || match_end) {
3177 match_beginning = match_end = 0;
3178 continue;
3179 }
3180
3181 /*
3182 * Reduce the number of context lines; reduce both
3183 * leading and trailing if they are equal otherwise
3184 * just reduce the larger context.
3185 */
3186 if (leading >= trailing) {
3187 image_remove_first_line(&preimage);
3188 image_remove_first_line(&postimage);
3189 pos--;
3190 leading--;
3191 }
3192 if (trailing > leading) {
3193 image_remove_last_line(&preimage);
3194 image_remove_last_line(&postimage);
3195 trailing--;
3196 }
3197 }
3198
3199 if (applied_pos >= 0) {
3200 if (new_blank_lines_at_end &&
3201 preimage.line_nr + applied_pos >= img->line_nr &&
3202 (ws_rule & WS_BLANK_AT_EOF) &&
3203 state->ws_error_action != nowarn_ws_error) {
3204 record_ws_error(state, WS_BLANK_AT_EOF, "+", 1,
3205 found_new_blank_lines_at_end);
3206 if (state->ws_error_action == correct_ws_error) {
3207 while (new_blank_lines_at_end--)
3208 image_remove_last_line(&postimage);
3209 }
3210 /*
3211 * We would want to prevent write_out_results()
3212 * from taking place in apply_patch() that follows
3213 * the callchain led us here, which is:
3214 * apply_patch->check_patch_list->check_patch->
3215 * apply_data->apply_fragments->apply_one_fragment
3216 */
3217 if (state->ws_error_action == die_on_ws_error)
3218 state->apply = 0;
3219 }
3220
3221 if (state->apply_verbosity > verbosity_normal && applied_pos != pos) {
3222 int offset = applied_pos - pos;
3223 if (state->apply_in_reverse)
3224 offset = 0 - offset;
3225 fprintf_ln(stderr,
3226 Q_("Hunk #%d succeeded at %d (offset %d line).",
3227 "Hunk #%d succeeded at %d (offset %d lines).",
3228 offset),
3229 nth_fragment, applied_pos + 1, offset);
3230 }
3231
3232 /*
3233 * Warn if it was necessary to reduce the number
3234 * of context lines.
3235 */
3236 if ((leading != frag->leading ||
3237 trailing != frag->trailing) && state->apply_verbosity > verbosity_silent)
3238 fprintf_ln(stderr, _("Context reduced to (%ld/%ld)"
3239 " to apply fragment at %d"),
3240 leading, trailing, applied_pos+1);
3241 update_image(state, img, applied_pos, &preimage, &postimage);
3242 } else {
3243 if (state->apply_verbosity > verbosity_normal)
3244 error(_("while searching for:\n%.*s"),
3245 (int)(old - oldlines), oldlines);
3246 }
3247
3248 out:
3249 free(oldlines);
3250 strbuf_release(&newlines);
3251 image_clear(&preimage);
3252 image_clear(&postimage);
3253
3254 return (applied_pos < 0);
3255 }
3256
3257 static int apply_binary_fragment(struct apply_state *state,
3258 struct image *img,
3259 struct patch *patch)
3260 {
3261 struct fragment *fragment = patch->fragments;
3262 size_t len;
3263 void *dst;
3264
3265 if (!fragment)
3266 return error(_("missing binary patch data for '%s'"),
3267 patch->new_name ?
3268 patch->new_name :
3269 patch->old_name);
3270
3271 /* Binary patch is irreversible without the optional second hunk */
3272 if (state->apply_in_reverse) {
3273 if (!fragment->next)
3274 return error(_("cannot reverse-apply a binary patch "
3275 "without the reverse hunk to '%s'"),
3276 patch->new_name
3277 ? patch->new_name : patch->old_name);
3278 fragment = fragment->next;
3279 }
3280 switch (fragment->binary_patch_method) {
3281 case BINARY_DELTA_DEFLATED:
3282 dst = patch_delta(img->buf.buf, img->buf.len, fragment->patch,
3283 fragment->size, &len);
3284 if (!dst)
3285 return -1;
3286 image_clear(img);
3287 strbuf_attach(&img->buf, dst, len, len + 1);
3288 return 0;
3289 case BINARY_LITERAL_DEFLATED:
3290 image_clear(img);
3291 strbuf_add(&img->buf, fragment->patch, fragment->size);
3292 return 0;
3293 }
3294 return -1;
3295 }
3296
3297 /*
3298 * Replace "img" with the result of applying the binary patch.
3299 * The binary patch data itself in patch->fragment is still kept
3300 * but the preimage prepared by the caller in "img" is freed here
3301 * or in the helper function apply_binary_fragment() this calls.
3302 */
3303 static int apply_binary(struct apply_state *state,
3304 struct image *img,
3305 struct patch *patch)
3306 {
3307 const char *name = patch->old_name ? patch->old_name : patch->new_name;
3308 struct object_id oid;
3309 const unsigned hexsz = the_hash_algo->hexsz;
3310
3311 /*
3312 * For safety, we require patch index line to contain
3313 * full hex textual object ID for old and new, at least for now.
3314 */
3315 if (strlen(patch->old_oid_prefix) != hexsz ||
3316 strlen(patch->new_oid_prefix) != hexsz ||
3317 get_oid_hex(patch->old_oid_prefix, &oid) ||
3318 get_oid_hex(patch->new_oid_prefix, &oid))
3319 return error(_("cannot apply binary patch to '%s' "
3320 "without full index line"), name);
3321
3322 if (patch->old_name) {
3323 /*
3324 * See if the old one matches what the patch
3325 * applies to.
3326 */
3327 hash_object_file(the_hash_algo, img->buf.buf, img->buf.len,
3328 OBJ_BLOB, &oid);
3329 if (strcmp(oid_to_hex(&oid), patch->old_oid_prefix))
3330 return error(_("the patch applies to '%s' (%s), "
3331 "which does not match the "
3332 "current contents."),
3333 name, oid_to_hex(&oid));
3334 }
3335 else {
3336 /* Otherwise, the old one must be empty. */
3337 if (img->buf.len)
3338 return error(_("the patch applies to an empty "
3339 "'%s' but it is not empty"), name);
3340 }
3341
3342 get_oid_hex(patch->new_oid_prefix, &oid);
3343 if (is_null_oid(&oid)) {
3344 image_clear(img);
3345 return 0; /* deletion patch */
3346 }
3347
3348 if (odb_has_object(the_repository->objects, &oid, 0)) {
3349 /* We already have the postimage */
3350 enum object_type type;
3351 size_t size;
3352 char *result;
3353
3354 result = odb_read_object(the_repository->objects, &oid,
3355 &type, &size);
3356 if (!result)
3357 return error(_("the necessary postimage %s for "
3358 "'%s' cannot be read"),
3359 patch->new_oid_prefix, name);
3360 image_clear(img);
3361 strbuf_attach(&img->buf, result, size, size + 1);
3362 } else {
3363 /*
3364 * We have verified buf matches the preimage;
3365 * apply the patch data to it, which is stored
3366 * in the patch->fragments->{patch,size}.
3367 */
3368 if (apply_binary_fragment(state, img, patch))
3369 return error(_("binary patch does not apply to '%s'"),
3370 name);
3371
3372 /* verify that the result matches */
3373 hash_object_file(the_hash_algo, img->buf.buf, img->buf.len, OBJ_BLOB,
3374 &oid);
3375 if (strcmp(oid_to_hex(&oid), patch->new_oid_prefix))
3376 return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
3377 name, patch->new_oid_prefix, oid_to_hex(&oid));
3378 }
3379
3380 return 0;
3381 }
3382
3383 static int apply_fragments(struct apply_state *state, struct image *img, struct patch *patch)
3384 {
3385 struct fragment *frag = patch->fragments;
3386 const char *name = patch->old_name ? patch->old_name : patch->new_name;
3387 unsigned ws_rule = patch->ws_rule;
3388 unsigned inaccurate_eof = patch->inaccurate_eof;
3389 int nth = 0;
3390
3391 if (patch->is_binary)
3392 return apply_binary(state, img, patch);
3393
3394 while (frag) {
3395 nth++;
3396 if (apply_one_fragment(state, img, frag, inaccurate_eof, ws_rule, nth)) {
3397 error(_("patch failed: %s:%ld"), name, frag->oldpos);
3398 if (!state->apply_with_reject)
3399 return -1;
3400 frag->rejected = 1;
3401 }
3402 frag = frag->next;
3403 }
3404 return 0;
3405 }
3406
3407 static int read_blob_object(struct strbuf *buf, const struct object_id *oid, unsigned mode)
3408 {
3409 if (S_ISGITLINK(mode)) {
3410 strbuf_grow(buf, 100);
3411 strbuf_addf(buf, "Subproject commit %s\n", oid_to_hex(oid));
3412 } else {
3413 enum object_type type;
3414 size_t sz;
3415 char *result;
3416
3417 result = odb_read_object(the_repository->objects, oid,
3418 &type, &sz);
3419 if (!result)
3420 return -1;
3421 /* XXX read_sha1_file NUL-terminates */
3422 strbuf_attach(buf, result, sz, sz + 1);
3423 }
3424 return 0;
3425 }
3426
3427 static int read_file_or_gitlink(const struct cache_entry *ce, struct strbuf *buf)
3428 {
3429 if (!ce)
3430 return 0;
3431 return read_blob_object(buf, &ce->oid, ce->ce_mode);
3432 }
3433
3434 static struct patch *in_fn_table(struct apply_state *state, const char *name)
3435 {
3436 struct string_list_item *item;
3437
3438 if (!name)
3439 return NULL;
3440
3441 item = string_list_lookup(&state->fn_table, name);
3442 if (item)
3443 return (struct patch *)item->util;
3444
3445 return NULL;
3446 }
3447
3448 /*
3449 * item->util in the filename table records the status of the path.
3450 * Usually it points at a patch (whose result records the contents
3451 * of it after applying it), but it could be PATH_WAS_DELETED for a
3452 * path that a previously applied patch has already removed, or
3453 * PATH_TO_BE_DELETED for a path that a later patch would remove.
3454 *
3455 * The latter is needed to deal with a case where two paths A and B
3456 * are swapped by first renaming A to B and then renaming B to A;
3457 * moving A to B should not be prevented due to presence of B as we
3458 * will remove it in a later patch.
3459 */
3460 #define PATH_TO_BE_DELETED ((struct patch *) -2)
3461 #define PATH_WAS_DELETED ((struct patch *) -1)
3462
3463 static int to_be_deleted(struct patch *patch)
3464 {
3465 return patch == PATH_TO_BE_DELETED;
3466 }
3467
3468 static int was_deleted(struct patch *patch)
3469 {
3470 return patch == PATH_WAS_DELETED;
3471 }
3472
3473 static void add_to_fn_table(struct apply_state *state, struct patch *patch)
3474 {
3475 struct string_list_item *item;
3476
3477 /*
3478 * Always add new_name unless patch is a deletion
3479 * This should cover the cases for normal diffs,
3480 * file creations and copies
3481 */
3482 if (patch->new_name) {
3483 item = string_list_insert(&state->fn_table, patch->new_name);
3484 item->util = patch;
3485 }
3486
3487 /*
3488 * store a failure on rename/deletion cases because
3489 * later chunks shouldn't patch old names
3490 */
3491 if ((patch->new_name == NULL) || (patch->is_rename)) {
3492 item = string_list_insert(&state->fn_table, patch->old_name);
3493 item->util = PATH_WAS_DELETED;
3494 }
3495 }
3496
3497 static void prepare_fn_table(struct apply_state *state, struct patch *patch)
3498 {
3499 /*
3500 * store information about incoming file deletion
3501 */
3502 while (patch) {
3503 if ((patch->new_name == NULL) || (patch->is_rename)) {
3504 struct string_list_item *item;
3505 item = string_list_insert(&state->fn_table, patch->old_name);
3506 item->util = PATH_TO_BE_DELETED;
3507 }
3508 patch = patch->next;
3509 }
3510 }
3511
3512 static int checkout_target(struct index_state *istate,
3513 struct cache_entry *ce, struct stat *st)
3514 {
3515 struct checkout costate = CHECKOUT_INIT;
3516
3517 costate.refresh_cache = 1;
3518 costate.istate = istate;
3519 if (checkout_entry(ce, &costate, NULL, NULL) ||
3520 lstat(ce->name, st))
3521 return error(_("cannot checkout %s"), ce->name);
3522 return 0;
3523 }
3524
3525 static struct patch *previous_patch(struct apply_state *state,
3526 struct patch *patch,
3527 int *gone)
3528 {
3529 struct patch *previous;
3530
3531 *gone = 0;
3532 if (patch->is_copy || patch->is_rename)
3533 return NULL; /* "git" patches do not depend on the order */
3534
3535 previous = in_fn_table(state, patch->old_name);
3536 if (!previous)
3537 return NULL;
3538
3539 if (to_be_deleted(previous))
3540 return NULL; /* the deletion hasn't happened yet */
3541
3542 if (was_deleted(previous))
3543 *gone = 1;
3544
3545 return previous;
3546 }
3547
3548 static int verify_index_match(struct apply_state *state,
3549 const struct cache_entry *ce,
3550 struct stat *st)
3551 {
3552 if (S_ISGITLINK(ce->ce_mode)) {
3553 if (!S_ISDIR(st->st_mode))
3554 return -1;
3555 return 0;
3556 }
3557 return ie_match_stat(state->repo->index, ce, st,
3558 CE_MATCH_IGNORE_VALID | CE_MATCH_IGNORE_SKIP_WORKTREE);
3559 }
3560
3561 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
3562
3563 static int load_patch_target(struct apply_state *state,
3564 struct strbuf *buf,
3565 const struct cache_entry *ce,
3566 struct stat *st,
3567 struct patch *patch,
3568 const char *name,
3569 unsigned expected_mode)
3570 {
3571 if (state->cached || state->check_index) {
3572 if (read_file_or_gitlink(ce, buf))
3573 return error(_("failed to read %s"), name);
3574 } else if (name) {
3575 if (S_ISGITLINK(expected_mode)) {
3576 if (ce)
3577 return read_file_or_gitlink(ce, buf);
3578 else
3579 return SUBMODULE_PATCH_WITHOUT_INDEX;
3580 } else if (has_symlink_leading_path(name, strlen(name))) {
3581 return error(_("reading from '%s' beyond a symbolic link"), name);
3582 } else {
3583 if (read_old_data(st, patch, name, buf))
3584 return error(_("failed to read %s"), name);
3585 }
3586 }
3587 return 0;
3588 }
3589
3590 /*
3591 * We are about to apply "patch"; populate the "image" with the
3592 * current version we have, from the working tree or from the index,
3593 * depending on the situation e.g. --cached/--index. If we are
3594 * applying a non-git patch that incrementally updates the tree,
3595 * we read from the result of a previous diff.
3596 */
3597 static int load_preimage(struct apply_state *state,
3598 struct image *image,
3599 struct patch *patch, struct stat *st,
3600 const struct cache_entry *ce)
3601 {
3602 struct strbuf buf = STRBUF_INIT;
3603 size_t len;
3604 char *img;
3605 struct patch *previous;
3606 int status;
3607
3608 previous = previous_patch(state, patch, &status);
3609 if (status)
3610 return error(_("path %s has been renamed/deleted"),
3611 patch->old_name);
3612 if (previous) {
3613 /* We have a patched copy in memory; use that. */
3614 strbuf_add(&buf, previous->result, previous->resultsize);
3615 } else {
3616 status = load_patch_target(state, &buf, ce, st, patch,
3617 patch->old_name, patch->old_mode);
3618 if (status < 0)
3619 return status;
3620 else if (status == SUBMODULE_PATCH_WITHOUT_INDEX) {
3621 /*
3622 * There is no way to apply subproject
3623 * patch without looking at the index.
3624 * NEEDSWORK: shouldn't this be flagged
3625 * as an error???
3626 */
3627 free_fragment_list(patch->fragments);
3628 patch->fragments = NULL;
3629 } else if (status) {
3630 return error(_("failed to read %s"), patch->old_name);
3631 }
3632 }
3633
3634 img = strbuf_detach(&buf, &len);
3635 image_prepare(image, img, len, !patch->is_binary);
3636 return 0;
3637 }
3638
3639 static int resolve_to(struct image *image, const struct object_id *result_id)
3640 {
3641 size_t size;
3642 enum object_type type;
3643 char *data;
3644
3645 image_clear(image);
3646
3647 data = odb_read_object(the_repository->objects, result_id, &type, &size);
3648 if (!data || type != OBJ_BLOB)
3649 die("unable to read blob object %s", oid_to_hex(result_id));
3650 strbuf_attach(&image->buf, data, size, size + 1);
3651
3652 return 0;
3653 }
3654
3655 static int three_way_merge(struct apply_state *state,
3656 struct image *image,
3657 char *path,
3658 const struct object_id *base,
3659 const struct object_id *ours,
3660 const struct object_id *theirs)
3661 {
3662 mmfile_t base_file, our_file, their_file;
3663 struct ll_merge_options merge_opts = LL_MERGE_OPTIONS_INIT;
3664 mmbuffer_t result = { NULL };
3665 enum ll_merge_result status;
3666
3667 /* resolve trivial cases first */
3668 if (oideq(base, ours))
3669 return resolve_to(image, theirs);
3670 else if (oideq(base, theirs) || oideq(ours, theirs))
3671 return resolve_to(image, ours);
3672
3673 read_mmblob(&base_file, the_repository->objects, base);
3674 read_mmblob(&our_file, the_repository->objects, ours);
3675 read_mmblob(&their_file, the_repository->objects, theirs);
3676 merge_opts.variant = state->merge_variant;
3677 status = ll_merge(&result, path,
3678 &base_file, "base",
3679 &our_file, "ours",
3680 &their_file, "theirs",
3681 state->repo->index,
3682 &merge_opts);
3683 if (status == LL_MERGE_BINARY_CONFLICT)
3684 warning("Cannot merge binary files: %s (%s vs. %s)",
3685 path, "ours", "theirs");
3686 free(base_file.ptr);
3687 free(our_file.ptr);
3688 free(their_file.ptr);
3689 if (status < 0 || !result.ptr) {
3690 free(result.ptr);
3691 return -1;
3692 }
3693 image_clear(image);
3694 strbuf_attach(&image->buf, result.ptr, result.size, result.size);
3695
3696 return status;
3697 }
3698
3699 /*
3700 * When directly falling back to add/add three-way merge, we read from
3701 * the current contents of the new_name. In no cases other than that
3702 * this function will be called.
3703 */
3704 static int load_current(struct apply_state *state,
3705 struct image *image,
3706 struct patch *patch)
3707 {
3708 struct strbuf buf = STRBUF_INIT;
3709 int status, pos;
3710 size_t len;
3711 char *img;
3712 struct stat st;
3713 struct cache_entry *ce;
3714 char *name = patch->new_name;
3715 unsigned mode = patch->new_mode;
3716
3717 if (!patch->is_new)
3718 BUG("patch to %s is not a creation", patch->old_name);
3719
3720 pos = index_name_pos(state->repo->index, name, strlen(name));
3721 if (pos < 0)
3722 return error(_("%s: does not exist in index"), name);
3723 ce = state->repo->index->cache[pos];
3724 if (lstat(name, &st)) {
3725 if (errno != ENOENT)
3726 return error_errno("%s", name);
3727 if (checkout_target(state->repo->index, ce, &st))
3728 return -1;
3729 }
3730 if (verify_index_match(state, ce, &st))
3731 return error(_("%s: does not match index"), name);
3732
3733 status = load_patch_target(state, &buf, ce, &st, patch, name, mode);
3734 if (status < 0)
3735 return status;
3736 else if (status)
3737 return -1;
3738 img = strbuf_detach(&buf, &len);
3739 image_prepare(image, img, len, !patch->is_binary);
3740 return 0;
3741 }
3742
3743 static int try_threeway(struct apply_state *state,
3744 struct image *image,
3745 struct patch *patch,
3746 struct stat *st,
3747 const struct cache_entry *ce)
3748 {
3749 struct object_id pre_oid, post_oid, our_oid;
3750 struct strbuf buf = STRBUF_INIT;
3751 size_t len;
3752 int status;
3753 char *img;
3754 struct image tmp_image = IMAGE_INIT;
3755
3756 /* No point falling back to 3-way merge in these cases */
3757 if (patch->is_delete ||
3758 S_ISGITLINK(patch->old_mode) || S_ISGITLINK(patch->new_mode) ||
3759 (patch->is_new && !patch->direct_to_threeway) ||
3760 (patch->is_rename && !patch->lines_added && !patch->lines_deleted))
3761 return -1;
3762
3763 /* Preimage the patch was prepared for */
3764 if (patch->is_new)
3765 odb_write_object(the_repository->objects, "", 0, OBJ_BLOB, &pre_oid);
3766 else if (repo_get_oid(the_repository, patch->old_oid_prefix, &pre_oid) ||
3767 read_blob_object(&buf, &pre_oid, patch->old_mode))
3768 return error(_("repository lacks the necessary blob to perform 3-way merge."));
3769
3770 if (state->apply_verbosity > verbosity_silent && patch->direct_to_threeway)
3771 fprintf(stderr, _("Performing three-way merge...\n"));
3772
3773 img = strbuf_detach(&buf, &len);
3774 image_prepare(&tmp_image, img, len, 1);
3775 /* Apply the patch to get the post image */
3776 if (apply_fragments(state, &tmp_image, patch) < 0) {
3777 image_clear(&tmp_image);
3778 return -1;
3779 }
3780 /* post_oid is theirs */
3781 odb_write_object(the_repository->objects, tmp_image.buf.buf,
3782 tmp_image.buf.len, OBJ_BLOB, &post_oid);
3783 image_clear(&tmp_image);
3784
3785 /* our_oid is ours */
3786 if (patch->is_new) {
3787 if (load_current(state, &tmp_image, patch))
3788 return error(_("cannot read the current contents of '%s'"),
3789 patch->new_name);
3790 } else {
3791 if (load_preimage(state, &tmp_image, patch, st, ce))
3792 return error(_("cannot read the current contents of '%s'"),
3793 patch->old_name);
3794 }
3795 odb_write_object(the_repository->objects, tmp_image.buf.buf,
3796 tmp_image.buf.len, OBJ_BLOB, &our_oid);
3797 image_clear(&tmp_image);
3798
3799 /* in-core three-way merge between post and our using pre as base */
3800 status = three_way_merge(state, image, patch->new_name,
3801 &pre_oid, &our_oid, &post_oid);
3802 if (status < 0) {
3803 if (state->apply_verbosity > verbosity_silent)
3804 fprintf(stderr,
3805 _("Failed to perform three-way merge...\n"));
3806 return status;
3807 }
3808
3809 if (status) {
3810 patch->conflicted_threeway = 1;
3811 if (patch->is_new)
3812 oidclr(&patch->threeway_stage[0], the_repository->hash_algo);
3813 else
3814 oidcpy(&patch->threeway_stage[0], &pre_oid);
3815 oidcpy(&patch->threeway_stage[1], &our_oid);
3816 oidcpy(&patch->threeway_stage[2], &post_oid);
3817 if (state->apply_verbosity > verbosity_silent)
3818 fprintf(stderr,
3819 _("Applied patch to '%s' with conflicts.\n"),
3820 patch->new_name);
3821 } else {
3822 if (state->apply_verbosity > verbosity_silent)
3823 fprintf(stderr,
3824 _("Applied patch to '%s' cleanly.\n"),
3825 patch->new_name);
3826 }
3827 return 0;
3828 }
3829
3830 static int apply_data(struct apply_state *state, struct patch *patch,
3831 struct stat *st, const struct cache_entry *ce)
3832 {
3833 struct image image = IMAGE_INIT;
3834
3835 if (load_preimage(state, &image, patch, st, ce) < 0)
3836 return -1;
3837
3838 if (!state->threeway || try_threeway(state, &image, patch, st, ce) < 0) {
3839 if (state->apply_verbosity > verbosity_silent &&
3840 state->threeway && !patch->direct_to_threeway)
3841 fprintf(stderr, _("Falling back to direct application...\n"));
3842
3843 /* Note: with --reject, apply_fragments() returns 0 */
3844 if (patch->direct_to_threeway || apply_fragments(state, &image, patch) < 0) {
3845 image_clear(&image);
3846 return -1;
3847 }
3848 }
3849 patch->result = strbuf_detach(&image.buf, &patch->resultsize);
3850 add_to_fn_table(state, patch);
3851 free(image.line);
3852
3853 if (0 < patch->is_delete && patch->resultsize)
3854 return error(_("removal patch leaves file contents"));
3855
3856 return 0;
3857 }
3858
3859 /*
3860 * If "patch" that we are looking at modifies or deletes what we have,
3861 * we would want it not to lose any local modification we have, either
3862 * in the working tree or in the index.
3863 *
3864 * This also decides if a non-git patch is a creation patch or a
3865 * modification to an existing empty file. We do not check the state
3866 * of the current tree for a creation patch in this function; the caller
3867 * check_patch() separately makes sure (and errors out otherwise) that
3868 * the path the patch creates does not exist in the current tree.
3869 */
3870 static int check_preimage(struct apply_state *state,
3871 struct patch *patch,
3872 struct cache_entry **ce,
3873 struct stat *st)
3874 {
3875 const char *old_name = patch->old_name;
3876 struct patch *previous = NULL;
3877 int stat_ret = 0, status;
3878 unsigned st_mode = 0;
3879
3880 if (!old_name)
3881 return 0;
3882
3883 assert(patch->is_new <= 0);
3884 previous = previous_patch(state, patch, &status);
3885
3886 if (status)
3887 return error(_("path %s has been renamed/deleted"), old_name);
3888 if (previous) {
3889 st_mode = previous->new_mode;
3890 } else if (!state->cached) {
3891 stat_ret = lstat(old_name, st);
3892 if (stat_ret && errno != ENOENT)
3893 return error_errno("%s", old_name);
3894 }
3895
3896 if (state->check_index && !previous) {
3897 int pos = index_name_pos(state->repo->index, old_name,
3898 strlen(old_name));
3899 if (pos < 0) {
3900 if (patch->is_new < 0)
3901 goto is_new;
3902 return error(_("%s: does not exist in index"), old_name);
3903 }
3904 *ce = state->repo->index->cache[pos];
3905 if (stat_ret < 0) {
3906 if (checkout_target(state->repo->index, *ce, st))
3907 return -1;
3908 }
3909 if (!state->cached && verify_index_match(state, *ce, st))
3910 return error(_("%s: does not match index"), old_name);
3911 if (state->cached)
3912 st_mode = (*ce)->ce_mode;
3913 } else if (stat_ret < 0) {
3914 if (patch->is_new < 0)
3915 goto is_new;
3916 return error_errno("%s", old_name);
3917 }
3918
3919 if (!state->cached && !previous) {
3920 if (*ce && !(*ce)->ce_mode)
3921 BUG("ce_mode == 0 for path '%s'", old_name);
3922
3923 if (repo_trust_executable_bit(state->repo) || !S_ISREG(st->st_mode))
3924 st_mode = ce_mode_from_stat(state->repo, *ce, st->st_mode);
3925 else if (*ce)
3926 st_mode = (*ce)->ce_mode;
3927 else
3928 st_mode = patch->old_mode;
3929 }
3930
3931 if (patch->is_new < 0)
3932 patch->is_new = 0;
3933 if (!patch->old_mode)
3934 patch->old_mode = st_mode;
3935 if ((st_mode ^ patch->old_mode) & S_IFMT)
3936 return error(_("%s: wrong type"), old_name);
3937 if (st_mode != patch->old_mode)
3938 warning(_("%s has type %o, expected %o"),
3939 old_name, st_mode, patch->old_mode);
3940 if (!patch->new_mode && !patch->is_delete)
3941 patch->new_mode = st_mode;
3942 return 0;
3943
3944 is_new:
3945 patch->is_new = 1;
3946 patch->is_delete = 0;
3947 FREE_AND_NULL(patch->old_name);
3948 return 0;
3949 }
3950
3951
3952 #define EXISTS_IN_INDEX 1
3953 #define EXISTS_IN_WORKTREE 2
3954 #define EXISTS_IN_INDEX_AS_ITA 3
3955
3956 static int check_to_create(struct apply_state *state,
3957 const char *new_name,
3958 int ok_if_exists)
3959 {
3960 struct stat nst;
3961
3962 if (state->check_index && (!ok_if_exists || !state->cached)) {
3963 int pos;
3964
3965 pos = index_name_pos(state->repo->index, new_name, strlen(new_name));
3966 if (pos >= 0) {
3967 struct cache_entry *ce = state->repo->index->cache[pos];
3968
3969 /* allow ITA, as they do not yet exist in the index */
3970 if (!ok_if_exists && !(ce->ce_flags & CE_INTENT_TO_ADD))
3971 return EXISTS_IN_INDEX;
3972
3973 /* ITA entries can never match working tree files */
3974 if (!state->cached && (ce->ce_flags & CE_INTENT_TO_ADD))
3975 return EXISTS_IN_INDEX_AS_ITA;
3976 }
3977 }
3978
3979 if (state->cached)
3980 return 0;
3981
3982 if (!lstat(new_name, &nst)) {
3983 if (S_ISDIR(nst.st_mode) || ok_if_exists)
3984 return 0;
3985 /*
3986 * A leading component of new_name might be a symlink
3987 * that is going to be removed with this patch, but
3988 * still pointing at somewhere that has the path.
3989 * In such a case, path "new_name" does not exist as
3990 * far as git is concerned.
3991 */
3992 if (has_symlink_leading_path(new_name, strlen(new_name)))
3993 return 0;
3994
3995 return EXISTS_IN_WORKTREE;
3996 } else if (!is_missing_file_error(errno)) {
3997 return error_errno("%s", new_name);
3998 }
3999 return 0;
4000 }
4001
4002 static void prepare_symlink_changes(struct apply_state *state, struct patch *patch)
4003 {
4004 for ( ; patch; patch = patch->next) {
4005 if ((patch->old_name && S_ISLNK(patch->old_mode)) &&
4006 (patch->is_rename || patch->is_delete))
4007 /* the symlink at patch->old_name is removed */
4008 strset_add(&state->removed_symlinks, patch->old_name);
4009
4010 if (patch->new_name && S_ISLNK(patch->new_mode))
4011 /* the symlink at patch->new_name is created or remains */
4012 strset_add(&state->kept_symlinks, patch->new_name);
4013 }
4014 }
4015
4016 static int path_is_beyond_symlink_1(struct apply_state *state, struct strbuf *name)
4017 {
4018 do {
4019 while (--name->len && name->buf[name->len] != '/')
4020 ; /* scan backwards */
4021 if (!name->len)
4022 break;
4023 name->buf[name->len] = '\0';
4024 if (strset_contains(&state->kept_symlinks, name->buf))
4025 return 1;
4026 if (strset_contains(&state->removed_symlinks, name->buf))
4027 /*
4028 * This cannot be "return 0", because we may
4029 * see a new one created at a higher level.
4030 */
4031 continue;
4032
4033 /* otherwise, check the preimage */
4034 if (state->check_index) {
4035 struct cache_entry *ce;
4036
4037 ce = index_file_exists(state->repo->index, name->buf,
4038 name->len, repo_ignore_case(the_repository));
4039 if (ce && S_ISLNK(ce->ce_mode))
4040 return 1;
4041 } else {
4042 struct stat st;
4043 if (!lstat(name->buf, &st) && S_ISLNK(st.st_mode))
4044 return 1;
4045 }
4046 } while (1);
4047 return 0;
4048 }
4049
4050 static int path_is_beyond_symlink(struct apply_state *state, const char *name_)
4051 {
4052 int ret;
4053 struct strbuf name = STRBUF_INIT;
4054
4055 assert(*name_ != '\0');
4056 strbuf_addstr(&name, name_);
4057 ret = path_is_beyond_symlink_1(state, &name);
4058 strbuf_release(&name);
4059
4060 return ret;
4061 }
4062
4063 static int check_unsafe_path(struct patch *patch)
4064 {
4065 const char *old_name = NULL;
4066 const char *new_name = NULL;
4067 if (patch->is_delete)
4068 old_name = patch->old_name;
4069 else if (!patch->is_new && !patch->is_copy)
4070 old_name = patch->old_name;
4071 if (!patch->is_delete)
4072 new_name = patch->new_name;
4073
4074 if (old_name && !verify_path(old_name, patch->old_mode))
4075 return error(_("invalid path '%s'"), old_name);
4076 if (new_name && !verify_path(new_name, patch->new_mode))
4077 return error(_("invalid path '%s'"), new_name);
4078 return 0;
4079 }
4080
4081 /*
4082 * Check and apply the patch in-core; leave the result in patch->result
4083 * for the caller to write it out to the final destination.
4084 */
4085 static int check_patch(struct apply_state *state, struct patch *patch)
4086 {
4087 struct stat st;
4088 const char *old_name = patch->old_name;
4089 const char *new_name = patch->new_name;
4090 const char *name = old_name ? old_name : new_name;
4091 struct cache_entry *ce = NULL;
4092 struct patch *tpatch;
4093 int ok_if_exists;
4094 int status;
4095
4096 patch->rejected = 1; /* we will drop this after we succeed */
4097
4098 status = check_preimage(state, patch, &ce, &st);
4099 if (status)
4100 return status;
4101 old_name = patch->old_name;
4102
4103 /*
4104 * A type-change diff is always split into a patch to delete
4105 * old, immediately followed by a patch to create new (see
4106 * diff.c::run_diff()); in such a case it is Ok that the entry
4107 * to be deleted by the previous patch is still in the working
4108 * tree and in the index.
4109 *
4110 * A patch to swap-rename between A and B would first rename A
4111 * to B and then rename B to A. While applying the first one,
4112 * the presence of B should not stop A from getting renamed to
4113 * B; ask to_be_deleted() about the later rename. Removal of
4114 * B and rename from A to B is handled the same way by asking
4115 * was_deleted().
4116 */
4117 if ((tpatch = in_fn_table(state, new_name)) &&
4118 (was_deleted(tpatch) || to_be_deleted(tpatch)))
4119 ok_if_exists = 1;
4120 else
4121 ok_if_exists = 0;
4122
4123 if (new_name &&
4124 ((0 < patch->is_new) || patch->is_rename || patch->is_copy)) {
4125 int err = check_to_create(state, new_name, ok_if_exists);
4126
4127 if (err && state->threeway) {
4128 patch->direct_to_threeway = 1;
4129 } else switch (err) {
4130 case 0:
4131 break; /* happy */
4132 case EXISTS_IN_INDEX:
4133 return error(_("%s: already exists in index"), new_name);
4134 case EXISTS_IN_INDEX_AS_ITA:
4135 return error(_("%s: does not match index"), new_name);
4136 case EXISTS_IN_WORKTREE:
4137 return error(_("%s: already exists in working directory"),
4138 new_name);
4139 default:
4140 return err;
4141 }
4142
4143 if (!patch->new_mode) {
4144 if (0 < patch->is_new)
4145 patch->new_mode = S_IFREG | 0644;
4146 else
4147 patch->new_mode = patch->old_mode;
4148 }
4149 }
4150
4151 if (new_name && old_name) {
4152 int same = !strcmp(old_name, new_name);
4153 if (!patch->new_mode)
4154 patch->new_mode = patch->old_mode;
4155 if ((patch->old_mode ^ patch->new_mode) & S_IFMT) {
4156 if (same)
4157 return error(_("new mode (%o) of %s does not "
4158 "match old mode (%o)"),
4159 patch->new_mode, new_name,
4160 patch->old_mode);
4161 else
4162 return error(_("new mode (%o) of %s does not "
4163 "match old mode (%o) of %s"),
4164 patch->new_mode, new_name,
4165 patch->old_mode, old_name);
4166 }
4167 }
4168
4169 if (!state->unsafe_paths && check_unsafe_path(patch))
4170 return -128;
4171
4172 /*
4173 * An attempt to read from or delete a path that is beyond a
4174 * symbolic link will be prevented by load_patch_target() that
4175 * is called at the beginning of apply_data() so we do not
4176 * have to worry about a patch marked with "is_delete" bit
4177 * here. We however need to make sure that the patch result
4178 * is not deposited to a path that is beyond a symbolic link
4179 * here.
4180 */
4181 if (!patch->is_delete && path_is_beyond_symlink(state, patch->new_name))
4182 return error(_("affected file '%s' is beyond a symbolic link"),
4183 patch->new_name);
4184
4185 if (apply_data(state, patch, &st, ce) < 0)
4186 return error(_("%s: patch does not apply"), name);
4187 patch->rejected = 0;
4188 return 0;
4189 }
4190
4191 static int check_patch_list(struct apply_state *state, struct patch *patch)
4192 {
4193 int err = 0;
4194
4195 prepare_symlink_changes(state, patch);
4196 prepare_fn_table(state, patch);
4197 while (patch) {
4198 int res;
4199 if (state->apply_verbosity > verbosity_normal)
4200 say_patch_name(stderr,
4201 _("Checking patch %s..."), patch);
4202 res = check_patch(state, patch);
4203 if (res == -128)
4204 return -128;
4205 err |= res;
4206 patch = patch->next;
4207 }
4208 return err;
4209 }
4210
4211 static int read_apply_cache(struct apply_state *state)
4212 {
4213 if (state->index_file)
4214 return read_index_from(state->repo->index, state->index_file,
4215 repo_get_git_dir(the_repository));
4216 else
4217 return repo_read_index(state->repo);
4218 }
4219
4220 /* This function tries to read the object name from the current index */
4221 static int get_current_oid(struct apply_state *state, const char *path,
4222 struct object_id *oid)
4223 {
4224 int pos;
4225
4226 if (read_apply_cache(state) < 0)
4227 return -1;
4228 pos = index_name_pos(state->repo->index, path, strlen(path));
4229 if (pos < 0)
4230 return -1;
4231 oidcpy(oid, &state->repo->index->cache[pos]->oid);
4232 return 0;
4233 }
4234
4235 static int preimage_oid_in_gitlink_patch(struct patch *p, struct object_id *oid)
4236 {
4237 /*
4238 * A usable gitlink patch has only one fragment (hunk) that looks like:
4239 * @@ -1 +1 @@
4240 * -Subproject commit <old sha1>
4241 * +Subproject commit <new sha1>
4242 * or
4243 * @@ -1 +0,0 @@
4244 * -Subproject commit <old sha1>
4245 * for a removal patch.
4246 */
4247 struct fragment *hunk = p->fragments;
4248 static const char heading[] = "-Subproject commit ";
4249 const char *preimage;
4250
4251 if (/* does the patch have only one hunk? */
4252 hunk && !hunk->next &&
4253 /* is its preimage one line? */
4254 hunk->oldpos == 1 && hunk->oldlines == 1 &&
4255 /* does preimage begin with the heading? */
4256 (preimage = memchr(hunk->patch, '\n', hunk->size)) != NULL &&
4257 starts_with(++preimage, heading) &&
4258 /* does it record full SHA-1? */
4259 !get_oid_hex(preimage + sizeof(heading) - 1, oid) &&
4260 preimage[sizeof(heading) + the_hash_algo->hexsz - 1] == '\n' &&
4261 /* does the abbreviated name on the index line agree with it? */
4262 starts_with(preimage + sizeof(heading) - 1, p->old_oid_prefix))
4263 return 0; /* it all looks fine */
4264
4265 /* we may have full object name on the index line */
4266 return get_oid_hex(p->old_oid_prefix, oid);
4267 }
4268
4269 /* Build an index that contains just the files needed for a 3way merge */
4270 static int build_fake_ancestor(struct apply_state *state, struct patch *list)
4271 {
4272 struct patch *patch;
4273 struct index_state result = INDEX_STATE_INIT(state->repo);
4274 struct lock_file lock = LOCK_INIT;
4275 int res;
4276
4277 /* Once we start supporting the reverse patch, it may be
4278 * worth showing the new sha1 prefix, but until then...
4279 */
4280 for (patch = list; patch; patch = patch->next) {
4281 struct object_id oid;
4282 struct cache_entry *ce;
4283 const char *name;
4284
4285 name = patch->old_name ? patch->old_name : patch->new_name;
4286 if (0 < patch->is_new)
4287 continue;
4288
4289 if (S_ISGITLINK(patch->old_mode)) {
4290 if (!preimage_oid_in_gitlink_patch(patch, &oid))
4291 ; /* ok, the textual part looks sane */
4292 else
4293 return error(_("sha1 information is lacking or "
4294 "useless for submodule %s"), name);
4295 } else if (!repo_get_oid_blob(the_repository, patch->old_oid_prefix, &oid)) {
4296 ; /* ok */
4297 } else if (!patch->lines_added && !patch->lines_deleted) {
4298 /* mode-only change: update the current */
4299 if (get_current_oid(state, patch->old_name, &oid))
4300 return error(_("mode change for %s, which is not "
4301 "in current HEAD"), name);
4302 } else
4303 return error(_("sha1 information is lacking or useless "
4304 "(%s)."), name);
4305
4306 ce = make_cache_entry(&result, patch->old_mode, &oid, name, 0, 0);
4307 if (!ce)
4308 return error(_("make_cache_entry failed for path '%s'"),
4309 name);
4310 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) {
4311 discard_cache_entry(ce);
4312 return error(_("could not add %s to temporary index"),
4313 name);
4314 }
4315 }
4316
4317 repo_hold_lock_file_for_update(state->repo, &lock, state->fake_ancestor,
4318 LOCK_DIE_ON_ERROR);
4319 res = write_locked_index(&result, &lock, COMMIT_LOCK);
4320 discard_index(&result);
4321
4322 if (res)
4323 return error(_("could not write temporary index to %s"),
4324 state->fake_ancestor);
4325
4326 return 0;
4327 }
4328
4329 static void stat_patch_list(struct apply_state *state, struct patch *patch)
4330 {
4331 int files, adds, dels;
4332
4333 for (files = adds = dels = 0 ; patch ; patch = patch->next) {
4334 files++;
4335 adds += patch->lines_added;
4336 dels += patch->lines_deleted;
4337 show_stats(state, patch);
4338 }
4339
4340 print_stat_summary(stdout, files, adds, dels);
4341 }
4342
4343 static void numstat_patch_list(struct apply_state *state,
4344 struct patch *patch)
4345 {
4346 for ( ; patch; patch = patch->next) {
4347 const char *name;
4348 name = patch->new_name ? patch->new_name : patch->old_name;
4349 if (patch->is_binary)
4350 printf("-\t-\t");
4351 else
4352 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
4353 write_name_quoted(name, stdout, state->line_termination);
4354 }
4355 }
4356
4357 static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
4358 {
4359 if (mode)
4360 printf(" %s mode %06o %s\n", newdelete, mode, name);
4361 else
4362 printf(" %s %s\n", newdelete, name);
4363 }
4364
4365 static void show_mode_change(struct patch *p, int show_name)
4366 {
4367 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
4368 if (show_name)
4369 printf(" mode change %06o => %06o %s\n",
4370 p->old_mode, p->new_mode, p->new_name);
4371 else
4372 printf(" mode change %06o => %06o\n",
4373 p->old_mode, p->new_mode);
4374 }
4375 }
4376
4377 static void show_rename_copy(struct patch *p)
4378 {
4379 const char *renamecopy = p->is_rename ? "rename" : "copy";
4380 const char *old_name, *new_name;
4381
4382 /* Find common prefix */
4383 old_name = p->old_name;
4384 new_name = p->new_name;
4385 while (1) {
4386 const char *slash_old, *slash_new;
4387 slash_old = strchr(old_name, '/');
4388 slash_new = strchr(new_name, '/');
4389 if (!slash_old ||
4390 !slash_new ||
4391 slash_old - old_name != slash_new - new_name ||
4392 memcmp(old_name, new_name, slash_new - new_name))
4393 break;
4394 old_name = slash_old + 1;
4395 new_name = slash_new + 1;
4396 }
4397 /* p->old_name through old_name is the common prefix, and old_name and
4398 * new_name through the end of names are renames
4399 */
4400 if (old_name != p->old_name)
4401 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
4402 (int)(old_name - p->old_name), p->old_name,
4403 old_name, new_name, p->score);
4404 else
4405 printf(" %s %s => %s (%d%%)\n", renamecopy,
4406 p->old_name, p->new_name, p->score);
4407 show_mode_change(p, 0);
4408 }
4409
4410 static void summary_patch_list(struct patch *patch)
4411 {
4412 struct patch *p;
4413
4414 for (p = patch; p; p = p->next) {
4415 if (p->is_new)
4416 show_file_mode_name("create", p->new_mode, p->new_name);
4417 else if (p->is_delete)
4418 show_file_mode_name("delete", p->old_mode, p->old_name);
4419 else {
4420 if (p->is_rename || p->is_copy)
4421 show_rename_copy(p);
4422 else {
4423 if (p->score) {
4424 printf(" rewrite %s (%d%%)\n",
4425 p->new_name, p->score);
4426 show_mode_change(p, 0);
4427 }
4428 else
4429 show_mode_change(p, 1);
4430 }
4431 }
4432 }
4433 }
4434
4435 static void patch_stats(struct apply_state *state, struct patch *patch)
4436 {
4437 int lines = patch->lines_added + patch->lines_deleted;
4438
4439 if (lines > state->max_change)
4440 state->max_change = lines;
4441 if (patch->old_name) {
4442 int len = quote_c_style(patch->old_name, NULL, NULL, 0);
4443 if (!len)
4444 len = strlen(patch->old_name);
4445 if (len > state->max_len)
4446 state->max_len = len;
4447 }
4448 if (patch->new_name) {
4449 int len = quote_c_style(patch->new_name, NULL, NULL, 0);
4450 if (!len)
4451 len = strlen(patch->new_name);
4452 if (len > state->max_len)
4453 state->max_len = len;
4454 }
4455 }
4456
4457 static int remove_file(struct apply_state *state, struct patch *patch, int rmdir_empty)
4458 {
4459 if (state->update_index && !state->ita_only) {
4460 if (remove_file_from_index(state->repo->index, patch->old_name) < 0)
4461 return error(_("unable to remove %s from index"), patch->old_name);
4462 }
4463 if (!state->cached) {
4464 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
4465 remove_path(patch->old_name);
4466 }
4467 }
4468 return 0;
4469 }
4470
4471 static int add_index_file(struct apply_state *state,
4472 const char *path,
4473 unsigned mode,
4474 void *buf,
4475 unsigned long size)
4476 {
4477 struct stat st;
4478 struct cache_entry *ce;
4479 int namelen = strlen(path);
4480
4481 ce = make_empty_cache_entry(state->repo->index, namelen);
4482 memcpy(ce->name, path, namelen);
4483 ce->ce_mode = create_ce_mode(mode);
4484 ce->ce_flags = create_ce_flags(0);
4485 ce->ce_namelen = namelen;
4486 if (state->ita_only) {
4487 ce->ce_flags |= CE_INTENT_TO_ADD;
4488 set_object_name_for_intent_to_add_entry(ce);
4489 } else if (S_ISGITLINK(mode)) {
4490 const char *s;
4491
4492 if (!skip_prefix(buf, "Subproject commit ", &s) ||
4493 get_oid_hex(s, &ce->oid)) {
4494 discard_cache_entry(ce);
4495 return error(_("corrupt patch for submodule %s"), path);
4496 }
4497 } else {
4498 if (!state->cached) {
4499 if (lstat(path, &st) < 0) {
4500 discard_cache_entry(ce);
4501 return error_errno(_("unable to stat newly "
4502 "created file '%s'"),
4503 path);
4504 }
4505 fill_stat_cache_info(state->repo->index, ce, &st);
4506 }
4507 if (odb_write_object(the_repository->objects, buf, size,
4508 OBJ_BLOB, &ce->oid) < 0) {
4509 discard_cache_entry(ce);
4510 return error(_("unable to create backing store "
4511 "for newly created file %s"), path);
4512 }
4513 }
4514 if (add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) < 0) {
4515 discard_cache_entry(ce);
4516 return error(_("unable to add cache entry for %s"), path);
4517 }
4518
4519 return 0;
4520 }
4521
4522 /*
4523 * Returns:
4524 * -1 if an unrecoverable error happened
4525 * 0 if everything went well
4526 * 1 if a recoverable error happened
4527 */
4528 static int try_create_file(struct apply_state *state, const char *path,
4529 unsigned int mode, const char *buf,
4530 unsigned long size)
4531 {
4532 int fd, res;
4533 struct strbuf nbuf = STRBUF_INIT;
4534
4535 if (S_ISGITLINK(mode)) {
4536 struct stat st;
4537 if (!lstat(path, &st) && S_ISDIR(st.st_mode))
4538 return 0;
4539 return !!mkdir(path, 0777);
4540 }
4541
4542 if (repo_has_symlinks(state->repo) && S_ISLNK(mode))
4543 /* Although buf:size is counted string, it also is NUL
4544 * terminated.
4545 */
4546 return !!symlink(buf, path);
4547
4548 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
4549 if (fd < 0)
4550 return 1;
4551
4552 if (convert_to_working_tree(state->repo->index, path, buf, size, &nbuf, NULL)) {
4553 size = nbuf.len;
4554 buf = nbuf.buf;
4555 }
4556
4557 res = write_in_full(fd, buf, size) < 0;
4558 if (res)
4559 error_errno(_("failed to write to '%s'"), path);
4560 strbuf_release(&nbuf);
4561
4562 if (close(fd) < 0 && !res)
4563 return error_errno(_("closing file '%s'"), path);
4564
4565 return res ? -1 : 0;
4566 }
4567
4568 /*
4569 * We optimistically assume that the directories exist,
4570 * which is true 99% of the time anyway. If they don't,
4571 * we create them and try again.
4572 *
4573 * Returns:
4574 * -1 on error
4575 * 0 otherwise
4576 */
4577 static int create_one_file(struct apply_state *state,
4578 char *path,
4579 unsigned mode,
4580 const char *buf,
4581 unsigned long size)
4582 {
4583 char *newpath = NULL;
4584 int res;
4585
4586 if (state->cached)
4587 return 0;
4588
4589 /*
4590 * We already try to detect whether files are beyond a symlink in our
4591 * up-front checks. But in the case where symlinks are created by any
4592 * of the intermediate hunks it can happen that our up-front checks
4593 * didn't yet see the symlink, but at the point of arriving here there
4594 * in fact is one. We thus repeat the check for symlinks here.
4595 *
4596 * Note that this does not make the up-front check obsolete as the
4597 * failure mode is different:
4598 *
4599 * - The up-front checks cause us to abort before we have written
4600 * anything into the working directory. So when we exit this way the
4601 * working directory remains clean.
4602 *
4603 * - The checks here happen in the middle of the action where we have
4604 * already started to apply the patch. The end result will be a dirty
4605 * working directory.
4606 *
4607 * Ideally, we should update the up-front checks to catch what would
4608 * happen when we apply the patch before we damage the working tree.
4609 * We have all the information necessary to do so. But for now, as a
4610 * part of embargoed security work, having this check would serve as a
4611 * reasonable first step.
4612 */
4613 if (path_is_beyond_symlink(state, path))
4614 return error(_("affected file '%s' is beyond a symbolic link"), path);
4615
4616 res = try_create_file(state, path, mode, buf, size);
4617 if (res < 0)
4618 return -1;
4619 if (!res)
4620 return 0;
4621
4622 if (errno == ENOENT) {
4623 if (safe_create_leading_directories_no_share(path))
4624 return 0;
4625 res = try_create_file(state, path, mode, buf, size);
4626 if (res < 0)
4627 return -1;
4628 if (!res)
4629 return 0;
4630 }
4631
4632 if (errno == EEXIST || errno == EACCES) {
4633 /* We may be trying to create a file where a directory
4634 * used to be.
4635 */
4636 struct stat st;
4637 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
4638 errno = EEXIST;
4639 }
4640
4641 if (errno == EEXIST) {
4642 unsigned int nr = getpid();
4643
4644 for (;;) {
4645 newpath = mkpathdup("%s~%u", path, nr);
4646 res = try_create_file(state, newpath, mode, buf, size);
4647 if (res < 0)
4648 goto out;
4649 if (!res) {
4650 if (!rename(newpath, path))
4651 goto out;
4652 unlink_or_warn(newpath);
4653 break;
4654 }
4655 if (errno != EEXIST)
4656 break;
4657 ++nr;
4658 FREE_AND_NULL(newpath);
4659 }
4660 }
4661 res = error_errno(_("unable to write file '%s' mode %o"), path, mode);
4662 out:
4663 free(newpath);
4664 return res;
4665 }
4666
4667 static int add_conflicted_stages_file(struct apply_state *state,
4668 struct patch *patch)
4669 {
4670 int stage, namelen;
4671 unsigned mode;
4672 struct cache_entry *ce;
4673
4674 if (!state->update_index)
4675 return 0;
4676 namelen = strlen(patch->new_name);
4677 mode = patch->new_mode ? patch->new_mode : (S_IFREG | 0644);
4678
4679 remove_file_from_index(state->repo->index, patch->new_name);
4680 for (stage = 1; stage < 4; stage++) {
4681 if (is_null_oid(&patch->threeway_stage[stage - 1]))
4682 continue;
4683 ce = make_empty_cache_entry(state->repo->index, namelen);
4684 memcpy(ce->name, patch->new_name, namelen);
4685 ce->ce_mode = create_ce_mode(mode);
4686 ce->ce_flags = create_ce_flags(stage);
4687 ce->ce_namelen = namelen;
4688 oidcpy(&ce->oid, &patch->threeway_stage[stage - 1]);
4689 if (add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) < 0) {
4690 discard_cache_entry(ce);
4691 return error(_("unable to add cache entry for %s"),
4692 patch->new_name);
4693 }
4694 }
4695
4696 return 0;
4697 }
4698
4699 static int create_file(struct apply_state *state, struct patch *patch)
4700 {
4701 char *path = patch->new_name;
4702 unsigned mode = patch->new_mode;
4703 unsigned long size = patch->resultsize;
4704 char *buf = patch->result;
4705
4706 if (!mode)
4707 mode = S_IFREG | 0644;
4708 if (create_one_file(state, path, mode, buf, size))
4709 return -1;
4710
4711 if (patch->conflicted_threeway)
4712 return add_conflicted_stages_file(state, patch);
4713 else if (state->check_index || (state->ita_only && patch->is_new > 0))
4714 return add_index_file(state, path, mode, buf, size);
4715 return 0;
4716 }
4717
4718 /* phase zero is to remove, phase one is to create */
4719 static int write_out_one_result(struct apply_state *state,
4720 struct patch *patch,
4721 int phase)
4722 {
4723 if (patch->is_delete > 0) {
4724 if (phase == 0)
4725 return remove_file(state, patch, 1);
4726 return 0;
4727 }
4728 if (patch->is_new > 0 || patch->is_copy) {
4729 if (phase == 1)
4730 return create_file(state, patch);
4731 return 0;
4732 }
4733 /*
4734 * Rename or modification boils down to the same
4735 * thing: remove the old, write the new
4736 */
4737 if (phase == 0)
4738 return remove_file(state, patch, patch->is_rename);
4739 if (phase == 1)
4740 return create_file(state, patch);
4741 return 0;
4742 }
4743
4744 static int write_out_one_reject(struct apply_state *state, struct patch *patch)
4745 {
4746 FILE *rej;
4747 char *namebuf;
4748 struct fragment *frag;
4749 int fd, cnt = 0;
4750 struct strbuf sb = STRBUF_INIT;
4751
4752 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
4753 if (!frag->rejected)
4754 continue;
4755 cnt++;
4756 }
4757
4758 if (!cnt) {
4759 if (state->apply_verbosity > verbosity_normal)
4760 say_patch_name(stderr,
4761 _("Applied patch %s cleanly."), patch);
4762 return 0;
4763 }
4764
4765 /* This should not happen, because a removal patch that leaves
4766 * contents are marked "rejected" at the patch level.
4767 */
4768 if (!patch->new_name)
4769 die(_("internal error"));
4770
4771 /* Say this even without --verbose */
4772 strbuf_addf(&sb, Q_("Applying patch %%s with %d reject...",
4773 "Applying patch %%s with %d rejects...",
4774 cnt),
4775 cnt);
4776 if (state->apply_verbosity > verbosity_silent)
4777 say_patch_name(stderr, sb.buf, patch);
4778 strbuf_release(&sb);
4779
4780 namebuf = xstrfmt("%s.rej", patch->new_name);
4781
4782 fd = open(namebuf, O_CREAT | O_EXCL | O_WRONLY, 0666);
4783 if (fd < 0) {
4784 if (errno != EEXIST) {
4785 error_errno(_("cannot open %s"), namebuf);
4786 goto error;
4787 }
4788 if (unlink(namebuf)) {
4789 error_errno(_("cannot unlink '%s'"), namebuf);
4790 goto error;
4791 }
4792 fd = open(namebuf, O_CREAT | O_EXCL | O_WRONLY, 0666);
4793 if (fd < 0) {
4794 error_errno(_("cannot open %s"), namebuf);
4795 goto error;
4796 }
4797 }
4798 rej = fdopen(fd, "w");
4799 if (!rej) {
4800 error_errno(_("cannot open %s"), namebuf);
4801 close(fd);
4802 goto error;
4803 }
4804
4805 /* Normal git tools never deal with .rej, so do not pretend
4806 * this is a git patch by saying --git or giving extended
4807 * headers. While at it, maybe please "kompare" that wants
4808 * the trailing TAB and some garbage at the end of line ;-).
4809 */
4810 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
4811 patch->new_name, patch->new_name);
4812 for (cnt = 1, frag = patch->fragments;
4813 frag;
4814 cnt++, frag = frag->next) {
4815 if (!frag->rejected) {
4816 if (state->apply_verbosity > verbosity_silent)
4817 fprintf_ln(stderr, _("Hunk #%d applied cleanly."), cnt);
4818 continue;
4819 }
4820 if (state->apply_verbosity > verbosity_silent)
4821 fprintf_ln(stderr, _("Rejected hunk #%d."), cnt);
4822 fprintf(rej, "%.*s", frag->size, frag->patch);
4823 if (frag->patch[frag->size-1] != '\n')
4824 fputc('\n', rej);
4825 }
4826 fclose(rej);
4827 error:
4828 free(namebuf);
4829 return -1;
4830 }
4831
4832 /*
4833 * Returns:
4834 * -1 if an error happened
4835 * 0 if the patch applied cleanly
4836 * 1 if the patch did not apply cleanly
4837 */
4838 static int write_out_results(struct apply_state *state, struct patch *list)
4839 {
4840 int phase;
4841 int errs = 0;
4842 struct patch *l;
4843 struct string_list cpath = STRING_LIST_INIT_DUP;
4844
4845 for (phase = 0; phase < 2; phase++) {
4846 l = list;
4847 while (l) {
4848 if (l->rejected)
4849 errs = 1;
4850 else {
4851 if (write_out_one_result(state, l, phase)) {
4852 string_list_clear(&cpath, 0);
4853 return -1;
4854 }
4855 if (phase == 1) {
4856 if (write_out_one_reject(state, l))
4857 errs = 1;
4858 if (l->conflicted_threeway) {
4859 string_list_append(&cpath, l->new_name);
4860 errs = 1;
4861 }
4862 }
4863 }
4864 l = l->next;
4865 }
4866 }
4867
4868 if (cpath.nr) {
4869 struct string_list_item *item;
4870
4871 string_list_sort(&cpath);
4872 if (state->apply_verbosity > verbosity_silent) {
4873 for_each_string_list_item(item, &cpath)
4874 fprintf(stderr, "U %s\n", item->string);
4875 }
4876 string_list_clear(&cpath, 0);
4877
4878 /*
4879 * rerere relies on the partially merged result being in the working
4880 * tree with conflict markers, but that isn't written with --cached.
4881 */
4882 if (!state->cached)
4883 repo_rerere(state->repo, 0);
4884 }
4885
4886 return errs;
4887 }
4888
4889 /*
4890 * Try to apply a patch.
4891 *
4892 * Returns:
4893 * -128 if a bad error happened (like patch unreadable)
4894 * -1 if patch did not apply and user cannot deal with it
4895 * 0 if the patch applied
4896 * 1 if the patch did not apply but user might fix it
4897 */
4898 static int apply_patch(struct apply_state *state,
4899 int fd,
4900 const char *filename,
4901 int options)
4902 {
4903 size_t offset;
4904 struct strbuf buf = STRBUF_INIT; /* owns the patch text */
4905 struct patch *list = NULL, **listp = &list;
4906 int skipped_patch = 0;
4907 int res = 0;
4908 int flush_attributes = 0;
4909
4910 state->patch_input_file = filename;
4911 state->linenr = 1;
4912 if (read_patch_file(&buf, fd) < 0) {
4913 res = -128;
4914 goto end;
4915 }
4916 offset = 0;
4917 while (offset < buf.len) {
4918 struct patch *patch;
4919 int nr;
4920
4921 CALLOC_ARRAY(patch, 1);
4922 patch->inaccurate_eof = !!(options & APPLY_OPT_INACCURATE_EOF);
4923 patch->recount = !!(options & APPLY_OPT_RECOUNT);
4924 nr = parse_chunk(state, buf.buf + offset, buf.len - offset, patch);
4925 if (nr < 0) {
4926 free_patch(patch);
4927 if (nr == -128) {
4928 res = -128;
4929 goto end;
4930 }
4931 break;
4932 }
4933 if (state->apply_in_reverse)
4934 reverse_patches(patch);
4935 if (use_patch(state, patch)) {
4936 patch_stats(state, patch);
4937 if (!list || !state->apply_in_reverse) {
4938 *listp = patch;
4939 listp = &patch->next;
4940 } else {
4941 patch->next = list;
4942 list = patch;
4943 }
4944
4945 if ((patch->new_name &&
4946 ends_with_path_components(patch->new_name,
4947 GITATTRIBUTES_FILE)) ||
4948 (patch->old_name &&
4949 ends_with_path_components(patch->old_name,
4950 GITATTRIBUTES_FILE)))
4951 flush_attributes = 1;
4952 }
4953 else {
4954 if (state->apply_verbosity > verbosity_normal)
4955 say_patch_name(stderr, _("Skipped patch '%s'."), patch);
4956 free_patch(patch);
4957 skipped_patch++;
4958 }
4959 offset += nr;
4960 }
4961
4962 if (!list && !skipped_patch) {
4963 if (!state->allow_empty) {
4964 error(_("No valid patches in input (allow with \"--allow-empty\")"));
4965 res = -128;
4966 }
4967 goto end;
4968 }
4969
4970 if (state->whitespace_error && (state->ws_error_action == die_on_ws_error))
4971 state->apply = 0;
4972
4973 state->update_index = (state->check_index || state->ita_only) && state->apply;
4974 if (state->update_index && !is_lock_file_locked(&state->lock_file)) {
4975 if (state->index_file)
4976 repo_hold_lock_file_for_update(state->repo,
4977 &state->lock_file,
4978 state->index_file,
4979 LOCK_DIE_ON_ERROR);
4980 else
4981 repo_hold_locked_index(state->repo, &state->lock_file,
4982 LOCK_DIE_ON_ERROR);
4983 }
4984
4985 if ((state->check_index || state->update_index) && read_apply_cache(state) < 0) {
4986 error(_("unable to read index file"));
4987 res = -128;
4988 goto end;
4989 }
4990
4991 if (state->check || state->apply) {
4992 int r = check_patch_list(state, list);
4993 if (r == -128) {
4994 res = -128;
4995 goto end;
4996 }
4997 if (r < 0 && !state->apply_with_reject) {
4998 res = -1;
4999 goto end;
5000 }
Showing first 5,000 of 5,320 lines. View raw