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