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 *2000 * And a hunk to add to an empty file would begin with2001 * @@ -0,0 +N,M @@2002 *2003 * In other words, a hunk that is (frag->oldpos <= 1) with or2004 * without leading context must match at the beginning.2005 */2006 match_beginning = frag->oldpos <=1;20072008/*2009 * A hunk without trailing lines must match at the end.2010 * However, we simply cannot tell if a hunk must match end2011 * from the lack of trailing lines if the patch was generated2012 * with unidiff without any context.2013 */2014 match_end = !unidiff_zero && !trailing;20152016 pos = frag->newpos ? (frag->newpos -1) :0;2017 preimage.buf = oldlines;2018 preimage.len = old - oldlines;2019 postimage.buf = newlines;2020 postimage.len =new- newlines;2021 preimage.line = preimage.line_allocated;2022 postimage.line = postimage.line_allocated;20232024for(;;) {20252026 applied_pos =find_pos(img, &preimage, &postimage, pos,2027 ws_rule, match_beginning, match_end);20282029if(applied_pos >=0)2030break;20312032/* Am I at my context limits? */2033if((leading <= p_context) && (trailing <= p_context))2034break;2035if(match_beginning || match_end) {2036 match_beginning = match_end =0;2037continue;2038}20392040/*2041 * Reduce the number of context lines; reduce both2042 * leading and trailing if they are equal otherwise2043 * just reduce the larger context.2044 */2045if(leading >= trailing) {2046remove_first_line(&preimage);2047remove_first_line(&postimage);2048 pos--;2049 leading--;2050}2051if(trailing > leading) {2052remove_last_line(&preimage);2053remove_last_line(&postimage);2054 trailing--;2055}2056}20572058if(applied_pos >=0) {2059if(ws_error_action == correct_ws_error &&2060 new_blank_lines_at_end &&2061 postimage.nr + applied_pos == img->nr) {2062/*2063 * If the patch application adds blank lines2064 * at the end, and if the patch applies at the2065 * end of the image, remove those added blank2066 * lines.2067 */2068while(new_blank_lines_at_end--)2069remove_last_line(&postimage);2070}20712072/*2073 * Warn if it was necessary to reduce the number2074 * of context lines.2075 */2076if((leading != frag->leading) ||2077(trailing != frag->trailing))2078fprintf(stderr,"Context reduced to (%ld/%ld)"2079" to apply fragment at%d\n",2080 leading, trailing, applied_pos+1);2081update_image(img, applied_pos, &preimage, &postimage);2082}else{2083if(apply_verbosely)2084error("while searching for:\n%.*s",2085(int)(old - oldlines), oldlines);2086}20872088free(oldlines);2089free(newlines);2090free(preimage.line_allocated);2091free(postimage.line_allocated);20922093return(applied_pos <0);2094}20952096static intapply_binary_fragment(struct image *img,struct patch *patch)2097{2098struct fragment *fragment = patch->fragments;2099unsigned long len;2100void*dst;21012102/* Binary patch is irreversible without the optional second hunk */2103if(apply_in_reverse) {2104if(!fragment->next)2105returnerror("cannot reverse-apply a binary patch "2106"without the reverse hunk to '%s'",2107 patch->new_name2108? patch->new_name : patch->old_name);2109 fragment = fragment->next;2110}2111switch(fragment->binary_patch_method) {2112case BINARY_DELTA_DEFLATED:2113 dst =patch_delta(img->buf, img->len, fragment->patch,2114 fragment->size, &len);2115if(!dst)2116return-1;2117clear_image(img);2118 img->buf = dst;2119 img->len = len;2120return0;2121case BINARY_LITERAL_DEFLATED:2122clear_image(img);2123 img->len = fragment->size;2124 img->buf =xmalloc(img->len+1);2125memcpy(img->buf, fragment->patch, img->len);2126 img->buf[img->len] ='\0';2127return0;2128}2129return-1;2130}21312132static intapply_binary(struct image *img,struct patch *patch)2133{2134const char*name = patch->old_name ? patch->old_name : patch->new_name;2135unsigned char sha1[20];21362137/*2138 * For safety, we require patch index line to contain2139 * full 40-byte textual SHA1 for old and new, at least for now.2140 */2141if(strlen(patch->old_sha1_prefix) !=40||2142strlen(patch->new_sha1_prefix) !=40||2143get_sha1_hex(patch->old_sha1_prefix, sha1) ||2144get_sha1_hex(patch->new_sha1_prefix, sha1))2145returnerror("cannot apply binary patch to '%s' "2146"without full index line", name);21472148if(patch->old_name) {2149/*2150 * See if the old one matches what the patch2151 * applies to.2152 */2153hash_sha1_file(img->buf, img->len, blob_type, sha1);2154if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2155returnerror("the patch applies to '%s' (%s), "2156"which does not match the "2157"current contents.",2158 name,sha1_to_hex(sha1));2159}2160else{2161/* Otherwise, the old one must be empty. */2162if(img->len)2163returnerror("the patch applies to an empty "2164"'%s' but it is not empty", name);2165}21662167get_sha1_hex(patch->new_sha1_prefix, sha1);2168if(is_null_sha1(sha1)) {2169clear_image(img);2170return0;/* deletion patch */2171}21722173if(has_sha1_file(sha1)) {2174/* We already have the postimage */2175enum object_type type;2176unsigned long size;2177char*result;21782179 result =read_sha1_file(sha1, &type, &size);2180if(!result)2181returnerror("the necessary postimage%sfor "2182"'%s' cannot be read",2183 patch->new_sha1_prefix, name);2184clear_image(img);2185 img->buf = result;2186 img->len = size;2187}else{2188/*2189 * We have verified buf matches the preimage;2190 * apply the patch data to it, which is stored2191 * in the patch->fragments->{patch,size}.2192 */2193if(apply_binary_fragment(img, patch))2194returnerror("binary patch does not apply to '%s'",2195 name);21962197/* verify that the result matches */2198hash_sha1_file(img->buf, img->len, blob_type, sha1);2199if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2200returnerror("binary patch to '%s' creates incorrect result (expecting%s, got%s)",2201 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2202}22032204return0;2205}22062207static intapply_fragments(struct image *img,struct patch *patch)2208{2209struct fragment *frag = patch->fragments;2210const char*name = patch->old_name ? patch->old_name : patch->new_name;2211unsigned ws_rule = patch->ws_rule;2212unsigned inaccurate_eof = patch->inaccurate_eof;22132214if(patch->is_binary)2215returnapply_binary(img, patch);22162217while(frag) {2218if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule)) {2219error("patch failed:%s:%ld", name, frag->oldpos);2220if(!apply_with_reject)2221return-1;2222 frag->rejected =1;2223}2224 frag = frag->next;2225}2226return0;2227}22282229static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2230{2231if(!ce)2232return0;22332234if(S_ISGITLINK(ce->ce_mode)) {2235strbuf_grow(buf,100);2236strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2237}else{2238enum object_type type;2239unsigned long sz;2240char*result;22412242 result =read_sha1_file(ce->sha1, &type, &sz);2243if(!result)2244return-1;2245/* XXX read_sha1_file NUL-terminates */2246strbuf_attach(buf, result, sz, sz +1);2247}2248return0;2249}22502251static struct patch *in_fn_table(const char*name)2252{2253struct string_list_item *item;22542255if(name == NULL)2256return NULL;22572258 item =string_list_lookup(name, &fn_table);2259if(item != NULL)2260return(struct patch *)item->util;22612262return NULL;2263}22642265static voidadd_to_fn_table(struct patch *patch)2266{2267struct string_list_item *item;22682269/*2270 * Always add new_name unless patch is a deletion2271 * This should cover the cases for normal diffs,2272 * file creations and copies2273 */2274if(patch->new_name != NULL) {2275 item =string_list_insert(patch->new_name, &fn_table);2276 item->util = patch;2277}22782279/*2280 * store a failure on rename/deletion cases because2281 * later chunks shouldn't patch old names2282 */2283if((patch->new_name == NULL) || (patch->is_rename)) {2284 item =string_list_insert(patch->old_name, &fn_table);2285 item->util = (struct patch *) -1;2286}2287}22882289static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)2290{2291struct strbuf buf;2292struct image image;2293size_t len;2294char*img;2295struct patch *tpatch;22962297strbuf_init(&buf,0);22982299if(!(patch->is_copy || patch->is_rename) &&2300((tpatch =in_fn_table(patch->old_name)) != NULL)) {2301if(tpatch == (struct patch *) -1) {2302returnerror("patch%shas been renamed/deleted",2303 patch->old_name);2304}2305/* We have a patched copy in memory use that */2306strbuf_add(&buf, tpatch->result, tpatch->resultsize);2307}else if(cached) {2308if(read_file_or_gitlink(ce, &buf))2309returnerror("read of%sfailed", patch->old_name);2310}else if(patch->old_name) {2311if(S_ISGITLINK(patch->old_mode)) {2312if(ce) {2313read_file_or_gitlink(ce, &buf);2314}else{2315/*2316 * There is no way to apply subproject2317 * patch without looking at the index.2318 */2319 patch->fragments = NULL;2320}2321}else{2322if(read_old_data(st, patch->old_name, &buf))2323returnerror("read of%sfailed", patch->old_name);2324}2325}23262327 img =strbuf_detach(&buf, &len);2328prepare_image(&image, img, len, !patch->is_binary);23292330if(apply_fragments(&image, patch) <0)2331return-1;/* note with --reject this succeeds. */2332 patch->result = image.buf;2333 patch->resultsize = image.len;2334add_to_fn_table(patch);2335free(image.line_allocated);23362337if(0< patch->is_delete && patch->resultsize)2338returnerror("removal patch leaves file contents");23392340return0;2341}23422343static intcheck_to_create_blob(const char*new_name,int ok_if_exists)2344{2345struct stat nst;2346if(!lstat(new_name, &nst)) {2347if(S_ISDIR(nst.st_mode) || ok_if_exists)2348return0;2349/*2350 * A leading component of new_name might be a symlink2351 * that is going to be removed with this patch, but2352 * still pointing at somewhere that has the path.2353 * In such a case, path "new_name" does not exist as2354 * far as git is concerned.2355 */2356if(has_symlink_leading_path(strlen(new_name), new_name))2357return0;23582359returnerror("%s: already exists in working directory", new_name);2360}2361else if((errno != ENOENT) && (errno != ENOTDIR))2362returnerror("%s:%s", new_name,strerror(errno));2363return0;2364}23652366static intverify_index_match(struct cache_entry *ce,struct stat *st)2367{2368if(S_ISGITLINK(ce->ce_mode)) {2369if(!S_ISDIR(st->st_mode))2370return-1;2371return0;2372}2373returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID);2374}23752376static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)2377{2378const char*old_name = patch->old_name;2379struct patch *tpatch = NULL;2380int stat_ret =0;2381unsigned st_mode =0;23822383/*2384 * Make sure that we do not have local modifications from the2385 * index when we are looking at the index. Also make sure2386 * we have the preimage file to be patched in the work tree,2387 * unless --cached, which tells git to apply only in the index.2388 */2389if(!old_name)2390return0;23912392assert(patch->is_new <=0);23932394if(!(patch->is_copy || patch->is_rename) &&2395(tpatch =in_fn_table(old_name)) != NULL) {2396if(tpatch == (struct patch *) -1) {2397returnerror("%s: has been deleted/renamed", old_name);2398}2399 st_mode = tpatch->new_mode;2400}else if(!cached) {2401 stat_ret =lstat(old_name, st);2402if(stat_ret && errno != ENOENT)2403returnerror("%s:%s", old_name,strerror(errno));2404}24052406if(check_index && !tpatch) {2407int pos =cache_name_pos(old_name,strlen(old_name));2408if(pos <0) {2409if(patch->is_new <0)2410goto is_new;2411returnerror("%s: does not exist in index", old_name);2412}2413*ce = active_cache[pos];2414if(stat_ret <0) {2415struct checkout costate;2416/* checkout */2417 costate.base_dir ="";2418 costate.base_dir_len =0;2419 costate.force =0;2420 costate.quiet =0;2421 costate.not_new =0;2422 costate.refresh_cache =1;2423if(checkout_entry(*ce, &costate, NULL) ||2424lstat(old_name, st))2425return-1;2426}2427if(!cached &&verify_index_match(*ce, st))2428returnerror("%s: does not match index", old_name);2429if(cached)2430 st_mode = (*ce)->ce_mode;2431}else if(stat_ret <0) {2432if(patch->is_new <0)2433goto is_new;2434returnerror("%s:%s", old_name,strerror(errno));2435}24362437if(!cached)2438 st_mode =ce_mode_from_stat(*ce, st->st_mode);24392440if(patch->is_new <0)2441 patch->is_new =0;2442if(!patch->old_mode)2443 patch->old_mode = st_mode;2444if((st_mode ^ patch->old_mode) & S_IFMT)2445returnerror("%s: wrong type", old_name);2446if(st_mode != patch->old_mode)2447fprintf(stderr,"warning:%shas type%o, expected%o\n",2448 old_name, st_mode, patch->old_mode);2449return0;24502451 is_new:2452 patch->is_new =1;2453 patch->is_delete =0;2454 patch->old_name = NULL;2455return0;2456}24572458static intcheck_patch(struct patch *patch)2459{2460struct stat st;2461const char*old_name = patch->old_name;2462const char*new_name = patch->new_name;2463const char*name = old_name ? old_name : new_name;2464struct cache_entry *ce = NULL;2465int ok_if_exists;2466int status;24672468 patch->rejected =1;/* we will drop this after we succeed */24692470 status =check_preimage(patch, &ce, &st);2471if(status)2472return status;2473 old_name = patch->old_name;24742475if(in_fn_table(new_name) == (struct patch *) -1)2476/*2477 * A type-change diff is always split into a patch to2478 * delete old, immediately followed by a patch to2479 * create new (see diff.c::run_diff()); in such a case2480 * it is Ok that the entry to be deleted by the2481 * previous patch is still in the working tree and in2482 * the index.2483 */2484 ok_if_exists =1;2485else2486 ok_if_exists =0;24872488if(new_name &&2489((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {2490if(check_index &&2491cache_name_pos(new_name,strlen(new_name)) >=0&&2492!ok_if_exists)2493returnerror("%s: already exists in index", new_name);2494if(!cached) {2495int err =check_to_create_blob(new_name, ok_if_exists);2496if(err)2497return err;2498}2499if(!patch->new_mode) {2500if(0< patch->is_new)2501 patch->new_mode = S_IFREG |0644;2502else2503 patch->new_mode = patch->old_mode;2504}2505}25062507if(new_name && old_name) {2508int same = !strcmp(old_name, new_name);2509if(!patch->new_mode)2510 patch->new_mode = patch->old_mode;2511if((patch->old_mode ^ patch->new_mode) & S_IFMT)2512returnerror("new mode (%o) of%sdoes not match old mode (%o)%s%s",2513 patch->new_mode, new_name, patch->old_mode,2514 same ?"":" of ", same ?"": old_name);2515}25162517if(apply_data(patch, &st, ce) <0)2518returnerror("%s: patch does not apply", name);2519 patch->rejected =0;2520return0;2521}25222523static intcheck_patch_list(struct patch *patch)2524{2525int err =0;25262527while(patch) {2528if(apply_verbosely)2529say_patch_name(stderr,2530"Checking patch ", patch,"...\n");2531 err |=check_patch(patch);2532 patch = patch->next;2533}2534return err;2535}25362537/* This function tries to read the sha1 from the current index */2538static intget_current_sha1(const char*path,unsigned char*sha1)2539{2540int pos;25412542if(read_cache() <0)2543return-1;2544 pos =cache_name_pos(path,strlen(path));2545if(pos <0)2546return-1;2547hashcpy(sha1, active_cache[pos]->sha1);2548return0;2549}25502551/* Build an index that contains the just the files needed for a 3way merge */2552static voidbuild_fake_ancestor(struct patch *list,const char*filename)2553{2554struct patch *patch;2555struct index_state result = {0};2556int fd;25572558/* Once we start supporting the reverse patch, it may be2559 * worth showing the new sha1 prefix, but until then...2560 */2561for(patch = list; patch; patch = patch->next) {2562const unsigned char*sha1_ptr;2563unsigned char sha1[20];2564struct cache_entry *ce;2565const char*name;25662567 name = patch->old_name ? patch->old_name : patch->new_name;2568if(0< patch->is_new)2569continue;2570else if(get_sha1(patch->old_sha1_prefix, sha1))2571/* git diff has no index line for mode/type changes */2572if(!patch->lines_added && !patch->lines_deleted) {2573if(get_current_sha1(patch->new_name, sha1) ||2574get_current_sha1(patch->old_name, sha1))2575die("mode change for%s, which is not "2576"in current HEAD", name);2577 sha1_ptr = sha1;2578}else2579die("sha1 information is lacking or useless "2580"(%s).", name);2581else2582 sha1_ptr = sha1;25832584 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);2585if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))2586die("Could not add%sto temporary index", name);2587}25882589 fd =open(filename, O_WRONLY | O_CREAT,0666);2590if(fd <0||write_index(&result, fd) ||close(fd))2591die("Could not write temporary index to%s", filename);25922593discard_index(&result);2594}25952596static voidstat_patch_list(struct patch *patch)2597{2598int files, adds, dels;25992600for(files = adds = dels =0; patch ; patch = patch->next) {2601 files++;2602 adds += patch->lines_added;2603 dels += patch->lines_deleted;2604show_stats(patch);2605}26062607printf("%dfiles changed,%dinsertions(+),%ddeletions(-)\n", files, adds, dels);2608}26092610static voidnumstat_patch_list(struct patch *patch)2611{2612for( ; patch; patch = patch->next) {2613const char*name;2614 name = patch->new_name ? patch->new_name : patch->old_name;2615if(patch->is_binary)2616printf("-\t-\t");2617else2618printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);2619write_name_quoted(name, stdout, line_termination);2620}2621}26222623static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)2624{2625if(mode)2626printf("%smode%06o%s\n", newdelete, mode, name);2627else2628printf("%s %s\n", newdelete, name);2629}26302631static voidshow_mode_change(struct patch *p,int show_name)2632{2633if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {2634if(show_name)2635printf(" mode change%06o =>%06o%s\n",2636 p->old_mode, p->new_mode, p->new_name);2637else2638printf(" mode change%06o =>%06o\n",2639 p->old_mode, p->new_mode);2640}2641}26422643static voidshow_rename_copy(struct patch *p)2644{2645const char*renamecopy = p->is_rename ?"rename":"copy";2646const char*old, *new;26472648/* Find common prefix */2649 old = p->old_name;2650new= p->new_name;2651while(1) {2652const char*slash_old, *slash_new;2653 slash_old =strchr(old,'/');2654 slash_new =strchr(new,'/');2655if(!slash_old ||2656!slash_new ||2657 slash_old - old != slash_new -new||2658memcmp(old,new, slash_new -new))2659break;2660 old = slash_old +1;2661new= slash_new +1;2662}2663/* p->old_name thru old is the common prefix, and old and new2664 * through the end of names are renames2665 */2666if(old != p->old_name)2667printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,2668(int)(old - p->old_name), p->old_name,2669 old,new, p->score);2670else2671printf("%s %s=>%s(%d%%)\n", renamecopy,2672 p->old_name, p->new_name, p->score);2673show_mode_change(p,0);2674}26752676static voidsummary_patch_list(struct patch *patch)2677{2678struct patch *p;26792680for(p = patch; p; p = p->next) {2681if(p->is_new)2682show_file_mode_name("create", p->new_mode, p->new_name);2683else if(p->is_delete)2684show_file_mode_name("delete", p->old_mode, p->old_name);2685else{2686if(p->is_rename || p->is_copy)2687show_rename_copy(p);2688else{2689if(p->score) {2690printf(" rewrite%s(%d%%)\n",2691 p->new_name, p->score);2692show_mode_change(p,0);2693}2694else2695show_mode_change(p,1);2696}2697}2698}2699}27002701static voidpatch_stats(struct patch *patch)2702{2703int lines = patch->lines_added + patch->lines_deleted;27042705if(lines > max_change)2706 max_change = lines;2707if(patch->old_name) {2708int len =quote_c_style(patch->old_name, NULL, NULL,0);2709if(!len)2710 len =strlen(patch->old_name);2711if(len > max_len)2712 max_len = len;2713}2714if(patch->new_name) {2715int len =quote_c_style(patch->new_name, NULL, NULL,0);2716if(!len)2717 len =strlen(patch->new_name);2718if(len > max_len)2719 max_len = len;2720}2721}27222723static voidremove_file(struct patch *patch,int rmdir_empty)2724{2725if(update_index) {2726if(remove_file_from_cache(patch->old_name) <0)2727die("unable to remove%sfrom index", patch->old_name);2728}2729if(!cached) {2730if(S_ISGITLINK(patch->old_mode)) {2731if(rmdir(patch->old_name))2732warning("unable to remove submodule%s",2733 patch->old_name);2734}else if(!unlink(patch->old_name) && rmdir_empty) {2735char*name =xstrdup(patch->old_name);2736char*end =strrchr(name,'/');2737while(end) {2738*end =0;2739if(rmdir(name))2740break;2741 end =strrchr(name,'/');2742}2743free(name);2744}2745}2746}27472748static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)2749{2750struct stat st;2751struct cache_entry *ce;2752int namelen =strlen(path);2753unsigned ce_size =cache_entry_size(namelen);27542755if(!update_index)2756return;27572758 ce =xcalloc(1, ce_size);2759memcpy(ce->name, path, namelen);2760 ce->ce_mode =create_ce_mode(mode);2761 ce->ce_flags = namelen;2762if(S_ISGITLINK(mode)) {2763const char*s = buf;27642765if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))2766die("corrupt patch for subproject%s", path);2767}else{2768if(!cached) {2769if(lstat(path, &st) <0)2770die("unable to stat newly created file%s",2771 path);2772fill_stat_cache_info(ce, &st);2773}2774if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)2775die("unable to create backing store for newly created file%s", path);2776}2777if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)2778die("unable to add cache entry for%s", path);2779}27802781static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)2782{2783int fd;2784struct strbuf nbuf;27852786if(S_ISGITLINK(mode)) {2787struct stat st;2788if(!lstat(path, &st) &&S_ISDIR(st.st_mode))2789return0;2790returnmkdir(path,0777);2791}27922793if(has_symlinks &&S_ISLNK(mode))2794/* Although buf:size is counted string, it also is NUL2795 * terminated.2796 */2797returnsymlink(buf, path);27982799 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);2800if(fd <0)2801return-1;28022803strbuf_init(&nbuf,0);2804if(convert_to_working_tree(path, buf, size, &nbuf)) {2805 size = nbuf.len;2806 buf = nbuf.buf;2807}2808write_or_die(fd, buf, size);2809strbuf_release(&nbuf);28102811if(close(fd) <0)2812die("closing file%s:%s", path,strerror(errno));2813return0;2814}28152816/*2817 * We optimistically assume that the directories exist,2818 * which is true 99% of the time anyway. If they don't,2819 * we create them and try again.2820 */2821static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)2822{2823if(cached)2824return;2825if(!try_create_file(path, mode, buf, size))2826return;28272828if(errno == ENOENT) {2829if(safe_create_leading_directories(path))2830return;2831if(!try_create_file(path, mode, buf, size))2832return;2833}28342835if(errno == EEXIST || errno == EACCES) {2836/* We may be trying to create a file where a directory2837 * used to be.2838 */2839struct stat st;2840if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))2841 errno = EEXIST;2842}28432844if(errno == EEXIST) {2845unsigned int nr =getpid();28462847for(;;) {2848const char*newpath;2849 newpath =mkpath("%s~%u", path, nr);2850if(!try_create_file(newpath, mode, buf, size)) {2851if(!rename(newpath, path))2852return;2853unlink(newpath);2854break;2855}2856if(errno != EEXIST)2857break;2858++nr;2859}2860}2861die("unable to write file%smode%o", path, mode);2862}28632864static voidcreate_file(struct patch *patch)2865{2866char*path = patch->new_name;2867unsigned mode = patch->new_mode;2868unsigned long size = patch->resultsize;2869char*buf = patch->result;28702871if(!mode)2872 mode = S_IFREG |0644;2873create_one_file(path, mode, buf, size);2874add_index_file(path, mode, buf, size);2875}28762877/* phase zero is to remove, phase one is to create */2878static voidwrite_out_one_result(struct patch *patch,int phase)2879{2880if(patch->is_delete >0) {2881if(phase ==0)2882remove_file(patch,1);2883return;2884}2885if(patch->is_new >0|| patch->is_copy) {2886if(phase ==1)2887create_file(patch);2888return;2889}2890/*2891 * Rename or modification boils down to the same2892 * thing: remove the old, write the new2893 */2894if(phase ==0)2895remove_file(patch, patch->is_rename);2896if(phase ==1)2897create_file(patch);2898}28992900static intwrite_out_one_reject(struct patch *patch)2901{2902FILE*rej;2903char namebuf[PATH_MAX];2904struct fragment *frag;2905int cnt =0;29062907for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {2908if(!frag->rejected)2909continue;2910 cnt++;2911}29122913if(!cnt) {2914if(apply_verbosely)2915say_patch_name(stderr,2916"Applied patch ", patch," cleanly.\n");2917return0;2918}29192920/* This should not happen, because a removal patch that leaves2921 * contents are marked "rejected" at the patch level.2922 */2923if(!patch->new_name)2924die("internal error");29252926/* Say this even without --verbose */2927say_patch_name(stderr,"Applying patch ", patch," with");2928fprintf(stderr,"%drejects...\n", cnt);29292930 cnt =strlen(patch->new_name);2931if(ARRAY_SIZE(namebuf) <= cnt +5) {2932 cnt =ARRAY_SIZE(namebuf) -5;2933fprintf(stderr,2934"warning: truncating .rej filename to %.*s.rej",2935 cnt -1, patch->new_name);2936}2937memcpy(namebuf, patch->new_name, cnt);2938memcpy(namebuf + cnt,".rej",5);29392940 rej =fopen(namebuf,"w");2941if(!rej)2942returnerror("cannot open%s:%s", namebuf,strerror(errno));29432944/* Normal git tools never deal with .rej, so do not pretend2945 * this is a git patch by saying --git nor give extended2946 * headers. While at it, maybe please "kompare" that wants2947 * the trailing TAB and some garbage at the end of line ;-).2948 */2949fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",2950 patch->new_name, patch->new_name);2951for(cnt =1, frag = patch->fragments;2952 frag;2953 cnt++, frag = frag->next) {2954if(!frag->rejected) {2955fprintf(stderr,"Hunk #%dapplied cleanly.\n", cnt);2956continue;2957}2958fprintf(stderr,"Rejected hunk #%d.\n", cnt);2959fprintf(rej,"%.*s", frag->size, frag->patch);2960if(frag->patch[frag->size-1] !='\n')2961fputc('\n', rej);2962}2963fclose(rej);2964return-1;2965}29662967static intwrite_out_results(struct patch *list,int skipped_patch)2968{2969int phase;2970int errs =0;2971struct patch *l;29722973if(!list && !skipped_patch)2974returnerror("No changes");29752976for(phase =0; phase <2; phase++) {2977 l = list;2978while(l) {2979if(l->rejected)2980 errs =1;2981else{2982write_out_one_result(l, phase);2983if(phase ==1&&write_out_one_reject(l))2984 errs =1;2985}2986 l = l->next;2987}2988}2989return errs;2990}29912992static struct lock_file lock_file;29932994static struct excludes {2995struct excludes *next;2996const char*path;2997} *excludes;29982999static intuse_patch(struct patch *p)3000{3001const char*pathname = p->new_name ? p->new_name : p->old_name;3002struct excludes *x = excludes;3003while(x) {3004if(fnmatch(x->path, pathname,0) ==0)3005return0;3006 x = x->next;3007}3008if(0< prefix_length) {3009int pathlen =strlen(pathname);3010if(pathlen <= prefix_length ||3011memcmp(prefix, pathname, prefix_length))3012return0;3013}3014return1;3015}30163017static voidprefix_one(char**name)3018{3019char*old_name = *name;3020if(!old_name)3021return;3022*name =xstrdup(prefix_filename(prefix, prefix_length, *name));3023free(old_name);3024}30253026static voidprefix_patches(struct patch *p)3027{3028if(!prefix || p->is_toplevel_relative)3029return;3030for( ; p; p = p->next) {3031if(p->new_name == p->old_name) {3032char*prefixed = p->new_name;3033prefix_one(&prefixed);3034 p->new_name = p->old_name = prefixed;3035}3036else{3037prefix_one(&p->new_name);3038prefix_one(&p->old_name);3039}3040}3041}30423043#define INACCURATE_EOF (1<<0)3044#define RECOUNT (1<<1)30453046static intapply_patch(int fd,const char*filename,int options)3047{3048size_t offset;3049struct strbuf buf;3050struct patch *list = NULL, **listp = &list;3051int skipped_patch =0;30523053/* FIXME - memory leak when using multiple patch files as inputs */3054memset(&fn_table,0,sizeof(struct string_list));3055strbuf_init(&buf,0);3056 patch_input_file = filename;3057read_patch_file(&buf, fd);3058 offset =0;3059while(offset < buf.len) {3060struct patch *patch;3061int nr;30623063 patch =xcalloc(1,sizeof(*patch));3064 patch->inaccurate_eof = !!(options & INACCURATE_EOF);3065 patch->recount = !!(options & RECOUNT);3066 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);3067if(nr <0)3068break;3069if(apply_in_reverse)3070reverse_patches(patch);3071if(prefix)3072prefix_patches(patch);3073if(use_patch(patch)) {3074patch_stats(patch);3075*listp = patch;3076 listp = &patch->next;3077}3078else{3079/* perhaps free it a bit better? */3080free(patch);3081 skipped_patch++;3082}3083 offset += nr;3084}30853086if(whitespace_error && (ws_error_action == die_on_ws_error))3087 apply =0;30883089 update_index = check_index && apply;3090if(update_index && newfd <0)3091 newfd =hold_locked_index(&lock_file,1);30923093if(check_index) {3094if(read_cache() <0)3095die("unable to read index file");3096}30973098if((check || apply) &&3099check_patch_list(list) <0&&3100!apply_with_reject)3101exit(1);31023103if(apply &&write_out_results(list, skipped_patch))3104exit(1);31053106if(fake_ancestor)3107build_fake_ancestor(list, fake_ancestor);31083109if(diffstat)3110stat_patch_list(list);31113112if(numstat)3113numstat_patch_list(list);31143115if(summary)3116summary_patch_list(list);31173118strbuf_release(&buf);3119return0;3120}31213122static intgit_apply_config(const char*var,const char*value,void*cb)3123{3124if(!strcmp(var,"apply.whitespace"))3125returngit_config_string(&apply_default_whitespace, var, value);3126returngit_default_config(var, value, cb);3127}312831293130intcmd_apply(int argc,const char**argv,const char*unused_prefix)3131{3132int i;3133int read_stdin =1;3134int options =0;3135int errs =0;3136int is_not_gitdir;31373138const char*whitespace_option = NULL;31393140 prefix =setup_git_directory_gently(&is_not_gitdir);3141 prefix_length = prefix ?strlen(prefix) :0;3142git_config(git_apply_config, NULL);3143if(apply_default_whitespace)3144parse_whitespace_option(apply_default_whitespace);31453146for(i =1; i < argc; i++) {3147const char*arg = argv[i];3148char*end;3149int fd;31503151if(!strcmp(arg,"-")) {3152 errs |=apply_patch(0,"<stdin>", options);3153 read_stdin =0;3154continue;3155}3156if(!prefixcmp(arg,"--exclude=")) {3157struct excludes *x =xmalloc(sizeof(*x));3158 x->path = arg +10;3159 x->next = excludes;3160 excludes = x;3161continue;3162}3163if(!prefixcmp(arg,"-p")) {3164 p_value =atoi(arg +2);3165 p_value_known =1;3166continue;3167}3168if(!strcmp(arg,"--no-add")) {3169 no_add =1;3170continue;3171}3172if(!strcmp(arg,"--stat")) {3173 apply =0;3174 diffstat =1;3175continue;3176}3177if(!strcmp(arg,"--allow-binary-replacement") ||3178!strcmp(arg,"--binary")) {3179continue;/* now no-op */3180}3181if(!strcmp(arg,"--numstat")) {3182 apply =0;3183 numstat =1;3184continue;3185}3186if(!strcmp(arg,"--summary")) {3187 apply =0;3188 summary =1;3189continue;3190}3191if(!strcmp(arg,"--check")) {3192 apply =0;3193 check =1;3194continue;3195}3196if(!strcmp(arg,"--index")) {3197if(is_not_gitdir)3198die("--index outside a repository");3199 check_index =1;3200continue;3201}3202if(!strcmp(arg,"--cached")) {3203if(is_not_gitdir)3204die("--cached outside a repository");3205 check_index =1;3206 cached =1;3207continue;3208}3209if(!strcmp(arg,"--apply")) {3210 apply =1;3211continue;3212}3213if(!strcmp(arg,"--build-fake-ancestor")) {3214 apply =0;3215if(++i >= argc)3216die("need a filename");3217 fake_ancestor = argv[i];3218continue;3219}3220if(!strcmp(arg,"-z")) {3221 line_termination =0;3222continue;3223}3224if(!prefixcmp(arg,"-C")) {3225 p_context =strtoul(arg +2, &end,0);3226if(*end !='\0')3227die("unrecognized context count '%s'", arg +2);3228continue;3229}3230if(!prefixcmp(arg,"--whitespace=")) {3231 whitespace_option = arg +13;3232parse_whitespace_option(arg +13);3233continue;3234}3235if(!strcmp(arg,"-R") || !strcmp(arg,"--reverse")) {3236 apply_in_reverse =1;3237continue;3238}3239if(!strcmp(arg,"--unidiff-zero")) {3240 unidiff_zero =1;3241continue;3242}3243if(!strcmp(arg,"--reject")) {3244 apply = apply_with_reject = apply_verbosely =1;3245continue;3246}3247if(!strcmp(arg,"-v") || !strcmp(arg,"--verbose")) {3248 apply_verbosely =1;3249continue;3250}3251if(!strcmp(arg,"--inaccurate-eof")) {3252 options |= INACCURATE_EOF;3253continue;3254}3255if(!strcmp(arg,"--recount")) {3256 options |= RECOUNT;3257continue;3258}3259if(!prefixcmp(arg,"--directory=")) {3260 arg +=strlen("--directory=");3261 root_len =strlen(arg);3262if(root_len && arg[root_len -1] !='/') {3263char*new_root;3264 root = new_root =xmalloc(root_len +2);3265strcpy(new_root, arg);3266strcpy(new_root + root_len++,"/");3267}else3268 root = arg;3269continue;3270}3271if(0< prefix_length)3272 arg =prefix_filename(prefix, prefix_length, arg);32733274 fd =open(arg, O_RDONLY);3275if(fd <0)3276die("can't open patch '%s':%s", arg,strerror(errno));3277 read_stdin =0;3278set_default_whitespace_mode(whitespace_option);3279 errs |=apply_patch(fd, arg, options);3280close(fd);3281}3282set_default_whitespace_mode(whitespace_option);3283if(read_stdin)3284 errs |=apply_patch(0,"<stdin>", options);3285if(whitespace_error) {3286if(squelch_whitespace_errors &&3287 squelch_whitespace_errors < whitespace_error) {3288int squelched =3289 whitespace_error - squelch_whitespace_errors;3290fprintf(stderr,"warning: squelched%d"3291"whitespace error%s\n",3292 squelched,3293 squelched ==1?"":"s");3294}3295if(ws_error_action == die_on_ws_error)3296die("%dline%sadd%swhitespace errors.",3297 whitespace_error,3298 whitespace_error ==1?"":"s",3299 whitespace_error ==1?"s":"");3300if(applied_after_fixing_ws && apply)3301fprintf(stderr,"warning:%dline%sapplied after"3302" fixing whitespace errors.\n",3303 applied_after_fixing_ws,3304 applied_after_fixing_ws ==1?"":"s");3305else if(whitespace_error)3306fprintf(stderr,"warning:%dline%sadd%swhitespace errors.\n",3307 whitespace_error,3308 whitespace_error ==1?"":"s",3309 whitespace_error ==1?"s":"");3310}33113312if(update_index) {3313if(write_cache(newfd, active_cache, active_nr) ||3314commit_locked_index(&lock_file))3315die("Unable to write new index file");3316}33173318return!!errs;3319}