1/* 2 * apply.c 3 * 4 * Copyright (C) Linus Torvalds, 2005 5 * 6 * This applies patches on top of some (arbitrary) version of the SCM. 7 * 8 */ 9#include"cache.h" 10#include"cache-tree.h" 11#include"quote.h" 12#include"blob.h" 13#include"delta.h" 14#include"builtin.h" 15#include"string-list.h" 16#include"dir.h" 17#include"parse-options.h" 18 19/* 20 * --check turns on checking that the working tree matches the 21 * files that are being modified, but doesn't apply the patch 22 * --stat does just a diffstat, and doesn't actually apply 23 * --numstat does numeric diffstat, and doesn't actually apply 24 * --index-info shows the old and new index info for paths if available. 25 * --index updates the cache as well. 26 * --cached updates only the cache without ever touching the working tree. 27 */ 28static const char*prefix; 29static int prefix_length = -1; 30static int newfd = -1; 31 32static int unidiff_zero; 33static int p_value =1; 34static int p_value_known; 35static int check_index; 36static int update_index; 37static int cached; 38static int diffstat; 39static int numstat; 40static int summary; 41static int check; 42static int apply =1; 43static int apply_in_reverse; 44static int apply_with_reject; 45static int apply_verbosely; 46static int no_add; 47static const char*fake_ancestor; 48static int line_termination ='\n'; 49static unsigned int p_context = UINT_MAX; 50static const char*const apply_usage[] = { 51"git apply [options] [<patch>...]", 52 NULL 53}; 54 55static enum ws_error_action { 56 nowarn_ws_error, 57 warn_on_ws_error, 58 die_on_ws_error, 59 correct_ws_error, 60} ws_error_action = warn_on_ws_error; 61static int whitespace_error; 62static int squelch_whitespace_errors =5; 63static int applied_after_fixing_ws; 64static const char*patch_input_file; 65static const char*root; 66static int root_len; 67static int read_stdin =1; 68static int options; 69 70static voidparse_whitespace_option(const char*option) 71{ 72if(!option) { 73 ws_error_action = warn_on_ws_error; 74return; 75} 76if(!strcmp(option,"warn")) { 77 ws_error_action = warn_on_ws_error; 78return; 79} 80if(!strcmp(option,"nowarn")) { 81 ws_error_action = nowarn_ws_error; 82return; 83} 84if(!strcmp(option,"error")) { 85 ws_error_action = die_on_ws_error; 86return; 87} 88if(!strcmp(option,"error-all")) { 89 ws_error_action = die_on_ws_error; 90 squelch_whitespace_errors =0; 91return; 92} 93if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 94 ws_error_action = correct_ws_error; 95return; 96} 97die("unrecognized whitespace option '%s'", option); 98} 99 100static voidset_default_whitespace_mode(const char*whitespace_option) 101{ 102if(!whitespace_option && !apply_default_whitespace) 103 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 104} 105 106/* 107 * For "diff-stat" like behaviour, we keep track of the biggest change 108 * we've seen, and the longest filename. That allows us to do simple 109 * scaling. 110 */ 111static int max_change, max_len; 112 113/* 114 * Various "current state", notably line numbers and what 115 * file (and how) we're patching right now.. The "is_xxxx" 116 * things are flags, where -1 means "don't know yet". 117 */ 118static int linenr =1; 119 120/* 121 * This represents one "hunk" from a patch, starting with 122 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 123 * patch text is pointed at by patch, and its byte length 124 * is stored in size. leading and trailing are the number 125 * of context lines. 126 */ 127struct fragment { 128unsigned long leading, trailing; 129unsigned long oldpos, oldlines; 130unsigned long newpos, newlines; 131const char*patch; 132int size; 133int rejected; 134struct fragment *next; 135}; 136 137/* 138 * When dealing with a binary patch, we reuse "leading" field 139 * to store the type of the binary hunk, either deflated "delta" 140 * or deflated "literal". 141 */ 142#define binary_patch_method leading 143#define BINARY_DELTA_DEFLATED 1 144#define BINARY_LITERAL_DEFLATED 2 145 146/* 147 * This represents a "patch" to a file, both metainfo changes 148 * such as creation/deletion, filemode and content changes represented 149 * as a series of fragments. 150 */ 151struct patch { 152char*new_name, *old_name, *def_name; 153unsigned int old_mode, new_mode; 154int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 155int rejected; 156unsigned ws_rule; 157unsigned long deflate_origlen; 158int lines_added, lines_deleted; 159int score; 160unsigned int is_toplevel_relative:1; 161unsigned int inaccurate_eof:1; 162unsigned int is_binary:1; 163unsigned int is_copy:1; 164unsigned int is_rename:1; 165unsigned int recount:1; 166struct fragment *fragments; 167char*result; 168size_t resultsize; 169char old_sha1_prefix[41]; 170char new_sha1_prefix[41]; 171struct patch *next; 172}; 173 174/* 175 * A line in a file, len-bytes long (includes the terminating LF, 176 * except for an incomplete line at the end if the file ends with 177 * one), and its contents hashes to 'hash'. 178 */ 179struct line { 180size_t len; 181unsigned hash :24; 182unsigned flag :8; 183#define LINE_COMMON 1 184}; 185 186/* 187 * This represents a "file", which is an array of "lines". 188 */ 189struct image { 190char*buf; 191size_t len; 192size_t nr; 193size_t alloc; 194struct line *line_allocated; 195struct line *line; 196}; 197 198/* 199 * Records filenames that have been touched, in order to handle 200 * the case where more than one patches touch the same file. 201 */ 202 203static struct string_list fn_table; 204 205static uint32_thash_line(const char*cp,size_t len) 206{ 207size_t i; 208uint32_t h; 209for(i =0, h =0; i < len; i++) { 210if(!isspace(cp[i])) { 211 h = h *3+ (cp[i] &0xff); 212} 213} 214return h; 215} 216 217static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 218{ 219ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 220 img->line_allocated[img->nr].len = len; 221 img->line_allocated[img->nr].hash =hash_line(bol, len); 222 img->line_allocated[img->nr].flag = flag; 223 img->nr++; 224} 225 226static voidprepare_image(struct image *image,char*buf,size_t len, 227int prepare_linetable) 228{ 229const char*cp, *ep; 230 231memset(image,0,sizeof(*image)); 232 image->buf = buf; 233 image->len = len; 234 235if(!prepare_linetable) 236return; 237 238 ep = image->buf + image->len; 239 cp = image->buf; 240while(cp < ep) { 241const char*next; 242for(next = cp; next < ep && *next !='\n'; next++) 243; 244if(next < ep) 245 next++; 246add_line_info(image, cp, next - cp,0); 247 cp = next; 248} 249 image->line = image->line_allocated; 250} 251 252static voidclear_image(struct image *image) 253{ 254free(image->buf); 255 image->buf = NULL; 256 image->len =0; 257} 258 259static voidsay_patch_name(FILE*output,const char*pre, 260struct patch *patch,const char*post) 261{ 262fputs(pre, output); 263if(patch->old_name && patch->new_name && 264strcmp(patch->old_name, patch->new_name)) { 265quote_c_style(patch->old_name, NULL, output,0); 266fputs(" => ", output); 267quote_c_style(patch->new_name, NULL, output,0); 268}else{ 269const char*n = patch->new_name; 270if(!n) 271 n = patch->old_name; 272quote_c_style(n, NULL, output,0); 273} 274fputs(post, output); 275} 276 277#define CHUNKSIZE (8192) 278#define SLOP (16) 279 280static voidread_patch_file(struct strbuf *sb,int fd) 281{ 282if(strbuf_read(sb, fd,0) <0) 283die_errno("git apply: failed to read"); 284 285/* 286 * Make sure that we have some slop in the buffer 287 * so that we can do speculative "memcmp" etc, and 288 * see to it that it is NUL-filled. 289 */ 290strbuf_grow(sb, SLOP); 291memset(sb->buf + sb->len,0, SLOP); 292} 293 294static unsigned longlinelen(const char*buffer,unsigned long size) 295{ 296unsigned long len =0; 297while(size--) { 298 len++; 299if(*buffer++ =='\n') 300break; 301} 302return len; 303} 304 305static intis_dev_null(const char*str) 306{ 307return!memcmp("/dev/null", str,9) &&isspace(str[9]); 308} 309 310#define TERM_SPACE 1 311#define TERM_TAB 2 312 313static intname_terminate(const char*name,int namelen,int c,int terminate) 314{ 315if(c ==' '&& !(terminate & TERM_SPACE)) 316return0; 317if(c =='\t'&& !(terminate & TERM_TAB)) 318return0; 319 320return1; 321} 322 323/* remove double slashes to make --index work with such filenames */ 324static char*squash_slash(char*name) 325{ 326int i =0, j =0; 327 328while(name[i]) { 329if((name[j++] = name[i++]) =='/') 330while(name[i] =='/') 331 i++; 332} 333 name[j] ='\0'; 334return name; 335} 336 337static char*find_name(const char*line,char*def,int p_value,int terminate) 338{ 339int len; 340const char*start = line; 341 342if(*line =='"') { 343struct strbuf name = STRBUF_INIT; 344 345/* 346 * Proposed "new-style" GNU patch/diff format; see 347 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2 348 */ 349if(!unquote_c_style(&name, line, NULL)) { 350char*cp; 351 352for(cp = name.buf; p_value; p_value--) { 353 cp =strchr(cp,'/'); 354if(!cp) 355break; 356 cp++; 357} 358if(cp) { 359/* name can later be freed, so we need 360 * to memmove, not just return cp 361 */ 362strbuf_remove(&name,0, cp - name.buf); 363free(def); 364if(root) 365strbuf_insert(&name,0, root, root_len); 366returnsquash_slash(strbuf_detach(&name, NULL)); 367} 368} 369strbuf_release(&name); 370} 371 372for(;;) { 373char c = *line; 374 375if(isspace(c)) { 376if(c =='\n') 377break; 378if(name_terminate(start, line-start, c, terminate)) 379break; 380} 381 line++; 382if(c =='/'&& !--p_value) 383 start = line; 384} 385if(!start) 386returnsquash_slash(def); 387 len = line - start; 388if(!len) 389returnsquash_slash(def); 390 391/* 392 * Generally we prefer the shorter name, especially 393 * if the other one is just a variation of that with 394 * something else tacked on to the end (ie "file.orig" 395 * or "file~"). 396 */ 397if(def) { 398int deflen =strlen(def); 399if(deflen < len && !strncmp(start, def, deflen)) 400returnsquash_slash(def); 401free(def); 402} 403 404if(root) { 405char*ret =xmalloc(root_len + len +1); 406strcpy(ret, root); 407memcpy(ret + root_len, start, len); 408 ret[root_len + len] ='\0'; 409returnsquash_slash(ret); 410} 411 412returnsquash_slash(xmemdupz(start, len)); 413} 414 415static intcount_slashes(const char*cp) 416{ 417int cnt =0; 418char ch; 419 420while((ch = *cp++)) 421if(ch =='/') 422 cnt++; 423return cnt; 424} 425 426/* 427 * Given the string after "--- " or "+++ ", guess the appropriate 428 * p_value for the given patch. 429 */ 430static intguess_p_value(const char*nameline) 431{ 432char*name, *cp; 433int val = -1; 434 435if(is_dev_null(nameline)) 436return-1; 437 name =find_name(nameline, NULL,0, TERM_SPACE | TERM_TAB); 438if(!name) 439return-1; 440 cp =strchr(name,'/'); 441if(!cp) 442 val =0; 443else if(prefix) { 444/* 445 * Does it begin with "a/$our-prefix" and such? Then this is 446 * very likely to apply to our directory. 447 */ 448if(!strncmp(name, prefix, prefix_length)) 449 val =count_slashes(prefix); 450else{ 451 cp++; 452if(!strncmp(cp, prefix, prefix_length)) 453 val =count_slashes(prefix) +1; 454} 455} 456free(name); 457return val; 458} 459 460/* 461 * Does the ---/+++ line has the POSIX timestamp after the last HT? 462 * GNU diff puts epoch there to signal a creation/deletion event. Is 463 * this such a timestamp? 464 */ 465static inthas_epoch_timestamp(const char*nameline) 466{ 467/* 468 * We are only interested in epoch timestamp; any non-zero 469 * fraction cannot be one, hence "(\.0+)?" in the regexp below. 470 * For the same reason, the date must be either 1969-12-31 or 471 * 1970-01-01, and the seconds part must be "00". 472 */ 473const char stamp_regexp[] = 474"^(1969-12-31|1970-01-01)" 475" " 476"[0-2][0-9]:[0-5][0-9]:00(\\.0+)?" 477" " 478"([-+][0-2][0-9][0-5][0-9])\n"; 479const char*timestamp = NULL, *cp; 480static regex_t *stamp; 481 regmatch_t m[10]; 482int zoneoffset; 483int hourminute; 484int status; 485 486for(cp = nameline; *cp !='\n'; cp++) { 487if(*cp =='\t') 488 timestamp = cp +1; 489} 490if(!timestamp) 491return0; 492if(!stamp) { 493 stamp =xmalloc(sizeof(*stamp)); 494if(regcomp(stamp, stamp_regexp, REG_EXTENDED)) { 495warning("Cannot prepare timestamp regexp%s", 496 stamp_regexp); 497return0; 498} 499} 500 501 status =regexec(stamp, timestamp,ARRAY_SIZE(m), m,0); 502if(status) { 503if(status != REG_NOMATCH) 504warning("regexec returned%dfor input:%s", 505 status, timestamp); 506return0; 507} 508 509 zoneoffset =strtol(timestamp + m[3].rm_so +1, NULL,10); 510 zoneoffset = (zoneoffset /100) *60+ (zoneoffset %100); 511if(timestamp[m[3].rm_so] =='-') 512 zoneoffset = -zoneoffset; 513 514/* 515 * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31 516 * (west of GMT) or 1970-01-01 (east of GMT) 517 */ 518if((zoneoffset <0&&memcmp(timestamp,"1969-12-31",10)) || 519(0<= zoneoffset &&memcmp(timestamp,"1970-01-01",10))) 520return0; 521 522 hourminute = (strtol(timestamp +11, NULL,10) *60+ 523strtol(timestamp +14, NULL,10) - 524 zoneoffset); 525 526return((zoneoffset <0&& hourminute ==1440) || 527(0<= zoneoffset && !hourminute)); 528} 529 530/* 531 * Get the name etc info from the ---/+++ lines of a traditional patch header 532 * 533 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 534 * files, we can happily check the index for a match, but for creating a 535 * new file we should try to match whatever "patch" does. I have no idea. 536 */ 537static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 538{ 539char*name; 540 541 first +=4;/* skip "--- " */ 542 second +=4;/* skip "+++ " */ 543if(!p_value_known) { 544int p, q; 545 p =guess_p_value(first); 546 q =guess_p_value(second); 547if(p <0) p = q; 548if(0<= p && p == q) { 549 p_value = p; 550 p_value_known =1; 551} 552} 553if(is_dev_null(first)) { 554 patch->is_new =1; 555 patch->is_delete =0; 556 name =find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB); 557 patch->new_name = name; 558}else if(is_dev_null(second)) { 559 patch->is_new =0; 560 patch->is_delete =1; 561 name =find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB); 562 patch->old_name = name; 563}else{ 564 name =find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB); 565 name =find_name(second, name, p_value, TERM_SPACE | TERM_TAB); 566if(has_epoch_timestamp(first)) { 567 patch->is_new =1; 568 patch->is_delete =0; 569 patch->new_name = name; 570}else if(has_epoch_timestamp(second)) { 571 patch->is_new =0; 572 patch->is_delete =1; 573 patch->old_name = name; 574}else{ 575 patch->old_name = patch->new_name = name; 576} 577} 578if(!name) 579die("unable to find filename in patch at line%d", linenr); 580} 581 582static intgitdiff_hdrend(const char*line,struct patch *patch) 583{ 584return-1; 585} 586 587/* 588 * We're anal about diff header consistency, to make 589 * sure that we don't end up having strange ambiguous 590 * patches floating around. 591 * 592 * As a result, gitdiff_{old|new}name() will check 593 * their names against any previous information, just 594 * to make sure.. 595 */ 596static char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,const char*oldnew) 597{ 598if(!orig_name && !isnull) 599returnfind_name(line, NULL, p_value, TERM_TAB); 600 601if(orig_name) { 602int len; 603const char*name; 604char*another; 605 name = orig_name; 606 len =strlen(name); 607if(isnull) 608die("git apply: bad git-diff - expected /dev/null, got%son line%d", name, linenr); 609 another =find_name(line, NULL, p_value, TERM_TAB); 610if(!another ||memcmp(another, name, len)) 611die("git apply: bad git-diff - inconsistent%sfilename on line%d", oldnew, linenr); 612free(another); 613return orig_name; 614} 615else{ 616/* expect "/dev/null" */ 617if(memcmp("/dev/null", line,9) || line[9] !='\n') 618die("git apply: bad git-diff - expected /dev/null on line%d", linenr); 619return NULL; 620} 621} 622 623static intgitdiff_oldname(const char*line,struct patch *patch) 624{ 625 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name,"old"); 626return0; 627} 628 629static intgitdiff_newname(const char*line,struct patch *patch) 630{ 631 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name,"new"); 632return0; 633} 634 635static intgitdiff_oldmode(const char*line,struct patch *patch) 636{ 637 patch->old_mode =strtoul(line, NULL,8); 638return0; 639} 640 641static intgitdiff_newmode(const char*line,struct patch *patch) 642{ 643 patch->new_mode =strtoul(line, NULL,8); 644return0; 645} 646 647static intgitdiff_delete(const char*line,struct patch *patch) 648{ 649 patch->is_delete =1; 650 patch->old_name = patch->def_name; 651returngitdiff_oldmode(line, patch); 652} 653 654static intgitdiff_newfile(const char*line,struct patch *patch) 655{ 656 patch->is_new =1; 657 patch->new_name = patch->def_name; 658returngitdiff_newmode(line, patch); 659} 660 661static intgitdiff_copysrc(const char*line,struct patch *patch) 662{ 663 patch->is_copy =1; 664 patch->old_name =find_name(line, NULL,0,0); 665return0; 666} 667 668static intgitdiff_copydst(const char*line,struct patch *patch) 669{ 670 patch->is_copy =1; 671 patch->new_name =find_name(line, NULL,0,0); 672return0; 673} 674 675static intgitdiff_renamesrc(const char*line,struct patch *patch) 676{ 677 patch->is_rename =1; 678 patch->old_name =find_name(line, NULL,0,0); 679return0; 680} 681 682static intgitdiff_renamedst(const char*line,struct patch *patch) 683{ 684 patch->is_rename =1; 685 patch->new_name =find_name(line, NULL,0,0); 686return0; 687} 688 689static intgitdiff_similarity(const char*line,struct patch *patch) 690{ 691if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 692 patch->score =0; 693return0; 694} 695 696static intgitdiff_dissimilarity(const char*line,struct patch *patch) 697{ 698if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 699 patch->score =0; 700return0; 701} 702 703static intgitdiff_index(const char*line,struct patch *patch) 704{ 705/* 706 * index line is N hexadecimal, "..", N hexadecimal, 707 * and optional space with octal mode. 708 */ 709const char*ptr, *eol; 710int len; 711 712 ptr =strchr(line,'.'); 713if(!ptr || ptr[1] !='.'||40< ptr - line) 714return0; 715 len = ptr - line; 716memcpy(patch->old_sha1_prefix, line, len); 717 patch->old_sha1_prefix[len] =0; 718 719 line = ptr +2; 720 ptr =strchr(line,' '); 721 eol =strchr(line,'\n'); 722 723if(!ptr || eol < ptr) 724 ptr = eol; 725 len = ptr - line; 726 727if(40< len) 728return0; 729memcpy(patch->new_sha1_prefix, line, len); 730 patch->new_sha1_prefix[len] =0; 731if(*ptr ==' ') 732 patch->old_mode =strtoul(ptr+1, NULL,8); 733return0; 734} 735 736/* 737 * This is normal for a diff that doesn't change anything: we'll fall through 738 * into the next diff. Tell the parser to break out. 739 */ 740static intgitdiff_unrecognized(const char*line,struct patch *patch) 741{ 742return-1; 743} 744 745static const char*stop_at_slash(const char*line,int llen) 746{ 747int i; 748 749for(i =0; i < llen; i++) { 750int ch = line[i]; 751if(ch =='/') 752return line + i; 753} 754return NULL; 755} 756 757/* 758 * This is to extract the same name that appears on "diff --git" 759 * line. We do not find and return anything if it is a rename 760 * patch, and it is OK because we will find the name elsewhere. 761 * We need to reliably find name only when it is mode-change only, 762 * creation or deletion of an empty file. In any of these cases, 763 * both sides are the same name under a/ and b/ respectively. 764 */ 765static char*git_header_name(char*line,int llen) 766{ 767const char*name; 768const char*second = NULL; 769size_t len; 770 771 line +=strlen("diff --git "); 772 llen -=strlen("diff --git "); 773 774if(*line =='"') { 775const char*cp; 776struct strbuf first = STRBUF_INIT; 777struct strbuf sp = STRBUF_INIT; 778 779if(unquote_c_style(&first, line, &second)) 780goto free_and_fail1; 781 782/* advance to the first slash */ 783 cp =stop_at_slash(first.buf, first.len); 784/* we do not accept absolute paths */ 785if(!cp || cp == first.buf) 786goto free_and_fail1; 787strbuf_remove(&first,0, cp +1- first.buf); 788 789/* 790 * second points at one past closing dq of name. 791 * find the second name. 792 */ 793while((second < line + llen) &&isspace(*second)) 794 second++; 795 796if(line + llen <= second) 797goto free_and_fail1; 798if(*second =='"') { 799if(unquote_c_style(&sp, second, NULL)) 800goto free_and_fail1; 801 cp =stop_at_slash(sp.buf, sp.len); 802if(!cp || cp == sp.buf) 803goto free_and_fail1; 804/* They must match, otherwise ignore */ 805if(strcmp(cp +1, first.buf)) 806goto free_and_fail1; 807strbuf_release(&sp); 808returnstrbuf_detach(&first, NULL); 809} 810 811/* unquoted second */ 812 cp =stop_at_slash(second, line + llen - second); 813if(!cp || cp == second) 814goto free_and_fail1; 815 cp++; 816if(line + llen - cp != first.len +1|| 817memcmp(first.buf, cp, first.len)) 818goto free_and_fail1; 819returnstrbuf_detach(&first, NULL); 820 821 free_and_fail1: 822strbuf_release(&first); 823strbuf_release(&sp); 824return NULL; 825} 826 827/* unquoted first name */ 828 name =stop_at_slash(line, llen); 829if(!name || name == line) 830return NULL; 831 name++; 832 833/* 834 * since the first name is unquoted, a dq if exists must be 835 * the beginning of the second name. 836 */ 837for(second = name; second < line + llen; second++) { 838if(*second =='"') { 839struct strbuf sp = STRBUF_INIT; 840const char*np; 841 842if(unquote_c_style(&sp, second, NULL)) 843goto free_and_fail2; 844 845 np =stop_at_slash(sp.buf, sp.len); 846if(!np || np == sp.buf) 847goto free_and_fail2; 848 np++; 849 850 len = sp.buf + sp.len - np; 851if(len < second - name && 852!strncmp(np, name, len) && 853isspace(name[len])) { 854/* Good */ 855strbuf_remove(&sp,0, np - sp.buf); 856returnstrbuf_detach(&sp, NULL); 857} 858 859 free_and_fail2: 860strbuf_release(&sp); 861return NULL; 862} 863} 864 865/* 866 * Accept a name only if it shows up twice, exactly the same 867 * form. 868 */ 869for(len =0; ; len++) { 870switch(name[len]) { 871default: 872continue; 873case'\n': 874return NULL; 875case'\t':case' ': 876 second = name+len; 877for(;;) { 878char c = *second++; 879if(c =='\n') 880return NULL; 881if(c =='/') 882break; 883} 884if(second[len] =='\n'&& !memcmp(name, second, len)) { 885returnxmemdupz(name, len); 886} 887} 888} 889} 890 891/* Verify that we recognize the lines following a git header */ 892static intparse_git_header(char*line,int len,unsigned int size,struct patch *patch) 893{ 894unsigned long offset; 895 896/* A git diff has explicit new/delete information, so we don't guess */ 897 patch->is_new =0; 898 patch->is_delete =0; 899 900/* 901 * Some things may not have the old name in the 902 * rest of the headers anywhere (pure mode changes, 903 * or removing or adding empty files), so we get 904 * the default name from the header. 905 */ 906 patch->def_name =git_header_name(line, len); 907if(patch->def_name && root) { 908char*s =xmalloc(root_len +strlen(patch->def_name) +1); 909strcpy(s, root); 910strcpy(s + root_len, patch->def_name); 911free(patch->def_name); 912 patch->def_name = s; 913} 914 915 line += len; 916 size -= len; 917 linenr++; 918for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) { 919static const struct opentry { 920const char*str; 921int(*fn)(const char*,struct patch *); 922} optable[] = { 923{"@@ -", gitdiff_hdrend }, 924{"--- ", gitdiff_oldname }, 925{"+++ ", gitdiff_newname }, 926{"old mode ", gitdiff_oldmode }, 927{"new mode ", gitdiff_newmode }, 928{"deleted file mode ", gitdiff_delete }, 929{"new file mode ", gitdiff_newfile }, 930{"copy from ", gitdiff_copysrc }, 931{"copy to ", gitdiff_copydst }, 932{"rename old ", gitdiff_renamesrc }, 933{"rename new ", gitdiff_renamedst }, 934{"rename from ", gitdiff_renamesrc }, 935{"rename to ", gitdiff_renamedst }, 936{"similarity index ", gitdiff_similarity }, 937{"dissimilarity index ", gitdiff_dissimilarity }, 938{"index ", gitdiff_index }, 939{"", gitdiff_unrecognized }, 940}; 941int i; 942 943 len =linelen(line, size); 944if(!len || line[len-1] !='\n') 945break; 946for(i =0; i <ARRAY_SIZE(optable); i++) { 947const struct opentry *p = optable + i; 948int oplen =strlen(p->str); 949if(len < oplen ||memcmp(p->str, line, oplen)) 950continue; 951if(p->fn(line + oplen, patch) <0) 952return offset; 953break; 954} 955} 956 957return offset; 958} 959 960static intparse_num(const char*line,unsigned long*p) 961{ 962char*ptr; 963 964if(!isdigit(*line)) 965return0; 966*p =strtoul(line, &ptr,10); 967return ptr - line; 968} 969 970static intparse_range(const char*line,int len,int offset,const char*expect, 971unsigned long*p1,unsigned long*p2) 972{ 973int digits, ex; 974 975if(offset <0|| offset >= len) 976return-1; 977 line += offset; 978 len -= offset; 979 980 digits =parse_num(line, p1); 981if(!digits) 982return-1; 983 984 offset += digits; 985 line += digits; 986 len -= digits; 987 988*p2 =1; 989if(*line ==',') { 990 digits =parse_num(line+1, p2); 991if(!digits) 992return-1; 993 994 offset += digits+1; 995 line += digits+1; 996 len -= digits+1; 997} 998 999 ex =strlen(expect);1000if(ex > len)1001return-1;1002if(memcmp(line, expect, ex))1003return-1;10041005return offset + ex;1006}10071008static voidrecount_diff(char*line,int size,struct fragment *fragment)1009{1010int oldlines =0, newlines =0, ret =0;10111012if(size <1) {1013warning("recount: ignore empty hunk");1014return;1015}10161017for(;;) {1018int len =linelen(line, size);1019 size -= len;1020 line += len;10211022if(size <1)1023break;10241025switch(*line) {1026case' ':case'\n':1027 newlines++;1028/* fall through */1029case'-':1030 oldlines++;1031continue;1032case'+':1033 newlines++;1034continue;1035case'\\':1036continue;1037case'@':1038 ret = size <3||prefixcmp(line,"@@ ");1039break;1040case'd':1041 ret = size <5||prefixcmp(line,"diff ");1042break;1043default:1044 ret = -1;1045break;1046}1047if(ret) {1048warning("recount: unexpected line: %.*s",1049(int)linelen(line, size), line);1050return;1051}1052break;1053}1054 fragment->oldlines = oldlines;1055 fragment->newlines = newlines;1056}10571058/*1059 * Parse a unified diff fragment header of the1060 * form "@@ -a,b +c,d @@"1061 */1062static intparse_fragment_header(char*line,int len,struct fragment *fragment)1063{1064int offset;10651066if(!len || line[len-1] !='\n')1067return-1;10681069/* Figure out the number of lines in a fragment */1070 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines);1071 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines);10721073return offset;1074}10751076static intfind_header(char*line,unsigned long size,int*hdrsize,struct patch *patch)1077{1078unsigned long offset, len;10791080 patch->is_toplevel_relative =0;1081 patch->is_rename = patch->is_copy =0;1082 patch->is_new = patch->is_delete = -1;1083 patch->old_mode = patch->new_mode =0;1084 patch->old_name = patch->new_name = NULL;1085for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) {1086unsigned long nextlen;10871088 len =linelen(line, size);1089if(!len)1090break;10911092/* Testing this early allows us to take a few shortcuts.. */1093if(len <6)1094continue;10951096/*1097 * Make sure we don't find any unconnected patch fragments.1098 * That's a sign that we didn't find a header, and that a1099 * patch has become corrupted/broken up.1100 */1101if(!memcmp("@@ -", line,4)) {1102struct fragment dummy;1103if(parse_fragment_header(line, len, &dummy) <0)1104continue;1105die("patch fragment without header at line%d: %.*s",1106 linenr, (int)len-1, line);1107}11081109if(size < len +6)1110break;11111112/*1113 * Git patch? It might not have a real patch, just a rename1114 * or mode change, so we handle that specially1115 */1116if(!memcmp("diff --git ", line,11)) {1117int git_hdr_len =parse_git_header(line, len, size, patch);1118if(git_hdr_len <= len)1119continue;1120if(!patch->old_name && !patch->new_name) {1121if(!patch->def_name)1122die("git diff header lacks filename information (line%d)", linenr);1123 patch->old_name = patch->new_name = patch->def_name;1124}1125 patch->is_toplevel_relative =1;1126*hdrsize = git_hdr_len;1127return offset;1128}11291130/* --- followed by +++ ? */1131if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1132continue;11331134/*1135 * We only accept unified patches, so we want it to1136 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1137 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1138 */1139 nextlen =linelen(line + len, size - len);1140if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1141continue;11421143/* Ok, we'll consider it a patch */1144parse_traditional_patch(line, line+len, patch);1145*hdrsize = len + nextlen;1146 linenr +=2;1147return offset;1148}1149return-1;1150}11511152static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1153{1154char*err;1155unsigned result =ws_check(line +1, len -1, ws_rule);1156if(!result)1157return;11581159 whitespace_error++;1160if(squelch_whitespace_errors &&1161 squelch_whitespace_errors < whitespace_error)1162;1163else{1164 err =whitespace_error_string(result);1165fprintf(stderr,"%s:%d:%s.\n%.*s\n",1166 patch_input_file, linenr, err, len -2, line +1);1167free(err);1168}1169}11701171/*1172 * Parse a unified diff. Note that this really needs to parse each1173 * fragment separately, since the only way to know the difference1174 * between a "---" that is part of a patch, and a "---" that starts1175 * the next patch is to look at the line counts..1176 */1177static intparse_fragment(char*line,unsigned long size,1178struct patch *patch,struct fragment *fragment)1179{1180int added, deleted;1181int len =linelen(line, size), offset;1182unsigned long oldlines, newlines;1183unsigned long leading, trailing;11841185 offset =parse_fragment_header(line, len, fragment);1186if(offset <0)1187return-1;1188if(offset >0&& patch->recount)1189recount_diff(line + offset, size - offset, fragment);1190 oldlines = fragment->oldlines;1191 newlines = fragment->newlines;1192 leading =0;1193 trailing =0;11941195/* Parse the thing.. */1196 line += len;1197 size -= len;1198 linenr++;1199 added = deleted =0;1200for(offset = len;12010< size;1202 offset += len, size -= len, line += len, linenr++) {1203if(!oldlines && !newlines)1204break;1205 len =linelen(line, size);1206if(!len || line[len-1] !='\n')1207return-1;1208switch(*line) {1209default:1210return-1;1211case'\n':/* newer GNU diff, an empty context line */1212case' ':1213 oldlines--;1214 newlines--;1215if(!deleted && !added)1216 leading++;1217 trailing++;1218break;1219case'-':1220if(apply_in_reverse &&1221 ws_error_action != nowarn_ws_error)1222check_whitespace(line, len, patch->ws_rule);1223 deleted++;1224 oldlines--;1225 trailing =0;1226break;1227case'+':1228if(!apply_in_reverse &&1229 ws_error_action != nowarn_ws_error)1230check_whitespace(line, len, patch->ws_rule);1231 added++;1232 newlines--;1233 trailing =0;1234break;12351236/*1237 * We allow "\ No newline at end of file". Depending1238 * on locale settings when the patch was produced we1239 * don't know what this line looks like. The only1240 * thing we do know is that it begins with "\ ".1241 * Checking for 12 is just for sanity check -- any1242 * l10n of "\ No newline..." is at least that long.1243 */1244case'\\':1245if(len <12||memcmp(line,"\\",2))1246return-1;1247break;1248}1249}1250if(oldlines || newlines)1251return-1;1252 fragment->leading = leading;1253 fragment->trailing = trailing;12541255/*1256 * If a fragment ends with an incomplete line, we failed to include1257 * it in the above loop because we hit oldlines == newlines == 01258 * before seeing it.1259 */1260if(12< size && !memcmp(line,"\\",2))1261 offset +=linelen(line, size);12621263 patch->lines_added += added;1264 patch->lines_deleted += deleted;12651266if(0< patch->is_new && oldlines)1267returnerror("new file depends on old contents");1268if(0< patch->is_delete && newlines)1269returnerror("deleted file still has contents");1270return offset;1271}12721273static intparse_single_patch(char*line,unsigned long size,struct patch *patch)1274{1275unsigned long offset =0;1276unsigned long oldlines =0, newlines =0, context =0;1277struct fragment **fragp = &patch->fragments;12781279while(size >4&& !memcmp(line,"@@ -",4)) {1280struct fragment *fragment;1281int len;12821283 fragment =xcalloc(1,sizeof(*fragment));1284 len =parse_fragment(line, size, patch, fragment);1285if(len <=0)1286die("corrupt patch at line%d", linenr);1287 fragment->patch = line;1288 fragment->size = len;1289 oldlines += fragment->oldlines;1290 newlines += fragment->newlines;1291 context += fragment->leading + fragment->trailing;12921293*fragp = fragment;1294 fragp = &fragment->next;12951296 offset += len;1297 line += len;1298 size -= len;1299}13001301/*1302 * If something was removed (i.e. we have old-lines) it cannot1303 * be creation, and if something was added it cannot be1304 * deletion. However, the reverse is not true; --unified=01305 * patches that only add are not necessarily creation even1306 * though they do not have any old lines, and ones that only1307 * delete are not necessarily deletion.1308 *1309 * Unfortunately, a real creation/deletion patch do _not_ have1310 * any context line by definition, so we cannot safely tell it1311 * apart with --unified=0 insanity. At least if the patch has1312 * more than one hunk it is not creation or deletion.1313 */1314if(patch->is_new <0&&1315(oldlines || (patch->fragments && patch->fragments->next)))1316 patch->is_new =0;1317if(patch->is_delete <0&&1318(newlines || (patch->fragments && patch->fragments->next)))1319 patch->is_delete =0;13201321if(0< patch->is_new && oldlines)1322die("new file%sdepends on old contents", patch->new_name);1323if(0< patch->is_delete && newlines)1324die("deleted file%sstill has contents", patch->old_name);1325if(!patch->is_delete && !newlines && context)1326fprintf(stderr,"** warning: file%sbecomes empty but "1327"is not deleted\n", patch->new_name);13281329return offset;1330}13311332staticinlineintmetadata_changes(struct patch *patch)1333{1334return patch->is_rename >0||1335 patch->is_copy >0||1336 patch->is_new >0||1337 patch->is_delete ||1338(patch->old_mode && patch->new_mode &&1339 patch->old_mode != patch->new_mode);1340}13411342static char*inflate_it(const void*data,unsigned long size,1343unsigned long inflated_size)1344{1345 z_stream stream;1346void*out;1347int st;13481349memset(&stream,0,sizeof(stream));13501351 stream.next_in = (unsigned char*)data;1352 stream.avail_in = size;1353 stream.next_out = out =xmalloc(inflated_size);1354 stream.avail_out = inflated_size;1355git_inflate_init(&stream);1356 st =git_inflate(&stream, Z_FINISH);1357git_inflate_end(&stream);1358if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1359free(out);1360return NULL;1361}1362return out;1363}13641365static struct fragment *parse_binary_hunk(char**buf_p,1366unsigned long*sz_p,1367int*status_p,1368int*used_p)1369{1370/*1371 * Expect a line that begins with binary patch method ("literal"1372 * or "delta"), followed by the length of data before deflating.1373 * a sequence of 'length-byte' followed by base-85 encoded data1374 * should follow, terminated by a newline.1375 *1376 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1377 * and we would limit the patch line to 66 characters,1378 * so one line can fit up to 13 groups that would decode1379 * to 52 bytes max. The length byte 'A'-'Z' corresponds1380 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1381 */1382int llen, used;1383unsigned long size = *sz_p;1384char*buffer = *buf_p;1385int patch_method;1386unsigned long origlen;1387char*data = NULL;1388int hunk_size =0;1389struct fragment *frag;13901391 llen =linelen(buffer, size);1392 used = llen;13931394*status_p =0;13951396if(!prefixcmp(buffer,"delta ")) {1397 patch_method = BINARY_DELTA_DEFLATED;1398 origlen =strtoul(buffer +6, NULL,10);1399}1400else if(!prefixcmp(buffer,"literal ")) {1401 patch_method = BINARY_LITERAL_DEFLATED;1402 origlen =strtoul(buffer +8, NULL,10);1403}1404else1405return NULL;14061407 linenr++;1408 buffer += llen;1409while(1) {1410int byte_length, max_byte_length, newsize;1411 llen =linelen(buffer, size);1412 used += llen;1413 linenr++;1414if(llen ==1) {1415/* consume the blank line */1416 buffer++;1417 size--;1418break;1419}1420/*1421 * Minimum line is "A00000\n" which is 7-byte long,1422 * and the line length must be multiple of 5 plus 2.1423 */1424if((llen <7) || (llen-2) %5)1425goto corrupt;1426 max_byte_length = (llen -2) /5*4;1427 byte_length = *buffer;1428if('A'<= byte_length && byte_length <='Z')1429 byte_length = byte_length -'A'+1;1430else if('a'<= byte_length && byte_length <='z')1431 byte_length = byte_length -'a'+27;1432else1433goto corrupt;1434/* if the input length was not multiple of 4, we would1435 * have filler at the end but the filler should never1436 * exceed 3 bytes1437 */1438if(max_byte_length < byte_length ||1439 byte_length <= max_byte_length -4)1440goto corrupt;1441 newsize = hunk_size + byte_length;1442 data =xrealloc(data, newsize);1443if(decode_85(data + hunk_size, buffer +1, byte_length))1444goto corrupt;1445 hunk_size = newsize;1446 buffer += llen;1447 size -= llen;1448}14491450 frag =xcalloc(1,sizeof(*frag));1451 frag->patch =inflate_it(data, hunk_size, origlen);1452if(!frag->patch)1453goto corrupt;1454free(data);1455 frag->size = origlen;1456*buf_p = buffer;1457*sz_p = size;1458*used_p = used;1459 frag->binary_patch_method = patch_method;1460return frag;14611462 corrupt:1463free(data);1464*status_p = -1;1465error("corrupt binary patch at line%d: %.*s",1466 linenr-1, llen-1, buffer);1467return NULL;1468}14691470static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1471{1472/*1473 * We have read "GIT binary patch\n"; what follows is a line1474 * that says the patch method (currently, either "literal" or1475 * "delta") and the length of data before deflating; a1476 * sequence of 'length-byte' followed by base-85 encoded data1477 * follows.1478 *1479 * When a binary patch is reversible, there is another binary1480 * hunk in the same format, starting with patch method (either1481 * "literal" or "delta") with the length of data, and a sequence1482 * of length-byte + base-85 encoded data, terminated with another1483 * empty line. This data, when applied to the postimage, produces1484 * the preimage.1485 */1486struct fragment *forward;1487struct fragment *reverse;1488int status;1489int used, used_1;14901491 forward =parse_binary_hunk(&buffer, &size, &status, &used);1492if(!forward && !status)1493/* there has to be one hunk (forward hunk) */1494returnerror("unrecognized binary patch at line%d", linenr-1);1495if(status)1496/* otherwise we already gave an error message */1497return status;14981499 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1500if(reverse)1501 used += used_1;1502else if(status) {1503/*1504 * Not having reverse hunk is not an error, but having1505 * a corrupt reverse hunk is.1506 */1507free((void*) forward->patch);1508free(forward);1509return status;1510}1511 forward->next = reverse;1512 patch->fragments = forward;1513 patch->is_binary =1;1514return used;1515}15161517static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1518{1519int hdrsize, patchsize;1520int offset =find_header(buffer, size, &hdrsize, patch);15211522if(offset <0)1523return offset;15241525 patch->ws_rule =whitespace_rule(patch->new_name1526? patch->new_name1527: patch->old_name);15281529 patchsize =parse_single_patch(buffer + offset + hdrsize,1530 size - offset - hdrsize, patch);15311532if(!patchsize) {1533static const char*binhdr[] = {1534"Binary files ",1535"Files ",1536 NULL,1537};1538static const char git_binary[] ="GIT binary patch\n";1539int i;1540int hd = hdrsize + offset;1541unsigned long llen =linelen(buffer + hd, size - hd);15421543if(llen ==sizeof(git_binary) -1&&1544!memcmp(git_binary, buffer + hd, llen)) {1545int used;1546 linenr++;1547 used =parse_binary(buffer + hd + llen,1548 size - hd - llen, patch);1549if(used)1550 patchsize = used + llen;1551else1552 patchsize =0;1553}1554else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1555for(i =0; binhdr[i]; i++) {1556int len =strlen(binhdr[i]);1557if(len < size - hd &&1558!memcmp(binhdr[i], buffer + hd, len)) {1559 linenr++;1560 patch->is_binary =1;1561 patchsize = llen;1562break;1563}1564}1565}15661567/* Empty patch cannot be applied if it is a text patch1568 * without metadata change. A binary patch appears1569 * empty to us here.1570 */1571if((apply || check) &&1572(!patch->is_binary && !metadata_changes(patch)))1573die("patch with only garbage at line%d", linenr);1574}15751576return offset + hdrsize + patchsize;1577}15781579#define swap(a,b) myswap((a),(b),sizeof(a))15801581#define myswap(a, b, size) do { \1582 unsigned char mytmp[size]; \1583 memcpy(mytmp, &a, size); \1584 memcpy(&a, &b, size); \1585 memcpy(&b, mytmp, size); \1586} while (0)15871588static voidreverse_patches(struct patch *p)1589{1590for(; p; p = p->next) {1591struct fragment *frag = p->fragments;15921593swap(p->new_name, p->old_name);1594swap(p->new_mode, p->old_mode);1595swap(p->is_new, p->is_delete);1596swap(p->lines_added, p->lines_deleted);1597swap(p->old_sha1_prefix, p->new_sha1_prefix);15981599for(; frag; frag = frag->next) {1600swap(frag->newpos, frag->oldpos);1601swap(frag->newlines, frag->oldlines);1602}1603}1604}16051606static const char pluses[] =1607"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";1608static const char minuses[]=1609"----------------------------------------------------------------------";16101611static voidshow_stats(struct patch *patch)1612{1613struct strbuf qname = STRBUF_INIT;1614char*cp = patch->new_name ? patch->new_name : patch->old_name;1615int max, add, del;16161617quote_c_style(cp, &qname, NULL,0);16181619/*1620 * "scale" the filename1621 */1622 max = max_len;1623if(max >50)1624 max =50;16251626if(qname.len > max) {1627 cp =strchr(qname.buf + qname.len +3- max,'/');1628if(!cp)1629 cp = qname.buf + qname.len +3- max;1630strbuf_splice(&qname,0, cp - qname.buf,"...",3);1631}16321633if(patch->is_binary) {1634printf(" %-*s | Bin\n", max, qname.buf);1635strbuf_release(&qname);1636return;1637}16381639printf(" %-*s |", max, qname.buf);1640strbuf_release(&qname);16411642/*1643 * scale the add/delete1644 */1645 max = max + max_change >70?70- max : max_change;1646 add = patch->lines_added;1647 del = patch->lines_deleted;16481649if(max_change >0) {1650int total = ((add + del) * max + max_change /2) / max_change;1651 add = (add * max + max_change /2) / max_change;1652 del = total - add;1653}1654printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,1655 add, pluses, del, minuses);1656}16571658static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)1659{1660switch(st->st_mode & S_IFMT) {1661case S_IFLNK:1662if(strbuf_readlink(buf, path, st->st_size) <0)1663returnerror("unable to read symlink%s", path);1664return0;1665case S_IFREG:1666if(strbuf_read_file(buf, path, st->st_size) != st->st_size)1667returnerror("unable to open or read%s", path);1668convert_to_git(path, buf->buf, buf->len, buf,0);1669return0;1670default:1671return-1;1672}1673}16741675static voidupdate_pre_post_images(struct image *preimage,1676struct image *postimage,1677char*buf,1678size_t len)1679{1680int i, ctx;1681char*new, *old, *fixed;1682struct image fixed_preimage;16831684/*1685 * Update the preimage with whitespace fixes. Note that we1686 * are not losing preimage->buf -- apply_one_fragment() will1687 * free "oldlines".1688 */1689prepare_image(&fixed_preimage, buf, len,1);1690assert(fixed_preimage.nr == preimage->nr);1691for(i =0; i < preimage->nr; i++)1692 fixed_preimage.line[i].flag = preimage->line[i].flag;1693free(preimage->line_allocated);1694*preimage = fixed_preimage;16951696/*1697 * Adjust the common context lines in postimage, in place.1698 * This is possible because whitespace fixing does not make1699 * the string grow.1700 */1701new= old = postimage->buf;1702 fixed = preimage->buf;1703for(i = ctx =0; i < postimage->nr; i++) {1704size_t len = postimage->line[i].len;1705if(!(postimage->line[i].flag & LINE_COMMON)) {1706/* an added line -- no counterparts in preimage */1707memmove(new, old, len);1708 old += len;1709new+= len;1710continue;1711}17121713/* a common context -- skip it in the original postimage */1714 old += len;17151716/* and find the corresponding one in the fixed preimage */1717while(ctx < preimage->nr &&1718!(preimage->line[ctx].flag & LINE_COMMON)) {1719 fixed += preimage->line[ctx].len;1720 ctx++;1721}1722if(preimage->nr <= ctx)1723die("oops");17241725/* and copy it in, while fixing the line length */1726 len = preimage->line[ctx].len;1727memcpy(new, fixed, len);1728new+= len;1729 fixed += len;1730 postimage->line[i].len = len;1731 ctx++;1732}17331734/* Fix the length of the whole thing */1735 postimage->len =new- postimage->buf;1736}17371738static intmatch_fragment(struct image *img,1739struct image *preimage,1740struct image *postimage,1741unsigned longtry,1742int try_lno,1743unsigned ws_rule,1744int match_beginning,int match_end)1745{1746int i;1747char*fixed_buf, *buf, *orig, *target;17481749if(preimage->nr + try_lno > img->nr)1750return0;17511752if(match_beginning && try_lno)1753return0;17541755if(match_end && preimage->nr + try_lno != img->nr)1756return0;17571758/* Quick hash check */1759for(i =0; i < preimage->nr; i++)1760if(preimage->line[i].hash != img->line[try_lno + i].hash)1761return0;17621763/*1764 * Do we have an exact match? If we were told to match1765 * at the end, size must be exactly at try+fragsize,1766 * otherwise try+fragsize must be still within the preimage,1767 * and either case, the old piece should match the preimage1768 * exactly.1769 */1770if((match_end1771? (try+ preimage->len == img->len)1772: (try+ preimage->len <= img->len)) &&1773!memcmp(img->buf +try, preimage->buf, preimage->len))1774return1;17751776if(ws_error_action != correct_ws_error)1777return0;17781779/*1780 * The hunk does not apply byte-by-byte, but the hash says1781 * it might with whitespace fuzz.1782 */1783 fixed_buf =xmalloc(preimage->len +1);1784 buf = fixed_buf;1785 orig = preimage->buf;1786 target = img->buf +try;1787for(i =0; i < preimage->nr; i++) {1788size_t fixlen;/* length after fixing the preimage */1789size_t oldlen = preimage->line[i].len;1790size_t tgtlen = img->line[try_lno + i].len;1791size_t tgtfixlen;/* length after fixing the target line */1792char tgtfixbuf[1024], *tgtfix;1793int match;17941795/* Try fixing the line in the preimage */1796 fixlen =ws_fix_copy(buf, orig, oldlen, ws_rule, NULL);17971798/* Try fixing the line in the target */1799if(sizeof(tgtfixbuf) > tgtlen)1800 tgtfix = tgtfixbuf;1801else1802 tgtfix =xmalloc(tgtlen);1803 tgtfixlen =ws_fix_copy(tgtfix, target, tgtlen, ws_rule, NULL);18041805/*1806 * If they match, either the preimage was based on1807 * a version before our tree fixed whitespace breakage,1808 * or we are lacking a whitespace-fix patch the tree1809 * the preimage was based on already had (i.e. target1810 * has whitespace breakage, the preimage doesn't).1811 * In either case, we are fixing the whitespace breakages1812 * so we might as well take the fix together with their1813 * real change.1814 */1815 match = (tgtfixlen == fixlen && !memcmp(tgtfix, buf, fixlen));18161817if(tgtfix != tgtfixbuf)1818free(tgtfix);1819if(!match)1820goto unmatch_exit;18211822 orig += oldlen;1823 buf += fixlen;1824 target += tgtlen;1825}18261827/*1828 * Yes, the preimage is based on an older version that still1829 * has whitespace breakages unfixed, and fixing them makes the1830 * hunk match. Update the context lines in the postimage.1831 */1832update_pre_post_images(preimage, postimage,1833 fixed_buf, buf - fixed_buf);1834return1;18351836 unmatch_exit:1837free(fixed_buf);1838return0;1839}18401841static intfind_pos(struct image *img,1842struct image *preimage,1843struct image *postimage,1844int line,1845unsigned ws_rule,1846int match_beginning,int match_end)1847{1848int i;1849unsigned long backwards, forwards,try;1850int backwards_lno, forwards_lno, try_lno;18511852if(preimage->nr > img->nr)1853return-1;18541855/*1856 * If match_begining or match_end is specified, there is no1857 * point starting from a wrong line that will never match and1858 * wander around and wait for a match at the specified end.1859 */1860if(match_beginning)1861 line =0;1862else if(match_end)1863 line = img->nr - preimage->nr;18641865if(line > img->nr)1866 line = img->nr;18671868try=0;1869for(i =0; i < line; i++)1870try+= img->line[i].len;18711872/*1873 * There's probably some smart way to do this, but I'll leave1874 * that to the smart and beautiful people. I'm simple and stupid.1875 */1876 backwards =try;1877 backwards_lno = line;1878 forwards =try;1879 forwards_lno = line;1880 try_lno = line;18811882for(i =0; ; i++) {1883if(match_fragment(img, preimage, postimage,1884try, try_lno, ws_rule,1885 match_beginning, match_end))1886return try_lno;18871888 again:1889if(backwards_lno ==0&& forwards_lno == img->nr)1890break;18911892if(i &1) {1893if(backwards_lno ==0) {1894 i++;1895goto again;1896}1897 backwards_lno--;1898 backwards -= img->line[backwards_lno].len;1899try= backwards;1900 try_lno = backwards_lno;1901}else{1902if(forwards_lno == img->nr) {1903 i++;1904goto again;1905}1906 forwards += img->line[forwards_lno].len;1907 forwards_lno++;1908try= forwards;1909 try_lno = forwards_lno;1910}19111912}1913return-1;1914}19151916static voidremove_first_line(struct image *img)1917{1918 img->buf += img->line[0].len;1919 img->len -= img->line[0].len;1920 img->line++;1921 img->nr--;1922}19231924static voidremove_last_line(struct image *img)1925{1926 img->len -= img->line[--img->nr].len;1927}19281929static voidupdate_image(struct image *img,1930int applied_pos,1931struct image *preimage,1932struct image *postimage)1933{1934/*1935 * remove the copy of preimage at offset in img1936 * and replace it with postimage1937 */1938int i, nr;1939size_t remove_count, insert_count, applied_at =0;1940char*result;19411942for(i =0; i < applied_pos; i++)1943 applied_at += img->line[i].len;19441945 remove_count =0;1946for(i =0; i < preimage->nr; i++)1947 remove_count += img->line[applied_pos + i].len;1948 insert_count = postimage->len;19491950/* Adjust the contents */1951 result =xmalloc(img->len + insert_count - remove_count +1);1952memcpy(result, img->buf, applied_at);1953memcpy(result + applied_at, postimage->buf, postimage->len);1954memcpy(result + applied_at + postimage->len,1955 img->buf + (applied_at + remove_count),1956 img->len - (applied_at + remove_count));1957free(img->buf);1958 img->buf = result;1959 img->len += insert_count - remove_count;1960 result[img->len] ='\0';19611962/* Adjust the line table */1963 nr = img->nr + postimage->nr - preimage->nr;1964if(preimage->nr < postimage->nr) {1965/*1966 * NOTE: this knows that we never call remove_first_line()1967 * on anything other than pre/post image.1968 */1969 img->line =xrealloc(img->line, nr *sizeof(*img->line));1970 img->line_allocated = img->line;1971}1972if(preimage->nr != postimage->nr)1973memmove(img->line + applied_pos + postimage->nr,1974 img->line + applied_pos + preimage->nr,1975(img->nr - (applied_pos + preimage->nr)) *1976sizeof(*img->line));1977memcpy(img->line + applied_pos,1978 postimage->line,1979 postimage->nr *sizeof(*img->line));1980 img->nr = nr;1981}19821983static intapply_one_fragment(struct image *img,struct fragment *frag,1984int inaccurate_eof,unsigned ws_rule)1985{1986int match_beginning, match_end;1987const char*patch = frag->patch;1988int size = frag->size;1989char*old, *new, *oldlines, *newlines;1990int new_blank_lines_at_end =0;1991unsigned long leading, trailing;1992int pos, applied_pos;1993struct image preimage;1994struct image postimage;19951996memset(&preimage,0,sizeof(preimage));1997memset(&postimage,0,sizeof(postimage));1998 oldlines =xmalloc(size);1999 newlines =xmalloc(size);20002001 old = oldlines;2002new= newlines;2003while(size >0) {2004char first;2005int len =linelen(patch, size);2006int plen, added;2007int added_blank_line =0;20082009if(!len)2010break;20112012/*2013 * "plen" is how much of the line we should use for2014 * the actual patch data. Normally we just remove the2015 * first character on the line, but if the line is2016 * followed by "\ No newline", then we also remove the2017 * last one (which is the newline, of course).2018 */2019 plen = len -1;2020if(len < size && patch[len] =='\\')2021 plen--;2022 first = *patch;2023if(apply_in_reverse) {2024if(first =='-')2025 first ='+';2026else if(first =='+')2027 first ='-';2028}20292030switch(first) {2031case'\n':2032/* Newer GNU diff, empty context line */2033if(plen <0)2034/* ... followed by '\No newline'; nothing */2035break;2036*old++ ='\n';2037*new++ ='\n';2038add_line_info(&preimage,"\n",1, LINE_COMMON);2039add_line_info(&postimage,"\n",1, LINE_COMMON);2040break;2041case' ':2042case'-':2043memcpy(old, patch +1, plen);2044add_line_info(&preimage, old, plen,2045(first ==' '? LINE_COMMON :0));2046 old += plen;2047if(first =='-')2048break;2049/* Fall-through for ' ' */2050case'+':2051/* --no-add does not add new lines */2052if(first =='+'&& no_add)2053break;20542055if(first !='+'||2056!whitespace_error ||2057 ws_error_action != correct_ws_error) {2058memcpy(new, patch +1, plen);2059 added = plen;2060}2061else{2062 added =ws_fix_copy(new, patch +1, plen, ws_rule, &applied_after_fixing_ws);2063}2064add_line_info(&postimage,new, added,2065(first =='+'?0: LINE_COMMON));2066new+= added;2067if(first =='+'&&2068 added ==1&&new[-1] =='\n')2069 added_blank_line =1;2070break;2071case'@':case'\\':2072/* Ignore it, we already handled it */2073break;2074default:2075if(apply_verbosely)2076error("invalid start of line: '%c'", first);2077return-1;2078}2079if(added_blank_line)2080 new_blank_lines_at_end++;2081else2082 new_blank_lines_at_end =0;2083 patch += len;2084 size -= len;2085}2086if(inaccurate_eof &&2087 old > oldlines && old[-1] =='\n'&&2088new> newlines &&new[-1] =='\n') {2089 old--;2090new--;2091}20922093 leading = frag->leading;2094 trailing = frag->trailing;20952096/*2097 * A hunk to change lines at the beginning would begin with2098 * @@ -1,L +N,M @@2099 * but we need to be careful. -U0 that inserts before the second2100 * line also has this pattern.2101 *2102 * And a hunk to add to an empty file would begin with2103 * @@ -0,0 +N,M @@2104 *2105 * In other words, a hunk that is (frag->oldpos <= 1) with or2106 * without leading context must match at the beginning.2107 */2108 match_beginning = (!frag->oldpos ||2109(frag->oldpos ==1&& !unidiff_zero));21102111/*2112 * A hunk without trailing lines must match at the end.2113 * However, we simply cannot tell if a hunk must match end2114 * from the lack of trailing lines if the patch was generated2115 * with unidiff without any context.2116 */2117 match_end = !unidiff_zero && !trailing;21182119 pos = frag->newpos ? (frag->newpos -1) :0;2120 preimage.buf = oldlines;2121 preimage.len = old - oldlines;2122 postimage.buf = newlines;2123 postimage.len =new- newlines;2124 preimage.line = preimage.line_allocated;2125 postimage.line = postimage.line_allocated;21262127for(;;) {21282129 applied_pos =find_pos(img, &preimage, &postimage, pos,2130 ws_rule, match_beginning, match_end);21312132if(applied_pos >=0)2133break;21342135/* Am I at my context limits? */2136if((leading <= p_context) && (trailing <= p_context))2137break;2138if(match_beginning || match_end) {2139 match_beginning = match_end =0;2140continue;2141}21422143/*2144 * Reduce the number of context lines; reduce both2145 * leading and trailing if they are equal otherwise2146 * just reduce the larger context.2147 */2148if(leading >= trailing) {2149remove_first_line(&preimage);2150remove_first_line(&postimage);2151 pos--;2152 leading--;2153}2154if(trailing > leading) {2155remove_last_line(&preimage);2156remove_last_line(&postimage);2157 trailing--;2158}2159}21602161if(applied_pos >=0) {2162if(ws_error_action == correct_ws_error &&2163 new_blank_lines_at_end &&2164 postimage.nr + applied_pos == img->nr) {2165/*2166 * If the patch application adds blank lines2167 * at the end, and if the patch applies at the2168 * end of the image, remove those added blank2169 * lines.2170 */2171while(new_blank_lines_at_end--)2172remove_last_line(&postimage);2173}21742175/*2176 * Warn if it was necessary to reduce the number2177 * of context lines.2178 */2179if((leading != frag->leading) ||2180(trailing != frag->trailing))2181fprintf(stderr,"Context reduced to (%ld/%ld)"2182" to apply fragment at%d\n",2183 leading, trailing, applied_pos+1);2184update_image(img, applied_pos, &preimage, &postimage);2185}else{2186if(apply_verbosely)2187error("while searching for:\n%.*s",2188(int)(old - oldlines), oldlines);2189}21902191free(oldlines);2192free(newlines);2193free(preimage.line_allocated);2194free(postimage.line_allocated);21952196return(applied_pos <0);2197}21982199static intapply_binary_fragment(struct image *img,struct patch *patch)2200{2201struct fragment *fragment = patch->fragments;2202unsigned long len;2203void*dst;22042205/* Binary patch is irreversible without the optional second hunk */2206if(apply_in_reverse) {2207if(!fragment->next)2208returnerror("cannot reverse-apply a binary patch "2209"without the reverse hunk to '%s'",2210 patch->new_name2211? patch->new_name : patch->old_name);2212 fragment = fragment->next;2213}2214switch(fragment->binary_patch_method) {2215case BINARY_DELTA_DEFLATED:2216 dst =patch_delta(img->buf, img->len, fragment->patch,2217 fragment->size, &len);2218if(!dst)2219return-1;2220clear_image(img);2221 img->buf = dst;2222 img->len = len;2223return0;2224case BINARY_LITERAL_DEFLATED:2225clear_image(img);2226 img->len = fragment->size;2227 img->buf =xmalloc(img->len+1);2228memcpy(img->buf, fragment->patch, img->len);2229 img->buf[img->len] ='\0';2230return0;2231}2232return-1;2233}22342235static intapply_binary(struct image *img,struct patch *patch)2236{2237const char*name = patch->old_name ? patch->old_name : patch->new_name;2238unsigned char sha1[20];22392240/*2241 * For safety, we require patch index line to contain2242 * full 40-byte textual SHA1 for old and new, at least for now.2243 */2244if(strlen(patch->old_sha1_prefix) !=40||2245strlen(patch->new_sha1_prefix) !=40||2246get_sha1_hex(patch->old_sha1_prefix, sha1) ||2247get_sha1_hex(patch->new_sha1_prefix, sha1))2248returnerror("cannot apply binary patch to '%s' "2249"without full index line", name);22502251if(patch->old_name) {2252/*2253 * See if the old one matches what the patch2254 * applies to.2255 */2256hash_sha1_file(img->buf, img->len, blob_type, sha1);2257if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2258returnerror("the patch applies to '%s' (%s), "2259"which does not match the "2260"current contents.",2261 name,sha1_to_hex(sha1));2262}2263else{2264/* Otherwise, the old one must be empty. */2265if(img->len)2266returnerror("the patch applies to an empty "2267"'%s' but it is not empty", name);2268}22692270get_sha1_hex(patch->new_sha1_prefix, sha1);2271if(is_null_sha1(sha1)) {2272clear_image(img);2273return0;/* deletion patch */2274}22752276if(has_sha1_file(sha1)) {2277/* We already have the postimage */2278enum object_type type;2279unsigned long size;2280char*result;22812282 result =read_sha1_file(sha1, &type, &size);2283if(!result)2284returnerror("the necessary postimage%sfor "2285"'%s' cannot be read",2286 patch->new_sha1_prefix, name);2287clear_image(img);2288 img->buf = result;2289 img->len = size;2290}else{2291/*2292 * We have verified buf matches the preimage;2293 * apply the patch data to it, which is stored2294 * in the patch->fragments->{patch,size}.2295 */2296if(apply_binary_fragment(img, patch))2297returnerror("binary patch does not apply to '%s'",2298 name);22992300/* verify that the result matches */2301hash_sha1_file(img->buf, img->len, blob_type, sha1);2302if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2303returnerror("binary patch to '%s' creates incorrect result (expecting%s, got%s)",2304 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2305}23062307return0;2308}23092310static intapply_fragments(struct image *img,struct patch *patch)2311{2312struct fragment *frag = patch->fragments;2313const char*name = patch->old_name ? patch->old_name : patch->new_name;2314unsigned ws_rule = patch->ws_rule;2315unsigned inaccurate_eof = patch->inaccurate_eof;23162317if(patch->is_binary)2318returnapply_binary(img, patch);23192320while(frag) {2321if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule)) {2322error("patch failed:%s:%ld", name, frag->oldpos);2323if(!apply_with_reject)2324return-1;2325 frag->rejected =1;2326}2327 frag = frag->next;2328}2329return0;2330}23312332static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2333{2334if(!ce)2335return0;23362337if(S_ISGITLINK(ce->ce_mode)) {2338strbuf_grow(buf,100);2339strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2340}else{2341enum object_type type;2342unsigned long sz;2343char*result;23442345 result =read_sha1_file(ce->sha1, &type, &sz);2346if(!result)2347return-1;2348/* XXX read_sha1_file NUL-terminates */2349strbuf_attach(buf, result, sz, sz +1);2350}2351return0;2352}23532354static struct patch *in_fn_table(const char*name)2355{2356struct string_list_item *item;23572358if(name == NULL)2359return NULL;23602361 item =string_list_lookup(name, &fn_table);2362if(item != NULL)2363return(struct patch *)item->util;23642365return NULL;2366}23672368/*2369 * item->util in the filename table records the status of the path.2370 * Usually it points at a patch (whose result records the contents2371 * of it after applying it), but it could be PATH_WAS_DELETED for a2372 * path that a previously applied patch has already removed.2373 */2374#define PATH_TO_BE_DELETED ((struct patch *) -2)2375#define PATH_WAS_DELETED ((struct patch *) -1)23762377static intto_be_deleted(struct patch *patch)2378{2379return patch == PATH_TO_BE_DELETED;2380}23812382static intwas_deleted(struct patch *patch)2383{2384return patch == PATH_WAS_DELETED;2385}23862387static voidadd_to_fn_table(struct patch *patch)2388{2389struct string_list_item *item;23902391/*2392 * Always add new_name unless patch is a deletion2393 * This should cover the cases for normal diffs,2394 * file creations and copies2395 */2396if(patch->new_name != NULL) {2397 item =string_list_insert(patch->new_name, &fn_table);2398 item->util = patch;2399}24002401/*2402 * store a failure on rename/deletion cases because2403 * later chunks shouldn't patch old names2404 */2405if((patch->new_name == NULL) || (patch->is_rename)) {2406 item =string_list_insert(patch->old_name, &fn_table);2407 item->util = PATH_WAS_DELETED;2408}2409}24102411static voidprepare_fn_table(struct patch *patch)2412{2413/*2414 * store information about incoming file deletion2415 */2416while(patch) {2417if((patch->new_name == NULL) || (patch->is_rename)) {2418struct string_list_item *item;2419 item =string_list_insert(patch->old_name, &fn_table);2420 item->util = PATH_TO_BE_DELETED;2421}2422 patch = patch->next;2423}2424}24252426static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)2427{2428struct strbuf buf = STRBUF_INIT;2429struct image image;2430size_t len;2431char*img;2432struct patch *tpatch;24332434if(!(patch->is_copy || patch->is_rename) &&2435(tpatch =in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {2436if(was_deleted(tpatch)) {2437returnerror("patch%shas been renamed/deleted",2438 patch->old_name);2439}2440/* We have a patched copy in memory use that */2441strbuf_add(&buf, tpatch->result, tpatch->resultsize);2442}else if(cached) {2443if(read_file_or_gitlink(ce, &buf))2444returnerror("read of%sfailed", patch->old_name);2445}else if(patch->old_name) {2446if(S_ISGITLINK(patch->old_mode)) {2447if(ce) {2448read_file_or_gitlink(ce, &buf);2449}else{2450/*2451 * There is no way to apply subproject2452 * patch without looking at the index.2453 */2454 patch->fragments = NULL;2455}2456}else{2457if(read_old_data(st, patch->old_name, &buf))2458returnerror("read of%sfailed", patch->old_name);2459}2460}24612462 img =strbuf_detach(&buf, &len);2463prepare_image(&image, img, len, !patch->is_binary);24642465if(apply_fragments(&image, patch) <0)2466return-1;/* note with --reject this succeeds. */2467 patch->result = image.buf;2468 patch->resultsize = image.len;2469add_to_fn_table(patch);2470free(image.line_allocated);24712472if(0< patch->is_delete && patch->resultsize)2473returnerror("removal patch leaves file contents");24742475return0;2476}24772478static intcheck_to_create_blob(const char*new_name,int ok_if_exists)2479{2480struct stat nst;2481if(!lstat(new_name, &nst)) {2482if(S_ISDIR(nst.st_mode) || ok_if_exists)2483return0;2484/*2485 * A leading component of new_name might be a symlink2486 * that is going to be removed with this patch, but2487 * still pointing at somewhere that has the path.2488 * In such a case, path "new_name" does not exist as2489 * far as git is concerned.2490 */2491if(has_symlink_leading_path(new_name,strlen(new_name)))2492return0;24932494returnerror("%s: already exists in working directory", new_name);2495}2496else if((errno != ENOENT) && (errno != ENOTDIR))2497returnerror("%s:%s", new_name,strerror(errno));2498return0;2499}25002501static intverify_index_match(struct cache_entry *ce,struct stat *st)2502{2503if(S_ISGITLINK(ce->ce_mode)) {2504if(!S_ISDIR(st->st_mode))2505return-1;2506return0;2507}2508returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID);2509}25102511static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)2512{2513const char*old_name = patch->old_name;2514struct patch *tpatch = NULL;2515int stat_ret =0;2516unsigned st_mode =0;25172518/*2519 * Make sure that we do not have local modifications from the2520 * index when we are looking at the index. Also make sure2521 * we have the preimage file to be patched in the work tree,2522 * unless --cached, which tells git to apply only in the index.2523 */2524if(!old_name)2525return0;25262527assert(patch->is_new <=0);25282529if(!(patch->is_copy || patch->is_rename) &&2530(tpatch =in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {2531if(was_deleted(tpatch))2532returnerror("%s: has been deleted/renamed", old_name);2533 st_mode = tpatch->new_mode;2534}else if(!cached) {2535 stat_ret =lstat(old_name, st);2536if(stat_ret && errno != ENOENT)2537returnerror("%s:%s", old_name,strerror(errno));2538}25392540if(to_be_deleted(tpatch))2541 tpatch = NULL;25422543if(check_index && !tpatch) {2544int pos =cache_name_pos(old_name,strlen(old_name));2545if(pos <0) {2546if(patch->is_new <0)2547goto is_new;2548returnerror("%s: does not exist in index", old_name);2549}2550*ce = active_cache[pos];2551if(stat_ret <0) {2552struct checkout costate;2553/* checkout */2554 costate.base_dir ="";2555 costate.base_dir_len =0;2556 costate.force =0;2557 costate.quiet =0;2558 costate.not_new =0;2559 costate.refresh_cache =1;2560if(checkout_entry(*ce, &costate, NULL) ||2561lstat(old_name, st))2562return-1;2563}2564if(!cached &&verify_index_match(*ce, st))2565returnerror("%s: does not match index", old_name);2566if(cached)2567 st_mode = (*ce)->ce_mode;2568}else if(stat_ret <0) {2569if(patch->is_new <0)2570goto is_new;2571returnerror("%s:%s", old_name,strerror(errno));2572}25732574if(!cached && !tpatch)2575 st_mode =ce_mode_from_stat(*ce, st->st_mode);25762577if(patch->is_new <0)2578 patch->is_new =0;2579if(!patch->old_mode)2580 patch->old_mode = st_mode;2581if((st_mode ^ patch->old_mode) & S_IFMT)2582returnerror("%s: wrong type", old_name);2583if(st_mode != patch->old_mode)2584warning("%shas type%o, expected%o",2585 old_name, st_mode, patch->old_mode);2586if(!patch->new_mode && !patch->is_delete)2587 patch->new_mode = st_mode;2588return0;25892590 is_new:2591 patch->is_new =1;2592 patch->is_delete =0;2593 patch->old_name = NULL;2594return0;2595}25962597static intcheck_patch(struct patch *patch)2598{2599struct stat st;2600const char*old_name = patch->old_name;2601const char*new_name = patch->new_name;2602const char*name = old_name ? old_name : new_name;2603struct cache_entry *ce = NULL;2604struct patch *tpatch;2605int ok_if_exists;2606int status;26072608 patch->rejected =1;/* we will drop this after we succeed */26092610 status =check_preimage(patch, &ce, &st);2611if(status)2612return status;2613 old_name = patch->old_name;26142615if((tpatch =in_fn_table(new_name)) &&2616(was_deleted(tpatch) ||to_be_deleted(tpatch)))2617/*2618 * A type-change diff is always split into a patch to2619 * delete old, immediately followed by a patch to2620 * create new (see diff.c::run_diff()); in such a case2621 * it is Ok that the entry to be deleted by the2622 * previous patch is still in the working tree and in2623 * the index.2624 */2625 ok_if_exists =1;2626else2627 ok_if_exists =0;26282629if(new_name &&2630((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {2631if(check_index &&2632cache_name_pos(new_name,strlen(new_name)) >=0&&2633!ok_if_exists)2634returnerror("%s: already exists in index", new_name);2635if(!cached) {2636int err =check_to_create_blob(new_name, ok_if_exists);2637if(err)2638return err;2639}2640if(!patch->new_mode) {2641if(0< patch->is_new)2642 patch->new_mode = S_IFREG |0644;2643else2644 patch->new_mode = patch->old_mode;2645}2646}26472648if(new_name && old_name) {2649int same = !strcmp(old_name, new_name);2650if(!patch->new_mode)2651 patch->new_mode = patch->old_mode;2652if((patch->old_mode ^ patch->new_mode) & S_IFMT)2653returnerror("new mode (%o) of%sdoes not match old mode (%o)%s%s",2654 patch->new_mode, new_name, patch->old_mode,2655 same ?"":" of ", same ?"": old_name);2656}26572658if(apply_data(patch, &st, ce) <0)2659returnerror("%s: patch does not apply", name);2660 patch->rejected =0;2661return0;2662}26632664static intcheck_patch_list(struct patch *patch)2665{2666int err =0;26672668prepare_fn_table(patch);2669while(patch) {2670if(apply_verbosely)2671say_patch_name(stderr,2672"Checking patch ", patch,"...\n");2673 err |=check_patch(patch);2674 patch = patch->next;2675}2676return err;2677}26782679/* This function tries to read the sha1 from the current index */2680static intget_current_sha1(const char*path,unsigned char*sha1)2681{2682int pos;26832684if(read_cache() <0)2685return-1;2686 pos =cache_name_pos(path,strlen(path));2687if(pos <0)2688return-1;2689hashcpy(sha1, active_cache[pos]->sha1);2690return0;2691}26922693/* Build an index that contains the just the files needed for a 3way merge */2694static voidbuild_fake_ancestor(struct patch *list,const char*filename)2695{2696struct patch *patch;2697struct index_state result = { NULL };2698int fd;26992700/* Once we start supporting the reverse patch, it may be2701 * worth showing the new sha1 prefix, but until then...2702 */2703for(patch = list; patch; patch = patch->next) {2704const unsigned char*sha1_ptr;2705unsigned char sha1[20];2706struct cache_entry *ce;2707const char*name;27082709 name = patch->old_name ? patch->old_name : patch->new_name;2710if(0< patch->is_new)2711continue;2712else if(get_sha1(patch->old_sha1_prefix, sha1))2713/* git diff has no index line for mode/type changes */2714if(!patch->lines_added && !patch->lines_deleted) {2715if(get_current_sha1(patch->new_name, sha1) ||2716get_current_sha1(patch->old_name, sha1))2717die("mode change for%s, which is not "2718"in current HEAD", name);2719 sha1_ptr = sha1;2720}else2721die("sha1 information is lacking or useless "2722"(%s).", name);2723else2724 sha1_ptr = sha1;27252726 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);2727if(!ce)2728die("make_cache_entry failed for path '%s'", name);2729if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))2730die("Could not add%sto temporary index", name);2731}27322733 fd =open(filename, O_WRONLY | O_CREAT,0666);2734if(fd <0||write_index(&result, fd) ||close(fd))2735die("Could not write temporary index to%s", filename);27362737discard_index(&result);2738}27392740static voidstat_patch_list(struct patch *patch)2741{2742int files, adds, dels;27432744for(files = adds = dels =0; patch ; patch = patch->next) {2745 files++;2746 adds += patch->lines_added;2747 dels += patch->lines_deleted;2748show_stats(patch);2749}27502751printf("%dfiles changed,%dinsertions(+),%ddeletions(-)\n", files, adds, dels);2752}27532754static voidnumstat_patch_list(struct patch *patch)2755{2756for( ; patch; patch = patch->next) {2757const char*name;2758 name = patch->new_name ? patch->new_name : patch->old_name;2759if(patch->is_binary)2760printf("-\t-\t");2761else2762printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);2763write_name_quoted(name, stdout, line_termination);2764}2765}27662767static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)2768{2769if(mode)2770printf("%smode%06o%s\n", newdelete, mode, name);2771else2772printf("%s %s\n", newdelete, name);2773}27742775static voidshow_mode_change(struct patch *p,int show_name)2776{2777if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {2778if(show_name)2779printf(" mode change%06o =>%06o%s\n",2780 p->old_mode, p->new_mode, p->new_name);2781else2782printf(" mode change%06o =>%06o\n",2783 p->old_mode, p->new_mode);2784}2785}27862787static voidshow_rename_copy(struct patch *p)2788{2789const char*renamecopy = p->is_rename ?"rename":"copy";2790const char*old, *new;27912792/* Find common prefix */2793 old = p->old_name;2794new= p->new_name;2795while(1) {2796const char*slash_old, *slash_new;2797 slash_old =strchr(old,'/');2798 slash_new =strchr(new,'/');2799if(!slash_old ||2800!slash_new ||2801 slash_old - old != slash_new -new||2802memcmp(old,new, slash_new -new))2803break;2804 old = slash_old +1;2805new= slash_new +1;2806}2807/* p->old_name thru old is the common prefix, and old and new2808 * through the end of names are renames2809 */2810if(old != p->old_name)2811printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,2812(int)(old - p->old_name), p->old_name,2813 old,new, p->score);2814else2815printf("%s %s=>%s(%d%%)\n", renamecopy,2816 p->old_name, p->new_name, p->score);2817show_mode_change(p,0);2818}28192820static voidsummary_patch_list(struct patch *patch)2821{2822struct patch *p;28232824for(p = patch; p; p = p->next) {2825if(p->is_new)2826show_file_mode_name("create", p->new_mode, p->new_name);2827else if(p->is_delete)2828show_file_mode_name("delete", p->old_mode, p->old_name);2829else{2830if(p->is_rename || p->is_copy)2831show_rename_copy(p);2832else{2833if(p->score) {2834printf(" rewrite%s(%d%%)\n",2835 p->new_name, p->score);2836show_mode_change(p,0);2837}2838else2839show_mode_change(p,1);2840}2841}2842}2843}28442845static voidpatch_stats(struct patch *patch)2846{2847int lines = patch->lines_added + patch->lines_deleted;28482849if(lines > max_change)2850 max_change = lines;2851if(patch->old_name) {2852int len =quote_c_style(patch->old_name, NULL, NULL,0);2853if(!len)2854 len =strlen(patch->old_name);2855if(len > max_len)2856 max_len = len;2857}2858if(patch->new_name) {2859int len =quote_c_style(patch->new_name, NULL, NULL,0);2860if(!len)2861 len =strlen(patch->new_name);2862if(len > max_len)2863 max_len = len;2864}2865}28662867static voidremove_file(struct patch *patch,int rmdir_empty)2868{2869if(update_index) {2870if(remove_file_from_cache(patch->old_name) <0)2871die("unable to remove%sfrom index", patch->old_name);2872}2873if(!cached) {2874if(S_ISGITLINK(patch->old_mode)) {2875if(rmdir(patch->old_name))2876warning("unable to remove submodule%s",2877 patch->old_name);2878}else if(!unlink_or_warn(patch->old_name) && rmdir_empty) {2879remove_path(patch->old_name);2880}2881}2882}28832884static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)2885{2886struct stat st;2887struct cache_entry *ce;2888int namelen =strlen(path);2889unsigned ce_size =cache_entry_size(namelen);28902891if(!update_index)2892return;28932894 ce =xcalloc(1, ce_size);2895memcpy(ce->name, path, namelen);2896 ce->ce_mode =create_ce_mode(mode);2897 ce->ce_flags = namelen;2898if(S_ISGITLINK(mode)) {2899const char*s = buf;29002901if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))2902die("corrupt patch for subproject%s", path);2903}else{2904if(!cached) {2905if(lstat(path, &st) <0)2906die_errno("unable to stat newly created file '%s'",2907 path);2908fill_stat_cache_info(ce, &st);2909}2910if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)2911die("unable to create backing store for newly created file%s", path);2912}2913if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)2914die("unable to add cache entry for%s", path);2915}29162917static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)2918{2919int fd;2920struct strbuf nbuf = STRBUF_INIT;29212922if(S_ISGITLINK(mode)) {2923struct stat st;2924if(!lstat(path, &st) &&S_ISDIR(st.st_mode))2925return0;2926returnmkdir(path,0777);2927}29282929if(has_symlinks &&S_ISLNK(mode))2930/* Although buf:size is counted string, it also is NUL2931 * terminated.2932 */2933returnsymlink(buf, path);29342935 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);2936if(fd <0)2937return-1;29382939if(convert_to_working_tree(path, buf, size, &nbuf)) {2940 size = nbuf.len;2941 buf = nbuf.buf;2942}2943write_or_die(fd, buf, size);2944strbuf_release(&nbuf);29452946if(close(fd) <0)2947die_errno("closing file '%s'", path);2948return0;2949}29502951/*2952 * We optimistically assume that the directories exist,2953 * which is true 99% of the time anyway. If they don't,2954 * we create them and try again.2955 */2956static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)2957{2958if(cached)2959return;2960if(!try_create_file(path, mode, buf, size))2961return;29622963if(errno == ENOENT) {2964if(safe_create_leading_directories(path))2965return;2966if(!try_create_file(path, mode, buf, size))2967return;2968}29692970if(errno == EEXIST || errno == EACCES) {2971/* We may be trying to create a file where a directory2972 * used to be.2973 */2974struct stat st;2975if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))2976 errno = EEXIST;2977}29782979if(errno == EEXIST) {2980unsigned int nr =getpid();29812982for(;;) {2983char newpath[PATH_MAX];2984mksnpath(newpath,sizeof(newpath),"%s~%u", path, nr);2985if(!try_create_file(newpath, mode, buf, size)) {2986if(!rename(newpath, path))2987return;2988unlink_or_warn(newpath);2989break;2990}2991if(errno != EEXIST)2992break;2993++nr;2994}2995}2996die_errno("unable to write file '%s' mode%o", path, mode);2997}29982999static voidcreate_file(struct patch *patch)3000{3001char*path = patch->new_name;3002unsigned mode = patch->new_mode;3003unsigned long size = patch->resultsize;3004char*buf = patch->result;30053006if(!mode)3007 mode = S_IFREG |0644;3008create_one_file(path, mode, buf, size);3009add_index_file(path, mode, buf, size);3010}30113012/* phase zero is to remove, phase one is to create */3013static voidwrite_out_one_result(struct patch *patch,int phase)3014{3015if(patch->is_delete >0) {3016if(phase ==0)3017remove_file(patch,1);3018return;3019}3020if(patch->is_new >0|| patch->is_copy) {3021if(phase ==1)3022create_file(patch);3023return;3024}3025/*3026 * Rename or modification boils down to the same3027 * thing: remove the old, write the new3028 */3029if(phase ==0)3030remove_file(patch, patch->is_rename);3031if(phase ==1)3032create_file(patch);3033}30343035static intwrite_out_one_reject(struct patch *patch)3036{3037FILE*rej;3038char namebuf[PATH_MAX];3039struct fragment *frag;3040int cnt =0;30413042for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {3043if(!frag->rejected)3044continue;3045 cnt++;3046}30473048if(!cnt) {3049if(apply_verbosely)3050say_patch_name(stderr,3051"Applied patch ", patch," cleanly.\n");3052return0;3053}30543055/* This should not happen, because a removal patch that leaves3056 * contents are marked "rejected" at the patch level.3057 */3058if(!patch->new_name)3059die("internal error");30603061/* Say this even without --verbose */3062say_patch_name(stderr,"Applying patch ", patch," with");3063fprintf(stderr,"%drejects...\n", cnt);30643065 cnt =strlen(patch->new_name);3066if(ARRAY_SIZE(namebuf) <= cnt +5) {3067 cnt =ARRAY_SIZE(namebuf) -5;3068warning("truncating .rej filename to %.*s.rej",3069 cnt -1, patch->new_name);3070}3071memcpy(namebuf, patch->new_name, cnt);3072memcpy(namebuf + cnt,".rej",5);30733074 rej =fopen(namebuf,"w");3075if(!rej)3076returnerror("cannot open%s:%s", namebuf,strerror(errno));30773078/* Normal git tools never deal with .rej, so do not pretend3079 * this is a git patch by saying --git nor give extended3080 * headers. While at it, maybe please "kompare" that wants3081 * the trailing TAB and some garbage at the end of line ;-).3082 */3083fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",3084 patch->new_name, patch->new_name);3085for(cnt =1, frag = patch->fragments;3086 frag;3087 cnt++, frag = frag->next) {3088if(!frag->rejected) {3089fprintf(stderr,"Hunk #%dapplied cleanly.\n", cnt);3090continue;3091}3092fprintf(stderr,"Rejected hunk #%d.\n", cnt);3093fprintf(rej,"%.*s", frag->size, frag->patch);3094if(frag->patch[frag->size-1] !='\n')3095fputc('\n', rej);3096}3097fclose(rej);3098return-1;3099}31003101static intwrite_out_results(struct patch *list,int skipped_patch)3102{3103int phase;3104int errs =0;3105struct patch *l;31063107if(!list && !skipped_patch)3108returnerror("No changes");31093110for(phase =0; phase <2; phase++) {3111 l = list;3112while(l) {3113if(l->rejected)3114 errs =1;3115else{3116write_out_one_result(l, phase);3117if(phase ==1&&write_out_one_reject(l))3118 errs =1;3119}3120 l = l->next;3121}3122}3123return errs;3124}31253126static struct lock_file lock_file;31273128static struct string_list limit_by_name;3129static int has_include;3130static voidadd_name_limit(const char*name,int exclude)3131{3132struct string_list_item *it;31333134 it =string_list_append(name, &limit_by_name);3135 it->util = exclude ? NULL : (void*)1;3136}31373138static intuse_patch(struct patch *p)3139{3140const char*pathname = p->new_name ? p->new_name : p->old_name;3141int i;31423143/* Paths outside are not touched regardless of "--include" */3144if(0< prefix_length) {3145int pathlen =strlen(pathname);3146if(pathlen <= prefix_length ||3147memcmp(prefix, pathname, prefix_length))3148return0;3149}31503151/* See if it matches any of exclude/include rule */3152for(i =0; i < limit_by_name.nr; i++) {3153struct string_list_item *it = &limit_by_name.items[i];3154if(!fnmatch(it->string, pathname,0))3155return(it->util != NULL);3156}31573158/*3159 * If we had any include, a path that does not match any rule is3160 * not used. Otherwise, we saw bunch of exclude rules (or none)3161 * and such a path is used.3162 */3163return!has_include;3164}316531663167static voidprefix_one(char**name)3168{3169char*old_name = *name;3170if(!old_name)3171return;3172*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3173free(old_name);3174}31753176static voidprefix_patches(struct patch *p)3177{3178if(!prefix || p->is_toplevel_relative)3179return;3180for( ; p; p = p->next) {3181if(p->new_name == p->old_name) {3182char*prefixed = p->new_name;3183prefix_one(&prefixed);3184 p->new_name = p->old_name = prefixed;3185}3186else{3187prefix_one(&p->new_name);3188prefix_one(&p->old_name);3189}3190}3191}31923193#define INACCURATE_EOF (1<<0)3194#define RECOUNT (1<<1)31953196static intapply_patch(int fd,const char*filename,int options)3197{3198size_t offset;3199struct strbuf buf = STRBUF_INIT;3200struct patch *list = NULL, **listp = &list;3201int skipped_patch =0;32023203/* FIXME - memory leak when using multiple patch files as inputs */3204memset(&fn_table,0,sizeof(struct string_list));3205 patch_input_file = filename;3206read_patch_file(&buf, fd);3207 offset =0;3208while(offset < buf.len) {3209struct patch *patch;3210int nr;32113212 patch =xcalloc(1,sizeof(*patch));3213 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3214 patch->recount = !!(options & RECOUNT);3215 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3216if(nr <0)3217break;3218if(apply_in_reverse)3219reverse_patches(patch);3220if(prefix)3221prefix_patches(patch);3222if(use_patch(patch)) {3223patch_stats(patch);3224*listp = patch;3225 listp = &patch->next;3226}3227else{3228/* perhaps free it a bit better? */3229free(patch);3230 skipped_patch++;3231}3232 offset += nr;3233}32343235if(whitespace_error && (ws_error_action == die_on_ws_error))3236 apply =0;32373238 update_index = check_index && apply;3239if(update_index && newfd <0)3240 newfd =hold_locked_index(&lock_file,1);32413242if(check_index) {3243if(read_cache() <0)3244die("unable to read index file");3245}32463247if((check || apply) &&3248check_patch_list(list) <0&&3249!apply_with_reject)3250exit(1);32513252if(apply &&write_out_results(list, skipped_patch))3253exit(1);32543255if(fake_ancestor)3256build_fake_ancestor(list, fake_ancestor);32573258if(diffstat)3259stat_patch_list(list);32603261if(numstat)3262numstat_patch_list(list);32633264if(summary)3265summary_patch_list(list);32663267strbuf_release(&buf);3268return0;3269}32703271static intgit_apply_config(const char*var,const char*value,void*cb)3272{3273if(!strcmp(var,"apply.whitespace"))3274returngit_config_string(&apply_default_whitespace, var, value);3275returngit_default_config(var, value, cb);3276}32773278static intoption_parse_exclude(const struct option *opt,3279const char*arg,int unset)3280{3281add_name_limit(arg,1);3282return0;3283}32843285static intoption_parse_include(const struct option *opt,3286const char*arg,int unset)3287{3288add_name_limit(arg,0);3289 has_include =1;3290return0;3291}32923293static intoption_parse_p(const struct option *opt,3294const char*arg,int unset)3295{3296 p_value =atoi(arg);3297 p_value_known =1;3298return0;3299}33003301static intoption_parse_z(const struct option *opt,3302const char*arg,int unset)3303{3304if(unset)3305 line_termination ='\n';3306else3307 line_termination =0;3308return0;3309}33103311static intoption_parse_whitespace(const struct option *opt,3312const char*arg,int unset)3313{3314const char**whitespace_option = opt->value;33153316*whitespace_option = arg;3317parse_whitespace_option(arg);3318return0;3319}33203321static intoption_parse_directory(const struct option *opt,3322const char*arg,int unset)3323{3324 root_len =strlen(arg);3325if(root_len && arg[root_len -1] !='/') {3326char*new_root;3327 root = new_root =xmalloc(root_len +2);3328strcpy(new_root, arg);3329strcpy(new_root + root_len++,"/");3330}else3331 root = arg;3332return0;3333}33343335intcmd_apply(int argc,const char**argv,const char*unused_prefix)3336{3337int i;3338int errs =0;3339int is_not_gitdir;3340int binary;3341int force_apply =0;33423343const char*whitespace_option = NULL;33443345struct option builtin_apply_options[] = {3346{ OPTION_CALLBACK,0,"exclude", NULL,"path",3347"don't apply changes matching the given path",33480, option_parse_exclude },3349{ OPTION_CALLBACK,0,"include", NULL,"path",3350"apply changes matching the given path",33510, option_parse_include },3352{ OPTION_CALLBACK,'p', NULL, NULL,"num",3353"remove <num> leading slashes from traditional diff paths",33540, option_parse_p },3355OPT_BOOLEAN(0,"no-add", &no_add,3356"ignore additions made by the patch"),3357OPT_BOOLEAN(0,"stat", &diffstat,3358"instead of applying the patch, output diffstat for the input"),3359{ OPTION_BOOLEAN,0,"allow-binary-replacement", &binary,3360 NULL,"old option, now no-op",3361 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3362{ OPTION_BOOLEAN,0,"binary", &binary,3363 NULL,"old option, now no-op",3364 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },3365OPT_BOOLEAN(0,"numstat", &numstat,3366"shows number of added and deleted lines in decimal notation"),3367OPT_BOOLEAN(0,"summary", &summary,3368"instead of applying the patch, output a summary for the input"),3369OPT_BOOLEAN(0,"check", &check,3370"instead of applying the patch, see if the patch is applicable"),3371OPT_BOOLEAN(0,"index", &check_index,3372"make sure the patch is applicable to the current index"),3373OPT_BOOLEAN(0,"cached", &cached,3374"apply a patch without touching the working tree"),3375OPT_BOOLEAN(0,"apply", &force_apply,3376"also apply the patch (use with --stat/--summary/--check)"),3377OPT_FILENAME(0,"build-fake-ancestor", &fake_ancestor,3378"build a temporary index based on embedded index information"),3379{ OPTION_CALLBACK,'z', NULL, NULL, NULL,3380"paths are separated with NUL character",3381 PARSE_OPT_NOARG, option_parse_z },3382OPT_INTEGER('C', NULL, &p_context,3383"ensure at least <n> lines of context match"),3384{ OPTION_CALLBACK,0,"whitespace", &whitespace_option,"action",3385"detect new or modified lines that have whitespace errors",33860, option_parse_whitespace },3387OPT_BOOLEAN('R',"reverse", &apply_in_reverse,3388"apply the patch in reverse"),3389OPT_BOOLEAN(0,"unidiff-zero", &unidiff_zero,3390"don't expect at least one line of context"),3391OPT_BOOLEAN(0,"reject", &apply_with_reject,3392"leave the rejected hunks in corresponding *.rej files"),3393OPT__VERBOSE(&apply_verbosely),3394OPT_BIT(0,"inaccurate-eof", &options,3395"tolerate incorrectly detected missing new-line at the end of file",3396 INACCURATE_EOF),3397OPT_BIT(0,"recount", &options,3398"do not trust the line counts in the hunk headers",3399 RECOUNT),3400{ OPTION_CALLBACK,0,"directory", NULL,"root",3401"prepend <root> to all filenames",34020, option_parse_directory },3403OPT_END()3404};34053406 prefix =setup_git_directory_gently(&is_not_gitdir);3407 prefix_length = prefix ?strlen(prefix) :0;3408git_config(git_apply_config, NULL);3409if(apply_default_whitespace)3410parse_whitespace_option(apply_default_whitespace);34113412 argc =parse_options(argc, argv, prefix, builtin_apply_options,3413 apply_usage,0);34143415if(apply_with_reject)3416 apply = apply_verbosely =1;3417if(!force_apply && (diffstat || numstat || summary || check || fake_ancestor))3418 apply =0;3419if(check_index && is_not_gitdir)3420die("--index outside a repository");3421if(cached) {3422if(is_not_gitdir)3423die("--cached outside a repository");3424 check_index =1;3425}3426for(i =0; i < argc; i++) {3427const char*arg = argv[i];3428int fd;34293430if(!strcmp(arg,"-")) {3431 errs |=apply_patch(0,"<stdin>", options);3432 read_stdin =0;3433continue;3434}else if(0< prefix_length)3435 arg =prefix_filename(prefix, prefix_length, arg);34363437 fd =open(arg, O_RDONLY);3438if(fd <0)3439die_errno("can't open patch '%s'", arg);3440 read_stdin =0;3441set_default_whitespace_mode(whitespace_option);3442 errs |=apply_patch(fd, arg, options);3443close(fd);3444}3445set_default_whitespace_mode(whitespace_option);3446if(read_stdin)3447 errs |=apply_patch(0,"<stdin>", options);3448if(whitespace_error) {3449if(squelch_whitespace_errors &&3450 squelch_whitespace_errors < whitespace_error) {3451int squelched =3452 whitespace_error - squelch_whitespace_errors;3453warning("squelched%d"3454"whitespace error%s",3455 squelched,3456 squelched ==1?"":"s");3457}3458if(ws_error_action == die_on_ws_error)3459die("%dline%sadd%swhitespace errors.",3460 whitespace_error,3461 whitespace_error ==1?"":"s",3462 whitespace_error ==1?"s":"");3463if(applied_after_fixing_ws && apply)3464warning("%dline%sapplied after"3465" fixing whitespace errors.",3466 applied_after_fixing_ws,3467 applied_after_fixing_ws ==1?"":"s");3468else if(whitespace_error)3469warning("%dline%sadd%swhitespace errors.",3470 whitespace_error,3471 whitespace_error ==1?"":"s",3472 whitespace_error ==1?"s":"");3473}34743475if(update_index) {3476if(write_cache(newfd, active_cache, active_nr) ||3477commit_locked_index(&lock_file))3478die("Unable to write new index file");3479}34803481return!!errs;3482}