1/* 2 * apply.c 3 * 4 * Copyright (C) Linus Torvalds, 2005 5 * 6 * This applies patches on top of some (arbitrary) version of the SCM. 7 * 8 */ 9#include"cache.h" 10#include"cache-tree.h" 11#include"quote.h" 12#include"blob.h" 13#include"delta.h" 14#include"builtin.h" 15#include"string-list.h" 16#include"dir.h" 17#include"parse-options.h" 18 19/* 20 * --check turns on checking that the working tree matches the 21 * files that are being modified, but doesn't apply the patch 22 * --stat does just a diffstat, and doesn't actually apply 23 * --numstat does numeric diffstat, and doesn't actually apply 24 * --index-info shows the old and new index info for paths if available. 25 * --index updates the cache as well. 26 * --cached updates only the cache without ever touching the working tree. 27 */ 28static const char*prefix; 29static int prefix_length = -1; 30static int newfd = -1; 31 32static int unidiff_zero; 33static int p_value =1; 34static int p_value_known; 35static int check_index; 36static int update_index; 37static int cached; 38static int diffstat; 39static int numstat; 40static int summary; 41static int check; 42static int apply =1; 43static int apply_in_reverse; 44static int apply_with_reject; 45static int apply_verbosely; 46static int no_add; 47static const char*fake_ancestor; 48static int line_termination ='\n'; 49static unsigned int p_context = UINT_MAX; 50static const char*const apply_usage[] = { 51"git apply [options] [<patch>...]", 52 NULL 53}; 54 55static enum ws_error_action { 56 nowarn_ws_error, 57 warn_on_ws_error, 58 die_on_ws_error, 59 correct_ws_error, 60} ws_error_action = warn_on_ws_error; 61static int whitespace_error; 62static int squelch_whitespace_errors =5; 63static int applied_after_fixing_ws; 64 65static enum ws_ignore { 66 ignore_ws_none, 67 ignore_ws_change, 68} ws_ignore_action = ignore_ws_none; 69 70 71static const char*patch_input_file; 72static const char*root; 73static int root_len; 74static int read_stdin =1; 75static int options; 76 77static voidparse_whitespace_option(const char*option) 78{ 79if(!option) { 80 ws_error_action = warn_on_ws_error; 81return; 82} 83if(!strcmp(option,"warn")) { 84 ws_error_action = warn_on_ws_error; 85return; 86} 87if(!strcmp(option,"nowarn")) { 88 ws_error_action = nowarn_ws_error; 89return; 90} 91if(!strcmp(option,"error")) { 92 ws_error_action = die_on_ws_error; 93return; 94} 95if(!strcmp(option,"error-all")) { 96 ws_error_action = die_on_ws_error; 97 squelch_whitespace_errors =0; 98return; 99} 100if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 101 ws_error_action = correct_ws_error; 102return; 103} 104die("unrecognized whitespace option '%s'", option); 105} 106 107static voidparse_ignorewhitespace_option(const char*option) 108{ 109if(!option || !strcmp(option,"no") || 110!strcmp(option,"false") || !strcmp(option,"never") || 111!strcmp(option,"none")) { 112 ws_ignore_action = ignore_ws_none; 113return; 114} 115if(!strcmp(option,"change")) { 116 ws_ignore_action = ignore_ws_change; 117return; 118} 119die("unrecognized whitespace ignore option '%s'", option); 120} 121 122static voidset_default_whitespace_mode(const char*whitespace_option) 123{ 124if(!whitespace_option && !apply_default_whitespace) 125 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 126} 127 128/* 129 * For "diff-stat" like behaviour, we keep track of the biggest change 130 * we've seen, and the longest filename. That allows us to do simple 131 * scaling. 132 */ 133static int max_change, max_len; 134 135/* 136 * Various "current state", notably line numbers and what 137 * file (and how) we're patching right now.. The "is_xxxx" 138 * things are flags, where -1 means "don't know yet". 139 */ 140static int linenr =1; 141 142/* 143 * This represents one "hunk" from a patch, starting with 144 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 145 * patch text is pointed at by patch, and its byte length 146 * is stored in size. leading and trailing are the number 147 * of context lines. 148 */ 149struct fragment { 150unsigned long leading, trailing; 151unsigned long oldpos, oldlines; 152unsigned long newpos, newlines; 153const char*patch; 154int size; 155int rejected; 156struct fragment *next; 157}; 158 159/* 160 * When dealing with a binary patch, we reuse "leading" field 161 * to store the type of the binary hunk, either deflated "delta" 162 * or deflated "literal". 163 */ 164#define binary_patch_method leading 165#define BINARY_DELTA_DEFLATED 1 166#define BINARY_LITERAL_DEFLATED 2 167 168/* 169 * This represents a "patch" to a file, both metainfo changes 170 * such as creation/deletion, filemode and content changes represented 171 * as a series of fragments. 172 */ 173struct patch { 174char*new_name, *old_name, *def_name; 175unsigned int old_mode, new_mode; 176int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 177int rejected; 178unsigned ws_rule; 179unsigned long deflate_origlen; 180int lines_added, lines_deleted; 181int score; 182unsigned int is_toplevel_relative:1; 183unsigned int inaccurate_eof:1; 184unsigned int is_binary:1; 185unsigned int is_copy:1; 186unsigned int is_rename:1; 187unsigned int recount:1; 188struct fragment *fragments; 189char*result; 190size_t resultsize; 191char old_sha1_prefix[41]; 192char new_sha1_prefix[41]; 193struct patch *next; 194}; 195 196/* 197 * A line in a file, len-bytes long (includes the terminating LF, 198 * except for an incomplete line at the end if the file ends with 199 * one), and its contents hashes to 'hash'. 200 */ 201struct line { 202size_t len; 203unsigned hash :24; 204unsigned flag :8; 205#define LINE_COMMON 1 206}; 207 208/* 209 * This represents a "file", which is an array of "lines". 210 */ 211struct image { 212char*buf; 213size_t len; 214size_t nr; 215size_t alloc; 216struct line *line_allocated; 217struct line *line; 218}; 219 220/* 221 * Records filenames that have been touched, in order to handle 222 * the case where more than one patches touch the same file. 223 */ 224 225static struct string_list fn_table; 226 227static uint32_thash_line(const char*cp,size_t len) 228{ 229size_t i; 230uint32_t h; 231for(i =0, h =0; i < len; i++) { 232if(!isspace(cp[i])) { 233 h = h *3+ (cp[i] &0xff); 234} 235} 236return h; 237} 238 239/* 240 * Compare lines s1 of length n1 and s2 of length n2, ignoring 241 * whitespace difference. Returns 1 if they match, 0 otherwise 242 */ 243static intfuzzy_matchlines(const char*s1,size_t n1, 244const char*s2,size_t n2) 245{ 246const char*last1 = s1 + n1 -1; 247const char*last2 = s2 + n2 -1; 248int result =0; 249 250if(n1 <0|| n2 <0) 251return0; 252 253/* ignore line endings */ 254while((*last1 =='\r') || (*last1 =='\n')) 255 last1--; 256while((*last2 =='\r') || (*last2 =='\n')) 257 last2--; 258 259/* skip leading whitespace */ 260while(isspace(*s1) && (s1 <= last1)) 261 s1++; 262while(isspace(*s2) && (s2 <= last2)) 263 s2++; 264/* early return if both lines are empty */ 265if((s1 > last1) && (s2 > last2)) 266return1; 267while(!result) { 268 result = *s1++ - *s2++; 269/* 270 * Skip whitespace inside. We check for whitespace on 271 * both buffers because we don't want "a b" to match 272 * "ab" 273 */ 274if(isspace(*s1) &&isspace(*s2)) { 275while(isspace(*s1) && s1 <= last1) 276 s1++; 277while(isspace(*s2) && s2 <= last2) 278 s2++; 279} 280/* 281 * If we reached the end on one side only, 282 * lines don't match 283 */ 284if( 285((s2 > last2) && (s1 <= last1)) || 286((s1 > last1) && (s2 <= last2))) 287return0; 288if((s1 > last1) && (s2 > last2)) 289break; 290} 291 292return!result; 293} 294 295static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 296{ 297ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 298 img->line_allocated[img->nr].len = len; 299 img->line_allocated[img->nr].hash =hash_line(bol, len); 300 img->line_allocated[img->nr].flag = flag; 301 img->nr++; 302} 303 304static voidprepare_image(struct image *image,char*buf,size_t len, 305int prepare_linetable) 306{ 307const char*cp, *ep; 308 309memset(image,0,sizeof(*image)); 310 image->buf = buf; 311 image->len = len; 312 313if(!prepare_linetable) 314return; 315 316 ep = image->buf + image->len; 317 cp = image->buf; 318while(cp < ep) { 319const char*next; 320for(next = cp; next < ep && *next !='\n'; next++) 321; 322if(next < ep) 323 next++; 324add_line_info(image, cp, next - cp,0); 325 cp = next; 326} 327 image->line = image->line_allocated; 328} 329 330static voidclear_image(struct image *image) 331{ 332free(image->buf); 333 image->buf = NULL; 334 image->len =0; 335} 336 337static voidsay_patch_name(FILE*output,const char*pre, 338struct patch *patch,const char*post) 339{ 340fputs(pre, output); 341if(patch->old_name && patch->new_name && 342strcmp(patch->old_name, patch->new_name)) { 343quote_c_style(patch->old_name, NULL, output,0); 344fputs(" => ", output); 345quote_c_style(patch->new_name, NULL, output,0); 346}else{ 347const char*n = patch->new_name; 348if(!n) 349 n = patch->old_name; 350quote_c_style(n, NULL, output,0); 351} 352fputs(post, output); 353} 354 355#define CHUNKSIZE (8192) 356#define SLOP (16) 357 358static voidread_patch_file(struct strbuf *sb,int fd) 359{ 360if(strbuf_read(sb, fd,0) <0) 361die_errno("git apply: failed to read"); 362 363/* 364 * Make sure that we have some slop in the buffer 365 * so that we can do speculative "memcmp" etc, and 366 * see to it that it is NUL-filled. 367 */ 368strbuf_grow(sb, SLOP); 369memset(sb->buf + sb->len,0, SLOP); 370} 371 372static unsigned longlinelen(const char*buffer,unsigned long size) 373{ 374unsigned long len =0; 375while(size--) { 376 len++; 377if(*buffer++ =='\n') 378break; 379} 380return len; 381} 382 383static intis_dev_null(const char*str) 384{ 385return!memcmp("/dev/null", str,9) &&isspace(str[9]); 386} 387 388#define TERM_SPACE 1 389#define TERM_TAB 2 390 391static intname_terminate(const char*name,int namelen,int c,int terminate) 392{ 393if(c ==' '&& !(terminate & TERM_SPACE)) 394return0; 395if(c =='\t'&& !(terminate & TERM_TAB)) 396return0; 397 398return1; 399} 400 401/* remove double slashes to make --index work with such filenames */ 402static char*squash_slash(char*name) 403{ 404int i =0, j =0; 405 406while(name[i]) { 407if((name[j++] = name[i++]) =='/') 408while(name[i] =='/') 409 i++; 410} 411 name[j] ='\0'; 412return name; 413} 414 415static char*find_name(const char*line,char*def,int p_value,int terminate) 416{ 417int len; 418const char*start = line; 419 420if(*line =='"') { 421struct strbuf name = STRBUF_INIT; 422 423/* 424 * Proposed "new-style" GNU patch/diff format; see 425 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2 426 */ 427if(!unquote_c_style(&name, line, NULL)) { 428char*cp; 429 430for(cp = name.buf; p_value; p_value--) { 431 cp =strchr(cp,'/'); 432if(!cp) 433break; 434 cp++; 435} 436if(cp) { 437/* name can later be freed, so we need 438 * to memmove, not just return cp 439 */ 440strbuf_remove(&name,0, cp - name.buf); 441free(def); 442if(root) 443strbuf_insert(&name,0, root, root_len); 444returnsquash_slash(strbuf_detach(&name, NULL)); 445} 446} 447strbuf_release(&name); 448} 449 450for(;;) { 451char c = *line; 452 453if(isspace(c)) { 454if(c =='\n') 455break; 456if(name_terminate(start, line-start, c, terminate)) 457break; 458} 459 line++; 460if(c =='/'&& !--p_value) 461 start = line; 462} 463if(!start) 464returnsquash_slash(def); 465 len = line - start; 466if(!len) 467returnsquash_slash(def); 468 469/* 470 * Generally we prefer the shorter name, especially 471 * if the other one is just a variation of that with 472 * something else tacked on to the end (ie "file.orig" 473 * or "file~"). 474 */ 475if(def) { 476int deflen =strlen(def); 477if(deflen < len && !strncmp(start, def, deflen)) 478returnsquash_slash(def); 479free(def); 480} 481 482if(root) { 483char*ret =xmalloc(root_len + len +1); 484strcpy(ret, root); 485memcpy(ret + root_len, start, len); 486 ret[root_len + len] ='\0'; 487returnsquash_slash(ret); 488} 489 490returnsquash_slash(xmemdupz(start, len)); 491} 492 493static intcount_slashes(const char*cp) 494{ 495int cnt =0; 496char ch; 497 498while((ch = *cp++)) 499if(ch =='/') 500 cnt++; 501return cnt; 502} 503 504/* 505 * Given the string after "--- " or "+++ ", guess the appropriate 506 * p_value for the given patch. 507 */ 508static intguess_p_value(const char*nameline) 509{ 510char*name, *cp; 511int val = -1; 512 513if(is_dev_null(nameline)) 514return-1; 515 name =find_name(nameline, NULL,0, TERM_SPACE | TERM_TAB); 516if(!name) 517return-1; 518 cp =strchr(name,'/'); 519if(!cp) 520 val =0; 521else if(prefix) { 522/* 523 * Does it begin with "a/$our-prefix" and such? Then this is 524 * very likely to apply to our directory. 525 */ 526if(!strncmp(name, prefix, prefix_length)) 527 val =count_slashes(prefix); 528else{ 529 cp++; 530if(!strncmp(cp, prefix, prefix_length)) 531 val =count_slashes(prefix) +1; 532} 533} 534free(name); 535return val; 536} 537 538/* 539 * Get the name etc info from the ---/+++ lines of a traditional patch header 540 * 541 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 542 * files, we can happily check the index for a match, but for creating a 543 * new file we should try to match whatever "patch" does. I have no idea. 544 */ 545static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 546{ 547char*name; 548 549 first +=4;/* skip "--- " */ 550 second +=4;/* skip "+++ " */ 551if(!p_value_known) { 552int p, q; 553 p =guess_p_value(first); 554 q =guess_p_value(second); 555if(p <0) p = q; 556if(0<= p && p == q) { 557 p_value = p; 558 p_value_known =1; 559} 560} 561if(is_dev_null(first)) { 562 patch->is_new =1; 563 patch->is_delete =0; 564 name =find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB); 565 patch->new_name = name; 566}else if(is_dev_null(second)) { 567 patch->is_new =0; 568 patch->is_delete =1; 569 name =find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB); 570 patch->old_name = name; 571}else{ 572 name =find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB); 573 name =find_name(second, name, p_value, TERM_SPACE | TERM_TAB); 574 patch->old_name = patch->new_name = name; 575} 576if(!name) 577die("unable to find filename in patch at line%d", linenr); 578} 579 580static intgitdiff_hdrend(const char*line,struct patch *patch) 581{ 582return-1; 583} 584 585/* 586 * We're anal about diff header consistency, to make 587 * sure that we don't end up having strange ambiguous 588 * patches floating around. 589 * 590 * As a result, gitdiff_{old|new}name() will check 591 * their names against any previous information, just 592 * to make sure.. 593 */ 594static char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,const char*oldnew) 595{ 596if(!orig_name && !isnull) 597returnfind_name(line, NULL, p_value, TERM_TAB); 598 599if(orig_name) { 600int len; 601const char*name; 602char*another; 603 name = orig_name; 604 len =strlen(name); 605if(isnull) 606die("git apply: bad git-diff - expected /dev/null, got%son line%d", name, linenr); 607 another =find_name(line, NULL, p_value, TERM_TAB); 608if(!another ||memcmp(another, name, len)) 609die("git apply: bad git-diff - inconsistent%sfilename on line%d", oldnew, linenr); 610free(another); 611return orig_name; 612} 613else{ 614/* expect "/dev/null" */ 615if(memcmp("/dev/null", line,9) || line[9] !='\n') 616die("git apply: bad git-diff - expected /dev/null on line%d", linenr); 617return NULL; 618} 619} 620 621static intgitdiff_oldname(const char*line,struct patch *patch) 622{ 623 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name,"old"); 624return0; 625} 626 627static intgitdiff_newname(const char*line,struct patch *patch) 628{ 629 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name,"new"); 630return0; 631} 632 633static intgitdiff_oldmode(const char*line,struct patch *patch) 634{ 635 patch->old_mode =strtoul(line, NULL,8); 636return0; 637} 638 639static intgitdiff_newmode(const char*line,struct patch *patch) 640{ 641 patch->new_mode =strtoul(line, NULL,8); 642return0; 643} 644 645static intgitdiff_delete(const char*line,struct patch *patch) 646{ 647 patch->is_delete =1; 648 patch->old_name = patch->def_name; 649returngitdiff_oldmode(line, patch); 650} 651 652static intgitdiff_newfile(const char*line,struct patch *patch) 653{ 654 patch->is_new =1; 655 patch->new_name = patch->def_name; 656returngitdiff_newmode(line, patch); 657} 658 659static intgitdiff_copysrc(const char*line,struct patch *patch) 660{ 661 patch->is_copy =1; 662 patch->old_name =find_name(line, NULL,0,0); 663return0; 664} 665 666static intgitdiff_copydst(const char*line,struct patch *patch) 667{ 668 patch->is_copy =1; 669 patch->new_name =find_name(line, NULL,0,0); 670return0; 671} 672 673static intgitdiff_renamesrc(const char*line,struct patch *patch) 674{ 675 patch->is_rename =1; 676 patch->old_name =find_name(line, NULL,0,0); 677return0; 678} 679 680static intgitdiff_renamedst(const char*line,struct patch *patch) 681{ 682 patch->is_rename =1; 683 patch->new_name =find_name(line, NULL,0,0); 684return0; 685} 686 687static intgitdiff_similarity(const char*line,struct patch *patch) 688{ 689if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 690 patch->score =0; 691return0; 692} 693 694static intgitdiff_dissimilarity(const char*line,struct patch *patch) 695{ 696if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 697 patch->score =0; 698return0; 699} 700 701static intgitdiff_index(const char*line,struct patch *patch) 702{ 703/* 704 * index line is N hexadecimal, "..", N hexadecimal, 705 * and optional space with octal mode. 706 */ 707const char*ptr, *eol; 708int len; 709 710 ptr =strchr(line,'.'); 711if(!ptr || ptr[1] !='.'||40< ptr - line) 712return0; 713 len = ptr - line; 714memcpy(patch->old_sha1_prefix, line, len); 715 patch->old_sha1_prefix[len] =0; 716 717 line = ptr +2; 718 ptr =strchr(line,' '); 719 eol =strchr(line,'\n'); 720 721if(!ptr || eol < ptr) 722 ptr = eol; 723 len = ptr - line; 724 725if(40< len) 726return0; 727memcpy(patch->new_sha1_prefix, line, len); 728 patch->new_sha1_prefix[len] =0; 729if(*ptr ==' ') 730 patch->old_mode =strtoul(ptr+1, NULL,8); 731return0; 732} 733 734/* 735 * This is normal for a diff that doesn't change anything: we'll fall through 736 * into the next diff. Tell the parser to break out. 737 */ 738static intgitdiff_unrecognized(const char*line,struct patch *patch) 739{ 740return-1; 741} 742 743static const char*stop_at_slash(const char*line,int llen) 744{ 745int i; 746 747for(i =0; i < llen; i++) { 748int ch = line[i]; 749if(ch =='/') 750return line + i; 751} 752return NULL; 753} 754 755/* 756 * This is to extract the same name that appears on "diff --git" 757 * line. We do not find and return anything if it is a rename 758 * patch, and it is OK because we will find the name elsewhere. 759 * We need to reliably find name only when it is mode-change only, 760 * creation or deletion of an empty file. In any of these cases, 761 * both sides are the same name under a/ and b/ respectively. 762 */ 763static char*git_header_name(char*line,int llen) 764{ 765const char*name; 766const char*second = NULL; 767size_t len; 768 769 line +=strlen("diff --git "); 770 llen -=strlen("diff --git "); 771 772if(*line =='"') { 773const char*cp; 774struct strbuf first = STRBUF_INIT; 775struct strbuf sp = STRBUF_INIT; 776 777if(unquote_c_style(&first, line, &second)) 778goto free_and_fail1; 779 780/* advance to the first slash */ 781 cp =stop_at_slash(first.buf, first.len); 782/* we do not accept absolute paths */ 783if(!cp || cp == first.buf) 784goto free_and_fail1; 785strbuf_remove(&first,0, cp +1- first.buf); 786 787/* 788 * second points at one past closing dq of name. 789 * find the second name. 790 */ 791while((second < line + llen) &&isspace(*second)) 792 second++; 793 794if(line + llen <= second) 795goto free_and_fail1; 796if(*second =='"') { 797if(unquote_c_style(&sp, second, NULL)) 798goto free_and_fail1; 799 cp =stop_at_slash(sp.buf, sp.len); 800if(!cp || cp == sp.buf) 801goto free_and_fail1; 802/* They must match, otherwise ignore */ 803if(strcmp(cp +1, first.buf)) 804goto free_and_fail1; 805strbuf_release(&sp); 806returnstrbuf_detach(&first, NULL); 807} 808 809/* unquoted second */ 810 cp =stop_at_slash(second, line + llen - second); 811if(!cp || cp == second) 812goto free_and_fail1; 813 cp++; 814if(line + llen - cp != first.len +1|| 815memcmp(first.buf, cp, first.len)) 816goto free_and_fail1; 817returnstrbuf_detach(&first, NULL); 818 819 free_and_fail1: 820strbuf_release(&first); 821strbuf_release(&sp); 822return NULL; 823} 824 825/* unquoted first name */ 826 name =stop_at_slash(line, llen); 827if(!name || name == line) 828return NULL; 829 name++; 830 831/* 832 * since the first name is unquoted, a dq if exists must be 833 * the beginning of the second name. 834 */ 835for(second = name; second < line + llen; second++) { 836if(*second =='"') { 837struct strbuf sp = STRBUF_INIT; 838const char*np; 839 840if(unquote_c_style(&sp, second, NULL)) 841goto free_and_fail2; 842 843 np =stop_at_slash(sp.buf, sp.len); 844if(!np || np == sp.buf) 845goto free_and_fail2; 846 np++; 847 848 len = sp.buf + sp.len - np; 849if(len < second - name && 850!strncmp(np, name, len) && 851isspace(name[len])) { 852/* Good */ 853strbuf_remove(&sp,0, np - sp.buf); 854returnstrbuf_detach(&sp, NULL); 855} 856 857 free_and_fail2: 858strbuf_release(&sp); 859return NULL; 860} 861} 862 863/* 864 * Accept a name only if it shows up twice, exactly the same 865 * form. 866 */ 867for(len =0; ; len++) { 868switch(name[len]) { 869default: 870continue; 871case'\n': 872return NULL; 873case'\t':case' ': 874 second = name+len; 875for(;;) { 876char c = *second++; 877if(c =='\n') 878return NULL; 879if(c =='/') 880break; 881} 882if(second[len] =='\n'&& !memcmp(name, second, len)) { 883returnxmemdupz(name, len); 884} 885} 886} 887} 888 889/* Verify that we recognize the lines following a git header */ 890static intparse_git_header(char*line,int len,unsigned int size,struct patch *patch) 891{ 892unsigned long offset; 893 894/* A git diff has explicit new/delete information, so we don't guess */ 895 patch->is_new =0; 896 patch->is_delete =0; 897 898/* 899 * Some things may not have the old name in the 900 * rest of the headers anywhere (pure mode changes, 901 * or removing or adding empty files), so we get 902 * the default name from the header. 903 */ 904 patch->def_name =git_header_name(line, len); 905if(patch->def_name && root) { 906char*s =xmalloc(root_len +strlen(patch->def_name) +1); 907strcpy(s, root); 908strcpy(s + root_len, patch->def_name); 909free(patch->def_name); 910 patch->def_name = s; 911} 912 913 line += len; 914 size -= len; 915 linenr++; 916for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) { 917static const struct opentry { 918const char*str; 919int(*fn)(const char*,struct patch *); 920} optable[] = { 921{"@@ -", gitdiff_hdrend }, 922{"--- ", gitdiff_oldname }, 923{"+++ ", gitdiff_newname }, 924{"old mode ", gitdiff_oldmode }, 925{"new mode ", gitdiff_newmode }, 926{"deleted file mode ", gitdiff_delete }, 927{"new file mode ", gitdiff_newfile }, 928{"copy from ", gitdiff_copysrc }, 929{"copy to ", gitdiff_copydst }, 930{"rename old ", gitdiff_renamesrc }, 931{"rename new ", gitdiff_renamedst }, 932{"rename from ", gitdiff_renamesrc }, 933{"rename to ", gitdiff_renamedst }, 934{"similarity index ", gitdiff_similarity }, 935{"dissimilarity index ", gitdiff_dissimilarity }, 936{"index ", gitdiff_index }, 937{"", gitdiff_unrecognized }, 938}; 939int i; 940 941 len =linelen(line, size); 942if(!len || line[len-1] !='\n') 943break; 944for(i =0; i <ARRAY_SIZE(optable); i++) { 945const struct opentry *p = optable + i; 946int oplen =strlen(p->str); 947if(len < oplen ||memcmp(p->str, line, oplen)) 948continue; 949if(p->fn(line + oplen, patch) <0) 950return offset; 951break; 952} 953} 954 955return offset; 956} 957 958static intparse_num(const char*line,unsigned long*p) 959{ 960char*ptr; 961 962if(!isdigit(*line)) 963return0; 964*p =strtoul(line, &ptr,10); 965return ptr - line; 966} 967 968static intparse_range(const char*line,int len,int offset,const char*expect, 969unsigned long*p1,unsigned long*p2) 970{ 971int digits, ex; 972 973if(offset <0|| offset >= len) 974return-1; 975 line += offset; 976 len -= offset; 977 978 digits =parse_num(line, p1); 979if(!digits) 980return-1; 981 982 offset += digits; 983 line += digits; 984 len -= digits; 985 986*p2 =1; 987if(*line ==',') { 988 digits =parse_num(line+1, p2); 989if(!digits) 990return-1; 991 992 offset += digits+1; 993 line += digits+1; 994 len -= digits+1; 995} 996 997 ex =strlen(expect); 998if(ex > len) 999return-1;1000if(memcmp(line, expect, ex))1001return-1;10021003return offset + ex;1004}10051006static voidrecount_diff(char*line,int size,struct fragment *fragment)1007{1008int oldlines =0, newlines =0, ret =0;10091010if(size <1) {1011warning("recount: ignore empty hunk");1012return;1013}10141015for(;;) {1016int len =linelen(line, size);1017 size -= len;1018 line += len;10191020if(size <1)1021break;10221023switch(*line) {1024case' ':case'\n':1025 newlines++;1026/* fall through */1027case'-':1028 oldlines++;1029continue;1030case'+':1031 newlines++;1032continue;1033case'\\':1034continue;1035case'@':1036 ret = size <3||prefixcmp(line,"@@ ");1037break;1038case'd':1039 ret = size <5||prefixcmp(line,"diff ");1040break;1041default:1042 ret = -1;1043break;1044}1045if(ret) {1046warning("recount: unexpected line: %.*s",1047(int)linelen(line, size), line);1048return;1049}1050break;1051}1052 fragment->oldlines = oldlines;1053 fragment->newlines = newlines;1054}10551056/*1057 * Parse a unified diff fragment header of the1058 * form "@@ -a,b +c,d @@"1059 */1060static intparse_fragment_header(char*line,int len,struct fragment *fragment)1061{1062int offset;10631064if(!len || line[len-1] !='\n')1065return-1;10661067/* Figure out the number of lines in a fragment */1068 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1069 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);10701071return offset;1072}10731074static intfind_header(char*line,unsigned long size,int*hdrsize,struct patch *patch)1075{1076unsigned long offset, len;10771078 patch->is_toplevel_relative =0;1079 patch->is_rename = patch->is_copy =0;1080 patch->is_new = patch->is_delete = -1;1081 patch->old_mode = patch->new_mode =0;1082 patch->old_name = patch->new_name = NULL;1083for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1084unsigned long nextlen;10851086 len =linelen(line, size);1087if(!len)1088break;10891090/* Testing this early allows us to take a few shortcuts.. */1091if(len <6)1092continue;10931094/*1095 * Make sure we don't find any unconnected patch fragments.1096 * That's a sign that we didn't find a header, and that a1097 * patch has become corrupted/broken up.1098 */1099if(!memcmp("@@ -", line,4)) {1100struct fragment dummy;1101if(parse_fragment_header(line, len, &dummy) <0)1102continue;1103die("patch fragment without header at line%d: %.*s",1104 linenr, (int)len-1, line);1105}11061107if(size < len +6)1108break;11091110/*1111 * Git patch? It might not have a real patch, just a rename1112 * or mode change, so we handle that specially1113 */1114if(!memcmp("diff --git ", line,11)) {1115int git_hdr_len =parse_git_header(line, len, size, patch);1116if(git_hdr_len <= len)1117continue;1118if(!patch->old_name && !patch->new_name) {1119if(!patch->def_name)1120die("git diff header lacks filename information (line%d)", linenr);1121 patch->old_name = patch->new_name = patch->def_name;1122}1123 patch->is_toplevel_relative =1;1124*hdrsize = git_hdr_len;1125return offset;1126}11271128/* --- followed by +++ ? */1129if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1130continue;11311132/*1133 * We only accept unified patches, so we want it to1134 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1135 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1136 */1137 nextlen =linelen(line + len, size - len);1138if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1139continue;11401141/* Ok, we'll consider it a patch */1142parse_traditional_patch(line, line+len, patch);1143*hdrsize = len + nextlen;1144 linenr +=2;1145return offset;1146}1147return-1;1148}11491150static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1151{1152char*err;1153unsigned result =ws_check(line +1, len -1, ws_rule);1154if(!result)1155return;11561157 whitespace_error++;1158if(squelch_whitespace_errors &&1159 squelch_whitespace_errors < whitespace_error)1160;1161else{1162 err =whitespace_error_string(result);1163fprintf(stderr,"%s:%d:%s.\n%.*s\n",1164 patch_input_file, linenr, err, len -2, line +1);1165free(err);1166}1167}11681169/*1170 * Parse a unified diff. Note that this really needs to parse each1171 * fragment separately, since the only way to know the difference1172 * between a "---" that is part of a patch, and a "---" that starts1173 * the next patch is to look at the line counts..1174 */1175static intparse_fragment(char*line,unsigned long size,1176struct patch *patch,struct fragment *fragment)1177{1178int added, deleted;1179int len =linelen(line, size), offset;1180unsigned long oldlines, newlines;1181unsigned long leading, trailing;11821183 offset =parse_fragment_header(line, len, fragment);1184if(offset <0)1185return-1;1186if(offset >0&& patch->recount)1187recount_diff(line + offset, size - offset, fragment);1188 oldlines = fragment->oldlines;1189 newlines = fragment->newlines;1190 leading =0;1191 trailing =0;11921193/* Parse the thing.. */1194 line += len;1195 size -= len;1196 linenr++;1197 added = deleted =0;1198for(offset = len;11990< size;1200 offset += len, size -= len, line += len, linenr++) {1201if(!oldlines && !newlines)1202break;1203 len =linelen(line, size);1204if(!len || line[len-1] !='\n')1205return-1;1206switch(*line) {1207default:1208return-1;1209case'\n':/* newer GNU diff, an empty context line */1210case' ':1211 oldlines--;1212 newlines--;1213if(!deleted && !added)1214 leading++;1215 trailing++;1216break;1217case'-':1218if(apply_in_reverse &&1219 ws_error_action != nowarn_ws_error)1220check_whitespace(line, len, patch->ws_rule);1221 deleted++;1222 oldlines--;1223 trailing =0;1224break;1225case'+':1226if(!apply_in_reverse &&1227 ws_error_action != nowarn_ws_error)1228check_whitespace(line, len, patch->ws_rule);1229 added++;1230 newlines--;1231 trailing =0;1232break;12331234/*1235 * We allow "\ No newline at end of file". Depending1236 * on locale settings when the patch was produced we1237 * don't know what this line looks like. The only1238 * thing we do know is that it begins with "\ ".1239 * Checking for 12 is just for sanity check -- any1240 * l10n of "\ No newline..." is at least that long.1241 */1242case'\\':1243if(len <12||memcmp(line,"\\",2))1244return-1;1245break;1246}1247}1248if(oldlines || newlines)1249return-1;1250 fragment->leading = leading;1251 fragment->trailing = trailing;12521253/*1254 * If a fragment ends with an incomplete line, we failed to include1255 * it in the above loop because we hit oldlines == newlines == 01256 * before seeing it.1257 */1258if(12< size && !memcmp(line,"\\",2))1259 offset +=linelen(line, size);12601261 patch->lines_added += added;1262 patch->lines_deleted += deleted;12631264if(0< patch->is_new && oldlines)1265returnerror("new file depends on old contents");1266if(0< patch->is_delete && newlines)1267returnerror("deleted file still has contents");1268return offset;1269}12701271static intparse_single_patch(char*line,unsigned long size,struct patch *patch)1272{1273unsigned long offset =0;1274unsigned long oldlines =0, newlines =0, context =0;1275struct fragment **fragp = &patch->fragments;12761277while(size >4&& !memcmp(line,"@@ -",4)) {1278struct fragment *fragment;1279int len;12801281 fragment =xcalloc(1,sizeof(*fragment));1282 len =parse_fragment(line, size, patch, fragment);1283if(len <=0)1284die("corrupt patch at line%d", linenr);1285 fragment->patch = line;1286 fragment->size = len;1287 oldlines += fragment->oldlines;1288 newlines += fragment->newlines;1289 context += fragment->leading + fragment->trailing;12901291*fragp = fragment;1292 fragp = &fragment->next;12931294 offset += len;1295 line += len;1296 size -= len;1297}12981299/*1300 * If something was removed (i.e. we have old-lines) it cannot1301 * be creation, and if something was added it cannot be1302 * deletion. However, the reverse is not true; --unified=01303 * patches that only add are not necessarily creation even1304 * though they do not have any old lines, and ones that only1305 * delete are not necessarily deletion.1306 *1307 * Unfortunately, a real creation/deletion patch do _not_ have1308 * any context line by definition, so we cannot safely tell it1309 * apart with --unified=0 insanity. At least if the patch has1310 * more than one hunk it is not creation or deletion.1311 */1312if(patch->is_new <0&&1313(oldlines || (patch->fragments && patch->fragments->next)))1314 patch->is_new =0;1315if(patch->is_delete <0&&1316(newlines || (patch->fragments && patch->fragments->next)))1317 patch->is_delete =0;13181319if(0< patch->is_new && oldlines)1320die("new file%sdepends on old contents", patch->new_name);1321if(0< patch->is_delete && newlines)1322die("deleted file%sstill has contents", patch->old_name);1323if(!patch->is_delete && !newlines && context)1324fprintf(stderr,"** warning: file%sbecomes empty but "1325"is not deleted\n", patch->new_name);13261327return offset;1328}13291330staticinlineintmetadata_changes(struct patch *patch)1331{1332return patch->is_rename >0||1333 patch->is_copy >0||1334 patch->is_new >0||1335 patch->is_delete ||1336(patch->old_mode && patch->new_mode &&1337 patch->old_mode != patch->new_mode);1338}13391340static char*inflate_it(const void*data,unsigned long size,1341unsigned long inflated_size)1342{1343 z_stream stream;1344void*out;1345int st;13461347memset(&stream,0,sizeof(stream));13481349 stream.next_in = (unsigned char*)data;1350 stream.avail_in = size;1351 stream.next_out = out =xmalloc(inflated_size);1352 stream.avail_out = inflated_size;1353git_inflate_init(&stream);1354 st =git_inflate(&stream, Z_FINISH);1355git_inflate_end(&stream);1356if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1357free(out);1358return NULL;1359}1360return out;1361}13621363static struct fragment *parse_binary_hunk(char**buf_p,1364unsigned long*sz_p,1365int*status_p,1366int*used_p)1367{1368/*1369 * Expect a line that begins with binary patch method ("literal"1370 * or "delta"), followed by the length of data before deflating.1371 * a sequence of 'length-byte' followed by base-85 encoded data1372 * should follow, terminated by a newline.1373 *1374 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1375 * and we would limit the patch line to 66 characters,1376 * so one line can fit up to 13 groups that would decode1377 * to 52 bytes max. The length byte 'A'-'Z' corresponds1378 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1379 */1380int llen, used;1381unsigned long size = *sz_p;1382char*buffer = *buf_p;1383int patch_method;1384unsigned long origlen;1385char*data = NULL;1386int hunk_size =0;1387struct fragment *frag;13881389 llen =linelen(buffer, size);1390 used = llen;13911392*status_p =0;13931394if(!prefixcmp(buffer,"delta ")) {1395 patch_method = BINARY_DELTA_DEFLATED;1396 origlen =strtoul(buffer +6, NULL,10);1397}1398else if(!prefixcmp(buffer,"literal ")) {1399 patch_method = BINARY_LITERAL_DEFLATED;1400 origlen =strtoul(buffer +8, NULL,10);1401}1402else1403return NULL;14041405 linenr++;1406 buffer += llen;1407while(1) {1408int byte_length, max_byte_length, newsize;1409 llen =linelen(buffer, size);1410 used += llen;1411 linenr++;1412if(llen ==1) {1413/* consume the blank line */1414 buffer++;1415 size--;1416break;1417}1418/*1419 * Minimum line is "A00000\n" which is 7-byte long,1420 * and the line length must be multiple of 5 plus 2.1421 */1422if((llen <7) || (llen-2) %5)1423goto corrupt;1424 max_byte_length = (llen -2) /5*4;1425 byte_length = *buffer;1426if('A'<= byte_length && byte_length <='Z')1427 byte_length = byte_length -'A'+1;1428else if('a'<= byte_length && byte_length <='z')1429 byte_length = byte_length -'a'+27;1430else1431goto corrupt;1432/* if the input length was not multiple of 4, we would1433 * have filler at the end but the filler should never1434 * exceed 3 bytes1435 */1436if(max_byte_length < byte_length ||1437 byte_length <= max_byte_length -4)1438goto corrupt;1439 newsize = hunk_size + byte_length;1440 data =xrealloc(data, newsize);1441if(decode_85(data + hunk_size, buffer +1, byte_length))1442goto corrupt;1443 hunk_size = newsize;1444 buffer += llen;1445 size -= llen;1446}14471448 frag =xcalloc(1,sizeof(*frag));1449 frag->patch =inflate_it(data, hunk_size, origlen);1450if(!frag->patch)1451goto corrupt;1452free(data);1453 frag->size = origlen;1454*buf_p = buffer;1455*sz_p = size;1456*used_p = used;1457 frag->binary_patch_method = patch_method;1458return frag;14591460 corrupt:1461free(data);1462*status_p = -1;1463error("corrupt binary patch at line%d: %.*s",1464 linenr-1, llen-1, buffer);1465return NULL;1466}14671468static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1469{1470/*1471 * We have read "GIT binary patch\n"; what follows is a line1472 * that says the patch method (currently, either "literal" or1473 * "delta") and the length of data before deflating; a1474 * sequence of 'length-byte' followed by base-85 encoded data1475 * follows.1476 *1477 * When a binary patch is reversible, there is another binary1478 * hunk in the same format, starting with patch method (either1479 * "literal" or "delta") with the length of data, and a sequence1480 * of length-byte + base-85 encoded data, terminated with another1481 * empty line. This data, when applied to the postimage, produces1482 * the preimage.1483 */1484struct fragment *forward;1485struct fragment *reverse;1486int status;1487int used, used_1;14881489 forward =parse_binary_hunk(&buffer, &size, &status, &used);1490if(!forward && !status)1491/* there has to be one hunk (forward hunk) */1492returnerror("unrecognized binary patch at line%d", linenr-1);1493if(status)1494/* otherwise we already gave an error message */1495return status;14961497 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1498if(reverse)1499 used += used_1;1500else if(status) {1501/*1502 * Not having reverse hunk is not an error, but having1503 * a corrupt reverse hunk is.1504 */1505free((void*) forward->patch);1506free(forward);1507return status;1508}1509 forward->next = reverse;1510 patch->fragments = forward;1511 patch->is_binary =1;1512return used;1513}15141515static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1516{1517int hdrsize, patchsize;1518int offset =find_header(buffer, size, &hdrsize, patch);15191520if(offset <0)1521return offset;15221523 patch->ws_rule =whitespace_rule(patch->new_name1524? patch->new_name1525: patch->old_name);15261527 patchsize =parse_single_patch(buffer + offset + hdrsize,1528 size - offset - hdrsize, patch);15291530if(!patchsize) {1531static const char*binhdr[] = {1532"Binary files ",1533"Files ",1534 NULL,1535};1536static const char git_binary[] ="GIT binary patch\n";1537int i;1538int hd = hdrsize + offset;1539unsigned long llen =linelen(buffer + hd, size - hd);15401541if(llen ==sizeof(git_binary) -1&&1542!memcmp(git_binary, buffer + hd, llen)) {1543int used;1544 linenr++;1545 used =parse_binary(buffer + hd + llen,1546 size - hd - llen, patch);1547if(used)1548 patchsize = used + llen;1549else1550 patchsize =0;1551}1552else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1553for(i =0; binhdr[i]; i++) {1554int len =strlen(binhdr[i]);1555if(len < size - hd &&1556!memcmp(binhdr[i], buffer + hd, len)) {1557 linenr++;1558 patch->is_binary =1;1559 patchsize = llen;1560break;1561}1562}1563}15641565/* Empty patch cannot be applied if it is a text patch1566 * without metadata change. A binary patch appears1567 * empty to us here.1568 */1569if((apply || check) &&1570(!patch->is_binary && !metadata_changes(patch)))1571die("patch with only garbage at line%d", linenr);1572}15731574return offset + hdrsize + patchsize;1575}15761577#define swap(a,b) myswap((a),(b),sizeof(a))15781579#define myswap(a, b, size) do { \1580 unsigned char mytmp[size]; \1581 memcpy(mytmp, &a, size); \1582 memcpy(&a, &b, size); \1583 memcpy(&b, mytmp, size); \1584} while (0)15851586static voidreverse_patches(struct patch *p)1587{1588for(; p; p = p->next) {1589struct fragment *frag = p->fragments;15901591swap(p->new_name, p->old_name);1592swap(p->new_mode, p->old_mode);1593swap(p->is_new, p->is_delete);1594swap(p->lines_added, p->lines_deleted);1595swap(p->old_sha1_prefix, p->new_sha1_prefix);15961597for(; frag; frag = frag->next) {1598swap(frag->newpos, frag->oldpos);1599swap(frag->newlines, frag->oldlines);1600}1601}1602}16031604static const char pluses[] =1605"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";1606static const char minuses[]=1607"----------------------------------------------------------------------";16081609static voidshow_stats(struct patch *patch)1610{1611struct strbuf qname = STRBUF_INIT;1612char*cp = patch->new_name ? patch->new_name : patch->old_name;1613int max, add, del;16141615quote_c_style(cp, &qname, NULL,0);16161617/*1618 * "scale" the filename1619 */1620 max = max_len;1621if(max >50)1622 max =50;16231624if(qname.len > max) {1625 cp =strchr(qname.buf + qname.len +3- max,'/');1626if(!cp)1627 cp = qname.buf + qname.len +3- max;1628strbuf_splice(&qname,0, cp - qname.buf,"...",3);1629}16301631if(patch->is_binary) {1632printf(" %-*s | Bin\n", max, qname.buf);1633strbuf_release(&qname);1634return;1635}16361637printf(" %-*s |", max, qname.buf);1638strbuf_release(&qname);16391640/*1641 * scale the add/delete1642 */1643 max = max + max_change >70?70- max : max_change;1644 add = patch->lines_added;1645 del = patch->lines_deleted;16461647if(max_change >0) {1648int total = ((add + del) * max + max_change /2) / max_change;1649 add = (add * max + max_change /2) / max_change;1650 del = total - add;1651}1652printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,1653 add, pluses, del, minuses);1654}16551656static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)1657{1658switch(st->st_mode & S_IFMT) {1659case S_IFLNK:1660if(strbuf_readlink(buf, path, st->st_size) <0)1661returnerror("unable to read symlink%s", path);1662return0;1663case S_IFREG:1664if(strbuf_read_file(buf, path, st->st_size) != st->st_size)1665returnerror("unable to open or read%s", path);1666convert_to_git(path, buf->buf, buf->len, buf,0);1667return0;1668default:1669return-1;1670}1671}16721673/*1674 * Update the preimage, and the common lines in postimage,1675 * from buffer buf of length len. If postlen is 0 the postimage1676 * is updated in place, otherwise it's updated on a new buffer1677 * of length postlen1678 */16791680static voidupdate_pre_post_images(struct image *preimage,1681struct image *postimage,1682char*buf,1683size_t len,size_t postlen)1684{1685int i, ctx;1686char*new, *old, *fixed;1687struct image fixed_preimage;16881689/*1690 * Update the preimage with whitespace fixes. Note that we1691 * are not losing preimage->buf -- apply_one_fragment() will1692 * free "oldlines".1693 */1694prepare_image(&fixed_preimage, buf, len,1);1695assert(fixed_preimage.nr == preimage->nr);1696for(i =0; i < preimage->nr; i++)1697 fixed_preimage.line[i].flag = preimage->line[i].flag;1698free(preimage->line_allocated);1699*preimage = fixed_preimage;17001701/*1702 * Adjust the common context lines in postimage. This can be1703 * done in-place when we are just doing whitespace fixing,1704 * which does not make the string grow, but needs a new buffer1705 * when ignoring whitespace causes the update, since in this case1706 * we could have e.g. tabs converted to multiple spaces.1707 * We trust the caller to tell us if the update can be done1708 * in place (postlen==0) or not.1709 */1710 old = postimage->buf;1711if(postlen)1712new= postimage->buf =xmalloc(postlen);1713else1714new= old;1715 fixed = preimage->buf;1716for(i = ctx =0; i < postimage->nr; i++) {1717size_t len = postimage->line[i].len;1718if(!(postimage->line[i].flag & LINE_COMMON)) {1719/* an added line -- no counterparts in preimage */1720memmove(new, old, len);1721 old += len;1722new+= len;1723continue;1724}17251726/* a common context -- skip it in the original postimage */1727 old += len;17281729/* and find the corresponding one in the fixed preimage */1730while(ctx < preimage->nr &&1731!(preimage->line[ctx].flag & LINE_COMMON)) {1732 fixed += preimage->line[ctx].len;1733 ctx++;1734}1735if(preimage->nr <= ctx)1736die("oops");17371738/* and copy it in, while fixing the line length */1739 len = preimage->line[ctx].len;1740memcpy(new, fixed, len);1741new+= len;1742 fixed += len;1743 postimage->line[i].len = len;1744 ctx++;1745}17461747/* Fix the length of the whole thing */1748 postimage->len =new- postimage->buf;1749}17501751static intmatch_fragment(struct image *img,1752struct image *preimage,1753struct image *postimage,1754unsigned longtry,1755int try_lno,1756unsigned ws_rule,1757int match_beginning,int match_end)1758{1759int i;1760char*fixed_buf, *buf, *orig, *target;17611762if(preimage->nr + try_lno > img->nr)1763return0;17641765if(match_beginning && try_lno)1766return0;17671768if(match_end && preimage->nr + try_lno != img->nr)1769return0;17701771/* Quick hash check */1772for(i =0; i < preimage->nr; i++)1773if(preimage->line[i].hash != img->line[try_lno + i].hash)1774return0;17751776/*1777 * Do we have an exact match? If we were told to match1778 * at the end, size must be exactly at try+fragsize,1779 * otherwise try+fragsize must be still within the preimage,1780 * and either case, the old piece should match the preimage1781 * exactly.1782 */1783if((match_end1784? (try+ preimage->len == img->len)1785: (try+ preimage->len <= img->len)) &&1786!memcmp(img->buf +try, preimage->buf, preimage->len))1787return1;17881789/*1790 * No exact match. If we are ignoring whitespace, run a line-by-line1791 * fuzzy matching. We collect all the line length information because1792 * we need it to adjust whitespace if we match.1793 */1794if(ws_ignore_action == ignore_ws_change) {1795size_t imgoff =0;1796size_t preoff =0;1797size_t postlen = postimage->len;1798size_t imglen[preimage->nr];1799for(i =0; i < preimage->nr; i++) {1800size_t prelen = preimage->line[i].len;18011802 imglen[i] = img->line[try_lno+i].len;1803if(!fuzzy_matchlines(1804 img->buf +try+ imgoff, imglen[i],1805 preimage->buf + preoff, prelen))1806return0;1807if(preimage->line[i].flag & LINE_COMMON)1808 postlen += imglen[i] - prelen;1809 imgoff += imglen[i];1810 preoff += prelen;1811}18121813/*1814 * Ok, the preimage matches with whitespace fuzz. Update it and1815 * the common postimage lines to use the same whitespace as the1816 * target. imgoff now holds the true length of the target that1817 * matches the preimage, and we need to update the line lengths1818 * of the preimage to match the target ones.1819 */1820 fixed_buf =xmalloc(imgoff);1821memcpy(fixed_buf, img->buf +try, imgoff);1822for(i =0; i < preimage->nr; i++)1823 preimage->line[i].len = imglen[i];18241825/*1826 * Update the preimage buffer and the postimage context lines.1827 */1828update_pre_post_images(preimage, postimage,1829 fixed_buf, imgoff, postlen);1830return1;1831}18321833if(ws_error_action != correct_ws_error)1834return0;18351836/*1837 * The hunk does not apply byte-by-byte, but the hash says1838 * it might with whitespace fuzz. We haven't been asked to1839 * ignore whitespace, we were asked to correct whitespace1840 * errors, so let's try matching after whitespace correction.1841 */1842 fixed_buf =xmalloc(preimage->len +1);1843 buf = fixed_buf;1844 orig = preimage->buf;1845 target = img->buf +try;1846for(i =0; i < preimage->nr; i++) {1847size_t fixlen;/* length after fixing the preimage */1848size_t oldlen = preimage->line[i].len;1849size_t tgtlen = img->line[try_lno + i].len;1850size_t tgtfixlen;/* length after fixing the target line */1851char tgtfixbuf[1024], *tgtfix;1852int match;18531854/* Try fixing the line in the preimage */1855 fixlen =ws_fix_copy(buf, orig, oldlen, ws_rule, NULL);18561857/* Try fixing the line in the target */1858if(sizeof(tgtfixbuf) > tgtlen)1859 tgtfix = tgtfixbuf;1860else1861 tgtfix =xmalloc(tgtlen);1862 tgtfixlen =ws_fix_copy(tgtfix, target, tgtlen, ws_rule, NULL);18631864/*1865 * If they match, either the preimage was based on1866 * a version before our tree fixed whitespace breakage,1867 * or we are lacking a whitespace-fix patch the tree1868 * the preimage was based on already had (i.e. target1869 * has whitespace breakage, the preimage doesn't).1870 * In either case, we are fixing the whitespace breakages1871 * so we might as well take the fix together with their1872 * real change.1873 */1874 match = (tgtfixlen == fixlen && !memcmp(tgtfix, buf, fixlen));18751876if(tgtfix != tgtfixbuf)1877free(tgtfix);1878if(!match)1879goto unmatch_exit;18801881 orig += oldlen;1882 buf += fixlen;1883 target += tgtlen;1884}18851886/*1887 * Yes, the preimage is based on an older version that still1888 * has whitespace breakages unfixed, and fixing them makes the1889 * hunk match. Update the context lines in the postimage.1890 */1891update_pre_post_images(preimage, postimage,1892 fixed_buf, buf - fixed_buf,0);1893return1;18941895 unmatch_exit:1896free(fixed_buf);1897return0;1898}18991900static intfind_pos(struct image *img,1901struct image *preimage,1902struct image *postimage,1903int line,1904unsigned ws_rule,1905int match_beginning,int match_end)1906{1907int i;1908unsigned long backwards, forwards,try;1909int backwards_lno, forwards_lno, try_lno;19101911if(preimage->nr > img->nr)1912return-1;19131914/*1915 * If match_begining or match_end is specified, there is no1916 * point starting from a wrong line that will never match and1917 * wander around and wait for a match at the specified end.1918 */1919if(match_beginning)1920 line =0;1921else if(match_end)1922 line = img->nr - preimage->nr;19231924if(line > img->nr)1925 line = img->nr;19261927try=0;1928for(i =0; i < line; i++)1929try+= img->line[i].len;19301931/*1932 * There's probably some smart way to do this, but I'll leave1933 * that to the smart and beautiful people. I'm simple and stupid.1934 */1935 backwards =try;1936 backwards_lno = line;1937 forwards =try;1938 forwards_lno = line;1939 try_lno = line;19401941for(i =0; ; i++) {1942if(match_fragment(img, preimage, postimage,1943try, try_lno, ws_rule,1944 match_beginning, match_end))1945return try_lno;19461947 again:1948if(backwards_lno ==0&& forwards_lno == img->nr)1949break;19501951if(i &1) {1952if(backwards_lno ==0) {1953 i++;1954goto again;1955}1956 backwards_lno--;1957 backwards -= img->line[backwards_lno].len;1958try= backwards;1959 try_lno = backwards_lno;1960}else{1961if(forwards_lno == img->nr) {1962 i++;1963goto again;1964}1965 forwards += img->line[forwards_lno].len;1966 forwards_lno++;1967try= forwards;1968 try_lno = forwards_lno;1969}19701971}1972return-1;1973}19741975static voidremove_first_line(struct image *img)1976{1977 img->buf += img->line[0].len;1978 img->len -= img->line[0].len;1979 img->line++;1980 img->nr--;1981}19821983static voidremove_last_line(struct image *img)1984{1985 img->len -= img->line[--img->nr].len;1986}19871988static voidupdate_image(struct image *img,1989int applied_pos,1990struct image *preimage,1991struct image *postimage)1992{1993/*1994 * remove the copy of preimage at offset in img1995 * and replace it with postimage1996 */1997int i, nr;1998size_t remove_count, insert_count, applied_at =0;1999char*result;20002001for(i =0; i < applied_pos; i++)2002 applied_at += img->line[i].len;20032004 remove_count =0;2005for(i =0; i < preimage->nr; i++)2006 remove_count += img->line[applied_pos + i].len;2007 insert_count = postimage->len;20082009/* Adjust the contents */2010 result =xmalloc(img->len + insert_count - remove_count +1);2011memcpy(result, img->buf, applied_at);2012memcpy(result + applied_at, postimage->buf, postimage->len);2013memcpy(result + applied_at + postimage->len,2014 img->buf + (applied_at + remove_count),2015 img->len - (applied_at + remove_count));2016free(img->buf);2017 img->buf = result;2018 img->len += insert_count - remove_count;2019 result[img->len] ='\0';20202021/* Adjust the line table */2022 nr = img->nr + postimage->nr - preimage->nr;2023if(preimage->nr < postimage->nr) {2024/*2025 * NOTE: this knows that we never call remove_first_line()2026 * on anything other than pre/post image.2027 */2028 img->line =xrealloc(img->line, nr *sizeof(*img->line));2029 img->line_allocated = img->line;2030}2031if(preimage->nr != postimage->nr)2032memmove(img->line + applied_pos + postimage->nr,2033 img->line + applied_pos + preimage->nr,2034(img->nr - (applied_pos + preimage->nr)) *2035sizeof(*img->line));2036memcpy(img->line + applied_pos,2037 postimage->line,2038 postimage->nr *sizeof(*img->line));2039 img->nr = nr;2040}20412042static intapply_one_fragment(struct image *img,struct fragment *frag,2043int inaccurate_eof,unsigned ws_rule)2044{2045int match_beginning, match_end;2046const char*patch = frag->patch;2047int size = frag->size;2048char*old, *new, *oldlines, *newlines;2049int new_blank_lines_at_end =0;2050unsigned long leading, trailing;2051int pos, applied_pos;2052struct image preimage;2053struct image postimage;20542055memset(&preimage,0,sizeof(preimage));2056memset(&postimage,0,sizeof(postimage));2057 oldlines =xmalloc(size);2058 newlines =xmalloc(size);20592060 old = oldlines;2061new= newlines;2062while(size >0) {2063char first;2064int len =linelen(patch, size);2065int plen, added;2066int added_blank_line =0;20672068if(!len)2069break;20702071/*2072 * "plen" is how much of the line we should use for2073 * the actual patch data. Normally we just remove the2074 * first character on the line, but if the line is2075 * followed by "\ No newline", then we also remove the2076 * last one (which is the newline, of course).2077 */2078 plen = len -1;2079if(len < size && patch[len] =='\\')2080 plen--;2081 first = *patch;2082if(apply_in_reverse) {2083if(first =='-')2084 first ='+';2085else if(first =='+')2086 first ='-';2087}20882089switch(first) {2090case'\n':2091/* Newer GNU diff, empty context line */2092if(plen <0)2093/* ... followed by '\No newline'; nothing */2094break;2095*old++ ='\n';2096*new++ ='\n';2097add_line_info(&preimage,"\n",1, LINE_COMMON);2098add_line_info(&postimage,"\n",1, LINE_COMMON);2099break;2100case' ':2101case'-':2102memcpy(old, patch +1, plen);2103add_line_info(&preimage, old, plen,2104(first ==' '? LINE_COMMON :0));2105 old += plen;2106if(first =='-')2107break;2108/* Fall-through for ' ' */2109case'+':2110/* --no-add does not add new lines */2111if(first =='+'&& no_add)2112break;21132114if(first !='+'||2115!whitespace_error ||2116 ws_error_action != correct_ws_error) {2117memcpy(new, patch +1, plen);2118 added = plen;2119}2120else{2121 added =ws_fix_copy(new, patch +1, plen, ws_rule, &applied_after_fixing_ws);2122}2123add_line_info(&postimage,new, added,2124(first =='+'?0: LINE_COMMON));2125new+= added;2126if(first =='+'&&2127 added ==1&&new[-1] =='\n')2128 added_blank_line =1;2129break;2130case'@':case'\\':2131/* Ignore it, we already handled it */2132break;2133default:2134if(apply_verbosely)2135error("invalid start of line: '%c'", first);2136return-1;2137}2138if(added_blank_line)2139 new_blank_lines_at_end++;2140else2141 new_blank_lines_at_end =0;2142 patch += len;2143 size -= len;2144}2145if(inaccurate_eof &&2146 old > oldlines && old[-1] =='\n'&&2147new> newlines &&new[-1] =='\n') {2148 old--;2149new--;2150}21512152 leading = frag->leading;2153 trailing = frag->trailing;21542155/*2156 * A hunk to change lines at the beginning would begin with2157 * @@ -1,L +N,M @@2158 * but we need to be careful. -U0 that inserts before the second2159 * line also has this pattern.2160 *2161 * And a hunk to add to an empty file would begin with2162 * @@ -0,0 +N,M @@2163 *2164 * In other words, a hunk that is (frag->oldpos <= 1) with or2165 * without leading context must match at the beginning.2166 */2167 match_beginning = (!frag->oldpos ||2168(frag->oldpos ==1&& !unidiff_zero));21692170/*2171 * A hunk without trailing lines must match at the end.2172 * However, we simply cannot tell if a hunk must match end2173 * from the lack of trailing lines if the patch was generated2174 * with unidiff without any context.2175 */2176 match_end = !unidiff_zero && !trailing;21772178 pos = frag->newpos ? (frag->newpos -1) :0;2179 preimage.buf = oldlines;2180 preimage.len = old - oldlines;2181 postimage.buf = newlines;2182 postimage.len =new- newlines;2183 preimage.line = preimage.line_allocated;2184 postimage.line = postimage.line_allocated;21852186for(;;) {21872188 applied_pos =find_pos(img, &preimage, &postimage, pos,2189 ws_rule, match_beginning, match_end);21902191if(applied_pos >=0)2192break;21932194/* Am I at my context limits? */2195if((leading <= p_context) && (trailing <= p_context))2196break;2197if(match_beginning || match_end) {2198 match_beginning = match_end =0;2199continue;2200}22012202/*2203 * Reduce the number of context lines; reduce both2204 * leading and trailing if they are equal otherwise2205 * just reduce the larger context.2206 */2207if(leading >= trailing) {2208remove_first_line(&preimage);2209remove_first_line(&postimage);2210 pos--;2211 leading--;2212}2213if(trailing > leading) {2214remove_last_line(&preimage);2215remove_last_line(&postimage);2216 trailing--;2217}2218}22192220if(applied_pos >=0) {2221if(ws_error_action == correct_ws_error &&2222 new_blank_lines_at_end &&2223 postimage.nr + applied_pos == img->nr) {2224/*2225 * If the patch application adds blank lines2226 * at the end, and if the patch applies at the2227 * end of the image, remove those added blank2228 * lines.2229 */2230while(new_blank_lines_at_end--)2231remove_last_line(&postimage);2232}22332234/*2235 * Warn if it was necessary to reduce the number2236 * of context lines.2237 */2238if((leading != frag->leading) ||2239(trailing != frag->trailing))2240fprintf(stderr,"Context reduced to (%ld/%ld)"2241" to apply fragment at%d\n",2242 leading, trailing, applied_pos+1);2243update_image(img, applied_pos, &preimage, &postimage);2244}else{2245if(apply_verbosely)2246error("while searching for:\n%.*s",2247(int)(old - oldlines), oldlines);2248}22492250free(oldlines);2251free(newlines);2252free(preimage.line_allocated);2253free(postimage.line_allocated);22542255return(applied_pos <0);2256}22572258static intapply_binary_fragment(struct image *img,struct patch *patch)2259{2260struct fragment *fragment = patch->fragments;2261unsigned long len;2262void*dst;22632264/* Binary patch is irreversible without the optional second hunk */2265if(apply_in_reverse) {2266if(!fragment->next)2267returnerror("cannot reverse-apply a binary patch "2268"without the reverse hunk to '%s'",2269 patch->new_name2270? patch->new_name : patch->old_name);2271 fragment = fragment->next;2272}2273switch(fragment->binary_patch_method) {2274case BINARY_DELTA_DEFLATED:2275 dst =patch_delta(img->buf, img->len, fragment->patch,2276 fragment->size, &len);2277if(!dst)2278return-1;2279clear_image(img);2280 img->buf = dst;2281 img->len = len;2282return0;2283case BINARY_LITERAL_DEFLATED:2284clear_image(img);2285 img->len = fragment->size;2286 img->buf =xmalloc(img->len+1);2287memcpy(img->buf, fragment->patch, img->len);2288 img->buf[img->len] ='\0';2289return0;2290}2291return-1;2292}22932294static intapply_binary(struct image *img,struct patch *patch)2295{2296const char*name = patch->old_name ? patch->old_name : patch->new_name;2297unsigned char sha1[20];22982299/*2300 * For safety, we require patch index line to contain2301 * full 40-byte textual SHA1 for old and new, at least for now.2302 */2303if(strlen(patch->old_sha1_prefix) !=40||2304strlen(patch->new_sha1_prefix) !=40||2305get_sha1_hex(patch->old_sha1_prefix, sha1) ||2306get_sha1_hex(patch->new_sha1_prefix, sha1))2307returnerror("cannot apply binary patch to '%s' "2308"without full index line", name);23092310if(patch->old_name) {2311/*2312 * See if the old one matches what the patch2313 * applies to.2314 */2315hash_sha1_file(img->buf, img->len, blob_type, sha1);2316if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2317returnerror("the patch applies to '%s' (%s), "2318"which does not match the "2319"current contents.",2320 name,sha1_to_hex(sha1));2321}2322else{2323/* Otherwise, the old one must be empty. */2324if(img->len)2325returnerror("the patch applies to an empty "2326"'%s' but it is not empty", name);2327}23282329get_sha1_hex(patch->new_sha1_prefix, sha1);2330if(is_null_sha1(sha1)) {2331clear_image(img);2332return0;/* deletion patch */2333}23342335if(has_sha1_file(sha1)) {2336/* We already have the postimage */2337enum object_type type;2338unsigned long size;2339char*result;23402341 result =read_sha1_file(sha1, &type, &size);2342if(!result)2343returnerror("the necessary postimage%sfor "2344"'%s' cannot be read",2345 patch->new_sha1_prefix, name);2346clear_image(img);2347 img->buf = result;2348 img->len = size;2349}else{2350/*2351 * We have verified buf matches the preimage;2352 * apply the patch data to it, which is stored2353 * in the patch->fragments->{patch,size}.2354 */2355if(apply_binary_fragment(img, patch))2356returnerror("binary patch does not apply to '%s'",2357 name);23582359/* verify that the result matches */2360hash_sha1_file(img->buf, img->len, blob_type, sha1);2361if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2362returnerror("binary patch to '%s' creates incorrect result (expecting%s, got%s)",2363 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2364}23652366return0;2367}23682369static intapply_fragments(struct image *img,struct patch *patch)2370{2371struct fragment *frag = patch->fragments;2372const char*name = patch->old_name ? patch->old_name : patch->new_name;2373unsigned ws_rule = patch->ws_rule;2374unsigned inaccurate_eof = patch->inaccurate_eof;23752376if(patch->is_binary)2377returnapply_binary(img, patch);23782379while(frag) {2380if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule)) {2381error("patch failed:%s:%ld", name, frag->oldpos);2382if(!apply_with_reject)2383return-1;2384 frag->rejected =1;2385}2386 frag = frag->next;2387}2388return0;2389}23902391static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2392{2393if(!ce)2394return0;23952396if(S_ISGITLINK(ce->ce_mode)) {2397strbuf_grow(buf,100);2398strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2399}else{2400enum object_type type;2401unsigned long sz;2402char*result;24032404 result =read_sha1_file(ce->sha1, &type, &sz);2405if(!result)2406return-1;2407/* XXX read_sha1_file NUL-terminates */2408strbuf_attach(buf, result, sz, sz +1);2409}2410return0;2411}24122413static struct patch *in_fn_table(const char*name)2414{2415struct string_list_item *item;24162417if(name == NULL)2418return NULL;24192420 item =string_list_lookup(name, &fn_table);2421if(item != NULL)2422return(struct patch *)item->util;24232424return NULL;2425}24262427/*2428 * item->util in the filename table records the status of the path.2429 * Usually it points at a patch (whose result records the contents2430 * of it after applying it), but it could be PATH_WAS_DELETED for a2431 * path that a previously applied patch has already removed.2432 */2433#define PATH_TO_BE_DELETED ((struct patch *) -2)2434#define PATH_WAS_DELETED ((struct patch *) -1)24352436static intto_be_deleted(struct patch *patch)2437{2438return patch == PATH_TO_BE_DELETED;2439}24402441static intwas_deleted(struct patch *patch)2442{2443return patch == PATH_WAS_DELETED;2444}24452446static voidadd_to_fn_table(struct patch *patch)2447{2448struct string_list_item *item;24492450/*2451 * Always add new_name unless patch is a deletion2452 * This should cover the cases for normal diffs,2453 * file creations and copies2454 */2455if(patch->new_name != NULL) {2456 item =string_list_insert(patch->new_name, &fn_table);2457 item->util = patch;2458}24592460/*2461 * store a failure on rename/deletion cases because2462 * later chunks shouldn't patch old names2463 */2464if((patch->new_name == NULL) || (patch->is_rename)) {2465 item =string_list_insert(patch->old_name, &fn_table);2466 item->util = PATH_WAS_DELETED;2467}2468}24692470static voidprepare_fn_table(struct patch *patch)2471{2472/*2473 * store information about incoming file deletion2474 */2475while(patch) {2476if((patch->new_name == NULL) || (patch->is_rename)) {2477struct string_list_item *item;2478 item =string_list_insert(patch->old_name, &fn_table);2479 item->util = PATH_TO_BE_DELETED;2480}2481 patch = patch->next;2482}2483}24842485static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)2486{2487struct strbuf buf = STRBUF_INIT;2488struct image image;2489size_t len;2490char*img;2491struct patch *tpatch;24922493if(!(patch->is_copy || patch->is_rename) &&2494(tpatch =in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {2495if(was_deleted(tpatch)) {2496returnerror("patch%shas been renamed/deleted",2497 patch->old_name);2498}2499/* We have a patched copy in memory use that */2500strbuf_add(&buf, tpatch->result, tpatch->resultsize);2501}else if(cached) {2502if(read_file_or_gitlink(ce, &buf))2503returnerror("read of%sfailed", patch->old_name);2504}else if(patch->old_name) {2505if(S_ISGITLINK(patch->old_mode)) {2506if(ce) {2507read_file_or_gitlink(ce, &buf);2508}else{2509/*2510 * There is no way to apply subproject2511 * patch without looking at the index.2512 */2513 patch->fragments = NULL;2514}2515}else{2516if(read_old_data(st, patch->old_name, &buf))2517returnerror("read of%sfailed", patch->old_name);2518}2519}25202521 img =strbuf_detach(&buf, &len);2522prepare_image(&image, img, len, !patch->is_binary);25232524if(apply_fragments(&image, patch) <0)2525return-1;/* note with --reject this succeeds. */2526 patch->result = image.buf;2527 patch->resultsize = image.len;2528add_to_fn_table(patch);2529free(image.line_allocated);25302531if(0< patch->is_delete && patch->resultsize)2532returnerror("removal patch leaves file contents");25332534return0;2535}25362537static intcheck_to_create_blob(const char*new_name,int ok_if_exists)2538{2539struct stat nst;2540if(!lstat(new_name, &nst)) {2541if(S_ISDIR(nst.st_mode) || ok_if_exists)2542return0;2543/*2544 * A leading component of new_name might be a symlink2545 * that is going to be removed with this patch, but2546 * still pointing at somewhere that has the path.2547 * In such a case, path "new_name" does not exist as2548 * far as git is concerned.2549 */2550if(has_symlink_leading_path(new_name,strlen(new_name)))2551return0;25522553returnerror("%s: already exists in working directory", new_name);2554}2555else if((errno != ENOENT) && (errno != ENOTDIR))2556returnerror("%s:%s", new_name,strerror(errno));2557return0;2558}25592560static intverify_index_match(struct cache_entry *ce,struct stat *st)2561{2562if(S_ISGITLINK(ce->ce_mode)) {2563if(!S_ISDIR(st->st_mode))2564return-1;2565return0;2566}2567returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID);2568}25692570static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)2571{2572const char*old_name = patch->old_name;2573struct patch *tpatch = NULL;2574int stat_ret =0;2575unsigned st_mode =0;25762577/*2578 * Make sure that we do not have local modifications from the2579 * index when we are looking at the index. Also make sure2580 * we have the preimage file to be patched in the work tree,2581 * unless --cached, which tells git to apply only in the index.2582 */2583if(!old_name)2584return0;25852586assert(patch->is_new <=0);25872588if(!(patch->is_copy || patch->is_rename) &&2589(tpatch =in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {2590if(was_deleted(tpatch))2591returnerror("%s: has been deleted/renamed", old_name);2592 st_mode = tpatch->new_mode;2593}else if(!cached) {2594 stat_ret =lstat(old_name, st);2595if(stat_ret && errno != ENOENT)2596returnerror("%s:%s", old_name,strerror(errno));2597}25982599if(to_be_deleted(tpatch))2600 tpatch = NULL;26012602if(check_index && !tpatch) {2603int pos =cache_name_pos(old_name,strlen(old_name));2604if(pos <0) {2605if(patch->is_new <0)2606goto is_new;2607returnerror("%s: does not exist in index", old_name);2608}2609*ce = active_cache[pos];2610if(stat_ret <0) {2611struct checkout costate;2612/* checkout */2613 costate.base_dir ="";2614 costate.base_dir_len =0;2615 costate.force =0;2616 costate.quiet =0;2617 costate.not_new =0;2618 costate.refresh_cache =1;2619if(checkout_entry(*ce, &costate, NULL) ||2620lstat(old_name, st))2621return-1;2622}2623if(!cached &&verify_index_match(*ce, st))2624returnerror("%s: does not match index", old_name);2625if(cached)2626 st_mode = (*ce)->ce_mode;2627}else if(stat_ret <0) {2628if(patch->is_new <0)2629goto is_new;2630returnerror("%s:%s", old_name,strerror(errno));2631}26322633if(!cached && !tpatch)2634 st_mode =ce_mode_from_stat(*ce, st->st_mode);26352636if(patch->is_new <0)2637 patch->is_new =0;2638if(!patch->old_mode)2639 patch->old_mode = st_mode;2640if((st_mode ^ patch->old_mode) & S_IFMT)2641returnerror("%s: wrong type", old_name);2642if(st_mode != patch->old_mode)2643warning("%shas type%o, expected%o",2644 old_name, st_mode, patch->old_mode);2645if(!patch->new_mode && !patch->is_delete)2646 patch->new_mode = st_mode;2647return0;26482649 is_new:2650 patch->is_new =1;2651 patch->is_delete =0;2652 patch->old_name = NULL;2653return0;2654}26552656static intcheck_patch(struct patch *patch)2657{2658struct stat st;2659const char*old_name = patch->old_name;2660const char*new_name = patch->new_name;2661const char*name = old_name ? old_name : new_name;2662struct cache_entry *ce = NULL;2663struct patch *tpatch;2664int ok_if_exists;2665int status;26662667 patch->rejected =1;/* we will drop this after we succeed */26682669 status =check_preimage(patch, &ce, &st);2670if(status)2671return status;2672 old_name = patch->old_name;26732674if((tpatch =in_fn_table(new_name)) &&2675(was_deleted(tpatch) ||to_be_deleted(tpatch)))2676/*2677 * A type-change diff is always split into a patch to2678 * delete old, immediately followed by a patch to2679 * create new (see diff.c::run_diff()); in such a case2680 * it is Ok that the entry to be deleted by the2681 * previous patch is still in the working tree and in2682 * the index.2683 */2684 ok_if_exists =1;2685else2686 ok_if_exists =0;26872688if(new_name &&2689((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {2690if(check_index &&2691cache_name_pos(new_name,strlen(new_name)) >=0&&2692!ok_if_exists)2693returnerror("%s: already exists in index", new_name);2694if(!cached) {2695int err =check_to_create_blob(new_name, ok_if_exists);2696if(err)2697return err;2698}2699if(!patch->new_mode) {2700if(0< patch->is_new)2701 patch->new_mode = S_IFREG |0644;2702else2703 patch->new_mode = patch->old_mode;2704}2705}27062707if(new_name && old_name) {2708int same = !strcmp(old_name, new_name);2709if(!patch->new_mode)2710 patch->new_mode = patch->old_mode;2711if((patch->old_mode ^ patch->new_mode) & S_IFMT)2712returnerror("new mode (%o) of%sdoes not match old mode (%o)%s%s",2713 patch->new_mode, new_name, patch->old_mode,2714 same ?"":" of ", same ?"": old_name);2715}27162717if(apply_data(patch, &st, ce) <0)2718returnerror("%s: patch does not apply", name);2719 patch->rejected =0;2720return0;2721}27222723static intcheck_patch_list(struct patch *patch)2724{2725int err =0;27262727prepare_fn_table(patch);2728while(patch) {2729if(apply_verbosely)2730say_patch_name(stderr,2731"Checking patch ", patch,"...\n");2732 err |=check_patch(patch);2733 patch = patch->next;2734}2735return err;2736}27372738/* This function tries to read the sha1 from the current index */2739static intget_current_sha1(const char*path,unsigned char*sha1)2740{2741int pos;27422743if(read_cache() <0)2744return-1;2745 pos =cache_name_pos(path,strlen(path));2746if(pos <0)2747return-1;2748hashcpy(sha1, active_cache[pos]->sha1);2749return0;2750}27512752/* Build an index that contains the just the files needed for a 3way merge */2753static voidbuild_fake_ancestor(struct patch *list,const char*filename)2754{2755struct patch *patch;2756struct index_state result = { NULL };2757int fd;27582759/* Once we start supporting the reverse patch, it may be2760 * worth showing the new sha1 prefix, but until then...2761 */2762for(patch = list; patch; patch = patch->next) {2763const unsigned char*sha1_ptr;2764unsigned char sha1[20];2765struct cache_entry *ce;2766const char*name;27672768 name = patch->old_name ? patch->old_name : patch->new_name;2769if(0< patch->is_new)2770continue;2771else if(get_sha1(patch->old_sha1_prefix, sha1))2772/* git diff has no index line for mode/type changes */2773if(!patch->lines_added && !patch->lines_deleted) {2774if(get_current_sha1(patch->new_name, sha1) ||2775get_current_sha1(patch->old_name, sha1))2776die("mode change for%s, which is not "2777"in current HEAD", name);2778 sha1_ptr = sha1;2779}else2780die("sha1 information is lacking or useless "2781"(%s).", name);2782else2783 sha1_ptr = sha1;27842785 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);2786if(!ce)2787die("make_cache_entry failed for path '%s'", name);2788if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))2789die("Could not add%sto temporary index", name);2790}27912792 fd =open(filename, O_WRONLY | O_CREAT,0666);2793if(fd <0||write_index(&result, fd) ||close(fd))2794die("Could not write temporary index to%s", filename);27952796discard_index(&result);2797}27982799static voidstat_patch_list(struct patch *patch)2800{2801int files, adds, dels;28022803for(files = adds = dels =0; patch ; patch = patch->next) {2804 files++;2805 adds += patch->lines_added;2806 dels += patch->lines_deleted;2807show_stats(patch);2808}28092810printf("%dfiles changed,%dinsertions(+),%ddeletions(-)\n", files, adds, dels);2811}28122813static voidnumstat_patch_list(struct patch *patch)2814{2815for( ; patch; patch = patch->next) {2816const char*name;2817 name = patch->new_name ? patch->new_name : patch->old_name;2818if(patch->is_binary)2819printf("-\t-\t");2820else2821printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);2822write_name_quoted(name, stdout, line_termination);2823}2824}28252826static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)2827{2828if(mode)2829printf("%smode%06o%s\n", newdelete, mode, name);2830else2831printf("%s %s\n", newdelete, name);2832}28332834static voidshow_mode_change(struct patch *p,int show_name)2835{2836if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {2837if(show_name)2838printf(" mode change%06o =>%06o%s\n",2839 p->old_mode, p->new_mode, p->new_name);2840else2841printf(" mode change%06o =>%06o\n",2842 p->old_mode, p->new_mode);2843}2844}28452846static voidshow_rename_copy(struct patch *p)2847{2848const char*renamecopy = p->is_rename ?"rename":"copy";2849const char*old, *new;28502851/* Find common prefix */2852 old = p->old_name;2853new= p->new_name;2854while(1) {2855const char*slash_old, *slash_new;2856 slash_old =strchr(old,'/');2857 slash_new =strchr(new,'/');2858if(!slash_old ||2859!slash_new ||2860 slash_old - old != slash_new -new||2861memcmp(old,new, slash_new -new))2862break;2863 old = slash_old +1;2864new= slash_new +1;2865}2866/* p->old_name thru old is the common prefix, and old and new2867 * through the end of names are renames2868 */2869if(old != p->old_name)2870printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,2871(int)(old - p->old_name), p->old_name,2872 old,new, p->score);2873else2874printf("%s %s=>%s(%d%%)\n", renamecopy,2875 p->old_name, p->new_name, p->score);2876show_mode_change(p,0);2877}28782879static voidsummary_patch_list(struct patch *patch)2880{2881struct patch *p;28822883for(p = patch; p; p = p->next) {2884if(p->is_new)2885show_file_mode_name("create", p->new_mode, p->new_name);2886else if(p->is_delete)2887show_file_mode_name("delete", p->old_mode, p->old_name);2888else{2889if(p->is_rename || p->is_copy)2890show_rename_copy(p);2891else{2892if(p->score) {2893printf(" rewrite%s(%d%%)\n",2894 p->new_name, p->score);2895show_mode_change(p,0);2896}2897else2898show_mode_change(p,1);2899}2900}2901}2902}29032904static voidpatch_stats(struct patch *patch)2905{2906int lines = patch->lines_added + patch->lines_deleted;29072908if(lines > max_change)2909 max_change = lines;2910if(patch->old_name) {2911int len =quote_c_style(patch->old_name, NULL, NULL,0);2912if(!len)2913 len =strlen(patch->old_name);2914if(len > max_len)2915 max_len = len;2916}2917if(patch->new_name) {2918int len =quote_c_style(patch->new_name, NULL, NULL,0);2919if(!len)2920 len =strlen(patch->new_name);2921if(len > max_len)2922 max_len = len;2923}2924}29252926static voidremove_file(struct patch *patch,int rmdir_empty)2927{2928if(update_index) {2929if(remove_file_from_cache(patch->old_name) <0)2930die("unable to remove%sfrom index", patch->old_name);2931}2932if(!cached) {2933if(S_ISGITLINK(patch->old_mode)) {2934if(rmdir(patch->old_name))2935warning("unable to remove submodule%s",2936 patch->old_name);2937}else if(!unlink_or_warn(patch->old_name) && rmdir_empty) {2938remove_path(patch->old_name);2939}2940}2941}29422943static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)2944{2945struct stat st;2946struct cache_entry *ce;2947int namelen =strlen(path);2948unsigned ce_size =cache_entry_size(namelen);29492950if(!update_index)2951return;29522953 ce =xcalloc(1, ce_size);2954memcpy(ce->name, path, namelen);2955 ce->ce_mode =create_ce_mode(mode);2956 ce->ce_flags = namelen;2957if(S_ISGITLINK(mode)) {2958const char*s = buf;29592960if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))2961die("corrupt patch for subproject%s", path);2962}else{2963if(!cached) {2964if(lstat(path, &st) <0)2965die_errno("unable to stat newly created file '%s'",2966 path);2967fill_stat_cache_info(ce, &st);2968}2969if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)2970die("unable to create backing store for newly created file%s", path);2971}2972if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)2973die("unable to add cache entry for%s", path);2974}29752976static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)2977{2978int fd;2979struct strbuf nbuf = STRBUF_INIT;29802981if(S_ISGITLINK(mode)) {2982struct stat st;2983if(!lstat(path, &st) &&S_ISDIR(st.st_mode))2984return0;2985returnmkdir(path,0777);2986}29872988if(has_symlinks &&S_ISLNK(mode))2989/* Although buf:size is counted string, it also is NUL2990 * terminated.2991 */2992returnsymlink(buf, path);29932994 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);2995if(fd <0)2996return-1;29972998if(convert_to_working_tree(path, buf, size, &nbuf)) {2999 size = nbuf.len;3000 buf = nbuf.buf;3001}3002write_or_die(fd, buf, size);3003strbuf_release(&nbuf);30043005if(close(fd) <0)3006die_errno("closing file '%s'", path);3007return0;3008}30093010/*3011 * We optimistically assume that the directories exist,3012 * which is true 99% of the time anyway. If they don't,3013 * we create them and try again.3014 */3015static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)3016{3017if(cached)3018return;3019if(!try_create_file(path, mode, buf, size))3020return;30213022if(errno == ENOENT) {3023if(safe_create_leading_directories(path))3024return;3025if(!try_create_file(path, mode, buf, size))3026return;3027}30283029if(errno == EEXIST || errno == EACCES) {3030/* We may be trying to create a file where a directory3031 * used to be.3032 */3033struct stat st;3034if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))3035 errno = EEXIST;3036}30373038if(errno == EEXIST) {3039unsigned int nr =getpid();30403041for(;;) {3042char newpath[PATH_MAX];3043mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);3044if(!try_create_file(newpath, mode, buf, size)) {3045if(!rename(newpath, path))3046return;3047unlink_or_warn(newpath);3048break;3049}3050if(errno != EEXIST)3051break;3052++nr;3053}3054}3055die_errno("unable to write file '%s' mode%o", path, mode);3056}30573058static voidcreate_file(struct patch *patch)3059{3060char*path = patch->new_name;3061unsigned mode = patch->new_mode;3062unsigned long size = patch->resultsize;3063char*buf = patch->result;30643065if(!mode)3066 mode = S_IFREG |0644;3067create_one_file(path, mode, buf, size);3068add_index_file(path, mode, buf, size);3069}30703071/* phase zero is to remove, phase one is to create */3072static voidwrite_out_one_result(struct patch *patch,int phase)3073{3074if(patch->is_delete >0) {3075if(phase ==0)3076remove_file(patch,1);3077return;3078}3079if(patch->is_new >0|| patch->is_copy) {3080if(phase ==1)3081create_file(patch);3082return;3083}3084/*3085 * Rename or modification boils down to the same3086 * thing: remove the old, write the new3087 */3088if(phase ==0)3089remove_file(patch, patch->is_rename);3090if(phase ==1)3091create_file(patch);3092}30933094static intwrite_out_one_reject(struct patch *patch)3095{3096FILE*rej;3097char namebuf[PATH_MAX];3098struct fragment *frag;3099int cnt =0;31003101for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {3102if(!frag->rejected)3103continue;3104 cnt++;3105}31063107if(!cnt) {3108if(apply_verbosely)3109say_patch_name(stderr,3110"Applied patch ", patch," cleanly.\n");3111return0;3112}31133114/* This should not happen, because a removal patch that leaves3115 * contents are marked "rejected" at the patch level.3116 */3117if(!patch->new_name)3118die("internal error");31193120/* Say this even without --verbose */3121say_patch_name(stderr,"Applying patch ", patch," with");3122fprintf(stderr,"%drejects...\n", cnt);31233124 cnt =strlen(patch->new_name);3125if(ARRAY_SIZE(namebuf) <= cnt +5) {3126 cnt =ARRAY_SIZE(namebuf) -5;3127warning("truncating .rej filename to %.*s.rej",3128 cnt -1, patch->new_name);3129}3130memcpy(namebuf, patch->new_name, cnt);3131memcpy(namebuf + cnt,".rej",5);31323133 rej =fopen(namebuf,"w");3134if(!rej)3135returnerror("cannot open%s:%s", namebuf,strerror(errno));31363137/* Normal git tools never deal with .rej, so do not pretend3138 * this is a git patch by saying --git nor give extended3139 * headers. While at it, maybe please "kompare" that wants3140 * the trailing TAB and some garbage at the end of line ;-).3141 */3142fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",3143 patch->new_name, patch->new_name);3144for(cnt =1, frag = patch->fragments;3145 frag;3146 cnt++, frag = frag->next) {3147if(!frag->rejected) {3148fprintf(stderr,"Hunk #%dapplied cleanly.\n", cnt);3149continue;3150}3151fprintf(stderr,"Rejected hunk #%d.\n", cnt);3152fprintf(rej,"%.*s", frag->size, frag->patch);3153if(frag->patch[frag->size-1] !='\n')3154fputc('\n', rej);3155}3156fclose(rej);3157return-1;3158}31593160static intwrite_out_results(struct patch *list,int skipped_patch)3161{3162int phase;3163int errs =0;3164struct patch *l;31653166if(!list && !skipped_patch)3167returnerror("No changes");31683169for(phase =0; phase <2; phase++) {3170 l = list;3171while(l) {3172if(l->rejected)3173 errs =1;3174else{3175write_out_one_result(l, phase);3176if(phase ==1&&write_out_one_reject(l))3177 errs =1;3178}3179 l = l->next;3180}3181}3182return errs;3183}31843185static struct lock_file lock_file;31863187static struct string_list limit_by_name;3188static int has_include;3189static voidadd_name_limit(const char*name,int exclude)3190{3191struct string_list_item *it;31923193 it =string_list_append(name, &limit_by_name);3194 it->util = exclude ? NULL : (void*)1;3195}31963197static intuse_patch(struct patch *p)3198{3199const char*pathname = p->new_name ? p->new_name : p->old_name;3200int i;32013202/* Paths outside are not touched regardless of "--include" */3203if(0< prefix_length) {3204int pathlen =strlen(pathname);3205if(pathlen <= prefix_length ||3206memcmp(prefix, pathname, prefix_length))3207return0;3208}32093210/* See if it matches any of exclude/include rule */3211for(i =0; i < limit_by_name.nr; i++) {3212struct string_list_item *it = &limit_by_name.items[i];3213if(!fnmatch(it->string, pathname,0))3214return(it->util != NULL);3215}32163217/*3218 * If we had any include, a path that does not match any rule is3219 * not used. Otherwise, we saw bunch of exclude rules (or none)3220 * and such a path is used.3221 */3222return!has_include;3223}322432253226static voidprefix_one(char**name)3227{3228char*old_name = *name;3229if(!old_name)3230return;3231*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3232free(old_name);3233}32343235static voidprefix_patches(struct patch *p)3236{3237if(!prefix || p->is_toplevel_relative)3238return;3239for( ; p; p = p->next) {3240if(p->new_name == p->old_name) {3241char*prefixed = p->new_name;3242prefix_one(&prefixed);3243 p->new_name = p->old_name = prefixed;3244}3245else{3246prefix_one(&p->new_name);3247prefix_one(&p->old_name);3248}3249}3250}32513252#define INACCURATE_EOF (1<<0)3253#define RECOUNT (1<<1)32543255static intapply_patch(int fd,const char*filename,int options)3256{3257size_t offset;3258struct strbuf buf = STRBUF_INIT;3259struct patch *list = NULL, **listp = &list;3260int skipped_patch =0;32613262/* FIXME - memory leak when using multiple patch files as inputs */3263memset(&fn_table,0,sizeof(struct string_list));3264 patch_input_file = filename;3265read_patch_file(&buf, fd);3266 offset =0;3267while(offset < buf.len) {3268struct patch *patch;3269int nr;32703271 patch =xcalloc(1,sizeof(*patch));3272 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3273 patch->recount = !!(options & RECOUNT);3274 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3275if(nr <0)3276break;3277if(apply_in_reverse)3278reverse_patches(patch);3279if(prefix)3280prefix_patches(patch);3281if(use_patch(patch)) {3282patch_stats(patch);3283*listp = patch;3284 listp = &patch->next;3285}3286else{3287/* perhaps free it a bit better? */3288free(patch);3289 skipped_patch++;3290}3291 offset += nr;3292}32933294if(whitespace_error && (ws_error_action == die_on_ws_error))3295 apply =0;32963297 update_index = check_index && apply;3298if(update_index && newfd <0)3299 newfd =hold_locked_index(&lock_file,1);33003301if(check_index) {3302if(read_cache() <0)3303die("unable to read index file");3304}33053306if((check || apply) &&3307check_patch_list(list) <0&&3308!apply_with_reject)3309exit(1);33103311if(apply &&write_out_results(list, skipped_patch))3312exit(1);33133314if(fake_ancestor)3315build_fake_ancestor(list, fake_ancestor);33163317if(diffstat)3318stat_patch_list(list);33193320if(numstat)3321numstat_patch_list(list);33223323if(summary)3324summary_patch_list(list);33253326strbuf_release(&buf);3327return0;3328}33293330static intgit_apply_config(const char*var,const char*value,void*cb)3331{3332if(!strcmp(var,"apply.whitespace"))3333returngit_config_string(&apply_default_whitespace, var, value);3334else if(!strcmp(var,"apply.ignorewhitespace"))3335returngit_config_string(&apply_default_ignorewhitespace, var, value);3336returngit_default_config(var, value, cb);3337}33383339static intoption_parse_exclude(const struct option *opt,3340const char*arg,int unset)3341{3342add_name_limit(arg,1);3343return0;3344}33453346static intoption_parse_include(const struct option *opt,3347const char*arg,int unset)3348{3349add_name_limit(arg,0);3350 has_include =1;3351return0;3352}33533354static intoption_parse_p(const struct option *opt,3355const char*arg,int unset)3356{3357 p_value =atoi(arg);3358 p_value_known =1;3359return0;3360}33613362static intoption_parse_z(const struct option *opt,3363const char*arg,int unset)3364{3365if(unset)3366 line_termination ='\n';3367else3368 line_termination =0;3369return0;3370}33713372static intoption_parse_space_change(const struct option *opt,3373const char*arg,int unset)3374{3375if(unset)3376 ws_ignore_action = ignore_ws_none;3377else3378 ws_ignore_action = ignore_ws_change;3379return0;3380}33813382static intoption_parse_whitespace(const struct option *opt,3383const char*arg,int unset)3384{3385const char**whitespace_option = opt->value;33863387*whitespace_option = arg;3388parse_whitespace_option(arg);3389return0;3390}33913392static intoption_parse_directory(const struct option *opt,3393const char*arg,int unset)3394{3395 root_len =strlen(arg);3396if(root_len && arg[root_len -1] !='/') {3397char*new_root;3398 root = new_root =xmalloc(root_len +2);3399strcpy(new_root, arg);3400strcpy(new_root + root_len++,"/");3401}else3402 root = arg;3403return0;3404}34053406intcmd_apply(int argc,const char**argv,const char*unused_prefix)3407{3408int i;3409int errs =0;3410int is_not_gitdir;3411int binary;3412int force_apply =0;34133414const char*whitespace_option = NULL;34153416struct option builtin_apply_options[] = {3417{ OPTION_CALLBACK,0,"exclude", NULL,"path",3418"don't apply changes matching the given path",34190, option_parse_exclude },3420{ OPTION_CALLBACK,0,"include", NULL,"path",3421"apply changes matching the given path",34220, option_parse_include },3423{ OPTION_CALLBACK,'p', NULL, NULL,"num",3424"remove <num> leading slashes from traditional diff paths",34250, option_parse_p },3426OPT_BOOLEAN(0,"no-add", &no_add,3427"ignore additions made by the patch"),3428OPT_BOOLEAN(0,"stat", &diffstat,3429"instead of applying the patch, output diffstat for the input"),3430{ OPTION_BOOLEAN,0,"allow-binary-replacement", &binary,3431 NULL,"old option, now no-op",3432 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3433{ OPTION_BOOLEAN,0,"binary", &binary,3434 NULL,"old option, now no-op",3435 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3436OPT_BOOLEAN(0,"numstat", &numstat,3437"shows number of added and deleted lines in decimal notation"),3438OPT_BOOLEAN(0,"summary", &summary,3439"instead of applying the patch, output a summary for the input"),3440OPT_BOOLEAN(0,"check", &check,3441"instead of applying the patch, see if the patch is applicable"),3442OPT_BOOLEAN(0,"index", &check_index,3443"make sure the patch is applicable to the current index"),3444OPT_BOOLEAN(0,"cached", &cached,3445"apply a patch without touching the working tree"),3446OPT_BOOLEAN(0,"apply", &force_apply,3447"also apply the patch (use with --stat/--summary/--check)"),3448OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,3449"build a temporary index based on embedded index information"),3450{ OPTION_CALLBACK,'z', NULL, NULL, NULL,3451"paths are separated with NUL character",3452 PARSE_OPT_NOARG, option_parse_z },3453OPT_INTEGER('C', NULL, &p_context,3454"ensure at least <n> lines of context match"),3455{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,"action",3456"detect new or modified lines that have whitespace errors",34570, option_parse_whitespace },3458{ OPTION_CALLBACK,0,"ignore-space-change", NULL, NULL,3459"ignore changes in whitespace when finding context",3460 PARSE_OPT_NOARG, option_parse_space_change },3461{ OPTION_CALLBACK,0,"ignore-whitespace", NULL, NULL,3462"ignore changes in whitespace when finding context",3463 PARSE_OPT_NOARG, option_parse_space_change },3464OPT_BOOLEAN('R',"reverse", &apply_in_reverse,3465"apply the patch in reverse"),3466OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,3467"don't expect at least one line of context"),3468OPT_BOOLEAN(0,"reject", &apply_with_reject,3469"leave the rejected hunks in corresponding *.rej files"),3470OPT__VERBOSE(&apply_verbosely),3471OPT_BIT(0,"inaccurate-eof", &options,3472"tolerate incorrectly detected missing new-line at the end of file",3473 INACCURATE_EOF),3474OPT_BIT(0,"recount", &options,3475"do not trust the line counts in the hunk headers",3476 RECOUNT),3477{ OPTION_CALLBACK,0,"directory", NULL,"root",3478"prepend <root> to all filenames",34790, option_parse_directory },3480OPT_END()3481};34823483 prefix =setup_git_directory_gently(&is_not_gitdir);3484 prefix_length = prefix ?strlen(prefix) :0;3485git_config(git_apply_config, NULL);3486if(apply_default_whitespace)3487parse_whitespace_option(apply_default_whitespace);3488if(apply_default_ignorewhitespace)3489parse_ignorewhitespace_option(apply_default_ignorewhitespace);34903491 argc =parse_options(argc, argv, prefix, builtin_apply_options,3492 apply_usage,0);34933494if(apply_with_reject)3495 apply = apply_verbosely =1;3496if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))3497 apply =0;3498if(check_index && is_not_gitdir)3499die("--index outside a repository");3500if(cached) {3501if(is_not_gitdir)3502die("--cached outside a repository");3503 check_index =1;3504}3505for(i =0; i < argc; i++) {3506const char*arg = argv[i];3507int fd;35083509if(!strcmp(arg,"-")) {3510 errs |=apply_patch(0,"<stdin>", options);3511 read_stdin =0;3512continue;3513}else if(0< prefix_length)3514 arg =prefix_filename(prefix, prefix_length, arg);35153516 fd =open(arg, O_RDONLY);3517if(fd <0)3518die_errno("can't open patch '%s'", arg);3519 read_stdin =0;3520set_default_whitespace_mode(whitespace_option);3521 errs |=apply_patch(fd, arg, options);3522close(fd);3523}3524set_default_whitespace_mode(whitespace_option);3525if(read_stdin)3526 errs |=apply_patch(0,"<stdin>", options);3527if(whitespace_error) {3528if(squelch_whitespace_errors &&3529 squelch_whitespace_errors < whitespace_error) {3530int squelched =3531 whitespace_error - squelch_whitespace_errors;3532warning("squelched%d"3533"whitespace error%s",3534 squelched,3535 squelched ==1?"":"s");3536}3537if(ws_error_action == die_on_ws_error)3538die("%dline%sadd%swhitespace errors.",3539 whitespace_error,3540 whitespace_error ==1?"":"s",3541 whitespace_error ==1?"s":"");3542if(applied_after_fixing_ws && apply)3543warning("%dline%sapplied after"3544" fixing whitespace errors.",3545 applied_after_fixing_ws,3546 applied_after_fixing_ws ==1?"":"s");3547else if(whitespace_error)3548warning("%dline%sadd%swhitespace errors.",3549 whitespace_error,3550 whitespace_error ==1?"":"s",3551 whitespace_error ==1?"s":"");3552}35533554if(update_index) {3555if(write_cache(newfd, active_cache, active_nr) ||3556commit_locked_index(&lock_file))3557die("Unable to write new index file");3558}35593560return!!errs;3561}