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