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