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 17/* 18 * --check turns on checking that the working tree matches the 19 * files that are being modified, but doesn't apply the patch 20 * --stat does just a diffstat, and doesn't actually apply 21 * --numstat does numeric diffstat, and doesn't actually apply 22 * --index-info shows the old and new index info for paths if available. 23 * --index updates the cache as well. 24 * --cached updates only the cache without ever touching the working tree. 25 */ 26static const char*prefix; 27static int prefix_length = -1; 28static int newfd = -1; 29 30static int unidiff_zero; 31static int p_value =1; 32static int p_value_known; 33static int check_index; 34static int update_index; 35static int cached; 36static int diffstat; 37static int numstat; 38static int summary; 39static int check; 40static int apply =1; 41static int apply_in_reverse; 42static int apply_with_reject; 43static int apply_verbosely; 44static int no_add; 45static const char*fake_ancestor; 46static int line_termination ='\n'; 47static unsigned long p_context = ULONG_MAX; 48static const char apply_usage[] = 49"git apply [--stat] [--numstat] [--summary] [--check] [--index] [--cached] [--apply] [--no-add] [--index-info] [--allow-binary-replacement] [--reverse] [--reject] [--verbose] [-z] [-pNUM] [-CNUM] [--whitespace=<nowarn|warn|fix|error|error-all>] <patch>..."; 50 51static enum ws_error_action { 52 nowarn_ws_error, 53 warn_on_ws_error, 54 die_on_ws_error, 55 correct_ws_error, 56} ws_error_action = warn_on_ws_error; 57static int whitespace_error; 58static int squelch_whitespace_errors =5; 59static int applied_after_fixing_ws; 60static const char*patch_input_file; 61static const char*root; 62static int root_len; 63 64static voidparse_whitespace_option(const char*option) 65{ 66if(!option) { 67 ws_error_action = warn_on_ws_error; 68return; 69} 70if(!strcmp(option,"warn")) { 71 ws_error_action = warn_on_ws_error; 72return; 73} 74if(!strcmp(option,"nowarn")) { 75 ws_error_action = nowarn_ws_error; 76return; 77} 78if(!strcmp(option,"error")) { 79 ws_error_action = die_on_ws_error; 80return; 81} 82if(!strcmp(option,"error-all")) { 83 ws_error_action = die_on_ws_error; 84 squelch_whitespace_errors =0; 85return; 86} 87if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 88 ws_error_action = correct_ws_error; 89return; 90} 91die("unrecognized whitespace option '%s'", option); 92} 93 94static voidset_default_whitespace_mode(const char*whitespace_option) 95{ 96if(!whitespace_option && !apply_default_whitespace) 97 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 98} 99 100/* 101 * For "diff-stat" like behaviour, we keep track of the biggest change 102 * we've seen, and the longest filename. That allows us to do simple 103 * scaling. 104 */ 105static int max_change, max_len; 106 107/* 108 * Various "current state", notably line numbers and what 109 * file (and how) we're patching right now.. The "is_xxxx" 110 * things are flags, where -1 means "don't know yet". 111 */ 112static int linenr =1; 113 114/* 115 * This represents one "hunk" from a patch, starting with 116 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 117 * patch text is pointed at by patch, and its byte length 118 * is stored in size. leading and trailing are the number 119 * of context lines. 120 */ 121struct fragment { 122unsigned long leading, trailing; 123unsigned long oldpos, oldlines; 124unsigned long newpos, newlines; 125const char*patch; 126int size; 127int rejected; 128struct fragment *next; 129}; 130 131/* 132 * When dealing with a binary patch, we reuse "leading" field 133 * to store the type of the binary hunk, either deflated "delta" 134 * or deflated "literal". 135 */ 136#define binary_patch_method leading 137#define BINARY_DELTA_DEFLATED 1 138#define BINARY_LITERAL_DEFLATED 2 139 140/* 141 * This represents a "patch" to a file, both metainfo changes 142 * such as creation/deletion, filemode and content changes represented 143 * as a series of fragments. 144 */ 145struct patch { 146char*new_name, *old_name, *def_name; 147unsigned int old_mode, new_mode; 148int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 149int rejected; 150unsigned ws_rule; 151unsigned long deflate_origlen; 152int lines_added, lines_deleted; 153int score; 154unsigned int is_toplevel_relative:1; 155unsigned int inaccurate_eof:1; 156unsigned int is_binary:1; 157unsigned int is_copy:1; 158unsigned int is_rename:1; 159unsigned int recount:1; 160struct fragment *fragments; 161char*result; 162size_t resultsize; 163char old_sha1_prefix[41]; 164char new_sha1_prefix[41]; 165struct patch *next; 166}; 167 168/* 169 * A line in a file, len-bytes long (includes the terminating LF, 170 * except for an incomplete line at the end if the file ends with 171 * one), and its contents hashes to 'hash'. 172 */ 173struct line { 174size_t len; 175unsigned hash :24; 176unsigned flag :8; 177#define LINE_COMMON 1 178}; 179 180/* 181 * This represents a "file", which is an array of "lines". 182 */ 183struct image { 184char*buf; 185size_t len; 186size_t nr; 187size_t alloc; 188struct line *line_allocated; 189struct line *line; 190}; 191 192/* 193 * Records filenames that have been touched, in order to handle 194 * the case where more than one patches touch the same file. 195 */ 196 197static struct string_list fn_table; 198 199static uint32_thash_line(const char*cp,size_t len) 200{ 201size_t i; 202uint32_t h; 203for(i =0, h =0; i < len; i++) { 204if(!isspace(cp[i])) { 205 h = h *3+ (cp[i] &0xff); 206} 207} 208return h; 209} 210 211static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 212{ 213ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 214 img->line_allocated[img->nr].len = len; 215 img->line_allocated[img->nr].hash =hash_line(bol, len); 216 img->line_allocated[img->nr].flag = flag; 217 img->nr++; 218} 219 220static voidprepare_image(struct image *image,char*buf,size_t len, 221int prepare_linetable) 222{ 223const char*cp, *ep; 224 225memset(image,0,sizeof(*image)); 226 image->buf = buf; 227 image->len = len; 228 229if(!prepare_linetable) 230return; 231 232 ep = image->buf + image->len; 233 cp = image->buf; 234while(cp < ep) { 235const char*next; 236for(next = cp; next < ep && *next !='\n'; next++) 237; 238if(next < ep) 239 next++; 240add_line_info(image, cp, next - cp,0); 241 cp = next; 242} 243 image->line = image->line_allocated; 244} 245 246static voidclear_image(struct image *image) 247{ 248free(image->buf); 249 image->buf = NULL; 250 image->len =0; 251} 252 253static voidsay_patch_name(FILE*output,const char*pre, 254struct patch *patch,const char*post) 255{ 256fputs(pre, output); 257if(patch->old_name && patch->new_name && 258strcmp(patch->old_name, patch->new_name)) { 259quote_c_style(patch->old_name, NULL, output,0); 260fputs(" => ", output); 261quote_c_style(patch->new_name, NULL, output,0); 262}else{ 263const char*n = patch->new_name; 264if(!n) 265 n = patch->old_name; 266quote_c_style(n, NULL, output,0); 267} 268fputs(post, output); 269} 270 271#define CHUNKSIZE (8192) 272#define SLOP (16) 273 274static voidread_patch_file(struct strbuf *sb,int fd) 275{ 276if(strbuf_read(sb, fd,0) <0) 277die("git-apply: read returned%s",strerror(errno)); 278 279/* 280 * Make sure that we have some slop in the buffer 281 * so that we can do speculative "memcmp" etc, and 282 * see to it that it is NUL-filled. 283 */ 284strbuf_grow(sb, SLOP); 285memset(sb->buf + sb->len,0, SLOP); 286} 287 288static unsigned longlinelen(const char*buffer,unsigned long size) 289{ 290unsigned long len =0; 291while(size--) { 292 len++; 293if(*buffer++ =='\n') 294break; 295} 296return len; 297} 298 299static intis_dev_null(const char*str) 300{ 301return!memcmp("/dev/null", str,9) &&isspace(str[9]); 302} 303 304#define TERM_SPACE 1 305#define TERM_TAB 2 306 307static intname_terminate(const char*name,int namelen,int c,int terminate) 308{ 309if(c ==' '&& !(terminate & TERM_SPACE)) 310return0; 311if(c =='\t'&& !(terminate & TERM_TAB)) 312return0; 313 314return1; 315} 316 317static char*find_name(const char*line,char*def,int p_value,int terminate) 318{ 319int len; 320const char*start = line; 321 322if(*line =='"') { 323struct strbuf name; 324 325/* 326 * Proposed "new-style" GNU patch/diff format; see 327 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2 328 */ 329strbuf_init(&name,0); 330if(!unquote_c_style(&name, line, NULL)) { 331char*cp; 332 333for(cp = name.buf; p_value; p_value--) { 334 cp =strchr(cp,'/'); 335if(!cp) 336break; 337 cp++; 338} 339if(cp) { 340/* name can later be freed, so we need 341 * to memmove, not just return cp 342 */ 343strbuf_remove(&name,0, cp - name.buf); 344free(def); 345if(root) 346strbuf_insert(&name,0, root, root_len); 347returnstrbuf_detach(&name, NULL); 348} 349} 350strbuf_release(&name); 351} 352 353for(;;) { 354char c = *line; 355 356if(isspace(c)) { 357if(c =='\n') 358break; 359if(name_terminate(start, line-start, c, terminate)) 360break; 361} 362 line++; 363if(c =='/'&& !--p_value) 364 start = line; 365} 366if(!start) 367return def; 368 len = line - start; 369if(!len) 370return def; 371 372/* 373 * Generally we prefer the shorter name, especially 374 * if the other one is just a variation of that with 375 * something else tacked on to the end (ie "file.orig" 376 * or "file~"). 377 */ 378if(def) { 379int deflen =strlen(def); 380if(deflen < len && !strncmp(start, def, deflen)) 381return def; 382free(def); 383} 384 385if(root) { 386char*ret =xmalloc(root_len + len +1); 387strcpy(ret, root); 388memcpy(ret + root_len, start, len); 389 ret[root_len + len] ='\0'; 390return ret; 391} 392 393returnxmemdupz(start, len); 394} 395 396static intcount_slashes(const char*cp) 397{ 398int cnt =0; 399char ch; 400 401while((ch = *cp++)) 402if(ch =='/') 403 cnt++; 404return cnt; 405} 406 407/* 408 * Given the string after "--- " or "+++ ", guess the appropriate 409 * p_value for the given patch. 410 */ 411static intguess_p_value(const char*nameline) 412{ 413char*name, *cp; 414int val = -1; 415 416if(is_dev_null(nameline)) 417return-1; 418 name =find_name(nameline, NULL,0, TERM_SPACE | TERM_TAB); 419if(!name) 420return-1; 421 cp =strchr(name,'/'); 422if(!cp) 423 val =0; 424else if(prefix) { 425/* 426 * Does it begin with "a/$our-prefix" and such? Then this is 427 * very likely to apply to our directory. 428 */ 429if(!strncmp(name, prefix, prefix_length)) 430 val =count_slashes(prefix); 431else{ 432 cp++; 433if(!strncmp(cp, prefix, prefix_length)) 434 val =count_slashes(prefix) +1; 435} 436} 437free(name); 438return val; 439} 440 441/* 442 * Get the name etc info from the ---/+++ lines of a traditional patch header 443 * 444 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 445 * files, we can happily check the index for a match, but for creating a 446 * new file we should try to match whatever "patch" does. I have no idea. 447 */ 448static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 449{ 450char*name; 451 452 first +=4;/* skip "--- " */ 453 second +=4;/* skip "+++ " */ 454if(!p_value_known) { 455int p, q; 456 p =guess_p_value(first); 457 q =guess_p_value(second); 458if(p <0) p = q; 459if(0<= p && p == q) { 460 p_value = p; 461 p_value_known =1; 462} 463} 464if(is_dev_null(first)) { 465 patch->is_new =1; 466 patch->is_delete =0; 467 name =find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB); 468 patch->new_name = name; 469}else if(is_dev_null(second)) { 470 patch->is_new =0; 471 patch->is_delete =1; 472 name =find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB); 473 patch->old_name = name; 474}else{ 475 name =find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB); 476 name =find_name(second, name, p_value, TERM_SPACE | TERM_TAB); 477 patch->old_name = patch->new_name = name; 478} 479if(!name) 480die("unable to find filename in patch at line%d", linenr); 481} 482 483static intgitdiff_hdrend(const char*line,struct patch *patch) 484{ 485return-1; 486} 487 488/* 489 * We're anal about diff header consistency, to make 490 * sure that we don't end up having strange ambiguous 491 * patches floating around. 492 * 493 * As a result, gitdiff_{old|new}name() will check 494 * their names against any previous information, just 495 * to make sure.. 496 */ 497static char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,const char*oldnew) 498{ 499if(!orig_name && !isnull) 500returnfind_name(line, NULL, p_value, TERM_TAB); 501 502if(orig_name) { 503int len; 504const char*name; 505char*another; 506 name = orig_name; 507 len =strlen(name); 508if(isnull) 509die("git-apply: bad git-diff - expected /dev/null, got%son line%d", name, linenr); 510 another =find_name(line, NULL, p_value, TERM_TAB); 511if(!another ||memcmp(another, name, len)) 512die("git-apply: bad git-diff - inconsistent%sfilename on line%d", oldnew, linenr); 513free(another); 514return orig_name; 515} 516else{ 517/* expect "/dev/null" */ 518if(memcmp("/dev/null", line,9) || line[9] !='\n') 519die("git-apply: bad git-diff - expected /dev/null on line%d", linenr); 520return NULL; 521} 522} 523 524static intgitdiff_oldname(const char*line,struct patch *patch) 525{ 526 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name,"old"); 527return0; 528} 529 530static intgitdiff_newname(const char*line,struct patch *patch) 531{ 532 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name,"new"); 533return0; 534} 535 536static intgitdiff_oldmode(const char*line,struct patch *patch) 537{ 538 patch->old_mode =strtoul(line, NULL,8); 539return0; 540} 541 542static intgitdiff_newmode(const char*line,struct patch *patch) 543{ 544 patch->new_mode =strtoul(line, NULL,8); 545return0; 546} 547 548static intgitdiff_delete(const char*line,struct patch *patch) 549{ 550 patch->is_delete =1; 551 patch->old_name = patch->def_name; 552returngitdiff_oldmode(line, patch); 553} 554 555static intgitdiff_newfile(const char*line,struct patch *patch) 556{ 557 patch->is_new =1; 558 patch->new_name = patch->def_name; 559returngitdiff_newmode(line, patch); 560} 561 562static intgitdiff_copysrc(const char*line,struct patch *patch) 563{ 564 patch->is_copy =1; 565 patch->old_name =find_name(line, NULL,0,0); 566return0; 567} 568 569static intgitdiff_copydst(const char*line,struct patch *patch) 570{ 571 patch->is_copy =1; 572 patch->new_name =find_name(line, NULL,0,0); 573return0; 574} 575 576static intgitdiff_renamesrc(const char*line,struct patch *patch) 577{ 578 patch->is_rename =1; 579 patch->old_name =find_name(line, NULL,0,0); 580return0; 581} 582 583static intgitdiff_renamedst(const char*line,struct patch *patch) 584{ 585 patch->is_rename =1; 586 patch->new_name =find_name(line, NULL,0,0); 587return0; 588} 589 590static intgitdiff_similarity(const char*line,struct patch *patch) 591{ 592if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 593 patch->score =0; 594return0; 595} 596 597static intgitdiff_dissimilarity(const char*line,struct patch *patch) 598{ 599if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 600 patch->score =0; 601return0; 602} 603 604static intgitdiff_index(const char*line,struct patch *patch) 605{ 606/* 607 * index line is N hexadecimal, "..", N hexadecimal, 608 * and optional space with octal mode. 609 */ 610const char*ptr, *eol; 611int len; 612 613 ptr =strchr(line,'.'); 614if(!ptr || ptr[1] !='.'||40< ptr - line) 615return0; 616 len = ptr - line; 617memcpy(patch->old_sha1_prefix, line, len); 618 patch->old_sha1_prefix[len] =0; 619 620 line = ptr +2; 621 ptr =strchr(line,' '); 622 eol =strchr(line,'\n'); 623 624if(!ptr || eol < ptr) 625 ptr = eol; 626 len = ptr - line; 627 628if(40< len) 629return0; 630memcpy(patch->new_sha1_prefix, line, len); 631 patch->new_sha1_prefix[len] =0; 632if(*ptr ==' ') 633 patch->new_mode = patch->old_mode =strtoul(ptr+1, NULL,8); 634return0; 635} 636 637/* 638 * This is normal for a diff that doesn't change anything: we'll fall through 639 * into the next diff. Tell the parser to break out. 640 */ 641static intgitdiff_unrecognized(const char*line,struct patch *patch) 642{ 643return-1; 644} 645 646static const char*stop_at_slash(const char*line,int llen) 647{ 648int i; 649 650for(i =0; i < llen; i++) { 651int ch = line[i]; 652if(ch =='/') 653return line + i; 654} 655return NULL; 656} 657 658/* 659 * This is to extract the same name that appears on "diff --git" 660 * line. We do not find and return anything if it is a rename 661 * patch, and it is OK because we will find the name elsewhere. 662 * We need to reliably find name only when it is mode-change only, 663 * creation or deletion of an empty file. In any of these cases, 664 * both sides are the same name under a/ and b/ respectively. 665 */ 666static char*git_header_name(char*line,int llen) 667{ 668const char*name; 669const char*second = NULL; 670size_t len; 671 672 line +=strlen("diff --git "); 673 llen -=strlen("diff --git "); 674 675if(*line =='"') { 676const char*cp; 677struct strbuf first; 678struct strbuf sp; 679 680strbuf_init(&first,0); 681strbuf_init(&sp,0); 682 683if(unquote_c_style(&first, line, &second)) 684goto free_and_fail1; 685 686/* advance to the first slash */ 687 cp =stop_at_slash(first.buf, first.len); 688/* we do not accept absolute paths */ 689if(!cp || cp == first.buf) 690goto free_and_fail1; 691strbuf_remove(&first,0, cp +1- first.buf); 692 693/* 694 * second points at one past closing dq of name. 695 * find the second name. 696 */ 697while((second < line + llen) &&isspace(*second)) 698 second++; 699 700if(line + llen <= second) 701goto free_and_fail1; 702if(*second =='"') { 703if(unquote_c_style(&sp, second, NULL)) 704goto free_and_fail1; 705 cp =stop_at_slash(sp.buf, sp.len); 706if(!cp || cp == sp.buf) 707goto free_and_fail1; 708/* They must match, otherwise ignore */ 709if(strcmp(cp +1, first.buf)) 710goto free_and_fail1; 711strbuf_release(&sp); 712returnstrbuf_detach(&first, NULL); 713} 714 715/* unquoted second */ 716 cp =stop_at_slash(second, line + llen - second); 717if(!cp || cp == second) 718goto free_and_fail1; 719 cp++; 720if(line + llen - cp != first.len +1|| 721memcmp(first.buf, cp, first.len)) 722goto free_and_fail1; 723returnstrbuf_detach(&first, NULL); 724 725 free_and_fail1: 726strbuf_release(&first); 727strbuf_release(&sp); 728return NULL; 729} 730 731/* unquoted first name */ 732 name =stop_at_slash(line, llen); 733if(!name || name == line) 734return NULL; 735 name++; 736 737/* 738 * since the first name is unquoted, a dq if exists must be 739 * the beginning of the second name. 740 */ 741for(second = name; second < line + llen; second++) { 742if(*second =='"') { 743struct strbuf sp; 744const char*np; 745 746strbuf_init(&sp,0); 747if(unquote_c_style(&sp, second, NULL)) 748goto free_and_fail2; 749 750 np =stop_at_slash(sp.buf, sp.len); 751if(!np || np == sp.buf) 752goto free_and_fail2; 753 np++; 754 755 len = sp.buf + sp.len - np; 756if(len < second - name && 757!strncmp(np, name, len) && 758isspace(name[len])) { 759/* Good */ 760strbuf_remove(&sp,0, np - sp.buf); 761returnstrbuf_detach(&sp, NULL); 762} 763 764 free_and_fail2: 765strbuf_release(&sp); 766return NULL; 767} 768} 769 770/* 771 * Accept a name only if it shows up twice, exactly the same 772 * form. 773 */ 774for(len =0; ; len++) { 775switch(name[len]) { 776default: 777continue; 778case'\n': 779return NULL; 780case'\t':case' ': 781 second = name+len; 782for(;;) { 783char c = *second++; 784if(c =='\n') 785return NULL; 786if(c =='/') 787break; 788} 789if(second[len] =='\n'&& !memcmp(name, second, len)) { 790returnxmemdupz(name, len); 791} 792} 793} 794} 795 796/* Verify that we recognize the lines following a git header */ 797static intparse_git_header(char*line,int len,unsigned int size,struct patch *patch) 798{ 799unsigned long offset; 800 801/* A git diff has explicit new/delete information, so we don't guess */ 802 patch->is_new =0; 803 patch->is_delete =0; 804 805/* 806 * Some things may not have the old name in the 807 * rest of the headers anywhere (pure mode changes, 808 * or removing or adding empty files), so we get 809 * the default name from the header. 810 */ 811 patch->def_name =git_header_name(line, len); 812 813 line += len; 814 size -= len; 815 linenr++; 816for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) { 817static const struct opentry { 818const char*str; 819int(*fn)(const char*,struct patch *); 820} optable[] = { 821{"@@ -", gitdiff_hdrend }, 822{"--- ", gitdiff_oldname }, 823{"+++ ", gitdiff_newname }, 824{"old mode ", gitdiff_oldmode }, 825{"new mode ", gitdiff_newmode }, 826{"deleted file mode ", gitdiff_delete }, 827{"new file mode ", gitdiff_newfile }, 828{"copy from ", gitdiff_copysrc }, 829{"copy to ", gitdiff_copydst }, 830{"rename old ", gitdiff_renamesrc }, 831{"rename new ", gitdiff_renamedst }, 832{"rename from ", gitdiff_renamesrc }, 833{"rename to ", gitdiff_renamedst }, 834{"similarity index ", gitdiff_similarity }, 835{"dissimilarity index ", gitdiff_dissimilarity }, 836{"index ", gitdiff_index }, 837{"", gitdiff_unrecognized }, 838}; 839int i; 840 841 len =linelen(line, size); 842if(!len || line[len-1] !='\n') 843break; 844for(i =0; i <ARRAY_SIZE(optable); i++) { 845const struct opentry *p = optable + i; 846int oplen =strlen(p->str); 847if(len < oplen ||memcmp(p->str, line, oplen)) 848continue; 849if(p->fn(line + oplen, patch) <0) 850return offset; 851break; 852} 853} 854 855return offset; 856} 857 858static intparse_num(const char*line,unsigned long*p) 859{ 860char*ptr; 861 862if(!isdigit(*line)) 863return0; 864*p =strtoul(line, &ptr,10); 865return ptr - line; 866} 867 868static intparse_range(const char*line,int len,int offset,const char*expect, 869unsigned long*p1,unsigned long*p2) 870{ 871int digits, ex; 872 873if(offset <0|| offset >= len) 874return-1; 875 line += offset; 876 len -= offset; 877 878 digits =parse_num(line, p1); 879if(!digits) 880return-1; 881 882 offset += digits; 883 line += digits; 884 len -= digits; 885 886*p2 =1; 887if(*line ==',') { 888 digits =parse_num(line+1, p2); 889if(!digits) 890return-1; 891 892 offset += digits+1; 893 line += digits+1; 894 len -= digits+1; 895} 896 897 ex =strlen(expect); 898if(ex > len) 899return-1; 900if(memcmp(line, expect, ex)) 901return-1; 902 903return offset + ex; 904} 905 906static voidrecount_diff(char*line,int size,struct fragment *fragment) 907{ 908int oldlines =0, newlines =0, ret =0; 909 910if(size <1) { 911warning("recount: ignore empty hunk"); 912return; 913} 914 915for(;;) { 916int len =linelen(line, size); 917 size -= len; 918 line += len; 919 920if(size <1) 921break; 922 923switch(*line) { 924case' ':case'\n': 925 newlines++; 926/* fall through */ 927case'-': 928 oldlines++; 929continue; 930case'+': 931 newlines++; 932continue; 933case'\\': 934continue; 935case'@': 936 ret = size <3||prefixcmp(line,"@@ "); 937break; 938case'd': 939 ret = size <5||prefixcmp(line,"diff "); 940break; 941default: 942 ret = -1; 943break; 944} 945if(ret) { 946warning("recount: unexpected line: %.*s", 947(int)linelen(line, size), line); 948return; 949} 950break; 951} 952 fragment->oldlines = oldlines; 953 fragment->newlines = newlines; 954} 955 956/* 957 * Parse a unified diff fragment header of the 958 * form "@@ -a,b +c,d @@" 959 */ 960static intparse_fragment_header(char*line,int len,struct fragment *fragment) 961{ 962int offset; 963 964if(!len || line[len-1] !='\n') 965return-1; 966 967/* Figure out the number of lines in a fragment */ 968 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines); 969 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines); 970 971return offset; 972} 973 974static intfind_header(char*line,unsigned long size,int*hdrsize,struct patch *patch) 975{ 976unsigned long offset, len; 977 978 patch->is_toplevel_relative =0; 979 patch->is_rename = patch->is_copy =0; 980 patch->is_new = patch->is_delete = -1; 981 patch->old_mode = patch->new_mode =0; 982 patch->old_name = patch->new_name = NULL; 983for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) { 984unsigned long nextlen; 985 986 len =linelen(line, size); 987if(!len) 988break; 989 990/* Testing this early allows us to take a few shortcuts.. */ 991if(len <6) 992continue; 993 994/* 995 * Make sure we don't find any unconnected patch fragments. 996 * That's a sign that we didn't find a header, and that a 997 * patch has become corrupted/broken up. 998 */ 999if(!memcmp("@@ -", line,4)) {1000struct fragment dummy;1001if(parse_fragment_header(line, len, &dummy) <0)1002continue;1003die("patch fragment without header at line%d: %.*s",1004 linenr, (int)len-1, line);1005}10061007if(size < len +6)1008break;10091010/*1011 * Git patch? It might not have a real patch, just a rename1012 * or mode change, so we handle that specially1013 */1014if(!memcmp("diff --git ", line,11)) {1015int git_hdr_len =parse_git_header(line, len, size, patch);1016if(git_hdr_len <= len)1017continue;1018if(!patch->old_name && !patch->new_name) {1019if(!patch->def_name)1020die("git diff header lacks filename information (line%d)", linenr);1021 patch->old_name = patch->new_name = patch->def_name;1022}1023 patch->is_toplevel_relative =1;1024*hdrsize = git_hdr_len;1025return offset;1026}10271028/* --- followed by +++ ? */1029if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4))1030continue;10311032/*1033 * We only accept unified patches, so we want it to1034 * at least have "@@ -a,b +c,d @@\n", which is 14 chars1035 * minimum ("@@ -0,0 +1 @@\n" is the shortest).1036 */1037 nextlen =linelen(line + len, size - len);1038if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4))1039continue;10401041/* Ok, we'll consider it a patch */1042parse_traditional_patch(line, line+len, patch);1043*hdrsize = len + nextlen;1044 linenr +=2;1045return offset;1046}1047return-1;1048}10491050static voidcheck_whitespace(const char*line,int len,unsigned ws_rule)1051{1052char*err;1053unsigned result =ws_check(line +1, len -1, ws_rule);1054if(!result)1055return;10561057 whitespace_error++;1058if(squelch_whitespace_errors &&1059 squelch_whitespace_errors < whitespace_error)1060;1061else{1062 err =whitespace_error_string(result);1063fprintf(stderr,"%s:%d:%s.\n%.*s\n",1064 patch_input_file, linenr, err, len -2, line +1);1065free(err);1066}1067}10681069/*1070 * Parse a unified diff. Note that this really needs to parse each1071 * fragment separately, since the only way to know the difference1072 * between a "---" that is part of a patch, and a "---" that starts1073 * the next patch is to look at the line counts..1074 */1075static intparse_fragment(char*line,unsigned long size,1076struct patch *patch,struct fragment *fragment)1077{1078int added, deleted;1079int len =linelen(line, size), offset;1080unsigned long oldlines, newlines;1081unsigned long leading, trailing;10821083 offset =parse_fragment_header(line, len, fragment);1084if(offset <0)1085return-1;1086if(offset >0&& patch->recount)1087recount_diff(line + offset, size - offset, fragment);1088 oldlines = fragment->oldlines;1089 newlines = fragment->newlines;1090 leading =0;1091 trailing =0;10921093/* Parse the thing.. */1094 line += len;1095 size -= len;1096 linenr++;1097 added = deleted =0;1098for(offset = len;10990< size;1100 offset += len, size -= len, line += len, linenr++) {1101if(!oldlines && !newlines)1102break;1103 len =linelen(line, size);1104if(!len || line[len-1] !='\n')1105return-1;1106switch(*line) {1107default:1108return-1;1109case'\n':/* newer GNU diff, an empty context line */1110case' ':1111 oldlines--;1112 newlines--;1113if(!deleted && !added)1114 leading++;1115 trailing++;1116break;1117case'-':1118if(apply_in_reverse &&1119 ws_error_action != nowarn_ws_error)1120check_whitespace(line, len, patch->ws_rule);1121 deleted++;1122 oldlines--;1123 trailing =0;1124break;1125case'+':1126if(!apply_in_reverse &&1127 ws_error_action != nowarn_ws_error)1128check_whitespace(line, len, patch->ws_rule);1129 added++;1130 newlines--;1131 trailing =0;1132break;11331134/*1135 * We allow "\ No newline at end of file". Depending1136 * on locale settings when the patch was produced we1137 * don't know what this line looks like. The only1138 * thing we do know is that it begins with "\ ".1139 * Checking for 12 is just for sanity check -- any1140 * l10n of "\ No newline..." is at least that long.1141 */1142case'\\':1143if(len <12||memcmp(line,"\\",2))1144return-1;1145break;1146}1147}1148if(oldlines || newlines)1149return-1;1150 fragment->leading = leading;1151 fragment->trailing = trailing;11521153/*1154 * If a fragment ends with an incomplete line, we failed to include1155 * it in the above loop because we hit oldlines == newlines == 01156 * before seeing it.1157 */1158if(12< size && !memcmp(line,"\\",2))1159 offset +=linelen(line, size);11601161 patch->lines_added += added;1162 patch->lines_deleted += deleted;11631164if(0< patch->is_new && oldlines)1165returnerror("new file depends on old contents");1166if(0< patch->is_delete && newlines)1167returnerror("deleted file still has contents");1168return offset;1169}11701171static intparse_single_patch(char*line,unsigned long size,struct patch *patch)1172{1173unsigned long offset =0;1174unsigned long oldlines =0, newlines =0, context =0;1175struct fragment **fragp = &patch->fragments;11761177while(size >4&& !memcmp(line,"@@ -",4)) {1178struct fragment *fragment;1179int len;11801181 fragment =xcalloc(1,sizeof(*fragment));1182 len =parse_fragment(line, size, patch, fragment);1183if(len <=0)1184die("corrupt patch at line%d", linenr);1185 fragment->patch = line;1186 fragment->size = len;1187 oldlines += fragment->oldlines;1188 newlines += fragment->newlines;1189 context += fragment->leading + fragment->trailing;11901191*fragp = fragment;1192 fragp = &fragment->next;11931194 offset += len;1195 line += len;1196 size -= len;1197}11981199/*1200 * If something was removed (i.e. we have old-lines) it cannot1201 * be creation, and if something was added it cannot be1202 * deletion. However, the reverse is not true; --unified=01203 * patches that only add are not necessarily creation even1204 * though they do not have any old lines, and ones that only1205 * delete are not necessarily deletion.1206 *1207 * Unfortunately, a real creation/deletion patch do _not_ have1208 * any context line by definition, so we cannot safely tell it1209 * apart with --unified=0 insanity. At least if the patch has1210 * more than one hunk it is not creation or deletion.1211 */1212if(patch->is_new <0&&1213(oldlines || (patch->fragments && patch->fragments->next)))1214 patch->is_new =0;1215if(patch->is_delete <0&&1216(newlines || (patch->fragments && patch->fragments->next)))1217 patch->is_delete =0;12181219if(0< patch->is_new && oldlines)1220die("new file%sdepends on old contents", patch->new_name);1221if(0< patch->is_delete && newlines)1222die("deleted file%sstill has contents", patch->old_name);1223if(!patch->is_delete && !newlines && context)1224fprintf(stderr,"** warning: file%sbecomes empty but "1225"is not deleted\n", patch->new_name);12261227return offset;1228}12291230staticinlineintmetadata_changes(struct patch *patch)1231{1232return patch->is_rename >0||1233 patch->is_copy >0||1234 patch->is_new >0||1235 patch->is_delete ||1236(patch->old_mode && patch->new_mode &&1237 patch->old_mode != patch->new_mode);1238}12391240static char*inflate_it(const void*data,unsigned long size,1241unsigned long inflated_size)1242{1243 z_stream stream;1244void*out;1245int st;12461247memset(&stream,0,sizeof(stream));12481249 stream.next_in = (unsigned char*)data;1250 stream.avail_in = size;1251 stream.next_out = out =xmalloc(inflated_size);1252 stream.avail_out = inflated_size;1253inflateInit(&stream);1254 st =inflate(&stream, Z_FINISH);1255if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1256free(out);1257return NULL;1258}1259return out;1260}12611262static struct fragment *parse_binary_hunk(char**buf_p,1263unsigned long*sz_p,1264int*status_p,1265int*used_p)1266{1267/*1268 * Expect a line that begins with binary patch method ("literal"1269 * or "delta"), followed by the length of data before deflating.1270 * a sequence of 'length-byte' followed by base-85 encoded data1271 * should follow, terminated by a newline.1272 *1273 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1274 * and we would limit the patch line to 66 characters,1275 * so one line can fit up to 13 groups that would decode1276 * to 52 bytes max. The length byte 'A'-'Z' corresponds1277 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1278 */1279int llen, used;1280unsigned long size = *sz_p;1281char*buffer = *buf_p;1282int patch_method;1283unsigned long origlen;1284char*data = NULL;1285int hunk_size =0;1286struct fragment *frag;12871288 llen =linelen(buffer, size);1289 used = llen;12901291*status_p =0;12921293if(!prefixcmp(buffer,"delta ")) {1294 patch_method = BINARY_DELTA_DEFLATED;1295 origlen =strtoul(buffer +6, NULL,10);1296}1297else if(!prefixcmp(buffer,"literal ")) {1298 patch_method = BINARY_LITERAL_DEFLATED;1299 origlen =strtoul(buffer +8, NULL,10);1300}1301else1302return NULL;13031304 linenr++;1305 buffer += llen;1306while(1) {1307int byte_length, max_byte_length, newsize;1308 llen =linelen(buffer, size);1309 used += llen;1310 linenr++;1311if(llen ==1) {1312/* consume the blank line */1313 buffer++;1314 size--;1315break;1316}1317/*1318 * Minimum line is "A00000\n" which is 7-byte long,1319 * and the line length must be multiple of 5 plus 2.1320 */1321if((llen <7) || (llen-2) %5)1322goto corrupt;1323 max_byte_length = (llen -2) /5*4;1324 byte_length = *buffer;1325if('A'<= byte_length && byte_length <='Z')1326 byte_length = byte_length -'A'+1;1327else if('a'<= byte_length && byte_length <='z')1328 byte_length = byte_length -'a'+27;1329else1330goto corrupt;1331/* if the input length was not multiple of 4, we would1332 * have filler at the end but the filler should never1333 * exceed 3 bytes1334 */1335if(max_byte_length < byte_length ||1336 byte_length <= max_byte_length -4)1337goto corrupt;1338 newsize = hunk_size + byte_length;1339 data =xrealloc(data, newsize);1340if(decode_85(data + hunk_size, buffer +1, byte_length))1341goto corrupt;1342 hunk_size = newsize;1343 buffer += llen;1344 size -= llen;1345}13461347 frag =xcalloc(1,sizeof(*frag));1348 frag->patch =inflate_it(data, hunk_size, origlen);1349if(!frag->patch)1350goto corrupt;1351free(data);1352 frag->size = origlen;1353*buf_p = buffer;1354*sz_p = size;1355*used_p = used;1356 frag->binary_patch_method = patch_method;1357return frag;13581359 corrupt:1360free(data);1361*status_p = -1;1362error("corrupt binary patch at line%d: %.*s",1363 linenr-1, llen-1, buffer);1364return NULL;1365}13661367static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1368{1369/*1370 * We have read "GIT binary patch\n"; what follows is a line1371 * that says the patch method (currently, either "literal" or1372 * "delta") and the length of data before deflating; a1373 * sequence of 'length-byte' followed by base-85 encoded data1374 * follows.1375 *1376 * When a binary patch is reversible, there is another binary1377 * hunk in the same format, starting with patch method (either1378 * "literal" or "delta") with the length of data, and a sequence1379 * of length-byte + base-85 encoded data, terminated with another1380 * empty line. This data, when applied to the postimage, produces1381 * the preimage.1382 */1383struct fragment *forward;1384struct fragment *reverse;1385int status;1386int used, used_1;13871388 forward =parse_binary_hunk(&buffer, &size, &status, &used);1389if(!forward && !status)1390/* there has to be one hunk (forward hunk) */1391returnerror("unrecognized binary patch at line%d", linenr-1);1392if(status)1393/* otherwise we already gave an error message */1394return status;13951396 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1397if(reverse)1398 used += used_1;1399else if(status) {1400/*1401 * Not having reverse hunk is not an error, but having1402 * a corrupt reverse hunk is.1403 */1404free((void*) forward->patch);1405free(forward);1406return status;1407}1408 forward->next = reverse;1409 patch->fragments = forward;1410 patch->is_binary =1;1411return used;1412}14131414static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1415{1416int hdrsize, patchsize;1417int offset =find_header(buffer, size, &hdrsize, patch);14181419if(offset <0)1420return offset;14211422 patch->ws_rule =whitespace_rule(patch->new_name1423? patch->new_name1424: patch->old_name);14251426 patchsize =parse_single_patch(buffer + offset + hdrsize,1427 size - offset - hdrsize, patch);14281429if(!patchsize) {1430static const char*binhdr[] = {1431"Binary files ",1432"Files ",1433 NULL,1434};1435static const char git_binary[] ="GIT binary patch\n";1436int i;1437int hd = hdrsize + offset;1438unsigned long llen =linelen(buffer + hd, size - hd);14391440if(llen ==sizeof(git_binary) -1&&1441!memcmp(git_binary, buffer + hd, llen)) {1442int used;1443 linenr++;1444 used =parse_binary(buffer + hd + llen,1445 size - hd - llen, patch);1446if(used)1447 patchsize = used + llen;1448else1449 patchsize =0;1450}1451else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1452for(i =0; binhdr[i]; i++) {1453int len =strlen(binhdr[i]);1454if(len < size - hd &&1455!memcmp(binhdr[i], buffer + hd, len)) {1456 linenr++;1457 patch->is_binary =1;1458 patchsize = llen;1459break;1460}1461}1462}14631464/* Empty patch cannot be applied if it is a text patch1465 * without metadata change. A binary patch appears1466 * empty to us here.1467 */1468if((apply || check) &&1469(!patch->is_binary && !metadata_changes(patch)))1470die("patch with only garbage at line%d", linenr);1471}14721473return offset + hdrsize + patchsize;1474}14751476#define swap(a,b) myswap((a),(b),sizeof(a))14771478#define myswap(a, b, size) do { \1479 unsigned char mytmp[size]; \1480 memcpy(mytmp, &a, size); \1481 memcpy(&a, &b, size); \1482 memcpy(&b, mytmp, size); \1483} while (0)14841485static voidreverse_patches(struct patch *p)1486{1487for(; p; p = p->next) {1488struct fragment *frag = p->fragments;14891490swap(p->new_name, p->old_name);1491swap(p->new_mode, p->old_mode);1492swap(p->is_new, p->is_delete);1493swap(p->lines_added, p->lines_deleted);1494swap(p->old_sha1_prefix, p->new_sha1_prefix);14951496for(; frag; frag = frag->next) {1497swap(frag->newpos, frag->oldpos);1498swap(frag->newlines, frag->oldlines);1499}1500}1501}15021503static const char pluses[] =1504"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";1505static const char minuses[]=1506"----------------------------------------------------------------------";15071508static voidshow_stats(struct patch *patch)1509{1510struct strbuf qname;1511char*cp = patch->new_name ? patch->new_name : patch->old_name;1512int max, add, del;15131514strbuf_init(&qname,0);1515quote_c_style(cp, &qname, NULL,0);15161517/*1518 * "scale" the filename1519 */1520 max = max_len;1521if(max >50)1522 max =50;15231524if(qname.len > max) {1525 cp =strchr(qname.buf + qname.len +3- max,'/');1526if(!cp)1527 cp = qname.buf + qname.len +3- max;1528strbuf_splice(&qname,0, cp - qname.buf,"...",3);1529}15301531if(patch->is_binary) {1532printf(" %-*s | Bin\n", max, qname.buf);1533strbuf_release(&qname);1534return;1535}15361537printf(" %-*s |", max, qname.buf);1538strbuf_release(&qname);15391540/*1541 * scale the add/delete1542 */1543 max = max + max_change >70?70- max : max_change;1544 add = patch->lines_added;1545 del = patch->lines_deleted;15461547if(max_change >0) {1548int total = ((add + del) * max + max_change /2) / max_change;1549 add = (add * max + max_change /2) / max_change;1550 del = total - add;1551}1552printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,1553 add, pluses, del, minuses);1554}15551556static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)1557{1558switch(st->st_mode & S_IFMT) {1559case S_IFLNK:1560strbuf_grow(buf, st->st_size);1561if(readlink(path, buf->buf, st->st_size) != st->st_size)1562return-1;1563strbuf_setlen(buf, st->st_size);1564return0;1565case S_IFREG:1566if(strbuf_read_file(buf, path, st->st_size) != st->st_size)1567returnerror("unable to open or read%s", path);1568convert_to_git(path, buf->buf, buf->len, buf,0);1569return0;1570default:1571return-1;1572}1573}15741575static voidupdate_pre_post_images(struct image *preimage,1576struct image *postimage,1577char*buf,1578size_t len)1579{1580int i, ctx;1581char*new, *old, *fixed;1582struct image fixed_preimage;15831584/*1585 * Update the preimage with whitespace fixes. Note that we1586 * are not losing preimage->buf -- apply_one_fragment() will1587 * free "oldlines".1588 */1589prepare_image(&fixed_preimage, buf, len,1);1590assert(fixed_preimage.nr == preimage->nr);1591for(i =0; i < preimage->nr; i++)1592 fixed_preimage.line[i].flag = preimage->line[i].flag;1593free(preimage->line_allocated);1594*preimage = fixed_preimage;15951596/*1597 * Adjust the common context lines in postimage, in place.1598 * This is possible because whitespace fixing does not make1599 * the string grow.1600 */1601new= old = postimage->buf;1602 fixed = preimage->buf;1603for(i = ctx =0; i < postimage->nr; i++) {1604size_t len = postimage->line[i].len;1605if(!(postimage->line[i].flag & LINE_COMMON)) {1606/* an added line -- no counterparts in preimage */1607memmove(new, old, len);1608 old += len;1609new+= len;1610continue;1611}16121613/* a common context -- skip it in the original postimage */1614 old += len;16151616/* and find the corresponding one in the fixed preimage */1617while(ctx < preimage->nr &&1618!(preimage->line[ctx].flag & LINE_COMMON)) {1619 fixed += preimage->line[ctx].len;1620 ctx++;1621}1622if(preimage->nr <= ctx)1623die("oops");16241625/* and copy it in, while fixing the line length */1626 len = preimage->line[ctx].len;1627memcpy(new, fixed, len);1628new+= len;1629 fixed += len;1630 postimage->line[i].len = len;1631 ctx++;1632}16331634/* Fix the length of the whole thing */1635 postimage->len =new- postimage->buf;1636}16371638static intmatch_fragment(struct image *img,1639struct image *preimage,1640struct image *postimage,1641unsigned longtry,1642int try_lno,1643unsigned ws_rule,1644int match_beginning,int match_end)1645{1646int i;1647char*fixed_buf, *buf, *orig, *target;16481649if(preimage->nr + try_lno > img->nr)1650return0;16511652if(match_beginning && try_lno)1653return0;16541655if(match_end && preimage->nr + try_lno != img->nr)1656return0;16571658/* Quick hash check */1659for(i =0; i < preimage->nr; i++)1660if(preimage->line[i].hash != img->line[try_lno + i].hash)1661return0;16621663/*1664 * Do we have an exact match? If we were told to match1665 * at the end, size must be exactly at try+fragsize,1666 * otherwise try+fragsize must be still within the preimage,1667 * and either case, the old piece should match the preimage1668 * exactly.1669 */1670if((match_end1671? (try+ preimage->len == img->len)1672: (try+ preimage->len <= img->len)) &&1673!memcmp(img->buf +try, preimage->buf, preimage->len))1674return1;16751676if(ws_error_action != correct_ws_error)1677return0;16781679/*1680 * The hunk does not apply byte-by-byte, but the hash says1681 * it might with whitespace fuzz.1682 */1683 fixed_buf =xmalloc(preimage->len +1);1684 buf = fixed_buf;1685 orig = preimage->buf;1686 target = img->buf +try;1687for(i =0; i < preimage->nr; i++) {1688size_t fixlen;/* length after fixing the preimage */1689size_t oldlen = preimage->line[i].len;1690size_t tgtlen = img->line[try_lno + i].len;1691size_t tgtfixlen;/* length after fixing the target line */1692char tgtfixbuf[1024], *tgtfix;1693int match;16941695/* Try fixing the line in the preimage */1696 fixlen =ws_fix_copy(buf, orig, oldlen, ws_rule, NULL);16971698/* Try fixing the line in the target */1699if(sizeof(tgtfixbuf) < tgtlen)1700 tgtfix = tgtfixbuf;1701else1702 tgtfix =xmalloc(tgtlen);1703 tgtfixlen =ws_fix_copy(tgtfix, target, tgtlen, ws_rule, NULL);17041705/*1706 * If they match, either the preimage was based on1707 * a version before our tree fixed whitespace breakage,1708 * or we are lacking a whitespace-fix patch the tree1709 * the preimage was based on already had (i.e. target1710 * has whitespace breakage, the preimage doesn't).1711 * In either case, we are fixing the whitespace breakages1712 * so we might as well take the fix together with their1713 * real change.1714 */1715 match = (tgtfixlen == fixlen && !memcmp(tgtfix, buf, fixlen));17161717if(tgtfix != tgtfixbuf)1718free(tgtfix);1719if(!match)1720goto unmatch_exit;17211722 orig += oldlen;1723 buf += fixlen;1724 target += tgtlen;1725}17261727/*1728 * Yes, the preimage is based on an older version that still1729 * has whitespace breakages unfixed, and fixing them makes the1730 * hunk match. Update the context lines in the postimage.1731 */1732update_pre_post_images(preimage, postimage,1733 fixed_buf, buf - fixed_buf);1734return1;17351736 unmatch_exit:1737free(fixed_buf);1738return0;1739}17401741static intfind_pos(struct image *img,1742struct image *preimage,1743struct image *postimage,1744int line,1745unsigned ws_rule,1746int match_beginning,int match_end)1747{1748int i;1749unsigned long backwards, forwards,try;1750int backwards_lno, forwards_lno, try_lno;17511752if(preimage->nr > img->nr)1753return-1;17541755/*1756 * If match_begining or match_end is specified, there is no1757 * point starting from a wrong line that will never match and1758 * wander around and wait for a match at the specified end.1759 */1760if(match_beginning)1761 line =0;1762else if(match_end)1763 line = img->nr - preimage->nr;17641765if(line > img->nr)1766 line = img->nr;17671768try=0;1769for(i =0; i < line; i++)1770try+= img->line[i].len;17711772/*1773 * There's probably some smart way to do this, but I'll leave1774 * that to the smart and beautiful people. I'm simple and stupid.1775 */1776 backwards =try;1777 backwards_lno = line;1778 forwards =try;1779 forwards_lno = line;1780 try_lno = line;17811782for(i =0; ; i++) {1783if(match_fragment(img, preimage, postimage,1784try, try_lno, ws_rule,1785 match_beginning, match_end))1786return try_lno;17871788 again:1789if(backwards_lno ==0&& forwards_lno == img->nr)1790break;17911792if(i &1) {1793if(backwards_lno ==0) {1794 i++;1795goto again;1796}1797 backwards_lno--;1798 backwards -= img->line[backwards_lno].len;1799try= backwards;1800 try_lno = backwards_lno;1801}else{1802if(forwards_lno == img->nr) {1803 i++;1804goto again;1805}1806 forwards += img->line[forwards_lno].len;1807 forwards_lno++;1808try= forwards;1809 try_lno = forwards_lno;1810}18111812}1813return-1;1814}18151816static voidremove_first_line(struct image *img)1817{1818 img->buf += img->line[0].len;1819 img->len -= img->line[0].len;1820 img->line++;1821 img->nr--;1822}18231824static voidremove_last_line(struct image *img)1825{1826 img->len -= img->line[--img->nr].len;1827}18281829static voidupdate_image(struct image *img,1830int applied_pos,1831struct image *preimage,1832struct image *postimage)1833{1834/*1835 * remove the copy of preimage at offset in img1836 * and replace it with postimage1837 */1838int i, nr;1839size_t remove_count, insert_count, applied_at =0;1840char*result;18411842for(i =0; i < applied_pos; i++)1843 applied_at += img->line[i].len;18441845 remove_count =0;1846for(i =0; i < preimage->nr; i++)1847 remove_count += img->line[applied_pos + i].len;1848 insert_count = postimage->len;18491850/* Adjust the contents */1851 result =xmalloc(img->len + insert_count - remove_count +1);1852memcpy(result, img->buf, applied_at);1853memcpy(result + applied_at, postimage->buf, postimage->len);1854memcpy(result + applied_at + postimage->len,1855 img->buf + (applied_at + remove_count),1856 img->len - (applied_at + remove_count));1857free(img->buf);1858 img->buf = result;1859 img->len += insert_count - remove_count;1860 result[img->len] ='\0';18611862/* Adjust the line table */1863 nr = img->nr + postimage->nr - preimage->nr;1864if(preimage->nr < postimage->nr) {1865/*1866 * NOTE: this knows that we never call remove_first_line()1867 * on anything other than pre/post image.1868 */1869 img->line =xrealloc(img->line, nr *sizeof(*img->line));1870 img->line_allocated = img->line;1871}1872if(preimage->nr != postimage->nr)1873memmove(img->line + applied_pos + postimage->nr,1874 img->line + applied_pos + preimage->nr,1875(img->nr - (applied_pos + preimage->nr)) *1876sizeof(*img->line));1877memcpy(img->line + applied_pos,1878 postimage->line,1879 postimage->nr *sizeof(*img->line));1880 img->nr = nr;1881}18821883static intapply_one_fragment(struct image *img,struct fragment *frag,1884int inaccurate_eof,unsigned ws_rule)1885{1886int match_beginning, match_end;1887const char*patch = frag->patch;1888int size = frag->size;1889char*old, *new, *oldlines, *newlines;1890int new_blank_lines_at_end =0;1891unsigned long leading, trailing;1892int pos, applied_pos;1893struct image preimage;1894struct image postimage;18951896memset(&preimage,0,sizeof(preimage));1897memset(&postimage,0,sizeof(postimage));1898 oldlines =xmalloc(size);1899 newlines =xmalloc(size);19001901 old = oldlines;1902new= newlines;1903while(size >0) {1904char first;1905int len =linelen(patch, size);1906int plen, added;1907int added_blank_line =0;19081909if(!len)1910break;19111912/*1913 * "plen" is how much of the line we should use for1914 * the actual patch data. Normally we just remove the1915 * first character on the line, but if the line is1916 * followed by "\ No newline", then we also remove the1917 * last one (which is the newline, of course).1918 */1919 plen = len -1;1920if(len < size && patch[len] =='\\')1921 plen--;1922 first = *patch;1923if(apply_in_reverse) {1924if(first =='-')1925 first ='+';1926else if(first =='+')1927 first ='-';1928}19291930switch(first) {1931case'\n':1932/* Newer GNU diff, empty context line */1933if(plen <0)1934/* ... followed by '\No newline'; nothing */1935break;1936*old++ ='\n';1937*new++ ='\n';1938add_line_info(&preimage,"\n",1, LINE_COMMON);1939add_line_info(&postimage,"\n",1, LINE_COMMON);1940break;1941case' ':1942case'-':1943memcpy(old, patch +1, plen);1944add_line_info(&preimage, old, plen,1945(first ==' '? LINE_COMMON :0));1946 old += plen;1947if(first =='-')1948break;1949/* Fall-through for ' ' */1950case'+':1951/* --no-add does not add new lines */1952if(first =='+'&& no_add)1953break;19541955if(first !='+'||1956!whitespace_error ||1957 ws_error_action != correct_ws_error) {1958memcpy(new, patch +1, plen);1959 added = plen;1960}1961else{1962 added =ws_fix_copy(new, patch +1, plen, ws_rule, &applied_after_fixing_ws);1963}1964add_line_info(&postimage,new, added,1965(first =='+'?0: LINE_COMMON));1966new+= added;1967if(first =='+'&&1968 added ==1&&new[-1] =='\n')1969 added_blank_line =1;1970break;1971case'@':case'\\':1972/* Ignore it, we already handled it */1973break;1974default:1975if(apply_verbosely)1976error("invalid start of line: '%c'", first);1977return-1;1978}1979if(added_blank_line)1980 new_blank_lines_at_end++;1981else1982 new_blank_lines_at_end =0;1983 patch += len;1984 size -= len;1985}1986if(inaccurate_eof &&1987 old > oldlines && old[-1] =='\n'&&1988new> newlines &&new[-1] =='\n') {1989 old--;1990new--;1991}19921993 leading = frag->leading;1994 trailing = frag->trailing;19951996/*1997 * A hunk to change lines at the beginning would begin with1998 * @@ -1,L +N,M @@1999 * but we need to be careful. -U0 that inserts before the second2000 * line also has this pattern.2001 *2002 * And a hunk to add to an empty file would begin with2003 * @@ -0,0 +N,M @@2004 *2005 * In other words, a hunk that is (frag->oldpos <= 1) with or2006 * without leading context must match at the beginning.2007 */2008 match_beginning = (!frag->oldpos ||2009(frag->oldpos ==1&& !unidiff_zero));20102011/*2012 * A hunk without trailing lines must match at the end.2013 * However, we simply cannot tell if a hunk must match end2014 * from the lack of trailing lines if the patch was generated2015 * with unidiff without any context.2016 */2017 match_end = !unidiff_zero && !trailing;20182019 pos = frag->newpos ? (frag->newpos -1) :0;2020 preimage.buf = oldlines;2021 preimage.len = old - oldlines;2022 postimage.buf = newlines;2023 postimage.len =new- newlines;2024 preimage.line = preimage.line_allocated;2025 postimage.line = postimage.line_allocated;20262027for(;;) {20282029 applied_pos =find_pos(img, &preimage, &postimage, pos,2030 ws_rule, match_beginning, match_end);20312032if(applied_pos >=0)2033break;20342035/* Am I at my context limits? */2036if((leading <= p_context) && (trailing <= p_context))2037break;2038if(match_beginning || match_end) {2039 match_beginning = match_end =0;2040continue;2041}20422043/*2044 * Reduce the number of context lines; reduce both2045 * leading and trailing if they are equal otherwise2046 * just reduce the larger context.2047 */2048if(leading >= trailing) {2049remove_first_line(&preimage);2050remove_first_line(&postimage);2051 pos--;2052 leading--;2053}2054if(trailing > leading) {2055remove_last_line(&preimage);2056remove_last_line(&postimage);2057 trailing--;2058}2059}20602061if(applied_pos >=0) {2062if(ws_error_action == correct_ws_error &&2063 new_blank_lines_at_end &&2064 postimage.nr + applied_pos == img->nr) {2065/*2066 * If the patch application adds blank lines2067 * at the end, and if the patch applies at the2068 * end of the image, remove those added blank2069 * lines.2070 */2071while(new_blank_lines_at_end--)2072remove_last_line(&postimage);2073}20742075/*2076 * Warn if it was necessary to reduce the number2077 * of context lines.2078 */2079if((leading != frag->leading) ||2080(trailing != frag->trailing))2081fprintf(stderr,"Context reduced to (%ld/%ld)"2082" to apply fragment at%d\n",2083 leading, trailing, applied_pos+1);2084update_image(img, applied_pos, &preimage, &postimage);2085}else{2086if(apply_verbosely)2087error("while searching for:\n%.*s",2088(int)(old - oldlines), oldlines);2089}20902091free(oldlines);2092free(newlines);2093free(preimage.line_allocated);2094free(postimage.line_allocated);20952096return(applied_pos <0);2097}20982099static intapply_binary_fragment(struct image *img,struct patch *patch)2100{2101struct fragment *fragment = patch->fragments;2102unsigned long len;2103void*dst;21042105/* Binary patch is irreversible without the optional second hunk */2106if(apply_in_reverse) {2107if(!fragment->next)2108returnerror("cannot reverse-apply a binary patch "2109"without the reverse hunk to '%s'",2110 patch->new_name2111? patch->new_name : patch->old_name);2112 fragment = fragment->next;2113}2114switch(fragment->binary_patch_method) {2115case BINARY_DELTA_DEFLATED:2116 dst =patch_delta(img->buf, img->len, fragment->patch,2117 fragment->size, &len);2118if(!dst)2119return-1;2120clear_image(img);2121 img->buf = dst;2122 img->len = len;2123return0;2124case BINARY_LITERAL_DEFLATED:2125clear_image(img);2126 img->len = fragment->size;2127 img->buf =xmalloc(img->len+1);2128memcpy(img->buf, fragment->patch, img->len);2129 img->buf[img->len] ='\0';2130return0;2131}2132return-1;2133}21342135static intapply_binary(struct image *img,struct patch *patch)2136{2137const char*name = patch->old_name ? patch->old_name : patch->new_name;2138unsigned char sha1[20];21392140/*2141 * For safety, we require patch index line to contain2142 * full 40-byte textual SHA1 for old and new, at least for now.2143 */2144if(strlen(patch->old_sha1_prefix) !=40||2145strlen(patch->new_sha1_prefix) !=40||2146get_sha1_hex(patch->old_sha1_prefix, sha1) ||2147get_sha1_hex(patch->new_sha1_prefix, sha1))2148returnerror("cannot apply binary patch to '%s' "2149"without full index line", name);21502151if(patch->old_name) {2152/*2153 * See if the old one matches what the patch2154 * applies to.2155 */2156hash_sha1_file(img->buf, img->len, blob_type, sha1);2157if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2158returnerror("the patch applies to '%s' (%s), "2159"which does not match the "2160"current contents.",2161 name,sha1_to_hex(sha1));2162}2163else{2164/* Otherwise, the old one must be empty. */2165if(img->len)2166returnerror("the patch applies to an empty "2167"'%s' but it is not empty", name);2168}21692170get_sha1_hex(patch->new_sha1_prefix, sha1);2171if(is_null_sha1(sha1)) {2172clear_image(img);2173return0;/* deletion patch */2174}21752176if(has_sha1_file(sha1)) {2177/* We already have the postimage */2178enum object_type type;2179unsigned long size;2180char*result;21812182 result =read_sha1_file(sha1, &type, &size);2183if(!result)2184returnerror("the necessary postimage%sfor "2185"'%s' cannot be read",2186 patch->new_sha1_prefix, name);2187clear_image(img);2188 img->buf = result;2189 img->len = size;2190}else{2191/*2192 * We have verified buf matches the preimage;2193 * apply the patch data to it, which is stored2194 * in the patch->fragments->{patch,size}.2195 */2196if(apply_binary_fragment(img, patch))2197returnerror("binary patch does not apply to '%s'",2198 name);21992200/* verify that the result matches */2201hash_sha1_file(img->buf, img->len, blob_type, sha1);2202if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2203returnerror("binary patch to '%s' creates incorrect result (expecting%s, got%s)",2204 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2205}22062207return0;2208}22092210static intapply_fragments(struct image *img,struct patch *patch)2211{2212struct fragment *frag = patch->fragments;2213const char*name = patch->old_name ? patch->old_name : patch->new_name;2214unsigned ws_rule = patch->ws_rule;2215unsigned inaccurate_eof = patch->inaccurate_eof;22162217if(patch->is_binary)2218returnapply_binary(img, patch);22192220while(frag) {2221if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule)) {2222error("patch failed:%s:%ld", name, frag->oldpos);2223if(!apply_with_reject)2224return-1;2225 frag->rejected =1;2226}2227 frag = frag->next;2228}2229return0;2230}22312232static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2233{2234if(!ce)2235return0;22362237if(S_ISGITLINK(ce->ce_mode)) {2238strbuf_grow(buf,100);2239strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2240}else{2241enum object_type type;2242unsigned long sz;2243char*result;22442245 result =read_sha1_file(ce->sha1, &type, &sz);2246if(!result)2247return-1;2248/* XXX read_sha1_file NUL-terminates */2249strbuf_attach(buf, result, sz, sz +1);2250}2251return0;2252}22532254static struct patch *in_fn_table(const char*name)2255{2256struct string_list_item *item;22572258if(name == NULL)2259return NULL;22602261 item =string_list_lookup(name, &fn_table);2262if(item != NULL)2263return(struct patch *)item->util;22642265return NULL;2266}22672268static voidadd_to_fn_table(struct patch *patch)2269{2270struct string_list_item *item;22712272/*2273 * Always add new_name unless patch is a deletion2274 * This should cover the cases for normal diffs,2275 * file creations and copies2276 */2277if(patch->new_name != NULL) {2278 item =string_list_insert(patch->new_name, &fn_table);2279 item->util = patch;2280}22812282/*2283 * store a failure on rename/deletion cases because2284 * later chunks shouldn't patch old names2285 */2286if((patch->new_name == NULL) || (patch->is_rename)) {2287 item =string_list_insert(patch->old_name, &fn_table);2288 item->util = (struct patch *) -1;2289}2290}22912292static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)2293{2294struct strbuf buf;2295struct image image;2296size_t len;2297char*img;2298struct patch *tpatch;22992300strbuf_init(&buf,0);23012302if(!(patch->is_copy || patch->is_rename) &&2303((tpatch =in_fn_table(patch->old_name)) != NULL)) {2304if(tpatch == (struct patch *) -1) {2305returnerror("patch%shas been renamed/deleted",2306 patch->old_name);2307}2308/* We have a patched copy in memory use that */2309strbuf_add(&buf, tpatch->result, tpatch->resultsize);2310}else if(cached) {2311if(read_file_or_gitlink(ce, &buf))2312returnerror("read of%sfailed", patch->old_name);2313}else if(patch->old_name) {2314if(S_ISGITLINK(patch->old_mode)) {2315if(ce) {2316read_file_or_gitlink(ce, &buf);2317}else{2318/*2319 * There is no way to apply subproject2320 * patch without looking at the index.2321 */2322 patch->fragments = NULL;2323}2324}else{2325if(read_old_data(st, patch->old_name, &buf))2326returnerror("read of%sfailed", patch->old_name);2327}2328}23292330 img =strbuf_detach(&buf, &len);2331prepare_image(&image, img, len, !patch->is_binary);23322333if(apply_fragments(&image, patch) <0)2334return-1;/* note with --reject this succeeds. */2335 patch->result = image.buf;2336 patch->resultsize = image.len;2337add_to_fn_table(patch);2338free(image.line_allocated);23392340if(0< patch->is_delete && patch->resultsize)2341returnerror("removal patch leaves file contents");23422343return0;2344}23452346static intcheck_to_create_blob(const char*new_name,int ok_if_exists)2347{2348struct stat nst;2349if(!lstat(new_name, &nst)) {2350if(S_ISDIR(nst.st_mode) || ok_if_exists)2351return0;2352/*2353 * A leading component of new_name might be a symlink2354 * that is going to be removed with this patch, but2355 * still pointing at somewhere that has the path.2356 * In such a case, path "new_name" does not exist as2357 * far as git is concerned.2358 */2359if(has_symlink_leading_path(strlen(new_name), new_name))2360return0;23612362returnerror("%s: already exists in working directory", new_name);2363}2364else if((errno != ENOENT) && (errno != ENOTDIR))2365returnerror("%s:%s", new_name,strerror(errno));2366return0;2367}23682369static intverify_index_match(struct cache_entry *ce,struct stat *st)2370{2371if(S_ISGITLINK(ce->ce_mode)) {2372if(!S_ISDIR(st->st_mode))2373return-1;2374return0;2375}2376returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID);2377}23782379static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)2380{2381const char*old_name = patch->old_name;2382struct patch *tpatch = NULL;2383int stat_ret =0;2384unsigned st_mode =0;23852386/*2387 * Make sure that we do not have local modifications from the2388 * index when we are looking at the index. Also make sure2389 * we have the preimage file to be patched in the work tree,2390 * unless --cached, which tells git to apply only in the index.2391 */2392if(!old_name)2393return0;23942395assert(patch->is_new <=0);23962397if(!(patch->is_copy || patch->is_rename) &&2398(tpatch =in_fn_table(old_name)) != NULL) {2399if(tpatch == (struct patch *) -1) {2400returnerror("%s: has been deleted/renamed", old_name);2401}2402 st_mode = tpatch->new_mode;2403}else if(!cached) {2404 stat_ret =lstat(old_name, st);2405if(stat_ret && errno != ENOENT)2406returnerror("%s:%s", old_name,strerror(errno));2407}24082409if(check_index && !tpatch) {2410int pos =cache_name_pos(old_name,strlen(old_name));2411if(pos <0) {2412if(patch->is_new <0)2413goto is_new;2414returnerror("%s: does not exist in index", old_name);2415}2416*ce = active_cache[pos];2417if(stat_ret <0) {2418struct checkout costate;2419/* checkout */2420 costate.base_dir ="";2421 costate.base_dir_len =0;2422 costate.force =0;2423 costate.quiet =0;2424 costate.not_new =0;2425 costate.refresh_cache =1;2426if(checkout_entry(*ce, &costate, NULL) ||2427lstat(old_name, st))2428return-1;2429}2430if(!cached &&verify_index_match(*ce, st))2431returnerror("%s: does not match index", old_name);2432if(cached)2433 st_mode = (*ce)->ce_mode;2434}else if(stat_ret <0) {2435if(patch->is_new <0)2436goto is_new;2437returnerror("%s:%s", old_name,strerror(errno));2438}24392440if(!cached)2441 st_mode =ce_mode_from_stat(*ce, st->st_mode);24422443if(patch->is_new <0)2444 patch->is_new =0;2445if(!patch->old_mode)2446 patch->old_mode = st_mode;2447if((st_mode ^ patch->old_mode) & S_IFMT)2448returnerror("%s: wrong type", old_name);2449if(st_mode != patch->old_mode)2450fprintf(stderr,"warning:%shas type%o, expected%o\n",2451 old_name, st_mode, patch->old_mode);2452return0;24532454 is_new:2455 patch->is_new =1;2456 patch->is_delete =0;2457 patch->old_name = NULL;2458return0;2459}24602461static intcheck_patch(struct patch *patch)2462{2463struct stat st;2464const char*old_name = patch->old_name;2465const char*new_name = patch->new_name;2466const char*name = old_name ? old_name : new_name;2467struct cache_entry *ce = NULL;2468int ok_if_exists;2469int status;24702471 patch->rejected =1;/* we will drop this after we succeed */24722473 status =check_preimage(patch, &ce, &st);2474if(status)2475return status;2476 old_name = patch->old_name;24772478if(in_fn_table(new_name) == (struct patch *) -1)2479/*2480 * A type-change diff is always split into a patch to2481 * delete old, immediately followed by a patch to2482 * create new (see diff.c::run_diff()); in such a case2483 * it is Ok that the entry to be deleted by the2484 * previous patch is still in the working tree and in2485 * the index.2486 */2487 ok_if_exists =1;2488else2489 ok_if_exists =0;24902491if(new_name &&2492((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {2493if(check_index &&2494cache_name_pos(new_name,strlen(new_name)) >=0&&2495!ok_if_exists)2496returnerror("%s: already exists in index", new_name);2497if(!cached) {2498int err =check_to_create_blob(new_name, ok_if_exists);2499if(err)2500return err;2501}2502if(!patch->new_mode) {2503if(0< patch->is_new)2504 patch->new_mode = S_IFREG |0644;2505else2506 patch->new_mode = patch->old_mode;2507}2508}25092510if(new_name && old_name) {2511int same = !strcmp(old_name, new_name);2512if(!patch->new_mode)2513 patch->new_mode = patch->old_mode;2514if((patch->old_mode ^ patch->new_mode) & S_IFMT)2515returnerror("new mode (%o) of%sdoes not match old mode (%o)%s%s",2516 patch->new_mode, new_name, patch->old_mode,2517 same ?"":" of ", same ?"": old_name);2518}25192520if(apply_data(patch, &st, ce) <0)2521returnerror("%s: patch does not apply", name);2522 patch->rejected =0;2523return0;2524}25252526static intcheck_patch_list(struct patch *patch)2527{2528int err =0;25292530while(patch) {2531if(apply_verbosely)2532say_patch_name(stderr,2533"Checking patch ", patch,"...\n");2534 err |=check_patch(patch);2535 patch = patch->next;2536}2537return err;2538}25392540/* This function tries to read the sha1 from the current index */2541static intget_current_sha1(const char*path,unsigned char*sha1)2542{2543int pos;25442545if(read_cache() <0)2546return-1;2547 pos =cache_name_pos(path,strlen(path));2548if(pos <0)2549return-1;2550hashcpy(sha1, active_cache[pos]->sha1);2551return0;2552}25532554/* Build an index that contains the just the files needed for a 3way merge */2555static voidbuild_fake_ancestor(struct patch *list,const char*filename)2556{2557struct patch *patch;2558struct index_state result = {0};2559int fd;25602561/* Once we start supporting the reverse patch, it may be2562 * worth showing the new sha1 prefix, but until then...2563 */2564for(patch = list; patch; patch = patch->next) {2565const unsigned char*sha1_ptr;2566unsigned char sha1[20];2567struct cache_entry *ce;2568const char*name;25692570 name = patch->old_name ? patch->old_name : patch->new_name;2571if(0< patch->is_new)2572continue;2573else if(get_sha1(patch->old_sha1_prefix, sha1))2574/* git diff has no index line for mode/type changes */2575if(!patch->lines_added && !patch->lines_deleted) {2576if(get_current_sha1(patch->new_name, sha1) ||2577get_current_sha1(patch->old_name, sha1))2578die("mode change for%s, which is not "2579"in current HEAD", name);2580 sha1_ptr = sha1;2581}else2582die("sha1 information is lacking or useless "2583"(%s).", name);2584else2585 sha1_ptr = sha1;25862587 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);2588if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))2589die("Could not add%sto temporary index", name);2590}25912592 fd =open(filename, O_WRONLY | O_CREAT,0666);2593if(fd <0||write_index(&result, fd) ||close(fd))2594die("Could not write temporary index to%s", filename);25952596discard_index(&result);2597}25982599static voidstat_patch_list(struct patch *patch)2600{2601int files, adds, dels;26022603for(files = adds = dels =0; patch ; patch = patch->next) {2604 files++;2605 adds += patch->lines_added;2606 dels += patch->lines_deleted;2607show_stats(patch);2608}26092610printf("%dfiles changed,%dinsertions(+),%ddeletions(-)\n", files, adds, dels);2611}26122613static voidnumstat_patch_list(struct patch *patch)2614{2615for( ; patch; patch = patch->next) {2616const char*name;2617 name = patch->new_name ? patch->new_name : patch->old_name;2618if(patch->is_binary)2619printf("-\t-\t");2620else2621printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);2622write_name_quoted(name, stdout, line_termination);2623}2624}26252626static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)2627{2628if(mode)2629printf("%smode%06o%s\n", newdelete, mode, name);2630else2631printf("%s %s\n", newdelete, name);2632}26332634static voidshow_mode_change(struct patch *p,int show_name)2635{2636if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {2637if(show_name)2638printf(" mode change%06o =>%06o%s\n",2639 p->old_mode, p->new_mode, p->new_name);2640else2641printf(" mode change%06o =>%06o\n",2642 p->old_mode, p->new_mode);2643}2644}26452646static voidshow_rename_copy(struct patch *p)2647{2648const char*renamecopy = p->is_rename ?"rename":"copy";2649const char*old, *new;26502651/* Find common prefix */2652 old = p->old_name;2653new= p->new_name;2654while(1) {2655const char*slash_old, *slash_new;2656 slash_old =strchr(old,'/');2657 slash_new =strchr(new,'/');2658if(!slash_old ||2659!slash_new ||2660 slash_old - old != slash_new -new||2661memcmp(old,new, slash_new -new))2662break;2663 old = slash_old +1;2664new= slash_new +1;2665}2666/* p->old_name thru old is the common prefix, and old and new2667 * through the end of names are renames2668 */2669if(old != p->old_name)2670printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,2671(int)(old - p->old_name), p->old_name,2672 old,new, p->score);2673else2674printf("%s %s=>%s(%d%%)\n", renamecopy,2675 p->old_name, p->new_name, p->score);2676show_mode_change(p,0);2677}26782679static voidsummary_patch_list(struct patch *patch)2680{2681struct patch *p;26822683for(p = patch; p; p = p->next) {2684if(p->is_new)2685show_file_mode_name("create", p->new_mode, p->new_name);2686else if(p->is_delete)2687show_file_mode_name("delete", p->old_mode, p->old_name);2688else{2689if(p->is_rename || p->is_copy)2690show_rename_copy(p);2691else{2692if(p->score) {2693printf(" rewrite%s(%d%%)\n",2694 p->new_name, p->score);2695show_mode_change(p,0);2696}2697else2698show_mode_change(p,1);2699}2700}2701}2702}27032704static voidpatch_stats(struct patch *patch)2705{2706int lines = patch->lines_added + patch->lines_deleted;27072708if(lines > max_change)2709 max_change = lines;2710if(patch->old_name) {2711int len =quote_c_style(patch->old_name, NULL, NULL,0);2712if(!len)2713 len =strlen(patch->old_name);2714if(len > max_len)2715 max_len = len;2716}2717if(patch->new_name) {2718int len =quote_c_style(patch->new_name, NULL, NULL,0);2719if(!len)2720 len =strlen(patch->new_name);2721if(len > max_len)2722 max_len = len;2723}2724}27252726static voidremove_file(struct patch *patch,int rmdir_empty)2727{2728if(update_index) {2729if(remove_file_from_cache(patch->old_name) <0)2730die("unable to remove%sfrom index", patch->old_name);2731}2732if(!cached) {2733if(S_ISGITLINK(patch->old_mode)) {2734if(rmdir(patch->old_name))2735warning("unable to remove submodule%s",2736 patch->old_name);2737}else if(!unlink(patch->old_name) && rmdir_empty) {2738char*name =xstrdup(patch->old_name);2739char*end =strrchr(name,'/');2740while(end) {2741*end =0;2742if(rmdir(name))2743break;2744 end =strrchr(name,'/');2745}2746free(name);2747}2748}2749}27502751static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)2752{2753struct stat st;2754struct cache_entry *ce;2755int namelen =strlen(path);2756unsigned ce_size =cache_entry_size(namelen);27572758if(!update_index)2759return;27602761 ce =xcalloc(1, ce_size);2762memcpy(ce->name, path, namelen);2763 ce->ce_mode =create_ce_mode(mode);2764 ce->ce_flags = namelen;2765if(S_ISGITLINK(mode)) {2766const char*s = buf;27672768if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))2769die("corrupt patch for subproject%s", path);2770}else{2771if(!cached) {2772if(lstat(path, &st) <0)2773die("unable to stat newly created file%s",2774 path);2775fill_stat_cache_info(ce, &st);2776}2777if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)2778die("unable to create backing store for newly created file%s", path);2779}2780if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)2781die("unable to add cache entry for%s", path);2782}27832784static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)2785{2786int fd;2787struct strbuf nbuf;27882789if(S_ISGITLINK(mode)) {2790struct stat st;2791if(!lstat(path, &st) &&S_ISDIR(st.st_mode))2792return0;2793returnmkdir(path,0777);2794}27952796if(has_symlinks &&S_ISLNK(mode))2797/* Although buf:size is counted string, it also is NUL2798 * terminated.2799 */2800returnsymlink(buf, path);28012802 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);2803if(fd <0)2804return-1;28052806strbuf_init(&nbuf,0);2807if(convert_to_working_tree(path, buf, size, &nbuf)) {2808 size = nbuf.len;2809 buf = nbuf.buf;2810}2811write_or_die(fd, buf, size);2812strbuf_release(&nbuf);28132814if(close(fd) <0)2815die("closing file%s:%s", path,strerror(errno));2816return0;2817}28182819/*2820 * We optimistically assume that the directories exist,2821 * which is true 99% of the time anyway. If they don't,2822 * we create them and try again.2823 */2824static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)2825{2826if(cached)2827return;2828if(!try_create_file(path, mode, buf, size))2829return;28302831if(errno == ENOENT) {2832if(safe_create_leading_directories(path))2833return;2834if(!try_create_file(path, mode, buf, size))2835return;2836}28372838if(errno == EEXIST || errno == EACCES) {2839/* We may be trying to create a file where a directory2840 * used to be.2841 */2842struct stat st;2843if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))2844 errno = EEXIST;2845}28462847if(errno == EEXIST) {2848unsigned int nr =getpid();28492850for(;;) {2851const char*newpath;2852 newpath =mkpath("%s~%u", path, nr);2853if(!try_create_file(newpath, mode, buf, size)) {2854if(!rename(newpath, path))2855return;2856unlink(newpath);2857break;2858}2859if(errno != EEXIST)2860break;2861++nr;2862}2863}2864die("unable to write file%smode%o", path, mode);2865}28662867static voidcreate_file(struct patch *patch)2868{2869char*path = patch->new_name;2870unsigned mode = patch->new_mode;2871unsigned long size = patch->resultsize;2872char*buf = patch->result;28732874if(!mode)2875 mode = S_IFREG |0644;2876create_one_file(path, mode, buf, size);2877add_index_file(path, mode, buf, size);2878}28792880/* phase zero is to remove, phase one is to create */2881static voidwrite_out_one_result(struct patch *patch,int phase)2882{2883if(patch->is_delete >0) {2884if(phase ==0)2885remove_file(patch,1);2886return;2887}2888if(patch->is_new >0|| patch->is_copy) {2889if(phase ==1)2890create_file(patch);2891return;2892}2893/*2894 * Rename or modification boils down to the same2895 * thing: remove the old, write the new2896 */2897if(phase ==0)2898remove_file(patch, patch->is_rename);2899if(phase ==1)2900create_file(patch);2901}29022903static intwrite_out_one_reject(struct patch *patch)2904{2905FILE*rej;2906char namebuf[PATH_MAX];2907struct fragment *frag;2908int cnt =0;29092910for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {2911if(!frag->rejected)2912continue;2913 cnt++;2914}29152916if(!cnt) {2917if(apply_verbosely)2918say_patch_name(stderr,2919"Applied patch ", patch," cleanly.\n");2920return0;2921}29222923/* This should not happen, because a removal patch that leaves2924 * contents are marked "rejected" at the patch level.2925 */2926if(!patch->new_name)2927die("internal error");29282929/* Say this even without --verbose */2930say_patch_name(stderr,"Applying patch ", patch," with");2931fprintf(stderr,"%drejects...\n", cnt);29322933 cnt =strlen(patch->new_name);2934if(ARRAY_SIZE(namebuf) <= cnt +5) {2935 cnt =ARRAY_SIZE(namebuf) -5;2936fprintf(stderr,2937"warning: truncating .rej filename to %.*s.rej",2938 cnt -1, patch->new_name);2939}2940memcpy(namebuf, patch->new_name, cnt);2941memcpy(namebuf + cnt,".rej",5);29422943 rej =fopen(namebuf,"w");2944if(!rej)2945returnerror("cannot open%s:%s", namebuf,strerror(errno));29462947/* Normal git tools never deal with .rej, so do not pretend2948 * this is a git patch by saying --git nor give extended2949 * headers. While at it, maybe please "kompare" that wants2950 * the trailing TAB and some garbage at the end of line ;-).2951 */2952fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",2953 patch->new_name, patch->new_name);2954for(cnt =1, frag = patch->fragments;2955 frag;2956 cnt++, frag = frag->next) {2957if(!frag->rejected) {2958fprintf(stderr,"Hunk #%dapplied cleanly.\n", cnt);2959continue;2960}2961fprintf(stderr,"Rejected hunk #%d.\n", cnt);2962fprintf(rej,"%.*s", frag->size, frag->patch);2963if(frag->patch[frag->size-1] !='\n')2964fputc('\n', rej);2965}2966fclose(rej);2967return-1;2968}29692970static intwrite_out_results(struct patch *list,int skipped_patch)2971{2972int phase;2973int errs =0;2974struct patch *l;29752976if(!list && !skipped_patch)2977returnerror("No changes");29782979for(phase =0; phase <2; phase++) {2980 l = list;2981while(l) {2982if(l->rejected)2983 errs =1;2984else{2985write_out_one_result(l, phase);2986if(phase ==1&&write_out_one_reject(l))2987 errs =1;2988}2989 l = l->next;2990}2991}2992return errs;2993}29942995static struct lock_file lock_file;29962997static struct excludes {2998struct excludes *next;2999const char*path;3000} *excludes;30013002static intuse_patch(struct patch *p)3003{3004const char*pathname = p->new_name ? p->new_name : p->old_name;3005struct excludes *x = excludes;3006while(x) {3007if(fnmatch(x->path, pathname,0) ==0)3008return0;3009 x = x->next;3010}3011if(0< prefix_length) {3012int pathlen =strlen(pathname);3013if(pathlen <= prefix_length ||3014memcmp(prefix, pathname, prefix_length))3015return0;3016}3017return1;3018}30193020static voidprefix_one(char**name)3021{3022char*old_name = *name;3023if(!old_name)3024return;3025*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3026free(old_name);3027}30283029static voidprefix_patches(struct patch *p)3030{3031if(!prefix || p->is_toplevel_relative)3032return;3033for( ; p; p = p->next) {3034if(p->new_name == p->old_name) {3035char*prefixed = p->new_name;3036prefix_one(&prefixed);3037 p->new_name = p->old_name = prefixed;3038}3039else{3040prefix_one(&p->new_name);3041prefix_one(&p->old_name);3042}3043}3044}30453046#define INACCURATE_EOF (1<<0)3047#define RECOUNT (1<<1)30483049static intapply_patch(int fd,const char*filename,int options)3050{3051size_t offset;3052struct strbuf buf;3053struct patch *list = NULL, **listp = &list;3054int skipped_patch =0;30553056/* FIXME - memory leak when using multiple patch files as inputs */3057memset(&fn_table,0,sizeof(struct string_list));3058strbuf_init(&buf,0);3059 patch_input_file = filename;3060read_patch_file(&buf, fd);3061 offset =0;3062while(offset < buf.len) {3063struct patch *patch;3064int nr;30653066 patch =xcalloc(1,sizeof(*patch));3067 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3068 patch->recount = !!(options & RECOUNT);3069 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3070if(nr <0)3071break;3072if(apply_in_reverse)3073reverse_patches(patch);3074if(prefix)3075prefix_patches(patch);3076if(use_patch(patch)) {3077patch_stats(patch);3078*listp = patch;3079 listp = &patch->next;3080}3081else{3082/* perhaps free it a bit better? */3083free(patch);3084 skipped_patch++;3085}3086 offset += nr;3087}30883089if(whitespace_error && (ws_error_action == die_on_ws_error))3090 apply =0;30913092 update_index = check_index && apply;3093if(update_index && newfd <0)3094 newfd =hold_locked_index(&lock_file,1);30953096if(check_index) {3097if(read_cache() <0)3098die("unable to read index file");3099}31003101if((check || apply) &&3102check_patch_list(list) <0&&3103!apply_with_reject)3104exit(1);31053106if(apply &&write_out_results(list, skipped_patch))3107exit(1);31083109if(fake_ancestor)3110build_fake_ancestor(list, fake_ancestor);31113112if(diffstat)3113stat_patch_list(list);31143115if(numstat)3116numstat_patch_list(list);31173118if(summary)3119summary_patch_list(list);31203121strbuf_release(&buf);3122return0;3123}31243125static intgit_apply_config(const char*var,const char*value,void*cb)3126{3127if(!strcmp(var,"apply.whitespace"))3128returngit_config_string(&apply_default_whitespace, var, value);3129returngit_default_config(var, value, cb);3130}313131323133intcmd_apply(int argc,const char**argv,const char*unused_prefix)3134{3135int i;3136int read_stdin =1;3137int options =0;3138int errs =0;3139int is_not_gitdir;31403141const char*whitespace_option = NULL;31423143 prefix =setup_git_directory_gently(&is_not_gitdir);3144 prefix_length = prefix ?strlen(prefix) :0;3145git_config(git_apply_config, NULL);3146if(apply_default_whitespace)3147parse_whitespace_option(apply_default_whitespace);31483149for(i =1; i < argc; i++) {3150const char*arg = argv[i];3151char*end;3152int fd;31533154if(!strcmp(arg,"-")) {3155 errs |=apply_patch(0,"<stdin>", options);3156 read_stdin =0;3157continue;3158}3159if(!prefixcmp(arg,"--exclude=")) {3160struct excludes *x =xmalloc(sizeof(*x));3161 x->path = arg +10;3162 x->next = excludes;3163 excludes = x;3164continue;3165}3166if(!prefixcmp(arg,"-p")) {3167 p_value =atoi(arg +2);3168 p_value_known =1;3169continue;3170}3171if(!strcmp(arg,"--no-add")) {3172 no_add =1;3173continue;3174}3175if(!strcmp(arg,"--stat")) {3176 apply =0;3177 diffstat =1;3178continue;3179}3180if(!strcmp(arg,"--allow-binary-replacement") ||3181!strcmp(arg,"--binary")) {3182continue;/* now no-op */3183}3184if(!strcmp(arg,"--numstat")) {3185 apply =0;3186 numstat =1;3187continue;3188}3189if(!strcmp(arg,"--summary")) {3190 apply =0;3191 summary =1;3192continue;3193}3194if(!strcmp(arg,"--check")) {3195 apply =0;3196 check =1;3197continue;3198}3199if(!strcmp(arg,"--index")) {3200if(is_not_gitdir)3201die("--index outside a repository");3202 check_index =1;3203continue;3204}3205if(!strcmp(arg,"--cached")) {3206if(is_not_gitdir)3207die("--cached outside a repository");3208 check_index =1;3209 cached =1;3210continue;3211}3212if(!strcmp(arg,"--apply")) {3213 apply =1;3214continue;3215}3216if(!strcmp(arg,"--build-fake-ancestor")) {3217 apply =0;3218if(++i >= argc)3219die("need a filename");3220 fake_ancestor = argv[i];3221continue;3222}3223if(!strcmp(arg,"-z")) {3224 line_termination =0;3225continue;3226}3227if(!prefixcmp(arg,"-C")) {3228 p_context =strtoul(arg +2, &end,0);3229if(*end !='\0')3230die("unrecognized context count '%s'", arg +2);3231continue;3232}3233if(!prefixcmp(arg,"--whitespace=")) {3234 whitespace_option = arg +13;3235parse_whitespace_option(arg +13);3236continue;3237}3238if(!strcmp(arg,"-R") || !strcmp(arg,"--reverse")) {3239 apply_in_reverse =1;3240continue;3241}3242if(!strcmp(arg,"--unidiff-zero")) {3243 unidiff_zero =1;3244continue;3245}3246if(!strcmp(arg,"--reject")) {3247 apply = apply_with_reject = apply_verbosely =1;3248continue;3249}3250if(!strcmp(arg,"-v") || !strcmp(arg,"--verbose")) {3251 apply_verbosely =1;3252continue;3253}3254if(!strcmp(arg,"--inaccurate-eof")) {3255 options |= INACCURATE_EOF;3256continue;3257}3258if(!strcmp(arg,"--recount")) {3259 options |= RECOUNT;3260continue;3261}3262if(!prefixcmp(arg,"--directory=")) {3263 arg +=strlen("--directory=");3264 root_len =strlen(arg);3265if(root_len && arg[root_len -1] !='/') {3266char*new_root;3267 root = new_root =xmalloc(root_len +2);3268strcpy(new_root, arg);3269strcpy(new_root + root_len++,"/");3270}else3271 root = arg;3272continue;3273}3274if(0< prefix_length)3275 arg =prefix_filename(prefix, prefix_length, arg);32763277 fd =open(arg, O_RDONLY);3278if(fd <0)3279die("can't open patch '%s':%s", arg,strerror(errno));3280 read_stdin =0;3281set_default_whitespace_mode(whitespace_option);3282 errs |=apply_patch(fd, arg, options);3283close(fd);3284}3285set_default_whitespace_mode(whitespace_option);3286if(read_stdin)3287 errs |=apply_patch(0,"<stdin>", options);3288if(whitespace_error) {3289if(squelch_whitespace_errors &&3290 squelch_whitespace_errors < whitespace_error) {3291int squelched =3292 whitespace_error - squelch_whitespace_errors;3293fprintf(stderr,"warning: squelched%d"3294"whitespace error%s\n",3295 squelched,3296 squelched ==1?"":"s");3297}3298if(ws_error_action == die_on_ws_error)3299die("%dline%sadd%swhitespace errors.",3300 whitespace_error,3301 whitespace_error ==1?"":"s",3302 whitespace_error ==1?"s":"");3303if(applied_after_fixing_ws && apply)3304fprintf(stderr,"warning:%dline%sapplied after"3305" fixing whitespace errors.\n",3306 applied_after_fixing_ws,3307 applied_after_fixing_ws ==1?"":"s");3308else if(whitespace_error)3309fprintf(stderr,"warning:%dline%sadd%swhitespace errors.\n",3310 whitespace_error,3311 whitespace_error ==1?"":"s",3312 whitespace_error ==1?"s":"");3313}33143315if(update_index) {3316if(write_cache(newfd, active_cache, active_nr) ||3317commit_locked_index(&lock_file))3318die("Unable to write new index file");3319}33203321return!!errs;3322}