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