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 i; 827 828for(i =0; i < llen; i++) { 829int ch = line[i]; 830if(ch =='/') 831return line + i; 832} 833return NULL; 834} 835 836/* 837 * This is to extract the same name that appears on "diff --git" 838 * line. We do not find and return anything if it is a rename 839 * patch, and it is OK because we will find the name elsewhere. 840 * We need to reliably find name only when it is mode-change only, 841 * creation or deletion of an empty file. In any of these cases, 842 * both sides are the same name under a/ and b/ respectively. 843 */ 844static char*git_header_name(char*line,int llen) 845{ 846const char*name; 847const char*second = NULL; 848size_t len; 849 850 line +=strlen("diff --git "); 851 llen -=strlen("diff --git "); 852 853if(*line =='"') { 854const char*cp; 855struct strbuf first = STRBUF_INIT; 856struct strbuf sp = STRBUF_INIT; 857 858if(unquote_c_style(&first, line, &second)) 859goto free_and_fail1; 860 861/* advance to the first slash */ 862 cp =stop_at_slash(first.buf, first.len); 863/* we do not accept absolute paths */ 864if(!cp || cp == first.buf) 865goto free_and_fail1; 866strbuf_remove(&first,0, cp +1- first.buf); 867 868/* 869 * second points at one past closing dq of name. 870 * find the second name. 871 */ 872while((second < line + llen) &&isspace(*second)) 873 second++; 874 875if(line + llen <= second) 876goto free_and_fail1; 877if(*second =='"') { 878if(unquote_c_style(&sp, second, NULL)) 879goto free_and_fail1; 880 cp =stop_at_slash(sp.buf, sp.len); 881if(!cp || cp == sp.buf) 882goto free_and_fail1; 883/* They must match, otherwise ignore */ 884if(strcmp(cp +1, first.buf)) 885goto free_and_fail1; 886strbuf_release(&sp); 887returnstrbuf_detach(&first, NULL); 888} 889 890/* unquoted second */ 891 cp =stop_at_slash(second, line + llen - second); 892if(!cp || cp == second) 893goto free_and_fail1; 894 cp++; 895if(line + llen - cp != first.len +1|| 896memcmp(first.buf, cp, first.len)) 897goto free_and_fail1; 898returnstrbuf_detach(&first, NULL); 899 900 free_and_fail1: 901strbuf_release(&first); 902strbuf_release(&sp); 903return NULL; 904} 905 906/* unquoted first name */ 907 name =stop_at_slash(line, llen); 908if(!name || name == line) 909return NULL; 910 name++; 911 912/* 913 * since the first name is unquoted, a dq if exists must be 914 * the beginning of the second name. 915 */ 916for(second = name; second < line + llen; second++) { 917if(*second =='"') { 918struct strbuf sp = STRBUF_INIT; 919const char*np; 920 921if(unquote_c_style(&sp, second, NULL)) 922goto free_and_fail2; 923 924 np =stop_at_slash(sp.buf, sp.len); 925if(!np || np == sp.buf) 926goto free_and_fail2; 927 np++; 928 929 len = sp.buf + sp.len - np; 930if(len < second - name && 931!strncmp(np, name, len) && 932isspace(name[len])) { 933/* Good */ 934strbuf_remove(&sp,0, np - sp.buf); 935returnstrbuf_detach(&sp, NULL); 936} 937 938 free_and_fail2: 939strbuf_release(&sp); 940return NULL; 941} 942} 943 944/* 945 * Accept a name only if it shows up twice, exactly the same 946 * form. 947 */ 948for(len =0; ; len++) { 949switch(name[len]) { 950default: 951continue; 952case'\n': 953return NULL; 954case'\t':case' ': 955 second = name+len; 956for(;;) { 957char c = *second++; 958if(c =='\n') 959return NULL; 960if(c =='/') 961break; 962} 963if(second[len] =='\n'&& !memcmp(name, second, len)) { 964returnxmemdupz(name, len); 965} 966} 967} 968} 969 970/* Verify that we recognize the lines following a git header */ 971static intparse_git_header(char*line,int len,unsigned int size,struct patch *patch) 972{ 973unsigned long offset; 974 975/* A git diff has explicit new/delete information, so we don't guess */ 976 patch->is_new =0; 977 patch->is_delete =0; 978 979/* 980 * Some things may not have the old name in the 981 * rest of the headers anywhere (pure mode changes, 982 * or removing or adding empty files), so we get 983 * the default name from the header. 984 */ 985 patch->def_name =git_header_name(line, len); 986if(patch->def_name && root) { 987char*s =xmalloc(root_len +strlen(patch->def_name) +1); 988strcpy(s, root); 989strcpy(s + root_len, patch->def_name); 990free(patch->def_name); 991 patch->def_name = s; 992} 993 994 line += len; 995 size -= len; 996 linenr++; 997for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) { 998static const struct opentry { 999const char*str;1000int(*fn)(const char*,struct patch *);1001} optable[] = {1002{"@@ -", gitdiff_hdrend },1003{"--- ", gitdiff_oldname },1004{"+++ ", gitdiff_newname },1005{"old mode ", gitdiff_oldmode },1006{"new mode ", gitdiff_newmode },1007{"deleted file mode ", gitdiff_delete },1008{"new file mode ", gitdiff_newfile },1009{"copy from ", gitdiff_copysrc },1010{"copy to ", gitdiff_copydst },1011{"rename old ", gitdiff_renamesrc },1012{"rename new ", gitdiff_renamedst },1013{"rename from ", gitdiff_renamesrc },1014{"rename to ", gitdiff_renamedst },1015{"similarity index ", gitdiff_similarity },1016{"dissimilarity index ", gitdiff_dissimilarity },1017{"index ", gitdiff_index },1018{"", gitdiff_unrecognized },1019};1020int i;10211022 len =linelen(line, size);1023if(!len || line[len-1] !='\n')1024break;1025for(i =0; i <ARRAY_SIZE(optable); i++) {1026const struct opentry *p = optable + i;1027int oplen =strlen(p->str);1028if(len < oplen ||memcmp(p->str, line, oplen))1029continue;1030if(p->fn(line + oplen, patch) <0)1031return offset;1032break;1033}1034}10351036return offset;1037}10381039static intparse_num(const char*line,unsigned long*p)1040{1041char*ptr;10421043if(!isdigit(*line))1044return0;1045*p =strtoul(line, &ptr,10);1046return ptr - line;1047}10481049static intparse_range(const char*line,int len,int offset,const char*expect,1050unsigned long*p1,unsigned long*p2)1051{1052int digits, ex;10531054if(offset <0|| offset >= len)1055return-1;1056 line += offset;1057 len -= offset;10581059 digits =parse_num(line, p1);1060if(!digits)1061return-1;10621063 offset += digits;1064 line += digits;1065 len -= digits;10661067*p2 =1;1068if(*line ==',') {1069 digits =parse_num(line+1, p2);1070if(!digits)1071return-1;10721073 offset += digits+1;1074 line += digits+1;1075 len -= digits+1;1076}10771078 ex =strlen(expect);1079if(ex > len)1080return-1;1081if(memcmp(line, expect, ex))1082return-1;10831084return offset + ex;1085}10861087static voidrecount_diff(char*line,int size,struct fragment *fragment)1088{1089int oldlines =0, newlines =0, ret =0;10901091if(size <1) {1092warning("recount: ignore empty hunk");1093return;1094}10951096for(;;) {1097int len =linelen(line, size);1098 size -= len;1099 line += len;11001101if(size <1)1102break;11031104switch(*line) {1105case' ':case'\n':1106 newlines++;1107/* fall through */1108case'-':1109 oldlines++;1110continue;1111case'+':1112 newlines++;1113continue;1114case'\\':1115continue;1116case'@':1117 ret = size <3||prefixcmp(line,"@@ ");1118break;1119case'd':1120 ret = size <5||prefixcmp(line,"diff ");1121break;1122default:1123 ret = -1;1124break;1125}1126if(ret) {1127warning("recount: unexpected line: %.*s",1128(int)linelen(line, size), line);1129return;1130}1131break;1132}1133 fragment->oldlines = oldlines;1134 fragment->newlines = newlines;1135}11361137/*1138 * Parse a unified diff fragment header of the1139 * form "@@ -a,b +c,d @@"1140 */1141static intparse_fragment_header(char*line,int len,struct fragment *fragment)1142{1143int offset;11441145if(!len || line[len-1] !='\n')1146return-1;11471148/* Figure out the number of lines in a fragment */1149 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1150 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);11511152return offset;1153}11541155static intfind_header(char*line,unsigned long size,int*hdrsize,struct patch *patch)1156{1157unsigned long offset, len;11581159 patch->is_toplevel_relative =0;1160 patch->is_rename = patch->is_copy =0;1161 patch->is_new = patch->is_delete = -1;1162 patch->old_mode = patch->new_mode =0;1163 patch->old_name = patch->new_name = NULL;1164for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1165unsigned long nextlen;11661167 len =linelen(line, size);1168if(!len)1169break;11701171/* Testing this early allows us to take a few shortcuts.. */1172if(len <6)1173continue;11741175/*1176 * Make sure we don't find any unconnected patch fragments.1177 * That's a sign that we didn't find a header, and that a1178 * patch has become corrupted/broken up.1179 */1180if(!memcmp("@@ -", line,4)) {1181struct fragment dummy;1182if(parse_fragment_header(line, len, &dummy) <0)1183continue;1184die("patch fragment without header at line%d: %.*s",1185 linenr, (int)len-1, line);1186}11871188if(size < len +6)1189break;11901191/*1192 * Git patch? It might not have a real patch, just a rename1193 * or mode change, so we handle that specially1194 */1195if(!memcmp("diff --git ", line,11)) {1196int git_hdr_len =parse_git_header(line, len, size, patch);1197if(git_hdr_len <= len)1198continue;1199if(!patch->old_name && !patch->new_name) {1200if(!patch->def_name)1201die("git diff header lacks filename information (line%d)", linenr);1202 patch->old_name = patch->new_name = patch->def_name;1203}1204 patch->is_toplevel_relative =1;1205*hdrsize = git_hdr_len;1206return offset;1207}12081209/* --- followed by +++ ? */1210if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1211continue;12121213/*1214 * We only accept unified patches, so we want it to1215 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1216 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1217 */1218 nextlen =linelen(line + len, size - len);1219if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1220continue;12211222/* Ok, we'll consider it a patch */1223parse_traditional_patch(line, line+len, patch);1224*hdrsize = len + nextlen;1225 linenr +=2;1226return offset;1227}1228return-1;1229}12301231static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1232{1233char*err;12341235if(!result)1236return;12371238 whitespace_error++;1239if(squelch_whitespace_errors &&1240 squelch_whitespace_errors < whitespace_error)1241return;12421243 err =whitespace_error_string(result);1244fprintf(stderr,"%s:%d:%s.\n%.*s\n",1245 patch_input_file, linenr, err, len, line);1246free(err);1247}12481249static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1250{1251unsigned result =ws_check(line +1, len -1, ws_rule);12521253record_ws_error(result, line +1, len -2, linenr);1254}12551256/*1257 * Parse a unified diff. Note that this really needs to parse each1258 * fragment separately, since the only way to know the difference1259 * between a "---" that is part of a patch, and a "---" that starts1260 * the next patch is to look at the line counts..1261 */1262static intparse_fragment(char*line,unsigned long size,1263struct patch *patch,struct fragment *fragment)1264{1265int added, deleted;1266int len =linelen(line, size), offset;1267unsigned long oldlines, newlines;1268unsigned long leading, trailing;12691270 offset =parse_fragment_header(line, len, fragment);1271if(offset <0)1272return-1;1273if(offset >0&& patch->recount)1274recount_diff(line + offset, size - offset, fragment);1275 oldlines = fragment->oldlines;1276 newlines = fragment->newlines;1277 leading =0;1278 trailing =0;12791280/* Parse the thing.. */1281 line += len;1282 size -= len;1283 linenr++;1284 added = deleted =0;1285for(offset = len;12860< size;1287 offset += len, size -= len, line += len, linenr++) {1288if(!oldlines && !newlines)1289break;1290 len =linelen(line, size);1291if(!len || line[len-1] !='\n')1292return-1;1293switch(*line) {1294default:1295return-1;1296case'\n':/* newer GNU diff, an empty context line */1297case' ':1298 oldlines--;1299 newlines--;1300if(!deleted && !added)1301 leading++;1302 trailing++;1303break;1304case'-':1305if(apply_in_reverse &&1306 ws_error_action != nowarn_ws_error)1307check_whitespace(line, len, patch->ws_rule);1308 deleted++;1309 oldlines--;1310 trailing =0;1311break;1312case'+':1313if(!apply_in_reverse &&1314 ws_error_action != nowarn_ws_error)1315check_whitespace(line, len, patch->ws_rule);1316 added++;1317 newlines--;1318 trailing =0;1319break;13201321/*1322 * We allow "\ No newline at end of file". Depending1323 * on locale settings when the patch was produced we1324 * don't know what this line looks like. The only1325 * thing we do know is that it begins with "\ ".1326 * Checking for 12 is just for sanity check -- any1327 * l10n of "\ No newline..." is at least that long.1328 */1329case'\\':1330if(len <12||memcmp(line,"\\",2))1331return-1;1332break;1333}1334}1335if(oldlines || newlines)1336return-1;1337 fragment->leading = leading;1338 fragment->trailing = trailing;13391340/*1341 * If a fragment ends with an incomplete line, we failed to include1342 * it in the above loop because we hit oldlines == newlines == 01343 * before seeing it.1344 */1345if(12< size && !memcmp(line,"\\",2))1346 offset +=linelen(line, size);13471348 patch->lines_added += added;1349 patch->lines_deleted += deleted;13501351if(0< patch->is_new && oldlines)1352returnerror("new file depends on old contents");1353if(0< patch->is_delete && newlines)1354returnerror("deleted file still has contents");1355return offset;1356}13571358static intparse_single_patch(char*line,unsigned long size,struct patch *patch)1359{1360unsigned long offset =0;1361unsigned long oldlines =0, newlines =0, context =0;1362struct fragment **fragp = &patch->fragments;13631364while(size >4&& !memcmp(line,"@@ -",4)) {1365struct fragment *fragment;1366int len;13671368 fragment =xcalloc(1,sizeof(*fragment));1369 fragment->linenr = linenr;1370 len =parse_fragment(line, size, patch, fragment);1371if(len <=0)1372die("corrupt patch at line%d", linenr);1373 fragment->patch = line;1374 fragment->size = len;1375 oldlines += fragment->oldlines;1376 newlines += fragment->newlines;1377 context += fragment->leading + fragment->trailing;13781379*fragp = fragment;1380 fragp = &fragment->next;13811382 offset += len;1383 line += len;1384 size -= len;1385}13861387/*1388 * If something was removed (i.e. we have old-lines) it cannot1389 * be creation, and if something was added it cannot be1390 * deletion. However, the reverse is not true; --unified=01391 * patches that only add are not necessarily creation even1392 * though they do not have any old lines, and ones that only1393 * delete are not necessarily deletion.1394 *1395 * Unfortunately, a real creation/deletion patch do _not_ have1396 * any context line by definition, so we cannot safely tell it1397 * apart with --unified=0 insanity. At least if the patch has1398 * more than one hunk it is not creation or deletion.1399 */1400if(patch->is_new <0&&1401(oldlines || (patch->fragments && patch->fragments->next)))1402 patch->is_new =0;1403if(patch->is_delete <0&&1404(newlines || (patch->fragments && patch->fragments->next)))1405 patch->is_delete =0;14061407if(0< patch->is_new && oldlines)1408die("new file%sdepends on old contents", patch->new_name);1409if(0< patch->is_delete && newlines)1410die("deleted file%sstill has contents", patch->old_name);1411if(!patch->is_delete && !newlines && context)1412fprintf(stderr,"** warning: file%sbecomes empty but "1413"is not deleted\n", patch->new_name);14141415return offset;1416}14171418staticinlineintmetadata_changes(struct patch *patch)1419{1420return patch->is_rename >0||1421 patch->is_copy >0||1422 patch->is_new >0||1423 patch->is_delete ||1424(patch->old_mode && patch->new_mode &&1425 patch->old_mode != patch->new_mode);1426}14271428static char*inflate_it(const void*data,unsigned long size,1429unsigned long inflated_size)1430{1431 z_stream stream;1432void*out;1433int st;14341435memset(&stream,0,sizeof(stream));14361437 stream.next_in = (unsigned char*)data;1438 stream.avail_in = size;1439 stream.next_out = out =xmalloc(inflated_size);1440 stream.avail_out = inflated_size;1441git_inflate_init(&stream);1442 st =git_inflate(&stream, Z_FINISH);1443git_inflate_end(&stream);1444if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1445free(out);1446return NULL;1447}1448return out;1449}14501451static struct fragment *parse_binary_hunk(char**buf_p,1452unsigned long*sz_p,1453int*status_p,1454int*used_p)1455{1456/*1457 * Expect a line that begins with binary patch method ("literal"1458 * or "delta"), followed by the length of data before deflating.1459 * a sequence of 'length-byte' followed by base-85 encoded data1460 * should follow, terminated by a newline.1461 *1462 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1463 * and we would limit the patch line to 66 characters,1464 * so one line can fit up to 13 groups that would decode1465 * to 52 bytes max. The length byte 'A'-'Z' corresponds1466 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1467 */1468int llen, used;1469unsigned long size = *sz_p;1470char*buffer = *buf_p;1471int patch_method;1472unsigned long origlen;1473char*data = NULL;1474int hunk_size =0;1475struct fragment *frag;14761477 llen =linelen(buffer, size);1478 used = llen;14791480*status_p =0;14811482if(!prefixcmp(buffer,"delta ")) {1483 patch_method = BINARY_DELTA_DEFLATED;1484 origlen =strtoul(buffer +6, NULL,10);1485}1486else if(!prefixcmp(buffer,"literal ")) {1487 patch_method = BINARY_LITERAL_DEFLATED;1488 origlen =strtoul(buffer +8, NULL,10);1489}1490else1491return NULL;14921493 linenr++;1494 buffer += llen;1495while(1) {1496int byte_length, max_byte_length, newsize;1497 llen =linelen(buffer, size);1498 used += llen;1499 linenr++;1500if(llen ==1) {1501/* consume the blank line */1502 buffer++;1503 size--;1504break;1505}1506/*1507 * Minimum line is "A00000\n" which is 7-byte long,1508 * and the line length must be multiple of 5 plus 2.1509 */1510if((llen <7) || (llen-2) %5)1511goto corrupt;1512 max_byte_length = (llen -2) /5*4;1513 byte_length = *buffer;1514if('A'<= byte_length && byte_length <='Z')1515 byte_length = byte_length -'A'+1;1516else if('a'<= byte_length && byte_length <='z')1517 byte_length = byte_length -'a'+27;1518else1519goto corrupt;1520/* if the input length was not multiple of 4, we would1521 * have filler at the end but the filler should never1522 * exceed 3 bytes1523 */1524if(max_byte_length < byte_length ||1525 byte_length <= max_byte_length -4)1526goto corrupt;1527 newsize = hunk_size + byte_length;1528 data =xrealloc(data, newsize);1529if(decode_85(data + hunk_size, buffer +1, byte_length))1530goto corrupt;1531 hunk_size = newsize;1532 buffer += llen;1533 size -= llen;1534}15351536 frag =xcalloc(1,sizeof(*frag));1537 frag->patch =inflate_it(data, hunk_size, origlen);1538if(!frag->patch)1539goto corrupt;1540free(data);1541 frag->size = origlen;1542*buf_p = buffer;1543*sz_p = size;1544*used_p = used;1545 frag->binary_patch_method = patch_method;1546return frag;15471548 corrupt:1549free(data);1550*status_p = -1;1551error("corrupt binary patch at line%d: %.*s",1552 linenr-1, llen-1, buffer);1553return NULL;1554}15551556static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1557{1558/*1559 * We have read "GIT binary patch\n"; what follows is a line1560 * that says the patch method (currently, either "literal" or1561 * "delta") and the length of data before deflating; a1562 * sequence of 'length-byte' followed by base-85 encoded data1563 * follows.1564 *1565 * When a binary patch is reversible, there is another binary1566 * hunk in the same format, starting with patch method (either1567 * "literal" or "delta") with the length of data, and a sequence1568 * of length-byte + base-85 encoded data, terminated with another1569 * empty line. This data, when applied to the postimage, produces1570 * the preimage.1571 */1572struct fragment *forward;1573struct fragment *reverse;1574int status;1575int used, used_1;15761577 forward =parse_binary_hunk(&buffer, &size, &status, &used);1578if(!forward && !status)1579/* there has to be one hunk (forward hunk) */1580returnerror("unrecognized binary patch at line%d", linenr-1);1581if(status)1582/* otherwise we already gave an error message */1583return status;15841585 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1586if(reverse)1587 used += used_1;1588else if(status) {1589/*1590 * Not having reverse hunk is not an error, but having1591 * a corrupt reverse hunk is.1592 */1593free((void*) forward->patch);1594free(forward);1595return status;1596}1597 forward->next = reverse;1598 patch->fragments = forward;1599 patch->is_binary =1;1600return used;1601}16021603static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1604{1605int hdrsize, patchsize;1606int offset =find_header(buffer, size, &hdrsize, patch);16071608if(offset <0)1609return offset;16101611 patch->ws_rule =whitespace_rule(patch->new_name1612? patch->new_name1613: patch->old_name);16141615 patchsize =parse_single_patch(buffer + offset + hdrsize,1616 size - offset - hdrsize, patch);16171618if(!patchsize) {1619static const char*binhdr[] = {1620"Binary files ",1621"Files ",1622 NULL,1623};1624static const char git_binary[] ="GIT binary patch\n";1625int i;1626int hd = hdrsize + offset;1627unsigned long llen =linelen(buffer + hd, size - hd);16281629if(llen ==sizeof(git_binary) -1&&1630!memcmp(git_binary, buffer + hd, llen)) {1631int used;1632 linenr++;1633 used =parse_binary(buffer + hd + llen,1634 size - hd - llen, patch);1635if(used)1636 patchsize = used + llen;1637else1638 patchsize =0;1639}1640else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1641for(i =0; binhdr[i]; i++) {1642int len =strlen(binhdr[i]);1643if(len < size - hd &&1644!memcmp(binhdr[i], buffer + hd, len)) {1645 linenr++;1646 patch->is_binary =1;1647 patchsize = llen;1648break;1649}1650}1651}16521653/* Empty patch cannot be applied if it is a text patch1654 * without metadata change. A binary patch appears1655 * empty to us here.1656 */1657if((apply || check) &&1658(!patch->is_binary && !metadata_changes(patch)))1659die("patch with only garbage at line%d", linenr);1660}16611662return offset + hdrsize + patchsize;1663}16641665#define swap(a,b) myswap((a),(b),sizeof(a))16661667#define myswap(a, b, size) do { \1668 unsigned char mytmp[size]; \1669 memcpy(mytmp, &a, size); \1670 memcpy(&a, &b, size); \1671 memcpy(&b, mytmp, size); \1672} while (0)16731674static voidreverse_patches(struct patch *p)1675{1676for(; p; p = p->next) {1677struct fragment *frag = p->fragments;16781679swap(p->new_name, p->old_name);1680swap(p->new_mode, p->old_mode);1681swap(p->is_new, p->is_delete);1682swap(p->lines_added, p->lines_deleted);1683swap(p->old_sha1_prefix, p->new_sha1_prefix);16841685for(; frag; frag = frag->next) {1686swap(frag->newpos, frag->oldpos);1687swap(frag->newlines, frag->oldlines);1688}1689}1690}16911692static const char pluses[] =1693"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";1694static const char minuses[]=1695"----------------------------------------------------------------------";16961697static voidshow_stats(struct patch *patch)1698{1699struct strbuf qname = STRBUF_INIT;1700char*cp = patch->new_name ? patch->new_name : patch->old_name;1701int max, add, del;17021703quote_c_style(cp, &qname, NULL,0);17041705/*1706 * "scale" the filename1707 */1708 max = max_len;1709if(max >50)1710 max =50;17111712if(qname.len > max) {1713 cp =strchr(qname.buf + qname.len +3- max,'/');1714if(!cp)1715 cp = qname.buf + qname.len +3- max;1716strbuf_splice(&qname,0, cp - qname.buf,"...",3);1717}17181719if(patch->is_binary) {1720printf(" %-*s | Bin\n", max, qname.buf);1721strbuf_release(&qname);1722return;1723}17241725printf(" %-*s |", max, qname.buf);1726strbuf_release(&qname);17271728/*1729 * scale the add/delete1730 */1731 max = max + max_change >70?70- max : max_change;1732 add = patch->lines_added;1733 del = patch->lines_deleted;17341735if(max_change >0) {1736int total = ((add + del) * max + max_change /2) / max_change;1737 add = (add * max + max_change /2) / max_change;1738 del = total - add;1739}1740printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,1741 add, pluses, del, minuses);1742}17431744static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)1745{1746switch(st->st_mode & S_IFMT) {1747case S_IFLNK:1748if(strbuf_readlink(buf, path, st->st_size) <0)1749returnerror("unable to read symlink%s", path);1750return0;1751case S_IFREG:1752if(strbuf_read_file(buf, path, st->st_size) != st->st_size)1753returnerror("unable to open or read%s", path);1754convert_to_git(path, buf->buf, buf->len, buf,0);1755return0;1756default:1757return-1;1758}1759}17601761/*1762 * Update the preimage, and the common lines in postimage,1763 * from buffer buf of length len. If postlen is 0 the postimage1764 * is updated in place, otherwise it's updated on a new buffer1765 * of length postlen1766 */17671768static voidupdate_pre_post_images(struct image *preimage,1769struct image *postimage,1770char*buf,1771size_t len,size_t postlen)1772{1773int i, ctx;1774char*new, *old, *fixed;1775struct image fixed_preimage;17761777/*1778 * Update the preimage with whitespace fixes. Note that we1779 * are not losing preimage->buf -- apply_one_fragment() will1780 * free "oldlines".1781 */1782prepare_image(&fixed_preimage, buf, len,1);1783assert(fixed_preimage.nr == preimage->nr);1784for(i =0; i < preimage->nr; i++)1785 fixed_preimage.line[i].flag = preimage->line[i].flag;1786free(preimage->line_allocated);1787*preimage = fixed_preimage;17881789/*1790 * Adjust the common context lines in postimage. This can be1791 * done in-place when we are just doing whitespace fixing,1792 * which does not make the string grow, but needs a new buffer1793 * when ignoring whitespace causes the update, since in this case1794 * we could have e.g. tabs converted to multiple spaces.1795 * We trust the caller to tell us if the update can be done1796 * in place (postlen==0) or not.1797 */1798 old = postimage->buf;1799if(postlen)1800new= postimage->buf =xmalloc(postlen);1801else1802new= old;1803 fixed = preimage->buf;1804for(i = ctx =0; i < postimage->nr; i++) {1805size_t len = postimage->line[i].len;1806if(!(postimage->line[i].flag & LINE_COMMON)) {1807/* an added line -- no counterparts in preimage */1808memmove(new, old, len);1809 old += len;1810new+= len;1811continue;1812}18131814/* a common context -- skip it in the original postimage */1815 old += len;18161817/* and find the corresponding one in the fixed preimage */1818while(ctx < preimage->nr &&1819!(preimage->line[ctx].flag & LINE_COMMON)) {1820 fixed += preimage->line[ctx].len;1821 ctx++;1822}1823if(preimage->nr <= ctx)1824die("oops");18251826/* and copy it in, while fixing the line length */1827 len = preimage->line[ctx].len;1828memcpy(new, fixed, len);1829new+= len;1830 fixed += len;1831 postimage->line[i].len = len;1832 ctx++;1833}18341835/* Fix the length of the whole thing */1836 postimage->len =new- postimage->buf;1837}18381839static intmatch_fragment(struct image *img,1840struct image *preimage,1841struct image *postimage,1842unsigned longtry,1843int try_lno,1844unsigned ws_rule,1845int match_beginning,int match_end)1846{1847int i;1848char*fixed_buf, *buf, *orig, *target;18491850if(preimage->nr + try_lno > img->nr)1851return0;18521853if(match_beginning && try_lno)1854return0;18551856if(match_end && preimage->nr + try_lno != img->nr)1857return0;18581859/* Quick hash check */1860for(i =0; i < preimage->nr; i++)1861if(preimage->line[i].hash != img->line[try_lno + i].hash)1862return0;18631864/*1865 * Do we have an exact match? If we were told to match1866 * at the end, size must be exactly at try+fragsize,1867 * otherwise try+fragsize must be still within the preimage,1868 * and either case, the old piece should match the preimage1869 * exactly.1870 */1871if((match_end1872? (try+ preimage->len == img->len)1873: (try+ preimage->len <= img->len)) &&1874!memcmp(img->buf +try, preimage->buf, preimage->len))1875return1;18761877/*1878 * No exact match. If we are ignoring whitespace, run a line-by-line1879 * fuzzy matching. We collect all the line length information because1880 * we need it to adjust whitespace if we match.1881 */1882if(ws_ignore_action == ignore_ws_change) {1883size_t imgoff =0;1884size_t preoff =0;1885size_t postlen = postimage->len;1886for(i =0; i < preimage->nr; i++) {1887size_t prelen = preimage->line[i].len;1888size_t imglen = img->line[try_lno+i].len;18891890if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,1891 preimage->buf + preoff, prelen))1892return0;1893if(preimage->line[i].flag & LINE_COMMON)1894 postlen += imglen - prelen;1895 imgoff += imglen;1896 preoff += prelen;1897}18981899/*1900 * Ok, the preimage matches with whitespace fuzz. Update it and1901 * the common postimage lines to use the same whitespace as the1902 * target. imgoff now holds the true length of the target that1903 * matches the preimage, and we need to update the line lengths1904 * of the preimage to match the target ones.1905 */1906 fixed_buf =xmalloc(imgoff);1907memcpy(fixed_buf, img->buf +try, imgoff);1908for(i =0; i < preimage->nr; i++)1909 preimage->line[i].len = img->line[try_lno+i].len;19101911/*1912 * Update the preimage buffer and the postimage context lines.1913 */1914update_pre_post_images(preimage, postimage,1915 fixed_buf, imgoff, postlen);1916return1;1917}19181919if(ws_error_action != correct_ws_error)1920return0;19211922/*1923 * The hunk does not apply byte-by-byte, but the hash says1924 * it might with whitespace fuzz. We haven't been asked to1925 * ignore whitespace, we were asked to correct whitespace1926 * errors, so let's try matching after whitespace correction.1927 */1928 fixed_buf =xmalloc(preimage->len +1);1929 buf = fixed_buf;1930 orig = preimage->buf;1931 target = img->buf +try;1932for(i =0; i < preimage->nr; i++) {1933size_t fixlen;/* length after fixing the preimage */1934size_t oldlen = preimage->line[i].len;1935size_t tgtlen = img->line[try_lno + i].len;1936size_t tgtfixlen;/* length after fixing the target line */1937char tgtfixbuf[1024], *tgtfix;1938int match;19391940/* Try fixing the line in the preimage */1941 fixlen =ws_fix_copy(buf, orig, oldlen, ws_rule, NULL);19421943/* Try fixing the line in the target */1944if(sizeof(tgtfixbuf) > tgtlen)1945 tgtfix = tgtfixbuf;1946else1947 tgtfix =xmalloc(tgtlen);1948 tgtfixlen =ws_fix_copy(tgtfix, target, tgtlen, ws_rule, NULL);19491950/*1951 * If they match, either the preimage was based on1952 * a version before our tree fixed whitespace breakage,1953 * or we are lacking a whitespace-fix patch the tree1954 * the preimage was based on already had (i.e. target1955 * has whitespace breakage, the preimage doesn't).1956 * In either case, we are fixing the whitespace breakages1957 * so we might as well take the fix together with their1958 * real change.1959 */1960 match = (tgtfixlen == fixlen && !memcmp(tgtfix, buf, fixlen));19611962if(tgtfix != tgtfixbuf)1963free(tgtfix);1964if(!match)1965goto unmatch_exit;19661967 orig += oldlen;1968 buf += fixlen;1969 target += tgtlen;1970}19711972/*1973 * Yes, the preimage is based on an older version that still1974 * has whitespace breakages unfixed, and fixing them makes the1975 * hunk match. Update the context lines in the postimage.1976 */1977update_pre_post_images(preimage, postimage,1978 fixed_buf, buf - fixed_buf,0);1979return1;19801981 unmatch_exit:1982free(fixed_buf);1983return0;1984}19851986static intfind_pos(struct image *img,1987struct image *preimage,1988struct image *postimage,1989int line,1990unsigned ws_rule,1991int match_beginning,int match_end)1992{1993int i;1994unsigned long backwards, forwards,try;1995int backwards_lno, forwards_lno, try_lno;19961997if(preimage->nr > img->nr)1998return-1;19992000/*2001 * If match_begining or match_end is specified, there is no2002 * point starting from a wrong line that will never match and2003 * wander around and wait for a match at the specified end.2004 */2005if(match_beginning)2006 line =0;2007else if(match_end)2008 line = img->nr - preimage->nr;20092010if(line > img->nr)2011 line = img->nr;20122013try=0;2014for(i =0; i < line; i++)2015try+= img->line[i].len;20162017/*2018 * There's probably some smart way to do this, but I'll leave2019 * that to the smart and beautiful people. I'm simple and stupid.2020 */2021 backwards =try;2022 backwards_lno = line;2023 forwards =try;2024 forwards_lno = line;2025 try_lno = line;20262027for(i =0; ; i++) {2028if(match_fragment(img, preimage, postimage,2029try, try_lno, ws_rule,2030 match_beginning, match_end))2031return try_lno;20322033 again:2034if(backwards_lno ==0&& forwards_lno == img->nr)2035break;20362037if(i &1) {2038if(backwards_lno ==0) {2039 i++;2040goto again;2041}2042 backwards_lno--;2043 backwards -= img->line[backwards_lno].len;2044try= backwards;2045 try_lno = backwards_lno;2046}else{2047if(forwards_lno == img->nr) {2048 i++;2049goto again;2050}2051 forwards += img->line[forwards_lno].len;2052 forwards_lno++;2053try= forwards;2054 try_lno = forwards_lno;2055}20562057}2058return-1;2059}20602061static voidremove_first_line(struct image *img)2062{2063 img->buf += img->line[0].len;2064 img->len -= img->line[0].len;2065 img->line++;2066 img->nr--;2067}20682069static voidremove_last_line(struct image *img)2070{2071 img->len -= img->line[--img->nr].len;2072}20732074static voidupdate_image(struct image *img,2075int applied_pos,2076struct image *preimage,2077struct image *postimage)2078{2079/*2080 * remove the copy of preimage at offset in img2081 * and replace it with postimage2082 */2083int i, nr;2084size_t remove_count, insert_count, applied_at =0;2085char*result;20862087for(i =0; i < applied_pos; i++)2088 applied_at += img->line[i].len;20892090 remove_count =0;2091for(i =0; i < preimage->nr; i++)2092 remove_count += img->line[applied_pos + i].len;2093 insert_count = postimage->len;20942095/* Adjust the contents */2096 result =xmalloc(img->len + insert_count - remove_count +1);2097memcpy(result, img->buf, applied_at);2098memcpy(result + applied_at, postimage->buf, postimage->len);2099memcpy(result + applied_at + postimage->len,2100 img->buf + (applied_at + remove_count),2101 img->len - (applied_at + remove_count));2102free(img->buf);2103 img->buf = result;2104 img->len += insert_count - remove_count;2105 result[img->len] ='\0';21062107/* Adjust the line table */2108 nr = img->nr + postimage->nr - preimage->nr;2109if(preimage->nr < postimage->nr) {2110/*2111 * NOTE: this knows that we never call remove_first_line()2112 * on anything other than pre/post image.2113 */2114 img->line =xrealloc(img->line, nr *sizeof(*img->line));2115 img->line_allocated = img->line;2116}2117if(preimage->nr != postimage->nr)2118memmove(img->line + applied_pos + postimage->nr,2119 img->line + applied_pos + preimage->nr,2120(img->nr - (applied_pos + preimage->nr)) *2121sizeof(*img->line));2122memcpy(img->line + applied_pos,2123 postimage->line,2124 postimage->nr *sizeof(*img->line));2125 img->nr = nr;2126}21272128static intapply_one_fragment(struct image *img,struct fragment *frag,2129int inaccurate_eof,unsigned ws_rule)2130{2131int match_beginning, match_end;2132const char*patch = frag->patch;2133int size = frag->size;2134char*old, *new, *oldlines, *newlines;2135int new_blank_lines_at_end =0;2136unsigned long leading, trailing;2137int pos, applied_pos;2138struct image preimage;2139struct image postimage;21402141memset(&preimage,0,sizeof(preimage));2142memset(&postimage,0,sizeof(postimage));2143 oldlines =xmalloc(size);2144 newlines =xmalloc(size);21452146 old = oldlines;2147new= newlines;2148while(size >0) {2149char first;2150int len =linelen(patch, size);2151int plen, added;2152int added_blank_line =0;2153int is_blank_context =0;21542155if(!len)2156break;21572158/*2159 * "plen" is how much of the line we should use for2160 * the actual patch data. Normally we just remove the2161 * first character on the line, but if the line is2162 * followed by "\ No newline", then we also remove the2163 * last one (which is the newline, of course).2164 */2165 plen = len -1;2166if(len < size && patch[len] =='\\')2167 plen--;2168 first = *patch;2169if(apply_in_reverse) {2170if(first =='-')2171 first ='+';2172else if(first =='+')2173 first ='-';2174}21752176switch(first) {2177case'\n':2178/* Newer GNU diff, empty context line */2179if(plen <0)2180/* ... followed by '\No newline'; nothing */2181break;2182*old++ ='\n';2183*new++ ='\n';2184add_line_info(&preimage,"\n",1, LINE_COMMON);2185add_line_info(&postimage,"\n",1, LINE_COMMON);2186 is_blank_context =1;2187break;2188case' ':2189if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2190ws_blank_line(patch +1, plen, ws_rule))2191 is_blank_context =1;2192case'-':2193memcpy(old, patch +1, plen);2194add_line_info(&preimage, old, plen,2195(first ==' '? LINE_COMMON :0));2196 old += plen;2197if(first =='-')2198break;2199/* Fall-through for ' ' */2200case'+':2201/* --no-add does not add new lines */2202if(first =='+'&& no_add)2203break;22042205if(first !='+'||2206!whitespace_error ||2207 ws_error_action != correct_ws_error) {2208memcpy(new, patch +1, plen);2209 added = plen;2210}2211else{2212 added =ws_fix_copy(new, patch +1, plen, ws_rule, &applied_after_fixing_ws);2213}2214add_line_info(&postimage,new, added,2215(first =='+'?0: LINE_COMMON));2216new+= added;2217if(first =='+'&&2218(ws_rule & WS_BLANK_AT_EOF) &&2219ws_blank_line(patch +1, plen, ws_rule))2220 added_blank_line =1;2221break;2222case'@':case'\\':2223/* Ignore it, we already handled it */2224break;2225default:2226if(apply_verbosely)2227error("invalid start of line: '%c'", first);2228return-1;2229}2230if(added_blank_line)2231 new_blank_lines_at_end++;2232else if(is_blank_context)2233;2234else2235 new_blank_lines_at_end =0;2236 patch += len;2237 size -= len;2238}2239if(inaccurate_eof &&2240 old > oldlines && old[-1] =='\n'&&2241new> newlines &&new[-1] =='\n') {2242 old--;2243new--;2244}22452246 leading = frag->leading;2247 trailing = frag->trailing;22482249/*2250 * A hunk to change lines at the beginning would begin with2251 * @@ -1,L +N,M @@2252 * but we need to be careful. -U0 that inserts before the second2253 * line also has this pattern.2254 *2255 * And a hunk to add to an empty file would begin with2256 * @@ -0,0 +N,M @@2257 *2258 * In other words, a hunk that is (frag->oldpos <= 1) with or2259 * without leading context must match at the beginning.2260 */2261 match_beginning = (!frag->oldpos ||2262(frag->oldpos ==1&& !unidiff_zero));22632264/*2265 * A hunk without trailing lines must match at the end.2266 * However, we simply cannot tell if a hunk must match end2267 * from the lack of trailing lines if the patch was generated2268 * with unidiff without any context.2269 */2270 match_end = !unidiff_zero && !trailing;22712272 pos = frag->newpos ? (frag->newpos -1) :0;2273 preimage.buf = oldlines;2274 preimage.len = old - oldlines;2275 postimage.buf = newlines;2276 postimage.len =new- newlines;2277 preimage.line = preimage.line_allocated;2278 postimage.line = postimage.line_allocated;22792280for(;;) {22812282 applied_pos =find_pos(img, &preimage, &postimage, pos,2283 ws_rule, match_beginning, match_end);22842285if(applied_pos >=0)2286break;22872288/* Am I at my context limits? */2289if((leading <= p_context) && (trailing <= p_context))2290break;2291if(match_beginning || match_end) {2292 match_beginning = match_end =0;2293continue;2294}22952296/*2297 * Reduce the number of context lines; reduce both2298 * leading and trailing if they are equal otherwise2299 * just reduce the larger context.2300 */2301if(leading >= trailing) {2302remove_first_line(&preimage);2303remove_first_line(&postimage);2304 pos--;2305 leading--;2306}2307if(trailing > leading) {2308remove_last_line(&preimage);2309remove_last_line(&postimage);2310 trailing--;2311}2312}23132314if(applied_pos >=0) {2315if(new_blank_lines_at_end &&2316 preimage.nr + applied_pos == img->nr &&2317(ws_rule & WS_BLANK_AT_EOF) &&2318 ws_error_action != nowarn_ws_error) {2319record_ws_error(WS_BLANK_AT_EOF,"+",1, frag->linenr);2320if(ws_error_action == correct_ws_error) {2321while(new_blank_lines_at_end--)2322remove_last_line(&postimage);2323}2324/*2325 * We would want to prevent write_out_results()2326 * from taking place in apply_patch() that follows2327 * the callchain led us here, which is:2328 * apply_patch->check_patch_list->check_patch->2329 * apply_data->apply_fragments->apply_one_fragment2330 */2331if(ws_error_action == die_on_ws_error)2332 apply =0;2333}23342335/*2336 * Warn if it was necessary to reduce the number2337 * of context lines.2338 */2339if((leading != frag->leading) ||2340(trailing != frag->trailing))2341fprintf(stderr,"Context reduced to (%ld/%ld)"2342" to apply fragment at%d\n",2343 leading, trailing, applied_pos+1);2344update_image(img, applied_pos, &preimage, &postimage);2345}else{2346if(apply_verbosely)2347error("while searching for:\n%.*s",2348(int)(old - oldlines), oldlines);2349}23502351free(oldlines);2352free(newlines);2353free(preimage.line_allocated);2354free(postimage.line_allocated);23552356return(applied_pos <0);2357}23582359static intapply_binary_fragment(struct image *img,struct patch *patch)2360{2361struct fragment *fragment = patch->fragments;2362unsigned long len;2363void*dst;23642365/* Binary patch is irreversible without the optional second hunk */2366if(apply_in_reverse) {2367if(!fragment->next)2368returnerror("cannot reverse-apply a binary patch "2369"without the reverse hunk to '%s'",2370 patch->new_name2371? patch->new_name : patch->old_name);2372 fragment = fragment->next;2373}2374switch(fragment->binary_patch_method) {2375case BINARY_DELTA_DEFLATED:2376 dst =patch_delta(img->buf, img->len, fragment->patch,2377 fragment->size, &len);2378if(!dst)2379return-1;2380clear_image(img);2381 img->buf = dst;2382 img->len = len;2383return0;2384case BINARY_LITERAL_DEFLATED:2385clear_image(img);2386 img->len = fragment->size;2387 img->buf =xmalloc(img->len+1);2388memcpy(img->buf, fragment->patch, img->len);2389 img->buf[img->len] ='\0';2390return0;2391}2392return-1;2393}23942395static intapply_binary(struct image *img,struct patch *patch)2396{2397const char*name = patch->old_name ? patch->old_name : patch->new_name;2398unsigned char sha1[20];23992400/*2401 * For safety, we require patch index line to contain2402 * full 40-byte textual SHA1 for old and new, at least for now.2403 */2404if(strlen(patch->old_sha1_prefix) !=40||2405strlen(patch->new_sha1_prefix) !=40||2406get_sha1_hex(patch->old_sha1_prefix, sha1) ||2407get_sha1_hex(patch->new_sha1_prefix, sha1))2408returnerror("cannot apply binary patch to '%s' "2409"without full index line", name);24102411if(patch->old_name) {2412/*2413 * See if the old one matches what the patch2414 * applies to.2415 */2416hash_sha1_file(img->buf, img->len, blob_type, sha1);2417if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2418returnerror("the patch applies to '%s' (%s), "2419"which does not match the "2420"current contents.",2421 name,sha1_to_hex(sha1));2422}2423else{2424/* Otherwise, the old one must be empty. */2425if(img->len)2426returnerror("the patch applies to an empty "2427"'%s' but it is not empty", name);2428}24292430get_sha1_hex(patch->new_sha1_prefix, sha1);2431if(is_null_sha1(sha1)) {2432clear_image(img);2433return0;/* deletion patch */2434}24352436if(has_sha1_file(sha1)) {2437/* We already have the postimage */2438enum object_type type;2439unsigned long size;2440char*result;24412442 result =read_sha1_file(sha1, &type, &size);2443if(!result)2444returnerror("the necessary postimage%sfor "2445"'%s' cannot be read",2446 patch->new_sha1_prefix, name);2447clear_image(img);2448 img->buf = result;2449 img->len = size;2450}else{2451/*2452 * We have verified buf matches the preimage;2453 * apply the patch data to it, which is stored2454 * in the patch->fragments->{patch,size}.2455 */2456if(apply_binary_fragment(img, patch))2457returnerror("binary patch does not apply to '%s'",2458 name);24592460/* verify that the result matches */2461hash_sha1_file(img->buf, img->len, blob_type, sha1);2462if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2463returnerror("binary patch to '%s' creates incorrect result (expecting%s, got%s)",2464 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2465}24662467return0;2468}24692470static intapply_fragments(struct image *img,struct patch *patch)2471{2472struct fragment *frag = patch->fragments;2473const char*name = patch->old_name ? patch->old_name : patch->new_name;2474unsigned ws_rule = patch->ws_rule;2475unsigned inaccurate_eof = patch->inaccurate_eof;24762477if(patch->is_binary)2478returnapply_binary(img, patch);24792480while(frag) {2481if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule)) {2482error("patch failed:%s:%ld", name, frag->oldpos);2483if(!apply_with_reject)2484return-1;2485 frag->rejected =1;2486}2487 frag = frag->next;2488}2489return0;2490}24912492static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2493{2494if(!ce)2495return0;24962497if(S_ISGITLINK(ce->ce_mode)) {2498strbuf_grow(buf,100);2499strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2500}else{2501enum object_type type;2502unsigned long sz;2503char*result;25042505 result =read_sha1_file(ce->sha1, &type, &sz);2506if(!result)2507return-1;2508/* XXX read_sha1_file NUL-terminates */2509strbuf_attach(buf, result, sz, sz +1);2510}2511return0;2512}25132514static struct patch *in_fn_table(const char*name)2515{2516struct string_list_item *item;25172518if(name == NULL)2519return NULL;25202521 item =string_list_lookup(name, &fn_table);2522if(item != NULL)2523return(struct patch *)item->util;25242525return NULL;2526}25272528/*2529 * item->util in the filename table records the status of the path.2530 * Usually it points at a patch (whose result records the contents2531 * of it after applying it), but it could be PATH_WAS_DELETED for a2532 * path that a previously applied patch has already removed.2533 */2534#define PATH_TO_BE_DELETED ((struct patch *) -2)2535#define PATH_WAS_DELETED ((struct patch *) -1)25362537static intto_be_deleted(struct patch *patch)2538{2539return patch == PATH_TO_BE_DELETED;2540}25412542static intwas_deleted(struct patch *patch)2543{2544return patch == PATH_WAS_DELETED;2545}25462547static voidadd_to_fn_table(struct patch *patch)2548{2549struct string_list_item *item;25502551/*2552 * Always add new_name unless patch is a deletion2553 * This should cover the cases for normal diffs,2554 * file creations and copies2555 */2556if(patch->new_name != NULL) {2557 item =string_list_insert(patch->new_name, &fn_table);2558 item->util = patch;2559}25602561/*2562 * store a failure on rename/deletion cases because2563 * later chunks shouldn't patch old names2564 */2565if((patch->new_name == NULL) || (patch->is_rename)) {2566 item =string_list_insert(patch->old_name, &fn_table);2567 item->util = PATH_WAS_DELETED;2568}2569}25702571static voidprepare_fn_table(struct patch *patch)2572{2573/*2574 * store information about incoming file deletion2575 */2576while(patch) {2577if((patch->new_name == NULL) || (patch->is_rename)) {2578struct string_list_item *item;2579 item =string_list_insert(patch->old_name, &fn_table);2580 item->util = PATH_TO_BE_DELETED;2581}2582 patch = patch->next;2583}2584}25852586static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)2587{2588struct strbuf buf = STRBUF_INIT;2589struct image image;2590size_t len;2591char*img;2592struct patch *tpatch;25932594if(!(patch->is_copy || patch->is_rename) &&2595(tpatch =in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {2596if(was_deleted(tpatch)) {2597returnerror("patch%shas been renamed/deleted",2598 patch->old_name);2599}2600/* We have a patched copy in memory use that */2601strbuf_add(&buf, tpatch->result, tpatch->resultsize);2602}else if(cached) {2603if(read_file_or_gitlink(ce, &buf))2604returnerror("read of%sfailed", patch->old_name);2605}else if(patch->old_name) {2606if(S_ISGITLINK(patch->old_mode)) {2607if(ce) {2608read_file_or_gitlink(ce, &buf);2609}else{2610/*2611 * There is no way to apply subproject2612 * patch without looking at the index.2613 */2614 patch->fragments = NULL;2615}2616}else{2617if(read_old_data(st, patch->old_name, &buf))2618returnerror("read of%sfailed", patch->old_name);2619}2620}26212622 img =strbuf_detach(&buf, &len);2623prepare_image(&image, img, len, !patch->is_binary);26242625if(apply_fragments(&image, patch) <0)2626return-1;/* note with --reject this succeeds. */2627 patch->result = image.buf;2628 patch->resultsize = image.len;2629add_to_fn_table(patch);2630free(image.line_allocated);26312632if(0< patch->is_delete && patch->resultsize)2633returnerror("removal patch leaves file contents");26342635return0;2636}26372638static intcheck_to_create_blob(const char*new_name,int ok_if_exists)2639{2640struct stat nst;2641if(!lstat(new_name, &nst)) {2642if(S_ISDIR(nst.st_mode) || ok_if_exists)2643return0;2644/*2645 * A leading component of new_name might be a symlink2646 * that is going to be removed with this patch, but2647 * still pointing at somewhere that has the path.2648 * In such a case, path "new_name" does not exist as2649 * far as git is concerned.2650 */2651if(has_symlink_leading_path(new_name,strlen(new_name)))2652return0;26532654returnerror("%s: already exists in working directory", new_name);2655}2656else if((errno != ENOENT) && (errno != ENOTDIR))2657returnerror("%s:%s", new_name,strerror(errno));2658return0;2659}26602661static intverify_index_match(struct cache_entry *ce,struct stat *st)2662{2663if(S_ISGITLINK(ce->ce_mode)) {2664if(!S_ISDIR(st->st_mode))2665return-1;2666return0;2667}2668returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID);2669}26702671static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)2672{2673const char*old_name = patch->old_name;2674struct patch *tpatch = NULL;2675int stat_ret =0;2676unsigned st_mode =0;26772678/*2679 * Make sure that we do not have local modifications from the2680 * index when we are looking at the index. Also make sure2681 * we have the preimage file to be patched in the work tree,2682 * unless --cached, which tells git to apply only in the index.2683 */2684if(!old_name)2685return0;26862687assert(patch->is_new <=0);26882689if(!(patch->is_copy || patch->is_rename) &&2690(tpatch =in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {2691if(was_deleted(tpatch))2692returnerror("%s: has been deleted/renamed", old_name);2693 st_mode = tpatch->new_mode;2694}else if(!cached) {2695 stat_ret =lstat(old_name, st);2696if(stat_ret && errno != ENOENT)2697returnerror("%s:%s", old_name,strerror(errno));2698}26992700if(to_be_deleted(tpatch))2701 tpatch = NULL;27022703if(check_index && !tpatch) {2704int pos =cache_name_pos(old_name,strlen(old_name));2705if(pos <0) {2706if(patch->is_new <0)2707goto is_new;2708returnerror("%s: does not exist in index", old_name);2709}2710*ce = active_cache[pos];2711if(stat_ret <0) {2712struct checkout costate;2713/* checkout */2714 costate.base_dir ="";2715 costate.base_dir_len =0;2716 costate.force =0;2717 costate.quiet =0;2718 costate.not_new =0;2719 costate.refresh_cache =1;2720if(checkout_entry(*ce, &costate, NULL) ||2721lstat(old_name, st))2722return-1;2723}2724if(!cached &&verify_index_match(*ce, st))2725returnerror("%s: does not match index", old_name);2726if(cached)2727 st_mode = (*ce)->ce_mode;2728}else if(stat_ret <0) {2729if(patch->is_new <0)2730goto is_new;2731returnerror("%s:%s", old_name,strerror(errno));2732}27332734if(!cached && !tpatch)2735 st_mode =ce_mode_from_stat(*ce, st->st_mode);27362737if(patch->is_new <0)2738 patch->is_new =0;2739if(!patch->old_mode)2740 patch->old_mode = st_mode;2741if((st_mode ^ patch->old_mode) & S_IFMT)2742returnerror("%s: wrong type", old_name);2743if(st_mode != patch->old_mode)2744warning("%shas type%o, expected%o",2745 old_name, st_mode, patch->old_mode);2746if(!patch->new_mode && !patch->is_delete)2747 patch->new_mode = st_mode;2748return0;27492750 is_new:2751 patch->is_new =1;2752 patch->is_delete =0;2753 patch->old_name = NULL;2754return0;2755}27562757static intcheck_patch(struct patch *patch)2758{2759struct stat st;2760const char*old_name = patch->old_name;2761const char*new_name = patch->new_name;2762const char*name = old_name ? old_name : new_name;2763struct cache_entry *ce = NULL;2764struct patch *tpatch;2765int ok_if_exists;2766int status;27672768 patch->rejected =1;/* we will drop this after we succeed */27692770 status =check_preimage(patch, &ce, &st);2771if(status)2772return status;2773 old_name = patch->old_name;27742775if((tpatch =in_fn_table(new_name)) &&2776(was_deleted(tpatch) ||to_be_deleted(tpatch)))2777/*2778 * A type-change diff is always split into a patch to2779 * delete old, immediately followed by a patch to2780 * create new (see diff.c::run_diff()); in such a case2781 * it is Ok that the entry to be deleted by the2782 * previous patch is still in the working tree and in2783 * the index.2784 */2785 ok_if_exists =1;2786else2787 ok_if_exists =0;27882789if(new_name &&2790((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {2791if(check_index &&2792cache_name_pos(new_name,strlen(new_name)) >=0&&2793!ok_if_exists)2794returnerror("%s: already exists in index", new_name);2795if(!cached) {2796int err =check_to_create_blob(new_name, ok_if_exists);2797if(err)2798return err;2799}2800if(!patch->new_mode) {2801if(0< patch->is_new)2802 patch->new_mode = S_IFREG |0644;2803else2804 patch->new_mode = patch->old_mode;2805}2806}28072808if(new_name && old_name) {2809int same = !strcmp(old_name, new_name);2810if(!patch->new_mode)2811 patch->new_mode = patch->old_mode;2812if((patch->old_mode ^ patch->new_mode) & S_IFMT)2813returnerror("new mode (%o) of%sdoes not match old mode (%o)%s%s",2814 patch->new_mode, new_name, patch->old_mode,2815 same ?"":" of ", same ?"": old_name);2816}28172818if(apply_data(patch, &st, ce) <0)2819returnerror("%s: patch does not apply", name);2820 patch->rejected =0;2821return0;2822}28232824static intcheck_patch_list(struct patch *patch)2825{2826int err =0;28272828prepare_fn_table(patch);2829while(patch) {2830if(apply_verbosely)2831say_patch_name(stderr,2832"Checking patch ", patch,"...\n");2833 err |=check_patch(patch);2834 patch = patch->next;2835}2836return err;2837}28382839/* This function tries to read the sha1 from the current index */2840static intget_current_sha1(const char*path,unsigned char*sha1)2841{2842int pos;28432844if(read_cache() <0)2845return-1;2846 pos =cache_name_pos(path,strlen(path));2847if(pos <0)2848return-1;2849hashcpy(sha1, active_cache[pos]->sha1);2850return0;2851}28522853/* Build an index that contains the just the files needed for a 3way merge */2854static voidbuild_fake_ancestor(struct patch *list,const char*filename)2855{2856struct patch *patch;2857struct index_state result = { NULL };2858int fd;28592860/* Once we start supporting the reverse patch, it may be2861 * worth showing the new sha1 prefix, but until then...2862 */2863for(patch = list; patch; patch = patch->next) {2864const unsigned char*sha1_ptr;2865unsigned char sha1[20];2866struct cache_entry *ce;2867const char*name;28682869 name = patch->old_name ? patch->old_name : patch->new_name;2870if(0< patch->is_new)2871continue;2872else if(get_sha1(patch->old_sha1_prefix, sha1))2873/* git diff has no index line for mode/type changes */2874if(!patch->lines_added && !patch->lines_deleted) {2875if(get_current_sha1(patch->new_name, sha1) ||2876get_current_sha1(patch->old_name, sha1))2877die("mode change for%s, which is not "2878"in current HEAD", name);2879 sha1_ptr = sha1;2880}else2881die("sha1 information is lacking or useless "2882"(%s).", name);2883else2884 sha1_ptr = sha1;28852886 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);2887if(!ce)2888die("make_cache_entry failed for path '%s'", name);2889if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))2890die("Could not add%sto temporary index", name);2891}28922893 fd =open(filename, O_WRONLY | O_CREAT,0666);2894if(fd <0||write_index(&result, fd) ||close(fd))2895die("Could not write temporary index to%s", filename);28962897discard_index(&result);2898}28992900static voidstat_patch_list(struct patch *patch)2901{2902int files, adds, dels;29032904for(files = adds = dels =0; patch ; patch = patch->next) {2905 files++;2906 adds += patch->lines_added;2907 dels += patch->lines_deleted;2908show_stats(patch);2909}29102911printf("%dfiles changed,%dinsertions(+),%ddeletions(-)\n", files, adds, dels);2912}29132914static voidnumstat_patch_list(struct patch *patch)2915{2916for( ; patch; patch = patch->next) {2917const char*name;2918 name = patch->new_name ? patch->new_name : patch->old_name;2919if(patch->is_binary)2920printf("-\t-\t");2921else2922printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);2923write_name_quoted(name, stdout, line_termination);2924}2925}29262927static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)2928{2929if(mode)2930printf("%smode%06o%s\n", newdelete, mode, name);2931else2932printf("%s %s\n", newdelete, name);2933}29342935static voidshow_mode_change(struct patch *p,int show_name)2936{2937if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {2938if(show_name)2939printf(" mode change%06o =>%06o%s\n",2940 p->old_mode, p->new_mode, p->new_name);2941else2942printf(" mode change%06o =>%06o\n",2943 p->old_mode, p->new_mode);2944}2945}29462947static voidshow_rename_copy(struct patch *p)2948{2949const char*renamecopy = p->is_rename ?"rename":"copy";2950const char*old, *new;29512952/* Find common prefix */2953 old = p->old_name;2954new= p->new_name;2955while(1) {2956const char*slash_old, *slash_new;2957 slash_old =strchr(old,'/');2958 slash_new =strchr(new,'/');2959if(!slash_old ||2960!slash_new ||2961 slash_old - old != slash_new -new||2962memcmp(old,new, slash_new -new))2963break;2964 old = slash_old +1;2965new= slash_new +1;2966}2967/* p->old_name thru old is the common prefix, and old and new2968 * through the end of names are renames2969 */2970if(old != p->old_name)2971printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,2972(int)(old - p->old_name), p->old_name,2973 old,new, p->score);2974else2975printf("%s %s=>%s(%d%%)\n", renamecopy,2976 p->old_name, p->new_name, p->score);2977show_mode_change(p,0);2978}29792980static voidsummary_patch_list(struct patch *patch)2981{2982struct patch *p;29832984for(p = patch; p; p = p->next) {2985if(p->is_new)2986show_file_mode_name("create", p->new_mode, p->new_name);2987else if(p->is_delete)2988show_file_mode_name("delete", p->old_mode, p->old_name);2989else{2990if(p->is_rename || p->is_copy)2991show_rename_copy(p);2992else{2993if(p->score) {2994printf(" rewrite%s(%d%%)\n",2995 p->new_name, p->score);2996show_mode_change(p,0);2997}2998else2999show_mode_change(p,1);3000}3001}3002}3003}30043005static voidpatch_stats(struct patch *patch)3006{3007int lines = patch->lines_added + patch->lines_deleted;30083009if(lines > max_change)3010 max_change = lines;3011if(patch->old_name) {3012int len =quote_c_style(patch->old_name, NULL, NULL,0);3013if(!len)3014 len =strlen(patch->old_name);3015if(len > max_len)3016 max_len = len;3017}3018if(patch->new_name) {3019int len =quote_c_style(patch->new_name, NULL, NULL,0);3020if(!len)3021 len =strlen(patch->new_name);3022if(len > max_len)3023 max_len = len;3024}3025}30263027static voidremove_file(struct patch *patch,int rmdir_empty)3028{3029if(update_index) {3030if(remove_file_from_cache(patch->old_name) <0)3031die("unable to remove%sfrom index", patch->old_name);3032}3033if(!cached) {3034if(S_ISGITLINK(patch->old_mode)) {3035if(rmdir(patch->old_name))3036warning("unable to remove submodule%s",3037 patch->old_name);3038}else if(!unlink_or_warn(patch->old_name) && rmdir_empty) {3039remove_path(patch->old_name);3040}3041}3042}30433044static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)3045{3046struct stat st;3047struct cache_entry *ce;3048int namelen =strlen(path);3049unsigned ce_size =cache_entry_size(namelen);30503051if(!update_index)3052return;30533054 ce =xcalloc(1, ce_size);3055memcpy(ce->name, path, namelen);3056 ce->ce_mode =create_ce_mode(mode);3057 ce->ce_flags = namelen;3058if(S_ISGITLINK(mode)) {3059const char*s = buf;30603061if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))3062die("corrupt patch for subproject%s", path);3063}else{3064if(!cached) {3065if(lstat(path, &st) <0)3066die_errno("unable to stat newly created file '%s'",3067 path);3068fill_stat_cache_info(ce, &st);3069}3070if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)3071die("unable to create backing store for newly created file%s", path);3072}3073if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3074die("unable to add cache entry for%s", path);3075}30763077static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)3078{3079int fd;3080struct strbuf nbuf = STRBUF_INIT;30813082if(S_ISGITLINK(mode)) {3083struct stat st;3084if(!lstat(path, &st) &&S_ISDIR(st.st_mode))3085return0;3086returnmkdir(path,0777);3087}30883089if(has_symlinks &&S_ISLNK(mode))3090/* Although buf:size is counted string, it also is NUL3091 * terminated.3092 */3093returnsymlink(buf, path);30943095 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);3096if(fd <0)3097return-1;30983099if(convert_to_working_tree(path, buf, size, &nbuf)) {3100 size = nbuf.len;3101 buf = nbuf.buf;3102}3103write_or_die(fd, buf, size);3104strbuf_release(&nbuf);31053106if(close(fd) <0)3107die_errno("closing file '%s'", path);3108return0;3109}31103111/*3112 * We optimistically assume that the directories exist,3113 * which is true 99% of the time anyway. If they don't,3114 * we create them and try again.3115 */3116static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)3117{3118if(cached)3119return;3120if(!try_create_file(path, mode, buf, size))3121return;31223123if(errno == ENOENT) {3124if(safe_create_leading_directories(path))3125return;3126if(!try_create_file(path, mode, buf, size))3127return;3128}31293130if(errno == EEXIST || errno == EACCES) {3131/* We may be trying to create a file where a directory3132 * used to be.3133 */3134struct stat st;3135if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))3136 errno = EEXIST;3137}31383139if(errno == EEXIST) {3140unsigned int nr =getpid();31413142for(;;) {3143char newpath[PATH_MAX];3144mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);3145if(!try_create_file(newpath, mode, buf, size)) {3146if(!rename(newpath, path))3147return;3148unlink_or_warn(newpath);3149break;3150}3151if(errno != EEXIST)3152break;3153++nr;3154}3155}3156die_errno("unable to write file '%s' mode%o", path, mode);3157}31583159static voidcreate_file(struct patch *patch)3160{3161char*path = patch->new_name;3162unsigned mode = patch->new_mode;3163unsigned long size = patch->resultsize;3164char*buf = patch->result;31653166if(!mode)3167 mode = S_IFREG |0644;3168create_one_file(path, mode, buf, size);3169add_index_file(path, mode, buf, size);3170}31713172/* phase zero is to remove, phase one is to create */3173static voidwrite_out_one_result(struct patch *patch,int phase)3174{3175if(patch->is_delete >0) {3176if(phase ==0)3177remove_file(patch,1);3178return;3179}3180if(patch->is_new >0|| patch->is_copy) {3181if(phase ==1)3182create_file(patch);3183return;3184}3185/*3186 * Rename or modification boils down to the same3187 * thing: remove the old, write the new3188 */3189if(phase ==0)3190remove_file(patch, patch->is_rename);3191if(phase ==1)3192create_file(patch);3193}31943195static intwrite_out_one_reject(struct patch *patch)3196{3197FILE*rej;3198char namebuf[PATH_MAX];3199struct fragment *frag;3200int cnt =0;32013202for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {3203if(!frag->rejected)3204continue;3205 cnt++;3206}32073208if(!cnt) {3209if(apply_verbosely)3210say_patch_name(stderr,3211"Applied patch ", patch," cleanly.\n");3212return0;3213}32143215/* This should not happen, because a removal patch that leaves3216 * contents are marked "rejected" at the patch level.3217 */3218if(!patch->new_name)3219die("internal error");32203221/* Say this even without --verbose */3222say_patch_name(stderr,"Applying patch ", patch," with");3223fprintf(stderr,"%drejects...\n", cnt);32243225 cnt =strlen(patch->new_name);3226if(ARRAY_SIZE(namebuf) <= cnt +5) {3227 cnt =ARRAY_SIZE(namebuf) -5;3228warning("truncating .rej filename to %.*s.rej",3229 cnt -1, patch->new_name);3230}3231memcpy(namebuf, patch->new_name, cnt);3232memcpy(namebuf + cnt,".rej",5);32333234 rej =fopen(namebuf,"w");3235if(!rej)3236returnerror("cannot open%s:%s", namebuf,strerror(errno));32373238/* Normal git tools never deal with .rej, so do not pretend3239 * this is a git patch by saying --git nor give extended3240 * headers. While at it, maybe please "kompare" that wants3241 * the trailing TAB and some garbage at the end of line ;-).3242 */3243fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",3244 patch->new_name, patch->new_name);3245for(cnt =1, frag = patch->fragments;3246 frag;3247 cnt++, frag = frag->next) {3248if(!frag->rejected) {3249fprintf(stderr,"Hunk #%dapplied cleanly.\n", cnt);3250continue;3251}3252fprintf(stderr,"Rejected hunk #%d.\n", cnt);3253fprintf(rej,"%.*s", frag->size, frag->patch);3254if(frag->patch[frag->size-1] !='\n')3255fputc('\n', rej);3256}3257fclose(rej);3258return-1;3259}32603261static intwrite_out_results(struct patch *list,int skipped_patch)3262{3263int phase;3264int errs =0;3265struct patch *l;32663267if(!list && !skipped_patch)3268returnerror("No changes");32693270for(phase =0; phase <2; phase++) {3271 l = list;3272while(l) {3273if(l->rejected)3274 errs =1;3275else{3276write_out_one_result(l, phase);3277if(phase ==1&&write_out_one_reject(l))3278 errs =1;3279}3280 l = l->next;3281}3282}3283return errs;3284}32853286static struct lock_file lock_file;32873288static struct string_list limit_by_name;3289static int has_include;3290static voidadd_name_limit(const char*name,int exclude)3291{3292struct string_list_item *it;32933294 it =string_list_append(name, &limit_by_name);3295 it->util = exclude ? NULL : (void*)1;3296}32973298static intuse_patch(struct patch *p)3299{3300const char*pathname = p->new_name ? p->new_name : p->old_name;3301int i;33023303/* Paths outside are not touched regardless of "--include" */3304if(0< prefix_length) {3305int pathlen =strlen(pathname);3306if(pathlen <= prefix_length ||3307memcmp(prefix, pathname, prefix_length))3308return0;3309}33103311/* See if it matches any of exclude/include rule */3312for(i =0; i < limit_by_name.nr; i++) {3313struct string_list_item *it = &limit_by_name.items[i];3314if(!fnmatch(it->string, pathname,0))3315return(it->util != NULL);3316}33173318/*3319 * If we had any include, a path that does not match any rule is3320 * not used. Otherwise, we saw bunch of exclude rules (or none)3321 * and such a path is used.3322 */3323return!has_include;3324}332533263327static voidprefix_one(char**name)3328{3329char*old_name = *name;3330if(!old_name)3331return;3332*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3333free(old_name);3334}33353336static voidprefix_patches(struct patch *p)3337{3338if(!prefix || p->is_toplevel_relative)3339return;3340for( ; p; p = p->next) {3341if(p->new_name == p->old_name) {3342char*prefixed = p->new_name;3343prefix_one(&prefixed);3344 p->new_name = p->old_name = prefixed;3345}3346else{3347prefix_one(&p->new_name);3348prefix_one(&p->old_name);3349}3350}3351}33523353#define INACCURATE_EOF (1<<0)3354#define RECOUNT (1<<1)33553356static intapply_patch(int fd,const char*filename,int options)3357{3358size_t offset;3359struct strbuf buf = STRBUF_INIT;3360struct patch *list = NULL, **listp = &list;3361int skipped_patch =0;33623363/* FIXME - memory leak when using multiple patch files as inputs */3364memset(&fn_table,0,sizeof(struct string_list));3365 patch_input_file = filename;3366read_patch_file(&buf, fd);3367 offset =0;3368while(offset < buf.len) {3369struct patch *patch;3370int nr;33713372 patch =xcalloc(1,sizeof(*patch));3373 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3374 patch->recount = !!(options & RECOUNT);3375 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3376if(nr <0)3377break;3378if(apply_in_reverse)3379reverse_patches(patch);3380if(prefix)3381prefix_patches(patch);3382if(use_patch(patch)) {3383patch_stats(patch);3384*listp = patch;3385 listp = &patch->next;3386}3387else{3388/* perhaps free it a bit better? */3389free(patch);3390 skipped_patch++;3391}3392 offset += nr;3393}33943395if(whitespace_error && (ws_error_action == die_on_ws_error))3396 apply =0;33973398 update_index = check_index && apply;3399if(update_index && newfd <0)3400 newfd =hold_locked_index(&lock_file,1);34013402if(check_index) {3403if(read_cache() <0)3404die("unable to read index file");3405}34063407if((check || apply) &&3408check_patch_list(list) <0&&3409!apply_with_reject)3410exit(1);34113412if(apply &&write_out_results(list, skipped_patch))3413exit(1);34143415if(fake_ancestor)3416build_fake_ancestor(list, fake_ancestor);34173418if(diffstat)3419stat_patch_list(list);34203421if(numstat)3422numstat_patch_list(list);34233424if(summary)3425summary_patch_list(list);34263427strbuf_release(&buf);3428return0;3429}34303431static intgit_apply_config(const char*var,const char*value,void*cb)3432{3433if(!strcmp(var,"apply.whitespace"))3434returngit_config_string(&apply_default_whitespace, var, value);3435else if(!strcmp(var,"apply.ignorewhitespace"))3436returngit_config_string(&apply_default_ignorewhitespace, var, value);3437returngit_default_config(var, value, cb);3438}34393440static intoption_parse_exclude(const struct option *opt,3441const char*arg,int unset)3442{3443add_name_limit(arg,1);3444return0;3445}34463447static intoption_parse_include(const struct option *opt,3448const char*arg,int unset)3449{3450add_name_limit(arg,0);3451 has_include =1;3452return0;3453}34543455static intoption_parse_p(const struct option *opt,3456const char*arg,int unset)3457{3458 p_value =atoi(arg);3459 p_value_known =1;3460return0;3461}34623463static intoption_parse_z(const struct option *opt,3464const char*arg,int unset)3465{3466if(unset)3467 line_termination ='\n';3468else3469 line_termination =0;3470return0;3471}34723473static intoption_parse_space_change(const struct option *opt,3474const char*arg,int unset)3475{3476if(unset)3477 ws_ignore_action = ignore_ws_none;3478else3479 ws_ignore_action = ignore_ws_change;3480return0;3481}34823483static intoption_parse_whitespace(const struct option *opt,3484const char*arg,int unset)3485{3486const char**whitespace_option = opt->value;34873488*whitespace_option = arg;3489parse_whitespace_option(arg);3490return0;3491}34923493static intoption_parse_directory(const struct option *opt,3494const char*arg,int unset)3495{3496 root_len =strlen(arg);3497if(root_len && arg[root_len -1] !='/') {3498char*new_root;3499 root = new_root =xmalloc(root_len +2);3500strcpy(new_root, arg);3501strcpy(new_root + root_len++,"/");3502}else3503 root = arg;3504return0;3505}35063507intcmd_apply(int argc,const char**argv,const char*unused_prefix)3508{3509int i;3510int errs =0;3511int is_not_gitdir;3512int binary;3513int force_apply =0;35143515const char*whitespace_option = NULL;35163517struct option builtin_apply_options[] = {3518{ OPTION_CALLBACK,0,"exclude", NULL,"path",3519"don't apply changes matching the given path",35200, option_parse_exclude },3521{ OPTION_CALLBACK,0,"include", NULL,"path",3522"apply changes matching the given path",35230, option_parse_include },3524{ OPTION_CALLBACK,'p', NULL, NULL,"num",3525"remove <num> leading slashes from traditional diff paths",35260, option_parse_p },3527OPT_BOOLEAN(0,"no-add", &no_add,3528"ignore additions made by the patch"),3529OPT_BOOLEAN(0,"stat", &diffstat,3530"instead of applying the patch, output diffstat for the input"),3531{ OPTION_BOOLEAN,0,"allow-binary-replacement", &binary,3532 NULL,"old option, now no-op",3533 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3534{ OPTION_BOOLEAN,0,"binary", &binary,3535 NULL,"old option, now no-op",3536 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3537OPT_BOOLEAN(0,"numstat", &numstat,3538"shows number of added and deleted lines in decimal notation"),3539OPT_BOOLEAN(0,"summary", &summary,3540"instead of applying the patch, output a summary for the input"),3541OPT_BOOLEAN(0,"check", &check,3542"instead of applying the patch, see if the patch is applicable"),3543OPT_BOOLEAN(0,"index", &check_index,3544"make sure the patch is applicable to the current index"),3545OPT_BOOLEAN(0,"cached", &cached,3546"apply a patch without touching the working tree"),3547OPT_BOOLEAN(0,"apply", &force_apply,3548"also apply the patch (use with --stat/--summary/--check)"),3549OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,3550"build a temporary index based on embedded index information"),3551{ OPTION_CALLBACK,'z', NULL, NULL, NULL,3552"paths are separated with NUL character",3553 PARSE_OPT_NOARG, option_parse_z },3554OPT_INTEGER('C', NULL, &p_context,3555"ensure at least <n> lines of context match"),3556{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,"action",3557"detect new or modified lines that have whitespace errors",35580, option_parse_whitespace },3559{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,3560"ignore changes in whitespace when finding context",3561 PARSE_OPT_NOARG, option_parse_space_change },3562{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,3563"ignore changes in whitespace when finding context",3564 PARSE_OPT_NOARG, option_parse_space_change },3565OPT_BOOLEAN('R',"reverse", &apply_in_reverse,3566"apply the patch in reverse"),3567OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,3568"don't expect at least one line of context"),3569OPT_BOOLEAN(0,"reject", &apply_with_reject,3570"leave the rejected hunks in corresponding *.rej files"),3571OPT__VERBOSE(&apply_verbosely),3572OPT_BIT(0,"inaccurate-eof", &options,3573"tolerate incorrectly detected missing new-line at the end of file",3574 INACCURATE_EOF),3575OPT_BIT(0,"recount", &options,3576"do not trust the line counts in the hunk headers",3577 RECOUNT),3578{ OPTION_CALLBACK,0,"directory", NULL,"root",3579"prepend <root> to all filenames",35800, option_parse_directory },3581OPT_END()3582};35833584 prefix =setup_git_directory_gently(&is_not_gitdir);3585 prefix_length = prefix ?strlen(prefix) :0;3586git_config(git_apply_config, NULL);3587if(apply_default_whitespace)3588parse_whitespace_option(apply_default_whitespace);3589if(apply_default_ignorewhitespace)3590parse_ignorewhitespace_option(apply_default_ignorewhitespace);35913592 argc =parse_options(argc, argv, prefix, builtin_apply_options,3593 apply_usage,0);35943595if(apply_with_reject)3596 apply = apply_verbosely =1;3597if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))3598 apply =0;3599if(check_index && is_not_gitdir)3600die("--index outside a repository");3601if(cached) {3602if(is_not_gitdir)3603die("--cached outside a repository");3604 check_index =1;3605}3606for(i =0; i < argc; i++) {3607const char*arg = argv[i];3608int fd;36093610if(!strcmp(arg,"-")) {3611 errs |=apply_patch(0,"<stdin>", options);3612 read_stdin =0;3613continue;3614}else if(0< prefix_length)3615 arg =prefix_filename(prefix, prefix_length, arg);36163617 fd =open(arg, O_RDONLY);3618if(fd <0)3619die_errno("can't open patch '%s'", arg);3620 read_stdin =0;3621set_default_whitespace_mode(whitespace_option);3622 errs |=apply_patch(fd, arg, options);3623close(fd);3624}3625set_default_whitespace_mode(whitespace_option);3626if(read_stdin)3627 errs |=apply_patch(0,"<stdin>", options);3628if(whitespace_error) {3629if(squelch_whitespace_errors &&3630 squelch_whitespace_errors < whitespace_error) {3631int squelched =3632 whitespace_error - squelch_whitespace_errors;3633warning("squelched%d"3634"whitespace error%s",3635 squelched,3636 squelched ==1?"":"s");3637}3638if(ws_error_action == die_on_ws_error)3639die("%dline%sadd%swhitespace errors.",3640 whitespace_error,3641 whitespace_error ==1?"":"s",3642 whitespace_error ==1?"s":"");3643if(applied_after_fixing_ws && apply)3644warning("%dline%sapplied after"3645" fixing whitespace errors.",3646 applied_after_fixing_ws,3647 applied_after_fixing_ws ==1?"":"s");3648else if(whitespace_error)3649warning("%dline%sadd%swhitespace errors.",3650 whitespace_error,3651 whitespace_error ==1?"":"s",3652 whitespace_error ==1?"s":"");3653}36543655if(update_index) {3656if(write_cache(newfd, active_cache, active_nr) ||3657commit_locked_index(&lock_file))3658die("Unable to write new index file");3659}36603661return!!errs;3662}