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; 156struct fragment *next; 157}; 158 159/* 160 * When dealing with a binary patch, we reuse "leading" field 161 * to store the type of the binary hunk, either deflated "delta" 162 * or deflated "literal". 163 */ 164#define binary_patch_method leading 165#define BINARY_DELTA_DEFLATED 1 166#define BINARY_LITERAL_DEFLATED 2 167 168/* 169 * This represents a "patch" to a file, both metainfo changes 170 * such as creation/deletion, filemode and content changes represented 171 * as a series of fragments. 172 */ 173struct patch { 174char*new_name, *old_name, *def_name; 175unsigned int old_mode, new_mode; 176int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 177int rejected; 178unsigned ws_rule; 179unsigned long deflate_origlen; 180int lines_added, lines_deleted; 181int score; 182unsigned int is_toplevel_relative:1; 183unsigned int inaccurate_eof:1; 184unsigned int is_binary:1; 185unsigned int is_copy:1; 186unsigned int is_rename:1; 187unsigned int recount:1; 188struct fragment *fragments; 189char*result; 190size_t resultsize; 191char old_sha1_prefix[41]; 192char new_sha1_prefix[41]; 193struct patch *next; 194}; 195 196/* 197 * A line in a file, len-bytes long (includes the terminating LF, 198 * except for an incomplete line at the end if the file ends with 199 * one), and its contents hashes to 'hash'. 200 */ 201struct line { 202size_t len; 203unsigned hash :24; 204unsigned flag :8; 205#define LINE_COMMON 1 206}; 207 208/* 209 * This represents a "file", which is an array of "lines". 210 */ 211struct image { 212char*buf; 213size_t len; 214size_t nr; 215size_t alloc; 216struct line *line_allocated; 217struct line *line; 218}; 219 220/* 221 * Records filenames that have been touched, in order to handle 222 * the case where more than one patches touch the same file. 223 */ 224 225static struct string_list fn_table; 226 227static uint32_thash_line(const char*cp,size_t len) 228{ 229size_t i; 230uint32_t h; 231for(i =0, h =0; i < len; i++) { 232if(!isspace(cp[i])) { 233 h = h *3+ (cp[i] &0xff); 234} 235} 236return h; 237} 238 239/* 240 * Compare lines s1 of length n1 and s2 of length n2, ignoring 241 * whitespace difference. Returns 1 if they match, 0 otherwise 242 */ 243static intfuzzy_matchlines(const char*s1,size_t n1, 244const char*s2,size_t n2) 245{ 246const char*last1 = s1 + n1 -1; 247const char*last2 = s2 + n2 -1; 248int result =0; 249 250if(n1 <0|| n2 <0) 251return0; 252 253/* ignore line endings */ 254while((*last1 =='\r') || (*last1 =='\n')) 255 last1--; 256while((*last2 =='\r') || (*last2 =='\n')) 257 last2--; 258 259/* skip leading whitespace */ 260while(isspace(*s1) && (s1 <= last1)) 261 s1++; 262while(isspace(*s2) && (s2 <= last2)) 263 s2++; 264/* early return if both lines are empty */ 265if((s1 > last1) && (s2 > last2)) 266return1; 267while(!result) { 268 result = *s1++ - *s2++; 269/* 270 * Skip whitespace inside. We check for whitespace on 271 * both buffers because we don't want "a b" to match 272 * "ab" 273 */ 274if(isspace(*s1) &&isspace(*s2)) { 275while(isspace(*s1) && s1 <= last1) 276 s1++; 277while(isspace(*s2) && s2 <= last2) 278 s2++; 279} 280/* 281 * If we reached the end on one side only, 282 * lines don't match 283 */ 284if( 285((s2 > last2) && (s1 <= last1)) || 286((s1 > last1) && (s2 <= last2))) 287return0; 288if((s1 > last1) && (s2 > last2)) 289break; 290} 291 292return!result; 293} 294 295static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 296{ 297ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 298 img->line_allocated[img->nr].len = len; 299 img->line_allocated[img->nr].hash =hash_line(bol, len); 300 img->line_allocated[img->nr].flag = flag; 301 img->nr++; 302} 303 304static voidprepare_image(struct image *image,char*buf,size_t len, 305int prepare_linetable) 306{ 307const char*cp, *ep; 308 309memset(image,0,sizeof(*image)); 310 image->buf = buf; 311 image->len = len; 312 313if(!prepare_linetable) 314return; 315 316 ep = image->buf + image->len; 317 cp = image->buf; 318while(cp < ep) { 319const char*next; 320for(next = cp; next < ep && *next !='\n'; next++) 321; 322if(next < ep) 323 next++; 324add_line_info(image, cp, next - cp,0); 325 cp = next; 326} 327 image->line = image->line_allocated; 328} 329 330static voidclear_image(struct image *image) 331{ 332free(image->buf); 333 image->buf = NULL; 334 image->len =0; 335} 336 337static voidsay_patch_name(FILE*output,const char*pre, 338struct patch *patch,const char*post) 339{ 340fputs(pre, output); 341if(patch->old_name && patch->new_name && 342strcmp(patch->old_name, patch->new_name)) { 343quote_c_style(patch->old_name, NULL, output,0); 344fputs(" => ", output); 345quote_c_style(patch->new_name, NULL, output,0); 346}else{ 347const char*n = patch->new_name; 348if(!n) 349 n = patch->old_name; 350quote_c_style(n, NULL, output,0); 351} 352fputs(post, output); 353} 354 355#define CHUNKSIZE (8192) 356#define SLOP (16) 357 358static voidread_patch_file(struct strbuf *sb,int fd) 359{ 360if(strbuf_read(sb, fd,0) <0) 361die_errno("git apply: failed to read"); 362 363/* 364 * Make sure that we have some slop in the buffer 365 * so that we can do speculative "memcmp" etc, and 366 * see to it that it is NUL-filled. 367 */ 368strbuf_grow(sb, SLOP); 369memset(sb->buf + sb->len,0, SLOP); 370} 371 372static unsigned longlinelen(const char*buffer,unsigned long size) 373{ 374unsigned long len =0; 375while(size--) { 376 len++; 377if(*buffer++ =='\n') 378break; 379} 380return len; 381} 382 383static intis_dev_null(const char*str) 384{ 385return!memcmp("/dev/null", str,9) &&isspace(str[9]); 386} 387 388#define TERM_SPACE 1 389#define TERM_TAB 2 390 391static intname_terminate(const char*name,int namelen,int c,int terminate) 392{ 393if(c ==' '&& !(terminate & TERM_SPACE)) 394return0; 395if(c =='\t'&& !(terminate & TERM_TAB)) 396return0; 397 398return1; 399} 400 401/* remove double slashes to make --index work with such filenames */ 402static char*squash_slash(char*name) 403{ 404int i =0, j =0; 405 406while(name[i]) { 407if((name[j++] = name[i++]) =='/') 408while(name[i] =='/') 409 i++; 410} 411 name[j] ='\0'; 412return name; 413} 414 415static char*find_name(const char*line,char*def,int p_value,int terminate) 416{ 417int len; 418const char*start = line; 419 420if(*line =='"') { 421struct strbuf name = STRBUF_INIT; 422 423/* 424 * Proposed "new-style" GNU patch/diff format; see 425 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2 426 */ 427if(!unquote_c_style(&name, line, NULL)) { 428char*cp; 429 430for(cp = name.buf; p_value; p_value--) { 431 cp =strchr(cp,'/'); 432if(!cp) 433break; 434 cp++; 435} 436if(cp) { 437/* name can later be freed, so we need 438 * to memmove, not just return cp 439 */ 440strbuf_remove(&name,0, cp - name.buf); 441free(def); 442if(root) 443strbuf_insert(&name,0, root, root_len); 444returnsquash_slash(strbuf_detach(&name, NULL)); 445} 446} 447strbuf_release(&name); 448} 449 450for(;;) { 451char c = *line; 452 453if(isspace(c)) { 454if(c =='\n') 455break; 456if(name_terminate(start, line-start, c, terminate)) 457break; 458} 459 line++; 460if(c =='/'&& !--p_value) 461 start = line; 462} 463if(!start) 464returnsquash_slash(def); 465 len = line - start; 466if(!len) 467returnsquash_slash(def); 468 469/* 470 * Generally we prefer the shorter name, especially 471 * if the other one is just a variation of that with 472 * something else tacked on to the end (ie "file.orig" 473 * or "file~"). 474 */ 475if(def) { 476int deflen =strlen(def); 477if(deflen < len && !strncmp(start, def, deflen)) 478returnsquash_slash(def); 479free(def); 480} 481 482if(root) { 483char*ret =xmalloc(root_len + len +1); 484strcpy(ret, root); 485memcpy(ret + root_len, start, len); 486 ret[root_len + len] ='\0'; 487returnsquash_slash(ret); 488} 489 490returnsquash_slash(xmemdupz(start, len)); 491} 492 493static intcount_slashes(const char*cp) 494{ 495int cnt =0; 496char ch; 497 498while((ch = *cp++)) 499if(ch =='/') 500 cnt++; 501return cnt; 502} 503 504/* 505 * Given the string after "--- " or "+++ ", guess the appropriate 506 * p_value for the given patch. 507 */ 508static intguess_p_value(const char*nameline) 509{ 510char*name, *cp; 511int val = -1; 512 513if(is_dev_null(nameline)) 514return-1; 515 name =find_name(nameline, NULL,0, TERM_SPACE | TERM_TAB); 516if(!name) 517return-1; 518 cp =strchr(name,'/'); 519if(!cp) 520 val =0; 521else if(prefix) { 522/* 523 * Does it begin with "a/$our-prefix" and such? Then this is 524 * very likely to apply to our directory. 525 */ 526if(!strncmp(name, prefix, prefix_length)) 527 val =count_slashes(prefix); 528else{ 529 cp++; 530if(!strncmp(cp, prefix, prefix_length)) 531 val =count_slashes(prefix) +1; 532} 533} 534free(name); 535return val; 536} 537 538/* 539 * Does the ---/+++ line has the POSIX timestamp after the last HT? 540 * GNU diff puts epoch there to signal a creation/deletion event. Is 541 * this such a timestamp? 542 */ 543static inthas_epoch_timestamp(const char*nameline) 544{ 545/* 546 * We are only interested in epoch timestamp; any non-zero 547 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 548 * For the same reason, the date must be either 1969-12-31 or 549 * 1970-01-01, and the seconds part must be "00". 550 */ 551const char stamp_regexp[] = 552"^(1969-12-31|1970-01-01)" 553" " 554"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 555" " 556"([-+][0-2][0-9][0-5][0-9])\n"; 557const char*timestamp = NULL, *cp; 558static regex_t *stamp; 559 regmatch_t m[10]; 560int zoneoffset; 561int hourminute; 562int status; 563 564for(cp = nameline; *cp !='\n'; cp++) { 565if(*cp =='\t') 566 timestamp = cp +1; 567} 568if(!timestamp) 569return0; 570if(!stamp) { 571 stamp =xmalloc(sizeof(*stamp)); 572if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 573warning("Cannot prepare timestamp regexp%s", 574 stamp_regexp); 575return0; 576} 577} 578 579 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 580if(status) { 581if(status != REG_NOMATCH) 582warning("regexec returned%dfor input:%s", 583 status, timestamp); 584return0; 585} 586 587 zoneoffset =strtol(timestamp + m[3].rm_so +1, NULL,10); 588 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 589if(timestamp[m[3].rm_so] =='-') 590 zoneoffset = -zoneoffset; 591 592/* 593 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 594 * (west of GMT) or 1970-01-01 (east of GMT) 595 */ 596if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 597(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 598return0; 599 600 hourminute = (strtol(timestamp +11, NULL,10) *60+ 601strtol(timestamp +14, NULL,10) - 602 zoneoffset); 603 604return((zoneoffset <0&& hourminute ==1440) || 605(0<= zoneoffset && !hourminute)); 606} 607 608/* 609 * Get the name etc info from the ---/+++ lines of a traditional patch header 610 * 611 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 612 * files, we can happily check the index for a match, but for creating a 613 * new file we should try to match whatever "patch" does. I have no idea. 614 */ 615static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 616{ 617char*name; 618 619 first +=4;/* skip "--- " */ 620 second +=4;/* skip "+++ " */ 621if(!p_value_known) { 622int p, q; 623 p =guess_p_value(first); 624 q =guess_p_value(second); 625if(p <0) p = q; 626if(0<= p && p == q) { 627 p_value = p; 628 p_value_known =1; 629} 630} 631if(is_dev_null(first)) { 632 patch->is_new =1; 633 patch->is_delete =0; 634 name =find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB); 635 patch->new_name = name; 636}else if(is_dev_null(second)) { 637 patch->is_new =0; 638 patch->is_delete =1; 639 name =find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB); 640 patch->old_name = name; 641}else{ 642 name =find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB); 643 name =find_name(second, name, p_value, TERM_SPACE | TERM_TAB); 644if(has_epoch_timestamp(first)) { 645 patch->is_new =1; 646 patch->is_delete =0; 647 patch->new_name = name; 648}else if(has_epoch_timestamp(second)) { 649 patch->is_new =0; 650 patch->is_delete =1; 651 patch->old_name = name; 652}else{ 653 patch->old_name = patch->new_name = name; 654} 655} 656if(!name) 657die("unable to find filename in patch at line%d", linenr); 658} 659 660static intgitdiff_hdrend(const char*line,struct patch *patch) 661{ 662return-1; 663} 664 665/* 666 * We're anal about diff header consistency, to make 667 * sure that we don't end up having strange ambiguous 668 * patches floating around. 669 * 670 * As a result, gitdiff_{old|new}name() will check 671 * their names against any previous information, just 672 * to make sure.. 673 */ 674static char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,const char*oldnew) 675{ 676if(!orig_name && !isnull) 677returnfind_name(line, NULL, p_value, TERM_TAB); 678 679if(orig_name) { 680int len; 681const char*name; 682char*another; 683 name = orig_name; 684 len =strlen(name); 685if(isnull) 686die("git apply: bad git-diff - expected /dev/null, got%son line%d", name, linenr); 687 another =find_name(line, NULL, p_value, TERM_TAB); 688if(!another ||memcmp(another, name, len)) 689die("git apply: bad git-diff - inconsistent%sfilename on line%d", oldnew, linenr); 690free(another); 691return orig_name; 692} 693else{ 694/* expect "/dev/null" */ 695if(memcmp("/dev/null", line,9) || line[9] !='\n') 696die("git apply: bad git-diff - expected /dev/null on line%d", linenr); 697return NULL; 698} 699} 700 701static intgitdiff_oldname(const char*line,struct patch *patch) 702{ 703 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name,"old"); 704return0; 705} 706 707static intgitdiff_newname(const char*line,struct patch *patch) 708{ 709 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name,"new"); 710return0; 711} 712 713static intgitdiff_oldmode(const char*line,struct patch *patch) 714{ 715 patch->old_mode =strtoul(line, NULL,8); 716return0; 717} 718 719static intgitdiff_newmode(const char*line,struct patch *patch) 720{ 721 patch->new_mode =strtoul(line, NULL,8); 722return0; 723} 724 725static intgitdiff_delete(const char*line,struct patch *patch) 726{ 727 patch->is_delete =1; 728 patch->old_name = patch->def_name; 729returngitdiff_oldmode(line, patch); 730} 731 732static intgitdiff_newfile(const char*line,struct patch *patch) 733{ 734 patch->is_new =1; 735 patch->new_name = patch->def_name; 736returngitdiff_newmode(line, patch); 737} 738 739static intgitdiff_copysrc(const char*line,struct patch *patch) 740{ 741 patch->is_copy =1; 742 patch->old_name =find_name(line, NULL,0,0); 743return0; 744} 745 746static intgitdiff_copydst(const char*line,struct patch *patch) 747{ 748 patch->is_copy =1; 749 patch->new_name =find_name(line, NULL,0,0); 750return0; 751} 752 753static intgitdiff_renamesrc(const char*line,struct patch *patch) 754{ 755 patch->is_rename =1; 756 patch->old_name =find_name(line, NULL,0,0); 757return0; 758} 759 760static intgitdiff_renamedst(const char*line,struct patch *patch) 761{ 762 patch->is_rename =1; 763 patch->new_name =find_name(line, NULL,0,0); 764return0; 765} 766 767static intgitdiff_similarity(const char*line,struct patch *patch) 768{ 769if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 770 patch->score =0; 771return0; 772} 773 774static intgitdiff_dissimilarity(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_index(const char*line,struct patch *patch) 782{ 783/* 784 * index line is N hexadecimal, "..", N hexadecimal, 785 * and optional space with octal mode. 786 */ 787const char*ptr, *eol; 788int len; 789 790 ptr =strchr(line,'.'); 791if(!ptr || ptr[1] !='.'||40< ptr - line) 792return0; 793 len = ptr - line; 794memcpy(patch->old_sha1_prefix, line, len); 795 patch->old_sha1_prefix[len] =0; 796 797 line = ptr +2; 798 ptr =strchr(line,' '); 799 eol =strchr(line,'\n'); 800 801if(!ptr || eol < ptr) 802 ptr = eol; 803 len = ptr - line; 804 805if(40< len) 806return0; 807memcpy(patch->new_sha1_prefix, line, len); 808 patch->new_sha1_prefix[len] =0; 809if(*ptr ==' ') 810 patch->old_mode =strtoul(ptr+1, NULL,8); 811return0; 812} 813 814/* 815 * This is normal for a diff that doesn't change anything: we'll fall through 816 * into the next diff. Tell the parser to break out. 817 */ 818static intgitdiff_unrecognized(const char*line,struct patch *patch) 819{ 820return-1; 821} 822 823static const char*stop_at_slash(const char*line,int llen) 824{ 825int i; 826 827for(i =0; i < llen; i++) { 828int ch = line[i]; 829if(ch =='/') 830return line + i; 831} 832return NULL; 833} 834 835/* 836 * This is to extract the same name that appears on "diff --git" 837 * line. We do not find and return anything if it is a rename 838 * patch, and it is OK because we will find the name elsewhere. 839 * We need to reliably find name only when it is mode-change only, 840 * creation or deletion of an empty file. In any of these cases, 841 * both sides are the same name under a/ and b/ respectively. 842 */ 843static char*git_header_name(char*line,int llen) 844{ 845const char*name; 846const char*second = NULL; 847size_t len; 848 849 line +=strlen("diff --git "); 850 llen -=strlen("diff --git "); 851 852if(*line =='"') { 853const char*cp; 854struct strbuf first = STRBUF_INIT; 855struct strbuf sp = STRBUF_INIT; 856 857if(unquote_c_style(&first, line, &second)) 858goto free_and_fail1; 859 860/* advance to the first slash */ 861 cp =stop_at_slash(first.buf, first.len); 862/* we do not accept absolute paths */ 863if(!cp || cp == first.buf) 864goto free_and_fail1; 865strbuf_remove(&first,0, cp +1- first.buf); 866 867/* 868 * second points at one past closing dq of name. 869 * find the second name. 870 */ 871while((second < line + llen) &&isspace(*second)) 872 second++; 873 874if(line + llen <= second) 875goto free_and_fail1; 876if(*second =='"') { 877if(unquote_c_style(&sp, second, NULL)) 878goto free_and_fail1; 879 cp =stop_at_slash(sp.buf, sp.len); 880if(!cp || cp == sp.buf) 881goto free_and_fail1; 882/* They must match, otherwise ignore */ 883if(strcmp(cp +1, first.buf)) 884goto free_and_fail1; 885strbuf_release(&sp); 886returnstrbuf_detach(&first, NULL); 887} 888 889/* unquoted second */ 890 cp =stop_at_slash(second, line + llen - second); 891if(!cp || cp == second) 892goto free_and_fail1; 893 cp++; 894if(line + llen - cp != first.len +1|| 895memcmp(first.buf, cp, first.len)) 896goto free_and_fail1; 897returnstrbuf_detach(&first, NULL); 898 899 free_and_fail1: 900strbuf_release(&first); 901strbuf_release(&sp); 902return NULL; 903} 904 905/* unquoted first name */ 906 name =stop_at_slash(line, llen); 907if(!name || name == line) 908return NULL; 909 name++; 910 911/* 912 * since the first name is unquoted, a dq if exists must be 913 * the beginning of the second name. 914 */ 915for(second = name; second < line + llen; second++) { 916if(*second =='"') { 917struct strbuf sp = STRBUF_INIT; 918const char*np; 919 920if(unquote_c_style(&sp, second, NULL)) 921goto free_and_fail2; 922 923 np =stop_at_slash(sp.buf, sp.len); 924if(!np || np == sp.buf) 925goto free_and_fail2; 926 np++; 927 928 len = sp.buf + sp.len - np; 929if(len < second - name && 930!strncmp(np, name, len) && 931isspace(name[len])) { 932/* Good */ 933strbuf_remove(&sp,0, np - sp.buf); 934returnstrbuf_detach(&sp, NULL); 935} 936 937 free_and_fail2: 938strbuf_release(&sp); 939return NULL; 940} 941} 942 943/* 944 * Accept a name only if it shows up twice, exactly the same 945 * form. 946 */ 947for(len =0; ; len++) { 948switch(name[len]) { 949default: 950continue; 951case'\n': 952return NULL; 953case'\t':case' ': 954 second = name+len; 955for(;;) { 956char c = *second++; 957if(c =='\n') 958return NULL; 959if(c =='/') 960break; 961} 962if(second[len] =='\n'&& !memcmp(name, second, len)) { 963returnxmemdupz(name, len); 964} 965} 966} 967} 968 969/* Verify that we recognize the lines following a git header */ 970static intparse_git_header(char*line,int len,unsigned int size,struct patch *patch) 971{ 972unsigned long offset; 973 974/* A git diff has explicit new/delete information, so we don't guess */ 975 patch->is_new =0; 976 patch->is_delete =0; 977 978/* 979 * Some things may not have the old name in the 980 * rest of the headers anywhere (pure mode changes, 981 * or removing or adding empty files), so we get 982 * the default name from the header. 983 */ 984 patch->def_name =git_header_name(line, len); 985if(patch->def_name && root) { 986char*s =xmalloc(root_len +strlen(patch->def_name) +1); 987strcpy(s, root); 988strcpy(s + root_len, patch->def_name); 989free(patch->def_name); 990 patch->def_name = s; 991} 992 993 line += len; 994 size -= len; 995 linenr++; 996for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) { 997static const struct opentry { 998const char*str; 999int(*fn)(const char*,struct patch *);1000} optable[] = {1001{"@@ -", gitdiff_hdrend },1002{"--- ", gitdiff_oldname },1003{"+++ ", gitdiff_newname },1004{"old mode ", gitdiff_oldmode },1005{"new mode ", gitdiff_newmode },1006{"deleted file mode ", gitdiff_delete },1007{"new file mode ", gitdiff_newfile },1008{"copy from ", gitdiff_copysrc },1009{"copy to ", gitdiff_copydst },1010{"rename old ", gitdiff_renamesrc },1011{"rename new ", gitdiff_renamedst },1012{"rename from ", gitdiff_renamesrc },1013{"rename to ", gitdiff_renamedst },1014{"similarity index ", gitdiff_similarity },1015{"dissimilarity index ", gitdiff_dissimilarity },1016{"index ", gitdiff_index },1017{"", gitdiff_unrecognized },1018};1019int i;10201021 len =linelen(line, size);1022if(!len || line[len-1] !='\n')1023break;1024for(i =0; i <ARRAY_SIZE(optable); i++) {1025const struct opentry *p = optable + i;1026int oplen =strlen(p->str);1027if(len < oplen ||memcmp(p->str, line, oplen))1028continue;1029if(p->fn(line + oplen, patch) <0)1030return offset;1031break;1032}1033}10341035return offset;1036}10371038static intparse_num(const char*line,unsigned long*p)1039{1040char*ptr;10411042if(!isdigit(*line))1043return0;1044*p =strtoul(line, &ptr,10);1045return ptr - line;1046}10471048static intparse_range(const char*line,int len,int offset,const char*expect,1049unsigned long*p1,unsigned long*p2)1050{1051int digits, ex;10521053if(offset <0|| offset >= len)1054return-1;1055 line += offset;1056 len -= offset;10571058 digits =parse_num(line, p1);1059if(!digits)1060return-1;10611062 offset += digits;1063 line += digits;1064 len -= digits;10651066*p2 =1;1067if(*line ==',') {1068 digits =parse_num(line+1, p2);1069if(!digits)1070return-1;10711072 offset += digits+1;1073 line += digits+1;1074 len -= digits+1;1075}10761077 ex =strlen(expect);1078if(ex > len)1079return-1;1080if(memcmp(line, expect, ex))1081return-1;10821083return offset + ex;1084}10851086static voidrecount_diff(char*line,int size,struct fragment *fragment)1087{1088int oldlines =0, newlines =0, ret =0;10891090if(size <1) {1091warning("recount: ignore empty hunk");1092return;1093}10941095for(;;) {1096int len =linelen(line, size);1097 size -= len;1098 line += len;10991100if(size <1)1101break;11021103switch(*line) {1104case' ':case'\n':1105 newlines++;1106/* fall through */1107case'-':1108 oldlines++;1109continue;1110case'+':1111 newlines++;1112continue;1113case'\\':1114continue;1115case'@':1116 ret = size <3||prefixcmp(line,"@@ ");1117break;1118case'd':1119 ret = size <5||prefixcmp(line,"diff ");1120break;1121default:1122 ret = -1;1123break;1124}1125if(ret) {1126warning("recount: unexpected line: %.*s",1127(int)linelen(line, size), line);1128return;1129}1130break;1131}1132 fragment->oldlines = oldlines;1133 fragment->newlines = newlines;1134}11351136/*1137 * Parse a unified diff fragment header of the1138 * form "@@ -a,b +c,d @@"1139 */1140static intparse_fragment_header(char*line,int len,struct fragment *fragment)1141{1142int offset;11431144if(!len || line[len-1] !='\n')1145return-1;11461147/* Figure out the number of lines in a fragment */1148 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1149 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);11501151return offset;1152}11531154static intfind_header(char*line,unsigned long size,int*hdrsize,struct patch *patch)1155{1156unsigned long offset, len;11571158 patch->is_toplevel_relative =0;1159 patch->is_rename = patch->is_copy =0;1160 patch->is_new = patch->is_delete = -1;1161 patch->old_mode = patch->new_mode =0;1162 patch->old_name = patch->new_name = NULL;1163for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1164unsigned long nextlen;11651166 len =linelen(line, size);1167if(!len)1168break;11691170/* Testing this early allows us to take a few shortcuts.. */1171if(len <6)1172continue;11731174/*1175 * Make sure we don't find any unconnected patch fragments.1176 * That's a sign that we didn't find a header, and that a1177 * patch has become corrupted/broken up.1178 */1179if(!memcmp("@@ -", line,4)) {1180struct fragment dummy;1181if(parse_fragment_header(line, len, &dummy) <0)1182continue;1183die("patch fragment without header at line%d: %.*s",1184 linenr, (int)len-1, line);1185}11861187if(size < len +6)1188break;11891190/*1191 * Git patch? It might not have a real patch, just a rename1192 * or mode change, so we handle that specially1193 */1194if(!memcmp("diff --git ", line,11)) {1195int git_hdr_len =parse_git_header(line, len, size, patch);1196if(git_hdr_len <= len)1197continue;1198if(!patch->old_name && !patch->new_name) {1199if(!patch->def_name)1200die("git diff header lacks filename information (line%d)", linenr);1201 patch->old_name = patch->new_name = patch->def_name;1202}1203 patch->is_toplevel_relative =1;1204*hdrsize = git_hdr_len;1205return offset;1206}12071208/* --- followed by +++ ? */1209if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1210continue;12111212/*1213 * We only accept unified patches, so we want it to1214 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1215 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1216 */1217 nextlen =linelen(line + len, size - len);1218if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1219continue;12201221/* Ok, we'll consider it a patch */1222parse_traditional_patch(line, line+len, patch);1223*hdrsize = len + nextlen;1224 linenr +=2;1225return offset;1226}1227return-1;1228}12291230static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1231{1232char*err;1233unsigned result =ws_check(line +1, len -1, ws_rule);1234if(!result)1235return;12361237 whitespace_error++;1238if(squelch_whitespace_errors &&1239 squelch_whitespace_errors < whitespace_error)1240;1241else{1242 err =whitespace_error_string(result);1243fprintf(stderr,"%s:%d:%s.\n%.*s\n",1244 patch_input_file, linenr, err, len -2, line +1);1245free(err);1246}1247}12481249/*1250 * Parse a unified diff. Note that this really needs to parse each1251 * fragment separately, since the only way to know the difference1252 * between a "---" that is part of a patch, and a "---" that starts1253 * the next patch is to look at the line counts..1254 */1255static intparse_fragment(char*line,unsigned long size,1256struct patch *patch,struct fragment *fragment)1257{1258int added, deleted;1259int len =linelen(line, size), offset;1260unsigned long oldlines, newlines;1261unsigned long leading, trailing;12621263 offset =parse_fragment_header(line, len, fragment);1264if(offset <0)1265return-1;1266if(offset >0&& patch->recount)1267recount_diff(line + offset, size - offset, fragment);1268 oldlines = fragment->oldlines;1269 newlines = fragment->newlines;1270 leading =0;1271 trailing =0;12721273/* Parse the thing.. */1274 line += len;1275 size -= len;1276 linenr++;1277 added = deleted =0;1278for(offset = len;12790< size;1280 offset += len, size -= len, line += len, linenr++) {1281if(!oldlines && !newlines)1282break;1283 len =linelen(line, size);1284if(!len || line[len-1] !='\n')1285return-1;1286switch(*line) {1287default:1288return-1;1289case'\n':/* newer GNU diff, an empty context line */1290case' ':1291 oldlines--;1292 newlines--;1293if(!deleted && !added)1294 leading++;1295 trailing++;1296break;1297case'-':1298if(apply_in_reverse &&1299 ws_error_action != nowarn_ws_error)1300check_whitespace(line, len, patch->ws_rule);1301 deleted++;1302 oldlines--;1303 trailing =0;1304break;1305case'+':1306if(!apply_in_reverse &&1307 ws_error_action != nowarn_ws_error)1308check_whitespace(line, len, patch->ws_rule);1309 added++;1310 newlines--;1311 trailing =0;1312break;13131314/*1315 * We allow "\ No newline at end of file". Depending1316 * on locale settings when the patch was produced we1317 * don't know what this line looks like. The only1318 * thing we do know is that it begins with "\ ".1319 * Checking for 12 is just for sanity check -- any1320 * l10n of "\ No newline..." is at least that long.1321 */1322case'\\':1323if(len <12||memcmp(line,"\\",2))1324return-1;1325break;1326}1327}1328if(oldlines || newlines)1329return-1;1330 fragment->leading = leading;1331 fragment->trailing = trailing;13321333/*1334 * If a fragment ends with an incomplete line, we failed to include1335 * it in the above loop because we hit oldlines == newlines == 01336 * before seeing it.1337 */1338if(12< size && !memcmp(line,"\\",2))1339 offset +=linelen(line, size);13401341 patch->lines_added += added;1342 patch->lines_deleted += deleted;13431344if(0< patch->is_new && oldlines)1345returnerror("new file depends on old contents");1346if(0< patch->is_delete && newlines)1347returnerror("deleted file still has contents");1348return offset;1349}13501351static intparse_single_patch(char*line,unsigned long size,struct patch *patch)1352{1353unsigned long offset =0;1354unsigned long oldlines =0, newlines =0, context =0;1355struct fragment **fragp = &patch->fragments;13561357while(size >4&& !memcmp(line,"@@ -",4)) {1358struct fragment *fragment;1359int len;13601361 fragment =xcalloc(1,sizeof(*fragment));1362 len =parse_fragment(line, size, patch, fragment);1363if(len <=0)1364die("corrupt patch at line%d", linenr);1365 fragment->patch = line;1366 fragment->size = len;1367 oldlines += fragment->oldlines;1368 newlines += fragment->newlines;1369 context += fragment->leading + fragment->trailing;13701371*fragp = fragment;1372 fragp = &fragment->next;13731374 offset += len;1375 line += len;1376 size -= len;1377}13781379/*1380 * If something was removed (i.e. we have old-lines) it cannot1381 * be creation, and if something was added it cannot be1382 * deletion. However, the reverse is not true; --unified=01383 * patches that only add are not necessarily creation even1384 * though they do not have any old lines, and ones that only1385 * delete are not necessarily deletion.1386 *1387 * Unfortunately, a real creation/deletion patch do _not_ have1388 * any context line by definition, so we cannot safely tell it1389 * apart with --unified=0 insanity. At least if the patch has1390 * more than one hunk it is not creation or deletion.1391 */1392if(patch->is_new <0&&1393(oldlines || (patch->fragments && patch->fragments->next)))1394 patch->is_new =0;1395if(patch->is_delete <0&&1396(newlines || (patch->fragments && patch->fragments->next)))1397 patch->is_delete =0;13981399if(0< patch->is_new && oldlines)1400die("new file%sdepends on old contents", patch->new_name);1401if(0< patch->is_delete && newlines)1402die("deleted file%sstill has contents", patch->old_name);1403if(!patch->is_delete && !newlines && context)1404fprintf(stderr,"** warning: file%sbecomes empty but "1405"is not deleted\n", patch->new_name);14061407return offset;1408}14091410staticinlineintmetadata_changes(struct patch *patch)1411{1412return patch->is_rename >0||1413 patch->is_copy >0||1414 patch->is_new >0||1415 patch->is_delete ||1416(patch->old_mode && patch->new_mode &&1417 patch->old_mode != patch->new_mode);1418}14191420static char*inflate_it(const void*data,unsigned long size,1421unsigned long inflated_size)1422{1423 z_stream stream;1424void*out;1425int st;14261427memset(&stream,0,sizeof(stream));14281429 stream.next_in = (unsigned char*)data;1430 stream.avail_in = size;1431 stream.next_out = out =xmalloc(inflated_size);1432 stream.avail_out = inflated_size;1433git_inflate_init(&stream);1434 st =git_inflate(&stream, Z_FINISH);1435git_inflate_end(&stream);1436if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1437free(out);1438return NULL;1439}1440return out;1441}14421443static struct fragment *parse_binary_hunk(char**buf_p,1444unsigned long*sz_p,1445int*status_p,1446int*used_p)1447{1448/*1449 * Expect a line that begins with binary patch method ("literal"1450 * or "delta"), followed by the length of data before deflating.1451 * a sequence of 'length-byte' followed by base-85 encoded data1452 * should follow, terminated by a newline.1453 *1454 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1455 * and we would limit the patch line to 66 characters,1456 * so one line can fit up to 13 groups that would decode1457 * to 52 bytes max. The length byte 'A'-'Z' corresponds1458 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1459 */1460int llen, used;1461unsigned long size = *sz_p;1462char*buffer = *buf_p;1463int patch_method;1464unsigned long origlen;1465char*data = NULL;1466int hunk_size =0;1467struct fragment *frag;14681469 llen =linelen(buffer, size);1470 used = llen;14711472*status_p =0;14731474if(!prefixcmp(buffer,"delta ")) {1475 patch_method = BINARY_DELTA_DEFLATED;1476 origlen =strtoul(buffer +6, NULL,10);1477}1478else if(!prefixcmp(buffer,"literal ")) {1479 patch_method = BINARY_LITERAL_DEFLATED;1480 origlen =strtoul(buffer +8, NULL,10);1481}1482else1483return NULL;14841485 linenr++;1486 buffer += llen;1487while(1) {1488int byte_length, max_byte_length, newsize;1489 llen =linelen(buffer, size);1490 used += llen;1491 linenr++;1492if(llen ==1) {1493/* consume the blank line */1494 buffer++;1495 size--;1496break;1497}1498/*1499 * Minimum line is "A00000\n" which is 7-byte long,1500 * and the line length must be multiple of 5 plus 2.1501 */1502if((llen <7) || (llen-2) %5)1503goto corrupt;1504 max_byte_length = (llen -2) /5*4;1505 byte_length = *buffer;1506if('A'<= byte_length && byte_length <='Z')1507 byte_length = byte_length -'A'+1;1508else if('a'<= byte_length && byte_length <='z')1509 byte_length = byte_length -'a'+27;1510else1511goto corrupt;1512/* if the input length was not multiple of 4, we would1513 * have filler at the end but the filler should never1514 * exceed 3 bytes1515 */1516if(max_byte_length < byte_length ||1517 byte_length <= max_byte_length -4)1518goto corrupt;1519 newsize = hunk_size + byte_length;1520 data =xrealloc(data, newsize);1521if(decode_85(data + hunk_size, buffer +1, byte_length))1522goto corrupt;1523 hunk_size = newsize;1524 buffer += llen;1525 size -= llen;1526}15271528 frag =xcalloc(1,sizeof(*frag));1529 frag->patch =inflate_it(data, hunk_size, origlen);1530if(!frag->patch)1531goto corrupt;1532free(data);1533 frag->size = origlen;1534*buf_p = buffer;1535*sz_p = size;1536*used_p = used;1537 frag->binary_patch_method = patch_method;1538return frag;15391540 corrupt:1541free(data);1542*status_p = -1;1543error("corrupt binary patch at line%d: %.*s",1544 linenr-1, llen-1, buffer);1545return NULL;1546}15471548static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1549{1550/*1551 * We have read "GIT binary patch\n"; what follows is a line1552 * that says the patch method (currently, either "literal" or1553 * "delta") and the length of data before deflating; a1554 * sequence of 'length-byte' followed by base-85 encoded data1555 * follows.1556 *1557 * When a binary patch is reversible, there is another binary1558 * hunk in the same format, starting with patch method (either1559 * "literal" or "delta") with the length of data, and a sequence1560 * of length-byte + base-85 encoded data, terminated with another1561 * empty line. This data, when applied to the postimage, produces1562 * the preimage.1563 */1564struct fragment *forward;1565struct fragment *reverse;1566int status;1567int used, used_1;15681569 forward =parse_binary_hunk(&buffer, &size, &status, &used);1570if(!forward && !status)1571/* there has to be one hunk (forward hunk) */1572returnerror("unrecognized binary patch at line%d", linenr-1);1573if(status)1574/* otherwise we already gave an error message */1575return status;15761577 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1578if(reverse)1579 used += used_1;1580else if(status) {1581/*1582 * Not having reverse hunk is not an error, but having1583 * a corrupt reverse hunk is.1584 */1585free((void*) forward->patch);1586free(forward);1587return status;1588}1589 forward->next = reverse;1590 patch->fragments = forward;1591 patch->is_binary =1;1592return used;1593}15941595static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1596{1597int hdrsize, patchsize;1598int offset =find_header(buffer, size, &hdrsize, patch);15991600if(offset <0)1601return offset;16021603 patch->ws_rule =whitespace_rule(patch->new_name1604? patch->new_name1605: patch->old_name);16061607 patchsize =parse_single_patch(buffer + offset + hdrsize,1608 size - offset - hdrsize, patch);16091610if(!patchsize) {1611static const char*binhdr[] = {1612"Binary files ",1613"Files ",1614 NULL,1615};1616static const char git_binary[] ="GIT binary patch\n";1617int i;1618int hd = hdrsize + offset;1619unsigned long llen =linelen(buffer + hd, size - hd);16201621if(llen ==sizeof(git_binary) -1&&1622!memcmp(git_binary, buffer + hd, llen)) {1623int used;1624 linenr++;1625 used =parse_binary(buffer + hd + llen,1626 size - hd - llen, patch);1627if(used)1628 patchsize = used + llen;1629else1630 patchsize =0;1631}1632else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1633for(i =0; binhdr[i]; i++) {1634int len =strlen(binhdr[i]);1635if(len < size - hd &&1636!memcmp(binhdr[i], buffer + hd, len)) {1637 linenr++;1638 patch->is_binary =1;1639 patchsize = llen;1640break;1641}1642}1643}16441645/* Empty patch cannot be applied if it is a text patch1646 * without metadata change. A binary patch appears1647 * empty to us here.1648 */1649if((apply || check) &&1650(!patch->is_binary && !metadata_changes(patch)))1651die("patch with only garbage at line%d", linenr);1652}16531654return offset + hdrsize + patchsize;1655}16561657#define swap(a,b) myswap((a),(b),sizeof(a))16581659#define myswap(a, b, size) do { \1660 unsigned char mytmp[size]; \1661 memcpy(mytmp, &a, size); \1662 memcpy(&a, &b, size); \1663 memcpy(&b, mytmp, size); \1664} while (0)16651666static voidreverse_patches(struct patch *p)1667{1668for(; p; p = p->next) {1669struct fragment *frag = p->fragments;16701671swap(p->new_name, p->old_name);1672swap(p->new_mode, p->old_mode);1673swap(p->is_new, p->is_delete);1674swap(p->lines_added, p->lines_deleted);1675swap(p->old_sha1_prefix, p->new_sha1_prefix);16761677for(; frag; frag = frag->next) {1678swap(frag->newpos, frag->oldpos);1679swap(frag->newlines, frag->oldlines);1680}1681}1682}16831684static const char pluses[] =1685"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";1686static const char minuses[]=1687"----------------------------------------------------------------------";16881689static voidshow_stats(struct patch *patch)1690{1691struct strbuf qname = STRBUF_INIT;1692char*cp = patch->new_name ? patch->new_name : patch->old_name;1693int max, add, del;16941695quote_c_style(cp, &qname, NULL,0);16961697/*1698 * "scale" the filename1699 */1700 max = max_len;1701if(max >50)1702 max =50;17031704if(qname.len > max) {1705 cp =strchr(qname.buf + qname.len +3- max,'/');1706if(!cp)1707 cp = qname.buf + qname.len +3- max;1708strbuf_splice(&qname,0, cp - qname.buf,"...",3);1709}17101711if(patch->is_binary) {1712printf(" %-*s | Bin\n", max, qname.buf);1713strbuf_release(&qname);1714return;1715}17161717printf(" %-*s |", max, qname.buf);1718strbuf_release(&qname);17191720/*1721 * scale the add/delete1722 */1723 max = max + max_change >70?70- max : max_change;1724 add = patch->lines_added;1725 del = patch->lines_deleted;17261727if(max_change >0) {1728int total = ((add + del) * max + max_change /2) / max_change;1729 add = (add * max + max_change /2) / max_change;1730 del = total - add;1731}1732printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,1733 add, pluses, del, minuses);1734}17351736static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)1737{1738switch(st->st_mode & S_IFMT) {1739case S_IFLNK:1740if(strbuf_readlink(buf, path, st->st_size) <0)1741returnerror("unable to read symlink%s", path);1742return0;1743case S_IFREG:1744if(strbuf_read_file(buf, path, st->st_size) != st->st_size)1745returnerror("unable to open or read%s", path);1746convert_to_git(path, buf->buf, buf->len, buf,0);1747return0;1748default:1749return-1;1750}1751}17521753/*1754 * Update the preimage, and the common lines in postimage,1755 * from buffer buf of length len. If postlen is 0 the postimage1756 * is updated in place, otherwise it's updated on a new buffer1757 * of length postlen1758 */17591760static voidupdate_pre_post_images(struct image *preimage,1761struct image *postimage,1762char*buf,1763size_t len,size_t postlen)1764{1765int i, ctx;1766char*new, *old, *fixed;1767struct image fixed_preimage;17681769/*1770 * Update the preimage with whitespace fixes. Note that we1771 * are not losing preimage->buf -- apply_one_fragment() will1772 * free "oldlines".1773 */1774prepare_image(&fixed_preimage, buf, len,1);1775assert(fixed_preimage.nr == preimage->nr);1776for(i =0; i < preimage->nr; i++)1777 fixed_preimage.line[i].flag = preimage->line[i].flag;1778free(preimage->line_allocated);1779*preimage = fixed_preimage;17801781/*1782 * Adjust the common context lines in postimage. This can be1783 * done in-place when we are just doing whitespace fixing,1784 * which does not make the string grow, but needs a new buffer1785 * when ignoring whitespace causes the update, since in this case1786 * we could have e.g. tabs converted to multiple spaces.1787 * We trust the caller to tell us if the update can be done1788 * in place (postlen==0) or not.1789 */1790 old = postimage->buf;1791if(postlen)1792new= postimage->buf =xmalloc(postlen);1793else1794new= old;1795 fixed = preimage->buf;1796for(i = ctx =0; i < postimage->nr; i++) {1797size_t len = postimage->line[i].len;1798if(!(postimage->line[i].flag & LINE_COMMON)) {1799/* an added line -- no counterparts in preimage */1800memmove(new, old, len);1801 old += len;1802new+= len;1803continue;1804}18051806/* a common context -- skip it in the original postimage */1807 old += len;18081809/* and find the corresponding one in the fixed preimage */1810while(ctx < preimage->nr &&1811!(preimage->line[ctx].flag & LINE_COMMON)) {1812 fixed += preimage->line[ctx].len;1813 ctx++;1814}1815if(preimage->nr <= ctx)1816die("oops");18171818/* and copy it in, while fixing the line length */1819 len = preimage->line[ctx].len;1820memcpy(new, fixed, len);1821new+= len;1822 fixed += len;1823 postimage->line[i].len = len;1824 ctx++;1825}18261827/* Fix the length of the whole thing */1828 postimage->len =new- postimage->buf;1829}18301831static intmatch_fragment(struct image *img,1832struct image *preimage,1833struct image *postimage,1834unsigned longtry,1835int try_lno,1836unsigned ws_rule,1837int match_beginning,int match_end)1838{1839int i;1840char*fixed_buf, *buf, *orig, *target;18411842if(preimage->nr + try_lno > img->nr)1843return0;18441845if(match_beginning && try_lno)1846return0;18471848if(match_end && preimage->nr + try_lno != img->nr)1849return0;18501851/* Quick hash check */1852for(i =0; i < preimage->nr; i++)1853if(preimage->line[i].hash != img->line[try_lno + i].hash)1854return0;18551856/*1857 * Do we have an exact match? If we were told to match1858 * at the end, size must be exactly at try+fragsize,1859 * otherwise try+fragsize must be still within the preimage,1860 * and either case, the old piece should match the preimage1861 * exactly.1862 */1863if((match_end1864? (try+ preimage->len == img->len)1865: (try+ preimage->len <= img->len)) &&1866!memcmp(img->buf +try, preimage->buf, preimage->len))1867return1;18681869/*1870 * No exact match. If we are ignoring whitespace, run a line-by-line1871 * fuzzy matching. We collect all the line length information because1872 * we need it to adjust whitespace if we match.1873 */1874if(ws_ignore_action == ignore_ws_change) {1875size_t imgoff =0;1876size_t preoff =0;1877size_t postlen = postimage->len;1878for(i =0; i < preimage->nr; i++) {1879size_t prelen = preimage->line[i].len;1880size_t imglen = img->line[try_lno+i].len;18811882if(!fuzzy_matchlines(img->buf +try+ imgoff, imglen,1883 preimage->buf + preoff, prelen))1884return0;1885if(preimage->line[i].flag & LINE_COMMON)1886 postlen += imglen - prelen;1887 imgoff += imglen;1888 preoff += prelen;1889}18901891/*1892 * Ok, the preimage matches with whitespace fuzz. Update it and1893 * the common postimage lines to use the same whitespace as the1894 * target. imgoff now holds the true length of the target that1895 * matches the preimage, and we need to update the line lengths1896 * of the preimage to match the target ones.1897 */1898 fixed_buf =xmalloc(imgoff);1899memcpy(fixed_buf, img->buf +try, imgoff);1900for(i =0; i < preimage->nr; i++)1901 preimage->line[i].len = img->line[try_lno+i].len;19021903/*1904 * Update the preimage buffer and the postimage context lines.1905 */1906update_pre_post_images(preimage, postimage,1907 fixed_buf, imgoff, postlen);1908return1;1909}19101911if(ws_error_action != correct_ws_error)1912return0;19131914/*1915 * The hunk does not apply byte-by-byte, but the hash says1916 * it might with whitespace fuzz. We haven't been asked to1917 * ignore whitespace, we were asked to correct whitespace1918 * errors, so let's try matching after whitespace correction.1919 */1920 fixed_buf =xmalloc(preimage->len +1);1921 buf = fixed_buf;1922 orig = preimage->buf;1923 target = img->buf +try;1924for(i =0; i < preimage->nr; i++) {1925size_t fixlen;/* length after fixing the preimage */1926size_t oldlen = preimage->line[i].len;1927size_t tgtlen = img->line[try_lno + i].len;1928size_t tgtfixlen;/* length after fixing the target line */1929char tgtfixbuf[1024], *tgtfix;1930int match;19311932/* Try fixing the line in the preimage */1933 fixlen =ws_fix_copy(buf, orig, oldlen, ws_rule, NULL);19341935/* Try fixing the line in the target */1936if(sizeof(tgtfixbuf) > tgtlen)1937 tgtfix = tgtfixbuf;1938else1939 tgtfix =xmalloc(tgtlen);1940 tgtfixlen =ws_fix_copy(tgtfix, target, tgtlen, ws_rule, NULL);19411942/*1943 * If they match, either the preimage was based on1944 * a version before our tree fixed whitespace breakage,1945 * or we are lacking a whitespace-fix patch the tree1946 * the preimage was based on already had (i.e. target1947 * has whitespace breakage, the preimage doesn't).1948 * In either case, we are fixing the whitespace breakages1949 * so we might as well take the fix together with their1950 * real change.1951 */1952 match = (tgtfixlen == fixlen && !memcmp(tgtfix, buf, fixlen));19531954if(tgtfix != tgtfixbuf)1955free(tgtfix);1956if(!match)1957goto unmatch_exit;19581959 orig += oldlen;1960 buf += fixlen;1961 target += tgtlen;1962}19631964/*1965 * Yes, the preimage is based on an older version that still1966 * has whitespace breakages unfixed, and fixing them makes the1967 * hunk match. Update the context lines in the postimage.1968 */1969update_pre_post_images(preimage, postimage,1970 fixed_buf, buf - fixed_buf,0);1971return1;19721973 unmatch_exit:1974free(fixed_buf);1975return0;1976}19771978static intfind_pos(struct image *img,1979struct image *preimage,1980struct image *postimage,1981int line,1982unsigned ws_rule,1983int match_beginning,int match_end)1984{1985int i;1986unsigned long backwards, forwards,try;1987int backwards_lno, forwards_lno, try_lno;19881989if(preimage->nr > img->nr)1990return-1;19911992/*1993 * If match_begining or match_end is specified, there is no1994 * point starting from a wrong line that will never match and1995 * wander around and wait for a match at the specified end.1996 */1997if(match_beginning)1998 line =0;1999else if(match_end)2000 line = img->nr - preimage->nr;20012002if(line > img->nr)2003 line = img->nr;20042005try=0;2006for(i =0; i < line; i++)2007try+= img->line[i].len;20082009/*2010 * There's probably some smart way to do this, but I'll leave2011 * that to the smart and beautiful people. I'm simple and stupid.2012 */2013 backwards =try;2014 backwards_lno = line;2015 forwards =try;2016 forwards_lno = line;2017 try_lno = line;20182019for(i =0; ; i++) {2020if(match_fragment(img, preimage, postimage,2021try, try_lno, ws_rule,2022 match_beginning, match_end))2023return try_lno;20242025 again:2026if(backwards_lno ==0&& forwards_lno == img->nr)2027break;20282029if(i &1) {2030if(backwards_lno ==0) {2031 i++;2032goto again;2033}2034 backwards_lno--;2035 backwards -= img->line[backwards_lno].len;2036try= backwards;2037 try_lno = backwards_lno;2038}else{2039if(forwards_lno == img->nr) {2040 i++;2041goto again;2042}2043 forwards += img->line[forwards_lno].len;2044 forwards_lno++;2045try= forwards;2046 try_lno = forwards_lno;2047}20482049}2050return-1;2051}20522053static voidremove_first_line(struct image *img)2054{2055 img->buf += img->line[0].len;2056 img->len -= img->line[0].len;2057 img->line++;2058 img->nr--;2059}20602061static voidremove_last_line(struct image *img)2062{2063 img->len -= img->line[--img->nr].len;2064}20652066static voidupdate_image(struct image *img,2067int applied_pos,2068struct image *preimage,2069struct image *postimage)2070{2071/*2072 * remove the copy of preimage at offset in img2073 * and replace it with postimage2074 */2075int i, nr;2076size_t remove_count, insert_count, applied_at =0;2077char*result;20782079for(i =0; i < applied_pos; i++)2080 applied_at += img->line[i].len;20812082 remove_count =0;2083for(i =0; i < preimage->nr; i++)2084 remove_count += img->line[applied_pos + i].len;2085 insert_count = postimage->len;20862087/* Adjust the contents */2088 result =xmalloc(img->len + insert_count - remove_count +1);2089memcpy(result, img->buf, applied_at);2090memcpy(result + applied_at, postimage->buf, postimage->len);2091memcpy(result + applied_at + postimage->len,2092 img->buf + (applied_at + remove_count),2093 img->len - (applied_at + remove_count));2094free(img->buf);2095 img->buf = result;2096 img->len += insert_count - remove_count;2097 result[img->len] ='\0';20982099/* Adjust the line table */2100 nr = img->nr + postimage->nr - preimage->nr;2101if(preimage->nr < postimage->nr) {2102/*2103 * NOTE: this knows that we never call remove_first_line()2104 * on anything other than pre/post image.2105 */2106 img->line =xrealloc(img->line, nr *sizeof(*img->line));2107 img->line_allocated = img->line;2108}2109if(preimage->nr != postimage->nr)2110memmove(img->line + applied_pos + postimage->nr,2111 img->line + applied_pos + preimage->nr,2112(img->nr - (applied_pos + preimage->nr)) *2113sizeof(*img->line));2114memcpy(img->line + applied_pos,2115 postimage->line,2116 postimage->nr *sizeof(*img->line));2117 img->nr = nr;2118}21192120static intapply_one_fragment(struct image *img,struct fragment *frag,2121int inaccurate_eof,unsigned ws_rule)2122{2123int match_beginning, match_end;2124const char*patch = frag->patch;2125int size = frag->size;2126char*old, *new, *oldlines, *newlines;2127int new_blank_lines_at_end =0;2128unsigned long leading, trailing;2129int pos, applied_pos;2130struct image preimage;2131struct image postimage;21322133memset(&preimage,0,sizeof(preimage));2134memset(&postimage,0,sizeof(postimage));2135 oldlines =xmalloc(size);2136 newlines =xmalloc(size);21372138 old = oldlines;2139new= newlines;2140while(size >0) {2141char first;2142int len =linelen(patch, size);2143int plen, added;2144int added_blank_line =0;21452146if(!len)2147break;21482149/*2150 * "plen" is how much of the line we should use for2151 * the actual patch data. Normally we just remove the2152 * first character on the line, but if the line is2153 * followed by "\ No newline", then we also remove the2154 * last one (which is the newline, of course).2155 */2156 plen = len -1;2157if(len < size && patch[len] =='\\')2158 plen--;2159 first = *patch;2160if(apply_in_reverse) {2161if(first =='-')2162 first ='+';2163else if(first =='+')2164 first ='-';2165}21662167switch(first) {2168case'\n':2169/* Newer GNU diff, empty context line */2170if(plen <0)2171/* ... followed by '\No newline'; nothing */2172break;2173*old++ ='\n';2174*new++ ='\n';2175add_line_info(&preimage,"\n",1, LINE_COMMON);2176add_line_info(&postimage,"\n",1, LINE_COMMON);2177break;2178case' ':2179case'-':2180memcpy(old, patch +1, plen);2181add_line_info(&preimage, old, plen,2182(first ==' '? LINE_COMMON :0));2183 old += plen;2184if(first =='-')2185break;2186/* Fall-through for ' ' */2187case'+':2188/* --no-add does not add new lines */2189if(first =='+'&& no_add)2190break;21912192if(first !='+'||2193!whitespace_error ||2194 ws_error_action != correct_ws_error) {2195memcpy(new, patch +1, plen);2196 added = plen;2197}2198else{2199 added =ws_fix_copy(new, patch +1, plen, ws_rule, &applied_after_fixing_ws);2200}2201add_line_info(&postimage,new, added,2202(first =='+'?0: LINE_COMMON));2203new+= added;2204if(first =='+'&&2205 added ==1&&new[-1] =='\n')2206 added_blank_line =1;2207break;2208case'@':case'\\':2209/* Ignore it, we already handled it */2210break;2211default:2212if(apply_verbosely)2213error("invalid start of line: '%c'", first);2214return-1;2215}2216if(added_blank_line)2217 new_blank_lines_at_end++;2218else2219 new_blank_lines_at_end =0;2220 patch += len;2221 size -= len;2222}2223if(inaccurate_eof &&2224 old > oldlines && old[-1] =='\n'&&2225new> newlines &&new[-1] =='\n') {2226 old--;2227new--;2228}22292230 leading = frag->leading;2231 trailing = frag->trailing;22322233/*2234 * A hunk to change lines at the beginning would begin with2235 * @@ -1,L +N,M @@2236 * but we need to be careful. -U0 that inserts before the second2237 * line also has this pattern.2238 *2239 * And a hunk to add to an empty file would begin with2240 * @@ -0,0 +N,M @@2241 *2242 * In other words, a hunk that is (frag->oldpos <= 1) with or2243 * without leading context must match at the beginning.2244 */2245 match_beginning = (!frag->oldpos ||2246(frag->oldpos ==1&& !unidiff_zero));22472248/*2249 * A hunk without trailing lines must match at the end.2250 * However, we simply cannot tell if a hunk must match end2251 * from the lack of trailing lines if the patch was generated2252 * with unidiff without any context.2253 */2254 match_end = !unidiff_zero && !trailing;22552256 pos = frag->newpos ? (frag->newpos -1) :0;2257 preimage.buf = oldlines;2258 preimage.len = old - oldlines;2259 postimage.buf = newlines;2260 postimage.len =new- newlines;2261 preimage.line = preimage.line_allocated;2262 postimage.line = postimage.line_allocated;22632264for(;;) {22652266 applied_pos =find_pos(img, &preimage, &postimage, pos,2267 ws_rule, match_beginning, match_end);22682269if(applied_pos >=0)2270break;22712272/* Am I at my context limits? */2273if((leading <= p_context) && (trailing <= p_context))2274break;2275if(match_beginning || match_end) {2276 match_beginning = match_end =0;2277continue;2278}22792280/*2281 * Reduce the number of context lines; reduce both2282 * leading and trailing if they are equal otherwise2283 * just reduce the larger context.2284 */2285if(leading >= trailing) {2286remove_first_line(&preimage);2287remove_first_line(&postimage);2288 pos--;2289 leading--;2290}2291if(trailing > leading) {2292remove_last_line(&preimage);2293remove_last_line(&postimage);2294 trailing--;2295}2296}22972298if(applied_pos >=0) {2299if(ws_error_action == correct_ws_error &&2300 new_blank_lines_at_end &&2301 postimage.nr + applied_pos == img->nr) {2302/*2303 * If the patch application adds blank lines2304 * at the end, and if the patch applies at the2305 * end of the image, remove those added blank2306 * lines.2307 */2308while(new_blank_lines_at_end--)2309remove_last_line(&postimage);2310}23112312/*2313 * Warn if it was necessary to reduce the number2314 * of context lines.2315 */2316if((leading != frag->leading) ||2317(trailing != frag->trailing))2318fprintf(stderr,"Context reduced to (%ld/%ld)"2319" to apply fragment at%d\n",2320 leading, trailing, applied_pos+1);2321update_image(img, applied_pos, &preimage, &postimage);2322}else{2323if(apply_verbosely)2324error("while searching for:\n%.*s",2325(int)(old - oldlines), oldlines);2326}23272328free(oldlines);2329free(newlines);2330free(preimage.line_allocated);2331free(postimage.line_allocated);23322333return(applied_pos <0);2334}23352336static intapply_binary_fragment(struct image *img,struct patch *patch)2337{2338struct fragment *fragment = patch->fragments;2339unsigned long len;2340void*dst;23412342/* Binary patch is irreversible without the optional second hunk */2343if(apply_in_reverse) {2344if(!fragment->next)2345returnerror("cannot reverse-apply a binary patch "2346"without the reverse hunk to '%s'",2347 patch->new_name2348? patch->new_name : patch->old_name);2349 fragment = fragment->next;2350}2351switch(fragment->binary_patch_method) {2352case BINARY_DELTA_DEFLATED:2353 dst =patch_delta(img->buf, img->len, fragment->patch,2354 fragment->size, &len);2355if(!dst)2356return-1;2357clear_image(img);2358 img->buf = dst;2359 img->len = len;2360return0;2361case BINARY_LITERAL_DEFLATED:2362clear_image(img);2363 img->len = fragment->size;2364 img->buf =xmalloc(img->len+1);2365memcpy(img->buf, fragment->patch, img->len);2366 img->buf[img->len] ='\0';2367return0;2368}2369return-1;2370}23712372static intapply_binary(struct image *img,struct patch *patch)2373{2374const char*name = patch->old_name ? patch->old_name : patch->new_name;2375unsigned char sha1[20];23762377/*2378 * For safety, we require patch index line to contain2379 * full 40-byte textual SHA1 for old and new, at least for now.2380 */2381if(strlen(patch->old_sha1_prefix) !=40||2382strlen(patch->new_sha1_prefix) !=40||2383get_sha1_hex(patch->old_sha1_prefix, sha1) ||2384get_sha1_hex(patch->new_sha1_prefix, sha1))2385returnerror("cannot apply binary patch to '%s' "2386"without full index line", name);23872388if(patch->old_name) {2389/*2390 * See if the old one matches what the patch2391 * applies to.2392 */2393hash_sha1_file(img->buf, img->len, blob_type, sha1);2394if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2395returnerror("the patch applies to '%s' (%s), "2396"which does not match the "2397"current contents.",2398 name,sha1_to_hex(sha1));2399}2400else{2401/* Otherwise, the old one must be empty. */2402if(img->len)2403returnerror("the patch applies to an empty "2404"'%s' but it is not empty", name);2405}24062407get_sha1_hex(patch->new_sha1_prefix, sha1);2408if(is_null_sha1(sha1)) {2409clear_image(img);2410return0;/* deletion patch */2411}24122413if(has_sha1_file(sha1)) {2414/* We already have the postimage */2415enum object_type type;2416unsigned long size;2417char*result;24182419 result =read_sha1_file(sha1, &type, &size);2420if(!result)2421returnerror("the necessary postimage%sfor "2422"'%s' cannot be read",2423 patch->new_sha1_prefix, name);2424clear_image(img);2425 img->buf = result;2426 img->len = size;2427}else{2428/*2429 * We have verified buf matches the preimage;2430 * apply the patch data to it, which is stored2431 * in the patch->fragments->{patch,size}.2432 */2433if(apply_binary_fragment(img, patch))2434returnerror("binary patch does not apply to '%s'",2435 name);24362437/* verify that the result matches */2438hash_sha1_file(img->buf, img->len, blob_type, sha1);2439if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2440returnerror("binary patch to '%s' creates incorrect result (expecting%s, got%s)",2441 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2442}24432444return0;2445}24462447static intapply_fragments(struct image *img,struct patch *patch)2448{2449struct fragment *frag = patch->fragments;2450const char*name = patch->old_name ? patch->old_name : patch->new_name;2451unsigned ws_rule = patch->ws_rule;2452unsigned inaccurate_eof = patch->inaccurate_eof;24532454if(patch->is_binary)2455returnapply_binary(img, patch);24562457while(frag) {2458if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule)) {2459error("patch failed:%s:%ld", name, frag->oldpos);2460if(!apply_with_reject)2461return-1;2462 frag->rejected =1;2463}2464 frag = frag->next;2465}2466return0;2467}24682469static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2470{2471if(!ce)2472return0;24732474if(S_ISGITLINK(ce->ce_mode)) {2475strbuf_grow(buf,100);2476strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2477}else{2478enum object_type type;2479unsigned long sz;2480char*result;24812482 result =read_sha1_file(ce->sha1, &type, &sz);2483if(!result)2484return-1;2485/* XXX read_sha1_file NUL-terminates */2486strbuf_attach(buf, result, sz, sz +1);2487}2488return0;2489}24902491static struct patch *in_fn_table(const char*name)2492{2493struct string_list_item *item;24942495if(name == NULL)2496return NULL;24972498 item =string_list_lookup(name, &fn_table);2499if(item != NULL)2500return(struct patch *)item->util;25012502return NULL;2503}25042505/*2506 * item->util in the filename table records the status of the path.2507 * Usually it points at a patch (whose result records the contents2508 * of it after applying it), but it could be PATH_WAS_DELETED for a2509 * path that a previously applied patch has already removed.2510 */2511#define PATH_TO_BE_DELETED ((struct patch *) -2)2512#define PATH_WAS_DELETED ((struct patch *) -1)25132514static intto_be_deleted(struct patch *patch)2515{2516return patch == PATH_TO_BE_DELETED;2517}25182519static intwas_deleted(struct patch *patch)2520{2521return patch == PATH_WAS_DELETED;2522}25232524static voidadd_to_fn_table(struct patch *patch)2525{2526struct string_list_item *item;25272528/*2529 * Always add new_name unless patch is a deletion2530 * This should cover the cases for normal diffs,2531 * file creations and copies2532 */2533if(patch->new_name != NULL) {2534 item =string_list_insert(patch->new_name, &fn_table);2535 item->util = patch;2536}25372538/*2539 * store a failure on rename/deletion cases because2540 * later chunks shouldn't patch old names2541 */2542if((patch->new_name == NULL) || (patch->is_rename)) {2543 item =string_list_insert(patch->old_name, &fn_table);2544 item->util = PATH_WAS_DELETED;2545}2546}25472548static voidprepare_fn_table(struct patch *patch)2549{2550/*2551 * store information about incoming file deletion2552 */2553while(patch) {2554if((patch->new_name == NULL) || (patch->is_rename)) {2555struct string_list_item *item;2556 item =string_list_insert(patch->old_name, &fn_table);2557 item->util = PATH_TO_BE_DELETED;2558}2559 patch = patch->next;2560}2561}25622563static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)2564{2565struct strbuf buf = STRBUF_INIT;2566struct image image;2567size_t len;2568char*img;2569struct patch *tpatch;25702571if(!(patch->is_copy || patch->is_rename) &&2572(tpatch =in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {2573if(was_deleted(tpatch)) {2574returnerror("patch%shas been renamed/deleted",2575 patch->old_name);2576}2577/* We have a patched copy in memory use that */2578strbuf_add(&buf, tpatch->result, tpatch->resultsize);2579}else if(cached) {2580if(read_file_or_gitlink(ce, &buf))2581returnerror("read of%sfailed", patch->old_name);2582}else if(patch->old_name) {2583if(S_ISGITLINK(patch->old_mode)) {2584if(ce) {2585read_file_or_gitlink(ce, &buf);2586}else{2587/*2588 * There is no way to apply subproject2589 * patch without looking at the index.2590 */2591 patch->fragments = NULL;2592}2593}else{2594if(read_old_data(st, patch->old_name, &buf))2595returnerror("read of%sfailed", patch->old_name);2596}2597}25982599 img =strbuf_detach(&buf, &len);2600prepare_image(&image, img, len, !patch->is_binary);26012602if(apply_fragments(&image, patch) <0)2603return-1;/* note with --reject this succeeds. */2604 patch->result = image.buf;2605 patch->resultsize = image.len;2606add_to_fn_table(patch);2607free(image.line_allocated);26082609if(0< patch->is_delete && patch->resultsize)2610returnerror("removal patch leaves file contents");26112612return0;2613}26142615static intcheck_to_create_blob(const char*new_name,int ok_if_exists)2616{2617struct stat nst;2618if(!lstat(new_name, &nst)) {2619if(S_ISDIR(nst.st_mode) || ok_if_exists)2620return0;2621/*2622 * A leading component of new_name might be a symlink2623 * that is going to be removed with this patch, but2624 * still pointing at somewhere that has the path.2625 * In such a case, path "new_name" does not exist as2626 * far as git is concerned.2627 */2628if(has_symlink_leading_path(new_name,strlen(new_name)))2629return0;26302631returnerror("%s: already exists in working directory", new_name);2632}2633else if((errno != ENOENT) && (errno != ENOTDIR))2634returnerror("%s:%s", new_name,strerror(errno));2635return0;2636}26372638static intverify_index_match(struct cache_entry *ce,struct stat *st)2639{2640if(S_ISGITLINK(ce->ce_mode)) {2641if(!S_ISDIR(st->st_mode))2642return-1;2643return0;2644}2645returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID);2646}26472648static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)2649{2650const char*old_name = patch->old_name;2651struct patch *tpatch = NULL;2652int stat_ret =0;2653unsigned st_mode =0;26542655/*2656 * Make sure that we do not have local modifications from the2657 * index when we are looking at the index. Also make sure2658 * we have the preimage file to be patched in the work tree,2659 * unless --cached, which tells git to apply only in the index.2660 */2661if(!old_name)2662return0;26632664assert(patch->is_new <=0);26652666if(!(patch->is_copy || patch->is_rename) &&2667(tpatch =in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {2668if(was_deleted(tpatch))2669returnerror("%s: has been deleted/renamed", old_name);2670 st_mode = tpatch->new_mode;2671}else if(!cached) {2672 stat_ret =lstat(old_name, st);2673if(stat_ret && errno != ENOENT)2674returnerror("%s:%s", old_name,strerror(errno));2675}26762677if(to_be_deleted(tpatch))2678 tpatch = NULL;26792680if(check_index && !tpatch) {2681int pos =cache_name_pos(old_name,strlen(old_name));2682if(pos <0) {2683if(patch->is_new <0)2684goto is_new;2685returnerror("%s: does not exist in index", old_name);2686}2687*ce = active_cache[pos];2688if(stat_ret <0) {2689struct checkout costate;2690/* checkout */2691 costate.base_dir ="";2692 costate.base_dir_len =0;2693 costate.force =0;2694 costate.quiet =0;2695 costate.not_new =0;2696 costate.refresh_cache =1;2697if(checkout_entry(*ce, &costate, NULL) ||2698lstat(old_name, st))2699return-1;2700}2701if(!cached &&verify_index_match(*ce, st))2702returnerror("%s: does not match index", old_name);2703if(cached)2704 st_mode = (*ce)->ce_mode;2705}else if(stat_ret <0) {2706if(patch->is_new <0)2707goto is_new;2708returnerror("%s:%s", old_name,strerror(errno));2709}27102711if(!cached && !tpatch)2712 st_mode =ce_mode_from_stat(*ce, st->st_mode);27132714if(patch->is_new <0)2715 patch->is_new =0;2716if(!patch->old_mode)2717 patch->old_mode = st_mode;2718if((st_mode ^ patch->old_mode) & S_IFMT)2719returnerror("%s: wrong type", old_name);2720if(st_mode != patch->old_mode)2721warning("%shas type%o, expected%o",2722 old_name, st_mode, patch->old_mode);2723if(!patch->new_mode && !patch->is_delete)2724 patch->new_mode = st_mode;2725return0;27262727 is_new:2728 patch->is_new =1;2729 patch->is_delete =0;2730 patch->old_name = NULL;2731return0;2732}27332734static intcheck_patch(struct patch *patch)2735{2736struct stat st;2737const char*old_name = patch->old_name;2738const char*new_name = patch->new_name;2739const char*name = old_name ? old_name : new_name;2740struct cache_entry *ce = NULL;2741struct patch *tpatch;2742int ok_if_exists;2743int status;27442745 patch->rejected =1;/* we will drop this after we succeed */27462747 status =check_preimage(patch, &ce, &st);2748if(status)2749return status;2750 old_name = patch->old_name;27512752if((tpatch =in_fn_table(new_name)) &&2753(was_deleted(tpatch) ||to_be_deleted(tpatch)))2754/*2755 * A type-change diff is always split into a patch to2756 * delete old, immediately followed by a patch to2757 * create new (see diff.c::run_diff()); in such a case2758 * it is Ok that the entry to be deleted by the2759 * previous patch is still in the working tree and in2760 * the index.2761 */2762 ok_if_exists =1;2763else2764 ok_if_exists =0;27652766if(new_name &&2767((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {2768if(check_index &&2769cache_name_pos(new_name,strlen(new_name)) >=0&&2770!ok_if_exists)2771returnerror("%s: already exists in index", new_name);2772if(!cached) {2773int err =check_to_create_blob(new_name, ok_if_exists);2774if(err)2775return err;2776}2777if(!patch->new_mode) {2778if(0< patch->is_new)2779 patch->new_mode = S_IFREG |0644;2780else2781 patch->new_mode = patch->old_mode;2782}2783}27842785if(new_name && old_name) {2786int same = !strcmp(old_name, new_name);2787if(!patch->new_mode)2788 patch->new_mode = patch->old_mode;2789if((patch->old_mode ^ patch->new_mode) & S_IFMT)2790returnerror("new mode (%o) of%sdoes not match old mode (%o)%s%s",2791 patch->new_mode, new_name, patch->old_mode,2792 same ?"":" of ", same ?"": old_name);2793}27942795if(apply_data(patch, &st, ce) <0)2796returnerror("%s: patch does not apply", name);2797 patch->rejected =0;2798return0;2799}28002801static intcheck_patch_list(struct patch *patch)2802{2803int err =0;28042805prepare_fn_table(patch);2806while(patch) {2807if(apply_verbosely)2808say_patch_name(stderr,2809"Checking patch ", patch,"...\n");2810 err |=check_patch(patch);2811 patch = patch->next;2812}2813return err;2814}28152816/* This function tries to read the sha1 from the current index */2817static intget_current_sha1(const char*path,unsigned char*sha1)2818{2819int pos;28202821if(read_cache() <0)2822return-1;2823 pos =cache_name_pos(path,strlen(path));2824if(pos <0)2825return-1;2826hashcpy(sha1, active_cache[pos]->sha1);2827return0;2828}28292830/* Build an index that contains the just the files needed for a 3way merge */2831static voidbuild_fake_ancestor(struct patch *list,const char*filename)2832{2833struct patch *patch;2834struct index_state result = { NULL };2835int fd;28362837/* Once we start supporting the reverse patch, it may be2838 * worth showing the new sha1 prefix, but until then...2839 */2840for(patch = list; patch; patch = patch->next) {2841const unsigned char*sha1_ptr;2842unsigned char sha1[20];2843struct cache_entry *ce;2844const char*name;28452846 name = patch->old_name ? patch->old_name : patch->new_name;2847if(0< patch->is_new)2848continue;2849else if(get_sha1(patch->old_sha1_prefix, sha1))2850/* git diff has no index line for mode/type changes */2851if(!patch->lines_added && !patch->lines_deleted) {2852if(get_current_sha1(patch->new_name, sha1) ||2853get_current_sha1(patch->old_name, sha1))2854die("mode change for%s, which is not "2855"in current HEAD", name);2856 sha1_ptr = sha1;2857}else2858die("sha1 information is lacking or useless "2859"(%s).", name);2860else2861 sha1_ptr = sha1;28622863 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);2864if(!ce)2865die("make_cache_entry failed for path '%s'", name);2866if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))2867die("Could not add%sto temporary index", name);2868}28692870 fd =open(filename, O_WRONLY | O_CREAT,0666);2871if(fd <0||write_index(&result, fd) ||close(fd))2872die("Could not write temporary index to%s", filename);28732874discard_index(&result);2875}28762877static voidstat_patch_list(struct patch *patch)2878{2879int files, adds, dels;28802881for(files = adds = dels =0; patch ; patch = patch->next) {2882 files++;2883 adds += patch->lines_added;2884 dels += patch->lines_deleted;2885show_stats(patch);2886}28872888printf("%dfiles changed,%dinsertions(+),%ddeletions(-)\n", files, adds, dels);2889}28902891static voidnumstat_patch_list(struct patch *patch)2892{2893for( ; patch; patch = patch->next) {2894const char*name;2895 name = patch->new_name ? patch->new_name : patch->old_name;2896if(patch->is_binary)2897printf("-\t-\t");2898else2899printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);2900write_name_quoted(name, stdout, line_termination);2901}2902}29032904static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)2905{2906if(mode)2907printf("%smode%06o%s\n", newdelete, mode, name);2908else2909printf("%s %s\n", newdelete, name);2910}29112912static voidshow_mode_change(struct patch *p,int show_name)2913{2914if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {2915if(show_name)2916printf(" mode change%06o =>%06o%s\n",2917 p->old_mode, p->new_mode, p->new_name);2918else2919printf(" mode change%06o =>%06o\n",2920 p->old_mode, p->new_mode);2921}2922}29232924static voidshow_rename_copy(struct patch *p)2925{2926const char*renamecopy = p->is_rename ?"rename":"copy";2927const char*old, *new;29282929/* Find common prefix */2930 old = p->old_name;2931new= p->new_name;2932while(1) {2933const char*slash_old, *slash_new;2934 slash_old =strchr(old,'/');2935 slash_new =strchr(new,'/');2936if(!slash_old ||2937!slash_new ||2938 slash_old - old != slash_new -new||2939memcmp(old,new, slash_new -new))2940break;2941 old = slash_old +1;2942new= slash_new +1;2943}2944/* p->old_name thru old is the common prefix, and old and new2945 * through the end of names are renames2946 */2947if(old != p->old_name)2948printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,2949(int)(old - p->old_name), p->old_name,2950 old,new, p->score);2951else2952printf("%s %s=>%s(%d%%)\n", renamecopy,2953 p->old_name, p->new_name, p->score);2954show_mode_change(p,0);2955}29562957static voidsummary_patch_list(struct patch *patch)2958{2959struct patch *p;29602961for(p = patch; p; p = p->next) {2962if(p->is_new)2963show_file_mode_name("create", p->new_mode, p->new_name);2964else if(p->is_delete)2965show_file_mode_name("delete", p->old_mode, p->old_name);2966else{2967if(p->is_rename || p->is_copy)2968show_rename_copy(p);2969else{2970if(p->score) {2971printf(" rewrite%s(%d%%)\n",2972 p->new_name, p->score);2973show_mode_change(p,0);2974}2975else2976show_mode_change(p,1);2977}2978}2979}2980}29812982static voidpatch_stats(struct patch *patch)2983{2984int lines = patch->lines_added + patch->lines_deleted;29852986if(lines > max_change)2987 max_change = lines;2988if(patch->old_name) {2989int len =quote_c_style(patch->old_name, NULL, NULL,0);2990if(!len)2991 len =strlen(patch->old_name);2992if(len > max_len)2993 max_len = len;2994}2995if(patch->new_name) {2996int len =quote_c_style(patch->new_name, NULL, NULL,0);2997if(!len)2998 len =strlen(patch->new_name);2999if(len > max_len)3000 max_len = len;3001}3002}30033004static voidremove_file(struct patch *patch,int rmdir_empty)3005{3006if(update_index) {3007if(remove_file_from_cache(patch->old_name) <0)3008die("unable to remove%sfrom index", patch->old_name);3009}3010if(!cached) {3011if(S_ISGITLINK(patch->old_mode)) {3012if(rmdir(patch->old_name))3013warning("unable to remove submodule%s",3014 patch->old_name);3015}else if(!unlink_or_warn(patch->old_name) && rmdir_empty) {3016remove_path(patch->old_name);3017}3018}3019}30203021static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)3022{3023struct stat st;3024struct cache_entry *ce;3025int namelen =strlen(path);3026unsigned ce_size =cache_entry_size(namelen);30273028if(!update_index)3029return;30303031 ce =xcalloc(1, ce_size);3032memcpy(ce->name, path, namelen);3033 ce->ce_mode =create_ce_mode(mode);3034 ce->ce_flags = namelen;3035if(S_ISGITLINK(mode)) {3036const char*s = buf;30373038if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))3039die("corrupt patch for subproject%s", path);3040}else{3041if(!cached) {3042if(lstat(path, &st) <0)3043die_errno("unable to stat newly created file '%s'",3044 path);3045fill_stat_cache_info(ce, &st);3046}3047if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)3048die("unable to create backing store for newly created file%s", path);3049}3050if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)3051die("unable to add cache entry for%s", path);3052}30533054static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)3055{3056int fd;3057struct strbuf nbuf = STRBUF_INIT;30583059if(S_ISGITLINK(mode)) {3060struct stat st;3061if(!lstat(path, &st) &&S_ISDIR(st.st_mode))3062return0;3063returnmkdir(path,0777);3064}30653066if(has_symlinks &&S_ISLNK(mode))3067/* Although buf:size is counted string, it also is NUL3068 * terminated.3069 */3070returnsymlink(buf, path);30713072 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);3073if(fd <0)3074return-1;30753076if(convert_to_working_tree(path, buf, size, &nbuf)) {3077 size = nbuf.len;3078 buf = nbuf.buf;3079}3080write_or_die(fd, buf, size);3081strbuf_release(&nbuf);30823083if(close(fd) <0)3084die_errno("closing file '%s'", path);3085return0;3086}30873088/*3089 * We optimistically assume that the directories exist,3090 * which is true 99% of the time anyway. If they don't,3091 * we create them and try again.3092 */3093static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)3094{3095if(cached)3096return;3097if(!try_create_file(path, mode, buf, size))3098return;30993100if(errno == ENOENT) {3101if(safe_create_leading_directories(path))3102return;3103if(!try_create_file(path, mode, buf, size))3104return;3105}31063107if(errno == EEXIST || errno == EACCES) {3108/* We may be trying to create a file where a directory3109 * used to be.3110 */3111struct stat st;3112if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))3113 errno = EEXIST;3114}31153116if(errno == EEXIST) {3117unsigned int nr =getpid();31183119for(;;) {3120char newpath[PATH_MAX];3121mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);3122if(!try_create_file(newpath, mode, buf, size)) {3123if(!rename(newpath, path))3124return;3125unlink_or_warn(newpath);3126break;3127}3128if(errno != EEXIST)3129break;3130++nr;3131}3132}3133die_errno("unable to write file '%s' mode%o", path, mode);3134}31353136static voidcreate_file(struct patch *patch)3137{3138char*path = patch->new_name;3139unsigned mode = patch->new_mode;3140unsigned long size = patch->resultsize;3141char*buf = patch->result;31423143if(!mode)3144 mode = S_IFREG |0644;3145create_one_file(path, mode, buf, size);3146add_index_file(path, mode, buf, size);3147}31483149/* phase zero is to remove, phase one is to create */3150static voidwrite_out_one_result(struct patch *patch,int phase)3151{3152if(patch->is_delete >0) {3153if(phase ==0)3154remove_file(patch,1);3155return;3156}3157if(patch->is_new >0|| patch->is_copy) {3158if(phase ==1)3159create_file(patch);3160return;3161}3162/*3163 * Rename or modification boils down to the same3164 * thing: remove the old, write the new3165 */3166if(phase ==0)3167remove_file(patch, patch->is_rename);3168if(phase ==1)3169create_file(patch);3170}31713172static intwrite_out_one_reject(struct patch *patch)3173{3174FILE*rej;3175char namebuf[PATH_MAX];3176struct fragment *frag;3177int cnt =0;31783179for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {3180if(!frag->rejected)3181continue;3182 cnt++;3183}31843185if(!cnt) {3186if(apply_verbosely)3187say_patch_name(stderr,3188"Applied patch ", patch," cleanly.\n");3189return0;3190}31913192/* This should not happen, because a removal patch that leaves3193 * contents are marked "rejected" at the patch level.3194 */3195if(!patch->new_name)3196die("internal error");31973198/* Say this even without --verbose */3199say_patch_name(stderr,"Applying patch ", patch," with");3200fprintf(stderr,"%drejects...\n", cnt);32013202 cnt =strlen(patch->new_name);3203if(ARRAY_SIZE(namebuf) <= cnt +5) {3204 cnt =ARRAY_SIZE(namebuf) -5;3205warning("truncating .rej filename to %.*s.rej",3206 cnt -1, patch->new_name);3207}3208memcpy(namebuf, patch->new_name, cnt);3209memcpy(namebuf + cnt,".rej",5);32103211 rej =fopen(namebuf,"w");3212if(!rej)3213returnerror("cannot open%s:%s", namebuf,strerror(errno));32143215/* Normal git tools never deal with .rej, so do not pretend3216 * this is a git patch by saying --git nor give extended3217 * headers. While at it, maybe please "kompare" that wants3218 * the trailing TAB and some garbage at the end of line ;-).3219 */3220fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",3221 patch->new_name, patch->new_name);3222for(cnt =1, frag = patch->fragments;3223 frag;3224 cnt++, frag = frag->next) {3225if(!frag->rejected) {3226fprintf(stderr,"Hunk #%dapplied cleanly.\n", cnt);3227continue;3228}3229fprintf(stderr,"Rejected hunk #%d.\n", cnt);3230fprintf(rej,"%.*s", frag->size, frag->patch);3231if(frag->patch[frag->size-1] !='\n')3232fputc('\n', rej);3233}3234fclose(rej);3235return-1;3236}32373238static intwrite_out_results(struct patch *list,int skipped_patch)3239{3240int phase;3241int errs =0;3242struct patch *l;32433244if(!list && !skipped_patch)3245returnerror("No changes");32463247for(phase =0; phase <2; phase++) {3248 l = list;3249while(l) {3250if(l->rejected)3251 errs =1;3252else{3253write_out_one_result(l, phase);3254if(phase ==1&&write_out_one_reject(l))3255 errs =1;3256}3257 l = l->next;3258}3259}3260return errs;3261}32623263static struct lock_file lock_file;32643265static struct string_list limit_by_name;3266static int has_include;3267static voidadd_name_limit(const char*name,int exclude)3268{3269struct string_list_item *it;32703271 it =string_list_append(name, &limit_by_name);3272 it->util = exclude ? NULL : (void*)1;3273}32743275static intuse_patch(struct patch *p)3276{3277const char*pathname = p->new_name ? p->new_name : p->old_name;3278int i;32793280/* Paths outside are not touched regardless of "--include" */3281if(0< prefix_length) {3282int pathlen =strlen(pathname);3283if(pathlen <= prefix_length ||3284memcmp(prefix, pathname, prefix_length))3285return0;3286}32873288/* See if it matches any of exclude/include rule */3289for(i =0; i < limit_by_name.nr; i++) {3290struct string_list_item *it = &limit_by_name.items[i];3291if(!fnmatch(it->string, pathname,0))3292return(it->util != NULL);3293}32943295/*3296 * If we had any include, a path that does not match any rule is3297 * not used. Otherwise, we saw bunch of exclude rules (or none)3298 * and such a path is used.3299 */3300return!has_include;3301}330233033304static voidprefix_one(char**name)3305{3306char*old_name = *name;3307if(!old_name)3308return;3309*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3310free(old_name);3311}33123313static voidprefix_patches(struct patch *p)3314{3315if(!prefix || p->is_toplevel_relative)3316return;3317for( ; p; p = p->next) {3318if(p->new_name == p->old_name) {3319char*prefixed = p->new_name;3320prefix_one(&prefixed);3321 p->new_name = p->old_name = prefixed;3322}3323else{3324prefix_one(&p->new_name);3325prefix_one(&p->old_name);3326}3327}3328}33293330#define INACCURATE_EOF (1<<0)3331#define RECOUNT (1<<1)33323333static intapply_patch(int fd,const char*filename,int options)3334{3335size_t offset;3336struct strbuf buf = STRBUF_INIT;3337struct patch *list = NULL, **listp = &list;3338int skipped_patch =0;33393340/* FIXME - memory leak when using multiple patch files as inputs */3341memset(&fn_table,0,sizeof(struct string_list));3342 patch_input_file = filename;3343read_patch_file(&buf, fd);3344 offset =0;3345while(offset < buf.len) {3346struct patch *patch;3347int nr;33483349 patch =xcalloc(1,sizeof(*patch));3350 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3351 patch->recount = !!(options & RECOUNT);3352 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3353if(nr <0)3354break;3355if(apply_in_reverse)3356reverse_patches(patch);3357if(prefix)3358prefix_patches(patch);3359if(use_patch(patch)) {3360patch_stats(patch);3361*listp = patch;3362 listp = &patch->next;3363}3364else{3365/* perhaps free it a bit better? */3366free(patch);3367 skipped_patch++;3368}3369 offset += nr;3370}33713372if(whitespace_error && (ws_error_action == die_on_ws_error))3373 apply =0;33743375 update_index = check_index && apply;3376if(update_index && newfd <0)3377 newfd =hold_locked_index(&lock_file,1);33783379if(check_index) {3380if(read_cache() <0)3381die("unable to read index file");3382}33833384if((check || apply) &&3385check_patch_list(list) <0&&3386!apply_with_reject)3387exit(1);33883389if(apply &&write_out_results(list, skipped_patch))3390exit(1);33913392if(fake_ancestor)3393build_fake_ancestor(list, fake_ancestor);33943395if(diffstat)3396stat_patch_list(list);33973398if(numstat)3399numstat_patch_list(list);34003401if(summary)3402summary_patch_list(list);34033404strbuf_release(&buf);3405return0;3406}34073408static intgit_apply_config(const char*var,const char*value,void*cb)3409{3410if(!strcmp(var,"apply.whitespace"))3411returngit_config_string(&apply_default_whitespace, var, value);3412else if(!strcmp(var,"apply.ignorewhitespace"))3413returngit_config_string(&apply_default_ignorewhitespace, var, value);3414returngit_default_config(var, value, cb);3415}34163417static intoption_parse_exclude(const struct option *opt,3418const char*arg,int unset)3419{3420add_name_limit(arg,1);3421return0;3422}34233424static intoption_parse_include(const struct option *opt,3425const char*arg,int unset)3426{3427add_name_limit(arg,0);3428 has_include =1;3429return0;3430}34313432static intoption_parse_p(const struct option *opt,3433const char*arg,int unset)3434{3435 p_value =atoi(arg);3436 p_value_known =1;3437return0;3438}34393440static intoption_parse_z(const struct option *opt,3441const char*arg,int unset)3442{3443if(unset)3444 line_termination ='\n';3445else3446 line_termination =0;3447return0;3448}34493450static intoption_parse_space_change(const struct option *opt,3451const char*arg,int unset)3452{3453if(unset)3454 ws_ignore_action = ignore_ws_none;3455else3456 ws_ignore_action = ignore_ws_change;3457return0;3458}34593460static intoption_parse_whitespace(const struct option *opt,3461const char*arg,int unset)3462{3463const char**whitespace_option = opt->value;34643465*whitespace_option = arg;3466parse_whitespace_option(arg);3467return0;3468}34693470static intoption_parse_directory(const struct option *opt,3471const char*arg,int unset)3472{3473 root_len =strlen(arg);3474if(root_len && arg[root_len -1] !='/') {3475char*new_root;3476 root = new_root =xmalloc(root_len +2);3477strcpy(new_root, arg);3478strcpy(new_root + root_len++,"/");3479}else3480 root = arg;3481return0;3482}34833484intcmd_apply(int argc,const char**argv,const char*unused_prefix)3485{3486int i;3487int errs =0;3488int is_not_gitdir;3489int binary;3490int force_apply =0;34913492const char*whitespace_option = NULL;34933494struct option builtin_apply_options[] = {3495{ OPTION_CALLBACK,0,"exclude", NULL,"path",3496"don't apply changes matching the given path",34970, option_parse_exclude },3498{ OPTION_CALLBACK,0,"include", NULL,"path",3499"apply changes matching the given path",35000, option_parse_include },3501{ OPTION_CALLBACK,'p', NULL, NULL,"num",3502"remove <num> leading slashes from traditional diff paths",35030, option_parse_p },3504OPT_BOOLEAN(0,"no-add", &no_add,3505"ignore additions made by the patch"),3506OPT_BOOLEAN(0,"stat", &diffstat,3507"instead of applying the patch, output diffstat for the input"),3508{ OPTION_BOOLEAN,0,"allow-binary-replacement", &binary,3509 NULL,"old option, now no-op",3510 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3511{ OPTION_BOOLEAN,0,"binary", &binary,3512 NULL,"old option, now no-op",3513 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3514OPT_BOOLEAN(0,"numstat", &numstat,3515"shows number of added and deleted lines in decimal notation"),3516OPT_BOOLEAN(0,"summary", &summary,3517"instead of applying the patch, output a summary for the input"),3518OPT_BOOLEAN(0,"check", &check,3519"instead of applying the patch, see if the patch is applicable"),3520OPT_BOOLEAN(0,"index", &check_index,3521"make sure the patch is applicable to the current index"),3522OPT_BOOLEAN(0,"cached", &cached,3523"apply a patch without touching the working tree"),3524OPT_BOOLEAN(0,"apply", &force_apply,3525"also apply the patch (use with --stat/--summary/--check)"),3526OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,3527"build a temporary index based on embedded index information"),3528{ OPTION_CALLBACK,'z', NULL, NULL, NULL,3529"paths are separated with NUL character",3530 PARSE_OPT_NOARG, option_parse_z },3531OPT_INTEGER('C', NULL, &p_context,3532"ensure at least <n> lines of context match"),3533{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,"action",3534"detect new or modified lines that have whitespace errors",35350, option_parse_whitespace },3536{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,3537"ignore changes in whitespace when finding context",3538 PARSE_OPT_NOARG, option_parse_space_change },3539{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,3540"ignore changes in whitespace when finding context",3541 PARSE_OPT_NOARG, option_parse_space_change },3542OPT_BOOLEAN('R',"reverse", &apply_in_reverse,3543"apply the patch in reverse"),3544OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,3545"don't expect at least one line of context"),3546OPT_BOOLEAN(0,"reject", &apply_with_reject,3547"leave the rejected hunks in corresponding *.rej files"),3548OPT__VERBOSE(&apply_verbosely),3549OPT_BIT(0,"inaccurate-eof", &options,3550"tolerate incorrectly detected missing new-line at the end of file",3551 INACCURATE_EOF),3552OPT_BIT(0,"recount", &options,3553"do not trust the line counts in the hunk headers",3554 RECOUNT),3555{ OPTION_CALLBACK,0,"directory", NULL,"root",3556"prepend <root> to all filenames",35570, option_parse_directory },3558OPT_END()3559};35603561 prefix =setup_git_directory_gently(&is_not_gitdir);3562 prefix_length = prefix ?strlen(prefix) :0;3563git_config(git_apply_config, NULL);3564if(apply_default_whitespace)3565parse_whitespace_option(apply_default_whitespace);3566if(apply_default_ignorewhitespace)3567parse_ignorewhitespace_option(apply_default_ignorewhitespace);35683569 argc =parse_options(argc, argv, prefix, builtin_apply_options,3570 apply_usage,0);35713572if(apply_with_reject)3573 apply = apply_verbosely =1;3574if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))3575 apply =0;3576if(check_index && is_not_gitdir)3577die("--index outside a repository");3578if(cached) {3579if(is_not_gitdir)3580die("--cached outside a repository");3581 check_index =1;3582}3583for(i =0; i < argc; i++) {3584const char*arg = argv[i];3585int fd;35863587if(!strcmp(arg,"-")) {3588 errs |=apply_patch(0,"<stdin>", options);3589 read_stdin =0;3590continue;3591}else if(0< prefix_length)3592 arg =prefix_filename(prefix, prefix_length, arg);35933594 fd =open(arg, O_RDONLY);3595if(fd <0)3596die_errno("can't open patch '%s'", arg);3597 read_stdin =0;3598set_default_whitespace_mode(whitespace_option);3599 errs |=apply_patch(fd, arg, options);3600close(fd);3601}3602set_default_whitespace_mode(whitespace_option);3603if(read_stdin)3604 errs |=apply_patch(0,"<stdin>", options);3605if(whitespace_error) {3606if(squelch_whitespace_errors &&3607 squelch_whitespace_errors < whitespace_error) {3608int squelched =3609 whitespace_error - squelch_whitespace_errors;3610warning("squelched%d"3611"whitespace error%s",3612 squelched,3613 squelched ==1?"":"s");3614}3615if(ws_error_action == die_on_ws_error)3616die("%dline%sadd%swhitespace errors.",3617 whitespace_error,3618 whitespace_error ==1?"":"s",3619 whitespace_error ==1?"s":"");3620if(applied_after_fixing_ws && apply)3621warning("%dline%sapplied after"3622" fixing whitespace errors.",3623 applied_after_fixing_ws,3624 applied_after_fixing_ws ==1?"":"s");3625else if(whitespace_error)3626warning("%dline%sadd%swhitespace errors.",3627 whitespace_error,3628 whitespace_error ==1?"":"s",3629 whitespace_error ==1?"s":"");3630}36313632if(update_index) {3633if(write_cache(newfd, active_cache, active_nr) ||3634commit_locked_index(&lock_file))3635die("Unable to write new index file");3636}36373638return!!errs;3639}