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 407if(!name) 408return NULL; 409 410while(name[i]) { 411if((name[j++] = name[i++]) =='/') 412while(name[i] =='/') 413 i++; 414} 415 name[j] ='\0'; 416return name; 417} 418 419static char*find_name(const char*line,char*def,int p_value,int terminate) 420{ 421int len; 422const char*start = NULL; 423 424if(p_value ==0) 425 start = line; 426 427if(*line =='"') { 428struct strbuf name = STRBUF_INIT; 429 430/* 431 * Proposed "new-style" GNU patch/diff format; see 432 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2 433 */ 434if(!unquote_c_style(&name, line, NULL)) { 435char*cp; 436 437for(cp = name.buf; p_value; p_value--) { 438 cp =strchr(cp,'/'); 439if(!cp) 440break; 441 cp++; 442} 443if(cp) { 444/* name can later be freed, so we need 445 * to memmove, not just return cp 446 */ 447strbuf_remove(&name,0, cp - name.buf); 448free(def); 449if(root) 450strbuf_insert(&name,0, root, root_len); 451returnsquash_slash(strbuf_detach(&name, NULL)); 452} 453} 454strbuf_release(&name); 455} 456 457for(;;) { 458char c = *line; 459 460if(isspace(c)) { 461if(c =='\n') 462break; 463if(name_terminate(start, line-start, c, terminate)) 464break; 465} 466 line++; 467if(c =='/'&& !--p_value) 468 start = line; 469} 470if(!start) 471returnsquash_slash(def); 472 len = line - start; 473if(!len) 474returnsquash_slash(def); 475 476/* 477 * Generally we prefer the shorter name, especially 478 * if the other one is just a variation of that with 479 * something else tacked on to the end (ie "file.orig" 480 * or "file~"). 481 */ 482if(def) { 483int deflen =strlen(def); 484if(deflen < len && !strncmp(start, def, deflen)) 485returnsquash_slash(def); 486free(def); 487} 488 489if(root) { 490char*ret =xmalloc(root_len + len +1); 491strcpy(ret, root); 492memcpy(ret + root_len, start, len); 493 ret[root_len + len] ='\0'; 494returnsquash_slash(ret); 495} 496 497returnsquash_slash(xmemdupz(start, len)); 498} 499 500static intcount_slashes(const char*cp) 501{ 502int cnt =0; 503char ch; 504 505while((ch = *cp++)) 506if(ch =='/') 507 cnt++; 508return cnt; 509} 510 511/* 512 * Given the string after "--- " or "+++ ", guess the appropriate 513 * p_value for the given patch. 514 */ 515static intguess_p_value(const char*nameline) 516{ 517char*name, *cp; 518int val = -1; 519 520if(is_dev_null(nameline)) 521return-1; 522 name =find_name(nameline, NULL,0, TERM_SPACE | TERM_TAB); 523if(!name) 524return-1; 525 cp =strchr(name,'/'); 526if(!cp) 527 val =0; 528else if(prefix) { 529/* 530 * Does it begin with "a/$our-prefix" and such? Then this is 531 * very likely to apply to our directory. 532 */ 533if(!strncmp(name, prefix, prefix_length)) 534 val =count_slashes(prefix); 535else{ 536 cp++; 537if(!strncmp(cp, prefix, prefix_length)) 538 val =count_slashes(prefix) +1; 539} 540} 541free(name); 542return val; 543} 544 545/* 546 * Does the ---/+++ line has the POSIX timestamp after the last HT? 547 * GNU diff puts epoch there to signal a creation/deletion event. Is 548 * this such a timestamp? 549 */ 550static inthas_epoch_timestamp(const char*nameline) 551{ 552/* 553 * We are only interested in epoch timestamp; any non-zero 554 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 555 * For the same reason, the date must be either 1969-12-31 or 556 * 1970-01-01, and the seconds part must be "00". 557 */ 558const char stamp_regexp[] = 559"^(1969-12-31|1970-01-01)" 560" " 561"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 562" " 563"([-+][0-2][0-9][0-5][0-9])\n"; 564const char*timestamp = NULL, *cp; 565static regex_t *stamp; 566 regmatch_t m[10]; 567int zoneoffset; 568int hourminute; 569int status; 570 571for(cp = nameline; *cp !='\n'; cp++) { 572if(*cp =='\t') 573 timestamp = cp +1; 574} 575if(!timestamp) 576return0; 577if(!stamp) { 578 stamp =xmalloc(sizeof(*stamp)); 579if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 580warning("Cannot prepare timestamp regexp%s", 581 stamp_regexp); 582return0; 583} 584} 585 586 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 587if(status) { 588if(status != REG_NOMATCH) 589warning("regexec returned%dfor input:%s", 590 status, timestamp); 591return0; 592} 593 594 zoneoffset =strtol(timestamp + m[3].rm_so +1, NULL,10); 595 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 596if(timestamp[m[3].rm_so] =='-') 597 zoneoffset = -zoneoffset; 598 599/* 600 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 601 * (west of GMT) or 1970-01-01 (east of GMT) 602 */ 603if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 604(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 605return0; 606 607 hourminute = (strtol(timestamp +11, NULL,10) *60+ 608strtol(timestamp +14, NULL,10) - 609 zoneoffset); 610 611return((zoneoffset <0&& hourminute ==1440) || 612(0<= zoneoffset && !hourminute)); 613} 614 615/* 616 * Get the name etc info from the ---/+++ lines of a traditional patch header 617 * 618 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 619 * files, we can happily check the index for a match, but for creating a 620 * new file we should try to match whatever "patch" does. I have no idea. 621 */ 622static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 623{ 624char*name; 625 626 first +=4;/* skip "--- " */ 627 second +=4;/* skip "+++ " */ 628if(!p_value_known) { 629int p, q; 630 p =guess_p_value(first); 631 q =guess_p_value(second); 632if(p <0) p = q; 633if(0<= p && p == q) { 634 p_value = p; 635 p_value_known =1; 636} 637} 638if(is_dev_null(first)) { 639 patch->is_new =1; 640 patch->is_delete =0; 641 name =find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB); 642 patch->new_name = name; 643}else if(is_dev_null(second)) { 644 patch->is_new =0; 645 patch->is_delete =1; 646 name =find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB); 647 patch->old_name = name; 648}else{ 649 name =find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB); 650 name =find_name(second, name, p_value, TERM_SPACE | TERM_TAB); 651if(has_epoch_timestamp(first)) { 652 patch->is_new =1; 653 patch->is_delete =0; 654 patch->new_name = name; 655}else if(has_epoch_timestamp(second)) { 656 patch->is_new =0; 657 patch->is_delete =1; 658 patch->old_name = name; 659}else{ 660 patch->old_name = patch->new_name = name; 661} 662} 663if(!name) 664die("unable to find filename in patch at line%d", linenr); 665} 666 667static intgitdiff_hdrend(const char*line,struct patch *patch) 668{ 669return-1; 670} 671 672/* 673 * We're anal about diff header consistency, to make 674 * sure that we don't end up having strange ambiguous 675 * patches floating around. 676 * 677 * As a result, gitdiff_{old|new}name() will check 678 * their names against any previous information, just 679 * to make sure.. 680 */ 681static char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,const char*oldnew) 682{ 683if(!orig_name && !isnull) 684returnfind_name(line, NULL, p_value, TERM_TAB); 685 686if(orig_name) { 687int len; 688const char*name; 689char*another; 690 name = orig_name; 691 len =strlen(name); 692if(isnull) 693die("git apply: bad git-diff - expected /dev/null, got%son line%d", name, linenr); 694 another =find_name(line, NULL, p_value, TERM_TAB); 695if(!another ||memcmp(another, name, len +1)) 696die("git apply: bad git-diff - inconsistent%sfilename on line%d", oldnew, linenr); 697free(another); 698return orig_name; 699} 700else{ 701/* expect "/dev/null" */ 702if(memcmp("/dev/null", line,9) || line[9] !='\n') 703die("git apply: bad git-diff - expected /dev/null on line%d", linenr); 704return NULL; 705} 706} 707 708static intgitdiff_oldname(const char*line,struct patch *patch) 709{ 710 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name,"old"); 711return0; 712} 713 714static intgitdiff_newname(const char*line,struct patch *patch) 715{ 716 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name,"new"); 717return0; 718} 719 720static intgitdiff_oldmode(const char*line,struct patch *patch) 721{ 722 patch->old_mode =strtoul(line, NULL,8); 723return0; 724} 725 726static intgitdiff_newmode(const char*line,struct patch *patch) 727{ 728 patch->new_mode =strtoul(line, NULL,8); 729return0; 730} 731 732static intgitdiff_delete(const char*line,struct patch *patch) 733{ 734 patch->is_delete =1; 735 patch->old_name = patch->def_name; 736returngitdiff_oldmode(line, patch); 737} 738 739static intgitdiff_newfile(const char*line,struct patch *patch) 740{ 741 patch->is_new =1; 742 patch->new_name = patch->def_name; 743returngitdiff_newmode(line, patch); 744} 745 746static intgitdiff_copysrc(const char*line,struct patch *patch) 747{ 748 patch->is_copy =1; 749 patch->old_name =find_name(line, NULL,0,0); 750return0; 751} 752 753static intgitdiff_copydst(const char*line,struct patch *patch) 754{ 755 patch->is_copy =1; 756 patch->new_name =find_name(line, NULL,0,0); 757return0; 758} 759 760static intgitdiff_renamesrc(const char*line,struct patch *patch) 761{ 762 patch->is_rename =1; 763 patch->old_name =find_name(line, NULL,0,0); 764return0; 765} 766 767static intgitdiff_renamedst(const char*line,struct patch *patch) 768{ 769 patch->is_rename =1; 770 patch->new_name =find_name(line, NULL,0,0); 771return0; 772} 773 774static intgitdiff_similarity(const char*line,struct patch *patch) 775{ 776if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 777 patch->score =0; 778return0; 779} 780 781static intgitdiff_dissimilarity(const char*line,struct patch *patch) 782{ 783if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 784 patch->score =0; 785return0; 786} 787 788static intgitdiff_index(const char*line,struct patch *patch) 789{ 790/* 791 * index line is N hexadecimal, "..", N hexadecimal, 792 * and optional space with octal mode. 793 */ 794const char*ptr, *eol; 795int len; 796 797 ptr =strchr(line,'.'); 798if(!ptr || ptr[1] !='.'||40< ptr - line) 799return0; 800 len = ptr - line; 801memcpy(patch->old_sha1_prefix, line, len); 802 patch->old_sha1_prefix[len] =0; 803 804 line = ptr +2; 805 ptr =strchr(line,' '); 806 eol =strchr(line,'\n'); 807 808if(!ptr || eol < ptr) 809 ptr = eol; 810 len = ptr - line; 811 812if(40< len) 813return0; 814memcpy(patch->new_sha1_prefix, line, len); 815 patch->new_sha1_prefix[len] =0; 816if(*ptr ==' ') 817 patch->old_mode =strtoul(ptr+1, NULL,8); 818return0; 819} 820 821/* 822 * This is normal for a diff that doesn't change anything: we'll fall through 823 * into the next diff. Tell the parser to break out. 824 */ 825static intgitdiff_unrecognized(const char*line,struct patch *patch) 826{ 827return-1; 828} 829 830static const char*stop_at_slash(const char*line,int llen) 831{ 832int nslash = p_value; 833int i; 834 835for(i =0; i < llen; i++) { 836int ch = line[i]; 837if(ch =='/'&& --nslash <=0) 838return&line[i]; 839} 840return NULL; 841} 842 843/* 844 * This is to extract the same name that appears on "diff --git" 845 * line. We do not find and return anything if it is a rename 846 * patch, and it is OK because we will find the name elsewhere. 847 * We need to reliably find name only when it is mode-change only, 848 * creation or deletion of an empty file. In any of these cases, 849 * both sides are the same name under a/ and b/ respectively. 850 */ 851static char*git_header_name(char*line,int llen) 852{ 853const char*name; 854const char*second = NULL; 855size_t len; 856 857 line +=strlen("diff --git "); 858 llen -=strlen("diff --git "); 859 860if(*line =='"') { 861const char*cp; 862struct strbuf first = STRBUF_INIT; 863struct strbuf sp = STRBUF_INIT; 864 865if(unquote_c_style(&first, line, &second)) 866goto free_and_fail1; 867 868/* advance to the first slash */ 869 cp =stop_at_slash(first.buf, first.len); 870/* we do not accept absolute paths */ 871if(!cp || cp == first.buf) 872goto free_and_fail1; 873strbuf_remove(&first,0, cp +1- first.buf); 874 875/* 876 * second points at one past closing dq of name. 877 * find the second name. 878 */ 879while((second < line + llen) &&isspace(*second)) 880 second++; 881 882if(line + llen <= second) 883goto free_and_fail1; 884if(*second =='"') { 885if(unquote_c_style(&sp, second, NULL)) 886goto free_and_fail1; 887 cp =stop_at_slash(sp.buf, sp.len); 888if(!cp || cp == sp.buf) 889goto free_and_fail1; 890/* They must match, otherwise ignore */ 891if(strcmp(cp +1, first.buf)) 892goto free_and_fail1; 893strbuf_release(&sp); 894returnstrbuf_detach(&first, NULL); 895} 896 897/* unquoted second */ 898 cp =stop_at_slash(second, line + llen - second); 899if(!cp || cp == second) 900goto free_and_fail1; 901 cp++; 902if(line + llen - cp != first.len +1|| 903memcmp(first.buf, cp, first.len)) 904goto free_and_fail1; 905returnstrbuf_detach(&first, NULL); 906 907 free_and_fail1: 908strbuf_release(&first); 909strbuf_release(&sp); 910return NULL; 911} 912 913/* unquoted first name */ 914 name =stop_at_slash(line, llen); 915if(!name || name == line) 916return NULL; 917 name++; 918 919/* 920 * since the first name is unquoted, a dq if exists must be 921 * the beginning of the second name. 922 */ 923for(second = name; second < line + llen; second++) { 924if(*second =='"') { 925struct strbuf sp = STRBUF_INIT; 926const char*np; 927 928if(unquote_c_style(&sp, second, NULL)) 929goto free_and_fail2; 930 931 np =stop_at_slash(sp.buf, sp.len); 932if(!np || np == sp.buf) 933goto free_and_fail2; 934 np++; 935 936 len = sp.buf + sp.len - np; 937if(len < second - name && 938!strncmp(np, name, len) && 939isspace(name[len])) { 940/* Good */ 941strbuf_remove(&sp,0, np - sp.buf); 942returnstrbuf_detach(&sp, NULL); 943} 944 945 free_and_fail2: 946strbuf_release(&sp); 947return NULL; 948} 949} 950 951/* 952 * Accept a name only if it shows up twice, exactly the same 953 * form. 954 */ 955for(len =0; ; len++) { 956switch(name[len]) { 957default: 958continue; 959case'\n': 960return NULL; 961case'\t':case' ': 962 second = name+len; 963for(;;) { 964char c = *second++; 965if(c =='\n') 966return NULL; 967if(c =='/') 968break; 969} 970if(second[len] =='\n'&& !memcmp(name, second, len)) { 971returnxmemdupz(name, len); 972} 973} 974} 975} 976 977/* Verify that we recognize the lines following a git header */ 978static intparse_git_header(char*line,int len,unsigned int size,struct patch *patch) 979{ 980unsigned long offset; 981 982/* A git diff has explicit new/delete information, so we don't guess */ 983 patch->is_new =0; 984 patch->is_delete =0; 985 986/* 987 * Some things may not have the old name in the 988 * rest of the headers anywhere (pure mode changes, 989 * or removing or adding empty files), so we get 990 * the default name from the header. 991 */ 992 patch->def_name =git_header_name(line, len); 993if(patch->def_name && root) { 994char*s =xmalloc(root_len +strlen(patch->def_name) +1); 995strcpy(s, root); 996strcpy(s + root_len, patch->def_name); 997free(patch->def_name); 998 patch->def_name = s; 999}10001001 line += len;1002 size -= len;1003 linenr++;1004for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) {1005static const struct opentry {1006const char*str;1007int(*fn)(const char*,struct patch *);1008} optable[] = {1009{"@@ -", gitdiff_hdrend },1010{"--- ", gitdiff_oldname },1011{"+++ ", gitdiff_newname },1012{"old mode ", gitdiff_oldmode },1013{"new mode ", gitdiff_newmode },1014{"deleted file mode ", gitdiff_delete },1015{"new file mode ", gitdiff_newfile },1016{"copy from ", gitdiff_copysrc },1017{"copy to ", gitdiff_copydst },1018{"rename old ", gitdiff_renamesrc },1019{"rename new ", gitdiff_renamedst },1020{"rename from ", gitdiff_renamesrc },1021{"rename to ", gitdiff_renamedst },1022{"similarity index ", gitdiff_similarity },1023{"dissimilarity index ", gitdiff_dissimilarity },1024{"index ", gitdiff_index },1025{"", gitdiff_unrecognized },1026};1027int i;10281029 len =linelen(line, size);1030if(!len || line[len-1] !='\n')1031break;1032for(i =0; i <ARRAY_SIZE(optable); i++) {1033const struct opentry *p = optable + i;1034int oplen =strlen(p->str);1035if(len < oplen ||memcmp(p->str, line, oplen))1036continue;1037if(p->fn(line + oplen, patch) <0)1038return offset;1039break;1040}1041}10421043return offset;1044}10451046static intparse_num(const char*line,unsigned long*p)1047{1048char*ptr;10491050if(!isdigit(*line))1051return0;1052*p =strtoul(line, &ptr,10);1053return ptr - line;1054}10551056static intparse_range(const char*line,int len,int offset,const char*expect,1057unsigned long*p1,unsigned long*p2)1058{1059int digits, ex;10601061if(offset <0|| offset >= len)1062return-1;1063 line += offset;1064 len -= offset;10651066 digits =parse_num(line, p1);1067if(!digits)1068return-1;10691070 offset += digits;1071 line += digits;1072 len -= digits;10731074*p2 =1;1075if(*line ==',') {1076 digits =parse_num(line+1, p2);1077if(!digits)1078return-1;10791080 offset += digits+1;1081 line += digits+1;1082 len -= digits+1;1083}10841085 ex =strlen(expect);1086if(ex > len)1087return-1;1088if(memcmp(line, expect, ex))1089return-1;10901091return offset + ex;1092}10931094static voidrecount_diff(char*line,int size,struct fragment *fragment)1095{1096int oldlines =0, newlines =0, ret =0;10971098if(size <1) {1099warning("recount: ignore empty hunk");1100return;1101}11021103for(;;) {1104int len =linelen(line, size);1105 size -= len;1106 line += len;11071108if(size <1)1109break;11101111switch(*line) {1112case' ':case'\n':1113 newlines++;1114/* fall through */1115case'-':1116 oldlines++;1117continue;1118case'+':1119 newlines++;1120continue;1121case'\\':1122continue;1123case'@':1124 ret = size <3||prefixcmp(line,"@@ ");1125break;1126case'd':1127 ret = size <5||prefixcmp(line,"diff ");1128break;1129default:1130 ret = -1;1131break;1132}1133if(ret) {1134warning("recount: unexpected line: %.*s",1135(int)linelen(line, size), line);1136return;1137}1138break;1139}1140 fragment->oldlines = oldlines;1141 fragment->newlines = newlines;1142}11431144/*1145 * Parse a unified diff fragment header of the1146 * form "@@ -a,b +c,d @@"1147 */1148static intparse_fragment_header(char*line,int len,struct fragment *fragment)1149{1150int offset;11511152if(!len || line[len-1] !='\n')1153return-1;11541155/* Figure out the number of lines in a fragment */1156 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1157 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);11581159return offset;1160}11611162static intfind_header(char*line,unsigned long size,int*hdrsize,struct patch *patch)1163{1164unsigned long offset, len;11651166 patch->is_toplevel_relative =0;1167 patch->is_rename = patch->is_copy =0;1168 patch->is_new = patch->is_delete = -1;1169 patch->old_mode = patch->new_mode =0;1170 patch->old_name = patch->new_name = NULL;1171for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1172unsigned long nextlen;11731174 len =linelen(line, size);1175if(!len)1176break;11771178/* Testing this early allows us to take a few shortcuts.. */1179if(len <6)1180continue;11811182/*1183 * Make sure we don't find any unconnected patch fragments.1184 * That's a sign that we didn't find a header, and that a1185 * patch has become corrupted/broken up.1186 */1187if(!memcmp("@@ -", line,4)) {1188struct fragment dummy;1189if(parse_fragment_header(line, len, &dummy) <0)1190continue;1191die("patch fragment without header at line%d: %.*s",1192 linenr, (int)len-1, line);1193}11941195if(size < len +6)1196break;11971198/*1199 * Git patch? It might not have a real patch, just a rename1200 * or mode change, so we handle that specially1201 */1202if(!memcmp("diff --git ", line,11)) {1203int git_hdr_len =parse_git_header(line, len, size, patch);1204if(git_hdr_len <= len)1205continue;1206if(!patch->old_name && !patch->new_name) {1207if(!patch->def_name)1208die("git diff header lacks filename information when removing "1209"%dleading pathname components (line%d)", p_value, linenr);1210 patch->old_name = patch->new_name = patch->def_name;1211}1212 patch->is_toplevel_relative =1;1213*hdrsize = git_hdr_len;1214return offset;1215}12161217/* --- followed by +++ ? */1218if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1219continue;12201221/*1222 * We only accept unified patches, so we want it to1223 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1224 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1225 */1226 nextlen =linelen(line + len, size - len);1227if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1228continue;12291230/* Ok, we'll consider it a patch */1231parse_traditional_patch(line, line+len, patch);1232*hdrsize = len + nextlen;1233 linenr +=2;1234return offset;1235}1236return-1;1237}12381239static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1240{1241char*err;12421243if(!result)1244return;12451246 whitespace_error++;1247if(squelch_whitespace_errors &&1248 squelch_whitespace_errors < whitespace_error)1249return;12501251 err =whitespace_error_string(result);1252fprintf(stderr,"%s:%d:%s.\n%.*s\n",1253 patch_input_file, linenr, err, len, line);1254free(err);1255}12561257static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1258{1259unsigned result =ws_check(line +1, len -1, ws_rule);12601261record_ws_error(result, line +1, len -2, linenr);1262}12631264/*1265 * Parse a unified diff. Note that this really needs to parse each1266 * fragment separately, since the only way to know the difference1267 * between a "---" that is part of a patch, and a "---" that starts1268 * the next patch is to look at the line counts..1269 */1270static intparse_fragment(char*line,unsigned long size,1271struct patch *patch,struct fragment *fragment)1272{1273int added, deleted;1274int len =linelen(line, size), offset;1275unsigned long oldlines, newlines;1276unsigned long leading, trailing;12771278 offset =parse_fragment_header(line, len, fragment);1279if(offset <0)1280return-1;1281if(offset >0&& patch->recount)1282recount_diff(line + offset, size - offset, fragment);1283 oldlines = fragment->oldlines;1284 newlines = fragment->newlines;1285 leading =0;1286 trailing =0;12871288/* Parse the thing.. */1289 line += len;1290 size -= len;1291 linenr++;1292 added = deleted =0;1293for(offset = len;12940< size;1295 offset += len, size -= len, line += len, linenr++) {1296if(!oldlines && !newlines)1297break;1298 len =linelen(line, size);1299if(!len || line[len-1] !='\n')1300return-1;1301switch(*line) {1302default:1303return-1;1304case'\n':/* newer GNU diff, an empty context line */1305case' ':1306 oldlines--;1307 newlines--;1308if(!deleted && !added)1309 leading++;1310 trailing++;1311break;1312case'-':1313if(apply_in_reverse &&1314 ws_error_action != nowarn_ws_error)1315check_whitespace(line, len, patch->ws_rule);1316 deleted++;1317 oldlines--;1318 trailing =0;1319break;1320case'+':1321if(!apply_in_reverse &&1322 ws_error_action != nowarn_ws_error)1323check_whitespace(line, len, patch->ws_rule);1324 added++;1325 newlines--;1326 trailing =0;1327break;13281329/*1330 * We allow "\ No newline at end of file". Depending1331 * on locale settings when the patch was produced we1332 * don't know what this line looks like. The only1333 * thing we do know is that it begins with "\ ".1334 * Checking for 12 is just for sanity check -- any1335 * l10n of "\ No newline..." is at least that long.1336 */1337case'\\':1338if(len <12||memcmp(line,"\\",2))1339return-1;1340break;1341}1342}1343if(oldlines || newlines)1344return-1;1345 fragment->leading = leading;1346 fragment->trailing = trailing;13471348/*1349 * If a fragment ends with an incomplete line, we failed to include1350 * it in the above loop because we hit oldlines == newlines == 01351 * before seeing it.1352 */1353if(12< size && !memcmp(line,"\\",2))1354 offset +=linelen(line, size);13551356 patch->lines_added += added;1357 patch->lines_deleted += deleted;13581359if(0< patch->is_new && oldlines)1360returnerror("new file depends on old contents");1361if(0< patch->is_delete && newlines)1362returnerror("deleted file still has contents");1363return offset;1364}13651366static intparse_single_patch(char*line,unsigned long size,struct patch *patch)1367{1368unsigned long offset =0;1369unsigned long oldlines =0, newlines =0, context =0;1370struct fragment **fragp = &patch->fragments;13711372while(size >4&& !memcmp(line,"@@ -",4)) {1373struct fragment *fragment;1374int len;13751376 fragment =xcalloc(1,sizeof(*fragment));1377 fragment->linenr = linenr;1378 len =parse_fragment(line, size, patch, fragment);1379if(len <=0)1380die("corrupt patch at line%d", linenr);1381 fragment->patch = line;1382 fragment->size = len;1383 oldlines += fragment->oldlines;1384 newlines += fragment->newlines;1385 context += fragment->leading + fragment->trailing;13861387*fragp = fragment;1388 fragp = &fragment->next;13891390 offset += len;1391 line += len;1392 size -= len;1393}13941395/*1396 * If something was removed (i.e. we have old-lines) it cannot1397 * be creation, and if something was added it cannot be1398 * deletion. However, the reverse is not true; --unified=01399 * patches that only add are not necessarily creation even1400 * though they do not have any old lines, and ones that only1401 * delete are not necessarily deletion.1402 *1403 * Unfortunately, a real creation/deletion patch do _not_ have1404 * any context line by definition, so we cannot safely tell it1405 * apart with --unified=0 insanity. At least if the patch has1406 * more than one hunk it is not creation or deletion.1407 */1408if(patch->is_new <0&&1409(oldlines || (patch->fragments && patch->fragments->next)))1410 patch->is_new =0;1411if(patch->is_delete <0&&1412(newlines || (patch->fragments && patch->fragments->next)))1413 patch->is_delete =0;14141415if(0< patch->is_new && oldlines)1416die("new file%sdepends on old contents", patch->new_name);1417if(0< patch->is_delete && newlines)1418die("deleted file%sstill has contents", patch->old_name);1419if(!patch->is_delete && !newlines && context)1420fprintf(stderr,"** warning: file%sbecomes empty but "1421"is not deleted\n", patch->new_name);14221423return offset;1424}14251426staticinlineintmetadata_changes(struct patch *patch)1427{1428return patch->is_rename >0||1429 patch->is_copy >0||1430 patch->is_new >0||1431 patch->is_delete ||1432(patch->old_mode && patch->new_mode &&1433 patch->old_mode != patch->new_mode);1434}14351436static char*inflate_it(const void*data,unsigned long size,1437unsigned long inflated_size)1438{1439 z_stream stream;1440void*out;1441int st;14421443memset(&stream,0,sizeof(stream));14441445 stream.next_in = (unsigned char*)data;1446 stream.avail_in = size;1447 stream.next_out = out =xmalloc(inflated_size);1448 stream.avail_out = inflated_size;1449git_inflate_init(&stream);1450 st =git_inflate(&stream, Z_FINISH);1451git_inflate_end(&stream);1452if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1453free(out);1454return NULL;1455}1456return out;1457}14581459static struct fragment *parse_binary_hunk(char**buf_p,1460unsigned long*sz_p,1461int*status_p,1462int*used_p)1463{1464/*1465 * Expect a line that begins with binary patch method ("literal"1466 * or "delta"), followed by the length of data before deflating.1467 * a sequence of 'length-byte' followed by base-85 encoded data1468 * should follow, terminated by a newline.1469 *1470 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1471 * and we would limit the patch line to 66 characters,1472 * so one line can fit up to 13 groups that would decode1473 * to 52 bytes max. The length byte 'A'-'Z' corresponds1474 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1475 */1476int llen, used;1477unsigned long size = *sz_p;1478char*buffer = *buf_p;1479int patch_method;1480unsigned long origlen;1481char*data = NULL;1482int hunk_size =0;1483struct fragment *frag;14841485 llen =linelen(buffer, size);1486 used = llen;14871488*status_p =0;14891490if(!prefixcmp(buffer,"delta ")) {1491 patch_method = BINARY_DELTA_DEFLATED;1492 origlen =strtoul(buffer +6, NULL,10);1493}1494else if(!prefixcmp(buffer,"literal ")) {1495 patch_method = BINARY_LITERAL_DEFLATED;1496 origlen =strtoul(buffer +8, NULL,10);1497}1498else1499return NULL;15001501 linenr++;1502 buffer += llen;1503while(1) {1504int byte_length, max_byte_length, newsize;1505 llen =linelen(buffer, size);1506 used += llen;1507 linenr++;1508if(llen ==1) {1509/* consume the blank line */1510 buffer++;1511 size--;1512break;1513}1514/*1515 * Minimum line is "A00000\n" which is 7-byte long,1516 * and the line length must be multiple of 5 plus 2.1517 */1518if((llen <7) || (llen-2) %5)1519goto corrupt;1520 max_byte_length = (llen -2) /5*4;1521 byte_length = *buffer;1522if('A'<= byte_length && byte_length <='Z')1523 byte_length = byte_length -'A'+1;1524else if('a'<= byte_length && byte_length <='z')1525 byte_length = byte_length -'a'+27;1526else1527goto corrupt;1528/* if the input length was not multiple of 4, we would1529 * have filler at the end but the filler should never1530 * exceed 3 bytes1531 */1532if(max_byte_length < byte_length ||1533 byte_length <= max_byte_length -4)1534goto corrupt;1535 newsize = hunk_size + byte_length;1536 data =xrealloc(data, newsize);1537if(decode_85(data + hunk_size, buffer +1, byte_length))1538goto corrupt;1539 hunk_size = newsize;1540 buffer += llen;1541 size -= llen;1542}15431544 frag =xcalloc(1,sizeof(*frag));1545 frag->patch =inflate_it(data, hunk_size, origlen);1546if(!frag->patch)1547goto corrupt;1548free(data);1549 frag->size = origlen;1550*buf_p = buffer;1551*sz_p = size;1552*used_p = used;1553 frag->binary_patch_method = patch_method;1554return frag;15551556 corrupt:1557free(data);1558*status_p = -1;1559error("corrupt binary patch at line%d: %.*s",1560 linenr-1, llen-1, buffer);1561return NULL;1562}15631564static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1565{1566/*1567 * We have read "GIT binary patch\n"; what follows is a line1568 * that says the patch method (currently, either "literal" or1569 * "delta") and the length of data before deflating; a1570 * sequence of 'length-byte' followed by base-85 encoded data1571 * follows.1572 *1573 * When a binary patch is reversible, there is another binary1574 * hunk in the same format, starting with patch method (either1575 * "literal" or "delta") with the length of data, and a sequence1576 * of length-byte + base-85 encoded data, terminated with another1577 * empty line. This data, when applied to the postimage, produces1578 * the preimage.1579 */1580struct fragment *forward;1581struct fragment *reverse;1582int status;1583int used, used_1;15841585 forward =parse_binary_hunk(&buffer, &size, &status, &used);1586if(!forward && !status)1587/* there has to be one hunk (forward hunk) */1588returnerror("unrecognized binary patch at line%d", linenr-1);1589if(status)1590/* otherwise we already gave an error message */1591return status;15921593 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1594if(reverse)1595 used += used_1;1596else if(status) {1597/*1598 * Not having reverse hunk is not an error, but having1599 * a corrupt reverse hunk is.1600 */1601free((void*) forward->patch);1602free(forward);1603return status;1604}1605 forward->next = reverse;1606 patch->fragments = forward;1607 patch->is_binary =1;1608return used;1609}16101611static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1612{1613int hdrsize, patchsize;1614int offset =find_header(buffer, size, &hdrsize, patch);16151616if(offset <0)1617return offset;16181619 patch->ws_rule =whitespace_rule(patch->new_name1620? patch->new_name1621: patch->old_name);16221623 patchsize =parse_single_patch(buffer + offset + hdrsize,1624 size - offset - hdrsize, patch);16251626if(!patchsize) {1627static const char*binhdr[] = {1628"Binary files ",1629"Files ",1630 NULL,1631};1632static const char git_binary[] ="GIT binary patch\n";1633int i;1634int hd = hdrsize + offset;1635unsigned long llen =linelen(buffer + hd, size - hd);16361637if(llen ==sizeof(git_binary) -1&&1638!memcmp(git_binary, buffer + hd, llen)) {1639int used;1640 linenr++;1641 used =parse_binary(buffer + hd + llen,1642 size - hd - llen, patch);1643if(used)1644 patchsize = used + llen;1645else1646 patchsize =0;1647}1648else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1649for(i =0; binhdr[i]; i++) {1650int len =strlen(binhdr[i]);1651if(len < size - hd &&1652!memcmp(binhdr[i], buffer + hd, len)) {1653 linenr++;1654 patch->is_binary =1;1655 patchsize = llen;1656break;1657}1658}1659}16601661/* Empty patch cannot be applied if it is a text patch1662 * without metadata change. A binary patch appears1663 * empty to us here.1664 */1665if((apply || check) &&1666(!patch->is_binary && !metadata_changes(patch)))1667die("patch with only garbage at line%d", linenr);1668}16691670return offset + hdrsize + patchsize;1671}16721673#define swap(a,b) myswap((a),(b),sizeof(a))16741675#define myswap(a, b, size) do { \1676 unsigned char mytmp[size]; \1677 memcpy(mytmp, &a, size); \1678 memcpy(&a, &b, size); \1679 memcpy(&b, mytmp, size); \1680} while (0)16811682static voidreverse_patches(struct patch *p)1683{1684for(; p; p = p->next) {1685struct fragment *frag = p->fragments;16861687swap(p->new_name, p->old_name);1688swap(p->new_mode, p->old_mode);1689swap(p->is_new, p->is_delete);1690swap(p->lines_added, p->lines_deleted);1691swap(p->old_sha1_prefix, p->new_sha1_prefix);16921693for(; frag; frag = frag->next) {1694swap(frag->newpos, frag->oldpos);1695swap(frag->newlines, frag->oldlines);1696}1697}1698}16991700static const char pluses[] =1701"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";1702static const char minuses[]=1703"----------------------------------------------------------------------";17041705static voidshow_stats(struct patch *patch)1706{1707struct strbuf qname = STRBUF_INIT;1708char*cp = patch->new_name ? patch->new_name : patch->old_name;1709int max, add, del;17101711quote_c_style(cp, &qname, NULL,0);17121713/*1714 * "scale" the filename1715 */1716 max = max_len;1717if(max >50)1718 max =50;17191720if(qname.len > max) {1721 cp =strchr(qname.buf + qname.len +3- max,'/');1722if(!cp)1723 cp = qname.buf + qname.len +3- max;1724strbuf_splice(&qname,0, cp - qname.buf,"...",3);1725}17261727if(patch->is_binary) {1728printf(" %-*s | Bin\n", max, qname.buf);1729strbuf_release(&qname);1730return;1731}17321733printf(" %-*s |", max, qname.buf);1734strbuf_release(&qname);17351736/*1737 * scale the add/delete1738 */1739 max = max + max_change >70?70- max : max_change;1740 add = patch->lines_added;1741 del = patch->lines_deleted;17421743if(max_change >0) {1744int total = ((add + del) * max + max_change /2) / max_change;1745 add = (add * max + max_change /2) / max_change;1746 del = total - add;1747}1748printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,1749 add, pluses, del, minuses);1750}17511752static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)1753{1754switch(st->st_mode & S_IFMT) {1755case S_IFLNK:1756if(strbuf_readlink(buf, path, st->st_size) <0)1757returnerror("unable to read symlink%s", path);1758return0;1759case S_IFREG:1760if(strbuf_read_file(buf, path, st->st_size) != st->st_size)1761returnerror("unable to open or read%s", path);1762convert_to_git(path, buf->buf, buf->len, buf,0);1763return0;1764default:1765return-1;1766}1767}17681769/*1770 * Update the preimage, and the common lines in postimage,1771 * from buffer buf of length len. If postlen is 0 the postimage1772 * is updated in place, otherwise it's updated on a new buffer1773 * of length postlen1774 */17751776static voidupdate_pre_post_images(struct image *preimage,1777struct image *postimage,1778char*buf,1779size_t len,size_t postlen)1780{1781int i, ctx;1782char*new, *old, *fixed;1783struct image fixed_preimage;17841785/*1786 * Update the preimage with whitespace fixes. Note that we1787 * are not losing preimage->buf -- apply_one_fragment() will1788 * free "oldlines".1789 */1790prepare_image(&fixed_preimage, buf, len,1);1791assert(fixed_preimage.nr == preimage->nr);1792for(i =0; i < preimage->nr; i++)1793 fixed_preimage.line[i].flag = preimage->line[i].flag;1794free(preimage->line_allocated);1795*preimage = fixed_preimage;17961797/*1798 * Adjust the common context lines in postimage. This can be1799 * done in-place when we are just doing whitespace fixing,1800 * which does not make the string grow, but needs a new buffer1801 * when ignoring whitespace causes the update, since in this case1802 * we could have e.g. tabs converted to multiple spaces.1803 * We trust the caller to tell us if the update can be done1804 * in place (postlen==0) or not.1805 */1806 old = postimage->buf;1807if(postlen)1808new= postimage->buf =xmalloc(postlen);1809else1810new= old;1811 fixed = preimage->buf;1812for(i = ctx =0; i < postimage->nr; i++) {1813size_t len = postimage->line[i].len;1814if(!(postimage->line[i].flag & LINE_COMMON)) {1815/* an added line -- no counterparts in preimage */1816memmove(new, old, len);1817 old += len;1818new+= len;1819continue;1820}18211822/* a common context -- skip it in the original postimage */1823 old += len;18241825/* and find the corresponding one in the fixed preimage */1826while(ctx < preimage->nr &&1827!(preimage->line[ctx].flag & LINE_COMMON)) {1828 fixed += preimage->line[ctx].len;1829 ctx++;1830}1831if(preimage->nr <= ctx)1832die("oops");18331834/* and copy it in, while fixing the line length */1835 len = preimage->line[ctx].len;1836memcpy(new, fixed, len);1837new+= len;1838 fixed += len;1839 postimage->line[i].len = len;1840 ctx++;1841}18421843/* Fix the length of the whole thing */1844 postimage->len =new- postimage->buf;1845}18461847static intmatch_fragment(struct image *img,1848struct image *preimage,1849struct image *postimage,1850unsigned longtry,1851int try_lno,1852unsigned ws_rule,1853int match_beginning,int match_end)1854{1855int i;1856char*fixed_buf, *buf, *orig, *target;18571858if(preimage->nr + try_lno > img->nr)1859return0;18601861if(match_beginning && try_lno)1862return0;18631864if(match_end && preimage->nr + try_lno != img->nr)1865return0;18661867/* Quick hash check */1868for(i =0; i < preimage->nr; i++)1869if(preimage->line[i].hash != img->line[try_lno + i].hash)1870return0;18711872/*1873 * Do we have an exact match? If we were told to match1874 * at the end, size must be exactly at try+fragsize,1875 * otherwise try+fragsize must be still within the preimage,1876 * and either case, the old piece should match the preimage1877 * exactly.1878 */1879if((match_end1880? (try+ preimage->len == img->len)1881: (try+ preimage->len <= img->len)) &&1882!memcmp(img->buf +try, preimage->buf, preimage->len))1883return1;18841885/*1886 * No exact match. If we are ignoring whitespace, run a line-by-line1887 * fuzzy matching. We collect all the line length information because1888 * we need it to adjust whitespace if we match.1889 */1890if(ws_ignore_action == ignore_ws_change) {1891size_t imgoff =0;1892size_t preoff =0;1893size_t postlen = postimage->len;1894for(i =0; i < preimage->nr; i++) {1895size_t prelen = preimage->line[i].len;1896size_t imglen = img->line[try_lno+i].len;18971898if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,1899 preimage->buf + preoff, prelen))1900return0;1901if(preimage->line[i].flag & LINE_COMMON)1902 postlen += imglen - prelen;1903 imgoff += imglen;1904 preoff += prelen;1905}19061907/*1908 * Ok, the preimage matches with whitespace fuzz. Update it and1909 * the common postimage lines to use the same whitespace as the1910 * target. imgoff now holds the true length of the target that1911 * matches the preimage, and we need to update the line lengths1912 * of the preimage to match the target ones.1913 */1914 fixed_buf =xmalloc(imgoff);1915memcpy(fixed_buf, img->buf +try, imgoff);1916for(i =0; i < preimage->nr; i++)1917 preimage->line[i].len = img->line[try_lno+i].len;19181919/*1920 * Update the preimage buffer and the postimage context lines.1921 */1922update_pre_post_images(preimage, postimage,1923 fixed_buf, imgoff, postlen);1924return1;1925}19261927if(ws_error_action != correct_ws_error)1928return0;19291930/*1931 * The hunk does not apply byte-by-byte, but the hash says1932 * it might with whitespace fuzz. We haven't been asked to1933 * ignore whitespace, we were asked to correct whitespace1934 * errors, so let's try matching after whitespace correction.1935 */1936 fixed_buf =xmalloc(preimage->len +1);1937 buf = fixed_buf;1938 orig = preimage->buf;1939 target = img->buf +try;1940for(i =0; i < preimage->nr; i++) {1941size_t fixlen;/* length after fixing the preimage */1942size_t oldlen = preimage->line[i].len;1943size_t tgtlen = img->line[try_lno + i].len;1944size_t tgtfixlen;/* length after fixing the target line */1945char tgtfixbuf[1024], *tgtfix;1946int match;19471948/* Try fixing the line in the preimage */1949 fixlen =ws_fix_copy(buf, orig, oldlen, ws_rule, NULL);19501951/* Try fixing the line in the target */1952if(sizeof(tgtfixbuf) > tgtlen)1953 tgtfix = tgtfixbuf;1954else1955 tgtfix =xmalloc(tgtlen);1956 tgtfixlen =ws_fix_copy(tgtfix, target, tgtlen, ws_rule, NULL);19571958/*1959 * If they match, either the preimage was based on1960 * a version before our tree fixed whitespace breakage,1961 * or we are lacking a whitespace-fix patch the tree1962 * the preimage was based on already had (i.e. target1963 * has whitespace breakage, the preimage doesn't).1964 * In either case, we are fixing the whitespace breakages1965 * so we might as well take the fix together with their1966 * real change.1967 */1968 match = (tgtfixlen == fixlen && !memcmp(tgtfix, buf, fixlen));19691970if(tgtfix != tgtfixbuf)1971free(tgtfix);1972if(!match)1973goto unmatch_exit;19741975 orig += oldlen;1976 buf += fixlen;1977 target += tgtlen;1978}19791980/*1981 * Yes, the preimage is based on an older version that still1982 * has whitespace breakages unfixed, and fixing them makes the1983 * hunk match. Update the context lines in the postimage.1984 */1985update_pre_post_images(preimage, postimage,1986 fixed_buf, buf - fixed_buf,0);1987return1;19881989 unmatch_exit:1990free(fixed_buf);1991return0;1992}19931994static intfind_pos(struct image *img,1995struct image *preimage,1996struct image *postimage,1997int line,1998unsigned ws_rule,1999int match_beginning,int match_end)2000{2001int i;2002unsigned long backwards, forwards,try;2003int backwards_lno, forwards_lno, try_lno;20042005if(preimage->nr > img->nr)2006return-1;20072008/*2009 * If match_begining or match_end is specified, there is no2010 * point starting from a wrong line that will never match and2011 * wander around and wait for a match at the specified end.2012 */2013if(match_beginning)2014 line =0;2015else if(match_end)2016 line = img->nr - preimage->nr;20172018if(line > img->nr)2019 line = img->nr;20202021try=0;2022for(i =0; i < line; i++)2023try+= img->line[i].len;20242025/*2026 * There's probably some smart way to do this, but I'll leave2027 * that to the smart and beautiful people. I'm simple and stupid.2028 */2029 backwards =try;2030 backwards_lno = line;2031 forwards =try;2032 forwards_lno = line;2033 try_lno = line;20342035for(i =0; ; i++) {2036if(match_fragment(img, preimage, postimage,2037try, try_lno, ws_rule,2038 match_beginning, match_end))2039return try_lno;20402041 again:2042if(backwards_lno ==0&& forwards_lno == img->nr)2043break;20442045if(i &1) {2046if(backwards_lno ==0) {2047 i++;2048goto again;2049}2050 backwards_lno--;2051 backwards -= img->line[backwards_lno].len;2052try= backwards;2053 try_lno = backwards_lno;2054}else{2055if(forwards_lno == img->nr) {2056 i++;2057goto again;2058}2059 forwards += img->line[forwards_lno].len;2060 forwards_lno++;2061try= forwards;2062 try_lno = forwards_lno;2063}20642065}2066return-1;2067}20682069static voidremove_first_line(struct image *img)2070{2071 img->buf += img->line[0].len;2072 img->len -= img->line[0].len;2073 img->line++;2074 img->nr--;2075}20762077static voidremove_last_line(struct image *img)2078{2079 img->len -= img->line[--img->nr].len;2080}20812082static voidupdate_image(struct image *img,2083int applied_pos,2084struct image *preimage,2085struct image *postimage)2086{2087/*2088 * remove the copy of preimage at offset in img2089 * and replace it with postimage2090 */2091int i, nr;2092size_t remove_count, insert_count, applied_at =0;2093char*result;20942095for(i =0; i < applied_pos; i++)2096 applied_at += img->line[i].len;20972098 remove_count =0;2099for(i =0; i < preimage->nr; i++)2100 remove_count += img->line[applied_pos + i].len;2101 insert_count = postimage->len;21022103/* Adjust the contents */2104 result =xmalloc(img->len + insert_count - remove_count +1);2105memcpy(result, img->buf, applied_at);2106memcpy(result + applied_at, postimage->buf, postimage->len);2107memcpy(result + applied_at + postimage->len,2108 img->buf + (applied_at + remove_count),2109 img->len - (applied_at + remove_count));2110free(img->buf);2111 img->buf = result;2112 img->len += insert_count - remove_count;2113 result[img->len] ='\0';21142115/* Adjust the line table */2116 nr = img->nr + postimage->nr - preimage->nr;2117if(preimage->nr < postimage->nr) {2118/*2119 * NOTE: this knows that we never call remove_first_line()2120 * on anything other than pre/post image.2121 */2122 img->line =xrealloc(img->line, nr *sizeof(*img->line));2123 img->line_allocated = img->line;2124}2125if(preimage->nr != postimage->nr)2126memmove(img->line + applied_pos + postimage->nr,2127 img->line + applied_pos + preimage->nr,2128(img->nr - (applied_pos + preimage->nr)) *2129sizeof(*img->line));2130memcpy(img->line + applied_pos,2131 postimage->line,2132 postimage->nr *sizeof(*img->line));2133 img->nr = nr;2134}21352136static intapply_one_fragment(struct image *img,struct fragment *frag,2137int inaccurate_eof,unsigned ws_rule)2138{2139int match_beginning, match_end;2140const char*patch = frag->patch;2141int size = frag->size;2142char*old, *new, *oldlines, *newlines;2143int new_blank_lines_at_end =0;2144unsigned long leading, trailing;2145int pos, applied_pos;2146struct image preimage;2147struct image postimage;21482149memset(&preimage,0,sizeof(preimage));2150memset(&postimage,0,sizeof(postimage));2151 oldlines =xmalloc(size);2152 newlines =xmalloc(size);21532154 old = oldlines;2155new= newlines;2156while(size >0) {2157char first;2158int len =linelen(patch, size);2159int plen, added;2160int added_blank_line =0;2161int is_blank_context =0;21622163if(!len)2164break;21652166/*2167 * "plen" is how much of the line we should use for2168 * the actual patch data. Normally we just remove the2169 * first character on the line, but if the line is2170 * followed by "\ No newline", then we also remove the2171 * last one (which is the newline, of course).2172 */2173 plen = len -1;2174if(len < size && patch[len] =='\\')2175 plen--;2176 first = *patch;2177if(apply_in_reverse) {2178if(first =='-')2179 first ='+';2180else if(first =='+')2181 first ='-';2182}21832184switch(first) {2185case'\n':2186/* Newer GNU diff, empty context line */2187if(plen <0)2188/* ... followed by '\No newline'; nothing */2189break;2190*old++ ='\n';2191*new++ ='\n';2192add_line_info(&preimage,"\n",1, LINE_COMMON);2193add_line_info(&postimage,"\n",1, LINE_COMMON);2194 is_blank_context =1;2195break;2196case' ':2197if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2198ws_blank_line(patch +1, plen, ws_rule))2199 is_blank_context =1;2200case'-':2201memcpy(old, patch +1, plen);2202add_line_info(&preimage, old, plen,2203(first ==' '? LINE_COMMON :0));2204 old += plen;2205if(first =='-')2206break;2207/* Fall-through for ' ' */2208case'+':2209/* --no-add does not add new lines */2210if(first =='+'&& no_add)2211break;22122213if(first !='+'||2214!whitespace_error ||2215 ws_error_action != correct_ws_error) {2216memcpy(new, patch +1, plen);2217 added = plen;2218}2219else{2220 added =ws_fix_copy(new, patch +1, plen, ws_rule, &applied_after_fixing_ws);2221}2222add_line_info(&postimage,new, added,2223(first =='+'?0: LINE_COMMON));2224new+= added;2225if(first =='+'&&2226(ws_rule & WS_BLANK_AT_EOF) &&2227ws_blank_line(patch +1, plen, ws_rule))2228 added_blank_line =1;2229break;2230case'@':case'\\':2231/* Ignore it, we already handled it */2232break;2233default:2234if(apply_verbosely)2235error("invalid start of line: '%c'", first);2236return-1;2237}2238if(added_blank_line)2239 new_blank_lines_at_end++;2240else if(is_blank_context)2241;2242else2243 new_blank_lines_at_end =0;2244 patch += len;2245 size -= len;2246}2247if(inaccurate_eof &&2248 old > oldlines && old[-1] =='\n'&&2249new> newlines &&new[-1] =='\n') {2250 old--;2251new--;2252}22532254 leading = frag->leading;2255 trailing = frag->trailing;22562257/*2258 * A hunk to change lines at the beginning would begin with2259 * @@ -1,L +N,M @@2260 * but we need to be careful. -U0 that inserts before the second2261 * line also has this pattern.2262 *2263 * And a hunk to add to an empty file would begin with2264 * @@ -0,0 +N,M @@2265 *2266 * In other words, a hunk that is (frag->oldpos <= 1) with or2267 * without leading context must match at the beginning.2268 */2269 match_beginning = (!frag->oldpos ||2270(frag->oldpos ==1&& !unidiff_zero));22712272/*2273 * A hunk without trailing lines must match at the end.2274 * However, we simply cannot tell if a hunk must match end2275 * from the lack of trailing lines if the patch was generated2276 * with unidiff without any context.2277 */2278 match_end = !unidiff_zero && !trailing;22792280 pos = frag->newpos ? (frag->newpos -1) :0;2281 preimage.buf = oldlines;2282 preimage.len = old - oldlines;2283 postimage.buf = newlines;2284 postimage.len =new- newlines;2285 preimage.line = preimage.line_allocated;2286 postimage.line = postimage.line_allocated;22872288for(;;) {22892290 applied_pos =find_pos(img, &preimage, &postimage, pos,2291 ws_rule, match_beginning, match_end);22922293if(applied_pos >=0)2294break;22952296/* Am I at my context limits? */2297if((leading <= p_context) && (trailing <= p_context))2298break;2299if(match_beginning || match_end) {2300 match_beginning = match_end =0;2301continue;2302}23032304/*2305 * Reduce the number of context lines; reduce both2306 * leading and trailing if they are equal otherwise2307 * just reduce the larger context.2308 */2309if(leading >= trailing) {2310remove_first_line(&preimage);2311remove_first_line(&postimage);2312 pos--;2313 leading--;2314}2315if(trailing > leading) {2316remove_last_line(&preimage);2317remove_last_line(&postimage);2318 trailing--;2319}2320}23212322if(applied_pos >=0) {2323if(new_blank_lines_at_end &&2324 preimage.nr + applied_pos == img->nr &&2325(ws_rule & WS_BLANK_AT_EOF) &&2326 ws_error_action != nowarn_ws_error) {2327record_ws_error(WS_BLANK_AT_EOF,"+",1, frag->linenr);2328if(ws_error_action == correct_ws_error) {2329while(new_blank_lines_at_end--)2330remove_last_line(&postimage);2331}2332/*2333 * We would want to prevent write_out_results()2334 * from taking place in apply_patch() that follows2335 * the callchain led us here, which is:2336 * apply_patch->check_patch_list->check_patch->2337 * apply_data->apply_fragments->apply_one_fragment2338 */2339if(ws_error_action == die_on_ws_error)2340 apply =0;2341}23422343/*2344 * Warn if it was necessary to reduce the number2345 * of context lines.2346 */2347if((leading != frag->leading) ||2348(trailing != frag->trailing))2349fprintf(stderr,"Context reduced to (%ld/%ld)"2350" to apply fragment at%d\n",2351 leading, trailing, applied_pos+1);2352update_image(img, applied_pos, &preimage, &postimage);2353}else{2354if(apply_verbosely)2355error("while searching for:\n%.*s",2356(int)(old - oldlines), oldlines);2357}23582359free(oldlines);2360free(newlines);2361free(preimage.line_allocated);2362free(postimage.line_allocated);23632364return(applied_pos <0);2365}23662367static intapply_binary_fragment(struct image *img,struct patch *patch)2368{2369struct fragment *fragment = patch->fragments;2370unsigned long len;2371void*dst;23722373/* Binary patch is irreversible without the optional second hunk */2374if(apply_in_reverse) {2375if(!fragment->next)2376returnerror("cannot reverse-apply a binary patch "2377"without the reverse hunk to '%s'",2378 patch->new_name2379? patch->new_name : patch->old_name);2380 fragment = fragment->next;2381}2382switch(fragment->binary_patch_method) {2383case BINARY_DELTA_DEFLATED:2384 dst =patch_delta(img->buf, img->len, fragment->patch,2385 fragment->size, &len);2386if(!dst)2387return-1;2388clear_image(img);2389 img->buf = dst;2390 img->len = len;2391return0;2392case BINARY_LITERAL_DEFLATED:2393clear_image(img);2394 img->len = fragment->size;2395 img->buf =xmalloc(img->len+1);2396memcpy(img->buf, fragment->patch, img->len);2397 img->buf[img->len] ='\0';2398return0;2399}2400return-1;2401}24022403static intapply_binary(struct image *img,struct patch *patch)2404{2405const char*name = patch->old_name ? patch->old_name : patch->new_name;2406unsigned char sha1[20];24072408/*2409 * For safety, we require patch index line to contain2410 * full 40-byte textual SHA1 for old and new, at least for now.2411 */2412if(strlen(patch->old_sha1_prefix) !=40||2413strlen(patch->new_sha1_prefix) !=40||2414get_sha1_hex(patch->old_sha1_prefix, sha1) ||2415get_sha1_hex(patch->new_sha1_prefix, sha1))2416returnerror("cannot apply binary patch to '%s' "2417"without full index line", name);24182419if(patch->old_name) {2420/*2421 * See if the old one matches what the patch2422 * applies to.2423 */2424hash_sha1_file(img->buf, img->len, blob_type, sha1);2425if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2426returnerror("the patch applies to '%s' (%s), "2427"which does not match the "2428"current contents.",2429 name,sha1_to_hex(sha1));2430}2431else{2432/* Otherwise, the old one must be empty. */2433if(img->len)2434returnerror("the patch applies to an empty "2435"'%s' but it is not empty", name);2436}24372438get_sha1_hex(patch->new_sha1_prefix, sha1);2439if(is_null_sha1(sha1)) {2440clear_image(img);2441return0;/* deletion patch */2442}24432444if(has_sha1_file(sha1)) {2445/* We already have the postimage */2446enum object_type type;2447unsigned long size;2448char*result;24492450 result =read_sha1_file(sha1, &type, &size);2451if(!result)2452returnerror("the necessary postimage%sfor "2453"'%s' cannot be read",2454 patch->new_sha1_prefix, name);2455clear_image(img);2456 img->buf = result;2457 img->len = size;2458}else{2459/*2460 * We have verified buf matches the preimage;2461 * apply the patch data to it, which is stored2462 * in the patch->fragments->{patch,size}.2463 */2464if(apply_binary_fragment(img, patch))2465returnerror("binary patch does not apply to '%s'",2466 name);24672468/* verify that the result matches */2469hash_sha1_file(img->buf, img->len, blob_type, sha1);2470if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2471returnerror("binary patch to '%s' creates incorrect result (expecting%s, got%s)",2472 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2473}24742475return0;2476}24772478static intapply_fragments(struct image *img,struct patch *patch)2479{2480struct fragment *frag = patch->fragments;2481const char*name = patch->old_name ? patch->old_name : patch->new_name;2482unsigned ws_rule = patch->ws_rule;2483unsigned inaccurate_eof = patch->inaccurate_eof;24842485if(patch->is_binary)2486returnapply_binary(img, patch);24872488while(frag) {2489if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule)) {2490error("patch failed:%s:%ld", name, frag->oldpos);2491if(!apply_with_reject)2492return-1;2493 frag->rejected =1;2494}2495 frag = frag->next;2496}2497return0;2498}24992500static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2501{2502if(!ce)2503return0;25042505if(S_ISGITLINK(ce->ce_mode)) {2506strbuf_grow(buf,100);2507strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2508}else{2509enum object_type type;2510unsigned long sz;2511char*result;25122513 result =read_sha1_file(ce->sha1, &type, &sz);2514if(!result)2515return-1;2516/* XXX read_sha1_file NUL-terminates */2517strbuf_attach(buf, result, sz, sz +1);2518}2519return0;2520}25212522static struct patch *in_fn_table(const char*name)2523{2524struct string_list_item *item;25252526if(name == NULL)2527return NULL;25282529 item =string_list_lookup(name, &fn_table);2530if(item != NULL)2531return(struct patch *)item->util;25322533return NULL;2534}25352536/*2537 * item->util in the filename table records the status of the path.2538 * Usually it points at a patch (whose result records the contents2539 * of it after applying it), but it could be PATH_WAS_DELETED for a2540 * path that a previously applied patch has already removed.2541 */2542#define PATH_TO_BE_DELETED ((struct patch *) -2)2543#define PATH_WAS_DELETED ((struct patch *) -1)25442545static intto_be_deleted(struct patch *patch)2546{2547return patch == PATH_TO_BE_DELETED;2548}25492550static intwas_deleted(struct patch *patch)2551{2552return patch == PATH_WAS_DELETED;2553}25542555static voidadd_to_fn_table(struct patch *patch)2556{2557struct string_list_item *item;25582559/*2560 * Always add new_name unless patch is a deletion2561 * This should cover the cases for normal diffs,2562 * file creations and copies2563 */2564if(patch->new_name != NULL) {2565 item =string_list_insert(patch->new_name, &fn_table);2566 item->util = patch;2567}25682569/*2570 * store a failure on rename/deletion cases because2571 * later chunks shouldn't patch old names2572 */2573if((patch->new_name == NULL) || (patch->is_rename)) {2574 item =string_list_insert(patch->old_name, &fn_table);2575 item->util = PATH_WAS_DELETED;2576}2577}25782579static voidprepare_fn_table(struct patch *patch)2580{2581/*2582 * store information about incoming file deletion2583 */2584while(patch) {2585if((patch->new_name == NULL) || (patch->is_rename)) {2586struct string_list_item *item;2587 item =string_list_insert(patch->old_name, &fn_table);2588 item->util = PATH_TO_BE_DELETED;2589}2590 patch = patch->next;2591}2592}25932594static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)2595{2596struct strbuf buf = STRBUF_INIT;2597struct image image;2598size_t len;2599char*img;2600struct patch *tpatch;26012602if(!(patch->is_copy || patch->is_rename) &&2603(tpatch =in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {2604if(was_deleted(tpatch)) {2605returnerror("patch%shas been renamed/deleted",2606 patch->old_name);2607}2608/* We have a patched copy in memory use that */2609strbuf_add(&buf, tpatch->result, tpatch->resultsize);2610}else if(cached) {2611if(read_file_or_gitlink(ce, &buf))2612returnerror("read of%sfailed", patch->old_name);2613}else if(patch->old_name) {2614if(S_ISGITLINK(patch->old_mode)) {2615if(ce) {2616read_file_or_gitlink(ce, &buf);2617}else{2618/*2619 * There is no way to apply subproject2620 * patch without looking at the index.2621 */2622 patch->fragments = NULL;2623}2624}else{2625if(read_old_data(st, patch->old_name, &buf))2626returnerror("read of%sfailed", patch->old_name);2627}2628}26292630 img =strbuf_detach(&buf, &len);2631prepare_image(&image, img, len, !patch->is_binary);26322633if(apply_fragments(&image, patch) <0)2634return-1;/* note with --reject this succeeds. */2635 patch->result = image.buf;2636 patch->resultsize = image.len;2637add_to_fn_table(patch);2638free(image.line_allocated);26392640if(0< patch->is_delete && patch->resultsize)2641returnerror("removal patch leaves file contents");26422643return0;2644}26452646static intcheck_to_create_blob(const char*new_name,int ok_if_exists)2647{2648struct stat nst;2649if(!lstat(new_name, &nst)) {2650if(S_ISDIR(nst.st_mode) || ok_if_exists)2651return0;2652/*2653 * A leading component of new_name might be a symlink2654 * that is going to be removed with this patch, but2655 * still pointing at somewhere that has the path.2656 * In such a case, path "new_name" does not exist as2657 * far as git is concerned.2658 */2659if(has_symlink_leading_path(new_name,strlen(new_name)))2660return0;26612662returnerror("%s: already exists in working directory", new_name);2663}2664else if((errno != ENOENT) && (errno != ENOTDIR))2665returnerror("%s:%s", new_name,strerror(errno));2666return0;2667}26682669static intverify_index_match(struct cache_entry *ce,struct stat *st)2670{2671if(S_ISGITLINK(ce->ce_mode)) {2672if(!S_ISDIR(st->st_mode))2673return-1;2674return0;2675}2676returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);2677}26782679static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)2680{2681const char*old_name = patch->old_name;2682struct patch *tpatch = NULL;2683int stat_ret =0;2684unsigned st_mode =0;26852686/*2687 * Make sure that we do not have local modifications from the2688 * index when we are looking at the index. Also make sure2689 * we have the preimage file to be patched in the work tree,2690 * unless --cached, which tells git to apply only in the index.2691 */2692if(!old_name)2693return0;26942695assert(patch->is_new <=0);26962697if(!(patch->is_copy || patch->is_rename) &&2698(tpatch =in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {2699if(was_deleted(tpatch))2700returnerror("%s: has been deleted/renamed", old_name);2701 st_mode = tpatch->new_mode;2702}else if(!cached) {2703 stat_ret =lstat(old_name, st);2704if(stat_ret && errno != ENOENT)2705returnerror("%s:%s", old_name,strerror(errno));2706}27072708if(to_be_deleted(tpatch))2709 tpatch = NULL;27102711if(check_index && !tpatch) {2712int pos =cache_name_pos(old_name,strlen(old_name));2713if(pos <0) {2714if(patch->is_new <0)2715goto is_new;2716returnerror("%s: does not exist in index", old_name);2717}2718*ce = active_cache[pos];2719if(stat_ret <0) {2720struct checkout costate;2721/* checkout */2722 costate.base_dir ="";2723 costate.base_dir_len =0;2724 costate.force =0;2725 costate.quiet =0;2726 costate.not_new =0;2727 costate.refresh_cache =1;2728if(checkout_entry(*ce, &costate, NULL) ||2729lstat(old_name, st))2730return-1;2731}2732if(!cached &&verify_index_match(*ce, st))2733returnerror("%s: does not match index", old_name);2734if(cached)2735 st_mode = (*ce)->ce_mode;2736}else if(stat_ret <0) {2737if(patch->is_new <0)2738goto is_new;2739returnerror("%s:%s", old_name,strerror(errno));2740}27412742if(!cached && !tpatch)2743 st_mode =ce_mode_from_stat(*ce, st->st_mode);27442745if(patch->is_new <0)2746 patch->is_new =0;2747if(!patch->old_mode)2748 patch->old_mode = st_mode;2749if((st_mode ^ patch->old_mode) & S_IFMT)2750returnerror("%s: wrong type", old_name);2751if(st_mode != patch->old_mode)2752warning("%shas type%o, expected%o",2753 old_name, st_mode, patch->old_mode);2754if(!patch->new_mode && !patch->is_delete)2755 patch->new_mode = st_mode;2756return0;27572758 is_new:2759 patch->is_new =1;2760 patch->is_delete =0;2761 patch->old_name = NULL;2762return0;2763}27642765static intcheck_patch(struct patch *patch)2766{2767struct stat st;2768const char*old_name = patch->old_name;2769const char*new_name = patch->new_name;2770const char*name = old_name ? old_name : new_name;2771struct cache_entry *ce = NULL;2772struct patch *tpatch;2773int ok_if_exists;2774int status;27752776 patch->rejected =1;/* we will drop this after we succeed */27772778 status =check_preimage(patch, &ce, &st);2779if(status)2780return status;2781 old_name = patch->old_name;27822783if((tpatch =in_fn_table(new_name)) &&2784(was_deleted(tpatch) ||to_be_deleted(tpatch)))2785/*2786 * A type-change diff is always split into a patch to2787 * delete old, immediately followed by a patch to2788 * create new (see diff.c::run_diff()); in such a case2789 * it is Ok that the entry to be deleted by the2790 * previous patch is still in the working tree and in2791 * the index.2792 */2793 ok_if_exists =1;2794else2795 ok_if_exists =0;27962797if(new_name &&2798((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {2799if(check_index &&2800cache_name_pos(new_name,strlen(new_name)) >=0&&2801!ok_if_exists)2802returnerror("%s: already exists in index", new_name);2803if(!cached) {2804int err =check_to_create_blob(new_name, ok_if_exists);2805if(err)2806return err;2807}2808if(!patch->new_mode) {2809if(0< patch->is_new)2810 patch->new_mode = S_IFREG |0644;2811else2812 patch->new_mode = patch->old_mode;2813}2814}28152816if(new_name && old_name) {2817int same = !strcmp(old_name, new_name);2818if(!patch->new_mode)2819 patch->new_mode = patch->old_mode;2820if((patch->old_mode ^ patch->new_mode) & S_IFMT)2821returnerror("new mode (%o) of%sdoes not match old mode (%o)%s%s",2822 patch->new_mode, new_name, patch->old_mode,2823 same ?"":" of ", same ?"": old_name);2824}28252826if(apply_data(patch, &st, ce) <0)2827returnerror("%s: patch does not apply", name);2828 patch->rejected =0;2829return0;2830}28312832static intcheck_patch_list(struct patch *patch)2833{2834int err =0;28352836prepare_fn_table(patch);2837while(patch) {2838if(apply_verbosely)2839say_patch_name(stderr,2840"Checking patch ", patch,"...\n");2841 err |=check_patch(patch);2842 patch = patch->next;2843}2844return err;2845}28462847/* This function tries to read the sha1 from the current index */2848static intget_current_sha1(const char*path,unsigned char*sha1)2849{2850int pos;28512852if(read_cache() <0)2853return-1;2854 pos =cache_name_pos(path,strlen(path));2855if(pos <0)2856return-1;2857hashcpy(sha1, active_cache[pos]->sha1);2858return0;2859}28602861/* Build an index that contains the just the files needed for a 3way merge */2862static voidbuild_fake_ancestor(struct patch *list,const char*filename)2863{2864struct patch *patch;2865struct index_state result = { NULL };2866int fd;28672868/* Once we start supporting the reverse patch, it may be2869 * worth showing the new sha1 prefix, but until then...2870 */2871for(patch = list; patch; patch = patch->next) {2872const unsigned char*sha1_ptr;2873unsigned char sha1[20];2874struct cache_entry *ce;2875const char*name;28762877 name = patch->old_name ? patch->old_name : patch->new_name;2878if(0< patch->is_new)2879continue;2880else if(get_sha1(patch->old_sha1_prefix, sha1))2881/* git diff has no index line for mode/type changes */2882if(!patch->lines_added && !patch->lines_deleted) {2883if(get_current_sha1(patch->new_name, sha1) ||2884get_current_sha1(patch->old_name, sha1))2885die("mode change for%s, which is not "2886"in current HEAD", name);2887 sha1_ptr = sha1;2888}else2889die("sha1 information is lacking or useless "2890"(%s).", name);2891else2892 sha1_ptr = sha1;28932894 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);2895if(!ce)2896die("make_cache_entry failed for path '%s'", name);2897if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))2898die("Could not add%sto temporary index", name);2899}29002901 fd =open(filename, O_WRONLY | O_CREAT,0666);2902if(fd <0||write_index(&result, fd) ||close(fd))2903die("Could not write temporary index to%s", filename);29042905discard_index(&result);2906}29072908static voidstat_patch_list(struct patch *patch)2909{2910int files, adds, dels;29112912for(files = adds = dels =0; patch ; patch = patch->next) {2913 files++;2914 adds += patch->lines_added;2915 dels += patch->lines_deleted;2916show_stats(patch);2917}29182919printf("%dfiles changed,%dinsertions(+),%ddeletions(-)\n", files, adds, dels);2920}29212922static voidnumstat_patch_list(struct patch *patch)2923{2924for( ; patch; patch = patch->next) {2925const char*name;2926 name = patch->new_name ? patch->new_name : patch->old_name;2927if(patch->is_binary)2928printf("-\t-\t");2929else2930printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);2931write_name_quoted(name, stdout, line_termination);2932}2933}29342935static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)2936{2937if(mode)2938printf("%smode%06o%s\n", newdelete, mode, name);2939else2940printf("%s %s\n", newdelete, name);2941}29422943static voidshow_mode_change(struct patch *p,int show_name)2944{2945if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {2946if(show_name)2947printf(" mode change%06o =>%06o%s\n",2948 p->old_mode, p->new_mode, p->new_name);2949else2950printf(" mode change%06o =>%06o\n",2951 p->old_mode, p->new_mode);2952}2953}29542955static voidshow_rename_copy(struct patch *p)2956{2957const char*renamecopy = p->is_rename ?"rename":"copy";2958const char*old, *new;29592960/* Find common prefix */2961 old = p->old_name;2962new= p->new_name;2963while(1) {2964const char*slash_old, *slash_new;2965 slash_old =strchr(old,'/');2966 slash_new =strchr(new,'/');2967if(!slash_old ||2968!slash_new ||2969 slash_old - old != slash_new -new||2970memcmp(old,new, slash_new -new))2971break;2972 old = slash_old +1;2973new= slash_new +1;2974}2975/* p->old_name thru old is the common prefix, and old and new2976 * through the end of names are renames2977 */2978if(old != p->old_name)2979printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,2980(int)(old - p->old_name), p->old_name,2981 old,new, p->score);2982else2983printf("%s %s=>%s(%d%%)\n", renamecopy,2984 p->old_name, p->new_name, p->score);2985show_mode_change(p,0);2986}29872988static voidsummary_patch_list(struct patch *patch)2989{2990struct patch *p;29912992for(p = patch; p; p = p->next) {2993if(p->is_new)2994show_file_mode_name("create", p->new_mode, p->new_name);2995else if(p->is_delete)2996show_file_mode_name("delete", p->old_mode, p->old_name);2997else{2998if(p->is_rename || p->is_copy)2999show_rename_copy(p);3000else{3001if(p->score) {3002printf(" rewrite%s(%d%%)\n",3003 p->new_name, p->score);3004show_mode_change(p,0);3005}3006else3007show_mode_change(p,1);3008}3009}3010}3011}30123013static voidpatch_stats(struct patch *patch)3014{3015int lines = patch->lines_added + patch->lines_deleted;30163017if(lines > max_change)3018 max_change = lines;3019if(patch->old_name) {3020int len =quote_c_style(patch->old_name, NULL, NULL,0);3021if(!len)3022 len =strlen(patch->old_name);3023if(len > max_len)3024 max_len = len;3025}3026if(patch->new_name) {3027int len =quote_c_style(patch->new_name, NULL, NULL,0);3028if(!len)3029 len =strlen(patch->new_name);3030if(len > max_len)3031 max_len = len;3032}3033}30343035static voidremove_file(struct patch *patch,int rmdir_empty)3036{3037if(update_index) {3038if(remove_file_from_cache(patch->old_name) <0)3039die("unable to remove%sfrom index", patch->old_name);3040}3041if(!cached) {3042if(S_ISGITLINK(patch->old_mode)) {3043if(rmdir(patch->old_name))3044warning("unable to remove submodule%s",3045 patch->old_name);3046}else if(!unlink_or_warn(patch->old_name) && rmdir_empty) {3047remove_path(patch->old_name);3048}3049}3050}30513052static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)3053{3054struct stat st;3055struct cache_entry *ce;3056int namelen =strlen(path);3057unsigned ce_size =cache_entry_size(namelen);30583059if(!update_index)3060return;30613062 ce =xcalloc(1, ce_size);3063memcpy(ce->name, path, namelen);3064 ce->ce_mode =create_ce_mode(mode);3065 ce->ce_flags = namelen;3066if(S_ISGITLINK(mode)) {3067const char*s = buf;30683069if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))3070die("corrupt patch for subproject%s", path);3071}else{3072if(!cached) {3073if(lstat(path, &st) <0)3074die_errno("unable to stat newly created file '%s'",3075 path);3076fill_stat_cache_info(ce, &st);3077}3078if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)3079die("unable to create backing store for newly created file%s", path);3080}3081if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3082die("unable to add cache entry for%s", path);3083}30843085static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)3086{3087int fd;3088struct strbuf nbuf = STRBUF_INIT;30893090if(S_ISGITLINK(mode)) {3091struct stat st;3092if(!lstat(path, &st) &&S_ISDIR(st.st_mode))3093return0;3094returnmkdir(path,0777);3095}30963097if(has_symlinks &&S_ISLNK(mode))3098/* Although buf:size is counted string, it also is NUL3099 * terminated.3100 */3101returnsymlink(buf, path);31023103 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);3104if(fd <0)3105return-1;31063107if(convert_to_working_tree(path, buf, size, &nbuf)) {3108 size = nbuf.len;3109 buf = nbuf.buf;3110}3111write_or_die(fd, buf, size);3112strbuf_release(&nbuf);31133114if(close(fd) <0)3115die_errno("closing file '%s'", path);3116return0;3117}31183119/*3120 * We optimistically assume that the directories exist,3121 * which is true 99% of the time anyway. If they don't,3122 * we create them and try again.3123 */3124static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)3125{3126if(cached)3127return;3128if(!try_create_file(path, mode, buf, size))3129return;31303131if(errno == ENOENT) {3132if(safe_create_leading_directories(path))3133return;3134if(!try_create_file(path, mode, buf, size))3135return;3136}31373138if(errno == EEXIST || errno == EACCES) {3139/* We may be trying to create a file where a directory3140 * used to be.3141 */3142struct stat st;3143if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))3144 errno = EEXIST;3145}31463147if(errno == EEXIST) {3148unsigned int nr =getpid();31493150for(;;) {3151char newpath[PATH_MAX];3152mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);3153if(!try_create_file(newpath, mode, buf, size)) {3154if(!rename(newpath, path))3155return;3156unlink_or_warn(newpath);3157break;3158}3159if(errno != EEXIST)3160break;3161++nr;3162}3163}3164die_errno("unable to write file '%s' mode%o", path, mode);3165}31663167static voidcreate_file(struct patch *patch)3168{3169char*path = patch->new_name;3170unsigned mode = patch->new_mode;3171unsigned long size = patch->resultsize;3172char*buf = patch->result;31733174if(!mode)3175 mode = S_IFREG |0644;3176create_one_file(path, mode, buf, size);3177add_index_file(path, mode, buf, size);3178}31793180/* phase zero is to remove, phase one is to create */3181static voidwrite_out_one_result(struct patch *patch,int phase)3182{3183if(patch->is_delete >0) {3184if(phase ==0)3185remove_file(patch,1);3186return;3187}3188if(patch->is_new >0|| patch->is_copy) {3189if(phase ==1)3190create_file(patch);3191return;3192}3193/*3194 * Rename or modification boils down to the same3195 * thing: remove the old, write the new3196 */3197if(phase ==0)3198remove_file(patch, patch->is_rename);3199if(phase ==1)3200create_file(patch);3201}32023203static intwrite_out_one_reject(struct patch *patch)3204{3205FILE*rej;3206char namebuf[PATH_MAX];3207struct fragment *frag;3208int cnt =0;32093210for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {3211if(!frag->rejected)3212continue;3213 cnt++;3214}32153216if(!cnt) {3217if(apply_verbosely)3218say_patch_name(stderr,3219"Applied patch ", patch," cleanly.\n");3220return0;3221}32223223/* This should not happen, because a removal patch that leaves3224 * contents are marked "rejected" at the patch level.3225 */3226if(!patch->new_name)3227die("internal error");32283229/* Say this even without --verbose */3230say_patch_name(stderr,"Applying patch ", patch," with");3231fprintf(stderr,"%drejects...\n", cnt);32323233 cnt =strlen(patch->new_name);3234if(ARRAY_SIZE(namebuf) <= cnt +5) {3235 cnt =ARRAY_SIZE(namebuf) -5;3236warning("truncating .rej filename to %.*s.rej",3237 cnt -1, patch->new_name);3238}3239memcpy(namebuf, patch->new_name, cnt);3240memcpy(namebuf + cnt,".rej",5);32413242 rej =fopen(namebuf,"w");3243if(!rej)3244returnerror("cannot open%s:%s", namebuf,strerror(errno));32453246/* Normal git tools never deal with .rej, so do not pretend3247 * this is a git patch by saying --git nor give extended3248 * headers. While at it, maybe please "kompare" that wants3249 * the trailing TAB and some garbage at the end of line ;-).3250 */3251fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",3252 patch->new_name, patch->new_name);3253for(cnt =1, frag = patch->fragments;3254 frag;3255 cnt++, frag = frag->next) {3256if(!frag->rejected) {3257fprintf(stderr,"Hunk #%dapplied cleanly.\n", cnt);3258continue;3259}3260fprintf(stderr,"Rejected hunk #%d.\n", cnt);3261fprintf(rej,"%.*s", frag->size, frag->patch);3262if(frag->patch[frag->size-1] !='\n')3263fputc('\n', rej);3264}3265fclose(rej);3266return-1;3267}32683269static intwrite_out_results(struct patch *list,int skipped_patch)3270{3271int phase;3272int errs =0;3273struct patch *l;32743275if(!list && !skipped_patch)3276returnerror("No changes");32773278for(phase =0; phase <2; phase++) {3279 l = list;3280while(l) {3281if(l->rejected)3282 errs =1;3283else{3284write_out_one_result(l, phase);3285if(phase ==1&&write_out_one_reject(l))3286 errs =1;3287}3288 l = l->next;3289}3290}3291return errs;3292}32933294static struct lock_file lock_file;32953296static struct string_list limit_by_name;3297static int has_include;3298static voidadd_name_limit(const char*name,int exclude)3299{3300struct string_list_item *it;33013302 it =string_list_append(name, &limit_by_name);3303 it->util = exclude ? NULL : (void*)1;3304}33053306static intuse_patch(struct patch *p)3307{3308const char*pathname = p->new_name ? p->new_name : p->old_name;3309int i;33103311/* Paths outside are not touched regardless of "--include" */3312if(0< prefix_length) {3313int pathlen =strlen(pathname);3314if(pathlen <= prefix_length ||3315memcmp(prefix, pathname, prefix_length))3316return0;3317}33183319/* See if it matches any of exclude/include rule */3320for(i =0; i < limit_by_name.nr; i++) {3321struct string_list_item *it = &limit_by_name.items[i];3322if(!fnmatch(it->string, pathname,0))3323return(it->util != NULL);3324}33253326/*3327 * If we had any include, a path that does not match any rule is3328 * not used. Otherwise, we saw bunch of exclude rules (or none)3329 * and such a path is used.3330 */3331return!has_include;3332}333333343335static voidprefix_one(char**name)3336{3337char*old_name = *name;3338if(!old_name)3339return;3340*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3341free(old_name);3342}33433344static voidprefix_patches(struct patch *p)3345{3346if(!prefix || p->is_toplevel_relative)3347return;3348for( ; p; p = p->next) {3349if(p->new_name == p->old_name) {3350char*prefixed = p->new_name;3351prefix_one(&prefixed);3352 p->new_name = p->old_name = prefixed;3353}3354else{3355prefix_one(&p->new_name);3356prefix_one(&p->old_name);3357}3358}3359}33603361#define INACCURATE_EOF (1<<0)3362#define RECOUNT (1<<1)33633364static intapply_patch(int fd,const char*filename,int options)3365{3366size_t offset;3367struct strbuf buf = STRBUF_INIT;3368struct patch *list = NULL, **listp = &list;3369int skipped_patch =0;33703371/* FIXME - memory leak when using multiple patch files as inputs */3372memset(&fn_table,0,sizeof(struct string_list));3373 patch_input_file = filename;3374read_patch_file(&buf, fd);3375 offset =0;3376while(offset < buf.len) {3377struct patch *patch;3378int nr;33793380 patch =xcalloc(1,sizeof(*patch));3381 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3382 patch->recount = !!(options & RECOUNT);3383 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3384if(nr <0)3385break;3386if(apply_in_reverse)3387reverse_patches(patch);3388if(prefix)3389prefix_patches(patch);3390if(use_patch(patch)) {3391patch_stats(patch);3392*listp = patch;3393 listp = &patch->next;3394}3395else{3396/* perhaps free it a bit better? */3397free(patch);3398 skipped_patch++;3399}3400 offset += nr;3401}34023403if(whitespace_error && (ws_error_action == die_on_ws_error))3404 apply =0;34053406 update_index = check_index && apply;3407if(update_index && newfd <0)3408 newfd =hold_locked_index(&lock_file,1);34093410if(check_index) {3411if(read_cache() <0)3412die("unable to read index file");3413}34143415if((check || apply) &&3416check_patch_list(list) <0&&3417!apply_with_reject)3418exit(1);34193420if(apply &&write_out_results(list, skipped_patch))3421exit(1);34223423if(fake_ancestor)3424build_fake_ancestor(list, fake_ancestor);34253426if(diffstat)3427stat_patch_list(list);34283429if(numstat)3430numstat_patch_list(list);34313432if(summary)3433summary_patch_list(list);34343435strbuf_release(&buf);3436return0;3437}34383439static intgit_apply_config(const char*var,const char*value,void*cb)3440{3441if(!strcmp(var,"apply.whitespace"))3442returngit_config_string(&apply_default_whitespace, var, value);3443else if(!strcmp(var,"apply.ignorewhitespace"))3444returngit_config_string(&apply_default_ignorewhitespace, var, value);3445returngit_default_config(var, value, cb);3446}34473448static intoption_parse_exclude(const struct option *opt,3449const char*arg,int unset)3450{3451add_name_limit(arg,1);3452return0;3453}34543455static intoption_parse_include(const struct option *opt,3456const char*arg,int unset)3457{3458add_name_limit(arg,0);3459 has_include =1;3460return0;3461}34623463static intoption_parse_p(const struct option *opt,3464const char*arg,int unset)3465{3466 p_value =atoi(arg);3467 p_value_known =1;3468return0;3469}34703471static intoption_parse_z(const struct option *opt,3472const char*arg,int unset)3473{3474if(unset)3475 line_termination ='\n';3476else3477 line_termination =0;3478return0;3479}34803481static intoption_parse_space_change(const struct option *opt,3482const char*arg,int unset)3483{3484if(unset)3485 ws_ignore_action = ignore_ws_none;3486else3487 ws_ignore_action = ignore_ws_change;3488return0;3489}34903491static intoption_parse_whitespace(const struct option *opt,3492const char*arg,int unset)3493{3494const char**whitespace_option = opt->value;34953496*whitespace_option = arg;3497parse_whitespace_option(arg);3498return0;3499}35003501static intoption_parse_directory(const struct option *opt,3502const char*arg,int unset)3503{3504 root_len =strlen(arg);3505if(root_len && arg[root_len -1] !='/') {3506char*new_root;3507 root = new_root =xmalloc(root_len +2);3508strcpy(new_root, arg);3509strcpy(new_root + root_len++,"/");3510}else3511 root = arg;3512return0;3513}35143515intcmd_apply(int argc,const char**argv,const char*unused_prefix)3516{3517int i;3518int errs =0;3519int is_not_gitdir;3520int binary;3521int force_apply =0;35223523const char*whitespace_option = NULL;35243525struct option builtin_apply_options[] = {3526{ OPTION_CALLBACK,0,"exclude", NULL,"path",3527"don't apply changes matching the given path",35280, option_parse_exclude },3529{ OPTION_CALLBACK,0,"include", NULL,"path",3530"apply changes matching the given path",35310, option_parse_include },3532{ OPTION_CALLBACK,'p', NULL, NULL,"num",3533"remove <num> leading slashes from traditional diff paths",35340, option_parse_p },3535OPT_BOOLEAN(0,"no-add", &no_add,3536"ignore additions made by the patch"),3537OPT_BOOLEAN(0,"stat", &diffstat,3538"instead of applying the patch, output diffstat for the input"),3539{ OPTION_BOOLEAN,0,"allow-binary-replacement", &binary,3540 NULL,"old option, now no-op",3541 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3542{ OPTION_BOOLEAN,0,"binary", &binary,3543 NULL,"old option, now no-op",3544 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3545OPT_BOOLEAN(0,"numstat", &numstat,3546"shows number of added and deleted lines in decimal notation"),3547OPT_BOOLEAN(0,"summary", &summary,3548"instead of applying the patch, output a summary for the input"),3549OPT_BOOLEAN(0,"check", &check,3550"instead of applying the patch, see if the patch is applicable"),3551OPT_BOOLEAN(0,"index", &check_index,3552"make sure the patch is applicable to the current index"),3553OPT_BOOLEAN(0,"cached", &cached,3554"apply a patch without touching the working tree"),3555OPT_BOOLEAN(0,"apply", &force_apply,3556"also apply the patch (use with --stat/--summary/--check)"),3557OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,3558"build a temporary index based on embedded index information"),3559{ OPTION_CALLBACK,'z', NULL, NULL, NULL,3560"paths are separated with NUL character",3561 PARSE_OPT_NOARG, option_parse_z },3562OPT_INTEGER('C', NULL, &p_context,3563"ensure at least <n> lines of context match"),3564{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,"action",3565"detect new or modified lines that have whitespace errors",35660, option_parse_whitespace },3567{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,3568"ignore changes in whitespace when finding context",3569 PARSE_OPT_NOARG, option_parse_space_change },3570{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,3571"ignore changes in whitespace when finding context",3572 PARSE_OPT_NOARG, option_parse_space_change },3573OPT_BOOLEAN('R',"reverse", &apply_in_reverse,3574"apply the patch in reverse"),3575OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,3576"don't expect at least one line of context"),3577OPT_BOOLEAN(0,"reject", &apply_with_reject,3578"leave the rejected hunks in corresponding *.rej files"),3579OPT__VERBOSE(&apply_verbosely),3580OPT_BIT(0,"inaccurate-eof", &options,3581"tolerate incorrectly detected missing new-line at the end of file",3582 INACCURATE_EOF),3583OPT_BIT(0,"recount", &options,3584"do not trust the line counts in the hunk headers",3585 RECOUNT),3586{ OPTION_CALLBACK,0,"directory", NULL,"root",3587"prepend <root> to all filenames",35880, option_parse_directory },3589OPT_END()3590};35913592 prefix =setup_git_directory_gently(&is_not_gitdir);3593 prefix_length = prefix ?strlen(prefix) :0;3594git_config(git_apply_config, NULL);3595if(apply_default_whitespace)3596parse_whitespace_option(apply_default_whitespace);3597if(apply_default_ignorewhitespace)3598parse_ignorewhitespace_option(apply_default_ignorewhitespace);35993600 argc =parse_options(argc, argv, prefix, builtin_apply_options,3601 apply_usage,0);36023603if(apply_with_reject)3604 apply = apply_verbosely =1;3605if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))3606 apply =0;3607if(check_index && is_not_gitdir)3608die("--index outside a repository");3609if(cached) {3610if(is_not_gitdir)3611die("--cached outside a repository");3612 check_index =1;3613}3614for(i =0; i < argc; i++) {3615const char*arg = argv[i];3616int fd;36173618if(!strcmp(arg,"-")) {3619 errs |=apply_patch(0,"<stdin>", options);3620 read_stdin =0;3621continue;3622}else if(0< prefix_length)3623 arg =prefix_filename(prefix, prefix_length, arg);36243625 fd =open(arg, O_RDONLY);3626if(fd <0)3627die_errno("can't open patch '%s'", arg);3628 read_stdin =0;3629set_default_whitespace_mode(whitespace_option);3630 errs |=apply_patch(fd, arg, options);3631close(fd);3632}3633set_default_whitespace_mode(whitespace_option);3634if(read_stdin)3635 errs |=apply_patch(0,"<stdin>", options);3636if(whitespace_error) {3637if(squelch_whitespace_errors &&3638 squelch_whitespace_errors < whitespace_error) {3639int squelched =3640 whitespace_error - squelch_whitespace_errors;3641warning("squelched%d"3642"whitespace error%s",3643 squelched,3644 squelched ==1?"":"s");3645}3646if(ws_error_action == die_on_ws_error)3647die("%dline%sadd%swhitespace errors.",3648 whitespace_error,3649 whitespace_error ==1?"":"s",3650 whitespace_error ==1?"s":"");3651if(applied_after_fixing_ws && apply)3652warning("%dline%sapplied after"3653" fixing whitespace errors.",3654 applied_after_fixing_ws,3655 applied_after_fixing_ws ==1?"":"s");3656else if(whitespace_error)3657warning("%dline%sadd%swhitespace errors.",3658 whitespace_error,3659 whitespace_error ==1?"":"s",3660 whitespace_error ==1?"s":"");3661}36623663if(update_index) {3664if(write_cache(newfd, active_cache, active_nr) ||3665commit_locked_index(&lock_file))3666die("Unable to write new index file");3667}36683669return!!errs;3670}