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; 64static const char*patch_input_file; 65static const char*root; 66static int root_len; 67static int read_stdin =1; 68static int options; 69 70static voidparse_whitespace_option(const char*option) 71{ 72if(!option) { 73 ws_error_action = warn_on_ws_error; 74return; 75} 76if(!strcmp(option,"warn")) { 77 ws_error_action = warn_on_ws_error; 78return; 79} 80if(!strcmp(option,"nowarn")) { 81 ws_error_action = nowarn_ws_error; 82return; 83} 84if(!strcmp(option,"error")) { 85 ws_error_action = die_on_ws_error; 86return; 87} 88if(!strcmp(option,"error-all")) { 89 ws_error_action = die_on_ws_error; 90 squelch_whitespace_errors =0; 91return; 92} 93if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 94 ws_error_action = correct_ws_error; 95return; 96} 97die("unrecognized whitespace option '%s'", option); 98} 99 100static voidset_default_whitespace_mode(const char*whitespace_option) 101{ 102if(!whitespace_option && !apply_default_whitespace) 103 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 104} 105 106/* 107 * For "diff-stat" like behaviour, we keep track of the biggest change 108 * we've seen, and the longest filename. That allows us to do simple 109 * scaling. 110 */ 111static int max_change, max_len; 112 113/* 114 * Various "current state", notably line numbers and what 115 * file (and how) we're patching right now.. The "is_xxxx" 116 * things are flags, where -1 means "don't know yet". 117 */ 118static int linenr =1; 119 120/* 121 * This represents one "hunk" from a patch, starting with 122 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 123 * patch text is pointed at by patch, and its byte length 124 * is stored in size. leading and trailing are the number 125 * of context lines. 126 */ 127struct fragment { 128unsigned long leading, trailing; 129unsigned long oldpos, oldlines; 130unsigned long newpos, newlines; 131const char*patch; 132int size; 133int rejected; 134int linenr; 135struct fragment *next; 136}; 137 138/* 139 * When dealing with a binary patch, we reuse "leading" field 140 * to store the type of the binary hunk, either deflated "delta" 141 * or deflated "literal". 142 */ 143#define binary_patch_method leading 144#define BINARY_DELTA_DEFLATED 1 145#define BINARY_LITERAL_DEFLATED 2 146 147/* 148 * This represents a "patch" to a file, both metainfo changes 149 * such as creation/deletion, filemode and content changes represented 150 * as a series of fragments. 151 */ 152struct patch { 153char*new_name, *old_name, *def_name; 154unsigned int old_mode, new_mode; 155int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 156int rejected; 157unsigned ws_rule; 158unsigned long deflate_origlen; 159int lines_added, lines_deleted; 160int score; 161unsigned int is_toplevel_relative:1; 162unsigned int inaccurate_eof:1; 163unsigned int is_binary:1; 164unsigned int is_copy:1; 165unsigned int is_rename:1; 166unsigned int recount:1; 167struct fragment *fragments; 168char*result; 169size_t resultsize; 170char old_sha1_prefix[41]; 171char new_sha1_prefix[41]; 172struct patch *next; 173}; 174 175/* 176 * A line in a file, len-bytes long (includes the terminating LF, 177 * except for an incomplete line at the end if the file ends with 178 * one), and its contents hashes to 'hash'. 179 */ 180struct line { 181size_t len; 182unsigned hash :24; 183unsigned flag :8; 184#define LINE_COMMON 1 185}; 186 187/* 188 * This represents a "file", which is an array of "lines". 189 */ 190struct image { 191char*buf; 192size_t len; 193size_t nr; 194size_t alloc; 195struct line *line_allocated; 196struct line *line; 197}; 198 199/* 200 * Records filenames that have been touched, in order to handle 201 * the case where more than one patches touch the same file. 202 */ 203 204static struct string_list fn_table; 205 206static uint32_thash_line(const char*cp,size_t len) 207{ 208size_t i; 209uint32_t h; 210for(i =0, h =0; i < len; i++) { 211if(!isspace(cp[i])) { 212 h = h *3+ (cp[i] &0xff); 213} 214} 215return h; 216} 217 218static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 219{ 220ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 221 img->line_allocated[img->nr].len = len; 222 img->line_allocated[img->nr].hash =hash_line(bol, len); 223 img->line_allocated[img->nr].flag = flag; 224 img->nr++; 225} 226 227static voidprepare_image(struct image *image,char*buf,size_t len, 228int prepare_linetable) 229{ 230const char*cp, *ep; 231 232memset(image,0,sizeof(*image)); 233 image->buf = buf; 234 image->len = len; 235 236if(!prepare_linetable) 237return; 238 239 ep = image->buf + image->len; 240 cp = image->buf; 241while(cp < ep) { 242const char*next; 243for(next = cp; next < ep && *next !='\n'; next++) 244; 245if(next < ep) 246 next++; 247add_line_info(image, cp, next - cp,0); 248 cp = next; 249} 250 image->line = image->line_allocated; 251} 252 253static voidclear_image(struct image *image) 254{ 255free(image->buf); 256 image->buf = NULL; 257 image->len =0; 258} 259 260static voidsay_patch_name(FILE*output,const char*pre, 261struct patch *patch,const char*post) 262{ 263fputs(pre, output); 264if(patch->old_name && patch->new_name && 265strcmp(patch->old_name, patch->new_name)) { 266quote_c_style(patch->old_name, NULL, output,0); 267fputs(" => ", output); 268quote_c_style(patch->new_name, NULL, output,0); 269}else{ 270const char*n = patch->new_name; 271if(!n) 272 n = patch->old_name; 273quote_c_style(n, NULL, output,0); 274} 275fputs(post, output); 276} 277 278#define CHUNKSIZE (8192) 279#define SLOP (16) 280 281static voidread_patch_file(struct strbuf *sb,int fd) 282{ 283if(strbuf_read(sb, fd,0) <0) 284die_errno("git apply: failed to read"); 285 286/* 287 * Make sure that we have some slop in the buffer 288 * so that we can do speculative "memcmp" etc, and 289 * see to it that it is NUL-filled. 290 */ 291strbuf_grow(sb, SLOP); 292memset(sb->buf + sb->len,0, SLOP); 293} 294 295static unsigned longlinelen(const char*buffer,unsigned long size) 296{ 297unsigned long len =0; 298while(size--) { 299 len++; 300if(*buffer++ =='\n') 301break; 302} 303return len; 304} 305 306static intis_dev_null(const char*str) 307{ 308return!memcmp("/dev/null", str,9) &&isspace(str[9]); 309} 310 311#define TERM_SPACE 1 312#define TERM_TAB 2 313 314static intname_terminate(const char*name,int namelen,int c,int terminate) 315{ 316if(c ==' '&& !(terminate & TERM_SPACE)) 317return0; 318if(c =='\t'&& !(terminate & TERM_TAB)) 319return0; 320 321return1; 322} 323 324/* remove double slashes to make --index work with such filenames */ 325static char*squash_slash(char*name) 326{ 327int i =0, j =0; 328 329while(name[i]) { 330if((name[j++] = name[i++]) =='/') 331while(name[i] =='/') 332 i++; 333} 334 name[j] ='\0'; 335return name; 336} 337 338static char*find_name(const char*line,char*def,int p_value,int terminate) 339{ 340int len; 341const char*start = line; 342 343if(*line =='"') { 344struct strbuf name = STRBUF_INIT; 345 346/* 347 * Proposed "new-style" GNU patch/diff format; see 348 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2 349 */ 350if(!unquote_c_style(&name, line, NULL)) { 351char*cp; 352 353for(cp = name.buf; p_value; p_value--) { 354 cp =strchr(cp,'/'); 355if(!cp) 356break; 357 cp++; 358} 359if(cp) { 360/* name can later be freed, so we need 361 * to memmove, not just return cp 362 */ 363strbuf_remove(&name,0, cp - name.buf); 364free(def); 365if(root) 366strbuf_insert(&name,0, root, root_len); 367returnsquash_slash(strbuf_detach(&name, NULL)); 368} 369} 370strbuf_release(&name); 371} 372 373for(;;) { 374char c = *line; 375 376if(isspace(c)) { 377if(c =='\n') 378break; 379if(name_terminate(start, line-start, c, terminate)) 380break; 381} 382 line++; 383if(c =='/'&& !--p_value) 384 start = line; 385} 386if(!start) 387returnsquash_slash(def); 388 len = line - start; 389if(!len) 390returnsquash_slash(def); 391 392/* 393 * Generally we prefer the shorter name, especially 394 * if the other one is just a variation of that with 395 * something else tacked on to the end (ie "file.orig" 396 * or "file~"). 397 */ 398if(def) { 399int deflen =strlen(def); 400if(deflen < len && !strncmp(start, def, deflen)) 401returnsquash_slash(def); 402free(def); 403} 404 405if(root) { 406char*ret =xmalloc(root_len + len +1); 407strcpy(ret, root); 408memcpy(ret + root_len, start, len); 409 ret[root_len + len] ='\0'; 410returnsquash_slash(ret); 411} 412 413returnsquash_slash(xmemdupz(start, len)); 414} 415 416static intcount_slashes(const char*cp) 417{ 418int cnt =0; 419char ch; 420 421while((ch = *cp++)) 422if(ch =='/') 423 cnt++; 424return cnt; 425} 426 427/* 428 * Given the string after "--- " or "+++ ", guess the appropriate 429 * p_value for the given patch. 430 */ 431static intguess_p_value(const char*nameline) 432{ 433char*name, *cp; 434int val = -1; 435 436if(is_dev_null(nameline)) 437return-1; 438 name =find_name(nameline, NULL,0, TERM_SPACE | TERM_TAB); 439if(!name) 440return-1; 441 cp =strchr(name,'/'); 442if(!cp) 443 val =0; 444else if(prefix) { 445/* 446 * Does it begin with "a/$our-prefix" and such? Then this is 447 * very likely to apply to our directory. 448 */ 449if(!strncmp(name, prefix, prefix_length)) 450 val =count_slashes(prefix); 451else{ 452 cp++; 453if(!strncmp(cp, prefix, prefix_length)) 454 val =count_slashes(prefix) +1; 455} 456} 457free(name); 458return val; 459} 460 461/* 462 * Does the ---/+++ line has the POSIX timestamp after the last HT? 463 * GNU diff puts epoch there to signal a creation/deletion event. Is 464 * this such a timestamp? 465 */ 466static inthas_epoch_timestamp(const char*nameline) 467{ 468/* 469 * We are only interested in epoch timestamp; any non-zero 470 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 471 * For the same reason, the date must be either 1969-12-31 or 472 * 1970-01-01, and the seconds part must be "00". 473 */ 474const char stamp_regexp[] = 475"^(1969-12-31|1970-01-01)" 476" " 477"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 478" " 479"([-+][0-2][0-9][0-5][0-9])\n"; 480const char*timestamp = NULL, *cp; 481static regex_t *stamp; 482 regmatch_t m[10]; 483int zoneoffset; 484int hourminute; 485int status; 486 487for(cp = nameline; *cp !='\n'; cp++) { 488if(*cp =='\t') 489 timestamp = cp +1; 490} 491if(!timestamp) 492return0; 493if(!stamp) { 494 stamp =xmalloc(sizeof(*stamp)); 495if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 496warning("Cannot prepare timestamp regexp%s", 497 stamp_regexp); 498return0; 499} 500} 501 502 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 503if(status) { 504if(status != REG_NOMATCH) 505warning("regexec returned%dfor input:%s", 506 status, timestamp); 507return0; 508} 509 510 zoneoffset =strtol(timestamp + m[3].rm_so +1, NULL,10); 511 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 512if(timestamp[m[3].rm_so] =='-') 513 zoneoffset = -zoneoffset; 514 515/* 516 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 517 * (west of GMT) or 1970-01-01 (east of GMT) 518 */ 519if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 520(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 521return0; 522 523 hourminute = (strtol(timestamp +11, NULL,10) *60+ 524strtol(timestamp +14, NULL,10) - 525 zoneoffset); 526 527return((zoneoffset <0&& hourminute ==1440) || 528(0<= zoneoffset && !hourminute)); 529} 530 531/* 532 * Get the name etc info from the ---/+++ lines of a traditional patch header 533 * 534 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 535 * files, we can happily check the index for a match, but for creating a 536 * new file we should try to match whatever "patch" does. I have no idea. 537 */ 538static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 539{ 540char*name; 541 542 first +=4;/* skip "--- " */ 543 second +=4;/* skip "+++ " */ 544if(!p_value_known) { 545int p, q; 546 p =guess_p_value(first); 547 q =guess_p_value(second); 548if(p <0) p = q; 549if(0<= p && p == q) { 550 p_value = p; 551 p_value_known =1; 552} 553} 554if(is_dev_null(first)) { 555 patch->is_new =1; 556 patch->is_delete =0; 557 name =find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB); 558 patch->new_name = name; 559}else if(is_dev_null(second)) { 560 patch->is_new =0; 561 patch->is_delete =1; 562 name =find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB); 563 patch->old_name = name; 564}else{ 565 name =find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB); 566 name =find_name(second, name, p_value, TERM_SPACE | TERM_TAB); 567if(has_epoch_timestamp(first)) { 568 patch->is_new =1; 569 patch->is_delete =0; 570 patch->new_name = name; 571}else if(has_epoch_timestamp(second)) { 572 patch->is_new =0; 573 patch->is_delete =1; 574 patch->old_name = name; 575}else{ 576 patch->old_name = patch->new_name = name; 577} 578} 579if(!name) 580die("unable to find filename in patch at line%d", linenr); 581} 582 583static intgitdiff_hdrend(const char*line,struct patch *patch) 584{ 585return-1; 586} 587 588/* 589 * We're anal about diff header consistency, to make 590 * sure that we don't end up having strange ambiguous 591 * patches floating around. 592 * 593 * As a result, gitdiff_{old|new}name() will check 594 * their names against any previous information, just 595 * to make sure.. 596 */ 597static char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,const char*oldnew) 598{ 599if(!orig_name && !isnull) 600returnfind_name(line, NULL, p_value, TERM_TAB); 601 602if(orig_name) { 603int len; 604const char*name; 605char*another; 606 name = orig_name; 607 len =strlen(name); 608if(isnull) 609die("git apply: bad git-diff - expected /dev/null, got%son line%d", name, linenr); 610 another =find_name(line, NULL, p_value, TERM_TAB); 611if(!another ||memcmp(another, name, len)) 612die("git apply: bad git-diff - inconsistent%sfilename on line%d", oldnew, linenr); 613free(another); 614return orig_name; 615} 616else{ 617/* expect "/dev/null" */ 618if(memcmp("/dev/null", line,9) || line[9] !='\n') 619die("git apply: bad git-diff - expected /dev/null on line%d", linenr); 620return NULL; 621} 622} 623 624static intgitdiff_oldname(const char*line,struct patch *patch) 625{ 626 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name,"old"); 627return0; 628} 629 630static intgitdiff_newname(const char*line,struct patch *patch) 631{ 632 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name,"new"); 633return0; 634} 635 636static intgitdiff_oldmode(const char*line,struct patch *patch) 637{ 638 patch->old_mode =strtoul(line, NULL,8); 639return0; 640} 641 642static intgitdiff_newmode(const char*line,struct patch *patch) 643{ 644 patch->new_mode =strtoul(line, NULL,8); 645return0; 646} 647 648static intgitdiff_delete(const char*line,struct patch *patch) 649{ 650 patch->is_delete =1; 651 patch->old_name = patch->def_name; 652returngitdiff_oldmode(line, patch); 653} 654 655static intgitdiff_newfile(const char*line,struct patch *patch) 656{ 657 patch->is_new =1; 658 patch->new_name = patch->def_name; 659returngitdiff_newmode(line, patch); 660} 661 662static intgitdiff_copysrc(const char*line,struct patch *patch) 663{ 664 patch->is_copy =1; 665 patch->old_name =find_name(line, NULL,0,0); 666return0; 667} 668 669static intgitdiff_copydst(const char*line,struct patch *patch) 670{ 671 patch->is_copy =1; 672 patch->new_name =find_name(line, NULL,0,0); 673return0; 674} 675 676static intgitdiff_renamesrc(const char*line,struct patch *patch) 677{ 678 patch->is_rename =1; 679 patch->old_name =find_name(line, NULL,0,0); 680return0; 681} 682 683static intgitdiff_renamedst(const char*line,struct patch *patch) 684{ 685 patch->is_rename =1; 686 patch->new_name =find_name(line, NULL,0,0); 687return0; 688} 689 690static intgitdiff_similarity(const char*line,struct patch *patch) 691{ 692if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 693 patch->score =0; 694return0; 695} 696 697static intgitdiff_dissimilarity(const char*line,struct patch *patch) 698{ 699if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 700 patch->score =0; 701return0; 702} 703 704static intgitdiff_index(const char*line,struct patch *patch) 705{ 706/* 707 * index line is N hexadecimal, "..", N hexadecimal, 708 * and optional space with octal mode. 709 */ 710const char*ptr, *eol; 711int len; 712 713 ptr =strchr(line,'.'); 714if(!ptr || ptr[1] !='.'||40< ptr - line) 715return0; 716 len = ptr - line; 717memcpy(patch->old_sha1_prefix, line, len); 718 patch->old_sha1_prefix[len] =0; 719 720 line = ptr +2; 721 ptr =strchr(line,' '); 722 eol =strchr(line,'\n'); 723 724if(!ptr || eol < ptr) 725 ptr = eol; 726 len = ptr - line; 727 728if(40< len) 729return0; 730memcpy(patch->new_sha1_prefix, line, len); 731 patch->new_sha1_prefix[len] =0; 732if(*ptr ==' ') 733 patch->old_mode =strtoul(ptr+1, NULL,8); 734return0; 735} 736 737/* 738 * This is normal for a diff that doesn't change anything: we'll fall through 739 * into the next diff. Tell the parser to break out. 740 */ 741static intgitdiff_unrecognized(const char*line,struct patch *patch) 742{ 743return-1; 744} 745 746static const char*stop_at_slash(const char*line,int llen) 747{ 748int i; 749 750for(i =0; i < llen; i++) { 751int ch = line[i]; 752if(ch =='/') 753return line + i; 754} 755return NULL; 756} 757 758/* 759 * This is to extract the same name that appears on "diff --git" 760 * line. We do not find and return anything if it is a rename 761 * patch, and it is OK because we will find the name elsewhere. 762 * We need to reliably find name only when it is mode-change only, 763 * creation or deletion of an empty file. In any of these cases, 764 * both sides are the same name under a/ and b/ respectively. 765 */ 766static char*git_header_name(char*line,int llen) 767{ 768const char*name; 769const char*second = NULL; 770size_t len; 771 772 line +=strlen("diff --git "); 773 llen -=strlen("diff --git "); 774 775if(*line =='"') { 776const char*cp; 777struct strbuf first = STRBUF_INIT; 778struct strbuf sp = STRBUF_INIT; 779 780if(unquote_c_style(&first, line, &second)) 781goto free_and_fail1; 782 783/* advance to the first slash */ 784 cp =stop_at_slash(first.buf, first.len); 785/* we do not accept absolute paths */ 786if(!cp || cp == first.buf) 787goto free_and_fail1; 788strbuf_remove(&first,0, cp +1- first.buf); 789 790/* 791 * second points at one past closing dq of name. 792 * find the second name. 793 */ 794while((second < line + llen) &&isspace(*second)) 795 second++; 796 797if(line + llen <= second) 798goto free_and_fail1; 799if(*second =='"') { 800if(unquote_c_style(&sp, second, NULL)) 801goto free_and_fail1; 802 cp =stop_at_slash(sp.buf, sp.len); 803if(!cp || cp == sp.buf) 804goto free_and_fail1; 805/* They must match, otherwise ignore */ 806if(strcmp(cp +1, first.buf)) 807goto free_and_fail1; 808strbuf_release(&sp); 809returnstrbuf_detach(&first, NULL); 810} 811 812/* unquoted second */ 813 cp =stop_at_slash(second, line + llen - second); 814if(!cp || cp == second) 815goto free_and_fail1; 816 cp++; 817if(line + llen - cp != first.len +1|| 818memcmp(first.buf, cp, first.len)) 819goto free_and_fail1; 820returnstrbuf_detach(&first, NULL); 821 822 free_and_fail1: 823strbuf_release(&first); 824strbuf_release(&sp); 825return NULL; 826} 827 828/* unquoted first name */ 829 name =stop_at_slash(line, llen); 830if(!name || name == line) 831return NULL; 832 name++; 833 834/* 835 * since the first name is unquoted, a dq if exists must be 836 * the beginning of the second name. 837 */ 838for(second = name; second < line + llen; second++) { 839if(*second =='"') { 840struct strbuf sp = STRBUF_INIT; 841const char*np; 842 843if(unquote_c_style(&sp, second, NULL)) 844goto free_and_fail2; 845 846 np =stop_at_slash(sp.buf, sp.len); 847if(!np || np == sp.buf) 848goto free_and_fail2; 849 np++; 850 851 len = sp.buf + sp.len - np; 852if(len < second - name && 853!strncmp(np, name, len) && 854isspace(name[len])) { 855/* Good */ 856strbuf_remove(&sp,0, np - sp.buf); 857returnstrbuf_detach(&sp, NULL); 858} 859 860 free_and_fail2: 861strbuf_release(&sp); 862return NULL; 863} 864} 865 866/* 867 * Accept a name only if it shows up twice, exactly the same 868 * form. 869 */ 870for(len =0; ; len++) { 871switch(name[len]) { 872default: 873continue; 874case'\n': 875return NULL; 876case'\t':case' ': 877 second = name+len; 878for(;;) { 879char c = *second++; 880if(c =='\n') 881return NULL; 882if(c =='/') 883break; 884} 885if(second[len] =='\n'&& !memcmp(name, second, len)) { 886returnxmemdupz(name, len); 887} 888} 889} 890} 891 892/* Verify that we recognize the lines following a git header */ 893static intparse_git_header(char*line,int len,unsigned int size,struct patch *patch) 894{ 895unsigned long offset; 896 897/* A git diff has explicit new/delete information, so we don't guess */ 898 patch->is_new =0; 899 patch->is_delete =0; 900 901/* 902 * Some things may not have the old name in the 903 * rest of the headers anywhere (pure mode changes, 904 * or removing or adding empty files), so we get 905 * the default name from the header. 906 */ 907 patch->def_name =git_header_name(line, len); 908if(patch->def_name && root) { 909char*s =xmalloc(root_len +strlen(patch->def_name) +1); 910strcpy(s, root); 911strcpy(s + root_len, patch->def_name); 912free(patch->def_name); 913 patch->def_name = s; 914} 915 916 line += len; 917 size -= len; 918 linenr++; 919for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) { 920static const struct opentry { 921const char*str; 922int(*fn)(const char*,struct patch *); 923} optable[] = { 924{"@@ -", gitdiff_hdrend }, 925{"--- ", gitdiff_oldname }, 926{"+++ ", gitdiff_newname }, 927{"old mode ", gitdiff_oldmode }, 928{"new mode ", gitdiff_newmode }, 929{"deleted file mode ", gitdiff_delete }, 930{"new file mode ", gitdiff_newfile }, 931{"copy from ", gitdiff_copysrc }, 932{"copy to ", gitdiff_copydst }, 933{"rename old ", gitdiff_renamesrc }, 934{"rename new ", gitdiff_renamedst }, 935{"rename from ", gitdiff_renamesrc }, 936{"rename to ", gitdiff_renamedst }, 937{"similarity index ", gitdiff_similarity }, 938{"dissimilarity index ", gitdiff_dissimilarity }, 939{"index ", gitdiff_index }, 940{"", gitdiff_unrecognized }, 941}; 942int i; 943 944 len =linelen(line, size); 945if(!len || line[len-1] !='\n') 946break; 947for(i =0; i <ARRAY_SIZE(optable); i++) { 948const struct opentry *p = optable + i; 949int oplen =strlen(p->str); 950if(len < oplen ||memcmp(p->str, line, oplen)) 951continue; 952if(p->fn(line + oplen, patch) <0) 953return offset; 954break; 955} 956} 957 958return offset; 959} 960 961static intparse_num(const char*line,unsigned long*p) 962{ 963char*ptr; 964 965if(!isdigit(*line)) 966return0; 967*p =strtoul(line, &ptr,10); 968return ptr - line; 969} 970 971static intparse_range(const char*line,int len,int offset,const char*expect, 972unsigned long*p1,unsigned long*p2) 973{ 974int digits, ex; 975 976if(offset <0|| offset >= len) 977return-1; 978 line += offset; 979 len -= offset; 980 981 digits =parse_num(line, p1); 982if(!digits) 983return-1; 984 985 offset += digits; 986 line += digits; 987 len -= digits; 988 989*p2 =1; 990if(*line ==',') { 991 digits =parse_num(line+1, p2); 992if(!digits) 993return-1; 994 995 offset += digits+1; 996 line += digits+1; 997 len -= digits+1; 998} 9991000 ex =strlen(expect);1001if(ex > len)1002return-1;1003if(memcmp(line, expect, ex))1004return-1;10051006return offset + ex;1007}10081009static voidrecount_diff(char*line,int size,struct fragment *fragment)1010{1011int oldlines =0, newlines =0, ret =0;10121013if(size <1) {1014warning("recount: ignore empty hunk");1015return;1016}10171018for(;;) {1019int len =linelen(line, size);1020 size -= len;1021 line += len;10221023if(size <1)1024break;10251026switch(*line) {1027case' ':case'\n':1028 newlines++;1029/* fall through */1030case'-':1031 oldlines++;1032continue;1033case'+':1034 newlines++;1035continue;1036case'\\':1037continue;1038case'@':1039 ret = size <3||prefixcmp(line,"@@ ");1040break;1041case'd':1042 ret = size <5||prefixcmp(line,"diff ");1043break;1044default:1045 ret = -1;1046break;1047}1048if(ret) {1049warning("recount: unexpected line: %.*s",1050(int)linelen(line, size), line);1051return;1052}1053break;1054}1055 fragment->oldlines = oldlines;1056 fragment->newlines = newlines;1057}10581059/*1060 * Parse a unified diff fragment header of the1061 * form "@@ -a,b +c,d @@"1062 */1063static intparse_fragment_header(char*line,int len,struct fragment *fragment)1064{1065int offset;10661067if(!len || line[len-1] !='\n')1068return-1;10691070/* Figure out the number of lines in a fragment */1071 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1072 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);10731074return offset;1075}10761077static intfind_header(char*line,unsigned long size,int*hdrsize,struct patch *patch)1078{1079unsigned long offset, len;10801081 patch->is_toplevel_relative =0;1082 patch->is_rename = patch->is_copy =0;1083 patch->is_new = patch->is_delete = -1;1084 patch->old_mode = patch->new_mode =0;1085 patch->old_name = patch->new_name = NULL;1086for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1087unsigned long nextlen;10881089 len =linelen(line, size);1090if(!len)1091break;10921093/* Testing this early allows us to take a few shortcuts.. */1094if(len <6)1095continue;10961097/*1098 * Make sure we don't find any unconnected patch fragments.1099 * That's a sign that we didn't find a header, and that a1100 * patch has become corrupted/broken up.1101 */1102if(!memcmp("@@ -", line,4)) {1103struct fragment dummy;1104if(parse_fragment_header(line, len, &dummy) <0)1105continue;1106die("patch fragment without header at line%d: %.*s",1107 linenr, (int)len-1, line);1108}11091110if(size < len +6)1111break;11121113/*1114 * Git patch? It might not have a real patch, just a rename1115 * or mode change, so we handle that specially1116 */1117if(!memcmp("diff --git ", line,11)) {1118int git_hdr_len =parse_git_header(line, len, size, patch);1119if(git_hdr_len <= len)1120continue;1121if(!patch->old_name && !patch->new_name) {1122if(!patch->def_name)1123die("git diff header lacks filename information (line%d)", linenr);1124 patch->old_name = patch->new_name = patch->def_name;1125}1126 patch->is_toplevel_relative =1;1127*hdrsize = git_hdr_len;1128return offset;1129}11301131/* --- followed by +++ ? */1132if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1133continue;11341135/*1136 * We only accept unified patches, so we want it to1137 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1138 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1139 */1140 nextlen =linelen(line + len, size - len);1141if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1142continue;11431144/* Ok, we'll consider it a patch */1145parse_traditional_patch(line, line+len, patch);1146*hdrsize = len + nextlen;1147 linenr +=2;1148return offset;1149}1150return-1;1151}11521153static voidrecord_ws_error(unsigned result,const char*line,int len,int linenr)1154{1155char*err;11561157if(!result)1158return;11591160 whitespace_error++;1161if(squelch_whitespace_errors &&1162 squelch_whitespace_errors < whitespace_error)1163return;11641165 err =whitespace_error_string(result);1166fprintf(stderr,"%s:%d:%s.\n%.*s\n",1167 patch_input_file, linenr, err, len, line);1168free(err);1169}11701171static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1172{1173unsigned result =ws_check(line +1, len -1, ws_rule);11741175record_ws_error(result, line +1, len -2, linenr);1176}11771178/*1179 * Parse a unified diff. Note that this really needs to parse each1180 * fragment separately, since the only way to know the difference1181 * between a "---" that is part of a patch, and a "---" that starts1182 * the next patch is to look at the line counts..1183 */1184static intparse_fragment(char*line,unsigned long size,1185struct patch *patch,struct fragment *fragment)1186{1187int added, deleted;1188int len =linelen(line, size), offset;1189unsigned long oldlines, newlines;1190unsigned long leading, trailing;11911192 offset =parse_fragment_header(line, len, fragment);1193if(offset <0)1194return-1;1195if(offset >0&& patch->recount)1196recount_diff(line + offset, size - offset, fragment);1197 oldlines = fragment->oldlines;1198 newlines = fragment->newlines;1199 leading =0;1200 trailing =0;12011202/* Parse the thing.. */1203 line += len;1204 size -= len;1205 linenr++;1206 added = deleted =0;1207for(offset = len;12080< size;1209 offset += len, size -= len, line += len, linenr++) {1210if(!oldlines && !newlines)1211break;1212 len =linelen(line, size);1213if(!len || line[len-1] !='\n')1214return-1;1215switch(*line) {1216default:1217return-1;1218case'\n':/* newer GNU diff, an empty context line */1219case' ':1220 oldlines--;1221 newlines--;1222if(!deleted && !added)1223 leading++;1224 trailing++;1225break;1226case'-':1227if(apply_in_reverse &&1228 ws_error_action != nowarn_ws_error)1229check_whitespace(line, len, patch->ws_rule);1230 deleted++;1231 oldlines--;1232 trailing =0;1233break;1234case'+':1235if(!apply_in_reverse &&1236 ws_error_action != nowarn_ws_error)1237check_whitespace(line, len, patch->ws_rule);1238 added++;1239 newlines--;1240 trailing =0;1241break;12421243/*1244 * We allow "\ No newline at end of file". Depending1245 * on locale settings when the patch was produced we1246 * don't know what this line looks like. The only1247 * thing we do know is that it begins with "\ ".1248 * Checking for 12 is just for sanity check -- any1249 * l10n of "\ No newline..." is at least that long.1250 */1251case'\\':1252if(len <12||memcmp(line,"\\",2))1253return-1;1254break;1255}1256}1257if(oldlines || newlines)1258return-1;1259 fragment->leading = leading;1260 fragment->trailing = trailing;12611262/*1263 * If a fragment ends with an incomplete line, we failed to include1264 * it in the above loop because we hit oldlines == newlines == 01265 * before seeing it.1266 */1267if(12< size && !memcmp(line,"\\",2))1268 offset +=linelen(line, size);12691270 patch->lines_added += added;1271 patch->lines_deleted += deleted;12721273if(0< patch->is_new && oldlines)1274returnerror("new file depends on old contents");1275if(0< patch->is_delete && newlines)1276returnerror("deleted file still has contents");1277return offset;1278}12791280static intparse_single_patch(char*line,unsigned long size,struct patch *patch)1281{1282unsigned long offset =0;1283unsigned long oldlines =0, newlines =0, context =0;1284struct fragment **fragp = &patch->fragments;12851286while(size >4&& !memcmp(line,"@@ -",4)) {1287struct fragment *fragment;1288int len;12891290 fragment =xcalloc(1,sizeof(*fragment));1291 fragment->linenr = linenr;1292 len =parse_fragment(line, size, patch, fragment);1293if(len <=0)1294die("corrupt patch at line%d", linenr);1295 fragment->patch = line;1296 fragment->size = len;1297 oldlines += fragment->oldlines;1298 newlines += fragment->newlines;1299 context += fragment->leading + fragment->trailing;13001301*fragp = fragment;1302 fragp = &fragment->next;13031304 offset += len;1305 line += len;1306 size -= len;1307}13081309/*1310 * If something was removed (i.e. we have old-lines) it cannot1311 * be creation, and if something was added it cannot be1312 * deletion. However, the reverse is not true; --unified=01313 * patches that only add are not necessarily creation even1314 * though they do not have any old lines, and ones that only1315 * delete are not necessarily deletion.1316 *1317 * Unfortunately, a real creation/deletion patch do _not_ have1318 * any context line by definition, so we cannot safely tell it1319 * apart with --unified=0 insanity. At least if the patch has1320 * more than one hunk it is not creation or deletion.1321 */1322if(patch->is_new <0&&1323(oldlines || (patch->fragments && patch->fragments->next)))1324 patch->is_new =0;1325if(patch->is_delete <0&&1326(newlines || (patch->fragments && patch->fragments->next)))1327 patch->is_delete =0;13281329if(0< patch->is_new && oldlines)1330die("new file%sdepends on old contents", patch->new_name);1331if(0< patch->is_delete && newlines)1332die("deleted file%sstill has contents", patch->old_name);1333if(!patch->is_delete && !newlines && context)1334fprintf(stderr,"** warning: file%sbecomes empty but "1335"is not deleted\n", patch->new_name);13361337return offset;1338}13391340staticinlineintmetadata_changes(struct patch *patch)1341{1342return patch->is_rename >0||1343 patch->is_copy >0||1344 patch->is_new >0||1345 patch->is_delete ||1346(patch->old_mode && patch->new_mode &&1347 patch->old_mode != patch->new_mode);1348}13491350static char*inflate_it(const void*data,unsigned long size,1351unsigned long inflated_size)1352{1353 z_stream stream;1354void*out;1355int st;13561357memset(&stream,0,sizeof(stream));13581359 stream.next_in = (unsigned char*)data;1360 stream.avail_in = size;1361 stream.next_out = out =xmalloc(inflated_size);1362 stream.avail_out = inflated_size;1363git_inflate_init(&stream);1364 st =git_inflate(&stream, Z_FINISH);1365git_inflate_end(&stream);1366if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1367free(out);1368return NULL;1369}1370return out;1371}13721373static struct fragment *parse_binary_hunk(char**buf_p,1374unsigned long*sz_p,1375int*status_p,1376int*used_p)1377{1378/*1379 * Expect a line that begins with binary patch method ("literal"1380 * or "delta"), followed by the length of data before deflating.1381 * a sequence of 'length-byte' followed by base-85 encoded data1382 * should follow, terminated by a newline.1383 *1384 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1385 * and we would limit the patch line to 66 characters,1386 * so one line can fit up to 13 groups that would decode1387 * to 52 bytes max. The length byte 'A'-'Z' corresponds1388 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1389 */1390int llen, used;1391unsigned long size = *sz_p;1392char*buffer = *buf_p;1393int patch_method;1394unsigned long origlen;1395char*data = NULL;1396int hunk_size =0;1397struct fragment *frag;13981399 llen =linelen(buffer, size);1400 used = llen;14011402*status_p =0;14031404if(!prefixcmp(buffer,"delta ")) {1405 patch_method = BINARY_DELTA_DEFLATED;1406 origlen =strtoul(buffer +6, NULL,10);1407}1408else if(!prefixcmp(buffer,"literal ")) {1409 patch_method = BINARY_LITERAL_DEFLATED;1410 origlen =strtoul(buffer +8, NULL,10);1411}1412else1413return NULL;14141415 linenr++;1416 buffer += llen;1417while(1) {1418int byte_length, max_byte_length, newsize;1419 llen =linelen(buffer, size);1420 used += llen;1421 linenr++;1422if(llen ==1) {1423/* consume the blank line */1424 buffer++;1425 size--;1426break;1427}1428/*1429 * Minimum line is "A00000\n" which is 7-byte long,1430 * and the line length must be multiple of 5 plus 2.1431 */1432if((llen <7) || (llen-2) %5)1433goto corrupt;1434 max_byte_length = (llen -2) /5*4;1435 byte_length = *buffer;1436if('A'<= byte_length && byte_length <='Z')1437 byte_length = byte_length -'A'+1;1438else if('a'<= byte_length && byte_length <='z')1439 byte_length = byte_length -'a'+27;1440else1441goto corrupt;1442/* if the input length was not multiple of 4, we would1443 * have filler at the end but the filler should never1444 * exceed 3 bytes1445 */1446if(max_byte_length < byte_length ||1447 byte_length <= max_byte_length -4)1448goto corrupt;1449 newsize = hunk_size + byte_length;1450 data =xrealloc(data, newsize);1451if(decode_85(data + hunk_size, buffer +1, byte_length))1452goto corrupt;1453 hunk_size = newsize;1454 buffer += llen;1455 size -= llen;1456}14571458 frag =xcalloc(1,sizeof(*frag));1459 frag->patch =inflate_it(data, hunk_size, origlen);1460if(!frag->patch)1461goto corrupt;1462free(data);1463 frag->size = origlen;1464*buf_p = buffer;1465*sz_p = size;1466*used_p = used;1467 frag->binary_patch_method = patch_method;1468return frag;14691470 corrupt:1471free(data);1472*status_p = -1;1473error("corrupt binary patch at line%d: %.*s",1474 linenr-1, llen-1, buffer);1475return NULL;1476}14771478static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1479{1480/*1481 * We have read "GIT binary patch\n"; what follows is a line1482 * that says the patch method (currently, either "literal" or1483 * "delta") and the length of data before deflating; a1484 * sequence of 'length-byte' followed by base-85 encoded data1485 * follows.1486 *1487 * When a binary patch is reversible, there is another binary1488 * hunk in the same format, starting with patch method (either1489 * "literal" or "delta") with the length of data, and a sequence1490 * of length-byte + base-85 encoded data, terminated with another1491 * empty line. This data, when applied to the postimage, produces1492 * the preimage.1493 */1494struct fragment *forward;1495struct fragment *reverse;1496int status;1497int used, used_1;14981499 forward =parse_binary_hunk(&buffer, &size, &status, &used);1500if(!forward && !status)1501/* there has to be one hunk (forward hunk) */1502returnerror("unrecognized binary patch at line%d", linenr-1);1503if(status)1504/* otherwise we already gave an error message */1505return status;15061507 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1508if(reverse)1509 used += used_1;1510else if(status) {1511/*1512 * Not having reverse hunk is not an error, but having1513 * a corrupt reverse hunk is.1514 */1515free((void*) forward->patch);1516free(forward);1517return status;1518}1519 forward->next = reverse;1520 patch->fragments = forward;1521 patch->is_binary =1;1522return used;1523}15241525static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1526{1527int hdrsize, patchsize;1528int offset =find_header(buffer, size, &hdrsize, patch);15291530if(offset <0)1531return offset;15321533 patch->ws_rule =whitespace_rule(patch->new_name1534? patch->new_name1535: patch->old_name);15361537 patchsize =parse_single_patch(buffer + offset + hdrsize,1538 size - offset - hdrsize, patch);15391540if(!patchsize) {1541static const char*binhdr[] = {1542"Binary files ",1543"Files ",1544 NULL,1545};1546static const char git_binary[] ="GIT binary patch\n";1547int i;1548int hd = hdrsize + offset;1549unsigned long llen =linelen(buffer + hd, size - hd);15501551if(llen ==sizeof(git_binary) -1&&1552!memcmp(git_binary, buffer + hd, llen)) {1553int used;1554 linenr++;1555 used =parse_binary(buffer + hd + llen,1556 size - hd - llen, patch);1557if(used)1558 patchsize = used + llen;1559else1560 patchsize =0;1561}1562else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1563for(i =0; binhdr[i]; i++) {1564int len =strlen(binhdr[i]);1565if(len < size - hd &&1566!memcmp(binhdr[i], buffer + hd, len)) {1567 linenr++;1568 patch->is_binary =1;1569 patchsize = llen;1570break;1571}1572}1573}15741575/* Empty patch cannot be applied if it is a text patch1576 * without metadata change. A binary patch appears1577 * empty to us here.1578 */1579if((apply || check) &&1580(!patch->is_binary && !metadata_changes(patch)))1581die("patch with only garbage at line%d", linenr);1582}15831584return offset + hdrsize + patchsize;1585}15861587#define swap(a,b) myswap((a),(b),sizeof(a))15881589#define myswap(a, b, size) do { \1590 unsigned char mytmp[size]; \1591 memcpy(mytmp, &a, size); \1592 memcpy(&a, &b, size); \1593 memcpy(&b, mytmp, size); \1594} while (0)15951596static voidreverse_patches(struct patch *p)1597{1598for(; p; p = p->next) {1599struct fragment *frag = p->fragments;16001601swap(p->new_name, p->old_name);1602swap(p->new_mode, p->old_mode);1603swap(p->is_new, p->is_delete);1604swap(p->lines_added, p->lines_deleted);1605swap(p->old_sha1_prefix, p->new_sha1_prefix);16061607for(; frag; frag = frag->next) {1608swap(frag->newpos, frag->oldpos);1609swap(frag->newlines, frag->oldlines);1610}1611}1612}16131614static const char pluses[] =1615"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";1616static const char minuses[]=1617"----------------------------------------------------------------------";16181619static voidshow_stats(struct patch *patch)1620{1621struct strbuf qname = STRBUF_INIT;1622char*cp = patch->new_name ? patch->new_name : patch->old_name;1623int max, add, del;16241625quote_c_style(cp, &qname, NULL,0);16261627/*1628 * "scale" the filename1629 */1630 max = max_len;1631if(max >50)1632 max =50;16331634if(qname.len > max) {1635 cp =strchr(qname.buf + qname.len +3- max,'/');1636if(!cp)1637 cp = qname.buf + qname.len +3- max;1638strbuf_splice(&qname,0, cp - qname.buf,"...",3);1639}16401641if(patch->is_binary) {1642printf(" %-*s | Bin\n", max, qname.buf);1643strbuf_release(&qname);1644return;1645}16461647printf(" %-*s |", max, qname.buf);1648strbuf_release(&qname);16491650/*1651 * scale the add/delete1652 */1653 max = max + max_change >70?70- max : max_change;1654 add = patch->lines_added;1655 del = patch->lines_deleted;16561657if(max_change >0) {1658int total = ((add + del) * max + max_change /2) / max_change;1659 add = (add * max + max_change /2) / max_change;1660 del = total - add;1661}1662printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,1663 add, pluses, del, minuses);1664}16651666static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)1667{1668switch(st->st_mode & S_IFMT) {1669case S_IFLNK:1670if(strbuf_readlink(buf, path, st->st_size) <0)1671returnerror("unable to read symlink%s", path);1672return0;1673case S_IFREG:1674if(strbuf_read_file(buf, path, st->st_size) != st->st_size)1675returnerror("unable to open or read%s", path);1676convert_to_git(path, buf->buf, buf->len, buf,0);1677return0;1678default:1679return-1;1680}1681}16821683static voidupdate_pre_post_images(struct image *preimage,1684struct image *postimage,1685char*buf,1686size_t len)1687{1688int i, ctx;1689char*new, *old, *fixed;1690struct image fixed_preimage;16911692/*1693 * Update the preimage with whitespace fixes. Note that we1694 * are not losing preimage->buf -- apply_one_fragment() will1695 * free "oldlines".1696 */1697prepare_image(&fixed_preimage, buf, len,1);1698assert(fixed_preimage.nr == preimage->nr);1699for(i =0; i < preimage->nr; i++)1700 fixed_preimage.line[i].flag = preimage->line[i].flag;1701free(preimage->line_allocated);1702*preimage = fixed_preimage;17031704/*1705 * Adjust the common context lines in postimage, in place.1706 * This is possible because whitespace fixing does not make1707 * the string grow.1708 */1709new= old = postimage->buf;1710 fixed = preimage->buf;1711for(i = ctx =0; i < postimage->nr; i++) {1712size_t len = postimage->line[i].len;1713if(!(postimage->line[i].flag & LINE_COMMON)) {1714/* an added line -- no counterparts in preimage */1715memmove(new, old, len);1716 old += len;1717new+= len;1718continue;1719}17201721/* a common context -- skip it in the original postimage */1722 old += len;17231724/* and find the corresponding one in the fixed preimage */1725while(ctx < preimage->nr &&1726!(preimage->line[ctx].flag & LINE_COMMON)) {1727 fixed += preimage->line[ctx].len;1728 ctx++;1729}1730if(preimage->nr <= ctx)1731die("oops");17321733/* and copy it in, while fixing the line length */1734 len = preimage->line[ctx].len;1735memcpy(new, fixed, len);1736new+= len;1737 fixed += len;1738 postimage->line[i].len = len;1739 ctx++;1740}17411742/* Fix the length of the whole thing */1743 postimage->len =new- postimage->buf;1744}17451746static intmatch_fragment(struct image *img,1747struct image *preimage,1748struct image *postimage,1749unsigned longtry,1750int try_lno,1751unsigned ws_rule,1752int match_beginning,int match_end)1753{1754int i;1755char*fixed_buf, *buf, *orig, *target;17561757if(preimage->nr + try_lno > img->nr)1758return0;17591760if(match_beginning && try_lno)1761return0;17621763if(match_end && preimage->nr + try_lno != img->nr)1764return0;17651766/* Quick hash check */1767for(i =0; i < preimage->nr; i++)1768if(preimage->line[i].hash != img->line[try_lno + i].hash)1769return0;17701771/*1772 * Do we have an exact match? If we were told to match1773 * at the end, size must be exactly at try+fragsize,1774 * otherwise try+fragsize must be still within the preimage,1775 * and either case, the old piece should match the preimage1776 * exactly.1777 */1778if((match_end1779? (try+ preimage->len == img->len)1780: (try+ preimage->len <= img->len)) &&1781!memcmp(img->buf +try, preimage->buf, preimage->len))1782return1;17831784if(ws_error_action != correct_ws_error)1785return0;17861787/*1788 * The hunk does not apply byte-by-byte, but the hash says1789 * it might with whitespace fuzz.1790 */1791 fixed_buf =xmalloc(preimage->len +1);1792 buf = fixed_buf;1793 orig = preimage->buf;1794 target = img->buf +try;1795for(i =0; i < preimage->nr; i++) {1796size_t fixlen;/* length after fixing the preimage */1797size_t oldlen = preimage->line[i].len;1798size_t tgtlen = img->line[try_lno + i].len;1799size_t tgtfixlen;/* length after fixing the target line */1800char tgtfixbuf[1024], *tgtfix;1801int match;18021803/* Try fixing the line in the preimage */1804 fixlen =ws_fix_copy(buf, orig, oldlen, ws_rule, NULL);18051806/* Try fixing the line in the target */1807if(sizeof(tgtfixbuf) > tgtlen)1808 tgtfix = tgtfixbuf;1809else1810 tgtfix =xmalloc(tgtlen);1811 tgtfixlen =ws_fix_copy(tgtfix, target, tgtlen, ws_rule, NULL);18121813/*1814 * If they match, either the preimage was based on1815 * a version before our tree fixed whitespace breakage,1816 * or we are lacking a whitespace-fix patch the tree1817 * the preimage was based on already had (i.e. target1818 * has whitespace breakage, the preimage doesn't).1819 * In either case, we are fixing the whitespace breakages1820 * so we might as well take the fix together with their1821 * real change.1822 */1823 match = (tgtfixlen == fixlen && !memcmp(tgtfix, buf, fixlen));18241825if(tgtfix != tgtfixbuf)1826free(tgtfix);1827if(!match)1828goto unmatch_exit;18291830 orig += oldlen;1831 buf += fixlen;1832 target += tgtlen;1833}18341835/*1836 * Yes, the preimage is based on an older version that still1837 * has whitespace breakages unfixed, and fixing them makes the1838 * hunk match. Update the context lines in the postimage.1839 */1840update_pre_post_images(preimage, postimage,1841 fixed_buf, buf - fixed_buf);1842return1;18431844 unmatch_exit:1845free(fixed_buf);1846return0;1847}18481849static intfind_pos(struct image *img,1850struct image *preimage,1851struct image *postimage,1852int line,1853unsigned ws_rule,1854int match_beginning,int match_end)1855{1856int i;1857unsigned long backwards, forwards,try;1858int backwards_lno, forwards_lno, try_lno;18591860if(preimage->nr > img->nr)1861return-1;18621863/*1864 * If match_begining or match_end is specified, there is no1865 * point starting from a wrong line that will never match and1866 * wander around and wait for a match at the specified end.1867 */1868if(match_beginning)1869 line =0;1870else if(match_end)1871 line = img->nr - preimage->nr;18721873if(line > img->nr)1874 line = img->nr;18751876try=0;1877for(i =0; i < line; i++)1878try+= img->line[i].len;18791880/*1881 * There's probably some smart way to do this, but I'll leave1882 * that to the smart and beautiful people. I'm simple and stupid.1883 */1884 backwards =try;1885 backwards_lno = line;1886 forwards =try;1887 forwards_lno = line;1888 try_lno = line;18891890for(i =0; ; i++) {1891if(match_fragment(img, preimage, postimage,1892try, try_lno, ws_rule,1893 match_beginning, match_end))1894return try_lno;18951896 again:1897if(backwards_lno ==0&& forwards_lno == img->nr)1898break;18991900if(i &1) {1901if(backwards_lno ==0) {1902 i++;1903goto again;1904}1905 backwards_lno--;1906 backwards -= img->line[backwards_lno].len;1907try= backwards;1908 try_lno = backwards_lno;1909}else{1910if(forwards_lno == img->nr) {1911 i++;1912goto again;1913}1914 forwards += img->line[forwards_lno].len;1915 forwards_lno++;1916try= forwards;1917 try_lno = forwards_lno;1918}19191920}1921return-1;1922}19231924static voidremove_first_line(struct image *img)1925{1926 img->buf += img->line[0].len;1927 img->len -= img->line[0].len;1928 img->line++;1929 img->nr--;1930}19311932static voidremove_last_line(struct image *img)1933{1934 img->len -= img->line[--img->nr].len;1935}19361937static voidupdate_image(struct image *img,1938int applied_pos,1939struct image *preimage,1940struct image *postimage)1941{1942/*1943 * remove the copy of preimage at offset in img1944 * and replace it with postimage1945 */1946int i, nr;1947size_t remove_count, insert_count, applied_at =0;1948char*result;19491950for(i =0; i < applied_pos; i++)1951 applied_at += img->line[i].len;19521953 remove_count =0;1954for(i =0; i < preimage->nr; i++)1955 remove_count += img->line[applied_pos + i].len;1956 insert_count = postimage->len;19571958/* Adjust the contents */1959 result =xmalloc(img->len + insert_count - remove_count +1);1960memcpy(result, img->buf, applied_at);1961memcpy(result + applied_at, postimage->buf, postimage->len);1962memcpy(result + applied_at + postimage->len,1963 img->buf + (applied_at + remove_count),1964 img->len - (applied_at + remove_count));1965free(img->buf);1966 img->buf = result;1967 img->len += insert_count - remove_count;1968 result[img->len] ='\0';19691970/* Adjust the line table */1971 nr = img->nr + postimage->nr - preimage->nr;1972if(preimage->nr < postimage->nr) {1973/*1974 * NOTE: this knows that we never call remove_first_line()1975 * on anything other than pre/post image.1976 */1977 img->line =xrealloc(img->line, nr *sizeof(*img->line));1978 img->line_allocated = img->line;1979}1980if(preimage->nr != postimage->nr)1981memmove(img->line + applied_pos + postimage->nr,1982 img->line + applied_pos + preimage->nr,1983(img->nr - (applied_pos + preimage->nr)) *1984sizeof(*img->line));1985memcpy(img->line + applied_pos,1986 postimage->line,1987 postimage->nr *sizeof(*img->line));1988 img->nr = nr;1989}19901991static intapply_one_fragment(struct image *img,struct fragment *frag,1992int inaccurate_eof,unsigned ws_rule)1993{1994int match_beginning, match_end;1995const char*patch = frag->patch;1996int size = frag->size;1997char*old, *new, *oldlines, *newlines;1998int new_blank_lines_at_end =0;1999unsigned long leading, trailing;2000int pos, applied_pos;2001struct image preimage;2002struct image postimage;20032004memset(&preimage,0,sizeof(preimage));2005memset(&postimage,0,sizeof(postimage));2006 oldlines =xmalloc(size);2007 newlines =xmalloc(size);20082009 old = oldlines;2010new= newlines;2011while(size >0) {2012char first;2013int len =linelen(patch, size);2014int plen, added;2015int added_blank_line =0;2016int is_blank_context =0;20172018if(!len)2019break;20202021/*2022 * "plen" is how much of the line we should use for2023 * the actual patch data. Normally we just remove the2024 * first character on the line, but if the line is2025 * followed by "\ No newline", then we also remove the2026 * last one (which is the newline, of course).2027 */2028 plen = len -1;2029if(len < size && patch[len] =='\\')2030 plen--;2031 first = *patch;2032if(apply_in_reverse) {2033if(first =='-')2034 first ='+';2035else if(first =='+')2036 first ='-';2037}20382039switch(first) {2040case'\n':2041/* Newer GNU diff, empty context line */2042if(plen <0)2043/* ... followed by '\No newline'; nothing */2044break;2045*old++ ='\n';2046*new++ ='\n';2047add_line_info(&preimage,"\n",1, LINE_COMMON);2048add_line_info(&postimage,"\n",1, LINE_COMMON);2049 is_blank_context =1;2050break;2051case' ':2052if(plen && (ws_rule & WS_BLANK_AT_EOF) &&2053ws_blank_line(patch +1, plen, ws_rule))2054 is_blank_context =1;2055case'-':2056memcpy(old, patch +1, plen);2057add_line_info(&preimage, old, plen,2058(first ==' '? LINE_COMMON :0));2059 old += plen;2060if(first =='-')2061break;2062/* Fall-through for ' ' */2063case'+':2064/* --no-add does not add new lines */2065if(first =='+'&& no_add)2066break;20672068if(first !='+'||2069!whitespace_error ||2070 ws_error_action != correct_ws_error) {2071memcpy(new, patch +1, plen);2072 added = plen;2073}2074else{2075 added =ws_fix_copy(new, patch +1, plen, ws_rule, &applied_after_fixing_ws);2076}2077add_line_info(&postimage,new, added,2078(first =='+'?0: LINE_COMMON));2079new+= added;2080if(first =='+'&&2081(ws_rule & WS_BLANK_AT_EOF) &&2082ws_blank_line(patch +1, plen, ws_rule))2083 added_blank_line =1;2084break;2085case'@':case'\\':2086/* Ignore it, we already handled it */2087break;2088default:2089if(apply_verbosely)2090error("invalid start of line: '%c'", first);2091return-1;2092}2093if(added_blank_line)2094 new_blank_lines_at_end++;2095else if(is_blank_context)2096;2097else2098 new_blank_lines_at_end =0;2099 patch += len;2100 size -= len;2101}2102if(inaccurate_eof &&2103 old > oldlines && old[-1] =='\n'&&2104new> newlines &&new[-1] =='\n') {2105 old--;2106new--;2107}21082109 leading = frag->leading;2110 trailing = frag->trailing;21112112/*2113 * A hunk to change lines at the beginning would begin with2114 * @@ -1,L +N,M @@2115 * but we need to be careful. -U0 that inserts before the second2116 * line also has this pattern.2117 *2118 * And a hunk to add to an empty file would begin with2119 * @@ -0,0 +N,M @@2120 *2121 * In other words, a hunk that is (frag->oldpos <= 1) with or2122 * without leading context must match at the beginning.2123 */2124 match_beginning = (!frag->oldpos ||2125(frag->oldpos ==1&& !unidiff_zero));21262127/*2128 * A hunk without trailing lines must match at the end.2129 * However, we simply cannot tell if a hunk must match end2130 * from the lack of trailing lines if the patch was generated2131 * with unidiff without any context.2132 */2133 match_end = !unidiff_zero && !trailing;21342135 pos = frag->newpos ? (frag->newpos -1) :0;2136 preimage.buf = oldlines;2137 preimage.len = old - oldlines;2138 postimage.buf = newlines;2139 postimage.len =new- newlines;2140 preimage.line = preimage.line_allocated;2141 postimage.line = postimage.line_allocated;21422143for(;;) {21442145 applied_pos =find_pos(img, &preimage, &postimage, pos,2146 ws_rule, match_beginning, match_end);21472148if(applied_pos >=0)2149break;21502151/* Am I at my context limits? */2152if((leading <= p_context) && (trailing <= p_context))2153break;2154if(match_beginning || match_end) {2155 match_beginning = match_end =0;2156continue;2157}21582159/*2160 * Reduce the number of context lines; reduce both2161 * leading and trailing if they are equal otherwise2162 * just reduce the larger context.2163 */2164if(leading >= trailing) {2165remove_first_line(&preimage);2166remove_first_line(&postimage);2167 pos--;2168 leading--;2169}2170if(trailing > leading) {2171remove_last_line(&preimage);2172remove_last_line(&postimage);2173 trailing--;2174}2175}21762177if(applied_pos >=0) {2178if(new_blank_lines_at_end &&2179 preimage.nr + applied_pos == img->nr &&2180(ws_rule & WS_BLANK_AT_EOF) &&2181 ws_error_action != nowarn_ws_error) {2182record_ws_error(WS_BLANK_AT_EOF,"+",1, frag->linenr);2183if(ws_error_action == correct_ws_error) {2184while(new_blank_lines_at_end--)2185remove_last_line(&postimage);2186}2187/*2188 * We would want to prevent write_out_results()2189 * from taking place in apply_patch() that follows2190 * the callchain led us here, which is:2191 * apply_patch->check_patch_list->check_patch->2192 * apply_data->apply_fragments->apply_one_fragment2193 */2194if(ws_error_action == die_on_ws_error)2195 apply =0;2196}21972198/*2199 * Warn if it was necessary to reduce the number2200 * of context lines.2201 */2202if((leading != frag->leading) ||2203(trailing != frag->trailing))2204fprintf(stderr,"Context reduced to (%ld/%ld)"2205" to apply fragment at%d\n",2206 leading, trailing, applied_pos+1);2207update_image(img, applied_pos, &preimage, &postimage);2208}else{2209if(apply_verbosely)2210error("while searching for:\n%.*s",2211(int)(old - oldlines), oldlines);2212}22132214free(oldlines);2215free(newlines);2216free(preimage.line_allocated);2217free(postimage.line_allocated);22182219return(applied_pos <0);2220}22212222static intapply_binary_fragment(struct image *img,struct patch *patch)2223{2224struct fragment *fragment = patch->fragments;2225unsigned long len;2226void*dst;22272228/* Binary patch is irreversible without the optional second hunk */2229if(apply_in_reverse) {2230if(!fragment->next)2231returnerror("cannot reverse-apply a binary patch "2232"without the reverse hunk to '%s'",2233 patch->new_name2234? patch->new_name : patch->old_name);2235 fragment = fragment->next;2236}2237switch(fragment->binary_patch_method) {2238case BINARY_DELTA_DEFLATED:2239 dst =patch_delta(img->buf, img->len, fragment->patch,2240 fragment->size, &len);2241if(!dst)2242return-1;2243clear_image(img);2244 img->buf = dst;2245 img->len = len;2246return0;2247case BINARY_LITERAL_DEFLATED:2248clear_image(img);2249 img->len = fragment->size;2250 img->buf =xmalloc(img->len+1);2251memcpy(img->buf, fragment->patch, img->len);2252 img->buf[img->len] ='\0';2253return0;2254}2255return-1;2256}22572258static intapply_binary(struct image *img,struct patch *patch)2259{2260const char*name = patch->old_name ? patch->old_name : patch->new_name;2261unsigned char sha1[20];22622263/*2264 * For safety, we require patch index line to contain2265 * full 40-byte textual SHA1 for old and new, at least for now.2266 */2267if(strlen(patch->old_sha1_prefix) !=40||2268strlen(patch->new_sha1_prefix) !=40||2269get_sha1_hex(patch->old_sha1_prefix, sha1) ||2270get_sha1_hex(patch->new_sha1_prefix, sha1))2271returnerror("cannot apply binary patch to '%s' "2272"without full index line", name);22732274if(patch->old_name) {2275/*2276 * See if the old one matches what the patch2277 * applies to.2278 */2279hash_sha1_file(img->buf, img->len, blob_type, sha1);2280if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2281returnerror("the patch applies to '%s' (%s), "2282"which does not match the "2283"current contents.",2284 name,sha1_to_hex(sha1));2285}2286else{2287/* Otherwise, the old one must be empty. */2288if(img->len)2289returnerror("the patch applies to an empty "2290"'%s' but it is not empty", name);2291}22922293get_sha1_hex(patch->new_sha1_prefix, sha1);2294if(is_null_sha1(sha1)) {2295clear_image(img);2296return0;/* deletion patch */2297}22982299if(has_sha1_file(sha1)) {2300/* We already have the postimage */2301enum object_type type;2302unsigned long size;2303char*result;23042305 result =read_sha1_file(sha1, &type, &size);2306if(!result)2307returnerror("the necessary postimage%sfor "2308"'%s' cannot be read",2309 patch->new_sha1_prefix, name);2310clear_image(img);2311 img->buf = result;2312 img->len = size;2313}else{2314/*2315 * We have verified buf matches the preimage;2316 * apply the patch data to it, which is stored2317 * in the patch->fragments->{patch,size}.2318 */2319if(apply_binary_fragment(img, patch))2320returnerror("binary patch does not apply to '%s'",2321 name);23222323/* verify that the result matches */2324hash_sha1_file(img->buf, img->len, blob_type, sha1);2325if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2326returnerror("binary patch to '%s' creates incorrect result (expecting%s, got%s)",2327 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2328}23292330return0;2331}23322333static intapply_fragments(struct image *img,struct patch *patch)2334{2335struct fragment *frag = patch->fragments;2336const char*name = patch->old_name ? patch->old_name : patch->new_name;2337unsigned ws_rule = patch->ws_rule;2338unsigned inaccurate_eof = patch->inaccurate_eof;23392340if(patch->is_binary)2341returnapply_binary(img, patch);23422343while(frag) {2344if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule)) {2345error("patch failed:%s:%ld", name, frag->oldpos);2346if(!apply_with_reject)2347return-1;2348 frag->rejected =1;2349}2350 frag = frag->next;2351}2352return0;2353}23542355static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2356{2357if(!ce)2358return0;23592360if(S_ISGITLINK(ce->ce_mode)) {2361strbuf_grow(buf,100);2362strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2363}else{2364enum object_type type;2365unsigned long sz;2366char*result;23672368 result =read_sha1_file(ce->sha1, &type, &sz);2369if(!result)2370return-1;2371/* XXX read_sha1_file NUL-terminates */2372strbuf_attach(buf, result, sz, sz +1);2373}2374return0;2375}23762377static struct patch *in_fn_table(const char*name)2378{2379struct string_list_item *item;23802381if(name == NULL)2382return NULL;23832384 item =string_list_lookup(name, &fn_table);2385if(item != NULL)2386return(struct patch *)item->util;23872388return NULL;2389}23902391/*2392 * item->util in the filename table records the status of the path.2393 * Usually it points at a patch (whose result records the contents2394 * of it after applying it), but it could be PATH_WAS_DELETED for a2395 * path that a previously applied patch has already removed.2396 */2397#define PATH_TO_BE_DELETED ((struct patch *) -2)2398#define PATH_WAS_DELETED ((struct patch *) -1)23992400static intto_be_deleted(struct patch *patch)2401{2402return patch == PATH_TO_BE_DELETED;2403}24042405static intwas_deleted(struct patch *patch)2406{2407return patch == PATH_WAS_DELETED;2408}24092410static voidadd_to_fn_table(struct patch *patch)2411{2412struct string_list_item *item;24132414/*2415 * Always add new_name unless patch is a deletion2416 * This should cover the cases for normal diffs,2417 * file creations and copies2418 */2419if(patch->new_name != NULL) {2420 item =string_list_insert(patch->new_name, &fn_table);2421 item->util = patch;2422}24232424/*2425 * store a failure on rename/deletion cases because2426 * later chunks shouldn't patch old names2427 */2428if((patch->new_name == NULL) || (patch->is_rename)) {2429 item =string_list_insert(patch->old_name, &fn_table);2430 item->util = PATH_WAS_DELETED;2431}2432}24332434static voidprepare_fn_table(struct patch *patch)2435{2436/*2437 * store information about incoming file deletion2438 */2439while(patch) {2440if((patch->new_name == NULL) || (patch->is_rename)) {2441struct string_list_item *item;2442 item =string_list_insert(patch->old_name, &fn_table);2443 item->util = PATH_TO_BE_DELETED;2444}2445 patch = patch->next;2446}2447}24482449static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)2450{2451struct strbuf buf = STRBUF_INIT;2452struct image image;2453size_t len;2454char*img;2455struct patch *tpatch;24562457if(!(patch->is_copy || patch->is_rename) &&2458(tpatch =in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {2459if(was_deleted(tpatch)) {2460returnerror("patch%shas been renamed/deleted",2461 patch->old_name);2462}2463/* We have a patched copy in memory use that */2464strbuf_add(&buf, tpatch->result, tpatch->resultsize);2465}else if(cached) {2466if(read_file_or_gitlink(ce, &buf))2467returnerror("read of%sfailed", patch->old_name);2468}else if(patch->old_name) {2469if(S_ISGITLINK(patch->old_mode)) {2470if(ce) {2471read_file_or_gitlink(ce, &buf);2472}else{2473/*2474 * There is no way to apply subproject2475 * patch without looking at the index.2476 */2477 patch->fragments = NULL;2478}2479}else{2480if(read_old_data(st, patch->old_name, &buf))2481returnerror("read of%sfailed", patch->old_name);2482}2483}24842485 img =strbuf_detach(&buf, &len);2486prepare_image(&image, img, len, !patch->is_binary);24872488if(apply_fragments(&image, patch) <0)2489return-1;/* note with --reject this succeeds. */2490 patch->result = image.buf;2491 patch->resultsize = image.len;2492add_to_fn_table(patch);2493free(image.line_allocated);24942495if(0< patch->is_delete && patch->resultsize)2496returnerror("removal patch leaves file contents");24972498return0;2499}25002501static intcheck_to_create_blob(const char*new_name,int ok_if_exists)2502{2503struct stat nst;2504if(!lstat(new_name, &nst)) {2505if(S_ISDIR(nst.st_mode) || ok_if_exists)2506return0;2507/*2508 * A leading component of new_name might be a symlink2509 * that is going to be removed with this patch, but2510 * still pointing at somewhere that has the path.2511 * In such a case, path "new_name" does not exist as2512 * far as git is concerned.2513 */2514if(has_symlink_leading_path(new_name,strlen(new_name)))2515return0;25162517returnerror("%s: already exists in working directory", new_name);2518}2519else if((errno != ENOENT) && (errno != ENOTDIR))2520returnerror("%s:%s", new_name,strerror(errno));2521return0;2522}25232524static intverify_index_match(struct cache_entry *ce,struct stat *st)2525{2526if(S_ISGITLINK(ce->ce_mode)) {2527if(!S_ISDIR(st->st_mode))2528return-1;2529return0;2530}2531returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID);2532}25332534static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)2535{2536const char*old_name = patch->old_name;2537struct patch *tpatch = NULL;2538int stat_ret =0;2539unsigned st_mode =0;25402541/*2542 * Make sure that we do not have local modifications from the2543 * index when we are looking at the index. Also make sure2544 * we have the preimage file to be patched in the work tree,2545 * unless --cached, which tells git to apply only in the index.2546 */2547if(!old_name)2548return0;25492550assert(patch->is_new <=0);25512552if(!(patch->is_copy || patch->is_rename) &&2553(tpatch =in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {2554if(was_deleted(tpatch))2555returnerror("%s: has been deleted/renamed", old_name);2556 st_mode = tpatch->new_mode;2557}else if(!cached) {2558 stat_ret =lstat(old_name, st);2559if(stat_ret && errno != ENOENT)2560returnerror("%s:%s", old_name,strerror(errno));2561}25622563if(to_be_deleted(tpatch))2564 tpatch = NULL;25652566if(check_index && !tpatch) {2567int pos =cache_name_pos(old_name,strlen(old_name));2568if(pos <0) {2569if(patch->is_new <0)2570goto is_new;2571returnerror("%s: does not exist in index", old_name);2572}2573*ce = active_cache[pos];2574if(stat_ret <0) {2575struct checkout costate;2576/* checkout */2577 costate.base_dir ="";2578 costate.base_dir_len =0;2579 costate.force =0;2580 costate.quiet =0;2581 costate.not_new =0;2582 costate.refresh_cache =1;2583if(checkout_entry(*ce, &costate, NULL) ||2584lstat(old_name, st))2585return-1;2586}2587if(!cached &&verify_index_match(*ce, st))2588returnerror("%s: does not match index", old_name);2589if(cached)2590 st_mode = (*ce)->ce_mode;2591}else if(stat_ret <0) {2592if(patch->is_new <0)2593goto is_new;2594returnerror("%s:%s", old_name,strerror(errno));2595}25962597if(!cached && !tpatch)2598 st_mode =ce_mode_from_stat(*ce, st->st_mode);25992600if(patch->is_new <0)2601 patch->is_new =0;2602if(!patch->old_mode)2603 patch->old_mode = st_mode;2604if((st_mode ^ patch->old_mode) & S_IFMT)2605returnerror("%s: wrong type", old_name);2606if(st_mode != patch->old_mode)2607warning("%shas type%o, expected%o",2608 old_name, st_mode, patch->old_mode);2609if(!patch->new_mode && !patch->is_delete)2610 patch->new_mode = st_mode;2611return0;26122613 is_new:2614 patch->is_new =1;2615 patch->is_delete =0;2616 patch->old_name = NULL;2617return0;2618}26192620static intcheck_patch(struct patch *patch)2621{2622struct stat st;2623const char*old_name = patch->old_name;2624const char*new_name = patch->new_name;2625const char*name = old_name ? old_name : new_name;2626struct cache_entry *ce = NULL;2627struct patch *tpatch;2628int ok_if_exists;2629int status;26302631 patch->rejected =1;/* we will drop this after we succeed */26322633 status =check_preimage(patch, &ce, &st);2634if(status)2635return status;2636 old_name = patch->old_name;26372638if((tpatch =in_fn_table(new_name)) &&2639(was_deleted(tpatch) ||to_be_deleted(tpatch)))2640/*2641 * A type-change diff is always split into a patch to2642 * delete old, immediately followed by a patch to2643 * create new (see diff.c::run_diff()); in such a case2644 * it is Ok that the entry to be deleted by the2645 * previous patch is still in the working tree and in2646 * the index.2647 */2648 ok_if_exists =1;2649else2650 ok_if_exists =0;26512652if(new_name &&2653((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {2654if(check_index &&2655cache_name_pos(new_name,strlen(new_name)) >=0&&2656!ok_if_exists)2657returnerror("%s: already exists in index", new_name);2658if(!cached) {2659int err =check_to_create_blob(new_name, ok_if_exists);2660if(err)2661return err;2662}2663if(!patch->new_mode) {2664if(0< patch->is_new)2665 patch->new_mode = S_IFREG |0644;2666else2667 patch->new_mode = patch->old_mode;2668}2669}26702671if(new_name && old_name) {2672int same = !strcmp(old_name, new_name);2673if(!patch->new_mode)2674 patch->new_mode = patch->old_mode;2675if((patch->old_mode ^ patch->new_mode) & S_IFMT)2676returnerror("new mode (%o) of%sdoes not match old mode (%o)%s%s",2677 patch->new_mode, new_name, patch->old_mode,2678 same ?"":" of ", same ?"": old_name);2679}26802681if(apply_data(patch, &st, ce) <0)2682returnerror("%s: patch does not apply", name);2683 patch->rejected =0;2684return0;2685}26862687static intcheck_patch_list(struct patch *patch)2688{2689int err =0;26902691prepare_fn_table(patch);2692while(patch) {2693if(apply_verbosely)2694say_patch_name(stderr,2695"Checking patch ", patch,"...\n");2696 err |=check_patch(patch);2697 patch = patch->next;2698}2699return err;2700}27012702/* This function tries to read the sha1 from the current index */2703static intget_current_sha1(const char*path,unsigned char*sha1)2704{2705int pos;27062707if(read_cache() <0)2708return-1;2709 pos =cache_name_pos(path,strlen(path));2710if(pos <0)2711return-1;2712hashcpy(sha1, active_cache[pos]->sha1);2713return0;2714}27152716/* Build an index that contains the just the files needed for a 3way merge */2717static voidbuild_fake_ancestor(struct patch *list,const char*filename)2718{2719struct patch *patch;2720struct index_state result = { NULL };2721int fd;27222723/* Once we start supporting the reverse patch, it may be2724 * worth showing the new sha1 prefix, but until then...2725 */2726for(patch = list; patch; patch = patch->next) {2727const unsigned char*sha1_ptr;2728unsigned char sha1[20];2729struct cache_entry *ce;2730const char*name;27312732 name = patch->old_name ? patch->old_name : patch->new_name;2733if(0< patch->is_new)2734continue;2735else if(get_sha1(patch->old_sha1_prefix, sha1))2736/* git diff has no index line for mode/type changes */2737if(!patch->lines_added && !patch->lines_deleted) {2738if(get_current_sha1(patch->new_name, sha1) ||2739get_current_sha1(patch->old_name, sha1))2740die("mode change for%s, which is not "2741"in current HEAD", name);2742 sha1_ptr = sha1;2743}else2744die("sha1 information is lacking or useless "2745"(%s).", name);2746else2747 sha1_ptr = sha1;27482749 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);2750if(!ce)2751die("make_cache_entry failed for path '%s'", name);2752if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))2753die("Could not add%sto temporary index", name);2754}27552756 fd =open(filename, O_WRONLY | O_CREAT,0666);2757if(fd <0||write_index(&result, fd) ||close(fd))2758die("Could not write temporary index to%s", filename);27592760discard_index(&result);2761}27622763static voidstat_patch_list(struct patch *patch)2764{2765int files, adds, dels;27662767for(files = adds = dels =0; patch ; patch = patch->next) {2768 files++;2769 adds += patch->lines_added;2770 dels += patch->lines_deleted;2771show_stats(patch);2772}27732774printf("%dfiles changed,%dinsertions(+),%ddeletions(-)\n", files, adds, dels);2775}27762777static voidnumstat_patch_list(struct patch *patch)2778{2779for( ; patch; patch = patch->next) {2780const char*name;2781 name = patch->new_name ? patch->new_name : patch->old_name;2782if(patch->is_binary)2783printf("-\t-\t");2784else2785printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);2786write_name_quoted(name, stdout, line_termination);2787}2788}27892790static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)2791{2792if(mode)2793printf("%smode%06o%s\n", newdelete, mode, name);2794else2795printf("%s %s\n", newdelete, name);2796}27972798static voidshow_mode_change(struct patch *p,int show_name)2799{2800if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {2801if(show_name)2802printf(" mode change%06o =>%06o%s\n",2803 p->old_mode, p->new_mode, p->new_name);2804else2805printf(" mode change%06o =>%06o\n",2806 p->old_mode, p->new_mode);2807}2808}28092810static voidshow_rename_copy(struct patch *p)2811{2812const char*renamecopy = p->is_rename ?"rename":"copy";2813const char*old, *new;28142815/* Find common prefix */2816 old = p->old_name;2817new= p->new_name;2818while(1) {2819const char*slash_old, *slash_new;2820 slash_old =strchr(old,'/');2821 slash_new =strchr(new,'/');2822if(!slash_old ||2823!slash_new ||2824 slash_old - old != slash_new -new||2825memcmp(old,new, slash_new -new))2826break;2827 old = slash_old +1;2828new= slash_new +1;2829}2830/* p->old_name thru old is the common prefix, and old and new2831 * through the end of names are renames2832 */2833if(old != p->old_name)2834printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,2835(int)(old - p->old_name), p->old_name,2836 old,new, p->score);2837else2838printf("%s %s=>%s(%d%%)\n", renamecopy,2839 p->old_name, p->new_name, p->score);2840show_mode_change(p,0);2841}28422843static voidsummary_patch_list(struct patch *patch)2844{2845struct patch *p;28462847for(p = patch; p; p = p->next) {2848if(p->is_new)2849show_file_mode_name("create", p->new_mode, p->new_name);2850else if(p->is_delete)2851show_file_mode_name("delete", p->old_mode, p->old_name);2852else{2853if(p->is_rename || p->is_copy)2854show_rename_copy(p);2855else{2856if(p->score) {2857printf(" rewrite%s(%d%%)\n",2858 p->new_name, p->score);2859show_mode_change(p,0);2860}2861else2862show_mode_change(p,1);2863}2864}2865}2866}28672868static voidpatch_stats(struct patch *patch)2869{2870int lines = patch->lines_added + patch->lines_deleted;28712872if(lines > max_change)2873 max_change = lines;2874if(patch->old_name) {2875int len =quote_c_style(patch->old_name, NULL, NULL,0);2876if(!len)2877 len =strlen(patch->old_name);2878if(len > max_len)2879 max_len = len;2880}2881if(patch->new_name) {2882int len =quote_c_style(patch->new_name, NULL, NULL,0);2883if(!len)2884 len =strlen(patch->new_name);2885if(len > max_len)2886 max_len = len;2887}2888}28892890static voidremove_file(struct patch *patch,int rmdir_empty)2891{2892if(update_index) {2893if(remove_file_from_cache(patch->old_name) <0)2894die("unable to remove%sfrom index", patch->old_name);2895}2896if(!cached) {2897if(S_ISGITLINK(patch->old_mode)) {2898if(rmdir(patch->old_name))2899warning("unable to remove submodule%s",2900 patch->old_name);2901}else if(!unlink_or_warn(patch->old_name) && rmdir_empty) {2902remove_path(patch->old_name);2903}2904}2905}29062907static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)2908{2909struct stat st;2910struct cache_entry *ce;2911int namelen =strlen(path);2912unsigned ce_size =cache_entry_size(namelen);29132914if(!update_index)2915return;29162917 ce =xcalloc(1, ce_size);2918memcpy(ce->name, path, namelen);2919 ce->ce_mode =create_ce_mode(mode);2920 ce->ce_flags = namelen;2921if(S_ISGITLINK(mode)) {2922const char*s = buf;29232924if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))2925die("corrupt patch for subproject%s", path);2926}else{2927if(!cached) {2928if(lstat(path, &st) <0)2929die_errno("unable to stat newly created file '%s'",2930 path);2931fill_stat_cache_info(ce, &st);2932}2933if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)2934die("unable to create backing store for newly created file%s", path);2935}2936if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)2937die("unable to add cache entry for%s", path);2938}29392940static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)2941{2942int fd;2943struct strbuf nbuf = STRBUF_INIT;29442945if(S_ISGITLINK(mode)) {2946struct stat st;2947if(!lstat(path, &st) &&S_ISDIR(st.st_mode))2948return0;2949returnmkdir(path,0777);2950}29512952if(has_symlinks &&S_ISLNK(mode))2953/* Although buf:size is counted string, it also is NUL2954 * terminated.2955 */2956returnsymlink(buf, path);29572958 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);2959if(fd <0)2960return-1;29612962if(convert_to_working_tree(path, buf, size, &nbuf)) {2963 size = nbuf.len;2964 buf = nbuf.buf;2965}2966write_or_die(fd, buf, size);2967strbuf_release(&nbuf);29682969if(close(fd) <0)2970die_errno("closing file '%s'", path);2971return0;2972}29732974/*2975 * We optimistically assume that the directories exist,2976 * which is true 99% of the time anyway. If they don't,2977 * we create them and try again.2978 */2979static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)2980{2981if(cached)2982return;2983if(!try_create_file(path, mode, buf, size))2984return;29852986if(errno == ENOENT) {2987if(safe_create_leading_directories(path))2988return;2989if(!try_create_file(path, mode, buf, size))2990return;2991}29922993if(errno == EEXIST || errno == EACCES) {2994/* We may be trying to create a file where a directory2995 * used to be.2996 */2997struct stat st;2998if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))2999 errno = EEXIST;3000}30013002if(errno == EEXIST) {3003unsigned int nr =getpid();30043005for(;;) {3006char newpath[PATH_MAX];3007mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);3008if(!try_create_file(newpath, mode, buf, size)) {3009if(!rename(newpath, path))3010return;3011unlink_or_warn(newpath);3012break;3013}3014if(errno != EEXIST)3015break;3016++nr;3017}3018}3019die_errno("unable to write file '%s' mode%o", path, mode);3020}30213022static voidcreate_file(struct patch *patch)3023{3024char*path = patch->new_name;3025unsigned mode = patch->new_mode;3026unsigned long size = patch->resultsize;3027char*buf = patch->result;30283029if(!mode)3030 mode = S_IFREG |0644;3031create_one_file(path, mode, buf, size);3032add_index_file(path, mode, buf, size);3033}30343035/* phase zero is to remove, phase one is to create */3036static voidwrite_out_one_result(struct patch *patch,int phase)3037{3038if(patch->is_delete >0) {3039if(phase ==0)3040remove_file(patch,1);3041return;3042}3043if(patch->is_new >0|| patch->is_copy) {3044if(phase ==1)3045create_file(patch);3046return;3047}3048/*3049 * Rename or modification boils down to the same3050 * thing: remove the old, write the new3051 */3052if(phase ==0)3053remove_file(patch, patch->is_rename);3054if(phase ==1)3055create_file(patch);3056}30573058static intwrite_out_one_reject(struct patch *patch)3059{3060FILE*rej;3061char namebuf[PATH_MAX];3062struct fragment *frag;3063int cnt =0;30643065for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {3066if(!frag->rejected)3067continue;3068 cnt++;3069}30703071if(!cnt) {3072if(apply_verbosely)3073say_patch_name(stderr,3074"Applied patch ", patch," cleanly.\n");3075return0;3076}30773078/* This should not happen, because a removal patch that leaves3079 * contents are marked "rejected" at the patch level.3080 */3081if(!patch->new_name)3082die("internal error");30833084/* Say this even without --verbose */3085say_patch_name(stderr,"Applying patch ", patch," with");3086fprintf(stderr,"%drejects...\n", cnt);30873088 cnt =strlen(patch->new_name);3089if(ARRAY_SIZE(namebuf) <= cnt +5) {3090 cnt =ARRAY_SIZE(namebuf) -5;3091warning("truncating .rej filename to %.*s.rej",3092 cnt -1, patch->new_name);3093}3094memcpy(namebuf, patch->new_name, cnt);3095memcpy(namebuf + cnt,".rej",5);30963097 rej =fopen(namebuf,"w");3098if(!rej)3099returnerror("cannot open%s:%s", namebuf,strerror(errno));31003101/* Normal git tools never deal with .rej, so do not pretend3102 * this is a git patch by saying --git nor give extended3103 * headers. While at it, maybe please "kompare" that wants3104 * the trailing TAB and some garbage at the end of line ;-).3105 */3106fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",3107 patch->new_name, patch->new_name);3108for(cnt =1, frag = patch->fragments;3109 frag;3110 cnt++, frag = frag->next) {3111if(!frag->rejected) {3112fprintf(stderr,"Hunk #%dapplied cleanly.\n", cnt);3113continue;3114}3115fprintf(stderr,"Rejected hunk #%d.\n", cnt);3116fprintf(rej,"%.*s", frag->size, frag->patch);3117if(frag->patch[frag->size-1] !='\n')3118fputc('\n', rej);3119}3120fclose(rej);3121return-1;3122}31233124static intwrite_out_results(struct patch *list,int skipped_patch)3125{3126int phase;3127int errs =0;3128struct patch *l;31293130if(!list && !skipped_patch)3131returnerror("No changes");31323133for(phase =0; phase <2; phase++) {3134 l = list;3135while(l) {3136if(l->rejected)3137 errs =1;3138else{3139write_out_one_result(l, phase);3140if(phase ==1&&write_out_one_reject(l))3141 errs =1;3142}3143 l = l->next;3144}3145}3146return errs;3147}31483149static struct lock_file lock_file;31503151static struct string_list limit_by_name;3152static int has_include;3153static voidadd_name_limit(const char*name,int exclude)3154{3155struct string_list_item *it;31563157 it =string_list_append(name, &limit_by_name);3158 it->util = exclude ? NULL : (void*)1;3159}31603161static intuse_patch(struct patch *p)3162{3163const char*pathname = p->new_name ? p->new_name : p->old_name;3164int i;31653166/* Paths outside are not touched regardless of "--include" */3167if(0< prefix_length) {3168int pathlen =strlen(pathname);3169if(pathlen <= prefix_length ||3170memcmp(prefix, pathname, prefix_length))3171return0;3172}31733174/* See if it matches any of exclude/include rule */3175for(i =0; i < limit_by_name.nr; i++) {3176struct string_list_item *it = &limit_by_name.items[i];3177if(!fnmatch(it->string, pathname,0))3178return(it->util != NULL);3179}31803181/*3182 * If we had any include, a path that does not match any rule is3183 * not used. Otherwise, we saw bunch of exclude rules (or none)3184 * and such a path is used.3185 */3186return!has_include;3187}318831893190static voidprefix_one(char**name)3191{3192char*old_name = *name;3193if(!old_name)3194return;3195*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3196free(old_name);3197}31983199static voidprefix_patches(struct patch *p)3200{3201if(!prefix || p->is_toplevel_relative)3202return;3203for( ; p; p = p->next) {3204if(p->new_name == p->old_name) {3205char*prefixed = p->new_name;3206prefix_one(&prefixed);3207 p->new_name = p->old_name = prefixed;3208}3209else{3210prefix_one(&p->new_name);3211prefix_one(&p->old_name);3212}3213}3214}32153216#define INACCURATE_EOF (1<<0)3217#define RECOUNT (1<<1)32183219static intapply_patch(int fd,const char*filename,int options)3220{3221size_t offset;3222struct strbuf buf = STRBUF_INIT;3223struct patch *list = NULL, **listp = &list;3224int skipped_patch =0;32253226/* FIXME - memory leak when using multiple patch files as inputs */3227memset(&fn_table,0,sizeof(struct string_list));3228 patch_input_file = filename;3229read_patch_file(&buf, fd);3230 offset =0;3231while(offset < buf.len) {3232struct patch *patch;3233int nr;32343235 patch =xcalloc(1,sizeof(*patch));3236 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3237 patch->recount = !!(options & RECOUNT);3238 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3239if(nr <0)3240break;3241if(apply_in_reverse)3242reverse_patches(patch);3243if(prefix)3244prefix_patches(patch);3245if(use_patch(patch)) {3246patch_stats(patch);3247*listp = patch;3248 listp = &patch->next;3249}3250else{3251/* perhaps free it a bit better? */3252free(patch);3253 skipped_patch++;3254}3255 offset += nr;3256}32573258if(whitespace_error && (ws_error_action == die_on_ws_error))3259 apply =0;32603261 update_index = check_index && apply;3262if(update_index && newfd <0)3263 newfd =hold_locked_index(&lock_file,1);32643265if(check_index) {3266if(read_cache() <0)3267die("unable to read index file");3268}32693270if((check || apply) &&3271check_patch_list(list) <0&&3272!apply_with_reject)3273exit(1);32743275if(apply &&write_out_results(list, skipped_patch))3276exit(1);32773278if(fake_ancestor)3279build_fake_ancestor(list, fake_ancestor);32803281if(diffstat)3282stat_patch_list(list);32833284if(numstat)3285numstat_patch_list(list);32863287if(summary)3288summary_patch_list(list);32893290strbuf_release(&buf);3291return0;3292}32933294static intgit_apply_config(const char*var,const char*value,void*cb)3295{3296if(!strcmp(var,"apply.whitespace"))3297returngit_config_string(&apply_default_whitespace, var, value);3298returngit_default_config(var, value, cb);3299}33003301static intoption_parse_exclude(const struct option *opt,3302const char*arg,int unset)3303{3304add_name_limit(arg,1);3305return0;3306}33073308static intoption_parse_include(const struct option *opt,3309const char*arg,int unset)3310{3311add_name_limit(arg,0);3312 has_include =1;3313return0;3314}33153316static intoption_parse_p(const struct option *opt,3317const char*arg,int unset)3318{3319 p_value =atoi(arg);3320 p_value_known =1;3321return0;3322}33233324static intoption_parse_z(const struct option *opt,3325const char*arg,int unset)3326{3327if(unset)3328 line_termination ='\n';3329else3330 line_termination =0;3331return0;3332}33333334static intoption_parse_whitespace(const struct option *opt,3335const char*arg,int unset)3336{3337const char**whitespace_option = opt->value;33383339*whitespace_option = arg;3340parse_whitespace_option(arg);3341return0;3342}33433344static intoption_parse_directory(const struct option *opt,3345const char*arg,int unset)3346{3347 root_len =strlen(arg);3348if(root_len && arg[root_len -1] !='/') {3349char*new_root;3350 root = new_root =xmalloc(root_len +2);3351strcpy(new_root, arg);3352strcpy(new_root + root_len++,"/");3353}else3354 root = arg;3355return0;3356}33573358intcmd_apply(int argc,const char**argv,const char*unused_prefix)3359{3360int i;3361int errs =0;3362int is_not_gitdir;3363int binary;3364int force_apply =0;33653366const char*whitespace_option = NULL;33673368struct option builtin_apply_options[] = {3369{ OPTION_CALLBACK,0,"exclude", NULL,"path",3370"don't apply changes matching the given path",33710, option_parse_exclude },3372{ OPTION_CALLBACK,0,"include", NULL,"path",3373"apply changes matching the given path",33740, option_parse_include },3375{ OPTION_CALLBACK,'p', NULL, NULL,"num",3376"remove <num> leading slashes from traditional diff paths",33770, option_parse_p },3378OPT_BOOLEAN(0,"no-add", &no_add,3379"ignore additions made by the patch"),3380OPT_BOOLEAN(0,"stat", &diffstat,3381"instead of applying the patch, output diffstat for the input"),3382{ OPTION_BOOLEAN,0,"allow-binary-replacement", &binary,3383 NULL,"old option, now no-op",3384 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3385{ OPTION_BOOLEAN,0,"binary", &binary,3386 NULL,"old option, now no-op",3387 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3388OPT_BOOLEAN(0,"numstat", &numstat,3389"shows number of added and deleted lines in decimal notation"),3390OPT_BOOLEAN(0,"summary", &summary,3391"instead of applying the patch, output a summary for the input"),3392OPT_BOOLEAN(0,"check", &check,3393"instead of applying the patch, see if the patch is applicable"),3394OPT_BOOLEAN(0,"index", &check_index,3395"make sure the patch is applicable to the current index"),3396OPT_BOOLEAN(0,"cached", &cached,3397"apply a patch without touching the working tree"),3398OPT_BOOLEAN(0,"apply", &force_apply,3399"also apply the patch (use with --stat/--summary/--check)"),3400OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,3401"build a temporary index based on embedded index information"),3402{ OPTION_CALLBACK,'z', NULL, NULL, NULL,3403"paths are separated with NUL character",3404 PARSE_OPT_NOARG, option_parse_z },3405OPT_INTEGER('C', NULL, &p_context,3406"ensure at least <n> lines of context match"),3407{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,"action",3408"detect new or modified lines that have whitespace errors",34090, option_parse_whitespace },3410OPT_BOOLEAN('R',"reverse", &apply_in_reverse,3411"apply the patch in reverse"),3412OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,3413"don't expect at least one line of context"),3414OPT_BOOLEAN(0,"reject", &apply_with_reject,3415"leave the rejected hunks in corresponding *.rej files"),3416OPT__VERBOSE(&apply_verbosely),3417OPT_BIT(0,"inaccurate-eof", &options,3418"tolerate incorrectly detected missing new-line at the end of file",3419 INACCURATE_EOF),3420OPT_BIT(0,"recount", &options,3421"do not trust the line counts in the hunk headers",3422 RECOUNT),3423{ OPTION_CALLBACK,0,"directory", NULL,"root",3424"prepend <root> to all filenames",34250, option_parse_directory },3426OPT_END()3427};34283429 prefix =setup_git_directory_gently(&is_not_gitdir);3430 prefix_length = prefix ?strlen(prefix) :0;3431git_config(git_apply_config, NULL);3432if(apply_default_whitespace)3433parse_whitespace_option(apply_default_whitespace);34343435 argc =parse_options(argc, argv, prefix, builtin_apply_options,3436 apply_usage,0);34373438if(apply_with_reject)3439 apply = apply_verbosely =1;3440if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))3441 apply =0;3442if(check_index && is_not_gitdir)3443die("--index outside a repository");3444if(cached) {3445if(is_not_gitdir)3446die("--cached outside a repository");3447 check_index =1;3448}3449for(i =0; i < argc; i++) {3450const char*arg = argv[i];3451int fd;34523453if(!strcmp(arg,"-")) {3454 errs |=apply_patch(0,"<stdin>", options);3455 read_stdin =0;3456continue;3457}else if(0< prefix_length)3458 arg =prefix_filename(prefix, prefix_length, arg);34593460 fd =open(arg, O_RDONLY);3461if(fd <0)3462die_errno("can't open patch '%s'", arg);3463 read_stdin =0;3464set_default_whitespace_mode(whitespace_option);3465 errs |=apply_patch(fd, arg, options);3466close(fd);3467}3468set_default_whitespace_mode(whitespace_option);3469if(read_stdin)3470 errs |=apply_patch(0,"<stdin>", options);3471if(whitespace_error) {3472if(squelch_whitespace_errors &&3473 squelch_whitespace_errors < whitespace_error) {3474int squelched =3475 whitespace_error - squelch_whitespace_errors;3476warning("squelched%d"3477"whitespace error%s",3478 squelched,3479 squelched ==1?"":"s");3480}3481if(ws_error_action == die_on_ws_error)3482die("%dline%sadd%swhitespace errors.",3483 whitespace_error,3484 whitespace_error ==1?"":"s",3485 whitespace_error ==1?"s":"");3486if(applied_after_fixing_ws && apply)3487warning("%dline%sapplied after"3488" fixing whitespace errors.",3489 applied_after_fixing_ws,3490 applied_after_fixing_ws ==1?"":"s");3491else if(whitespace_error)3492warning("%dline%sadd%swhitespace errors.",3493 whitespace_error,3494 whitespace_error ==1?"":"s",3495 whitespace_error ==1?"s":"");3496}34973498if(update_index) {3499if(write_cache(newfd, active_cache, active_nr) ||3500commit_locked_index(&lock_file))3501die("Unable to write new index file");3502}35033504return!!errs;3505}