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