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 * 8 */ 9#include "cache.h" 10#include "cache-tree.h" 11#include "quote.h" 12#include "blob.h" 13#include "delta.h" 14#include "builtin.h" 15#include "string-list.h" 16#include "dir.h" 17#include "parse-options.h" 18 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 */ 28static const char *prefix; 29static int prefix_length = -1; 30static int newfd = -1; 31 32static int unidiff_zero; 33static int p_value = 1; 34static int p_value_known; 35static int check_index; 36static int update_index; 37static int cached; 38static int diffstat; 39static int numstat; 40static int summary; 41static int check; 42static int apply = 1; 43static int apply_in_reverse; 44static int apply_with_reject; 45static int apply_verbosely; 46static int allow_overlap; 47static int no_add; 48static const char *fake_ancestor; 49static int line_termination = '\n'; 50static unsigned int p_context = UINT_MAX; 51static const char * const apply_usage[] = { 52 "git apply [options] [<patch>...]", 53 NULL 54}; 55 56static enum ws_error_action { 57 nowarn_ws_error, 58 warn_on_ws_error, 59 die_on_ws_error, 60 correct_ws_error 61} ws_error_action = warn_on_ws_error; 62static int whitespace_error; 63static int squelch_whitespace_errors = 5; 64static int applied_after_fixing_ws; 65 66static enum ws_ignore { 67 ignore_ws_none, 68 ignore_ws_change 69} ws_ignore_action = ignore_ws_none; 70 71 72static const char *patch_input_file; 73static const char *root; 74static int root_len; 75static int read_stdin = 1; 76static int options; 77 78static void parse_whitespace_option(const char *option) 79{ 80 if (!option) { 81 ws_error_action = warn_on_ws_error; 82 return; 83 } 84 if (!strcmp(option, "warn")) { 85 ws_error_action = warn_on_ws_error; 86 return; 87 } 88 if (!strcmp(option, "nowarn")) { 89 ws_error_action = nowarn_ws_error; 90 return; 91 } 92 if (!strcmp(option, "error")) { 93 ws_error_action = die_on_ws_error; 94 return; 95 } 96 if (!strcmp(option, "error-all")) { 97 ws_error_action = die_on_ws_error; 98 squelch_whitespace_errors = 0; 99 return; 100 } 101 if (!strcmp(option, "strip") || !strcmp(option, "fix")) { 102 ws_error_action = correct_ws_error; 103 return; 104 } 105 die("unrecognized whitespace option '%s'", option); 106} 107 108static void parse_ignorewhitespace_option(const char *option) 109{ 110 if (!option || !strcmp(option, "no") || 111 !strcmp(option, "false") || !strcmp(option, "never") || 112 !strcmp(option, "none")) { 113 ws_ignore_action = ignore_ws_none; 114 return; 115 } 116 if (!strcmp(option, "change")) { 117 ws_ignore_action = ignore_ws_change; 118 return; 119 } 120 die("unrecognized whitespace ignore option '%s'", option); 121} 122 123static void set_default_whitespace_mode(const char *whitespace_option) 124{ 125 if (!whitespace_option && !apply_default_whitespace) 126 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 127} 128 129/* 130 * For "diff-stat" like behaviour, we keep track of the biggest change 131 * we've seen, and the longest filename. That allows us to do simple 132 * scaling. 133 */ 134static int max_change, max_len; 135 136/* 137 * Various "current state", notably line numbers and what 138 * file (and how) we're patching right now.. The "is_xxxx" 139 * things are flags, where -1 means "don't know yet". 140 */ 141static int linenr = 1; 142 143/* 144 * This represents one "hunk" from a patch, starting with 145 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 146 * patch text is pointed at by patch, and its byte length 147 * is stored in size. leading and trailing are the number 148 * of context lines. 149 */ 150struct fragment { 151 unsigned long leading, trailing; 152 unsigned long oldpos, oldlines; 153 unsigned long newpos, newlines; 154 const char *patch; 155 unsigned free_patch:1, 156 rejected:1; 157 int size; 158 int linenr; 159 struct fragment *next; 160}; 161 162/* 163 * When dealing with a binary patch, we reuse "leading" field 164 * to store the type of the binary hunk, either deflated "delta" 165 * or deflated "literal". 166 */ 167#define binary_patch_method leading 168#define BINARY_DELTA_DEFLATED 1 169#define BINARY_LITERAL_DEFLATED 2 170 171/* 172 * This represents a "patch" to a file, both metainfo changes 173 * such as creation/deletion, filemode and content changes represented 174 * as a series of fragments. 175 */ 176struct patch { 177 char *new_name, *old_name, *def_name; 178 unsigned int old_mode, new_mode; 179 int is_new, is_delete; /* -1 = unknown, 0 = false, 1 = true */ 180 int rejected; 181 unsigned ws_rule; 182 unsigned long deflate_origlen; 183 int lines_added, lines_deleted; 184 int score; 185 unsigned int is_toplevel_relative:1; 186 unsigned int inaccurate_eof:1; 187 unsigned int is_binary:1; 188 unsigned int is_copy:1; 189 unsigned int is_rename:1; 190 unsigned int recount:1; 191 struct fragment *fragments; 192 char *result; 193 size_t resultsize; 194 char old_sha1_prefix[41]; 195 char new_sha1_prefix[41]; 196 struct patch *next; 197}; 198 199static void free_patch(struct patch *patch) 200{ 201 struct fragment *fragment = patch->fragments; 202 203 while (fragment) { 204 struct fragment *fragment_next = fragment->next; 205 if (fragment->patch != NULL && fragment->free_patch) 206 free((char *)fragment->patch); 207 free(fragment); 208 fragment = fragment_next; 209 } 210 free(patch); 211} 212 213static void free_patch_list(struct patch *list) 214{ 215 while (list) { 216 struct patch *next = list->next; 217 free_patch(list); 218 list = next; 219 } 220} 221 222/* 223 * A line in a file, len-bytes long (includes the terminating LF, 224 * except for an incomplete line at the end if the file ends with 225 * one), and its contents hashes to 'hash'. 226 */ 227struct line { 228 size_t len; 229 unsigned hash : 24; 230 unsigned flag : 8; 231#define LINE_COMMON 1 232#define LINE_PATCHED 2 233}; 234 235/* 236 * This represents a "file", which is an array of "lines". 237 */ 238struct image { 239 char *buf; 240 size_t len; 241 size_t nr; 242 size_t alloc; 243 struct line *line_allocated; 244 struct line *line; 245}; 246 247/* 248 * Records filenames that have been touched, in order to handle 249 * the case where more than one patches touch the same file. 250 */ 251 252static struct string_list fn_table; 253 254static uint32_t hash_line(const char *cp, size_t len) 255{ 256 size_t i; 257 uint32_t h; 258 for (i = 0, h = 0; i < len; i++) { 259 if (!isspace(cp[i])) { 260 h = h * 3 + (cp[i] & 0xff); 261 } 262 } 263 return h; 264} 265 266/* 267 * Compare lines s1 of length n1 and s2 of length n2, ignoring 268 * whitespace difference. Returns 1 if they match, 0 otherwise 269 */ 270static int fuzzy_matchlines(const char *s1, size_t n1, 271 const char *s2, size_t n2) 272{ 273 const char *last1 = s1 + n1 - 1; 274 const char *last2 = s2 + n2 - 1; 275 int result = 0; 276 277 /* ignore line endings */ 278 while ((*last1 == '\r') || (*last1 == '\n')) 279 last1--; 280 while ((*last2 == '\r') || (*last2 == '\n')) 281 last2--; 282 283 /* skip leading whitespace */ 284 while (isspace(*s1) && (s1 <= last1)) 285 s1++; 286 while (isspace(*s2) && (s2 <= last2)) 287 s2++; 288 /* early return if both lines are empty */ 289 if ((s1 > last1) && (s2 > last2)) 290 return 1; 291 while (!result) { 292 result = *s1++ - *s2++; 293 /* 294 * Skip whitespace inside. We check for whitespace on 295 * both buffers because we don't want "a b" to match 296 * "ab" 297 */ 298 if (isspace(*s1) && isspace(*s2)) { 299 while (isspace(*s1) && s1 <= last1) 300 s1++; 301 while (isspace(*s2) && s2 <= last2) 302 s2++; 303 } 304 /* 305 * If we reached the end on one side only, 306 * lines don't match 307 */ 308 if ( 309 ((s2 > last2) && (s1 <= last1)) || 310 ((s1 > last1) && (s2 <= last2))) 311 return 0; 312 if ((s1 > last1) && (s2 > last2)) 313 break; 314 } 315 316 return !result; 317} 318 319static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag) 320{ 321 ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc); 322 img->line_allocated[img->nr].len = len; 323 img->line_allocated[img->nr].hash = hash_line(bol, len); 324 img->line_allocated[img->nr].flag = flag; 325 img->nr++; 326} 327 328static void prepare_image(struct image *image, char *buf, size_t len, 329 int prepare_linetable) 330{ 331 const char *cp, *ep; 332 333 memset(image, 0, sizeof(*image)); 334 image->buf = buf; 335 image->len = len; 336 337 if (!prepare_linetable) 338 return; 339 340 ep = image->buf + image->len; 341 cp = image->buf; 342 while (cp < ep) { 343 const char *next; 344 for (next = cp; next < ep && *next != '\n'; next++) 345 ; 346 if (next < ep) 347 next++; 348 add_line_info(image, cp, next - cp, 0); 349 cp = next; 350 } 351 image->line = image->line_allocated; 352} 353 354static void clear_image(struct image *image) 355{ 356 free(image->buf); 357 image->buf = NULL; 358 image->len = 0; 359} 360 361static void say_patch_name(FILE *output, const char *pre, 362 struct patch *patch, const char *post) 363{ 364 fputs(pre, output); 365 if (patch->old_name && patch->new_name && 366 strcmp(patch->old_name, patch->new_name)) { 367 quote_c_style(patch->old_name, NULL, output, 0); 368 fputs(" => ", output); 369 quote_c_style(patch->new_name, NULL, output, 0); 370 } else { 371 const char *n = patch->new_name; 372 if (!n) 373 n = patch->old_name; 374 quote_c_style(n, NULL, output, 0); 375 } 376 fputs(post, output); 377} 378 379#define CHUNKSIZE (8192) 380#define SLOP (16) 381 382static void read_patch_file(struct strbuf *sb, int fd) 383{ 384 if (strbuf_read(sb, fd, 0) < 0) 385 die_errno("git apply: failed to read"); 386 387 /* 388 * Make sure that we have some slop in the buffer 389 * so that we can do speculative "memcmp" etc, and 390 * see to it that it is NUL-filled. 391 */ 392 strbuf_grow(sb, SLOP); 393 memset(sb->buf + sb->len, 0, SLOP); 394} 395 396static unsigned long linelen(const char *buffer, unsigned long size) 397{ 398 unsigned long len = 0; 399 while (size--) { 400 len++; 401 if (*buffer++ == '\n') 402 break; 403 } 404 return len; 405} 406 407static int is_dev_null(const char *str) 408{ 409 return !memcmp("/dev/null", str, 9) && isspace(str[9]); 410} 411 412#define TERM_SPACE 1 413#define TERM_TAB 2 414 415static int name_terminate(const char *name, int namelen, int c, int terminate) 416{ 417 if (c == ' ' && !(terminate & TERM_SPACE)) 418 return 0; 419 if (c == '\t' && !(terminate & TERM_TAB)) 420 return 0; 421 422 return 1; 423} 424 425/* remove double slashes to make --index work with such filenames */ 426static char *squash_slash(char *name) 427{ 428 int i = 0, j = 0; 429 430 if (!name) 431 return NULL; 432 433 while (name[i]) { 434 if ((name[j++] = name[i++]) == '/') 435 while (name[i] == '/') 436 i++; 437 } 438 name[j] = '\0'; 439 return name; 440} 441 442static char *find_name_gnu(const char *line, char *def, int p_value) 443{ 444 struct strbuf name = STRBUF_INIT; 445 char *cp; 446 447 /* 448 * Proposed "new-style" GNU patch/diff format; see 449 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2 450 */ 451 if (unquote_c_style(&name, line, NULL)) { 452 strbuf_release(&name); 453 return NULL; 454 } 455 456 for (cp = name.buf; p_value; p_value--) { 457 cp = strchr(cp, '/'); 458 if (!cp) { 459 strbuf_release(&name); 460 return NULL; 461 } 462 cp++; 463 } 464 465 /* name can later be freed, so we need 466 * to memmove, not just return cp 467 */ 468 strbuf_remove(&name, 0, cp - name.buf); 469 free(def); 470 if (root) 471 strbuf_insert(&name, 0, root, root_len); 472 return squash_slash(strbuf_detach(&name, NULL)); 473} 474 475static size_t sane_tz_len(const char *line, size_t len) 476{ 477 const char *tz, *p; 478 479 if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ') 480 return 0; 481 tz = line + len - strlen(" +0500"); 482 483 if (tz[1] != '+' && tz[1] != '-') 484 return 0; 485 486 for (p = tz + 2; p != line + len; p++) 487 if (!isdigit(*p)) 488 return 0; 489 490 return line + len - tz; 491} 492 493static size_t tz_with_colon_len(const char *line, size_t len) 494{ 495 const char *tz, *p; 496 497 if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':') 498 return 0; 499 tz = line + len - strlen(" +08:00"); 500 501 if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-')) 502 return 0; 503 p = tz + 2; 504 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' || 505 !isdigit(*p++) || !isdigit(*p++)) 506 return 0; 507 508 return line + len - tz; 509} 510 511static size_t date_len(const char *line, size_t len) 512{ 513 const char *date, *p; 514 515 if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-') 516 return 0; 517 p = date = line + len - strlen("72-02-05"); 518 519 if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' || 520 !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' || 521 !isdigit(*p++) || !isdigit(*p++)) /* Not a date. */ 522 return 0; 523 524 if (date - line >= strlen("19") && 525 isdigit(date[-1]) && isdigit(date[-2])) /* 4-digit year */ 526 date -= strlen("19"); 527 528 return line + len - date; 529} 530 531static size_t short_time_len(const char *line, size_t len) 532{ 533 const char *time, *p; 534 535 if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':') 536 return 0; 537 p = time = line + len - strlen(" 07:01:32"); 538 539 /* Permit 1-digit hours? */ 540 if (*p++ != ' ' || 541 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' || 542 !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' || 543 !isdigit(*p++) || !isdigit(*p++)) /* Not a time. */ 544 return 0; 545 546 return line + len - time; 547} 548 549static size_t fractional_time_len(const char *line, size_t len) 550{ 551 const char *p; 552 size_t n; 553 554 /* Expected format: 19:41:17.620000023 */ 555 if (!len || !isdigit(line[len - 1])) 556 return 0; 557 p = line + len - 1; 558 559 /* Fractional seconds. */ 560 while (p > line && isdigit(*p)) 561 p--; 562 if (*p != '.') 563 return 0; 564 565 /* Hours, minutes, and whole seconds. */ 566 n = short_time_len(line, p - line); 567 if (!n) 568 return 0; 569 570 return line + len - p + n; 571} 572 573static size_t trailing_spaces_len(const char *line, size_t len) 574{ 575 const char *p; 576 577 /* Expected format: ' ' x (1 or more) */ 578 if (!len || line[len - 1] != ' ') 579 return 0; 580 581 p = line + len; 582 while (p != line) { 583 p--; 584 if (*p != ' ') 585 return line + len - (p + 1); 586 } 587 588 /* All spaces! */ 589 return len; 590} 591 592static size_t diff_timestamp_len(const char *line, size_t len) 593{ 594 const char *end = line + len; 595 size_t n; 596 597 /* 598 * Posix: 2010-07-05 19:41:17 599 * GNU: 2010-07-05 19:41:17.620000023 -0500 600 */ 601 602 if (!isdigit(end[-1])) 603 return 0; 604 605 n = sane_tz_len(line, end - line); 606 if (!n) 607 n = tz_with_colon_len(line, end - line); 608 end -= n; 609 610 n = short_time_len(line, end - line); 611 if (!n) 612 n = fractional_time_len(line, end - line); 613 end -= n; 614 615 n = date_len(line, end - line); 616 if (!n) /* No date. Too bad. */ 617 return 0; 618 end -= n; 619 620 if (end == line) /* No space before date. */ 621 return 0; 622 if (end[-1] == '\t') { /* Success! */ 623 end--; 624 return line + len - end; 625 } 626 if (end[-1] != ' ') /* No space before date. */ 627 return 0; 628 629 /* Whitespace damage. */ 630 end -= trailing_spaces_len(line, end - line); 631 return line + len - end; 632} 633 634static char *find_name_common(const char *line, char *def, int p_value, 635 const char *end, int terminate) 636{ 637 int len; 638 const char *start = NULL; 639 640 if (p_value == 0) 641 start = line; 642 while (line != end) { 643 char c = *line; 644 645 if (!end && isspace(c)) { 646 if (c == '\n') 647 break; 648 if (name_terminate(start, line-start, c, terminate)) 649 break; 650 } 651 line++; 652 if (c == '/' && !--p_value) 653 start = line; 654 } 655 if (!start) 656 return squash_slash(def); 657 len = line - start; 658 if (!len) 659 return squash_slash(def); 660 661 /* 662 * Generally we prefer the shorter name, especially 663 * if the other one is just a variation of that with 664 * something else tacked on to the end (ie "file.orig" 665 * or "file~"). 666 */ 667 if (def) { 668 int deflen = strlen(def); 669 if (deflen < len && !strncmp(start, def, deflen)) 670 return squash_slash(def); 671 free(def); 672 } 673 674 if (root) { 675 char *ret = xmalloc(root_len + len + 1); 676 strcpy(ret, root); 677 memcpy(ret + root_len, start, len); 678 ret[root_len + len] = '\0'; 679 return squash_slash(ret); 680 } 681 682 return squash_slash(xmemdupz(start, len)); 683} 684 685static char *find_name(const char *line, char *def, int p_value, int terminate) 686{ 687 if (*line == '"') { 688 char *name = find_name_gnu(line, def, p_value); 689 if (name) 690 return name; 691 } 692 693 return find_name_common(line, def, p_value, NULL, terminate); 694} 695 696static char *find_name_traditional(const char *line, char *def, int p_value) 697{ 698 size_t len = strlen(line); 699 size_t date_len; 700 701 if (*line == '"') { 702 char *name = find_name_gnu(line, def, p_value); 703 if (name) 704 return name; 705 } 706 707 len = strchrnul(line, '\n') - line; 708 date_len = diff_timestamp_len(line, len); 709 if (!date_len) 710 return find_name_common(line, def, p_value, NULL, TERM_TAB); 711 len -= date_len; 712 713 return find_name_common(line, def, p_value, line + len, 0); 714} 715 716static int count_slashes(const char *cp) 717{ 718 int cnt = 0; 719 char ch; 720 721 while ((ch = *cp++)) 722 if (ch == '/') 723 cnt++; 724 return cnt; 725} 726 727/* 728 * Given the string after "--- " or "+++ ", guess the appropriate 729 * p_value for the given patch. 730 */ 731static int guess_p_value(const char *nameline) 732{ 733 char *name, *cp; 734 int val = -1; 735 736 if (is_dev_null(nameline)) 737 return -1; 738 name = find_name_traditional(nameline, NULL, 0); 739 if (!name) 740 return -1; 741 cp = strchr(name, '/'); 742 if (!cp) 743 val = 0; 744 else if (prefix) { 745 /* 746 * Does it begin with "a/$our-prefix" and such? Then this is 747 * very likely to apply to our directory. 748 */ 749 if (!strncmp(name, prefix, prefix_length)) 750 val = count_slashes(prefix); 751 else { 752 cp++; 753 if (!strncmp(cp, prefix, prefix_length)) 754 val = count_slashes(prefix) + 1; 755 } 756 } 757 free(name); 758 return val; 759} 760 761/* 762 * Does the ---/+++ line has the POSIX timestamp after the last HT? 763 * GNU diff puts epoch there to signal a creation/deletion event. Is 764 * this such a timestamp? 765 */ 766static int has_epoch_timestamp(const char *nameline) 767{ 768 /* 769 * We are only interested in epoch timestamp; any non-zero 770 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 771 * For the same reason, the date must be either 1969-12-31 or 772 * 1970-01-01, and the seconds part must be "00". 773 */ 774 const char stamp_regexp[] = 775 "^(1969-12-31|1970-01-01)" 776 " " 777 "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 778 " " 779 "([-+][0-2][0-9]:?[0-5][0-9])\n"; 780 const char *timestamp = NULL, *cp, *colon; 781 static regex_t *stamp; 782 regmatch_t m[10]; 783 int zoneoffset; 784 int hourminute; 785 int status; 786 787 for (cp = nameline; *cp != '\n'; cp++) { 788 if (*cp == '\t') 789 timestamp = cp + 1; 790 } 791 if (!timestamp) 792 return 0; 793 if (!stamp) { 794 stamp = xmalloc(sizeof(*stamp)); 795 if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 796 warning("Cannot prepare timestamp regexp %s", 797 stamp_regexp); 798 return 0; 799 } 800 } 801 802 status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0); 803 if (status) { 804 if (status != REG_NOMATCH) 805 warning("regexec returned %d for input: %s", 806 status, timestamp); 807 return 0; 808 } 809 810 zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10); 811 if (*colon == ':') 812 zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10); 813 else 814 zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100); 815 if (timestamp[m[3].rm_so] == '-') 816 zoneoffset = -zoneoffset; 817 818 /* 819 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 820 * (west of GMT) or 1970-01-01 (east of GMT) 821 */ 822 if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) || 823 (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10))) 824 return 0; 825 826 hourminute = (strtol(timestamp + 11, NULL, 10) * 60 + 827 strtol(timestamp + 14, NULL, 10) - 828 zoneoffset); 829 830 return ((zoneoffset < 0 && hourminute == 1440) || 831 (0 <= zoneoffset && !hourminute)); 832} 833 834/* 835 * Get the name etc info from the ---/+++ lines of a traditional patch header 836 * 837 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 838 * files, we can happily check the index for a match, but for creating a 839 * new file we should try to match whatever "patch" does. I have no idea. 840 */ 841static void parse_traditional_patch(const char *first, const char *second, struct patch *patch) 842{ 843 char *name; 844 845 first += 4; /* skip "--- " */ 846 second += 4; /* skip "+++ " */ 847 if (!p_value_known) { 848 int p, q; 849 p = guess_p_value(first); 850 q = guess_p_value(second); 851 if (p < 0) p = q; 852 if (0 <= p && p == q) { 853 p_value = p; 854 p_value_known = 1; 855 } 856 } 857 if (is_dev_null(first)) { 858 patch->is_new = 1; 859 patch->is_delete = 0; 860 name = find_name_traditional(second, NULL, p_value); 861 patch->new_name = name; 862 } else if (is_dev_null(second)) { 863 patch->is_new = 0; 864 patch->is_delete = 1; 865 name = find_name_traditional(first, NULL, p_value); 866 patch->old_name = name; 867 } else { 868 name = find_name_traditional(first, NULL, p_value); 869 name = find_name_traditional(second, name, p_value); 870 if (has_epoch_timestamp(first)) { 871 patch->is_new = 1; 872 patch->is_delete = 0; 873 patch->new_name = name; 874 } else if (has_epoch_timestamp(second)) { 875 patch->is_new = 0; 876 patch->is_delete = 1; 877 patch->old_name = name; 878 } else { 879 patch->old_name = patch->new_name = name; 880 } 881 } 882 if (!name) 883 die("unable to find filename in patch at line %d", linenr); 884} 885 886static int gitdiff_hdrend(const char *line, struct patch *patch) 887{ 888 return -1; 889} 890 891/* 892 * We're anal about diff header consistency, to make 893 * sure that we don't end up having strange ambiguous 894 * patches floating around. 895 * 896 * As a result, gitdiff_{old|new}name() will check 897 * their names against any previous information, just 898 * to make sure.. 899 */ 900static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew) 901{ 902 if (!orig_name && !isnull) 903 return find_name(line, NULL, p_value, TERM_TAB); 904 905 if (orig_name) { 906 int len; 907 const char *name; 908 char *another; 909 name = orig_name; 910 len = strlen(name); 911 if (isnull) 912 die("git apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr); 913 another = find_name(line, NULL, p_value, TERM_TAB); 914 if (!another || memcmp(another, name, len + 1)) 915 die("git apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr); 916 free(another); 917 return orig_name; 918 } 919 else { 920 /* expect "/dev/null" */ 921 if (memcmp("/dev/null", line, 9) || line[9] != '\n') 922 die("git apply: bad git-diff - expected /dev/null on line %d", linenr); 923 return NULL; 924 } 925} 926 927static int gitdiff_oldname(const char *line, struct patch *patch) 928{ 929 patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old"); 930 return 0; 931} 932 933static int gitdiff_newname(const char *line, struct patch *patch) 934{ 935 patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new"); 936 return 0; 937} 938 939static int gitdiff_oldmode(const char *line, struct patch *patch) 940{ 941 patch->old_mode = strtoul(line, NULL, 8); 942 return 0; 943} 944 945static int gitdiff_newmode(const char *line, struct patch *patch) 946{ 947 patch->new_mode = strtoul(line, NULL, 8); 948 return 0; 949} 950 951static int gitdiff_delete(const char *line, struct patch *patch) 952{ 953 patch->is_delete = 1; 954 patch->old_name = patch->def_name; 955 return gitdiff_oldmode(line, patch); 956} 957 958static int gitdiff_newfile(const char *line, struct patch *patch) 959{ 960 patch->is_new = 1; 961 patch->new_name = patch->def_name; 962 return gitdiff_newmode(line, patch); 963} 964 965static int gitdiff_copysrc(const char *line, struct patch *patch) 966{ 967 patch->is_copy = 1; 968 patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0); 969 return 0; 970} 971 972static int gitdiff_copydst(const char *line, struct patch *patch) 973{ 974 patch->is_copy = 1; 975 patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0); 976 return 0; 977} 978 979static int gitdiff_renamesrc(const char *line, struct patch *patch) 980{ 981 patch->is_rename = 1; 982 patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0); 983 return 0; 984} 985 986static int gitdiff_renamedst(const char *line, struct patch *patch) 987{ 988 patch->is_rename = 1; 989 patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0); 990 return 0; 991} 992 993static int gitdiff_similarity(const char *line, struct patch *patch) 994{ 995 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX) 996 patch->score = 0; 997 return 0; 998} 9991000static int gitdiff_dissimilarity(const char *line, struct patch *patch)1001{1002 if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)1003 patch->score = 0;1004 return 0;1005}10061007static int gitdiff_index(const char *line, struct patch *patch)1008{1009 /*1010 * index line is N hexadecimal, "..", N hexadecimal,1011 * and optional space with octal mode.1012 */1013 const char *ptr, *eol;1014 int len;10151016 ptr = strchr(line, '.');1017 if (!ptr || ptr[1] != '.' || 40 < ptr - line)1018 return 0;1019 len = ptr - line;1020 memcpy(patch->old_sha1_prefix, line, len);1021 patch->old_sha1_prefix[len] = 0;10221023 line = ptr + 2;1024 ptr = strchr(line, ' ');1025 eol = strchr(line, '\n');10261027 if (!ptr || eol < ptr)1028 ptr = eol;1029 len = ptr - line;10301031 if (40 < len)1032 return 0;1033 memcpy(patch->new_sha1_prefix, line, len);1034 patch->new_sha1_prefix[len] = 0;1035 if (*ptr == ' ')1036 patch->old_mode = strtoul(ptr+1, NULL, 8);1037 return 0;1038}10391040/*1041 * This is normal for a diff that doesn't change anything: we'll fall through1042 * into the next diff. Tell the parser to break out.1043 */1044static int gitdiff_unrecognized(const char *line, struct patch *patch)1045{1046 return -1;1047}10481049static const char *stop_at_slash(const char *line, int llen)1050{1051 int nslash = p_value;1052 int i;10531054 for (i = 0; i < llen; i++) {1055 int ch = line[i];1056 if (ch == '/' && --nslash <= 0)1057 return &line[i];1058 }1059 return NULL;1060}10611062/*1063 * This is to extract the same name that appears on "diff --git"1064 * line. We do not find and return anything if it is a rename1065 * patch, and it is OK because we will find the name elsewhere.1066 * We need to reliably find name only when it is mode-change only,1067 * creation or deletion of an empty file. In any of these cases,1068 * both sides are the same name under a/ and b/ respectively.1069 */1070static char *git_header_name(char *line, int llen)1071{1072 const char *name;1073 const char *second = NULL;1074 size_t len, line_len;10751076 line += strlen("diff --git ");1077 llen -= strlen("diff --git ");10781079 if (*line == '"') {1080 const char *cp;1081 struct strbuf first = STRBUF_INIT;1082 struct strbuf sp = STRBUF_INIT;10831084 if (unquote_c_style(&first, line, &second))1085 goto free_and_fail1;10861087 /* advance to the first slash */1088 cp = stop_at_slash(first.buf, first.len);1089 /* we do not accept absolute paths */1090 if (!cp || cp == first.buf)1091 goto free_and_fail1;1092 strbuf_remove(&first, 0, cp + 1 - first.buf);10931094 /*1095 * second points at one past closing dq of name.1096 * find the second name.1097 */1098 while ((second < line + llen) && isspace(*second))1099 second++;11001101 if (line + llen <= second)1102 goto free_and_fail1;1103 if (*second == '"') {1104 if (unquote_c_style(&sp, second, NULL))1105 goto free_and_fail1;1106 cp = stop_at_slash(sp.buf, sp.len);1107 if (!cp || cp == sp.buf)1108 goto free_and_fail1;1109 /* They must match, otherwise ignore */1110 if (strcmp(cp + 1, first.buf))1111 goto free_and_fail1;1112 strbuf_release(&sp);1113 return strbuf_detach(&first, NULL);1114 }11151116 /* unquoted second */1117 cp = stop_at_slash(second, line + llen - second);1118 if (!cp || cp == second)1119 goto free_and_fail1;1120 cp++;1121 if (line + llen - cp != first.len + 1 ||1122 memcmp(first.buf, cp, first.len))1123 goto free_and_fail1;1124 return strbuf_detach(&first, NULL);11251126 free_and_fail1:1127 strbuf_release(&first);1128 strbuf_release(&sp);1129 return NULL;1130 }11311132 /* unquoted first name */1133 name = stop_at_slash(line, llen);1134 if (!name || name == line)1135 return NULL;1136 name++;11371138 /*1139 * since the first name is unquoted, a dq if exists must be1140 * the beginning of the second name.1141 */1142 for (second = name; second < line + llen; second++) {1143 if (*second == '"') {1144 struct strbuf sp = STRBUF_INIT;1145 const char *np;11461147 if (unquote_c_style(&sp, second, NULL))1148 goto free_and_fail2;11491150 np = stop_at_slash(sp.buf, sp.len);1151 if (!np || np == sp.buf)1152 goto free_and_fail2;1153 np++;11541155 len = sp.buf + sp.len - np;1156 if (len < second - name &&1157 !strncmp(np, name, len) &&1158 isspace(name[len])) {1159 /* Good */1160 strbuf_remove(&sp, 0, np - sp.buf);1161 return strbuf_detach(&sp, NULL);1162 }11631164 free_and_fail2:1165 strbuf_release(&sp);1166 return NULL;1167 }1168 }11691170 /*1171 * Accept a name only if it shows up twice, exactly the same1172 * form.1173 */1174 second = strchr(name, '\n');1175 if (!second)1176 return NULL;1177 line_len = second - name;1178 for (len = 0 ; ; len++) {1179 switch (name[len]) {1180 default:1181 continue;1182 case '\n':1183 return NULL;1184 case '\t': case ' ':1185 second = stop_at_slash(name + len, line_len - len);1186 if (!second)1187 return NULL;1188 second++;1189 if (second[len] == '\n' && !strncmp(name, second, len)) {1190 return xmemdupz(name, len);1191 }1192 }1193 }1194}11951196/* Verify that we recognize the lines following a git header */1197static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)1198{1199 unsigned long offset;12001201 /* A git diff has explicit new/delete information, so we don't guess */1202 patch->is_new = 0;1203 patch->is_delete = 0;12041205 /*1206 * Some things may not have the old name in the1207 * rest of the headers anywhere (pure mode changes,1208 * or removing or adding empty files), so we get1209 * the default name from the header.1210 */1211 patch->def_name = git_header_name(line, len);1212 if (patch->def_name && root) {1213 char *s = xmalloc(root_len + strlen(patch->def_name) + 1);1214 strcpy(s, root);1215 strcpy(s + root_len, patch->def_name);1216 free(patch->def_name);1217 patch->def_name = s;1218 }12191220 line += len;1221 size -= len;1222 linenr++;1223 for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {1224 static const struct opentry {1225 const char *str;1226 int (*fn)(const char *, struct patch *);1227 } optable[] = {1228 { "@@ -", gitdiff_hdrend },1229 { "--- ", gitdiff_oldname },1230 { "+++ ", gitdiff_newname },1231 { "old mode ", gitdiff_oldmode },1232 { "new mode ", gitdiff_newmode },1233 { "deleted file mode ", gitdiff_delete },1234 { "new file mode ", gitdiff_newfile },1235 { "copy from ", gitdiff_copysrc },1236 { "copy to ", gitdiff_copydst },1237 { "rename old ", gitdiff_renamesrc },1238 { "rename new ", gitdiff_renamedst },1239 { "rename from ", gitdiff_renamesrc },1240 { "rename to ", gitdiff_renamedst },1241 { "similarity index ", gitdiff_similarity },1242 { "dissimilarity index ", gitdiff_dissimilarity },1243 { "index ", gitdiff_index },1244 { "", gitdiff_unrecognized },1245 };1246 int i;12471248 len = linelen(line, size);1249 if (!len || line[len-1] != '\n')1250 break;1251 for (i = 0; i < ARRAY_SIZE(optable); i++) {1252 const struct opentry *p = optable + i;1253 int oplen = strlen(p->str);1254 if (len < oplen || memcmp(p->str, line, oplen))1255 continue;1256 if (p->fn(line + oplen, patch) < 0)1257 return offset;1258 break;1259 }1260 }12611262 return offset;1263}12641265static int parse_num(const char *line, unsigned long *p)1266{1267 char *ptr;12681269 if (!isdigit(*line))1270 return 0;1271 *p = strtoul(line, &ptr, 10);1272 return ptr - line;1273}12741275static int parse_range(const char *line, int len, int offset, const char *expect,1276 unsigned long *p1, unsigned long *p2)1277{1278 int digits, ex;12791280 if (offset < 0 || offset >= len)1281 return -1;1282 line += offset;1283 len -= offset;12841285 digits = parse_num(line, p1);1286 if (!digits)1287 return -1;12881289 offset += digits;1290 line += digits;1291 len -= digits;12921293 *p2 = 1;1294 if (*line == ',') {1295 digits = parse_num(line+1, p2);1296 if (!digits)1297 return -1;12981299 offset += digits+1;1300 line += digits+1;1301 len -= digits+1;1302 }13031304 ex = strlen(expect);1305 if (ex > len)1306 return -1;1307 if (memcmp(line, expect, ex))1308 return -1;13091310 return offset + ex;1311}13121313static void recount_diff(char *line, int size, struct fragment *fragment)1314{1315 int oldlines = 0, newlines = 0, ret = 0;13161317 if (size < 1) {1318 warning("recount: ignore empty hunk");1319 return;1320 }13211322 for (;;) {1323 int len = linelen(line, size);1324 size -= len;1325 line += len;13261327 if (size < 1)1328 break;13291330 switch (*line) {1331 case ' ': case '\n':1332 newlines++;1333 /* fall through */1334 case '-':1335 oldlines++;1336 continue;1337 case '+':1338 newlines++;1339 continue;1340 case '\\':1341 continue;1342 case '@':1343 ret = size < 3 || prefixcmp(line, "@@ ");1344 break;1345 case 'd':1346 ret = size < 5 || prefixcmp(line, "diff ");1347 break;1348 default:1349 ret = -1;1350 break;1351 }1352 if (ret) {1353 warning("recount: unexpected line: %.*s",1354 (int)linelen(line, size), line);1355 return;1356 }1357 break;1358 }1359 fragment->oldlines = oldlines;1360 fragment->newlines = newlines;1361}13621363/*1364 * Parse a unified diff fragment header of the1365 * form "@@ -a,b +c,d @@"1366 */1367static int parse_fragment_header(char *line, int len, struct fragment *fragment)1368{1369 int offset;13701371 if (!len || line[len-1] != '\n')1372 return -1;13731374 /* Figure out the number of lines in a fragment */1375 offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);1376 offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);13771378 return offset;1379}13801381static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)1382{1383 unsigned long offset, len;13841385 patch->is_toplevel_relative = 0;1386 patch->is_rename = patch->is_copy = 0;1387 patch->is_new = patch->is_delete = -1;1388 patch->old_mode = patch->new_mode = 0;1389 patch->old_name = patch->new_name = NULL;1390 for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {1391 unsigned long nextlen;13921393 len = linelen(line, size);1394 if (!len)1395 break;13961397 /* Testing this early allows us to take a few shortcuts.. */1398 if (len < 6)1399 continue;14001401 /*1402 * Make sure we don't find any unconnected patch fragments.1403 * That's a sign that we didn't find a header, and that a1404 * patch has become corrupted/broken up.1405 */1406 if (!memcmp("@@ -", line, 4)) {1407 struct fragment dummy;1408 if (parse_fragment_header(line, len, &dummy) < 0)1409 continue;1410 die("patch fragment without header at line %d: %.*s",1411 linenr, (int)len-1, line);1412 }14131414 if (size < len + 6)1415 break;14161417 /*1418 * Git patch? It might not have a real patch, just a rename1419 * or mode change, so we handle that specially1420 */1421 if (!memcmp("diff --git ", line, 11)) {1422 int git_hdr_len = parse_git_header(line, len, size, patch);1423 if (git_hdr_len <= len)1424 continue;1425 if (!patch->old_name && !patch->new_name) {1426 if (!patch->def_name)1427 die("git diff header lacks filename information when removing "1428 "%d leading pathname components (line %d)" , p_value, linenr);1429 patch->old_name = patch->new_name = patch->def_name;1430 }1431 if (!patch->is_delete && !patch->new_name)1432 die("git diff header lacks filename information "1433 "(line %d)", linenr);1434 patch->is_toplevel_relative = 1;1435 *hdrsize = git_hdr_len;1436 return offset;1437 }14381439 /* --- followed by +++ ? */1440 if (memcmp("--- ", line, 4) || memcmp("+++ ", line + len, 4))1441 continue;14421443 /*1444 * We only accept unified patches, so we want it to1445 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1446 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1447 */1448 nextlen = linelen(line + len, size - len);1449 if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))1450 continue;14511452 /* Ok, we'll consider it a patch */1453 parse_traditional_patch(line, line+len, patch);1454 *hdrsize = len + nextlen;1455 linenr += 2;1456 return offset;1457 }1458 return -1;1459}14601461static void record_ws_error(unsigned result, const char *line, int len, int linenr)1462{1463 char *err;14641465 if (!result)1466 return;14671468 whitespace_error++;1469 if (squelch_whitespace_errors &&1470 squelch_whitespace_errors < whitespace_error)1471 return;14721473 err = whitespace_error_string(result);1474 fprintf(stderr, "%s:%d: %s.\n%.*s\n",1475 patch_input_file, linenr, err, len, line);1476 free(err);1477}14781479static void check_whitespace(const char *line, int len, unsigned ws_rule)1480{1481 unsigned result = ws_check(line + 1, len - 1, ws_rule);14821483 record_ws_error(result, line + 1, len - 2, linenr);1484}14851486/*1487 * Parse a unified diff. Note that this really needs to parse each1488 * fragment separately, since the only way to know the difference1489 * between a "---" that is part of a patch, and a "---" that starts1490 * the next patch is to look at the line counts..1491 */1492static int parse_fragment(char *line, unsigned long size,1493 struct patch *patch, struct fragment *fragment)1494{1495 int added, deleted;1496 int len = linelen(line, size), offset;1497 unsigned long oldlines, newlines;1498 unsigned long leading, trailing;14991500 offset = parse_fragment_header(line, len, fragment);1501 if (offset < 0)1502 return -1;1503 if (offset > 0 && patch->recount)1504 recount_diff(line + offset, size - offset, fragment);1505 oldlines = fragment->oldlines;1506 newlines = fragment->newlines;1507 leading = 0;1508 trailing = 0;15091510 /* Parse the thing.. */1511 line += len;1512 size -= len;1513 linenr++;1514 added = deleted = 0;1515 for (offset = len;1516 0 < size;1517 offset += len, size -= len, line += len, linenr++) {1518 if (!oldlines && !newlines)1519 break;1520 len = linelen(line, size);1521 if (!len || line[len-1] != '\n')1522 return -1;1523 switch (*line) {1524 default:1525 return -1;1526 case '\n': /* newer GNU diff, an empty context line */1527 case ' ':1528 oldlines--;1529 newlines--;1530 if (!deleted && !added)1531 leading++;1532 trailing++;1533 break;1534 case '-':1535 if (apply_in_reverse &&1536 ws_error_action != nowarn_ws_error)1537 check_whitespace(line, len, patch->ws_rule);1538 deleted++;1539 oldlines--;1540 trailing = 0;1541 break;1542 case '+':1543 if (!apply_in_reverse &&1544 ws_error_action != nowarn_ws_error)1545 check_whitespace(line, len, patch->ws_rule);1546 added++;1547 newlines--;1548 trailing = 0;1549 break;15501551 /*1552 * We allow "\ No newline at end of file". Depending1553 * on locale settings when the patch was produced we1554 * don't know what this line looks like. The only1555 * thing we do know is that it begins with "\ ".1556 * Checking for 12 is just for sanity check -- any1557 * l10n of "\ No newline..." is at least that long.1558 */1559 case '\\':1560 if (len < 12 || memcmp(line, "\\ ", 2))1561 return -1;1562 break;1563 }1564 }1565 if (oldlines || newlines)1566 return -1;1567 fragment->leading = leading;1568 fragment->trailing = trailing;15691570 /*1571 * If a fragment ends with an incomplete line, we failed to include1572 * it in the above loop because we hit oldlines == newlines == 01573 * before seeing it.1574 */1575 if (12 < size && !memcmp(line, "\\ ", 2))1576 offset += linelen(line, size);15771578 patch->lines_added += added;1579 patch->lines_deleted += deleted;15801581 if (0 < patch->is_new && oldlines)1582 return error("new file depends on old contents");1583 if (0 < patch->is_delete && newlines)1584 return error("deleted file still has contents");1585 return offset;1586}15871588static int parse_single_patch(char *line, unsigned long size, struct patch *patch)1589{1590 unsigned long offset = 0;1591 unsigned long oldlines = 0, newlines = 0, context = 0;1592 struct fragment **fragp = &patch->fragments;15931594 while (size > 4 && !memcmp(line, "@@ -", 4)) {1595 struct fragment *fragment;1596 int len;15971598 fragment = xcalloc(1, sizeof(*fragment));1599 fragment->linenr = linenr;1600 len = parse_fragment(line, size, patch, fragment);1601 if (len <= 0)1602 die("corrupt patch at line %d", linenr);1603 fragment->patch = line;1604 fragment->size = len;1605 oldlines += fragment->oldlines;1606 newlines += fragment->newlines;1607 context += fragment->leading + fragment->trailing;16081609 *fragp = fragment;1610 fragp = &fragment->next;16111612 offset += len;1613 line += len;1614 size -= len;1615 }16161617 /*1618 * If something was removed (i.e. we have old-lines) it cannot1619 * be creation, and if something was added it cannot be1620 * deletion. However, the reverse is not true; --unified=01621 * patches that only add are not necessarily creation even1622 * though they do not have any old lines, and ones that only1623 * delete are not necessarily deletion.1624 *1625 * Unfortunately, a real creation/deletion patch do _not_ have1626 * any context line by definition, so we cannot safely tell it1627 * apart with --unified=0 insanity. At least if the patch has1628 * more than one hunk it is not creation or deletion.1629 */1630 if (patch->is_new < 0 &&1631 (oldlines || (patch->fragments && patch->fragments->next)))1632 patch->is_new = 0;1633 if (patch->is_delete < 0 &&1634 (newlines || (patch->fragments && patch->fragments->next)))1635 patch->is_delete = 0;16361637 if (0 < patch->is_new && oldlines)1638 die("new file %s depends on old contents", patch->new_name);1639 if (0 < patch->is_delete && newlines)1640 die("deleted file %s still has contents", patch->old_name);1641 if (!patch->is_delete && !newlines && context)1642 fprintf(stderr, "** warning: file %s becomes empty but "1643 "is not deleted\n", patch->new_name);16441645 return offset;1646}16471648static inline int metadata_changes(struct patch *patch)1649{1650 return patch->is_rename > 0 ||1651 patch->is_copy > 0 ||1652 patch->is_new > 0 ||1653 patch->is_delete ||1654 (patch->old_mode && patch->new_mode &&1655 patch->old_mode != patch->new_mode);1656}16571658static char *inflate_it(const void *data, unsigned long size,1659 unsigned long inflated_size)1660{1661 git_zstream stream;1662 void *out;1663 int st;16641665 memset(&stream, 0, sizeof(stream));16661667 stream.next_in = (unsigned char *)data;1668 stream.avail_in = size;1669 stream.next_out = out = xmalloc(inflated_size);1670 stream.avail_out = inflated_size;1671 git_inflate_init(&stream);1672 st = git_inflate(&stream, Z_FINISH);1673 git_inflate_end(&stream);1674 if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {1675 free(out);1676 return NULL;1677 }1678 return out;1679}16801681static struct fragment *parse_binary_hunk(char **buf_p,1682 unsigned long *sz_p,1683 int *status_p,1684 int *used_p)1685{1686 /*1687 * Expect a line that begins with binary patch method ("literal"1688 * or "delta"), followed by the length of data before deflating.1689 * a sequence of 'length-byte' followed by base-85 encoded data1690 * should follow, terminated by a newline.1691 *1692 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1693 * and we would limit the patch line to 66 characters,1694 * so one line can fit up to 13 groups that would decode1695 * to 52 bytes max. The length byte 'A'-'Z' corresponds1696 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1697 */1698 int llen, used;1699 unsigned long size = *sz_p;1700 char *buffer = *buf_p;1701 int patch_method;1702 unsigned long origlen;1703 char *data = NULL;1704 int hunk_size = 0;1705 struct fragment *frag;17061707 llen = linelen(buffer, size);1708 used = llen;17091710 *status_p = 0;17111712 if (!prefixcmp(buffer, "delta ")) {1713 patch_method = BINARY_DELTA_DEFLATED;1714 origlen = strtoul(buffer + 6, NULL, 10);1715 }1716 else if (!prefixcmp(buffer, "literal ")) {1717 patch_method = BINARY_LITERAL_DEFLATED;1718 origlen = strtoul(buffer + 8, NULL, 10);1719 }1720 else1721 return NULL;17221723 linenr++;1724 buffer += llen;1725 while (1) {1726 int byte_length, max_byte_length, newsize;1727 llen = linelen(buffer, size);1728 used += llen;1729 linenr++;1730 if (llen == 1) {1731 /* consume the blank line */1732 buffer++;1733 size--;1734 break;1735 }1736 /*1737 * Minimum line is "A00000\n" which is 7-byte long,1738 * and the line length must be multiple of 5 plus 2.1739 */1740 if ((llen < 7) || (llen-2) % 5)1741 goto corrupt;1742 max_byte_length = (llen - 2) / 5 * 4;1743 byte_length = *buffer;1744 if ('A' <= byte_length && byte_length <= 'Z')1745 byte_length = byte_length - 'A' + 1;1746 else if ('a' <= byte_length && byte_length <= 'z')1747 byte_length = byte_length - 'a' + 27;1748 else1749 goto corrupt;1750 /* if the input length was not multiple of 4, we would1751 * have filler at the end but the filler should never1752 * exceed 3 bytes1753 */1754 if (max_byte_length < byte_length ||1755 byte_length <= max_byte_length - 4)1756 goto corrupt;1757 newsize = hunk_size + byte_length;1758 data = xrealloc(data, newsize);1759 if (decode_85(data + hunk_size, buffer + 1, byte_length))1760 goto corrupt;1761 hunk_size = newsize;1762 buffer += llen;1763 size -= llen;1764 }17651766 frag = xcalloc(1, sizeof(*frag));1767 frag->patch = inflate_it(data, hunk_size, origlen);1768 frag->free_patch = 1;1769 if (!frag->patch)1770 goto corrupt;1771 free(data);1772 frag->size = origlen;1773 *buf_p = buffer;1774 *sz_p = size;1775 *used_p = used;1776 frag->binary_patch_method = patch_method;1777 return frag;17781779 corrupt:1780 free(data);1781 *status_p = -1;1782 error("corrupt binary patch at line %d: %.*s",1783 linenr-1, llen-1, buffer);1784 return NULL;1785}17861787static int parse_binary(char *buffer, unsigned long size, struct patch *patch)1788{1789 /*1790 * We have read "GIT binary patch\n"; what follows is a line1791 * that says the patch method (currently, either "literal" or1792 * "delta") and the length of data before deflating; a1793 * sequence of 'length-byte' followed by base-85 encoded data1794 * follows.1795 *1796 * When a binary patch is reversible, there is another binary1797 * hunk in the same format, starting with patch method (either1798 * "literal" or "delta") with the length of data, and a sequence1799 * of length-byte + base-85 encoded data, terminated with another1800 * empty line. This data, when applied to the postimage, produces1801 * the preimage.1802 */1803 struct fragment *forward;1804 struct fragment *reverse;1805 int status;1806 int used, used_1;18071808 forward = parse_binary_hunk(&buffer, &size, &status, &used);1809 if (!forward && !status)1810 /* there has to be one hunk (forward hunk) */1811 return error("unrecognized binary patch at line %d", linenr-1);1812 if (status)1813 /* otherwise we already gave an error message */1814 return status;18151816 reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);1817 if (reverse)1818 used += used_1;1819 else if (status) {1820 /*1821 * Not having reverse hunk is not an error, but having1822 * a corrupt reverse hunk is.1823 */1824 free((void*) forward->patch);1825 free(forward);1826 return status;1827 }1828 forward->next = reverse;1829 patch->fragments = forward;1830 patch->is_binary = 1;1831 return used;1832}18331834static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)1835{1836 int hdrsize, patchsize;1837 int offset = find_header(buffer, size, &hdrsize, patch);18381839 if (offset < 0)1840 return offset;18411842 patch->ws_rule = whitespace_rule(patch->new_name1843 ? patch->new_name1844 : patch->old_name);18451846 patchsize = parse_single_patch(buffer + offset + hdrsize,1847 size - offset - hdrsize, patch);18481849 if (!patchsize) {1850 static const char *binhdr[] = {1851 "Binary files ",1852 "Files ",1853 NULL,1854 };1855 static const char git_binary[] = "GIT binary patch\n";1856 int i;1857 int hd = hdrsize + offset;1858 unsigned long llen = linelen(buffer + hd, size - hd);18591860 if (llen == sizeof(git_binary) - 1 &&1861 !memcmp(git_binary, buffer + hd, llen)) {1862 int used;1863 linenr++;1864 used = parse_binary(buffer + hd + llen,1865 size - hd - llen, patch);1866 if (used)1867 patchsize = used + llen;1868 else1869 patchsize = 0;1870 }1871 else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {1872 for (i = 0; binhdr[i]; i++) {1873 int len = strlen(binhdr[i]);1874 if (len < size - hd &&1875 !memcmp(binhdr[i], buffer + hd, len)) {1876 linenr++;1877 patch->is_binary = 1;1878 patchsize = llen;1879 break;1880 }1881 }1882 }18831884 /* Empty patch cannot be applied if it is a text patch1885 * without metadata change. A binary patch appears1886 * empty to us here.1887 */1888 if ((apply || check) &&1889 (!patch->is_binary && !metadata_changes(patch)))1890 die("patch with only garbage at line %d", linenr);1891 }18921893 return offset + hdrsize + patchsize;1894}18951896#define swap(a,b) myswap((a),(b),sizeof(a))18971898#define myswap(a, b, size) do { \1899 unsigned char mytmp[size]; \1900 memcpy(mytmp, &a, size); \1901 memcpy(&a, &b, size); \1902 memcpy(&b, mytmp, size); \1903} while (0)19041905static void reverse_patches(struct patch *p)1906{1907 for (; p; p = p->next) {1908 struct fragment *frag = p->fragments;19091910 swap(p->new_name, p->old_name);1911 swap(p->new_mode, p->old_mode);1912 swap(p->is_new, p->is_delete);1913 swap(p->lines_added, p->lines_deleted);1914 swap(p->old_sha1_prefix, p->new_sha1_prefix);19151916 for (; frag; frag = frag->next) {1917 swap(frag->newpos, frag->oldpos);1918 swap(frag->newlines, frag->oldlines);1919 }1920 }1921}19221923static const char pluses[] =1924"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";1925static const char minuses[]=1926"----------------------------------------------------------------------";19271928static void show_stats(struct patch *patch)1929{1930 struct strbuf qname = STRBUF_INIT;1931 char *cp = patch->new_name ? patch->new_name : patch->old_name;1932 int max, add, del;19331934 quote_c_style(cp, &qname, NULL, 0);19351936 /*1937 * "scale" the filename1938 */1939 max = max_len;1940 if (max > 50)1941 max = 50;19421943 if (qname.len > max) {1944 cp = strchr(qname.buf + qname.len + 3 - max, '/');1945 if (!cp)1946 cp = qname.buf + qname.len + 3 - max;1947 strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);1948 }19491950 if (patch->is_binary) {1951 printf(" %-*s | Bin\n", max, qname.buf);1952 strbuf_release(&qname);1953 return;1954 }19551956 printf(" %-*s |", max, qname.buf);1957 strbuf_release(&qname);19581959 /*1960 * scale the add/delete1961 */1962 max = max + max_change > 70 ? 70 - max : max_change;1963 add = patch->lines_added;1964 del = patch->lines_deleted;19651966 if (max_change > 0) {1967 int total = ((add + del) * max + max_change / 2) / max_change;1968 add = (add * max + max_change / 2) / max_change;1969 del = total - add;1970 }1971 printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,1972 add, pluses, del, minuses);1973}19741975static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)1976{1977 switch (st->st_mode & S_IFMT) {1978 case S_IFLNK:1979 if (strbuf_readlink(buf, path, st->st_size) < 0)1980 return error("unable to read symlink %s", path);1981 return 0;1982 case S_IFREG:1983 if (strbuf_read_file(buf, path, st->st_size) != st->st_size)1984 return error("unable to open or read %s", path);1985 convert_to_git(path, buf->buf, buf->len, buf, 0);1986 return 0;1987 default:1988 return -1;1989 }1990}19911992/*1993 * Update the preimage, and the common lines in postimage,1994 * from buffer buf of length len. If postlen is 0 the postimage1995 * is updated in place, otherwise it's updated on a new buffer1996 * of length postlen1997 */19981999static void update_pre_post_images(struct image *preimage,2000 struct image *postimage,2001 char *buf,2002 size_t len, size_t postlen)2003{2004 int i, ctx;2005 char *new, *old, *fixed;2006 struct image fixed_preimage;20072008 /*2009 * Update the preimage with whitespace fixes. Note that we2010 * are not losing preimage->buf -- apply_one_fragment() will2011 * free "oldlines".2012 */2013 prepare_image(&fixed_preimage, buf, len, 1);2014 assert(fixed_preimage.nr == preimage->nr);2015 for (i = 0; i < preimage->nr; i++)2016 fixed_preimage.line[i].flag = preimage->line[i].flag;2017 free(preimage->line_allocated);2018 *preimage = fixed_preimage;20192020 /*2021 * Adjust the common context lines in postimage. This can be2022 * done in-place when we are just doing whitespace fixing,2023 * which does not make the string grow, but needs a new buffer2024 * when ignoring whitespace causes the update, since in this case2025 * we could have e.g. tabs converted to multiple spaces.2026 * We trust the caller to tell us if the update can be done2027 * in place (postlen==0) or not.2028 */2029 old = postimage->buf;2030 if (postlen)2031 new = postimage->buf = xmalloc(postlen);2032 else2033 new = old;2034 fixed = preimage->buf;2035 for (i = ctx = 0; i < postimage->nr; i++) {2036 size_t len = postimage->line[i].len;2037 if (!(postimage->line[i].flag & LINE_COMMON)) {2038 /* an added line -- no counterparts in preimage */2039 memmove(new, old, len);2040 old += len;2041 new += len;2042 continue;2043 }20442045 /* a common context -- skip it in the original postimage */2046 old += len;20472048 /* and find the corresponding one in the fixed preimage */2049 while (ctx < preimage->nr &&2050 !(preimage->line[ctx].flag & LINE_COMMON)) {2051 fixed += preimage->line[ctx].len;2052 ctx++;2053 }2054 if (preimage->nr <= ctx)2055 die("oops");20562057 /* and copy it in, while fixing the line length */2058 len = preimage->line[ctx].len;2059 memcpy(new, fixed, len);2060 new += len;2061 fixed += len;2062 postimage->line[i].len = len;2063 ctx++;2064 }20652066 /* Fix the length of the whole thing */2067 postimage->len = new - postimage->buf;2068}20692070static int match_fragment(struct image *img,2071 struct image *preimage,2072 struct image *postimage,2073 unsigned long try,2074 int try_lno,2075 unsigned ws_rule,2076 int match_beginning, int match_end)2077{2078 int i;2079 char *fixed_buf, *buf, *orig, *target;2080 struct strbuf fixed;2081 size_t fixed_len;2082 int preimage_limit;20832084 if (preimage->nr + try_lno <= img->nr) {2085 /*2086 * The hunk falls within the boundaries of img.2087 */2088 preimage_limit = preimage->nr;2089 if (match_end && (preimage->nr + try_lno != img->nr))2090 return 0;2091 } else if (ws_error_action == correct_ws_error &&2092 (ws_rule & WS_BLANK_AT_EOF)) {2093 /*2094 * This hunk extends beyond the end of img, and we are2095 * removing blank lines at the end of the file. This2096 * many lines from the beginning of the preimage must2097 * match with img, and the remainder of the preimage2098 * must be blank.2099 */2100 preimage_limit = img->nr - try_lno;2101 } else {2102 /*2103 * The hunk extends beyond the end of the img and2104 * we are not removing blanks at the end, so we2105 * should reject the hunk at this position.2106 */2107 return 0;2108 }21092110 if (match_beginning && try_lno)2111 return 0;21122113 /* Quick hash check */2114 for (i = 0; i < preimage_limit; i++)2115 if ((img->line[try_lno + i].flag & LINE_PATCHED) ||2116 (preimage->line[i].hash != img->line[try_lno + i].hash))2117 return 0;21182119 if (preimage_limit == preimage->nr) {2120 /*2121 * Do we have an exact match? If we were told to match2122 * at the end, size must be exactly at try+fragsize,2123 * otherwise try+fragsize must be still within the preimage,2124 * and either case, the old piece should match the preimage2125 * exactly.2126 */2127 if ((match_end2128 ? (try + preimage->len == img->len)2129 : (try + preimage->len <= img->len)) &&2130 !memcmp(img->buf + try, preimage->buf, preimage->len))2131 return 1;2132 } else {2133 /*2134 * The preimage extends beyond the end of img, so2135 * there cannot be an exact match.2136 *2137 * There must be one non-blank context line that match2138 * a line before the end of img.2139 */2140 char *buf_end;21412142 buf = preimage->buf;2143 buf_end = buf;2144 for (i = 0; i < preimage_limit; i++)2145 buf_end += preimage->line[i].len;21462147 for ( ; buf < buf_end; buf++)2148 if (!isspace(*buf))2149 break;2150 if (buf == buf_end)2151 return 0;2152 }21532154 /*2155 * No exact match. If we are ignoring whitespace, run a line-by-line2156 * fuzzy matching. We collect all the line length information because2157 * we need it to adjust whitespace if we match.2158 */2159 if (ws_ignore_action == ignore_ws_change) {2160 size_t imgoff = 0;2161 size_t preoff = 0;2162 size_t postlen = postimage->len;2163 size_t extra_chars;2164 char *preimage_eof;2165 char *preimage_end;2166 for (i = 0; i < preimage_limit; i++) {2167 size_t prelen = preimage->line[i].len;2168 size_t imglen = img->line[try_lno+i].len;21692170 if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,2171 preimage->buf + preoff, prelen))2172 return 0;2173 if (preimage->line[i].flag & LINE_COMMON)2174 postlen += imglen - prelen;2175 imgoff += imglen;2176 preoff += prelen;2177 }21782179 /*2180 * Ok, the preimage matches with whitespace fuzz.2181 *2182 * imgoff now holds the true length of the target that2183 * matches the preimage before the end of the file.2184 *2185 * Count the number of characters in the preimage that fall2186 * beyond the end of the file and make sure that all of them2187 * are whitespace characters. (This can only happen if2188 * we are removing blank lines at the end of the file.)2189 */2190 buf = preimage_eof = preimage->buf + preoff;2191 for ( ; i < preimage->nr; i++)2192 preoff += preimage->line[i].len;2193 preimage_end = preimage->buf + preoff;2194 for ( ; buf < preimage_end; buf++)2195 if (!isspace(*buf))2196 return 0;21972198 /*2199 * Update the preimage and the common postimage context2200 * lines to use the same whitespace as the target.2201 * If whitespace is missing in the target (i.e.2202 * if the preimage extends beyond the end of the file),2203 * use the whitespace from the preimage.2204 */2205 extra_chars = preimage_end - preimage_eof;2206 strbuf_init(&fixed, imgoff + extra_chars);2207 strbuf_add(&fixed, img->buf + try, imgoff);2208 strbuf_add(&fixed, preimage_eof, extra_chars);2209 fixed_buf = strbuf_detach(&fixed, &fixed_len);2210 update_pre_post_images(preimage, postimage,2211 fixed_buf, fixed_len, postlen);2212 return 1;2213 }22142215 if (ws_error_action != correct_ws_error)2216 return 0;22172218 /*2219 * The hunk does not apply byte-by-byte, but the hash says2220 * it might with whitespace fuzz. We haven't been asked to2221 * ignore whitespace, we were asked to correct whitespace2222 * errors, so let's try matching after whitespace correction.2223 *2224 * The preimage may extend beyond the end of the file,2225 * but in this loop we will only handle the part of the2226 * preimage that falls within the file.2227 */2228 strbuf_init(&fixed, preimage->len + 1);2229 orig = preimage->buf;2230 target = img->buf + try;2231 for (i = 0; i < preimage_limit; i++) {2232 size_t oldlen = preimage->line[i].len;2233 size_t tgtlen = img->line[try_lno + i].len;2234 size_t fixstart = fixed.len;2235 struct strbuf tgtfix;2236 int match;22372238 /* Try fixing the line in the preimage */2239 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);22402241 /* Try fixing the line in the target */2242 strbuf_init(&tgtfix, tgtlen);2243 ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);22442245 /*2246 * If they match, either the preimage was based on2247 * a version before our tree fixed whitespace breakage,2248 * or we are lacking a whitespace-fix patch the tree2249 * the preimage was based on already had (i.e. target2250 * has whitespace breakage, the preimage doesn't).2251 * In either case, we are fixing the whitespace breakages2252 * so we might as well take the fix together with their2253 * real change.2254 */2255 match = (tgtfix.len == fixed.len - fixstart &&2256 !memcmp(tgtfix.buf, fixed.buf + fixstart,2257 fixed.len - fixstart));22582259 strbuf_release(&tgtfix);2260 if (!match)2261 goto unmatch_exit;22622263 orig += oldlen;2264 target += tgtlen;2265 }226622672268 /*2269 * Now handle the lines in the preimage that falls beyond the2270 * end of the file (if any). They will only match if they are2271 * empty or only contain whitespace (if WS_BLANK_AT_EOL is2272 * false).2273 */2274 for ( ; i < preimage->nr; i++) {2275 size_t fixstart = fixed.len; /* start of the fixed preimage */2276 size_t oldlen = preimage->line[i].len;2277 int j;22782279 /* Try fixing the line in the preimage */2280 ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);22812282 for (j = fixstart; j < fixed.len; j++)2283 if (!isspace(fixed.buf[j]))2284 goto unmatch_exit;22852286 orig += oldlen;2287 }22882289 /*2290 * Yes, the preimage is based on an older version that still2291 * has whitespace breakages unfixed, and fixing them makes the2292 * hunk match. Update the context lines in the postimage.2293 */2294 fixed_buf = strbuf_detach(&fixed, &fixed_len);2295 update_pre_post_images(preimage, postimage,2296 fixed_buf, fixed_len, 0);2297 return 1;22982299 unmatch_exit:2300 strbuf_release(&fixed);2301 return 0;2302}23032304static int find_pos(struct image *img,2305 struct image *preimage,2306 struct image *postimage,2307 int line,2308 unsigned ws_rule,2309 int match_beginning, int match_end)2310{2311 int i;2312 unsigned long backwards, forwards, try;2313 int backwards_lno, forwards_lno, try_lno;23142315 /*2316 * If match_beginning or match_end is specified, there is no2317 * point starting from a wrong line that will never match and2318 * wander around and wait for a match at the specified end.2319 */2320 if (match_beginning)2321 line = 0;2322 else if (match_end)2323 line = img->nr - preimage->nr;23242325 /*2326 * Because the comparison is unsigned, the following test2327 * will also take care of a negative line number that can2328 * result when match_end and preimage is larger than the target.2329 */2330 if ((size_t) line > img->nr)2331 line = img->nr;23322333 try = 0;2334 for (i = 0; i < line; i++)2335 try += img->line[i].len;23362337 /*2338 * There's probably some smart way to do this, but I'll leave2339 * that to the smart and beautiful people. I'm simple and stupid.2340 */2341 backwards = try;2342 backwards_lno = line;2343 forwards = try;2344 forwards_lno = line;2345 try_lno = line;23462347 for (i = 0; ; i++) {2348 if (match_fragment(img, preimage, postimage,2349 try, try_lno, ws_rule,2350 match_beginning, match_end))2351 return try_lno;23522353 again:2354 if (backwards_lno == 0 && forwards_lno == img->nr)2355 break;23562357 if (i & 1) {2358 if (backwards_lno == 0) {2359 i++;2360 goto again;2361 }2362 backwards_lno--;2363 backwards -= img->line[backwards_lno].len;2364 try = backwards;2365 try_lno = backwards_lno;2366 } else {2367 if (forwards_lno == img->nr) {2368 i++;2369 goto again;2370 }2371 forwards += img->line[forwards_lno].len;2372 forwards_lno++;2373 try = forwards;2374 try_lno = forwards_lno;2375 }23762377 }2378 return -1;2379}23802381static void remove_first_line(struct image *img)2382{2383 img->buf += img->line[0].len;2384 img->len -= img->line[0].len;2385 img->line++;2386 img->nr--;2387}23882389static void remove_last_line(struct image *img)2390{2391 img->len -= img->line[--img->nr].len;2392}23932394static void update_image(struct image *img,2395 int applied_pos,2396 struct image *preimage,2397 struct image *postimage)2398{2399 /*2400 * remove the copy of preimage at offset in img2401 * and replace it with postimage2402 */2403 int i, nr;2404 size_t remove_count, insert_count, applied_at = 0;2405 char *result;2406 int preimage_limit;24072408 /*2409 * If we are removing blank lines at the end of img,2410 * the preimage may extend beyond the end.2411 * If that is the case, we must be careful only to2412 * remove the part of the preimage that falls within2413 * the boundaries of img. Initialize preimage_limit2414 * to the number of lines in the preimage that falls2415 * within the boundaries.2416 */2417 preimage_limit = preimage->nr;2418 if (preimage_limit > img->nr - applied_pos)2419 preimage_limit = img->nr - applied_pos;24202421 for (i = 0; i < applied_pos; i++)2422 applied_at += img->line[i].len;24232424 remove_count = 0;2425 for (i = 0; i < preimage_limit; i++)2426 remove_count += img->line[applied_pos + i].len;2427 insert_count = postimage->len;24282429 /* Adjust the contents */2430 result = xmalloc(img->len + insert_count - remove_count + 1);2431 memcpy(result, img->buf, applied_at);2432 memcpy(result + applied_at, postimage->buf, postimage->len);2433 memcpy(result + applied_at + postimage->len,2434 img->buf + (applied_at + remove_count),2435 img->len - (applied_at + remove_count));2436 free(img->buf);2437 img->buf = result;2438 img->len += insert_count - remove_count;2439 result[img->len] = '\0';24402441 /* Adjust the line table */2442 nr = img->nr + postimage->nr - preimage_limit;2443 if (preimage_limit < postimage->nr) {2444 /*2445 * NOTE: this knows that we never call remove_first_line()2446 * on anything other than pre/post image.2447 */2448 img->line = xrealloc(img->line, nr * sizeof(*img->line));2449 img->line_allocated = img->line;2450 }2451 if (preimage_limit != postimage->nr)2452 memmove(img->line + applied_pos + postimage->nr,2453 img->line + applied_pos + preimage_limit,2454 (img->nr - (applied_pos + preimage_limit)) *2455 sizeof(*img->line));2456 memcpy(img->line + applied_pos,2457 postimage->line,2458 postimage->nr * sizeof(*img->line));2459 if (!allow_overlap)2460 for (i = 0; i < postimage->nr; i++)2461 img->line[applied_pos + i].flag |= LINE_PATCHED;2462 img->nr = nr;2463}24642465static int apply_one_fragment(struct image *img, struct fragment *frag,2466 int inaccurate_eof, unsigned ws_rule,2467 int nth_fragment)2468{2469 int match_beginning, match_end;2470 const char *patch = frag->patch;2471 int size = frag->size;2472 char *old, *oldlines;2473 struct strbuf newlines;2474 int new_blank_lines_at_end = 0;2475 int found_new_blank_lines_at_end = 0;2476 int hunk_linenr = frag->linenr;2477 unsigned long leading, trailing;2478 int pos, applied_pos;2479 struct image preimage;2480 struct image postimage;24812482 memset(&preimage, 0, sizeof(preimage));2483 memset(&postimage, 0, sizeof(postimage));2484 oldlines = xmalloc(size);2485 strbuf_init(&newlines, size);24862487 old = oldlines;2488 while (size > 0) {2489 char first;2490 int len = linelen(patch, size);2491 int plen;2492 int added_blank_line = 0;2493 int is_blank_context = 0;2494 size_t start;24952496 if (!len)2497 break;24982499 /*2500 * "plen" is how much of the line we should use for2501 * the actual patch data. Normally we just remove the2502 * first character on the line, but if the line is2503 * followed by "\ No newline", then we also remove the2504 * last one (which is the newline, of course).2505 */2506 plen = len - 1;2507 if (len < size && patch[len] == '\\')2508 plen--;2509 first = *patch;2510 if (apply_in_reverse) {2511 if (first == '-')2512 first = '+';2513 else if (first == '+')2514 first = '-';2515 }25162517 switch (first) {2518 case '\n':2519 /* Newer GNU diff, empty context line */2520 if (plen < 0)2521 /* ... followed by '\No newline'; nothing */2522 break;2523 *old++ = '\n';2524 strbuf_addch(&newlines, '\n');2525 add_line_info(&preimage, "\n", 1, LINE_COMMON);2526 add_line_info(&postimage, "\n", 1, LINE_COMMON);2527 is_blank_context = 1;2528 break;2529 case ' ':2530 if (plen && (ws_rule & WS_BLANK_AT_EOF) &&2531 ws_blank_line(patch + 1, plen, ws_rule))2532 is_blank_context = 1;2533 case '-':2534 memcpy(old, patch + 1, plen);2535 add_line_info(&preimage, old, plen,2536 (first == ' ' ? LINE_COMMON : 0));2537 old += plen;2538 if (first == '-')2539 break;2540 /* Fall-through for ' ' */2541 case '+':2542 /* --no-add does not add new lines */2543 if (first == '+' && no_add)2544 break;25452546 start = newlines.len;2547 if (first != '+' ||2548 !whitespace_error ||2549 ws_error_action != correct_ws_error) {2550 strbuf_add(&newlines, patch + 1, plen);2551 }2552 else {2553 ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &applied_after_fixing_ws);2554 }2555 add_line_info(&postimage, newlines.buf + start, newlines.len - start,2556 (first == '+' ? 0 : LINE_COMMON));2557 if (first == '+' &&2558 (ws_rule & WS_BLANK_AT_EOF) &&2559 ws_blank_line(patch + 1, plen, ws_rule))2560 added_blank_line = 1;2561 break;2562 case '@': case '\\':2563 /* Ignore it, we already handled it */2564 break;2565 default:2566 if (apply_verbosely)2567 error("invalid start of line: '%c'", first);2568 return -1;2569 }2570 if (added_blank_line) {2571 if (!new_blank_lines_at_end)2572 found_new_blank_lines_at_end = hunk_linenr;2573 new_blank_lines_at_end++;2574 }2575 else if (is_blank_context)2576 ;2577 else2578 new_blank_lines_at_end = 0;2579 patch += len;2580 size -= len;2581 hunk_linenr++;2582 }2583 if (inaccurate_eof &&2584 old > oldlines && old[-1] == '\n' &&2585 newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {2586 old--;2587 strbuf_setlen(&newlines, newlines.len - 1);2588 }25892590 leading = frag->leading;2591 trailing = frag->trailing;25922593 /*2594 * A hunk to change lines at the beginning would begin with2595 * @@ -1,L +N,M @@2596 * but we need to be careful. -U0 that inserts before the second2597 * line also has this pattern.2598 *2599 * And a hunk to add to an empty file would begin with2600 * @@ -0,0 +N,M @@2601 *2602 * In other words, a hunk that is (frag->oldpos <= 1) with or2603 * without leading context must match at the beginning.2604 */2605 match_beginning = (!frag->oldpos ||2606 (frag->oldpos == 1 && !unidiff_zero));26072608 /*2609 * A hunk without trailing lines must match at the end.2610 * However, we simply cannot tell if a hunk must match end2611 * from the lack of trailing lines if the patch was generated2612 * with unidiff without any context.2613 */2614 match_end = !unidiff_zero && !trailing;26152616 pos = frag->newpos ? (frag->newpos - 1) : 0;2617 preimage.buf = oldlines;2618 preimage.len = old - oldlines;2619 postimage.buf = newlines.buf;2620 postimage.len = newlines.len;2621 preimage.line = preimage.line_allocated;2622 postimage.line = postimage.line_allocated;26232624 for (;;) {26252626 applied_pos = find_pos(img, &preimage, &postimage, pos,2627 ws_rule, match_beginning, match_end);26282629 if (applied_pos >= 0)2630 break;26312632 /* Am I at my context limits? */2633 if ((leading <= p_context) && (trailing <= p_context))2634 break;2635 if (match_beginning || match_end) {2636 match_beginning = match_end = 0;2637 continue;2638 }26392640 /*2641 * Reduce the number of context lines; reduce both2642 * leading and trailing if they are equal otherwise2643 * just reduce the larger context.2644 */2645 if (leading >= trailing) {2646 remove_first_line(&preimage);2647 remove_first_line(&postimage);2648 pos--;2649 leading--;2650 }2651 if (trailing > leading) {2652 remove_last_line(&preimage);2653 remove_last_line(&postimage);2654 trailing--;2655 }2656 }26572658 if (applied_pos >= 0) {2659 if (new_blank_lines_at_end &&2660 preimage.nr + applied_pos >= img->nr &&2661 (ws_rule & WS_BLANK_AT_EOF) &&2662 ws_error_action != nowarn_ws_error) {2663 record_ws_error(WS_BLANK_AT_EOF, "+", 1,2664 found_new_blank_lines_at_end);2665 if (ws_error_action == correct_ws_error) {2666 while (new_blank_lines_at_end--)2667 remove_last_line(&postimage);2668 }2669 /*2670 * We would want to prevent write_out_results()2671 * from taking place in apply_patch() that follows2672 * the callchain led us here, which is:2673 * apply_patch->check_patch_list->check_patch->2674 * apply_data->apply_fragments->apply_one_fragment2675 */2676 if (ws_error_action == die_on_ws_error)2677 apply = 0;2678 }26792680 if (apply_verbosely && applied_pos != pos) {2681 int offset = applied_pos - pos;2682 if (apply_in_reverse)2683 offset = 0 - offset;2684 fprintf(stderr,2685 "Hunk #%d succeeded at %d (offset %d lines).\n",2686 nth_fragment, applied_pos + 1, offset);2687 }26882689 /*2690 * Warn if it was necessary to reduce the number2691 * of context lines.2692 */2693 if ((leading != frag->leading) ||2694 (trailing != frag->trailing))2695 fprintf(stderr, "Context reduced to (%ld/%ld)"2696 " to apply fragment at %d\n",2697 leading, trailing, applied_pos+1);2698 update_image(img, applied_pos, &preimage, &postimage);2699 } else {2700 if (apply_verbosely)2701 error("while searching for:\n%.*s",2702 (int)(old - oldlines), oldlines);2703 }27042705 free(oldlines);2706 strbuf_release(&newlines);2707 free(preimage.line_allocated);2708 free(postimage.line_allocated);27092710 return (applied_pos < 0);2711}27122713static int apply_binary_fragment(struct image *img, struct patch *patch)2714{2715 struct fragment *fragment = patch->fragments;2716 unsigned long len;2717 void *dst;27182719 if (!fragment)2720 return error("missing binary patch data for '%s'",2721 patch->new_name ?2722 patch->new_name :2723 patch->old_name);27242725 /* Binary patch is irreversible without the optional second hunk */2726 if (apply_in_reverse) {2727 if (!fragment->next)2728 return error("cannot reverse-apply a binary patch "2729 "without the reverse hunk to '%s'",2730 patch->new_name2731 ? patch->new_name : patch->old_name);2732 fragment = fragment->next;2733 }2734 switch (fragment->binary_patch_method) {2735 case BINARY_DELTA_DEFLATED:2736 dst = patch_delta(img->buf, img->len, fragment->patch,2737 fragment->size, &len);2738 if (!dst)2739 return -1;2740 clear_image(img);2741 img->buf = dst;2742 img->len = len;2743 return 0;2744 case BINARY_LITERAL_DEFLATED:2745 clear_image(img);2746 img->len = fragment->size;2747 img->buf = xmalloc(img->len+1);2748 memcpy(img->buf, fragment->patch, img->len);2749 img->buf[img->len] = '\0';2750 return 0;2751 }2752 return -1;2753}27542755static int apply_binary(struct image *img, struct patch *patch)2756{2757 const char *name = patch->old_name ? patch->old_name : patch->new_name;2758 unsigned char sha1[20];27592760 /*2761 * For safety, we require patch index line to contain2762 * full 40-byte textual SHA1 for old and new, at least for now.2763 */2764 if (strlen(patch->old_sha1_prefix) != 40 ||2765 strlen(patch->new_sha1_prefix) != 40 ||2766 get_sha1_hex(patch->old_sha1_prefix, sha1) ||2767 get_sha1_hex(patch->new_sha1_prefix, sha1))2768 return error("cannot apply binary patch to '%s' "2769 "without full index line", name);27702771 if (patch->old_name) {2772 /*2773 * See if the old one matches what the patch2774 * applies to.2775 */2776 hash_sha1_file(img->buf, img->len, blob_type, sha1);2777 if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2778 return error("the patch applies to '%s' (%s), "2779 "which does not match the "2780 "current contents.",2781 name, sha1_to_hex(sha1));2782 }2783 else {2784 /* Otherwise, the old one must be empty. */2785 if (img->len)2786 return error("the patch applies to an empty "2787 "'%s' but it is not empty", name);2788 }27892790 get_sha1_hex(patch->new_sha1_prefix, sha1);2791 if (is_null_sha1(sha1)) {2792 clear_image(img);2793 return 0; /* deletion patch */2794 }27952796 if (has_sha1_file(sha1)) {2797 /* We already have the postimage */2798 enum object_type type;2799 unsigned long size;2800 char *result;28012802 result = read_sha1_file(sha1, &type, &size);2803 if (!result)2804 return error("the necessary postimage %s for "2805 "'%s' cannot be read",2806 patch->new_sha1_prefix, name);2807 clear_image(img);2808 img->buf = result;2809 img->len = size;2810 } else {2811 /*2812 * We have verified buf matches the preimage;2813 * apply the patch data to it, which is stored2814 * in the patch->fragments->{patch,size}.2815 */2816 if (apply_binary_fragment(img, patch))2817 return error("binary patch does not apply to '%s'",2818 name);28192820 /* verify that the result matches */2821 hash_sha1_file(img->buf, img->len, blob_type, sha1);2822 if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2823 return error("binary patch to '%s' creates incorrect result (expecting %s, got %s)",2824 name, patch->new_sha1_prefix, sha1_to_hex(sha1));2825 }28262827 return 0;2828}28292830static int apply_fragments(struct image *img, struct patch *patch)2831{2832 struct fragment *frag = patch->fragments;2833 const char *name = patch->old_name ? patch->old_name : patch->new_name;2834 unsigned ws_rule = patch->ws_rule;2835 unsigned inaccurate_eof = patch->inaccurate_eof;2836 int nth = 0;28372838 if (patch->is_binary)2839 return apply_binary(img, patch);28402841 while (frag) {2842 nth++;2843 if (apply_one_fragment(img, frag, inaccurate_eof, ws_rule, nth)) {2844 error("patch failed: %s:%ld", name, frag->oldpos);2845 if (!apply_with_reject)2846 return -1;2847 frag->rejected = 1;2848 }2849 frag = frag->next;2850 }2851 return 0;2852}28532854static int read_file_or_gitlink(struct cache_entry *ce, struct strbuf *buf)2855{2856 if (!ce)2857 return 0;28582859 if (S_ISGITLINK(ce->ce_mode)) {2860 strbuf_grow(buf, 100);2861 strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(ce->sha1));2862 } else {2863 enum object_type type;2864 unsigned long sz;2865 char *result;28662867 result = read_sha1_file(ce->sha1, &type, &sz);2868 if (!result)2869 return -1;2870 /* XXX read_sha1_file NUL-terminates */2871 strbuf_attach(buf, result, sz, sz + 1);2872 }2873 return 0;2874}28752876static struct patch *in_fn_table(const char *name)2877{2878 struct string_list_item *item;28792880 if (name == NULL)2881 return NULL;28822883 item = string_list_lookup(&fn_table, name);2884 if (item != NULL)2885 return (struct patch *)item->util;28862887 return NULL;2888}28892890/*2891 * item->util in the filename table records the status of the path.2892 * Usually it points at a patch (whose result records the contents2893 * of it after applying it), but it could be PATH_WAS_DELETED for a2894 * path that a previously applied patch has already removed.2895 */2896 #define PATH_TO_BE_DELETED ((struct patch *) -2)2897#define PATH_WAS_DELETED ((struct patch *) -1)28982899static int to_be_deleted(struct patch *patch)2900{2901 return patch == PATH_TO_BE_DELETED;2902}29032904static int was_deleted(struct patch *patch)2905{2906 return patch == PATH_WAS_DELETED;2907}29082909static void add_to_fn_table(struct patch *patch)2910{2911 struct string_list_item *item;29122913 /*2914 * Always add new_name unless patch is a deletion2915 * This should cover the cases for normal diffs,2916 * file creations and copies2917 */2918 if (patch->new_name != NULL) {2919 item = string_list_insert(&fn_table, patch->new_name);2920 item->util = patch;2921 }29222923 /*2924 * store a failure on rename/deletion cases because2925 * later chunks shouldn't patch old names2926 */2927 if ((patch->new_name == NULL) || (patch->is_rename)) {2928 item = string_list_insert(&fn_table, patch->old_name);2929 item->util = PATH_WAS_DELETED;2930 }2931}29322933static void prepare_fn_table(struct patch *patch)2934{2935 /*2936 * store information about incoming file deletion2937 */2938 while (patch) {2939 if ((patch->new_name == NULL) || (patch->is_rename)) {2940 struct string_list_item *item;2941 item = string_list_insert(&fn_table, patch->old_name);2942 item->util = PATH_TO_BE_DELETED;2943 }2944 patch = patch->next;2945 }2946}29472948static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce)2949{2950 struct strbuf buf = STRBUF_INIT;2951 struct image image;2952 size_t len;2953 char *img;2954 struct patch *tpatch;29552956 if (!(patch->is_copy || patch->is_rename) &&2957 (tpatch = in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {2958 if (was_deleted(tpatch)) {2959 return error("patch %s has been renamed/deleted",2960 patch->old_name);2961 }2962 /* We have a patched copy in memory use that */2963 strbuf_add(&buf, tpatch->result, tpatch->resultsize);2964 } else if (cached) {2965 if (read_file_or_gitlink(ce, &buf))2966 return error("read of %s failed", patch->old_name);2967 } else if (patch->old_name) {2968 if (S_ISGITLINK(patch->old_mode)) {2969 if (ce) {2970 read_file_or_gitlink(ce, &buf);2971 } else {2972 /*2973 * There is no way to apply subproject2974 * patch without looking at the index.2975 */2976 patch->fragments = NULL;2977 }2978 } else {2979 if (read_old_data(st, patch->old_name, &buf))2980 return error("read of %s failed", patch->old_name);2981 }2982 }29832984 img = strbuf_detach(&buf, &len);2985 prepare_image(&image, img, len, !patch->is_binary);29862987 if (apply_fragments(&image, patch) < 0)2988 return -1; /* note with --reject this succeeds. */2989 patch->result = image.buf;2990 patch->resultsize = image.len;2991 add_to_fn_table(patch);2992 free(image.line_allocated);29932994 if (0 < patch->is_delete && patch->resultsize)2995 return error("removal patch leaves file contents");29962997 return 0;2998}29993000static int check_to_create_blob(const char *new_name, int ok_if_exists)3001{3002 struct stat nst;3003 if (!lstat(new_name, &nst)) {3004 if (S_ISDIR(nst.st_mode) || ok_if_exists)3005 return 0;3006 /*3007 * A leading component of new_name might be a symlink3008 * that is going to be removed with this patch, but3009 * still pointing at somewhere that has the path.3010 * In such a case, path "new_name" does not exist as3011 * far as git is concerned.3012 */3013 if (has_symlink_leading_path(new_name, strlen(new_name)))3014 return 0;30153016 return error("%s: already exists in working directory", new_name);3017 }3018 else if ((errno != ENOENT) && (errno != ENOTDIR))3019 return error("%s: %s", new_name, strerror(errno));3020 return 0;3021}30223023static int verify_index_match(struct cache_entry *ce, struct stat *st)3024{3025 if (S_ISGITLINK(ce->ce_mode)) {3026 if (!S_ISDIR(st->st_mode))3027 return -1;3028 return 0;3029 }3030 return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);3031}30323033static int check_preimage(struct patch *patch, struct cache_entry **ce, struct stat *st)3034{3035 const char *old_name = patch->old_name;3036 struct patch *tpatch = NULL;3037 int stat_ret = 0;3038 unsigned st_mode = 0;30393040 /*3041 * Make sure that we do not have local modifications from the3042 * index when we are looking at the index. Also make sure3043 * we have the preimage file to be patched in the work tree,3044 * unless --cached, which tells git to apply only in the index.3045 */3046 if (!old_name)3047 return 0;30483049 assert(patch->is_new <= 0);30503051 if (!(patch->is_copy || patch->is_rename) &&3052 (tpatch = in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {3053 if (was_deleted(tpatch))3054 return error("%s: has been deleted/renamed", old_name);3055 st_mode = tpatch->new_mode;3056 } else if (!cached) {3057 stat_ret = lstat(old_name, st);3058 if (stat_ret && errno != ENOENT)3059 return error("%s: %s", old_name, strerror(errno));3060 }30613062 if (to_be_deleted(tpatch))3063 tpatch = NULL;30643065 if (check_index && !tpatch) {3066 int pos = cache_name_pos(old_name, strlen(old_name));3067 if (pos < 0) {3068 if (patch->is_new < 0)3069 goto is_new;3070 return error("%s: does not exist in index", old_name);3071 }3072 *ce = active_cache[pos];3073 if (stat_ret < 0) {3074 struct checkout costate;3075 /* checkout */3076 memset(&costate, 0, sizeof(costate));3077 costate.base_dir = "";3078 costate.refresh_cache = 1;3079 if (checkout_entry(*ce, &costate, NULL) ||3080 lstat(old_name, st))3081 return -1;3082 }3083 if (!cached && verify_index_match(*ce, st))3084 return error("%s: does not match index", old_name);3085 if (cached)3086 st_mode = (*ce)->ce_mode;3087 } else if (stat_ret < 0) {3088 if (patch->is_new < 0)3089 goto is_new;3090 return error("%s: %s", old_name, strerror(errno));3091 }30923093 if (!cached && !tpatch)3094 st_mode = ce_mode_from_stat(*ce, st->st_mode);30953096 if (patch->is_new < 0)3097 patch->is_new = 0;3098 if (!patch->old_mode)3099 patch->old_mode = st_mode;3100 if ((st_mode ^ patch->old_mode) & S_IFMT)3101 return error("%s: wrong type", old_name);3102 if (st_mode != patch->old_mode)3103 warning("%s has type %o, expected %o",3104 old_name, st_mode, patch->old_mode);3105 if (!patch->new_mode && !patch->is_delete)3106 patch->new_mode = st_mode;3107 return 0;31083109 is_new:3110 patch->is_new = 1;3111 patch->is_delete = 0;3112 patch->old_name = NULL;3113 return 0;3114}31153116static int check_patch(struct patch *patch)3117{3118 struct stat st;3119 const char *old_name = patch->old_name;3120 const char *new_name = patch->new_name;3121 const char *name = old_name ? old_name : new_name;3122 struct cache_entry *ce = NULL;3123 struct patch *tpatch;3124 int ok_if_exists;3125 int status;31263127 patch->rejected = 1; /* we will drop this after we succeed */31283129 status = check_preimage(patch, &ce, &st);3130 if (status)3131 return status;3132 old_name = patch->old_name;31333134 if ((tpatch = in_fn_table(new_name)) &&3135 (was_deleted(tpatch) || to_be_deleted(tpatch)))3136 /*3137 * A type-change diff is always split into a patch to3138 * delete old, immediately followed by a patch to3139 * create new (see diff.c::run_diff()); in such a case3140 * it is Ok that the entry to be deleted by the3141 * previous patch is still in the working tree and in3142 * the index.3143 */3144 ok_if_exists = 1;3145 else3146 ok_if_exists = 0;31473148 if (new_name &&3149 ((0 < patch->is_new) | (0 < patch->is_rename) | patch->is_copy)) {3150 if (check_index &&3151 cache_name_pos(new_name, strlen(new_name)) >= 0 &&3152 !ok_if_exists)3153 return error("%s: already exists in index", new_name);3154 if (!cached) {3155 int err = check_to_create_blob(new_name, ok_if_exists);3156 if (err)3157 return err;3158 }3159 if (!patch->new_mode) {3160 if (0 < patch->is_new)3161 patch->new_mode = S_IFREG | 0644;3162 else3163 patch->new_mode = patch->old_mode;3164 }3165 }31663167 if (new_name && old_name) {3168 int same = !strcmp(old_name, new_name);3169 if (!patch->new_mode)3170 patch->new_mode = patch->old_mode;3171 if ((patch->old_mode ^ patch->new_mode) & S_IFMT)3172 return error("new mode (%o) of %s does not match old mode (%o)%s%s",3173 patch->new_mode, new_name, patch->old_mode,3174 same ? "" : " of ", same ? "" : old_name);3175 }31763177 if (apply_data(patch, &st, ce) < 0)3178 return error("%s: patch does not apply", name);3179 patch->rejected = 0;3180 return 0;3181}31823183static int check_patch_list(struct patch *patch)3184{3185 int err = 0;31863187 prepare_fn_table(patch);3188 while (patch) {3189 if (apply_verbosely)3190 say_patch_name(stderr,3191 "Checking patch ", patch, "...\n");3192 err |= check_patch(patch);3193 patch = patch->next;3194 }3195 return err;3196}31973198/* This function tries to read the sha1 from the current index */3199static int get_current_sha1(const char *path, unsigned char *sha1)3200{3201 int pos;32023203 if (read_cache() < 0)3204 return -1;3205 pos = cache_name_pos(path, strlen(path));3206 if (pos < 0)3207 return -1;3208 hashcpy(sha1, active_cache[pos]->sha1);3209 return 0;3210}32113212/* Build an index that contains the just the files needed for a 3way merge */3213static void build_fake_ancestor(struct patch *list, const char *filename)3214{3215 struct patch *patch;3216 struct index_state result = { NULL };3217 int fd;32183219 /* Once we start supporting the reverse patch, it may be3220 * worth showing the new sha1 prefix, but until then...3221 */3222 for (patch = list; patch; patch = patch->next) {3223 const unsigned char *sha1_ptr;3224 unsigned char sha1[20];3225 struct cache_entry *ce;3226 const char *name;32273228 name = patch->old_name ? patch->old_name : patch->new_name;3229 if (0 < patch->is_new)3230 continue;3231 else if (get_sha1(patch->old_sha1_prefix, sha1))3232 /* git diff has no index line for mode/type changes */3233 if (!patch->lines_added && !patch->lines_deleted) {3234 if (get_current_sha1(patch->old_name, sha1))3235 die("mode change for %s, which is not "3236 "in current HEAD", name);3237 sha1_ptr = sha1;3238 } else3239 die("sha1 information is lacking or useless "3240 "(%s).", name);3241 else3242 sha1_ptr = sha1;32433244 ce = make_cache_entry(patch->old_mode, sha1_ptr, name, 0, 0);3245 if (!ce)3246 die("make_cache_entry failed for path '%s'", name);3247 if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))3248 die ("Could not add %s to temporary index", name);3249 }32503251 fd = open(filename, O_WRONLY | O_CREAT, 0666);3252 if (fd < 0 || write_index(&result, fd) || close(fd))3253 die ("Could not write temporary index to %s", filename);32543255 discard_index(&result);3256}32573258static void stat_patch_list(struct patch *patch)3259{3260 int files, adds, dels;32613262 for (files = adds = dels = 0 ; patch ; patch = patch->next) {3263 files++;3264 adds += patch->lines_added;3265 dels += patch->lines_deleted;3266 show_stats(patch);3267 }32683269 printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);3270}32713272static void numstat_patch_list(struct patch *patch)3273{3274 for ( ; patch; patch = patch->next) {3275 const char *name;3276 name = patch->new_name ? patch->new_name : patch->old_name;3277 if (patch->is_binary)3278 printf("-\t-\t");3279 else3280 printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);3281 write_name_quoted(name, stdout, line_termination);3282 }3283}32843285static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)3286{3287 if (mode)3288 printf(" %s mode %06o %s\n", newdelete, mode, name);3289 else3290 printf(" %s %s\n", newdelete, name);3291}32923293static void show_mode_change(struct patch *p, int show_name)3294{3295 if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {3296 if (show_name)3297 printf(" mode change %06o => %06o %s\n",3298 p->old_mode, p->new_mode, p->new_name);3299 else3300 printf(" mode change %06o => %06o\n",3301 p->old_mode, p->new_mode);3302 }3303}33043305static void show_rename_copy(struct patch *p)3306{3307 const char *renamecopy = p->is_rename ? "rename" : "copy";3308 const char *old, *new;33093310 /* Find common prefix */3311 old = p->old_name;3312 new = p->new_name;3313 while (1) {3314 const char *slash_old, *slash_new;3315 slash_old = strchr(old, '/');3316 slash_new = strchr(new, '/');3317 if (!slash_old ||3318 !slash_new ||3319 slash_old - old != slash_new - new ||3320 memcmp(old, new, slash_new - new))3321 break;3322 old = slash_old + 1;3323 new = slash_new + 1;3324 }3325 /* p->old_name thru old is the common prefix, and old and new3326 * through the end of names are renames3327 */3328 if (old != p->old_name)3329 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,3330 (int)(old - p->old_name), p->old_name,3331 old, new, p->score);3332 else3333 printf(" %s %s => %s (%d%%)\n", renamecopy,3334 p->old_name, p->new_name, p->score);3335 show_mode_change(p, 0);3336}33373338static void summary_patch_list(struct patch *patch)3339{3340 struct patch *p;33413342 for (p = patch; p; p = p->next) {3343 if (p->is_new)3344 show_file_mode_name("create", p->new_mode, p->new_name);3345 else if (p->is_delete)3346 show_file_mode_name("delete", p->old_mode, p->old_name);3347 else {3348 if (p->is_rename || p->is_copy)3349 show_rename_copy(p);3350 else {3351 if (p->score) {3352 printf(" rewrite %s (%d%%)\n",3353 p->new_name, p->score);3354 show_mode_change(p, 0);3355 }3356 else3357 show_mode_change(p, 1);3358 }3359 }3360 }3361}33623363static void patch_stats(struct patch *patch)3364{3365 int lines = patch->lines_added + patch->lines_deleted;33663367 if (lines > max_change)3368 max_change = lines;3369 if (patch->old_name) {3370 int len = quote_c_style(patch->old_name, NULL, NULL, 0);3371 if (!len)3372 len = strlen(patch->old_name);3373 if (len > max_len)3374 max_len = len;3375 }3376 if (patch->new_name) {3377 int len = quote_c_style(patch->new_name, NULL, NULL, 0);3378 if (!len)3379 len = strlen(patch->new_name);3380 if (len > max_len)3381 max_len = len;3382 }3383}33843385static void remove_file(struct patch *patch, int rmdir_empty)3386{3387 if (update_index) {3388 if (remove_file_from_cache(patch->old_name) < 0)3389 die("unable to remove %s from index", patch->old_name);3390 }3391 if (!cached) {3392 if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {3393 remove_path(patch->old_name);3394 }3395 }3396}33973398static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)3399{3400 struct stat st;3401 struct cache_entry *ce;3402 int namelen = strlen(path);3403 unsigned ce_size = cache_entry_size(namelen);34043405 if (!update_index)3406 return;34073408 ce = xcalloc(1, ce_size);3409 memcpy(ce->name, path, namelen);3410 ce->ce_mode = create_ce_mode(mode);3411 ce->ce_flags = namelen;3412 if (S_ISGITLINK(mode)) {3413 const char *s = buf;34143415 if (get_sha1_hex(s + strlen("Subproject commit "), ce->sha1))3416 die("corrupt patch for subproject %s", path);3417 } else {3418 if (!cached) {3419 if (lstat(path, &st) < 0)3420 die_errno("unable to stat newly created file '%s'",3421 path);3422 fill_stat_cache_info(ce, &st);3423 }3424 if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)3425 die("unable to create backing store for newly created file %s", path);3426 }3427 if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)3428 die("unable to add cache entry for %s", path);3429}34303431static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)3432{3433 int fd;3434 struct strbuf nbuf = STRBUF_INIT;34353436 if (S_ISGITLINK(mode)) {3437 struct stat st;3438 if (!lstat(path, &st) && S_ISDIR(st.st_mode))3439 return 0;3440 return mkdir(path, 0777);3441 }34423443 if (has_symlinks && S_ISLNK(mode))3444 /* Although buf:size is counted string, it also is NUL3445 * terminated.3446 */3447 return symlink(buf, path);34483449 fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);3450 if (fd < 0)3451 return -1;34523453 if (convert_to_working_tree(path, buf, size, &nbuf)) {3454 size = nbuf.len;3455 buf = nbuf.buf;3456 }3457 write_or_die(fd, buf, size);3458 strbuf_release(&nbuf);34593460 if (close(fd) < 0)3461 die_errno("closing file '%s'", path);3462 return 0;3463}34643465/*3466 * We optimistically assume that the directories exist,3467 * which is true 99% of the time anyway. If they don't,3468 * we create them and try again.3469 */3470static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)3471{3472 if (cached)3473 return;3474 if (!try_create_file(path, mode, buf, size))3475 return;34763477 if (errno == ENOENT) {3478 if (safe_create_leading_directories(path))3479 return;3480 if (!try_create_file(path, mode, buf, size))3481 return;3482 }34833484 if (errno == EEXIST || errno == EACCES) {3485 /* We may be trying to create a file where a directory3486 * used to be.3487 */3488 struct stat st;3489 if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))3490 errno = EEXIST;3491 }34923493 if (errno == EEXIST) {3494 unsigned int nr = getpid();34953496 for (;;) {3497 char newpath[PATH_MAX];3498 mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);3499 if (!try_create_file(newpath, mode, buf, size)) {3500 if (!rename(newpath, path))3501 return;3502 unlink_or_warn(newpath);3503 break;3504 }3505 if (errno != EEXIST)3506 break;3507 ++nr;3508 }3509 }3510 die_errno("unable to write file '%s' mode %o", path, mode);3511}35123513static void create_file(struct patch *patch)3514{3515 char *path = patch->new_name;3516 unsigned mode = patch->new_mode;3517 unsigned long size = patch->resultsize;3518 char *buf = patch->result;35193520 if (!mode)3521 mode = S_IFREG | 0644;3522 create_one_file(path, mode, buf, size);3523 add_index_file(path, mode, buf, size);3524}35253526/* phase zero is to remove, phase one is to create */3527static void write_out_one_result(struct patch *patch, int phase)3528{3529 if (patch->is_delete > 0) {3530 if (phase == 0)3531 remove_file(patch, 1);3532 return;3533 }3534 if (patch->is_new > 0 || patch->is_copy) {3535 if (phase == 1)3536 create_file(patch);3537 return;3538 }3539 /*3540 * Rename or modification boils down to the same3541 * thing: remove the old, write the new3542 */3543 if (phase == 0)3544 remove_file(patch, patch->is_rename);3545 if (phase == 1)3546 create_file(patch);3547}35483549static int write_out_one_reject(struct patch *patch)3550{3551 FILE *rej;3552 char namebuf[PATH_MAX];3553 struct fragment *frag;3554 int cnt = 0;35553556 for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {3557 if (!frag->rejected)3558 continue;3559 cnt++;3560 }35613562 if (!cnt) {3563 if (apply_verbosely)3564 say_patch_name(stderr,3565 "Applied patch ", patch, " cleanly.\n");3566 return 0;3567 }35683569 /* This should not happen, because a removal patch that leaves3570 * contents are marked "rejected" at the patch level.3571 */3572 if (!patch->new_name)3573 die("internal error");35743575 /* Say this even without --verbose */3576 say_patch_name(stderr, "Applying patch ", patch, " with");3577 fprintf(stderr, " %d rejects...\n", cnt);35783579 cnt = strlen(patch->new_name);3580 if (ARRAY_SIZE(namebuf) <= cnt + 5) {3581 cnt = ARRAY_SIZE(namebuf) - 5;3582 warning("truncating .rej filename to %.*s.rej",3583 cnt - 1, patch->new_name);3584 }3585 memcpy(namebuf, patch->new_name, cnt);3586 memcpy(namebuf + cnt, ".rej", 5);35873588 rej = fopen(namebuf, "w");3589 if (!rej)3590 return error("cannot open %s: %s", namebuf, strerror(errno));35913592 /* Normal git tools never deal with .rej, so do not pretend3593 * this is a git patch by saying --git nor give extended3594 * headers. While at it, maybe please "kompare" that wants3595 * the trailing TAB and some garbage at the end of line ;-).3596 */3597 fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",3598 patch->new_name, patch->new_name);3599 for (cnt = 1, frag = patch->fragments;3600 frag;3601 cnt++, frag = frag->next) {3602 if (!frag->rejected) {3603 fprintf(stderr, "Hunk #%d applied cleanly.\n", cnt);3604 continue;3605 }3606 fprintf(stderr, "Rejected hunk #%d.\n", cnt);3607 fprintf(rej, "%.*s", frag->size, frag->patch);3608 if (frag->patch[frag->size-1] != '\n')3609 fputc('\n', rej);3610 }3611 fclose(rej);3612 return -1;3613}36143615static int write_out_results(struct patch *list)3616{3617 int phase;3618 int errs = 0;3619 struct patch *l;36203621 for (phase = 0; phase < 2; phase++) {3622 l = list;3623 while (l) {3624 if (l->rejected)3625 errs = 1;3626 else {3627 write_out_one_result(l, phase);3628 if (phase == 1 && write_out_one_reject(l))3629 errs = 1;3630 }3631 l = l->next;3632 }3633 }3634 return errs;3635}36363637static struct lock_file lock_file;36383639static struct string_list limit_by_name;3640static int has_include;3641static void add_name_limit(const char *name, int exclude)3642{3643 struct string_list_item *it;36443645 it = string_list_append(&limit_by_name, name);3646 it->util = exclude ? NULL : (void *) 1;3647}36483649static int use_patch(struct patch *p)3650{3651 const char *pathname = p->new_name ? p->new_name : p->old_name;3652 int i;36533654 /* Paths outside are not touched regardless of "--include" */3655 if (0 < prefix_length) {3656 int pathlen = strlen(pathname);3657 if (pathlen <= prefix_length ||3658 memcmp(prefix, pathname, prefix_length))3659 return 0;3660 }36613662 /* See if it matches any of exclude/include rule */3663 for (i = 0; i < limit_by_name.nr; i++) {3664 struct string_list_item *it = &limit_by_name.items[i];3665 if (!fnmatch(it->string, pathname, 0))3666 return (it->util != NULL);3667 }36683669 /*3670 * If we had any include, a path that does not match any rule is3671 * not used. Otherwise, we saw bunch of exclude rules (or none)3672 * and such a path is used.3673 */3674 return !has_include;3675}367636773678static void prefix_one(char **name)3679{3680 char *old_name = *name;3681 if (!old_name)3682 return;3683 *name = xstrdup(prefix_filename(prefix, prefix_length, *name));3684 free(old_name);3685}36863687static void prefix_patches(struct patch *p)3688{3689 if (!prefix || p->is_toplevel_relative)3690 return;3691 for ( ; p; p = p->next) {3692 if (p->new_name == p->old_name) {3693 char *prefixed = p->new_name;3694 prefix_one(&prefixed);3695 p->new_name = p->old_name = prefixed;3696 }3697 else {3698 prefix_one(&p->new_name);3699 prefix_one(&p->old_name);3700 }3701 }3702}37033704#define INACCURATE_EOF (1<<0)3705#define RECOUNT (1<<1)37063707static int apply_patch(int fd, const char *filename, int options)3708{3709 size_t offset;3710 struct strbuf buf = STRBUF_INIT;3711 struct patch *list = NULL, **listp = &list;3712 int skipped_patch = 0;37133714 memset(&fn_table, 0, sizeof(struct string_list));3715 patch_input_file = filename;3716 read_patch_file(&buf, fd);3717 offset = 0;3718 while (offset < buf.len) {3719 struct patch *patch;3720 int nr;37213722 patch = xcalloc(1, sizeof(*patch));3723 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3724 patch->recount = !!(options & RECOUNT);3725 nr = parse_chunk(buf.buf + offset, buf.len - offset, patch);3726 if (nr < 0)3727 break;3728 if (apply_in_reverse)3729 reverse_patches(patch);3730 if (prefix)3731 prefix_patches(patch);3732 if (use_patch(patch)) {3733 patch_stats(patch);3734 *listp = patch;3735 listp = &patch->next;3736 }3737 else {3738 free_patch(patch);3739 skipped_patch++;3740 }3741 offset += nr;3742 }37433744 if (!list && !skipped_patch)3745 die("unrecognized input");37463747 if (whitespace_error && (ws_error_action == die_on_ws_error))3748 apply = 0;37493750 update_index = check_index && apply;3751 if (update_index && newfd < 0)3752 newfd = hold_locked_index(&lock_file, 1);37533754 if (check_index) {3755 if (read_cache() < 0)3756 die("unable to read index file");3757 }37583759 if ((check || apply) &&3760 check_patch_list(list) < 0 &&3761 !apply_with_reject)3762 exit(1);37633764 if (apply && write_out_results(list))3765 exit(1);37663767 if (fake_ancestor)3768 build_fake_ancestor(list, fake_ancestor);37693770 if (diffstat)3771 stat_patch_list(list);37723773 if (numstat)3774 numstat_patch_list(list);37753776 if (summary)3777 summary_patch_list(list);37783779 free_patch_list(list);3780 strbuf_release(&buf);3781 return 0;3782}37833784static int git_apply_config(const char *var, const char *value, void *cb)3785{3786 if (!strcmp(var, "apply.whitespace"))3787 return git_config_string(&apply_default_whitespace, var, value);3788 else if (!strcmp(var, "apply.ignorewhitespace"))3789 return git_config_string(&apply_default_ignorewhitespace, var, value);3790 return git_default_config(var, value, cb);3791}37923793static int option_parse_exclude(const struct option *opt,3794 const char *arg, int unset)3795{3796 add_name_limit(arg, 1);3797 return 0;3798}37993800static int option_parse_include(const struct option *opt,3801 const char *arg, int unset)3802{3803 add_name_limit(arg, 0);3804 has_include = 1;3805 return 0;3806}38073808static int option_parse_p(const struct option *opt,3809 const char *arg, int unset)3810{3811 p_value = atoi(arg);3812 p_value_known = 1;3813 return 0;3814}38153816static int option_parse_z(const struct option *opt,3817 const char *arg, int unset)3818{3819 if (unset)3820 line_termination = '\n';3821 else3822 line_termination = 0;3823 return 0;3824}38253826static int option_parse_space_change(const struct option *opt,3827 const char *arg, int unset)3828{3829 if (unset)3830 ws_ignore_action = ignore_ws_none;3831 else3832 ws_ignore_action = ignore_ws_change;3833 return 0;3834}38353836static int option_parse_whitespace(const struct option *opt,3837 const char *arg, int unset)3838{3839 const char **whitespace_option = opt->value;38403841 *whitespace_option = arg;3842 parse_whitespace_option(arg);3843 return 0;3844}38453846static int option_parse_directory(const struct option *opt,3847 const char *arg, int unset)3848{3849 root_len = strlen(arg);3850 if (root_len && arg[root_len - 1] != '/') {3851 char *new_root;3852 root = new_root = xmalloc(root_len + 2);3853 strcpy(new_root, arg);3854 strcpy(new_root + root_len++, "/");3855 } else3856 root = arg;3857 return 0;3858}38593860int cmd_apply(int argc, const char **argv, const char *prefix_)3861{3862 int i;3863 int errs = 0;3864 int is_not_gitdir = !startup_info->have_repository;3865 int force_apply = 0;38663867 const char *whitespace_option = NULL;38683869 struct option builtin_apply_options[] = {3870 { OPTION_CALLBACK, 0, "exclude", NULL, "path",3871 "don't apply changes matching the given path",3872 0, option_parse_exclude },3873 { OPTION_CALLBACK, 0, "include", NULL, "path",3874 "apply changes matching the given path",3875 0, option_parse_include },3876 { OPTION_CALLBACK, 'p', NULL, NULL, "num",3877 "remove <num> leading slashes from traditional diff paths",3878 0, option_parse_p },3879 OPT_BOOLEAN(0, "no-add", &no_add,3880 "ignore additions made by the patch"),3881 OPT_BOOLEAN(0, "stat", &diffstat,3882 "instead of applying the patch, output diffstat for the input"),3883 OPT_NOOP_NOARG(0, "allow-binary-replacement"),3884 OPT_NOOP_NOARG(0, "binary"),3885 OPT_BOOLEAN(0, "numstat", &numstat,3886 "shows number of added and deleted lines in decimal notation"),3887 OPT_BOOLEAN(0, "summary", &summary,3888 "instead of applying the patch, output a summary for the input"),3889 OPT_BOOLEAN(0, "check", &check,3890 "instead of applying the patch, see if the patch is applicable"),3891 OPT_BOOLEAN(0, "index", &check_index,3892 "make sure the patch is applicable to the current index"),3893 OPT_BOOLEAN(0, "cached", &cached,3894 "apply a patch without touching the working tree"),3895 OPT_BOOLEAN(0, "apply", &force_apply,3896 "also apply the patch (use with --stat/--summary/--check)"),3897 OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor,3898 "build a temporary index based on embedded index information"),3899 { OPTION_CALLBACK, 'z', NULL, NULL, NULL,3900 "paths are separated with NUL character",3901 PARSE_OPT_NOARG, option_parse_z },3902 OPT_INTEGER('C', NULL, &p_context,3903 "ensure at least <n> lines of context match"),3904 { OPTION_CALLBACK, 0, "whitespace", &whitespace_option, "action",3905 "detect new or modified lines that have whitespace errors",3906 0, option_parse_whitespace },3907 { OPTION_CALLBACK, 0, "ignore-space-change", NULL, NULL,3908 "ignore changes in whitespace when finding context",3909 PARSE_OPT_NOARG, option_parse_space_change },3910 { OPTION_CALLBACK, 0, "ignore-whitespace", NULL, NULL,3911 "ignore changes in whitespace when finding context",3912 PARSE_OPT_NOARG, option_parse_space_change },3913 OPT_BOOLEAN('R', "reverse", &apply_in_reverse,3914 "apply the patch in reverse"),3915 OPT_BOOLEAN(0, "unidiff-zero", &unidiff_zero,3916 "don't expect at least one line of context"),3917 OPT_BOOLEAN(0, "reject", &apply_with_reject,3918 "leave the rejected hunks in corresponding *.rej files"),3919 OPT_BOOLEAN(0, "allow-overlap", &allow_overlap,3920 "allow overlapping hunks"),3921 OPT__VERBOSE(&apply_verbosely, "be verbose"),3922 OPT_BIT(0, "inaccurate-eof", &options,3923 "tolerate incorrectly detected missing new-line at the end of file",3924 INACCURATE_EOF),3925 OPT_BIT(0, "recount", &options,3926 "do not trust the line counts in the hunk headers",3927 RECOUNT),3928 { OPTION_CALLBACK, 0, "directory", NULL, "root",3929 "prepend <root> to all filenames",3930 0, option_parse_directory },3931 OPT_END()3932 };39333934 prefix = prefix_;3935 prefix_length = prefix ? strlen(prefix) : 0;3936 git_config(git_apply_config, NULL);3937 if (apply_default_whitespace)3938 parse_whitespace_option(apply_default_whitespace);3939 if (apply_default_ignorewhitespace)3940 parse_ignorewhitespace_option(apply_default_ignorewhitespace);39413942 argc = parse_options(argc, argv, prefix, builtin_apply_options,3943 apply_usage, 0);39443945 if (apply_with_reject)3946 apply = apply_verbosely = 1;3947 if (!force_apply && (diffstat || numstat || summary || check || fake_ancestor))3948 apply = 0;3949 if (check_index && is_not_gitdir)3950 die("--index outside a repository");3951 if (cached) {3952 if (is_not_gitdir)3953 die("--cached outside a repository");3954 check_index = 1;3955 }3956 for (i = 0; i < argc; i++) {3957 const char *arg = argv[i];3958 int fd;39593960 if (!strcmp(arg, "-")) {3961 errs |= apply_patch(0, "<stdin>", options);3962 read_stdin = 0;3963 continue;3964 } else if (0 < prefix_length)3965 arg = prefix_filename(prefix, prefix_length, arg);39663967 fd = open(arg, O_RDONLY);3968 if (fd < 0)3969 die_errno("can't open patch '%s'", arg);3970 read_stdin = 0;3971 set_default_whitespace_mode(whitespace_option);3972 errs |= apply_patch(fd, arg, options);3973 close(fd);3974 }3975 set_default_whitespace_mode(whitespace_option);3976 if (read_stdin)3977 errs |= apply_patch(0, "<stdin>", options);3978 if (whitespace_error) {3979 if (squelch_whitespace_errors &&3980 squelch_whitespace_errors < whitespace_error) {3981 int squelched =3982 whitespace_error - squelch_whitespace_errors;3983 warning("squelched %d "3984 "whitespace error%s",3985 squelched,3986 squelched == 1 ? "" : "s");3987 }3988 if (ws_error_action == die_on_ws_error)3989 die("%d line%s add%s whitespace errors.",3990 whitespace_error,3991 whitespace_error == 1 ? "" : "s",3992 whitespace_error == 1 ? "s" : "");3993 if (applied_after_fixing_ws && apply)3994 warning("%d line%s applied after"3995 " fixing whitespace errors.",3996 applied_after_fixing_ws,3997 applied_after_fixing_ws == 1 ? "" : "s");3998 else if (whitespace_error)3999 warning("%d line%s add%s whitespace errors.",4000 whitespace_error,4001 whitespace_error == 1 ? "" : "s",4002 whitespace_error == 1 ? "s" : "");4003 }40044005 if (update_index) {4006 if (write_cache(newfd, active_cache, active_nr) ||4007 commit_locked_index(&lock_file))4008 die("Unable to write new index file");4009 }40104011 return !!errs;4012}