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"path-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; 61 62static voidparse_whitespace_option(const char*option) 63{ 64if(!option) { 65 ws_error_action = warn_on_ws_error; 66return; 67} 68if(!strcmp(option,"warn")) { 69 ws_error_action = warn_on_ws_error; 70return; 71} 72if(!strcmp(option,"nowarn")) { 73 ws_error_action = nowarn_ws_error; 74return; 75} 76if(!strcmp(option,"error")) { 77 ws_error_action = die_on_ws_error; 78return; 79} 80if(!strcmp(option,"error-all")) { 81 ws_error_action = die_on_ws_error; 82 squelch_whitespace_errors =0; 83return; 84} 85if(!strcmp(option,"strip") || !strcmp(option,"fix")) { 86 ws_error_action = correct_ws_error; 87return; 88} 89die("unrecognized whitespace option '%s'", option); 90} 91 92static voidset_default_whitespace_mode(const char*whitespace_option) 93{ 94if(!whitespace_option && !apply_default_whitespace) 95 ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error); 96} 97 98/* 99 * For "diff-stat" like behaviour, we keep track of the biggest change 100 * we've seen, and the longest filename. That allows us to do simple 101 * scaling. 102 */ 103static int max_change, max_len; 104 105/* 106 * Various "current state", notably line numbers and what 107 * file (and how) we're patching right now.. The "is_xxxx" 108 * things are flags, where -1 means "don't know yet". 109 */ 110static int linenr =1; 111 112/* 113 * This represents one "hunk" from a patch, starting with 114 * "@@ -oldpos,oldlines +newpos,newlines @@" marker. The 115 * patch text is pointed at by patch, and its byte length 116 * is stored in size. leading and trailing are the number 117 * of context lines. 118 */ 119struct fragment { 120unsigned long leading, trailing; 121unsigned long oldpos, oldlines; 122unsigned long newpos, newlines; 123const char*patch; 124int size; 125int rejected; 126struct fragment *next; 127}; 128 129/* 130 * When dealing with a binary patch, we reuse "leading" field 131 * to store the type of the binary hunk, either deflated "delta" 132 * or deflated "literal". 133 */ 134#define binary_patch_method leading 135#define BINARY_DELTA_DEFLATED 1 136#define BINARY_LITERAL_DEFLATED 2 137 138/* 139 * This represents a "patch" to a file, both metainfo changes 140 * such as creation/deletion, filemode and content changes represented 141 * as a series of fragments. 142 */ 143struct patch { 144char*new_name, *old_name, *def_name; 145unsigned int old_mode, new_mode; 146int is_new, is_delete;/* -1 = unknown, 0 = false, 1 = true */ 147int rejected; 148unsigned ws_rule; 149unsigned long deflate_origlen; 150int lines_added, lines_deleted; 151int score; 152unsigned int is_toplevel_relative:1; 153unsigned int inaccurate_eof:1; 154unsigned int is_binary:1; 155unsigned int is_copy:1; 156unsigned int is_rename:1; 157struct fragment *fragments; 158char*result; 159size_t resultsize; 160char old_sha1_prefix[41]; 161char new_sha1_prefix[41]; 162struct patch *next; 163}; 164 165/* 166 * A line in a file, len-bytes long (includes the terminating LF, 167 * except for an incomplete line at the end if the file ends with 168 * one), and its contents hashes to 'hash'. 169 */ 170struct line { 171size_t len; 172unsigned hash :24; 173unsigned flag :8; 174#define LINE_COMMON 1 175}; 176 177/* 178 * This represents a "file", which is an array of "lines". 179 */ 180struct image { 181char*buf; 182size_t len; 183size_t nr; 184size_t alloc; 185struct line *line_allocated; 186struct line *line; 187}; 188 189/* 190 * Records filenames that have been touched, in order to handle 191 * the case where more than one patches touch the same file. 192 */ 193 194static struct path_list fn_table; 195 196static uint32_thash_line(const char*cp,size_t len) 197{ 198size_t i; 199uint32_t h; 200for(i =0, h =0; i < len; i++) { 201if(!isspace(cp[i])) { 202 h = h *3+ (cp[i] &0xff); 203} 204} 205return h; 206} 207 208static voidadd_line_info(struct image *img,const char*bol,size_t len,unsigned flag) 209{ 210ALLOC_GROW(img->line_allocated, img->nr +1, img->alloc); 211 img->line_allocated[img->nr].len = len; 212 img->line_allocated[img->nr].hash =hash_line(bol, len); 213 img->line_allocated[img->nr].flag = flag; 214 img->nr++; 215} 216 217static voidprepare_image(struct image *image,char*buf,size_t len, 218int prepare_linetable) 219{ 220const char*cp, *ep; 221 222memset(image,0,sizeof(*image)); 223 image->buf = buf; 224 image->len = len; 225 226if(!prepare_linetable) 227return; 228 229 ep = image->buf + image->len; 230 cp = image->buf; 231while(cp < ep) { 232const char*next; 233for(next = cp; next < ep && *next !='\n'; next++) 234; 235if(next < ep) 236 next++; 237add_line_info(image, cp, next - cp,0); 238 cp = next; 239} 240 image->line = image->line_allocated; 241} 242 243static voidclear_image(struct image *image) 244{ 245free(image->buf); 246 image->buf = NULL; 247 image->len =0; 248} 249 250static voidsay_patch_name(FILE*output,const char*pre, 251struct patch *patch,const char*post) 252{ 253fputs(pre, output); 254if(patch->old_name && patch->new_name && 255strcmp(patch->old_name, patch->new_name)) { 256quote_c_style(patch->old_name, NULL, output,0); 257fputs(" => ", output); 258quote_c_style(patch->new_name, NULL, output,0); 259}else{ 260const char*n = patch->new_name; 261if(!n) 262 n = patch->old_name; 263quote_c_style(n, NULL, output,0); 264} 265fputs(post, output); 266} 267 268#define CHUNKSIZE (8192) 269#define SLOP (16) 270 271static voidread_patch_file(struct strbuf *sb,int fd) 272{ 273if(strbuf_read(sb, fd,0) <0) 274die("git-apply: read returned%s",strerror(errno)); 275 276/* 277 * Make sure that we have some slop in the buffer 278 * so that we can do speculative "memcmp" etc, and 279 * see to it that it is NUL-filled. 280 */ 281strbuf_grow(sb, SLOP); 282memset(sb->buf + sb->len,0, SLOP); 283} 284 285static unsigned longlinelen(const char*buffer,unsigned long size) 286{ 287unsigned long len =0; 288while(size--) { 289 len++; 290if(*buffer++ =='\n') 291break; 292} 293return len; 294} 295 296static intis_dev_null(const char*str) 297{ 298return!memcmp("/dev/null", str,9) &&isspace(str[9]); 299} 300 301#define TERM_SPACE 1 302#define TERM_TAB 2 303 304static intname_terminate(const char*name,int namelen,int c,int terminate) 305{ 306if(c ==' '&& !(terminate & TERM_SPACE)) 307return0; 308if(c =='\t'&& !(terminate & TERM_TAB)) 309return0; 310 311return1; 312} 313 314static char*find_name(const char*line,char*def,int p_value,int terminate) 315{ 316int len; 317const char*start = line; 318 319if(*line =='"') { 320struct strbuf name; 321 322/* 323 * Proposed "new-style" GNU patch/diff format; see 324 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2 325 */ 326strbuf_init(&name,0); 327if(!unquote_c_style(&name, line, NULL)) { 328char*cp; 329 330for(cp = name.buf; p_value; p_value--) { 331 cp =strchr(cp,'/'); 332if(!cp) 333break; 334 cp++; 335} 336if(cp) { 337/* name can later be freed, so we need 338 * to memmove, not just return cp 339 */ 340strbuf_remove(&name,0, cp - name.buf); 341free(def); 342returnstrbuf_detach(&name, NULL); 343} 344} 345strbuf_release(&name); 346} 347 348for(;;) { 349char c = *line; 350 351if(isspace(c)) { 352if(c =='\n') 353break; 354if(name_terminate(start, line-start, c, terminate)) 355break; 356} 357 line++; 358if(c =='/'&& !--p_value) 359 start = line; 360} 361if(!start) 362return def; 363 len = line - start; 364if(!len) 365return def; 366 367/* 368 * Generally we prefer the shorter name, especially 369 * if the other one is just a variation of that with 370 * something else tacked on to the end (ie "file.orig" 371 * or "file~"). 372 */ 373if(def) { 374int deflen =strlen(def); 375if(deflen < len && !strncmp(start, def, deflen)) 376return def; 377free(def); 378} 379 380returnxmemdupz(start, len); 381} 382 383static intcount_slashes(const char*cp) 384{ 385int cnt =0; 386char ch; 387 388while((ch = *cp++)) 389if(ch =='/') 390 cnt++; 391return cnt; 392} 393 394/* 395 * Given the string after "--- " or "+++ ", guess the appropriate 396 * p_value for the given patch. 397 */ 398static intguess_p_value(const char*nameline) 399{ 400char*name, *cp; 401int val = -1; 402 403if(is_dev_null(nameline)) 404return-1; 405 name =find_name(nameline, NULL,0, TERM_SPACE | TERM_TAB); 406if(!name) 407return-1; 408 cp =strchr(name,'/'); 409if(!cp) 410 val =0; 411else if(prefix) { 412/* 413 * Does it begin with "a/$our-prefix" and such? Then this is 414 * very likely to apply to our directory. 415 */ 416if(!strncmp(name, prefix, prefix_length)) 417 val =count_slashes(prefix); 418else{ 419 cp++; 420if(!strncmp(cp, prefix, prefix_length)) 421 val =count_slashes(prefix) +1; 422} 423} 424free(name); 425return val; 426} 427 428/* 429 * Get the name etc info from the ---/+++ lines of a traditional patch header 430 * 431 * FIXME! The end-of-filename heuristics are kind of screwy. For existing 432 * files, we can happily check the index for a match, but for creating a 433 * new file we should try to match whatever "patch" does. I have no idea. 434 */ 435static voidparse_traditional_patch(const char*first,const char*second,struct patch *patch) 436{ 437char*name; 438 439 first +=4;/* skip "--- " */ 440 second +=4;/* skip "+++ " */ 441if(!p_value_known) { 442int p, q; 443 p =guess_p_value(first); 444 q =guess_p_value(second); 445if(p <0) p = q; 446if(0<= p && p == q) { 447 p_value = p; 448 p_value_known =1; 449} 450} 451if(is_dev_null(first)) { 452 patch->is_new =1; 453 patch->is_delete =0; 454 name =find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB); 455 patch->new_name = name; 456}else if(is_dev_null(second)) { 457 patch->is_new =0; 458 patch->is_delete =1; 459 name =find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB); 460 patch->old_name = name; 461}else{ 462 name =find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB); 463 name =find_name(second, name, p_value, TERM_SPACE | TERM_TAB); 464 patch->old_name = patch->new_name = name; 465} 466if(!name) 467die("unable to find filename in patch at line%d", linenr); 468} 469 470static intgitdiff_hdrend(const char*line,struct patch *patch) 471{ 472return-1; 473} 474 475/* 476 * We're anal about diff header consistency, to make 477 * sure that we don't end up having strange ambiguous 478 * patches floating around. 479 * 480 * As a result, gitdiff_{old|new}name() will check 481 * their names against any previous information, just 482 * to make sure.. 483 */ 484static char*gitdiff_verify_name(const char*line,int isnull,char*orig_name,const char*oldnew) 485{ 486if(!orig_name && !isnull) 487returnfind_name(line, NULL, p_value, TERM_TAB); 488 489if(orig_name) { 490int len; 491const char*name; 492char*another; 493 name = orig_name; 494 len =strlen(name); 495if(isnull) 496die("git-apply: bad git-diff - expected /dev/null, got%son line%d", name, linenr); 497 another =find_name(line, NULL, p_value, TERM_TAB); 498if(!another ||memcmp(another, name, len)) 499die("git-apply: bad git-diff - inconsistent%sfilename on line%d", oldnew, linenr); 500free(another); 501return orig_name; 502} 503else{ 504/* expect "/dev/null" */ 505if(memcmp("/dev/null", line,9) || line[9] !='\n') 506die("git-apply: bad git-diff - expected /dev/null on line%d", linenr); 507return NULL; 508} 509} 510 511static intgitdiff_oldname(const char*line,struct patch *patch) 512{ 513 patch->old_name =gitdiff_verify_name(line, patch->is_new, patch->old_name,"old"); 514return0; 515} 516 517static intgitdiff_newname(const char*line,struct patch *patch) 518{ 519 patch->new_name =gitdiff_verify_name(line, patch->is_delete, patch->new_name,"new"); 520return0; 521} 522 523static intgitdiff_oldmode(const char*line,struct patch *patch) 524{ 525 patch->old_mode =strtoul(line, NULL,8); 526return0; 527} 528 529static intgitdiff_newmode(const char*line,struct patch *patch) 530{ 531 patch->new_mode =strtoul(line, NULL,8); 532return0; 533} 534 535static intgitdiff_delete(const char*line,struct patch *patch) 536{ 537 patch->is_delete =1; 538 patch->old_name = patch->def_name; 539returngitdiff_oldmode(line, patch); 540} 541 542static intgitdiff_newfile(const char*line,struct patch *patch) 543{ 544 patch->is_new =1; 545 patch->new_name = patch->def_name; 546returngitdiff_newmode(line, patch); 547} 548 549static intgitdiff_copysrc(const char*line,struct patch *patch) 550{ 551 patch->is_copy =1; 552 patch->old_name =find_name(line, NULL,0,0); 553return0; 554} 555 556static intgitdiff_copydst(const char*line,struct patch *patch) 557{ 558 patch->is_copy =1; 559 patch->new_name =find_name(line, NULL,0,0); 560return0; 561} 562 563static intgitdiff_renamesrc(const char*line,struct patch *patch) 564{ 565 patch->is_rename =1; 566 patch->old_name =find_name(line, NULL,0,0); 567return0; 568} 569 570static intgitdiff_renamedst(const char*line,struct patch *patch) 571{ 572 patch->is_rename =1; 573 patch->new_name =find_name(line, NULL,0,0); 574return0; 575} 576 577static intgitdiff_similarity(const char*line,struct patch *patch) 578{ 579if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 580 patch->score =0; 581return0; 582} 583 584static intgitdiff_dissimilarity(const char*line,struct patch *patch) 585{ 586if((patch->score =strtoul(line, NULL,10)) == ULONG_MAX) 587 patch->score =0; 588return0; 589} 590 591static intgitdiff_index(const char*line,struct patch *patch) 592{ 593/* 594 * index line is N hexadecimal, "..", N hexadecimal, 595 * and optional space with octal mode. 596 */ 597const char*ptr, *eol; 598int len; 599 600 ptr =strchr(line,'.'); 601if(!ptr || ptr[1] !='.'||40< ptr - line) 602return0; 603 len = ptr - line; 604memcpy(patch->old_sha1_prefix, line, len); 605 patch->old_sha1_prefix[len] =0; 606 607 line = ptr +2; 608 ptr =strchr(line,' '); 609 eol =strchr(line,'\n'); 610 611if(!ptr || eol < ptr) 612 ptr = eol; 613 len = ptr - line; 614 615if(40< len) 616return0; 617memcpy(patch->new_sha1_prefix, line, len); 618 patch->new_sha1_prefix[len] =0; 619if(*ptr ==' ') 620 patch->new_mode = patch->old_mode =strtoul(ptr+1, NULL,8); 621return0; 622} 623 624/* 625 * This is normal for a diff that doesn't change anything: we'll fall through 626 * into the next diff. Tell the parser to break out. 627 */ 628static intgitdiff_unrecognized(const char*line,struct patch *patch) 629{ 630return-1; 631} 632 633static const char*stop_at_slash(const char*line,int llen) 634{ 635int i; 636 637for(i =0; i < llen; i++) { 638int ch = line[i]; 639if(ch =='/') 640return line + i; 641} 642return NULL; 643} 644 645/* 646 * This is to extract the same name that appears on "diff --git" 647 * line. We do not find and return anything if it is a rename 648 * patch, and it is OK because we will find the name elsewhere. 649 * We need to reliably find name only when it is mode-change only, 650 * creation or deletion of an empty file. In any of these cases, 651 * both sides are the same name under a/ and b/ respectively. 652 */ 653static char*git_header_name(char*line,int llen) 654{ 655const char*name; 656const char*second = NULL; 657size_t len; 658 659 line +=strlen("diff --git "); 660 llen -=strlen("diff --git "); 661 662if(*line =='"') { 663const char*cp; 664struct strbuf first; 665struct strbuf sp; 666 667strbuf_init(&first,0); 668strbuf_init(&sp,0); 669 670if(unquote_c_style(&first, line, &second)) 671goto free_and_fail1; 672 673/* advance to the first slash */ 674 cp =stop_at_slash(first.buf, first.len); 675/* we do not accept absolute paths */ 676if(!cp || cp == first.buf) 677goto free_and_fail1; 678strbuf_remove(&first,0, cp +1- first.buf); 679 680/* 681 * second points at one past closing dq of name. 682 * find the second name. 683 */ 684while((second < line + llen) &&isspace(*second)) 685 second++; 686 687if(line + llen <= second) 688goto free_and_fail1; 689if(*second =='"') { 690if(unquote_c_style(&sp, second, NULL)) 691goto free_and_fail1; 692 cp =stop_at_slash(sp.buf, sp.len); 693if(!cp || cp == sp.buf) 694goto free_and_fail1; 695/* They must match, otherwise ignore */ 696if(strcmp(cp +1, first.buf)) 697goto free_and_fail1; 698strbuf_release(&sp); 699returnstrbuf_detach(&first, NULL); 700} 701 702/* unquoted second */ 703 cp =stop_at_slash(second, line + llen - second); 704if(!cp || cp == second) 705goto free_and_fail1; 706 cp++; 707if(line + llen - cp != first.len +1|| 708memcmp(first.buf, cp, first.len)) 709goto free_and_fail1; 710returnstrbuf_detach(&first, NULL); 711 712 free_and_fail1: 713strbuf_release(&first); 714strbuf_release(&sp); 715return NULL; 716} 717 718/* unquoted first name */ 719 name =stop_at_slash(line, llen); 720if(!name || name == line) 721return NULL; 722 name++; 723 724/* 725 * since the first name is unquoted, a dq if exists must be 726 * the beginning of the second name. 727 */ 728for(second = name; second < line + llen; second++) { 729if(*second =='"') { 730struct strbuf sp; 731const char*np; 732 733strbuf_init(&sp,0); 734if(unquote_c_style(&sp, second, NULL)) 735goto free_and_fail2; 736 737 np =stop_at_slash(sp.buf, sp.len); 738if(!np || np == sp.buf) 739goto free_and_fail2; 740 np++; 741 742 len = sp.buf + sp.len - np; 743if(len < second - name && 744!strncmp(np, name, len) && 745isspace(name[len])) { 746/* Good */ 747strbuf_remove(&sp,0, np - sp.buf); 748returnstrbuf_detach(&sp, NULL); 749} 750 751 free_and_fail2: 752strbuf_release(&sp); 753return NULL; 754} 755} 756 757/* 758 * Accept a name only if it shows up twice, exactly the same 759 * form. 760 */ 761for(len =0; ; len++) { 762switch(name[len]) { 763default: 764continue; 765case'\n': 766return NULL; 767case'\t':case' ': 768 second = name+len; 769for(;;) { 770char c = *second++; 771if(c =='\n') 772return NULL; 773if(c =='/') 774break; 775} 776if(second[len] =='\n'&& !memcmp(name, second, len)) { 777returnxmemdupz(name, len); 778} 779} 780} 781} 782 783/* Verify that we recognize the lines following a git header */ 784static intparse_git_header(char*line,int len,unsigned int size,struct patch *patch) 785{ 786unsigned long offset; 787 788/* A git diff has explicit new/delete information, so we don't guess */ 789 patch->is_new =0; 790 patch->is_delete =0; 791 792/* 793 * Some things may not have the old name in the 794 * rest of the headers anywhere (pure mode changes, 795 * or removing or adding empty files), so we get 796 * the default name from the header. 797 */ 798 patch->def_name =git_header_name(line, len); 799 800 line += len; 801 size -= len; 802 linenr++; 803for(offset = len ; size >0; offset += len, size -= len, line += len, linenr++) { 804static const struct opentry { 805const char*str; 806int(*fn)(const char*,struct patch *); 807} optable[] = { 808{"@@ -", gitdiff_hdrend }, 809{"--- ", gitdiff_oldname }, 810{"+++ ", gitdiff_newname }, 811{"old mode ", gitdiff_oldmode }, 812{"new mode ", gitdiff_newmode }, 813{"deleted file mode ", gitdiff_delete }, 814{"new file mode ", gitdiff_newfile }, 815{"copy from ", gitdiff_copysrc }, 816{"copy to ", gitdiff_copydst }, 817{"rename old ", gitdiff_renamesrc }, 818{"rename new ", gitdiff_renamedst }, 819{"rename from ", gitdiff_renamesrc }, 820{"rename to ", gitdiff_renamedst }, 821{"similarity index ", gitdiff_similarity }, 822{"dissimilarity index ", gitdiff_dissimilarity }, 823{"index ", gitdiff_index }, 824{"", gitdiff_unrecognized }, 825}; 826int i; 827 828 len =linelen(line, size); 829if(!len || line[len-1] !='\n') 830break; 831for(i =0; i <ARRAY_SIZE(optable); i++) { 832const struct opentry *p = optable + i; 833int oplen =strlen(p->str); 834if(len < oplen ||memcmp(p->str, line, oplen)) 835continue; 836if(p->fn(line + oplen, patch) <0) 837return offset; 838break; 839} 840} 841 842return offset; 843} 844 845static intparse_num(const char*line,unsigned long*p) 846{ 847char*ptr; 848 849if(!isdigit(*line)) 850return0; 851*p =strtoul(line, &ptr,10); 852return ptr - line; 853} 854 855static intparse_range(const char*line,int len,int offset,const char*expect, 856unsigned long*p1,unsigned long*p2) 857{ 858int digits, ex; 859 860if(offset <0|| offset >= len) 861return-1; 862 line += offset; 863 len -= offset; 864 865 digits =parse_num(line, p1); 866if(!digits) 867return-1; 868 869 offset += digits; 870 line += digits; 871 len -= digits; 872 873*p2 =1; 874if(*line ==',') { 875 digits =parse_num(line+1, p2); 876if(!digits) 877return-1; 878 879 offset += digits+1; 880 line += digits+1; 881 len -= digits+1; 882} 883 884 ex =strlen(expect); 885if(ex > len) 886return-1; 887if(memcmp(line, expect, ex)) 888return-1; 889 890return offset + ex; 891} 892 893/* 894 * Parse a unified diff fragment header of the 895 * form "@@ -a,b +c,d @@" 896 */ 897static intparse_fragment_header(char*line,int len,struct fragment *fragment) 898{ 899int offset; 900 901if(!len || line[len-1] !='\n') 902return-1; 903 904/* Figure out the number of lines in a fragment */ 905 offset =parse_range(line, len,4," +", &fragment->oldpos, &fragment->oldlines); 906 offset =parse_range(line, len, offset," @@", &fragment->newpos, &fragment->newlines); 907 908return offset; 909} 910 911static intfind_header(char*line,unsigned long size,int*hdrsize,struct patch *patch) 912{ 913unsigned long offset, len; 914 915 patch->is_toplevel_relative =0; 916 patch->is_rename = patch->is_copy =0; 917 patch->is_new = patch->is_delete = -1; 918 patch->old_mode = patch->new_mode =0; 919 patch->old_name = patch->new_name = NULL; 920for(offset =0; size >0; offset += len, size -= len, line += len, linenr++) { 921unsigned long nextlen; 922 923 len =linelen(line, size); 924if(!len) 925break; 926 927/* Testing this early allows us to take a few shortcuts.. */ 928if(len <6) 929continue; 930 931/* 932 * Make sure we don't find any unconnected patch fragments. 933 * That's a sign that we didn't find a header, and that a 934 * patch has become corrupted/broken up. 935 */ 936if(!memcmp("@@ -", line,4)) { 937struct fragment dummy; 938if(parse_fragment_header(line, len, &dummy) <0) 939continue; 940die("patch fragment without header at line%d: %.*s", 941 linenr, (int)len-1, line); 942} 943 944if(size < len +6) 945break; 946 947/* 948 * Git patch? It might not have a real patch, just a rename 949 * or mode change, so we handle that specially 950 */ 951if(!memcmp("diff --git ", line,11)) { 952int git_hdr_len =parse_git_header(line, len, size, patch); 953if(git_hdr_len <= len) 954continue; 955if(!patch->old_name && !patch->new_name) { 956if(!patch->def_name) 957die("git diff header lacks filename information (line%d)", linenr); 958 patch->old_name = patch->new_name = patch->def_name; 959} 960 patch->is_toplevel_relative =1; 961*hdrsize = git_hdr_len; 962return offset; 963} 964 965/* --- followed by +++ ? */ 966if(memcmp("--- ", line,4) ||memcmp("+++ ", line + len,4)) 967continue; 968 969/* 970 * We only accept unified patches, so we want it to 971 * at least have "@@ -a,b +c,d @@\n", which is 14 chars 972 * minimum ("@@ -0,0 +1 @@\n" is the shortest). 973 */ 974 nextlen =linelen(line + len, size - len); 975if(size < nextlen +14||memcmp("@@ -", line + len + nextlen,4)) 976continue; 977 978/* Ok, we'll consider it a patch */ 979parse_traditional_patch(line, line+len, patch); 980*hdrsize = len + nextlen; 981 linenr +=2; 982return offset; 983} 984return-1; 985} 986 987static voidcheck_whitespace(const char*line,int len,unsigned ws_rule) 988{ 989char*err; 990unsigned result =check_and_emit_line(line +1, len -1, ws_rule, 991 NULL, NULL, NULL, NULL); 992if(!result) 993return; 994 995 whitespace_error++; 996if(squelch_whitespace_errors && 997 squelch_whitespace_errors < whitespace_error) 998; 999else{1000 err =whitespace_error_string(result);1001fprintf(stderr,"%s:%d:%s.\n%.*s\n",1002 patch_input_file, linenr, err, len -2, line +1);1003free(err);1004}1005}10061007/*1008 * Parse a unified diff. Note that this really needs to parse each1009 * fragment separately, since the only way to know the difference1010 * between a "---" that is part of a patch, and a "---" that starts1011 * the next patch is to look at the line counts..1012 */1013static intparse_fragment(char*line,unsigned long size,1014struct patch *patch,struct fragment *fragment)1015{1016int added, deleted;1017int len =linelen(line, size), offset;1018unsigned long oldlines, newlines;1019unsigned long leading, trailing;10201021 offset =parse_fragment_header(line, len, fragment);1022if(offset <0)1023return-1;1024 oldlines = fragment->oldlines;1025 newlines = fragment->newlines;1026 leading =0;1027 trailing =0;10281029/* Parse the thing.. */1030 line += len;1031 size -= len;1032 linenr++;1033 added = deleted =0;1034for(offset = len;10350< size;1036 offset += len, size -= len, line += len, linenr++) {1037if(!oldlines && !newlines)1038break;1039 len =linelen(line, size);1040if(!len || line[len-1] !='\n')1041return-1;1042switch(*line) {1043default:1044return-1;1045case'\n':/* newer GNU diff, an empty context line */1046case' ':1047 oldlines--;1048 newlines--;1049if(!deleted && !added)1050 leading++;1051 trailing++;1052break;1053case'-':1054if(apply_in_reverse &&1055 ws_error_action != nowarn_ws_error)1056check_whitespace(line, len, patch->ws_rule);1057 deleted++;1058 oldlines--;1059 trailing =0;1060break;1061case'+':1062if(!apply_in_reverse &&1063 ws_error_action != nowarn_ws_error)1064check_whitespace(line, len, patch->ws_rule);1065 added++;1066 newlines--;1067 trailing =0;1068break;10691070/*1071 * We allow "\ No newline at end of file". Depending1072 * on locale settings when the patch was produced we1073 * don't know what this line looks like. The only1074 * thing we do know is that it begins with "\ ".1075 * Checking for 12 is just for sanity check -- any1076 * l10n of "\ No newline..." is at least that long.1077 */1078case'\\':1079if(len <12||memcmp(line,"\\",2))1080return-1;1081break;1082}1083}1084if(oldlines || newlines)1085return-1;1086 fragment->leading = leading;1087 fragment->trailing = trailing;10881089/*1090 * If a fragment ends with an incomplete line, we failed to include1091 * it in the above loop because we hit oldlines == newlines == 01092 * before seeing it.1093 */1094if(12< size && !memcmp(line,"\\",2))1095 offset +=linelen(line, size);10961097 patch->lines_added += added;1098 patch->lines_deleted += deleted;10991100if(0< patch->is_new && oldlines)1101returnerror("new file depends on old contents");1102if(0< patch->is_delete && newlines)1103returnerror("deleted file still has contents");1104return offset;1105}11061107static intparse_single_patch(char*line,unsigned long size,struct patch *patch)1108{1109unsigned long offset =0;1110unsigned long oldlines =0, newlines =0, context =0;1111struct fragment **fragp = &patch->fragments;11121113while(size >4&& !memcmp(line,"@@ -",4)) {1114struct fragment *fragment;1115int len;11161117 fragment =xcalloc(1,sizeof(*fragment));1118 len =parse_fragment(line, size, patch, fragment);1119if(len <=0)1120die("corrupt patch at line%d", linenr);1121 fragment->patch = line;1122 fragment->size = len;1123 oldlines += fragment->oldlines;1124 newlines += fragment->newlines;1125 context += fragment->leading + fragment->trailing;11261127*fragp = fragment;1128 fragp = &fragment->next;11291130 offset += len;1131 line += len;1132 size -= len;1133}11341135/*1136 * If something was removed (i.e. we have old-lines) it cannot1137 * be creation, and if something was added it cannot be1138 * deletion. However, the reverse is not true; --unified=01139 * patches that only add are not necessarily creation even1140 * though they do not have any old lines, and ones that only1141 * delete are not necessarily deletion.1142 *1143 * Unfortunately, a real creation/deletion patch do _not_ have1144 * any context line by definition, so we cannot safely tell it1145 * apart with --unified=0 insanity. At least if the patch has1146 * more than one hunk it is not creation or deletion.1147 */1148if(patch->is_new <0&&1149(oldlines || (patch->fragments && patch->fragments->next)))1150 patch->is_new =0;1151if(patch->is_delete <0&&1152(newlines || (patch->fragments && patch->fragments->next)))1153 patch->is_delete =0;11541155if(0< patch->is_new && oldlines)1156die("new file%sdepends on old contents", patch->new_name);1157if(0< patch->is_delete && newlines)1158die("deleted file%sstill has contents", patch->old_name);1159if(!patch->is_delete && !newlines && context)1160fprintf(stderr,"** warning: file%sbecomes empty but "1161"is not deleted\n", patch->new_name);11621163return offset;1164}11651166staticinlineintmetadata_changes(struct patch *patch)1167{1168return patch->is_rename >0||1169 patch->is_copy >0||1170 patch->is_new >0||1171 patch->is_delete ||1172(patch->old_mode && patch->new_mode &&1173 patch->old_mode != patch->new_mode);1174}11751176static char*inflate_it(const void*data,unsigned long size,1177unsigned long inflated_size)1178{1179 z_stream stream;1180void*out;1181int st;11821183memset(&stream,0,sizeof(stream));11841185 stream.next_in = (unsigned char*)data;1186 stream.avail_in = size;1187 stream.next_out = out =xmalloc(inflated_size);1188 stream.avail_out = inflated_size;1189inflateInit(&stream);1190 st =inflate(&stream, Z_FINISH);1191if((st != Z_STREAM_END) || stream.total_out != inflated_size) {1192free(out);1193return NULL;1194}1195return out;1196}11971198static struct fragment *parse_binary_hunk(char**buf_p,1199unsigned long*sz_p,1200int*status_p,1201int*used_p)1202{1203/*1204 * Expect a line that begins with binary patch method ("literal"1205 * or "delta"), followed by the length of data before deflating.1206 * a sequence of 'length-byte' followed by base-85 encoded data1207 * should follow, terminated by a newline.1208 *1209 * Each 5-byte sequence of base-85 encodes up to 4 bytes,1210 * and we would limit the patch line to 66 characters,1211 * so one line can fit up to 13 groups that would decode1212 * to 52 bytes max. The length byte 'A'-'Z' corresponds1213 * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.1214 */1215int llen, used;1216unsigned long size = *sz_p;1217char*buffer = *buf_p;1218int patch_method;1219unsigned long origlen;1220char*data = NULL;1221int hunk_size =0;1222struct fragment *frag;12231224 llen =linelen(buffer, size);1225 used = llen;12261227*status_p =0;12281229if(!prefixcmp(buffer,"delta ")) {1230 patch_method = BINARY_DELTA_DEFLATED;1231 origlen =strtoul(buffer +6, NULL,10);1232}1233else if(!prefixcmp(buffer,"literal ")) {1234 patch_method = BINARY_LITERAL_DEFLATED;1235 origlen =strtoul(buffer +8, NULL,10);1236}1237else1238return NULL;12391240 linenr++;1241 buffer += llen;1242while(1) {1243int byte_length, max_byte_length, newsize;1244 llen =linelen(buffer, size);1245 used += llen;1246 linenr++;1247if(llen ==1) {1248/* consume the blank line */1249 buffer++;1250 size--;1251break;1252}1253/*1254 * Minimum line is "A00000\n" which is 7-byte long,1255 * and the line length must be multiple of 5 plus 2.1256 */1257if((llen <7) || (llen-2) %5)1258goto corrupt;1259 max_byte_length = (llen -2) /5*4;1260 byte_length = *buffer;1261if('A'<= byte_length && byte_length <='Z')1262 byte_length = byte_length -'A'+1;1263else if('a'<= byte_length && byte_length <='z')1264 byte_length = byte_length -'a'+27;1265else1266goto corrupt;1267/* if the input length was not multiple of 4, we would1268 * have filler at the end but the filler should never1269 * exceed 3 bytes1270 */1271if(max_byte_length < byte_length ||1272 byte_length <= max_byte_length -4)1273goto corrupt;1274 newsize = hunk_size + byte_length;1275 data =xrealloc(data, newsize);1276if(decode_85(data + hunk_size, buffer +1, byte_length))1277goto corrupt;1278 hunk_size = newsize;1279 buffer += llen;1280 size -= llen;1281}12821283 frag =xcalloc(1,sizeof(*frag));1284 frag->patch =inflate_it(data, hunk_size, origlen);1285if(!frag->patch)1286goto corrupt;1287free(data);1288 frag->size = origlen;1289*buf_p = buffer;1290*sz_p = size;1291*used_p = used;1292 frag->binary_patch_method = patch_method;1293return frag;12941295 corrupt:1296free(data);1297*status_p = -1;1298error("corrupt binary patch at line%d: %.*s",1299 linenr-1, llen-1, buffer);1300return NULL;1301}13021303static intparse_binary(char*buffer,unsigned long size,struct patch *patch)1304{1305/*1306 * We have read "GIT binary patch\n"; what follows is a line1307 * that says the patch method (currently, either "literal" or1308 * "delta") and the length of data before deflating; a1309 * sequence of 'length-byte' followed by base-85 encoded data1310 * follows.1311 *1312 * When a binary patch is reversible, there is another binary1313 * hunk in the same format, starting with patch method (either1314 * "literal" or "delta") with the length of data, and a sequence1315 * of length-byte + base-85 encoded data, terminated with another1316 * empty line. This data, when applied to the postimage, produces1317 * the preimage.1318 */1319struct fragment *forward;1320struct fragment *reverse;1321int status;1322int used, used_1;13231324 forward =parse_binary_hunk(&buffer, &size, &status, &used);1325if(!forward && !status)1326/* there has to be one hunk (forward hunk) */1327returnerror("unrecognized binary patch at line%d", linenr-1);1328if(status)1329/* otherwise we already gave an error message */1330return status;13311332 reverse =parse_binary_hunk(&buffer, &size, &status, &used_1);1333if(reverse)1334 used += used_1;1335else if(status) {1336/*1337 * Not having reverse hunk is not an error, but having1338 * a corrupt reverse hunk is.1339 */1340free((void*) forward->patch);1341free(forward);1342return status;1343}1344 forward->next = reverse;1345 patch->fragments = forward;1346 patch->is_binary =1;1347return used;1348}13491350static intparse_chunk(char*buffer,unsigned long size,struct patch *patch)1351{1352int hdrsize, patchsize;1353int offset =find_header(buffer, size, &hdrsize, patch);13541355if(offset <0)1356return offset;13571358 patch->ws_rule =whitespace_rule(patch->new_name1359? patch->new_name1360: patch->old_name);13611362 patchsize =parse_single_patch(buffer + offset + hdrsize,1363 size - offset - hdrsize, patch);13641365if(!patchsize) {1366static const char*binhdr[] = {1367"Binary files ",1368"Files ",1369 NULL,1370};1371static const char git_binary[] ="GIT binary patch\n";1372int i;1373int hd = hdrsize + offset;1374unsigned long llen =linelen(buffer + hd, size - hd);13751376if(llen ==sizeof(git_binary) -1&&1377!memcmp(git_binary, buffer + hd, llen)) {1378int used;1379 linenr++;1380 used =parse_binary(buffer + hd + llen,1381 size - hd - llen, patch);1382if(used)1383 patchsize = used + llen;1384else1385 patchsize =0;1386}1387else if(!memcmp(" differ\n", buffer + hd + llen -8,8)) {1388for(i =0; binhdr[i]; i++) {1389int len =strlen(binhdr[i]);1390if(len < size - hd &&1391!memcmp(binhdr[i], buffer + hd, len)) {1392 linenr++;1393 patch->is_binary =1;1394 patchsize = llen;1395break;1396}1397}1398}13991400/* Empty patch cannot be applied if it is a text patch1401 * without metadata change. A binary patch appears1402 * empty to us here.1403 */1404if((apply || check) &&1405(!patch->is_binary && !metadata_changes(patch)))1406die("patch with only garbage at line%d", linenr);1407}14081409return offset + hdrsize + patchsize;1410}14111412#define swap(a,b) myswap((a),(b),sizeof(a))14131414#define myswap(a, b, size) do { \1415 unsigned char mytmp[size]; \1416 memcpy(mytmp, &a, size); \1417 memcpy(&a, &b, size); \1418 memcpy(&b, mytmp, size); \1419} while (0)14201421static voidreverse_patches(struct patch *p)1422{1423for(; p; p = p->next) {1424struct fragment *frag = p->fragments;14251426swap(p->new_name, p->old_name);1427swap(p->new_mode, p->old_mode);1428swap(p->is_new, p->is_delete);1429swap(p->lines_added, p->lines_deleted);1430swap(p->old_sha1_prefix, p->new_sha1_prefix);14311432for(; frag; frag = frag->next) {1433swap(frag->newpos, frag->oldpos);1434swap(frag->newlines, frag->oldlines);1435}1436}1437}14381439static const char pluses[] =1440"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";1441static const char minuses[]=1442"----------------------------------------------------------------------";14431444static voidshow_stats(struct patch *patch)1445{1446struct strbuf qname;1447char*cp = patch->new_name ? patch->new_name : patch->old_name;1448int max, add, del;14491450strbuf_init(&qname,0);1451quote_c_style(cp, &qname, NULL,0);14521453/*1454 * "scale" the filename1455 */1456 max = max_len;1457if(max >50)1458 max =50;14591460if(qname.len > max) {1461 cp =strchr(qname.buf + qname.len +3- max,'/');1462if(!cp)1463 cp = qname.buf + qname.len +3- max;1464strbuf_splice(&qname,0, cp - qname.buf,"...",3);1465}14661467if(patch->is_binary) {1468printf(" %-*s | Bin\n", max, qname.buf);1469strbuf_release(&qname);1470return;1471}14721473printf(" %-*s |", max, qname.buf);1474strbuf_release(&qname);14751476/*1477 * scale the add/delete1478 */1479 max = max + max_change >70?70- max : max_change;1480 add = patch->lines_added;1481 del = patch->lines_deleted;14821483if(max_change >0) {1484int total = ((add + del) * max + max_change /2) / max_change;1485 add = (add * max + max_change /2) / max_change;1486 del = total - add;1487}1488printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,1489 add, pluses, del, minuses);1490}14911492static intread_old_data(struct stat *st,const char*path,struct strbuf *buf)1493{1494switch(st->st_mode & S_IFMT) {1495case S_IFLNK:1496strbuf_grow(buf, st->st_size);1497if(readlink(path, buf->buf, st->st_size) != st->st_size)1498return-1;1499strbuf_setlen(buf, st->st_size);1500return0;1501case S_IFREG:1502if(strbuf_read_file(buf, path, st->st_size) != st->st_size)1503returnerror("unable to open or read%s", path);1504convert_to_git(path, buf->buf, buf->len, buf,0);1505return0;1506default:1507return-1;1508}1509}15101511static voidupdate_pre_post_images(struct image *preimage,1512struct image *postimage,1513char*buf,1514size_t len)1515{1516int i, ctx;1517char*new, *old, *fixed;1518struct image fixed_preimage;15191520/*1521 * Update the preimage with whitespace fixes. Note that we1522 * are not losing preimage->buf -- apply_one_fragment() will1523 * free "oldlines".1524 */1525prepare_image(&fixed_preimage, buf, len,1);1526assert(fixed_preimage.nr == preimage->nr);1527for(i =0; i < preimage->nr; i++)1528 fixed_preimage.line[i].flag = preimage->line[i].flag;1529free(preimage->line_allocated);1530*preimage = fixed_preimage;15311532/*1533 * Adjust the common context lines in postimage, in place.1534 * This is possible because whitespace fixing does not make1535 * the string grow.1536 */1537new= old = postimage->buf;1538 fixed = preimage->buf;1539for(i = ctx =0; i < postimage->nr; i++) {1540size_t len = postimage->line[i].len;1541if(!(postimage->line[i].flag & LINE_COMMON)) {1542/* an added line -- no counterparts in preimage */1543memmove(new, old, len);1544 old += len;1545new+= len;1546continue;1547}15481549/* a common context -- skip it in the original postimage */1550 old += len;15511552/* and find the corresponding one in the fixed preimage */1553while(ctx < preimage->nr &&1554!(preimage->line[ctx].flag & LINE_COMMON)) {1555 fixed += preimage->line[ctx].len;1556 ctx++;1557}1558if(preimage->nr <= ctx)1559die("oops");15601561/* and copy it in, while fixing the line length */1562 len = preimage->line[ctx].len;1563memcpy(new, fixed, len);1564new+= len;1565 fixed += len;1566 postimage->line[i].len = len;1567 ctx++;1568}15691570/* Fix the length of the whole thing */1571 postimage->len =new- postimage->buf;1572}15731574static intmatch_fragment(struct image *img,1575struct image *preimage,1576struct image *postimage,1577unsigned longtry,1578int try_lno,1579unsigned ws_rule,1580int match_beginning,int match_end)1581{1582int i;1583char*fixed_buf, *buf, *orig, *target;15841585if(preimage->nr + try_lno > img->nr)1586return0;15871588if(match_beginning && try_lno)1589return0;15901591if(match_end && preimage->nr + try_lno != img->nr)1592return0;15931594/* Quick hash check */1595for(i =0; i < preimage->nr; i++)1596if(preimage->line[i].hash != img->line[try_lno + i].hash)1597return0;15981599/*1600 * Do we have an exact match? If we were told to match1601 * at the end, size must be exactly at try+fragsize,1602 * otherwise try+fragsize must be still within the preimage,1603 * and either case, the old piece should match the preimage1604 * exactly.1605 */1606if((match_end1607? (try+ preimage->len == img->len)1608: (try+ preimage->len <= img->len)) &&1609!memcmp(img->buf +try, preimage->buf, preimage->len))1610return1;16111612if(ws_error_action != correct_ws_error)1613return0;16141615/*1616 * The hunk does not apply byte-by-byte, but the hash says1617 * it might with whitespace fuzz.1618 */1619 fixed_buf =xmalloc(preimage->len +1);1620 buf = fixed_buf;1621 orig = preimage->buf;1622 target = img->buf +try;1623for(i =0; i < preimage->nr; i++) {1624size_t fixlen;/* length after fixing the preimage */1625size_t oldlen = preimage->line[i].len;1626size_t tgtlen = img->line[try_lno + i].len;1627size_t tgtfixlen;/* length after fixing the target line */1628char tgtfixbuf[1024], *tgtfix;1629int match;16301631/* Try fixing the line in the preimage */1632 fixlen =ws_fix_copy(buf, orig, oldlen, ws_rule, NULL);16331634/* Try fixing the line in the target */1635if(sizeof(tgtfixbuf) < tgtlen)1636 tgtfix = tgtfixbuf;1637else1638 tgtfix =xmalloc(tgtlen);1639 tgtfixlen =ws_fix_copy(tgtfix, target, tgtlen, ws_rule, NULL);16401641/*1642 * If they match, either the preimage was based on1643 * a version before our tree fixed whitespace breakage,1644 * or we are lacking a whitespace-fix patch the tree1645 * the preimage was based on already had (i.e. target1646 * has whitespace breakage, the preimage doesn't).1647 * In either case, we are fixing the whitespace breakages1648 * so we might as well take the fix together with their1649 * real change.1650 */1651 match = (tgtfixlen == fixlen && !memcmp(tgtfix, buf, fixlen));16521653if(tgtfix != tgtfixbuf)1654free(tgtfix);1655if(!match)1656goto unmatch_exit;16571658 orig += oldlen;1659 buf += fixlen;1660 target += tgtlen;1661}16621663/*1664 * Yes, the preimage is based on an older version that still1665 * has whitespace breakages unfixed, and fixing them makes the1666 * hunk match. Update the context lines in the postimage.1667 */1668update_pre_post_images(preimage, postimage,1669 fixed_buf, buf - fixed_buf);1670return1;16711672 unmatch_exit:1673free(fixed_buf);1674return0;1675}16761677static intfind_pos(struct image *img,1678struct image *preimage,1679struct image *postimage,1680int line,1681unsigned ws_rule,1682int match_beginning,int match_end)1683{1684int i;1685unsigned long backwards, forwards,try;1686int backwards_lno, forwards_lno, try_lno;16871688if(preimage->nr > img->nr)1689return-1;16901691/*1692 * If match_begining or match_end is specified, there is no1693 * point starting from a wrong line that will never match and1694 * wander around and wait for a match at the specified end.1695 */1696if(match_beginning)1697 line =0;1698else if(match_end)1699 line = img->nr - preimage->nr;17001701if(line > img->nr)1702 line = img->nr;17031704try=0;1705for(i =0; i < line; i++)1706try+= img->line[i].len;17071708/*1709 * There's probably some smart way to do this, but I'll leave1710 * that to the smart and beautiful people. I'm simple and stupid.1711 */1712 backwards =try;1713 backwards_lno = line;1714 forwards =try;1715 forwards_lno = line;1716 try_lno = line;17171718for(i =0; ; i++) {1719if(match_fragment(img, preimage, postimage,1720try, try_lno, ws_rule,1721 match_beginning, match_end))1722return try_lno;17231724 again:1725if(backwards_lno ==0&& forwards_lno == img->nr)1726break;17271728if(i &1) {1729if(backwards_lno ==0) {1730 i++;1731goto again;1732}1733 backwards_lno--;1734 backwards -= img->line[backwards_lno].len;1735try= backwards;1736 try_lno = backwards_lno;1737}else{1738if(forwards_lno == img->nr) {1739 i++;1740goto again;1741}1742 forwards += img->line[forwards_lno].len;1743 forwards_lno++;1744try= forwards;1745 try_lno = forwards_lno;1746}17471748}1749return-1;1750}17511752static voidremove_first_line(struct image *img)1753{1754 img->buf += img->line[0].len;1755 img->len -= img->line[0].len;1756 img->line++;1757 img->nr--;1758}17591760static voidremove_last_line(struct image *img)1761{1762 img->len -= img->line[--img->nr].len;1763}17641765static voidupdate_image(struct image *img,1766int applied_pos,1767struct image *preimage,1768struct image *postimage)1769{1770/*1771 * remove the copy of preimage at offset in img1772 * and replace it with postimage1773 */1774int i, nr;1775size_t remove_count, insert_count, applied_at =0;1776char*result;17771778for(i =0; i < applied_pos; i++)1779 applied_at += img->line[i].len;17801781 remove_count =0;1782for(i =0; i < preimage->nr; i++)1783 remove_count += img->line[applied_pos + i].len;1784 insert_count = postimage->len;17851786/* Adjust the contents */1787 result =xmalloc(img->len + insert_count - remove_count +1);1788memcpy(result, img->buf, applied_at);1789memcpy(result + applied_at, postimage->buf, postimage->len);1790memcpy(result + applied_at + postimage->len,1791 img->buf + (applied_at + remove_count),1792 img->len - (applied_at + remove_count));1793free(img->buf);1794 img->buf = result;1795 img->len += insert_count - remove_count;1796 result[img->len] ='\0';17971798/* Adjust the line table */1799 nr = img->nr + postimage->nr - preimage->nr;1800if(preimage->nr < postimage->nr) {1801/*1802 * NOTE: this knows that we never call remove_first_line()1803 * on anything other than pre/post image.1804 */1805 img->line =xrealloc(img->line, nr *sizeof(*img->line));1806 img->line_allocated = img->line;1807}1808if(preimage->nr != postimage->nr)1809memmove(img->line + applied_pos + postimage->nr,1810 img->line + applied_pos + preimage->nr,1811(img->nr - (applied_pos + preimage->nr)) *1812sizeof(*img->line));1813memcpy(img->line + applied_pos,1814 postimage->line,1815 postimage->nr *sizeof(*img->line));1816 img->nr = nr;1817}18181819static intapply_one_fragment(struct image *img,struct fragment *frag,1820int inaccurate_eof,unsigned ws_rule)1821{1822int match_beginning, match_end;1823const char*patch = frag->patch;1824int size = frag->size;1825char*old, *new, *oldlines, *newlines;1826int new_blank_lines_at_end =0;1827unsigned long leading, trailing;1828int pos, applied_pos;1829struct image preimage;1830struct image postimage;18311832memset(&preimage,0,sizeof(preimage));1833memset(&postimage,0,sizeof(postimage));1834 oldlines =xmalloc(size);1835 newlines =xmalloc(size);18361837 old = oldlines;1838new= newlines;1839while(size >0) {1840char first;1841int len =linelen(patch, size);1842int plen, added;1843int added_blank_line =0;18441845if(!len)1846break;18471848/*1849 * "plen" is how much of the line we should use for1850 * the actual patch data. Normally we just remove the1851 * first character on the line, but if the line is1852 * followed by "\ No newline", then we also remove the1853 * last one (which is the newline, of course).1854 */1855 plen = len -1;1856if(len < size && patch[len] =='\\')1857 plen--;1858 first = *patch;1859if(apply_in_reverse) {1860if(first =='-')1861 first ='+';1862else if(first =='+')1863 first ='-';1864}18651866switch(first) {1867case'\n':1868/* Newer GNU diff, empty context line */1869if(plen <0)1870/* ... followed by '\No newline'; nothing */1871break;1872*old++ ='\n';1873*new++ ='\n';1874add_line_info(&preimage,"\n",1, LINE_COMMON);1875add_line_info(&postimage,"\n",1, LINE_COMMON);1876break;1877case' ':1878case'-':1879memcpy(old, patch +1, plen);1880add_line_info(&preimage, old, plen,1881(first ==' '? LINE_COMMON :0));1882 old += plen;1883if(first =='-')1884break;1885/* Fall-through for ' ' */1886case'+':1887/* --no-add does not add new lines */1888if(first =='+'&& no_add)1889break;18901891if(first !='+'||1892!whitespace_error ||1893 ws_error_action != correct_ws_error) {1894memcpy(new, patch +1, plen);1895 added = plen;1896}1897else{1898 added =ws_fix_copy(new, patch +1, plen, ws_rule, &applied_after_fixing_ws);1899}1900add_line_info(&postimage,new, added,1901(first =='+'?0: LINE_COMMON));1902new+= added;1903if(first =='+'&&1904 added ==1&&new[-1] =='\n')1905 added_blank_line =1;1906break;1907case'@':case'\\':1908/* Ignore it, we already handled it */1909break;1910default:1911if(apply_verbosely)1912error("invalid start of line: '%c'", first);1913return-1;1914}1915if(added_blank_line)1916 new_blank_lines_at_end++;1917else1918 new_blank_lines_at_end =0;1919 patch += len;1920 size -= len;1921}1922if(inaccurate_eof &&1923 old > oldlines && old[-1] =='\n'&&1924new> newlines &&new[-1] =='\n') {1925 old--;1926new--;1927}19281929 leading = frag->leading;1930 trailing = frag->trailing;19311932/*1933 * A hunk to change lines at the beginning would begin with1934 * @@ -1,L +N,M @@1935 *1936 * And a hunk to add to an empty file would begin with1937 * @@ -0,0 +N,M @@1938 *1939 * In other words, a hunk that is (frag->oldpos <= 1) with or1940 * without leading context must match at the beginning.1941 */1942 match_beginning = frag->oldpos <=1;19431944/*1945 * A hunk without trailing lines must match at the end.1946 * However, we simply cannot tell if a hunk must match end1947 * from the lack of trailing lines if the patch was generated1948 * with unidiff without any context.1949 */1950 match_end = !unidiff_zero && !trailing;19511952 pos = frag->newpos ? (frag->newpos -1) :0;1953 preimage.buf = oldlines;1954 preimage.len = old - oldlines;1955 postimage.buf = newlines;1956 postimage.len =new- newlines;1957 preimage.line = preimage.line_allocated;1958 postimage.line = postimage.line_allocated;19591960for(;;) {19611962 applied_pos =find_pos(img, &preimage, &postimage, pos,1963 ws_rule, match_beginning, match_end);19641965if(applied_pos >=0)1966break;19671968/* Am I at my context limits? */1969if((leading <= p_context) && (trailing <= p_context))1970break;1971if(match_beginning || match_end) {1972 match_beginning = match_end =0;1973continue;1974}19751976/*1977 * Reduce the number of context lines; reduce both1978 * leading and trailing if they are equal otherwise1979 * just reduce the larger context.1980 */1981if(leading >= trailing) {1982remove_first_line(&preimage);1983remove_first_line(&postimage);1984 pos--;1985 leading--;1986}1987if(trailing > leading) {1988remove_last_line(&preimage);1989remove_last_line(&postimage);1990 trailing--;1991}1992}19931994if(applied_pos >=0) {1995if(ws_error_action == correct_ws_error &&1996 new_blank_lines_at_end &&1997 postimage.nr + applied_pos == img->nr) {1998/*1999 * If the patch application adds blank lines2000 * at the end, and if the patch applies at the2001 * end of the image, remove those added blank2002 * lines.2003 */2004while(new_blank_lines_at_end--)2005remove_last_line(&postimage);2006}20072008/*2009 * Warn if it was necessary to reduce the number2010 * of context lines.2011 */2012if((leading != frag->leading) ||2013(trailing != frag->trailing))2014fprintf(stderr,"Context reduced to (%ld/%ld)"2015" to apply fragment at%d\n",2016 leading, trailing, applied_pos+1);2017update_image(img, applied_pos, &preimage, &postimage);2018}else{2019if(apply_verbosely)2020error("while searching for:\n%.*s",2021(int)(old - oldlines), oldlines);2022}20232024free(oldlines);2025free(newlines);2026free(preimage.line_allocated);2027free(postimage.line_allocated);20282029return(applied_pos <0);2030}20312032static intapply_binary_fragment(struct image *img,struct patch *patch)2033{2034struct fragment *fragment = patch->fragments;2035unsigned long len;2036void*dst;20372038/* Binary patch is irreversible without the optional second hunk */2039if(apply_in_reverse) {2040if(!fragment->next)2041returnerror("cannot reverse-apply a binary patch "2042"without the reverse hunk to '%s'",2043 patch->new_name2044? patch->new_name : patch->old_name);2045 fragment = fragment->next;2046}2047switch(fragment->binary_patch_method) {2048case BINARY_DELTA_DEFLATED:2049 dst =patch_delta(img->buf, img->len, fragment->patch,2050 fragment->size, &len);2051if(!dst)2052return-1;2053clear_image(img);2054 img->buf = dst;2055 img->len = len;2056return0;2057case BINARY_LITERAL_DEFLATED:2058clear_image(img);2059 img->len = fragment->size;2060 img->buf =xmalloc(img->len+1);2061memcpy(img->buf, fragment->patch, img->len);2062 img->buf[img->len] ='\0';2063return0;2064}2065return-1;2066}20672068static intapply_binary(struct image *img,struct patch *patch)2069{2070const char*name = patch->old_name ? patch->old_name : patch->new_name;2071unsigned char sha1[20];20722073/*2074 * For safety, we require patch index line to contain2075 * full 40-byte textual SHA1 for old and new, at least for now.2076 */2077if(strlen(patch->old_sha1_prefix) !=40||2078strlen(patch->new_sha1_prefix) !=40||2079get_sha1_hex(patch->old_sha1_prefix, sha1) ||2080get_sha1_hex(patch->new_sha1_prefix, sha1))2081returnerror("cannot apply binary patch to '%s' "2082"without full index line", name);20832084if(patch->old_name) {2085/*2086 * See if the old one matches what the patch2087 * applies to.2088 */2089hash_sha1_file(img->buf, img->len, blob_type, sha1);2090if(strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))2091returnerror("the patch applies to '%s' (%s), "2092"which does not match the "2093"current contents.",2094 name,sha1_to_hex(sha1));2095}2096else{2097/* Otherwise, the old one must be empty. */2098if(img->len)2099returnerror("the patch applies to an empty "2100"'%s' but it is not empty", name);2101}21022103get_sha1_hex(patch->new_sha1_prefix, sha1);2104if(is_null_sha1(sha1)) {2105clear_image(img);2106return0;/* deletion patch */2107}21082109if(has_sha1_file(sha1)) {2110/* We already have the postimage */2111enum object_type type;2112unsigned long size;2113char*result;21142115 result =read_sha1_file(sha1, &type, &size);2116if(!result)2117returnerror("the necessary postimage%sfor "2118"'%s' cannot be read",2119 patch->new_sha1_prefix, name);2120clear_image(img);2121 img->buf = result;2122 img->len = size;2123}else{2124/*2125 * We have verified buf matches the preimage;2126 * apply the patch data to it, which is stored2127 * in the patch->fragments->{patch,size}.2128 */2129if(apply_binary_fragment(img, patch))2130returnerror("binary patch does not apply to '%s'",2131 name);21322133/* verify that the result matches */2134hash_sha1_file(img->buf, img->len, blob_type, sha1);2135if(strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))2136returnerror("binary patch to '%s' creates incorrect result (expecting%s, got%s)",2137 name, patch->new_sha1_prefix,sha1_to_hex(sha1));2138}21392140return0;2141}21422143static intapply_fragments(struct image *img,struct patch *patch)2144{2145struct fragment *frag = patch->fragments;2146const char*name = patch->old_name ? patch->old_name : patch->new_name;2147unsigned ws_rule = patch->ws_rule;2148unsigned inaccurate_eof = patch->inaccurate_eof;21492150if(patch->is_binary)2151returnapply_binary(img, patch);21522153while(frag) {2154if(apply_one_fragment(img, frag, inaccurate_eof, ws_rule)) {2155error("patch failed:%s:%ld", name, frag->oldpos);2156if(!apply_with_reject)2157return-1;2158 frag->rejected =1;2159}2160 frag = frag->next;2161}2162return0;2163}21642165static intread_file_or_gitlink(struct cache_entry *ce,struct strbuf *buf)2166{2167if(!ce)2168return0;21692170if(S_ISGITLINK(ce->ce_mode)) {2171strbuf_grow(buf,100);2172strbuf_addf(buf,"Subproject commit%s\n",sha1_to_hex(ce->sha1));2173}else{2174enum object_type type;2175unsigned long sz;2176char*result;21772178 result =read_sha1_file(ce->sha1, &type, &sz);2179if(!result)2180return-1;2181/* XXX read_sha1_file NUL-terminates */2182strbuf_attach(buf, result, sz, sz +1);2183}2184return0;2185}21862187static struct patch *in_fn_table(const char*name)2188{2189struct path_list_item *item;21902191if(name == NULL)2192return NULL;21932194 item =path_list_lookup(name, &fn_table);2195if(item != NULL)2196return(struct patch *)item->util;21972198return NULL;2199}22002201static voidadd_to_fn_table(struct patch *patch)2202{2203struct path_list_item *item;22042205/*2206 * Always add new_name unless patch is a deletion2207 * This should cover the cases for normal diffs,2208 * file creations and copies2209 */2210if(patch->new_name != NULL) {2211 item =path_list_insert(patch->new_name, &fn_table);2212 item->util = patch;2213}22142215/*2216 * store a failure on rename/deletion cases because2217 * later chunks shouldn't patch old names2218 */2219if((patch->new_name == NULL) || (patch->is_rename)) {2220 item =path_list_insert(patch->old_name, &fn_table);2221 item->util = (struct patch *) -1;2222}2223}22242225static intapply_data(struct patch *patch,struct stat *st,struct cache_entry *ce)2226{2227struct strbuf buf;2228struct image image;2229size_t len;2230char*img;2231struct patch *tpatch;22322233strbuf_init(&buf,0);22342235if((tpatch =in_fn_table(patch->old_name)) != NULL) {2236if(tpatch == (struct patch *) -1) {2237returnerror("patch%shas been renamed/deleted",2238 patch->old_name);2239}2240/* We have a patched copy in memory use that */2241strbuf_add(&buf, tpatch->result, tpatch->resultsize);2242}else if(cached) {2243if(read_file_or_gitlink(ce, &buf))2244returnerror("read of%sfailed", patch->old_name);2245}else if(patch->old_name) {2246if(S_ISGITLINK(patch->old_mode)) {2247if(ce) {2248read_file_or_gitlink(ce, &buf);2249}else{2250/*2251 * There is no way to apply subproject2252 * patch without looking at the index.2253 */2254 patch->fragments = NULL;2255}2256}else{2257if(read_old_data(st, patch->old_name, &buf))2258returnerror("read of%sfailed", patch->old_name);2259}2260}22612262 img =strbuf_detach(&buf, &len);2263prepare_image(&image, img, len, !patch->is_binary);22642265if(apply_fragments(&image, patch) <0)2266return-1;/* note with --reject this succeeds. */2267 patch->result = image.buf;2268 patch->resultsize = image.len;2269add_to_fn_table(patch);2270free(image.line_allocated);22712272if(0< patch->is_delete && patch->resultsize)2273returnerror("removal patch leaves file contents");22742275return0;2276}22772278static intcheck_to_create_blob(const char*new_name,int ok_if_exists)2279{2280struct stat nst;2281if(!lstat(new_name, &nst)) {2282if(S_ISDIR(nst.st_mode) || ok_if_exists)2283return0;2284/*2285 * A leading component of new_name might be a symlink2286 * that is going to be removed with this patch, but2287 * still pointing at somewhere that has the path.2288 * In such a case, path "new_name" does not exist as2289 * far as git is concerned.2290 */2291if(has_symlink_leading_path(strlen(new_name), new_name))2292return0;22932294returnerror("%s: already exists in working directory", new_name);2295}2296else if((errno != ENOENT) && (errno != ENOTDIR))2297returnerror("%s:%s", new_name,strerror(errno));2298return0;2299}23002301static intverify_index_match(struct cache_entry *ce,struct stat *st)2302{2303if(S_ISGITLINK(ce->ce_mode)) {2304if(!S_ISDIR(st->st_mode))2305return-1;2306return0;2307}2308returnce_match_stat(ce, st, CE_MATCH_IGNORE_VALID);2309}23102311static intcheck_preimage(struct patch *patch,struct cache_entry **ce,struct stat *st)2312{2313const char*old_name = patch->old_name;2314struct patch *tpatch;2315int stat_ret =0;2316unsigned st_mode =0;23172318/*2319 * Make sure that we do not have local modifications from the2320 * index when we are looking at the index. Also make sure2321 * we have the preimage file to be patched in the work tree,2322 * unless --cached, which tells git to apply only in the index.2323 */2324if(!old_name)2325return0;23262327assert(patch->is_new <=0);2328if((tpatch =in_fn_table(old_name)) != NULL) {2329if(tpatch == (struct patch *) -1) {2330returnerror("%s: has been deleted/renamed", old_name);2331}2332 st_mode = tpatch->new_mode;2333}else if(!cached) {2334 stat_ret =lstat(old_name, st);2335if(stat_ret && errno != ENOENT)2336returnerror("%s:%s", old_name,strerror(errno));2337}2338if(check_index && !tpatch) {2339int pos =cache_name_pos(old_name,strlen(old_name));2340if(pos <0) {2341if(patch->is_new <0)2342goto is_new;2343returnerror("%s: does not exist in index", old_name);2344}2345*ce = active_cache[pos];2346if(stat_ret <0) {2347struct checkout costate;2348/* checkout */2349 costate.base_dir ="";2350 costate.base_dir_len =0;2351 costate.force =0;2352 costate.quiet =0;2353 costate.not_new =0;2354 costate.refresh_cache =1;2355if(checkout_entry(*ce, &costate, NULL) ||2356lstat(old_name, st))2357return-1;2358}2359if(!cached &&verify_index_match(*ce, st))2360returnerror("%s: does not match index", old_name);2361if(cached)2362 st_mode = (*ce)->ce_mode;2363}else if(stat_ret <0) {2364if(patch->is_new <0)2365goto is_new;2366returnerror("%s:%s", old_name,strerror(errno));2367}23682369if(!cached)2370 st_mode =ce_mode_from_stat(*ce, st->st_mode);23712372if(patch->is_new <0)2373 patch->is_new =0;2374if(!patch->old_mode)2375 patch->old_mode = st_mode;2376if((st_mode ^ patch->old_mode) & S_IFMT)2377returnerror("%s: wrong type", old_name);2378if(st_mode != patch->old_mode)2379fprintf(stderr,"warning:%shas type%o, expected%o\n",2380 old_name, st_mode, patch->old_mode);2381return0;23822383 is_new:2384 patch->is_new =1;2385 patch->is_delete =0;2386 patch->old_name = NULL;2387return0;2388}23892390static intcheck_patch(struct patch *patch)2391{2392struct stat st;2393const char*old_name = patch->old_name;2394const char*new_name = patch->new_name;2395const char*name = old_name ? old_name : new_name;2396struct cache_entry *ce = NULL;2397int ok_if_exists;2398int status;23992400 patch->rejected =1;/* we will drop this after we succeed */24012402 status =check_preimage(patch, &ce, &st);2403if(status)2404return status;2405 old_name = patch->old_name;24062407if(in_fn_table(new_name) == (struct patch *) -1)2408/*2409 * A type-change diff is always split into a patch to2410 * delete old, immediately followed by a patch to2411 * create new (see diff.c::run_diff()); in such a case2412 * it is Ok that the entry to be deleted by the2413 * previous patch is still in the working tree and in2414 * the index.2415 */2416 ok_if_exists =1;2417else2418 ok_if_exists =0;24192420if(new_name &&2421((0< patch->is_new) | (0< patch->is_rename) | patch->is_copy)) {2422if(check_index &&2423cache_name_pos(new_name,strlen(new_name)) >=0&&2424!ok_if_exists)2425returnerror("%s: already exists in index", new_name);2426if(!cached) {2427int err =check_to_create_blob(new_name, ok_if_exists);2428if(err)2429return err;2430}2431if(!patch->new_mode) {2432if(0< patch->is_new)2433 patch->new_mode = S_IFREG |0644;2434else2435 patch->new_mode = patch->old_mode;2436}2437}24382439if(new_name && old_name) {2440int same = !strcmp(old_name, new_name);2441if(!patch->new_mode)2442 patch->new_mode = patch->old_mode;2443if((patch->old_mode ^ patch->new_mode) & S_IFMT)2444returnerror("new mode (%o) of%sdoes not match old mode (%o)%s%s",2445 patch->new_mode, new_name, patch->old_mode,2446 same ?"":" of ", same ?"": old_name);2447}24482449if(apply_data(patch, &st, ce) <0)2450returnerror("%s: patch does not apply", name);2451 patch->rejected =0;2452return0;2453}24542455static intcheck_patch_list(struct patch *patch)2456{2457int err =0;24582459while(patch) {2460if(apply_verbosely)2461say_patch_name(stderr,2462"Checking patch ", patch,"...\n");2463 err |=check_patch(patch);2464 patch = patch->next;2465}2466return err;2467}24682469/* This function tries to read the sha1 from the current index */2470static intget_current_sha1(const char*path,unsigned char*sha1)2471{2472int pos;24732474if(read_cache() <0)2475return-1;2476 pos =cache_name_pos(path,strlen(path));2477if(pos <0)2478return-1;2479hashcpy(sha1, active_cache[pos]->sha1);2480return0;2481}24822483/* Build an index that contains the just the files needed for a 3way merge */2484static voidbuild_fake_ancestor(struct patch *list,const char*filename)2485{2486struct patch *patch;2487struct index_state result = {0};2488int fd;24892490/* Once we start supporting the reverse patch, it may be2491 * worth showing the new sha1 prefix, but until then...2492 */2493for(patch = list; patch; patch = patch->next) {2494const unsigned char*sha1_ptr;2495unsigned char sha1[20];2496struct cache_entry *ce;2497const char*name;24982499 name = patch->old_name ? patch->old_name : patch->new_name;2500if(0< patch->is_new)2501continue;2502else if(get_sha1(patch->old_sha1_prefix, sha1))2503/* git diff has no index line for mode/type changes */2504if(!patch->lines_added && !patch->lines_deleted) {2505if(get_current_sha1(patch->new_name, sha1) ||2506get_current_sha1(patch->old_name, sha1))2507die("mode change for%s, which is not "2508"in current HEAD", name);2509 sha1_ptr = sha1;2510}else2511die("sha1 information is lacking or useless "2512"(%s).", name);2513else2514 sha1_ptr = sha1;25152516 ce =make_cache_entry(patch->old_mode, sha1_ptr, name,0,0);2517if(add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))2518die("Could not add%sto temporary index", name);2519}25202521 fd =open(filename, O_WRONLY | O_CREAT,0666);2522if(fd <0||write_index(&result, fd) ||close(fd))2523die("Could not write temporary index to%s", filename);25242525discard_index(&result);2526}25272528static voidstat_patch_list(struct patch *patch)2529{2530int files, adds, dels;25312532for(files = adds = dels =0; patch ; patch = patch->next) {2533 files++;2534 adds += patch->lines_added;2535 dels += patch->lines_deleted;2536show_stats(patch);2537}25382539printf("%dfiles changed,%dinsertions(+),%ddeletions(-)\n", files, adds, dels);2540}25412542static voidnumstat_patch_list(struct patch *patch)2543{2544for( ; patch; patch = patch->next) {2545const char*name;2546 name = patch->new_name ? patch->new_name : patch->old_name;2547if(patch->is_binary)2548printf("-\t-\t");2549else2550printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);2551write_name_quoted(name, stdout, line_termination);2552}2553}25542555static voidshow_file_mode_name(const char*newdelete,unsigned int mode,const char*name)2556{2557if(mode)2558printf("%smode%06o%s\n", newdelete, mode, name);2559else2560printf("%s %s\n", newdelete, name);2561}25622563static voidshow_mode_change(struct patch *p,int show_name)2564{2565if(p->old_mode && p->new_mode && p->old_mode != p->new_mode) {2566if(show_name)2567printf(" mode change%06o =>%06o%s\n",2568 p->old_mode, p->new_mode, p->new_name);2569else2570printf(" mode change%06o =>%06o\n",2571 p->old_mode, p->new_mode);2572}2573}25742575static voidshow_rename_copy(struct patch *p)2576{2577const char*renamecopy = p->is_rename ?"rename":"copy";2578const char*old, *new;25792580/* Find common prefix */2581 old = p->old_name;2582new= p->new_name;2583while(1) {2584const char*slash_old, *slash_new;2585 slash_old =strchr(old,'/');2586 slash_new =strchr(new,'/');2587if(!slash_old ||2588!slash_new ||2589 slash_old - old != slash_new -new||2590memcmp(old,new, slash_new -new))2591break;2592 old = slash_old +1;2593new= slash_new +1;2594}2595/* p->old_name thru old is the common prefix, and old and new2596 * through the end of names are renames2597 */2598if(old != p->old_name)2599printf("%s%.*s{%s=>%s} (%d%%)\n", renamecopy,2600(int)(old - p->old_name), p->old_name,2601 old,new, p->score);2602else2603printf("%s %s=>%s(%d%%)\n", renamecopy,2604 p->old_name, p->new_name, p->score);2605show_mode_change(p,0);2606}26072608static voidsummary_patch_list(struct patch *patch)2609{2610struct patch *p;26112612for(p = patch; p; p = p->next) {2613if(p->is_new)2614show_file_mode_name("create", p->new_mode, p->new_name);2615else if(p->is_delete)2616show_file_mode_name("delete", p->old_mode, p->old_name);2617else{2618if(p->is_rename || p->is_copy)2619show_rename_copy(p);2620else{2621if(p->score) {2622printf(" rewrite%s(%d%%)\n",2623 p->new_name, p->score);2624show_mode_change(p,0);2625}2626else2627show_mode_change(p,1);2628}2629}2630}2631}26322633static voidpatch_stats(struct patch *patch)2634{2635int lines = patch->lines_added + patch->lines_deleted;26362637if(lines > max_change)2638 max_change = lines;2639if(patch->old_name) {2640int len =quote_c_style(patch->old_name, NULL, NULL,0);2641if(!len)2642 len =strlen(patch->old_name);2643if(len > max_len)2644 max_len = len;2645}2646if(patch->new_name) {2647int len =quote_c_style(patch->new_name, NULL, NULL,0);2648if(!len)2649 len =strlen(patch->new_name);2650if(len > max_len)2651 max_len = len;2652}2653}26542655static voidremove_file(struct patch *patch,int rmdir_empty)2656{2657if(update_index) {2658if(remove_file_from_cache(patch->old_name) <0)2659die("unable to remove%sfrom index", patch->old_name);2660}2661if(!cached) {2662if(S_ISGITLINK(patch->old_mode)) {2663if(rmdir(patch->old_name))2664warning("unable to remove submodule%s",2665 patch->old_name);2666}else if(!unlink(patch->old_name) && rmdir_empty) {2667char*name =xstrdup(patch->old_name);2668char*end =strrchr(name,'/');2669while(end) {2670*end =0;2671if(rmdir(name))2672break;2673 end =strrchr(name,'/');2674}2675free(name);2676}2677}2678}26792680static voidadd_index_file(const char*path,unsigned mode,void*buf,unsigned long size)2681{2682struct stat st;2683struct cache_entry *ce;2684int namelen =strlen(path);2685unsigned ce_size =cache_entry_size(namelen);26862687if(!update_index)2688return;26892690 ce =xcalloc(1, ce_size);2691memcpy(ce->name, path, namelen);2692 ce->ce_mode =create_ce_mode(mode);2693 ce->ce_flags = namelen;2694if(S_ISGITLINK(mode)) {2695const char*s = buf;26962697if(get_sha1_hex(s +strlen("Subproject commit "), ce->sha1))2698die("corrupt patch for subproject%s", path);2699}else{2700if(!cached) {2701if(lstat(path, &st) <0)2702die("unable to stat newly created file%s",2703 path);2704fill_stat_cache_info(ce, &st);2705}2706if(write_sha1_file(buf, size, blob_type, ce->sha1) <0)2707die("unable to create backing store for newly created file%s", path);2708}2709if(add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) <0)2710die("unable to add cache entry for%s", path);2711}27122713static inttry_create_file(const char*path,unsigned int mode,const char*buf,unsigned long size)2714{2715int fd;2716struct strbuf nbuf;27172718if(S_ISGITLINK(mode)) {2719struct stat st;2720if(!lstat(path, &st) &&S_ISDIR(st.st_mode))2721return0;2722returnmkdir(path,0777);2723}27242725if(has_symlinks &&S_ISLNK(mode))2726/* Although buf:size is counted string, it also is NUL2727 * terminated.2728 */2729returnsymlink(buf, path);27302731 fd =open(path, O_CREAT | O_EXCL | O_WRONLY, (mode &0100) ?0777:0666);2732if(fd <0)2733return-1;27342735strbuf_init(&nbuf,0);2736if(convert_to_working_tree(path, buf, size, &nbuf)) {2737 size = nbuf.len;2738 buf = nbuf.buf;2739}2740write_or_die(fd, buf, size);2741strbuf_release(&nbuf);27422743if(close(fd) <0)2744die("closing file%s:%s", path,strerror(errno));2745return0;2746}27472748/*2749 * We optimistically assume that the directories exist,2750 * which is true 99% of the time anyway. If they don't,2751 * we create them and try again.2752 */2753static voidcreate_one_file(char*path,unsigned mode,const char*buf,unsigned long size)2754{2755if(cached)2756return;2757if(!try_create_file(path, mode, buf, size))2758return;27592760if(errno == ENOENT) {2761if(safe_create_leading_directories(path))2762return;2763if(!try_create_file(path, mode, buf, size))2764return;2765}27662767if(errno == EEXIST || errno == EACCES) {2768/* We may be trying to create a file where a directory2769 * used to be.2770 */2771struct stat st;2772if(!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))2773 errno = EEXIST;2774}27752776if(errno == EEXIST) {2777unsigned int nr =getpid();27782779for(;;) {2780const char*newpath;2781 newpath =mkpath("%s~%u", path, nr);2782if(!try_create_file(newpath, mode, buf, size)) {2783if(!rename(newpath, path))2784return;2785unlink(newpath);2786break;2787}2788if(errno != EEXIST)2789break;2790++nr;2791}2792}2793die("unable to write file%smode%o", path, mode);2794}27952796static voidcreate_file(struct patch *patch)2797{2798char*path = patch->new_name;2799unsigned mode = patch->new_mode;2800unsigned long size = patch->resultsize;2801char*buf = patch->result;28022803if(!mode)2804 mode = S_IFREG |0644;2805create_one_file(path, mode, buf, size);2806add_index_file(path, mode, buf, size);2807}28082809/* phase zero is to remove, phase one is to create */2810static voidwrite_out_one_result(struct patch *patch,int phase)2811{2812if(patch->is_delete >0) {2813if(phase ==0)2814remove_file(patch,1);2815return;2816}2817if(patch->is_new >0|| patch->is_copy) {2818if(phase ==1)2819create_file(patch);2820return;2821}2822/*2823 * Rename or modification boils down to the same2824 * thing: remove the old, write the new2825 */2826if(phase ==0)2827remove_file(patch, patch->is_rename);2828if(phase ==1)2829create_file(patch);2830}28312832static intwrite_out_one_reject(struct patch *patch)2833{2834FILE*rej;2835char namebuf[PATH_MAX];2836struct fragment *frag;2837int cnt =0;28382839for(cnt =0, frag = patch->fragments; frag; frag = frag->next) {2840if(!frag->rejected)2841continue;2842 cnt++;2843}28442845if(!cnt) {2846if(apply_verbosely)2847say_patch_name(stderr,2848"Applied patch ", patch," cleanly.\n");2849return0;2850}28512852/* This should not happen, because a removal patch that leaves2853 * contents are marked "rejected" at the patch level.2854 */2855if(!patch->new_name)2856die("internal error");28572858/* Say this even without --verbose */2859say_patch_name(stderr,"Applying patch ", patch," with");2860fprintf(stderr,"%drejects...\n", cnt);28612862 cnt =strlen(patch->new_name);2863if(ARRAY_SIZE(namebuf) <= cnt +5) {2864 cnt =ARRAY_SIZE(namebuf) -5;2865fprintf(stderr,2866"warning: truncating .rej filename to %.*s.rej",2867 cnt -1, patch->new_name);2868}2869memcpy(namebuf, patch->new_name, cnt);2870memcpy(namebuf + cnt,".rej",5);28712872 rej =fopen(namebuf,"w");2873if(!rej)2874returnerror("cannot open%s:%s", namebuf,strerror(errno));28752876/* Normal git tools never deal with .rej, so do not pretend2877 * this is a git patch by saying --git nor give extended2878 * headers. While at it, maybe please "kompare" that wants2879 * the trailing TAB and some garbage at the end of line ;-).2880 */2881fprintf(rej,"diff a/%sb/%s\t(rejected hunks)\n",2882 patch->new_name, patch->new_name);2883for(cnt =1, frag = patch->fragments;2884 frag;2885 cnt++, frag = frag->next) {2886if(!frag->rejected) {2887fprintf(stderr,"Hunk #%dapplied cleanly.\n", cnt);2888continue;2889}2890fprintf(stderr,"Rejected hunk #%d.\n", cnt);2891fprintf(rej,"%.*s", frag->size, frag->patch);2892if(frag->patch[frag->size-1] !='\n')2893fputc('\n', rej);2894}2895fclose(rej);2896return-1;2897}28982899static intwrite_out_results(struct patch *list,int skipped_patch)2900{2901int phase;2902int errs =0;2903struct patch *l;29042905if(!list && !skipped_patch)2906returnerror("No changes");29072908for(phase =0; phase <2; phase++) {2909 l = list;2910while(l) {2911if(l->rejected)2912 errs =1;2913else{2914write_out_one_result(l, phase);2915if(phase ==1&&write_out_one_reject(l))2916 errs =1;2917}2918 l = l->next;2919}2920}2921return errs;2922}29232924static struct lock_file lock_file;29252926static struct excludes {2927struct excludes *next;2928const char*path;2929} *excludes;29302931static intuse_patch(struct patch *p)2932{2933const char*pathname = p->new_name ? p->new_name : p->old_name;2934struct excludes *x = excludes;2935while(x) {2936if(fnmatch(x->path, pathname,0) ==0)2937return0;2938 x = x->next;2939}2940if(0< prefix_length) {2941int pathlen =strlen(pathname);2942if(pathlen <= prefix_length ||2943memcmp(prefix, pathname, prefix_length))2944return0;2945}2946return1;2947}29482949static voidprefix_one(char**name)2950{2951char*old_name = *name;2952if(!old_name)2953return;2954*name =xstrdup(prefix_filename(prefix, prefix_length, *name));2955free(old_name);2956}29572958static voidprefix_patches(struct patch *p)2959{2960if(!prefix || p->is_toplevel_relative)2961return;2962for( ; p; p = p->next) {2963if(p->new_name == p->old_name) {2964char*prefixed = p->new_name;2965prefix_one(&prefixed);2966 p->new_name = p->old_name = prefixed;2967}2968else{2969prefix_one(&p->new_name);2970prefix_one(&p->old_name);2971}2972}2973}29742975static intapply_patch(int fd,const char*filename,int inaccurate_eof)2976{2977size_t offset;2978struct strbuf buf;2979struct patch *list = NULL, **listp = &list;2980int skipped_patch =0;29812982/* FIXME - memory leak when using multiple patch files as inputs */2983memset(&fn_table,0,sizeof(struct path_list));2984strbuf_init(&buf,0);2985 patch_input_file = filename;2986read_patch_file(&buf, fd);2987 offset =0;2988while(offset < buf.len) {2989struct patch *patch;2990int nr;29912992 patch =xcalloc(1,sizeof(*patch));2993 patch->inaccurate_eof = inaccurate_eof;2994 nr =parse_chunk(buf.buf + offset, buf.len - offset, patch);2995if(nr <0)2996break;2997if(apply_in_reverse)2998reverse_patches(patch);2999if(prefix)3000prefix_patches(patch);3001if(use_patch(patch)) {3002patch_stats(patch);3003*listp = patch;3004 listp = &patch->next;3005}3006else{3007/* perhaps free it a bit better? */3008free(patch);3009 skipped_patch++;3010}3011 offset += nr;3012}30133014if(whitespace_error && (ws_error_action == die_on_ws_error))3015 apply =0;30163017 update_index = check_index && apply;3018if(update_index && newfd <0)3019 newfd =hold_locked_index(&lock_file,1);30203021if(check_index) {3022if(read_cache() <0)3023die("unable to read index file");3024}30253026if((check || apply) &&3027check_patch_list(list) <0&&3028!apply_with_reject)3029exit(1);30303031if(apply &&write_out_results(list, skipped_patch))3032exit(1);30333034if(fake_ancestor)3035build_fake_ancestor(list, fake_ancestor);30363037if(diffstat)3038stat_patch_list(list);30393040if(numstat)3041numstat_patch_list(list);30423043if(summary)3044summary_patch_list(list);30453046strbuf_release(&buf);3047return0;3048}30493050static intgit_apply_config(const char*var,const char*value,void*cb)3051{3052if(!strcmp(var,"apply.whitespace"))3053returngit_config_string(&apply_default_whitespace, var, value);3054returngit_default_config(var, value, cb);3055}305630573058intcmd_apply(int argc,const char**argv,const char*unused_prefix)3059{3060int i;3061int read_stdin =1;3062int inaccurate_eof =0;3063int errs =0;3064int is_not_gitdir;30653066const char*whitespace_option = NULL;30673068 prefix =setup_git_directory_gently(&is_not_gitdir);3069 prefix_length = prefix ?strlen(prefix) :0;3070git_config(git_apply_config, NULL);3071if(apply_default_whitespace)3072parse_whitespace_option(apply_default_whitespace);30733074for(i =1; i < argc; i++) {3075const char*arg = argv[i];3076char*end;3077int fd;30783079if(!strcmp(arg,"-")) {3080 errs |=apply_patch(0,"<stdin>", inaccurate_eof);3081 read_stdin =0;3082continue;3083}3084if(!prefixcmp(arg,"--exclude=")) {3085struct excludes *x =xmalloc(sizeof(*x));3086 x->path = arg +10;3087 x->next = excludes;3088 excludes = x;3089continue;3090}3091if(!prefixcmp(arg,"-p")) {3092 p_value =atoi(arg +2);3093 p_value_known =1;3094continue;3095}3096if(!strcmp(arg,"--no-add")) {3097 no_add =1;3098continue;3099}3100if(!strcmp(arg,"--stat")) {3101 apply =0;3102 diffstat =1;3103continue;3104}3105if(!strcmp(arg,"--allow-binary-replacement") ||3106!strcmp(arg,"--binary")) {3107continue;/* now no-op */3108}3109if(!strcmp(arg,"--numstat")) {3110 apply =0;3111 numstat =1;3112continue;3113}3114if(!strcmp(arg,"--summary")) {3115 apply =0;3116 summary =1;3117continue;3118}3119if(!strcmp(arg,"--check")) {3120 apply =0;3121 check =1;3122continue;3123}3124if(!strcmp(arg,"--index")) {3125if(is_not_gitdir)3126die("--index outside a repository");3127 check_index =1;3128continue;3129}3130if(!strcmp(arg,"--cached")) {3131if(is_not_gitdir)3132die("--cached outside a repository");3133 check_index =1;3134 cached =1;3135continue;3136}3137if(!strcmp(arg,"--apply")) {3138 apply =1;3139continue;3140}3141if(!strcmp(arg,"--build-fake-ancestor")) {3142 apply =0;3143if(++i >= argc)3144die("need a filename");3145 fake_ancestor = argv[i];3146continue;3147}3148if(!strcmp(arg,"-z")) {3149 line_termination =0;3150continue;3151}3152if(!prefixcmp(arg,"-C")) {3153 p_context =strtoul(arg +2, &end,0);3154if(*end !='\0')3155die("unrecognized context count '%s'", arg +2);3156continue;3157}3158if(!prefixcmp(arg,"--whitespace=")) {3159 whitespace_option = arg +13;3160parse_whitespace_option(arg +13);3161continue;3162}3163if(!strcmp(arg,"-R") || !strcmp(arg,"--reverse")) {3164 apply_in_reverse =1;3165continue;3166}3167if(!strcmp(arg,"--unidiff-zero")) {3168 unidiff_zero =1;3169continue;3170}3171if(!strcmp(arg,"--reject")) {3172 apply = apply_with_reject = apply_verbosely =1;3173continue;3174}3175if(!strcmp(arg,"-v") || !strcmp(arg,"--verbose")) {3176 apply_verbosely =1;3177continue;3178}3179if(!strcmp(arg,"--inaccurate-eof")) {3180 inaccurate_eof =1;3181continue;3182}3183if(0< prefix_length)3184 arg =prefix_filename(prefix, prefix_length, arg);31853186 fd =open(arg, O_RDONLY);3187if(fd <0)3188die("can't open patch '%s':%s", arg,strerror(errno));3189 read_stdin =0;3190set_default_whitespace_mode(whitespace_option);3191 errs |=apply_patch(fd, arg, inaccurate_eof);3192close(fd);3193}3194set_default_whitespace_mode(whitespace_option);3195if(read_stdin)3196 errs |=apply_patch(0,"<stdin>", inaccurate_eof);3197if(whitespace_error) {3198if(squelch_whitespace_errors &&3199 squelch_whitespace_errors < whitespace_error) {3200int squelched =3201 whitespace_error - squelch_whitespace_errors;3202fprintf(stderr,"warning: squelched%d"3203"whitespace error%s\n",3204 squelched,3205 squelched ==1?"":"s");3206}3207if(ws_error_action == die_on_ws_error)3208die("%dline%sadd%swhitespace errors.",3209 whitespace_error,3210 whitespace_error ==1?"":"s",3211 whitespace_error ==1?"s":"");3212if(applied_after_fixing_ws && apply)3213fprintf(stderr,"warning:%dline%sapplied after"3214" fixing whitespace errors.\n",3215 applied_after_fixing_ws,3216 applied_after_fixing_ws ==1?"":"s");3217else if(whitespace_error)3218fprintf(stderr,"warning:%dline%sadd%swhitespace errors.\n",3219 whitespace_error,3220 whitespace_error ==1?"":"s",3221 whitespace_error ==1?"s":"");3222}32233224if(update_index) {3225if(write_cache(newfd, active_cache, active_nr) ||3226commit_locked_index(&lock_file))3227die("Unable to write new index file");3228}32293230return!!errs;3231}