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