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 no_add; 47static const char*fake_ancestor; 48static int line_termination ='\n'; 49static unsigned int p_context = UINT_MAX; 50static const char*const apply_usage[] = { 51"git apply [options] [<patch>...]", 52 NULL 53}; 54 55static enum ws_error_action { 56 nowarn_ws_error, 57 warn_on_ws_error, 58 die_on_ws_error, 59 correct_ws_error, 60} ws_error_action = warn_on_ws_error; 61static int whitespace_error; 62static int squelch_whitespace_errors =5; 63static int applied_after_fixing_ws; 64 65static enum ws_ignore { 66 ignore_ws_none, 67 ignore_ws_change, 68} ws_ignore_action = ignore_ws_none; 69 70 71static const char*patch_input_file; 72static const char*root; 73static int root_len; 74static int read_stdin =1; 75static int options; 76 77static voidparse_whitespace_option(const char*option) 78{ 79if(!option) { 80 ws_error_action = warn_on_ws_error; 81return; 82} 83if(!strcmp(option,"warn")) { 84 ws_error_action = warn_on_ws_error; 85return; 86} 87if(!strcmp(option,"nowarn")) { 88 ws_error_action = nowarn_ws_error; 89return; 90} 91if(!strcmp(option,"error")) { 92 ws_error_action = die_on_ws_error; 93return; 94} 95if(!strcmp(option,"error-all")) { 96 ws_error_action = die_on_ws_error; 97 squelch_whitespace_errors =0; 98return; 99} 100if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 101 ws_error_action = correct_ws_error; 102return; 103} 104die("unrecognized whitespace option '%s'", option); 105} 106 107static voidparse_ignorewhitespace_option(const char*option) 108{ 109if(!option || !strcmp(option,"no") || 110!strcmp(option,"false") || !strcmp(option,"never") || 111!strcmp(option,"none")) { 112 ws_ignore_action = ignore_ws_none; 113return; 114} 115if(!strcmp(option,"change")) { 116 ws_ignore_action = ignore_ws_change; 117return; 118} 119die("unrecognized whitespace ignore option '%s'", option); 120} 121 122static voidset_default_whitespace_mode(const char*whitespace_option) 123{ 124if(!whitespace_option && !apply_default_whitespace) 125 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 126} 127 128/* 129 * For "diff-stat" like behaviour, we keep track of the biggest change 130 * we've seen, and the longest filename. That allows us to do simple 131 * scaling. 132 */ 133static int max_change, max_len; 134 135/* 136 * Various "current state", notably line numbers and what 137 * file (and how) we're patching right now.. The "is_xxxx" 138 * things are flags, where -1 means "don't know yet". 139 */ 140static int linenr =1; 141 142/* 143 * This represents one "hunk" from a patch, starting with 144 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 145 * patch text is pointed at by patch, and its byte length 146 * is stored in size. leading and trailing are the number 147 * of context lines. 148 */ 149struct fragment { 150unsigned long leading, trailing; 151unsigned long oldpos, oldlines; 152unsigned long newpos, newlines; 153const char*patch; 154int size; 155int rejected; 156int linenr; 157struct fragment *next; 158}; 159 160/* 161 * When dealing with a binary patch, we reuse "leading" field 162 * to store the type of the binary hunk, either deflated "delta" 163 * or deflated "literal". 164 */ 165#define binary_patch_method leading 166#define BINARY_DELTA_DEFLATED 1 167#define BINARY_LITERAL_DEFLATED 2 168 169/* 170 * This represents a "patch" to a file, both metainfo changes 171 * such as creation/deletion, filemode and content changes represented 172 * as a series of fragments. 173 */ 174struct patch { 175char*new_name, *old_name, *def_name; 176unsigned int old_mode, new_mode; 177int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 178int rejected; 179unsigned ws_rule; 180unsigned long deflate_origlen; 181int lines_added, lines_deleted; 182int score; 183unsigned int is_toplevel_relative:1; 184unsigned int inaccurate_eof:1; 185unsigned int is_binary:1; 186unsigned int is_copy:1; 187unsigned int is_rename:1; 188unsigned int recount:1; 189struct fragment *fragments; 190char*result; 191size_t resultsize; 192char old_sha1_prefix[41]; 193char new_sha1_prefix[41]; 194struct patch *next; 195}; 196 197/* 198 * A line in a file, len-bytes long (includes the terminating LF, 199 * except for an incomplete line at the end if the file ends with 200 * one), and its contents hashes to 'hash'. 201 */ 202struct line { 203size_t len; 204unsigned hash :24; 205unsigned flag :8; 206#define LINE_COMMON 1 207}; 208 209/* 210 * This represents a "file", which is an array of "lines". 211 */ 212struct image { 213char*buf; 214size_t len; 215size_t nr; 216size_t alloc; 217struct line *line_allocated; 218struct line *line; 219}; 220 221/* 222 * Records filenames that have been touched, in order to handle 223 * the case where more than one patches touch the same file. 224 */ 225 226static struct string_list fn_table; 227 228static uint32_thash_line(const char*cp,size_t len) 229{ 230size_t i; 231uint32_t h; 232for(i =0, h =0; i < len; i++) { 233if(!isspace(cp[i])) { 234 h = h *3+ (cp[i] &0xff); 235} 236} 237return h; 238} 239 240/* 241 * Compare lines s1 of length n1 and s2 of length n2, ignoring 242 * whitespace difference. Returns 1 if they match, 0 otherwise 243 */ 244static intfuzzy_matchlines(const char*s1,size_t n1, 245const char*s2,size_t n2) 246{ 247const char*last1 = s1 + n1 -1; 248const char*last2 = s2 + n2 -1; 249int result =0; 250 251if(n1 <0|| n2 <0) 252return0; 253 254/* ignore line endings */ 255while((*last1 =='\r') || (*last1 =='\n')) 256 last1--; 257while((*last2 =='\r') || (*last2 =='\n')) 258 last2--; 259 260/* skip leading whitespace */ 261while(isspace(*s1) && (s1 <= last1)) 262 s1++; 263while(isspace(*s2) && (s2 <= last2)) 264 s2++; 265/* early return if both lines are empty */ 266if((s1 > last1) && (s2 > last2)) 267return1; 268while(!result) { 269 result = *s1++ - *s2++; 270/* 271 * Skip whitespace inside. We check for whitespace on 272 * both buffers because we don't want "a b" to match 273 * "ab" 274 */ 275if(isspace(*s1) &&isspace(*s2)) { 276while(isspace(*s1) && s1 <= last1) 277 s1++; 278while(isspace(*s2) && s2 <= last2) 279 s2++; 280} 281/* 282 * If we reached the end on one side only, 283 * lines don't match 284 */ 285if( 286((s2 > last2) && (s1 <= last1)) || 287((s1 > last1) && (s2 <= last2))) 288return0; 289if((s1 > last1) && (s2 > last2)) 290break; 291} 292 293return!result; 294} 295 296static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 297{ 298ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 299 img->line_allocated[img->nr].len = len; 300 img->line_allocated[img->nr].hash =hash_line(bol, len); 301 img->line_allocated[img->nr].flag = flag; 302 img->nr++; 303} 304 305static voidprepare_image(struct image *image,char*buf,size_t len, 306int prepare_linetable) 307{ 308const char*cp, *ep; 309 310memset(image,0,sizeof(*image)); 311 image->buf = buf; 312 image->len = len; 313 314if(!prepare_linetable) 315return; 316 317 ep = image->buf + image->len; 318 cp = image->buf; 319while(cp < ep) { 320const char*next; 321for(next = cp; next < ep && *next !='\n'; next++) 322; 323if(next < ep) 324 next++; 325add_line_info(image, cp, next - cp,0); 326 cp = next; 327} 328 image->line = image->line_allocated; 329} 330 331static voidclear_image(struct image *image) 332{ 333free(image->buf); 334 image->buf = NULL; 335 image->len =0; 336} 337 338static voidsay_patch_name(FILE*output,const char*pre, 339struct patch *patch,const char*post) 340{ 341fputs(pre, output); 342if(patch->old_name && patch->new_name && 343strcmp(patch->old_name, patch->new_name)) { 344quote_c_style(patch->old_name, NULL, output,0); 345fputs(" => ", output); 346quote_c_style(patch->new_name, NULL, output,0); 347}else{ 348const char*n = patch->new_name; 349if(!n) 350 n = patch->old_name; 351quote_c_style(n, NULL, output,0); 352} 353fputs(post, output); 354} 355 356#define CHUNKSIZE (8192) 357#define SLOP (16) 358 359static voidread_patch_file(struct strbuf *sb,int fd) 360{ 361if(strbuf_read(sb, fd,0) <0) 362die_errno("git apply: failed to read"); 363 364/* 365 * Make sure that we have some slop in the buffer 366 * so that we can do speculative "memcmp" etc, and 367 * see to it that it is NUL-filled. 368 */ 369strbuf_grow(sb, SLOP); 370memset(sb->buf + sb->len,0, SLOP); 371} 372 373static unsigned longlinelen(const char*buffer,unsigned long size) 374{ 375unsigned long len =0; 376while(size--) { 377 len++; 378if(*buffer++ =='\n') 379break; 380} 381return len; 382} 383 384static intis_dev_null(const char*str) 385{ 386return!memcmp("/dev/null", str,9) &&isspace(str[9]); 387} 388 389#define TERM_SPACE 1 390#define TERM_TAB 2 391 392static intname_terminate(const char*name,int namelen,int c,int terminate) 393{ 394if(c ==' '&& !(terminate & TERM_SPACE)) 395return0; 396if(c =='\t'&& !(terminate & TERM_TAB)) 397return0; 398 399return1; 400} 401 402/* remove double slashes to make --index work with such filenames */ 403static char*squash_slash(char*name) 404{ 405int i =0, j =0; 406 407while(name[i]) { 408if((name[j++] = name[i++]) =='/') 409while(name[i] =='/') 410 i++; 411} 412 name[j] ='\0'; 413return name; 414} 415 416static char*find_name(const char*line,char*def,int p_value,int terminate) 417{ 418int len; 419const char*start = line; 420 421if(*line =='"') { 422struct strbuf name = STRBUF_INIT; 423 424/* 425 * Proposed "new-style" GNU patch/diff format; see 426 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2 427 */ 428if(!unquote_c_style(&name, line, NULL)) { 429char*cp; 430 431for(cp = name.buf; p_value; p_value--) { 432 cp =strchr(cp,'/'); 433if(!cp) 434break; 435 cp++; 436} 437if(cp) { 438/* name can later be freed, so we need 439 * to memmove, not just return cp 440 */ 441strbuf_remove(&name,0, cp - name.buf); 442free(def); 443if(root) 444strbuf_insert(&name,0, root, root_len); 445returnsquash_slash(strbuf_detach(&name, NULL)); 446} 447} 448strbuf_release(&name); 449} 450 451for(;;) { 452char c = *line; 453 454if(isspace(c)) { 455if(c =='\n') 456break; 457if(name_terminate(start, line-start, c, terminate)) 458break; 459} 460 line++; 461if(c =='/'&& !--p_value) 462 start = line; 463} 464if(!start) 465returnsquash_slash(def); 466 len = line - start; 467if(!len) 468returnsquash_slash(def); 469 470/* 471 * Generally we prefer the shorter name, especially 472 * if the other one is just a variation of that with 473 * something else tacked on to the end (ie "file.orig" 474 * or "file~"). 475 */ 476if(def) { 477int deflen =strlen(def); 478if(deflen < len && !strncmp(start, def, deflen)) 479returnsquash_slash(def); 480free(def); 481} 482 483if(root) { 484char*ret =xmalloc(root_len + len +1); 485strcpy(ret, root); 486memcpy(ret + root_len, start, len); 487 ret[root_len + len] ='\0'; 488returnsquash_slash(ret); 489} 490 491returnsquash_slash(xmemdupz(start, len)); 492} 493 494static intcount_slashes(const char*cp) 495{ 496int cnt =0; 497char ch; 498 499while((ch = *cp++)) 500if(ch =='/') 501 cnt++; 502return cnt; 503} 504 505/* 506 * Given the string after "--- " or "+++ ", guess the appropriate 507 * p_value for the given patch. 508 */ 509static intguess_p_value(const char*nameline) 510{ 511char*name, *cp; 512int val = -1; 513 514if(is_dev_null(nameline)) 515return-1; 516 name =find_name(nameline, NULL,0, TERM_SPACE | TERM_TAB); 517if(!name) 518return-1; 519 cp =strchr(name,'/'); 520if(!cp) 521 val =0; 522else if(prefix) { 523/* 524 * Does it begin with "a/$our-prefix" and such? Then this is 525 * very likely to apply to our directory. 526 */ 527if(!strncmp(name, prefix, prefix_length)) 528 val =count_slashes(prefix); 529else{ 530 cp++; 531if(!strncmp(cp, prefix, prefix_length)) 532 val =count_slashes(prefix) +1; 533} 534} 535free(name); 536return val; 537} 538 539/* 540 * Does the ---/+++ line has the POSIX timestamp after the last HT? 541 * GNU diff puts epoch there to signal a creation/deletion event. Is 542 * this such a timestamp? 543 */ 544static inthas_epoch_timestamp(const char*nameline) 545{ 546/* 547 * We are only interested in epoch timestamp; any non-zero 548 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 549 * For the same reason, the date must be either 1969-12-31 or 550 * 1970-01-01, and the seconds part must be "00". 551 */ 552const char stamp_regexp[] = 553"^(1969-12-31|1970-01-01)" 554" " 555"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 556" " 557"([-+][0-2][0-9][0-5][0-9])\n"; 558const char*timestamp = NULL, *cp; 559static regex_t *stamp; 560 regmatch_t m[10]; 561int zoneoffset; 562int hourminute; 563int status; 564 565for(cp = nameline; *cp !='\n'; cp++) { 566if(*cp =='\t') 567 timestamp = cp +1; 568} 569if(!timestamp) 570return0; 571if(!stamp) { 572 stamp =xmalloc(sizeof(*stamp)); 573if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 574warning("Cannot prepare timestamp regexp%s", 575 stamp_regexp); 576return0; 577} 578} 579 580 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 581if(status) { 582if(status != REG_NOMATCH) 583warning("regexec returned%dfor input:%s", 584 status, timestamp); 585return0; 586} 587 588 zoneoffset =strtol(timestamp + m[3].rm_so +1, NULL,10); 589 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 590if(timestamp[m[3].rm_so] =='-') 591 zoneoffset = -zoneoffset; 592 593/* 594 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 595 * (west of GMT) or 1970-01-01 (east of GMT) 596 */ 597if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 598(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 599return0; 600 601 hourminute = (strtol(timestamp +11, NULL,10) *60+ 602strtol(timestamp +14, NULL,10) - 603 zoneoffset); 604 605return((zoneoffset <0&& hourminute ==1440) || 606(0<= zoneoffset && !hourminute)); 607} 608 609/* 610 * Get the name etc info from the ---/+++ lines of a traditional patch header 611 * 612 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 613 * files, we can happily check the index for a match, but for creating a 614 * new file we should try to match whatever "patch" does. I have no idea. 615 */ 616static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 617{ 618char*name; 619 620 first +=4;/* skip "--- " */ 621 second +=4;/* skip "+++ " */ 622if(!p_value_known) { 623int p, q; 624 p =guess_p_value(first); 625 q =guess_p_value(second); 626if(p <0) p = q; 627if(0<= p && p == q) { 628 p_value = p; 629 p_value_known =1; 630} 631} 632if(is_dev_null(first)) { 633 patch->is_new =1; 634 patch->is_delete =0; 635 name =find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB); 636 patch->new_name = name; 637}else if(is_dev_null(second)) { 638 patch->is_new =0; 639 patch->is_delete =1; 640 name =find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB); 641 patch->old_name = name; 642}else{ 643 name =find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB); 644 name =find_name(second, name, p_value, TERM_SPACE | TERM_TAB); 645if(has_epoch_timestamp(first)) { 646 patch->is_new =1; 647 patch->is_delete =0; 648 patch->new_name = name; 649}else if(has_epoch_timestamp(second)) { 650 patch->is_new =0; 651 patch->is_delete =1; 652 patch->old_name = name; 653}else{ 654 patch->old_name = patch->new_name = name; 655} 656} 657if(!name) 658die("unable to find filename in patch at line%d", linenr); 659} 660 661static intgitdiff_hdrend(const char*line,struct patch *patch) 662{ 663return-1; 664} 665 666/* 667 * We're anal about diff header consistency, to make 668 * sure that we don't end up having strange ambiguous 669 * patches floating around. 670 * 671 * As a result, gitdiff_{old|new}name() will check 672 * their names against any previous information, just 673 * to make sure.. 674 */ 675static char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,const char*oldnew) 676{ 677if(!orig_name && !isnull) 678returnfind_name(line, NULL, p_value, TERM_TAB); 679 680if(orig_name) { 681int len; 682const char*name; 683char*another; 684 name = orig_name; 685 len =strlen(name); 686if(isnull) 687die("git apply: bad git-diff - expected /dev/null, got%son line%d", name, linenr); 688 another =find_name(line, NULL, p_value, TERM_TAB); 689if(!another ||memcmp(another, name, len)) 690die("git apply: bad git-diff - inconsistent%sfilename on line%d", oldnew, linenr); 691free(another); 692return orig_name; 693} 694else{ 695/* expect "/dev/null" */ 696if(memcmp("/dev/null", line,9) || line[9] !='\n') 697die("git apply: bad git-diff - expected /dev/null on line%d", linenr); 698return NULL; 699} 700} 701 702static intgitdiff_oldname(const char*line,struct patch *patch) 703{ 704 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name,"old"); 705return0; 706} 707 708static intgitdiff_newname(const char*line,struct patch *patch) 709{ 710 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name,"new"); 711return0; 712} 713 714static intgitdiff_oldmode(const char*line,struct patch *patch) 715{ 716 patch->old_mode =strtoul(line, NULL,8); 717return0; 718} 719 720static intgitdiff_newmode(const char*line,struct patch *patch) 721{ 722 patch->new_mode =strtoul(line, NULL,8); 723return0; 724} 725 726static intgitdiff_delete(const char*line,struct patch *patch) 727{ 728 patch->is_delete =1; 729 patch->old_name = patch->def_name; 730returngitdiff_oldmode(line, patch); 731} 732 733static intgitdiff_newfile(const char*line,struct patch *patch) 734{ 735 patch->is_new =1; 736 patch->new_name = patch->def_name; 737returngitdiff_newmode(line, patch); 738} 739 740static intgitdiff_copysrc(const char*line,struct patch *patch) 741{ 742 patch->is_copy =1; 743 patch->old_name =find_name(line, NULL,0,0); 744return0; 745} 746 747static intgitdiff_copydst(const char*line,struct patch *patch) 748{ 749 patch->is_copy =1; 750 patch->new_name =find_name(line, NULL,0,0); 751return0; 752} 753 754static intgitdiff_renamesrc(const char*line,struct patch *patch) 755{ 756 patch->is_rename =1; 757 patch->old_name =find_name(line, NULL,0,0); 758return0; 759} 760 761static intgitdiff_renamedst(const char*line,struct patch *patch) 762{ 763 patch->is_rename =1; 764 patch->new_name =find_name(line, NULL,0,0); 765return0; 766} 767 768static intgitdiff_similarity(const char*line,struct patch *patch) 769{ 770if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 771 patch->score =0; 772return0; 773} 774 775static intgitdiff_dissimilarity(const char*line,struct patch *patch) 776{ 777if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 778 patch->score =0; 779return0; 780} 781 782static intgitdiff_index(const char*line,struct patch *patch) 783{ 784/* 785 * index line is N hexadecimal, "..", N hexadecimal, 786 * and optional space with octal mode. 787 */ 788const char*ptr, *eol; 789int len; 790 791 ptr =strchr(line,'.'); 792if(!ptr || ptr[1] !='.'||40< ptr - line) 793return0; 794 len = ptr - line; 795memcpy(patch->old_sha1_prefix, line, len); 796 patch->old_sha1_prefix[len] =0; 797 798 line = ptr +2; 799 ptr =strchr(line,' '); 800 eol =strchr(line,'\n'); 801 802if(!ptr || eol < ptr) 803 ptr = eol; 804 len = ptr - line; 805 806if(40< len) 807return0; 808memcpy(patch->new_sha1_prefix, line, len); 809 patch->new_sha1_prefix[len] =0; 810if(*ptr ==' ') 811 patch->old_mode =strtoul(ptr+1, NULL,8); 812return0; 813} 814 815/* 816 * This is normal for a diff that doesn't change anything: we'll fall through 817 * into the next diff. Tell the parser to break out. 818 */ 819static intgitdiff_unrecognized(const char*line,struct patch *patch) 820{ 821return-1; 822} 823 824static const char*stop_at_slash(const char*line,int llen) 825{ 826int nslash = p_value; 827int i; 828 829for(i =0; i < llen; i++) { 830int ch = line[i]; 831if(ch =='/'&& --nslash <=0) 832return&line[i]; 833} 834return NULL; 835} 836 837/* 838 * This is to extract the same name that appears on "diff --git" 839 * line. We do not find and return anything if it is a rename 840 * patch, and it is OK because we will find the name elsewhere. 841 * We need to reliably find name only when it is mode-change only, 842 * creation or deletion of an empty file. In any of these cases, 843 * both sides are the same name under a/ and b/ respectively. 844 */ 845static char*git_header_name(char*line,int llen) 846{ 847const char*name; 848const char*second = NULL; 849size_t len; 850 851 line +=strlen("diff --git "); 852 llen -=strlen("diff --git "); 853 854if(*line =='"') { 855const char*cp; 856struct strbuf first = STRBUF_INIT; 857struct strbuf sp = STRBUF_INIT; 858 859if(unquote_c_style(&first, line, &second)) 860goto free_and_fail1; 861 862/* advance to the first slash */ 863 cp =stop_at_slash(first.buf, first.len); 864/* we do not accept absolute paths */ 865if(!cp || cp == first.buf) 866goto free_and_fail1; 867strbuf_remove(&first,0, cp +1- first.buf); 868 869/* 870 * second points at one past closing dq of name. 871 * find the second name. 872 */ 873while((second < line + llen) &&isspace(*second)) 874 second++; 875 876if(line + llen <= second) 877goto free_and_fail1; 878if(*second =='"') { 879if(unquote_c_style(&sp, second, NULL)) 880goto free_and_fail1; 881 cp =stop_at_slash(sp.buf, sp.len); 882if(!cp || cp == sp.buf) 883goto free_and_fail1; 884/* They must match, otherwise ignore */ 885if(strcmp(cp +1, first.buf)) 886goto free_and_fail1; 887strbuf_release(&sp); 888returnstrbuf_detach(&first, NULL); 889} 890 891/* unquoted second */ 892 cp =stop_at_slash(second, line + llen - second); 893if(!cp || cp == second) 894goto free_and_fail1; 895 cp++; 896if(line + llen - cp != first.len +1|| 897memcmp(first.buf, cp, first.len)) 898goto free_and_fail1; 899returnstrbuf_detach(&first, NULL); 900 901 free_and_fail1: 902strbuf_release(&first); 903strbuf_release(&sp); 904return NULL; 905} 906 907/* unquoted first name */ 908 name =stop_at_slash(line, llen); 909if(!name || name == line) 910return NULL; 911 name++; 912 913/* 914 * since the first name is unquoted, a dq if exists must be 915 * the beginning of the second name. 916 */ 917for(second = name; second < line + llen; second++) { 918if(*second =='"') { 919struct strbuf sp = STRBUF_INIT; 920const char*np; 921 922if(unquote_c_style(&sp, second, NULL)) 923goto free_and_fail2; 924 925 np =stop_at_slash(sp.buf, sp.len); 926if(!np || np == sp.buf) 927goto free_and_fail2; 928 np++; 929 930 len = sp.buf + sp.len - np; 931if(len < second - name && 932!strncmp(np, name, len) && 933isspace(name[len])) { 934/* Good */ 935strbuf_remove(&sp,0, np - sp.buf); 936returnstrbuf_detach(&sp, NULL); 937} 938 939 free_and_fail2: 940strbuf_release(&sp); 941return NULL; 942} 943} 944 945/* 946 * Accept a name only if it shows up twice, exactly the same 947 * form. 948 */ 949for(len =0; ; len++) { 950switch(name[len]) { 951default: 952continue; 953case'\n': 954return NULL; 955case'\t':case' ': 956 second = name+len; 957for(;;) { 958char c = *second++; 959if(c =='\n') 960return NULL; 961if(c =='/') 962break; 963} 964if(second[len] =='\n'&& !memcmp(name, second, len)) { 965returnxmemdupz(name, len); 966} 967} 968} 969} 970 971/* Verify that we recognize the lines following a git header */ 972static intparse_git_header(char*line,int len,unsigned int size,struct patch *patch) 973{ 974unsigned long offset; 975 976/* A git diff has explicit new/delete information, so we don't guess */ 977 patch->is_new =0; 978 patch->is_delete =0; 979 980/* 981 * Some things may not have the old name in the 982 * rest of the headers anywhere (pure mode changes, 983 * or removing or adding empty files), so we get 984 * the default name from the header. 985 */ 986 patch->def_name =git_header_name(line, len); 987if(patch->def_name && root) { 988char*s =xmalloc(root_len +strlen(patch->def_name) +1); 989strcpy(s, root); 990strcpy(s + root_len, patch->def_name); 991free(patch->def_name); 992 patch->def_name = s; 993} 994 995 line += len; 996 size -= len; 997 linenr++; 998for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) { 999static const struct opentry {1000const char*str;1001int(*fn)(const char*,struct patch *);1002} optable[] = {1003{"@@ -", gitdiff_hdrend },1004{"--- ", gitdiff_oldname },1005{"+++ ", gitdiff_newname },1006{"old mode ", gitdiff_oldmode },1007{"new mode ", gitdiff_newmode },1008{"deleted file mode ", gitdiff_delete },1009{"new file mode ", gitdiff_newfile },1010{"copy from ", gitdiff_copysrc },1011{"copy to ", gitdiff_copydst },1012{"rename old ", gitdiff_renamesrc },1013{"rename new ", gitdiff_renamedst },1014{"rename from ", gitdiff_renamesrc },1015{"rename to ", gitdiff_renamedst },1016{"similarity index ", gitdiff_similarity },1017{"dissimilarity index ", gitdiff_dissimilarity },1018{"index ", gitdiff_index },1019{"", gitdiff_unrecognized },1020};1021int i;10221023 len =linelen(line, size);1024if(!len || line[len-1] !='\n')1025break;1026for(i =0; i <ARRAY_SIZE(optable); i++) {1027const struct opentry *p = optable + i;1028int oplen =strlen(p->str);1029if(len < oplen ||memcmp(p->str, line, oplen))1030continue;1031if(p->fn(line + oplen, patch) <0)1032return offset;1033break;1034}1035}10361037return offset;1038}10391040static intparse_num(const char*line,unsigned long*p)1041{1042char*ptr;10431044if(!isdigit(*line))1045return0;1046*p =strtoul(line, &ptr,10);1047return ptr - line;1048}10491050static intparse_range(const char*line,int len,int offset,const char*expect,1051unsigned long*p1,unsigned long*p2)1052{1053int digits, ex;10541055if(offset <0|| offset >= len)1056return-1;1057 line += offset;1058 len -= offset;10591060 digits =parse_num(line, p1);1061if(!digits)1062return-1;10631064 offset += digits;1065 line += digits;1066 len -= digits;10671068*p2 =1;1069if(*line ==',') {1070 digits =parse_num(line+1, p2);1071if(!digits)1072return-1;10731074 offset += digits+1;1075 line += digits+1;1076 len -= digits+1;1077}10781079 ex =strlen(expect);1080if(ex > len)1081return-1;1082if(memcmp(line, expect, ex))1083return-1;10841085return offset + ex;1086}10871088static voidrecount_diff(char*line,int size,struct fragment *fragment)1089{1090int oldlines =0, newlines =0, ret =0;10911092if(size <1) {1093warning("recount: ignore empty hunk");1094return;1095}10961097for(;;) {1098int len =linelen(line, size);1099 size -= len;1100 line += len;11011102if(size <1)1103break;11041105switch(*line) {1106case' ':case'\n':1107 newlines++;1108/* fall through */1109case'-':1110 oldlines++;1111continue;1112case'+':1113 newlines++;1114continue;1115case'\\':1116continue;1117case'@':1118 ret = size <3||prefixcmp(line,"@@ ");1119break;1120case'd':1121 ret = size <5||prefixcmp(line,"diff ");1122break;1123default:1124 ret = -1;1125break;1126}1127if(ret) {1128warning("recount: unexpected line: %.*s",1129(int)linelen(line, size), line);1130return;1131}1132break;1133}1134 fragment->oldlines = oldlines;1135 fragment->newlines = newlines;1136}11371138/*1139 * Parse a unified diff fragment header of the1140 * form "@@ -a,b +c,d @@"1141 */1142static intparse_fragment_header(char*line,int len,struct fragment *fragment)1143{1144int offset;11451146if(!len || line[len-1] !='\n')1147return-1;11481149/* Figure out the number of lines in a fragment */1150 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1151 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);11521153return offset;1154}11551156static intfind_header(char*line,unsigned long size,int*hdrsize,struct patch *patch)1157{1158unsigned long offset, len;11591160 patch->is_toplevel_relative =0;1161 patch->is_rename = patch->is_copy =0;1162 patch->is_new = patch->is_delete = -1;1163 patch->old_mode = patch->new_mode =0;1164 patch->old_name = patch->new_name = NULL;1165for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1166unsigned long nextlen;11671168 len =linelen(line, size);1169if(!len)1170break;11711172/* Testing this early allows us to take a few shortcuts.. */1173if(len <6)1174continue;11751176/*1177 * Make sure we don't find any unconnected patch fragments.1178 * That's a sign that we didn't find a header, and that a1179 * patch has become corrupted/broken up.1180 */1181if(!memcmp("@@ -", line,4)) {1182struct fragment dummy;1183if(parse_fragment_header(line, len, &dummy) <0)1184continue;1185die("patch fragment without header at line%d: %.*s",1186 linenr, (int)len-1, line);1187}11881189if(size < len +6)1190break;11911192/*1193 * Git patch? It might not have a real patch, just a rename1194 * or mode change, so we handle that specially1195 */1196if(!memcmp("diff --git ", line,11)) {1197int git_hdr_len =parse_git_header(line, len, size, patch);1198if(git_hdr_len <= len)1199continue;1200if(!patch->old_name && !patch->new_name) {1201if(!patch->def_name)1202die("git diff header lacks filename information (line%d)", linenr);1203 patch->old_name = patch->new_name = patch->def_name;1204}1205 patch->is_toplevel_relative =1;1206*hdrsize = git_hdr_len;1207return offset;1208}12091210/* --- followed by +++ ? */1211if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1212continue;12131214/*1215 * We only accept unified patches, so we want it to1216 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1217 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1218 */1219 nextlen =linelen(line + len, size - len);1220if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1221continue;12221223/* Ok, we'll consider it a patch */1224parse_traditional_patch(line, line+len, patch);1225*hdrsize = len + nextlen;1226 linenr +=2;1227return offset;1228}1229return-1;1230}12311232static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1233{1234char*err;12351236if(!result)1237return;12381239 whitespace_error++;1240if(squelch_whitespace_errors &&1241 squelch_whitespace_errors < whitespace_error)1242return;12431244 err =whitespace_error_string(result);1245fprintf(stderr,"%s:%d:%s.\n%.*s\n",1246 patch_input_file, linenr, err, len, line);1247free(err);1248}12491250static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1251{1252unsigned result =ws_check(line +1, len -1, ws_rule);12531254record_ws_error(result, line +1, len -2, linenr);1255}12561257/*1258 * Parse a unified diff. Note that this really needs to parse each1259 * fragment separately, since the only way to know the difference1260 * between a "---" that is part of a patch, and a "---" that starts1261 * the next patch is to look at the line counts..1262 */1263static intparse_fragment(char*line,unsigned long size,1264struct patch *patch,struct fragment *fragment)1265{1266int added, deleted;1267int len =linelen(line, size), offset;1268unsigned long oldlines, newlines;1269unsigned long leading, trailing;12701271 offset =parse_fragment_header(line, len, fragment);1272if(offset <0)1273return-1;1274if(offset >0&& patch->recount)1275recount_diff(line + offset, size - offset, fragment);1276 oldlines = fragment->oldlines;1277 newlines = fragment->newlines;1278 leading =0;1279 trailing =0;12801281/* Parse the thing.. */1282 line += len;1283 size -= len;1284 linenr++;1285 added = deleted =0;1286for(offset = len;12870< size;1288 offset += len, size -= len, line += len, linenr++) {1289if(!oldlines && !newlines)1290break;1291 len =linelen(line, size);1292if(!len || line[len-1] !='\n')1293return-1;1294switch(*line) {1295default:1296return-1;1297case'\n':/* newer GNU diff, an empty context line */1298case' ':1299 oldlines--;1300 newlines--;1301if(!deleted && !added)1302 leading++;1303 trailing++;1304break;1305case'-':1306if(apply_in_reverse &&1307 ws_error_action != nowarn_ws_error)1308check_whitespace(line, len, patch->ws_rule);1309 deleted++;1310 oldlines--;1311 trailing =0;1312break;1313case'+':1314if(!apply_in_reverse &&1315 ws_error_action != nowarn_ws_error)1316check_whitespace(line, len, patch->ws_rule);1317 added++;1318 newlines--;1319 trailing =0;1320break;13211322/*1323 * We allow "\ No newline at end of file". Depending1324 * on locale settings when the patch was produced we1325 * don't know what this line looks like. The only1326 * thing we do know is that it begins with "\ ".1327 * Checking for 12 is just for sanity check -- any1328 * l10n of "\ No newline..." is at least that long.1329 */1330case'\\':1331if(len <12||memcmp(line,"\\",2))1332return-1;1333break;1334}1335}1336if(oldlines || newlines)1337return-1;1338 fragment->leading = leading;1339 fragment->trailing = trailing;13401341/*1342 * If a fragment ends with an incomplete line, we failed to include1343 * it in the above loop because we hit oldlines == newlines == 01344 * before seeing it.1345 */1346if(12< size && !memcmp(line,"\\",2))1347 offset +=linelen(line, size);13481349 patch->lines_added += added;1350 patch->lines_deleted += deleted;13511352if(0< patch->is_new && oldlines)1353returnerror("new file depends on old contents");1354if(0< patch->is_delete && newlines)1355returnerror("deleted file still has contents");1356return offset;1357}13581359static intparse_single_patch(char*line,unsigned long size,struct patch *patch)1360{1361unsigned long offset =0;1362unsigned long oldlines =0, newlines =0, context =0;1363struct fragment **fragp = &patch->fragments;13641365while(size >4&& !memcmp(line,"@@ -",4)) {1366struct fragment *fragment;1367int len;13681369 fragment =xcalloc(1,sizeof(*fragment));1370 fragment->linenr = linenr;1371 len =parse_fragment(line, size, patch, fragment);1372if(len <=0)1373die("corrupt patch at line%d", linenr);1374 fragment->patch = line;1375 fragment->size = len;1376 oldlines += fragment->oldlines;1377 newlines += fragment->newlines;1378 context += fragment->leading + fragment->trailing;13791380*fragp = fragment;1381 fragp = &fragment->next;13821383 offset += len;1384 line += len;1385 size -= len;1386}13871388/*1389 * If something was removed (i.e. we have old-lines) it cannot1390 * be creation, and if something was added it cannot be1391 * deletion. However, the reverse is not true; --unified=01392 * patches that only add are not necessarily creation even1393 * though they do not have any old lines, and ones that only1394 * delete are not necessarily deletion.1395 *1396 * Unfortunately, a real creation/deletion patch do _not_ have1397 * any context line by definition, so we cannot safely tell it1398 * apart with --unified=0 insanity. At least if the patch has1399 * more than one hunk it is not creation or deletion.1400 */1401if(patch->is_new <0&&1402(oldlines || (patch->fragments && patch->fragments->next)))1403 patch->is_new =0;1404if(patch->is_delete <0&&1405(newlines || (patch->fragments && patch->fragments->next)))1406 patch->is_delete =0;14071408if(0< patch->is_new && oldlines)1409die("new file%sdepends on old contents", patch->new_name);1410if(0< patch->is_delete && newlines)1411die("deleted file%sstill has contents", patch->old_name);1412if(!patch->is_delete && !newlines && context)1413fprintf(stderr,"** warning: file%sbecomes empty but "1414"is not deleted\n", patch->new_name);14151416return offset;1417}14181419staticinlineintmetadata_changes(struct patch *patch)1420{1421return patch->is_rename >0||1422 patch->is_copy >0||1423 patch->is_new >0||1424 patch->is_delete ||1425(patch->old_mode && patch->new_mode &&1426 patch->old_mode != patch->new_mode);1427}14281429static char*inflate_it(const void*data,unsigned long size,1430unsigned long inflated_size)1431{1432 z_stream stream;1433void*out;1434int st;14351436memset(&stream,0,sizeof(stream));14371438 stream.next_in = (unsigned char*)data;1439 stream.avail_in = size;1440 stream.next_out = out =xmalloc(inflated_size);1441 stream.avail_out = inflated_size;1442git_inflate_init(&stream);1443 st =git_inflate(&stream, Z_FINISH);1444git_inflate_end(&stream);1445if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1446free(out);1447return NULL;1448}1449return out;1450}14511452static struct fragment *parse_binary_hunk(char**buf_p,1453unsigned long*sz_p,1454int*status_p,1455int*used_p)1456{1457/*1458 * Expect a line that begins with binary patch method ("literal"1459 * or "delta"), followed by the length of data before deflating.1460 * a sequence of 'length-byte' followed by base-85 encoded data1461 * should follow, terminated by a newline.1462 *1463 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1464 * and we would limit the patch line to 66 characters,1465 * so one line can fit up to 13 groups that would decode1466 * to 52 bytes max. The length byte 'A'-'Z' corresponds1467 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1468 */1469int llen, used;1470unsigned long size = *sz_p;1471char*buffer = *buf_p;1472int patch_method;1473unsigned long origlen;1474char*data = NULL;1475int hunk_size =0;1476struct fragment *frag;14771478 llen =linelen(buffer, size);1479 used = llen;14801481*status_p =0;14821483if(!prefixcmp(buffer,"delta ")) {1484 patch_method = BINARY_DELTA_DEFLATED;1485 origlen =strtoul(buffer +6, NULL,10);1486}1487else if(!prefixcmp(buffer,"literal ")) {1488 patch_method = BINARY_LITERAL_DEFLATED;1489 origlen =strtoul(buffer +8, NULL,10);1490}1491else1492return NULL;14931494 linenr++;1495 buffer += llen;1496while(1) {1497int byte_length, max_byte_length, newsize;1498 llen =linelen(buffer, size);1499 used += llen;1500 linenr++;1501if(llen ==1) {1502/* consume the blank line */1503 buffer++;1504 size--;1505break;1506}1507/*1508 * Minimum line is "A00000\n" which is 7-byte long,1509 * and the line length must be multiple of 5 plus 2.1510 */1511if((llen <7) || (llen-2) %5)1512goto corrupt;1513 max_byte_length = (llen -2) /5*4;1514 byte_length = *buffer;1515if('A'<= byte_length && byte_length <='Z')1516 byte_length = byte_length -'A'+1;1517else if('a'<= byte_length && byte_length <='z')1518 byte_length = byte_length -'a'+27;1519else1520goto corrupt;1521/* if the input length was not multiple of 4, we would1522 * have filler at the end but the filler should never1523 * exceed 3 bytes1524 */1525if(max_byte_length < byte_length ||1526 byte_length <= max_byte_length -4)1527goto corrupt;1528 newsize = hunk_size + byte_length;1529 data =xrealloc(data, newsize);1530if(decode_85(data + hunk_size, buffer +1, byte_length))1531goto corrupt;1532 hunk_size = newsize;1533 buffer += llen;1534 size -= llen;1535}15361537 frag =xcalloc(1,sizeof(*frag));1538 frag->patch =inflate_it(data, hunk_size, origlen);1539if(!frag->patch)1540goto corrupt;1541free(data);1542 frag->size = origlen;1543*buf_p = buffer;1544*sz_p = size;1545*used_p = used;1546 frag->binary_patch_method = patch_method;1547return frag;15481549 corrupt:1550free(data);1551*status_p = -1;1552error("corrupt binary patch at line%d: %.*s",1553 linenr-1, llen-1, buffer);1554return NULL;1555}15561557static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1558{1559/*1560 * We have read "GIT binary patch\n"; what follows is a line1561 * that says the patch method (currently, either "literal" or1562 * "delta") and the length of data before deflating; a1563 * sequence of 'length-byte' followed by base-85 encoded data1564 * follows.1565 *1566 * When a binary patch is reversible, there is another binary1567 * hunk in the same format, starting with patch method (either1568 * "literal" or "delta") with the length of data, and a sequence1569 * of length-byte + base-85 encoded data, terminated with another1570 * empty line. This data, when applied to the postimage, produces1571 * the preimage.1572 */1573struct fragment *forward;1574struct fragment *reverse;1575int status;1576int used, used_1;15771578 forward =parse_binary_hunk(&buffer, &size, &status, &used);1579if(!forward && !status)1580/* there has to be one hunk (forward hunk) */1581returnerror("unrecognized binary patch at line%d", linenr-1);1582if(status)1583/* otherwise we already gave an error message */1584return status;15851586 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1587if(reverse)1588 used += used_1;1589else if(status) {1590/*1591 * Not having reverse hunk is not an error, but having1592 * a corrupt reverse hunk is.1593 */1594free((void*) forward->patch);1595free(forward);1596return status;1597}1598 forward->next = reverse;1599 patch->fragments = forward;1600 patch->is_binary =1;1601return used;1602}16031604static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1605{1606int hdrsize, patchsize;1607int offset =find_header(buffer, size, &hdrsize, patch);16081609if(offset <0)1610return offset;16111612 patch->ws_rule =whitespace_rule(patch->new_name1613? patch->new_name1614: patch->old_name);16151616 patchsize =parse_single_patch(buffer + offset + hdrsize,1617 size - offset - hdrsize, patch);16181619if(!patchsize) {1620static const char*binhdr[] = {1621"Binary files ",1622"Files ",1623 NULL,1624};1625static const char git_binary[] ="GIT binary patch\n";1626int i;1627int hd = hdrsize + offset;1628unsigned long llen =linelen(buffer + hd, size - hd);16291630if(llen ==sizeof(git_binary) -1&&1631!memcmp(git_binary, buffer + hd, llen)) {1632int used;1633 linenr++;1634 used =parse_binary(buffer + hd + llen,1635 size - hd - llen, patch);1636if(used)1637 patchsize = used + llen;1638else1639 patchsize =0;1640}1641else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1642for(i =0; binhdr[i]; i++) {1643int len =strlen(binhdr[i]);1644if(len < size - hd &&1645!memcmp(binhdr[i], buffer + hd, len)) {1646 linenr++;1647 patch->is_binary =1;1648 patchsize = llen;1649break;1650}1651}1652}16531654/* Empty patch cannot be applied if it is a text patch1655 * without metadata change. A binary patch appears1656 * empty to us here.1657 */1658if((apply || check) &&1659(!patch->is_binary && !metadata_changes(patch)))1660die("patch with only garbage at line%d", linenr);1661}16621663return offset + hdrsize + patchsize;1664}16651666#define swap(a,b) myswap((a),(b),sizeof(a))16671668#define myswap(a, b, size) do { \1669 unsigned char mytmp[size]; \1670 memcpy(mytmp, &a, size); \1671 memcpy(&a, &b, size); \1672 memcpy(&b, mytmp, size); \1673} while (0)16741675static voidreverse_patches(struct patch *p)1676{1677for(; p; p = p->next) {1678struct fragment *frag = p->fragments;16791680swap(p->new_name, p->old_name);1681swap(p->new_mode, p->old_mode);1682swap(p->is_new, p->is_delete);1683swap(p->lines_added, p->lines_deleted);1684swap(p->old_sha1_prefix, p->new_sha1_prefix);16851686for(; frag; frag = frag->next) {1687swap(frag->newpos, frag->oldpos);1688swap(frag->newlines, frag->oldlines);1689}1690}1691}16921693static const char pluses[] =1694"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";1695static const char minuses[]=1696"----------------------------------------------------------------------";16971698static voidshow_stats(struct patch *patch)1699{1700struct strbuf qname = STRBUF_INIT;1701char*cp = patch->new_name ? patch->new_name : patch->old_name;1702int max, add, del;17031704quote_c_style(cp, &qname, NULL,0);17051706/*1707 * "scale" the filename1708 */1709 max = max_len;1710if(max >50)1711 max =50;17121713if(qname.len > max) {1714 cp =strchr(qname.buf + qname.len +3- max,'/');1715if(!cp)1716 cp = qname.buf + qname.len +3- max;1717strbuf_splice(&qname,0, cp - qname.buf,"...",3);1718}17191720if(patch->is_binary) {1721printf(" %-*s | Bin\n", max, qname.buf);1722strbuf_release(&qname);1723return;1724}17251726printf(" %-*s |", max, qname.buf);1727strbuf_release(&qname);17281729/*1730 * scale the add/delete1731 */1732 max = max + max_change >70?70- max : max_change;1733 add = patch->lines_added;1734 del = patch->lines_deleted;17351736if(max_change >0) {1737int total = ((add + del) * max + max_change /2) / max_change;1738 add = (add * max + max_change /2) / max_change;1739 del = total - add;1740}1741printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,1742 add, pluses, del, minuses);1743}17441745static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)1746{1747switch(st->st_mode & S_IFMT) {1748case S_IFLNK:1749if(strbuf_readlink(buf, path, st->st_size) <0)1750returnerror("unable to read symlink%s", path);1751return0;1752case S_IFREG:1753if(strbuf_read_file(buf, path, st->st_size) != st->st_size)1754returnerror("unable to open or read%s", path);1755convert_to_git(path, buf->buf, buf->len, buf,0);1756return0;1757default:1758return-1;1759}1760}17611762/*1763 * Update the preimage, and the common lines in postimage,1764 * from buffer buf of length len. If postlen is 0 the postimage1765 * is updated in place, otherwise it's updated on a new buffer1766 * of length postlen1767 */17681769static voidupdate_pre_post_images(struct image *preimage,1770struct image *postimage,1771char*buf,1772size_t len,size_t postlen)1773{1774int i, ctx;1775char*new, *old, *fixed;1776struct image fixed_preimage;17771778/*1779 * Update the preimage with whitespace fixes. Note that we1780 * are not losing preimage->buf -- apply_one_fragment() will1781 * free "oldlines".1782 */1783prepare_image(&fixed_preimage, buf, len,1);1784assert(fixed_preimage.nr == preimage->nr);1785for(i =0; i < preimage->nr; i++)1786 fixed_preimage.line[i].flag = preimage->line[i].flag;1787free(preimage->line_allocated);1788*preimage = fixed_preimage;17891790/*1791 * Adjust the common context lines in postimage. This can be1792 * done in-place when we are just doing whitespace fixing,1793 * which does not make the string grow, but needs a new buffer1794 * when ignoring whitespace causes the update, since in this case1795 * we could have e.g. tabs converted to multiple spaces.1796 * We trust the caller to tell us if the update can be done1797 * in place (postlen==0) or not.1798 */1799 old = postimage->buf;1800if(postlen)1801new= postimage->buf =xmalloc(postlen);1802else1803new= old;1804 fixed = preimage->buf;1805for(i = ctx =0; i < postimage->nr; i++) {1806size_t len = postimage->line[i].len;1807if(!(postimage->line[i].flag & LINE_COMMON)) {1808/* an added line -- no counterparts in preimage */1809memmove(new, old, len);1810 old += len;1811new+= len;1812continue;1813}18141815/* a common context -- skip it in the original postimage */1816 old += len;18171818/* and find the corresponding one in the fixed preimage */1819while(ctx < preimage->nr &&1820!(preimage->line[ctx].flag & LINE_COMMON)) {1821 fixed += preimage->line[ctx].len;1822 ctx++;1823}1824if(preimage->nr <= ctx)1825die("oops");18261827/* and copy it in, while fixing the line length */1828 len = preimage->line[ctx].len;1829memcpy(new, fixed, len);1830new+= len;1831 fixed += len;1832 postimage->line[i].len = len;1833 ctx++;1834}18351836/* Fix the length of the whole thing */1837 postimage->len =new- postimage->buf;1838}18391840static intmatch_fragment(struct image *img,1841struct image *preimage,1842struct image *postimage,1843unsigned longtry,1844int try_lno,1845unsigned ws_rule,1846int match_beginning,int match_end)1847{1848int i;1849char*fixed_buf, *buf, *orig, *target;18501851if(preimage->nr + try_lno > img->nr)1852return0;18531854if(match_beginning && try_lno)1855return0;18561857if(match_end && preimage->nr + try_lno != img->nr)1858return0;18591860/* Quick hash check */1861for(i =0; i < preimage->nr; i++)1862if(preimage->line[i].hash != img->line[try_lno + i].hash)1863return0;18641865/*1866 * Do we have an exact match? If we were told to match1867 * at the end, size must be exactly at try+fragsize,1868 * otherwise try+fragsize must be still within the preimage,1869 * and either case, the old piece should match the preimage1870 * exactly.1871 */1872if((match_end1873? (try+ preimage->len == img->len)1874: (try+ preimage->len <= img->len)) &&1875!memcmp(img->buf +try, preimage->buf, preimage->len))1876return1;18771878/*1879 * No exact match. If we are ignoring whitespace, run a line-by-line1880 * fuzzy matching. We collect all the line length information because1881 * we need it to adjust whitespace if we match.1882 */1883if(ws_ignore_action == ignore_ws_change) {1884size_t imgoff =0;1885size_t preoff =0;1886size_t postlen = postimage->len;1887for(i =0; i < preimage->nr; i++) {1888size_t prelen = preimage->line[i].len;1889size_t imglen = img->line[try_lno+i].len;18901891if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,1892 preimage->buf + preoff, prelen))1893return0;1894if(preimage->line[i].flag & LINE_COMMON)1895 postlen += imglen - prelen;1896 imgoff += imglen;1897 preoff += prelen;1898}18991900/*1901 * Ok, the preimage matches with whitespace fuzz. Update it and1902 * the common postimage lines to use the same whitespace as the1903 * target. imgoff now holds the true length of the target that1904 * matches the preimage, and we need to update the line lengths1905 * of the preimage to match the target ones.1906 */1907 fixed_buf =xmalloc(imgoff);1908memcpy(fixed_buf, img->buf +try, imgoff);1909for(i =0; i < preimage->nr; i++)1910 preimage->line[i].len = img->line[try_lno+i].len;19111912/*1913 * Update the preimage buffer and the postimage context lines.1914 */1915update_pre_post_images(preimage, postimage,1916 fixed_buf, imgoff, postlen);1917return1;1918}19191920if(ws_error_action != correct_ws_error)1921return0;19221923/*1924 * The hunk does not apply byte-by-byte, but the hash says1925 * it might with whitespace fuzz. We haven't been asked to1926 * ignore whitespace, we were asked to correct whitespace1927 * errors, so let's try matching after whitespace correction.1928 */1929 fixed_buf =xmalloc(preimage->len +1);1930 buf = fixed_buf;1931 orig = preimage->buf;1932 target = img->buf +try;1933for(i =0; i < preimage->nr; i++) {1934size_t fixlen;/* length after fixing the preimage */1935size_t oldlen = preimage->line[i].len;1936size_t tgtlen = img->line[try_lno + i].len;1937size_t tgtfixlen;/* length after fixing the target line */1938char tgtfixbuf[1024], *tgtfix;1939int match;19401941/* Try fixing the line in the preimage */1942 fixlen =ws_fix_copy(buf, orig, oldlen, ws_rule, NULL);19431944/* Try fixing the line in the target */1945if(sizeof(tgtfixbuf) > tgtlen)1946 tgtfix = tgtfixbuf;1947else1948 tgtfix =xmalloc(tgtlen);1949 tgtfixlen =ws_fix_copy(tgtfix, target, tgtlen, ws_rule, NULL);19501951/*1952 * If they match, either the preimage was based on1953 * a version before our tree fixed whitespace breakage,1954 * or we are lacking a whitespace-fix patch the tree1955 * the preimage was based on already had (i.e. target1956 * has whitespace breakage, the preimage doesn't).1957 * In either case, we are fixing the whitespace breakages1958 * so we might as well take the fix together with their1959 * real change.1960 */1961 match = (tgtfixlen == fixlen && !memcmp(tgtfix, buf, fixlen));19621963if(tgtfix != tgtfixbuf)1964free(tgtfix);1965if(!match)1966goto unmatch_exit;19671968 orig += oldlen;1969 buf += fixlen;1970 target += tgtlen;1971}19721973/*1974 * Yes, the preimage is based on an older version that still1975 * has whitespace breakages unfixed, and fixing them makes the1976 * hunk match. Update the context lines in the postimage.1977 */1978update_pre_post_images(preimage, postimage,1979 fixed_buf, buf - fixed_buf,0);1980return1;19811982 unmatch_exit:1983free(fixed_buf);1984return0;1985}19861987static intfind_pos(struct image *img,1988struct image *preimage,1989struct image *postimage,1990int line,1991unsigned ws_rule,1992int match_beginning,int match_end)1993{1994int i;1995unsigned long backwards, forwards,try;1996int backwards_lno, forwards_lno, try_lno;19971998if(preimage->nr > img->nr)1999return-1;20002001/*2002 * If match_begining or match_end is specified, there is no2003 * point starting from a wrong line that will never match and2004 * wander around and wait for a match at the specified end.2005 */2006if(match_beginning)2007 line =0;2008else if(match_end)2009 line = img->nr - preimage->nr;20102011if(line > img->nr)2012 line = img->nr;20132014try=0;2015for(i =0; i < line; i++)2016try+= img->line[i].len;20172018/*2019 * There's probably some smart way to do this, but I'll leave2020 * that to the smart and beautiful people. I'm simple and stupid.2021 */2022 backwards =try;2023 backwards_lno = line;2024 forwards =try;2025 forwards_lno = line;2026 try_lno = line;20272028for(i =0; ; i++) {2029if(match_fragment(img, preimage, postimage,2030try, try_lno, ws_rule,2031 match_beginning, match_end))2032return try_lno;20332034 again:2035if(backwards_lno ==0&& forwards_lno == img->nr)2036break;20372038if(i &1) {2039if(backwards_lno ==0) {2040 i++;2041goto again;2042}2043 backwards_lno--;2044 backwards -= img->line[backwards_lno].len;2045try= backwards;2046 try_lno = backwards_lno;2047}else{2048if(forwards_lno == img->nr) {2049 i++;2050goto again;2051}2052 forwards += img->line[forwards_lno].len;2053 forwards_lno++;2054try= forwards;2055 try_lno = forwards_lno;2056}20572058}2059return-1;2060}20612062static voidremove_first_line(struct image *img)2063{2064 img->buf += img->line[0].len;2065 img->len -= img->line[0].len;2066 img->line++;2067 img->nr--;2068}20692070static voidremove_last_line(struct image *img)2071{2072 img->len -= img->line[--img->nr].len;2073}20742075static voidupdate_image(struct image *img,2076int applied_pos,2077struct image *preimage,2078struct image *postimage)2079{2080/*2081 * remove the copy of preimage at offset in img2082 * and replace it with postimage2083 */2084int i, nr;2085size_t remove_count, insert_count, applied_at =0;2086char*result;20872088for(i =0; i < applied_pos; i++)2089 applied_at += img->line[i].len;20902091 remove_count =0;2092for(i =0; i < preimage->nr; i++)2093 remove_count += img->line[applied_pos + i].len;2094 insert_count = postimage->len;20952096/* Adjust the contents */2097 result =xmalloc(img->len + insert_count - remove_count +1);2098memcpy(result, img->buf, applied_at);2099memcpy(result + applied_at, postimage->buf, postimage->len);2100memcpy(result + applied_at + postimage->len,2101 img->buf + (applied_at + remove_count),2102 img->len - (applied_at + remove_count));2103free(img->buf);2104 img->buf = result;2105 img->len += insert_count - remove_count;2106 result[img->len] ='\0';21072108/* Adjust the line table */2109 nr = img->nr + postimage->nr - preimage->nr;2110if(preimage->nr < postimage->nr) {2111/*2112 * NOTE: this knows that we never call remove_first_line()2113 * on anything other than pre/post image.2114 */2115 img->line =xrealloc(img->line, nr *sizeof(*img->line));2116 img->line_allocated = img->line;2117}2118if(preimage->nr != postimage->nr)2119memmove(img->line + applied_pos + postimage->nr,2120 img->line + applied_pos + preimage->nr,2121(img->nr - (applied_pos + preimage->nr)) *2122sizeof(*img->line));2123memcpy(img->line + applied_pos,2124 postimage->line,2125 postimage->nr *sizeof(*img->line));2126 img->nr = nr;2127}21282129static intapply_one_fragment(struct image *img,struct fragment *frag,2130int inaccurate_eof,unsigned ws_rule)2131{2132int match_beginning, match_end;2133const char*patch = frag->patch;2134int size = frag->size;2135char*old, *new, *oldlines, *newlines;2136int new_blank_lines_at_end =0;2137unsigned long leading, trailing;2138int pos, applied_pos;2139struct image preimage;2140struct image postimage;21412142memset(&preimage,0,sizeof(preimage));2143memset(&postimage,0,sizeof(postimage));2144 oldlines =xmalloc(size);2145 newlines =xmalloc(size);21462147 old = oldlines;2148new= newlines;2149while(size >0) {2150char first;2151int len =linelen(patch, size);2152int plen, added;2153int added_blank_line =0;2154int is_blank_context =0;21552156if(!len)2157break;21582159/*2160 * "plen" is how much of the line we should use for2161 * the actual patch data. Normally we just remove the2162 * first character on the line, but if the line is2163 * followed by "\ No newline", then we also remove the2164 * last one (which is the newline, of course).2165 */2166 plen = len -1;2167if(len < size && patch[len] =='\\')2168 plen--;2169 first = *patch;2170if(apply_in_reverse) {2171if(first =='-')2172 first ='+';2173else if(first =='+')2174 first ='-';2175}21762177switch(first) {2178case'\n':2179/* Newer GNU diff, empty context line */2180if(plen <0)2181/* ... followed by '\No newline'; nothing */2182break;2183*old++ ='\n';2184*new++ ='\n';2185add_line_info(&preimage,"\n",1, LINE_COMMON);2186add_line_info(&postimage,"\n",1, LINE_COMMON);2187 is_blank_context =1;2188break;2189case' ':2190if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2191ws_blank_line(patch +1, plen, ws_rule))2192 is_blank_context =1;2193case'-':2194memcpy(old, patch +1, plen);2195add_line_info(&preimage, old, plen,2196(first ==' '? LINE_COMMON :0));2197 old += plen;2198if(first =='-')2199break;2200/* Fall-through for ' ' */2201case'+':2202/* --no-add does not add new lines */2203if(first =='+'&& no_add)2204break;22052206if(first !='+'||2207!whitespace_error ||2208 ws_error_action != correct_ws_error) {2209memcpy(new, patch +1, plen);2210 added = plen;2211}2212else{2213 added =ws_fix_copy(new, patch +1, plen, ws_rule, &applied_after_fixing_ws);2214}2215add_line_info(&postimage,new, added,2216(first =='+'?0: LINE_COMMON));2217new+= added;2218if(first =='+'&&2219(ws_rule & WS_BLANK_AT_EOF) &&2220ws_blank_line(patch +1, plen, ws_rule))2221 added_blank_line =1;2222break;2223case'@':case'\\':2224/* Ignore it, we already handled it */2225break;2226default:2227if(apply_verbosely)2228error("invalid start of line: '%c'", first);2229return-1;2230}2231if(added_blank_line)2232 new_blank_lines_at_end++;2233else if(is_blank_context)2234;2235else2236 new_blank_lines_at_end =0;2237 patch += len;2238 size -= len;2239}2240if(inaccurate_eof &&2241 old > oldlines && old[-1] =='\n'&&2242new> newlines &&new[-1] =='\n') {2243 old--;2244new--;2245}22462247 leading = frag->leading;2248 trailing = frag->trailing;22492250/*2251 * A hunk to change lines at the beginning would begin with2252 * @@ -1,L +N,M @@2253 * but we need to be careful. -U0 that inserts before the second2254 * line also has this pattern.2255 *2256 * And a hunk to add to an empty file would begin with2257 * @@ -0,0 +N,M @@2258 *2259 * In other words, a hunk that is (frag->oldpos <= 1) with or2260 * without leading context must match at the beginning.2261 */2262 match_beginning = (!frag->oldpos ||2263(frag->oldpos ==1&& !unidiff_zero));22642265/*2266 * A hunk without trailing lines must match at the end.2267 * However, we simply cannot tell if a hunk must match end2268 * from the lack of trailing lines if the patch was generated2269 * with unidiff without any context.2270 */2271 match_end = !unidiff_zero && !trailing;22722273 pos = frag->newpos ? (frag->newpos -1) :0;2274 preimage.buf = oldlines;2275 preimage.len = old - oldlines;2276 postimage.buf = newlines;2277 postimage.len =new- newlines;2278 preimage.line = preimage.line_allocated;2279 postimage.line = postimage.line_allocated;22802281for(;;) {22822283 applied_pos =find_pos(img, &preimage, &postimage, pos,2284 ws_rule, match_beginning, match_end);22852286if(applied_pos >=0)2287break;22882289/* Am I at my context limits? */2290if((leading <= p_context) && (trailing <= p_context))2291break;2292if(match_beginning || match_end) {2293 match_beginning = match_end =0;2294continue;2295}22962297/*2298 * Reduce the number of context lines; reduce both2299 * leading and trailing if they are equal otherwise2300 * just reduce the larger context.2301 */2302if(leading >= trailing) {2303remove_first_line(&preimage);2304remove_first_line(&postimage);2305 pos--;2306 leading--;2307}2308if(trailing > leading) {2309remove_last_line(&preimage);2310remove_last_line(&postimage);2311 trailing--;2312}2313}23142315if(applied_pos >=0) {2316if(new_blank_lines_at_end &&2317 preimage.nr + applied_pos == img->nr &&2318(ws_rule & WS_BLANK_AT_EOF) &&2319 ws_error_action != nowarn_ws_error) {2320record_ws_error(WS_BLANK_AT_EOF,"+",1, frag->linenr);2321if(ws_error_action == correct_ws_error) {2322while(new_blank_lines_at_end--)2323remove_last_line(&postimage);2324}2325/*2326 * We would want to prevent write_out_results()2327 * from taking place in apply_patch() that follows2328 * the callchain led us here, which is:2329 * apply_patch->check_patch_list->check_patch->2330 * apply_data->apply_fragments->apply_one_fragment2331 */2332if(ws_error_action == die_on_ws_error)2333 apply =0;2334}23352336/*2337 * Warn if it was necessary to reduce the number2338 * of context lines.2339 */2340if((leading != frag->leading) ||2341(trailing != frag->trailing))2342fprintf(stderr,"Context reduced to (%ld/%ld)"2343" to apply fragment at%d\n",2344 leading, trailing, applied_pos+1);2345update_image(img, applied_pos, &preimage, &postimage);2346}else{2347if(apply_verbosely)2348error("while searching for:\n%.*s",2349(int)(old - oldlines), oldlines);2350}23512352free(oldlines);2353free(newlines);2354free(preimage.line_allocated);2355free(postimage.line_allocated);23562357return(applied_pos <0);2358}23592360static intapply_binary_fragment(struct image *img,struct patch *patch)2361{2362struct fragment *fragment = patch->fragments;2363unsigned long len;2364void*dst;23652366/* Binary patch is irreversible without the optional second hunk */2367if(apply_in_reverse) {2368if(!fragment->next)2369returnerror("cannot reverse-apply a binary patch "2370"without the reverse hunk to '%s'",2371 patch->new_name2372? patch->new_name : patch->old_name);2373 fragment = fragment->next;2374}2375switch(fragment->binary_patch_method) {2376case BINARY_DELTA_DEFLATED:2377 dst =patch_delta(img->buf, img->len, fragment->patch,2378 fragment->size, &len);2379if(!dst)2380return-1;2381clear_image(img);2382 img->buf = dst;2383 img->len = len;2384return0;2385case BINARY_LITERAL_DEFLATED:2386clear_image(img);2387 img->len = fragment->size;2388 img->buf =xmalloc(img->len+1);2389memcpy(img->buf, fragment->patch, img->len);2390 img->buf[img->len] ='\0';2391return0;2392}2393return-1;2394}23952396static intapply_binary(struct image *img,struct patch *patch)2397{2398const char*name = patch->old_name ? patch->old_name : patch->new_name;2399unsigned char sha1[20];24002401/*2402 * For safety, we require patch index line to contain2403 * full 40-byte textual SHA1 for old and new, at least for now.2404 */2405if(strlen(patch->old_sha1_prefix) !=40||2406strlen(patch->new_sha1_prefix) !=40||2407get_sha1_hex(patch->old_sha1_prefix, sha1) ||2408get_sha1_hex(patch->new_sha1_prefix, sha1))2409returnerror("cannot apply binary patch to '%s' "2410"without full index line", name);24112412if(patch->old_name) {2413/*2414 * See if the old one matches what the patch2415 * applies to.2416 */2417hash_sha1_file(img->buf, img->len, blob_type, sha1);2418if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2419returnerror("the patch applies to '%s' (%s), "2420"which does not match the "2421"current contents.",2422 name,sha1_to_hex(sha1));2423}2424else{2425/* Otherwise, the old one must be empty. */2426if(img->len)2427returnerror("the patch applies to an empty "2428"'%s' but it is not empty", name);2429}24302431get_sha1_hex(patch->new_sha1_prefix, sha1);2432if(is_null_sha1(sha1)) {2433clear_image(img);2434return0;/* deletion patch */2435}24362437if(has_sha1_file(sha1)) {2438/* We already have the postimage */2439enum object_type type;2440unsigned long size;2441char*result;24422443 result =read_sha1_file(sha1, &type, &size);2444if(!result)2445returnerror("the necessary postimage%sfor "2446"'%s' cannot be read",2447 patch->new_sha1_prefix, name);2448clear_image(img);2449 img->buf = result;2450 img->len = size;2451}else{2452/*2453 * We have verified buf matches the preimage;2454 * apply the patch data to it, which is stored2455 * in the patch->fragments->{patch,size}.2456 */2457if(apply_binary_fragment(img, patch))2458returnerror("binary patch does not apply to '%s'",2459 name);24602461/* verify that the result matches */2462hash_sha1_file(img->buf, img->len, blob_type, sha1);2463if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2464returnerror("binary patch to '%s' creates incorrect result (expecting%s, got%s)",2465 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2466}24672468return0;2469}24702471static intapply_fragments(struct image *img,struct patch *patch)2472{2473struct fragment *frag = patch->fragments;2474const char*name = patch->old_name ? patch->old_name : patch->new_name;2475unsigned ws_rule = patch->ws_rule;2476unsigned inaccurate_eof = patch->inaccurate_eof;24772478if(patch->is_binary)2479returnapply_binary(img, patch);24802481while(frag) {2482if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule)) {2483error("patch failed:%s:%ld", name, frag->oldpos);2484if(!apply_with_reject)2485return-1;2486 frag->rejected =1;2487}2488 frag = frag->next;2489}2490return0;2491}24922493static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2494{2495if(!ce)2496return0;24972498if(S_ISGITLINK(ce->ce_mode)) {2499strbuf_grow(buf,100);2500strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2501}else{2502enum object_type type;2503unsigned long sz;2504char*result;25052506 result =read_sha1_file(ce->sha1, &type, &sz);2507if(!result)2508return-1;2509/* XXX read_sha1_file NUL-terminates */2510strbuf_attach(buf, result, sz, sz +1);2511}2512return0;2513}25142515static struct patch *in_fn_table(const char*name)2516{2517struct string_list_item *item;25182519if(name == NULL)2520return NULL;25212522 item =string_list_lookup(name, &fn_table);2523if(item != NULL)2524return(struct patch *)item->util;25252526return NULL;2527}25282529/*2530 * item->util in the filename table records the status of the path.2531 * Usually it points at a patch (whose result records the contents2532 * of it after applying it), but it could be PATH_WAS_DELETED for a2533 * path that a previously applied patch has already removed.2534 */2535#define PATH_TO_BE_DELETED ((struct patch *) -2)2536#define PATH_WAS_DELETED ((struct patch *) -1)25372538static intto_be_deleted(struct patch *patch)2539{2540return patch == PATH_TO_BE_DELETED;2541}25422543static intwas_deleted(struct patch *patch)2544{2545return patch == PATH_WAS_DELETED;2546}25472548static voidadd_to_fn_table(struct patch *patch)2549{2550struct string_list_item *item;25512552/*2553 * Always add new_name unless patch is a deletion2554 * This should cover the cases for normal diffs,2555 * file creations and copies2556 */2557if(patch->new_name != NULL) {2558 item =string_list_insert(patch->new_name, &fn_table);2559 item->util = patch;2560}25612562/*2563 * store a failure on rename/deletion cases because2564 * later chunks shouldn't patch old names2565 */2566if((patch->new_name == NULL) || (patch->is_rename)) {2567 item =string_list_insert(patch->old_name, &fn_table);2568 item->util = PATH_WAS_DELETED;2569}2570}25712572static voidprepare_fn_table(struct patch *patch)2573{2574/*2575 * store information about incoming file deletion2576 */2577while(patch) {2578if((patch->new_name == NULL) || (patch->is_rename)) {2579struct string_list_item *item;2580 item =string_list_insert(patch->old_name, &fn_table);2581 item->util = PATH_TO_BE_DELETED;2582}2583 patch = patch->next;2584}2585}25862587static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)2588{2589struct strbuf buf = STRBUF_INIT;2590struct image image;2591size_t len;2592char*img;2593struct patch *tpatch;25942595if(!(patch->is_copy || patch->is_rename) &&2596(tpatch =in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {2597if(was_deleted(tpatch)) {2598returnerror("patch%shas been renamed/deleted",2599 patch->old_name);2600}2601/* We have a patched copy in memory use that */2602strbuf_add(&buf, tpatch->result, tpatch->resultsize);2603}else if(cached) {2604if(read_file_or_gitlink(ce, &buf))2605returnerror("read of%sfailed", patch->old_name);2606}else if(patch->old_name) {2607if(S_ISGITLINK(patch->old_mode)) {2608if(ce) {2609read_file_or_gitlink(ce, &buf);2610}else{2611/*2612 * There is no way to apply subproject2613 * patch without looking at the index.2614 */2615 patch->fragments = NULL;2616}2617}else{2618if(read_old_data(st, patch->old_name, &buf))2619returnerror("read of%sfailed", patch->old_name);2620}2621}26222623 img =strbuf_detach(&buf, &len);2624prepare_image(&image, img, len, !patch->is_binary);26252626if(apply_fragments(&image, patch) <0)2627return-1;/* note with --reject this succeeds. */2628 patch->result = image.buf;2629 patch->resultsize = image.len;2630add_to_fn_table(patch);2631free(image.line_allocated);26322633if(0< patch->is_delete && patch->resultsize)2634returnerror("removal patch leaves file contents");26352636return0;2637}26382639static intcheck_to_create_blob(const char*new_name,int ok_if_exists)2640{2641struct stat nst;2642if(!lstat(new_name, &nst)) {2643if(S_ISDIR(nst.st_mode) || ok_if_exists)2644return0;2645/*2646 * A leading component of new_name might be a symlink2647 * that is going to be removed with this patch, but2648 * still pointing at somewhere that has the path.2649 * In such a case, path "new_name" does not exist as2650 * far as git is concerned.2651 */2652if(has_symlink_leading_path(new_name,strlen(new_name)))2653return0;26542655returnerror("%s: already exists in working directory", new_name);2656}2657else if((errno != ENOENT) && (errno != ENOTDIR))2658returnerror("%s:%s", new_name,strerror(errno));2659return0;2660}26612662static intverify_index_match(struct cache_entry *ce,struct stat *st)2663{2664if(S_ISGITLINK(ce->ce_mode)) {2665if(!S_ISDIR(st->st_mode))2666return-1;2667return0;2668}2669returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID);2670}26712672static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)2673{2674const char*old_name = patch->old_name;2675struct patch *tpatch = NULL;2676int stat_ret =0;2677unsigned st_mode =0;26782679/*2680 * Make sure that we do not have local modifications from the2681 * index when we are looking at the index. Also make sure2682 * we have the preimage file to be patched in the work tree,2683 * unless --cached, which tells git to apply only in the index.2684 */2685if(!old_name)2686return0;26872688assert(patch->is_new <=0);26892690if(!(patch->is_copy || patch->is_rename) &&2691(tpatch =in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {2692if(was_deleted(tpatch))2693returnerror("%s: has been deleted/renamed", old_name);2694 st_mode = tpatch->new_mode;2695}else if(!cached) {2696 stat_ret =lstat(old_name, st);2697if(stat_ret && errno != ENOENT)2698returnerror("%s:%s", old_name,strerror(errno));2699}27002701if(to_be_deleted(tpatch))2702 tpatch = NULL;27032704if(check_index && !tpatch) {2705int pos =cache_name_pos(old_name,strlen(old_name));2706if(pos <0) {2707if(patch->is_new <0)2708goto is_new;2709returnerror("%s: does not exist in index", old_name);2710}2711*ce = active_cache[pos];2712if(stat_ret <0) {2713struct checkout costate;2714/* checkout */2715 costate.base_dir ="";2716 costate.base_dir_len =0;2717 costate.force =0;2718 costate.quiet =0;2719 costate.not_new =0;2720 costate.refresh_cache =1;2721if(checkout_entry(*ce, &costate, NULL) ||2722lstat(old_name, st))2723return-1;2724}2725if(!cached &&verify_index_match(*ce, st))2726returnerror("%s: does not match index", old_name);2727if(cached)2728 st_mode = (*ce)->ce_mode;2729}else if(stat_ret <0) {2730if(patch->is_new <0)2731goto is_new;2732returnerror("%s:%s", old_name,strerror(errno));2733}27342735if(!cached && !tpatch)2736 st_mode =ce_mode_from_stat(*ce, st->st_mode);27372738if(patch->is_new <0)2739 patch->is_new =0;2740if(!patch->old_mode)2741 patch->old_mode = st_mode;2742if((st_mode ^ patch->old_mode) & S_IFMT)2743returnerror("%s: wrong type", old_name);2744if(st_mode != patch->old_mode)2745warning("%shas type%o, expected%o",2746 old_name, st_mode, patch->old_mode);2747if(!patch->new_mode && !patch->is_delete)2748 patch->new_mode = st_mode;2749return0;27502751 is_new:2752 patch->is_new =1;2753 patch->is_delete =0;2754 patch->old_name = NULL;2755return0;2756}27572758static intcheck_patch(struct patch *patch)2759{2760struct stat st;2761const char*old_name = patch->old_name;2762const char*new_name = patch->new_name;2763const char*name = old_name ? old_name : new_name;2764struct cache_entry *ce = NULL;2765struct patch *tpatch;2766int ok_if_exists;2767int status;27682769 patch->rejected =1;/* we will drop this after we succeed */27702771 status =check_preimage(patch, &ce, &st);2772if(status)2773return status;2774 old_name = patch->old_name;27752776if((tpatch =in_fn_table(new_name)) &&2777(was_deleted(tpatch) ||to_be_deleted(tpatch)))2778/*2779 * A type-change diff is always split into a patch to2780 * delete old, immediately followed by a patch to2781 * create new (see diff.c::run_diff()); in such a case2782 * it is Ok that the entry to be deleted by the2783 * previous patch is still in the working tree and in2784 * the index.2785 */2786 ok_if_exists =1;2787else2788 ok_if_exists =0;27892790if(new_name &&2791((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {2792if(check_index &&2793cache_name_pos(new_name,strlen(new_name)) >=0&&2794!ok_if_exists)2795returnerror("%s: already exists in index", new_name);2796if(!cached) {2797int err =check_to_create_blob(new_name, ok_if_exists);2798if(err)2799return err;2800}2801if(!patch->new_mode) {2802if(0< patch->is_new)2803 patch->new_mode = S_IFREG |0644;2804else2805 patch->new_mode = patch->old_mode;2806}2807}28082809if(new_name && old_name) {2810int same = !strcmp(old_name, new_name);2811if(!patch->new_mode)2812 patch->new_mode = patch->old_mode;2813if((patch->old_mode ^ patch->new_mode) & S_IFMT)2814returnerror("new mode (%o) of%sdoes not match old mode (%o)%s%s",2815 patch->new_mode, new_name, patch->old_mode,2816 same ?"":" of ", same ?"": old_name);2817}28182819if(apply_data(patch, &st, ce) <0)2820returnerror("%s: patch does not apply", name);2821 patch->rejected =0;2822return0;2823}28242825static intcheck_patch_list(struct patch *patch)2826{2827int err =0;28282829prepare_fn_table(patch);2830while(patch) {2831if(apply_verbosely)2832say_patch_name(stderr,2833"Checking patch ", patch,"...\n");2834 err |=check_patch(patch);2835 patch = patch->next;2836}2837return err;2838}28392840/* This function tries to read the sha1 from the current index */2841static intget_current_sha1(const char*path,unsigned char*sha1)2842{2843int pos;28442845if(read_cache() <0)2846return-1;2847 pos =cache_name_pos(path,strlen(path));2848if(pos <0)2849return-1;2850hashcpy(sha1, active_cache[pos]->sha1);2851return0;2852}28532854/* Build an index that contains the just the files needed for a 3way merge */2855static voidbuild_fake_ancestor(struct patch *list,const char*filename)2856{2857struct patch *patch;2858struct index_state result = { NULL };2859int fd;28602861/* Once we start supporting the reverse patch, it may be2862 * worth showing the new sha1 prefix, but until then...2863 */2864for(patch = list; patch; patch = patch->next) {2865const unsigned char*sha1_ptr;2866unsigned char sha1[20];2867struct cache_entry *ce;2868const char*name;28692870 name = patch->old_name ? patch->old_name : patch->new_name;2871if(0< patch->is_new)2872continue;2873else if(get_sha1(patch->old_sha1_prefix, sha1))2874/* git diff has no index line for mode/type changes */2875if(!patch->lines_added && !patch->lines_deleted) {2876if(get_current_sha1(patch->new_name, sha1) ||2877get_current_sha1(patch->old_name, sha1))2878die("mode change for%s, which is not "2879"in current HEAD", name);2880 sha1_ptr = sha1;2881}else2882die("sha1 information is lacking or useless "2883"(%s).", name);2884else2885 sha1_ptr = sha1;28862887 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);2888if(!ce)2889die("make_cache_entry failed for path '%s'", name);2890if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))2891die("Could not add%sto temporary index", name);2892}28932894 fd =open(filename, O_WRONLY | O_CREAT,0666);2895if(fd <0||write_index(&result, fd) ||close(fd))2896die("Could not write temporary index to%s", filename);28972898discard_index(&result);2899}29002901static voidstat_patch_list(struct patch *patch)2902{2903int files, adds, dels;29042905for(files = adds = dels =0; patch ; patch = patch->next) {2906 files++;2907 adds += patch->lines_added;2908 dels += patch->lines_deleted;2909show_stats(patch);2910}29112912printf("%dfiles changed,%dinsertions(+),%ddeletions(-)\n", files, adds, dels);2913}29142915static voidnumstat_patch_list(struct patch *patch)2916{2917for( ; patch; patch = patch->next) {2918const char*name;2919 name = patch->new_name ? patch->new_name : patch->old_name;2920if(patch->is_binary)2921printf("-\t-\t");2922else2923printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);2924write_name_quoted(name, stdout, line_termination);2925}2926}29272928static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)2929{2930if(mode)2931printf("%smode%06o%s\n", newdelete, mode, name);2932else2933printf("%s %s\n", newdelete, name);2934}29352936static voidshow_mode_change(struct patch *p,int show_name)2937{2938if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {2939if(show_name)2940printf(" mode change%06o =>%06o%s\n",2941 p->old_mode, p->new_mode, p->new_name);2942else2943printf(" mode change%06o =>%06o\n",2944 p->old_mode, p->new_mode);2945}2946}29472948static voidshow_rename_copy(struct patch *p)2949{2950const char*renamecopy = p->is_rename ?"rename":"copy";2951const char*old, *new;29522953/* Find common prefix */2954 old = p->old_name;2955new= p->new_name;2956while(1) {2957const char*slash_old, *slash_new;2958 slash_old =strchr(old,'/');2959 slash_new =strchr(new,'/');2960if(!slash_old ||2961!slash_new ||2962 slash_old - old != slash_new -new||2963memcmp(old,new, slash_new -new))2964break;2965 old = slash_old +1;2966new= slash_new +1;2967}2968/* p->old_name thru old is the common prefix, and old and new2969 * through the end of names are renames2970 */2971if(old != p->old_name)2972printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,2973(int)(old - p->old_name), p->old_name,2974 old,new, p->score);2975else2976printf("%s %s=>%s(%d%%)\n", renamecopy,2977 p->old_name, p->new_name, p->score);2978show_mode_change(p,0);2979}29802981static voidsummary_patch_list(struct patch *patch)2982{2983struct patch *p;29842985for(p = patch; p; p = p->next) {2986if(p->is_new)2987show_file_mode_name("create", p->new_mode, p->new_name);2988else if(p->is_delete)2989show_file_mode_name("delete", p->old_mode, p->old_name);2990else{2991if(p->is_rename || p->is_copy)2992show_rename_copy(p);2993else{2994if(p->score) {2995printf(" rewrite%s(%d%%)\n",2996 p->new_name, p->score);2997show_mode_change(p,0);2998}2999else3000show_mode_change(p,1);3001}3002}3003}3004}30053006static voidpatch_stats(struct patch *patch)3007{3008int lines = patch->lines_added + patch->lines_deleted;30093010if(lines > max_change)3011 max_change = lines;3012if(patch->old_name) {3013int len =quote_c_style(patch->old_name, NULL, NULL,0);3014if(!len)3015 len =strlen(patch->old_name);3016if(len > max_len)3017 max_len = len;3018}3019if(patch->new_name) {3020int len =quote_c_style(patch->new_name, NULL, NULL,0);3021if(!len)3022 len =strlen(patch->new_name);3023if(len > max_len)3024 max_len = len;3025}3026}30273028static voidremove_file(struct patch *patch,int rmdir_empty)3029{3030if(update_index) {3031if(remove_file_from_cache(patch->old_name) <0)3032die("unable to remove%sfrom index", patch->old_name);3033}3034if(!cached) {3035if(S_ISGITLINK(patch->old_mode)) {3036if(rmdir(patch->old_name))3037warning("unable to remove submodule%s",3038 patch->old_name);3039}else if(!unlink_or_warn(patch->old_name) && rmdir_empty) {3040remove_path(patch->old_name);3041}3042}3043}30443045static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)3046{3047struct stat st;3048struct cache_entry *ce;3049int namelen =strlen(path);3050unsigned ce_size =cache_entry_size(namelen);30513052if(!update_index)3053return;30543055 ce =xcalloc(1, ce_size);3056memcpy(ce->name, path, namelen);3057 ce->ce_mode =create_ce_mode(mode);3058 ce->ce_flags = namelen;3059if(S_ISGITLINK(mode)) {3060const char*s = buf;30613062if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))3063die("corrupt patch for subproject%s", path);3064}else{3065if(!cached) {3066if(lstat(path, &st) <0)3067die_errno("unable to stat newly created file '%s'",3068 path);3069fill_stat_cache_info(ce, &st);3070}3071if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)3072die("unable to create backing store for newly created file%s", path);3073}3074if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3075die("unable to add cache entry for%s", path);3076}30773078static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)3079{3080int fd;3081struct strbuf nbuf = STRBUF_INIT;30823083if(S_ISGITLINK(mode)) {3084struct stat st;3085if(!lstat(path, &st) &&S_ISDIR(st.st_mode))3086return0;3087returnmkdir(path,0777);3088}30893090if(has_symlinks &&S_ISLNK(mode))3091/* Although buf:size is counted string, it also is NUL3092 * terminated.3093 */3094returnsymlink(buf, path);30953096 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);3097if(fd <0)3098return-1;30993100if(convert_to_working_tree(path, buf, size, &nbuf)) {3101 size = nbuf.len;3102 buf = nbuf.buf;3103}3104write_or_die(fd, buf, size);3105strbuf_release(&nbuf);31063107if(close(fd) <0)3108die_errno("closing file '%s'", path);3109return0;3110}31113112/*3113 * We optimistically assume that the directories exist,3114 * which is true 99% of the time anyway. If they don't,3115 * we create them and try again.3116 */3117static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)3118{3119if(cached)3120return;3121if(!try_create_file(path, mode, buf, size))3122return;31233124if(errno == ENOENT) {3125if(safe_create_leading_directories(path))3126return;3127if(!try_create_file(path, mode, buf, size))3128return;3129}31303131if(errno == EEXIST || errno == EACCES) {3132/* We may be trying to create a file where a directory3133 * used to be.3134 */3135struct stat st;3136if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))3137 errno = EEXIST;3138}31393140if(errno == EEXIST) {3141unsigned int nr =getpid();31423143for(;;) {3144char newpath[PATH_MAX];3145mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);3146if(!try_create_file(newpath, mode, buf, size)) {3147if(!rename(newpath, path))3148return;3149unlink_or_warn(newpath);3150break;3151}3152if(errno != EEXIST)3153break;3154++nr;3155}3156}3157die_errno("unable to write file '%s' mode%o", path, mode);3158}31593160static voidcreate_file(struct patch *patch)3161{3162char*path = patch->new_name;3163unsigned mode = patch->new_mode;3164unsigned long size = patch->resultsize;3165char*buf = patch->result;31663167if(!mode)3168 mode = S_IFREG |0644;3169create_one_file(path, mode, buf, size);3170add_index_file(path, mode, buf, size);3171}31723173/* phase zero is to remove, phase one is to create */3174static voidwrite_out_one_result(struct patch *patch,int phase)3175{3176if(patch->is_delete >0) {3177if(phase ==0)3178remove_file(patch,1);3179return;3180}3181if(patch->is_new >0|| patch->is_copy) {3182if(phase ==1)3183create_file(patch);3184return;3185}3186/*3187 * Rename or modification boils down to the same3188 * thing: remove the old, write the new3189 */3190if(phase ==0)3191remove_file(patch, patch->is_rename);3192if(phase ==1)3193create_file(patch);3194}31953196static intwrite_out_one_reject(struct patch *patch)3197{3198FILE*rej;3199char namebuf[PATH_MAX];3200struct fragment *frag;3201int cnt =0;32023203for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {3204if(!frag->rejected)3205continue;3206 cnt++;3207}32083209if(!cnt) {3210if(apply_verbosely)3211say_patch_name(stderr,3212"Applied patch ", patch," cleanly.\n");3213return0;3214}32153216/* This should not happen, because a removal patch that leaves3217 * contents are marked "rejected" at the patch level.3218 */3219if(!patch->new_name)3220die("internal error");32213222/* Say this even without --verbose */3223say_patch_name(stderr,"Applying patch ", patch," with");3224fprintf(stderr,"%drejects...\n", cnt);32253226 cnt =strlen(patch->new_name);3227if(ARRAY_SIZE(namebuf) <= cnt +5) {3228 cnt =ARRAY_SIZE(namebuf) -5;3229warning("truncating .rej filename to %.*s.rej",3230 cnt -1, patch->new_name);3231}3232memcpy(namebuf, patch->new_name, cnt);3233memcpy(namebuf + cnt,".rej",5);32343235 rej =fopen(namebuf,"w");3236if(!rej)3237returnerror("cannot open%s:%s", namebuf,strerror(errno));32383239/* Normal git tools never deal with .rej, so do not pretend3240 * this is a git patch by saying --git nor give extended3241 * headers. While at it, maybe please "kompare" that wants3242 * the trailing TAB and some garbage at the end of line ;-).3243 */3244fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",3245 patch->new_name, patch->new_name);3246for(cnt =1, frag = patch->fragments;3247 frag;3248 cnt++, frag = frag->next) {3249if(!frag->rejected) {3250fprintf(stderr,"Hunk #%dapplied cleanly.\n", cnt);3251continue;3252}3253fprintf(stderr,"Rejected hunk #%d.\n", cnt);3254fprintf(rej,"%.*s", frag->size, frag->patch);3255if(frag->patch[frag->size-1] !='\n')3256fputc('\n', rej);3257}3258fclose(rej);3259return-1;3260}32613262static intwrite_out_results(struct patch *list,int skipped_patch)3263{3264int phase;3265int errs =0;3266struct patch *l;32673268if(!list && !skipped_patch)3269returnerror("No changes");32703271for(phase =0; phase <2; phase++) {3272 l = list;3273while(l) {3274if(l->rejected)3275 errs =1;3276else{3277write_out_one_result(l, phase);3278if(phase ==1&&write_out_one_reject(l))3279 errs =1;3280}3281 l = l->next;3282}3283}3284return errs;3285}32863287static struct lock_file lock_file;32883289static struct string_list limit_by_name;3290static int has_include;3291static voidadd_name_limit(const char*name,int exclude)3292{3293struct string_list_item *it;32943295 it =string_list_append(name, &limit_by_name);3296 it->util = exclude ? NULL : (void*)1;3297}32983299static intuse_patch(struct patch *p)3300{3301const char*pathname = p->new_name ? p->new_name : p->old_name;3302int i;33033304/* Paths outside are not touched regardless of "--include" */3305if(0< prefix_length) {3306int pathlen =strlen(pathname);3307if(pathlen <= prefix_length ||3308memcmp(prefix, pathname, prefix_length))3309return0;3310}33113312/* See if it matches any of exclude/include rule */3313for(i =0; i < limit_by_name.nr; i++) {3314struct string_list_item *it = &limit_by_name.items[i];3315if(!fnmatch(it->string, pathname,0))3316return(it->util != NULL);3317}33183319/*3320 * If we had any include, a path that does not match any rule is3321 * not used. Otherwise, we saw bunch of exclude rules (or none)3322 * and such a path is used.3323 */3324return!has_include;3325}332633273328static voidprefix_one(char**name)3329{3330char*old_name = *name;3331if(!old_name)3332return;3333*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3334free(old_name);3335}33363337static voidprefix_patches(struct patch *p)3338{3339if(!prefix || p->is_toplevel_relative)3340return;3341for( ; p; p = p->next) {3342if(p->new_name == p->old_name) {3343char*prefixed = p->new_name;3344prefix_one(&prefixed);3345 p->new_name = p->old_name = prefixed;3346}3347else{3348prefix_one(&p->new_name);3349prefix_one(&p->old_name);3350}3351}3352}33533354#define INACCURATE_EOF (1<<0)3355#define RECOUNT (1<<1)33563357static intapply_patch(int fd,const char*filename,int options)3358{3359size_t offset;3360struct strbuf buf = STRBUF_INIT;3361struct patch *list = NULL, **listp = &list;3362int skipped_patch =0;33633364/* FIXME - memory leak when using multiple patch files as inputs */3365memset(&fn_table,0,sizeof(struct string_list));3366 patch_input_file = filename;3367read_patch_file(&buf, fd);3368 offset =0;3369while(offset < buf.len) {3370struct patch *patch;3371int nr;33723373 patch =xcalloc(1,sizeof(*patch));3374 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3375 patch->recount = !!(options & RECOUNT);3376 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3377if(nr <0)3378break;3379if(apply_in_reverse)3380reverse_patches(patch);3381if(prefix)3382prefix_patches(patch);3383if(use_patch(patch)) {3384patch_stats(patch);3385*listp = patch;3386 listp = &patch->next;3387}3388else{3389/* perhaps free it a bit better? */3390free(patch);3391 skipped_patch++;3392}3393 offset += nr;3394}33953396if(whitespace_error && (ws_error_action == die_on_ws_error))3397 apply =0;33983399 update_index = check_index && apply;3400if(update_index && newfd <0)3401 newfd =hold_locked_index(&lock_file,1);34023403if(check_index) {3404if(read_cache() <0)3405die("unable to read index file");3406}34073408if((check || apply) &&3409check_patch_list(list) <0&&3410!apply_with_reject)3411exit(1);34123413if(apply &&write_out_results(list, skipped_patch))3414exit(1);34153416if(fake_ancestor)3417build_fake_ancestor(list, fake_ancestor);34183419if(diffstat)3420stat_patch_list(list);34213422if(numstat)3423numstat_patch_list(list);34243425if(summary)3426summary_patch_list(list);34273428strbuf_release(&buf);3429return0;3430}34313432static intgit_apply_config(const char*var,const char*value,void*cb)3433{3434if(!strcmp(var,"apply.whitespace"))3435returngit_config_string(&apply_default_whitespace, var, value);3436else if(!strcmp(var,"apply.ignorewhitespace"))3437returngit_config_string(&apply_default_ignorewhitespace, var, value);3438returngit_default_config(var, value, cb);3439}34403441static intoption_parse_exclude(const struct option *opt,3442const char*arg,int unset)3443{3444add_name_limit(arg,1);3445return0;3446}34473448static intoption_parse_include(const struct option *opt,3449const char*arg,int unset)3450{3451add_name_limit(arg,0);3452 has_include =1;3453return0;3454}34553456static intoption_parse_p(const struct option *opt,3457const char*arg,int unset)3458{3459 p_value =atoi(arg);3460 p_value_known =1;3461return0;3462}34633464static intoption_parse_z(const struct option *opt,3465const char*arg,int unset)3466{3467if(unset)3468 line_termination ='\n';3469else3470 line_termination =0;3471return0;3472}34733474static intoption_parse_space_change(const struct option *opt,3475const char*arg,int unset)3476{3477if(unset)3478 ws_ignore_action = ignore_ws_none;3479else3480 ws_ignore_action = ignore_ws_change;3481return0;3482}34833484static intoption_parse_whitespace(const struct option *opt,3485const char*arg,int unset)3486{3487const char**whitespace_option = opt->value;34883489*whitespace_option = arg;3490parse_whitespace_option(arg);3491return0;3492}34933494static intoption_parse_directory(const struct option *opt,3495const char*arg,int unset)3496{3497 root_len =strlen(arg);3498if(root_len && arg[root_len -1] !='/') {3499char*new_root;3500 root = new_root =xmalloc(root_len +2);3501strcpy(new_root, arg);3502strcpy(new_root + root_len++,"/");3503}else3504 root = arg;3505return0;3506}35073508intcmd_apply(int argc,const char**argv,const char*unused_prefix)3509{3510int i;3511int errs =0;3512int is_not_gitdir;3513int binary;3514int force_apply =0;35153516const char*whitespace_option = NULL;35173518struct option builtin_apply_options[] = {3519{ OPTION_CALLBACK,0,"exclude", NULL,"path",3520"don't apply changes matching the given path",35210, option_parse_exclude },3522{ OPTION_CALLBACK,0,"include", NULL,"path",3523"apply changes matching the given path",35240, option_parse_include },3525{ OPTION_CALLBACK,'p', NULL, NULL,"num",3526"remove <num> leading slashes from traditional diff paths",35270, option_parse_p },3528OPT_BOOLEAN(0,"no-add", &no_add,3529"ignore additions made by the patch"),3530OPT_BOOLEAN(0,"stat", &diffstat,3531"instead of applying the patch, output diffstat for the input"),3532{ OPTION_BOOLEAN,0,"allow-binary-replacement", &binary,3533 NULL,"old option, now no-op",3534 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3535{ OPTION_BOOLEAN,0,"binary", &binary,3536 NULL,"old option, now no-op",3537 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3538OPT_BOOLEAN(0,"numstat", &numstat,3539"shows number of added and deleted lines in decimal notation"),3540OPT_BOOLEAN(0,"summary", &summary,3541"instead of applying the patch, output a summary for the input"),3542OPT_BOOLEAN(0,"check", &check,3543"instead of applying the patch, see if the patch is applicable"),3544OPT_BOOLEAN(0,"index", &check_index,3545"make sure the patch is applicable to the current index"),3546OPT_BOOLEAN(0,"cached", &cached,3547"apply a patch without touching the working tree"),3548OPT_BOOLEAN(0,"apply", &force_apply,3549"also apply the patch (use with --stat/--summary/--check)"),3550OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,3551"build a temporary index based on embedded index information"),3552{ OPTION_CALLBACK,'z', NULL, NULL, NULL,3553"paths are separated with NUL character",3554 PARSE_OPT_NOARG, option_parse_z },3555OPT_INTEGER('C', NULL, &p_context,3556"ensure at least <n> lines of context match"),3557{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,"action",3558"detect new or modified lines that have whitespace errors",35590, option_parse_whitespace },3560{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,3561"ignore changes in whitespace when finding context",3562 PARSE_OPT_NOARG, option_parse_space_change },3563{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,3564"ignore changes in whitespace when finding context",3565 PARSE_OPT_NOARG, option_parse_space_change },3566OPT_BOOLEAN('R',"reverse", &apply_in_reverse,3567"apply the patch in reverse"),3568OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,3569"don't expect at least one line of context"),3570OPT_BOOLEAN(0,"reject", &apply_with_reject,3571"leave the rejected hunks in corresponding *.rej files"),3572OPT__VERBOSE(&apply_verbosely),3573OPT_BIT(0,"inaccurate-eof", &options,3574"tolerate incorrectly detected missing new-line at the end of file",3575 INACCURATE_EOF),3576OPT_BIT(0,"recount", &options,3577"do not trust the line counts in the hunk headers",3578 RECOUNT),3579{ OPTION_CALLBACK,0,"directory", NULL,"root",3580"prepend <root> to all filenames",35810, option_parse_directory },3582OPT_END()3583};35843585 prefix =setup_git_directory_gently(&is_not_gitdir);3586 prefix_length = prefix ?strlen(prefix) :0;3587git_config(git_apply_config, NULL);3588if(apply_default_whitespace)3589parse_whitespace_option(apply_default_whitespace);3590if(apply_default_ignorewhitespace)3591parse_ignorewhitespace_option(apply_default_ignorewhitespace);35923593 argc =parse_options(argc, argv, prefix, builtin_apply_options,3594 apply_usage,0);35953596if(apply_with_reject)3597 apply = apply_verbosely =1;3598if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))3599 apply =0;3600if(check_index && is_not_gitdir)3601die("--index outside a repository");3602if(cached) {3603if(is_not_gitdir)3604die("--cached outside a repository");3605 check_index =1;3606}3607for(i =0; i < argc; i++) {3608const char*arg = argv[i];3609int fd;36103611if(!strcmp(arg,"-")) {3612 errs |=apply_patch(0,"<stdin>", options);3613 read_stdin =0;3614continue;3615}else if(0< prefix_length)3616 arg =prefix_filename(prefix, prefix_length, arg);36173618 fd =open(arg, O_RDONLY);3619if(fd <0)3620die_errno("can't open patch '%s'", arg);3621 read_stdin =0;3622set_default_whitespace_mode(whitespace_option);3623 errs |=apply_patch(fd, arg, options);3624close(fd);3625}3626set_default_whitespace_mode(whitespace_option);3627if(read_stdin)3628 errs |=apply_patch(0,"<stdin>", options);3629if(whitespace_error) {3630if(squelch_whitespace_errors &&3631 squelch_whitespace_errors < whitespace_error) {3632int squelched =3633 whitespace_error - squelch_whitespace_errors;3634warning("squelched%d"3635"whitespace error%s",3636 squelched,3637 squelched ==1?"":"s");3638}3639if(ws_error_action == die_on_ws_error)3640die("%dline%sadd%swhitespace errors.",3641 whitespace_error,3642 whitespace_error ==1?"":"s",3643 whitespace_error ==1?"s":"");3644if(applied_after_fixing_ws && apply)3645warning("%dline%sapplied after"3646" fixing whitespace errors.",3647 applied_after_fixing_ws,3648 applied_after_fixing_ws ==1?"":"s");3649else if(whitespace_error)3650warning("%dline%sadd%swhitespace errors.",3651 whitespace_error,3652 whitespace_error ==1?"":"s",3653 whitespace_error ==1?"s":"");3654}36553656if(update_index) {3657if(write_cache(newfd, active_cache, active_nr) ||3658commit_locked_index(&lock_file))3659die("Unable to write new index file");3660}36613662return!!errs;3663}