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